code
stringlengths 38
801k
| repo_path
stringlengths 6
263
|
---|---|
const builtin = @import("builtin");
const TypeInfo = builtin.TypeInfo;
const std = @import("std");
const testing = std.testing;
fn testTypes(comptime types: []const type) void {
inline for (types) |testType| {
testing.expect(testType == @Type(@typeInfo(testType)));
}
}
test "Type.MetaType" {
testing.expect(type == @Type(TypeInfo{ .Type = undefined }));
testTypes(&[_]type{type});
}
test "Type.Void" {
testing.expect(void == @Type(TypeInfo{ .Void = undefined }));
testTypes(&[_]type{void});
}
test "Type.Bool" {
testing.expect(bool == @Type(TypeInfo{ .Bool = undefined }));
testTypes(&[_]type{bool});
}
test "Type.NoReturn" {
testing.expect(noreturn == @Type(TypeInfo{ .NoReturn = undefined }));
testTypes(&[_]type{noreturn});
}
test "Type.Int" {
testing.expect(u1 == @Type(TypeInfo{ .Int = TypeInfo.Int{ .is_signed = false, .bits = 1 } }));
testing.expect(i1 == @Type(TypeInfo{ .Int = TypeInfo.Int{ .is_signed = true, .bits = 1 } }));
testing.expect(u8 == @Type(TypeInfo{ .Int = TypeInfo.Int{ .is_signed = false, .bits = 8 } }));
testing.expect(i8 == @Type(TypeInfo{ .Int = TypeInfo.Int{ .is_signed = true, .bits = 8 } }));
testing.expect(u64 == @Type(TypeInfo{ .Int = TypeInfo.Int{ .is_signed = false, .bits = 64 } }));
testing.expect(i64 == @Type(TypeInfo{ .Int = TypeInfo.Int{ .is_signed = true, .bits = 64 } }));
testTypes(&[_]type{ u8, u32, i64 });
}
test "Type.Float" {
testing.expect(f16 == @Type(TypeInfo{ .Float = TypeInfo.Float{ .bits = 16 } }));
testing.expect(f32 == @Type(TypeInfo{ .Float = TypeInfo.Float{ .bits = 32 } }));
testing.expect(f64 == @Type(TypeInfo{ .Float = TypeInfo.Float{ .bits = 64 } }));
testing.expect(f128 == @Type(TypeInfo{ .Float = TypeInfo.Float{ .bits = 128 } }));
testTypes(&[_]type{ f16, f32, f64, f128 });
}
test "Type.Pointer" {
testTypes(&[_]type{
// One Value Pointer Types
*u8, *const u8,
*volatile u8, *const volatile u8,
*align(4) u8, *align(4) const u8,
*align(4) volatile u8, *align(4) const volatile u8,
*align(8) u8, *align(8) const u8,
*align(8) volatile u8, *align(8) const volatile u8,
*allowzero u8, *allowzero const u8,
*allowzero volatile u8, *allowzero const volatile u8,
*allowzero align(4) u8, *allowzero align(4) const u8,
*allowzero align(4) volatile u8, *allowzero align(4) const volatile u8,
// Many Values Pointer Types
[*]u8, [*]const u8,
[*]volatile u8, [*]const volatile u8,
[*]align(4) u8, [*]align(4) const u8,
[*]align(4) volatile u8, [*]align(4) const volatile u8,
[*]align(8) u8, [*]align(8) const u8,
[*]align(8) volatile u8, [*]align(8) const volatile u8,
[*]allowzero u8, [*]allowzero const u8,
[*]allowzero volatile u8, [*]allowzero const volatile u8,
[*]allowzero align(4) u8, [*]allowzero align(4) const u8,
[*]allowzero align(4) volatile u8, [*]allowzero align(4) const volatile u8,
// Slice Types
[]u8, []const u8,
[]volatile u8, []const volatile u8,
[]align(4) u8, []align(4) const u8,
[]align(4) volatile u8, []align(4) const volatile u8,
[]align(8) u8, []align(8) const u8,
[]align(8) volatile u8, []align(8) const volatile u8,
[]allowzero u8, []allowzero const u8,
[]allowzero volatile u8, []allowzero const volatile u8,
[]allowzero align(4) u8, []allowzero align(4) const u8,
[]allowzero align(4) volatile u8, []allowzero align(4) const volatile u8,
// C Pointer Types
[*c]u8, [*c]const u8,
[*c]volatile u8, [*c]const volatile u8,
[*c]align(4) u8, [*c]align(4) const u8,
[*c]align(4) volatile u8, [*c]align(4) const volatile u8,
[*c]align(8) u8, [*c]align(8) const u8,
[*c]align(8) volatile u8, [*c]align(8) const volatile u8,
});
}
test "Type.Array" {
testing.expect([123]u8 == @Type(TypeInfo{
.Array = TypeInfo.Array{
.len = 123,
.child = u8,
.sentinel = null,
},
}));
testing.expect([2]u32 == @Type(TypeInfo{
.Array = TypeInfo.Array{
.len = 2,
.child = u32,
.sentinel = null,
},
}));
testing.expect([2:0]u32 == @Type(TypeInfo{
.Array = TypeInfo.Array{
.len = 2,
.child = u32,
.sentinel = 0,
},
}));
testTypes(&[_]type{ [1]u8, [30]usize, [7]bool });
}
test "Type.ComptimeFloat" {
testTypes(&[_]type{comptime_float});
}
test "Type.ComptimeInt" {
testTypes(&[_]type{comptime_int});
}
test "Type.Undefined" {
testTypes(&[_]type{@typeOf(undefined)});
}
test "Type.Null" {
testTypes(&[_]type{@typeOf(null)});
} | test/stage1/behavior/type.zig |
const kernel = @import("../../kernel.zig");
const TODO = kernel.TODO;
// TODO: make possible to instantiate more than one same-class virtio driver
const page_size = kernel.arch.page_size;
// **** VIRTIO DRIVER CONFORMANCE ****
// A driver MUST conform to three conformance clauses:
// - Clause 7.2 [ ]
// - One of clauses:
// - 7.2.1 [ ]
// - 7.2.2 [ ]
// - 7.2.3 [ ]
//
// - One of clauses:
// - 7.2.4 [ ]
// - 7.2.5 [ ]
// - 7.2.6 [ ]
// - 7.2.7 [ ]
// - 7.2.8 [ ]
// - 7.2.9 [ ]
// - 7.2.12 [ ]
//
// CLAUSE 7.2
// A driver must conform to the following normative statements:
// - 2.1.1 [x] We panic on failure
// - 2.2.1 [x] We go with the features the virtio driver produces
// - 2.4.1 [ ] ???
// - 2.6.1 [x]
// - 2.6.4.2 [ ] ???
// - 2.6.5.2 [ ] ???
// - 2.6.5.3.1 [ ]
// - 2.6.7.1 [ ]
// - 2.6.6.1 [ ]
// - 2.6.8.3 [ ]
// - 2.6.10.1 [ ]
// - 2.6.13.3.1 [ ]
// - 2.6.13.4.1 [ ]
// - 3.1.1 [ ]
// - 3.3.1 [ ]
// - 6.1 [ ]
const ring_size = 128;
pub const Block = @import("virtio_block.zig");
pub const GPU = @import("virtio_gpu.zig");
pub const MMIO = struct {
magic_value: u32,
version: u32,
device_id: u32,
vendor_id: u32,
device_features: u32,
device_feature_selector: u32,
reserved1: [8]u8,
driver_features: u32,
driver_feature_selector: u32,
reserved2: [8]u8,
queue_selector: u32,
queue_num_max: u32,
queue_num: u32,
reserved3: [4]u8,
reserved4: [4]u8,
queue_ready: u32,
reserved5: [8]u8,
queue_notify: u32,
reserved6: [12]u8,
interrupt_status: InterruptStatus,
interrupt_ack: u32,
reserved7: [8]u8,
device_status: DeviceStatus,
reserved8: [12]u8,
queue_descriptor_low: u32,
queue_descriptor_high: u32,
reserved9: [8]u8,
queue_available_low: u32,
queue_available_high: u32,
reserved10: [8]u8,
queue_used_low: u32,
queue_used_high: u32,
reserved11: [8]u8,
reserved12: [0x4c]u8,
config_gen: u32,
pub const magic = 0x74726976;
pub const version = 2;
pub const configuration_offset = 0x100;
pub fn init(mmio: *volatile @This(), comptime FeaturesEnumT: type) void {
if (mmio.magic_value != magic) @panic("virtio magic corrupted");
if (mmio.version != version) @panic("outdated virtio spec");
if (mmio.device_id == 0) @panic("invalid device");
// 1. Reset
mmio.reset_device();
if (mmio.device_status.bits != 0) @panic("Device status should be reset and cleared");
// 2. Ack the device
mmio.device_status.or_flag(.acknowledge);
// 3. The driver knows how to use the device
mmio.device_status.or_flag(.driver);
// 4. Read device feature bits and write (a subset of) them
var features = mmio.device_features;
mmio.debug_device_features(FeaturesEnumT);
log.debug("Features: {b}", .{features});
// Disable VIRTIO F RING EVENT INDEX
features &= ~@as(u32, 1 << 29);
mmio.driver_features = features;
// 5. Set features ok status bit
mmio.device_status.or_flag(.features_ok);
if (!mmio.device_status.contains(.features_ok)) @panic("unsupported features");
}
pub inline fn reset_device(mmio: *volatile @This()) void {
mmio.device_status = DeviceStatus.empty();
}
pub inline fn set_driver_initialized(mmio: *volatile @This()) void {
mmio.device_status.or_flag(.driver_ok);
}
pub inline fn notify_queue(mmio: *volatile @This()) void {
mmio.queue_notify = 0;
}
pub fn add_queue_to_device(mmio: *volatile @This(), selected_queue: u32) *volatile SplitQueue {
if (mmio.queue_num_max < ring_size) {
@panic("foooo");
}
mmio.queue_selector = selected_queue;
mmio.queue_num = ring_size;
if (mmio.queue_ready != 0) @panic("queue ready");
const total_size = @sizeOf(SplitQueue) + (@sizeOf(Descriptor) * ring_size) + @sizeOf(Available) + @sizeOf(Used);
const page_count = total_size / page_size + @boolToInt(total_size % page_size != 0);
// All physical address space is identity-mapped so mapping is not needed here
const queue_physical = kernel.arch.Physical.allocate1(page_count) orelse @panic("unable to allocate memory for virtio block device queue");
const queue = @intToPtr(*volatile SplitQueue, kernel.arch.Virtual.AddressSpace.physical_to_virtual(queue_physical));
// TODO: distinguist between physical and virtual
queue.num = 0;
queue.last_seen_used = 0;
var ptr: u64 = kernel.align_forward(queue_physical + @sizeOf(SplitQueue), SplitQueue.descriptor_table_alignment);
queue.descriptors = @intToPtr(@TypeOf(queue.descriptors), ptr);
// identity-mapped
const physical = @ptrToInt(queue);
const descriptor = physical + @sizeOf(SplitQueue);
ptr += ring_size * @sizeOf(Descriptor);
ptr = kernel.align_forward(ptr, SplitQueue.available_ring_alignment);
const available = ptr;
queue.available = @intToPtr(@TypeOf(queue.available), available);
queue.available.flags = 0;
queue.available.index = 0;
ptr += @sizeOf(Available);
ptr = kernel.align_forward(ptr, SplitQueue.used_ring_alignment);
const used = ptr;
queue.used = @intToPtr(@TypeOf(queue.used), used);
queue.used.flags = 0;
queue.used.index = 0;
// notify device of queue
mmio.queue_num = ring_size;
// specify queue structs
mmio.queue_descriptor_low = @truncate(u32, descriptor);
mmio.queue_descriptor_high = @truncate(u32, descriptor >> 32);
mmio.queue_available_low = @truncate(u32, available);
mmio.queue_available_high = @truncate(u32, available >> 32);
mmio.queue_used_low = @truncate(u32, used);
mmio.queue_used_high = @truncate(u32, used >> 32);
mmio.queue_ready = 1;
return queue;
}
pub const DeviceStatus = kernel.Bitflag(true, enum(u32) {
acknowledge = 0,
driver = 1,
driver_ok = 2,
features_ok = 3,
device_needs_reset = 6,
failed = 7,
});
const Features = enum(u6) {
ring_indirect_descriptors = 28,
ring_event_index = 29,
version_1 = 32,
access_platform = 33,
ring_packed = 34,
in_order = 35,
order_platform = 36,
single_root_io_virtualization = 37,
notification_data = 38,
};
const log = kernel.log.scoped(.MMIO);
pub fn debug_device_status(mmio: *volatile MMIO) void {
log.debug("Reading device status...", .{});
const device_status = mmio.device_status;
for (kernel.enum_values(DeviceStatus)) |flag| {
if (device_status & @enumToInt(flag) != 0) {
log.debug("Flag set: {}", .{flag});
}
}
}
pub fn debug_device_features(mmio: *volatile MMIO, comptime FeaturesEnum: type) void {
mmio.device_feature_selector = 0;
const low = mmio.device_features;
mmio.device_feature_selector = 1;
const high = mmio.device_features;
mmio.device_feature_selector = 0;
const features: u64 = (@intCast(u64, high) << 32) | low;
for (kernel.enum_values(Features)) |feature| {
if (features & (@intCast(u64, 1) << @enumToInt(feature)) != 0) {
log.debug("Device has feature: {s}, bit {}", .{ @tagName(feature), @enumToInt(feature) });
}
}
for (kernel.enum_values(FeaturesEnum)) |feature| {
if (features & (@intCast(u64, 1) << @enumToInt(feature)) != 0) {
log.debug("Device has {}: {s}, bit {}", .{ FeaturesEnum, @tagName(feature), @enumToInt(feature) });
}
}
}
};
pub const Descriptor = struct {
address: u64,
length: u32,
flags: u16,
next: u16,
pub const Flag = enum(u16) {
next = 1 << 0,
write_only = 1 << 1,
indirect = 1 << 2,
};
};
const Available = struct {
flags: u16,
index: u16,
ring: [ring_size]u16,
event: u16,
padding: [2]u8,
};
const Used = struct {
flags: u16,
index: u16,
ring: [ring_size]Entry,
event: u16,
const Entry = struct {
id: u32,
length: u32,
};
};
pub const SplitQueue = struct {
num: u32,
last_seen_used: u32,
descriptors: [*]align(descriptor_table_alignment) volatile Descriptor,
available: *align(available_ring_alignment) volatile Available,
used: *align(used_ring_alignment) volatile Used,
const descriptor_table_alignment = 16;
const available_ring_alignment = 2;
const used_ring_alignment = 4;
pub fn push_descriptor(queue: *volatile SplitQueue, p_descriptor_index: *u16) *volatile Descriptor {
// TODO Cause for a bug
p_descriptor_index.* = @intCast(u16, queue.num);
const descriptor = &queue.descriptors[queue.num];
queue.num += 1;
while (queue.num >= ring_size) : (queue.num -= ring_size) {}
return descriptor;
}
pub fn push_available(queue: *volatile SplitQueue, descriptor: u16) void {
queue.available.ring[queue.available.index % ring_size] = descriptor;
queue.available.index += 1;
}
pub fn pop_used(queue: *volatile SplitQueue) ?*volatile Descriptor {
if (queue.last_seen_used == queue.used.index) return null;
const id = queue.used.ring[queue.last_seen_used % ring_size].id;
queue.last_seen_used += 1;
const used = &queue.descriptors[id];
return used;
}
pub fn get_descriptor(queue: *volatile SplitQueue, descriptor_id: u16) ?*volatile Descriptor {
if (descriptor_id < ring_size) return &queue.descriptors[descriptor_id] else return null;
}
};
const InterruptStatus = kernel.Bitflag(true, enum(u32) {
used_buffer = 0,
configuration_change = 1,
}); | src/kernel/arch/riscv64/virtio.zig |
const std = @import("std");
const SerialPortConsole = @import("console/SerialPortConsole.zig");
const TextConsole = @import("console/TextConsole.zig");
const Console = @This();
// I chose SerialPortConsole colors, since SerialPortConsole is going to be used even after entering graphics mode.
// Also, after entering graphics mode, we have no problems with representing SerialPortConsole colors anyway.
pub const ForegroundColor = SerialPortConsole.ForegroundColor;
pub const BackgroundColor = SerialPortConsole.BackgroundColor;
serial_port_console: SerialPortConsole,
text_console: TextConsole,
foreground_color: ForegroundColor = ForegroundColor.default,
background_color: BackgroundColor = BackgroundColor.default,
fn text_console_foreground_color(self: *const Console) TextConsole.ForegroundColor {
return switch (self.foreground_color) {
.default => .light_gray,
.black => .black,
.red => .red,
.green => .green,
.yellow => .yellow,
.blue => .blue,
.magenta => .purple,
.cyan => .cyan,
.light_gray => .light_gray,
.gray => .gray,
.light_red => .light_red,
.light_green => .light_green,
.light_yellow => .yellow,
.light_blue => .light_blue,
.light_magenta => .light_purple,
.light_cyan => .cyan,
.white => .white,
};
}
fn text_console_background_color(self: *const Console) TextConsole.BackgroundColor {
return switch (self.background_color) {
.default => .black,
.black => .black,
.red => .red,
.green => .green,
.yellow => .gray,
.blue => .blue,
.magenta => .purple,
.cyan => .cyan,
.light_gray => .gray,
.gray => .gray,
.light_red => .red,
.light_green => .green,
.light_yellow => .gray,
.light_blue => .blue,
.light_magenta => .purple,
.light_cyan => .cyan,
.white => .gray,
};
}
pub fn clear_and_reset_cursor(self: *Console) void {
self.serial_port_console.set_background_color(self.background_color);
self.serial_port_console.set_foreground_color(self.foreground_color);
self.serial_port_console.clear_and_reset_cursor();
self.text_console.clear_and_reset_cursor(self.text_console_foreground_color(), self.text_console_background_color());
}
pub fn write_formatted(self: *Console, comptime format: []const u8, arguments: anytype) void {
try std.fmt.format(self.writer(), format, arguments);
}
pub fn write_string(self: *Console, string: []const u8) void {
self.serial_port_console.set_background_color(self.background_color);
self.serial_port_console.set_foreground_color(self.foreground_color);
self.serial_port_console.write_string(string);
self.text_console.write_string(string, self.text_console_foreground_color(), self.text_console_background_color());
}
fn writer_write(context: *Console, string: []const u8) error{}!usize {
context.write_string(string);
return string.len;
}
pub const Writer = std.io.Writer(*Console, error{}, writer_write);
pub fn writer(self: *Console) Writer {
return .{ .context = self };
}
pub fn initialize() Console {
return .{ .serial_port_console = SerialPortConsole.com1(), .text_console = TextConsole.standard_text_console() };
} | kernel/Console.zig |
const std = @import("std");
const ArrayList = std.ArrayList;
const Allocator = std.mem.Allocator;
const Checksum = @import("./checksum.zig").Checksum;
/// A checksum implementation - using the Adler-32 algorithm.
pub fn Adler32() type {
return struct {
const Self = @This();
const ChecksumType = u32;
const PRIME_MOD = 65521;
const default_adler32_val = 0;
bytes: ArrayList(u8),
checksum: Checksum(ChecksumType),
checksum_value: ChecksumType,
allocator: *Allocator,
pub fn init(allocator: *Allocator) Self {
return Self{
.bytes = ArrayList(u8).init(allocator),
.checksum = Checksum(ChecksumType){
.reset_fn = reset,
.update_byte_array_range_fn = updateByteArrayRange,
.close_fn = close,
},
.checksum_value = default_adler32_val,
.allocator = allocator,
};
}
fn reset(checksum: *Checksum(ChecksumType)) void {
const self = @fieldParentPtr(Self, "checksum", checksum);
self.checksum_value = default_adler32_val;
self.bytes.shrink(0);
}
fn close(checksum: *Checksum(ChecksumType)) void {
const self = @fieldParentPtr(Self, "checksum", checksum);
self.bytes.deinit();
}
/// Simple, unoptimised implementation
fn updateByteArrayRange(checksum: *Checksum(ChecksumType), bs: []const u8, offset: usize, len: usize) !void {
const self = @fieldParentPtr(Self, "checksum", checksum);
for (bs[offset .. offset + len]) |b| {
try self.bytes.append(b);
}
var r: ChecksumType = 1;
var s: ChecksumType = 0;
for (self.bytes.items) |b| {
r = @mod(r + b, PRIME_MOD);
s = @mod(r + s, PRIME_MOD);
}
self.checksum_value = (s << 16) | r;
}
};
} | src/adler32.zig |
const std = @import("std");
// dross-zig
const Color = @import("../core/color.zig").Color;
const Vector2 = @import("../core/vector2.zig").Vector2;
const tx = @import("texture.zig");
const TextureId = tx.TextureId;
const Texture = tx.Texture;
const TextureErrors = tx.TextureErrors;
const TextureRegion = @import("texture_region.zig").TextureRegion;
const ResourceHandler = @import("../core/resource_handler.zig").ResourceHandler;
// -----------------------------------------
// - Sprite -
// -----------------------------------------
pub const Sprite = struct {
internal_texture_region: ?*TextureRegion = undefined,
internal_color: Color = undefined,
/// The point of rotation on the sprite in pixels.
internal_origin: Vector2 = undefined,
internal_scale: Vector2 = undefined,
internal_angle: f32 = 0.0,
flip_h: bool = false,
const Self = @This();
/// Allocates and builds a Sprite
/// Comments: The allocated Sprite will be owned by the caller, but the
/// allocated Texture is owned by the Resource Handler.
pub fn new(
allocator: *std.mem.Allocator,
texture_name: []const u8,
texture_path: []const u8,
atlas_coordinates: Vector2,
texture_region_size: Vector2,
number_of_cells: Vector2,
) !*Self {
var self = try allocator.create(Sprite);
const texture_op = try ResourceHandler.loadTexture(texture_name, texture_path);
const texture_atlas = texture_op orelse return TextureErrors.FailedToLoad;
self.internal_texture_region = try TextureRegion.new(
allocator,
texture_atlas,
atlas_coordinates,
texture_region_size,
number_of_cells,
);
//const texture_size = self.internal_texture.?.size();
self.internal_color = Color.rgba(1.0, 1.0, 1.0, 1.0);
// self.origin = texture_size.?.scale(0.5);
self.internal_origin = Vector2.zero();
self.internal_scale = Vector2.new(1.0, 1.0);
self.internal_angle = 0.0;
self.flip_h = false;
return self;
}
/// Cleans up and de-allocates the Sprite
pub fn free(allocator: *std.mem.Allocator, self: *Self) void {
// Sprite is not the owner of texture, but has a reference to it is all.
// Resource Handler is what owns all textures and will dispose of it.
// It wouldn't make sense to unload a texture just because a single
// Sprite instance was destroyed, unless that is the only reference of
// the texture.
TextureRegion.free(allocator, self.internal_texture_region.?);
allocator.destroy(self);
}
/// Returns a pointer to the stored TextureRegion
pub fn textureRegion(self: *Self) ?*TextureRegion {
return self.internal_texture_region;
}
/// Returns the TextureId of the stored texture
pub fn textureId(self: *Self) ?TextureId {
if (self.internal_texture_region == undefined) return null;
return self.internal_texture_region.?.texture().?.id();
}
/// Sets the Sprites texture
pub fn setTexture(self: *Self, new_texture: *TextureRegion) void {
self.internal_texture_region = new_texture;
}
/// Sets the Sprite color modulation
pub fn setColor(self: *Self, new_color: Color) void {
self.internal_color = new_color;
}
/// Returns the Sprite current color modulation
pub fn color(self: *Self) Color {
return self.internal_color;
}
/// Sets the Sprite scale
pub fn setScale(self: *Self, new_scale: Vector2) void {
self.internal_scale = new_scale;
}
/// Returns the Sprite's current scale as a Vector2
pub fn scale(self: *Self) Vector2 {
return self.internal_scale;
}
/// Returns the size of the Sprite's active texture
pub fn size(self: *Self) ?Vector2 {
if (self.internal_texture_region == undefined) return null;
return self.internal_texture_region.?.texture().?.size();
}
/// Returns the Sprite's origin
pub fn origin(self: *Self) Vector2 {
return self.internal_origin;
}
/// Sets the Sprite's origin
/// Origin is in pixels, not percentage.
pub fn setOrigin(self: *Self, new_origin: Vector2) void {
self.internal_origin = new_origin;
}
/// Returns the Sprite's angle of rotation (in degrees)
pub fn angle(self: *Self) f32 {
return self.internal_angle;
}
/// Sets the Sprite's angle of rotation (in degrees)
pub fn setAngle(self: *Self, new_angle: f32) void {
self.internal_angle = new_angle;
}
/// Flags for the sprite's texture to be flipped horizontally
pub fn setFlipH(self: *Self, value: bool) void {
self.flip_h = value;
}
/// Returns whether the Sprite's texture has been flagged to be flipped horizontally
pub fn flipH(self: *Self) bool {
return self.flip_h;
}
}; | src/renderer/sprite.zig |
const std = @import("std");
const os = std.os;
const irc = @import("client.zig");
fn initClient() !irc.Client {
return try irc.Client.initFromConfig(.{
.server = os.getenv("IRC_SERVER") orelse return error.MissingEnv,
.port = os.getenv("IRC_PORT") orelse return error.MissingEnv,
.nickname = os.getenv("IRC_NICKNAME") orelse return error.MissingEnv,
.channel = os.getenv("IRC_CHANNEL") orelse return error.MissingEnv,
.password = <PASSWORD>("IRC_OAUTH"),
.clientid = os.getenv("IRC_CLIENTID"),
.api_config_file = os.getenv("API_CONFIG_FILE"),
});
}
pub fn main() anyerror!void {
const client = try initClient();
try client.identify();
try client.handle();
}
// zig test src/main.zig -lc -lcurl -L/usr/lib/x86_64-linux-gnu -I/usr/include/x86_64-linux-gnu/ -isystem /usr/include/
test "simple stress test" {
const client = try initClient();
defer client.deinit();
try client.identify();
const api = @import("api.zig");
const mhs = @import("message_handlers.zig");
const reqs = try api.initRequests(std.heap.c_allocator, client.config);
const welcome =
\\:tmi.twitch.tv 001 nickname :Welcome, GLHF!
\\:tmi.twitch.tv 002 nickname :Your host is tmi.twitch.tv
\\:tmi.twitch.tv 003 nickname :This server is rather new
\\:tmi.twitch.tv 004 nickname :-
\\:tmi.twitch.tv 375 nickname :-
\\:tmi.twitch.tv 372 nickname :You are in a maze of twisty passages, all alike.
\\:tmi.twitch.tv 376 nickname :>
\\:nickname!<EMAIL> JOIN #channel
\\:nickname.tmi.twitch.tv 353 nickname = #channel :nickname
\\:nickname.tmi.twitch.tv 366 nickname #channel :End of /NAMES list
\\:[email protected] PRIVMSG #channel :hello chat
\\PING :tmi.twitch.tv
\\:[email protected] PRIVMSG #channel :!name
\\:[email protected] PRIVMSG #channel :!logo
\\:channel!<EMAIL>@channel.tmi.twitch.tv PRIVMSG #channel :!uptime
;
var ctx = mhs.Context{ .config = client.config, .requests = reqs };
var i: usize = 0;
while (i < 100) : (i += 1)
try client.handleReceived(welcome, ctx);
} | src/main.zig |
const std = @import("std");
const hyperia = @import("hyperia.zig");
const SpinLock = hyperia.sync.SpinLock;
const math = std.math;
const time = std.time;
const testing = std.testing;
pub const Options = struct {
// max_concurrent_attempts: usize, // TODO(kenta): use a cancellable semaphore to limit max number of concurrent attempts
failure_threshold: usize,
reset_timeout: usize,
};
pub fn CircuitBreaker(comptime opts: Options) type {
return struct {
const Self = @This();
pub const State = enum {
closed,
open,
half_open,
};
lock: SpinLock = .{},
failure_count: usize = 0,
last_failure_time: usize = 0,
pub fn init(state: State) Self {
return switch (state) {
.closed => .{},
.half_open => .{ .failure_count = math.maxInt(usize) },
.open => .{ .failure_count = math.maxInt(usize), .last_failure_time = math.maxInt(usize) },
};
}
pub fn run(self: *Self, current_time: usize, closure: anytype) !void {
switch (self.query()) {
.closed, .half_open => {
closure.call() catch {
self.reportFailure(current_time);
return error.Failed;
};
self.reportSuccess();
},
.open => return error.Broken,
}
}
pub fn query(self: *Self, current_time: usize) State {
const held = self.lock.acquire();
defer held.release();
if (self.failure_count >= opts.failure_threshold) {
if (math.sub(usize, current_time, self.last_failure_time) catch 0 <= opts.reset_timeout) {
return .open;
}
return .half_open;
}
return .closed;
}
pub fn reportFailure(self: *Self, current_time: usize) void {
const held = self.lock.acquire();
defer held.release();
self.failure_count = math.add(usize, self.failure_count, 1) catch opts.failure_threshold;
self.last_failure_time = current_time;
}
pub fn reportSuccess(self: *Self) void {
const held = self.lock.acquire();
defer held.release();
self.failure_count = 0;
self.last_failure_time = 0;
}
};
}
test {
testing.refAllDecls(CircuitBreaker(.{ .failure_threshold = 10, .reset_timeout = 1000 }));
}
test "circuit_breaker: init and query state" {
const TestBreaker = CircuitBreaker(.{ .failure_threshold = 10, .reset_timeout = 1000 });
const current_time = @intCast(usize, time.milliTimestamp());
testing.expect(TestBreaker.init(.open).query(current_time) == .open);
testing.expect(TestBreaker.init(.closed).query(current_time) == .closed);
testing.expect(TestBreaker.init(.half_open).query(current_time) == .half_open);
} | circuit_breaker.zig |
const std = @import("std");
const print = std.debug.print;
const data = @embedFile("../data/day08.txt");
pub fn count_overlap(haystack: []const u8, needle: []const u8) u8 {
var count : u8 = 0;
for (haystack) |h| {
for (needle) |n| {
if (h == n) {
count += 1;
}
}
}
return count;
}
pub fn main() !void {
var timer = try std.time.Timer.start();
{
var lines = std.mem.tokenize(data, "\r\n");
var total : u32 = 0;
while (lines.next()) |line| {
var unique_signal_values_or_input = std.mem.tokenize(line, "|");
var unique_signal_values = unique_signal_values_or_input.next().?;
var inputs = unique_signal_values_or_input.next().?;
var inputs_iterator = std.mem.tokenize(inputs, " ");
while (inputs_iterator.next()) |input| {
total += switch (input.len) {
2, 3, 4, 7 => 1,
else => @as(u32, 0)
};
}
}
print("🎁 Total 1, 4, 7, 8 digits: {}\n", .{total});
print("Day 08 - part 01 took {:15}ns\n", .{timer.lap()});
timer.reset();
}
{
var lines = std.mem.tokenize(data, "\r\n");
var total : usize = 0;
while (lines.next()) |line| {
var digits = [_]?[]const u8{null} ** 10;
var unique_signal_values_or_input = std.mem.tokenize(line, "|");
var unique_signal_values = unique_signal_values_or_input.next().?;
{
var iterator = std.mem.tokenize(unique_signal_values, " ");
// First we record the easy ones: 2, 4, 3, & 7
while (iterator.next()) |unique_signal_value| {
switch (unique_signal_value.len) {
2 => digits[1] = unique_signal_value,
4 => digits[4] = unique_signal_value,
3 => digits[7] = unique_signal_value,
7 => digits[8] = unique_signal_value,
else => {},
}
}
}
{
var iterator = std.mem.tokenize(unique_signal_values, " ");
while (iterator.next()) |unique_signal_value| {
// 3 is the only digit with 5 segments that contains 1
if (unique_signal_value.len == 5) {
const overlap = count_overlap(unique_signal_value, digits[1].?);
if (overlap == 2) {
digits[3] = unique_signal_value;
}
}
// 6 is the only digit with 6 segments that does not contain 1
if (unique_signal_value.len == 6) {
const overlap = count_overlap(unique_signal_value, digits[1].?);
if (overlap != 2) {
digits[6] = unique_signal_value;
}
}
// 9 is the only digit with 6 segments that contains 4
if (unique_signal_value.len == 6) {
const overlap = count_overlap(unique_signal_value, digits[4].?);
if (overlap == 4) {
digits[9] = unique_signal_value;
}
}
}
}
{
var iterator = std.mem.tokenize(unique_signal_values, " ");
while (iterator.next()) |unique_signal_value| {
// 5 is the only digit with 5 segments that is contained in 6, and
// 2 is the only digit with 5 segments that has 4 overlaps with 6, and
// does not contain 1 (this excludes 3)
if (unique_signal_value.len == 5) {
const overlap = count_overlap(unique_signal_value, digits[6].?);
if (overlap == 5) {
digits[5] = unique_signal_value;
}
if (overlap == 4) {
if (1 == count_overlap(unique_signal_value, digits[1].?)) {
digits[2] = unique_signal_value;
}
}
}
// 0 is the only digit with 6 segments that isn't 6 or 9
if (unique_signal_value.len == 6) {
if ((6 != count_overlap(unique_signal_value, digits[6].?)) and
(6 != count_overlap(unique_signal_value, digits[9].?))) {
digits[0] = unique_signal_value;
}
}
}
}
var output : usize = 0;
var inputs = unique_signal_values_or_input.next().?;
var inputs_iterator = std.mem.tokenize(inputs, " ");
while (inputs_iterator.next()) |input| {
for (digits) |digit, i| {
if (input.len != digit.?.len) {
continue;
}
if (input.len != count_overlap(input, digit.?)) {
continue;
}
output *= 10;
output += i;
break;
}
}
total += output;
}
print("🎁 Total output values: {}\n", .{total});
print("Day 08 - part 02 took {:15}ns\n", .{timer.lap()});
print("❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️\n", .{});
}
} | src/day08.zig |
const std = @import("std");
const warn = std.debug.print;
const Allocator = std.mem.Allocator;
const util = @import("../util.zig");
const c = @cImport({
@cInclude("lmdb.h");
});
var env: *c.MDB_env = undefined;
const dbpath = "./db";
pub fn init(allocator: *Allocator) !void {
var mdb_ret: c_int = 0;
mdb_ret = c.mdb_env_create(@ptrCast([*c]?*c.MDB_env, &env));
if (mdb_ret != 0) {
warn("mdb_env_create failed {}\n", .{mdb_ret});
return error.BadValue;
}
mdb_ret = c.mdb_env_set_mapsize(env, 250 * 1024 * 1024);
if (mdb_ret != 0) {
warn("mdb_env_set_mapsize failed {}\n", .{mdb_ret});
return error.BadValue;
}
std.os.mkdir(dbpath, 0o0755) catch {};
mdb_ret = c.mdb_env_open(env, util.sliceToCstr(allocator, dbpath), 0, 0o644);
if (mdb_ret != 0) {
warn("mdb_env_open failed {}\n", .{mdb_ret});
return error.BadValue;
}
stats();
}
pub fn stats() void {
var mdbStat: c.MDB_stat = undefined;
c.mdb_env_stat(env, &mdbStat);
warn("lmdb cache {} entries\n", .{mdbStat.ms_entries});
}
pub fn write(namespace: []const u8, key: []const u8, value: []const u8, allocator: *Allocator) !void {
var txnptr = allocator.create(*c.struct_MDB_txn) catch unreachable;
var ctxnMaybe = @ptrCast([*c]?*c.struct_MDB_txn, txnptr);
var ret = c.mdb_txn_begin(env, null, 0, ctxnMaybe);
if (ret == 0) {
// warn("lmdb write {} {}={}\n", namespace, key, value);
var dbiptr = allocator.create(c.MDB_dbi) catch unreachable;
ret = c.mdb_dbi_open(txnptr.*, null, c.MDB_CREATE, dbiptr);
if (ret == 0) {
// TODO: seperator issue. perhaps 2 byte invalid utf8 sequence
var fullkey = std.fmt.allocPrint(allocator, "{}:{}", .{ namespace, key }) catch unreachable;
var mdb_key = mdbVal(fullkey, allocator);
var mdb_value = mdbVal(value, allocator);
ret = c.mdb_put(txnptr.*, dbiptr.*, mdb_key, mdb_value, 0);
if (ret == 0) {
ret = c.mdb_txn_commit(txnptr.*);
if (ret == 0) {
_ = c.mdb_dbi_close(env, dbiptr.*);
} else {
warn("mdb_txn_commit ERR {}\n", .{ret});
return error.mdb_txn_commit;
}
} else {
warn("mdb_put ERR {}\n", .{ret});
return error.mdb_put;
}
} else {
warn("mdb_dbi_open ERR {}\n", .{ret});
return error.mdb_dbi_open;
}
} else {
warn("mdb_txn_begin ERR {}\n", .{ret});
return error.mdb_txn_begin;
}
}
fn mdbVal(data: []const u8, allocator: *Allocator) *c.MDB_val {
var dataptr = @intToPtr(?*anyopaque, @ptrToInt(data.ptr));
var mdb_val = allocator.create(c.MDB_val) catch unreachable;
mdb_val.mv_size = data.len;
mdb_val.mv_data = dataptr;
return mdb_val;
} | src/db/lmdb.zig |
const std = @import("std");
const real_input = @embedFile("day-18_real-input");
const test_input_1 = @embedFile("day-18_test-input-1");
const test_input_2 = @embedFile("day-18_test-input-2");
var allocator: std.mem.Allocator = undefined;
pub fn main() !void {
std.debug.print("--- Day 18 ---\n", .{});
const total_magnitude = try totalMagnitude(real_input);
std.debug.print("total magnitude is {}\n", .{ total_magnitude });
const highest_magnitude = try highestMagnitude(real_input);
std.debug.print("highest magnitude is {}\n", .{ highest_magnitude });
}
fn highestMagnitude(input: []const u8) !u32 {
var outer_alloc = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer outer_alloc.deinit();
var lines = std.ArrayList([]const u8).init(outer_alloc.allocator());
var line_it = std.mem.tokenize(u8, input, "\n\r");
while (line_it.next()) |line| {
if (line.len == 0) continue;
try lines.append(line);
}
var highest_magnitude: u32 = 0;
var lhs: usize = 0;
while (lhs < lines.items.len):(lhs += 1) {
var rhs: usize = 0;
while (rhs < lines.items.len):(rhs += 1) {
if (lhs == rhs) continue;
var inner_alloc = std.heap.ArenaAllocator.init(outer_alloc.allocator());
defer inner_alloc.deinit();
allocator = inner_alloc.allocator();
var left = try parseValue(lines.items[lhs]);
var right = try parseValue(lines.items[rhs]);
const result = try add(left, right);
try reduce(result);
highest_magnitude = @maximum(result.magnitude(), highest_magnitude);
}
}
return highest_magnitude;
}
fn totalMagnitude(input: []const u8) !u32 {
var alloc = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer alloc.deinit();
allocator = alloc.allocator();
const add_result = try addList(input);
return add_result.magnitude();
}
fn addList(input: []const u8) !*Node {
var line_it = std.mem.tokenize(u8, input, "\n\r");
var current = try parseValue(line_it.next().?);
while (line_it.next()) |line| {
if (line.len == 0) continue;
var other = try parseValue(line);
current = try add(current, other);
try reduce(current);
}
return current;
}
fn add(lhs: *Node, rhs: *Node) !*Node {
var result = try allocator.create(Node);
result.* = .{
.parent = null,
.value = .{
.pair = .{
.left = lhs,
.right = rhs,
}
}
};
lhs.parent = result;
rhs.parent = result;
return result;
}
fn reduce(root: *Node) !void {
while (true) {
if (try handleFirstExplosion(root)) {
continue;
}
if (try handleFirstSplit(root)) {
continue;
}
break;
}
}
fn handleFirstSplit(root: *Node) !bool {
var it = try TreeIterator.init(root);
return while (try it.next()) |node| {
switch (node.value) {
.number => |number| {
if (number >= 10) {
const float = @intToFloat(f32, number);
const div = float / 2;
var left = try allocator.create(Node);
left.* = .{
.parent = node,
.value = .{ .number = @floatToInt(u32, @floor(div)) },
};
var right = try allocator.create(Node);
right.* = .{
.parent = node,
.value = .{ .number = @floatToInt(u32, @ceil(div)) }
};
node.value = .{
.pair = .{
.left = left,
.right = right,
}
};
break true;
}
},
.pair => { },
}
} else false;
}
fn handleFirstExplosion(root: *Node) !bool {
var it = try TreeIterator.init(root);
var last_number: ?*u32 = null;
return while (try it.next()) |node| {
switch (node.value) {
.number => |*number| {
last_number = number;
},
.pair => |pair| {
if (node.level() >= 4 and pair.canExplode()) {
_ = (try it.next()).?;
_ = (try it.next()).?;
if (last_number) |number| {
number.* += pair.left.value.number;
}
while (try it.next()) |next| {
switch (next.value) {
.number => |*number| {
number.* += pair.right.value.number;
break;
},
.pair => { },
}
}
node.value = .{ .number = 0 };
break true;
}
},
}
} else false;
}
fn parseValue(string: []const u8) !*Node {
var it = StringIterator { .string = string };
return parseValueRecursive(&it, null);
}
fn parseValueRecursive(it: *StringIterator, parent: ?*Node) std.mem.Allocator.Error!*Node {
var result = try allocator.create(Node);
const char = it.next();
switch (char) {
'[' => {
var left = try parseValueRecursive(it, result);
it.gobble(',');
var right = try parseValueRecursive(it, result);
it.gobble(']');
result.* = .{
.parent = parent,
.value = .{
.pair = .{
.left = left,
.right = right,
}
},
};
},
'0'...'9' => {
result.* = .{
.parent = parent,
.value = .{ .number = char - '0' },
};
},
else => {
std.debug.print("nothing implemented for {c}\n", .{ char });
unreachable;
}
}
return result;
}
const Node = struct {
parent: ?*Node,
value: Value,
fn level(node: Node) u32 {
var parent = node.parent;
var result: u32 = 0;
while (parent != null) {
parent = parent.?.parent;
result += 1;
}
return result;
}
fn magnitude(node: *Node) u32 {
return switch (node.value) {
.number => |number| number,
.pair => |pair| 3 * pair.left.magnitude() + 2 * pair.right.magnitude(),
};
}
fn toString(node: *Node, buffer: []u8) ![]const u8 {
var alloc = std.heap.FixedBufferAllocator.init(buffer);
var string = std.ArrayList(u8).init(alloc.allocator());
try toStringRecursive(node, &string);
return string.items;
}
fn toStringRecursive(node: *Node, string: *std.ArrayList(u8)) std.ArrayList(u8).Writer.Error!void {
switch (node.value) {
.number => |number| try string.writer().print("{}", .{ number }),
.pair => |pair| {
try string.writer().print("[", .{});
try toStringRecursive(pair.left, string);
try string.writer().print(",", .{});
try toStringRecursive(pair.right, string);
try string.writer().print("]", .{});
},
}
}
};
const ValueType = enum { number, pair };
const Value = union(ValueType) {
number: u32,
pair: Pair,
};
const Pair = struct {
left: *Node,
right: *Node,
fn canExplode(pair: Pair) bool {
const lhs_number = @as(ValueType, pair.left.value) == .number;
const rhs_number = @as(ValueType, pair.right.value) == .number;
return lhs_number and rhs_number;
}
};
const TreeIterator = struct {
stack: std.ArrayList(*Node),
fn init(root: *Node) !@This() {
var it = @This() { .stack = std.ArrayList(*Node).init(allocator) };
try it.stack.append(root);
return it;
}
fn next(it: *@This()) !?*Node {
if (it.stack.items.len == 0) return null;
var result = it.stack.pop();
switch (result.value) {
.number => { },
.pair => |pair| {
try it.stack.append(pair.right);
try it.stack.append(pair.left);
}
}
return result;
}
};
const StringIterator = struct {
string: []const u8,
current: usize = 0,
fn next(reader: *@This()) u8 {
if (reader.current >= reader.string.len) @panic("out of bounds!");
defer reader.current += 1;
return reader.string[reader.current];
}
fn gobble(reader: *@This(), expected: u8,) void {
const char = reader.next();
if (char != expected) {
std.debug.print("expected {c}, but found {c}\n", .{ expected, char });
unreachable;
}
}
};
test "explode" {
std.debug.print("\n", .{});
var alloc = std.heap.ArenaAllocator.init(std.heap.page_allocator);
var string_buffer: [1024 * 1024]u8 = undefined;
defer alloc.deinit();
allocator = alloc.allocator();
const cases = [_]struct { input: []const u8, expected: []const u8 } {
.{ .input = "[[[[[9,8],1],2],3],4]", .expected = "[[[[0,9],2],3],4]" },
.{ .input = "[7,[6,[5,[4,[3,2]]]]]", .expected = "[7,[6,[5,[7,0]]]]" },
.{ .input = "[[6,[5,[4,[3,2]]]],1]", .expected = "[[6,[5,[7,0]]],3]" },
.{ .input = "[[3,[2,[1,[7,3]]]],[6,[5,[4,[3,2]]]]]", .expected = "[[3,[2,[8,0]]],[9,[5,[7,0]]]]" },
};
for (cases) |case, i| {
var root = try parseValue(case.input);
try reduce(root);
const result = try root.toString(string_buffer[0..]);
std.debug.print("case {}: {s} -> {s}\n", .{ i, case.input, result });
try std.testing.expectEqualStrings(case.expected, result);
}
}
test "add" {
std.debug.print("\n", .{});
var alloc = std.heap.ArenaAllocator.init(std.heap.page_allocator);
var string_buffer: [1024 * 1024]u8 = undefined;
defer alloc.deinit();
allocator = alloc.allocator();
const cases = [_]struct { lhs: []const u8, rhs: []const u8, expected: []const u8 } {
.{ // case 0
.lhs = "[[[[4,3],4],4],[7,[[8,4],9]]]",
.rhs = "[1,1]",
.expected = "[[[[0,7],4],[[7,8],[6,0]]],[8,1]]",
},
.{ // case 1
.lhs = "[[[0,[4,5]],[0,0]],[[[4,5],[2,6]],[9,5]]]",
.rhs = "[7,[[[3,7],[4,3]],[[6,3],[8,8]]]]",
.expected = "[[[[4,0],[5,4]],[[7,7],[6,0]]],[[8,[7,7]],[[7,9],[5,0]]]]",
},
.{ // case 2
.lhs = "[[[[4,0],[5,4]],[[7,7],[6,0]]],[[8,[7,7]],[[7,9],[5,0]]]]",
.rhs = "[[2,[[0,8],[3,4]]],[[[6,7],1],[7,[1,6]]]]",
.expected = "[[[[6,7],[6,7]],[[7,7],[0,7]]],[[[8,7],[7,7]],[[8,8],[8,0]]]]",
},
.{ // case 3
.lhs = "[[[[6,7],[6,7]],[[7,7],[0,7]]],[[[8,7],[7,7]],[[8,8],[8,0]]]]",
.rhs = "[[[[2,4],7],[6,[0,5]]],[[[6,8],[2,8]],[[2,1],[4,5]]]]",
.expected = "[[[[7,0],[7,7]],[[7,7],[7,8]]],[[[7,7],[8,8]],[[7,7],[8,7]]]]",
}, // case 4
.{
.lhs = "[[[[7,0],[7,7]],[[7,7],[7,8]]],[[[7,7],[8,8]],[[7,7],[8,7]]]]",
.rhs = "[7,[5,[[3,8],[1,4]]]]",
.expected = "[[[[7,7],[7,8]],[[9,5],[8,7]]],[[[6,8],[0,8]],[[9,9],[9,0]]]]",
},
.{ // case 5
.lhs = "[[[[7,7],[7,8]],[[9,5],[8,7]]],[[[6,8],[0,8]],[[9,9],[9,0]]]]",
.rhs = "[[2,[2,2]],[8,[8,1]]]",
.expected = "[[[[6,6],[6,6]],[[6,0],[6,7]]],[[[7,7],[8,9]],[8,[8,1]]]]",
},
.{ // case 6
.lhs = "[[[[6,6],[6,6]],[[6,0],[6,7]]],[[[7,7],[8,9]],[8,[8,1]]]]",
.rhs = "[2,9]",
.expected = "[[[[6,6],[7,7]],[[0,7],[7,7]]],[[[5,5],[5,6]],9]]"
},
.{ // case 7
.lhs = "[[[[6,6],[7,7]],[[0,7],[7,7]]],[[[5,5],[5,6]],9]]",
.rhs = "[1,[[[9,3],9],[[9,0],[0,7]]]]",
.expected = "[[[[7,8],[6,7]],[[6,8],[0,8]]],[[[7,7],[5,0]],[[5,5],[5,6]]]]",
},
.{ // case 8
.lhs = "[[[[7,8],[6,7]],[[6,8],[0,8]]],[[[7,7],[5,0]],[[5,5],[5,6]]]]",
.rhs = "[[[5,[7,4]],7],1]",
.expected = "[[[[7,7],[7,7]],[[8,7],[8,7]]],[[[7,0],[7,7]],9]]",
},
.{ // case 9
.lhs = "[[[[7,7],[7,7]],[[8,7],[8,7]]],[[[7,0],[7,7]],9]]",
.rhs = "[[[[4,2],2],6],[8,7]]",
.expected = "[[[[8,7],[7,7]],[[8,6],[7,7]]],[[[0,7],[6,6]],[8,7]]]",
},
};
for (cases) |case, i| {
var lhs = try parseValue(case.lhs);
var rhs = try parseValue(case.rhs);
var root = try add(lhs, rhs);
try reduce(root);
const result = try root.toString(string_buffer[0..]);
std.debug.print("case {}: {s} + {s} -> {s}\n", .{ i, case.lhs, case.rhs, result });
try std.testing.expectEqualStrings(case.expected, result);
}
}
test "magnitude" {
var alloc = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer alloc.deinit();
allocator = alloc.allocator();
const cases = [_]struct { input: []const u8, expected: u32 } {
.{ .input = "[9,1]", .expected = 29 },
.{ .input = "[1,9]", .expected = 21 },
.{ .input = "[[9,1],[1,9]]", .expected = 129 },
.{ .input = "[[1,2],[[3,4],5]]", .expected = 143 },
.{ .input = "[[[[0,7],4],[[7,8],[6,0]]],[8,1]]", .expected = 1384 },
.{ .input = "[[[[1,1],[2,2]],[3,3]],[4,4]]", .expected = 445 },
.{ .input = "[[[[3,0],[5,3]],[4,4]],[5,5]]", .expected = 791 },
.{ .input = "[[[[5,0],[7,4]],[5,5]],[6,6]]", .expected = 1137 },
.{ .input = "[[[[8,7],[7,7]],[[8,6],[7,7]]],[[[0,7],[6,6]],[8,7]]]", .expected = 3488 },
.{ .input = "[[[[6,6],[7,6]],[[7,7],[7,0]]],[[[7,7],[7,7]],[[7,8],[9,9]]]]", .expected = 4140 },
};
for (cases) |case| {
const root = try parseValue(case.input);
const result = root.magnitude();
try std.testing.expectEqual(case.expected, result);
}
}
test "addList" {
std.debug.print("\n", .{});
var alloc = std.heap.ArenaAllocator.init(std.heap.page_allocator);
var buffer: [1024 * 1024]u8 = undefined;
defer alloc.deinit();
allocator = alloc.allocator();
const cases = [_]struct { input: []const u8, expected: []const u8 } {
.{ .input = test_input_1, .expected = "[[[[8,7],[7,7]],[[8,6],[7,7]]],[[[0,7],[6,6]],[8,7]]]" },
.{ .input = test_input_2, .expected = "[[[[6,6],[7,6]],[[7,7],[7,0]]],[[[7,7],[7,7]],[[7,8],[9,9]]]]" },
};
for (cases) |case, i| {
std.debug.print("case {}\n", .{ i });
const result = try addList(case.input);
try std.testing.expectEqualStrings(case.expected, try result.toString(buffer[0..]));
}
}
test "totalMagnitude" {
const cases = [_]struct { input: []const u8, expected: u32 } {
.{ .input = test_input_1, .expected = 3488 },
.{ .input = test_input_2, .expected = 4140 },
};
for (cases) |case| {
const result = try totalMagnitude(case.input);
try std.testing.expectEqual(case.expected, result);
}
}
test "highestMagnitude" {
const expected: u32 = 3993;
const result = try highestMagnitude(test_input_2);
try std.testing.expectEqual(expected, result);
} | day-18.zig |
usingnamespace @import("root").preamble;
fn PtrCastPreserveCV(comptime T: type, comptime PtrToT: type, comptime NewT: type) type {
return switch (PtrToT) {
*T => *NewT,
*const T => *const NewT,
*volatile T => *volatile NewT,
*const volatile T => *const volatile NewT,
else => @compileError("wtf you doing"),
};
}
fn BitType(comptime FieldType: type, comptime ValueType: type, comptime shamt: usize) type {
const self_bit: FieldType = (1 << shamt);
return struct {
bits: Bitfield(FieldType, shamt, 1),
pub fn set(self: anytype) void {
self.bits.field().* |= self_bit;
}
pub fn unset(self: anytype) void {
self.bits.field().* &= ~self_bit;
}
pub fn read(self: anytype) ValueType {
return @bitCast(ValueType, @truncate(u1, self.bits.field().* >> shamt));
}
// Since these are mostly used with MMIO, I want to avoid
// reading the memory just to write it again, also races
pub fn write(self: anytype, val: ValueType) void {
if (@bitCast(bool, val)) {
self.set();
} else {
self.unset();
}
}
};
}
pub fn Bit(comptime FieldType: type, comptime shamt: usize) type {
return BitType(FieldType, u1, shamt);
}
pub fn Boolean(comptime FieldType: type, comptime shamt: usize) type {
return BitType(FieldType, bool, shamt);
}
pub fn Bitfield(comptime FieldType: type, comptime shamt: usize, comptime num_bits: usize) type {
if (shamt + num_bits > @bitSizeOf(FieldType)) {
@compileError("bitfield doesn't fit");
}
const self_mask: FieldType = ((1 << num_bits) - 1) << shamt;
const ValueType = std.meta.Int(.unsigned, num_bits);
return struct {
dummy: FieldType,
fn field(self: anytype) PtrCastPreserveCV(@This(), @TypeOf(self), FieldType) {
return @ptrCast(PtrCastPreserveCV(@This(), @TypeOf(self), FieldType), self);
}
pub fn write(self: anytype, val: ValueType) void {
self.field().* &= ~self_mask;
self.field().* |= @intCast(FieldType, val) << shamt;
}
pub fn read(self: anytype) ValueType {
const val: FieldType = self.field().*;
return @intCast(ValueType, (val & self_mask) >> shamt);
}
};
}
test "bit" {
const S = extern union {
low: Bit(u32, 0),
high: Bit(u32, 1),
val: u32,
};
std.testing.expect(@sizeOf(S) == 4);
std.testing.expect(@bitSizeOf(S) == 32);
var s: S = .{ .val = 1 };
std.testing.expect(s.low.read() == 1);
std.testing.expect(s.high.read() == 0);
s.low.write(0);
s.high.write(1);
std.testing.expect(s.val == 2);
}
test "boolean" {
const S = extern union {
low: Boolean(u32, 0),
high: Boolean(u32, 1),
val: u32,
};
std.testing.expect(@sizeOf(S) == 4);
std.testing.expect(@bitSizeOf(S) == 32);
var s: S = .{ .val = 2 };
std.testing.expect(s.low.read() == false);
std.testing.expect(s.high.read() == true);
s.low.write(true);
s.high.write(false);
std.testing.expect(s.val == 1);
}
test "bitfield" {
const S = extern union {
low: Bitfield(u32, 0, 16),
high: Bitfield(u32, 16, 16),
val: u32,
};
std.testing.expect(@sizeOf(S) == 4);
std.testing.expect(@bitSizeOf(S) == 32);
var s: S = .{ .val = 0x13376969 };
std.testing.expect(s.low.read() == 0x6969);
std.testing.expect(s.high.read() == 0x1337);
s.low.write(0x1337);
s.high.write(0x6969);
std.testing.expect(s.val == 0x69691337);
} | lib/util/bitfields.zig |
const std = @import("std");
const bog = @import("../bog.zig");
const Value = bog.Value;
const Vm = bog.Vm;
pub fn parse(str: []const u8, vm: *Vm) !*Value {
var tokens = std.json.TokenStream.init(str);
const token = (try tokens.next()) orelse return error.UnexpectedEndOfJson;
return parseInternal(vm, token, &tokens);
}
const Error = error{ UnexpectedToken, UnexpectedEndOfJson } || std.mem.Allocator.Error || std.json.TokenStream.Error ||
std.fmt.ParseIntError;
fn parseInternal(vm: *Vm, token: std.json.Token, tokens: *std.json.TokenStream) Error!*Value {
switch (token) {
.ObjectBegin => {
const res = try vm.gc.alloc();
res.* = .{ .map = Value.Map{} };
const map = &res.map;
while (true) {
var tok = (try tokens.next()) orelse return error.UnexpectedEndOfJson;
switch (tok) {
.ObjectEnd => break,
else => {},
}
const key = try parseInternal(vm, tok, tokens);
tok = (try tokens.next()) orelse return error.UnexpectedEndOfJson;
const val = try parseInternal(vm, tok, tokens);
try map.put(vm.gc.gpa, key, val);
}
return res;
},
.ArrayBegin => {
const res = try vm.gc.alloc();
res.* = .{ .list = Value.List{} };
const list = &res.list;
while (true) {
const tok = (try tokens.next()) orelse return error.UnexpectedEndOfJson;
switch (tok) {
.ArrayEnd => break,
else => {},
}
try list.append(vm.gc.gpa, try parseInternal(vm, tok, tokens));
}
return res;
},
.ObjectEnd, .ArrayEnd => return error.UnexpectedToken,
.String => |info| {
const source_slice = info.slice(tokens.slice, tokens.i - 1);
const val = try vm.gc.alloc();
switch (info.escapes) {
.None => val.* = Value.string(try vm.gc.gpa.dupe(u8, source_slice)),
.Some => {
const output = try vm.gc.gpa.alloc(u8, info.decodedLength());
errdefer vm.gc.gpa.free(output);
try std.json.unescapeValidString(output, source_slice);
val.* = Value.string(output);
},
}
return val;
},
.Number => |info| {
const val = try vm.gc.alloc();
if (info.is_integer) {
val.* = .{ .int = try std.fmt.parseInt(i64, info.slice(tokens.slice, tokens.i - 1), 10) };
} else {
val.* = .{ .num = try std.fmt.parseFloat(f64, info.slice(tokens.slice, tokens.i - 1)) };
}
return val;
},
.True => return &Value.True,
.False => return &Value.False,
.Null => return &Value.None,
}
}
pub fn stringify(val: *Value, vm: *Vm) !Value.String {
var b = Value.String.builder(vm.gc.gpa);
errdefer b.cancel();
try std.json.stringify(val, .{}, b.writer());
return b.finish();
} | src/std/json.zig |
pub const PR = extern enum(i32) {
SET_PDEATHSIG = 1,
GET_PDEATHSIG = 2,
GET_DUMPABLE = 3,
SET_DUMPABLE = 4,
GET_UNALIGN = 5,
SET_UNALIGN = 6,
GET_KEEPCAPS = 7,
SET_KEEPCAPS = 8,
GET_FPEMU = 9,
SET_FPEMU = 10,
GET_FPEXC = 11,
SET_FPEXC = 12,
GET_TIMING = 13,
SET_TIMING = 14,
SET_NAME = 15,
GET_NAME = 16,
GET_ENDIAN = 19,
SET_ENDIAN = 20,
GET_SECCOMP = 21,
SET_SECCOMP = 22,
CAPBSET_READ = 23,
CAPBSET_DROP = 24,
GET_TSC = 25,
SET_TSC = 26,
GET_SECUREBITS = 27,
SET_SECUREBITS = 28,
SET_TIMERSLACK = 29,
GET_TIMERSLACK = 30,
TASK_PERF_EVENTS_DISABLE = 31,
TASK_PERF_EVENTS_ENABLE = 32,
MCE_KILL = 33,
MCE_KILL_GET = 34,
SET_MM = 35,
SET_PTRACER = 0x59616d61,
SET_CHILD_SUBREAPER = 36,
GET_CHILD_SUBREAPER = 37,
SET_NO_NEW_PRIVS = 38,
GET_NO_NEW_PRIVS = 39,
GET_TID_ADDRESS = 40,
SET_THP_DISABLE = 41,
GET_THP_DISABLE = 42,
MPX_ENABLE_MANAGEMENT = 43,
MPX_DISABLE_MANAGEMENT = 44,
SET_FP_MODE = 45,
GET_FP_MODE = 46,
CAP_AMBIENT = 47,
SVE_SET_VL = 50,
SVE_GET_VL = 51,
GET_SPECULATION_CTRL = 52,
SET_SPECULATION_CTRL = 53,
_,
};
pub const PR_SET_PDEATHSIG = @enumToInt(PR.PR_SET_PDEATHSIG);
pub const PR_GET_PDEATHSIG = @enumToInt(PR.PR_GET_PDEATHSIG);
pub const PR_GET_DUMPABLE = @enumToInt(PR.PR_GET_DUMPABLE);
pub const PR_SET_DUMPABLE = @enumToInt(PR.PR_SET_DUMPABLE);
pub const PR_GET_UNALIGN = @enumToInt(PR.PR_GET_UNALIGN);
pub const PR_SET_UNALIGN = @enumToInt(PR.PR_SET_UNALIGN);
pub const PR_UNALIGN_NOPRINT = 1;
pub const PR_UNALIGN_SIGBUS = 2;
pub const PR_GET_KEEPCAPS = @enumToInt(PR.PR_GET_KEEPCAPS);
pub const PR_SET_KEEPCAPS = @enumToInt(PR.PR_SET_KEEPCAPS);
pub const PR_GET_FPEMU = @enumToInt(PR.PR_GET_FPEMU);
pub const PR_SET_FPEMU = @enumToInt(PR.PR_SET_FPEMU);
pub const PR_FPEMU_NOPRINT = 1;
pub const PR_FPEMU_SIGFPE = 2;
pub const PR_GET_FPEXC = @enumToInt(PR.PR_GET_FPEXC);
pub const PR_SET_FPEXC = @enumToInt(PR.PR_SET_FPEXC);
pub const PR_FP_EXC_SW_ENABLE = 0x80;
pub const PR_FP_EXC_DIV = 0x010000;
pub const PR_FP_EXC_OVF = 0x020000;
pub const PR_FP_EXC_UND = 0x040000;
pub const PR_FP_EXC_RES = 0x080000;
pub const PR_FP_EXC_INV = 0x100000;
pub const PR_FP_EXC_DISABLED = 0;
pub const PR_FP_EXC_NONRECOV = 1;
pub const PR_FP_EXC_ASYNC = 2;
pub const PR_FP_EXC_PRECISE = 3;
pub const PR_GET_TIMING = @enumToInt(PR.PR_GET_TIMING);
pub const PR_SET_TIMING = @enumToInt(PR.PR_SET_TIMING);
pub const PR_TIMING_STATISTICAL = 0;
pub const PR_TIMING_TIMESTAMP = 1;
pub const PR_SET_NAME = @enumToInt(PR.PR_SET_NAME);
pub const PR_GET_NAME = @enumToInt(PR.PR_GET_NAME);
pub const PR_GET_ENDIAN = @enumToInt(PR.PR_GET_ENDIAN);
pub const PR_SET_ENDIAN = @enumToInt(PR.PR_SET_ENDIAN);
pub const PR_ENDIAN_BIG = 0;
pub const PR_ENDIAN_LITTLE = 1;
pub const PR_ENDIAN_PPC_LITTLE = 2;
pub const PR_GET_SECCOMP = @enumToInt(PR.PR_GET_SECCOMP);
pub const PR_SET_SECCOMP = @enumToInt(PR.PR_SET_SECCOMP);
pub const PR_CAPBSET_READ = @enumToInt(PR.PR_CAPBSET_READ);
pub const PR_CAPBSET_DROP = @enumToInt(PR.PR_CAPBSET_DROP);
pub const PR_GET_TSC = @enumToInt(PR.PR_GET_TSC);
pub const PR_SET_TSC = @enumToInt(PR.PR_SET_TSC);
pub const PR_TSC_ENABLE = 1;
pub const PR_TSC_SIGSEGV = 2;
pub const PR_GET_SECUREBITS = @enumToInt(PR.PR_GET_SECUREBITS);
pub const PR_SET_SECUREBITS = @enumToInt(PR.PR_SET_SECUREBITS);
pub const PR_SET_TIMERSLACK = @enumToInt(PR.PR_SET_TIMERSLACK);
pub const PR_GET_TIMERSLACK = @enumToInt(PR.PR_GET_TIMERSLACK);
pub const PR_TASK_PERF_EVENTS_DISABLE = @enumToInt(PR.PR_TASK_PERF_EVENTS_DISABLE);
pub const PR_TASK_PERF_EVENTS_ENABLE = @enumToInt(PR.PR_TASK_PERF_EVENTS_ENABLE);
pub const PR_MCE_KILL = @enumToInt(PR.PR_MCE_KILL);
pub const PR_MCE_KILL_CLEAR = 0;
pub const PR_MCE_KILL_SET = 1;
pub const PR_MCE_KILL_LATE = 0;
pub const PR_MCE_KILL_EARLY = 1;
pub const PR_MCE_KILL_DEFAULT = 2;
pub const PR_MCE_KILL_GET = @enumToInt(PR.PR_MCE_KILL_GET);
pub const PR_SET_MM = @enumToInt(PR.PR_SET_MM);
pub const PR_SET_MM_START_CODE = 1;
pub const PR_SET_MM_END_CODE = 2;
pub const PR_SET_MM_START_DATA = 3;
pub const PR_SET_MM_END_DATA = 4;
pub const PR_SET_MM_START_STACK = 5;
pub const PR_SET_MM_START_BRK = 6;
pub const PR_SET_MM_BRK = 7;
pub const PR_SET_MM_ARG_START = 8;
pub const PR_SET_MM_ARG_END = 9;
pub const PR_SET_MM_ENV_START = 10;
pub const PR_SET_MM_ENV_END = 11;
pub const PR_SET_MM_AUXV = 12;
pub const PR_SET_MM_EXE_FILE = 13;
pub const PR_SET_MM_MAP = 14;
pub const PR_SET_MM_MAP_SIZE = 15;
pub const prctl_mm_map = extern struct {
start_code: u64,
end_code: u64,
start_data: u64,
end_data: u64,
start_brk: u64,
brk: u64,
start_stack: u64,
arg_start: u64,
arg_end: u64,
env_start: u64,
env_end: u64,
auxv: *u64,
auxv_size: u32,
exe_fd: u32,
};
pub const PR_SET_PTRACER = @enumToInt(PR.PR_SET_PTRACER);
pub const PR_SET_PTRACER_ANY = std.math.maxInt(c_ulong);
pub const PR_SET_CHILD_SUBREAPER = @enumToInt(PR.PR_SET_CHILD_SUBREAPER);
pub const PR_GET_CHILD_SUBREAPER = @enumToInt(PR.PR_GET_CHILD_SUBREAPER);
pub const PR_SET_NO_NEW_PRIVS = @enumToInt(PR.PR_SET_NO_NEW_PRIVS);
pub const PR_GET_NO_NEW_PRIVS = @enumToInt(PR.PR_GET_NO_NEW_PRIVS);
pub const PR_GET_TID_ADDRESS = @enumToInt(PR.PR_GET_TID_ADDRESS);
pub const PR_SET_THP_DISABLE = @enumToInt(PR.PR_SET_THP_DISABLE);
pub const PR_GET_THP_DISABLE = @enumToInt(PR.PR_GET_THP_DISABLE);
pub const PR_MPX_ENABLE_MANAGEMENT = @enumToInt(PR.PR_MPX_ENABLE_MANAGEMENT);
pub const PR_MPX_DISABLE_MANAGEMENT = @enumToInt(PR.PR_MPX_DISABLE_MANAGEMENT);
pub const PR_SET_FP_MODE = @enumToInt(PR.PR_SET_FP_MODE);
pub const PR_GET_FP_MODE = @enumToInt(PR.PR_GET_FP_MODE);
pub const PR_FP_MODE_FR = 1 << 0;
pub const PR_FP_MODE_FRE = 1 << 1;
pub const PR_CAP_AMBIENT = @enumToInt(PR.PR_CAP_AMBIENT);
pub const PR_CAP_AMBIENT_IS_SET = 1;
pub const PR_CAP_AMBIENT_RAISE = 2;
pub const PR_CAP_AMBIENT_LOWER = 3;
pub const PR_CAP_AMBIENT_CLEAR_ALL = 4;
pub const PR_SVE_SET_VL = @enumToInt(PR.PR_SVE_SET_VL);
pub const PR_SVE_SET_VL_ONEXEC = 1 << 18;
pub const PR_SVE_GET_VL = @enumToInt(PR.PR_SVE_GET_VL);
pub const PR_SVE_VL_LEN_MASK = 0xffff;
pub const PR_SVE_VL_INHERIT = 1 << 17;
pub const PR_GET_SPECULATION_CTRL = @enumToInt(PR.PR_GET_SPECULATION_CTRL);
pub const PR_SET_SPECULATION_CTRL = @enumToInt(PR.PR_SET_SPECULATION_CTRL);
pub const PR_SPEC_STORE_BYPASS = 0;
pub const PR_SPEC_NOT_AFFECTED = 0;
pub const PR_SPEC_PRCTL = 1 << 0;
pub const PR_SPEC_ENABLE = 1 << 1;
pub const PR_SPEC_DISABLE = 1 << 2;
pub const PR_SPEC_FORCE_DISABLE = 1 << 3; | lib/std/os/bits/linux/prctl.zig |
const std = @import("std");
const c = @cImport({
@cDefine("LIBXML_TREE_ENABLED", {});
@cDefine("LIBXML_SCHEMAS_ENABLED", {});
@cDefine("LIBXML_READER_ENABLED", {});
@cInclude("libxml/xmlreader.h");
});
const Allocator = std.mem.Allocator;
pub const Node = c.xmlNode;
pub const Doc = c.xmlDoc;
pub const readFile = c.xmlReadFile;
pub const readIo = c.xmlReadIO;
pub const cleanupParser = c.xmlCleanupParser;
pub const freeDoc = c.xmlFreeDoc;
pub const docGetRootElement = c.xmlDocGetRootElement;
pub fn getAttribute(node: ?*Node, key: [:0]const u8) ?[]const u8 {
if (c.xmlHasProp(node, key.ptr)) |prop| {
if (@ptrCast(*c.xmlAttr, prop).children) |value_node| {
if (@ptrCast(*Node, value_node).content) |content| {
return std.mem.span(content);
}
}
}
return null;
}
pub fn findNode(node: ?*Node, key: []const u8) ?*Node {
return if (node) |n| blk: {
var it: ?*Node = n;
break :blk while (it != null) : (it = it.?.next) {
if (it.?.type != 1)
continue;
const name = std.mem.span(it.?.name orelse continue);
if (std.mem.eql(u8, key, name))
break it;
} else null;
} else null;
}
pub fn findValueForKey(node: ?*Node, key: []const u8) ?[]const u8 {
return if (findNode(node, key)) |n|
if (@ptrCast(?*Node, n.children)) |child|
if (@ptrCast(?[*:0]const u8, child.content)) |content|
std.mem.span(content)
else
null
else
null
else
null;
}
pub fn parseDescription(allocator: Allocator, node: ?*Node, key: []const u8) !?[]const u8 {
return if (findValueForKey(node, key)) |value|
try allocator.dupe(u8, value)
else
null;
}
pub fn parseIntForKey(comptime T: type, allocator: std.mem.Allocator, node: ?*Node, key: []const u8) !?T {
return if (findValueForKey(node, key)) |str| blk: {
const lower = try std.ascii.allocLowerString(allocator, str);
defer allocator.free(lower);
break :blk if (std.mem.startsWith(u8, lower, "#")) weird_base2: {
for (lower[1..]) |*character| {
if (character.* == 'x') {
character.* = '0';
}
}
break :weird_base2 try std.fmt.parseInt(T, lower[1..], 2);
} else try std.fmt.parseInt(T, lower, 0);
} else null;
}
pub fn parseBoolean(allocator: Allocator, node: ?*Node, key: []const u8) !?bool {
return if (findValueForKey(node, key)) |str| blk: {
const lower = try std.ascii.allocLowerString(allocator, str);
defer allocator.free(lower);
break :blk if (std.mem.eql(u8, "0", lower))
false
else if (std.mem.eql(u8, "1", lower))
true
else if (std.mem.eql(u8, "false", lower))
false
else if (std.mem.eql(u8, "true", lower))
true
else
return error.InvalidBoolean;
} else null;
} | src/xml.zig |
const std = @import("std");
const tga = @import("tga.zig");
test "" {
std.testing.refAllDecls(@This());
std.testing.refAllDecls(Image);
}
/// Image defines a single image with 32-bit, non-alpha-premultiplied RGBA pixel data.
pub const Image = struct {
allocator: std.mem.Allocator,
pixels: []u8,
width: usize,
height: usize,
/// init creates an empty image with the given dimensions.
/// Asserts that width and height are > 0.
pub fn init(allocator: std.mem.Allocator, width: usize, height: usize) !@This() {
std.debug.assert(width > 0);
std.debug.assert(height > 0);
return @This(){
.allocator = allocator,
.width = width,
.height = height,
.pixels = try allocator.alloc(u8, width * height * 4),
};
}
pub fn deinit(self: *const @This()) void {
if (self.pixels.len > 0)
self.allocator.free(self.pixels);
}
/// reinit re-initializes the image to the given size. This discards any existing pixel data.
/// Asserts that width and height are > 0.
pub fn reinit(self: *@This(), width: usize, height: usize) !void {
std.debug.assert(width > 0);
std.debug.assert(height > 0);
self.deinit();
self.width = width;
self.height = height;
self.pixels = try self.allocator.alloc(u8, width * height * 4);
}
/// readData reads image data from the encoded image data.
pub fn readData(allocator: std.mem.Allocator, data: []const u8) !@This() {
var stream = std.io.fixedBufferStream(data);
return readStream(allocator, stream.reader());
}
/// readFilepath reads image data from the given file.
pub fn readFilepath(allocator: std.mem.Allocator, filepath: []const u8) !@This() {
const resolved = try std.fs.path.resolve(allocator, &.{filepath});
defer allocator.free(resolved);
var fd = try std.fs.openFileAbsolute(resolved, .{ .read = true, .write = false });
defer fd.close();
return readStream(allocator, fd.reader());
}
/// readStream reads image data from the given reader.
pub fn readStream(allocator: std.mem.Allocator, reader: anytype) !@This() {
var self = @This(){
.allocator = allocator,
.width = 0,
.height = 0,
.pixels = &.{},
};
try tga.decode(&self, reader);
return self;
}
/// writeFilepath encodes the given image as TGA data and writes it to the given output file.
/// This writes a 24- or 32-bit Truecolor image which is optionally RLE-compressed.
/// The selected bit-depth depends on whether the input image is opaque or not.
pub fn writeFilepath(self: *const Image, filepath: []const u8, compressed: bool) !void {
const resolved = try std.fs.path.resolve(self.allocator, &.{filepath});
defer self.allocator.free(resolved);
var fd = try std.fs.createFileAbsolute(resolved, .{ .read = false, .truncate = true });
defer fd.close();
return self.writeStream(fd.writer(), compressed);
}
/// writeStream encodes the given image as TGA data and writes it to the given output stream.
/// This writes a 24- or 32-bit Truecolor image which is optionally RLE-compressed.
/// The selected bit-depth depends on whether the input image is opaque or not.
pub fn writeStream(self: *const Image, writer: anytype, compressed: bool) !void {
try tga.encode(writer, self, compressed);
}
/// get returns the pixel at the given coordinate.
/// Asserts that the given coordinates are valid.
pub inline fn get(self: *const @This(), x: usize, y: usize) []u8 {
const index = self.offset(x, y);
return self.pixels[index .. index + 4];
}
/// set sets the pixel at the given coordinate to the specified value.
/// Asserts that the given coordinate is valid.
/// Asserts that pixel.len >= 4.
pub inline fn set(self: *const @This(), x: usize, y: usize, pixel: []u8) void {
std.debug.assert(pixel.len >= 4);
std.mem.copy(u8, self.pixels[self.offset(x, y)..], pixel[0..4]);
}
/// offset returns the pixel offset for the given x/y coordinate.
/// Asserts that the given coordinate is valid.
pub inline fn offset(self: *const @This(), x: usize, y: usize) usize {
std.debug.assert(x < self.width);
std.debug.assert(y < self.height);
return y * self.width * 4 + x * 4;
}
/// isOpaque returns true if all pixels have an alpha value of 0xff.
pub fn isOpaque(self: *const @This()) bool {
var i: usize = 3;
while (i < self.pixels.len) : (i += 4) {
if (self.pixels[i] != 0xff)
return false;
}
return true;
}
}; | src/image.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const zua = @import("zua.zig");
const Lexer = @import("lex.zig").Lexer;
const LexErrorContext = zua.lex.LexErrorContext;
const Token = @import("lex.zig").Token;
const Node = @import("ast.zig").Node;
const Tree = @import("ast.zig").Tree;
const AutoComptimeLookup = @import("comptime_lookup.zig").AutoComptimeLookup;
// Notes:
//
// Lua parser always parses into a function (called the 'main' function) which
// is always varargs (the values in the varargs differs depending on Lua version)
//
// Lua parses directly into bytecode with no AST step in between. This implementation
// will generate an AST, though, so it won't be a 1:1 port of the Lua parser.
//
// The functions in Parser are currently named the same as their Lua C
// counterparts, but that will/should probably change.
/// SHRT_MAX, only used when checking the local var vector size
pub const max_local_vars = std.math.maxInt(i16);
/// LUAI_MAXVARS in luaconf.h
pub const max_local_vars_per_func = 200;
/// LUAI_MAXCCALLS in luaconf.h
pub const max_syntax_levels = 200;
/// From llimits.h
pub const max_stack_size = 250;
pub const ParseError = error{
FunctionArgumentsExpected,
ExpectedEqualsOrIn,
ExpectedNameOrVarArg,
UnexpectedSymbol,
SyntaxError,
ExpectedDifferentToken, // error_expected in lparser.c
TooManyLocalVariables,
NoLoopToBreak,
TooManySyntaxLevels,
AmbiguousSyntax,
VarArgOutsideVarArgFunction,
};
/// error -> msg lookup for parse errors
pub const parse_error_strings = AutoComptimeLookup(ParseError, []const u8, .{
.{ ParseError.FunctionArgumentsExpected, "function arguments expected" },
.{ ParseError.ExpectedEqualsOrIn, "'=' or 'in' expected" },
.{ ParseError.ExpectedNameOrVarArg, "<name> or '...' expected" },
.{ ParseError.UnexpectedSymbol, "unexpected symbol" },
.{ ParseError.SyntaxError, "syntax error" },
//.{ ParseError.ExpectedDifferentToken, ... }, this is context-specific
.{ ParseError.TooManyLocalVariables, "too many local variables" },
.{ ParseError.NoLoopToBreak, "no loop to break" },
.{ ParseError.TooManySyntaxLevels, "chunk has too many syntax levels" },
.{ ParseError.AmbiguousSyntax, "ambiguous syntax (function call x new statement)" },
.{ ParseError.VarArgOutsideVarArgFunction, "cannot use '...' outside a vararg function" },
});
// TODO this is duplcated from lex.zig, should be combined in the future
pub const ParseErrorContext = struct {
token: Token,
expected: ?Token = null,
expected_match: ?Token = null,
// TODO this is kinda weird, doesn't seem like it needs to be stored (maybe passed to render instead?)
err: ParseError,
pub fn renderAlloc(self: *ParseErrorContext, allocator: Allocator, parser: *Parser) ![]const u8 {
var buffer = std.ArrayList(u8).init(allocator);
errdefer buffer.deinit();
var msg_buf: [256]u8 = undefined;
const msg = msg: {
if (self.err == ParseError.ExpectedDifferentToken) {
var msg_fbs = std.io.fixedBufferStream(&msg_buf);
const msg_writer = msg_fbs.writer();
msg_writer.print("'{s}' expected", .{self.expected.?.nameForDisplay()}) catch unreachable;
if (self.expected_match != null and self.expected_match.?.line_number != self.token.line_number) {
msg_writer.print(" (to close '{s}' at line {d})", .{
self.expected_match.?.nameForDisplay(),
self.expected_match.?.line_number,
}) catch unreachable;
}
break :msg msg_fbs.getWritten();
} else {
break :msg parse_error_strings.get(self.err).?;
}
};
const error_writer = buffer.writer();
const MAXSRC = 80; // see MAXSRC in llex.c
var chunk_id_buf: [MAXSRC]u8 = undefined;
const chunk_id = zua.object.getChunkId(parser.lexer.chunk_name, &chunk_id_buf);
try error_writer.print("{s}:{d}: {s}", .{ chunk_id, self.token.line_number, msg });
// special case for 1:1 compatibility with Lua's errors
if (!self.token.isChar(0) and self.err != ParseError.TooManySyntaxLevels) {
try error_writer.print(" near '{s}'", .{self.token.nameForErrorDisplay(parser.lexer.buffer)});
}
return buffer.toOwnedSlice();
}
};
pub const Parser = struct {
const Self = @This();
lexer: *Lexer,
error_context: ?ParseErrorContext = null,
/// values that need to be initialized per-parse
state: Parser.State = undefined,
pub const Error = ParseError || Lexer.Error || Allocator.Error;
pub fn init(lexer: *Lexer) Parser {
return Parser{
.lexer = lexer,
};
}
pub const State = struct {
token: Token,
allocator: Allocator,
arena: Allocator,
in_loop: bool = false,
in_vararg_func: bool = true, // main chunk is always vararg
syntax_level: usize = 0,
};
pub fn parse(self: *Self, allocator: Allocator) Error!*Tree {
var arena = std.heap.ArenaAllocator.init(allocator);
errdefer arena.deinit();
self.state = Parser.State{
.token = try self.lexer.next(),
.allocator = allocator,
.arena = arena.allocator(),
};
const parsed_chunk = try self.chunk();
const tree = try self.state.arena.create(Tree);
tree.* = .{
.node = parsed_chunk,
.source = self.lexer.buffer,
.arena = arena.state,
.allocator = allocator,
};
return tree;
}
pub const PossibleLValueExpression = struct {
node: *Node,
can_be_assigned_to: bool = true,
};
/// chunk -> { stat [`;'] }
fn chunk(self: *Self) Error!*Node {
var statements = std.ArrayList(*Node).init(self.state.allocator);
defer statements.deinit();
try self.block(&statements);
try self.check(.eof);
const node = try self.state.arena.create(Node.Chunk);
node.* = .{
.body = try self.state.arena.dupe(*Node, statements.items),
};
return &node.base;
}
fn statement(self: *Self) Error!*Node {
switch (self.state.token.id) {
.keyword_if => return self.ifstat(),
.keyword_local => {
try self.nextToken();
const possible_function_token = self.state.token;
if (try self.testnext(.keyword_function)) {
return self.localfunc(possible_function_token);
} else {
return self.localstat();
}
},
.keyword_return => return self.retstat(),
.keyword_while => return self.whilestat(),
.keyword_do => return self.dostat(),
.keyword_repeat => return self.repeatstat(),
.keyword_break => return self.breakstat(),
.keyword_for => return self.forstat(),
.keyword_function => return self.funcstat(),
else => return self.exprstat(),
}
}
fn block(self: *Self, list: *std.ArrayList(*Node)) Error!void {
try self.enterlevel();
while (!blockFollow(self.state.token)) {
const stat = try self.statement();
try list.append(stat);
_ = try self.testcharnext(';');
const must_be_last_statement = stat.id == .return_statement or stat.id == .break_statement;
if (must_be_last_statement) {
break;
}
}
self.leavelevel();
}
/// parlist -> [ param { `,' param } ]
/// Returns true if vararg was found in the parameter list
fn parlist(self: *Self, list: *std.ArrayList(Token)) Error!bool {
// no params
if (self.state.token.isChar(')')) return false;
var found_vararg = false;
while (true) {
switch (self.state.token.id) {
.name => {},
.ellipsis => {
found_vararg = true;
},
else => return self.reportParseError(ParseError.ExpectedNameOrVarArg),
}
try list.append(self.state.token);
try self.nextToken();
if (found_vararg or !try self.testcharnext(',')) {
break;
}
}
return found_vararg;
}
/// body -> `(' parlist `)' chunk END
fn funcbody(self: *Self, function_token: Token, name: ?*Node, is_local: bool) Error!*Node {
try self.checkcharnext('(');
var params = std.ArrayList(Token).init(self.state.allocator);
defer params.deinit();
const vararg_found = try self.parlist(¶ms);
try self.checkcharnext(')');
var body = std.ArrayList(*Node).init(self.state.allocator);
defer body.deinit();
const in_vararg_func_prev = self.state.in_vararg_func;
self.state.in_vararg_func = vararg_found;
try self.block(&body);
self.state.in_vararg_func = in_vararg_func_prev;
try self.check_match(.keyword_end, function_token);
const node = try self.state.arena.create(Node.FunctionDeclaration);
node.* = .{
.name = name,
.parameters = try self.state.arena.dupe(Token, params.items),
.body = try self.state.arena.dupe(*Node, body.items),
.is_local = is_local,
};
return &node.base;
}
// funcstat -> FUNCTION funcname body
fn funcstat(self: *Self) Error!*Node {
std.debug.assert(self.state.token.id == .keyword_function);
const function_token = self.state.token;
try self.nextToken();
const name = try self.funcname();
return self.funcbody(function_token, name, false);
}
// funcname -> NAME {field} [`:' NAME]
fn funcname(self: *Self) Error!*Node {
const name_token = try self.checkname();
var identifier_node = try self.state.arena.create(Node.Identifier);
identifier_node.* = .{
.token = name_token,
};
var node = &identifier_node.base;
while (self.state.token.isChar('.')) {
const separator = self.state.token;
try self.nextToken(); // skip separator
const field_token = try self.checkname();
var new_node = try self.state.arena.create(Node.FieldAccess);
new_node.* = .{
.prefix = node,
.field = field_token,
.separator = separator,
};
node = &new_node.base;
}
if (self.state.token.isChar(':')) {
const separator = self.state.token;
try self.nextToken();
const field_token = try self.checkname();
var new_node = try self.state.arena.create(Node.FieldAccess);
new_node.* = .{
.prefix = node,
.field = field_token,
.separator = separator,
};
node = &new_node.base;
}
return node;
}
/// stat -> RETURN explist
fn retstat(self: *Self) Error!*Node {
std.debug.assert(self.state.token.id == .keyword_return);
try self.nextToken();
var return_values = std.ArrayList(*Node).init(self.state.allocator);
defer return_values.deinit();
const no_return_values = blockFollow(self.state.token) or (self.state.token.isChar(';'));
if (!no_return_values) {
_ = try self.explist1(&return_values);
}
const node = try self.state.arena.create(Node.ReturnStatement);
node.* = .{
.values = try self.state.arena.dupe(*Node, return_values.items),
};
return &node.base;
}
/// cond -> exp
fn cond(self: *Self) Error!*Node {
return self.expr();
}
/// whilestat -> WHILE cond DO block END
fn whilestat(self: *Self) Error!*Node {
std.debug.assert(self.state.token.id == .keyword_while);
const while_token = self.state.token;
try self.nextToken();
const condition = try self.cond();
try self.checknext(.keyword_do);
var body = std.ArrayList(*Node).init(self.state.allocator);
defer body.deinit();
const in_loop_prev = self.state.in_loop;
self.state.in_loop = true;
try self.block(&body);
self.state.in_loop = in_loop_prev;
try self.check_match(.keyword_end, while_token);
var while_statement = try self.state.arena.create(Node.WhileStatement);
while_statement.* = .{
.condition = condition,
.body = try self.state.arena.dupe(*Node, body.items),
};
return &while_statement.base;
}
fn breakstat(self: *Self) Error!*Node {
std.debug.assert(self.state.token.id == .keyword_break);
const break_token = self.state.token;
try self.nextToken();
if (!self.state.in_loop) {
return self.reportParseError(ParseError.NoLoopToBreak);
}
var break_statement = try self.state.arena.create(Node.BreakStatement);
break_statement.* = .{
.token = break_token,
};
return &break_statement.base;
}
fn dostat(self: *Self) Error!*Node {
std.debug.assert(self.state.token.id == .keyword_do);
const do_token = self.state.token;
try self.nextToken();
var body = std.ArrayList(*Node).init(self.state.allocator);
defer body.deinit();
try self.block(&body);
try self.check_match(.keyword_end, do_token);
const node = try self.state.arena.create(Node.DoStatement);
node.* = .{
.body = try self.state.arena.dupe(*Node, body.items),
};
return &node.base;
}
/// repeatstat -> REPEAT block UNTIL cond
fn repeatstat(self: *Self) Error!*Node {
std.debug.assert(self.state.token.id == .keyword_repeat);
const repeat_token = self.state.token;
try self.nextToken();
var body = std.ArrayList(*Node).init(self.state.allocator);
defer body.deinit();
const in_loop_prev = self.state.in_loop;
self.state.in_loop = true;
try self.block(&body);
self.state.in_loop = in_loop_prev;
try self.check_match(.keyword_until, repeat_token);
const condition = try self.cond();
const node = try self.state.arena.create(Node.RepeatStatement);
node.* = .{
.condition = condition,
.body = try self.state.arena.dupe(*Node, body.items),
};
return &node.base;
}
/// forstat -> FOR (fornum | forlist) END
fn forstat(self: *Self) Error!*Node {
std.debug.assert(self.state.token.id == .keyword_for);
const for_token = self.state.token;
try self.nextToken();
const name_token = try self.checkname();
var for_node: *Node = undefined;
switch (self.state.token.id) {
.single_char => switch (self.state.token.char.?) {
'=' => for_node = try self.fornum(name_token),
',' => for_node = try self.forlist(name_token),
else => return self.reportParseError(ParseError.ExpectedEqualsOrIn),
},
.keyword_in => for_node = try self.forlist(name_token),
else => return self.reportParseError(ParseError.ExpectedEqualsOrIn),
}
try self.check_match(.keyword_end, for_token);
return for_node;
}
/// fornum -> NAME = exp1,exp1[,exp1] forbody
fn fornum(self: *Self, name_token: Token) Error!*Node {
try self.checkcharnext('=');
const start_expression = try self.expr();
try self.checkcharnext(',');
const end_expression = try self.expr();
var increment_expression: ?*Node = null;
if (try self.testcharnext(',')) {
increment_expression = try self.expr();
}
try self.checknext(.keyword_do);
var body = std.ArrayList(*Node).init(self.state.allocator);
defer body.deinit();
const in_loop_prev = self.state.in_loop;
self.state.in_loop = true;
try self.block(&body);
self.state.in_loop = in_loop_prev;
var for_node = try self.state.arena.create(Node.ForStatementNumeric);
for_node.* = .{
.name = name_token,
.start = start_expression,
.end = end_expression,
.increment = increment_expression,
.body = try self.state.arena.dupe(*Node, body.items),
};
return &for_node.base;
}
/// forlist -> NAME {,NAME} IN explist1 forbody
fn forlist(self: *Self, first_name_token: Token) Error!*Node {
var names = try std.ArrayList(Token).initCapacity(self.state.allocator, 1);
defer names.deinit();
names.appendAssumeCapacity(first_name_token);
while (try self.testcharnext(',')) {
const name_token = try self.checkname();
try names.append(name_token);
}
try self.checknext(.keyword_in);
var expressions = std.ArrayList(*Node).init(self.state.allocator);
defer expressions.deinit();
_ = try self.explist1(&expressions);
try self.checknext(.keyword_do);
var body = std.ArrayList(*Node).init(self.state.allocator);
defer body.deinit();
const in_loop_prev = self.state.in_loop;
self.state.in_loop = true;
try self.block(&body);
self.state.in_loop = in_loop_prev;
var for_node = try self.state.arena.create(Node.ForStatementGeneric);
for_node.* = .{
.names = try self.state.arena.dupe(Token, names.items),
.expressions = try self.state.arena.dupe(*Node, expressions.items),
.body = try self.state.arena.dupe(*Node, body.items),
};
return &for_node.base;
}
/// sort of the equivalent of Lua's test_then_block in lparser.c but handles else too
fn ifclause(self: *Self) Error!*Node {
std.debug.assert(self.state.token.id == .keyword_if or self.state.token.id == .keyword_elseif or self.state.token.id == .keyword_else);
const if_token = self.state.token;
var condition: ?*Node = null;
try self.nextToken();
switch (if_token.id) {
.keyword_if, .keyword_elseif => {
condition = try self.cond();
try self.checknext(.keyword_then);
},
.keyword_else => {},
else => unreachable,
}
var body = std.ArrayList(*Node).init(self.state.allocator);
defer body.deinit();
try self.block(&body);
var if_clause = try self.state.arena.create(Node.IfClause);
if_clause.* = .{
.if_token = if_token,
.condition = condition,
.body = try self.state.arena.dupe(*Node, body.items),
};
return &if_clause.base;
}
/// ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END
fn ifstat(self: *Self) Error!*Node {
std.debug.assert(self.state.token.id == .keyword_if);
const if_token = self.state.token;
var clauses = std.ArrayList(*Node).init(self.state.allocator);
defer clauses.deinit();
// if
const if_clause = try self.ifclause();
try clauses.append(if_clause);
// elseif
while (self.state.token.id == .keyword_elseif) {
const elseif_clause = try self.ifclause();
try clauses.append(elseif_clause);
}
// else
if (self.state.token.id == .keyword_else) {
const else_clause = try self.ifclause();
try clauses.append(else_clause);
}
try self.check_match(.keyword_end, if_token);
var if_statement = try self.state.arena.create(Node.IfStatement);
if_statement.* = .{
.clauses = try self.state.arena.dupe(*Node, clauses.items),
};
return &if_statement.base;
}
fn localfunc(self: *Self, function_token: Token) Error!*Node {
const name_token = try self.checkname();
var name = try self.state.arena.create(Node.Identifier);
name.* = .{ .token = name_token };
return self.funcbody(function_token, &name.base, true);
}
/// listfield -> expr
fn listfield(self: *Self) Error!*Node {
var value = try self.expr();
var node = try self.state.arena.create(Node.TableField);
node.* = .{
.key = null,
.value = value,
};
return &node.base;
}
/// recfield -> (NAME | `['exp1`]') = exp1
fn recfield(self: *Self) Error!*Node {
var key: *Node = get_key: {
if (self.state.token.id == .name) {
const name_token = try self.checkname();
// This might be kinda weird, but the name token here is actually used as
// more of a string literal, so create a Literal node instead of Identifier.
// This is a special case.
// TODO revisit this?
var name_node = try self.state.arena.create(Node.Literal);
name_node.* = .{ .token = name_token };
break :get_key &name_node.base;
} else {
std.debug.assert(self.state.token.isChar('['));
try self.nextToken(); // skip the [
const key_expr = try self.expr();
try self.checkcharnext(']');
break :get_key key_expr;
}
};
try self.checkcharnext('=');
const value = try self.expr();
var node = try self.state.arena.create(Node.TableField);
node.* = .{
.key = key,
.value = value,
};
return &node.base;
}
/// constructor -> ??
fn constructor(self: *Self) Error!*Node {
const open_brace_token = self.state.token;
try self.checkcharnext('{');
var fields = std.ArrayList(*Node).init(self.state.allocator);
defer fields.deinit();
while (!self.state.token.isChar('}')) {
var field: *Node = get_field: {
switch (self.state.token.id) {
.name => {
// TODO presumably should catch EOF or errors here and translate them to more appropriate errors
const lookahead_token = self.lexer.lookahead() catch {
break :get_field try self.listfield();
};
if (lookahead_token.isChar('=')) {
break :get_field try self.recfield();
} else {
break :get_field try self.listfield();
}
},
.single_char => switch (self.state.token.char.?) {
'[' => break :get_field try self.recfield(),
else => break :get_field try self.listfield(),
},
else => break :get_field try self.listfield(),
}
};
try fields.append(field);
const has_more = (try self.testcharnext(',')) or (try self.testcharnext(';'));
if (!has_more) break;
}
const close_brace_token = self.state.token;
try self.checkchar_match('}', open_brace_token);
var node = try self.state.arena.create(Node.TableConstructor);
node.* = .{
.fields = try self.state.arena.dupe(*Node, fields.items),
.open_token = open_brace_token,
.close_token = close_brace_token,
};
return &node.base;
}
/// stat -> LOCAL NAME {`,' NAME} [`=' explist1]
fn localstat(self: *Self) Error!*Node {
return try self.assignment(null);
}
/// if first_variable is null, then this is a local assignment
fn assignment(self: *Self, first_variable: ?PossibleLValueExpression) Error!*Node {
const is_local = first_variable == null;
var variables = std.ArrayList(*Node).init(self.state.allocator);
defer variables.deinit();
var values = std.ArrayList(*Node).init(self.state.allocator);
defer values.deinit();
if (is_local) {
while (true) {
const name_token = try self.checkname();
var identifier = try self.state.arena.create(Node.Identifier);
identifier.* = .{ .token = name_token };
try variables.append(&identifier.base);
// TODO this needs work, it doesn't really belong here.
// We need to keep track of *all* local vars in order to function
// like the Lua parser (even local var literals like `self`).
// Might need to be checked at compile-time rather than parse-time.
if (variables.items.len > max_local_vars) {
return self.reportParseError(ParseError.TooManyLocalVariables);
}
if (!try self.testcharnext(',')) break;
}
if (try self.testcharnext('=')) {
_ = try self.explist1(&values);
}
} else {
var variable = first_variable.?;
while (true) {
if (!variable.can_be_assigned_to) {
return self.reportParseError(ParseError.SyntaxError);
}
try variables.append(variable.node);
if (try self.testcharnext(',')) {
variable = try self.primaryexp();
} else {
break;
}
}
try self.checkcharnext('=');
_ = try self.explist1(&values);
}
var local = try self.state.arena.create(Node.AssignmentStatement);
local.* = .{
.variables = try self.state.arena.dupe(*Node, variables.items),
.values = try self.state.arena.dupe(*Node, values.items),
.is_local = is_local,
};
return &local.base;
}
/// stat -> func | assignment
fn exprstat(self: *Self) Error!*Node {
var expression = try self.primaryexp();
if (expression.node.id == .call) {
const call_node = @fieldParentPtr(Node.Call, "base", expression.node);
call_node.is_statement = true;
} else {
// if it's not a call, then it's an assignment
expression.node = try self.assignment(expression);
}
return expression.node;
}
fn explist1(self: *Self, list: *std.ArrayList(*Node)) Error!usize {
var num_expressions: usize = 1;
try list.append(try self.expr());
while (try self.testcharnext(',')) {
try list.append(try self.expr());
}
return num_expressions;
}
/// simpleexp -> NUMBER | STRING | NIL | true | false | ... |
/// constructor | FUNCTION body | primaryexp
fn simpleexp(self: *Self) Error!*Node {
switch (self.state.token.id) {
.string, .number, .keyword_false, .keyword_true, .keyword_nil, .ellipsis => {
if (self.state.token.id == .ellipsis and !self.state.in_vararg_func) {
return self.reportParseError(ParseError.VarArgOutsideVarArgFunction);
}
const node = try self.state.arena.create(Node.Literal);
node.* = .{
.token = self.state.token,
};
try self.nextToken();
return &node.base;
},
.single_char => {
switch (self.state.token.char.?) {
'{' => return self.constructor(),
else => {},
}
},
.keyword_function => {
const function_token = self.state.token;
try self.nextToken(); // skip function
return self.funcbody(function_token, null, false);
},
else => {},
}
const expression = try self.primaryexp();
return expression.node;
}
pub const SubExpr = struct {
node: *Node,
untreated_operator: ?Token,
};
/// subexpr -> (simpleexp | unop subexpr) { binop subexpr }
/// where `binop' is any binary operator with a priority higher than `limit'
fn subexpr(self: *Self, limit: usize) Error!SubExpr {
try self.enterlevel();
var node: *Node = get_node: {
if (isUnaryOperator(self.state.token)) {
const unary_token = self.state.token;
try self.nextToken();
var argument_expr = try self.subexpr(unary_priority);
const unary_node = try self.state.arena.create(Node.UnaryExpression);
unary_node.* = .{
.operator = unary_token,
.argument = argument_expr.node,
};
break :get_node &unary_node.base;
} else {
break :get_node try self.simpleexp();
}
};
var op: ?Token = self.state.token;
while (op != null and isBinaryOperator(op.?)) {
const binary_token = op.?;
const priority = getBinaryPriority(binary_token);
if (priority.left <= limit) break;
try self.nextToken();
var right_expr = try self.subexpr(priority.right);
const new_node = try self.state.arena.create(Node.BinaryExpression);
new_node.* = .{
.operator = binary_token,
.left = node,
.right = right_expr.node,
};
node = &new_node.base;
op = right_expr.untreated_operator;
} else {
op = null;
}
self.leavelevel();
return SubExpr{
.node = node,
.untreated_operator = op,
};
}
fn expr(self: *Self) Error!*Node {
return (try self.subexpr(0)).node;
}
fn primaryexp(self: *Self) Error!PossibleLValueExpression {
var arguments = std.ArrayList(*Node).init(self.state.allocator);
defer arguments.deinit();
var expression = try self.prefixexp();
loop: while (true) {
switch (self.state.token.id) {
.single_char => {
switch (self.state.token.char.?) {
'.' => {
const separator = self.state.token;
try self.nextToken(); // skip the dot
const field_token = try self.checkname();
var new_node = try self.state.arena.create(Node.FieldAccess);
new_node.* = .{
.prefix = expression.node,
.field = field_token,
.separator = separator,
};
expression.node = &new_node.base;
expression.can_be_assigned_to = true;
},
'[' => {
const open_token = self.state.token;
try self.nextToken(); // skip the [
const index = try self.expr();
const close_token = self.state.token;
try self.checkcharnext(']');
var new_node = try self.state.arena.create(Node.IndexAccess);
new_node.* = .{
.prefix = expression.node,
.index = index,
.open_token = open_token,
.close_token = close_token,
};
expression.node = &new_node.base;
expression.can_be_assigned_to = true;
},
':' => {
const separator = self.state.token;
try self.nextToken(); // skip the :
const field_token = try self.checkname();
var new_node = try self.state.arena.create(Node.FieldAccess);
new_node.* = .{
.prefix = expression.node,
.field = field_token,
.separator = separator,
};
expression.node = &new_node.base;
expression.can_be_assigned_to = false;
expression.node = try self.funcargs(expression.node);
},
'(', '{' => {
expression.node = try self.funcargs(expression.node);
expression.can_be_assigned_to = false;
},
else => break :loop,
}
},
.string => {
expression.node = try self.funcargs(expression.node);
expression.can_be_assigned_to = false;
},
else => break :loop,
}
}
return expression;
}
fn funcargs(self: *Self, expression: *Node) Error!*Node {
var arguments = std.ArrayList(*Node).init(self.state.allocator);
defer arguments.deinit();
var open_args_token: ?Token = null;
var close_args_token: ?Token = null;
switch (self.state.token.id) {
.single_char => switch (self.state.token.char.?) {
'(' => {
open_args_token = self.state.token;
const last_token = expression.getLastToken();
if (last_token.line_number != open_args_token.?.line_number) {
return self.reportParseError(ParseError.AmbiguousSyntax);
}
try self.nextToken();
const has_no_arguments = self.state.token.isChar(')');
if (!has_no_arguments) {
_ = try self.explist1(&arguments);
}
close_args_token = self.state.token;
try self.checkchar_match(')', open_args_token.?);
},
'{' => {
const node = try self.constructor();
try arguments.append(node);
},
else => {
return self.reportParseError(ParseError.FunctionArgumentsExpected);
},
},
.string => {
const node = try self.state.arena.create(Node.Literal);
node.* = .{
.token = self.state.token,
};
try arguments.append(&node.base);
try self.nextToken();
},
else => return self.reportParseError(ParseError.FunctionArgumentsExpected),
}
var call = try self.state.arena.create(Node.Call);
call.* = .{
.expression = expression,
.arguments = try self.state.arena.dupe(*Node, arguments.items),
.open_args_token = open_args_token,
.close_args_token = close_args_token,
};
return &call.base;
}
fn prefixexp(self: *Self) Error!PossibleLValueExpression {
switch (self.state.token.id) {
.name => {
const node = try self.state.arena.create(Node.Identifier);
node.* = .{
.token = self.state.token,
};
try self.nextToken();
return PossibleLValueExpression{ .node = &node.base };
},
.single_char => switch (self.state.token.char.?) {
'(' => {
const open_paren_token = self.state.token;
try self.nextToken();
const expression = try self.expr();
const node = try self.state.arena.create(Node.GroupedExpression);
node.* = .{
.open_token = open_paren_token,
.expression = expression,
.close_token = self.state.token,
};
try self.checkchar_match(')', open_paren_token);
return PossibleLValueExpression{
.node = &node.base,
.can_be_assigned_to = false,
};
},
else => {},
},
else => {},
}
return self.reportParseError(ParseError.UnexpectedSymbol);
}
fn nextToken(self: *Self) Lexer.Error!void {
self.state.token = try self.lexer.next();
}
/// Skip to next token if the current token matches the given ID
fn testnext(self: *Self, id: Token.Id) !bool {
if (self.state.token.id == id) {
try self.nextToken();
return true;
}
return false;
}
/// Skip to next token if the current token is a single character token with the given value
fn testcharnext(self: *Self, char: u8) !bool {
if (self.state.token.isChar(char)) {
try self.nextToken();
return true;
}
return false;
}
fn check(self: *Self, expected_id: Token.Id) !void {
if (self.state.token.id != expected_id) {
return self.reportParseErrorExpected(ParseError.ExpectedDifferentToken, Token{
.id = expected_id,
.start = self.state.token.start,
.end = self.state.token.end,
.char = null,
.line_number = self.state.token.line_number,
});
}
}
fn checkchar(self: *Self, expected_char: u8) !void {
if (!self.state.token.isChar(expected_char)) {
return self.reportParseErrorExpected(ParseError.ExpectedDifferentToken, Token{
.id = .single_char,
.start = self.state.token.start,
.end = self.state.token.end,
.char = expected_char,
.line_number = self.state.token.line_number,
});
}
}
fn checknext(self: *Self, expected_id: Token.Id) !void {
try self.check(expected_id);
try self.nextToken();
}
fn checkcharnext(self: *Self, expected_char: u8) !void {
try self.checkchar(expected_char);
try self.nextToken();
}
// TODO eliminate?
/// Returns the name token, since it is typically used when constructing the AST node
fn checkname(self: *Self) !Token {
const token = self.state.token;
try self.checknext(.name);
return token;
}
fn check_match(self: *Self, expected_id: Token.Id, to_close: Token) !void {
if (!try self.testnext(expected_id)) {
return self.reportParseErrorExpectedToMatch(ParseError.ExpectedDifferentToken, Token{
.id = expected_id,
.start = self.state.token.start,
.end = self.state.token.end,
.char = null,
.line_number = self.state.token.line_number,
}, to_close);
}
}
fn checkchar_match(self: *Self, expected_char: u8, to_close: Token) !void {
if (!try self.testcharnext(expected_char)) {
return self.reportParseErrorExpectedToMatch(ParseError.ExpectedDifferentToken, Token{
.id = .single_char,
.start = self.state.token.start,
.end = self.state.token.end,
.char = expected_char,
.line_number = self.state.token.line_number,
}, to_close);
}
}
fn enterlevel(self: *Self) !void {
self.state.syntax_level += 1;
if (self.state.syntax_level > max_syntax_levels) {
return self.reportParseError(ParseError.TooManySyntaxLevels);
}
}
fn leavelevel(self: *Self) void {
std.debug.assert(self.state.syntax_level > 0);
self.state.syntax_level -= 1;
}
fn reportParseError(self: *Self, err: ParseError) ParseError {
return self.reportParseErrorExpectedToMatch(err, null, null);
}
fn reportParseErrorExpected(self: *Self, err: ParseError, expected: ?Token) ParseError {
return self.reportParseErrorExpectedToMatch(err, expected, null);
}
fn reportParseErrorExpectedToMatch(self: *Self, err: ParseError, expected: ?Token, expected_match: ?Token) ParseError {
self.error_context = .{
.token = self.state.token,
.expected = expected,
.expected_match = expected_match,
.err = err,
};
return err;
}
pub fn renderErrorAlloc(self: *Self, allocator: Allocator) ![]const u8 {
if (self.error_context) |*ctx| {
return ctx.renderAlloc(allocator, self);
} else {
return self.lexer.renderErrorAlloc(allocator);
}
}
};
pub const unary_priority = 8;
// TODO: move to Token?
fn blockFollow(token: Token) bool {
return switch (token.id) {
.keyword_else,
.keyword_elseif,
.keyword_end,
.keyword_until,
.eof,
=> true,
else => false,
};
}
// TODO: move to Token?
fn isUnaryOperator(token: Token) bool {
return switch (token.id) {
.keyword_not => true,
.single_char => switch (token.char.?) {
'-', '#' => true,
else => false,
},
else => false,
};
}
// TODO: move to Token?
fn isBinaryOperator(token: Token) bool {
return switch (token.id) {
.concat, .ne, .eq, .le, .ge, .keyword_and, .keyword_or => true,
.single_char => switch (token.char.?) {
'+', '-', '*', '/', '%', '^', '<', '>' => true,
else => false,
},
else => false,
};
}
pub const BinaryPriority = struct {
left: u8,
right: u8,
};
// TODO: move to Token?
fn getBinaryPriority(token: Token) BinaryPriority {
return switch (token.id) {
.single_char => switch (token.char.?) {
'+', '-' => BinaryPriority{ .left = 6, .right = 6 },
'*', '/', '%' => BinaryPriority{ .left = 7, .right = 7 },
'^' => BinaryPriority{ .left = 10, .right = 9 },
'>', '<' => BinaryPriority{ .left = 3, .right = 3 },
else => unreachable,
},
.concat => BinaryPriority{ .left = 5, .right = 4 },
.eq, .ne, .le, .ge => BinaryPriority{ .left = 3, .right = 3 },
.keyword_and => BinaryPriority{ .left = 2, .right = 2 },
.keyword_or => BinaryPriority{ .left = 1, .right = 1 },
else => unreachable,
};
}
test "check hello world ast" {
const allocator = std.testing.allocator;
const source = "print \"hello world\"";
var lexer = Lexer.init(source, source);
var parser = Parser.init(&lexer);
var tree = try parser.parse(allocator);
defer tree.deinit();
try std.testing.expectEqual(Node.Id.chunk, tree.node.id);
const chunk = tree.node.cast(.chunk).?;
try std.testing.expectEqual(@as(usize, 1), chunk.body.len);
try std.testing.expectEqual(Node.Id.call, chunk.body[0].id);
const call = chunk.body[0].cast(.call).?;
try std.testing.expectEqual(Node.Id.identifier, call.expression.id);
try std.testing.expectEqual(@as(usize, 1), call.arguments.len);
try std.testing.expectEqual(Node.Id.literal, call.arguments[0].id);
}
fn testParse(source: []const u8, expected_ast_dump: []const u8) !void {
const allocator = std.testing.allocator;
var lexer = Lexer.init(source, source);
var parser = Parser.init(&lexer);
var tree = try parser.parse(allocator);
defer tree.deinit();
var buf = std.ArrayList(u8).init(allocator);
defer buf.deinit();
try tree.dump(buf.writer());
try std.testing.expectEqualStrings(expected_ast_dump, buf.items);
}
fn expectParseError(expected: ParseError, source: []const u8) !void {
try std.testing.expectError(expected, testParse(source, ""));
}
test "hello world" {
try testParse("print \"hello world\"",
\\chunk
\\ call
\\ identifier
\\ (
\\ literal <string>
\\ )
\\
);
try testParse("print(\"hello world\")",
\\chunk
\\ call
\\ identifier
\\ (
\\ literal <string>
\\ )
\\
);
}
test "function call" {
try testParse("print(123)",
\\chunk
\\ call
\\ identifier
\\ (
\\ literal <number>
\\ )
\\
);
try testParse("print(\"hello\", 'world', nil, true, false, 123)",
\\chunk
\\ call
\\ identifier
\\ (
\\ literal <string>
\\ literal <string>
\\ literal nil
\\ literal true
\\ literal false
\\ literal <number>
\\ )
\\
);
// chained
try testParse("a()()()",
\\chunk
\\ call
\\ call
\\ call
\\ identifier
\\ ()
\\ ()
\\ ()
\\
);
// table constructor
try testParse("a{}",
\\chunk
\\ call
\\ identifier
\\ (
\\ table_constructor
\\ )
\\
);
// long string
try testParse("a[[string]]",
\\chunk
\\ call
\\ identifier
\\ (
\\ literal <string>
\\ )
\\
);
}
test "local statements" {
try testParse("local x, y",
\\chunk
\\ assignment_statement local
\\ identifier
\\ identifier
\\
);
try testParse("local x = nil",
\\chunk
\\ assignment_statement local
\\ identifier
\\ =
\\ literal nil
\\
);
try testParse("local x, y = nil, true",
\\chunk
\\ assignment_statement local
\\ identifier
\\ identifier
\\ =
\\ literal nil
\\ literal true
\\
);
try testParse("local x, y = z",
\\chunk
\\ assignment_statement local
\\ identifier
\\ identifier
\\ =
\\ identifier
\\
);
}
test "field and index access" {
try testParse("z.a = nil",
\\chunk
\\ assignment_statement
\\ field_access .<name>
\\ identifier
\\ =
\\ literal nil
\\
);
try testParse("z.a.b.c = nil",
\\chunk
\\ assignment_statement
\\ field_access .<name>
\\ field_access .<name>
\\ field_access .<name>
\\ identifier
\\ =
\\ literal nil
\\
);
try testParse("z.a['b'].c = nil",
\\chunk
\\ assignment_statement
\\ field_access .<name>
\\ index_access
\\ field_access .<name>
\\ identifier
\\ literal <string>
\\ =
\\ literal nil
\\
);
try testParse("z.a[b.a[1]].c = nil",
\\chunk
\\ assignment_statement
\\ field_access .<name>
\\ index_access
\\ field_access .<name>
\\ identifier
\\ index_access
\\ field_access .<name>
\\ identifier
\\ literal <number>
\\ =
\\ literal nil
\\
);
try testParse("a.b:c 'd'",
\\chunk
\\ call
\\ field_access :<name>
\\ field_access .<name>
\\ identifier
\\ (
\\ literal <string>
\\ )
\\
);
}
test "if statements" {
try testParse("if a then b() end",
\\chunk
\\ if_statement
\\ if_clause if
\\ identifier
\\ then
\\ call
\\ identifier
\\ ()
\\
);
try testParse("if a then elseif b then elseif true then else end",
\\chunk
\\ if_statement
\\ if_clause if
\\ identifier
\\ then
\\ if_clause elseif
\\ identifier
\\ then
\\ if_clause elseif
\\ literal true
\\ then
\\ if_clause else
\\
);
}
test "return statements" {
try testParse("return",
\\chunk
\\ return_statement
\\
);
try testParse("return nil, true, x, 'a', b()",
\\chunk
\\ return_statement
\\ literal nil
\\ literal true
\\ identifier
\\ literal <string>
\\ call
\\ identifier
\\ ()
\\
);
}
test "while statements" {
try testParse("while a do b() end",
\\chunk
\\ while_statement
\\ identifier
\\ do
\\ call
\\ identifier
\\ ()
\\
);
}
test "do statements" {
try testParse("do b() end",
\\chunk
\\ do_statement
\\ call
\\ identifier
\\ ()
\\
);
}
test "repeat statements" {
try testParse("repeat b() until a",
\\chunk
\\ repeat_statement
\\ call
\\ identifier
\\ ()
\\ until
\\ identifier
\\
);
}
test "break statements" {
try testParse("for i=1,2 do break end",
\\chunk
\\ for_statement_numeric
\\ literal <number>
\\ literal <number>
\\ do
\\ break_statement
\\
);
// break just needs to be at the end of its immediate block, so wrapping it in a `do end`
// allows you to put a break statement before the end of another block
try testParse("for i=1,2 do do break end print(\"dead\") end",
\\chunk
\\ for_statement_numeric
\\ literal <number>
\\ literal <number>
\\ do
\\ do_statement
\\ break_statement
\\ call
\\ identifier
\\ (
\\ literal <string>
\\ )
\\
);
// break in loop with nested loop
try testParse(
\\for i=1,2 do
\\ for j=1,2 do
\\ end
\\ break
\\end
,
\\chunk
\\ for_statement_numeric
\\ literal <number>
\\ literal <number>
\\ do
\\ for_statement_numeric
\\ literal <number>
\\ literal <number>
\\ do
\\ break_statement
\\
);
}
test "numeric for statements" {
try testParse("for i=1,2 do end",
\\chunk
\\ for_statement_numeric
\\ literal <number>
\\ literal <number>
\\ do
\\
);
try testParse("for i=1,2,a do b() end",
\\chunk
\\ for_statement_numeric
\\ literal <number>
\\ literal <number>
\\ identifier
\\ do
\\ call
\\ identifier
\\ ()
\\
);
}
test "generic for statements" {
try testParse("for k,v in ipairs(a) do end",
\\chunk
\\ for_statement_generic <name> <name>
\\ in
\\ call
\\ identifier
\\ (
\\ identifier
\\ )
\\ do
\\
);
try testParse("for a in b,c,d,e do f() end",
\\chunk
\\ for_statement_generic <name>
\\ in
\\ identifier
\\ identifier
\\ identifier
\\ identifier
\\ do
\\ call
\\ identifier
\\ ()
\\
);
}
test "function declarations" {
try testParse("function a() end",
\\chunk
\\ function_declaration
\\ identifier
\\ ()
\\
);
try testParse("local function a() end",
\\chunk
\\ function_declaration local
\\ identifier
\\ ()
\\
);
try testParse("function a.b:c() end",
\\chunk
\\ function_declaration
\\ field_access :<name>
\\ field_access .<name>
\\ identifier
\\ ()
\\
);
try testParse("local function a(b, c, ...) end",
\\chunk
\\ function_declaration local
\\ identifier
\\ (<name> <name> ...)
\\
);
try testParse("function a(b, c, ...) end",
\\chunk
\\ function_declaration
\\ identifier
\\ (<name> <name> ...)
\\
);
}
test "anonymous function" {
try testParse("local a = function() end",
\\chunk
\\ assignment_statement local
\\ identifier
\\ =
\\ function_declaration
\\ ()
\\
);
}
test "assignment" {
try testParse("test = nil",
\\chunk
\\ assignment_statement
\\ identifier
\\ =
\\ literal nil
\\
);
try testParse("a, b, c.d, e[f] = nil, true",
\\chunk
\\ assignment_statement
\\ identifier
\\ identifier
\\ field_access .<name>
\\ identifier
\\ index_access
\\ identifier
\\ identifier
\\ =
\\ literal nil
\\ literal true
\\
);
try testParse("(a).b = nil",
\\chunk
\\ assignment_statement
\\ field_access .<name>
\\ grouped_expression
\\ (
\\ identifier
\\ )
\\ =
\\ literal nil
\\
);
try testParse("a().b = nil",
\\chunk
\\ assignment_statement
\\ field_access .<name>
\\ call
\\ identifier
\\ ()
\\ =
\\ literal nil
\\
);
try testParse("a = ...",
\\chunk
\\ assignment_statement
\\ identifier
\\ =
\\ literal ...
\\
);
}
test "assignment errors" {
try expectParseError(ParseError.SyntaxError, "(a) = nil");
try expectParseError(ParseError.UnexpectedSymbol, "(a)() = nil");
try expectParseError(ParseError.FunctionArgumentsExpected, "a:b = nil");
try expectParseError(ParseError.SyntaxError, "(a)");
try expectParseError(ParseError.UnexpectedSymbol, "true = nil");
}
test "table constructors" {
try testParse("a = {}",
\\chunk
\\ assignment_statement
\\ identifier
\\ =
\\ table_constructor
\\
);
try testParse("a = {1;nil,something}",
\\chunk
\\ assignment_statement
\\ identifier
\\ =
\\ table_constructor
\\ table_field
\\ literal <number>
\\ table_field
\\ literal nil
\\ table_field
\\ identifier
\\
);
try testParse("a = {b=true}",
\\chunk
\\ assignment_statement
\\ identifier
\\ =
\\ table_constructor
\\ table_field
\\ literal <name>
\\ =
\\ literal true
\\
);
try testParse("a = {[true]=1}",
\\chunk
\\ assignment_statement
\\ identifier
\\ =
\\ table_constructor
\\ table_field
\\ literal true
\\ =
\\ literal <number>
\\
);
try testParse("a = {[something]=1}",
\\chunk
\\ assignment_statement
\\ identifier
\\ =
\\ table_constructor
\\ table_field
\\ identifier
\\ =
\\ literal <number>
\\
);
try testParse("a = {[\"something\"]=1}",
\\chunk
\\ assignment_statement
\\ identifier
\\ =
\\ table_constructor
\\ table_field
\\ literal <string>
\\ =
\\ literal <number>
\\
);
try testParse("a = {[{}]={},{}}",
\\chunk
\\ assignment_statement
\\ identifier
\\ =
\\ table_constructor
\\ table_field
\\ table_constructor
\\ =
\\ table_constructor
\\ table_field
\\ table_constructor
\\
);
}
test "operators" {
try testParse("a = #b",
\\chunk
\\ assignment_statement
\\ identifier
\\ =
\\ unary_expression #
\\ identifier
\\
);
try testParse("a = ###b",
\\chunk
\\ assignment_statement
\\ identifier
\\ =
\\ unary_expression #
\\ unary_expression #
\\ unary_expression #
\\ identifier
\\
);
try testParse("a = a+i < b/2+1",
\\chunk
\\ assignment_statement
\\ identifier
\\ =
\\ binary_expression <
\\ binary_expression +
\\ identifier
\\ identifier
\\ binary_expression +
\\ binary_expression /
\\ identifier
\\ literal <number>
\\ literal <number>
\\
);
try testParse("a = 5+x^2*8",
\\chunk
\\ assignment_statement
\\ identifier
\\ =
\\ binary_expression +
\\ literal <number>
\\ binary_expression *
\\ binary_expression ^
\\ identifier
\\ literal <number>
\\ literal <number>
\\
);
try testParse("a = a < y and y <= z",
\\chunk
\\ assignment_statement
\\ identifier
\\ =
\\ binary_expression and
\\ binary_expression <
\\ identifier
\\ identifier
\\ binary_expression <=
\\ identifier
\\ identifier
\\
);
try testParse("a = -x^2",
\\chunk
\\ assignment_statement
\\ identifier
\\ =
\\ unary_expression -
\\ binary_expression ^
\\ identifier
\\ literal <number>
\\
);
try testParse("a = x^y^z",
\\chunk
\\ assignment_statement
\\ identifier
\\ =
\\ binary_expression ^
\\ identifier
\\ binary_expression ^
\\ identifier
\\ identifier
\\
);
}
test "errors" {
try expectParseError(ParseError.ExpectedDifferentToken, "untilû");
try expectParseError(ParseError.ExpectedDifferentToken, "until");
// return and break must be the last statement in a block
try expectParseError(ParseError.ExpectedDifferentToken, "return; local a = 1");
try expectParseError(ParseError.ExpectedDifferentToken, "for i=1,2 do break; local a = 1 end");
// break must be in a loop
try expectParseError(ParseError.NoLoopToBreak, "break");
try expectParseError(ParseError.ExpectedDifferentToken,
\\local a = function()
\\
\\
);
try expectParseError(ParseError.ExpectedDifferentToken,
\\(
\\
\\a
\\
);
try expectParseError(ParseError.AmbiguousSyntax, "f\n()");
try expectParseError(ParseError.AmbiguousSyntax, "(\nf\n)\n()");
try expectParseError(ParseError.VarArgOutsideVarArgFunction, "function a() local b = {...} end");
} | src/parse.zig |
const std = @import("std");
pub fn install(step: *std.build.LibExeObjStep, comptime prefix: []const u8) !void {
step.subsystem = .Native;
// step.linkSystemLibrary("glfw");
// step.linkSystemLibrary("GLESv2");
switch (step.target.getOsTag()) {
.linux, .freebsd => {
step.linkLibC();
step.linkSystemLibrary("gtk+-3.0");
},
.windows => {
// There doesn't seem to be a way to link to a .def file so we temporarily put it in the Zig installation folder
const libcommon = step.builder.pathJoin(&.{ std.fs.path.dirname(step.builder.zig_exe).?, "lib", "libc", "mingw", "lib-common", "gdiplus.def" });
defer step.builder.allocator.free(libcommon);
std.fs.accessAbsolute(libcommon, .{}) catch |err| switch (err) {
error.FileNotFound => {
try std.fs.copyFileAbsolute(
step.builder.pathFromRoot(prefix ++ "/src/backends/win32/gdiplus.def"), libcommon, .{});
},
else => {}
};
step.subsystem = .Windows;
step.linkSystemLibrary("comctl32");
step.linkSystemLibrary("gdi32");
step.linkSystemLibrary("gdiplus");
switch (step.target.toTarget().cpu.arch) {
.x86_64 => step.addObjectFile(prefix ++ "/src/backends/win32/res/x86_64.o"),
//.i386 => step.addObjectFile(prefix ++ "/src/backends/win32/res/i386.o"), // currently disabled due to problems with safe SEH
else => {}, // not much of a problem as it'll just lack styling
}
},
.freestanding => {
if (step.target.toTarget().cpu.arch == .wasm32) {
// supported
} else {
return error.UnsupportedOs;
}
},
else => {
// TODO: use the GLES backend as long as the windowing system is supported
// but the UI library isn't
return error.UnsupportedOs;
},
}
const zgt = std.build.Pkg{ .name = "zgt", .path = std.build.FileSource.relative(prefix ++ "/src/main.zig"), .dependencies = &[_]std.build.Pkg{} };
step.addPackage(zgt);
}
pub fn build(b: *std.build.Builder) !void {
const target = b.standardTargetOptions(.{});
const mode = b.standardReleaseOptions();
var examplesDir = try std.fs.cwd().openDir("examples", .{ .iterate = true });
defer examplesDir.close();
const broken = switch (target.getOsTag()) {
.windows => &[_][]const u8{ "fade" },
else => &[_][]const u8{},
};
var walker = try examplesDir.walk(b.allocator);
defer walker.deinit();
while (try walker.next()) |entry| {
if (entry.kind == .File and std.mem.eql(u8, std.fs.path.extension(entry.path), ".zig")) {
const name = try std.mem.replaceOwned(u8, b.allocator, entry.path[0 .. entry.path.len - 4], "/", "-");
defer b.allocator.free(name);
// it is not freed as the path is used later for building
const programPath = b.pathJoin(&.{ "examples", entry.path });
const exe: *std.build.LibExeObjStep = if (target.toTarget().isWasm())
b.addSharedLibrary(name, programPath, .unversioned)
else
b.addExecutable(name, programPath);
exe.setTarget(target);
exe.setBuildMode(mode);
try install(exe, ".");
const install_step = b.addInstallArtifact(exe);
const working = blk: {
for (broken) |broken_name| {
if (std.mem.eql(u8, name, broken_name))
break :blk false;
}
break :blk true;
};
if (working) {
b.getInstallStep().dependOn(&install_step.step);
} else {
std.log.warn("'{s}' is broken (disabled by default)", .{name});
}
if (!target.toTarget().isWasm()) {
const run_cmd = exe.run();
run_cmd.step.dependOn(&exe.install_step.?.step);
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_step = b.step(name, "Run this example");
run_step.dependOn(&run_cmd.step);
}
}
}
const tests = b.addTest("src/main.zig");
tests.setTarget(target);
tests.setBuildMode(mode);
// tests.emit_docs = .emit;
try install(tests, ".");
const test_step = b.step("test", "Run unit tests and also generate the documentation");
test_step.dependOn(&tests.step);
} | build.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const print = std.debug.print;
const input = @embedFile("../in07.txt");
fn find_bag_def(bag: []const u8) []const u8 {
var line_it = std.mem.tokenize(input, "\n");
while (line_it.next()) |line| {
if (std.mem.startsWith(u8, line, bag)) {
return line;
}
}
print("No bag matching '{}' found!", .{bag});
@panic("unknown bag!");
}
fn contains_shiny(bag: []const u8) bool {
//print(" {} -", .{bag});
if (std.mem.eql(u8, bag, "shiny gold")) return true;
if (std.mem.eql(u8, bag, "no other")) return false;
var bag_def_line = find_bag_def(bag);
var eocontains: usize = std.mem.indexOf(u8, bag_def_line, "contain") orelse @panic("uncontaining bag");
eocontains += 8; // length of "contain "
var baglist = bag_def_line[eocontains..];
var bag_it = std.mem.split(baglist, ",");
while (bag_it.next()) |numbags| {
var bag_name = std.mem.trimLeft(u8, numbags, " 1234567890");
var eoname = std.mem.indexOf(u8, bag_name, " bag") orelse @panic("not a bag");
bag_name = bag_name[0..eoname];
if (contains_shiny(bag_name)) return true;
}
return false;
}
fn weight_of(bag: []const u8) usize {
var weight: usize = 0;
if (std.mem.eql(u8, bag, "no other")) return weight;
weight += 1; // self weight
var bag_def_line = find_bag_def(bag);
var eocontains: usize = std.mem.indexOf(u8, bag_def_line, "contain") orelse @panic("uncontaining bag");
eocontains += 8; // length of "contain "
var baglist = bag_def_line[eocontains..];
var bag_it = std.mem.split(baglist, ",");
while (bag_it.next()) |numbags| {
var bag_name = std.mem.trimLeft(u8, numbags, " ");
var eonum = std.mem.indexOf(u8, bag_name, " ") orelse @panic("not a bag");
var num = std.fmt.parseInt(usize, bag_name[0..eonum], 10) catch 0;
if (num == 0) {
//print("couldn't parse {} - got number {}\n", .{ numbags, bag_name[0 .. eonum - 1] });
continue; // "no other bags" fails to barse a number
}
var eoname = std.mem.indexOf(u8, bag_name, " bag") orelse @panic("not a bag");
bag_name = bag_name[eonum + 1 .. eoname];
weight += num * weight_of(bag_name);
}
return weight;
}
pub fn main() !void {
if (false) {
var line_it = std.mem.tokenize(input, "\n");
var count: usize = 0;
while (line_it.next()) |line| {
var word_it = std.mem.split(line, " bag");
if (word_it.next()) |bag| {
//print("{}: Checking {} :", .{ count, bag });
if (contains_shiny(bag)) count += 1;
////print("\n", .{});
}
}
count -= 1; // the shiny gold bag can't hold itself
print("{} bags can be outside a shiny gold one.\n", .{count});
}
{
var weight = weight_of("shiny gold");
weight -= 1; // the shiny gold bag can't hold itself
print("shiny gold bag contains {} bags\n", .{weight});
}
} | src/day07.zig |
const std = @import("std");
const c = @import("../c.zig");
const Global = @import("../global.zig");
const Application = @import("../application/application.zig").Application;
const Config = @import("../application/config.zig");
const System = @import("../system/system.zig").System;
const UIVulkanContext = @import("ui_vulkan.zig").UIVulkanContext;
const vk = @import("../vk.zig");
const DockSpace = @import("dockspace.zig").DockSpace;
const RGPass = @import("../renderer/render_graph/render_graph_pass.zig").RGPass;
const rg = @import("../renderer/render_graph/render_graph.zig");
const RenderGraph = rg.RenderGraph;
pub const paletteValues = [_]c_uint{
c.ImGuiCol_Text,
c.ImGuiCol_TextDisabled,
c.ImGuiCol_WindowBg,
c.ImGuiCol_ChildBg,
c.ImGuiCol_PopupBg,
c.ImGuiCol_Border,
c.ImGuiCol_BorderShadow,
c.ImGuiCol_FrameBg,
c.ImGuiCol_FrameBgHovered,
c.ImGuiCol_FrameBgActive,
c.ImGuiCol_TitleBg,
c.ImGuiCol_TitleBgActive,
c.ImGuiCol_TitleBgCollapsed,
c.ImGuiCol_MenuBarBg,
c.ImGuiCol_ScrollbarBg,
c.ImGuiCol_ScrollbarGrab,
c.ImGuiCol_ScrollbarGrabHovered,
c.ImGuiCol_ScrollbarGrabActive,
c.ImGuiCol_CheckMark,
c.ImGuiCol_SliderGrab,
c.ImGuiCol_SliderGrabActive,
c.ImGuiCol_Button,
c.ImGuiCol_ButtonHovered,
c.ImGuiCol_ButtonActive,
c.ImGuiCol_Header,
c.ImGuiCol_HeaderHovered,
c.ImGuiCol_HeaderActive,
c.ImGuiCol_Separator,
c.ImGuiCol_SeparatorHovered,
c.ImGuiCol_SeparatorActive,
c.ImGuiCol_ResizeGrip,
c.ImGuiCol_ResizeGripHovered,
c.ImGuiCol_ResizeGripActive,
c.ImGuiCol_Tab,
c.ImGuiCol_TabHovered,
c.ImGuiCol_TabActive,
c.ImGuiCol_TabUnfocused,
c.ImGuiCol_TabUnfocusedActive,
c.ImGuiCol_PlotLines,
c.ImGuiCol_PlotLinesHovered,
c.ImGuiCol_PlotHistogram,
c.ImGuiCol_PlotHistogramHovered,
c.ImGuiCol_TableHeaderBg,
c.ImGuiCol_TableBorderStrong,
c.ImGuiCol_TableBorderLight,
c.ImGuiCol_TableRowBg,
c.ImGuiCol_TableRowBgAlt,
c.ImGuiCol_TextSelectedBg,
c.ImGuiCol_DragDropTarget,
c.ImGuiCol_NavHighlight,
c.ImGuiCol_NavWindowingHighlight,
c.ImGuiCol_NavWindowingDimBg,
c.ImGuiCol_ModalWindowDimBg,
};
pub const UI = struct {
app: *Application,
name: []const u8,
imgui_config_path: [:0]const u8,
system: System,
vulkan_context: UIVulkanContext,
dockspace: ?*DockSpace,
render_pass: RGPass,
paletteFn: ?fn (col: c.ImGuiCol_) c.ImVec4 = null,
drawFn: fn (ui: *UI) void,
context: *c.ImGuiContext,
pub fn init(self: *UI, comptime name: []const u8, allocator: std.mem.Allocator) void {
self.dockspace = null;
self.name = name;
self.system = System.create(name ++ " System", systemInit, systemDeinit, systemUpdate);
self.render_pass.init("UI Render Pass", allocator, renderPassInit, renderPassDeinit, renderPassRender);
self.render_pass.pipeline_start = .{ .fragment_shader_bit = true };
self.render_pass.pipeline_end = .{ .transfer_bit = true };
}
fn initPalette(self: *UI) void {
if (self.paletteFn == null)
return;
var style: *c.ImGuiStyle = c.igGetStyle();
for (paletteValues) |p|
style.Colors[@intCast(usize, p)] = self.paletteFn.?(p);
}
fn initScaling(app: *Application) void {
var width: c_int = undefined;
var height: c_int = undefined;
c.glfwGetWindowSize(app.window, &width, &height);
var io: *c.ImGuiIO = c.igGetIO() orelse unreachable;
io.DisplaySize = .{ .x = @intToFloat(f32, width), .y = @intToFloat(f32, height) };
io.DisplayFramebufferScale = .{ .x = 1.0, .y = 1.0 };
var scale: [2]f32 = undefined;
c.glfwGetWindowContentScale(app.window, &scale[0], &scale[1]);
var style: *c.ImGuiStyle = c.igGetStyle();
c.ImGuiStyle_ScaleAllSizes(style, scale[1]);
}
fn renderPassInit(render_pass: *RGPass) void {
const self: *UI = @fieldParentPtr(UI, "render_pass", render_pass);
self.render_pass.appendWriteResource(&rg.global_render_graph.final_swapchain.rg_resource);
}
fn renderPassDeinit(render_pass: *RGPass) void {
const self: *UI = @fieldParentPtr(UI, "render_pass", render_pass);
self.render_pass.removeWriteResource(&rg.global_render_graph.final_swapchain.rg_resource);
}
fn renderPassRender(render_pass: *RGPass, command_buffer: vk.CommandBuffer, image_index: u32) void {
const self: *UI = @fieldParentPtr(UI, "render_pass", render_pass);
self.vulkan_context.render(command_buffer, image_index);
}
fn systemInit(system: *System, app: *Application) void {
const self: *UI = @fieldParentPtr(UI, "system", system);
self.app = app;
const temp_path = Global.config.getValidConfigPath("imgui.ini") catch unreachable;
self.imgui_config_path = Global.config.allocator.dupeZ(u8, temp_path) catch unreachable;
Global.config.allocator.free(temp_path);
self.context = c.igCreateContext(null);
self.vulkan_context.init(self);
var io: *c.ImGuiIO = c.igGetIO();
io.ConfigFlags |= c.ImGuiConfigFlags_DockingEnable;
io.IniFilename = self.imgui_config_path.ptr;
self.initPalette();
initScaling(app);
}
fn systemDeinit(system: *System) void {
const self: *UI = @fieldParentPtr(UI, "system", system);
c.igDestroyContext(self.context);
self.vulkan_context.deinit();
Global.config.allocator.free(self.imgui_config_path);
}
fn systemUpdate(system: *System, elapsed_time: f64) void {
_ = elapsed_time;
const self: *UI = @fieldParentPtr(UI, "system", system);
self.checkFramebufferResized();
c.igNewFrame();
if (self.dockspace) |d|
d.drawBegin();
self.drawFn(self);
if (self.dockspace) |d|
d.drawEnd();
c.igRender();
c.igEndFrame();
}
fn checkFramebufferResized(self: *UI) void {
if (!self.app.framebuffer_resized)
return;
var width: c_int = undefined;
var height: c_int = undefined;
c.glfwGetWindowSize(self.app.window, &width, &height);
var io: *c.ImGuiIO = c.igGetIO() orelse unreachable;
io.DisplaySize = .{ .x = @intToFloat(f32, width), .y = @intToFloat(f32, height) };
io.DisplayFramebufferScale = .{ .x = 1.0, .y = 1.0 };
}
}; | src/ui/ui.zig |
pub const PROPSETFLAG_DEFAULT = @as(u32, 0);
pub const PROPSETFLAG_NONSIMPLE = @as(u32, 1);
pub const PROPSETFLAG_ANSI = @as(u32, 2);
pub const PROPSETFLAG_UNBUFFERED = @as(u32, 4);
pub const PROPSETFLAG_CASE_SENSITIVE = @as(u32, 8);
pub const PROPSET_BEHAVIOR_CASE_SENSITIVE = @as(u32, 1);
pub const PID_DICTIONARY = @as(u32, 0);
pub const PID_CODEPAGE = @as(u32, 1);
pub const PID_FIRST_USABLE = @as(u32, 2);
pub const PID_FIRST_NAME_DEFAULT = @as(u32, 4095);
pub const PID_LOCALE = @as(u32, 2147483648);
pub const PID_MODIFY_TIME = @as(u32, 2147483649);
pub const PID_SECURITY = @as(u32, 2147483650);
pub const PID_BEHAVIOR = @as(u32, 2147483651);
pub const PID_ILLEGAL = @as(u32, 4294967295);
pub const PID_MIN_READONLY = @as(u32, 2147483648);
pub const PID_MAX_READONLY = @as(u32, 3221225471);
pub const PRSPEC_INVALID = @as(u32, 4294967295);
pub const PROPSETHDR_OSVERSION_UNKNOWN = @as(u32, 4294967295);
pub const PIDDI_THUMBNAIL = @as(i32, 2);
pub const PIDSI_TITLE = @as(i32, 2);
pub const PIDSI_SUBJECT = @as(i32, 3);
pub const PIDSI_AUTHOR = @as(i32, 4);
pub const PIDSI_KEYWORDS = @as(i32, 5);
pub const PIDSI_COMMENTS = @as(i32, 6);
pub const PIDSI_TEMPLATE = @as(i32, 7);
pub const PIDSI_LASTAUTHOR = @as(i32, 8);
pub const PIDSI_REVNUMBER = @as(i32, 9);
pub const PIDSI_EDITTIME = @as(i32, 10);
pub const PIDSI_LASTPRINTED = @as(i32, 11);
pub const PIDSI_CREATE_DTM = @as(i32, 12);
pub const PIDSI_LASTSAVE_DTM = @as(i32, 13);
pub const PIDSI_PAGECOUNT = @as(i32, 14);
pub const PIDSI_WORDCOUNT = @as(i32, 15);
pub const PIDSI_CHARCOUNT = @as(i32, 16);
pub const PIDSI_THUMBNAIL = @as(i32, 17);
pub const PIDSI_APPNAME = @as(i32, 18);
pub const PIDSI_DOC_SECURITY = @as(i32, 19);
pub const PIDDSI_CATEGORY = @as(u32, 2);
pub const PIDDSI_PRESFORMAT = @as(u32, 3);
pub const PIDDSI_BYTECOUNT = @as(u32, 4);
pub const PIDDSI_LINECOUNT = @as(u32, 5);
pub const PIDDSI_PARCOUNT = @as(u32, 6);
pub const PIDDSI_SLIDECOUNT = @as(u32, 7);
pub const PIDDSI_NOTECOUNT = @as(u32, 8);
pub const PIDDSI_HIDDENCOUNT = @as(u32, 9);
pub const PIDDSI_MMCLIPCOUNT = @as(u32, 10);
pub const PIDDSI_SCALE = @as(u32, 11);
pub const PIDDSI_HEADINGPAIR = @as(u32, 12);
pub const PIDDSI_DOCPARTS = @as(u32, 13);
pub const PIDDSI_MANAGER = @as(u32, 14);
pub const PIDDSI_COMPANY = @as(u32, 15);
pub const PIDDSI_LINKSDIRTY = @as(u32, 16);
pub const PIDMSI_EDITOR = @as(i32, 2);
pub const PIDMSI_SUPPLIER = @as(i32, 3);
pub const PIDMSI_SOURCE = @as(i32, 4);
pub const PIDMSI_SEQUENCE_NO = @as(i32, 5);
pub const PIDMSI_PROJECT = @as(i32, 6);
pub const PIDMSI_STATUS = @as(i32, 7);
pub const PIDMSI_OWNER = @as(i32, 8);
pub const PIDMSI_RATING = @as(i32, 9);
pub const PIDMSI_PRODUCTION = @as(i32, 10);
pub const PIDMSI_COPYRIGHT = @as(i32, 11);
pub const CWCSTORAGENAME = @as(u32, 32);
pub const STGM_DIRECT = @as(i32, 0);
pub const STGM_TRANSACTED = @as(i32, 65536);
pub const STGM_SIMPLE = @as(i32, 134217728);
pub const STGM_READ = @as(i32, 0);
pub const STGM_WRITE = @as(i32, 1);
pub const STGM_READWRITE = @as(i32, 2);
pub const STGM_SHARE_DENY_NONE = @as(i32, 64);
pub const STGM_SHARE_DENY_READ = @as(i32, 48);
pub const STGM_SHARE_DENY_WRITE = @as(i32, 32);
pub const STGM_SHARE_EXCLUSIVE = @as(i32, 16);
pub const STGM_PRIORITY = @as(i32, 262144);
pub const STGM_DELETEONRELEASE = @as(i32, 67108864);
pub const STGM_NOSCRATCH = @as(i32, 1048576);
pub const STGM_CREATE = @as(i32, 4096);
pub const STGM_CONVERT = @as(i32, 131072);
pub const STGM_FAILIFTHERE = @as(i32, 0);
pub const STGM_NOSNAPSHOT = @as(i32, 2097152);
pub const STGM_DIRECT_SWMR = @as(i32, 4194304);
pub const STGFMT_STORAGE = @as(u32, 0);
pub const STGFMT_NATIVE = @as(u32, 1);
pub const STGFMT_FILE = @as(u32, 3);
pub const STGFMT_ANY = @as(u32, 4);
pub const STGFMT_DOCFILE = @as(u32, 5);
pub const STGFMT_DOCUMENT = @as(u32, 0);
pub const STGOPTIONS_VERSION = @as(u32, 1);
pub const CCH_MAX_PROPSTG_NAME = @as(u32, 31);
//--------------------------------------------------------------------------------
// Section: Types (56)
//--------------------------------------------------------------------------------
pub const PROPSPEC_KIND = enum(u32) {
LPWSTR = 0,
PROPID = 1,
};
pub const PRSPEC_LPWSTR = PROPSPEC_KIND.LPWSTR;
pub const PRSPEC_PROPID = PROPSPEC_KIND.PROPID;
pub const STGC = enum(i32) {
DEFAULT = 0,
OVERWRITE = 1,
ONLYIFCURRENT = 2,
DANGEROUSLYCOMMITMERELYTODISKCACHE = 4,
CONSOLIDATE = 8,
};
pub const STGC_DEFAULT = STGC.DEFAULT;
pub const STGC_OVERWRITE = STGC.OVERWRITE;
pub const STGC_ONLYIFCURRENT = STGC.ONLYIFCURRENT;
pub const STGC_DANGEROUSLYCOMMITMERELYTODISKCACHE = STGC.DANGEROUSLYCOMMITMERELYTODISKCACHE;
pub const STGC_CONSOLIDATE = STGC.CONSOLIDATE;
pub const STGMOVE = enum(i32) {
MOVE = 0,
COPY = 1,
SHALLOWCOPY = 2,
};
pub const STGMOVE_MOVE = STGMOVE.MOVE;
pub const STGMOVE_COPY = STGMOVE.COPY;
pub const STGMOVE_SHALLOWCOPY = STGMOVE.SHALLOWCOPY;
pub const STATFLAG = enum(i32) {
DEFAULT = 0,
NONAME = 1,
NOOPEN = 2,
};
pub const STATFLAG_DEFAULT = STATFLAG.DEFAULT;
pub const STATFLAG_NONAME = STATFLAG.NONAME;
pub const STATFLAG_NOOPEN = STATFLAG.NOOPEN;
pub const BSTRBLOB = extern struct {
cbSize: u32,
pData: ?*u8,
};
pub const CLIPDATA = extern struct {
cbSize: u32,
ulClipFmt: i32,
pClipData: ?*u8,
};
pub const LOCKTYPE = enum(i32) {
WRITE = 1,
EXCLUSIVE = 2,
ONLYONCE = 4,
};
pub const LOCK_WRITE = LOCKTYPE.WRITE;
pub const LOCK_EXCLUSIVE = LOCKTYPE.EXCLUSIVE;
pub const LOCK_ONLYONCE = LOCKTYPE.ONLYONCE;
// TODO: this type is limited to platform 'windows5.0'
const IID_IEnumSTATSTG_Value = Guid.initString("0000000d-0000-0000-c000-000000000046");
pub const IID_IEnumSTATSTG = &IID_IEnumSTATSTG_Value;
pub const IEnumSTATSTG = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Next: fn(
self: *const IEnumSTATSTG,
celt: u32,
rgelt: [*]STATSTG,
pceltFetched: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Skip: fn(
self: *const IEnumSTATSTG,
celt: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reset: fn(
self: *const IEnumSTATSTG,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clone: fn(
self: *const IEnumSTATSTG,
ppenum: ?*?*IEnumSTATSTG,
) 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 IEnumSTATSTG_Next(self: *const T, celt: u32, rgelt: [*]STATSTG, pceltFetched: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumSTATSTG.VTable, self.vtable).Next(@ptrCast(*const IEnumSTATSTG, self), celt, rgelt, pceltFetched);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumSTATSTG_Skip(self: *const T, celt: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumSTATSTG.VTable, self.vtable).Skip(@ptrCast(*const IEnumSTATSTG, self), celt);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumSTATSTG_Reset(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumSTATSTG.VTable, self.vtable).Reset(@ptrCast(*const IEnumSTATSTG, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumSTATSTG_Clone(self: *const T, ppenum: ?*?*IEnumSTATSTG) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumSTATSTG.VTable, self.vtable).Clone(@ptrCast(*const IEnumSTATSTG, self), ppenum);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const RemSNB = extern struct {
ulCntStr: u32,
ulCntChar: u32,
rgString: [1]u16,
};
// TODO: this type is limited to platform 'windows5.0'
const IID_IStorage_Value = Guid.initString("0000000b-0000-0000-c000-000000000046");
pub const IID_IStorage = &IID_IStorage_Value;
pub const IStorage = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
CreateStream: fn(
self: *const IStorage,
pwcsName: ?[*:0]const u16,
grfMode: u32,
reserved1: u32,
reserved2: u32,
ppstm: ?*?*IStream,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
OpenStream: fn(
self: *const IStorage,
pwcsName: ?[*:0]const u16,
reserved1: ?*anyopaque,
grfMode: u32,
reserved2: u32,
ppstm: ?*?*IStream,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateStorage: fn(
self: *const IStorage,
pwcsName: ?[*:0]const u16,
grfMode: u32,
reserved1: u32,
reserved2: u32,
ppstg: ?*?*IStorage,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
OpenStorage: fn(
self: *const IStorage,
pwcsName: ?[*:0]const u16,
pstgPriority: ?*IStorage,
grfMode: u32,
snbExclude: ?*?*u16,
reserved: u32,
ppstg: ?*?*IStorage,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CopyTo: fn(
self: *const IStorage,
ciidExclude: u32,
rgiidExclude: ?[*]const Guid,
snbExclude: ?*?*u16,
pstgDest: ?*IStorage,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MoveElementTo: fn(
self: *const IStorage,
pwcsName: ?[*:0]const u16,
pstgDest: ?*IStorage,
pwcsNewName: ?[*:0]const u16,
grfFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Commit: fn(
self: *const IStorage,
grfCommitFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Revert: fn(
self: *const IStorage,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EnumElements: fn(
self: *const IStorage,
reserved1: u32,
reserved2: ?*anyopaque,
reserved3: u32,
ppenum: ?*?*IEnumSTATSTG,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DestroyElement: fn(
self: *const IStorage,
pwcsName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RenameElement: fn(
self: *const IStorage,
pwcsOldName: ?[*:0]const u16,
pwcsNewName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetElementTimes: fn(
self: *const IStorage,
pwcsName: ?[*:0]const u16,
pctime: ?*const FILETIME,
patime: ?*const FILETIME,
pmtime: ?*const FILETIME,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetClass: fn(
self: *const IStorage,
clsid: ?*const Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetStateBits: fn(
self: *const IStorage,
grfStateBits: u32,
grfMask: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Stat: fn(
self: *const IStorage,
pstatstg: ?*STATSTG,
grfStatFlag: 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 IStorage_CreateStream(self: *const T, pwcsName: ?[*:0]const u16, grfMode: u32, reserved1: u32, reserved2: u32, ppstm: ?*?*IStream) callconv(.Inline) HRESULT {
return @ptrCast(*const IStorage.VTable, self.vtable).CreateStream(@ptrCast(*const IStorage, self), pwcsName, grfMode, reserved1, reserved2, ppstm);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IStorage_OpenStream(self: *const T, pwcsName: ?[*:0]const u16, reserved1: ?*anyopaque, grfMode: u32, reserved2: u32, ppstm: ?*?*IStream) callconv(.Inline) HRESULT {
return @ptrCast(*const IStorage.VTable, self.vtable).OpenStream(@ptrCast(*const IStorage, self), pwcsName, reserved1, grfMode, reserved2, ppstm);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IStorage_CreateStorage(self: *const T, pwcsName: ?[*:0]const u16, grfMode: u32, reserved1: u32, reserved2: u32, ppstg: ?*?*IStorage) callconv(.Inline) HRESULT {
return @ptrCast(*const IStorage.VTable, self.vtable).CreateStorage(@ptrCast(*const IStorage, self), pwcsName, grfMode, reserved1, reserved2, ppstg);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IStorage_OpenStorage(self: *const T, pwcsName: ?[*:0]const u16, pstgPriority: ?*IStorage, grfMode: u32, snbExclude: ?*?*u16, reserved: u32, ppstg: ?*?*IStorage) callconv(.Inline) HRESULT {
return @ptrCast(*const IStorage.VTable, self.vtable).OpenStorage(@ptrCast(*const IStorage, self), pwcsName, pstgPriority, grfMode, snbExclude, reserved, ppstg);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IStorage_CopyTo(self: *const T, ciidExclude: u32, rgiidExclude: ?[*]const Guid, snbExclude: ?*?*u16, pstgDest: ?*IStorage) callconv(.Inline) HRESULT {
return @ptrCast(*const IStorage.VTable, self.vtable).CopyTo(@ptrCast(*const IStorage, self), ciidExclude, rgiidExclude, snbExclude, pstgDest);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IStorage_MoveElementTo(self: *const T, pwcsName: ?[*:0]const u16, pstgDest: ?*IStorage, pwcsNewName: ?[*:0]const u16, grfFlags: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IStorage.VTable, self.vtable).MoveElementTo(@ptrCast(*const IStorage, self), pwcsName, pstgDest, pwcsNewName, grfFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IStorage_Commit(self: *const T, grfCommitFlags: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IStorage.VTable, self.vtable).Commit(@ptrCast(*const IStorage, self), grfCommitFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IStorage_Revert(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IStorage.VTable, self.vtable).Revert(@ptrCast(*const IStorage, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IStorage_EnumElements(self: *const T, reserved1: u32, reserved2: ?*anyopaque, reserved3: u32, ppenum: ?*?*IEnumSTATSTG) callconv(.Inline) HRESULT {
return @ptrCast(*const IStorage.VTable, self.vtable).EnumElements(@ptrCast(*const IStorage, self), reserved1, reserved2, reserved3, ppenum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IStorage_DestroyElement(self: *const T, pwcsName: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IStorage.VTable, self.vtable).DestroyElement(@ptrCast(*const IStorage, self), pwcsName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IStorage_RenameElement(self: *const T, pwcsOldName: ?[*:0]const u16, pwcsNewName: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IStorage.VTable, self.vtable).RenameElement(@ptrCast(*const IStorage, self), pwcsOldName, pwcsNewName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IStorage_SetElementTimes(self: *const T, pwcsName: ?[*:0]const u16, pctime: ?*const FILETIME, patime: ?*const FILETIME, pmtime: ?*const FILETIME) callconv(.Inline) HRESULT {
return @ptrCast(*const IStorage.VTable, self.vtable).SetElementTimes(@ptrCast(*const IStorage, self), pwcsName, pctime, patime, pmtime);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IStorage_SetClass(self: *const T, clsid: ?*const Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const IStorage.VTable, self.vtable).SetClass(@ptrCast(*const IStorage, self), clsid);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IStorage_SetStateBits(self: *const T, grfStateBits: u32, grfMask: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IStorage.VTable, self.vtable).SetStateBits(@ptrCast(*const IStorage, self), grfStateBits, grfMask);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IStorage_Stat(self: *const T, pstatstg: ?*STATSTG, grfStatFlag: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IStorage.VTable, self.vtable).Stat(@ptrCast(*const IStorage, self), pstatstg, grfStatFlag);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.0'
const IID_IPersistStorage_Value = Guid.initString("0000010a-0000-0000-c000-000000000046");
pub const IID_IPersistStorage = &IID_IPersistStorage_Value;
pub const IPersistStorage = extern struct {
pub const VTable = extern struct {
base: IPersist.VTable,
IsDirty: fn(
self: *const IPersistStorage,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
InitNew: fn(
self: *const IPersistStorage,
pStg: ?*IStorage,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Load: fn(
self: *const IPersistStorage,
pStg: ?*IStorage,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Save: fn(
self: *const IPersistStorage,
pStgSave: ?*IStorage,
fSameAsLoad: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SaveCompleted: fn(
self: *const IPersistStorage,
pStgNew: ?*IStorage,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
HandsOffStorage: fn(
self: *const IPersistStorage,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IPersist.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPersistStorage_IsDirty(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IPersistStorage.VTable, self.vtable).IsDirty(@ptrCast(*const IPersistStorage, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPersistStorage_InitNew(self: *const T, pStg: ?*IStorage) callconv(.Inline) HRESULT {
return @ptrCast(*const IPersistStorage.VTable, self.vtable).InitNew(@ptrCast(*const IPersistStorage, self), pStg);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPersistStorage_Load(self: *const T, pStg: ?*IStorage) callconv(.Inline) HRESULT {
return @ptrCast(*const IPersistStorage.VTable, self.vtable).Load(@ptrCast(*const IPersistStorage, self), pStg);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPersistStorage_Save(self: *const T, pStgSave: ?*IStorage, fSameAsLoad: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IPersistStorage.VTable, self.vtable).Save(@ptrCast(*const IPersistStorage, self), pStgSave, fSameAsLoad);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPersistStorage_SaveCompleted(self: *const T, pStgNew: ?*IStorage) callconv(.Inline) HRESULT {
return @ptrCast(*const IPersistStorage.VTable, self.vtable).SaveCompleted(@ptrCast(*const IPersistStorage, self), pStgNew);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPersistStorage_HandsOffStorage(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IPersistStorage.VTable, self.vtable).HandsOffStorage(@ptrCast(*const IPersistStorage, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.0'
const IID_ILockBytes_Value = Guid.initString("0000000a-0000-0000-c000-000000000046");
pub const IID_ILockBytes = &IID_ILockBytes_Value;
pub const ILockBytes = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
ReadAt: fn(
self: *const ILockBytes,
ulOffset: ULARGE_INTEGER,
// TODO: what to do with BytesParamIndex 2?
pv: ?*anyopaque,
cb: u32,
pcbRead: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteAt: fn(
self: *const ILockBytes,
ulOffset: ULARGE_INTEGER,
// TODO: what to do with BytesParamIndex 2?
pv: ?*const anyopaque,
cb: u32,
pcbWritten: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Flush: fn(
self: *const ILockBytes,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetSize: fn(
self: *const ILockBytes,
cb: ULARGE_INTEGER,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
LockRegion: fn(
self: *const ILockBytes,
libOffset: ULARGE_INTEGER,
cb: ULARGE_INTEGER,
dwLockType: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UnlockRegion: fn(
self: *const ILockBytes,
libOffset: ULARGE_INTEGER,
cb: ULARGE_INTEGER,
dwLockType: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Stat: fn(
self: *const ILockBytes,
pstatstg: ?*STATSTG,
grfStatFlag: 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 ILockBytes_ReadAt(self: *const T, ulOffset: ULARGE_INTEGER, pv: ?*anyopaque, cb: u32, pcbRead: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ILockBytes.VTable, self.vtable).ReadAt(@ptrCast(*const ILockBytes, self), ulOffset, pv, cb, pcbRead);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ILockBytes_WriteAt(self: *const T, ulOffset: ULARGE_INTEGER, pv: ?*const anyopaque, cb: u32, pcbWritten: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ILockBytes.VTable, self.vtable).WriteAt(@ptrCast(*const ILockBytes, self), ulOffset, pv, cb, pcbWritten);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ILockBytes_Flush(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ILockBytes.VTable, self.vtable).Flush(@ptrCast(*const ILockBytes, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ILockBytes_SetSize(self: *const T, cb: ULARGE_INTEGER) callconv(.Inline) HRESULT {
return @ptrCast(*const ILockBytes.VTable, self.vtable).SetSize(@ptrCast(*const ILockBytes, self), cb);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ILockBytes_LockRegion(self: *const T, libOffset: ULARGE_INTEGER, cb: ULARGE_INTEGER, dwLockType: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ILockBytes.VTable, self.vtable).LockRegion(@ptrCast(*const ILockBytes, self), libOffset, cb, dwLockType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ILockBytes_UnlockRegion(self: *const T, libOffset: ULARGE_INTEGER, cb: ULARGE_INTEGER, dwLockType: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ILockBytes.VTable, self.vtable).UnlockRegion(@ptrCast(*const ILockBytes, self), libOffset, cb, dwLockType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ILockBytes_Stat(self: *const T, pstatstg: ?*STATSTG, grfStatFlag: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ILockBytes.VTable, self.vtable).Stat(@ptrCast(*const ILockBytes, self), pstatstg, grfStatFlag);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.0'
const IID_IRootStorage_Value = Guid.initString("00000012-0000-0000-c000-000000000046");
pub const IID_IRootStorage = &IID_IRootStorage_Value;
pub const IRootStorage = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SwitchToFile: fn(
self: *const IRootStorage,
pszFile: ?PWSTR,
) 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 IRootStorage_SwitchToFile(self: *const T, pszFile: ?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRootStorage.VTable, self.vtable).SwitchToFile(@ptrCast(*const IRootStorage, self), pszFile);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.0'
const IID_IFillLockBytes_Value = Guid.initString("99caf010-415e-11cf-8814-00aa00b569f5");
pub const IID_IFillLockBytes = &IID_IFillLockBytes_Value;
pub const IFillLockBytes = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
FillAppend: fn(
self: *const IFillLockBytes,
// TODO: what to do with BytesParamIndex 1?
pv: ?*const anyopaque,
cb: u32,
pcbWritten: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FillAt: fn(
self: *const IFillLockBytes,
ulOffset: ULARGE_INTEGER,
// TODO: what to do with BytesParamIndex 2?
pv: ?*const anyopaque,
cb: u32,
pcbWritten: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetFillSize: fn(
self: *const IFillLockBytes,
ulSize: ULARGE_INTEGER,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Terminate: fn(
self: *const IFillLockBytes,
bCanceled: 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 IFillLockBytes_FillAppend(self: *const T, pv: ?*const anyopaque, cb: u32, pcbWritten: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IFillLockBytes.VTable, self.vtable).FillAppend(@ptrCast(*const IFillLockBytes, self), pv, cb, pcbWritten);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFillLockBytes_FillAt(self: *const T, ulOffset: ULARGE_INTEGER, pv: ?*const anyopaque, cb: u32, pcbWritten: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IFillLockBytes.VTable, self.vtable).FillAt(@ptrCast(*const IFillLockBytes, self), ulOffset, pv, cb, pcbWritten);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFillLockBytes_SetFillSize(self: *const T, ulSize: ULARGE_INTEGER) callconv(.Inline) HRESULT {
return @ptrCast(*const IFillLockBytes.VTable, self.vtable).SetFillSize(@ptrCast(*const IFillLockBytes, self), ulSize);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFillLockBytes_Terminate(self: *const T, bCanceled: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IFillLockBytes.VTable, self.vtable).Terminate(@ptrCast(*const IFillLockBytes, self), bCanceled);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.0'
const IID_ILayoutStorage_Value = Guid.initString("0e6d4d90-6738-11cf-9608-00aa00680db4");
pub const IID_ILayoutStorage = &IID_ILayoutStorage_Value;
pub const ILayoutStorage = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
LayoutScript: fn(
self: *const ILayoutStorage,
pStorageLayout: [*]StorageLayout,
nEntries: u32,
glfInterleavedFlag: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
BeginMonitor: fn(
self: *const ILayoutStorage,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EndMonitor: fn(
self: *const ILayoutStorage,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ReLayoutDocfile: fn(
self: *const ILayoutStorage,
pwcsNewDfName: ?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ReLayoutDocfileOnILockBytes: fn(
self: *const ILayoutStorage,
pILockBytes: ?*ILockBytes,
) 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 ILayoutStorage_LayoutScript(self: *const T, pStorageLayout: [*]StorageLayout, nEntries: u32, glfInterleavedFlag: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ILayoutStorage.VTable, self.vtable).LayoutScript(@ptrCast(*const ILayoutStorage, self), pStorageLayout, nEntries, glfInterleavedFlag);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ILayoutStorage_BeginMonitor(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ILayoutStorage.VTable, self.vtable).BeginMonitor(@ptrCast(*const ILayoutStorage, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ILayoutStorage_EndMonitor(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ILayoutStorage.VTable, self.vtable).EndMonitor(@ptrCast(*const ILayoutStorage, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ILayoutStorage_ReLayoutDocfile(self: *const T, pwcsNewDfName: ?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ILayoutStorage.VTable, self.vtable).ReLayoutDocfile(@ptrCast(*const ILayoutStorage, self), pwcsNewDfName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ILayoutStorage_ReLayoutDocfileOnILockBytes(self: *const T, pILockBytes: ?*ILockBytes) callconv(.Inline) HRESULT {
return @ptrCast(*const ILayoutStorage.VTable, self.vtable).ReLayoutDocfileOnILockBytes(@ptrCast(*const ILayoutStorage, self), pILockBytes);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.0'
const IID_IDirectWriterLock_Value = Guid.initString("0e6d4d92-6738-11cf-9608-00aa00680db4");
pub const IID_IDirectWriterLock = &IID_IDirectWriterLock_Value;
pub const IDirectWriterLock = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
WaitForWriteAccess: fn(
self: *const IDirectWriterLock,
dwTimeout: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ReleaseWriteAccess: fn(
self: *const IDirectWriterLock,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
HaveWriteAccess: fn(
self: *const IDirectWriterLock,
) 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 IDirectWriterLock_WaitForWriteAccess(self: *const T, dwTimeout: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDirectWriterLock.VTable, self.vtable).WaitForWriteAccess(@ptrCast(*const IDirectWriterLock, self), dwTimeout);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDirectWriterLock_ReleaseWriteAccess(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDirectWriterLock.VTable, self.vtable).ReleaseWriteAccess(@ptrCast(*const IDirectWriterLock, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDirectWriterLock_HaveWriteAccess(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDirectWriterLock.VTable, self.vtable).HaveWriteAccess(@ptrCast(*const IDirectWriterLock, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const VERSIONEDSTREAM = extern struct {
guidVersion: Guid,
pStream: ?*IStream,
};
pub const CAC = extern struct {
cElems: u32,
pElems: ?PSTR,
};
pub const CAUB = extern struct {
cElems: u32,
pElems: ?*u8,
};
pub const CAI = extern struct {
cElems: u32,
pElems: ?*i16,
};
pub const CAUI = extern struct {
cElems: u32,
pElems: ?*u16,
};
pub const CAL = extern struct {
cElems: u32,
pElems: ?*i32,
};
pub const CAUL = extern struct {
cElems: u32,
pElems: ?*u32,
};
pub const CAFLT = extern struct {
cElems: u32,
pElems: ?*f32,
};
pub const CADBL = extern struct {
cElems: u32,
pElems: ?*f64,
};
pub const CACY = extern struct {
cElems: u32,
pElems: ?*CY,
};
pub const CADATE = extern struct {
cElems: u32,
pElems: ?*f64,
};
pub const CABSTR = extern struct {
cElems: u32,
pElems: ?*?BSTR,
};
pub const CABSTRBLOB = extern struct {
cElems: u32,
pElems: ?*BSTRBLOB,
};
pub const CABOOL = extern struct {
cElems: u32,
pElems: ?*i16,
};
pub const CASCODE = extern struct {
cElems: u32,
pElems: ?*i32,
};
pub const CAPROPVARIANT = extern struct {
cElems: u32,
pElems: ?*PROPVARIANT,
};
pub const CAH = extern struct {
cElems: u32,
pElems: ?*LARGE_INTEGER,
};
pub const CAUH = extern struct {
cElems: u32,
pElems: ?*ULARGE_INTEGER,
};
pub const CALPSTR = extern struct {
cElems: u32,
pElems: ?*?PSTR,
};
pub const CALPWSTR = extern struct {
cElems: u32,
pElems: ?*?PWSTR,
};
pub const CAFILETIME = extern struct {
cElems: u32,
pElems: ?*FILETIME,
};
pub const CACLIPDATA = extern struct {
cElems: u32,
pElems: ?*CLIPDATA,
};
pub const CACLSID = extern struct {
cElems: u32,
pElems: ?*Guid,
};
pub const PROPVARIANT = extern struct {
Anonymous: extern union {
Anonymous: extern struct {
vt: u16,
wReserved1: u16,
wReserved2: u16,
wReserved3: u16,
Anonymous: extern union {
cVal: CHAR,
bVal: u8,
iVal: i16,
uiVal: u16,
lVal: i32,
ulVal: u32,
intVal: i32,
uintVal: u32,
hVal: LARGE_INTEGER,
uhVal: ULARGE_INTEGER,
fltVal: f32,
dblVal: f64,
boolVal: i16,
__OBSOLETE__VARIANT_BOOL: i16,
scode: i32,
cyVal: CY,
date: f64,
filetime: FILETIME,
puuid: ?*Guid,
pclipdata: ?*CLIPDATA,
bstrVal: ?BSTR,
bstrblobVal: BSTRBLOB,
blob: BLOB,
pszVal: ?PSTR,
pwszVal: ?PWSTR,
punkVal: ?*IUnknown,
pdispVal: ?*IDispatch,
pStream: ?*IStream,
pStorage: ?*IStorage,
pVersionedStream: ?*VERSIONEDSTREAM,
parray: ?*SAFEARRAY,
cac: CAC,
caub: CAUB,
cai: CAI,
caui: CAUI,
cal: CAL,
caul: CAUL,
cah: CAH,
cauh: CAUH,
caflt: CAFLT,
cadbl: CADBL,
cabool: CABOOL,
cascode: CASCODE,
cacy: CACY,
cadate: CADATE,
cafiletime: CAFILETIME,
cauuid: CACLSID,
caclipdata: CACLIPDATA,
cabstr: CABSTR,
cabstrblob: CABSTRBLOB,
calpstr: CALPSTR,
calpwstr: CALPWSTR,
capropvar: CAPROPVARIANT,
pcVal: ?PSTR,
pbVal: ?*u8,
piVal: ?*i16,
puiVal: ?*u16,
plVal: ?*i32,
pulVal: ?*u32,
pintVal: ?*i32,
puintVal: ?*u32,
pfltVal: ?*f32,
pdblVal: ?*f64,
pboolVal: ?*i16,
pdecVal: ?*DECIMAL,
pscode: ?*i32,
pcyVal: ?*CY,
pdate: ?*f64,
pbstrVal: ?*?BSTR,
ppunkVal: ?*?*IUnknown,
ppdispVal: ?*?*IDispatch,
pparray: ?*?*SAFEARRAY,
pvarVal: ?*PROPVARIANT,
},
},
decVal: DECIMAL,
},
};
pub const PROPSPEC = extern struct {
ulKind: PROPSPEC_KIND,
Anonymous: extern union {
propid: u32,
lpwstr: ?PWSTR,
},
};
pub const STATPROPSTG = extern struct {
lpwstrName: ?PWSTR,
propid: u32,
vt: u16,
};
pub const STATPROPSETSTG = extern struct {
fmtid: Guid,
clsid: Guid,
grfFlags: u32,
mtime: FILETIME,
ctime: FILETIME,
atime: FILETIME,
dwOSVersion: u32,
};
// TODO: this type is limited to platform 'windows5.0'
const IID_IPropertyStorage_Value = Guid.initString("00000138-0000-0000-c000-000000000046");
pub const IID_IPropertyStorage = &IID_IPropertyStorage_Value;
pub const IPropertyStorage = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
ReadMultiple: fn(
self: *const IPropertyStorage,
cpspec: u32,
rgpspec: [*]const PROPSPEC,
rgpropvar: [*]PROPVARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteMultiple: fn(
self: *const IPropertyStorage,
cpspec: u32,
rgpspec: [*]const PROPSPEC,
rgpropvar: [*]const PROPVARIANT,
propidNameFirst: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DeleteMultiple: fn(
self: *const IPropertyStorage,
cpspec: u32,
rgpspec: [*]const PROPSPEC,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ReadPropertyNames: fn(
self: *const IPropertyStorage,
cpropid: u32,
rgpropid: [*]const u32,
rglpwstrName: [*]?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WritePropertyNames: fn(
self: *const IPropertyStorage,
cpropid: u32,
rgpropid: [*]const u32,
rglpwstrName: [*]const ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DeletePropertyNames: fn(
self: *const IPropertyStorage,
cpropid: u32,
rgpropid: [*]const u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Commit: fn(
self: *const IPropertyStorage,
grfCommitFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Revert: fn(
self: *const IPropertyStorage,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Enum: fn(
self: *const IPropertyStorage,
ppenum: ?*?*IEnumSTATPROPSTG,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetTimes: fn(
self: *const IPropertyStorage,
pctime: ?*const FILETIME,
patime: ?*const FILETIME,
pmtime: ?*const FILETIME,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetClass: fn(
self: *const IPropertyStorage,
clsid: ?*const Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Stat: fn(
self: *const IPropertyStorage,
pstatpsstg: ?*STATPROPSETSTG,
) 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 IPropertyStorage_ReadMultiple(self: *const T, cpspec: u32, rgpspec: [*]const PROPSPEC, rgpropvar: [*]PROPVARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IPropertyStorage.VTable, self.vtable).ReadMultiple(@ptrCast(*const IPropertyStorage, self), cpspec, rgpspec, rgpropvar);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPropertyStorage_WriteMultiple(self: *const T, cpspec: u32, rgpspec: [*]const PROPSPEC, rgpropvar: [*]const PROPVARIANT, propidNameFirst: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IPropertyStorage.VTable, self.vtable).WriteMultiple(@ptrCast(*const IPropertyStorage, self), cpspec, rgpspec, rgpropvar, propidNameFirst);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPropertyStorage_DeleteMultiple(self: *const T, cpspec: u32, rgpspec: [*]const PROPSPEC) callconv(.Inline) HRESULT {
return @ptrCast(*const IPropertyStorage.VTable, self.vtable).DeleteMultiple(@ptrCast(*const IPropertyStorage, self), cpspec, rgpspec);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPropertyStorage_ReadPropertyNames(self: *const T, cpropid: u32, rgpropid: [*]const u32, rglpwstrName: [*]?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IPropertyStorage.VTable, self.vtable).ReadPropertyNames(@ptrCast(*const IPropertyStorage, self), cpropid, rgpropid, rglpwstrName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPropertyStorage_WritePropertyNames(self: *const T, cpropid: u32, rgpropid: [*]const u32, rglpwstrName: [*]const ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IPropertyStorage.VTable, self.vtable).WritePropertyNames(@ptrCast(*const IPropertyStorage, self), cpropid, rgpropid, rglpwstrName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPropertyStorage_DeletePropertyNames(self: *const T, cpropid: u32, rgpropid: [*]const u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IPropertyStorage.VTable, self.vtable).DeletePropertyNames(@ptrCast(*const IPropertyStorage, self), cpropid, rgpropid);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPropertyStorage_Commit(self: *const T, grfCommitFlags: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IPropertyStorage.VTable, self.vtable).Commit(@ptrCast(*const IPropertyStorage, self), grfCommitFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPropertyStorage_Revert(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IPropertyStorage.VTable, self.vtable).Revert(@ptrCast(*const IPropertyStorage, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPropertyStorage_Enum(self: *const T, ppenum: ?*?*IEnumSTATPROPSTG) callconv(.Inline) HRESULT {
return @ptrCast(*const IPropertyStorage.VTable, self.vtable).Enum(@ptrCast(*const IPropertyStorage, self), ppenum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPropertyStorage_SetTimes(self: *const T, pctime: ?*const FILETIME, patime: ?*const FILETIME, pmtime: ?*const FILETIME) callconv(.Inline) HRESULT {
return @ptrCast(*const IPropertyStorage.VTable, self.vtable).SetTimes(@ptrCast(*const IPropertyStorage, self), pctime, patime, pmtime);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPropertyStorage_SetClass(self: *const T, clsid: ?*const Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const IPropertyStorage.VTable, self.vtable).SetClass(@ptrCast(*const IPropertyStorage, self), clsid);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPropertyStorage_Stat(self: *const T, pstatpsstg: ?*STATPROPSETSTG) callconv(.Inline) HRESULT {
return @ptrCast(*const IPropertyStorage.VTable, self.vtable).Stat(@ptrCast(*const IPropertyStorage, self), pstatpsstg);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.0'
const IID_IPropertySetStorage_Value = Guid.initString("0000013a-0000-0000-c000-000000000046");
pub const IID_IPropertySetStorage = &IID_IPropertySetStorage_Value;
pub const IPropertySetStorage = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Create: fn(
self: *const IPropertySetStorage,
rfmtid: ?*const Guid,
pclsid: ?*const Guid,
grfFlags: u32,
grfMode: u32,
ppprstg: ?*?*IPropertyStorage,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Open: fn(
self: *const IPropertySetStorage,
rfmtid: ?*const Guid,
grfMode: u32,
ppprstg: ?*?*IPropertyStorage,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Delete: fn(
self: *const IPropertySetStorage,
rfmtid: ?*const Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Enum: fn(
self: *const IPropertySetStorage,
ppenum: ?*?*IEnumSTATPROPSETSTG,
) 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 IPropertySetStorage_Create(self: *const T, rfmtid: ?*const Guid, pclsid: ?*const Guid, grfFlags: u32, grfMode: u32, ppprstg: ?*?*IPropertyStorage) callconv(.Inline) HRESULT {
return @ptrCast(*const IPropertySetStorage.VTable, self.vtable).Create(@ptrCast(*const IPropertySetStorage, self), rfmtid, pclsid, grfFlags, grfMode, ppprstg);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPropertySetStorage_Open(self: *const T, rfmtid: ?*const Guid, grfMode: u32, ppprstg: ?*?*IPropertyStorage) callconv(.Inline) HRESULT {
return @ptrCast(*const IPropertySetStorage.VTable, self.vtable).Open(@ptrCast(*const IPropertySetStorage, self), rfmtid, grfMode, ppprstg);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPropertySetStorage_Delete(self: *const T, rfmtid: ?*const Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const IPropertySetStorage.VTable, self.vtable).Delete(@ptrCast(*const IPropertySetStorage, self), rfmtid);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPropertySetStorage_Enum(self: *const T, ppenum: ?*?*IEnumSTATPROPSETSTG) callconv(.Inline) HRESULT {
return @ptrCast(*const IPropertySetStorage.VTable, self.vtable).Enum(@ptrCast(*const IPropertySetStorage, self), ppenum);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.0'
const IID_IEnumSTATPROPSTG_Value = Guid.initString("00000139-0000-0000-c000-000000000046");
pub const IID_IEnumSTATPROPSTG = &IID_IEnumSTATPROPSTG_Value;
pub const IEnumSTATPROPSTG = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Next: fn(
self: *const IEnumSTATPROPSTG,
celt: u32,
rgelt: [*]STATPROPSTG,
pceltFetched: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Skip: fn(
self: *const IEnumSTATPROPSTG,
celt: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reset: fn(
self: *const IEnumSTATPROPSTG,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clone: fn(
self: *const IEnumSTATPROPSTG,
ppenum: ?*?*IEnumSTATPROPSTG,
) 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 IEnumSTATPROPSTG_Next(self: *const T, celt: u32, rgelt: [*]STATPROPSTG, pceltFetched: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumSTATPROPSTG.VTable, self.vtable).Next(@ptrCast(*const IEnumSTATPROPSTG, self), celt, rgelt, pceltFetched);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumSTATPROPSTG_Skip(self: *const T, celt: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumSTATPROPSTG.VTable, self.vtable).Skip(@ptrCast(*const IEnumSTATPROPSTG, self), celt);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumSTATPROPSTG_Reset(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumSTATPROPSTG.VTable, self.vtable).Reset(@ptrCast(*const IEnumSTATPROPSTG, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumSTATPROPSTG_Clone(self: *const T, ppenum: ?*?*IEnumSTATPROPSTG) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumSTATPROPSTG.VTable, self.vtable).Clone(@ptrCast(*const IEnumSTATPROPSTG, self), ppenum);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.0'
const IID_IEnumSTATPROPSETSTG_Value = Guid.initString("0000013b-0000-0000-c000-000000000046");
pub const IID_IEnumSTATPROPSETSTG = &IID_IEnumSTATPROPSETSTG_Value;
pub const IEnumSTATPROPSETSTG = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Next: fn(
self: *const IEnumSTATPROPSETSTG,
celt: u32,
rgelt: [*]STATPROPSETSTG,
pceltFetched: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Skip: fn(
self: *const IEnumSTATPROPSETSTG,
celt: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reset: fn(
self: *const IEnumSTATPROPSETSTG,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clone: fn(
self: *const IEnumSTATPROPSETSTG,
ppenum: ?*?*IEnumSTATPROPSETSTG,
) 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 IEnumSTATPROPSETSTG_Next(self: *const T, celt: u32, rgelt: [*]STATPROPSETSTG, pceltFetched: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumSTATPROPSETSTG.VTable, self.vtable).Next(@ptrCast(*const IEnumSTATPROPSETSTG, self), celt, rgelt, pceltFetched);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumSTATPROPSETSTG_Skip(self: *const T, celt: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumSTATPROPSETSTG.VTable, self.vtable).Skip(@ptrCast(*const IEnumSTATPROPSETSTG, self), celt);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumSTATPROPSETSTG_Reset(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumSTATPROPSETSTG.VTable, self.vtable).Reset(@ptrCast(*const IEnumSTATPROPSETSTG, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumSTATPROPSETSTG_Clone(self: *const T, ppenum: ?*?*IEnumSTATPROPSETSTG) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumSTATPROPSETSTG.VTable, self.vtable).Clone(@ptrCast(*const IEnumSTATPROPSETSTG, self), ppenum);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const STGOPTIONS = extern struct {
usVersion: u16,
reserved: u16,
ulSectorSize: u32,
pwcsTemplateFile: ?[*:0]const u16,
};
pub const PIDMSI_STATUS_VALUE = enum(i32) {
NORMAL = 0,
NEW = 1,
PRELIM = 2,
DRAFT = 3,
INPROGRESS = 4,
EDIT = 5,
REVIEW = 6,
PROOF = 7,
FINAL = 8,
OTHER = 32767,
};
pub const PIDMSI_STATUS_NORMAL = PIDMSI_STATUS_VALUE.NORMAL;
pub const PIDMSI_STATUS_NEW = PIDMSI_STATUS_VALUE.NEW;
pub const PIDMSI_STATUS_PRELIM = PIDMSI_STATUS_VALUE.PRELIM;
pub const PIDMSI_STATUS_DRAFT = PIDMSI_STATUS_VALUE.DRAFT;
pub const PIDMSI_STATUS_INPROGRESS = PIDMSI_STATUS_VALUE.INPROGRESS;
pub const PIDMSI_STATUS_EDIT = PIDMSI_STATUS_VALUE.EDIT;
pub const PIDMSI_STATUS_REVIEW = PIDMSI_STATUS_VALUE.REVIEW;
pub const PIDMSI_STATUS_PROOF = PIDMSI_STATUS_VALUE.PROOF;
pub const PIDMSI_STATUS_FINAL = PIDMSI_STATUS_VALUE.FINAL;
pub const PIDMSI_STATUS_OTHER = PIDMSI_STATUS_VALUE.OTHER;
pub const SERIALIZEDPROPERTYVALUE = extern struct {
dwType: u32,
rgb: [1]u8,
};
pub const PMemoryAllocator = extern struct {
placeholder: usize, // TODO: why is this type empty?
};
const IID_IPropertyBag_Value = Guid.initString("55272a00-42cb-11ce-8135-00aa004bb851");
pub const IID_IPropertyBag = &IID_IPropertyBag_Value;
pub const IPropertyBag = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Read: fn(
self: *const IPropertyBag,
pszPropName: ?[*:0]const u16,
pVar: ?*VARIANT,
pErrorLog: ?*IErrorLog,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Write: fn(
self: *const IPropertyBag,
pszPropName: ?[*:0]const u16,
pVar: ?*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 IPropertyBag_Read(self: *const T, pszPropName: ?[*:0]const u16, pVar: ?*VARIANT, pErrorLog: ?*IErrorLog) callconv(.Inline) HRESULT {
return @ptrCast(*const IPropertyBag.VTable, self.vtable).Read(@ptrCast(*const IPropertyBag, self), pszPropName, pVar, pErrorLog);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPropertyBag_Write(self: *const T, pszPropName: ?[*:0]const u16, pVar: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IPropertyBag.VTable, self.vtable).Write(@ptrCast(*const IPropertyBag, self), pszPropName, pVar);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const OLESTREAMVTBL = extern struct {
Get: isize,
Put: isize,
};
pub const OLESTREAM = extern struct {
lpstbl: ?*OLESTREAMVTBL,
};
pub const PROPBAG2 = extern struct {
dwType: u32,
vt: u16,
cfType: u16,
dwHint: u32,
pstrName: ?PWSTR,
clsid: Guid,
};
const IID_IPropertyBag2_Value = Guid.initString("22f55882-280b-11d0-a8a9-00a0c90c2004");
pub const IID_IPropertyBag2 = &IID_IPropertyBag2_Value;
pub const IPropertyBag2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Read: fn(
self: *const IPropertyBag2,
cProperties: u32,
pPropBag: [*]PROPBAG2,
pErrLog: ?*IErrorLog,
pvarValue: [*]VARIANT,
phrError: [*]HRESULT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Write: fn(
self: *const IPropertyBag2,
cProperties: u32,
pPropBag: [*]PROPBAG2,
pvarValue: [*]VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CountProperties: fn(
self: *const IPropertyBag2,
pcProperties: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPropertyInfo: fn(
self: *const IPropertyBag2,
iProperty: u32,
cProperties: u32,
pPropBag: [*]PROPBAG2,
pcProperties: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
LoadObject: fn(
self: *const IPropertyBag2,
pstrName: ?[*:0]const u16,
dwHint: u32,
pUnkObject: ?*IUnknown,
pErrLog: ?*IErrorLog,
) 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 IPropertyBag2_Read(self: *const T, cProperties: u32, pPropBag: [*]PROPBAG2, pErrLog: ?*IErrorLog, pvarValue: [*]VARIANT, phrError: [*]HRESULT) callconv(.Inline) HRESULT {
return @ptrCast(*const IPropertyBag2.VTable, self.vtable).Read(@ptrCast(*const IPropertyBag2, self), cProperties, pPropBag, pErrLog, pvarValue, phrError);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPropertyBag2_Write(self: *const T, cProperties: u32, pPropBag: [*]PROPBAG2, pvarValue: [*]VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IPropertyBag2.VTable, self.vtable).Write(@ptrCast(*const IPropertyBag2, self), cProperties, pPropBag, pvarValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPropertyBag2_CountProperties(self: *const T, pcProperties: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IPropertyBag2.VTable, self.vtable).CountProperties(@ptrCast(*const IPropertyBag2, self), pcProperties);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPropertyBag2_GetPropertyInfo(self: *const T, iProperty: u32, cProperties: u32, pPropBag: [*]PROPBAG2, pcProperties: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IPropertyBag2.VTable, self.vtable).GetPropertyInfo(@ptrCast(*const IPropertyBag2, self), iProperty, cProperties, pPropBag, pcProperties);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPropertyBag2_LoadObject(self: *const T, pstrName: ?[*:0]const u16, dwHint: u32, pUnkObject: ?*IUnknown, pErrLog: ?*IErrorLog) callconv(.Inline) HRESULT {
return @ptrCast(*const IPropertyBag2.VTable, self.vtable).LoadObject(@ptrCast(*const IPropertyBag2, self), pstrName, dwHint, pUnkObject, pErrLog);
}
};}
pub usingnamespace MethodMixin(@This());
};
//--------------------------------------------------------------------------------
// Section: Functions (45)
//--------------------------------------------------------------------------------
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn CoGetInstanceFromFile(
pServerInfo: ?*COSERVERINFO,
pClsid: ?*Guid,
punkOuter: ?*IUnknown,
dwClsCtx: CLSCTX,
grfMode: u32,
pwszName: ?PWSTR,
dwCount: u32,
pResults: [*]MULTI_QI,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn CoGetInstanceFromIStorage(
pServerInfo: ?*COSERVERINFO,
pClsid: ?*Guid,
punkOuter: ?*IUnknown,
dwClsCtx: CLSCTX,
pstg: ?*IStorage,
dwCount: u32,
pResults: [*]MULTI_QI,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ole32" fn StgOpenAsyncDocfileOnIFillLockBytes(
pflb: ?*IFillLockBytes,
grfMode: u32,
asyncFlags: u32,
ppstgOpen: ?*?*IStorage,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ole32" fn StgGetIFillLockBytesOnILockBytes(
pilb: ?*ILockBytes,
ppflb: ?*?*IFillLockBytes,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ole32" fn StgGetIFillLockBytesOnFile(
pwcsName: ?[*:0]const u16,
ppflb: ?*?*IFillLockBytes,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "dflayout" fn StgOpenLayoutDocfile(
pwcsDfName: ?[*:0]const u16,
grfMode: u32,
reserved: u32,
ppstgOpen: ?*?*IStorage,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn CreateStreamOnHGlobal(
hGlobal: isize,
fDeleteOnRelease: BOOL,
ppstm: ?*?*IStream,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn GetHGlobalFromStream(
pstm: ?*IStream,
phglobal: ?*isize,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn CoGetInterfaceAndReleaseStream(
pStm: ?*IStream,
iid: ?*const Guid,
ppv: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn PropVariantCopy(
pvarDest: ?*PROPVARIANT,
pvarSrc: ?*const PROPVARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn PropVariantClear(
pvar: ?*PROPVARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn FreePropVariantArray(
cVariants: u32,
rgvars: [*]PROPVARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn StgCreateDocfile(
pwcsName: ?[*:0]const u16,
grfMode: u32,
reserved: u32,
ppstgOpen: ?*?*IStorage,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn StgCreateDocfileOnILockBytes(
plkbyt: ?*ILockBytes,
grfMode: u32,
reserved: u32,
ppstgOpen: ?*?*IStorage,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn StgOpenStorage(
pwcsName: ?[*:0]const u16,
pstgPriority: ?*IStorage,
grfMode: u32,
snbExclude: ?*?*u16,
reserved: u32,
ppstgOpen: ?*?*IStorage,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn StgOpenStorageOnILockBytes(
plkbyt: ?*ILockBytes,
pstgPriority: ?*IStorage,
grfMode: u32,
snbExclude: ?*?*u16,
reserved: u32,
ppstgOpen: ?*?*IStorage,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn StgIsStorageFile(
pwcsName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn StgIsStorageILockBytes(
plkbyt: ?*ILockBytes,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn StgSetTimes(
lpszName: ?[*:0]const u16,
pctime: ?*const FILETIME,
patime: ?*const FILETIME,
pmtime: ?*const FILETIME,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn StgCreateStorageEx(
pwcsName: ?[*:0]const u16,
grfMode: u32,
stgfmt: u32,
grfAttrs: u32,
pStgOptions: ?*STGOPTIONS,
pSecurityDescriptor: ?*SECURITY_DESCRIPTOR,
riid: ?*const Guid,
ppObjectOpen: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn StgOpenStorageEx(
pwcsName: ?[*:0]const u16,
grfMode: u32,
stgfmt: u32,
grfAttrs: u32,
pStgOptions: ?*STGOPTIONS,
pSecurityDescriptor: ?*SECURITY_DESCRIPTOR,
riid: ?*const Guid,
ppObjectOpen: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn StgCreatePropStg(
pUnk: ?*IUnknown,
fmtid: ?*const Guid,
pclsid: ?*const Guid,
grfFlags: u32,
dwReserved: u32,
ppPropStg: ?*?*IPropertyStorage,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn StgOpenPropStg(
pUnk: ?*IUnknown,
fmtid: ?*const Guid,
grfFlags: u32,
dwReserved: u32,
ppPropStg: ?*?*IPropertyStorage,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn StgCreatePropSetStg(
pStorage: ?*IStorage,
dwReserved: u32,
ppPropSetStg: ?*?*IPropertySetStorage,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn FmtIdToPropStgName(
pfmtid: ?*const Guid,
oszName: ?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn PropStgNameToFmtId(
oszName: ?[*:0]const u16,
pfmtid: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn ReadClassStg(
pStg: ?*IStorage,
pclsid: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn WriteClassStg(
pStg: ?*IStorage,
rclsid: ?*const Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn ReadClassStm(
pStm: ?*IStream,
pclsid: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn WriteClassStm(
pStm: ?*IStream,
rclsid: ?*const Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn GetHGlobalFromILockBytes(
plkbyt: ?*ILockBytes,
phglobal: ?*isize,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn CreateILockBytesOnHGlobal(
hGlobal: isize,
fDeleteOnRelease: BOOL,
pplkbyt: ?*?*ILockBytes,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn GetConvertStg(
pStg: ?*IStorage,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ole32" fn StgConvertVariantToProperty(
pvar: ?*const PROPVARIANT,
CodePage: u16,
// TODO: what to do with BytesParamIndex 3?
pprop: ?*SERIALIZEDPROPERTYVALUE,
pcb: ?*u32,
pid: u32,
fReserved: BOOLEAN,
pcIndirect: ?*u32,
) callconv(@import("std").os.windows.WINAPI) ?*SERIALIZEDPROPERTYVALUE;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ole32" fn StgConvertPropertyToVariant(
pprop: ?*const SERIALIZEDPROPERTYVALUE,
CodePage: u16,
pvar: ?*PROPVARIANT,
pma: ?*PMemoryAllocator,
) callconv(@import("std").os.windows.WINAPI) BOOLEAN;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ole32" fn StgPropertyLengthAsVariant(
// TODO: what to do with BytesParamIndex 1?
pProp: ?*const SERIALIZEDPROPERTYVALUE,
cbProp: u32,
CodePage: u16,
bReserved: u8,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn WriteFmtUserTypeStg(
pstg: ?*IStorage,
cf: u16,
lpszUserType: ?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn ReadFmtUserTypeStg(
pstg: ?*IStorage,
pcf: ?*u16,
lplpszUserType: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ole32" fn OleConvertOLESTREAMToIStorage(
lpolestream: ?*OLESTREAM,
pstg: ?*IStorage,
ptd: ?*const DVTARGETDEVICE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ole32" fn OleConvertIStorageToOLESTREAM(
pstg: ?*IStorage,
lpolestream: ?*OLESTREAM,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLE32" fn SetConvertStg(
pStg: ?*IStorage,
fConvert: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ole32" fn OleConvertIStorageToOLESTREAMEx(
pstg: ?*IStorage,
cfFormat: u16,
lWidth: i32,
lHeight: i32,
dwSize: u32,
pmedium: ?*STGMEDIUM,
polestm: ?*OLESTREAM,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ole32" fn OleConvertOLESTREAMToIStorageEx(
polestm: ?*OLESTREAM,
pstg: ?*IStorage,
pcfFormat: ?*u16,
plwWidth: ?*i32,
plHeight: ?*i32,
pdwSize: ?*u32,
pmedium: ?*STGMEDIUM,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "PROPSYS" fn StgSerializePropVariant(
ppropvar: ?*const PROPVARIANT,
ppProp: ?*?*SERIALIZEDPROPERTYVALUE,
pcb: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "PROPSYS" fn StgDeserializePropVariant(
pprop: ?*const SERIALIZEDPROPERTYVALUE,
cbMax: u32,
ppropvar: ?*PROPVARIANT,
) 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 (29)
//--------------------------------------------------------------------------------
const Guid = @import("../../zig.zig").Guid;
const BLOB = @import("../../system/com.zig").BLOB;
const BOOL = @import("../../foundation.zig").BOOL;
const BOOLEAN = @import("../../foundation.zig").BOOLEAN;
const BSTR = @import("../../foundation.zig").BSTR;
const CHAR = @import("../../foundation.zig").CHAR;
const CLSCTX = @import("../../system/com.zig").CLSCTX;
const COSERVERINFO = @import("../../system/com.zig").COSERVERINFO;
const CY = @import("../../system/com.zig").CY;
const DECIMAL = @import("../../foundation.zig").DECIMAL;
const DVTARGETDEVICE = @import("../../system/com.zig").DVTARGETDEVICE;
const FILETIME = @import("../../foundation.zig").FILETIME;
const HRESULT = @import("../../foundation.zig").HRESULT;
const IDispatch = @import("../../system/com.zig").IDispatch;
const IErrorLog = @import("../../system/com.zig").IErrorLog;
const IPersist = @import("../../system/com.zig").IPersist;
const IStream = @import("../../system/com.zig").IStream;
const IUnknown = @import("../../system/com.zig").IUnknown;
const LARGE_INTEGER = @import("../../foundation.zig").LARGE_INTEGER;
const MULTI_QI = @import("../../system/com.zig").MULTI_QI;
const PSTR = @import("../../foundation.zig").PSTR;
const PWSTR = @import("../../foundation.zig").PWSTR;
const SAFEARRAY = @import("../../system/com.zig").SAFEARRAY;
const SECURITY_DESCRIPTOR = @import("../../security.zig").SECURITY_DESCRIPTOR;
const STATSTG = @import("../../system/com.zig").STATSTG;
const STGMEDIUM = @import("../../system/com.zig").STGMEDIUM;
const StorageLayout = @import("../../system/com.zig").StorageLayout;
const ULARGE_INTEGER = @import("../../foundation.zig").ULARGE_INTEGER;
const VARIANT = @import("../../system/com.zig").VARIANT;
test {
@setEvalBranchQuota(
@import("std").meta.declarations(@This()).len * 3
);
// reference all the pub declarations
if (!@import("builtin").is_test) return;
inline for (@import("std").meta.declarations(@This())) |decl| {
if (decl.is_pub) {
_ = decl;
}
}
} | win32/system/com/structured_storage.zig |
const std = @import("std");
const c = @import("internal/c.zig");
const internal = @import("internal/internal.zig");
const log = std.log.scoped(.git);
const git = @import("git.zig");
pub const Remote = opaque {
/// Free the memory associated with a remote.
pub fn deinit(self: *Remote) !void {
log.debug("Remote.deinit called", .{});
c.git_remote_free(@ptrCast(*c.git_remote, self));
log.debug("remote closed successfully", .{});
}
/// Add a fetch refspec to the remote's configuration.
///
/// ## Parameters
/// * `remote` - Name of the remote to change.
/// * `refspec` - The new fetch refspec.
pub fn addFetch(repository: *git.Repository, remote: [:0]const u8, refspec: [:0]const u8) !void {
log.debug("Remote.addFetch called, remote={s}, refspec={s}", .{ remote, refspec });
try internal.wrapCall("git_remote_add_fetch", .{
@ptrCast(*c.git_repository, repository),
remote.ptr,
refspec.ptr,
});
log.debug("successfully added fetch", .{});
}
/// Add a pull refspec to the remote's configuration.
///
/// ## Parameters
/// * `remote` - Name of the remote to change.
/// * `refspec` - The new pull refspec.
pub fn addPush(repository: *git.Repository, remote: [:0]const u8, refspec: [:0]const u8) !void {
log.debug("Remote.addPush called, remote={s}, refspecs={s}", .{ remote, refspec });
try internal.wrapCall("git_remote_add_push", .{
@ptrCast(*c.git_repository, repository),
remote.ptr,
refspec.ptr,
});
log.debug("successfully added pull", .{});
}
const AutotagOption = enum(c_uint) {
DOWNLOAD_TAGS_UNSPECIFIED,
DOWNLOAD_TAGS_AUTO,
DOWNLOAD_TAGS_NONE,
DOWNLOAD_TAGS_ALL,
};
/// Retrieve the tag auto-follow setting.
pub fn autotag(self: *const Remote) AutotagOption {
log.debug("Remote.autotag called", .{});
var res = c.git_remote_autotag(@ptrCast(*const c.git_remote, self));
return @intToEnum(AutotagOption, res);
}
/// Open a connection to a remote.
///
/// ## Parameters
/// * `direction` - FETCH if you want to fetch or PUSH if you want to push.
/// * `callbacks` - The callbacks to use for this connection.
/// * `proxy_opts` - Proxy settings.
/// * `custom_headers` - Extra HTTP headers to use in this connection.
pub fn connect(
self: *Remote,
direction: git.Direction,
callbacks: RemoteCallbacks,
proxy_opts: git.ProxyOptions,
custom_headers: *git.StrArray,
) !void {
log.debug("Remote.connect called, direction={}, proxy_opts: {}", .{ direction, proxy_opts });
try internal.wrapCall("git_remote_connect", .{
@ptrCast(*c.git_remote, self),
@enumToInt(direction),
&callbacks.makeCOptionsObject(),
&proxy_opts.makeCOptionsObject(),
@ptrCast(*c.git_strarray, custom_headers),
});
log.debug("successfully made connection", .{});
}
/// Check whether the remote is connected.
pub fn connected(self: *const Remote) !bool {
log.debug("Remote.connected called", .{});
var res = try internal.wrapCallWithReturn("git_remote_connected", .{
@ptrCast(*const c.git_remote, self),
});
log.debug("connected={}", .{res != 0});
return res != 0;
}
/// Add a remote with the default fetch refspec to the repository's configuration.
///
/// ## Parameters
/// * `repository` - The repository in which to create the remote.
/// * `name` - The remote's name.
/// * `url` - The remote's url.
pub fn create(repository: *git.Repository, name: [:0]const u8, url: [:0]const u8) !*Remote {
log.debug("Remote.create called, name={s}, url={s}", .{ name, url });
var remote: *Remote = undefined;
try internal.wrapCall("git_remote_create", .{
@ptrCast([*c]?*c.git_remote, &remote),
@ptrCast(*c.git_repository, repository),
name.ptr,
url.ptr,
});
log.debug("successfully created remote", .{});
return remote;
}
/// Create a remote with the given url in-memory. You can use this when you have a url instead of a remote's name.
///
/// ## Parameters
/// * `repository` - The repository in which to create the remote.
/// * `name` - The remote's name.
/// * `url` - The remote's url.
pub fn createAnonymous(repository: *git.Repository, url: [:0]const u8) !*Remote {
log.debug("Remote.createAnonymous called, url={s}", .{url});
var remote: *Remote = undefined;
try internal.wrapCall("git_remote_create_anonymous", .{
@ptrCast([*c]?*c.git_remote, &remote),
@ptrCast(*c.git_repository, repository),
url.ptr,
});
log.debug("successfully created remote", .{});
return remote;
}
/// Create a remote without a connected local repo.
///
/// Create a remote with the given url in-memory. You can use this when you have a URL instead of a remote's name.
///
/// Contrasted with git_remote_create_anonymous, a detached remote will not consider any repo configuration values
/// (such as insteadof url substitutions).
///
/// ## Parameters
/// * `url` - The remote's url.
pub fn createDetached(url: [:0]const u8) !*Remote {
log.debug("Remote.createDetached called, url={s}", .{url});
var remote: *Remote = undefined;
try internal.wrapCall("git_remote_create_detached", .{
@ptrCast([*c]?*c.git_remote, &remote),
url.ptr,
});
log.debug("successfully created remote", .{});
return remote;
}
/// Add a remote with the provided refspec (or default if NULL) to the repository's configuration.
///
/// ## Parameters
/// * `repository` - The repository in which to create the remote.
/// * `name` - The remote's name.
/// * `url` - The remote's url.
/// * `fetch` - The remote fetch value.
pub fn createWithFetchspec(repository: *git.Repository, name: [:0]const u8, url: [:0]const u8, fetchspec: [:0]const u8) !*Remote {
log.debug("Remote.createDetached called, name={s}, url={s}, fetch={s}", .{ name, url, fetchspec });
var remote: *Remote = undefined;
try internal.wrapCall("git_remote_create_with_fetchspec", .{
@ptrCast([*c]?*c.git_remote, &remote),
@ptrCast(*c.git_repository, repository),
name.ptr,
url.ptr,
fetchspec.ptr,
});
log.debug("successfully created remote", .{});
return remote;
}
/// Remote creation options flags.
pub const CreateFlags = packed struct {
/// Ignore the repository apply.insteadOf configuration.
SKIP_INSTEADOF: bool = false,
/// Don't build a fetchspec from the name if none is set.
SKIP_DEFAULT_FETCHSPEC: bool = false,
z_padding: u30 = 0,
comptime {
std.testing.refAllDecls(@This());
std.debug.assert(@sizeOf(c_uint) == @sizeOf(CreateFlags));
std.debug.assert(@bitSizeOf(c_uint) == @bitSizeOf(CreateFlags));
}
};
/// Remote creation options structure.
pub const CreateOptions = struct {
repository: *git.Repository,
name: []const u8,
fetchspec: []const u8,
flags: CreateFlags = .{},
pub fn makeCOptionsObject(self: CreateOptions) c.git_remote_create_options {
return .{
.version = c.GIT_STATUS_OPTIONS_VERSION,
.repository = @ptrCast(*c.git_repository, self.repository),
.name = self.name.ptr,
.fetchspec = self.fetchspec.ptr,
.flags = @bitCast(c_uint, self.flags),
};
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// Create a remote, with options.
///
/// This function allows more fine-grained control over the remote creation.
///
/// Passing NULL as the opts argument will result in a detached remote.
///
/// ## Parameters
/// * `url` - The remote's url.
/// * `options` - The remote creation options.
pub fn createWithOpts(url: [:0]const u8, options: CreateOptions) !*Remote {
log.debug("Remote.createDetached called, url={s}, options={}", .{ url, options });
var remote: *Remote = undefined;
try internal.wrapCall("git_remote_create_with_opts", .{
@ptrCast([*c]?*c.git_remote, &remote),
url.ptr,
@ptrCast(*c.git_remote_create_options, &options.makeCOptionsObject()),
});
log.debug("successfully created remote", .{});
return remote;
}
/// Retrieve the name of the remote's default branch
///
/// The default branch of a repository is the branch which HEAD points to. If the remote does not support reporting this information directly, it performs the guess as git does; that is, if there are multiple branches which point to the same commit, the first one is chosen. If the master branch is a candidate, it wins.
///
/// This function must only be called after connecting.
pub fn defaultBranch(self: *Remote) !git.Buf {
log.debug("Remote.defaultBranch called", .{});
var buf = git.Buf{};
try internal.wrapCall("git_remote_default_branch", .{
@ptrCast(*c.git_buf, &buf),
@ptrCast(*c.git_remote, self),
});
log.debug("successfully found default branch={s}", .{buf.toSlice()});
return buf;
}
/// Delete an existing persisted remote.
///
/// All remote-tracking branches and configuration settings for the remote will be removed.
///
/// ## Parameters
/// * `name` - The remote to delete
pub fn delete(repository: *git.Repository, name: [:0]const u8) !void {
log.debug("Remote.delete called, name={s}", .{name});
try internal.wrapCall("git_remote_delete", .{
@ptrCast(*c.git_repository, repository),
name.ptr,
});
log.debug("successfully deleted remote", .{});
}
/// Close the connection to the remote.
pub fn disconnect(self: *Remote) !void {
log.debug("Remote.diconnect called", .{});
try internal.wrapCall("git_remote_disconnect", .{
@ptrCast(*c.git_remote, self),
});
log.debug("successfully disconnected remote", .{});
}
/// Download and index the packfile
///
/// Connect to the remote if it hasn't been done yet, negotiate with the remote git which objects are missing,
/// download and index the packfile.
///
/// The .idx file will be created and both it and the packfile with be renamed to their final name.
///
/// ## Parameters
/// * `refspecs` - the refspecs to use for this negotiation and download. Use NULL or an empty array to use the
/// base refspecs
/// * `options` - the options to use for this fetch
pub fn download(self: *Remote, refspecs: *git.StrArray, options: FetchOptions) !void {
log.debug("Remote.download called, options={}", .{options});
try internal.wrapCall("git_remote_download", .{
@ptrCast(*c.git_remote, self),
@ptrCast(*c.git_strarray, refspecs),
&options.makeCOptionsObject(),
});
log.debug("successfully downloaded remote", .{});
}
/// Create a copy of an existing remote. All internal strings are also duplicated. Callbacks are not duplicated.
pub fn dupe(self: *Remote) !*Remote {
log.debug("Remote.dupe called", .{});
var remote: *Remote = undefined;
try internal.wrapCall("git_remote_dup", .{
@ptrCast([*c]?*c.git_remote, &remote),
@ptrCast(*c.git_remote, self),
});
log.debug("successfully duplicated remote", .{});
return remote;
}
/// Fetch options structure.
pub const FetchOptions = struct {
/// Callbacks to use for this fetch operation.
callbacks: RemoteCallbacks = .{},
/// Whether to perform a prune after the fetch.
prune: FetchPrune = .UNSPECIFIED,
/// Whether to write the results to FETCH_HEAD. Defaults to on. Leave this default to behave like git.
update_fetchhead: bool = false,
/// Determines how to behave regarding tags on the remote, such as auto-dowloading tags for objects we're
/// downloading or downloading all of them. The default is to auto-follow tags.
download_tags: AutoTagOption = .UNSPECIFIED,
/// Proxy options to use, bu default no proxy is used.
proxy_opts: git.ProxyOptions = .{},
/// Extra headers for this fetch operation.
custom_headers: git.StrArray = .{},
/// Acceptable prune settings from the configuration.
pub const FetchPrune = enum(c_uint) {
/// Use the setting from the configuration.
UNSPECIFIED = 0,
/// Force pruning on.
PRUNE,
/// Force pruning off.
NO_PRUNE,
};
/// Automatic tag following option.
pub const AutoTagOption = enum(c_uint) {
/// Use the setting from the configuration.
UNSPECIFIED = 0,
/// Ask the server for tags pointing to objects we're already downloading.
AUTO,
/// Don't ask for any tags beyond the refspecs.
NONE,
/// Ask for all the tags.
ALL,
};
pub fn makeCOptionsObject(self: FetchOptions) c.git_fetch_options {
return .{
.version = c.GIT_FETCH_OPTIONS_VERSION,
.callbacks = self.callbacks.makeCOptionsObject(),
.prune = @enumToInt(self.prune),
.update_fetchhead = @boolToInt(self.update_fetchhead),
.download_tags = @enumToInt(self.download_tags),
.proxy_opts = self.proxy_opts.makeCOptionsObject(),
.custom_headers = @bitCast(c.git_strarray, self.custom_headers),
};
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// Download new data and update tips.
///
/// ## Parameters
/// * `refspecs` - The refspecs to use for this fetch. Pass null or an empty array to use the base refspecs.
/// * `options` - Options to use for this fetch.
/// * `reflog_message` - The message to insert into the reflogs. If null, the default is "fetch".
pub fn fetch(self: *Remote, refspecs: ?*git.StrArray, options: FetchOptions, reflog_message: [:0]const u8) !void {
log.debug("Remote.fetch called, options={}", .{options});
try internal.wrapCall("git_remote_fetch", .{
@ptrCast(*c.git_remote, self),
@ptrCast(*c.git_strarray, refspecs),
&options.makeCOptionsObject(),
reflog_message.ptr,
});
log.debug("successfully fetched remote", .{});
}
/// Get the remote's list of fetch refspecs.
///
/// The memory is owned by the caller and should be free with StrArray.deinit.
pub fn getFetchRefspecs(self: *Remote) !git.StrArray {
log.debug("Remote.getFetchRefspecs called", .{});
var ret: git.StrArray = undefined;
try internal.wrapCall("git_remote_get_fetch_refspecs", .{
@ptrCast(*c.git_strarray, &ret),
@ptrCast(*c.git_remote, self),
});
log.debug("successfully got fetch refspecs", .{});
return ret;
}
/// Get the remote's list of push refspecs.
///
/// The memory is owned by the caller and should be free with StrArray.deinit.
pub fn getPushRefspecs(self: *Remote) !git.StrArray {
log.debug("Remote.getPushRefspecs called", .{});
var ret: git.StrArray = undefined;
try internal.wrapCall("git_remote_get_push_refspecs", .{
@ptrCast(*c.git_strarray, &ret),
@ptrCast(*c.git_remote, self),
});
log.debug("successfully got push refspecs", .{});
return ret;
}
/// Get a refspec from the remote
///
/// ## Parameters
/// * `n` - The refspec to get.
pub fn getRefspecs(self: *const Remote, n: usize) ?*const git.Refspec {
log.debug("Remote.getRefspecs called", .{});
var ret = c.git_remote_get_refspec(@ptrCast(*const c.git_remote, self), n);
return @ptrCast(?*const git.Refspec, ret);
}
/// Get a list of the configured remotes for a repo
///
/// The returned array must be deinit by user.
pub fn list(repo: *git.Repository) !git.StrArray {
log.debug("Remote.list called", .{});
var str: git.StrArray = undefined;
try internal.wrapCall("git_remote_list", .{
@ptrCast(*c.git_strarray, &str),
@ptrCast(*c.git_repository, repo),
});
log.debug("successfully got remotes list", .{});
return str;
}
/// Get the information for a particular remote.
///
/// ## Parameters
/// * `name` - The remote's name
pub fn lookup(repository: *git.Repository, name: [:0]const u8) !*Remote {
log.debug("Remote.lookup called, name=\"{s}\"", .{name});
var remote: *Remote = undefined;
try internal.wrapCall("git_remote_lookup", .{
@ptrCast([*c]?*c.git_remote, &remote),
@ptrCast(*c.git_repository, repository),
name.ptr,
});
log.debug("successfully found remote", .{});
return remote;
}
/// Description of a reference advertised by a remote server, given out on `ls` calls.
pub const Head = extern struct {
local: c_int,
oid: git.Oid,
loid: git.Oid,
name: [*:0]u8,
symref_trget: [*:0]u8,
};
/// Get the remote repository's reference advertisement list
///
/// Get the list of references with which the server responds to a new connection.
///
/// The remote (or more exactly its transport) must have connected to the remote repository. This list is available
/// as soon as the connection to the remote is initiated and it remains available after disconnecting.
///
/// The memory belongs to the remote. The pointer will be valid as long as a new connection is not initiated, but
/// it is recommended that you make a copy in order to make use of the data.
pub fn ls(self: *Remote) ![]*Head {
log.debug("Remote.ls called", .{});
var head_ptr: [*c]*Head = undefined;
var head_n: usize = undefined;
try internal.wrapCall("git_remote_ls", .{
@ptrCast([*c][*c][*c]c.git_remote_head, &head_ptr),
&head_n,
@ptrCast(*c.git_remote, self),
});
log.debug("successfully found heads", .{});
return head_ptr[0..head_n];
}
/// Get the remote's name.
pub fn getName(self: *const Remote) ?[:0]const u8 {
log.debug("Remote.getName called", .{});
var ret_c = c.git_remote_name(@ptrCast(*const c.git_remote, self));
const ret = if (ret_c) |r| std.mem.span(r) else null;
log.debug("name={s}", .{ret});
return ret;
}
/// Ensure the remote name is well-formed.
pub fn nameIsValid(remote_name: [:0]const u8) !bool {
log.debug("Remote.nameIsValid called, remote_name={s}", .{remote_name});
var ret: c_int = undefined;
try internal.wrapCall("git_remote_name_is_valid", .{
&ret,
remote_name.ptr,
});
log.debug("successfully checked name, valid={}", .{ret != 0});
return ret != 0;
}
/// Get the remote's repository.
pub fn getOwner(self: *const Remote) ?*git.Repository {
log.debug("Remote.owner called", .{});
var ret = @ptrCast(?*git.Repository, c.git_remote_owner(@ptrCast(*const c.git_remote, self)));
return ret;
}
/// Prune tracking refs that are no longer present on remote.
///
/// ## Parameters
/// * `callbacks` - Callbacks to use for this prune.
pub fn prune(self: *Remote, callbacks: RemoteCallbacks) !void {
log.debug("Remote.prune called", .{});
try internal.wrapCall("git_remote_prune", .{
@ptrCast(*c.git_remote, self),
&callbacks.makeCOptionsObject(),
});
log.debug("successfully pruned remote", .{});
}
/// Retrieve the ref-prune setting.
pub fn getPruneRefs(self: *const Remote) c_int {
log.debug("Remote.getPruneRefs called", .{});
return c.git_remote_prune_refs(@ptrCast(*const c.git_remote, self));
}
pub const PushOptions = struct {
/// If the transport being used to push to the remote requires the creation of a pack file, this controls the
/// number of worker threads used by the packbuilder when creating that pack file to be sent to the remote. If
/// set to 0, the packbuilder will auto-detect the number of threads to create. The default value is 1.
pb_parallelism: c_uint = 1,
///Callbacks to use for this push operation
callbacks: RemoteCallbacks = .{},
///Proxy options to use, by default no proxy is used.
proxy_opts: git.ProxyOptions = .{},
///Extra headers for this push operation
custom_headers: git.StrArray = .{},
pub fn makeCOptionsObject(self: PushOptions) c.git_push_options {
return .{
.version = c.GIT_PUSH_OPTIONS_VERSION,
.pb_parallelism = self.pb_parallelism,
.callbacks = self.callbacks.makeCOptionsObject(),
.proxy_opts = self.proxy_opts.makeCOptionsObject(),
.custom_headers = @bitCast(c.git_strarray, self.custom_headers),
};
}
};
/// Preform a push.
///
/// ## Parameters
/// * `refspecs` - The refspecs to use for pushing. If NULL or an empty array, the configured refspecs will be used.
/// * `options` - The options to use for this push.
pub fn push(self: *Remote, refspecs: ?*git.StrArray, options: PushOptions) !void {
log.debug("Remote.push called, options={}", .{options});
try internal.wrapCall("git_remote_push", .{
@ptrCast(*c.git_remote, self),
@ptrCast(*c.git_strarray, refspecs),
&options.makeCOptionsObject(),
});
log.debug("successfully pushed remote", .{});
}
/// Get the remote's url for pushing.
pub fn getPushUrl(self: *const Remote) ?[:0]const u8 {
log.debug("Remote.getPushUrl called", .{});
var ret = c.git_remote_pushurl(@ptrCast(*const c.git_remote, self));
return if (ret) |r| std.mem.span(r) else null;
}
/// Get the number of refspecs for a remote.
pub fn getRefspecCount(self: *const Remote) usize {
log.debug("Remote.getRefspecsCount called", .{});
return c.git_remote_refspec_count(@ptrCast(*const c.git_remote, self));
}
/// Give the remote a new name
///
/// All remote-tracking branches and configuration settings for the remote are updated.
///
/// The new name will be checked for validity. See git_tag_create() for rules about valid names.
///
/// No loaded instances of a the remote with the old name will change their name or their list of refspecs.
///
/// ## Problems
/// * `problems` - non-default refspecs cannot be renamed and will be stored here for further processing by the
/// caller. Always free this strarray on successful return.
/// * `repository` - the repository in which to rename
/// * `name` - the current name of the remote
/// * `new_name` - the new name the remote should bear
pub fn rename(problems: *git.StrArray, repository: *git.Repository, name: [:0]const u8, new_name: [:0]const u8) !void {
log.debug("Remote.rename called, name={s}, new_name={s}", .{ name, new_name });
try internal.wrapCall("git_remote_rename", .{
@ptrCast(*c.git_strarray, problems),
@ptrCast(*c.git_repository, repository),
name.ptr,
new_name.ptr,
});
log.debug("successfully renamed", .{});
}
/// Set the remote's tag following setting.
///
/// The change will be made in the configuration. No loaded remotes will be affected.
///
/// ## Parameters
/// * `repository` - The repository in which to make the change.
/// * `remote` - The name of the remote.
/// * `value` - The new value to take.
pub fn setAutotag(repository: *git.Repository, remote: [:0]const u8, value: AutotagOption) !void {
log.debug("Remote.setAutotag called, remote={s}, value={s}", .{ remote, @tagName(value) });
try internal.wrapCall("git_remote_set_autotag", .{
@ptrCast(*c.git_repository, repository),
remote.ptr,
@enumToInt(value),
});
log.debug("successfully set autotag", .{});
}
/// Set the push url for this particular url instance. The URL in the configuration will be ignored, and will not
/// be changed.
///
/// ## Parameters
/// * `url` - The url to set.
pub fn setInstancePushurl(self: *Remote, url: [:0]const u8) !void {
log.debug("Remote.setInstancePushurl called, url={s}", .{url});
try internal.wrapCall("git_remote_set_instance_pushurl", .{
@ptrCast(*c.git_remote, self),
url.ptr,
});
log.debug("successfully set instance pushurl", .{});
}
/// Set the url for this particular url instance. The URL in the configuration will be ignored, and will not be
/// changed.
///
/// ## Parameters
/// * `url` - The url to set.
pub fn setInstanceUrl(self: *Remote, url: [:0]const u8) !void {
log.debug("Remote.setInstanceUrl called, url={s}", .{url});
try internal.wrapCall("git_remote_set_instance_url", .{
@ptrCast(*c.git_remote, self),
url.ptr,
});
log.debug("successfully set instance url", .{});
}
/// Set the remote's url for pushing in the configuration.
///
/// ## Parameters
/// * `repository` - The repository in which to perform the change.
/// * `remote` - The remote's name.
/// * `url` - The url to set.
pub fn setPushurl(repository: *git.Repository, remote: [:0]const u8, url: [:0]const u8) !void {
log.debug("Remote.setPushurl called, remote={s}, url={s}", .{ remote, url });
try internal.wrapCall("git_remote_set_pushurl", .{
@ptrCast(*c.git_repository, repository),
remote.ptr,
url.ptr,
});
log.debug("successfully set pushurl", .{});
}
/// Set the remote's url in the configuration
///
/// ## Parameters
/// * `repository` - The repository in which to perform the change.
/// * `remote` - The remote's name.
/// * `url` - The url to set.
pub fn setUrl(repository: *git.Repository, remote: [:0]const u8, url: [:0]const u8) !void {
log.debug("Remote.setUrl called, remote={s}, url={s}", .{ remote, url });
try internal.wrapCall("git_remote_set_url", .{
@ptrCast(*c.git_repository, repository),
remote.ptr,
url.ptr,
});
log.debug("successfully set url", .{});
}
/// Get the statistics structure that is filled in by the fetch operation.
pub fn getStats(self: *Remote) ?*const git.Indexer.Progress {
var ret: ?*const c.git_indexer_progress = c.git_remote_stats(@ptrCast(*c.git_remote, self));
return @ptrCast(?*const git.Indexer.Progress, ret);
}
/// Cancel the operation.
///
/// At certain points in its operation, the network code checks whether the operation has been cancelled and if so
/// stops the operation.
pub fn stop(self: *Remote) !void {
log.debug("Remote.stop called", .{});
try internal.wrapCall("git_remote_stop", .{
@ptrCast(*c.git_remote, self),
});
log.debug("successfully stopped remote operation", .{});
}
/// Update the tips to the new state.
///
/// ## Parameters
/// * `callbacks` pointer to the callback structure to use
/// * `update_fetchhead` whether to write to FETCH_HEAD. Pass true to behave like git.
/// * `download_tags` what the behaviour for downloading tags is for this fetch. This is ignored for push. This must be the same value passed to `git_remote_download()`.
/// * `reflog_message` The message to insert into the reflogs. If NULL and fetching, the default is "fetch ", where is the name of the remote (or its url, for in-memory remotes). This parameter is ignored when pushing.
pub fn updateTips(
self: *Remote,
callbacks: RemoteCallbacks,
update_fetchead: bool,
download_tags: AutotagOption,
reflog_message: [:0]const u8,
) !void {
log.debug("Remote.updateTips called, update_fetchhead={}, download_tags={s}, reflog_message={s}", .{ update_fetchead, @tagName(download_tags), reflog_message });
try internal.wrapCall("git_remote_update_tips", .{
@ptrCast(*c.git_remote, self),
&callbacks.makeCOptionsObject(),
@boolToInt(update_fetchead),
@enumToInt(download_tags),
reflog_message.ptr,
});
log.debug("successfully updated tips", .{});
}
/// Create a packfile and send it to the server
///
/// Connect to the remote if it hasn't been done yet, negotiate with the remote git which objects are missing, create a packfile with the missing objects and send it.
///
/// ## Parameters
/// * remote - The remote.
/// * refspecs - The refspecs to use for this negotiation and upload. Use NULL or an empty array to use the base
/// refspecs.
/// * options - The options to use for this push.
pub fn upload(self: *Remote, refspecs: *git.StrArray, options: PushOptions) !void {
log.debug("Remote.upload called, options={}", .{options});
try internal.wrapCall("git_remote_upload", .{
@ptrCast(*c.git_remote, self),
@ptrCast(*c.git_strarray, refspecs),
&options.makeCOptionsObject(),
});
log.debug("successfully completed upload", .{});
}
/// Get the remote's url
///
/// If url.*.insteadOf has been configured for this URL, it will return the modified URL. If
/// git_remote_set_instance_pushurl has been called for this remote, then that URL will be returned.
pub fn getUrl(self: *const Remote) ?[:0]const u8 {
var ret = c.git_remote_url(@ptrCast(*const c.git_remote, self));
return if (ret) |r| std.mem.span(r) else null;
}
/// Argument to the completion callback which tells it which operation finished.
pub const RemoteCompletion = enum(c_uint) {
DOWNLOAD,
INDEXING,
ERROR,
};
/// Set the callbacks to be called by the remote when informing the user about the proogress of the networking
/// operations.
pub const RemoteCallbacks = struct {
/// Textual progress from the remote. Text send over the progress side-band will be passed to this function (this is
/// the 'counting objects' output).
///
/// Return a negative value to cancel the network operation.
///
/// ## Parameters
/// * `str` - The message from the transport
/// * `len` - The length of the message
/// * `payload` - Payload provided by the caller
sideband_progress: ?fn (str: [*:0]const u8, len: c_uint, payload: ?*anyopaque) callconv(.C) c_int = null,
/// Completion is called when different parts of the download process are done (currently unused).
completion: ?fn (@"type": RemoteCompletion, payload: ?*anyopaque) callconv(.C) c_int = null,
/// This will be called if the remote host requires authentication in order to connect to it. Returning
/// GIT_PASSTHROUGH will make libgit2 behave as though this field isn't set.
///
/// Return 0 for success, < 0 to indicate an error, > 0 to indicate no credential was acquired
/// Returning `GIT_PASSTHROUGH` will make libgit2 behave as though this field isn't set.
///
/// ## Parameters
/// * `out` - The newly created credential object.
/// * `url` - The resource for which we are demanding a credential.
/// * `username_from_url` - The username that was embedded in a "user\@host" remote url, or `null` if not included.
/// * `allowed_types` - A bitmask stating which credential types are OK to return.
/// * `payload` - The payload provided when specifying this callback.
credentials: ?fn (
out: **git.Credential,
url: [*:0]const u8,
username_from_url: [*:0]const u8,
/// BUG: This is supposed to be `git.Credential.CredentialType`, but can't be due to a zig compiler bug
allowed_types: c_uint,
payload: ?*anyopaque,
) callconv(.C) c_int = null,
/// If cert verification fails, this will be called to let the user make the final decision of whether to allow the
/// connection to proceed. Returns 0 to allow the connection or a negative value to indicate an error.
///
/// Return 0 to proceed with the connection, < 0 to fail the connection or > 0 to indicate that the callback refused
/// to act and that the existing validity determination should be honored
///
/// ## Parameters
/// * `cert` - The host certificate
/// * `valid` - Whether the libgit2 checks (OpenSSL or WinHTTP) think this certificate is valid.
/// * `host` - Hostname of the host libgit2 connected to
/// * `payload` - Payload provided by the caller
certificate_check: ?fn (
cert: *git.Certificate,
valid: bool,
host: [*:0]const u8,
payload: ?*anyopaque,
) callconv(.C) c_int = null,
/// During the download of new data, this will be regularly called with the current count of progress done by the
/// indexer.
///
/// Return a value less than 0 to cancel the indexing or download.
///
/// ## Parameters
/// * `stats` - Structure containing information about the state of the transfer
/// * `payload` - Payload provided by the caller
transfer_progress: ?fn (stats: *const git.Indexer.Progress, payload: ?*anyopaque) callconv(.C) c_int = null,
/// Each time a reference is updated locally, this function will be called with information about it.
update_tips: ?fn (
refname: [*:0]const u8,
a: *const git.Oid,
b: *const git.Oid,
payload: ?*anyopaque,
) callconv(.C) c_int = null,
/// Function to call with progress information during pack building. Be aware that this is called inline with pack
/// building operations, so perfomance may be affected.
pack_progress: ?fn (stage: git.PackbuildStage, current: u32, total: u32, payload: ?*anyopaque) callconv(.C) c_int = null,
/// Function to call with progress information during the upload portion nof a push. Be aware that this is called
/// inline with pack building operations, so performance may be affected.
push_transfer_progress: ?fn (current: c_uint, total: c_uint, size: usize, payload: ?*anyopaque) callconv(.C) c_int = null,
/// Callback used to inform of the update status from the remote.
///
/// Called for each updated reference on push. If `status` is not `null`, the update was rejected by the remote server
/// and `status` contains the reason given.
///
/// 0 on success, otherwise an error
///
/// ## Parameters
/// * `refname` - refname specifying to the remote ref
/// * `status` - status message sent from the remote
/// * `data` - data provided by the caller
push_update_reference: ?fn (
refname: [*:0]const u8,
status: ?[*:0]const u8,
data: ?*anyopaque,
) callconv(.C) c_int = null,
/// Called once between the negotiation step and the upload. It provides information about what updates will be
/// performed.
/// Callback used to inform of upcoming updates.
///
/// ## Parameters
/// * `updates` - an array containing the updates which will be sent as commands to the destination.
/// * `len` - number of elements in `updates`
/// * `payload` - Payload provided by the caller
push_negotiation: ?fn (updates: [*]*const PushUpdate, len: usize, payload: ?*anyopaque) callconv(.C) c_int = null,
/// Create the transport to use for this operation. Leave `null` to auto-detect.
transport: ?fn (out: **git.Transport, owner: *Remote, param: ?*anyopaque) callconv(.C) c_int = null,
/// Callback invoked immediately before we attempt to connect to the given url. Callers may change the URL
/// before the connection by calling git_remote_set_instance_url in the callback.
///
/// ## Parameters
/// * `remote` - The remote to be connected.
/// * `direction` - GIT_DIRECTION_FETCH or GIT_DIRECTION_PUSH.
/// * `payload` - Payload provided by the caller.
remote_ready: ?fn (remote: *git.Remote, direction: git.Direction, payload: ?*anyopaque) callconv(.C) c_int = null,
// This will be passed to each of the callbacks in this sruct as the last parameter.
payload: ?*anyopaque = null,
/// Resolve URL before connecting to remote. The returned URL will be used to connect to the remote instead.
/// This callback is deprecated; users should use git_remote_ready_cb and configure the instance URL instead.
///
/// Return 0 on success, `GIT_PASSTHROUGH` or an error
/// If you return `GIT_PASSTHROUGH`, you don't need to write anything to url_resolved.
///
/// ## Parameters
/// * `url_resolved` - The buffer to write the resolved URL to
/// * `url` - The URL to resolve
/// * `direction` - direction of the resolution
/// * `payload` - Payload provided by the caller
resolve_url: ?fn (
url_resolved: *git.Buf,
url: [*:0]const u8,
direction: git.Direction,
payload: ?*anyopaque,
) callconv(.C) c_int = null,
pub fn makeCOptionsObject(self: RemoteCallbacks) c.git_remote_callbacks {
return .{
.version = c.GIT_CHECKOUT_OPTIONS_VERSION,
.sideband_progress = @ptrCast(c.git_transport_message_cb, self.sideband_progress),
.completion = @ptrCast(?fn (c.git_remote_completion_t, ?*anyopaque) callconv(.C) c_int, self.completion),
.credentials = @ptrCast(c.git_credential_acquire_cb, self.credentials),
.certificate_check = @ptrCast(c.git_transport_certificate_check_cb, self.certificate_check),
.transfer_progress = @ptrCast(c.git_indexer_progress_cb, self.transfer_progress),
.update_tips = @ptrCast(
?fn ([*c]const u8, [*c]const c.git_oid, [*c]const c.git_oid, ?*anyopaque) callconv(.C) c_int,
self.update_tips,
),
.pack_progress = @ptrCast(c.git_packbuilder_progress, self.pack_progress),
.push_transfer_progress = @ptrCast(c.git_push_transfer_progress_cb, self.push_transfer_progress),
.push_update_reference = @ptrCast(c.git_push_update_reference_cb, self.push_update_reference),
.push_negotiation = @ptrCast(c.git_push_negotiation, self.push_negotiation),
.transport = @ptrCast(c.git_transport_cb, self.transport),
.remote_ready = @ptrCast(c.git_remote_ready_cb, self.remote_ready),
.payload = self.payload,
.resolve_url = @ptrCast(c.git_url_resolve_cb, self.resolve_url),
};
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// Represents an update which will be performed on the remote during push
pub const PushUpdate = extern struct {
/// The source name of the reference
src_refname: [*:0]const u8,
/// The name of the reference to update on the server
dst_refname: [*:0]const u8,
/// The current target of the reference
src: git.Oid,
/// The new target for the reference
dst: git.Oid,
comptime {
std.testing.refAllDecls(@This());
}
};
comptime {
std.testing.refAllDecls(@This());
}
};
comptime {
std.testing.refAllDecls(@This());
} | src/remote.zig |
const std = @import("std");
const fs = std.fs;
const Dir = fs.Dir;
const File = fs.File;
const Entry = fs.Dir.Entry;
const io = std.io;
const json = std.json;
const mem = std.mem;
const path = std.fs.path;
const warn = std.debug.warn;
pub const Export = struct {
base: []const u8,
arena: std.heap.ArenaAllocator,
allocator: *mem.Allocator,
list: List,
pub const List = std.ArrayList(*Pkg);
pub const Pkg = struct {
name: []const u8,
path: []const u8,
pub fn dump(self: *Pkg, level: usize) void {}
fn pad(times: usize) void {
var i: usize = 0;
while (i < times) : (i += 1) {
warn(" ");
}
}
};
pub fn deinit(self: *Export) void {
self.arena.deinit();
self.list.deinit();
}
pub fn init(a: *mem.Allocator, base: []const u8) Export {
return Export{
.base = base,
.arena = std.heap.ArenaAllocator.init(a),
.allocator = a,
.list = List.init(a),
};
}
pub fn dump(self: *Export) !void {
var buf = &try std.Buffer.init(self.allocator, "");
defer buf.deinit();
for (self.list.toSlice()) |p| {
try buf.resize(0);
try buf.append("Pkg{.name=\"");
try buf.append(p.name);
try buf.append("\",.path=\"");
try buf.append(p.path);
try buf.append("\"},");
warn("{}\n", buf.toSlice());
}
}
pub fn dumpStream(self: *Export, stream: var) !void {
var buf = &try std.Buffer.init(self.allocator, "");
defer buf.deinit();
for (self.list.toSlice()) |p| {
try buf.resize(0);
try buf.append("Pkg{.name=\"");
try buf.append(p.name);
try buf.append("\",.path=\"");
try buf.append(p.path);
try buf.append("\"},");
try stream.print("{}\n", buf.toSlice());
}
}
pub fn dir(self: *Export, full_path: []const u8) !void {
try self.walkTree(full_path, full_path);
}
fn pkg(self: *Export, root: []const u8, name: []const u8, pkg_path: []const u8) !void {
var a = &self.arena.allocator;
var p = try a.create(Pkg);
p.* = Pkg{
.name = stripExtension(name),
.path = pkg_path,
};
try self.list.append(p);
}
fn walkTree(self: *Export, root: []const u8, full_path: []const u8) anyerror!void {
var a = &self.arena.allocator;
// If we have a [basename].zig file then we use it as exported for the
// given package
//
// example src/apples/apples.zig
const base = path.basename(full_path);
var ext = try self.allocator.alloc(u8, base.len + 4);
mem.copy(u8, ext, base);
mem.copy(u8, ext[base.len..], ".zig");
errdefer self.allocator.free(ext);
defer self.allocator.free(ext);
const defaults = [_][]const u8{
"index.zig",
ext,
};
for (defaults) |default_file| {
const default_file_path = try path.join(self.allocator, [_][]const u8{
full_path,
default_file,
});
errdefer self.allocator.free(default_file_path);
if (fileExists(default_file_path)) {
try self.pkg(
root,
try path.relative(a, root, full_path),
try path.relative(a, self.base, default_file_path),
);
self.allocator.free(default_file_path);
return;
} else {
self.allocator.free(default_file_path);
}
}
var directory = try Dir.open(self.allocator, full_path);
defer directory.close();
var full_entry_buf = &try std.Buffer.init(self.allocator, "");
defer full_entry_buf.deinit();
while (try directory.next()) |entry| {
if (!accept(entry)) {
continue;
}
try full_entry_buf.resize(full_path.len + entry.name.len + 1);
const full_entry_path = full_entry_buf.toSlice();
mem.copy(u8, full_entry_path, full_path);
full_entry_path[full_path.len] = path.sep;
mem.copy(u8, full_entry_path[full_path.len + 1 ..], entry.name);
switch (entry.kind) {
Entry.Kind.File => {
try self.pkg(
root,
try path.relative(a, root, full_entry_path),
try path.relative(a, self.base, full_entry_path),
);
},
Entry.Kind.Directory => {
try self.walkTree(root, full_entry_path);
},
else => {},
}
}
}
};
fn stripExtension(s: []const u8) []const u8 {
return mem.trimRight(u8, s, ".zig");
}
fn accept(e: Entry) bool {
switch (e.kind) {
.File => {
if (mem.endsWith(u8, e.name, ".zig")) {
if (mem.endsWith(u8, e.name, "_test.zig")) {
return false;
}
return true;
}
},
.Directory => {
if (!mem.eql(u8, e.name, "zig-cache")) {
return true;
}
},
else => {},
}
return false;
}
/// returuns true if file exists.
pub fn fileExists(name: []const u8) bool {
var file = File.openRead(name) catch |err| {
switch (err) {
error.FileNotFound => return false,
else => {
warn("open: {} {}\n", name, err);
return false;
},
}
};
file.close();
return true;
} | src/pkg/exports/exports.zig |
const msgpack = @import("fileformats/msgpack.zig");
const std = @import("std");
const main = @import("main.zig");
const math = @import("math.zig");
pub const ActorKinds = enum(u4) {
Player, Puppet, Enemy
};
pub const Vec3 = struct {
x: f32 = 0,
y: f32 = 0,
z: f32 = 0,
};
pub const Sprite = struct {
x: u32 = 0, y: u32 = 0
};
pub const Actor = struct {
pos: Vec3 = .{ .x = 0, .y = 0, .z = 0 },
vel: Vec3 = .{ .x = 0, .y = 0, .z = 0 },
spr: Sprite = .{ .x = 0, .y = 0 },
anim: f32 = 0,
process: bool = true,
visible: bool = true,
flip_x: bool = false,
flip_y: bool = false,
kind: ActorKinds = undefined,
pub fn processPlayer(actor: *Actor, delta: f32) void {
var keys = main.getKeys();
switch (@floatToInt(u32, actor.anim)) {
0, 2 => actor.spr.x = 0,
1 => actor.spr.x = 1,
3 => actor.spr.x = 2,
else => actor.anim = 0,
}
actor.vel.x = math.lerp(actor.vel.x, 0, delta * 15);
actor.vel.y = math.lerp(actor.vel.y, 0, delta * 15);
if (keys.down) {
actor.vel.y += 20;
}
if (keys.right) {
actor.vel.x += 20;
actor.flip_x = false;
}
if (keys.up) {
actor.vel.y -= 20;
}
if (keys.left) {
actor.vel.x -= 20;
actor.flip_x = true;
}
if ((keys.down and !keys.up) or
(keys.right and !keys.left) or
(keys.up and !keys.down) or
(keys.left and !keys.right))
{
actor.anim += delta * 5; // Fun fact: spriteboy's animation is around 172 BPM
} else {
actor.anim = 0;
}
var camera = main.getCamera();
camera.x = actor.pos.x;
camera.y = actor.pos.y;
}
};
pub const Tile = struct {
x: u32, y: u32, collide: bool = false, spr: Sprite = .{ .x = 0, .y = 0 }
};
pub const Level = struct {
tiles: []Tile,
actors: []Actor,
};
pub const World = struct {
levels: []Level
};
pub fn loadMap(data: []const u8) !World {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const alloc: *std.mem.Allocator = &arena.allocator;
defer arena.deinit();
var origin = try msgpack.decode(alloc, data);
var _worldlevels = std.ArrayList(Level).init(std.heap.page_allocator);
for (origin.data.Array) |layer| {
var levtiles = std.ArrayList(Tile).init(std.heap.page_allocator);
const tiles = try layer.get("tiles");
for (tiles.Array) |tile| {
var x = try tile.get("x");
var y = try tile.get("y");
var c = try tile.get("c");
var sx = try tile.get("sx");
var sy = try tile.get("sy");
_ = try levtiles.append(Tile{
.x = @intCast(u32, x.UInt),
.y = @intCast(u32, y.UInt),
.collide = c.Boolean,
.spr = .{
.x = @intCast(u32, sx.UInt),
.y = @intCast(u32, sy.UInt),
},
});
}
var levactors = std.ArrayList(Actor).init(std.heap.page_allocator);
_ = try levactors.append(Actor{ .kind = .Player });
_ = try _worldlevels.append(Level{
.tiles = levtiles.toOwnedSlice(),
.actors = levactors.toOwnedSlice(),
});
}
return World{ .levels = _worldlevels.toOwnedSlice() };
} | src/level.zig |
const std = @import("std");
usingnamespace @import("imgui");
const ts = @import("tilescript.zig");
const upaya = @import("upaya");
const files = @import("filebrowser");
const stb = @import("stb");
// used to fill the ui while we are getting input for loading/resizing
var temp_state = struct {
tile_size: usize = 16,
tile_spacing: usize = 0,
map_width: usize = 64,
map_height: usize = 64,
has_image: bool = false,
invalid_image_selected: bool = false,
error_loading_file: bool = false,
image: [255:0]u8 = undefined,
show_load_tileset_popup: bool = false,
pub fn reset(self: *@This()) void {
self.tile_size = 16;
self.tile_spacing = 0;
self.map_width = 64;
self.map_height = 64;
self.has_image = false;
self.invalid_image_selected = false;
self.error_loading_file = false;
std.mem.set(u8, &self.image, 0);
}
}{};
fn checkKeyboardShortcuts(state: *ts.AppState) void {
// shortcuts for pressing 1-9 to set the brush
var key: usize = 49;
while (key < 58) : (key += 1) {
if (ogKeyPressed(key)) state.selected_brush_index = @intCast(usize, key - 49);
}
// show the quick brush selector
// TODO: this igIsPopupOpenStr doesnt work
// if (!igIsPopupOpenStr("##pattern_popup")) {
// if (ogKeyPressed(upaya.sokol.SAPP_KEYCODE_B)) {
// igOpenPopup("##brushes-root");
// }
// }
// undo/redo
if (ogKeyPressed(upaya.sokol.SAPP_KEYCODE_Z) and (igGetIO().KeySuper or igGetIO().KeyCtrl) and igGetIO().KeyShift) {
ts.history.redo();
state.map_data_dirty = true;
} else if (ogKeyPressed(upaya.sokol.SAPP_KEYCODE_Z) and (igGetIO().KeySuper or igGetIO().KeyCtrl)) {
ts.history.undo();
state.map_data_dirty = true;
}
// help
if (ogKeyPressed(upaya.sokol.SAPP_KEYCODE_SLASH) and igGetIO().KeyShift) {
igOpenPopup("Help");
}
// zoom in/out
if (ogKeyPressed(upaya.sokol.SAPP_KEYCODE_UP)) {
if (state.prefs.tile_size_multiplier < 4) {
state.prefs.tile_size_multiplier += 1;
}
}
if (ogKeyPressed(upaya.sokol.SAPP_KEYCODE_DOWN)) {
if (state.prefs.tile_size_multiplier > 1) {
state.prefs.tile_size_multiplier -= 1;
}
}
state.map_rect_size = @intToFloat(f32, state.map.tile_size * state.prefs.tile_size_multiplier);
if (ogKeyPressed(upaya.sokol.SAPP_KEYCODE_TAB)) {
state.toggleEditMode();
}
}
fn getDefaultPath() [:0]const u8 {
const path_or_null = @import("known-folders.zig").getPath(upaya.mem.tmp_allocator, .desktop) catch unreachable;
const tmp_path = std.mem.concat(upaya.mem.tmp_allocator, u8, &[_][]const u8{ path_or_null.?, std.fs.path.sep_str }) catch unreachable;
return std.mem.dupeZ(upaya.mem.tmp_allocator, u8, tmp_path) catch unreachable;
}
pub fn draw(state: *ts.AppState) void {
checkKeyboardShortcuts(state);
var show_load_tileset_popup = false;
var show_resize_popup = false;
var show_help_popup = false;
if (igBeginMenuBar()) {
defer igEndMenuBar();
if (igBeginMenu("File", true)) {
defer igEndMenu();
if (igMenuItemBool("New", null, false, true)) {
// TODO: fix loading of map getting wrong margin/size/tiles-per-row or something...
@import("windows/object_editor.zig").setSelectedObject(null);
const tile_size = state.map.tile_size;
const tile_spacing = state.map.tile_spacing;
state.map.deinit();
state.map = ts.Map.init(tile_size, tile_spacing);
state.clearQuickFile(.opened);
state.clearQuickFile(.exported);
state.resizeMap(state.map.w, state.map.h);
}
if (igMenuItemBool("Open...", null, false, true)) {
const res = files.openFileDialog("Open project", getDefaultPath(), "*.ts");
if (res != null) {
state.loadMap(std.mem.spanZ(res)) catch |err| {
state.showToast("Error loading map. Could not find tileset image.", 300);
};
}
}
if (igMenuItemBool("Save", null, false, state.opened_file != null)) {
state.saveMap(state.opened_file.?) catch unreachable;
}
if (igMenuItemBool("Save As...", null, false, true)) {
if (state.map.image.len == 0) {
state.showToast("No tileset image has been selected.\nLoad a tileset image before saving.", 200);
return;
}
const res = files.saveFileDialog("Save project", getDefaultPath(), "*.ts");
if (res != null) {
var out_file = res[0..std.mem.lenZ(res)];
if (!std.mem.endsWith(u8, out_file, ".ts")) {
out_file = std.mem.concat(upaya.mem.tmp_allocator, u8, &[_][]const u8{ out_file, ".ts" }) catch unreachable;
}
// validate our image path and copy the image to our save dir if its absolute
if (std.fs.path.isAbsolute(state.map.image)) {
const my_cwd = std.fs.cwd();
const dst_dir = std.fs.cwd().openDir(std.fs.path.dirname(out_file).?, .{}) catch unreachable;
const image_name = std.fs.path.basename(state.map.image);
std.fs.Dir.copyFile(my_cwd, state.map.image, dst_dir, image_name, .{}) catch |err| {
std.debug.print("error copying tileset file: {}\n", .{err});
};
// dupe the image before we free it
const duped_image_name = upaya.mem.allocator.dupe(u8, image_name) catch unreachable;
upaya.mem.allocator.free(state.map.image);
state.map.image = duped_image_name;
}
state.saveMap(out_file) catch unreachable;
// store the filename so we can do direct saves later
state.clearQuickFile(.opened);
state.opened_file = upaya.mem.allocator.dupe(u8, out_file) catch unreachable;
}
}
igSeparator();
if (igBeginMenu("Export", true)) {
defer igEndMenu();
if (igMenuItemBool("Quick JSON Export", null, false, state.exported_file != null)) {
state.exportJson(state.exported_file.?) catch unreachable;
}
if (igMenuItemBool("JSON...", null, false, true)) {
const res = files.saveFileDialog("Export to JSON", getDefaultPath(), "*.json");
if (res != null) {
var out_file = res[0..std.mem.lenZ(res)];
if (!std.mem.endsWith(u8, out_file, ".json")) {
out_file = std.mem.concat(upaya.mem.tmp_allocator, u8, &[_][]const u8{ out_file, ".json" }) catch unreachable;
}
state.exportJson(out_file) catch unreachable;
// store the filename so we can do quick exports later
state.clearQuickFile(.exported);
state.exported_file = upaya.mem.allocator.dupe(u8, out_file) catch unreachable;
}
}
if (igMenuItemBool("Binary...", null, false, true)) {
state.showToast("Doesn't work yet...", 100);
}
if (igMenuItemBool("Tiled...", null, false, true)) {
const res = files.saveFileDialog("Export to Tiled", getDefaultPath(), "*.json");
if (res != null) {
var out_file = res[0..std.mem.lenZ(res)];
if (!std.mem.endsWith(u8, out_file, ".json")) {
out_file = std.mem.concat(upaya.mem.tmp_allocator, u8, &[_][]const u8{ out_file, ".json" }) catch unreachable;
}
@import("persistence.zig").exportTiled(state, out_file) catch unreachable;
}
}
}
}
if (igBeginMenu("Map", true)) {
defer igEndMenu();
show_load_tileset_popup = igMenuItemBool("Load Tileset", null, false, true);
show_resize_popup = igMenuItemBool("Resize Map", null, false, true);
}
if (igBeginMenu("View", true)) {
defer igEndMenu();
_ = igMenuItemBoolPtr("Objects", null, &state.prefs.windows.objects, true);
_ = igMenuItemBoolPtr("Tags", null, &state.prefs.windows.tags, true);
_ = igMenuItemBoolPtr("Tile Definitions", null, &state.prefs.windows.tile_definitions, true);
_ = igMenuItemBoolPtr("Animations", null, &state.prefs.windows.animations, true);
_ = igMenuItemBoolPtr("Post Processed Map", null, &state.prefs.windows.post_processed_map, true);
}
if (igBeginMenu("Settings", true)) {
defer igEndMenu();
if (igBeginMenu("Map Display Size", true)) {
defer igEndMenu();
if (igMenuItemBool("1x", null, state.prefs.tile_size_multiplier == 1, true)) {
state.prefs.tile_size_multiplier = 1;
state.map_rect_size = @intToFloat(f32, state.map.tile_size);
}
if (igMenuItemBool("2x", null, state.prefs.tile_size_multiplier == 2, true)) {
state.prefs.tile_size_multiplier = 2;
state.map_rect_size = @intToFloat(f32, state.map.tile_size * 2);
}
if (igMenuItemBool("3x", null, state.prefs.tile_size_multiplier == 3, true)) {
state.prefs.tile_size_multiplier = 3;
state.map_rect_size = @intToFloat(f32, state.map.tile_size * 3);
}
if (igMenuItemBool("4x", null, state.prefs.tile_size_multiplier == 4, true)) {
state.prefs.tile_size_multiplier = 4;
state.map_rect_size = @intToFloat(f32, state.map.tile_size * 4);
}
}
_ = igMenuItemBoolPtr("Show Animations", null, &state.prefs.show_animations, true);
_ = igMenuItemBoolPtr("Show Objects", null, &state.prefs.show_objects, true);
if (igColorEdit3("UI Tint Color", &ts.colors.ui_tint.x, ImGuiColorEditFlags_NoInputs)) {
ts.colors.setTintColor(ts.colors.ui_tint);
}
}
if (igBeginMenu("Help", true)) {
show_help_popup = true;
igEndMenu();
}
const buttom_margin: f32 = if (state.object_edit_mode) 88 else 75;
igSetCursorPosX(igGetWindowWidth() - buttom_margin);
if (ogButton(if (state.object_edit_mode) "Object Mode" else "Tile Mode")) {
state.toggleEditMode();
}
}
// handle popups in the same scope
if (show_load_tileset_popup) {
temp_state.reset();
igOpenPopup("Load Tileset");
}
if (show_help_popup) {
igOpenPopup("Help");
}
// handle a dragged-in file
if (temp_state.show_load_tileset_popup) {
temp_state.show_load_tileset_popup = false;
igOpenPopup("Load Tileset");
}
if (show_resize_popup) {
temp_state.reset();
temp_state.map_width = state.map.w;
temp_state.map_height = state.map.h;
igOpenPopup("Resize Map");
}
loadTilesetPopup(state);
resizeMapPopup(state);
helpPopup();
}
/// sets the file in our state and triggers the load-tileset popup to be shown
pub fn loadTileset(file: []const u8) void {
temp_state.reset();
temp_state.has_image = true;
temp_state.show_load_tileset_popup = true;
std.mem.copy(u8, &temp_state.image, file);
}
fn loadTilesetPopup(state: *ts.AppState) void {
if (igBeginPopupModal("Load Tileset", null, ImGuiWindowFlags_AlwaysAutoResize)) {
defer igEndPopup();
if (temp_state.has_image) {
// only display the filename here (not the full path) so there is room for the button
const last_sep = std.mem.lastIndexOf(u8, &temp_state.image, std.fs.path.sep_str) orelse 0;
const sentinel_index = std.mem.indexOfScalar(u8, &temp_state.image, 0) orelse temp_state.image.len;
const c_file = std.cstr.addNullByte(upaya.mem.tmp_allocator, temp_state.image[last_sep + 1 .. sentinel_index]) catch unreachable;
igText(c_file);
}
igSameLine(0, 5);
if (igButton("Choose", ImVec2{ .x = -1, .y = 0 })) {
const desktop = getDefaultPath();
const res = files.openFileDialog("Import tileset image", desktop, "*.png");
if (res != null) {
std.mem.copy(u8, &temp_state.image, std.mem.spanZ(res));
temp_state.has_image = true;
} else {
temp_state.has_image = false;
}
}
_ = ogDrag(usize, "Tile Size", &temp_state.tile_size, 0.1, 8, 32);
_ = ogDrag(usize, "Tile Spacing", &temp_state.tile_spacing, 0.1, 0, 8);
// error messages
if (temp_state.invalid_image_selected) {
igSpacing();
igTextWrapped("Error: image width not compatible with tile size/spacing");
igSpacing();
}
if (temp_state.error_loading_file) {
igSpacing();
igTextWrapped("Error: could not load file");
igSpacing();
}
igSeparator();
var size = ogGetContentRegionAvail();
if (ogButtonEx("Cancel", ImVec2{ .x = (size.x - 4) / 2 })) {
igCloseCurrentPopup();
}
igSameLine(0, 4);
if (!temp_state.has_image) {
igPushItemFlag(ImGuiItemFlags_Disabled, true);
igPushStyleVarFloat(ImGuiStyleVar_Alpha, 0.5);
}
if (igButton("Load", ImVec2{ .x = -1, .y = 0 })) {
// load the image and validate that its width is divisible by the tile size (take spacing into account too)
if (validateImage()) {
state.map.image = upaya.mem.allocator.dupe(u8, temp_state.image[0..std.mem.lenZ(temp_state.image)]) catch unreachable;
state.map.tile_size = temp_state.tile_size;
state.map.tile_spacing = temp_state.tile_spacing;
state.tiles_per_row = 0;
state.map_rect_size = @intToFloat(f32, state.map.tile_size * state.prefs.tile_size_multiplier);
state.texture.deinit();
state.texture = upaya.Texture.initFromFile(state.map.image, .nearest) catch unreachable;
ogImage(state.texture.imTextureID(), state.texture.width, state.texture.height); // hack to fix a render bug on windows
igCloseCurrentPopup();
}
}
if (!temp_state.has_image) {
igPopItemFlag();
igPopStyleVar(1);
}
}
}
fn validateImage() bool {
const image_contents = upaya.fs.read(upaya.mem.tmp_allocator, std.mem.spanZ(&temp_state.image)) catch unreachable;
var w: c_int = 0;
var h: c_int = 0;
var comp: c_int = 0;
if (stb.stbi_info_from_memory(image_contents.ptr, @intCast(c_int, image_contents.len), &w, &h, &comp) == 1) {
const max_tiles = @intCast(usize, w) / temp_state.tile_size;
var i: usize = 3;
while (i <= max_tiles) : (i += 1) {
const space = (2 * temp_state.tile_spacing) + (i - 1) * temp_state.tile_spacing;
const filled = i * temp_state.tile_size;
if (space + filled == w) {
return true;
}
}
temp_state.invalid_image_selected = true;
return false;
}
temp_state.error_loading_file = true;
return false;
}
fn resizeMapPopup(state: *ts.AppState) void {
if (igBeginPopupModal("Resize Map", null, ImGuiWindowFlags_AlwaysAutoResize)) {
defer igEndPopup();
_ = ogDrag(usize, "Width", &temp_state.map_width, 0.5, 16, 512);
_ = ogDrag(usize, "Height", &temp_state.map_height, 0.5, 16, 512);
igSeparator();
if (temp_state.map_width < state.map.w or temp_state.map_height < state.map.h) {
igSpacing();
igPushStyleColorU32(ImGuiCol_Text, ts.colors.colorRgb(200, 200, 30));
igTextWrapped("Warning: resizing to a smaller size will result in map data loss and objects outside of the map boundary will be moved.");
igPopStyleColor(1);
igSpacing();
}
igSpacing();
igTextWrapped("Note: when resizing a map all undo/redo data will be purged");
igSpacing();
var size = ogGetContentRegionAvail();
if (ogButtonEx("Cancel", ImVec2{ .x = (size.x - 4) / 2 })) {
igCloseCurrentPopup();
}
igSameLine(0, 4);
if (igButton("Apply", ImVec2{ .x = -1, .y = 0 })) {
state.resizeMap(temp_state.map_width, temp_state.map_height);
igCloseCurrentPopup();
}
}
}
var help_section: enum { overview, input_map, rules, rulesets, tags_objects, tile_definitions, shortcuts } = .overview;
fn helpPopup() void {
ogSetNextWindowSize(.{ .x = 500, .y = -1 }, ImGuiCond_Always);
if (igBeginPopupModal("Help", null, ImGuiWindowFlags_AlwaysAutoResize)) {
defer igEndPopup();
igColumns(2, "id", true);
igSetColumnWidth(0, 110);
igPushItemWidth(-1);
if (igListBoxHeaderVec2("", .{})) {
defer igListBoxFooter();
if (ogSelectableBool("Overview", help_section == .overview, ImGuiSelectableFlags_DontClosePopups, .{})) {
help_section = .overview;
}
if (ogSelectableBool("Input Map", help_section == .input_map, ImGuiSelectableFlags_DontClosePopups, .{})) {
help_section = .input_map;
}
if (ogSelectableBool("Rules", help_section == .rules, ImGuiSelectableFlags_DontClosePopups, .{})) {
help_section = .rules;
}
if (ogSelectableBool("RuleSets", help_section == .rulesets, ImGuiSelectableFlags_DontClosePopups, .{})) {
help_section = .rulesets;
}
if (ogSelectableBool("Tags/Objects", help_section == .tags_objects, ImGuiSelectableFlags_DontClosePopups, .{})) {
help_section = .tags_objects;
}
if (ogSelectableBool("Tile Defs", help_section == .tile_definitions, ImGuiSelectableFlags_DontClosePopups, .{})) {
help_section = .tile_definitions;
}
if (ogSelectableBool("Shortcuts", help_section == .shortcuts, ImGuiSelectableFlags_DontClosePopups, .{})) {
help_section = .shortcuts;
}
}
igPopItemWidth();
igNextColumn();
switch (help_section) {
.overview => helpOverview(),
.input_map => helpInputMap(),
.rules => helpRules(),
.rulesets => helpRuleSets(),
.tags_objects => helpTagsObjects(),
.tile_definitions => helpTileDefinitions(),
.shortcuts => helpShortCuts(),
}
igColumns(1, "id", false);
if (ogButton("Close")) {
igCloseCurrentPopup();
}
}
}
fn helpOverview() void {
igTextWrapped("TileScript lets you setup Rules that are used to generate a tilemap. This allows you to paint a simple map with premade brushes which is then transformed into something more complex. This is done by using the Rules to dictate how they will map to your actual tileset. Additional RuleSets can be added that contain Rules that run only on the basic brushes before being transformed to your tileset.");
}
fn helpInputMap() void {
igTextWrapped("The input map consists of the raw tile data that is passed through your Rules to generate the final tilemap. Left-click and drag to paint with the current brush. Right-click and drag to erase.");
}
fn helpRules() void {
igTextWrapped("Rules are required for data to be transformed from the input map to the output map. Every Rule is run for each tile in the input map. A Rule consists of a pattern and one or more result tiles. If the Rule pattern passes, one of the result tiles will be passed along to the output map. A Rule can be made to randomly fail by setting the Chance value to less than 100%.");
}
fn helpRuleSets() void {
igTextWrapped("Additional RuleSets can be added that operate only on the raw map data. The Rules in a RuleSet are run on the input map and create an intermediate map (visible by opening the Post Processed Map window) that is then processed with the main Ruels to generate the tilemap. RuleSets can be set to repeat one or more times allowing you to do flood fills, grow plants and use many other recursive techniques.");
}
fn helpTagsObjects() void {
igTextWrapped("Tags let you associate a string with one or more tiles. This data is exported for you to use however you want.");
igSeparator();
igTextWrapped("Objects can be created and placed on any tile in the Output Map. You can define custom data (float/int/string/link) for each object. When in object edit mode, you can drag objects to place them. You can link two objects by Cmd/Alt dragging from one to another.");
}
fn helpTileDefinitions() void {
igTextWrapped("Tile Definitions provide a way to select one or more tiles from your tileset per type. This data is exported and can be used to handle collision detection.");
}
fn helpShortCuts() void {
igTextUnformatted("1 - 9: quick brush selector\nShift + drag tab: enable window docking\nCmd/Ctrl + z: undo\nShift + Cmd/Ctrl + z: redo\nTab: toggle tile/object mode\nArrow up/down: zoom in/out", null);
igSeparator();
igTextUnformatted("Input Map Shortcuts\nAlt/Cmd + left mouse drag: reposition map\nAlt + mouse wheel: zoom in/out\nShift + left mouse drag: paint rectangle\nShift + right mouse drag: clear rectangle", null);
} | tilescript/menu.zig |
const std = @import("std");
pub const AdapterType = enum {
discrete_gpu,
integrated_gpu,
cpu,
unknown,
};
pub const AddressMode = enum {
repeat,
mirror_repeat,
clamp_to_edge,
};
pub const BackendType = enum {
webgpu,
d3d11,
d3d12,
metal,
vulkan,
opengl,
opengl_es,
unknown,
};
pub const BlendFactor = enum {
zero,
one,
src,
one_minus_src,
src_alpha,
one_minus_src_alpha,
dst,
one_minus_dst,
dst_alpha,
one_minus_dst_alpha,
src_alpha_saturated,
constant,
one_minus_constant,
};
pub const BlendOperation = enum {
add,
subtract,
reverse_subtract,
min,
max,
};
pub const BufferBindingType = enum {
uniform,
storage,
read_only_storage,
};
pub const CompareFunction = enum {
never,
less,
less_equal,
greater,
greater_equal,
equal,
not_equal,
always,
};
pub const CompilationMessageType = enum {
err,
warn,
info,
};
pub const ComputePassTimestampLocation = enum {
beginning,
end,
};
pub const CullMode = enum {
none,
front,
back,
};
pub const DeviceLostReason = enum {
destroyed,
};
pub const ErrorFilter = enum {
validation,
out_of_memory,
};
pub const ErrorType = enum {
no_error,
validation,
out_of_memory,
unknown,
device_lost,
};
pub const FilterMode = enum {
nearest,
linear,
};
pub const FrontFace = enum {
ccw,
cw,
};
pub const IndexFormat = enum {
uint16,
uint32,
};
pub const LoadOp = enum {
clear,
load,
};
pub const PipelineStatisticName = enum {
vertex_shader_invocations,
clipper_invocations,
clipper_primitives_out,
fragment_shader_invocations,
compute_shader_invocations,
};
pub const PowerPreference = enum {
low_power,
high_performance,
};
pub const PresentMode = enum {
immediate,
mailbox,
fifo,
};
pub const PrimitiveTopology = enum {
point_list,
line_list,
list_strip,
triangle_list,
triangle_strip,
};
pub const QueryType = enum {
occlusion,
pipeline_statistics,
timestamp,
};
pub const RenderPassTimestampLocation = enum {
beginning,
end,
};
pub const SamplerBindingType = enum {
filtering,
non_filtering,
comparison,
};
pub const StencilOperation = enum {
keep,
zero,
replace,
invert,
increment_clamp,
decrement_clamp,
increment_wrap,
decrement_wrap,
};
pub const StorageTextureAccess = enum {
write_only,
};
pub const StoreOp = enum {
store,
discard,
};
pub const TextureAspect = enum {
all,
stencil_only,
depth_only,
};
pub const TextureComponentType = enum {
float,
sint,
uint,
depth_comparison,
};
pub const TextureDimension = enum {
d1,
d2,
d3,
};
pub const TextureFormat = enum {
r8_unorm,
r8_snorm,
r8_uint,
r8_sint,
r16_uint,
r16_sint,
r16_float,
rg8_unorm,
rg8_snorm,
rg8_uint,
rg8_sint,
r32_float,
r32_uint,
r32_sint,
rg16_uint,
rg16_sint,
rg16_float,
rgba8_unorm,
rgba8_unorm_srgb,
rgba8_snorm,
rgba8_uint,
rgba8_sint,
bgra8_unorm,
bgra8_unorm_srgb,
rgb10a2_unorm,
rg11b10_ufloat,
rgb9e5_ufloat,
rg32_float,
rg32_uint,
rg32_sint,
rgba16_uint,
rgba16_sint,
rgba16_float,
rgba32_float,
rgba32_uint,
rgba32_sint,
stencil8,
depth16_unorm,
depth24_plus,
depth24_plus_stencil8,
depth24_unorm_stencil8,
depth32_float,
depth32_float_stencil8,
bc1rgba_unorm,
bc1rgba_unorm_srgb,
bc2rgba_unorm,
bc2rgba_unorm_srgb,
bc3rgba_unorm,
bc3rgba_unorm_srgb,
bc4r_unorm,
bc4r_snorm,
bc5rg_unorm,
bc5rg_snorm,
bc6hrgb_ufloat,
bc6hrgb_float,
bc7rgba_unorm,
bc7rgba_unorm_srgb,
etc2rgb8_unorm,
etc2rgb8_unorm_srgb,
etc2rgb8a1_unorm,
etc2rgb8a1_unorm_srgb,
etc2rgba8_unorm,
etc2rgba8_unorm_srgb,
eacr11_unorm,
eacr11_snorm,
eacrg11_unorm,
eacrg11_snorm,
astc4x4_unorm,
astc4x4_unorm_srgb,
astc5x4_unorm,
astc5x4_unorm_srgb,
astc5x5_unorm,
astc5x5_unorm_srgb,
astc6x5_unorm,
astc6x5_unorm_srgb,
astc6x6_unorm,
astc6x6_unorm_srgb,
astc8x5_unorm,
astc8x5_unorm_srgb,
astc8x6_unorm,
astc8x6_unorm_srgb,
astc8x8_unorm,
astc8x8_unorm_srgb,
astc10x5_unorm,
astc10x5_unorm_srgb,
astc10x6_unorm,
astc10x6_unorm_srgb,
astc10x8_unorm,
astc10x8_unorm_srgb,
astc10x10_unorm,
astc10x10_unorm_srgb,
astc12x10_unorm,
astc12x10_unorm_srgb,
astc12x12_unorm,
astc12x12_unorm_srgb,
};
pub const TextureSampleType = enum {
float,
unfilterable_float,
depth,
sint,
uint,
};
pub const TextureViewDimension = enum {
d1,
d2,
d2_array,
cube,
cube_array,
d3,
};
pub const VertexFormat = enum {
uint8x2,
uint8x4,
sint8x2,
sint8x4,
unorm8x2,
unorm8x4,
snorm8x2,
snorm8x4,
uint16x2,
uint16x4,
sint16x2,
sint16x4,
unorm16x2,
unorm16x4,
snorm16x2,
snorm16x4,
float16x2,
float16x4,
float32,
float32x2,
float32x3,
float32x4,
uint32,
uint32x2,
uint32x3,
uint32x4,
sint32,
sint32x2,
sint32x3,
sint32x4,
};
pub const VertexStepMode = enum {
vertex,
instance,
}; | src/enums.zig |
pub const GUID_DEVINTERFACE_PWM_CONTROLLER = Guid.initString("60824b4c-eed1-4c9c-b49c-1b961461a819");
pub const IOCTL_PWM_CONTROLLER_GET_INFO = @as(u32, 262144);
pub const IOCTL_PWM_CONTROLLER_GET_ACTUAL_PERIOD = @as(u32, 262148);
pub const IOCTL_PWM_CONTROLLER_SET_DESIRED_PERIOD = @as(u32, 294920);
pub const IOCTL_PWM_PIN_GET_ACTIVE_DUTY_CYCLE_PERCENTAGE = @as(u32, 262544);
pub const IOCTL_PWM_PIN_SET_ACTIVE_DUTY_CYCLE_PERCENTAGE = @as(u32, 295316);
pub const IOCTL_PWM_PIN_GET_POLARITY = @as(u32, 262552);
pub const IOCTL_PWM_PIN_SET_POLARITY = @as(u32, 295324);
pub const IOCTL_PWM_PIN_START = @as(u32, 295331);
pub const IOCTL_PWM_PIN_STOP = @as(u32, 295335);
pub const IOCTL_PWM_PIN_IS_STARTED = @as(u32, 262568);
pub const PWM_IOCTL_ID_CONTROLLER_GET_INFO = @as(i32, 0);
pub const PWM_IOCTL_ID_CONTROLLER_GET_ACTUAL_PERIOD = @as(i32, 1);
pub const PWM_IOCTL_ID_CONTROLLER_SET_DESIRED_PERIOD = @as(i32, 2);
pub const PWM_IOCTL_ID_PIN_GET_ACTIVE_DUTY_CYCLE_PERCENTAGE = @as(i32, 100);
pub const PWM_IOCTL_ID_PIN_SET_ACTIVE_DUTY_CYCLE_PERCENTAGE = @as(i32, 101);
pub const PWM_IOCTL_ID_PIN_GET_POLARITY = @as(i32, 102);
pub const PWM_IOCTL_ID_PIN_SET_POLARITY = @as(i32, 103);
pub const PWM_IOCTL_ID_PIN_START = @as(i32, 104);
pub const PWM_IOCTL_ID_PIN_STOP = @as(i32, 105);
pub const PWM_IOCTL_ID_PIN_IS_STARTED = @as(i32, 106);
//--------------------------------------------------------------------------------
// Section: Types (10)
//--------------------------------------------------------------------------------
pub const PWM_CONTROLLER_INFO = extern struct {
Size: usize,
PinCount: u32,
MinimumPeriod: u64,
MaximumPeriod: u64,
};
pub const PWM_CONTROLLER_GET_ACTUAL_PERIOD_OUTPUT = extern struct {
ActualPeriod: u64,
};
pub const PWM_CONTROLLER_SET_DESIRED_PERIOD_INPUT = extern struct {
DesiredPeriod: u64,
};
pub const PWM_CONTROLLER_SET_DESIRED_PERIOD_OUTPUT = extern struct {
ActualPeriod: u64,
};
pub const PWM_PIN_GET_ACTIVE_DUTY_CYCLE_PERCENTAGE_OUTPUT = extern struct {
Percentage: u64,
};
pub const PWM_PIN_SET_ACTIVE_DUTY_CYCLE_PERCENTAGE_INPUT = extern struct {
Percentage: u64,
};
pub const PWM_POLARITY = enum(i32) {
HIGH = 0,
LOW = 1,
};
pub const PWM_ACTIVE_HIGH = PWM_POLARITY.HIGH;
pub const PWM_ACTIVE_LOW = PWM_POLARITY.LOW;
pub const PWM_PIN_GET_POLARITY_OUTPUT = extern struct {
Polarity: PWM_POLARITY,
};
pub const PWM_PIN_SET_POLARITY_INPUT = extern struct {
Polarity: PWM_POLARITY,
};
pub const PWM_PIN_IS_STARTED_OUTPUT = extern struct {
IsStarted: BOOLEAN,
};
//--------------------------------------------------------------------------------
// 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 (2)
//--------------------------------------------------------------------------------
const Guid = @import("../zig.zig").Guid;
const BOOLEAN = @import("../foundation.zig").BOOLEAN;
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/devices/pwm.zig |
const std = @import("../../std.zig");
const builtin = @import("builtin");
const ArrayList = std.ArrayList;
const Allocator = std.mem.Allocator;
const process = std.process;
const mem = std.mem;
const NativePaths = @This();
const NativeTargetInfo = std.zig.system.NativeTargetInfo;
include_dirs: ArrayList([:0]u8),
lib_dirs: ArrayList([:0]u8),
framework_dirs: ArrayList([:0]u8),
rpaths: ArrayList([:0]u8),
warnings: ArrayList([:0]u8),
pub fn detect(allocator: Allocator, native_info: NativeTargetInfo) !NativePaths {
const native_target = native_info.target;
var self: NativePaths = .{
.include_dirs = ArrayList([:0]u8).init(allocator),
.lib_dirs = ArrayList([:0]u8).init(allocator),
.framework_dirs = ArrayList([:0]u8).init(allocator),
.rpaths = ArrayList([:0]u8).init(allocator),
.warnings = ArrayList([:0]u8).init(allocator),
};
errdefer self.deinit();
var is_nix = false;
if (process.getEnvVarOwned(allocator, "NIX_CFLAGS_COMPILE")) |nix_cflags_compile| {
defer allocator.free(nix_cflags_compile);
is_nix = true;
var it = mem.tokenize(u8, nix_cflags_compile, " ");
while (true) {
const word = it.next() orelse break;
if (mem.eql(u8, word, "-isystem")) {
const include_path = it.next() orelse {
try self.addWarning("Expected argument after -isystem in NIX_CFLAGS_COMPILE");
break;
};
try self.addIncludeDir(include_path);
} else if (mem.eql(u8, word, "-iframework)) {
const framework_path = it.next() orelse {
try self.addWarning("Expected argument after -iframework in NIX_CFLAGS_COMPILE");
break;
};
try self.addFrameworkDir(framework_path);
} else {
if (mem.startsWith(u8, word, "-frandom-seed=")) {
continue;
}
try self.addWarningFmt("Unrecognized C flag from NIX_CFLAGS_COMPILE: {s}", .{word});
}
}
} else |err| switch (err) {
error.InvalidUtf8 => {},
error.EnvironmentVariableNotFound => {},
error.OutOfMemory => |e| return e,
}
if (process.getEnvVarOwned(allocator, "NIX_LDFLAGS")) |nix_ldflags| {
defer allocator.free(nix_ldflags);
is_nix = true;
var it = mem.tokenize(u8, nix_ldflags, " ");
while (true) {
const word = it.next() orelse break;
if (mem.eql(u8, word, "-rpath")) {
const rpath = it.next() orelse {
try self.addWarning("Expected argument after -rpath in NIX_LDFLAGS");
break;
};
try self.addRPath(rpath);
} else if (word.len > 2 and word[0] == '-' and word[1] == 'L') {
const lib_path = word[2..];
try self.addLibDir(lib_path);
} else {
try self.addWarningFmt("Unrecognized C flag from NIX_LDFLAGS: {s}", .{word});
break;
}
}
} else |err| switch (err) {
error.InvalidUtf8 => {},
error.EnvironmentVariableNotFound => {},
error.OutOfMemory => |e| return e,
}
if (is_nix) {
return self;
}
if (comptime builtin.target.isDarwin()) {
try self.addIncludeDir("/usr/include");
try self.addIncludeDir("/usr/local/include");
try self.addLibDir("/usr/lib");
try self.addLibDir("/usr/local/lib");
try self.addFrameworkDir("/Library/Frameworks");
try self.addFrameworkDir("/System/Library/Frameworks");
return self;
}
if (comptime native_target.os.tag == .solaris) {
try self.addLibDir("/usr/lib/64");
try self.addLibDir("/usr/local/lib/64");
try self.addLibDir("/lib/64");
try self.addIncludeDir("/usr/include");
try self.addIncludeDir("/usr/local/include");
return self;
}
if (native_target.os.tag != .windows) {
const triple = try native_target.linuxTriple(allocator);
const qual = native_target.cpu.arch.ptrBitWidth();
// TODO: $ ld --verbose | grep SEARCH_DIR
// the output contains some paths that end with lib64, maybe include them too?
// TODO: what is the best possible order of things?
// TODO: some of these are suspect and should only be added on some systems. audit needed.
try self.addIncludeDir("/usr/local/include");
try self.addLibDirFmt("/usr/local/lib{d}", .{qual});
try self.addLibDir("/usr/local/lib");
try self.addIncludeDirFmt("/usr/include/{s}", .{triple});
try self.addLibDirFmt("/usr/lib/{s}", .{triple});
try self.addIncludeDir("/usr/include");
try self.addLibDirFmt("/lib{d}", .{qual});
try self.addLibDir("/lib");
try self.addLibDirFmt("/usr/lib{d}", .{qual});
try self.addLibDir("/usr/lib");
// example: on a 64-bit debian-based linux distro, with zlib installed from apt:
// zlib.h is in /usr/include (added above)
// libz.so.1 is in /lib/x86_64-linux-gnu (added here)
try self.addLibDirFmt("/lib/{s}", .{triple});
}
return self;
}
pub fn deinit(self: *NativePaths) void {
deinitArray(&self.include_dirs);
deinitArray(&self.lib_dirs);
deinitArray(&self.framework_dirs);
deinitArray(&self.rpaths);
deinitArray(&self.warnings);
self.* = undefined;
}
fn deinitArray(array: *ArrayList([:0]u8)) void {
for (array.items) |item| {
array.allocator.free(item);
}
array.deinit();
}
pub fn addIncludeDir(self: *NativePaths, s: []const u8) !void {
return self.appendArray(&self.include_dirs, s);
}
pub fn addIncludeDirFmt(self: *NativePaths, comptime fmt: []const u8, args: anytype) !void {
const item = try std.fmt.allocPrintZ(self.include_dirs.allocator, fmt, args);
errdefer self.include_dirs.allocator.free(item);
try self.include_dirs.append(item);
}
pub fn addLibDir(self: *NativePaths, s: []const u8) !void {
return self.appendArray(&self.lib_dirs, s);
}
pub fn addLibDirFmt(self: *NativePaths, comptime fmt: []const u8, args: anytype) !void {
const item = try std.fmt.allocPrintZ(self.lib_dirs.allocator, fmt, args);
errdefer self.lib_dirs.allocator.free(item);
try self.lib_dirs.append(item);
}
pub fn addWarning(self: *NativePaths, s: []const u8) !void {
return self.appendArray(&self.warnings, s);
}
pub fn addFrameworkDir(self: *NativePaths, s: []const u8) !void {
return self.appendArray(&self.framework_dirs, s);
}
pub fn addFrameworkDirFmt(self: *NativePaths, comptime fmt: []const u8, args: anytype) !void {
const item = try std.fmt.allocPrintZ(self.framework_dirs.allocator, fmt, args);
errdefer self.framework_dirs.allocator.free(item);
try self.framework_dirs.append(item);
}
pub fn addWarningFmt(self: *NativePaths, comptime fmt: []const u8, args: anytype) !void {
const item = try std.fmt.allocPrintZ(self.warnings.allocator, fmt, args);
errdefer self.warnings.allocator.free(item);
try self.warnings.append(item);
}
pub fn addRPath(self: *NativePaths, s: []const u8) !void {
return self.appendArray(&self.rpaths, s);
}
fn appendArray(self: *NativePaths, array: *ArrayList([:0]u8), s: []const u8) !void {
_ = self;
const item = try array.allocator.dupeZ(u8, s);
errdefer array.allocator.free(item);
try array.append(item);
} | lib/std/zig/system/NativePaths.zig |
const std = @import("std");
const aoc = @import("aoc-lib.zig");
const HH = struct {
pub const Op = enum(u8) { acc, jmp, nop };
const Inst = struct { op: Op, arg: i64 };
code: []Inst,
ip: isize = 0,
acc: i64 = 0,
alloc: std.mem.Allocator,
pub fn fromInput(inp: anytype, alloc: std.mem.Allocator) !*HH {
var code = try alloc.alloc(Inst, inp.len);
var hh = try alloc.create(HH);
for (inp) |line, ip| {
var it = std.mem.split(u8, line, " ");
const opstr = it.next().?;
const arg = try aoc.parseInt(i64, it.next().?, 10);
var op: Op = undefined;
switch (opstr[0]) {
'a' => {
op = .acc;
},
'n' => {
op = .nop;
},
'j' => {
op = .jmp;
},
else => {
unreachable;
},
}
code[ip].op = op;
code[ip].arg = arg;
}
hh.code = code;
hh.ip = 0;
hh.acc = 0;
hh.alloc = alloc;
return hh;
}
pub fn deinit(self: *HH) void {
self.alloc.free(self.code);
self.alloc.destroy(self);
}
pub fn clone(self: *HH) !*HH {
var code = try self.alloc.alloc(Inst, self.code.len);
var hh = try self.alloc.create(HH);
for (self.code) |inst, ip| {
code[ip].op = inst.op;
code[ip].arg = inst.arg;
}
hh.code = code;
hh.ip = 0;
hh.acc = 0;
hh.alloc = self.alloc;
return hh;
}
pub fn reset(self: *HH) void {
self.ip = 0;
self.acc = 0;
}
pub fn run(self: *HH) void {
var seen = std.AutoHashMap(isize, bool).init(self.alloc);
defer seen.deinit();
while (self.ip < self.code.len) : (self.ip += 1) {
if (seen.contains(self.ip)) {
break;
}
seen.put(self.ip, true) catch unreachable;
const inst = self.code[std.math.absCast(self.ip)];
switch (inst.op) {
Op.acc => {
self.acc += inst.arg;
},
Op.jmp => {
self.ip += inst.arg - 1;
},
Op.nop => {},
}
}
}
pub fn fixOp(self: *HH, ip: usize) bool {
if (self.code[ip].op == Op.jmp) {
self.code[ip].op = Op.nop;
return true;
} else if (self.code[ip].op == Op.nop) {
self.code[ip].op = Op.jmp;
return true;
}
return false;
}
};
test "examples" {
const test1 = aoc.readLines(aoc.talloc, aoc.test1file);
defer aoc.talloc.free(test1);
const inp = aoc.readLines(aoc.talloc, aoc.inputfile);
defer aoc.talloc.free(inp);
try aoc.assertEq(@as(i64, 5), part1(aoc.talloc, test1));
try aoc.assertEq(@as(i64, 8), part2(aoc.talloc, test1));
try aoc.assertEq(@as(i64, 1614), part1(aoc.talloc, inp));
try aoc.assertEq(@as(i64, 1260), part2(aoc.talloc, inp));
}
fn part1(alloc: std.mem.Allocator, inp: anytype) i64 {
var hh = HH.fromInput(inp, alloc) catch unreachable;
defer hh.deinit();
hh.run();
return hh.acc;
}
fn part2(alloc: std.mem.Allocator, inp: anytype) i64 {
var hh = HH.fromInput(inp, alloc) catch unreachable;
defer hh.deinit();
for (hh.code) |_, ip| {
var mhh = hh.clone() catch unreachable;
defer mhh.deinit();
if (!mhh.fixOp(ip)) {
continue;
}
mhh.run();
if (mhh.ip >= hh.code.len) {
return mhh.acc;
}
}
return 0;
}
fn day08(inp: []const u8, bench: bool) anyerror!void {
var spec = aoc.readLines(aoc.halloc, inp);
defer aoc.halloc.free(spec);
var p1 = part1(aoc.halloc, spec);
var p2 = part2(aoc.halloc, spec);
if (!bench) {
try aoc.print("Part 1: {}\nPart 2: {}\n", .{ p1, p2 });
}
}
pub fn main() anyerror!void {
try aoc.benchme(aoc.input(), day08);
} | 2020/08/aoc.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const List = std.ArrayList;
const Map = std.AutoHashMap;
const StrMap = std.StringHashMap;
const BitSet = std.DynamicBitSet;
const Str = []const u8;
const util = @import("util.zig");
const gpa = util.gpa;
const data = @embedFile("../data/day03.txt");
// const data = @embedFile("../data/day03-tst.txt");
pub fn main() !void {
var grid = try Grid.init();
// Part1
// const slopes = [1][2]usize{
// [2]usize{ 3, 1 },
// };
const slopes = [5][2]usize{
[2]usize{ 1, 1 },
[2]usize{ 3, 1 },
[2]usize{ 5, 1 },
[2]usize{ 7, 1 },
[2]usize{ 1, 2 },
};
var mult: usize = 1;
for (slopes) |slope| {
var i: usize = 0;
var j: usize = 0;
var cpt: usize = 0;
while (j < grid.h) : ({
i += slope[0];
j += slope[1];
}) {
if (grid.hasTree(i, j)) {
cpt += 1;
}
}
mult *= cpt;
}
print("{}\n", .{mult});
}
const Grid = struct {
w: usize,
h: usize,
trees: List(bool),
fn init() !Grid {
var grid = Grid{
.w = 0,
.h = 0,
.trees = List(bool).init(gpa),
};
var it = tokenize(u8, data, "\r\n");
while (it.next()) |line| {
if (grid.w == 0) {
grid.w = line.len;
}
assert(grid.w == line.len);
grid.h += 1;
for (line) |c| {
try grid.trees.append(c == '#');
}
}
return grid;
}
fn hasTree(self: Grid, i: usize, j: usize) bool {
return self.trees.items[(i % self.w) + j * self.w];
}
};
// Useful stdlib functions
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const indexOf = std.mem.indexOfScalar;
const indexOfAny = std.mem.indexOfAny;
const indexOfStr = std.mem.indexOfPosLinear;
const lastIndexOf = std.mem.lastIndexOfScalar;
const lastIndexOfAny = std.mem.lastIndexOfAny;
const lastIndexOfStr = std.mem.lastIndexOfLinear;
const trim = std.mem.trim;
const sliceMin = std.mem.min;
const sliceMax = std.mem.max;
const parseInt = std.fmt.parseInt;
const parseFloat = std.fmt.parseFloat;
const min = std.math.min;
const min3 = std.math.min3;
const max = std.math.max;
const max3 = std.math.max3;
const print = std.debug.print;
const assert = std.debug.assert;
const sort = std.sort.sort;
const asc = std.sort.asc;
const desc = std.sort.desc; | src/day03.zig |
const game = @import("game.zig");
/// Simple analyzer which counts wins and losses
pub const WinLossAnalyzer = struct {
// number of total turns
turns : usize ,
// number of games lost
losses : usize ,
// number of games won
wins : usize ,
pub fn init() @This() {
return @This() {.wins = 0, .losses = 0, .turns = 0};
}
/// accumulate two analyzers and create a new one with the
/// cumulative wins, losses, and turns
pub fn accAnalyzer(self : @This(), other: @This()) @This() {
return WinLossAnalyzer {
.turns = self.turns+ other.turns, .losses = self.losses + other.losses, .wins = self.wins + other.wins
};
}
/// accumulate a game and create a new analyzer with the
/// new number of wins, losses, and turns
/// returns an error if the given game is both won and lost
pub fn accGame(self : @This(), g : game.Game) !@This() {
const new_turns = self.turns+g.turn_count;
var new_losses = self.losses;
var new_wins = self.wins;
const won = g.isWon();
const lost = g.isLost();
if (won and lost) {
return error.IllegalGameState;
}
if (won) {
new_wins +=1;
} else {
new_losses +=1;
}
return WinLossAnalyzer {
.turns = new_turns, .wins = new_wins, .losses = new_losses
};
}
};
const std = @import("std");
const concepts = @import("concepts.zig");
test "WinLossAnalyzer.init()" {
const wla = WinLossAnalyzer.init();
try std.testing.expect(std.meta.eql(wla, .{.wins = 0, .losses = 0, .turns = 0}));
}
test "WinLossAnalyzer.accAnalyzer" {
const anal1 = WinLossAnalyzer{.turns = 1, .wins = 2, .losses = 3};
const anal2 = WinLossAnalyzer{.turns = 2, .wins = 4, .losses = 6};
try std.testing.expect(std.meta.eql(anal1.accAnalyzer(anal2),anal2.accAnalyzer(anal1)));
try std.testing.expect(std.meta.eql(anal1.accAnalyzer(anal2),.{.turns = 3, .wins = 6, .losses = 9}));
}
test "WinLossAnalyzer.accGame" {
const anal = WinLossAnalyzer{.turns = 1, .wins = 2, .losses = 3};
const gwon = game.Game{.fruit_count = [_]usize{0}**game.TREE_COUNT, .raven_count = 0, .turn_count = 12};
try std.testing.expect(gwon.isWon() and !gwon.isLost());
try std.testing.expect(std.meta.eql(anal.accGame(gwon) catch unreachable,.{.turns=13,.wins = 3,.losses = 3}));
const glost = game.Game{.fruit_count = [1]usize{1}**game.TREE_COUNT, .raven_count = game.RAVEN_COMPLETE_COUNT, .turn_count = 123};
try std.testing.expect(!glost.isWon() and glost.isLost());
try std.testing.expect(std.meta.eql(anal.accGame(glost) catch unreachable,.{.turns=124,.wins = 2,.losses = 4}));
const gillegal = concepts.structUpdate(gwon,.{.raven_count = game.RAVEN_COMPLETE_COUNT});
try std.testing.expect(gillegal.isWon() and gillegal.isLost());
try std.testing.expectError(error.IllegalGameState, anal.accGame(gillegal));
} | src/analyze.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const List = std.ArrayList;
const Map = std.AutoHashMap;
const StrMap = std.StringHashMap;
const BitSet = std.DynamicBitSet;
const Str = []const u8;
const util = @import("util.zig");
const gpa = util.gpa;
const data = @embedFile("../data/day01.txt");
pub fn main() !void {
print("{}\n", .{task1()});
print("{}\n", .{task2()});
}
fn task1() i64 {
var largerCount: i64 = -1;
var lines = tokenize(u8, data, "\r\n");
var current: i64 = 0;
var previous: i64 = 0;
while (lines.next()) |line| {
current = parseInt(i64, line, 10) catch unreachable;
if (current > previous) {
largerCount += 1;
}
previous = current;
}
return largerCount;
}
fn task2() i64 {
var largerCount: i64 = 0;
var lines = tokenize(u8, data, "\r\n");
var indexCounter: u64 = 0;
const WINDOW_SIZE = 4;
var window: [WINDOW_SIZE]i64 = .{ 0, 0, 0, 0 };
while (lines.next()) |line| {
window[indexCounter % WINDOW_SIZE] = parseInt(i64, line, 10) catch unreachable;
var a: i64 = 0;
var b: i64 = 0;
if (indexCounter >= 3) {
b += window[(indexCounter - 0) % WINDOW_SIZE];
b += window[(indexCounter - 1) % WINDOW_SIZE];
b += window[(indexCounter - 2) % WINDOW_SIZE];
a += window[(indexCounter - 1) % WINDOW_SIZE];
a += window[(indexCounter - 2) % WINDOW_SIZE];
a += window[(indexCounter - 3) % WINDOW_SIZE];
}
if (a < b) {
largerCount += 1;
}
indexCounter += 1;
}
return largerCount;
}
// Useful stdlib functions
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const indexOf = std.mem.indexOfScalar;
const indexOfAny = std.mem.indexOfAny;
const indexOfStr = std.mem.indexOfPosLinear;
const lastIndexOf = std.mem.lastIndexOfScalar;
const lastIndexOfAny = std.mem.lastIndexOfAny;
const lastIndexOfStr = std.mem.lastIndexOfLinear;
const trim = std.mem.trim;
const sliceMin = std.mem.min;
const sliceMax = std.mem.max;
const parseInt = std.fmt.parseInt;
const parseFloat = std.fmt.parseFloat;
const min = std.math.min;
const min3 = std.math.min3;
const max = std.math.max;
const max3 = std.math.max3;
const print = std.debug.print;
const assert = std.debug.assert;
const sort = std.sort.sort;
const asc = std.sort.asc;
const desc = std.sort.desc; | src/day01.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const print = std.debug.print;
const input = @embedFile("../input/day18.txt");
const Operation = enum(u2) {
None,
Add,
Multiply,
};
const Calculator = struct {
const Frame = struct {
accum: u64 = 0,
op: Operation = .None,
fn num(self: *Frame, n: u64) void {
switch (self.op) {
.None => self.accum = n,
.Multiply => self.accum *= n,
.Add => self.accum += n,
}
self.op = .None;
}
};
stack: [10]Frame = undefined,
sp: usize = 0,
const Self = @This();
fn push(self: *Self) void {
self.sp += 1;
self.stack[self.sp] = Frame{};
}
fn pop(self: *Self) void {
var n = self.stack[self.sp].accum;
self.sp -= 1;
self.num(n);
}
fn op(self: *Self, o: Operation) void {
self.stack[self.sp].op = o;
}
fn num(self: *Self, n: u64) void {
self.stack[self.sp].num(n);
}
fn result(self: Self) u64 {
return self.stack[self.sp].accum;
}
};
fn eval(string: []const u8) u64 {
var calc = Calculator{};
for (string) |c| {
switch (c) {
'(' => calc.push(),
')' => calc.pop(),
'+' => calc.op(.Add),
'*' => calc.op(.Multiply),
'0'...'9' => calc.num(c - '0'),
else => {},
}
}
return calc.result();
}
// https://www.paulgriffiths.net/program/c/calc1.php
fn precedence(c: u8) u32 {
return switch (c) {
'*' => 1,
'+' => 2,
')' => 3,
'(' => 4,
else => unreachable,
};
}
fn eval2(string: []const u8) u64 {
// convert to postfix
const STACK_SIZE = 10;
var buffer: [100]u8 = undefined;
var pos: usize = 0;
var op_stack: [STACK_SIZE]u8 = undefined;
var top: usize = 0;
for (string) |c| {
switch (c) {
' ' => {},
'0'...'9' => {
buffer[pos] = c;
pos += 1;
},
else => { // op
if (top == 0 or precedence(c) > precedence(op_stack[top]) or op_stack[top] == '(') {
top += 1;
op_stack[top] = c;
} else { // remove all operators from the op_stack which have higher precendence
var balparen: i32 = 0;
while (top > 0
and (precedence(op_stack[top]) >= precedence(c) or balparen != 0)
and !(balparen == 0 and op_stack[top] == '(')) {
if (op_stack[top] == ')') {
balparen += 1;
} else if (op_stack[top] == '(') {
balparen -= 1;
} else {
buffer[pos] = op_stack[top];
pos += 1;
}
top -= 1;
}
top += 1;
op_stack[top] = c;
}
},
}
}
// append remaining ops
while (top > 0) : (top -= 1) {
if (op_stack[top] != '(' and op_stack[top] != ')') {
buffer[pos] = op_stack[top];
pos += 1;
}
}
var postfix = buffer[0..pos];
// eval postfix
var stack: [STACK_SIZE]u64 = undefined;
top = 0;
for (postfix) |c| {
switch (c) {
'0'...'9' => {
top += 1;
stack[top] = c - '0';
},
else => {
const op0 = stack[top];
top -= 1;
const op1 = stack[top];
top -= 1;
top += 1;
stack[top] = switch (c) {
'+' => op0 + op1,
'*' => op0 * op1,
else => unreachable,
};
}
}
}
return stack[top];
}
pub fn main() !void {
assert(eval("1 + (2 * 3) + (4 * (5 + 6))") == 51);
assert(eval("2 * 3 + (4 * 5)") == 26);
assert(eval("5 + (8 * 3 + 9 + 3 * 4 * 3)") == 437);
assert(eval("5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))") == 12240);
assert(eval("((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2") == 13632);
var lines = std.mem.tokenize(input, "\r\n");
var sum: u64 = 0;
while (lines.next()) |line| {
sum += eval(line);
}
print("part1: {}\n", .{sum});
assert(eval2("1 + (2 * 3) + (4 * (5 + 6))") == 51);
assert(eval2("2 * 3 + (4 * 5)") == 46);
assert(eval2("5 + (8 * 3 + 9 + 3 * 4 * 3)") == 1445);
assert(eval2("5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))") == 669060);
assert(eval2("((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2") == 23340);
lines.index = 0;
sum = 0;
while (lines.next()) |line| {
sum += eval2(line);
}
print("part2: {}\n", .{sum});
} | src/day18.zig |
const std = @import("std");
const warn = std.debug.warn;
const wgi = @import("WindowGraphicsInput/WindowGraphicsInput.zig");
const window = wgi.window;
const input = wgi.input;
const image = wgi.image;
const c = wgi.c;
const Constants = wgi.Constants;
const vertexarray = wgi.vertexarray;
const buffer = wgi.buffer;
const render = @import("RTRenderEngine/RTRenderEngine.zig");
const ModelData = @import("ModelFiles/ModelFiles.zig").ModelData;
const c_allocator = std.heap.c_allocator;
const maths = @import("Mathematics/Mathematics.zig");
const Matrix = maths.Matrix;
const Vector = maths.Vector;
const Files = @import("Files.zig");
const loadFile = Files.loadFile;
const compress = @import("Compress/Compress.zig");
const assets = @import("Assets/Assets.zig");
const Asset = assets.Asset;
const HSV2RGB = @import("Colour.zig").HSV2RGB;
const scenes = @import("Scene/Scene.zig");
var camera_position: [3]f32 = [3]f32{ 0.0, 1.75, 10.0 };
var camera_rotation_euler: [3]f32 = [3]f32{ 0.0, 0.0, 0.0 };
var cursor_enabled: bool = true;
fn mouseCallback(button: i32, action: i32, mods: i32) void {
if (button == 1 and action == Constants.RELEASE) {
cursor_enabled = !cursor_enabled;
input.setCursorEnabled(cursor_enabled);
}
}
fn moveNoUp(x: f32, y: f32, z: f32) void {
if (z != 0.0) {
camera_position[0] += (z * std.math.sin(camera_rotation_euler[1]));
camera_position[2] += (z * std.math.cos(camera_rotation_euler[1]));
}
if (x != 0.0) {
camera_position[0] += (x * std.math.sin(camera_rotation_euler[1] + 1.57079632679));
camera_position[2] += (x * std.math.cos(camera_rotation_euler[1] + 1.57079632679));
}
if (y != 0.0) {
camera_position[0] += y * std.math.sin(camera_rotation_euler[2]);
camera_position[2] += -std.math.sin(camera_rotation_euler[0]) * y;
}
}
var fullscreen: bool = false;
fn keyCallback(key: i32, scancode: i32, action: i32, mods: i32) void {
if (action == Constants.RELEASE and key == Constants.KEY_F11) {
if (fullscreen) {
window.exitFullScreen(1024, 768);
} else {
window.goFullScreen();
}
fullscreen = !fullscreen;
}
}
pub fn main() !void {
errdefer @import("ErrorDialog.zig").showErrorMessageDialog("Fatal Error", "An error has occurred.");
// Specify root folder for assets
assets.setAssetsDirectory("DemoAssets" ++ Files.path_seperator);
var assets_list = std.ArrayList(Asset).init(c_allocator);
defer assets_list.deinit();
try assets_list.resize(1);
var model_asset = &assets_list.items[0];
model_asset.* = try Asset.init("objects.model");
defer { // Free all assets (even if they are being used)
for (assets_list.items) |*a| {
a.*.free(true);
}
}
try assets.startAssetLoader1(assets_list.items, c_allocator);
try window.createWindow(false, 1024, 768, "Demo 3", true, 0);
defer window.closeWindow();
window.setResizeable(true);
input.setKeyCallback(keyCallback);
input.setMouseButtonCallback(mouseCallback);
try render.init(wgi.getMicroTime(), c_allocator);
defer render.deinit(c_allocator);
const settings = render.getSettings();
settings.enable_point_lights = false;
settings.enable_spot_lights = false;
settings.enable_directional_lights = true;
settings.max_fragment_lights = 1;
settings.max_vertex_lights = 0;
settings.enable_specular_light = false;
settings.ambient[0] = 0.1;
settings.ambient[1] = 0.1;
settings.ambient[2] = 0.1;
settings.clear_colour[0] = 0.0;
settings.clear_colour[1] = 0.0;
settings.clear_colour[2] = 0.0;
settings.fog_colour[3] = 0.0;
var root_object: render.Object = render.Object.init("root");
defer root_object.delete(true);
var camera: render.Object = render.Object.init("camera");
try root_object.addChild(&camera);
render.setActiveCamera(&camera);
var light: render.Object = render.Object.init("light");
light.light = render.Light{
.light_type = render.Light.LightType.Directional,
.colour = [3]f32{ 1, 1, 1 },
.attenuation = 1,
.cast_realtime_shadows = true,
.shadow_near = 1.0,
.shadow_far = 100.0,
.shadow_resolution_width = 1024,
};
var m = Matrix(f32, 4).rotateX(0.1);
m = m.mul(Matrix(f32, 4).rotateY(0.0));
light.setTransform(m);
try root_object.addChild(&light);
// Wait for game assets to finish loading
// Keep calling pollEvents() to stop the window freezing
// This would be where a loading bar is shown
while (!assets.assetsLoaded()) {
window.pollEvents();
if (window.windowShouldClose()) {
return;
}
// 0.1s
std.time.sleep(100000000);
}
assets.assetLoaderCleanup();
// Check all assets were loaded successfully
for (assets_list.items) |*a| {
if (a.state != Asset.AssetState.Ready) {
return error.AssetLoadError;
}
}
var object = render.Object.init("o");
var mesh: render.Mesh = try render.Mesh.initFromAsset(model_asset, false);
var mesh_renderer = try render.MeshRenderer.init(&mesh, c_allocator);
mesh_renderer.enable_per_object_light = false;
mesh_renderer.materials[0].flat_shading = true;
mesh_renderer.materials[1].flat_shading = true;
//mesh_renderer.materials[2].flat_shading = true;
object.setMeshRenderer(&mesh_renderer);
try root_object.addChild(&object);
// Free assets (data has been uploaded the GPU)
// This frees the cpu-side copy of model data which is now stored on the GPU
for (assets_list.items) |*a| {
a.freeData();
}
var mouse_pos_prev: [2]i32 = input.getMousePosition();
var brightness: f32 = 1.0;
var contrast: f32 = 1.0;
var last_frame_time = wgi.getMicroTime();
var last_fps_print_time = last_frame_time;
var fps_count: u32 = 0;
// Game loop
var rotation: f32 = 0;
while (!window.windowShouldClose()) {
if (input.isKeyDown(Constants.KEY_ESCAPE)) {
break;
}
const micro_time = wgi.getMicroTime();
const this_frame_time = micro_time;
const deltaTime = @intToFloat(f32, this_frame_time - last_frame_time) * 0.000001;
last_frame_time = this_frame_time;
if (this_frame_time - last_fps_print_time >= 990000) {
warn("{}\n", .{fps_count + 1});
fps_count = 0;
last_fps_print_time = this_frame_time;
} else {
fps_count += 1;
}
if (input.isKeyDown(Constants.KEY_LEFT_BRACKET)) {
brightness -= 0.08;
if (brightness < 0.0) {
brightness = 0.0;
}
} else if (input.isKeyDown(Constants.KEY_RIGHT_BRACKET)) {
brightness += 0.08;
}
if (input.isKeyDown(Constants.KEY_COMMA)) {
contrast -= 0.01;
if (contrast < 0.0) {
contrast = 0.0;
}
} else if (input.isKeyDown(Constants.KEY_PERIOD)) {
contrast += 0.01;
}
render.setImageCorrection(brightness, contrast);
// FPS-style camera rotation
const mouse_pos = input.getMousePosition();
if (!cursor_enabled) {
camera_rotation_euler[1] += -0.1 * deltaTime * @intToFloat(f32, mouse_pos[0] - mouse_pos_prev[0]);
camera_rotation_euler[0] += 0.1 * deltaTime * @intToFloat(f32, mouse_pos[1] - mouse_pos_prev[1]);
const max_angle = 1.4;
if (camera_rotation_euler[0] > max_angle) {
camera_rotation_euler[0] = max_angle;
} else if (camera_rotation_euler[0] < -max_angle) {
camera_rotation_euler[0] = -max_angle;
}
}
mouse_pos_prev = mouse_pos;
// FPS-style movement
var speed: f32 = 1.0;
if (input.isKeyDown(Constants.KEY_LEFT_CONTROL)) {
speed = 10.0;
}
if (input.isKeyDown(Constants.KEY_W)) {
moveNoUp(0.0, 0.0, -1.875 * deltaTime * speed);
} else if (input.isKeyDown(Constants.KEY_S)) {
moveNoUp(0.0, 0.0, 1.875 * deltaTime * speed);
}
if (input.isKeyDown(Constants.KEY_D)) {
moveNoUp(1.875 * deltaTime * speed, 0.0, 0.0);
} else if (input.isKeyDown(Constants.KEY_A)) {
moveNoUp(-1.875 * deltaTime * speed, 0.0, 0.0);
}
// Levitation (does not take camera rotation into account)
if (input.isKeyDown(Constants.KEY_SPACE)) {
camera_position[1] += 1.875 * deltaTime * speed;
} else if (input.isKeyDown(Constants.KEY_LEFT_SHIFT)) {
camera_position[1] -= 1.875 * deltaTime * speed;
}
// Transforms must be done in this order:
// Scale
// Rotate x
// Rotate y
// Rotate z
// Translation
m = Matrix(f32, 4).rotateX(camera_rotation_euler[0]);
m = m.mul(Matrix(f32, 4).rotateY(camera_rotation_euler[1]));
m = m.mul(Matrix(f32, 4).rotateZ(camera_rotation_euler[2]));
m = m.mul(Matrix(f32, 4).translate(Vector(f32, 3).init(camera_position)));
camera.setTransform(m);
rotation += deltaTime;
m = Matrix(f32, 4).rotateX(0.3);
m = m.mul(Matrix(f32, 4).translate(Vector(f32, 3).init([3]f32{ 0.0, 0.0, 10.0 })));
m = m.mul(Matrix(f32, 4).rotateY(rotation));
light.setTransform(m);
try render.render(&root_object, micro_time, c_allocator);
window.swapBuffers();
window.pollEvents();
}
} | src/Demo3.zig |
const os = @import("root").os;
pub const InterruptState = bool;
pub fn get_and_disable_interrupts() InterruptState {
// Get interrupt mask flag
var daif = asm volatile("MRS %[daif_val], DAIF" : [daif_val] "=r" (-> u64));
// Set the flag
asm volatile("MSR DAIFSET, 2" ::: "memory");
// Check if it was set
return (daif >> 7) & 1 == 0;
}
pub fn set_interrupts(s: InterruptState) void {
if(s) {
// Enable interrupts
asm volatile("MSR DAIFCLR, 2" ::: "memory");
} else {
// Disable interrupts
asm volatile("MSR DAIFSET, 2" ::: "memory");
}
}
pub const InterruptFrame = struct {
spsr: u64,
pc: u64,
x31: u64,
x30: u64,
x29: u64,
x28: u64,
x27: u64,
x26: u64,
x25: u64,
x24: u64,
x23: u64,
x22: u64,
x21: u64,
x20: u64,
x19: u64,
x18: u64,
x17: u64,
x16: u64,
x15: u64,
x14: u64,
x13: u64,
x12: u64,
x11: u64,
x10: u64,
x9: u64,
x8: u64,
x7: u64,
x6: u64,
x5: u64,
x4: u64,
x3: u64,
x2: u64,
x1: u64,
x0: u64,
sp: u64,
_: u64,
pub fn dump(self: *const @This()) void {
os.log("FRAME DUMP:\n", .{});
os.log("X0 ={x:0>16} X1 ={x:0>16} X2 ={x:0>16} X3 ={x:0>16}\n", .{self.x0, self.x1, self.x2, self.x3});
os.log("X4 ={x:0>16} X5 ={x:0>16} X6 ={x:0>16} X7 ={x:0>16}\n", .{self.x4, self.x5, self.x6, self.x7});
os.log("X8 ={x:0>16} X9 ={x:0>16} X10={x:0>16} X11={x:0>16}\n", .{self.x8, self.x9, self.x10, self.x11});
os.log("X12={x:0>16} X13={x:0>16} X14={x:0>16} X15={x:0>16}\n", .{self.x12, self.x13, self.x14, self.x15});
os.log("X16={x:0>16} X17={x:0>16} X18={x:0>16} X19={x:0>16}\n", .{self.x16, self.x17, self.x18, self.x19});
os.log("X20={x:0>16} X21={x:0>16} X22={x:0>16} X23={x:0>16}\n", .{self.x20, self.x21, self.x22, self.x23});
os.log("X24={x:0>16} X25={x:0>16} X26={x:0>16} X27={x:0>16}\n", .{self.x24, self.x25, self.x26, self.x27});
os.log("X28={x:0>16} X29={x:0>16} X30={x:0>16} X31={x:0>16}\n", .{self.x28, self.x29, self.x30, self.x31});
os.log("PC ={x:0>16} SP ={x:0>16} SPSR={x:0>16}\n", .{self.pc, self.sp, self.spsr});
}
pub fn trace_stack(self: *const @This()) void {
os.lib.debug.dump_frame(self.x29, self.pc);
}
};
export fn interrupt_common() callconv(.Naked) void {
asm volatile(
\\STP X3, X2, [SP, #-0x10]!
\\STP X5, X4, [SP, #-0x10]!
\\STP X7, X6, [SP, #-0x10]!
\\STP X9, X8, [SP, #-0x10]!
\\STP X11, X10, [SP, #-0x10]!
\\STP X13, X12, [SP, #-0x10]!
\\STP X15, X14, [SP, #-0x10]!
\\STP X17, X16, [SP, #-0x10]!
\\STP X19, X18, [SP, #-0x10]!
\\STP X21, X20, [SP, #-0x10]!
\\STP X23, X22, [SP, #-0x10]!
\\STP X25, X24, [SP, #-0x10]!
\\STP X27, X26, [SP, #-0x10]!
\\STP X29, X28, [SP, #-0x10]!
\\STP X31, X30, [SP, #-0x10]!
\\MRS X0, SPSR_EL1
\\MRS X1, ELR_EL1
\\STP X0, X1, [SP, #-0x10]!
\\MOV X0, SP
\\BL interrupt_handler
\\LDP X0, X1, [SP], 0x10
\\MSR ELR_EL1, X1
\\MSR SPSR_EL1, X1
\\LDP X31, X30, [SP], 0x10
\\LDP X29, X28, [SP], 0x10
\\LDP X27, X26, [SP], 0x10
\\LDP X25, X24, [SP], 0x10
\\LDP X23, X22, [SP], 0x10
\\LDP X21, X20, [SP], 0x10
\\LDP X19, X18, [SP], 0x10
\\LDP X17, X16, [SP], 0x10
\\LDP X15, X14, [SP], 0x10
\\LDP X13, X12, [SP], 0x10
\\LDP X11, X10, [SP], 0x10
\\LDP X9, X8, [SP], 0x10
\\LDP X7, X6, [SP], 0x10
\\LDP X5, X4, [SP], 0x10
\\LDP X3, X2, [SP], 0x10
\\
\\// Critical section
\\MSR DAIFSET, #0xF
\\
\\// Make the current SP the interrupt stack
\\MSR SPSel, 1
\\MRS X0, SP_EL0
\\MOV SP, X0
\\
\\// Restore old stack pointer
\\LDP X1, XZR, [SP, #0x10] // Load stack poiner
\\MSR SP_EL0, X1 // Write old stack pointer to SP0
\\LDP X1, X0, [SP], 0x20
\\MSR SPSel, 0
\\ERET
);
unreachable;
}
/// The vector which uses the already selected interrupt stack
export fn interrupt_irq_stack() callconv(.Naked) void {
asm volatile(
\\STP X1, X0, [SP, #-0x20]!
\\MRS X1, SP_EL0
\\STP X1, XZR, [SP, #0x10] // Store old stack pointer
\\B interrupt_common
);
unreachable;
}
/// The vector which switches to the per-CPU scheduler stack
export fn interrupt_sched_stack() callconv(.Naked) void {
asm volatile(
\\STP X0, X1, [SP, #-0x10]!
\\MRS X0, TPIDR_EL1 // Get the current cpu struct
\\LDR X0, [X0, %[sched_stack_offset]] // Get the CPU scheduler stack
\\MRS X1, SP_EL0
\\STP X1, XZR, [X0, #-0x10]! // Push SP0 onto the scheduler stack
\\MSR SP_EL0, X0 // Use our new, shiny call stack
\\LDP X0, X1, [SP], 0x10
\\MSR SPSel, #0 // Switch to it
\\STP X1, X0, [SP, #-0x10]!
\\B interrupt_common
:
: [sched_stack_offset] "i" (@as(usize, @byteOffsetOf(os.platform.smp.CoreData, "sched_stack")))
);
unreachable;
}
/// The vector which switches to the per-task syscall stack
export fn interrupt_syscall_stack() callconv(.Naked) void {
asm volatile(
\\STP X0, X1, [SP, #-0x10]!
\\MRS X0, TPIDR_EL1 // Get the current cpu struct
\\LDR X0, [X0, %[task_offset]] // Get the task
\\LDR X0, [X0, %[syscall_stack_offset]]
\\MRS X1, SP_EL0
\\STP X1, XZR, [X0, #-0x10]! // Push SP0 onto the syscall stack
\\MSR SP_EL0, X0 // Use our new, shiny syscall stack
\\LDP X0, X1, [SP], 0x10
\\MSR SPSel, #0 // Switch to it
\\STP X1, X0, [SP, #-0x10]!
\\B interrupt_common
:
: [task_offset] "i" (@as(usize, @byteOffsetOf(os.platform.smp.CoreData, "current_task")))
, [syscall_stack_offset] "i" (@as(usize, @byteOffsetOf(os.thread.Task, "stack")))
);
unreachable;
}
/// The handler for everything else, which should cause some kind
/// of panic or similar.
export fn unhandled_vector() callconv(.Naked) void {
// We don't plan on returning, calling the scheduler
// nor enabling interrupts in this handler one, so
// we can just use any handler here
asm volatile(
\\B interrupt_irq_stack
);
unreachable;
}
comptime {
asm(
\\.section .text.evt
\\.balign 0x800
\\.global exception_vector_table; exception_vector_table:
\\ // Normal IRQs/scheduler calls from within kernel
\\.balign 0x80; B interrupt_sched_stack // curr_el_sp0_sync
\\.balign 0x80; B interrupt_irq_stack // curr_el_sp0_irq
\\.balign 0x80; B interrupt_irq_stack // curr_el_sp0_fiq
\\.balign 0x80; B unhandled_vector // curr_el_sp0_serror
\\ // The following 4 are unsupported as we only use spx with interrupts disabled,
\\ // in a context where a fail probably shouldn't be handled either.
\\.balign 0x80; B unhandled_vector // curr_el_spx_sync
\\.balign 0x80; B unhandled_vector // curr_el_spx_irq
\\.balign 0x80; B unhandled_vector // curr_el_spx_fiq
\\.balign 0x80; B unhandled_vector // curr_el_spx_serror
\\ // Userspace IRQs or syscalls
\\.balign 0x80; B interrupt_syscall_stack // lower_el_aarch64_sync
\\.balign 0x80; B interrupt_irq_stack // lower_el_aarch64_irq
\\.balign 0x80; B interrupt_irq_stack // lower_el_aarch64_fiq
\\.balign 0x80; B interrupt_syscall_stack // lower_el_aarch64_serror
\\ // 32 bit Userspace IRQs or syscalls
\\.balign 0x80; B interrupt_syscall_stack // lower_el_aarch32_sync
\\.balign 0x80; B interrupt_irq_stack // lower_el_aarch32_irq
\\.balign 0x80; B interrupt_irq_stack // lower_el_aarch32_fiq
\\.balign 0x80; B interrupt_syscall_stack // lower_el_aarch32_serror
);
}
extern const exception_vector_table: [0x800]u8;
pub fn install_vector_table() void {
asm volatile(
\\MSR VBAR_EL1, %[evt]
:
: [evt] "r" (&exception_vector_table)
);
}
export fn interrupt_handler(frame: *InterruptFrame) void {
const esr = asm volatile("MRS %[esr], ESR_EL1" : [esr] "=r" (-> u64));
const ec = (esr >> 26) & 0x3f;
const iss = esr & 0x1ffffff;
if(ec == 0b111100) {
os.log("BRK instruction execution in AArch64 state\n", .{});
os.platform.hang();
}
switch(ec) {
else => @panic("Unknown EC!"),
0b00000000 => @panic("Unknown reason in EC!"),
0b00100101 => {
const far = asm volatile("MRS %[esr], FAR_EL1" : [esr] "=r" (-> u64));
const wnr = (iss >> 6) & 1;
const dfsc = iss & 0x3f;
// Assume present == !translation fault
const present = (dfsc & 0b111100) != 0b000100;
// addr: usize, present: bool, access: PageFaultAccess, frame: anytype
os.platform.page_fault(far, present, if(wnr == 1) .Write else .Read, frame);
},
0b00100001 => @panic("Instruction fault without change in exception level"),
0b00010101 => {
// SVC instruction execution in AArch64 state
// Figure out which call this is
switch(@truncate(u16, iss)) {
else => @panic("Unknown SVC"),
'B' => os.thread.preemption.bootstrap(frame),
'Y' => os.thread.preemption.wait_yield(frame),
}
},
}
}
pub fn set_interrupt_stack(int_stack: usize) void {
const current_stack = asm volatile("MRS %[res], SPSel" : [res]"=r"(->u64));
if(current_stack != 0) @panic("Cannot set interrupt stack while using it!");
asm volatile(
\\ MSR SPSel, #1
\\ MOV SP, %[int_stack]
\\ MSR SPSel, #0
:
: [int_stack] "r" (int_stack)
);
} | src/platform/aarch64/interrupts.zig |
const std = @import("std");
const math = std.math;
const zp = @import("zplay");
const dig = zp.deps.dig;
const nvg = zp.deps.nvg;
const nsvg = zp.deps.nsvg;
var font_normal: i32 = undefined;
var font_bold: i32 = undefined;
var font_icons: i32 = undefined;
var font_emoji: i32 = undefined;
var images: [12]nvg.Image = undefined;
var tiger: nsvg.SVG = undefined;
fn init(ctx: *zp.Context) anyerror!void {
std.log.info("game init", .{});
// init imgui
try dig.init(ctx.window);
// init nanovg context
try nvg.init(nvg.c.NVG_ANTIALIAS | nvg.c.NVG_STENCIL_STROKES);
var i: usize = 0;
var buf: [64]u8 = undefined;
while (i < 12) : (i += 1) {
var path = try std.fmt.bufPrintZ(&buf, "assets/images/image{d}.jpg", .{i + 1});
images[i] = nvg.createImage(path, .{});
if (images[i].handle == 0) {
std.debug.panic("load image({s}) failed!", .{buf});
}
}
font_icons = nvg.createFont("icons", "assets/entypo.ttf");
if (font_icons == -1) {
std.debug.panic("load font failed!", .{});
}
font_normal = nvg.createFont("sans", "assets/Roboto-Regular.ttf");
if (font_normal == -1) {
std.debug.panic("load font failed!", .{});
}
font_bold = nvg.createFont("sans", "assets/Roboto-Bold.ttf");
if (font_bold == -1) {
std.debug.panic("load font failed!", .{});
}
font_emoji = nvg.createFont("emoji", "assets/NotoEmoji-Regular.ttf");
if (font_emoji == -1) {
std.debug.panic("load font failed!", .{});
}
_ = nvg.addFallbackFontId(font_normal, font_emoji);
_ = nvg.addFallbackFontId(font_bold, font_emoji);
tiger = nsvg.loadFile("assets/23.svg", null, null) orelse unreachable;
}
fn loop(ctx: *zp.Context) void {
while (ctx.pollEvent()) |e| {
_ = dig.processEvent(e);
switch (e) {
.keyboard_event => |key| {
if (key.trigger_type == .up) {
switch (key.scan_code) {
.escape => ctx.kill(),
.f1 => ctx.toggleFullscreeen(null),
else => {},
}
}
},
.quit_event => ctx.kill(),
else => {},
}
}
var width: u32 = undefined;
var height: u32 = undefined;
var fwidth: u32 = undefined;
var fheight: u32 = undefined;
ctx.getWindowSize(&width, &height);
ctx.graphics.getDrawableSize(ctx.window, &fwidth, &fheight);
var mouse_state = ctx.getMouseState();
var xpos = @intToFloat(f32, mouse_state.x);
var ypos = @intToFloat(f32, mouse_state.y);
ctx.graphics.setViewport(0, 0, fwidth, fheight);
ctx.graphics.clear(true, true, true, [_]f32{ 0.3, 0.3, 0.32, 1.0 });
dig.beginFrame();
defer dig.endFrame();
dig.showMetricsWindow(null);
nvg.beginFrame(
@intToFloat(f32, width),
@intToFloat(f32, height),
@intToFloat(f32, fwidth) / @intToFloat(f32, width),
);
defer nvg.endFrame();
drawEyes(@intToFloat(f32, fwidth) - 250, 50, 150, 100, xpos, ypos, ctx.tick);
drawGraph(0, @intToFloat(f32, fheight) / 2, @intToFloat(f32, fwidth), @intToFloat(f32, fheight) / 2, ctx.tick);
drawColorwheel(@intToFloat(f32, fwidth) - 300, @intToFloat(f32, fheight) - 300, 250, 250, ctx.tick);
drawLines(120, @intToFloat(f32, fheight) - 50, 600, 50, ctx.tick);
drawWidths(10, 50, 30);
drawCaps(10, 300, 30);
drawScissor(50, @intToFloat(f32, fheight) - 80, ctx.tick);
// Form
var x: f32 = 60;
var y: f32 = 95;
drawLabel("Login", x, y, 280, 20);
y += 25;
drawLabel("Diameter", x, y, 280, 20);
// Thumbnails box
drawThumbnails(500, 50, 160, 300, ctx.tick);
// draw svg
nvg.save();
nvg.translate(100, 100);
nvg.scale(0.5, 0.5);
nvg.svg(tiger);
nvg.restore();
}
fn drawEyes(x: f32, y: f32, w: f32, h: f32, mx: f32, my: f32, t: f32) void {
var gloss: nvg.Paint = undefined;
var bg: nvg.Paint = undefined;
var dx: f32 = undefined;
var dy: f32 = undefined;
var d: f32 = undefined;
const ex = w * 0.23;
const ey = h * 0.5;
const lx = x + ex;
const ly = y + ey;
const rx = x + w - ex;
const ry = y + ey;
const br = if (ex < ey) ex * 0.5 else ey * 0.5;
const blink = 1 - math.pow(f32, math.sin(t * 0.5), 200) * 0.8;
bg = nvg.linearGradient(x, y + h * 0.5, x + w * 0.1, y + h, nvg.rgba(0, 0, 0, 32), nvg.rgba(0, 0, 0, 16));
nvg.beginPath();
nvg.ellipse(lx + 3.0, ly + 16.0, ex, ey);
nvg.ellipse(rx + 3.0, ry + 16.0, ex, ey);
nvg.fillPaint(bg);
nvg.fill();
bg = nvg.linearGradient(x, y + h * 0.25, x + w * 0.1, y + h, nvg.rgba(220, 220, 220, 255), nvg.rgba(128, 128, 128, 255));
nvg.beginPath();
nvg.ellipse(lx, ly, ex, ey);
nvg.ellipse(rx, ry, ex, ey);
nvg.fillPaint(bg);
nvg.fill();
dx = (mx - rx) / (ex * 10);
dy = (my - ry) / (ey * 10);
d = math.sqrt(dx * dx + dy * dy);
if (d > 1.0) {
dx /= d;
dy /= d;
}
dx *= ex * 0.4;
dy *= ey * 0.5;
nvg.beginPath();
nvg.ellipse(lx + dx, ly + dy + ey * 0.25 * (1 - blink), br, br * blink);
nvg.fillColor(nvg.rgba(32, 32, 32, 255));
nvg.fill();
dx = (mx - rx) / (ex * 10);
dy = (my - ry) / (ey * 10);
d = math.sqrt(dx * dx + dy * dy);
if (d > 1.0) {
dx /= d;
dy /= d;
}
dx *= ex * 0.4;
dy *= ey * 0.5;
nvg.beginPath();
nvg.ellipse(rx + dx, ry + dy + ey * 0.25 * (1 - blink), br, br * blink);
nvg.fillColor(nvg.rgba(32, 32, 32, 255));
nvg.fill();
gloss = nvg.radialGradient(lx - ex * 0.25, ly - ey * 0.5, ex * 0.1, ex * 0.75, nvg.rgba(255, 255, 255, 128), nvg.rgba(255, 255, 255, 0));
nvg.beginPath();
nvg.ellipse(lx, ly, ex, ey);
nvg.fillPaint(gloss);
nvg.fill();
gloss = nvg.radialGradient(rx - ex * 0.25, ry - ey * 0.5, ex * 0.1, ex * 0.75, nvg.rgba(255, 255, 255, 128), nvg.rgba(255, 255, 255, 0));
nvg.beginPath();
nvg.ellipse(rx, ry, ex, ey);
nvg.fillPaint(gloss);
nvg.fill();
}
fn drawGraph(x: f32, y: f32, w: f32, h: f32, t: f32) void {
var bg: nvg.Paint = undefined;
var samples: [6]f32 = undefined;
var sx: [6]f32 = undefined;
var sy: [6]f32 = undefined;
var dx = w / 5.0;
var i: usize = undefined;
samples[0] = (1 + math.sin(t * 1.2345 + math.cos(t * 0.33457) * 0.44)) * 0.5;
samples[1] = (1 + math.sin(t * 0.68363 + math.cos(t * 1.3) * 1.55)) * 0.5;
samples[2] = (1 + math.sin(t * 1.1642 + math.cos(t * 0.33457) * 1.24)) * 0.5;
samples[3] = (1 + math.sin(t * 0.56345 + math.cos(t * 1.63) * 0.14)) * 0.5;
samples[4] = (1 + math.sin(t * 1.6245 + math.cos(t * 0.254) * 0.3)) * 0.5;
samples[5] = (1 + math.sin(t * 0.345 + math.cos(t * 0.03) * 0.6)) * 0.5;
i = 0;
while (i < 6) : (i += 1) {
sx[i] = x + @intToFloat(f32, i) * dx;
sy[i] = y + h * samples[i] * 0.8;
}
// Graph background
bg = nvg.linearGradient(x, y, x, y + h, nvg.rgba(0, 160, 192, 0), nvg.rgba(0, 160, 192, 64));
nvg.beginPath();
nvg.moveTo(sx[0], sy[0]);
i = 1;
while (i < 6) : (i += 1) {
nvg.bezierTo(sx[i - 1] + dx * 0.5, sy[i - 1], sx[i] - dx * 0.5, sy[i], sx[i], sy[i]);
}
nvg.lineTo(x + w, y + h);
nvg.lineTo(x, y + h);
nvg.fillPaint(bg);
nvg.fill();
// Graph line
nvg.beginPath();
nvg.moveTo(sx[0], sy[0] + 2);
i = 1;
while (i < 6) : (i += 1) {
nvg.bezierTo(sx[i - 1] + dx * 0.5, sy[i - 1] + 2, sx[i] - dx * 0.5, sy[i] + 2, sx[i], sy[i] + 2);
}
nvg.strokeColor(nvg.rgba(0, 0, 0, 32));
nvg.strokeWidth(3.0);
nvg.stroke();
nvg.beginPath();
nvg.moveTo(sx[0], sy[0]);
i = 1;
while (i < 6) : (i += 1) {
nvg.bezierTo(sx[i - 1] + dx * 0.5, sy[i - 1], sx[i] - dx * 0.5, sy[i], sx[i], sy[i]);
}
nvg.strokeColor(nvg.rgba(0, 160, 192, 255));
nvg.strokeWidth(3.0);
nvg.stroke();
// Graph sample pos
i = 0;
while (i < 6) : (i += 1) {
bg = nvg.radialGradient(sx[i], sy[i] + 2, 3.0, 8.0, nvg.rgba(0, 0, 0, 32), nvg.rgba(0, 0, 0, 0));
nvg.beginPath();
nvg.rect(sx[i] - 10, sy[i] - 10 + 2, 20, 20);
nvg.fillPaint(bg);
nvg.fill();
}
nvg.beginPath();
i = 0;
while (i < 6) : (i += 1) {
nvg.circle(sx[i], sy[i], 4.0);
}
nvg.fillColor(nvg.rgba(0, 160, 192, 255));
nvg.fill();
nvg.beginPath();
i = 0;
while (i < 6) : (i += 1) {
nvg.circle(sx[i], sy[i], 2.0);
}
nvg.fillColor(nvg.rgba(220, 220, 220, 255));
nvg.fill();
nvg.strokeWidth(1.0);
}
fn drawColorwheel(x: f32, y: f32, w: f32, h: f32, t: f32) void {
var i: i32 = undefined;
var r0: f32 = undefined;
var r1: f32 = undefined;
var ax: f32 = undefined;
var ay: f32 = undefined;
var bx: f32 = undefined;
var by: f32 = undefined;
var cx: f32 = undefined;
var cy: f32 = undefined;
var aeps: f32 = undefined;
var r: f32 = undefined;
var hue: f32 = math.sin(t * 0.12);
var paint: nvg.Paint = undefined;
nvg.save();
cx = x + w * 0.5;
cy = y + h * 0.5;
r1 = (if (w < h) w * 0.5 else h * 0.5) - 5.0;
r0 = r1 - 20.0;
aeps = 0.5 / r1; // half a pixel arc length in radians (2pi cancels out).
i = 0;
while (i < 6) : (i += 1) {
var a0: f32 = @intToFloat(f32, i) / 6.0 * math.pi * 2.0 - aeps;
var a1: f32 = (@intToFloat(f32, i) + 1.0) / 6.0 * math.pi * 2.0 + aeps;
nvg.beginPath();
nvg.arc(cx, cy, r0, a0, a1, .cw);
nvg.arc(cx, cy, r1, a1, a0, .ccw);
nvg.closePath();
ax = cx + math.cos(a0) * (r0 + r1) * 0.5;
ay = cy + math.sin(a0) * (r0 + r1) * 0.5;
bx = cx + math.cos(a1) * (r0 + r1) * 0.5;
by = cy + math.sin(a1) * (r0 + r1) * 0.5;
paint = nvg.linearGradient(ax, ay, bx, by, nvg.hsla(a0 / (math.pi * 2.0), 1.0, 0.55, 255), nvg.hsla(a1 / (math.pi * 2.0), 1.0, 0.55, 255));
nvg.fillPaint(paint);
nvg.fill();
}
nvg.beginPath();
nvg.circle(cx, cy, r0 - 0.5);
nvg.circle(cx, cy, r1 + 0.5);
nvg.strokeColor(nvg.rgba(0, 0, 0, 64));
nvg.strokeWidth(1.0);
nvg.stroke();
// Selector
nvg.save();
nvg.translate(cx, cy);
nvg.rotate(hue * math.pi * 2);
// Marker on
nvg.strokeWidth(2.0);
nvg.beginPath();
nvg.rect(r0 - 1, -3, r1 - r0 + 2, 6);
nvg.strokeColor(nvg.rgba(255, 255, 255, 192));
nvg.stroke();
paint = nvg.boxGradient(r0 - 3, -5, r1 - r0 + 6, 10, 2, 4, nvg.rgba(0, 0, 0, 128), nvg.rgba(0, 0, 0, 0));
nvg.beginPath();
nvg.rect(r0 - 2 - 10, -4 - 10, r1 - r0 + 4 + 20, 8 + 20);
nvg.rect(r0 - 2, -4, r1 - r0 + 4, 8);
nvg.pathWinding(.cw);
nvg.fillPaint(paint);
nvg.fill();
// Center triangle
r = r0 - 6;
ax = math.cos(120.0 / 180.0 * @as(f32, math.pi)) * r;
ay = math.sin(120.0 / 180.0 * @as(f32, math.pi)) * r;
bx = math.cos(-120.0 / 180.0 * @as(f32, math.pi)) * r;
by = math.sin(-120.0 / 180.0 * @as(f32, math.pi)) * r;
nvg.beginPath();
nvg.moveTo(r, 0);
nvg.lineTo(ax, ay);
nvg.lineTo(bx, by);
nvg.closePath();
paint = nvg.linearGradient(r, 0, ax, ay, nvg.hsla(hue, 1.0, 0.5, 255), nvg.rgba(255, 255, 255, 255));
nvg.fillPaint(paint);
nvg.fill();
paint = nvg.linearGradient((r + ax) * 0.5, (0 + ay) * 0.5, bx, by, nvg.rgba(0, 0, 0, 0), nvg.rgba(0, 0, 0, 255));
nvg.fillPaint(paint);
nvg.fill();
nvg.strokeColor(nvg.rgba(0, 0, 0, 64));
nvg.stroke();
// Select circle on triangle
ax = math.cos(120.0 / 180.0 * @as(f32, math.pi)) * r * 0.3;
ay = math.sin(120.0 / 180.0 * @as(f32, math.pi)) * r * 0.4;
nvg.strokeWidth(2.0);
nvg.beginPath();
nvg.circle(ax, ay, 5);
nvg.strokeColor(nvg.rgba(255, 255, 255, 192));
nvg.stroke();
paint = nvg.radialGradient(ax, ay, 7, 9, nvg.rgba(0, 0, 0, 64), nvg.rgba(0, 0, 0, 0));
nvg.beginPath();
nvg.rect(ax - 20, ay - 20, 40, 40);
nvg.circle(ax, ay, 7);
nvg.pathWinding(.cw);
nvg.fillPaint(paint);
nvg.fill();
nvg.restore();
nvg.restore();
}
fn drawLines(x: f32, y: f32, w: f32, h: f32, t: f32) void {
_ = h;
var i: i32 = undefined;
var j: i32 = undefined;
var pad: f32 = 5.0;
var s: f32 = w / 9.0 - pad * 2;
var pts: [4 * 2]f32 = undefined;
var fx: f32 = undefined;
var fy: f32 = undefined;
var joins: [3]nvg.LineJoin = .{ .miter, .round, .bevel };
var caps: [3]nvg.LineCap = .{ .butt, .round, .square };
nvg.save();
pts[0] = -s * 0.25 + math.cos(t * 0.3) * s * 0.5;
pts[1] = math.sin(t * 0.3) * s * 0.5;
pts[2] = -s * 0.25;
pts[3] = 0;
pts[4] = s * 0.25;
pts[5] = 0;
pts[6] = s * 0.25 + math.cos(-t * 0.3) * s * 0.5;
pts[7] = math.sin(-t * 0.3) * s * 0.5;
i = 0;
while (i < 3) : (i += 1) {
j = 0;
while (j < 3) : (j += 1) {
fx = x + s * 0.5 + @intToFloat(f32, i * 3 + j) / 9.0 * w + pad;
fy = y - s * 0.5 + pad;
nvg.lineCap(caps[@intCast(usize, i)]);
nvg.lineJoin(joins[@intCast(usize, j)]);
nvg.strokeWidth(s * 0.3);
nvg.strokeColor(nvg.rgba(0, 0, 0, 160));
nvg.beginPath();
nvg.moveTo(fx + pts[0], fy + pts[1]);
nvg.lineTo(fx + pts[2], fy + pts[3]);
nvg.lineTo(fx + pts[4], fy + pts[5]);
nvg.lineTo(fx + pts[6], fy + pts[7]);
nvg.stroke();
nvg.lineCap(.butt);
nvg.lineJoin(.bevel);
nvg.strokeWidth(1.0);
nvg.strokeColor(nvg.rgba(0, 192, 255, 255));
nvg.beginPath();
nvg.moveTo(fx + pts[0], fy + pts[1]);
nvg.lineTo(fx + pts[2], fy + pts[3]);
nvg.lineTo(fx + pts[4], fy + pts[5]);
nvg.lineTo(fx + pts[6], fy + pts[7]);
nvg.stroke();
}
}
nvg.restore();
}
fn drawWidths(x: f32, y: f32, width: f32) void {
var i: i32 = undefined;
nvg.save();
nvg.strokeColor(nvg.rgba(0, 0, 0, 255));
i = 0;
var oy = y;
while (i < 20) : (i += 1) {
var w: f32 = (@intToFloat(f32, i) + 0.5) * 0.1;
nvg.strokeWidth(w);
nvg.beginPath();
nvg.moveTo(x, oy);
nvg.lineTo(x + width, oy + width * 0.3);
nvg.stroke();
oy += 10;
}
nvg.restore();
}
fn drawCaps(x: f32, y: f32, width: f32) void {
var i: i32 = undefined;
var caps: [3]nvg.LineCap = .{ .butt, .round, .square };
var line_width: f32 = 8.0;
nvg.save();
nvg.beginPath();
nvg.rect(x - line_width / 2, y, width + line_width, 40);
nvg.fillColor(nvg.rgba(255, 255, 255, 32));
nvg.fill();
nvg.beginPath();
nvg.rect(x, y, width, 40);
nvg.fillColor(nvg.rgba(255, 255, 255, 32));
nvg.fill();
nvg.strokeWidth(line_width);
i = 0;
while (i < 3) : (i += 1) {
nvg.lineCap(caps[@intCast(usize, i)]);
nvg.strokeColor(nvg.rgba(0, 0, 0, 255));
nvg.beginPath();
nvg.moveTo(x, y + @intToFloat(f32, i * 10) + 5);
nvg.lineTo(x + width, y + @intToFloat(f32, i * 10) + 5);
nvg.stroke();
}
nvg.restore();
}
fn drawScissor(x: f32, y: f32, t: f32) void {
nvg.save();
// Draw first rect and set scissor to it's area.
nvg.translate(x, y);
nvg.rotate(nvg.degToRad(5));
nvg.beginPath();
nvg.rect(-20, -20, 60, 40);
nvg.fillColor(nvg.rgba(255, 0, 0, 255));
nvg.fill();
nvg.scissor(-20, -20, 60, 40);
// Draw second rectangle with offset and rotation.
nvg.translate(40, 0);
nvg.rotate(t);
// Draw the intended second rectangle without any scissoring.
nvg.save();
nvg.resetScissor();
nvg.beginPath();
nvg.rect(-20, -10, 60, 30);
nvg.fillColor(nvg.rgba(255, 128, 0, 64));
nvg.fill();
nvg.restore();
// Draw second rectangle with combined scissoring.
nvg.intersectScissor(-20, -10, 60, 30);
nvg.beginPath();
nvg.rect(-20, -10, 60, 30);
nvg.fillColor(nvg.rgba(255, 128, 0, 255));
nvg.fill();
nvg.restore();
}
fn drawLabel(text: []const u8, x: f32, y: f32, w: f32, h: f32) void {
_ = w;
nvg.fontSize(15.0);
nvg.fontFace("sans");
nvg.fillColor(nvg.rgba(255, 255, 255, 128));
nvg.textAlign(.{ .horizontal = .left, .vertical = .middle });
_ = nvg.text(x, y + h * 0.5, text);
}
fn drawSpinner(cx: f32, cy: f32, r: f32, t: f32) void {
var a0: f32 = 0.0 + t * 6;
var a1: f32 = math.pi + t * 6;
var r0: f32 = r;
var r1: f32 = r * 0.75;
var ax: f32 = undefined;
var ay: f32 = undefined;
var bx: f32 = undefined;
var by: f32 = undefined;
var paint: nvg.Paint = undefined;
nvg.save();
nvg.beginPath();
nvg.arc(cx, cy, r0, a0, a1, .cw);
nvg.arc(cx, cy, r1, a1, a0, .ccw);
nvg.closePath();
ax = cx + math.cos(a0) * (r0 + r1) * 0.5;
ay = cy + math.sin(a0) * (r0 + r1) * 0.5;
bx = cx + math.cos(a1) * (r0 + r1) * 0.5;
by = cy + math.sin(a1) * (r0 + r1) * 0.5;
paint = nvg.linearGradient(ax, ay, bx, by, nvg.rgba(0, 0, 0, 0), nvg.rgba(0, 0, 0, 128));
nvg.fillPaint(paint);
nvg.fill();
nvg.restore();
}
fn drawThumbnails(x: f32, y: f32, w: f32, h: f32, t: f32) void {
var cornerRadius: f32 = 3.0;
var shadowPaint: nvg.Paint = undefined;
var imgPaint: nvg.Paint = undefined;
var fadePaint: nvg.Paint = undefined;
var ix: f32 = undefined;
var iy: f32 = undefined;
var iw: f32 = undefined;
var ih: f32 = undefined;
var thumb: f32 = 60.0;
var arry: f32 = 30.5;
var imgw: u32 = undefined;
var imgh: u32 = undefined;
var stackh: f32 = @intToFloat(f32, images.len) / 2 * (thumb + 10) + 10;
var i: usize = undefined;
var u: f32 = (1 + math.cos(t * 0.5)) * 0.5;
var ua: f32 = (1 - math.cos(t * 0.2)) * 0.5;
var scrollh: f32 = undefined;
var dv: f32 = undefined;
nvg.save();
// Drop shadow
shadowPaint = nvg.boxGradient(x, y + 4, w, h, cornerRadius * 2, 20, nvg.rgba(0, 0, 0, 128), nvg.rgba(0, 0, 0, 0));
nvg.beginPath();
nvg.rect(x - 10, y - 10, w + 20, h + 30);
nvg.roundedRect(x, y, w, h, cornerRadius);
nvg.pathWinding(.cw);
nvg.fillPaint(shadowPaint);
nvg.fill();
// Window
nvg.beginPath();
nvg.roundedRect(x, y, w, h, cornerRadius);
nvg.moveTo(x - 10, y + arry);
nvg.lineTo(x + 1, y + arry - 11);
nvg.lineTo(x + 1, y + arry + 11);
nvg.fillColor(nvg.rgba(200, 200, 200, 255));
nvg.fill();
nvg.save();
nvg.scissor(x, y, w, h);
nvg.translate(0, -(stackh - h) * u);
dv = 1.0 / @intToFloat(f32, images.len - 1);
i = 0;
while (i < images.len) : (i += 1) {
var tx: f32 = undefined;
var ty: f32 = undefined;
var v: f32 = undefined;
var a: f32 = undefined;
tx = x + 10;
ty = y + 10;
tx += @intToFloat(f32, i % 2) * (thumb + 10);
ty += @intToFloat(f32, i / 2) * (thumb + 10);
nvg.imageSize(images[i], &imgw, &imgh);
if (imgw < imgh) {
iw = thumb;
ih = iw * @intToFloat(f32, imgh) / @intToFloat(f32, imgw);
ix = 0;
iy = -(ih - thumb) * 0.5;
} else {
ih = thumb;
iw = ih * @intToFloat(f32, imgw) / @intToFloat(f32, imgh);
ix = -(iw - thumb) * 0.5;
iy = 0;
}
v = @intToFloat(f32, i) * dv;
a = std.math.clamp((ua - v) / dv, 0, 1);
if (a < 1.0)
drawSpinner(tx + thumb / 2, ty + thumb / 2, thumb * 0.25, t);
imgPaint = nvg.imagePattern(tx + ix, ty + iy, iw, ih, 0.0 / 180.0 * math.pi, images[i], a);
nvg.beginPath();
nvg.roundedRect(tx, ty, thumb, thumb, 5);
nvg.fillPaint(imgPaint);
nvg.fill();
shadowPaint = nvg.boxGradient(tx - 1, ty, thumb + 2, thumb + 2, 5, 3, nvg.rgba(0, 0, 0, 128), nvg.rgba(0, 0, 0, 0));
nvg.beginPath();
nvg.rect(tx - 5, ty - 5, thumb + 10, thumb + 10);
nvg.roundedRect(tx, ty, thumb, thumb, 6);
nvg.pathWinding(.cw);
nvg.fillPaint(shadowPaint);
nvg.fill();
nvg.beginPath();
nvg.roundedRect(tx + 0.5, ty + 0.5, thumb - 1, thumb - 1, 4 - 0.5);
nvg.strokeWidth(1.0);
nvg.strokeColor(nvg.rgba(255, 255, 255, 192));
nvg.stroke();
}
nvg.restore();
// Hide fades
fadePaint = nvg.linearGradient(x, y, x, y + 6, nvg.rgba(200, 200, 200, 255), nvg.rgba(200, 200, 200, 0));
nvg.beginPath();
nvg.rect(x + 4, y, w - 8, 6);
nvg.fillPaint(fadePaint);
nvg.fill();
fadePaint = nvg.linearGradient(x, y + h, x, y + h - 6, nvg.rgba(200, 200, 200, 255), nvg.rgba(200, 200, 200, 0));
nvg.beginPath();
nvg.rect(x + 4, y + h - 6, w - 8, 6);
nvg.fillPaint(fadePaint);
nvg.fill();
// Scroll bar
shadowPaint = nvg.boxGradient(x + w - 12 + 1, y + 4 + 1, 8, h - 8, 3, 4, nvg.rgba(0, 0, 0, 32), nvg.rgba(0, 0, 0, 92));
nvg.beginPath();
nvg.roundedRect(x + w - 12, y + 4, 8, h - 8, 3);
nvg.fillPaint(shadowPaint);
// nvg.fillColor( nvg.rgba(255,0,0,128));
nvg.fill();
scrollh = (h / stackh) * (h - 8);
shadowPaint = nvg.boxGradient(x + w - 12 - 1, y + 4 + (h - 8 - scrollh) * u - 1, 8, scrollh, 3, 4, nvg.rgba(220, 220, 220, 255), nvg.rgba(128, 128, 128, 255));
nvg.beginPath();
nvg.roundedRect(x + w - 12 + 1, y + 4 + 1 + (h - 8 - scrollh) * u, 8 - 2, scrollh - 2, 2);
nvg.fillPaint(shadowPaint);
// nvg.fillColor( nvg.rgba(0,0,0,128));
nvg.fill();
nvg.restore();
}
fn quit(ctx: *zp.Context) void {
_ = ctx;
std.log.info("game quit", .{});
}
pub fn main() anyerror!void {
try zp.run(.{
.initFn = init,
.loopFn = loop,
.quitFn = quit,
.width = 1000,
.height = 600,
});
} | examples/vector_graphics.zig |
const std = @import("std");
const c = @import("c.zig").c;
const glfw = @import("glfw");
const theme = @import("theme.zig");
pub fn main() !void {
std.debug.print("-*- zig imgui template -*-\n", .{});
var font: *c.ImFont = undefined;
var run: bool = true;
var display_size = c.ImVec2{
.x = 1280,
.y = 720,
};
// setup glfw & imgui
var window: glfw.Window = undefined;
var context: *c.ImGuiContext = undefined;
var io: *c.ImGuiIO = undefined;
{
try glfw.init(glfw.InitHints{});
window = try glfw.Window.create(
@floatToInt(u32, display_size.x),
@floatToInt(u32, display_size.y),
"zig imgui template",
null,
null,
glfw.Window.Hints{
.context_version_major = 3,
.context_version_minor = 0,
});
try glfw.makeContextCurrent(window);
try glfw.swapInterval(1); // vsync
std.debug.print("imgui version: {s}\n", .{c.igGetVersion()});
context = c.igCreateContext(null);
theme.setImguiTheme(&c.igGetStyle().*.Colors);
if (!c.ImGui_ImplGlfw_InitForOpenGL(@ptrCast(*c.GLFWwindow, window.handle), true)) {
std.debug.panic("", .{});
}
const glsl_version = "#version 130";
if (!c.ImGui_ImplOpenGL3_Init(glsl_version)) {
std.debug.panic("could not init opengl", .{});
}
io = c.igGetIO();
var text_pixels: [*c]u8 = undefined;
var text_w: i32 = undefined;
var text_h: i32 = undefined;
c.ImFontAtlas_GetTexDataAsRGBA32(io.Fonts, &text_pixels, &text_w, &text_h, null);
font = c.ImFontAtlas_AddFontFromFileTTF(io.Fonts, "res/font/CascadiaMonoPL.ttf", 15.0, null, c.ImFontAtlas_GetGlyphRangesDefault(io.Fonts));
_ = c.ImFontAtlas_Build(io.Fonts);
io.DisplaySize = display_size;
io.DeltaTime = 1.0 / 60.0;
}
// run loop
var show_demo_window = false;
while (run) {
if (glfw.pollEvents()) {} else |err| {
std.debug.panic("failed to poll events: {}", .{err});
}
// escape can exit the program
var action: glfw.Action = window.getKey(glfw.Key.escape);
if (action == glfw.Action.press or window.shouldClose()) {
run = false;
}
c.ImGui_ImplOpenGL3_NewFrame();
c.ImGui_ImplGlfw_NewFrame();
c.igNewFrame();
c.igPushFont(font);
///////////////////////////////////////////////////////////////////////////////
// YOUR CODE GOES HERE
{
_ = c.igBegin("Your code goes here", 0, 0);
c.igText("It's this easy to draw text with imgui");
var text_size: c.ImVec2 = undefined;
c.igCalcTextSize(&text_size, "toggle imgui demo", null, true, 1000.0);
if (c.igButton("toggle imgui demo", c.ImVec2{.x = text_size.x + 8, .y = text_size.y + 8})) {
show_demo_window = !show_demo_window;
}
c.igEnd();
}
// draw imgui's demo window
if (show_demo_window) {
c.igShowDemoWindow(&show_demo_window);
}
///////////////////////////////////////////////////////////////////////////////
c.igPopFont();
c.igRender();
if (window.getFramebufferSize()) |size| {
c.glViewport(0, 0, @intCast(c_int, size.width), @intCast(c_int, size.height));
c.glClearColor(0.9, 0.9, 0.9, 0);
c.glClear(c.GL_COLOR_BUFFER_BIT);
c.ImGui_ImplOpenGL3_RenderDrawData(c.igGetDrawData());
} else |err| {
std.debug.panic("failed to get frame buffer size: {}", .{err});
}
if (window.swapBuffers()) {} else |err| {
std.debug.panic("failed to swap buffers: {}", .{err});
}
}
// cleanup
c.igDestroyContext(context);
window.destroy();
glfw.terminate();
} | src/main.zig |
const stdx = @import("stdx");
const NodeRef = @import("ui.zig").NodeRef;
const widget = @import("widget.zig");
const WidgetUserId = widget.WidgetUserId;
const WidgetTypeId = widget.WidgetTypeId;
const WidgetKey = widget.WidgetKey;
const WidgetVTable = widget.WidgetVTable;
pub const FrameId = u32;
pub const NullFrameId = stdx.ds.CompactNull(FrameId);
/// A frame represents a declaration of a widget instance and is created in each Widget's `build` function.
/// Before the ui engine performs layout, these frames are used to diff against an existing node tree to determine whether a new
/// widget instance is created or updated.
pub const Frame = struct {
const Self = @This();
vtable: *const WidgetVTable,
// TODO: Allow this to be a u32 as well.
/// Used to map a unique id to the created node.
id: ?WidgetUserId,
/// Binds to WidgetRef upon initializing Widget instance.
widget_bind: ?*anyopaque,
/// Binds to NodeRefs upon initializing Widget instance.
node_binds: ?*BindNode,
/// Used to find an existing node under the same parent.
/// Should only be of type WidgetKey.EnumLiteral.
/// WidgetKey.Idx keys are created during the diff op and used as a default key.
key: ?WidgetKey,
/// Used to map a common tag to the created node.
tag: ?[]const u8,
/// Pointer to the props data.
props: FramePropsPtr,
/// This is only used by the special Fragment frame which represents multiple frames.
fragment_children: FrameListPtr,
pub fn init(vtable: *const WidgetVTable, id: ?WidgetUserId, bind: ?*anyopaque, props: FramePropsPtr, fragment_children: FrameListPtr) Self {
return .{
.vtable = vtable,
.id = id,
.widget_bind = bind,
.node_binds = null,
.props = props,
.fragment_children = fragment_children,
.key = null,
.tag = null,
};
}
};
/// Sized pointer to props data.
pub const FramePropsPtr = stdx.ds.DynamicArrayList(u32, u8).SizedPtr;
/// Represent a list of frames as a slice since the buffer could have been reallocated.
pub const FrameListPtr = struct {
id: FrameId,
len: u32,
pub fn init(id: FrameId, len: u32) @This() {
return .{ .id = id, .len = len };
}
};
/// Allows more than one builder to bind to a frame.
pub const BindNode = struct {
node_ref: *NodeRef,
next: ?*BindNode,
}; | ui/src/frame.zig |
const std = @import("std");
const build = std.build;
const ArrayList = std.ArrayList;
const fmt = std.fmt;
const mem = std.mem;
const fs = std.fs;
const warn = std.debug.warn;
pub const RunTranslatedCContext = struct {
b: *build.Builder,
step: *build.Step,
test_index: usize,
test_filter: ?[]const u8,
const TestCase = struct {
name: []const u8,
sources: ArrayList(SourceFile),
expected_stdout: []const u8,
allow_warnings: bool,
const SourceFile = struct {
filename: []const u8,
source: []const u8,
};
pub fn addSourceFile(self: *TestCase, filename: []const u8, source: []const u8) void {
self.sources.append(SourceFile{
.filename = filename,
.source = source,
}) catch unreachable;
}
};
pub fn create(
self: *RunTranslatedCContext,
allow_warnings: bool,
filename: []const u8,
name: []const u8,
source: []const u8,
expected_stdout: []const u8,
) *TestCase {
const tc = self.b.allocator.create(TestCase) catch unreachable;
tc.* = TestCase{
.name = name,
.sources = ArrayList(TestCase.SourceFile).init(self.b.allocator),
.expected_stdout = expected_stdout,
.allow_warnings = allow_warnings,
};
tc.addSourceFile(filename, source);
return tc;
}
pub fn add(
self: *RunTranslatedCContext,
name: []const u8,
source: []const u8,
expected_stdout: []const u8,
) void {
const tc = self.create(false, "source.c", name, source, expected_stdout);
self.addCase(tc);
}
pub fn addAllowWarnings(
self: *RunTranslatedCContext,
name: []const u8,
source: []const u8,
expected_stdout: []const u8,
) void {
const tc = self.create(true, "source.c", name, source, expected_stdout);
self.addCase(tc);
}
pub fn addCase(self: *RunTranslatedCContext, case: *const TestCase) void {
const b = self.b;
const annotated_case_name = fmt.allocPrint(self.b.allocator, "run-translated-c {}", .{case.name}) catch unreachable;
if (self.test_filter) |filter| {
if (mem.indexOf(u8, annotated_case_name, filter) == null) return;
}
const write_src = b.addWriteFiles();
for (case.sources.items) |src_file| {
write_src.add(src_file.filename, src_file.source);
}
const translate_c = b.addTranslateC(.{
.write_file = .{
.step = write_src,
.basename = case.sources.items[0].filename,
},
});
translate_c.step.name = b.fmt("{} translate-c", .{annotated_case_name});
const exe = translate_c.addExecutable();
exe.step.name = b.fmt("{} build-exe", .{annotated_case_name});
exe.linkLibC();
const run = exe.run();
run.step.name = b.fmt("{} run", .{annotated_case_name});
if (!case.allow_warnings) {
run.expectStdErrEqual("");
}
run.expectStdOutEqual(case.expected_stdout);
self.step.dependOn(&run.step);
}
}; | test/src/run_translated_c.zig |
const std = @import("../std.zig");
const assert = std.debug.assert;
const testing = std.testing;
const mem = std.mem;
const Token = std.zig.Token;
pub const TokenIndex = usize;
pub const NodeIndex = usize;
pub const Tree = struct {
/// Reference to externally-owned data.
source: []const u8,
token_ids: []const Token.Id,
token_locs: []const Token.Loc,
errors: []const Error,
root_node: *Node.Root,
arena: std.heap.ArenaAllocator.State,
gpa: *mem.Allocator,
/// translate-c uses this to avoid having to emit correct newlines
/// TODO get rid of this hack
generated: bool = false,
pub fn deinit(self: *Tree) void {
self.gpa.free(self.token_ids);
self.gpa.free(self.token_locs);
self.gpa.free(self.errors);
self.arena.promote(self.gpa).deinit();
}
pub fn renderError(self: *Tree, parse_error: *const Error, stream: anytype) !void {
return parse_error.render(self.token_ids, stream);
}
pub fn tokenSlice(self: *Tree, token_index: TokenIndex) []const u8 {
return self.tokenSliceLoc(self.token_locs[token_index]);
}
pub fn tokenSliceLoc(self: *Tree, token: Token.Loc) []const u8 {
return self.source[token.start..token.end];
}
pub fn getNodeSource(self: *const Tree, node: *const Node) []const u8 {
const first_token = self.token_locs[node.firstToken()];
const last_token = self.token_locs[node.lastToken()];
return self.source[first_token.start..last_token.end];
}
pub const Location = struct {
line: usize,
column: usize,
line_start: usize,
line_end: usize,
};
/// Return the Location of the token relative to the offset specified by `start_index`.
pub fn tokenLocationLoc(self: *Tree, start_index: usize, token: Token.Loc) Location {
var loc = Location{
.line = 0,
.column = 0,
.line_start = start_index,
.line_end = self.source.len,
};
if (self.generated)
return loc;
const token_start = token.start;
for (self.source[start_index..]) |c, i| {
if (i + start_index == token_start) {
loc.line_end = i + start_index;
while (loc.line_end < self.source.len and self.source[loc.line_end] != '\n') : (loc.line_end += 1) {}
return loc;
}
if (c == '\n') {
loc.line += 1;
loc.column = 0;
loc.line_start = i + 1;
} else {
loc.column += 1;
}
}
return loc;
}
pub fn tokenLocation(self: *Tree, start_index: usize, token_index: TokenIndex) Location {
return self.tokenLocationLoc(start_index, self.token_locs[token_index]);
}
pub fn tokensOnSameLine(self: *Tree, token1_index: TokenIndex, token2_index: TokenIndex) bool {
return self.tokensOnSameLineLoc(self.token_locs[token1_index], self.token_locs[token2_index]);
}
pub fn tokensOnSameLineLoc(self: *Tree, token1: Token.Loc, token2: Token.Loc) bool {
return mem.indexOfScalar(u8, self.source[token1.end..token2.start], '\n') == null;
}
pub fn dump(self: *Tree) void {
self.root_node.base.dump(0);
}
/// Skips over comments
pub fn prevToken(self: *Tree, token_index: TokenIndex) TokenIndex {
var index = token_index - 1;
while (self.token_ids[index] == Token.Id.LineComment) {
index -= 1;
}
return index;
}
/// Skips over comments
pub fn nextToken(self: *Tree, token_index: TokenIndex) TokenIndex {
var index = token_index + 1;
while (self.token_ids[index] == Token.Id.LineComment) {
index += 1;
}
return index;
}
};
pub const Error = union(enum) {
InvalidToken: InvalidToken,
ExpectedContainerMembers: ExpectedContainerMembers,
ExpectedStringLiteral: ExpectedStringLiteral,
ExpectedIntegerLiteral: ExpectedIntegerLiteral,
ExpectedPubItem: ExpectedPubItem,
ExpectedIdentifier: ExpectedIdentifier,
ExpectedStatement: ExpectedStatement,
ExpectedVarDeclOrFn: ExpectedVarDeclOrFn,
ExpectedVarDecl: ExpectedVarDecl,
ExpectedFn: ExpectedFn,
ExpectedReturnType: ExpectedReturnType,
ExpectedAggregateKw: ExpectedAggregateKw,
UnattachedDocComment: UnattachedDocComment,
ExpectedEqOrSemi: ExpectedEqOrSemi,
ExpectedSemiOrLBrace: ExpectedSemiOrLBrace,
ExpectedSemiOrElse: ExpectedSemiOrElse,
ExpectedLabelOrLBrace: ExpectedLabelOrLBrace,
ExpectedLBrace: ExpectedLBrace,
ExpectedColonOrRParen: ExpectedColonOrRParen,
ExpectedLabelable: ExpectedLabelable,
ExpectedInlinable: ExpectedInlinable,
ExpectedAsmOutputReturnOrType: ExpectedAsmOutputReturnOrType,
ExpectedCall: ExpectedCall,
ExpectedCallOrFnProto: ExpectedCallOrFnProto,
ExpectedSliceOrRBracket: ExpectedSliceOrRBracket,
ExtraAlignQualifier: ExtraAlignQualifier,
ExtraConstQualifier: ExtraConstQualifier,
ExtraVolatileQualifier: ExtraVolatileQualifier,
ExtraAllowZeroQualifier: ExtraAllowZeroQualifier,
ExpectedTypeExpr: ExpectedTypeExpr,
ExpectedPrimaryTypeExpr: ExpectedPrimaryTypeExpr,
ExpectedParamType: ExpectedParamType,
ExpectedExpr: ExpectedExpr,
ExpectedPrimaryExpr: ExpectedPrimaryExpr,
ExpectedToken: ExpectedToken,
ExpectedCommaOrEnd: ExpectedCommaOrEnd,
ExpectedParamList: ExpectedParamList,
ExpectedPayload: ExpectedPayload,
ExpectedBlockOrAssignment: ExpectedBlockOrAssignment,
ExpectedBlockOrExpression: ExpectedBlockOrExpression,
ExpectedExprOrAssignment: ExpectedExprOrAssignment,
ExpectedPrefixExpr: ExpectedPrefixExpr,
ExpectedLoopExpr: ExpectedLoopExpr,
ExpectedDerefOrUnwrap: ExpectedDerefOrUnwrap,
ExpectedSuffixOp: ExpectedSuffixOp,
ExpectedBlockOrField: ExpectedBlockOrField,
DeclBetweenFields: DeclBetweenFields,
InvalidAnd: InvalidAnd,
pub fn render(self: *const Error, tokens: []const Token.Id, stream: anytype) !void {
switch (self.*) {
.InvalidToken => |*x| return x.render(tokens, stream),
.ExpectedContainerMembers => |*x| return x.render(tokens, stream),
.ExpectedStringLiteral => |*x| return x.render(tokens, stream),
.ExpectedIntegerLiteral => |*x| return x.render(tokens, stream),
.ExpectedPubItem => |*x| return x.render(tokens, stream),
.ExpectedIdentifier => |*x| return x.render(tokens, stream),
.ExpectedStatement => |*x| return x.render(tokens, stream),
.ExpectedVarDeclOrFn => |*x| return x.render(tokens, stream),
.ExpectedVarDecl => |*x| return x.render(tokens, stream),
.ExpectedFn => |*x| return x.render(tokens, stream),
.ExpectedReturnType => |*x| return x.render(tokens, stream),
.ExpectedAggregateKw => |*x| return x.render(tokens, stream),
.UnattachedDocComment => |*x| return x.render(tokens, stream),
.ExpectedEqOrSemi => |*x| return x.render(tokens, stream),
.ExpectedSemiOrLBrace => |*x| return x.render(tokens, stream),
.ExpectedSemiOrElse => |*x| return x.render(tokens, stream),
.ExpectedLabelOrLBrace => |*x| return x.render(tokens, stream),
.ExpectedLBrace => |*x| return x.render(tokens, stream),
.ExpectedColonOrRParen => |*x| return x.render(tokens, stream),
.ExpectedLabelable => |*x| return x.render(tokens, stream),
.ExpectedInlinable => |*x| return x.render(tokens, stream),
.ExpectedAsmOutputReturnOrType => |*x| return x.render(tokens, stream),
.ExpectedCall => |*x| return x.render(tokens, stream),
.ExpectedCallOrFnProto => |*x| return x.render(tokens, stream),
.ExpectedSliceOrRBracket => |*x| return x.render(tokens, stream),
.ExtraAlignQualifier => |*x| return x.render(tokens, stream),
.ExtraConstQualifier => |*x| return x.render(tokens, stream),
.ExtraVolatileQualifier => |*x| return x.render(tokens, stream),
.ExtraAllowZeroQualifier => |*x| return x.render(tokens, stream),
.ExpectedTypeExpr => |*x| return x.render(tokens, stream),
.ExpectedPrimaryTypeExpr => |*x| return x.render(tokens, stream),
.ExpectedParamType => |*x| return x.render(tokens, stream),
.ExpectedExpr => |*x| return x.render(tokens, stream),
.ExpectedPrimaryExpr => |*x| return x.render(tokens, stream),
.ExpectedToken => |*x| return x.render(tokens, stream),
.ExpectedCommaOrEnd => |*x| return x.render(tokens, stream),
.ExpectedParamList => |*x| return x.render(tokens, stream),
.ExpectedPayload => |*x| return x.render(tokens, stream),
.ExpectedBlockOrAssignment => |*x| return x.render(tokens, stream),
.ExpectedBlockOrExpression => |*x| return x.render(tokens, stream),
.ExpectedExprOrAssignment => |*x| return x.render(tokens, stream),
.ExpectedPrefixExpr => |*x| return x.render(tokens, stream),
.ExpectedLoopExpr => |*x| return x.render(tokens, stream),
.ExpectedDerefOrUnwrap => |*x| return x.render(tokens, stream),
.ExpectedSuffixOp => |*x| return x.render(tokens, stream),
.ExpectedBlockOrField => |*x| return x.render(tokens, stream),
.DeclBetweenFields => |*x| return x.render(tokens, stream),
.InvalidAnd => |*x| return x.render(tokens, stream),
}
}
pub fn loc(self: *const Error) TokenIndex {
switch (self.*) {
.InvalidToken => |x| return x.token,
.ExpectedContainerMembers => |x| return x.token,
.ExpectedStringLiteral => |x| return x.token,
.ExpectedIntegerLiteral => |x| return x.token,
.ExpectedPubItem => |x| return x.token,
.ExpectedIdentifier => |x| return x.token,
.ExpectedStatement => |x| return x.token,
.ExpectedVarDeclOrFn => |x| return x.token,
.ExpectedVarDecl => |x| return x.token,
.ExpectedFn => |x| return x.token,
.ExpectedReturnType => |x| return x.token,
.ExpectedAggregateKw => |x| return x.token,
.UnattachedDocComment => |x| return x.token,
.ExpectedEqOrSemi => |x| return x.token,
.ExpectedSemiOrLBrace => |x| return x.token,
.ExpectedSemiOrElse => |x| return x.token,
.ExpectedLabelOrLBrace => |x| return x.token,
.ExpectedLBrace => |x| return x.token,
.ExpectedColonOrRParen => |x| return x.token,
.ExpectedLabelable => |x| return x.token,
.ExpectedInlinable => |x| return x.token,
.ExpectedAsmOutputReturnOrType => |x| return x.token,
.ExpectedCall => |x| return x.node.firstToken(),
.ExpectedCallOrFnProto => |x| return x.node.firstToken(),
.ExpectedSliceOrRBracket => |x| return x.token,
.ExtraAlignQualifier => |x| return x.token,
.ExtraConstQualifier => |x| return x.token,
.ExtraVolatileQualifier => |x| return x.token,
.ExtraAllowZeroQualifier => |x| return x.token,
.ExpectedTypeExpr => |x| return x.token,
.ExpectedPrimaryTypeExpr => |x| return x.token,
.ExpectedParamType => |x| return x.token,
.ExpectedExpr => |x| return x.token,
.ExpectedPrimaryExpr => |x| return x.token,
.ExpectedToken => |x| return x.token,
.ExpectedCommaOrEnd => |x| return x.token,
.ExpectedParamList => |x| return x.token,
.ExpectedPayload => |x| return x.token,
.ExpectedBlockOrAssignment => |x| return x.token,
.ExpectedBlockOrExpression => |x| return x.token,
.ExpectedExprOrAssignment => |x| return x.token,
.ExpectedPrefixExpr => |x| return x.token,
.ExpectedLoopExpr => |x| return x.token,
.ExpectedDerefOrUnwrap => |x| return x.token,
.ExpectedSuffixOp => |x| return x.token,
.ExpectedBlockOrField => |x| return x.token,
.DeclBetweenFields => |x| return x.token,
.InvalidAnd => |x| return x.token,
}
}
pub const InvalidToken = SingleTokenError("Invalid token '{}'");
pub const ExpectedContainerMembers = SingleTokenError("Expected test, comptime, var decl, or container field, found '{}'");
pub const ExpectedStringLiteral = SingleTokenError("Expected string literal, found '{}'");
pub const ExpectedIntegerLiteral = SingleTokenError("Expected integer literal, found '{}'");
pub const ExpectedIdentifier = SingleTokenError("Expected identifier, found '{}'");
pub const ExpectedStatement = SingleTokenError("Expected statement, found '{}'");
pub const ExpectedVarDeclOrFn = SingleTokenError("Expected variable declaration or function, found '{}'");
pub const ExpectedVarDecl = SingleTokenError("Expected variable declaration, found '{}'");
pub const ExpectedFn = SingleTokenError("Expected function, found '{}'");
pub const ExpectedReturnType = SingleTokenError("Expected 'var' or return type expression, found '{}'");
pub const ExpectedAggregateKw = SingleTokenError("Expected '" ++ Token.Id.Keyword_struct.symbol() ++ "', '" ++ Token.Id.Keyword_union.symbol() ++ "', or '" ++ Token.Id.Keyword_enum.symbol() ++ "', found '{}'");
pub const ExpectedEqOrSemi = SingleTokenError("Expected '=' or ';', found '{}'");
pub const ExpectedSemiOrLBrace = SingleTokenError("Expected ';' or '{{', found '{}'");
pub const ExpectedSemiOrElse = SingleTokenError("Expected ';' or 'else', found '{}'");
pub const ExpectedLBrace = SingleTokenError("Expected '{{', found '{}'");
pub const ExpectedLabelOrLBrace = SingleTokenError("Expected label or '{{', found '{}'");
pub const ExpectedColonOrRParen = SingleTokenError("Expected ':' or ')', found '{}'");
pub const ExpectedLabelable = SingleTokenError("Expected 'while', 'for', 'inline', 'suspend', or '{{', found '{}'");
pub const ExpectedInlinable = SingleTokenError("Expected 'while' or 'for', found '{}'");
pub const ExpectedAsmOutputReturnOrType = SingleTokenError("Expected '->' or '" ++ Token.Id.Identifier.symbol() ++ "', found '{}'");
pub const ExpectedSliceOrRBracket = SingleTokenError("Expected ']' or '..', found '{}'");
pub const ExpectedTypeExpr = SingleTokenError("Expected type expression, found '{}'");
pub const ExpectedPrimaryTypeExpr = SingleTokenError("Expected primary type expression, found '{}'");
pub const ExpectedExpr = SingleTokenError("Expected expression, found '{}'");
pub const ExpectedPrimaryExpr = SingleTokenError("Expected primary expression, found '{}'");
pub const ExpectedParamList = SingleTokenError("Expected parameter list, found '{}'");
pub const ExpectedPayload = SingleTokenError("Expected loop payload, found '{}'");
pub const ExpectedBlockOrAssignment = SingleTokenError("Expected block or assignment, found '{}'");
pub const ExpectedBlockOrExpression = SingleTokenError("Expected block or expression, found '{}'");
pub const ExpectedExprOrAssignment = SingleTokenError("Expected expression or assignment, found '{}'");
pub const ExpectedPrefixExpr = SingleTokenError("Expected prefix expression, found '{}'");
pub const ExpectedLoopExpr = SingleTokenError("Expected loop expression, found '{}'");
pub const ExpectedDerefOrUnwrap = SingleTokenError("Expected pointer dereference or optional unwrap, found '{}'");
pub const ExpectedSuffixOp = SingleTokenError("Expected pointer dereference, optional unwrap, or field access, found '{}'");
pub const ExpectedBlockOrField = SingleTokenError("Expected block or field, found '{}'");
pub const ExpectedParamType = SimpleError("Expected parameter type");
pub const ExpectedPubItem = SimpleError("Expected function or variable declaration after pub");
pub const UnattachedDocComment = SimpleError("Unattached documentation comment");
pub const ExtraAlignQualifier = SimpleError("Extra align qualifier");
pub const ExtraConstQualifier = SimpleError("Extra const qualifier");
pub const ExtraVolatileQualifier = SimpleError("Extra volatile qualifier");
pub const ExtraAllowZeroQualifier = SimpleError("Extra allowzero qualifier");
pub const DeclBetweenFields = SimpleError("Declarations are not allowed between container fields");
pub const InvalidAnd = SimpleError("`&&` is invalid. Note that `and` is boolean AND.");
pub const ExpectedCall = struct {
node: *Node,
pub fn render(self: *const ExpectedCall, tokens: []const Token.Id, stream: anytype) !void {
return stream.print("expected " ++ @tagName(Node.Tag.Call) ++ ", found {}", .{
@tagName(self.node.tag),
});
}
};
pub const ExpectedCallOrFnProto = struct {
node: *Node,
pub fn render(self: *const ExpectedCallOrFnProto, tokens: []const Token.Id, stream: anytype) !void {
return stream.print("expected " ++ @tagName(Node.Tag.Call) ++ " or " ++
@tagName(Node.Tag.FnProto) ++ ", found {}", .{@tagName(self.node.tag)});
}
};
pub const ExpectedToken = struct {
token: TokenIndex,
expected_id: Token.Id,
pub fn render(self: *const ExpectedToken, tokens: []const Token.Id, stream: anytype) !void {
const found_token = tokens[self.token];
switch (found_token) {
.Invalid => {
return stream.print("expected '{}', found invalid bytes", .{self.expected_id.symbol()});
},
else => {
const token_name = found_token.symbol();
return stream.print("expected '{}', found '{}'", .{ self.expected_id.symbol(), token_name });
},
}
}
};
pub const ExpectedCommaOrEnd = struct {
token: TokenIndex,
end_id: Token.Id,
pub fn render(self: *const ExpectedCommaOrEnd, tokens: []const Token.Id, stream: anytype) !void {
const actual_token = tokens[self.token];
return stream.print("expected ',' or '{}', found '{}'", .{
self.end_id.symbol(),
actual_token.symbol(),
});
}
};
fn SingleTokenError(comptime msg: []const u8) type {
return struct {
const ThisError = @This();
token: TokenIndex,
pub fn render(self: *const ThisError, tokens: []const Token.Id, stream: anytype) !void {
const actual_token = tokens[self.token];
return stream.print(msg, .{actual_token.symbol()});
}
};
}
fn SimpleError(comptime msg: []const u8) type {
return struct {
const ThisError = @This();
token: TokenIndex,
pub fn render(self: *const ThisError, tokens: []const Token.Id, stream: anytype) !void {
return stream.writeAll(msg);
}
};
}
};
pub const Node = struct {
tag: Tag,
pub const Tag = enum {
// Top level
Root,
Use,
TestDecl,
// Statements
VarDecl,
Defer,
// Infix operators
Catch,
// SimpleInfixOp
Add,
AddWrap,
ArrayCat,
ArrayMult,
Assign,
AssignBitAnd,
AssignBitOr,
AssignBitShiftLeft,
AssignBitShiftRight,
AssignBitXor,
AssignDiv,
AssignSub,
AssignSubWrap,
AssignMod,
AssignAdd,
AssignAddWrap,
AssignMul,
AssignMulWrap,
BangEqual,
BitAnd,
BitOr,
BitShiftLeft,
BitShiftRight,
BitXor,
BoolAnd,
BoolOr,
Div,
EqualEqual,
ErrorUnion,
GreaterOrEqual,
GreaterThan,
LessOrEqual,
LessThan,
MergeErrorSets,
Mod,
Mul,
MulWrap,
Period,
Range,
Sub,
SubWrap,
OrElse,
// SimplePrefixOp
AddressOf,
Await,
BitNot,
BoolNot,
OptionalType,
Negation,
NegationWrap,
Resume,
Try,
ArrayType,
/// ArrayType but has a sentinel node.
ArrayTypeSentinel,
PtrType,
SliceType,
/// `a[b..c]`
Slice,
/// `a.*`
Deref,
/// `a.?`
UnwrapOptional,
/// `a[b]`
ArrayAccess,
/// `T{a, b}`
ArrayInitializer,
/// ArrayInitializer but with `.` instead of a left-hand-side operand.
ArrayInitializerDot,
/// `T{.a = b}`
StructInitializer,
/// StructInitializer but with `.` instead of a left-hand-side operand.
StructInitializerDot,
/// `foo()`
Call,
// Control flow
Switch,
While,
For,
If,
ControlFlowExpression,
Suspend,
// Type expressions
AnyType,
ErrorType,
FnProto,
AnyFrameType,
// Primary expressions
IntegerLiteral,
FloatLiteral,
EnumLiteral,
StringLiteral,
MultilineStringLiteral,
CharLiteral,
BoolLiteral,
NullLiteral,
UndefinedLiteral,
Unreachable,
Identifier,
GroupedExpression,
BuiltinCall,
ErrorSetDecl,
ContainerDecl,
Asm,
Comptime,
Nosuspend,
Block,
// Misc
DocComment,
SwitchCase,
SwitchElse,
Else,
Payload,
PointerPayload,
PointerIndexPayload,
ContainerField,
ErrorTag,
FieldInitializer,
pub fn Type(tag: Tag) type {
return switch (tag) {
.Root => Root,
.Use => Use,
.TestDecl => TestDecl,
.VarDecl => VarDecl,
.Defer => Defer,
.Catch => Catch,
.Add,
.AddWrap,
.ArrayCat,
.ArrayMult,
.Assign,
.AssignBitAnd,
.AssignBitOr,
.AssignBitShiftLeft,
.AssignBitShiftRight,
.AssignBitXor,
.AssignDiv,
.AssignSub,
.AssignSubWrap,
.AssignMod,
.AssignAdd,
.AssignAddWrap,
.AssignMul,
.AssignMulWrap,
.BangEqual,
.BitAnd,
.BitOr,
.BitShiftLeft,
.BitShiftRight,
.BitXor,
.BoolAnd,
.BoolOr,
.Div,
.EqualEqual,
.ErrorUnion,
.GreaterOrEqual,
.GreaterThan,
.LessOrEqual,
.LessThan,
.MergeErrorSets,
.Mod,
.Mul,
.MulWrap,
.Period,
.Range,
.Sub,
.SubWrap,
.OrElse,
=> SimpleInfixOp,
.AddressOf,
.Await,
.BitNot,
.BoolNot,
.OptionalType,
.Negation,
.NegationWrap,
.Resume,
.Try,
=> SimplePrefixOp,
.ArrayType => ArrayType,
.ArrayTypeSentinel => ArrayTypeSentinel,
.PtrType => PtrType,
.SliceType => SliceType,
.Slice => Slice,
.Deref, .UnwrapOptional => SimpleSuffixOp,
.ArrayAccess => ArrayAccess,
.ArrayInitializer => ArrayInitializer,
.ArrayInitializerDot => ArrayInitializerDot,
.StructInitializer => StructInitializer,
.StructInitializerDot => StructInitializerDot,
.Call => Call,
.Switch => Switch,
.While => While,
.For => For,
.If => If,
.ControlFlowExpression => ControlFlowExpression,
.Suspend => Suspend,
.AnyType => AnyType,
.ErrorType => ErrorType,
.FnProto => FnProto,
.AnyFrameType => AnyFrameType,
.IntegerLiteral => IntegerLiteral,
.FloatLiteral => FloatLiteral,
.EnumLiteral => EnumLiteral,
.StringLiteral => StringLiteral,
.MultilineStringLiteral => MultilineStringLiteral,
.CharLiteral => CharLiteral,
.BoolLiteral => BoolLiteral,
.NullLiteral => NullLiteral,
.UndefinedLiteral => UndefinedLiteral,
.Unreachable => Unreachable,
.Identifier => Identifier,
.GroupedExpression => GroupedExpression,
.BuiltinCall => BuiltinCall,
.ErrorSetDecl => ErrorSetDecl,
.ContainerDecl => ContainerDecl,
.Asm => Asm,
.Comptime => Comptime,
.Nosuspend => Nosuspend,
.Block => Block,
.DocComment => DocComment,
.SwitchCase => SwitchCase,
.SwitchElse => SwitchElse,
.Else => Else,
.Payload => Payload,
.PointerPayload => PointerPayload,
.PointerIndexPayload => PointerIndexPayload,
.ContainerField => ContainerField,
.ErrorTag => ErrorTag,
.FieldInitializer => FieldInitializer,
};
}
};
/// Prefer `castTag` to this.
pub fn cast(base: *Node, comptime T: type) ?*T {
if (std.meta.fieldInfo(T, "base").default_value) |default_base| {
return base.castTag(default_base.tag);
}
inline for (@typeInfo(Tag).Enum.fields) |field| {
const tag = @intToEnum(Tag, field.value);
if (base.tag == tag) {
if (T == tag.Type()) {
return @fieldParentPtr(T, "base", base);
}
return null;
}
}
unreachable;
}
pub fn castTag(base: *Node, comptime tag: Tag) ?*tag.Type() {
if (base.tag == tag) {
return @fieldParentPtr(tag.Type(), "base", base);
}
return null;
}
pub fn iterate(base: *Node, index: usize) ?*Node {
inline for (@typeInfo(Tag).Enum.fields) |field| {
const tag = @intToEnum(Tag, field.value);
if (base.tag == tag) {
return @fieldParentPtr(tag.Type(), "base", base).iterate(index);
}
}
unreachable;
}
pub fn firstToken(base: *const Node) TokenIndex {
inline for (@typeInfo(Tag).Enum.fields) |field| {
const tag = @intToEnum(Tag, field.value);
if (base.tag == tag) {
return @fieldParentPtr(tag.Type(), "base", base).firstToken();
}
}
unreachable;
}
pub fn lastToken(base: *const Node) TokenIndex {
inline for (@typeInfo(Tag).Enum.fields) |field| {
const tag = @intToEnum(Tag, field.value);
if (base.tag == tag) {
return @fieldParentPtr(tag.Type(), "base", base).lastToken();
}
}
unreachable;
}
pub fn requireSemiColon(base: *const Node) bool {
var n = base;
while (true) {
switch (n.tag) {
.Root,
.ContainerField,
.Block,
.Payload,
.PointerPayload,
.PointerIndexPayload,
.Switch,
.SwitchCase,
.SwitchElse,
.FieldInitializer,
.DocComment,
.TestDecl,
=> return false,
.While => {
const while_node = @fieldParentPtr(While, "base", n);
if (while_node.@"else") |@"else"| {
n = &@"else".base;
continue;
}
return while_node.body.tag != .Block;
},
.For => {
const for_node = @fieldParentPtr(For, "base", n);
if (for_node.@"else") |@"else"| {
n = &@"else".base;
continue;
}
return for_node.body.tag != .Block;
},
.If => {
const if_node = @fieldParentPtr(If, "base", n);
if (if_node.@"else") |@"else"| {
n = &@"else".base;
continue;
}
return if_node.body.tag != .Block;
},
.Else => {
const else_node = @fieldParentPtr(Else, "base", n);
n = else_node.body;
continue;
},
.Defer => {
const defer_node = @fieldParentPtr(Defer, "base", n);
return defer_node.expr.tag != .Block;
},
.Comptime => {
const comptime_node = @fieldParentPtr(Comptime, "base", n);
return comptime_node.expr.tag != .Block;
},
.Suspend => {
const suspend_node = @fieldParentPtr(Suspend, "base", n);
if (suspend_node.body) |body| {
return body.tag != .Block;
}
return true;
},
.Nosuspend => {
const nosuspend_node = @fieldParentPtr(Nosuspend, "base", n);
return nosuspend_node.expr.tag != .Block;
},
else => return true,
}
}
}
pub fn dump(self: *Node, indent: usize) void {
{
var i: usize = 0;
while (i < indent) : (i += 1) {
std.debug.warn(" ", .{});
}
}
std.debug.warn("{}\n", .{@tagName(self.tag)});
var child_i: usize = 0;
while (self.iterate(child_i)) |child| : (child_i += 1) {
child.dump(indent + 2);
}
}
/// The decls data follows this struct in memory as an array of Node pointers.
pub const Root = struct {
base: Node = Node{ .tag = .Root },
eof_token: TokenIndex,
decls_len: NodeIndex,
/// After this the caller must initialize the decls list.
pub fn create(allocator: *mem.Allocator, decls_len: NodeIndex, eof_token: TokenIndex) !*Root {
const bytes = try allocator.alignedAlloc(u8, @alignOf(Root), sizeInBytes(decls_len));
const self = @ptrCast(*Root, bytes.ptr);
self.* = .{
.eof_token = eof_token,
.decls_len = decls_len,
};
return self;
}
pub fn destroy(self: *Decl, allocator: *mem.Allocator) void {
const bytes = @ptrCast([*]u8, self)[0..sizeInBytes(self.decls_len)];
allocator.free(bytes);
}
pub fn iterate(self: *const Root, index: usize) ?*Node {
var i = index;
if (i < self.decls_len) return self.declsConst()[i];
return null;
}
pub fn decls(self: *Root) []*Node {
const decls_start = @ptrCast([*]u8, self) + @sizeOf(Root);
return @ptrCast([*]*Node, decls_start)[0..self.decls_len];
}
pub fn declsConst(self: *const Root) []const *Node {
const decls_start = @ptrCast([*]const u8, self) + @sizeOf(Root);
return @ptrCast([*]const *Node, decls_start)[0..self.decls_len];
}
pub fn firstToken(self: *const Root) TokenIndex {
if (self.decls_len == 0) return self.eof_token;
return self.declsConst()[0].firstToken();
}
pub fn lastToken(self: *const Root) TokenIndex {
if (self.decls_len == 0) return self.eof_token;
return self.declsConst()[self.decls_len - 1].lastToken();
}
fn sizeInBytes(decls_len: NodeIndex) usize {
return @sizeOf(Root) + @sizeOf(*Node) * @as(usize, decls_len);
}
};
/// Trailed in memory by possibly many things, with each optional thing
/// determined by a bit in `trailer_flags`.
pub const VarDecl = struct {
base: Node = Node{ .tag = .VarDecl },
trailer_flags: TrailerFlags,
mut_token: TokenIndex,
name_token: TokenIndex,
semicolon_token: TokenIndex,
pub const TrailerFlags = std.meta.TrailerFlags(struct {
doc_comments: *DocComment,
visib_token: TokenIndex,
thread_local_token: TokenIndex,
eq_token: TokenIndex,
comptime_token: TokenIndex,
extern_export_token: TokenIndex,
lib_name: *Node,
type_node: *Node,
align_node: *Node,
section_node: *Node,
init_node: *Node,
});
pub const RequiredFields = struct {
mut_token: TokenIndex,
name_token: TokenIndex,
semicolon_token: TokenIndex,
};
pub fn getTrailer(self: *const VarDecl, comptime name: []const u8) ?TrailerFlags.Field(name) {
const trailers_start = @ptrCast([*]const u8, self) + @sizeOf(VarDecl);
return self.trailer_flags.get(trailers_start, name);
}
pub fn setTrailer(self: *VarDecl, comptime name: []const u8, value: TrailerFlags.Field(name)) void {
const trailers_start = @ptrCast([*]u8, self) + @sizeOf(VarDecl);
self.trailer_flags.set(trailers_start, name, value);
}
pub fn create(allocator: *mem.Allocator, required: RequiredFields, trailers: anytype) !*VarDecl {
const trailer_flags = TrailerFlags.init(trailers);
const bytes = try allocator.alignedAlloc(u8, @alignOf(VarDecl), sizeInBytes(trailer_flags));
const var_decl = @ptrCast(*VarDecl, bytes.ptr);
var_decl.* = .{
.trailer_flags = trailer_flags,
.mut_token = required.mut_token,
.name_token = required.name_token,
.semicolon_token = required.semicolon_token,
};
const trailers_start = bytes.ptr + @sizeOf(VarDecl);
trailer_flags.setMany(trailers_start, trailers);
return var_decl;
}
pub fn destroy(self: *VarDecl, allocator: *mem.Allocator) void {
const bytes = @ptrCast([*]u8, self)[0..sizeInBytes(self.trailer_flags)];
allocator.free(bytes);
}
pub fn iterate(self: *const VarDecl, index: usize) ?*Node {
var i = index;
if (self.getTrailer("type_node")) |type_node| {
if (i < 1) return type_node;
i -= 1;
}
if (self.getTrailer("align_node")) |align_node| {
if (i < 1) return align_node;
i -= 1;
}
if (self.getTrailer("section_node")) |section_node| {
if (i < 1) return section_node;
i -= 1;
}
if (self.getTrailer("init_node")) |init_node| {
if (i < 1) return init_node;
i -= 1;
}
return null;
}
pub fn firstToken(self: *const VarDecl) TokenIndex {
if (self.getTrailer("visib_token")) |visib_token| return visib_token;
if (self.getTrailer("thread_local_token")) |thread_local_token| return thread_local_token;
if (self.getTrailer("comptime_token")) |comptime_token| return comptime_token;
if (self.getTrailer("extern_export_token")) |extern_export_token| return extern_export_token;
assert(self.getTrailer("lib_name") == null);
return self.mut_token;
}
pub fn lastToken(self: *const VarDecl) TokenIndex {
return self.semicolon_token;
}
fn sizeInBytes(trailer_flags: TrailerFlags) usize {
return @sizeOf(VarDecl) + trailer_flags.sizeInBytes();
}
};
pub const Use = struct {
base: Node = Node{ .tag = .Use },
doc_comments: ?*DocComment,
visib_token: ?TokenIndex,
use_token: TokenIndex,
expr: *Node,
semicolon_token: TokenIndex,
pub fn iterate(self: *const Use, index: usize) ?*Node {
var i = index;
if (i < 1) return self.expr;
i -= 1;
return null;
}
pub fn firstToken(self: *const Use) TokenIndex {
if (self.visib_token) |visib_token| return visib_token;
return self.use_token;
}
pub fn lastToken(self: *const Use) TokenIndex {
return self.semicolon_token;
}
};
pub const ErrorSetDecl = struct {
base: Node = Node{ .tag = .ErrorSetDecl },
error_token: TokenIndex,
rbrace_token: TokenIndex,
decls_len: NodeIndex,
/// After this the caller must initialize the decls list.
pub fn alloc(allocator: *mem.Allocator, decls_len: NodeIndex) !*ErrorSetDecl {
const bytes = try allocator.alignedAlloc(u8, @alignOf(ErrorSetDecl), sizeInBytes(decls_len));
return @ptrCast(*ErrorSetDecl, bytes.ptr);
}
pub fn free(self: *ErrorSetDecl, allocator: *mem.Allocator) void {
const bytes = @ptrCast([*]u8, self)[0..sizeInBytes(self.decls_len)];
allocator.free(bytes);
}
pub fn iterate(self: *const ErrorSetDecl, index: usize) ?*Node {
var i = index;
if (i < self.decls_len) return self.declsConst()[i];
i -= self.decls_len;
return null;
}
pub fn firstToken(self: *const ErrorSetDecl) TokenIndex {
return self.error_token;
}
pub fn lastToken(self: *const ErrorSetDecl) TokenIndex {
return self.rbrace_token;
}
pub fn decls(self: *ErrorSetDecl) []*Node {
const decls_start = @ptrCast([*]u8, self) + @sizeOf(ErrorSetDecl);
return @ptrCast([*]*Node, decls_start)[0..self.decls_len];
}
pub fn declsConst(self: *const ErrorSetDecl) []const *Node {
const decls_start = @ptrCast([*]const u8, self) + @sizeOf(ErrorSetDecl);
return @ptrCast([*]const *Node, decls_start)[0..self.decls_len];
}
fn sizeInBytes(decls_len: NodeIndex) usize {
return @sizeOf(ErrorSetDecl) + @sizeOf(*Node) * @as(usize, decls_len);
}
};
/// The fields and decls Node pointers directly follow this struct in memory.
pub const ContainerDecl = struct {
base: Node = Node{ .tag = .ContainerDecl },
kind_token: TokenIndex,
layout_token: ?TokenIndex,
lbrace_token: TokenIndex,
rbrace_token: TokenIndex,
fields_and_decls_len: NodeIndex,
init_arg_expr: InitArg,
pub const InitArg = union(enum) {
None,
Enum: ?*Node,
Type: *Node,
};
/// After this the caller must initialize the fields_and_decls list.
pub fn alloc(allocator: *mem.Allocator, fields_and_decls_len: NodeIndex) !*ContainerDecl {
const bytes = try allocator.alignedAlloc(u8, @alignOf(ContainerDecl), sizeInBytes(fields_and_decls_len));
return @ptrCast(*ContainerDecl, bytes.ptr);
}
pub fn free(self: *ContainerDecl, allocator: *mem.Allocator) void {
const bytes = @ptrCast([*]u8, self)[0..sizeInBytes(self.fields_and_decls_len)];
allocator.free(bytes);
}
pub fn iterate(self: *const ContainerDecl, index: usize) ?*Node {
var i = index;
switch (self.init_arg_expr) {
.Type => |t| {
if (i < 1) return t;
i -= 1;
},
.None, .Enum => {},
}
if (i < self.fields_and_decls_len) return self.fieldsAndDeclsConst()[i];
i -= self.fields_and_decls_len;
return null;
}
pub fn firstToken(self: *const ContainerDecl) TokenIndex {
if (self.layout_token) |layout_token| {
return layout_token;
}
return self.kind_token;
}
pub fn lastToken(self: *const ContainerDecl) TokenIndex {
return self.rbrace_token;
}
pub fn fieldsAndDecls(self: *ContainerDecl) []*Node {
const decls_start = @ptrCast([*]u8, self) + @sizeOf(ContainerDecl);
return @ptrCast([*]*Node, decls_start)[0..self.fields_and_decls_len];
}
pub fn fieldsAndDeclsConst(self: *const ContainerDecl) []const *Node {
const decls_start = @ptrCast([*]const u8, self) + @sizeOf(ContainerDecl);
return @ptrCast([*]const *Node, decls_start)[0..self.fields_and_decls_len];
}
fn sizeInBytes(fields_and_decls_len: NodeIndex) usize {
return @sizeOf(ContainerDecl) + @sizeOf(*Node) * @as(usize, fields_and_decls_len);
}
};
pub const ContainerField = struct {
base: Node = Node{ .tag = .ContainerField },
doc_comments: ?*DocComment,
comptime_token: ?TokenIndex,
name_token: TokenIndex,
type_expr: ?*Node,
value_expr: ?*Node,
align_expr: ?*Node,
pub fn iterate(self: *const ContainerField, index: usize) ?*Node {
var i = index;
if (self.type_expr) |type_expr| {
if (i < 1) return type_expr;
i -= 1;
}
if (self.align_expr) |align_expr| {
if (i < 1) return align_expr;
i -= 1;
}
if (self.value_expr) |value_expr| {
if (i < 1) return value_expr;
i -= 1;
}
return null;
}
pub fn firstToken(self: *const ContainerField) TokenIndex {
return self.comptime_token orelse self.name_token;
}
pub fn lastToken(self: *const ContainerField) TokenIndex {
if (self.value_expr) |value_expr| {
return value_expr.lastToken();
}
if (self.align_expr) |align_expr| {
// The expression refers to what's inside the parenthesis, the
// last token is the closing one
return align_expr.lastToken() + 1;
}
if (self.type_expr) |type_expr| {
return type_expr.lastToken();
}
return self.name_token;
}
};
pub const ErrorTag = struct {
base: Node = Node{ .tag = .ErrorTag },
doc_comments: ?*DocComment,
name_token: TokenIndex,
pub fn iterate(self: *const ErrorTag, index: usize) ?*Node {
var i = index;
if (self.doc_comments) |comments| {
if (i < 1) return &comments.base;
i -= 1;
}
return null;
}
pub fn firstToken(self: *const ErrorTag) TokenIndex {
return self.name_token;
}
pub fn lastToken(self: *const ErrorTag) TokenIndex {
return self.name_token;
}
};
pub const Identifier = struct {
base: Node = Node{ .tag = .Identifier },
token: TokenIndex,
pub fn iterate(self: *const Identifier, index: usize) ?*Node {
return null;
}
pub fn firstToken(self: *const Identifier) TokenIndex {
return self.token;
}
pub fn lastToken(self: *const Identifier) TokenIndex {
return self.token;
}
};
/// The params are directly after the FnProto in memory.
/// Next, each optional thing determined by a bit in `trailer_flags`.
pub const FnProto = struct {
base: Node = Node{ .tag = .FnProto },
trailer_flags: TrailerFlags,
fn_token: TokenIndex,
params_len: NodeIndex,
return_type: ReturnType,
pub const TrailerFlags = std.meta.TrailerFlags(struct {
doc_comments: *DocComment,
body_node: *Node,
lib_name: *Node, // populated if this is an extern declaration
align_expr: *Node, // populated if align(A) is present
section_expr: *Node, // populated if linksection(A) is present
callconv_expr: *Node, // populated if callconv(A) is present
visib_token: TokenIndex,
name_token: TokenIndex,
var_args_token: TokenIndex,
extern_export_inline_token: TokenIndex,
is_extern_prototype: void, // TODO: Remove once extern fn rewriting is
is_async: void, // TODO: remove once async fn rewriting is
});
pub const RequiredFields = struct {
fn_token: TokenIndex,
params_len: NodeIndex,
return_type: ReturnType,
};
pub const ReturnType = union(enum) {
Explicit: *Node,
InferErrorSet: *Node,
Invalid: TokenIndex,
};
pub const ParamDecl = struct {
doc_comments: ?*DocComment,
comptime_token: ?TokenIndex,
noalias_token: ?TokenIndex,
name_token: ?TokenIndex,
param_type: ParamType,
pub const ParamType = union(enum) {
any_type: *Node,
type_expr: *Node,
};
pub fn iterate(self: *const ParamDecl, index: usize) ?*Node {
var i = index;
if (i < 1) {
switch (self.param_type) {
.any_type, .type_expr => |node| return node,
}
}
i -= 1;
return null;
}
pub fn firstToken(self: *const ParamDecl) TokenIndex {
if (self.comptime_token) |comptime_token| return comptime_token;
if (self.noalias_token) |noalias_token| return noalias_token;
if (self.name_token) |name_token| return name_token;
switch (self.param_type) {
.any_type, .type_expr => |node| return node.firstToken(),
}
}
pub fn lastToken(self: *const ParamDecl) TokenIndex {
switch (self.param_type) {
.any_type, .type_expr => |node| return node.lastToken(),
}
}
};
/// For debugging purposes.
pub fn dump(self: *const FnProto) void {
const trailers_start = @alignCast(
@alignOf(ParamDecl),
@ptrCast([*]const u8, self) + @sizeOf(FnProto) + @sizeOf(ParamDecl) * self.params_len,
);
std.debug.print("{*} flags: {b} name_token: {} {*} params_len: {}\n", .{
self,
self.trailer_flags.bits,
self.getTrailer("name_token"),
self.trailer_flags.ptrConst(trailers_start, "name_token"),
self.params_len,
});
}
pub fn getTrailer(self: *const FnProto, comptime name: []const u8) ?TrailerFlags.Field(name) {
const trailers_start = @alignCast(
@alignOf(ParamDecl),
@ptrCast([*]const u8, self) + @sizeOf(FnProto) + @sizeOf(ParamDecl) * self.params_len,
);
return self.trailer_flags.get(trailers_start, name);
}
pub fn setTrailer(self: *FnProto, comptime name: []const u8, value: TrailerFlags.Field(name)) void {
const trailers_start = @alignCast(
@alignOf(ParamDecl),
@ptrCast([*]u8, self) + @sizeOf(FnProto) + @sizeOf(ParamDecl) * self.params_len,
);
self.trailer_flags.set(trailers_start, name, value);
}
/// After this the caller must initialize the params list.
pub fn create(allocator: *mem.Allocator, required: RequiredFields, trailers: anytype) !*FnProto {
const trailer_flags = TrailerFlags.init(trailers);
const bytes = try allocator.alignedAlloc(u8, @alignOf(FnProto), sizeInBytes(
required.params_len,
trailer_flags,
));
const fn_proto = @ptrCast(*FnProto, bytes.ptr);
fn_proto.* = .{
.trailer_flags = trailer_flags,
.fn_token = required.fn_token,
.params_len = required.params_len,
.return_type = required.return_type,
};
const trailers_start = @alignCast(
@alignOf(ParamDecl),
bytes.ptr + @sizeOf(FnProto) + @sizeOf(ParamDecl) * required.params_len,
);
trailer_flags.setMany(trailers_start, trailers);
return fn_proto;
}
pub fn destroy(self: *FnProto, allocator: *mem.Allocator) void {
const bytes = @ptrCast([*]u8, self)[0..sizeInBytes(self.params_len, self.trailer_flags)];
allocator.free(bytes);
}
pub fn iterate(self: *const FnProto, index: usize) ?*Node {
var i = index;
if (self.getTrailer("lib_name")) |lib_name| {
if (i < 1) return lib_name;
i -= 1;
}
const params_len: usize = if (self.params_len == 0)
0
else switch (self.paramsConst()[self.params_len - 1].param_type) {
.any_type, .type_expr => self.params_len,
};
if (i < params_len) {
switch (self.paramsConst()[i].param_type) {
.any_type => |n| return n,
.type_expr => |n| return n,
}
}
i -= params_len;
if (self.getTrailer("align_expr")) |align_expr| {
if (i < 1) return align_expr;
i -= 1;
}
if (self.getTrailer("section_expr")) |section_expr| {
if (i < 1) return section_expr;
i -= 1;
}
switch (self.return_type) {
.Explicit, .InferErrorSet => |node| {
if (i < 1) return node;
i -= 1;
},
.Invalid => {},
}
if (self.getTrailer("body_node")) |body_node| {
if (i < 1) return body_node;
i -= 1;
}
return null;
}
pub fn firstToken(self: *const FnProto) TokenIndex {
if (self.getTrailer("visib_token")) |visib_token| return visib_token;
if (self.getTrailer("extern_export_inline_token")) |extern_export_inline_token| return extern_export_inline_token;
assert(self.getTrailer("lib_name") == null);
return self.fn_token;
}
pub fn lastToken(self: *const FnProto) TokenIndex {
if (self.getTrailer("body_node")) |body_node| return body_node.lastToken();
switch (self.return_type) {
.Explicit, .InferErrorSet => |node| return node.lastToken(),
.Invalid => |tok| return tok,
}
}
pub fn params(self: *FnProto) []ParamDecl {
const params_start = @ptrCast([*]u8, self) + @sizeOf(FnProto);
return @ptrCast([*]ParamDecl, params_start)[0..self.params_len];
}
pub fn paramsConst(self: *const FnProto) []const ParamDecl {
const params_start = @ptrCast([*]const u8, self) + @sizeOf(FnProto);
return @ptrCast([*]const ParamDecl, params_start)[0..self.params_len];
}
fn sizeInBytes(params_len: NodeIndex, trailer_flags: TrailerFlags) usize {
return @sizeOf(FnProto) + @sizeOf(ParamDecl) * @as(usize, params_len) + trailer_flags.sizeInBytes();
}
};
pub const AnyFrameType = struct {
base: Node = Node{ .tag = .AnyFrameType },
anyframe_token: TokenIndex,
result: ?Result,
pub const Result = struct {
arrow_token: TokenIndex,
return_type: *Node,
};
pub fn iterate(self: *const AnyFrameType, index: usize) ?*Node {
var i = index;
if (self.result) |result| {
if (i < 1) return result.return_type;
i -= 1;
}
return null;
}
pub fn firstToken(self: *const AnyFrameType) TokenIndex {
return self.anyframe_token;
}
pub fn lastToken(self: *const AnyFrameType) TokenIndex {
if (self.result) |result| return result.return_type.lastToken();
return self.anyframe_token;
}
};
/// The statements of the block follow Block directly in memory.
pub const Block = struct {
base: Node = Node{ .tag = .Block },
statements_len: NodeIndex,
lbrace: TokenIndex,
rbrace: TokenIndex,
label: ?TokenIndex,
/// After this the caller must initialize the statements list.
pub fn alloc(allocator: *mem.Allocator, statements_len: NodeIndex) !*Block {
const bytes = try allocator.alignedAlloc(u8, @alignOf(Block), sizeInBytes(statements_len));
return @ptrCast(*Block, bytes.ptr);
}
pub fn free(self: *Block, allocator: *mem.Allocator) void {
const bytes = @ptrCast([*]u8, self)[0..sizeInBytes(self.statements_len)];
allocator.free(bytes);
}
pub fn iterate(self: *const Block, index: usize) ?*Node {
var i = index;
if (i < self.statements_len) return self.statementsConst()[i];
i -= self.statements_len;
return null;
}
pub fn firstToken(self: *const Block) TokenIndex {
if (self.label) |label| {
return label;
}
return self.lbrace;
}
pub fn lastToken(self: *const Block) TokenIndex {
return self.rbrace;
}
pub fn statements(self: *Block) []*Node {
const decls_start = @ptrCast([*]u8, self) + @sizeOf(Block);
return @ptrCast([*]*Node, decls_start)[0..self.statements_len];
}
pub fn statementsConst(self: *const Block) []const *Node {
const decls_start = @ptrCast([*]const u8, self) + @sizeOf(Block);
return @ptrCast([*]const *Node, decls_start)[0..self.statements_len];
}
fn sizeInBytes(statements_len: NodeIndex) usize {
return @sizeOf(Block) + @sizeOf(*Node) * @as(usize, statements_len);
}
};
pub const Defer = struct {
base: Node = Node{ .tag = .Defer },
defer_token: TokenIndex,
payload: ?*Node,
expr: *Node,
pub fn iterate(self: *const Defer, index: usize) ?*Node {
var i = index;
if (i < 1) return self.expr;
i -= 1;
return null;
}
pub fn firstToken(self: *const Defer) TokenIndex {
return self.defer_token;
}
pub fn lastToken(self: *const Defer) TokenIndex {
return self.expr.lastToken();
}
};
pub const Comptime = struct {
base: Node = Node{ .tag = .Comptime },
doc_comments: ?*DocComment,
comptime_token: TokenIndex,
expr: *Node,
pub fn iterate(self: *const Comptime, index: usize) ?*Node {
var i = index;
if (i < 1) return self.expr;
i -= 1;
return null;
}
pub fn firstToken(self: *const Comptime) TokenIndex {
return self.comptime_token;
}
pub fn lastToken(self: *const Comptime) TokenIndex {
return self.expr.lastToken();
}
};
pub const Nosuspend = struct {
base: Node = Node{ .tag = .Nosuspend },
nosuspend_token: TokenIndex,
expr: *Node,
pub fn iterate(self: *const Nosuspend, index: usize) ?*Node {
var i = index;
if (i < 1) return self.expr;
i -= 1;
return null;
}
pub fn firstToken(self: *const Nosuspend) TokenIndex {
return self.nosuspend_token;
}
pub fn lastToken(self: *const Nosuspend) TokenIndex {
return self.expr.lastToken();
}
};
pub const Payload = struct {
base: Node = Node{ .tag = .Payload },
lpipe: TokenIndex,
error_symbol: *Node,
rpipe: TokenIndex,
pub fn iterate(self: *const Payload, index: usize) ?*Node {
var i = index;
if (i < 1) return self.error_symbol;
i -= 1;
return null;
}
pub fn firstToken(self: *const Payload) TokenIndex {
return self.lpipe;
}
pub fn lastToken(self: *const Payload) TokenIndex {
return self.rpipe;
}
};
pub const PointerPayload = struct {
base: Node = Node{ .tag = .PointerPayload },
lpipe: TokenIndex,
ptr_token: ?TokenIndex,
value_symbol: *Node,
rpipe: TokenIndex,
pub fn iterate(self: *const PointerPayload, index: usize) ?*Node {
var i = index;
if (i < 1) return self.value_symbol;
i -= 1;
return null;
}
pub fn firstToken(self: *const PointerPayload) TokenIndex {
return self.lpipe;
}
pub fn lastToken(self: *const PointerPayload) TokenIndex {
return self.rpipe;
}
};
pub const PointerIndexPayload = struct {
base: Node = Node{ .tag = .PointerIndexPayload },
lpipe: TokenIndex,
ptr_token: ?TokenIndex,
value_symbol: *Node,
index_symbol: ?*Node,
rpipe: TokenIndex,
pub fn iterate(self: *const PointerIndexPayload, index: usize) ?*Node {
var i = index;
if (i < 1) return self.value_symbol;
i -= 1;
if (self.index_symbol) |index_symbol| {
if (i < 1) return index_symbol;
i -= 1;
}
return null;
}
pub fn firstToken(self: *const PointerIndexPayload) TokenIndex {
return self.lpipe;
}
pub fn lastToken(self: *const PointerIndexPayload) TokenIndex {
return self.rpipe;
}
};
pub const Else = struct {
base: Node = Node{ .tag = .Else },
else_token: TokenIndex,
payload: ?*Node,
body: *Node,
pub fn iterate(self: *const Else, index: usize) ?*Node {
var i = index;
if (self.payload) |payload| {
if (i < 1) return payload;
i -= 1;
}
if (i < 1) return self.body;
i -= 1;
return null;
}
pub fn firstToken(self: *const Else) TokenIndex {
return self.else_token;
}
pub fn lastToken(self: *const Else) TokenIndex {
return self.body.lastToken();
}
};
/// The cases node pointers are found in memory after Switch.
/// They must be SwitchCase or SwitchElse nodes.
pub const Switch = struct {
base: Node = Node{ .tag = .Switch },
switch_token: TokenIndex,
rbrace: TokenIndex,
cases_len: NodeIndex,
expr: *Node,
/// After this the caller must initialize the fields_and_decls list.
pub fn alloc(allocator: *mem.Allocator, cases_len: NodeIndex) !*Switch {
const bytes = try allocator.alignedAlloc(u8, @alignOf(Switch), sizeInBytes(cases_len));
return @ptrCast(*Switch, bytes.ptr);
}
pub fn free(self: *Switch, allocator: *mem.Allocator) void {
const bytes = @ptrCast([*]u8, self)[0..sizeInBytes(self.cases_len)];
allocator.free(bytes);
}
pub fn iterate(self: *const Switch, index: usize) ?*Node {
var i = index;
if (i < 1) return self.expr;
i -= 1;
if (i < self.cases_len) return self.casesConst()[i];
i -= self.cases_len;
return null;
}
pub fn firstToken(self: *const Switch) TokenIndex {
return self.switch_token;
}
pub fn lastToken(self: *const Switch) TokenIndex {
return self.rbrace;
}
pub fn cases(self: *Switch) []*Node {
const decls_start = @ptrCast([*]u8, self) + @sizeOf(Switch);
return @ptrCast([*]*Node, decls_start)[0..self.cases_len];
}
pub fn casesConst(self: *const Switch) []const *Node {
const decls_start = @ptrCast([*]const u8, self) + @sizeOf(Switch);
return @ptrCast([*]const *Node, decls_start)[0..self.cases_len];
}
fn sizeInBytes(cases_len: NodeIndex) usize {
return @sizeOf(Switch) + @sizeOf(*Node) * @as(usize, cases_len);
}
};
/// Items sub-nodes appear in memory directly following SwitchCase.
pub const SwitchCase = struct {
base: Node = Node{ .tag = .SwitchCase },
arrow_token: TokenIndex,
payload: ?*Node,
expr: *Node,
items_len: NodeIndex,
/// After this the caller must initialize the fields_and_decls list.
pub fn alloc(allocator: *mem.Allocator, items_len: NodeIndex) !*SwitchCase {
const bytes = try allocator.alignedAlloc(u8, @alignOf(SwitchCase), sizeInBytes(items_len));
return @ptrCast(*SwitchCase, bytes.ptr);
}
pub fn free(self: *SwitchCase, allocator: *mem.Allocator) void {
const bytes = @ptrCast([*]u8, self)[0..sizeInBytes(self.items_len)];
allocator.free(bytes);
}
pub fn iterate(self: *const SwitchCase, index: usize) ?*Node {
var i = index;
if (i < self.items_len) return self.itemsConst()[i];
i -= self.items_len;
if (self.payload) |payload| {
if (i < 1) return payload;
i -= 1;
}
if (i < 1) return self.expr;
i -= 1;
return null;
}
pub fn firstToken(self: *const SwitchCase) TokenIndex {
return self.itemsConst()[0].firstToken();
}
pub fn lastToken(self: *const SwitchCase) TokenIndex {
return self.expr.lastToken();
}
pub fn items(self: *SwitchCase) []*Node {
const decls_start = @ptrCast([*]u8, self) + @sizeOf(SwitchCase);
return @ptrCast([*]*Node, decls_start)[0..self.items_len];
}
pub fn itemsConst(self: *const SwitchCase) []const *Node {
const decls_start = @ptrCast([*]const u8, self) + @sizeOf(SwitchCase);
return @ptrCast([*]const *Node, decls_start)[0..self.items_len];
}
fn sizeInBytes(items_len: NodeIndex) usize {
return @sizeOf(SwitchCase) + @sizeOf(*Node) * @as(usize, items_len);
}
};
pub const SwitchElse = struct {
base: Node = Node{ .tag = .SwitchElse },
token: TokenIndex,
pub fn iterate(self: *const SwitchElse, index: usize) ?*Node {
return null;
}
pub fn firstToken(self: *const SwitchElse) TokenIndex {
return self.token;
}
pub fn lastToken(self: *const SwitchElse) TokenIndex {
return self.token;
}
};
pub const While = struct {
base: Node = Node{ .tag = .While },
label: ?TokenIndex,
inline_token: ?TokenIndex,
while_token: TokenIndex,
condition: *Node,
payload: ?*Node,
continue_expr: ?*Node,
body: *Node,
@"else": ?*Else,
pub fn iterate(self: *const While, index: usize) ?*Node {
var i = index;
if (i < 1) return self.condition;
i -= 1;
if (self.payload) |payload| {
if (i < 1) return payload;
i -= 1;
}
if (self.continue_expr) |continue_expr| {
if (i < 1) return continue_expr;
i -= 1;
}
if (i < 1) return self.body;
i -= 1;
if (self.@"else") |@"else"| {
if (i < 1) return &@"else".base;
i -= 1;
}
return null;
}
pub fn firstToken(self: *const While) TokenIndex {
if (self.label) |label| {
return label;
}
if (self.inline_token) |inline_token| {
return inline_token;
}
return self.while_token;
}
pub fn lastToken(self: *const While) TokenIndex {
if (self.@"else") |@"else"| {
return @"else".body.lastToken();
}
return self.body.lastToken();
}
};
pub const For = struct {
base: Node = Node{ .tag = .For },
label: ?TokenIndex,
inline_token: ?TokenIndex,
for_token: TokenIndex,
array_expr: *Node,
payload: *Node,
body: *Node,
@"else": ?*Else,
pub fn iterate(self: *const For, index: usize) ?*Node {
var i = index;
if (i < 1) return self.array_expr;
i -= 1;
if (i < 1) return self.payload;
i -= 1;
if (i < 1) return self.body;
i -= 1;
if (self.@"else") |@"else"| {
if (i < 1) return &@"else".base;
i -= 1;
}
return null;
}
pub fn firstToken(self: *const For) TokenIndex {
if (self.label) |label| {
return label;
}
if (self.inline_token) |inline_token| {
return inline_token;
}
return self.for_token;
}
pub fn lastToken(self: *const For) TokenIndex {
if (self.@"else") |@"else"| {
return @"else".body.lastToken();
}
return self.body.lastToken();
}
};
pub const If = struct {
base: Node = Node{ .tag = .If },
if_token: TokenIndex,
condition: *Node,
payload: ?*Node,
body: *Node,
@"else": ?*Else,
pub fn iterate(self: *const If, index: usize) ?*Node {
var i = index;
if (i < 1) return self.condition;
i -= 1;
if (self.payload) |payload| {
if (i < 1) return payload;
i -= 1;
}
if (i < 1) return self.body;
i -= 1;
if (self.@"else") |@"else"| {
if (i < 1) return &@"else".base;
i -= 1;
}
return null;
}
pub fn firstToken(self: *const If) TokenIndex {
return self.if_token;
}
pub fn lastToken(self: *const If) TokenIndex {
if (self.@"else") |@"else"| {
return @"else".body.lastToken();
}
return self.body.lastToken();
}
};
pub const Catch = struct {
base: Node = Node{ .tag = .Catch },
op_token: TokenIndex,
lhs: *Node,
rhs: *Node,
payload: ?*Node,
pub fn iterate(self: *const Catch, index: usize) ?*Node {
var i = index;
if (i < 1) return self.lhs;
i -= 1;
if (self.payload) |payload| {
if (i < 1) return payload;
i -= 1;
}
if (i < 1) return self.rhs;
i -= 1;
return null;
}
pub fn firstToken(self: *const Catch) TokenIndex {
return self.lhs.firstToken();
}
pub fn lastToken(self: *const Catch) TokenIndex {
return self.rhs.lastToken();
}
};
pub const SimpleInfixOp = struct {
base: Node,
op_token: TokenIndex,
lhs: *Node,
rhs: *Node,
pub fn iterate(self: *const SimpleInfixOp, index: usize) ?*Node {
var i = index;
if (i < 1) return self.lhs;
i -= 1;
if (i < 1) return self.rhs;
i -= 1;
return null;
}
pub fn firstToken(self: *const SimpleInfixOp) TokenIndex {
return self.lhs.firstToken();
}
pub fn lastToken(self: *const SimpleInfixOp) TokenIndex {
return self.rhs.lastToken();
}
};
pub const SimplePrefixOp = struct {
base: Node,
op_token: TokenIndex,
rhs: *Node,
const Self = @This();
pub fn iterate(self: *const Self, index: usize) ?*Node {
if (index == 0) return self.rhs;
return null;
}
pub fn firstToken(self: *const Self) TokenIndex {
return self.op_token;
}
pub fn lastToken(self: *const Self) TokenIndex {
return self.rhs.lastToken();
}
};
pub const ArrayType = struct {
base: Node = Node{ .tag = .ArrayType },
op_token: TokenIndex,
rhs: *Node,
len_expr: *Node,
pub fn iterate(self: *const ArrayType, index: usize) ?*Node {
var i = index;
if (i < 1) return self.len_expr;
i -= 1;
if (i < 1) return self.rhs;
i -= 1;
return null;
}
pub fn firstToken(self: *const ArrayType) TokenIndex {
return self.op_token;
}
pub fn lastToken(self: *const ArrayType) TokenIndex {
return self.rhs.lastToken();
}
};
pub const ArrayTypeSentinel = struct {
base: Node = Node{ .tag = .ArrayTypeSentinel },
op_token: TokenIndex,
rhs: *Node,
len_expr: *Node,
sentinel: *Node,
pub fn iterate(self: *const ArrayTypeSentinel, index: usize) ?*Node {
var i = index;
if (i < 1) return self.len_expr;
i -= 1;
if (i < 1) return self.sentinel;
i -= 1;
if (i < 1) return self.rhs;
i -= 1;
return null;
}
pub fn firstToken(self: *const ArrayTypeSentinel) TokenIndex {
return self.op_token;
}
pub fn lastToken(self: *const ArrayTypeSentinel) TokenIndex {
return self.rhs.lastToken();
}
};
pub const PtrType = struct {
base: Node = Node{ .tag = .PtrType },
op_token: TokenIndex,
rhs: *Node,
/// TODO Add a u8 flags field to Node where it would otherwise be padding, and each bit represents
/// one of these possibly-null things. Then we have them directly follow the PtrType in memory.
ptr_info: PtrInfo = .{},
pub fn iterate(self: *const PtrType, index: usize) ?*Node {
var i = index;
if (self.ptr_info.sentinel) |sentinel| {
if (i < 1) return sentinel;
i -= 1;
}
if (self.ptr_info.align_info) |align_info| {
if (i < 1) return align_info.node;
i -= 1;
}
if (i < 1) return self.rhs;
i -= 1;
return null;
}
pub fn firstToken(self: *const PtrType) TokenIndex {
return self.op_token;
}
pub fn lastToken(self: *const PtrType) TokenIndex {
return self.rhs.lastToken();
}
};
pub const SliceType = struct {
base: Node = Node{ .tag = .SliceType },
op_token: TokenIndex,
rhs: *Node,
/// TODO Add a u8 flags field to Node where it would otherwise be padding, and each bit represents
/// one of these possibly-null things. Then we have them directly follow the SliceType in memory.
ptr_info: PtrInfo = .{},
pub fn iterate(self: *const SliceType, index: usize) ?*Node {
var i = index;
if (self.ptr_info.sentinel) |sentinel| {
if (i < 1) return sentinel;
i -= 1;
}
if (self.ptr_info.align_info) |align_info| {
if (i < 1) return align_info.node;
i -= 1;
}
if (i < 1) return self.rhs;
i -= 1;
return null;
}
pub fn firstToken(self: *const SliceType) TokenIndex {
return self.op_token;
}
pub fn lastToken(self: *const SliceType) TokenIndex {
return self.rhs.lastToken();
}
};
pub const FieldInitializer = struct {
base: Node = Node{ .tag = .FieldInitializer },
period_token: TokenIndex,
name_token: TokenIndex,
expr: *Node,
pub fn iterate(self: *const FieldInitializer, index: usize) ?*Node {
var i = index;
if (i < 1) return self.expr;
i -= 1;
return null;
}
pub fn firstToken(self: *const FieldInitializer) TokenIndex {
return self.period_token;
}
pub fn lastToken(self: *const FieldInitializer) TokenIndex {
return self.expr.lastToken();
}
};
/// Elements occur directly in memory after ArrayInitializer.
pub const ArrayInitializer = struct {
base: Node = Node{ .tag = .ArrayInitializer },
rtoken: TokenIndex,
list_len: NodeIndex,
lhs: *Node,
/// After this the caller must initialize the fields_and_decls list.
pub fn alloc(allocator: *mem.Allocator, list_len: NodeIndex) !*ArrayInitializer {
const bytes = try allocator.alignedAlloc(u8, @alignOf(ArrayInitializer), sizeInBytes(list_len));
return @ptrCast(*ArrayInitializer, bytes.ptr);
}
pub fn free(self: *ArrayInitializer, allocator: *mem.Allocator) void {
const bytes = @ptrCast([*]u8, self)[0..sizeInBytes(self.list_len)];
allocator.free(bytes);
}
pub fn iterate(self: *const ArrayInitializer, index: usize) ?*Node {
var i = index;
if (i < 1) return self.lhs;
i -= 1;
if (i < self.list_len) return self.listConst()[i];
i -= self.list_len;
return null;
}
pub fn firstToken(self: *const ArrayInitializer) TokenIndex {
return self.lhs.firstToken();
}
pub fn lastToken(self: *const ArrayInitializer) TokenIndex {
return self.rtoken;
}
pub fn list(self: *ArrayInitializer) []*Node {
const decls_start = @ptrCast([*]u8, self) + @sizeOf(ArrayInitializer);
return @ptrCast([*]*Node, decls_start)[0..self.list_len];
}
pub fn listConst(self: *const ArrayInitializer) []const *Node {
const decls_start = @ptrCast([*]const u8, self) + @sizeOf(ArrayInitializer);
return @ptrCast([*]const *Node, decls_start)[0..self.list_len];
}
fn sizeInBytes(list_len: NodeIndex) usize {
return @sizeOf(ArrayInitializer) + @sizeOf(*Node) * @as(usize, list_len);
}
};
/// Elements occur directly in memory after ArrayInitializerDot.
pub const ArrayInitializerDot = struct {
base: Node = Node{ .tag = .ArrayInitializerDot },
dot: TokenIndex,
rtoken: TokenIndex,
list_len: NodeIndex,
/// After this the caller must initialize the fields_and_decls list.
pub fn alloc(allocator: *mem.Allocator, list_len: NodeIndex) !*ArrayInitializerDot {
const bytes = try allocator.alignedAlloc(u8, @alignOf(ArrayInitializerDot), sizeInBytes(list_len));
return @ptrCast(*ArrayInitializerDot, bytes.ptr);
}
pub fn free(self: *ArrayInitializerDot, allocator: *mem.Allocator) void {
const bytes = @ptrCast([*]u8, self)[0..sizeInBytes(self.list_len)];
allocator.free(bytes);
}
pub fn iterate(self: *const ArrayInitializerDot, index: usize) ?*Node {
var i = index;
if (i < self.list_len) return self.listConst()[i];
i -= self.list_len;
return null;
}
pub fn firstToken(self: *const ArrayInitializerDot) TokenIndex {
return self.dot;
}
pub fn lastToken(self: *const ArrayInitializerDot) TokenIndex {
return self.rtoken;
}
pub fn list(self: *ArrayInitializerDot) []*Node {
const decls_start = @ptrCast([*]u8, self) + @sizeOf(ArrayInitializerDot);
return @ptrCast([*]*Node, decls_start)[0..self.list_len];
}
pub fn listConst(self: *const ArrayInitializerDot) []const *Node {
const decls_start = @ptrCast([*]const u8, self) + @sizeOf(ArrayInitializerDot);
return @ptrCast([*]const *Node, decls_start)[0..self.list_len];
}
fn sizeInBytes(list_len: NodeIndex) usize {
return @sizeOf(ArrayInitializerDot) + @sizeOf(*Node) * @as(usize, list_len);
}
};
/// Elements occur directly in memory after StructInitializer.
pub const StructInitializer = struct {
base: Node = Node{ .tag = .StructInitializer },
rtoken: TokenIndex,
list_len: NodeIndex,
lhs: *Node,
/// After this the caller must initialize the fields_and_decls list.
pub fn alloc(allocator: *mem.Allocator, list_len: NodeIndex) !*StructInitializer {
const bytes = try allocator.alignedAlloc(u8, @alignOf(StructInitializer), sizeInBytes(list_len));
return @ptrCast(*StructInitializer, bytes.ptr);
}
pub fn free(self: *StructInitializer, allocator: *mem.Allocator) void {
const bytes = @ptrCast([*]u8, self)[0..sizeInBytes(self.list_len)];
allocator.free(bytes);
}
pub fn iterate(self: *const StructInitializer, index: usize) ?*Node {
var i = index;
if (i < 1) return self.lhs;
i -= 1;
if (i < self.list_len) return self.listConst()[i];
i -= self.list_len;
return null;
}
pub fn firstToken(self: *const StructInitializer) TokenIndex {
return self.lhs.firstToken();
}
pub fn lastToken(self: *const StructInitializer) TokenIndex {
return self.rtoken;
}
pub fn list(self: *StructInitializer) []*Node {
const decls_start = @ptrCast([*]u8, self) + @sizeOf(StructInitializer);
return @ptrCast([*]*Node, decls_start)[0..self.list_len];
}
pub fn listConst(self: *const StructInitializer) []const *Node {
const decls_start = @ptrCast([*]const u8, self) + @sizeOf(StructInitializer);
return @ptrCast([*]const *Node, decls_start)[0..self.list_len];
}
fn sizeInBytes(list_len: NodeIndex) usize {
return @sizeOf(StructInitializer) + @sizeOf(*Node) * @as(usize, list_len);
}
};
/// Elements occur directly in memory after StructInitializerDot.
pub const StructInitializerDot = struct {
base: Node = Node{ .tag = .StructInitializerDot },
dot: TokenIndex,
rtoken: TokenIndex,
list_len: NodeIndex,
/// After this the caller must initialize the fields_and_decls list.
pub fn alloc(allocator: *mem.Allocator, list_len: NodeIndex) !*StructInitializerDot {
const bytes = try allocator.alignedAlloc(u8, @alignOf(StructInitializerDot), sizeInBytes(list_len));
return @ptrCast(*StructInitializerDot, bytes.ptr);
}
pub fn free(self: *StructInitializerDot, allocator: *mem.Allocator) void {
const bytes = @ptrCast([*]u8, self)[0..sizeInBytes(self.list_len)];
allocator.free(bytes);
}
pub fn iterate(self: *const StructInitializerDot, index: usize) ?*Node {
var i = index;
if (i < self.list_len) return self.listConst()[i];
i -= self.list_len;
return null;
}
pub fn firstToken(self: *const StructInitializerDot) TokenIndex {
return self.dot;
}
pub fn lastToken(self: *const StructInitializerDot) TokenIndex {
return self.rtoken;
}
pub fn list(self: *StructInitializerDot) []*Node {
const decls_start = @ptrCast([*]u8, self) + @sizeOf(StructInitializerDot);
return @ptrCast([*]*Node, decls_start)[0..self.list_len];
}
pub fn listConst(self: *const StructInitializerDot) []const *Node {
const decls_start = @ptrCast([*]const u8, self) + @sizeOf(StructInitializerDot);
return @ptrCast([*]const *Node, decls_start)[0..self.list_len];
}
fn sizeInBytes(list_len: NodeIndex) usize {
return @sizeOf(StructInitializerDot) + @sizeOf(*Node) * @as(usize, list_len);
}
};
/// Parameter nodes directly follow Call in memory.
pub const Call = struct {
base: Node = Node{ .tag = .Call },
rtoken: TokenIndex,
lhs: *Node,
params_len: NodeIndex,
async_token: ?TokenIndex,
/// After this the caller must initialize the fields_and_decls list.
pub fn alloc(allocator: *mem.Allocator, params_len: NodeIndex) !*Call {
const bytes = try allocator.alignedAlloc(u8, @alignOf(Call), sizeInBytes(params_len));
return @ptrCast(*Call, bytes.ptr);
}
pub fn free(self: *Call, allocator: *mem.Allocator) void {
const bytes = @ptrCast([*]u8, self)[0..sizeInBytes(self.params_len)];
allocator.free(bytes);
}
pub fn iterate(self: *const Call, index: usize) ?*Node {
var i = index;
if (i < 1) return self.lhs;
i -= 1;
if (i < self.params_len) return self.paramsConst()[i];
i -= self.params_len;
return null;
}
pub fn firstToken(self: *const Call) TokenIndex {
if (self.async_token) |async_token| return async_token;
return self.lhs.firstToken();
}
pub fn lastToken(self: *const Call) TokenIndex {
return self.rtoken;
}
pub fn params(self: *Call) []*Node {
const decls_start = @ptrCast([*]u8, self) + @sizeOf(Call);
return @ptrCast([*]*Node, decls_start)[0..self.params_len];
}
pub fn paramsConst(self: *const Call) []const *Node {
const decls_start = @ptrCast([*]const u8, self) + @sizeOf(Call);
return @ptrCast([*]const *Node, decls_start)[0..self.params_len];
}
fn sizeInBytes(params_len: NodeIndex) usize {
return @sizeOf(Call) + @sizeOf(*Node) * @as(usize, params_len);
}
};
pub const ArrayAccess = struct {
base: Node = Node{ .tag = .ArrayAccess },
rtoken: TokenIndex,
lhs: *Node,
index_expr: *Node,
pub fn iterate(self: *const ArrayAccess, index: usize) ?*Node {
var i = index;
if (i < 1) return self.lhs;
i -= 1;
if (i < 1) return self.index_expr;
i -= 1;
return null;
}
pub fn firstToken(self: *const ArrayAccess) TokenIndex {
return self.lhs.firstToken();
}
pub fn lastToken(self: *const ArrayAccess) TokenIndex {
return self.rtoken;
}
};
pub const SimpleSuffixOp = struct {
base: Node,
rtoken: TokenIndex,
lhs: *Node,
pub fn iterate(self: *const SimpleSuffixOp, index: usize) ?*Node {
var i = index;
if (i < 1) return self.lhs;
i -= 1;
return null;
}
pub fn firstToken(self: *const SimpleSuffixOp) TokenIndex {
return self.lhs.firstToken();
}
pub fn lastToken(self: *const SimpleSuffixOp) TokenIndex {
return self.rtoken;
}
};
pub const Slice = struct {
base: Node = Node{ .tag = .Slice },
rtoken: TokenIndex,
lhs: *Node,
start: *Node,
end: ?*Node,
sentinel: ?*Node,
pub fn iterate(self: *const Slice, index: usize) ?*Node {
var i = index;
if (i < 1) return self.lhs;
i -= 1;
if (i < 1) return self.start;
i -= 1;
if (self.end) |end| {
if (i < 1) return end;
i -= 1;
}
if (self.sentinel) |sentinel| {
if (i < 1) return sentinel;
i -= 1;
}
return null;
}
pub fn firstToken(self: *const Slice) TokenIndex {
return self.lhs.firstToken();
}
pub fn lastToken(self: *const Slice) TokenIndex {
return self.rtoken;
}
};
pub const GroupedExpression = struct {
base: Node = Node{ .tag = .GroupedExpression },
lparen: TokenIndex,
expr: *Node,
rparen: TokenIndex,
pub fn iterate(self: *const GroupedExpression, index: usize) ?*Node {
var i = index;
if (i < 1) return self.expr;
i -= 1;
return null;
}
pub fn firstToken(self: *const GroupedExpression) TokenIndex {
return self.lparen;
}
pub fn lastToken(self: *const GroupedExpression) TokenIndex {
return self.rparen;
}
};
/// TODO break this into separate Break, Continue, Return AST Nodes to save memory.
/// Could be further broken into LabeledBreak, LabeledContinue, and ReturnVoid to save even more.
pub const ControlFlowExpression = struct {
base: Node = Node{ .tag = .ControlFlowExpression },
ltoken: TokenIndex,
kind: Kind,
rhs: ?*Node,
pub const Kind = union(enum) {
Break: ?*Node,
Continue: ?*Node,
Return,
};
pub fn iterate(self: *const ControlFlowExpression, index: usize) ?*Node {
var i = index;
switch (self.kind) {
.Break, .Continue => |maybe_label| {
if (maybe_label) |label| {
if (i < 1) return label;
i -= 1;
}
},
.Return => {},
}
if (self.rhs) |rhs| {
if (i < 1) return rhs;
i -= 1;
}
return null;
}
pub fn firstToken(self: *const ControlFlowExpression) TokenIndex {
return self.ltoken;
}
pub fn lastToken(self: *const ControlFlowExpression) TokenIndex {
if (self.rhs) |rhs| {
return rhs.lastToken();
}
switch (self.kind) {
.Break, .Continue => |maybe_label| {
if (maybe_label) |label| {
return label.lastToken();
}
},
.Return => return self.ltoken,
}
return self.ltoken;
}
};
pub const Suspend = struct {
base: Node = Node{ .tag = .Suspend },
suspend_token: TokenIndex,
body: ?*Node,
pub fn iterate(self: *const Suspend, index: usize) ?*Node {
var i = index;
if (self.body) |body| {
if (i < 1) return body;
i -= 1;
}
return null;
}
pub fn firstToken(self: *const Suspend) TokenIndex {
return self.suspend_token;
}
pub fn lastToken(self: *const Suspend) TokenIndex {
if (self.body) |body| {
return body.lastToken();
}
return self.suspend_token;
}
};
pub const IntegerLiteral = struct {
base: Node = Node{ .tag = .IntegerLiteral },
token: TokenIndex,
pub fn iterate(self: *const IntegerLiteral, index: usize) ?*Node {
return null;
}
pub fn firstToken(self: *const IntegerLiteral) TokenIndex {
return self.token;
}
pub fn lastToken(self: *const IntegerLiteral) TokenIndex {
return self.token;
}
};
pub const EnumLiteral = struct {
base: Node = Node{ .tag = .EnumLiteral },
dot: TokenIndex,
name: TokenIndex,
pub fn iterate(self: *const EnumLiteral, index: usize) ?*Node {
return null;
}
pub fn firstToken(self: *const EnumLiteral) TokenIndex {
return self.dot;
}
pub fn lastToken(self: *const EnumLiteral) TokenIndex {
return self.name;
}
};
pub const FloatLiteral = struct {
base: Node = Node{ .tag = .FloatLiteral },
token: TokenIndex,
pub fn iterate(self: *const FloatLiteral, index: usize) ?*Node {
return null;
}
pub fn firstToken(self: *const FloatLiteral) TokenIndex {
return self.token;
}
pub fn lastToken(self: *const FloatLiteral) TokenIndex {
return self.token;
}
};
/// Parameters are in memory following BuiltinCall.
pub const BuiltinCall = struct {
base: Node = Node{ .tag = .BuiltinCall },
params_len: NodeIndex,
builtin_token: TokenIndex,
rparen_token: TokenIndex,
/// After this the caller must initialize the fields_and_decls list.
pub fn alloc(allocator: *mem.Allocator, params_len: NodeIndex) !*BuiltinCall {
const bytes = try allocator.alignedAlloc(u8, @alignOf(BuiltinCall), sizeInBytes(params_len));
return @ptrCast(*BuiltinCall, bytes.ptr);
}
pub fn free(self: *BuiltinCall, allocator: *mem.Allocator) void {
const bytes = @ptrCast([*]u8, self)[0..sizeInBytes(self.params_len)];
allocator.free(bytes);
}
pub fn iterate(self: *const BuiltinCall, index: usize) ?*Node {
var i = index;
if (i < self.params_len) return self.paramsConst()[i];
i -= self.params_len;
return null;
}
pub fn firstToken(self: *const BuiltinCall) TokenIndex {
return self.builtin_token;
}
pub fn lastToken(self: *const BuiltinCall) TokenIndex {
return self.rparen_token;
}
pub fn params(self: *BuiltinCall) []*Node {
const decls_start = @ptrCast([*]u8, self) + @sizeOf(BuiltinCall);
return @ptrCast([*]*Node, decls_start)[0..self.params_len];
}
pub fn paramsConst(self: *const BuiltinCall) []const *Node {
const decls_start = @ptrCast([*]const u8, self) + @sizeOf(BuiltinCall);
return @ptrCast([*]const *Node, decls_start)[0..self.params_len];
}
fn sizeInBytes(params_len: NodeIndex) usize {
return @sizeOf(BuiltinCall) + @sizeOf(*Node) * @as(usize, params_len);
}
};
pub const StringLiteral = struct {
base: Node = Node{ .tag = .StringLiteral },
token: TokenIndex,
pub fn iterate(self: *const StringLiteral, index: usize) ?*Node {
return null;
}
pub fn firstToken(self: *const StringLiteral) TokenIndex {
return self.token;
}
pub fn lastToken(self: *const StringLiteral) TokenIndex {
return self.token;
}
};
/// The string literal tokens appear directly in memory after MultilineStringLiteral.
pub const MultilineStringLiteral = struct {
base: Node = Node{ .tag = .MultilineStringLiteral },
lines_len: TokenIndex,
/// After this the caller must initialize the lines list.
pub fn alloc(allocator: *mem.Allocator, lines_len: NodeIndex) !*MultilineStringLiteral {
const bytes = try allocator.alignedAlloc(u8, @alignOf(MultilineStringLiteral), sizeInBytes(lines_len));
return @ptrCast(*MultilineStringLiteral, bytes.ptr);
}
pub fn free(self: *MultilineStringLiteral, allocator: *mem.Allocator) void {
const bytes = @ptrCast([*]u8, self)[0..sizeInBytes(self.lines_len)];
allocator.free(bytes);
}
pub fn iterate(self: *const MultilineStringLiteral, index: usize) ?*Node {
return null;
}
pub fn firstToken(self: *const MultilineStringLiteral) TokenIndex {
return self.linesConst()[0];
}
pub fn lastToken(self: *const MultilineStringLiteral) TokenIndex {
return self.linesConst()[self.lines_len - 1];
}
pub fn lines(self: *MultilineStringLiteral) []TokenIndex {
const decls_start = @ptrCast([*]u8, self) + @sizeOf(MultilineStringLiteral);
return @ptrCast([*]TokenIndex, decls_start)[0..self.lines_len];
}
pub fn linesConst(self: *const MultilineStringLiteral) []const TokenIndex {
const decls_start = @ptrCast([*]const u8, self) + @sizeOf(MultilineStringLiteral);
return @ptrCast([*]const TokenIndex, decls_start)[0..self.lines_len];
}
fn sizeInBytes(lines_len: NodeIndex) usize {
return @sizeOf(MultilineStringLiteral) + @sizeOf(TokenIndex) * @as(usize, lines_len);
}
};
pub const CharLiteral = struct {
base: Node = Node{ .tag = .CharLiteral },
token: TokenIndex,
pub fn iterate(self: *const CharLiteral, index: usize) ?*Node {
return null;
}
pub fn firstToken(self: *const CharLiteral) TokenIndex {
return self.token;
}
pub fn lastToken(self: *const CharLiteral) TokenIndex {
return self.token;
}
};
pub const BoolLiteral = struct {
base: Node = Node{ .tag = .BoolLiteral },
token: TokenIndex,
pub fn iterate(self: *const BoolLiteral, index: usize) ?*Node {
return null;
}
pub fn firstToken(self: *const BoolLiteral) TokenIndex {
return self.token;
}
pub fn lastToken(self: *const BoolLiteral) TokenIndex {
return self.token;
}
};
pub const NullLiteral = struct {
base: Node = Node{ .tag = .NullLiteral },
token: TokenIndex,
pub fn iterate(self: *const NullLiteral, index: usize) ?*Node {
return null;
}
pub fn firstToken(self: *const NullLiteral) TokenIndex {
return self.token;
}
pub fn lastToken(self: *const NullLiteral) TokenIndex {
return self.token;
}
};
pub const UndefinedLiteral = struct {
base: Node = Node{ .tag = .UndefinedLiteral },
token: TokenIndex,
pub fn iterate(self: *const UndefinedLiteral, index: usize) ?*Node {
return null;
}
pub fn firstToken(self: *const UndefinedLiteral) TokenIndex {
return self.token;
}
pub fn lastToken(self: *const UndefinedLiteral) TokenIndex {
return self.token;
}
};
pub const Asm = struct {
base: Node = Node{ .tag = .Asm },
asm_token: TokenIndex,
rparen: TokenIndex,
volatile_token: ?TokenIndex,
template: *Node,
outputs: []Output,
inputs: []Input,
/// A clobber node must be a StringLiteral or MultilineStringLiteral.
clobbers: []*Node,
pub const Output = struct {
lbracket: TokenIndex,
symbolic_name: *Node,
constraint: *Node,
kind: Kind,
rparen: TokenIndex,
pub const Kind = union(enum) {
Variable: *Identifier,
Return: *Node,
};
pub fn iterate(self: *const Output, index: usize) ?*Node {
var i = index;
if (i < 1) return self.symbolic_name;
i -= 1;
if (i < 1) return self.constraint;
i -= 1;
switch (self.kind) {
.Variable => |variable_name| {
if (i < 1) return &variable_name.base;
i -= 1;
},
.Return => |return_type| {
if (i < 1) return return_type;
i -= 1;
},
}
return null;
}
pub fn firstToken(self: *const Output) TokenIndex {
return self.lbracket;
}
pub fn lastToken(self: *const Output) TokenIndex {
return self.rparen;
}
};
pub const Input = struct {
lbracket: TokenIndex,
symbolic_name: *Node,
constraint: *Node,
expr: *Node,
rparen: TokenIndex,
pub fn iterate(self: *const Input, index: usize) ?*Node {
var i = index;
if (i < 1) return self.symbolic_name;
i -= 1;
if (i < 1) return self.constraint;
i -= 1;
if (i < 1) return self.expr;
i -= 1;
return null;
}
pub fn firstToken(self: *const Input) TokenIndex {
return self.lbracket;
}
pub fn lastToken(self: *const Input) TokenIndex {
return self.rparen;
}
};
pub fn iterate(self: *const Asm, index: usize) ?*Node {
var i = index;
if (i < self.outputs.len * 3) switch (i % 3) {
0 => return self.outputs[i / 3].symbolic_name,
1 => return self.outputs[i / 3].constraint,
2 => switch (self.outputs[i / 3].kind) {
.Variable => |variable_name| return &variable_name.base,
.Return => |return_type| return return_type,
},
else => unreachable,
};
i -= self.outputs.len * 3;
if (i < self.inputs.len * 3) switch (i % 3) {
0 => return self.inputs[i / 3].symbolic_name,
1 => return self.inputs[i / 3].constraint,
2 => return self.inputs[i / 3].expr,
else => unreachable,
};
i -= self.inputs.len * 3;
return null;
}
pub fn firstToken(self: *const Asm) TokenIndex {
return self.asm_token;
}
pub fn lastToken(self: *const Asm) TokenIndex {
return self.rparen;
}
};
pub const Unreachable = struct {
base: Node = Node{ .tag = .Unreachable },
token: TokenIndex,
pub fn iterate(self: *const Unreachable, index: usize) ?*Node {
return null;
}
pub fn firstToken(self: *const Unreachable) TokenIndex {
return self.token;
}
pub fn lastToken(self: *const Unreachable) TokenIndex {
return self.token;
}
};
pub const ErrorType = struct {
base: Node = Node{ .tag = .ErrorType },
token: TokenIndex,
pub fn iterate(self: *const ErrorType, index: usize) ?*Node {
return null;
}
pub fn firstToken(self: *const ErrorType) TokenIndex {
return self.token;
}
pub fn lastToken(self: *const ErrorType) TokenIndex {
return self.token;
}
};
pub const AnyType = struct {
base: Node = Node{ .tag = .AnyType },
token: TokenIndex,
pub fn iterate(self: *const AnyType, index: usize) ?*Node {
return null;
}
pub fn firstToken(self: *const AnyType) TokenIndex {
return self.token;
}
pub fn lastToken(self: *const AnyType) TokenIndex {
return self.token;
}
};
/// TODO remove from the Node base struct
/// TODO actually maybe remove entirely in favor of iterating backward from Node.firstToken()
/// and forwards to find same-line doc comments.
pub const DocComment = struct {
base: Node = Node{ .tag = .DocComment },
/// Points to the first doc comment token. API users are expected to iterate over the
/// tokens array, looking for more doc comments, ignoring line comments, and stopping
/// at the first other token.
first_line: TokenIndex,
pub fn iterate(self: *const DocComment, index: usize) ?*Node {
return null;
}
pub fn firstToken(self: *const DocComment) TokenIndex {
return self.first_line;
}
/// Returns the first doc comment line. Be careful, this may not be the desired behavior,
/// which would require the tokens array.
pub fn lastToken(self: *const DocComment) TokenIndex {
return self.first_line;
}
};
pub const TestDecl = struct {
base: Node = Node{ .tag = .TestDecl },
doc_comments: ?*DocComment,
test_token: TokenIndex,
name: *Node,
body_node: *Node,
pub fn iterate(self: *const TestDecl, index: usize) ?*Node {
var i = index;
if (i < 1) return self.body_node;
i -= 1;
return null;
}
pub fn firstToken(self: *const TestDecl) TokenIndex {
return self.test_token;
}
pub fn lastToken(self: *const TestDecl) TokenIndex {
return self.body_node.lastToken();
}
};
};
pub const PtrInfo = struct {
allowzero_token: ?TokenIndex = null,
align_info: ?Align = null,
const_token: ?TokenIndex = null,
volatile_token: ?TokenIndex = null,
sentinel: ?*Node = null,
pub const Align = struct {
node: *Node,
bit_range: ?BitRange = null,
pub const BitRange = struct {
start: *Node,
end: *Node,
};
};
};
test "iterate" {
var root = Node.Root{
.base = Node{ .tag = Node.Tag.Root },
.decls_len = 0,
.eof_token = 0,
};
var base = &root.base;
testing.expect(base.iterate(0) == null);
} | lib/std/zig/ast.zig |
const builtin = @import("builtin");
const std = @import("../std.zig");
const io = std.io;
const meta = std.meta;
const trait = std.trait;
const DefaultPrng = std.rand.DefaultPrng;
const expect = std.testing.expect;
const expectError = std.testing.expectError;
const mem = std.mem;
const fs = std.fs;
const File = std.fs.File;
test "write a file, read it, then delete it" {
var raw_bytes: [200 * 1024]u8 = undefined;
var allocator = &std.heap.FixedBufferAllocator.init(raw_bytes[0..]).allocator;
var data: [1024]u8 = undefined;
var prng = DefaultPrng.init(1234);
prng.random.bytes(data[0..]);
const tmp_file_name = "temp_test_file.txt";
{
var file = try File.openWrite(tmp_file_name);
defer file.close();
var file_out_stream = file.outStream();
var buf_stream = io.BufferedOutStream(File.WriteError).init(&file_out_stream.stream);
const st = &buf_stream.stream;
try st.print("begin");
try st.write(data[0..]);
try st.print("end");
try buf_stream.flush();
}
{
// make sure openWriteNoClobber doesn't harm the file
if (File.openWriteNoClobber(tmp_file_name, File.default_mode)) |file| {
unreachable;
} else |err| {
std.debug.assert(err == File.OpenError.PathAlreadyExists);
}
}
{
var file = try File.openRead(tmp_file_name);
defer file.close();
const file_size = try file.getEndPos();
const expected_file_size = "begin".len + data.len + "end".len;
expect(file_size == expected_file_size);
var file_in_stream = file.inStream();
var buf_stream = io.BufferedInStream(File.ReadError).init(&file_in_stream.stream);
const st = &buf_stream.stream;
const contents = try st.readAllAlloc(allocator, 2 * 1024);
defer allocator.free(contents);
expect(mem.eql(u8, contents[0.."begin".len], "begin"));
expect(mem.eql(u8, contents["begin".len .. contents.len - "end".len], data));
expect(mem.eql(u8, contents[contents.len - "end".len ..], "end"));
}
try fs.deleteFile(tmp_file_name);
}
test "BufferOutStream" {
var bytes: [100]u8 = undefined;
var allocator = &std.heap.FixedBufferAllocator.init(bytes[0..]).allocator;
var buffer = try std.Buffer.initSize(allocator, 0);
var buf_stream = &std.io.BufferOutStream.init(&buffer).stream;
const x: i32 = 42;
const y: i32 = 1234;
try buf_stream.print("x: {}\ny: {}\n", x, y);
expect(mem.eql(u8, buffer.toSlice(), "x: 42\ny: 1234\n"));
}
test "SliceInStream" {
const bytes = [_]u8{ 1, 2, 3, 4, 5, 6, 7 };
var ss = io.SliceInStream.init(bytes);
var dest: [4]u8 = undefined;
var read = try ss.stream.read(dest[0..4]);
expect(read == 4);
expect(mem.eql(u8, dest[0..4], bytes[0..4]));
read = try ss.stream.read(dest[0..4]);
expect(read == 3);
expect(mem.eql(u8, dest[0..3], bytes[4..7]));
read = try ss.stream.read(dest[0..4]);
expect(read == 0);
}
test "PeekStream" {
const bytes = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8 };
var ss = io.SliceInStream.init(bytes);
var ps = io.PeekStream(2, io.SliceInStream.Error).init(&ss.stream);
var dest: [4]u8 = undefined;
ps.putBackByte(9);
ps.putBackByte(10);
var read = try ps.stream.read(dest[0..4]);
expect(read == 4);
expect(dest[0] == 10);
expect(dest[1] == 9);
expect(mem.eql(u8, dest[2..4], bytes[0..2]));
read = try ps.stream.read(dest[0..4]);
expect(read == 4);
expect(mem.eql(u8, dest[0..4], bytes[2..6]));
read = try ps.stream.read(dest[0..4]);
expect(read == 2);
expect(mem.eql(u8, dest[0..2], bytes[6..8]));
ps.putBackByte(11);
ps.putBackByte(12);
read = try ps.stream.read(dest[0..4]);
expect(read == 2);
expect(dest[0] == 12);
expect(dest[1] == 11);
}
test "SliceOutStream" {
var buffer: [10]u8 = undefined;
var ss = io.SliceOutStream.init(buffer[0..]);
try ss.stream.write("Hello");
expect(mem.eql(u8, ss.getWritten(), "Hello"));
try ss.stream.write("world");
expect(mem.eql(u8, ss.getWritten(), "Helloworld"));
expectError(error.OutOfSpace, ss.stream.write("!"));
expect(mem.eql(u8, ss.getWritten(), "Helloworld"));
ss.reset();
expect(ss.getWritten().len == 0);
expectError(error.OutOfSpace, ss.stream.write("Hello world!"));
expect(mem.eql(u8, ss.getWritten(), "Hello worl"));
}
test "BitInStream" {
const mem_be = [_]u8{ 0b11001101, 0b00001011 };
const mem_le = [_]u8{ 0b00011101, 0b10010101 };
var mem_in_be = io.SliceInStream.init(mem_be[0..]);
const InError = io.SliceInStream.Error;
var bit_stream_be = io.BitInStream(builtin.Endian.Big, InError).init(&mem_in_be.stream);
var out_bits: usize = undefined;
expect(1 == try bit_stream_be.readBits(u2, 1, &out_bits));
expect(out_bits == 1);
expect(2 == try bit_stream_be.readBits(u5, 2, &out_bits));
expect(out_bits == 2);
expect(3 == try bit_stream_be.readBits(u128, 3, &out_bits));
expect(out_bits == 3);
expect(4 == try bit_stream_be.readBits(u8, 4, &out_bits));
expect(out_bits == 4);
expect(5 == try bit_stream_be.readBits(u9, 5, &out_bits));
expect(out_bits == 5);
expect(1 == try bit_stream_be.readBits(u1, 1, &out_bits));
expect(out_bits == 1);
mem_in_be.pos = 0;
bit_stream_be.bit_count = 0;
expect(0b110011010000101 == try bit_stream_be.readBits(u15, 15, &out_bits));
expect(out_bits == 15);
mem_in_be.pos = 0;
bit_stream_be.bit_count = 0;
expect(0b1100110100001011 == try bit_stream_be.readBits(u16, 16, &out_bits));
expect(out_bits == 16);
_ = try bit_stream_be.readBits(u0, 0, &out_bits);
expect(0 == try bit_stream_be.readBits(u1, 1, &out_bits));
expect(out_bits == 0);
expectError(error.EndOfStream, bit_stream_be.readBitsNoEof(u1, 1));
var mem_in_le = io.SliceInStream.init(mem_le[0..]);
var bit_stream_le = io.BitInStream(builtin.Endian.Little, InError).init(&mem_in_le.stream);
expect(1 == try bit_stream_le.readBits(u2, 1, &out_bits));
expect(out_bits == 1);
expect(2 == try bit_stream_le.readBits(u5, 2, &out_bits));
expect(out_bits == 2);
expect(3 == try bit_stream_le.readBits(u128, 3, &out_bits));
expect(out_bits == 3);
expect(4 == try bit_stream_le.readBits(u8, 4, &out_bits));
expect(out_bits == 4);
expect(5 == try bit_stream_le.readBits(u9, 5, &out_bits));
expect(out_bits == 5);
expect(1 == try bit_stream_le.readBits(u1, 1, &out_bits));
expect(out_bits == 1);
mem_in_le.pos = 0;
bit_stream_le.bit_count = 0;
expect(0b001010100011101 == try bit_stream_le.readBits(u15, 15, &out_bits));
expect(out_bits == 15);
mem_in_le.pos = 0;
bit_stream_le.bit_count = 0;
expect(0b1001010100011101 == try bit_stream_le.readBits(u16, 16, &out_bits));
expect(out_bits == 16);
_ = try bit_stream_le.readBits(u0, 0, &out_bits);
expect(0 == try bit_stream_le.readBits(u1, 1, &out_bits));
expect(out_bits == 0);
expectError(error.EndOfStream, bit_stream_le.readBitsNoEof(u1, 1));
}
test "BitOutStream" {
var mem_be = [_]u8{0} ** 2;
var mem_le = [_]u8{0} ** 2;
var mem_out_be = io.SliceOutStream.init(mem_be[0..]);
const OutError = io.SliceOutStream.Error;
var bit_stream_be = io.BitOutStream(builtin.Endian.Big, OutError).init(&mem_out_be.stream);
try bit_stream_be.writeBits(u2(1), 1);
try bit_stream_be.writeBits(u5(2), 2);
try bit_stream_be.writeBits(u128(3), 3);
try bit_stream_be.writeBits(u8(4), 4);
try bit_stream_be.writeBits(u9(5), 5);
try bit_stream_be.writeBits(u1(1), 1);
expect(mem_be[0] == 0b11001101 and mem_be[1] == 0b00001011);
mem_out_be.pos = 0;
try bit_stream_be.writeBits(u15(0b110011010000101), 15);
try bit_stream_be.flushBits();
expect(mem_be[0] == 0b11001101 and mem_be[1] == 0b00001010);
mem_out_be.pos = 0;
try bit_stream_be.writeBits(u32(0b110011010000101), 16);
expect(mem_be[0] == 0b01100110 and mem_be[1] == 0b10000101);
try bit_stream_be.writeBits(u0(0), 0);
var mem_out_le = io.SliceOutStream.init(mem_le[0..]);
var bit_stream_le = io.BitOutStream(builtin.Endian.Little, OutError).init(&mem_out_le.stream);
try bit_stream_le.writeBits(u2(1), 1);
try bit_stream_le.writeBits(u5(2), 2);
try bit_stream_le.writeBits(u128(3), 3);
try bit_stream_le.writeBits(u8(4), 4);
try bit_stream_le.writeBits(u9(5), 5);
try bit_stream_le.writeBits(u1(1), 1);
expect(mem_le[0] == 0b00011101 and mem_le[1] == 0b10010101);
mem_out_le.pos = 0;
try bit_stream_le.writeBits(u15(0b110011010000101), 15);
try bit_stream_le.flushBits();
expect(mem_le[0] == 0b10000101 and mem_le[1] == 0b01100110);
mem_out_le.pos = 0;
try bit_stream_le.writeBits(u32(0b1100110100001011), 16);
expect(mem_le[0] == 0b00001011 and mem_le[1] == 0b11001101);
try bit_stream_le.writeBits(u0(0), 0);
}
test "BitStreams with File Stream" {
const tmp_file_name = "temp_test_file.txt";
{
var file = try File.openWrite(tmp_file_name);
defer file.close();
var file_out = file.outStream();
var file_out_stream = &file_out.stream;
const OutError = File.WriteError;
var bit_stream = io.BitOutStream(builtin.endian, OutError).init(file_out_stream);
try bit_stream.writeBits(u2(1), 1);
try bit_stream.writeBits(u5(2), 2);
try bit_stream.writeBits(u128(3), 3);
try bit_stream.writeBits(u8(4), 4);
try bit_stream.writeBits(u9(5), 5);
try bit_stream.writeBits(u1(1), 1);
try bit_stream.flushBits();
}
{
var file = try File.openRead(tmp_file_name);
defer file.close();
var file_in = file.inStream();
var file_in_stream = &file_in.stream;
const InError = File.ReadError;
var bit_stream = io.BitInStream(builtin.endian, InError).init(file_in_stream);
var out_bits: usize = undefined;
expect(1 == try bit_stream.readBits(u2, 1, &out_bits));
expect(out_bits == 1);
expect(2 == try bit_stream.readBits(u5, 2, &out_bits));
expect(out_bits == 2);
expect(3 == try bit_stream.readBits(u128, 3, &out_bits));
expect(out_bits == 3);
expect(4 == try bit_stream.readBits(u8, 4, &out_bits));
expect(out_bits == 4);
expect(5 == try bit_stream.readBits(u9, 5, &out_bits));
expect(out_bits == 5);
expect(1 == try bit_stream.readBits(u1, 1, &out_bits));
expect(out_bits == 1);
expectError(error.EndOfStream, bit_stream.readBitsNoEof(u1, 1));
}
try fs.deleteFile(tmp_file_name);
}
fn testIntSerializerDeserializer(comptime endian: builtin.Endian, comptime packing: io.Packing) !void {
//@NOTE: if this test is taking too long, reduce the maximum tested bitsize
const max_test_bitsize = 128;
const total_bytes = comptime blk: {
var bytes = 0;
comptime var i = 0;
while (i <= max_test_bitsize) : (i += 1) bytes += (i / 8) + @boolToInt(i % 8 > 0);
break :blk bytes * 2;
};
var data_mem: [total_bytes]u8 = undefined;
var out = io.SliceOutStream.init(data_mem[0..]);
const OutError = io.SliceOutStream.Error;
var out_stream = &out.stream;
var serializer = io.Serializer(endian, packing, OutError).init(out_stream);
var in = io.SliceInStream.init(data_mem[0..]);
const InError = io.SliceInStream.Error;
var in_stream = &in.stream;
var deserializer = io.Deserializer(endian, packing, InError).init(in_stream);
comptime var i = 0;
inline while (i <= max_test_bitsize) : (i += 1) {
const U = @IntType(false, i);
const S = @IntType(true, i);
try serializer.serializeInt(U(i));
if (i != 0) try serializer.serializeInt(S(-1)) else try serializer.serialize(S(0));
}
try serializer.flush();
i = 0;
inline while (i <= max_test_bitsize) : (i += 1) {
const U = @IntType(false, i);
const S = @IntType(true, i);
const x = try deserializer.deserializeInt(U);
const y = try deserializer.deserializeInt(S);
expect(x == U(i));
if (i != 0) expect(y == S(-1)) else expect(y == 0);
}
const u8_bit_count = comptime meta.bitCount(u8);
//0 + 1 + 2 + ... n = (n * (n + 1)) / 2
//and we have each for unsigned and signed, so * 2
const total_bits = (max_test_bitsize * (max_test_bitsize + 1));
const extra_packed_byte = @boolToInt(total_bits % u8_bit_count > 0);
const total_packed_bytes = (total_bits / u8_bit_count) + extra_packed_byte;
expect(in.pos == if (packing == .Bit) total_packed_bytes else total_bytes);
//Verify that empty error set works with serializer.
//deserializer is covered by SliceInStream
const NullError = io.NullOutStream.Error;
var null_out = io.NullOutStream.init();
var null_out_stream = &null_out.stream;
var null_serializer = io.Serializer(endian, packing, NullError).init(null_out_stream);
try null_serializer.serialize(data_mem[0..]);
try null_serializer.flush();
}
test "Serializer/Deserializer Int" {
try testIntSerializerDeserializer(.Big, .Byte);
try testIntSerializerDeserializer(.Little, .Byte);
// TODO these tests are disabled due to tripping an LLVM assertion
// https://github.com/ziglang/zig/issues/2019
//try testIntSerializerDeserializer(builtin.Endian.Big, true);
//try testIntSerializerDeserializer(builtin.Endian.Little, true);
}
fn testIntSerializerDeserializerInfNaN(
comptime endian: builtin.Endian,
comptime packing: io.Packing,
) !void {
const mem_size = (16 * 2 + 32 * 2 + 64 * 2 + 128 * 2) / comptime meta.bitCount(u8);
var data_mem: [mem_size]u8 = undefined;
var out = io.SliceOutStream.init(data_mem[0..]);
const OutError = io.SliceOutStream.Error;
var out_stream = &out.stream;
var serializer = io.Serializer(endian, packing, OutError).init(out_stream);
var in = io.SliceInStream.init(data_mem[0..]);
const InError = io.SliceInStream.Error;
var in_stream = &in.stream;
var deserializer = io.Deserializer(endian, packing, InError).init(in_stream);
//@TODO: isInf/isNan not currently implemented for f128.
try serializer.serialize(std.math.nan(f16));
try serializer.serialize(std.math.inf(f16));
try serializer.serialize(std.math.nan(f32));
try serializer.serialize(std.math.inf(f32));
try serializer.serialize(std.math.nan(f64));
try serializer.serialize(std.math.inf(f64));
//try serializer.serialize(std.math.nan(f128));
//try serializer.serialize(std.math.inf(f128));
const nan_check_f16 = try deserializer.deserialize(f16);
const inf_check_f16 = try deserializer.deserialize(f16);
const nan_check_f32 = try deserializer.deserialize(f32);
deserializer.alignToByte();
const inf_check_f32 = try deserializer.deserialize(f32);
const nan_check_f64 = try deserializer.deserialize(f64);
const inf_check_f64 = try deserializer.deserialize(f64);
//const nan_check_f128 = try deserializer.deserialize(f128);
//const inf_check_f128 = try deserializer.deserialize(f128);
expect(std.math.isNan(nan_check_f16));
expect(std.math.isInf(inf_check_f16));
expect(std.math.isNan(nan_check_f32));
expect(std.math.isInf(inf_check_f32));
expect(std.math.isNan(nan_check_f64));
expect(std.math.isInf(inf_check_f64));
//expect(std.math.isNan(nan_check_f128));
//expect(std.math.isInf(inf_check_f128));
}
test "Serializer/Deserializer Int: Inf/NaN" {
try testIntSerializerDeserializerInfNaN(.Big, .Byte);
try testIntSerializerDeserializerInfNaN(.Little, .Byte);
try testIntSerializerDeserializerInfNaN(.Big, .Bit);
try testIntSerializerDeserializerInfNaN(.Little, .Bit);
}
fn testAlternateSerializer(self: var, serializer: var) !void {
try serializer.serialize(self.f_f16);
}
fn testSerializerDeserializer(comptime endian: builtin.Endian, comptime packing: io.Packing) !void {
const ColorType = enum(u4) {
RGB8 = 1,
RA16 = 2,
R32 = 3,
};
const TagAlign = union(enum(u32)) {
A: u8,
B: u8,
C: u8,
};
const Color = union(ColorType) {
RGB8: struct {
r: u8,
g: u8,
b: u8,
a: u8,
},
RA16: struct {
r: u16,
a: u16,
},
R32: u32,
};
const PackedStruct = packed struct {
f_i3: i3,
f_u2: u2,
};
//to test custom serialization
const Custom = struct {
f_f16: f16,
f_unused_u32: u32,
pub fn deserialize(self: *@This(), deserializer: var) !void {
try deserializer.deserializeInto(&self.f_f16);
self.f_unused_u32 = 47;
}
pub const serialize = testAlternateSerializer;
};
const MyStruct = struct {
f_i3: i3,
f_u8: u8,
f_tag_align: TagAlign,
f_u24: u24,
f_i19: i19,
f_void: void,
f_f32: f32,
f_f128: f128,
f_packed_0: PackedStruct,
f_i7arr: [10]i7,
f_of64n: ?f64,
f_of64v: ?f64,
f_color_type: ColorType,
f_packed_1: PackedStruct,
f_custom: Custom,
f_color: Color,
};
const my_inst = MyStruct{
.f_i3 = -1,
.f_u8 = 8,
.f_tag_align = TagAlign{ .B = 148 },
.f_u24 = 24,
.f_i19 = 19,
.f_void = {},
.f_f32 = 32.32,
.f_f128 = 128.128,
.f_packed_0 = PackedStruct{ .f_i3 = -1, .f_u2 = 2 },
.f_i7arr = [10]i7{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
.f_of64n = null,
.f_of64v = 64.64,
.f_color_type = ColorType.R32,
.f_packed_1 = PackedStruct{ .f_i3 = 1, .f_u2 = 1 },
.f_custom = Custom{ .f_f16 = 38.63, .f_unused_u32 = 47 },
.f_color = Color{ .R32 = 123822 },
};
var data_mem: [@sizeOf(MyStruct)]u8 = undefined;
var out = io.SliceOutStream.init(data_mem[0..]);
const OutError = io.SliceOutStream.Error;
var out_stream = &out.stream;
var serializer = io.Serializer(endian, packing, OutError).init(out_stream);
var in = io.SliceInStream.init(data_mem[0..]);
const InError = io.SliceInStream.Error;
var in_stream = &in.stream;
var deserializer = io.Deserializer(endian, packing, InError).init(in_stream);
try serializer.serialize(my_inst);
const my_copy = try deserializer.deserialize(MyStruct);
expect(meta.eql(my_copy, my_inst));
}
test "Serializer/Deserializer generic" {
try testSerializerDeserializer(builtin.Endian.Big, .Byte);
try testSerializerDeserializer(builtin.Endian.Little, .Byte);
try testSerializerDeserializer(builtin.Endian.Big, .Bit);
try testSerializerDeserializer(builtin.Endian.Little, .Bit);
}
fn testBadData(comptime endian: builtin.Endian, comptime packing: io.Packing) !void {
const E = enum(u14) {
One = 1,
Two = 2,
};
const A = struct {
e: E,
};
const C = union(E) {
One: u14,
Two: f16,
};
var data_mem: [4]u8 = undefined;
var out = io.SliceOutStream.init(data_mem[0..]);
const OutError = io.SliceOutStream.Error;
var out_stream = &out.stream;
var serializer = io.Serializer(endian, packing, OutError).init(out_stream);
var in = io.SliceInStream.init(data_mem[0..]);
const InError = io.SliceInStream.Error;
var in_stream = &in.stream;
var deserializer = io.Deserializer(endian, packing, InError).init(in_stream);
try serializer.serialize(u14(3));
expectError(error.InvalidEnumTag, deserializer.deserialize(A));
out.pos = 0;
try serializer.serialize(u14(3));
try serializer.serialize(u14(88));
expectError(error.InvalidEnumTag, deserializer.deserialize(C));
}
test "Deserializer bad data" {
try testBadData(.Big, .Byte);
try testBadData(.Little, .Byte);
try testBadData(.Big, .Bit);
try testBadData(.Little, .Bit);
}
test "c out stream" {
if (!builtin.link_libc) return error.SkipZigTest;
const filename = c"tmp_io_test_file.txt";
const out_file = std.c.fopen(filename, c"w") orelse return error.UnableToOpenTestFile;
defer {
_ = std.c.fclose(out_file);
fs.deleteFileC(filename) catch {};
}
const out_stream = &io.COutStream.init(out_file).stream;
try out_stream.print("hi: {}\n", i32(123));
}
test "File seek ops" {
const tmp_file_name = "temp_test_file.txt";
var file = try File.openWrite(tmp_file_name);
defer {
file.close();
fs.deleteFile(tmp_file_name) catch {};
}
try file.write([_]u8{0x55} ** 8192);
// Seek to the end
try file.seekFromEnd(0);
std.testing.expect((try file.getPos()) == try file.getEndPos());
// Negative delta
try file.seekBy(-4096);
std.testing.expect((try file.getPos()) == 4096);
// Positive delta
try file.seekBy(10);
std.testing.expect((try file.getPos()) == 4106);
// Absolute position
try file.seekTo(1234);
std.testing.expect((try file.getPos()) == 1234);
}
test "updateTimes" {
const tmp_file_name = "just_a_temporary_file.txt";
var file = try File.openWrite(tmp_file_name);
defer {
file.close();
std.fs.deleteFile(tmp_file_name) catch {};
}
var stat_old = try file.stat();
// Set atime and mtime to 5s before
try file.updateTimes(
stat_old.atime - 5 * std.time.ns_per_s,
stat_old.mtime - 5 * std.time.ns_per_s,
);
var stat_new = try file.stat();
std.testing.expect(stat_new.atime < stat_old.atime);
std.testing.expect(stat_new.mtime < stat_old.mtime);
} | lib/std/io/test.zig |
const aoc = @import("../aoc.zig");
const std = @import("std");
const Command = union(enum) {
// RotateBased tables for password.len = 8
const rotate_based_table = [_]u8 { 7, 6, 5, 4, 2, 1, 0, 7 };
const inverse_rotate_based_table = [_]u8 { 1, 1, 6, 2, 7, 3, 0, 4 };
SwapPosition: struct { pos_x: u8, pos_y: u8 },
SwapLetter: struct { letter_x: u8, letter_y: u8 },
RotateLeft: u8,
RotateRight: u8,
RotateBased: u8,
Reverse: struct { pos_x: u8, pos_y: u8 },
Move: struct { pos_x: u8, pos_y: u8 },
InverseRotateBased: u8,
fn process(self: Command, password: []u8) void {
switch (self) {
.SwapPosition => |sp| std.mem.swap(u8, &password[sp.pos_x], &password[sp.pos_y]),
.SwapLetter => |sl| std.mem.swap(u8, &password[std.mem.indexOfScalar(u8, password, sl.letter_x).?], &password[std.mem.indexOfScalar(u8, password, sl.letter_y).?]),
.RotateLeft => |rl| std.mem.rotate(u8, password, rl),
.RotateRight => |rr| std.mem.rotate(u8, password, password.len - rr),
.RotateBased => |rb| std.mem.rotate(u8, password, rotate_based_table[std.mem.indexOfScalar(u8, password, rb).?]),
.Reverse => |r| std.mem.reverse(u8, password[r.pos_x..r.pos_y+1]),
.Move => |m|
if (m.pos_x < m.pos_y) {
std.mem.rotate(u8, password[m.pos_x..m.pos_y + 1], 1);
}
else {
std.mem.rotate(u8, password[m.pos_y..m.pos_x + 1], m.pos_x - m.pos_y);
}
,
.InverseRotateBased => |irb| std.mem.rotate(u8, password, inverse_rotate_based_table[std.mem.indexOfScalar(u8, password, irb).?]),
}
}
fn inverse(self: Command) Command {
return switch (self) {
.SwapPosition => self,
.SwapLetter => self,
.RotateLeft => |rl| .{ .RotateRight = rl },
.RotateRight => |rr| .{ .RotateLeft = rr },
.RotateBased => |rb| .{ .InverseRotateBased = rb },
.Reverse => self,
.Move => |m| .{ .Move = .{ .pos_x = m.pos_y, .pos_y = m.pos_x } },
.InverseRotateBased => unreachable,
};
}
};
pub fn run(problem: *aoc.Problem) !aoc.Solution {
var commands = std.ArrayList(Command).init(problem.allocator);
defer commands.deinit();
while (problem.line()) |line| {
const command = blk: {
var tokens = std.mem.tokenize(u8, line, " ");
const instr1 = tokens.next().?;
const instr2 = tokens.next().?;
if (std.mem.eql(u8, instr1, "swap")) {
const x = tokens.next().?;
_ = tokens.next().?;
_ = tokens.next().?;
const y = tokens.next().?;
break :blk if (std.mem.eql(u8, instr2, "position"))
Command{ .SwapPosition = .{ .pos_x = try std.fmt.parseInt(u8, x, 10), .pos_y = try std.fmt.parseInt(u8, y, 10) } }
else
Command{ .SwapLetter = .{ .letter_x = x[0], .letter_y = y[0] } }
;
}
if (std.mem.eql(u8, instr1, "rotate")) {
if (std.mem.eql(u8, instr2, "based")) {
_ = tokens.next().?;
_ = tokens.next().?;
_ = tokens.next().?;
_ = tokens.next().?;
const x = tokens.next().?;
break :blk Command{ .RotateBased = x[0] };
}
const x = try std.fmt.parseInt(u8, tokens.next().?, 10);
break :blk if (std.mem.eql(u8, instr2, "left"))
Command{ .RotateLeft = x }
else
Command{ .RotateRight = x }
;
}
if (std.mem.eql(u8, instr1, "reverse")) {
const x = try std.fmt.parseInt(u8, tokens.next().?, 10);
_ = tokens.next().?;
const y = try std.fmt.parseInt(u8, tokens.next().?, 10);
break :blk Command{ .Reverse = .{ .pos_x = x, .pos_y = y } };
}
if (std.mem.eql(u8, instr1, "move")) {
const x = try std.fmt.parseInt(u8, tokens.next().?, 10);
_ = tokens.next().?;
_ = tokens.next().?;
const y = try std.fmt.parseInt(u8, tokens.next().?, 10);
break :blk Command{ .Move = .{ .pos_x = x, .pos_y = y } };
}
unreachable;
};
try commands.append(command);
}
const s1 = blk: {
var password: [8]u8 = undefined;
std.mem.copy(u8, &password, "abcdefgh");
for (commands.items) |command| {
command.process(&password);
}
break :blk password;
};
const s2 = blk: {
var password: [8]u8 = undefined;
std.mem.copy(u8, &password, "<PASSWORD>");
var command_idx: usize = commands.items.len - 1;
while (true) : (command_idx -= 1) {
commands.items[command_idx].inverse().process(&password);
if (command_idx == 0) {
break :blk password;
}
}
unreachable;
};
return problem.solution(&s1, &s2);
} | src/main/zig/2016/day21.zig |
const std = @import("std");
const mem = std.mem;
const testing = std.testing;
const c = @import("c.zig").c;
const Error = @import("errors.zig").Error;
const getError = @import("errors.zig").getError;
const GammaRamp = @import("GammaRamp.zig");
const VideoMode = @import("VideoMode.zig");
const Monitor = @This();
handle: *c.GLFWmonitor,
/// A monitor position, in screen coordinates, of the upper left corner of the monitor on the
/// virtual screen.
const Pos = struct {
/// The x coordinate.
x: usize,
/// The y coordinate.
y: usize,
};
/// Returns the position of the monitor's viewport on the virtual screen.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_properties
pub inline fn getPos(self: Monitor) Error!Pos {
var xpos: c_int = 0;
var ypos: c_int = 0;
c.glfwGetMonitorPos(self.handle, &xpos, &ypos);
try getError();
return Pos{ .x = @intCast(usize, xpos), .y = @intCast(usize, ypos) };
}
/// The monitor workarea, in screen coordinates.
///
/// This is the position of the upper-left corner of the work area of the monitor, along with the
/// work area size. The work area is defined as the area of the monitor not occluded by the
/// operating system task bar where present. If no task bar exists then the work area is the
/// monitor resolution in screen coordinates.
const Workarea = struct {
x: usize,
y: usize,
width: usize,
height: usize,
};
/// Retrieves the work area of the monitor.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_workarea
pub inline fn getWorkarea(self: Monitor) Error!Workarea {
var xpos: c_int = 0;
var ypos: c_int = 0;
var width: c_int = 0;
var height: c_int = 0;
c.glfwGetMonitorWorkarea(self.handle, &xpos, &ypos, &width, &height);
try getError();
return Workarea{ .x = @intCast(usize, xpos), .y = @intCast(usize, ypos), .width = @intCast(usize, width), .height = @intCast(usize, height) };
}
/// The physical size, in millimetres, of the display area of a monitor.
const PhysicalSize = struct {
width_mm: usize,
height_mm: usize,
};
/// Returns the physical size of the monitor.
///
/// Some systems do not provide accurate monitor size information, either because the monitor
/// [EDID](https://en.wikipedia.org/wiki/Extended_display_identification_data)
/// data is incorrect or because the driver does not report it accurately.
///
/// Possible errors include glfw.Error.NotInitialized.
///
/// win32: calculates the returned physical size from the current resolution and system DPI
/// instead of querying the monitor EDID data.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_properties
pub inline fn getPhysicalSize(self: Monitor) Error!PhysicalSize {
var width_mm: c_int = 0;
var height_mm: c_int = 0;
c.glfwGetMonitorPhysicalSize(self.handle, &width_mm, &height_mm);
try getError();
return PhysicalSize{ .width_mm = @intCast(usize, width_mm), .height_mm = @intCast(usize, height_mm) };
}
/// The content scale for a monitor.
///
/// This is the ratio between the current DPI and the platform's default DPI. This is especially
/// important for text and any UI elements. If the pixel dimensions of your UI scaled by this look
/// appropriate on your machine then it should appear at a reasonable size on other machines
/// regardless of their DPI and scaling settings. This relies on the system DPI and scaling
/// settings being somewhat correct.
///
/// The content scale may depend on both the monitor resolution and pixel density and on users
/// settings. It may be very different from the raw DPI calculated from the physical size and
/// current resolution.
const ContentScale = struct {
x_scale: f32,
y_scale: f32,
};
/// Returns the content scale for the monitor.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_scale, glfw.Window.getContentScale
pub inline fn getContentScale(self: Monitor) Error!ContentScale {
var x_scale: f32 = 0;
var y_scale: f32 = 0;
c.glfwGetMonitorContentScale(self.handle, &x_scale, &y_scale);
try getError();
return ContentScale{ .x_scale = @floatCast(f32, x_scale), .y_scale = @floatCast(f32, y_scale) };
}
/// Returns the name of the specified monitor.
///
/// This function returns a human-readable name, encoded as UTF-8, of the specified monitor. The
/// name typically reflects the make and model of the monitor and is not guaranteed to be unique
/// among the connected monitors.
///
/// Possible errors include glfw.Error.NotInitialized.
///
/// @pointer_lifetime The returned string is allocated and freed by GLFW. You should not free it
/// yourself. It is valid until the specified monitor is disconnected or the library is terminated.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_properties
pub inline fn getName(self: Monitor) Error![*c]const u8 {
const name = c.glfwGetMonitorName(self.handle);
try getError();
return name;
}
/// Sets the user pointer of the specified monitor.
///
/// This function sets the user-defined pointer of the specified monitor. The current value is
/// retained until the monitor is disconnected.
///
/// This function may be called from the monitor callback, even for a monitor that is being
/// disconnected.
///
/// Possible errors include glfw.Error.NotInitialized.
///
/// @thread_safety This function may be called from any thread. Access is not synchronized.
///
/// see also: monitor_userptr, glfw.Monitor.getUserPointer
pub inline fn setUserPointer(self: Monitor, comptime T: type, ptr: *T) Error!void {
c.glfwSetMonitorUserPointer(self.handle, ptr);
try getError();
}
/// Returns the user pointer of the specified monitor.
///
/// This function returns the current value of the user-defined pointer of the specified monitor.
///
/// This function may be called from the monitor callback, even for a monitor that is being
/// disconnected.
///
/// Possible errors include glfw.Error.NotInitialized.
///
/// @thread_safety This function may be called from any thread. Access is not synchronized.
///
/// see also: monitor_userptr, glfw.Monitor.setUserPointer
pub inline fn getUserPointer(self: Monitor, comptime T: type) Error!?*T {
const ptr = c.glfwGetMonitorUserPointer(self.handle);
try getError();
if (ptr == null) return null;
return @ptrCast(*T, @alignCast(@alignOf(T), ptr.?));
}
/// Returns the available video modes for the specified monitor.
///
/// This function returns an array of all video modes supported by the monitor. The returned slice
/// is sorted in ascending order, first by color bit depth (the sum of all channel depths) and
/// then by resolution area (the product of width and height).
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// The returned slice memory is owned by the caller.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_modes, glfw.Monitor.getVideoMode
pub inline fn getVideoModes(self: Monitor, allocator: *mem.Allocator) Error![]VideoMode {
var count: c_int = 0;
const modes = c.glfwGetVideoModes(self.handle, &count);
try getError();
const slice = try allocator.alloc(VideoMode, @intCast(usize, count));
var i: usize = 0;
while (i < count) : (i += 1) {
slice[i] = VideoMode{ .handle = modes[i] };
}
return slice;
}
/// Returns the current mode of the specified monitor.
///
/// This function returns the current video mode of the specified monitor. If you have created a
/// full screen window for that monitor, the return value will depend on whether that window is
/// iconified.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_modes, glfw.Monitor.getVideoModes
pub inline fn getVideoMode(self: Monitor) Error!VideoMode {
const mode = c.glfwGetVideoMode(self.handle);
try getError();
return VideoMode{ .handle = mode.?.* };
}
/// Generates a gamma ramp and sets it for the specified monitor.
///
/// This function generates an appropriately sized gamma ramp from the specified exponent and then
/// calls glfw.Monitor.setGammaRamp with it. The value must be a finite number greater than zero.
///
/// The software controlled gamma ramp is applied _in addition_ to the hardware gamma correction,
/// which today is usually an approximation of sRGB gamma. This means that setting a perfectly
/// linear ramp, or gamma 1.0, will produce the default (usually sRGB-like) behavior.
///
/// For gamma correct rendering with OpenGL or OpenGL ES, see the glfw.srgb_capable hint.
///
/// Possible errors include glfw.Error.NotInitialized, glfw.Error.InvalidValue and glfw.Error.PlatformError.
///
/// wayland: Gamma handling is a privileged protocol, this function will thus never be implemented
/// and emits glfw.Error.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_gamma
pub inline fn setGamma(self: Monitor, gamma: f32) Error!void {
c.glfwSetGamma(self.handle, gamma);
try getError();
}
/// Returns the current gamma ramp for the specified monitor.
///
/// This function returns the current gamma ramp of the specified monitor.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// wayland: Gamma handling is a privileged protocol, this function will thus never be implemented
/// and returns glfw.Error.PlatformError.
///
/// The returned gamma ramp is `.owned = true` by GLFW, and is valid until the monitor is
/// disconnected, this function is called again, or `glfw.terminate()` is called.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_gamma
pub inline fn getGammaRamp(self: Monitor) Error!GammaRamp {
const ramp = c.glfwGetGammaRamp(self.handle);
try getError();
return GammaRamp.fromC(ramp.*);
}
/// Sets the current gamma ramp for the specified monitor.
///
/// This function sets the current gamma ramp for the specified monitor. The original gamma ramp
/// for that monitor is saved by GLFW the first time this function is called and is restored by
/// `glfw.terminate()`.
///
/// The software controlled gamma ramp is applied _in addition_ to the hardware gamma correction,
/// which today is usually an approximation of sRGB gamma. This means that setting a perfectly
/// linear ramp, or gamma 1.0, will produce the default (usually sRGB-like) behavior.
///
/// For gamma correct rendering with OpenGL or OpenGL ES, see the glfw.srgb_capable hint.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// The size of the specified gamma ramp should match the size of the current ramp for that
/// monitor. On win32, the gamma ramp size must be 256.
///
/// wayland: Gamma handling is a privileged protocol, this function will thus never be implemented
/// and emits glfw.Error.PlatformError.
///
/// @pointer_lifetime The specified gamma ramp is copied before this function returns.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_gamma
pub inline fn setGammaRamp(self: Monitor, ramp: GammaRamp) Error!void {
c.glfwSetGammaRamp(self.handle, &ramp.toC());
try getError();
}
/// Returns the currently connected monitors.
///
/// This function returns a slice of all currently connected monitors. The primary monitor is
/// always first. If no monitors were found, this function returns an empty slice.
///
/// The returned slice memory is owned by the caller. The underlying handles are owned by GLFW, and
/// are valid until the monitor configuration changes or `glfw.terminate` is called.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_monitors, monitor_event, glfw.monitor.getPrimary
pub inline fn getAll(allocator: *mem.Allocator) Error![]Monitor {
var count: c_int = 0;
const monitors = c.glfwGetMonitors(&count);
try getError();
const slice = try allocator.alloc(Monitor, @intCast(usize, count));
var i: usize = 0;
while (i < count) : (i += 1) {
slice[i] = Monitor{ .handle = monitors[i].? };
}
return slice;
}
/// Returns the primary monitor.
///
/// This function returns the primary monitor. This is usually the monitor where elements like
/// the task bar or global menu bar are located.
///
/// Possible errors include glfw.Error.NotInitialized.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_monitors, glfw.monitors.getAll
pub inline fn getPrimary() Error!?Monitor {
const handle = c.glfwGetPrimaryMonitor();
try getError();
if (handle == null) {
return null;
}
return Monitor{ .handle = handle.? };
}
var callback_fn_ptr: ?usize = null;
var callback_data_ptr: ?usize = undefined;
/// Sets the monitor configuration callback.
///
/// This function sets the monitor configuration callback, or removes the currently set callback.
/// This is called when a monitor is connected to or disconnected from the system. Example:
///
/// ```
/// fn monitorCallback(monitor: glfw.Monitor, event: usize, data: *MyData) void {
/// // data is the pointer you passed into setCallback.
/// // event is one of glfw.connected or glfw.disconnected
/// }
/// ...
/// glfw.Monitor.setCallback(MyData, &myData, monitorCallback)
/// ```
///
/// `event` may be one of glfw.connected or glfw.disconnected. More events may be added in the
/// future.
///
/// Possible errors include glfw.Error.NotInitialized.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_event
pub inline fn setCallback(comptime Data: type, data: *Data, f: ?*const fn (monitor: Monitor, event: usize, data: *Data) void) Error!void {
if (f) |new_callback| {
callback_fn_ptr = @ptrToInt(new_callback);
callback_data_ptr = @ptrToInt(data);
const NewCallback = @TypeOf(new_callback);
_ = c.glfwSetMonitorCallback((struct {
fn callbackC(monitor: ?*c.GLFWmonitor, event: c_int) callconv(.C) void {
const callback = @intToPtr(NewCallback, callback_fn_ptr.?);
callback.*(
Monitor{ .handle = monitor.? },
@intCast(usize, event),
@intToPtr(*Data, callback_data_ptr.?),
);
}
}).callbackC);
} else {
_ = c.glfwSetMonitorCallback(null);
callback_fn_ptr = null;
callback_data_ptr = null;
}
try getError();
}
test "getAll" {
const glfw = @import("main.zig");
try glfw.init();
defer glfw.terminate();
const allocator = testing.allocator;
const monitors = try getAll(allocator);
defer allocator.free(monitors);
}
test "getPrimary" {
const glfw = @import("main.zig");
try glfw.init();
defer glfw.terminate();
_ = try getPrimary();
}
test "getPos" {
const glfw = @import("main.zig");
try glfw.init();
defer glfw.terminate();
const monitor = try getPrimary();
if (monitor) |m| {
_ = try m.getPos();
}
}
test "getWorkarea" {
const glfw = @import("main.zig");
try glfw.init();
defer glfw.terminate();
const monitor = try getPrimary();
if (monitor) |m| {
_ = try m.getWorkarea();
}
}
test "getPhysicalSize" {
const glfw = @import("main.zig");
try glfw.init();
defer glfw.terminate();
const monitor = try getPrimary();
if (monitor) |m| {
_ = try m.getPhysicalSize();
}
}
test "getContentScale" {
const glfw = @import("main.zig");
try glfw.init();
defer glfw.terminate();
const monitor = try getPrimary();
if (monitor) |m| {
_ = try m.getContentScale();
}
}
test "getName" {
const glfw = @import("main.zig");
try glfw.init();
defer glfw.terminate();
const monitor = try getPrimary();
if (monitor) |m| {
_ = try m.getName();
}
}
test "userPointer" {
const glfw = @import("main.zig");
try glfw.init();
defer glfw.terminate();
const monitor = try getPrimary();
if (monitor) |m| {
var p = try m.getUserPointer(u32);
try testing.expect(p == null);
var x: u32 = 5;
try m.setUserPointer(u32, &x);
p = try m.getUserPointer(u32);
try testing.expectEqual(p.?.*, 5);
}
}
test "setCallback" {
const glfw = @import("main.zig");
try glfw.init();
defer glfw.terminate();
var custom_data: u32 = 5;
try setCallback(u32, &custom_data, &(struct {
fn callback(monitor: Monitor, event: usize, data: *u32) void {
_ = monitor;
_ = event;
_ = data;
}
}).callback);
}
test "getVideoModes" {
const glfw = @import("main.zig");
try glfw.init();
defer glfw.terminate();
const monitor = try getPrimary();
if (monitor) |m| {
const allocator = testing.allocator;
const modes = try m.getVideoModes(allocator);
defer allocator.free(modes);
}
}
test "getVideoMode" {
const glfw = @import("main.zig");
try glfw.init();
defer glfw.terminate();
const monitor = try getPrimary();
if (monitor) |m| {
_ = try m.getVideoMode();
}
}
test "set_getGammaRamp" {
const allocator = testing.allocator;
const glfw = @import("main.zig");
try glfw.init();
defer glfw.terminate();
const monitor = try getPrimary();
if (monitor) |m| {
const ramp = m.getGammaRamp() catch |err| {
std.debug.print("can't get window position, wayland maybe? error={}\n", .{err});
return;
};
// Set it to the exact same value; if we do otherwise an our tests fail it wouldn't call
// terminate and our made-up gamma ramp would get stuck.
try m.setGammaRamp(ramp);
// technically not needed here / noop because GLFW owns this gamma ramp.
defer ramp.deinit(allocator);
}
} | glfw/src/Monitor.zig |
const testing = @import("std.zig").testing;
/// Wasm instruction opcodes
///
/// All instructions are defined as per spec:
/// https://webassembly.github.io/spec/core/appendix/index-instructions.html
pub const Opcode = enum(u8) {
@"unreachable" = 0x00,
nop = 0x01,
block = 0x02,
loop = 0x03,
@"if" = 0x04,
@"else" = 0x05,
end = 0x0B,
br = 0x0C,
br_if = 0x0D,
br_table = 0x0E,
@"return" = 0x0F,
call = 0x10,
call_indirect = 0x11,
drop = 0x1A,
select = 0x1B,
local_get = 0x20,
local_set = 0x21,
local_tee = 0x22,
global_get = 0x23,
global_set = 0x24,
i32_load = 0x28,
i64_load = 0x29,
f32_load = 0x2A,
f64_load = 0x2B,
i32_load8_s = 0x2C,
i32_load8_u = 0x2D,
i32_load16_s = 0x2E,
i32_load16_u = 0x2F,
i64_load8_s = 0x30,
i64_load8_u = 0x31,
i64_load16_s = 0x32,
i64_load16_u = 0x33,
i64_load32_s = 0x34,
i64_load32_u = 0x35,
i32_store = 0x36,
i64_store = 0x37,
f32_store = 0x38,
f64_store = 0x39,
i32_store8 = 0x3A,
i32_store16 = 0x3B,
i64_store8 = 0x3C,
i64_store16 = 0x3D,
i64_store32 = 0x3E,
memory_size = 0x3F,
memory_grow = 0x40,
i32_const = 0x41,
i64_const = 0x42,
f32_const = 0x43,
f64_const = 0x44,
i32_eqz = 0x45,
i32_eq = 0x46,
i32_ne = 0x47,
i32_lt_s = 0x48,
i32_lt_u = 0x49,
i32_gt_s = 0x4A,
i32_gt_u = 0x4B,
i32_le_s = 0x4C,
i32_le_u = 0x4D,
i32_ge_s = 0x4E,
i32_ge_u = 0x4F,
i64_eqz = 0x50,
i64_eq = 0x51,
i64_ne = 0x52,
i64_lt_s = 0x53,
i64_lt_u = 0x54,
i64_gt_s = 0x55,
i64_gt_u = 0x56,
i64_le_s = 0x57,
i64_le_u = 0x58,
i64_ge_s = 0x59,
i64_ge_u = 0x5A,
f32_eq = 0x5B,
f32_ne = 0x5C,
f32_lt = 0x5D,
f32_gt = 0x5E,
f32_le = 0x5F,
f32_ge = 0x60,
f64_eq = 0x61,
f64_ne = 0x62,
f64_lt = 0x63,
f64_gt = 0x64,
f64_le = 0x65,
f64_ge = 0x66,
i32_clz = 0x67,
i32_ctz = 0x68,
i32_popcnt = 0x69,
i32_add = 0x6A,
i32_sub = 0x6B,
i32_mul = 0x6C,
i32_div_s = 0x6D,
i32_div_u = 0x6E,
i32_rem_s = 0x6F,
i32_rem_u = 0x70,
i32_and = 0x71,
i32_or = 0x72,
i32_xor = 0x73,
i32_shl = 0x74,
i32_shr_s = 0x75,
i32_shr_u = 0x76,
i32_rotl = 0x77,
i32_rotr = 0x78,
i64_clz = 0x79,
i64_ctz = 0x7A,
i64_popcnt = 0x7B,
i64_add = 0x7C,
i64_sub = 0x7D,
i64_mul = 0x7E,
i64_div_s = 0x7F,
i64_div_u = 0x80,
i64_rem_s = 0x81,
i64_rem_u = 0x82,
i64_and = 0x83,
i64_or = 0x84,
i64_xor = 0x85,
i64_shl = 0x86,
i64_shr_s = 0x87,
i64_shr_u = 0x88,
i64_rotl = 0x89,
i64_rotr = 0x8A,
f32_abs = 0x8B,
f32_neg = 0x8C,
f32_ceil = 0x8D,
f32_floor = 0x8E,
f32_trunc = 0x8F,
f32_nearest = 0x90,
f32_sqrt = 0x91,
f32_add = 0x92,
f32_sub = 0x93,
f32_mul = 0x94,
f32_div = 0x95,
f32_min = 0x96,
f32_max = 0x97,
f32_copysign = 0x98,
f64_abs = 0x99,
f64_neg = 0x9A,
f64_ceil = 0x9B,
f64_floor = 0x9C,
f64_trunc = 0x9D,
f64_nearest = 0x9E,
f64_sqrt = 0x9F,
f64_add = 0xA0,
f64_sub = 0xA1,
f64_mul = 0xA2,
f64_div = 0xA3,
f64_min = 0xA4,
f64_max = 0xA5,
f64_copysign = 0xA6,
i32_wrap_i64 = 0xA7,
i32_trunc_f32_s = 0xA8,
i32_trunc_f32_u = 0xA9,
i32_trunc_f64_s = 0xB0,
i32_trunc_f64_u = 0xB1,
f32_convert_i32_s = 0xB2,
f32_convert_i32_u = 0xB3,
f32_convert_i64_s = 0xB4,
f32_convert_i64_u = 0xB5,
f32_demote_f64 = 0xB6,
f64_convert_i32_s = 0xB7,
f64_convert_i32_u = 0xB8,
f64_convert_i64_s = 0xB9,
f64_convert_i64_u = 0xBA,
f64_promote_f32 = 0xBB,
i32_reinterpret_f32 = 0xBC,
i64_reinterpret_f64 = 0xBD,
f32_reinterpret_i32 = 0xBE,
i64_reinterpret_i64 = 0xBF,
i32_extend8_s = 0xC0,
i32_extend16_s = 0xC1,
i64_extend8_s = 0xC2,
i64_extend16_s = 0xC3,
i64_extend32_s = 0xC4,
_,
};
/// Returns the integer value of an `Opcode`. Used by the Zig compiler
/// to write instructions to the wasm binary file
pub fn opcode(op: Opcode) u8 {
return @enumToInt(op);
}
test "Wasm - opcodes" {
// Ensure our opcodes values remain intact as certain values are skipped due to them being reserved
const i32_const = opcode(.i32_const);
const end = opcode(.end);
const drop = opcode(.drop);
const local_get = opcode(.local_get);
const i64_extend32_s = opcode(.i64_extend32_s);
testing.expectEqual(@as(u16, 0x41), i32_const);
testing.expectEqual(@as(u16, 0x0B), end);
testing.expectEqual(@as(u16, 0x1A), drop);
testing.expectEqual(@as(u16, 0x20), local_get);
testing.expectEqual(@as(u16, 0xC4), i64_extend32_s);
}
/// Enum representing all Wasm value types as per spec:
/// https://webassembly.github.io/spec/core/binary/types.html
pub const Valtype = enum(u8) {
i32 = 0x7F,
i64 = 0x7E,
f32 = 0x7D,
f64 = 0x7C,
};
/// Returns the integer value of a `Valtype`
pub fn valtype(value: Valtype) u8 {
return @enumToInt(value);
}
test "Wasm - valtypes" {
const _i32 = valtype(.i32);
const _i64 = valtype(.i64);
const _f32 = valtype(.f32);
const _f64 = valtype(.f64);
testing.expectEqual(@as(u8, 0x7F), _i32);
testing.expectEqual(@as(u8, 0x7E), _i64);
testing.expectEqual(@as(u8, 0x7D), _f32);
testing.expectEqual(@as(u8, 0x7C), _f64);
}
/// Wasm module sections as per spec:
/// https://webassembly.github.io/spec/core/binary/modules.html
pub const Section = enum(u8) {
custom,
type,
import,
function,
table,
memory,
global,
@"export",
start,
element,
code,
data,
};
/// Returns the integer value of a given `Section`
pub fn section(val: Section) u8 {
return @enumToInt(val);
}
// types
pub const element_type: u8 = 0x70;
pub const function_type: u8 = 0x60;
pub const result_type: u8 = 0x40;
/// Represents a block which will not return a value
pub const block_empty: u8 = 0x40;
// binary constants
pub const magic = [_]u8{ 0x00, 0x61, 0x73, 0x6D }; // \0asm
pub const version = [_]u8{ 0x01, 0x00, 0x00, 0x00 }; // version 1 | lib/std/wasm.zig |
const color = @import("./color/color.zig");
/// A Point is an X, Y coordinate pair. The axes increase right and down.
pub const Point = struct {
x: isize,
y: isize,
pub fn init(x: isize, y: isize) Point {
return Point{ .x = x, .y = y };
}
pub fn add(p: Point, q: Point) Point {
return Point{ .x = p.x + q.x, .y = p.y + q.y };
}
pub fn sub(p: Point, q: Point) Point {
return Point{ .x = p.x - q.x, .y = p.y - q.y };
}
pub fn mul(p: Point, q: Point) Point {
return Point{ .x = p.x * q.x, .y = p.y * q.y };
}
pub fn div(p: Point, q: Point) Point {
return Point{ .x = @divExact(p.x, q.x), .y = @divExact(p.y, q.y) };
}
pub fn in(p: Point, r: Rectangle) bool {
return r.min.x <= p.x and p.x < r.max.x and r.min.y <= p.y and p.y < r.max.y;
}
pub fn mod(p: Point, r: Rectangle) Point {
const w = r.dx();
const h = r.dy();
const point = p.sub(r.min);
var x = @mod(point.x, w);
if (x < 0) {
x += w;
}
var y = @mod(point.y, h);
if (y < 0) {
y += h;
}
const np = Point.init(x, y);
return np.add(r.min);
}
pub fn eq(p: Point, q: Point) bool {
return p.x == q.x and p.y == q.y;
}
};
pub const Rectangle = struct {
min: Point,
max: Point,
pub fn init(x0: isize, y0: isize, x1: isize, y1: isize) Rectangle {
return Rectangle{
.min = Point{
.x = x0,
.y = y0,
},
.max = Point{
.x = x1,
.y = y1,
},
};
}
pub fn rect(x0: isize, y0: isize, x1: isize, y1: isize) Rectangle {
var r = Rectangle{
.min = Point{
.x = x0,
.y = y0,
},
.max = Point{
.x = x1,
.y = y1,
},
};
if (x0 > x1) {
const x = x0;
r.min.x = x1;
r.max.x = x;
}
if (y0 > y1) {
const y = y0;
r.min.y = y1;
r.max.y = y;
}
return r;
}
/// dx returns r's width.
pub fn dx(r: Rectangle) isize {
return r.max.x - r.min.x;
}
pub fn zero() Rectangle {
return Rectangle.init(0, 0, 0, 0);
}
/// dy returns r's height.
pub fn dy(r: Rectangle) isize {
return r.max.y - r.min.y;
}
/// size returns r's width and height.
pub fn size(r: Rectangle) Point {
return Point{ .x = r.dx(), .y = r.dy() };
}
/// eEmpty reports whether the rectangle contains no points.
pub fn empty(r: Rectangle) bool {
return r.min.x >= r.max.x or r.min.y >= r.max.y;
}
pub fn add(r: Rectangle, p: Point) Rectangle {
return Rectangle{
.min = Point{ .x = r.min.x + p.x, .y = r.min.y + p.y },
.max = Point{ .x = r.max.x + p.x, .y = r.max.y + p.y },
};
}
pub fn sub(r: Rectangle, p: Point) Rectangle {
return Rectangle{
.min = Point{ .x = r.min.x - p.x, .y = r.min.y - p.y },
.max = Point{ .x = r.max.x - p.x, .y = r.max.y - p.y },
};
}
/// Inset returns the rectangle r inset by n, which may be negative. If either
/// of r's dimensions is less than 2*n then an empty rectangle near the center
/// of r will be returned.
pub fn inset(r: Rectangle, n: isize) Rectangle {
var x0 = r.min.x;
var x1 = r.min.x;
if (r.dx() < 2 * n) {
x0 = @divExact((r.min.x + r.max.x), 2);
x1 = x0;
} else {
x0 += n;
x1 -= n;
}
var y0 = r.min.y;
var y1 = r.max.y;
if (r.dy() < 2 * n) {
y0 = @divExact((r.min.y + r.max.y), 2);
y1 = y0;
} else {
y0 += n;
y1 -= n;
}
return Rectangle.init(x0, y0, x1, y1);
}
/// Intersect returns the largest rectangle contained by both r and s. If the
/// two rectangles do not overlap then the zero rectangle will be returned.
pub fn intersect(r: Rectangle, s: Rectangle) Rectangle {
var x0 = r.min.x;
var y0 = r.min.y;
var x1 = r.max.x;
var y1 = r.max.y;
if (x0 < s.min.x) {
x0 = s.min.x;
}
if (y0 < s.min.y) {
y0 = s.min.y;
}
if (x1 > s.max.x) {
x1 = s.max.x;
}
if (y1 > s.max.y) {
y1 = s.max.y;
}
const rec = Rectangle.init(x0, y0, x1, y1);
if (rec.empty()) {
return Rectangle.zero();
}
return rec;
}
/// Union returns the smallest rectangle that contains both r and s.
pub fn runion(r: Rectangle, s: Rectangle) Rectangle {
if (r.empty()) {
return s;
}
if (s.empty()) {
return r;
}
var a = []isize{ r.min.x, r.min.y, r.max.x, r.max.y };
if (a[0] > s.min.x) {
a[0] = s.min.x;
}
if (a[1] > s.min.y) {
a[1] = s.min.y;
}
if (a[2] < s.max.x) {
a[2] = s.max.x;
}
if (a[3] < s.max.y) {
a[3] = s.max.y;
}
return Rectangle.init(a[0], a[1], a[2], a[3]);
}
pub fn eq(r: Rectangle, s: Rectangle) bool {
return r.max.eq(s.max) and r.min.eq(s.min) or r.empty() and s.empty();
}
pub fn overlaps(r: Rectangle, s: Rectangle) bool {
return !r.empty() and !s.empty() and
r.min.x < s.max.x and s.min.x < r.max.x and r.min.y < s.max.y and s.min.y < r.max.y;
}
pub fn in(r: Rectangle, s: Rectangle) bool {
if (r.empty()) {
return true;
}
return s.min.x <= r.min.x and r.max.x <= s.max.x and
s.min.y <= r.min.y and r.max.y <= s.max.y;
}
pub fn canon(r: Rectangle) Rectangle {
var x0 = r.min.x;
var x1 = r.max.x;
if (r.max.x < r.min.x) {
const x = r.min.x;
x0 = r.max.x;
x1 = x;
}
var y0 = r.min.x;
var y1 = r.min.x;
if (r.min.y < r.max.y) {
const y = y0;
y0 = y1;
y1 = y;
}
return Rectangle.init(x0, y0, x1, y1);
}
pub fn at(r: Rectangle, x: isize, y: isize) color.Color {
var p = Point{ .x = x, .y = y };
if (p.in(r)) {
return color.Opaque.toColor();
}
return color.Transparent.toColor();
}
pub fn bounds(r: Rectangle) Rectangle {
return r;
}
pub fn colorModel(r: Rectangle) color.Model {
return color.Alpha16Model;
}
};
pub const Config = struct {
color_model: color.Model,
width: isize,
height: isize,
};
/// Image is a finite rectangular grid of color.Color values taken from a color
/// model.
pub const Image = struct {
/// color_model is the Image's color model.
color_model: color.Model,
/// bounds is the domain for which At can return non-zero color.
/// The bounds do not necessarily contain the point (0, 0).
bounds: Rectangle,
image_fn: ImageFuncs,
};
/// ImageFuncs are futcion which statisfies different interfaces. Some are
/// optional others are a must.
pub const ImageFuncs = struct {
/// at returns the color of the pixel at (x, y).
/// At(Bounds().Min.X, Bounds().Min.Y) returns the upper-left pixel of the grid.
/// At(Bounds().Max.X-1, Bounds().Max.Y-1) returns the lower-right one.
at_fn: fn (self: *ImageFuncs, x: isize, y: isize) color.Color,
opaque_fn: ?fn (self: *ImageFuncs) bool,
set_fn: ?fn (self: *ImageFuncs, x: isize, y: isize, c: color.ModelType) void,
/// calculate subimage from rectangle r and assigns the resulting image to
/// img_ptr
/// TODO: Fix the API.
set_sub_image: ?fn (self: *ImageFuncs, r: Rectangle, img_ptr: *Image) void,
};
/// PalettedImage is an image whose colors may come from a limited palette.
/// If m is a PalettedImage and m.ColorModel() returns a color.Palette p,
/// then m.At(x, y) should be equivalent to p[m.ColorIndexAt(x, y)]. If m's
/// color model is not a color.Palette, then ColorIndexAt's behavior is
/// undefined.
pub const PalettedImage = struct {
image: Image,
color_index_at: fn (x: usize, y: usize) u8,
};
pub const Pix = struct {
r: u8,
g: u8,
b: u8,
a: u8,
pub fn init() Pix {
return Pix{
.r = 0,
.g = 0,
.b = 0,
.a = 0,
};
}
};
pub const RGBA = struct {
/// Pix holds the image's pixels, in R, G, B, A order. The pixel at
/// (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*4].
pix: []u8,
/// Stride is the Pix stride (in bytes) between vertically adjacent pixels.
stride: isize,
/// Rect is the image's bounds.
rect: Rectangle,
image_fn: ImageFuncs,
pub fn init(pix: []u8, stride: isize, rect: Rectangle) RGBA {
return RGBA{
.pix = pix,
.stride = stride,
.rect = rect,
.image_fn = ImageFuncs{
.at_fn = at,
.opaque_fn = opaqueFn,
.set_fn = setFn,
.set_sub_image = subImageFn,
},
};
}
pub fn zero() RGBA {
return RGBA.init("", 0, Rectangle.zero());
}
pub fn colorModel(r: *RGBA) color.Model {
return color.RGBAModel;
}
pub fn rgbaAt(r: *RGBA, x: isize, y: isize) color.RGBA {
const p = Point.init(x, y);
if (p.in(r.rect)) {
return color.RGBA{ .r = 0, .g = 0, .b = 0, .a = 0 };
}
const i = r.pixOffset(x, y);
const size = @intCast(usize, i);
const s = r.pix[size .. size + 4];
return color.RGBA{ .r = s[0], .g = s[1], .b = s[2], .a = s[3] };
}
pub fn at(r: *ImageFuncs, x: isize, y: isize) color.Color {
const self = @fieldParentPtr(RGBA, "image_fn", r);
return self.rgbaAt(x, y).toColor();
}
pub fn opaqueFn(r: *ImageFuncs) bool {
const self = @fieldParentPtr(RGBA, "image_fn", r);
return self.opaque();
}
pub fn subImageFn(r: *ImageFuncs, rec: Rectangle, img_ptr: *Image) void {
const self = @fieldParentPtr(RGBA, "image_fn", r);
var img = self.subImage(rec).image();
img_ptr.* = img;
}
pub fn setFn(r: *ImageFuncs, x: isize, y: isize, c: color.ModelType) void {
const self = @fieldParentPtr(RGBA, "image_fn", r);
return self.set(x, y, c);
}
pub fn pixOffset(r: *RGBA, x: isize, y: isize) isize {
return (y - r.rect.min.y) * r.stride + (x - r.rect.min.x) * 4;
}
pub fn image(r: *RGBA) Image {
return Image{
.color_model = r.colorModel(),
.image_fn = r.image_fn,
.bounds = r.rect,
};
}
pub fn set(r: *RGBA, x: isize, y: isize, c: color.ModelType) void {
const p = Point.init(x, y);
if (p.in(r.rect)) {
return;
}
const v = color.RGBAModel.convert(c);
const i = r.pixOffset(x, y);
const size = @intCast(usize, i);
var s = r.pix[size .. size + 4];
s[0] = @intCast(u8, v.rgb.r);
s[1] = @intCast(u8, v.rgb.g);
s[2] = @intCast(u8, v.rgb.b);
s[3] = @intCast(u8, v.rgb.a);
}
pub fn setRGBA(r: *RGBA, x: isize, y: isize, c: color.RGBA) void {
const p = Point.init(x, y);
if (p.in(r.rect)) {
return;
}
const i = r.pixOffset(x, y);
const size = @intCast(usize, i);
const s = r.pix[size .. size + 4];
s[0] = c.r;
s[1] = c.g;
s[2] = c.b;
s[3] = c.a;
}
/// subImage returns an image representing the portion of the image p visible
/// through rec. The returned value shares pixels with the original image.
pub fn subImage(r: *RGBA, rec: Rectangle) RGBA {
const ri = rec.intersect(r.rect);
if (ri.empty()) {
return RGBA.zero();
}
const i = r.pixOffset(ri.min.x, ri.min.y);
const size = @intCast(usize, i);
return RGBA.init(r.pix[size..], r.stride, ri);
}
pub fn opaque(r: *RGBA) bool {
if (r.rect.empty()) {
return true;
}
var x0: isize = 0;
var x1 = r.rect.dx() * 4;
var y = r.rect.min.y;
while (y < r.rect.max.y) {
var i = x0;
while (i < x1) {
const idx = @intCast(usize, i);
if (r.pix[idx] == 0xff) {
return false;
}
i += 4;
}
x0 += r.stride;
x1 += r.stride;
y += 1;
}
return true;
}
}; | src/image.zig |
const sg = @import("sokol").gfx;
//
// #version:1# (machine generated, don't edit!)
//
// Generated by sokol-shdc (https://github.com/floooh/sokol-tools)
//
// Cmdline: sokol-shdc --input .\data\shaders\default.glsl --output .\src\default.glsl.zig --slang glsl330:hlsl5:metal_macos -f sokol_zig
//
// Overview:
//
// Shader program 'texcube':
// Get shader desc: shd.texcubeShaderDesc(sg.queryBackend());
// Vertex shader: vs
// Attribute slots:
// ATTR_vs_pos = 0
// ATTR_vs_col = 1
// ATTR_vs_texc = 2
// Fragment shader: fs
// Image 'tex':
// Type: ._2D
// Component Type: .FLOAT
// Bind slot: SLOT_tex = 0
//
//
pub const ATTR_vs_pos = 0;
pub const ATTR_vs_col = 1;
pub const ATTR_vs_texc = 2;
pub const SLOT_tex = 0;
//
// #version 330
//
// layout(location = 0) in vec4 pos;
// out vec4 color;
// layout(location = 1) in vec4 col;
// out vec2 uv;
// layout(location = 2) in vec2 texc;
//
// void main()
// {
// gl_Position = pos;
// color = col;
// uv = texc;
// }
//
//
const vs_source_glsl330 = [220]u8 {
0x23,0x76,0x65,0x72,0x73,0x69,0x6f,0x6e,0x20,0x33,0x33,0x30,0x0a,0x0a,0x6c,0x61,
0x79,0x6f,0x75,0x74,0x28,0x6c,0x6f,0x63,0x61,0x74,0x69,0x6f,0x6e,0x20,0x3d,0x20,
0x30,0x29,0x20,0x69,0x6e,0x20,0x76,0x65,0x63,0x34,0x20,0x70,0x6f,0x73,0x3b,0x0a,
0x6f,0x75,0x74,0x20,0x76,0x65,0x63,0x34,0x20,0x63,0x6f,0x6c,0x6f,0x72,0x3b,0x0a,
0x6c,0x61,0x79,0x6f,0x75,0x74,0x28,0x6c,0x6f,0x63,0x61,0x74,0x69,0x6f,0x6e,0x20,
0x3d,0x20,0x31,0x29,0x20,0x69,0x6e,0x20,0x76,0x65,0x63,0x34,0x20,0x63,0x6f,0x6c,
0x3b,0x0a,0x6f,0x75,0x74,0x20,0x76,0x65,0x63,0x32,0x20,0x75,0x76,0x3b,0x0a,0x6c,
0x61,0x79,0x6f,0x75,0x74,0x28,0x6c,0x6f,0x63,0x61,0x74,0x69,0x6f,0x6e,0x20,0x3d,
0x20,0x32,0x29,0x20,0x69,0x6e,0x20,0x76,0x65,0x63,0x32,0x20,0x74,0x65,0x78,0x63,
0x3b,0x0a,0x0a,0x76,0x6f,0x69,0x64,0x20,0x6d,0x61,0x69,0x6e,0x28,0x29,0x0a,0x7b,
0x0a,0x20,0x20,0x20,0x20,0x67,0x6c,0x5f,0x50,0x6f,0x73,0x69,0x74,0x69,0x6f,0x6e,
0x20,0x3d,0x20,0x70,0x6f,0x73,0x3b,0x0a,0x20,0x20,0x20,0x20,0x63,0x6f,0x6c,0x6f,
0x72,0x20,0x3d,0x20,0x63,0x6f,0x6c,0x3b,0x0a,0x20,0x20,0x20,0x20,0x75,0x76,0x20,
0x3d,0x20,0x74,0x65,0x78,0x63,0x3b,0x0a,0x7d,0x0a,0x0a,0x00,
};
//
// #version 330
//
// uniform sampler2D tex;
//
// layout(location = 0) out vec4 frag_color;
// in vec2 uv;
// in vec4 color;
//
// void main()
// {
// frag_color = texture(tex, uv);
// }
//
//
const fs_source_glsl330 = [161]u8 {
0x23,0x76,0x65,0x72,0x73,0x69,0x6f,0x6e,0x20,0x33,0x33,0x30,0x0a,0x0a,0x75,0x6e,
0x69,0x66,0x6f,0x72,0x6d,0x20,0x73,0x61,0x6d,0x70,0x6c,0x65,0x72,0x32,0x44,0x20,
0x74,0x65,0x78,0x3b,0x0a,0x0a,0x6c,0x61,0x79,0x6f,0x75,0x74,0x28,0x6c,0x6f,0x63,
0x61,0x74,0x69,0x6f,0x6e,0x20,0x3d,0x20,0x30,0x29,0x20,0x6f,0x75,0x74,0x20,0x76,
0x65,0x63,0x34,0x20,0x66,0x72,0x61,0x67,0x5f,0x63,0x6f,0x6c,0x6f,0x72,0x3b,0x0a,
0x69,0x6e,0x20,0x76,0x65,0x63,0x32,0x20,0x75,0x76,0x3b,0x0a,0x69,0x6e,0x20,0x76,
0x65,0x63,0x34,0x20,0x63,0x6f,0x6c,0x6f,0x72,0x3b,0x0a,0x0a,0x76,0x6f,0x69,0x64,
0x20,0x6d,0x61,0x69,0x6e,0x28,0x29,0x0a,0x7b,0x0a,0x20,0x20,0x20,0x20,0x66,0x72,
0x61,0x67,0x5f,0x63,0x6f,0x6c,0x6f,0x72,0x20,0x3d,0x20,0x74,0x65,0x78,0x74,0x75,
0x72,0x65,0x28,0x74,0x65,0x78,0x2c,0x20,0x75,0x76,0x29,0x3b,0x0a,0x7d,0x0a,0x0a,
0x00,
};
//
// static float4 gl_Position;
// static float4 pos;
// static float4 color;
// static float4 col;
// static float2 uv;
// static float2 texc;
//
// struct SPIRV_Cross_Input
// {
// float4 pos : TEXCOORD0;
// float4 col : TEXCOORD1;
// float2 texc : TEXCOORD2;
// };
//
// struct SPIRV_Cross_Output
// {
// float4 color : TEXCOORD0;
// float2 uv : TEXCOORD1;
// float4 gl_Position : SV_Position;
// };
//
// #line 18 ".\data\shaders\default.glsl"
// void vert_main()
// {
// #line 18 ".\data\shaders\default.glsl"
// gl_Position = pos;
// #line 19 ".\data\shaders\default.glsl"
// color = col;
// #line 20 ".\data\shaders\default.glsl"
// uv = texc;
// }
//
// SPIRV_Cross_Output main(SPIRV_Cross_Input stage_input)
// {
// pos = stage_input.pos;
// col = stage_input.col;
// texc = stage_input.texc;
// vert_main();
// SPIRV_Cross_Output stage_output;
// stage_output.gl_Position = gl_Position;
// stage_output.color = color;
// stage_output.uv = uv;
// return stage_output;
// }
//
const vs_source_hlsl5 = [925]u8 {
0x73,0x74,0x61,0x74,0x69,0x63,0x20,0x66,0x6c,0x6f,0x61,0x74,0x34,0x20,0x67,0x6c,
0x5f,0x50,0x6f,0x73,0x69,0x74,0x69,0x6f,0x6e,0x3b,0x0a,0x73,0x74,0x61,0x74,0x69,
0x63,0x20,0x66,0x6c,0x6f,0x61,0x74,0x34,0x20,0x70,0x6f,0x73,0x3b,0x0a,0x73,0x74,
0x61,0x74,0x69,0x63,0x20,0x66,0x6c,0x6f,0x61,0x74,0x34,0x20,0x63,0x6f,0x6c,0x6f,
0x72,0x3b,0x0a,0x73,0x74,0x61,0x74,0x69,0x63,0x20,0x66,0x6c,0x6f,0x61,0x74,0x34,
0x20,0x63,0x6f,0x6c,0x3b,0x0a,0x73,0x74,0x61,0x74,0x69,0x63,0x20,0x66,0x6c,0x6f,
0x61,0x74,0x32,0x20,0x75,0x76,0x3b,0x0a,0x73,0x74,0x61,0x74,0x69,0x63,0x20,0x66,
0x6c,0x6f,0x61,0x74,0x32,0x20,0x74,0x65,0x78,0x63,0x3b,0x0a,0x0a,0x73,0x74,0x72,
0x75,0x63,0x74,0x20,0x53,0x50,0x49,0x52,0x56,0x5f,0x43,0x72,0x6f,0x73,0x73,0x5f,
0x49,0x6e,0x70,0x75,0x74,0x0a,0x7b,0x0a,0x20,0x20,0x20,0x20,0x66,0x6c,0x6f,0x61,
0x74,0x34,0x20,0x70,0x6f,0x73,0x20,0x3a,0x20,0x54,0x45,0x58,0x43,0x4f,0x4f,0x52,
0x44,0x30,0x3b,0x0a,0x20,0x20,0x20,0x20,0x66,0x6c,0x6f,0x61,0x74,0x34,0x20,0x63,
0x6f,0x6c,0x20,0x3a,0x20,0x54,0x45,0x58,0x43,0x4f,0x4f,0x52,0x44,0x31,0x3b,0x0a,
0x20,0x20,0x20,0x20,0x66,0x6c,0x6f,0x61,0x74,0x32,0x20,0x74,0x65,0x78,0x63,0x20,
0x3a,0x20,0x54,0x45,0x58,0x43,0x4f,0x4f,0x52,0x44,0x32,0x3b,0x0a,0x7d,0x3b,0x0a,
0x0a,0x73,0x74,0x72,0x75,0x63,0x74,0x20,0x53,0x50,0x49,0x52,0x56,0x5f,0x43,0x72,
0x6f,0x73,0x73,0x5f,0x4f,0x75,0x74,0x70,0x75,0x74,0x0a,0x7b,0x0a,0x20,0x20,0x20,
0x20,0x66,0x6c,0x6f,0x61,0x74,0x34,0x20,0x63,0x6f,0x6c,0x6f,0x72,0x20,0x3a,0x20,
0x54,0x45,0x58,0x43,0x4f,0x4f,0x52,0x44,0x30,0x3b,0x0a,0x20,0x20,0x20,0x20,0x66,
0x6c,0x6f,0x61,0x74,0x32,0x20,0x75,0x76,0x20,0x3a,0x20,0x54,0x45,0x58,0x43,0x4f,
0x4f,0x52,0x44,0x31,0x3b,0x0a,0x20,0x20,0x20,0x20,0x66,0x6c,0x6f,0x61,0x74,0x34,
0x20,0x67,0x6c,0x5f,0x50,0x6f,0x73,0x69,0x74,0x69,0x6f,0x6e,0x20,0x3a,0x20,0x53,
0x56,0x5f,0x50,0x6f,0x73,0x69,0x74,0x69,0x6f,0x6e,0x3b,0x0a,0x7d,0x3b,0x0a,0x0a,
0x23,0x6c,0x69,0x6e,0x65,0x20,0x31,0x38,0x20,0x22,0x2e,0x5c,0x64,0x61,0x74,0x61,
0x5c,0x73,0x68,0x61,0x64,0x65,0x72,0x73,0x5c,0x64,0x65,0x66,0x61,0x75,0x6c,0x74,
0x2e,0x67,0x6c,0x73,0x6c,0x22,0x0a,0x76,0x6f,0x69,0x64,0x20,0x76,0x65,0x72,0x74,
0x5f,0x6d,0x61,0x69,0x6e,0x28,0x29,0x0a,0x7b,0x0a,0x23,0x6c,0x69,0x6e,0x65,0x20,
0x31,0x38,0x20,0x22,0x2e,0x5c,0x64,0x61,0x74,0x61,0x5c,0x73,0x68,0x61,0x64,0x65,
0x72,0x73,0x5c,0x64,0x65,0x66,0x61,0x75,0x6c,0x74,0x2e,0x67,0x6c,0x73,0x6c,0x22,
0x0a,0x20,0x20,0x20,0x20,0x67,0x6c,0x5f,0x50,0x6f,0x73,0x69,0x74,0x69,0x6f,0x6e,
0x20,0x3d,0x20,0x70,0x6f,0x73,0x3b,0x0a,0x23,0x6c,0x69,0x6e,0x65,0x20,0x31,0x39,
0x20,0x22,0x2e,0x5c,0x64,0x61,0x74,0x61,0x5c,0x73,0x68,0x61,0x64,0x65,0x72,0x73,
0x5c,0x64,0x65,0x66,0x61,0x75,0x6c,0x74,0x2e,0x67,0x6c,0x73,0x6c,0x22,0x0a,0x20,
0x20,0x20,0x20,0x63,0x6f,0x6c,0x6f,0x72,0x20,0x3d,0x20,0x63,0x6f,0x6c,0x3b,0x0a,
0x23,0x6c,0x69,0x6e,0x65,0x20,0x32,0x30,0x20,0x22,0x2e,0x5c,0x64,0x61,0x74,0x61,
0x5c,0x73,0x68,0x61,0x64,0x65,0x72,0x73,0x5c,0x64,0x65,0x66,0x61,0x75,0x6c,0x74,
0x2e,0x67,0x6c,0x73,0x6c,0x22,0x0a,0x20,0x20,0x20,0x20,0x75,0x76,0x20,0x3d,0x20,
0x74,0x65,0x78,0x63,0x3b,0x0a,0x7d,0x0a,0x0a,0x53,0x50,0x49,0x52,0x56,0x5f,0x43,
0x72,0x6f,0x73,0x73,0x5f,0x4f,0x75,0x74,0x70,0x75,0x74,0x20,0x6d,0x61,0x69,0x6e,
0x28,0x53,0x50,0x49,0x52,0x56,0x5f,0x43,0x72,0x6f,0x73,0x73,0x5f,0x49,0x6e,0x70,
0x75,0x74,0x20,0x73,0x74,0x61,0x67,0x65,0x5f,0x69,0x6e,0x70,0x75,0x74,0x29,0x0a,
0x7b,0x0a,0x20,0x20,0x20,0x20,0x70,0x6f,0x73,0x20,0x3d,0x20,0x73,0x74,0x61,0x67,
0x65,0x5f,0x69,0x6e,0x70,0x75,0x74,0x2e,0x70,0x6f,0x73,0x3b,0x0a,0x20,0x20,0x20,
0x20,0x63,0x6f,0x6c,0x20,0x3d,0x20,0x73,0x74,0x61,0x67,0x65,0x5f,0x69,0x6e,0x70,
0x75,0x74,0x2e,0x63,0x6f,0x6c,0x3b,0x0a,0x20,0x20,0x20,0x20,0x74,0x65,0x78,0x63,
0x20,0x3d,0x20,0x73,0x74,0x61,0x67,0x65,0x5f,0x69,0x6e,0x70,0x75,0x74,0x2e,0x74,
0x65,0x78,0x63,0x3b,0x0a,0x20,0x20,0x20,0x20,0x76,0x65,0x72,0x74,0x5f,0x6d,0x61,
0x69,0x6e,0x28,0x29,0x3b,0x0a,0x20,0x20,0x20,0x20,0x53,0x50,0x49,0x52,0x56,0x5f,
0x43,0x72,0x6f,0x73,0x73,0x5f,0x4f,0x75,0x74,0x70,0x75,0x74,0x20,0x73,0x74,0x61,
0x67,0x65,0x5f,0x6f,0x75,0x74,0x70,0x75,0x74,0x3b,0x0a,0x20,0x20,0x20,0x20,0x73,
0x74,0x61,0x67,0x65,0x5f,0x6f,0x75,0x74,0x70,0x75,0x74,0x2e,0x67,0x6c,0x5f,0x50,
0x6f,0x73,0x69,0x74,0x69,0x6f,0x6e,0x20,0x3d,0x20,0x67,0x6c,0x5f,0x50,0x6f,0x73,
0x69,0x74,0x69,0x6f,0x6e,0x3b,0x0a,0x20,0x20,0x20,0x20,0x73,0x74,0x61,0x67,0x65,
0x5f,0x6f,0x75,0x74,0x70,0x75,0x74,0x2e,0x63,0x6f,0x6c,0x6f,0x72,0x20,0x3d,0x20,
0x63,0x6f,0x6c,0x6f,0x72,0x3b,0x0a,0x20,0x20,0x20,0x20,0x73,0x74,0x61,0x67,0x65,
0x5f,0x6f,0x75,0x74,0x70,0x75,0x74,0x2e,0x75,0x76,0x20,0x3d,0x20,0x75,0x76,0x3b,
0x0a,0x20,0x20,0x20,0x20,0x72,0x65,0x74,0x75,0x72,0x6e,0x20,0x73,0x74,0x61,0x67,
0x65,0x5f,0x6f,0x75,0x74,0x70,0x75,0x74,0x3b,0x0a,0x7d,0x0a,0x00,
};
//
// Texture2D<float4> tex : register(t0);
// SamplerState _tex_sampler : register(s0);
//
// static float4 frag_color;
// static float2 uv;
// static float4 color;
//
// struct SPIRV_Cross_Input
// {
// float4 color : TEXCOORD0;
// float2 uv : TEXCOORD1;
// };
//
// struct SPIRV_Cross_Output
// {
// float4 frag_color : SV_Target0;
// };
//
// #line 13 ".\data\shaders\default.glsl"
// void frag_main()
// {
// #line 13 ".\data\shaders\default.glsl"
// frag_color = tex.Sample(_tex_sampler, uv);
// }
//
// SPIRV_Cross_Output main(SPIRV_Cross_Input stage_input)
// {
// uv = stage_input.uv;
// color = stage_input.color;
// frag_main();
// SPIRV_Cross_Output stage_output;
// stage_output.frag_color = frag_color;
// return stage_output;
// }
//
const fs_source_hlsl5 = [687]u8 {
0x54,0x65,0x78,0x74,0x75,0x72,0x65,0x32,0x44,0x3c,0x66,0x6c,0x6f,0x61,0x74,0x34,
0x3e,0x20,0x74,0x65,0x78,0x20,0x3a,0x20,0x72,0x65,0x67,0x69,0x73,0x74,0x65,0x72,
0x28,0x74,0x30,0x29,0x3b,0x0a,0x53,0x61,0x6d,0x70,0x6c,0x65,0x72,0x53,0x74,0x61,
0x74,0x65,0x20,0x5f,0x74,0x65,0x78,0x5f,0x73,0x61,0x6d,0x70,0x6c,0x65,0x72,0x20,
0x3a,0x20,0x72,0x65,0x67,0x69,0x73,0x74,0x65,0x72,0x28,0x73,0x30,0x29,0x3b,0x0a,
0x0a,0x73,0x74,0x61,0x74,0x69,0x63,0x20,0x66,0x6c,0x6f,0x61,0x74,0x34,0x20,0x66,
0x72,0x61,0x67,0x5f,0x63,0x6f,0x6c,0x6f,0x72,0x3b,0x0a,0x73,0x74,0x61,0x74,0x69,
0x63,0x20,0x66,0x6c,0x6f,0x61,0x74,0x32,0x20,0x75,0x76,0x3b,0x0a,0x73,0x74,0x61,
0x74,0x69,0x63,0x20,0x66,0x6c,0x6f,0x61,0x74,0x34,0x20,0x63,0x6f,0x6c,0x6f,0x72,
0x3b,0x0a,0x0a,0x73,0x74,0x72,0x75,0x63,0x74,0x20,0x53,0x50,0x49,0x52,0x56,0x5f,
0x43,0x72,0x6f,0x73,0x73,0x5f,0x49,0x6e,0x70,0x75,0x74,0x0a,0x7b,0x0a,0x20,0x20,
0x20,0x20,0x66,0x6c,0x6f,0x61,0x74,0x34,0x20,0x63,0x6f,0x6c,0x6f,0x72,0x20,0x3a,
0x20,0x54,0x45,0x58,0x43,0x4f,0x4f,0x52,0x44,0x30,0x3b,0x0a,0x20,0x20,0x20,0x20,
0x66,0x6c,0x6f,0x61,0x74,0x32,0x20,0x75,0x76,0x20,0x3a,0x20,0x54,0x45,0x58,0x43,
0x4f,0x4f,0x52,0x44,0x31,0x3b,0x0a,0x7d,0x3b,0x0a,0x0a,0x73,0x74,0x72,0x75,0x63,
0x74,0x20,0x53,0x50,0x49,0x52,0x56,0x5f,0x43,0x72,0x6f,0x73,0x73,0x5f,0x4f,0x75,
0x74,0x70,0x75,0x74,0x0a,0x7b,0x0a,0x20,0x20,0x20,0x20,0x66,0x6c,0x6f,0x61,0x74,
0x34,0x20,0x66,0x72,0x61,0x67,0x5f,0x63,0x6f,0x6c,0x6f,0x72,0x20,0x3a,0x20,0x53,
0x56,0x5f,0x54,0x61,0x72,0x67,0x65,0x74,0x30,0x3b,0x0a,0x7d,0x3b,0x0a,0x0a,0x23,
0x6c,0x69,0x6e,0x65,0x20,0x31,0x33,0x20,0x22,0x2e,0x5c,0x64,0x61,0x74,0x61,0x5c,
0x73,0x68,0x61,0x64,0x65,0x72,0x73,0x5c,0x64,0x65,0x66,0x61,0x75,0x6c,0x74,0x2e,
0x67,0x6c,0x73,0x6c,0x22,0x0a,0x76,0x6f,0x69,0x64,0x20,0x66,0x72,0x61,0x67,0x5f,
0x6d,0x61,0x69,0x6e,0x28,0x29,0x0a,0x7b,0x0a,0x23,0x6c,0x69,0x6e,0x65,0x20,0x31,
0x33,0x20,0x22,0x2e,0x5c,0x64,0x61,0x74,0x61,0x5c,0x73,0x68,0x61,0x64,0x65,0x72,
0x73,0x5c,0x64,0x65,0x66,0x61,0x75,0x6c,0x74,0x2e,0x67,0x6c,0x73,0x6c,0x22,0x0a,
0x20,0x20,0x20,0x20,0x66,0x72,0x61,0x67,0x5f,0x63,0x6f,0x6c,0x6f,0x72,0x20,0x3d,
0x20,0x74,0x65,0x78,0x2e,0x53,0x61,0x6d,0x70,0x6c,0x65,0x28,0x5f,0x74,0x65,0x78,
0x5f,0x73,0x61,0x6d,0x70,0x6c,0x65,0x72,0x2c,0x20,0x75,0x76,0x29,0x3b,0x0a,0x7d,
0x0a,0x0a,0x53,0x50,0x49,0x52,0x56,0x5f,0x43,0x72,0x6f,0x73,0x73,0x5f,0x4f,0x75,
0x74,0x70,0x75,0x74,0x20,0x6d,0x61,0x69,0x6e,0x28,0x53,0x50,0x49,0x52,0x56,0x5f,
0x43,0x72,0x6f,0x73,0x73,0x5f,0x49,0x6e,0x70,0x75,0x74,0x20,0x73,0x74,0x61,0x67,
0x65,0x5f,0x69,0x6e,0x70,0x75,0x74,0x29,0x0a,0x7b,0x0a,0x20,0x20,0x20,0x20,0x75,
0x76,0x20,0x3d,0x20,0x73,0x74,0x61,0x67,0x65,0x5f,0x69,0x6e,0x70,0x75,0x74,0x2e,
0x75,0x76,0x3b,0x0a,0x20,0x20,0x20,0x20,0x63,0x6f,0x6c,0x6f,0x72,0x20,0x3d,0x20,
0x73,0x74,0x61,0x67,0x65,0x5f,0x69,0x6e,0x70,0x75,0x74,0x2e,0x63,0x6f,0x6c,0x6f,
0x72,0x3b,0x0a,0x20,0x20,0x20,0x20,0x66,0x72,0x61,0x67,0x5f,0x6d,0x61,0x69,0x6e,
0x28,0x29,0x3b,0x0a,0x20,0x20,0x20,0x20,0x53,0x50,0x49,0x52,0x56,0x5f,0x43,0x72,
0x6f,0x73,0x73,0x5f,0x4f,0x75,0x74,0x70,0x75,0x74,0x20,0x73,0x74,0x61,0x67,0x65,
0x5f,0x6f,0x75,0x74,0x70,0x75,0x74,0x3b,0x0a,0x20,0x20,0x20,0x20,0x73,0x74,0x61,
0x67,0x65,0x5f,0x6f,0x75,0x74,0x70,0x75,0x74,0x2e,0x66,0x72,0x61,0x67,0x5f,0x63,
0x6f,0x6c,0x6f,0x72,0x20,0x3d,0x20,0x66,0x72,0x61,0x67,0x5f,0x63,0x6f,0x6c,0x6f,
0x72,0x3b,0x0a,0x20,0x20,0x20,0x20,0x72,0x65,0x74,0x75,0x72,0x6e,0x20,0x73,0x74,
0x61,0x67,0x65,0x5f,0x6f,0x75,0x74,0x70,0x75,0x74,0x3b,0x0a,0x7d,0x0a,0x00,
};
//
// #include <metal_stdlib>
// #include <simd/simd.h>
//
// using namespace metal;
//
// struct main0_out
// {
// float4 color [[user(locn0)]];
// float2 uv [[user(locn1)]];
// float4 gl_Position [[position]];
// };
//
// struct main0_in
// {
// float4 pos [[attribute(0)]];
// float4 col [[attribute(1)]];
// float2 texc [[attribute(2)]];
// };
//
// #line 18 ".\data\shaders\default.glsl"
// vertex main0_out main0(main0_in in [[stage_in]])
// {
// main0_out out = {};
// #line 18 ".\data\shaders\default.glsl"
// out.gl_Position = in.pos;
// #line 19 ".\data\shaders\default.glsl"
// out.color = in.col;
// #line 20 ".\data\shaders\default.glsl"
// out.uv = in.texc;
// return out;
// }
//
//
const vs_source_metal_macos = [646]u8 {
0x23,0x69,0x6e,0x63,0x6c,0x75,0x64,0x65,0x20,0x3c,0x6d,0x65,0x74,0x61,0x6c,0x5f,
0x73,0x74,0x64,0x6c,0x69,0x62,0x3e,0x0a,0x23,0x69,0x6e,0x63,0x6c,0x75,0x64,0x65,
0x20,0x3c,0x73,0x69,0x6d,0x64,0x2f,0x73,0x69,0x6d,0x64,0x2e,0x68,0x3e,0x0a,0x0a,
0x75,0x73,0x69,0x6e,0x67,0x20,0x6e,0x61,0x6d,0x65,0x73,0x70,0x61,0x63,0x65,0x20,
0x6d,0x65,0x74,0x61,0x6c,0x3b,0x0a,0x0a,0x73,0x74,0x72,0x75,0x63,0x74,0x20,0x6d,
0x61,0x69,0x6e,0x30,0x5f,0x6f,0x75,0x74,0x0a,0x7b,0x0a,0x20,0x20,0x20,0x20,0x66,
0x6c,0x6f,0x61,0x74,0x34,0x20,0x63,0x6f,0x6c,0x6f,0x72,0x20,0x5b,0x5b,0x75,0x73,
0x65,0x72,0x28,0x6c,0x6f,0x63,0x6e,0x30,0x29,0x5d,0x5d,0x3b,0x0a,0x20,0x20,0x20,
0x20,0x66,0x6c,0x6f,0x61,0x74,0x32,0x20,0x75,0x76,0x20,0x5b,0x5b,0x75,0x73,0x65,
0x72,0x28,0x6c,0x6f,0x63,0x6e,0x31,0x29,0x5d,0x5d,0x3b,0x0a,0x20,0x20,0x20,0x20,
0x66,0x6c,0x6f,0x61,0x74,0x34,0x20,0x67,0x6c,0x5f,0x50,0x6f,0x73,0x69,0x74,0x69,
0x6f,0x6e,0x20,0x5b,0x5b,0x70,0x6f,0x73,0x69,0x74,0x69,0x6f,0x6e,0x5d,0x5d,0x3b,
0x0a,0x7d,0x3b,0x0a,0x0a,0x73,0x74,0x72,0x75,0x63,0x74,0x20,0x6d,0x61,0x69,0x6e,
0x30,0x5f,0x69,0x6e,0x0a,0x7b,0x0a,0x20,0x20,0x20,0x20,0x66,0x6c,0x6f,0x61,0x74,
0x34,0x20,0x70,0x6f,0x73,0x20,0x5b,0x5b,0x61,0x74,0x74,0x72,0x69,0x62,0x75,0x74,
0x65,0x28,0x30,0x29,0x5d,0x5d,0x3b,0x0a,0x20,0x20,0x20,0x20,0x66,0x6c,0x6f,0x61,
0x74,0x34,0x20,0x63,0x6f,0x6c,0x20,0x5b,0x5b,0x61,0x74,0x74,0x72,0x69,0x62,0x75,
0x74,0x65,0x28,0x31,0x29,0x5d,0x5d,0x3b,0x0a,0x20,0x20,0x20,0x20,0x66,0x6c,0x6f,
0x61,0x74,0x32,0x20,0x74,0x65,0x78,0x63,0x20,0x5b,0x5b,0x61,0x74,0x74,0x72,0x69,
0x62,0x75,0x74,0x65,0x28,0x32,0x29,0x5d,0x5d,0x3b,0x0a,0x7d,0x3b,0x0a,0x0a,0x23,
0x6c,0x69,0x6e,0x65,0x20,0x31,0x38,0x20,0x22,0x2e,0x5c,0x64,0x61,0x74,0x61,0x5c,
0x73,0x68,0x61,0x64,0x65,0x72,0x73,0x5c,0x64,0x65,0x66,0x61,0x75,0x6c,0x74,0x2e,
0x67,0x6c,0x73,0x6c,0x22,0x0a,0x76,0x65,0x72,0x74,0x65,0x78,0x20,0x6d,0x61,0x69,
0x6e,0x30,0x5f,0x6f,0x75,0x74,0x20,0x6d,0x61,0x69,0x6e,0x30,0x28,0x6d,0x61,0x69,
0x6e,0x30,0x5f,0x69,0x6e,0x20,0x69,0x6e,0x20,0x5b,0x5b,0x73,0x74,0x61,0x67,0x65,
0x5f,0x69,0x6e,0x5d,0x5d,0x29,0x0a,0x7b,0x0a,0x20,0x20,0x20,0x20,0x6d,0x61,0x69,
0x6e,0x30,0x5f,0x6f,0x75,0x74,0x20,0x6f,0x75,0x74,0x20,0x3d,0x20,0x7b,0x7d,0x3b,
0x0a,0x23,0x6c,0x69,0x6e,0x65,0x20,0x31,0x38,0x20,0x22,0x2e,0x5c,0x64,0x61,0x74,
0x61,0x5c,0x73,0x68,0x61,0x64,0x65,0x72,0x73,0x5c,0x64,0x65,0x66,0x61,0x75,0x6c,
0x74,0x2e,0x67,0x6c,0x73,0x6c,0x22,0x0a,0x20,0x20,0x20,0x20,0x6f,0x75,0x74,0x2e,
0x67,0x6c,0x5f,0x50,0x6f,0x73,0x69,0x74,0x69,0x6f,0x6e,0x20,0x3d,0x20,0x69,0x6e,
0x2e,0x70,0x6f,0x73,0x3b,0x0a,0x23,0x6c,0x69,0x6e,0x65,0x20,0x31,0x39,0x20,0x22,
0x2e,0x5c,0x64,0x61,0x74,0x61,0x5c,0x73,0x68,0x61,0x64,0x65,0x72,0x73,0x5c,0x64,
0x65,0x66,0x61,0x75,0x6c,0x74,0x2e,0x67,0x6c,0x73,0x6c,0x22,0x0a,0x20,0x20,0x20,
0x20,0x6f,0x75,0x74,0x2e,0x63,0x6f,0x6c,0x6f,0x72,0x20,0x3d,0x20,0x69,0x6e,0x2e,
0x63,0x6f,0x6c,0x3b,0x0a,0x23,0x6c,0x69,0x6e,0x65,0x20,0x32,0x30,0x20,0x22,0x2e,
0x5c,0x64,0x61,0x74,0x61,0x5c,0x73,0x68,0x61,0x64,0x65,0x72,0x73,0x5c,0x64,0x65,
0x66,0x61,0x75,0x6c,0x74,0x2e,0x67,0x6c,0x73,0x6c,0x22,0x0a,0x20,0x20,0x20,0x20,
0x6f,0x75,0x74,0x2e,0x75,0x76,0x20,0x3d,0x20,0x69,0x6e,0x2e,0x74,0x65,0x78,0x63,
0x3b,0x0a,0x20,0x20,0x20,0x20,0x72,0x65,0x74,0x75,0x72,0x6e,0x20,0x6f,0x75,0x74,
0x3b,0x0a,0x7d,0x0a,0x0a,0x00,
};
//
// #include <metal_stdlib>
// #include <simd/simd.h>
//
// using namespace metal;
//
// struct main0_out
// {
// float4 frag_color [[color(0)]];
// };
//
// struct main0_in
// {
// float2 uv [[user(locn1)]];
// };
//
// #line 13 ".\data\shaders\default.glsl"
// fragment main0_out main0(main0_in in [[stage_in]], texture2d<float> tex [[texture(0)]], sampler texSmplr [[sampler(0)]])
// {
// main0_out out = {};
// #line 13 ".\data\shaders\default.glsl"
// out.frag_color = tex.sample(texSmplr, in.uv);
// return out;
// }
//
//
const fs_source_metal_macos = [479]u8 {
0x23,0x69,0x6e,0x63,0x6c,0x75,0x64,0x65,0x20,0x3c,0x6d,0x65,0x74,0x61,0x6c,0x5f,
0x73,0x74,0x64,0x6c,0x69,0x62,0x3e,0x0a,0x23,0x69,0x6e,0x63,0x6c,0x75,0x64,0x65,
0x20,0x3c,0x73,0x69,0x6d,0x64,0x2f,0x73,0x69,0x6d,0x64,0x2e,0x68,0x3e,0x0a,0x0a,
0x75,0x73,0x69,0x6e,0x67,0x20,0x6e,0x61,0x6d,0x65,0x73,0x70,0x61,0x63,0x65,0x20,
0x6d,0x65,0x74,0x61,0x6c,0x3b,0x0a,0x0a,0x73,0x74,0x72,0x75,0x63,0x74,0x20,0x6d,
0x61,0x69,0x6e,0x30,0x5f,0x6f,0x75,0x74,0x0a,0x7b,0x0a,0x20,0x20,0x20,0x20,0x66,
0x6c,0x6f,0x61,0x74,0x34,0x20,0x66,0x72,0x61,0x67,0x5f,0x63,0x6f,0x6c,0x6f,0x72,
0x20,0x5b,0x5b,0x63,0x6f,0x6c,0x6f,0x72,0x28,0x30,0x29,0x5d,0x5d,0x3b,0x0a,0x7d,
0x3b,0x0a,0x0a,0x73,0x74,0x72,0x75,0x63,0x74,0x20,0x6d,0x61,0x69,0x6e,0x30,0x5f,
0x69,0x6e,0x0a,0x7b,0x0a,0x20,0x20,0x20,0x20,0x66,0x6c,0x6f,0x61,0x74,0x32,0x20,
0x75,0x76,0x20,0x5b,0x5b,0x75,0x73,0x65,0x72,0x28,0x6c,0x6f,0x63,0x6e,0x31,0x29,
0x5d,0x5d,0x3b,0x0a,0x7d,0x3b,0x0a,0x0a,0x23,0x6c,0x69,0x6e,0x65,0x20,0x31,0x33,
0x20,0x22,0x2e,0x5c,0x64,0x61,0x74,0x61,0x5c,0x73,0x68,0x61,0x64,0x65,0x72,0x73,
0x5c,0x64,0x65,0x66,0x61,0x75,0x6c,0x74,0x2e,0x67,0x6c,0x73,0x6c,0x22,0x0a,0x66,
0x72,0x61,0x67,0x6d,0x65,0x6e,0x74,0x20,0x6d,0x61,0x69,0x6e,0x30,0x5f,0x6f,0x75,
0x74,0x20,0x6d,0x61,0x69,0x6e,0x30,0x28,0x6d,0x61,0x69,0x6e,0x30,0x5f,0x69,0x6e,
0x20,0x69,0x6e,0x20,0x5b,0x5b,0x73,0x74,0x61,0x67,0x65,0x5f,0x69,0x6e,0x5d,0x5d,
0x2c,0x20,0x74,0x65,0x78,0x74,0x75,0x72,0x65,0x32,0x64,0x3c,0x66,0x6c,0x6f,0x61,
0x74,0x3e,0x20,0x74,0x65,0x78,0x20,0x5b,0x5b,0x74,0x65,0x78,0x74,0x75,0x72,0x65,
0x28,0x30,0x29,0x5d,0x5d,0x2c,0x20,0x73,0x61,0x6d,0x70,0x6c,0x65,0x72,0x20,0x74,
0x65,0x78,0x53,0x6d,0x70,0x6c,0x72,0x20,0x5b,0x5b,0x73,0x61,0x6d,0x70,0x6c,0x65,
0x72,0x28,0x30,0x29,0x5d,0x5d,0x29,0x0a,0x7b,0x0a,0x20,0x20,0x20,0x20,0x6d,0x61,
0x69,0x6e,0x30,0x5f,0x6f,0x75,0x74,0x20,0x6f,0x75,0x74,0x20,0x3d,0x20,0x7b,0x7d,
0x3b,0x0a,0x23,0x6c,0x69,0x6e,0x65,0x20,0x31,0x33,0x20,0x22,0x2e,0x5c,0x64,0x61,
0x74,0x61,0x5c,0x73,0x68,0x61,0x64,0x65,0x72,0x73,0x5c,0x64,0x65,0x66,0x61,0x75,
0x6c,0x74,0x2e,0x67,0x6c,0x73,0x6c,0x22,0x0a,0x20,0x20,0x20,0x20,0x6f,0x75,0x74,
0x2e,0x66,0x72,0x61,0x67,0x5f,0x63,0x6f,0x6c,0x6f,0x72,0x20,0x3d,0x20,0x74,0x65,
0x78,0x2e,0x73,0x61,0x6d,0x70,0x6c,0x65,0x28,0x74,0x65,0x78,0x53,0x6d,0x70,0x6c,
0x72,0x2c,0x20,0x69,0x6e,0x2e,0x75,0x76,0x29,0x3b,0x0a,0x20,0x20,0x20,0x20,0x72,
0x65,0x74,0x75,0x72,0x6e,0x20,0x6f,0x75,0x74,0x3b,0x0a,0x7d,0x0a,0x0a,0x00,
};
pub fn texcubeShaderDesc(backend: sg.Backend) sg.ShaderDesc {
var desc: sg.ShaderDesc = .{};
switch (backend) {
.GLCORE33 => {
desc.attrs[0].name = "pos";
desc.attrs[1].name = "col";
desc.attrs[2].name = "texc";
desc.vs.source = &vs_source_glsl330;
desc.vs.entry = "main";
desc.fs.source = &fs_source_glsl330;
desc.fs.entry = "main";
desc.fs.images[0].name = "tex";
desc.fs.images[0].image_type = ._2D;
desc.fs.images[0].sampler_type = .FLOAT;
desc.label = "texcube_shader";
},
.D3D11 => {
desc.attrs[0].sem_name = "TEXCOORD";
desc.attrs[0].sem_index = 0;
desc.attrs[1].sem_name = "TEXCOORD";
desc.attrs[1].sem_index = 1;
desc.attrs[2].sem_name = "TEXCOORD";
desc.attrs[2].sem_index = 2;
desc.vs.source = &vs_source_hlsl5;
desc.vs.d3d11_target = "vs_5_0";
desc.vs.entry = "main";
desc.fs.source = &fs_source_hlsl5;
desc.fs.d3d11_target = "ps_5_0";
desc.fs.entry = "main";
desc.fs.images[0].name = "tex";
desc.fs.images[0].image_type = ._2D;
desc.fs.images[0].sampler_type = .FLOAT;
desc.label = "texcube_shader";
},
.METAL_MACOS => {
desc.vs.source = &vs_source_metal_macos;
desc.vs.entry = "main0";
desc.fs.source = &fs_source_metal_macos;
desc.fs.entry = "main0";
desc.fs.images[0].name = "tex";
desc.fs.images[0].image_type = ._2D;
desc.fs.images[0].sampler_type = .FLOAT;
desc.label = "texcube_shader";
},
else => {},
}
return desc;
} | src/default.glsl.zig |
const std = @import("std");
const expect = std.testing.expect;
const math = std.math;
const pi = std.math.pi;
const e = std.math.e;
const Vector = std.meta.Vector;
const epsilon = 0.000001;
test "floating point comparisons" {
try testFloatComparisons();
comptime try testFloatComparisons();
}
fn testFloatComparisons() !void {
inline for ([_]type{ f16, f32, f64, f128 }) |ty| {
// No decimal part
{
const x: ty = 1.0;
try expect(x == 1);
try expect(x != 0);
try expect(x > 0);
try expect(x < 2);
try expect(x >= 1);
try expect(x <= 1);
}
// Non-zero decimal part
{
const x: ty = 1.5;
try expect(x != 1);
try expect(x != 2);
try expect(x > 1);
try expect(x < 2);
try expect(x >= 1);
try expect(x <= 2);
}
}
}
test "different sized float comparisons" {
try testDifferentSizedFloatComparisons();
comptime try testDifferentSizedFloatComparisons();
}
fn testDifferentSizedFloatComparisons() !void {
var a: f16 = 1;
var b: f64 = 2;
try expect(a < b);
}
// TODO This is waiting on library support for the Windows build (not sure why the other's don't need it)
//test "@nearbyint" {
// comptime testNearbyInt();
// testNearbyInt();
//}
//fn testNearbyInt() void {
// // TODO test f16, f128, and c_longdouble
// // https://github.com/ziglang/zig/issues/4026
// {
// var a: f32 = 2.1;
// try expect(@nearbyint(a) == 2);
// }
// {
// var a: f64 = -3.75;
// try expect(@nearbyint(a) == -4);
// }
//}
test "negative f128 floatToInt at compile-time" {
const a: f128 = -2;
var b = @floatToInt(i64, a);
try expect(@as(i64, -2) == b);
}
test "@sqrt" {
comptime try testSqrt();
try testSqrt();
}
fn testSqrt() !void {
{
var a: f16 = 4;
try expect(@sqrt(a) == 2);
}
{
var a: f32 = 9;
try expect(@sqrt(a) == 3);
var b: f32 = 1.1;
try expect(math.approxEqAbs(f32, @sqrt(b), 1.0488088481701516, epsilon));
}
{
var a: f64 = 25;
try expect(@sqrt(a) == 5);
}
}
test "more @sqrt f16 tests" {
// TODO these are not all passing at comptime
try expect(@sqrt(@as(f16, 0.0)) == 0.0);
try expect(math.approxEqAbs(f16, @sqrt(@as(f16, 2.0)), 1.414214, epsilon));
try expect(math.approxEqAbs(f16, @sqrt(@as(f16, 3.6)), 1.897367, epsilon));
try expect(@sqrt(@as(f16, 4.0)) == 2.0);
try expect(math.approxEqAbs(f16, @sqrt(@as(f16, 7.539840)), 2.745877, epsilon));
try expect(math.approxEqAbs(f16, @sqrt(@as(f16, 19.230934)), 4.385309, epsilon));
try expect(@sqrt(@as(f16, 64.0)) == 8.0);
try expect(math.approxEqAbs(f16, @sqrt(@as(f16, 64.1)), 8.006248, epsilon));
try expect(math.approxEqAbs(f16, @sqrt(@as(f16, 8942.230469)), 94.563370, epsilon));
// special cases
try expect(math.isPositiveInf(@sqrt(@as(f16, math.inf(f16)))));
try expect(@sqrt(@as(f16, 0.0)) == 0.0);
try expect(@sqrt(@as(f16, -0.0)) == -0.0);
try expect(math.isNan(@sqrt(@as(f16, -1.0))));
try expect(math.isNan(@sqrt(@as(f16, math.nan(f16)))));
} | test/behavior/floatop.zig |
const std = @import("std");
const Client = @import("../Client.zig");
const util = @import("../util.zig");
const log = std.log.scoped(.zCord);
const Heartbeat = @This();
handler: union(enum) {
thread: *ThreadHandler,
callback: CallbackHandler,
},
pub const Message = enum { start, ack, stop, deinit };
pub const Strategy = union(enum) {
thread,
manual,
callback: CallbackHandler,
pub const default = Strategy.thread;
};
pub fn init(client: *Client, strategy: Strategy) !Heartbeat {
return Heartbeat{
.handler = switch (strategy) {
.thread => .{ .thread = try ThreadHandler.init(client) },
.callback => |cb| .{ .callback = cb },
.manual => .{
.callback = .{
.context = undefined,
.func = struct {
fn noop(ctx: *c_void, msg: Message) void {}
}.noop,
},
},
},
};
}
pub fn deinit(self: Heartbeat) void {
switch (self.handler) {
.thread => |thread| thread.deinit(),
.callback => |cb| cb.func(cb.context, .deinit),
}
}
pub fn send(self: Heartbeat, msg: Message) void {
switch (self.handler) {
.thread => |thread| thread.mailbox.putOverwrite(msg),
.callback => |cb| cb.func(cb.context, msg),
}
}
pub const CallbackHandler = struct {
context: *c_void,
func: fn (ctx: *c_void, msg: Message) void,
};
const ThreadHandler = struct {
allocator: *std.mem.Allocator,
mailbox: util.Mailbox(Message),
thread: *std.Thread,
fn init(client: *Client) !*ThreadHandler {
const result = try client.allocator.create(ThreadHandler);
errdefer client.allocator.destroy(result);
result.allocator = client.allocator;
try result.mailbox.init();
errdefer result.mailbox.deinit();
result.thread = try std.Thread.spawn(handler, .{ .ctx = result, .client = client });
return result;
}
fn deinit(ctx: *ThreadHandler) void {
ctx.mailbox.putOverwrite(.deinit);
// Reap the thread
ctx.thread.wait();
ctx.mailbox.deinit();
ctx.allocator.destroy(ctx);
}
fn handler(args: struct { ctx: *ThreadHandler, client: *Client }) void {
var heartbeat_interval_ms: u64 = 0;
var ack = false;
while (true) {
if (heartbeat_interval_ms == 0) {
switch (args.ctx.mailbox.get()) {
.start => {
heartbeat_interval_ms = args.client.connect_info.?.heartbeat_interval_ms;
ack = true;
},
.ack, .stop => {},
.deinit => return,
}
} else {
// Force fire the heartbeat earlier
const timeout_ms = heartbeat_interval_ms - 1000;
if (args.ctx.mailbox.getWithTimeout(timeout_ms * std.time.ns_per_ms)) |msg| {
switch (msg) {
.start => {},
.ack => {
log.info("<< ♥", .{});
ack = true;
},
.stop => heartbeat_interval_ms = 0,
.deinit => return,
}
continue;
}
if (ack) {
ack = false;
// TODO: actually check this or fix threads + async
if (nosuspend args.client.sendCommand(.{ .heartbeat = args.client.connect_info.?.seq })) |_| {
log.info(">> ♡", .{});
continue;
} else |_| {
log.info("Heartbeat send failed. Reconnecting...", .{});
}
} else {
log.info("Missed heartbeat. Reconnecting...", .{});
}
args.client.ssl_tunnel.?.shutdown() catch |err| {
log.info("Shutdown failed: {}", .{err});
};
heartbeat_interval_ms = 0;
}
}
}
}; | src/Client/Heartbeat.zig |
const std = @import("std");
const std_json = @import("std-json.zig");
const debug_buffer = std.builtin.mode == .Debug;
pub fn streamJson(reader: anytype) StreamJson(@TypeOf(reader)) {
return .{
.reader = reader,
.parser = std_json.StreamingParser.init(),
.element_number = 0,
._root = null,
._debug_buffer = if (debug_buffer)
std.fifo.LinearFifo(u8, .{ .Static = 0x100 }).init()
else {},
};
}
pub fn StreamJson(comptime Reader: type) type {
return struct {
const Stream = @This();
reader: Reader,
parser: std_json.StreamingParser,
element_number: usize,
_root: ?Element,
_debug_buffer: if (debug_buffer)
std.fifo.LinearFifo(u8, .{ .Static = 0x100 })
else
void,
const ElementType = union(enum) {
Object: void,
Array: void,
String: void,
Number: struct { first_char: u8 },
Boolean: void,
Null: void,
};
const Error = Reader.Error || std_json.StreamingParser.Error || error{
WrongElementType,
UnexpectedEndOfJson,
};
pub const Element = struct {
ctx: *Stream,
kind: ElementType,
element_number: usize,
stack_level: u8,
fn init(ctx: *Stream) Error!?Element {
ctx.assertState(.{ .ValueBegin, .ValueBeginNoClosing, .TopLevelBegin });
const start_state = ctx.parser.state;
const kind: ElementType = blk: {
while (true) {
const byte = try ctx.nextByte();
if (try ctx.feed(byte)) |token| {
switch (token) {
.ArrayBegin => break :blk .Array,
.ObjectBegin => break :blk .Object,
.ArrayEnd, .ObjectEnd => return null,
else => ctx.assertFailure("Element unrecognized: {}", .{token}),
}
}
if (ctx.parser.state != start_state) {
switch (ctx.parser.state) {
.String => break :blk .String,
.Number, .NumberMaybeDotOrExponent, .NumberMaybeDigitOrDotOrExponent => break :blk .{ .Number = .{ .first_char = byte } },
.TrueLiteral1, .FalseLiteral1 => break :blk .Boolean,
.NullLiteral1 => break :blk .Null,
else => ctx.assertFailure("Element unrecognized: {}", .{ctx.parser.state}),
}
}
}
};
ctx.element_number += 1;
return Element{ .ctx = ctx, .kind = kind, .element_number = ctx.element_number, .stack_level = ctx.parser.stack_used };
}
pub fn boolean(self: Element) Error!bool {
if (self.kind != .Boolean) {
return error.WrongElementType;
}
self.ctx.assertState(.{ .TrueLiteral1, .FalseLiteral1 });
switch ((try self.finalizeToken()).?) {
.True => return true,
.False => return false,
else => unreachable,
}
}
pub fn optionalBoolean(self: Element) Error!?bool {
if (try self.checkOptional()) {
return null;
} else {
return try self.boolean();
}
}
pub fn optionalNumber(self: Element, comptime T: type) !?T {
if (try self.checkOptional()) {
return null;
} else {
return try self.number(T);
}
}
pub fn number(self: Element, comptime T: type) !T {
if (self.kind != .Number) {
return error.WrongElementType;
}
switch (@typeInfo(T)) {
.Int => {
// +1 for converting floor -> ceil
// +1 for negative sign
// +1 for simplifying terminating character detection
const max_digits = std.math.log10(std.math.maxInt(T)) + 3;
var buffer: [max_digits]u8 = undefined;
return try std.fmt.parseInt(T, try self.numberBuffer(&buffer), 10);
},
.Float => {
const max_digits = 0x1000; // Yeah this is a total kludge, but floats are hard. :(
var buffer: [max_digits]u8 = undefined;
return try std.fmt.parseFloat(T, try self.numberBuffer(&buffer));
},
else => @compileError("Unsupported number type"),
}
}
fn numberBuffer(self: Element, buffer: []u8) (Error || error{Overflow})![]u8 {
// Handle first byte manually
buffer[0] = self.kind.Number.first_char;
for (buffer[1..]) |*c, i| {
const byte = try self.ctx.nextByte();
if (try self.ctx.feed(byte)) |token| {
const len = i + 1;
std.debug.assert(token == .Number);
std.debug.assert(token.Number.count == len);
return buffer[0..len];
} else {
c.* = byte;
}
}
return error.Overflow;
}
pub fn stringBuffer(self: Element, buffer: []u8) (Error || error{NoSpaceLeft})![]u8 {
const reader = try self.stringReader();
const size = try reader.readAll(buffer);
return buffer[0..size];
}
const StringReader = std.io.Reader(
Element,
Error,
(struct {
fn read(self: Element, buffer: []u8) Error!usize {
if (self.ctx.parser.state == .ValueEnd or self.ctx.parser.state == .TopLevelEnd) {
return 0;
}
for (buffer) |*c, i| {
const byte = try self.ctx.nextByte();
if (try self.ctx.feed(byte)) |token| {
std.debug.assert(token == .String);
return i;
} else if (byte == '\\') {
const next = try self.ctx.nextByte();
std.debug.assert((try self.ctx.feed(next)) == null);
c.* = switch (next) {
'"' => '"',
'/' => '/',
'\\' => '\\',
'n' => '\n',
'r' => '\r',
't' => '\t',
'b' => 0x08, // backspace
'f' => 0x0C, // form feed
'u' => {
// TODO: handle unicode escapes
return error.InvalidEscapeCharacter;
},
// should have been handled by the internal parser
else => unreachable,
};
} else {
c.* = byte;
}
}
return buffer.len;
}
}).read,
);
pub fn stringReader(self: Element) Error!StringReader {
if (self.kind != .String) {
return error.WrongElementType;
}
return StringReader{ .context = self };
}
pub fn optionalStringBuffer(self: Element, buffer: []u8) (Error || error{NoSpaceLeft})!?[]u8 {
if (try self.checkOptional()) {
return null;
} else {
return try self.stringBuffer(buffer);
}
}
pub fn arrayNext(self: Element) Error!?Element {
if (self.kind != .Array) {
return error.WrongElementType;
}
if (self.ctx.parser.state == .TopLevelEnd) {
return null;
}
// Scan for next element
while (self.ctx.parser.state == .ValueEnd) {
if (try self.ctx.feed(try self.ctx.nextByte())) |token| {
std.debug.assert(token == .ArrayEnd);
return null;
}
}
return try Element.init(self.ctx);
}
const ObjectMatch = struct {
key: []const u8,
value: Element,
};
pub fn objectMatch(self: Element, key: []const u8) !?ObjectMatch {
return self.objectMatchAny(&[_][]const u8{key});
}
pub fn objectMatchAny(self: Element, keys: []const []const u8) !?ObjectMatch {
if (self.kind != .Object) {
return error.WrongElementType;
}
while (true) {
if (self.ctx.parser.state == .TopLevelEnd) {
return null;
}
// Scan for next element
while (self.ctx.parser.state == .ValueEnd) {
if (try self.ctx.feed(try self.ctx.nextByte())) |token| {
std.debug.assert(token == .ObjectEnd);
return null;
}
}
const key_element = (try Element.init(self.ctx)) orelse return null;
std.debug.assert(key_element.kind == .String);
const key_match = try key_element.stringFind(keys);
// Skip over the colon
while (self.ctx.parser.state == .ObjectSeparator) {
_ = try self.ctx.feed(try self.ctx.nextByte());
}
if (key_match) |key| {
// Match detected
return ObjectMatch{
.key = key,
.value = (try Element.init(self.ctx)).?,
};
} else {
// Skip over value
const value_element = (try Element.init(self.ctx)).?;
_ = try value_element.finalizeToken();
}
}
}
fn stringFind(self: Element, checks: []const []const u8) !?[]const u8 {
std.debug.assert(self.kind == .String);
var last_byte: u8 = undefined;
var prev_match: []const u8 = &[0]u8{};
var tail: usize = 0;
var string_complete = false;
for (checks) |check| {
if (string_complete and std.mem.eql(u8, check, prev_match[0 .. tail - 1])) {
return check;
}
if (tail >= 2 and !std.mem.eql(u8, check[0 .. tail - 2], prev_match[0 .. tail - 2])) {
continue;
}
if (tail >= 1 and (tail - 1 >= check.len or check[tail - 1] != last_byte)) {
continue;
}
prev_match = check;
while (!string_complete and tail <= check.len and
(tail < 1 or check[tail - 1] == last_byte)) : (tail += 1)
{
last_byte = try self.ctx.nextByte();
if (try self.ctx.feed(last_byte)) |token| {
std.debug.assert(token == .String);
string_complete = true;
if (tail == check.len) {
return check;
}
}
}
}
if (!string_complete) {
const token = try self.finalizeToken();
std.debug.assert(token.? == .String);
}
return null;
}
fn checkOptional(self: Element) !bool {
if (self.kind != .Null) return false;
self.ctx.assertState(.{.NullLiteral1});
_ = try self.finalizeToken();
return true;
}
pub fn finalizeToken(self: Element) Error!?std_json.Token {
switch (self.kind) {
.Boolean, .Null, .Number, .String => {
std.debug.assert(self.element_number == self.ctx.element_number);
switch (self.ctx.parser.state) {
.ValueEnd, .TopLevelEnd, .ValueBeginNoClosing => return null,
else => {},
}
},
.Array, .Object => {
if (self.ctx.parser.stack_used == self.stack_level - 1) {
// Assert the parser state
return null;
} else {
std.debug.assert(self.ctx.parser.stack_used >= self.stack_level);
}
},
}
while (true) {
const byte = try self.ctx.nextByte();
if (try self.ctx.feed(byte)) |token| {
switch (self.kind) {
.Boolean => std.debug.assert(token == .True or token == .False),
.Null => std.debug.assert(token == .Null),
.Number => std.debug.assert(token == .Number),
.String => std.debug.assert(token == .String),
.Array => {
if (self.ctx.parser.stack_used >= self.stack_level) {
continue;
}
// Number followed by ArrayEnd generates two tokens at once
// causing raw token assertion to be unreliable.
std.debug.assert(byte == ']');
return .ArrayEnd;
},
.Object => {
if (self.ctx.parser.stack_used >= self.stack_level) {
continue;
}
// Number followed by ObjectEnd generates two tokens at once
// causing raw token assertion to be unreliable.
std.debug.assert(byte == '}');
return .ObjectEnd;
},
}
return token;
}
}
}
};
pub fn root(self: *Stream) Error!Element {
if (self._root == null) {
self._root = (try Element.init(self)).?;
}
return self._root.?;
}
fn assertState(ctx: Stream, valids: anytype) void {
inline for (valids) |valid| {
if (ctx.parser.state == valid) {
return;
}
}
ctx.assertFailure("Unexpected state: {s}", .{ctx.parser.state});
}
fn assertFailure(ctx: Stream, comptime fmt: []const u8, args: anytype) void {
if (debug_buffer) {
ctx.debugDump(std.io.getStdErr().writer()) catch {};
}
if (std.debug.runtime_safety) {
var buffer: [0x1000]u8 = undefined;
@panic(std.fmt.bufPrint(&buffer, fmt, args) catch &buffer);
}
}
pub fn debugDump(ctx: Stream, writer: anytype) !void {
var tmp = ctx._debug_buffer;
const reader = tmp.reader();
var buf: [0x100]u8 = undefined;
const size = try reader.read(&buf);
try writer.writeAll(buf[0..size]);
try writer.writeByte('\n');
}
fn nextByte(ctx: *Stream) Error!u8 {
return ctx.reader.readByte() catch |err| switch (err) {
error.EndOfStream => error.UnexpectedEndOfJson,
else => |e| e,
};
}
// A simpler feed() to enable one liners.
// token2 can only be close object/array and we don't need it
fn feed(ctx: *Stream, byte: u8) !?std_json.Token {
if (debug_buffer) {
if (ctx._debug_buffer.writableLength() == 0) {
ctx._debug_buffer.discard(1);
std.debug.assert(ctx._debug_buffer.writableLength() == 1);
}
ctx._debug_buffer.writeAssumeCapacity(&[_]u8{byte});
}
var token1: ?std_json.Token = undefined;
var token2: ?std_json.Token = undefined;
ctx.parser.feed(byte, &token1, &token2) catch |err| {
if (debug_buffer) {
ctx.debugDump(std.io.getStdErr().writer()) catch {};
}
return err;
};
return token1;
}
};
}
fn expectEqual(actual: anytype, expected: ExpectedType(@TypeOf(actual))) void {
std.testing.expectEqual(expected, actual);
}
fn ExpectedType(comptime ActualType: type) type {
if (@typeInfo(ActualType) == .Union) {
return @TagType(ActualType);
} else {
return ActualType;
}
}
test "boolean" {
var fbs = std.io.fixedBufferStream("[true]");
var stream = streamJson(fbs.reader());
const root = try stream.root();
const element = (try root.arrayNext()).?;
expectEqual(element.kind, .Boolean);
expectEqual(try element.boolean(), true);
}
test "null" {
var fbs = std.io.fixedBufferStream("[null]");
var stream = streamJson(fbs.reader());
const root = try stream.root();
const element = (try root.arrayNext()).?;
expectEqual(element.kind, .Null);
expectEqual(try element.optionalBoolean(), null);
}
test "integer" {
{
var fbs = std.io.fixedBufferStream("[1]");
var stream = streamJson(fbs.reader());
const root = try stream.root();
const element = (try root.arrayNext()).?;
expectEqual(element.kind, .Number);
expectEqual(try element.number(u8), 1);
}
{
// Technically invalid, but we don't stream far enough to find out
var fbs = std.io.fixedBufferStream("[123,]");
var stream = streamJson(fbs.reader());
const root = try stream.root();
const element = (try root.arrayNext()).?;
expectEqual(element.kind, .Number);
expectEqual(try element.number(u8), 123);
}
{
var fbs = std.io.fixedBufferStream("[-128]");
var stream = streamJson(fbs.reader());
const root = try stream.root();
const element = (try root.arrayNext()).?;
expectEqual(element.kind, .Number);
expectEqual(try element.number(i8), -128);
}
{
var fbs = std.io.fixedBufferStream("[456]");
var stream = streamJson(fbs.reader());
const root = try stream.root();
const element = (try root.arrayNext()).?;
expectEqual(element.kind, .Number);
expectEqual(element.number(u8), error.Overflow);
}
}
test "float" {
{
var fbs = std.io.fixedBufferStream("[1.125]");
var stream = streamJson(fbs.reader());
const root = try stream.root();
const element = (try root.arrayNext()).?;
expectEqual(element.kind, .Number);
expectEqual(try element.number(f32), 1.125);
}
{
// Technically invalid, but we don't stream far enough to find out
var fbs = std.io.fixedBufferStream("[2.5,]");
var stream = streamJson(fbs.reader());
const root = try stream.root();
const element = (try root.arrayNext()).?;
expectEqual(element.kind, .Number);
expectEqual(try element.number(f64), 2.5);
}
{
var fbs = std.io.fixedBufferStream("[-1]");
var stream = streamJson(fbs.reader());
const root = try stream.root();
const element = (try root.arrayNext()).?;
expectEqual(element.kind, .Number);
expectEqual(try element.number(f64), -1);
}
{
var fbs = std.io.fixedBufferStream("[1e64]");
var stream = streamJson(fbs.reader());
const root = try stream.root();
const element = (try root.arrayNext()).?;
expectEqual(element.kind, .Number);
expectEqual(element.number(f64), 1e64);
}
}
test "string" {
{
var fbs = std.io.fixedBufferStream(
\\"hello world"
);
var stream = streamJson(fbs.reader());
const element = try stream.root();
expectEqual(element.kind, .String);
var buffer: [100]u8 = undefined;
std.testing.expectEqualStrings("hello world", try element.stringBuffer(&buffer));
}
}
test "string escapes" {
{
var fbs = std.io.fixedBufferStream(
\\"hello\nworld\t"
);
var stream = streamJson(fbs.reader());
const element = try stream.root();
expectEqual(element.kind, .String);
var buffer: [100]u8 = undefined;
std.testing.expectEqualStrings("hello\nworld\t", try element.stringBuffer(&buffer));
}
}
test "empty array" {
var fbs = std.io.fixedBufferStream("[]");
var stream = streamJson(fbs.reader());
const root = try stream.root();
expectEqual(root.kind, .Array);
expectEqual(try root.arrayNext(), null);
}
test "array of simple values" {
var fbs = std.io.fixedBufferStream("[false, true, null]");
var stream = streamJson(fbs.reader());
const root = try stream.root();
expectEqual(root.kind, .Array);
if (try root.arrayNext()) |item| {
expectEqual(item.kind, .Boolean);
expectEqual(try item.boolean(), false);
} else {
std.debug.panic("Expected a value", .{});
}
if (try root.arrayNext()) |item| {
expectEqual(item.kind, .Boolean);
expectEqual(try item.boolean(), true);
} else {
std.debug.panic("Expected a value", .{});
}
if (try root.arrayNext()) |item| {
expectEqual(item.kind, .Null);
expectEqual(try item.optionalBoolean(), null);
} else {
std.debug.panic("Expected a value", .{});
}
expectEqual(try root.arrayNext(), null);
}
test "array of numbers" {
var fbs = std.io.fixedBufferStream("[1, 2, -3]");
var stream = streamJson(fbs.reader());
const root = try stream.root();
expectEqual(root.kind, .Array);
if (try root.arrayNext()) |item| {
expectEqual(item.kind, .Number);
expectEqual(try item.number(u8), 1);
} else {
std.debug.panic("Expected a value", .{});
}
if (try root.arrayNext()) |item| {
expectEqual(item.kind, .Number);
expectEqual(try item.number(u8), 2);
} else {
std.debug.panic("Expected a value", .{});
}
if (try root.arrayNext()) |item| {
expectEqual(item.kind, .Number);
expectEqual(try item.number(i8), -3);
} else {
std.debug.panic("Expected a value", .{});
}
expectEqual(try root.arrayNext(), null);
}
test "array of strings" {
var fbs = std.io.fixedBufferStream(
\\["hello", "world"]);
);
var stream = streamJson(fbs.reader());
const root = try stream.root();
expectEqual(root.kind, .Array);
if (try root.arrayNext()) |item| {
var buffer: [100]u8 = undefined;
expectEqual(item.kind, .String);
std.testing.expectEqualSlices(u8, "hello", try item.stringBuffer(&buffer));
} else {
std.debug.panic("Expected a value", .{});
}
if (try root.arrayNext()) |item| {
var buffer: [100]u8 = undefined;
expectEqual(item.kind, .String);
std.testing.expectEqualSlices(u8, "world", try item.stringBuffer(&buffer));
} else {
std.debug.panic("Expected a value", .{});
}
expectEqual(try root.arrayNext(), null);
}
test "empty object" {
var fbs = std.io.fixedBufferStream("{}");
var stream = streamJson(fbs.reader());
const root = try stream.root();
expectEqual(root.kind, .Object);
expectEqual(try root.objectMatch(""), null);
}
test "object match" {
var fbs = std.io.fixedBufferStream(
\\{"foo": true, "bar": false}
);
var stream = streamJson(fbs.reader());
const root = try stream.root();
expectEqual(root.kind, .Object);
if (try root.objectMatch("foo")) |match| {
std.testing.expectEqualSlices(u8, "foo", match.key);
var buffer: [100]u8 = undefined;
expectEqual(match.value.kind, .Boolean);
expectEqual(try match.value.boolean(), true);
} else {
std.debug.panic("Expected a value", .{});
}
if (try root.objectMatch("bar")) |match| {
std.testing.expectEqualSlices(u8, "bar", match.key);
var buffer: [100]u8 = undefined;
expectEqual(match.value.kind, .Boolean);
expectEqual(try match.value.boolean(), false);
} else {
std.debug.panic("Expected a value", .{});
}
}
test "object match any" {
var fbs = std.io.fixedBufferStream(
\\{"foo": true, "foobar": false, "bar": null}
);
var stream = streamJson(fbs.reader());
const root = try stream.root();
expectEqual(root.kind, .Object);
if (try root.objectMatchAny(&[_][]const u8{ "foobar", "foo" })) |match| {
std.testing.expectEqualSlices(u8, "foo", match.key);
var buffer: [100]u8 = undefined;
expectEqual(match.value.kind, .Boolean);
expectEqual(try match.value.boolean(), true);
} else {
std.debug.panic("Expected a value", .{});
}
if (try root.objectMatchAny(&[_][]const u8{ "foo", "foobar" })) |match| {
std.testing.expectEqualSlices(u8, "foobar", match.key);
var buffer: [100]u8 = undefined;
expectEqual(match.value.kind, .Boolean);
expectEqual(try match.value.boolean(), false);
} else {
std.debug.panic("Expected a value", .{});
}
}
test "object match not found" {
var fbs = std.io.fixedBufferStream(
\\{"foo": [[]], "bar": false, "baz": {}}
);
var stream = streamJson(fbs.reader());
const root = try stream.root();
expectEqual(root.kind, .Object);
expectEqual(try root.objectMatch("???"), null);
}
fn expectElement(e: anytype) StreamJson(std.io.FixedBufferStream([]const u8).Reader).Error!void {
switch (e.kind) {
// TODO: test objects better
.Object => _ = try e.finalizeToken(),
.Array => {
while (try e.arrayNext()) |child| {
try expectElement(child);
}
},
.String => _ = try e.finalizeToken(),
// TODO: fix inferred errors
// .Number => _ = try e.number(u64),
.Number => _ = try e.finalizeToken(),
.Boolean => _ = try e.boolean(),
.Null => _ = try e.optionalBoolean(),
}
}
fn expectValidParseOutput(input: []const u8) !void {
var fbs = std.io.fixedBufferStream(input);
var stream = streamJson(fbs.reader());
const root = try stream.root();
try expectElement(root);
}
test "smoke" {
try expectValidParseOutput(
\\[[], [], [[]], [[""], [], [[], 0], null], false]
);
}
test "finalizeToken on object" {
var fbs = std.io.fixedBufferStream("{}");
var stream = streamJson(fbs.reader());
const root = try stream.root();
expectEqual(root.kind, .Object);
expectEqual(try root.finalizeToken(), .ObjectEnd);
expectEqual(try root.finalizeToken(), null);
expectEqual(try root.finalizeToken(), null);
expectEqual(try root.finalizeToken(), null);
expectEqual(try root.finalizeToken(), null);
expectEqual(try root.finalizeToken(), null);
}
test "finalizeToken on string" {
var fbs = std.io.fixedBufferStream(
\\"foo"
);
var stream = streamJson(fbs.reader());
const root = try stream.root();
expectEqual(root.kind, .String);
std.testing.expect((try root.finalizeToken()).? == .String);
expectEqual(try root.finalizeToken(), null);
expectEqual(try root.finalizeToken(), null);
expectEqual(try root.finalizeToken(), null);
expectEqual(try root.finalizeToken(), null);
expectEqual(try root.finalizeToken(), null);
}
test "finalizeToken on number" {
var fbs = std.io.fixedBufferStream("[[1234,5678]]");
var stream = streamJson(fbs.reader());
const root = try stream.root();
expectEqual(root.kind, .Array);
const inner = (try root.arrayNext()).?;
expectEqual(inner.kind, .Array);
const first = (try inner.arrayNext()).?;
expectEqual(first.kind, .Number);
std.testing.expect((try first.finalizeToken()).? == .Number);
expectEqual(try first.finalizeToken(), null);
expectEqual(try first.finalizeToken(), null);
expectEqual(try first.finalizeToken(), null);
expectEqual(try first.finalizeToken(), null);
const second = (try inner.arrayNext()).?;
expectEqual(second.kind, .Number);
std.testing.expect((try second.finalizeToken()).? == .Number);
expectEqual(try second.finalizeToken(), null);
expectEqual(try second.finalizeToken(), null);
expectEqual(try second.finalizeToken(), null);
}
/// Super simple "perfect hash" algorithm
/// Only really useful for switching on strings
// TODO: can we auto detect and promote the underlying type?
pub fn Swhash(comptime max_bytes: comptime_int) type {
const T = std.meta.Int(.unsigned, max_bytes * 8);
return struct {
pub fn match(string: []const u8) T {
return hash(string) orelse std.math.maxInt(T);
}
pub fn case(comptime string: []const u8) T {
return hash(string) orelse @compileError("Cannot hash '" ++ string ++ "'");
}
fn hash(string: []const u8) ?T {
if (string.len > max_bytes) return null;
var tmp = [_]u8{0} ** max_bytes;
std.mem.copy(u8, &tmp, string);
return std.mem.readIntNative(T, &tmp);
}
};
}
pub fn Mailbox(comptime T: type) type {
return struct {
const Self = @This();
value: T,
mutex: std.Mutex,
pub fn init() Self {
var result = Self{ .value = undefined, .mutex = std.Mutex{} };
// Manually lock this so get() is blocked
_ = result.mutex.acquire();
return result;
}
pub fn initWithValue(value: T) Self {
return .{ .value = value, .mutex = std.Mutex{} };
}
pub fn get(self: *Self) T {
_ = self.mutex.acquire();
// TODO: add a mutex around the result data?
return self.value;
}
pub fn putOverwrite(self: *Self, value: T) void {
const lock = self.mutex.tryAcquire() orelse std.Mutex.Held{ .mutex = &self.mutex };
self.value = value;
lock.release();
}
};
} | src/util.zig |
pub const DISPID_EVENT_ON_STATE_CHANGED = @as(u32, 5);
pub const DISPID_EVENT_ON_TERMINATION = @as(u32, 6);
pub const DISPID_EVENT_ON_CONTEXT_DATA = @as(u32, 7);
pub const DISPID_EVENT_ON_SEND_ERROR = @as(u32, 8);
//--------------------------------------------------------------------------------
// Section: Types (6)
//--------------------------------------------------------------------------------
const CLSID_RendezvousApplication_Value = Guid.initString("0b7e019a-b5de-47fa-8966-9082f82fb192");
pub const CLSID_RendezvousApplication = &CLSID_RendezvousApplication_Value;
pub const RENDEZVOUS_SESSION_STATE = enum(i32) {
UNKNOWN = 0,
READY = 1,
INVITATION = 2,
ACCEPTED = 3,
CONNECTED = 4,
CANCELLED = 5,
DECLINED = 6,
TERMINATED = 7,
};
pub const RSS_UNKNOWN = RENDEZVOUS_SESSION_STATE.UNKNOWN;
pub const RSS_READY = RENDEZVOUS_SESSION_STATE.READY;
pub const RSS_INVITATION = RENDEZVOUS_SESSION_STATE.INVITATION;
pub const RSS_ACCEPTED = RENDEZVOUS_SESSION_STATE.ACCEPTED;
pub const RSS_CONNECTED = RENDEZVOUS_SESSION_STATE.CONNECTED;
pub const RSS_CANCELLED = RENDEZVOUS_SESSION_STATE.CANCELLED;
pub const RSS_DECLINED = RENDEZVOUS_SESSION_STATE.DECLINED;
pub const RSS_TERMINATED = RENDEZVOUS_SESSION_STATE.TERMINATED;
pub const RENDEZVOUS_SESSION_FLAGS = enum(i32) {
NONE = 0,
INVITER = 1,
INVITEE = 2,
ORIGINAL_INVITER = 4,
REMOTE_LEGACYSESSION = 8,
REMOTE_WIN7SESSION = 16,
};
pub const RSF_NONE = RENDEZVOUS_SESSION_FLAGS.NONE;
pub const RSF_INVITER = RENDEZVOUS_SESSION_FLAGS.INVITER;
pub const RSF_INVITEE = RENDEZVOUS_SESSION_FLAGS.INVITEE;
pub const RSF_ORIGINAL_INVITER = RENDEZVOUS_SESSION_FLAGS.ORIGINAL_INVITER;
pub const RSF_REMOTE_LEGACYSESSION = RENDEZVOUS_SESSION_FLAGS.REMOTE_LEGACYSESSION;
pub const RSF_REMOTE_WIN7SESSION = RENDEZVOUS_SESSION_FLAGS.REMOTE_WIN7SESSION;
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IRendezvousSession_Value = Guid.initString("9ba4b1dd-8b0c-48b7-9e7c-2f25857c8df5");
pub const IID_IRendezvousSession = &IID_IRendezvousSession_Value;
pub const IRendezvousSession = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_State: fn(
self: *const IRendezvousSession,
pSessionState: ?*RENDEZVOUS_SESSION_STATE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_RemoteUser: fn(
self: *const IRendezvousSession,
bstrUserName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Flags: fn(
self: *const IRendezvousSession,
pFlags: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SendContextData: fn(
self: *const IRendezvousSession,
bstrData: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Terminate: fn(
self: *const IRendezvousSession,
hr: HRESULT,
bstrAppData: ?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 IRendezvousSession_get_State(self: *const T, pSessionState: ?*RENDEZVOUS_SESSION_STATE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRendezvousSession.VTable, self.vtable).get_State(@ptrCast(*const IRendezvousSession, self), pSessionState);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRendezvousSession_get_RemoteUser(self: *const T, bstrUserName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRendezvousSession.VTable, self.vtable).get_RemoteUser(@ptrCast(*const IRendezvousSession, self), bstrUserName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRendezvousSession_get_Flags(self: *const T, pFlags: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRendezvousSession.VTable, self.vtable).get_Flags(@ptrCast(*const IRendezvousSession, self), pFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRendezvousSession_SendContextData(self: *const T, bstrData: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRendezvousSession.VTable, self.vtable).SendContextData(@ptrCast(*const IRendezvousSession, self), bstrData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRendezvousSession_Terminate(self: *const T, hr: HRESULT, bstrAppData: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRendezvousSession.VTable, self.vtable).Terminate(@ptrCast(*const IRendezvousSession, self), hr, bstrAppData);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_DRendezvousSessionEvents_Value = Guid.initString("3fa19cf8-64c4-4f53-ae60-635b3806eca6");
pub const IID_DRendezvousSessionEvents = &IID_DRendezvousSessionEvents_Value;
pub const DRendezvousSessionEvents = 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());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IRendezvousApplication_Value = Guid.initString("4f4d070b-a275-49fb-b10d-8ec26387b50d");
pub const IID_IRendezvousApplication = &IID_IRendezvousApplication_Value;
pub const IRendezvousApplication = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetRendezvousSession: fn(
self: *const IRendezvousApplication,
pRendezvousSession: ?*IUnknown,
) 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 IRendezvousApplication_SetRendezvousSession(self: *const T, pRendezvousSession: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IRendezvousApplication.VTable, self.vtable).SetRendezvousSession(@ptrCast(*const IRendezvousApplication, self), pRendezvousSession);
}
};}
pub usingnamespace MethodMixin(@This());
};
//--------------------------------------------------------------------------------
// Section: Functions (0)
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (0)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../zig.zig").unicode_mode) {
.ansi => struct {
},
.wide => struct {
},
.unspecified => if (@import("builtin").is_test) struct {
} else struct {
},
};
//--------------------------------------------------------------------------------
// Section: Imports (5)
//--------------------------------------------------------------------------------
const Guid = @import("../zig.zig").Guid;
const BSTR = @import("../foundation.zig").BSTR;
const HRESULT = @import("../foundation.zig").HRESULT;
const IDispatch = @import("../system/com.zig").IDispatch;
const IUnknown = @import("../system/com.zig").IUnknown;
test {
@setEvalBranchQuota(
@import("std").meta.declarations(@This()).len * 3
);
// reference all the pub declarations
if (!@import("builtin").is_test) return;
inline for (@import("std").meta.declarations(@This())) |decl| {
if (decl.is_pub) {
_ = decl;
}
}
} | win32/system/remote_assistance.zig |
pub const WIA_DIP_DEV_ID = @as(u32, 2);
pub const WIA_DIP_VEND_DESC = @as(u32, 3);
pub const WIA_DIP_DEV_DESC = @as(u32, 4);
pub const WIA_DIP_DEV_TYPE = @as(u32, 5);
pub const WIA_DIP_PORT_NAME = @as(u32, 6);
pub const WIA_DIP_DEV_NAME = @as(u32, 7);
pub const WIA_DIP_SERVER_NAME = @as(u32, 8);
pub const WIA_DIP_REMOTE_DEV_ID = @as(u32, 9);
pub const WIA_DIP_UI_CLSID = @as(u32, 10);
pub const WIA_DIP_HW_CONFIG = @as(u32, 11);
pub const WIA_DIP_BAUDRATE = @as(u32, 12);
pub const WIA_DIP_STI_GEN_CAPABILITIES = @as(u32, 13);
pub const WIA_DIP_WIA_VERSION = @as(u32, 14);
pub const WIA_DIP_DRIVER_VERSION = @as(u32, 15);
pub const WIA_DIP_PNP_ID = @as(u32, 16);
pub const WIA_DIP_STI_DRIVER_VERSION = @as(u32, 17);
pub const WIA_DPA_FIRMWARE_VERSION = @as(u32, 1026);
pub const WIA_DPA_CONNECT_STATUS = @as(u32, 1027);
pub const WIA_DPA_DEVICE_TIME = @as(u32, 1028);
pub const WIA_DPC_PICTURES_TAKEN = @as(u32, 2050);
pub const WIA_DPC_PICTURES_REMAINING = @as(u32, 2051);
pub const WIA_DPC_EXPOSURE_MODE = @as(u32, 2052);
pub const WIA_DPC_EXPOSURE_COMP = @as(u32, 2053);
pub const WIA_DPC_EXPOSURE_TIME = @as(u32, 2054);
pub const WIA_DPC_FNUMBER = @as(u32, 2055);
pub const WIA_DPC_FLASH_MODE = @as(u32, 2056);
pub const WIA_DPC_FOCUS_MODE = @as(u32, 2057);
pub const WIA_DPC_FOCUS_MANUAL_DIST = @as(u32, 2058);
pub const WIA_DPC_ZOOM_POSITION = @as(u32, 2059);
pub const WIA_DPC_PAN_POSITION = @as(u32, 2060);
pub const WIA_DPC_TILT_POSITION = @as(u32, 2061);
pub const WIA_DPC_TIMER_MODE = @as(u32, 2062);
pub const WIA_DPC_TIMER_VALUE = @as(u32, 2063);
pub const WIA_DPC_POWER_MODE = @as(u32, 2064);
pub const WIA_DPC_BATTERY_STATUS = @as(u32, 2065);
pub const WIA_DPC_THUMB_WIDTH = @as(u32, 2066);
pub const WIA_DPC_THUMB_HEIGHT = @as(u32, 2067);
pub const WIA_DPC_PICT_WIDTH = @as(u32, 2068);
pub const WIA_DPC_PICT_HEIGHT = @as(u32, 2069);
pub const WIA_DPC_DIMENSION = @as(u32, 2070);
pub const WIA_DPC_COMPRESSION_SETTING = @as(u32, 2071);
pub const WIA_DPC_FOCUS_METERING = @as(u32, 2072);
pub const WIA_DPC_TIMELAPSE_INTERVAL = @as(u32, 2073);
pub const WIA_DPC_TIMELAPSE_NUMBER = @as(u32, 2074);
pub const WIA_DPC_BURST_INTERVAL = @as(u32, 2075);
pub const WIA_DPC_BURST_NUMBER = @as(u32, 2076);
pub const WIA_DPC_EFFECT_MODE = @as(u32, 2077);
pub const WIA_DPC_DIGITAL_ZOOM = @as(u32, 2078);
pub const WIA_DPC_SHARPNESS = @as(u32, 2079);
pub const WIA_DPC_CONTRAST = @as(u32, 2080);
pub const WIA_DPC_CAPTURE_MODE = @as(u32, 2081);
pub const WIA_DPC_CAPTURE_DELAY = @as(u32, 2082);
pub const WIA_DPC_EXPOSURE_INDEX = @as(u32, 2083);
pub const WIA_DPC_EXPOSURE_METERING_MODE = @as(u32, 2084);
pub const WIA_DPC_FOCUS_METERING_MODE = @as(u32, 2085);
pub const WIA_DPC_FOCUS_DISTANCE = @as(u32, 2086);
pub const WIA_DPC_FOCAL_LENGTH = @as(u32, 2087);
pub const WIA_DPC_RGB_GAIN = @as(u32, 2088);
pub const WIA_DPC_WHITE_BALANCE = @as(u32, 2089);
pub const WIA_DPC_UPLOAD_URL = @as(u32, 2090);
pub const WIA_DPC_ARTIST = @as(u32, 2091);
pub const WIA_DPC_COPYRIGHT_INFO = @as(u32, 2092);
pub const WIA_DPS_HORIZONTAL_BED_SIZE = @as(u32, 3074);
pub const WIA_DPS_VERTICAL_BED_SIZE = @as(u32, 3075);
pub const WIA_DPS_HORIZONTAL_SHEET_FEED_SIZE = @as(u32, 3076);
pub const WIA_DPS_VERTICAL_SHEET_FEED_SIZE = @as(u32, 3077);
pub const WIA_DPS_SHEET_FEEDER_REGISTRATION = @as(u32, 3078);
pub const WIA_DPS_HORIZONTAL_BED_REGISTRATION = @as(u32, 3079);
pub const WIA_DPS_VERTICAL_BED_REGISTRATION = @as(u32, 3080);
pub const WIA_DPS_PLATEN_COLOR = @as(u32, 3081);
pub const WIA_DPS_PAD_COLOR = @as(u32, 3082);
pub const WIA_DPS_FILTER_SELECT = @as(u32, 3083);
pub const WIA_DPS_DITHER_SELECT = @as(u32, 3084);
pub const WIA_DPS_DITHER_PATTERN_DATA = @as(u32, 3085);
pub const WIA_DPS_DOCUMENT_HANDLING_CAPABILITIES = @as(u32, 3086);
pub const WIA_DPS_DOCUMENT_HANDLING_STATUS = @as(u32, 3087);
pub const WIA_DPS_DOCUMENT_HANDLING_SELECT = @as(u32, 3088);
pub const WIA_DPS_DOCUMENT_HANDLING_CAPACITY = @as(u32, 3089);
pub const WIA_DPS_OPTICAL_XRES = @as(u32, 3090);
pub const WIA_DPS_OPTICAL_YRES = @as(u32, 3091);
pub const WIA_DPS_ENDORSER_CHARACTERS = @as(u32, 3092);
pub const WIA_DPS_ENDORSER_STRING = @as(u32, 3093);
pub const WIA_DPS_SCAN_AHEAD_PAGES = @as(u32, 3094);
pub const WIA_DPS_MAX_SCAN_TIME = @as(u32, 3095);
pub const WIA_DPS_PAGES = @as(u32, 3096);
pub const WIA_DPS_PAGE_SIZE = @as(u32, 3097);
pub const WIA_DPS_PAGE_WIDTH = @as(u32, 3098);
pub const WIA_DPS_PAGE_HEIGHT = @as(u32, 3099);
pub const WIA_DPS_PREVIEW = @as(u32, 3100);
pub const WIA_DPS_TRANSPARENCY = @as(u32, 3101);
pub const WIA_DPS_TRANSPARENCY_SELECT = @as(u32, 3102);
pub const WIA_DPS_SHOW_PREVIEW_CONTROL = @as(u32, 3103);
pub const WIA_DPS_MIN_HORIZONTAL_SHEET_FEED_SIZE = @as(u32, 3104);
pub const WIA_DPS_MIN_VERTICAL_SHEET_FEED_SIZE = @as(u32, 3105);
pub const WIA_DPS_TRANSPARENCY_CAPABILITIES = @as(u32, 3106);
pub const WIA_DPS_TRANSPARENCY_STATUS = @as(u32, 3107);
pub const WIA_DPF_MOUNT_POINT = @as(u32, 3330);
pub const WIA_DPV_LAST_PICTURE_TAKEN = @as(u32, 3586);
pub const WIA_DPV_IMAGES_DIRECTORY = @as(u32, 3587);
pub const WIA_DPV_DSHOW_DEVICE_PATH = @as(u32, 3588);
pub const WIA_IPA_ITEM_NAME = @as(u32, 4098);
pub const WIA_IPA_FULL_ITEM_NAME = @as(u32, 4099);
pub const WIA_IPA_ITEM_TIME = @as(u32, 4100);
pub const WIA_IPA_ITEM_FLAGS = @as(u32, 4101);
pub const WIA_IPA_ACCESS_RIGHTS = @as(u32, 4102);
pub const WIA_IPA_DATATYPE = @as(u32, 4103);
pub const WIA_IPA_DEPTH = @as(u32, 4104);
pub const WIA_IPA_PREFERRED_FORMAT = @as(u32, 4105);
pub const WIA_IPA_FORMAT = @as(u32, 4106);
pub const WIA_IPA_COMPRESSION = @as(u32, 4107);
pub const WIA_IPA_TYMED = @as(u32, 4108);
pub const WIA_IPA_CHANNELS_PER_PIXEL = @as(u32, 4109);
pub const WIA_IPA_BITS_PER_CHANNEL = @as(u32, 4110);
pub const WIA_IPA_PLANAR = @as(u32, 4111);
pub const WIA_IPA_PIXELS_PER_LINE = @as(u32, 4112);
pub const WIA_IPA_BYTES_PER_LINE = @as(u32, 4113);
pub const WIA_IPA_NUMBER_OF_LINES = @as(u32, 4114);
pub const WIA_IPA_GAMMA_CURVES = @as(u32, 4115);
pub const WIA_IPA_ITEM_SIZE = @as(u32, 4116);
pub const WIA_IPA_COLOR_PROFILE = @as(u32, 4117);
pub const WIA_IPA_MIN_BUFFER_SIZE = @as(u32, 4118);
pub const WIA_IPA_BUFFER_SIZE = @as(u32, 4118);
pub const WIA_IPA_REGION_TYPE = @as(u32, 4119);
pub const WIA_IPA_ICM_PROFILE_NAME = @as(u32, 4120);
pub const WIA_IPA_APP_COLOR_MAPPING = @as(u32, 4121);
pub const WIA_IPA_PROP_STREAM_COMPAT_ID = @as(u32, 4122);
pub const WIA_IPA_FILENAME_EXTENSION = @as(u32, 4123);
pub const WIA_IPA_SUPPRESS_PROPERTY_PAGE = @as(u32, 4124);
pub const WIA_IPC_THUMBNAIL = @as(u32, 5122);
pub const WIA_IPC_THUMB_WIDTH = @as(u32, 5123);
pub const WIA_IPC_THUMB_HEIGHT = @as(u32, 5124);
pub const WIA_IPC_AUDIO_AVAILABLE = @as(u32, 5125);
pub const WIA_IPC_AUDIO_DATA_FORMAT = @as(u32, 5126);
pub const WIA_IPC_AUDIO_DATA = @as(u32, 5127);
pub const WIA_IPC_NUM_PICT_PER_ROW = @as(u32, 5128);
pub const WIA_IPC_SEQUENCE = @as(u32, 5129);
pub const WIA_IPC_TIMEDELAY = @as(u32, 5130);
pub const WIA_IPS_CUR_INTENT = @as(u32, 6146);
pub const WIA_IPS_XRES = @as(u32, 6147);
pub const WIA_IPS_YRES = @as(u32, 6148);
pub const WIA_IPS_XPOS = @as(u32, 6149);
pub const WIA_IPS_YPOS = @as(u32, 6150);
pub const WIA_IPS_XEXTENT = @as(u32, 6151);
pub const WIA_IPS_YEXTENT = @as(u32, 6152);
pub const WIA_IPS_PHOTOMETRIC_INTERP = @as(u32, 6153);
pub const WIA_IPS_BRIGHTNESS = @as(u32, 6154);
pub const WIA_IPS_CONTRAST = @as(u32, 6155);
pub const WIA_IPS_ORIENTATION = @as(u32, 6156);
pub const WIA_IPS_ROTATION = @as(u32, 6157);
pub const WIA_IPS_MIRROR = @as(u32, 6158);
pub const WIA_IPS_THRESHOLD = @as(u32, 6159);
pub const WIA_IPS_INVERT = @as(u32, 6160);
pub const WIA_IPS_WARM_UP_TIME = @as(u32, 6161);
pub const WIA_DPS_USER_NAME = @as(u32, 3112);
pub const WIA_DPS_SERVICE_ID = @as(u32, 3113);
pub const WIA_DPS_DEVICE_ID = @as(u32, 3114);
pub const WIA_DPS_GLOBAL_IDENTITY = @as(u32, 3115);
pub const WIA_DPS_SCAN_AVAILABLE_ITEM = @as(u32, 3116);
pub const WIA_IPS_DESKEW_X = @as(u32, 6162);
pub const WIA_IPS_DESKEW_Y = @as(u32, 6163);
pub const WIA_IPS_SEGMENTATION = @as(u32, 6164);
pub const WIA_IPS_MAX_HORIZONTAL_SIZE = @as(u32, 6165);
pub const WIA_IPS_MAX_VERTICAL_SIZE = @as(u32, 6166);
pub const WIA_IPS_MIN_HORIZONTAL_SIZE = @as(u32, 6167);
pub const WIA_IPS_MIN_VERTICAL_SIZE = @as(u32, 6168);
pub const WIA_IPS_TRANSFER_CAPABILITIES = @as(u32, 6169);
pub const WIA_IPS_SHEET_FEEDER_REGISTRATION = @as(u32, 3078);
pub const WIA_IPS_DOCUMENT_HANDLING_SELECT = @as(u32, 3088);
pub const WIA_IPS_OPTICAL_XRES = @as(u32, 3090);
pub const WIA_IPS_OPTICAL_YRES = @as(u32, 3091);
pub const WIA_IPS_PAGES = @as(u32, 3096);
pub const WIA_IPS_PAGE_SIZE = @as(u32, 3097);
pub const WIA_IPS_PAGE_WIDTH = @as(u32, 3098);
pub const WIA_IPS_PAGE_HEIGHT = @as(u32, 3099);
pub const WIA_IPS_PREVIEW = @as(u32, 3100);
pub const WIA_IPS_SHOW_PREVIEW_CONTROL = @as(u32, 3103);
pub const WIA_IPS_FILM_SCAN_MODE = @as(u32, 3104);
pub const WIA_IPS_LAMP = @as(u32, 3105);
pub const WIA_IPS_LAMP_AUTO_OFF = @as(u32, 3106);
pub const WIA_IPS_AUTO_DESKEW = @as(u32, 3107);
pub const WIA_IPS_SUPPORTS_CHILD_ITEM_CREATION = @as(u32, 3108);
pub const WIA_IPS_XSCALING = @as(u32, 3109);
pub const WIA_IPS_YSCALING = @as(u32, 3110);
pub const WIA_IPS_PREVIEW_TYPE = @as(u32, 3111);
pub const WIA_IPA_ITEM_CATEGORY = @as(u32, 4125);
pub const WIA_IPA_UPLOAD_ITEM_SIZE = @as(u32, 4126);
pub const WIA_IPA_ITEMS_STORED = @as(u32, 4127);
pub const WIA_IPA_RAW_BITS_PER_CHANNEL = @as(u32, 4128);
pub const WIA_IPS_FILM_NODE_NAME = @as(u32, 4129);
pub const WIA_IPS_PRINTER_ENDORSER = @as(u32, 4130);
pub const WIA_IPS_PRINTER_ENDORSER_ORDER = @as(u32, 4131);
pub const WIA_IPS_PRINTER_ENDORSER_COUNTER = @as(u32, 4132);
pub const WIA_IPS_PRINTER_ENDORSER_STEP = @as(u32, 4133);
pub const WIA_IPS_PRINTER_ENDORSER_XOFFSET = @as(u32, 4134);
pub const WIA_IPS_PRINTER_ENDORSER_YOFFSET = @as(u32, 4135);
pub const WIA_IPS_PRINTER_ENDORSER_NUM_LINES = @as(u32, 4136);
pub const WIA_IPS_PRINTER_ENDORSER_STRING = @as(u32, 4137);
pub const WIA_IPS_PRINTER_ENDORSER_VALID_CHARACTERS = @as(u32, 4138);
pub const WIA_IPS_PRINTER_ENDORSER_VALID_FORMAT_SPECIFIERS = @as(u32, 4139);
pub const WIA_IPS_PRINTER_ENDORSER_TEXT_UPLOAD = @as(u32, 4140);
pub const WIA_IPS_PRINTER_ENDORSER_TEXT_DOWNLOAD = @as(u32, 4141);
pub const WIA_IPS_PRINTER_ENDORSER_GRAPHICS = @as(u32, 4142);
pub const WIA_IPS_PRINTER_ENDORSER_GRAPHICS_POSITION = @as(u32, 4143);
pub const WIA_IPS_PRINTER_ENDORSER_GRAPHICS_MIN_WIDTH = @as(u32, 4144);
pub const WIA_IPS_PRINTER_ENDORSER_GRAPHICS_MAX_WIDTH = @as(u32, 4145);
pub const WIA_IPS_PRINTER_ENDORSER_GRAPHICS_MIN_HEIGHT = @as(u32, 4146);
pub const WIA_IPS_PRINTER_ENDORSER_GRAPHICS_MAX_HEIGHT = @as(u32, 4147);
pub const WIA_IPS_PRINTER_ENDORSER_GRAPHICS_UPLOAD = @as(u32, 4148);
pub const WIA_IPS_PRINTER_ENDORSER_GRAPHICS_DOWNLOAD = @as(u32, 4149);
pub const WIA_IPS_BARCODE_READER = @as(u32, 4150);
pub const WIA_IPS_MAXIMUM_BARCODES_PER_PAGE = @as(u32, 4151);
pub const WIA_IPS_BARCODE_SEARCH_DIRECTION = @as(u32, 4152);
pub const WIA_IPS_MAXIMUM_BARCODE_SEARCH_RETRIES = @as(u32, 4153);
pub const WIA_IPS_BARCODE_SEARCH_TIMEOUT = @as(u32, 4154);
pub const WIA_IPS_SUPPORTED_BARCODE_TYPES = @as(u32, 4155);
pub const WIA_IPS_ENABLED_BARCODE_TYPES = @as(u32, 4156);
pub const WIA_IPS_PATCH_CODE_READER = @as(u32, 4157);
pub const WIA_IPS_SUPPORTED_PATCH_CODE_TYPES = @as(u32, 4162);
pub const WIA_IPS_ENABLED_PATCH_CODE_TYPES = @as(u32, 4163);
pub const WIA_IPS_MICR_READER = @as(u32, 4164);
pub const WIA_IPS_JOB_SEPARATORS = @as(u32, 4165);
pub const WIA_IPS_LONG_DOCUMENT = @as(u32, 4166);
pub const WIA_IPS_BLANK_PAGES = @as(u32, 4167);
pub const WIA_IPS_MULTI_FEED = @as(u32, 4168);
pub const WIA_IPS_MULTI_FEED_SENSITIVITY = @as(u32, 4169);
pub const WIA_IPS_AUTO_CROP = @as(u32, 4170);
pub const WIA_IPS_OVER_SCAN = @as(u32, 4171);
pub const WIA_IPS_OVER_SCAN_LEFT = @as(u32, 4172);
pub const WIA_IPS_OVER_SCAN_RIGHT = @as(u32, 4173);
pub const WIA_IPS_OVER_SCAN_TOP = @as(u32, 4174);
pub const WIA_IPS_OVER_SCAN_BOTTOM = @as(u32, 4175);
pub const WIA_IPS_COLOR_DROP = @as(u32, 4176);
pub const WIA_IPS_COLOR_DROP_RED = @as(u32, 4177);
pub const WIA_IPS_COLOR_DROP_GREEN = @as(u32, 4178);
pub const WIA_IPS_COLOR_DROP_BLUE = @as(u32, 4179);
pub const WIA_IPS_SCAN_AHEAD = @as(u32, 4180);
pub const WIA_IPS_SCAN_AHEAD_CAPACITY = @as(u32, 4181);
pub const WIA_IPS_FEEDER_CONTROL = @as(u32, 4182);
pub const WIA_IPS_PRINTER_ENDORSER_PADDING = @as(u32, 4183);
pub const WIA_IPS_PRINTER_ENDORSER_FONT_TYPE = @as(u32, 4184);
pub const WIA_IPS_ALARM = @as(u32, 4185);
pub const WIA_IPS_PRINTER_ENDORSER_INK = @as(u32, 4186);
pub const WIA_IPS_PRINTER_ENDORSER_CHARACTER_ROTATION = @as(u32, 4187);
pub const WIA_IPS_PRINTER_ENDORSER_MAX_CHARACTERS = @as(u32, 4188);
pub const WIA_IPS_PRINTER_ENDORSER_MAX_GRAPHICS = @as(u32, 4189);
pub const WIA_IPS_PRINTER_ENDORSER_COUNTER_DIGITS = @as(u32, 4190);
pub const WIA_IPS_COLOR_DROP_MULTI = @as(u32, 4191);
pub const WIA_IPS_BLANK_PAGES_SENSITIVITY = @as(u32, 4192);
pub const WIA_IPS_MULTI_FEED_DETECT_METHOD = @as(u32, 4193);
pub const WIA_CATEGORY_FINISHED_FILE = Guid.initString("ff2b77ca-cf84-432b-a735-3a130dde2a88");
pub const WIA_CATEGORY_FLATBED = Guid.initString("fb607b1f-43f3-488b-855b-fb703ec342a6");
pub const WIA_CATEGORY_FEEDER = Guid.initString("fe131934-f84c-42ad-8da4-6129cddd7288");
pub const WIA_CATEGORY_FILM = Guid.initString("fcf65be7-3ce3-4473-af85-f5d37d21b68a");
pub const WIA_CATEGORY_ROOT = Guid.initString("f193526f-59b8-4a26-9888-e16e4f97ce10");
pub const WIA_CATEGORY_FOLDER = Guid.initString("c692a446-6f5a-481d-85bb-92e2e86fd30a");
pub const WIA_CATEGORY_FEEDER_FRONT = Guid.initString("4823175c-3b28-487b-a7e6-eebc17614fd1");
pub const WIA_CATEGORY_FEEDER_BACK = Guid.initString("61ca74d4-39db-42aa-89b1-8c19c9cd4c23");
pub const WIA_CATEGORY_AUTO = Guid.initString("defe5fd8-6c97-4dde-b11e-cb509b270e11");
pub const WIA_CATEGORY_IMPRINTER = Guid.initString("fc65016d-9202-43dd-91a7-64c2954cfb8b");
pub const WIA_CATEGORY_ENDORSER = Guid.initString("47102cc3-127f-4771-adfc-991ab8ee1e97");
pub const WIA_CATEGORY_BARCODE_READER = Guid.initString("36e178a0-473f-494b-af8f-6c3f6d7486fc");
pub const WIA_CATEGORY_PATCH_CODE_READER = Guid.initString("8faa1a6d-9c8a-42cd-98b3-ee9700cbc74f");
pub const WIA_CATEGORY_MICR_READER = Guid.initString("3b86c1ec-71bc-4645-b4d5-1b19da2be978");
pub const CLSID_WiaDefaultSegFilter = Guid.initString("d4f4d30b-0b29-4508-8922-0c5797d42765");
pub const WIA_TRANSFER_CHILDREN_SINGLE_SCAN = @as(u32, 1);
pub const WIA_USE_SEGMENTATION_FILTER = @as(u32, 0);
pub const WIA_DONT_USE_SEGMENTATION_FILTER = @as(u32, 1);
pub const WIA_FILM_COLOR_SLIDE = @as(u32, 0);
pub const WIA_FILM_COLOR_NEGATIVE = @as(u32, 1);
pub const WIA_FILM_BW_NEGATIVE = @as(u32, 2);
pub const WIA_LAMP_ON = @as(u32, 0);
pub const WIA_LAMP_OFF = @as(u32, 1);
pub const WIA_AUTO_DESKEW_ON = @as(u32, 0);
pub const WIA_AUTO_DESKEW_OFF = @as(u32, 1);
pub const WIA_ADVANCED_PREVIEW = @as(u32, 0);
pub const WIA_BASIC_PREVIEW = @as(u32, 1);
pub const WIA_PRINTER_ENDORSER_DISABLED = @as(u32, 0);
pub const WIA_PRINTER_ENDORSER_AUTO = @as(u32, 1);
pub const WIA_PRINTER_ENDORSER_FLATBED = @as(u32, 2);
pub const WIA_PRINTER_ENDORSER_FEEDER_FRONT = @as(u32, 3);
pub const WIA_PRINTER_ENDORSER_FEEDER_BACK = @as(u32, 4);
pub const WIA_PRINTER_ENDORSER_FEEDER_DUPLEX = @as(u32, 5);
pub const WIA_PRINTER_ENDORSER_DIGITAL = @as(u32, 6);
pub const WIA_PRINTER_ENDORSER_BEFORE_SCAN = @as(u32, 0);
pub const WIA_PRINTER_ENDORSER_AFTER_SCAN = @as(u32, 1);
pub const WIA_PRINT_DATE = @as(u32, 0);
pub const WIA_PRINT_YEAR = @as(u32, 1);
pub const WIA_PRINT_MONTH = @as(u32, 2);
pub const WIA_PRINT_DAY = @as(u32, 3);
pub const WIA_PRINT_WEEK_DAY = @as(u32, 4);
pub const WIA_PRINT_TIME_24H = @as(u32, 5);
pub const WIA_PRINT_TIME_12H = @as(u32, 6);
pub const WIA_PRINT_HOUR_24H = @as(u32, 7);
pub const WIA_PRINT_HOUR_12H = @as(u32, 8);
pub const WIA_PRINT_AM_PM = @as(u32, 9);
pub const WIA_PRINT_MINUTE = @as(u32, 10);
pub const WIA_PRINT_SECOND = @as(u32, 11);
pub const WIA_PRINT_PAGE_COUNT = @as(u32, 12);
pub const WIA_PRINT_IMAGE = @as(u32, 13);
pub const WIA_PRINT_MILLISECOND = @as(u32, 14);
pub const WIA_PRINT_MONTH_NAME = @as(u32, 15);
pub const WIA_PRINT_MONTH_SHORT = @as(u32, 16);
pub const WIA_PRINT_WEEK_DAY_SHORT = @as(u32, 17);
pub const WIA_PRINTER_ENDORSER_GRAPHICS_LEFT = @as(u32, 0);
pub const WIA_PRINTER_ENDORSER_GRAPHICS_RIGHT = @as(u32, 1);
pub const WIA_PRINTER_ENDORSER_GRAPHICS_TOP = @as(u32, 2);
pub const WIA_PRINTER_ENDORSER_GRAPHICS_BOTTOM = @as(u32, 3);
pub const WIA_PRINTER_ENDORSER_GRAPHICS_TOP_LEFT = @as(u32, 4);
pub const WIA_PRINTER_ENDORSER_GRAPHICS_TOP_RIGHT = @as(u32, 5);
pub const WIA_PRINTER_ENDORSER_GRAPHICS_BOTTOM_LEFT = @as(u32, 6);
pub const WIA_PRINTER_ENDORSER_GRAPHICS_BOTTOM_RIGHT = @as(u32, 7);
pub const WIA_PRINTER_ENDORSER_GRAPHICS_BACKGROUND = @as(u32, 8);
pub const WIA_PRINTER_ENDORSER_GRAPHICS_DEVICE_DEFAULT = @as(u32, 9);
pub const WIA_BARCODE_READER_DISABLED = @as(u32, 0);
pub const WIA_BARCODE_READER_AUTO = @as(u32, 1);
pub const WIA_BARCODE_READER_FLATBED = @as(u32, 2);
pub const WIA_BARCODE_READER_FEEDER_FRONT = @as(u32, 3);
pub const WIA_BARCODE_READER_FEEDER_BACK = @as(u32, 4);
pub const WIA_BARCODE_READER_FEEDER_DUPLEX = @as(u32, 5);
pub const WIA_BARCODE_HORIZONTAL_SEARCH = @as(u32, 0);
pub const WIA_BARCODE_VERTICAL_SEARCH = @as(u32, 1);
pub const WIA_BARCODE_HORIZONTAL_VERTICAL_SEARCH = @as(u32, 2);
pub const WIA_BARCODE_VERTICAL_HORIZONTAL_SEARCH = @as(u32, 3);
pub const WIA_BARCODE_AUTO_SEARCH = @as(u32, 4);
pub const WIA_BARCODE_UPCA = @as(u32, 0);
pub const WIA_BARCODE_UPCE = @as(u32, 1);
pub const WIA_BARCODE_CODABAR = @as(u32, 2);
pub const WIA_BARCODE_NONINTERLEAVED_2OF5 = @as(u32, 3);
pub const WIA_BARCODE_INTERLEAVED_2OF5 = @as(u32, 4);
pub const WIA_BARCODE_CODE39 = @as(u32, 5);
pub const WIA_BARCODE_CODE39_MOD43 = @as(u32, 6);
pub const WIA_BARCODE_CODE39_FULLASCII = @as(u32, 7);
pub const WIA_BARCODE_CODE93 = @as(u32, 8);
pub const WIA_BARCODE_CODE128 = @as(u32, 9);
pub const WIA_BARCODE_CODE128A = @as(u32, 10);
pub const WIA_BARCODE_CODE128B = @as(u32, 11);
pub const WIA_BARCODE_CODE128C = @as(u32, 12);
pub const WIA_BARCODE_GS1128 = @as(u32, 13);
pub const WIA_BARCODE_GS1DATABAR = @as(u32, 14);
pub const WIA_BARCODE_ITF14 = @as(u32, 15);
pub const WIA_BARCODE_EAN8 = @as(u32, 16);
pub const WIA_BARCODE_EAN13 = @as(u32, 17);
pub const WIA_BARCODE_POSTNETA = @as(u32, 18);
pub const WIA_BARCODE_POSTNETB = @as(u32, 19);
pub const WIA_BARCODE_POSTNETC = @as(u32, 20);
pub const WIA_BARCODE_POSTNET_DPBC = @as(u32, 21);
pub const WIA_BARCODE_PLANET = @as(u32, 22);
pub const WIA_BARCODE_INTELLIGENT_MAIL = @as(u32, 23);
pub const WIA_BARCODE_POSTBAR = @as(u32, 24);
pub const WIA_BARCODE_RM4SCC = @as(u32, 25);
pub const WIA_BARCODE_HIGH_CAPACITY_COLOR = @as(u32, 26);
pub const WIA_BARCODE_MAXICODE = @as(u32, 27);
pub const WIA_BARCODE_PDF417 = @as(u32, 28);
pub const WIA_BARCODE_CPCBINARY = @as(u32, 29);
pub const WIA_BARCODE_FIM = @as(u32, 30);
pub const WIA_BARCODE_PHARMACODE = @as(u32, 31);
pub const WIA_BARCODE_PLESSEY = @as(u32, 32);
pub const WIA_BARCODE_MSI = @as(u32, 33);
pub const WIA_BARCODE_JAN = @as(u32, 34);
pub const WIA_BARCODE_TELEPEN = @as(u32, 35);
pub const WIA_BARCODE_AZTEC = @as(u32, 36);
pub const WIA_BARCODE_SMALLAZTEC = @as(u32, 37);
pub const WIA_BARCODE_DATAMATRIX = @as(u32, 38);
pub const WIA_BARCODE_DATASTRIP = @as(u32, 39);
pub const WIA_BARCODE_EZCODE = @as(u32, 40);
pub const WIA_BARCODE_QRCODE = @as(u32, 41);
pub const WIA_BARCODE_SHOTCODE = @as(u32, 42);
pub const WIA_BARCODE_SPARQCODE = @as(u32, 43);
pub const WIA_BARCODE_CUSTOMBASE = @as(u32, 32768);
pub const WIA_PATCH_CODE_READER_DISABLED = @as(u32, 0);
pub const WIA_PATCH_CODE_READER_AUTO = @as(u32, 1);
pub const WIA_PATCH_CODE_READER_FLATBED = @as(u32, 2);
pub const WIA_PATCH_CODE_READER_FEEDER_FRONT = @as(u32, 3);
pub const WIA_PATCH_CODE_READER_FEEDER_BACK = @as(u32, 4);
pub const WIA_PATCH_CODE_READER_FEEDER_DUPLEX = @as(u32, 5);
pub const WIA_PATCH_CODE_UNKNOWN = @as(u32, 0);
pub const WIA_PATCH_CODE_1 = @as(u32, 1);
pub const WIA_PATCH_CODE_2 = @as(u32, 2);
pub const WIA_PATCH_CODE_3 = @as(u32, 3);
pub const WIA_PATCH_CODE_4 = @as(u32, 4);
pub const WIA_PATCH_CODE_T = @as(u32, 5);
pub const WIA_PATCH_CODE_6 = @as(u32, 6);
pub const WIA_PATCH_CODE_7 = @as(u32, 7);
pub const WIA_PATCH_CODE_8 = @as(u32, 8);
pub const WIA_PATCH_CODE_9 = @as(u32, 9);
pub const WIA_PATCH_CODE_10 = @as(u32, 10);
pub const WIA_PATCH_CODE_11 = @as(u32, 11);
pub const WIA_PATCH_CODE_12 = @as(u32, 12);
pub const WIA_PATCH_CODE_13 = @as(u32, 13);
pub const WIA_PATCH_CODE_14 = @as(u32, 14);
pub const WIA_PATCH_CODE_CUSTOM_BASE = @as(u32, 32768);
pub const WIA_MICR_READER_DISABLED = @as(u32, 0);
pub const WIA_MICR_READER_AUTO = @as(u32, 1);
pub const WIA_MICR_READER_FLATBED = @as(u32, 2);
pub const WIA_MICR_READER_FEEDER_FRONT = @as(u32, 3);
pub const WIA_MICR_READER_FEEDER_BACK = @as(u32, 4);
pub const WIA_MICR_READER_FEEDER_DUPLEX = @as(u32, 5);
pub const WIA_SEPARATOR_DISABLED = @as(u32, 0);
pub const WIA_SEPARATOR_DETECT_SCAN_CONTINUE = @as(u32, 1);
pub const WIA_SEPARATOR_DETECT_SCAN_STOP = @as(u32, 2);
pub const WIA_SEPARATOR_DETECT_NOSCAN_CONTINUE = @as(u32, 3);
pub const WIA_SEPARATOR_DETECT_NOSCAN_STOP = @as(u32, 4);
pub const WIA_LONG_DOCUMENT_DISABLED = @as(u32, 0);
pub const WIA_LONG_DOCUMENT_ENABLED = @as(u32, 1);
pub const WIA_LONG_DOCUMENT_SPLIT = @as(u32, 2);
pub const WIA_BLANK_PAGE_DETECTION_DISABLED = @as(u32, 0);
pub const WIA_BLANK_PAGE_DISCARD = @as(u32, 1);
pub const WIA_BLANK_PAGE_JOB_SEPARATOR = @as(u32, 2);
pub const WIA_MULTI_FEED_DETECT_DISABLED = @as(u32, 0);
pub const WIA_MULTI_FEED_DETECT_STOP_ERROR = @as(u32, 1);
pub const WIA_MULTI_FEED_DETECT_STOP_SUCCESS = @as(u32, 2);
pub const WIA_MULTI_FEED_DETECT_CONTINUE = @as(u32, 3);
pub const WIA_MULTI_FEED_DETECT_METHOD_LENGTH = @as(u32, 0);
pub const WIA_MULTI_FEED_DETECT_METHOD_OVERLAP = @as(u32, 1);
pub const WIA_AUTO_CROP_DISABLED = @as(u32, 0);
pub const WIA_AUTO_CROP_SINGLE = @as(u32, 1);
pub const WIA_AUTO_CROP_MULTI = @as(u32, 2);
pub const WIA_OVER_SCAN_DISABLED = @as(u32, 0);
pub const WIA_OVER_SCAN_TOP_BOTTOM = @as(u32, 1);
pub const WIA_OVER_SCAN_LEFT_RIGHT = @as(u32, 2);
pub const WIA_OVER_SCAN_ALL = @as(u32, 3);
pub const WIA_COLOR_DROP_DISABLED = @as(u32, 0);
pub const WIA_COLOR_DROP_RED = @as(u32, 1);
pub const WIA_COLOR_DROP_GREEN = @as(u32, 2);
pub const WIA_COLOR_DROP_BLUE = @as(u32, 3);
pub const WIA_COLOR_DROP_RGB = @as(u32, 4);
pub const WIA_SCAN_AHEAD_DISABLED = @as(u32, 0);
pub const WIA_SCAN_AHEAD_ENABLED = @as(u32, 1);
pub const WIA_FEEDER_CONTROL_AUTO = @as(u32, 0);
pub const WIA_FEEDER_CONTROL_MANUAL = @as(u32, 1);
pub const WIA_PRINT_PADDING_NONE = @as(u32, 0);
pub const WIA_PRINT_PADDING_ZERO = @as(u32, 1);
pub const WIA_PRINT_PADDING_BLANK = @as(u32, 2);
pub const WIA_PRINT_FONT_NORMAL = @as(u32, 0);
pub const WIA_PRINT_FONT_BOLD = @as(u32, 1);
pub const WIA_PRINT_FONT_EXTRA_BOLD = @as(u32, 2);
pub const WIA_PRINT_FONT_ITALIC_BOLD = @as(u32, 3);
pub const WIA_PRINT_FONT_ITALIC_EXTRA_BOLD = @as(u32, 4);
pub const WIA_PRINT_FONT_ITALIC = @as(u32, 5);
pub const WIA_PRINT_FONT_SMALL = @as(u32, 6);
pub const WIA_PRINT_FONT_SMALL_BOLD = @as(u32, 7);
pub const WIA_PRINT_FONT_SMALL_EXTRA_BOLD = @as(u32, 8);
pub const WIA_PRINT_FONT_SMALL_ITALIC_BOLD = @as(u32, 9);
pub const WIA_PRINT_FONT_SMALL_ITALIC_EXTRA_BOLD = @as(u32, 10);
pub const WIA_PRINT_FONT_SMALL_ITALIC = @as(u32, 11);
pub const WIA_PRINT_FONT_LARGE = @as(u32, 12);
pub const WIA_PRINT_FONT_LARGE_BOLD = @as(u32, 13);
pub const WIA_PRINT_FONT_LARGE_EXTRA_BOLD = @as(u32, 14);
pub const WIA_PRINT_FONT_LARGE_ITALIC_BOLD = @as(u32, 15);
pub const WIA_PRINT_FONT_LARGE_ITALIC_EXTRA_BOLD = @as(u32, 16);
pub const WIA_PRINT_FONT_LARGE_ITALIC = @as(u32, 17);
pub const WIA_ALARM_NONE = @as(u32, 0);
pub const WIA_ALARM_BEEP1 = @as(u32, 1);
pub const WIA_ALARM_BEEP2 = @as(u32, 2);
pub const WIA_ALARM_BEEP3 = @as(u32, 3);
pub const WIA_ALARM_BEEP4 = @as(u32, 4);
pub const WIA_ALARM_BEEP5 = @as(u32, 5);
pub const WIA_ALARM_BEEP6 = @as(u32, 6);
pub const WIA_ALARM_BEEP7 = @as(u32, 7);
pub const WIA_ALARM_BEEP8 = @as(u32, 8);
pub const WIA_ALARM_BEEP9 = @as(u32, 9);
pub const WIA_ALARM_BEEP10 = @as(u32, 10);
pub const WIA_PRIVATE_DEVPROP = @as(u32, 38914);
pub const WIA_PRIVATE_ITEMPROP = @as(u32, 71682);
pub const WiaImgFmt_UNDEFINED = Guid.initString("b96b3ca9-0728-11d3-9d7b-0000f81ef32e");
pub const WiaImgFmt_RAWRGB = Guid.initString("bca48b55-f272-4371-b0f1-4a150d057bb4");
pub const WiaImgFmt_MEMORYBMP = Guid.initString("b96b3caa-0728-11d3-9d7b-0000f81ef32e");
pub const WiaImgFmt_BMP = Guid.initString("b96b3cab-0728-11d3-9d7b-0000f81ef32e");
pub const WiaImgFmt_EMF = Guid.initString("b96b3cac-0728-11d3-9d7b-0000f81ef32e");
pub const WiaImgFmt_WMF = Guid.initString("b96b3cad-0728-11d3-9d7b-0000f81ef32e");
pub const WiaImgFmt_JPEG = Guid.initString("b96b3cae-0728-11d3-9d7b-0000f81ef32e");
pub const WiaImgFmt_PNG = Guid.initString("b96b3caf-0728-11d3-9d7b-0000f81ef32e");
pub const WiaImgFmt_GIF = Guid.initString("b96b3cb0-0728-11d3-9d7b-0000f81ef32e");
pub const WiaImgFmt_TIFF = Guid.initString("b96b3cb1-0728-11d3-9d7b-0000f81ef32e");
pub const WiaImgFmt_EXIF = Guid.initString("b96b3cb2-0728-11d3-9d7b-0000f81ef32e");
pub const WiaImgFmt_PHOTOCD = Guid.initString("b96b3cb3-0728-11d3-9d7b-0000f81ef32e");
pub const WiaImgFmt_FLASHPIX = Guid.initString("b96b3cb4-0728-11d3-9d7b-0000f81ef32e");
pub const WiaImgFmt_ICO = Guid.initString("b96b3cb5-0728-11d3-9d7b-0000f81ef32e");
pub const WiaImgFmt_CIFF = Guid.initString("9821a8ab-3a7e-4215-94e0-d27a460c03b2");
pub const WiaImgFmt_PICT = Guid.initString("a6bc85d8-6b3e-40ee-a95c-25d482e41adc");
pub const WiaImgFmt_JPEG2K = Guid.initString("344ee2b2-39db-4dde-8173-c4b75f8f1e49");
pub const WiaImgFmt_JPEG2KX = Guid.initString("43e14614-c80a-4850-baf3-4b152dc8da27");
pub const WiaImgFmt_RAW = Guid.initString("6f120719-f1a8-4e07-9ade-9b64c63a3dcc");
pub const WiaImgFmt_JBIG = Guid.initString("41e8dd92-2f0a-43d4-8636-f1614ba11e46");
pub const WiaImgFmt_JBIG2 = Guid.initString("bb8e7e67-283c-4235-9e59-0b9bf94ca687");
pub const WiaImgFmt_RTF = Guid.initString("573dd6a3-4834-432d-a9b5-e198dd9e890d");
pub const WiaImgFmt_XML = Guid.initString("b9171457-dac8-4884-b393-15b471d5f07e");
pub const WiaImgFmt_HTML = Guid.initString("c99a4e62-99de-4a94-acca-71956ac2977d");
pub const WiaImgFmt_TXT = Guid.initString("fafd4d82-723f-421f-9318-30501ac44b59");
pub const WiaImgFmt_PDFA = Guid.initString("9980bd5b-3463-43c7-bdca-3caa146f229f");
pub const WiaImgFmt_XPS = Guid.initString("700b4a0f-2011-411c-b430-d1e0b2e10b28");
pub const WiaImgFmt_OXPS = Guid.initString("2c7b1240-c14d-4109-9755-04b89025153a");
pub const WiaImgFmt_CSV = Guid.initString("355bda24-5a9f-4494-80dc-be752cecbc8c");
pub const WiaImgFmt_MPG = Guid.initString("ecd757e4-d2ec-4f57-955d-bcf8a97c4e52");
pub const WiaImgFmt_AVI = Guid.initString("32f8ca14-087c-4908-b7c4-6757fe7e90ab");
pub const WiaAudFmt_WAV = Guid.initString("f818e146-07af-40ff-ae55-be8f2c065dbe");
pub const WiaAudFmt_MP3 = Guid.initString("0fbc71fb-43bf-49f2-9190-e6fecff37e54");
pub const WiaAudFmt_AIFF = Guid.initString("66e2bf4f-b6fc-443f-94c8-2f33c8a65aaf");
pub const WiaAudFmt_WMA = Guid.initString("d61d6413-8bc2-438f-93ad-21bd484db6a1");
pub const WiaImgFmt_ASF = Guid.initString("8d948ee9-d0aa-4a12-9d9a-9cc5de36199b");
pub const WiaImgFmt_SCRIPT = Guid.initString("fe7d6c53-2dac-446a-b0bd-d73e21e924c9");
pub const WiaImgFmt_EXEC = Guid.initString("485da097-141e-4aa5-bb3b-a5618d95d02b");
pub const WiaImgFmt_UNICODE16 = Guid.initString("1b7639b6-6357-47d1-9a07-12452dc073e9");
pub const WiaImgFmt_DPOF = Guid.initString("369eeeab-a0e8-45ca-86a6-a83ce5697e28");
pub const WiaImgFmt_XMLBAR = Guid.initString("6235701c-3a98-484c-b2a8-fdffd87e6b16");
pub const WiaImgFmt_RAWBAR = Guid.initString("da63f833-d26e-451e-90d2-ea55a1365d62");
pub const WiaImgFmt_XMLPAT = Guid.initString("f8986f55-f052-460d-9523-3a7dfedbb33c");
pub const WiaImgFmt_RAWPAT = Guid.initString("7760507c-5064-400c-9a17-575624d8824b");
pub const WiaImgFmt_XMLMIC = Guid.initString("2d164c61-b9ae-4b23-8973-c7067e1fbd31");
pub const WiaImgFmt_RAWMIC = Guid.initString("22c4f058-0d88-409c-ac1c-eec12b0ea680");
pub const WIA_EVENT_DEVICE_DISCONNECTED = Guid.initString("143e4e83-6497-11d2-a231-00c04fa31809");
pub const WIA_EVENT_DEVICE_CONNECTED = Guid.initString("a28bbade-64b6-11d2-a231-00c04fa31809");
pub const WIA_EVENT_ITEM_DELETED = Guid.initString("1d22a559-e14f-11d2-b326-00c04f68ce61");
pub const WIA_EVENT_ITEM_CREATED = Guid.initString("4c8f4ef5-e14f-11d2-b326-00c04f68ce61");
pub const WIA_EVENT_TREE_UPDATED = Guid.initString("c9859b91-4ab2-4cd6-a1fc-582eec55e585");
pub const WIA_EVENT_VOLUME_INSERT = Guid.initString("9638bbfd-d1bd-11d2-b31f-00c04f68ce61");
pub const WIA_EVENT_SCAN_IMAGE = Guid.initString("a6c5a715-8c6e-11d2-977a-0000f87a926f");
pub const WIA_EVENT_SCAN_PRINT_IMAGE = Guid.initString("b441f425-8c6e-11d2-977a-0000f87a926f");
pub const WIA_EVENT_SCAN_FAX_IMAGE = Guid.initString("c00eb793-8c6e-11d2-977a-0000f87a926f");
pub const WIA_EVENT_SCAN_OCR_IMAGE = Guid.initString("9d095b89-37d6-4877-afed-62a297dc6dbe");
pub const WIA_EVENT_SCAN_EMAIL_IMAGE = Guid.initString("c686dcee-54f2-419e-9a27-2fc7f2e98f9e");
pub const WIA_EVENT_SCAN_FILM_IMAGE = Guid.initString("9b2b662c-6185-438c-b68b-e39ee25e71cb");
pub const WIA_EVENT_SCAN_IMAGE2 = Guid.initString("fc4767c1-c8b3-48a2-9cfa-2e90cb3d3590");
pub const WIA_EVENT_SCAN_IMAGE3 = Guid.initString("154e27be-b617-4653-acc5-0fd7bd4c65ce");
pub const WIA_EVENT_SCAN_IMAGE4 = Guid.initString("a65b704a-7f3c-4447-a75d-8a26dfca1fdf");
pub const WIA_EVENT_STORAGE_CREATED = Guid.initString("353308b2-fe73-46c8-895e-fa4551ccc85a");
pub const WIA_EVENT_STORAGE_DELETED = Guid.initString("5e41e75e-9390-44c5-9a51-e47019e390cf");
pub const WIA_EVENT_STI_PROXY = Guid.initString("d711f81f-1f0d-422d-8641-927d1b93e5e5");
pub const WIA_EVENT_CANCEL_IO = Guid.initString("c860f7b8-9ccd-41ea-bbbf-4dd09c5b1795");
pub const WIA_EVENT_POWER_SUSPEND = Guid.initString("a0922ff9-c3b4-411c-9e29-03a66993d2be");
pub const WIA_EVENT_POWER_RESUME = Guid.initString("618f153e-f686-4350-9634-4115a304830c");
pub const WIA_EVENT_HANDLER_NO_ACTION = Guid.initString("e0372b7d-e115-4525-bc55-b629e68c745a");
pub const WIA_EVENT_HANDLER_PROMPT = Guid.initString("5f4baad0-4d59-4fcd-b213-783ce7a92f22");
pub const WIA_EVENT_DEVICE_NOT_READY = Guid.initString("d8962d7e-e4dc-4b4d-ba29-668a87f42e6f");
pub const WIA_EVENT_DEVICE_READY = Guid.initString("7523ec6c-988b-419e-9a0a-425ac31b37dc");
pub const WIA_EVENT_FLATBED_LID_OPEN = Guid.initString("ba0a0623-437d-4f03-a97d-7793b123113c");
pub const WIA_EVENT_FLATBED_LID_CLOSED = Guid.initString("f879af0f-9b29-4283-ad95-d412164d39a9");
pub const WIA_EVENT_FEEDER_LOADED = Guid.initString("cc8d701e-9aba-481d-bf74-78f763dc342a");
pub const WIA_EVENT_FEEDER_EMPTIED = Guid.initString("e70b4b82-6dda-46bb-8ff9-53ceb1a03e35");
pub const WIA_EVENT_COVER_OPEN = Guid.initString("19a12136-fa1c-4f66-900f-8f914ec74ec9");
pub const WIA_EVENT_COVER_CLOSED = Guid.initString("6714a1e6-e285-468c-9b8c-da7dc4cbaa05");
pub const WIA_CMD_SYNCHRONIZE = Guid.initString("9b26b7b2-acad-11d2-a093-00c04f72dc3c");
pub const WIA_CMD_TAKE_PICTURE = Guid.initString("af933cac-acad-11d2-a093-00c04f72dc3c");
pub const WIA_CMD_DELETE_ALL_ITEMS = Guid.initString("e208c170-acad-11d2-a093-00c04f72dc3c");
pub const WIA_CMD_CHANGE_DOCUMENT = Guid.initString("04e725b0-acae-11d2-a093-00c04f72dc3c");
pub const WIA_CMD_UNLOAD_DOCUMENT = Guid.initString("1f3b3d8e-acae-11d2-a093-00c04f72dc3c");
pub const WIA_CMD_DIAGNOSTIC = Guid.initString("10ff52f5-de04-4cf0-a5ad-691f8dce0141");
pub const WIA_CMD_FORMAT = Guid.initString("c3a693aa-f788-4d34-a5b0-be7190759a24");
pub const WIA_CMD_DELETE_DEVICE_TREE = Guid.initString("73815942-dbea-11d2-8416-00c04fa36145");
pub const WIA_CMD_BUILD_DEVICE_TREE = Guid.initString("9cba5ce0-dbea-11d2-8416-00c04fa36145");
pub const WIA_CMD_START_FEEDER = Guid.initString("5a9df6c9-5f2d-4a39-9d6c-00456d047f00");
pub const WIA_CMD_STOP_FEEDER = Guid.initString("d847b06d-3905-459c-9509-9b29cdb691e7");
pub const WIA_CMD_PAUSE_FEEDER = Guid.initString("50985e4d-a5b2-4b71-9c95-6d7d7c469a43");
pub const BASE_VAL_WIA_ERROR = @as(u32, 0);
pub const BASE_VAL_WIA_SUCCESS = @as(u32, 0);
pub const WIA_ERROR_GENERAL_ERROR = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145320959));
pub const WIA_ERROR_PAPER_JAM = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145320958));
pub const WIA_ERROR_PAPER_EMPTY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145320957));
pub const WIA_ERROR_PAPER_PROBLEM = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145320956));
pub const WIA_ERROR_OFFLINE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145320955));
pub const WIA_ERROR_BUSY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145320954));
pub const WIA_ERROR_WARMING_UP = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145320953));
pub const WIA_ERROR_USER_INTERVENTION = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145320952));
pub const WIA_ERROR_ITEM_DELETED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145320951));
pub const WIA_ERROR_DEVICE_COMMUNICATION = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145320950));
pub const WIA_ERROR_INVALID_COMMAND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145320949));
pub const WIA_ERROR_INCORRECT_HARDWARE_SETTING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145320948));
pub const WIA_ERROR_DEVICE_LOCKED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145320947));
pub const WIA_ERROR_EXCEPTION_IN_DRIVER = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145320946));
pub const WIA_ERROR_INVALID_DRIVER_RESPONSE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145320945));
pub const WIA_ERROR_COVER_OPEN = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145320944));
pub const WIA_ERROR_LAMP_OFF = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145320943));
pub const WIA_ERROR_DESTINATION = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145320942));
pub const WIA_ERROR_NETWORK_RESERVATION_FAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145320941));
pub const WIA_ERROR_MULTI_FEED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145320940));
pub const WIA_ERROR_MAXIMUM_PRINTER_ENDORSER_COUNTER = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145320939));
pub const WIA_STATUS_END_OF_MEDIA = @import("../zig.zig").typedConst(HRESULT, @as(i32, 2162689));
pub const WIA_STATUS_WARMING_UP = @import("../zig.zig").typedConst(HRESULT, @as(i32, 2162690));
pub const WIA_STATUS_CALIBRATING = @import("../zig.zig").typedConst(HRESULT, @as(i32, 2162691));
pub const WIA_STATUS_RESERVING_NETWORK_DEVICE = @import("../zig.zig").typedConst(HRESULT, @as(i32, 2162694));
pub const WIA_STATUS_NETWORK_DEVICE_RESERVED = @import("../zig.zig").typedConst(HRESULT, @as(i32, 2162695));
pub const WIA_STATUS_CLEAR = @import("../zig.zig").typedConst(HRESULT, @as(i32, 2162696));
pub const WIA_STATUS_SKIP_ITEM = @import("../zig.zig").typedConst(HRESULT, @as(i32, 2162697));
pub const WIA_STATUS_NOT_HANDLED = @import("../zig.zig").typedConst(HRESULT, @as(i32, 2162698));
pub const WIA_S_CHANGE_DEVICE = @import("../zig.zig").typedConst(HRESULT, @as(i32, 2162699));
pub const WIA_S_NO_DEVICE_AVAILABLE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145320939));
pub const WIA_SELECT_DEVICE_NODEFAULT = @as(u32, 1);
pub const WIA_DEVICE_DIALOG_SINGLE_IMAGE = @as(u32, 2);
pub const WIA_DEVICE_DIALOG_USE_COMMON_UI = @as(u32, 4);
pub const WIA_REGISTER_EVENT_CALLBACK = @as(u32, 1);
pub const WIA_UNREGISTER_EVENT_CALLBACK = @as(u32, 2);
pub const WIA_SET_DEFAULT_HANDLER = @as(u32, 4);
pub const WIA_NOTIFICATION_EVENT = @as(u32, 1);
pub const WIA_ACTION_EVENT = @as(u32, 2);
pub const WIA_LINE_ORDER_TOP_TO_BOTTOM = @as(u32, 1);
pub const WIA_LINE_ORDER_BOTTOM_TO_TOP = @as(u32, 2);
pub const WIA_IS_DEFAULT_HANDLER = @as(u32, 1);
pub const TYMED_CALLBACK = @as(u32, 128);
pub const TYMED_MULTIPAGE_FILE = @as(u32, 256);
pub const TYMED_MULTIPAGE_CALLBACK = @as(u32, 512);
pub const IT_MSG_DATA_HEADER = @as(u32, 1);
pub const IT_MSG_DATA = @as(u32, 2);
pub const IT_MSG_STATUS = @as(u32, 3);
pub const IT_MSG_TERMINATION = @as(u32, 4);
pub const IT_MSG_NEW_PAGE = @as(u32, 5);
pub const IT_MSG_FILE_PREVIEW_DATA = @as(u32, 6);
pub const IT_MSG_FILE_PREVIEW_DATA_HEADER = @as(u32, 7);
pub const IT_STATUS_TRANSFER_FROM_DEVICE = @as(u32, 1);
pub const IT_STATUS_PROCESSING_DATA = @as(u32, 2);
pub const IT_STATUS_TRANSFER_TO_CLIENT = @as(u32, 4);
pub const IT_STATUS_MASK = @as(u32, 7);
pub const WIA_TRANSFER_ACQUIRE_CHILDREN = @as(u32, 1);
pub const WIA_TRANSFER_MSG_STATUS = @as(u32, 1);
pub const WIA_TRANSFER_MSG_END_OF_STREAM = @as(u32, 2);
pub const WIA_TRANSFER_MSG_END_OF_TRANSFER = @as(u32, 3);
pub const WIA_TRANSFER_MSG_DEVICE_STATUS = @as(u32, 5);
pub const WIA_TRANSFER_MSG_NEW_PAGE = @as(u32, 6);
pub const WIA_MAJOR_EVENT_DEVICE_CONNECT = @as(u32, 1);
pub const WIA_MAJOR_EVENT_DEVICE_DISCONNECT = @as(u32, 2);
pub const WIA_MAJOR_EVENT_PICTURE_TAKEN = @as(u32, 3);
pub const WIA_MAJOR_EVENT_PICTURE_DELETED = @as(u32, 4);
pub const WIA_DEVICE_NOT_CONNECTED = @as(u32, 0);
pub const WIA_DEVICE_CONNECTED = @as(u32, 1);
pub const WIA_DEVICE_COMMANDS = @as(u32, 1);
pub const WIA_DEVICE_EVENTS = @as(u32, 2);
pub const WIA_DEVINFO_ENUM_ALL = @as(u32, 15);
pub const WIA_DEVINFO_ENUM_LOCAL = @as(u32, 16);
pub const WiaItemTypeFree = @as(u32, 0);
pub const WiaItemTypeImage = @as(u32, 1);
pub const WiaItemTypeFile = @as(u32, 2);
pub const WiaItemTypeFolder = @as(u32, 4);
pub const WiaItemTypeRoot = @as(u32, 8);
pub const WiaItemTypeAnalyze = @as(u32, 16);
pub const WiaItemTypeAudio = @as(u32, 32);
pub const WiaItemTypeDevice = @as(u32, 64);
pub const WiaItemTypeDeleted = @as(u32, 128);
pub const WiaItemTypeDisconnected = @as(u32, 256);
pub const WiaItemTypeHPanorama = @as(u32, 512);
pub const WiaItemTypeVPanorama = @as(u32, 1024);
pub const WiaItemTypeBurst = @as(u32, 2048);
pub const WiaItemTypeStorage = @as(u32, 4096);
pub const WiaItemTypeTransfer = @as(u32, 8192);
pub const WiaItemTypeGenerated = @as(u32, 16384);
pub const WiaItemTypeHasAttachments = @as(u32, 32768);
pub const WiaItemTypeVideo = @as(u32, 65536);
pub const WiaItemTypeRemoved = @as(u32, 2147483648);
pub const WiaItemTypeDocument = @as(u32, 262144);
pub const WiaItemTypeProgrammableDataSource = @as(u32, 524288);
pub const WiaItemTypeMask = @as(u32, 2148532223);
pub const WIA_MAX_CTX_SIZE = @as(u32, 16777216);
pub const WIA_PROP_READ = @as(u32, 1);
pub const WIA_PROP_WRITE = @as(u32, 2);
pub const WIA_PROP_SYNC_REQUIRED = @as(u32, 4);
pub const WIA_PROP_NONE = @as(u32, 8);
pub const WIA_PROP_RANGE = @as(u32, 16);
pub const WIA_PROP_LIST = @as(u32, 32);
pub const WIA_PROP_FLAG = @as(u32, 64);
pub const WIA_PROP_CACHEABLE = @as(u32, 65536);
pub const COPY_PARENT_PROPERTY_VALUES = @as(u32, 1073741824);
pub const WIA_ITEM_CAN_BE_DELETED = @as(u32, 128);
pub const WIA_ITEM_READ = @as(u32, 1);
pub const WIA_ITEM_WRITE = @as(u32, 2);
pub const WIA_RANGE_MIN = @as(u32, 0);
pub const WIA_RANGE_NOM = @as(u32, 1);
pub const WIA_RANGE_MAX = @as(u32, 2);
pub const WIA_RANGE_STEP = @as(u32, 3);
pub const WIA_RANGE_NUM_ELEMS = @as(u32, 4);
pub const WIA_LIST_COUNT = @as(u32, 0);
pub const WIA_LIST_NOM = @as(u32, 1);
pub const WIA_LIST_VALUES = @as(u32, 2);
pub const WIA_LIST_NUM_ELEMS = @as(u32, 2);
pub const WIA_FLAG_NOM = @as(u32, 0);
pub const WIA_FLAG_VALUES = @as(u32, 1);
pub const WIA_FLAG_NUM_ELEMS = @as(u32, 2);
pub const WIA_DIP_FIRST = @as(u32, 2);
pub const WIA_IPA_FIRST = @as(u32, 4098);
pub const WIA_DPF_FIRST = @as(u32, 3330);
pub const WIA_IPS_FIRST = @as(u32, 6146);
pub const WIA_DPS_FIRST = @as(u32, 3074);
pub const WIA_IPC_FIRST = @as(u32, 5122);
pub const WIA_NUM_IPC = @as(u32, 9);
pub const WIA_RESERVED_FOR_NEW_PROPS = @as(u32, 1024);
pub const WHITEBALANCE_MANUAL = @as(u32, 1);
pub const WHITEBALANCE_AUTO = @as(u32, 2);
pub const WHITEBALANCE_ONEPUSH_AUTO = @as(u32, 3);
pub const WHITEBALANCE_DAYLIGHT = @as(u32, 4);
pub const WHITEBALANCE_FLORESCENT = @as(u32, 5);
pub const WHITEBALANCE_TUNGSTEN = @as(u32, 6);
pub const WHITEBALANCE_FLASH = @as(u32, 7);
pub const FOCUSMODE_MANUAL = @as(u32, 1);
pub const FOCUSMODE_AUTO = @as(u32, 2);
pub const FOCUSMODE_MACROAUTO = @as(u32, 3);
pub const EXPOSUREMETERING_AVERAGE = @as(u32, 1);
pub const EXPOSUREMETERING_CENTERWEIGHT = @as(u32, 2);
pub const EXPOSUREMETERING_MULTISPOT = @as(u32, 3);
pub const EXPOSUREMETERING_CENTERSPOT = @as(u32, 4);
pub const FLASHMODE_AUTO = @as(u32, 1);
pub const FLASHMODE_OFF = @as(u32, 2);
pub const FLASHMODE_FILL = @as(u32, 3);
pub const FLASHMODE_REDEYE_AUTO = @as(u32, 4);
pub const FLASHMODE_REDEYE_FILL = @as(u32, 5);
pub const FLASHMODE_EXTERNALSYNC = @as(u32, 6);
pub const EXPOSUREMODE_MANUAL = @as(u32, 1);
pub const EXPOSUREMODE_AUTO = @as(u32, 2);
pub const EXPOSUREMODE_APERTURE_PRIORITY = @as(u32, 3);
pub const EXPOSUREMODE_SHUTTER_PRIORITY = @as(u32, 4);
pub const EXPOSUREMODE_PROGRAM_CREATIVE = @as(u32, 5);
pub const EXPOSUREMODE_PROGRAM_ACTION = @as(u32, 6);
pub const EXPOSUREMODE_PORTRAIT = @as(u32, 7);
pub const CAPTUREMODE_NORMAL = @as(u32, 1);
pub const CAPTUREMODE_BURST = @as(u32, 2);
pub const CAPTUREMODE_TIMELAPSE = @as(u32, 3);
pub const EFFECTMODE_STANDARD = @as(u32, 1);
pub const EFFECTMODE_BW = @as(u32, 2);
pub const EFFECTMODE_SEPIA = @as(u32, 3);
pub const FOCUSMETERING_CENTERSPOT = @as(u32, 1);
pub const FOCUSMETERING_MULTISPOT = @as(u32, 2);
pub const POWERMODE_LINE = @as(u32, 1);
pub const POWERMODE_BATTERY = @as(u32, 2);
pub const LEFT_JUSTIFIED = @as(u32, 0);
pub const CENTERED = @as(u32, 1);
pub const RIGHT_JUSTIFIED = @as(u32, 2);
pub const TOP_JUSTIFIED = @as(u32, 0);
pub const BOTTOM_JUSTIFIED = @as(u32, 2);
pub const PORTRAIT = @as(u32, 0);
pub const LANSCAPE = @as(u32, 1);
pub const LANDSCAPE = @as(u32, 1);
pub const ROT180 = @as(u32, 2);
pub const ROT270 = @as(u32, 3);
pub const MIRRORED = @as(u32, 1);
pub const FEED = @as(u32, 1);
pub const FLAT = @as(u32, 2);
pub const DUP = @as(u32, 4);
pub const DETECT_FLAT = @as(u32, 8);
pub const DETECT_SCAN = @as(u32, 16);
pub const DETECT_FEED = @as(u32, 32);
pub const DETECT_DUP = @as(u32, 64);
pub const DETECT_FEED_AVAIL = @as(u32, 128);
pub const DETECT_DUP_AVAIL = @as(u32, 256);
pub const FILM_TPA = @as(u32, 512);
pub const DETECT_FILM_TPA = @as(u32, 1024);
pub const STOR = @as(u32, 2048);
pub const DETECT_STOR = @as(u32, 4096);
pub const ADVANCED_DUP = @as(u32, 8192);
pub const AUTO_SOURCE = @as(u32, 32768);
pub const IMPRINTER = @as(u32, 65536);
pub const ENDORSER = @as(u32, 131072);
pub const BARCODE_READER = @as(u32, 262144);
pub const PATCH_CODE_READER = @as(u32, 524288);
pub const MICR_READER = @as(u32, 1048576);
pub const FEED_READY = @as(u32, 1);
pub const FLAT_READY = @as(u32, 2);
pub const DUP_READY = @as(u32, 4);
pub const FLAT_COVER_UP = @as(u32, 8);
pub const PATH_COVER_UP = @as(u32, 16);
pub const PAPER_JAM = @as(u32, 32);
pub const FILM_TPA_READY = @as(u32, 64);
pub const STORAGE_READY = @as(u32, 128);
pub const STORAGE_FULL = @as(u32, 256);
pub const MULTIPLE_FEED = @as(u32, 512);
pub const DEVICE_ATTENTION = @as(u32, 1024);
pub const LAMP_ERR = @as(u32, 2048);
pub const IMPRINTER_READY = @as(u32, 4096);
pub const ENDORSER_READY = @as(u32, 8192);
pub const BARCODE_READER_READY = @as(u32, 16384);
pub const PATCH_CODE_READER_READY = @as(u32, 32768);
pub const MICR_READER_READY = @as(u32, 65536);
pub const FEEDER = @as(u32, 1);
pub const FLATBED = @as(u32, 2);
pub const DUPLEX = @as(u32, 4);
pub const FRONT_FIRST = @as(u32, 8);
pub const BACK_FIRST = @as(u32, 16);
pub const FRONT_ONLY = @as(u32, 32);
pub const BACK_ONLY = @as(u32, 64);
pub const NEXT_PAGE = @as(u32, 128);
pub const PREFEED = @as(u32, 256);
pub const AUTO_ADVANCE = @as(u32, 512);
pub const ADVANCED_DUPLEX = @as(u32, 1024);
pub const LIGHT_SOURCE_PRESENT_DETECT = @as(u32, 1);
pub const LIGHT_SOURCE_PRESENT = @as(u32, 2);
pub const LIGHT_SOURCE_DETECT_READY = @as(u32, 4);
pub const LIGHT_SOURCE_READY = @as(u32, 8);
pub const TRANSPARENCY_DYNAMIC_FRAME_SUPPORT = @as(u32, 1);
pub const TRANSPARENCY_STATIC_FRAME_SUPPORT = @as(u32, 2);
pub const LIGHT_SOURCE_SELECT = @as(u32, 1);
pub const LIGHT_SOURCE_POSITIVE = @as(u32, 2);
pub const LIGHT_SOURCE_NEGATIVE = @as(u32, 4);
pub const WIA_SCAN_AHEAD_ALL = @as(u32, 0);
pub const ALL_PAGES = @as(u32, 0);
pub const WIA_FINAL_SCAN = @as(u32, 0);
pub const WIA_PREVIEW_SCAN = @as(u32, 1);
pub const WIA_SHOW_PREVIEW_CONTROL = @as(u32, 0);
pub const WIA_DONT_SHOW_PREVIEW_CONTROL = @as(u32, 1);
pub const WIA_PAGE_A4 = @as(u32, 0);
pub const WIA_PAGE_LETTER = @as(u32, 1);
pub const WIA_PAGE_CUSTOM = @as(u32, 2);
pub const WIA_PAGE_USLEGAL = @as(u32, 3);
pub const WIA_PAGE_USLETTER = @as(u32, 1);
pub const WIA_PAGE_USLEDGER = @as(u32, 4);
pub const WIA_PAGE_USSTATEMENT = @as(u32, 5);
pub const WIA_PAGE_BUSINESSCARD = @as(u32, 6);
pub const WIA_PAGE_ISO_A0 = @as(u32, 7);
pub const WIA_PAGE_ISO_A1 = @as(u32, 8);
pub const WIA_PAGE_ISO_A2 = @as(u32, 9);
pub const WIA_PAGE_ISO_A3 = @as(u32, 10);
pub const WIA_PAGE_ISO_A4 = @as(u32, 0);
pub const WIA_PAGE_ISO_A5 = @as(u32, 11);
pub const WIA_PAGE_ISO_A6 = @as(u32, 12);
pub const WIA_PAGE_ISO_A7 = @as(u32, 13);
pub const WIA_PAGE_ISO_A8 = @as(u32, 14);
pub const WIA_PAGE_ISO_A9 = @as(u32, 15);
pub const WIA_PAGE_ISO_A10 = @as(u32, 16);
pub const WIA_PAGE_ISO_B0 = @as(u32, 17);
pub const WIA_PAGE_ISO_B1 = @as(u32, 18);
pub const WIA_PAGE_ISO_B2 = @as(u32, 19);
pub const WIA_PAGE_ISO_B3 = @as(u32, 20);
pub const WIA_PAGE_ISO_B4 = @as(u32, 21);
pub const WIA_PAGE_ISO_B5 = @as(u32, 22);
pub const WIA_PAGE_ISO_B6 = @as(u32, 23);
pub const WIA_PAGE_ISO_B7 = @as(u32, 24);
pub const WIA_PAGE_ISO_B8 = @as(u32, 25);
pub const WIA_PAGE_ISO_B9 = @as(u32, 26);
pub const WIA_PAGE_ISO_B10 = @as(u32, 27);
pub const WIA_PAGE_ISO_C0 = @as(u32, 28);
pub const WIA_PAGE_ISO_C1 = @as(u32, 29);
pub const WIA_PAGE_ISO_C2 = @as(u32, 30);
pub const WIA_PAGE_ISO_C3 = @as(u32, 31);
pub const WIA_PAGE_ISO_C4 = @as(u32, 32);
pub const WIA_PAGE_ISO_C5 = @as(u32, 33);
pub const WIA_PAGE_ISO_C6 = @as(u32, 34);
pub const WIA_PAGE_ISO_C7 = @as(u32, 35);
pub const WIA_PAGE_ISO_C8 = @as(u32, 36);
pub const WIA_PAGE_ISO_C9 = @as(u32, 37);
pub const WIA_PAGE_ISO_C10 = @as(u32, 38);
pub const WIA_PAGE_JIS_B0 = @as(u32, 39);
pub const WIA_PAGE_JIS_B1 = @as(u32, 40);
pub const WIA_PAGE_JIS_B2 = @as(u32, 41);
pub const WIA_PAGE_JIS_B3 = @as(u32, 42);
pub const WIA_PAGE_JIS_B4 = @as(u32, 43);
pub const WIA_PAGE_JIS_B5 = @as(u32, 44);
pub const WIA_PAGE_JIS_B6 = @as(u32, 45);
pub const WIA_PAGE_JIS_B7 = @as(u32, 46);
pub const WIA_PAGE_JIS_B8 = @as(u32, 47);
pub const WIA_PAGE_JIS_B9 = @as(u32, 48);
pub const WIA_PAGE_JIS_B10 = @as(u32, 49);
pub const WIA_PAGE_JIS_2A = @as(u32, 50);
pub const WIA_PAGE_JIS_4A = @as(u32, 51);
pub const WIA_PAGE_DIN_2B = @as(u32, 52);
pub const WIA_PAGE_DIN_4B = @as(u32, 53);
pub const WIA_PAGE_AUTO = @as(u32, 100);
pub const WIA_PAGE_CUSTOM_BASE = @as(u32, 32768);
pub const WIA_COMPRESSION_NONE = @as(u32, 0);
pub const WIA_COMPRESSION_BI_RLE4 = @as(u32, 1);
pub const WIA_COMPRESSION_BI_RLE8 = @as(u32, 2);
pub const WIA_COMPRESSION_G3 = @as(u32, 3);
pub const WIA_COMPRESSION_G4 = @as(u32, 4);
pub const WIA_COMPRESSION_JPEG = @as(u32, 5);
pub const WIA_COMPRESSION_JBIG = @as(u32, 6);
pub const WIA_COMPRESSION_JPEG2K = @as(u32, 7);
pub const WIA_COMPRESSION_PNG = @as(u32, 8);
pub const WIA_COMPRESSION_AUTO = @as(u32, 100);
pub const WIA_PACKED_PIXEL = @as(u32, 0);
pub const WIA_PLANAR = @as(u32, 1);
pub const WIA_DATA_THRESHOLD = @as(u32, 0);
pub const WIA_DATA_DITHER = @as(u32, 1);
pub const WIA_DATA_GRAYSCALE = @as(u32, 2);
pub const WIA_DATA_COLOR = @as(u32, 3);
pub const WIA_DATA_COLOR_THRESHOLD = @as(u32, 4);
pub const WIA_DATA_COLOR_DITHER = @as(u32, 5);
pub const WIA_DATA_RAW_RGB = @as(u32, 6);
pub const WIA_DATA_RAW_BGR = @as(u32, 7);
pub const WIA_DATA_RAW_YUV = @as(u32, 8);
pub const WIA_DATA_RAW_YUVK = @as(u32, 9);
pub const WIA_DATA_RAW_CMY = @as(u32, 10);
pub const WIA_DATA_RAW_CMYK = @as(u32, 11);
pub const WIA_DATA_AUTO = @as(u32, 100);
pub const WIA_DEPTH_AUTO = @as(u32, 0);
pub const WIA_PHOTO_WHITE_1 = @as(u32, 0);
pub const WIA_PHOTO_WHITE_0 = @as(u32, 1);
pub const WIA_PROPPAGE_SCANNER_ITEM_GENERAL = @as(u32, 1);
pub const WIA_PROPPAGE_CAMERA_ITEM_GENERAL = @as(u32, 2);
pub const WIA_PROPPAGE_DEVICE_GENERAL = @as(u32, 4);
pub const WIA_INTENT_NONE = @as(u32, 0);
pub const WIA_INTENT_IMAGE_TYPE_COLOR = @as(u32, 1);
pub const WIA_INTENT_IMAGE_TYPE_GRAYSCALE = @as(u32, 2);
pub const WIA_INTENT_IMAGE_TYPE_TEXT = @as(u32, 4);
pub const WIA_INTENT_IMAGE_TYPE_MASK = @as(u32, 15);
pub const WIA_INTENT_MINIMIZE_SIZE = @as(u32, 65536);
pub const WIA_INTENT_MAXIMIZE_QUALITY = @as(u32, 131072);
pub const WIA_INTENT_BEST_PREVIEW = @as(u32, 262144);
pub const WIA_INTENT_SIZE_MASK = @as(u32, 983040);
pub const WIA_NUM_DIP = @as(u32, 16);
pub const GUID_DEVINTERFACE_IMAGE = Guid.initString("6bdd1fc6-810f-11d0-bec7-08002be2092f");
pub const MAX_IO_HANDLES = @as(u32, 16);
pub const MAX_RESERVED = @as(u32, 4);
pub const MAX_ANSI_CHAR = @as(u32, 255);
pub const BUS_TYPE_SCSI = @as(u32, 200);
pub const BUS_TYPE_USB = @as(u32, 201);
pub const BUS_TYPE_PARALLEL = @as(u32, 202);
pub const BUS_TYPE_FIREWIRE = @as(u32, 203);
pub const SCAN_FIRST = @as(u32, 10);
pub const SCAN_NEXT = @as(u32, 20);
pub const SCAN_FINISHED = @as(u32, 30);
pub const SCANMODE_FINALSCAN = @as(u32, 0);
pub const SCANMODE_PREVIEWSCAN = @as(u32, 1);
pub const CMD_INITIALIZE = @as(u32, 100);
pub const CMD_UNINITIALIZE = @as(u32, 101);
pub const CMD_SETXRESOLUTION = @as(u32, 102);
pub const CMD_SETYRESOLUTION = @as(u32, 103);
pub const CMD_SETCONTRAST = @as(u32, 104);
pub const CMD_SETINTENSITY = @as(u32, 105);
pub const CMD_SETDATATYPE = @as(u32, 106);
pub const CMD_SETDITHER = @as(u32, 107);
pub const CMD_SETMIRROR = @as(u32, 108);
pub const CMD_SETNEGATIVE = @as(u32, 109);
pub const CMD_SETTONEMAP = @as(u32, 110);
pub const CMD_SETCOLORDITHER = @as(u32, 111);
pub const CMD_SETMATRIX = @as(u32, 112);
pub const CMD_SETSPEED = @as(u32, 113);
pub const CMD_SETFILTER = @as(u32, 114);
pub const CMD_LOAD_ADF = @as(u32, 115);
pub const CMD_UNLOAD_ADF = @as(u32, 116);
pub const CMD_GETADFAVAILABLE = @as(u32, 117);
pub const CMD_GETADFOPEN = @as(u32, 118);
pub const CMD_GETADFREADY = @as(u32, 119);
pub const CMD_GETADFHASPAPER = @as(u32, 120);
pub const CMD_GETADFSTATUS = @as(u32, 121);
pub const CMD_GETADFUNLOADREADY = @as(u32, 122);
pub const CMD_GETTPAAVAILABLE = @as(u32, 123);
pub const CMD_GETTPAOPENED = @as(u32, 124);
pub const CMD_TPAREADY = @as(u32, 125);
pub const CMD_SETLAMP = @as(u32, 126);
pub const CMD_SENDSCSICOMMAND = @as(u32, 127);
pub const CMD_STI_DEVICERESET = @as(u32, 128);
pub const CMD_STI_GETSTATUS = @as(u32, 129);
pub const CMD_STI_DIAGNOSTIC = @as(u32, 130);
pub const CMD_RESETSCANNER = @as(u32, 131);
pub const CMD_GETCAPABILITIES = @as(u32, 132);
pub const CMD_GET_INTERRUPT_EVENT = @as(u32, 133);
pub const CMD_SETGSDNAME = @as(u32, 134);
pub const CMD_SETSCANMODE = @as(u32, 135);
pub const CMD_SETSTIDEVICEHKEY = @as(u32, 136);
pub const CMD_GETSUPPORTEDFILEFORMATS = @as(u32, 138);
pub const CMD_GETSUPPORTEDMEMORYFORMATS = @as(u32, 139);
pub const CMD_SETFORMAT = @as(u32, 140);
pub const SUPPORT_COLOR = @as(u32, 1);
pub const SUPPORT_BW = @as(u32, 2);
pub const SUPPORT_GRAYSCALE = @as(u32, 4);
pub const MCRO_ERROR_GENERAL_ERROR = @as(u32, 0);
pub const MCRO_STATUS_OK = @as(u32, 1);
pub const MCRO_ERROR_PAPER_JAM = @as(u32, 2);
pub const MCRO_ERROR_PAPER_PROBLEM = @as(u32, 3);
pub const MCRO_ERROR_PAPER_EMPTY = @as(u32, 4);
pub const MCRO_ERROR_OFFLINE = @as(u32, 5);
pub const MCRO_ERROR_USER_INTERVENTION = @as(u32, 6);
pub const WIA_ORDER_RGB = @as(u32, 0);
pub const WIA_ORDER_BGR = @as(u32, 1);
pub const WiaItemTypeTwainCapabilityPassThrough = @as(u32, 131072);
pub const ESC_TWAIN_CAPABILITY = @as(u32, 2001);
pub const ESC_TWAIN_PRIVATE_SUPPORTED_CAPS = @as(u32, 2002);
pub const WIA_WSD_MANUFACTURER = @as(u32, 38914);
pub const WIA_WSD_MANUFACTURER_URL = @as(u32, 38915);
pub const WIA_WSD_MODEL_NAME = @as(u32, 38916);
pub const WIA_WSD_MODEL_NUMBER = @as(u32, 38917);
pub const WIA_WSD_MODEL_URL = @as(u32, 38918);
pub const WIA_WSD_PRESENTATION_URL = @as(u32, 38919);
pub const WIA_WSD_FRIENDLY_NAME = @as(u32, 38920);
pub const WIA_WSD_SERIAL_NUMBER = @as(u32, 38921);
pub const WIA_WSD_SCAN_AVAILABLE_ITEM = @as(u32, 38922);
//--------------------------------------------------------------------------------
// Section: Types (67)
//--------------------------------------------------------------------------------
const CLSID_WiaDevMgr_Value = Guid.initString("a1f4e726-8cf1-11d1-bf92-0060081ed811");
pub const CLSID_WiaDevMgr = &CLSID_WiaDevMgr_Value;
const CLSID_WiaDevMgr2_Value = Guid.initString("b6c292bc-7c88-41ee-8b54-8ec92617e599");
pub const CLSID_WiaDevMgr2 = &CLSID_WiaDevMgr2_Value;
const CLSID_WiaLog_Value = Guid.initString("a1e75357-881a-419e-83e2-bb16db197c68");
pub const CLSID_WiaLog = &CLSID_WiaLog_Value;
pub const WIA_DITHER_PATTERN_DATA = extern struct {
lSize: i32,
bstrPatternName: ?BSTR,
lPatternWidth: i32,
lPatternLength: i32,
cbPattern: i32,
pbPattern: ?*u8,
};
pub const WIA_PROPID_TO_NAME = extern struct {
propid: u32,
pszName: ?PWSTR,
};
pub const WIA_FORMAT_INFO = extern struct {
guidFormatID: Guid,
lTymed: i32,
};
pub const WIA_RAW_HEADER = extern struct {
Tag: u32,
Version: u32,
HeaderSize: u32,
XRes: u32,
YRes: u32,
XExtent: u32,
YExtent: u32,
BytesPerLine: u32,
BitsPerPixel: u32,
ChannelsPerPixel: u32,
DataType: u32,
BitsPerChannel: [8]u8,
Compression: u32,
PhotometricInterp: u32,
LineOrder: u32,
RawDataOffset: u32,
RawDataSize: u32,
PaletteOffset: u32,
PaletteSize: u32,
};
pub const WIA_BARCODE_INFO = extern struct {
Size: u32,
Type: u32,
Page: u32,
Confidence: u32,
XOffset: u32,
YOffset: u32,
Rotation: u32,
Length: u32,
Text: [1]u16,
};
pub const WIA_BARCODES = extern struct {
Tag: u32,
Version: u32,
Size: u32,
Count: u32,
Barcodes: [1]WIA_BARCODE_INFO,
};
pub const WIA_PATCH_CODE_INFO = extern struct {
Type: u32,
};
pub const WIA_PATCH_CODES = extern struct {
Tag: u32,
Version: u32,
Size: u32,
Count: u32,
PatchCodes: [1]WIA_PATCH_CODE_INFO,
};
pub const WIA_MICR_INFO = extern struct {
Size: u32,
Page: u32,
Length: u32,
Text: [1]u16,
};
pub const WIA_MICR = extern struct {
Tag: u32,
Version: u32,
Size: u32,
Placeholder: u16,
Reserved: u16,
Count: u32,
Micr: [1]WIA_MICR_INFO,
};
// TODO: this type is limited to platform 'windows5.0'
const IID_IWiaDevMgr_Value = Guid.initString("5eb2502a-8cf1-11d1-bf92-0060081ed811");
pub const IID_IWiaDevMgr = &IID_IWiaDevMgr_Value;
pub const IWiaDevMgr = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
EnumDeviceInfo: fn(
self: *const IWiaDevMgr,
lFlag: i32,
ppIEnum: ?*?*IEnumWIA_DEV_INFO,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateDevice: fn(
self: *const IWiaDevMgr,
bstrDeviceID: ?BSTR,
ppWiaItemRoot: ?*?*IWiaItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SelectDeviceDlg: fn(
self: *const IWiaDevMgr,
hwndParent: ?HWND,
lDeviceType: i32,
lFlags: i32,
pbstrDeviceID: ?*?BSTR,
ppItemRoot: ?*?*IWiaItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SelectDeviceDlgID: fn(
self: *const IWiaDevMgr,
hwndParent: ?HWND,
lDeviceType: i32,
lFlags: i32,
pbstrDeviceID: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetImageDlg: fn(
self: *const IWiaDevMgr,
hwndParent: ?HWND,
lDeviceType: i32,
lFlags: i32,
lIntent: i32,
pItemRoot: ?*IWiaItem,
bstrFilename: ?BSTR,
pguidFormat: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RegisterEventCallbackProgram: fn(
self: *const IWiaDevMgr,
lFlags: i32,
bstrDeviceID: ?BSTR,
pEventGUID: ?*const Guid,
bstrCommandline: ?BSTR,
bstrName: ?BSTR,
bstrDescription: ?BSTR,
bstrIcon: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RegisterEventCallbackInterface: fn(
self: *const IWiaDevMgr,
lFlags: i32,
bstrDeviceID: ?BSTR,
pEventGUID: ?*const Guid,
pIWiaEventCallback: ?*IWiaEventCallback,
pEventObject: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RegisterEventCallbackCLSID: fn(
self: *const IWiaDevMgr,
lFlags: i32,
bstrDeviceID: ?BSTR,
pEventGUID: ?*const Guid,
pClsID: ?*const Guid,
bstrName: ?BSTR,
bstrDescription: ?BSTR,
bstrIcon: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddDeviceDlg: fn(
self: *const IWiaDevMgr,
hwndParent: ?HWND,
lFlags: 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 IWiaDevMgr_EnumDeviceInfo(self: *const T, lFlag: i32, ppIEnum: ?*?*IEnumWIA_DEV_INFO) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDevMgr.VTable, self.vtable).EnumDeviceInfo(@ptrCast(*const IWiaDevMgr, self), lFlag, ppIEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaDevMgr_CreateDevice(self: *const T, bstrDeviceID: ?BSTR, ppWiaItemRoot: ?*?*IWiaItem) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDevMgr.VTable, self.vtable).CreateDevice(@ptrCast(*const IWiaDevMgr, self), bstrDeviceID, ppWiaItemRoot);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaDevMgr_SelectDeviceDlg(self: *const T, hwndParent: ?HWND, lDeviceType: i32, lFlags: i32, pbstrDeviceID: ?*?BSTR, ppItemRoot: ?*?*IWiaItem) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDevMgr.VTable, self.vtable).SelectDeviceDlg(@ptrCast(*const IWiaDevMgr, self), hwndParent, lDeviceType, lFlags, pbstrDeviceID, ppItemRoot);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaDevMgr_SelectDeviceDlgID(self: *const T, hwndParent: ?HWND, lDeviceType: i32, lFlags: i32, pbstrDeviceID: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDevMgr.VTable, self.vtable).SelectDeviceDlgID(@ptrCast(*const IWiaDevMgr, self), hwndParent, lDeviceType, lFlags, pbstrDeviceID);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaDevMgr_GetImageDlg(self: *const T, hwndParent: ?HWND, lDeviceType: i32, lFlags: i32, lIntent: i32, pItemRoot: ?*IWiaItem, bstrFilename: ?BSTR, pguidFormat: ?*Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDevMgr.VTable, self.vtable).GetImageDlg(@ptrCast(*const IWiaDevMgr, self), hwndParent, lDeviceType, lFlags, lIntent, pItemRoot, bstrFilename, pguidFormat);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaDevMgr_RegisterEventCallbackProgram(self: *const T, lFlags: i32, bstrDeviceID: ?BSTR, pEventGUID: ?*const Guid, bstrCommandline: ?BSTR, bstrName: ?BSTR, bstrDescription: ?BSTR, bstrIcon: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDevMgr.VTable, self.vtable).RegisterEventCallbackProgram(@ptrCast(*const IWiaDevMgr, self), lFlags, bstrDeviceID, pEventGUID, bstrCommandline, bstrName, bstrDescription, bstrIcon);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaDevMgr_RegisterEventCallbackInterface(self: *const T, lFlags: i32, bstrDeviceID: ?BSTR, pEventGUID: ?*const Guid, pIWiaEventCallback: ?*IWiaEventCallback, pEventObject: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDevMgr.VTable, self.vtable).RegisterEventCallbackInterface(@ptrCast(*const IWiaDevMgr, self), lFlags, bstrDeviceID, pEventGUID, pIWiaEventCallback, pEventObject);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaDevMgr_RegisterEventCallbackCLSID(self: *const T, lFlags: i32, bstrDeviceID: ?BSTR, pEventGUID: ?*const Guid, pClsID: ?*const Guid, bstrName: ?BSTR, bstrDescription: ?BSTR, bstrIcon: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDevMgr.VTable, self.vtable).RegisterEventCallbackCLSID(@ptrCast(*const IWiaDevMgr, self), lFlags, bstrDeviceID, pEventGUID, pClsID, bstrName, bstrDescription, bstrIcon);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaDevMgr_AddDeviceDlg(self: *const T, hwndParent: ?HWND, lFlags: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDevMgr.VTable, self.vtable).AddDeviceDlg(@ptrCast(*const IWiaDevMgr, self), hwndParent, lFlags);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.0'
const IID_IEnumWIA_DEV_INFO_Value = Guid.initString("5e38b83c-8cf1-11d1-bf92-0060081ed811");
pub const IID_IEnumWIA_DEV_INFO = &IID_IEnumWIA_DEV_INFO_Value;
pub const IEnumWIA_DEV_INFO = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Next: fn(
self: *const IEnumWIA_DEV_INFO,
celt: u32,
rgelt: ?*?*IWiaPropertyStorage,
pceltFetched: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Skip: fn(
self: *const IEnumWIA_DEV_INFO,
celt: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reset: fn(
self: *const IEnumWIA_DEV_INFO,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clone: fn(
self: *const IEnumWIA_DEV_INFO,
ppIEnum: ?*?*IEnumWIA_DEV_INFO,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCount: fn(
self: *const IEnumWIA_DEV_INFO,
celt: ?*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 IEnumWIA_DEV_INFO_Next(self: *const T, celt: u32, rgelt: ?*?*IWiaPropertyStorage, pceltFetched: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumWIA_DEV_INFO.VTable, self.vtable).Next(@ptrCast(*const IEnumWIA_DEV_INFO, self), celt, rgelt, pceltFetched);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumWIA_DEV_INFO_Skip(self: *const T, celt: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumWIA_DEV_INFO.VTable, self.vtable).Skip(@ptrCast(*const IEnumWIA_DEV_INFO, self), celt);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumWIA_DEV_INFO_Reset(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumWIA_DEV_INFO.VTable, self.vtable).Reset(@ptrCast(*const IEnumWIA_DEV_INFO, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumWIA_DEV_INFO_Clone(self: *const T, ppIEnum: ?*?*IEnumWIA_DEV_INFO) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumWIA_DEV_INFO.VTable, self.vtable).Clone(@ptrCast(*const IEnumWIA_DEV_INFO, self), ppIEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumWIA_DEV_INFO_GetCount(self: *const T, celt: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumWIA_DEV_INFO.VTable, self.vtable).GetCount(@ptrCast(*const IEnumWIA_DEV_INFO, self), celt);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.0'
const IID_IWiaEventCallback_Value = Guid.initString("ae6287b0-0084-11d2-973b-00a0c9068f2e");
pub const IID_IWiaEventCallback = &IID_IWiaEventCallback_Value;
pub const IWiaEventCallback = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
ImageEventCallback: fn(
self: *const IWiaEventCallback,
pEventGUID: ?*const Guid,
bstrEventDescription: ?BSTR,
bstrDeviceID: ?BSTR,
bstrDeviceDescription: ?BSTR,
dwDeviceType: u32,
bstrFullItemName: ?BSTR,
pulEventType: ?*u32,
ulReserved: 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 IWiaEventCallback_ImageEventCallback(self: *const T, pEventGUID: ?*const Guid, bstrEventDescription: ?BSTR, bstrDeviceID: ?BSTR, bstrDeviceDescription: ?BSTR, dwDeviceType: u32, bstrFullItemName: ?BSTR, pulEventType: ?*u32, ulReserved: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaEventCallback.VTable, self.vtable).ImageEventCallback(@ptrCast(*const IWiaEventCallback, self), pEventGUID, bstrEventDescription, bstrDeviceID, bstrDeviceDescription, dwDeviceType, bstrFullItemName, pulEventType, ulReserved);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const WIA_DATA_CALLBACK_HEADER = extern struct {
lSize: i32,
guidFormatID: Guid,
lBufferSize: i32,
lPageCount: i32,
};
// TODO: this type is limited to platform 'windows5.0'
const IID_IWiaDataCallback_Value = Guid.initString("a558a866-a5b0-11d2-a08f-00c04f72dc3c");
pub const IID_IWiaDataCallback = &IID_IWiaDataCallback_Value;
pub const IWiaDataCallback = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
BandedDataCallback: fn(
self: *const IWiaDataCallback,
lMessage: i32,
lStatus: i32,
lPercentComplete: i32,
lOffset: i32,
lLength: i32,
lReserved: i32,
lResLength: i32,
pbBuffer: ?*u8,
) 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 IWiaDataCallback_BandedDataCallback(self: *const T, lMessage: i32, lStatus: i32, lPercentComplete: i32, lOffset: i32, lLength: i32, lReserved: i32, lResLength: i32, pbBuffer: ?*u8) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDataCallback.VTable, self.vtable).BandedDataCallback(@ptrCast(*const IWiaDataCallback, self), lMessage, lStatus, lPercentComplete, lOffset, lLength, lReserved, lResLength, pbBuffer);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const WIA_DATA_TRANSFER_INFO = extern struct {
ulSize: u32,
ulSection: u32,
ulBufferSize: u32,
bDoubleBuffer: BOOL,
ulReserved1: u32,
ulReserved2: u32,
ulReserved3: u32,
};
pub const WIA_EXTENDED_TRANSFER_INFO = extern struct {
ulSize: u32,
ulMinBufferSize: u32,
ulOptimalBufferSize: u32,
ulMaxBufferSize: u32,
ulNumBuffers: u32,
};
// TODO: this type is limited to platform 'windows5.0'
const IID_IWiaDataTransfer_Value = Guid.initString("a6cef998-a5b0-11d2-a08f-00c04f72dc3c");
pub const IID_IWiaDataTransfer = &IID_IWiaDataTransfer_Value;
pub const IWiaDataTransfer = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
idtGetData: fn(
self: *const IWiaDataTransfer,
pMedium: ?*STGMEDIUM,
pIWiaDataCallback: ?*IWiaDataCallback,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
idtGetBandedData: fn(
self: *const IWiaDataTransfer,
pWiaDataTransInfo: ?*WIA_DATA_TRANSFER_INFO,
pIWiaDataCallback: ?*IWiaDataCallback,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
idtQueryGetData: fn(
self: *const IWiaDataTransfer,
pfe: ?*WIA_FORMAT_INFO,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
idtEnumWIA_FORMAT_INFO: fn(
self: *const IWiaDataTransfer,
ppEnum: ?*?*IEnumWIA_FORMAT_INFO,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
idtGetExtendedTransferInfo: fn(
self: *const IWiaDataTransfer,
pExtendedTransferInfo: ?*WIA_EXTENDED_TRANSFER_INFO,
) 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 IWiaDataTransfer_idtGetData(self: *const T, pMedium: ?*STGMEDIUM, pIWiaDataCallback: ?*IWiaDataCallback) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDataTransfer.VTable, self.vtable).idtGetData(@ptrCast(*const IWiaDataTransfer, self), pMedium, pIWiaDataCallback);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaDataTransfer_idtGetBandedData(self: *const T, pWiaDataTransInfo: ?*WIA_DATA_TRANSFER_INFO, pIWiaDataCallback: ?*IWiaDataCallback) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDataTransfer.VTable, self.vtable).idtGetBandedData(@ptrCast(*const IWiaDataTransfer, self), pWiaDataTransInfo, pIWiaDataCallback);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaDataTransfer_idtQueryGetData(self: *const T, pfe: ?*WIA_FORMAT_INFO) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDataTransfer.VTable, self.vtable).idtQueryGetData(@ptrCast(*const IWiaDataTransfer, self), pfe);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaDataTransfer_idtEnumWIA_FORMAT_INFO(self: *const T, ppEnum: ?*?*IEnumWIA_FORMAT_INFO) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDataTransfer.VTable, self.vtable).idtEnumWIA_FORMAT_INFO(@ptrCast(*const IWiaDataTransfer, self), ppEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaDataTransfer_idtGetExtendedTransferInfo(self: *const T, pExtendedTransferInfo: ?*WIA_EXTENDED_TRANSFER_INFO) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDataTransfer.VTable, self.vtable).idtGetExtendedTransferInfo(@ptrCast(*const IWiaDataTransfer, self), pExtendedTransferInfo);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.0'
const IID_IWiaItem_Value = Guid.initString("4db1ad10-3391-11d2-9a33-00c04fa36145");
pub const IID_IWiaItem = &IID_IWiaItem_Value;
pub const IWiaItem = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetItemType: fn(
self: *const IWiaItem,
pItemType: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AnalyzeItem: fn(
self: *const IWiaItem,
lFlags: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EnumChildItems: fn(
self: *const IWiaItem,
ppIEnumWiaItem: ?*?*IEnumWiaItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DeleteItem: fn(
self: *const IWiaItem,
lFlags: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateChildItem: fn(
self: *const IWiaItem,
lFlags: i32,
bstrItemName: ?BSTR,
bstrFullItemName: ?BSTR,
ppIWiaItem: ?*?*IWiaItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EnumRegisterEventInfo: fn(
self: *const IWiaItem,
lFlags: i32,
pEventGUID: ?*const Guid,
ppIEnum: ?*?*IEnumWIA_DEV_CAPS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FindItemByName: fn(
self: *const IWiaItem,
lFlags: i32,
bstrFullItemName: ?BSTR,
ppIWiaItem: ?*?*IWiaItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DeviceDlg: fn(
self: *const IWiaItem,
hwndParent: ?HWND,
lFlags: i32,
lIntent: i32,
plItemCount: ?*i32,
ppIWiaItem: ?*?*?*IWiaItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DeviceCommand: fn(
self: *const IWiaItem,
lFlags: i32,
pCmdGUID: ?*const Guid,
pIWiaItem: ?*?*IWiaItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetRootItem: fn(
self: *const IWiaItem,
ppIWiaItem: ?*?*IWiaItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EnumDeviceCapabilities: fn(
self: *const IWiaItem,
lFlags: i32,
ppIEnumWIA_DEV_CAPS: ?*?*IEnumWIA_DEV_CAPS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DumpItemData: fn(
self: *const IWiaItem,
bstrData: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DumpDrvItemData: fn(
self: *const IWiaItem,
bstrData: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DumpTreeItemData: fn(
self: *const IWiaItem,
bstrData: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Diagnostic: fn(
self: *const IWiaItem,
ulSize: u32,
pBuffer: [*:0]u8,
) 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 IWiaItem_GetItemType(self: *const T, pItemType: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItem.VTable, self.vtable).GetItemType(@ptrCast(*const IWiaItem, self), pItemType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaItem_AnalyzeItem(self: *const T, lFlags: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItem.VTable, self.vtable).AnalyzeItem(@ptrCast(*const IWiaItem, self), lFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaItem_EnumChildItems(self: *const T, ppIEnumWiaItem: ?*?*IEnumWiaItem) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItem.VTable, self.vtable).EnumChildItems(@ptrCast(*const IWiaItem, self), ppIEnumWiaItem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaItem_DeleteItem(self: *const T, lFlags: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItem.VTable, self.vtable).DeleteItem(@ptrCast(*const IWiaItem, self), lFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaItem_CreateChildItem(self: *const T, lFlags: i32, bstrItemName: ?BSTR, bstrFullItemName: ?BSTR, ppIWiaItem: ?*?*IWiaItem) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItem.VTable, self.vtable).CreateChildItem(@ptrCast(*const IWiaItem, self), lFlags, bstrItemName, bstrFullItemName, ppIWiaItem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaItem_EnumRegisterEventInfo(self: *const T, lFlags: i32, pEventGUID: ?*const Guid, ppIEnum: ?*?*IEnumWIA_DEV_CAPS) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItem.VTable, self.vtable).EnumRegisterEventInfo(@ptrCast(*const IWiaItem, self), lFlags, pEventGUID, ppIEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaItem_FindItemByName(self: *const T, lFlags: i32, bstrFullItemName: ?BSTR, ppIWiaItem: ?*?*IWiaItem) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItem.VTable, self.vtable).FindItemByName(@ptrCast(*const IWiaItem, self), lFlags, bstrFullItemName, ppIWiaItem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaItem_DeviceDlg(self: *const T, hwndParent: ?HWND, lFlags: i32, lIntent: i32, plItemCount: ?*i32, ppIWiaItem: ?*?*?*IWiaItem) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItem.VTable, self.vtable).DeviceDlg(@ptrCast(*const IWiaItem, self), hwndParent, lFlags, lIntent, plItemCount, ppIWiaItem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaItem_DeviceCommand(self: *const T, lFlags: i32, pCmdGUID: ?*const Guid, pIWiaItem: ?*?*IWiaItem) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItem.VTable, self.vtable).DeviceCommand(@ptrCast(*const IWiaItem, self), lFlags, pCmdGUID, pIWiaItem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaItem_GetRootItem(self: *const T, ppIWiaItem: ?*?*IWiaItem) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItem.VTable, self.vtable).GetRootItem(@ptrCast(*const IWiaItem, self), ppIWiaItem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaItem_EnumDeviceCapabilities(self: *const T, lFlags: i32, ppIEnumWIA_DEV_CAPS: ?*?*IEnumWIA_DEV_CAPS) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItem.VTable, self.vtable).EnumDeviceCapabilities(@ptrCast(*const IWiaItem, self), lFlags, ppIEnumWIA_DEV_CAPS);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaItem_DumpItemData(self: *const T, bstrData: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItem.VTable, self.vtable).DumpItemData(@ptrCast(*const IWiaItem, self), bstrData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaItem_DumpDrvItemData(self: *const T, bstrData: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItem.VTable, self.vtable).DumpDrvItemData(@ptrCast(*const IWiaItem, self), bstrData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaItem_DumpTreeItemData(self: *const T, bstrData: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItem.VTable, self.vtable).DumpTreeItemData(@ptrCast(*const IWiaItem, self), bstrData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaItem_Diagnostic(self: *const T, ulSize: u32, pBuffer: [*:0]u8) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItem.VTable, self.vtable).Diagnostic(@ptrCast(*const IWiaItem, self), ulSize, pBuffer);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.0'
const IID_IWiaPropertyStorage_Value = Guid.initString("98b5e8a0-29cc-491a-aac0-e6db4fdcceb6");
pub const IID_IWiaPropertyStorage = &IID_IWiaPropertyStorage_Value;
pub const IWiaPropertyStorage = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
ReadMultiple: fn(
self: *const IWiaPropertyStorage,
cpspec: u32,
rgpspec: [*]const PROPSPEC,
rgpropvar: [*]PROPVARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteMultiple: fn(
self: *const IWiaPropertyStorage,
cpspec: u32,
rgpspec: ?*const PROPSPEC,
rgpropvar: ?*const PROPVARIANT,
propidNameFirst: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DeleteMultiple: fn(
self: *const IWiaPropertyStorage,
cpspec: u32,
rgpspec: [*]const PROPSPEC,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ReadPropertyNames: fn(
self: *const IWiaPropertyStorage,
cpropid: u32,
rgpropid: [*]const u32,
rglpwstrName: [*]?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WritePropertyNames: fn(
self: *const IWiaPropertyStorage,
cpropid: u32,
rgpropid: [*]const u32,
rglpwstrName: [*]const ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DeletePropertyNames: fn(
self: *const IWiaPropertyStorage,
cpropid: u32,
rgpropid: [*]const u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Commit: fn(
self: *const IWiaPropertyStorage,
grfCommitFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Revert: fn(
self: *const IWiaPropertyStorage,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Enum: fn(
self: *const IWiaPropertyStorage,
ppenum: ?*?*IEnumSTATPROPSTG,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetTimes: fn(
self: *const IWiaPropertyStorage,
pctime: ?*const FILETIME,
patime: ?*const FILETIME,
pmtime: ?*const FILETIME,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetClass: fn(
self: *const IWiaPropertyStorage,
clsid: ?*const Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Stat: fn(
self: *const IWiaPropertyStorage,
pstatpsstg: ?*STATPROPSETSTG,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPropertyAttributes: fn(
self: *const IWiaPropertyStorage,
cpspec: u32,
rgpspec: [*]PROPSPEC,
rgflags: [*]u32,
rgpropvar: [*]PROPVARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCount: fn(
self: *const IWiaPropertyStorage,
pulNumProps: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPropertyStream: fn(
self: *const IWiaPropertyStorage,
pCompatibilityId: ?*Guid,
ppIStream: ?*?*IStream,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetPropertyStream: fn(
self: *const IWiaPropertyStorage,
pCompatibilityId: ?*Guid,
pIStream: ?*IStream,
) 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 IWiaPropertyStorage_ReadMultiple(self: *const T, cpspec: u32, rgpspec: [*]const PROPSPEC, rgpropvar: [*]PROPVARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaPropertyStorage.VTable, self.vtable).ReadMultiple(@ptrCast(*const IWiaPropertyStorage, self), cpspec, rgpspec, rgpropvar);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaPropertyStorage_WriteMultiple(self: *const T, cpspec: u32, rgpspec: ?*const PROPSPEC, rgpropvar: ?*const PROPVARIANT, propidNameFirst: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaPropertyStorage.VTable, self.vtable).WriteMultiple(@ptrCast(*const IWiaPropertyStorage, self), cpspec, rgpspec, rgpropvar, propidNameFirst);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaPropertyStorage_DeleteMultiple(self: *const T, cpspec: u32, rgpspec: [*]const PROPSPEC) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaPropertyStorage.VTable, self.vtable).DeleteMultiple(@ptrCast(*const IWiaPropertyStorage, self), cpspec, rgpspec);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaPropertyStorage_ReadPropertyNames(self: *const T, cpropid: u32, rgpropid: [*]const u32, rglpwstrName: [*]?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaPropertyStorage.VTable, self.vtable).ReadPropertyNames(@ptrCast(*const IWiaPropertyStorage, self), cpropid, rgpropid, rglpwstrName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaPropertyStorage_WritePropertyNames(self: *const T, cpropid: u32, rgpropid: [*]const u32, rglpwstrName: [*]const ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaPropertyStorage.VTable, self.vtable).WritePropertyNames(@ptrCast(*const IWiaPropertyStorage, self), cpropid, rgpropid, rglpwstrName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaPropertyStorage_DeletePropertyNames(self: *const T, cpropid: u32, rgpropid: [*]const u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaPropertyStorage.VTable, self.vtable).DeletePropertyNames(@ptrCast(*const IWiaPropertyStorage, self), cpropid, rgpropid);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaPropertyStorage_Commit(self: *const T, grfCommitFlags: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaPropertyStorage.VTable, self.vtable).Commit(@ptrCast(*const IWiaPropertyStorage, self), grfCommitFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaPropertyStorage_Revert(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaPropertyStorage.VTable, self.vtable).Revert(@ptrCast(*const IWiaPropertyStorage, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaPropertyStorage_Enum(self: *const T, ppenum: ?*?*IEnumSTATPROPSTG) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaPropertyStorage.VTable, self.vtable).Enum(@ptrCast(*const IWiaPropertyStorage, self), ppenum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaPropertyStorage_SetTimes(self: *const T, pctime: ?*const FILETIME, patime: ?*const FILETIME, pmtime: ?*const FILETIME) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaPropertyStorage.VTable, self.vtable).SetTimes(@ptrCast(*const IWiaPropertyStorage, self), pctime, patime, pmtime);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaPropertyStorage_SetClass(self: *const T, clsid: ?*const Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaPropertyStorage.VTable, self.vtable).SetClass(@ptrCast(*const IWiaPropertyStorage, self), clsid);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaPropertyStorage_Stat(self: *const T, pstatpsstg: ?*STATPROPSETSTG) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaPropertyStorage.VTable, self.vtable).Stat(@ptrCast(*const IWiaPropertyStorage, self), pstatpsstg);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaPropertyStorage_GetPropertyAttributes(self: *const T, cpspec: u32, rgpspec: [*]PROPSPEC, rgflags: [*]u32, rgpropvar: [*]PROPVARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaPropertyStorage.VTable, self.vtable).GetPropertyAttributes(@ptrCast(*const IWiaPropertyStorage, self), cpspec, rgpspec, rgflags, rgpropvar);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaPropertyStorage_GetCount(self: *const T, pulNumProps: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaPropertyStorage.VTable, self.vtable).GetCount(@ptrCast(*const IWiaPropertyStorage, self), pulNumProps);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaPropertyStorage_GetPropertyStream(self: *const T, pCompatibilityId: ?*Guid, ppIStream: ?*?*IStream) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaPropertyStorage.VTable, self.vtable).GetPropertyStream(@ptrCast(*const IWiaPropertyStorage, self), pCompatibilityId, ppIStream);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaPropertyStorage_SetPropertyStream(self: *const T, pCompatibilityId: ?*Guid, pIStream: ?*IStream) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaPropertyStorage.VTable, self.vtable).SetPropertyStream(@ptrCast(*const IWiaPropertyStorage, self), pCompatibilityId, pIStream);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.0'
const IID_IEnumWiaItem_Value = Guid.initString("5e8383fc-3391-11d2-9a33-00c04fa36145");
pub const IID_IEnumWiaItem = &IID_IEnumWiaItem_Value;
pub const IEnumWiaItem = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Next: fn(
self: *const IEnumWiaItem,
celt: u32,
ppIWiaItem: ?*?*IWiaItem,
pceltFetched: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Skip: fn(
self: *const IEnumWiaItem,
celt: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reset: fn(
self: *const IEnumWiaItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clone: fn(
self: *const IEnumWiaItem,
ppIEnum: ?*?*IEnumWiaItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCount: fn(
self: *const IEnumWiaItem,
celt: ?*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 IEnumWiaItem_Next(self: *const T, celt: u32, ppIWiaItem: ?*?*IWiaItem, pceltFetched: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumWiaItem.VTable, self.vtable).Next(@ptrCast(*const IEnumWiaItem, self), celt, ppIWiaItem, pceltFetched);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumWiaItem_Skip(self: *const T, celt: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumWiaItem.VTable, self.vtable).Skip(@ptrCast(*const IEnumWiaItem, self), celt);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumWiaItem_Reset(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumWiaItem.VTable, self.vtable).Reset(@ptrCast(*const IEnumWiaItem, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumWiaItem_Clone(self: *const T, ppIEnum: ?*?*IEnumWiaItem) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumWiaItem.VTable, self.vtable).Clone(@ptrCast(*const IEnumWiaItem, self), ppIEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumWiaItem_GetCount(self: *const T, celt: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumWiaItem.VTable, self.vtable).GetCount(@ptrCast(*const IEnumWiaItem, self), celt);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const WIA_DEV_CAP = extern struct {
guid: Guid,
ulFlags: u32,
bstrName: ?BSTR,
bstrDescription: ?BSTR,
bstrIcon: ?BSTR,
bstrCommandline: ?BSTR,
};
// TODO: this type is limited to platform 'windows5.0'
const IID_IEnumWIA_DEV_CAPS_Value = Guid.initString("1fcc4287-aca6-11d2-a093-00c04f72dc3c");
pub const IID_IEnumWIA_DEV_CAPS = &IID_IEnumWIA_DEV_CAPS_Value;
pub const IEnumWIA_DEV_CAPS = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Next: fn(
self: *const IEnumWIA_DEV_CAPS,
celt: u32,
rgelt: ?*WIA_DEV_CAP,
pceltFetched: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Skip: fn(
self: *const IEnumWIA_DEV_CAPS,
celt: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reset: fn(
self: *const IEnumWIA_DEV_CAPS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clone: fn(
self: *const IEnumWIA_DEV_CAPS,
ppIEnum: ?*?*IEnumWIA_DEV_CAPS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCount: fn(
self: *const IEnumWIA_DEV_CAPS,
pcelt: ?*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 IEnumWIA_DEV_CAPS_Next(self: *const T, celt: u32, rgelt: ?*WIA_DEV_CAP, pceltFetched: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumWIA_DEV_CAPS.VTable, self.vtable).Next(@ptrCast(*const IEnumWIA_DEV_CAPS, self), celt, rgelt, pceltFetched);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumWIA_DEV_CAPS_Skip(self: *const T, celt: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumWIA_DEV_CAPS.VTable, self.vtable).Skip(@ptrCast(*const IEnumWIA_DEV_CAPS, self), celt);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumWIA_DEV_CAPS_Reset(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumWIA_DEV_CAPS.VTable, self.vtable).Reset(@ptrCast(*const IEnumWIA_DEV_CAPS, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumWIA_DEV_CAPS_Clone(self: *const T, ppIEnum: ?*?*IEnumWIA_DEV_CAPS) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumWIA_DEV_CAPS.VTable, self.vtable).Clone(@ptrCast(*const IEnumWIA_DEV_CAPS, self), ppIEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumWIA_DEV_CAPS_GetCount(self: *const T, pcelt: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumWIA_DEV_CAPS.VTable, self.vtable).GetCount(@ptrCast(*const IEnumWIA_DEV_CAPS, self), pcelt);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.0'
const IID_IEnumWIA_FORMAT_INFO_Value = Guid.initString("81befc5b-656d-44f1-b24c-d41d51b4dc81");
pub const IID_IEnumWIA_FORMAT_INFO = &IID_IEnumWIA_FORMAT_INFO_Value;
pub const IEnumWIA_FORMAT_INFO = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Next: fn(
self: *const IEnumWIA_FORMAT_INFO,
celt: u32,
rgelt: ?*WIA_FORMAT_INFO,
pceltFetched: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Skip: fn(
self: *const IEnumWIA_FORMAT_INFO,
celt: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reset: fn(
self: *const IEnumWIA_FORMAT_INFO,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clone: fn(
self: *const IEnumWIA_FORMAT_INFO,
ppIEnum: ?*?*IEnumWIA_FORMAT_INFO,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCount: fn(
self: *const IEnumWIA_FORMAT_INFO,
pcelt: ?*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 IEnumWIA_FORMAT_INFO_Next(self: *const T, celt: u32, rgelt: ?*WIA_FORMAT_INFO, pceltFetched: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumWIA_FORMAT_INFO.VTable, self.vtable).Next(@ptrCast(*const IEnumWIA_FORMAT_INFO, self), celt, rgelt, pceltFetched);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumWIA_FORMAT_INFO_Skip(self: *const T, celt: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumWIA_FORMAT_INFO.VTable, self.vtable).Skip(@ptrCast(*const IEnumWIA_FORMAT_INFO, self), celt);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumWIA_FORMAT_INFO_Reset(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumWIA_FORMAT_INFO.VTable, self.vtable).Reset(@ptrCast(*const IEnumWIA_FORMAT_INFO, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumWIA_FORMAT_INFO_Clone(self: *const T, ppIEnum: ?*?*IEnumWIA_FORMAT_INFO) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumWIA_FORMAT_INFO.VTable, self.vtable).Clone(@ptrCast(*const IEnumWIA_FORMAT_INFO, self), ppIEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumWIA_FORMAT_INFO_GetCount(self: *const T, pcelt: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumWIA_FORMAT_INFO.VTable, self.vtable).GetCount(@ptrCast(*const IEnumWIA_FORMAT_INFO, self), pcelt);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.0'
const IID_IWiaLog_Value = Guid.initString("a00c10b6-82a1-452f-8b6c-86062aad6890");
pub const IID_IWiaLog = &IID_IWiaLog_Value;
pub const IWiaLog = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
InitializeLog: fn(
self: *const IWiaLog,
hInstance: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
hResult: fn(
self: *const IWiaLog,
hResult: HRESULT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Log: fn(
self: *const IWiaLog,
lFlags: i32,
lResID: i32,
lDetail: i32,
bstrText: ?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 IWiaLog_InitializeLog(self: *const T, hInstance: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaLog.VTable, self.vtable).InitializeLog(@ptrCast(*const IWiaLog, self), hInstance);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaLog_hResult(self: *const T, hResult: HRESULT) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaLog.VTable, self.vtable).hResult(@ptrCast(*const IWiaLog, self), hResult);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaLog_Log(self: *const T, lFlags: i32, lResID: i32, lDetail: i32, bstrText: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaLog.VTable, self.vtable).Log(@ptrCast(*const IWiaLog, self), lFlags, lResID, lDetail, bstrText);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.0'
const IID_IWiaLogEx_Value = Guid.initString("af1f22ac-7a40-4787-b421-aeb47a1fbd0b");
pub const IID_IWiaLogEx = &IID_IWiaLogEx_Value;
pub const IWiaLogEx = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
InitializeLogEx: fn(
self: *const IWiaLogEx,
hInstance: ?*u8,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
hResult: fn(
self: *const IWiaLogEx,
hResult: HRESULT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Log: fn(
self: *const IWiaLogEx,
lFlags: i32,
lResID: i32,
lDetail: i32,
bstrText: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
hResultEx: fn(
self: *const IWiaLogEx,
lMethodId: i32,
hResult: HRESULT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
LogEx: fn(
self: *const IWiaLogEx,
lMethodId: i32,
lFlags: i32,
lResID: i32,
lDetail: i32,
bstrText: ?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 IWiaLogEx_InitializeLogEx(self: *const T, hInstance: ?*u8) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaLogEx.VTable, self.vtable).InitializeLogEx(@ptrCast(*const IWiaLogEx, self), hInstance);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaLogEx_hResult(self: *const T, hResult: HRESULT) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaLogEx.VTable, self.vtable).hResult(@ptrCast(*const IWiaLogEx, self), hResult);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaLogEx_Log(self: *const T, lFlags: i32, lResID: i32, lDetail: i32, bstrText: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaLogEx.VTable, self.vtable).Log(@ptrCast(*const IWiaLogEx, self), lFlags, lResID, lDetail, bstrText);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaLogEx_hResultEx(self: *const T, lMethodId: i32, hResult: HRESULT) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaLogEx.VTable, self.vtable).hResultEx(@ptrCast(*const IWiaLogEx, self), lMethodId, hResult);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaLogEx_LogEx(self: *const T, lMethodId: i32, lFlags: i32, lResID: i32, lDetail: i32, bstrText: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaLogEx.VTable, self.vtable).LogEx(@ptrCast(*const IWiaLogEx, self), lMethodId, lFlags, lResID, lDetail, bstrText);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.0'
const IID_IWiaNotifyDevMgr_Value = Guid.initString("70681ea0-e7bf-4291-9fb1-4e8813a3f78e");
pub const IID_IWiaNotifyDevMgr = &IID_IWiaNotifyDevMgr_Value;
pub const IWiaNotifyDevMgr = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
NewDeviceArrival: fn(
self: *const IWiaNotifyDevMgr,
) 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 IWiaNotifyDevMgr_NewDeviceArrival(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaNotifyDevMgr.VTable, self.vtable).NewDeviceArrival(@ptrCast(*const IWiaNotifyDevMgr, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.0'
const IID_IWiaItemExtras_Value = Guid.initString("6291ef2c-36ef-4532-876a-8e132593778d");
pub const IID_IWiaItemExtras = &IID_IWiaItemExtras_Value;
pub const IWiaItemExtras = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetExtendedErrorInfo: fn(
self: *const IWiaItemExtras,
bstrErrorText: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Escape: fn(
self: *const IWiaItemExtras,
dwEscapeCode: u32,
lpInData: [*:0]u8,
cbInDataSize: u32,
pOutData: ?*u8,
dwOutDataSize: u32,
pdwActualDataSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CancelPendingIO: fn(
self: *const IWiaItemExtras,
) 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 IWiaItemExtras_GetExtendedErrorInfo(self: *const T, bstrErrorText: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItemExtras.VTable, self.vtable).GetExtendedErrorInfo(@ptrCast(*const IWiaItemExtras, self), bstrErrorText);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaItemExtras_Escape(self: *const T, dwEscapeCode: u32, lpInData: [*:0]u8, cbInDataSize: u32, pOutData: ?*u8, dwOutDataSize: u32, pdwActualDataSize: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItemExtras.VTable, self.vtable).Escape(@ptrCast(*const IWiaItemExtras, self), dwEscapeCode, lpInData, cbInDataSize, pOutData, dwOutDataSize, pdwActualDataSize);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaItemExtras_CancelPendingIO(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItemExtras.VTable, self.vtable).CancelPendingIO(@ptrCast(*const IWiaItemExtras, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWiaAppErrorHandler_Value = Guid.initString("6c16186c-d0a6-400c-80f4-d26986a0e734");
pub const IID_IWiaAppErrorHandler = &IID_IWiaAppErrorHandler_Value;
pub const IWiaAppErrorHandler = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetWindow: fn(
self: *const IWiaAppErrorHandler,
phwnd: ?*?HWND,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ReportStatus: fn(
self: *const IWiaAppErrorHandler,
lFlags: i32,
pWiaItem2: ?*IWiaItem2,
hrStatus: HRESULT,
lPercentComplete: 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 IWiaAppErrorHandler_GetWindow(self: *const T, phwnd: ?*?HWND) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaAppErrorHandler.VTable, self.vtable).GetWindow(@ptrCast(*const IWiaAppErrorHandler, self), phwnd);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaAppErrorHandler_ReportStatus(self: *const T, lFlags: i32, pWiaItem2: ?*IWiaItem2, hrStatus: HRESULT, lPercentComplete: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaAppErrorHandler.VTable, self.vtable).ReportStatus(@ptrCast(*const IWiaAppErrorHandler, self), lFlags, pWiaItem2, hrStatus, lPercentComplete);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWiaErrorHandler_Value = Guid.initString("0e4a51b1-bc1f-443d-a835-72e890759ef3");
pub const IID_IWiaErrorHandler = &IID_IWiaErrorHandler_Value;
pub const IWiaErrorHandler = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
ReportStatus: fn(
self: *const IWiaErrorHandler,
lFlags: i32,
hwndParent: ?HWND,
pWiaItem2: ?*IWiaItem2,
hrStatus: HRESULT,
lPercentComplete: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetStatusDescription: fn(
self: *const IWiaErrorHandler,
lFlags: i32,
pWiaItem2: ?*IWiaItem2,
hrStatus: HRESULT,
pbstrDescription: ?*?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 IWiaErrorHandler_ReportStatus(self: *const T, lFlags: i32, hwndParent: ?HWND, pWiaItem2: ?*IWiaItem2, hrStatus: HRESULT, lPercentComplete: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaErrorHandler.VTable, self.vtable).ReportStatus(@ptrCast(*const IWiaErrorHandler, self), lFlags, hwndParent, pWiaItem2, hrStatus, lPercentComplete);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaErrorHandler_GetStatusDescription(self: *const T, lFlags: i32, pWiaItem2: ?*IWiaItem2, hrStatus: HRESULT, pbstrDescription: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaErrorHandler.VTable, self.vtable).GetStatusDescription(@ptrCast(*const IWiaErrorHandler, self), lFlags, pWiaItem2, hrStatus, pbstrDescription);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWiaTransfer_Value = Guid.initString("c39d6942-2f4e-4d04-92fe-4ef4d3a1de5a");
pub const IID_IWiaTransfer = &IID_IWiaTransfer_Value;
pub const IWiaTransfer = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Download: fn(
self: *const IWiaTransfer,
lFlags: i32,
pIWiaTransferCallback: ?*IWiaTransferCallback,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Upload: fn(
self: *const IWiaTransfer,
lFlags: i32,
pSource: ?*IStream,
pIWiaTransferCallback: ?*IWiaTransferCallback,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Cancel: fn(
self: *const IWiaTransfer,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EnumWIA_FORMAT_INFO: fn(
self: *const IWiaTransfer,
ppEnum: ?*?*IEnumWIA_FORMAT_INFO,
) 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 IWiaTransfer_Download(self: *const T, lFlags: i32, pIWiaTransferCallback: ?*IWiaTransferCallback) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaTransfer.VTable, self.vtable).Download(@ptrCast(*const IWiaTransfer, self), lFlags, pIWiaTransferCallback);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaTransfer_Upload(self: *const T, lFlags: i32, pSource: ?*IStream, pIWiaTransferCallback: ?*IWiaTransferCallback) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaTransfer.VTable, self.vtable).Upload(@ptrCast(*const IWiaTransfer, self), lFlags, pSource, pIWiaTransferCallback);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaTransfer_Cancel(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaTransfer.VTable, self.vtable).Cancel(@ptrCast(*const IWiaTransfer, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaTransfer_EnumWIA_FORMAT_INFO(self: *const T, ppEnum: ?*?*IEnumWIA_FORMAT_INFO) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaTransfer.VTable, self.vtable).EnumWIA_FORMAT_INFO(@ptrCast(*const IWiaTransfer, self), ppEnum);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const WiaTransferParams = extern struct {
lMessage: i32,
lPercentComplete: i32,
ulTransferredBytes: u64,
hrErrorStatus: HRESULT,
};
const IID_IWiaTransferCallback_Value = Guid.initString("27d4eaaf-28a6-4ca5-9aab-e678168b9527");
pub const IID_IWiaTransferCallback = &IID_IWiaTransferCallback_Value;
pub const IWiaTransferCallback = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
TransferCallback: fn(
self: *const IWiaTransferCallback,
lFlags: i32,
pWiaTransferParams: ?*WiaTransferParams,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetNextStream: fn(
self: *const IWiaTransferCallback,
lFlags: i32,
bstrItemName: ?BSTR,
bstrFullItemName: ?BSTR,
ppDestination: ?*?*IStream,
) 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 IWiaTransferCallback_TransferCallback(self: *const T, lFlags: i32, pWiaTransferParams: ?*WiaTransferParams) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaTransferCallback.VTable, self.vtable).TransferCallback(@ptrCast(*const IWiaTransferCallback, self), lFlags, pWiaTransferParams);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaTransferCallback_GetNextStream(self: *const T, lFlags: i32, bstrItemName: ?BSTR, bstrFullItemName: ?BSTR, ppDestination: ?*?*IStream) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaTransferCallback.VTable, self.vtable).GetNextStream(@ptrCast(*const IWiaTransferCallback, self), lFlags, bstrItemName, bstrFullItemName, ppDestination);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWiaSegmentationFilter_Value = Guid.initString("ec46a697-ac04-4447-8f65-ff63d5154b21");
pub const IID_IWiaSegmentationFilter = &IID_IWiaSegmentationFilter_Value;
pub const IWiaSegmentationFilter = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
DetectRegions: fn(
self: *const IWiaSegmentationFilter,
lFlags: i32,
pInputStream: ?*IStream,
pWiaItem2: ?*IWiaItem2,
) 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 IWiaSegmentationFilter_DetectRegions(self: *const T, lFlags: i32, pInputStream: ?*IStream, pWiaItem2: ?*IWiaItem2) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaSegmentationFilter.VTable, self.vtable).DetectRegions(@ptrCast(*const IWiaSegmentationFilter, self), lFlags, pInputStream, pWiaItem2);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWiaImageFilter_Value = Guid.initString("a8a79ffa-450b-41f1-8f87-849ccd94ebf6");
pub const IID_IWiaImageFilter = &IID_IWiaImageFilter_Value;
pub const IWiaImageFilter = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
InitializeFilter: fn(
self: *const IWiaImageFilter,
pWiaItem2: ?*IWiaItem2,
pWiaTransferCallback: ?*IWiaTransferCallback,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetNewCallback: fn(
self: *const IWiaImageFilter,
pWiaTransferCallback: ?*IWiaTransferCallback,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FilterPreviewImage: fn(
self: *const IWiaImageFilter,
lFlags: i32,
pWiaChildItem2: ?*IWiaItem2,
InputImageExtents: RECT,
pInputStream: ?*IStream,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ApplyProperties: fn(
self: *const IWiaImageFilter,
pWiaPropertyStorage: ?*IWiaPropertyStorage,
) 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 IWiaImageFilter_InitializeFilter(self: *const T, pWiaItem2: ?*IWiaItem2, pWiaTransferCallback: ?*IWiaTransferCallback) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaImageFilter.VTable, self.vtable).InitializeFilter(@ptrCast(*const IWiaImageFilter, self), pWiaItem2, pWiaTransferCallback);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaImageFilter_SetNewCallback(self: *const T, pWiaTransferCallback: ?*IWiaTransferCallback) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaImageFilter.VTable, self.vtable).SetNewCallback(@ptrCast(*const IWiaImageFilter, self), pWiaTransferCallback);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaImageFilter_FilterPreviewImage(self: *const T, lFlags: i32, pWiaChildItem2: ?*IWiaItem2, InputImageExtents: RECT, pInputStream: ?*IStream) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaImageFilter.VTable, self.vtable).FilterPreviewImage(@ptrCast(*const IWiaImageFilter, self), lFlags, pWiaChildItem2, InputImageExtents, pInputStream);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaImageFilter_ApplyProperties(self: *const T, pWiaPropertyStorage: ?*IWiaPropertyStorage) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaImageFilter.VTable, self.vtable).ApplyProperties(@ptrCast(*const IWiaImageFilter, self), pWiaPropertyStorage);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWiaPreview_Value = Guid.initString("95c2b4fd-33f2-4d86-ad40-9431f0df08f7");
pub const IID_IWiaPreview = &IID_IWiaPreview_Value;
pub const IWiaPreview = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetNewPreview: fn(
self: *const IWiaPreview,
lFlags: i32,
pWiaItem2: ?*IWiaItem2,
pWiaTransferCallback: ?*IWiaTransferCallback,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UpdatePreview: fn(
self: *const IWiaPreview,
lFlags: i32,
pChildWiaItem2: ?*IWiaItem2,
pWiaTransferCallback: ?*IWiaTransferCallback,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DetectRegions: fn(
self: *const IWiaPreview,
lFlags: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clear: fn(
self: *const IWiaPreview,
) 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 IWiaPreview_GetNewPreview(self: *const T, lFlags: i32, pWiaItem2: ?*IWiaItem2, pWiaTransferCallback: ?*IWiaTransferCallback) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaPreview.VTable, self.vtable).GetNewPreview(@ptrCast(*const IWiaPreview, self), lFlags, pWiaItem2, pWiaTransferCallback);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaPreview_UpdatePreview(self: *const T, lFlags: i32, pChildWiaItem2: ?*IWiaItem2, pWiaTransferCallback: ?*IWiaTransferCallback) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaPreview.VTable, self.vtable).UpdatePreview(@ptrCast(*const IWiaPreview, self), lFlags, pChildWiaItem2, pWiaTransferCallback);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaPreview_DetectRegions(self: *const T, lFlags: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaPreview.VTable, self.vtable).DetectRegions(@ptrCast(*const IWiaPreview, self), lFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaPreview_Clear(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaPreview.VTable, self.vtable).Clear(@ptrCast(*const IWiaPreview, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IEnumWiaItem2_Value = Guid.initString("59970af4-cd0d-44d9-ab24-52295630e582");
pub const IID_IEnumWiaItem2 = &IID_IEnumWiaItem2_Value;
pub const IEnumWiaItem2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Next: fn(
self: *const IEnumWiaItem2,
cElt: u32,
ppIWiaItem2: ?*?*IWiaItem2,
pcEltFetched: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Skip: fn(
self: *const IEnumWiaItem2,
cElt: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reset: fn(
self: *const IEnumWiaItem2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clone: fn(
self: *const IEnumWiaItem2,
ppIEnum: ?*?*IEnumWiaItem2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCount: fn(
self: *const IEnumWiaItem2,
cElt: ?*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 IEnumWiaItem2_Next(self: *const T, cElt: u32, ppIWiaItem2: ?*?*IWiaItem2, pcEltFetched: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumWiaItem2.VTable, self.vtable).Next(@ptrCast(*const IEnumWiaItem2, self), cElt, ppIWiaItem2, pcEltFetched);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumWiaItem2_Skip(self: *const T, cElt: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumWiaItem2.VTable, self.vtable).Skip(@ptrCast(*const IEnumWiaItem2, self), cElt);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumWiaItem2_Reset(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumWiaItem2.VTable, self.vtable).Reset(@ptrCast(*const IEnumWiaItem2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumWiaItem2_Clone(self: *const T, ppIEnum: ?*?*IEnumWiaItem2) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumWiaItem2.VTable, self.vtable).Clone(@ptrCast(*const IEnumWiaItem2, self), ppIEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumWiaItem2_GetCount(self: *const T, cElt: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumWiaItem2.VTable, self.vtable).GetCount(@ptrCast(*const IEnumWiaItem2, self), cElt);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWiaItem2_Value = Guid.initString("6cba0075-1287-407d-9b77-cf0e030435cc");
pub const IID_IWiaItem2 = &IID_IWiaItem2_Value;
pub const IWiaItem2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
CreateChildItem: fn(
self: *const IWiaItem2,
lItemFlags: i32,
lCreationFlags: i32,
bstrItemName: ?BSTR,
ppIWiaItem2: ?*?*IWiaItem2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DeleteItem: fn(
self: *const IWiaItem2,
lFlags: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EnumChildItems: fn(
self: *const IWiaItem2,
pCategoryGUID: ?*const Guid,
ppIEnumWiaItem2: ?*?*IEnumWiaItem2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FindItemByName: fn(
self: *const IWiaItem2,
lFlags: i32,
bstrFullItemName: ?BSTR,
ppIWiaItem2: ?*?*IWiaItem2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetItemCategory: fn(
self: *const IWiaItem2,
pItemCategoryGUID: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetItemType: fn(
self: *const IWiaItem2,
pItemType: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DeviceDlg: fn(
self: *const IWiaItem2,
lFlags: i32,
hwndParent: ?HWND,
bstrFolderName: ?BSTR,
bstrFilename: ?BSTR,
plNumFiles: ?*i32,
ppbstrFilePaths: ?*?*?BSTR,
ppItem: ?*?*IWiaItem2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DeviceCommand: fn(
self: *const IWiaItem2,
lFlags: i32,
pCmdGUID: ?*const Guid,
ppIWiaItem2: ?*?*IWiaItem2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EnumDeviceCapabilities: fn(
self: *const IWiaItem2,
lFlags: i32,
ppIEnumWIA_DEV_CAPS: ?*?*IEnumWIA_DEV_CAPS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CheckExtension: fn(
self: *const IWiaItem2,
lFlags: i32,
bstrName: ?BSTR,
riidExtensionInterface: ?*const Guid,
pbExtensionExists: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetExtension: fn(
self: *const IWiaItem2,
lFlags: i32,
bstrName: ?BSTR,
riidExtensionInterface: ?*const Guid,
ppOut: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetParentItem: fn(
self: *const IWiaItem2,
ppIWiaItem2: ?*?*IWiaItem2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetRootItem: fn(
self: *const IWiaItem2,
ppIWiaItem2: ?*?*IWiaItem2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPreviewComponent: fn(
self: *const IWiaItem2,
lFlags: i32,
ppWiaPreview: ?*?*IWiaPreview,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EnumRegisterEventInfo: fn(
self: *const IWiaItem2,
lFlags: i32,
pEventGUID: ?*const Guid,
ppIEnum: ?*?*IEnumWIA_DEV_CAPS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Diagnostic: fn(
self: *const IWiaItem2,
ulSize: u32,
pBuffer: [*:0]u8,
) 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 IWiaItem2_CreateChildItem(self: *const T, lItemFlags: i32, lCreationFlags: i32, bstrItemName: ?BSTR, ppIWiaItem2: ?*?*IWiaItem2) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItem2.VTable, self.vtable).CreateChildItem(@ptrCast(*const IWiaItem2, self), lItemFlags, lCreationFlags, bstrItemName, ppIWiaItem2);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaItem2_DeleteItem(self: *const T, lFlags: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItem2.VTable, self.vtable).DeleteItem(@ptrCast(*const IWiaItem2, self), lFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaItem2_EnumChildItems(self: *const T, pCategoryGUID: ?*const Guid, ppIEnumWiaItem2: ?*?*IEnumWiaItem2) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItem2.VTable, self.vtable).EnumChildItems(@ptrCast(*const IWiaItem2, self), pCategoryGUID, ppIEnumWiaItem2);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaItem2_FindItemByName(self: *const T, lFlags: i32, bstrFullItemName: ?BSTR, ppIWiaItem2: ?*?*IWiaItem2) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItem2.VTable, self.vtable).FindItemByName(@ptrCast(*const IWiaItem2, self), lFlags, bstrFullItemName, ppIWiaItem2);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaItem2_GetItemCategory(self: *const T, pItemCategoryGUID: ?*Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItem2.VTable, self.vtable).GetItemCategory(@ptrCast(*const IWiaItem2, self), pItemCategoryGUID);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaItem2_GetItemType(self: *const T, pItemType: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItem2.VTable, self.vtable).GetItemType(@ptrCast(*const IWiaItem2, self), pItemType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaItem2_DeviceDlg(self: *const T, lFlags: i32, hwndParent: ?HWND, bstrFolderName: ?BSTR, bstrFilename: ?BSTR, plNumFiles: ?*i32, ppbstrFilePaths: ?*?*?BSTR, ppItem: ?*?*IWiaItem2) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItem2.VTable, self.vtable).DeviceDlg(@ptrCast(*const IWiaItem2, self), lFlags, hwndParent, bstrFolderName, bstrFilename, plNumFiles, ppbstrFilePaths, ppItem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaItem2_DeviceCommand(self: *const T, lFlags: i32, pCmdGUID: ?*const Guid, ppIWiaItem2: ?*?*IWiaItem2) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItem2.VTable, self.vtable).DeviceCommand(@ptrCast(*const IWiaItem2, self), lFlags, pCmdGUID, ppIWiaItem2);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaItem2_EnumDeviceCapabilities(self: *const T, lFlags: i32, ppIEnumWIA_DEV_CAPS: ?*?*IEnumWIA_DEV_CAPS) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItem2.VTable, self.vtable).EnumDeviceCapabilities(@ptrCast(*const IWiaItem2, self), lFlags, ppIEnumWIA_DEV_CAPS);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaItem2_CheckExtension(self: *const T, lFlags: i32, bstrName: ?BSTR, riidExtensionInterface: ?*const Guid, pbExtensionExists: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItem2.VTable, self.vtable).CheckExtension(@ptrCast(*const IWiaItem2, self), lFlags, bstrName, riidExtensionInterface, pbExtensionExists);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaItem2_GetExtension(self: *const T, lFlags: i32, bstrName: ?BSTR, riidExtensionInterface: ?*const Guid, ppOut: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItem2.VTable, self.vtable).GetExtension(@ptrCast(*const IWiaItem2, self), lFlags, bstrName, riidExtensionInterface, ppOut);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaItem2_GetParentItem(self: *const T, ppIWiaItem2: ?*?*IWiaItem2) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItem2.VTable, self.vtable).GetParentItem(@ptrCast(*const IWiaItem2, self), ppIWiaItem2);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaItem2_GetRootItem(self: *const T, ppIWiaItem2: ?*?*IWiaItem2) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItem2.VTable, self.vtable).GetRootItem(@ptrCast(*const IWiaItem2, self), ppIWiaItem2);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaItem2_GetPreviewComponent(self: *const T, lFlags: i32, ppWiaPreview: ?*?*IWiaPreview) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItem2.VTable, self.vtable).GetPreviewComponent(@ptrCast(*const IWiaItem2, self), lFlags, ppWiaPreview);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaItem2_EnumRegisterEventInfo(self: *const T, lFlags: i32, pEventGUID: ?*const Guid, ppIEnum: ?*?*IEnumWIA_DEV_CAPS) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItem2.VTable, self.vtable).EnumRegisterEventInfo(@ptrCast(*const IWiaItem2, self), lFlags, pEventGUID, ppIEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaItem2_Diagnostic(self: *const T, ulSize: u32, pBuffer: [*:0]u8) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaItem2.VTable, self.vtable).Diagnostic(@ptrCast(*const IWiaItem2, self), ulSize, pBuffer);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWiaDevMgr2_Value = Guid.initString("79c07cf1-cbdd-41ee-8ec3-f00080cada7a");
pub const IID_IWiaDevMgr2 = &IID_IWiaDevMgr2_Value;
pub const IWiaDevMgr2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
EnumDeviceInfo: fn(
self: *const IWiaDevMgr2,
lFlags: i32,
ppIEnum: ?*?*IEnumWIA_DEV_INFO,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateDevice: fn(
self: *const IWiaDevMgr2,
lFlags: i32,
bstrDeviceID: ?BSTR,
ppWiaItem2Root: ?*?*IWiaItem2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SelectDeviceDlg: fn(
self: *const IWiaDevMgr2,
hwndParent: ?HWND,
lDeviceType: i32,
lFlags: i32,
pbstrDeviceID: ?*?BSTR,
ppItemRoot: ?*?*IWiaItem2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SelectDeviceDlgID: fn(
self: *const IWiaDevMgr2,
hwndParent: ?HWND,
lDeviceType: i32,
lFlags: i32,
pbstrDeviceID: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RegisterEventCallbackInterface: fn(
self: *const IWiaDevMgr2,
lFlags: i32,
bstrDeviceID: ?BSTR,
pEventGUID: ?*const Guid,
pIWiaEventCallback: ?*IWiaEventCallback,
pEventObject: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RegisterEventCallbackProgram: fn(
self: *const IWiaDevMgr2,
lFlags: i32,
bstrDeviceID: ?BSTR,
pEventGUID: ?*const Guid,
bstrFullAppName: ?BSTR,
bstrCommandLineArg: ?BSTR,
bstrName: ?BSTR,
bstrDescription: ?BSTR,
bstrIcon: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RegisterEventCallbackCLSID: fn(
self: *const IWiaDevMgr2,
lFlags: i32,
bstrDeviceID: ?BSTR,
pEventGUID: ?*const Guid,
pClsID: ?*const Guid,
bstrName: ?BSTR,
bstrDescription: ?BSTR,
bstrIcon: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetImageDlg: fn(
self: *const IWiaDevMgr2,
lFlags: i32,
bstrDeviceID: ?BSTR,
hwndParent: ?HWND,
bstrFolderName: ?BSTR,
bstrFilename: ?BSTR,
plNumFiles: ?*i32,
ppbstrFilePaths: ?*?*?BSTR,
ppItem: ?*?*IWiaItem2,
) 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 IWiaDevMgr2_EnumDeviceInfo(self: *const T, lFlags: i32, ppIEnum: ?*?*IEnumWIA_DEV_INFO) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDevMgr2.VTable, self.vtable).EnumDeviceInfo(@ptrCast(*const IWiaDevMgr2, self), lFlags, ppIEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaDevMgr2_CreateDevice(self: *const T, lFlags: i32, bstrDeviceID: ?BSTR, ppWiaItem2Root: ?*?*IWiaItem2) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDevMgr2.VTable, self.vtable).CreateDevice(@ptrCast(*const IWiaDevMgr2, self), lFlags, bstrDeviceID, ppWiaItem2Root);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaDevMgr2_SelectDeviceDlg(self: *const T, hwndParent: ?HWND, lDeviceType: i32, lFlags: i32, pbstrDeviceID: ?*?BSTR, ppItemRoot: ?*?*IWiaItem2) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDevMgr2.VTable, self.vtable).SelectDeviceDlg(@ptrCast(*const IWiaDevMgr2, self), hwndParent, lDeviceType, lFlags, pbstrDeviceID, ppItemRoot);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaDevMgr2_SelectDeviceDlgID(self: *const T, hwndParent: ?HWND, lDeviceType: i32, lFlags: i32, pbstrDeviceID: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDevMgr2.VTable, self.vtable).SelectDeviceDlgID(@ptrCast(*const IWiaDevMgr2, self), hwndParent, lDeviceType, lFlags, pbstrDeviceID);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaDevMgr2_RegisterEventCallbackInterface(self: *const T, lFlags: i32, bstrDeviceID: ?BSTR, pEventGUID: ?*const Guid, pIWiaEventCallback: ?*IWiaEventCallback, pEventObject: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDevMgr2.VTable, self.vtable).RegisterEventCallbackInterface(@ptrCast(*const IWiaDevMgr2, self), lFlags, bstrDeviceID, pEventGUID, pIWiaEventCallback, pEventObject);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaDevMgr2_RegisterEventCallbackProgram(self: *const T, lFlags: i32, bstrDeviceID: ?BSTR, pEventGUID: ?*const Guid, bstrFullAppName: ?BSTR, bstrCommandLineArg: ?BSTR, bstrName: ?BSTR, bstrDescription: ?BSTR, bstrIcon: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDevMgr2.VTable, self.vtable).RegisterEventCallbackProgram(@ptrCast(*const IWiaDevMgr2, self), lFlags, bstrDeviceID, pEventGUID, bstrFullAppName, bstrCommandLineArg, bstrName, bstrDescription, bstrIcon);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaDevMgr2_RegisterEventCallbackCLSID(self: *const T, lFlags: i32, bstrDeviceID: ?BSTR, pEventGUID: ?*const Guid, pClsID: ?*const Guid, bstrName: ?BSTR, bstrDescription: ?BSTR, bstrIcon: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDevMgr2.VTable, self.vtable).RegisterEventCallbackCLSID(@ptrCast(*const IWiaDevMgr2, self), lFlags, bstrDeviceID, pEventGUID, pClsID, bstrName, bstrDescription, bstrIcon);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaDevMgr2_GetImageDlg(self: *const T, lFlags: i32, bstrDeviceID: ?BSTR, hwndParent: ?HWND, bstrFolderName: ?BSTR, bstrFilename: ?BSTR, plNumFiles: ?*i32, ppbstrFilePaths: ?*?*?BSTR, ppItem: ?*?*IWiaItem2) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDevMgr2.VTable, self.vtable).GetImageDlg(@ptrCast(*const IWiaDevMgr2, self), lFlags, bstrDeviceID, hwndParent, bstrFolderName, bstrFilename, plNumFiles, ppbstrFilePaths, ppItem);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const MINIDRV_TRANSFER_CONTEXT = extern struct {
lSize: i32,
lWidthInPixels: i32,
lLines: i32,
lDepth: i32,
lXRes: i32,
lYRes: i32,
lCompression: i32,
guidFormatID: Guid,
tymed: i32,
hFile: isize,
cbOffset: i32,
lBufferSize: i32,
lActiveBuffer: i32,
lNumBuffers: i32,
pBaseBuffer: ?*u8,
pTransferBuffer: ?*u8,
bTransferDataCB: BOOL,
bClassDrvAllocBuf: BOOL,
lClientAddress: isize,
pIWiaMiniDrvCallBack: ?*IWiaMiniDrvCallBack,
lImageSize: i32,
lHeaderSize: i32,
lItemSize: i32,
cbWidthInBytes: i32,
lPage: i32,
lCurIfdOffset: i32,
lPrevIfdOffset: i32,
};
pub const WIA_DEV_CAP_DRV = extern struct {
guid: ?*Guid,
ulFlags: u32,
wszName: ?PWSTR,
wszDescription: ?PWSTR,
wszIcon: ?PWSTR,
};
const IID_IWiaMiniDrv_Value = Guid.initString("d8cdee14-3c6c-11d2-9a35-00c04fa36145");
pub const IID_IWiaMiniDrv = &IID_IWiaMiniDrv_Value;
pub const IWiaMiniDrv = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
drvInitializeWia: fn(
self: *const IWiaMiniDrv,
__MIDL__IWiaMiniDrv0000: ?*u8,
__MIDL__IWiaMiniDrv0001: i32,
__MIDL__IWiaMiniDrv0002: ?BSTR,
__MIDL__IWiaMiniDrv0003: ?BSTR,
__MIDL__IWiaMiniDrv0004: ?*IUnknown,
__MIDL__IWiaMiniDrv0005: ?*IUnknown,
__MIDL__IWiaMiniDrv0006: ?*?*IWiaDrvItem,
__MIDL__IWiaMiniDrv0007: ?*?*IUnknown,
__MIDL__IWiaMiniDrv0008: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
drvAcquireItemData: fn(
self: *const IWiaMiniDrv,
__MIDL__IWiaMiniDrv0009: ?*u8,
__MIDL__IWiaMiniDrv0010: i32,
__MIDL__IWiaMiniDrv0011: ?*MINIDRV_TRANSFER_CONTEXT,
__MIDL__IWiaMiniDrv0012: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
drvInitItemProperties: fn(
self: *const IWiaMiniDrv,
__MIDL__IWiaMiniDrv0013: ?*u8,
__MIDL__IWiaMiniDrv0014: i32,
__MIDL__IWiaMiniDrv0015: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
drvValidateItemProperties: fn(
self: *const IWiaMiniDrv,
__MIDL__IWiaMiniDrv0016: ?*u8,
__MIDL__IWiaMiniDrv0017: i32,
__MIDL__IWiaMiniDrv0018: u32,
__MIDL__IWiaMiniDrv0019: ?*const PROPSPEC,
__MIDL__IWiaMiniDrv0020: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
drvWriteItemProperties: fn(
self: *const IWiaMiniDrv,
__MIDL__IWiaMiniDrv0021: ?*u8,
__MIDL__IWiaMiniDrv0022: i32,
__MIDL__IWiaMiniDrv0023: ?*MINIDRV_TRANSFER_CONTEXT,
__MIDL__IWiaMiniDrv0024: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
drvReadItemProperties: fn(
self: *const IWiaMiniDrv,
__MIDL__IWiaMiniDrv0025: ?*u8,
__MIDL__IWiaMiniDrv0026: i32,
__MIDL__IWiaMiniDrv0027: u32,
__MIDL__IWiaMiniDrv0028: ?*const PROPSPEC,
__MIDL__IWiaMiniDrv0029: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
drvLockWiaDevice: fn(
self: *const IWiaMiniDrv,
__MIDL__IWiaMiniDrv0030: ?*u8,
__MIDL__IWiaMiniDrv0031: i32,
__MIDL__IWiaMiniDrv0032: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
drvUnLockWiaDevice: fn(
self: *const IWiaMiniDrv,
__MIDL__IWiaMiniDrv0033: ?*u8,
__MIDL__IWiaMiniDrv0034: i32,
__MIDL__IWiaMiniDrv0035: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
drvAnalyzeItem: fn(
self: *const IWiaMiniDrv,
__MIDL__IWiaMiniDrv0036: ?*u8,
__MIDL__IWiaMiniDrv0037: i32,
__MIDL__IWiaMiniDrv0038: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
drvGetDeviceErrorStr: fn(
self: *const IWiaMiniDrv,
__MIDL__IWiaMiniDrv0039: i32,
__MIDL__IWiaMiniDrv0040: i32,
__MIDL__IWiaMiniDrv0041: ?*?PWSTR,
__MIDL__IWiaMiniDrv0042: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
drvDeviceCommand: fn(
self: *const IWiaMiniDrv,
__MIDL__IWiaMiniDrv0043: ?*u8,
__MIDL__IWiaMiniDrv0044: i32,
__MIDL__IWiaMiniDrv0045: ?*const Guid,
__MIDL__IWiaMiniDrv0046: ?*?*IWiaDrvItem,
__MIDL__IWiaMiniDrv0047: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
drvGetCapabilities: fn(
self: *const IWiaMiniDrv,
__MIDL__IWiaMiniDrv0048: ?*u8,
__MIDL__IWiaMiniDrv0049: i32,
__MIDL__IWiaMiniDrv0050: ?*i32,
__MIDL__IWiaMiniDrv0051: ?*?*WIA_DEV_CAP_DRV,
__MIDL__IWiaMiniDrv0052: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
drvDeleteItem: fn(
self: *const IWiaMiniDrv,
__MIDL__IWiaMiniDrv0053: ?*u8,
__MIDL__IWiaMiniDrv0054: i32,
__MIDL__IWiaMiniDrv0055: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
drvFreeDrvItemContext: fn(
self: *const IWiaMiniDrv,
__MIDL__IWiaMiniDrv0056: i32,
__MIDL__IWiaMiniDrv0057: ?*u8,
__MIDL__IWiaMiniDrv0058: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
drvGetWiaFormatInfo: fn(
self: *const IWiaMiniDrv,
__MIDL__IWiaMiniDrv0059: ?*u8,
__MIDL__IWiaMiniDrv0060: i32,
__MIDL__IWiaMiniDrv0061: ?*i32,
__MIDL__IWiaMiniDrv0062: ?*?*WIA_FORMAT_INFO,
__MIDL__IWiaMiniDrv0063: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
drvNotifyPnpEvent: fn(
self: *const IWiaMiniDrv,
pEventGUID: ?*const Guid,
bstrDeviceID: ?BSTR,
ulReserved: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
drvUnInitializeWia: fn(
self: *const IWiaMiniDrv,
__MIDL__IWiaMiniDrv0064: ?*u8,
) 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 IWiaMiniDrv_drvInitializeWia(self: *const T, __MIDL__IWiaMiniDrv0000: ?*u8, __MIDL__IWiaMiniDrv0001: i32, __MIDL__IWiaMiniDrv0002: ?BSTR, __MIDL__IWiaMiniDrv0003: ?BSTR, __MIDL__IWiaMiniDrv0004: ?*IUnknown, __MIDL__IWiaMiniDrv0005: ?*IUnknown, __MIDL__IWiaMiniDrv0006: ?*?*IWiaDrvItem, __MIDL__IWiaMiniDrv0007: ?*?*IUnknown, __MIDL__IWiaMiniDrv0008: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaMiniDrv.VTable, self.vtable).drvInitializeWia(@ptrCast(*const IWiaMiniDrv, self), __MIDL__IWiaMiniDrv0000, __MIDL__IWiaMiniDrv0001, __MIDL__IWiaMiniDrv0002, __MIDL__IWiaMiniDrv0003, __MIDL__IWiaMiniDrv0004, __MIDL__IWiaMiniDrv0005, __MIDL__IWiaMiniDrv0006, __MIDL__IWiaMiniDrv0007, __MIDL__IWiaMiniDrv0008);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaMiniDrv_drvAcquireItemData(self: *const T, __MIDL__IWiaMiniDrv0009: ?*u8, __MIDL__IWiaMiniDrv0010: i32, __MIDL__IWiaMiniDrv0011: ?*MINIDRV_TRANSFER_CONTEXT, __MIDL__IWiaMiniDrv0012: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaMiniDrv.VTable, self.vtable).drvAcquireItemData(@ptrCast(*const IWiaMiniDrv, self), __MIDL__IWiaMiniDrv0009, __MIDL__IWiaMiniDrv0010, __MIDL__IWiaMiniDrv0011, __MIDL__IWiaMiniDrv0012);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaMiniDrv_drvInitItemProperties(self: *const T, __MIDL__IWiaMiniDrv0013: ?*u8, __MIDL__IWiaMiniDrv0014: i32, __MIDL__IWiaMiniDrv0015: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaMiniDrv.VTable, self.vtable).drvInitItemProperties(@ptrCast(*const IWiaMiniDrv, self), __MIDL__IWiaMiniDrv0013, __MIDL__IWiaMiniDrv0014, __MIDL__IWiaMiniDrv0015);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaMiniDrv_drvValidateItemProperties(self: *const T, __MIDL__IWiaMiniDrv0016: ?*u8, __MIDL__IWiaMiniDrv0017: i32, __MIDL__IWiaMiniDrv0018: u32, __MIDL__IWiaMiniDrv0019: ?*const PROPSPEC, __MIDL__IWiaMiniDrv0020: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaMiniDrv.VTable, self.vtable).drvValidateItemProperties(@ptrCast(*const IWiaMiniDrv, self), __MIDL__IWiaMiniDrv0016, __MIDL__IWiaMiniDrv0017, __MIDL__IWiaMiniDrv0018, __MIDL__IWiaMiniDrv0019, __MIDL__IWiaMiniDrv0020);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaMiniDrv_drvWriteItemProperties(self: *const T, __MIDL__IWiaMiniDrv0021: ?*u8, __MIDL__IWiaMiniDrv0022: i32, __MIDL__IWiaMiniDrv0023: ?*MINIDRV_TRANSFER_CONTEXT, __MIDL__IWiaMiniDrv0024: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaMiniDrv.VTable, self.vtable).drvWriteItemProperties(@ptrCast(*const IWiaMiniDrv, self), __MIDL__IWiaMiniDrv0021, __MIDL__IWiaMiniDrv0022, __MIDL__IWiaMiniDrv0023, __MIDL__IWiaMiniDrv0024);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaMiniDrv_drvReadItemProperties(self: *const T, __MIDL__IWiaMiniDrv0025: ?*u8, __MIDL__IWiaMiniDrv0026: i32, __MIDL__IWiaMiniDrv0027: u32, __MIDL__IWiaMiniDrv0028: ?*const PROPSPEC, __MIDL__IWiaMiniDrv0029: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaMiniDrv.VTable, self.vtable).drvReadItemProperties(@ptrCast(*const IWiaMiniDrv, self), __MIDL__IWiaMiniDrv0025, __MIDL__IWiaMiniDrv0026, __MIDL__IWiaMiniDrv0027, __MIDL__IWiaMiniDrv0028, __MIDL__IWiaMiniDrv0029);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaMiniDrv_drvLockWiaDevice(self: *const T, __MIDL__IWiaMiniDrv0030: ?*u8, __MIDL__IWiaMiniDrv0031: i32, __MIDL__IWiaMiniDrv0032: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaMiniDrv.VTable, self.vtable).drvLockWiaDevice(@ptrCast(*const IWiaMiniDrv, self), __MIDL__IWiaMiniDrv0030, __MIDL__IWiaMiniDrv0031, __MIDL__IWiaMiniDrv0032);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaMiniDrv_drvUnLockWiaDevice(self: *const T, __MIDL__IWiaMiniDrv0033: ?*u8, __MIDL__IWiaMiniDrv0034: i32, __MIDL__IWiaMiniDrv0035: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaMiniDrv.VTable, self.vtable).drvUnLockWiaDevice(@ptrCast(*const IWiaMiniDrv, self), __MIDL__IWiaMiniDrv0033, __MIDL__IWiaMiniDrv0034, __MIDL__IWiaMiniDrv0035);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaMiniDrv_drvAnalyzeItem(self: *const T, __MIDL__IWiaMiniDrv0036: ?*u8, __MIDL__IWiaMiniDrv0037: i32, __MIDL__IWiaMiniDrv0038: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaMiniDrv.VTable, self.vtable).drvAnalyzeItem(@ptrCast(*const IWiaMiniDrv, self), __MIDL__IWiaMiniDrv0036, __MIDL__IWiaMiniDrv0037, __MIDL__IWiaMiniDrv0038);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaMiniDrv_drvGetDeviceErrorStr(self: *const T, __MIDL__IWiaMiniDrv0039: i32, __MIDL__IWiaMiniDrv0040: i32, __MIDL__IWiaMiniDrv0041: ?*?PWSTR, __MIDL__IWiaMiniDrv0042: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaMiniDrv.VTable, self.vtable).drvGetDeviceErrorStr(@ptrCast(*const IWiaMiniDrv, self), __MIDL__IWiaMiniDrv0039, __MIDL__IWiaMiniDrv0040, __MIDL__IWiaMiniDrv0041, __MIDL__IWiaMiniDrv0042);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaMiniDrv_drvDeviceCommand(self: *const T, __MIDL__IWiaMiniDrv0043: ?*u8, __MIDL__IWiaMiniDrv0044: i32, __MIDL__IWiaMiniDrv0045: ?*const Guid, __MIDL__IWiaMiniDrv0046: ?*?*IWiaDrvItem, __MIDL__IWiaMiniDrv0047: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaMiniDrv.VTable, self.vtable).drvDeviceCommand(@ptrCast(*const IWiaMiniDrv, self), __MIDL__IWiaMiniDrv0043, __MIDL__IWiaMiniDrv0044, __MIDL__IWiaMiniDrv0045, __MIDL__IWiaMiniDrv0046, __MIDL__IWiaMiniDrv0047);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaMiniDrv_drvGetCapabilities(self: *const T, __MIDL__IWiaMiniDrv0048: ?*u8, __MIDL__IWiaMiniDrv0049: i32, __MIDL__IWiaMiniDrv0050: ?*i32, __MIDL__IWiaMiniDrv0051: ?*?*WIA_DEV_CAP_DRV, __MIDL__IWiaMiniDrv0052: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaMiniDrv.VTable, self.vtable).drvGetCapabilities(@ptrCast(*const IWiaMiniDrv, self), __MIDL__IWiaMiniDrv0048, __MIDL__IWiaMiniDrv0049, __MIDL__IWiaMiniDrv0050, __MIDL__IWiaMiniDrv0051, __MIDL__IWiaMiniDrv0052);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaMiniDrv_drvDeleteItem(self: *const T, __MIDL__IWiaMiniDrv0053: ?*u8, __MIDL__IWiaMiniDrv0054: i32, __MIDL__IWiaMiniDrv0055: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaMiniDrv.VTable, self.vtable).drvDeleteItem(@ptrCast(*const IWiaMiniDrv, self), __MIDL__IWiaMiniDrv0053, __MIDL__IWiaMiniDrv0054, __MIDL__IWiaMiniDrv0055);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaMiniDrv_drvFreeDrvItemContext(self: *const T, __MIDL__IWiaMiniDrv0056: i32, __MIDL__IWiaMiniDrv0057: ?*u8, __MIDL__IWiaMiniDrv0058: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaMiniDrv.VTable, self.vtable).drvFreeDrvItemContext(@ptrCast(*const IWiaMiniDrv, self), __MIDL__IWiaMiniDrv0056, __MIDL__IWiaMiniDrv0057, __MIDL__IWiaMiniDrv0058);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaMiniDrv_drvGetWiaFormatInfo(self: *const T, __MIDL__IWiaMiniDrv0059: ?*u8, __MIDL__IWiaMiniDrv0060: i32, __MIDL__IWiaMiniDrv0061: ?*i32, __MIDL__IWiaMiniDrv0062: ?*?*WIA_FORMAT_INFO, __MIDL__IWiaMiniDrv0063: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaMiniDrv.VTable, self.vtable).drvGetWiaFormatInfo(@ptrCast(*const IWiaMiniDrv, self), __MIDL__IWiaMiniDrv0059, __MIDL__IWiaMiniDrv0060, __MIDL__IWiaMiniDrv0061, __MIDL__IWiaMiniDrv0062, __MIDL__IWiaMiniDrv0063);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaMiniDrv_drvNotifyPnpEvent(self: *const T, pEventGUID: ?*const Guid, bstrDeviceID: ?BSTR, ulReserved: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaMiniDrv.VTable, self.vtable).drvNotifyPnpEvent(@ptrCast(*const IWiaMiniDrv, self), pEventGUID, bstrDeviceID, ulReserved);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaMiniDrv_drvUnInitializeWia(self: *const T, __MIDL__IWiaMiniDrv0064: ?*u8) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaMiniDrv.VTable, self.vtable).drvUnInitializeWia(@ptrCast(*const IWiaMiniDrv, self), __MIDL__IWiaMiniDrv0064);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWiaMiniDrvCallBack_Value = Guid.initString("33a57d5a-3de8-11d2-9a36-00c04fa36145");
pub const IID_IWiaMiniDrvCallBack = &IID_IWiaMiniDrvCallBack_Value;
pub const IWiaMiniDrvCallBack = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
MiniDrvCallback: fn(
self: *const IWiaMiniDrvCallBack,
lReason: i32,
lStatus: i32,
lPercentComplete: i32,
lOffset: i32,
lLength: i32,
pTranCtx: ?*MINIDRV_TRANSFER_CONTEXT,
lReserved: 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 IWiaMiniDrvCallBack_MiniDrvCallback(self: *const T, lReason: i32, lStatus: i32, lPercentComplete: i32, lOffset: i32, lLength: i32, pTranCtx: ?*MINIDRV_TRANSFER_CONTEXT, lReserved: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaMiniDrvCallBack.VTable, self.vtable).MiniDrvCallback(@ptrCast(*const IWiaMiniDrvCallBack, self), lReason, lStatus, lPercentComplete, lOffset, lLength, pTranCtx, lReserved);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWiaMiniDrvTransferCallback_Value = Guid.initString("a9d2ee89-2ce5-4ff0-8adb-c961d1d774ca");
pub const IID_IWiaMiniDrvTransferCallback = &IID_IWiaMiniDrvTransferCallback_Value;
pub const IWiaMiniDrvTransferCallback = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetNextStream: fn(
self: *const IWiaMiniDrvTransferCallback,
lFlags: i32,
bstrItemName: ?BSTR,
bstrFullItemName: ?BSTR,
ppIStream: ?*?*IStream,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SendMessage: fn(
self: *const IWiaMiniDrvTransferCallback,
lFlags: i32,
pWiaTransferParams: ?*WiaTransferParams,
) 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 IWiaMiniDrvTransferCallback_GetNextStream(self: *const T, lFlags: i32, bstrItemName: ?BSTR, bstrFullItemName: ?BSTR, ppIStream: ?*?*IStream) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaMiniDrvTransferCallback.VTable, self.vtable).GetNextStream(@ptrCast(*const IWiaMiniDrvTransferCallback, self), lFlags, bstrItemName, bstrFullItemName, ppIStream);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaMiniDrvTransferCallback_SendMessage(self: *const T, lFlags: i32, pWiaTransferParams: ?*WiaTransferParams) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaMiniDrvTransferCallback.VTable, self.vtable).SendMessage(@ptrCast(*const IWiaMiniDrvTransferCallback, self), lFlags, pWiaTransferParams);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWiaDrvItem_Value = Guid.initString("1f02b5c5-b00c-11d2-a094-00c04f72dc3c");
pub const IID_IWiaDrvItem = &IID_IWiaDrvItem_Value;
pub const IWiaDrvItem = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetItemFlags: fn(
self: *const IWiaDrvItem,
__MIDL__IWiaDrvItem0000: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDeviceSpecContext: fn(
self: *const IWiaDrvItem,
__MIDL__IWiaDrvItem0001: ?*?*u8,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFullItemName: fn(
self: *const IWiaDrvItem,
__MIDL__IWiaDrvItem0002: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetItemName: fn(
self: *const IWiaDrvItem,
__MIDL__IWiaDrvItem0003: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddItemToFolder: fn(
self: *const IWiaDrvItem,
__MIDL__IWiaDrvItem0004: ?*IWiaDrvItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UnlinkItemTree: fn(
self: *const IWiaDrvItem,
__MIDL__IWiaDrvItem0005: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveItemFromFolder: fn(
self: *const IWiaDrvItem,
__MIDL__IWiaDrvItem0006: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FindItemByName: fn(
self: *const IWiaDrvItem,
__MIDL__IWiaDrvItem0007: i32,
__MIDL__IWiaDrvItem0008: ?BSTR,
__MIDL__IWiaDrvItem0009: ?*?*IWiaDrvItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FindChildItemByName: fn(
self: *const IWiaDrvItem,
__MIDL__IWiaDrvItem0010: ?BSTR,
__MIDL__IWiaDrvItem0011: ?*?*IWiaDrvItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetParentItem: fn(
self: *const IWiaDrvItem,
__MIDL__IWiaDrvItem0012: ?*?*IWiaDrvItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFirstChildItem: fn(
self: *const IWiaDrvItem,
__MIDL__IWiaDrvItem0013: ?*?*IWiaDrvItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetNextSiblingItem: fn(
self: *const IWiaDrvItem,
__MIDL__IWiaDrvItem0014: ?*?*IWiaDrvItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DumpItemData: fn(
self: *const IWiaDrvItem,
__MIDL__IWiaDrvItem0015: ?*?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 IWiaDrvItem_GetItemFlags(self: *const T, __MIDL__IWiaDrvItem0000: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDrvItem.VTable, self.vtable).GetItemFlags(@ptrCast(*const IWiaDrvItem, self), __MIDL__IWiaDrvItem0000);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaDrvItem_GetDeviceSpecContext(self: *const T, __MIDL__IWiaDrvItem0001: ?*?*u8) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDrvItem.VTable, self.vtable).GetDeviceSpecContext(@ptrCast(*const IWiaDrvItem, self), __MIDL__IWiaDrvItem0001);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaDrvItem_GetFullItemName(self: *const T, __MIDL__IWiaDrvItem0002: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDrvItem.VTable, self.vtable).GetFullItemName(@ptrCast(*const IWiaDrvItem, self), __MIDL__IWiaDrvItem0002);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaDrvItem_GetItemName(self: *const T, __MIDL__IWiaDrvItem0003: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDrvItem.VTable, self.vtable).GetItemName(@ptrCast(*const IWiaDrvItem, self), __MIDL__IWiaDrvItem0003);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaDrvItem_AddItemToFolder(self: *const T, __MIDL__IWiaDrvItem0004: ?*IWiaDrvItem) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDrvItem.VTable, self.vtable).AddItemToFolder(@ptrCast(*const IWiaDrvItem, self), __MIDL__IWiaDrvItem0004);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaDrvItem_UnlinkItemTree(self: *const T, __MIDL__IWiaDrvItem0005: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDrvItem.VTable, self.vtable).UnlinkItemTree(@ptrCast(*const IWiaDrvItem, self), __MIDL__IWiaDrvItem0005);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaDrvItem_RemoveItemFromFolder(self: *const T, __MIDL__IWiaDrvItem0006: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDrvItem.VTable, self.vtable).RemoveItemFromFolder(@ptrCast(*const IWiaDrvItem, self), __MIDL__IWiaDrvItem0006);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaDrvItem_FindItemByName(self: *const T, __MIDL__IWiaDrvItem0007: i32, __MIDL__IWiaDrvItem0008: ?BSTR, __MIDL__IWiaDrvItem0009: ?*?*IWiaDrvItem) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDrvItem.VTable, self.vtable).FindItemByName(@ptrCast(*const IWiaDrvItem, self), __MIDL__IWiaDrvItem0007, __MIDL__IWiaDrvItem0008, __MIDL__IWiaDrvItem0009);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaDrvItem_FindChildItemByName(self: *const T, __MIDL__IWiaDrvItem0010: ?BSTR, __MIDL__IWiaDrvItem0011: ?*?*IWiaDrvItem) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDrvItem.VTable, self.vtable).FindChildItemByName(@ptrCast(*const IWiaDrvItem, self), __MIDL__IWiaDrvItem0010, __MIDL__IWiaDrvItem0011);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaDrvItem_GetParentItem(self: *const T, __MIDL__IWiaDrvItem0012: ?*?*IWiaDrvItem) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDrvItem.VTable, self.vtable).GetParentItem(@ptrCast(*const IWiaDrvItem, self), __MIDL__IWiaDrvItem0012);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaDrvItem_GetFirstChildItem(self: *const T, __MIDL__IWiaDrvItem0013: ?*?*IWiaDrvItem) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDrvItem.VTable, self.vtable).GetFirstChildItem(@ptrCast(*const IWiaDrvItem, self), __MIDL__IWiaDrvItem0013);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaDrvItem_GetNextSiblingItem(self: *const T, __MIDL__IWiaDrvItem0014: ?*?*IWiaDrvItem) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDrvItem.VTable, self.vtable).GetNextSiblingItem(@ptrCast(*const IWiaDrvItem, self), __MIDL__IWiaDrvItem0014);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaDrvItem_DumpItemData(self: *const T, __MIDL__IWiaDrvItem0015: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaDrvItem.VTable, self.vtable).DumpItemData(@ptrCast(*const IWiaDrvItem, self), __MIDL__IWiaDrvItem0015);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const WIA_PROPERTY_INFO = extern struct {
lAccessFlags: u32,
vt: u16,
ValidVal: extern union {
Range: extern struct {
Min: i32,
Nom: i32,
Max: i32,
Inc: i32,
},
RangeFloat: extern struct {
Min: f64,
Nom: f64,
Max: f64,
Inc: f64,
},
List: extern struct {
cNumList: i32,
Nom: i32,
pList: ?*u8,
},
ListFloat: extern struct {
cNumList: i32,
Nom: f64,
pList: ?*u8,
},
ListGuid: extern struct {
cNumList: i32,
Nom: Guid,
pList: ?*Guid,
},
ListBStr: extern struct {
cNumList: i32,
Nom: ?BSTR,
pList: ?*?BSTR,
},
Flag: extern struct {
Nom: i32,
ValidBits: i32,
},
None: extern struct {
Dummy: i32,
},
},
};
pub const WIA_PROPERTY_CONTEXT = extern struct {
cProps: u32,
pProps: ?*u32,
pChanged: ?*BOOL,
};
pub const WIAS_CHANGED_VALUE_INFO = extern struct {
bChanged: BOOL,
vt: i32,
Old: extern union {
lVal: i32,
fltVal: f32,
bstrVal: ?BSTR,
guidVal: Guid,
},
Current: extern union {
lVal: i32,
fltVal: f32,
bstrVal: ?BSTR,
guidVal: Guid,
},
};
pub const WIAS_DOWN_SAMPLE_INFO = extern struct {
ulOriginalWidth: u32,
ulOriginalHeight: u32,
ulBitsPerPixel: u32,
ulXRes: u32,
ulYRes: u32,
ulDownSampledWidth: u32,
ulDownSampledHeight: u32,
ulActualSize: u32,
ulDestBufSize: u32,
ulSrcBufSize: u32,
pSrcBuffer: ?*u8,
pDestBuffer: ?*u8,
};
pub const WIAS_ENDORSER_VALUE = extern struct {
wszTokenName: ?PWSTR,
wszValue: ?PWSTR,
};
pub const WIAS_ENDORSER_INFO = extern struct {
ulPageCount: u32,
ulNumEndorserValues: u32,
pEndorserValues: ?*WIAS_ENDORSER_VALUE,
};
const CLSID_WiaVideo_Value = Guid.initString("3908c3cd-4478-4536-af2f-10c25d4ef89a");
pub const CLSID_WiaVideo = &CLSID_WiaVideo_Value;
pub const WIAVIDEO_STATE = enum(i32) {
NO_VIDEO = 1,
CREATING_VIDEO = 2,
VIDEO_CREATED = 3,
VIDEO_PLAYING = 4,
VIDEO_PAUSED = 5,
DESTROYING_VIDEO = 6,
};
pub const WIAVIDEO_NO_VIDEO = WIAVIDEO_STATE.NO_VIDEO;
pub const WIAVIDEO_CREATING_VIDEO = WIAVIDEO_STATE.CREATING_VIDEO;
pub const WIAVIDEO_VIDEO_CREATED = WIAVIDEO_STATE.VIDEO_CREATED;
pub const WIAVIDEO_VIDEO_PLAYING = WIAVIDEO_STATE.VIDEO_PLAYING;
pub const WIAVIDEO_VIDEO_PAUSED = WIAVIDEO_STATE.VIDEO_PAUSED;
pub const WIAVIDEO_DESTROYING_VIDEO = WIAVIDEO_STATE.DESTROYING_VIDEO;
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_IWiaVideo_Value = Guid.initString("d52920aa-db88-41f0-946c-e00dc0a19cfa");
pub const IID_IWiaVideo = &IID_IWiaVideo_Value;
pub const IWiaVideo = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_PreviewVisible: fn(
self: *const IWiaVideo,
pbPreviewVisible: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_PreviewVisible: fn(
self: *const IWiaVideo,
bPreviewVisible: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ImagesDirectory: fn(
self: *const IWiaVideo,
pbstrImageDirectory: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_ImagesDirectory: fn(
self: *const IWiaVideo,
bstrImageDirectory: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateVideoByWiaDevID: fn(
self: *const IWiaVideo,
bstrWiaDeviceID: ?BSTR,
hwndParent: ?HWND,
bStretchToFitParent: BOOL,
bAutoBeginPlayback: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateVideoByDevNum: fn(
self: *const IWiaVideo,
uiDeviceNumber: u32,
hwndParent: ?HWND,
bStretchToFitParent: BOOL,
bAutoBeginPlayback: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateVideoByName: fn(
self: *const IWiaVideo,
bstrFriendlyName: ?BSTR,
hwndParent: ?HWND,
bStretchToFitParent: BOOL,
bAutoBeginPlayback: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DestroyVideo: fn(
self: *const IWiaVideo,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Play: fn(
self: *const IWiaVideo,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Pause: fn(
self: *const IWiaVideo,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TakePicture: fn(
self: *const IWiaVideo,
pbstrNewImageFilename: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ResizeVideo: fn(
self: *const IWiaVideo,
bStretchToFitParent: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCurrentState: fn(
self: *const IWiaVideo,
pState: ?*WIAVIDEO_STATE,
) 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 IWiaVideo_get_PreviewVisible(self: *const T, pbPreviewVisible: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaVideo.VTable, self.vtable).get_PreviewVisible(@ptrCast(*const IWiaVideo, self), pbPreviewVisible);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaVideo_put_PreviewVisible(self: *const T, bPreviewVisible: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaVideo.VTable, self.vtable).put_PreviewVisible(@ptrCast(*const IWiaVideo, self), bPreviewVisible);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaVideo_get_ImagesDirectory(self: *const T, pbstrImageDirectory: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaVideo.VTable, self.vtable).get_ImagesDirectory(@ptrCast(*const IWiaVideo, self), pbstrImageDirectory);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaVideo_put_ImagesDirectory(self: *const T, bstrImageDirectory: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaVideo.VTable, self.vtable).put_ImagesDirectory(@ptrCast(*const IWiaVideo, self), bstrImageDirectory);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaVideo_CreateVideoByWiaDevID(self: *const T, bstrWiaDeviceID: ?BSTR, hwndParent: ?HWND, bStretchToFitParent: BOOL, bAutoBeginPlayback: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaVideo.VTable, self.vtable).CreateVideoByWiaDevID(@ptrCast(*const IWiaVideo, self), bstrWiaDeviceID, hwndParent, bStretchToFitParent, bAutoBeginPlayback);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaVideo_CreateVideoByDevNum(self: *const T, uiDeviceNumber: u32, hwndParent: ?HWND, bStretchToFitParent: BOOL, bAutoBeginPlayback: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaVideo.VTable, self.vtable).CreateVideoByDevNum(@ptrCast(*const IWiaVideo, self), uiDeviceNumber, hwndParent, bStretchToFitParent, bAutoBeginPlayback);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaVideo_CreateVideoByName(self: *const T, bstrFriendlyName: ?BSTR, hwndParent: ?HWND, bStretchToFitParent: BOOL, bAutoBeginPlayback: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaVideo.VTable, self.vtable).CreateVideoByName(@ptrCast(*const IWiaVideo, self), bstrFriendlyName, hwndParent, bStretchToFitParent, bAutoBeginPlayback);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaVideo_DestroyVideo(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaVideo.VTable, self.vtable).DestroyVideo(@ptrCast(*const IWiaVideo, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaVideo_Play(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaVideo.VTable, self.vtable).Play(@ptrCast(*const IWiaVideo, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaVideo_Pause(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaVideo.VTable, self.vtable).Pause(@ptrCast(*const IWiaVideo, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaVideo_TakePicture(self: *const T, pbstrNewImageFilename: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaVideo.VTable, self.vtable).TakePicture(@ptrCast(*const IWiaVideo, self), pbstrNewImageFilename);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaVideo_ResizeVideo(self: *const T, bStretchToFitParent: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaVideo.VTable, self.vtable).ResizeVideo(@ptrCast(*const IWiaVideo, self), bStretchToFitParent);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaVideo_GetCurrentState(self: *const T, pState: ?*WIAVIDEO_STATE) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaVideo.VTable, self.vtable).GetCurrentState(@ptrCast(*const IWiaVideo, self), pState);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DEVICEDIALOGDATA2 = extern struct {
cbSize: u32,
pIWiaItemRoot: ?*IWiaItem2,
dwFlags: u32,
hwndParent: ?HWND,
bstrFolderName: ?BSTR,
bstrFilename: ?BSTR,
lNumFiles: i32,
pbstrFilePaths: ?*?BSTR,
pWiaItem: ?*IWiaItem2,
};
const IID_IWiaUIExtension2_Value = Guid.initString("305600d7-5088-46d7-9a15-b77b09cdba7a");
pub const IID_IWiaUIExtension2 = &IID_IWiaUIExtension2_Value;
pub const IWiaUIExtension2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
DeviceDialog: fn(
self: *const IWiaUIExtension2,
pDeviceDialogData: ?*DEVICEDIALOGDATA2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDeviceIcon: fn(
self: *const IWiaUIExtension2,
bstrDeviceId: ?BSTR,
phIcon: ?*?HICON,
nSize: 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 IWiaUIExtension2_DeviceDialog(self: *const T, pDeviceDialogData: ?*DEVICEDIALOGDATA2) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaUIExtension2.VTable, self.vtable).DeviceDialog(@ptrCast(*const IWiaUIExtension2, self), pDeviceDialogData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaUIExtension2_GetDeviceIcon(self: *const T, bstrDeviceId: ?BSTR, phIcon: ?*?HICON, nSize: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaUIExtension2.VTable, self.vtable).GetDeviceIcon(@ptrCast(*const IWiaUIExtension2, self), bstrDeviceId, phIcon, nSize);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DEVICEDIALOGDATA = extern struct {
cbSize: u32,
hwndParent: ?HWND,
pIWiaItemRoot: ?*IWiaItem,
dwFlags: u32,
lIntent: i32,
lItemCount: i32,
ppWiaItems: ?*?*IWiaItem,
};
const IID_IWiaUIExtension_Value = Guid.initString("da319113-50ee-4c80-b460-57d005d44a2c");
pub const IID_IWiaUIExtension = &IID_IWiaUIExtension_Value;
pub const IWiaUIExtension = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
DeviceDialog: fn(
self: *const IWiaUIExtension,
pDeviceDialogData: ?*DEVICEDIALOGDATA,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDeviceIcon: fn(
self: *const IWiaUIExtension,
bstrDeviceId: ?BSTR,
phIcon: ?*?HICON,
nSize: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDeviceBitmapLogo: fn(
self: *const IWiaUIExtension,
bstrDeviceId: ?BSTR,
phBitmap: ?*?HBITMAP,
nMaxWidth: u32,
nMaxHeight: 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 IWiaUIExtension_DeviceDialog(self: *const T, pDeviceDialogData: ?*DEVICEDIALOGDATA) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaUIExtension.VTable, self.vtable).DeviceDialog(@ptrCast(*const IWiaUIExtension, self), pDeviceDialogData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaUIExtension_GetDeviceIcon(self: *const T, bstrDeviceId: ?BSTR, phIcon: ?*?HICON, nSize: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaUIExtension.VTable, self.vtable).GetDeviceIcon(@ptrCast(*const IWiaUIExtension, self), bstrDeviceId, phIcon, nSize);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWiaUIExtension_GetDeviceBitmapLogo(self: *const T, bstrDeviceId: ?BSTR, phBitmap: ?*?HBITMAP, nMaxWidth: u32, nMaxHeight: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWiaUIExtension.VTable, self.vtable).GetDeviceBitmapLogo(@ptrCast(*const IWiaUIExtension, self), bstrDeviceId, phBitmap, nMaxWidth, nMaxHeight);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DeviceDialogFunction = fn(
param0: ?*DEVICEDIALOGDATA,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const RANGEVALUE = extern struct {
lMin: i32,
lMax: i32,
lStep: i32,
};
pub const SCANWINDOW = extern struct {
xPos: i32,
yPos: i32,
xExtent: i32,
yExtent: i32,
};
pub const SCANINFO = extern struct {
ADF: i32,
TPA: i32,
Endorser: i32,
OpticalXResolution: i32,
OpticalYResolution: i32,
BedWidth: i32,
BedHeight: i32,
IntensityRange: RANGEVALUE,
ContrastRange: RANGEVALUE,
SupportedCompressionType: i32,
SupportedDataTypes: i32,
WidthPixels: i32,
WidthBytes: i32,
Lines: i32,
DataType: i32,
PixelBits: i32,
Intensity: i32,
Contrast: i32,
Xresolution: i32,
Yresolution: i32,
Window: SCANWINDOW,
DitherPattern: i32,
Negative: i32,
Mirror: i32,
AutoBack: i32,
ColorDitherPattern: i32,
ToneMap: i32,
Compression: i32,
RawDataFormat: i32,
RawPixelOrder: i32,
bNeedDataAlignment: i32,
DelayBetweenRead: i32,
MaxBufferSize: i32,
DeviceIOHandles: [16]?HANDLE,
lReserved: [4]i32,
pMicroDriverContext: ?*anyopaque,
};
pub const VAL = extern struct {
lVal: i32,
dblVal: f64,
pGuid: ?*Guid,
pScanInfo: ?*SCANINFO,
handle: isize,
ppButtonNames: ?*?*u16,
pHandle: ?*?HANDLE,
lReserved: i32,
szVal: [255]CHAR,
};
pub const TWAIN_CAPABILITY = extern struct {
lSize: i32,
lMSG: i32,
lCapID: i32,
lConType: i32,
lRC: i32,
lCC: i32,
lDataSize: i32,
Data: [1]u8,
};
//--------------------------------------------------------------------------------
// 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 (19)
//--------------------------------------------------------------------------------
const Guid = @import("../zig.zig").Guid;
const BOOL = @import("../foundation.zig").BOOL;
const BSTR = @import("../foundation.zig").BSTR;
const CHAR = @import("../foundation.zig").CHAR;
const FILETIME = @import("../foundation.zig").FILETIME;
const HANDLE = @import("../foundation.zig").HANDLE;
const HBITMAP = @import("../graphics/gdi.zig").HBITMAP;
const HICON = @import("../ui/windows_and_messaging.zig").HICON;
const HRESULT = @import("../foundation.zig").HRESULT;
const HWND = @import("../foundation.zig").HWND;
const IEnumSTATPROPSTG = @import("../system/com/structured_storage.zig").IEnumSTATPROPSTG;
const IStream = @import("../system/com.zig").IStream;
const IUnknown = @import("../system/com.zig").IUnknown;
const PROPSPEC = @import("../system/com/structured_storage.zig").PROPSPEC;
const PROPVARIANT = @import("../system/com/structured_storage.zig").PROPVARIANT;
const PWSTR = @import("../foundation.zig").PWSTR;
const RECT = @import("../foundation.zig").RECT;
const STATPROPSETSTG = @import("../system/com/structured_storage.zig").STATPROPSETSTG;
const STGMEDIUM = @import("../system/com.zig").STGMEDIUM;
test {
// The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476
if (@hasDecl(@This(), "DeviceDialogFunction")) { _ = DeviceDialogFunction; }
@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/devices/image_acquisition.zig |
const Regex = @import("regex.zig").Regex;
const debug = @import("std").debug;
const Parser = @import("parse.zig").Parser;
const re_debug = @import("debug.zig");
const std = @import("std");
const FixedBufferAllocator = std.heap.FixedBufferAllocator;
const mem = std.mem;
// Debug global allocator is too small for our tests
var buffer: [800000]u8 = undefined;
var fixed_allocator = FixedBufferAllocator.init(buffer[0..]);
fn check(re_input: []const u8, to_match: []const u8, expected: bool) void {
var re = Regex.compile(&fixed_allocator.allocator, re_input) catch unreachable;
if ((re.partialMatch(to_match) catch unreachable) != expected) {
debug.warn(
\\
\\ -- Failure! ------------------
\\
\\Regex: '{s}'
\\String: '{s}'
\\Expected: {s}
\\
, .{
re_input,
to_match,
expected,
});
// Dump expression tree and bytecode
var p = Parser.init(std.testing.allocator);
defer p.deinit();
const expr = p.parse(re_input) catch unreachable;
debug.warn(
\\
\\ -- Expression Tree ------------
\\
, .{});
re_debug.dumpExpr(expr.*);
debug.warn(
\\
\\ -- Bytecode -------------------
\\
, .{});
re_debug.dumpProgram(re.compiled);
debug.warn(
\\
\\ -------------------------------
\\
, .{});
@panic("assertion failure");
}
}
test "regex sanity tests" {
// Taken from tiny-regex-c
check("\\d", "5", true);
check("\\w+", "hej", true);
check("\\s", "\t \n", true);
check("\\S", "\t \n", false);
check("[\\s]", "\t \n", true);
check("[\\S]", "\t \n", false);
check("\\D", "5", false);
check("\\W+", "hej", false);
check("[0-9]+", "12345", true);
check("\\D", "hej", true);
check("\\d", "hej", false);
check("[^\\w]", "\\", true);
check("[\\W]", "\\", true);
check("[\\w]", "\\", false);
check("[^\\d]", "d", true);
check("[\\d]", "d", false);
check("[^\\D]", "d", false);
check("[\\D]", "d", true);
check("^.*\\\\.*$", "c:\\Tools", true);
check("^[\\+-]*[\\d]+$", "+27", true);
check("[abc]", "1c2", true);
check("[abc]", "1C2", false);
check("[1-5]+", "0123456789", true);
check("[.2]", "1C2", true);
check("a*$", "Xaa", true);
check("a*$", "Xaa", true);
check("[a-h]+", "abcdefghxxx", true);
check("[a-h]+", "ABCDEFGH", false);
check("[A-H]+", "ABCDEFGH", true);
check("[A-H]+", "abcdefgh", false);
check("[^\\s]+", "abc def", true);
check("[^fc]+", "abc def", true);
check("[^d\\sf]+", "abc def", true);
check("\n", "abc\ndef", true);
//check("b.\\s*\n", "aa\r\nbb\r\ncc\r\n\r\n", true);
check(".*c", "abcabc", true);
check(".+c", "abcabc", true);
check("[b-z].*", "ab", true);
check("b[k-z]*", "ab", true);
check("[0-9]", " - ", false);
check("[^0-9]", " - ", true);
check("[Hh]ello [Ww]orld\\s*[!]?", "Hello world !", true);
check("[Hh]ello [Ww]orld\\s*[!]?", "hello world !", true);
check("[Hh]ello [Ww]orld\\s*[!]?", "Hello World !", true);
check("[Hh]ello [Ww]orld\\s*[!]?", "Hello world! ", true);
check("[Hh]ello [Ww]orld\\s*[!]?", "Hello world !", true);
check("[Hh]ello [Ww]orld\\s*[!]?", "hello World !", true);
check("[^\\w][^-1-4]", ")T", true);
check("[^\\w][^-1-4]", ")^", true);
check("[^\\w][^-1-4]", "*)", true);
check("[^\\w][^-1-4]", "!.", true);
check("[^\\w][^-1-4]", " x", true);
check("[^\\w][^-1-4]", "$b", true);
}
test "regex captures" {
var r = Regex.compile(std.testing.allocator, "ab(\\d+)") catch unreachable;
debug.assert(try r.partialMatch("xxxxab0123a"));
const caps = if (try r.captures("xxxxab0123a")) |caps| caps else unreachable;
debug.assert(mem.eql(u8, "ab0123", caps.sliceAt(0).?));
debug.assert(mem.eql(u8, "0123", caps.sliceAt(1).?));
} | src/regex_test.zig |
const std = @import("std");
const testing = std.testing;
const allocator = std.heap.page_allocator;
pub const Puzzle = struct {
said: std.AutoHashMap(usize, usize),
turn: usize,
last: usize,
progress: bool,
pub fn init(progress: bool) Puzzle {
var self = Puzzle{
.said = std.AutoHashMap(usize, usize).init(allocator),
.turn = 0,
.last = 0,
.progress = progress,
};
return self;
}
pub fn deinit(self: *Puzzle) void {
self.said.deinit();
}
pub fn run(self: *Puzzle, seed: []const u8, turns: usize) usize {
var it = std.mem.tokenize(u8, seed, ",");
var first: bool = true;
var curr: usize = 0;
while (it.next()) |num| {
curr = std.fmt.parseInt(usize, num, 10) catch unreachable;
if (!first) {
_ = self.said.put(self.last, self.turn) catch unreachable;
}
first = false;
self.last = curr;
self.turn += 1;
// std.debug.warn("SEED {} {}\n", .{ self.turn, self.last });
}
var show_progress_every: usize = turns / 20;
if (show_progress_every < 1_000) show_progress_every = 1_000;
while (self.turn < turns) {
var pos = self.turn;
if (self.said.contains(self.last)) {
pos = self.said.get(self.last).?;
_ = self.said.remove(self.last);
}
_ = self.said.put(self.last, self.turn) catch unreachable;
self.last = self.turn - pos;
self.turn += 1;
if (self.progress and self.turn % show_progress_every == 0) {
const progress: usize = 100 * self.turn / turns;
std.debug.warn("GAME {}% {} {}\n", .{ progress, self.turn, self.last });
}
}
return self.last;
}
};
test "sample short 1" {
const data: []const u8 = "0,3,6";
var puzzle = Puzzle.init(false);
defer puzzle.deinit();
const number = puzzle.run(data, 2020);
try testing.expect(number == 436);
}
test "sample short 2" {
const data: []const u8 = "1,3,2";
var puzzle = Puzzle.init(false);
defer puzzle.deinit();
const number = puzzle.run(data, 2020);
try testing.expect(number == 1);
}
test "sample short 3" {
const data: []const u8 = "2,1,3";
var puzzle = Puzzle.init(false);
defer puzzle.deinit();
const number = puzzle.run(data, 2020);
try testing.expect(number == 10);
}
test "sample short 4" {
const data: []const u8 = "1,2,3";
var puzzle = Puzzle.init(false);
defer puzzle.deinit();
const number = puzzle.run(data, 2020);
try testing.expect(number == 27);
}
test "sample short 5" {
const data: []const u8 = "2,3,1";
var puzzle = Puzzle.init(false);
defer puzzle.deinit();
const number = puzzle.run(data, 2020);
try testing.expect(number == 78);
}
test "sample short 6" {
const data: []const u8 = "3,2,1";
var puzzle = Puzzle.init(false);
defer puzzle.deinit();
const number = puzzle.run(data, 2020);
try testing.expect(number == 438);
}
test "sample short 7" {
const data: []const u8 = "3,1,2";
var puzzle = Puzzle.init(false);
defer puzzle.deinit();
const number = puzzle.run(data, 2020);
try testing.expect(number == 1836);
}
// ------------------------------------------------------------------
// All these tests pass, but they take longer (minutes on my laptop).
// ------------------------------------------------------------------
// test "sample long 1" {
// const data: []const u8 = "0,3,6";
//
// var puzzle = Puzzle.init(true);
// defer puzzle.deinit();
//
// const number = puzzle.run(data, 30000000);
// try testing.expect(number == 175594);
// }
//
// test "sample long 2" {
// const data: []const u8 = "1,3,2";
//
// var puzzle = Puzzle.init(true);
// defer puzzle.deinit();
//
// const number = puzzle.run(data, 30000000);
// try testing.expect(number == 2578);
// }
//
// test "sample long 3" {
// const data: []const u8 = "2,1,3";
//
// var puzzle = Puzzle.init(true);
// defer puzzle.deinit();
//
// const number = puzzle.run(data, 30000000);
// try testing.expect(number == 3544142);
// }
//
// test "sample long 4" {
// const data: []const u8 = "1,2,3";
//
// var puzzle = Puzzle.init(true);
// defer puzzle.deinit();
//
// const number = puzzle.run(data, 30000000);
// try testing.expect(number == 261214);
// }
//
// test "sample long 5" {
// const data: []const u8 = "2,3,1";
//
// var puzzle = Puzzle.init(true);
// defer puzzle.deinit();
//
// const number = puzzle.run(data, 30000000);
// try testing.expect(number == 6895259);
// }
//
// test "sample long 6" {
// const data: []const u8 = "3,2,1";
//
// var puzzle = Puzzle.init(true);
// defer puzzle.deinit();
//
// const number = puzzle.run(data, 30000000);
// try testing.expect(number == 18);
// }
//
// test "sample long 7" {
// const data: []const u8 = "3,1,2";
//
// var puzzle = Puzzle.init(true);
// defer puzzle.deinit();
//
// const number = puzzle.run(data, 30000000);
// try testing.expect(number == 362);
// } | 2020/p15/puzzle.zig |
const std = @import("std");
const cast = std.meta.cast;
const mode = std.builtin.mode; // Checked arithmetic is disabled in non-debug modes to avoid side channels
/// The function addcarryxU64 is an addition with carry.
/// Postconditions:
/// out1 = (arg1 + arg2 + arg3) mod 2^64
/// out2 = ⌊(arg1 + arg2 + arg3) / 2^64⌋
///
/// Input Bounds:
/// arg1: [0x0 ~> 0x1]
/// arg2: [0x0 ~> 0xffffffffffffffff]
/// arg3: [0x0 ~> 0xffffffffffffffff]
/// Output Bounds:
/// out1: [0x0 ~> 0xffffffffffffffff]
/// out2: [0x0 ~> 0x1]
fn addcarryxU64(out1: *u64, out2: *u1, arg1: u1, arg2: u64, arg3: u64) callconv(.Inline) void {
@setRuntimeSafety(mode == .Debug);
const x1 = ((cast(u128, arg1) + cast(u128, arg2)) + cast(u128, arg3));
const x2 = cast(u64, (x1 & cast(u128, 0xffffffffffffffff)));
const x3 = cast(u1, (x1 >> 64));
out1.* = x2;
out2.* = x3;
}
/// The function subborrowxU64 is a subtraction with borrow.
/// Postconditions:
/// out1 = (-arg1 + arg2 + -arg3) mod 2^64
/// out2 = -⌊(-arg1 + arg2 + -arg3) / 2^64⌋
///
/// Input Bounds:
/// arg1: [0x0 ~> 0x1]
/// arg2: [0x0 ~> 0xffffffffffffffff]
/// arg3: [0x0 ~> 0xffffffffffffffff]
/// Output Bounds:
/// out1: [0x0 ~> 0xffffffffffffffff]
/// out2: [0x0 ~> 0x1]
fn subborrowxU64(out1: *u64, out2: *u1, arg1: u1, arg2: u64, arg3: u64) callconv(.Inline) void {
@setRuntimeSafety(mode == .Debug);
const x1 = ((cast(i128, arg2) - cast(i128, arg1)) - cast(i128, arg3));
const x2 = cast(i1, (x1 >> 64));
const x3 = cast(u64, (x1 & cast(i128, 0xffffffffffffffff)));
out1.* = x3;
out2.* = cast(u1, (cast(i2, 0x0) - cast(i2, x2)));
}
/// The function mulxU64 is a multiplication, returning the full double-width result.
/// Postconditions:
/// out1 = (arg1 * arg2) mod 2^64
/// out2 = ⌊arg1 * arg2 / 2^64⌋
///
/// Input Bounds:
/// arg1: [0x0 ~> 0xffffffffffffffff]
/// arg2: [0x0 ~> 0xffffffffffffffff]
/// Output Bounds:
/// out1: [0x0 ~> 0xffffffffffffffff]
/// out2: [0x0 ~> 0xffffffffffffffff]
fn mulxU64(out1: *u64, out2: *u64, arg1: u64, arg2: u64) callconv(.Inline) void {
@setRuntimeSafety(mode == .Debug);
const x1 = (cast(u128, arg1) * cast(u128, arg2));
const x2 = cast(u64, (x1 & cast(u128, 0xffffffffffffffff)));
const x3 = cast(u64, (x1 >> 64));
out1.* = x2;
out2.* = x3;
}
/// The function cmovznzU64 is a single-word conditional move.
/// Postconditions:
/// out1 = (if arg1 = 0 then arg2 else arg3)
///
/// Input Bounds:
/// arg1: [0x0 ~> 0x1]
/// arg2: [0x0 ~> 0xffffffffffffffff]
/// arg3: [0x0 ~> 0xffffffffffffffff]
/// Output Bounds:
/// out1: [0x0 ~> 0xffffffffffffffff]
fn cmovznzU64(out1: *u64, arg1: u1, arg2: u64, arg3: u64) callconv(.Inline) void {
@setRuntimeSafety(mode == .Debug);
const x1 = (~(~arg1));
const x2 = cast(u64, (cast(i128, cast(i1, (cast(i2, 0x0) - cast(i2, x1)))) & cast(i128, 0xffffffffffffffff)));
const x3 = ((x2 & arg3) | ((~x2) & arg2));
out1.* = x3;
}
/// The function mul multiplies two field elements in the Montgomery domain.
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// 0 ≤ eval arg2 < m
/// Postconditions:
/// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg2)) mod m
/// 0 ≤ eval out1 < m
///
/// Input Bounds:
/// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
/// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
pub fn mul(out1: *[4]u64, arg1: [4]u64, arg2: [4]u64) void {
@setRuntimeSafety(mode == .Debug);
const x1 = (arg1[1]);
const x2 = (arg1[2]);
const x3 = (arg1[3]);
const x4 = (arg1[0]);
var x5: u64 = undefined;
var x6: u64 = undefined;
mulxU64(&x5, &x6, x4, (arg2[3]));
var x7: u64 = undefined;
var x8: u64 = undefined;
mulxU64(&x7, &x8, x4, (arg2[2]));
var x9: u64 = undefined;
var x10: u64 = undefined;
mulxU64(&x9, &x10, x4, (arg2[1]));
var x11: u64 = undefined;
var x12: u64 = undefined;
mulxU64(&x11, &x12, x4, (arg2[0]));
var x13: u64 = undefined;
var x14: u1 = undefined;
addcarryxU64(&x13, &x14, 0x0, x12, x9);
var x15: u64 = undefined;
var x16: u1 = undefined;
addcarryxU64(&x15, &x16, x14, x10, x7);
var x17: u64 = undefined;
var x18: u1 = undefined;
addcarryxU64(&x17, &x18, x16, x8, x5);
const x19 = (cast(u64, x18) + x6);
var x20: u64 = undefined;
var x21: u64 = undefined;
mulxU64(&x20, &x21, x11, 0xffffffffffffffff);
var x22: u64 = undefined;
var x23: u64 = undefined;
mulxU64(&x22, &x23, x20, 0xffffffff);
var x24: u64 = undefined;
var x25: u64 = undefined;
mulxU64(&x24, &x25, x20, 0xffffffffffffffff);
var x26: u64 = undefined;
var x27: u64 = undefined;
mulxU64(&x26, &x27, x20, 0xffffffff00000000);
var x28: u64 = undefined;
var x29: u1 = undefined;
addcarryxU64(&x28, &x29, 0x0, x27, x24);
var x30: u64 = undefined;
var x31: u1 = undefined;
addcarryxU64(&x30, &x31, x29, x25, x22);
const x32 = (cast(u64, x31) + x23);
var x33: u64 = undefined;
var x34: u1 = undefined;
addcarryxU64(&x33, &x34, 0x0, x11, x20);
var x35: u64 = undefined;
var x36: u1 = undefined;
addcarryxU64(&x35, &x36, x34, x13, x26);
var x37: u64 = undefined;
var x38: u1 = undefined;
addcarryxU64(&x37, &x38, x36, x15, x28);
var x39: u64 = undefined;
var x40: u1 = undefined;
addcarryxU64(&x39, &x40, x38, x17, x30);
var x41: u64 = undefined;
var x42: u1 = undefined;
addcarryxU64(&x41, &x42, x40, x19, x32);
var x43: u64 = undefined;
var x44: u64 = undefined;
mulxU64(&x43, &x44, x1, (arg2[3]));
var x45: u64 = undefined;
var x46: u64 = undefined;
mulxU64(&x45, &x46, x1, (arg2[2]));
var x47: u64 = undefined;
var x48: u64 = undefined;
mulxU64(&x47, &x48, x1, (arg2[1]));
var x49: u64 = undefined;
var x50: u64 = undefined;
mulxU64(&x49, &x50, x1, (arg2[0]));
var x51: u64 = undefined;
var x52: u1 = undefined;
addcarryxU64(&x51, &x52, 0x0, x50, x47);
var x53: u64 = undefined;
var x54: u1 = undefined;
addcarryxU64(&x53, &x54, x52, x48, x45);
var x55: u64 = undefined;
var x56: u1 = undefined;
addcarryxU64(&x55, &x56, x54, x46, x43);
const x57 = (cast(u64, x56) + x44);
var x58: u64 = undefined;
var x59: u1 = undefined;
addcarryxU64(&x58, &x59, 0x0, x35, x49);
var x60: u64 = undefined;
var x61: u1 = undefined;
addcarryxU64(&x60, &x61, x59, x37, x51);
var x62: u64 = undefined;
var x63: u1 = undefined;
addcarryxU64(&x62, &x63, x61, x39, x53);
var x64: u64 = undefined;
var x65: u1 = undefined;
addcarryxU64(&x64, &x65, x63, x41, x55);
var x66: u64 = undefined;
var x67: u1 = undefined;
addcarryxU64(&x66, &x67, x65, cast(u64, x42), x57);
var x68: u64 = undefined;
var x69: u64 = undefined;
mulxU64(&x68, &x69, x58, 0xffffffffffffffff);
var x70: u64 = undefined;
var x71: u64 = undefined;
mulxU64(&x70, &x71, x68, 0xffffffff);
var x72: u64 = undefined;
var x73: u64 = undefined;
mulxU64(&x72, &x73, x68, 0xffffffffffffffff);
var x74: u64 = undefined;
var x75: u64 = undefined;
mulxU64(&x74, &x75, x68, 0xffffffff00000000);
var x76: u64 = undefined;
var x77: u1 = undefined;
addcarryxU64(&x76, &x77, 0x0, x75, x72);
var x78: u64 = undefined;
var x79: u1 = undefined;
addcarryxU64(&x78, &x79, x77, x73, x70);
const x80 = (cast(u64, x79) + x71);
var x81: u64 = undefined;
var x82: u1 = undefined;
addcarryxU64(&x81, &x82, 0x0, x58, x68);
var x83: u64 = undefined;
var x84: u1 = undefined;
addcarryxU64(&x83, &x84, x82, x60, x74);
var x85: u64 = undefined;
var x86: u1 = undefined;
addcarryxU64(&x85, &x86, x84, x62, x76);
var x87: u64 = undefined;
var x88: u1 = undefined;
addcarryxU64(&x87, &x88, x86, x64, x78);
var x89: u64 = undefined;
var x90: u1 = undefined;
addcarryxU64(&x89, &x90, x88, x66, x80);
const x91 = (cast(u64, x90) + cast(u64, x67));
var x92: u64 = undefined;
var x93: u64 = undefined;
mulxU64(&x92, &x93, x2, (arg2[3]));
var x94: u64 = undefined;
var x95: u64 = undefined;
mulxU64(&x94, &x95, x2, (arg2[2]));
var x96: u64 = undefined;
var x97: u64 = undefined;
mulxU64(&x96, &x97, x2, (arg2[1]));
var x98: u64 = undefined;
var x99: u64 = undefined;
mulxU64(&x98, &x99, x2, (arg2[0]));
var x100: u64 = undefined;
var x101: u1 = undefined;
addcarryxU64(&x100, &x101, 0x0, x99, x96);
var x102: u64 = undefined;
var x103: u1 = undefined;
addcarryxU64(&x102, &x103, x101, x97, x94);
var x104: u64 = undefined;
var x105: u1 = undefined;
addcarryxU64(&x104, &x105, x103, x95, x92);
const x106 = (cast(u64, x105) + x93);
var x107: u64 = undefined;
var x108: u1 = undefined;
addcarryxU64(&x107, &x108, 0x0, x83, x98);
var x109: u64 = undefined;
var x110: u1 = undefined;
addcarryxU64(&x109, &x110, x108, x85, x100);
var x111: u64 = undefined;
var x112: u1 = undefined;
addcarryxU64(&x111, &x112, x110, x87, x102);
var x113: u64 = undefined;
var x114: u1 = undefined;
addcarryxU64(&x113, &x114, x112, x89, x104);
var x115: u64 = undefined;
var x116: u1 = undefined;
addcarryxU64(&x115, &x116, x114, x91, x106);
var x117: u64 = undefined;
var x118: u64 = undefined;
mulxU64(&x117, &x118, x107, 0xffffffffffffffff);
var x119: u64 = undefined;
var x120: u64 = undefined;
mulxU64(&x119, &x120, x117, 0xffffffff);
var x121: u64 = undefined;
var x122: u64 = undefined;
mulxU64(&x121, &x122, x117, 0xffffffffffffffff);
var x123: u64 = undefined;
var x124: u64 = undefined;
mulxU64(&x123, &x124, x117, 0xffffffff00000000);
var x125: u64 = undefined;
var x126: u1 = undefined;
addcarryxU64(&x125, &x126, 0x0, x124, x121);
var x127: u64 = undefined;
var x128: u1 = undefined;
addcarryxU64(&x127, &x128, x126, x122, x119);
const x129 = (cast(u64, x128) + x120);
var x130: u64 = undefined;
var x131: u1 = undefined;
addcarryxU64(&x130, &x131, 0x0, x107, x117);
var x132: u64 = undefined;
var x133: u1 = undefined;
addcarryxU64(&x132, &x133, x131, x109, x123);
var x134: u64 = undefined;
var x135: u1 = undefined;
addcarryxU64(&x134, &x135, x133, x111, x125);
var x136: u64 = undefined;
var x137: u1 = undefined;
addcarryxU64(&x136, &x137, x135, x113, x127);
var x138: u64 = undefined;
var x139: u1 = undefined;
addcarryxU64(&x138, &x139, x137, x115, x129);
const x140 = (cast(u64, x139) + cast(u64, x116));
var x141: u64 = undefined;
var x142: u64 = undefined;
mulxU64(&x141, &x142, x3, (arg2[3]));
var x143: u64 = undefined;
var x144: u64 = undefined;
mulxU64(&x143, &x144, x3, (arg2[2]));
var x145: u64 = undefined;
var x146: u64 = undefined;
mulxU64(&x145, &x146, x3, (arg2[1]));
var x147: u64 = undefined;
var x148: u64 = undefined;
mulxU64(&x147, &x148, x3, (arg2[0]));
var x149: u64 = undefined;
var x150: u1 = undefined;
addcarryxU64(&x149, &x150, 0x0, x148, x145);
var x151: u64 = undefined;
var x152: u1 = undefined;
addcarryxU64(&x151, &x152, x150, x146, x143);
var x153: u64 = undefined;
var x154: u1 = undefined;
addcarryxU64(&x153, &x154, x152, x144, x141);
const x155 = (cast(u64, x154) + x142);
var x156: u64 = undefined;
var x157: u1 = undefined;
addcarryxU64(&x156, &x157, 0x0, x132, x147);
var x158: u64 = undefined;
var x159: u1 = undefined;
addcarryxU64(&x158, &x159, x157, x134, x149);
var x160: u64 = undefined;
var x161: u1 = undefined;
addcarryxU64(&x160, &x161, x159, x136, x151);
var x162: u64 = undefined;
var x163: u1 = undefined;
addcarryxU64(&x162, &x163, x161, x138, x153);
var x164: u64 = undefined;
var x165: u1 = undefined;
addcarryxU64(&x164, &x165, x163, x140, x155);
var x166: u64 = undefined;
var x167: u64 = undefined;
mulxU64(&x166, &x167, x156, 0xffffffffffffffff);
var x168: u64 = undefined;
var x169: u64 = undefined;
mulxU64(&x168, &x169, x166, 0xffffffff);
var x170: u64 = undefined;
var x171: u64 = undefined;
mulxU64(&x170, &x171, x166, 0xffffffffffffffff);
var x172: u64 = undefined;
var x173: u64 = undefined;
mulxU64(&x172, &x173, x166, 0xffffffff00000000);
var x174: u64 = undefined;
var x175: u1 = undefined;
addcarryxU64(&x174, &x175, 0x0, x173, x170);
var x176: u64 = undefined;
var x177: u1 = undefined;
addcarryxU64(&x176, &x177, x175, x171, x168);
const x178 = (cast(u64, x177) + x169);
var x179: u64 = undefined;
var x180: u1 = undefined;
addcarryxU64(&x179, &x180, 0x0, x156, x166);
var x181: u64 = undefined;
var x182: u1 = undefined;
addcarryxU64(&x181, &x182, x180, x158, x172);
var x183: u64 = undefined;
var x184: u1 = undefined;
addcarryxU64(&x183, &x184, x182, x160, x174);
var x185: u64 = undefined;
var x186: u1 = undefined;
addcarryxU64(&x185, &x186, x184, x162, x176);
var x187: u64 = undefined;
var x188: u1 = undefined;
addcarryxU64(&x187, &x188, x186, x164, x178);
const x189 = (cast(u64, x188) + cast(u64, x165));
var x190: u64 = undefined;
var x191: u1 = undefined;
subborrowxU64(&x190, &x191, 0x0, x181, cast(u64, 0x1));
var x192: u64 = undefined;
var x193: u1 = undefined;
subborrowxU64(&x192, &x193, x191, x183, 0xffffffff00000000);
var x194: u64 = undefined;
var x195: u1 = undefined;
subborrowxU64(&x194, &x195, x193, x185, 0xffffffffffffffff);
var x196: u64 = undefined;
var x197: u1 = undefined;
subborrowxU64(&x196, &x197, x195, x187, 0xffffffff);
var x198: u64 = undefined;
var x199: u1 = undefined;
subborrowxU64(&x198, &x199, x197, x189, cast(u64, 0x0));
var x200: u64 = undefined;
cmovznzU64(&x200, x199, x190, x181);
var x201: u64 = undefined;
cmovznzU64(&x201, x199, x192, x183);
var x202: u64 = undefined;
cmovznzU64(&x202, x199, x194, x185);
var x203: u64 = undefined;
cmovznzU64(&x203, x199, x196, x187);
out1[0] = x200;
out1[1] = x201;
out1[2] = x202;
out1[3] = x203;
}
/// The function square squares a field element in the Montgomery domain.
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// Postconditions:
/// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg1)) mod m
/// 0 ≤ eval out1 < m
///
/// Input Bounds:
/// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
pub fn square(out1: *[4]u64, arg1: [4]u64) void {
@setRuntimeSafety(mode == .Debug);
const x1 = (arg1[1]);
const x2 = (arg1[2]);
const x3 = (arg1[3]);
const x4 = (arg1[0]);
var x5: u64 = undefined;
var x6: u64 = undefined;
mulxU64(&x5, &x6, x4, (arg1[3]));
var x7: u64 = undefined;
var x8: u64 = undefined;
mulxU64(&x7, &x8, x4, (arg1[2]));
var x9: u64 = undefined;
var x10: u64 = undefined;
mulxU64(&x9, &x10, x4, (arg1[1]));
var x11: u64 = undefined;
var x12: u64 = undefined;
mulxU64(&x11, &x12, x4, (arg1[0]));
var x13: u64 = undefined;
var x14: u1 = undefined;
addcarryxU64(&x13, &x14, 0x0, x12, x9);
var x15: u64 = undefined;
var x16: u1 = undefined;
addcarryxU64(&x15, &x16, x14, x10, x7);
var x17: u64 = undefined;
var x18: u1 = undefined;
addcarryxU64(&x17, &x18, x16, x8, x5);
const x19 = (cast(u64, x18) + x6);
var x20: u64 = undefined;
var x21: u64 = undefined;
mulxU64(&x20, &x21, x11, 0xffffffffffffffff);
var x22: u64 = undefined;
var x23: u64 = undefined;
mulxU64(&x22, &x23, x20, 0xffffffff);
var x24: u64 = undefined;
var x25: u64 = undefined;
mulxU64(&x24, &x25, x20, 0xffffffffffffffff);
var x26: u64 = undefined;
var x27: u64 = undefined;
mulxU64(&x26, &x27, x20, 0xffffffff00000000);
var x28: u64 = undefined;
var x29: u1 = undefined;
addcarryxU64(&x28, &x29, 0x0, x27, x24);
var x30: u64 = undefined;
var x31: u1 = undefined;
addcarryxU64(&x30, &x31, x29, x25, x22);
const x32 = (cast(u64, x31) + x23);
var x33: u64 = undefined;
var x34: u1 = undefined;
addcarryxU64(&x33, &x34, 0x0, x11, x20);
var x35: u64 = undefined;
var x36: u1 = undefined;
addcarryxU64(&x35, &x36, x34, x13, x26);
var x37: u64 = undefined;
var x38: u1 = undefined;
addcarryxU64(&x37, &x38, x36, x15, x28);
var x39: u64 = undefined;
var x40: u1 = undefined;
addcarryxU64(&x39, &x40, x38, x17, x30);
var x41: u64 = undefined;
var x42: u1 = undefined;
addcarryxU64(&x41, &x42, x40, x19, x32);
var x43: u64 = undefined;
var x44: u64 = undefined;
mulxU64(&x43, &x44, x1, (arg1[3]));
var x45: u64 = undefined;
var x46: u64 = undefined;
mulxU64(&x45, &x46, x1, (arg1[2]));
var x47: u64 = undefined;
var x48: u64 = undefined;
mulxU64(&x47, &x48, x1, (arg1[1]));
var x49: u64 = undefined;
var x50: u64 = undefined;
mulxU64(&x49, &x50, x1, (arg1[0]));
var x51: u64 = undefined;
var x52: u1 = undefined;
addcarryxU64(&x51, &x52, 0x0, x50, x47);
var x53: u64 = undefined;
var x54: u1 = undefined;
addcarryxU64(&x53, &x54, x52, x48, x45);
var x55: u64 = undefined;
var x56: u1 = undefined;
addcarryxU64(&x55, &x56, x54, x46, x43);
const x57 = (cast(u64, x56) + x44);
var x58: u64 = undefined;
var x59: u1 = undefined;
addcarryxU64(&x58, &x59, 0x0, x35, x49);
var x60: u64 = undefined;
var x61: u1 = undefined;
addcarryxU64(&x60, &x61, x59, x37, x51);
var x62: u64 = undefined;
var x63: u1 = undefined;
addcarryxU64(&x62, &x63, x61, x39, x53);
var x64: u64 = undefined;
var x65: u1 = undefined;
addcarryxU64(&x64, &x65, x63, x41, x55);
var x66: u64 = undefined;
var x67: u1 = undefined;
addcarryxU64(&x66, &x67, x65, cast(u64, x42), x57);
var x68: u64 = undefined;
var x69: u64 = undefined;
mulxU64(&x68, &x69, x58, 0xffffffffffffffff);
var x70: u64 = undefined;
var x71: u64 = undefined;
mulxU64(&x70, &x71, x68, 0xffffffff);
var x72: u64 = undefined;
var x73: u64 = undefined;
mulxU64(&x72, &x73, x68, 0xffffffffffffffff);
var x74: u64 = undefined;
var x75: u64 = undefined;
mulxU64(&x74, &x75, x68, 0xffffffff00000000);
var x76: u64 = undefined;
var x77: u1 = undefined;
addcarryxU64(&x76, &x77, 0x0, x75, x72);
var x78: u64 = undefined;
var x79: u1 = undefined;
addcarryxU64(&x78, &x79, x77, x73, x70);
const x80 = (cast(u64, x79) + x71);
var x81: u64 = undefined;
var x82: u1 = undefined;
addcarryxU64(&x81, &x82, 0x0, x58, x68);
var x83: u64 = undefined;
var x84: u1 = undefined;
addcarryxU64(&x83, &x84, x82, x60, x74);
var x85: u64 = undefined;
var x86: u1 = undefined;
addcarryxU64(&x85, &x86, x84, x62, x76);
var x87: u64 = undefined;
var x88: u1 = undefined;
addcarryxU64(&x87, &x88, x86, x64, x78);
var x89: u64 = undefined;
var x90: u1 = undefined;
addcarryxU64(&x89, &x90, x88, x66, x80);
const x91 = (cast(u64, x90) + cast(u64, x67));
var x92: u64 = undefined;
var x93: u64 = undefined;
mulxU64(&x92, &x93, x2, (arg1[3]));
var x94: u64 = undefined;
var x95: u64 = undefined;
mulxU64(&x94, &x95, x2, (arg1[2]));
var x96: u64 = undefined;
var x97: u64 = undefined;
mulxU64(&x96, &x97, x2, (arg1[1]));
var x98: u64 = undefined;
var x99: u64 = undefined;
mulxU64(&x98, &x99, x2, (arg1[0]));
var x100: u64 = undefined;
var x101: u1 = undefined;
addcarryxU64(&x100, &x101, 0x0, x99, x96);
var x102: u64 = undefined;
var x103: u1 = undefined;
addcarryxU64(&x102, &x103, x101, x97, x94);
var x104: u64 = undefined;
var x105: u1 = undefined;
addcarryxU64(&x104, &x105, x103, x95, x92);
const x106 = (cast(u64, x105) + x93);
var x107: u64 = undefined;
var x108: u1 = undefined;
addcarryxU64(&x107, &x108, 0x0, x83, x98);
var x109: u64 = undefined;
var x110: u1 = undefined;
addcarryxU64(&x109, &x110, x108, x85, x100);
var x111: u64 = undefined;
var x112: u1 = undefined;
addcarryxU64(&x111, &x112, x110, x87, x102);
var x113: u64 = undefined;
var x114: u1 = undefined;
addcarryxU64(&x113, &x114, x112, x89, x104);
var x115: u64 = undefined;
var x116: u1 = undefined;
addcarryxU64(&x115, &x116, x114, x91, x106);
var x117: u64 = undefined;
var x118: u64 = undefined;
mulxU64(&x117, &x118, x107, 0xffffffffffffffff);
var x119: u64 = undefined;
var x120: u64 = undefined;
mulxU64(&x119, &x120, x117, 0xffffffff);
var x121: u64 = undefined;
var x122: u64 = undefined;
mulxU64(&x121, &x122, x117, 0xffffffffffffffff);
var x123: u64 = undefined;
var x124: u64 = undefined;
mulxU64(&x123, &x124, x117, 0xffffffff00000000);
var x125: u64 = undefined;
var x126: u1 = undefined;
addcarryxU64(&x125, &x126, 0x0, x124, x121);
var x127: u64 = undefined;
var x128: u1 = undefined;
addcarryxU64(&x127, &x128, x126, x122, x119);
const x129 = (cast(u64, x128) + x120);
var x130: u64 = undefined;
var x131: u1 = undefined;
addcarryxU64(&x130, &x131, 0x0, x107, x117);
var x132: u64 = undefined;
var x133: u1 = undefined;
addcarryxU64(&x132, &x133, x131, x109, x123);
var x134: u64 = undefined;
var x135: u1 = undefined;
addcarryxU64(&x134, &x135, x133, x111, x125);
var x136: u64 = undefined;
var x137: u1 = undefined;
addcarryxU64(&x136, &x137, x135, x113, x127);
var x138: u64 = undefined;
var x139: u1 = undefined;
addcarryxU64(&x138, &x139, x137, x115, x129);
const x140 = (cast(u64, x139) + cast(u64, x116));
var x141: u64 = undefined;
var x142: u64 = undefined;
mulxU64(&x141, &x142, x3, (arg1[3]));
var x143: u64 = undefined;
var x144: u64 = undefined;
mulxU64(&x143, &x144, x3, (arg1[2]));
var x145: u64 = undefined;
var x146: u64 = undefined;
mulxU64(&x145, &x146, x3, (arg1[1]));
var x147: u64 = undefined;
var x148: u64 = undefined;
mulxU64(&x147, &x148, x3, (arg1[0]));
var x149: u64 = undefined;
var x150: u1 = undefined;
addcarryxU64(&x149, &x150, 0x0, x148, x145);
var x151: u64 = undefined;
var x152: u1 = undefined;
addcarryxU64(&x151, &x152, x150, x146, x143);
var x153: u64 = undefined;
var x154: u1 = undefined;
addcarryxU64(&x153, &x154, x152, x144, x141);
const x155 = (cast(u64, x154) + x142);
var x156: u64 = undefined;
var x157: u1 = undefined;
addcarryxU64(&x156, &x157, 0x0, x132, x147);
var x158: u64 = undefined;
var x159: u1 = undefined;
addcarryxU64(&x158, &x159, x157, x134, x149);
var x160: u64 = undefined;
var x161: u1 = undefined;
addcarryxU64(&x160, &x161, x159, x136, x151);
var x162: u64 = undefined;
var x163: u1 = undefined;
addcarryxU64(&x162, &x163, x161, x138, x153);
var x164: u64 = undefined;
var x165: u1 = undefined;
addcarryxU64(&x164, &x165, x163, x140, x155);
var x166: u64 = undefined;
var x167: u64 = undefined;
mulxU64(&x166, &x167, x156, 0xffffffffffffffff);
var x168: u64 = undefined;
var x169: u64 = undefined;
mulxU64(&x168, &x169, x166, 0xffffffff);
var x170: u64 = undefined;
var x171: u64 = undefined;
mulxU64(&x170, &x171, x166, 0xffffffffffffffff);
var x172: u64 = undefined;
var x173: u64 = undefined;
mulxU64(&x172, &x173, x166, 0xffffffff00000000);
var x174: u64 = undefined;
var x175: u1 = undefined;
addcarryxU64(&x174, &x175, 0x0, x173, x170);
var x176: u64 = undefined;
var x177: u1 = undefined;
addcarryxU64(&x176, &x177, x175, x171, x168);
const x178 = (cast(u64, x177) + x169);
var x179: u64 = undefined;
var x180: u1 = undefined;
addcarryxU64(&x179, &x180, 0x0, x156, x166);
var x181: u64 = undefined;
var x182: u1 = undefined;
addcarryxU64(&x181, &x182, x180, x158, x172);
var x183: u64 = undefined;
var x184: u1 = undefined;
addcarryxU64(&x183, &x184, x182, x160, x174);
var x185: u64 = undefined;
var x186: u1 = undefined;
addcarryxU64(&x185, &x186, x184, x162, x176);
var x187: u64 = undefined;
var x188: u1 = undefined;
addcarryxU64(&x187, &x188, x186, x164, x178);
const x189 = (cast(u64, x188) + cast(u64, x165));
var x190: u64 = undefined;
var x191: u1 = undefined;
subborrowxU64(&x190, &x191, 0x0, x181, cast(u64, 0x1));
var x192: u64 = undefined;
var x193: u1 = undefined;
subborrowxU64(&x192, &x193, x191, x183, 0xffffffff00000000);
var x194: u64 = undefined;
var x195: u1 = undefined;
subborrowxU64(&x194, &x195, x193, x185, 0xffffffffffffffff);
var x196: u64 = undefined;
var x197: u1 = undefined;
subborrowxU64(&x196, &x197, x195, x187, 0xffffffff);
var x198: u64 = undefined;
var x199: u1 = undefined;
subborrowxU64(&x198, &x199, x197, x189, cast(u64, 0x0));
var x200: u64 = undefined;
cmovznzU64(&x200, x199, x190, x181);
var x201: u64 = undefined;
cmovznzU64(&x201, x199, x192, x183);
var x202: u64 = undefined;
cmovznzU64(&x202, x199, x194, x185);
var x203: u64 = undefined;
cmovznzU64(&x203, x199, x196, x187);
out1[0] = x200;
out1[1] = x201;
out1[2] = x202;
out1[3] = x203;
}
/// The function add adds two field elements in the Montgomery domain.
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// 0 ≤ eval arg2 < m
/// Postconditions:
/// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) + eval (from_montgomery arg2)) mod m
/// 0 ≤ eval out1 < m
///
/// Input Bounds:
/// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
/// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
pub fn add(out1: *[4]u64, arg1: [4]u64, arg2: [4]u64) void {
@setRuntimeSafety(mode == .Debug);
var x1: u64 = undefined;
var x2: u1 = undefined;
addcarryxU64(&x1, &x2, 0x0, (arg1[0]), (arg2[0]));
var x3: u64 = undefined;
var x4: u1 = undefined;
addcarryxU64(&x3, &x4, x2, (arg1[1]), (arg2[1]));
var x5: u64 = undefined;
var x6: u1 = undefined;
addcarryxU64(&x5, &x6, x4, (arg1[2]), (arg2[2]));
var x7: u64 = undefined;
var x8: u1 = undefined;
addcarryxU64(&x7, &x8, x6, (arg1[3]), (arg2[3]));
var x9: u64 = undefined;
var x10: u1 = undefined;
subborrowxU64(&x9, &x10, 0x0, x1, cast(u64, 0x1));
var x11: u64 = undefined;
var x12: u1 = undefined;
subborrowxU64(&x11, &x12, x10, x3, 0xffffffff00000000);
var x13: u64 = undefined;
var x14: u1 = undefined;
subborrowxU64(&x13, &x14, x12, x5, 0xffffffffffffffff);
var x15: u64 = undefined;
var x16: u1 = undefined;
subborrowxU64(&x15, &x16, x14, x7, 0xffffffff);
var x17: u64 = undefined;
var x18: u1 = undefined;
subborrowxU64(&x17, &x18, x16, cast(u64, x8), cast(u64, 0x0));
var x19: u64 = undefined;
cmovznzU64(&x19, x18, x9, x1);
var x20: u64 = undefined;
cmovznzU64(&x20, x18, x11, x3);
var x21: u64 = undefined;
cmovznzU64(&x21, x18, x13, x5);
var x22: u64 = undefined;
cmovznzU64(&x22, x18, x15, x7);
out1[0] = x19;
out1[1] = x20;
out1[2] = x21;
out1[3] = x22;
}
/// The function sub subtracts two field elements in the Montgomery domain.
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// 0 ≤ eval arg2 < m
/// Postconditions:
/// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) - eval (from_montgomery arg2)) mod m
/// 0 ≤ eval out1 < m
///
/// Input Bounds:
/// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
/// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
pub fn sub(out1: *[4]u64, arg1: [4]u64, arg2: [4]u64) void {
@setRuntimeSafety(mode == .Debug);
var x1: u64 = undefined;
var x2: u1 = undefined;
subborrowxU64(&x1, &x2, 0x0, (arg1[0]), (arg2[0]));
var x3: u64 = undefined;
var x4: u1 = undefined;
subborrowxU64(&x3, &x4, x2, (arg1[1]), (arg2[1]));
var x5: u64 = undefined;
var x6: u1 = undefined;
subborrowxU64(&x5, &x6, x4, (arg1[2]), (arg2[2]));
var x7: u64 = undefined;
var x8: u1 = undefined;
subborrowxU64(&x7, &x8, x6, (arg1[3]), (arg2[3]));
var x9: u64 = undefined;
cmovznzU64(&x9, x8, cast(u64, 0x0), 0xffffffffffffffff);
var x10: u64 = undefined;
var x11: u1 = undefined;
addcarryxU64(&x10, &x11, 0x0, x1, cast(u64, cast(u1, (x9 & cast(u64, 0x1)))));
var x12: u64 = undefined;
var x13: u1 = undefined;
addcarryxU64(&x12, &x13, x11, x3, (x9 & 0xffffffff00000000));
var x14: u64 = undefined;
var x15: u1 = undefined;
addcarryxU64(&x14, &x15, x13, x5, x9);
var x16: u64 = undefined;
var x17: u1 = undefined;
addcarryxU64(&x16, &x17, x15, x7, (x9 & 0xffffffff));
out1[0] = x10;
out1[1] = x12;
out1[2] = x14;
out1[3] = x16;
}
/// The function opp negates a field element in the Montgomery domain.
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// Postconditions:
/// eval (from_montgomery out1) mod m = -eval (from_montgomery arg1) mod m
/// 0 ≤ eval out1 < m
///
/// Input Bounds:
/// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
pub fn opp(out1: *[4]u64, arg1: [4]u64) void {
@setRuntimeSafety(mode == .Debug);
var x1: u64 = undefined;
var x2: u1 = undefined;
subborrowxU64(&x1, &x2, 0x0, cast(u64, 0x0), (arg1[0]));
var x3: u64 = undefined;
var x4: u1 = undefined;
subborrowxU64(&x3, &x4, x2, cast(u64, 0x0), (arg1[1]));
var x5: u64 = undefined;
var x6: u1 = undefined;
subborrowxU64(&x5, &x6, x4, cast(u64, 0x0), (arg1[2]));
var x7: u64 = undefined;
var x8: u1 = undefined;
subborrowxU64(&x7, &x8, x6, cast(u64, 0x0), (arg1[3]));
var x9: u64 = undefined;
cmovznzU64(&x9, x8, cast(u64, 0x0), 0xffffffffffffffff);
var x10: u64 = undefined;
var x11: u1 = undefined;
addcarryxU64(&x10, &x11, 0x0, x1, cast(u64, cast(u1, (x9 & cast(u64, 0x1)))));
var x12: u64 = undefined;
var x13: u1 = undefined;
addcarryxU64(&x12, &x13, x11, x3, (x9 & 0xffffffff00000000));
var x14: u64 = undefined;
var x15: u1 = undefined;
addcarryxU64(&x14, &x15, x13, x5, x9);
var x16: u64 = undefined;
var x17: u1 = undefined;
addcarryxU64(&x16, &x17, x15, x7, (x9 & 0xffffffff));
out1[0] = x10;
out1[1] = x12;
out1[2] = x14;
out1[3] = x16;
}
/// The function fromMontgomery translates a field element out of the Montgomery domain.
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// Postconditions:
/// eval out1 mod m = (eval arg1 * ((2^64)⁻¹ mod m)^4) mod m
/// 0 ≤ eval out1 < m
///
/// Input Bounds:
/// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
pub fn fromMontgomery(out1: *[4]u64, arg1: [4]u64) void {
@setRuntimeSafety(mode == .Debug);
const x1 = (arg1[0]);
var x2: u64 = undefined;
var x3: u64 = undefined;
mulxU64(&x2, &x3, x1, 0xffffffffffffffff);
var x4: u64 = undefined;
var x5: u64 = undefined;
mulxU64(&x4, &x5, x2, 0xffffffff);
var x6: u64 = undefined;
var x7: u64 = undefined;
mulxU64(&x6, &x7, x2, 0xffffffffffffffff);
var x8: u64 = undefined;
var x9: u64 = undefined;
mulxU64(&x8, &x9, x2, 0xffffffff00000000);
var x10: u64 = undefined;
var x11: u1 = undefined;
addcarryxU64(&x10, &x11, 0x0, x9, x6);
var x12: u64 = undefined;
var x13: u1 = undefined;
addcarryxU64(&x12, &x13, x11, x7, x4);
var x14: u64 = undefined;
var x15: u1 = undefined;
addcarryxU64(&x14, &x15, 0x0, x1, x2);
var x16: u64 = undefined;
var x17: u1 = undefined;
addcarryxU64(&x16, &x17, x15, cast(u64, 0x0), x8);
var x18: u64 = undefined;
var x19: u1 = undefined;
addcarryxU64(&x18, &x19, x17, cast(u64, 0x0), x10);
var x20: u64 = undefined;
var x21: u1 = undefined;
addcarryxU64(&x20, &x21, x19, cast(u64, 0x0), x12);
var x22: u64 = undefined;
var x23: u1 = undefined;
addcarryxU64(&x22, &x23, 0x0, x16, (arg1[1]));
var x24: u64 = undefined;
var x25: u1 = undefined;
addcarryxU64(&x24, &x25, x23, x18, cast(u64, 0x0));
var x26: u64 = undefined;
var x27: u1 = undefined;
addcarryxU64(&x26, &x27, x25, x20, cast(u64, 0x0));
var x28: u64 = undefined;
var x29: u64 = undefined;
mulxU64(&x28, &x29, x22, 0xffffffffffffffff);
var x30: u64 = undefined;
var x31: u64 = undefined;
mulxU64(&x30, &x31, x28, 0xffffffff);
var x32: u64 = undefined;
var x33: u64 = undefined;
mulxU64(&x32, &x33, x28, 0xffffffffffffffff);
var x34: u64 = undefined;
var x35: u64 = undefined;
mulxU64(&x34, &x35, x28, 0xffffffff00000000);
var x36: u64 = undefined;
var x37: u1 = undefined;
addcarryxU64(&x36, &x37, 0x0, x35, x32);
var x38: u64 = undefined;
var x39: u1 = undefined;
addcarryxU64(&x38, &x39, x37, x33, x30);
var x40: u64 = undefined;
var x41: u1 = undefined;
addcarryxU64(&x40, &x41, 0x0, x22, x28);
var x42: u64 = undefined;
var x43: u1 = undefined;
addcarryxU64(&x42, &x43, x41, x24, x34);
var x44: u64 = undefined;
var x45: u1 = undefined;
addcarryxU64(&x44, &x45, x43, x26, x36);
var x46: u64 = undefined;
var x47: u1 = undefined;
addcarryxU64(&x46, &x47, x45, (cast(u64, x27) + (cast(u64, x21) + (cast(u64, x13) + x5))), x38);
var x48: u64 = undefined;
var x49: u1 = undefined;
addcarryxU64(&x48, &x49, 0x0, x42, (arg1[2]));
var x50: u64 = undefined;
var x51: u1 = undefined;
addcarryxU64(&x50, &x51, x49, x44, cast(u64, 0x0));
var x52: u64 = undefined;
var x53: u1 = undefined;
addcarryxU64(&x52, &x53, x51, x46, cast(u64, 0x0));
var x54: u64 = undefined;
var x55: u64 = undefined;
mulxU64(&x54, &x55, x48, 0xffffffffffffffff);
var x56: u64 = undefined;
var x57: u64 = undefined;
mulxU64(&x56, &x57, x54, 0xffffffff);
var x58: u64 = undefined;
var x59: u64 = undefined;
mulxU64(&x58, &x59, x54, 0xffffffffffffffff);
var x60: u64 = undefined;
var x61: u64 = undefined;
mulxU64(&x60, &x61, x54, 0xffffffff00000000);
var x62: u64 = undefined;
var x63: u1 = undefined;
addcarryxU64(&x62, &x63, 0x0, x61, x58);
var x64: u64 = undefined;
var x65: u1 = undefined;
addcarryxU64(&x64, &x65, x63, x59, x56);
var x66: u64 = undefined;
var x67: u1 = undefined;
addcarryxU64(&x66, &x67, 0x0, x48, x54);
var x68: u64 = undefined;
var x69: u1 = undefined;
addcarryxU64(&x68, &x69, x67, x50, x60);
var x70: u64 = undefined;
var x71: u1 = undefined;
addcarryxU64(&x70, &x71, x69, x52, x62);
var x72: u64 = undefined;
var x73: u1 = undefined;
addcarryxU64(&x72, &x73, x71, (cast(u64, x53) + (cast(u64, x47) + (cast(u64, x39) + x31))), x64);
var x74: u64 = undefined;
var x75: u1 = undefined;
addcarryxU64(&x74, &x75, 0x0, x68, (arg1[3]));
var x76: u64 = undefined;
var x77: u1 = undefined;
addcarryxU64(&x76, &x77, x75, x70, cast(u64, 0x0));
var x78: u64 = undefined;
var x79: u1 = undefined;
addcarryxU64(&x78, &x79, x77, x72, cast(u64, 0x0));
var x80: u64 = undefined;
var x81: u64 = undefined;
mulxU64(&x80, &x81, x74, 0xffffffffffffffff);
var x82: u64 = undefined;
var x83: u64 = undefined;
mulxU64(&x82, &x83, x80, 0xffffffff);
var x84: u64 = undefined;
var x85: u64 = undefined;
mulxU64(&x84, &x85, x80, 0xffffffffffffffff);
var x86: u64 = undefined;
var x87: u64 = undefined;
mulxU64(&x86, &x87, x80, 0xffffffff00000000);
var x88: u64 = undefined;
var x89: u1 = undefined;
addcarryxU64(&x88, &x89, 0x0, x87, x84);
var x90: u64 = undefined;
var x91: u1 = undefined;
addcarryxU64(&x90, &x91, x89, x85, x82);
var x92: u64 = undefined;
var x93: u1 = undefined;
addcarryxU64(&x92, &x93, 0x0, x74, x80);
var x94: u64 = undefined;
var x95: u1 = undefined;
addcarryxU64(&x94, &x95, x93, x76, x86);
var x96: u64 = undefined;
var x97: u1 = undefined;
addcarryxU64(&x96, &x97, x95, x78, x88);
var x98: u64 = undefined;
var x99: u1 = undefined;
addcarryxU64(&x98, &x99, x97, (cast(u64, x79) + (cast(u64, x73) + (cast(u64, x65) + x57))), x90);
const x100 = (cast(u64, x99) + (cast(u64, x91) + x83));
var x101: u64 = undefined;
var x102: u1 = undefined;
subborrowxU64(&x101, &x102, 0x0, x94, cast(u64, 0x1));
var x103: u64 = undefined;
var x104: u1 = undefined;
subborrowxU64(&x103, &x104, x102, x96, 0xffffffff00000000);
var x105: u64 = undefined;
var x106: u1 = undefined;
subborrowxU64(&x105, &x106, x104, x98, 0xffffffffffffffff);
var x107: u64 = undefined;
var x108: u1 = undefined;
subborrowxU64(&x107, &x108, x106, x100, 0xffffffff);
var x109: u64 = undefined;
var x110: u1 = undefined;
subborrowxU64(&x109, &x110, x108, cast(u64, 0x0), cast(u64, 0x0));
var x111: u64 = undefined;
cmovznzU64(&x111, x110, x101, x94);
var x112: u64 = undefined;
cmovznzU64(&x112, x110, x103, x96);
var x113: u64 = undefined;
cmovznzU64(&x113, x110, x105, x98);
var x114: u64 = undefined;
cmovznzU64(&x114, x110, x107, x100);
out1[0] = x111;
out1[1] = x112;
out1[2] = x113;
out1[3] = x114;
}
/// The function toMontgomery translates a field element into the Montgomery domain.
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// Postconditions:
/// eval (from_montgomery out1) mod m = eval arg1 mod m
/// 0 ≤ eval out1 < m
///
/// Input Bounds:
/// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
pub fn toMontgomery(out1: *[4]u64, arg1: [4]u64) void {
@setRuntimeSafety(mode == .Debug);
const x1 = (arg1[1]);
const x2 = (arg1[2]);
const x3 = (arg1[3]);
const x4 = (arg1[0]);
var x5: u64 = undefined;
var x6: u64 = undefined;
mulxU64(&x5, &x6, x4, 0xffffffff);
var x7: u64 = undefined;
var x8: u64 = undefined;
mulxU64(&x7, &x8, x4, 0xfffffffe00000000);
var x9: u64 = undefined;
var x10: u64 = undefined;
mulxU64(&x9, &x10, x4, 0xffffffff00000000);
var x11: u64 = undefined;
var x12: u64 = undefined;
mulxU64(&x11, &x12, x4, 0xffffffff00000001);
var x13: u64 = undefined;
var x14: u1 = undefined;
addcarryxU64(&x13, &x14, 0x0, x12, x9);
var x15: u64 = undefined;
var x16: u1 = undefined;
addcarryxU64(&x15, &x16, x14, x10, x7);
var x17: u64 = undefined;
var x18: u1 = undefined;
addcarryxU64(&x17, &x18, x16, x8, x5);
var x19: u64 = undefined;
var x20: u64 = undefined;
mulxU64(&x19, &x20, x11, 0xffffffffffffffff);
var x21: u64 = undefined;
var x22: u64 = undefined;
mulxU64(&x21, &x22, x19, 0xffffffff);
var x23: u64 = undefined;
var x24: u64 = undefined;
mulxU64(&x23, &x24, x19, 0xffffffffffffffff);
var x25: u64 = undefined;
var x26: u64 = undefined;
mulxU64(&x25, &x26, x19, 0xffffffff00000000);
var x27: u64 = undefined;
var x28: u1 = undefined;
addcarryxU64(&x27, &x28, 0x0, x26, x23);
var x29: u64 = undefined;
var x30: u1 = undefined;
addcarryxU64(&x29, &x30, x28, x24, x21);
var x31: u64 = undefined;
var x32: u1 = undefined;
addcarryxU64(&x31, &x32, 0x0, x11, x19);
var x33: u64 = undefined;
var x34: u1 = undefined;
addcarryxU64(&x33, &x34, x32, x13, x25);
var x35: u64 = undefined;
var x36: u1 = undefined;
addcarryxU64(&x35, &x36, x34, x15, x27);
var x37: u64 = undefined;
var x38: u1 = undefined;
addcarryxU64(&x37, &x38, x36, x17, x29);
var x39: u64 = undefined;
var x40: u64 = undefined;
mulxU64(&x39, &x40, x1, 0xffffffff);
var x41: u64 = undefined;
var x42: u64 = undefined;
mulxU64(&x41, &x42, x1, 0xfffffffe00000000);
var x43: u64 = undefined;
var x44: u64 = undefined;
mulxU64(&x43, &x44, x1, 0xffffffff00000000);
var x45: u64 = undefined;
var x46: u64 = undefined;
mulxU64(&x45, &x46, x1, 0xffffffff00000001);
var x47: u64 = undefined;
var x48: u1 = undefined;
addcarryxU64(&x47, &x48, 0x0, x46, x43);
var x49: u64 = undefined;
var x50: u1 = undefined;
addcarryxU64(&x49, &x50, x48, x44, x41);
var x51: u64 = undefined;
var x52: u1 = undefined;
addcarryxU64(&x51, &x52, x50, x42, x39);
var x53: u64 = undefined;
var x54: u1 = undefined;
addcarryxU64(&x53, &x54, 0x0, x33, x45);
var x55: u64 = undefined;
var x56: u1 = undefined;
addcarryxU64(&x55, &x56, x54, x35, x47);
var x57: u64 = undefined;
var x58: u1 = undefined;
addcarryxU64(&x57, &x58, x56, x37, x49);
var x59: u64 = undefined;
var x60: u1 = undefined;
addcarryxU64(&x59, &x60, x58, ((cast(u64, x38) + (cast(u64, x18) + x6)) + (cast(u64, x30) + x22)), x51);
var x61: u64 = undefined;
var x62: u64 = undefined;
mulxU64(&x61, &x62, x53, 0xffffffffffffffff);
var x63: u64 = undefined;
var x64: u64 = undefined;
mulxU64(&x63, &x64, x61, 0xffffffff);
var x65: u64 = undefined;
var x66: u64 = undefined;
mulxU64(&x65, &x66, x61, 0xffffffffffffffff);
var x67: u64 = undefined;
var x68: u64 = undefined;
mulxU64(&x67, &x68, x61, 0xffffffff00000000);
var x69: u64 = undefined;
var x70: u1 = undefined;
addcarryxU64(&x69, &x70, 0x0, x68, x65);
var x71: u64 = undefined;
var x72: u1 = undefined;
addcarryxU64(&x71, &x72, x70, x66, x63);
var x73: u64 = undefined;
var x74: u1 = undefined;
addcarryxU64(&x73, &x74, 0x0, x53, x61);
var x75: u64 = undefined;
var x76: u1 = undefined;
addcarryxU64(&x75, &x76, x74, x55, x67);
var x77: u64 = undefined;
var x78: u1 = undefined;
addcarryxU64(&x77, &x78, x76, x57, x69);
var x79: u64 = undefined;
var x80: u1 = undefined;
addcarryxU64(&x79, &x80, x78, x59, x71);
var x81: u64 = undefined;
var x82: u64 = undefined;
mulxU64(&x81, &x82, x2, 0xffffffff);
var x83: u64 = undefined;
var x84: u64 = undefined;
mulxU64(&x83, &x84, x2, 0xfffffffe00000000);
var x85: u64 = undefined;
var x86: u64 = undefined;
mulxU64(&x85, &x86, x2, 0xffffffff00000000);
var x87: u64 = undefined;
var x88: u64 = undefined;
mulxU64(&x87, &x88, x2, 0xffffffff00000001);
var x89: u64 = undefined;
var x90: u1 = undefined;
addcarryxU64(&x89, &x90, 0x0, x88, x85);
var x91: u64 = undefined;
var x92: u1 = undefined;
addcarryxU64(&x91, &x92, x90, x86, x83);
var x93: u64 = undefined;
var x94: u1 = undefined;
addcarryxU64(&x93, &x94, x92, x84, x81);
var x95: u64 = undefined;
var x96: u1 = undefined;
addcarryxU64(&x95, &x96, 0x0, x75, x87);
var x97: u64 = undefined;
var x98: u1 = undefined;
addcarryxU64(&x97, &x98, x96, x77, x89);
var x99: u64 = undefined;
var x100: u1 = undefined;
addcarryxU64(&x99, &x100, x98, x79, x91);
var x101: u64 = undefined;
var x102: u1 = undefined;
addcarryxU64(&x101, &x102, x100, ((cast(u64, x80) + (cast(u64, x60) + (cast(u64, x52) + x40))) + (cast(u64, x72) + x64)), x93);
var x103: u64 = undefined;
var x104: u64 = undefined;
mulxU64(&x103, &x104, x95, 0xffffffffffffffff);
var x105: u64 = undefined;
var x106: u64 = undefined;
mulxU64(&x105, &x106, x103, 0xffffffff);
var x107: u64 = undefined;
var x108: u64 = undefined;
mulxU64(&x107, &x108, x103, 0xffffffffffffffff);
var x109: u64 = undefined;
var x110: u64 = undefined;
mulxU64(&x109, &x110, x103, 0xffffffff00000000);
var x111: u64 = undefined;
var x112: u1 = undefined;
addcarryxU64(&x111, &x112, 0x0, x110, x107);
var x113: u64 = undefined;
var x114: u1 = undefined;
addcarryxU64(&x113, &x114, x112, x108, x105);
var x115: u64 = undefined;
var x116: u1 = undefined;
addcarryxU64(&x115, &x116, 0x0, x95, x103);
var x117: u64 = undefined;
var x118: u1 = undefined;
addcarryxU64(&x117, &x118, x116, x97, x109);
var x119: u64 = undefined;
var x120: u1 = undefined;
addcarryxU64(&x119, &x120, x118, x99, x111);
var x121: u64 = undefined;
var x122: u1 = undefined;
addcarryxU64(&x121, &x122, x120, x101, x113);
var x123: u64 = undefined;
var x124: u64 = undefined;
mulxU64(&x123, &x124, x3, 0xffffffff);
var x125: u64 = undefined;
var x126: u64 = undefined;
mulxU64(&x125, &x126, x3, 0xfffffffe00000000);
var x127: u64 = undefined;
var x128: u64 = undefined;
mulxU64(&x127, &x128, x3, 0xffffffff00000000);
var x129: u64 = undefined;
var x130: u64 = undefined;
mulxU64(&x129, &x130, x3, 0xffffffff00000001);
var x131: u64 = undefined;
var x132: u1 = undefined;
addcarryxU64(&x131, &x132, 0x0, x130, x127);
var x133: u64 = undefined;
var x134: u1 = undefined;
addcarryxU64(&x133, &x134, x132, x128, x125);
var x135: u64 = undefined;
var x136: u1 = undefined;
addcarryxU64(&x135, &x136, x134, x126, x123);
var x137: u64 = undefined;
var x138: u1 = undefined;
addcarryxU64(&x137, &x138, 0x0, x117, x129);
var x139: u64 = undefined;
var x140: u1 = undefined;
addcarryxU64(&x139, &x140, x138, x119, x131);
var x141: u64 = undefined;
var x142: u1 = undefined;
addcarryxU64(&x141, &x142, x140, x121, x133);
var x143: u64 = undefined;
var x144: u1 = undefined;
addcarryxU64(&x143, &x144, x142, ((cast(u64, x122) + (cast(u64, x102) + (cast(u64, x94) + x82))) + (cast(u64, x114) + x106)), x135);
var x145: u64 = undefined;
var x146: u64 = undefined;
mulxU64(&x145, &x146, x137, 0xffffffffffffffff);
var x147: u64 = undefined;
var x148: u64 = undefined;
mulxU64(&x147, &x148, x145, 0xffffffff);
var x149: u64 = undefined;
var x150: u64 = undefined;
mulxU64(&x149, &x150, x145, 0xffffffffffffffff);
var x151: u64 = undefined;
var x152: u64 = undefined;
mulxU64(&x151, &x152, x145, 0xffffffff00000000);
var x153: u64 = undefined;
var x154: u1 = undefined;
addcarryxU64(&x153, &x154, 0x0, x152, x149);
var x155: u64 = undefined;
var x156: u1 = undefined;
addcarryxU64(&x155, &x156, x154, x150, x147);
var x157: u64 = undefined;
var x158: u1 = undefined;
addcarryxU64(&x157, &x158, 0x0, x137, x145);
var x159: u64 = undefined;
var x160: u1 = undefined;
addcarryxU64(&x159, &x160, x158, x139, x151);
var x161: u64 = undefined;
var x162: u1 = undefined;
addcarryxU64(&x161, &x162, x160, x141, x153);
var x163: u64 = undefined;
var x164: u1 = undefined;
addcarryxU64(&x163, &x164, x162, x143, x155);
const x165 = ((cast(u64, x164) + (cast(u64, x144) + (cast(u64, x136) + x124))) + (cast(u64, x156) + x148));
var x166: u64 = undefined;
var x167: u1 = undefined;
subborrowxU64(&x166, &x167, 0x0, x159, cast(u64, 0x1));
var x168: u64 = undefined;
var x169: u1 = undefined;
subborrowxU64(&x168, &x169, x167, x161, 0xffffffff00000000);
var x170: u64 = undefined;
var x171: u1 = undefined;
subborrowxU64(&x170, &x171, x169, x163, 0xffffffffffffffff);
var x172: u64 = undefined;
var x173: u1 = undefined;
subborrowxU64(&x172, &x173, x171, x165, 0xffffffff);
var x174: u64 = undefined;
var x175: u1 = undefined;
subborrowxU64(&x174, &x175, x173, cast(u64, 0x0), cast(u64, 0x0));
var x176: u64 = undefined;
cmovznzU64(&x176, x175, x166, x159);
var x177: u64 = undefined;
cmovznzU64(&x177, x175, x168, x161);
var x178: u64 = undefined;
cmovznzU64(&x178, x175, x170, x163);
var x179: u64 = undefined;
cmovznzU64(&x179, x175, x172, x165);
out1[0] = x176;
out1[1] = x177;
out1[2] = x178;
out1[3] = x179;
}
/// The function nonzero outputs a single non-zero word if the input is non-zero and zero otherwise.
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// Postconditions:
/// out1 = 0 ↔ eval (from_montgomery arg1) mod m = 0
///
/// Input Bounds:
/// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
/// Output Bounds:
/// out1: [0x0 ~> 0xffffffffffffffff]
pub fn nonzero(out1: *u64, arg1: [4]u64) void {
@setRuntimeSafety(mode == .Debug);
const x1 = ((arg1[0]) | ((arg1[1]) | ((arg1[2]) | (arg1[3]))));
out1.* = x1;
}
/// The function selectznz is a multi-limb conditional select.
/// Postconditions:
/// eval out1 = (if arg1 = 0 then eval arg2 else eval arg3)
///
/// Input Bounds:
/// arg1: [0x0 ~> 0x1]
/// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
/// arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
pub fn selectznz(out1: *[4]u64, arg1: u1, arg2: [4]u64, arg3: [4]u64) void {
@setRuntimeSafety(mode == .Debug);
var x1: u64 = undefined;
cmovznzU64(&x1, arg1, (arg2[0]), (arg3[0]));
var x2: u64 = undefined;
cmovznzU64(&x2, arg1, (arg2[1]), (arg3[1]));
var x3: u64 = undefined;
cmovznzU64(&x3, arg1, (arg2[2]), (arg3[2]));
var x4: u64 = undefined;
cmovznzU64(&x4, arg1, (arg2[3]), (arg3[3]));
out1[0] = x1;
out1[1] = x2;
out1[2] = x3;
out1[3] = x4;
}
/// The function toBytes serializes a field element NOT in the Montgomery domain to bytes in little-endian order.
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// Postconditions:
/// out1 = map (λ x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)⌋) [0..27]
///
/// Input Bounds:
/// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffff]]
/// Output Bounds:
/// out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]]
pub fn toBytes(out1: *[28]u8, arg1: [4]u64) void {
@setRuntimeSafety(mode == .Debug);
const x1 = (arg1[3]);
const x2 = (arg1[2]);
const x3 = (arg1[1]);
const x4 = (arg1[0]);
const x5 = cast(u8, (x4 & cast(u64, 0xff)));
const x6 = (x4 >> 8);
const x7 = cast(u8, (x6 & cast(u64, 0xff)));
const x8 = (x6 >> 8);
const x9 = cast(u8, (x8 & cast(u64, 0xff)));
const x10 = (x8 >> 8);
const x11 = cast(u8, (x10 & cast(u64, 0xff)));
const x12 = (x10 >> 8);
const x13 = cast(u8, (x12 & cast(u64, 0xff)));
const x14 = (x12 >> 8);
const x15 = cast(u8, (x14 & cast(u64, 0xff)));
const x16 = (x14 >> 8);
const x17 = cast(u8, (x16 & cast(u64, 0xff)));
const x18 = cast(u8, (x16 >> 8));
const x19 = cast(u8, (x3 & cast(u64, 0xff)));
const x20 = (x3 >> 8);
const x21 = cast(u8, (x20 & cast(u64, 0xff)));
const x22 = (x20 >> 8);
const x23 = cast(u8, (x22 & cast(u64, 0xff)));
const x24 = (x22 >> 8);
const x25 = cast(u8, (x24 & cast(u64, 0xff)));
const x26 = (x24 >> 8);
const x27 = cast(u8, (x26 & cast(u64, 0xff)));
const x28 = (x26 >> 8);
const x29 = cast(u8, (x28 & cast(u64, 0xff)));
const x30 = (x28 >> 8);
const x31 = cast(u8, (x30 & cast(u64, 0xff)));
const x32 = cast(u8, (x30 >> 8));
const x33 = cast(u8, (x2 & cast(u64, 0xff)));
const x34 = (x2 >> 8);
const x35 = cast(u8, (x34 & cast(u64, 0xff)));
const x36 = (x34 >> 8);
const x37 = cast(u8, (x36 & cast(u64, 0xff)));
const x38 = (x36 >> 8);
const x39 = cast(u8, (x38 & cast(u64, 0xff)));
const x40 = (x38 >> 8);
const x41 = cast(u8, (x40 & cast(u64, 0xff)));
const x42 = (x40 >> 8);
const x43 = cast(u8, (x42 & cast(u64, 0xff)));
const x44 = (x42 >> 8);
const x45 = cast(u8, (x44 & cast(u64, 0xff)));
const x46 = cast(u8, (x44 >> 8));
const x47 = cast(u8, (x1 & cast(u64, 0xff)));
const x48 = (x1 >> 8);
const x49 = cast(u8, (x48 & cast(u64, 0xff)));
const x50 = (x48 >> 8);
const x51 = cast(u8, (x50 & cast(u64, 0xff)));
const x52 = cast(u8, (x50 >> 8));
out1[0] = x5;
out1[1] = x7;
out1[2] = x9;
out1[3] = x11;
out1[4] = x13;
out1[5] = x15;
out1[6] = x17;
out1[7] = x18;
out1[8] = x19;
out1[9] = x21;
out1[10] = x23;
out1[11] = x25;
out1[12] = x27;
out1[13] = x29;
out1[14] = x31;
out1[15] = x32;
out1[16] = x33;
out1[17] = x35;
out1[18] = x37;
out1[19] = x39;
out1[20] = x41;
out1[21] = x43;
out1[22] = x45;
out1[23] = x46;
out1[24] = x47;
out1[25] = x49;
out1[26] = x51;
out1[27] = x52;
}
/// The function fromBytes deserializes a field element NOT in the Montgomery domain from bytes in little-endian order.
/// Preconditions:
/// 0 ≤ bytes_eval arg1 < m
/// Postconditions:
/// eval out1 mod m = bytes_eval arg1 mod m
/// 0 ≤ eval out1 < m
///
/// Input Bounds:
/// arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]]
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffff]]
pub fn fromBytes(out1: *[4]u64, arg1: [28]u8) void {
@setRuntimeSafety(mode == .Debug);
const x1 = (cast(u64, (arg1[27])) << 24);
const x2 = (cast(u64, (arg1[26])) << 16);
const x3 = (cast(u64, (arg1[25])) << 8);
const x4 = (arg1[24]);
const x5 = (cast(u64, (arg1[23])) << 56);
const x6 = (cast(u64, (arg1[22])) << 48);
const x7 = (cast(u64, (arg1[21])) << 40);
const x8 = (cast(u64, (arg1[20])) << 32);
const x9 = (cast(u64, (arg1[19])) << 24);
const x10 = (cast(u64, (arg1[18])) << 16);
const x11 = (cast(u64, (arg1[17])) << 8);
const x12 = (arg1[16]);
const x13 = (cast(u64, (arg1[15])) << 56);
const x14 = (cast(u64, (arg1[14])) << 48);
const x15 = (cast(u64, (arg1[13])) << 40);
const x16 = (cast(u64, (arg1[12])) << 32);
const x17 = (cast(u64, (arg1[11])) << 24);
const x18 = (cast(u64, (arg1[10])) << 16);
const x19 = (cast(u64, (arg1[9])) << 8);
const x20 = (arg1[8]);
const x21 = (cast(u64, (arg1[7])) << 56);
const x22 = (cast(u64, (arg1[6])) << 48);
const x23 = (cast(u64, (arg1[5])) << 40);
const x24 = (cast(u64, (arg1[4])) << 32);
const x25 = (cast(u64, (arg1[3])) << 24);
const x26 = (cast(u64, (arg1[2])) << 16);
const x27 = (cast(u64, (arg1[1])) << 8);
const x28 = (arg1[0]);
const x29 = (x27 + cast(u64, x28));
const x30 = (x26 + x29);
const x31 = (x25 + x30);
const x32 = (x24 + x31);
const x33 = (x23 + x32);
const x34 = (x22 + x33);
const x35 = (x21 + x34);
const x36 = (x19 + cast(u64, x20));
const x37 = (x18 + x36);
const x38 = (x17 + x37);
const x39 = (x16 + x38);
const x40 = (x15 + x39);
const x41 = (x14 + x40);
const x42 = (x13 + x41);
const x43 = (x11 + cast(u64, x12));
const x44 = (x10 + x43);
const x45 = (x9 + x44);
const x46 = (x8 + x45);
const x47 = (x7 + x46);
const x48 = (x6 + x47);
const x49 = (x5 + x48);
const x50 = (x3 + cast(u64, x4));
const x51 = (x2 + x50);
const x52 = (x1 + x51);
out1[0] = x35;
out1[1] = x42;
out1[2] = x49;
out1[3] = x52;
}
/// The function setOne returns the field element one in the Montgomery domain.
/// Postconditions:
/// eval (from_montgomery out1) mod m = 1 mod m
/// 0 ≤ eval out1 < m
///
/// Input Bounds:
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
pub fn setOne(out1: *[4]u64) void {
@setRuntimeSafety(mode == .Debug);
out1[0] = 0xffffffff00000000;
out1[1] = 0xffffffffffffffff;
out1[2] = cast(u64, 0x0);
out1[3] = cast(u64, 0x0);
}
/// The function msat returns the saturated representation of the prime modulus.
/// Postconditions:
/// twos_complement_eval out1 = m
/// 0 ≤ eval out1 < m
///
/// Input Bounds:
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
pub fn msat(out1: *[5]u64) void {
@setRuntimeSafety(mode == .Debug);
out1[0] = cast(u64, 0x1);
out1[1] = 0xffffffff00000000;
out1[2] = 0xffffffffffffffff;
out1[3] = 0xffffffff;
out1[4] = cast(u64, 0x0);
}
/// The function divstep computes a divstep.
/// Preconditions:
/// 0 ≤ eval arg4 < m
/// 0 ≤ eval arg5 < m
/// Postconditions:
/// out1 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then 1 - arg1 else 1 + arg1)
/// twos_complement_eval out2 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then twos_complement_eval arg3 else twos_complement_eval arg2)
/// twos_complement_eval out3 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then ⌊(twos_complement_eval arg3 - twos_complement_eval arg2) / 2⌋ else ⌊(twos_complement_eval arg3 + (twos_complement_eval arg3 mod 2) * twos_complement_eval arg2) / 2⌋)
/// eval (from_montgomery out4) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (2 * eval (from_montgomery arg5)) mod m else (2 * eval (from_montgomery arg4)) mod m)
/// eval (from_montgomery out5) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (eval (from_montgomery arg4) - eval (from_montgomery arg4)) mod m else (eval (from_montgomery arg5) + (twos_complement_eval arg3 mod 2) * eval (from_montgomery arg4)) mod m)
/// 0 ≤ eval out5 < m
/// 0 ≤ eval out5 < m
/// 0 ≤ eval out2 < m
/// 0 ≤ eval out3 < m
///
/// Input Bounds:
/// arg1: [0x0 ~> 0xffffffffffffffff]
/// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
/// arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
/// arg4: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
/// arg5: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
/// Output Bounds:
/// out1: [0x0 ~> 0xffffffffffffffff]
/// out2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
/// out3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
/// out4: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
/// out5: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
pub fn divstep(out1: *u64, out2: *[5]u64, out3: *[5]u64, out4: *[4]u64, out5: *[4]u64, arg1: u64, arg2: [5]u64, arg3: [5]u64, arg4: [4]u64, arg5: [4]u64) void {
@setRuntimeSafety(mode == .Debug);
var x1: u64 = undefined;
var x2: u1 = undefined;
addcarryxU64(&x1, &x2, 0x0, (~arg1), cast(u64, 0x1));
const x3 = (cast(u1, (x1 >> 63)) & cast(u1, ((arg3[0]) & cast(u64, 0x1))));
var x4: u64 = undefined;
var x5: u1 = undefined;
addcarryxU64(&x4, &x5, 0x0, (~arg1), cast(u64, 0x1));
var x6: u64 = undefined;
cmovznzU64(&x6, x3, arg1, x4);
var x7: u64 = undefined;
cmovznzU64(&x7, x3, (arg2[0]), (arg3[0]));
var x8: u64 = undefined;
cmovznzU64(&x8, x3, (arg2[1]), (arg3[1]));
var x9: u64 = undefined;
cmovznzU64(&x9, x3, (arg2[2]), (arg3[2]));
var x10: u64 = undefined;
cmovznzU64(&x10, x3, (arg2[3]), (arg3[3]));
var x11: u64 = undefined;
cmovznzU64(&x11, x3, (arg2[4]), (arg3[4]));
var x12: u64 = undefined;
var x13: u1 = undefined;
addcarryxU64(&x12, &x13, 0x0, cast(u64, 0x1), (~(arg2[0])));
var x14: u64 = undefined;
var x15: u1 = undefined;
addcarryxU64(&x14, &x15, x13, cast(u64, 0x0), (~(arg2[1])));
var x16: u64 = undefined;
var x17: u1 = undefined;
addcarryxU64(&x16, &x17, x15, cast(u64, 0x0), (~(arg2[2])));
var x18: u64 = undefined;
var x19: u1 = undefined;
addcarryxU64(&x18, &x19, x17, cast(u64, 0x0), (~(arg2[3])));
var x20: u64 = undefined;
var x21: u1 = undefined;
addcarryxU64(&x20, &x21, x19, cast(u64, 0x0), (~(arg2[4])));
var x22: u64 = undefined;
cmovznzU64(&x22, x3, (arg3[0]), x12);
var x23: u64 = undefined;
cmovznzU64(&x23, x3, (arg3[1]), x14);
var x24: u64 = undefined;
cmovznzU64(&x24, x3, (arg3[2]), x16);
var x25: u64 = undefined;
cmovznzU64(&x25, x3, (arg3[3]), x18);
var x26: u64 = undefined;
cmovznzU64(&x26, x3, (arg3[4]), x20);
var x27: u64 = undefined;
cmovznzU64(&x27, x3, (arg4[0]), (arg5[0]));
var x28: u64 = undefined;
cmovznzU64(&x28, x3, (arg4[1]), (arg5[1]));
var x29: u64 = undefined;
cmovznzU64(&x29, x3, (arg4[2]), (arg5[2]));
var x30: u64 = undefined;
cmovznzU64(&x30, x3, (arg4[3]), (arg5[3]));
var x31: u64 = undefined;
var x32: u1 = undefined;
addcarryxU64(&x31, &x32, 0x0, x27, x27);
var x33: u64 = undefined;
var x34: u1 = undefined;
addcarryxU64(&x33, &x34, x32, x28, x28);
var x35: u64 = undefined;
var x36: u1 = undefined;
addcarryxU64(&x35, &x36, x34, x29, x29);
var x37: u64 = undefined;
var x38: u1 = undefined;
addcarryxU64(&x37, &x38, x36, x30, x30);
var x39: u64 = undefined;
var x40: u1 = undefined;
subborrowxU64(&x39, &x40, 0x0, x31, cast(u64, 0x1));
var x41: u64 = undefined;
var x42: u1 = undefined;
subborrowxU64(&x41, &x42, x40, x33, 0xffffffff00000000);
var x43: u64 = undefined;
var x44: u1 = undefined;
subborrowxU64(&x43, &x44, x42, x35, 0xffffffffffffffff);
var x45: u64 = undefined;
var x46: u1 = undefined;
subborrowxU64(&x45, &x46, x44, x37, 0xffffffff);
var x47: u64 = undefined;
var x48: u1 = undefined;
subborrowxU64(&x47, &x48, x46, cast(u64, x38), cast(u64, 0x0));
const x49 = (arg4[3]);
const x50 = (arg4[2]);
const x51 = (arg4[1]);
const x52 = (arg4[0]);
var x53: u64 = undefined;
var x54: u1 = undefined;
subborrowxU64(&x53, &x54, 0x0, cast(u64, 0x0), x52);
var x55: u64 = undefined;
var x56: u1 = undefined;
subborrowxU64(&x55, &x56, x54, cast(u64, 0x0), x51);
var x57: u64 = undefined;
var x58: u1 = undefined;
subborrowxU64(&x57, &x58, x56, cast(u64, 0x0), x50);
var x59: u64 = undefined;
var x60: u1 = undefined;
subborrowxU64(&x59, &x60, x58, cast(u64, 0x0), x49);
var x61: u64 = undefined;
cmovznzU64(&x61, x60, cast(u64, 0x0), 0xffffffffffffffff);
var x62: u64 = undefined;
var x63: u1 = undefined;
addcarryxU64(&x62, &x63, 0x0, x53, cast(u64, cast(u1, (x61 & cast(u64, 0x1)))));
var x64: u64 = undefined;
var x65: u1 = undefined;
addcarryxU64(&x64, &x65, x63, x55, (x61 & 0xffffffff00000000));
var x66: u64 = undefined;
var x67: u1 = undefined;
addcarryxU64(&x66, &x67, x65, x57, x61);
var x68: u64 = undefined;
var x69: u1 = undefined;
addcarryxU64(&x68, &x69, x67, x59, (x61 & 0xffffffff));
var x70: u64 = undefined;
cmovznzU64(&x70, x3, (arg5[0]), x62);
var x71: u64 = undefined;
cmovznzU64(&x71, x3, (arg5[1]), x64);
var x72: u64 = undefined;
cmovznzU64(&x72, x3, (arg5[2]), x66);
var x73: u64 = undefined;
cmovznzU64(&x73, x3, (arg5[3]), x68);
const x74 = cast(u1, (x22 & cast(u64, 0x1)));
var x75: u64 = undefined;
cmovznzU64(&x75, x74, cast(u64, 0x0), x7);
var x76: u64 = undefined;
cmovznzU64(&x76, x74, cast(u64, 0x0), x8);
var x77: u64 = undefined;
cmovznzU64(&x77, x74, cast(u64, 0x0), x9);
var x78: u64 = undefined;
cmovznzU64(&x78, x74, cast(u64, 0x0), x10);
var x79: u64 = undefined;
cmovznzU64(&x79, x74, cast(u64, 0x0), x11);
var x80: u64 = undefined;
var x81: u1 = undefined;
addcarryxU64(&x80, &x81, 0x0, x22, x75);
var x82: u64 = undefined;
var x83: u1 = undefined;
addcarryxU64(&x82, &x83, x81, x23, x76);
var x84: u64 = undefined;
var x85: u1 = undefined;
addcarryxU64(&x84, &x85, x83, x24, x77);
var x86: u64 = undefined;
var x87: u1 = undefined;
addcarryxU64(&x86, &x87, x85, x25, x78);
var x88: u64 = undefined;
var x89: u1 = undefined;
addcarryxU64(&x88, &x89, x87, x26, x79);
var x90: u64 = undefined;
cmovznzU64(&x90, x74, cast(u64, 0x0), x27);
var x91: u64 = undefined;
cmovznzU64(&x91, x74, cast(u64, 0x0), x28);
var x92: u64 = undefined;
cmovznzU64(&x92, x74, cast(u64, 0x0), x29);
var x93: u64 = undefined;
cmovznzU64(&x93, x74, cast(u64, 0x0), x30);
var x94: u64 = undefined;
var x95: u1 = undefined;
addcarryxU64(&x94, &x95, 0x0, x70, x90);
var x96: u64 = undefined;
var x97: u1 = undefined;
addcarryxU64(&x96, &x97, x95, x71, x91);
var x98: u64 = undefined;
var x99: u1 = undefined;
addcarryxU64(&x98, &x99, x97, x72, x92);
var x100: u64 = undefined;
var x101: u1 = undefined;
addcarryxU64(&x100, &x101, x99, x73, x93);
var x102: u64 = undefined;
var x103: u1 = undefined;
subborrowxU64(&x102, &x103, 0x0, x94, cast(u64, 0x1));
var x104: u64 = undefined;
var x105: u1 = undefined;
subborrowxU64(&x104, &x105, x103, x96, 0xffffffff00000000);
var x106: u64 = undefined;
var x107: u1 = undefined;
subborrowxU64(&x106, &x107, x105, x98, 0xffffffffffffffff);
var x108: u64 = undefined;
var x109: u1 = undefined;
subborrowxU64(&x108, &x109, x107, x100, 0xffffffff);
var x110: u64 = undefined;
var x111: u1 = undefined;
subborrowxU64(&x110, &x111, x109, cast(u64, x101), cast(u64, 0x0));
var x112: u64 = undefined;
var x113: u1 = undefined;
addcarryxU64(&x112, &x113, 0x0, x6, cast(u64, 0x1));
const x114 = ((x80 >> 1) | ((x82 << 63) & 0xffffffffffffffff));
const x115 = ((x82 >> 1) | ((x84 << 63) & 0xffffffffffffffff));
const x116 = ((x84 >> 1) | ((x86 << 63) & 0xffffffffffffffff));
const x117 = ((x86 >> 1) | ((x88 << 63) & 0xffffffffffffffff));
const x118 = ((x88 & 0x8000000000000000) | (x88 >> 1));
var x119: u64 = undefined;
cmovznzU64(&x119, x48, x39, x31);
var x120: u64 = undefined;
cmovznzU64(&x120, x48, x41, x33);
var x121: u64 = undefined;
cmovznzU64(&x121, x48, x43, x35);
var x122: u64 = undefined;
cmovznzU64(&x122, x48, x45, x37);
var x123: u64 = undefined;
cmovznzU64(&x123, x111, x102, x94);
var x124: u64 = undefined;
cmovznzU64(&x124, x111, x104, x96);
var x125: u64 = undefined;
cmovznzU64(&x125, x111, x106, x98);
var x126: u64 = undefined;
cmovznzU64(&x126, x111, x108, x100);
out1.* = x112;
out2[0] = x7;
out2[1] = x8;
out2[2] = x9;
out2[3] = x10;
out2[4] = x11;
out3[0] = x114;
out3[1] = x115;
out3[2] = x116;
out3[3] = x117;
out3[4] = x118;
out4[0] = x119;
out4[1] = x120;
out4[2] = x121;
out4[3] = x122;
out5[0] = x123;
out5[1] = x124;
out5[2] = x125;
out5[3] = x126;
}
/// The function divstepPrecomp returns the precomputed value for Bernstein-Yang-inversion (in montgomery form).
/// Postconditions:
/// eval (from_montgomery out1) = ⌊(m - 1) / 2⌋^(if (log2 m) + 1 < 46 then ⌊(49 * ((log2 m) + 1) + 80) / 17⌋ else ⌊(49 * ((log2 m) + 1) + 57) / 17⌋)
/// 0 ≤ eval out1 < m
///
/// Input Bounds:
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
pub fn divstepPrecomp(out1: *[4]u64) void {
@setRuntimeSafety(mode == .Debug);
out1[0] = 0x7ffffffe800001;
out1[1] = 0xff7fffff00800000;
out1[2] = 0xffffff;
out1[3] = 0xff800000;
} | fiat-zig/src/p224_64.zig |
const sf = @import("../sfml.zig");
pub const RectangleShape = struct {
const Self = @This();
// Constructor/destructor
/// Creates a rectangle shape with a size. The rectangle will be white
pub fn init(size: sf.Vector2f) !Self {
var rect = sf.c.sfRectangleShape_create();
if (rect == null)
return sf.Error.nullptrUnknownReason;
sf.c.sfRectangleShape_setFillColor(rect, sf.c.sfWhite);
sf.c.sfRectangleShape_setSize(rect, size.toCSFML());
return Self{ .ptr = rect.? };
}
/// Destroys a rectangle shape
pub fn deinit(self: Self) void {
sf.c.sfRectangleShape_destroy(self.ptr);
}
// Getters/setters
/// Gets the fill color of this rectangle shape
pub fn getFillColor(self: Self) sf.Color {
return sf.Color.fromCSFML(sf.c.sfRectangleShape_getFillColor(self.ptr));
}
/// Sets the fill color of this rectangle shape
pub fn setFillColor(self: Self, color: sf.Color) void {
sf.c.sfRectangleShape_setFillColor(self.ptr, color.toCSFML());
}
/// Gets the size of this rectangle shape
pub fn getSize(self: Self) sf.Vector2f {
return sf.Vector2f.fromCSFML(sf.c.sfRectangleShape_getSize(self.ptr));
}
/// Sets the size of this rectangle shape
pub fn setSize(self: Self, size: sf.Vector2f) void {
sf.c.sfRectangleShape_setSize(self.ptr, size.toCSFML());
}
/// Gets the position of this rectangle shape
pub fn getPosition(self: Self) sf.Vector2f {
return sf.Vector2f.fromCSFML(sf.c.sfRectangleShape_getPosition(self.ptr));
}
/// Sets the position of this rectangle shape
pub fn setPosition(self: Self, pos: sf.Vector2f) void {
sf.c.sfRectangleShape_setPosition(self.ptr, pos.toCSFML());
}
/// Adds the offset to this shape's position
pub fn move(self: Self, offset: sf.Vector2f) void {
sf.c.sfRectangleShape_move(self.ptr, offset.toCSFML());
}
/// Gets the origin of this rectangle shape
pub fn getOrigin(self: Self) sf.Vector2f {
return sf.Vector2f.fromCSFML(sf.c.sfRectangleShape_getOrigin(self.ptr));
}
/// Sets the origin of this rectangle shape
pub fn setOrigin(self: Self, origin: sf.Vector2f) void {
sf.c.sfRectangleShape_setOrigin(self.ptr, origin.toCSFML());
}
/// Gets the rotation of this rectangle shape
pub fn getRotation(self: Self) f32 {
return sf.c.sfRectangleShape_getRotation(self.ptr);
}
/// Sets the rotation of this rectangle shape
pub fn setRotation(self: Self, angle: f32) void {
sf.c.sfRectangleShape_setRotation(self.ptr, angle);
}
/// Rotates this shape by a given amount
pub fn rotate(self: Self, angle: f32) void {
sf.c.sfRectangleShape_rotate(self.ptr, angle);
}
/// Gets the texture of this shape
pub fn getTexture(self: Self) ?sf.Texture {
var t = sf.c.sfRectangleShape_getTexture(self.ptr);
if (t != null) {
return sf.Texture{ .const_ptr = t.? };
} else
return null;
}
/// Sets the texture of this shape
pub fn setTexture(self: Self, texture: ?sf.Texture) void {
var tex = if (texture) |t| t.get() else null;
sf.c.sfRectangleShape_setTexture(self.ptr, tex, 0);
}
/// Gets the sub-rectangle of the texture that the shape will display
pub fn getTextureRect(self: Self) sf.FloatRect {
return sf.FloatRect.fromCSFML(sf.c.sfRectangleShape_getTextureRect(self.ptr));
}
/// Sets the sub-rectangle of the texture that the shape will display
pub fn setTextureRect(self: Self, rect: sf.FloatRect) void {
sf.c.sfRectangleShape_getTextureRect(self.ptr, rect.toCSFML());
}
/// Gets the bounds in the local coordinates system
pub fn getLocalBounds(self: Self) sf.FloatRect {
return sf.FloatRect.fromCSFML(sf.c.sfRectangleShape_getLocalBounds(self.ptr));
}
/// Gets the bounds in the global coordinates
pub fn getGlobalBounds(self: Self) sf.FloatRect {
return sf.FloatRect.fromCSFML(sf.c.sfRectangleShape_getGlobalBounds(self.ptr));
}
/// Pointer to the csfml structure
ptr: *sf.c.sfRectangleShape
};
test "rectangle shape: sane getters and setters" {
const tst = @import("std").testing;
var rect = try RectangleShape.init(sf.Vector2f{ .x = 30, .y = 50 });
defer rect.deinit();
tst.expectEqual(sf.Vector2f{ .x = 30, .y = 50 }, rect.getSize());
rect.setFillColor(sf.Color.Yellow);
rect.setSize(.{ .x = 15, .y = 510 });
rect.setRotation(15);
rect.setPosition(.{ .x = 1, .y = 2 });
rect.setOrigin(.{ .x = 20, .y = 25 });
// TODO : issue #2
//tst.expectEqual(sf.c.sfYellow, rect.getFillColor());
tst.expectEqual(sf.Vector2f{ .x = 15, .y = 510 }, rect.getSize());
tst.expectEqual(@as(f32, 15), rect.getRotation());
tst.expectEqual(sf.Vector2f{ .x = 1, .y = 2 }, rect.getPosition());
tst.expectEqual(sf.Vector2f{ .x = 20, .y = 25 }, rect.getOrigin());
// TODO : find why that doesn't work
//tst.expectEqual(@as(?sf.Texture, null), rect.getTexture());
rect.rotate(5);
rect.move(.{ .x = -5, .y = 5 });
tst.expectEqual(@as(f32, 20), rect.getRotation());
tst.expectEqual(sf.Vector2f{ .x = -4, .y = 7 }, rect.getPosition());
} | src/sfml/graphics/rectangle_shape.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const game = @import("game.zig");
const bot_trivial = @import("bot_trivial.zig");
const bot_rand = @import("bot_random.zig");
fn playASingleGame(turnLimit: u32, alloc: *Allocator, rng: *std.rand.Xoroshiro128) !game.GameState {
const bot = game.BotCode{
.shouldRollTwoDiceFunc = bot_rand.shouldRollTwoDice,
.getCardToPurchaseFunc = bot_rand.getCardToPurchase,
.shouldActivateHarborFunc = bot_rand.shouldActivateHarbor,
.shouldReroll = bot_rand.shouldReroll,
.getPlayerToStealCoinsFrom = bot_rand.getPlayerToStealCoinsFrom,
};
var state = try game.GameState.init(alloc, rng, bot);
//state.print();
//std.debug.warn("\n");
while (state.currentTurn < turnLimit) {
const gameover = try state.playTurn();
if (gameover) break;
}
if (state.currentTurn >= turnLimit) {
std.debug.warn("A game ran over the turn limit of {} turns!\n", turnLimit);
}
//state.print();
return state;
}
pub fn main() !void {
//const gamesToPlay = 10000000;
const gamesToPlay = 1000000;
//const gamesToPlay = 1000;
const turnLimit = 300; // TODO: We don't really expect to hit this? I suppose there isn't a reason why we can't
var totalOwnedByWinners = [_]u64{0} ** @memberCount(game.EstablishmentType);
var totalCoinsEarnedByEstablishment = [_]i64{0} ** @memberCount(game.EstablishmentType);
var winnerCoinsEarnedByEstablishment = [_]i64{0} ** @memberCount(game.EstablishmentType);
std.debug.warn("Playing {} games...\n", @intCast(u32, gamesToPlay));
var heapAlloc = std.heap.HeapAllocator.init();
var rng = std.rand.Xoroshiro128.init(std.time.milliTimestamp());
var t = try std.time.Timer.start();
var currentGame: u32 = 0;
while (currentGame < gamesToPlay) {
var alloc = std.heap.ArenaAllocator.init(&heapAlloc.allocator);
const endState = try playASingleGame(turnLimit, &alloc.allocator, &rng);
var ownedByWinner = [_]u64{0} ** @memberCount(game.EstablishmentType);
const winner = &endState.players[endState.currentPlayerIndex];
for (winner.establishmentsAnyTurn.toSliceConst()) |est| {
ownedByWinner[@enumToInt(est.type)] += 1;
}
for (winner.establishmentsYourTurn.toSliceConst()) |est| {
ownedByWinner[@enumToInt(est.type)] += 1;
}
for (winner.establishmentsOtherTurns.toSliceConst()) |est| {
ownedByWinner[@enumToInt(est.type)] += 1;
}
for (winner.totalCoinsEarned) |earned, estIndex| {
winnerCoinsEarnedByEstablishment[estIndex] += earned;
}
for (endState.players) |*player| {
for (player.totalCoinsEarned) |earned, estIndex| {
totalCoinsEarnedByEstablishment[estIndex] += earned;
}
}
alloc.deinit();
for (ownedByWinner) |owned, index| {
totalOwnedByWinners[index] += ownedByWinner[index];
}
currentGame += 1;
}
heapAlloc.deinit();
std.debug.warn("Winner owns establishment:\n");
for (totalOwnedByWinners) |totalOwned, estTypeIndex| {
var est = &game.allEstablishments[estTypeIndex];
var avgOwnedByWinners = @intToFloat(f64, totalOwned) / gamesToPlay;
var avgEarnedByWinners = @intToFloat(f64, winnerCoinsEarnedByEstablishment[estTypeIndex]) / gamesToPlay;
var avgEarnedByAllPlayers = @intToFloat(f64, totalCoinsEarnedByEstablishment[estTypeIndex]) / (game.PlayerCount * gamesToPlay);
std.debug.warn("{},{d:.3},{d:.3},{d:.3}\n", @tagName(est.type), avgOwnedByWinners, avgEarnedByWinners, avgEarnedByAllPlayers);
}
const elapsedNs = t.read();
const msPerNs = 1.0 / @intToFloat(f64, std.time.millisecond);
std.debug.warn("\n\nCompleted in {}ms\n\n", @intToFloat(f64, elapsedNs) * msPerNs);
} | src/main.zig |
const std = @import("std");
const Target = std.Target;
const llvm = @import("llvm.zig");
pub const FloatAbi = enum {
Hard,
Soft,
SoftFp,
};
/// TODO expose the arch and subarch separately
pub fn isArmOrThumb(self: Target) bool {
return switch (self.getArch()) {
.arm,
.armeb,
.aarch64,
.aarch64_be,
.thumb,
.thumbeb,
=> true,
else => false,
};
}
pub fn getFloatAbi(self: Target) FloatAbi {
return switch (self.getAbi()) {
.gnueabihf,
.eabihf,
.musleabihf,
=> .Hard,
else => .Soft,
};
}
pub fn getDynamicLinkerPath(self: Target) ?[]const u8 {
const env = self.getAbi();
const arch = self.getArch();
const os = self.getOs();
switch (os) {
.freebsd => {
return "/libexec/ld-elf.so.1";
},
.linux => {
switch (env) {
.android => {
if (self.getArchPtrBitWidth() == 64) {
return "/system/bin/linker64";
} else {
return "/system/bin/linker";
}
},
.gnux32 => {
if (arch == .x86_64) {
return "/libx32/ld-linux-x32.so.2";
}
},
.musl,
.musleabi,
.musleabihf,
=> {
if (arch == .x86_64) {
return "/lib/ld-musl-x86_64.so.1";
}
},
else => {},
}
switch (arch) {
.i386,
.sparc,
.sparcel,
=> return "/lib/ld-linux.so.2",
.aarch64 => return "/lib/ld-linux-aarch64.so.1",
.aarch64_be => return "/lib/ld-linux-aarch64_be.so.1",
.arm,
.thumb,
=> return switch (getFloatAbi(self)) {
.Hard => return "/lib/ld-linux-armhf.so.3",
else => return "/lib/ld-linux.so.3",
},
.armeb,
.thumbeb,
=> return switch (getFloatAbi(self)) {
.Hard => return "/lib/ld-linux-armhf.so.3",
else => return "/lib/ld-linux.so.3",
},
.mips,
.mipsel,
.mips64,
.mips64el,
=> return null,
.powerpc => return "/lib/ld.so.1",
.powerpc64 => return "/lib64/ld64.so.2",
.powerpc64le => return "/lib64/ld64.so.2",
.s390x => return "/lib64/ld64.so.1",
.sparcv9 => return "/lib64/ld-linux.so.2",
.x86_64 => return "/lib64/ld-linux-x86-64.so.2",
.arc,
.avr,
.bpfel,
.bpfeb,
.hexagon,
.msp430,
.r600,
.amdgcn,
.riscv32,
.riscv64,
.tce,
.tcele,
.xcore,
.nvptx,
.nvptx64,
.le32,
.le64,
.amdil,
.amdil64,
.hsail,
.hsail64,
.spir,
.spir64,
.kalimba,
.shave,
.lanai,
.wasm32,
.wasm64,
.renderscript32,
.renderscript64,
.aarch64_32,
=> return null,
}
},
else => return null,
}
}
pub fn getDarwinArchString(self: Target) [:0]const u8 {
const arch = self.getArch();
switch (arch) {
.aarch64 => return "arm64",
.thumb,
.arm,
=> return "arm",
.powerpc => return "ppc",
.powerpc64 => return "ppc64",
.powerpc64le => return "ppc64le",
// @tagName should be able to return sentinel terminated slice
else => @panic("TODO https://github.com/ziglang/zig/issues/3779"), //return @tagName(arch),
}
}
pub fn llvmTargetFromTriple(triple: std.Buffer) !*llvm.Target {
var result: *llvm.Target = undefined;
var err_msg: [*:0]u8 = undefined;
if (llvm.GetTargetFromTriple(triple.toSlice(), &result, &err_msg) != 0) {
std.debug.warn("triple: {s} error: {s}\n", .{ triple.toSlice(), err_msg });
return error.UnsupportedTarget;
}
return result;
}
pub fn initializeAllTargets() void {
llvm.InitializeAllTargets();
llvm.InitializeAllTargetInfos();
llvm.InitializeAllTargetMCs();
llvm.InitializeAllAsmPrinters();
llvm.InitializeAllAsmParsers();
}
pub fn getTriple(allocator: *std.mem.Allocator, self: std.Target) !std.Buffer {
var result = try std.Buffer.initSize(allocator, 0);
errdefer result.deinit();
// LLVM WebAssembly output support requires the target to be activated at
// build type with -DCMAKE_LLVM_EXPIERMENTAL_TARGETS_TO_BUILD=WebAssembly.
//
// LLVM determines the output format based on the abi suffix,
// defaulting to an object based on the architecture. The default format in
// LLVM 6 sets the wasm arch output incorrectly to ELF. We need to
// explicitly set this ourself in order for it to work.
//
// This is fixed in LLVM 7 and you will be able to get wasm output by
// using the target triple `wasm32-unknown-unknown-unknown`.
const env_name = if (self.isWasm()) "wasm" else @tagName(self.getAbi());
var out = &std.io.BufferOutStream.init(&result).stream;
try out.print("{}-unknown-{}-{}", .{ @tagName(self.getArch()), @tagName(self.getOs()), env_name });
return result;
} | src-self-hosted/util.zig |
const std = @import("std");
const TestContext = @import("../../src/test.zig").TestContext;
const linux_arm = std.zig.CrossTarget{
.cpu_arch = .arm,
.os_tag = .linux,
};
pub fn addCases(ctx: *TestContext) !void {
{
var case = ctx.exe("linux_arm hello world", linux_arm);
// Regular old hello world
case.addCompareOutput(
\\export fn _start() noreturn {
\\ print();
\\ exit();
\\}
\\
\\fn print() void {
\\ asm volatile ("svc #0"
\\ :
\\ : [number] "{r7}" (4),
\\ [arg1] "{r0}" (1),
\\ [arg2] "{r1}" (@ptrToInt("Hello, World!\n")),
\\ [arg3] "{r2}" (14)
\\ : "memory"
\\ );
\\ return;
\\}
\\
\\fn exit() noreturn {
\\ asm volatile ("svc #0"
\\ :
\\ : [number] "{r7}" (1),
\\ [arg1] "{r0}" (0)
\\ : "memory"
\\ );
\\ unreachable;
\\}
,
"Hello, World!\n",
);
}
{
var case = ctx.exe("parameters and return values", linux_arm);
// Testing simple parameters and return values
//
// TODO: The parameters to the asm statement in print() had to
// be in a specific order because otherwise the write to r0
// would overwrite the len parameter which resides in r0
case.addCompareOutput(
\\export fn _start() noreturn {
\\ print(id(14));
\\ exit();
\\}
\\
\\fn id(x: u32) u32 {
\\ return x;
\\}
\\
\\fn print(len: u32) void {
\\ asm volatile ("svc #0"
\\ :
\\ : [number] "{r7}" (4),
\\ [arg3] "{r2}" (len),
\\ [arg1] "{r0}" (1),
\\ [arg2] "{r1}" (@ptrToInt("Hello, World!\n"))
\\ : "memory"
\\ );
\\ return;
\\}
\\
\\fn exit() noreturn {
\\ asm volatile ("svc #0"
\\ :
\\ : [number] "{r7}" (1),
\\ [arg1] "{r0}" (0)
\\ : "memory"
\\ );
\\ unreachable;
\\}
,
"Hello, World!\n",
);
}
{
var case = ctx.exe("non-leaf functions", linux_arm);
// Testing non-leaf functions
case.addCompareOutput(
\\export fn _start() noreturn {
\\ foo();
\\ exit();
\\}
\\
\\fn foo() void {
\\ bar();
\\}
\\
\\fn bar() void {}
\\
\\fn exit() noreturn {
\\ asm volatile ("svc #0"
\\ :
\\ : [number] "{r7}" (1),
\\ [arg1] "{r0}" (0)
\\ : "memory"
\\ );
\\ unreachable;
\\}
,
"",
);
}
{
var case = ctx.exe("arithmetic operations", linux_arm);
// Add two numbers
case.addCompareOutput(
\\export fn _start() noreturn {
\\ print(2, 4);
\\ print(1, 7);
\\ exit();
\\}
\\
\\fn print(a: u32, b: u32) void {
\\ asm volatile ("svc #0"
\\ :
\\ : [number] "{r7}" (4),
\\ [arg3] "{r2}" (a + b),
\\ [arg1] "{r0}" (1),
\\ [arg2] "{r1}" (@ptrToInt("123456789"))
\\ : "memory"
\\ );
\\ return;
\\}
\\
\\fn exit() noreturn {
\\ asm volatile ("svc #0"
\\ :
\\ : [number] "{r7}" (1),
\\ [arg1] "{r0}" (0)
\\ : "memory"
\\ );
\\ unreachable;
\\}
,
"12345612345678",
);
// Subtract two numbers
case.addCompareOutput(
\\export fn _start() noreturn {
\\ print(10, 5);
\\ print(4, 3);
\\ exit();
\\}
\\
\\fn print(a: u32, b: u32) void {
\\ asm volatile ("svc #0"
\\ :
\\ : [number] "{r7}" (4),
\\ [arg3] "{r2}" (a - b),
\\ [arg1] "{r0}" (1),
\\ [arg2] "{r1}" (@ptrToInt("123456789"))
\\ : "memory"
\\ );
\\ return;
\\}
\\
\\fn exit() noreturn {
\\ asm volatile ("svc #0"
\\ :
\\ : [number] "{r7}" (1),
\\ [arg1] "{r0}" (0)
\\ : "memory"
\\ );
\\ unreachable;
\\}
,
"123451",
);
// Bitwise And
case.addCompareOutput(
\\export fn _start() noreturn {
\\ print(8, 9);
\\ print(3, 7);
\\ exit();
\\}
\\
\\fn print(a: u32, b: u32) void {
\\ asm volatile ("svc #0"
\\ :
\\ : [number] "{r7}" (4),
\\ [arg3] "{r2}" (a & b),
\\ [arg1] "{r0}" (1),
\\ [arg2] "{r1}" (@ptrToInt("123456789"))
\\ : "memory"
\\ );
\\ return;
\\}
\\
\\fn exit() noreturn {
\\ asm volatile ("svc #0"
\\ :
\\ : [number] "{r7}" (1),
\\ [arg1] "{r0}" (0)
\\ : "memory"
\\ );
\\ unreachable;
\\}
,
"12345678123",
);
// Bitwise Or
case.addCompareOutput(
\\export fn _start() noreturn {
\\ print(4, 2);
\\ print(3, 7);
\\ exit();
\\}
\\
\\fn print(a: u32, b: u32) void {
\\ asm volatile ("svc #0"
\\ :
\\ : [number] "{r7}" (4),
\\ [arg3] "{r2}" (a | b),
\\ [arg1] "{r0}" (1),
\\ [arg2] "{r1}" (@ptrToInt("123456789"))
\\ : "memory"
\\ );
\\ return;
\\}
\\
\\fn exit() noreturn {
\\ asm volatile ("svc #0"
\\ :
\\ : [number] "{r7}" (1),
\\ [arg1] "{r0}" (0)
\\ : "memory"
\\ );
\\ unreachable;
\\}
,
"1234561234567",
);
// Bitwise Xor
case.addCompareOutput(
\\export fn _start() noreturn {
\\ print(42, 42);
\\ print(3, 5);
\\ exit();
\\}
\\
\\fn print(a: u32, b: u32) void {
\\ asm volatile ("svc #0"
\\ :
\\ : [number] "{r7}" (4),
\\ [arg3] "{r2}" (a ^ b),
\\ [arg1] "{r0}" (1),
\\ [arg2] "{r1}" (@ptrToInt("123456789"))
\\ : "memory"
\\ );
\\ return;
\\}
\\
\\fn exit() noreturn {
\\ asm volatile ("svc #0"
\\ :
\\ : [number] "{r7}" (1),
\\ [arg1] "{r0}" (0)
\\ : "memory"
\\ );
\\ unreachable;
\\}
,
"123456",
);
}
{
var case = ctx.exe("if statements", linux_arm);
// Simple if statement in assert
case.addCompareOutput(
\\export fn _start() noreturn {
\\ var x: u32 = 123;
\\ var y: u32 = 42;
\\ assert(x > y);
\\ exit();
\\}
\\
\\fn assert(ok: bool) void {
\\ if (!ok) unreachable;
\\}
\\
\\fn exit() noreturn {
\\ asm volatile ("svc #0"
\\ :
\\ : [number] "{r7}" (1),
\\ [arg1] "{r0}" (0)
\\ : "memory"
\\ );
\\ unreachable;
\\}
,
"",
);
}
{
var case = ctx.exe("while loops", linux_arm);
// Simple while loop with assert
case.addCompareOutput(
\\export fn _start() noreturn {
\\ var x: u32 = 2020;
\\ var i: u32 = 0;
\\ while (x > 0) {
\\ x -= 2;
\\ i += 1;
\\ }
\\ assert(i == 1010);
\\ exit();
\\}
\\
\\fn assert(ok: bool) void {
\\ if (!ok) unreachable;
\\}
\\
\\fn exit() noreturn {
\\ asm volatile ("svc #0"
\\ :
\\ : [number] "{r7}" (1),
\\ [arg1] "{r0}" (0)
\\ : "memory"
\\ );
\\ unreachable;
\\}
,
"",
);
}
{
var case = ctx.exe("integer multiplication", linux_arm);
// Simple u32 integer multiplication
case.addCompareOutput(
\\export fn _start() noreturn {
\\ assert(mul(1, 1) == 1);
\\ assert(mul(42, 1) == 42);
\\ assert(mul(1, 42) == 42);
\\ assert(mul(123, 42) == 5166);
\\ exit();
\\}
\\
\\fn mul(x: u32, y: u32) u32 {
\\ return x * y;
\\}
\\
\\fn assert(ok: bool) void {
\\ if (!ok) unreachable;
\\}
\\
\\fn exit() noreturn {
\\ asm volatile ("svc #0"
\\ :
\\ : [number] "{r7}" (1),
\\ [arg1] "{r0}" (0)
\\ : "memory"
\\ );
\\ unreachable;
\\}
,
"",
);
}
{
var case = ctx.exe("save function return values in callee preserved register", linux_arm);
// Here, it is necessary to save the result of bar() into a
// callee preserved register, otherwise it will be overwritten
// by the first parameter to baz.
case.addCompareOutput(
\\export fn _start() noreturn {
\\ assert(foo() == 43);
\\ exit();
\\}
\\
\\fn foo() u32 {
\\ return bar() + baz(42);
\\}
\\
\\fn bar() u32 {
\\ return 1;
\\}
\\
\\fn baz(x: u32) u32 {
\\ return x;
\\}
\\
\\fn assert(ok: bool) void {
\\ if (!ok) unreachable;
\\}
\\
\\fn exit() noreturn {
\\ asm volatile ("svc #0"
\\ :
\\ : [number] "{r7}" (1),
\\ [arg1] "{r0}" (0)
\\ : "memory"
\\ );
\\ unreachable;
\\}
,
"",
);
}
{
var case = ctx.exe("recursive fibonacci", linux_arm);
case.addCompareOutput(
\\export fn _start() noreturn {
\\ assert(fib(0) == 0);
\\ assert(fib(1) == 1);
\\ assert(fib(2) == 1);
\\ assert(fib(3) == 2);
\\ assert(fib(10) == 55);
\\ assert(fib(20) == 6765);
\\ exit();
\\}
\\
\\fn fib(n: u32) u32 {
\\ if (n < 2) {
\\ return n;
\\ } else {
\\ return fib(n - 2) + fib(n - 1);
\\ }
\\}
\\
\\fn assert(ok: bool) void {
\\ if (!ok) unreachable;
\\}
\\
\\fn exit() noreturn {
\\ asm volatile ("svc #0"
\\ :
\\ : [number] "{r7}" (1),
\\ [arg1] "{r0}" (0)
\\ : "memory"
\\ );
\\ unreachable;
\\}
,
"",
);
}
} | test/stage2/arm.zig |
const std = @import("std");
const File = @import("File.zig");
const Process = @import("Process.zig");
const Thread = @import("Thread.zig");
const P = @import("Memory.zig").P;
const T = @import("types.zig");
pub const handler = switch (std.builtin.arch) {
.powerpc => handlers.powerpc,
.x86_64 => handlers.x86_64,
else => @compileError("handler '" ++ @tagName(std.builtin.arch) ++ "' not defined"),
};
const handlers = struct {
pub fn powerpc() callconv(.Naked) noreturn {
const code = asm volatile (""
: [ret] "={r0}" (-> u32)
);
var raw_args: [6]u32 = .{
asm volatile (""
: [ret] "={r3}" (-> u32)
),
asm volatile (""
: [ret] "={r4}" (-> u32)
),
asm volatile (""
: [ret] "={r5}" (-> u32)
),
asm volatile (""
: [ret] "={r6}" (-> u32)
),
asm volatile (""
: [ret] "={r7}" (-> u32)
),
asm volatile (""
: [ret] "={r8}" (-> u32)
),
};
var errored = false;
const thread = Thread.active().?;
const value = invoke(thread, code, raw_args) catch |err| switch (err) {
error.IllegalSyscall => {
thread.pid.process().signal(.ill);
unreachable;
},
else => |e| blk: {
errored = true;
break :blk @enumToInt(T.Errno.from(e));
},
};
_ = asm volatile ("rfi"
: [ret] "={r3}" (-> usize)
: [value] "{r3}" (value),
[err] "{cr0}" (errored)
);
unreachable;
}
pub fn x86_64() callconv(.Naked) noreturn {
const code = asm volatile (""
: [ret] "={rax}" (-> u64)
);
const ret_addr = asm volatile (""
: [ret] "={rcx}" (-> u64)
);
var raw_args: [6]u64 = .{
asm volatile (""
: [ret] "={rdi}" (-> u64)
),
asm volatile (""
: [ret] "={rsi}" (-> u64)
),
asm volatile (""
: [ret] "={rdx}" (-> u64)
),
asm volatile (""
: [ret] "={r10}" (-> u64)
),
asm volatile (""
: [ret] "={r8}" (-> u64)
),
asm volatile (""
: [ret] "={r9}" (-> u64)
),
};
const thread = Thread.active().?;
const value = invoke(thread, code, raw_args) catch |err| switch (err) {
error.IllegalSyscall => {
thread.pid.process().signal(.ill);
unreachable;
},
else => |e| -%@as(u32, @enumToInt(T.Errno.from(e))),
};
_ = asm volatile ("sysret"
: [ret] "={rax}" (-> usize)
: [value] "{rax}" (value)
);
unreachable;
}
};
const FatalError = error{
IllegalSyscall,
};
fn invoke(thread: *Thread, code: usize, raw_args: [6]usize) (FatalError || T.Errno.E)!usize {
inline for (std.meta.declarations(impls)) |decl| {
if (code == comptime decode(decl.name)) {
const func = @field(impls, decl.name);
const Args = std.meta.ArgsTuple(@TypeOf(func));
var args: Args = undefined;
args[0] = thread;
if (args.len > 1) {
inline for (std.meta.fields(Args)[1..]) |field, i| {
const Int = std.meta.Int(.unsigned, @bitSizeOf(field.field_type));
const raw = std.math.cast(Int, raw_args[i]) catch |err| switch (err) {
error.Overflow => return error.IllegalSyscall,
};
args[i + 1] = switch (@typeInfo(field.field_type)) {
.Enum => @intToEnum(field.field_type, raw),
.Pointer => @intToPtr(field.field_type, raw),
else => @bitCast(field.field_type, raw),
};
}
}
const raw_result = @call(comptime std.builtin.CallOptions{}, func, args);
const result = switch (@typeInfo(@TypeOf(raw_result))) {
.ErrorUnion => try raw_result,
else => raw_result,
};
return switch (@typeInfo(@TypeOf(result))) {
.Enum => @enumToInt(result),
.Pointer => @ptrToInt(result),
else => result,
};
}
}
return error.IllegalSyscall;
}
test {
_ = invoke;
_ = handler;
}
fn decode(comptime name: []const u8) comptime_int {
if (name[0] < '0' or name[0] > '9' or
name[1] < '0' or name[1] > '9' or
name[2] < '0' or name[2] > '9' or
name[3] != ' ')
{
@compileError("fn @\"" ++ name ++ "\" must start with '000 '");
}
return @as(u16, 100) * (name[0] - '0') + @as(u16, 10) * (name[1] - '0') + (name[2] - '0');
}
test "decode" {
std.testing.expectEqual(1, decode("001 "));
std.testing.expectEqual(69, decode("069 "));
std.testing.expectEqual(420, decode("420 "));
}
const impls = struct {
pub fn @"000 restart"(thread: *Thread) usize {
unreachable;
}
pub fn @"001 exit"(thread: *Thread, arg: usize) usize {
unreachable;
}
pub fn @"002 fork"(thread: *Thread) !Process.Id {
const forked = Process.fork(thread) catch |err| switch (err) {
error.OutOfMemory => return T.Errno.E.ENOMEM,
};
return forked.id;
}
pub fn @"003 read"(thread: *Thread, fid: File.Id, buf: P(u8), count: usize) !usize {
const process = thread.pid.process();
if (!process.fids.contains(fid)) return T.Errno.E.EBADF;
return fid.file().read(try process.memory.getMany(buf, count));
}
pub fn @"004 write"(thread: *Thread, fid: File.Id, buf: P(u8), count: usize) !usize {
const process = thread.pid.process();
if (!process.fids.contains(fid)) return T.Errno.E.EBADF;
return fid.file().write(try process.memory.getMany(buf, count));
}
pub fn @"005 open"(thread: *Thread, path: P(u8), flags: File.Flags, perm: File.Mode) !File.Id {
const process = thread.pid.process();
const file = try File.open(
try process.memory.getManyZ(path),
flags,
perm,
);
errdefer file.release();
process.fids.putNoClobber(file.id, {}) catch |err| switch (err) {
error.OutOfMemory => return T.Errno.E.EMFILE,
};
return file.id;
}
pub fn @"006 close"(thread: *Thread, fid: File.Id) !usize {
const process = thread.pid.process();
if (process.fids.remove(fid) == null) {
return T.Errno.E.EBADF;
}
fid.file().release();
return 0;
}
}; | src/syscall.zig |
usingnamespace @import("root").preamble;
pub fn renderBitmapFont(
comptime f: anytype,
background_color: lib.graphics.color.Color,
foreground_color: lib.graphics.color.Color,
comptime pixel_format: lib.graphics.pixel_format.PixelFormat,
) renderedFontType(f, pixel_format) {
var result: renderedFontType(f, pixel_format) = undefined;
@setEvalBranchQuota(1000000);
var byte_pos: usize = 0;
for (result) |*c, i| {
const region = c.regionMutable();
region.fill(background_color, 0, 0, region.width, region.height, false);
var y: usize = 0;
while (y < f.height) : ({
y += 1;
byte_pos += 1;
}) {
var x: usize = 0;
var bit: usize = 0;
while (x < f.width) : ({
x += 1;
}) {
const shift = f.width - 1 - x;
const has_pixel_set = ((f.data[byte_pos] >> shift) & 1) != 0;
if (has_pixel_set)
region.drawPixel(foreground_color, x, y, false);
}
}
}
return result;
}
fn numChars(comptime f: anytype) usize {
const num_bytes = f.data.len;
const bytes_per_line = @divFloor(f.width + 7, 8);
const bytes_per_char = bytes_per_line * f.height;
return @divExact(f.data.len, bytes_per_char);
}
fn renderedFontType(
comptime f: anytype,
comptime pixel_format: lib.graphics.pixel_format.PixelFormat,
) type {
return [numChars(f)]RenderedChar(f.width, f.height, pixel_format);
}
fn RenderedChar(
comptime width: usize,
comptime height: usize,
comptime pixel_format: lib.graphics.pixel_format.PixelFormat,
) type {
return struct {
data: [width * height * pixel_format.bytesPerPixel()]u8,
pub fn regionMutable(self: *@This()) lib.graphics.image_region.ImageRegion {
return .{
.width = width,
.height = height,
.pixel_format = pixel_format,
.bytes = self.data[0..],
.pitch = width * pixel_format.bytesPerPixel(),
.invalidateRectFunc = null,
};
}
pub fn region(self: *const @This()) lib.graphics.image_region.ImageRegion {
return .{
.width = width,
.height = height,
.pixel_format = pixel_format,
// @TODO: Remove ugly af cast
.bytes = @intToPtr([*]u8, @ptrToInt(@as([]const u8, self.data[0..]).ptr))[0..self.data.len],
.pitch = width * pixel_format.bytesPerPixel(),
.invalidateRectFunc = null,
};
}
};
} | lib/graphics/font_renderer.zig |
const token = @import("./lang/token.zig");
const colors = @import("./term/colors.zig");
const Colors = colors.Color;
const builtin = @import("builtin");
const parser = @import("./lang/parser.zig");
const cli = @import("./cli.zig");
const std = @import("std");
const w = Colors.white;
const d = Colors.red;
const c = Colors.cyan;
const g = Colors.green;
const y = Colors.yellow;
const m = Colors.magenta;
const b = Colors.blue;
pub const log_level: std.log.Level = .debug;
pub const info = std.log.scoped(.info);
pub const warn = std.log.scoped(.warn);
pub const err = std.log.scoped(.err);
pub fn log(
comptime level: std.log.Level,
comptime scope: @TypeOf(.EnumLiteral),
comptime format: []const u8,
args: anytype,
) void {
const r = comptime colors.reset();
const wb = comptime w.bold(.normal_fg);
const wd = comptime w.finish(.bright_fg);
const cb = comptime c.bold(.bright_fg);
const cd = comptime c.dim(.normal_fg);
const rb = comptime d.bold(.bright_fg);
const rd = comptime d.finish(.normal_fg);
const gb = comptime g.bold(.bright_fg);
const gd = comptime g.finish(.normal_fg);
const yb = comptime y.bold(.bright_fg);
const yd = comptime y.finish(.normal_fg);
const bb = comptime b.bold(.bright_fg);
const bd = comptime b.finish(.normal_fg);
const mb = comptime m.bold(.bright_fg);
const md = comptime m.finish(.normal_fg);
const sc_colors = switch (scope) {
.compiler => "[" ++ wb ++ "COMP" ++ wd ++ " :: ",
.parser => "[" ++ cb ++ "PARS" ++ cd ++ " :: ",
.lexer => "[" ++ bb ++ "LEX " ++ bd ++ " :: ",
.vm => "[" ++ mb ++ " VM " ++ md ++ " :: ",
.cli => "[" ++ yb ++ "CLI " ++ yd ++ " ][ ",
.ast => "[" ++ bb ++ "AST " ++ bd ++ " ][ ",
.expr => "[" ++ gb ++ "EXPR" ++ gd ++ ":: ",
.fmt => yb ++ "FMTG" ++ "\x1b[37;1m" ++ " :: ",
.token => mb ++ @tagName(scope)[0..3] ++ md ++ " :: ",
else => if (@enumToInt(level) <= @enumToInt(std.log.Level.err))
@tagName(scope)
else
return,
};
const status_pre = switch (level) {
.debug => gb ++ "DBG " ++ r ++ gd ++ "] -> ",
.info => bb ++ "INF " ++ r ++ bd ++ "] -> ",
.warn => yb ++ "WAR " ++ r ++ yd ++ "] -> ",
.err => rb ++ "ERR " ++ r ++ rd ++ "] -> ",
};
// std.debug.getStderrMutex().lock();
// defer std.debug.getStderrMutex().unlock();
// const stderr = std.io.getStdErr().writer();
const stdout = std.io.getStdOut().writer();
stdout.print(sc_colors ++ status_pre ++ format ++ "\n", args) catch return;
// nosuspend stderr.print(sc_colors ++ status_pre ++ format ++ "\n", args) catch return;
} | src/log.zig |
pub const NSVG_PAINT_NONE: c_int = 0;
pub const NSVG_PAINT_COLOR: c_int = 1;
pub const NSVG_PAINT_LINEAR_GRADIENT: c_int = 2;
pub const NSVG_PAINT_RADIAL_GRADIENT: c_int = 3;
pub const enum_NSVGpaintType = c_uint;
pub const NSVG_SPREAD_PAD: c_int = 0;
pub const NSVG_SPREAD_REFLECT: c_int = 1;
pub const NSVG_SPREAD_REPEAT: c_int = 2;
pub const enum_NSVGspreadType = c_uint;
pub const NSVG_JOIN_MITER: c_int = 0;
pub const NSVG_JOIN_ROUND: c_int = 1;
pub const NSVG_JOIN_BEVEL: c_int = 2;
pub const enum_NSVGlineJoin = c_uint;
pub const NSVG_CAP_BUTT: c_int = 0;
pub const NSVG_CAP_ROUND: c_int = 1;
pub const NSVG_CAP_SQUARE: c_int = 2;
pub const enum_NSVGlineCap = c_uint;
pub const NSVG_FILLRULE_NONZERO: c_int = 0;
pub const NSVG_FILLRULE_EVENODD: c_int = 1;
pub const enum_NSVGfillRule = c_uint;
pub const NSVG_FLAGS_VISIBLE: c_int = 1;
pub const enum_NSVGflags = c_uint;
pub const NSVGpaintType = enum_NSVGpaintType;
pub const NSVGspreadType = enum_NSVGspreadType;
pub const NSVGlineJoin = enum_NSVGlineJoin;
pub const NSVGlineCap = enum_NSVGlineCap;
pub const NSVGfillRule = enum_NSVGfillRule;
pub const NSVGflags = enum_NSVGflags;
pub const struct_NSVGgradientStop = extern struct {
color: c_uint,
offset: f32,
};
pub const NSVGgradientStop = struct_NSVGgradientStop;
pub const struct_NSVGgradient = extern struct {
xform: [6]f32,
spread: u8,
fx: f32,
fy: f32,
nstops: c_int,
stops: [*c]NSVGgradientStop,
};
pub const NSVGgradient = struct_NSVGgradient;
const union_unnamed_1 = extern union {
color: c_uint,
gradient: [*c]NSVGgradient,
};
pub const struct_NSVGpaint = extern struct {
type: u8,
unnamed_0: union_unnamed_1,
};
pub const NSVGpaint = struct_NSVGpaint;
pub const struct_NSVGpath = extern struct {
pts: [*c]f32,
npts: c_int,
closed: u8,
bounds: [4]f32,
next: [*c]struct_NSVGpath,
};
pub const NSVGpath = struct_NSVGpath;
pub const struct_NSVGshape = extern struct {
id: [64]u8,
fill: NSVGpaint,
stroke: NSVGpaint,
opacity: f32,
strokeWidth: f32,
strokeDashOffset: f32,
strokeDashArray: [8]f32,
strokeDashCount: u8,
strokeLineJoin: u8,
strokeLineCap: u8,
miterLimit: f32,
fillRule: u8,
flags: u8,
bounds: [4]f32,
paths: [*c]NSVGpath,
next: [*c]struct_NSVGshape,
};
pub const NSVGshape = struct_NSVGshape;
pub const struct_NSVGimage = extern struct {
width: f32,
height: f32,
shapes: [*c]NSVGshape,
};
pub const NSVGimage = struct_NSVGimage;
pub extern fn nsvgParseFromFile(filename: [*c]const u8, units: [*c]const u8, dpi: f32) [*c]NSVGimage;
pub extern fn nsvgParse(input: [*c]u8, units: [*c]const u8, dpi: f32) [*c]NSVGimage;
pub extern fn nsvgDuplicatePath(p: [*c]NSVGpath) [*c]NSVGpath;
pub extern fn nsvgDelete(image: [*c]NSVGimage) void; | src/deps/nanosvg/c.zig |
const std = @import("std");
const mem = std.mem;
const testing = std.testing;
pub const generator = @import("generator.zig");
pub const parser = @import("parser.zig");
pub const tokenizer = @import("tokenizer.zig");
test {
testing.refAllDecls(@This());
}
const Allocator = mem.Allocator;
const Generator = generator.Generator;
const Parser = parser.Parser;
const Scope = parser.Scope;
const Tokenizer = tokenizer.Tokenizer;
const Token = tokenizer.Token;
const TokenIndex = tokenizer.TokenIndex;
const TokenIterator = tokenizer.TokenIterator;
pub const Result = union(enum) {
ok: []const u8,
err: []const u8,
};
pub fn generate(gpa: Allocator, source: []const u8) !Result {
var arena_alloc = std.heap.ArenaAllocator.init(gpa);
defer arena_alloc.deinit();
const arena = arena_alloc.allocator();
var ttokenizer = Tokenizer{ .buffer = source };
var tokens = std.ArrayList(Token).init(arena);
while (true) {
const token = ttokenizer.next();
try tokens.append(token);
if (token.id == .eof) break;
}
var token_it = TokenIterator{ .buffer = tokens.items };
var scope = Scope{};
var pparser = Parser{
.arena = arena,
.token_it = &token_it,
.scope = &scope,
};
switch (try pparser.parse()) {
.ok => {},
.err => |err_msg| {
var msg = std.ArrayList(u8).init(gpa);
defer msg.deinit();
const token = token_it.buffer[err_msg.loc];
// TODO restore the immediate parent scope for error handling
const loc = try std.fmt.allocPrint(arena, "{s}\n", .{source[token.loc.start..token.loc.end]});
try msg.appendSlice(loc);
try msg.appendSlice(err_msg.msg);
return Result{ .err = msg.toOwnedSlice() };
},
}
var code = std.ArrayList(u8).init(gpa);
defer code.deinit();
var ggenerator = Generator{
.arena = arena,
.buffer = source,
.tokens = tokens.items,
.parse_scope = &scope,
};
switch (try ggenerator.generate(&code)) {
.ok => {},
.err => |err_msg| {
return Result{ .err = err_msg.msg };
},
}
return Result{ .ok = code.toOwnedSlice() };
} | src/lib.zig |
const c = @import("c.zig");
const mem = @import("std").mem;
const math = @import("std").math;
const debug = @import("std").debug;
const builtin = @import("builtin");
const OpenGLHasDrawWithBaseVertex = @hasField(c, "IMGUI_IMPL_OPENGL_ES2") or
@hasField(c, "IMGUI_IMPL_OPENGL_ES3");
// OpenGL Data
var g_GlslVersionString_buf: [32]u8 = undefined;
var g_GlslVersionString: []u8 = g_GlslVersionString_buf[0..0];
var g_FontTexture: c.GLuint = 0;
var g_ShaderHandle: c.GLuint = 0;
var g_VertHandle: c.GLuint = 0;
var g_FragHandle: c.GLuint = 0;
var g_AttribLocationTex: c.GLint = 0;
var g_AttribLocationProjMtx: c.GLint = 0;
var g_AttribLocationVtxPos: c.GLint = 0;
var g_AttribLocationVtxUV: c.GLint = 0;
var g_AttribLocationVtxColor: c.GLint = 0;
var g_VboHandle: c.GLuint = 0;
var g_ElementsHandle: c.GLuint = 0;
pub fn Init() void {
const io = c.igGetIO();
io.*.BackendRendererName = "imgui_impl_gl3.zig";
if (OpenGLHasDrawWithBaseVertex)
io.*.BackendFlags |= c.ImGuiBackendFlags_RendererHasVtxOffset;
// @TODO: Viewports
// io.*.BackendFlags |= @enumToInt(c.ImGuiBackendFlags_RendererHasViewports);
// @TODO: GLSL versions?
// g_GlslVersionString = g_GlslVersionString_buf[0..glsl_version.len];
// mem.copy(u8, g_GlslVersionString, glsl_version);
// @FIXME: just for testing:
var tex: c.GLint = undefined;
c.glGetIntegerv(c.GL_TEXTURE_BINDING_2D, &tex);
// @TODO: Viewports
// if (io.*.ConfigFlags & @enumToInt(c.ImGuiConfigFlags_ViewportsEnable) != 0)
// InitPlatformInterface();
}
pub fn Shutdown() void {
// ImGui_ImplOpenGL3_ShutdownPlatformInterface();
DestroyDeviceObjects();
}
pub fn NewFrame() !void {
if (g_ShaderHandle == 0)
try CreateDeviceObjects();
}
fn CreateDeviceObjects() !void {
// back up GL state
var last_texture: c.GLint = undefined;
var last_array_buffer: c.GLint = undefined;
var last_vertex_array: c.GLint = undefined;
c.glGetIntegerv(c.GL_TEXTURE_BINDING_2D, &last_texture);
defer c.glBindTexture(c.GL_TEXTURE_2D, @intCast(c.GLuint, last_texture));
c.glGetIntegerv(c.GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
c.glBindBuffer(c.GL_ARRAY_BUFFER, @intCast(c.GLuint, last_array_buffer));
if (!@hasField(c, "IMGUI_IMPL_OPENGL_ES2"))
c.glGetIntegerv(c.GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
defer if (!@hasField(c, "IMGUI_IMPL_OPENGL_ES2"))
c.glBindVertexArray(@intCast(c.GLuint, last_vertex_array));
// @TODO: GLSL versions?
const vertex_shader_glsl: [*]const c.GLchar =
\\#version 150
\\uniform mat4 ProjMtx;
\\in vec2 Position;
\\in vec2 UV;
\\in vec4 Color;
\\out vec2 Frag_UV;
\\out vec4 Frag_Color;
\\void main()
\\{
\\ Frag_UV = UV;
\\ Frag_Color = Color;
\\ gl_Position = ProjMtx * vec4(Position.xy, 0, 1);
\\}
;
const fragment_shader_glsl: [*]const c.GLchar =
\\#version 150
\\uniform sampler2D Texture;
\\in vec2 Frag_UV;
\\in vec4 Frag_Color;
\\out vec4 Out_Color;
\\void main()
\\{
\\ Out_Color = Frag_Color * texture(Texture, Frag_UV.st);
\\}
;
// Create shaders / programs
g_VertHandle = c.glCreateShader(c.GL_VERTEX_SHADER);
c.glShaderSource(g_VertHandle, 1, &vertex_shader_glsl, null);
c.glCompileShader(g_VertHandle);
try CheckThing(.Shader, g_VertHandle, "vertex shader");
g_FragHandle = c.glCreateShader(c.GL_FRAGMENT_SHADER);
c.glShaderSource(g_FragHandle, 1, &fragment_shader_glsl, null);
c.glCompileShader(g_FragHandle);
try CheckThing(.Shader, g_FragHandle, "fragment shader");
g_ShaderHandle = c.glCreateProgram();
c.glAttachShader(g_ShaderHandle, g_VertHandle);
c.glAttachShader(g_ShaderHandle, g_FragHandle);
c.glLinkProgram(g_ShaderHandle);
try CheckThing(.Program, g_ShaderHandle, "shader program");
g_AttribLocationTex = c.glGetUniformLocation(g_ShaderHandle, "Texture");
g_AttribLocationProjMtx = c.glGetUniformLocation(g_ShaderHandle, "ProjMtx");
g_AttribLocationVtxPos = c.glGetAttribLocation(g_ShaderHandle, "Position");
g_AttribLocationVtxUV = c.glGetAttribLocation(g_ShaderHandle, "UV");
g_AttribLocationVtxColor = c.glGetAttribLocation(g_ShaderHandle, "Color");
// Create buffers
c.glGenBuffers(1, &g_VboHandle);
c.glGenBuffers(1, &g_ElementsHandle);
CreateFontsTexture();
}
const CheckableThing = enum {
Shader,
Program,
};
fn CheckThing(comptime thingType: CheckableThing, handle: c.GLuint, desc: []const u8) !void {
var status: c.GLint = undefined;
var log_length: c.GLint = undefined;
const getInfoLogFunc = switch (thingType) {
.Shader => blk: {
c.glGetShaderiv(handle, c.GL_COMPILE_STATUS, &status);
c.glGetShaderiv(handle, c.GL_INFO_LOG_LENGTH, &log_length);
break :blk c.glGetShaderInfoLog;
},
.Program => blk: {
c.glGetProgramiv(handle, c.GL_LINK_STATUS, &status);
c.glGetProgramiv(handle, c.GL_INFO_LOG_LENGTH, &log_length);
break :blk c.glGetProgramInfoLog;
},
};
if (log_length > 1) {
var buf: [1024]u8 = undefined;
var length: c.GLsizei = undefined;
getInfoLogFunc(handle, buf.len, &length, &buf[0]);
debug.warn("{}\n", .{buf[0..@intCast(usize, length)]});
}
if (@intCast(c.GLboolean, status) == c.GL_FALSE) {
debug.warn("ERROR: CreateDeviceObjects: failed to compile/link {}! (with GLSL '{}')\n", .{desc, g_GlslVersionString});
return error.ShaderLinkError;
}
}
fn DestroyDeviceObjects() void {
if (g_VboHandle != 0) {
c.glDeleteBuffers(1, &g_VboHandle);
g_VboHandle = 0;
}
if (g_ElementsHandle != 0) {
c.glDeleteBuffers(1, &g_ElementsHandle);
g_ElementsHandle = 0;
}
if (g_ShaderHandle != 0 and g_VertHandle != 0)
c.glDetachShader(g_ShaderHandle, g_VertHandle);
if (g_ShaderHandle != 0 and g_FragHandle != 0)
c.glDetachShader(g_ShaderHandle, g_FragHandle);
if (g_VertHandle != 0) {
c.glDeleteShader(g_VertHandle);
g_VertHandle = 0;
}
if (g_FragHandle != 0) {
c.glDeleteShader(g_FragHandle);
g_FragHandle = 0;
}
if (g_ShaderHandle != 0) {
c.glDeleteProgram(g_ShaderHandle);
g_ShaderHandle = 0;
}
DestroyFontsTexture();
}
fn CreateFontsTexture() void {
const io = c.igGetIO();
// Get current font image data
var width: c_int = undefined;
var height: c_int = undefined;
var pixels: [*c]u8 = undefined;
c.ImFontAtlas_GetTexDataAsRGBA32(io.*.Fonts, &pixels, &width, &height, null);
// backup & restore state
var last_texture: c.GLint = undefined;
c.glGetIntegerv(c.GL_TEXTURE_BINDING_2D, &last_texture);
defer c.glBindTexture(c.GL_TEXTURE_2D, @intCast(c.GLuint, last_texture));
// Upload texture to graphics system
c.glGenTextures(1, &g_FontTexture);
c.glBindTexture(c.GL_TEXTURE_2D, g_FontTexture);
c.glTexParameteri(c.GL_TEXTURE_2D, c.GL_TEXTURE_MIN_FILTER, c.GL_LINEAR);
c.glTexParameteri(c.GL_TEXTURE_2D, c.GL_TEXTURE_MAG_FILTER, c.GL_LINEAR);
if (@hasField(c, "GL_UNPACK_ROW_LENGTH"))
c.glPixelStorei(c.GL_UNPACK_ROW_LENGTH, 0);
c.glTexImage2D(c.GL_TEXTURE_2D, 0, c.GL_RGBA, width, height, 0, c.GL_RGBA, c.GL_UNSIGNED_BYTE, pixels);
// Store texture ID
io.*.Fonts.*.TexID = @intToPtr(c.ImTextureID, g_FontTexture);
}
fn DestroyFontsTexture() void {
if (g_FontTexture == 0)
return;
const io = c.igGetIO();
c.glDeleteTextures(1, &g_FontTexture);
io.*.Fonts.*.TexID = @intToPtr(c.ImTextureID, 0);
g_FontTexture = 0;
}
pub fn RenderDrawData(draw_data: *c.ImDrawData) void {
// Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
const fb_width = @floatToInt(i32, draw_data.*.DisplaySize.x * draw_data.*.FramebufferScale.x);
const fb_height = @floatToInt(i32, draw_data.*.DisplaySize.y * draw_data.*.FramebufferScale.y);
if (fb_width <= 0 or fb_height <= 0)
return;
// Backup GL state
var last_program: c.GLint = undefined;
var last_texture: c.GLint = undefined;
var last_sampler: c.GLint = undefined;
var last_array_buffer: c.GLint = undefined;
var last_vertex_array_object: c.GLint = undefined;
var last_polygon_mode: [2]c.GLint = undefined;
var last_viewport: [4]c.GLint = undefined;
var last_scissor_box: [4]c.GLint = undefined;
var last_blend_src_rgb: c.GLint = undefined;
var last_blend_dst_rgb: c.GLint = undefined;
var last_blend_src_alpha: c.GLint = undefined;
var last_blend_dst_alpha: c.GLint = undefined;
var last_blend_equation_rgb: c.GLint = undefined;
var last_blend_equation_alpha: c.GLint = undefined;
var clip_origin_lower_left: bool = true;
var last_clip_origin: c.GLint = 0;
var last_active_texture: c.GLint = undefined;
c.glGetIntegerv(c.GL_ACTIVE_TEXTURE, &last_active_texture);
c.glActiveTexture(c.GL_TEXTURE0);
c.glGetIntegerv(c.GL_CURRENT_PROGRAM, &last_program);
c.glGetIntegerv(c.GL_TEXTURE_BINDING_2D, &last_texture);
if (@hasField(c, "GL_SAMPLER_BINDING"))
c.glGetIntegerv(c.GL_SAMPLER_BINDING, &last_sampler);
c.glGetIntegerv(c.GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
if (!@hasField(c, "IMGUI_IMPL_OPENc.GL_ES2"))
c.glGetIntegerv(c.GL_VERTEX_ARRAY_BINDING, &last_vertex_array_object);
if (@hasField(c, "GL_POLYGON_MODE"))
c.glGetIntegerv(c.GL_POLYGON_MODE, last_polygon_mode);
c.glGetIntegerv(c.GL_VIEWPORT, &last_viewport[0]);
c.glGetIntegerv(c.GL_SCISSOR_BOX, &last_scissor_box[0]);
c.glGetIntegerv(c.GL_BLEND_SRC_RGB, &last_blend_src_rgb);
c.glGetIntegerv(c.GL_BLEND_DST_RGB, &last_blend_dst_rgb);
c.glGetIntegerv(c.GL_BLEND_SRC_ALPHA, &last_blend_src_alpha);
c.glGetIntegerv(c.GL_BLEND_DST_ALPHA, &last_blend_dst_alpha);
c.glGetIntegerv(c.GL_BLEND_EQUATION_RGB, &last_blend_equation_rgb);
c.glGetIntegerv(c.GL_BLEND_EQUATION_ALPHA, &last_blend_equation_alpha);
var last_enable_blend: c.GLboolean = c.glIsEnabled(c.GL_BLEND);
var last_enable_cull_face: c.GLboolean = c.glIsEnabled(c.GL_CULL_FACE);
var last_enable_depth_test: c.GLboolean = c.glIsEnabled(c.GL_DEPTH_TEST);
var last_enable_scissor_test: c.GLboolean = c.glIsEnabled(c.GL_SCISSOR_TEST);
if (@hasField(c, "GL_CLIP_ORIGIN") and builtin.os != builtin.Os.osx) {
// Support for GL 4.5's glClipControl(GL_UPPER_LEFT)
c.glGetIntegerv(c.GL_CLIP_ORIGIN, &last_clip_origin);
if (last_clip_origin == c.GL_UPPER_LEFT)
clip_origin_lower_left = false;
}
defer {
// Restore modified GL state
c.glUseProgram(@intCast(c.GLuint, last_program));
c.glBindTexture(c.GL_TEXTURE_2D, @intCast(c.GLuint, last_texture));
if (@hasField(c, "GL_SAMPLER_BINDING"))
c.glBindSampler(0, @intCast(c.GLuint, last_sampler));
c.glActiveTexture(@intCast(c.GLuint, last_active_texture));
if (!@hasField(c, "IMGUI_IMPL_OPENGL_ES2"))
c.glBindVertexArray(@intCast(c.GLuint, last_vertex_array_object));
c.glBindBuffer(c.GL_ARRAY_BUFFER, @intCast(c.GLuint, last_array_buffer));
c.glBlendEquationSeparate(@intCast(c.GLuint, last_blend_equation_rgb), @intCast(c.GLuint, last_blend_equation_alpha));
c.glBlendFuncSeparate(@intCast(c.GLuint, last_blend_src_rgb), @intCast(c.GLuint, last_blend_dst_rgb), @intCast(c.GLuint, last_blend_src_alpha), @intCast(c.GLuint, last_blend_dst_alpha));
if (last_enable_blend == c.GL_TRUE) {
c.glEnable(c.GL_BLEND);
} else {
c.glDisable(c.GL_BLEND);
}
if (last_enable_cull_face == c.GL_TRUE) {
c.glEnable(c.GL_CULL_FACE);
} else {
c.glDisable(c.GL_CULL_FACE);
}
if (last_enable_depth_test == c.GL_TRUE) {
c.glEnable(c.GL_DEPTH_TEST);
} else {
c.glDisable(c.GL_DEPTH_TEST);
}
if (last_enable_scissor_test == c.GL_TRUE) {
c.glEnable(c.GL_SCISSOR_TEST);
} else {
c.glDisable(c.GL_SCISSOR_TEST);
}
if (@hasField(c, "GL_POLYGON_MODE"))
c.glPolygonMode(c.GL_FRONT_AND_BACK, @intCast(c.GLenum, last_polygon_mode[0]));
c.glViewport(last_viewport[0], last_viewport[1], @intCast(c.GLsizei, last_viewport[2]), @intCast(c.GLsizei, last_viewport[3]));
c.glScissor(last_scissor_box[0], last_scissor_box[1], @intCast(c.GLsizei, last_scissor_box[2]), @intCast(c.GLsizei, last_scissor_box[3]));
}
// Setup desired GL state
// Recreate the VAO every time (this is to easily allow multiple GL contexts to be rendered to. VAO are not shared among GL contexts)
// The renderer would actually work without any VAO bound, but then our VertexAttrib calls would overwrite the default one currently bound.
var vertex_array_object: c.GLuint = 0;
if (!@hasField(c, "IMGUI_IMPL_OPENGL_ES2"))
c.glGenVertexArrays(1, &vertex_array_object);
defer if (!@hasField(c, "IMGUI_IMPL_OPENGL_ES2"))
c.glDeleteVertexArrays(1, &vertex_array_object);
SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object);
// Will project scissor/clipping rectangles into framebuffer space
const clip_off = draw_data.*.DisplayPos; // (0,0) unless using multi-viewports
const clip_scale = draw_data.*.FramebufferScale; // (1,1) unless using retina display which are often (2,2)
// Render command lists
var n: usize = 0;
while (n < @intCast(usize, draw_data.*.CmdListsCount)) : (n += 1) {
const cmd_list = draw_data.*.CmdLists[n];
// Upload vertex/index buffers
c.glBufferData(c.GL_ARRAY_BUFFER, cmd_list.*.VtxBuffer.Size * @sizeOf(c.ImDrawVert), @ptrCast(?*c.GLvoid, cmd_list.*.VtxBuffer.Data), c.GL_STREAM_DRAW);
c.glBufferData(c.GL_ELEMENT_ARRAY_BUFFER, cmd_list.*.IdxBuffer.Size * @sizeOf(c.ImDrawIdx), @ptrCast(*c.GLvoid, cmd_list.*.IdxBuffer.Data), c.GL_STREAM_DRAW);
var cmd_i: usize = 0;
while (cmd_i < @intCast(usize, cmd_list.*.CmdBuffer.Size)) : (cmd_i += 1) {
const pcmd = &cmd_list.*.CmdBuffer.Data[cmd_i];
if (pcmd.*.UserCallback != null) {
// User callback, registered via ImDrawList::AddCallback()
// (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
const ImDrawCallback_ResetRenderState = @intToPtr(c.ImDrawCallback, math.maxInt(usize));
if (pcmd.*.UserCallback == ImDrawCallback_ResetRenderState) {
SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object);
} else {
if (pcmd.*.UserCallback) |callback| {
callback(cmd_list, pcmd);
} else {
unreachable;
}
}
} else {
// Project scissor/clipping rectangles into framebuffer space
var clip_rect: c.ImVec4 = undefined;
clip_rect.x = (pcmd.*.ClipRect.x - clip_off.x) * clip_scale.x;
clip_rect.y = (pcmd.*.ClipRect.y - clip_off.y) * clip_scale.y;
clip_rect.z = (pcmd.*.ClipRect.z - clip_off.x) * clip_scale.x;
clip_rect.w = (pcmd.*.ClipRect.w - clip_off.y) * clip_scale.y;
if (clip_rect.x < @intToFloat(f32, fb_width) and clip_rect.y < @intToFloat(f32, fb_height) and clip_rect.z >= 0.0 and clip_rect.w >= 0.0) {
// Apply scissor/clipping rectangle
if (clip_origin_lower_left) {
c.glScissor(@floatToInt(c.GLint, clip_rect.x), fb_height - @floatToInt(c.GLint, clip_rect.w), @floatToInt(c.GLint, clip_rect.z - clip_rect.x), @floatToInt(c.GLint, clip_rect.w - clip_rect.y));
} else {
// Support for GL 4.5 rarely used glClipControl(GL_UPPER_LEFT)
c.glScissor(@floatToInt(c.GLint, clip_rect.x), @floatToInt(c.GLint, clip_rect.y), @floatToInt(c.GLint, clip_rect.z), @floatToInt(c.GLint, clip_rect.w));
}
// Bind texture, Draw
c.glBindTexture(c.GL_TEXTURE_2D, @intCast(c.GLuint, @ptrToInt(pcmd.*.TextureId)));
const drawIndexSize = @sizeOf(c.ImDrawIdx);
const drawIndexType = if (drawIndexSize == 2) c.GL_UNSIGNED_SHORT else c.GL_UNSIGNED_INT;
const offset = @intToPtr(?*c.GLvoid, pcmd.*.IdxOffset * drawIndexSize);
if (@hasField(c, "IMGUI_IMPL_OPENGL_HAS_DRAW_WITH_BASE_VERTEX")) {
c.glDrawElementsBaseVertex(c.GL_TRIANGLES, @intCast(c.GLsizei, pcmd.*.ElemCount), drawIndexType, offset, @intCast(c.GLint, pcmd.*.VtxOffset));
} else {
c.glDrawElements(c.GL_TRIANGLES, @intCast(c.GLsizei, pcmd.*.ElemCount), drawIndexType, offset);
}
}
}
}
}
}
fn SetupRenderState(draw_data: *c.ImDrawData, fb_width: i32, fb_height: i32, vertex_array_object: c.GLuint) void {
// Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, polygon fill
c.glEnable(c.GL_BLEND);
c.glBlendEquation(c.GL_FUNC_ADD);
c.glBlendFunc(c.GL_SRC_ALPHA, c.GL_ONE_MINUS_SRC_ALPHA);
c.glDisable(c.GL_CULL_FACE);
c.glDisable(c.GL_DEPTH_TEST);
c.glEnable(c.GL_SCISSOR_TEST);
if (@hasField(c, "GL_POLYGON_MODE"))
c.glPolygonMode(c.GL_FRONT_AND_BACK, c.GL_FILL);
// Setup viewport, orthographic projection matrix
// Our visible imgui space lies from draw_data.*.DisplayPos (top left) to draw_data.*.DisplayPos+data_data.*.DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps.
c.glViewport(0, 0, @intCast(c.GLsizei, fb_width), @intCast(c.GLsizei, fb_height));
const L = draw_data.*.DisplayPos.x;
const R = draw_data.*.DisplayPos.x + draw_data.*.DisplaySize.x;
const T = draw_data.*.DisplayPos.y;
const B = draw_data.*.DisplayPos.y + draw_data.*.DisplaySize.y;
const ortho_projection = [4][4]f32{
[_]f32{ 2.0 / (R - L), 0.0, 0.0, 0.0 },
[_]f32{ 0.0, 2.0 / (T - B), 0.0, 0.0 },
[_]f32{ 0.0, 0.0, -1.0, 0.0 },
[_]f32{ (R + L) / (L - R), (T + B) / (B - T), 0.0, 1.0 },
};
c.glUseProgram(g_ShaderHandle);
c.glUniform1i(g_AttribLocationTex, 0);
c.glUniformMatrix4fv(g_AttribLocationProjMtx, 1, c.GL_FALSE, &ortho_projection[0][0]);
if (@hasField(c, "GL_SAMPLER_BINDING"))
c.glBindSampler(0, 0); // We use combined texture/sampler state. Applications using GL 3.3 may set that otherwise.
if (!@hasField(c, "IMGUI_IMPL_OPENGL_ES2"))
c.glBindVertexArray(vertex_array_object);
// Bind vertex/index buffers and setup attributes for ImDrawVert
c.glBindBuffer(c.GL_ARRAY_BUFFER, g_VboHandle);
c.glBindBuffer(c.GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle);
c.glEnableVertexAttribArray(@intCast(c.GLuint, g_AttribLocationVtxPos));
c.glEnableVertexAttribArray(@intCast(c.GLuint, g_AttribLocationVtxUV));
c.glEnableVertexAttribArray(@intCast(c.GLuint, g_AttribLocationVtxColor));
c.glVertexAttribPointer(@intCast(c.GLuint, g_AttribLocationVtxPos), 2, c.GL_FLOAT, c.GL_FALSE, @sizeOf(c.ImDrawVert), @intToPtr(?*c.GLvoid, @byteOffsetOf(c.ImDrawVert, "pos")));
c.glVertexAttribPointer(@intCast(c.GLuint, g_AttribLocationVtxUV), 2, c.GL_FLOAT, c.GL_FALSE, @sizeOf(c.ImDrawVert), @intToPtr(?*c.GLvoid, @byteOffsetOf(c.ImDrawVert, "uv")));
c.glVertexAttribPointer(@intCast(c.GLuint, g_AttribLocationVtxColor), 4, c.GL_UNSIGNED_BYTE, c.GL_TRUE, @sizeOf(c.ImDrawVert), @intToPtr(?*c.GLvoid, @byteOffsetOf(c.ImDrawVert, "col")));
} | examples/imgui-dice-roller/src/gl3_impl.zig |
const std = @import("std");
const testing = std.testing;
const Allocator = std.mem.Allocator;
/// Wrapping map over a map of keys and values
/// that provides an easy way to free all its memory.
pub const KeyValueMap = struct {
/// inner map
map: MapType,
const MapType = std.StringHashMapUnmanaged([]const u8);
/// Frees all memory owned by this `KeyValueMap`
pub fn deinit(self: *KeyValueMap, gpa: *Allocator) void {
var it = self.map.iterator();
while (it.next()) |pair| {
gpa.free(pair.key_ptr.*);
gpa.free(pair.value_ptr.*);
}
self.map.deinit(gpa);
}
/// Wrapping method over inner `map`'s `get()` function for easy access
pub fn get(self: KeyValueMap, key: []const u8) ?[]const u8 {
return self.map.get(key);
}
/// Wrapping method over inner map's `iterator()` function for easy access
pub fn iterator(self: KeyValueMap) MapType.Iterator {
return self.map.iterator();
}
};
/// Possible errors when parsing query parameters
const QueryError = error{ MalformedUrl, OutOfMemory, InvalidCharacter };
pub const Url = struct {
path: []const u8,
raw_path: []const u8,
raw_query: []const u8,
/// Builds a new URL from a given path
pub fn init(path: []const u8) Url {
const query = blk: {
var raw_query: []const u8 = undefined;
if (std.mem.indexOf(u8, path, "?")) |index| {
raw_query = path[index..];
} else {
raw_query = "";
}
break :blk raw_query;
};
return Url{
.path = path[0 .. path.len - query.len],
.raw_path = path,
.raw_query = query,
};
}
/// Builds query parameters from url's `raw_query`
/// Memory is owned by caller
/// Note: For now, each key/value pair needs to be freed manually
pub fn queryParameters(self: Url, gpa: *Allocator) QueryError!KeyValueMap {
return decodeQueryString(gpa, self.raw_query);
}
};
/// Decodes a query string into key-value pairs. This will also
/// url-decode and replace %<hex> with its ascii value.
///
/// Memory is owned by the caller and as each key and value are allocated due to decoding,
/// must be freed individually
pub fn decodeQueryString(gpa: *Allocator, data: []const u8) QueryError!KeyValueMap {
var queries = KeyValueMap{ .map = KeyValueMap.MapType{} };
errdefer queries.deinit(gpa);
var query = data;
if (std.mem.startsWith(u8, query, "?")) {
query = query[1..];
}
while (query.len > 0) {
var key = query;
if (std.mem.indexOfScalar(u8, key, '&')) |index| {
query = key[index + 1 ..];
key = key[0..index];
} else {
query = "";
}
if (key.len == 0) continue;
var value: []const u8 = undefined;
if (std.mem.indexOfScalar(u8, key, '=')) |index| {
value = key[index + 1 ..];
key = key[0..index];
}
key = try decode(gpa, key);
errdefer gpa.free(key);
value = try decode(gpa, value);
errdefer gpa.free(value);
try queries.map.put(gpa, key, value);
}
return queries;
}
/// Decodes the given input `value` by decoding the %hex number into ascii
/// memory is owned by caller
pub fn decode(allocator: *Allocator, value: []const u8) QueryError![]const u8 {
var perc_counter: usize = 0;
var has_plus: bool = false;
// find % and + symbols to determine buffer size
var i: usize = 0;
while (i < value.len) : (i += 1) {
switch (value[i]) {
'%' => {
perc_counter += 1;
if (i + 2 > value.len or !isHex(value[i + 1]) or !isHex(value[i + 2])) {
return QueryError.MalformedUrl;
}
i += 2;
},
'+' => {
has_plus = true;
},
else => {},
}
}
// replace url encoded string
const buffer = try allocator.alloc(u8, value.len - 2 * perc_counter);
errdefer allocator.free(buffer);
// No decoding required, so copy into allocated buffer so the result
// can be freed consistantly.
if (perc_counter == 0 and !has_plus) {
std.mem.copy(u8, buffer, value);
return buffer;
}
i = 0;
while (i < buffer.len) : (i += 1) {
switch (value[i]) {
'%' => {
const a = try std.fmt.charToDigit(value[i + 1], 16);
const b = try std.fmt.charToDigit(value[i + 2], 16);
buffer[i] = a << 4 | b;
i += 2;
},
'+' => buffer[i] = ' ',
else => buffer[i] = value[i],
}
}
return buffer;
}
/// Sanitizes the given `path` by removing '..' etc.
/// This returns a slice from a static buffer and therefore requires no allocations
pub fn sanitize(path: []const u8, buffer: []u8) []const u8 {
// var buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined;
if (path.len == 0) {
buffer[0] = '.';
return buffer[0..1][0..];
}
const rooted = path[0] == '/';
const len = path.len;
std.mem.copy(u8, buffer, path);
var out = BufferUtil.init(buffer, path);
var i: usize = 0;
var dot: usize = 0;
if (rooted) {
out.append('/');
i = 1;
dot = 1;
}
while (i < len) {
if (path[i] == '/') {
// empty path element
i += 1;
continue;
}
if (path[i] == '.' and (i + 1 == len or path[i + 1] == '/')) {
// . element
i += 1;
continue;
}
if (path[i] == '.' and path[i + 1] == '.' and (i + 2 == len or path[i + 2] == '/')) {
// .. element, remove '..' bits till last '/'
i += 2;
if (out.index > dot) {
out.index -= 1;
while (out.index > dot and out.char() != '/') : (out.index -= 1) {}
continue;
}
if (!rooted) {
if (out.index > 0) out.append('/');
out.append('.');
out.append('.');
dot = out.index;
continue;
}
}
if (rooted and out.index != 1 or !rooted and out.index != 0) out.append('/');
while (i < len and path[i] != '/') : (i += 1) {
out.append(path[i]);
}
}
if (out.index == 0) {
buffer[0] = '.';
return buffer[0..1][0..];
}
return out.result();
}
const BufferUtil = struct {
buffer: []u8,
index: usize,
path: []const u8,
fn init(buffer: []u8, path: []const u8) BufferUtil {
return .{ .buffer = buffer, .index = 0, .path = path };
}
fn append(self: *BufferUtil, c: u8) void {
std.debug.assert(self.index < self.buffer.len);
if (self.index < self.path.len and self.path[self.index] == c) {
self.index += 1;
return;
}
self.buffer[self.index] = c;
self.index += 1;
}
fn char(self: BufferUtil) u8 {
return self.buffer[self.index];
}
fn result(self: BufferUtil) []const u8 {
return self.buffer[0..self.index][0..];
}
};
/// Escapes a string by encoding symbols so it can be safely used inside an URL
fn escape(value: []const u8) []const u8 {
_ = value;
@compileError("TODO: Implement escape()");
}
/// Returns true if the given byte is heximal
fn isHex(c: u8) bool {
return switch (c) {
'0'...'9', 'a'...'f', 'A'...'F' => true,
else => false,
};
}
test "Basic raw query" {
const path = "/example?name=value";
const url: Url = Url.init(path);
try testing.expectEqualSlices(u8, "?name=value", url.raw_query);
}
test "Retrieve query parameters" {
const path = "/example?name=value";
const url: Url = Url.init(path);
var query_params = try url.queryParameters(testing.allocator);
defer query_params.deinit(testing.allocator);
try testing.expect(query_params.map.contains("name"));
try testing.expectEqualStrings("value", query_params.get("name") orelse " ");
}
test "Sanitize paths" {
const cases = .{
// Already clean
.{ .input = "", .expected = "." },
.{ .input = "abc", .expected = "abc" },
.{ .input = "abc/def", .expected = "abc/def" },
.{ .input = "a/b/c", .expected = "a/b/c" },
.{ .input = ".", .expected = "." },
.{ .input = "..", .expected = ".." },
.{ .input = "../..", .expected = "../.." },
.{ .input = "../../abc", .expected = "../../abc" },
.{ .input = "/abc", .expected = "/abc" },
.{ .input = "/", .expected = "/" },
// Remove trailing slash
.{ .input = "abc/", .expected = "abc" },
.{ .input = "abc/def/", .expected = "abc/def" },
.{ .input = "a/b/c/", .expected = "a/b/c" },
.{ .input = "./", .expected = "." },
.{ .input = "../", .expected = ".." },
.{ .input = "../../", .expected = "../.." },
.{ .input = "/abc/", .expected = "/abc" },
// Remove doubled slash
.{ .input = "abc//def//ghi", .expected = "abc/def/ghi" },
.{ .input = "//abc", .expected = "/abc" },
.{ .input = "///abc", .expected = "/abc" },
.{ .input = "//abc//", .expected = "/abc" },
.{ .input = "abc//", .expected = "abc" },
// Remove . elements
.{ .input = "abc/./def", .expected = "abc/def" },
.{ .input = "/./abc/def", .expected = "/abc/def" },
.{ .input = "abc/.", .expected = "abc" },
// Remove .. elements
.{ .input = "abc/def/ghi/../jkl", .expected = "abc/def/jkl" },
.{ .input = "abc/def/../ghi/../jkl", .expected = "abc/jkl" },
.{ .input = "abc/def/..", .expected = "abc" },
.{ .input = "abc/def/../..", .expected = "." },
.{ .input = "/abc/def/../..", .expected = "/" },
.{ .input = "abc/def/../../..", .expected = ".." },
.{ .input = "/abc/def/../../..", .expected = "/" },
.{ .input = "abc/def/../../../ghi/jkl/../../../mno", .expected = "../../mno" },
// Combinations
.{ .input = "abc/./../def", .expected = "def" },
.{ .input = "abc//./../def", .expected = "def" },
.{ .input = "abc/../../././../def", .expected = "../../def" },
};
inline for (cases) |case| {
var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined;
try testing.expectEqualStrings(case.expected, sanitize(case.input, &buf));
}
} | src/url.zig |
const std = @import("std");
const io = std.io;
pub fn length(sample_rate: u32, frame_length_msec: u8) u16 {
return @intCast(u16, sample_rate / 1000) * frame_length_msec;
}
pub fn shift(sample_rate: u32, frame_shift_msec: u8) u16 {
return @intCast(u16, sample_rate / 1000) * frame_shift_msec;
}
pub const FrameOpts = struct {
length: u16 = 256,
shift: u16 = 100,
};
pub fn FrameMaker(comptime ReaderType: type, comptime SampleType: type) type {
return struct {
const Self = @This();
pub const Error = ReaderType.Error || error{ IncorrectFrameSize, UnexpectedEOF, BufferTooShort };
pub const Reader = io.Reader(*Self, Error, readFn);
allocator: *std.mem.Allocator,
source: ReaderType,
opts: FrameOpts,
buf: []SampleType,
buf_read_idx: usize,
buf_write_idx: usize,
readfn_scratch: []SampleType,
frame_count: usize = 0,
pub fn init(allocator: *std.mem.Allocator, source: ReaderType, opts: FrameOpts) !Self {
var buf = try allocator.alloc(SampleType, opts.length);
// fill half the length with zeros for the first frame and advance the write index.
std.mem.set(SampleType, buf[0 .. opts.length / 2], 0);
const buf_write_idx = (opts.length) / 2; // ceil division in case length is odd
const buf_read_idx = 0;
var scratch = try allocator.alloc(SampleType, opts.length);
return Self{
.allocator = allocator,
.source = source,
.opts = opts,
.buf = buf,
.buf_read_idx = buf_read_idx,
.buf_write_idx = buf_write_idx,
.readfn_scratch = scratch,
};
}
pub fn deinit(self: *Self) void {
self.allocator.free(self.buf);
self.allocator.free(self.readfn_scratch);
}
// reads the next frame from source, padded with zeros at the end.
// returns true when frame is successfully read, false if source is
// fully read.
pub fn readFrame(self: *Self, dst: []SampleType) !bool {
if (dst.len != self.opts.length) return Error.IncorrectFrameSize;
defer self.frame_count += 1;
var n = if (self.frame_count == 0) (self.opts.length + 1) / 2 else self.opts.shift;
if (!try self.readBuf(n)) return false; // done
// copy self.buf into dst; this may have to be done in two steps
// depending on self.buf_read_idx
const buf_tail_length = self.buf.len - self.buf_read_idx;
if (buf_tail_length >= dst.len) {
std.mem.copy(SampleType, dst, self.buf[self.buf_read_idx .. self.buf_read_idx + dst.len]);
} else {
std.mem.copy(SampleType, dst[0..buf_tail_length], self.buf[self.buf_read_idx..]);
std.mem.copy(SampleType, dst[buf_tail_length..], self.buf[0 .. dst.len - buf_tail_length]);
}
self.buf_read_idx = (self.buf_read_idx + self.opts.shift) % self.buf.len;
return true;
}
/// reads exactly n items into buf. if source has eof, it pads with 0.
/// if at least one sample was read from source, returns true.
fn readBuf(self: *Self, n: usize) !bool {
var unread_count: usize = n;
var ret_val = false;
while (unread_count > 0) {
const buf_tail_length = self.buf.len - self.buf_write_idx;
const len = if (unread_count < buf_tail_length) unread_count else buf_tail_length;
const r = try self.readSamples(self.buf[self.buf_write_idx .. self.buf_write_idx + len]);
if (r > 0) {
ret_val = true;
self.buf_write_idx = (self.buf_write_idx + r) % self.buf.len;
unread_count -= r;
} else {
// source had eof, pad with zeros.
while (unread_count > 0) {
self.buf[self.buf_write_idx] = 0;
self.buf_write_idx = (self.buf_write_idx + 1) % self.buf.len;
unread_count -= 1;
}
}
}
return ret_val;
}
fn readSamples(self: *Self, dst: []SampleType) Error!usize {
if (comptime std.meta.trait.hasFn("readSamples")(ReaderType)) {
// read samples directly from the source, since it's a wave reader.
return try self.source.readSamples(dst);
}
// we are dealing with a raw reader, read samples by reinterpreting bytes.
var dst_u8 = std.mem.sliceAsBytes(dst);
const n = try self.source.readAll(dst_u8);
if (n % @sizeOf(SampleType) != 0) {
return Error.UnexpectedEOF;
}
return n / @sizeOf(SampleType);
}
/// implements the io.Reader interface. Provided buffer must be long
/// enough to hold an entire frame.
fn readFn(self: *Self, buf: []u8) Error!usize {
if (buf.len < self.opts.length * @sizeOf(SampleType)) {
return Error.BufferTooShort;
}
if (!try self.readFrame(self.readfn_scratch)) {
return 0;
}
const scratch_u8 = std.mem.sliceAsBytes(self.readfn_scratch);
std.mem.copy(u8, buf, scratch_u8);
return scratch_u8.len;
}
pub fn reader(self: *Self) Reader {
return .{ .context = self };
}
};
}
pub fn frameMaker(allocator: *std.mem.Allocator, reader: anytype, opts: FrameOpts) !FrameMaker(@TypeOf(reader), f32) {
return FrameMaker(@TypeOf(reader), f32).init(allocator, reader, opts);
}
test "framemaker src=io.Reader" {
var r = std.io.fixedBufferStream(@embedFile("testdata/test_pcm16.f32.raw")).reader();
var fm = try frameMaker(std.testing.allocator, r, .{});
defer fm.deinit();
var truthReader = std.io.fixedBufferStream(@embedFile("testdata/test_pcm16.f32.frames")).reader();
var got = try std.testing.allocator.alloc(f32, fm.opts.length);
defer std.testing.allocator.free(got);
var frame: usize = 0;
while (true) {
if (!try fm.readFrame(got)) {
try std.testing.expectError(error.EndOfStream, truthReader.readByte());
break;
}
for (got) |g, idx| {
const want = @bitCast(f32, try truthReader.readIntLittle(i32));
std.testing.expectApproxEqRel(want, g, 0.001) catch |err| {
std.debug.warn("failed at frame={d} index={d}", .{ frame, idx });
return err;
};
}
frame += 1;
}
}
test "framemaker src=WaveReader" {
const wav = @import("../wav/wav.zig");
var r = std.io.fixedBufferStream(@embedFile("testdata/test_pcm16.wav")).reader();
var wavr = wav.waveReaderFloat32(r);
var fm = try frameMaker(std.testing.allocator, wavr, .{});
defer fm.deinit();
var truthReader = std.io.fixedBufferStream(@embedFile("testdata/test_pcm16.f32.frames")).reader();
var got = try std.testing.allocator.alloc(f32, fm.opts.length);
defer std.testing.allocator.free(got);
var frame: usize = 0;
while (true) {
if (!try fm.readFrame(got)) {
try std.testing.expectError(error.EndOfStream, truthReader.readByte());
break;
}
for (got) |g, idx| {
const want = @bitCast(f32, try truthReader.readIntLittle(i32));
std.testing.expectApproxEqRel(want, g, 0.001) catch |err| {
std.debug.warn("failed at frame={d} index={d}", .{ frame, idx });
return err;
};
}
frame += 1;
}
}
test "framemaker src=WaveReader as io.Reader" {
const wav = @import("../wav/wav.zig");
var r = std.io.fixedBufferStream(@embedFile("testdata/test_pcm16.wav")).reader();
var wavr = wav.waveReaderFloat32(r).reader();
var fm = try frameMaker(std.testing.allocator, wavr, .{});
defer fm.deinit();
const got = try fm.reader().readAllAlloc(std.testing.allocator, std.math.maxInt(usize));
defer std.testing.allocator.free(got);
var truth = std.io.fixedBufferStream(@embedFile("testdata/test_pcm16.f32.frames")).reader();
const want = try truth.readAllAlloc(std.testing.allocator, std.math.maxInt(usize));
defer std.testing.allocator.free(want);
try std.testing.expectEqualSlices(u8, want, got);
} | src/dsp/frame.zig |
const std = @import("std");
const testing = std.testing;
const zupnp = @import("zupnp");
const SUT = struct {
const dest = "/endpoint";
const Endpoint = struct {
last_message: []const u8,
pub fn prepare(self: *Endpoint, _: void) !void {
self.last_message = try testing.allocator.alloc(u8, 0);
}
pub fn deinit(self: *Endpoint) void {
testing.allocator.free(self.last_message);
}
pub fn post(self: *Endpoint, request: *const zupnp.web.ServerPostRequest) bool {
testing.allocator.free(self.last_message);
self.last_message = testing.allocator.dupe(u8, request.contents) catch |e| @panic(@errorName(e));
return true;
}
};
lib: zupnp.ZUPnP = undefined,
endpoint: *Endpoint = undefined,
url: [:0]const u8 = undefined,
fn init(self: *SUT) !void {
self.lib = try zupnp.ZUPnP.init(testing.allocator, .{});
self.endpoint = try self.lib.server.createEndpoint(Endpoint, {}, dest);
try self.lib.server.start();
self.url = try std.fmt.allocPrintZ(testing.allocator, "{s}{s}", .{self.lib.server.base_url, dest});
}
fn deinit(self: *SUT) void {
testing.allocator.free(self.url);
self.lib.deinit();
}
};
test "POST request stores contents and returns code 200 with no contents" {
var sut = SUT {};
try sut.init();
defer sut.deinit();
const contents = "Hello world!";
var response = try zupnp.web.request(.POST, sut.url, .{ .contents = contents });
try testing.expectEqual(@as(c_int, 200), response.http_status);
try testing.expectEqualStrings(contents, sut.endpoint.last_message);
}
test "unhandled requests return server error codes" {
var sut = SUT {};
try sut.init();
defer sut.deinit();
inline for (.{
.{.GET, 404},
.{.HEAD, 404},
.{.PUT, 501},
.{.DELETE, 500}
}) |requestAndCode| {
var response = try zupnp.web.request(requestAndCode.@"0", sut.url, .{});
try testing.expectEqual(@as(c_int, requestAndCode.@"1"), response.http_status);
}
} | test/web/test_post_requests.zig |
const builtin = @import("builtin");
const std = @import("std");
const day24_compiled = @import("day24_compiled.zig");
const input = @import("input.zig");
pub fn run(stdout: anytype) anyerror!void {
if (builtin.mode == .Debug) {
var program = std.BoundedArray(Op, 252).init(0) catch unreachable;
{
var input_ = try input.readFile("inputs/day24");
defer input_.deinit();
var input_i: usize = 0;
while (try input_.next()) |line| {
try program.append(try Op.init(line, &input_i));
}
}
simplify(&program);
const file = try std.fs.cwd().createFile("src/day24_compiled.zig", .{});
defer file.close();
const writer = file.writer();
try writer.print("const std = @import(\"std\");\n\n", .{});
try writer.print("const Digit = std.math.IntFittingRange(0, 9);\n\n", .{});
try compileProgram(program.constSlice(), writer);
try writer.print("\n", .{});
try compileProgram2(program.constSlice(), writer);
}
{
const result = part1();
try stdout.print("24a: {}\n", .{ result });
std.debug.assert(result == 93959993429899);
}
{
const result = part2();
try stdout.print("24b: {}\n", .{ result });
std.debug.assert(result == 11815671117121);
}
}
const Digit = std.math.IntFittingRange(0, 9);
const Answer = std.math.IntFittingRange(11111111111111, 99999999999999);
fn part1() Answer {
var result_digits: [14]Digit = undefined;
if (builtin.mode == .Debug) {
result_digits = [_]Digit { 9, 3, 9, 5, 9, 9, 9, 3, 4, 2, 9, 8, 9, 9 };
const z = day24_compiled.evaluate(result_digits);
std.debug.assert(z == 0);
}
else {
result_digits = day24_compiled.evaluate2(.{ 9, 8, 7, 6, 5, 4, 3, 2, 1 }) catch unreachable;
}
var result: Answer = 0;
for (result_digits) |result_digit| {
result = result * 10 + result_digit;
}
return result;
}
fn part2() Answer {
var result_digits: [14]Digit = undefined;
if (builtin.mode == .Debug) {
result_digits = [_]Digit { 1, 1, 8, 1, 5, 6, 7, 1, 1, 1, 7, 1, 2, 1 };
const z = day24_compiled.evaluate(result_digits);
std.debug.assert(z == 0);
}
else {
result_digits = day24_compiled.evaluate2(.{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }) catch unreachable;
}
var result: Answer = 0;
for (result_digits) |result_digit| {
result = result * 10 + result_digit;
}
return result;
}
const Op = struct {
code: OpCode,
lhs: Reg,
rhs: Rhs,
fn init(line: []const u8, input_i: *usize) !@This() {
var parts = std.mem.tokenize(u8, line, " ");
const op_s = parts.next() orelse return error.InvalidInput;
const lhs_s = parts.next() orelse return error.InvalidInput;
const lhs = try Reg.init(lhs_s);
if (std.mem.eql(u8, op_s, "inp")) {
const result = Op {
.code = .set,
.lhs = lhs,
.rhs = .{ .inp = input_i.* },
};
input_i.* += 1;
return result;
}
else {
const code = try OpCode.init(op_s);
const rhs_s = parts.next() orelse return error.InvalidInput;
const rhs = try Rhs.init(rhs_s);
return Op {
.code = code,
.lhs = lhs,
.rhs = rhs,
};
}
}
};
const OpCode = enum {
add,
mul,
div,
mod,
eql,
neq,
set,
fn init(op_s: []const u8) !@This() {
if (std.mem.eql(u8, op_s, "add")) {
return OpCode.add;
}
else if (std.mem.eql(u8, op_s, "mul")) {
return OpCode.mul;
}
else if (std.mem.eql(u8, op_s, "div")) {
return OpCode.div;
}
else if (std.mem.eql(u8, op_s, "mod")) {
return OpCode.mod;
}
else if (std.mem.eql(u8, op_s, "eql")) {
return OpCode.eql;
}
else {
return error.InvalidInput;
}
}
};
const OpInp = struct {
lhs: Reg,
rhs: usize,
};
const OpBin = struct {
lhs: Reg,
rhs: Rhs,
};
const Reg = enum {
w,
x,
y,
z,
fn init(arg: []const u8) !@This() {
if (arg.len != 1) {
return error.InvalidInput;
}
return switch (arg[0]) {
'w' => .w,
'x' => .x,
'y' => .y,
'z' => .z,
else => error.InvalidInput,
};
}
};
const Rhs = union (enum) {
reg: Reg,
inp: usize,
constant: i64,
fn init(arg: []const u8) !@This() {
return
if (Reg.init(arg) catch null) |reg| .{ .reg = reg }
else .{ .constant = try std.fmt.parseInt(i64, arg, 10) };
}
};
const Value = union (enum) {
constant: i64,
inp: usize,
unknown: ValueRange,
fn asConstant(self: @This()) ?i64 {
return switch (self) {
.constant => |constant| constant,
else => null,
};
}
fn range(self: @This()) ValueRange {
return switch (self) {
.constant => |constant| .{ .min = constant, .max = constant },
.inp => .{ .min = 1, .max = 9 },
.unknown => |unknown| unknown,
};
}
};
const ValueRange = struct {
min: i64,
max: i64,
};
fn evalValue(variables: *const [4]Value, rhs: Rhs) Value {
return switch (rhs) {
.reg => |reg| switch (reg) {
.w => variables[0],
.x => variables[1],
.y => variables[2],
.z => variables[3],
},
.inp => |inp| .{ .inp = inp },
.constant => |constant| .{ .constant = constant },
};
}
fn setValue(variables: *[4]Value, reg: Reg, value: Value) void {
switch (reg) {
.w => variables[0] = value,
.x => variables[1] = value,
.y => variables[2] = value,
.z => variables[3] = value,
}
}
fn simplify(program: *std.BoundedArray(Op, 252)) void {
loop: while (true) {
var variables = [_]Value { .{ .constant = 0 } } ** 4;
for (program.slice()) |*op, i| {
const evaled_rhs = evalValue(&variables, op.rhs);
{
const new_rhs = switch (evaled_rhs) {
.constant => |constant_rhs| switch (op.rhs) {
.constant => |constant|
if (constant != constant_rhs) Rhs { .constant = constant_rhs }
else null,
else => Rhs { .constant = constant_rhs },
},
.inp => |inp_rhs| switch (op.rhs) {
.inp => |inp|
if (inp != inp_rhs) Rhs { .inp = inp_rhs }
else null,
else => Rhs { .inp = inp_rhs },
},
.unknown => null,
};
if (new_rhs) |new_rhs_| {
op.* = .{
.code = op.code,
.lhs = op.lhs,
.rhs = new_rhs_,
};
continue :loop;
}
}
const evaled_rhs_range = evaled_rhs.range();
const evaled_lhs = evalValue(&variables, .{ .reg = op.lhs });
const evaled_lhs_range = evaled_lhs.range();
var new_min: ?i64 = null;
var new_max: ?i64 = null;
switch (op.code) {
.add => {
if (evaled_lhs.asConstant()) |constant_lhs| {
if (constant_lhs == 0) {
// a = 0 => add a b -> set a b
op.* = .{
.code = .set,
.lhs = op.lhs,
.rhs = op.rhs,
};
continue :loop;
}
}
if (evaled_rhs.asConstant()) |constant_rhs| {
if (constant_rhs == 0) {
// add a 0 -> X
_ = program.orderedRemove(i);
continue :loop;
}
if (evaled_lhs.asConstant()) |constant_lhs| {
// a = M => add a N -> set a (M + N)
op.* = .{
.code = .set,
.lhs = op.lhs,
.rhs = .{ .constant = constant_lhs + constant_rhs },
};
continue :loop;
}
}
new_min = evaled_lhs_range.min +| evaled_rhs_range.min;
new_max = evaled_lhs_range.max +| evaled_rhs_range.max;
},
.mul => {
if (evaled_lhs.asConstant()) |constant_lhs| {
if (constant_lhs == 0) {
// a = 0 => mul a b -> X
_ = program.orderedRemove(i);
continue :loop;
}
if (constant_lhs == 1) {
// a = 1 => mul a b -> set a b
op.* = .{
.code = .set,
.lhs = op.lhs,
.rhs = op.rhs,
};
continue :loop;
}
}
if (evaled_rhs.asConstant()) |constant_rhs| {
if (constant_rhs == 0) {
// mul a 0 -> set a 0
op.* = .{
.code = .set,
.lhs = op.lhs,
.rhs = .{ .constant = 0 },
};
continue :loop;
}
if (constant_rhs == 1) {
// mul a 1 -> X
_ = program.orderedRemove(i);
continue :loop;
}
if (evaled_lhs.asConstant()) |constant_lhs| {
// a = M => mul a N -> set a (M * N)
op.* = .{
.code = .set,
.lhs = op.lhs,
.rhs = .{ .constant = constant_lhs * constant_rhs },
};
continue :loop;
}
}
new_min =
std.math.min(
std.math.min(evaled_lhs_range.min *| evaled_rhs_range.min, evaled_lhs_range.max *| evaled_rhs_range.max),
std.math.min(evaled_lhs_range.min *| evaled_rhs_range.max, evaled_lhs_range.max *| evaled_rhs_range.min),
);
new_max =
std.math.max(
std.math.max(evaled_lhs_range.min *| evaled_rhs_range.min, evaled_lhs_range.max *| evaled_rhs_range.max),
std.math.max(evaled_lhs_range.min *| evaled_rhs_range.max, evaled_lhs_range.max *| evaled_rhs_range.min),
);
},
.div => {
if (evaled_lhs.asConstant()) |constant_lhs| {
if (constant_lhs == 0) {
// a = 0 => div a N -> X
_ = program.orderedRemove(i);
continue :loop;
}
}
if (evaled_rhs.asConstant()) |constant_rhs| {
if (constant_rhs == 1) {
// div a 1 -> X
_ = program.orderedRemove(i);
continue :loop;
}
if (evaled_lhs.asConstant()) |constant_lhs| {
// a = M => div a N -> set a (M / N)
op.* = .{
.code = .set,
.lhs = op.lhs,
.rhs = .{ .constant = @divTrunc(constant_lhs, constant_rhs) },
};
continue :loop;
}
}
new_min =
std.math.min(
std.math.min(@divTrunc(evaled_lhs_range.min, evaled_rhs_range.min), @divTrunc(evaled_lhs_range.max, evaled_rhs_range.max)),
std.math.min(@divTrunc(evaled_lhs_range.min, evaled_rhs_range.max), @divTrunc(evaled_lhs_range.max, evaled_rhs_range.min)),
);
new_max =
std.math.max(
std.math.max(@divTrunc(evaled_lhs_range.min, evaled_rhs_range.min), @divTrunc(evaled_lhs_range.max, evaled_rhs_range.max)),
std.math.max(@divTrunc(evaled_lhs_range.min, evaled_rhs_range.max), @divTrunc(evaled_lhs_range.max, evaled_rhs_range.min)),
);
},
.mod => {
if (evaled_lhs.asConstant()) |constant_lhs| {
if (constant_lhs == 0) {
// a = 0 => mod a N -> X
_ = program.orderedRemove(i);
continue :loop;
}
}
if (evaled_rhs.asConstant()) |constant_rhs| {
std.debug.assert(constant_rhs > 0);
if (evaled_lhs.asConstant()) |constant_lhs| {
// a = M => mod a N -> set a (M % N)
op.* = .{
.code = .set,
.lhs = op.lhs,
.rhs = .{ .constant = @mod(constant_lhs, constant_rhs) },
};
continue :loop;
}
if (evaled_lhs_range.min >= 0 and evaled_lhs_range.min < constant_rhs and evaled_lhs_range.max >= 0 and evaled_lhs_range.max < constant_rhs) {
new_min = evaled_lhs_range.min;
new_max = evaled_lhs_range.max;
}
else {
new_min = 0;
new_max = constant_rhs - 1;
}
}
},
.eql => {
if (i < program.len) {
const next_op = program.constSlice()[i + 1];
switch (next_op.code) {
.eql => {
if (evalValue(&variables, next_op.rhs).asConstant()) |constant_rhs| {
if (constant_rhs == 0) {
// eql a b; eql a 0 -> neq a b
op.* = .{
.code = .neq,
.lhs = op.lhs,
.rhs = op.rhs,
};
_ = program.orderedRemove(i + 1);
continue :loop;
}
}
},
else => {},
}
}
if (evaled_lhs_range.max < evaled_rhs_range.min or evaled_rhs_range.max < evaled_lhs_range.min) {
// a and b are disjoint => eql a b -> set a 0
op.* = .{
.code = .set,
.lhs = op.lhs,
.rhs = .{ .constant = 0 },
};
continue :loop;
}
new_min = 0;
new_max = 1;
},
.neq => {
if (evaled_lhs_range.max < evaled_rhs_range.min or evaled_rhs_range.max < evaled_lhs_range.min) {
// a and b are disjoint => neq a b -> set a 1
op.* = .{
.code = .set,
.lhs = op.lhs,
.rhs = .{ .constant = 1 },
};
continue :loop;
}
new_min = 0;
new_max = 1;
},
.set => {
if (i > 0) {
// ... does not use a => a = b; ...; set a N -> set a N
var j = i - 1;
while (true) : (j -= 1) {
const prev_op = program.constSlice()[j];
if (prev_op.lhs == op.lhs) {
_ = program.orderedRemove(j);
continue :loop;
}
switch (prev_op.rhs) {
.reg => |reg| {
if (reg == op.lhs) {
break;
}
},
else => {},
}
if (j == 0) {
break;
}
}
}
// ... does not use a => set a N; ...; $ -> ...; $
for (program.constSlice()[(i + 1)..]) |next_op| {
switch (next_op.rhs) {
.reg => |reg| if (reg == op.lhs) {
break;
},
else => {},
}
}
else {
_ = program.orderedRemove(i);
continue :loop;
}
if (evaled_rhs.asConstant()) |constant_rhs| {
if (evaled_lhs.asConstant()) |constant_lhs| {
// a = N => set a N -> X
if (constant_lhs == constant_rhs) {
_ = program.orderedRemove(i);
continue :loop;
}
}
}
},
}
if (op.code == .set) {
setValue(&variables, op.lhs, evaled_rhs);
}
else {
const new_min_ = new_min.?;
const new_max_ = new_max.?;
std.debug.assert(new_min_ < new_max_);
setValue(&variables, op.lhs, .{ .unknown = .{ .min = new_min_, .max = new_max_ } });
}
}
break;
}
}
fn compileProgram(program: []const Op, writer: anytype) !void {
try writer.print(
\\pub fn evaluate(inputs: [14]Digit) i64 {{
\\ var w: i64 = 0;
\\ _ = w;
\\ var x: i64 = 0;
\\ _ = x;
\\ var y: i64 = 0;
\\ _ = y;
\\ var z: i64 = 0;
\\ _ = z;
\\
\\
,
.{},
);
for (program) |op| {
try writer.print(" ", .{});
try printOp(op, writer);
}
try writer.print(
\\
\\ return z;
\\}}
\\
,
.{},
);
}
fn printOp(op: Op, writer: anytype) !void {
try printReg(op.lhs, writer);
switch (op.code) {
.add => {
try writer.print(" += ", .{});
try printRhs(op.rhs, writer);
},
.mul => {
try writer.print(" *= ", .{});
try printRhs(op.rhs, writer);
},
.div => {
try writer.print(" = @divTrunc(", .{});
try printReg(op.lhs, writer);
try writer.print(", ", .{});
try printRhs(op.rhs, writer);
try writer.print(")", .{});
},
.mod => {
try writer.print(" = @mod(", .{});
try printReg(op.lhs, writer);
try writer.print(", ", .{});
try printRhs(op.rhs, writer);
try writer.print(")", .{});
},
.eql => {
try writer.print(" = @boolToInt(", .{});
try printReg(op.lhs, writer);
try writer.print(" == ", .{});
try printRhs(op.rhs, writer);
try writer.print(")", .{});
},
.neq => {
try writer.print(" = @boolToInt(", .{});
try printReg(op.lhs, writer);
try writer.print(" != ", .{});
try printRhs(op.rhs, writer);
try writer.print(")", .{});
},
.set => {
try writer.print(" = ", .{});
try printRhs(op.rhs, writer);
},
}
try writer.print(";\n", .{});
}
fn printReg(reg: Reg, writer: anytype) !void {
switch (reg) {
.w => try writer.print("w", .{}),
.x => try writer.print("x", .{}),
.y => try writer.print("y", .{}),
.z => try writer.print("z", .{}),
}
}
fn printRhs(rhs: Rhs, writer: anytype) !void {
switch (rhs) {
.reg => |reg| try printReg(reg, writer),
.inp => |inp| try printInp(inp, writer),
.constant => |constant| try writer.print("{}", .{ constant }),
}
}
fn printInp(inp: usize, writer: anytype) !void {
try writer.print("inputs[{}]", .{ inp });
}
fn compileProgram2(program: []const Op, writer: anytype) !void {
var depths = [_]usize { 0 } ** 4;
try writer.print(
\\pub fn evaluate2(digits: [9]Digit) [14]Digit {{
\\
,
.{},
);
var next_inp: usize = 0;
for (program) |op| {
try printOp2(op, writer, &depths, &next_inp);
}
try writer.print("\n", .{});
try indent(next_inp, writer);
try writer.print("if (", .{});
try printReg2(.z, writer, &depths, .input);
try writer.print(" == 0) {{\n", .{});
try indent(next_inp, writer);
try writer.print(" return [_]Digit {{ d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13 }};\n", .{});
try indent(next_inp, writer);
try writer.print("}}\n", .{});
try indent(next_inp, writer);
try writer.print("else if (d5 == 1 and d6 == 1 and d7 == 1 and d8 == 1 and d9 == 1 and d10 == 1 and d11 == 1 and d12 == 1 and d13 == 1) {{\n", .{});
try indent(next_inp, writer);
try writer.print(" const inputs = [_]Digit {{ d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13 }};\n", .{});
try indent(next_inp, writer);
try writer.print(" std.debug.print(\"??? {{any}}\\n\", .{{ inputs }});\n", .{});
try indent(next_inp, writer);
try writer.print("}}\n", .{});
while (next_inp >= 1) {
next_inp -= 1;
try indent(next_inp, writer);
try writer.print("}}\n", .{});
}
try indent(next_inp, writer);
try writer.print("else unreachable;\n}}\n", .{});
}
fn printOp2(op: Op, writer: anytype, depths: *[4]usize, next_inp: *usize) !void {
try indent(next_inp.*, writer);
switch (op.code) {
.add => {
var new_depths = depths.*;
try writer.print("const ", .{});
try printReg2(op.lhs, writer, &new_depths, .output);
try writer.print(" = ", .{});
try printReg2(op.lhs, writer, depths, .input);
try writer.print(" + ", .{});
try printRhs2(op.rhs, writer, depths);
try writer.print(";\n", .{});
depths.* = new_depths;
},
.mul => {
var new_depths = depths.*;
try writer.print("const ", .{});
try printReg2(op.lhs, writer, &new_depths, .output);
try writer.print(" = ", .{});
try printReg2(op.lhs, writer, depths, .input);
try writer.print(" * ", .{});
try printRhs2(op.rhs, writer, depths);
try writer.print(";\n", .{});
depths.* = new_depths;
},
.div => {
var new_depths = depths.*;
try writer.print("const ", .{});
try printReg2(op.lhs, writer, &new_depths, .output);
try writer.print(" = @divTrunc(", .{});
try printReg2(op.lhs, writer, depths, .input);
try writer.print(", ", .{});
try printRhs2(op.rhs, writer, depths);
try writer.print(");\n", .{});
depths.* = new_depths;
},
.mod => {
var new_depths = depths.*;
try writer.print("const ", .{});
try printReg2(op.lhs, writer, &new_depths, .output);
try writer.print(" = @mod(", .{});
try printReg2(op.lhs, writer, depths, .input);
try writer.print(", ", .{});
try printRhs2(op.rhs, writer, depths);
try writer.print(");\n", .{});
depths.* = new_depths;
},
.eql => {
var new_depths = depths.*;
try writer.print("const ", .{});
try printReg2(op.lhs, writer, &new_depths, .output);
try writer.print(": i64 = @boolToInt(", .{});
try printReg2(op.lhs, writer, depths, .input);
try writer.print(" == ", .{});
try printRhs2(op.rhs, writer, depths);
try writer.print(");\n", .{});
depths.* = new_depths;
},
.neq => switch (op.rhs) {
.inp => |inp| {
if (inp == next_inp.*) {
try writer.print("for (digits) |", .{});
try printInp2(inp, writer);
try writer.print("| {{\n", .{});
try indent(next_inp.*, writer);
try writer.print(" ", .{});
next_inp.* += 1;
}
var new_depths = depths.*;
try writer.print("const ", .{});
try printReg2(op.lhs, writer, &new_depths, .output);
try writer.print(": i64 = @boolToInt(", .{});
try printReg2(op.lhs, writer, depths, .input);
try writer.print(" != ", .{});
try printRhs2(op.rhs, writer, depths);
try writer.print(");\n", .{});
depths.* = new_depths;
},
else => {
var new_depths = depths.*;
try writer.print("const ", .{});
try printReg2(op.lhs, writer, &new_depths, .output);
try writer.print(": i64 = if (", .{});
try printReg2(op.lhs, writer, depths, .input);
try writer.print(" == ", .{});
try printRhs2(op.rhs, writer, depths);
try writer.print(") 0 else 1;\n", .{});
depths.* = new_depths;
},
},
.set => switch (op.rhs) {
.inp => |inp| {
if (inp == next_inp.*) {
try writer.print("for (digits) |", .{});
try printInp2(inp, writer);
try writer.print("| {{\n", .{});
try indent(next_inp.*, writer);
try writer.print(" ", .{});
next_inp.* += 1;
}
var new_depths = depths.*;
try writer.print("const ", .{});
try printReg2(op.lhs, writer, &new_depths, .output);
try writer.print(": i64 = ", .{});
try printRhs2(op.rhs, writer, depths);
try writer.print(";\n", .{});
depths.* = new_depths;
},
else => {
var new_depths = depths.*;
try writer.print("const ", .{});
try printReg2(op.lhs, writer, &new_depths, .output);
try writer.print(" = ", .{});
try printRhs2(op.rhs, writer, depths);
try writer.print(";\n", .{});
depths.* = new_depths;
},
},
}
}
const PrintReg2Options = enum {
input,
output,
};
fn printReg2(reg: Reg, writer: anytype, depths: *[4]usize, options: PrintReg2Options) !void {
const current_depth = switch (reg) {
.w => &depths[0],
.x => &depths[1],
.y => &depths[2],
.z => &depths[3],
};
switch (options) {
.input => {},
.output => {
current_depth.* += 1;
},
}
switch (reg) {
.w => try writer.print("w{}", .{ current_depth.* - 1 }),
.x => try writer.print("x{}", .{ current_depth.* - 1 }),
.y => try writer.print("y{}", .{ current_depth.* - 1 }),
.z => try writer.print("z{}", .{ current_depth.* - 1 }),
}
}
fn printRhs2(rhs: Rhs, writer: anytype, depths: *[4]usize) !void {
switch (rhs) {
.reg => |reg| try printReg2(reg, writer, depths, .input),
.inp => |inp| try printInp2(inp, writer),
.constant => |constant| try writer.print("{}", .{ constant }),
}
}
fn printInp2(inp: usize, writer: anytype) !void {
try writer.print("d{}", .{ inp });
}
fn indent(next_inp: usize, writer: anytype) !void {
var i: usize = 0;
while (i <= next_inp) : (i += 1) {
try writer.print(" ", .{});
}
} | src/day24.zig |
const std = @import("std");
const assert = std.debug.assert;
const panic = std.debug.panic;
const testing = std.testing;
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const ArenaAllocator = std.heap.ArenaAllocator;
const AutoHashMap = std.AutoHashMap;
/// Handle is like an uniq Id, which is used to retrieve a specific datum
/// stored in the Entities data-structure.
pub fn Handle(comptime T: anytype) type {
return struct {
id: i32,
pub fn new(id: i32) @This() {
return .{ .id = id };
}
};
}
///
/// This entities data-structure had to meet strict requirements:
///
/// 1) Refering data chunck as only one integer because it's much
/// easy to serialize it.
///
/// 2) Shouldn't suffer from ABA problems.
///
/// 3) Being able to hardcode ids without further referencing problems,
/// which is often the case when items are coming from serialized data).
///
pub fn Entities(comptime T: anytype) type {
return struct {
/// Data stored
data: ArrayList(T),
/// Handle composed by the generational id as `key` and
/// data arraylist's index as `value`.
handles: AutoHashMap(i32, usize),
/// Array of all free handles, stored generational id
/// in it.
free: ArrayList(i32),
/// keeping track of the last id incremented.
last_id: i32 = 0,
/// All postpone ids goes here.
_prealloc: AutoHashMap(i32, void),
/// Arena allocator, used to free all heap allocated data once.
_arena: *ArenaAllocator,
const Self = @This();
pub fn init(allocator: *Allocator) Self {
var entities: Self = undefined;
entities.last_id = 0;
entities._arena = allocator.create(ArenaAllocator) catch |e| {
panic("Crash :: {}.\n", .{e});
};
entities._arena.* = ArenaAllocator.init(allocator);
entities._prealloc = AutoHashMap(i32, void).init(&entities._arena.allocator);
entities.data = ArrayList(T).init(&entities._arena.allocator);
entities.handles = AutoHashMap(i32, usize).init(&entities._arena.allocator);
entities.free = ArrayList(i32).init(&entities._arena.allocator);
return entities;
}
pub fn append(self: *Self, item: T) !Handle(T) {
if (self.free.items.len == 0) {
self.increment_id(null);
}
return try self.add_chunk(item, self.last_id);
}
/// Store new item by using the given `id`.
/// This method also checked with there are given `id` isn't
/// alreayd used.
pub fn append_hard(self: *Self, item: T, id: i32) !Handle(T) {
if (self.handles.contains(id)) {
panic("Given id '{}' is already in use.\n", .{id});
}
try self._prealloc.put(id, {});
return try self.add_chunk(item, id);
}
fn add_chunk(self: *Self, item: T, id: i32) !Handle(T) {
var handle: Handle(T) = .{ .id = id };
const index = self.data.items.len;
if (self.free.items.len > 0) {
const data_index = self.handles.get(self.free.pop()).?;
self.data.items[data_index] = item;
} else {
try self.handles.putNoClobber(id, index);
try self.data.append(item);
}
return handle;
}
pub fn get(self: *const Self, handle: Handle(T)) *T {
if (self.is_valid(handle)) {
const data_index = self.handles.get(handle.id).?;
return &self.data.items[data_index];
} else {
panic("Given handle not valid: '{}'\n", .{handle});
}
}
fn increment_id(self: *Self, next: ?i32) void {
const next_version = if (next) |v| v else self.last_id + 1;
if (self._prealloc.contains(next_version)) {
increment_id(self, next_version + 1);
} else {
self.last_id = next_version;
}
}
pub fn iterate(self: *Self) EntitiesIterator {
return .{ .entities = self, .index = 0 };
}
pub fn get_count(self: *Self) i32 {
var count: i32 = 0;
var it = self.iterate();
while (it.next()) |_| count += 1;
return count;
}
pub fn remove(self: *Self, handle: Handle(T)) void {
if (self.is_valid(handle)) {
increment_id(self, null);
const old_entry = self.handles.getEntry(handle.id).?;
self.handles.putNoClobber(self.last_id, old_entry.value_ptr.*) catch unreachable;
_ = self.handles.remove(old_entry.key_ptr.*);
self.free.append(self.last_id) catch |e| {
panic("Crash while removing entity: '{}'\n", .{e});
};
}
}
pub fn is_valid(self: *const Self, handle: Handle(T)) bool {
var is_handle_valid = false;
if (self.handles.contains(handle.id)) {
is_handle_valid = true;
for (self.free.items) |item| {
if (item == handle.id) is_handle_valid = false;
}
}
return is_handle_valid;
}
pub fn clear(self: *Self) void {
var it = self.handles.iterator();
while (it.next()) |entry| {
const key = entry.key_ptr.*;
var already_freed = false;
for (self.free.items) |free_idx| {
if (free_idx == key) already_freed = true;
}
if (!already_freed) self.remove(.{ .id = key });
}
}
pub fn deinit(self: *Self) void {
const allocator = self._arena.child_allocator;
self._arena.deinit();
allocator.destroy(self._arena);
}
pub const EntitiesIterator = struct {
entities: *Self,
index: u32,
pub fn next(it: *EntitiesIterator) ?*T {
const handles = it.entities.handles;
var iter = it.entities.handles.iterator();
iter.index = it.index;
while (iter.next()) |entry| {
var is_freed = false;
it.index = iter.index;
for (it.entities.free.items) |idx| {
if (entry.key_ptr.* == idx) {
is_freed = true;
break;
}
}
if (!is_freed) {
return &it.entities.data.items[entry.value_ptr.*];
}
}
return null;
}
};
};
}
test "entities.init" {
var entities = Entities(i32).init(testing.allocator);
defer entities.deinit();
try testing.expectEqual(entities.is_valid(Handle(i32).new(0)), false);
try testing.expectEqual(entities.handles.unmanaged.size, 0);
try testing.expectEqual(entities.data.items.len, 0);
try testing.expectEqual(entities.free.items.len, 0);
try testing.expectEqual(entities.last_id, 0);
}
test "entities.append" {
var entities = Entities(i32).init(testing.allocator);
defer entities.deinit();
const handle_1 = try entities.append(11);
const handle_2 = try entities.append(22);
const handle_3 = try entities.append(33);
try testing.expectEqual(entities.handles.get(1).? == 0, true);
try testing.expectEqual(entities.handles.get(2).? == 1, true);
try testing.expectEqual(entities.handles.get(3).? == 2, true);
}
test "entities.append_hard" {
var entities = Entities(i32).init(testing.allocator);
defer entities.deinit();
const handle_1 = try entities.append_hard(0, 1);
const handle_2 = try entities.append_hard(0, 2);
const handle_3 = try entities.append_hard(0, 55);
const handle_4 = try entities.append(5);
try testing.expectEqual(entities.is_valid(handle_1), true);
try testing.expectEqual(entities.is_valid(handle_2), true);
try testing.expectEqual(entities.is_valid(handle_3), true);
try testing.expectEqual(entities.is_valid(handle_4), true);
try testing.expectEqual(handle_1.id == 1, true);
try testing.expectEqual(handle_2.id == 2, true);
try testing.expectEqual(handle_3.id == 55, true);
try testing.expectEqual(handle_4.id == 3, true);
}
test "entities.get" {
var entities = Entities(f32).init(testing.allocator);
defer entities.deinit();
const handle_1 = try entities.append(11.0);
const handle_2 = try entities.append(22.0);
const handle_3 = try entities.append(33.0);
try testing.expectEqual(entities.get(handle_1).*, 11.0);
try testing.expectEqual(entities.get(handle_2).*, 22.0);
try testing.expectEqual(entities.get(handle_3).*, 33.0);
}
test "entities.remove" {
var entities = Entities(i32).init(testing.allocator);
defer entities.deinit();
const handle_1 = try entities.append(11);
const handle_2 = try entities.append(22);
const handle_3 = try entities.append(33);
entities.remove(handle_2);
try testing.expectEqual(entities.free.items.len, 1);
try testing.expectEqual(entities.is_valid(handle_2), false);
const handle_4 = try entities.append(44);
try testing.expectEqual(handle_2.id == handle_4.id, false);
try testing.expectEqual(entities.is_valid(handle_2), false);
try testing.expectEqual(entities.free.items.len, 0);
try testing.expectEqual(entities.get(handle_4).*, 44);
}
test "entities.clear" {
var entities = Entities(i32).init(testing.allocator);
defer entities.deinit();
const handle_1 = try entities.append(11);
const handle_2 = try entities.append(22);
const handle_3 = try entities.append(33);
try testing.expectEqual(entities.is_valid(handle_1), true);
try testing.expectEqual(entities.is_valid(handle_2), true);
try testing.expectEqual(entities.is_valid(handle_3), true);
entities.clear();
try testing.expectEqual(entities.is_valid(handle_1), false);
try testing.expectEqual(entities.is_valid(handle_2), false);
try testing.expectEqual(entities.is_valid(handle_3), false);
}
test "entities.interator" {
var entities = Entities(f32).init(testing.allocator);
defer entities.deinit();
const handle_1 = try entities.append(10.0);
const handle_2 = try entities.append(20.0);
const handle_3 = try entities.append(30.0);
entities.remove(handle_2);
var it = entities.iterate();
var count: f32 = 0;
while (it.next()) |value| : (count += value.*) {
const expectedValue: f32 = if (count == 0) 10.0 else 30.0;
try testing.expectEqual(value.*, expectedValue);
}
try testing.expectEqual(count, 40);
} | src/main.zig |
const assert = std.debug.assert;
const std = @import("std");
const testing = std.testing;
const zigimg = @import("zigimg");
const image = zigimg.image;
const Image = image.Image;
const color = zigimg.color;
const PixelFormat = zigimg.PixelFormat;
const helpers = @import("helpers.zig");
test "Create Image Bpp1" {
const test_image = try Image.create(helpers.zigimg_test_allocator, 24, 32, PixelFormat.Bpp1, .Raw);
defer test_image.deinit();
try helpers.expectEq(test_image.width, 24);
try helpers.expectEq(test_image.height, 32);
try helpers.expectEq(test_image.pixelFormat(), PixelFormat.Bpp1);
try testing.expect(test_image.pixels != null);
if (test_image.pixels) |pixels| {
try testing.expect(pixels == .Bpp1);
try testing.expect(pixels.Bpp1.palette.len == 2);
try testing.expect(pixels.Bpp1.indices.len == 24 * 32);
}
}
test "Create Image Bpp2" {
const test_image = try Image.create(helpers.zigimg_test_allocator, 24, 32, PixelFormat.Bpp2, .Raw);
defer test_image.deinit();
try helpers.expectEq(test_image.width, 24);
try helpers.expectEq(test_image.height, 32);
try helpers.expectEq(test_image.pixelFormat(), PixelFormat.Bpp2);
try testing.expect(test_image.pixels != null);
if (test_image.pixels) |pixels| {
try testing.expect(pixels == .Bpp2);
try testing.expect(pixels.Bpp2.palette.len == 4);
try testing.expect(pixels.Bpp2.indices.len == 24 * 32);
}
}
test "Create Image Bpp4" {
const test_image = try Image.create(helpers.zigimg_test_allocator, 24, 32, PixelFormat.Bpp4, .Raw);
defer test_image.deinit();
try helpers.expectEq(test_image.width, 24);
try helpers.expectEq(test_image.height, 32);
try helpers.expectEq(test_image.pixelFormat(), PixelFormat.Bpp4);
try testing.expect(test_image.pixels != null);
if (test_image.pixels) |pixels| {
try testing.expect(pixels == .Bpp4);
try testing.expect(pixels.Bpp4.palette.len == 16);
try testing.expect(pixels.Bpp4.indices.len == 24 * 32);
}
}
test "Create Image Bpp8" {
const test_image = try Image.create(helpers.zigimg_test_allocator, 24, 32, PixelFormat.Bpp8, .Raw);
defer test_image.deinit();
try helpers.expectEq(test_image.width, 24);
try helpers.expectEq(test_image.height, 32);
try helpers.expectEq(test_image.pixelFormat(), PixelFormat.Bpp8);
try testing.expect(test_image.pixels != null);
if (test_image.pixels) |pixels| {
try testing.expect(pixels == .Bpp8);
try testing.expect(pixels.Bpp8.palette.len == 256);
try testing.expect(pixels.Bpp8.indices.len == 24 * 32);
}
}
test "Create Image Bpp16" {
const test_image = try Image.create(helpers.zigimg_test_allocator, 24, 32, PixelFormat.Bpp16, .Raw);
defer test_image.deinit();
try helpers.expectEq(test_image.width, 24);
try helpers.expectEq(test_image.height, 32);
try helpers.expectEq(test_image.pixelFormat(), PixelFormat.Bpp16);
try testing.expect(test_image.pixels != null);
if (test_image.pixels) |pixels| {
try testing.expect(pixels == .Bpp16);
try testing.expect(pixels.Bpp16.palette.len == 65536);
try testing.expect(pixels.Bpp16.indices.len == 24 * 32);
}
}
test "Create Image Rgb24" {
const test_image = try Image.create(helpers.zigimg_test_allocator, 24, 32, PixelFormat.Rgb24, .Raw);
defer test_image.deinit();
try helpers.expectEq(test_image.width, 24);
try helpers.expectEq(test_image.height, 32);
try helpers.expectEq(test_image.pixelFormat(), PixelFormat.Rgb24);
try testing.expect(test_image.pixels != null);
if (test_image.pixels) |pixels| {
try testing.expect(pixels == .Rgb24);
try testing.expect(pixels.Rgb24.len == 24 * 32);
}
}
test "Create Image Rgba32" {
const test_image = try Image.create(helpers.zigimg_test_allocator, 24, 32, PixelFormat.Rgba32, .Raw);
defer test_image.deinit();
try helpers.expectEq(test_image.width, 24);
try helpers.expectEq(test_image.height, 32);
try helpers.expectEq(test_image.pixelFormat(), PixelFormat.Rgba32);
try testing.expect(test_image.pixels != null);
if (test_image.pixels) |pixels| {
try testing.expect(pixels == .Rgba32);
try testing.expect(pixels.Rgba32.len == 24 * 32);
}
}
test "Create Image Rgb565" {
const test_image = try Image.create(helpers.zigimg_test_allocator, 24, 32, PixelFormat.Rgb565, .Raw);
defer test_image.deinit();
try helpers.expectEq(test_image.width, 24);
try helpers.expectEq(test_image.height, 32);
try helpers.expectEq(test_image.pixelFormat(), PixelFormat.Rgb565);
try testing.expect(test_image.pixels != null);
if (test_image.pixels) |pixels| {
try testing.expect(pixels == .Rgb565);
try testing.expect(pixels.Rgb565.len == 24 * 32);
}
}
test "Create Image Rgb555" {
const test_image = try Image.create(helpers.zigimg_test_allocator, 24, 32, PixelFormat.Rgb555, .Raw);
defer test_image.deinit();
try helpers.expectEq(test_image.width, 24);
try helpers.expectEq(test_image.height, 32);
try helpers.expectEq(test_image.pixelFormat(), PixelFormat.Rgb555);
try testing.expect(test_image.pixels != null);
if (test_image.pixels) |pixels| {
try testing.expect(pixels == .Rgb555);
try testing.expect(pixels.Rgb555.len == 24 * 32);
}
}
test "Create Image Bgra32" {
const test_image = try Image.create(helpers.zigimg_test_allocator, 24, 32, PixelFormat.Bgra32, .Raw);
defer test_image.deinit();
try helpers.expectEq(test_image.width, 24);
try helpers.expectEq(test_image.height, 32);
try helpers.expectEq(test_image.pixelFormat(), PixelFormat.Bgra32);
try testing.expect(test_image.pixels != null);
if (test_image.pixels) |pixels| {
try testing.expect(pixels == .Bgra32);
try testing.expect(pixels.Bgra32.len == 24 * 32);
}
}
test "Create Image Float32" {
const test_image = try Image.create(helpers.zigimg_test_allocator, 24, 32, PixelFormat.Float32, .Raw);
defer test_image.deinit();
try helpers.expectEq(test_image.width, 24);
try helpers.expectEq(test_image.height, 32);
try helpers.expectEq(test_image.pixelFormat(), PixelFormat.Float32);
try testing.expect(test_image.pixels != null);
if (test_image.pixels) |pixels| {
try testing.expect(pixels == .Float32);
try testing.expect(pixels.Float32.len == 24 * 32);
}
}
test "Should detect BMP properly" {
const image_tests = &[_][]const u8{
"tests/fixtures/bmp/simple_v4.bmp",
"tests/fixtures/bmp/windows_rgba_v5.bmp",
};
for (image_tests) |image_path| {
const test_image = try Image.fromFilePath(helpers.zigimg_test_allocator, image_path);
defer test_image.deinit();
try testing.expect(test_image.image_format == .Bmp);
}
}
test "Should detect Memory BMP properly" {
const MemoryRGBABitmap = @embedFile("fixtures/bmp/windows_rgba_v5.bmp");
const test_image = try Image.fromMemory(helpers.zigimg_test_allocator, MemoryRGBABitmap);
defer test_image.deinit();
try testing.expect(test_image.image_format == .Bmp);
}
test "Should detect PCX properly" {
const image_tests = &[_][]const u8{
"tests/fixtures/pcx/test-bpp1.pcx",
"tests/fixtures/pcx/test-bpp4.pcx",
"tests/fixtures/pcx/test-bpp8.pcx",
"tests/fixtures/pcx/test-bpp24.pcx",
};
for (image_tests) |image_path| {
const test_image = try Image.fromFilePath(helpers.zigimg_test_allocator, image_path);
defer test_image.deinit();
try testing.expect(test_image.image_format == .Pcx);
}
}
test "Should detect PBM properly" {
const image_tests = &[_][]const u8{
"tests/fixtures/netpbm/pbm_ascii.pbm",
"tests/fixtures/netpbm/pbm_binary.pbm",
};
for (image_tests) |image_path| {
const test_image = try Image.fromFilePath(helpers.zigimg_test_allocator, image_path);
defer test_image.deinit();
try testing.expect(test_image.image_format == .Pbm);
}
}
test "Should detect PGM properly" {
const image_tests = &[_][]const u8{
"tests/fixtures/netpbm/pgm_ascii_grayscale8.pgm",
"tests/fixtures/netpbm/pgm_binary_grayscale8.pgm",
"tests/fixtures/netpbm/pgm_ascii_grayscale16.pgm",
"tests/fixtures/netpbm/pgm_binary_grayscale16.pgm",
};
for (image_tests) |image_path| {
const test_image = try Image.fromFilePath(helpers.zigimg_test_allocator, image_path);
defer test_image.deinit();
try testing.expect(test_image.image_format == .Pgm);
}
}
test "Should detect PPM properly" {
const image_tests = &[_][]const u8{
"tests/fixtures/netpbm/ppm_ascii_rgb24.ppm",
"tests/fixtures/netpbm/ppm_binary_rgb24.ppm",
};
for (image_tests) |image_path| {
const test_image = try Image.fromFilePath(helpers.zigimg_test_allocator, image_path);
defer test_image.deinit();
try testing.expect(test_image.image_format == .Ppm);
}
}
test "Should detect PNG properly" {
const image_tests = &[_][]const u8{
"tests/fixtures/png/basn0g01.png",
"tests/fixtures/png/basi0g01.png",
};
for (image_tests) |image_path| {
const test_image = try Image.fromFilePath(helpers.zigimg_test_allocator, image_path);
defer test_image.deinit();
try testing.expect(test_image.image_format == .Png);
}
}
test "Should detect TGA properly" {
const image_tests = &[_][]const u8{
"tests/fixtures/tga/cbw8.tga",
"tests/fixtures/tga/ccm8.tga",
"tests/fixtures/tga/ctc24.tga",
"tests/fixtures/tga/ubw8.tga",
"tests/fixtures/tga/ucm8.tga",
"tests/fixtures/tga/utc16.tga",
"tests/fixtures/tga/utc24.tga",
"tests/fixtures/tga/utc32.tga",
};
for (image_tests) |image_path| {
const test_image = try Image.fromFilePath(helpers.zigimg_test_allocator, image_path);
defer test_image.deinit();
try testing.expect(test_image.image_format == .Tga);
}
}
test "Should detect QOI properly" {
const image_tests = &[_][]const u8{"tests/fixtures/qoi/zero.qoi"};
for (image_tests) |image_path| {
const test_image = try Image.fromFilePath(helpers.zigimg_test_allocator, image_path);
defer test_image.deinit();
try testing.expect(test_image.image_format == .Qoi);
}
}
test "Should error on invalid path" {
var invalidPath = Image.fromFilePath(helpers.zigimg_test_allocator, "notapathdummy");
try helpers.expectError(invalidPath, error.FileNotFound);
}
test "Should error on invalid file" {
var invalidFile = Image.fromFilePath(helpers.zigimg_test_allocator, "tests/helpers.zig");
try helpers.expectError(invalidFile, error.ImageFormatInvalid);
}
test "Should read a 24-bit bitmap" {
var test_image = try Image.fromFilePath(helpers.zigimg_test_allocator, "tests/fixtures/bmp/simple_v4.bmp");
defer test_image.deinit();
try helpers.expectEq(test_image.width, 8);
try helpers.expectEq(test_image.height, 1);
if (test_image.pixels) |pixels| {
try testing.expect(pixels == .Bgr24);
const red = pixels.Bgr24[0];
try helpers.expectEq(red.R, 0xFF);
try helpers.expectEq(red.G, 0x00);
try helpers.expectEq(red.B, 0x00);
const green = pixels.Bgr24[1];
try helpers.expectEq(green.R, 0x00);
try helpers.expectEq(green.G, 0xFF);
try helpers.expectEq(green.B, 0x00);
const blue = pixels.Bgr24[2];
try helpers.expectEq(blue.R, 0x00);
try helpers.expectEq(blue.G, 0x00);
try helpers.expectEq(blue.B, 0xFF);
const cyan = pixels.Bgr24[3];
try helpers.expectEq(cyan.R, 0x00);
try helpers.expectEq(cyan.G, 0xFF);
try helpers.expectEq(cyan.B, 0xFF);
const magenta = pixels.Bgr24[4];
try helpers.expectEq(magenta.R, 0xFF);
try helpers.expectEq(magenta.G, 0x00);
try helpers.expectEq(magenta.B, 0xFF);
const yellow = pixels.Bgr24[5];
try helpers.expectEq(yellow.R, 0xFF);
try helpers.expectEq(yellow.G, 0xFF);
try helpers.expectEq(yellow.B, 0x00);
const black = pixels.Bgr24[6];
try helpers.expectEq(black.R, 0x00);
try helpers.expectEq(black.G, 0x00);
try helpers.expectEq(black.B, 0x00);
const white = pixels.Bgr24[7];
try helpers.expectEq(white.R, 0xFF);
try helpers.expectEq(white.G, 0xFF);
try helpers.expectEq(white.B, 0xFF);
}
}
test "Test Color iterator" {
var test_image = try Image.fromFilePath(helpers.zigimg_test_allocator, "tests/fixtures/bmp/simple_v4.bmp");
defer test_image.deinit();
const expectedColors = [_]color.Color{
color.Color.initRGB(1.0, 0.0, 0.0),
color.Color.initRGB(0.0, 1.0, 0.0),
color.Color.initRGB(0.0, 0.0, 1.0),
color.Color.initRGB(0.0, 1.0, 1.0),
color.Color.initRGB(1.0, 0.0, 1.0),
color.Color.initRGB(1.0, 1.0, 0.0),
color.Color.initRGB(0.0, 0.0, 0.0),
color.Color.initRGB(1.0, 1.0, 1.0),
};
try helpers.expectEq(test_image.width, 8);
try helpers.expectEq(test_image.height, 1);
var it = test_image.iterator();
var i: usize = 0;
while (it.next()) |actual| {
const expected = expectedColors[i];
try helpers.expectEq(actual.R, expected.R);
try helpers.expectEq(actual.G, expected.G);
try helpers.expectEq(actual.B, expected.B);
i += 1;
}
} | tests/image_test.zig |
const std = @import("std");
const builtin = @import("builtin");
const Builder = std.build.Builder;
const Step = std.build.Step;
pub fn addStaticLibrary(
b: *Builder,
app: *std.build.LibExeObjStep,
comptime path: []const u8,
use_vulkan_sdk: bool,
enable_tracing: bool,
) *std.build.LibExeObjStep {
const os_tag = if (app.target.os_tag != null) app.target.os_tag.? else builtin.os.tag;
const nyancoreLib = b.addStaticLibrary("nyancore", path ++ "src/main.zig");
nyancoreLib.setBuildMode(app.build_mode);
nyancoreLib.setTarget(app.target);
const nyancore_options = b.addOptions();
nyancore_options.addOption(bool, "use_vulkan_sdk", use_vulkan_sdk);
nyancore_options.addOption(bool, "enable_tracing", enable_tracing);
nyancoreLib.addOptions("nyancore_options", nyancore_options);
app.addOptions("nyancore_options", nyancore_options);
app.addPackage(.{
.name = "nyancore",
.path = .{ .path = path ++ "/src/main.zig" },
.dependencies = &[_]std.build.Pkg{
nyancore_options.getPackage("nyancore_options"),
},
});
// Vulkan
const vulkanPackage: std.build.Pkg = .{
.name = "vulkan",
.path = .{ .path = path ++ "src/vk.zig" },
};
nyancoreLib.addPackage(vulkanPackage);
app.addPackage(vulkanPackage);
if (use_vulkan_sdk) {
const vulkan_sdk_path = std.process.getEnvVarOwned(b.allocator, "VULKAN_SDK") catch {
std.debug.print("[ERR] Can't get VULKAN_SDK environment variable", .{});
return nyancoreLib;
};
defer b.allocator.free(vulkan_sdk_path);
const vulkan_sdk_include_path = std.fs.path.join(b.allocator, &[_][]const u8{ vulkan_sdk_path, "include" }) catch unreachable;
defer b.allocator.free(vulkan_sdk_include_path);
nyancoreLib.addIncludeDir(vulkan_sdk_include_path);
app.addIncludeDir(vulkan_sdk_include_path);
}
// Tracy
if (enable_tracing) {
const tracy_path: []const u8 = path ++ "third_party/tracy/";
const tracy_lib = b.addStaticLibrary("tracy", null);
const tracy_flags = &[_][]const u8{ "-DTRACY_ENABLE", "-DTRACY_NO_CALLSTACK", "-DTRACY_NO_SYSTEM_TRACING" };
tracy_lib.setTarget(app.target);
tracy_lib.setBuildMode(app.build_mode);
tracy_lib.linkSystemLibrary("c");
tracy_lib.linkSystemLibrary("c++");
if (os_tag == .windows) {
tracy_lib.linkSystemLibrary("advapi32");
tracy_lib.linkSystemLibrary("user32");
tracy_lib.linkSystemLibrary("ws2_32");
tracy_lib.linkSystemLibrary("dbghelp");
}
tracy_lib.addIncludeDir(tracy_path);
tracy_lib.addCSourceFile(tracy_path ++ "TracyClient.cpp", tracy_flags);
nyancoreLib.step.dependOn(&tracy_lib.step);
nyancoreLib.linkLibrary(tracy_lib);
app.addIncludeDir(tracy_path);
app.linkLibrary(tracy_lib);
}
// GLFW
const glfw_path: []const u8 = path ++ "third_party/glfw/";
const glfw_lib = b.addStaticLibrary("glfw", null);
glfw_lib.setTarget(app.target);
glfw_lib.setBuildMode(app.build_mode);
const glfw_flags = &[_][]const u8{
switch (os_tag) {
.windows => "-D_GLFW_WIN32",
.macos => "-D_GLFW_COCA",
else => "-D_GLFW_X11", // -D_GLFW_WAYLAND
},
};
glfw_lib.linkSystemLibrary("c");
glfw_lib.addIncludeDir(glfw_path ++ "include");
glfw_lib.addCSourceFiles(&[_][]const u8{
glfw_path ++ "src/context.c",
glfw_path ++ "src/egl_context.c",
glfw_path ++ "src/init.c",
glfw_path ++ "src/input.c",
glfw_path ++ "src/monitor.c",
glfw_path ++ "src/null_init.c",
glfw_path ++ "src/null_joystick.c",
glfw_path ++ "src/null_monitor.c",
glfw_path ++ "src/null_window.c",
glfw_path ++ "src/osmesa_context.c",
glfw_path ++ "src/platform.c",
glfw_path ++ "src/vulkan.c",
glfw_path ++ "src/window.c",
}, glfw_flags);
glfw_lib.addCSourceFiles(switch (os_tag) {
.windows => &[_][]const u8{
glfw_path ++ "src/wgl_context.c",
glfw_path ++ "src/win32_init.c",
glfw_path ++ "src/win32_joystick.c",
glfw_path ++ "src/win32_module.c",
glfw_path ++ "src/win32_monitor.c",
glfw_path ++ "src/win32_thread.c",
glfw_path ++ "src/win32_time.c",
glfw_path ++ "src/win32_window.c",
},
.macos => &[_][]const u8{
glfw_path ++ "src/cocoa_init.m",
glfw_path ++ "src/cocoa_joystick.m",
glfw_path ++ "src/cocoa_monitor.m",
glfw_path ++ "src/cocoa_time.c",
glfw_path ++ "src/cocoa_window.m",
glfw_path ++ "src/nsgl_context.m",
glfw_path ++ "src/posix_thread.c",
glfw_path ++ "src/posix_module.c",
glfw_path ++ "src/posix_poll.c",
},
else => &[_][]const u8{
glfw_path ++ "src/posix_poll.c",
glfw_path ++ "src/posix_module.c",
glfw_path ++ "src/posix_thread.c",
glfw_path ++ "src/posix_time.c",
glfw_path ++ "src/linux_joystick.c",
// X11
glfw_path ++ "src/glx_context.c",
glfw_path ++ "src/x11_init.c",
glfw_path ++ "src/x11_monitor.c",
glfw_path ++ "src/x11_window.c",
glfw_path ++ "src/xkb_unicode.c",
// Wayland
//glfw_path ++ "src/wl_init.c",
//glfw_path ++ "src/wl_monitor.c",
//glfw_path ++ "src/wl_window.c",
},
}, glfw_flags);
if (os_tag != .windows) {
glfw_lib.linkSystemLibrary("X11");
glfw_lib.linkSystemLibrary("xcb");
glfw_lib.linkSystemLibrary("Xau");
glfw_lib.linkSystemLibrary("Xdmcp");
} else {
glfw_lib.linkSystemLibrary("gdi32");
}
nyancoreLib.step.dependOn(&glfw_lib.step);
nyancoreLib.linkLibrary(glfw_lib);
app.addIncludeDir(glfw_path ++ "include");
app.linkLibrary(glfw_lib);
// Dear ImGui
const cimgui_path: []const u8 = path ++ "third_party/cimgui/";
const imgui_flags = &[_][]const u8{};
const imgui_lib = b.addStaticLibrary("imgui", null);
imgui_lib.setTarget(app.target);
imgui_lib.setBuildMode(app.build_mode);
imgui_lib.linkSystemLibrary("c");
imgui_lib.linkSystemLibrary("c++");
imgui_lib.addIncludeDir(cimgui_path ++ "");
imgui_lib.addIncludeDir(cimgui_path ++ "imgui");
imgui_lib.addCSourceFile(cimgui_path ++ "imgui/imgui.cpp", imgui_flags);
imgui_lib.addCSourceFile(cimgui_path ++ "imgui/imgui_demo.cpp", imgui_flags);
imgui_lib.addCSourceFile(cimgui_path ++ "imgui/imgui_draw.cpp", imgui_flags);
imgui_lib.addCSourceFile(cimgui_path ++ "imgui/imgui_tables.cpp", imgui_flags);
imgui_lib.addCSourceFile(cimgui_path ++ "imgui/imgui_widgets.cpp", imgui_flags);
imgui_lib.addCSourceFile(cimgui_path ++ "cimgui.cpp", imgui_flags);
nyancoreLib.step.dependOn(&imgui_lib.step);
nyancoreLib.linkLibrary(imgui_lib);
app.addIncludeDir(cimgui_path);
app.linkLibrary(imgui_lib);
// glslang
const glslang_path: []const u8 = path ++ "third_party/glslang/";
const glslang_machine_dependent_path = if (os_tag == .windows) glslang_path ++ "glslang/OSDependent/Windows/" else glslang_path ++ "glslang/OSDependent/Unix/";
const glslang_flags = &[_][]const u8{};
const glslang_lib = b.addStaticLibrary("glslang", null);
glslang_lib.setTarget(app.target);
glslang_lib.setBuildMode(app.build_mode);
glslang_lib.linkSystemLibrary("c");
glslang_lib.linkSystemLibrary("c++");
glslang_lib.addIncludeDir(glslang_path);
glslang_lib.addCSourceFile(glslang_path ++ "glslang/CInterface/glslang_c_interface.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "glslang/GenericCodeGen/CodeGen.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "glslang/GenericCodeGen/Link.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "glslang/MachineIndependent/attribute.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "glslang/MachineIndependent/Constant.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "glslang/MachineIndependent/Initialize.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "glslang/MachineIndependent/InfoSink.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "glslang/MachineIndependent/Intermediate.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "glslang/MachineIndependent/intermOut.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "glslang/MachineIndependent/IntermTraverse.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "glslang/MachineIndependent/iomapper.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "glslang/MachineIndependent/glslang_tab.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "glslang/MachineIndependent/linkValidate.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "glslang/MachineIndependent/limits.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "glslang/MachineIndependent/parseConst.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "glslang/MachineIndependent/ParseContextBase.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "glslang/MachineIndependent/preprocessor/Pp.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "glslang/MachineIndependent/preprocessor/PpAtom.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "glslang/MachineIndependent/preprocessor/PpContext.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "glslang/MachineIndependent/preprocessor/PpScanner.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "glslang/MachineIndependent/preprocessor/PpTokens.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "glslang/MachineIndependent/propagateNoContraction.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "glslang/MachineIndependent/reflection.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "glslang/MachineIndependent/RemoveTree.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "glslang/MachineIndependent/Scan.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "glslang/MachineIndependent/ShaderLang.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "glslang/MachineIndependent/SpirvIntrinsics.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "glslang/MachineIndependent/SymbolTable.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "glslang/MachineIndependent/ParseHelper.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "glslang/MachineIndependent/PoolAlloc.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "glslang/MachineIndependent/Versions.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "OGLCompilersDLL/InitializeDll.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "SPIRV/CInterface/spirv_c_interface.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "SPIRV/GlslangToSpv.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "SPIRV/InReadableOrder.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "SPIRV/Logger.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "SPIRV/SpvBuilder.cpp", glslang_flags);
glslang_lib.addCSourceFile(glslang_path ++ "SPIRV/SpvPostProcess.cpp", glslang_flags);
const osssource_path = std.fs.path.join(b.allocator, &.{ glslang_machine_dependent_path, "ossource.cpp" }) catch unreachable;
glslang_lib.addCSourceFile(osssource_path, glslang_flags);
nyancoreLib.step.dependOn(&glslang_lib.step);
nyancoreLib.linkLibrary(glslang_lib);
app.addIncludeDir(glslang_path ++ "glslang/Include");
app.linkLibrary(glslang_lib);
// Fonts
nyancoreLib.addIncludeDir(path ++ "third_party/fonts/");
app.addIncludeDir(path ++ "third_party/fonts/");
// Enet
const enet_path: []const u8 = path ++ "third_party/enet/";
const enet_flags = switch (os_tag) {
.windows => &[_][]const u8{
"-fno-sanitize=undefined",
"-DHAS_GETNAMEINFO=1",
"-DHAS_INET_PTON=1",
"-DHAS_INET_NTOP=1",
"-DHAS_MSGHDR_FLAGS=1",
},
else => &[_][]const u8{
"-fno-sanitize=undefined",
"-DHAS_FCNTL=1",
"-DHAS_POLL=1",
"-DHAS_GETADDRINFO=1",
"-DHAS_GETNAMEINFO=1",
"-DHAS_GETHOSTBYNAME_R=1",
"-DHAS_GETHOSTBYADDR_R=1",
"-DHAS_INET_PTON=1",
"-DHAS_INET_NTOP=1",
"-DHAS_MSGHDR_FLAGS=1",
"-DHAS_SOCKLEN_T=1",
},
};
const enet_lib = b.addStaticLibrary("enet", null);
enet_lib.setTarget(app.target);
enet_lib.setBuildMode(app.build_mode);
enet_lib.linkSystemLibrary("c");
enet_lib.addIncludeDir(enet_path ++ "include");
enet_lib.addCSourceFile(enet_path ++ "callbacks.c", enet_flags);
enet_lib.addCSourceFile(enet_path ++ "compress.c", enet_flags);
enet_lib.addCSourceFile(enet_path ++ "host.c", enet_flags);
enet_lib.addCSourceFile(enet_path ++ "list.c", enet_flags);
enet_lib.addCSourceFile(enet_path ++ "packet.c", enet_flags);
enet_lib.addCSourceFile(enet_path ++ "peer.c", enet_flags);
enet_lib.addCSourceFile(enet_path ++ "protocol.c", enet_flags);
enet_lib.addCSourceFile(enet_path ++ "unix.c", enet_flags);
enet_lib.addCSourceFile(enet_path ++ "win32.c", enet_flags);
nyancoreLib.step.dependOn(&enet_lib.step);
nyancoreLib.linkLibrary(enet_lib);
app.addIncludeDir(enet_path ++ "include");
app.linkLibrary(enet_lib);
nyancoreLib.install();
return nyancoreLib;
} | build.zig |
const std = @import("std");
const builtin = @import("builtin");
const math = std.math;
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var global_allocator = gpa.allocator();
const solar_mass = 4.0 * math.pi * math.pi;
const year = 365.24;
const Planet = struct {
x: f64,
y: f64,
z: f64,
vx: f64,
vy: f64,
vz: f64,
mass: f64,
};
fn advance(bodies: []Planet, dt: f64, steps: usize) void {
var i: usize = 0;
while (i < steps) : (i += 1) {
for (bodies) |*bi, j| {
var vx = bi.vx;
var vy = bi.vy;
var vz = bi.vz;
for (bodies[j + 1 ..]) |*bj| {
const dx = bi.x - bj.x;
const dy = bi.y - bj.y;
const dz = bi.z - bj.z;
const dsq = dx * dx + dy * dy + dz * dz;
const dst = math.sqrt(dsq);
const mag = dt / (dsq * dst);
const mi = bi.mass;
vx -= dx * bj.mass * mag;
vy -= dy * bj.mass * mag;
vz -= dz * bj.mass * mag;
bj.vx += dx * mi * mag;
bj.vy += dy * mi * mag;
bj.vz += dz * mi * mag;
}
bi.vx = vx;
bi.vy = vy;
bi.vz = vz;
bi.x += dt * vx;
bi.y += dt * vy;
bi.z += dt * vz;
}
}
}
fn energy(bodies: []const Planet) f64 {
var e: f64 = 0.0;
for (bodies) |bi, i| {
e += 0.5 * (bi.vx * bi.vx + bi.vy * bi.vy + bi.vz * bi.vz) * bi.mass;
for (bodies[i + 1 ..]) |bj| {
const dx = bi.x - bj.x;
const dy = bi.y - bj.y;
const dz = bi.z - bj.z;
const dist = math.sqrt(dx * dx + dy * dy + dz * dz);
e -= bi.mass * bj.mass / dist;
}
}
return e;
}
fn offset_momentum(bodies: []Planet) void {
var px: f64 = 0.0;
var py: f64 = 0.0;
var pz: f64 = 0.0;
for (bodies) |b| {
px -= b.vx * b.mass;
py -= b.vy * b.mass;
pz -= b.vz * b.mass;
}
var sun = &bodies[0];
sun.vx = px / solar_mass;
sun.vy = py / solar_mass;
sun.vz = pz / solar_mass;
}
const solar_bodies = [_]Planet{
// Sun
Planet{
.x = 0.0,
.y = 0.0,
.z = 0.0,
.vx = 0.0,
.vy = 0.0,
.vz = 0.0,
.mass = solar_mass,
},
// Jupiter
Planet{
.x = 4.84143144246472090e+00,
.y = -1.16032004402742839e+00,
.z = -1.03622044471123109e-01,
.vx = 1.66007664274403694e-03 * year,
.vy = 7.69901118419740425e-03 * year,
.vz = -6.90460016972063023e-05 * year,
.mass = 9.54791938424326609e-04 * solar_mass,
},
// Saturn
Planet{
.x = 8.34336671824457987e+00,
.y = 4.12479856412430479e+00,
.z = -4.03523417114321381e-01,
.vx = -2.76742510726862411e-03 * year,
.vy = 4.99852801234917238e-03 * year,
.vz = 2.30417297573763929e-05 * year,
.mass = 2.85885980666130812e-04 * solar_mass,
},
// Uranus
Planet{
.x = 1.28943695621391310e+01,
.y = -1.51111514016986312e+01,
.z = -2.23307578892655734e-01,
.vx = 2.96460137564761618e-03 * year,
.vy = 2.37847173959480950e-03 * year,
.vz = -2.96589568540237556e-05 * year,
.mass = 4.36624404335156298e-05 * solar_mass,
},
// Neptune
Planet{
.x = 1.53796971148509165e+01,
.y = -2.59193146099879641e+01,
.z = 1.79258772950371181e-01,
.vx = 2.68067772490389322e-03 * year,
.vy = 1.62824170038242295e-03 * year,
.vz = -9.51592254519715870e-05 * year,
.mass = 5.15138902046611451e-05 * solar_mass,
},
};
var buffer: [32]u8 = undefined;
var fixed_allocator = std.heap.FixedBufferAllocator.init(buffer[0..]);
var allocator = &fixed_allocator.allocator;
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
const n = try get_n();
var bodies = solar_bodies;
offset_momentum(bodies[0..]);
var ret = energy(bodies[0..]);
try stdout.print("{d:.9}\n", .{ret});
advance(bodies[0..], 0.01, n);
ret = energy(bodies[0..]);
try stdout.print("{d:.9}\n", .{ret});
}
fn get_n() !usize {
var arg_it = std.process.args();
_ = arg_it.skip();
const arg = arg_it.next() orelse return 1000;
return try std.fmt.parseInt(usize, arg, 10);
} | bench/algorithm/nbody/1.zig |
pub const Entity = struct {
name: []const u8,
value: Value,
pub const Value = union(enum) {
Rune: usize,
Rune2: [2]usize,
};
pub fn init(name: []const u8, value: Value) Entity {
return Entity{ .name = name, .value = value };
}
};
/// we are defining all entity value on a single list. This is an offset to mark
/// the end of the first entity values in the list
pub const entity_one_size: usize = 2138;
pub const entity_list = [_]Entity{
ntity.init("AElig", Entity.Value{ .Rune = 0xc6 }),
Entity.init("AElig;", Entity.Value{ .Rune = 0xc6 }),
Entity.init("AMP", Entity.Value{ .Rune = 0x26 }),
Entity.init("AMP;", Entity.Value{ .Rune = 0x26 }),
Entity.init("Aacute", Entity.Value{ .Rune = 0xc1 }),
Entity.init("Aacute;", Entity.Value{ .Rune = 0xc1 }),
Entity.init("Abreve;", Entity.Value{ .Rune = 0x102 }),
Entity.init("Acirc", Entity.Value{ .Rune = 0xc2 }),
Entity.init("Acirc;", Entity.Value{ .Rune = 0xc2 }),
Entity.init("Acy;", Entity.Value{ .Rune = 0x410 }),
Entity.init("Afr;", Entity.Value{ .Rune = 0x1d504 }),
Entity.init("Agrave", Entity.Value{ .Rune = 0xc0 }),
Entity.init("Agrave;", Entity.Value{ .Rune = 0xc0 }),
Entity.init("Alpha;", Entity.Value{ .Rune = 0x391 }),
Entity.init("Amacr;", Entity.Value{ .Rune = 0x100 }),
Entity.init("And;", Entity.Value{ .Rune = 0x2a53 }),
Entity.init("Aogon;", Entity.Value{ .Rune = 0x104 }),
Entity.init("Aopf;", Entity.Value{ .Rune = 0x1d538 }),
Entity.init("ApplyFunction;", Entity.Value{ .Rune = 0x2061 }),
Entity.init("Aring", Entity.Value{ .Rune = 0xc5 }),
Entity.init("Aring;", Entity.Value{ .Rune = 0xc5 }),
Entity.init("Ascr;", Entity.Value{ .Rune = 0x1d49c }),
Entity.init("Assign;", Entity.Value{ .Rune = 0x2254 }),
Entity.init("Atilde", Entity.Value{ .Rune = 0xc3 }),
Entity.init("Atilde;", Entity.Value{ .Rune = 0xc3 }),
Entity.init("Auml", Entity.Value{ .Rune = 0xc4 }),
Entity.init("Auml;", Entity.Value{ .Rune = 0xc4 }),
Entity.init("Backslash;", Entity.Value{ .Rune = 0x2216 }),
Entity.init("Barv;", Entity.Value{ .Rune = 0x2ae7 }),
Entity.init("Barwed;", Entity.Value{ .Rune = 0x2306 }),
Entity.init("Bcy;", Entity.Value{ .Rune = 0x411 }),
Entity.init("Because;", Entity.Value{ .Rune = 0x2235 }),
Entity.init("Bernoullis;", Entity.Value{ .Rune = 0x212c }),
Entity.init("Beta;", Entity.Value{ .Rune = 0x392 }),
Entity.init("Bfr;", Entity.Value{ .Rune = 0x1d505 }),
Entity.init("Bopf;", Entity.Value{ .Rune = 0x1d539 }),
Entity.init("Breve;", Entity.Value{ .Rune = 0x2d8 }),
Entity.init("Bscr;", Entity.Value{ .Rune = 0x212c }),
Entity.init("Bumpeq;", Entity.Value{ .Rune = 0x224e }),
Entity.init("CHcy;", Entity.Value{ .Rune = 0x427 }),
Entity.init("COPY", Entity.Value{ .Rune = 0xa9 }),
Entity.init("COPY;", Entity.Value{ .Rune = 0xa9 }),
Entity.init("Cacute;", Entity.Value{ .Rune = 0x106 }),
Entity.init("Cap;", Entity.Value{ .Rune = 0x22d2 }),
Entity.init("CapitalDifferentialD;", Entity.Value{ .Rune = 0x2145 }),
Entity.init("Cayleys;", Entity.Value{ .Rune = 0x212d }),
Entity.init("Ccaron;", Entity.Value{ .Rune = 0x10c }),
Entity.init("Ccedil", Entity.Value{ .Rune = 0xc7 }),
Entity.init("Ccedil;", Entity.Value{ .Rune = 0xc7 }),
Entity.init("Ccirc;", Entity.Value{ .Rune = 0x108 }),
Entity.init("Cconint;", Entity.Value{ .Rune = 0x2230 }),
Entity.init("Cdot;", Entity.Value{ .Rune = 0x10a }),
Entity.init("Cedilla;", Entity.Value{ .Rune = 0xb8 }),
Entity.init("CenterDot;", Entity.Value{ .Rune = 0xb7 }),
Entity.init("Cfr;", Entity.Value{ .Rune = 0x212d }),
Entity.init("Chi;", Entity.Value{ .Rune = 0x3a7 }),
Entity.init("CircleDot;", Entity.Value{ .Rune = 0x2299 }),
Entity.init("CircleMinus;", Entity.Value{ .Rune = 0x2296 }),
Entity.init("CirclePlus;", Entity.Value{ .Rune = 0x2295 }),
Entity.init("CircleTimes;", Entity.Value{ .Rune = 0x2297 }),
Entity.init("ClockwiseContourIntegral;", Entity.Value{ .Rune = 0x2232 }),
Entity.init("CloseCurlyDoubleQuote;", Entity.Value{ .Rune = 0x201d }),
Entity.init("CloseCurlyQuote;", Entity.Value{ .Rune = 0x2019 }),
Entity.init("Colon;", Entity.Value{ .Rune = 0x2237 }),
Entity.init("Colone;", Entity.Value{ .Rune = 0x2a74 }),
Entity.init("Congruent;", Entity.Value{ .Rune = 0x2261 }),
Entity.init("Conint;", Entity.Value{ .Rune = 0x222f }),
Entity.init("ContourIntegral;", Entity.Value{ .Rune = 0x222e }),
Entity.init("Copf;", Entity.Value{ .Rune = 0x2102 }),
Entity.init("Coproduct;", Entity.Value{ .Rune = 0x2210 }),
Entity.init("CounterClockwiseContourIntegral;", Entity.Value{ .Rune = 0x2233 }),
Entity.init("Cross;", Entity.Value{ .Rune = 0x2a2f }),
Entity.init("Cscr;", Entity.Value{ .Rune = 0x1d49e }),
Entity.init("Cup;", Entity.Value{ .Rune = 0x22d3 }),
Entity.init("CupCap;", Entity.Value{ .Rune = 0x224d }),
Entity.init("DD;", Entity.Value{ .Rune = 0x2145 }),
Entity.init("DDotrahd;", Entity.Value{ .Rune = 0x2911 }),
Entity.init("DJcy;", Entity.Value{ .Rune = 0x402 }),
Entity.init("DScy;", Entity.Value{ .Rune = 0x405 }),
Entity.init("DZcy;", Entity.Value{ .Rune = 0x40f }),
Entity.init("Dagger;", Entity.Value{ .Rune = 0x2021 }),
Entity.init("Darr;", Entity.Value{ .Rune = 0x21a1 }),
Entity.init("Dashv;", Entity.Value{ .Rune = 0x2ae4 }),
Entity.init("Dcaron;", Entity.Value{ .Rune = 0x10e }),
Entity.init("Dcy;", Entity.Value{ .Rune = 0x414 }),
Entity.init("Del;", Entity.Value{ .Rune = 0x2207 }),
Entity.init("Delta;", Entity.Value{ .Rune = 0x394 }),
Entity.init("Dfr;", Entity.Value{ .Rune = 0x1d507 }),
Entity.init("DiacriticalAcute;", Entity.Value{ .Rune = 0xb4 }),
Entity.init("DiacriticalDot;", Entity.Value{ .Rune = 0x2d9 }),
Entity.init("DiacriticalDoubleAcute;", Entity.Value{ .Rune = 0x2dd }),
Entity.init("DiacriticalGrave;", Entity.Value{ .Rune = 0x60 }),
Entity.init("DiacriticalTilde;", Entity.Value{ .Rune = 0x2dc }),
Entity.init("Diamond;", Entity.Value{ .Rune = 0x22c4 }),
Entity.init("DifferentialD;", Entity.Value{ .Rune = 0x2146 }),
Entity.init("Dopf;", Entity.Value{ .Rune = 0x1d53b }),
Entity.init("Dot;", Entity.Value{ .Rune = 0xa8 }),
Entity.init("DotDot;", Entity.Value{ .Rune = 0x20dc }),
Entity.init("DotEqual;", Entity.Value{ .Rune = 0x2250 }),
Entity.init("DoubleContourIntegral;", Entity.Value{ .Rune = 0x222f }),
Entity.init("DoubleDot;", Entity.Value{ .Rune = 0xa8 }),
Entity.init("DoubleDownArrow;", Entity.Value{ .Rune = 0x21d3 }),
Entity.init("DoubleLeftArrow;", Entity.Value{ .Rune = 0x21d0 }),
Entity.init("DoubleLeftRightArrow;", Entity.Value{ .Rune = 0x21d4 }),
Entity.init("DoubleLeftTee;", Entity.Value{ .Rune = 0x2ae4 }),
Entity.init("DoubleLongLeftArrow;", Entity.Value{ .Rune = 0x27f8 }),
Entity.init("DoubleLongLeftRightArrow;", Entity.Value{ .Rune = 0x27fa }),
Entity.init("DoubleLongRightArrow;", Entity.Value{ .Rune = 0x27f9 }),
Entity.init("DoubleRightArrow;", Entity.Value{ .Rune = 0x21d2 }),
Entity.init("DoubleRightTee;", Entity.Value{ .Rune = 0x22a8 }),
Entity.init("DoubleUpArrow;", Entity.Value{ .Rune = 0x21d1 }),
Entity.init("DoubleUpDownArrow;", Entity.Value{ .Rune = 0x21d5 }),
Entity.init("DoubleVerticalBar;", Entity.Value{ .Rune = 0x2225 }),
Entity.init("DownArrow;", Entity.Value{ .Rune = 0x2193 }),
Entity.init("DownArrowBar;", Entity.Value{ .Rune = 0x2913 }),
Entity.init("DownArrowUpArrow;", Entity.Value{ .Rune = 0x21f5 }),
Entity.init("DownBreve;", Entity.Value{ .Rune = 0x311 }),
Entity.init("DownLeftRightVector;", Entity.Value{ .Rune = 0x2950 }),
Entity.init("DownLeftTeeVector;", Entity.Value{ .Rune = 0x295e }),
Entity.init("DownLeftVector;", Entity.Value{ .Rune = 0x21bd }),
Entity.init("DownLeftVectorBar;", Entity.Value{ .Rune = 0x2956 }),
Entity.init("DownRightTeeVector;", Entity.Value{ .Rune = 0x295f }),
Entity.init("DownRightVector;", Entity.Value{ .Rune = 0x21c1 }),
Entity.init("DownRightVectorBar;", Entity.Value{ .Rune = 0x2957 }),
Entity.init("DownTee;", Entity.Value{ .Rune = 0x22a4 }),
Entity.init("DownTeeArrow;", Entity.Value{ .Rune = 0x21a7 }),
Entity.init("Downarrow;", Entity.Value{ .Rune = 0x21d3 }),
Entity.init("Dscr;", Entity.Value{ .Rune = 0x1d49f }),
Entity.init("Dstrok;", Entity.Value{ .Rune = 0x110 }),
Entity.init("ENG;", Entity.Value{ .Rune = 0x14a }),
Entity.init("ETH", Entity.Value{ .Rune = 0xd0 }),
Entity.init("ETH;", Entity.Value{ .Rune = 0xd0 }),
Entity.init("Eacute", Entity.Value{ .Rune = 0xc9 }),
Entity.init("Eacute;", Entity.Value{ .Rune = 0xc9 }),
Entity.init("Ecaron;", Entity.Value{ .Rune = 0x11a }),
Entity.init("Ecirc", Entity.Value{ .Rune = 0xca }),
Entity.init("Ecirc;", Entity.Value{ .Rune = 0xca }),
Entity.init("Ecy;", Entity.Value{ .Rune = 0x42d }),
Entity.init("Edot;", Entity.Value{ .Rune = 0x116 }),
Entity.init("Efr;", Entity.Value{ .Rune = 0x1d508 }),
Entity.init("Egrave", Entity.Value{ .Rune = 0xc8 }),
Entity.init("Egrave;", Entity.Value{ .Rune = 0xc8 }),
Entity.init("Element;", Entity.Value{ .Rune = 0x2208 }),
Entity.init("Emacr;", Entity.Value{ .Rune = 0x112 }),
Entity.init("EmptySmallSquare;", Entity.Value{ .Rune = 0x25fb }),
Entity.init("EmptyVerySmallSquare;", Entity.Value{ .Rune = 0x25ab }),
Entity.init("Eogon;", Entity.Value{ .Rune = 0x118 }),
Entity.init("Eopf;", Entity.Value{ .Rune = 0x1d53c }),
Entity.init("Epsilon;", Entity.Value{ .Rune = 0x395 }),
Entity.init("Equal;", Entity.Value{ .Rune = 0x2a75 }),
Entity.init("EqualTilde;", Entity.Value{ .Rune = 0x2242 }),
Entity.init("Equilibrium;", Entity.Value{ .Rune = 0x21cc }),
Entity.init("Escr;", Entity.Value{ .Rune = 0x2130 }),
Entity.init("Esim;", Entity.Value{ .Rune = 0x2a73 }),
Entity.init("Eta;", Entity.Value{ .Rune = 0x397 }),
Entity.init("Euml", Entity.Value{ .Rune = 0xcb }),
Entity.init("Euml;", Entity.Value{ .Rune = 0xcb }),
Entity.init("Exists;", Entity.Value{ .Rune = 0x2203 }),
Entity.init("ExponentialE;", Entity.Value{ .Rune = 0x2147 }),
Entity.init("Fcy;", Entity.Value{ .Rune = 0x424 }),
Entity.init("Ffr;", Entity.Value{ .Rune = 0x1d509 }),
Entity.init("FilledSmallSquare;", Entity.Value{ .Rune = 0x25fc }),
Entity.init("FilledVerySmallSquare;", Entity.Value{ .Rune = 0x25aa }),
Entity.init("Fopf;", Entity.Value{ .Rune = 0x1d53d }),
Entity.init("ForAll;", Entity.Value{ .Rune = 0x2200 }),
Entity.init("Fouriertrf;", Entity.Value{ .Rune = 0x2131 }),
Entity.init("Fscr;", Entity.Value{ .Rune = 0x2131 }),
Entity.init("GJcy;", Entity.Value{ .Rune = 0x403 }),
Entity.init("GT", Entity.Value{ .Rune = 0x3e }),
Entity.init("GT;", Entity.Value{ .Rune = 0x3e }),
Entity.init("Gamma;", Entity.Value{ .Rune = 0x393 }),
Entity.init("Gammad;", Entity.Value{ .Rune = 0x3dc }),
Entity.init("Gbreve;", Entity.Value{ .Rune = 0x11e }),
Entity.init("Gcedil;", Entity.Value{ .Rune = 0x122 }),
Entity.init("Gcirc;", Entity.Value{ .Rune = 0x11c }),
Entity.init("Gcy;", Entity.Value{ .Rune = 0x413 }),
Entity.init("Gdot;", Entity.Value{ .Rune = 0x120 }),
Entity.init("Gfr;", Entity.Value{ .Rune = 0x1d50a }),
Entity.init("Gg;", Entity.Value{ .Rune = 0x22d9 }),
Entity.init("Gopf;", Entity.Value{ .Rune = 0x1d53e }),
Entity.init("GreaterEqual;", Entity.Value{ .Rune = 0x2265 }),
Entity.init("GreaterEqualLess;", Entity.Value{ .Rune = 0x22db }),
Entity.init("GreaterFullEqual;", Entity.Value{ .Rune = 0x2267 }),
Entity.init("GreaterGreater;", Entity.Value{ .Rune = 0x2aa2 }),
Entity.init("GreaterLess;", Entity.Value{ .Rune = 0x2277 }),
Entity.init("GreaterSlantEqual;", Entity.Value{ .Rune = 0x2a7e }),
Entity.init("GreaterTilde;", Entity.Value{ .Rune = 0x2273 }),
Entity.init("Gscr;", Entity.Value{ .Rune = 0x1d4a2 }),
Entity.init("Gt;", Entity.Value{ .Rune = 0x226b }),
Entity.init("HARDcy;", Entity.Value{ .Rune = 0x42a }),
Entity.init("Hacek;", Entity.Value{ .Rune = 0x2c7 }),
Entity.init("Hat;", Entity.Value{ .Rune = 0x5e }),
Entity.init("Hcirc;", Entity.Value{ .Rune = 0x124 }),
Entity.init("Hfr;", Entity.Value{ .Rune = 0x210c }),
Entity.init("HilbertSpace;", Entity.Value{ .Rune = 0x210b }),
Entity.init("Hopf;", Entity.Value{ .Rune = 0x210d }),
Entity.init("HorizontalLine;", Entity.Value{ .Rune = 0x2500 }),
Entity.init("Hscr;", Entity.Value{ .Rune = 0x210b }),
Entity.init("Hstrok;", Entity.Value{ .Rune = 0x126 }),
Entity.init("HumpDownHump;", Entity.Value{ .Rune = 0x224e }),
Entity.init("HumpEqual;", Entity.Value{ .Rune = 0x224f }),
Entity.init("IEcy;", Entity.Value{ .Rune = 0x415 }),
Entity.init("IJlig;", Entity.Value{ .Rune = 0x132 }),
Entity.init("IOcy;", Entity.Value{ .Rune = 0x401 }),
Entity.init("Iacute", Entity.Value{ .Rune = 0xcd }),
Entity.init("Iacute;", Entity.Value{ .Rune = 0xcd }),
Entity.init("Icirc", Entity.Value{ .Rune = 0xce }),
Entity.init("Icirc;", Entity.Value{ .Rune = 0xce }),
Entity.init("Icy;", Entity.Value{ .Rune = 0x418 }),
Entity.init("Idot;", Entity.Value{ .Rune = 0x130 }),
Entity.init("Ifr;", Entity.Value{ .Rune = 0x2111 }),
Entity.init("Igrave", Entity.Value{ .Rune = 0xcc }),
Entity.init("Igrave;", Entity.Value{ .Rune = 0xcc }),
Entity.init("Im;", Entity.Value{ .Rune = 0x2111 }),
Entity.init("Imacr;", Entity.Value{ .Rune = 0x12a }),
Entity.init("ImaginaryI;", Entity.Value{ .Rune = 0x2148 }),
Entity.init("Implies;", Entity.Value{ .Rune = 0x21d2 }),
Entity.init("Int;", Entity.Value{ .Rune = 0x222c }),
Entity.init("Integral;", Entity.Value{ .Rune = 0x222b }),
Entity.init("Intersection;", Entity.Value{ .Rune = 0x22c2 }),
Entity.init("InvisibleComma;", Entity.Value{ .Rune = 0x2063 }),
Entity.init("InvisibleTimes;", Entity.Value{ .Rune = 0x2062 }),
Entity.init("Iogon;", Entity.Value{ .Rune = 0x12e }),
Entity.init("Iopf;", Entity.Value{ .Rune = 0x1d540 }),
Entity.init("Iota;", Entity.Value{ .Rune = 0x399 }),
Entity.init("Iscr;", Entity.Value{ .Rune = 0x2110 }),
Entity.init("Itilde;", Entity.Value{ .Rune = 0x128 }),
Entity.init("Iukcy;", Entity.Value{ .Rune = 0x406 }),
Entity.init("Iuml", Entity.Value{ .Rune = 0xcf }),
Entity.init("Iuml;", Entity.Value{ .Rune = 0xcf }),
Entity.init("Jcirc;", Entity.Value{ .Rune = 0x134 }),
Entity.init("Jcy;", Entity.Value{ .Rune = 0x419 }),
Entity.init("Jfr;", Entity.Value{ .Rune = 0x1d50d }),
Entity.init("Jopf;", Entity.Value{ .Rune = 0x1d541 }),
Entity.init("Jscr;", Entity.Value{ .Rune = 0x1d4a5 }),
Entity.init("Jsercy;", Entity.Value{ .Rune = 0x408 }),
Entity.init("Jukcy;", Entity.Value{ .Rune = 0x404 }),
Entity.init("KHcy;", Entity.Value{ .Rune = 0x425 }),
Entity.init("KJcy;", Entity.Value{ .Rune = 0x40c }),
Entity.init("Kappa;", Entity.Value{ .Rune = 0x39a }),
Entity.init("Kcedil;", Entity.Value{ .Rune = 0x136 }),
Entity.init("Kcy;", Entity.Value{ .Rune = 0x41a }),
Entity.init("Kfr;", Entity.Value{ .Rune = 0x1d50e }),
Entity.init("Kopf;", Entity.Value{ .Rune = 0x1d542 }),
Entity.init("Kscr;", Entity.Value{ .Rune = 0x1d4a6 }),
Entity.init("LJcy;", Entity.Value{ .Rune = 0x409 }),
Entity.init("LT", Entity.Value{ .Rune = 0x3c }),
Entity.init("LT;", Entity.Value{ .Rune = 0x3c }),
Entity.init("Lacute;", Entity.Value{ .Rune = 0x139 }),
Entity.init("Lambda;", Entity.Value{ .Rune = 0x39b }),
Entity.init("Lang;", Entity.Value{ .Rune = 0x27ea }),
Entity.init("Laplacetrf;", Entity.Value{ .Rune = 0x2112 }),
Entity.init("Larr;", Entity.Value{ .Rune = 0x219e }),
Entity.init("Lcaron;", Entity.Value{ .Rune = 0x13d }),
Entity.init("Lcedil;", Entity.Value{ .Rune = 0x13b }),
Entity.init("Lcy;", Entity.Value{ .Rune = 0x41b }),
Entity.init("LeftAngleBracket;", Entity.Value{ .Rune = 0x27e8 }),
Entity.init("LeftArrow;", Entity.Value{ .Rune = 0x2190 }),
Entity.init("LeftArrowBar;", Entity.Value{ .Rune = 0x21e4 }),
Entity.init("LeftArrowRightArrow;", Entity.Value{ .Rune = 0x21c6 }),
Entity.init("LeftCeiling;", Entity.Value{ .Rune = 0x2308 }),
Entity.init("LeftDoubleBracket;", Entity.Value{ .Rune = 0x27e6 }),
Entity.init("LeftDownTeeVector;", Entity.Value{ .Rune = 0x2961 }),
Entity.init("LeftDownVector;", Entity.Value{ .Rune = 0x21c3 }),
Entity.init("LeftDownVectorBar;", Entity.Value{ .Rune = 0x2959 }),
Entity.init("LeftFloor;", Entity.Value{ .Rune = 0x230a }),
Entity.init("LeftRightArrow;", Entity.Value{ .Rune = 0x2194 }),
Entity.init("LeftRightVector;", Entity.Value{ .Rune = 0x294e }),
Entity.init("LeftTee;", Entity.Value{ .Rune = 0x22a3 }),
Entity.init("LeftTeeArrow;", Entity.Value{ .Rune = 0x21a4 }),
Entity.init("LeftTeeVector;", Entity.Value{ .Rune = 0x295a }),
Entity.init("LeftTriangle;", Entity.Value{ .Rune = 0x22b2 }),
Entity.init("LeftTriangleBar;", Entity.Value{ .Rune = 0x29cf }),
Entity.init("LeftTriangleEqual;", Entity.Value{ .Rune = 0x22b4 }),
Entity.init("LeftUpDownVector;", Entity.Value{ .Rune = 0x2951 }),
Entity.init("LeftUpTeeVector;", Entity.Value{ .Rune = 0x2960 }),
Entity.init("LeftUpVector;", Entity.Value{ .Rune = 0x21bf }),
Entity.init("LeftUpVectorBar;", Entity.Value{ .Rune = 0x2958 }),
Entity.init("LeftVector;", Entity.Value{ .Rune = 0x21bc }),
Entity.init("LeftVectorBar;", Entity.Value{ .Rune = 0x2952 }),
Entity.init("Leftarrow;", Entity.Value{ .Rune = 0x21d0 }),
Entity.init("Leftrightarrow;", Entity.Value{ .Rune = 0x21d4 }),
Entity.init("LessEqualGreater;", Entity.Value{ .Rune = 0x22da }),
Entity.init("LessFullEqual;", Entity.Value{ .Rune = 0x2266 }),
Entity.init("LessGreater;", Entity.Value{ .Rune = 0x2276 }),
Entity.init("LessLess;", Entity.Value{ .Rune = 0x2aa1 }),
Entity.init("LessSlantEqual;", Entity.Value{ .Rune = 0x2a7d }),
Entity.init("LessTilde;", Entity.Value{ .Rune = 0x2272 }),
Entity.init("Lfr;", Entity.Value{ .Rune = 0x1d50f }),
Entity.init("Ll;", Entity.Value{ .Rune = 0x22d8 }),
Entity.init("Lleftarrow;", Entity.Value{ .Rune = 0x21da }),
Entity.init("Lmidot;", Entity.Value{ .Rune = 0x13f }),
Entity.init("LongLeftArrow;", Entity.Value{ .Rune = 0x27f5 }),
Entity.init("LongLeftRightArrow;", Entity.Value{ .Rune = 0x27f7 }),
Entity.init("LongRightArrow;", Entity.Value{ .Rune = 0x27f6 }),
Entity.init("Longleftarrow;", Entity.Value{ .Rune = 0x27f8 }),
Entity.init("Longleftrightarrow;", Entity.Value{ .Rune = 0x27fa }),
Entity.init("Longrightarrow;", Entity.Value{ .Rune = 0x27f9 }),
Entity.init("Lopf;", Entity.Value{ .Rune = 0x1d543 }),
Entity.init("LowerLeftArrow;", Entity.Value{ .Rune = 0x2199 }),
Entity.init("LowerRightArrow;", Entity.Value{ .Rune = 0x2198 }),
Entity.init("Lscr;", Entity.Value{ .Rune = 0x2112 }),
Entity.init("Lsh;", Entity.Value{ .Rune = 0x21b0 }),
Entity.init("Lstrok;", Entity.Value{ .Rune = 0x141 }),
Entity.init("Lt;", Entity.Value{ .Rune = 0x226a }),
Entity.init("Map;", Entity.Value{ .Rune = 0x2905 }),
Entity.init("Mcy;", Entity.Value{ .Rune = 0x41c }),
Entity.init("MediumSpace;", Entity.Value{ .Rune = 0x205f }),
Entity.init("Mellintrf;", Entity.Value{ .Rune = 0x2133 }),
Entity.init("Mfr;", Entity.Value{ .Rune = 0x1d510 }),
Entity.init("MinusPlus;", Entity.Value{ .Rune = 0x2213 }),
Entity.init("Mopf;", Entity.Value{ .Rune = 0x1d544 }),
Entity.init("Mscr;", Entity.Value{ .Rune = 0x2133 }),
Entity.init("Mu;", Entity.Value{ .Rune = 0x39c }),
Entity.init("NJcy;", Entity.Value{ .Rune = 0x40a }),
Entity.init("Nacute;", Entity.Value{ .Rune = 0x143 }),
Entity.init("Ncaron;", Entity.Value{ .Rune = 0x147 }),
Entity.init("Ncedil;", Entity.Value{ .Rune = 0x145 }),
Entity.init("Ncy;", Entity.Value{ .Rune = 0x41d }),
Entity.init("NegativeMediumSpace;", Entity.Value{ .Rune = 0x200b }),
Entity.init("NegativeThickSpace;", Entity.Value{ .Rune = 0x200b }),
Entity.init("NegativeThinSpace;", Entity.Value{ .Rune = 0x200b }),
Entity.init("NegativeVeryThinSpace;", Entity.Value{ .Rune = 0x200b }),
Entity.init("NestedGreaterGreater;", Entity.Value{ .Rune = 0x226b }),
Entity.init("NestedLessLess;", Entity.Value{ .Rune = 0x226a }),
Entity.init("NewLine;", Entity.Value{ .Rune = 0xa }),
Entity.init("Nfr;", Entity.Value{ .Rune = 0x1d511 }),
Entity.init("NoBreak;", Entity.Value{ .Rune = 0x2060 }),
Entity.init("NonBreakingSpace;", Entity.Value{ .Rune = 0xa0 }),
Entity.init("Nopf;", Entity.Value{ .Rune = 0x2115 }),
Entity.init("Not;", Entity.Value{ .Rune = 0x2aec }),
Entity.init("NotCongruent;", Entity.Value{ .Rune = 0x2262 }),
Entity.init("NotCupCap;", Entity.Value{ .Rune = 0x226d }),
Entity.init("NotDoubleVerticalBar;", Entity.Value{ .Rune = 0x2226 }),
Entity.init("NotElement;", Entity.Value{ .Rune = 0x2209 }),
Entity.init("NotEqual;", Entity.Value{ .Rune = 0x2260 }),
Entity.init("NotExists;", Entity.Value{ .Rune = 0x2204 }),
Entity.init("NotGreater;", Entity.Value{ .Rune = 0x226f }),
Entity.init("NotGreaterEqual;", Entity.Value{ .Rune = 0x2271 }),
Entity.init("NotGreaterLess;", Entity.Value{ .Rune = 0x2279 }),
Entity.init("NotGreaterTilde;", Entity.Value{ .Rune = 0x2275 }),
Entity.init("NotLeftTriangle;", Entity.Value{ .Rune = 0x22ea }),
Entity.init("NotLeftTriangleEqual;", Entity.Value{ .Rune = 0x22ec }),
Entity.init("NotLess;", Entity.Value{ .Rune = 0x226e }),
Entity.init("NotLessEqual;", Entity.Value{ .Rune = 0x2270 }),
Entity.init("NotLessGreater;", Entity.Value{ .Rune = 0x2278 }),
Entity.init("NotLessTilde;", Entity.Value{ .Rune = 0x2274 }),
Entity.init("NotPrecedes;", Entity.Value{ .Rune = 0x2280 }),
Entity.init("NotPrecedesSlantEqual;", Entity.Value{ .Rune = 0x22e0 }),
Entity.init("NotReverseElement;", Entity.Value{ .Rune = 0x220c }),
Entity.init("NotRightTriangle;", Entity.Value{ .Rune = 0x22eb }),
Entity.init("NotRightTriangleEqual;", Entity.Value{ .Rune = 0x22ed }),
Entity.init("NotSquareSubsetEqual;", Entity.Value{ .Rune = 0x22e2 }),
Entity.init("NotSquareSupersetEqual;", Entity.Value{ .Rune = 0x22e3 }),
Entity.init("NotSubsetEqual;", Entity.Value{ .Rune = 0x2288 }),
Entity.init("NotSucceeds;", Entity.Value{ .Rune = 0x2281 }),
Entity.init("NotSucceedsSlantEqual;", Entity.Value{ .Rune = 0x22e1 }),
Entity.init("NotSupersetEqual;", Entity.Value{ .Rune = 0x2289 }),
Entity.init("NotTilde;", Entity.Value{ .Rune = 0x2241 }),
Entity.init("NotTildeEqual;", Entity.Value{ .Rune = 0x2244 }),
Entity.init("NotTildeFullEqual;", Entity.Value{ .Rune = 0x2247 }),
Entity.init("NotTildeTilde;", Entity.Value{ .Rune = 0x2249 }),
Entity.init("NotVerticalBar;", Entity.Value{ .Rune = 0x2224 }),
Entity.init("Nscr;", Entity.Value{ .Rune = 0x1d4a9 }),
Entity.init("Ntilde", Entity.Value{ .Rune = 0xd1 }),
Entity.init("Ntilde;", Entity.Value{ .Rune = 0xd1 }),
Entity.init("Nu;", Entity.Value{ .Rune = 0x39d }),
Entity.init("OElig;", Entity.Value{ .Rune = 0x152 }),
Entity.init("Oacute", Entity.Value{ .Rune = 0xd3 }),
Entity.init("Oacute;", Entity.Value{ .Rune = 0xd3 }),
Entity.init("Ocirc", Entity.Value{ .Rune = 0xd4 }),
Entity.init("Ocirc;", Entity.Value{ .Rune = 0xd4 }),
Entity.init("Ocy;", Entity.Value{ .Rune = 0x41e }),
Entity.init("Odblac;", Entity.Value{ .Rune = 0x150 }),
Entity.init("Ofr;", Entity.Value{ .Rune = 0x1d512 }),
Entity.init("Ograve", Entity.Value{ .Rune = 0xd2 }),
Entity.init("Ograve;", Entity.Value{ .Rune = 0xd2 }),
Entity.init("Omacr;", Entity.Value{ .Rune = 0x14c }),
Entity.init("Omega;", Entity.Value{ .Rune = 0x3a9 }),
Entity.init("Omicron;", Entity.Value{ .Rune = 0x39f }),
Entity.init("Oopf;", Entity.Value{ .Rune = 0x1d546 }),
Entity.init("OpenCurlyDoubleQuote;", Entity.Value{ .Rune = 0x201c }),
Entity.init("OpenCurlyQuote;", Entity.Value{ .Rune = 0x2018 }),
Entity.init("Or;", Entity.Value{ .Rune = 0x2a54 }),
Entity.init("Oscr;", Entity.Value{ .Rune = 0x1d4aa }),
Entity.init("Oslash", Entity.Value{ .Rune = 0xd8 }),
Entity.init("Oslash;", Entity.Value{ .Rune = 0xd8 }),
Entity.init("Otilde", Entity.Value{ .Rune = 0xd5 }),
Entity.init("Otilde;", Entity.Value{ .Rune = 0xd5 }),
Entity.init("Otimes;", Entity.Value{ .Rune = 0x2a37 }),
Entity.init("Ouml", Entity.Value{ .Rune = 0xd6 }),
Entity.init("Ouml;", Entity.Value{ .Rune = 0xd6 }),
Entity.init("OverBar;", Entity.Value{ .Rune = 0x203e }),
Entity.init("OverBrace;", Entity.Value{ .Rune = 0x23de }),
Entity.init("OverBracket;", Entity.Value{ .Rune = 0x23b4 }),
Entity.init("OverParenthesis;", Entity.Value{ .Rune = 0x23dc }),
Entity.init("PartialD;", Entity.Value{ .Rune = 0x2202 }),
Entity.init("Pcy;", Entity.Value{ .Rune = 0x41f }),
Entity.init("Pfr;", Entity.Value{ .Rune = 0x1d513 }),
Entity.init("Phi;", Entity.Value{ .Rune = 0x3a6 }),
Entity.init("Pi;", Entity.Value{ .Rune = 0x3a0 }),
Entity.init("PlusMinus;", Entity.Value{ .Rune = 0xb1 }),
Entity.init("Poincareplane;", Entity.Value{ .Rune = 0x210c }),
Entity.init("Popf;", Entity.Value{ .Rune = 0x2119 }),
Entity.init("Pr;", Entity.Value{ .Rune = 0x2abb }),
Entity.init("Precedes;", Entity.Value{ .Rune = 0x227a }),
Entity.init("PrecedesEqual;", Entity.Value{ .Rune = 0x2aaf }),
Entity.init("PrecedesSlantEqual;", Entity.Value{ .Rune = 0x227c }),
Entity.init("PrecedesTilde;", Entity.Value{ .Rune = 0x227e }),
Entity.init("Prime;", Entity.Value{ .Rune = 0x2033 }),
Entity.init("Product;", Entity.Value{ .Rune = 0x220f }),
Entity.init("Proportion;", Entity.Value{ .Rune = 0x2237 }),
Entity.init("Proportional;", Entity.Value{ .Rune = 0x221d }),
Entity.init("Pscr;", Entity.Value{ .Rune = 0x1d4ab }),
Entity.init("Psi;", Entity.Value{ .Rune = 0x3a8 }),
Entity.init("QUOT", Entity.Value{ .Rune = 0x22 }),
Entity.init("QUOT;", Entity.Value{ .Rune = 0x22 }),
Entity.init("Qfr;", Entity.Value{ .Rune = 0x1d514 }),
Entity.init("Qopf;", Entity.Value{ .Rune = 0x211a }),
Entity.init("Qscr;", Entity.Value{ .Rune = 0x1d4ac }),
Entity.init("RBarr;", Entity.Value{ .Rune = 0x2910 }),
Entity.init("REG", Entity.Value{ .Rune = 0xae }),
Entity.init("REG;", Entity.Value{ .Rune = 0xae }),
Entity.init("Racute;", Entity.Value{ .Rune = 0x154 }),
Entity.init("Rang;", Entity.Value{ .Rune = 0x27eb }),
Entity.init("Rarr;", Entity.Value{ .Rune = 0x21a0 }),
Entity.init("Rarrtl;", Entity.Value{ .Rune = 0x2916 }),
Entity.init("Rcaron;", Entity.Value{ .Rune = 0x158 }),
Entity.init("Rcedil;", Entity.Value{ .Rune = 0x156 }),
Entity.init("Rcy;", Entity.Value{ .Rune = 0x420 }),
Entity.init("Re;", Entity.Value{ .Rune = 0x211c }),
Entity.init("ReverseElement;", Entity.Value{ .Rune = 0x220b }),
Entity.init("ReverseEquilibrium;", Entity.Value{ .Rune = 0x21cb }),
Entity.init("ReverseUpEquilibrium;", Entity.Value{ .Rune = 0x296f }),
Entity.init("Rfr;", Entity.Value{ .Rune = 0x211c }),
Entity.init("Rho;", Entity.Value{ .Rune = 0x3a1 }),
Entity.init("RightAngleBracket;", Entity.Value{ .Rune = 0x27e9 }),
Entity.init("RightArrow;", Entity.Value{ .Rune = 0x2192 }),
Entity.init("RightArrowBar;", Entity.Value{ .Rune = 0x21e5 }),
Entity.init("RightArrowLeftArrow;", Entity.Value{ .Rune = 0x21c4 }),
Entity.init("RightCeiling;", Entity.Value{ .Rune = 0x2309 }),
Entity.init("RightDoubleBracket;", Entity.Value{ .Rune = 0x27e7 }),
Entity.init("RightDownTeeVector;", Entity.Value{ .Rune = 0x295d }),
Entity.init("RightDownVector;", Entity.Value{ .Rune = 0x21c2 }),
Entity.init("RightDownVectorBar;", Entity.Value{ .Rune = 0x2955 }),
Entity.init("RightFloor;", Entity.Value{ .Rune = 0x230b }),
Entity.init("RightTee;", Entity.Value{ .Rune = 0x22a2 }),
Entity.init("RightTeeArrow;", Entity.Value{ .Rune = 0x21a6 }),
Entity.init("RightTeeVector;", Entity.Value{ .Rune = 0x295b }),
Entity.init("RightTriangle;", Entity.Value{ .Rune = 0x22b3 }),
Entity.init("RightTriangleBar;", Entity.Value{ .Rune = 0x29d0 }),
Entity.init("RightTriangleEqual;", Entity.Value{ .Rune = 0x22b5 }),
Entity.init("RightUpDownVector;", Entity.Value{ .Rune = 0x294f }),
Entity.init("RightUpTeeVector;", Entity.Value{ .Rune = 0x295c }),
Entity.init("RightUpVector;", Entity.Value{ .Rune = 0x21be }),
Entity.init("RightUpVectorBar;", Entity.Value{ .Rune = 0x2954 }),
Entity.init("RightVector;", Entity.Value{ .Rune = 0x21c0 }),
Entity.init("RightVectorBar;", Entity.Value{ .Rune = 0x2953 }),
Entity.init("Rightarrow;", Entity.Value{ .Rune = 0x21d2 }),
Entity.init("Ropf;", Entity.Value{ .Rune = 0x211d }),
Entity.init("RoundImplies;", Entity.Value{ .Rune = 0x2970 }),
Entity.init("Rrightarrow;", Entity.Value{ .Rune = 0x21db }),
Entity.init("Rscr;", Entity.Value{ .Rune = 0x211b }),
Entity.init("Rsh;", Entity.Value{ .Rune = 0x21b1 }),
Entity.init("RuleDelayed;", Entity.Value{ .Rune = 0x29f4 }),
Entity.init("SHCHcy;", Entity.Value{ .Rune = 0x429 }),
Entity.init("SHcy;", Entity.Value{ .Rune = 0x428 }),
Entity.init("SOFTcy;", Entity.Value{ .Rune = 0x42c }),
Entity.init("Sacute;", Entity.Value{ .Rune = 0x15a }),
Entity.init("Sc;", Entity.Value{ .Rune = 0x2abc }),
Entity.init("Scaron;", Entity.Value{ .Rune = 0x160 }),
Entity.init("Scedil;", Entity.Value{ .Rune = 0x15e }),
Entity.init("Scirc;", Entity.Value{ .Rune = 0x15c }),
Entity.init("Scy;", Entity.Value{ .Rune = 0x421 }),
Entity.init("Sfr;", Entity.Value{ .Rune = 0x1d516 }),
Entity.init("ShortDownArrow;", Entity.Value{ .Rune = 0x2193 }),
Entity.init("ShortLeftArrow;", Entity.Value{ .Rune = 0x2190 }),
Entity.init("ShortRightArrow;", Entity.Value{ .Rune = 0x2192 }),
Entity.init("ShortUpArrow;", Entity.Value{ .Rune = 0x2191 }),
Entity.init("Sigma;", Entity.Value{ .Rune = 0x3a3 }),
Entity.init("SmallCircle;", Entity.Value{ .Rune = 0x2218 }),
Entity.init("Sopf;", Entity.Value{ .Rune = 0x1d54a }),
Entity.init("Sqrt;", Entity.Value{ .Rune = 0x221a }),
Entity.init("Square;", Entity.Value{ .Rune = 0x25a1 }),
Entity.init("SquareIntersection;", Entity.Value{ .Rune = 0x2293 }),
Entity.init("SquareSubset;", Entity.Value{ .Rune = 0x228f }),
Entity.init("SquareSubsetEqual;", Entity.Value{ .Rune = 0x2291 }),
Entity.init("SquareSuperset;", Entity.Value{ .Rune = 0x2290 }),
Entity.init("SquareSupersetEqual;", Entity.Value{ .Rune = 0x2292 }),
Entity.init("SquareUnion;", Entity.Value{ .Rune = 0x2294 }),
Entity.init("Sscr;", Entity.Value{ .Rune = 0x1d4ae }),
Entity.init("Star;", Entity.Value{ .Rune = 0x22c6 }),
Entity.init("Sub;", Entity.Value{ .Rune = 0x22d0 }),
Entity.init("Subset;", Entity.Value{ .Rune = 0x22d0 }),
Entity.init("SubsetEqual;", Entity.Value{ .Rune = 0x2286 }),
Entity.init("Succeeds;", Entity.Value{ .Rune = 0x227b }),
Entity.init("SucceedsEqual;", Entity.Value{ .Rune = 0x2ab0 }),
Entity.init("SucceedsSlantEqual;", Entity.Value{ .Rune = 0x227d }),
Entity.init("SucceedsTilde;", Entity.Value{ .Rune = 0x227f }),
Entity.init("SuchThat;", Entity.Value{ .Rune = 0x220b }),
Entity.init("Sum;", Entity.Value{ .Rune = 0x2211 }),
Entity.init("Sup;", Entity.Value{ .Rune = 0x22d1 }),
Entity.init("Superset;", Entity.Value{ .Rune = 0x2283 }),
Entity.init("SupersetEqual;", Entity.Value{ .Rune = 0x2287 }),
Entity.init("Supset;", Entity.Value{ .Rune = 0x22d1 }),
Entity.init("THORN", Entity.Value{ .Rune = 0xde }),
Entity.init("THORN;", Entity.Value{ .Rune = 0xde }),
Entity.init("TRADE;", Entity.Value{ .Rune = 0x2122 }),
Entity.init("TSHcy;", Entity.Value{ .Rune = 0x40b }),
Entity.init("TScy;", Entity.Value{ .Rune = 0x426 }),
Entity.init("Tab;", Entity.Value{ .Rune = 0x9 }),
Entity.init("Tau;", Entity.Value{ .Rune = 0x3a4 }),
Entity.init("Tcaron;", Entity.Value{ .Rune = 0x164 }),
Entity.init("Tcedil;", Entity.Value{ .Rune = 0x162 }),
Entity.init("Tcy;", Entity.Value{ .Rune = 0x422 }),
Entity.init("Tfr;", Entity.Value{ .Rune = 0x1d517 }),
Entity.init("Therefore;", Entity.Value{ .Rune = 0x2234 }),
Entity.init("Theta;", Entity.Value{ .Rune = 0x398 }),
Entity.init("ThinSpace;", Entity.Value{ .Rune = 0x2009 }),
Entity.init("Tilde;", Entity.Value{ .Rune = 0x223c }),
Entity.init("TildeEqual;", Entity.Value{ .Rune = 0x2243 }),
Entity.init("TildeFullEqual;", Entity.Value{ .Rune = 0x2245 }),
Entity.init("TildeTilde;", Entity.Value{ .Rune = 0x2248 }),
Entity.init("Topf;", Entity.Value{ .Rune = 0x1d54b }),
Entity.init("TripleDot;", Entity.Value{ .Rune = 0x20db }),
Entity.init("Tscr;", Entity.Value{ .Rune = 0x1d4af }),
Entity.init("Tstrok;", Entity.Value{ .Rune = 0x166 }),
Entity.init("Uacute", Entity.Value{ .Rune = 0xda }),
Entity.init("Uacute;", Entity.Value{ .Rune = 0xda }),
Entity.init("Uarr;", Entity.Value{ .Rune = 0x219f }),
Entity.init("Uarrocir;", Entity.Value{ .Rune = 0x2949 }),
Entity.init("Ubrcy;", Entity.Value{ .Rune = 0x40e }),
Entity.init("Ubreve;", Entity.Value{ .Rune = 0x16c }),
Entity.init("Ucirc", Entity.Value{ .Rune = 0xdb }),
Entity.init("Ucirc;", Entity.Value{ .Rune = 0xdb }),
Entity.init("Ucy;", Entity.Value{ .Rune = 0x423 }),
Entity.init("Udblac;", Entity.Value{ .Rune = 0x170 }),
Entity.init("Ufr;", Entity.Value{ .Rune = 0x1d518 }),
Entity.init("Ugrave", Entity.Value{ .Rune = 0xd9 }),
Entity.init("Ugrave;", Entity.Value{ .Rune = 0xd9 }),
Entity.init("Umacr;", Entity.Value{ .Rune = 0x16a }),
Entity.init("UnderBar;", Entity.Value{ .Rune = 0x5f }),
Entity.init("UnderBrace;", Entity.Value{ .Rune = 0x23df }),
Entity.init("UnderBracket;", Entity.Value{ .Rune = 0x23b5 }),
Entity.init("UnderParenthesis;", Entity.Value{ .Rune = 0x23dd }),
Entity.init("Union;", Entity.Value{ .Rune = 0x22c3 }),
Entity.init("UnionPlus;", Entity.Value{ .Rune = 0x228e }),
Entity.init("Uogon;", Entity.Value{ .Rune = 0x172 }),
Entity.init("Uopf;", Entity.Value{ .Rune = 0x1d54c }),
Entity.init("UpArrow;", Entity.Value{ .Rune = 0x2191 }),
Entity.init("UpArrowBar;", Entity.Value{ .Rune = 0x2912 }),
Entity.init("UpArrowDownArrow;", Entity.Value{ .Rune = 0x21c5 }),
Entity.init("UpDownArrow;", Entity.Value{ .Rune = 0x2195 }),
Entity.init("UpEquilibrium;", Entity.Value{ .Rune = 0x296e }),
Entity.init("UpTee;", Entity.Value{ .Rune = 0x22a5 }),
Entity.init("UpTeeArrow;", Entity.Value{ .Rune = 0x21a5 }),
Entity.init("Uparrow;", Entity.Value{ .Rune = 0x21d1 }),
Entity.init("Updownarrow;", Entity.Value{ .Rune = 0x21d5 }),
Entity.init("UpperLeftArrow;", Entity.Value{ .Rune = 0x2196 }),
Entity.init("UpperRightArrow;", Entity.Value{ .Rune = 0x2197 }),
Entity.init("Upsi;", Entity.Value{ .Rune = 0x3d2 }),
Entity.init("Upsilon;", Entity.Value{ .Rune = 0x3a5 }),
Entity.init("Uring;", Entity.Value{ .Rune = 0x16e }),
Entity.init("Uscr;", Entity.Value{ .Rune = 0x1d4b0 }),
Entity.init("Utilde;", Entity.Value{ .Rune = 0x168 }),
Entity.init("Uuml", Entity.Value{ .Rune = 0xdc }),
Entity.init("Uuml;", Entity.Value{ .Rune = 0xdc }),
Entity.init("VDash;", Entity.Value{ .Rune = 0x22ab }),
Entity.init("Vbar;", Entity.Value{ .Rune = 0x2aeb }),
Entity.init("Vcy;", Entity.Value{ .Rune = 0x412 }),
Entity.init("Vdash;", Entity.Value{ .Rune = 0x22a9 }),
Entity.init("Vdashl;", Entity.Value{ .Rune = 0x2ae6 }),
Entity.init("Vee;", Entity.Value{ .Rune = 0x22c1 }),
Entity.init("Verbar;", Entity.Value{ .Rune = 0x2016 }),
Entity.init("Vert;", Entity.Value{ .Rune = 0x2016 }),
Entity.init("VerticalBar;", Entity.Value{ .Rune = 0x2223 }),
Entity.init("VerticalLine;", Entity.Value{ .Rune = 0x7c }),
Entity.init("VerticalSeparator;", Entity.Value{ .Rune = 0x2758 }),
Entity.init("VerticalTilde;", Entity.Value{ .Rune = 0x2240 }),
Entity.init("VeryThinSpace;", Entity.Value{ .Rune = 0x200a }),
Entity.init("Vfr;", Entity.Value{ .Rune = 0x1d519 }),
Entity.init("Vopf;", Entity.Value{ .Rune = 0x1d54d }),
Entity.init("Vscr;", Entity.Value{ .Rune = 0x1d4b1 }),
Entity.init("Vvdash;", Entity.Value{ .Rune = 0x22aa }),
Entity.init("Wcirc;", Entity.Value{ .Rune = 0x174 }),
Entity.init("Wedge;", Entity.Value{ .Rune = 0x22c0 }),
Entity.init("Wfr;", Entity.Value{ .Rune = 0x1d51a }),
Entity.init("Wopf;", Entity.Value{ .Rune = 0x1d54e }),
Entity.init("Wscr;", Entity.Value{ .Rune = 0x1d4b2 }),
Entity.init("Xfr;", Entity.Value{ .Rune = 0x1d51b }),
Entity.init("Xi;", Entity.Value{ .Rune = 0x39e }),
Entity.init("Xopf;", Entity.Value{ .Rune = 0x1d54f }),
Entity.init("Xscr;", Entity.Value{ .Rune = 0x1d4b3 }),
Entity.init("YAcy;", Entity.Value{ .Rune = 0x42f }),
Entity.init("YIcy;", Entity.Value{ .Rune = 0x407 }),
Entity.init("YUcy;", Entity.Value{ .Rune = 0x42e }),
Entity.init("Yacute", Entity.Value{ .Rune = 0xdd }),
Entity.init("Yacute;", Entity.Value{ .Rune = 0xdd }),
Entity.init("Ycirc;", Entity.Value{ .Rune = 0x176 }),
Entity.init("Ycy;", Entity.Value{ .Rune = 0x42b }),
Entity.init("Yfr;", Entity.Value{ .Rune = 0x1d51c }),
Entity.init("Yopf;", Entity.Value{ .Rune = 0x1d550 }),
Entity.init("Yscr;", Entity.Value{ .Rune = 0x1d4b4 }),
Entity.init("Yuml;", Entity.Value{ .Rune = 0x178 }),
Entity.init("ZHcy;", Entity.Value{ .Rune = 0x416 }),
Entity.init("Zacute;", Entity.Value{ .Rune = 0x179 }),
Entity.init("Zcaron;", Entity.Value{ .Rune = 0x17d }),
Entity.init("Zcy;", Entity.Value{ .Rune = 0x417 }),
Entity.init("Zdot;", Entity.Value{ .Rune = 0x17b }),
Entity.init("ZeroWidthSpace;", Entity.Value{ .Rune = 0x200b }),
Entity.init("Zeta;", Entity.Value{ .Rune = 0x396 }),
Entity.init("Zfr;", Entity.Value{ .Rune = 0x2128 }),
Entity.init("Zopf;", Entity.Value{ .Rune = 0x2124 }),
Entity.init("Zscr;", Entity.Value{ .Rune = 0x1d4b5 }),
Entity.init("aacute", Entity.Value{ .Rune = 0xe1 }),
Entity.init("aacute;", Entity.Value{ .Rune = 0xe1 }),
Entity.init("abreve;", Entity.Value{ .Rune = 0x103 }),
Entity.init("ac;", Entity.Value{ .Rune = 0x223e }),
Entity.init("acd;", Entity.Value{ .Rune = 0x223f }),
Entity.init("acirc", Entity.Value{ .Rune = 0xe2 }),
Entity.init("acirc;", Entity.Value{ .Rune = 0xe2 }),
Entity.init("acute", Entity.Value{ .Rune = 0xb4 }),
Entity.init("acute;", Entity.Value{ .Rune = 0xb4 }),
Entity.init("acy;", Entity.Value{ .Rune = 0x430 }),
Entity.init("aelig", Entity.Value{ .Rune = 0xe6 }),
Entity.init("aelig;", Entity.Value{ .Rune = 0xe6 }),
Entity.init("af;", Entity.Value{ .Rune = 0x2061 }),
Entity.init("afr;", Entity.Value{ .Rune = 0x1d51e }),
Entity.init("agrave", Entity.Value{ .Rune = 0xe0 }),
Entity.init("agrave;", Entity.Value{ .Rune = 0xe0 }),
Entity.init("alefsym;", Entity.Value{ .Rune = 0x2135 }),
Entity.init("aleph;", Entity.Value{ .Rune = 0x2135 }),
Entity.init("alpha;", Entity.Value{ .Rune = 0x3b1 }),
Entity.init("amacr;", Entity.Value{ .Rune = 0x101 }),
Entity.init("amalg;", Entity.Value{ .Rune = 0x2a3f }),
Entity.init("amp", Entity.Value{ .Rune = 0x26 }),
Entity.init("amp;", Entity.Value{ .Rune = 0x26 }),
Entity.init("and;", Entity.Value{ .Rune = 0x2227 }),
Entity.init("andand;", Entity.Value{ .Rune = 0x2a55 }),
Entity.init("andd;", Entity.Value{ .Rune = 0x2a5c }),
Entity.init("andslope;", Entity.Value{ .Rune = 0x2a58 }),
Entity.init("andv;", Entity.Value{ .Rune = 0x2a5a }),
Entity.init("ang;", Entity.Value{ .Rune = 0x2220 }),
Entity.init("ange;", Entity.Value{ .Rune = 0x29a4 }),
Entity.init("angle;", Entity.Value{ .Rune = 0x2220 }),
Entity.init("angmsd;", Entity.Value{ .Rune = 0x2221 }),
Entity.init("angmsdaa;", Entity.Value{ .Rune = 0x29a8 }),
Entity.init("angmsdab;", Entity.Value{ .Rune = 0x29a9 }),
Entity.init("angmsdac;", Entity.Value{ .Rune = 0x29aa }),
Entity.init("angmsdad;", Entity.Value{ .Rune = 0x29ab }),
Entity.init("angmsdae;", Entity.Value{ .Rune = 0x29ac }),
Entity.init("angmsdaf;", Entity.Value{ .Rune = 0x29ad }),
Entity.init("angmsdag;", Entity.Value{ .Rune = 0x29ae }),
Entity.init("angmsdah;", Entity.Value{ .Rune = 0x29af }),
Entity.init("angrt;", Entity.Value{ .Rune = 0x221f }),
Entity.init("angrtvb;", Entity.Value{ .Rune = 0x22be }),
Entity.init("angrtvbd;", Entity.Value{ .Rune = 0x299d }),
Entity.init("angsph;", Entity.Value{ .Rune = 0x2222 }),
Entity.init("angst;", Entity.Value{ .Rune = 0xc5 }),
Entity.init("angzarr;", Entity.Value{ .Rune = 0x237c }),
Entity.init("aogon;", Entity.Value{ .Rune = 0x105 }),
Entity.init("aopf;", Entity.Value{ .Rune = 0x1d552 }),
Entity.init("ap;", Entity.Value{ .Rune = 0x2248 }),
Entity.init("apE;", Entity.Value{ .Rune = 0x2a70 }),
Entity.init("apacir;", Entity.Value{ .Rune = 0x2a6f }),
Entity.init("ape;", Entity.Value{ .Rune = 0x224a }),
Entity.init("apid;", Entity.Value{ .Rune = 0x224b }),
Entity.init("apos;", Entity.Value{ .Rune = 0x27 }),
Entity.init("approx;", Entity.Value{ .Rune = 0x2248 }),
Entity.init("approxeq;", Entity.Value{ .Rune = 0x224a }),
Entity.init("aring", Entity.Value{ .Rune = 0xe5 }),
Entity.init("aring;", Entity.Value{ .Rune = 0xe5 }),
Entity.init("ascr;", Entity.Value{ .Rune = 0x1d4b6 }),
Entity.init("ast;", Entity.Value{ .Rune = 0x2a }),
Entity.init("asymp;", Entity.Value{ .Rune = 0x2248 }),
Entity.init("asympeq;", Entity.Value{ .Rune = 0x224d }),
Entity.init("atilde", Entity.Value{ .Rune = 0xe3 }),
Entity.init("atilde;", Entity.Value{ .Rune = 0xe3 }),
Entity.init("auml", Entity.Value{ .Rune = 0xe4 }),
Entity.init("auml;", Entity.Value{ .Rune = 0xe4 }),
Entity.init("awconint;", Entity.Value{ .Rune = 0x2233 }),
Entity.init("awint;", Entity.Value{ .Rune = 0x2a11 }),
Entity.init("bNot;", Entity.Value{ .Rune = 0x2aed }),
Entity.init("backcong;", Entity.Value{ .Rune = 0x224c }),
Entity.init("backepsilon;", Entity.Value{ .Rune = 0x3f6 }),
Entity.init("backprime;", Entity.Value{ .Rune = 0x2035 }),
Entity.init("backsim;", Entity.Value{ .Rune = 0x223d }),
Entity.init("backsimeq;", Entity.Value{ .Rune = 0x22cd }),
Entity.init("barvee;", Entity.Value{ .Rune = 0x22bd }),
Entity.init("barwed;", Entity.Value{ .Rune = 0x2305 }),
Entity.init("barwedge;", Entity.Value{ .Rune = 0x2305 }),
Entity.init("bbrk;", Entity.Value{ .Rune = 0x23b5 }),
Entity.init("bbrktbrk;", Entity.Value{ .Rune = 0x23b6 }),
Entity.init("bcong;", Entity.Value{ .Rune = 0x224c }),
Entity.init("bcy;", Entity.Value{ .Rune = 0x431 }),
Entity.init("bdquo;", Entity.Value{ .Rune = 0x201e }),
Entity.init("becaus;", Entity.Value{ .Rune = 0x2235 }),
Entity.init("because;", Entity.Value{ .Rune = 0x2235 }),
Entity.init("bemptyv;", Entity.Value{ .Rune = 0x29b0 }),
Entity.init("bepsi;", Entity.Value{ .Rune = 0x3f6 }),
Entity.init("bernou;", Entity.Value{ .Rune = 0x212c }),
Entity.init("beta;", Entity.Value{ .Rune = 0x3b2 }),
Entity.init("beth;", Entity.Value{ .Rune = 0x2136 }),
Entity.init("between;", Entity.Value{ .Rune = 0x226c }),
Entity.init("bfr;", Entity.Value{ .Rune = 0x1d51f }),
Entity.init("bigcap;", Entity.Value{ .Rune = 0x22c2 }),
Entity.init("bigcirc;", Entity.Value{ .Rune = 0x25ef }),
Entity.init("bigcup;", Entity.Value{ .Rune = 0x22c3 }),
Entity.init("bigodot;", Entity.Value{ .Rune = 0x2a00 }),
Entity.init("bigoplus;", Entity.Value{ .Rune = 0x2a01 }),
Entity.init("bigotimes;", Entity.Value{ .Rune = 0x2a02 }),
Entity.init("bigsqcup;", Entity.Value{ .Rune = 0x2a06 }),
Entity.init("bigstar;", Entity.Value{ .Rune = 0x2605 }),
Entity.init("bigtriangledown;", Entity.Value{ .Rune = 0x25bd }),
Entity.init("bigtriangleup;", Entity.Value{ .Rune = 0x25b3 }),
Entity.init("biguplus;", Entity.Value{ .Rune = 0x2a04 }),
Entity.init("bigvee;", Entity.Value{ .Rune = 0x22c1 }),
Entity.init("bigwedge;", Entity.Value{ .Rune = 0x22c0 }),
Entity.init("bkarow;", Entity.Value{ .Rune = 0x290d }),
Entity.init("blacklozenge;", Entity.Value{ .Rune = 0x29eb }),
Entity.init("blacksquare;", Entity.Value{ .Rune = 0x25aa }),
Entity.init("blacktriangle;", Entity.Value{ .Rune = 0x25b4 }),
Entity.init("blacktriangledown;", Entity.Value{ .Rune = 0x25be }),
Entity.init("blacktriangleleft;", Entity.Value{ .Rune = 0x25c2 }),
Entity.init("blacktriangleright;", Entity.Value{ .Rune = 0x25b8 }),
Entity.init("blank;", Entity.Value{ .Rune = 0x2423 }),
Entity.init("blk12;", Entity.Value{ .Rune = 0x2592 }),
Entity.init("blk14;", Entity.Value{ .Rune = 0x2591 }),
Entity.init("blk34;", Entity.Value{ .Rune = 0x2593 }),
Entity.init("block;", Entity.Value{ .Rune = 0x2588 }),
Entity.init("bnot;", Entity.Value{ .Rune = 0x2310 }),
Entity.init("bopf;", Entity.Value{ .Rune = 0x1d553 }),
Entity.init("bot;", Entity.Value{ .Rune = 0x22a5 }),
Entity.init("bottom;", Entity.Value{ .Rune = 0x22a5 }),
Entity.init("bowtie;", Entity.Value{ .Rune = 0x22c8 }),
Entity.init("boxDL;", Entity.Value{ .Rune = 0x2557 }),
Entity.init("boxDR;", Entity.Value{ .Rune = 0x2554 }),
Entity.init("boxDl;", Entity.Value{ .Rune = 0x2556 }),
Entity.init("boxDr;", Entity.Value{ .Rune = 0x2553 }),
Entity.init("boxH;", Entity.Value{ .Rune = 0x2550 }),
Entity.init("boxHD;", Entity.Value{ .Rune = 0x2566 }),
Entity.init("boxHU;", Entity.Value{ .Rune = 0x2569 }),
Entity.init("boxHd;", Entity.Value{ .Rune = 0x2564 }),
Entity.init("boxHu;", Entity.Value{ .Rune = 0x2567 }),
Entity.init("boxUL;", Entity.Value{ .Rune = 0x255d }),
Entity.init("boxUR;", Entity.Value{ .Rune = 0x255a }),
Entity.init("boxUl;", Entity.Value{ .Rune = 0x255c }),
Entity.init("boxUr;", Entity.Value{ .Rune = 0x2559 }),
Entity.init("boxV;", Entity.Value{ .Rune = 0x2551 }),
Entity.init("boxVH;", Entity.Value{ .Rune = 0x256c }),
Entity.init("boxVL;", Entity.Value{ .Rune = 0x2563 }),
Entity.init("boxVR;", Entity.Value{ .Rune = 0x2560 }),
Entity.init("boxVh;", Entity.Value{ .Rune = 0x256b }),
Entity.init("boxVl;", Entity.Value{ .Rune = 0x2562 }),
Entity.init("boxVr;", Entity.Value{ .Rune = 0x255f }),
Entity.init("boxbox;", Entity.Value{ .Rune = 0x29c9 }),
Entity.init("boxdL;", Entity.Value{ .Rune = 0x2555 }),
Entity.init("boxdR;", Entity.Value{ .Rune = 0x2552 }),
Entity.init("boxdl;", Entity.Value{ .Rune = 0x2510 }),
Entity.init("boxdr;", Entity.Value{ .Rune = 0x250c }),
Entity.init("boxh;", Entity.Value{ .Rune = 0x2500 }),
Entity.init("boxhD;", Entity.Value{ .Rune = 0x2565 }),
Entity.init("boxhU;", Entity.Value{ .Rune = 0x2568 }),
Entity.init("boxhd;", Entity.Value{ .Rune = 0x252c }),
Entity.init("boxhu;", Entity.Value{ .Rune = 0x2534 }),
Entity.init("boxminus;", Entity.Value{ .Rune = 0x229f }),
Entity.init("boxplus;", Entity.Value{ .Rune = 0x229e }),
Entity.init("boxtimes;", Entity.Value{ .Rune = 0x22a0 }),
Entity.init("boxuL;", Entity.Value{ .Rune = 0x255b }),
Entity.init("boxuR;", Entity.Value{ .Rune = 0x2558 }),
Entity.init("boxul;", Entity.Value{ .Rune = 0x2518 }),
Entity.init("boxur;", Entity.Value{ .Rune = 0x2514 }),
Entity.init("boxv;", Entity.Value{ .Rune = 0x2502 }),
Entity.init("boxvH;", Entity.Value{ .Rune = 0x256a }),
Entity.init("boxvL;", Entity.Value{ .Rune = 0x2561 }),
Entity.init("boxvR;", Entity.Value{ .Rune = 0x255e }),
Entity.init("boxvh;", Entity.Value{ .Rune = 0x253c }),
Entity.init("boxvl;", Entity.Value{ .Rune = 0x2524 }),
Entity.init("boxvr;", Entity.Value{ .Rune = 0x251c }),
Entity.init("bprime;", Entity.Value{ .Rune = 0x2035 }),
Entity.init("breve;", Entity.Value{ .Rune = 0x2d8 }),
Entity.init("brvbar", Entity.Value{ .Rune = 0xa6 }),
Entity.init("brvbar;", Entity.Value{ .Rune = 0xa6 }),
Entity.init("bscr;", Entity.Value{ .Rune = 0x1d4b7 }),
Entity.init("bsemi;", Entity.Value{ .Rune = 0x204f }),
Entity.init("bsim;", Entity.Value{ .Rune = 0x223d }),
Entity.init("bsime;", Entity.Value{ .Rune = 0x22cd }),
Entity.init("bsol;", Entity.Value{ .Rune = 0x5c }),
Entity.init("bsolb;", Entity.Value{ .Rune = 0x29c5 }),
Entity.init("bsolhsub;", Entity.Value{ .Rune = 0x27c8 }),
Entity.init("bull;", Entity.Value{ .Rune = 0x2022 }),
Entity.init("bullet;", Entity.Value{ .Rune = 0x2022 }),
Entity.init("bump;", Entity.Value{ .Rune = 0x224e }),
Entity.init("bumpE;", Entity.Value{ .Rune = 0x2aae }),
Entity.init("bumpe;", Entity.Value{ .Rune = 0x224f }),
Entity.init("bumpeq;", Entity.Value{ .Rune = 0x224f }),
Entity.init("cacute;", Entity.Value{ .Rune = 0x107 }),
Entity.init("cap;", Entity.Value{ .Rune = 0x2229 }),
Entity.init("capand;", Entity.Value{ .Rune = 0x2a44 }),
Entity.init("capbrcup;", Entity.Value{ .Rune = 0x2a49 }),
Entity.init("capcap;", Entity.Value{ .Rune = 0x2a4b }),
Entity.init("capcup;", Entity.Value{ .Rune = 0x2a47 }),
Entity.init("capdot;", Entity.Value{ .Rune = 0x2a40 }),
Entity.init("caret;", Entity.Value{ .Rune = 0x2041 }),
Entity.init("caron;", Entity.Value{ .Rune = 0x2c7 }),
Entity.init("ccaps;", Entity.Value{ .Rune = 0x2a4d }),
Entity.init("ccaron;", Entity.Value{ .Rune = 0x10d }),
Entity.init("ccedil", Entity.Value{ .Rune = 0xe7 }),
Entity.init("ccedil;", Entity.Value{ .Rune = 0xe7 }),
Entity.init("ccirc;", Entity.Value{ .Rune = 0x109 }),
Entity.init("ccups;", Entity.Value{ .Rune = 0x2a4c }),
Entity.init("ccupssm;", Entity.Value{ .Rune = 0x2a50 }),
Entity.init("cdot;", Entity.Value{ .Rune = 0x10b }),
Entity.init("cedil", Entity.Value{ .Rune = 0xb8 }),
Entity.init("cedil;", Entity.Value{ .Rune = 0xb8 }),
Entity.init("cemptyv;", Entity.Value{ .Rune = 0x29b2 }),
Entity.init("cent", Entity.Value{ .Rune = 0xa2 }),
Entity.init("cent;", Entity.Value{ .Rune = 0xa2 }),
Entity.init("centerdot;", Entity.Value{ .Rune = 0xb7 }),
Entity.init("cfr;", Entity.Value{ .Rune = 0x1d520 }),
Entity.init("chcy;", Entity.Value{ .Rune = 0x447 }),
Entity.init("check;", Entity.Value{ .Rune = 0x2713 }),
Entity.init("checkmark;", Entity.Value{ .Rune = 0x2713 }),
Entity.init("chi;", Entity.Value{ .Rune = 0x3c7 }),
Entity.init("cir;", Entity.Value{ .Rune = 0x25cb }),
Entity.init("cirE;", Entity.Value{ .Rune = 0x29c3 }),
Entity.init("circ;", Entity.Value{ .Rune = 0x2c6 }),
Entity.init("circeq;", Entity.Value{ .Rune = 0x2257 }),
Entity.init("circlearrowleft;", Entity.Value{ .Rune = 0x21ba }),
Entity.init("circlearrowright;", Entity.Value{ .Rune = 0x21bb }),
Entity.init("circledR;", Entity.Value{ .Rune = 0xae }),
Entity.init("circledS;", Entity.Value{ .Rune = 0x24c8 }),
Entity.init("circledast;", Entity.Value{ .Rune = 0x229b }),
Entity.init("circledcirc;", Entity.Value{ .Rune = 0x229a }),
Entity.init("circleddash;", Entity.Value{ .Rune = 0x229d }),
Entity.init("cire;", Entity.Value{ .Rune = 0x2257 }),
Entity.init("cirfnint;", Entity.Value{ .Rune = 0x2a10 }),
Entity.init("cirmid;", Entity.Value{ .Rune = 0x2aef }),
Entity.init("cirscir;", Entity.Value{ .Rune = 0x29c2 }),
Entity.init("clubs;", Entity.Value{ .Rune = 0x2663 }),
Entity.init("clubsuit;", Entity.Value{ .Rune = 0x2663 }),
Entity.init("colon;", Entity.Value{ .Rune = 0x3a }),
Entity.init("colone;", Entity.Value{ .Rune = 0x2254 }),
Entity.init("coloneq;", Entity.Value{ .Rune = 0x2254 }),
Entity.init("comma;", Entity.Value{ .Rune = 0x2c }),
Entity.init("commat;", Entity.Value{ .Rune = 0x40 }),
Entity.init("comp;", Entity.Value{ .Rune = 0x2201 }),
Entity.init("compfn;", Entity.Value{ .Rune = 0x2218 }),
Entity.init("complement;", Entity.Value{ .Rune = 0x2201 }),
Entity.init("complexes;", Entity.Value{ .Rune = 0x2102 }),
Entity.init("cong;", Entity.Value{ .Rune = 0x2245 }),
Entity.init("congdot;", Entity.Value{ .Rune = 0x2a6d }),
Entity.init("conint;", Entity.Value{ .Rune = 0x222e }),
Entity.init("copf;", Entity.Value{ .Rune = 0x1d554 }),
Entity.init("coprod;", Entity.Value{ .Rune = 0x2210 }),
Entity.init("copy", Entity.Value{ .Rune = 0xa9 }),
Entity.init("copy;", Entity.Value{ .Rune = 0xa9 }),
Entity.init("copysr;", Entity.Value{ .Rune = 0x2117 }),
Entity.init("crarr;", Entity.Value{ .Rune = 0x21b5 }),
Entity.init("cross;", Entity.Value{ .Rune = 0x2717 }),
Entity.init("cscr;", Entity.Value{ .Rune = 0x1d4b8 }),
Entity.init("csub;", Entity.Value{ .Rune = 0x2acf }),
Entity.init("csube;", Entity.Value{ .Rune = 0x2ad1 }),
Entity.init("csup;", Entity.Value{ .Rune = 0x2ad0 }),
Entity.init("csupe;", Entity.Value{ .Rune = 0x2ad2 }),
Entity.init("ctdot;", Entity.Value{ .Rune = 0x22ef }),
Entity.init("cudarrl;", Entity.Value{ .Rune = 0x2938 }),
Entity.init("cudarrr;", Entity.Value{ .Rune = 0x2935 }),
Entity.init("cuepr;", Entity.Value{ .Rune = 0x22de }),
Entity.init("cuesc;", Entity.Value{ .Rune = 0x22df }),
Entity.init("cularr;", Entity.Value{ .Rune = 0x21b6 }),
Entity.init("cularrp;", Entity.Value{ .Rune = 0x293d }),
Entity.init("cup;", Entity.Value{ .Rune = 0x222a }),
Entity.init("cupbrcap;", Entity.Value{ .Rune = 0x2a48 }),
Entity.init("cupcap;", Entity.Value{ .Rune = 0x2a46 }),
Entity.init("cupcup;", Entity.Value{ .Rune = 0x2a4a }),
Entity.init("cupdot;", Entity.Value{ .Rune = 0x228d }),
Entity.init("cupor;", Entity.Value{ .Rune = 0x2a45 }),
Entity.init("curarr;", Entity.Value{ .Rune = 0x21b7 }),
Entity.init("curarrm;", Entity.Value{ .Rune = 0x293c }),
Entity.init("curlyeqprec;", Entity.Value{ .Rune = 0x22de }),
Entity.init("curlyeqsucc;", Entity.Value{ .Rune = 0x22df }),
Entity.init("curlyvee;", Entity.Value{ .Rune = 0x22ce }),
Entity.init("curlywedge;", Entity.Value{ .Rune = 0x22cf }),
Entity.init("curren", Entity.Value{ .Rune = 0xa4 }),
Entity.init("curren;", Entity.Value{ .Rune = 0xa4 }),
Entity.init("curvearrowleft;", Entity.Value{ .Rune = 0x21b6 }),
Entity.init("curvearrowright;", Entity.Value{ .Rune = 0x21b7 }),
Entity.init("cuvee;", Entity.Value{ .Rune = 0x22ce }),
Entity.init("cuwed;", Entity.Value{ .Rune = 0x22cf }),
Entity.init("cwconint;", Entity.Value{ .Rune = 0x2232 }),
Entity.init("cwint;", Entity.Value{ .Rune = 0x2231 }),
Entity.init("cylcty;", Entity.Value{ .Rune = 0x232d }),
Entity.init("dArr;", Entity.Value{ .Rune = 0x21d3 }),
Entity.init("dHar;", Entity.Value{ .Rune = 0x2965 }),
Entity.init("dagger;", Entity.Value{ .Rune = 0x2020 }),
Entity.init("daleth;", Entity.Value{ .Rune = 0x2138 }),
Entity.init("darr;", Entity.Value{ .Rune = 0x2193 }),
Entity.init("dash;", Entity.Value{ .Rune = 0x2010 }),
Entity.init("dashv;", Entity.Value{ .Rune = 0x22a3 }),
Entity.init("dbkarow;", Entity.Value{ .Rune = 0x290f }),
Entity.init("dblac;", Entity.Value{ .Rune = 0x2dd }),
Entity.init("dcaron;", Entity.Value{ .Rune = 0x10f }),
Entity.init("dcy;", Entity.Value{ .Rune = 0x434 }),
Entity.init("dd;", Entity.Value{ .Rune = 0x2146 }),
Entity.init("ddagger;", Entity.Value{ .Rune = 0x2021 }),
Entity.init("ddarr;", Entity.Value{ .Rune = 0x21ca }),
Entity.init("ddotseq;", Entity.Value{ .Rune = 0x2a77 }),
Entity.init("deg", Entity.Value{ .Rune = 0xb0 }),
Entity.init("deg;", Entity.Value{ .Rune = 0xb0 }),
Entity.init("delta;", Entity.Value{ .Rune = 0x3b4 }),
Entity.init("demptyv;", Entity.Value{ .Rune = 0x29b1 }),
Entity.init("dfisht;", Entity.Value{ .Rune = 0x297f }),
Entity.init("dfr;", Entity.Value{ .Rune = 0x1d521 }),
Entity.init("dharl;", Entity.Value{ .Rune = 0x21c3 }),
Entity.init("dharr;", Entity.Value{ .Rune = 0x21c2 }),
Entity.init("diam;", Entity.Value{ .Rune = 0x22c4 }),
Entity.init("diamond;", Entity.Value{ .Rune = 0x22c4 }),
Entity.init("diamondsuit;", Entity.Value{ .Rune = 0x2666 }),
Entity.init("diams;", Entity.Value{ .Rune = 0x2666 }),
Entity.init("die;", Entity.Value{ .Rune = 0xa8 }),
Entity.init("digamma;", Entity.Value{ .Rune = 0x3dd }),
Entity.init("disin;", Entity.Value{ .Rune = 0x22f2 }),
Entity.init("div;", Entity.Value{ .Rune = 0xf7 }),
Entity.init("divide", Entity.Value{ .Rune = 0xf7 }),
Entity.init("divide;", Entity.Value{ .Rune = 0xf7 }),
Entity.init("divideontimes;", Entity.Value{ .Rune = 0x22c7 }),
Entity.init("divonx;", Entity.Value{ .Rune = 0x22c7 }),
Entity.init("djcy;", Entity.Value{ .Rune = 0x452 }),
Entity.init("dlcorn;", Entity.Value{ .Rune = 0x231e }),
Entity.init("dlcrop;", Entity.Value{ .Rune = 0x230d }),
Entity.init("dollar;", Entity.Value{ .Rune = 0x24 }),
Entity.init("dopf;", Entity.Value{ .Rune = 0x1d555 }),
Entity.init("dot;", Entity.Value{ .Rune = 0x2d9 }),
Entity.init("doteq;", Entity.Value{ .Rune = 0x2250 }),
Entity.init("doteqdot;", Entity.Value{ .Rune = 0x2251 }),
Entity.init("dotminus;", Entity.Value{ .Rune = 0x2238 }),
Entity.init("dotplus;", Entity.Value{ .Rune = 0x2214 }),
Entity.init("dotsquare;", Entity.Value{ .Rune = 0x22a1 }),
Entity.init("doublebarwedge;", Entity.Value{ .Rune = 0x2306 }),
Entity.init("downarrow;", Entity.Value{ .Rune = 0x2193 }),
Entity.init("downdownarrows;", Entity.Value{ .Rune = 0x21ca }),
Entity.init("downharpoonleft;", Entity.Value{ .Rune = 0x21c3 }),
Entity.init("downharpoonright;", Entity.Value{ .Rune = 0x21c2 }),
Entity.init("drbkarow;", Entity.Value{ .Rune = 0x2910 }),
Entity.init("drcorn;", Entity.Value{ .Rune = 0x231f }),
Entity.init("drcrop;", Entity.Value{ .Rune = 0x230c }),
Entity.init("dscr;", Entity.Value{ .Rune = 0x1d4b9 }),
Entity.init("dscy;", Entity.Value{ .Rune = 0x455 }),
Entity.init("dsol;", Entity.Value{ .Rune = 0x29f6 }),
Entity.init("dstrok;", Entity.Value{ .Rune = 0x111 }),
Entity.init("dtdot;", Entity.Value{ .Rune = 0x22f1 }),
Entity.init("dtri;", Entity.Value{ .Rune = 0x25bf }),
Entity.init("dtrif;", Entity.Value{ .Rune = 0x25be }),
Entity.init("duarr;", Entity.Value{ .Rune = 0x21f5 }),
Entity.init("duhar;", Entity.Value{ .Rune = 0x296f }),
Entity.init("dwangle;", Entity.Value{ .Rune = 0x29a6 }),
Entity.init("dzcy;", Entity.Value{ .Rune = 0x45f }),
Entity.init("dzigrarr;", Entity.Value{ .Rune = 0x27ff }),
Entity.init("eDDot;", Entity.Value{ .Rune = 0x2a77 }),
Entity.init("eDot;", Entity.Value{ .Rune = 0x2251 }),
Entity.init("eacute", Entity.Value{ .Rune = 0xe9 }),
Entity.init("eacute;", Entity.Value{ .Rune = 0xe9 }),
Entity.init("easter;", Entity.Value{ .Rune = 0x2a6e }),
Entity.init("ecaron;", Entity.Value{ .Rune = 0x11b }),
Entity.init("ecir;", Entity.Value{ .Rune = 0x2256 }),
Entity.init("ecirc", Entity.Value{ .Rune = 0xea }),
Entity.init("ecirc;", Entity.Value{ .Rune = 0xea }),
Entity.init("ecolon;", Entity.Value{ .Rune = 0x2255 }),
Entity.init("ecy;", Entity.Value{ .Rune = 0x44d }),
Entity.init("edot;", Entity.Value{ .Rune = 0x117 }),
Entity.init("ee;", Entity.Value{ .Rune = 0x2147 }),
Entity.init("efDot;", Entity.Value{ .Rune = 0x2252 }),
Entity.init("efr;", Entity.Value{ .Rune = 0x1d522 }),
Entity.init("eg;", Entity.Value{ .Rune = 0x2a9a }),
Entity.init("egrave", Entity.Value{ .Rune = 0xe8 }),
Entity.init("egrave;", Entity.Value{ .Rune = 0xe8 }),
Entity.init("egs;", Entity.Value{ .Rune = 0x2a96 }),
Entity.init("egsdot;", Entity.Value{ .Rune = 0x2a98 }),
Entity.init("el;", Entity.Value{ .Rune = 0x2a99 }),
Entity.init("elinters;", Entity.Value{ .Rune = 0x23e7 }),
Entity.init("ell;", Entity.Value{ .Rune = 0x2113 }),
Entity.init("els;", Entity.Value{ .Rune = 0x2a95 }),
Entity.init("elsdot;", Entity.Value{ .Rune = 0x2a97 }),
Entity.init("emacr;", Entity.Value{ .Rune = 0x113 }),
Entity.init("empty;", Entity.Value{ .Rune = 0x2205 }),
Entity.init("emptyset;", Entity.Value{ .Rune = 0x2205 }),
Entity.init("emptyv;", Entity.Value{ .Rune = 0x2205 }),
Entity.init("emsp13;", Entity.Value{ .Rune = 0x2004 }),
Entity.init("emsp14;", Entity.Value{ .Rune = 0x2005 }),
Entity.init("emsp;", Entity.Value{ .Rune = 0x2003 }),
Entity.init("eng;", Entity.Value{ .Rune = 0x14b }),
Entity.init("ensp;", Entity.Value{ .Rune = 0x2002 }),
Entity.init("eogon;", Entity.Value{ .Rune = 0x119 }),
Entity.init("eopf;", Entity.Value{ .Rune = 0x1d556 }),
Entity.init("epar;", Entity.Value{ .Rune = 0x22d5 }),
Entity.init("eparsl;", Entity.Value{ .Rune = 0x29e3 }),
Entity.init("eplus;", Entity.Value{ .Rune = 0x2a71 }),
Entity.init("epsi;", Entity.Value{ .Rune = 0x3b5 }),
Entity.init("epsilon;", Entity.Value{ .Rune = 0x3b5 }),
Entity.init("epsiv;", Entity.Value{ .Rune = 0x3f5 }),
Entity.init("eqcirc;", Entity.Value{ .Rune = 0x2256 }),
Entity.init("eqcolon;", Entity.Value{ .Rune = 0x2255 }),
Entity.init("eqsim;", Entity.Value{ .Rune = 0x2242 }),
Entity.init("eqslantgtr;", Entity.Value{ .Rune = 0x2a96 }),
Entity.init("eqslantless;", Entity.Value{ .Rune = 0x2a95 }),
Entity.init("equals;", Entity.Value{ .Rune = 0x3d }),
Entity.init("equest;", Entity.Value{ .Rune = 0x225f }),
Entity.init("equiv;", Entity.Value{ .Rune = 0x2261 }),
Entity.init("equivDD;", Entity.Value{ .Rune = 0x2a78 }),
Entity.init("eqvparsl;", Entity.Value{ .Rune = 0x29e5 }),
Entity.init("erDot;", Entity.Value{ .Rune = 0x2253 }),
Entity.init("erarr;", Entity.Value{ .Rune = 0x2971 }),
Entity.init("escr;", Entity.Value{ .Rune = 0x212f }),
Entity.init("esdot;", Entity.Value{ .Rune = 0x2250 }),
Entity.init("esim;", Entity.Value{ .Rune = 0x2242 }),
Entity.init("eta;", Entity.Value{ .Rune = 0x3b7 }),
Entity.init("eth", Entity.Value{ .Rune = 0xf0 }),
Entity.init("eth;", Entity.Value{ .Rune = 0xf0 }),
Entity.init("euml", Entity.Value{ .Rune = 0xeb }),
Entity.init("euml;", Entity.Value{ .Rune = 0xeb }),
Entity.init("euro;", Entity.Value{ .Rune = 0x20ac }),
Entity.init("excl;", Entity.Value{ .Rune = 0x21 }),
Entity.init("exist;", Entity.Value{ .Rune = 0x2203 }),
Entity.init("expectation;", Entity.Value{ .Rune = 0x2130 }),
Entity.init("exponentiale;", Entity.Value{ .Rune = 0x2147 }),
Entity.init("fallingdotseq;", Entity.Value{ .Rune = 0x2252 }),
Entity.init("fcy;", Entity.Value{ .Rune = 0x444 }),
Entity.init("female;", Entity.Value{ .Rune = 0x2640 }),
Entity.init("ffilig;", Entity.Value{ .Rune = 0xfb03 }),
Entity.init("fflig;", Entity.Value{ .Rune = 0xfb00 }),
Entity.init("ffllig;", Entity.Value{ .Rune = 0xfb04 }),
Entity.init("ffr;", Entity.Value{ .Rune = 0x1d523 }),
Entity.init("filig;", Entity.Value{ .Rune = 0xfb01 }),
Entity.init("flat;", Entity.Value{ .Rune = 0x266d }),
Entity.init("fllig;", Entity.Value{ .Rune = 0xfb02 }),
Entity.init("fltns;", Entity.Value{ .Rune = 0x25b1 }),
Entity.init("fnof;", Entity.Value{ .Rune = 0x192 }),
Entity.init("fopf;", Entity.Value{ .Rune = 0x1d557 }),
Entity.init("forall;", Entity.Value{ .Rune = 0x2200 }),
Entity.init("fork;", Entity.Value{ .Rune = 0x22d4 }),
Entity.init("forkv;", Entity.Value{ .Rune = 0x2ad9 }),
Entity.init("fpartint;", Entity.Value{ .Rune = 0x2a0d }),
Entity.init("frac12", Entity.Value{ .Rune = 0xbd }),
Entity.init("frac12;", Entity.Value{ .Rune = 0xbd }),
Entity.init("frac13;", Entity.Value{ .Rune = 0x2153 }),
Entity.init("frac14", Entity.Value{ .Rune = 0xbc }),
Entity.init("frac14;", Entity.Value{ .Rune = 0xbc }),
Entity.init("frac15;", Entity.Value{ .Rune = 0x2155 }),
Entity.init("frac16;", Entity.Value{ .Rune = 0x2159 }),
Entity.init("frac18;", Entity.Value{ .Rune = 0x215b }),
Entity.init("frac23;", Entity.Value{ .Rune = 0x2154 }),
Entity.init("frac25;", Entity.Value{ .Rune = 0x2156 }),
Entity.init("frac34", Entity.Value{ .Rune = 0xbe }),
Entity.init("frac34;", Entity.Value{ .Rune = 0xbe }),
Entity.init("frac35;", Entity.Value{ .Rune = 0x2157 }),
Entity.init("frac38;", Entity.Value{ .Rune = 0x215c }),
Entity.init("frac45;", Entity.Value{ .Rune = 0x2158 }),
Entity.init("frac56;", Entity.Value{ .Rune = 0x215a }),
Entity.init("frac58;", Entity.Value{ .Rune = 0x215d }),
Entity.init("frac78;", Entity.Value{ .Rune = 0x215e }),
Entity.init("frasl;", Entity.Value{ .Rune = 0x2044 }),
Entity.init("frown;", Entity.Value{ .Rune = 0x2322 }),
Entity.init("fscr;", Entity.Value{ .Rune = 0x1d4bb }),
Entity.init("gE;", Entity.Value{ .Rune = 0x2267 }),
Entity.init("gEl;", Entity.Value{ .Rune = 0x2a8c }),
Entity.init("gacute;", Entity.Value{ .Rune = 0x1f5 }),
Entity.init("gamma;", Entity.Value{ .Rune = 0x3b3 }),
Entity.init("gammad;", Entity.Value{ .Rune = 0x3dd }),
Entity.init("gap;", Entity.Value{ .Rune = 0x2a86 }),
Entity.init("gbreve;", Entity.Value{ .Rune = 0x11f }),
Entity.init("gcirc;", Entity.Value{ .Rune = 0x11d }),
Entity.init("gcy;", Entity.Value{ .Rune = 0x433 }),
Entity.init("gdot;", Entity.Value{ .Rune = 0x121 }),
Entity.init("ge;", Entity.Value{ .Rune = 0x2265 }),
Entity.init("gel;", Entity.Value{ .Rune = 0x22db }),
Entity.init("geq;", Entity.Value{ .Rune = 0x2265 }),
Entity.init("geqq;", Entity.Value{ .Rune = 0x2267 }),
Entity.init("geqslant;", Entity.Value{ .Rune = 0x2a7e }),
Entity.init("ges;", Entity.Value{ .Rune = 0x2a7e }),
Entity.init("gescc;", Entity.Value{ .Rune = 0x2aa9 }),
Entity.init("gesdot;", Entity.Value{ .Rune = 0x2a80 }),
Entity.init("gesdoto;", Entity.Value{ .Rune = 0x2a82 }),
Entity.init("gesdotol;", Entity.Value{ .Rune = 0x2a84 }),
Entity.init("gesles;", Entity.Value{ .Rune = 0x2a94 }),
Entity.init("gfr;", Entity.Value{ .Rune = 0x1d524 }),
Entity.init("gg;", Entity.Value{ .Rune = 0x226b }),
Entity.init("ggg;", Entity.Value{ .Rune = 0x22d9 }),
Entity.init("gimel;", Entity.Value{ .Rune = 0x2137 }),
Entity.init("gjcy;", Entity.Value{ .Rune = 0x453 }),
Entity.init("gl;", Entity.Value{ .Rune = 0x2277 }),
Entity.init("glE;", Entity.Value{ .Rune = 0x2a92 }),
Entity.init("gla;", Entity.Value{ .Rune = 0x2aa5 }),
Entity.init("glj;", Entity.Value{ .Rune = 0x2aa4 }),
Entity.init("gnE;", Entity.Value{ .Rune = 0x2269 }),
Entity.init("gnap;", Entity.Value{ .Rune = 0x2a8a }),
Entity.init("gnapprox;", Entity.Value{ .Rune = 0x2a8a }),
Entity.init("gne;", Entity.Value{ .Rune = 0x2a88 }),
Entity.init("gneq;", Entity.Value{ .Rune = 0x2a88 }),
Entity.init("gneqq;", Entity.Value{ .Rune = 0x2269 }),
Entity.init("gnsim;", Entity.Value{ .Rune = 0x22e7 }),
Entity.init("gopf;", Entity.Value{ .Rune = 0x1d558 }),
Entity.init("grave;", Entity.Value{ .Rune = 0x60 }),
Entity.init("gscr;", Entity.Value{ .Rune = 0x210a }),
Entity.init("gsim;", Entity.Value{ .Rune = 0x2273 }),
Entity.init("gsime;", Entity.Value{ .Rune = 0x2a8e }),
Entity.init("gsiml;", Entity.Value{ .Rune = 0x2a90 }),
Entity.init("gt", Entity.Value{ .Rune = 0x3e }),
Entity.init("gt;", Entity.Value{ .Rune = 0x3e }),
Entity.init("gtcc;", Entity.Value{ .Rune = 0x2aa7 }),
Entity.init("gtcir;", Entity.Value{ .Rune = 0x2a7a }),
Entity.init("gtdot;", Entity.Value{ .Rune = 0x22d7 }),
Entity.init("gtlPar;", Entity.Value{ .Rune = 0x2995 }),
Entity.init("gtquest;", Entity.Value{ .Rune = 0x2a7c }),
Entity.init("gtrapprox;", Entity.Value{ .Rune = 0x2a86 }),
Entity.init("gtrarr;", Entity.Value{ .Rune = 0x2978 }),
Entity.init("gtrdot;", Entity.Value{ .Rune = 0x22d7 }),
Entity.init("gtreqless;", Entity.Value{ .Rune = 0x22db }),
Entity.init("gtreqqless;", Entity.Value{ .Rune = 0x2a8c }),
Entity.init("gtrless;", Entity.Value{ .Rune = 0x2277 }),
Entity.init("gtrsim;", Entity.Value{ .Rune = 0x2273 }),
Entity.init("hArr;", Entity.Value{ .Rune = 0x21d4 }),
Entity.init("hairsp;", Entity.Value{ .Rune = 0x200a }),
Entity.init("half;", Entity.Value{ .Rune = 0xbd }),
Entity.init("hamilt;", Entity.Value{ .Rune = 0x210b }),
Entity.init("hardcy;", Entity.Value{ .Rune = 0x44a }),
Entity.init("harr;", Entity.Value{ .Rune = 0x2194 }),
Entity.init("harrcir;", Entity.Value{ .Rune = 0x2948 }),
Entity.init("harrw;", Entity.Value{ .Rune = 0x21ad }),
Entity.init("hbar;", Entity.Value{ .Rune = 0x210f }),
Entity.init("hcirc;", Entity.Value{ .Rune = 0x125 }),
Entity.init("hearts;", Entity.Value{ .Rune = 0x2665 }),
Entity.init("heartsuit;", Entity.Value{ .Rune = 0x2665 }),
Entity.init("hellip;", Entity.Value{ .Rune = 0x2026 }),
Entity.init("hercon;", Entity.Value{ .Rune = 0x22b9 }),
Entity.init("hfr;", Entity.Value{ .Rune = 0x1d525 }),
Entity.init("hksearow;", Entity.Value{ .Rune = 0x2925 }),
Entity.init("hkswarow;", Entity.Value{ .Rune = 0x2926 }),
Entity.init("hoarr;", Entity.Value{ .Rune = 0x21ff }),
Entity.init("homtht;", Entity.Value{ .Rune = 0x223b }),
Entity.init("hookleftarrow;", Entity.Value{ .Rune = 0x21a9 }),
Entity.init("hookrightarrow;", Entity.Value{ .Rune = 0x21aa }),
Entity.init("hopf;", Entity.Value{ .Rune = 0x1d559 }),
Entity.init("horbar;", Entity.Value{ .Rune = 0x2015 }),
Entity.init("hscr;", Entity.Value{ .Rune = 0x1d4bd }),
Entity.init("hslash;", Entity.Value{ .Rune = 0x210f }),
Entity.init("hstrok;", Entity.Value{ .Rune = 0x127 }),
Entity.init("hybull;", Entity.Value{ .Rune = 0x2043 }),
Entity.init("hyphen;", Entity.Value{ .Rune = 0x2010 }),
Entity.init("iacute", Entity.Value{ .Rune = 0xed }),
Entity.init("iacute;", Entity.Value{ .Rune = 0xed }),
Entity.init("ic;", Entity.Value{ .Rune = 0x2063 }),
Entity.init("icirc", Entity.Value{ .Rune = 0xee }),
Entity.init("icirc;", Entity.Value{ .Rune = 0xee }),
Entity.init("icy;", Entity.Value{ .Rune = 0x438 }),
Entity.init("iecy;", Entity.Value{ .Rune = 0x435 }),
Entity.init("iexcl", Entity.Value{ .Rune = 0xa1 }),
Entity.init("iexcl;", Entity.Value{ .Rune = 0xa1 }),
Entity.init("iff;", Entity.Value{ .Rune = 0x21d4 }),
Entity.init("ifr;", Entity.Value{ .Rune = 0x1d526 }),
Entity.init("igrave", Entity.Value{ .Rune = 0xec }),
Entity.init("igrave;", Entity.Value{ .Rune = 0xec }),
Entity.init("ii;", Entity.Value{ .Rune = 0x2148 }),
Entity.init("iiiint;", Entity.Value{ .Rune = 0x2a0c }),
Entity.init("iiint;", Entity.Value{ .Rune = 0x222d }),
Entity.init("iinfin;", Entity.Value{ .Rune = 0x29dc }),
Entity.init("iiota;", Entity.Value{ .Rune = 0x2129 }),
Entity.init("ijlig;", Entity.Value{ .Rune = 0x133 }),
Entity.init("imacr;", Entity.Value{ .Rune = 0x12b }),
Entity.init("image;", Entity.Value{ .Rune = 0x2111 }),
Entity.init("imagline;", Entity.Value{ .Rune = 0x2110 }),
Entity.init("imagpart;", Entity.Value{ .Rune = 0x2111 }),
Entity.init("imath;", Entity.Value{ .Rune = 0x131 }),
Entity.init("imof;", Entity.Value{ .Rune = 0x22b7 }),
Entity.init("imped;", Entity.Value{ .Rune = 0x1b5 }),
Entity.init("in;", Entity.Value{ .Rune = 0x2208 }),
Entity.init("incare;", Entity.Value{ .Rune = 0x2105 }),
Entity.init("infin;", Entity.Value{ .Rune = 0x221e }),
Entity.init("infintie;", Entity.Value{ .Rune = 0x29dd }),
Entity.init("inodot;", Entity.Value{ .Rune = 0x131 }),
Entity.init("int;", Entity.Value{ .Rune = 0x222b }),
Entity.init("intcal;", Entity.Value{ .Rune = 0x22ba }),
Entity.init("integers;", Entity.Value{ .Rune = 0x2124 }),
Entity.init("intercal;", Entity.Value{ .Rune = 0x22ba }),
Entity.init("intlarhk;", Entity.Value{ .Rune = 0x2a17 }),
Entity.init("intprod;", Entity.Value{ .Rune = 0x2a3c }),
Entity.init("iocy;", Entity.Value{ .Rune = 0x451 }),
Entity.init("iogon;", Entity.Value{ .Rune = 0x12f }),
Entity.init("iopf;", Entity.Value{ .Rune = 0x1d55a }),
Entity.init("iota;", Entity.Value{ .Rune = 0x3b9 }),
Entity.init("iprod;", Entity.Value{ .Rune = 0x2a3c }),
Entity.init("iquest", Entity.Value{ .Rune = 0xbf }),
Entity.init("iquest;", Entity.Value{ .Rune = 0xbf }),
Entity.init("iscr;", Entity.Value{ .Rune = 0x1d4be }),
Entity.init("isin;", Entity.Value{ .Rune = 0x2208 }),
Entity.init("isinE;", Entity.Value{ .Rune = 0x22f9 }),
Entity.init("isindot;", Entity.Value{ .Rune = 0x22f5 }),
Entity.init("isins;", Entity.Value{ .Rune = 0x22f4 }),
Entity.init("isinsv;", Entity.Value{ .Rune = 0x22f3 }),
Entity.init("isinv;", Entity.Value{ .Rune = 0x2208 }),
Entity.init("it;", Entity.Value{ .Rune = 0x2062 }),
Entity.init("itilde;", Entity.Value{ .Rune = 0x129 }),
Entity.init("iukcy;", Entity.Value{ .Rune = 0x456 }),
Entity.init("iuml", Entity.Value{ .Rune = 0xef }),
Entity.init("iuml;", Entity.Value{ .Rune = 0xef }),
Entity.init("jcirc;", Entity.Value{ .Rune = 0x135 }),
Entity.init("jcy;", Entity.Value{ .Rune = 0x439 }),
Entity.init("jfr;", Entity.Value{ .Rune = 0x1d527 }),
Entity.init("jmath;", Entity.Value{ .Rune = 0x237 }),
Entity.init("jopf;", Entity.Value{ .Rune = 0x1d55b }),
Entity.init("jscr;", Entity.Value{ .Rune = 0x1d4bf }),
Entity.init("jsercy;", Entity.Value{ .Rune = 0x458 }),
Entity.init("jukcy;", Entity.Value{ .Rune = 0x454 }),
Entity.init("kappa;", Entity.Value{ .Rune = 0x3ba }),
Entity.init("kappav;", Entity.Value{ .Rune = 0x3f0 }),
Entity.init("kcedil;", Entity.Value{ .Rune = 0x137 }),
Entity.init("kcy;", Entity.Value{ .Rune = 0x43a }),
Entity.init("kfr;", Entity.Value{ .Rune = 0x1d528 }),
Entity.init("kgreen;", Entity.Value{ .Rune = 0x138 }),
Entity.init("khcy;", Entity.Value{ .Rune = 0x445 }),
Entity.init("kjcy;", Entity.Value{ .Rune = 0x45c }),
Entity.init("kopf;", Entity.Value{ .Rune = 0x1d55c }),
Entity.init("kscr;", Entity.Value{ .Rune = 0x1d4c0 }),
Entity.init("lAarr;", Entity.Value{ .Rune = 0x21da }),
Entity.init("lArr;", Entity.Value{ .Rune = 0x21d0 }),
Entity.init("lAtail;", Entity.Value{ .Rune = 0x291b }),
Entity.init("lBarr;", Entity.Value{ .Rune = 0x290e }),
Entity.init("lE;", Entity.Value{ .Rune = 0x2266 }),
Entity.init("lEg;", Entity.Value{ .Rune = 0x2a8b }),
Entity.init("lHar;", Entity.Value{ .Rune = 0x2962 }),
Entity.init("lacute;", Entity.Value{ .Rune = 0x13a }),
Entity.init("laemptyv;", Entity.Value{ .Rune = 0x29b4 }),
Entity.init("lagran;", Entity.Value{ .Rune = 0x2112 }),
Entity.init("lambda;", Entity.Value{ .Rune = 0x3bb }),
Entity.init("lang;", Entity.Value{ .Rune = 0x27e8 }),
Entity.init("langd;", Entity.Value{ .Rune = 0x2991 }),
Entity.init("langle;", Entity.Value{ .Rune = 0x27e8 }),
Entity.init("lap;", Entity.Value{ .Rune = 0x2a85 }),
Entity.init("laquo", Entity.Value{ .Rune = 0xab }),
Entity.init("laquo;", Entity.Value{ .Rune = 0xab }),
Entity.init("larr;", Entity.Value{ .Rune = 0x2190 }),
Entity.init("larrb;", Entity.Value{ .Rune = 0x21e4 }),
Entity.init("larrbfs;", Entity.Value{ .Rune = 0x291f }),
Entity.init("larrfs;", Entity.Value{ .Rune = 0x291d }),
Entity.init("larrhk;", Entity.Value{ .Rune = 0x21a9 }),
Entity.init("larrlp;", Entity.Value{ .Rune = 0x21ab }),
Entity.init("larrpl;", Entity.Value{ .Rune = 0x2939 }),
Entity.init("larrsim;", Entity.Value{ .Rune = 0x2973 }),
Entity.init("larrtl;", Entity.Value{ .Rune = 0x21a2 }),
Entity.init("lat;", Entity.Value{ .Rune = 0x2aab }),
Entity.init("latail;", Entity.Value{ .Rune = 0x2919 }),
Entity.init("late;", Entity.Value{ .Rune = 0x2aad }),
Entity.init("lbarr;", Entity.Value{ .Rune = 0x290c }),
Entity.init("lbbrk;", Entity.Value{ .Rune = 0x2772 }),
Entity.init("lbrace;", Entity.Value{ .Rune = 0x7b }),
Entity.init("lbrack;", Entity.Value{ .Rune = 0x5b }),
Entity.init("lbrke;", Entity.Value{ .Rune = 0x298b }),
Entity.init("lbrksld;", Entity.Value{ .Rune = 0x298f }),
Entity.init("lbrkslu;", Entity.Value{ .Rune = 0x298d }),
Entity.init("lcaron;", Entity.Value{ .Rune = 0x13e }),
Entity.init("lcedil;", Entity.Value{ .Rune = 0x13c }),
Entity.init("lceil;", Entity.Value{ .Rune = 0x2308 }),
Entity.init("lcub;", Entity.Value{ .Rune = 0x7b }),
Entity.init("lcy;", Entity.Value{ .Rune = 0x43b }),
Entity.init("ldca;", Entity.Value{ .Rune = 0x2936 }),
Entity.init("ldquo;", Entity.Value{ .Rune = 0x201c }),
Entity.init("ldquor;", Entity.Value{ .Rune = 0x201e }),
Entity.init("ldrdhar;", Entity.Value{ .Rune = 0x2967 }),
Entity.init("ldrushar;", Entity.Value{ .Rune = 0x294b }),
Entity.init("ldsh;", Entity.Value{ .Rune = 0x21b2 }),
Entity.init("le;", Entity.Value{ .Rune = 0x2264 }),
Entity.init("leftarrow;", Entity.Value{ .Rune = 0x2190 }),
Entity.init("leftarrowtail;", Entity.Value{ .Rune = 0x21a2 }),
Entity.init("leftharpoondown;", Entity.Value{ .Rune = 0x21bd }),
Entity.init("leftharpoonup;", Entity.Value{ .Rune = 0x21bc }),
Entity.init("leftleftarrows;", Entity.Value{ .Rune = 0x21c7 }),
Entity.init("leftrightarrow;", Entity.Value{ .Rune = 0x2194 }),
Entity.init("leftrightarrows;", Entity.Value{ .Rune = 0x21c6 }),
Entity.init("leftrightharpoons;", Entity.Value{ .Rune = 0x21cb }),
Entity.init("leftrightsquigarrow;", Entity.Value{ .Rune = 0x21ad }),
Entity.init("leftthreetimes;", Entity.Value{ .Rune = 0x22cb }),
Entity.init("leg;", Entity.Value{ .Rune = 0x22da }),
Entity.init("leq;", Entity.Value{ .Rune = 0x2264 }),
Entity.init("leqq;", Entity.Value{ .Rune = 0x2266 }),
Entity.init("leqslant;", Entity.Value{ .Rune = 0x2a7d }),
Entity.init("les;", Entity.Value{ .Rune = 0x2a7d }),
Entity.init("lescc;", Entity.Value{ .Rune = 0x2aa8 }),
Entity.init("lesdot;", Entity.Value{ .Rune = 0x2a7f }),
Entity.init("lesdoto;", Entity.Value{ .Rune = 0x2a81 }),
Entity.init("lesdotor;", Entity.Value{ .Rune = 0x2a83 }),
Entity.init("lesges;", Entity.Value{ .Rune = 0x2a93 }),
Entity.init("lessapprox;", Entity.Value{ .Rune = 0x2a85 }),
Entity.init("lessdot;", Entity.Value{ .Rune = 0x22d6 }),
Entity.init("lesseqgtr;", Entity.Value{ .Rune = 0x22da }),
Entity.init("lesseqqgtr;", Entity.Value{ .Rune = 0x2a8b }),
Entity.init("lessgtr;", Entity.Value{ .Rune = 0x2276 }),
Entity.init("lesssim;", Entity.Value{ .Rune = 0x2272 }),
Entity.init("lfisht;", Entity.Value{ .Rune = 0x297c }),
Entity.init("lfloor;", Entity.Value{ .Rune = 0x230a }),
Entity.init("lfr;", Entity.Value{ .Rune = 0x1d529 }),
Entity.init("lg;", Entity.Value{ .Rune = 0x2276 }),
Entity.init("lgE;", Entity.Value{ .Rune = 0x2a91 }),
Entity.init("lhard;", Entity.Value{ .Rune = 0x21bd }),
Entity.init("lharu;", Entity.Value{ .Rune = 0x21bc }),
Entity.init("lharul;", Entity.Value{ .Rune = 0x296a }),
Entity.init("lhblk;", Entity.Value{ .Rune = 0x2584 }),
Entity.init("ljcy;", Entity.Value{ .Rune = 0x459 }),
Entity.init("ll;", Entity.Value{ .Rune = 0x226a }),
Entity.init("llarr;", Entity.Value{ .Rune = 0x21c7 }),
Entity.init("llcorner;", Entity.Value{ .Rune = 0x231e }),
Entity.init("llhard;", Entity.Value{ .Rune = 0x296b }),
Entity.init("lltri;", Entity.Value{ .Rune = 0x25fa }),
Entity.init("lmidot;", Entity.Value{ .Rune = 0x140 }),
Entity.init("lmoust;", Entity.Value{ .Rune = 0x23b0 }),
Entity.init("lmoustache;", Entity.Value{ .Rune = 0x23b0 }),
Entity.init("lnE;", Entity.Value{ .Rune = 0x2268 }),
Entity.init("lnap;", Entity.Value{ .Rune = 0x2a89 }),
Entity.init("lnapprox;", Entity.Value{ .Rune = 0x2a89 }),
Entity.init("lne;", Entity.Value{ .Rune = 0x2a87 }),
Entity.init("lneq;", Entity.Value{ .Rune = 0x2a87 }),
Entity.init("lneqq;", Entity.Value{ .Rune = 0x2268 }),
Entity.init("lnsim;", Entity.Value{ .Rune = 0x22e6 }),
Entity.init("loang;", Entity.Value{ .Rune = 0x27ec }),
Entity.init("loarr;", Entity.Value{ .Rune = 0x21fd }),
Entity.init("lobrk;", Entity.Value{ .Rune = 0x27e6 }),
Entity.init("longleftarrow;", Entity.Value{ .Rune = 0x27f5 }),
Entity.init("longleftrightarrow;", Entity.Value{ .Rune = 0x27f7 }),
Entity.init("longmapsto;", Entity.Value{ .Rune = 0x27fc }),
Entity.init("longrightarrow;", Entity.Value{ .Rune = 0x27f6 }),
Entity.init("looparrowleft;", Entity.Value{ .Rune = 0x21ab }),
Entity.init("looparrowright;", Entity.Value{ .Rune = 0x21ac }),
Entity.init("lopar;", Entity.Value{ .Rune = 0x2985 }),
Entity.init("lopf;", Entity.Value{ .Rune = 0x1d55d }),
Entity.init("loplus;", Entity.Value{ .Rune = 0x2a2d }),
Entity.init("lotimes;", Entity.Value{ .Rune = 0x2a34 }),
Entity.init("lowast;", Entity.Value{ .Rune = 0x2217 }),
Entity.init("lowbar;", Entity.Value{ .Rune = 0x5f }),
Entity.init("loz;", Entity.Value{ .Rune = 0x25ca }),
Entity.init("lozenge;", Entity.Value{ .Rune = 0x25ca }),
Entity.init("lozf;", Entity.Value{ .Rune = 0x29eb }),
Entity.init("lpar;", Entity.Value{ .Rune = 0x28 }),
Entity.init("lparlt;", Entity.Value{ .Rune = 0x2993 }),
Entity.init("lrarr;", Entity.Value{ .Rune = 0x21c6 }),
Entity.init("lrcorner;", Entity.Value{ .Rune = 0x231f }),
Entity.init("lrhar;", Entity.Value{ .Rune = 0x21cb }),
Entity.init("lrhard;", Entity.Value{ .Rune = 0x296d }),
Entity.init("lrm;", Entity.Value{ .Rune = 0x200e }),
Entity.init("lrtri;", Entity.Value{ .Rune = 0x22bf }),
Entity.init("lsaquo;", Entity.Value{ .Rune = 0x2039 }),
Entity.init("lscr;", Entity.Value{ .Rune = 0x1d4c1 }),
Entity.init("lsh;", Entity.Value{ .Rune = 0x21b0 }),
Entity.init("lsim;", Entity.Value{ .Rune = 0x2272 }),
Entity.init("lsime;", Entity.Value{ .Rune = 0x2a8d }),
Entity.init("lsimg;", Entity.Value{ .Rune = 0x2a8f }),
Entity.init("lsqb;", Entity.Value{ .Rune = 0x5b }),
Entity.init("lsquo;", Entity.Value{ .Rune = 0x2018 }),
Entity.init("lsquor;", Entity.Value{ .Rune = 0x201a }),
Entity.init("lstrok;", Entity.Value{ .Rune = 0x142 }),
Entity.init("lt", Entity.Value{ .Rune = 0x3c }),
Entity.init("lt;", Entity.Value{ .Rune = 0x3c }),
Entity.init("ltcc;", Entity.Value{ .Rune = 0x2aa6 }),
Entity.init("ltcir;", Entity.Value{ .Rune = 0x2a79 }),
Entity.init("ltdot;", Entity.Value{ .Rune = 0x22d6 }),
Entity.init("lthree;", Entity.Value{ .Rune = 0x22cb }),
Entity.init("ltimes;", Entity.Value{ .Rune = 0x22c9 }),
Entity.init("ltlarr;", Entity.Value{ .Rune = 0x2976 }),
Entity.init("ltquest;", Entity.Value{ .Rune = 0x2a7b }),
Entity.init("ltrPar;", Entity.Value{ .Rune = 0x2996 }),
Entity.init("ltri;", Entity.Value{ .Rune = 0x25c3 }),
Entity.init("ltrie;", Entity.Value{ .Rune = 0x22b4 }),
Entity.init("ltrif;", Entity.Value{ .Rune = 0x25c2 }),
Entity.init("lurdshar;", Entity.Value{ .Rune = 0x294a }),
Entity.init("luruhar;", Entity.Value{ .Rune = 0x2966 }),
Entity.init("mDDot;", Entity.Value{ .Rune = 0x223a }),
Entity.init("macr", Entity.Value{ .Rune = 0xaf }),
Entity.init("macr;", Entity.Value{ .Rune = 0xaf }),
Entity.init("male;", Entity.Value{ .Rune = 0x2642 }),
Entity.init("malt;", Entity.Value{ .Rune = 0x2720 }),
Entity.init("maltese;", Entity.Value{ .Rune = 0x2720 }),
Entity.init("map;", Entity.Value{ .Rune = 0x21a6 }),
Entity.init("mapsto;", Entity.Value{ .Rune = 0x21a6 }),
Entity.init("mapstodown;", Entity.Value{ .Rune = 0x21a7 }),
Entity.init("mapstoleft;", Entity.Value{ .Rune = 0x21a4 }),
Entity.init("mapstoup;", Entity.Value{ .Rune = 0x21a5 }),
Entity.init("marker;", Entity.Value{ .Rune = 0x25ae }),
Entity.init("mcomma;", Entity.Value{ .Rune = 0x2a29 }),
Entity.init("mcy;", Entity.Value{ .Rune = 0x43c }),
Entity.init("mdash;", Entity.Value{ .Rune = 0x2014 }),
Entity.init("measuredangle;", Entity.Value{ .Rune = 0x2221 }),
Entity.init("mfr;", Entity.Value{ .Rune = 0x1d52a }),
Entity.init("mho;", Entity.Value{ .Rune = 0x2127 }),
Entity.init("micro", Entity.Value{ .Rune = 0xb5 }),
Entity.init("micro;", Entity.Value{ .Rune = 0xb5 }),
Entity.init("mid;", Entity.Value{ .Rune = 0x2223 }),
Entity.init("midast;", Entity.Value{ .Rune = 0x2a }),
Entity.init("midcir;", Entity.Value{ .Rune = 0x2af0 }),
Entity.init("middot", Entity.Value{ .Rune = 0xb7 }),
Entity.init("middot;", Entity.Value{ .Rune = 0xb7 }),
Entity.init("minus;", Entity.Value{ .Rune = 0x2212 }),
Entity.init("minusb;", Entity.Value{ .Rune = 0x229f }),
Entity.init("minusd;", Entity.Value{ .Rune = 0x2238 }),
Entity.init("minusdu;", Entity.Value{ .Rune = 0x2a2a }),
Entity.init("mlcp;", Entity.Value{ .Rune = 0x2adb }),
Entity.init("mldr;", Entity.Value{ .Rune = 0x2026 }),
Entity.init("mnplus;", Entity.Value{ .Rune = 0x2213 }),
Entity.init("models;", Entity.Value{ .Rune = 0x22a7 }),
Entity.init("mopf;", Entity.Value{ .Rune = 0x1d55e }),
Entity.init("mp;", Entity.Value{ .Rune = 0x2213 }),
Entity.init("mscr;", Entity.Value{ .Rune = 0x1d4c2 }),
Entity.init("mstpos;", Entity.Value{ .Rune = 0x223e }),
Entity.init("mu;", Entity.Value{ .Rune = 0x3bc }),
Entity.init("multimap;", Entity.Value{ .Rune = 0x22b8 }),
Entity.init("mumap;", Entity.Value{ .Rune = 0x22b8 }),
Entity.init("nLeftarrow;", Entity.Value{ .Rune = 0x21cd }),
Entity.init("nLeftrightarrow;", Entity.Value{ .Rune = 0x21ce }),
Entity.init("nRightarrow;", Entity.Value{ .Rune = 0x21cf }),
Entity.init("nVDash;", Entity.Value{ .Rune = 0x22af }),
Entity.init("nVdash;", Entity.Value{ .Rune = 0x22ae }),
Entity.init("nabla;", Entity.Value{ .Rune = 0x2207 }),
Entity.init("nacute;", Entity.Value{ .Rune = 0x144 }),
Entity.init("nap;", Entity.Value{ .Rune = 0x2249 }),
Entity.init("napos;", Entity.Value{ .Rune = 0x149 }),
Entity.init("napprox;", Entity.Value{ .Rune = 0x2249 }),
Entity.init("natur;", Entity.Value{ .Rune = 0x266e }),
Entity.init("natural;", Entity.Value{ .Rune = 0x266e }),
Entity.init("naturals;", Entity.Value{ .Rune = 0x2115 }),
Entity.init("nbsp", Entity.Value{ .Rune = 0xa0 }),
Entity.init("nbsp;", Entity.Value{ .Rune = 0xa0 }),
Entity.init("ncap;", Entity.Value{ .Rune = 0x2a43 }),
Entity.init("ncaron;", Entity.Value{ .Rune = 0x148 }),
Entity.init("ncedil;", Entity.Value{ .Rune = 0x146 }),
Entity.init("ncong;", Entity.Value{ .Rune = 0x2247 }),
Entity.init("ncup;", Entity.Value{ .Rune = 0x2a42 }),
Entity.init("ncy;", Entity.Value{ .Rune = 0x43d }),
Entity.init("ndash;", Entity.Value{ .Rune = 0x2013 }),
Entity.init("ne;", Entity.Value{ .Rune = 0x2260 }),
Entity.init("neArr;", Entity.Value{ .Rune = 0x21d7 }),
Entity.init("nearhk;", Entity.Value{ .Rune = 0x2924 }),
Entity.init("nearr;", Entity.Value{ .Rune = 0x2197 }),
Entity.init("nearrow;", Entity.Value{ .Rune = 0x2197 }),
Entity.init("nequiv;", Entity.Value{ .Rune = 0x2262 }),
Entity.init("nesear;", Entity.Value{ .Rune = 0x2928 }),
Entity.init("nexist;", Entity.Value{ .Rune = 0x2204 }),
Entity.init("nexists;", Entity.Value{ .Rune = 0x2204 }),
Entity.init("nfr;", Entity.Value{ .Rune = 0x1d52b }),
Entity.init("nge;", Entity.Value{ .Rune = 0x2271 }),
Entity.init("ngeq;", Entity.Value{ .Rune = 0x2271 }),
Entity.init("ngsim;", Entity.Value{ .Rune = 0x2275 }),
Entity.init("ngt;", Entity.Value{ .Rune = 0x226f }),
Entity.init("ngtr;", Entity.Value{ .Rune = 0x226f }),
Entity.init("nhArr;", Entity.Value{ .Rune = 0x21ce }),
Entity.init("nharr;", Entity.Value{ .Rune = 0x21ae }),
Entity.init("nhpar;", Entity.Value{ .Rune = 0x2af2 }),
Entity.init("ni;", Entity.Value{ .Rune = 0x220b }),
Entity.init("nis;", Entity.Value{ .Rune = 0x22fc }),
Entity.init("nisd;", Entity.Value{ .Rune = 0x22fa }),
Entity.init("niv;", Entity.Value{ .Rune = 0x220b }),
Entity.init("njcy;", Entity.Value{ .Rune = 0x45a }),
Entity.init("nlArr;", Entity.Value{ .Rune = 0x21cd }),
Entity.init("nlarr;", Entity.Value{ .Rune = 0x219a }),
Entity.init("nldr;", Entity.Value{ .Rune = 0x2025 }),
Entity.init("nle;", Entity.Value{ .Rune = 0x2270 }),
Entity.init("nleftarrow;", Entity.Value{ .Rune = 0x219a }),
Entity.init("nleftrightarrow;", Entity.Value{ .Rune = 0x21ae }),
Entity.init("nleq;", Entity.Value{ .Rune = 0x2270 }),
Entity.init("nless;", Entity.Value{ .Rune = 0x226e }),
Entity.init("nlsim;", Entity.Value{ .Rune = 0x2274 }),
Entity.init("nlt;", Entity.Value{ .Rune = 0x226e }),
Entity.init("nltri;", Entity.Value{ .Rune = 0x22ea }),
Entity.init("nltrie;", Entity.Value{ .Rune = 0x22ec }),
Entity.init("nmid;", Entity.Value{ .Rune = 0x2224 }),
Entity.init("nopf;", Entity.Value{ .Rune = 0x1d55f }),
Entity.init("not", Entity.Value{ .Rune = 0xac }),
Entity.init("not;", Entity.Value{ .Rune = 0xac }),
Entity.init("notin;", Entity.Value{ .Rune = 0x2209 }),
Entity.init("notinva;", Entity.Value{ .Rune = 0x2209 }),
Entity.init("notinvb;", Entity.Value{ .Rune = 0x22f7 }),
Entity.init("notinvc;", Entity.Value{ .Rune = 0x22f6 }),
Entity.init("notni;", Entity.Value{ .Rune = 0x220c }),
Entity.init("notniva;", Entity.Value{ .Rune = 0x220c }),
Entity.init("notnivb;", Entity.Value{ .Rune = 0x22fe }),
Entity.init("notnivc;", Entity.Value{ .Rune = 0x22fd }),
Entity.init("npar;", Entity.Value{ .Rune = 0x2226 }),
Entity.init("nparallel;", Entity.Value{ .Rune = 0x2226 }),
Entity.init("npolint;", Entity.Value{ .Rune = 0x2a14 }),
Entity.init("npr;", Entity.Value{ .Rune = 0x2280 }),
Entity.init("nprcue;", Entity.Value{ .Rune = 0x22e0 }),
Entity.init("nprec;", Entity.Value{ .Rune = 0x2280 }),
Entity.init("nrArr;", Entity.Value{ .Rune = 0x21cf }),
Entity.init("nrarr;", Entity.Value{ .Rune = 0x219b }),
Entity.init("nrightarrow;", Entity.Value{ .Rune = 0x219b }),
Entity.init("nrtri;", Entity.Value{ .Rune = 0x22eb }),
Entity.init("nrtrie;", Entity.Value{ .Rune = 0x22ed }),
Entity.init("nsc;", Entity.Value{ .Rune = 0x2281 }),
Entity.init("nsccue;", Entity.Value{ .Rune = 0x22e1 }),
Entity.init("nscr;", Entity.Value{ .Rune = 0x1d4c3 }),
Entity.init("nshortmid;", Entity.Value{ .Rune = 0x2224 }),
Entity.init("nshortparallel;", Entity.Value{ .Rune = 0x2226 }),
Entity.init("nsim;", Entity.Value{ .Rune = 0x2241 }),
Entity.init("nsime;", Entity.Value{ .Rune = 0x2244 }),
Entity.init("nsimeq;", Entity.Value{ .Rune = 0x2244 }),
Entity.init("nsmid;", Entity.Value{ .Rune = 0x2224 }),
Entity.init("nspar;", Entity.Value{ .Rune = 0x2226 }),
Entity.init("nsqsube;", Entity.Value{ .Rune = 0x22e2 }),
Entity.init("nsqsupe;", Entity.Value{ .Rune = 0x22e3 }),
Entity.init("nsub;", Entity.Value{ .Rune = 0x2284 }),
Entity.init("nsube;", Entity.Value{ .Rune = 0x2288 }),
Entity.init("nsubseteq;", Entity.Value{ .Rune = 0x2288 }),
Entity.init("nsucc;", Entity.Value{ .Rune = 0x2281 }),
Entity.init("nsup;", Entity.Value{ .Rune = 0x2285 }),
Entity.init("nsupe;", Entity.Value{ .Rune = 0x2289 }),
Entity.init("nsupseteq;", Entity.Value{ .Rune = 0x2289 }),
Entity.init("ntgl;", Entity.Value{ .Rune = 0x2279 }),
Entity.init("ntilde", Entity.Value{ .Rune = 0xf1 }),
Entity.init("ntilde;", Entity.Value{ .Rune = 0xf1 }),
Entity.init("ntlg;", Entity.Value{ .Rune = 0x2278 }),
Entity.init("ntriangleleft;", Entity.Value{ .Rune = 0x22ea }),
Entity.init("ntrianglelefteq;", Entity.Value{ .Rune = 0x22ec }),
Entity.init("ntriangleright;", Entity.Value{ .Rune = 0x22eb }),
Entity.init("ntrianglerighteq;", Entity.Value{ .Rune = 0x22ed }),
Entity.init("nu;", Entity.Value{ .Rune = 0x3bd }),
Entity.init("num;", Entity.Value{ .Rune = 0x23 }),
Entity.init("numero;", Entity.Value{ .Rune = 0x2116 }),
Entity.init("numsp;", Entity.Value{ .Rune = 0x2007 }),
Entity.init("nvDash;", Entity.Value{ .Rune = 0x22ad }),
Entity.init("nvHarr;", Entity.Value{ .Rune = 0x2904 }),
Entity.init("nvdash;", Entity.Value{ .Rune = 0x22ac }),
Entity.init("nvinfin;", Entity.Value{ .Rune = 0x29de }),
Entity.init("nvlArr;", Entity.Value{ .Rune = 0x2902 }),
Entity.init("nvrArr;", Entity.Value{ .Rune = 0x2903 }),
Entity.init("nwArr;", Entity.Value{ .Rune = 0x21d6 }),
Entity.init("nwarhk;", Entity.Value{ .Rune = 0x2923 }),
Entity.init("nwarr;", Entity.Value{ .Rune = 0x2196 }),
Entity.init("nwarrow;", Entity.Value{ .Rune = 0x2196 }),
Entity.init("nwnear;", Entity.Value{ .Rune = 0x2927 }),
Entity.init("oS;", Entity.Value{ .Rune = 0x24c8 }),
Entity.init("oacute", Entity.Value{ .Rune = 0xf3 }),
Entity.init("oacute;", Entity.Value{ .Rune = 0xf3 }),
Entity.init("oast;", Entity.Value{ .Rune = 0x229b }),
Entity.init("ocir;", Entity.Value{ .Rune = 0x229a }),
Entity.init("ocirc", Entity.Value{ .Rune = 0xf4 }),
Entity.init("ocirc;", Entity.Value{ .Rune = 0xf4 }),
Entity.init("ocy;", Entity.Value{ .Rune = 0x43e }),
Entity.init("odash;", Entity.Value{ .Rune = 0x229d }),
Entity.init("odblac;", Entity.Value{ .Rune = 0x151 }),
Entity.init("odiv;", Entity.Value{ .Rune = 0x2a38 }),
Entity.init("odot;", Entity.Value{ .Rune = 0x2299 }),
Entity.init("odsold;", Entity.Value{ .Rune = 0x29bc }),
Entity.init("oelig;", Entity.Value{ .Rune = 0x153 }),
Entity.init("ofcir;", Entity.Value{ .Rune = 0x29bf }),
Entity.init("ofr;", Entity.Value{ .Rune = 0x1d52c }),
Entity.init("ogon;", Entity.Value{ .Rune = 0x2db }),
Entity.init("ograve", Entity.Value{ .Rune = 0xf2 }),
Entity.init("ograve;", Entity.Value{ .Rune = 0xf2 }),
Entity.init("ogt;", Entity.Value{ .Rune = 0x29c1 }),
Entity.init("ohbar;", Entity.Value{ .Rune = 0x29b5 }),
Entity.init("ohm;", Entity.Value{ .Rune = 0x3a9 }),
Entity.init("oint;", Entity.Value{ .Rune = 0x222e }),
Entity.init("olarr;", Entity.Value{ .Rune = 0x21ba }),
Entity.init("olcir;", Entity.Value{ .Rune = 0x29be }),
Entity.init("olcross;", Entity.Value{ .Rune = 0x29bb }),
Entity.init("oline;", Entity.Value{ .Rune = 0x203e }),
Entity.init("olt;", Entity.Value{ .Rune = 0x29c0 }),
Entity.init("omacr;", Entity.Value{ .Rune = 0x14d }),
Entity.init("omega;", Entity.Value{ .Rune = 0x3c9 }),
Entity.init("omicron;", Entity.Value{ .Rune = 0x3bf }),
Entity.init("omid;", Entity.Value{ .Rune = 0x29b6 }),
Entity.init("ominus;", Entity.Value{ .Rune = 0x2296 }),
Entity.init("oopf;", Entity.Value{ .Rune = 0x1d560 }),
Entity.init("opar;", Entity.Value{ .Rune = 0x29b7 }),
Entity.init("operp;", Entity.Value{ .Rune = 0x29b9 }),
Entity.init("oplus;", Entity.Value{ .Rune = 0x2295 }),
Entity.init("or;", Entity.Value{ .Rune = 0x2228 }),
Entity.init("orarr;", Entity.Value{ .Rune = 0x21bb }),
Entity.init("ord;", Entity.Value{ .Rune = 0x2a5d }),
Entity.init("order;", Entity.Value{ .Rune = 0x2134 }),
Entity.init("orderof;", Entity.Value{ .Rune = 0x2134 }),
Entity.init("ordf", Entity.Value{ .Rune = 0xaa }),
Entity.init("ordf;", Entity.Value{ .Rune = 0xaa }),
Entity.init("ordm", Entity.Value{ .Rune = 0xba }),
Entity.init("ordm;", Entity.Value{ .Rune = 0xba }),
Entity.init("origof;", Entity.Value{ .Rune = 0x22b6 }),
Entity.init("oror;", Entity.Value{ .Rune = 0x2a56 }),
Entity.init("orslope;", Entity.Value{ .Rune = 0x2a57 }),
Entity.init("orv;", Entity.Value{ .Rune = 0x2a5b }),
Entity.init("oscr;", Entity.Value{ .Rune = 0x2134 }),
Entity.init("oslash", Entity.Value{ .Rune = 0xf8 }),
Entity.init("oslash;", Entity.Value{ .Rune = 0xf8 }),
Entity.init("osol;", Entity.Value{ .Rune = 0x2298 }),
Entity.init("otilde", Entity.Value{ .Rune = 0xf5 }),
Entity.init("otilde;", Entity.Value{ .Rune = 0xf5 }),
Entity.init("otimes;", Entity.Value{ .Rune = 0x2297 }),
Entity.init("otimesas;", Entity.Value{ .Rune = 0x2a36 }),
Entity.init("ouml", Entity.Value{ .Rune = 0xf6 }),
Entity.init("ouml;", Entity.Value{ .Rune = 0xf6 }),
Entity.init("ovbar;", Entity.Value{ .Rune = 0x233d }),
Entity.init("par;", Entity.Value{ .Rune = 0x2225 }),
Entity.init("para", Entity.Value{ .Rune = 0xb6 }),
Entity.init("para;", Entity.Value{ .Rune = 0xb6 }),
Entity.init("parallel;", Entity.Value{ .Rune = 0x2225 }),
Entity.init("parsim;", Entity.Value{ .Rune = 0x2af3 }),
Entity.init("parsl;", Entity.Value{ .Rune = 0x2afd }),
Entity.init("part;", Entity.Value{ .Rune = 0x2202 }),
Entity.init("pcy;", Entity.Value{ .Rune = 0x43f }),
Entity.init("percnt;", Entity.Value{ .Rune = 0x25 }),
Entity.init("period;", Entity.Value{ .Rune = 0x2e }),
Entity.init("permil;", Entity.Value{ .Rune = 0x2030 }),
Entity.init("perp;", Entity.Value{ .Rune = 0x22a5 }),
Entity.init("pertenk;", Entity.Value{ .Rune = 0x2031 }),
Entity.init("pfr;", Entity.Value{ .Rune = 0x1d52d }),
Entity.init("phi;", Entity.Value{ .Rune = 0x3c6 }),
Entity.init("phiv;", Entity.Value{ .Rune = 0x3d5 }),
Entity.init("phmmat;", Entity.Value{ .Rune = 0x2133 }),
Entity.init("phone;", Entity.Value{ .Rune = 0x260e }),
Entity.init("pi;", Entity.Value{ .Rune = 0x3c0 }),
Entity.init("pitchfork;", Entity.Value{ .Rune = 0x22d4 }),
Entity.init("piv;", Entity.Value{ .Rune = 0x3d6 }),
Entity.init("planck;", Entity.Value{ .Rune = 0x210f }),
Entity.init("planckh;", Entity.Value{ .Rune = 0x210e }),
Entity.init("plankv;", Entity.Value{ .Rune = 0x210f }),
Entity.init("plus;", Entity.Value{ .Rune = 0x2b }),
Entity.init("plusacir;", Entity.Value{ .Rune = 0x2a23 }),
Entity.init("plusb;", Entity.Value{ .Rune = 0x229e }),
Entity.init("pluscir;", Entity.Value{ .Rune = 0x2a22 }),
Entity.init("plusdo;", Entity.Value{ .Rune = 0x2214 }),
Entity.init("plusdu;", Entity.Value{ .Rune = 0x2a25 }),
Entity.init("pluse;", Entity.Value{ .Rune = 0x2a72 }),
Entity.init("plusmn", Entity.Value{ .Rune = 0xb1 }),
Entity.init("plusmn;", Entity.Value{ .Rune = 0xb1 }),
Entity.init("plussim;", Entity.Value{ .Rune = 0x2a26 }),
Entity.init("plustwo;", Entity.Value{ .Rune = 0x2a27 }),
Entity.init("pm;", Entity.Value{ .Rune = 0xb1 }),
Entity.init("pointint;", Entity.Value{ .Rune = 0x2a15 }),
Entity.init("popf;", Entity.Value{ .Rune = 0x1d561 }),
Entity.init("pound", Entity.Value{ .Rune = 0xa3 }),
Entity.init("pound;", Entity.Value{ .Rune = 0xa3 }),
Entity.init("pr;", Entity.Value{ .Rune = 0x227a }),
Entity.init("prE;", Entity.Value{ .Rune = 0x2ab3 }),
Entity.init("prap;", Entity.Value{ .Rune = 0x2ab7 }),
Entity.init("prcue;", Entity.Value{ .Rune = 0x227c }),
Entity.init("pre;", Entity.Value{ .Rune = 0x2aaf }),
Entity.init("prec;", Entity.Value{ .Rune = 0x227a }),
Entity.init("precapprox;", Entity.Value{ .Rune = 0x2ab7 }),
Entity.init("preccurlyeq;", Entity.Value{ .Rune = 0x227c }),
Entity.init("preceq;", Entity.Value{ .Rune = 0x2aaf }),
Entity.init("precnapprox;", Entity.Value{ .Rune = 0x2ab9 }),
Entity.init("precneqq;", Entity.Value{ .Rune = 0x2ab5 }),
Entity.init("precnsim;", Entity.Value{ .Rune = 0x22e8 }),
Entity.init("precsim;", Entity.Value{ .Rune = 0x227e }),
Entity.init("prime;", Entity.Value{ .Rune = 0x2032 }),
Entity.init("primes;", Entity.Value{ .Rune = 0x2119 }),
Entity.init("prnE;", Entity.Value{ .Rune = 0x2ab5 }),
Entity.init("prnap;", Entity.Value{ .Rune = 0x2ab9 }),
Entity.init("prnsim;", Entity.Value{ .Rune = 0x22e8 }),
Entity.init("prod;", Entity.Value{ .Rune = 0x220f }),
Entity.init("profalar;", Entity.Value{ .Rune = 0x232e }),
Entity.init("profline;", Entity.Value{ .Rune = 0x2312 }),
Entity.init("profsurf;", Entity.Value{ .Rune = 0x2313 }),
Entity.init("prop;", Entity.Value{ .Rune = 0x221d }),
Entity.init("propto;", Entity.Value{ .Rune = 0x221d }),
Entity.init("prsim;", Entity.Value{ .Rune = 0x227e }),
Entity.init("prurel;", Entity.Value{ .Rune = 0x22b0 }),
Entity.init("pscr;", Entity.Value{ .Rune = 0x1d4c5 }),
Entity.init("psi;", Entity.Value{ .Rune = 0x3c8 }),
Entity.init("puncsp;", Entity.Value{ .Rune = 0x2008 }),
Entity.init("qfr;", Entity.Value{ .Rune = 0x1d52e }),
Entity.init("qint;", Entity.Value{ .Rune = 0x2a0c }),
Entity.init("qopf;", Entity.Value{ .Rune = 0x1d562 }),
Entity.init("qprime;", Entity.Value{ .Rune = 0x2057 }),
Entity.init("qscr;", Entity.Value{ .Rune = 0x1d4c6 }),
Entity.init("quaternions;", Entity.Value{ .Rune = 0x210d }),
Entity.init("quatint;", Entity.Value{ .Rune = 0x2a16 }),
Entity.init("quest;", Entity.Value{ .Rune = 0x3f }),
Entity.init("questeq;", Entity.Value{ .Rune = 0x225f }),
Entity.init("quot", Entity.Value{ .Rune = 0x22 }),
Entity.init("quot;", Entity.Value{ .Rune = 0x22 }),
Entity.init("rAarr;", Entity.Value{ .Rune = 0x21db }),
Entity.init("rArr;", Entity.Value{ .Rune = 0x21d2 }),
Entity.init("rAtail;", Entity.Value{ .Rune = 0x291c }),
Entity.init("rBarr;", Entity.Value{ .Rune = 0x290f }),
Entity.init("rHar;", Entity.Value{ .Rune = 0x2964 }),
Entity.init("racute;", Entity.Value{ .Rune = 0x155 }),
Entity.init("radic;", Entity.Value{ .Rune = 0x221a }),
Entity.init("raemptyv;", Entity.Value{ .Rune = 0x29b3 }),
Entity.init("rang;", Entity.Value{ .Rune = 0x27e9 }),
Entity.init("rangd;", Entity.Value{ .Rune = 0x2992 }),
Entity.init("range;", Entity.Value{ .Rune = 0x29a5 }),
Entity.init("rangle;", Entity.Value{ .Rune = 0x27e9 }),
Entity.init("raquo", Entity.Value{ .Rune = 0xbb }),
Entity.init("raquo;", Entity.Value{ .Rune = 0xbb }),
Entity.init("rarr;", Entity.Value{ .Rune = 0x2192 }),
Entity.init("rarrap;", Entity.Value{ .Rune = 0x2975 }),
Entity.init("rarrb;", Entity.Value{ .Rune = 0x21e5 }),
Entity.init("rarrbfs;", Entity.Value{ .Rune = 0x2920 }),
Entity.init("rarrc;", Entity.Value{ .Rune = 0x2933 }),
Entity.init("rarrfs;", Entity.Value{ .Rune = 0x291e }),
Entity.init("rarrhk;", Entity.Value{ .Rune = 0x21aa }),
Entity.init("rarrlp;", Entity.Value{ .Rune = 0x21ac }),
Entity.init("rarrpl;", Entity.Value{ .Rune = 0x2945 }),
Entity.init("rarrsim;", Entity.Value{ .Rune = 0x2974 }),
Entity.init("rarrtl;", Entity.Value{ .Rune = 0x21a3 }),
Entity.init("rarrw;", Entity.Value{ .Rune = 0x219d }),
Entity.init("ratail;", Entity.Value{ .Rune = 0x291a }),
Entity.init("ratio;", Entity.Value{ .Rune = 0x2236 }),
Entity.init("rationals;", Entity.Value{ .Rune = 0x211a }),
Entity.init("rbarr;", Entity.Value{ .Rune = 0x290d }),
Entity.init("rbbrk;", Entity.Value{ .Rune = 0x2773 }),
Entity.init("rbrace;", Entity.Value{ .Rune = 0x7d }),
Entity.init("rbrack;", Entity.Value{ .Rune = 0x5d }),
Entity.init("rbrke;", Entity.Value{ .Rune = 0x298c }),
Entity.init("rbrksld;", Entity.Value{ .Rune = 0x298e }),
Entity.init("rbrkslu;", Entity.Value{ .Rune = 0x2990 }),
Entity.init("rcaron;", Entity.Value{ .Rune = 0x159 }),
Entity.init("rcedil;", Entity.Value{ .Rune = 0x157 }),
Entity.init("rceil;", Entity.Value{ .Rune = 0x2309 }),
Entity.init("rcub;", Entity.Value{ .Rune = 0x7d }),
Entity.init("rcy;", Entity.Value{ .Rune = 0x440 }),
Entity.init("rdca;", Entity.Value{ .Rune = 0x2937 }),
Entity.init("rdldhar;", Entity.Value{ .Rune = 0x2969 }),
Entity.init("rdquo;", Entity.Value{ .Rune = 0x201d }),
Entity.init("rdquor;", Entity.Value{ .Rune = 0x201d }),
Entity.init("rdsh;", Entity.Value{ .Rune = 0x21b3 }),
Entity.init("real;", Entity.Value{ .Rune = 0x211c }),
Entity.init("realine;", Entity.Value{ .Rune = 0x211b }),
Entity.init("realpart;", Entity.Value{ .Rune = 0x211c }),
Entity.init("reals;", Entity.Value{ .Rune = 0x211d }),
Entity.init("rect;", Entity.Value{ .Rune = 0x25ad }),
Entity.init("reg", Entity.Value{ .Rune = 0xae }),
Entity.init("reg;", Entity.Value{ .Rune = 0xae }),
Entity.init("rfisht;", Entity.Value{ .Rune = 0x297d }),
Entity.init("rfloor;", Entity.Value{ .Rune = 0x230b }),
Entity.init("rfr;", Entity.Value{ .Rune = 0x1d52f }),
Entity.init("rhard;", Entity.Value{ .Rune = 0x21c1 }),
Entity.init("rharu;", Entity.Value{ .Rune = 0x21c0 }),
Entity.init("rharul;", Entity.Value{ .Rune = 0x296c }),
Entity.init("rho;", Entity.Value{ .Rune = 0x3c1 }),
Entity.init("rhov;", Entity.Value{ .Rune = 0x3f1 }),
Entity.init("rightarrow;", Entity.Value{ .Rune = 0x2192 }),
Entity.init("rightarrowtail;", Entity.Value{ .Rune = 0x21a3 }),
Entity.init("rightharpoondown;", Entity.Value{ .Rune = 0x21c1 }),
Entity.init("rightharpoonup;", Entity.Value{ .Rune = 0x21c0 }),
Entity.init("rightleftarrows;", Entity.Value{ .Rune = 0x21c4 }),
Entity.init("rightleftharpoons;", Entity.Value{ .Rune = 0x21cc }),
Entity.init("rightrightarrows;", Entity.Value{ .Rune = 0x21c9 }),
Entity.init("rightsquigarrow;", Entity.Value{ .Rune = 0x219d }),
Entity.init("rightthreetimes;", Entity.Value{ .Rune = 0x22cc }),
Entity.init("ring;", Entity.Value{ .Rune = 0x2da }),
Entity.init("risingdotseq;", Entity.Value{ .Rune = 0x2253 }),
Entity.init("rlarr;", Entity.Value{ .Rune = 0x21c4 }),
Entity.init("rlhar;", Entity.Value{ .Rune = 0x21cc }),
Entity.init("rlm;", Entity.Value{ .Rune = 0x200f }),
Entity.init("rmoust;", Entity.Value{ .Rune = 0x23b1 }),
Entity.init("rmoustache;", Entity.Value{ .Rune = 0x23b1 }),
Entity.init("rnmid;", Entity.Value{ .Rune = 0x2aee }),
Entity.init("roang;", Entity.Value{ .Rune = 0x27ed }),
Entity.init("roarr;", Entity.Value{ .Rune = 0x21fe }),
Entity.init("robrk;", Entity.Value{ .Rune = 0x27e7 }),
Entity.init("ropar;", Entity.Value{ .Rune = 0x2986 }),
Entity.init("ropf;", Entity.Value{ .Rune = 0x1d563 }),
Entity.init("roplus;", Entity.Value{ .Rune = 0x2a2e }),
Entity.init("rotimes;", Entity.Value{ .Rune = 0x2a35 }),
Entity.init("rpar;", Entity.Value{ .Rune = 0x29 }),
Entity.init("rpargt;", Entity.Value{ .Rune = 0x2994 }),
Entity.init("rppolint;", Entity.Value{ .Rune = 0x2a12 }),
Entity.init("rrarr;", Entity.Value{ .Rune = 0x21c9 }),
Entity.init("rsaquo;", Entity.Value{ .Rune = 0x203a }),
Entity.init("rscr;", Entity.Value{ .Rune = 0x1d4c7 }),
Entity.init("rsh;", Entity.Value{ .Rune = 0x21b1 }),
Entity.init("rsqb;", Entity.Value{ .Rune = 0x5d }),
Entity.init("rsquo;", Entity.Value{ .Rune = 0x2019 }),
Entity.init("rsquor;", Entity.Value{ .Rune = 0x2019 }),
Entity.init("rthree;", Entity.Value{ .Rune = 0x22cc }),
Entity.init("rtimes;", Entity.Value{ .Rune = 0x22ca }),
Entity.init("rtri;", Entity.Value{ .Rune = 0x25b9 }),
Entity.init("rtrie;", Entity.Value{ .Rune = 0x22b5 }),
Entity.init("rtrif;", Entity.Value{ .Rune = 0x25b8 }),
Entity.init("rtriltri;", Entity.Value{ .Rune = 0x29ce }),
Entity.init("ruluhar;", Entity.Value{ .Rune = 0x2968 }),
Entity.init("rx;", Entity.Value{ .Rune = 0x211e }),
Entity.init("sacute;", Entity.Value{ .Rune = 0x15b }),
Entity.init("sbquo;", Entity.Value{ .Rune = 0x201a }),
Entity.init("sc;", Entity.Value{ .Rune = 0x227b }),
Entity.init("scE;", Entity.Value{ .Rune = 0x2ab4 }),
Entity.init("scap;", Entity.Value{ .Rune = 0x2ab8 }),
Entity.init("scaron;", Entity.Value{ .Rune = 0x161 }),
Entity.init("sccue;", Entity.Value{ .Rune = 0x227d }),
Entity.init("sce;", Entity.Value{ .Rune = 0x2ab0 }),
Entity.init("scedil;", Entity.Value{ .Rune = 0x15f }),
Entity.init("scirc;", Entity.Value{ .Rune = 0x15d }),
Entity.init("scnE;", Entity.Value{ .Rune = 0x2ab6 }),
Entity.init("scnap;", Entity.Value{ .Rune = 0x2aba }),
Entity.init("scnsim;", Entity.Value{ .Rune = 0x22e9 }),
Entity.init("scpolint;", Entity.Value{ .Rune = 0x2a13 }),
Entity.init("scsim;", Entity.Value{ .Rune = 0x227f }),
Entity.init("scy;", Entity.Value{ .Rune = 0x441 }),
Entity.init("sdot;", Entity.Value{ .Rune = 0x22c5 }),
Entity.init("sdotb;", Entity.Value{ .Rune = 0x22a1 }),
Entity.init("sdote;", Entity.Value{ .Rune = 0x2a66 }),
Entity.init("seArr;", Entity.Value{ .Rune = 0x21d8 }),
Entity.init("searhk;", Entity.Value{ .Rune = 0x2925 }),
Entity.init("searr;", Entity.Value{ .Rune = 0x2198 }),
Entity.init("searrow;", Entity.Value{ .Rune = 0x2198 }),
Entity.init("sect", Entity.Value{ .Rune = 0xa7 }),
Entity.init("sect;", Entity.Value{ .Rune = 0xa7 }),
Entity.init("semi;", Entity.Value{ .Rune = 0x3b }),
Entity.init("seswar;", Entity.Value{ .Rune = 0x2929 }),
Entity.init("setminus;", Entity.Value{ .Rune = 0x2216 }),
Entity.init("setmn;", Entity.Value{ .Rune = 0x2216 }),
Entity.init("sext;", Entity.Value{ .Rune = 0x2736 }),
Entity.init("sfr;", Entity.Value{ .Rune = 0x1d530 }),
Entity.init("sfrown;", Entity.Value{ .Rune = 0x2322 }),
Entity.init("sharp;", Entity.Value{ .Rune = 0x266f }),
Entity.init("shchcy;", Entity.Value{ .Rune = 0x449 }),
Entity.init("shcy;", Entity.Value{ .Rune = 0x448 }),
Entity.init("shortmid;", Entity.Value{ .Rune = 0x2223 }),
Entity.init("shortparallel;", Entity.Value{ .Rune = 0x2225 }),
Entity.init("shy", Entity.Value{ .Rune = 0xad }),
Entity.init("shy;", Entity.Value{ .Rune = 0xad }),
Entity.init("sigma;", Entity.Value{ .Rune = 0x3c3 }),
Entity.init("sigmaf;", Entity.Value{ .Rune = 0x3c2 }),
Entity.init("sigmav;", Entity.Value{ .Rune = 0x3c2 }),
Entity.init("sim;", Entity.Value{ .Rune = 0x223c }),
Entity.init("simdot;", Entity.Value{ .Rune = 0x2a6a }),
Entity.init("sime;", Entity.Value{ .Rune = 0x2243 }),
Entity.init("simeq;", Entity.Value{ .Rune = 0x2243 }),
Entity.init("simg;", Entity.Value{ .Rune = 0x2a9e }),
Entity.init("simgE;", Entity.Value{ .Rune = 0x2aa0 }),
Entity.init("siml;", Entity.Value{ .Rune = 0x2a9d }),
Entity.init("simlE;", Entity.Value{ .Rune = 0x2a9f }),
Entity.init("simne;", Entity.Value{ .Rune = 0x2246 }),
Entity.init("simplus;", Entity.Value{ .Rune = 0x2a24 }),
Entity.init("simrarr;", Entity.Value{ .Rune = 0x2972 }),
Entity.init("slarr;", Entity.Value{ .Rune = 0x2190 }),
Entity.init("smallsetminus;", Entity.Value{ .Rune = 0x2216 }),
Entity.init("smashp;", Entity.Value{ .Rune = 0x2a33 }),
Entity.init("smeparsl;", Entity.Value{ .Rune = 0x29e4 }),
Entity.init("smid;", Entity.Value{ .Rune = 0x2223 }),
Entity.init("smile;", Entity.Value{ .Rune = 0x2323 }),
Entity.init("smt;", Entity.Value{ .Rune = 0x2aaa }),
Entity.init("smte;", Entity.Value{ .Rune = 0x2aac }),
Entity.init("softcy;", Entity.Value{ .Rune = 0x44c }),
Entity.init("sol;", Entity.Value{ .Rune = 0x2f }),
Entity.init("solb;", Entity.Value{ .Rune = 0x29c4 }),
Entity.init("solbar;", Entity.Value{ .Rune = 0x233f }),
Entity.init("sopf;", Entity.Value{ .Rune = 0x1d564 }),
Entity.init("spades;", Entity.Value{ .Rune = 0x2660 }),
Entity.init("spadesuit;", Entity.Value{ .Rune = 0x2660 }),
Entity.init("spar;", Entity.Value{ .Rune = 0x2225 }),
Entity.init("sqcap;", Entity.Value{ .Rune = 0x2293 }),
Entity.init("sqcup;", Entity.Value{ .Rune = 0x2294 }),
Entity.init("sqsub;", Entity.Value{ .Rune = 0x228f }),
Entity.init("sqsube;", Entity.Value{ .Rune = 0x2291 }),
Entity.init("sqsubset;", Entity.Value{ .Rune = 0x228f }),
Entity.init("sqsubseteq;", Entity.Value{ .Rune = 0x2291 }),
Entity.init("sqsup;", Entity.Value{ .Rune = 0x2290 }),
Entity.init("sqsupe;", Entity.Value{ .Rune = 0x2292 }),
Entity.init("sqsupset;", Entity.Value{ .Rune = 0x2290 }),
Entity.init("sqsupseteq;", Entity.Value{ .Rune = 0x2292 }),
Entity.init("squ;", Entity.Value{ .Rune = 0x25a1 }),
Entity.init("square;", Entity.Value{ .Rune = 0x25a1 }),
Entity.init("squarf;", Entity.Value{ .Rune = 0x25aa }),
Entity.init("squf;", Entity.Value{ .Rune = 0x25aa }),
Entity.init("srarr;", Entity.Value{ .Rune = 0x2192 }),
Entity.init("sscr;", Entity.Value{ .Rune = 0x1d4c8 }),
Entity.init("ssetmn;", Entity.Value{ .Rune = 0x2216 }),
Entity.init("ssmile;", Entity.Value{ .Rune = 0x2323 }),
Entity.init("sstarf;", Entity.Value{ .Rune = 0x22c6 }),
Entity.init("star;", Entity.Value{ .Rune = 0x2606 }),
Entity.init("starf;", Entity.Value{ .Rune = 0x2605 }),
Entity.init("straightepsilon;", Entity.Value{ .Rune = 0x3f5 }),
Entity.init("straightphi;", Entity.Value{ .Rune = 0x3d5 }),
Entity.init("strns;", Entity.Value{ .Rune = 0xaf }),
Entity.init("sub;", Entity.Value{ .Rune = 0x2282 }),
Entity.init("subE;", Entity.Value{ .Rune = 0x2ac5 }),
Entity.init("subdot;", Entity.Value{ .Rune = 0x2abd }),
Entity.init("sube;", Entity.Value{ .Rune = 0x2286 }),
Entity.init("subedot;", Entity.Value{ .Rune = 0x2ac3 }),
Entity.init("submult;", Entity.Value{ .Rune = 0x2ac1 }),
Entity.init("subnE;", Entity.Value{ .Rune = 0x2acb }),
Entity.init("subne;", Entity.Value{ .Rune = 0x228a }),
Entity.init("subplus;", Entity.Value{ .Rune = 0x2abf }),
Entity.init("subrarr;", Entity.Value{ .Rune = 0x2979 }),
Entity.init("subset;", Entity.Value{ .Rune = 0x2282 }),
Entity.init("subseteq;", Entity.Value{ .Rune = 0x2286 }),
Entity.init("subseteqq;", Entity.Value{ .Rune = 0x2ac5 }),
Entity.init("subsetneq;", Entity.Value{ .Rune = 0x228a }),
Entity.init("subsetneqq;", Entity.Value{ .Rune = 0x2acb }),
Entity.init("subsim;", Entity.Value{ .Rune = 0x2ac7 }),
Entity.init("subsub;", Entity.Value{ .Rune = 0x2ad5 }),
Entity.init("subsup;", Entity.Value{ .Rune = 0x2ad3 }),
Entity.init("succ;", Entity.Value{ .Rune = 0x227b }),
Entity.init("succapprox;", Entity.Value{ .Rune = 0x2ab8 }),
Entity.init("succcurlyeq;", Entity.Value{ .Rune = 0x227d }),
Entity.init("succeq;", Entity.Value{ .Rune = 0x2ab0 }),
Entity.init("succnapprox;", Entity.Value{ .Rune = 0x2aba }),
Entity.init("succneqq;", Entity.Value{ .Rune = 0x2ab6 }),
Entity.init("succnsim;", Entity.Value{ .Rune = 0x22e9 }),
Entity.init("succsim;", Entity.Value{ .Rune = 0x227f }),
Entity.init("sum;", Entity.Value{ .Rune = 0x2211 }),
Entity.init("sung;", Entity.Value{ .Rune = 0x266a }),
Entity.init("sup1", Entity.Value{ .Rune = 0xb9 }),
Entity.init("sup1;", Entity.Value{ .Rune = 0xb9 }),
Entity.init("sup2", Entity.Value{ .Rune = 0xb2 }),
Entity.init("sup2;", Entity.Value{ .Rune = 0xb2 }),
Entity.init("sup3", Entity.Value{ .Rune = 0xb3 }),
Entity.init("sup3;", Entity.Value{ .Rune = 0xb3 }),
Entity.init("sup;", Entity.Value{ .Rune = 0x2283 }),
Entity.init("supE;", Entity.Value{ .Rune = 0x2ac6 }),
Entity.init("supdot;", Entity.Value{ .Rune = 0x2abe }),
Entity.init("supdsub;", Entity.Value{ .Rune = 0x2ad8 }),
Entity.init("supe;", Entity.Value{ .Rune = 0x2287 }),
Entity.init("supedot;", Entity.Value{ .Rune = 0x2ac4 }),
Entity.init("suphsol;", Entity.Value{ .Rune = 0x27c9 }),
Entity.init("suphsub;", Entity.Value{ .Rune = 0x2ad7 }),
Entity.init("suplarr;", Entity.Value{ .Rune = 0x297b }),
Entity.init("supmult;", Entity.Value{ .Rune = 0x2ac2 }),
Entity.init("supnE;", Entity.Value{ .Rune = 0x2acc }),
Entity.init("supne;", Entity.Value{ .Rune = 0x228b }),
Entity.init("supplus;", Entity.Value{ .Rune = 0x2ac0 }),
Entity.init("supset;", Entity.Value{ .Rune = 0x2283 }),
Entity.init("supseteq;", Entity.Value{ .Rune = 0x2287 }),
Entity.init("supseteqq;", Entity.Value{ .Rune = 0x2ac6 }),
Entity.init("supsetneq;", Entity.Value{ .Rune = 0x228b }),
Entity.init("supsetneqq;", Entity.Value{ .Rune = 0x2acc }),
Entity.init("supsim;", Entity.Value{ .Rune = 0x2ac8 }),
Entity.init("supsub;", Entity.Value{ .Rune = 0x2ad4 }),
Entity.init("supsup;", Entity.Value{ .Rune = 0x2ad6 }),
Entity.init("swArr;", Entity.Value{ .Rune = 0x21d9 }),
Entity.init("swarhk;", Entity.Value{ .Rune = 0x2926 }),
Entity.init("swarr;", Entity.Value{ .Rune = 0x2199 }),
Entity.init("swarrow;", Entity.Value{ .Rune = 0x2199 }),
Entity.init("swnwar;", Entity.Value{ .Rune = 0x292a }),
Entity.init("szlig", Entity.Value{ .Rune = 0xdf }),
Entity.init("szlig;", Entity.Value{ .Rune = 0xdf }),
Entity.init("target;", Entity.Value{ .Rune = 0x2316 }),
Entity.init("tau;", Entity.Value{ .Rune = 0x3c4 }),
Entity.init("tbrk;", Entity.Value{ .Rune = 0x23b4 }),
Entity.init("tcaron;", Entity.Value{ .Rune = 0x165 }),
Entity.init("tcedil;", Entity.Value{ .Rune = 0x163 }),
Entity.init("tcy;", Entity.Value{ .Rune = 0x442 }),
Entity.init("tdot;", Entity.Value{ .Rune = 0x20db }),
Entity.init("telrec;", Entity.Value{ .Rune = 0x2315 }),
Entity.init("tfr;", Entity.Value{ .Rune = 0x1d531 }),
Entity.init("there4;", Entity.Value{ .Rune = 0x2234 }),
Entity.init("therefore;", Entity.Value{ .Rune = 0x2234 }),
Entity.init("theta;", Entity.Value{ .Rune = 0x3b8 }),
Entity.init("thetasym;", Entity.Value{ .Rune = 0x3d1 }),
Entity.init("thetav;", Entity.Value{ .Rune = 0x3d1 }),
Entity.init("thickapprox;", Entity.Value{ .Rune = 0x2248 }),
Entity.init("thicksim;", Entity.Value{ .Rune = 0x223c }),
Entity.init("thinsp;", Entity.Value{ .Rune = 0x2009 }),
Entity.init("thkap;", Entity.Value{ .Rune = 0x2248 }),
Entity.init("thksim;", Entity.Value{ .Rune = 0x223c }),
Entity.init("thorn", Entity.Value{ .Rune = 0xfe }),
Entity.init("thorn;", Entity.Value{ .Rune = 0xfe }),
Entity.init("tilde;", Entity.Value{ .Rune = 0x2dc }),
Entity.init("times", Entity.Value{ .Rune = 0xd7 }),
Entity.init("times;", Entity.Value{ .Rune = 0xd7 }),
Entity.init("timesb;", Entity.Value{ .Rune = 0x22a0 }),
Entity.init("timesbar;", Entity.Value{ .Rune = 0x2a31 }),
Entity.init("timesd;", Entity.Value{ .Rune = 0x2a30 }),
Entity.init("tint;", Entity.Value{ .Rune = 0x222d }),
Entity.init("toea;", Entity.Value{ .Rune = 0x2928 }),
Entity.init("top;", Entity.Value{ .Rune = 0x22a4 }),
Entity.init("topbot;", Entity.Value{ .Rune = 0x2336 }),
Entity.init("topcir;", Entity.Value{ .Rune = 0x2af1 }),
Entity.init("topf;", Entity.Value{ .Rune = 0x1d565 }),
Entity.init("topfork;", Entity.Value{ .Rune = 0x2ada }),
Entity.init("tosa;", Entity.Value{ .Rune = 0x2929 }),
Entity.init("tprime;", Entity.Value{ .Rune = 0x2034 }),
Entity.init("trade;", Entity.Value{ .Rune = 0x2122 }),
Entity.init("triangle;", Entity.Value{ .Rune = 0x25b5 }),
Entity.init("triangledown;", Entity.Value{ .Rune = 0x25bf }),
Entity.init("triangleleft;", Entity.Value{ .Rune = 0x25c3 }),
Entity.init("trianglelefteq;", Entity.Value{ .Rune = 0x22b4 }),
Entity.init("triangleq;", Entity.Value{ .Rune = 0x225c }),
Entity.init("triangleright;", Entity.Value{ .Rune = 0x25b9 }),
Entity.init("trianglerighteq;", Entity.Value{ .Rune = 0x22b5 }),
Entity.init("tridot;", Entity.Value{ .Rune = 0x25ec }),
Entity.init("trie;", Entity.Value{ .Rune = 0x225c }),
Entity.init("triminus;", Entity.Value{ .Rune = 0x2a3a }),
Entity.init("triplus;", Entity.Value{ .Rune = 0x2a39 }),
Entity.init("trisb;", Entity.Value{ .Rune = 0x29cd }),
Entity.init("tritime;", Entity.Value{ .Rune = 0x2a3b }),
Entity.init("trpezium;", Entity.Value{ .Rune = 0x23e2 }),
Entity.init("tscr;", Entity.Value{ .Rune = 0x1d4c9 }),
Entity.init("tscy;", Entity.Value{ .Rune = 0x446 }),
Entity.init("tshcy;", Entity.Value{ .Rune = 0x45b }),
Entity.init("tstrok;", Entity.Value{ .Rune = 0x167 }),
Entity.init("twixt;", Entity.Value{ .Rune = 0x226c }),
Entity.init("twoheadleftarrow;", Entity.Value{ .Rune = 0x219e }),
Entity.init("twoheadrightarrow;", Entity.Value{ .Rune = 0x21a0 }),
Entity.init("uArr;", Entity.Value{ .Rune = 0x21d1 }),
Entity.init("uHar;", Entity.Value{ .Rune = 0x2963 }),
Entity.init("uacute", Entity.Value{ .Rune = 0xfa }),
Entity.init("uacute;", Entity.Value{ .Rune = 0xfa }),
Entity.init("uarr;", Entity.Value{ .Rune = 0x2191 }),
Entity.init("ubrcy;", Entity.Value{ .Rune = 0x45e }),
Entity.init("ubreve;", Entity.Value{ .Rune = 0x16d }),
Entity.init("ucirc", Entity.Value{ .Rune = 0xfb }),
Entity.init("ucirc;", Entity.Value{ .Rune = 0xfb }),
Entity.init("ucy;", Entity.Value{ .Rune = 0x443 }),
Entity.init("udarr;", Entity.Value{ .Rune = 0x21c5 }),
Entity.init("udblac;", Entity.Value{ .Rune = 0x171 }),
Entity.init("udhar;", Entity.Value{ .Rune = 0x296e }),
Entity.init("ufisht;", Entity.Value{ .Rune = 0x297e }),
Entity.init("ufr;", Entity.Value{ .Rune = 0x1d532 }),
Entity.init("ugrave", Entity.Value{ .Rune = 0xf9 }),
Entity.init("ugrave;", Entity.Value{ .Rune = 0xf9 }),
Entity.init("uharl;", Entity.Value{ .Rune = 0x21bf }),
Entity.init("uharr;", Entity.Value{ .Rune = 0x21be }),
Entity.init("uhblk;", Entity.Value{ .Rune = 0x2580 }),
Entity.init("ulcorn;", Entity.Value{ .Rune = 0x231c }),
Entity.init("ulcorner;", Entity.Value{ .Rune = 0x231c }),
Entity.init("ulcrop;", Entity.Value{ .Rune = 0x230f }),
Entity.init("ultri;", Entity.Value{ .Rune = 0x25f8 }),
Entity.init("umacr;", Entity.Value{ .Rune = 0x16b }),
Entity.init("uml", Entity.Value{ .Rune = 0xa8 }),
Entity.init("uml;", Entity.Value{ .Rune = 0xa8 }),
Entity.init("uogon;", Entity.Value{ .Rune = 0x173 }),
Entity.init("uopf;", Entity.Value{ .Rune = 0x1d566 }),
Entity.init("uparrow;", Entity.Value{ .Rune = 0x2191 }),
Entity.init("updownarrow;", Entity.Value{ .Rune = 0x2195 }),
Entity.init("upharpoonleft;", Entity.Value{ .Rune = 0x21bf }),
Entity.init("upharpoonright;", Entity.Value{ .Rune = 0x21be }),
Entity.init("uplus;", Entity.Value{ .Rune = 0x228e }),
Entity.init("upsi;", Entity.Value{ .Rune = 0x3c5 }),
Entity.init("upsih;", Entity.Value{ .Rune = 0x3d2 }),
Entity.init("upsilon;", Entity.Value{ .Rune = 0x3c5 }),
Entity.init("upuparrows;", Entity.Value{ .Rune = 0x21c8 }),
Entity.init("urcorn;", Entity.Value{ .Rune = 0x231d }),
Entity.init("urcorner;", Entity.Value{ .Rune = 0x231d }),
Entity.init("urcrop;", Entity.Value{ .Rune = 0x230e }),
Entity.init("uring;", Entity.Value{ .Rune = 0x16f }),
Entity.init("urtri;", Entity.Value{ .Rune = 0x25f9 }),
Entity.init("uscr;", Entity.Value{ .Rune = 0x1d4ca }),
Entity.init("utdot;", Entity.Value{ .Rune = 0x22f0 }),
Entity.init("utilde;", Entity.Value{ .Rune = 0x169 }),
Entity.init("utri;", Entity.Value{ .Rune = 0x25b5 }),
Entity.init("utrif;", Entity.Value{ .Rune = 0x25b4 }),
Entity.init("uuarr;", Entity.Value{ .Rune = 0x21c8 }),
Entity.init("uuml", Entity.Value{ .Rune = 0xfc }),
Entity.init("uuml;", Entity.Value{ .Rune = 0xfc }),
Entity.init("uwangle;", Entity.Value{ .Rune = 0x29a7 }),
Entity.init("vArr;", Entity.Value{ .Rune = 0x21d5 }),
Entity.init("vBar;", Entity.Value{ .Rune = 0x2ae8 }),
Entity.init("vBarv;", Entity.Value{ .Rune = 0x2ae9 }),
Entity.init("vDash;", Entity.Value{ .Rune = 0x22a8 }),
Entity.init("vangrt;", Entity.Value{ .Rune = 0x299c }),
Entity.init("varepsilon;", Entity.Value{ .Rune = 0x3f5 }),
Entity.init("varkappa;", Entity.Value{ .Rune = 0x3f0 }),
Entity.init("varnothing;", Entity.Value{ .Rune = 0x2205 }),
Entity.init("varphi;", Entity.Value{ .Rune = 0x3d5 }),
Entity.init("varpi;", Entity.Value{ .Rune = 0x3d6 }),
Entity.init("varpropto;", Entity.Value{ .Rune = 0x221d }),
Entity.init("varr;", Entity.Value{ .Rune = 0x2195 }),
Entity.init("varrho;", Entity.Value{ .Rune = 0x3f1 }),
Entity.init("varsigma;", Entity.Value{ .Rune = 0x3c2 }),
Entity.init("vartheta;", Entity.Value{ .Rune = 0x3d1 }),
Entity.init("vartriangleleft;", Entity.Value{ .Rune = 0x22b2 }),
Entity.init("vartriangleright;", Entity.Value{ .Rune = 0x22b3 }),
Entity.init("vcy;", Entity.Value{ .Rune = 0x432 }),
Entity.init("vdash;", Entity.Value{ .Rune = 0x22a2 }),
Entity.init("vee;", Entity.Value{ .Rune = 0x2228 }),
Entity.init("veebar;", Entity.Value{ .Rune = 0x22bb }),
Entity.init("veeeq;", Entity.Value{ .Rune = 0x225a }),
Entity.init("vellip;", Entity.Value{ .Rune = 0x22ee }),
Entity.init("verbar;", Entity.Value{ .Rune = 0x7c }),
Entity.init("vert;", Entity.Value{ .Rune = 0x7c }),
Entity.init("vfr;", Entity.Value{ .Rune = 0x1d533 }),
Entity.init("vltri;", Entity.Value{ .Rune = 0x22b2 }),
Entity.init("vopf;", Entity.Value{ .Rune = 0x1d567 }),
Entity.init("vprop;", Entity.Value{ .Rune = 0x221d }),
Entity.init("vrtri;", Entity.Value{ .Rune = 0x22b3 }),
Entity.init("vscr;", Entity.Value{ .Rune = 0x1d4cb }),
Entity.init("vzigzag;", Entity.Value{ .Rune = 0x299a }),
Entity.init("wcirc;", Entity.Value{ .Rune = 0x175 }),
Entity.init("wedbar;", Entity.Value{ .Rune = 0x2a5f }),
Entity.init("wedge;", Entity.Value{ .Rune = 0x2227 }),
Entity.init("wedgeq;", Entity.Value{ .Rune = 0x2259 }),
Entity.init("weierp;", Entity.Value{ .Rune = 0x2118 }),
Entity.init("wfr;", Entity.Value{ .Rune = 0x1d534 }),
Entity.init("wopf;", Entity.Value{ .Rune = 0x1d568 }),
Entity.init("wp;", Entity.Value{ .Rune = 0x2118 }),
Entity.init("wr;", Entity.Value{ .Rune = 0x2240 }),
Entity.init("wreath;", Entity.Value{ .Rune = 0x2240 }),
Entity.init("wscr;", Entity.Value{ .Rune = 0x1d4cc }),
Entity.init("xcap;", Entity.Value{ .Rune = 0x22c2 }),
Entity.init("xcirc;", Entity.Value{ .Rune = 0x25ef }),
Entity.init("xcup;", Entity.Value{ .Rune = 0x22c3 }),
Entity.init("xdtri;", Entity.Value{ .Rune = 0x25bd }),
Entity.init("xfr;", Entity.Value{ .Rune = 0x1d535 }),
Entity.init("xhArr;", Entity.Value{ .Rune = 0x27fa }),
Entity.init("xharr;", Entity.Value{ .Rune = 0x27f7 }),
Entity.init("xi;", Entity.Value{ .Rune = 0x3be }),
Entity.init("xlArr;", Entity.Value{ .Rune = 0x27f8 }),
Entity.init("xlarr;", Entity.Value{ .Rune = 0x27f5 }),
Entity.init("xmap;", Entity.Value{ .Rune = 0x27fc }),
Entity.init("xnis;", Entity.Value{ .Rune = 0x22fb }),
Entity.init("xodot;", Entity.Value{ .Rune = 0x2a00 }),
Entity.init("xopf;", Entity.Value{ .Rune = 0x1d569 }),
Entity.init("xoplus;", Entity.Value{ .Rune = 0x2a01 }),
Entity.init("xotime;", Entity.Value{ .Rune = 0x2a02 }),
Entity.init("xrArr;", Entity.Value{ .Rune = 0x27f9 }),
Entity.init("xrarr;", Entity.Value{ .Rune = 0x27f6 }),
Entity.init("xscr;", Entity.Value{ .Rune = 0x1d4cd }),
Entity.init("xsqcup;", Entity.Value{ .Rune = 0x2a06 }),
Entity.init("xuplus;", Entity.Value{ .Rune = 0x2a04 }),
Entity.init("xutri;", Entity.Value{ .Rune = 0x25b3 }),
Entity.init("xvee;", Entity.Value{ .Rune = 0x22c1 }),
Entity.init("xwedge;", Entity.Value{ .Rune = 0x22c0 }),
Entity.init("yacute", Entity.Value{ .Rune = 0xfd }),
Entity.init("yacute;", Entity.Value{ .Rune = 0xfd }),
Entity.init("yacy;", Entity.Value{ .Rune = 0x44f }),
Entity.init("ycirc;", Entity.Value{ .Rune = 0x177 }),
Entity.init("ycy;", Entity.Value{ .Rune = 0x44b }),
Entity.init("yen", Entity.Value{ .Rune = 0xa5 }),
Entity.init("yen;", Entity.Value{ .Rune = 0xa5 }),
Entity.init("yfr;", Entity.Value{ .Rune = 0x1d536 }),
Entity.init("yicy;", Entity.Value{ .Rune = 0x457 }),
Entity.init("yopf;", Entity.Value{ .Rune = 0x1d56a }),
Entity.init("yscr;", Entity.Value{ .Rune = 0x1d4ce }),
Entity.init("yucy;", Entity.Value{ .Rune = 0x44e }),
Entity.init("yuml", Entity.Value{ .Rune = 0xff }),
Entity.init("yuml;", Entity.Value{ .Rune = 0xff }),
Entity.init("zacute;", Entity.Value{ .Rune = 0x17a }),
Entity.init("zcaron;", Entity.Value{ .Rune = 0x17e }),
Entity.init("zcy;", Entity.Value{ .Rune = 0x437 }),
Entity.init("zdot;", Entity.Value{ .Rune = 0x17c }),
Entity.init("zeetrf;", Entity.Value{ .Rune = 0x2128 }),
Entity.init("zeta;", Entity.Value{ .Rune = 0x3b6 }),
Entity.init("zfr;", Entity.Value{ .Rune = 0x1d537 }),
Entity.init("zhcy;", Entity.Value{ .Rune = 0x436 }),
Entity.init("zigrarr;", Entity.Value{ .Rune = 0x21dd }),
Entity.init("zopf;", Entity.Value{ .Rune = 0x1d56b }),
Entity.init("zscr;", Entity.Value{ .Rune = 0x1d4cf }),
Entity.init("zwj;", Entity.Value{ .Rune = 0x200d }),
Entity.init("zwnj;", Entity.Value{ .Rune = 0x200c }),
//entity2
Entity.init("NotEqualTilde;", Entity.Value{ .Rune2 = []usize{ 0x2242, 0x338 } }),
Entity.init("NotGreaterFullEqual;", Entity.Value{ .Rune2 = []usize{ 0x2267, 0x338 } }),
Entity.init("NotGreaterGreater;", Entity.Value{ .Rune2 = []usize{ 0x226b, 0x338 } }),
Entity.init("NotGreaterSlantEqual;", Entity.Value{ .Rune2 = []usize{ 0x2a7e, 0x338 } }),
Entity.init("NotHumpDownHump;", Entity.Value{ .Rune2 = []usize{ 0x224e, 0x338 } }),
Entity.init("NotHumpEqual;", Entity.Value{ .Rune2 = []usize{ 0x224f, 0x338 } }),
Entity.init("NotLeftTriangleBar;", Entity.Value{ .Rune2 = []usize{ 0x29cf, 0x338 } }),
Entity.init("NotLessLess;", Entity.Value{ .Rune2 = []usize{ 0x226a, 0x338 } }),
Entity.init("NotLessSlantEqual;", Entity.Value{ .Rune2 = []usize{ 0x2a7d, 0x338 } }),
Entity.init("NotNestedGreaterGreater;", Entity.Value{ .Rune2 = []usize{ 0x2aa2, 0x338 } }),
Entity.init("NotNestedLessLess;", Entity.Value{ .Rune2 = []usize{ 0x2aa1, 0x338 } }),
Entity.init("NotPrecedesEqual;", Entity.Value{ .Rune2 = []usize{ 0x2aaf, 0x338 } }),
Entity.init("NotRightTriangleBar;", Entity.Value{ .Rune2 = []usize{ 0x29d0, 0x338 } }),
Entity.init("NotSquareSubset;", Entity.Value{ .Rune2 = []usize{ 0x228f, 0x338 } }),
Entity.init("NotSquareSuperset;", Entity.Value{ .Rune2 = []usize{ 0x2290, 0x338 } }),
Entity.init("NotSubset;", Entity.Value{ .Rune2 = []usize{ 0x2282, 0x20d2 } }),
Entity.init("NotSucceedsEqual;", Entity.Value{ .Rune2 = []usize{ 0x2ab0, 0x338 } }),
Entity.init("NotSucceedsTilde;", Entity.Value{ .Rune2 = []usize{ 0x227f, 0x338 } }),
Entity.init("NotSuperset;", Entity.Value{ .Rune2 = []usize{ 0x2283, 0x20d2 } }),
Entity.init("ThickSpace;", Entity.Value{ .Rune2 = []usize{ 0x205f, 0x200a } }),
Entity.init("acE;", Entity.Value{ .Rune2 = []usize{ 0x223e, 0x333 } }),
Entity.init("bne;", Entity.Value{ .Rune2 = []usize{ 0x3d, 0x20e5 } }),
Entity.init("bnequiv;", Entity.Value{ .Rune2 = []usize{ 0x2261, 0x20e5 } }),
Entity.init("caps;", Entity.Value{ .Rune2 = []usize{ 0x2229, 0xfe00 } }),
Entity.init("cups;", Entity.Value{ .Rune2 = []usize{ 0x222a, 0xfe00 } }),
Entity.init("fjlig;", Entity.Value{ .Rune2 = []usize{ 0x66, 0x6a } }),
Entity.init("gesl;", Entity.Value{ .Rune2 = []usize{ 0x22db, 0xfe00 } }),
Entity.init("gvertneqq;", Entity.Value{ .Rune2 = []usize{ 0x2269, 0xfe00 } }),
Entity.init("gvnE;", Entity.Value{ .Rune2 = []usize{ 0x2269, 0xfe00 } }),
Entity.init("lates;", Entity.Value{ .Rune2 = []usize{ 0x2aad, 0xfe00 } }),
Entity.init("lesg;", Entity.Value{ .Rune2 = []usize{ 0x22da, 0xfe00 } }),
Entity.init("lvertneqq;", Entity.Value{ .Rune2 = []usize{ 0x2268, 0xfe00 } }),
Entity.init("lvnE;", Entity.Value{ .Rune2 = []usize{ 0x2268, 0xfe00 } }),
Entity.init("nGg;", Entity.Value{ .Rune2 = []usize{ 0x22d9, 0x338 } }),
Entity.init("nGtv;", Entity.Value{ .Rune2 = []usize{ 0x226b, 0x338 } }),
Entity.init("nLl;", Entity.Value{ .Rune2 = []usize{ 0x22d8, 0x338 } }),
Entity.init("nLtv;", Entity.Value{ .Rune2 = []usize{ 0x226a, 0x338 } }),
Entity.init("nang;", Entity.Value{ .Rune2 = []usize{ 0x2220, 0x20d2 } }),
Entity.init("napE;", Entity.Value{ .Rune2 = []usize{ 0x2a70, 0x338 } }),
Entity.init("napid;", Entity.Value{ .Rune2 = []usize{ 0x224b, 0x338 } }),
Entity.init("nbump;", Entity.Value{ .Rune2 = []usize{ 0x224e, 0x338 } }),
Entity.init("nbumpe;", Entity.Value{ .Rune2 = []usize{ 0x224f, 0x338 } }),
Entity.init("ncongdot;", Entity.Value{ .Rune2 = []usize{ 0x2a6d, 0x338 } }),
Entity.init("nedot;", Entity.Value{ .Rune2 = []usize{ 0x2250, 0x338 } }),
Entity.init("nesim;", Entity.Value{ .Rune2 = []usize{ 0x2242, 0x338 } }),
Entity.init("ngE;", Entity.Value{ .Rune2 = []usize{ 0x2267, 0x338 } }),
Entity.init("ngeqq;", Entity.Value{ .Rune2 = []usize{ 0x2267, 0x338 } }),
Entity.init("ngeqslant;", Entity.Value{ .Rune2 = []usize{ 0x2a7e, 0x338 } }),
Entity.init("nges;", Entity.Value{ .Rune2 = []usize{ 0x2a7e, 0x338 } }),
Entity.init("nlE;", Entity.Value{ .Rune2 = []usize{ 0x2266, 0x338 } }),
Entity.init("nleqq;", Entity.Value{ .Rune2 = []usize{ 0x2266, 0x338 } }),
Entity.init("nleqslant;", Entity.Value{ .Rune2 = []usize{ 0x2a7d, 0x338 } }),
Entity.init("nles;", Entity.Value{ .Rune2 = []usize{ 0x2a7d, 0x338 } }),
Entity.init("notinE;", Entity.Value{ .Rune2 = []usize{ 0x22f9, 0x338 } }),
Entity.init("notindot;", Entity.Value{ .Rune2 = []usize{ 0x22f5, 0x338 } }),
Entity.init("nparsl;", Entity.Value{ .Rune2 = []usize{ 0x2afd, 0x20e5 } }),
Entity.init("npart;", Entity.Value{ .Rune2 = []usize{ 0x2202, 0x338 } }),
Entity.init("npre;", Entity.Value{ .Rune2 = []usize{ 0x2aaf, 0x338 } }),
Entity.init("npreceq;", Entity.Value{ .Rune2 = []usize{ 0x2aaf, 0x338 } }),
Entity.init("nrarrc;", Entity.Value{ .Rune2 = []usize{ 0x2933, 0x338 } }),
Entity.init("nrarrw;", Entity.Value{ .Rune2 = []usize{ 0x219d, 0x338 } }),
Entity.init("nsce;", Entity.Value{ .Rune2 = []usize{ 0x2ab0, 0x338 } }),
Entity.init("nsubE;", Entity.Value{ .Rune2 = []usize{ 0x2ac5, 0x338 } }),
Entity.init("nsubset;", Entity.Value{ .Rune2 = []usize{ 0x2282, 0x20d2 } }),
Entity.init("nsubseteqq;", Entity.Value{ .Rune2 = []usize{ 0x2ac5, 0x338 } }),
Entity.init("nsucceq;", Entity.Value{ .Rune2 = []usize{ 0x2ab0, 0x338 } }),
Entity.init("nsupE;", Entity.Value{ .Rune2 = []usize{ 0x2ac6, 0x338 } }),
Entity.init("nsupset;", Entity.Value{ .Rune2 = []usize{ 0x2283, 0x20d2 } }),
Entity.init("nsupseteqq;", Entity.Value{ .Rune2 = []usize{ 0x2ac6, 0x338 } }),
Entity.init("nvap;", Entity.Value{ .Rune2 = []usize{ 0x224d, 0x20d2 } }),
Entity.init("nvge;", Entity.Value{ .Rune2 = []usize{ 0x2265, 0x20d2 } }),
Entity.init("nvgt;", Entity.Value{ .Rune2 = []usize{ 0x3e, 0x20d2 } }),
Entity.init("nvle;", Entity.Value{ .Rune2 = []usize{ 0x2264, 0x20d2 } }),
Entity.init("nvlt;", Entity.Value{ .Rune2 = []usize{ 0x3c, 0x20d2 } }),
Entity.init("nvltrie;", Entity.Value{ .Rune2 = []usize{ 0x22b4, 0x20d2 } }),
Entity.init("nvrtrie;", Entity.Value{ .Rune2 = []usize{ 0x22b5, 0x20d2 } }),
Entity.init("nvsim;", Entity.Value{ .Rune2 = []usize{ 0x223c, 0x20d2 } }),
Entity.init("race;", Entity.Value{ .Rune2 = []usize{ 0x223d, 0x331 } }),
Entity.init("smtes;", Entity.Value{ .Rune2 = []usize{ 0x2aac, 0xfe00 } }),
Entity.init("sqcaps;", Entity.Value{ .Rune2 = []usize{ 0x2293, 0xfe00 } }),
Entity.init("sqcups;", Entity.Value{ .Rune2 = []usize{ 0x2294, 0xfe00 } }),
Entity.init("varsubsetneq;", Entity.Value{ .Rune2 = []usize{ 0x228a, 0xfe00 } }),
Entity.init("varsubsetneqq;", Entity.Value{ .Rune2 = []usize{ 0x2acb, 0xfe00 } }),
Entity.init("varsupsetneq;", Entity.Value{ .Rune2 = []usize{ 0x228b, 0xfe00 } }),
Entity.init("varsupsetneqq;", Entity.Value{ .Rune2 = []usize{ 0x2acc, 0xfe00 } }),
Entity.init("vnsub;", Entity.Value{ .Rune2 = []usize{ 0x2282, 0x20d2 } }),
Entity.init("vnsup;", Entity.Value{ .Rune2 = []usize{ 0x2283, 0x20d2 } }),
Entity.init("vsubnE;", Entity.Value{ .Rune2 = []usize{ 0x2acb, 0xfe00 } }),
Entity.init("vsubne;", Entity.Value{ .Rune2 = []usize{ 0x228a, 0xfe00 } }),
Entity.init("vsupnE;", Entity.Value{ .Rune2 = []usize{ 0x2acc, 0xfe00 } }),
Entity.init("vsupne;", Entity.Value{ .Rune2 = []usize{ 0x228b, 0xfe00 } }),
}; | src/html/entity.zig |
const mem = @import("std").mem;
const Allocator = mem.Allocator;
const assert = @import("std").debug.assert;
extern const __heap_start: usize;
extern const __heap_phys_start: *usize;
fn alignPageAllocLen(full_len: usize, len: usize, len_align: u29) usize {
const aligned_len = mem.alignAllocLen(full_len, len, len_align);
assert(mem.alignForward(aligned_len, mem.page_size) == full_len);
return aligned_len;
}
pub fn BumpAllocator() type {
return struct {
addr: usize,
const Self = @This();
pub fn init() Self {
return Self{
.addr = 0xffff000002000000
};
}
pub fn allocator(self: *Self) Allocator {
return Allocator.init(self, alloc, resize, free);
}
fn alloc(
self: *Self,
n: usize,
ptr_align: u29,
len_align: u29,
ra: usize,
) error{OutOfMemory}![]u8 {
_ = ra;
_ = ptr_align;
assert(n > 0);
const aligned_len = mem.alignForward(n, mem.page_size);
var alloc_addr = self.addr;
self.addr += aligned_len;
const return_ptr = @ptrCast([*]u8,@intToPtr(*u8, alloc_addr));
return return_ptr[0..alignPageAllocLen(aligned_len, n, len_align)];
}
fn resize(
self: *Self,
buf_unaligned: []u8,
buf_align: u29,
new_len: usize,
len_align: u29,
return_address: usize,
) ?usize {
_ = self;
_ = buf_unaligned;
_ = buf_align;
_ = new_len;
_ = len_align;
_ = return_address;
return null;
}
fn free(
self: *Self,
buf: []u8,
buf_align: u29,
ra: usize,
) void {
_ = self;
_ = buf;
_ = buf_align;
_ = ra;
}
};
} | kernel/src/vm/page_frame_manager.zig |
usingnamespace @import("std").zig.c_builtins;
pub const FMOD_BOOL = c_int;
pub const struct_FMOD_SYSTEM = opaque {};
pub const FMOD_SYSTEM = struct_FMOD_SYSTEM;
pub const struct_FMOD_SOUND = opaque {};
pub const FMOD_SOUND = struct_FMOD_SOUND;
pub const struct_FMOD_CHANNELCONTROL = opaque {};
pub const FMOD_CHANNELCONTROL = struct_FMOD_CHANNELCONTROL;
pub const struct_FMOD_CHANNEL = opaque {};
pub const FMOD_CHANNEL = struct_FMOD_CHANNEL;
pub const struct_FMOD_CHANNELGROUP = opaque {};
pub const FMOD_CHANNELGROUP = struct_FMOD_CHANNELGROUP;
pub const struct_FMOD_SOUNDGROUP = opaque {};
pub const FMOD_SOUNDGROUP = struct_FMOD_SOUNDGROUP;
pub const struct_FMOD_REVERB3D = opaque {};
pub const FMOD_REVERB3D = struct_FMOD_REVERB3D;
pub const struct_FMOD_DSP = opaque {};
pub const FMOD_DSP = struct_FMOD_DSP;
pub const struct_FMOD_DSPCONNECTION = opaque {};
pub const FMOD_DSPCONNECTION = struct_FMOD_DSPCONNECTION;
pub const struct_FMOD_POLYGON = opaque {};
pub const FMOD_POLYGON = struct_FMOD_POLYGON;
pub const struct_FMOD_GEOMETRY = opaque {};
pub const FMOD_GEOMETRY = struct_FMOD_GEOMETRY;
pub const struct_FMOD_SYNCPOINT = opaque {};
pub const FMOD_SYNCPOINT = struct_FMOD_SYNCPOINT;
pub const FMOD_ASYNCREADINFO = struct_FMOD_ASYNCREADINFO;
pub const FMOD_OK: c_int = 0;
pub const FMOD_ERR_BADCOMMAND: c_int = 1;
pub const FMOD_ERR_CHANNEL_ALLOC: c_int = 2;
pub const FMOD_ERR_CHANNEL_STOLEN: c_int = 3;
pub const FMOD_ERR_DMA: c_int = 4;
pub const FMOD_ERR_DSP_CONNECTION: c_int = 5;
pub const FMOD_ERR_DSP_DONTPROCESS: c_int = 6;
pub const FMOD_ERR_DSP_FORMAT: c_int = 7;
pub const FMOD_ERR_DSP_INUSE: c_int = 8;
pub const FMOD_ERR_DSP_NOTFOUND: c_int = 9;
pub const FMOD_ERR_DSP_RESERVED: c_int = 10;
pub const FMOD_ERR_DSP_SILENCE: c_int = 11;
pub const FMOD_ERR_DSP_TYPE: c_int = 12;
pub const FMOD_ERR_FILE_BAD: c_int = 13;
pub const FMOD_ERR_FILE_COULDNOTSEEK: c_int = 14;
pub const FMOD_ERR_FILE_DISKEJECTED: c_int = 15;
pub const FMOD_ERR_FILE_EOF: c_int = 16;
pub const FMOD_ERR_FILE_ENDOFDATA: c_int = 17;
pub const FMOD_ERR_FILE_NOTFOUND: c_int = 18;
pub const FMOD_ERR_FORMAT: c_int = 19;
pub const FMOD_ERR_HEADER_MISMATCH: c_int = 20;
pub const FMOD_ERR_HTTP: c_int = 21;
pub const FMOD_ERR_HTTP_ACCESS: c_int = 22;
pub const FMOD_ERR_HTTP_PROXY_AUTH: c_int = 23;
pub const FMOD_ERR_HTTP_SERVER_ERROR: c_int = 24;
pub const FMOD_ERR_HTTP_TIMEOUT: c_int = 25;
pub const FMOD_ERR_INITIALIZATION: c_int = 26;
pub const FMOD_ERR_INITIALIZED: c_int = 27;
pub const FMOD_ERR_INTERNAL: c_int = 28;
pub const FMOD_ERR_INVALID_FLOAT: c_int = 29;
pub const FMOD_ERR_INVALID_HANDLE: c_int = 30;
pub const FMOD_ERR_INVALID_PARAM: c_int = 31;
pub const FMOD_ERR_INVALID_POSITION: c_int = 32;
pub const FMOD_ERR_INVALID_SPEAKER: c_int = 33;
pub const FMOD_ERR_INVALID_SYNCPOINT: c_int = 34;
pub const FMOD_ERR_INVALID_THREAD: c_int = 35;
pub const FMOD_ERR_INVALID_VECTOR: c_int = 36;
pub const FMOD_ERR_MAXAUDIBLE: c_int = 37;
pub const FMOD_ERR_MEMORY: c_int = 38;
pub const FMOD_ERR_MEMORY_CANTPOINT: c_int = 39;
pub const FMOD_ERR_NEEDS3D: c_int = 40;
pub const FMOD_ERR_NEEDSHARDWARE: c_int = 41;
pub const FMOD_ERR_NET_CONNECT: c_int = 42;
pub const FMOD_ERR_NET_SOCKET_ERROR: c_int = 43;
pub const FMOD_ERR_NET_URL: c_int = 44;
pub const FMOD_ERR_NET_WOULD_BLOCK: c_int = 45;
pub const FMOD_ERR_NOTREADY: c_int = 46;
pub const FMOD_ERR_OUTPUT_ALLOCATED: c_int = 47;
pub const FMOD_ERR_OUTPUT_CREATEBUFFER: c_int = 48;
pub const FMOD_ERR_OUTPUT_DRIVERCALL: c_int = 49;
pub const FMOD_ERR_OUTPUT_FORMAT: c_int = 50;
pub const FMOD_ERR_OUTPUT_INIT: c_int = 51;
pub const FMOD_ERR_OUTPUT_NODRIVERS: c_int = 52;
pub const FMOD_ERR_PLUGIN: c_int = 53;
pub const FMOD_ERR_PLUGIN_MISSING: c_int = 54;
pub const FMOD_ERR_PLUGIN_RESOURCE: c_int = 55;
pub const FMOD_ERR_PLUGIN_VERSION: c_int = 56;
pub const FMOD_ERR_RECORD: c_int = 57;
pub const FMOD_ERR_REVERB_CHANNELGROUP: c_int = 58;
pub const FMOD_ERR_REVERB_INSTANCE: c_int = 59;
pub const FMOD_ERR_SUBSOUNDS: c_int = 60;
pub const FMOD_ERR_SUBSOUND_ALLOCATED: c_int = 61;
pub const FMOD_ERR_SUBSOUND_CANTMOVE: c_int = 62;
pub const FMOD_ERR_TAGNOTFOUND: c_int = 63;
pub const FMOD_ERR_TOOMANYCHANNELS: c_int = 64;
pub const FMOD_ERR_TRUNCATED: c_int = 65;
pub const FMOD_ERR_UNIMPLEMENTED: c_int = 66;
pub const FMOD_ERR_UNINITIALIZED: c_int = 67;
pub const FMOD_ERR_UNSUPPORTED: c_int = 68;
pub const FMOD_ERR_VERSION: c_int = 69;
pub const FMOD_ERR_EVENT_ALREADY_LOADED: c_int = 70;
pub const FMOD_ERR_EVENT_LIVEUPDATE_BUSY: c_int = 71;
pub const FMOD_ERR_EVENT_LIVEUPDATE_MISMATCH: c_int = 72;
pub const FMOD_ERR_EVENT_LIVEUPDATE_TIMEOUT: c_int = 73;
pub const FMOD_ERR_EVENT_NOTFOUND: c_int = 74;
pub const FMOD_ERR_STUDIO_UNINITIALIZED: c_int = 75;
pub const FMOD_ERR_STUDIO_NOT_LOADED: c_int = 76;
pub const FMOD_ERR_INVALID_STRING: c_int = 77;
pub const FMOD_ERR_ALREADY_LOCKED: c_int = 78;
pub const FMOD_ERR_NOT_LOCKED: c_int = 79;
pub const FMOD_ERR_RECORD_DISCONNECTED: c_int = 80;
pub const FMOD_ERR_TOOMANYSAMPLES: c_int = 81;
pub const FMOD_RESULT_FORCEINT: c_int = 65536;
pub const enum_FMOD_RESULT = c_uint;
pub const FMOD_RESULT = enum_FMOD_RESULT;
pub const FMOD_FILE_ASYNCDONE_FUNC = ?fn ([*c]FMOD_ASYNCREADINFO, FMOD_RESULT) callconv(.C) void;
pub const struct_FMOD_ASYNCREADINFO = extern struct {
handle: ?*c_void,
offset: c_uint,
sizebytes: c_uint,
priority: c_int,
userdata: ?*c_void,
buffer: ?*c_void,
bytesread: c_uint,
done: FMOD_FILE_ASYNCDONE_FUNC,
};
pub const FMOD_PORT_TYPE = c_uint;
pub const FMOD_PORT_INDEX = c_ulonglong;
pub const FMOD_DEBUG_FLAGS = c_uint;
pub const FMOD_MEMORY_TYPE = c_uint;
pub const FMOD_INITFLAGS = c_uint;
pub const FMOD_DRIVER_STATE = c_uint;
pub const FMOD_TIMEUNIT = c_uint;
pub const FMOD_SYSTEM_CALLBACK_TYPE = c_uint;
pub const FMOD_MODE = c_uint;
pub const FMOD_CHANNELMASK = c_uint;
pub const FMOD_THREAD_PRIORITY = c_int;
pub const FMOD_THREAD_STACK_SIZE = c_uint;
pub const FMOD_THREAD_AFFINITY = c_ulonglong;
pub const FMOD_THREAD_TYPE_MIXER: c_int = 0;
pub const FMOD_THREAD_TYPE_FEEDER: c_int = 1;
pub const FMOD_THREAD_TYPE_STREAM: c_int = 2;
pub const FMOD_THREAD_TYPE_FILE: c_int = 3;
pub const FMOD_THREAD_TYPE_NONBLOCKING: c_int = 4;
pub const FMOD_THREAD_TYPE_RECORD: c_int = 5;
pub const FMOD_THREAD_TYPE_GEOMETRY: c_int = 6;
pub const FMOD_THREAD_TYPE_PROFILER: c_int = 7;
pub const FMOD_THREAD_TYPE_STUDIO_UPDATE: c_int = 8;
pub const FMOD_THREAD_TYPE_STUDIO_LOAD_BANK: c_int = 9;
pub const FMOD_THREAD_TYPE_STUDIO_LOAD_SAMPLE: c_int = 10;
pub const FMOD_THREAD_TYPE_CONVOLUTION1: c_int = 11;
pub const FMOD_THREAD_TYPE_CONVOLUTION2: c_int = 12;
pub const FMOD_THREAD_TYPE_MAX: c_int = 13;
pub const FMOD_THREAD_TYPE_FORCEINT: c_int = 65536;
pub const enum_FMOD_THREAD_TYPE = c_uint;
pub const FMOD_THREAD_TYPE = enum_FMOD_THREAD_TYPE;
pub const FMOD_CHANNELCONTROL_CHANNEL: c_int = 0;
pub const FMOD_CHANNELCONTROL_CHANNELGROUP: c_int = 1;
pub const FMOD_CHANNELCONTROL_MAX: c_int = 2;
pub const FMOD_CHANNELCONTROL_FORCEINT: c_int = 65536;
pub const enum_FMOD_CHANNELCONTROL_TYPE = c_uint;
pub const FMOD_CHANNELCONTROL_TYPE = enum_FMOD_CHANNELCONTROL_TYPE;
pub const FMOD_OUTPUTTYPE_AUTODETECT: c_int = 0;
pub const FMOD_OUTPUTTYPE_UNKNOWN: c_int = 1;
pub const FMOD_OUTPUTTYPE_NOSOUND: c_int = 2;
pub const FMOD_OUTPUTTYPE_WAVWRITER: c_int = 3;
pub const FMOD_OUTPUTTYPE_NOSOUND_NRT: c_int = 4;
pub const FMOD_OUTPUTTYPE_WAVWRITER_NRT: c_int = 5;
pub const FMOD_OUTPUTTYPE_WASAPI: c_int = 6;
pub const FMOD_OUTPUTTYPE_ASIO: c_int = 7;
pub const FMOD_OUTPUTTYPE_PULSEAUDIO: c_int = 8;
pub const FMOD_OUTPUTTYPE_ALSA: c_int = 9;
pub const FMOD_OUTPUTTYPE_COREAUDIO: c_int = 10;
pub const FMOD_OUTPUTTYPE_AUDIOTRACK: c_int = 11;
pub const FMOD_OUTPUTTYPE_OPENSL: c_int = 12;
pub const FMOD_OUTPUTTYPE_AUDIOOUT: c_int = 13;
pub const FMOD_OUTPUTTYPE_AUDIO3D: c_int = 14;
pub const FMOD_OUTPUTTYPE_WEBAUDIO: c_int = 15;
pub const FMOD_OUTPUTTYPE_NNAUDIO: c_int = 16;
pub const FMOD_OUTPUTTYPE_WINSONIC: c_int = 17;
pub const FMOD_OUTPUTTYPE_AAUDIO: c_int = 18;
pub const FMOD_OUTPUTTYPE_MAX: c_int = 19;
pub const FMOD_OUTPUTTYPE_FORCEINT: c_int = 65536;
pub const enum_FMOD_OUTPUTTYPE = c_uint;
pub const FMOD_OUTPUTTYPE = enum_FMOD_OUTPUTTYPE;
pub const FMOD_DEBUG_MODE_TTY: c_int = 0;
pub const FMOD_DEBUG_MODE_FILE: c_int = 1;
pub const FMOD_DEBUG_MODE_CALLBACK: c_int = 2;
pub const FMOD_DEBUG_MODE_FORCEINT: c_int = 65536;
pub const enum_FMOD_DEBUG_MODE = c_uint;
pub const FMOD_DEBUG_MODE = enum_FMOD_DEBUG_MODE;
pub const FMOD_SPEAKERMODE_DEFAULT: c_int = 0;
pub const FMOD_SPEAKERMODE_RAW: c_int = 1;
pub const FMOD_SPEAKERMODE_MONO: c_int = 2;
pub const FMOD_SPEAKERMODE_STEREO: c_int = 3;
pub const FMOD_SPEAKERMODE_QUAD: c_int = 4;
pub const FMOD_SPEAKERMODE_SURROUND: c_int = 5;
pub const FMOD_SPEAKERMODE_5POINT1: c_int = 6;
pub const FMOD_SPEAKERMODE_7POINT1: c_int = 7;
pub const FMOD_SPEAKERMODE_7POINT1POINT4: c_int = 8;
pub const FMOD_SPEAKERMODE_MAX: c_int = 9;
pub const FMOD_SPEAKERMODE_FORCEINT: c_int = 65536;
pub const enum_FMOD_SPEAKERMODE = c_uint;
pub const FMOD_SPEAKERMODE = enum_FMOD_SPEAKERMODE;
pub const FMOD_SPEAKER_NONE: c_int = -1;
pub const FMOD_SPEAKER_FRONT_LEFT: c_int = 0;
pub const FMOD_SPEAKER_FRONT_RIGHT: c_int = 1;
pub const FMOD_SPEAKER_FRONT_CENTER: c_int = 2;
pub const FMOD_SPEAKER_LOW_FREQUENCY: c_int = 3;
pub const FMOD_SPEAKER_SURROUND_LEFT: c_int = 4;
pub const FMOD_SPEAKER_SURROUND_RIGHT: c_int = 5;
pub const FMOD_SPEAKER_BACK_LEFT: c_int = 6;
pub const FMOD_SPEAKER_BACK_RIGHT: c_int = 7;
pub const FMOD_SPEAKER_TOP_FRONT_LEFT: c_int = 8;
pub const FMOD_SPEAKER_TOP_FRONT_RIGHT: c_int = 9;
pub const FMOD_SPEAKER_TOP_BACK_LEFT: c_int = 10;
pub const FMOD_SPEAKER_TOP_BACK_RIGHT: c_int = 11;
pub const FMOD_SPEAKER_MAX: c_int = 12;
pub const FMOD_SPEAKER_FORCEINT: c_int = 65536;
pub const enum_FMOD_SPEAKER = c_int;
pub const FMOD_SPEAKER = enum_FMOD_SPEAKER;
pub const FMOD_CHANNELORDER_DEFAULT: c_int = 0;
pub const FMOD_CHANNELORDER_WAVEFORMAT: c_int = 1;
pub const FMOD_CHANNELORDER_PROTOOLS: c_int = 2;
pub const FMOD_CHANNELORDER_ALLMONO: c_int = 3;
pub const FMOD_CHANNELORDER_ALLSTEREO: c_int = 4;
pub const FMOD_CHANNELORDER_ALSA: c_int = 5;
pub const FMOD_CHANNELORDER_MAX: c_int = 6;
pub const FMOD_CHANNELORDER_FORCEINT: c_int = 65536;
pub const enum_FMOD_CHANNELORDER = c_uint;
pub const FMOD_CHANNELORDER = enum_FMOD_CHANNELORDER;
pub const FMOD_PLUGINTYPE_OUTPUT: c_int = 0;
pub const FMOD_PLUGINTYPE_CODEC: c_int = 1;
pub const FMOD_PLUGINTYPE_DSP: c_int = 2;
pub const FMOD_PLUGINTYPE_MAX: c_int = 3;
pub const FMOD_PLUGINTYPE_FORCEINT: c_int = 65536;
pub const enum_FMOD_PLUGINTYPE = c_uint;
pub const FMOD_PLUGINTYPE = enum_FMOD_PLUGINTYPE;
pub const FMOD_SOUND_TYPE_UNKNOWN: c_int = 0;
pub const FMOD_SOUND_TYPE_AIFF: c_int = 1;
pub const FMOD_SOUND_TYPE_ASF: c_int = 2;
pub const FMOD_SOUND_TYPE_DLS: c_int = 3;
pub const FMOD_SOUND_TYPE_FLAC: c_int = 4;
pub const FMOD_SOUND_TYPE_FSB: c_int = 5;
pub const FMOD_SOUND_TYPE_IT: c_int = 6;
pub const FMOD_SOUND_TYPE_MIDI: c_int = 7;
pub const FMOD_SOUND_TYPE_MOD: c_int = 8;
pub const FMOD_SOUND_TYPE_MPEG: c_int = 9;
pub const FMOD_SOUND_TYPE_OGGVORBIS: c_int = 10;
pub const FMOD_SOUND_TYPE_PLAYLIST: c_int = 11;
pub const FMOD_SOUND_TYPE_RAW: c_int = 12;
pub const FMOD_SOUND_TYPE_S3M: c_int = 13;
pub const FMOD_SOUND_TYPE_USER: c_int = 14;
pub const FMOD_SOUND_TYPE_WAV: c_int = 15;
pub const FMOD_SOUND_TYPE_XM: c_int = 16;
pub const FMOD_SOUND_TYPE_XMA: c_int = 17;
pub const FMOD_SOUND_TYPE_AUDIOQUEUE: c_int = 18;
pub const FMOD_SOUND_TYPE_AT9: c_int = 19;
pub const FMOD_SOUND_TYPE_VORBIS: c_int = 20;
pub const FMOD_SOUND_TYPE_MEDIA_FOUNDATION: c_int = 21;
pub const FMOD_SOUND_TYPE_MEDIACODEC: c_int = 22;
pub const FMOD_SOUND_TYPE_FADPCM: c_int = 23;
pub const FMOD_SOUND_TYPE_OPUS: c_int = 24;
pub const FMOD_SOUND_TYPE_MAX: c_int = 25;
pub const FMOD_SOUND_TYPE_FORCEINT: c_int = 65536;
pub const enum_FMOD_SOUND_TYPE = c_uint;
pub const FMOD_SOUND_TYPE = enum_FMOD_SOUND_TYPE;
pub const FMOD_SOUND_FORMAT_NONE: c_int = 0;
pub const FMOD_SOUND_FORMAT_PCM8: c_int = 1;
pub const FMOD_SOUND_FORMAT_PCM16: c_int = 2;
pub const FMOD_SOUND_FORMAT_PCM24: c_int = 3;
pub const FMOD_SOUND_FORMAT_PCM32: c_int = 4;
pub const FMOD_SOUND_FORMAT_PCMFLOAT: c_int = 5;
pub const FMOD_SOUND_FORMAT_BITSTREAM: c_int = 6;
pub const FMOD_SOUND_FORMAT_MAX: c_int = 7;
pub const FMOD_SOUND_FORMAT_FORCEINT: c_int = 65536;
pub const enum_FMOD_SOUND_FORMAT = c_uint;
pub const FMOD_SOUND_FORMAT = enum_FMOD_SOUND_FORMAT;
pub const FMOD_OPENSTATE_READY: c_int = 0;
pub const FMOD_OPENSTATE_LOADING: c_int = 1;
pub const FMOD_OPENSTATE_ERROR: c_int = 2;
pub const FMOD_OPENSTATE_CONNECTING: c_int = 3;
pub const FMOD_OPENSTATE_BUFFERING: c_int = 4;
pub const FMOD_OPENSTATE_SEEKING: c_int = 5;
pub const FMOD_OPENSTATE_PLAYING: c_int = 6;
pub const FMOD_OPENSTATE_SETPOSITION: c_int = 7;
pub const FMOD_OPENSTATE_MAX: c_int = 8;
pub const FMOD_OPENSTATE_FORCEINT: c_int = 65536;
pub const enum_FMOD_OPENSTATE = c_uint;
pub const FMOD_OPENSTATE = enum_FMOD_OPENSTATE;
pub const FMOD_SOUNDGROUP_BEHAVIOR_FAIL: c_int = 0;
pub const FMOD_SOUNDGROUP_BEHAVIOR_MUTE: c_int = 1;
pub const FMOD_SOUNDGROUP_BEHAVIOR_STEALLOWEST: c_int = 2;
pub const FMOD_SOUNDGROUP_BEHAVIOR_MAX: c_int = 3;
pub const FMOD_SOUNDGROUP_BEHAVIOR_FORCEINT: c_int = 65536;
pub const enum_FMOD_SOUNDGROUP_BEHAVIOR = c_uint;
pub const FMOD_SOUNDGROUP_BEHAVIOR = enum_FMOD_SOUNDGROUP_BEHAVIOR;
pub const FMOD_CHANNELCONTROL_CALLBACK_END: c_int = 0;
pub const FMOD_CHANNELCONTROL_CALLBACK_VIRTUALVOICE: c_int = 1;
pub const FMOD_CHANNELCONTROL_CALLBACK_SYNCPOINT: c_int = 2;
pub const FMOD_CHANNELCONTROL_CALLBACK_OCCLUSION: c_int = 3;
pub const FMOD_CHANNELCONTROL_CALLBACK_MAX: c_int = 4;
pub const FMOD_CHANNELCONTROL_CALLBACK_FORCEINT: c_int = 65536;
pub const enum_FMOD_CHANNELCONTROL_CALLBACK_TYPE = c_uint;
pub const FMOD_CHANNELCONTROL_CALLBACK_TYPE = enum_FMOD_CHANNELCONTROL_CALLBACK_TYPE;
pub const FMOD_CHANNELCONTROL_DSP_HEAD: c_int = -1;
pub const FMOD_CHANNELCONTROL_DSP_FADER: c_int = -2;
pub const FMOD_CHANNELCONTROL_DSP_TAIL: c_int = -3;
pub const FMOD_CHANNELCONTROL_DSP_FORCEINT: c_int = 65536;
pub const enum_FMOD_CHANNELCONTROL_DSP_INDEX = c_int;
pub const FMOD_CHANNELCONTROL_DSP_INDEX = enum_FMOD_CHANNELCONTROL_DSP_INDEX;
pub const FMOD_ERRORCALLBACK_INSTANCETYPE_NONE: c_int = 0;
pub const FMOD_ERRORCALLBACK_INSTANCETYPE_SYSTEM: c_int = 1;
pub const FMOD_ERRORCALLBACK_INSTANCETYPE_CHANNEL: c_int = 2;
pub const FMOD_ERRORCALLBACK_INSTANCETYPE_CHANNELGROUP: c_int = 3;
pub const FMOD_ERRORCALLBACK_INSTANCETYPE_CHANNELCONTROL: c_int = 4;
pub const FMOD_ERRORCALLBACK_INSTANCETYPE_SOUND: c_int = 5;
pub const FMOD_ERRORCALLBACK_INSTANCETYPE_SOUNDGROUP: c_int = 6;
pub const FMOD_ERRORCALLBACK_INSTANCETYPE_DSP: c_int = 7;
pub const FMOD_ERRORCALLBACK_INSTANCETYPE_DSPCONNECTION: c_int = 8;
pub const FMOD_ERRORCALLBACK_INSTANCETYPE_GEOMETRY: c_int = 9;
pub const FMOD_ERRORCALLBACK_INSTANCETYPE_REVERB3D: c_int = 10;
pub const FMOD_ERRORCALLBACK_INSTANCETYPE_STUDIO_SYSTEM: c_int = 11;
pub const FMOD_ERRORCALLBACK_INSTANCETYPE_STUDIO_EVENTDESCRIPTION: c_int = 12;
pub const FMOD_ERRORCALLBACK_INSTANCETYPE_STUDIO_EVENTINSTANCE: c_int = 13;
pub const FMOD_ERRORCALLBACK_INSTANCETYPE_STUDIO_PARAMETERINSTANCE: c_int = 14;
pub const FMOD_ERRORCALLBACK_INSTANCETYPE_STUDIO_BUS: c_int = 15;
pub const FMOD_ERRORCALLBACK_INSTANCETYPE_STUDIO_VCA: c_int = 16;
pub const FMOD_ERRORCALLBACK_INSTANCETYPE_STUDIO_BANK: c_int = 17;
pub const FMOD_ERRORCALLBACK_INSTANCETYPE_STUDIO_COMMANDREPLAY: c_int = 18;
pub const FMOD_ERRORCALLBACK_INSTANCETYPE_FORCEINT: c_int = 65536;
pub const enum_FMOD_ERRORCALLBACK_INSTANCETYPE = c_uint;
pub const FMOD_ERRORCALLBACK_INSTANCETYPE = enum_FMOD_ERRORCALLBACK_INSTANCETYPE;
pub const FMOD_DSP_RESAMPLER_DEFAULT: c_int = 0;
pub const FMOD_DSP_RESAMPLER_NOINTERP: c_int = 1;
pub const FMOD_DSP_RESAMPLER_LINEAR: c_int = 2;
pub const FMOD_DSP_RESAMPLER_CUBIC: c_int = 3;
pub const FMOD_DSP_RESAMPLER_SPLINE: c_int = 4;
pub const FMOD_DSP_RESAMPLER_MAX: c_int = 5;
pub const FMOD_DSP_RESAMPLER_FORCEINT: c_int = 65536;
pub const enum_FMOD_DSP_RESAMPLER = c_uint;
pub const FMOD_DSP_RESAMPLER = enum_FMOD_DSP_RESAMPLER;
pub const FMOD_DSPCONNECTION_TYPE_STANDARD: c_int = 0;
pub const FMOD_DSPCONNECTION_TYPE_SIDECHAIN: c_int = 1;
pub const FMOD_DSPCONNECTION_TYPE_SEND: c_int = 2;
pub const FMOD_DSPCONNECTION_TYPE_SEND_SIDECHAIN: c_int = 3;
pub const FMOD_DSPCONNECTION_TYPE_MAX: c_int = 4;
pub const FMOD_DSPCONNECTION_TYPE_FORCEINT: c_int = 65536;
pub const enum_FMOD_DSPCONNECTION_TYPE = c_uint;
pub const FMOD_DSPCONNECTION_TYPE = enum_FMOD_DSPCONNECTION_TYPE;
pub const FMOD_TAGTYPE_UNKNOWN: c_int = 0;
pub const FMOD_TAGTYPE_ID3V1: c_int = 1;
pub const FMOD_TAGTYPE_ID3V2: c_int = 2;
pub const FMOD_TAGTYPE_VORBISCOMMENT: c_int = 3;
pub const FMOD_TAGTYPE_SHOUTCAST: c_int = 4;
pub const FMOD_TAGTYPE_ICECAST: c_int = 5;
pub const FMOD_TAGTYPE_ASF: c_int = 6;
pub const FMOD_TAGTYPE_MIDI: c_int = 7;
pub const FMOD_TAGTYPE_PLAYLIST: c_int = 8;
pub const FMOD_TAGTYPE_FMOD: c_int = 9;
pub const FMOD_TAGTYPE_USER: c_int = 10;
pub const FMOD_TAGTYPE_MAX: c_int = 11;
pub const FMOD_TAGTYPE_FORCEINT: c_int = 65536;
pub const enum_FMOD_TAGTYPE = c_uint;
pub const FMOD_TAGTYPE = enum_FMOD_TAGTYPE;
pub const FMOD_TAGDATATYPE_BINARY: c_int = 0;
pub const FMOD_TAGDATATYPE_INT: c_int = 1;
pub const FMOD_TAGDATATYPE_FLOAT: c_int = 2;
pub const FMOD_TAGDATATYPE_STRING: c_int = 3;
pub const FMOD_TAGDATATYPE_STRING_UTF16: c_int = 4;
pub const FMOD_TAGDATATYPE_STRING_UTF16BE: c_int = 5;
pub const FMOD_TAGDATATYPE_STRING_UTF8: c_int = 6;
pub const FMOD_TAGDATATYPE_MAX: c_int = 7;
pub const FMOD_TAGDATATYPE_FORCEINT: c_int = 65536;
pub const enum_FMOD_TAGDATATYPE = c_uint;
pub const FMOD_TAGDATATYPE = enum_FMOD_TAGDATATYPE;
pub const FMOD_DEBUG_CALLBACK = ?fn (FMOD_DEBUG_FLAGS, [*c]const u8, c_int, [*c]const u8, [*c]const u8) callconv(.C) FMOD_RESULT;
pub const FMOD_SYSTEM_CALLBACK = ?fn (?*FMOD_SYSTEM, FMOD_SYSTEM_CALLBACK_TYPE, ?*c_void, ?*c_void, ?*c_void) callconv(.C) FMOD_RESULT;
pub const FMOD_CHANNELCONTROL_CALLBACK = ?fn (?*FMOD_CHANNELCONTROL, FMOD_CHANNELCONTROL_TYPE, FMOD_CHANNELCONTROL_CALLBACK_TYPE, ?*c_void, ?*c_void) callconv(.C) FMOD_RESULT;
pub const FMOD_SOUND_NONBLOCK_CALLBACK = ?fn (?*FMOD_SOUND, FMOD_RESULT) callconv(.C) FMOD_RESULT;
pub const FMOD_SOUND_PCMREAD_CALLBACK = ?fn (?*FMOD_SOUND, ?*c_void, c_uint) callconv(.C) FMOD_RESULT;
pub const FMOD_SOUND_PCMSETPOS_CALLBACK = ?fn (?*FMOD_SOUND, c_int, c_uint, FMOD_TIMEUNIT) callconv(.C) FMOD_RESULT;
pub const FMOD_FILE_OPEN_CALLBACK = ?fn ([*c]const u8, [*c]c_uint, [*c]?*c_void, ?*c_void) callconv(.C) FMOD_RESULT;
pub const FMOD_FILE_CLOSE_CALLBACK = ?fn (?*c_void, ?*c_void) callconv(.C) FMOD_RESULT;
pub const FMOD_FILE_READ_CALLBACK = ?fn (?*c_void, ?*c_void, c_uint, [*c]c_uint, ?*c_void) callconv(.C) FMOD_RESULT;
pub const FMOD_FILE_SEEK_CALLBACK = ?fn (?*c_void, c_uint, ?*c_void) callconv(.C) FMOD_RESULT;
pub const FMOD_FILE_ASYNCREAD_CALLBACK = ?fn ([*c]FMOD_ASYNCREADINFO, ?*c_void) callconv(.C) FMOD_RESULT;
pub const FMOD_FILE_ASYNCCANCEL_CALLBACK = ?fn ([*c]FMOD_ASYNCREADINFO, ?*c_void) callconv(.C) FMOD_RESULT;
pub const FMOD_MEMORY_ALLOC_CALLBACK = ?fn (c_uint, FMOD_MEMORY_TYPE, [*c]const u8) callconv(.C) ?*c_void;
pub const FMOD_MEMORY_REALLOC_CALLBACK = ?fn (?*c_void, c_uint, FMOD_MEMORY_TYPE, [*c]const u8) callconv(.C) ?*c_void;
pub const FMOD_MEMORY_FREE_CALLBACK = ?fn (?*c_void, FMOD_MEMORY_TYPE, [*c]const u8) callconv(.C) void;
pub const FMOD_3D_ROLLOFF_CALLBACK = ?fn (?*FMOD_CHANNELCONTROL, f32) callconv(.C) f32;
pub const struct_FMOD_VECTOR = extern struct {
x: f32,
y: f32,
z: f32,
};
pub const FMOD_VECTOR = struct_FMOD_VECTOR;
pub const struct_FMOD_3D_ATTRIBUTES = extern struct {
position: FMOD_VECTOR,
velocity: FMOD_VECTOR,
forward: FMOD_VECTOR,
up: FMOD_VECTOR,
};
pub const FMOD_3D_ATTRIBUTES = struct_FMOD_3D_ATTRIBUTES;
pub const struct_FMOD_GUID = extern struct {
Data1: c_uint,
Data2: c_ushort,
Data3: c_ushort,
Data4: [8]u8,
};
pub const FMOD_GUID = struct_FMOD_GUID;
pub const struct_FMOD_PLUGINLIST = extern struct {
type: FMOD_PLUGINTYPE,
description: ?*c_void,
};
pub const FMOD_PLUGINLIST = struct_FMOD_PLUGINLIST;
pub const struct_FMOD_ADVANCEDSETTINGS = extern struct {
cbSize: c_int,
maxMPEGCodecs: c_int,
maxADPCMCodecs: c_int,
maxXMACodecs: c_int,
maxVorbisCodecs: c_int,
maxAT9Codecs: c_int,
maxFADPCMCodecs: c_int,
maxPCMCodecs: c_int,
ASIONumChannels: c_int,
ASIOChannelList: [*c][*c]u8,
ASIOSpeakerList: [*c]FMOD_SPEAKER,
vol0virtualvol: f32,
defaultDecodeBufferSize: c_uint,
profilePort: c_ushort,
geometryMaxFadeTime: c_uint,
distanceFilterCenterFreq: f32,
reverb3Dinstance: c_int,
DSPBufferPoolSize: c_int,
resamplerMethod: FMOD_DSP_RESAMPLER,
randomSeed: c_uint,
maxConvolutionThreads: c_int,
};
pub const FMOD_ADVANCEDSETTINGS = struct_FMOD_ADVANCEDSETTINGS;
pub const struct_FMOD_TAG = extern struct {
type: FMOD_TAGTYPE,
datatype: FMOD_TAGDATATYPE,
name: [*c]u8,
data: ?*c_void,
datalen: c_uint,
updated: FMOD_BOOL,
};
pub const FMOD_TAG = struct_FMOD_TAG;
pub const struct_FMOD_CREATESOUNDEXINFO = extern struct {
cbsize: c_int,
length: c_uint,
fileoffset: c_uint,
numchannels: c_int,
defaultfrequency: c_int,
format: FMOD_SOUND_FORMAT,
decodebuffersize: c_uint,
initialsubsound: c_int,
numsubsounds: c_int,
inclusionlist: [*c]c_int,
inclusionlistnum: c_int,
pcmreadcallback: FMOD_SOUND_PCMREAD_CALLBACK,
pcmsetposcallback: FMOD_SOUND_PCMSETPOS_CALLBACK,
nonblockcallback: FMOD_SOUND_NONBLOCK_CALLBACK,
dlsname: [*c]const u8,
encryptionkey: [*c]const u8,
maxpolyphony: c_int,
userdata: ?*c_void,
suggestedsoundtype: FMOD_SOUND_TYPE,
fileuseropen: FMOD_FILE_OPEN_CALLBACK,
fileuserclose: FMOD_FILE_CLOSE_CALLBACK,
fileuserread: FMOD_FILE_READ_CALLBACK,
fileuserseek: FMOD_FILE_SEEK_CALLBACK,
fileuserasyncread: FMOD_FILE_ASYNCREAD_CALLBACK,
fileuserasynccancel: FMOD_FILE_ASYNCCANCEL_CALLBACK,
fileuserdata: ?*c_void,
filebuffersize: c_int,
channelorder: FMOD_CHANNELORDER,
initialsoundgroup: ?*FMOD_SOUNDGROUP,
initialseekposition: c_uint,
initialseekpostype: FMOD_TIMEUNIT,
ignoresetfilesystem: c_int,
audioqueuepolicy: c_uint,
minmidigranularity: c_uint,
nonblockthreadid: c_int,
fsbguid: [*c]FMOD_GUID,
};
pub const FMOD_CREATESOUNDEXINFO = struct_FMOD_CREATESOUNDEXINFO;
pub const struct_FMOD_REVERB_PROPERTIES = extern struct {
DecayTime: f32,
EarlyDelay: f32,
LateDelay: f32,
HFReference: f32,
HFDecayRatio: f32,
Diffusion: f32,
Density: f32,
LowShelfFrequency: f32,
LowShelfGain: f32,
HighCut: f32,
EarlyLateMix: f32,
WetLevel: f32,
};
pub const FMOD_REVERB_PROPERTIES = struct_FMOD_REVERB_PROPERTIES;
pub const struct_FMOD_ERRORCALLBACK_INFO = extern struct {
result: FMOD_RESULT,
instancetype: FMOD_ERRORCALLBACK_INSTANCETYPE,
instance: ?*c_void,
functionname: [*c]const u8,
functionparams: [*c]const u8,
};
pub const FMOD_ERRORCALLBACK_INFO = struct_FMOD_ERRORCALLBACK_INFO;
pub const struct_FMOD_CODEC_WAVEFORMAT = extern struct {
name: [*c]const u8,
format: FMOD_SOUND_FORMAT,
channels: c_int,
frequency: c_int,
lengthbytes: c_uint,
lengthpcm: c_uint,
pcmblocksize: c_uint,
loopstart: c_int,
loopend: c_int,
mode: FMOD_MODE,
channelmask: FMOD_CHANNELMASK,
channelorder: FMOD_CHANNELORDER,
peakvolume: f32,
};
pub const FMOD_CODEC_WAVEFORMAT = struct_FMOD_CODEC_WAVEFORMAT;
pub const FMOD_CODEC_STATE = struct_FMOD_CODEC_STATE;
pub const FMOD_CODEC_METADATA_FUNC = ?fn ([*c]FMOD_CODEC_STATE, FMOD_TAGTYPE, [*c]u8, ?*c_void, c_uint, FMOD_TAGDATATYPE, c_int) callconv(.C) FMOD_RESULT;
pub const struct_FMOD_CODEC_STATE = extern struct {
numsubsounds: c_int,
waveformat: [*c]FMOD_CODEC_WAVEFORMAT,
plugindata: ?*c_void,
filehandle: ?*c_void,
filesize: c_uint,
fileread: FMOD_FILE_READ_CALLBACK,
fileseek: FMOD_FILE_SEEK_CALLBACK,
metadata: FMOD_CODEC_METADATA_FUNC,
waveformatversion: c_int,
};
pub const FMOD_CODEC_OPEN_CALLBACK = ?fn ([*c]FMOD_CODEC_STATE, FMOD_MODE, [*c]FMOD_CREATESOUNDEXINFO) callconv(.C) FMOD_RESULT;
pub const FMOD_CODEC_CLOSE_CALLBACK = ?fn ([*c]FMOD_CODEC_STATE) callconv(.C) FMOD_RESULT;
pub const FMOD_CODEC_READ_CALLBACK = ?fn ([*c]FMOD_CODEC_STATE, ?*c_void, c_uint, [*c]c_uint) callconv(.C) FMOD_RESULT;
pub const FMOD_CODEC_GETLENGTH_CALLBACK = ?fn ([*c]FMOD_CODEC_STATE, [*c]c_uint, FMOD_TIMEUNIT) callconv(.C) FMOD_RESULT;
pub const FMOD_CODEC_SETPOSITION_CALLBACK = ?fn ([*c]FMOD_CODEC_STATE, c_int, c_uint, FMOD_TIMEUNIT) callconv(.C) FMOD_RESULT;
pub const FMOD_CODEC_GETPOSITION_CALLBACK = ?fn ([*c]FMOD_CODEC_STATE, [*c]c_uint, FMOD_TIMEUNIT) callconv(.C) FMOD_RESULT;
pub const FMOD_CODEC_SOUNDCREATE_CALLBACK = ?fn ([*c]FMOD_CODEC_STATE, c_int, ?*FMOD_SOUND) callconv(.C) FMOD_RESULT;
pub const FMOD_CODEC_GETWAVEFORMAT_CALLBACK = ?fn ([*c]FMOD_CODEC_STATE, c_int, [*c]FMOD_CODEC_WAVEFORMAT) callconv(.C) FMOD_RESULT;
pub const struct_FMOD_CODEC_DESCRIPTION = extern struct {
name: [*c]const u8,
version: c_uint,
defaultasstream: c_int,
timeunits: FMOD_TIMEUNIT,
open: FMOD_CODEC_OPEN_CALLBACK,
close: FMOD_CODEC_CLOSE_CALLBACK,
read: FMOD_CODEC_READ_CALLBACK,
getlength: FMOD_CODEC_GETLENGTH_CALLBACK,
setposition: FMOD_CODEC_SETPOSITION_CALLBACK,
getposition: FMOD_CODEC_GETPOSITION_CALLBACK,
soundcreate: FMOD_CODEC_SOUNDCREATE_CALLBACK,
getwaveformat: FMOD_CODEC_GETWAVEFORMAT_CALLBACK,
};
pub const FMOD_CODEC_DESCRIPTION = struct_FMOD_CODEC_DESCRIPTION;
pub const FMOD_DSP_TYPE_UNKNOWN: c_int = 0;
pub const FMOD_DSP_TYPE_MIXER: c_int = 1;
pub const FMOD_DSP_TYPE_OSCILLATOR: c_int = 2;
pub const FMOD_DSP_TYPE_LOWPASS: c_int = 3;
pub const FMOD_DSP_TYPE_ITLOWPASS: c_int = 4;
pub const FMOD_DSP_TYPE_HIGHPASS: c_int = 5;
pub const FMOD_DSP_TYPE_ECHO: c_int = 6;
pub const FMOD_DSP_TYPE_FADER: c_int = 7;
pub const FMOD_DSP_TYPE_FLANGE: c_int = 8;
pub const FMOD_DSP_TYPE_DISTORTION: c_int = 9;
pub const FMOD_DSP_TYPE_NORMALIZE: c_int = 10;
pub const FMOD_DSP_TYPE_LIMITER: c_int = 11;
pub const FMOD_DSP_TYPE_PARAMEQ: c_int = 12;
pub const FMOD_DSP_TYPE_PITCHSHIFT: c_int = 13;
pub const FMOD_DSP_TYPE_CHORUS: c_int = 14;
pub const FMOD_DSP_TYPE_VSTPLUGIN: c_int = 15;
pub const FMOD_DSP_TYPE_WINAMPPLUGIN: c_int = 16;
pub const FMOD_DSP_TYPE_ITECHO: c_int = 17;
pub const FMOD_DSP_TYPE_COMPRESSOR: c_int = 18;
pub const FMOD_DSP_TYPE_SFXREVERB: c_int = 19;
pub const FMOD_DSP_TYPE_LOWPASS_SIMPLE: c_int = 20;
pub const FMOD_DSP_TYPE_DELAY: c_int = 21;
pub const FMOD_DSP_TYPE_TREMOLO: c_int = 22;
pub const FMOD_DSP_TYPE_LADSPAPLUGIN: c_int = 23;
pub const FMOD_DSP_TYPE_SEND: c_int = 24;
pub const FMOD_DSP_TYPE_RETURN: c_int = 25;
pub const FMOD_DSP_TYPE_HIGHPASS_SIMPLE: c_int = 26;
pub const FMOD_DSP_TYPE_PAN: c_int = 27;
pub const FMOD_DSP_TYPE_THREE_EQ: c_int = 28;
pub const FMOD_DSP_TYPE_FFT: c_int = 29;
pub const FMOD_DSP_TYPE_LOUDNESS_METER: c_int = 30;
pub const FMOD_DSP_TYPE_ENVELOPEFOLLOWER: c_int = 31;
pub const FMOD_DSP_TYPE_CONVOLUTIONREVERB: c_int = 32;
pub const FMOD_DSP_TYPE_CHANNELMIX: c_int = 33;
pub const FMOD_DSP_TYPE_TRANSCEIVER: c_int = 34;
pub const FMOD_DSP_TYPE_OBJECTPAN: c_int = 35;
pub const FMOD_DSP_TYPE_MULTIBAND_EQ: c_int = 36;
pub const FMOD_DSP_TYPE_MAX: c_int = 37;
pub const FMOD_DSP_TYPE_FORCEINT: c_int = 65536;
pub const FMOD_DSP_TYPE = c_uint;
pub const FMOD_DSP_OSCILLATOR_TYPE: c_int = 0;
pub const FMOD_DSP_OSCILLATOR_RATE: c_int = 1;
pub const FMOD_DSP_OSCILLATOR = c_uint;
pub const FMOD_DSP_LOWPASS_CUTOFF: c_int = 0;
pub const FMOD_DSP_LOWPASS_RESONANCE: c_int = 1;
pub const FMOD_DSP_LOWPASS = c_uint;
pub const FMOD_DSP_ITLOWPASS_CUTOFF: c_int = 0;
pub const FMOD_DSP_ITLOWPASS_RESONANCE: c_int = 1;
pub const FMOD_DSP_ITLOWPASS = c_uint;
pub const FMOD_DSP_HIGHPASS_CUTOFF: c_int = 0;
pub const FMOD_DSP_HIGHPASS_RESONANCE: c_int = 1;
pub const FMOD_DSP_HIGHPASS = c_uint;
pub const FMOD_DSP_ECHO_DELAY: c_int = 0;
pub const FMOD_DSP_ECHO_FEEDBACK: c_int = 1;
pub const FMOD_DSP_ECHO_DRYLEVEL: c_int = 2;
pub const FMOD_DSP_ECHO_WETLEVEL: c_int = 3;
pub const FMOD_DSP_ECHO = c_uint;
pub const FMOD_DSP_FADER_GAIN: c_int = 0;
pub const FMOD_DSP_FADER_OVERALL_GAIN: c_int = 1;
pub const enum_FMOD_DSP_FADER = c_uint;
pub const FMOD_DSP_FADER = enum_FMOD_DSP_FADER;
pub const FMOD_DSP_FLANGE_MIX: c_int = 0;
pub const FMOD_DSP_FLANGE_DEPTH: c_int = 1;
pub const FMOD_DSP_FLANGE_RATE: c_int = 2;
pub const FMOD_DSP_FLANGE = c_uint;
pub const FMOD_DSP_DISTORTION_LEVEL: c_int = 0;
pub const FMOD_DSP_DISTORTION = c_uint;
pub const FMOD_DSP_NORMALIZE_FADETIME: c_int = 0;
pub const FMOD_DSP_NORMALIZE_THRESHHOLD: c_int = 1;
pub const FMOD_DSP_NORMALIZE_MAXAMP: c_int = 2;
pub const FMOD_DSP_NORMALIZE = c_uint;
pub const FMOD_DSP_LIMITER_RELEASETIME: c_int = 0;
pub const FMOD_DSP_LIMITER_CEILING: c_int = 1;
pub const FMOD_DSP_LIMITER_MAXIMIZERGAIN: c_int = 2;
pub const FMOD_DSP_LIMITER_MODE: c_int = 3;
pub const FMOD_DSP_LIMITER = c_uint;
pub const FMOD_DSP_PARAMEQ_CENTER: c_int = 0;
pub const FMOD_DSP_PARAMEQ_BANDWIDTH: c_int = 1;
pub const FMOD_DSP_PARAMEQ_GAIN: c_int = 2;
pub const FMOD_DSP_PARAMEQ = c_uint;
pub const FMOD_DSP_MULTIBAND_EQ_A_FILTER: c_int = 0;
pub const FMOD_DSP_MULTIBAND_EQ_A_FREQUENCY: c_int = 1;
pub const FMOD_DSP_MULTIBAND_EQ_A_Q: c_int = 2;
pub const FMOD_DSP_MULTIBAND_EQ_A_GAIN: c_int = 3;
pub const FMOD_DSP_MULTIBAND_EQ_B_FILTER: c_int = 4;
pub const FMOD_DSP_MULTIBAND_EQ_B_FREQUENCY: c_int = 5;
pub const FMOD_DSP_MULTIBAND_EQ_B_Q: c_int = 6;
pub const FMOD_DSP_MULTIBAND_EQ_B_GAIN: c_int = 7;
pub const FMOD_DSP_MULTIBAND_EQ_C_FILTER: c_int = 8;
pub const FMOD_DSP_MULTIBAND_EQ_C_FREQUENCY: c_int = 9;
pub const FMOD_DSP_MULTIBAND_EQ_C_Q: c_int = 10;
pub const FMOD_DSP_MULTIBAND_EQ_C_GAIN: c_int = 11;
pub const FMOD_DSP_MULTIBAND_EQ_D_FILTER: c_int = 12;
pub const FMOD_DSP_MULTIBAND_EQ_D_FREQUENCY: c_int = 13;
pub const FMOD_DSP_MULTIBAND_EQ_D_Q: c_int = 14;
pub const FMOD_DSP_MULTIBAND_EQ_D_GAIN: c_int = 15;
pub const FMOD_DSP_MULTIBAND_EQ_E_FILTER: c_int = 16;
pub const FMOD_DSP_MULTIBAND_EQ_E_FREQUENCY: c_int = 17;
pub const FMOD_DSP_MULTIBAND_EQ_E_Q: c_int = 18;
pub const FMOD_DSP_MULTIBAND_EQ_E_GAIN: c_int = 19;
pub const enum_FMOD_DSP_MULTIBAND_EQ = c_uint;
pub const FMOD_DSP_MULTIBAND_EQ = enum_FMOD_DSP_MULTIBAND_EQ;
pub const FMOD_DSP_MULTIBAND_EQ_FILTER_DISABLED: c_int = 0;
pub const FMOD_DSP_MULTIBAND_EQ_FILTER_LOWPASS_12DB: c_int = 1;
pub const FMOD_DSP_MULTIBAND_EQ_FILTER_LOWPASS_24DB: c_int = 2;
pub const FMOD_DSP_MULTIBAND_EQ_FILTER_LOWPASS_48DB: c_int = 3;
pub const FMOD_DSP_MULTIBAND_EQ_FILTER_HIGHPASS_12DB: c_int = 4;
pub const FMOD_DSP_MULTIBAND_EQ_FILTER_HIGHPASS_24DB: c_int = 5;
pub const FMOD_DSP_MULTIBAND_EQ_FILTER_HIGHPASS_48DB: c_int = 6;
pub const FMOD_DSP_MULTIBAND_EQ_FILTER_LOWSHELF: c_int = 7;
pub const FMOD_DSP_MULTIBAND_EQ_FILTER_HIGHSHELF: c_int = 8;
pub const FMOD_DSP_MULTIBAND_EQ_FILTER_PEAKING: c_int = 9;
pub const FMOD_DSP_MULTIBAND_EQ_FILTER_BANDPASS: c_int = 10;
pub const FMOD_DSP_MULTIBAND_EQ_FILTER_NOTCH: c_int = 11;
pub const FMOD_DSP_MULTIBAND_EQ_FILTER_ALLPASS: c_int = 12;
pub const enum_FMOD_DSP_MULTIBAND_EQ_FILTER_TYPE = c_uint;
pub const FMOD_DSP_MULTIBAND_EQ_FILTER_TYPE = enum_FMOD_DSP_MULTIBAND_EQ_FILTER_TYPE;
pub const FMOD_DSP_PITCHSHIFT_PITCH: c_int = 0;
pub const FMOD_DSP_PITCHSHIFT_FFTSIZE: c_int = 1;
pub const FMOD_DSP_PITCHSHIFT_OVERLAP: c_int = 2;
pub const FMOD_DSP_PITCHSHIFT_MAXCHANNELS: c_int = 3;
pub const FMOD_DSP_PITCHSHIFT = c_uint;
pub const FMOD_DSP_CHORUS_MIX: c_int = 0;
pub const FMOD_DSP_CHORUS_RATE: c_int = 1;
pub const FMOD_DSP_CHORUS_DEPTH: c_int = 2;
pub const FMOD_DSP_CHORUS = c_uint;
pub const FMOD_DSP_ITECHO_WETDRYMIX: c_int = 0;
pub const FMOD_DSP_ITECHO_FEEDBACK: c_int = 1;
pub const FMOD_DSP_ITECHO_LEFTDELAY: c_int = 2;
pub const FMOD_DSP_ITECHO_RIGHTDELAY: c_int = 3;
pub const FMOD_DSP_ITECHO_PANDELAY: c_int = 4;
pub const FMOD_DSP_ITECHO = c_uint;
pub const FMOD_DSP_COMPRESSOR_THRESHOLD: c_int = 0;
pub const FMOD_DSP_COMPRESSOR_RATIO: c_int = 1;
pub const FMOD_DSP_COMPRESSOR_ATTACK: c_int = 2;
pub const FMOD_DSP_COMPRESSOR_RELEASE: c_int = 3;
pub const FMOD_DSP_COMPRESSOR_GAINMAKEUP: c_int = 4;
pub const FMOD_DSP_COMPRESSOR_USESIDECHAIN: c_int = 5;
pub const FMOD_DSP_COMPRESSOR_LINKED: c_int = 6;
pub const FMOD_DSP_COMPRESSOR = c_uint;
pub const FMOD_DSP_SFXREVERB_DECAYTIME: c_int = 0;
pub const FMOD_DSP_SFXREVERB_EARLYDELAY: c_int = 1;
pub const FMOD_DSP_SFXREVERB_LATEDELAY: c_int = 2;
pub const FMOD_DSP_SFXREVERB_HFREFERENCE: c_int = 3;
pub const FMOD_DSP_SFXREVERB_HFDECAYRATIO: c_int = 4;
pub const FMOD_DSP_SFXREVERB_DIFFUSION: c_int = 5;
pub const FMOD_DSP_SFXREVERB_DENSITY: c_int = 6;
pub const FMOD_DSP_SFXREVERB_LOWSHELFFREQUENCY: c_int = 7;
pub const FMOD_DSP_SFXREVERB_LOWSHELFGAIN: c_int = 8;
pub const FMOD_DSP_SFXREVERB_HIGHCUT: c_int = 9;
pub const FMOD_DSP_SFXREVERB_EARLYLATEMIX: c_int = 10;
pub const FMOD_DSP_SFXREVERB_WETLEVEL: c_int = 11;
pub const FMOD_DSP_SFXREVERB_DRYLEVEL: c_int = 12;
pub const FMOD_DSP_SFXREVERB = c_uint;
pub const FMOD_DSP_LOWPASS_SIMPLE_CUTOFF: c_int = 0;
pub const FMOD_DSP_LOWPASS_SIMPLE = c_uint;
pub const FMOD_DSP_DELAY_CH0: c_int = 0;
pub const FMOD_DSP_DELAY_CH1: c_int = 1;
pub const FMOD_DSP_DELAY_CH2: c_int = 2;
pub const FMOD_DSP_DELAY_CH3: c_int = 3;
pub const FMOD_DSP_DELAY_CH4: c_int = 4;
pub const FMOD_DSP_DELAY_CH5: c_int = 5;
pub const FMOD_DSP_DELAY_CH6: c_int = 6;
pub const FMOD_DSP_DELAY_CH7: c_int = 7;
pub const FMOD_DSP_DELAY_CH8: c_int = 8;
pub const FMOD_DSP_DELAY_CH9: c_int = 9;
pub const FMOD_DSP_DELAY_CH10: c_int = 10;
pub const FMOD_DSP_DELAY_CH11: c_int = 11;
pub const FMOD_DSP_DELAY_CH12: c_int = 12;
pub const FMOD_DSP_DELAY_CH13: c_int = 13;
pub const FMOD_DSP_DELAY_CH14: c_int = 14;
pub const FMOD_DSP_DELAY_CH15: c_int = 15;
pub const FMOD_DSP_DELAY_MAXDELAY: c_int = 16;
pub const FMOD_DSP_DELAY = c_uint;
pub const FMOD_DSP_TREMOLO_FREQUENCY: c_int = 0;
pub const FMOD_DSP_TREMOLO_DEPTH: c_int = 1;
pub const FMOD_DSP_TREMOLO_SHAPE: c_int = 2;
pub const FMOD_DSP_TREMOLO_SKEW: c_int = 3;
pub const FMOD_DSP_TREMOLO_DUTY: c_int = 4;
pub const FMOD_DSP_TREMOLO_SQUARE: c_int = 5;
pub const FMOD_DSP_TREMOLO_PHASE: c_int = 6;
pub const FMOD_DSP_TREMOLO_SPREAD: c_int = 7;
pub const FMOD_DSP_TREMOLO = c_uint;
pub const FMOD_DSP_SEND_RETURNID: c_int = 0;
pub const FMOD_DSP_SEND_LEVEL: c_int = 1;
pub const FMOD_DSP_SEND = c_uint;
pub const FMOD_DSP_RETURN_ID: c_int = 0;
pub const FMOD_DSP_RETURN_INPUT_SPEAKER_MODE: c_int = 1;
pub const FMOD_DSP_RETURN = c_uint;
pub const FMOD_DSP_HIGHPASS_SIMPLE_CUTOFF: c_int = 0;
pub const FMOD_DSP_HIGHPASS_SIMPLE = c_uint;
pub const FMOD_DSP_PAN_2D_STEREO_MODE_DISTRIBUTED: c_int = 0;
pub const FMOD_DSP_PAN_2D_STEREO_MODE_DISCRETE: c_int = 1;
pub const FMOD_DSP_PAN_2D_STEREO_MODE_TYPE = c_uint;
pub const FMOD_DSP_PAN_MODE_MONO: c_int = 0;
pub const FMOD_DSP_PAN_MODE_STEREO: c_int = 1;
pub const FMOD_DSP_PAN_MODE_SURROUND: c_int = 2;
pub const FMOD_DSP_PAN_MODE_TYPE = c_uint;
pub const FMOD_DSP_PAN_3D_ROLLOFF_LINEARSQUARED: c_int = 0;
pub const FMOD_DSP_PAN_3D_ROLLOFF_LINEAR: c_int = 1;
pub const FMOD_DSP_PAN_3D_ROLLOFF_INVERSE: c_int = 2;
pub const FMOD_DSP_PAN_3D_ROLLOFF_INVERSETAPERED: c_int = 3;
pub const FMOD_DSP_PAN_3D_ROLLOFF_CUSTOM: c_int = 4;
pub const FMOD_DSP_PAN_3D_ROLLOFF_TYPE = c_uint;
pub const FMOD_DSP_PAN_3D_EXTENT_MODE_AUTO: c_int = 0;
pub const FMOD_DSP_PAN_3D_EXTENT_MODE_USER: c_int = 1;
pub const FMOD_DSP_PAN_3D_EXTENT_MODE_OFF: c_int = 2;
pub const FMOD_DSP_PAN_3D_EXTENT_MODE_TYPE = c_uint;
pub const FMOD_DSP_PAN_MODE: c_int = 0;
pub const FMOD_DSP_PAN_2D_STEREO_POSITION: c_int = 1;
pub const FMOD_DSP_PAN_2D_DIRECTION: c_int = 2;
pub const FMOD_DSP_PAN_2D_EXTENT: c_int = 3;
pub const FMOD_DSP_PAN_2D_ROTATION: c_int = 4;
pub const FMOD_DSP_PAN_2D_LFE_LEVEL: c_int = 5;
pub const FMOD_DSP_PAN_2D_STEREO_MODE: c_int = 6;
pub const FMOD_DSP_PAN_2D_STEREO_SEPARATION: c_int = 7;
pub const FMOD_DSP_PAN_2D_STEREO_AXIS: c_int = 8;
pub const FMOD_DSP_PAN_ENABLED_SPEAKERS: c_int = 9;
pub const FMOD_DSP_PAN_3D_POSITION: c_int = 10;
pub const FMOD_DSP_PAN_3D_ROLLOFF: c_int = 11;
pub const FMOD_DSP_PAN_3D_MIN_DISTANCE: c_int = 12;
pub const FMOD_DSP_PAN_3D_MAX_DISTANCE: c_int = 13;
pub const FMOD_DSP_PAN_3D_EXTENT_MODE: c_int = 14;
pub const FMOD_DSP_PAN_3D_SOUND_SIZE: c_int = 15;
pub const FMOD_DSP_PAN_3D_MIN_EXTENT: c_int = 16;
pub const FMOD_DSP_PAN_3D_PAN_BLEND: c_int = 17;
pub const FMOD_DSP_PAN_LFE_UPMIX_ENABLED: c_int = 18;
pub const FMOD_DSP_PAN_OVERALL_GAIN: c_int = 19;
pub const FMOD_DSP_PAN_SURROUND_SPEAKER_MODE: c_int = 20;
pub const FMOD_DSP_PAN_2D_HEIGHT_BLEND: c_int = 21;
pub const FMOD_DSP_PAN = c_uint;
pub const FMOD_DSP_THREE_EQ_CROSSOVERSLOPE_12DB: c_int = 0;
pub const FMOD_DSP_THREE_EQ_CROSSOVERSLOPE_24DB: c_int = 1;
pub const FMOD_DSP_THREE_EQ_CROSSOVERSLOPE_48DB: c_int = 2;
pub const FMOD_DSP_THREE_EQ_CROSSOVERSLOPE_TYPE = c_uint;
pub const FMOD_DSP_THREE_EQ_LOWGAIN: c_int = 0;
pub const FMOD_DSP_THREE_EQ_MIDGAIN: c_int = 1;
pub const FMOD_DSP_THREE_EQ_HIGHGAIN: c_int = 2;
pub const FMOD_DSP_THREE_EQ_LOWCROSSOVER: c_int = 3;
pub const FMOD_DSP_THREE_EQ_HIGHCROSSOVER: c_int = 4;
pub const FMOD_DSP_THREE_EQ_CROSSOVERSLOPE: c_int = 5;
pub const FMOD_DSP_THREE_EQ = c_uint;
pub const FMOD_DSP_FFT_WINDOW_RECT: c_int = 0;
pub const FMOD_DSP_FFT_WINDOW_TRIANGLE: c_int = 1;
pub const FMOD_DSP_FFT_WINDOW_HAMMING: c_int = 2;
pub const FMOD_DSP_FFT_WINDOW_HANNING: c_int = 3;
pub const FMOD_DSP_FFT_WINDOW_BLACKMAN: c_int = 4;
pub const FMOD_DSP_FFT_WINDOW_BLACKMANHARRIS: c_int = 5;
pub const FMOD_DSP_FFT_WINDOW = c_uint;
pub const FMOD_DSP_FFT_WINDOWSIZE: c_int = 0;
pub const FMOD_DSP_FFT_WINDOWTYPE: c_int = 1;
pub const FMOD_DSP_FFT_SPECTRUMDATA: c_int = 2;
pub const FMOD_DSP_FFT_DOMINANT_FREQ: c_int = 3;
pub const FMOD_DSP_FFT = c_uint;
pub const FMOD_DSP_LOUDNESS_METER_STATE: c_int = 0;
pub const FMOD_DSP_LOUDNESS_METER_WEIGHTING: c_int = 1;
pub const FMOD_DSP_LOUDNESS_METER_INFO: c_int = 2;
pub const FMOD_DSP_LOUDNESS_METER = c_uint;
pub const FMOD_DSP_LOUDNESS_METER_STATE_RESET_INTEGRATED: c_int = -3;
pub const FMOD_DSP_LOUDNESS_METER_STATE_RESET_MAXPEAK: c_int = -2;
pub const FMOD_DSP_LOUDNESS_METER_STATE_RESET_ALL: c_int = -1;
pub const FMOD_DSP_LOUDNESS_METER_STATE_PAUSED: c_int = 0;
pub const FMOD_DSP_LOUDNESS_METER_STATE_ANALYZING: c_int = 1;
pub const FMOD_DSP_LOUDNESS_METER_STATE_TYPE = c_int;
pub const struct_FMOD_DSP_LOUDNESS_METER_INFO_TYPE = extern struct {
momentaryloudness: f32,
shorttermloudness: f32,
integratedloudness: f32,
loudness10thpercentile: f32,
loudness95thpercentile: f32,
loudnesshistogram: [66]f32,
maxtruepeak: f32,
maxmomentaryloudness: f32,
};
pub const FMOD_DSP_LOUDNESS_METER_INFO_TYPE = struct_FMOD_DSP_LOUDNESS_METER_INFO_TYPE;
pub const struct_FMOD_DSP_LOUDNESS_METER_WEIGHTING_TYPE = extern struct {
channelweight: [32]f32,
};
pub const FMOD_DSP_LOUDNESS_METER_WEIGHTING_TYPE = struct_FMOD_DSP_LOUDNESS_METER_WEIGHTING_TYPE;
pub const FMOD_DSP_ENVELOPEFOLLOWER_ATTACK: c_int = 0;
pub const FMOD_DSP_ENVELOPEFOLLOWER_RELEASE: c_int = 1;
pub const FMOD_DSP_ENVELOPEFOLLOWER_ENVELOPE: c_int = 2;
pub const FMOD_DSP_ENVELOPEFOLLOWER_USESIDECHAIN: c_int = 3;
pub const FMOD_DSP_ENVELOPEFOLLOWER = c_uint;
pub const FMOD_DSP_CONVOLUTION_REVERB_PARAM_IR: c_int = 0;
pub const FMOD_DSP_CONVOLUTION_REVERB_PARAM_WET: c_int = 1;
pub const FMOD_DSP_CONVOLUTION_REVERB_PARAM_DRY: c_int = 2;
pub const FMOD_DSP_CONVOLUTION_REVERB_PARAM_LINKED: c_int = 3;
pub const FMOD_DSP_CONVOLUTION_REVERB = c_uint;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_DEFAULT: c_int = 0;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_ALLMONO: c_int = 1;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_ALLSTEREO: c_int = 2;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_ALLQUAD: c_int = 3;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_ALL5POINT1: c_int = 4;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_ALL7POINT1: c_int = 5;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_ALLLFE: c_int = 6;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_ALL7POINT1POINT4: c_int = 7;
pub const FMOD_DSP_CHANNELMIX_OUTPUT = c_uint;
pub const FMOD_DSP_CHANNELMIX_OUTPUTGROUPING: c_int = 0;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH0: c_int = 1;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH1: c_int = 2;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH2: c_int = 3;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH3: c_int = 4;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH4: c_int = 5;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH5: c_int = 6;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH6: c_int = 7;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH7: c_int = 8;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH8: c_int = 9;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH9: c_int = 10;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH10: c_int = 11;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH11: c_int = 12;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH12: c_int = 13;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH13: c_int = 14;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH14: c_int = 15;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH15: c_int = 16;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH16: c_int = 17;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH17: c_int = 18;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH18: c_int = 19;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH19: c_int = 20;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH20: c_int = 21;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH21: c_int = 22;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH22: c_int = 23;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH23: c_int = 24;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH24: c_int = 25;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH25: c_int = 26;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH26: c_int = 27;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH27: c_int = 28;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH28: c_int = 29;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH29: c_int = 30;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH30: c_int = 31;
pub const FMOD_DSP_CHANNELMIX_GAIN_CH31: c_int = 32;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH0: c_int = 33;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH1: c_int = 34;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH2: c_int = 35;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH3: c_int = 36;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH4: c_int = 37;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH5: c_int = 38;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH6: c_int = 39;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH7: c_int = 40;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH8: c_int = 41;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH9: c_int = 42;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH10: c_int = 43;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH11: c_int = 44;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH12: c_int = 45;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH13: c_int = 46;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH14: c_int = 47;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH15: c_int = 48;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH16: c_int = 49;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH17: c_int = 50;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH18: c_int = 51;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH19: c_int = 52;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH20: c_int = 53;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH21: c_int = 54;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH22: c_int = 55;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH23: c_int = 56;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH24: c_int = 57;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH25: c_int = 58;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH26: c_int = 59;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH27: c_int = 60;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH28: c_int = 61;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH29: c_int = 62;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH30: c_int = 63;
pub const FMOD_DSP_CHANNELMIX_OUTPUT_CH31: c_int = 64;
pub const FMOD_DSP_CHANNELMIX = c_uint;
pub const FMOD_DSP_TRANSCEIVER_SPEAKERMODE_AUTO: c_int = -1;
pub const FMOD_DSP_TRANSCEIVER_SPEAKERMODE_MONO: c_int = 0;
pub const FMOD_DSP_TRANSCEIVER_SPEAKERMODE_STEREO: c_int = 1;
pub const FMOD_DSP_TRANSCEIVER_SPEAKERMODE_SURROUND: c_int = 2;
pub const FMOD_DSP_TRANSCEIVER_SPEAKERMODE = c_int;
pub const FMOD_DSP_TRANSCEIVER_TRANSMIT: c_int = 0;
pub const FMOD_DSP_TRANSCEIVER_GAIN: c_int = 1;
pub const FMOD_DSP_TRANSCEIVER_CHANNEL: c_int = 2;
pub const FMOD_DSP_TRANSCEIVER_TRANSMITSPEAKERMODE: c_int = 3;
pub const FMOD_DSP_TRANSCEIVER = c_uint;
pub const FMOD_DSP_OBJECTPAN_3D_POSITION: c_int = 0;
pub const FMOD_DSP_OBJECTPAN_3D_ROLLOFF: c_int = 1;
pub const FMOD_DSP_OBJECTPAN_3D_MIN_DISTANCE: c_int = 2;
pub const FMOD_DSP_OBJECTPAN_3D_MAX_DISTANCE: c_int = 3;
pub const FMOD_DSP_OBJECTPAN_3D_EXTENT_MODE: c_int = 4;
pub const FMOD_DSP_OBJECTPAN_3D_SOUND_SIZE: c_int = 5;
pub const FMOD_DSP_OBJECTPAN_3D_MIN_EXTENT: c_int = 6;
pub const FMOD_DSP_OBJECTPAN_OVERALL_GAIN: c_int = 7;
pub const FMOD_DSP_OBJECTPAN_OUTPUTGAIN: c_int = 8;
pub const FMOD_DSP_OBJECTPAN = c_uint;
pub const FMOD_DSP_ALLOC_FUNC = ?fn (c_uint, FMOD_MEMORY_TYPE, [*c]const u8) callconv(.C) ?*c_void;
pub const FMOD_DSP_REALLOC_FUNC = ?fn (?*c_void, c_uint, FMOD_MEMORY_TYPE, [*c]const u8) callconv(.C) ?*c_void;
pub const FMOD_DSP_FREE_FUNC = ?fn (?*c_void, FMOD_MEMORY_TYPE, [*c]const u8) callconv(.C) void;
pub const FMOD_DSP_STATE = struct_FMOD_DSP_STATE;
pub const FMOD_DSP_GETSAMPLERATE_FUNC = ?fn ([*c]FMOD_DSP_STATE, [*c]c_int) callconv(.C) FMOD_RESULT;
pub const FMOD_DSP_GETBLOCKSIZE_FUNC = ?fn ([*c]FMOD_DSP_STATE, [*c]c_uint) callconv(.C) FMOD_RESULT;
pub const struct_FMOD_COMPLEX = extern struct {
real: f32,
imag: f32,
};
pub const FMOD_COMPLEX = struct_FMOD_COMPLEX;
pub const FMOD_DSP_DFT_FFTREAL_FUNC = ?fn ([*c]FMOD_DSP_STATE, c_int, [*c]const f32, [*c]FMOD_COMPLEX, [*c]const f32, c_int) callconv(.C) FMOD_RESULT;
pub const FMOD_DSP_DFT_IFFTREAL_FUNC = ?fn ([*c]FMOD_DSP_STATE, c_int, [*c]const FMOD_COMPLEX, [*c]f32, [*c]const f32, c_int) callconv(.C) FMOD_RESULT;
pub const struct_FMOD_DSP_STATE_DFT_FUNCTIONS = extern struct {
fftreal: FMOD_DSP_DFT_FFTREAL_FUNC,
inversefftreal: FMOD_DSP_DFT_IFFTREAL_FUNC,
};
pub const FMOD_DSP_STATE_DFT_FUNCTIONS = struct_FMOD_DSP_STATE_DFT_FUNCTIONS;
pub const FMOD_DSP_PAN_SUMMONOMATRIX_FUNC = ?fn ([*c]FMOD_DSP_STATE, FMOD_SPEAKERMODE, f32, f32, [*c]f32) callconv(.C) FMOD_RESULT;
pub const FMOD_DSP_PAN_SUMSTEREOMATRIX_FUNC = ?fn ([*c]FMOD_DSP_STATE, FMOD_SPEAKERMODE, f32, f32, f32, c_int, [*c]f32) callconv(.C) FMOD_RESULT;
pub const FMOD_DSP_PAN_SURROUND_DEFAULT: c_int = 0;
pub const FMOD_DSP_PAN_SURROUND_ROTATION_NOT_BIASED: c_int = 1;
pub const FMOD_DSP_PAN_SURROUND_FLAGS_FORCEINT: c_int = 65536;
pub const enum_FMOD_DSP_PAN_SURROUND_FLAGS = c_uint;
pub const FMOD_DSP_PAN_SURROUND_FLAGS = enum_FMOD_DSP_PAN_SURROUND_FLAGS;
pub const FMOD_DSP_PAN_SUMSURROUNDMATRIX_FUNC = ?fn ([*c]FMOD_DSP_STATE, FMOD_SPEAKERMODE, FMOD_SPEAKERMODE, f32, f32, f32, f32, f32, c_int, [*c]f32, FMOD_DSP_PAN_SURROUND_FLAGS) callconv(.C) FMOD_RESULT;
pub const FMOD_DSP_PAN_SUMMONOTOSURROUNDMATRIX_FUNC = ?fn ([*c]FMOD_DSP_STATE, FMOD_SPEAKERMODE, f32, f32, f32, f32, c_int, [*c]f32) callconv(.C) FMOD_RESULT;
pub const FMOD_DSP_PAN_SUMSTEREOTOSURROUNDMATRIX_FUNC = ?fn ([*c]FMOD_DSP_STATE, FMOD_SPEAKERMODE, f32, f32, f32, f32, f32, c_int, [*c]f32) callconv(.C) FMOD_RESULT;
pub const FMOD_DSP_PAN_GETROLLOFFGAIN_FUNC = ?fn ([*c]FMOD_DSP_STATE, FMOD_DSP_PAN_3D_ROLLOFF_TYPE, f32, f32, f32, [*c]f32) callconv(.C) FMOD_RESULT;
pub const struct_FMOD_DSP_STATE_PAN_FUNCTIONS = extern struct {
summonomatrix: FMOD_DSP_PAN_SUMMONOMATRIX_FUNC,
sumstereomatrix: FMOD_DSP_PAN_SUMSTEREOMATRIX_FUNC,
sumsurroundmatrix: FMOD_DSP_PAN_SUMSURROUNDMATRIX_FUNC,
summonotosurroundmatrix: FMOD_DSP_PAN_SUMMONOTOSURROUNDMATRIX_FUNC,
sumstereotosurroundmatrix: FMOD_DSP_PAN_SUMSTEREOTOSURROUNDMATRIX_FUNC,
getrolloffgain: FMOD_DSP_PAN_GETROLLOFFGAIN_FUNC,
};
pub const FMOD_DSP_STATE_PAN_FUNCTIONS = struct_FMOD_DSP_STATE_PAN_FUNCTIONS;
pub const FMOD_DSP_GETSPEAKERMODE_FUNC = ?fn ([*c]FMOD_DSP_STATE, [*c]FMOD_SPEAKERMODE, [*c]FMOD_SPEAKERMODE) callconv(.C) FMOD_RESULT;
pub const FMOD_DSP_GETCLOCK_FUNC = ?fn ([*c]FMOD_DSP_STATE, [*c]c_ulonglong, [*c]c_uint, [*c]c_uint) callconv(.C) FMOD_RESULT;
pub const FMOD_DSP_GETLISTENERATTRIBUTES_FUNC = ?fn ([*c]FMOD_DSP_STATE, [*c]c_int, [*c]FMOD_3D_ATTRIBUTES) callconv(.C) FMOD_RESULT;
pub const FMOD_DSP_LOG_FUNC = ?fn (FMOD_DEBUG_FLAGS, [*c]const u8, c_int, [*c]const u8, [*c]const u8, ...) callconv(.C) void;
pub const FMOD_DSP_GETUSERDATA_FUNC = ?fn ([*c]FMOD_DSP_STATE, [*c]?*c_void) callconv(.C) FMOD_RESULT;
pub const struct_FMOD_DSP_STATE_FUNCTIONS = extern struct {
alloc: FMOD_DSP_ALLOC_FUNC,
realloc: FMOD_DSP_REALLOC_FUNC,
free: FMOD_DSP_FREE_FUNC,
getsamplerate: FMOD_DSP_GETSAMPLERATE_FUNC,
getblocksize: FMOD_DSP_GETBLOCKSIZE_FUNC,
dft: [*c]FMOD_DSP_STATE_DFT_FUNCTIONS,
pan: [*c]FMOD_DSP_STATE_PAN_FUNCTIONS,
getspeakermode: FMOD_DSP_GETSPEAKERMODE_FUNC,
getclock: FMOD_DSP_GETCLOCK_FUNC,
getlistenerattributes: FMOD_DSP_GETLISTENERATTRIBUTES_FUNC,
log: FMOD_DSP_LOG_FUNC,
getuserdata: FMOD_DSP_GETUSERDATA_FUNC,
};
pub const FMOD_DSP_STATE_FUNCTIONS = struct_FMOD_DSP_STATE_FUNCTIONS;
pub const struct_FMOD_DSP_STATE = extern struct {
instance: ?*c_void,
plugindata: ?*c_void,
channelmask: FMOD_CHANNELMASK,
source_speakermode: FMOD_SPEAKERMODE,
sidechaindata: [*c]f32,
sidechainchannels: c_int,
functions: [*c]FMOD_DSP_STATE_FUNCTIONS,
systemobject: c_int,
};
pub const struct_FMOD_DSP_BUFFER_ARRAY = extern struct {
numbuffers: c_int,
buffernumchannels: [*c]c_int,
bufferchannelmask: [*c]FMOD_CHANNELMASK,
buffers: [*c][*c]f32,
speakermode: FMOD_SPEAKERMODE,
};
pub const FMOD_DSP_BUFFER_ARRAY = struct_FMOD_DSP_BUFFER_ARRAY;
pub const FMOD_DSP_PROCESS_PERFORM: c_int = 0;
pub const FMOD_DSP_PROCESS_QUERY: c_int = 1;
pub const FMOD_DSP_PROCESS_OPERATION = c_uint;
pub const FMOD_DSP_PARAMETER_TYPE_FLOAT: c_int = 0;
pub const FMOD_DSP_PARAMETER_TYPE_INT: c_int = 1;
pub const FMOD_DSP_PARAMETER_TYPE_BOOL: c_int = 2;
pub const FMOD_DSP_PARAMETER_TYPE_DATA: c_int = 3;
pub const FMOD_DSP_PARAMETER_TYPE_MAX: c_int = 4;
pub const FMOD_DSP_PARAMETER_TYPE_FORCEINT: c_int = 65536;
pub const FMOD_DSP_PARAMETER_TYPE = c_uint;
pub const FMOD_DSP_PARAMETER_FLOAT_MAPPING_TYPE_LINEAR: c_int = 0;
pub const FMOD_DSP_PARAMETER_FLOAT_MAPPING_TYPE_AUTO: c_int = 1;
pub const FMOD_DSP_PARAMETER_FLOAT_MAPPING_TYPE_PIECEWISE_LINEAR: c_int = 2;
pub const FMOD_DSP_PARAMETER_FLOAT_MAPPING_TYPE_FORCEINT: c_int = 65536;
pub const FMOD_DSP_PARAMETER_FLOAT_MAPPING_TYPE = c_uint;
pub const FMOD_DSP_PARAMETER_DATA_TYPE_USER: c_int = 0;
pub const FMOD_DSP_PARAMETER_DATA_TYPE_OVERALLGAIN: c_int = -1;
pub const FMOD_DSP_PARAMETER_DATA_TYPE_3DATTRIBUTES: c_int = -2;
pub const FMOD_DSP_PARAMETER_DATA_TYPE_SIDECHAIN: c_int = -3;
pub const FMOD_DSP_PARAMETER_DATA_TYPE_FFT: c_int = -4;
pub const FMOD_DSP_PARAMETER_DATA_TYPE_3DATTRIBUTES_MULTI: c_int = -5;
pub const FMOD_DSP_PARAMETER_DATA_TYPE = c_int;
pub const FMOD_DSP_CREATE_CALLBACK = ?fn ([*c]FMOD_DSP_STATE) callconv(.C) FMOD_RESULT;
pub const FMOD_DSP_RELEASE_CALLBACK = ?fn ([*c]FMOD_DSP_STATE) callconv(.C) FMOD_RESULT;
pub const FMOD_DSP_RESET_CALLBACK = ?fn ([*c]FMOD_DSP_STATE) callconv(.C) FMOD_RESULT;
pub const FMOD_DSP_READ_CALLBACK = ?fn ([*c]FMOD_DSP_STATE, [*c]f32, [*c]f32, c_uint, c_int, [*c]c_int) callconv(.C) FMOD_RESULT;
pub const FMOD_DSP_PROCESS_CALLBACK = ?fn ([*c]FMOD_DSP_STATE, c_uint, [*c]const FMOD_DSP_BUFFER_ARRAY, [*c]FMOD_DSP_BUFFER_ARRAY, FMOD_BOOL, FMOD_DSP_PROCESS_OPERATION) callconv(.C) FMOD_RESULT;
pub const FMOD_DSP_SETPOSITION_CALLBACK = ?fn ([*c]FMOD_DSP_STATE, c_uint) callconv(.C) FMOD_RESULT;
pub const FMOD_DSP_SHOULDIPROCESS_CALLBACK = ?fn ([*c]FMOD_DSP_STATE, FMOD_BOOL, c_uint, FMOD_CHANNELMASK, c_int, FMOD_SPEAKERMODE) callconv(.C) FMOD_RESULT;
pub const FMOD_DSP_SETPARAM_FLOAT_CALLBACK = ?fn ([*c]FMOD_DSP_STATE, c_int, f32) callconv(.C) FMOD_RESULT;
pub const FMOD_DSP_SETPARAM_INT_CALLBACK = ?fn ([*c]FMOD_DSP_STATE, c_int, c_int) callconv(.C) FMOD_RESULT;
pub const FMOD_DSP_SETPARAM_BOOL_CALLBACK = ?fn ([*c]FMOD_DSP_STATE, c_int, FMOD_BOOL) callconv(.C) FMOD_RESULT;
pub const FMOD_DSP_SETPARAM_DATA_CALLBACK = ?fn ([*c]FMOD_DSP_STATE, c_int, ?*c_void, c_uint) callconv(.C) FMOD_RESULT;
pub const FMOD_DSP_GETPARAM_FLOAT_CALLBACK = ?fn ([*c]FMOD_DSP_STATE, c_int, [*c]f32, [*c]u8) callconv(.C) FMOD_RESULT;
pub const FMOD_DSP_GETPARAM_INT_CALLBACK = ?fn ([*c]FMOD_DSP_STATE, c_int, [*c]c_int, [*c]u8) callconv(.C) FMOD_RESULT;
pub const FMOD_DSP_GETPARAM_BOOL_CALLBACK = ?fn ([*c]FMOD_DSP_STATE, c_int, [*c]FMOD_BOOL, [*c]u8) callconv(.C) FMOD_RESULT;
pub const FMOD_DSP_GETPARAM_DATA_CALLBACK = ?fn ([*c]FMOD_DSP_STATE, c_int, [*c]?*c_void, [*c]c_uint, [*c]u8) callconv(.C) FMOD_RESULT;
pub const FMOD_DSP_SYSTEM_REGISTER_CALLBACK = ?fn ([*c]FMOD_DSP_STATE) callconv(.C) FMOD_RESULT;
pub const FMOD_DSP_SYSTEM_DEREGISTER_CALLBACK = ?fn ([*c]FMOD_DSP_STATE) callconv(.C) FMOD_RESULT;
pub const FMOD_DSP_SYSTEM_MIX_CALLBACK = ?fn ([*c]FMOD_DSP_STATE, c_int) callconv(.C) FMOD_RESULT;
pub const struct_FMOD_DSP_PARAMETER_FLOAT_MAPPING_PIECEWISE_LINEAR = extern struct {
numpoints: c_int,
pointparamvalues: [*c]f32,
pointpositions: [*c]f32,
};
pub const FMOD_DSP_PARAMETER_FLOAT_MAPPING_PIECEWISE_LINEAR = struct_FMOD_DSP_PARAMETER_FLOAT_MAPPING_PIECEWISE_LINEAR;
pub const struct_FMOD_DSP_PARAMETER_FLOAT_MAPPING = extern struct {
type: FMOD_DSP_PARAMETER_FLOAT_MAPPING_TYPE,
piecewiselinearmapping: FMOD_DSP_PARAMETER_FLOAT_MAPPING_PIECEWISE_LINEAR,
};
pub const FMOD_DSP_PARAMETER_FLOAT_MAPPING = struct_FMOD_DSP_PARAMETER_FLOAT_MAPPING;
pub const struct_FMOD_DSP_PARAMETER_DESC_FLOAT = extern struct {
min: f32,
max: f32,
defaultval: f32,
mapping: FMOD_DSP_PARAMETER_FLOAT_MAPPING,
};
pub const FMOD_DSP_PARAMETER_DESC_FLOAT = struct_FMOD_DSP_PARAMETER_DESC_FLOAT;
pub const struct_FMOD_DSP_PARAMETER_DESC_INT = extern struct {
min: c_int,
max: c_int,
defaultval: c_int,
goestoinf: FMOD_BOOL,
valuenames: [*c]const [*c]const u8,
};
pub const FMOD_DSP_PARAMETER_DESC_INT = struct_FMOD_DSP_PARAMETER_DESC_INT;
pub const struct_FMOD_DSP_PARAMETER_DESC_BOOL = extern struct {
defaultval: FMOD_BOOL,
valuenames: [*c]const [*c]const u8,
};
pub const FMOD_DSP_PARAMETER_DESC_BOOL = struct_FMOD_DSP_PARAMETER_DESC_BOOL;
pub const struct_FMOD_DSP_PARAMETER_DESC_DATA = extern struct {
datatype: c_int,
};
pub const FMOD_DSP_PARAMETER_DESC_DATA = struct_FMOD_DSP_PARAMETER_DESC_DATA;
const union_unnamed_1 = extern union {
floatdesc: FMOD_DSP_PARAMETER_DESC_FLOAT,
intdesc: FMOD_DSP_PARAMETER_DESC_INT,
booldesc: FMOD_DSP_PARAMETER_DESC_BOOL,
datadesc: FMOD_DSP_PARAMETER_DESC_DATA,
};
pub const struct_FMOD_DSP_PARAMETER_DESC = extern struct {
type: FMOD_DSP_PARAMETER_TYPE,
name: [16]u8,
label: [16]u8,
description: [*c]const u8,
unnamed_0: union_unnamed_1,
};
pub const FMOD_DSP_PARAMETER_DESC = struct_FMOD_DSP_PARAMETER_DESC;
pub const struct_FMOD_DSP_PARAMETER_OVERALLGAIN = extern struct {
linear_gain: f32,
linear_gain_additive: f32,
};
pub const FMOD_DSP_PARAMETER_OVERALLGAIN = struct_FMOD_DSP_PARAMETER_OVERALLGAIN;
pub const struct_FMOD_DSP_PARAMETER_3DATTRIBUTES = extern struct {
relative: FMOD_3D_ATTRIBUTES,
absolute: FMOD_3D_ATTRIBUTES,
};
pub const FMOD_DSP_PARAMETER_3DATTRIBUTES = struct_FMOD_DSP_PARAMETER_3DATTRIBUTES;
pub const struct_FMOD_DSP_PARAMETER_3DATTRIBUTES_MULTI = extern struct {
numlisteners: c_int,
relative: [8]FMOD_3D_ATTRIBUTES,
weight: [8]f32,
absolute: FMOD_3D_ATTRIBUTES,
};
pub const FMOD_DSP_PARAMETER_3DATTRIBUTES_MULTI = struct_FMOD_DSP_PARAMETER_3DATTRIBUTES_MULTI;
pub const struct_FMOD_DSP_PARAMETER_SIDECHAIN = extern struct {
sidechainenable: FMOD_BOOL,
};
pub const FMOD_DSP_PARAMETER_SIDECHAIN = struct_FMOD_DSP_PARAMETER_SIDECHAIN;
pub const struct_FMOD_DSP_PARAMETER_FFT = extern struct {
length: c_int,
numchannels: c_int,
spectrum: [32][*c]f32,
};
pub const FMOD_DSP_PARAMETER_FFT = struct_FMOD_DSP_PARAMETER_FFT;
pub const struct_FMOD_DSP_DESCRIPTION = extern struct {
pluginsdkversion: c_uint,
name: [32]u8,
version: c_uint,
numinputbuffers: c_int,
numoutputbuffers: c_int,
create: FMOD_DSP_CREATE_CALLBACK,
release: FMOD_DSP_RELEASE_CALLBACK,
reset: FMOD_DSP_RESET_CALLBACK,
read: FMOD_DSP_READ_CALLBACK,
process: FMOD_DSP_PROCESS_CALLBACK,
setposition: FMOD_DSP_SETPOSITION_CALLBACK,
numparameters: c_int,
paramdesc: [*c][*c]FMOD_DSP_PARAMETER_DESC,
setparameterfloat: FMOD_DSP_SETPARAM_FLOAT_CALLBACK,
setparameterint: FMOD_DSP_SETPARAM_INT_CALLBACK,
setparameterbool: FMOD_DSP_SETPARAM_BOOL_CALLBACK,
setparameterdata: FMOD_DSP_SETPARAM_DATA_CALLBACK,
getparameterfloat: FMOD_DSP_GETPARAM_FLOAT_CALLBACK,
getparameterint: FMOD_DSP_GETPARAM_INT_CALLBACK,
getparameterbool: FMOD_DSP_GETPARAM_BOOL_CALLBACK,
getparameterdata: FMOD_DSP_GETPARAM_DATA_CALLBACK,
shouldiprocess: FMOD_DSP_SHOULDIPROCESS_CALLBACK,
userdata: ?*c_void,
sys_register: FMOD_DSP_SYSTEM_REGISTER_CALLBACK,
sys_deregister: FMOD_DSP_SYSTEM_DEREGISTER_CALLBACK,
sys_mix: FMOD_DSP_SYSTEM_MIX_CALLBACK,
};
pub const FMOD_DSP_DESCRIPTION = struct_FMOD_DSP_DESCRIPTION;
pub const struct_FMOD_DSP_METERING_INFO = extern struct {
numsamples: c_int,
peaklevel: [32]f32,
rmslevel: [32]f32,
numchannels: c_short,
};
pub const FMOD_DSP_METERING_INFO = struct_FMOD_DSP_METERING_INFO;
pub const FMOD_OUTPUT_STATE = struct_FMOD_OUTPUT_STATE;
pub const FMOD_OUTPUT_READFROMMIXER_FUNC = ?fn ([*c]FMOD_OUTPUT_STATE, ?*c_void, c_uint) callconv(.C) FMOD_RESULT;
pub const FMOD_OUTPUT_ALLOC_FUNC = ?fn (c_uint, c_uint, [*c]const u8, c_int) callconv(.C) ?*c_void;
pub const FMOD_OUTPUT_FREE_FUNC = ?fn (?*c_void, [*c]const u8, c_int) callconv(.C) void;
pub const FMOD_OUTPUT_LOG_FUNC = ?fn (FMOD_DEBUG_FLAGS, [*c]const u8, c_int, [*c]const u8, [*c]const u8, ...) callconv(.C) void;
pub const FMOD_OUTPUT_COPYPORT_FUNC = ?fn ([*c]FMOD_OUTPUT_STATE, c_int, ?*c_void, c_uint) callconv(.C) FMOD_RESULT;
pub const FMOD_OUTPUT_REQUESTRESET_FUNC = ?fn ([*c]FMOD_OUTPUT_STATE) callconv(.C) FMOD_RESULT;
pub const struct_FMOD_OUTPUT_STATE = extern struct {
plugindata: ?*c_void,
readfrommixer: FMOD_OUTPUT_READFROMMIXER_FUNC,
alloc: FMOD_OUTPUT_ALLOC_FUNC,
free: FMOD_OUTPUT_FREE_FUNC,
log: FMOD_OUTPUT_LOG_FUNC,
copyport: FMOD_OUTPUT_COPYPORT_FUNC,
requestreset: FMOD_OUTPUT_REQUESTRESET_FUNC,
};
pub const struct_FMOD_OUTPUT_OBJECT3DINFO = extern struct {
buffer: [*c]f32,
bufferlength: c_uint,
position: FMOD_VECTOR,
gain: f32,
spread: f32,
priority: f32,
};
pub const FMOD_OUTPUT_OBJECT3DINFO = struct_FMOD_OUTPUT_OBJECT3DINFO;
pub const FMOD_OUTPUT_METHOD = c_uint;
pub const FMOD_OUTPUT_GETNUMDRIVERS_CALLBACK = ?fn ([*c]FMOD_OUTPUT_STATE, [*c]c_int) callconv(.C) FMOD_RESULT;
pub const FMOD_OUTPUT_GETDRIVERINFO_CALLBACK = ?fn ([*c]FMOD_OUTPUT_STATE, c_int, [*c]u8, c_int, [*c]FMOD_GUID, [*c]c_int, [*c]FMOD_SPEAKERMODE, [*c]c_int) callconv(.C) FMOD_RESULT;
pub const FMOD_OUTPUT_INIT_CALLBACK = ?fn ([*c]FMOD_OUTPUT_STATE, c_int, FMOD_INITFLAGS, [*c]c_int, [*c]FMOD_SPEAKERMODE, [*c]c_int, [*c]FMOD_SOUND_FORMAT, c_int, c_int, ?*c_void) callconv(.C) FMOD_RESULT;
pub const FMOD_OUTPUT_START_CALLBACK = ?fn ([*c]FMOD_OUTPUT_STATE) callconv(.C) FMOD_RESULT;
pub const FMOD_OUTPUT_STOP_CALLBACK = ?fn ([*c]FMOD_OUTPUT_STATE) callconv(.C) FMOD_RESULT;
pub const FMOD_OUTPUT_CLOSE_CALLBACK = ?fn ([*c]FMOD_OUTPUT_STATE) callconv(.C) FMOD_RESULT;
pub const FMOD_OUTPUT_UPDATE_CALLBACK = ?fn ([*c]FMOD_OUTPUT_STATE) callconv(.C) FMOD_RESULT;
pub const FMOD_OUTPUT_GETHANDLE_CALLBACK = ?fn ([*c]FMOD_OUTPUT_STATE, [*c]?*c_void) callconv(.C) FMOD_RESULT;
pub const FMOD_OUTPUT_GETPOSITION_CALLBACK = ?fn ([*c]FMOD_OUTPUT_STATE, [*c]c_uint) callconv(.C) FMOD_RESULT;
pub const FMOD_OUTPUT_LOCK_CALLBACK = ?fn ([*c]FMOD_OUTPUT_STATE, c_uint, c_uint, [*c]?*c_void, [*c]?*c_void, [*c]c_uint, [*c]c_uint) callconv(.C) FMOD_RESULT;
pub const FMOD_OUTPUT_UNLOCK_CALLBACK = ?fn ([*c]FMOD_OUTPUT_STATE, ?*c_void, ?*c_void, c_uint, c_uint) callconv(.C) FMOD_RESULT;
pub const FMOD_OUTPUT_MIXER_CALLBACK = ?fn ([*c]FMOD_OUTPUT_STATE) callconv(.C) FMOD_RESULT;
pub const FMOD_OUTPUT_OBJECT3DGETINFO_CALLBACK = ?fn ([*c]FMOD_OUTPUT_STATE, [*c]c_int) callconv(.C) FMOD_RESULT;
pub const FMOD_OUTPUT_OBJECT3DALLOC_CALLBACK = ?fn ([*c]FMOD_OUTPUT_STATE, [*c]?*c_void) callconv(.C) FMOD_RESULT;
pub const FMOD_OUTPUT_OBJECT3DFREE_CALLBACK = ?fn ([*c]FMOD_OUTPUT_STATE, ?*c_void) callconv(.C) FMOD_RESULT;
pub const FMOD_OUTPUT_OBJECT3DUPDATE_CALLBACK = ?fn ([*c]FMOD_OUTPUT_STATE, ?*c_void, [*c]const FMOD_OUTPUT_OBJECT3DINFO) callconv(.C) FMOD_RESULT;
pub const FMOD_OUTPUT_OPENPORT_CALLBACK = ?fn ([*c]FMOD_OUTPUT_STATE, FMOD_PORT_TYPE, FMOD_PORT_INDEX, [*c]c_int, [*c]c_int, [*c]c_int, [*c]FMOD_SOUND_FORMAT) callconv(.C) FMOD_RESULT;
pub const FMOD_OUTPUT_CLOSEPORT_CALLBACK = ?fn ([*c]FMOD_OUTPUT_STATE, c_int) callconv(.C) FMOD_RESULT;
pub const FMOD_OUTPUT_DEVICELISTCHANGED_CALLBACK = ?fn ([*c]FMOD_OUTPUT_STATE) callconv(.C) FMOD_RESULT;
pub const struct_FMOD_OUTPUT_DESCRIPTION = extern struct {
apiversion: c_uint,
name: [*c]const u8,
version: c_uint,
method: FMOD_OUTPUT_METHOD,
getnumdrivers: FMOD_OUTPUT_GETNUMDRIVERS_CALLBACK,
getdriverinfo: FMOD_OUTPUT_GETDRIVERINFO_CALLBACK,
init: FMOD_OUTPUT_INIT_CALLBACK,
start: FMOD_OUTPUT_START_CALLBACK,
stop: FMOD_OUTPUT_STOP_CALLBACK,
close: FMOD_OUTPUT_CLOSE_CALLBACK,
update: FMOD_OUTPUT_UPDATE_CALLBACK,
gethandle: FMOD_OUTPUT_GETHANDLE_CALLBACK,
getposition: FMOD_OUTPUT_GETPOSITION_CALLBACK,
lock: FMOD_OUTPUT_LOCK_CALLBACK,
unlock: FMOD_OUTPUT_UNLOCK_CALLBACK,
mixer: FMOD_OUTPUT_MIXER_CALLBACK,
object3dgetinfo: FMOD_OUTPUT_OBJECT3DGETINFO_CALLBACK,
object3dalloc: FMOD_OUTPUT_OBJECT3DALLOC_CALLBACK,
object3dfree: FMOD_OUTPUT_OBJECT3DFREE_CALLBACK,
object3dupdate: FMOD_OUTPUT_OBJECT3DUPDATE_CALLBACK,
openport: FMOD_OUTPUT_OPENPORT_CALLBACK,
closeport: FMOD_OUTPUT_CLOSEPORT_CALLBACK,
devicelistchanged: FMOD_OUTPUT_DEVICELISTCHANGED_CALLBACK,
};
pub const FMOD_OUTPUT_DESCRIPTION = struct_FMOD_OUTPUT_DESCRIPTION;
pub extern fn FMOD_Memory_Initialize(poolmem: ?*c_void, poollen: c_int, useralloc: FMOD_MEMORY_ALLOC_CALLBACK, userrealloc: FMOD_MEMORY_REALLOC_CALLBACK, userfree: FMOD_MEMORY_FREE_CALLBACK, memtypeflags: FMOD_MEMORY_TYPE) FMOD_RESULT;
pub extern fn FMOD_Memory_GetStats(currentalloced: [*c]c_int, maxalloced: [*c]c_int, blocking: FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Debug_Initialize(flags: FMOD_DEBUG_FLAGS, mode: FMOD_DEBUG_MODE, callback: FMOD_DEBUG_CALLBACK, filename: [*c]const u8) FMOD_RESULT;
pub extern fn FMOD_File_SetDiskBusy(busy: c_int) FMOD_RESULT;
pub extern fn FMOD_File_GetDiskBusy(busy: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Thread_SetAttributes(type: FMOD_THREAD_TYPE, affinity: FMOD_THREAD_AFFINITY, priority: FMOD_THREAD_PRIORITY, stacksize: FMOD_THREAD_STACK_SIZE) FMOD_RESULT;
pub extern fn FMOD_System_Create(system: [*c]?*FMOD_SYSTEM) FMOD_RESULT;
pub extern fn FMOD_System_Release(system: ?*FMOD_SYSTEM) FMOD_RESULT;
pub extern fn FMOD_System_SetOutput(system: ?*FMOD_SYSTEM, output: FMOD_OUTPUTTYPE) FMOD_RESULT;
pub extern fn FMOD_System_GetOutput(system: ?*FMOD_SYSTEM, output: [*c]FMOD_OUTPUTTYPE) FMOD_RESULT;
pub extern fn FMOD_System_GetNumDrivers(system: ?*FMOD_SYSTEM, numdrivers: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_System_GetDriverInfo(system: ?*FMOD_SYSTEM, id: c_int, name: [*c]u8, namelen: c_int, guid: [*c]FMOD_GUID, systemrate: [*c]c_int, speakermode: [*c]FMOD_SPEAKERMODE, speakermodechannels: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_System_SetDriver(system: ?*FMOD_SYSTEM, driver: c_int) FMOD_RESULT;
pub extern fn FMOD_System_GetDriver(system: ?*FMOD_SYSTEM, driver: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_System_SetSoftwareChannels(system: ?*FMOD_SYSTEM, numsoftwarechannels: c_int) FMOD_RESULT;
pub extern fn FMOD_System_GetSoftwareChannels(system: ?*FMOD_SYSTEM, numsoftwarechannels: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_System_SetSoftwareFormat(system: ?*FMOD_SYSTEM, samplerate: c_int, speakermode: FMOD_SPEAKERMODE, numrawspeakers: c_int) FMOD_RESULT;
pub extern fn FMOD_System_GetSoftwareFormat(system: ?*FMOD_SYSTEM, samplerate: [*c]c_int, speakermode: [*c]FMOD_SPEAKERMODE, numrawspeakers: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_System_SetDSPBufferSize(system: ?*FMOD_SYSTEM, bufferlength: c_uint, numbuffers: c_int) FMOD_RESULT;
pub extern fn FMOD_System_GetDSPBufferSize(system: ?*FMOD_SYSTEM, bufferlength: [*c]c_uint, numbuffers: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_System_SetFileSystem(system: ?*FMOD_SYSTEM, useropen: FMOD_FILE_OPEN_CALLBACK, userclose: FMOD_FILE_CLOSE_CALLBACK, userread: FMOD_FILE_READ_CALLBACK, userseek: FMOD_FILE_SEEK_CALLBACK, userasyncread: FMOD_FILE_ASYNCREAD_CALLBACK, userasynccancel: FMOD_FILE_ASYNCCANCEL_CALLBACK, blockalign: c_int) FMOD_RESULT;
pub extern fn FMOD_System_AttachFileSystem(system: ?*FMOD_SYSTEM, useropen: FMOD_FILE_OPEN_CALLBACK, userclose: FMOD_FILE_CLOSE_CALLBACK, userread: FMOD_FILE_READ_CALLBACK, userseek: FMOD_FILE_SEEK_CALLBACK) FMOD_RESULT;
pub extern fn FMOD_System_SetAdvancedSettings(system: ?*FMOD_SYSTEM, settings: [*c]FMOD_ADVANCEDSETTINGS) FMOD_RESULT;
pub extern fn FMOD_System_GetAdvancedSettings(system: ?*FMOD_SYSTEM, settings: [*c]FMOD_ADVANCEDSETTINGS) FMOD_RESULT;
pub extern fn FMOD_System_SetCallback(system: ?*FMOD_SYSTEM, callback: FMOD_SYSTEM_CALLBACK, callbackmask: FMOD_SYSTEM_CALLBACK_TYPE) FMOD_RESULT;
pub extern fn FMOD_System_SetPluginPath(system: ?*FMOD_SYSTEM, path: [*c]const u8) FMOD_RESULT;
pub extern fn FMOD_System_LoadPlugin(system: ?*FMOD_SYSTEM, filename: [*c]const u8, handle: [*c]c_uint, priority: c_uint) FMOD_RESULT;
pub extern fn FMOD_System_UnloadPlugin(system: ?*FMOD_SYSTEM, handle: c_uint) FMOD_RESULT;
pub extern fn FMOD_System_GetNumNestedPlugins(system: ?*FMOD_SYSTEM, handle: c_uint, count: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_System_GetNestedPlugin(system: ?*FMOD_SYSTEM, handle: c_uint, index: c_int, nestedhandle: [*c]c_uint) FMOD_RESULT;
pub extern fn FMOD_System_GetNumPlugins(system: ?*FMOD_SYSTEM, plugintype: FMOD_PLUGINTYPE, numplugins: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_System_GetPluginHandle(system: ?*FMOD_SYSTEM, plugintype: FMOD_PLUGINTYPE, index: c_int, handle: [*c]c_uint) FMOD_RESULT;
pub extern fn FMOD_System_GetPluginInfo(system: ?*FMOD_SYSTEM, handle: c_uint, plugintype: [*c]FMOD_PLUGINTYPE, name: [*c]u8, namelen: c_int, version: [*c]c_uint) FMOD_RESULT;
pub extern fn FMOD_System_SetOutputByPlugin(system: ?*FMOD_SYSTEM, handle: c_uint) FMOD_RESULT;
pub extern fn FMOD_System_GetOutputByPlugin(system: ?*FMOD_SYSTEM, handle: [*c]c_uint) FMOD_RESULT;
pub extern fn FMOD_System_CreateDSPByPlugin(system: ?*FMOD_SYSTEM, handle: c_uint, dsp: [*c]?*FMOD_DSP) FMOD_RESULT;
pub extern fn FMOD_System_GetDSPInfoByPlugin(system: ?*FMOD_SYSTEM, handle: c_uint, description: [*c][*c]const FMOD_DSP_DESCRIPTION) FMOD_RESULT;
pub extern fn FMOD_System_RegisterCodec(system: ?*FMOD_SYSTEM, description: [*c]FMOD_CODEC_DESCRIPTION, handle: [*c]c_uint, priority: c_uint) FMOD_RESULT;
pub extern fn FMOD_System_RegisterDSP(system: ?*FMOD_SYSTEM, description: [*c]const FMOD_DSP_DESCRIPTION, handle: [*c]c_uint) FMOD_RESULT;
pub extern fn FMOD_System_RegisterOutput(system: ?*FMOD_SYSTEM, description: [*c]const FMOD_OUTPUT_DESCRIPTION, handle: [*c]c_uint) FMOD_RESULT;
pub extern fn FMOD_System_Init(system: ?*FMOD_SYSTEM, maxchannels: c_int, flags: FMOD_INITFLAGS, extradriverdata: ?*c_void) FMOD_RESULT;
pub extern fn FMOD_System_Close(system: ?*FMOD_SYSTEM) FMOD_RESULT;
pub extern fn FMOD_System_Update(system: ?*FMOD_SYSTEM) FMOD_RESULT;
pub extern fn FMOD_System_SetSpeakerPosition(system: ?*FMOD_SYSTEM, speaker: FMOD_SPEAKER, x: f32, y: f32, active: FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_System_GetSpeakerPosition(system: ?*FMOD_SYSTEM, speaker: FMOD_SPEAKER, x: [*c]f32, y: [*c]f32, active: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_System_SetStreamBufferSize(system: ?*FMOD_SYSTEM, filebuffersize: c_uint, filebuffersizetype: FMOD_TIMEUNIT) FMOD_RESULT;
pub extern fn FMOD_System_GetStreamBufferSize(system: ?*FMOD_SYSTEM, filebuffersize: [*c]c_uint, filebuffersizetype: [*c]FMOD_TIMEUNIT) FMOD_RESULT;
pub extern fn FMOD_System_Set3DSettings(system: ?*FMOD_SYSTEM, dopplerscale: f32, distancefactor: f32, rolloffscale: f32) FMOD_RESULT;
pub extern fn FMOD_System_Get3DSettings(system: ?*FMOD_SYSTEM, dopplerscale: [*c]f32, distancefactor: [*c]f32, rolloffscale: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_System_Set3DNumListeners(system: ?*FMOD_SYSTEM, numlisteners: c_int) FMOD_RESULT;
pub extern fn FMOD_System_Get3DNumListeners(system: ?*FMOD_SYSTEM, numlisteners: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_System_Set3DListenerAttributes(system: ?*FMOD_SYSTEM, listener: c_int, pos: [*c]const FMOD_VECTOR, vel: [*c]const FMOD_VECTOR, forward: [*c]const FMOD_VECTOR, up: [*c]const FMOD_VECTOR) FMOD_RESULT;
pub extern fn FMOD_System_Get3DListenerAttributes(system: ?*FMOD_SYSTEM, listener: c_int, pos: [*c]FMOD_VECTOR, vel: [*c]FMOD_VECTOR, forward: [*c]FMOD_VECTOR, up: [*c]FMOD_VECTOR) FMOD_RESULT;
pub extern fn FMOD_System_MixerSuspend(system: ?*FMOD_SYSTEM) FMOD_RESULT;
pub extern fn FMOD_System_MixerResume(system: ?*FMOD_SYSTEM) FMOD_RESULT;
pub extern fn FMOD_System_GetDefaultMixMatrix(system: ?*FMOD_SYSTEM, sourcespeakermode: FMOD_SPEAKERMODE, targetspeakermode: FMOD_SPEAKERMODE, matrix: [*c]f32, matrixhop: c_int) FMOD_RESULT;
pub extern fn FMOD_System_GetSpeakerModeChannels(system: ?*FMOD_SYSTEM, mode: FMOD_SPEAKERMODE, channels: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_System_GetVersion(system: ?*FMOD_SYSTEM, version: [*c]c_uint) FMOD_RESULT;
pub extern fn FMOD_System_GetOutputHandle(system: ?*FMOD_SYSTEM, handle: [*c]?*c_void) FMOD_RESULT;
pub extern fn FMOD_System_GetChannelsPlaying(system: ?*FMOD_SYSTEM, channels: [*c]c_int, realchannels: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_System_GetCPUUsage(system: ?*FMOD_SYSTEM, dsp: [*c]f32, stream: [*c]f32, geometry: [*c]f32, update: [*c]f32, total: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_System_GetCPUUsageEx(system: ?*FMOD_SYSTEM, convolutionThread1: [*c]f32, convolutionThread2: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_System_GetFileUsage(system: ?*FMOD_SYSTEM, sampleBytesRead: [*c]c_longlong, streamBytesRead: [*c]c_longlong, otherBytesRead: [*c]c_longlong) FMOD_RESULT;
pub extern fn FMOD_System_CreateSound(system: ?*FMOD_SYSTEM, name_or_data: [*c]const u8, mode: FMOD_MODE, exinfo: [*c]FMOD_CREATESOUNDEXINFO, sound: [*c]?*FMOD_SOUND) FMOD_RESULT;
pub extern fn FMOD_System_CreateStream(system: ?*FMOD_SYSTEM, name_or_data: [*c]const u8, mode: FMOD_MODE, exinfo: [*c]FMOD_CREATESOUNDEXINFO, sound: [*c]?*FMOD_SOUND) FMOD_RESULT;
pub extern fn FMOD_System_CreateDSP(system: ?*FMOD_SYSTEM, description: [*c]const FMOD_DSP_DESCRIPTION, dsp: [*c]?*FMOD_DSP) FMOD_RESULT;
pub extern fn FMOD_System_CreateDSPByType(system: ?*FMOD_SYSTEM, type: FMOD_DSP_TYPE, dsp: [*c]?*FMOD_DSP) FMOD_RESULT;
pub extern fn FMOD_System_CreateChannelGroup(system: ?*FMOD_SYSTEM, name: [*c]const u8, channelgroup: [*c]?*FMOD_CHANNELGROUP) FMOD_RESULT;
pub extern fn FMOD_System_CreateSoundGroup(system: ?*FMOD_SYSTEM, name: [*c]const u8, soundgroup: [*c]?*FMOD_SOUNDGROUP) FMOD_RESULT;
pub extern fn FMOD_System_CreateReverb3D(system: ?*FMOD_SYSTEM, reverb: [*c]?*FMOD_REVERB3D) FMOD_RESULT;
pub extern fn FMOD_System_PlaySound(system: ?*FMOD_SYSTEM, sound: ?*FMOD_SOUND, channelgroup: ?*FMOD_CHANNELGROUP, paused: FMOD_BOOL, channel: [*c]?*FMOD_CHANNEL) FMOD_RESULT;
pub extern fn FMOD_System_PlayDSP(system: ?*FMOD_SYSTEM, dsp: ?*FMOD_DSP, channelgroup: ?*FMOD_CHANNELGROUP, paused: FMOD_BOOL, channel: [*c]?*FMOD_CHANNEL) FMOD_RESULT;
pub extern fn FMOD_System_GetChannel(system: ?*FMOD_SYSTEM, channelid: c_int, channel: [*c]?*FMOD_CHANNEL) FMOD_RESULT;
pub extern fn FMOD_System_GetDSPInfoByType(system: ?*FMOD_SYSTEM, type: FMOD_DSP_TYPE, description: [*c][*c]const FMOD_DSP_DESCRIPTION) FMOD_RESULT;
pub extern fn FMOD_System_GetMasterChannelGroup(system: ?*FMOD_SYSTEM, channelgroup: [*c]?*FMOD_CHANNELGROUP) FMOD_RESULT;
pub extern fn FMOD_System_GetMasterSoundGroup(system: ?*FMOD_SYSTEM, soundgroup: [*c]?*FMOD_SOUNDGROUP) FMOD_RESULT;
pub extern fn FMOD_System_AttachChannelGroupToPort(system: ?*FMOD_SYSTEM, portType: FMOD_PORT_TYPE, portIndex: FMOD_PORT_INDEX, channelgroup: ?*FMOD_CHANNELGROUP, passThru: FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_System_DetachChannelGroupFromPort(system: ?*FMOD_SYSTEM, channelgroup: ?*FMOD_CHANNELGROUP) FMOD_RESULT;
pub extern fn FMOD_System_SetReverbProperties(system: ?*FMOD_SYSTEM, instance: c_int, prop: [*c]const FMOD_REVERB_PROPERTIES) FMOD_RESULT;
pub extern fn FMOD_System_GetReverbProperties(system: ?*FMOD_SYSTEM, instance: c_int, prop: [*c]FMOD_REVERB_PROPERTIES) FMOD_RESULT;
pub extern fn FMOD_System_LockDSP(system: ?*FMOD_SYSTEM) FMOD_RESULT;
pub extern fn FMOD_System_UnlockDSP(system: ?*FMOD_SYSTEM) FMOD_RESULT;
pub extern fn FMOD_System_GetRecordNumDrivers(system: ?*FMOD_SYSTEM, numdrivers: [*c]c_int, numconnected: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_System_GetRecordDriverInfo(system: ?*FMOD_SYSTEM, id: c_int, name: [*c]u8, namelen: c_int, guid: [*c]FMOD_GUID, systemrate: [*c]c_int, speakermode: [*c]FMOD_SPEAKERMODE, speakermodechannels: [*c]c_int, state: [*c]FMOD_DRIVER_STATE) FMOD_RESULT;
pub extern fn FMOD_System_GetRecordPosition(system: ?*FMOD_SYSTEM, id: c_int, position: [*c]c_uint) FMOD_RESULT;
pub extern fn FMOD_System_RecordStart(system: ?*FMOD_SYSTEM, id: c_int, sound: ?*FMOD_SOUND, loop: FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_System_RecordStop(system: ?*FMOD_SYSTEM, id: c_int) FMOD_RESULT;
pub extern fn FMOD_System_IsRecording(system: ?*FMOD_SYSTEM, id: c_int, recording: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_System_CreateGeometry(system: ?*FMOD_SYSTEM, maxpolygons: c_int, maxvertices: c_int, geometry: [*c]?*FMOD_GEOMETRY) FMOD_RESULT;
pub extern fn FMOD_System_SetGeometrySettings(system: ?*FMOD_SYSTEM, maxworldsize: f32) FMOD_RESULT;
pub extern fn FMOD_System_GetGeometrySettings(system: ?*FMOD_SYSTEM, maxworldsize: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_System_LoadGeometry(system: ?*FMOD_SYSTEM, data: ?*const c_void, datasize: c_int, geometry: [*c]?*FMOD_GEOMETRY) FMOD_RESULT;
pub extern fn FMOD_System_GetGeometryOcclusion(system: ?*FMOD_SYSTEM, listener: [*c]const FMOD_VECTOR, source: [*c]const FMOD_VECTOR, direct: [*c]f32, reverb: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_System_SetNetworkProxy(system: ?*FMOD_SYSTEM, proxy: [*c]const u8) FMOD_RESULT;
pub extern fn FMOD_System_GetNetworkProxy(system: ?*FMOD_SYSTEM, proxy: [*c]u8, proxylen: c_int) FMOD_RESULT;
pub extern fn FMOD_System_SetNetworkTimeout(system: ?*FMOD_SYSTEM, timeout: c_int) FMOD_RESULT;
pub extern fn FMOD_System_GetNetworkTimeout(system: ?*FMOD_SYSTEM, timeout: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_System_SetUserData(system: ?*FMOD_SYSTEM, userdata: ?*c_void) FMOD_RESULT;
pub extern fn FMOD_System_GetUserData(system: ?*FMOD_SYSTEM, userdata: [*c]?*c_void) FMOD_RESULT;
pub extern fn FMOD_Sound_Release(sound: ?*FMOD_SOUND) FMOD_RESULT;
pub extern fn FMOD_Sound_GetSystemObject(sound: ?*FMOD_SOUND, system: [*c]?*FMOD_SYSTEM) FMOD_RESULT;
pub extern fn FMOD_Sound_Lock(sound: ?*FMOD_SOUND, offset: c_uint, length: c_uint, ptr1: [*c]?*c_void, ptr2: [*c]?*c_void, len1: [*c]c_uint, len2: [*c]c_uint) FMOD_RESULT;
pub extern fn FMOD_Sound_Unlock(sound: ?*FMOD_SOUND, ptr1: ?*c_void, ptr2: ?*c_void, len1: c_uint, len2: c_uint) FMOD_RESULT;
pub extern fn FMOD_Sound_SetDefaults(sound: ?*FMOD_SOUND, frequency: f32, priority: c_int) FMOD_RESULT;
pub extern fn FMOD_Sound_GetDefaults(sound: ?*FMOD_SOUND, frequency: [*c]f32, priority: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Sound_Set3DMinMaxDistance(sound: ?*FMOD_SOUND, min: f32, max: f32) FMOD_RESULT;
pub extern fn FMOD_Sound_Get3DMinMaxDistance(sound: ?*FMOD_SOUND, min: [*c]f32, max: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Sound_Set3DConeSettings(sound: ?*FMOD_SOUND, insideconeangle: f32, outsideconeangle: f32, outsidevolume: f32) FMOD_RESULT;
pub extern fn FMOD_Sound_Get3DConeSettings(sound: ?*FMOD_SOUND, insideconeangle: [*c]f32, outsideconeangle: [*c]f32, outsidevolume: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Sound_Set3DCustomRolloff(sound: ?*FMOD_SOUND, points: [*c]FMOD_VECTOR, numpoints: c_int) FMOD_RESULT;
pub extern fn FMOD_Sound_Get3DCustomRolloff(sound: ?*FMOD_SOUND, points: [*c][*c]FMOD_VECTOR, numpoints: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Sound_GetSubSound(sound: ?*FMOD_SOUND, index: c_int, subsound: [*c]?*FMOD_SOUND) FMOD_RESULT;
pub extern fn FMOD_Sound_GetSubSoundParent(sound: ?*FMOD_SOUND, parentsound: [*c]?*FMOD_SOUND) FMOD_RESULT;
pub extern fn FMOD_Sound_GetName(sound: ?*FMOD_SOUND, name: [*c]u8, namelen: c_int) FMOD_RESULT;
pub extern fn FMOD_Sound_GetLength(sound: ?*FMOD_SOUND, length: [*c]c_uint, lengthtype: FMOD_TIMEUNIT) FMOD_RESULT;
pub extern fn FMOD_Sound_GetFormat(sound: ?*FMOD_SOUND, type: [*c]FMOD_SOUND_TYPE, format: [*c]FMOD_SOUND_FORMAT, channels: [*c]c_int, bits: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Sound_GetNumSubSounds(sound: ?*FMOD_SOUND, numsubsounds: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Sound_GetNumTags(sound: ?*FMOD_SOUND, numtags: [*c]c_int, numtagsupdated: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Sound_GetTag(sound: ?*FMOD_SOUND, name: [*c]const u8, index: c_int, tag: [*c]FMOD_TAG) FMOD_RESULT;
pub extern fn FMOD_Sound_GetOpenState(sound: ?*FMOD_SOUND, openstate: [*c]FMOD_OPENSTATE, percentbuffered: [*c]c_uint, starving: [*c]FMOD_BOOL, diskbusy: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Sound_ReadData(sound: ?*FMOD_SOUND, buffer: ?*c_void, length: c_uint, read: [*c]c_uint) FMOD_RESULT;
pub extern fn FMOD_Sound_SeekData(sound: ?*FMOD_SOUND, pcm: c_uint) FMOD_RESULT;
pub extern fn FMOD_Sound_SetSoundGroup(sound: ?*FMOD_SOUND, soundgroup: ?*FMOD_SOUNDGROUP) FMOD_RESULT;
pub extern fn FMOD_Sound_GetSoundGroup(sound: ?*FMOD_SOUND, soundgroup: [*c]?*FMOD_SOUNDGROUP) FMOD_RESULT;
pub extern fn FMOD_Sound_GetNumSyncPoints(sound: ?*FMOD_SOUND, numsyncpoints: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Sound_GetSyncPoint(sound: ?*FMOD_SOUND, index: c_int, point: [*c]?*FMOD_SYNCPOINT) FMOD_RESULT;
pub extern fn FMOD_Sound_GetSyncPointInfo(sound: ?*FMOD_SOUND, point: ?*FMOD_SYNCPOINT, name: [*c]u8, namelen: c_int, offset: [*c]c_uint, offsettype: FMOD_TIMEUNIT) FMOD_RESULT;
pub extern fn FMOD_Sound_AddSyncPoint(sound: ?*FMOD_SOUND, offset: c_uint, offsettype: FMOD_TIMEUNIT, name: [*c]const u8, point: [*c]?*FMOD_SYNCPOINT) FMOD_RESULT;
pub extern fn FMOD_Sound_DeleteSyncPoint(sound: ?*FMOD_SOUND, point: ?*FMOD_SYNCPOINT) FMOD_RESULT;
pub extern fn FMOD_Sound_SetMode(sound: ?*FMOD_SOUND, mode: FMOD_MODE) FMOD_RESULT;
pub extern fn FMOD_Sound_GetMode(sound: ?*FMOD_SOUND, mode: [*c]FMOD_MODE) FMOD_RESULT;
pub extern fn FMOD_Sound_SetLoopCount(sound: ?*FMOD_SOUND, loopcount: c_int) FMOD_RESULT;
pub extern fn FMOD_Sound_GetLoopCount(sound: ?*FMOD_SOUND, loopcount: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Sound_SetLoopPoints(sound: ?*FMOD_SOUND, loopstart: c_uint, loopstarttype: FMOD_TIMEUNIT, loopend: c_uint, loopendtype: FMOD_TIMEUNIT) FMOD_RESULT;
pub extern fn FMOD_Sound_GetLoopPoints(sound: ?*FMOD_SOUND, loopstart: [*c]c_uint, loopstarttype: FMOD_TIMEUNIT, loopend: [*c]c_uint, loopendtype: FMOD_TIMEUNIT) FMOD_RESULT;
pub extern fn FMOD_Sound_GetMusicNumChannels(sound: ?*FMOD_SOUND, numchannels: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Sound_SetMusicChannelVolume(sound: ?*FMOD_SOUND, channel: c_int, volume: f32) FMOD_RESULT;
pub extern fn FMOD_Sound_GetMusicChannelVolume(sound: ?*FMOD_SOUND, channel: c_int, volume: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Sound_SetMusicSpeed(sound: ?*FMOD_SOUND, speed: f32) FMOD_RESULT;
pub extern fn FMOD_Sound_GetMusicSpeed(sound: ?*FMOD_SOUND, speed: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Sound_SetUserData(sound: ?*FMOD_SOUND, userdata: ?*c_void) FMOD_RESULT;
pub extern fn FMOD_Sound_GetUserData(sound: ?*FMOD_SOUND, userdata: [*c]?*c_void) FMOD_RESULT;
pub extern fn FMOD_Channel_GetSystemObject(channel: ?*FMOD_CHANNEL, system: [*c]?*FMOD_SYSTEM) FMOD_RESULT;
pub extern fn FMOD_Channel_Stop(channel: ?*FMOD_CHANNEL) FMOD_RESULT;
pub extern fn FMOD_Channel_SetPaused(channel: ?*FMOD_CHANNEL, paused: FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Channel_GetPaused(channel: ?*FMOD_CHANNEL, paused: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Channel_SetVolume(channel: ?*FMOD_CHANNEL, volume: f32) FMOD_RESULT;
pub extern fn FMOD_Channel_GetVolume(channel: ?*FMOD_CHANNEL, volume: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Channel_SetVolumeRamp(channel: ?*FMOD_CHANNEL, ramp: FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Channel_GetVolumeRamp(channel: ?*FMOD_CHANNEL, ramp: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Channel_GetAudibility(channel: ?*FMOD_CHANNEL, audibility: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Channel_SetPitch(channel: ?*FMOD_CHANNEL, pitch: f32) FMOD_RESULT;
pub extern fn FMOD_Channel_GetPitch(channel: ?*FMOD_CHANNEL, pitch: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Channel_SetMute(channel: ?*FMOD_CHANNEL, mute: FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Channel_GetMute(channel: ?*FMOD_CHANNEL, mute: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Channel_SetReverbProperties(channel: ?*FMOD_CHANNEL, instance: c_int, wet: f32) FMOD_RESULT;
pub extern fn FMOD_Channel_GetReverbProperties(channel: ?*FMOD_CHANNEL, instance: c_int, wet: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Channel_SetLowPassGain(channel: ?*FMOD_CHANNEL, gain: f32) FMOD_RESULT;
pub extern fn FMOD_Channel_GetLowPassGain(channel: ?*FMOD_CHANNEL, gain: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Channel_SetMode(channel: ?*FMOD_CHANNEL, mode: FMOD_MODE) FMOD_RESULT;
pub extern fn FMOD_Channel_GetMode(channel: ?*FMOD_CHANNEL, mode: [*c]FMOD_MODE) FMOD_RESULT;
pub extern fn FMOD_Channel_SetCallback(channel: ?*FMOD_CHANNEL, callback: FMOD_CHANNELCONTROL_CALLBACK) FMOD_RESULT;
pub extern fn FMOD_Channel_IsPlaying(channel: ?*FMOD_CHANNEL, isplaying: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Channel_SetPan(channel: ?*FMOD_CHANNEL, pan: f32) FMOD_RESULT;
pub extern fn FMOD_Channel_SetMixLevelsOutput(channel: ?*FMOD_CHANNEL, frontleft: f32, frontright: f32, center: f32, lfe: f32, surroundleft: f32, surroundright: f32, backleft: f32, backright: f32) FMOD_RESULT;
pub extern fn FMOD_Channel_SetMixLevelsInput(channel: ?*FMOD_CHANNEL, levels: [*c]f32, numlevels: c_int) FMOD_RESULT;
pub extern fn FMOD_Channel_SetMixMatrix(channel: ?*FMOD_CHANNEL, matrix: [*c]f32, outchannels: c_int, inchannels: c_int, inchannel_hop: c_int) FMOD_RESULT;
pub extern fn FMOD_Channel_GetMixMatrix(channel: ?*FMOD_CHANNEL, matrix: [*c]f32, outchannels: [*c]c_int, inchannels: [*c]c_int, inchannel_hop: c_int) FMOD_RESULT;
pub extern fn FMOD_Channel_GetDSPClock(channel: ?*FMOD_CHANNEL, dspclock: [*c]c_ulonglong, parentclock: [*c]c_ulonglong) FMOD_RESULT;
pub extern fn FMOD_Channel_SetDelay(channel: ?*FMOD_CHANNEL, dspclock_start: c_ulonglong, dspclock_end: c_ulonglong, stopchannels: FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Channel_GetDelay(channel: ?*FMOD_CHANNEL, dspclock_start: [*c]c_ulonglong, dspclock_end: [*c]c_ulonglong, stopchannels: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Channel_AddFadePoint(channel: ?*FMOD_CHANNEL, dspclock: c_ulonglong, volume: f32) FMOD_RESULT;
pub extern fn FMOD_Channel_SetFadePointRamp(channel: ?*FMOD_CHANNEL, dspclock: c_ulonglong, volume: f32) FMOD_RESULT;
pub extern fn FMOD_Channel_RemoveFadePoints(channel: ?*FMOD_CHANNEL, dspclock_start: c_ulonglong, dspclock_end: c_ulonglong) FMOD_RESULT;
pub extern fn FMOD_Channel_GetFadePoints(channel: ?*FMOD_CHANNEL, numpoints: [*c]c_uint, point_dspclock: [*c]c_ulonglong, point_volume: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Channel_GetDSP(channel: ?*FMOD_CHANNEL, index: c_int, dsp: [*c]?*FMOD_DSP) FMOD_RESULT;
pub extern fn FMOD_Channel_AddDSP(channel: ?*FMOD_CHANNEL, index: c_int, dsp: ?*FMOD_DSP) FMOD_RESULT;
pub extern fn FMOD_Channel_RemoveDSP(channel: ?*FMOD_CHANNEL, dsp: ?*FMOD_DSP) FMOD_RESULT;
pub extern fn FMOD_Channel_GetNumDSPs(channel: ?*FMOD_CHANNEL, numdsps: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Channel_SetDSPIndex(channel: ?*FMOD_CHANNEL, dsp: ?*FMOD_DSP, index: c_int) FMOD_RESULT;
pub extern fn FMOD_Channel_GetDSPIndex(channel: ?*FMOD_CHANNEL, dsp: ?*FMOD_DSP, index: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Channel_Set3DAttributes(channel: ?*FMOD_CHANNEL, pos: [*c]const FMOD_VECTOR, vel: [*c]const FMOD_VECTOR) FMOD_RESULT;
pub extern fn FMOD_Channel_Get3DAttributes(channel: ?*FMOD_CHANNEL, pos: [*c]FMOD_VECTOR, vel: [*c]FMOD_VECTOR) FMOD_RESULT;
pub extern fn FMOD_Channel_Set3DMinMaxDistance(channel: ?*FMOD_CHANNEL, mindistance: f32, maxdistance: f32) FMOD_RESULT;
pub extern fn FMOD_Channel_Get3DMinMaxDistance(channel: ?*FMOD_CHANNEL, mindistance: [*c]f32, maxdistance: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Channel_Set3DConeSettings(channel: ?*FMOD_CHANNEL, insideconeangle: f32, outsideconeangle: f32, outsidevolume: f32) FMOD_RESULT;
pub extern fn FMOD_Channel_Get3DConeSettings(channel: ?*FMOD_CHANNEL, insideconeangle: [*c]f32, outsideconeangle: [*c]f32, outsidevolume: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Channel_Set3DConeOrientation(channel: ?*FMOD_CHANNEL, orientation: [*c]FMOD_VECTOR) FMOD_RESULT;
pub extern fn FMOD_Channel_Get3DConeOrientation(channel: ?*FMOD_CHANNEL, orientation: [*c]FMOD_VECTOR) FMOD_RESULT;
pub extern fn FMOD_Channel_Set3DCustomRolloff(channel: ?*FMOD_CHANNEL, points: [*c]FMOD_VECTOR, numpoints: c_int) FMOD_RESULT;
pub extern fn FMOD_Channel_Get3DCustomRolloff(channel: ?*FMOD_CHANNEL, points: [*c][*c]FMOD_VECTOR, numpoints: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Channel_Set3DOcclusion(channel: ?*FMOD_CHANNEL, directocclusion: f32, reverbocclusion: f32) FMOD_RESULT;
pub extern fn FMOD_Channel_Get3DOcclusion(channel: ?*FMOD_CHANNEL, directocclusion: [*c]f32, reverbocclusion: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Channel_Set3DSpread(channel: ?*FMOD_CHANNEL, angle: f32) FMOD_RESULT;
pub extern fn FMOD_Channel_Get3DSpread(channel: ?*FMOD_CHANNEL, angle: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Channel_Set3DLevel(channel: ?*FMOD_CHANNEL, level: f32) FMOD_RESULT;
pub extern fn FMOD_Channel_Get3DLevel(channel: ?*FMOD_CHANNEL, level: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Channel_Set3DDopplerLevel(channel: ?*FMOD_CHANNEL, level: f32) FMOD_RESULT;
pub extern fn FMOD_Channel_Get3DDopplerLevel(channel: ?*FMOD_CHANNEL, level: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Channel_Set3DDistanceFilter(channel: ?*FMOD_CHANNEL, custom: FMOD_BOOL, customLevel: f32, centerFreq: f32) FMOD_RESULT;
pub extern fn FMOD_Channel_Get3DDistanceFilter(channel: ?*FMOD_CHANNEL, custom: [*c]FMOD_BOOL, customLevel: [*c]f32, centerFreq: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Channel_SetUserData(channel: ?*FMOD_CHANNEL, userdata: ?*c_void) FMOD_RESULT;
pub extern fn FMOD_Channel_GetUserData(channel: ?*FMOD_CHANNEL, userdata: [*c]?*c_void) FMOD_RESULT;
pub extern fn FMOD_Channel_SetFrequency(channel: ?*FMOD_CHANNEL, frequency: f32) FMOD_RESULT;
pub extern fn FMOD_Channel_GetFrequency(channel: ?*FMOD_CHANNEL, frequency: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Channel_SetPriority(channel: ?*FMOD_CHANNEL, priority: c_int) FMOD_RESULT;
pub extern fn FMOD_Channel_GetPriority(channel: ?*FMOD_CHANNEL, priority: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Channel_SetPosition(channel: ?*FMOD_CHANNEL, position: c_uint, postype: FMOD_TIMEUNIT) FMOD_RESULT;
pub extern fn FMOD_Channel_GetPosition(channel: ?*FMOD_CHANNEL, position: [*c]c_uint, postype: FMOD_TIMEUNIT) FMOD_RESULT;
pub extern fn FMOD_Channel_SetChannelGroup(channel: ?*FMOD_CHANNEL, channelgroup: ?*FMOD_CHANNELGROUP) FMOD_RESULT;
pub extern fn FMOD_Channel_GetChannelGroup(channel: ?*FMOD_CHANNEL, channelgroup: [*c]?*FMOD_CHANNELGROUP) FMOD_RESULT;
pub extern fn FMOD_Channel_SetLoopCount(channel: ?*FMOD_CHANNEL, loopcount: c_int) FMOD_RESULT;
pub extern fn FMOD_Channel_GetLoopCount(channel: ?*FMOD_CHANNEL, loopcount: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Channel_SetLoopPoints(channel: ?*FMOD_CHANNEL, loopstart: c_uint, loopstarttype: FMOD_TIMEUNIT, loopend: c_uint, loopendtype: FMOD_TIMEUNIT) FMOD_RESULT;
pub extern fn FMOD_Channel_GetLoopPoints(channel: ?*FMOD_CHANNEL, loopstart: [*c]c_uint, loopstarttype: FMOD_TIMEUNIT, loopend: [*c]c_uint, loopendtype: FMOD_TIMEUNIT) FMOD_RESULT;
pub extern fn FMOD_Channel_IsVirtual(channel: ?*FMOD_CHANNEL, isvirtual: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Channel_GetCurrentSound(channel: ?*FMOD_CHANNEL, sound: [*c]?*FMOD_SOUND) FMOD_RESULT;
pub extern fn FMOD_Channel_GetIndex(channel: ?*FMOD_CHANNEL, index: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_GetSystemObject(channelgroup: ?*FMOD_CHANNELGROUP, system: [*c]?*FMOD_SYSTEM) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_Stop(channelgroup: ?*FMOD_CHANNELGROUP) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_SetPaused(channelgroup: ?*FMOD_CHANNELGROUP, paused: FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_GetPaused(channelgroup: ?*FMOD_CHANNELGROUP, paused: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_SetVolume(channelgroup: ?*FMOD_CHANNELGROUP, volume: f32) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_GetVolume(channelgroup: ?*FMOD_CHANNELGROUP, volume: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_SetVolumeRamp(channelgroup: ?*FMOD_CHANNELGROUP, ramp: FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_GetVolumeRamp(channelgroup: ?*FMOD_CHANNELGROUP, ramp: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_GetAudibility(channelgroup: ?*FMOD_CHANNELGROUP, audibility: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_SetPitch(channelgroup: ?*FMOD_CHANNELGROUP, pitch: f32) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_GetPitch(channelgroup: ?*FMOD_CHANNELGROUP, pitch: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_SetMute(channelgroup: ?*FMOD_CHANNELGROUP, mute: FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_GetMute(channelgroup: ?*FMOD_CHANNELGROUP, mute: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_SetReverbProperties(channelgroup: ?*FMOD_CHANNELGROUP, instance: c_int, wet: f32) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_GetReverbProperties(channelgroup: ?*FMOD_CHANNELGROUP, instance: c_int, wet: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_SetLowPassGain(channelgroup: ?*FMOD_CHANNELGROUP, gain: f32) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_GetLowPassGain(channelgroup: ?*FMOD_CHANNELGROUP, gain: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_SetMode(channelgroup: ?*FMOD_CHANNELGROUP, mode: FMOD_MODE) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_GetMode(channelgroup: ?*FMOD_CHANNELGROUP, mode: [*c]FMOD_MODE) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_SetCallback(channelgroup: ?*FMOD_CHANNELGROUP, callback: FMOD_CHANNELCONTROL_CALLBACK) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_IsPlaying(channelgroup: ?*FMOD_CHANNELGROUP, isplaying: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_SetPan(channelgroup: ?*FMOD_CHANNELGROUP, pan: f32) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_SetMixLevelsOutput(channelgroup: ?*FMOD_CHANNELGROUP, frontleft: f32, frontright: f32, center: f32, lfe: f32, surroundleft: f32, surroundright: f32, backleft: f32, backright: f32) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_SetMixLevelsInput(channelgroup: ?*FMOD_CHANNELGROUP, levels: [*c]f32, numlevels: c_int) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_SetMixMatrix(channelgroup: ?*FMOD_CHANNELGROUP, matrix: [*c]f32, outchannels: c_int, inchannels: c_int, inchannel_hop: c_int) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_GetMixMatrix(channelgroup: ?*FMOD_CHANNELGROUP, matrix: [*c]f32, outchannels: [*c]c_int, inchannels: [*c]c_int, inchannel_hop: c_int) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_GetDSPClock(channelgroup: ?*FMOD_CHANNELGROUP, dspclock: [*c]c_ulonglong, parentclock: [*c]c_ulonglong) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_SetDelay(channelgroup: ?*FMOD_CHANNELGROUP, dspclock_start: c_ulonglong, dspclock_end: c_ulonglong, stopchannels: FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_GetDelay(channelgroup: ?*FMOD_CHANNELGROUP, dspclock_start: [*c]c_ulonglong, dspclock_end: [*c]c_ulonglong, stopchannels: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_AddFadePoint(channelgroup: ?*FMOD_CHANNELGROUP, dspclock: c_ulonglong, volume: f32) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_SetFadePointRamp(channelgroup: ?*FMOD_CHANNELGROUP, dspclock: c_ulonglong, volume: f32) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_RemoveFadePoints(channelgroup: ?*FMOD_CHANNELGROUP, dspclock_start: c_ulonglong, dspclock_end: c_ulonglong) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_GetFadePoints(channelgroup: ?*FMOD_CHANNELGROUP, numpoints: [*c]c_uint, point_dspclock: [*c]c_ulonglong, point_volume: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_GetDSP(channelgroup: ?*FMOD_CHANNELGROUP, index: c_int, dsp: [*c]?*FMOD_DSP) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_AddDSP(channelgroup: ?*FMOD_CHANNELGROUP, index: c_int, dsp: ?*FMOD_DSP) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_RemoveDSP(channelgroup: ?*FMOD_CHANNELGROUP, dsp: ?*FMOD_DSP) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_GetNumDSPs(channelgroup: ?*FMOD_CHANNELGROUP, numdsps: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_SetDSPIndex(channelgroup: ?*FMOD_CHANNELGROUP, dsp: ?*FMOD_DSP, index: c_int) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_GetDSPIndex(channelgroup: ?*FMOD_CHANNELGROUP, dsp: ?*FMOD_DSP, index: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_Set3DAttributes(channelgroup: ?*FMOD_CHANNELGROUP, pos: [*c]const FMOD_VECTOR, vel: [*c]const FMOD_VECTOR) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_Get3DAttributes(channelgroup: ?*FMOD_CHANNELGROUP, pos: [*c]FMOD_VECTOR, vel: [*c]FMOD_VECTOR) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_Set3DMinMaxDistance(channelgroup: ?*FMOD_CHANNELGROUP, mindistance: f32, maxdistance: f32) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_Get3DMinMaxDistance(channelgroup: ?*FMOD_CHANNELGROUP, mindistance: [*c]f32, maxdistance: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_Set3DConeSettings(channelgroup: ?*FMOD_CHANNELGROUP, insideconeangle: f32, outsideconeangle: f32, outsidevolume: f32) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_Get3DConeSettings(channelgroup: ?*FMOD_CHANNELGROUP, insideconeangle: [*c]f32, outsideconeangle: [*c]f32, outsidevolume: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_Set3DConeOrientation(channelgroup: ?*FMOD_CHANNELGROUP, orientation: [*c]FMOD_VECTOR) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_Get3DConeOrientation(channelgroup: ?*FMOD_CHANNELGROUP, orientation: [*c]FMOD_VECTOR) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_Set3DCustomRolloff(channelgroup: ?*FMOD_CHANNELGROUP, points: [*c]FMOD_VECTOR, numpoints: c_int) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_Get3DCustomRolloff(channelgroup: ?*FMOD_CHANNELGROUP, points: [*c][*c]FMOD_VECTOR, numpoints: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_Set3DOcclusion(channelgroup: ?*FMOD_CHANNELGROUP, directocclusion: f32, reverbocclusion: f32) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_Get3DOcclusion(channelgroup: ?*FMOD_CHANNELGROUP, directocclusion: [*c]f32, reverbocclusion: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_Set3DSpread(channelgroup: ?*FMOD_CHANNELGROUP, angle: f32) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_Get3DSpread(channelgroup: ?*FMOD_CHANNELGROUP, angle: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_Set3DLevel(channelgroup: ?*FMOD_CHANNELGROUP, level: f32) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_Get3DLevel(channelgroup: ?*FMOD_CHANNELGROUP, level: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_Set3DDopplerLevel(channelgroup: ?*FMOD_CHANNELGROUP, level: f32) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_Get3DDopplerLevel(channelgroup: ?*FMOD_CHANNELGROUP, level: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_Set3DDistanceFilter(channelgroup: ?*FMOD_CHANNELGROUP, custom: FMOD_BOOL, customLevel: f32, centerFreq: f32) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_Get3DDistanceFilter(channelgroup: ?*FMOD_CHANNELGROUP, custom: [*c]FMOD_BOOL, customLevel: [*c]f32, centerFreq: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_SetUserData(channelgroup: ?*FMOD_CHANNELGROUP, userdata: ?*c_void) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_GetUserData(channelgroup: ?*FMOD_CHANNELGROUP, userdata: [*c]?*c_void) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_Release(channelgroup: ?*FMOD_CHANNELGROUP) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_AddGroup(channelgroup: ?*FMOD_CHANNELGROUP, group: ?*FMOD_CHANNELGROUP, propagatedspclock: FMOD_BOOL, connection: [*c]?*FMOD_DSPCONNECTION) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_GetNumGroups(channelgroup: ?*FMOD_CHANNELGROUP, numgroups: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_GetGroup(channelgroup: ?*FMOD_CHANNELGROUP, index: c_int, group: [*c]?*FMOD_CHANNELGROUP) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_GetParentGroup(channelgroup: ?*FMOD_CHANNELGROUP, group: [*c]?*FMOD_CHANNELGROUP) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_GetName(channelgroup: ?*FMOD_CHANNELGROUP, name: [*c]u8, namelen: c_int) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_GetNumChannels(channelgroup: ?*FMOD_CHANNELGROUP, numchannels: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_ChannelGroup_GetChannel(channelgroup: ?*FMOD_CHANNELGROUP, index: c_int, channel: [*c]?*FMOD_CHANNEL) FMOD_RESULT;
pub extern fn FMOD_SoundGroup_Release(soundgroup: ?*FMOD_SOUNDGROUP) FMOD_RESULT;
pub extern fn FMOD_SoundGroup_GetSystemObject(soundgroup: ?*FMOD_SOUNDGROUP, system: [*c]?*FMOD_SYSTEM) FMOD_RESULT;
pub extern fn FMOD_SoundGroup_SetMaxAudible(soundgroup: ?*FMOD_SOUNDGROUP, maxaudible: c_int) FMOD_RESULT;
pub extern fn FMOD_SoundGroup_GetMaxAudible(soundgroup: ?*FMOD_SOUNDGROUP, maxaudible: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_SoundGroup_SetMaxAudibleBehavior(soundgroup: ?*FMOD_SOUNDGROUP, behavior: FMOD_SOUNDGROUP_BEHAVIOR) FMOD_RESULT;
pub extern fn FMOD_SoundGroup_GetMaxAudibleBehavior(soundgroup: ?*FMOD_SOUNDGROUP, behavior: [*c]FMOD_SOUNDGROUP_BEHAVIOR) FMOD_RESULT;
pub extern fn FMOD_SoundGroup_SetMuteFadeSpeed(soundgroup: ?*FMOD_SOUNDGROUP, speed: f32) FMOD_RESULT;
pub extern fn FMOD_SoundGroup_GetMuteFadeSpeed(soundgroup: ?*FMOD_SOUNDGROUP, speed: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_SoundGroup_SetVolume(soundgroup: ?*FMOD_SOUNDGROUP, volume: f32) FMOD_RESULT;
pub extern fn FMOD_SoundGroup_GetVolume(soundgroup: ?*FMOD_SOUNDGROUP, volume: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_SoundGroup_Stop(soundgroup: ?*FMOD_SOUNDGROUP) FMOD_RESULT;
pub extern fn FMOD_SoundGroup_GetName(soundgroup: ?*FMOD_SOUNDGROUP, name: [*c]u8, namelen: c_int) FMOD_RESULT;
pub extern fn FMOD_SoundGroup_GetNumSounds(soundgroup: ?*FMOD_SOUNDGROUP, numsounds: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_SoundGroup_GetSound(soundgroup: ?*FMOD_SOUNDGROUP, index: c_int, sound: [*c]?*FMOD_SOUND) FMOD_RESULT;
pub extern fn FMOD_SoundGroup_GetNumPlaying(soundgroup: ?*FMOD_SOUNDGROUP, numplaying: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_SoundGroup_SetUserData(soundgroup: ?*FMOD_SOUNDGROUP, userdata: ?*c_void) FMOD_RESULT;
pub extern fn FMOD_SoundGroup_GetUserData(soundgroup: ?*FMOD_SOUNDGROUP, userdata: [*c]?*c_void) FMOD_RESULT;
pub extern fn FMOD_DSP_Release(dsp: ?*FMOD_DSP) FMOD_RESULT;
pub extern fn FMOD_DSP_GetSystemObject(dsp: ?*FMOD_DSP, system: [*c]?*FMOD_SYSTEM) FMOD_RESULT;
pub extern fn FMOD_DSP_AddInput(dsp: ?*FMOD_DSP, input: ?*FMOD_DSP, connection: [*c]?*FMOD_DSPCONNECTION, type: FMOD_DSPCONNECTION_TYPE) FMOD_RESULT;
pub extern fn FMOD_DSP_DisconnectFrom(dsp: ?*FMOD_DSP, target: ?*FMOD_DSP, connection: ?*FMOD_DSPCONNECTION) FMOD_RESULT;
pub extern fn FMOD_DSP_DisconnectAll(dsp: ?*FMOD_DSP, inputs: FMOD_BOOL, outputs: FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_DSP_GetNumInputs(dsp: ?*FMOD_DSP, numinputs: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_DSP_GetNumOutputs(dsp: ?*FMOD_DSP, numoutputs: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_DSP_GetInput(dsp: ?*FMOD_DSP, index: c_int, input: [*c]?*FMOD_DSP, inputconnection: [*c]?*FMOD_DSPCONNECTION) FMOD_RESULT;
pub extern fn FMOD_DSP_GetOutput(dsp: ?*FMOD_DSP, index: c_int, output: [*c]?*FMOD_DSP, outputconnection: [*c]?*FMOD_DSPCONNECTION) FMOD_RESULT;
pub extern fn FMOD_DSP_SetActive(dsp: ?*FMOD_DSP, active: FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_DSP_GetActive(dsp: ?*FMOD_DSP, active: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_DSP_SetBypass(dsp: ?*FMOD_DSP, bypass: FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_DSP_GetBypass(dsp: ?*FMOD_DSP, bypass: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_DSP_SetWetDryMix(dsp: ?*FMOD_DSP, prewet: f32, postwet: f32, dry: f32) FMOD_RESULT;
pub extern fn FMOD_DSP_GetWetDryMix(dsp: ?*FMOD_DSP, prewet: [*c]f32, postwet: [*c]f32, dry: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_DSP_SetChannelFormat(dsp: ?*FMOD_DSP, channelmask: FMOD_CHANNELMASK, numchannels: c_int, source_speakermode: FMOD_SPEAKERMODE) FMOD_RESULT;
pub extern fn FMOD_DSP_GetChannelFormat(dsp: ?*FMOD_DSP, channelmask: [*c]FMOD_CHANNELMASK, numchannels: [*c]c_int, source_speakermode: [*c]FMOD_SPEAKERMODE) FMOD_RESULT;
pub extern fn FMOD_DSP_GetOutputChannelFormat(dsp: ?*FMOD_DSP, inmask: FMOD_CHANNELMASK, inchannels: c_int, inspeakermode: FMOD_SPEAKERMODE, outmask: [*c]FMOD_CHANNELMASK, outchannels: [*c]c_int, outspeakermode: [*c]FMOD_SPEAKERMODE) FMOD_RESULT;
pub extern fn FMOD_DSP_Reset(dsp: ?*FMOD_DSP) FMOD_RESULT;
pub extern fn FMOD_DSP_SetParameterFloat(dsp: ?*FMOD_DSP, index: c_int, value: f32) FMOD_RESULT;
pub extern fn FMOD_DSP_SetParameterInt(dsp: ?*FMOD_DSP, index: c_int, value: c_int) FMOD_RESULT;
pub extern fn FMOD_DSP_SetParameterBool(dsp: ?*FMOD_DSP, index: c_int, value: FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_DSP_SetParameterData(dsp: ?*FMOD_DSP, index: c_int, data: ?*c_void, length: c_uint) FMOD_RESULT;
pub extern fn FMOD_DSP_GetParameterFloat(dsp: ?*FMOD_DSP, index: c_int, value: [*c]f32, valuestr: [*c]u8, valuestrlen: c_int) FMOD_RESULT;
pub extern fn FMOD_DSP_GetParameterInt(dsp: ?*FMOD_DSP, index: c_int, value: [*c]c_int, valuestr: [*c]u8, valuestrlen: c_int) FMOD_RESULT;
pub extern fn FMOD_DSP_GetParameterBool(dsp: ?*FMOD_DSP, index: c_int, value: [*c]FMOD_BOOL, valuestr: [*c]u8, valuestrlen: c_int) FMOD_RESULT;
pub extern fn FMOD_DSP_GetParameterData(dsp: ?*FMOD_DSP, index: c_int, data: [*c]?*c_void, length: [*c]c_uint, valuestr: [*c]u8, valuestrlen: c_int) FMOD_RESULT;
pub extern fn FMOD_DSP_GetNumParameters(dsp: ?*FMOD_DSP, numparams: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_DSP_GetParameterInfo(dsp: ?*FMOD_DSP, index: c_int, desc: [*c][*c]FMOD_DSP_PARAMETER_DESC) FMOD_RESULT;
pub extern fn FMOD_DSP_GetDataParameterIndex(dsp: ?*FMOD_DSP, datatype: c_int, index: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_DSP_ShowConfigDialog(dsp: ?*FMOD_DSP, hwnd: ?*c_void, show: FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_DSP_GetInfo(dsp: ?*FMOD_DSP, name: [*c]u8, version: [*c]c_uint, channels: [*c]c_int, configwidth: [*c]c_int, configheight: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_DSP_GetType(dsp: ?*FMOD_DSP, type: [*c]FMOD_DSP_TYPE) FMOD_RESULT;
pub extern fn FMOD_DSP_GetIdle(dsp: ?*FMOD_DSP, idle: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_DSP_SetUserData(dsp: ?*FMOD_DSP, userdata: ?*c_void) FMOD_RESULT;
pub extern fn FMOD_DSP_GetUserData(dsp: ?*FMOD_DSP, userdata: [*c]?*c_void) FMOD_RESULT;
pub extern fn FMOD_DSP_SetMeteringEnabled(dsp: ?*FMOD_DSP, inputEnabled: FMOD_BOOL, outputEnabled: FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_DSP_GetMeteringEnabled(dsp: ?*FMOD_DSP, inputEnabled: [*c]FMOD_BOOL, outputEnabled: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_DSP_GetMeteringInfo(dsp: ?*FMOD_DSP, inputInfo: [*c]FMOD_DSP_METERING_INFO, outputInfo: [*c]FMOD_DSP_METERING_INFO) FMOD_RESULT;
pub extern fn FMOD_DSP_GetCPUUsage(dsp: ?*FMOD_DSP, exclusive: [*c]c_uint, inclusive: [*c]c_uint) FMOD_RESULT;
pub extern fn FMOD_DSPConnection_GetInput(dspconnection: ?*FMOD_DSPCONNECTION, input: [*c]?*FMOD_DSP) FMOD_RESULT;
pub extern fn FMOD_DSPConnection_GetOutput(dspconnection: ?*FMOD_DSPCONNECTION, output: [*c]?*FMOD_DSP) FMOD_RESULT;
pub extern fn FMOD_DSPConnection_SetMix(dspconnection: ?*FMOD_DSPCONNECTION, volume: f32) FMOD_RESULT;
pub extern fn FMOD_DSPConnection_GetMix(dspconnection: ?*FMOD_DSPCONNECTION, volume: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_DSPConnection_SetMixMatrix(dspconnection: ?*FMOD_DSPCONNECTION, matrix: [*c]f32, outchannels: c_int, inchannels: c_int, inchannel_hop: c_int) FMOD_RESULT;
pub extern fn FMOD_DSPConnection_GetMixMatrix(dspconnection: ?*FMOD_DSPCONNECTION, matrix: [*c]f32, outchannels: [*c]c_int, inchannels: [*c]c_int, inchannel_hop: c_int) FMOD_RESULT;
pub extern fn FMOD_DSPConnection_GetType(dspconnection: ?*FMOD_DSPCONNECTION, type: [*c]FMOD_DSPCONNECTION_TYPE) FMOD_RESULT;
pub extern fn FMOD_DSPConnection_SetUserData(dspconnection: ?*FMOD_DSPCONNECTION, userdata: ?*c_void) FMOD_RESULT;
pub extern fn FMOD_DSPConnection_GetUserData(dspconnection: ?*FMOD_DSPCONNECTION, userdata: [*c]?*c_void) FMOD_RESULT;
pub extern fn FMOD_Geometry_Release(geometry: ?*FMOD_GEOMETRY) FMOD_RESULT;
pub extern fn FMOD_Geometry_AddPolygon(geometry: ?*FMOD_GEOMETRY, directocclusion: f32, reverbocclusion: f32, doublesided: FMOD_BOOL, numvertices: c_int, vertices: [*c]const FMOD_VECTOR, polygonindex: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Geometry_GetNumPolygons(geometry: ?*FMOD_GEOMETRY, numpolygons: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Geometry_GetMaxPolygons(geometry: ?*FMOD_GEOMETRY, maxpolygons: [*c]c_int, maxvertices: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Geometry_GetPolygonNumVertices(geometry: ?*FMOD_GEOMETRY, index: c_int, numvertices: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Geometry_SetPolygonVertex(geometry: ?*FMOD_GEOMETRY, index: c_int, vertexindex: c_int, vertex: [*c]const FMOD_VECTOR) FMOD_RESULT;
pub extern fn FMOD_Geometry_GetPolygonVertex(geometry: ?*FMOD_GEOMETRY, index: c_int, vertexindex: c_int, vertex: [*c]FMOD_VECTOR) FMOD_RESULT;
pub extern fn FMOD_Geometry_SetPolygonAttributes(geometry: ?*FMOD_GEOMETRY, index: c_int, directocclusion: f32, reverbocclusion: f32, doublesided: FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Geometry_GetPolygonAttributes(geometry: ?*FMOD_GEOMETRY, index: c_int, directocclusion: [*c]f32, reverbocclusion: [*c]f32, doublesided: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Geometry_SetActive(geometry: ?*FMOD_GEOMETRY, active: FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Geometry_GetActive(geometry: ?*FMOD_GEOMETRY, active: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Geometry_SetRotation(geometry: ?*FMOD_GEOMETRY, forward: [*c]const FMOD_VECTOR, up: [*c]const FMOD_VECTOR) FMOD_RESULT;
pub extern fn FMOD_Geometry_GetRotation(geometry: ?*FMOD_GEOMETRY, forward: [*c]FMOD_VECTOR, up: [*c]FMOD_VECTOR) FMOD_RESULT;
pub extern fn FMOD_Geometry_SetPosition(geometry: ?*FMOD_GEOMETRY, position: [*c]const FMOD_VECTOR) FMOD_RESULT;
pub extern fn FMOD_Geometry_GetPosition(geometry: ?*FMOD_GEOMETRY, position: [*c]FMOD_VECTOR) FMOD_RESULT;
pub extern fn FMOD_Geometry_SetScale(geometry: ?*FMOD_GEOMETRY, scale: [*c]const FMOD_VECTOR) FMOD_RESULT;
pub extern fn FMOD_Geometry_GetScale(geometry: ?*FMOD_GEOMETRY, scale: [*c]FMOD_VECTOR) FMOD_RESULT;
pub extern fn FMOD_Geometry_Save(geometry: ?*FMOD_GEOMETRY, data: ?*c_void, datasize: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Geometry_SetUserData(geometry: ?*FMOD_GEOMETRY, userdata: ?*c_void) FMOD_RESULT;
pub extern fn FMOD_Geometry_GetUserData(geometry: ?*FMOD_GEOMETRY, userdata: [*c]?*c_void) FMOD_RESULT;
pub extern fn FMOD_Reverb3D_Release(reverb3d: ?*FMOD_REVERB3D) FMOD_RESULT;
pub extern fn FMOD_Reverb3D_Set3DAttributes(reverb3d: ?*FMOD_REVERB3D, position: [*c]const FMOD_VECTOR, mindistance: f32, maxdistance: f32) FMOD_RESULT;
pub extern fn FMOD_Reverb3D_Get3DAttributes(reverb3d: ?*FMOD_REVERB3D, position: [*c]FMOD_VECTOR, mindistance: [*c]f32, maxdistance: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Reverb3D_SetProperties(reverb3d: ?*FMOD_REVERB3D, properties: [*c]const FMOD_REVERB_PROPERTIES) FMOD_RESULT;
pub extern fn FMOD_Reverb3D_GetProperties(reverb3d: ?*FMOD_REVERB3D, properties: [*c]FMOD_REVERB_PROPERTIES) FMOD_RESULT;
pub extern fn FMOD_Reverb3D_SetActive(reverb3d: ?*FMOD_REVERB3D, active: FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Reverb3D_GetActive(reverb3d: ?*FMOD_REVERB3D, active: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Reverb3D_SetUserData(reverb3d: ?*FMOD_REVERB3D, userdata: ?*c_void) FMOD_RESULT;
pub extern fn FMOD_Reverb3D_GetUserData(reverb3d: ?*FMOD_REVERB3D, userdata: [*c]?*c_void) FMOD_RESULT;
pub const struct_FMOD_STUDIO_SYSTEM = opaque {};
pub const FMOD_STUDIO_SYSTEM = struct_FMOD_STUDIO_SYSTEM;
pub const struct_FMOD_STUDIO_EVENTDESCRIPTION = opaque {};
pub const FMOD_STUDIO_EVENTDESCRIPTION = struct_FMOD_STUDIO_EVENTDESCRIPTION;
pub const struct_FMOD_STUDIO_EVENTINSTANCE = opaque {};
pub const FMOD_STUDIO_EVENTINSTANCE = struct_FMOD_STUDIO_EVENTINSTANCE;
pub const struct_FMOD_STUDIO_BUS = opaque {};
pub const FMOD_STUDIO_BUS = struct_FMOD_STUDIO_BUS;
pub const struct_FMOD_STUDIO_VCA = opaque {};
pub const FMOD_STUDIO_VCA = struct_FMOD_STUDIO_VCA;
pub const struct_FMOD_STUDIO_BANK = opaque {};
pub const FMOD_STUDIO_BANK = struct_FMOD_STUDIO_BANK;
pub const struct_FMOD_STUDIO_COMMANDREPLAY = opaque {};
pub const FMOD_STUDIO_COMMANDREPLAY = struct_FMOD_STUDIO_COMMANDREPLAY;
pub const FMOD_STUDIO_INITFLAGS = c_uint;
pub const FMOD_STUDIO_PARAMETER_FLAGS = c_uint;
pub const FMOD_STUDIO_SYSTEM_CALLBACK_TYPE = c_uint;
pub const FMOD_STUDIO_EVENT_CALLBACK_TYPE = c_uint;
pub const FMOD_STUDIO_LOAD_BANK_FLAGS = c_uint;
pub const FMOD_STUDIO_COMMANDCAPTURE_FLAGS = c_uint;
pub const FMOD_STUDIO_COMMANDREPLAY_FLAGS = c_uint;
pub const FMOD_STUDIO_LOADING_STATE_UNLOADING: c_int = 0;
pub const FMOD_STUDIO_LOADING_STATE_UNLOADED: c_int = 1;
pub const FMOD_STUDIO_LOADING_STATE_LOADING: c_int = 2;
pub const FMOD_STUDIO_LOADING_STATE_LOADED: c_int = 3;
pub const FMOD_STUDIO_LOADING_STATE_ERROR: c_int = 4;
pub const FMOD_STUDIO_LOADING_STATE_FORCEINT: c_int = 65536;
pub const enum_FMOD_STUDIO_LOADING_STATE = c_uint;
pub const FMOD_STUDIO_LOADING_STATE = enum_FMOD_STUDIO_LOADING_STATE;
pub const FMOD_STUDIO_LOAD_MEMORY: c_int = 0;
pub const FMOD_STUDIO_LOAD_MEMORY_POINT: c_int = 1;
pub const FMOD_STUDIO_LOAD_MEMORY_FORCEINT: c_int = 65536;
pub const enum_FMOD_STUDIO_LOAD_MEMORY_MODE = c_uint;
pub const FMOD_STUDIO_LOAD_MEMORY_MODE = enum_FMOD_STUDIO_LOAD_MEMORY_MODE;
pub const FMOD_STUDIO_PARAMETER_GAME_CONTROLLED: c_int = 0;
pub const FMOD_STUDIO_PARAMETER_AUTOMATIC_DISTANCE: c_int = 1;
pub const FMOD_STUDIO_PARAMETER_AUTOMATIC_EVENT_CONE_ANGLE: c_int = 2;
pub const FMOD_STUDIO_PARAMETER_AUTOMATIC_EVENT_ORIENTATION: c_int = 3;
pub const FMOD_STUDIO_PARAMETER_AUTOMATIC_DIRECTION: c_int = 4;
pub const FMOD_STUDIO_PARAMETER_AUTOMATIC_ELEVATION: c_int = 5;
pub const FMOD_STUDIO_PARAMETER_AUTOMATIC_LISTENER_ORIENTATION: c_int = 6;
pub const FMOD_STUDIO_PARAMETER_AUTOMATIC_SPEED: c_int = 7;
pub const FMOD_STUDIO_PARAMETER_AUTOMATIC_SPEED_ABSOLUTE: c_int = 8;
pub const FMOD_STUDIO_PARAMETER_MAX: c_int = 9;
pub const FMOD_STUDIO_PARAMETER_FORCEINT: c_int = 65536;
pub const enum_FMOD_STUDIO_PARAMETER_TYPE = c_uint;
pub const FMOD_STUDIO_PARAMETER_TYPE = enum_FMOD_STUDIO_PARAMETER_TYPE;
pub const FMOD_STUDIO_USER_PROPERTY_TYPE_INTEGER: c_int = 0;
pub const FMOD_STUDIO_USER_PROPERTY_TYPE_BOOLEAN: c_int = 1;
pub const FMOD_STUDIO_USER_PROPERTY_TYPE_FLOAT: c_int = 2;
pub const FMOD_STUDIO_USER_PROPERTY_TYPE_STRING: c_int = 3;
pub const FMOD_STUDIO_USER_PROPERTY_TYPE_FORCEINT: c_int = 65536;
pub const enum_FMOD_STUDIO_USER_PROPERTY_TYPE = c_uint;
pub const FMOD_STUDIO_USER_PROPERTY_TYPE = enum_FMOD_STUDIO_USER_PROPERTY_TYPE;
pub const FMOD_STUDIO_EVENT_PROPERTY_CHANNELPRIORITY: c_int = 0;
pub const FMOD_STUDIO_EVENT_PROPERTY_SCHEDULE_DELAY: c_int = 1;
pub const FMOD_STUDIO_EVENT_PROPERTY_SCHEDULE_LOOKAHEAD: c_int = 2;
pub const FMOD_STUDIO_EVENT_PROPERTY_MINIMUM_DISTANCE: c_int = 3;
pub const FMOD_STUDIO_EVENT_PROPERTY_MAXIMUM_DISTANCE: c_int = 4;
pub const FMOD_STUDIO_EVENT_PROPERTY_COOLDOWN: c_int = 5;
pub const FMOD_STUDIO_EVENT_PROPERTY_MAX: c_int = 6;
pub const FMOD_STUDIO_EVENT_PROPERTY_FORCEINT: c_int = 65536;
pub const enum_FMOD_STUDIO_EVENT_PROPERTY = c_uint;
pub const FMOD_STUDIO_EVENT_PROPERTY = enum_FMOD_STUDIO_EVENT_PROPERTY;
pub const FMOD_STUDIO_PLAYBACK_PLAYING: c_int = 0;
pub const FMOD_STUDIO_PLAYBACK_SUSTAINING: c_int = 1;
pub const FMOD_STUDIO_PLAYBACK_STOPPED: c_int = 2;
pub const FMOD_STUDIO_PLAYBACK_STARTING: c_int = 3;
pub const FMOD_STUDIO_PLAYBACK_STOPPING: c_int = 4;
pub const FMOD_STUDIO_PLAYBACK_FORCEINT: c_int = 65536;
pub const enum_FMOD_STUDIO_PLAYBACK_STATE = c_uint;
pub const FMOD_STUDIO_PLAYBACK_STATE = enum_FMOD_STUDIO_PLAYBACK_STATE;
pub const FMOD_STUDIO_STOP_ALLOWFADEOUT: c_int = 0;
pub const FMOD_STUDIO_STOP_IMMEDIATE: c_int = 1;
pub const FMOD_STUDIO_STOP_FORCEINT: c_int = 65536;
pub const enum_FMOD_STUDIO_STOP_MODE = c_uint;
pub const FMOD_STUDIO_STOP_MODE = enum_FMOD_STUDIO_STOP_MODE;
pub const FMOD_STUDIO_INSTANCETYPE_NONE: c_int = 0;
pub const FMOD_STUDIO_INSTANCETYPE_SYSTEM: c_int = 1;
pub const FMOD_STUDIO_INSTANCETYPE_EVENTDESCRIPTION: c_int = 2;
pub const FMOD_STUDIO_INSTANCETYPE_EVENTINSTANCE: c_int = 3;
pub const FMOD_STUDIO_INSTANCETYPE_PARAMETERINSTANCE: c_int = 4;
pub const FMOD_STUDIO_INSTANCETYPE_BUS: c_int = 5;
pub const FMOD_STUDIO_INSTANCETYPE_VCA: c_int = 6;
pub const FMOD_STUDIO_INSTANCETYPE_BANK: c_int = 7;
pub const FMOD_STUDIO_INSTANCETYPE_COMMANDREPLAY: c_int = 8;
pub const FMOD_STUDIO_INSTANCETYPE_FORCEINT: c_int = 65536;
pub const enum_FMOD_STUDIO_INSTANCETYPE = c_uint;
pub const FMOD_STUDIO_INSTANCETYPE = enum_FMOD_STUDIO_INSTANCETYPE;
pub const struct_FMOD_STUDIO_BANK_INFO = extern struct {
size: c_int,
userdata: ?*c_void,
userdatalength: c_int,
opencallback: FMOD_FILE_OPEN_CALLBACK,
closecallback: FMOD_FILE_CLOSE_CALLBACK,
readcallback: FMOD_FILE_READ_CALLBACK,
seekcallback: FMOD_FILE_SEEK_CALLBACK,
};
pub const FMOD_STUDIO_BANK_INFO = struct_FMOD_STUDIO_BANK_INFO;
pub const struct_FMOD_STUDIO_PARAMETER_ID = extern struct {
data1: c_uint,
data2: c_uint,
};
pub const FMOD_STUDIO_PARAMETER_ID = struct_FMOD_STUDIO_PARAMETER_ID;
pub const struct_FMOD_STUDIO_PARAMETER_DESCRIPTION = extern struct {
name: [*c]const u8,
id: FMOD_STUDIO_PARAMETER_ID,
minimum: f32,
maximum: f32,
defaultvalue: f32,
type: FMOD_STUDIO_PARAMETER_TYPE,
flags: FMOD_STUDIO_PARAMETER_FLAGS,
};
pub const FMOD_STUDIO_PARAMETER_DESCRIPTION = struct_FMOD_STUDIO_PARAMETER_DESCRIPTION;
const union_unnamed_2 = extern union {
intvalue: c_int,
boolvalue: FMOD_BOOL,
floatvalue: f32,
stringvalue: [*c]const u8,
};
pub const struct_FMOD_STUDIO_USER_PROPERTY = extern struct {
name: [*c]const u8,
type: FMOD_STUDIO_USER_PROPERTY_TYPE,
unnamed_0: union_unnamed_2,
};
pub const FMOD_STUDIO_USER_PROPERTY = struct_FMOD_STUDIO_USER_PROPERTY;
pub const struct_FMOD_STUDIO_PROGRAMMER_SOUND_PROPERTIES = extern struct {
name: [*c]const u8,
sound: ?*FMOD_SOUND,
subsoundIndex: c_int,
};
pub const FMOD_STUDIO_PROGRAMMER_SOUND_PROPERTIES = struct_FMOD_STUDIO_PROGRAMMER_SOUND_PROPERTIES;
pub const struct_FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES = extern struct {
name: [*c]const u8,
dsp: ?*FMOD_DSP,
};
pub const FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES = struct_FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES;
pub const struct_FMOD_STUDIO_TIMELINE_MARKER_PROPERTIES = extern struct {
name: [*c]const u8,
position: c_int,
};
pub const FMOD_STUDIO_TIMELINE_MARKER_PROPERTIES = struct_FMOD_STUDIO_TIMELINE_MARKER_PROPERTIES;
pub const struct_FMOD_STUDIO_TIMELINE_BEAT_PROPERTIES = extern struct {
bar: c_int,
beat: c_int,
position: c_int,
tempo: f32,
timesignatureupper: c_int,
timesignaturelower: c_int,
};
pub const FMOD_STUDIO_TIMELINE_BEAT_PROPERTIES = struct_FMOD_STUDIO_TIMELINE_BEAT_PROPERTIES;
pub const struct_FMOD_STUDIO_TIMELINE_NESTED_BEAT_PROPERTIES = extern struct {
eventid: FMOD_GUID,
properties: FMOD_STUDIO_TIMELINE_BEAT_PROPERTIES,
};
pub const FMOD_STUDIO_TIMELINE_NESTED_BEAT_PROPERTIES = struct_FMOD_STUDIO_TIMELINE_NESTED_BEAT_PROPERTIES;
pub const struct_FMOD_STUDIO_ADVANCEDSETTINGS = extern struct {
cbsize: c_int,
commandqueuesize: c_uint,
handleinitialsize: c_uint,
studioupdateperiod: c_int,
idlesampledatapoolsize: c_int,
streamingscheduledelay: c_uint,
encryptionkey: [*c]const u8,
};
pub const FMOD_STUDIO_ADVANCEDSETTINGS = struct_FMOD_STUDIO_ADVANCEDSETTINGS;
pub const struct_FMOD_STUDIO_CPU_USAGE = extern struct {
dspusage: f32,
streamusage: f32,
geometryusage: f32,
updateusage: f32,
studiousage: f32,
};
pub const FMOD_STUDIO_CPU_USAGE = struct_FMOD_STUDIO_CPU_USAGE;
pub const struct_FMOD_STUDIO_BUFFER_INFO = extern struct {
currentusage: c_int,
peakusage: c_int,
capacity: c_int,
stallcount: c_int,
stalltime: f32,
};
pub const FMOD_STUDIO_BUFFER_INFO = struct_FMOD_STUDIO_BUFFER_INFO;
pub const struct_FMOD_STUDIO_BUFFER_USAGE = extern struct {
studiocommandqueue: FMOD_STUDIO_BUFFER_INFO,
studiohandle: FMOD_STUDIO_BUFFER_INFO,
};
pub const FMOD_STUDIO_BUFFER_USAGE = struct_FMOD_STUDIO_BUFFER_USAGE;
pub const struct_FMOD_STUDIO_SOUND_INFO = extern struct {
name_or_data: [*c]const u8,
mode: FMOD_MODE,
exinfo: FMOD_CREATESOUNDEXINFO,
subsoundindex: c_int,
};
pub const FMOD_STUDIO_SOUND_INFO = struct_FMOD_STUDIO_SOUND_INFO;
pub const struct_FMOD_STUDIO_COMMAND_INFO = extern struct {
commandname: [*c]const u8,
parentcommandindex: c_int,
framenumber: c_int,
frametime: f32,
instancetype: FMOD_STUDIO_INSTANCETYPE,
outputtype: FMOD_STUDIO_INSTANCETYPE,
instancehandle: c_uint,
outputhandle: c_uint,
};
pub const FMOD_STUDIO_COMMAND_INFO = struct_FMOD_STUDIO_COMMAND_INFO;
pub const struct_FMOD_STUDIO_MEMORY_USAGE = extern struct {
exclusive: c_int,
inclusive: c_int,
sampledata: c_int,
};
pub const FMOD_STUDIO_MEMORY_USAGE = struct_FMOD_STUDIO_MEMORY_USAGE;
pub const FMOD_STUDIO_SYSTEM_CALLBACK = ?fn (?*FMOD_STUDIO_SYSTEM, FMOD_STUDIO_SYSTEM_CALLBACK_TYPE, ?*c_void, ?*c_void) callconv(.C) FMOD_RESULT;
pub const FMOD_STUDIO_EVENT_CALLBACK = ?fn (FMOD_STUDIO_EVENT_CALLBACK_TYPE, ?*FMOD_STUDIO_EVENTINSTANCE, ?*c_void) callconv(.C) FMOD_RESULT;
pub const FMOD_STUDIO_COMMANDREPLAY_FRAME_CALLBACK = ?fn (?*FMOD_STUDIO_COMMANDREPLAY, c_int, f32, ?*c_void) callconv(.C) FMOD_RESULT;
pub const FMOD_STUDIO_COMMANDREPLAY_LOAD_BANK_CALLBACK = ?fn (?*FMOD_STUDIO_COMMANDREPLAY, c_int, [*c]const FMOD_GUID, [*c]const u8, FMOD_STUDIO_LOAD_BANK_FLAGS, [*c]?*FMOD_STUDIO_BANK, ?*c_void) callconv(.C) FMOD_RESULT;
pub const FMOD_STUDIO_COMMANDREPLAY_CREATE_INSTANCE_CALLBACK = ?fn (?*FMOD_STUDIO_COMMANDREPLAY, c_int, ?*FMOD_STUDIO_EVENTDESCRIPTION, [*c]?*FMOD_STUDIO_EVENTINSTANCE, ?*c_void) callconv(.C) FMOD_RESULT;
pub extern fn FMOD_Studio_ParseID(idstring: [*c]const u8, id: [*c]FMOD_GUID) FMOD_RESULT;
pub extern fn FMOD_Studio_System_Create(system: [*c]?*FMOD_STUDIO_SYSTEM, headerversion: c_uint) FMOD_RESULT;
pub extern fn FMOD_Studio_System_IsValid(system: ?*FMOD_STUDIO_SYSTEM) FMOD_BOOL;
pub extern fn FMOD_Studio_System_SetAdvancedSettings(system: ?*FMOD_STUDIO_SYSTEM, settings: [*c]FMOD_STUDIO_ADVANCEDSETTINGS) FMOD_RESULT;
pub extern fn FMOD_Studio_System_GetAdvancedSettings(system: ?*FMOD_STUDIO_SYSTEM, settings: [*c]FMOD_STUDIO_ADVANCEDSETTINGS) FMOD_RESULT;
pub extern fn FMOD_Studio_System_Initialize(system: ?*FMOD_STUDIO_SYSTEM, maxchannels: c_int, studioflags: FMOD_STUDIO_INITFLAGS, flags: FMOD_INITFLAGS, extradriverdata: ?*c_void) FMOD_RESULT;
pub extern fn FMOD_Studio_System_Release(system: ?*FMOD_STUDIO_SYSTEM) FMOD_RESULT;
pub extern fn FMOD_Studio_System_Update(system: ?*FMOD_STUDIO_SYSTEM) FMOD_RESULT;
pub extern fn FMOD_Studio_System_GetCoreSystem(system: ?*FMOD_STUDIO_SYSTEM, coresystem: [*c]?*FMOD_SYSTEM) FMOD_RESULT;
pub extern fn FMOD_Studio_System_GetEvent(system: ?*FMOD_STUDIO_SYSTEM, pathOrID: [*c]const u8, event: [*c]?*FMOD_STUDIO_EVENTDESCRIPTION) FMOD_RESULT;
pub extern fn FMOD_Studio_System_GetBus(system: ?*FMOD_STUDIO_SYSTEM, pathOrID: [*c]const u8, bus: [*c]?*FMOD_STUDIO_BUS) FMOD_RESULT;
pub extern fn FMOD_Studio_System_GetVCA(system: ?*FMOD_STUDIO_SYSTEM, pathOrID: [*c]const u8, vca: [*c]?*FMOD_STUDIO_VCA) FMOD_RESULT;
pub extern fn FMOD_Studio_System_GetBank(system: ?*FMOD_STUDIO_SYSTEM, pathOrID: [*c]const u8, bank: [*c]?*FMOD_STUDIO_BANK) FMOD_RESULT;
pub extern fn FMOD_Studio_System_GetEventByID(system: ?*FMOD_STUDIO_SYSTEM, id: [*c]const FMOD_GUID, event: [*c]?*FMOD_STUDIO_EVENTDESCRIPTION) FMOD_RESULT;
pub extern fn FMOD_Studio_System_GetBusByID(system: ?*FMOD_STUDIO_SYSTEM, id: [*c]const FMOD_GUID, bus: [*c]?*FMOD_STUDIO_BUS) FMOD_RESULT;
pub extern fn FMOD_Studio_System_GetVCAByID(system: ?*FMOD_STUDIO_SYSTEM, id: [*c]const FMOD_GUID, vca: [*c]?*FMOD_STUDIO_VCA) FMOD_RESULT;
pub extern fn FMOD_Studio_System_GetBankByID(system: ?*FMOD_STUDIO_SYSTEM, id: [*c]const FMOD_GUID, bank: [*c]?*FMOD_STUDIO_BANK) FMOD_RESULT;
pub extern fn FMOD_Studio_System_GetSoundInfo(system: ?*FMOD_STUDIO_SYSTEM, key: [*c]const u8, info: [*c]FMOD_STUDIO_SOUND_INFO) FMOD_RESULT;
pub extern fn FMOD_Studio_System_GetParameterDescriptionByName(system: ?*FMOD_STUDIO_SYSTEM, name: [*c]const u8, parameter: [*c]FMOD_STUDIO_PARAMETER_DESCRIPTION) FMOD_RESULT;
pub extern fn FMOD_Studio_System_GetParameterDescriptionByID(system: ?*FMOD_STUDIO_SYSTEM, id: FMOD_STUDIO_PARAMETER_ID, parameter: [*c]FMOD_STUDIO_PARAMETER_DESCRIPTION) FMOD_RESULT;
pub extern fn FMOD_Studio_System_GetParameterByID(system: ?*FMOD_STUDIO_SYSTEM, id: FMOD_STUDIO_PARAMETER_ID, value: [*c]f32, finalvalue: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Studio_System_SetParameterByID(system: ?*FMOD_STUDIO_SYSTEM, id: FMOD_STUDIO_PARAMETER_ID, value: f32, ignoreseekspeed: FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Studio_System_SetParametersByIDs(system: ?*FMOD_STUDIO_SYSTEM, ids: [*c]const FMOD_STUDIO_PARAMETER_ID, values: [*c]f32, count: c_int, ignoreseekspeed: FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Studio_System_GetParameterByName(system: ?*FMOD_STUDIO_SYSTEM, name: [*c]const u8, value: [*c]f32, finalvalue: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Studio_System_SetParameterByName(system: ?*FMOD_STUDIO_SYSTEM, name: [*c]const u8, value: f32, ignoreseekspeed: FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Studio_System_LookupID(system: ?*FMOD_STUDIO_SYSTEM, path: [*c]const u8, id: [*c]FMOD_GUID) FMOD_RESULT;
pub extern fn FMOD_Studio_System_LookupPath(system: ?*FMOD_STUDIO_SYSTEM, id: [*c]const FMOD_GUID, path: [*c]u8, size: c_int, retrieved: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Studio_System_GetNumListeners(system: ?*FMOD_STUDIO_SYSTEM, numlisteners: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Studio_System_SetNumListeners(system: ?*FMOD_STUDIO_SYSTEM, numlisteners: c_int) FMOD_RESULT;
pub extern fn FMOD_Studio_System_GetListenerAttributes(system: ?*FMOD_STUDIO_SYSTEM, index: c_int, attributes: [*c]FMOD_3D_ATTRIBUTES, attenuationposition: [*c]FMOD_VECTOR) FMOD_RESULT;
pub extern fn FMOD_Studio_System_SetListenerAttributes(system: ?*FMOD_STUDIO_SYSTEM, index: c_int, attributes: [*c]const FMOD_3D_ATTRIBUTES, attenuationposition: [*c]const FMOD_VECTOR) FMOD_RESULT;
pub extern fn FMOD_Studio_System_GetListenerWeight(system: ?*FMOD_STUDIO_SYSTEM, index: c_int, weight: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Studio_System_SetListenerWeight(system: ?*FMOD_STUDIO_SYSTEM, index: c_int, weight: f32) FMOD_RESULT;
pub extern fn FMOD_Studio_System_LoadBankFile(system: ?*FMOD_STUDIO_SYSTEM, filename: [*c]const u8, flags: FMOD_STUDIO_LOAD_BANK_FLAGS, bank: [*c]?*FMOD_STUDIO_BANK) FMOD_RESULT;
pub extern fn FMOD_Studio_System_LoadBankMemory(system: ?*FMOD_STUDIO_SYSTEM, buffer: [*c]const u8, length: c_int, mode: FMOD_STUDIO_LOAD_MEMORY_MODE, flags: FMOD_STUDIO_LOAD_BANK_FLAGS, bank: [*c]?*FMOD_STUDIO_BANK) FMOD_RESULT;
pub extern fn FMOD_Studio_System_LoadBankCustom(system: ?*FMOD_STUDIO_SYSTEM, info: [*c]const FMOD_STUDIO_BANK_INFO, flags: FMOD_STUDIO_LOAD_BANK_FLAGS, bank: [*c]?*FMOD_STUDIO_BANK) FMOD_RESULT;
pub extern fn FMOD_Studio_System_RegisterPlugin(system: ?*FMOD_STUDIO_SYSTEM, description: [*c]const FMOD_DSP_DESCRIPTION) FMOD_RESULT;
pub extern fn FMOD_Studio_System_UnregisterPlugin(system: ?*FMOD_STUDIO_SYSTEM, name: [*c]const u8) FMOD_RESULT;
pub extern fn FMOD_Studio_System_UnloadAll(system: ?*FMOD_STUDIO_SYSTEM) FMOD_RESULT;
pub extern fn FMOD_Studio_System_FlushCommands(system: ?*FMOD_STUDIO_SYSTEM) FMOD_RESULT;
pub extern fn FMOD_Studio_System_FlushSampleLoading(system: ?*FMOD_STUDIO_SYSTEM) FMOD_RESULT;
pub extern fn FMOD_Studio_System_StartCommandCapture(system: ?*FMOD_STUDIO_SYSTEM, filename: [*c]const u8, flags: FMOD_STUDIO_COMMANDCAPTURE_FLAGS) FMOD_RESULT;
pub extern fn FMOD_Studio_System_StopCommandCapture(system: ?*FMOD_STUDIO_SYSTEM) FMOD_RESULT;
pub extern fn FMOD_Studio_System_LoadCommandReplay(system: ?*FMOD_STUDIO_SYSTEM, filename: [*c]const u8, flags: FMOD_STUDIO_COMMANDREPLAY_FLAGS, replay: [*c]?*FMOD_STUDIO_COMMANDREPLAY) FMOD_RESULT;
pub extern fn FMOD_Studio_System_GetBankCount(system: ?*FMOD_STUDIO_SYSTEM, count: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Studio_System_GetBankList(system: ?*FMOD_STUDIO_SYSTEM, array: [*c]?*FMOD_STUDIO_BANK, capacity: c_int, count: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Studio_System_GetParameterDescriptionCount(system: ?*FMOD_STUDIO_SYSTEM, count: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Studio_System_GetParameterDescriptionList(system: ?*FMOD_STUDIO_SYSTEM, array: [*c]FMOD_STUDIO_PARAMETER_DESCRIPTION, capacity: c_int, count: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Studio_System_GetCPUUsage(system: ?*FMOD_STUDIO_SYSTEM, usage: [*c]FMOD_STUDIO_CPU_USAGE) FMOD_RESULT;
pub extern fn FMOD_Studio_System_GetBufferUsage(system: ?*FMOD_STUDIO_SYSTEM, usage: [*c]FMOD_STUDIO_BUFFER_USAGE) FMOD_RESULT;
pub extern fn FMOD_Studio_System_ResetBufferUsage(system: ?*FMOD_STUDIO_SYSTEM) FMOD_RESULT;
pub extern fn FMOD_Studio_System_SetCallback(system: ?*FMOD_STUDIO_SYSTEM, callback: FMOD_STUDIO_SYSTEM_CALLBACK, callbackmask: FMOD_STUDIO_SYSTEM_CALLBACK_TYPE) FMOD_RESULT;
pub extern fn FMOD_Studio_System_SetUserData(system: ?*FMOD_STUDIO_SYSTEM, userdata: ?*c_void) FMOD_RESULT;
pub extern fn FMOD_Studio_System_GetUserData(system: ?*FMOD_STUDIO_SYSTEM, userdata: [*c]?*c_void) FMOD_RESULT;
pub extern fn FMOD_Studio_System_GetMemoryUsage(system: ?*FMOD_STUDIO_SYSTEM, memoryusage: [*c]FMOD_STUDIO_MEMORY_USAGE) FMOD_RESULT;
pub extern fn FMOD_Studio_EventDescription_IsValid(eventdescription: ?*FMOD_STUDIO_EVENTDESCRIPTION) FMOD_BOOL;
pub extern fn FMOD_Studio_EventDescription_GetID(eventdescription: ?*FMOD_STUDIO_EVENTDESCRIPTION, id: [*c]FMOD_GUID) FMOD_RESULT;
pub extern fn FMOD_Studio_EventDescription_GetPath(eventdescription: ?*FMOD_STUDIO_EVENTDESCRIPTION, path: [*c]u8, size: c_int, retrieved: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Studio_EventDescription_GetParameterDescriptionCount(eventdescription: ?*FMOD_STUDIO_EVENTDESCRIPTION, count: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Studio_EventDescription_GetParameterDescriptionByIndex(eventdescription: ?*FMOD_STUDIO_EVENTDESCRIPTION, index: c_int, parameter: [*c]FMOD_STUDIO_PARAMETER_DESCRIPTION) FMOD_RESULT;
pub extern fn FMOD_Studio_EventDescription_GetParameterDescriptionByName(eventdescription: ?*FMOD_STUDIO_EVENTDESCRIPTION, name: [*c]const u8, parameter: [*c]FMOD_STUDIO_PARAMETER_DESCRIPTION) FMOD_RESULT;
pub extern fn FMOD_Studio_EventDescription_GetParameterDescriptionByID(eventdescription: ?*FMOD_STUDIO_EVENTDESCRIPTION, id: FMOD_STUDIO_PARAMETER_ID, parameter: [*c]FMOD_STUDIO_PARAMETER_DESCRIPTION) FMOD_RESULT;
pub extern fn FMOD_Studio_EventDescription_GetUserPropertyCount(eventdescription: ?*FMOD_STUDIO_EVENTDESCRIPTION, count: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Studio_EventDescription_GetUserPropertyByIndex(eventdescription: ?*FMOD_STUDIO_EVENTDESCRIPTION, index: c_int, property: [*c]FMOD_STUDIO_USER_PROPERTY) FMOD_RESULT;
pub extern fn FMOD_Studio_EventDescription_GetUserProperty(eventdescription: ?*FMOD_STUDIO_EVENTDESCRIPTION, name: [*c]const u8, property: [*c]FMOD_STUDIO_USER_PROPERTY) FMOD_RESULT;
pub extern fn FMOD_Studio_EventDescription_GetLength(eventdescription: ?*FMOD_STUDIO_EVENTDESCRIPTION, length: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Studio_EventDescription_GetMinimumDistance(eventdescription: ?*FMOD_STUDIO_EVENTDESCRIPTION, distance: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Studio_EventDescription_GetMaximumDistance(eventdescription: ?*FMOD_STUDIO_EVENTDESCRIPTION, distance: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Studio_EventDescription_GetSoundSize(eventdescription: ?*FMOD_STUDIO_EVENTDESCRIPTION, size: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Studio_EventDescription_IsSnapshot(eventdescription: ?*FMOD_STUDIO_EVENTDESCRIPTION, snapshot: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Studio_EventDescription_IsOneshot(eventdescription: ?*FMOD_STUDIO_EVENTDESCRIPTION, oneshot: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Studio_EventDescription_IsStream(eventdescription: ?*FMOD_STUDIO_EVENTDESCRIPTION, isStream: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Studio_EventDescription_Is3D(eventdescription: ?*FMOD_STUDIO_EVENTDESCRIPTION, is3D: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Studio_EventDescription_IsDopplerEnabled(eventdescription: ?*FMOD_STUDIO_EVENTDESCRIPTION, doppler: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Studio_EventDescription_HasCue(eventdescription: ?*FMOD_STUDIO_EVENTDESCRIPTION, cue: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Studio_EventDescription_CreateInstance(eventdescription: ?*FMOD_STUDIO_EVENTDESCRIPTION, instance: [*c]?*FMOD_STUDIO_EVENTINSTANCE) FMOD_RESULT;
pub extern fn FMOD_Studio_EventDescription_GetInstanceCount(eventdescription: ?*FMOD_STUDIO_EVENTDESCRIPTION, count: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Studio_EventDescription_GetInstanceList(eventdescription: ?*FMOD_STUDIO_EVENTDESCRIPTION, array: [*c]?*FMOD_STUDIO_EVENTINSTANCE, capacity: c_int, count: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Studio_EventDescription_LoadSampleData(eventdescription: ?*FMOD_STUDIO_EVENTDESCRIPTION) FMOD_RESULT;
pub extern fn FMOD_Studio_EventDescription_UnloadSampleData(eventdescription: ?*FMOD_STUDIO_EVENTDESCRIPTION) FMOD_RESULT;
pub extern fn FMOD_Studio_EventDescription_GetSampleLoadingState(eventdescription: ?*FMOD_STUDIO_EVENTDESCRIPTION, state: [*c]FMOD_STUDIO_LOADING_STATE) FMOD_RESULT;
pub extern fn FMOD_Studio_EventDescription_ReleaseAllInstances(eventdescription: ?*FMOD_STUDIO_EVENTDESCRIPTION) FMOD_RESULT;
pub extern fn FMOD_Studio_EventDescription_SetCallback(eventdescription: ?*FMOD_STUDIO_EVENTDESCRIPTION, callback: FMOD_STUDIO_EVENT_CALLBACK, callbackmask: FMOD_STUDIO_EVENT_CALLBACK_TYPE) FMOD_RESULT;
pub extern fn FMOD_Studio_EventDescription_GetUserData(eventdescription: ?*FMOD_STUDIO_EVENTDESCRIPTION, userdata: [*c]?*c_void) FMOD_RESULT;
pub extern fn FMOD_Studio_EventDescription_SetUserData(eventdescription: ?*FMOD_STUDIO_EVENTDESCRIPTION, userdata: ?*c_void) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_IsValid(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE) FMOD_BOOL;
pub extern fn FMOD_Studio_EventInstance_GetDescription(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE, description: [*c]?*FMOD_STUDIO_EVENTDESCRIPTION) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_GetVolume(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE, volume: [*c]f32, finalvolume: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_SetVolume(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE, volume: f32) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_GetPitch(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE, pitch: [*c]f32, finalpitch: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_SetPitch(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE, pitch: f32) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_Get3DAttributes(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE, attributes: [*c]FMOD_3D_ATTRIBUTES) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_Set3DAttributes(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE, attributes: [*c]FMOD_3D_ATTRIBUTES) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_GetListenerMask(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE, mask: [*c]c_uint) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_SetListenerMask(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE, mask: c_uint) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_GetProperty(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE, index: FMOD_STUDIO_EVENT_PROPERTY, value: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_SetProperty(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE, index: FMOD_STUDIO_EVENT_PROPERTY, value: f32) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_GetReverbLevel(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE, index: c_int, level: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_SetReverbLevel(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE, index: c_int, level: f32) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_GetPaused(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE, paused: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_SetPaused(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE, paused: FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_Start(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_Stop(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE, mode: FMOD_STUDIO_STOP_MODE) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_GetTimelinePosition(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE, position: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_SetTimelinePosition(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE, position: c_int) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_GetPlaybackState(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE, state: [*c]FMOD_STUDIO_PLAYBACK_STATE) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_GetChannelGroup(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE, group: [*c]?*FMOD_CHANNELGROUP) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_Release(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_IsVirtual(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE, virtualstate: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_GetParameterByName(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE, name: [*c]const u8, value: [*c]f32, finalvalue: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_SetParameterByName(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE, name: [*c]const u8, value: f32, ignoreseekspeed: FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_GetParameterByID(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE, id: FMOD_STUDIO_PARAMETER_ID, value: [*c]f32, finalvalue: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_SetParameterByID(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE, id: FMOD_STUDIO_PARAMETER_ID, value: f32, ignoreseekspeed: FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_SetParametersByIDs(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE, ids: [*c]const FMOD_STUDIO_PARAMETER_ID, values: [*c]f32, count: c_int, ignoreseekspeed: FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_TriggerCue(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_SetCallback(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE, callback: FMOD_STUDIO_EVENT_CALLBACK, callbackmask: FMOD_STUDIO_EVENT_CALLBACK_TYPE) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_GetUserData(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE, userdata: [*c]?*c_void) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_SetUserData(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE, userdata: ?*c_void) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_GetCPUUsage(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE, exclusive: [*c]c_uint, inclusive: [*c]c_uint) FMOD_RESULT;
pub extern fn FMOD_Studio_EventInstance_GetMemoryUsage(eventinstance: ?*FMOD_STUDIO_EVENTINSTANCE, memoryusage: [*c]FMOD_STUDIO_MEMORY_USAGE) FMOD_RESULT;
pub extern fn FMOD_Studio_Bus_IsValid(bus: ?*FMOD_STUDIO_BUS) FMOD_BOOL;
pub extern fn FMOD_Studio_Bus_GetID(bus: ?*FMOD_STUDIO_BUS, id: [*c]FMOD_GUID) FMOD_RESULT;
pub extern fn FMOD_Studio_Bus_GetPath(bus: ?*FMOD_STUDIO_BUS, path: [*c]u8, size: c_int, retrieved: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Studio_Bus_GetVolume(bus: ?*FMOD_STUDIO_BUS, volume: [*c]f32, finalvolume: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Studio_Bus_SetVolume(bus: ?*FMOD_STUDIO_BUS, volume: f32) FMOD_RESULT;
pub extern fn FMOD_Studio_Bus_GetPaused(bus: ?*FMOD_STUDIO_BUS, paused: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Studio_Bus_SetPaused(bus: ?*FMOD_STUDIO_BUS, paused: FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Studio_Bus_GetMute(bus: ?*FMOD_STUDIO_BUS, mute: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Studio_Bus_SetMute(bus: ?*FMOD_STUDIO_BUS, mute: FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Studio_Bus_StopAllEvents(bus: ?*FMOD_STUDIO_BUS, mode: FMOD_STUDIO_STOP_MODE) FMOD_RESULT;
pub extern fn FMOD_Studio_Bus_LockChannelGroup(bus: ?*FMOD_STUDIO_BUS) FMOD_RESULT;
pub extern fn FMOD_Studio_Bus_UnlockChannelGroup(bus: ?*FMOD_STUDIO_BUS) FMOD_RESULT;
pub extern fn FMOD_Studio_Bus_GetChannelGroup(bus: ?*FMOD_STUDIO_BUS, group: [*c]?*FMOD_CHANNELGROUP) FMOD_RESULT;
pub extern fn FMOD_Studio_Bus_GetCPUUsage(bus: ?*FMOD_STUDIO_BUS, exclusive: [*c]c_uint, inclusive: [*c]c_uint) FMOD_RESULT;
pub extern fn FMOD_Studio_Bus_GetMemoryUsage(bus: ?*FMOD_STUDIO_BUS, memoryusage: [*c]FMOD_STUDIO_MEMORY_USAGE) FMOD_RESULT;
pub extern fn FMOD_Studio_VCA_IsValid(vca: ?*FMOD_STUDIO_VCA) FMOD_BOOL;
pub extern fn FMOD_Studio_VCA_GetID(vca: ?*FMOD_STUDIO_VCA, id: [*c]FMOD_GUID) FMOD_RESULT;
pub extern fn FMOD_Studio_VCA_GetPath(vca: ?*FMOD_STUDIO_VCA, path: [*c]u8, size: c_int, retrieved: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Studio_VCA_GetVolume(vca: ?*FMOD_STUDIO_VCA, volume: [*c]f32, finalvolume: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Studio_VCA_SetVolume(vca: ?*FMOD_STUDIO_VCA, volume: f32) FMOD_RESULT;
pub extern fn FMOD_Studio_Bank_IsValid(bank: ?*FMOD_STUDIO_BANK) FMOD_BOOL;
pub extern fn FMOD_Studio_Bank_GetID(bank: ?*FMOD_STUDIO_BANK, id: [*c]FMOD_GUID) FMOD_RESULT;
pub extern fn FMOD_Studio_Bank_GetPath(bank: ?*FMOD_STUDIO_BANK, path: [*c]u8, size: c_int, retrieved: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Studio_Bank_Unload(bank: ?*FMOD_STUDIO_BANK) FMOD_RESULT;
pub extern fn FMOD_Studio_Bank_LoadSampleData(bank: ?*FMOD_STUDIO_BANK) FMOD_RESULT;
pub extern fn FMOD_Studio_Bank_UnloadSampleData(bank: ?*FMOD_STUDIO_BANK) FMOD_RESULT;
pub extern fn FMOD_Studio_Bank_GetLoadingState(bank: ?*FMOD_STUDIO_BANK, state: [*c]FMOD_STUDIO_LOADING_STATE) FMOD_RESULT;
pub extern fn FMOD_Studio_Bank_GetSampleLoadingState(bank: ?*FMOD_STUDIO_BANK, state: [*c]FMOD_STUDIO_LOADING_STATE) FMOD_RESULT;
pub extern fn FMOD_Studio_Bank_GetStringCount(bank: ?*FMOD_STUDIO_BANK, count: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Studio_Bank_GetStringInfo(bank: ?*FMOD_STUDIO_BANK, index: c_int, id: [*c]FMOD_GUID, path: [*c]u8, size: c_int, retrieved: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Studio_Bank_GetEventCount(bank: ?*FMOD_STUDIO_BANK, count: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Studio_Bank_GetEventList(bank: ?*FMOD_STUDIO_BANK, array: [*c]?*FMOD_STUDIO_EVENTDESCRIPTION, capacity: c_int, count: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Studio_Bank_GetBusCount(bank: ?*FMOD_STUDIO_BANK, count: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Studio_Bank_GetBusList(bank: ?*FMOD_STUDIO_BANK, array: [*c]?*FMOD_STUDIO_BUS, capacity: c_int, count: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Studio_Bank_GetVCACount(bank: ?*FMOD_STUDIO_BANK, count: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Studio_Bank_GetVCAList(bank: ?*FMOD_STUDIO_BANK, array: [*c]?*FMOD_STUDIO_VCA, capacity: c_int, count: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Studio_Bank_GetUserData(bank: ?*FMOD_STUDIO_BANK, userdata: [*c]?*c_void) FMOD_RESULT;
pub extern fn FMOD_Studio_Bank_SetUserData(bank: ?*FMOD_STUDIO_BANK, userdata: ?*c_void) FMOD_RESULT;
pub extern fn FMOD_Studio_CommandReplay_IsValid(replay: ?*FMOD_STUDIO_COMMANDREPLAY) FMOD_BOOL;
pub extern fn FMOD_Studio_CommandReplay_GetSystem(replay: ?*FMOD_STUDIO_COMMANDREPLAY, system: [*c]?*FMOD_STUDIO_SYSTEM) FMOD_RESULT;
pub extern fn FMOD_Studio_CommandReplay_GetLength(replay: ?*FMOD_STUDIO_COMMANDREPLAY, length: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Studio_CommandReplay_GetCommandCount(replay: ?*FMOD_STUDIO_COMMANDREPLAY, count: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Studio_CommandReplay_GetCommandInfo(replay: ?*FMOD_STUDIO_COMMANDREPLAY, commandindex: c_int, info: [*c]FMOD_STUDIO_COMMAND_INFO) FMOD_RESULT;
pub extern fn FMOD_Studio_CommandReplay_GetCommandString(replay: ?*FMOD_STUDIO_COMMANDREPLAY, commandindex: c_int, buffer: [*c]u8, length: c_int) FMOD_RESULT;
pub extern fn FMOD_Studio_CommandReplay_GetCommandAtTime(replay: ?*FMOD_STUDIO_COMMANDREPLAY, time: f32, commandindex: [*c]c_int) FMOD_RESULT;
pub extern fn FMOD_Studio_CommandReplay_SetBankPath(replay: ?*FMOD_STUDIO_COMMANDREPLAY, bankPath: [*c]const u8) FMOD_RESULT;
pub extern fn FMOD_Studio_CommandReplay_Start(replay: ?*FMOD_STUDIO_COMMANDREPLAY) FMOD_RESULT;
pub extern fn FMOD_Studio_CommandReplay_Stop(replay: ?*FMOD_STUDIO_COMMANDREPLAY) FMOD_RESULT;
pub extern fn FMOD_Studio_CommandReplay_SeekToTime(replay: ?*FMOD_STUDIO_COMMANDREPLAY, time: f32) FMOD_RESULT;
pub extern fn FMOD_Studio_CommandReplay_SeekToCommand(replay: ?*FMOD_STUDIO_COMMANDREPLAY, commandindex: c_int) FMOD_RESULT;
pub extern fn FMOD_Studio_CommandReplay_GetPaused(replay: ?*FMOD_STUDIO_COMMANDREPLAY, paused: [*c]FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Studio_CommandReplay_SetPaused(replay: ?*FMOD_STUDIO_COMMANDREPLAY, paused: FMOD_BOOL) FMOD_RESULT;
pub extern fn FMOD_Studio_CommandReplay_GetPlaybackState(replay: ?*FMOD_STUDIO_COMMANDREPLAY, state: [*c]FMOD_STUDIO_PLAYBACK_STATE) FMOD_RESULT;
pub extern fn FMOD_Studio_CommandReplay_GetCurrentCommand(replay: ?*FMOD_STUDIO_COMMANDREPLAY, commandindex: [*c]c_int, currenttime: [*c]f32) FMOD_RESULT;
pub extern fn FMOD_Studio_CommandReplay_Release(replay: ?*FMOD_STUDIO_COMMANDREPLAY) FMOD_RESULT;
pub extern fn FMOD_Studio_CommandReplay_SetFrameCallback(replay: ?*FMOD_STUDIO_COMMANDREPLAY, callback: FMOD_STUDIO_COMMANDREPLAY_FRAME_CALLBACK) FMOD_RESULT;
pub extern fn FMOD_Studio_CommandReplay_SetLoadBankCallback(replay: ?*FMOD_STUDIO_COMMANDREPLAY, callback: FMOD_STUDIO_COMMANDREPLAY_LOAD_BANK_CALLBACK) FMOD_RESULT;
pub extern fn FMOD_Studio_CommandReplay_SetCreateInstanceCallback(replay: ?*FMOD_STUDIO_COMMANDREPLAY, callback: FMOD_STUDIO_COMMANDREPLAY_CREATE_INSTANCE_CALLBACK) FMOD_RESULT;
pub extern fn FMOD_Studio_CommandReplay_GetUserData(replay: ?*FMOD_STUDIO_COMMANDREPLAY, userdata: [*c]?*c_void) FMOD_RESULT;
pub extern fn FMOD_Studio_CommandReplay_SetUserData(replay: ?*FMOD_STUDIO_COMMANDREPLAY, userdata: ?*c_void) FMOD_RESULT;
pub const FMOD_PRESET_OFF = @compileError("unable to translate C expr: unexpected token .LBrace"); // ../../core/inc/fmod_common.h:269:9
pub const FMOD_PRESET_GENERIC = @compileError("unable to translate C expr: unexpected token .LBrace"); // ../../core/inc/fmod_common.h:270:9
pub const FMOD_PRESET_PADDEDCELL = @compileError("unable to translate C expr: unexpected token .LBrace"); // ../../core/inc/fmod_common.h:271:9
pub const FMOD_PRESET_ROOM = @compileError("unable to translate C expr: unexpected token .LBrace"); // ../../core/inc/fmod_common.h:272:9
pub const FMOD_PRESET_BATHROOM = @compileError("unable to translate C expr: unexpected token .LBrace"); // ../../core/inc/fmod_common.h:273:9
pub const FMOD_PRESET_LIVINGROOM = @compileError("unable to translate C expr: unexpected token .LBrace"); // ../../core/inc/fmod_common.h:274:9
pub const FMOD_PRESET_STONEROOM = @compileError("unable to translate C expr: unexpected token .LBrace"); // ../../core/inc/fmod_common.h:275:9
pub const FMOD_PRESET_AUDITORIUM = @compileError("unable to translate C expr: unexpected token .LBrace"); // ../../core/inc/fmod_common.h:276:9
pub const FMOD_PRESET_CONCERTHALL = @compileError("unable to translate C expr: unexpected token .LBrace"); // ../../core/inc/fmod_common.h:277:9
pub const FMOD_PRESET_CAVE = @compileError("unable to translate C expr: unexpected token .LBrace"); // ../../core/inc/fmod_common.h:278:9
pub const FMOD_PRESET_ARENA = @compileError("unable to translate C expr: unexpected token .LBrace"); // ../../core/inc/fmod_common.h:279:9
pub const FMOD_PRESET_HANGAR = @compileError("unable to translate C expr: unexpected token .LBrace"); // ../../core/inc/fmod_common.h:280:9
pub const FMOD_PRESET_CARPETTEDHALLWAY = @compileError("unable to translate C expr: unexpected token .LBrace"); // ../../core/inc/fmod_common.h:281:9
pub const FMOD_PRESET_HALLWAY = @compileError("unable to translate C expr: unexpected token .LBrace"); // ../../core/inc/fmod_common.h:282:9
pub const FMOD_PRESET_STONECORRIDOR = @compileError("unable to translate C expr: unexpected token .LBrace"); // ../../core/inc/fmod_common.h:283:9
pub const FMOD_PRESET_ALLEY = @compileError("unable to translate C expr: unexpected token .LBrace"); // ../../core/inc/fmod_common.h:284:9
pub const FMOD_PRESET_FOREST = @compileError("unable to translate C expr: unexpected token .LBrace"); // ../../core/inc/fmod_common.h:285:9
pub const FMOD_PRESET_CITY = @compileError("unable to translate C expr: unexpected token .LBrace"); // ../../core/inc/fmod_common.h:286:9
pub const FMOD_PRESET_MOUNTAINS = @compileError("unable to translate C expr: unexpected token .LBrace"); // ../../core/inc/fmod_common.h:287:9
pub const FMOD_PRESET_QUARRY = @compileError("unable to translate C expr: unexpected token .LBrace"); // ../../core/inc/fmod_common.h:288:9
pub const FMOD_PRESET_PLAIN = @compileError("unable to translate C expr: unexpected token .LBrace"); // ../../core/inc/fmod_common.h:289:9
pub const FMOD_PRESET_PARKINGLOT = @compileError("unable to translate C expr: unexpected token .LBrace"); // ../../core/inc/fmod_common.h:290:9
pub const FMOD_PRESET_SEWERPIPE = @compileError("unable to translate C expr: unexpected token .LBrace"); // ../../core/inc/fmod_common.h:291:9
pub const FMOD_PRESET_UNDERWATER = @compileError("unable to translate C expr: unexpected token .LBrace"); // ../../core/inc/fmod_common.h:292:9
pub const FMOD_DSP_INIT_PARAMDESC_FLOAT = @compileError("unable to translate C expr: unexpected token .Semicolon"); // ../../core/inc/fmod_dsp.h:310:9
pub const FMOD_DSP_INIT_PARAMDESC_FLOAT_WITH_MAPPING = @compileError("unable to translate C expr: unexpected token .Semicolon"); // ../../core/inc/fmod_dsp.h:321:9
pub const FMOD_DSP_INIT_PARAMDESC_INT = @compileError("unable to translate C expr: unexpected token .Semicolon"); // ../../core/inc/fmod_dsp.h:335:9
pub const FMOD_DSP_INIT_PARAMDESC_INT_ENUMERATED = @compileError("unable to translate C expr: unexpected token .Semicolon"); // ../../core/inc/fmod_dsp.h:347:9
pub const FMOD_DSP_INIT_PARAMDESC_BOOL = @compileError("unable to translate C expr: unexpected token .Semicolon"); // ../../core/inc/fmod_dsp.h:359:9
pub const FMOD_DSP_INIT_PARAMDESC_DATA = @compileError("unable to translate C expr: unexpected token .Semicolon"); // ../../core/inc/fmod_dsp.h:368:9
pub const FMOD_DSP_LOG = @compileError("unable to translate C expr: expected ')'"); // ../../core/inc/fmod_dsp.h:382:9
pub const FMOD_OUTPUT_LOG = @compileError("unable to translate C expr: expected ')'"); // ../../core/inc/fmod_output.h:122:9
// pub const __llvm__ = @as(c_int, 1);
// pub const __clang__ = @as(c_int, 1);
// pub const __clang_major__ = @as(c_int, 12);
// pub const __clang_minor__ = @as(c_int, 0);
// pub const __clang_patchlevel__ = @as(c_int, 1);
// pub const __clang_version__ = "12.0.1 (https://github.com/llvm/llvm-project 328a6ec955327c6d56b6bc3478c723dd3cd468ef)";
// pub const __GNUC__ = @as(c_int, 4);
// pub const __GNUC_MINOR__ = @as(c_int, 2);
// pub const __GNUC_PATCHLEVEL__ = @as(c_int, 1);
// pub const __GXX_ABI_VERSION = @as(c_int, 1002);
// pub const __ATOMIC_RELAXED = @as(c_int, 0);
// pub const __ATOMIC_CONSUME = @as(c_int, 1);
// pub const __ATOMIC_ACQUIRE = @as(c_int, 2);
// pub const __ATOMIC_RELEASE = @as(c_int, 3);
// pub const __ATOMIC_ACQ_REL = @as(c_int, 4);
// pub const __ATOMIC_SEQ_CST = @as(c_int, 5);
// pub const __OPENCL_MEMORY_SCOPE_WORK_ITEM = @as(c_int, 0);
// pub const __OPENCL_MEMORY_SCOPE_WORK_GROUP = @as(c_int, 1);
// pub const __OPENCL_MEMORY_SCOPE_DEVICE = @as(c_int, 2);
// pub const __OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES = @as(c_int, 3);
// pub const __OPENCL_MEMORY_SCOPE_SUB_GROUP = @as(c_int, 4);
// pub const __PRAGMA_REDEFINE_EXTNAME = @as(c_int, 1);
// pub const __VERSION__ = "Clang 12.0.1 (https://github.com/llvm/llvm-project 328a6ec955327c6d56b6bc3478c723dd3cd468ef)";
// pub const __OBJC_BOOL_IS_BOOL = @as(c_int, 0);
// pub const __CONSTANT_CFSTRINGS__ = @as(c_int, 1);
// pub const __SEH__ = @as(c_int, 1);
// pub const __OPTIMIZE__ = @as(c_int, 1);
// pub const __ORDER_LITTLE_ENDIAN__ = @as(c_int, 1234);
// pub const __ORDER_BIG_ENDIAN__ = @as(c_int, 4321);
// pub const __ORDER_PDP_ENDIAN__ = @as(c_int, 3412);
// pub const __BYTE_ORDER__ = __ORDER_LITTLE_ENDIAN__;
// pub const __LITTLE_ENDIAN__ = @as(c_int, 1);
// pub const __CHAR_BIT__ = @as(c_int, 8);
// pub const __SCHAR_MAX__ = @as(c_int, 127);
// pub const __SHRT_MAX__ = @as(c_int, 32767);
// pub const __INT_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 2147483647, .decimal);
// pub const __LONG_MAX__ = @as(c_long, 2147483647);
// pub const __LONG_LONG_MAX__ = @as(c_longlong, 9223372036854775807);
// pub const __WCHAR_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 65535, .decimal);
// pub const __WINT_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 65535, .decimal);
// pub const __INTMAX_MAX__ = @as(c_longlong, 9223372036854775807);
// pub const __SIZE_MAX__ = @as(c_ulonglong, 18446744073709551615);
// pub const __UINTMAX_MAX__ = @as(c_ulonglong, 18446744073709551615);
// pub const __PTRDIFF_MAX__ = @as(c_longlong, 9223372036854775807);
// pub const __INTPTR_MAX__ = @as(c_longlong, 9223372036854775807);
// pub const __UINTPTR_MAX__ = @as(c_ulonglong, 18446744073709551615);
// pub const __SIZEOF_DOUBLE__ = @as(c_int, 8);
// pub const __SIZEOF_FLOAT__ = @as(c_int, 4);
// pub const __SIZEOF_INT__ = @as(c_int, 4);
// pub const __SIZEOF_LONG__ = @as(c_int, 4);
// pub const __SIZEOF_LONG_DOUBLE__ = @as(c_int, 16);
// pub const __SIZEOF_LONG_LONG__ = @as(c_int, 8);
// pub const __SIZEOF_POINTER__ = @as(c_int, 8);
// pub const __SIZEOF_SHORT__ = @as(c_int, 2);
// pub const __SIZEOF_PTRDIFF_T__ = @as(c_int, 8);
// pub const __SIZEOF_SIZE_T__ = @as(c_int, 8);
// pub const __SIZEOF_WCHAR_T__ = @as(c_int, 2);
// pub const __SIZEOF_WINT_T__ = @as(c_int, 2);
// pub const __SIZEOF_INT128__ = @as(c_int, 16);
// pub const __INTMAX_TYPE__ = c_longlong;
// pub const __INTMAX_FMTd__ = "lld";
// pub const __INTMAX_FMTi__ = "lli";
// pub const __INTMAX_C_SUFFIX__ = LL;
// pub const __UINTMAX_TYPE__ = c_ulonglong;
// pub const __UINTMAX_FMTo__ = "llo";
// pub const __UINTMAX_FMTu__ = "llu";
// pub const __UINTMAX_FMTx__ = "llx";
// pub const __UINTMAX_FMTX__ = "llX";
// pub const __UINTMAX_C_SUFFIX__ = ULL;
// pub const __INTMAX_WIDTH__ = @as(c_int, 64);
// pub const __PTRDIFF_TYPE__ = c_longlong;
// pub const __PTRDIFF_FMTd__ = "lld";
// pub const __PTRDIFF_FMTi__ = "lli";
// pub const __PTRDIFF_WIDTH__ = @as(c_int, 64);
// pub const __INTPTR_TYPE__ = c_longlong;
// pub const __INTPTR_FMTd__ = "lld";
// pub const __INTPTR_FMTi__ = "lli";
// pub const __INTPTR_WIDTH__ = @as(c_int, 64);
// pub const __SIZE_TYPE__ = c_ulonglong;
// pub const __SIZE_FMTo__ = "llo";
// pub const __SIZE_FMTu__ = "llu";
// pub const __SIZE_FMTx__ = "llx";
// pub const __SIZE_FMTX__ = "llX";
// pub const __SIZE_WIDTH__ = @as(c_int, 64);
// pub const __WCHAR_TYPE__ = c_ushort;
// pub const __WCHAR_WIDTH__ = @as(c_int, 16);
// pub const __WINT_TYPE__ = c_ushort;
// pub const __WINT_WIDTH__ = @as(c_int, 16);
// pub const __SIG_ATOMIC_WIDTH__ = @as(c_int, 32);
// pub const __SIG_ATOMIC_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 2147483647, .decimal);
// pub const __CHAR16_TYPE__ = c_ushort;
// pub const __CHAR32_TYPE__ = c_uint;
// pub const __UINTMAX_WIDTH__ = @as(c_int, 64);
// pub const __UINTPTR_TYPE__ = c_ulonglong;
// pub const __UINTPTR_FMTo__ = "llo";
// pub const __UINTPTR_FMTu__ = "llu";
// pub const __UINTPTR_FMTx__ = "llx";
// pub const __UINTPTR_FMTX__ = "llX";
// pub const __UINTPTR_WIDTH__ = @as(c_int, 64);
// pub const __FLT_DENORM_MIN__ = @as(f32, 1.40129846e-45);
// pub const __FLT_HAS_DENORM__ = @as(c_int, 1);
// pub const __FLT_DIG__ = @as(c_int, 6);
// pub const __FLT_DECIMAL_DIG__ = @as(c_int, 9);
// pub const __FLT_EPSILON__ = @as(f32, 1.19209290e-7);
// pub const __FLT_HAS_INFINITY__ = @as(c_int, 1);
// pub const __FLT_HAS_QUIET_NAN__ = @as(c_int, 1);
// pub const __FLT_MANT_DIG__ = @as(c_int, 24);
// pub const __FLT_MAX_10_EXP__ = @as(c_int, 38);
// pub const __FLT_MAX_EXP__ = @as(c_int, 128);
// pub const __FLT_MAX__ = @as(f32, 3.40282347e+38);
// pub const __FLT_MIN_10_EXP__ = -@as(c_int, 37);
// pub const __FLT_MIN_EXP__ = -@as(c_int, 125);
// pub const __FLT_MIN__ = @as(f32, 1.17549435e-38);
// pub const __DBL_DENORM_MIN__ = 4.9406564584124654e-324;
// pub const __DBL_HAS_DENORM__ = @as(c_int, 1);
// pub const __DBL_DIG__ = @as(c_int, 15);
// pub const __DBL_DECIMAL_DIG__ = @as(c_int, 17);
// pub const __DBL_EPSILON__ = 2.2204460492503131e-16;
// pub const __DBL_HAS_INFINITY__ = @as(c_int, 1);
// pub const __DBL_HAS_QUIET_NAN__ = @as(c_int, 1);
// pub const __DBL_MANT_DIG__ = @as(c_int, 53);
// pub const __DBL_MAX_10_EXP__ = @as(c_int, 308);
// pub const __DBL_MAX_EXP__ = @as(c_int, 1024);
// pub const __DBL_MAX__ = 1.7976931348623157e+308;
// pub const __DBL_MIN_10_EXP__ = -@as(c_int, 307);
// pub const __DBL_MIN_EXP__ = -@as(c_int, 1021);
// pub const __DBL_MIN__ = 2.2250738585072014e-308;
// pub const __LDBL_DENORM_MIN__ = @as(c_longdouble, 3.64519953188247460253e-4951);
// pub const __LDBL_HAS_DENORM__ = @as(c_int, 1);
// pub const __LDBL_DIG__ = @as(c_int, 18);
// pub const __LDBL_DECIMAL_DIG__ = @as(c_int, 21);
// pub const __LDBL_EPSILON__ = @as(c_longdouble, 1.08420217248550443401e-19);
// pub const __LDBL_HAS_INFINITY__ = @as(c_int, 1);
// pub const __LDBL_HAS_QUIET_NAN__ = @as(c_int, 1);
// pub const __LDBL_MANT_DIG__ = @as(c_int, 64);
// pub const __LDBL_MAX_10_EXP__ = @as(c_int, 4932);
// pub const __LDBL_MAX_EXP__ = @as(c_int, 16384);
// pub const __LDBL_MAX__ = @as(c_longdouble, 1.18973149535723176502e+4932);
// pub const __LDBL_MIN_10_EXP__ = -@as(c_int, 4931);
// pub const __LDBL_MIN_EXP__ = -@as(c_int, 16381);
// pub const __LDBL_MIN__ = @as(c_longdouble, 3.36210314311209350626e-4932);
// pub const __POINTER_WIDTH__ = @as(c_int, 64);
// pub const __BIGGEST_ALIGNMENT__ = @as(c_int, 16);
// pub const __WCHAR_UNSIGNED__ = @as(c_int, 1);
// pub const __WINT_UNSIGNED__ = @as(c_int, 1);
// pub const __INT8_TYPE__ = i8;
// pub const __INT8_FMTd__ = "hhd";
// pub const __INT8_FMTi__ = "hhi";
// pub const __INT16_TYPE__ = c_short;
// pub const __INT16_FMTd__ = "hd";
// pub const __INT16_FMTi__ = "hi";
// pub const __INT32_TYPE__ = c_int;
// pub const __INT32_FMTd__ = "d";
// pub const __INT32_FMTi__ = "i";
// pub const __INT64_TYPE__ = c_longlong;
// pub const __INT64_FMTd__ = "lld";
// pub const __INT64_FMTi__ = "lli";
// pub const __INT64_C_SUFFIX__ = LL;
// pub const __UINT8_TYPE__ = u8;
// pub const __UINT8_FMTo__ = "hho";
// pub const __UINT8_FMTu__ = "hhu";
// pub const __UINT8_FMTx__ = "hhx";
// pub const __UINT8_FMTX__ = "hhX";
// pub const __UINT8_MAX__ = @as(c_int, 255);
// pub const __INT8_MAX__ = @as(c_int, 127);
// pub const __UINT16_TYPE__ = c_ushort;
// pub const __UINT16_FMTo__ = "ho";
// pub const __UINT16_FMTu__ = "hu";
// pub const __UINT16_FMTx__ = "hx";
// pub const __UINT16_FMTX__ = "hX";
// pub const __UINT16_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 65535, .decimal);
// pub const __INT16_MAX__ = @as(c_int, 32767);
// pub const __UINT32_TYPE__ = c_uint;
// pub const __UINT32_FMTo__ = "o";
// pub const __UINT32_FMTu__ = "u";
// pub const __UINT32_FMTx__ = "x";
// pub const __UINT32_FMTX__ = "X";
// pub const __UINT32_C_SUFFIX__ = U;
// pub const __UINT32_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_uint, 4294967295, .decimal);
// pub const __INT32_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 2147483647, .decimal);
// pub const __UINT64_TYPE__ = c_ulonglong;
// pub const __UINT64_FMTo__ = "llo";
// pub const __UINT64_FMTu__ = "llu";
// pub const __UINT64_FMTx__ = "llx";
// pub const __UINT64_FMTX__ = "llX";
// pub const __UINT64_C_SUFFIX__ = ULL;
// pub const __UINT64_MAX__ = @as(c_ulonglong, 18446744073709551615);
// pub const __INT64_MAX__ = @as(c_longlong, 9223372036854775807);
// pub const __INT_LEAST8_TYPE__ = i8;
// pub const __INT_LEAST8_MAX__ = @as(c_int, 127);
// pub const __INT_LEAST8_FMTd__ = "hhd";
// pub const __INT_LEAST8_FMTi__ = "hhi";
// pub const __UINT_LEAST8_TYPE__ = u8;
// pub const __UINT_LEAST8_MAX__ = @as(c_int, 255);
// pub const __UINT_LEAST8_FMTo__ = "hho";
// pub const __UINT_LEAST8_FMTu__ = "hhu";
// pub const __UINT_LEAST8_FMTx__ = "hhx";
// pub const __UINT_LEAST8_FMTX__ = "hhX";
// pub const __INT_LEAST16_TYPE__ = c_short;
// pub const __INT_LEAST16_MAX__ = @as(c_int, 32767);
// pub const __INT_LEAST16_FMTd__ = "hd";
// pub const __INT_LEAST16_FMTi__ = "hi";
// pub const __UINT_LEAST16_TYPE__ = c_ushort;
// pub const __UINT_LEAST16_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 65535, .decimal);
// pub const __UINT_LEAST16_FMTo__ = "ho";
// pub const __UINT_LEAST16_FMTu__ = "hu";
// pub const __UINT_LEAST16_FMTx__ = "hx";
// pub const __UINT_LEAST16_FMTX__ = "hX";
// pub const __INT_LEAST32_TYPE__ = c_int;
// pub const __INT_LEAST32_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 2147483647, .decimal);
// pub const __INT_LEAST32_FMTd__ = "d";
// pub const __INT_LEAST32_FMTi__ = "i";
// pub const __UINT_LEAST32_TYPE__ = c_uint;
// pub const __UINT_LEAST32_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_uint, 4294967295, .decimal);
// pub const __UINT_LEAST32_FMTo__ = "o";
// pub const __UINT_LEAST32_FMTu__ = "u";
// pub const __UINT_LEAST32_FMTx__ = "x";
// pub const __UINT_LEAST32_FMTX__ = "X";
// pub const __INT_LEAST64_TYPE__ = c_longlong;
// pub const __INT_LEAST64_MAX__ = @as(c_longlong, 9223372036854775807);
// pub const __INT_LEAST64_FMTd__ = "lld";
// pub const __INT_LEAST64_FMTi__ = "lli";
// pub const __UINT_LEAST64_TYPE__ = c_ulonglong;
// pub const __UINT_LEAST64_MAX__ = @as(c_ulonglong, 18446744073709551615);
// pub const __UINT_LEAST64_FMTo__ = "llo";
// pub const __UINT_LEAST64_FMTu__ = "llu";
// pub const __UINT_LEAST64_FMTx__ = "llx";
// pub const __UINT_LEAST64_FMTX__ = "llX";
// pub const __INT_FAST8_TYPE__ = i8;
// pub const __INT_FAST8_MAX__ = @as(c_int, 127);
// pub const __INT_FAST8_FMTd__ = "hhd";
// pub const __INT_FAST8_FMTi__ = "hhi";
// pub const __UINT_FAST8_TYPE__ = u8;
// pub const __UINT_FAST8_MAX__ = @as(c_int, 255);
// pub const __UINT_FAST8_FMTo__ = "hho";
// pub const __UINT_FAST8_FMTu__ = "hhu";
// pub const __UINT_FAST8_FMTx__ = "hhx";
// pub const __UINT_FAST8_FMTX__ = "hhX";
// pub const __INT_FAST16_TYPE__ = c_short;
// pub const __INT_FAST16_MAX__ = @as(c_int, 32767);
// pub const __INT_FAST16_FMTd__ = "hd";
// pub const __INT_FAST16_FMTi__ = "hi";
// pub const __UINT_FAST16_TYPE__ = c_ushort;
// pub const __UINT_FAST16_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 65535, .decimal);
// pub const __UINT_FAST16_FMTo__ = "ho";
// pub const __UINT_FAST16_FMTu__ = "hu";
// pub const __UINT_FAST16_FMTx__ = "hx";
// pub const __UINT_FAST16_FMTX__ = "hX";
// pub const __INT_FAST32_TYPE__ = c_int;
// pub const __INT_FAST32_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 2147483647, .decimal);
// pub const __INT_FAST32_FMTd__ = "d";
// pub const __INT_FAST32_FMTi__ = "i";
// pub const __UINT_FAST32_TYPE__ = c_uint;
// pub const __UINT_FAST32_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_uint, 4294967295, .decimal);
// pub const __UINT_FAST32_FMTo__ = "o";
// pub const __UINT_FAST32_FMTu__ = "u";
// pub const __UINT_FAST32_FMTx__ = "x";
// pub const __UINT_FAST32_FMTX__ = "X";
// pub const __INT_FAST64_TYPE__ = c_longlong;
// pub const __INT_FAST64_MAX__ = @as(c_longlong, 9223372036854775807);
// pub const __INT_FAST64_FMTd__ = "lld";
// pub const __INT_FAST64_FMTi__ = "lli";
// pub const __UINT_FAST64_TYPE__ = c_ulonglong;
// pub const __UINT_FAST64_MAX__ = @as(c_ulonglong, 18446744073709551615);
// pub const __UINT_FAST64_FMTo__ = "llo";
// pub const __UINT_FAST64_FMTu__ = "llu";
// pub const __UINT_FAST64_FMTx__ = "llx";
// pub const __UINT_FAST64_FMTX__ = "llX";
// pub const __FINITE_MATH_ONLY__ = @as(c_int, 0);
// pub const __GNUC_STDC_INLINE__ = @as(c_int, 1);
// pub const __GCC_ATOMIC_TEST_AND_SET_TRUEVAL = @as(c_int, 1);
// pub const __CLANG_ATOMIC_BOOL_LOCK_FREE = @as(c_int, 2);
// pub const __CLANG_ATOMIC_CHAR_LOCK_FREE = @as(c_int, 2);
// pub const __CLANG_ATOMIC_CHAR16_T_LOCK_FREE = @as(c_int, 2);
// pub const __CLANG_ATOMIC_CHAR32_T_LOCK_FREE = @as(c_int, 2);
// pub const __CLANG_ATOMIC_WCHAR_T_LOCK_FREE = @as(c_int, 2);
// pub const __CLANG_ATOMIC_SHORT_LOCK_FREE = @as(c_int, 2);
// pub const __CLANG_ATOMIC_INT_LOCK_FREE = @as(c_int, 2);
// pub const __CLANG_ATOMIC_LONG_LOCK_FREE = @as(c_int, 2);
// pub const __CLANG_ATOMIC_LLONG_LOCK_FREE = @as(c_int, 2);
// pub const __CLANG_ATOMIC_POINTER_LOCK_FREE = @as(c_int, 2);
// pub const __GCC_ATOMIC_BOOL_LOCK_FREE = @as(c_int, 2);
// pub const __GCC_ATOMIC_CHAR_LOCK_FREE = @as(c_int, 2);
// pub const __GCC_ATOMIC_CHAR16_T_LOCK_FREE = @as(c_int, 2);
// pub const __GCC_ATOMIC_CHAR32_T_LOCK_FREE = @as(c_int, 2);
// pub const __GCC_ATOMIC_WCHAR_T_LOCK_FREE = @as(c_int, 2);
// pub const __GCC_ATOMIC_SHORT_LOCK_FREE = @as(c_int, 2);
// pub const __GCC_ATOMIC_INT_LOCK_FREE = @as(c_int, 2);
// pub const __GCC_ATOMIC_LONG_LOCK_FREE = @as(c_int, 2);
// pub const __GCC_ATOMIC_LLONG_LOCK_FREE = @as(c_int, 2);
// pub const __GCC_ATOMIC_POINTER_LOCK_FREE = @as(c_int, 2);
// pub const __PIC__ = @as(c_int, 2);
// pub const __pic__ = @as(c_int, 2);
// pub const __FLT_EVAL_METHOD__ = @as(c_int, 0);
// pub const __FLT_RADIX__ = @as(c_int, 2);
// pub const __DECIMAL_DIG__ = __LDBL_DECIMAL_DIG__;
// pub const __SSP_STRONG__ = @as(c_int, 2);
// pub const __GCC_ASM_FLAG_OUTPUTS__ = @as(c_int, 1);
// pub const __code_model_small__ = @as(c_int, 1);
// pub const __amd64__ = @as(c_int, 1);
// pub const __amd64 = @as(c_int, 1);
// pub const __x86_64 = @as(c_int, 1);
// pub const __x86_64__ = @as(c_int, 1);
// pub const __SEG_GS = @as(c_int, 1);
// pub const __SEG_FS = @as(c_int, 1);
// pub const __seg_gs = __attribute__(address_space(@as(c_int, 256)));
// pub const __seg_fs = __attribute__(address_space(@as(c_int, 257)));
// pub const __corei7 = @as(c_int, 1);
// pub const __corei7__ = @as(c_int, 1);
// pub const __tune_corei7__ = @as(c_int, 1);
// pub const __NO_MATH_INLINES = @as(c_int, 1);
// pub const __AES__ = @as(c_int, 1);
// pub const __PCLMUL__ = @as(c_int, 1);
// pub const __LAHF_SAHF__ = @as(c_int, 1);
// pub const __LZCNT__ = @as(c_int, 1);
// pub const __RDRND__ = @as(c_int, 1);
// pub const __FSGSBASE__ = @as(c_int, 1);
// pub const __BMI__ = @as(c_int, 1);
// pub const __BMI2__ = @as(c_int, 1);
// pub const __POPCNT__ = @as(c_int, 1);
// pub const __RTM__ = @as(c_int, 1);
// pub const __PRFCHW__ = @as(c_int, 1);
// pub const __RDSEED__ = @as(c_int, 1);
// pub const __ADX__ = @as(c_int, 1);
// pub const __MOVBE__ = @as(c_int, 1);
// pub const __FMA__ = @as(c_int, 1);
// pub const __F16C__ = @as(c_int, 1);
// pub const __FXSR__ = @as(c_int, 1);
// pub const __XSAVE__ = @as(c_int, 1);
// pub const __XSAVEOPT__ = @as(c_int, 1);
// pub const __XSAVEC__ = @as(c_int, 1);
// pub const __XSAVES__ = @as(c_int, 1);
// pub const __CLFLUSHOPT__ = @as(c_int, 1);
// pub const __SGX__ = @as(c_int, 1);
// pub const __INVPCID__ = @as(c_int, 1);
// pub const __AVX2__ = @as(c_int, 1);
// pub const __AVX__ = @as(c_int, 1);
// pub const __SSE4_2__ = @as(c_int, 1);
// pub const __SSE4_1__ = @as(c_int, 1);
// pub const __SSSE3__ = @as(c_int, 1);
// pub const __SSE3__ = @as(c_int, 1);
// pub const __SSE2__ = @as(c_int, 1);
// pub const __SSE2_MATH__ = @as(c_int, 1);
// pub const __SSE__ = @as(c_int, 1);
// pub const __SSE_MATH__ = @as(c_int, 1);
// pub const __MMX__ = @as(c_int, 1);
// pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 = @as(c_int, 1);
// pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 = @as(c_int, 1);
// pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 = @as(c_int, 1);
// pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 = @as(c_int, 1);
// pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_16 = @as(c_int, 1);
// pub const __SIZEOF_FLOAT128__ = @as(c_int, 16);
// pub const _WIN32 = @as(c_int, 1);
// pub const _WIN64 = @as(c_int, 1);
// pub const WIN32 = @as(c_int, 1);
// pub const __WIN32 = @as(c_int, 1);
// pub const __WIN32__ = @as(c_int, 1);
// pub const WINNT = @as(c_int, 1);
// pub const __WINNT = @as(c_int, 1);
// pub const __WINNT__ = @as(c_int, 1);
// pub const WIN64 = @as(c_int, 1);
// pub const __WIN64 = @as(c_int, 1);
// pub const __WIN64__ = @as(c_int, 1);
// pub const __MINGW64__ = @as(c_int, 1);
// pub const __MSVCRT__ = @as(c_int, 1);
// pub const __MINGW32__ = @as(c_int, 1);
// const _cdecl = __attribute__(__cdecl__);
// const __cdecl = __attribute__(__cdecl__);
// const _stdcall = __attribute__(__stdcall__);
// const _fastcall = __attribute__(__fastcall__);
// const __fastcall = __attribute__(__fastcall__);
// const _thiscall = __attribute__(__thiscall__);
// const __thiscall = __attribute__(__thiscall__);
// const _pascal = __attribute__(__pascal__);
// const __pascal = __attribute__(__pascal__);
// const __STDC__ = @as(c_int, 1);
// const __STDC_HOSTED__ = @as(c_int, 1);
// const __STDC_VERSION__ = @as(c_long, 201710);
// const __STDC_UTF_16__ = @as(c_int, 1);
// const __STDC_UTF_32__ = @as(c_int, 1);
// const _DEBUG = @as(c_int, 1);
pub const FMOD_VERSION = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00020110, .hexadecimal);
pub const FMOD_DEBUG_LEVEL_NONE = @as(c_int, 0x00000000);
pub const FMOD_DEBUG_LEVEL_ERROR = @as(c_int, 0x00000001);
pub const FMOD_DEBUG_LEVEL_WARNING = @as(c_int, 0x00000002);
pub const FMOD_DEBUG_LEVEL_LOG = @as(c_int, 0x00000004);
pub const FMOD_DEBUG_TYPE_MEMORY = @as(c_int, 0x00000100);
pub const FMOD_DEBUG_TYPE_FILE = @as(c_int, 0x00000200);
pub const FMOD_DEBUG_TYPE_CODEC = @as(c_int, 0x00000400);
pub const FMOD_DEBUG_TYPE_TRACE = @as(c_int, 0x00000800);
pub const FMOD_DEBUG_DISPLAY_TIMESTAMPS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00010000, .hexadecimal);
pub const FMOD_DEBUG_DISPLAY_LINENUMBERS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00020000, .hexadecimal);
pub const FMOD_DEBUG_DISPLAY_THREAD = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00040000, .hexadecimal);
pub const FMOD_MEMORY_NORMAL = @as(c_int, 0x00000000);
pub const FMOD_MEMORY_STREAM_FILE = @as(c_int, 0x00000001);
pub const FMOD_MEMORY_STREAM_DECODE = @as(c_int, 0x00000002);
pub const FMOD_MEMORY_SAMPLEDATA = @as(c_int, 0x00000004);
pub const FMOD_MEMORY_DSP_BUFFER = @as(c_int, 0x00000008);
pub const FMOD_MEMORY_PLUGIN = @as(c_int, 0x00000010);
pub const FMOD_MEMORY_PERSISTENT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00200000, .hexadecimal);
pub const FMOD_MEMORY_ALL = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFFFFFFF, .hexadecimal);
pub const FMOD_INIT_NORMAL = @as(c_int, 0x00000000);
pub const FMOD_INIT_STREAM_FROM_UPDATE = @as(c_int, 0x00000001);
pub const FMOD_INIT_MIX_FROM_UPDATE = @as(c_int, 0x00000002);
pub const FMOD_INIT_3D_RIGHTHANDED = @as(c_int, 0x00000004);
pub const FMOD_INIT_CHANNEL_LOWPASS = @as(c_int, 0x00000100);
pub const FMOD_INIT_CHANNEL_DISTANCEFILTER = @as(c_int, 0x00000200);
pub const FMOD_INIT_PROFILE_ENABLE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00010000, .hexadecimal);
pub const FMOD_INIT_VOL0_BECOMES_VIRTUAL = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00020000, .hexadecimal);
pub const FMOD_INIT_GEOMETRY_USECLOSEST = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00040000, .hexadecimal);
pub const FMOD_INIT_PREFER_DOLBY_DOWNMIX = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00080000, .hexadecimal);
pub const FMOD_INIT_THREAD_UNSAFE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00100000, .hexadecimal);
pub const FMOD_INIT_PROFILE_METER_ALL = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00200000, .hexadecimal);
pub const FMOD_INIT_MEMORY_TRACKING = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00400000, .hexadecimal);
pub const FMOD_DRIVER_STATE_CONNECTED = @as(c_int, 0x00000001);
pub const FMOD_DRIVER_STATE_DEFAULT = @as(c_int, 0x00000002);
pub const FMOD_TIMEUNIT_MS = @as(c_int, 0x00000001);
pub const FMOD_TIMEUNIT_PCM = @as(c_int, 0x00000002);
pub const FMOD_TIMEUNIT_PCMBYTES = @as(c_int, 0x00000004);
pub const FMOD_TIMEUNIT_RAWBYTES = @as(c_int, 0x00000008);
pub const FMOD_TIMEUNIT_PCMFRACTION = @as(c_int, 0x00000010);
pub const FMOD_TIMEUNIT_MODORDER = @as(c_int, 0x00000100);
pub const FMOD_TIMEUNIT_MODROW = @as(c_int, 0x00000200);
pub const FMOD_TIMEUNIT_MODPATTERN = @as(c_int, 0x00000400);
pub const FMOD_SYSTEM_CALLBACK_DEVICELISTCHANGED = @as(c_int, 0x00000001);
pub const FMOD_SYSTEM_CALLBACK_DEVICELOST = @as(c_int, 0x00000002);
pub const FMOD_SYSTEM_CALLBACK_MEMORYALLOCATIONFAILED = @as(c_int, 0x00000004);
pub const FMOD_SYSTEM_CALLBACK_THREADCREATED = @as(c_int, 0x00000008);
pub const FMOD_SYSTEM_CALLBACK_BADDSPCONNECTION = @as(c_int, 0x00000010);
pub const FMOD_SYSTEM_CALLBACK_PREMIX = @as(c_int, 0x00000020);
pub const FMOD_SYSTEM_CALLBACK_POSTMIX = @as(c_int, 0x00000040);
pub const FMOD_SYSTEM_CALLBACK_ERROR = @as(c_int, 0x00000080);
pub const FMOD_SYSTEM_CALLBACK_MIDMIX = @as(c_int, 0x00000100);
pub const FMOD_SYSTEM_CALLBACK_THREADDESTROYED = @as(c_int, 0x00000200);
pub const FMOD_SYSTEM_CALLBACK_PREUPDATE = @as(c_int, 0x00000400);
pub const FMOD_SYSTEM_CALLBACK_POSTUPDATE = @as(c_int, 0x00000800);
pub const FMOD_SYSTEM_CALLBACK_RECORDLISTCHANGED = @as(c_int, 0x00001000);
pub const FMOD_SYSTEM_CALLBACK_BUFFEREDNOMIX = @as(c_int, 0x00002000);
pub const FMOD_SYSTEM_CALLBACK_DEVICEREINITIALIZE = @as(c_int, 0x00004000);
pub const FMOD_SYSTEM_CALLBACK_OUTPUTUNDERRUN = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00008000, .hexadecimal);
pub const FMOD_SYSTEM_CALLBACK_ALL = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFFFFFFF, .hexadecimal);
pub const FMOD_DEFAULT = @as(c_int, 0x00000000);
pub const FMOD_LOOP_OFF = @as(c_int, 0x00000001);
pub const FMOD_LOOP_NORMAL = @as(c_int, 0x00000002);
pub const FMOD_LOOP_BIDI = @as(c_int, 0x00000004);
pub const FMOD_2D = @as(c_int, 0x00000008);
pub const FMOD_3D = @as(c_int, 0x00000010);
pub const FMOD_CREATESTREAM = @as(c_int, 0x00000080);
pub const FMOD_CREATESAMPLE = @as(c_int, 0x00000100);
pub const FMOD_CREATECOMPRESSEDSAMPLE = @as(c_int, 0x00000200);
pub const FMOD_OPENUSER = @as(c_int, 0x00000400);
pub const FMOD_OPENMEMORY = @as(c_int, 0x00000800);
pub const FMOD_OPENMEMORY_POINT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x10000000, .hexadecimal);
pub const FMOD_OPENRAW = @as(c_int, 0x00001000);
pub const FMOD_OPENONLY = @as(c_int, 0x00002000);
pub const FMOD_ACCURATETIME = @as(c_int, 0x00004000);
pub const FMOD_MPEGSEARCH = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00008000, .hexadecimal);
pub const FMOD_NONBLOCKING = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00010000, .hexadecimal);
pub const FMOD_UNIQUE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00020000, .hexadecimal);
pub const FMOD_3D_HEADRELATIVE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00040000, .hexadecimal);
pub const FMOD_3D_WORLDRELATIVE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00080000, .hexadecimal);
pub const FMOD_3D_INVERSEROLLOFF = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00100000, .hexadecimal);
pub const FMOD_3D_LINEARROLLOFF = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00200000, .hexadecimal);
pub const FMOD_3D_LINEARSQUAREROLLOFF = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00400000, .hexadecimal);
pub const FMOD_3D_INVERSETAPEREDROLLOFF = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00800000, .hexadecimal);
pub const FMOD_3D_CUSTOMROLLOFF = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x04000000, .hexadecimal);
pub const FMOD_3D_IGNOREGEOMETRY = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x40000000, .hexadecimal);
pub const FMOD_IGNORETAGS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x02000000, .hexadecimal);
pub const FMOD_LOWMEM = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x08000000, .hexadecimal);
pub const FMOD_VIRTUAL_PLAYFROMSTART = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x80000000, .hexadecimal);
pub const FMOD_CHANNELMASK_FRONT_LEFT = @as(c_int, 0x00000001);
pub const FMOD_CHANNELMASK_FRONT_RIGHT = @as(c_int, 0x00000002);
pub const FMOD_CHANNELMASK_FRONT_CENTER = @as(c_int, 0x00000004);
pub const FMOD_CHANNELMASK_LOW_FREQUENCY = @as(c_int, 0x00000008);
pub const FMOD_CHANNELMASK_SURROUND_LEFT = @as(c_int, 0x00000010);
pub const FMOD_CHANNELMASK_SURROUND_RIGHT = @as(c_int, 0x00000020);
pub const FMOD_CHANNELMASK_BACK_LEFT = @as(c_int, 0x00000040);
pub const FMOD_CHANNELMASK_BACK_RIGHT = @as(c_int, 0x00000080);
pub const FMOD_CHANNELMASK_BACK_CENTER = @as(c_int, 0x00000100);
pub const FMOD_CHANNELMASK_MONO = FMOD_CHANNELMASK_FRONT_LEFT;
pub const FMOD_CHANNELMASK_STEREO = FMOD_CHANNELMASK_FRONT_LEFT | FMOD_CHANNELMASK_FRONT_RIGHT;
pub const FMOD_CHANNELMASK_LRC = (FMOD_CHANNELMASK_FRONT_LEFT | FMOD_CHANNELMASK_FRONT_RIGHT) | FMOD_CHANNELMASK_FRONT_CENTER;
pub const FMOD_CHANNELMASK_QUAD = ((FMOD_CHANNELMASK_FRONT_LEFT | FMOD_CHANNELMASK_FRONT_RIGHT) | FMOD_CHANNELMASK_SURROUND_LEFT) | FMOD_CHANNELMASK_SURROUND_RIGHT;
pub const FMOD_CHANNELMASK_SURROUND = (((FMOD_CHANNELMASK_FRONT_LEFT | FMOD_CHANNELMASK_FRONT_RIGHT) | FMOD_CHANNELMASK_FRONT_CENTER) | FMOD_CHANNELMASK_SURROUND_LEFT) | FMOD_CHANNELMASK_SURROUND_RIGHT;
pub const FMOD_CHANNELMASK_5POINT1 = ((((FMOD_CHANNELMASK_FRONT_LEFT | FMOD_CHANNELMASK_FRONT_RIGHT) | FMOD_CHANNELMASK_FRONT_CENTER) | FMOD_CHANNELMASK_LOW_FREQUENCY) | FMOD_CHANNELMASK_SURROUND_LEFT) | FMOD_CHANNELMASK_SURROUND_RIGHT;
pub const FMOD_CHANNELMASK_5POINT1_REARS = ((((FMOD_CHANNELMASK_FRONT_LEFT | FMOD_CHANNELMASK_FRONT_RIGHT) | FMOD_CHANNELMASK_FRONT_CENTER) | FMOD_CHANNELMASK_LOW_FREQUENCY) | FMOD_CHANNELMASK_BACK_LEFT) | FMOD_CHANNELMASK_BACK_RIGHT;
pub const FMOD_CHANNELMASK_7POINT0 = (((((FMOD_CHANNELMASK_FRONT_LEFT | FMOD_CHANNELMASK_FRONT_RIGHT) | FMOD_CHANNELMASK_FRONT_CENTER) | FMOD_CHANNELMASK_SURROUND_LEFT) | FMOD_CHANNELMASK_SURROUND_RIGHT) | FMOD_CHANNELMASK_BACK_LEFT) | FMOD_CHANNELMASK_BACK_RIGHT;
pub const FMOD_CHANNELMASK_7POINT1 = ((((((FMOD_CHANNELMASK_FRONT_LEFT | FMOD_CHANNELMASK_FRONT_RIGHT) | FMOD_CHANNELMASK_FRONT_CENTER) | FMOD_CHANNELMASK_LOW_FREQUENCY) | FMOD_CHANNELMASK_SURROUND_LEFT) | FMOD_CHANNELMASK_SURROUND_RIGHT) | FMOD_CHANNELMASK_BACK_LEFT) | FMOD_CHANNELMASK_BACK_RIGHT;
pub const FMOD_THREAD_PRIORITY_PLATFORM_MIN = -@as(c_int, 32) * @as(c_int, 1024);
pub const FMOD_THREAD_PRIORITY_PLATFORM_MAX = @as(c_int, 32) * @as(c_int, 1024);
pub const FMOD_THREAD_PRIORITY_DEFAULT = FMOD_THREAD_PRIORITY_PLATFORM_MIN - @as(c_int, 1);
pub const FMOD_THREAD_PRIORITY_LOW = FMOD_THREAD_PRIORITY_PLATFORM_MIN - @as(c_int, 2);
pub const FMOD_THREAD_PRIORITY_MEDIUM = FMOD_THREAD_PRIORITY_PLATFORM_MIN - @as(c_int, 3);
pub const FMOD_THREAD_PRIORITY_HIGH = FMOD_THREAD_PRIORITY_PLATFORM_MIN - @as(c_int, 4);
pub const FMOD_THREAD_PRIORITY_VERY_HIGH = FMOD_THREAD_PRIORITY_PLATFORM_MIN - @as(c_int, 5);
pub const FMOD_THREAD_PRIORITY_EXTREME = FMOD_THREAD_PRIORITY_PLATFORM_MIN - @as(c_int, 6);
pub const FMOD_THREAD_PRIORITY_CRITICAL = FMOD_THREAD_PRIORITY_PLATFORM_MIN - @as(c_int, 7);
pub const FMOD_THREAD_PRIORITY_MIXER = FMOD_THREAD_PRIORITY_EXTREME;
pub const FMOD_THREAD_PRIORITY_FEEDER = FMOD_THREAD_PRIORITY_CRITICAL;
pub const FMOD_THREAD_PRIORITY_STREAM = FMOD_THREAD_PRIORITY_VERY_HIGH;
pub const FMOD_THREAD_PRIORITY_FILE = FMOD_THREAD_PRIORITY_HIGH;
pub const FMOD_THREAD_PRIORITY_NONBLOCKING = FMOD_THREAD_PRIORITY_HIGH;
pub const FMOD_THREAD_PRIORITY_RECORD = FMOD_THREAD_PRIORITY_HIGH;
pub const FMOD_THREAD_PRIORITY_GEOMETRY = FMOD_THREAD_PRIORITY_LOW;
pub const FMOD_THREAD_PRIORITY_PROFILER = FMOD_THREAD_PRIORITY_MEDIUM;
pub const FMOD_THREAD_PRIORITY_STUDIO_UPDATE = FMOD_THREAD_PRIORITY_MEDIUM;
pub const FMOD_THREAD_PRIORITY_STUDIO_LOAD_BANK = FMOD_THREAD_PRIORITY_MEDIUM;
pub const FMOD_THREAD_PRIORITY_STUDIO_LOAD_SAMPLE = FMOD_THREAD_PRIORITY_MEDIUM;
pub const FMOD_THREAD_PRIORITY_CONVOLUTION1 = FMOD_THREAD_PRIORITY_VERY_HIGH;
pub const FMOD_THREAD_PRIORITY_CONVOLUTION2 = FMOD_THREAD_PRIORITY_VERY_HIGH;
pub const FMOD_THREAD_STACK_SIZE_DEFAULT = @as(c_int, 0);
pub const FMOD_THREAD_STACK_SIZE_MIXER = @as(c_int, 80) * @as(c_int, 1024);
pub const FMOD_THREAD_STACK_SIZE_FEEDER = @as(c_int, 16) * @as(c_int, 1024);
pub const FMOD_THREAD_STACK_SIZE_STREAM = @as(c_int, 96) * @as(c_int, 1024);
pub const FMOD_THREAD_STACK_SIZE_FILE = @as(c_int, 48) * @as(c_int, 1024);
pub const FMOD_THREAD_STACK_SIZE_NONBLOCKING = @as(c_int, 112) * @as(c_int, 1024);
pub const FMOD_THREAD_STACK_SIZE_RECORD = @as(c_int, 16) * @as(c_int, 1024);
pub const FMOD_THREAD_STACK_SIZE_GEOMETRY = @as(c_int, 48) * @as(c_int, 1024);
pub const FMOD_THREAD_STACK_SIZE_PROFILER = @as(c_int, 128) * @as(c_int, 1024);
pub const FMOD_THREAD_STACK_SIZE_STUDIO_UPDATE = @as(c_int, 96) * @as(c_int, 1024);
pub const FMOD_THREAD_STACK_SIZE_STUDIO_LOAD_BANK = @as(c_int, 96) * @as(c_int, 1024);
pub const FMOD_THREAD_STACK_SIZE_STUDIO_LOAD_SAMPLE = @as(c_int, 96) * @as(c_int, 1024);
pub const FMOD_THREAD_STACK_SIZE_CONVOLUTION1 = @as(c_int, 16) * @as(c_int, 1024);
pub const FMOD_THREAD_STACK_SIZE_CONVOLUTION2 = @as(c_int, 16) * @as(c_int, 1024);
pub const FMOD_THREAD_AFFINITY_GROUP_DEFAULT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8000000000000000, .hexadecimal);
pub const FMOD_THREAD_AFFINITY_GROUP_A = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8000000000000001, .hexadecimal);
pub const FMOD_THREAD_AFFINITY_GROUP_B = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8000000000000002, .hexadecimal);
pub const FMOD_THREAD_AFFINITY_GROUP_C = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8000000000000003, .hexadecimal);
pub const FMOD_THREAD_AFFINITY_MIXER = FMOD_THREAD_AFFINITY_GROUP_A;
pub const FMOD_THREAD_AFFINITY_FEEDER = FMOD_THREAD_AFFINITY_GROUP_C;
pub const FMOD_THREAD_AFFINITY_STREAM = FMOD_THREAD_AFFINITY_GROUP_C;
pub const FMOD_THREAD_AFFINITY_FILE = FMOD_THREAD_AFFINITY_GROUP_C;
pub const FMOD_THREAD_AFFINITY_NONBLOCKING = FMOD_THREAD_AFFINITY_GROUP_C;
pub const FMOD_THREAD_AFFINITY_RECORD = FMOD_THREAD_AFFINITY_GROUP_C;
pub const FMOD_THREAD_AFFINITY_GEOMETRY = FMOD_THREAD_AFFINITY_GROUP_C;
pub const FMOD_THREAD_AFFINITY_PROFILER = FMOD_THREAD_AFFINITY_GROUP_C;
pub const FMOD_THREAD_AFFINITY_STUDIO_UPDATE = FMOD_THREAD_AFFINITY_GROUP_B;
pub const FMOD_THREAD_AFFINITY_STUDIO_LOAD_BANK = FMOD_THREAD_AFFINITY_GROUP_C;
pub const FMOD_THREAD_AFFINITY_STUDIO_LOAD_SAMPLE = FMOD_THREAD_AFFINITY_GROUP_C;
pub const FMOD_THREAD_AFFINITY_CONVOLUTION1 = FMOD_THREAD_AFFINITY_GROUP_C;
pub const FMOD_THREAD_AFFINITY_CONVOLUTION2 = FMOD_THREAD_AFFINITY_GROUP_C;
pub const FMOD_THREAD_AFFINITY_CORE_ALL = @as(c_int, 0);
pub const FMOD_THREAD_AFFINITY_CORE_0 = @as(c_int, 1) << @as(c_int, 0);
pub const FMOD_THREAD_AFFINITY_CORE_1 = @as(c_int, 1) << @as(c_int, 1);
pub const FMOD_THREAD_AFFINITY_CORE_2 = @as(c_int, 1) << @as(c_int, 2);
pub const FMOD_THREAD_AFFINITY_CORE_3 = @as(c_int, 1) << @as(c_int, 3);
pub const FMOD_THREAD_AFFINITY_CORE_4 = @as(c_int, 1) << @as(c_int, 4);
pub const FMOD_THREAD_AFFINITY_CORE_5 = @as(c_int, 1) << @as(c_int, 5);
pub const FMOD_THREAD_AFFINITY_CORE_6 = @as(c_int, 1) << @as(c_int, 6);
pub const FMOD_THREAD_AFFINITY_CORE_7 = @as(c_int, 1) << @as(c_int, 7);
pub const FMOD_THREAD_AFFINITY_CORE_8 = @as(c_int, 1) << @as(c_int, 8);
pub const FMOD_THREAD_AFFINITY_CORE_9 = @as(c_int, 1) << @as(c_int, 9);
pub const FMOD_THREAD_AFFINITY_CORE_10 = @as(c_int, 1) << @as(c_int, 10);
pub const FMOD_THREAD_AFFINITY_CORE_11 = @as(c_int, 1) << @as(c_int, 11);
pub const FMOD_THREAD_AFFINITY_CORE_12 = @as(c_int, 1) << @as(c_int, 12);
pub const FMOD_THREAD_AFFINITY_CORE_13 = @as(c_int, 1) << @as(c_int, 13);
pub const FMOD_THREAD_AFFINITY_CORE_14 = @as(c_int, 1) << @as(c_int, 14);
pub const FMOD_THREAD_AFFINITY_CORE_15 = @as(c_int, 1) << @as(c_int, 15);
pub const FMOD_MAX_CHANNEL_WIDTH = @as(c_int, 32);
pub const FMOD_MAX_SYSTEMS = @as(c_int, 8);
pub const FMOD_MAX_LISTENERS = @as(c_int, 8);
pub const FMOD_REVERB_MAXINSTANCES = @as(c_int, 4);
pub const FMOD_PORT_INDEX_NONE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFFFFFFFFFFFFFFF, .hexadecimal);
pub const FMOD_CODEC_WAVEFORMAT_VERSION = @as(c_int, 3);
pub const FMOD_DSP_LOUDNESS_METER_HISTOGRAM_SAMPLES = @as(c_int, 66);
pub const FMOD_PLUGIN_SDK_VERSION = @as(c_int, 110);
pub const FMOD_DSP_GETPARAM_VALUESTR_LENGTH = @as(c_int, 32);
// pub inline fn FMOD_DSP_ALLOC(_state: anytype, _size: anytype) @TypeOf(_state.*.functions.*.alloc(_size, FMOD_MEMORY_NORMAL, __FILE__)) {
// return _state.*.functions.*.alloc(_size, FMOD_MEMORY_NORMAL, __FILE__);
// }
// pub inline fn FMOD_DSP_REALLOC(_state: anytype, _ptr: anytype, _size: anytype) @TypeOf(_state.*.functions.*.realloc(_ptr, _size, FMOD_MEMORY_NORMAL, __FILE__)) {
// return _state.*.functions.*.realloc(_ptr, _size, FMOD_MEMORY_NORMAL, __FILE__);
// }
// pub inline fn FMOD_DSP_FREE(_state: anytype, _ptr: anytype) @TypeOf(_state.*.functions.*.free(_ptr, FMOD_MEMORY_NORMAL, __FILE__)) {
// return _state.*.functions.*.free(_ptr, FMOD_MEMORY_NORMAL, __FILE__);
// }
// pub inline fn FMOD_DSP_GETSAMPLERATE(_state: anytype, _rate: anytype) @TypeOf(_state.*.functions.*.getsamplerate(_state, _rate)) {
// return _state.*.functions.*.getsamplerate(_state, _rate);
// }
// pub inline fn FMOD_DSP_GETBLOCKSIZE(_state: anytype, _blocksize: anytype) @TypeOf(_state.*.functions.*.getblocksize(_state, _blocksize)) {
// return _state.*.functions.*.getblocksize(_state, _blocksize);
// }
// pub inline fn FMOD_DSP_GETSPEAKERMODE(_state: anytype, _speakermodemix: anytype, _speakermodeout: anytype) @TypeOf(_state.*.functions.*.getspeakermode(_state, _speakermodemix, _speakermodeout)) {
// return _state.*.functions.*.getspeakermode(_state, _speakermodemix, _speakermodeout);
// }
// pub inline fn FMOD_DSP_GETCLOCK(_state: anytype, _clock: anytype, _offset: anytype, _length: anytype) @TypeOf(_state.*.functions.*.getclock(_state, _clock, _offset, _length)) {
// return _state.*.functions.*.getclock(_state, _clock, _offset, _length);
// }
// pub inline fn FMOD_DSP_GETLISTENERATTRIBUTES(_state: anytype, _numlisteners: anytype, _attributes: anytype) @TypeOf(_state.*.functions.*.getlistenerattributes(_state, _numlisteners, _attributes)) {
// return _state.*.functions.*.getlistenerattributes(_state, _numlisteners, _attributes);
// }
// pub inline fn FMOD_DSP_GETUSERDATA(_state: anytype, _userdata: anytype) @TypeOf(_state.*.functions.*.getuserdata(_state, _userdata)) {
// return _state.*.functions.*.getuserdata(_state, _userdata);
// }
// pub inline fn FMOD_DSP_DFT_FFTREAL(_state: anytype, _size: anytype, _signal: anytype, _dft: anytype, _window: anytype, _signalhop: anytype) @TypeOf(_state.*.functions.*.dft.*.fftreal(_state, _size, _signal, _dft, _window, _signalhop)) {
// return _state.*.functions.*.dft.*.fftreal(_state, _size, _signal, _dft, _window, _signalhop);
// }
// pub inline fn FMOD_DSP_DFT_IFFTREAL(_state: anytype, _size: anytype, _dft: anytype, _signal: anytype, _window: anytype, _signalhop: anytype) @TypeOf(_state.*.functions.*.dft.*.inversefftreal(_state, _size, _dft, _signal, _window, _signalhop)) {
// return _state.*.functions.*.dft.*.inversefftreal(_state, _size, _dft, _signal, _window, _signalhop);
// }
// pub inline fn FMOD_DSP_PAN_SUMMONOMATRIX(_state: anytype, _sourcespeakermode: anytype, _lowfrequencygain: anytype, _overallgain: anytype, _matrix: anytype) @TypeOf(_state.*.functions.*.pan.*.summonomatrix(_state, _sourcespeakermode, _lowfrequencygain, _overallgain, _matrix)) {
// return _state.*.functions.*.pan.*.summonomatrix(_state, _sourcespeakermode, _lowfrequencygain, _overallgain, _matrix);
// }
// pub inline fn FMOD_DSP_PAN_SUMSTEREOMATRIX(_state: anytype, _sourcespeakermode: anytype, _pan: anytype, _lowfrequencygain: anytype, _overallgain: anytype, _matrixhop: anytype, _matrix: anytype) @TypeOf(_state.*.functions.*.pan.*.sumstereomatrix(_state, _sourcespeakermode, _pan, _lowfrequencygain, _overallgain, _matrixhop, _matrix)) {
// return _state.*.functions.*.pan.*.sumstereomatrix(_state, _sourcespeakermode, _pan, _lowfrequencygain, _overallgain, _matrixhop, _matrix);
// }
// pub inline fn FMOD_DSP_PAN_SUMSURROUNDMATRIX(_state: anytype, _sourcespeakermode: anytype, _targetspeakermode: anytype, _direction: anytype, _extent: anytype, _rotation: anytype, _lowfrequencygain: anytype, _overallgain: anytype, _matrixhop: anytype, _matrix: anytype, _flags: anytype) @TypeOf(_state.*.functions.*.pan.*.sumsurroundmatrix(_state, _sourcespeakermode, _targetspeakermode, _direction, _extent, _rotation, _lowfrequencygain, _overallgain, _matrixhop, _matrix, _flags)) {
// return _state.*.functions.*.pan.*.sumsurroundmatrix(_state, _sourcespeakermode, _targetspeakermode, _direction, _extent, _rotation, _lowfrequencygain, _overallgain, _matrixhop, _matrix, _flags);
// }
// pub inline fn FMOD_DSP_PAN_SUMMONOTOSURROUNDMATRIX(_state: anytype, _targetspeakermode: anytype, _direction: anytype, _extent: anytype, _lowfrequencygain: anytype, _overallgain: anytype, _matrixhop: anytype, _matrix: anytype) @TypeOf(_state.*.functions.*.pan.*.summonotosurroundmatrix(_state, _targetspeakermode, _direction, _extent, _lowfrequencygain, _overallgain, _matrixhop, _matrix)) {
// return _state.*.functions.*.pan.*.summonotosurroundmatrix(_state, _targetspeakermode, _direction, _extent, _lowfrequencygain, _overallgain, _matrixhop, _matrix);
// }
// pub inline fn FMOD_DSP_PAN_SUMSTEREOTOSURROUNDMATRIX(_state: anytype, _targetspeakermode: anytype, _direction: anytype, _extent: anytype, _rotation: anytype, _lowfrequencygain: anytype, _overallgain: anytype, matrixhop: anytype, _matrix: anytype) @TypeOf(_state.*.functions.*.pan.*.sumstereotosurroundmatrix(_state, _targetspeakermode, _direction, _extent, _rotation, _lowfrequencygain, _overallgain, matrixhop, _matrix)) {
// return _state.*.functions.*.pan.*.sumstereotosurroundmatrix(_state, _targetspeakermode, _direction, _extent, _rotation, _lowfrequencygain, _overallgain, matrixhop, _matrix);
// }
// pub inline fn FMOD_DSP_PAN_GETROLLOFFGAIN(_state: anytype, _rolloff: anytype, _distance: anytype, _mindistance: anytype, _maxdistance: anytype, _gain: anytype) @TypeOf(_state.*.functions.*.pan.*.getrolloffgain(_state, _rolloff, _distance, _mindistance, _maxdistance, _gain)) {
// return _state.*.functions.*.pan.*.getrolloffgain(_state, _rolloff, _distance, _mindistance, _maxdistance, _gain);
// }
pub const FMOD_OUTPUT_PLUGIN_VERSION = @as(c_int, 4);
pub const FMOD_OUTPUT_METHOD_MIX_DIRECT = @as(c_int, 0);
pub const FMOD_OUTPUT_METHOD_POLLING = @as(c_int, 1);
pub const FMOD_OUTPUT_METHOD_MIX_BUFFERED = @as(c_int, 2);
// pub inline fn FMOD_OUTPUT_READFROMMIXER(_state: anytype, _buffer: anytype, _length: anytype) @TypeOf(_state.*.readfrommixer(_state, _buffer, _length)) {
// return _state.*.readfrommixer(_state, _buffer, _length);
// }
// pub inline fn FMOD_OUTPUT_ALLOC(_state: anytype, _size: anytype, _align: anytype) @TypeOf(_state.*.alloc(_size, _align, __FILE__, __LINE__)) {
// return _state.*.alloc(_size, _align, __FILE__, __LINE__);
// }
// pub inline fn FMOD_OUTPUT_FREE(_state: anytype, _ptr: anytype) @TypeOf(_state.*.free(_ptr, __FILE__, __LINE__)) {
// return _state.*.free(_ptr, __FILE__, __LINE__);
// }
// pub inline fn FMOD_OUTPUT_COPYPORT(_state: anytype, _id: anytype, _buffer: anytype, _length: anytype) @TypeOf(_state.*.copyport(_state, _id, _buffer, _length)) {
// return _state.*.copyport(_state, _id, _buffer, _length);
// }
// pub inline fn FMOD_OUTPUT_REQUESTRESET(_state: anytype) @TypeOf(_state.*.requestreset(_state)) {
// return _state.*.requestreset(_state);
// }
pub const FMOD_STUDIO_LOAD_MEMORY_ALIGNMENT = @as(c_int, 32);
pub const FMOD_STUDIO_INIT_NORMAL = @as(c_int, 0x00000000);
pub const FMOD_STUDIO_INIT_LIVEUPDATE = @as(c_int, 0x00000001);
pub const FMOD_STUDIO_INIT_ALLOW_MISSING_PLUGINS = @as(c_int, 0x00000002);
pub const FMOD_STUDIO_INIT_SYNCHRONOUS_UPDATE = @as(c_int, 0x00000004);
pub const FMOD_STUDIO_INIT_DEFERRED_CALLBACKS = @as(c_int, 0x00000008);
pub const FMOD_STUDIO_INIT_LOAD_FROM_UPDATE = @as(c_int, 0x00000010);
pub const FMOD_STUDIO_INIT_MEMORY_TRACKING = @as(c_int, 0x00000020);
pub const FMOD_STUDIO_PARAMETER_READONLY = @as(c_int, 0x00000001);
pub const FMOD_STUDIO_PARAMETER_AUTOMATIC = @as(c_int, 0x00000002);
pub const FMOD_STUDIO_PARAMETER_GLOBAL = @as(c_int, 0x00000004);
pub const FMOD_STUDIO_PARAMETER_DISCRETE = @as(c_int, 0x00000008);
pub const FMOD_STUDIO_SYSTEM_CALLBACK_PREUPDATE = @as(c_int, 0x00000001);
pub const FMOD_STUDIO_SYSTEM_CALLBACK_POSTUPDATE = @as(c_int, 0x00000002);
pub const FMOD_STUDIO_SYSTEM_CALLBACK_BANK_UNLOAD = @as(c_int, 0x00000004);
pub const FMOD_STUDIO_SYSTEM_CALLBACK_LIVEUPDATE_CONNECTED = @as(c_int, 0x00000008);
pub const FMOD_STUDIO_SYSTEM_CALLBACK_LIVEUPDATE_DISCONNECTED = @as(c_int, 0x00000010);
pub const FMOD_STUDIO_SYSTEM_CALLBACK_ALL = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFFFFFFF, .hexadecimal);
pub const FMOD_STUDIO_EVENT_CALLBACK_CREATED = @as(c_int, 0x00000001);
pub const FMOD_STUDIO_EVENT_CALLBACK_DESTROYED = @as(c_int, 0x00000002);
pub const FMOD_STUDIO_EVENT_CALLBACK_STARTING = @as(c_int, 0x00000004);
pub const FMOD_STUDIO_EVENT_CALLBACK_STARTED = @as(c_int, 0x00000008);
pub const FMOD_STUDIO_EVENT_CALLBACK_RESTARTED = @as(c_int, 0x00000010);
pub const FMOD_STUDIO_EVENT_CALLBACK_STOPPED = @as(c_int, 0x00000020);
pub const FMOD_STUDIO_EVENT_CALLBACK_START_FAILED = @as(c_int, 0x00000040);
pub const FMOD_STUDIO_EVENT_CALLBACK_CREATE_PROGRAMMER_SOUND = @as(c_int, 0x00000080);
pub const FMOD_STUDIO_EVENT_CALLBACK_DESTROY_PROGRAMMER_SOUND = @as(c_int, 0x00000100);
pub const FMOD_STUDIO_EVENT_CALLBACK_PLUGIN_CREATED = @as(c_int, 0x00000200);
pub const FMOD_STUDIO_EVENT_CALLBACK_PLUGIN_DESTROYED = @as(c_int, 0x00000400);
pub const FMOD_STUDIO_EVENT_CALLBACK_TIMELINE_MARKER = @as(c_int, 0x00000800);
pub const FMOD_STUDIO_EVENT_CALLBACK_TIMELINE_BEAT = @as(c_int, 0x00001000);
pub const FMOD_STUDIO_EVENT_CALLBACK_SOUND_PLAYED = @as(c_int, 0x00002000);
pub const FMOD_STUDIO_EVENT_CALLBACK_SOUND_STOPPED = @as(c_int, 0x00004000);
pub const FMOD_STUDIO_EVENT_CALLBACK_REAL_TO_VIRTUAL = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00008000, .hexadecimal);
pub const FMOD_STUDIO_EVENT_CALLBACK_VIRTUAL_TO_REAL = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00010000, .hexadecimal);
pub const FMOD_STUDIO_EVENT_CALLBACK_START_EVENT_COMMAND = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00020000, .hexadecimal);
pub const FMOD_STUDIO_EVENT_CALLBACK_NESTED_TIMELINE_BEAT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x00040000, .hexadecimal);
pub const FMOD_STUDIO_EVENT_CALLBACK_ALL = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFFFFFFF, .hexadecimal);
pub const FMOD_STUDIO_LOAD_BANK_NORMAL = @as(c_int, 0x00000000);
pub const FMOD_STUDIO_LOAD_BANK_NONBLOCKING = @as(c_int, 0x00000001);
pub const FMOD_STUDIO_LOAD_BANK_DECOMPRESS_SAMPLES = @as(c_int, 0x00000002);
pub const FMOD_STUDIO_LOAD_BANK_UNENCRYPTED = @as(c_int, 0x00000004);
pub const FMOD_STUDIO_COMMANDCAPTURE_NORMAL = @as(c_int, 0x00000000);
pub const FMOD_STUDIO_COMMANDCAPTURE_FILEFLUSH = @as(c_int, 0x00000001);
pub const FMOD_STUDIO_COMMANDCAPTURE_SKIP_INITIAL_STATE = @as(c_int, 0x00000002);
pub const FMOD_STUDIO_COMMANDREPLAY_NORMAL = @as(c_int, 0x00000000);
pub const FMOD_STUDIO_COMMANDREPLAY_SKIP_CLEANUP = @as(c_int, 0x00000001);
pub const FMOD_STUDIO_COMMANDREPLAY_FAST_FORWARD = @as(c_int, 0x00000002);
pub const FMOD_STUDIO_COMMANDREPLAY_SKIP_BANK_LOAD = @as(c_int, 0x00000004); | src/fmod.zig |
const std = @import("std");
const string = []const u8;
const zfetch = @import("zfetch");
const UrlValues = @import("UrlValues");
const extras = @import("extras");
const shared = @import("./shared.zig");
pub fn AllOf(comptime xs: []const type) type {
var fields: []const std.builtin.TypeInfo.StructField = &.{};
inline for (xs) |item| {
fields = fields ++ std.meta.fields(item);
}
return Struct(fields);
}
fn Struct(comptime fields: []const std.builtin.TypeInfo.StructField) type {
return @Type(.{ .Struct = .{ .layout = .Auto, .fields = fields, .decls = &.{}, .is_tuple = false } });
}
pub const Method = enum {
get,
head,
post,
put,
patch,
delete,
};
pub fn name(comptime Top: type, comptime This: type) string {
inline for (std.meta.declarations(Top)) |item| {
if (item.is_pub and @field(Top, item.name) == This) {
return item.name;
}
}
@compileError("not found");
}
pub fn Fn(comptime method: Method, comptime endpoint: string, comptime P: type, comptime Q: type, comptime B: type, comptime R: type) type {
return struct {
pub usingnamespace switch (method) {
.get => struct {
pub const get = real;
},
.head => struct {
pub const head = real;
},
.post => struct {
pub const post = real;
},
.put => struct {
pub const put = real;
},
.patch => struct {
pub const patch = real;
},
.delete => struct {
pub const delete = real;
},
};
const real = switch (P) {
void => switch (Q) {
void => switch (B) {
void => unreachable,
else => inner1_B,
},
else => switch (B) {
void => inner1_Q,
else => inner2_QB,
},
},
else => switch (Q) {
void => switch (B) {
void => inner1_P,
else => inner2_PB,
},
else => switch (B) {
void => inner2_PQ,
else => inner,
},
},
};
fn inner1_P(alloc: std.mem.Allocator, args: P) !R {
return inner(alloc, args, {}, {});
}
fn inner1_Q(alloc: std.mem.Allocator, args: Q) !R {
return inner(alloc, {}, args, {});
}
fn inner1_B(alloc: std.mem.Allocator, args: B) !R {
return inner(alloc, {}, {}, args);
}
fn inner2_PQ(alloc: std.mem.Allocator, args1: P, args2: Q) !R {
return inner(alloc, args1, args2, {});
}
fn inner2_PB(alloc: std.mem.Allocator, args1: P, args2: B) !R {
return inner(alloc, args1, {}, args2);
}
fn inner2_QB(alloc: std.mem.Allocator, args1: Q, args2: B) !R {
return inner(alloc, {}, args1, args2);
}
fn inner(alloc: std.mem.Allocator, argsP: P, argsQ: Q, argsB: B) !R {
@setEvalBranchQuota(1_000_000);
const endpoint_actual = comptime replace(replace(endpoint, '{', "{["), '}', "]s}");
const url = try std.fmt.allocPrint(alloc, "http://localhost" ++ "/" ++ shared.version ++ endpoint_actual, if (P != void) argsP else .{});
var paramsQ = try newUrlValues(alloc, Q, argsQ);
defer paramsQ.inner.deinit();
const full_url = try std.mem.concat(alloc, u8, &.{ url, "?", try paramsQ.encode() });
std.log.debug("{s} {s}", .{ @tagName(fixMethod(method)), full_url });
var conn = try zfetch.Connection.connect(alloc, .{ .protocol = .unix, .hostname = "/var/run/docker.sock" });
var req = try zfetch.Request.fromConnection(alloc, conn, full_url);
var paramsB = try newUrlValues(alloc, B, argsB);
defer paramsB.inner.deinit();
var headers = zfetch.Headers.init(alloc);
try headers.appendValue("Content-Type", "application/x-www-form-urlencoded");
try req.do(fixMethod(method), headers, if (paramsB.inner.count() == 0) null else try paramsB.encode());
const r = req.reader();
const body_content = try r.readAllAlloc(alloc, 1024 * 1024 * 5);
const code = try std.fmt.allocPrint(alloc, "{d}", .{req.status.code});
std.log.debug("{d}", .{req.status.code});
std.log.debug("{s}", .{body_content});
inline for (std.meta.fields(R)) |item| {
if (std.mem.eql(u8, item.name, code)) {
var jstream = std.json.TokenStream.init(body_content);
const res = try std.json.parse(extras.FieldType(R, @field(std.meta.FieldEnum(R), item.name)), &jstream, .{
.allocator = alloc,
.ignore_unknown_fields = true,
});
return @unionInit(R, item.name, res);
}
}
@panic(code);
}
};
}
fn replace(comptime haystack: string, comptime needle: u8, comptime replacement: string) string {
comptime var res: string = &.{};
inline for (haystack) |c| {
if (c == needle) {
res = res ++ replacement;
} else {
const temp: string = &.{c};
res = res ++ temp;
}
}
return res;
}
fn newUrlValues(alloc: std.mem.Allocator, comptime T: type, args: T) !*UrlValues {
var params = try alloc.create(UrlValues);
params.* = UrlValues.init(alloc);
inline for (meta_fields(T)) |item| {
const U = item.field_type;
const key = item.name;
const value = @field(args, item.name);
if (comptime std.meta.trait.isZigString(U)) {
try params.add(key, value);
} else if (U == bool) {
try params.add(key, if (value) "true" else "false");
} else if (U == i32) {
try params.add(key, try std.fmt.allocPrint(alloc, "{d}", .{value}));
} else {
@compileError(@typeName(U));
}
}
return params;
}
fn meta_fields(comptime T: type) []const std.builtin.TypeInfo.StructField {
return switch (@typeInfo(T)) {
.Struct => std.meta.fields(T),
.Void => &.{},
else => |v| @compileError(@tagName(v)),
};
}
fn fixMethod(m: Method) zfetch.Method {
return switch (m) {
.get => .GET,
.head => .HEAD,
.post => .POST,
.put => .PUT,
.patch => .PATCH,
.delete => .DELETE,
};
} | src/internal.zig |
const std = @import("std");
const debug = std.debug;
const assert = debug.assert;
const mem = std.mem;
const os = std.os;
// used for sleep, and other, it may be removed
// to relax libC needs
const c = @cImport({
@cInclude("stdio.h");
@cInclude("unistd.h");
@cInclude("signal.h");
@cInclude("time.h");
@cInclude("string.h");
});
const leveldb = @import("leveldb.zig");
const mqtt = @import("mqttlib.zig");
const processlib = @import("processlib.zig");
const topics = @import("topics.zig");
const toml = @import("toml");
const stdoutFile = std.io.getStdOut();
const out = std.fs.File.writer(stdoutFile);
const Verbose = false;
// This structure defines the process informations
// with live agent running, this permit to track the process and
// relaunch it if needed
//
const AdditionalProcessInformation = struct {
// pid is to track the process while running
pid: ?i32 = undefined,
// process identifier attributed by IOTMonitor, to track existing processes
// processIdentifier: []const u8 = "",
exec: []const u8 = "",
};
const MonitoringInfo = struct {
// name of the device
name: []const u8 = "",
watchTopics: []const u8,
nextContact: c.time_t,
timeoutValue: u32 = 30,
stateTopics: ?[]const u8 = null,
helloTopic: ?[]const u8 = null,
helloTopicCount: u64 = 0,
allocator: *mem.Allocator,
// in case of process informations,
associatedProcessInformation: ?*AdditionalProcessInformation = null,
fn init(allocator: *mem.Allocator) !*MonitoringInfo {
const device = try allocator.create(MonitoringInfo);
device.allocator = allocator;
device.stateTopics = null;
device.helloTopic = null;
device.helloTopicCount = 0;
device.timeoutValue = 30;
device.associatedProcessInformation = null;
return device;
}
fn deinit(self: *MonitoringInfo) void {
self.allocator.destroy(self);
}
fn updateNextContact(device: *MonitoringInfo) !void {
_ = c.time(&device.*.nextContact);
device.*.nextContact = device.*.nextContact + @intCast(c_long, device.*.timeoutValue);
}
fn hasExpired(device: *MonitoringInfo) !bool {
var currentTime: c.time_t = undefined;
_ = c.time(¤tTime);
const diff = c.difftime(currentTime, device.*.nextContact);
if (diff > 0) return true;
return false;
}
};
fn stripLastWildCard(watchValue: []const u8) ![]const u8 {
assert(watchValue.len > 0);
if (watchValue[watchValue.len - 1] == '#') {
return watchValue[0 .. watchValue.len - 2];
}
return watchValue;
}
test "test update time" {
var d = MonitoringInfo{
.timeoutValue = 1,
.watchTopics = "",
.nextContact = undefined,
.allocator = undefined,
.helloTopic = undefined,
.stateTopics = undefined,
.associatedProcessInformation = undefined,
};
try d.updateNextContact();
_ = c.sleep(3);
debug.assert(try d.hasExpired());
d.timeoutValue = 20;
try d.updateNextContact();
_ = c.sleep(3);
debug.assert(!try d.hasExpired());
}
pub fn secureZero(comptime T: type, s: []T) void {
// NOTE: We do not use a volatile slice cast here since LLVM cannot
// see that it can be replaced by a memset.
const ptr = @ptrCast([*]volatile u8, s.ptr);
const length = s.len * @sizeOf(T);
@memset(ptr, 0, length);
}
// parse the device info,
// device must have a watch topics
fn parseDevice(allocator: *mem.Allocator, name: *[]const u8, entry: *toml.Table) !*MonitoringInfo {
const device = try MonitoringInfo.init(allocator);
errdefer device.deinit();
const allocName = try allocator.alloc(u8, name.*.len + 1);
secureZero(u8, allocName);
std.mem.copy(u8, allocName, name.*);
device.name = allocName;
if (entry.getKey("exec")) |exec| {
const execValue = exec.String;
assert(execValue.len > 0);
const execCommand = try allocator.allocSentinel(u8, execValue.len, 0);
mem.copy(u8, execCommand, execValue);
const additionalStructure = try allocator.create(AdditionalProcessInformation);
additionalStructure.exec = execCommand;
additionalStructure.pid = null;
device.associatedProcessInformation = additionalStructure;
}
if (entry.getKey("watchTopics")) |watch| {
// there may have a wildcard at the end
// strip it to compare to the received topic
const watchValue = watch.String;
assert(watchValue.len > 0);
device.watchTopics = try stripLastWildCard(watchValue);
if (Verbose) {
_ = try out.print("add {} to device {} \n", .{ device.name, device.watchTopics });
}
} else {
return error.DEVICE_MUST_HAVE_A_WATCH_TOPIC;
}
if (entry.getKey("stateTopics")) |watch| {
// there may have a wildcard at the end
// strip it to compare to the received topic
const watchValue = watch.String;
assert(watchValue.len > 0);
device.stateTopics = try stripLastWildCard(watchValue);
if (Verbose) {
_ = try out.print("add {} to device {} \n", .{ device.name, device.stateTopics });
}
}
if (entry.getKey("helloTopic")) |hello| {
const helloValue = hello.String;
assert(helloValue.len > 0);
device.helloTopic = helloValue;
if (Verbose) {
_ = try out.print("hello topic for device {s}\n", .{device.helloTopic});
}
}
if (entry.getKey("watchTimeOut")) |timeout| {
const timeOutValue = timeout.Integer;
device.timeoutValue = @intCast(u32, timeOutValue);
if (Verbose) {
_ = try out.print("watch timeout for topic for device {}\n", .{device.helloTopic});
}
}
try device.updateNextContact();
return device;
}
const Config = struct {
clientId: []const u8,
mqttBroker: []const u8,
user: []const u8,
password: []const u8,
clientid: []const u8,
mqttIotmonitorBaseTopic: []u8
};
var MqttConfig: *Config = undefined;
fn parseTomlConfig(allocator: *mem.Allocator, _alldevices: *AllDevices, filename: []const u8) !void {
// getting config parameters
var config = try toml.parseFile(allocator, filename);
defer config.deinit();
var it = config.children.iterator();
while (it.next()) |e| {
if (e.key_ptr.*.len >= 7) {
const DEVICEPREFIX = "device_";
const AGENTPREFIX = "agent_";
const isDevice = mem.eql(u8, e.key_ptr.*[0..DEVICEPREFIX.len], DEVICEPREFIX);
const isAgent = mem.eql(u8, e.key_ptr.*[0..AGENTPREFIX.len], AGENTPREFIX);
if (isDevice or isAgent) {
if (Verbose) {
try out.print("device found :{}\n", .{e.key_ptr.*});
}
var prefixlen = AGENTPREFIX.len;
if (isDevice) prefixlen = DEVICEPREFIX.len;
const dev = try parseDevice(allocator, &e.key_ptr.*[prefixlen..], e.value_ptr.*);
if (Verbose) {
try out.print("add {} to device list, with watch {} and state {} \n", .{ dev.name, dev.watchTopics, dev.stateTopics });
}
_ = try _alldevices.put(dev.name, dev);
}
}
}
const conf = try allocator.create(Config);
if (config.getTable("mqtt")) |mqttconfig| {
if (mqttconfig.getKey("serverAddress")) |configAdd| {
conf.mqttBroker = configAdd.String;
} else {
return error.noKeyServerAddress;
}
if (mqttconfig.getKey("user")) |u| {
conf.user = u.String;
} else {
return error.ConfigNoUser;
}
if (mqttconfig.getKey("password")) |p| {
conf.password = p.String;
} else {
return error.ConfigNoPassword;
}
if (mqttconfig.getKey("clientid")) |cid| {
conf.clientid = cid.String;
try out.print("Using {s} as clientid \n", .{ conf.clientid });
} else {
conf.clientid = "iotmonitor";
}
const topicBase = if (mqttconfig.getKey("baseTopic")) |baseTopic| baseTopic.String else "home/monitoring";
conf.mqttIotmonitorBaseTopic = try allocator.alloc(u8, topicBase.len + 1);
conf.mqttIotmonitorBaseTopic[topicBase.len] = 0;
mem.copy(u8, conf.mqttIotmonitorBaseTopic, topicBase[0..topicBase.len]);
} else {
return error.ConfignoMqtt;
}
MqttConfig = conf;
}
fn _external_callback(topic: []u8, message: []u8) void {
callback(topic, message) catch {
@panic("error in the callback");
};
}
// MQTT Callback implementation
fn callback(topic: []u8, message: []u8) !void {
// MQTT callback
if (Verbose) {
try out.print("on topic {}\n", .{topic});
try out.print(" message arrived {}\n", .{message});
try out.writeAll(topic);
try out.writeAll("\n");
}
// look for all devices
var iterator = alldevices.iterator();
// device loop
while (iterator.next()) |e| {
const deviceInfo = e.value_ptr.*;
if (Verbose) {
try out.print("evaluate {} with {} \n", .{ deviceInfo.stateTopics, topic });
}
const watchTopic = deviceInfo.watchTopics;
const storeTopic = deviceInfo.stateTopics;
const helloTopic = deviceInfo.helloTopic;
if (storeTopic) |store| {
if (try topics.doesTopicBelongTo(topic, store)) |sub| {
// store sub topic in leveldb
// trigger the refresh for timeout
if (Verbose) {
try out.print("sub topic to store value :{}, in {}\n", .{ message, topic });
try out.print("length {}\n", .{topic.len});
}
db.put(topic, message) catch |errStorage| {
debug.warn("fail to store message {s} for topic {s}, on database with error {} \n", .{ message, topic, errStorage });
};
}
}
if (helloTopic) |hello| {
if (mem.eql(u8, topic, hello)) {
if (Verbose) {
try out.print("device started, put all state informations \n", .{});
}
// count the number of hello topic
//
//
deviceInfo.helloTopicCount += 1;
// iterate on db, on state topic
const itstorage = try db.iterator();
// itstorage is an allocated pointer
defer globalAllocator.destroy(itstorage);
defer itstorage.deinit();
itstorage.first();
while (itstorage.isValid()) {
var storedTopic = itstorage.iterKey();
if (storedTopic) |storedTopicValue| {
defer globalAllocator.destroy(storedTopicValue);
if (storedTopicValue.len >= topic.len) {
const slice = storedTopicValue.*;
if (mem.eql(u8, slice[0..topic.len], topic[0..])) {
var stateTopic = itstorage.iterValue();
if (stateTopic) |stateTopicValue| {
// try out.print("sending state {} to topic {}\n", .{ stateTopic.?.*, slice });
defer globalAllocator.destroy(stateTopicValue);
const topicWithSentinel = try globalAllocator.allocSentinel(u8, storedTopicValue.*.len, 0);
defer globalAllocator.free(topicWithSentinel);
mem.copy(u8, topicWithSentinel[0..], storedTopicValue.*);
// resend state
cnx.publish(topicWithSentinel, stateTopicValue.*) catch |errorMqtt| {
std.debug.warn("ERROR {} fail to publish initial state on topic {}", .{ errorMqtt, topicWithSentinel });
try out.print(".. state restoring done, listening mqtt topics\n", .{});
};
}
}
}
}
itstorage.next();
}
}
} // hello
if (try topics.doesTopicBelongTo(topic, watchTopic)) |sub| {
// trigger the timeout for the iot element
try deviceInfo.updateNextContact();
}
}
if (Verbose) {
try out.print("end of callback \n", .{});
}
}
// global types
const AllDevices = std.StringHashMap(*MonitoringInfo);
const DiskHash = leveldb.LevelDBHashArray(u8, u8);
// global variables
const globalAllocator = std.heap.c_allocator;
var alldevices: AllDevices = undefined;
var db: *DiskHash = undefined;
test "read whole database" {
var arena = std.heap.ArenaAllocator.init(std.heap.c_allocator);
defer arena.deinit();
globalAllocator = &arena.allocator;
db = try DiskHash.init(globalAllocator);
const filename = "iotdb.leveldb";
_ = try db.open(filename);
defer db.close();
const iterator = try db.iterator();
defer globalAllocator.destroy(iterator);
defer iterator.deinit();
debug.warn("Dump the iot database \n", .{});
iterator.first();
while (iterator.isValid()) {
const optReadKey = iterator.iterKey();
if (optReadKey) |k| {
defer globalAllocator.destroy(k);
const optReadValue = iterator.iterValue();
if (optReadValue) |v| {
debug.warn(" key :{} value: {}\n", .{ k.*, v.* });
defer globalAllocator.destroy(v);
}
}
iterator.next();
}
}
// main connection for subscription
var cnx: *mqtt.MqttCnx = undefined;
var cpt: u32 = 0;
const MAGICPROCSSHEADER = "IOTMONITORMAGIC_";
const MAGIC_BUFFER_SIZE = 16 * 1024;
const LAUNCH_COMMAND_LINE_BUFFER_SIZE = 16 * 1024;
fn launchProcess(monitoringInfo: *MonitoringInfo) !void {
assert(monitoringInfo.associatedProcessInformation != null);
const associatedProcessInformation = monitoringInfo.*.associatedProcessInformation.?.*;
const pid = try os.fork();
if (pid == 0) {
// detach from parent, this permit the process to live independently from
// its parent
_ = c.setsid();
const bufferMagic = try globalAllocator.allocSentinel(u8, MAGIC_BUFFER_SIZE, 0);
defer globalAllocator.free(bufferMagic);
_ = c.sprintf(bufferMagic.ptr, "%s%s", MAGICPROCSSHEADER, monitoringInfo.name.ptr);
const commandLineBuffer = try globalAllocator.allocSentinel(u8, LAUNCH_COMMAND_LINE_BUFFER_SIZE, 0);
defer globalAllocator.free(commandLineBuffer);
const exec = associatedProcessInformation.exec;
_ = c.sprintf(commandLineBuffer.ptr, "echo %s;%s;echo END", bufferMagic.ptr, exec.ptr);
// launch here a bash to have a silent process identification
const argv = [_][]const u8{
"/bin/bash",
"-c",
commandLineBuffer[0..c.strlen(commandLineBuffer)],
};
var m = std.BufMap.init(globalAllocator);
// may add additional information about the process ...
try m.put("IOTMONITORMAGIC", bufferMagic[0..c.strlen(bufferMagic)]);
// execute the process
const err = std.process.execve(globalAllocator, &argv, &m);
// if succeeded the process is replaced
// otherwise this is an error
unreachable;
} else {
try out.print("process launched, pid : {}\n", .{pid});
monitoringInfo.*.associatedProcessInformation.?.pid = pid;
}
}
test "test_launch_process" {
globalAllocator = std.heap.c_allocator;
alldevices = AllDevices.init(globalAllocator);
var processInfo = AdditionalProcessInformation{
.exec = "sleep 20",
.pid = undefined,
};
var d = MonitoringInfo{
.timeoutValue = 1,
.name = "MYPROCESS",
.watchTopics = "",
.nextContact = undefined,
.allocator = undefined,
.helloTopic = undefined,
.stateTopics = undefined,
.associatedProcessInformation = &processInfo,
};
// try launchProcess(&d);
// const pid: i32 = d.associatedProcessInformation.?.*.pid.?;
// debug.warn("pid launched : {}\n", .{pid});
try alldevices.put(d.name, &d);
// var p: processlib.ProcessInformation = .{};
// const processFound = try processlib.getProcessInformations(pid, &p);
// assert(processFound);
try processlib.listProcesses(handleCheckAgent);
}
fn handleCheckAgent(processInformation: *processlib.ProcessInformation) void {
// iterate over the devices, to check which device belong to this process
// information
var it = alldevices.iterator();
while (it.next()) |deviceInfo| {
const device = deviceInfo.value_ptr.*;
// not on optional
if (device.associatedProcessInformation) |infos| {
// check if process has the magic Key
var itCmdLine = processInformation.iterator();
while (itCmdLine.next()) |a| {
if (Verbose) {
out.print("look in {}\n", .{a.ptr}) catch unreachable;
}
const bufferMagic = globalAllocator.allocSentinel(u8, MAGIC_BUFFER_SIZE, 0) catch unreachable;
defer globalAllocator.free(bufferMagic);
_ = c.sprintf(bufferMagic.ptr, "%s%s", MAGICPROCSSHEADER, device.name.ptr);
const p = c.strstr(a.ptr, bufferMagic.ptr);
if (Verbose) {
out.print("found {}\n", .{p}) catch unreachable;
}
if (p != null) {
// found in arguments, remember the pid
// of the process
infos.*.pid = processInformation.*.pid;
if (Verbose) {
out.print("process {} is monitored pid found\n", .{infos.pid}) catch unreachable;
}
break;
}
if (Verbose) {
out.writeAll("next ..\n") catch unreachable;
}
}
} else {
continue;
}
}
}
fn runAllMissings() !void {
// once all the process have been browsed,
// run all missing processes
var it = alldevices.iterator();
while (it.next()) |deviceinfo| {
const device = deviceinfo.value_ptr.*;
if (device.associatedProcessInformation) |processinfo| {
// this is a process monitored
if (processinfo.*.pid == null) {
out.print("running ...{s} \n", .{device.name}) catch unreachable;
// no pid associated to the info
//
launchProcess(device) catch {
@panic("fail to run process");
};
}
}
}
}
fn checkProcessesAndRunMissing() !void {
// RAZ pid infos
var it = alldevices.iterator();
while (it.next()) |deviceInfo| {
const device = deviceInfo.value_ptr.*;
if (device.associatedProcessInformation) |infos| {
infos.pid = null;
}
}
// list all process for wrapping
try processlib.listProcesses(handleCheckAgent);
try runAllMissings();
}
// this function publish a watchdog for the iotmonitor process
// this permit to check if the monitoring is up
fn publishWatchDog() !void {
var topicBufferPayload = try globalAllocator.alloc(u8, 512);
defer globalAllocator.free(topicBufferPayload);
secureZero(u8, topicBufferPayload);
_ = c.sprintf(topicBufferPayload.ptr, "%s/up", MqttConfig.mqttIotmonitorBaseTopic.ptr);
var bufferPayload = try globalAllocator.alloc(u8, 512);
defer globalAllocator.free(bufferPayload);
secureZero(u8, bufferPayload);
cpt = (cpt + 1) % 1_000_000;
_ = c.sprintf(bufferPayload.ptr, "%d", cpt);
cpt = (cpt + 1) % 1_000_000;
_ = c.sprintf(bufferPayload.ptr, "%d", cpt);
const topicloadLength = c.strlen(topicBufferPayload.ptr);
const payloadLength = c.strlen(bufferPayload.ptr);
cnx.publish(topicBufferPayload.ptr, bufferPayload[0..payloadLength]) catch {
std.debug.warn("cannot publish watchdog message, will retryi \n", .{});
};
}
fn publishDeviceMonitoringInfos(device: *MonitoringInfo) !void {
var topicBufferPayload = try globalAllocator.alloc(u8, 512);
defer globalAllocator.free(topicBufferPayload);
secureZero(u8, topicBufferPayload);
_ = c.sprintf(topicBufferPayload.ptr, "%s/helloTopicCount/%s", MqttConfig.mqttIotmonitorBaseTopic.ptr, device.*.name.ptr);
var bufferPayload = try globalAllocator.alloc(u8, 512);
defer globalAllocator.free(bufferPayload);
secureZero(u8, bufferPayload);
_ = c.sprintf(bufferPayload.ptr, "%u", device.helloTopicCount);
const payloadLen = c.strlen(bufferPayload.ptr);
cnx.publish(topicBufferPayload.ptr, bufferPayload[0..payloadLen]) catch {
std.debug.warn("cannot publish timeout message for device {} , will retry \n", .{device.name});
};
}
// this function pulish a mqtt message for a device that is not publishing
// it mqtt messages
fn publishDeviceTimeOut(device: *MonitoringInfo) !void {
var topicBufferPayload = try globalAllocator.alloc(u8, 512);
defer globalAllocator.free(topicBufferPayload);
secureZero(u8, topicBufferPayload);
_ = c.sprintf(topicBufferPayload.ptr, "%s/expired/%s", MqttConfig.mqttIotmonitorBaseTopic.ptr, device.*.name.ptr);
var bufferPayload = try globalAllocator.alloc(u8, 512);
defer globalAllocator.free(bufferPayload);
secureZero(u8, bufferPayload);
_ = c.sprintf(bufferPayload.ptr, "%d", device.nextContact);
const payloadLen = c.strlen(bufferPayload.ptr);
cnx.publish(topicBufferPayload.ptr, bufferPayload[0..payloadLen]) catch {
std.debug.warn("cannot publish timeout message for device {} , will retry \n", .{device.name});
};
}
// main procedure
pub fn main() !void {
try out.writeAll("IotMonitor start, version 0.2.2\n");
try out.writeAll("-------------------------------\n");
alldevices = AllDevices.init(globalAllocator);
const configurationFile = "config.toml";
try out.writeAll("Reading the config file\n");
try parseTomlConfig(globalAllocator, &alldevices, configurationFile);
try out.writeAll("Opening database\n");
db = try DiskHash.init(globalAllocator);
const filename = "iotdb.leveldb";
_ = try db.open(filename);
defer db.close();
// connecting to MQTT
var serverAddress: []const u8 = MqttConfig.mqttBroker;
var userName: []const u8 = MqttConfig.user;
var password: []const u8 = MqttConfig.password;
var clientid: []const u8 = MqttConfig.clientid;
try out.writeAll("Connecting to mqtt ..\n");
try out.print("connecting to {s} with user {s}\n", .{ serverAddress, userName });
cnx = try mqtt.MqttCnx.init(globalAllocator, serverAddress, clientid, userName, password);
try out.print("checking running monitored processes\n", .{});
try checkProcessesAndRunMissing();
try out.print("restoring saved states topics ... \n", .{});
// read all elements in database, then redefine the state for all
const it = try db.iterator();
defer globalAllocator.destroy(it);
defer it.deinit();
it.first();
while (it.isValid()) {
const r = it.iterKey();
if (r) |subject| {
defer globalAllocator.destroy(subject);
const v = it.iterValue();
if (v) |value| {
defer globalAllocator.destroy(value);
try out.print("sending initial stored state {s} to {s}\n", .{ value.*, subject.* });
const topicWithSentinel = try globalAllocator.allocSentinel(u8, subject.*.len, 0);
defer globalAllocator.free(topicWithSentinel);
mem.copy(u8, topicWithSentinel[0..], subject.*);
// if failed, stop the process
cnx.publish(topicWithSentinel, value.*) catch |e| {
std.debug.warn("ERROR {} fail to publish initial state on topic {s}", .{ e, topicWithSentinel });
try out.print(".. state restoring done, listening mqtt topics\n", .{});
};
}
}
it.next();
}
try out.print(".. state restoring done, listening mqtt topics\n", .{});
cnx.callBack = _external_callback;
// register to all, it may be huge, and probably not scaling
_ = try cnx.register("#");
while (true) {
_ = c.sleep(1); // in seconds
try checkProcessesAndRunMissing();
try publishWatchDog();
var iterator = alldevices.iterator();
while (iterator.next()) |e| {
// publish message
const deviceInfo = e.value_ptr.*;
const hasExpired = try deviceInfo.hasExpired();
if (hasExpired) {
try publishDeviceTimeOut(deviceInfo);
}
try publishDeviceMonitoringInfos(deviceInfo);
}
}
debug.warn("ended", .{});
return;
} | iotmonitor.zig |
const std = @import("std");
const eql = std.meta.eql;
const Allocator = std.mem.Allocator;
const Arena = std.heap.ArenaAllocator;
const assert = std.debug.assert;
const panic = std.debug.panic;
const init_codebase = @import("init_codebase.zig");
const initCodebase = init_codebase.initCodebase;
const initBuiltins = init_codebase.initBuiltins;
const List = @import("list.zig").List;
const ecs = @import("ecs.zig");
const Entity = ecs.Entity;
const ECS = ecs.ECS;
const strings = @import("strings.zig");
const Strings = strings.Strings;
const InternedString = strings.InternedString;
const tokenize = @import("tokenizer.zig").tokenize;
const parse = @import("parser.zig").parse;
const MockFileSystem = @import("file_system.zig").FileSystem;
const components = @import("components.zig");
const query = @import("query.zig");
const literalOf = query.literalOf;
const typeOf = query.typeOf;
const parentType = query.parentType;
const valueType = query.valueType;
const colors = @import("colors.zig");
fn Context(comptime FileSystem: type) type {
return struct {
allocator: Allocator,
codebase: *ECS,
file_system: FileSystem,
module: Entity,
function: Entity,
active_scopes: []const u64,
builtins: *const components.Builtins,
const Self = @This();
const Match = enum {
no,
implicit_conversion,
exact,
};
fn convertibleTo(self: *Self, to: Entity, from: Entity) Match {
if (eql(to, from)) return .exact;
const b = self.builtins;
const builtins = [_]Entity{ b.I64, b.I32, b.I16, b.I8, b.U64, b.U32, b.U16, b.U8, b.F64, b.F32 };
const float_builtins = [_]Entity{ b.F64, b.F32 };
if (eql(from, b.IntLiteral)) {
for (builtins) |builtin| {
if (eql(to, builtin)) return .implicit_conversion;
}
if (eql(to, b.FloatLiteral)) return .implicit_conversion;
return .no;
}
if (eql(from, b.FloatLiteral)) {
for (float_builtins) |builtin| {
if (eql(to, builtin)) return .implicit_conversion;
}
return .no;
}
if (from.has(components.ParentType)) |parent_type| {
assert(eql(parent_type.entity, b.Array));
const from_value_type = from.get(components.ValueType).entity;
const to_value_type = to.get(components.ValueType).entity;
return self.convertibleTo(to_value_type, from_value_type);
}
return .no;
}
fn implicitTypeConversion(self: *Self, value: Entity, expected_type: Entity) error{OutOfMemory}!void {
const actual_type = typeOf(value);
const b = self.builtins;
assert(self.convertibleTo(expected_type, actual_type) != .no);
_ = try value.set(.{components.Type.init(expected_type)});
if (value.has(components.DependentEntities)) |dependent_entities| {
for (dependent_entities.slice()) |entity| {
const t = typeOf(entity);
if (!eql(t, b.IntLiteral) and !eql(t, b.FloatLiteral)) continue;
try self.implicitTypeConversion(entity, expected_type);
}
}
}
fn unifyTypes(self: *Self, lhs: Entity, rhs: Entity) !Entity {
const lhs_type = typeOf(lhs);
const rhs_type = typeOf(rhs);
switch (self.convertibleTo(lhs_type, rhs_type)) {
.exact => return lhs_type,
.implicit_conversion => {
_ = try rhs.set(.{components.Type.init(lhs_type)});
if (rhs.has(components.DependentEntities)) |dependent_entities| {
for (dependent_entities.slice()) |entity| {
try self.implicitTypeConversion(entity, lhs_type);
}
}
return lhs_type;
},
.no => {
switch (self.convertibleTo(rhs_type, lhs_type)) {
.exact => return rhs_type,
.implicit_conversion => {
_ = try lhs.set(.{components.Type.init(rhs_type)});
if (lhs.has(components.DependentEntities)) |dependent_entities| {
for (dependent_entities.slice()) |entity| {
try self.implicitTypeConversion(entity, rhs_type);
}
}
return rhs_type;
},
.no => {
panic("\ncannot unify {s} and {s}\n", .{
literalOf(lhs_type),
literalOf(rhs_type),
});
},
}
},
}
}
fn analyzeSymbol(self: *Self, entity: Entity) !Entity {
const literal = entity.get(components.Literal);
const scopes = self.function.get(components.Scopes);
if (scopes.hasLiteral(literal)) |local| {
return local;
}
const global_scope = self.codebase.get(components.Scope);
if (global_scope.hasLiteral(literal)) |global| {
return global;
}
const top_level_scope = self.module.get(components.TopLevel);
if (top_level_scope.hasLiteral(literal)) |top_level| {
assert(top_level.get(components.AstKind) == .overload_set);
const overloads = top_level.get(components.Overloads).slice();
assert(overloads.len == 1);
const overload = overloads[0];
assert(overload.get(components.AstKind) == .struct_);
return overload;
}
panic("\nanalyzeSymbol failed for symbol {s}\n", .{literalOf(entity)});
}
const Candidate = struct {
overload: Entity,
match: Match,
named_arguments: components.OrderedNamedArguments,
literal: components.Literal,
module: Entity,
};
const CalleeContext = struct {
module: Entity,
call: Entity,
callable: Entity,
arguments: []const Entity,
named_arguments: components.NamedArguments,
literal: components.Literal,
};
fn checkCandidatesForModule(self: *Self, callee_context: CalleeContext, candidate: *Candidate, ordered_named_arguments: []Entity) !void {
const top_level = self.module.get(components.TopLevel);
if (top_level.hasLiteral(candidate.literal)) |function| {
const overloads = function.get(components.Overloads).slice();
for (overloads) |overload| {
const kind = overload.get(components.AstKind);
if (kind == .struct_) {
const fields = overload.get(components.Fields).slice();
if (!overload.contains(components.AnalyzedFields)) {
for (fields) |field| {
const field_type = try self.analyzeExpression(field.get(components.TypeAst).entity);
_ = try field.set(.{
components.Type.init(field_type),
components.Name.init(field),
});
}
_ = try overload.set(.{components.AnalyzedFields{ .value = true }});
}
if (fields.len < callee_context.arguments.len) continue;
var match = Match.exact;
var i: usize = 0;
while (i < callee_context.arguments.len) : (i += 1) {
const field_type = typeOf(fields[i]);
const argument_type = typeOf(callee_context.arguments[i]);
switch (self.convertibleTo(field_type, argument_type)) {
.exact => continue,
.implicit_conversion => if (match == .exact) {
match = .implicit_conversion;
},
.no => {
match = .no;
break;
},
}
}
while (i < fields.len) : (i += 1) {
const field = fields[i];
const field_type = typeOf(field);
if (callee_context.named_arguments.hasLiteral(field.get(components.Literal))) |argument| {
ordered_named_arguments[i - callee_context.arguments.len] = argument;
const argument_type = typeOf(argument);
switch (self.convertibleTo(field_type, argument_type)) {
.exact => continue,
.implicit_conversion => if (match == .exact) {
match = .implicit_conversion;
},
.no => {
match = .no;
break;
},
}
} else {
match = .no;
break;
}
}
if (@enumToInt(match) < @enumToInt(candidate.match)) continue;
if (match != .no and match == candidate.match) {
panic("ambiguous overload set overload match {} best match {}", .{ match, candidate.match });
}
candidate.match = match;
candidate.overload = overload;
candidate.module = self.module;
std.mem.copy(Entity, candidate.named_arguments.mutSlice(), ordered_named_arguments);
continue;
}
assert(kind == .function);
if (!overload.contains(components.AnalyzedParameters)) {
var scopes = components.Scopes.init(self.allocator, self.codebase.getPtr(Strings));
const scope = try scopes.pushScope();
_ = try overload.set(.{scopes});
const active_scopes = [_]u64{scope};
var context = Self{
.allocator = self.allocator,
.codebase = self.codebase,
.file_system = self.file_system,
.module = self.module,
.function = overload,
.active_scopes = &active_scopes,
.builtins = self.builtins,
};
try context.analyzeFunctionParameters();
}
const parameters = overload.get(components.Parameters).slice();
if (parameters.len < callee_context.arguments.len) continue;
var match = Match.exact;
var i: usize = 0;
while (i < callee_context.arguments.len) : (i += 1) {
const parameter_type = typeOf(parameters[i]);
const argument_type = typeOf(callee_context.arguments[i]);
switch (self.convertibleTo(parameter_type, argument_type)) {
.exact => continue,
.implicit_conversion => if (match == .exact) {
match = .implicit_conversion;
},
.no => {
match = .no;
break;
},
}
}
while (i < parameters.len) : (i += 1) {
const parameter = parameters[i];
const parameter_type = typeOf(parameter);
if (callee_context.named_arguments.hasLiteral(parameter.get(components.Literal))) |argument| {
ordered_named_arguments[i - callee_context.arguments.len] = argument;
const argument_type = typeOf(argument);
switch (self.convertibleTo(parameter_type, argument_type)) {
.exact => continue,
.implicit_conversion => if (match == .exact) {
match = .implicit_conversion;
},
.no => {
match = .no;
break;
},
}
} else {
match = .no;
break;
}
}
if (@enumToInt(match) < @enumToInt(candidate.match)) continue;
if (match != .no and match == candidate.match) {
panic("ambiguous overload set overload match {} best match {}", .{ match, candidate.match });
}
candidate.match = match;
candidate.overload = overload;
candidate.module = self.module;
std.mem.copy(Entity, candidate.named_arguments.mutSlice(), ordered_named_arguments);
}
} else {}
}
fn bestOverloadCandidate(self: *Self, callee_context: CalleeContext) !Candidate {
const count = callee_context.named_arguments.count();
var candidate = Candidate{
.overload = undefined,
.match = .no,
.named_arguments = try components.OrderedNamedArguments.withCapacity(self.allocator, count),
.literal = callee_context.callable.get(components.Literal),
.module = undefined,
};
candidate.named_arguments.values.len = count;
var ordered_named_arguments = try self.allocator.alloc(Entity, count);
try checkCandidatesForModule(self, callee_context, &candidate, ordered_named_arguments);
const imports = self.module.get(components.Imports).slice();
for (imports) |import| {
const module = blk: {
if (import.has(components.Module)) |m| {
break :blk m.entity;
} else {
const module_name = literalOf(import.get(components.Path).entity);
const contents = try self.file_system.read(module_name);
const interned = try self.codebase.getPtr(Strings).intern(module_name[0 .. module_name.len - 5]);
const module = try self.codebase.createEntity(.{components.Literal.init(interned)});
var tokens = try tokenize(module, contents);
try parse(module, &tokens);
const source = components.ModuleSource{ .string = contents };
const path = components.ModulePath{ .string = module_name };
_ = try module.set(.{
source,
path,
});
_ = try import.set(.{components.Module.init(module)});
break :blk module;
}
};
var context = Self{
.allocator = self.allocator,
.codebase = self.codebase,
.file_system = self.file_system,
.module = module,
.function = self.function,
.active_scopes = self.active_scopes,
.builtins = self.builtins,
};
try checkCandidatesForModule(&context, callee_context, &candidate, ordered_named_arguments);
}
if (candidate.match == .no) {
var body = List(u8, .{ .initial_capacity = 1000 }).init(self.allocator);
try body.appendSlice("No matching function overload found for argument types (");
for (callee_context.arguments) |argument, i| {
const argument_type = typeOf(argument);
try body.appendSlice(literalOf(argument_type));
if (i < callee_context.arguments.len - 1) {
try body.appendSlice(", ");
}
}
try body.append(')');
var hint = List(u8, .{ .initial_capacity = 1000 }).init(self.allocator);
try hint.appendSlice("Here are the possible candidates:\n");
var candidates = List(List(u8, .{}), .{ .initial_capacity = 8 }).init(self.allocator);
var file_and_lines = List(List(u8, .{}), .{ .initial_capacity = 8 }).init(self.allocator);
var candidate_width: usize = 0;
const top_level = self.module.get(components.TopLevel);
if (top_level.hasLiteral(candidate.literal)) |function| {
const overloads = function.get(components.Overloads).slice();
for (overloads) |overload| {
var candidate_error = List(u8, .{}).init(self.allocator);
try candidate_error.append('\n');
try candidate_error.appendSlice(literalOf(overload.get(components.Name).entity));
try candidate_error.append('(');
const parameters = overload.get(components.Parameters).slice();
for (parameters) |parameter, i| {
const parameter_type = typeOf(parameter);
var mismatch = false;
if (i < callee_context.arguments.len) {
mismatch = self.convertibleTo(parameter_type, typeOf(callee_context.arguments[i])) == .no;
} else {
mismatch = true;
}
if (mismatch) {
try candidate_error.appendSlice(colors.RED);
}
try candidate_error.appendSlice(literalOf(parameter));
try candidate_error.appendSlice(": ");
try candidate_error.appendSlice(literalOf(parameter_type));
if (mismatch) {
try candidate_error.appendSlice(colors.RESET);
}
if (i < parameters.len - 1) {
try candidate_error.appendSlice(", ");
}
}
try candidate_error.append(')');
try candidates.append(candidate_error);
candidate_width = std.math.max(candidate_width, candidate_error.len);
var file_and_line = List(u8, .{}).init(self.allocator);
try file_and_line.appendSlice(self.module.get(components.ModulePath).string);
try file_and_line.append(':');
const result = try std.fmt.allocPrint(self.allocator, "{}", .{overload.get(components.Span).begin.row + 1});
try file_and_line.appendSlice(result);
try file_and_lines.append(file_and_line);
}
}
const file_and_lines_slice = file_and_lines.slice();
for (candidates.slice()) |candidate_error, i| {
const candidate_slice = candidate_error.slice();
try hint.appendSlice(candidate_slice);
const delta = candidate_width - candidate_slice.len;
var spaces: usize = 0;
while (spaces < delta) : (spaces += 1) {
try hint.append(' ');
}
try hint.appendSlice(" ----- ");
try hint.appendSlice(file_and_lines_slice[i].slice());
}
try hint.append('\n');
const error_component = components.Error{
.header = "FUNCTION CALL ERROR",
.body = body.mutSlice(),
.span = callee_context.call.get(components.Span),
.hint = hint.mutSlice(),
.module = self.module,
};
_ = try callee_context.call.set(.{error_component});
return error.CompileError;
}
_ = try callee_context.call.set(.{candidate.named_arguments});
return candidate;
}
fn analyzePointer(self: *Self, entity: Entity) !Entity {
const value = try self.analyzeExpression(entity.get(components.Value).entity);
const b = self.builtins;
const type_of = typeOf(value);
if (eql(type_of, b.Type)) {
const memoized = b.Ptr.getPtr(components.Memoized);
const result = try memoized.getOrPut(value);
if (result.found_existing) {
return result.value_ptr.*;
}
const string = try std.fmt.allocPrint(self.allocator, "*{s}", .{literalOf(value)});
const interned = try self.codebase.getPtr(Strings).intern(string);
const pointer_type = try self.codebase.createEntity(.{
components.Literal.init(interned),
components.Type.init(b.Type),
components.ParentType.init(b.Ptr),
components.ValueType.init(value),
});
result.value_ptr.* = pointer_type;
return pointer_type;
}
assert(eql(parentType(type_of), b.Ptr));
const value_type = valueType(type_of);
const scalars = [_]Entity{ b.I64, b.I32, b.I16, b.I8, b.U64, b.U32, b.U16, b.U8, b.F64, b.F32 };
for (scalars) |scalar| {
if (eql(value_type, scalar)) {
return try self.codebase.createEntity(.{
components.AstKind.intrinsic,
components.Intrinsic.load,
try components.Arguments.fromSlice(self.allocator, &.{value}),
components.Type.init(valueType(type_of)),
});
}
}
const vectors = [_]Entity{ b.I64X2, b.I32X4, b.I16X8, b.I8X16, b.U64X2, b.U32X4, b.U16X8, b.U8X16, b.F64X2, b.F32X4 };
for (vectors) |vector| {
if (eql(value_type, vector)) {
return try self.codebase.createEntity(.{
components.AstKind.intrinsic,
components.Intrinsic.v128_load,
try components.Arguments.fromSlice(self.allocator, &.{value}),
components.Type.init(valueType(type_of)),
});
}
}
panic("\npointer of type {s} not supported yet\n", .{literalOf(value_type)});
}
fn arrayType(self: *Self, T: Entity) !Entity {
const literal = literalOf(T);
const b = self.builtins;
assert(eql(typeOf(T), b.Type));
const memoized = b.Array.getPtr(components.Memoized);
const result = try memoized.getOrPut(T);
if (result.found_existing) {
return result.value_ptr.*;
}
var fields = components.Fields.init(self.allocator);
{
const interned = try self.codebase.getPtr(Strings).intern("ptr");
const pointer_memoized = b.Ptr.getPtr(components.Memoized);
const pointer_result = try pointer_memoized.getOrPut(T);
const pointer_type = blk: {
if (pointer_result.found_existing) {
break :blk pointer_result.value_ptr.*;
} else {
const pointer_string = try std.fmt.allocPrint(self.allocator, "*{s}", .{literal});
const pointer_interned = try self.codebase.getPtr(Strings).intern(pointer_string);
const pointer_type = try self.codebase.createEntity(.{
components.Literal.init(pointer_interned),
components.Type.init(b.Type),
components.ParentType.init(b.Ptr),
components.ValueType.init(T),
});
pointer_result.value_ptr.* = pointer_type;
break :blk pointer_type;
}
};
const ptr = try self.codebase.createEntity(.{
components.Literal.init(interned),
components.Type.init(pointer_type),
});
_ = try ptr.set(.{components.Name.init(ptr)});
try fields.append(ptr);
}
{
const interned = try self.codebase.getPtr(Strings).intern("len");
const len = try self.codebase.createEntity(.{
components.Literal.init(interned),
components.Type.init(b.I32),
});
_ = try len.set(.{components.Name.init(len)});
try fields.append(len);
}
const string = try std.fmt.allocPrint(self.allocator, "[]{s}", .{literal});
const interned = try self.codebase.getPtr(Strings).intern(string);
const array_type = try self.codebase.createEntity(.{
components.AstKind.struct_,
components.Literal.init(interned),
components.Type.init(b.Type),
components.ParentType.init(b.Array),
components.ValueType.init(T),
fields,
});
result.value_ptr.* = array_type;
return array_type;
}
fn analyzeArray(self: *Self, entity: Entity) !Entity {
const value = try self.analyzeExpression(entity.get(components.Value).entity);
return try self.arrayType(value);
}
fn analyzeCast(self: *Self, arguments: []const Entity) !Entity {
assert(arguments.len == 2);
const b = self.builtins;
const to = arguments[0];
assert(eql(parentType(to), b.Ptr));
const value = arguments[1];
try self.implicitTypeConversion(value, b.I32);
return try self.codebase.createEntity(.{
components.AstKind.cast,
components.Type.init(to),
components.Value.init(value),
});
}
fn analyzeCall(self: *Self, call: Entity, callingContext: *Self) !Entity {
const callable = call.get(components.Callable).entity;
const call_arguments = call.get(components.Arguments).slice();
var analyzed_arguments = try components.Arguments.withCapacity(self.allocator, call_arguments.len);
for (call_arguments) |argument| {
const analyzed_argument = try callingContext.analyzeExpression(argument);
analyzed_arguments.appendAssumeCapacity(analyzed_argument);
}
var analyzed_named_arguments = components.NamedArguments.init(self.allocator, call.ecs.getPtr(Strings));
var iterator = call.get(components.NamedArguments).iterator();
while (iterator.next()) |pair| {
const argument = pair.value_ptr.*;
const analyzed_argument = try callingContext.analyzeExpression(argument);
try analyzed_named_arguments.putInterned(pair.key_ptr.*, analyzed_argument);
}
const callable_literal = callable.get(components.Literal);
if (eql(callable_literal, self.builtins.Cast.get(components.Literal))) {
return try self.analyzeCast(analyzed_arguments.slice());
}
const analyzed_arguments_slice = analyzed_arguments.slice();
const candidate = try self.bestOverloadCandidate(.{
.module = self.module,
.call = call,
.callable = callable,
.arguments = analyzed_arguments_slice,
.named_arguments = analyzed_named_arguments,
.literal = callable.get(components.Literal),
});
const kind = candidate.overload.get(components.AstKind);
if (kind == .function) {
if (!candidate.overload.contains(components.AnalyzedBody)) {
_ = try candidate.overload.set(.{components.AnalyzedBody{ .value = true }});
const scopes = candidate.overload.getPtr(components.Scopes).slice();
assert(scopes.len == 1);
const active_scopes = [_]u64{0};
var context = Self{
.allocator = self.allocator,
.codebase = self.codebase,
.file_system = self.file_system,
.module = candidate.module,
.function = candidate.overload,
.active_scopes = &active_scopes,
.builtins = self.builtins,
};
try context.analyzeFunction();
}
const parameters = candidate.overload.get(components.Parameters).slice();
var i: usize = 0;
while (i < analyzed_arguments_slice.len) : (i += 1) {
try self.implicitTypeConversion(analyzed_arguments_slice[i], typeOf(parameters[i]));
}
const ordered_named_arguments = call.get(components.OrderedNamedArguments);
const ordered_named_arguments_slice = ordered_named_arguments.slice();
while (i < parameters.len) : (i += 1) {
try self.implicitTypeConversion(ordered_named_arguments_slice[i - analyzed_arguments_slice.len], typeOf(parameters[i]));
}
const return_type = candidate.overload.get(components.ReturnType).entity;
return try self.codebase.createEntity(.{
components.Type.init(return_type),
components.Callable.init(candidate.overload),
components.AstKind.call,
analyzed_arguments,
analyzed_named_arguments,
call.get(components.Span),
ordered_named_arguments,
});
}
assert(kind == .struct_);
const fields = candidate.overload.get(components.Fields).slice();
var i: usize = 0;
while (i < analyzed_arguments_slice.len) : (i += 1) {
try self.implicitTypeConversion(analyzed_arguments_slice[i], typeOf(fields[i]));
}
const ordered_named_arguments = call.get(components.OrderedNamedArguments);
const ordered_named_arguments_slice = ordered_named_arguments.slice();
while (i < fields.len) : (i += 1) {
try self.implicitTypeConversion(ordered_named_arguments_slice[i - analyzed_arguments_slice.len], typeOf(fields[i]));
}
return try self.codebase.createEntity(.{
components.Type.init(candidate.overload),
components.AstKind.construct,
analyzed_arguments,
analyzed_named_arguments,
call.get(components.Span),
ordered_named_arguments,
});
}
fn uniformFunctionCall(self: *Self, lhs: Entity, rhs: Entity) !Entity {
const span = components.Span.init(
lhs.get(components.Span).begin,
rhs.get(components.Span).end,
);
switch (rhs.get(components.AstKind)) {
.call => {
const call = try self.codebase.createEntity(.{
components.AstKind.call,
rhs.get(components.Callable),
span,
rhs.get(components.NamedArguments),
});
try self.uniformFunctionCallArguments(call, lhs, rhs);
return try self.analyzeCall(call, self);
},
.symbol => {
const call_arguments = try components.Arguments.fromSlice(self.allocator, &.{lhs});
const named_arguments = components.NamedArguments.init(self.allocator, self.codebase.getPtr(Strings));
const call = try self.codebase.createEntity(.{
components.AstKind.call,
components.Callable.init(rhs),
call_arguments,
named_arguments,
span,
});
return try self.analyzeCall(call, self);
},
else => |k| panic("\nanalyze dot invalid rhs kind {}\n", .{k}),
}
}
fn analyzeDot(self: *Self, entity: Entity) !Entity {
const dot_arguments = entity.get(components.Arguments).slice();
const lhs = try self.analyzeExpression(dot_arguments[0]);
const rhs = dot_arguments[1];
const lhs_type = typeOf(lhs);
if (lhs.get(components.AstKind) == .local) {
if (lhs_type.has(components.AstKind)) |lhs_type_kind| {
assert(lhs_type_kind == .struct_);
switch (rhs.get(components.AstKind)) {
.symbol => {
const rhs_literal = rhs.get(components.Literal);
for (lhs_type.get(components.Fields).slice()) |field| {
if (!eql(field.get(components.Literal), rhs_literal)) continue;
return try self.codebase.createEntity(.{
components.AstKind.field,
components.Type.init(typeOf(field)),
components.Local.init(lhs),
components.Field.init(field),
});
}
},
.call => return try self.uniformFunctionCall(lhs, rhs),
else => |k| panic("\nanalyzed ot invalid rhs kind {}\n", .{k}),
}
} else return try self.uniformFunctionCall(lhs, rhs);
}
return try self.uniformFunctionCall(lhs, rhs);
}
fn uniformFunctionCallArguments(self: Self, analyzed_call: Entity, lhs: Entity, call: Entity) !void {
const arguments = call.get(components.Arguments).slice();
var underscore_index: ?u64 = null;
for (arguments) |argument, i| {
if (argument.get(components.AstKind) == .underscore) {
assert(underscore_index == null);
underscore_index = i;
}
}
if (underscore_index == null) {
var call_arguments = try components.Arguments.withCapacity(self.allocator, arguments.len + 1);
call_arguments.appendAssumeCapacity(lhs);
for (arguments) |argument| {
call_arguments.appendAssumeCapacity(argument);
}
_ = try analyzed_call.set(.{call_arguments});
return;
}
const call_arguments = try components.Arguments.fromSlice(self.allocator, arguments);
call_arguments.mutSlice()[underscore_index.?] = lhs;
_ = try analyzed_call.set(.{call_arguments});
}
fn analyzePointerArithmetic(self: *Self, lhs: Entity, rhs: Entity, intrinsic: components.Intrinsic) !Entity {
const rhs_type = typeOf(rhs);
const b = self.builtins;
if (eql(rhs_type, b.IntLiteral) or eql(rhs_type, b.I32)) {
try self.implicitTypeConversion(rhs, b.I32);
const new_intrinsic: components.Intrinsic = switch (intrinsic) {
.add => .add_ptr_i32,
.subtract => .subtract_ptr_i32,
else => panic("\nanalyze pointer arithmetic unsupported intrinsic {}\n", .{intrinsic}),
};
return try self.codebase.createEntity(.{
components.AstKind.intrinsic,
new_intrinsic,
try components.Arguments.fromSlice(self.allocator, &.{ lhs, rhs }),
lhs.get(components.Type),
});
}
assert(eql(valueType(typeOf(lhs)), valueType(rhs_type)));
switch (intrinsic) {
.equal, .not_equal, .greater_equal, .greater_than, .less_equal, .less_than => {
return try self.codebase.createEntity(.{
components.AstKind.intrinsic,
intrinsic,
try components.Arguments.fromSlice(self.allocator, &.{ lhs, rhs }),
components.Type.init(b.I32),
});
},
.subtract => {
return try self.codebase.createEntity(.{
components.AstKind.intrinsic,
components.Intrinsic.subtract_ptr_ptr,
try components.Arguments.fromSlice(self.allocator, &.{ lhs, rhs }),
components.Type.init(b.I32),
});
},
else => panic("\nanalyze pointer arithmetic unsupported intrinsic {}\n", .{intrinsic}),
}
}
fn analyzeIntrinsic(self: *Self, entity: Entity, intrinsic: components.Intrinsic, result_is_i32: bool) !Entity {
const arguments = entity.get(components.Arguments).slice();
const lhs = try self.analyzeExpression(arguments[0]);
const rhs = try self.analyzeExpression(arguments[1]);
const lhs_type = typeOf(lhs);
const b = self.builtins;
if (lhs_type.has(components.ParentType)) |parent_type| {
assert(eql(parent_type.entity, b.Ptr));
return try self.analyzePointerArithmetic(lhs, rhs, intrinsic);
}
const builtins = &[_]Entity{ b.I64, b.I32, b.I16, b.I8, b.U64, b.U32, b.U16, b.U8, b.F64, b.F32, b.IntLiteral, b.FloatLiteral };
for (builtins) |builtin| {
if (!eql(lhs_type, builtin)) continue;
const result_type = try self.unifyTypes(lhs, rhs);
const result = try self.codebase.createEntity(.{
components.AstKind.intrinsic,
try components.Arguments.fromSlice(self.allocator, &.{ lhs, rhs }),
intrinsic,
});
if (result_is_i32) {
_ = try result.set(.{components.Type.init(b.I32)});
if (eql(result_type, b.IntLiteral) or eql(result_type, b.FloatLiteral)) {
try addDependentEntities(lhs, &.{rhs});
try addDependentEntities(rhs, &.{lhs});
}
} else {
_ = try result.set(.{components.Type.init(result_type)});
if (eql(result_type, b.IntLiteral) or eql(result_type, b.FloatLiteral)) {
try addDependentEntities(result, &.{ lhs, rhs });
}
}
return result;
}
const vectors = &[_]Entity{ b.I64X2, b.I32X4, b.I16X8, b.I8X16, b.U64X2, b.U32X4, b.U16X8, b.U8X16 };
for (vectors) |vector| {
if (!eql(lhs_type, vector)) continue;
assert(intrinsic != .divide);
const result_type = try self.unifyTypes(lhs, rhs);
const type_of = components.Type.init(result_type);
return try self.codebase.createEntity(.{
components.AstKind.intrinsic,
intrinsic,
try components.Arguments.fromSlice(self.allocator, &.{ lhs, rhs }),
type_of,
});
}
const float_vectors = &[_]Entity{ b.F64X2, b.F32X4 };
for (float_vectors) |vector| {
if (!eql(lhs_type, vector)) continue;
const result_type = try self.unifyTypes(lhs, rhs);
const type_of = components.Type.init(result_type);
return try self.codebase.createEntity(.{
components.AstKind.intrinsic,
intrinsic,
try components.Arguments.fromSlice(self.allocator, &.{ lhs, rhs }),
type_of,
});
}
panic("\noperator overloading not yet implemented\n", .{});
}
fn analyzeBinaryOp(self: *Self, entity: Entity) !Entity {
const binary_op = entity.get(components.BinaryOp);
return try switch (binary_op) {
.dot => self.analyzeDot(entity),
.add => self.analyzeIntrinsic(entity, .add, false),
.subtract => self.analyzeIntrinsic(entity, .subtract, false),
.multiply => self.analyzeIntrinsic(entity, .multiply, false),
.divide => self.analyzeIntrinsic(entity, .divide, false),
.remainder => self.analyzeIntrinsic(entity, .remainder, false),
.bit_and => self.analyzeIntrinsic(entity, .bit_and, false),
.bit_or => self.analyzeIntrinsic(entity, .bit_or, false),
.bit_xor => self.analyzeIntrinsic(entity, .bit_xor, false),
.left_shift => self.analyzeIntrinsic(entity, .left_shift, false),
.right_shift => self.analyzeIntrinsic(entity, .right_shift, false),
.equal => self.analyzeIntrinsic(entity, .equal, true),
.not_equal => self.analyzeIntrinsic(entity, .not_equal, true),
.less_than => self.analyzeIntrinsic(entity, .less_than, true),
.less_equal => self.analyzeIntrinsic(entity, .less_equal, true),
.greater_than => self.analyzeIntrinsic(entity, .greater_than, true),
.greater_equal => self.analyzeIntrinsic(entity, .greater_equal, true),
};
}
fn analyzeDefine(self: *Self, define: Entity) !Entity {
const name = define.get(components.Name);
const value = try self.analyzeExpression(define.get(components.Value).entity);
const kind = name.entity.get(components.AstKind);
switch (kind) {
.symbol => {
const scopes = self.function.getPtr(components.Scopes);
if (scopes.hasName(name)) |local| {
assert(!define.contains(components.TypeAst));
_ = try local.set(.{components.Mutable{ .value = true }});
const type_of = try self.unifyTypes(value, local);
const b = self.builtins;
const assign = try self.codebase.createEntity(.{
components.AstKind.assign,
components.Value.init(value),
components.Local.init(local),
components.Type.init(b.Void),
});
if (eql(type_of, b.IntLiteral) or eql(type_of, b.FloatLiteral)) {
try addDependentEntities(local, &.{value});
}
return assign;
}
if (define.has(components.TypeAst)) |type_ast| {
const explicit_type = try analyzeExpression(self, type_ast.entity);
try self.implicitTypeConversion(value, explicit_type);
}
const b = self.builtins;
const type_of = typeOf(value);
const local = try self.codebase.createEntity(.{
components.AstKind.local,
name,
components.Type.init(type_of),
components.Value.init(value),
define.get(components.Span),
});
const analyzed_define = try self.codebase.createEntity(.{
components.AstKind.define,
components.Local.init(local),
components.Type.init(b.Void),
components.Value.init(value),
});
if (eql(type_of, b.IntLiteral)) {
try addDependentEntities(local, &.{value});
try self.function.getPtr(components.IntLiterals).append(local);
}
if (eql(type_of, b.FloatLiteral)) {
try addDependentEntities(local, &.{value});
}
try scopes.putName(name, local);
return analyzed_define;
},
.pointer => {
const pointer = try self.analyzeExpression(name.entity.get(components.Value).entity);
const pointer_type = typeOf(pointer);
const b = self.builtins;
assert(eql(parentType(pointer_type), b.Ptr));
const value_type = valueType(pointer_type);
try self.implicitTypeConversion(value, value_type);
const scalars = [_]Entity{ b.I64, b.I32, b.U64, b.U32, b.F64, b.F32 };
for (scalars) |scalar| {
if (eql(value_type, scalar)) {
return try self.codebase.createEntity(.{
components.AstKind.intrinsic,
components.Intrinsic.store,
try components.Arguments.fromSlice(self.allocator, &.{ pointer, value }),
components.Type.init(b.Void),
});
}
}
const vectors = [_]Entity{ b.I64X2, b.I32X4, b.I16X8, b.I8X16 };
for (vectors) |vector| {
if (eql(value_type, vector)) {
return try self.codebase.createEntity(.{
components.AstKind.intrinsic,
components.Intrinsic.v128_store,
try components.Arguments.fromSlice(self.allocator, &.{ pointer, value }),
components.Type.init(b.Void),
});
}
}
if (value_type.has(components.ParentType)) |value_type_parent_type| {
assert(eql(value_type_parent_type.entity, b.Ptr));
return try self.codebase.createEntity(.{
components.AstKind.intrinsic,
components.Intrinsic.store,
try components.Arguments.fromSlice(self.allocator, &.{ pointer, value }),
components.Type.init(b.Void),
});
}
panic("\nunsupported store for value type {s}\n", .{literalOf(value_type)});
},
.binary_op => {
const arguments = name.entity.get(components.Arguments).slice();
const lhs = try self.analyzeExpression(arguments[0]);
const type_of = typeOf(lhs);
assert(type_of.get(components.AstKind) == .struct_);
const fields = type_of.get(components.Fields).slice();
const rhs = arguments[1];
assert(rhs.get(components.AstKind) == .symbol);
const literal = rhs.get(components.Literal);
for (fields) |field| {
if (!eql(field.get(components.Literal), literal)) continue;
try self.implicitTypeConversion(value, typeOf(field));
return try self.codebase.createEntity(.{
components.AstKind.assign_field,
components.Type.init(self.builtins.Void),
components.Local.init(lhs),
components.Field.init(field),
components.Value.init(value),
});
}
panic("\nassigning to invalid field {s}\n", .{literalOf(rhs)});
},
else => panic("\nassigning to unsupported kind {}\n", .{kind}),
}
}
fn analyzePlusEqual(self: *Self, plus_equal: Entity) !Entity {
const arguments = plus_equal.get(components.Arguments).slice();
const left = arguments[0];
const right = arguments[1];
assert(left.get(components.AstKind) == .symbol);
const span = plus_equal.get(components.Span);
const binary_op_arguments = try components.Arguments.fromSlice(self.codebase.arena.allocator(), &.{ left, right });
const binary_op = try self.codebase.createEntity(.{
components.AstKind.binary_op,
components.BinaryOp.add,
span,
binary_op_arguments,
});
const define = try self.codebase.createEntity(.{
components.AstKind.define,
components.Name.init(arguments[0]),
components.Value.init(binary_op),
span,
});
return self.analyzeDefine(define);
}
fn analyzeTimesEqual(self: *Self, times_equal: Entity) !Entity {
const arguments = times_equal.get(components.Arguments).slice();
const left = arguments[0];
const right = arguments[1];
assert(left.get(components.AstKind) == .symbol);
const span = times_equal.get(components.Span);
const binary_op_arguments = try components.Arguments.fromSlice(self.codebase.arena.allocator(), &.{ left, right });
const binary_op = try self.codebase.createEntity(.{
components.AstKind.binary_op,
components.BinaryOp.multiply,
span,
binary_op_arguments,
});
const define = try self.codebase.createEntity(.{
components.AstKind.define,
components.Name.init(arguments[0]),
components.Value.init(binary_op),
span,
});
return self.analyzeDefine(define);
}
fn analyzeIf(self: *Self, if_: Entity) !Entity {
const scopes = self.function.getPtr(components.Scopes);
const conditional = try self.analyzeExpression(if_.get(components.Conditional).entity);
try self.implicitTypeConversion(conditional, self.builtins.I32);
const active_scopes = self.active_scopes;
const then = if_.get(components.Then).slice();
assert(then.len > 0);
const then_scopes = try self.allocator.alloc(u64, active_scopes.len + 1);
std.mem.copy(u64, then_scopes, active_scopes);
then_scopes[active_scopes.len] = try scopes.pushScope();
self.active_scopes = then_scopes;
var analyzed_then = try components.Then.withCapacity(self.allocator, then.len);
for (then) |entity| {
analyzed_then.appendAssumeCapacity(try self.analyzeExpression(entity));
}
const then_entity = analyzed_then.last();
const else_ = if_.get(components.Else).slice();
assert(else_.len > 0);
const else_scopes = try self.allocator.alloc(u64, active_scopes.len + 1);
std.mem.copy(u64, else_scopes, active_scopes);
else_scopes[active_scopes.len] = try scopes.pushScope();
self.active_scopes = else_scopes;
var analyzed_else = try components.Else.withCapacity(self.allocator, else_.len);
for (else_) |entity| {
analyzed_else.appendAssumeCapacity(try self.analyzeExpression(entity));
}
const else_entity = analyzed_else.last();
const type_of = try self.unifyTypes(then_entity, else_entity);
const result = try self.codebase.createEntity(.{
components.AstKind.if_,
components.Type.init(type_of),
components.Conditional.init(conditional),
analyzed_then,
analyzed_else,
});
if (eql(type_of, self.builtins.IntLiteral) or eql(type_of, self.builtins.FloatLiteral)) {
try addDependentEntities(result, &.{ then_entity, else_entity });
}
const finally_scopes = try self.allocator.alloc(u64, active_scopes.len + 1);
std.mem.copy(u64, finally_scopes, active_scopes);
finally_scopes[active_scopes.len] = try scopes.pushScope();
self.active_scopes = finally_scopes;
return result;
}
fn analyzeWhile(self: *Self, while_: Entity) !Entity {
const scopes = self.function.getPtr(components.Scopes);
const conditional = try self.analyzeExpression(while_.get(components.Conditional).entity);
try self.implicitTypeConversion(conditional, self.builtins.I32);
const active_scopes = self.active_scopes;
const body = while_.get(components.Body).slice();
assert(body.len > 0);
const body_scopes = try self.allocator.alloc(u64, active_scopes.len + 1);
std.mem.copy(u64, body_scopes, active_scopes);
body_scopes[active_scopes.len] = try scopes.pushScope();
self.active_scopes = body_scopes;
var analyzed_body = try components.Body.withCapacity(self.allocator, body.len);
for (body) |entity| {
analyzed_body.appendAssumeCapacity(try self.analyzeExpression(entity));
}
const result = try self.codebase.createEntity(.{
components.AstKind.while_,
components.Type.init(self.builtins.Void),
components.Conditional.init(conditional),
analyzed_body,
});
const finally_scopes = try self.allocator.alloc(u64, active_scopes.len + 1);
std.mem.copy(u64, finally_scopes, active_scopes);
finally_scopes[active_scopes.len] = try scopes.pushScope();
self.active_scopes = finally_scopes;
return result;
}
fn analyzeFor(self: *Self, for_: Entity) !Entity {
const scopes = self.function.getPtr(components.Scopes);
const iterator = try self.analyzeExpression(for_.get(components.Iterator).entity);
const loop_variable = blk: {
if (for_.has(components.LoopVariable)) |loop_variable| {
break :blk loop_variable.entity;
} else {
const interned = try self.codebase.getPtr(Strings).intern("it");
break :blk try self.codebase.createEntity(.{
components.TokenKind.symbol,
components.Literal.init(interned),
});
}
};
const name = components.Name.init(loop_variable);
const first = iterator.get(components.First).entity;
const last = iterator.get(components.Last).entity;
const type_of = typeOf(first);
const local = try self.codebase.createEntity(.{
components.AstKind.local,
name,
components.Type.init(type_of),
});
if (eql(type_of, self.builtins.IntLiteral)) {
try addDependentEntities(local, &.{ first, last });
}
const define = try self.codebase.createEntity(.{
components.AstKind.define,
components.Local.init(local),
components.Type.init(self.builtins.Void),
components.Value.init(first),
});
try scopes.putName(name, local);
const active_scopes = self.active_scopes;
const body = for_.get(components.Body).slice();
assert(body.len > 0);
const body_scopes = try self.allocator.alloc(u64, active_scopes.len + 1);
std.mem.copy(u64, body_scopes, active_scopes);
body_scopes[active_scopes.len] = try scopes.pushScope();
self.active_scopes = body_scopes;
var analyzed_body = try components.Body.withCapacity(self.allocator, body.len);
for (body) |entity| {
analyzed_body.appendAssumeCapacity(try self.analyzeExpression(entity));
}
const result = try self.codebase.createEntity(.{
components.AstKind.for_,
components.Type.init(self.builtins.Void),
components.LoopVariable.init(define),
components.Iterator.init(iterator),
analyzed_body,
});
const finally_scopes = try self.allocator.alloc(u64, active_scopes.len + 1);
std.mem.copy(u64, finally_scopes, active_scopes);
finally_scopes[active_scopes.len] = try scopes.pushScope();
self.active_scopes = finally_scopes;
if (eql(typeOf(local), self.builtins.IntLiteral)) {
try self.function.getPtr(components.IntLiterals).append(local);
}
return result;
}
fn analyzeRange(self: *Self, entity: Entity) !Entity {
const b = self.builtins;
const first = blk: {
if (entity.has(components.First)) |first| {
break :blk try self.analyzeExpression(first.entity);
} else {
const interned = try self.codebase.getPtr(Strings).intern("0");
break :blk try self.codebase.createEntity(.{
components.AstKind.int,
components.Literal.init(interned),
components.Type.init(b.IntLiteral),
});
}
};
const last = try self.analyzeExpression(entity.get(components.Last).entity);
const type_of = try self.unifyTypes(first, last);
const range_type = blk: {
const memoized = b.Range.getPtr(components.Memoized);
const result = try memoized.getOrPut(type_of);
if (result.found_existing) {
break :blk result.value_ptr.*;
}
const string = try std.fmt.allocPrint(self.allocator, "Range({s})", .{literalOf(type_of)});
const interned = try self.codebase.getPtr(Strings).intern(string);
break :blk try self.codebase.createEntity(.{
components.Literal.init(interned),
components.Type.init(b.Type),
components.ParentType.init(b.Range),
components.ValueType.init(type_of),
});
};
return try self.codebase.createEntity(.{
components.Type.init(range_type),
components.AstKind.range,
entity.get(components.Span),
components.First.init(first),
components.Last.init(last),
});
}
fn analyzeString(self: *Self, entity: Entity) !Entity {
const b = self.builtins;
const array_type = try self.arrayType(b.U8);
return entity.set(.{components.Type.init(array_type)});
}
fn analyzeArrayLiteral(self: *Self, entity: Entity) !Entity {
const values = entity.get(components.Values).slice();
assert(values.len > 1);
var analyzed_values = try components.Values.withCapacity(self.allocator, values.len);
const first = try self.analyzeExpression(values[0]);
try analyzed_values.append(first);
for (values[1..]) |value| {
const analyzed_value = try self.analyzeExpression(value);
try analyzed_values.append(analyzed_value);
}
const array_type = try self.arrayType(typeOf(first));
return try self.codebase.createEntity(.{
components.AstKind.array_literal,
components.Type.init(array_type),
analyzed_values,
});
}
fn analyzeChar(self: *Self, entity: Entity) !Entity {
const char = literalOf(entity)[0];
const string = try std.fmt.allocPrint(self.allocator, "{}", .{char});
const interned = try self.codebase.getPtr(Strings).intern(string);
return try self.codebase.createEntity(.{
components.Type.init(self.builtins.U8),
components.Literal.init(interned),
components.AstKind.int,
entity.get(components.Span),
});
}
fn analyzeIndex(self: *Self, entity: Entity) !Entity {
const arguments = entity.get(components.Arguments).slice();
const array = try self.analyzeExpression(arguments[0]);
const array_type = typeOf(array);
const parent_type = parentType(array_type);
const value_type = valueType(array_type);
assert(eql(parent_type, self.builtins.Array));
const index = try self.analyzeExpression(arguments[1]);
try self.implicitTypeConversion(index, self.builtins.I32);
return try self.codebase.createEntity(.{
components.AstKind.index,
try components.Arguments.fromSlice(self.allocator, &.{ array, index }),
entity.get(components.Span),
components.Type.init(value_type),
});
}
const Error = error{ Overflow, InvalidCharacter, OutOfMemory, CantOpenFile, CannotUnifyTypes, CompileError };
fn analyzeExpression(self: *Self, entity: Entity) Error!Entity {
if (entity.contains(components.AnalyzedExpression)) return entity;
const kind = entity.get(components.AstKind);
const analyzed_entity = switch (kind) {
.symbol => try self.analyzeSymbol(entity),
.int, .float => entity,
.call => try self.analyzeCall(entity, self),
.binary_op => try self.analyzeBinaryOp(entity),
.define => try self.analyzeDefine(entity),
.if_ => try self.analyzeIf(entity),
.while_ => try self.analyzeWhile(entity),
.for_ => try self.analyzeFor(entity),
.pointer => try self.analyzePointer(entity),
.array => try self.analyzeArray(entity),
.range => try self.analyzeRange(entity),
.string => try self.analyzeString(entity),
.array_literal => try self.analyzeArrayLiteral(entity),
.char => try self.analyzeChar(entity),
.plus_equal => try self.analyzePlusEqual(entity),
.times_equal => try self.analyzeTimesEqual(entity),
.index => try self.analyzeIndex(entity),
else => panic("\nanalyzeExpression unsupported kind {}\n", .{kind}),
};
_ = try analyzed_entity.set(.{components.AnalyzedExpression{ .value = true }});
return analyzed_entity;
}
fn analyzeFunctionParameters(self: *Self) !void {
const scopes = self.function.getPtr(components.Scopes);
const parameters = self.function.get(components.Parameters).slice();
for (parameters) |parameter| {
const parameter_type = try self.analyzeExpression(parameter.get(components.TypeAst).entity);
_ = try parameter.set(.{
components.Type.init(parameter_type),
components.Name.init(parameter),
components.AstKind.local,
});
try scopes.putLiteral(parameter.get(components.Literal), parameter);
}
_ = try self.function.set(.{components.AnalyzedParameters{ .value = true }});
}
fn analyzeFunctionBody(self: *Self, body: []const Entity) !Entity {
var analyzed_body = try components.Body.withCapacity(self.allocator, body.len);
for (body) |expression| {
try analyzed_body.append(try self.analyzeExpression(expression));
}
_ = try self.function.set(.{analyzed_body});
const sliced = analyzed_body.slice();
assert(sliced.len > 0);
return sliced[sliced.len - 1];
}
fn analyzeFunction(self: *Self) !void {
_ = try self.function.set(.{
components.Module.init(self.module),
components.IntLiterals.init(self.allocator),
});
if (!self.function.contains(components.AnalyzedParameters)) {
try self.analyzeFunctionParameters();
}
const return_type = blk: {
if (self.function.has(components.ReturnTypeAst)) |return_type_ast| {
const analyzed = try self.analyzeExpression(return_type_ast.entity);
_ = try self.function.set(.{components.ReturnType.init(analyzed)});
break :blk analyzed;
} else {
break :blk null;
}
};
if (self.function.has(components.Body)) |body| {
_ = try self.codebase.getPtr(components.Functions).append(self.function);
const return_entity = try self.analyzeFunctionBody(body.slice());
if (return_type) |entity| {
try self.implicitTypeConversion(return_entity, entity);
}
for (self.function.get(components.IntLiterals).slice()) |int_literal| {
if (eql(typeOf(int_literal), self.builtins.IntLiteral)) {
try self.implicitTypeConversion(int_literal, self.builtins.I32);
}
}
if (return_type == null) {
const return_entity_type = typeOf(return_entity);
if (eql(return_entity_type, self.builtins.IntLiteral)) {
try self.implicitTypeConversion(return_entity, self.builtins.I32);
_ = try self.function.set(.{components.ReturnType.init(self.builtins.I32)});
} else if (eql(return_entity_type, self.builtins.FloatLiteral)) {
try self.implicitTypeConversion(return_entity, self.builtins.F32);
_ = try self.function.set(.{components.ReturnType.init(self.builtins.F32)});
} else {
_ = try self.function.set(.{components.ReturnType.init(return_entity_type)});
}
}
} else {
_ = try self.codebase.getPtr(components.ForeignImports).append(self.function);
}
}
};
}
fn addDependentEntities(entity: Entity, entities: []const Entity) !void {
if (entity.contains(components.DependentEntities)) {
const dependent_entities = entity.getPtr(components.DependentEntities);
for (entities) |e| {
try dependent_entities.append(e);
}
} else {
_ = try entity.set(.{
try components.DependentEntities.fromSlice(entity.ecs.arena.allocator(), entities),
});
}
}
fn analyzeOverload(file_system: anytype, module: Entity, overload: Entity) !void {
if (overload.contains(components.AnalyzedBody)) return;
_ = try overload.set(.{components.AnalyzedBody{ .value = true }});
const codebase = overload.ecs;
const allocator = codebase.arena.allocator();
var scopes = components.Scopes.init(allocator, codebase.getPtr(Strings));
const scope = try scopes.pushScope();
_ = try overload.set(.{scopes});
const active_scopes = [_]u64{scope};
var context = Context(@TypeOf(file_system)){
.allocator = allocator,
.codebase = codebase,
.file_system = file_system,
.module = module,
.function = overload,
.active_scopes = &active_scopes,
.builtins = codebase.getPtr(components.Builtins),
};
try context.analyzeFunction();
}
pub fn analyzeSemantics(codebase: *ECS, file_system: anytype, module_name: []const u8) !Entity {
const allocator = codebase.arena.allocator();
_ = try codebase.set(.{components.Functions.init(allocator)});
_ = try codebase.set(.{components.ForeignImports.init(allocator)});
const contents = try file_system.read(module_name);
const interned = try codebase.getPtr(Strings).intern(module_name[0 .. module_name.len - 5]);
const source = components.ModuleSource{ .string = contents };
const path = components.ModulePath{ .string = module_name };
const module = try codebase.createEntity(.{
source,
path,
components.Literal.init(interned),
});
var tokens = try tokenize(module, contents);
try parse(module, &tokens);
const top_level = module.get(components.TopLevel);
const foreign_exports = module.get(components.ForeignExports).slice();
if (foreign_exports.len > 0) {
for (foreign_exports) |foreign_export| {
const literal = foreign_export.get(components.Literal);
const overloads = top_level.findLiteral(literal).get(components.Overloads).slice();
assert(overloads.len == 1);
try analyzeOverload(file_system, module, overloads[0]);
}
} else {
const overloads = top_level.findString("start").get(components.Overloads).slice();
assert(overloads.len == 1);
try analyzeOverload(file_system, module, overloads[0]);
}
return module;
} | src/semantic_analyzer.zig |
const std = @import("std");
fn root() []const u8 {
return std.fs.path.dirname(@src().file) orelse ".";
}
fn pathJoinRoot(comptime components: []const []const u8) []const u8 {
var ret = root();
inline for (components) |component|
ret = ret ++ std.fs.path.sep_str ++ component;
return ret;
}
const srcs = blk: {
@setEvalBranchQuota(10000);
var ret = &.{
pathJoinRoot(&.{ "c", "deps", "http-parser", "http_parser.c" }),
pathJoinRoot(&.{ "c", "src", "allocators", "failalloc.c" }),
pathJoinRoot(&.{ "c", "src", "allocators", "stdalloc.c" }),
pathJoinRoot(&.{ "c", "src", "streams", "openssl.c" }),
pathJoinRoot(&.{ "c", "src", "streams", "registry.c" }),
pathJoinRoot(&.{ "c", "src", "streams", "socket.c" }),
pathJoinRoot(&.{ "c", "src", "streams", "tls.c" }),
pathJoinRoot(&.{"mbedtls.c"}),
pathJoinRoot(&.{ "c", "src", "transports", "auth.c" }),
pathJoinRoot(&.{ "c", "src", "transports", "credential.c" }),
pathJoinRoot(&.{ "c", "src", "transports", "http.c" }),
pathJoinRoot(&.{ "c", "src", "transports", "httpclient.c" }),
pathJoinRoot(&.{ "c", "src", "transports", "smart_protocol.c" }),
pathJoinRoot(&.{ "c", "src", "transports", "ssh.c" }),
pathJoinRoot(&.{ "c", "src", "transports", "git.c" }),
pathJoinRoot(&.{ "c", "src", "transports", "smart.c" }),
pathJoinRoot(&.{ "c", "src", "transports", "smart_pkt.c" }),
pathJoinRoot(&.{ "c", "src", "transports", "local.c" }),
pathJoinRoot(&.{ "c", "src", "xdiff", "xdiffi.c" }),
pathJoinRoot(&.{ "c", "src", "xdiff", "xemit.c" }),
pathJoinRoot(&.{ "c", "src", "xdiff", "xhistogram.c" }),
pathJoinRoot(&.{ "c", "src", "xdiff", "xmerge.c" }),
pathJoinRoot(&.{ "c", "src", "xdiff", "xpatience.c" }),
pathJoinRoot(&.{ "c", "src", "xdiff", "xprepare.c" }),
pathJoinRoot(&.{ "c", "src", "xdiff", "xutils.c" }),
pathJoinRoot(&.{ "c", "src", "hash", "sha1", "mbedtls.c" }),
pathJoinRoot(&.{ "c", "src", "alloc.c" }),
pathJoinRoot(&.{ "c", "src", "annotated_commit.c" }),
pathJoinRoot(&.{ "c", "src", "apply.c" }),
pathJoinRoot(&.{ "c", "src", "attr.c" }),
pathJoinRoot(&.{ "c", "src", "attrcache.c" }),
pathJoinRoot(&.{ "c", "src", "attr_file.c" }),
pathJoinRoot(&.{ "c", "src", "blame.c" }),
pathJoinRoot(&.{ "c", "src", "blame_git.c" }),
pathJoinRoot(&.{ "c", "src", "blob.c" }),
pathJoinRoot(&.{ "c", "src", "branch.c" }),
pathJoinRoot(&.{ "c", "src", "buffer.c" }),
pathJoinRoot(&.{ "c", "src", "cache.c" }),
pathJoinRoot(&.{ "c", "src", "checkout.c" }),
pathJoinRoot(&.{ "c", "src", "cherrypick.c" }),
pathJoinRoot(&.{ "c", "src", "clone.c" }),
pathJoinRoot(&.{ "c", "src", "commit.c" }),
pathJoinRoot(&.{ "c", "src", "commit_graph.c" }),
pathJoinRoot(&.{ "c", "src", "commit_list.c" }),
pathJoinRoot(&.{ "c", "src", "config.c" }),
pathJoinRoot(&.{ "c", "src", "config_cache.c" }),
pathJoinRoot(&.{ "c", "src", "config_entries.c" }),
pathJoinRoot(&.{ "c", "src", "config_file.c" }),
pathJoinRoot(&.{ "c", "src", "config_mem.c" }),
pathJoinRoot(&.{ "c", "src", "config_parse.c" }),
pathJoinRoot(&.{ "c", "src", "config_snapshot.c" }),
pathJoinRoot(&.{ "c", "src", "crlf.c" }),
pathJoinRoot(&.{ "c", "src", "date.c" }),
pathJoinRoot(&.{ "c", "src", "delta.c" }),
pathJoinRoot(&.{ "c", "src", "describe.c" }),
pathJoinRoot(&.{ "c", "src", "diff.c" }),
pathJoinRoot(&.{ "c", "src", "diff_driver.c" }),
pathJoinRoot(&.{ "c", "src", "diff_file.c" }),
pathJoinRoot(&.{ "c", "src", "diff_generate.c" }),
pathJoinRoot(&.{ "c", "src", "diff_parse.c" }),
pathJoinRoot(&.{ "c", "src", "diff_print.c" }),
pathJoinRoot(&.{ "c", "src", "diff_stats.c" }),
pathJoinRoot(&.{ "c", "src", "diff_tform.c" }),
pathJoinRoot(&.{ "c", "src", "diff_xdiff.c" }),
pathJoinRoot(&.{ "c", "src", "errors.c" }),
pathJoinRoot(&.{ "c", "src", "email.c" }),
pathJoinRoot(&.{ "c", "src", "fetch.c" }),
pathJoinRoot(&.{ "c", "src", "fetchhead.c" }),
pathJoinRoot(&.{ "c", "src", "filebuf.c" }),
pathJoinRoot(&.{ "c", "src", "filter.c" }),
pathJoinRoot(&.{ "c", "src", "futils.c" }),
pathJoinRoot(&.{ "c", "src", "graph.c" }),
pathJoinRoot(&.{ "c", "src", "hash.c" }),
pathJoinRoot(&.{ "c", "src", "hashsig.c" }),
pathJoinRoot(&.{ "c", "src", "ident.c" }),
pathJoinRoot(&.{ "c", "src", "idxmap.c" }),
pathJoinRoot(&.{ "c", "src", "ignore.c" }),
pathJoinRoot(&.{ "c", "src", "index.c" }),
pathJoinRoot(&.{ "c", "src", "indexer.c" }),
pathJoinRoot(&.{ "c", "src", "iterator.c" }),
pathJoinRoot(&.{ "c", "src", "libgit2.c" }),
pathJoinRoot(&.{ "c", "src", "mailmap.c" }),
pathJoinRoot(&.{ "c", "src", "merge.c" }),
pathJoinRoot(&.{ "c", "src", "merge_driver.c" }),
pathJoinRoot(&.{ "c", "src", "merge_file.c" }),
pathJoinRoot(&.{ "c", "src", "message.c" }),
pathJoinRoot(&.{ "c", "src", "midx.c" }),
pathJoinRoot(&.{ "c", "src", "mwindow.c" }),
pathJoinRoot(&.{ "c", "src", "net.c" }),
pathJoinRoot(&.{ "c", "src", "netops.c" }),
pathJoinRoot(&.{ "c", "src", "notes.c" }),
pathJoinRoot(&.{ "c", "src", "object_api.c" }),
pathJoinRoot(&.{ "c", "src", "object.c" }),
pathJoinRoot(&.{ "c", "src", "odb.c" }),
pathJoinRoot(&.{ "c", "src", "odb_loose.c" }),
pathJoinRoot(&.{ "c", "src", "odb_mempack.c" }),
pathJoinRoot(&.{ "c", "src", "odb_pack.c" }),
pathJoinRoot(&.{ "c", "src", "offmap.c" }),
pathJoinRoot(&.{ "c", "src", "oidarray.c" }),
pathJoinRoot(&.{ "c", "src", "oid.c" }),
pathJoinRoot(&.{ "c", "src", "oidmap.c" }),
pathJoinRoot(&.{ "c", "src", "pack.c" }),
pathJoinRoot(&.{ "c", "src", "pack-objects.c" }),
pathJoinRoot(&.{ "c", "src", "parse.c" }),
pathJoinRoot(&.{ "c", "src", "patch.c" }),
pathJoinRoot(&.{ "c", "src", "patch_generate.c" }),
pathJoinRoot(&.{ "c", "src", "patch_parse.c" }),
pathJoinRoot(&.{ "c", "src", "path.c" }),
pathJoinRoot(&.{ "c", "src", "pathspec.c" }),
pathJoinRoot(&.{ "c", "src", "pool.c" }),
pathJoinRoot(&.{ "c", "src", "pqueue.c" }),
pathJoinRoot(&.{ "c", "src", "proxy.c" }),
pathJoinRoot(&.{ "c", "src", "push.c" }),
pathJoinRoot(&.{ "c", "src", "reader.c" }),
pathJoinRoot(&.{ "c", "src", "rebase.c" }),
pathJoinRoot(&.{ "c", "src", "refdb.c" }),
pathJoinRoot(&.{ "c", "src", "refdb_fs.c" }),
pathJoinRoot(&.{ "c", "src", "reflog.c" }),
pathJoinRoot(&.{ "c", "src", "refs.c" }),
pathJoinRoot(&.{ "c", "src", "refspec.c" }),
pathJoinRoot(&.{ "c", "src", "regexp.c" }),
pathJoinRoot(&.{ "c", "src", "remote.c" }),
pathJoinRoot(&.{ "c", "src", "repository.c" }),
pathJoinRoot(&.{ "c", "src", "reset.c" }),
pathJoinRoot(&.{ "c", "src", "revert.c" }),
pathJoinRoot(&.{ "c", "src", "revparse.c" }),
pathJoinRoot(&.{ "c", "src", "revwalk.c" }),
pathJoinRoot(&.{ "c", "src", "runtime.c" }),
pathJoinRoot(&.{ "c", "src", "signature.c" }),
pathJoinRoot(&.{ "c", "src", "sortedcache.c" }),
pathJoinRoot(&.{ "c", "src", "stash.c" }),
pathJoinRoot(&.{ "c", "src", "status.c" }),
pathJoinRoot(&.{ "c", "src", "strarray.c" }),
pathJoinRoot(&.{ "c", "src", "strmap.c" }),
pathJoinRoot(&.{ "c", "src", "submodule.c" }),
pathJoinRoot(&.{ "c", "src", "sysdir.c" }),
pathJoinRoot(&.{ "c", "src", "tag.c" }),
pathJoinRoot(&.{ "c", "src", "thread.c" }),
pathJoinRoot(&.{ "c", "src", "threadstate.c" }),
pathJoinRoot(&.{ "c", "src", "trace.c" }),
pathJoinRoot(&.{ "c", "src", "trailer.c" }),
pathJoinRoot(&.{ "c", "src", "transaction.c" }),
pathJoinRoot(&.{ "c", "src", "transport.c" }),
pathJoinRoot(&.{ "c", "src", "tree.c" }),
pathJoinRoot(&.{ "c", "src", "tree-cache.c" }),
pathJoinRoot(&.{ "c", "src", "tsort.c" }),
pathJoinRoot(&.{ "c", "src", "utf8.c" }),
pathJoinRoot(&.{ "c", "src", "util.c" }),
pathJoinRoot(&.{ "c", "src", "varint.c" }),
pathJoinRoot(&.{ "c", "src", "vector.c" }),
pathJoinRoot(&.{ "c", "src", "wildmatch.c" }),
pathJoinRoot(&.{ "c", "src", "worktree.c" }),
pathJoinRoot(&.{ "c", "src", "zstream.c" }),
};
break :blk ret;
};
const zlib_srcs = &.{
pathJoinRoot(&.{ "c", "deps", "zlib", "adler32.c" }),
pathJoinRoot(&.{ "c", "deps", "zlib", "crc32.c" }),
pathJoinRoot(&.{ "c", "deps", "zlib", "deflate.c" }),
pathJoinRoot(&.{ "c", "deps", "zlib", "infback.c" }),
pathJoinRoot(&.{ "c", "deps", "zlib", "inffast.c" }),
pathJoinRoot(&.{ "c", "deps", "zlib", "inflate.c" }),
pathJoinRoot(&.{ "c", "deps", "zlib", "inftrees.c" }),
pathJoinRoot(&.{ "c", "deps", "zlib", "trees.c" }),
pathJoinRoot(&.{ "c", "deps", "zlib", "zutil.c" }),
};
const pcre_srcs = &.{
pathJoinRoot(&.{ "c", "deps", "pcre", "pcre_byte_order.c" }),
pathJoinRoot(&.{ "c", "deps", "pcre", "pcre_chartables.c" }),
pathJoinRoot(&.{ "c", "deps", "pcre", "pcre_compile.c" }),
pathJoinRoot(&.{ "c", "deps", "pcre", "pcre_config.c" }),
pathJoinRoot(&.{ "c", "deps", "pcre", "pcre_dfa_exec.c" }),
pathJoinRoot(&.{ "c", "deps", "pcre", "pcre_exec.c" }),
pathJoinRoot(&.{ "c", "deps", "pcre", "pcre_fullinfo.c" }),
pathJoinRoot(&.{ "c", "deps", "pcre", "pcre_get.c" }),
pathJoinRoot(&.{ "c", "deps", "pcre", "pcre_globals.c" }),
pathJoinRoot(&.{ "c", "deps", "pcre", "pcre_jit_compile.c" }),
pathJoinRoot(&.{ "c", "deps", "pcre", "pcre_maketables.c" }),
pathJoinRoot(&.{ "c", "deps", "pcre", "pcre_newline.c" }),
pathJoinRoot(&.{ "c", "deps", "pcre", "pcre_ord2utf8.c" }),
pathJoinRoot(&.{ "c", "deps", "pcre", "pcreposix.c" }),
pathJoinRoot(&.{ "c", "deps", "pcre", "pcre_printint.c" }),
pathJoinRoot(&.{ "c", "deps", "pcre", "pcre_refcount.c" }),
pathJoinRoot(&.{ "c", "deps", "pcre", "pcre_string_utils.c" }),
pathJoinRoot(&.{ "c", "deps", "pcre", "pcre_study.c" }),
pathJoinRoot(&.{ "c", "deps", "pcre", "pcre_tables.c" }),
pathJoinRoot(&.{ "c", "deps", "pcre", "pcre_ucd.c" }),
pathJoinRoot(&.{ "c", "deps", "pcre", "pcre_valid_utf8.c" }),
pathJoinRoot(&.{ "c", "deps", "pcre", "pcre_version.c" }),
pathJoinRoot(&.{ "c", "deps", "pcre", "pcre_xclass.c" }),
};
const posix_srcs = &.{
pathJoinRoot(&.{ "c", "src", "posix.c" }),
};
const unix_srcs = &.{
pathJoinRoot(&.{ "c", "src", "unix", "map.c" }),
pathJoinRoot(&.{ "c", "src", "unix", "realpath.c" }),
};
const win32_srcs = &.{
pathJoinRoot(&.{ "c", "src", "win32", "dir.c" }),
pathJoinRoot(&.{ "c", "src", "win32", "error.c" }),
pathJoinRoot(&.{ "c", "src", "win32", "findfile.c" }),
pathJoinRoot(&.{ "c", "src", "win32", "map.c" }),
pathJoinRoot(&.{ "c", "src", "win32", "path_w32.c" }),
pathJoinRoot(&.{ "c", "src", "win32", "posix_w32.c" }),
pathJoinRoot(&.{ "c", "src", "win32", "precompiled.c" }),
pathJoinRoot(&.{ "c", "src", "win32", "thread.c" }),
pathJoinRoot(&.{ "c", "src", "win32", "utf-conv.c" }),
pathJoinRoot(&.{ "c", "src", "win32", "w32_buffer.c" }),
pathJoinRoot(&.{ "c", "src", "win32", "w32_leakcheck.c" }),
pathJoinRoot(&.{ "c", "src", "win32", "w32_util.c" }),
};
pub fn link(
b: *std.build.Builder,
artifact: *std.build.LibExeObjStep,
) !void {
var flags = std.ArrayList([]const u8).init(b.allocator);
defer flags.deinit();
try flags.appendSlice(&.{
"-DLIBGIT2_NO_FEATURES_H",
"-DGIT_TRACE=1",
"-DGIT_THREADS=1",
"-DGIT_USE_FUTIMENS=1",
"-DGIT_REGEX_PCRE",
"-DGIT_SSH=1",
"-DGIT_SSH_MEMORY_CREDENTIALS=1",
"-DGIT_HTTPS=1",
"-DGIT_MBEDTLS=1",
"-DGIT_SHA1_MBEDTLS=1",
"-fno-sanitize=all",
});
if (64 == artifact.target.getCpuArch().ptrBitWidth())
try flags.append("-DGIT_ARCH_64=1");
artifact.addCSourceFiles(srcs, flags.items);
if (artifact.target.isWindows()) {
try flags.appendSlice(&.{
"-DGIT_WIN32",
"-DGIT_WINHTTP",
});
artifact.addCSourceFiles(win32_srcs, flags.items);
if (artifact.target.getAbi().isGnu()) {
artifact.addCSourceFiles(posix_srcs, flags.items);
artifact.addCSourceFiles(unix_srcs, flags.items);
}
} else {
artifact.addCSourceFiles(posix_srcs, flags.items);
artifact.addCSourceFiles(unix_srcs, flags.items);
}
if (artifact.target.isLinux())
try flags.appendSlice(&.{
"-DGIT_USE_NSEC=1",
"-DGIT_USE_STAT_MTIM=1",
});
artifact.addCSourceFiles(zlib_srcs, &.{});
artifact.addCSourceFiles(pcre_srcs, &.{
"-DLINK_SIZE=2",
"-DNEWLINE=10",
"-DPOSIX_MALLOC_THRESHOLD=10",
"-DMATCH_LIMIT_RECURSION=MATCH_LIMIT",
"-DPARENS_NEST_LIMIT=250",
"-DMATCH_LIMIT=10000000",
"-DMAX_NAME_SIZE=32",
"-DMAX_NAME_COUNT=10000",
});
artifact.addIncludeDir(root() ++
std.fs.path.sep_str ++ "c" ++
std.fs.path.sep_str ++ "include");
artifact.addIncludeDir(root() ++
std.fs.path.sep_str ++ "c" ++
std.fs.path.sep_str ++ "src");
artifact.addIncludeDir(root() ++
std.fs.path.sep_str ++ "c" ++
std.fs.path.sep_str ++ "deps" ++
std.fs.path.sep_str ++ "zlib");
artifact.addIncludeDir(root() ++
std.fs.path.sep_str ++ "c" ++
std.fs.path.sep_str ++ "deps" ++
std.fs.path.sep_str ++ "pcre");
artifact.addIncludeDir(root() ++
std.fs.path.sep_str ++ "c" ++
std.fs.path.sep_str ++ "deps" ++
std.fs.path.sep_str ++ "http-parser");
artifact.linkLibC();
} | libs/libgit2/libgit2.zig |
const std = @import("std");
const c = @import("c.zig");
pub const snd = struct {
/// log.crit({first}: {result});
pub fn check(log: anytype, first: []const u8, result: i32) void {
log.crit("{s}: {s}", .{ first, snd.strerror(result) });
}
/// snd_sterror
pub fn strerror(errnum: i32) ?[]const u8 {
const dat = snd_strerror(errnum);
if (dat) |data|
return std.mem.spanZ(data);
return null;
}
pub const pcm = struct {
pub const t = c.snd_pcm_t;
pub const hw_params_t = c.snd_pcm_hw_params_t;
pub const sw_params_t = c.snd_pcm_sw_params_t;
pub const stream = extern enum(c_int) {
playback,
capture,
};
pub const nonblock = c.SND_PCM_NONBLOCK;
/// snd_pcm_open
pub fn open(pcmp: **t, name: ?[]const u8, st: stream, mode: i32) i32 {
return snd_pcm_open(
pcmp,
if (name) |data| @ptrCast([*c]const u8, data) else null,
st,
mode,
);
}
/// snd_pcm_close
pub fn close(pcmp: *t) i32 {
return snd_pcm_close(pcmp);
}
/// snd_pcm_hw_params_sizeof
pub fn hw_params_sizeof() usize {
return snd_pcm_hw_params_sizeof();
}
/// snd_pcm_hw_params_alloca
pub fn hw_params_alloca(hw: **hw_params_t) void {
@compileError("does not implemented");
return c.snd_pcm_hw_params_alloca(hw);
}
/// snd_pcm_hw_params
pub fn hw_params(pcmp: *t, hw: *hw_params_t) i32 {
return snd_pcm_hw_params(pcmp, hw);
}
};
};
extern fn snd_strerror(errnum: c_int) [*c]const u8;
extern fn snd_pcm_open(pcmp: ?**snd.pcm.t, name: [*c]const u8, stream: snd.pcm.stream, mode: c_int) c_int;
extern fn snd_pcm_close(pcmp: ?*snd.pcm.t) c_int;
extern fn snd_pcm_hw_params_sizeof() c_ulong;
extern fn snd_pcm_hw_params(pcmp: ?*snd.pcm.t, params: ?*snd.pcm.hw_params_t) c_int; | src/native/alsalib.zig |
const std = @import("std");
const debug = std.debug;
const mem = std.mem;
const testing = std.testing;
const unicode = std.unicode;
const WBP = @import("../components.zig").WordBreakProperty;
const CodePoint = @import("CodePoint.zig");
const CodePointIterator = CodePoint.CodePointIterator;
const Emoji = @import("../components.zig").EmojiData;
pub const Word = @This();
bytes: []const u8,
offset: usize,
pub fn eql(self: Word, str: []const u8) bool {
return mem.eql(u8, self.bytes, str);
}
const Type = enum {
aletter,
cr,
dquote,
extend,
extendnumlet,
format,
hletter,
katakana,
lf,
midletter,
midnum,
midnumlet,
newline,
numeric,
regional,
squote,
wsegspace,
xpic,
zwj,
any,
fn get(cp: CodePoint) Type {
var ty: Type = .any;
if (0x000D == cp.scalar) ty = .cr;
if (0x000A == cp.scalar) ty = .lf;
if (0x200D == cp.scalar) ty = .zwj;
if (0x0022 == cp.scalar) ty = .dquote;
if (0x0027 == cp.scalar) ty = .squote;
if (WBP.isALetter(cp.scalar)) ty = .aletter;
if (WBP.isExtend(cp.scalar)) ty = .extend;
if (WBP.isExtendNumLet(cp.scalar)) ty = .extendnumlet;
if (WBP.isFormat(cp.scalar)) ty = .format;
if (WBP.isHebrewLetter(cp.scalar)) ty = .hletter;
if (WBP.isKatakana(cp.scalar)) ty = .katakana;
if (WBP.isMidLetter(cp.scalar)) ty = .midletter;
if (WBP.isMidNum(cp.scalar)) ty = .midnum;
if (WBP.isMidNumLet(cp.scalar)) ty = .midnumlet;
if (WBP.isNewline(cp.scalar)) ty = .newline;
if (WBP.isNumeric(cp.scalar)) ty = .numeric;
if (WBP.isRegionalIndicator(cp.scalar)) ty = .regional;
if (WBP.isWSegSpace(cp.scalar)) ty = .wsegspace;
if (Emoji.isExtendedPictographic(cp.scalar)) ty = .xpic;
return ty;
}
};
const Token = struct {
ty: Type,
code_point: CodePoint,
offset: usize = 0,
fn is(self: Token, ty: Type) bool {
return self.ty == ty;
}
};
const TokenList = std.ArrayList(Token);
pub const WordIterator = struct {
bytes: []const u8,
i: ?usize = null,
start: ?Token = null,
tokens: TokenList,
const Self = @This();
pub fn init(allocator: *mem.Allocator, str: []const u8) !Self {
if (!unicode.utf8ValidateSlice(str)) return error.InvalidUtf8;
var self = Self{
.bytes = str,
.tokens = TokenList.init(allocator),
};
try self.lex();
if (self.tokens.items.len == 0) return error.NoTokens;
self.start = self.tokens.items[0];
// Set token offsets.
for (self.tokens.items) |*token, i| {
token.offset = i;
}
return self;
}
pub fn deinit(self: *Self) void {
self.tokens.deinit();
}
fn lex(self: *Self) !void {
var iter = CodePointIterator{
.bytes = self.bytes,
.i = 0,
};
while (iter.next()) |cp| {
try self.tokens.append(.{
.ty = Type.get(cp),
.code_point = cp,
});
}
}
// Main API.
pub fn next(self: *Self) ?Word {
if (self.advance()) |current_token| {
var end = self.current();
var done = false;
if (!done and isBreaker(current_token)) {
if (current_token.is(.cr)) {
if (self.peek()) |p| {
// WB
if (p.is(.lf)) {
_ = self.advance();
end = self.current();
done = true;
}
}
}
}
if (!done and end.is(.zwj)) {
if (self.peek()) |p| {
// WB3c
if (p.is(.xpic)) {
_ = self.advance();
end = self.current();
done = true;
}
}
}
if (!done and current_token.is(.wsegspace)) {
if (self.peek()) |p| {
// WB3d
if (p.is(.wsegspace) and !isIgnorable(end)) {
_ = self.advance();
end = self.current();
done = true;
}
}
}
if (!done and (isAHLetter(current_token) or current_token.is(.numeric))) {
if (self.peek()) |p| {
// WB5, WB8, WB9, WB10
if (isAHLetter(p) or p.is(.numeric)) {
self.run(isAlphaNum);
end = self.current();
done = true;
}
}
}
if (!done and isAHLetter(current_token)) {
if (self.peek()) |p| {
// WB6, WB7
if (p.is(.midletter) or isMidNumLetQ(p)) {
const original_i = self.i; // Save position.
_ = self.advance(); // (MidLetter|MidNumLetQ)
if (self.peek()) |pp| {
if (isAHLetter(pp)) {
_ = self.advance(); // AHLetter
end = self.current();
done = true;
}
}
if (!done) self.i = original_i; // Restore position.
}
}
}
if (!done and current_token.is(.hletter)) {
if (self.peek()) |p| {
// WB7a
if (p.is(.squote)) {
_ = self.advance();
end = self.current();
done = true;
} else if (p.is(.dquote)) {
// WB7b, WB7c
const original_i = self.i; // Save position.
_ = self.advance(); // Double_Quote
if (self.peek()) |pp| {
if (pp.is(.hletter)) {
_ = self.advance(); // Hebrew_Letter
end = self.current();
done = true;
}
}
if (!done) self.i = original_i; // Restore position.
}
}
}
if (!done and current_token.is(.numeric)) {
if (self.peek()) |p| {
if (p.is(.midnum) or isMidNumLetQ(p)) {
// WB11, WB12
const original_i = self.i; // Save position.
_ = self.advance(); // (MidNum|MidNumLetQ)
if (self.peek()) |pp| {
if (pp.is(.numeric)) {
_ = self.advance(); // Numeric
end = self.current();
done = true;
}
}
if (!done) self.i = original_i; // Restore position.
}
}
}
if (!done and (isAHLetter(current_token) or current_token.is(.numeric) or current_token.is(.katakana) or
current_token.is(.extendnumlet)))
{
while (true) {
if (self.peek()) |p| {
// WB13a
if (p.is(.extendnumlet)) {
_ = self.advance(); // ExtendNumLet
if (self.peek()) |pp| {
if (isAHLetter(pp) or isNumeric(pp) or pp.is(.katakana)) {
// WB13b
_ = self.advance(); // (AHLetter|Numeric|Katakana)
}
}
end = self.current();
done = true;
} else break;
} else break;
}
}
if (!done and current_token.is(.extendnumlet)) {
while (true) {
if (self.peek()) |p| {
// WB13b
if (isAHLetter(p) or p.is(.numeric) or p.is(.katakana)) {
_ = self.advance(); // (AHLetter|Numeric|Katakana)
end = self.current();
done = true;
if (self.peek()) |pp| {
// Chain.
if (pp.is(.extendnumlet)) {
_ = self.advance(); // ExtendNumLet
continue;
}
}
} else break;
} else break;
}
}
if (!done and current_token.is(.katakana)) {
if (self.peek()) |p| {
// WB13
if (p.is(.katakana)) {
_ = self.advance();
end = self.current();
done = true;
}
}
}
if (!done and current_token.is(.regional)) {
if (self.peek()) |p| {
// WB
if (p.is(.regional)) {
_ = self.advance();
end = self.current();
done = true;
}
}
}
if (!done and current_token.is(.xpic)) {
if (self.peek()) |p| {
// WB
if (p.is(.xpic) and end.is(.zwj)) {
_ = self.advance();
end = self.current();
done = true;
}
}
}
const start = self.start.?;
self.start = self.peek();
// WB
return self.emit(start, end);
}
return null;
}
// Token array movement.
fn forward(self: *Self) bool {
if (self.i) |*index| {
index.* += 1;
if (index.* >= self.tokens.items.len) return false;
} else {
self.i = 0;
}
return true;
}
// Token array movement.
fn getRelative(self: Self, n: isize) ?Token {
var index: usize = self.i orelse 0;
if (n < 0) {
if (index == 0 or -%n > index) return null;
index -= @intCast(usize, -%n);
} else {
const un = @intCast(usize, n);
if (index + un >= self.tokens.items.len) return null;
index += un;
}
return self.tokens.items[index];
}
fn prevAfterSkip(self: *Self, predicate: TokenPredicate) ?Token {
if (self.i == null or self.i.? == 0) return null;
var i: isize = 1;
while (self.getRelative(-i)) |token| : (i += 1) {
if (!predicate(token)) return token;
}
return null;
}
fn current(self: Self) Token {
// Assumes self.i is not null.
return self.tokens.items[self.i.?];
}
fn last(self: Self) Token {
return self.tokens.items[self.tokens.items.len - 1];
}
fn peek(self: Self) ?Token {
return self.getRelative(1);
}
fn peekAfterSkip(self: *Self, predicate: TokenPredicate) ?Token {
var i: isize = 1;
while (self.getRelative(i)) |token| : (i += 1) {
if (!predicate(token)) return token;
}
return null;
}
fn advance(self: *Self) ?Token {
const token = if (self.forward()) self.current() else return null;
// WB3a, WB3b
if (!isBreaker(token)) _ = self.skipIgnorables(token);
return token;
}
fn run(self: *Self, predicate: TokenPredicate) void {
while (self.peek()) |token| {
if (!predicate(token)) break;
_ = self.advance();
}
}
fn skipIgnorables(self: *Self, end: Token) Token {
if (self.peek()) |p| {
if (isIgnorable(p)) {
self.run(isIgnorable);
return self.current();
}
}
return end;
}
// Production.
fn emit(self: Self, start_token: Token, end_token: Token) Word {
const start = start_token.code_point.offset;
const end = end_token.code_point.end();
return .{
.bytes = self.bytes[start..end],
.offset = start,
};
}
};
// Predicates
const TokenPredicate = fn (Token) bool;
fn isAHLetter(token: Token) bool {
return token.ty == .aletter or token.ty == .hletter;
}
fn isAlphaNum(token: Token) bool {
return isAHLetter(token) or isNumeric(token);
}
fn isBreaker(token: Token) bool {
return token.ty == .newline or token.ty == .cr or token.ty == .lf;
}
fn isIgnorable(token: Token) bool {
return token.ty == .extend or token.ty == .format or token.ty == .zwj;
}
fn isMidNumLetQ(token: Token) bool {
return token.ty == .midnumlet or token.ty == .squote;
}
fn isNumeric(token: Token) bool {
return token.ty == .numeric;
}
test "Segmentation WordIterator" {
var path_buf: [1024]u8 = undefined;
var path = try std.fs.cwd().realpath(".", &path_buf);
// Check if testing in this library path.
if (!mem.endsWith(u8, path, "ziglyph")) return;
var allocator = std.testing.allocator;
var file = try std.fs.cwd().openFile("src/data/ucd/WordBreakTest.txt", .{});
defer file.close();
var buf_reader = std.io.bufferedReader(file.reader());
var input_stream = buf_reader.reader();
var buf: [4096]u8 = undefined;
var line_no: usize = 1;
while (try input_stream.readUntilDelimiterOrEof(&buf, '\n')) |raw| : (line_no += 1) {
// Skip comments or empty lines.
if (raw.len == 0 or raw[0] == '#' or raw[0] == '@') continue;
// Clean up.
var line = mem.trimLeft(u8, raw, "÷ ");
if (mem.indexOf(u8, line, " ÷\t#")) |octo| {
line = line[0..octo];
}
//debug.print("\nline {}: {s}\n", .{ line_no, line });
// Iterate over fields.
var want = std.ArrayList(Word).init(allocator);
defer {
for (want.items) |snt| {
allocator.free(snt.bytes);
}
want.deinit();
}
var all_bytes = std.ArrayList(u8).init(allocator);
defer all_bytes.deinit();
var sentences = mem.split(u8, line, " ÷ ");
var bytes_index: usize = 0;
while (sentences.next()) |field| {
var code_points = mem.split(u8, field, " ");
var cp_buf: [4]u8 = undefined;
var cp_index: usize = 0;
var first: u21 = undefined;
var cp_bytes = std.ArrayList(u8).init(allocator);
defer cp_bytes.deinit();
while (code_points.next()) |code_point| {
if (mem.eql(u8, code_point, "×")) continue;
const cp: u21 = try std.fmt.parseInt(u21, code_point, 16);
if (cp_index == 0) first = cp;
const len = try unicode.utf8Encode(cp, &cp_buf);
try all_bytes.appendSlice(cp_buf[0..len]);
try cp_bytes.appendSlice(cp_buf[0..len]);
cp_index += len;
}
try want.append(Word{
.bytes = cp_bytes.toOwnedSlice(),
.offset = bytes_index,
});
bytes_index += cp_index;
}
//debug.print("\nline {}: {s}\n", .{ line_no, all_bytes.items });
var iter = try WordIterator.init(allocator, all_bytes.items);
defer iter.deinit();
// Chaeck.
for (want.items) |w| {
const g = (iter.next()).?;
//debug.print("\n", .{});
//for (w.bytes) |b| {
// debug.print("line {}: w:({x})\n", .{ line_no, b });
//}
//for (g.bytes) |b| {
// debug.print("line {}: g:({x})\n", .{ line_no, b });
//}
//debug.print("line {}: w:({s}), g:({s})\n", .{ line_no, w.bytes, g.bytes });
try testing.expectEqualStrings(w.bytes, g.bytes);
try testing.expectEqual(w.offset, g.offset);
}
}
}
// Comptime
fn getTokens(comptime str: []const u8, comptime n: usize) [n]Token {
var i: usize = 0;
var cp_iter = CodePointIterator{ .bytes = str };
var tokens: [n]Token = undefined;
while (cp_iter.next()) |cp| : (i += 1) {
tokens[i] = .{
.ty = Type.get(cp),
.code_point = cp,
.offset = i,
};
}
return tokens;
}
pub fn ComptimeWordIterator(comptime str: []const u8) type {
const cp_count: usize = unicode.utf8CountCodepoints(str) catch @compileError("Invalid UTF-8.");
if (cp_count == 0) @compileError("No code points?");
const tokens = getTokens(str, cp_count);
return struct {
bytes: []const u8 = str,
i: ?usize = null,
start: ?Token = tokens[0],
tokens: [cp_count]Token = tokens,
const Self = @This();
// Main API.
pub fn next(self: *Self) ?Word {
if (self.advance()) |current_token| {
var end = self.current();
var done = false;
if (!done and isBreaker(current_token)) {
if (current_token.is(.cr)) {
if (self.peek()) |p| {
// WB
if (p.is(.lf)) {
_ = self.advance();
end = self.current();
done = true;
}
}
}
}
if (!done and end.is(.zwj)) {
if (self.peek()) |p| {
// WB3c
if (p.is(.xpic)) {
_ = self.advance();
end = self.current();
done = true;
}
}
}
if (!done and current_token.is(.wsegspace)) {
if (self.peek()) |p| {
// WB3d
if (p.is(.wsegspace) and !isIgnorable(end)) {
_ = self.advance();
end = self.current();
done = true;
}
}
}
if (!done and (isAHLetter(current_token) or current_token.is(.numeric))) {
if (self.peek()) |p| {
// WB5, WB8, WB9, WB10
if (isAHLetter(p) or p.is(.numeric)) {
self.run(isAlphaNum);
end = self.current();
done = true;
}
}
}
if (!done and isAHLetter(current_token)) {
if (self.peek()) |p| {
// WB6, WB7
if (p.is(.midletter) or isMidNumLetQ(p)) {
const original_i = self.i; // Save position.
_ = self.advance(); // (MidLetter|MidNumLetQ)
if (self.peek()) |pp| {
if (isAHLetter(pp)) {
_ = self.advance(); // AHLetter
end = self.current();
done = true;
}
}
if (!done) self.i = original_i; // Restore position.
}
}
}
if (!done and current_token.is(.hletter)) {
if (self.peek()) |p| {
// WB7a
if (p.is(.squote)) {
_ = self.advance();
end = self.current();
done = true;
} else if (p.is(.dquote)) {
// WB7b, WB7c
const original_i = self.i; // Save position.
_ = self.advance(); // Double_Quote
if (self.peek()) |pp| {
if (pp.is(.hletter)) {
_ = self.advance(); // Hebrew_Letter
end = self.current();
done = true;
}
}
if (!done) self.i = original_i; // Restore position.
}
}
}
if (!done and current_token.is(.numeric)) {
if (self.peek()) |p| {
if (p.is(.midnum) or isMidNumLetQ(p)) {
// WB11, WB12
const original_i = self.i; // Save position.
_ = self.advance(); // (MidNum|MidNumLetQ)
if (self.peek()) |pp| {
if (pp.is(.numeric)) {
_ = self.advance(); // Numeric
end = self.current();
done = true;
}
}
if (!done) self.i = original_i; // Restore position.
}
}
}
if (!done and (isAHLetter(current_token) or current_token.is(.numeric) or current_token.is(.katakana) or
current_token.is(.extendnumlet)))
{
while (true) {
if (self.peek()) |p| {
// WB13a
if (p.is(.extendnumlet)) {
_ = self.advance(); // ExtendNumLet
if (self.peek()) |pp| {
if (isAHLetter(pp) or isNumeric(pp) or pp.is(.katakana)) {
// WB13b
_ = self.advance(); // (AHLetter|Numeric|Katakana)
}
}
end = self.current();
done = true;
} else break;
} else break;
}
}
if (!done and current_token.is(.extendnumlet)) {
while (true) {
if (self.peek()) |p| {
// WB13b
if (isAHLetter(p) or p.is(.numeric) or p.is(.katakana)) {
_ = self.advance(); // (AHLetter|Numeric|Katakana)
end = self.current();
done = true;
if (self.peek()) |pp| {
// Chain.
if (pp.is(.extendnumlet)) {
_ = self.advance(); // ExtendNumLet
continue;
}
}
} else break;
} else break;
}
}
if (!done and current_token.is(.katakana)) {
if (self.peek()) |p| {
// WB13
if (p.is(.katakana)) {
_ = self.advance();
end = self.current();
done = true;
}
}
}
if (!done and current_token.is(.regional)) {
if (self.peek()) |p| {
// WB
if (p.is(.regional)) {
_ = self.advance();
end = self.current();
done = true;
}
}
}
if (!done and current_token.is(.xpic)) {
if (self.peek()) |p| {
// WB
if (p.is(.xpic) and end.is(.zwj)) {
_ = self.advance();
end = self.current();
done = true;
}
}
}
const start = self.start.?;
self.start = self.peek();
// WB
return self.emit(start, end);
}
return null;
}
// Token array movement.
fn forward(self: *Self) bool {
if (self.i) |*index| {
index.* += 1;
if (index.* >= self.tokens.len) return false;
} else {
self.i = 0;
}
return true;
}
pub fn count(self: *Self) usize {
const original_i = self.i;
const original_start = self.start;
defer {
self.i = original_i;
self.start = original_start;
}
self.rewind();
var i: usize = 0;
while (self.next()) |_| : (i += 1) {}
return i;
}
// Token array movement.
pub fn rewind(self: *Self) void {
self.i = null;
self.start = self.tokens[0];
}
fn getRelative(self: Self, n: isize) ?Token {
var index: usize = self.i orelse 0;
if (n < 0) {
if (index == 0 or -%n > index) return null;
index -= @intCast(usize, -%n);
} else {
const un = @intCast(usize, n);
if (index + un >= self.tokens.len) return null;
index += un;
}
return self.tokens[index];
}
fn prevAfterSkip(self: *Self, predicate: TokenPredicate) ?Token {
if (self.i == null or self.i.? == 0) return null;
var i: isize = 1;
while (self.getRelative(-i)) |token| : (i += 1) {
if (!predicate(token)) return token;
}
return null;
}
fn current(self: Self) Token {
// Assumes self.i is not null.
return self.tokens[self.i.?];
}
fn last(self: Self) Token {
return self.tokens[self.tokens.len - 1];
}
fn peek(self: Self) ?Token {
return self.getRelative(1);
}
fn peekAfterSkip(self: *Self, predicate: TokenPredicate) ?Token {
var i: isize = 1;
while (self.getRelative(i)) |token| : (i += 1) {
if (!predicate(token)) return token;
}
return null;
}
fn advance(self: *Self) ?Token {
const token = if (self.forward()) self.current() else return null;
// WB3a, WB3b
if (!isBreaker(token)) _ = self.skipIgnorables(token);
return token;
}
fn run(self: *Self, predicate: TokenPredicate) void {
while (self.peek()) |token| {
if (!predicate(token)) break;
_ = self.advance();
}
}
fn skipIgnorables(self: *Self, end: Token) Token {
if (self.peek()) |p| {
if (isIgnorable(p)) {
self.run(isIgnorable);
return self.current();
}
}
return end;
}
// Production.
fn emit(self: Self, start_token: Token, end_token: Token) Word {
const start = start_token.code_point.offset;
const end = end_token.code_point.end();
return .{
.bytes = self.bytes[start..end],
.offset = start,
};
}
};
}
test "Segmentation ComptimeWordIterator" {
comptime var ct_iter = ComptimeWordIterator("Hello World"){};
const n = comptime ct_iter.count();
var words: [n]Word = undefined;
comptime {
var i: usize = 0;
while (ct_iter.next()) |word| : (i += 1) {
words[i] = word;
}
}
const want = [_][]const u8{ "Hello", " ", "World" };
for (words) |word, i| {
try testing.expect(word.eql(want[i]));
}
} | src/segmenter/Word.zig |
const std = @import("std");
const builtin = @import("builtin");
const assert = std.debug.assert;
const mem = std.mem;
const net = std.net;
const os = std.os;
const linux = os.linux;
const testing = std.testing;
const io_uring_params = linux.io_uring_params;
const io_uring_sqe = linux.io_uring_sqe;
const io_uring_cqe = linux.io_uring_cqe;
const TT = union {
accept: void,
read: os.fd_t,
};
const Token = packed struct {
tag: enum(u16) {
accept,
read,
read_fixed, // buf_idx
write_fixed,
write,
close,
shutdown,
},
buf_idx: i16 = -1,
client_fd: os.fd_t = -1,
};
const Ring = struct {
uring: std.os.linux.IO_Uring,
client_addr: os.sockaddr,
client_addr_len: os.socklen_t = @sizeOf(os.sockaddr),
pub fn init(entries: u13, flags: u32) !Ring {
return Ring{
.uring = try std.os.linux.IO_Uring.init(entries, flags),
.client_addr = undefined,
};
}
fn deinit(self: *Ring) void {
self.uring.deinit();
}
fn queue_close(self: *Ring, fd: os.fd_t) !*io_uring_sqe {
return try self.uring.close(@bitCast(u64, Token{ .tag = .close }), fd);
}
fn queue_shutdown(self: *Ring, fd: os.socket_t, how: u32) !*io_uring_sqe {
return try self.uring.shutdown(@bitCast(u64, Token{ .tag = .close }), fd, how);
}
fn queue_accept(self: *Ring, server: os.socket_t) !*io_uring_sqe {
return try self.uring.accept(@bitCast(u64, Token{ .tag = .accept }), server, &self.client_addr, &self.client_addr_len, 0);
}
fn queue_read(
self: *Ring,
client_fd: os.fd_t,
buffer: []u8,
offset: u64,
) !*io_uring_sqe {
return try self.uring.read(@bitCast(u64, Token{
.tag = .read,
.client_fd = client_fd,
}), client_fd, buffer, offset);
}
fn queue_write_fixed(
self: *Ring,
client_fd: os.fd_t,
buffer: *os.iovec,
offset: u64,
buffer_index: u16,
) !*io_uring_sqe {
const udata = Token{
.tag = .write,
.client_fd = client_fd,
};
return try self.uring.write_fixed(@bitCast(u64, udata), client_fd, buffer, offset, buffer_index);
}
fn queue_write(
self: *Ring,
client_fd: os.fd_t,
buffer: []const u8,
offset: u64,
) !*io_uring_sqe {
const udata = Token{
.tag = .write,
.client_fd = client_fd,
};
return try self.uring.write(@bitCast(u64, udata), client_fd, buffer, offset);
}
};
var global_stop = std.atomic.Atomic(bool).init(false);
fn initSignalHandlers() !void {
// SIGPIPE is ignored, errors need to be handled on read/writes
os.sigaction(os.SIGPIPE, &.{
.handler = .{ .sigaction = os.SIG_IGN },
.mask = os.empty_sigset,
.flags = 0,
}, null);
// SIGTERM/SIGINT set global_stop
for ([_]os.SIG{
.INT,
.TERM,
}) |sig| {
os.sigaction(sig, &.{
.handler = .{
.handler = struct {
fn wrapper(_: c_int) callconv(.C) void {
global_stop.store(true, .SeqCst);
}
}.wrapper,
},
.mask = os.empty_sigset,
.flags = 0,
}, null);
}
}
pub fn main() !void {
// TODO: support other tcp-ish socket types
// - tcp
// - unix-socket
// - unix-abstract-socket e.g. \0 prefixed
const address = try net.Address.parseIp4("127.0.0.1", 3131);
const kernel_backlog = 1;
const server = try os.socket(address.any.family, os.SOCK.STREAM | os.SOCK.CLOEXEC, 0);
defer os.close(server);
try os.setsockopt(server, os.SOL.SOCKET, os.SO.REUSEADDR, &mem.toBytes(@as(c_int, 1)));
try os.bind(server, &address.any, address.getOsSockLen());
try os.listen(server, kernel_backlog);
std.debug.print("net: echo server: io_uring: listening on {}...\n", .{address});
// TODO: no idea what a reasonable value is for entries, 16 seems nice and low.
// smaller is better until benchmarks show otherwise (a big buffer can hide deadlock bugs until prod).
var ring = try Ring.init(16, 0);
defer ring.deinit();
_ = try ring.queue_accept(server);
const BUF_COUNT = 16;
const BUF_SIZE = 4096;
var raw_bufs: [BUF_COUNT][BUF_SIZE]u8 = undefined;
var buffers: [raw_bufs.len]std.os.iovec = undefined;
for (buffers) |*iovc, i| {
iovc.* = .{ .iov_base = &raw_bufs[i], .iov_len = raw_bufs[i].len };
}
const READ_BUF_IDX = z0;
try ring.uring.register_buffers(buffers[0..]);
var buffer_write = [_]u8{98} ** 3;
// std.mem.
// std.mem.copy(u8, &raw_bufs[0], "foobar");
while (true) {
// TODO: Write a golang client to fuzz bad behavior from clients (e.g. slow/other).
// long running tests that validate checksums to find weird behavior at scale.
// TODO: benchmark vs batching + peeking vs kernal submit thread
// TODO: ensure everything else is non-blocking (or attach a timeout?).
// otherwise we need to have a background thread for periodic tasks
// like updating a dns cache or sending metrics/heartbeats.
// TODO: install bcc and monitor tcp stuff + other utilization metrics.
_ = try ring.uring.submit_and_wait(1);
// TODO: benchmark copy_cqes for a batch of [256] completions at a time.
const cqe = try ring.uring.copy_cqe();
switch (cqe.err()) {
.SUCCESS => {},
else => |errno| std.debug.panic("unhandled errno: {}", .{errno}),
}
const token = @bitCast(Token, cqe.user_data);
std.log.info("token: {}", .{token});
// tag indicates what event was completed
switch (token.tag) {
// We have a new connection, we need to
// 1) reject new connections over some limit by skipping queue_accept?
// 2) dedicate a new "connection" object that has the buffers and other
// stuff dedicated to a single long-lived tcp-connection.
.accept => {
// TODO: limit number of connections here, by not queing an accept?
_ = try ring.queue_accept(server);
// TODO: I think this has a race condition, if we accept again
// before this read has finished the two reads could write to the
// buffer concurrently?
// We don't control what order the events are completed here.
// I think this is solved by using a pool (or dedicated per client)
// buffers + readv.
const buf_idx = READ_BUF_IDX;
const offset = 0;
_ = try ring.uring.read_fixed(@bitCast(u64, Token{
.tag = .read_fixed,
.client_fd = cqe.res,
.buf_idx = buf_idx,
}), cqe.res, &buffers[buf_idx], offset, buf_idx);
},
.read_fixed => {
// TODO: we are done with the buffer.
const data_read = raw_bufs[@intCast(usize, token.buf_idx)][0..@intCast(usize, cqe.res)];
std.debug.print("complete.read_fixed: {s}\n", .{data_read});
_ = try ring.uring.write(
@bitCast(u64, Token{
.tag = .write,
.client_fd = token.client_fd,
}),
token.client_fd,
buffer_write[0..],
0,
);
},
.write_fixed, .write => {
// TODO: another ordering bug I think, we need to ensure that no sqe is
// still in progress for the given client_fd (I think this can be a flush/nop,
// or maybe just a per fd ref count)
std.debug.print("complete.write: nbytes={}\n", .{cqe.res});
_ = try ring.queue_close(token.client_fd);
},
.read => unreachable,
.close, .shutdown => {
std.debug.print("complete.close\n", .{});
},
}
}
} | src/v0/main.zig |
const std = @import("std");
const testing = std.testing;
const expect = testing.expect;
const expectEqual = testing.expectEqual;
const expectApproxEqRel = testing.expectApproxEqRel;
pub const Vector2Int = packed struct {
x: i32,
y: i32,
pub fn init(x: i32, y: i32) Vector2Int {
return .{ .x = x, .y = y };
}
pub fn set(value: i32) Vector2Int {
return .{ .x = value, .y = value };
}
pub fn add(a: Vector2Int, b: Vector2Int) Vector2Int {
return init(a.x + b.x, a.y + b.y);
}
pub fn subtract(a: Vector2Int, b: Vector2Int) Vector2Int {
return init(a.x - b.x, a.y - b.y);
}
pub fn multiply(a: Vector2Int, b: Vector2Int) Vector2Int {
return init(a.x * b.x, a.y * b.y);
}
pub fn divideTrunc(a: Vector2Int, b: Vector2Int) Vector2Int {
return init(@divTrunc(a.x, b.x), @divTrunc(a.y, b.y));
}
pub fn addScalar(a: Vector2Int, b: i32) Vector2Int {
return init(a.x + b, a.y + b);
}
pub fn subtractScalar(a: Vector2Int, b: i32) Vector2Int {
return init(a.x - b, a.y - b);
}
pub fn multiplyScalar(a: Vector2Int, b: i32) Vector2Int {
return init(a.x * b, a.y * b);
}
pub fn divideScalarTrunc(a: Vector2Int, b: i32) Vector2Int {
return init(@divTrunc(a.x, b), @divTrunc(a.y, b));
}
};
test "Vector2Int" {
var v1 = Vector2Int.init(1, 2);
var v2 = Vector2Int.init(5, 6);
var v: Vector2Int = undefined;
v = Vector2Int.init(1, 2);
try expectEqual(@as(i32, 1.0), v.x);
try expectEqual(@as(i32, 2.0), v.y);
v = Vector2Int.set(4);
try expectEqual(@as(i32, 4.0), v.x);
try expectEqual(@as(i32, 4.0), v.y);
v = v1.add(v2);
try expectEqual(Vector2Int.init(6, 8), v);
v = v1.addScalar(14);
try expectEqual(Vector2Int.init(15, 16), v);
v = v1.subtract(v2);
try expectEqual(Vector2Int.init(-4, -4), v);
v = v1.subtractScalar(-4);
try expectEqual(Vector2Int.init(5, 6), v);
v = v1.multiply(v2);
try expectEqual(Vector2Int.init(5, 12), v);
v = v1.multiplyScalar(-4);
try expectEqual(Vector2Int.init(-4, -8), v);
v = v2.divideTrunc(v1);
try expectEqual(Vector2Int.init(5, 3), v);
v = v2.divideScalarTrunc(2);
try expectEqual(Vector2Int.init(2, 3), v);
} | src/vector2_int.zig |
const std = @import("std");
const math = @import("std").math;
const Mat3 = @import("mat3.zig").Mat3;
const Mat4 = @import("mat4.zig").Mat4;
const utils = @import("utils.zig");
const Vec3 = @import("vec3.zig").Vec3;
pub const quat_identity = Quat.create(0, 0, 0, 1);
pub const quat_zero = Quat.create(0, 0, 0, 0);
pub const Quat = packed struct {
x: f32,
y: f32,
z: f32,
w: f32,
pub fn create(x: f32, y: f32, z: f32, w: f32) Quat {
return Quat{
.x = x,
.y = y,
.z = z,
.w = w,
};
}
pub const identity = quat_identity;
pub const zero = quat_zero;
test "identity" {
const quatA = Quat.identity;
try std.testing.expect(utils.f_eq(quatA.x, 0));
try std.testing.expect(utils.f_eq(quatA.y, 0));
try std.testing.expect(utils.f_eq(quatA.z, 0));
try std.testing.expect(utils.f_eq(quatA.w, 1));
}
///Gets the rotation axis and angle for a given quaternion.
pub fn getAxisAngle(q: Quat, out_axis: ?*Vec3) f32 {
const rad = math.acos(q.w) * 2.0;
if (out_axis) |v| {
const s = @sin(rad / 2.0);
if (s > utils.epsilon) {
v.* = Vec3.create(
q.x / s,
q.y / s,
q.z / s,
);
} else {
v.* = Vec3.create(1, 0, 0);
}
}
return rad;
}
test "getAxisAngle no rotation" {
const quat = fromAxisAngle(Vec3.create(0, 1, 0), 0.0);
const deg90 = quat.getAxisAngle(null);
try std.testing.expect(utils.f_eq(@mod(deg90, math.pi * 2.0), 0.0));
}
test "getAxisAngle simple rotation X" {
const quat = fromAxisAngle(Vec3.create(1, 0, 0), 0.7778);
var out = Vec3.zero;
const deg90 = quat.getAxisAngle(&out);
try std.testing.expect(utils.f_eq(deg90, 0.7778));
try Vec3.expectEqual(Vec3.create(1, 0, 0), out);
}
test "getAxisAngle simple rotation Y" {
const quat = fromAxisAngle(Vec3.create(0, 0, 1), 0.123456);
var out = Vec3.zero;
const deg90 = quat.getAxisAngle(&out);
try std.testing.expect(utils.f_eq(deg90, 0.123456));
try Vec3.expectEqual(Vec3.create(0, 0, 1), out);
}
test "getAxisAngle slightly irregular axis and right angle" {
const quat = fromAxisAngle(Vec3.create(0.707106, 0, 0.707106), math.pi * 0.5);
var out = Vec3.zero;
const deg90 = quat.getAxisAngle(&out);
try std.testing.expect(utils.f_eq(deg90, math.pi * 0.5));
try Vec3.expectEqual(Vec3.create(0.707106, 0, 0.707106), out);
}
test "getAxisAngle very irregular axis and negative input angle" {
const quatA = fromAxisAngle(Vec3.create(0.65538555, 0.49153915, 0.57346237), 8.8888);
var vec = Vec3.zero;
const deg90 = quatA.getAxisAngle(&vec);
const quatB = fromAxisAngle(vec, deg90);
try std.testing.expect(deg90 > 0.0);
try std.testing.expect(deg90 < math.pi * 2.0);
try expectEqual(quatA, quatB);
}
test "getAxisAngle simple rotation Z" {
const quat = fromAxisAngle(Vec3.create(0, 1, 0), 0.879546);
var out = Vec3.zero;
const deg90 = quat.getAxisAngle(&out);
try std.testing.expect(utils.f_eq(deg90, 0.879546));
try Vec3.expectEqual(Vec3.create(0, 1, 0), out);
}
/// Sets a quat from the given angle and rotation axis,
/// then returns it.
pub fn fromAxisAngle(axis: Vec3, rad: f32) Quat {
const radHalf = rad * 0.5;
const s = @sin(radHalf);
const c = @cos(radHalf);
return Quat{
.x = s * axis.x,
.y = s * axis.y,
.z = s * axis.z,
.w = c,
};
}
test "fromAxisAngle" {
const out = fromAxisAngle(Vec3.create(1, 0, 0), math.pi * 0.5);
const expected = create(0.707106, 0, 0, 0.707106);
try expectEqual(expected, out);
}
/// Gets the angular distance between two unit quaternions
pub fn getAngle(a: Quat, b: Quat) f32 {
const dotproduct = dot(a, b);
return math.acos(2 * dotproduct * dotproduct - 1);
}
test "getAngle from itself" {
const quatA = create(1, 2, 3, 4).normalize();
const out = getAngle(quatA, quatA);
try std.testing.expect(utils.f_eq(out, 0.0));
}
test "getAngle from rotated" {
const quatA = create(1, 2, 3, 4).normalize();
const quatB = quatA.rotateX(math.pi / 4.0);
const out = getAngle(quatA, quatB);
try std.testing.expect(utils.f_eq(out, math.pi / 4.0));
}
test "getAngle compare with axisAngle" {
const quatA = create(1, 2, 3, 4).normalize();
const quatB = create(5, 6, 7, 8).normalize();
const quatAInv = conjugate(quatA);
const quatAB = multiply(quatAInv, quatB);
const reference = getAxisAngle(quatAB, null);
try std.testing.expect(utils.f_eq(getAngle(quatA, quatB), reference));
}
/// Adds two quats
pub fn add(a: Quat, b: Quat) Quat {
return Quat{
.x = a.x + b.x,
.y = a.y + b.y,
.z = a.z + b.z,
.w = a.w + b.w,
};
}
test "add" {
const a = Quat.create(1, 2, 3, 4);
const b = Quat.create(5, 6, 7, 8);
const out = Quat.add(a, b);
const expected = Quat.create(6, 8, 10, 12);
try expectEqual(expected, out);
}
/// Multiplies two quats
pub fn multiply(a: Quat, b: Quat) Quat {
return Quat{
.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y,
.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z,
.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x,
.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z,
};
}
/// Scales a quat by a scalar number
pub fn scale(a: Quat, s: f32) Quat {
return Quat{
.x = a.x * s,
.y = a.y * s,
.z = a.z * s,
.w = a.w * s,
};
}
test "scale" {
const a = Quat.create(1, 2, 3, 4);
const out = Quat.scale(a, 2);
const expected = Quat.create(2, 4, 6, 8);
try expectEqual(expected, out);
}
pub fn dot(a: Quat, b: Quat) f32 {
return a.x * b.x //
+ a.y * b.y //
+ a.z * b.z //
+ a.w * b.w;
}
test "dot" {
const a = Quat.create(1, 2, 3, 4);
const b = Quat.create(5, 6, 7, 8);
const out = Quat.dot(a, b);
const expected = 70.0;
try std.testing.expect(utils.f_eq(expected, out));
}
pub fn lerp(a: Quat, b: Quat, t: f32) Quat {
return Quat{
.x = a.x + t * (b.x - a.x),
.y = a.y + t * (b.y - a.y),
.z = a.z + t * (b.z - a.z),
.w = a.w + t * (b.w - a.w),
};
}
test "lerp" {
const a = Quat.create(1, 2, 3, 4);
const b = Quat.create(5, 6, 7, 8);
const out = Quat.lerp(a, b, 0.5);
const expected = Quat.create(3, 4, 5, 6);
try expectEqual(expected, out);
}
pub fn length(a: Quat) f32 {
// TODO: use std.math.hypot
return @sqrt(a.squaredLength());
}
test "length" {
const a = Quat.create(1, 2, 3, 4);
const out = Quat.length(a);
try std.testing.expect(utils.f_eq(out, 5.477225));
}
pub fn squaredLength(a: Quat) f32 {
return a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w;
}
test "squaredLength" {
const a = Quat.create(1, 2, 3, 4);
const out = Quat.squaredLength(a);
try std.testing.expect(utils.f_eq(out, 30));
}
pub fn normalize(a: Quat) Quat {
var l = a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w;
if (l > 0)
l = 1 / @sqrt(l);
return Quat{
.x = a.x * l,
.y = a.y * l,
.z = a.z * l,
.w = a.w * l,
};
}
test "normalize" {
const a = Quat.create(5, 0, 0, 0);
const out = Quat.normalize(a);
const expected = Quat.create(1, 0, 0, 0);
try expectEqual(expected, out);
}
/// Rotates a quaternion by the given angle about the X axis
pub fn rotateX(a: Quat, rad: f32) Quat {
var radHalf = rad * 0.5;
const bx = @sin(radHalf);
const bw = @cos(radHalf);
return Quat{
.x = a.x * bw + a.w * bx,
.y = a.y * bw + a.z * bx,
.z = a.z * bw - a.y * bx,
.w = a.w * bw - a.x * bx,
};
}
test "rotateX" {
const out = identity.rotateX(math.pi / 2.0);
const vec = Vec3.create(0, 0, -1).transformQuat(out);
const expected = Vec3.create(0, 1, 0);
try Vec3.expectEqual(expected, vec);
}
/// Rotates a quaternion by the given angle about the Y axis
pub fn rotateY(a: Quat, rad: f32) Quat {
var radHalf = rad * 0.5;
const by = @sin(radHalf);
const bw = @cos(radHalf);
return Quat{
.x = a.x * bw - a.z * by,
.y = a.y * bw + a.w * by,
.z = a.z * bw + a.x * by,
.w = a.w * bw - a.y * by,
};
}
test "rotateY" {
const out = identity.rotateY(math.pi / 2.0);
const vec = Vec3.create(0, 0, -1).transformQuat(out);
const expected = Vec3.create(-1, 0, 0);
try Vec3.expectEqual(expected, vec);
}
/// Rotates a quaternion by the given angle about the Z axis
pub fn rotateZ(a: Quat, rad: f32) Quat {
const radHalf = rad * 0.5;
const bz = @sin(radHalf);
const bw = @cos(radHalf);
return Quat{
.x = a.x * bw + a.y * bz,
.y = a.y * bw - a.x * bz,
.z = a.z * bw + a.w * bz,
.w = a.w * bw - a.z * bz,
};
}
test "rotateZ" {
const out = identity.rotateZ(math.pi / 2.0);
const vec = Vec3.create(0, 1, 0).transformQuat(out);
const expected = Vec3.create(-1, 0, 0);
try Vec3.expectEqual(expected, vec);
}
/// Calculates the W component of a quat from the X, Y, and Z components.
/// Assumes that quaternion is 1 unit in length.
/// Any existing W component will be ignored.
pub fn calculatW(a: Quat) Quat {
return Quat{
.x = a.x,
.y = a.y,
.z = a.z,
.w = @sqrt(@fabs(1.0 - a.x * a.x - a.y * a.y - a.z * a.z)),
};
}
/// Calculate the exponential of a unit quaternion.
pub fn exp(a: Quat) Quat {
var r = @sqrt(a.x * a.x + a.y * a.y + a.z * a.z);
var et = @exp(a.w);
var s = if (r > 0) (et * @sin(r) / r) else 0.0;
return Quat{
.x = a.x * s,
.y = a.y * s,
.z = a.z * s,
.w = et * @cos(r),
};
}
/// Calculate the naturl logarithm of a unit quaternion.
pub fn ln(a: Quat) Quat {
var r = @sqrt(a.x * a.x + a.y * a.y + a.z * a.z);
var t: f32 = 0.0;
if (r > 0)
t = math.atan2(f32, r, a.w) / r;
return Quat{
.x = a.x * t,
.y = a.y * t,
.z = a.z * t,
.w = 0.5 * @log10(a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w),
};
}
/// Calculate the scalar power of a unit quaternion.
pub fn pow(a: Quat, b: f32) Quat {
var out = ln(a);
out = scale(out, b);
out = exp(out);
return out;
}
test "pow identity quat" {
const result = pow(identity, 2.1);
try expectEqual(result, identity);
}
test "pow of one" {
var quatA = create(1, 2, 3, 4);
quatA = normalize(quatA);
const result = pow(quatA, 1);
try expectEqual(result, quatA);
}
test "pow squared" {
var quatA = create(1, 2, 3, 4);
quatA = normalize(quatA);
const result = pow(quatA, 2);
try expectEqual(result, multiply(quatA, quatA));
}
/// Performs a spherical linear interpolation between two quats
pub fn slerp(a: Quat, b: Quat, t: f32) Quat {
// calc cosine
var cosom = a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
var bx = b.x;
var by = b.y;
var bz = b.z;
var bw = b.w;
// adjust signs (if necessary)
if (cosom < 0.0) {
cosom = -cosom;
bx = -bx;
by = -by;
bz = -bz;
bw = -bw;
}
var scale0: f32 = 0.0;
var scale1: f32 = 0.0;
// calculate coefficients
if ((1.0 - cosom) > utils.epsilon) {
// standard case (slerp)
const omega = math.acos(cosom);
const sinom = @sin(omega);
scale0 = @sin((1.0 - t) * omega) / sinom;
scale1 = @sin(t * omega) / sinom;
} else {
// "from" and "to" quaternions are very close
// ... so we can do a linear interpolation
scale0 = 1.0 - t;
scale1 = t;
}
// calculate final values
return Quat{
.x = scale0 * a.x + scale1 * bx,
.y = scale0 * a.y + scale1 * by,
.z = scale0 * a.z + scale1 * bz,
.w = scale0 * a.w + scale1 * bw,
};
}
test "slerp normal case" {
const out = slerp(create(0, 0, 0, 1), create(0, 1, 0, 0), 0.5);
const expected = create(0, 0.707106, 0, 0.707106);
try expectEqual(expected, out);
}
test "slerp a == b" {
const out = slerp(create(0, 0, 0, 1), create(0, 0, 0, 1), 0.5);
const expected = create(0, 0, 0, 1);
try expectEqual(expected, out);
}
test "slerp a == -b" {
const out = slerp(create(1, 0, 0, 0), create(-1, 0, 0, 0), 0.5);
const expected = create(1, 0, 0, 0);
try expectEqual(expected, out);
}
test "slerp theta == 180deg" {
const quatA = create(1, 0, 0, 0).rotateX(math.pi);
const out = slerp(create(-1, 0, 0, 0), quatA, 1);
const expected = create(0, 0, 0, -1);
try expectEqual(expected, out);
}
/// Calculates the inverse of a quat
pub fn invert(a: Quat) Quat {
const dotProduct = Quat.dot(a, a);
const invDot = if (dotProduct != 0.0) 1.0 / dotProduct else 0.0;
if (invDot == 0) return quat_zero;
return Quat{
.x = -a.x * invDot,
.y = -a.y * invDot,
.z = -a.z * invDot,
.w = a.w * invDot,
};
}
test "invert" {
const out = create(1, 2, 3, 4).invert();
const expected = create(-0.033333, -0.066666, -0.1, 0.133333);
try expectEqual(expected, out);
}
/// Calculates the conjugate of a quat
/// If the quaternion is normalized, this function is faster than Quat.inverse
/// and produces the same result.
pub fn conjugate(a: Quat) Quat {
return Quat{
.x = -a.x,
.y = -a.y,
.z = -a.z,
.w = a.w,
};
}
test "conjugate" {
var quatA = create(1, 2, 3, 4).normalize();
var result = pow(quatA, -1);
try expectEqual(quatA.conjugate(), result);
try std.testing.expect(utils.f_eq(result.length(), 1.0));
}
test "conjugate reversible" {
var quatA = create(1, 2, 3, 4).normalize();
const b = 2.1;
const result = pow(pow(quatA, b), 1 / b);
try expectEqual(quatA, result);
try std.testing.expect(utils.f_eq(result.length(), 1.0));
}
/// Creates a quaternion from the given 3x3 rotation matrix.
/// NOTE: The resultant quaternion is not normalized, so you should be sure
/// to renomalize the quaternion yourself where necessary.
pub fn fromMat3(m: Mat3) Quat {
// Algorithm in <NAME>'s article in 1987 SIGGRAPH course notes
// article "Quaternion Calculus and Fast Animation".
const fTrace = m.data[0][0] + m.data[1][1] + m.data[2][2];
if (fTrace > 0.0) {
// |w| > 1/2, may as well choose w > 1/2
const fRoot = @sqrt(fTrace + 1.0); // 2w
const fRoot4 = 0.5 / fRoot;
return Quat{
.x = (m.data[1][2] - m.data[2][1]) * fRoot4,
.y = (m.data[2][0] - m.data[0][2]) * fRoot4,
.z = (m.data[0][1] - m.data[1][0]) * fRoot4,
.w = 0.5 * fRoot,
};
} else {
// 0 1 2
// 3 4 5
// 6 7 8
// |w| <= 1/2
var i: usize = 0;
if (m.data[1][1] > m.data[0][0])
i = 1;
if (m.data[2][2] > m.data[i][i])
i = 2;
var j = (i + 1) % 3;
var k = (i + 2) % 3;
const fRoot = @sqrt(m.data[i][i] - m.data[j][j] - m.data[k][k] + 1.0);
const fRoot2 = 0.5 / fRoot;
var out: [4]f32 = undefined;
out[i] = 0.5 * fRoot;
out[3] = (m.data[j][k] - m.data[k][j]) * fRoot2;
out[j] = (m.data[j][i] + m.data[i][j]) * fRoot2;
out[k] = (m.data[k][i] + m.data[i][k]) * fRoot2;
return Quat{
.x = out[0],
.y = out[1],
.z = out[2],
.w = out[3],
};
}
}
test "fromMat3 where trace > 0" {
const mat = Mat3.create(1, 0, 0, 0, 0, -1, 0, 1, 0);
const result = fromMat3(mat);
const out = Vec3.create(0, 1, 0).transformQuat(result);
const expected = Vec3.create(0, 0, -1);
try Vec3.expectEqual(expected, out);
}
fn testFromMat3(eye: Vec3, center: Vec3, up: Vec3) !void {
const lookat = Mat4.lookat(eye, center, up);
var mat = Mat3.fromMat4(lookat).invert() orelse @panic("test failed");
mat = mat.transpose();
const result = fromMat3(mat);
const out = Vec3.create(3, 2, -1).transformQuat(result.normalize());
const expected = Vec3.create(3, 2, -1).transformMat3(mat);
try Vec3.expectEqual(expected, out);
}
test "fromMat3 normal matrix looking 'backward'" {
try testFromMat3(Vec3.create(0, 0, 0), Vec3.create(0, 0, 1), Vec3.create(0, 1, 0));
}
test "fromMat3 normal matrix looking 'left' and 'upside down'" {
try testFromMat3(Vec3.create(0, 0, 0), Vec3.create(-1, 0, 0), Vec3.create(0, -1, 0));
}
test "fromMat3 normal matrix looking 'upside down'" {
try testFromMat3(Vec3.create(0, 0, 0), Vec3.create(0, 0, 0), Vec3.create(0, -1, 0));
}
/// Creates a quaternion from the given euler angle x, y, z.
pub fn fromEuler(x: f32, y: f32, z: f32) Quat {
const halfToRad = 0.5 * math.pi / 180.0;
const xH = x * halfToRad;
const yH = y * halfToRad;
const zH = z * halfToRad;
const sx = @sin(xH);
const cx = @cos(xH);
const sy = @sin(yH);
const cy = @cos(yH);
const sz = @sin(zH);
const cz = @cos(zH);
return Quat{
.x = sx * cy * cz - cx * sy * sz,
.y = cx * sy * cz + sx * cy * sz,
.z = cx * cy * sz - sx * sy * cz,
.w = cx * cy * cz + sx * sy * sz,
};
}
test "fromEuler legacy" {
const result = fromEuler(-90, 0, 0);
try expectEqual(result, Quat.create(-0.707106, 0, 0, 0.707106));
}
test "fromEuler where trace > 0" {
const result = fromEuler(-90, 0, 0);
try expectEqual(result, Quat.create(-0.707106, 0, 0, 0.707106));
}
/// Sets a quaternion to represent the shortest rotation from one
/// vector to another.
/// Both vectors are assumed to be unit length.
pub fn rotationTo(a: Vec3, b: Vec3) Quat {
var tmpvec3 = Vec3.zero;
var xUnitVec3 = Vec3.create(1, 0, 0);
var yUnitVec3 = Vec3.create(0, 1, 0);
const dotProduct = Vec3.dot(a, b);
if (dotProduct < (-1 + utils.epsilon)) {
tmpvec3 = Vec3.cross(xUnitVec3, a);
if (Vec3.len(tmpvec3) < utils.epsilon)
tmpvec3 = Vec3.cross(yUnitVec3, a);
tmpvec3 = Vec3.normalize(tmpvec3);
return fromAxisAngle(tmpvec3, math.pi);
} else if (dotProduct > (1 - utils.epsilon)) {
return quat_identity;
} else {
tmpvec3 = Vec3.cross(a, b);
const out = Quat{
.x = tmpvec3.x,
.y = tmpvec3.y,
.z = tmpvec3.z,
.w = 1 + dotProduct,
};
return normalize(out);
}
}
test "rotationTo at right angle" {
const result = rotationTo(Vec3.create(0, 1, 0), Vec3.create(1, 0, 0));
try expectEqual(result, Quat.create(0, 0, -0.707106, 0.707106));
}
test "rotationTo when vectors are parallel" {
const result = rotationTo(Vec3.create(0, 1, 0), Vec3.create(0, 1, 0));
try Vec3.expectEqual(Vec3.create(0, 1, 0), Vec3.create(0, 1, 0).transformQuat(result));
}
test "rotationTo when vectors are opposed X" {
const result = rotationTo(Vec3.create(1, 0, 0), Vec3.create(-1, 0, 0));
try Vec3.expectEqual(Vec3.create(-1, 0, 0), Vec3.create(1, 0, 0).transformQuat(result));
}
test "rotationTo when vectors are opposed Y" {
const result = rotationTo(Vec3.create(0, 1, 0), Vec3.create(0, -1, 0));
try Vec3.expectEqual(Vec3.create(0, -1, 0), Vec3.create(0, 1, 0).transformQuat(result));
}
test "rotationTo when vectors are opposed Z" {
const result = rotationTo(Vec3.create(0, 0, 1), Vec3.create(0, 0, -1));
try Vec3.expectEqual(Vec3.create(0, 0, -1), Vec3.create(0, 0, 1).transformQuat(result));
}
/// Performs a spherical linear interpolation with two control points
pub fn sqlerp(a: Quat, b: Quat, c: Quat, d: Quat, t: f32) Quat {
var temp1 = slerp(a, d, t);
var temp2 = slerp(b, c, t);
return slerp(temp1, temp2, 2 * t * (1 - t));
}
pub fn equals(a: Quat, b: Quat) bool {
return utils.f_eq(a.x, b.x) //
and utils.f_eq(a.y, b.y) //
and utils.f_eq(a.z, b.z) //
and utils.f_eq(a.w, b.w);
}
pub fn equalsExact(a: Quat, b: Quat) bool {
return a.x == b.x //
and a.y == b.y //
and a.z == b.z //
and a.w == b.w;
}
pub fn format(
value: @This(),
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = options;
_ = fmt;
const str = "Quat({d:.3}, {d:.3}, {d:.3}, {d:.3})";
return std.fmt.format(writer, str, .{ value.x, value.y, value.z, value.w });
}
fn expectEqual(expected: Quat, actual: Quat) !void {
if (!expected.equals(actual)) {
std.debug.warn("Expected: {}, found {}", .{ expected, actual });
return error.NotEqual;
}
}
pub const mul = multiply;
}; | src/quat.zig |
pub const rune_error: u32 = 0xfffd;
pub const max_rune: u32 = 0x10ffff;
pub const rune_self: u32 = 0x80;
const surrogate_min: u32 = 0xD800;
const surrogate_max: u32 = 0xDFFF;
const t1: u32 = 0x00; // 0000 0000
const tx: u32 = 0x80; // 1000 0000
const t2: u32 = 0xC0; // 1100 0000
const t3: u32 = 0xE0; // 1110 0000
const t4: u32 = 0xF0; // 1111 0000
const t5: u32 = 0xF8; // 1111 1000
const maskx: u32 = 0x3F; // 0011 1111
const mask2: u32 = 0x1F; // 0001 1111
const mask3: u32 = 0x0F; // 0000 1111
const mask4: u32 = 0x07; // 0000 0111
const rune1Max: u32 = 1 << 7 - 1;
const rune2Max: u32 = 1 << 11 - 1;
const rune3Max: u32 = 1 << 16 - 1;
// The default lowest and highest continuation byte.
const locb: u8 = 0x80; // 1000 0000
const hicb: u8 = 0xBF; // 1011 1111
// These names of these constants are chosen to give nice alignment in the
// table below. The first nibble is an index into acceptRanges or F for
// special one-byte cases. The second nibble is the Rune length or the
// Status for the special one-byte case.
const xx: u8 = 0xF1; // invalid: size 1
const as: u8 = 0xF0; // ASCII: size 1
const s1: u8 = 0x02; // accept 0, size 2
const s2: u8 = 0x13; // accept 1, size 3
const s3: u8 = 0x03; // accept 0, size 3
const s4: u8 = 0x23; // accept 2, size 3
const s5: u8 = 0x34; // accept 3, size 4
const s6: u8 = 0x04; // accept 0, size 4
const s7: u8 = 0x44; // accept 4, size 4
// first is information about the first byte in a UTF-8 sequence.
const first = []u8{
// 1 2 3 4 5 6 7 8 9 A B C D E F
as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, // 0x00-0x0F
as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, // 0x10-0x1F
as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, // 0x20-0x2F
as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, // 0x30-0x3F
as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, // 0x40-0x4F
as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, // 0x50-0x5F
as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, // 0x60-0x6F
as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, as, // 0x70-0x7F
// 1 2 3 4 5 6 7 8 9 A B C D E F
xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, // 0x80-0x8F
xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, // 0x90-0x9F
xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, // 0xA0-0xAF
xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, // 0xB0-0xBF
xx, xx, s1, s1, s1, s1, s1, s1, s1, s1, s1, s1, s1, s1, s1, s1, // 0xC0-0xCF
s1, s1, s1, s1, s1, s1, s1, s1, s1, s1, s1, s1, s1, s1, s1, s1, // 0xD0-0xDF
s2, s3, s3, s3, s3, s3, s3, s3, s3, s3, s3, s3, s3, s4, s3, s3, // 0xE0-0xEF
s5, s6, s6, s6, s7, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, // 0xF0-0xFF
};
const acceptRange = struct{
lo: u8,
hi: u8,
fn init(lo: u8, hi: u8) acceptRange {
return acceptRange{ .lo = lo, .hi = hi };
}
};
const accept_ranges = []acceptRange{
acceptRange.init(locb, hicb),
acceptRange.init(0xA0, hicb),
acceptRange.init(locb, 0x9F),
acceptRange.init(0x90, hicb),
acceptRange.init(locb, 0x8F),
};
pub fn fullRune(p: []const u8) bool {
const n = p.len;
if (n == 0) {
return false;
}
const x = first[p[0]];
if (n >= @intCast(usize, x & 7)) {
return true; // ASCII, invalid or valid.
}
// Must be short or invalid
const accept = accept_ranges[@intCast(usize, x >> 4)];
if (n > 1 and (p[1] < accept.lo or accept.hi < p[1])) {
return true;
} else if (n > 2 and (p[0] < locb or hicb < p[2])) {
return true;
}
return false;
}
pub const Rune = struct{
value: u32,
size: usize,
};
pub fn decodeRune(p: []const u8) !Rune {
const n = p.len;
if (n < 1) {
return error.RuneError;
}
const p0 = p[0];
const x = first[p[0]];
if (x >= as) {
// The following code simulates an additional check for x == xx and
// handling the ASCII and invalid cases accordingly. This mask-and-or
// approach prevents an additional branch.
const mask = @intCast(u32) << 31 >> 31;
return Rune{
.value = @intCast(u32, p[0]) & ~mask | rune_error & mask,
.size = 1,
};
}
const sz = x & 7;
const accept = accept_ranges[@intCast(usize, x >> 4)];
if (n < @intCast(usize, sz)) {
return error.RuneError;
}
const b1 = p[1];
if (b1 < accept.lo or accept.hi < b1) {
return error.RuneError;
}
if (sz == 2) {
return Rune{
.value = @intCast(u32, p0 & mask2) << 6 | @intCast(u32, b1 & maskx),
.size = 2,
};
}
const b2 = p[2];
if (b2 < locb or hicb < b2) {
return error.RuneError;
}
if (sz == 3) {
return Rune{
.value = @intCast(u32, p0 & mask3) << 12 | @intCast(u32, b1 & maskx) << 6 | @intCast(u32, b2 & maskx),
.size = 3,
};
}
const b3 = p[3];
if (b3 < locb or hicb < be) {
return error.RuneError;
}
return Rune{
.value = @intCast(u32, p0 & mask4) << 18 | @intCast(u32, b1 & maskx) << 12 | @intCast(u32, b2 & maskx) << 6 | @intCast(u32, b3 & maskx),
.size = 3,
};
} | src/unicode/utf8/index.zig |
const sg = @import("sokol").gfx;
const sapp = @import("sokol").app;
const sgapp = @import("sokol").app_gfx_glue;
const stm = @import("sokol").time;
const sdtx = @import("sokol").debugtext;
const std = @import("std");
const fmt = @import("std").fmt;
fn script() void {
_ = say(.{
.o = "rack",
.m =
\\hello! my name's rack!
\\it's a pleasure to meet you!
});
var v = switch (say(.{
.o = "rack",
.m = "everything's fine?",
.p = [4][]const u8{ "yup :)", "nope :(", undefined, undefined },
})) {
0 => {
_ = say(.{
.o = "rack",
.m =
\\that's great, dude!
\\i'm glad you're glad :)
});
},
1 => {
_ = say(.{
.o = "rack",
.m =
\\aw shucks man, that sucks.
\\i hope everything gets-
\\better from now on...
});
},
else => unreachable,
};
stop();
}
var scriptframe: @Frame(script) = undefined;
var pass_action: sg.PassAction = .{};
export fn init() void {
stm.setup();
sg.setup(.{ .context = sgapp.context() });
var sdtx_desc: sdtx.Desc = .{};
sdtx_desc.fonts[0] = @import("fontdata.zig").fontdesc;
sdtx.setup(sdtx_desc);
pass_action.colors[0] = .{
.action = .CLEAR,
.value = .{ .r = 0, .g = 0.125, .b = 0.25, .a = 1 },
};
scriptframe = async script();
}
////////////////////////////////////////////////////////////////////////////////////////
pub const dialogline = struct {
o: []const u8 = "UNKN_WN", m: []const u8 = "FLAGRANT ERROR!", // lets rant about flags for a second
p: [4][]const u8 = undefined
};
var sintime: f32 = 0;
var continueDialog: bool = true;
var currentDialog: dialogline = undefined;
var length: f32 = 0;
var speed: f32 = 4;
var busy: bool = true;
var selection: u8 = 0;
var sayframe: anyframe = undefined;
pub fn say(what: dialogline) u8 {
sayframe = @frame();
selection = 0;
length = 0;
currentDialog = what;
suspend;
return selection;
}
pub fn stop() void {
busy = false;
}
const name = "metahome";
var frame_count: u32 = 0;
var time_stamp: u64 = 0;
export fn frame() void {
frame_count += 1;
const delta = @floatCast(f32, stm.ms(stm.laptime(&time_stamp)) * 0.005);
sdtx.canvas(sapp.widthf() * 0.5, sapp.heightf() * 0.5);
sdtx.origin(4, 11);
sdtx.font(0);
if (busy) {
sintime += delta;
sdtx.color3b(0xbb, 0xaa, 0xff);
sdtx.print("{s}:\n", .{currentDialog.o});
sdtx.crlf();
sdtx.moveY(-0.5);
sdtx.color3b(0xff, 0xff, 0xff);
sdtx.print("{s}", .{currentDialog.m[0..@floatToInt(u32, length)]});
sdtx.crlf();
if (@floatToInt(u32, length) < currentDialog.m.len) {
if (currentDialog.m[@floatToInt(u32, length)] == 17) {
resume sayframe;
}
if (keys.skp) {
length += speed * 2 * delta;
} else {
length += speed * delta;
}
} else {
var maxselect: u8 = 4;
var skipped: bool = false;
sdtx.moveY(0.5);
var mx: f32 = 0;
var my: f32 = 0;
for (currentDialog.p) |option, indx| {
if (option.len == 0) {
maxselect = @intCast(u8, indx);
skipped = (indx == 0);
break;
}
if ((@mod(@intToFloat(f32, indx), 2)) == 0) {
mx = @sin(sintime / 2) / 8;
my = @cos(sintime / 2) / 8;
} else {
mx = @cos(sintime / 2) / 8;
my = @sin(sintime / 2) / 8;
}
sdtx.move(mx, my);
if (indx == selection) {
sdtx.color3b(0xff, 0xe4, 0x78);
sdtx.print(">", .{});
} else {
sdtx.color3b(0xff, 0xaa, 0xd0);
sdtx.print(" ", .{});
}
sdtx.print("{s} ", .{option});
sdtx.move(-mx, -my);
}
if (skipped) {
mx = @sin(sintime / 2) / 8;
my = @cos(sintime / 2) / 8;
sdtx.move(mx, my);
sdtx.color3b(0xff, 0xe4, 0x78);
sdtx.print(">next", .{});
sdtx.move(-mx, -my);
} else {
if (keys.jst_rig) {
if (selection == maxselect - 1) {
selection = 0;
} else {
selection += 1;
}
}
if (keys.jst_lef) {
if (selection == 0) {
selection = maxselect - 1;
} else {
selection -= 1;
}
}
}
if (keys.nxt) {
resume sayframe;
}
}
} else {
sintime += delta / 2;
for (name) |char, indx| {
sdtx.putc(char);
sdtx.crlf();
sdtx.posX(@intToFloat(f32, indx + 1));
sdtx.posY(@sin(sintime + @intToFloat(f32, indx + 1)));
}
}
sg.beginDefaultPass(pass_action, sapp.width(), sapp.height());
sdtx.draw();
sg.endPass();
sg.commit();
keys.jst_lef = false;
keys.jst_rig = false;
}
export fn cleanup() void {
sdtx.shutdown();
sg.shutdown();
}
const _keystruct = struct {
nxt: bool = false, skp: bool = false, any: bool = false, lef: bool = false, rig: bool = false, jst_lef: bool = false, jst_rig: bool = false
};
var keys = _keystruct{};
export fn input(ev: ?*const sapp.Event) void {
const event = ev.?;
if ((event.type == .KEY_DOWN) or (event.type == .KEY_UP)) {
const key_pressed = event.type == .KEY_DOWN;
keys.any = key_pressed;
switch (event.key_code) {
.X => keys.skp = key_pressed,
.C => keys.nxt = key_pressed,
.LEFT => {
keys.jst_lef = key_pressed and !keys.lef;
keys.lef = key_pressed;
},
.RIGHT => {
keys.jst_rig = key_pressed and !keys.rig;
keys.rig = key_pressed;
},
else => {},
}
}
}
pub fn main() void {
sapp.run(.{
.init_cb = init,
.frame_cb = frame,
.cleanup_cb = cleanup,
.event_cb = input,
.width = 640,
.height = 480,
.window_title = "METAHOME DEBUGTEXT BUILD",
});
} | src/dialogtest.zig |
const builtin = @import("builtin");
const std = @import("std");
const os = @import("windows.zig");
const dxgi = @import("dxgi.zig");
const dcommon = @import("dcommon.zig");
const HRESULT = os.HRESULT;
const ITextFormat = @import("dwrite.zig").ITextFormat;
const IWICBitmapSource = @import("wincodec.zig").IBitmapSource;
pub const FACTORY_TYPE = extern enum {
SINGLE_THREADED = 0,
MULTI_THREADED = 1,
};
pub const DEBUG_LEVEL = extern enum {
NONE = 0,
ERROR = 1,
WARNING = 2,
INFORMATION = 3,
};
pub const FACTORY_OPTIONS = extern struct {
debugLevel: DEBUG_LEVEL,
};
pub const DEVICE_CONTEXT_OPTIONS = packed struct {
ENABLE_MULTITHREADED_OPTIMIZATIONS: bool = false,
};
pub const COLOR_F = extern struct {
r: f32,
g: f32,
b: f32,
a: f32,
pub const Black = COLOR_F{ .r = 0.0, .g = 0.0, .b = 0.0, .a = 1.0 };
fn toSrgb(s: f32) f32 {
var l: f32 = undefined;
if (s > 0.0031308) {
l = 1.055 * (std.math.pow(f32, s, (1.0 / 2.4))) - 0.055;
} else {
l = 12.92 * s;
}
return l;
}
pub fn linearToSrgb(r: f32, g: f32, b: f32, a: f32) COLOR_F {
return COLOR_F{
.r = toSrgb(r),
.g = toSrgb(g),
.b = toSrgb(b),
.a = a,
};
}
};
pub const COLOR_SPACE = extern enum {
CUSTOM = 0,
SRGB = 1,
SCRGB = 2,
};
pub const ELLIPSE = extern struct {
point: dcommon.POINT_2F,
radiusX: f32,
radiusY: f32,
};
pub const BITMAP_OPTIONS = packed struct {
TARGET: bool = false,
CANNOT_DRAW: bool = false,
CPU_READ: bool = false,
GDI_COMPATIBLE: bool = false,
padding: u28 = 0,
};
pub const BITMAP_INTERPOLATION_MODE = extern enum {
NEAREST_NEIGHBOR = 0,
LINEAR = 1,
CUBIC = 2,
MULTI_SAMPLE_LINEAR = 3,
ANISOTROPIC = 4,
HIGH_QUALITY_CUBIC = 5,
FANT = 6,
MIPMAP_LINEAR = 7,
};
pub const BRUSH_PROPERTIES = extern struct {
opacity: f32,
transform: dcommon.MATRIX_3X2_F,
};
pub const BITMAP_PROPERTIES1 = extern struct {
pixelFormat: dcommon.PIXEL_FORMAT,
dpiX: f32,
dpiY: f32,
bitmapOptions: BITMAP_OPTIONS,
colorContext: ?*IColorContext = null,
};
pub const DRAW_TEXT_OPTIONS = packed struct {
NO_SNAP: bool = false,
CLIP: bool = false,
ENABLE_COLOR_FONT: bool = false,
DISABLE_COLOR_BITMAP_SNAPPING: bool = false,
padding: u28 = 0,
};
pub const IResource = extern struct {
const Self = @This();
vtbl: *const extern struct {
// IUnknown
QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT,
AddRef: fn (*Self) callconv(.C) u32,
Release: fn (*Self) callconv(.C) u32,
// ID2D1Resource
GetFactory: *c_void,
},
usingnamespace os.IUnknown.Methods(Self);
};
pub const IImage = extern struct {
const Self = @This();
vtbl: *const extern struct {
// IUnknown
QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT,
AddRef: fn (*Self) callconv(.C) u32,
Release: fn (*Self) callconv(.C) u32,
// ID2D1Resource
GetFactory: *c_void,
},
usingnamespace os.IUnknown.Methods(Self);
};
pub const IColorContext = extern struct {
const Self = @This();
vtbl: *const extern struct {
// IUnknown
QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT,
AddRef: fn (*Self) callconv(.C) u32,
Release: fn (*Self) callconv(.C) u32,
// ID2D1Resource
GetFactory: *c_void,
// ID2D1ColorContext
GetColorSpace: *c_void,
GetProfileSize: *c_void,
GetProfile: *c_void,
},
usingnamespace os.IUnknown.Methods(Self);
};
pub const IBitmap1 = extern struct {
const Self = @This();
vtbl: *const extern struct {
// IUnknown
QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT,
AddRef: fn (*Self) callconv(.C) u32,
Release: fn (*Self) callconv(.C) u32,
// ID2D1Resource
GetFactory: *c_void,
// ID2D1Bitmap
GetSize: *c_void,
GetPixelSize: *c_void,
GetPixelFormat: *c_void,
GetPixelDpi: *c_void,
CopyFromBitmap: *c_void,
CopyFromRenderTarget: *c_void,
CopyFromMemory: *c_void,
// ID2D1Bitmap1
GetColorContext: *c_void,
GetOptions: *c_void,
GetSurface: *c_void,
Map: *c_void,
Unmap: *c_void,
},
usingnamespace os.IUnknown.Methods(Self);
};
pub const IGradientStopCollection = extern struct {
const Self = @This();
vtbl: *const extern struct {
// IUnknown
QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT,
AddRef: fn (*Self) callconv(.C) u32,
Release: fn (*Self) callconv(.C) u32,
// ID2D1Resource
GetFactory: *c_void,
// ID2D1GradientStopCollection
GetGradientStopCount: *c_void,
GetGradientStops: *c_void,
GetColorInterpolationGamma: *c_void,
GetExtendMode: *c_void,
},
usingnamespace os.IUnknown.Methods(Self);
};
pub const IBrush = extern struct {
const Self = @This();
vtbl: *const extern struct {
// IUnknown
QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT,
AddRef: fn (*Self) callconv(.C) u32,
Release: fn (*Self) callconv(.C) u32,
// ID2D1Resource
GetFactory: *c_void,
// ID2D1Brush
SetOpacity: *c_void,
SetTransform: *c_void,
GetOpacity: *c_void,
GetTransform: *c_void,
},
usingnamespace os.IUnknown.Methods(Self);
};
pub const IBitmapBrush = extern struct {
const Self = @This();
vtbl: *const extern struct {
// IUnknown
QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT,
AddRef: fn (*Self) callconv(.C) u32,
Release: fn (*Self) callconv(.C) u32,
// ID2D1Resource
GetFactory: fn (*Self, **IFactory) callconv(.C) void,
GetFactory: *c_void,
// ID2D1Brush
SetOpacity: *c_void,
SetTransform: *c_void,
GetOpacity: *c_void,
GetTransform: *c_void,
// ID2D1BitmapBrush
SetExtendModeX: *c_void,
SetExtendModeY: *c_void,
SetInterpolationMode: *c_void,
SetBitmap: *c_void,
GetExtendModeX: *c_void,
GetExtendModeY: *c_void,
GetInterpolationMode: *c_void,
GetBitmap: *c_void,
},
usingnamespace os.IUnknown.Methods(Self);
};
pub const ISolidColorBrush = extern struct {
const Self = @This();
vtbl: *const extern struct {
// IUnknown
QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT,
AddRef: fn (*Self) callconv(.C) u32,
Release: fn (*Self) callconv(.C) u32,
// ID2D1Resource
GetFactory: *c_void,
// ID2D1Brush
SetOpacity: *c_void,
SetTransform: *c_void,
GetOpacity: *c_void,
GetTransform: *c_void,
// ID2D1SolidColorBrush
SetColor: fn (*Self, *const COLOR_F) callconv(.C) void,
GetColor: fn (*Self, *COLOR_F) callconv(.C) *COLOR_F,
},
usingnamespace os.IUnknown.Methods(Self);
usingnamespace ISolidColorBrush.Methods(Self);
fn Methods(comptime T: type) type {
return extern struct {
pub inline fn SetColor(self: *T, color: *const COLOR_F) void {
self.vtbl.SetColor(self, color);
}
pub inline fn GetColor(self: *T) COLOR_F {
var color: COLOR_F = undefined;
_ = self.vtbl.GetColor(self, &color);
return color;
}
};
}
};
pub const ILinearGradientBrush = extern struct {
const Self = @This();
vtbl: *const extern struct {
// IUnknown
QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT,
AddRef: fn (*Self) callconv(.C) u32,
Release: fn (*Self) callconv(.C) u32,
// ID2D1Resource
GetFactory: *c_void,
// ID2D1Brush
SetOpacity: *c_void,
SetTransform: *c_void,
GetOpacity: *c_void,
GetTransform: *c_void,
// ID2D1LinearGradientBrush
SetStartPoint: *c_void,
SetEndPoint: *c_void,
GetStartPoint: *c_void,
GetEndPoint: *c_void,
GetGradientStopCollection: *c_void,
},
usingnamespace os.IUnknown.Methods(Self);
};
pub const IRadialGradientBrush = extern struct {
const Self = @This();
vtbl: *const extern struct {
// IUnknown
QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT,
AddRef: fn (*Self) callconv(.C) u32,
Release: fn (*Self) callconv(.C) u32,
// ID2D1Resource
GetFactory: *c_void,
// ID2D1Brush
SetOpacity: *c_void,
SetTransform: *c_void,
GetOpacity: *c_void,
GetTransform: *c_void,
// ID2D1RadialGradientBrush
SetCenter: *c_void,
SetGradientOriginOffset: *c_void,
SetRadiusX: *c_void,
SetRadiusY: *c_void,
GetCenter: *c_void,
GetGradientOriginOffset: *c_void,
GetRadiusX: *c_void,
GetRadiusY: *c_void,
GetGradientStopCollection: *c_void,
},
usingnamespace os.IUnknown.Methods(Self);
};
pub const IStrokeStyle = extern struct {
const Self = @This();
vtbl: *const extern struct {
// IUnknown
QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT,
AddRef: fn (*Self) callconv(.C) u32,
Release: fn (*Self) callconv(.C) u32,
// ID2D1Resource
GetFactory: *c_void,
// ID2D1StrokeStyle
GetStartCap: *c_void,
GetEndCap: *c_void,
GetDashCap: *c_void,
GetMiterLimit: *c_void,
GetLineJoin: *c_void,
GetDashOffset: *c_void,
GetDashStyle: *c_void,
GetDashesCount: *c_void,
GetDashes: *c_void,
},
usingnamespace os.IUnknown.Methods(Self);
};
pub const IGeometry = extern struct {
const Self = @This();
vtbl: *const extern struct {
// IUnknown
QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT,
AddRef: fn (*Self) callconv(.C) u32,
Release: fn (*Self) callconv(.C) u32,
// ID2D1Resource
GetFactory: *c_void,
// ID2D1Geometry
GetBounds: *c_void,
GetWidenedBounds: *c_void,
StrokeContainsPoint: *c_void,
FillContainsPoint: *c_void,
CompareWithGeometry: *c_void,
Simplify: *c_void,
Tessellate: *c_void,
CombineWithGeometry: *c_void,
Outline: *c_void,
ComputeArea: *c_void,
ComputeLength: *c_void,
ComputePointAtLength: *c_void,
Widen: *c_void,
},
usingnamespace os.IUnknown.Methods(Self);
};
pub const IRectangleGeometry = extern struct {
const Self = @This();
vtbl: *const extern struct {
// IUnknown
QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT,
AddRef: fn (*Self) callconv(.C) u32,
Release: fn (*Self) callconv(.C) u32,
// ID2D1Resource
GetFactory: *c_void,
// ID2D1Geometry
GetBounds: *c_void,
GetWidenedBounds: *c_void,
StrokeContainsPoint: *c_void,
FillContainsPoint: *c_void,
CompareWithGeometry: *c_void,
Simplify: *c_void,
Tessellate: *c_void,
CombineWithGeometry: *c_void,
Outline: *c_void,
ComputeArea: *c_void,
ComputeLength: *c_void,
ComputePointAtLength: *c_void,
Widen: *c_void,
// ID2D1RectangleGeometry
GetRect: *c_void,
},
usingnamespace os.IUnknown.Methods(Self);
};
pub const IRoundedRectangleGeometry = extern struct {
const Self = @This();
vtbl: *const extern struct {
// IUnknown
QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT,
AddRef: fn (*Self) callconv(.C) u32,
Release: fn (*Self) callconv(.C) u32,
// ID2D1Resource
GetFactory: *c_void,
// ID2D1Geometry
GetBounds: *c_void,
GetWidenedBounds: *c_void,
StrokeContainsPoint: *c_void,
FillContainsPoint: *c_void,
CompareWithGeometry: *c_void,
Simplify: *c_void,
Tessellate: *c_void,
CombineWithGeometry: *c_void,
Outline: *c_void,
ComputeArea: *c_void,
ComputeLength: *c_void,
ComputePointAtLength: *c_void,
Widen: *c_void,
// ID2D1RoundedRectangleGeometry
GetRoundRect: *c_void,
},
usingnamespace os.IUnknown.Methods(Self);
};
pub const IEllipseGeometry = extern struct {
const Self = @This();
vtbl: *const extern struct {
// IUnknown
QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT,
AddRef: fn (*Self) callconv(.C) u32,
Release: fn (*Self) callconv(.C) u32,
// ID2D1Resource
GetFactory: *c_void,
// ID2D1Geometry
GetBounds: *c_void,
GetWidenedBounds: *c_void,
StrokeContainsPoint: *c_void,
FillContainsPoint: *c_void,
CompareWithGeometry: *c_void,
Simplify: *c_void,
Tessellate: *c_void,
CombineWithGeometry: *c_void,
Outline: *c_void,
ComputeArea: *c_void,
ComputeLength: *c_void,
ComputePointAtLength: *c_void,
Widen: *c_void,
// ID2D1EllipseGeometry
GetEllipse: *c_void,
},
usingnamespace os.IUnknown.Methods(Self);
};
pub const IGeometryGroup = extern struct {
const Self = @This();
vtbl: *const extern struct {
// IUnknown
QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT,
AddRef: fn (*Self) callconv(.C) u32,
Release: fn (*Self) callconv(.C) u32,
// ID2D1Resource
GetFactory: *c_void,
// ID2D1Geometry
GetBounds: *c_void,
GetWidenedBounds: *c_void,
StrokeContainsPoint: *c_void,
FillContainsPoint: *c_void,
CompareWithGeometry: *c_void,
Simplify: *c_void,
Tessellate: *c_void,
CombineWithGeometry: *c_void,
Outline: *c_void,
ComputeArea: *c_void,
ComputeLength: *c_void,
ComputePointAtLength: *c_void,
Widen: *c_void,
// ID2D1GeometryGroup
GetFillMode: *c_void,
GetSourceGeometryCount: *c_void,
GetSourceGeometries: *c_void,
},
usingnamespace os.IUnknown.Methods(Self);
};
pub const ITransformedGeometry = extern struct {
const Self = @This();
vtbl: *const extern struct {
// IUnknown
QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT,
AddRef: fn (*Self) callconv(.C) u32,
Release: fn (*Self) callconv(.C) u32,
// ID2D1Resource
GetFactory: *c_void,
// ID2D1Geometry
GetBounds: *c_void,
GetWidenedBounds: *c_void,
StrokeContainsPoint: *c_void,
FillContainsPoint: *c_void,
CompareWithGeometry: *c_void,
Simplify: *c_void,
Tessellate: *c_void,
CombineWithGeometry: *c_void,
Outline: *c_void,
ComputeArea: *c_void,
ComputeLength: *c_void,
ComputePointAtLength: *c_void,
Widen: *c_void,
// ID2D1TransformedGeometry
GetSourceGeometry: *c_void,
GetTransform: *c_void,
},
usingnamespace os.IUnknown.Methods(Self);
};
pub const ISimplifiedGeometrySink = extern struct {
const Self = @This();
vtbl: *const extern struct {
// IUnknown
QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT,
AddRef: fn (*Self) callconv(.C) u32,
Release: fn (*Self) callconv(.C) u32,
// ID2D1SimplifiedGeometrySink
SetFillMode: *c_void,
SetSegmentFlags: *c_void,
BeginFigure: *c_void,
AddLines: *c_void,
AddBeziers: *c_void,
EndFigure: *c_void,
Close: *c_void,
},
usingnamespace os.IUnknown.Methods(Self);
};
pub const IGeometrySink = extern struct {
const Self = @This();
vtbl: *const extern struct {
// IUnknown
QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT,
AddRef: fn (*Self) callconv(.C) u32,
Release: fn (*Self) callconv(.C) u32,
// ID2D1SimplifiedGeometrySink
SetFillMode: *c_void,
SetSegmentFlags: *c_void,
BeginFigure: *c_void,
AddLines: *c_void,
AddBeziers: *c_void,
EndFigure: *c_void,
Close: *c_void,
// ID2D1GeometrySink
AddLine: *c_void,
AddBezier: *c_void,
AddQuadraticBezier: *c_void,
AddQuadraticBeziers: *c_void,
AddArc: *c_void,
},
usingnamespace os.IUnknown.Methods(Self);
};
pub const ITessellationSink = extern struct {
const Self = @This();
vtbl: *const extern struct {
// IUnknown
QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT,
AddRef: fn (*Self) callconv(.C) u32,
Release: fn (*Self) callconv(.C) u32,
// ID2D1TessellationSink
AddTriangles: *c_void,
Close: *c_void,
},
usingnamespace os.IUnknown.Methods(Self);
};
pub const IPathGeometry = extern struct {
const Self = @This();
vtbl: *const extern struct {
// IUnknown
QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT,
AddRef: fn (*Self) callconv(.C) u32,
Release: fn (*Self) callconv(.C) u32,
// ID2D1Resource
GetFactory: *c_void,
// ID2D1Geometry
GetBounds: *c_void,
GetWidenedBounds: *c_void,
StrokeContainsPoint: *c_void,
FillContainsPoint: *c_void,
CompareWithGeometry: *c_void,
Simplify: *c_void,
Tessellate: *c_void,
CombineWithGeometry: *c_void,
Outline: *c_void,
ComputeArea: *c_void,
ComputeLength: *c_void,
ComputePointAtLength: *c_void,
Widen: *c_void,
// ID2D1PathGeometry
Open: *c_void,
Stream: *c_void,
GetSegmentCount: *c_void,
GetFigureCount: *c_void,
},
usingnamespace os.IUnknown.Methods(Self);
};
pub const IMesh = extern struct {
const Self = @This();
vtbl: *const extern struct {
// IUnknown
QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT,
AddRef: fn (*Self) callconv(.C) u32,
Release: fn (*Self) callconv(.C) u32,
// ID2D1Resource
GetFactory: *c_void,
// ID2D1Mesh
Open: *c_void,
},
usingnamespace os.IUnknown.Methods(Self);
};
pub const ILayer = extern struct {
const Self = @This();
vtbl: *const extern struct {
// IUnknown
QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT,
AddRef: fn (*Self) callconv(.C) u32,
Release: fn (*Self) callconv(.C) u32,
// ID2D1Resource
GetFactory: *c_void,
// ID2D1Layer
GetSize: *c_void,
},
usingnamespace os.IUnknown.Methods(Self);
};
pub const IDrawingStateBlock = extern struct {
const Self = @This();
vtbl: *const extern struct {
// IUnknown
QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT,
AddRef: fn (*Self) callconv(.C) u32,
Release: fn (*Self) callconv(.C) u32,
// ID2D1Resource
GetFactory: *c_void,
// ID2D1DrawingStateBlock
GetDescription: *c_void,
SetDescription: *c_void,
SetTextRenderingParams: *c_void,
GetTextRenderingParams: *c_void,
},
usingnamespace os.IUnknown.Methods(Self);
};
pub const IDeviceContext6 = extern struct {
const Self = @This();
vtbl: *const extern struct {
// IUnknown
QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT,
AddRef: fn (*Self) callconv(.C) u32,
Release: fn (*Self) callconv(.C) u32,
// ID2D1Resource
GetFactory: *c_void,
// ID2D1RenderTarget
CreateBitmap: *c_void,
CreateBitmapFromWicBitmap: *c_void,
CreateSharedBitmap: *c_void,
CreateBitmapBrush: *c_void,
CreateSolidColorBrush: fn (
*Self,
*const COLOR_F,
?*const BRUSH_PROPERTIES,
**ISolidColorBrush,
) callconv(.C) HRESULT,
CreateGradientStopCollection: *c_void,
CreateLinearGradientBrush: *c_void,
CreateRadialGradientBrush: *c_void,
CreateCompatibleRenderTarget: *c_void,
CreateLayer: *c_void,
CreateMesh: *c_void,
DrawLine: fn (
*Self,
dcommon.POINT_2F,
dcommon.POINT_2F,
*IBrush,
f32,
?*IStrokeStyle,
) callconv(.C) void,
DrawRectangle: *c_void,
FillRectangle: fn (*Self, *const dcommon.RECT_F, *IBrush) callconv(.C) void,
DrawRoundedRectangle: *c_void,
FillRoundedRectangle: *c_void,
DrawEllipse: *c_void,
FillEllipse: fn (*Self, *const ELLIPSE, *IBrush) callconv(.C) void,
DrawGeometry: *c_void,
FillGeometry: *c_void,
FillMesh: *c_void,
FillOpacityMask: *c_void,
DrawBitmap: fn (
*Self,
*IBitmap1,
?*const dcommon.RECT_F,
f32,
BITMAP_INTERPOLATION_MODE,
?*const dcommon.RECT_F,
) callconv(.C) void,
DrawText: fn (
*Self,
os.LPCWSTR,
u32,
*ITextFormat,
*const dcommon.RECT_F,
*IBrush,
DRAW_TEXT_OPTIONS,
dcommon.MEASURING_MODE,
) callconv(.C) void,
DrawTextLayout: *c_void,
DrawGlyphRun: *c_void,
SetTransform: fn (*Self, *const dcommon.MATRIX_3X2_F) callconv(.C) void,
GetTransform: *c_void,
SetAntialiasMode: *c_void,
GetAntialiasMode: *c_void,
SetTextAntialiasMode: *c_void,
GetTextAntialiasMode: *c_void,
SetTextRenderingParams: *c_void,
GetTextRenderingParams: *c_void,
SetTags: *c_void,
GetTags: *c_void,
PushLayer: *c_void,
PopLayer: *c_void,
Flush: *c_void,
SaveDrawingState: *c_void,
RestoreDrawingState: *c_void,
PushAxisAlignedClip: *c_void,
PopAxisAlignedClip: *c_void,
Clear: fn (*Self, *const COLOR_F) callconv(.C) void,
BeginDraw: fn (*Self) callconv(.C) void,
EndDraw: fn (*Self, ?*u64, ?*u64) callconv(.C) HRESULT,
GetPixelFormat: *c_void,
SetDpi: *c_void,
GetDpi: *c_void,
GetSize: *c_void,
GetPixelSize: *c_void,
GetMaximumBitmapSize: *c_void,
IsSupported: *c_void,
// ID2D1DeviceContext
CreateBitmap1: *c_void,
CreateBitmapFromWicBitmap1: fn (
*Self,
*IWICBitmapSource,
?*const BITMAP_PROPERTIES1,
**IBitmap1,
) callconv(.C) HRESULT,
CreateColorContext: *c_void,
CreateColorContextFromFilename: *c_void,
CreateColorContextFromWicColorContext: *c_void,
CreateBitmapFromDxgiSurface: fn (
*Self,
*dxgi.ISurface,
*const BITMAP_PROPERTIES1,
**IBitmap1,
) callconv(.C) HRESULT,
CreateEffect: *c_void,
CreateGradientStopCollection1: *c_void,
CreateImageBrush: *c_void,
CreateBitmapBrush1: *c_void,
CreateCommandList: *c_void,
IsDxgiFormatSupported: *c_void,
IsBufferPrecisionSupported: *c_void,
GetImageLocalBounds: *c_void,
GetImageWorldBounds: *c_void,
GetGlyphRunWorldBounds: *c_void,
GetDevice: *c_void,
SetTarget: fn (*Self, *IImage) callconv(.C) void,
GetTarget: *c_void,
SetRenderingControls: *c_void,
GetRenderingControls: *c_void,
SetPrimitiveBlend: *c_void,
GetPrimitiveBlend: *c_void,
SetUnitMode: *c_void,
GetUnitMode: *c_void,
DrawGlyphRun1: *c_void,
DrawImage: *c_void,
DrawGdiMetafile: *c_void,
DrawBitmap1: *c_void,
PushLayer1: *c_void,
InvalidateEffectInputRectangle: *c_void,
GetEffectInvalidRectangleCount: *c_void,
GetEffectInvalidRectangles: *c_void,
GetEffectRequiredInputRectangles: *c_void,
FillOpacityMask1: *c_void,
// ID2D1DeviceContext1
CreateFilledGeometryRealization: *c_void,
CreateStrokedGeometryRealization: *c_void,
DrawGeometryRealization: *c_void,
// ID2D1DeviceContext2
CreateInk: *c_void,
CreateInkStyle: *c_void,
CreateGradientMesh: *c_void,
CreateImageSourceFromWic: *c_void,
CreateLookupTable3D: *c_void,
CreateImageSourceFromDxgi: *c_void,
GetGradientMeshWorldBounds: *c_void,
DrawInk: *c_void,
DrawGradientMesh: *c_void,
DrawGdiMetafile1: *c_void,
CreateTransformedImageSource: *c_void,
// ID2D1DeviceContext3
CreateSpriteBatch: *c_void,
DrawSpriteBatch: *c_void,
// ID2D1DeviceContext4
CreateSvgGlyphStyle: *c_void,
DrawText1: *c_void,
DrawTextLayout1: *c_void,
DrawColorBitmapGlyphRun: *c_void,
DrawSvgGlyphRun: *c_void,
GetColorBitmapGlyphImage: *c_void,
GetSvgGlyphImage: *c_void,
// ID2D1DeviceContext5
CreateSvgDocument: *c_void,
DrawSvgDocument: *c_void,
CreateColorContextFromDxgiColorSpace: *c_void,
CreateColorContextFromSimpleColorProfile: *c_void,
// ID2D1DeviceContext6
BlendImage: *c_void,
},
usingnamespace os.IUnknown.Methods(Self);
usingnamespace IDeviceContext6.Methods(Self);
fn Methods(comptime T: type) type {
return extern struct {
pub inline fn CreateBitmapFromDxgiSurface(
self: *T,
surface: *dxgi.ISurface,
properties: *const BITMAP_PROPERTIES1,
bitmap: **IBitmap1,
) HRESULT {
return self.vtbl.CreateBitmapFromDxgiSurface(self, surface, properties, bitmap);
}
pub inline fn CreateSolidColorBrush(
self: *T,
color: *const COLOR_F,
properties: ?*const BRUSH_PROPERTIES,
brush: **ISolidColorBrush,
) HRESULT {
return self.vtbl.CreateSolidColorBrush(self, color, properties, brush);
}
pub inline fn SetTarget(self: *T, image: *IImage) void {
self.vtbl.SetTarget(self, image);
}
pub inline fn BeginDraw(self: *T) void {
self.vtbl.BeginDraw(self);
}
pub inline fn EndDraw(self: *T, tag1: ?*u64, tag2: ?*u64) HRESULT {
return self.vtbl.EndDraw(self, tag1, tag2);
}
pub inline fn SetTransform(self: *T, transform: *const dcommon.MATRIX_3X2_F) void {
self.vtbl.SetTransform(self, transform);
}
pub inline fn Clear(self: *T, color: *const COLOR_F) void {
self.vtbl.Clear(self, color);
}
pub inline fn FillRectangle(self: *T, rect: *const dcommon.RECT_F, brush: *IBrush) void {
self.vtbl.FillRectangle(self, rect, brush);
}
pub inline fn FillEllipse(self: *T, ellipse: *const ELLIPSE, brush: *IBrush) void {
self.vtbl.FillEllipse(self, ellipse, brush);
}
pub inline fn DrawLine(
self: *T,
p0: dcommon.POINT_2F,
p1: dcommon.POINT_2F,
brush: *IBrush,
width: f32,
style: ?*IStrokeStyle,
) void {
self.vtbl.DrawLine(self, p0, p1, brush, width, style);
}
pub inline fn DrawText(
self: *T,
string: os.LPCWSTR,
length: u32,
format: *ITextFormat,
layout_rect: *const dcommon.RECT_F,
brush: *IBrush,
options: DRAW_TEXT_OPTIONS,
measuring_mode: dcommon.MEASURING_MODE,
) void {
self.vtbl.DrawText(
self,
string,
length,
format,
layout_rect,
brush,
options,
measuring_mode,
);
}
pub fn DrawTextSimple(
self: *T,
string: []u8,
format: *ITextFormat,
layout_rect: *const dcommon.RECT_F,
brush: *IBrush,
) void {
// NOTE: This is helper method, not part of D2D1 API.
std.debug.assert(string.len < 128);
var utf16: [128:0]u16 = undefined;
const len = std.unicode.utf8ToUtf16Le(utf16[0..], string) catch unreachable;
utf16[len] = 0;
DrawText(self, &utf16, @intCast(u32, len), format, layout_rect, brush, .{}, .NATURAL);
}
pub inline fn DrawBitmap(
self: *T,
bitmap: *IBitmap1,
dst_rect: ?*const dcommon.RECT_F,
opacity: f32,
interpolation_mode: BITMAP_INTERPOLATION_MODE,
src_rect: ?*const dcommon.RECT_F,
) void {
self.vtbl.DrawBitmap(self, bitmap, dst_rect, opacity, interpolation_mode, src_rect);
}
pub inline fn CreateBitmapFromWicBitmap1(
self: *T,
wic_src: *IWICBitmapSource,
props: ?*const BITMAP_PROPERTIES1,
bitmap: **IBitmap1,
) HRESULT {
return self.vtbl.CreateBitmapFromWicBitmap1(self, wic_src, props, bitmap);
}
};
}
};
pub const IDevice6 = extern struct {
const Self = @This();
vtbl: *const extern struct {
// IUnknown
QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT,
AddRef: fn (*Self) callconv(.C) u32,
Release: fn (*Self) callconv(.C) u32,
// ID2D1Resource
GetFactory: *c_void,
// ID2D1Device
CreateDeviceContext: *c_void,
CreatePrintControl: *c_void,
SetMaximumTextureMemory: *c_void,
GetMaximumTextureMemory: *c_void,
ClearResources: *c_void,
// ID2D1Device1
GetRenderingPriority: *c_void,
SetRenderingPriority: *c_void,
CreateDeviceContext1: *c_void,
// ID2D1Device2
CreateDeviceContext2: *c_void,
FlushDeviceContexts: *c_void,
GetDxgiDevice: *c_void,
// ID2D1Device3
CreateDeviceContext3: *c_void,
// ID2D1Device4
CreateDeviceContext4: *c_void,
SetMaximumColorGlyphCacheMemory: *c_void,
GetMaximumColorGlyphCacheMemory: *c_void,
// ID2D1Device5
CreateDeviceContext5: *c_void,
// ID2D1Device6
CreateDeviceContext6: fn (
*Self,
DEVICE_CONTEXT_OPTIONS,
**IDeviceContext6,
) callconv(.C) HRESULT,
},
usingnamespace os.IUnknown.Methods(Self);
usingnamespace IDevice6.Methods(Self);
fn Methods(comptime T: type) type {
return extern struct {
pub inline fn CreateDeviceContext6(
self: *T,
options: DEVICE_CONTEXT_OPTIONS,
device_context6: **IDeviceContext6,
) HRESULT {
return self.vtbl.CreateDeviceContext6(self, options, device_context6);
}
};
}
};
pub const IFactory7 = extern struct {
const Self = @This();
vtbl: *const extern struct {
// IUnknown
QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT,
AddRef: fn (*Self) callconv(.C) u32,
Release: fn (*Self) callconv(.C) u32,
// ID2D1Factory
ReloadSystemMetrics: *c_void,
GetDesktopDpi: *c_void,
CreateRectangleGeometry: *c_void,
CreateRoundedRectangleGeometry: *c_void,
CreateEllipseleGeometry: *c_void,
CreateGeometryGroup: *c_void,
CreateTransformedGeometry: *c_void,
CreatePathGeometry: *c_void,
CreateStrokeStyle: *c_void,
CreateDrawingStateBlock: *c_void,
CreateWicBitmapRenderTarget: *c_void,
CreateHwndRenderTarget: *c_void,
CreateDxgiSurfaceRenderTarget: *c_void,
CreateDCRenderTarget: *c_void,
// ID2D1Factory1
CreateDevice: *c_void,
CreateStrokeStyle1: *c_void,
CreatePathGeometry1: *c_void,
CreateDrawingStateBlock1: *c_void,
CreateGdiMetafile: *c_void,
RegisterEffectFromStream: *c_void,
RegisterEffectFromString: *c_void,
UnregisterEffect: *c_void,
GetRegisteredEffects: *c_void,
GetEffectProperties: *c_void,
// ID2D1Factory2
CreateDevice1: *c_void,
// ID2D1Factory3
CreateDevice2: *c_void,
// ID2D1Factory4
CreateDevice3: *c_void,
// ID2D1Factory5
CreateDevice4: *c_void,
// ID2D1Factory6
CreateDevice5: *c_void,
// ID2D1Factory7
CreateDevice6: fn (*Self, *dxgi.IDevice, **IDevice6) callconv(.C) HRESULT,
},
usingnamespace os.IUnknown.Methods(Self);
usingnamespace IFactory7.Methods(Self);
fn Methods(comptime T: type) type {
return extern struct {
pub inline fn CreateDevice6(
self: *T,
dxgi_device: *dxgi.IDevice,
d2d_device6: **IDevice6,
) HRESULT {
return self.vtbl.CreateDevice6(self, dxgi_device, d2d_device6);
}
};
}
};
pub const IID_IFactory7 = os.GUID{
.Data1 = 0xbdc2bdd3,
.Data2 = 0xb96c,
.Data3 = 0x4de6,
.Data4 = .{ 0xbd, 0xf7, 0x99, 0xd4, 0x74, 0x54, 0x54, 0xde },
};
pub var CreateFactory: fn (
FACTORY_TYPE,
*const os.GUID,
*const FACTORY_OPTIONS,
**c_void,
) callconv(.C) HRESULT = undefined;
pub fn init() void {
var d2d1_dll = os.LoadLibraryA("d2d1.dll").?;
CreateFactory = @ptrCast(@TypeOf(CreateFactory), os.kernel32.GetProcAddress(
d2d1_dll,
"D2D1CreateFactory",
).?);
} | src/windows/d2d1.zig |
const inputFile = @embedFile("./input/day12.txt");
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const Str = []const u8;
const BitSet = std.DynamicBitSet;
const StrMap = std.StringHashMap;
const assert = std.debug.assert;
const tokenize = std.mem.tokenize;
const print = std.debug.print;
fn sort(comptime T: type, items: []T) void {
std.sort.sort(T, items, {}, comptime std.sort.asc(T));
}
fn println(x: Str) void {
print("{s}\n", .{x});
}
/// Perform a DFS on the input
fn partOne(input: Input, allocator: Allocator) !usize {
var visited = try BitSet.initEmpty(allocator, input.caves.len);
var path = ArrayList(usize).init(allocator);
return try dfsRecursive(input, input.start, &visited, &path, 0);
}
/// Perform a DFS on the input
fn partTwo(input: Input, allocator: Allocator) !usize {
var visited = try BitSet.initEmpty(allocator, input.caves.len);
defer visited.deinit();
var path = ArrayList(usize).init(allocator);
defer path.deinit();
return try dfsRecursive(input, input.start, &visited, &path, null);
}
fn dfsRecursive(input: Input, n: usize, visited: *BitSet, path: *ArrayList(usize), visitedSmallCaveTwice_: ?usize) error{OutOfMemory}!usize {
if (n == input.end) {
// print("Reached with path ", .{});
// for (path.items) |pathnode| {
// print("{s}, ", .{input.caveNames[pathnode]});
// }
// println("end");
return 1;
}
var visitedSmallCaveTwice = visitedSmallCaveTwice_;
if (visited.isSet(n) and input.caves[n] == .Small) {
if (visitedSmallCaveTwice != null) return 0;
visitedSmallCaveTwice = n;
}
var result: usize = 0;
visited.set(n);
try path.append(n);
for (input.adjacency[n]) |neighbor| {
result += try dfsRecursive(input, neighbor, visited, path, visitedSmallCaveTwice);
}
_ = path.pop();
// Handle the case when you visited the small cave twice, so don't unpop from visited
if (visitedSmallCaveTwice) |caveVisited| {
if (caveVisited == n) {
return result;
}
}
// In other cases, unpop visited.
visited.unset(n);
return result;
}
pub fn main() !void {
// Standard boilerplate for Aoc problems
const stdout = std.io.getStdOut().writer();
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var gpaAllocator = gpa.allocator();
defer assert(!gpa.deinit()); // Check for memory leaks
var arena = std.heap.ArenaAllocator.init(gpaAllocator);
defer arena.deinit();
var allocator = arena.allocator(); // use an arena
var input = try parseInput(inputFile, allocator);
const p1 = try partOne(input, allocator);
const p2 = try partTwo(input, allocator);
try stdout.print("{any}\nPart1: {d}\nPart2: {d}", .{ input, p1, p2 });
}
const CaveType = enum { Big, Small };
const Input = struct {
caves: []CaveType,
caveNames: []Str,
adjacency: [][]usize,
start: usize,
end: usize,
allocator: Allocator,
pub fn deinit(self: @This()) void {
self.allocator.free(self.caves);
self.allocator.free(self.caveNames);
for (self.adjacency) |nodes| {
self.allocator.free(nodes);
}
self.allocator.free(self.adjacency);
}
// printf implementation
pub fn format(self: @This(), comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
for (self.adjacency) |neighbors, from| {
try writer.print("{s} ({any}) - ", .{ self.caveNames[from], self.caves[from] });
for (neighbors) |neighbor| {
try writer.print("{s}, ", .{self.caveNames[neighbor]});
}
try writer.print("\n", .{});
}
}
};
fn parseInput(input: Str, allocator: Allocator) !Input {
var caves = ArrayList(CaveType).init(allocator);
errdefer caves.deinit();
var caveNames = ArrayList(Str).init(allocator);
errdefer caveNames.deinit();
var caveNameToNum = StrMap(usize).init(allocator);
defer caveNameToNum.deinit();
var adjacency = ArrayList(ArrayList(usize)).init(allocator);
defer adjacency.deinit();
errdefer for (adjacency.items) |neighbors| {
neighbors.deinit();
};
try caves.append(.Small);
try caveNames.append("start");
try caveNameToNum.put("start", 0);
var start: usize = 0;
var end: usize = 0;
var it = tokenize(u8, input, "\n");
while (it.next()) |line| {
var caveIt = tokenize(u8, line, "-");
const first = try getCaveNum(caveIt.next().?, &caveNameToNum, &caveNames, &caves, &start, &end);
const second = try getCaveNum(caveIt.next().?, &caveNameToNum, &caveNames, &caves, &start, &end);
assert(caveIt.next() == null);
const from = std.math.min(first, second);
const to = std.math.max(first, second);
if (to >= adjacency.items.len) {
// allocate and initialize more space
var i = adjacency.items.len;
try adjacency.resize(to + 1);
while (i <= to) : (i += 1) {
adjacency.items[i] = ArrayList(usize).init(allocator);
}
}
try adjacency.items[from].append(to);
if (from != start) {
// one way for start (special cased)
try adjacency.items[to].append(from);
}
}
const adjacencySlices = try allocator.alloc([]usize, adjacency.items.len);
for (adjacencySlices) |*slic, i| {
slic.* = adjacency.items[i].toOwnedSlice();
}
// sanity checks
assert(caves.items.len == caveNames.items.len);
assert(caves.items.len == adjacencySlices.len);
return Input{
.caves = caves.toOwnedSlice(),
.caveNames = caveNames.toOwnedSlice(),
.adjacency = adjacencySlices,
.start = start,
.end = end,
.allocator = allocator,
};
}
// Helper function extracted out
fn getCaveNum(
name: Str,
caveNameToNum: *StrMap(usize),
caveNames: *ArrayList(Str),
caves: *ArrayList(CaveType),
start: *usize,
end: *usize,
) !usize {
if (caveNameToNum.get(name)) |num| {
return num;
}
const num = caveNames.items.len;
try caveNames.append(name);
try caveNameToNum.put(name, num);
if (std.ascii.isUpper(name[0])) {
try caves.append(.Big);
} else {
try caves.append(.Small);
if (std.mem.eql(u8, name, "start")) {
start.* = num;
} else if (std.mem.eql(u8, name, "end")) {
end.* = num;
}
}
return num;
}
test "parse input" {
const testInput =
\\start-A
\\start-b
\\A-c
\\A-b
\\b-d
\\A-end
\\b-end
\\
;
var allocator = std.testing.allocator;
const input = try parseInput(testInput, allocator);
defer input.deinit();
print("\n{any}\n", .{input});
}
test "part 2" {
const testInput =
\\start-A
\\start-b
\\A-c
\\A-b
\\b-d
\\A-end
\\b-end
\\
;
var allocator = std.testing.allocator;
const input = try parseInput(testInput, allocator);
defer input.deinit();
try std.testing.expectEqual(@as(usize, 36), try partTwo(input, allocator));
}
test "part 2 Larger" {
const testInput =
\\dc-end
\\HN-start
\\start-kj
\\dc-start
\\dc-HN
\\LN-dc
\\HN-end
\\kj-sa
\\kj-HN
\\kj-dc
\\
;
var allocator = std.testing.allocator;
const input = try parseInput(testInput, allocator);
defer input.deinit();
try std.testing.expectEqual(@as(usize, 103), try partTwo(input, allocator));
}
test "part 2 Larger 2" {
const testInput =
\\fs-end
\\he-DX
\\fs-he
\\start-DX
\\pj-DX
\\end-zg
\\zg-sl
\\zg-pj
\\pj-he
\\RW-he
\\fs-DX
\\pj-RW
\\zg-RW
\\start-pj
\\he-WI
\\zg-he
\\pj-fs
\\start-RW
\\
;
var allocator = std.testing.allocator;
const input = try parseInput(testInput, allocator);
defer input.deinit();
try std.testing.expectEqual(@as(usize, 3509), try partTwo(input, allocator));
} | src/day12.zig |
const std = @import("std");
const mem = std.mem;
const net = std.net;
const os = std.os;
const time = std.time;
const IO = @import("tigerbeetle-io").IO;
const http = @import("http");
fn IoOpContext(comptime ResultType: type) type {
return struct {
frame: anyframe = undefined,
result: ResultType = undefined,
};
}
const Client = struct {
io: IO,
sock: os.socket_t,
address: std.net.Address,
send_buf: []u8,
recv_buf: []u8,
recv_ctx: RecvWithTimeoutContext = undefined,
allocator: mem.Allocator,
done: bool = false,
fn init(allocator: mem.Allocator, address: std.net.Address) !Client {
const sock = try os.socket(address.any.family, os.SOCK_STREAM | os.SOCK_CLOEXEC, 0);
const send_buf = try allocator.alloc(u8, 8192);
const recv_buf = try allocator.alloc(u8, 8192);
return Client{
.io = try IO.init(256, 0),
.sock = sock,
.address = address,
.send_buf = send_buf,
.recv_buf = recv_buf,
.allocator = allocator,
};
}
pub fn deinit(self: *Client) void {
self.allocator.free(self.send_buf);
self.allocator.free(self.recv_buf);
self.io.deinit();
}
pub fn start(self: *Client, recv_timeout_nanoseconds: u63) !void {
defer {
close(&self.io, self.sock) catch |err| {
std.debug.print("failed to close socket. err={s}\n", .{@errorName(err)});
};
// self.done = true;
}
try connect(&self.io, self.sock, self.address);
var fbs = std.io.fixedBufferStream(self.send_buf);
var w = fbs.writer();
std.fmt.format(w, "Hello from client!\n", .{}) catch unreachable;
const sent = try send(&self.io, self.sock, fbs.getWritten());
std.debug.print("Sent: {s}", .{self.send_buf[0..sent]});
self.recv_ctx.client = self;
if (recvWithTimeout(&self.io, &self.recv_ctx, self.sock, self.recv_buf, recv_timeout_nanoseconds)) |received| {
std.debug.print("Received: {s}", .{self.recv_buf[0..received]});
} else |err| {
switch (err) {
error.Canceled => std.debug.print("recv canceled.\n", .{}),
else => std.debug.print("unexpected error from recvWithTimeout, err={s}\n", .{@errorName(err)}),
}
}
}
pub fn run(self: *Client) !void {
while (!self.done) try self.io.tick();
}
const ConnectContext = IoOpContext(IO.ConnectError!void);
fn connect(io: *IO, sock: os.socket_t, address: std.net.Address) IO.ConnectError!void {
var ctx: ConnectContext = undefined;
var completion: IO.Completion = undefined;
io.connect(*ConnectContext, &ctx, connectCallback, &completion, sock, address);
suspend {
ctx.frame = @frame();
}
return ctx.result;
}
fn connectCallback(
ctx: *ConnectContext,
completion: *IO.Completion,
result: IO.ConnectError!void,
) void {
ctx.result = result;
resume ctx.frame;
}
const SendContext = IoOpContext(IO.SendError!usize);
fn send(io: *IO, sock: os.socket_t, buffer: []const u8) IO.SendError!usize {
var ctx: SendContext = undefined;
var completion: IO.Completion = undefined;
io.send(
*SendContext,
&ctx,
sendCallback,
&completion,
sock,
buffer,
if (std.Target.current.os.tag == .linux) os.MSG_NOSIGNAL else 0,
);
suspend {
ctx.frame = @frame();
}
return ctx.result;
}
fn sendCallback(
ctx: *SendContext,
completion: *IO.Completion,
result: IO.SendError!usize,
) void {
ctx.result = result;
resume ctx.frame;
}
const RecvContext = IoOpContext(IO.RecvError!usize);
fn recv(io: *IO, sock: os.socket_t, buffer: []u8) IO.RecvError!usize {
var ctx: RecvContext = undefined;
var completion: IO.Completion = undefined;
io.recv(
*RecvContext,
&ctx,
recvCallback,
&completion,
sock,
buffer,
if (std.Target.current.os.tag == .linux) os.MSG_NOSIGNAL else 0,
);
suspend {
ctx.frame = @frame();
}
return ctx.result;
}
fn recvCallback(
ctx: *RecvContext,
completion: *IO.Completion,
result: IO.RecvError!usize,
) void {
ctx.result = result;
resume ctx.frame;
}
const RecvWithTimeoutContext = struct {
recv_completion: IO.Completion = undefined,
timeout_completion: IO.Completion = undefined,
frame: anyframe = undefined,
result: ?IO.RecvError!usize = null,
cancel_recv_completion: IO.Completion = undefined,
cancel_timeout_completion: IO.Completion = undefined,
client: *Client = null,
};
fn recvWithTimeout(io: *IO, ctx: *RecvWithTimeoutContext, sock: os.socket_t, buffer: []u8, timeout_nanoseconds: u63) IO.RecvError!usize {
io.recv(
*RecvWithTimeoutContext,
ctx,
recvWithTimeoutRecvCallback,
&ctx.recv_completion,
sock,
buffer,
if (std.Target.current.os.tag == .linux) os.MSG_NOSIGNAL else 0,
);
io.timeout(
*RecvWithTimeoutContext,
ctx,
recvWithTimeoutTimeoutCallback,
&ctx.timeout_completion,
timeout_nanoseconds,
);
std.debug.print("submitted recv and timeout.\n", .{});
suspend {
ctx.frame = @frame();
}
return ctx.result.?;
}
fn recvWithTimeoutRecvCallback(
ctx: *RecvWithTimeoutContext,
completion: *IO.Completion,
result: IO.RecvError!usize,
) void {
if (ctx.result) |_| {} else {
completion.io.cancelTimeout(
*RecvWithTimeoutContext,
ctx,
recvWithTimeoutCancelTimeoutCallback,
&ctx.cancel_timeout_completion,
&ctx.timeout_completion,
);
ctx.result = result;
std.debug.print("resume frame after recv.\n", .{});
resume ctx.frame;
}
}
fn recvWithTimeoutTimeoutCallback(
ctx: *RecvWithTimeoutContext,
completion: *IO.Completion,
result: IO.TimeoutError!void,
) void {
if (ctx.result) |_| {} else {
completion.io.cancel(
*RecvWithTimeoutContext,
ctx,
recvWithTimeoutCancelRecvCallback,
&ctx.cancel_recv_completion,
&ctx.recv_completion,
);
ctx.result = error.Canceled;
std.debug.print("resume frame after timeout.\n", .{});
resume ctx.frame;
}
}
fn recvWithTimeoutCancelRecvCallback(
ctx: *RecvWithTimeoutContext,
completion: *IO.Completion,
result: IO.CancelError!void,
) void {
std.debug.print("recvWithTimeoutCancelRecvCallback start\n", .{});
ctx.client.done = true;
if (result) |_| {} else |err| {
switch (err) {
error.AlreadyInProgress, error.NotFound => {
std.debug.print("recv op canceled, err={s}\n", .{@errorName(err)});
},
else => @panic(@errorName(err)),
}
}
}
fn recvWithTimeoutCancelTimeoutCallback(
ctx: *RecvWithTimeoutContext,
completion: *IO.Completion,
result: IO.CancelTimeoutError!void,
) void {
std.debug.print("recvWithTimeoutCancelTimeoutCallback start\n", .{});
ctx.client.done = true;
if (result) |_| {} else |err| {
switch (err) {
error.AlreadyInProgress, error.NotFound, error.Canceled => {
std.debug.print("timeout op canceled, err={s}\n", .{@errorName(err)});
},
else => @panic(@errorName(err)),
}
}
}
const CloseContext = IoOpContext(IO.CloseError!void);
fn close(io: *IO, sock: os.socket_t) IO.CloseError!void {
var ctx: CloseContext = undefined;
var completion: IO.Completion = undefined;
io.close(
*CloseContext,
&ctx,
closeCallback,
&completion,
sock,
);
suspend {
ctx.frame = @frame();
}
return ctx.result;
}
fn closeCallback(
ctx: *CloseContext,
completion: *IO.Completion,
result: IO.CloseError!void,
) void {
ctx.result = result;
resume ctx.frame;
}
};
pub fn main() anyerror!void {
const allocator = std.heap.page_allocator;
const address = try std.net.Address.parseIp4("127.0.0.1", 3131);
var client = try Client.init(allocator, address);
defer client.deinit();
var recv_timeout: u63 = 500 * std.time.ns_per_ms;
var args = std.process.args();
if (args.nextPosix()) |_| {
if (args.nextPosix()) |arg| {
if (std.fmt.parseInt(u63, arg, 10)) |v| {
recv_timeout = v * std.time.ns_per_ms;
} else |_| {}
}
}
std.debug.print("recv_timeout={d} ms.\n", .{recv_timeout / time.ns_per_ms});
_ = async client.start(recv_timeout);
try client.run();
} | examples/async_tcp_echo_client_timeout.zig |
const std = @import("std");
const use_test_input = false;
const filename = if (use_test_input) "day-10_test-input" else "day-10_real-input";
const line_count = if (use_test_input) 10 else 94;
pub fn main() !void {
std.debug.print("--- Day 10 ---\n", .{});
var scores_buffer: [1024 * 1024]u8 = undefined;
var scores_allocator = std.heap.FixedBufferAllocator.init(scores_buffer[0..]);
var line_scores = std.ArrayList(u64).init(scores_allocator.allocator());
var file = try std.fs.cwd().openFile(filename, .{});
defer file.close();
var line_index: usize = 0;
while (line_index < line_count):(line_index += 1) {
var buffer: [1000]u8 = undefined;
var buffer_allocator = std.heap.FixedBufferAllocator.init(buffer[0..]);
var parenStack = std.ArrayList(u8).init(buffer_allocator.allocator());
var line_is_corrupted = false;
var char = try file.reader().readByte();
while (char != '\r' and char != '\n'):(char = try file.reader().readByte()) {
var is_open_paren = true;
switch (char) {
'(' => try parenStack.append(')'),
'[' => try parenStack.append(']'),
'{' => try parenStack.append('}'),
'<' => try parenStack.append('>'),
else => is_open_paren = false
}
if (!is_open_paren) {
const expected = parenStack.pop();
if (char != expected) {
line_is_corrupted = true;
break;
}
}
}
if (char != '\n') {
try file.reader().skipUntilDelimiterOrEof('\n');
}
if (!line_is_corrupted) {
var line_score: u64 = 0;
while (parenStack.items.len > 0) {
const expected = parenStack.pop();
line_score *= 5;
line_score += getPoints(expected);
}
try line_scores.append(line_score);
}
}
if (line_scores.items.len == 0) unreachable;
quickSort(line_scores.items);
const middle_score = line_scores.items[line_scores.items.len / 2];
std.debug.print("middle score is {}\n", .{ middle_score });
}
fn getPoints(char: u8) u64 {
return switch (char) {
')' => 1,
']' => 2,
'}' => 3,
'>' => 4,
else => unreachable
};
}
fn quickSort(array: []u64) void {
var pivot = array.len - 1;
var greater: usize = 0;
var smaller: usize = 0;
while (true) {
while (greater < pivot):(greater += 1) {
if (array[greater] > array[pivot]) {
break;
}
}
if (smaller < greater) {
smaller = greater;
}
while (smaller < pivot):(smaller += 1) {
if (array[smaller] < array[pivot]) {
break;
}
}
if (greater == pivot or smaller == pivot) {
break;
}
const tmp = array[greater];
array[greater] = array[smaller];
array[smaller] = tmp;
}
{
const tmp = array[greater];
array[greater] = array[pivot];
array[pivot] = tmp;
}
if (greater > 0) {
quickSort(array[0..greater]);
}
if (greater < array.len - 1) {
quickSort(array[(greater + 1)..]);
}
}
test "sort" {
var array = [_]u64 { 8, 7, 6, 1, 0, 9, 2 };
quickSort(array[0..]);
} | day-10.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const mustache = @import("../mustache.zig");
const Element = mustache.Element;
const ParseError = mustache.ParseError;
const ParseErrorDetail = mustache.ParseErrorDetail;
const TemplateOptions = mustache.options.TemplateOptions;
const TemplateLoadMode = mustache.options.TemplateLoadMode;
const assert = std.debug.assert;
const testing = std.testing;
const parsing = @import("parsing.zig");
const Delimiters = parsing.Delimiters;
const PartType = parsing.PartType;
const ref_counter = @import("ref_counter.zig");
pub fn Parser(comptime options: TemplateOptions) type {
const allow_lambdas = options.features.lambdas == .Enabled;
const copy_string = options.copyStrings();
const is_comptime = options.load_mode == .comptime_loaded;
return struct {
pub const LoadError = Allocator.Error || if (options.source == .Stream) std.fs.File.ReadError || std.fs.File.OpenError else error{};
pub const AbortError = error{ParserAbortedError};
pub const Node = parsing.Node(options);
const TextScanner = parsing.TextScanner(Node, options);
const FileReader = parsing.FileReader(options);
const TextPart = Node.TextPart;
const RefCounter = ref_counter.RefCounter(options);
const comptime_count = if (is_comptime) TextScanner.ComptimeCounter.count() else {};
fn RenderError(comptime TRender: type) type {
switch (@typeInfo(TRender)) {
.Pointer => |pointer| {
if (pointer.size == .One) {
const Render = pointer.child;
return Render.Error;
}
},
else => {},
}
@compileError("Expected a pointer to a Render");
}
const Self = @This();
/// General purpose allocator
gpa: Allocator,
/// Stores the last error ocurred parsing the content
last_error: ?ParseErrorDetail = null,
/// Default open/close delimiters
default_delimiters: Delimiters,
/// Parser's inner state
inner_state: struct {
nodes: Node.List = undefined,
text_scanner: TextScanner,
last_static_text_node: ?u32 = null,
},
pub fn init(gpa: Allocator, template: []const u8, delimiters: Delimiters) if (options.source == .String) Allocator.Error!Self else FileReader.OpenError!Self {
return Self{
.gpa = gpa,
.default_delimiters = delimiters,
.inner_state = .{
.text_scanner = try TextScanner.init(template),
},
};
}
pub fn deinit(self: *Self) void {
self.inner_state.text_scanner.deinit(self.gpa);
}
pub fn parse(self: *Self, render: anytype) (LoadError || RenderError(@TypeOf(render)))!bool {
self.inner_state.nodes = Node.List{};
var nodes = &self.inner_state.nodes;
self.inner_state.text_scanner.nodes = nodes;
if (is_comptime) {
var buffer: [comptime_count.nodes]Node = undefined;
nodes.items.ptr = &buffer;
nodes.items.len = 0;
nodes.capacity = buffer.len;
} else {
// Initializes with a small buffer
// It gives a better performance for tiny templates and serves as hint for next resizes.
const initial_capacity = 16;
try nodes.ensureTotalCapacityPrecise(self.gpa, initial_capacity);
}
defer if (is_comptime) {
nodes.clearRetainingCapacity();
} else {
nodes.deinit(self.gpa);
};
self.beginLevel(0, self.default_delimiters, render) catch |err| switch (err) {
AbortError.ParserAbortedError => return false,
else => {
const Error = LoadError || RenderError(@TypeOf(render));
return @errSetCast(Error, err);
},
};
return true;
}
fn beginLevel(self: *Self, level: u32, delimiters: Delimiters, render: anytype) (AbortError || LoadError || RenderError(@TypeOf(render)))!void {
var current_delimiters = delimiters;
var nodes = &self.inner_state.nodes;
const initial_index = nodes.items.len;
if (self.inner_state.text_scanner.delimiter_max_size == 0) {
self.inner_state.text_scanner.setDelimiters(current_delimiters) catch |err| {
return self.abort(err, null);
};
}
while (try self.inner_state.text_scanner.next(self.gpa)) |*text_part| {
switch (text_part.part_type) {
.static_text => {
// TODO: Static text must be ignored if inside a "parent" tag
// https://github.com/mustache/spec/blob/b2aeb3c283de931a7004b5f7a2cb394b89382369/specs/~inheritance.yml#L211
},
.comments => {
defer if (options.isRefCounted()) text_part.unRef(self.gpa);
// Comments are just ignored
self.checkIfLastNodeCanBeStandAlone(text_part.part_type);
continue;
},
.delimiters => {
defer if (options.isRefCounted()) text_part.unRef(self.gpa);
current_delimiters = text_part.parseDelimiters() orelse return self.abort(ParseError.InvalidDelimiters, text_part);
self.inner_state.text_scanner.setDelimiters(current_delimiters) catch |err| {
return self.abort(err, text_part);
};
self.checkIfLastNodeCanBeStandAlone(text_part.part_type);
continue;
},
.close_section => {
defer if (options.isRefCounted()) text_part.unRef(self.gpa);
if (level == 0 or initial_index == 0) {
return self.abort(ParseError.UnexpectedCloseSection, text_part);
}
var open_node: *Node = &nodes.items[initial_index - 1];
const open_identifier = open_node.identifier orelse return self.abort(ParseError.UnexpectedCloseSection, text_part);
const close_identifier = (try self.parseIdentifier(text_part)) orelse unreachable;
if (!std.mem.eql(u8, open_identifier, close_identifier)) {
return self.abort(ParseError.ClosingTagMismatch, text_part);
}
open_node.children_count = @intCast(u32, nodes.items.len - initial_index);
if (allow_lambdas and open_node.text_part.part_type == .section) {
if (try self.inner_state.text_scanner.endBookmark(nodes)) |bookmark| {
open_node.inner_text.content = bookmark;
}
}
self.checkIfLastNodeCanBeStandAlone(text_part.part_type);
return;
},
else => {},
}
// Adding
var current_node: *Node = current_node: {
const index = @intCast(u32, nodes.items.len);
const node = Node{
.index = index,
.identifier = try self.parseIdentifier(text_part),
.text_part = text_part.*,
.delimiters = current_delimiters,
};
if (is_comptime) {
nodes.appendAssumeCapacity(node);
} else {
try nodes.append(self.gpa, node);
}
break :current_node &nodes.items[index];
};
switch (current_node.text_part.part_type) {
.static_text => {
current_node.trimStandAlone(nodes);
if (current_node.text_part.isEmpty()) {
current_node.text_part.unRef(self.gpa);
_ = nodes.pop();
continue;
}
self.inner_state.last_static_text_node = current_node.index;
// When options.output = .Render,
// A stand-alone line in the root level indicates that the previous produced nodes can be rendered
if (options.output == .Render) {
if (level == 0 and
current_node.text_part.trimming.left != .PreserveWhitespaces and
self.canProducePartialNodes())
{
// Remove the last node
const last_node_value = nodes.pop();
// Render all nodes produced until now
try self.produceNodes(render);
// Clean all nodes and reinsert the last one for the next iteration,
nodes.clearRetainingCapacity();
const node = Node{
.index = 0,
.identifier = last_node_value.identifier,
.text_part = last_node_value.text_part,
.children_count = last_node_value.children_count,
.inner_text = last_node_value.inner_text,
.delimiters = last_node_value.delimiters,
};
nodes.appendAssumeCapacity(node);
current_node = &nodes.items[0];
self.inner_state.last_static_text_node = current_node.index;
}
}
},
.section,
.inverted_section,
.parent,
.block,
=> {
if (allow_lambdas and current_node.text_part.part_type == .section) {
try self.inner_state.text_scanner.beginBookmark(current_node);
}
try self.beginLevel(level + 1, current_delimiters, render);
// Restore parent delimiters
self.inner_state.text_scanner.setDelimiters(current_delimiters) catch |err| {
return self.abort(err, ¤t_node.text_part);
};
},
else => {},
}
}
if (level != 0) {
return self.abort(ParseError.UnexpectedEof, null);
}
if (self.inner_state.last_static_text_node) |last_static_text_node_index| {
var last_static_text_node: *Node = &nodes.items[last_static_text_node_index];
last_static_text_node.trimLast(self.gpa, nodes);
}
try self.produceNodes(render);
}
fn checkIfLastNodeCanBeStandAlone(self: *Self, part_type: PartType) void {
var nodes = &self.inner_state.nodes;
if (nodes.items.len > 0) {
var last_node: *Node = &nodes.items[nodes.items.len - 1];
last_node.text_part.is_stand_alone = part_type.canBeStandAlone();
}
}
fn canProducePartialNodes(self: *const Self) bool {
if (options.output == .Render) {
var nodes = &self.inner_state.nodes;
const min_nodes = 2;
if (nodes.items.len > min_nodes) {
var index: usize = 0;
const final_index = nodes.items.len - min_nodes;
while (index < final_index) : (index += 1) {
const node: *const Node = &nodes.items[index];
if (!node.text_part.isEmpty()) {
return true;
}
}
}
}
return false;
}
fn parseIdentifier(self: *Self, text_part: *const TextPart) AbortError!?[]const u8 {
switch (text_part.part_type) {
.comments,
.delimiters,
.static_text,
=> return null,
else => {
var tokenizer = std.mem.tokenize(u8, text_part.content.slice, " \t");
if (tokenizer.next()) |value| {
if (tokenizer.next() == null) {
return value;
}
}
return self.abort(ParseError.InvalidIdentifier, text_part);
},
}
}
fn abort(self: *Self, err: ParseError, text_part: ?*const TextPart) AbortError {
self.last_error = ParseErrorDetail{
.parse_error = err,
.lin = if (text_part) |value| value.source.lin else 0,
.col = if (text_part) |value| value.source.col else 0,
};
return AbortError.ParserAbortedError;
}
fn produceNodes(self: *Self, render: anytype) !void {
var nodes = &self.inner_state.nodes;
if (nodes.items.len == 0) return;
defer if (options.isRefCounted()) self.unRefNodes();
var list: std.ArrayListUnmanaged(Element) = .{};
if (options.load_mode == .runtime_loaded) {
try list.ensureTotalCapacityPrecise(self.gpa, nodes.items.len);
} else {
var buffer: [comptime_count.nodes]Element = undefined;
list.items.ptr = &buffer;
list.items.len = 0;
list.capacity = buffer.len;
}
defer if (options.load_mode == .runtime_loaded) {
// Clean up any elements left,
// Both in case of error during the creation, or in case of output == .Render
Element.deinitMany(self.gpa, copy_string, list.items);
list.deinit(self.gpa);
};
for (nodes.items) |*node| {
if (!node.text_part.isEmpty()) {
list.appendAssumeCapacity(try self.createElement(node));
}
}
const elements = if (options.output == .Render or options.load_mode == .comptime_loaded) list.items else list.toOwnedSlice(self.gpa);
try render.render(elements);
}
fn unRefNodes(self: *Self) void {
if (options.isRefCounted()) {
var nodes = &self.inner_state.nodes;
for (nodes.items) |*node| {
node.unRef(self.gpa);
}
}
}
inline fn dupe(self: *Self, slice: []const u8) Allocator.Error![]const u8 {
if (comptime copy_string) {
return try self.gpa.dupe(u8, slice);
} else {
return slice;
}
}
pub fn parsePath(self: *Self, identifier: []const u8) Allocator.Error!Element.Path {
const action = struct {
pub fn action(ctx: *Self, iterator: *std.mem.TokenIterator(u8), index: usize) Allocator.Error!?[][]const u8 {
if (iterator.next()) |part| {
var path = (try action(ctx, iterator, index + 1)) orelse unreachable;
path[index] = try ctx.dupe(part);
return path;
} else {
if (comptime options.load_mode == .comptime_loaded) {
if (index == 0) {
return null;
} else {
// Creates a static buffer only if running at comptime
const buffer_len = comptime_count.path;
assert(buffer_len >= index);
var buffer: [buffer_len][]const u8 = undefined;
return buffer[0..index];
}
} else {
if (index == 0) {
return null;
} else {
return try ctx.gpa.alloc([]const u8, index);
}
}
}
}
}.action;
const empty: Element.Path = &[0][]const u8{};
if (identifier.len == 0) {
return empty;
} else {
const path_separator = ".";
var iterator = std.mem.tokenize(u8, identifier, path_separator);
return (try action(self, &iterator, 0)) orelse empty;
}
}
fn createElement(self: *Self, node: *const Node) (AbortError || Allocator.Error)!Element {
return switch (node.text_part.part_type) {
.static_text => .{
.static_text = try self.dupe(node.text_part.content.slice),
},
else => |part_type| {
const allocator = self.gpa;
const identifier = node.identifier.?;
const indentation = if (node.getIndentation()) |node_indentation| try self.dupe(node_indentation) else null;
errdefer if (copy_string) if (indentation) |indentation_value| allocator.free(indentation_value);
const inner_text = if (node.getInnerText()) |inner_text_value| try self.dupe(inner_text_value) else null;
errdefer if (copy_string) if (inner_text) |inner_text_value| allocator.free(inner_text_value);
const children_count = node.children_count;
return switch (part_type) {
.interpolation => .{
.interpolation = try self.parsePath(identifier),
},
.unescaped_interpolation, .triple_mustache => .{
.unescaped_interpolation = try self.parsePath(identifier),
},
.inverted_section => .{
.inverted_section = .{
.path = try self.parsePath(identifier),
.children_count = children_count,
},
},
.section => .{
.section = .{
.path = try self.parsePath(identifier),
.children_count = children_count,
.inner_text = inner_text,
.delimiters = node.delimiters,
},
},
.partial => .{
.partial = .{
.key = try self.dupe(identifier),
.indentation = indentation,
},
},
.parent => .{
.parent = .{
.key = try self.dupe(identifier),
.children_count = children_count,
.indentation = indentation,
},
},
.block => .{
.block = .{
.key = try self.dupe(identifier),
.children_count = children_count,
},
},
else => unreachable,
};
},
};
}
};
}
const comptime_tests_enabled = mustache.options.comptime_tests_enabled;
fn TesterParser(comptime load_mode: TemplateLoadMode) type {
return Parser(.{ .source = .{ .String = .{} }, .output = .Render, .load_mode = load_mode });
}
const DummyRender = struct {
pub const Error = error{};
pub fn render(ctx: *@This(), elements: []Element) Error!void {
_ = ctx;
_ = elements;
}
};
test "Basic parse" {
const template_text =
\\{{! Comments block }}
\\ Hello
\\ {{#section}}
\\Name: {{name}}
\\Comments: {{&comments}}
\\{{^inverted}}Inverted text{{/inverted}}
\\{{/section}}
\\World
;
const TestRender = struct {
pub const Error = error{ TestUnexpectedResult, TestExpectedEqual };
calls: u32 = 0,
pub fn render(ctx: *@This(), elements: []Element) Error!void {
defer ctx.calls += 1;
switch (ctx.calls) {
0 => {
try testing.expectEqual(@as(usize, 10), elements.len);
{
const element = elements[0];
try testing.expectEqual(Element.Type.static_text, element);
try testing.expectEqualStrings(" Hello\n", element.static_text);
}
{
const element = elements[1];
try testing.expectEqual(Element.Type.section, element);
try testing.expectEqualStrings("section", element.section.path[0]);
try testing.expectEqual(@as(u32, 8), element.section.children_count);
}
{
const element = elements[2];
try testing.expectEqual(Element.Type.static_text, element);
try testing.expectEqualStrings("Name: ", element.static_text);
}
{
const element = elements[3];
try testing.expectEqual(Element.Type.interpolation, element);
try testing.expectEqualStrings("name", element.interpolation[0]);
}
{
const element = elements[4];
try testing.expectEqual(Element.Type.static_text, element);
try testing.expectEqualStrings("\nComments: ", element.static_text);
}
{
const element = elements[5];
try testing.expectEqual(Element.Type.unescaped_interpolation, element);
try testing.expectEqualStrings("comments", element.unescaped_interpolation[0]);
}
{
const element = elements[6];
try testing.expectEqual(Element.Type.static_text, element);
try testing.expectEqualStrings("\n", element.static_text);
}
{
const element = elements[7];
try testing.expectEqual(Element.Type.inverted_section, element);
try testing.expectEqualStrings("inverted", element.inverted_section.path[0]);
try testing.expectEqual(@as(u32, 1), element.inverted_section.children_count);
}
{
const element = elements[8];
try testing.expectEqual(Element.Type.static_text, element);
try testing.expectEqualStrings("Inverted text", element.static_text);
}
{
const element = elements[9];
try testing.expectEqual(Element.Type.static_text, element);
try testing.expectEqualStrings("\n", element.static_text);
}
},
1 => {
try testing.expectEqual(@as(usize, 1), elements.len);
{
const element = elements[0];
try testing.expectEqual(Element.Type.static_text, element);
try testing.expectEqualStrings("World", element.static_text);
}
},
else => try testing.expect(false),
}
}
};
const runTheTest = struct {
pub fn action(comptime load_mode: TemplateLoadMode) !void {
const allocator = testing.allocator;
var test_render = TestRender{};
var parser = try TesterParser(load_mode).init(allocator, template_text, .{});
defer parser.deinit();
const success = try parser.parse(&test_render);
try testing.expect(success);
try testing.expectEqual(@as(u32, 2), test_render.calls);
}
}.action;
//Runtime test
try runTheTest(.runtime_loaded);
//Comptime test
if (comptime_tests_enabled) comptime {
@setEvalBranchQuota(9999);
try runTheTest(.{
.comptime_loaded = .{
.template_text = template_text,
.default_delimiters = .{},
},
});
};
}
test "Scan standAlone tags" {
const template_text =
\\ {{!
\\ Comments block
\\ }}
\\Hello
;
const TestRender = struct {
pub const Error = error{ TestUnexpectedResult, TestExpectedEqual };
calls: u32 = 0,
pub fn render(ctx: *@This(), elements: []Element) Error!void {
defer ctx.calls += 1;
switch (ctx.calls) {
0 => {
try testing.expectEqual(@as(usize, 1), elements.len);
{
var element = elements[0];
try testing.expectEqual(Element.Type.static_text, element);
try testing.expectEqualStrings("Hello", element.static_text);
}
},
else => try testing.expect(false),
}
}
};
const runTheTest = struct {
pub fn action(comptime load_mode: TemplateLoadMode) !void {
const allocator = testing.allocator;
var test_render = TestRender{};
var parser = try TesterParser(load_mode).init(allocator, template_text, .{});
defer parser.deinit();
const success = try parser.parse(&test_render);
try testing.expect(success);
try testing.expectEqual(@as(u32, 1), test_render.calls);
}
}.action;
//Runtime test
try runTheTest(.runtime_loaded);
//Comptime test
if (comptime_tests_enabled) comptime {
@setEvalBranchQuota(9999);
try runTheTest(.{
.comptime_loaded = .{
.template_text = template_text,
.default_delimiters = .{},
},
});
};
}
test "Scan delimiters Tags" {
const template_text =
\\{{=[ ]=}}
\\[interpolation.value]
;
const TestRender = struct {
pub const Error = error{ TestUnexpectedResult, TestExpectedEqual };
calls: u32 = 0,
pub fn render(ctx: *@This(), elements: []Element) Error!void {
defer ctx.calls += 1;
switch (ctx.calls) {
0 => {
try testing.expectEqual(@as(usize, 1), elements.len);
{
var element = elements[0];
try testing.expectEqual(Element.Type.interpolation, element);
try testing.expectEqualStrings("interpolation", element.interpolation[0]);
try testing.expectEqualStrings("value", element.interpolation[1]);
}
},
else => try testing.expect(false),
}
}
};
const runTheTest = struct {
pub fn action(comptime load_mode: TemplateLoadMode) !void {
const allocator = testing.allocator;
var test_render = TestRender{};
var parser = try TesterParser(load_mode).init(allocator, template_text, .{});
defer parser.deinit();
const success = try parser.parse(&test_render);
try testing.expect(success);
try testing.expectEqual(@as(u32, 1), test_render.calls);
}
}.action;
//Runtime test
try runTheTest(.runtime_loaded);
//Comptime test
if (comptime_tests_enabled) comptime {
@setEvalBranchQuota(99999);
try runTheTest(.{
.comptime_loaded = .{
.template_text = template_text,
.default_delimiters = .{},
},
});
};
}
test "Parse - UnexpectedCloseSection " {
// Close section
// ↓
const template_text = "hello{{/section}}";
const allocator = testing.allocator;
// Cannot test parser errors at comptime because they generate compile errors.Allocator
// This test can only run at runtime
var parser = try TesterParser(.runtime_loaded).init(allocator, template_text, .{});
defer parser.deinit();
var render = DummyRender{};
const success = try parser.parse(&render);
try testing.expect(success == false);
try testing.expect(parser.last_error != null);
const err = parser.last_error.?;
try testing.expectEqual(ParseError.UnexpectedCloseSection, err.parse_error);
try testing.expectEqual(@as(u32, 1), err.lin);
try testing.expectEqual(@as(u32, 6), err.col);
}
test "Parse - Invalid delimiter" {
// Delimiter
// ↓
const template_text = "{{= not valid delimiter =}}";
const allocator = testing.allocator;
// Cannot test parser errors at comptime because they generate compile errors.Allocator
// This test can only run at runtime
var parser = try TesterParser(.runtime_loaded).init(allocator, template_text, .{});
defer parser.deinit();
var render = DummyRender{};
const success = try parser.parse(&render);
try testing.expect(success == false);
try testing.expect(parser.last_error != null);
const err = parser.last_error.?;
try testing.expectEqual(ParseError.InvalidDelimiters, err.parse_error);
try testing.expectEqual(@as(u32, 1), err.lin);
try testing.expectEqual(@as(u32, 1), err.col);
}
test "Parse - Invalid identifier" {
// Identifier
// ↓
const template_text = "Hi {{ not a valid identifier }}";
const allocator = testing.allocator;
// Cannot test parser errors at comptime because they generate compile errors.Allocator
// This test can only run at runtime
var parser = try TesterParser(.runtime_loaded).init(allocator, template_text, .{});
defer parser.deinit();
var render = DummyRender{};
const success = try parser.parse(&render);
try testing.expect(success == false);
try testing.expect(parser.last_error != null);
const err = parser.last_error.?;
try testing.expectEqual(ParseError.InvalidIdentifier, err.parse_error);
try testing.expectEqual(@as(u32, 1), err.lin);
try testing.expectEqual(@as(u32, 4), err.col);
}
test "Parse - ClosingTagMismatch " {
// Close section
// ↓
const template_text = "{{#hello}}...{{/world}}";
const allocator = testing.allocator;
// Cannot test parser errors at comptime because they generate compile errors.Allocator
// This test can only run at runtime
var parser = try TesterParser(.runtime_loaded).init(allocator, template_text, .{});
defer parser.deinit();
var render = DummyRender{};
const success = try parser.parse(&render);
try testing.expect(success == false);
try testing.expect(parser.last_error != null);
const err = parser.last_error.?;
try testing.expectEqual(ParseError.ClosingTagMismatch, err.parse_error);
try testing.expectEqual(@as(u32, 1), err.lin);
try testing.expectEqual(@as(u32, 14), err.col);
} | src/parsing/parser.zig |
const std = @import("std");
const reserved_chars = &[_]u8 {
'!', '#', '$', '%', '&', '\'',
'(', ')', '*', '+', ',', ':',
';', '=', '?', '@', '[', ']',
};
/// Returns a URI from a path, caller owns the memory allocated with `allocator`
pub fn fromPath(allocator: *std.mem.Allocator, path: []const u8) ![]const u8 {
if (path.len == 0) return "";
const prefix = if (std.builtin.os.tag == .windows) "file:///" else "file://";
var buf = std.ArrayList(u8).init(allocator);
try buf.appendSlice(prefix);
var out_stream = buf.outStream();
for (path) |char| {
if (char == std.fs.path.sep) {
try buf.append('/');
} else if (std.mem.indexOfScalar(u8, reserved_chars, char) != null) {
// Write '%' + hex with uppercase
try buf.append('%');
try std.fmt.format(out_stream, "{X}", .{char});
} else {
try buf.append(std.ascii.toLower(char));
}
}
return buf.toOwnedSlice();
}
// Original code: https://github.com/andersfr/zig-lsp/blob/master/uri.zig
fn parseHex(c: u8) !u8 {
return switch(c) {
'0'...'9' => c - '0',
'a'...'f' => c - 'a' + 10,
'A'...'F' => c - 'A' + 10,
else => return error.UriBadHexChar,
};
}
/// Caller should free memory
pub fn parse(allocator: *std.mem.Allocator, str: []const u8) ![]u8 {
if (str.len < 7 or !std.mem.eql(u8, "file://", str[0..7])) return error.UriBadScheme;
var uri = try allocator.alloc(u8, str.len - (if (std.fs.path.sep == '\\') 8 else 7));
errdefer allocator.free(uri);
const path = if (std.fs.path.sep == '\\') str[8..] else str[7..];
var i: usize = 0;
var j: usize = 0;
var e: usize = path.len;
while (j < e) : (i += 1) {
if (path[j] == '%') {
if (j + 2 >= e) return error.UriBadEscape;
const upper = try parseHex(path[j + 1]);
const lower = try parseHex(path[j + 2]);
uri[i] = (upper << 4) + lower;
j += 3;
} else {
uri[i] = if (path[j] == '/') std.fs.path.sep else path[j];
j += 1;
}
}
// Remove trailing separator
if (i > 0 and uri[i - 1] == std.fs.path.sep) {
i -= 1;
}
return allocator.shrink(uri, i);
} | src/uri.zig |
const std = @import("std");
const builtin = @import("builtin");
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
const expectError = std.testing.expectError;
var global_x: i32 = 1;
test "simple coroutine suspend and resume" {
var frame = async simpleAsyncFn();
expect(global_x == 2);
resume frame;
expect(global_x == 3);
const af: anyframe->void = &frame;
resume frame;
expect(global_x == 4);
}
fn simpleAsyncFn() void {
global_x += 1;
suspend;
global_x += 1;
suspend;
global_x += 1;
}
var global_y: i32 = 1;
test "pass parameter to coroutine" {
var p = async simpleAsyncFnWithArg(2);
expect(global_y == 3);
resume p;
expect(global_y == 5);
}
fn simpleAsyncFnWithArg(delta: i32) void {
global_y += delta;
suspend;
global_y += delta;
}
test "suspend at end of function" {
const S = struct {
var x: i32 = 1;
fn doTheTest() void {
expect(x == 1);
const p = async suspendAtEnd();
expect(x == 2);
}
fn suspendAtEnd() void {
x += 1;
suspend;
}
};
S.doTheTest();
}
test "local variable in async function" {
const S = struct {
var x: i32 = 0;
fn doTheTest() void {
expect(x == 0);
var p = async add(1, 2);
expect(x == 0);
resume p;
expect(x == 0);
resume p;
expect(x == 0);
resume p;
expect(x == 3);
}
fn add(a: i32, b: i32) void {
var accum: i32 = 0;
suspend;
accum += a;
suspend;
accum += b;
suspend;
x = accum;
}
};
S.doTheTest();
}
test "calling an inferred async function" {
const S = struct {
var x: i32 = 1;
var other_frame: *@Frame(other) = undefined;
fn doTheTest() void {
_ = async first();
expect(x == 1);
resume other_frame.*;
expect(x == 2);
}
fn first() void {
other();
}
fn other() void {
other_frame = @frame();
suspend;
x += 1;
}
};
S.doTheTest();
}
test "@frameSize" {
const S = struct {
fn doTheTest() void {
{
var ptr = @ptrCast(async fn (i32) void, other);
const size = @frameSize(ptr);
expect(size == @sizeOf(@Frame(other)));
}
{
var ptr = @ptrCast(async fn () void, first);
const size = @frameSize(ptr);
expect(size == @sizeOf(@Frame(first)));
}
}
fn first() void {
other(1);
}
fn other(param: i32) void {
var local: i32 = undefined;
suspend;
}
};
S.doTheTest();
}
test "coroutine suspend, resume" {
const S = struct {
var frame: anyframe = undefined;
fn doTheTest() void {
_ = async amain();
seq('d');
resume frame;
seq('h');
expect(std.mem.eql(u8, &points, "abcdefgh"));
}
fn amain() void {
seq('a');
var f = async testAsyncSeq();
seq('c');
await f;
seq('g');
}
fn testAsyncSeq() void {
defer seq('f');
seq('b');
suspend {
frame = @frame();
}
seq('e');
}
var points = [_]u8{'x'} ** "abcdefgh".len;
var index: usize = 0;
fn seq(c: u8) void {
points[index] = c;
index += 1;
}
};
S.doTheTest();
}
test "coroutine suspend with block" {
const p = async testSuspendBlock();
expect(!global_result);
resume a_promise;
expect(global_result);
}
var a_promise: anyframe = undefined;
var global_result = false;
async fn testSuspendBlock() void {
suspend {
comptime expect(@TypeOf(@frame()) == *@Frame(testSuspendBlock));
a_promise = @frame();
}
// Test to make sure that @frame() works as advertised (issue #1296)
// var our_handle: anyframe = @frame();
expect(a_promise == @as(anyframe, @frame()));
global_result = true;
}
var await_a_promise: anyframe = undefined;
var await_final_result: i32 = 0;
test "coroutine await" {
await_seq('a');
var p = async await_amain();
await_seq('f');
resume await_a_promise;
await_seq('i');
expect(await_final_result == 1234);
expect(std.mem.eql(u8, &await_points, "abcdefghi"));
}
async fn await_amain() void {
await_seq('b');
var p = async await_another();
await_seq('e');
await_final_result = await p;
await_seq('h');
}
async fn await_another() i32 {
await_seq('c');
suspend {
await_seq('d');
await_a_promise = @frame();
}
await_seq('g');
return 1234;
}
var await_points = [_]u8{0} ** "abcdefghi".len;
var await_seq_index: usize = 0;
fn await_seq(c: u8) void {
await_points[await_seq_index] = c;
await_seq_index += 1;
}
var early_final_result: i32 = 0;
test "coroutine await early return" {
early_seq('a');
var p = async early_amain();
early_seq('f');
expect(early_final_result == 1234);
expect(std.mem.eql(u8, &early_points, "abcdef"));
}
async fn early_amain() void {
early_seq('b');
var p = async early_another();
early_seq('d');
early_final_result = await p;
early_seq('e');
}
async fn early_another() i32 {
early_seq('c');
return 1234;
}
var early_points = [_]u8{0} ** "abcdef".len;
var early_seq_index: usize = 0;
fn early_seq(c: u8) void {
early_points[early_seq_index] = c;
early_seq_index += 1;
}
test "async function with dot syntax" {
const S = struct {
var y: i32 = 1;
async fn foo() void {
y += 1;
suspend;
}
};
const p = async S.foo();
expect(S.y == 2);
}
test "async fn pointer in a struct field" {
var data: i32 = 1;
const Foo = struct {
bar: async fn (*i32) void,
};
var foo = Foo{ .bar = simpleAsyncFn2 };
var bytes: [64]u8 align(16) = undefined;
const f = @asyncCall(&bytes, {}, foo.bar, &data);
comptime expect(@TypeOf(f) == anyframe->void);
expect(data == 2);
resume f;
expect(data == 4);
_ = async doTheAwait(f);
expect(data == 4);
}
fn doTheAwait(f: anyframe->void) void {
await f;
}
async fn simpleAsyncFn2(y: *i32) void {
defer y.* += 2;
y.* += 1;
suspend;
}
test "@asyncCall with return type" {
const Foo = struct {
bar: async fn () i32,
var global_frame: anyframe = undefined;
async fn middle() i32 {
return afunc();
}
fn afunc() i32 {
global_frame = @frame();
suspend;
return 1234;
}
};
var foo = Foo{ .bar = Foo.middle };
var bytes: [150]u8 align(16) = undefined;
var aresult: i32 = 0;
_ = @asyncCall(&bytes, &aresult, foo.bar);
expect(aresult == 0);
resume Foo.global_frame;
expect(aresult == 1234);
}
test "async fn with inferred error set" {
const S = struct {
var global_frame: anyframe = undefined;
fn doTheTest() void {
var frame: [1]@Frame(middle) = undefined;
var fn_ptr = middle;
var result: @TypeOf(fn_ptr).ReturnType.ErrorSet!void = undefined;
_ = @asyncCall(std.mem.sliceAsBytes(frame[0..]), &result, fn_ptr);
resume global_frame;
std.testing.expectError(error.Fail, result);
}
async fn middle() !void {
var f = async middle2();
return await f;
}
fn middle2() !void {
return failing();
}
fn failing() !void {
global_frame = @frame();
suspend;
return error.Fail;
}
};
S.doTheTest();
}
test "error return trace across suspend points - early return" {
const p = nonFailing();
resume p;
const p2 = async printTrace(p);
}
test "error return trace across suspend points - async return" {
const p = nonFailing();
const p2 = async printTrace(p);
resume p;
}
fn nonFailing() (anyframe->anyerror!void) {
const Static = struct {
var frame: @Frame(suspendThenFail) = undefined;
};
Static.frame = async suspendThenFail();
return &Static.frame;
}
async fn suspendThenFail() anyerror!void {
suspend;
return error.Fail;
}
async fn printTrace(p: anyframe->(anyerror!void)) void {
(await p) catch |e| {
std.testing.expect(e == error.Fail);
if (@errorReturnTrace()) |trace| {
expect(trace.index == 1);
} else switch (builtin.mode) {
.Debug, .ReleaseSafe => @panic("expected return trace"),
.ReleaseFast, .ReleaseSmall => {},
}
};
}
test "break from suspend" {
var my_result: i32 = 1;
const p = async testBreakFromSuspend(&my_result);
std.testing.expect(my_result == 2);
}
async fn testBreakFromSuspend(my_result: *i32) void {
suspend {
resume @frame();
}
my_result.* += 1;
suspend;
my_result.* += 1;
}
test "heap allocated async function frame" {
const S = struct {
var x: i32 = 42;
fn doTheTest() !void {
const frame = try std.testing.allocator.create(@Frame(someFunc));
defer std.testing.allocator.destroy(frame);
expect(x == 42);
frame.* = async someFunc();
expect(x == 43);
resume frame;
expect(x == 44);
}
fn someFunc() void {
x += 1;
suspend;
x += 1;
}
};
try S.doTheTest();
}
test "async function call return value" {
const S = struct {
var frame: anyframe = undefined;
var pt = Point{ .x = 10, .y = 11 };
fn doTheTest() void {
expectEqual(pt.x, 10);
expectEqual(pt.y, 11);
_ = async first();
expectEqual(pt.x, 10);
expectEqual(pt.y, 11);
resume frame;
expectEqual(pt.x, 1);
expectEqual(pt.y, 2);
}
fn first() void {
pt = second(1, 2);
}
fn second(x: i32, y: i32) Point {
return other(x, y);
}
fn other(x: i32, y: i32) Point {
frame = @frame();
suspend;
return Point{
.x = x,
.y = y,
};
}
const Point = struct {
x: i32,
y: i32,
};
};
S.doTheTest();
}
test "suspension points inside branching control flow" {
const S = struct {
var result: i32 = 10;
fn doTheTest() void {
expect(10 == result);
var frame = async func(true);
expect(10 == result);
resume frame;
expect(11 == result);
resume frame;
expect(12 == result);
resume frame;
expect(13 == result);
}
fn func(b: bool) void {
while (b) {
suspend;
result += 1;
}
}
};
S.doTheTest();
}
test "call async function which has struct return type" {
const S = struct {
var frame: anyframe = undefined;
fn doTheTest() void {
_ = async atest();
resume frame;
}
fn atest() void {
const result = func();
expect(result.x == 5);
expect(result.y == 6);
}
const Point = struct {
x: usize,
y: usize,
};
fn func() Point {
suspend {
frame = @frame();
}
return Point{
.x = 5,
.y = 6,
};
}
};
S.doTheTest();
}
test "pass string literal to async function" {
const S = struct {
var frame: anyframe = undefined;
var ok: bool = false;
fn doTheTest() void {
_ = async hello("hello");
resume frame;
expect(ok);
}
fn hello(msg: []const u8) void {
frame = @frame();
suspend;
expectEqual(@as([]const u8, "hello"), msg);
ok = true;
}
};
S.doTheTest();
}
test "await inside an errdefer" {
const S = struct {
var frame: anyframe = undefined;
fn doTheTest() void {
_ = async amainWrap();
resume frame;
}
fn amainWrap() !void {
var foo = async func();
errdefer await foo;
return error.Bad;
}
fn func() void {
frame = @frame();
suspend;
}
};
S.doTheTest();
}
test "try in an async function with error union and non-zero-bit payload" {
const S = struct {
var frame: anyframe = undefined;
var ok = false;
fn doTheTest() void {
_ = async amain();
resume frame;
expect(ok);
}
fn amain() void {
std.testing.expectError(error.Bad, theProblem());
ok = true;
}
fn theProblem() ![]u8 {
frame = @frame();
suspend;
const result = try other();
return result;
}
fn other() ![]u8 {
return error.Bad;
}
};
S.doTheTest();
}
test "returning a const error from async function" {
const S = struct {
var frame: anyframe = undefined;
var ok = false;
fn doTheTest() void {
_ = async amain();
resume frame;
expect(ok);
}
fn amain() !void {
var download_frame = async fetchUrl(10, "a string");
const download_text = try await download_frame;
@panic("should not get here");
}
fn fetchUrl(unused: i32, url: []const u8) ![]u8 {
frame = @frame();
suspend;
ok = true;
return error.OutOfMemory;
}
};
S.doTheTest();
}
test "async/await typical usage" {
inline for ([_]bool{ false, true }) |b1| {
inline for ([_]bool{ false, true }) |b2| {
inline for ([_]bool{ false, true }) |b3| {
inline for ([_]bool{ false, true }) |b4| {
testAsyncAwaitTypicalUsage(b1, b2, b3, b4).doTheTest();
}
}
}
}
}
fn testAsyncAwaitTypicalUsage(
comptime simulate_fail_download: bool,
comptime simulate_fail_file: bool,
comptime suspend_download: bool,
comptime suspend_file: bool,
) type {
return struct {
fn doTheTest() void {
_ = async amainWrap();
if (suspend_file) {
resume global_file_frame;
}
if (suspend_download) {
resume global_download_frame;
}
}
fn amainWrap() void {
if (amain()) |_| {
expect(!simulate_fail_download);
expect(!simulate_fail_file);
} else |e| switch (e) {
error.NoResponse => expect(simulate_fail_download),
error.FileNotFound => expect(simulate_fail_file),
else => @panic("test failure"),
}
}
fn amain() !void {
const allocator = std.testing.allocator;
var download_frame = async fetchUrl(allocator, "https://example.com/");
var download_awaited = false;
errdefer if (!download_awaited) {
if (await download_frame) |x| allocator.free(x) else |_| {}
};
var file_frame = async readFile(allocator, "something.txt");
var file_awaited = false;
errdefer if (!file_awaited) {
if (await file_frame) |x| allocator.free(x) else |_| {}
};
download_awaited = true;
const download_text = try await download_frame;
defer allocator.free(download_text);
file_awaited = true;
const file_text = try await file_frame;
defer allocator.free(file_text);
expect(std.mem.eql(u8, "expected download text", download_text));
expect(std.mem.eql(u8, "expected file text", file_text));
}
var global_download_frame: anyframe = undefined;
fn fetchUrl(allocator: *std.mem.Allocator, url: []const u8) anyerror![]u8 {
const result = try std.mem.dupe(allocator, u8, "expected download text");
errdefer allocator.free(result);
if (suspend_download) {
suspend {
global_download_frame = @frame();
}
}
if (simulate_fail_download) return error.NoResponse;
return result;
}
var global_file_frame: anyframe = undefined;
fn readFile(allocator: *std.mem.Allocator, filename: []const u8) anyerror![]u8 {
const result = try std.mem.dupe(allocator, u8, "expected file text");
errdefer allocator.free(result);
if (suspend_file) {
suspend {
global_file_frame = @frame();
}
}
if (simulate_fail_file) return error.FileNotFound;
return result;
}
};
}
test "alignment of local variables in async functions" {
const S = struct {
fn doTheTest() void {
var y: u8 = 123;
var x: u8 align(128) = 1;
expect(@ptrToInt(&x) % 128 == 0);
}
};
S.doTheTest();
}
test "no reason to resolve frame still works" {
_ = async simpleNothing();
}
fn simpleNothing() void {
var x: i32 = 1234;
}
test "async call a generic function" {
const S = struct {
fn doTheTest() void {
var f = async func(i32, 2);
const result = await f;
expect(result == 3);
}
fn func(comptime T: type, inc: T) T {
var x: T = 1;
suspend {
resume @frame();
}
x += inc;
return x;
}
};
_ = async S.doTheTest();
}
test "return from suspend block" {
const S = struct {
fn doTheTest() void {
expect(func() == 1234);
}
fn func() i32 {
suspend {
return 1234;
}
}
};
_ = async S.doTheTest();
}
test "struct parameter to async function is copied to the frame" {
const S = struct {
const Point = struct {
x: i32,
y: i32,
};
var frame: anyframe = undefined;
fn doTheTest() void {
_ = async atest();
resume frame;
}
fn atest() void {
var f: @Frame(foo) = undefined;
bar(&f);
clobberStack(10);
}
fn clobberStack(x: i32) void {
if (x == 0) return;
clobberStack(x - 1);
var y: i32 = x;
}
fn bar(f: *@Frame(foo)) void {
var pt = Point{ .x = 1, .y = 2 };
f.* = async foo(pt);
var result = await f;
expect(result == 1);
}
fn foo(point: Point) i32 {
suspend {
frame = @frame();
}
return point.x;
}
};
S.doTheTest();
}
test "cast fn to async fn when it is inferred to be async" {
const S = struct {
var frame: anyframe = undefined;
var ok = false;
fn doTheTest() void {
var ptr: async fn () i32 = undefined;
ptr = func;
var buf: [100]u8 align(16) = undefined;
var result: i32 = undefined;
const f = @asyncCall(&buf, &result, ptr);
_ = await f;
expect(result == 1234);
ok = true;
}
fn func() i32 {
suspend {
frame = @frame();
}
return 1234;
}
};
_ = async S.doTheTest();
resume S.frame;
expect(S.ok);
}
test "cast fn to async fn when it is inferred to be async, awaited directly" {
const S = struct {
var frame: anyframe = undefined;
var ok = false;
fn doTheTest() void {
var ptr: async fn () i32 = undefined;
ptr = func;
var buf: [100]u8 align(16) = undefined;
var result: i32 = undefined;
_ = await @asyncCall(&buf, &result, ptr);
expect(result == 1234);
ok = true;
}
fn func() i32 {
suspend {
frame = @frame();
}
return 1234;
}
};
_ = async S.doTheTest();
resume S.frame;
expect(S.ok);
}
test "await does not force async if callee is blocking" {
const S = struct {
fn simple() i32 {
return 1234;
}
};
var x = async S.simple();
expect(await x == 1234);
}
test "recursive async function" {
expect(recursiveAsyncFunctionTest(false).doTheTest() == 55);
expect(recursiveAsyncFunctionTest(true).doTheTest() == 55);
}
fn recursiveAsyncFunctionTest(comptime suspending_implementation: bool) type {
return struct {
fn fib(allocator: *std.mem.Allocator, x: u32) error{OutOfMemory}!u32 {
if (x <= 1) return x;
if (suspending_implementation) {
suspend {
resume @frame();
}
}
const f1 = try allocator.create(@Frame(fib));
defer allocator.destroy(f1);
const f2 = try allocator.create(@Frame(fib));
defer allocator.destroy(f2);
f1.* = async fib(allocator, x - 1);
var f1_awaited = false;
errdefer if (!f1_awaited) {
_ = await f1;
};
f2.* = async fib(allocator, x - 2);
var f2_awaited = false;
errdefer if (!f2_awaited) {
_ = await f2;
};
var sum: u32 = 0;
f1_awaited = true;
sum += try await f1;
f2_awaited = true;
sum += try await f2;
return sum;
}
fn doTheTest() u32 {
if (suspending_implementation) {
var result: u32 = undefined;
_ = async amain(&result);
return result;
} else {
return fib(std.testing.allocator, 10) catch unreachable;
}
}
fn amain(result: *u32) void {
var x = async fib(std.testing.allocator, 10);
result.* = (await x) catch unreachable;
}
};
}
test "@asyncCall with comptime-known function, but not awaited directly" {
const S = struct {
var global_frame: anyframe = undefined;
fn doTheTest() void {
var frame: [1]@Frame(middle) = undefined;
var result: @TypeOf(middle).ReturnType.ErrorSet!void = undefined;
_ = @asyncCall(std.mem.sliceAsBytes(frame[0..]), &result, middle);
resume global_frame;
std.testing.expectError(error.Fail, result);
}
async fn middle() !void {
var f = async middle2();
return await f;
}
fn middle2() !void {
return failing();
}
fn failing() !void {
global_frame = @frame();
suspend;
return error.Fail;
}
};
S.doTheTest();
}
test "@asyncCall with actual frame instead of byte buffer" {
const S = struct {
fn func() i32 {
suspend;
return 1234;
}
};
var frame: @Frame(S.func) = undefined;
var result: i32 = undefined;
const ptr = @asyncCall(&frame, &result, S.func);
resume ptr;
expect(result == 1234);
}
test "@asyncCall using the result location inside the frame" {
const S = struct {
async fn simple2(y: *i32) i32 {
defer y.* += 2;
y.* += 1;
suspend;
return 1234;
}
fn getAnswer(f: anyframe->i32, out: *i32) void {
out.* = await f;
}
};
var data: i32 = 1;
const Foo = struct {
bar: async fn (*i32) i32,
};
var foo = Foo{ .bar = S.simple2 };
var bytes: [64]u8 align(16) = undefined;
const f = @asyncCall(&bytes, {}, foo.bar, &data);
comptime expect(@TypeOf(f) == anyframe->i32);
expect(data == 2);
resume f;
expect(data == 4);
_ = async S.getAnswer(f, &data);
expect(data == 1234);
}
test "@TypeOf an async function call of generic fn with error union type" {
const S = struct {
fn func(comptime x: var) anyerror!i32 {
const T = @TypeOf(async func(x));
comptime expect(T == @TypeOf(@frame()).Child);
return undefined;
}
};
_ = async S.func(i32);
}
test "using @TypeOf on a generic function call" {
const S = struct {
var global_frame: anyframe = undefined;
var global_ok = false;
var buf: [100]u8 align(16) = undefined;
fn amain(x: var) void {
if (x == 0) {
global_ok = true;
return;
}
suspend {
global_frame = @frame();
}
const F = @TypeOf(async amain(x - 1));
const frame = @intToPtr(*F, @ptrToInt(&buf));
return await @asyncCall(frame, {}, amain, x - 1);
}
};
_ = async S.amain(@as(u32, 1));
resume S.global_frame;
expect(S.global_ok);
}
test "recursive call of await @asyncCall with struct return type" {
const S = struct {
var global_frame: anyframe = undefined;
var global_ok = false;
var buf: [100]u8 align(16) = undefined;
fn amain(x: var) Foo {
if (x == 0) {
global_ok = true;
return Foo{ .x = 1, .y = 2, .z = 3 };
}
suspend {
global_frame = @frame();
}
const F = @TypeOf(async amain(x - 1));
const frame = @intToPtr(*F, @ptrToInt(&buf));
return await @asyncCall(frame, {}, amain, x - 1);
}
const Foo = struct {
x: u64,
y: u64,
z: u64,
};
};
var res: S.Foo = undefined;
var frame: @TypeOf(async S.amain(@as(u32, 1))) = undefined;
_ = @asyncCall(&frame, &res, S.amain, @as(u32, 1));
resume S.global_frame;
expect(S.global_ok);
expect(res.x == 1);
expect(res.y == 2);
expect(res.z == 3);
}
test "nosuspend function call" {
const S = struct {
fn doTheTest() void {
const result = nosuspend add(50, 100);
expect(result == 150);
}
fn add(a: i32, b: i32) i32 {
if (a > 100) {
suspend;
}
return a + b;
}
};
S.doTheTest();
}
test "await used in expression and awaiting fn with no suspend but async calling convention" {
const S = struct {
fn atest() void {
var f1 = async add(1, 2);
var f2 = async add(3, 4);
const sum = (await f1) + (await f2);
expect(sum == 10);
}
async fn add(a: i32, b: i32) i32 {
return a + b;
}
};
_ = async S.atest();
}
test "await used in expression after a fn call" {
const S = struct {
fn atest() void {
var f1 = async add(3, 4);
var sum: i32 = 0;
sum = foo() + await f1;
expect(sum == 8);
}
async fn add(a: i32, b: i32) i32 {
return a + b;
}
fn foo() i32 {
return 1;
}
};
_ = async S.atest();
}
test "async fn call used in expression after a fn call" {
const S = struct {
fn atest() void {
var sum: i32 = 0;
sum = foo() + add(3, 4);
expect(sum == 8);
}
async fn add(a: i32, b: i32) i32 {
return a + b;
}
fn foo() i32 {
return 1;
}
};
_ = async S.atest();
}
test "suspend in for loop" {
const S = struct {
var global_frame: ?anyframe = null;
fn doTheTest() void {
_ = async atest();
while (global_frame) |f| resume f;
}
fn atest() void {
expect(func(&[_]u8{ 1, 2, 3 }) == 6);
}
fn func(stuff: []const u8) u32 {
global_frame = @frame();
var sum: u32 = 0;
for (stuff) |x| {
suspend;
sum += x;
}
global_frame = null;
return sum;
}
};
S.doTheTest();
}
test "suspend in while loop" {
const S = struct {
var global_frame: ?anyframe = null;
fn doTheTest() void {
_ = async atest();
while (global_frame) |f| resume f;
}
fn atest() void {
expect(optional(6) == 6);
expect(errunion(6) == 6);
}
fn optional(stuff: ?u32) u32 {
global_frame = @frame();
defer global_frame = null;
while (stuff) |val| {
suspend;
return val;
}
return 0;
}
fn errunion(stuff: anyerror!u32) u32 {
global_frame = @frame();
defer global_frame = null;
while (stuff) |val| {
suspend;
return val;
} else |err| {
return 0;
}
}
};
S.doTheTest();
}
test "correctly spill when returning the error union result of another async fn" {
const S = struct {
var global_frame: anyframe = undefined;
fn doTheTest() void {
expect((atest() catch unreachable) == 1234);
}
fn atest() !i32 {
return fallible1();
}
fn fallible1() anyerror!i32 {
suspend {
global_frame = @frame();
}
return 1234;
}
};
_ = async S.doTheTest();
resume S.global_frame;
}
test "spill target expr in a for loop" {
const S = struct {
var global_frame: anyframe = undefined;
fn doTheTest() void {
var foo = Foo{
.slice = &[_]i32{ 1, 2 },
};
expect(atest(&foo) == 3);
}
const Foo = struct {
slice: []const i32,
};
fn atest(foo: *Foo) i32 {
var sum: i32 = 0;
for (foo.slice) |x| {
suspend {
global_frame = @frame();
}
sum += x;
}
return sum;
}
};
_ = async S.doTheTest();
resume S.global_frame;
resume S.global_frame;
}
test "spill target expr in a for loop, with a var decl in the loop body" {
const S = struct {
var global_frame: anyframe = undefined;
fn doTheTest() void {
var foo = Foo{
.slice = &[_]i32{ 1, 2 },
};
expect(atest(&foo) == 3);
}
const Foo = struct {
slice: []const i32,
};
fn atest(foo: *Foo) i32 {
var sum: i32 = 0;
for (foo.slice) |x| {
// Previously this var decl would prevent spills. This test makes sure
// the for loop spills still happen even though there is a VarDecl in scope
// before the suspend.
var anything = true;
_ = anything;
suspend {
global_frame = @frame();
}
sum += x;
}
return sum;
}
};
_ = async S.doTheTest();
resume S.global_frame;
resume S.global_frame;
}
test "async call with @call" {
const S = struct {
var global_frame: anyframe = undefined;
fn doTheTest() void {
_ = @call(.{ .modifier = .async_kw }, atest, .{});
resume global_frame;
}
fn atest() void {
var frame = @call(.{ .modifier = .async_kw }, afoo, .{});
const res = await frame;
expect(res == 42);
}
fn afoo() i32 {
suspend {
global_frame = @frame();
}
return 42;
}
};
S.doTheTest();
}
test "async function passed 0-bit arg after non-0-bit arg" {
const S = struct {
var global_frame: anyframe = undefined;
var global_int: i32 = 0;
fn foo() void {
bar(1, .{}) catch unreachable;
}
fn bar(x: i32, args: var) anyerror!void {
global_frame = @frame();
suspend;
global_int = x;
}
};
_ = async S.foo();
resume S.global_frame;
expect(S.global_int == 1);
}
test "async function passed align(16) arg after align(8) arg" {
const S = struct {
var global_frame: anyframe = undefined;
var global_int: u128 = 0;
fn foo() void {
var a: u128 = 99;
bar(10, .{a}) catch unreachable;
}
fn bar(x: u64, args: var) anyerror!void {
expect(x == 10);
global_frame = @frame();
suspend;
global_int = args[0];
}
};
_ = async S.foo();
resume S.global_frame;
expect(S.global_int == 99);
}
test "async function call resolves target fn frame, comptime func" {
const S = struct {
var global_frame: anyframe = undefined;
var global_int: i32 = 9;
fn foo() anyerror!void {
const stack_size = 1000;
var stack_frame: [stack_size]u8 align(std.Target.stack_align) = undefined;
return await @asyncCall(&stack_frame, {}, bar);
}
fn bar() anyerror!void {
global_frame = @frame();
suspend;
global_int += 1;
}
};
_ = async S.foo();
resume S.global_frame;
expect(S.global_int == 10);
}
test "async function call resolves target fn frame, runtime func" {
const S = struct {
var global_frame: anyframe = undefined;
var global_int: i32 = 9;
fn foo() anyerror!void {
const stack_size = 1000;
var stack_frame: [stack_size]u8 align(std.Target.stack_align) = undefined;
var func: async fn () anyerror!void = bar;
return await @asyncCall(&stack_frame, {}, func);
}
fn bar() anyerror!void {
global_frame = @frame();
suspend;
global_int += 1;
}
};
_ = async S.foo();
resume S.global_frame;
expect(S.global_int == 10);
}
test "properly spill optional payload capture value" {
const S = struct {
var global_frame: anyframe = undefined;
var global_int: usize = 2;
fn foo() void {
var opt: ?usize = 1234;
if (opt) |x| {
bar();
global_int += x;
}
}
fn bar() void {
global_frame = @frame();
suspend;
global_int += 1;
}
};
_ = async S.foo();
resume S.global_frame;
expect(S.global_int == 1237);
}
test "handle defer interfering with return value spill" {
const S = struct {
var global_frame1: anyframe = undefined;
var global_frame2: anyframe = undefined;
var finished = false;
var baz_happened = false;
fn doTheTest() void {
_ = async testFoo();
resume global_frame1;
resume global_frame2;
expect(baz_happened);
expect(finished);
}
fn testFoo() void {
expectError(error.Bad, foo());
finished = true;
}
fn foo() anyerror!void {
defer baz();
return bar() catch |err| return err;
}
fn bar() anyerror!void {
global_frame1 = @frame();
suspend;
return error.Bad;
}
fn baz() void {
global_frame2 = @frame();
suspend;
baz_happened = true;
}
};
S.doTheTest();
}
test "take address of temporary async frame" {
const S = struct {
var global_frame: anyframe = undefined;
var finished = false;
fn doTheTest() void {
_ = async asyncDoTheTest();
resume global_frame;
expect(finished);
}
fn asyncDoTheTest() void {
expect(finishIt(&async foo(10)) == 1245);
finished = true;
}
fn foo(arg: i32) i32 {
global_frame = @frame();
suspend;
return arg + 1234;
}
fn finishIt(frame: anyframe->i32) i32 {
return (await frame) + 1;
}
};
S.doTheTest();
}
test "nosuspend await" {
const S = struct {
var finished = false;
fn doTheTest() void {
var frame = async foo(false);
expect(nosuspend await frame == 42);
finished = true;
}
fn foo(want_suspend: bool) i32 {
if (want_suspend) {
suspend;
}
return 42;
}
};
S.doTheTest();
expect(S.finished);
}
test "nosuspend on function calls" {
const S0 = struct {
b: i32 = 42,
};
const S1 = struct {
fn c() S0 {
return S0{};
}
fn d() !S0 {
return S0{};
}
};
expectEqual(@as(i32, 42), nosuspend S1.c().b);
expectEqual(@as(i32, 42), (try nosuspend S1.d()).b);
}
test "avoid forcing frame alignment resolution implicit cast to *c_void" {
const S = struct {
var x: ?*c_void = null;
fn foo() bool {
suspend {
x = @frame();
}
return true;
}
};
var frame = async S.foo();
resume @ptrCast(anyframe->bool, @alignCast(@alignOf(@Frame(S.foo)), S.x));
expect(nosuspend await frame);
} | test/stage1/behavior/async_fn.zig |
const std = @import("std");
const expect = std.testing.expect;
const Value = union(enum) {
Int: u64,
Array: [9]u8,
};
const Agg = struct {
val1: Value,
val2: Value,
};
const v1 = Value{ .Int = 1234 };
const v2 = Value{ .Array = [_]u8{3} ** 9 };
const err = @as(anyerror!Agg, Agg{
.val1 = v1,
.val2 = v2,
});
const array = [_]Value{
v1,
v2,
v1,
v2,
};
test "unions embedded in aggregate types" {
switch (array[1]) {
Value.Array => |arr| expect(arr[4] == 3),
else => unreachable,
}
switch ((err catch unreachable).val1) {
Value.Int => |x| expect(x == 1234),
else => unreachable,
}
}
const Foo = union {
float: f64,
int: i32,
};
test "basic unions" {
var foo = Foo{ .int = 1 };
expect(foo.int == 1);
foo = Foo{ .float = 12.34 };
expect(foo.float == 12.34);
}
test "comptime union field access" {
comptime {
var foo = Foo{ .int = 0 };
expect(foo.int == 0);
foo = Foo{ .float = 42.42 };
expect(foo.float == 42.42);
}
}
test "init union with runtime value" {
var foo: Foo = undefined;
setFloat(&foo, 12.34);
expect(foo.float == 12.34);
setInt(&foo, 42);
expect(foo.int == 42);
}
fn setFloat(foo: *Foo, x: f64) void {
foo.* = Foo{ .float = x };
}
fn setInt(foo: *Foo, x: i32) void {
foo.* = Foo{ .int = x };
}
const FooExtern = extern union {
float: f64,
int: i32,
};
test "basic extern unions" {
var foo = FooExtern{ .int = 1 };
expect(foo.int == 1);
foo.float = 12.34;
expect(foo.float == 12.34);
}
const Letter = enum {
A,
B,
C,
};
const Payload = union(Letter) {
A: i32,
B: f64,
C: bool,
};
test "union with specified enum tag" {
doTest();
comptime doTest();
}
fn doTest() void {
expect(bar(Payload{ .A = 1234 }) == -10);
}
fn bar(value: Payload) i32 {
expect(@as(Letter, value) == Letter.A);
return switch (value) {
Payload.A => |x| return x - 1244,
Payload.B => |x| if (x == 12.34) @as(i32, 20) else 21,
Payload.C => |x| if (x) @as(i32, 30) else 31,
};
}
const MultipleChoice = union(enum(u32)) {
A = 20,
B = 40,
C = 60,
D = 1000,
};
test "simple union(enum(u32))" {
var x = MultipleChoice.C;
expect(x == MultipleChoice.C);
expect(@enumToInt(@as(@TagType(MultipleChoice), x)) == 60);
}
const MultipleChoice2 = union(enum(u32)) {
Unspecified1: i32,
A: f32 = 20,
Unspecified2: void,
B: bool = 40,
Unspecified3: i32,
C: i8 = 60,
Unspecified4: void,
D: void = 1000,
Unspecified5: i32,
};
test "union(enum(u32)) with specified and unspecified tag values" {
comptime expect(@TagType(@TagType(MultipleChoice2)) == u32);
testEnumWithSpecifiedAndUnspecifiedTagValues(MultipleChoice2{ .C = 123 });
comptime testEnumWithSpecifiedAndUnspecifiedTagValues(MultipleChoice2{ .C = 123 });
}
fn testEnumWithSpecifiedAndUnspecifiedTagValues(x: MultipleChoice2) void {
expect(@enumToInt(@as(@TagType(MultipleChoice2), x)) == 60);
expect(1123 == switch (x) {
MultipleChoice2.A => 1,
MultipleChoice2.B => 2,
MultipleChoice2.C => |v| @as(i32, 1000) + v,
MultipleChoice2.D => 4,
MultipleChoice2.Unspecified1 => 5,
MultipleChoice2.Unspecified2 => 6,
MultipleChoice2.Unspecified3 => 7,
MultipleChoice2.Unspecified4 => 8,
MultipleChoice2.Unspecified5 => 9,
});
}
const ExternPtrOrInt = extern union {
ptr: *u8,
int: u64,
};
test "extern union size" {
comptime expect(@sizeOf(ExternPtrOrInt) == 8);
}
const PackedPtrOrInt = packed union {
ptr: *u8,
int: u64,
};
test "extern union size" {
comptime expect(@sizeOf(PackedPtrOrInt) == 8);
}
const ZeroBits = union {
OnlyField: void,
};
test "union with only 1 field which is void should be zero bits" {
comptime expect(@sizeOf(ZeroBits) == 0);
}
const TheTag = enum {
A,
B,
C,
};
const TheUnion = union(TheTag) {
A: i32,
B: i32,
C: i32,
};
test "union field access gives the enum values" {
expect(TheUnion.A == TheTag.A);
expect(TheUnion.B == TheTag.B);
expect(TheUnion.C == TheTag.C);
}
test "cast union to tag type of union" {
testCastUnionToTagType(TheUnion{ .B = 1234 });
comptime testCastUnionToTagType(TheUnion{ .B = 1234 });
}
fn testCastUnionToTagType(x: TheUnion) void {
expect(@as(TheTag, x) == TheTag.B);
}
test "cast tag type of union to union" {
var x: Value2 = Letter2.B;
expect(@as(Letter2, x) == Letter2.B);
}
const Letter2 = enum {
A,
B,
C,
};
const Value2 = union(Letter2) {
A: i32,
B,
C,
};
test "implicit cast union to its tag type" {
var x: Value2 = Letter2.B;
expect(x == Letter2.B);
giveMeLetterB(x);
}
fn giveMeLetterB(x: Letter2) void {
expect(x == Value2.B);
}
pub const PackThis = union(enum) {
Invalid: bool,
StringLiteral: u2,
};
test "constant packed union" {
testConstPackedUnion(&[_]PackThis{PackThis{ .StringLiteral = 1 }});
}
fn testConstPackedUnion(expected_tokens: []const PackThis) void {
expect(expected_tokens[0].StringLiteral == 1);
}
test "switch on union with only 1 field" {
var r: PartialInst = undefined;
r = PartialInst.Compiled;
switch (r) {
PartialInst.Compiled => {
var z: PartialInstWithPayload = undefined;
z = PartialInstWithPayload{ .Compiled = 1234 };
switch (z) {
PartialInstWithPayload.Compiled => |x| {
expect(x == 1234);
return;
},
}
},
}
unreachable;
}
const PartialInst = union(enum) {
Compiled,
};
const PartialInstWithPayload = union(enum) {
Compiled: i32,
};
test "access a member of tagged union with conflicting enum tag name" {
const Bar = union(enum) {
A: A,
B: B,
const A = u8;
const B = void;
};
comptime expect(Bar.A == u8);
}
test "tagged union initialization with runtime void" {
expect(testTaggedUnionInit({}));
}
const TaggedUnionWithAVoid = union(enum) {
A,
B: i32,
};
fn testTaggedUnionInit(x: var) bool {
const y = TaggedUnionWithAVoid{ .A = x };
return @as(@TagType(TaggedUnionWithAVoid), y) == TaggedUnionWithAVoid.A;
}
pub const UnionEnumNoPayloads = union(enum) {
A,
B,
};
test "tagged union with no payloads" {
const a = UnionEnumNoPayloads{ .B = {} };
switch (a) {
@TagType(UnionEnumNoPayloads).A => @panic("wrong"),
@TagType(UnionEnumNoPayloads).B => {},
}
}
test "union with only 1 field casted to its enum type" {
const Literal = union(enum) {
Number: f64,
Bool: bool,
};
const Expr = union(enum) {
Literal: Literal,
};
var e = Expr{ .Literal = Literal{ .Bool = true } };
const Tag = @TagType(Expr);
comptime expect(@TagType(Tag) == u0);
var t = @as(Tag, e);
expect(t == Expr.Literal);
}
test "union with only 1 field casted to its enum type which has enum value specified" {
const Literal = union(enum) {
Number: f64,
Bool: bool,
};
const Tag = enum(comptime_int) {
Literal = 33,
};
const Expr = union(Tag) {
Literal: Literal,
};
var e = Expr{ .Literal = Literal{ .Bool = true } };
comptime expect(@TagType(Tag) == comptime_int);
var t = @as(Tag, e);
expect(t == Expr.Literal);
expect(@enumToInt(t) == 33);
comptime expect(@enumToInt(t) == 33);
}
test "@enumToInt works on unions" {
const Bar = union(enum) {
A: bool,
B: u8,
C,
};
const a = Bar{ .A = true };
var b = Bar{ .B = undefined };
var c = Bar.C;
expect(@enumToInt(a) == 0);
expect(@enumToInt(b) == 1);
expect(@enumToInt(c) == 2);
}
const Attribute = union(enum) {
A: bool,
B: u8,
};
fn setAttribute(attr: Attribute) void {}
fn Setter(attr: Attribute) type {
return struct {
fn set() void {
setAttribute(attr);
}
};
}
test "comptime union field value equality" {
const a0 = Setter(Attribute{ .A = false });
const a1 = Setter(Attribute{ .A = true });
const a2 = Setter(Attribute{ .A = false });
const b0 = Setter(Attribute{ .B = 5 });
const b1 = Setter(Attribute{ .B = 9 });
const b2 = Setter(Attribute{ .B = 5 });
expect(a0 == a0);
expect(a1 == a1);
expect(a0 == a2);
expect(b0 == b0);
expect(b1 == b1);
expect(b0 == b2);
expect(a0 != b0);
expect(a0 != a1);
expect(b0 != b1);
}
test "return union init with void payload" {
const S = struct {
fn entry() void {
expect(func().state == State.one);
}
const Outer = union(enum) {
state: State,
};
const State = union(enum) {
one: void,
two: u32,
};
fn func() Outer {
return Outer{ .state = State{ .one = {} } };
}
};
S.entry();
comptime S.entry();
}
test "@unionInit can modify a union type" {
const UnionInitEnum = union(enum) {
Boolean: bool,
Byte: u8,
};
var value: UnionInitEnum = undefined;
value = @unionInit(UnionInitEnum, "Boolean", true);
expect(value.Boolean == true);
value.Boolean = false;
expect(value.Boolean == false);
value = @unionInit(UnionInitEnum, "Byte", 2);
expect(value.Byte == 2);
value.Byte = 3;
expect(value.Byte == 3);
}
test "@unionInit can modify a pointer value" {
const UnionInitEnum = union(enum) {
Boolean: bool,
Byte: u8,
};
var value: UnionInitEnum = undefined;
var value_ptr = &value;
value_ptr.* = @unionInit(UnionInitEnum, "Boolean", true);
expect(value.Boolean == true);
value_ptr.* = @unionInit(UnionInitEnum, "Byte", 2);
expect(value.Byte == 2);
}
test "union no tag with struct member" {
const Struct = struct {};
const Union = union {
s: Struct,
pub fn foo(self: *@This()) void {}
};
var u = Union{ .s = Struct{} };
u.foo();
}
fn testComparison() void {
var x = Payload{ .A = 42 };
expect(x == .A);
expect(x != .B);
expect(x != .C);
expect((x == .B) == false);
expect((x == .C) == false);
expect((x != .A) == false);
}
test "comparison between union and enum literal" {
testComparison();
comptime testComparison();
}
test "packed union generates correctly aligned LLVM type" {
const U = packed union {
f1: fn () void,
f2: u32,
};
var foo = [_]U{
U{ .f1 = doTest },
U{ .f2 = 0 },
};
foo[0].f1();
}
test "union with one member defaults to u0 tag type" {
const U0 = union(enum) {
X: u32,
};
comptime expect(@TagType(@TagType(U0)) == u0);
}
test "union with comptime_int tag" {
const Union = union(enum(comptime_int)) {
X: u32,
Y: u16,
Z: u8,
};
comptime expect(@TagType(@TagType(Union)) == comptime_int);
}
test "extern union doesn't trigger field check at comptime" {
const U = extern union {
x: u32,
y: u8,
};
const x = U{ .x = 0x55AAAA55 };
comptime expect(x.y == 0x55);
}
const Foo1 = union(enum) {
f: struct {
x: usize,
},
};
var glbl: Foo1 = undefined;
test "global union with single field is correctly initialized" {
glbl = Foo1{
.f = @memberType(Foo1, 0){ .x = 123 },
};
expect(glbl.f.x == 123);
}
pub const FooUnion = union(enum) {
U0: usize,
U1: u8,
};
var glbl_array: [2]FooUnion = undefined;
test "initialize global array of union" {
glbl_array[1] = FooUnion{ .U1 = 2 };
glbl_array[0] = FooUnion{ .U0 = 1 };
expect(glbl_array[0].U0 == 1);
expect(glbl_array[1].U1 == 2);
}
test "anonymous union literal syntax" {
const S = struct {
const Number = union {
int: i32,
float: f64,
};
fn doTheTest() void {
var i: Number = .{ .int = 42 };
var f = makeNumber();
expect(i.int == 42);
expect(f.float == 12.34);
}
fn makeNumber() Number {
return .{ .float = 12.34 };
}
};
S.doTheTest();
comptime S.doTheTest();
}
test "update the tag value for zero-sized unions" {
const S = union(enum) {
U0: void,
U1: void,
};
var x = S{ .U0 = {} };
expect(x == .U0);
x = S{ .U1 = {} };
expect(x == .U1);
}
test "function call result coerces from tagged union to the tag" {
const S = struct {
const Arch = union(enum) {
One,
Two: usize,
};
const ArchTag = @TagType(Arch);
fn doTheTest() void {
var x: ArchTag = getArch1();
expect(x == .One);
var y: ArchTag = getArch2();
expect(y == .Two);
}
pub fn getArch1() Arch {
return .One;
}
pub fn getArch2() Arch {
return .{ .Two = 99 };
}
};
S.doTheTest();
comptime S.doTheTest();
}
test "0-sized extern union definition" {
const U = extern union {
a: void,
const f = 1;
};
expect(U.f == 1);
} | test/stage1/behavior/union.zig |
const std = @import("std");
const json_std = @import("json/std.zig");
pub const path = @import("json/path.zig");
const log = std.log.scoped(.zCord);
const debug_buffer = std.builtin.mode == .Debug;
pub fn Formatter(comptime T: type) type {
return struct {
data: T,
pub fn format(self: @This(), comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
// TODO: convert stringify options
return std.json.stringify(self.data, .{ .string = .{ .String = .{} } }, writer);
}
};
}
pub fn format(data: anytype) Formatter(@TypeOf(data)) {
return .{ .data = data };
}
pub fn stream(reader: anytype) Stream(@TypeOf(reader)) {
return .{
.reader = reader,
.parser = json_std.StreamingParser.init(),
.element_number = 0,
.parse_failure = null,
._root = null,
._debug_cursor = null,
._debug_buffer = if (debug_buffer)
std.fifo.LinearFifo(u8, .{ .Static = 0x100 }).init()
else {},
};
}
pub fn Stream(comptime Reader: type) type {
return struct {
const Self = @This();
reader: Reader,
parser: json_std.StreamingParser,
element_number: usize,
parse_failure: ?ParseFailure,
_root: ?Element,
_debug_cursor: ?usize,
_debug_buffer: if (debug_buffer)
std.fifo.LinearFifo(u8, .{ .Static = 0x100 })
else
void,
const ParseFailure = union(enum) {
wrong_element: struct { wanted: ElementType, actual: ElementType },
};
const ElementType = enum { Object, Array, String, Number, Boolean, Null };
pub const Error = Reader.Error || ParseError;
pub const ParseError = json_std.StreamingParser.Error || error{
WrongElementType,
UnexpectedEndOfJson,
};
pub const Element = struct {
ctx: *Self,
kind: ElementType,
first_char: u8,
element_number: usize,
stack_level: u8,
fn init(ctx: *Self) Error!?Element {
ctx.assertState(&.{ .ValueBegin, .ValueBeginNoClosing, .TopLevelBegin });
const start_state = ctx.parser.state;
var byte: u8 = undefined;
const kind: ElementType = blk: {
while (true) {
byte = try ctx.nextByte();
if (try ctx.feed(byte)) |token| {
switch (token) {
.ArrayBegin => break :blk .Array,
.ObjectBegin => break :blk .Object,
.ArrayEnd, .ObjectEnd => return null,
else => ctx.assertFailure("Element unrecognized: {}", .{token}),
}
}
if (ctx.parser.state != start_state) {
switch (ctx.parser.state) {
.String => break :blk .String,
.Number, .NumberMaybeDotOrExponent, .NumberMaybeDigitOrDotOrExponent => break :blk .Number,
.TrueLiteral1, .FalseLiteral1 => break :blk .Boolean,
.NullLiteral1 => break :blk .Null,
else => ctx.assertFailure("Element unrecognized: {}", .{ctx.parser.state}),
}
}
}
};
ctx.element_number += 1;
return Element{
.ctx = ctx,
.kind = kind,
.first_char = byte,
.element_number = ctx.element_number,
.stack_level = ctx.parser.stack_used,
};
}
pub fn boolean(self: Element) Error!bool {
try self.validateType(.Boolean);
self.ctx.assertState(&.{ .TrueLiteral1, .FalseLiteral1 });
switch ((try self.finalizeToken()).?) {
.True => return true,
.False => return false,
else => unreachable,
}
}
pub fn optionalBoolean(self: Element) Error!?bool {
if (try self.checkOptional()) {
return null;
} else {
return try self.boolean();
}
}
pub fn optionalNumber(self: Element, comptime T: type) !?T {
if (try self.checkOptional()) {
return null;
} else {
return try self.number(T);
}
}
pub fn number(self: Element, comptime T: type) !T {
try self.validateType(.Number);
switch (@typeInfo(T)) {
.Int => {
// +1 for converting floor -> ceil
// +1 for negative sign
// +1 for simplifying terminating character detection
const max_digits = std.math.log10(std.math.maxInt(T)) + 3;
var buffer: [max_digits]u8 = undefined;
return try std.fmt.parseInt(T, try self.numberBuffer(&buffer), 10);
},
.Float => {
const max_digits = 0x1000; // Yeah this is a total kludge, but floats are hard. :(
var buffer: [max_digits]u8 = undefined;
return try std.fmt.parseFloat(T, try self.numberBuffer(&buffer));
},
else => @compileError("Unsupported number type '" ++ @typeName(T) ++ "'"),
}
}
fn numberBuffer(self: Element, buffer: []u8) (Error || error{Overflow})![]u8 {
// Handle first byte manually
buffer[0] = self.first_char;
for (buffer[1..]) |*c, i| {
const byte = try self.ctx.nextByte();
if (try self.ctx.feed(byte)) |token| {
const len = i + 1;
self.ctx.assert(token == .Number);
self.ctx.assert(token.Number.count == len);
return buffer[0..len];
} else {
c.* = byte;
}
}
return error.Overflow;
}
pub fn stringBuffer(self: Element, buffer: []u8) (Error || error{StreamTooLong})![]u8 {
const reader = try self.stringReader();
const size = try reader.readAll(buffer);
if (size == buffer.len) {
if (reader.readByte()) |_| {
return error.StreamTooLong;
} else |err| switch (err) {
error.EndOfStream => {},
else => |e| return e,
}
}
return buffer[0..size];
}
const StringReader = std.io.Reader(
Element,
Error,
(struct {
fn read(self: Element, buffer: []u8) Error!usize {
if (self.ctx.parser.state == .ValueEnd or self.ctx.parser.state == .TopLevelEnd) {
return 0;
}
var i: usize = 0;
while (i < buffer.len) : (i += 1) {
const byte = try self.ctx.nextByte();
if (try self.ctx.feed(byte)) |token| {
self.ctx.assert(token == .String);
return i;
} else if (byte == '\\') {
const next = try self.ctx.nextByte();
self.ctx.assert((try self.ctx.feed(next)) == null);
buffer[i] = switch (next) {
'"' => '"',
'/' => '/',
'\\' => '\\',
'n' => '\n',
'r' => '\r',
't' => '\t',
'b' => 0x08, // backspace
'f' => 0x0C, // form feed
'u' => {
var hexes: [4]u8 = undefined;
for (hexes) |*hex| {
hex.* = try self.ctx.nextByte();
self.ctx.assert((try self.ctx.feed(hex.*)) == null);
}
const MASK = 0b111111;
const charpoint = std.fmt.parseInt(u16, &hexes, 16) catch unreachable;
switch (charpoint) {
0...0x7F => buffer[i] = @intCast(u8, charpoint),
0x80...0x07FF => {
buffer[i] = 0xC0 | @intCast(u8, charpoint >> 6);
i += 1;
buffer[i] = 0x80 | @intCast(u8, charpoint & MASK);
},
0x0800...0xFFFF => {
buffer[i] = 0xE0 | @intCast(u8, charpoint >> 12);
i += 1;
buffer[i] = 0x80 | @intCast(u8, charpoint >> 6 & MASK);
i += 1;
buffer[i] = 0x80 | @intCast(u8, charpoint & MASK);
},
}
continue;
},
// should have been handled by the internal parser
else => unreachable,
};
} else {
buffer[i] = byte;
}
}
return buffer.len;
}
}).read,
);
pub fn stringReader(self: Element) Error!StringReader {
try self.validateType(.String);
return StringReader{ .context = self };
}
pub fn optionalStringReader(self: Element) Error!?StringReader {
if (try self.checkOptional()) {
return null;
} else {
return try self.stringReader();
}
}
pub fn optionalStringBuffer(self: Element, buffer: []u8) (Error || error{StreamTooLong})!?[]u8 {
if (try self.checkOptional()) {
return null;
} else {
return try self.stringBuffer(buffer);
}
}
pub fn arrayNext(self: Element) Error!?Element {
try self.validateType(.Array);
// This array has been closed out.
// TODO: evaluate to see if this is actually robust
if (self.ctx.parser.stack_used < self.stack_level) {
return null;
}
// Scan for next element
while (self.ctx.parser.state == .ValueEnd) {
if (try self.ctx.feed(try self.ctx.nextByte())) |token| {
self.ctx.assert(token == .ArrayEnd);
return null;
}
}
return try Element.init(self.ctx);
}
fn ObjectMatchUnion(comptime TagType: type) type {
comptime var union_fields: []const std.builtin.TypeInfo.UnionField = &.{};
inline for (std.meta.fields(TagType)) |field| {
union_fields = union_fields ++ [_]std.builtin.TypeInfo.UnionField{.{
.name = field.name,
.field_type = Element,
.alignment = @alignOf(Element),
}};
}
const Tagged = union(enum) { temp };
var info = @typeInfo(Tagged);
info.Union.tag_type = TagType;
info.Union.fields = union_fields;
return @Type(info);
}
pub fn objectMatch(self: Element, comptime Enum: type) !?ObjectMatchUnion(Enum) {
comptime var string_keys: []const []const u8 = &.{};
inline for (std.meta.fields(Enum)) |field| {
string_keys = string_keys ++ [_][]const u8{field.name};
}
const raw_match = (try self.objectMatchAny(string_keys)) orelse return null;
inline for (string_keys) |key| {
if (std.mem.eql(u8, key, raw_match.key)) {
return @unionInit(ObjectMatchUnion(Enum), key, raw_match.value);
}
}
unreachable;
}
const ObjectMatchString = struct {
key: []const u8,
value: Element,
};
pub fn objectMatchOne(self: Element, key: []const u8) Error!?ObjectMatchString {
return self.objectMatchAny(&[_][]const u8{key});
}
pub fn objectMatchAny(self: Element, keys: []const []const u8) Error!?ObjectMatchString {
try self.validateType(.Object);
while (true) {
// This object has been closed out.
// TODO: evaluate to see if this is actually robust
if (self.ctx.parser.stack_used < self.stack_level) {
return null;
}
// Scan for next element
while (self.ctx.parser.state == .ValueEnd) {
if (try self.ctx.feed(try self.ctx.nextByte())) |token| {
self.ctx.assert(token == .ObjectEnd);
return null;
}
}
const key_element = (try Element.init(self.ctx)) orelse return null;
self.ctx.assert(key_element.kind == .String);
const key_match = try key_element.stringFind(keys);
// Skip over the colon
while (self.ctx.parser.state == .ObjectSeparator) {
_ = try self.ctx.feed(try self.ctx.nextByte());
}
if (key_match) |key| {
// Match detected
return ObjectMatchString{
.key = key,
.value = (try Element.init(self.ctx)).?,
};
} else {
// Skip over value
const value_element = (try Element.init(self.ctx)).?;
_ = try value_element.finalizeToken();
}
}
}
fn stringFind(self: Element, checks: []const []const u8) !?[]const u8 {
self.ctx.assert(self.kind == .String);
var last_byte: u8 = undefined;
var prev_match: []const u8 = &[0]u8{};
var tail: usize = 0;
var string_complete = false;
for (checks) |check| {
if (string_complete and std.mem.eql(u8, check, prev_match[0 .. tail - 1])) {
return check;
}
if (tail >= 2 and !std.mem.eql(u8, check[0 .. tail - 2], prev_match[0 .. tail - 2])) {
continue;
}
if (tail >= 1 and (tail - 1 >= check.len or check[tail - 1] != last_byte)) {
continue;
}
prev_match = check;
while (!string_complete and tail <= check.len and
(tail < 1 or check[tail - 1] == last_byte)) : (tail += 1)
{
last_byte = try self.ctx.nextByte();
if (try self.ctx.feed(last_byte)) |token| {
self.ctx.assert(token == .String);
string_complete = true;
if (tail == check.len) {
return check;
}
}
}
}
if (!string_complete) {
const token = try self.finalizeToken();
self.ctx.assert(token.? == .String);
}
return null;
}
fn checkOptional(self: Element) !bool {
if (self.kind != .Null) return false;
self.ctx.assertState(&.{.NullLiteral1});
_ = try self.finalizeToken();
return true;
}
fn validateType(self: Element, wanted: ElementType) error{WrongElementType}!void {
if (self.kind != wanted) {
self.ctx.parse_failure = ParseFailure{
.wrong_element = .{ .wanted = wanted, .actual = self.kind },
};
return error.WrongElementType;
}
}
/// Dump the rest of this element into a writer.
/// Warning: this consumes the stream contents.
pub fn debugDump(self: Element, writer: anytype) !void {
const Context = struct {
element: Element,
writer: @TypeOf(writer),
pub fn feed(s: @This(), byte: u8) !?json_std.Token {
try s.writer.writeByte(byte);
return try s.element.ctx.feed(byte);
}
};
_ = try self.finalizeTokenWithCustomFeeder(Context{ .element = self, .writer = writer });
}
pub fn finalizeToken(self: Element) Error!?json_std.Token {
return self.finalizeTokenWithCustomFeeder(self.ctx);
}
fn finalizeTokenWithCustomFeeder(self: Element, feeder: anytype) !?json_std.Token {
switch (self.kind) {
.Boolean, .Null, .Number, .String => {
self.ctx.assert(self.element_number == self.ctx.element_number);
switch (self.ctx.parser.state) {
.ValueEnd, .TopLevelEnd, .ValueBeginNoClosing => return null,
else => {},
}
},
.Array, .Object => {
if (self.ctx.parser.stack_used == self.stack_level - 1) {
// Assert the parser state
return null;
} else {
self.ctx.assert(self.ctx.parser.stack_used >= self.stack_level);
}
},
}
while (true) {
const byte = try self.ctx.nextByte();
if (try feeder.feed(byte)) |token| {
switch (self.kind) {
.Boolean => self.ctx.assert(token == .True or token == .False),
.Null => self.ctx.assert(token == .Null),
.Number => self.ctx.assert(token == .Number),
.String => self.ctx.assert(token == .String),
.Array => {
if (self.ctx.parser.stack_used >= self.stack_level) {
continue;
}
// Number followed by ArrayEnd generates two tokens at once
// causing raw token assertion to be unreliable.
self.ctx.assert(byte == ']');
return .ArrayEnd;
},
.Object => {
if (self.ctx.parser.stack_used >= self.stack_level) {
continue;
}
// Number followed by ObjectEnd generates two tokens at once
// causing raw token assertion to be unreliable.
self.ctx.assert(byte == '}');
return .ObjectEnd;
},
}
return token;
}
}
}
};
pub fn root(self: *Self) Error!Element {
if (self._root == null) {
self._root = (try Element.init(self)).?;
}
return self._root.?;
}
fn assertState(ctx: *Self, valids: []const json_std.StreamingParser.State) void {
for (valids) |valid| {
if (ctx.parser.state == valid) {
return;
}
}
ctx.assertFailure("Unexpected state: {s}", .{ctx.parser.state});
}
fn assert(ctx: *Self, cond: bool) void {
if (!cond) {
std.debug.print("{}", ctx.debugInfo());
unreachable;
}
}
fn assertFailure(ctx: *Self, comptime fmt: []const u8, args: anytype) void {
if (std.debug.runtime_safety) {
std.debug.print("{}", ctx.debugInfo());
var buffer: [0x1000]u8 = undefined;
@panic(std.fmt.bufPrint(&buffer, fmt, args) catch &buffer);
}
}
const DebugInfo = struct {
ctx: *Self,
pub fn format(self: DebugInfo, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
if (debug_buffer) {
if (self.ctx._debug_cursor == null) {
self.ctx._debug_cursor = 0;
var i: usize = 0;
while (self.ctx.nextByte()) |byte| {
i += 1;
if (i > 30) break;
switch (byte) {
'"', ',', ' ', '\t', '\n' => {
self.ctx._debug_buffer.count -= 1;
break;
},
else => {},
}
} else |err| {}
}
var copy = self.ctx._debug_buffer;
const reader = copy.reader();
var buf: [0x100]u8 = undefined;
const size = try reader.read(&buf);
try writer.writeAll(buf[0..size]);
try writer.writeByte('\n');
}
if (self.ctx.parse_failure) |parse_failure| switch (parse_failure) {
.wrong_element => |wrong_element| {
try writer.print("WrongElementType - wanted: {s}", .{@tagName(wrong_element.wanted)});
},
};
}
};
pub fn debugInfo(ctx: *Self) DebugInfo {
return .{ .ctx = ctx };
}
fn nextByte(ctx: *Self) Error!u8 {
const byte = ctx.reader.readByte() catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfJson,
else => |e| return e,
};
if (debug_buffer) {
if (ctx._debug_buffer.writableLength() == 0) {
ctx._debug_buffer.discard(1);
std.debug.assert(ctx._debug_buffer.writableLength() == 1);
}
ctx._debug_buffer.writeAssumeCapacity(&[_]u8{byte});
}
return byte;
}
// A simpler feed() to enable one liners.
// token2 can only be close object/array and we don't need it
fn feed(ctx: *Self, byte: u8) !?json_std.Token {
var token1: ?json_std.Token = undefined;
var token2: ?json_std.Token = undefined;
try ctx.parser.feed(byte, &token1, &token2);
return token1;
}
};
}
fn expectEqual(actual: anytype, expected: ExpectedType(@TypeOf(actual))) void {
std.testing.expectEqual(expected, actual);
}
fn ExpectedType(comptime ActualType: type) type {
if (@typeInfo(ActualType) == .Union) {
return std.meta.Tag(ActualType);
} else {
return ActualType;
}
}
test "boolean" {
var fbs = std.io.fixedBufferStream("[true]");
var str = stream(fbs.reader());
const root = try str.root();
const element = (try root.arrayNext()).?;
expectEqual(element.kind, .Boolean);
expectEqual(try element.boolean(), true);
}
test "null" {
var fbs = std.io.fixedBufferStream("[null]");
var str = stream(fbs.reader());
const root = try str.root();
const element = (try root.arrayNext()).?;
expectEqual(element.kind, .Null);
expectEqual(try element.optionalBoolean(), null);
}
test "integer" {
{
var fbs = std.io.fixedBufferStream("[1]");
var str = stream(fbs.reader());
const root = try str.root();
const element = (try root.arrayNext()).?;
expectEqual(element.kind, .Number);
expectEqual(try element.number(u8), 1);
}
{
// Technically invalid, but we don't str far enough to find out
var fbs = std.io.fixedBufferStream("[123,]");
var str = stream(fbs.reader());
const root = try str.root();
const element = (try root.arrayNext()).?;
expectEqual(element.kind, .Number);
expectEqual(try element.number(u8), 123);
}
{
var fbs = std.io.fixedBufferStream("[-128]");
var str = stream(fbs.reader());
const root = try str.root();
const element = (try root.arrayNext()).?;
expectEqual(element.kind, .Number);
expectEqual(try element.number(i8), -128);
}
{
var fbs = std.io.fixedBufferStream("[456]");
var str = stream(fbs.reader());
const root = try str.root();
const element = (try root.arrayNext()).?;
expectEqual(element.kind, .Number);
expectEqual(element.number(u8), error.Overflow);
}
}
test "float" {
{
var fbs = std.io.fixedBufferStream("[1.125]");
var str = stream(fbs.reader());
const root = try str.root();
const element = (try root.arrayNext()).?;
expectEqual(element.kind, .Number);
expectEqual(try element.number(f32), 1.125);
}
{
// Technically invalid, but we don't str far enough to find out
var fbs = std.io.fixedBufferStream("[2.5,]");
var str = stream(fbs.reader());
const root = try str.root();
const element = (try root.arrayNext()).?;
expectEqual(element.kind, .Number);
expectEqual(try element.number(f64), 2.5);
}
{
var fbs = std.io.fixedBufferStream("[-1]");
var str = stream(fbs.reader());
const root = try str.root();
const element = (try root.arrayNext()).?;
expectEqual(element.kind, .Number);
expectEqual(try element.number(f64), -1);
}
{
var fbs = std.io.fixedBufferStream("[1e64]");
var str = stream(fbs.reader());
const root = try str.root();
const element = (try root.arrayNext()).?;
expectEqual(element.kind, .Number);
expectEqual(element.number(f64), 1e64);
}
}
test "string" {
{
var fbs = std.io.fixedBufferStream(
\\"hello world"
);
var str = stream(fbs.reader());
const element = try str.root();
expectEqual(element.kind, .String);
var buffer: [100]u8 = undefined;
std.testing.expectEqualStrings("hello world", try element.stringBuffer(&buffer));
}
}
test "string escapes" {
{
var fbs = std.io.fixedBufferStream(
\\"hello\nworld\t"
);
var str = stream(fbs.reader());
const element = try str.root();
expectEqual(element.kind, .String);
var buffer: [100]u8 = undefined;
std.testing.expectEqualStrings("hello\nworld\t", try element.stringBuffer(&buffer));
}
}
test "string unicode escape" {
{
var fbs = std.io.fixedBufferStream(
\\"\u0024"
);
var str = stream(fbs.reader());
const element = try str.root();
expectEqual(element.kind, .String);
var buffer: [100]u8 = undefined;
std.testing.expectEqualStrings("$", try element.stringBuffer(&buffer));
}
{
var fbs = std.io.fixedBufferStream(
\\"\u00A2"
);
var str = stream(fbs.reader());
const element = try str.root();
expectEqual(element.kind, .String);
var buffer: [100]u8 = undefined;
std.testing.expectEqualStrings("¢", try element.stringBuffer(&buffer));
}
{
var fbs = std.io.fixedBufferStream(
\\"\u0939"
);
var str = stream(fbs.reader());
const element = try str.root();
expectEqual(element.kind, .String);
var buffer: [100]u8 = undefined;
std.testing.expectEqualStrings("ह", try element.stringBuffer(&buffer));
}
{
var fbs = std.io.fixedBufferStream(
\\"\u20AC"
);
var str = stream(fbs.reader());
const element = try str.root();
expectEqual(element.kind, .String);
var buffer: [100]u8 = undefined;
std.testing.expectEqualStrings("€", try element.stringBuffer(&buffer));
}
{
var fbs = std.io.fixedBufferStream(
\\"\uD55C"
);
var str = stream(fbs.reader());
const element = try str.root();
expectEqual(element.kind, .String);
var buffer: [100]u8 = undefined;
std.testing.expectEqualStrings("한", try element.stringBuffer(&buffer));
}
}
test "empty array" {
var fbs = std.io.fixedBufferStream("[]");
var str = stream(fbs.reader());
const root = try str.root();
expectEqual(root.kind, .Array);
expectEqual(try root.arrayNext(), null);
}
test "array of simple values" {
var fbs = std.io.fixedBufferStream("[false, true, null]");
var str = stream(fbs.reader());
const root = try str.root();
expectEqual(root.kind, .Array);
if (try root.arrayNext()) |item| {
expectEqual(item.kind, .Boolean);
expectEqual(try item.boolean(), false);
} else {
std.debug.panic("Expected a value", .{});
}
if (try root.arrayNext()) |item| {
expectEqual(item.kind, .Boolean);
expectEqual(try item.boolean(), true);
} else {
std.debug.panic("Expected a value", .{});
}
if (try root.arrayNext()) |item| {
expectEqual(item.kind, .Null);
expectEqual(try item.optionalBoolean(), null);
} else {
std.debug.panic("Expected a value", .{});
}
expectEqual(try root.arrayNext(), null);
}
test "array of numbers" {
var fbs = std.io.fixedBufferStream("[1, 2, -3]");
var str = stream(fbs.reader());
const root = try str.root();
expectEqual(root.kind, .Array);
if (try root.arrayNext()) |item| {
expectEqual(item.kind, .Number);
expectEqual(try item.number(u8), 1);
} else {
std.debug.panic("Expected a value", .{});
}
if (try root.arrayNext()) |item| {
expectEqual(item.kind, .Number);
expectEqual(try item.number(u8), 2);
} else {
std.debug.panic("Expected a value", .{});
}
if (try root.arrayNext()) |item| {
expectEqual(item.kind, .Number);
expectEqual(try item.number(i8), -3);
} else {
std.debug.panic("Expected a value", .{});
}
expectEqual(try root.arrayNext(), null);
}
test "array of strings" {
var fbs = std.io.fixedBufferStream(
\\["hello", "world"]);
);
var str = stream(fbs.reader());
const root = try str.root();
expectEqual(root.kind, .Array);
if (try root.arrayNext()) |item| {
var buffer: [100]u8 = undefined;
expectEqual(item.kind, .String);
std.testing.expectEqualSlices(u8, "hello", try item.stringBuffer(&buffer));
} else {
std.debug.panic("Expected a value", .{});
}
if (try root.arrayNext()) |item| {
var buffer: [100]u8 = undefined;
expectEqual(item.kind, .String);
std.testing.expectEqualSlices(u8, "world", try item.stringBuffer(&buffer));
} else {
std.debug.panic("Expected a value", .{});
}
expectEqual(try root.arrayNext(), null);
}
test "array early finalize" {
var fbs = std.io.fixedBufferStream(
\\[1, 2, 3]
);
var str = stream(fbs.reader());
const root = try str.root();
while (try root.arrayNext()) |_| {
_ = try root.finalizeToken();
}
}
test "objects ending in number" {
var fbs = std.io.fixedBufferStream(
\\[{"id":0},{"id": 1}, {"id": 2}]
);
var str = stream(fbs.reader());
const root = try str.root();
while (try root.arrayNext()) |obj| {
if (try obj.objectMatchOne("banana")) |_| {
std.debug.panic("How did this match?", .{});
}
}
}
test "empty object" {
var fbs = std.io.fixedBufferStream("{}");
var str = stream(fbs.reader());
const root = try str.root();
expectEqual(root.kind, .Object);
expectEqual(try root.objectMatchOne(""), null);
}
test "object match" {
var fbs = std.io.fixedBufferStream(
\\{"foo": true, "bar": false}
);
var str = stream(fbs.reader());
const root = try str.root();
expectEqual(root.kind, .Object);
if (try root.objectMatchOne("foo")) |match| {
std.testing.expectEqualSlices(u8, "foo", match.key);
var buffer: [100]u8 = undefined;
expectEqual(match.value.kind, .Boolean);
expectEqual(try match.value.boolean(), true);
} else {
std.debug.panic("Expected a value", .{});
}
if (try root.objectMatchOne("bar")) |match| {
std.testing.expectEqualSlices(u8, "bar", match.key);
var buffer: [100]u8 = undefined;
expectEqual(match.value.kind, .Boolean);
expectEqual(try match.value.boolean(), false);
} else {
std.debug.panic("Expected a value", .{});
}
}
test "object match any" {
var fbs = std.io.fixedBufferStream(
\\{"foo": true, "foobar": false, "bar": null}
);
var str = stream(fbs.reader());
const root = try str.root();
expectEqual(root.kind, .Object);
if (try root.objectMatchAny(&[_][]const u8{ "foobar", "foo" })) |match| {
std.testing.expectEqualSlices(u8, "foo", match.key);
var buffer: [100]u8 = undefined;
expectEqual(match.value.kind, .Boolean);
expectEqual(try match.value.boolean(), true);
} else {
std.debug.panic("Expected a value", .{});
}
if (try root.objectMatchAny(&[_][]const u8{ "foo", "foobar" })) |match| {
std.testing.expectEqualSlices(u8, "foobar", match.key);
var buffer: [100]u8 = undefined;
expectEqual(match.value.kind, .Boolean);
expectEqual(try match.value.boolean(), false);
} else {
std.debug.panic("Expected a value", .{});
}
}
test "object match union" {
var fbs = std.io.fixedBufferStream(
\\{"foo": true, "foobar": false, "bar": null}
);
var str = stream(fbs.reader());
const root = try str.root();
expectEqual(root.kind, .Object);
if (try root.objectMatch(enum { foobar, foo })) |match| {
expectEqual(match.foo.kind, .Boolean);
expectEqual(try match.foo.boolean(), true);
} else {
std.debug.panic("Expected a value", .{});
}
if (try root.objectMatch(enum { foo, foobar })) |match| {
expectEqual(match.foobar.kind, .Boolean);
expectEqual(try match.foobar.boolean(), false);
} else {
std.debug.panic("Expected a value", .{});
}
}
test "object match not found" {
var fbs = std.io.fixedBufferStream(
\\{"foo": [[]], "bar": false, "baz": {}}
);
var str = stream(fbs.reader());
const root = try str.root();
expectEqual(root.kind, .Object);
expectEqual(try root.objectMatchOne("???"), null);
}
fn expectElement(e: anytype) Stream(std.io.FixedBufferStream([]const u8).Reader).Error!void {
switch (e.kind) {
// TODO: test objects better
.Object => _ = try e.finalizeToken(),
.Array => {
while (try e.arrayNext()) |child| {
try expectElement(child);
}
},
.String => _ = try e.finalizeToken(),
// TODO: fix inferred errors
// .Number => _ = try e.number(u64),
.Number => _ = try e.finalizeToken(),
.Boolean => _ = try e.boolean(),
.Null => _ = try e.optionalBoolean(),
}
}
fn expectValidParseOutput(input: []const u8) !void {
var fbs = std.io.fixedBufferStream(input);
var str = stream(fbs.reader());
const root = try str.root();
try expectElement(root);
}
test "smoke" {
try expectValidParseOutput(
\\[[], [], [[]], [[""], [], [[], 0], null], false]
);
}
test "finalizeToken on object" {
var fbs = std.io.fixedBufferStream("{}");
var str = stream(fbs.reader());
const root = try str.root();
expectEqual(root.kind, .Object);
expectEqual(try root.finalizeToken(), .ObjectEnd);
expectEqual(try root.finalizeToken(), null);
expectEqual(try root.finalizeToken(), null);
expectEqual(try root.finalizeToken(), null);
expectEqual(try root.finalizeToken(), null);
expectEqual(try root.finalizeToken(), null);
}
test "finalizeToken on string" {
var fbs = std.io.fixedBufferStream(
\\"foo"
);
var str = stream(fbs.reader());
const root = try str.root();
expectEqual(root.kind, .String);
std.testing.expect((try root.finalizeToken()).? == .String);
expectEqual(try root.finalizeToken(), null);
expectEqual(try root.finalizeToken(), null);
expectEqual(try root.finalizeToken(), null);
expectEqual(try root.finalizeToken(), null);
expectEqual(try root.finalizeToken(), null);
}
test "finalizeToken on number" {
var fbs = std.io.fixedBufferStream("[[1234,5678]]");
var str = stream(fbs.reader());
const root = try str.root();
expectEqual(root.kind, .Array);
const inner = (try root.arrayNext()).?;
expectEqual(inner.kind, .Array);
const first = (try inner.arrayNext()).?;
expectEqual(first.kind, .Number);
std.testing.expect((try first.finalizeToken()).? == .Number);
expectEqual(try first.finalizeToken(), null);
expectEqual(try first.finalizeToken(), null);
expectEqual(try first.finalizeToken(), null);
expectEqual(try first.finalizeToken(), null);
const second = (try inner.arrayNext()).?;
expectEqual(second.kind, .Number);
std.testing.expect((try second.finalizeToken()).? == .Number);
expectEqual(try second.finalizeToken(), null);
expectEqual(try second.finalizeToken(), null);
expectEqual(try second.finalizeToken(), null);
}
test {
std.testing.refAllDecls(@This());
} | src/json.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const sokol = @import("sokol/sokol.zig");
const sg = sokol.gfx;
const app = sokol.app;
usingnamespace @import("math.zig");
const Texture = @import("texture.zig").Texture;
const Vertex = @import("gfx.zig").Vertex;
const shader = @import("default.glsl.zig");
const tile_sz: f32 = 16.0;
// number of maximum sprites in a batch
const batch_sz: usize = 10;
// vertices needed for a single sprite
const single_sprite_vertices = 6;
// buffers size
const vubf_sz = batch_sz * single_sprite_vertices;
const vertices = [_]Vertex {
.{ .x = -0.5, .y = 0.5, .z = 0.5, .color = 0xff0000ff, .u = 0, .v = 1 },
.{ .x = 0.5, .y = 0.5, .z = 0.5, .color = 0x00ff00ff, .u = 1, .v = 1 },
.{ .x = 0.5, .y = -0.5, .z = 0.5, .color = 0x0000ffff, .u = 1, .v = 0 },
.{ .x = -0.5, .y = 0.5, .z = 0.5, .color = 0xff0000ff, .u = 0, .v = 1 },
.{ .x = 0.5, .y = -0.5, .z = 0.5, .color = 0x0000ffff, .u = 1, .v = 0 },
.{ .x = -0.5, .y = -0.5, .z = 0.5, .color = 0xffff00ff, .u = 0, .v = 0 },
};
pub const Sprite = struct {
texture: Texture,
pos: Vec2 = Vec2.zero(),
size: Vec2 = Vec2.new(tile_sz, tile_sz),
scale: Vec2 = Vec2.one(),
rotation: f32 = 0.0,
origin: Vec2 = Vec2.new(tile_sz / 2, tile_sz / 2),
texc: Vec2 = Vec2.zero(),
texsize: Vec2 = Vec2.one(),
};
pub const SpriteBatcher = struct {
allocator: *Allocator,
bind: sg.Bindings = .{},
pip: sg.Pipeline = .{},
pass_action: sg.PassAction = .{},
vbuf: [vubf_sz]Vertex = undefined,
batch: [batch_sz]Sprite = undefined,
sprite_count: u32 = 0,
pub fn init(sb: *SpriteBatcher) void {
// initialize pipeline
var pip_desc: sg.PipelineDesc = .{
.shader = sg.makeShader(shader.texcubeShaderDesc(sg.queryBackend())),
.cull_mode = .BACK
};
pip_desc.layout.attrs[shader.ATTR_vs_pos].format = .FLOAT3;
pip_desc.layout.attrs[shader.ATTR_vs_col].format = .UBYTE4N;
pip_desc.layout.attrs[shader.ATTR_vs_texc].format = .FLOAT2;
sb.pip = sg.makePipeline(pip_desc);
// set background color
sb.pass_action.colors[0] = .{
.action = .CLEAR,
.value = .{ .r=0.85, .g=0.25, .b=0.25, .a=1 }
};
// initialize the two buffers
sb.bind.vertex_buffers[0] = sg.makeBuffer(.{
.size = @sizeOf(@TypeOf(sb.vbuf)),
.usage = .STREAM,
});
}
pub fn addSprite(sb: *SpriteBatcher, spr: Sprite) void {
sb.batch[sb.sprite_count] = spr;
if(sb.sprite_count == sb.batch.len) {
sb.flush();
}
}
pub fn flush(sb: *SpriteBatcher) void {
for(sb.batch[0..sb.sprite_count]) |spr, i| {
const vindex = i * single_sprite_vertices;
sb.vbuf[vindex] = .{
};
}
sb.sprite_count = 0;
}
pub fn drawSprite(sb: *SpriteBatcher, spr: *Sprite) void {
// update buffer
sg.updateBuffer(sb.bind.vertex_buffers[0], sg.asRange(sb.vbuf));
// set texture
sb.bind.fs_images[shader.SLOT_tex].id = spr.texture.getId();
// 2d camera matrix
// s = scale
// o = rotation? (probably set to 0 for now)
// t = translation
// [ sx ox tx ]
// [ oy sy ty ]
// [ 0 0 1 ]
sg.beginDefaultPass(sb.pass_action, app.width(), app.height());
sg.applyPipeline(sb.pip);
sg.applyBindings(sb.bind);
sg.draw(0, vertices.len, 1);
sg.endPass();
sg.commit();
}
}; | src/sprite_batcher.zig |
const std = @import("std");
pub fn main() void {
// Take a good look at the array type to which we're coercing
// the zen12 string (the REAL nature of strings will be
// revealed when we've learned some additional features):
const zen12: *const [21]u8 = "Memory is a resource.";
//
// It would also have been valid to coerce to a slice:
// const zen12: []const u8 = "...";
//
// Now let's turn this into a "many-item pointer":
const zen_manyptr: [*]const u8 = zen12;
// It's okay to access zen_manyptr just like an array or slice as
// long as you keep track of the length yourself!
//
// A "string" in Zig is a pointer to an array of const u8 values
// (or a slice of const u8 values, as we saw above). So, we could
// treat a "many-item pointer" of const u8 as a string as long as
// we can CONVERT IT TO A SLICE. (Hint: we do know the length!)
//
// Please fix this line so the print below statement can print it:
const zen12_string: []const u8 = zen_manyptr;
// Here's the moment of truth!
std.debug.print("{s}\n", .{zen12_string});
}
//
// Are all of these pointer types starting to get confusing?
//
// FREE ZIG POINTER CHEATSHEET! (Using u8 as the example type.)
// +---------------+----------------------------------------------+
// | u8 | one u8 |
// | *u8 | pointer to one u8 |
// | [2]u8 | two u8s |
// | [*]u8 | pointer to unknown number of u8s |
// | [2]const u8 | two immutable u8s |
// | [*]const u8 | pointer to unknown number of immutable u8s |
// | *[2]u8 | pointer to an array of 2 u8s |
// | *const [2]u8 | pointer to an immutable array of 2 u8s |
// | []u8 | slice of u8s |
// | []const u8 | slice of immutable u8s |
// +---------------+----------------------------------------------+ | exercises/054_manypointers.zig |
const std = @import("std");
const fmt = std.fmt;
const testing = std.testing;
const P256 = @import("p256.zig").P256;
test "p256 ECDH key exchange" {
const dha = P256.scalar.random(.Little);
const dhb = P256.scalar.random(.Little);
const dhA = try P256.basePoint.mul(dha, .Little);
const dhB = try P256.basePoint.mul(dhb, .Little);
const shareda = try dhA.mul(dhb, .Little);
const sharedb = try dhB.mul(dha, .Little);
try testing.expect(shareda.equivalent(sharedb));
}
test "p256 point from affine coordinates" {
const xh = "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296";
const yh = "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5";
var xs: [32]u8 = undefined;
_ = try fmt.hexToBytes(&xs, xh);
var ys: [32]u8 = undefined;
_ = try fmt.hexToBytes(&ys, yh);
var p = try P256.fromSerializedAffineCoordinates(xs, ys, .Big);
try testing.expect(p.equivalent(P256.basePoint));
}
test "p256 test vectors" {
const expected = [_][]const u8{
"0000000000000000000000000000000000000000000000000000000000000000",
"6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296",
"<KEY>",
"5ecbe4d1a6330a44c8f7ef951d4bf165e6c6b721efada985fb41661bc6e7fd6c",
"e2534a3532d08fbba02dde659ee62bd0031fe2db785596ef509302446b030852",
"51590b7a515140d2d784c85608668fdfef8c82fd1f5be52421554a0dc3d033ed",
"<KEY>",
"<KEY>",
"62d9779dbee9b0534042742d3ab54cadc1d238980fce97dbb4dd9dc1db6fb393",
"ea68d7b6fedf0b71878938d51d71f8729e0acb8c2c6df8b3d79e8a4b90949ee0",
};
var p = P256.identityElement;
for (expected) |xh| {
const x = p.affineCoordinates().x;
p = p.add(P256.basePoint);
var xs: [32]u8 = undefined;
_ = try fmt.hexToBytes(&xs, xh);
try testing.expectEqualSlices(u8, &x.toBytes(.Big), &xs);
}
}
test "p256 test vectors - doubling" {
const expected = [_][]const u8{
"6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296",
"7cf27b188d034f7e8a52380304b51ac3c08969e277f21b35a60b48fc47669978",
"e2534a3532d08fbba02dde659ee62bd0031fe2db785596ef509302446b030852",
"<KEY>",
};
var p = P256.basePoint;
for (expected) |xh| {
const x = p.affineCoordinates().x;
p = p.dbl();
var xs: [32]u8 = undefined;
_ = try fmt.hexToBytes(&xs, xh);
try testing.expectEqualSlices(u8, &x.toBytes(.Big), &xs);
}
}
test "p256 compressed sec1 encoding/decoding" {
const p = P256.random();
const s = p.toCompressedSec1();
const q = try P256.fromSec1(&s);
try testing.expect(p.equivalent(q));
}
test "p256 uncompressed sec1 encoding/decoding" {
const p = P256.random();
const s = p.toUncompressedSec1();
const q = try P256.fromSec1(&s);
try testing.expect(p.equivalent(q));
}
test "p256 public key is the neutral element" {
const n = P256.scalar.Scalar.zero.toBytes(.Little);
const p = P256.random();
try testing.expectError(error.IdentityElement, p.mul(n, .Little));
}
test "p256 public key is the neutral element (public verification)" {
const n = P256.scalar.Scalar.zero.toBytes(.Little);
const p = P256.random();
try testing.expectError(error.IdentityElement, p.mulPublic(n, .Little));
}
test "p256 field element non-canonical encoding" {
const s = [_]u8{0xff} ** 32;
try testing.expectError(error.NonCanonical, P256.Fe.fromBytes(s, .Little));
}
test "p256 neutral element decoding" {
try testing.expectError(error.InvalidEncoding, P256.fromAffineCoordinates(.{ .x = P256.Fe.zero, .y = P256.Fe.zero }));
const p = try P256.fromAffineCoordinates(.{ .x = P256.Fe.zero, .y = P256.Fe.one });
try testing.expectError(error.IdentityElement, p.rejectIdentity());
} | lib/std/crypto/pcurves/tests.zig |
const c = @import("c.zig");
const nk = @import("../nuklear.zig");
const std = @import("std");
const mem = std.mem;
const testing = std.testing;
/// Same as `beginTitled` but instead of taking a `name` which the caller needs to ensure
/// is a unique string, this function generates a unique name for each unique type passed
/// to `id`.
pub fn begin(
ctx: *nk.Context,
comptime Id: type,
bounds: nk.Rect,
flags: nk.PanelFlags,
) ?*const nk.Window {
const id = nk.typeId(Id);
return beginTitled(ctx, mem.asBytes(&id), bounds, flags);
}
pub fn beginTitled(
ctx: *nk.Context,
name: []const u8,
bounds: nk.Rect,
flags: nk.PanelFlags,
) ?*const nk.Window {
const res = c.nk_begin_titled(
ctx,
nk.slice(name),
nk.slice(flags.title orelse ""),
bounds,
flags.toNuklear(),
);
if (res == 0)
return null;
return ctx.current;
}
pub fn end(ctx: *nk.Context) void {
c.nk_end(ctx);
}
pub fn find(ctx: *nk.Context, comptime Id: type) ?*const nk.Window {
const id = nk.typeId(Id);
return findByName(ctx, mem.asBytes(&id));
}
pub fn findByName(ctx: *nk.Context, name: []const u8) ?*const nk.Window {
return c.nk_window_find(ctx, nk.slice(name));
}
pub fn hasFocus(ctx: *nk.Context, win: *const nk.Window) bool {
return win == @as(*const nk.Window, ctx.active);
}
pub fn isHovered(ctx: *nk.Context, win: *const nk.Window) bool {
if ((win.flags & c.NK_WINDOW_HIDDEN) != 0)
return false;
return c.nk_input_is_mouse_hovering_rect(&ctx.input, win.bounds) != 0;
}
pub fn isAnyHovered(ctx: *nk.Context) bool {
return c.nk_window_is_any_hovered(ctx) != 0;
}
pub fn isAnyActive(ctx: *nk.Context) bool {
return c.nk_item_is_any_active(ctx) != 0;
}
test {
testing.refAllDecls(@This());
}
test "window" {
var ctx = &try nk.testing.init();
defer nk.free(ctx);
const Id = opaque {};
if (nk.window.begin(ctx, Id, nk.rect(10, 10, 10, 10), .{})) |win| {
try std.testing.expectEqual(@as(?*const nk.Window, win), nk.window.find(ctx, Id));
}
nk.window.end(ctx);
} | src/window.zig |
const std = @import("std");
//--------------------------------------------------------------------------------------------------
pub fn is_winning_board(board: [5][5]?u32) bool {
// Check if entire row is cleared
for (board) |row| {
var is_row_empty = true;
for (row) |cell| {
if (cell != null) {
is_row_empty = false;
break;
}
}
if (is_row_empty) {
return true;
}
}
// Check if entire column is cleared
var col_idx: u32 = 0;
while (col_idx < 5) : (col_idx += 1) {
var is_column_empty = true;
var row_idx: u32 = 0;
while (row_idx < 5) : (row_idx += 1) {
var cell = board[row_idx][col_idx];
if (cell != null) {
is_column_empty = false;
break;
}
}
if (is_column_empty) {
return true;
}
}
return false;
}
//--------------------------------------------------------------------------------------------------
pub fn unpack_board(input: [25]?u32) [5][5]?u32 {
var res: [5][5]?u32 = undefined;
var i: u32 = 0;
while (i < 25) : (i += 1) {
res[i / 5][i % 5] = input[i];
}
return res;
}
//--------------------------------------------------------------------------------------------------
pub fn remaining_sum(input: [25]?u32) u32 {
var res: u32 = 0;
var i: u32 = 0;
while (i < 25) : (i += 1) {
res += input[i] orelse 0;
}
return res;
}
//--------------------------------------------------------------------------------------------------
pub fn is_already_won(board_idx: usize, winners: []usize) bool {
for (winners) |idx| {
if (idx == board_idx) {
return true;
}
}
return false;
}
//--------------------------------------------------------------------------------------------------
pub fn part1() anyerror!void {
const file = std.fs.cwd().openFile("data/day04_input.txt", .{}) catch |err| label: {
std.debug.print("unable to open file: {e}\n", .{err});
const stderr = std.io.getStdErr();
break :label stderr;
};
defer file.close();
const file_size = try file.getEndPos();
std.log.info("File size {}", .{file_size});
var reader = std.io.bufferedReader(file.reader());
var istream = reader.reader();
var buf: [1024]u8 = undefined;
var line_count: u32 = 0;
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
var input = std.ArrayList(u32).init(allocator);
defer input.deinit();
//var card = std.ArrayList(?u32).init(allocator);
//defer card.deinit();
var cards = std.ArrayList([25]?u32).init(allocator);
defer cards.deinit();
var cur_values = [_]?u32{0} ** 25;
var cur_values_idx: u32 = 0;
while (try istream.readUntilDelimiterOrEof(&buf, '\n')) |line| {
//std.log.info("{s}", .{line});
// Store the input from the first line in input
if (line_count == 0) {
var it = std.mem.tokenize(u8, line, ", ");
while (it.next()) |value| {
input.append(std.fmt.parseInt(u32, value, 10) catch 0) catch unreachable;
//std.log.info("Value {d}", .{current_val});
}
std.log.info("ArrayList size {}", .{input.items.len});
} else if (line.len > 0) {
var it = std.mem.tokenize(u8, line, " ");
while (it.next()) |value| {
cur_values[cur_values_idx] = std.fmt.parseInt(u32, value, 10) catch 0;
cur_values_idx += 1;
if (cur_values_idx >= 25) {
cur_values_idx = 0;
try cards.append(cur_values);
}
//std.log.info("Value {d}", .{current_val});
}
}
line_count += 1;
}
//std.log.info("Cards {d}", .{cards.items});
//std.log.info("Cards size {}", .{cards.items.len});
var winners = std.ArrayList(usize).init(allocator);
defer winners.deinit();
for (input.items) |check_val| {
//std.log.info("Check {d}", .{check_val});
for (cards.items) |*card, card_idx| {
if (is_already_won(card_idx, winners.items)) {
continue;
}
for (card.*) |*val| {
if (check_val == val.* orelse null) {
val.* = null;
// Check if we are a winner
if (is_winning_board(unpack_board(card.*))) {
try winners.append(card_idx);
//if (num_winners = 1) {
var sum: u32 = remaining_sum(card.*);
std.log.info("Part 1: winning board idx={d}, last_number={d}, sum={d}, answer={d}", .{ card_idx, check_val, sum, check_val * sum });
//}
}
}
}
}
}
// std.log.info("Part 1 counts={d}, gamma_rate={b}, epsilon_rate={b}, answer={d}", .{ counts, gamma_rate, epsilon_rate, gamma_rate * @as(u32, epsilon_rate) });
}
//--------------------------------------------------------------------------------------------------
pub fn copy_array(input: [12]u8) [12]u8 {
var res = [_]u8{0} ** 12;
var i: u32 = 0;
while (i < 12) : (i += 1) {
res[i] = input[i];
}
return res;
}
//--------------------------------------------------------------------------------------------------
pub fn eq_array(lhs: [12]u8, rhs: [12]u8, limit: u32) bool {
var i: u32 = 0;
while (i < 12 and i < limit) : (i += 1) {
if (lhs[i] != rhs[i]) {
return false;
}
}
return true;
}
//--------------------------------------------------------------------------------------------------
pub fn array_to_int(input: [12]u8) u32 {
var res: u32 = 0;
var i: u32 = 0;
while (i < 12) : (i += 1) {
if (input[i] == '1') {
res |= (@as(u32, 1) << @truncate(u4, 11 - i));
}
}
return res;
}
//--------------------------------------------------------------------------------------------------
pub fn main() anyerror!void {
try part1();
//try part2();
}
//-------------------------------------------------------------------------------------------------- | src/day04.zig |
const std = @import("std");
const assert = std.debug.assert;
const L = std.unicode.utf8ToUtf16LeStringLiteral;
const zwin32 = @import("zwin32");
const w = zwin32.base;
const d3d12 = zwin32.d3d12;
const d2d1 = zwin32.d2d1;
const dwrite = zwin32.dwrite;
const hrPanic = zwin32.hrPanic;
const hrPanicOnFail = zwin32.hrPanicOnFail;
const zd3d12 = @import("zd3d12");
const common = @import("common");
const c = common.c;
pub export const D3D12SDKVersion: u32 = 4;
pub export const D3D12SDKPath: [*:0]const u8 = ".\\d3d12\\";
const window_name = "zig-gamedev: vector graphics test";
const window_width = 1920;
const window_height = 1080;
const DemoState = struct {
grfx: zd3d12.GraphicsContext,
frame_stats: common.FrameStats,
brush: *d2d1.ISolidColorBrush,
radial_gradient_brush: *d2d1.IRadialGradientBrush,
textformat: *dwrite.ITextFormat,
ellipse: *d2d1.IEllipseGeometry,
stroke_style: *d2d1.IStrokeStyle,
path: *d2d1.IPathGeometry,
ink: *d2d1.IInk,
ink_style: *d2d1.IInkStyle,
bezier_lines_path: *d2d1.IPathGeometry,
ink_points: std.ArrayList(d2d1.POINT_2F),
left_mountain_geo: *d2d1.IGeometry,
right_mountain_geo: *d2d1.IGeometry,
sun_geo: *d2d1.IGeometry,
river_geo: *d2d1.IGeometry,
custom_txtfmt: *dwrite.ITextFormat,
};
fn init(gpa_allocator: std.mem.Allocator) DemoState {
const window = common.initWindow(gpa_allocator, window_name, window_width, window_height) catch unreachable;
var grfx = zd3d12.GraphicsContext.init(gpa_allocator, window);
var ink_points = std.ArrayList(d2d1.POINT_2F).init(gpa_allocator);
const brush = blk: {
var maybe_brush: ?*d2d1.ISolidColorBrush = null;
hrPanicOnFail(grfx.d2d.?.context.CreateSolidColorBrush(
&d2d1.COLOR_F{ .r = 1.0, .g = 0.0, .b = 0.0, .a = 0.5 },
null,
&maybe_brush,
));
break :blk maybe_brush.?;
};
const textformat = blk: {
var maybe_textformat: ?*dwrite.ITextFormat = null;
hrPanicOnFail(grfx.d2d.?.dwrite_factory.CreateTextFormat(
L("Verdana"),
null,
dwrite.FONT_WEIGHT.NORMAL,
dwrite.FONT_STYLE.NORMAL,
dwrite.FONT_STRETCH.NORMAL,
32.0,
L("en-us"),
&maybe_textformat,
));
break :blk maybe_textformat.?;
};
hrPanicOnFail(textformat.SetTextAlignment(.LEADING));
hrPanicOnFail(textformat.SetParagraphAlignment(.NEAR));
const custom_txtfmt = blk: {
var maybe_textformat: ?*dwrite.ITextFormat = null;
hrPanicOnFail(grfx.d2d.?.dwrite_factory.CreateTextFormat(
L("Ink Free"),
null,
dwrite.FONT_WEIGHT.NORMAL,
dwrite.FONT_STYLE.NORMAL,
dwrite.FONT_STRETCH.NORMAL,
64.0,
L("en-us"),
&maybe_textformat,
));
break :blk maybe_textformat.?;
};
hrPanicOnFail(custom_txtfmt.SetTextAlignment(.LEADING));
hrPanicOnFail(custom_txtfmt.SetParagraphAlignment(.NEAR));
const ellipse = blk: {
var maybe_ellipse: ?*d2d1.IEllipseGeometry = null;
hrPanicOnFail(grfx.d2d.?.factory.CreateEllipseGeometry(
&.{ .point = .{ .x = 1210.0, .y = 150.0 }, .radiusX = 50.0, .radiusY = 70.0 },
&maybe_ellipse,
));
break :blk maybe_ellipse.?;
};
const stroke_style = blk: {
var maybe_stroke_style: ?*d2d1.IStrokeStyle = null;
hrPanicOnFail(grfx.d2d.?.factory.CreateStrokeStyle(
&.{
.startCap = .ROUND,
.endCap = .ROUND,
.dashCap = .FLAT,
.lineJoin = .MITER,
.miterLimit = 0.0,
.dashStyle = .SOLID,
.dashOffset = 0.0,
},
null,
0,
&maybe_stroke_style,
));
break :blk maybe_stroke_style.?;
};
const path = blk: {
var path: *d2d1.IPathGeometry = undefined;
hrPanicOnFail(grfx.d2d.?.factory.CreatePathGeometry(@ptrCast(*?*d2d1.IPathGeometry, &path)));
var sink: *d2d1.IGeometrySink = undefined;
hrPanicOnFail(path.Open(@ptrCast(*?*d2d1.IGeometrySink, &sink)));
defer {
hrPanicOnFail(sink.Close());
_ = sink.Release();
}
sink.BeginFigure(.{ .x = 500.0, .y = 400.0 }, .FILLED);
sink.AddLine(.{ .x = 600.0, .y = 300.0 });
sink.AddLine(.{ .x = 700.0, .y = 400.0 });
sink.AddLine(.{ .x = 800.0, .y = 300.0 });
sink.AddBezier(&.{
.point1 = .{ .x = 850.0, .y = 350.0 },
.point2 = .{ .x = 850.0, .y = 350.0 },
.point3 = .{ .x = 900.0, .y = 300.0 },
});
sink.AddBezier(&.{
.point1 = .{ .x = 920.0, .y = 280.0 },
.point2 = .{ .x = 950.0, .y = 320.0 },
.point3 = .{ .x = 1000.0, .y = 300.0 },
});
sink.EndFigure(.OPEN);
break :blk path;
};
const ink_style = blk: {
var ink_style: *d2d1.IInkStyle = undefined;
hrPanicOnFail(grfx.d2d.?.context.CreateInkStyle(
&.{ .nibShape = .ROUND, .nibTransform = d2d1.MATRIX_3X2_F.initIdentity() },
@ptrCast(*?*d2d1.IInkStyle, &ink_style),
));
break :blk ink_style;
};
const ink = blk: {
var ink: *d2d1.IInk = undefined;
hrPanicOnFail(grfx.d2d.?.context.CreateInk(
&.{ .x = 0.0, .y = 0.0, .radius = 0.0 },
@ptrCast(*?*d2d1.IInk, &ink),
));
var p0 = d2d1.POINT_2F{ .x = 0.0, .y = 0.0 };
ink_points.append(p0) catch unreachable;
ink.SetStartPoint(&.{ .x = p0.x, .y = p0.y, .radius = 1.0 });
const sp = ink.GetStartPoint();
assert(sp.x == p0.x and sp.y == p0.y and sp.radius == 1.0);
assert(ink.GetSegmentCount() == 0);
{
const p1 = d2d1.POINT_2F{ .x = 200.0, .y = 0.0 };
const cp1 = d2d1.POINT_2F{ .x = p0.x - 40.0, .y = p0.y + 140.0 };
const cp2 = d2d1.POINT_2F{ .x = p1.x + 40.0, .y = p1.y - 140.0 };
ink_points.append(cp1) catch unreachable;
ink_points.append(cp2) catch unreachable;
hrPanicOnFail(ink.AddSegments(&[_]d2d1.INK_BEZIER_SEGMENT{.{
.point1 = .{ .x = cp1.x, .y = cp1.y, .radius = 12.5 },
.point2 = .{ .x = cp2.x, .y = cp2.y, .radius = 12.5 },
.point3 = .{ .x = p1.x, .y = p1.y, .radius = 9.0 },
}}, 1));
ink_points.append(p1) catch unreachable;
}
p0 = ink_points.items[ink_points.items.len - 1];
{
const p1 = d2d1.POINT_2F{ .x = 400.0, .y = 0.0 };
const cp1 = d2d1.POINT_2F{ .x = p0.x - 40.0, .y = p0.y + 140.0 };
const cp2 = d2d1.POINT_2F{ .x = p1.x + 40.0, .y = p1.y - 140.0 };
ink_points.append(cp1) catch unreachable;
ink_points.append(cp2) catch unreachable;
hrPanicOnFail(ink.AddSegments(&[_]d2d1.INK_BEZIER_SEGMENT{.{
.point1 = .{ .x = cp1.x, .y = cp1.y, .radius = 6.25 },
.point2 = .{ .x = cp2.x, .y = cp2.y, .radius = 6.25 },
.point3 = .{ .x = p1.x, .y = p1.y, .radius = 1.0 },
}}, 1));
ink_points.append(p1) catch unreachable;
}
break :blk ink;
};
const bezier_lines_path = blk: {
var bezier_lines_path: *d2d1.IPathGeometry = undefined;
hrPanicOnFail(grfx.d2d.?.factory.CreatePathGeometry(@ptrCast(*?*d2d1.IPathGeometry, &bezier_lines_path)));
var sink: *d2d1.IGeometrySink = undefined;
hrPanicOnFail(bezier_lines_path.Open(@ptrCast(*?*d2d1.IGeometrySink, &sink)));
defer {
hrPanicOnFail(sink.Close());
_ = sink.Release();
}
sink.BeginFigure(.{ .x = 0.0, .y = 0.0 }, .FILLED);
sink.AddLines(ink_points.items.ptr + 1, @intCast(u32, ink_points.items.len - 1));
sink.EndFigure(.OPEN);
break :blk bezier_lines_path;
};
const left_mountain_geo = blk: {
var left_mountain_path: *d2d1.IPathGeometry = undefined;
hrPanicOnFail(grfx.d2d.?.factory.CreatePathGeometry(@ptrCast(*?*d2d1.IPathGeometry, &left_mountain_path)));
var sink: *d2d1.IGeometrySink = undefined;
hrPanicOnFail(left_mountain_path.Open(@ptrCast(*?*d2d1.IGeometrySink, &sink)));
defer {
hrPanicOnFail(sink.Close());
_ = sink.Release();
}
sink.SetFillMode(.WINDING);
sink.BeginFigure(.{ .x = 346.0, .y = 255.0 }, .FILLED);
const points = [_]d2d1.POINT_2F{
.{ .x = 267.0, .y = 177.0 },
.{ .x = 236.0, .y = 192.0 },
.{ .x = 212.0, .y = 160.0 },
.{ .x = 156.0, .y = 255.0 },
.{ .x = 346.0, .y = 255.0 },
};
sink.AddLines(&points, points.len);
sink.EndFigure(.CLOSED);
break :blk @ptrCast(*d2d1.IGeometry, left_mountain_path);
};
const right_mountain_geo = blk: {
var right_mountain_path: *d2d1.IPathGeometry = undefined;
hrPanicOnFail(grfx.d2d.?.factory.CreatePathGeometry(@ptrCast(*?*d2d1.IPathGeometry, &right_mountain_path)));
var sink: *d2d1.IGeometrySink = undefined;
hrPanicOnFail(right_mountain_path.Open(@ptrCast(*?*d2d1.IGeometrySink, &sink)));
defer {
hrPanicOnFail(sink.Close());
_ = sink.Release();
}
sink.SetFillMode(.WINDING);
sink.BeginFigure(.{ .x = 575.0, .y = 263.0 }, .FILLED);
const points = [_]d2d1.POINT_2F{
.{ .x = 481.0, .y = 146.0 },
.{ .x = 449.0, .y = 181.0 },
.{ .x = 433.0, .y = 159.0 },
.{ .x = 401.0, .y = 214.0 },
.{ .x = 381.0, .y = 199.0 },
.{ .x = 323.0, .y = 263.0 },
.{ .x = 575.0, .y = 263.0 },
};
sink.AddLines(&points, points.len);
sink.EndFigure(.CLOSED);
break :blk @ptrCast(*d2d1.IGeometry, right_mountain_path);
};
const sun_geo = blk: {
var sun_path: *d2d1.IPathGeometry = undefined;
hrPanicOnFail(grfx.d2d.?.factory.CreatePathGeometry(@ptrCast(*?*d2d1.IPathGeometry, &sun_path)));
var sink: *d2d1.IGeometrySink = undefined;
hrPanicOnFail(sun_path.Open(@ptrCast(*?*d2d1.IGeometrySink, &sink)));
defer {
hrPanicOnFail(sink.Close());
_ = sink.Release();
}
sink.SetFillMode(.WINDING);
sink.BeginFigure(.{ .x = 270.0, .y = 255.0 }, .FILLED);
sink.AddArc(&.{
.point = .{ .x = 440.0, .y = 255.0 },
.size = .{ .width = 85.0, .height = 85.0 },
.rotationAngle = 0.0, // rotation angle
.sweepDirection = .CLOCKWISE,
.arcSize = .SMALL,
});
sink.EndFigure(.CLOSED);
sink.BeginFigure(.{ .x = 299.0, .y = 182.0 }, .HOLLOW);
sink.AddBezier(&.{
.point1 = .{ .x = 299.0, .y = 182.0 },
.point2 = .{ .x = 294.0, .y = 176.0 },
.point3 = .{ .x = 285.0, .y = 178.0 },
});
sink.AddBezier(&.{
.point1 = .{ .x = 276.0, .y = 179.0 },
.point2 = .{ .x = 272.0, .y = 173.0 },
.point3 = .{ .x = 272.0, .y = 173.0 },
});
sink.EndFigure(.OPEN);
sink.BeginFigure(.{ .x = 354.0, .y = 156.0 }, .HOLLOW);
sink.AddBezier(&.{
.point1 = .{ .x = 354.0, .y = 156.0 },
.point2 = .{ .x = 358.0, .y = 149.0 },
.point3 = .{ .x = 354.0, .y = 142.0 },
});
sink.AddBezier(&.{
.point1 = .{ .x = 349.0, .y = 134.0 },
.point2 = .{ .x = 354.0, .y = 127.0 },
.point3 = .{ .x = 354.0, .y = 127.0 },
});
sink.EndFigure(.OPEN);
sink.BeginFigure(.{ .x = 322.0, .y = 164.0 }, .HOLLOW);
sink.AddBezier(&.{
.point1 = .{ .x = 322.0, .y = 164.0 },
.point2 = .{ .x = 322.0, .y = 156.0 },
.point3 = .{ .x = 314.0, .y = 152.0 },
});
sink.AddBezier(&.{
.point1 = .{ .x = 306.0, .y = 149.0 },
.point2 = .{ .x = 305.0, .y = 141.0 },
.point3 = .{ .x = 305.0, .y = 141.0 },
});
sink.EndFigure(.OPEN);
sink.BeginFigure(.{ .x = 385.0, .y = 164.0 }, .HOLLOW);
sink.AddBezier(&.{
.point1 = .{ .x = 385.0, .y = 164.0 },
.point2 = .{ .x = 392.0, .y = 161.0 },
.point3 = .{ .x = 394.0, .y = 152.0 },
});
sink.AddBezier(&.{
.point1 = .{ .x = 395.0, .y = 144.0 },
.point2 = .{ .x = 402.0, .y = 141.0 },
.point3 = .{ .x = 402.0, .y = 142.0 },
});
sink.EndFigure(.OPEN);
sink.BeginFigure(.{ .x = 408.0, .y = 182.0 }, .HOLLOW);
sink.AddBezier(&.{
.point1 = .{ .x = 408.0, .y = 182.0 },
.point2 = .{ .x = 416.0, .y = 184.0 },
.point3 = .{ .x = 422.0, .y = 178.0 },
});
sink.AddBezier(&.{
.point1 = .{ .x = 428.0, .y = 171.0 },
.point2 = .{ .x = 435.0, .y = 173.0 },
.point3 = .{ .x = 435.0, .y = 173.0 },
});
sink.EndFigure(.OPEN);
break :blk @ptrCast(*d2d1.IGeometry, sun_path);
};
const river_geo = blk: {
var river_path: *d2d1.IPathGeometry = undefined;
hrPanicOnFail(grfx.d2d.?.factory.CreatePathGeometry(@ptrCast(*?*d2d1.IPathGeometry, &river_path)));
var sink: *d2d1.IGeometrySink = undefined;
hrPanicOnFail(river_path.Open(@ptrCast(*?*d2d1.IGeometrySink, &sink)));
defer {
hrPanicOnFail(sink.Close());
_ = sink.Release();
}
sink.SetFillMode(.WINDING);
sink.BeginFigure(.{ .x = 183.0, .y = 392.0 }, .FILLED);
sink.AddBezier(&.{
.point1 = .{ .x = 238.0, .y = 284.0 },
.point2 = .{ .x = 472.0, .y = 345.0 },
.point3 = .{ .x = 356.0, .y = 303.0 },
});
sink.AddBezier(&.{
.point1 = .{ .x = 237.0, .y = 261.0 },
.point2 = .{ .x = 333.0, .y = 256.0 },
.point3 = .{ .x = 333.0, .y = 256.0 },
});
sink.AddBezier(&.{
.point1 = .{ .x = 335.0, .y = 257.0 },
.point2 = .{ .x = 241.0, .y = 261.0 },
.point3 = .{ .x = 411.0, .y = 306.0 },
});
sink.AddBezier(&.{
.point1 = .{ .x = 574.0, .y = 350.0 },
.point2 = .{ .x = 288.0, .y = 324.0 },
.point3 = .{ .x = 296.0, .y = 392.0 },
});
sink.EndFigure(.CLOSED);
break :blk @ptrCast(*d2d1.IGeometry, river_path);
};
const radial_gradient_brush = blk: {
const stops = [_]d2d1.GRADIENT_STOP{
.{ .color = d2d1.colorf.YellowGreen, .position = 0.0 },
.{ .color = d2d1.colorf.LightSkyBlue, .position = 1.0 },
};
var stop_collection: *d2d1.IGradientStopCollection = undefined;
hrPanicOnFail(grfx.d2d.?.context.CreateGradientStopCollection(
&stops,
2,
._2_2,
.CLAMP,
@ptrCast(*?*d2d1.IGradientStopCollection, &stop_collection),
));
defer _ = stop_collection.Release();
var radial_gradient_brush: *d2d1.IRadialGradientBrush = undefined;
hrPanicOnFail(grfx.d2d.?.context.CreateRadialGradientBrush(
&.{
.center = .{ .x = 75.0, .y = 75.0 },
.gradientOriginOffset = .{ .x = 0.0, .y = 0.0 },
.radiusX = 75.0,
.radiusY = 75.0,
},
null,
stop_collection,
@ptrCast(*?*d2d1.IRadialGradientBrush, &radial_gradient_brush),
));
break :blk radial_gradient_brush;
};
return .{
.grfx = grfx,
.frame_stats = common.FrameStats.init(),
.brush = brush,
.textformat = textformat,
.ellipse = ellipse,
.stroke_style = stroke_style,
.path = path,
.ink_style = ink_style,
.ink = ink,
.ink_points = ink_points,
.bezier_lines_path = bezier_lines_path,
.left_mountain_geo = left_mountain_geo,
.right_mountain_geo = right_mountain_geo,
.sun_geo = sun_geo,
.river_geo = river_geo,
.radial_gradient_brush = radial_gradient_brush,
.custom_txtfmt = custom_txtfmt,
};
}
fn drawShapes(demo: DemoState) void {
var grfx = &demo.grfx;
grfx.d2d.?.context.DrawLine(
.{ .x = 20.0, .y = 200.0 },
.{ .x = 120.0, .y = 300.0 },
@ptrCast(*d2d1.IBrush, demo.brush),
33.0,
demo.stroke_style,
);
grfx.d2d.?.context.DrawLine(
.{ .x = 160.0, .y = 300.0 },
.{ .x = 260.0, .y = 200.0 },
@ptrCast(*d2d1.IBrush, demo.brush),
33.0,
demo.stroke_style,
);
grfx.d2d.?.context.DrawLine(
.{ .x = 300.0, .y = 200.0 },
.{ .x = 400.0, .y = 300.0 },
@ptrCast(*d2d1.IBrush, demo.brush),
33.0,
demo.stroke_style,
);
grfx.d2d.?.context.DrawRectangle(
&.{ .left = 500.0, .top = 100.0, .right = 600.0, .bottom = 200.0 },
@ptrCast(*d2d1.IBrush, demo.brush),
5.0,
null,
);
grfx.d2d.?.context.FillRectangle(
&.{ .left = 610.0, .top = 100.0, .right = 710.0, .bottom = 200.0 },
@ptrCast(*d2d1.IBrush, demo.brush),
);
grfx.d2d.?.context.FillRoundedRectangle(
&.{
.rect = .{ .left = 830.0, .top = 100.0, .right = 930.0, .bottom = 200.0 },
.radiusX = 20.0,
.radiusY = 20.0,
},
@ptrCast(*d2d1.IBrush, demo.brush),
);
grfx.d2d.?.context.DrawEllipse(
&.{ .point = .{ .x = 990.0, .y = 150.0 }, .radiusX = 50.0, .radiusY = 70.0 },
@ptrCast(*d2d1.IBrush, demo.brush),
5.0,
null,
);
grfx.d2d.?.context.FillEllipse(
&.{ .point = .{ .x = 1100.0, .y = 150.0 }, .radiusX = 50.0, .radiusY = 70.0 },
@ptrCast(*d2d1.IBrush, demo.brush),
);
grfx.d2d.?.context.DrawGeometry(
@ptrCast(*d2d1.IGeometry, demo.ellipse),
@ptrCast(*d2d1.IBrush, demo.brush),
7.0,
null,
);
grfx.d2d.?.context.SetTransform(&d2d1.MATRIX_3X2_F.initTranslation(110.0, 0.0));
grfx.d2d.?.context.FillGeometry(
@ptrCast(*d2d1.IGeometry, demo.ellipse),
@ptrCast(*d2d1.IBrush, demo.brush),
null,
);
grfx.d2d.?.context.SetTransform(&d2d1.MATRIX_3X2_F.initIdentity());
demo.brush.SetColor(&d2d1.COLOR_F{ .r = 0.2, .g = 0.4, .b = 0.8, .a = 1.0 });
var i: u32 = 0;
while (i < 5) : (i += 1) {
grfx.d2d.?.context.SetTransform(&d2d1.MATRIX_3X2_F.initTranslation(0.0, @intToFloat(f32, i) * 50.0));
grfx.d2d.?.context.DrawGeometry(
@ptrCast(*d2d1.IGeometry, demo.path),
@ptrCast(*d2d1.IBrush, demo.brush),
15.0,
null,
);
}
grfx.d2d.?.context.SetTransform(&d2d1.MATRIX_3X2_F.initTranslation(500.0, 800.0));
grfx.d2d.?.context.DrawInk(demo.ink, @ptrCast(*d2d1.IBrush, demo.brush), demo.ink_style);
demo.brush.SetColor(&d2d1.COLOR_F{ .r = 1.0, .g = 1.0, .b = 1.0, .a = 1.0 });
grfx.d2d.?.context.DrawGeometry(
@ptrCast(*d2d1.IGeometry, demo.bezier_lines_path),
@ptrCast(*d2d1.IBrush, demo.brush),
3.0,
null,
);
demo.brush.SetColor(&d2d1.COLOR_F{ .r = 0.8, .g = 0.0, .b = 0.0, .a = 1.0 });
for (demo.ink_points.items) |cp| {
grfx.d2d.?.context.FillEllipse(
&.{ .point = cp, .radiusX = 9.0, .radiusY = 9.0 },
@ptrCast(*d2d1.IBrush, demo.brush),
);
}
grfx.d2d.?.context.SetTransform(&d2d1.MATRIX_3X2_F.initTranslation(750.0, 900.0));
grfx.d2d.?.context.DrawInk(demo.ink, @ptrCast(*d2d1.IBrush, demo.brush), demo.ink_style);
grfx.d2d.?.context.SetTransform(&d2d1.MATRIX_3X2_F.initTranslation(1080.0, 640.0));
// Draw background.
demo.brush.SetColor(&d2d1.colorf.White);
grfx.d2d.?.context.FillRectangle(
&.{ .left = 100.0, .top = 100.0, .right = 620.0, .bottom = 420.0 },
@ptrCast(*d2d1.IBrush, demo.brush),
);
// NOTE(mziulek): D2D1 is slow. It creates and destroys resources every frame (see graphics.endDraw2d()).
// TODO(mziulek): Check if ID2D1GeometryRealization helps.
// Draw sun.
// NOTE(mziulek): Using 'demo.radial_gradient_brush' causes GPU-Based Validation errors (D3D11on12 bug?).
// As a workaround we use 'demo.brush' (solid color brush).
demo.brush.SetColor(&d2d1.colorf.DarkOrange);
grfx.d2d.?.context.FillGeometry(demo.sun_geo, @ptrCast(*d2d1.IBrush, demo.brush), null);
demo.brush.SetColor(&d2d1.colorf.Black);
grfx.d2d.?.context.DrawGeometry(demo.sun_geo, @ptrCast(*d2d1.IBrush, demo.brush), 5.0, null);
// Draw left mountain geometry.
demo.brush.SetColor(&d2d1.colorf.OliveDrab);
grfx.d2d.?.context.FillGeometry(demo.left_mountain_geo, @ptrCast(*d2d1.IBrush, demo.brush), null);
demo.brush.SetColor(&d2d1.colorf.Black);
grfx.d2d.?.context.DrawGeometry(demo.left_mountain_geo, @ptrCast(*d2d1.IBrush, demo.brush), 5.0, null);
// Draw river geometry.
demo.brush.SetColor(&d2d1.colorf.LightSkyBlue);
grfx.d2d.?.context.FillGeometry(demo.river_geo, @ptrCast(*d2d1.IBrush, demo.brush), null);
demo.brush.SetColor(&d2d1.colorf.Black);
grfx.d2d.?.context.DrawGeometry(demo.river_geo, @ptrCast(*d2d1.IBrush, demo.brush), 5.0, null);
// Draw right mountain geometry.
demo.brush.SetColor(&d2d1.colorf.YellowGreen);
grfx.d2d.?.context.FillGeometry(demo.right_mountain_geo, @ptrCast(*d2d1.IBrush, demo.brush), null);
demo.brush.SetColor(&d2d1.colorf.Black);
grfx.d2d.?.context.DrawGeometry(demo.right_mountain_geo, @ptrCast(*d2d1.IBrush, demo.brush), 5.0, null);
grfx.d2d.?.context.SetTransform(&d2d1.MATRIX_3X2_F.initIdentity());
}
fn deinit(demo: *DemoState, gpa_allocator: std.mem.Allocator) void {
demo.grfx.finishGpuCommands();
_ = demo.brush.Release();
_ = demo.textformat.Release();
_ = demo.custom_txtfmt.Release();
_ = demo.ellipse.Release();
_ = demo.stroke_style.Release();
_ = demo.path.Release();
_ = demo.ink.Release();
_ = demo.ink_style.Release();
_ = demo.bezier_lines_path.Release();
_ = demo.left_mountain_geo.Release();
_ = demo.right_mountain_geo.Release();
_ = demo.sun_geo.Release();
_ = demo.river_geo.Release();
_ = demo.radial_gradient_brush.Release();
demo.ink_points.deinit();
demo.grfx.deinit(gpa_allocator);
common.deinitWindow(gpa_allocator);
demo.* = undefined;
}
fn update(demo: *DemoState) void {
demo.frame_stats.update(demo.grfx.window, window_name);
}
fn draw(demo: *DemoState) void {
var grfx = &demo.grfx;
grfx.beginFrame();
const back_buffer = grfx.getBackBuffer();
grfx.addTransitionBarrier(back_buffer.resource_handle, d3d12.RESOURCE_STATE_RENDER_TARGET);
grfx.flushResourceBarriers();
grfx.cmdlist.OMSetRenderTargets(
1,
&[_]d3d12.CPU_DESCRIPTOR_HANDLE{back_buffer.descriptor_handle},
w.TRUE,
null,
);
grfx.cmdlist.ClearRenderTargetView(
back_buffer.descriptor_handle,
&[4]f32{ 0.0, 0.0, 0.0, 1.0 },
0,
null,
);
grfx.beginDraw2d();
{
const stats = &demo.frame_stats;
var buffer = [_]u8{0} ** 64;
const text = std.fmt.bufPrint(
buffer[0..],
"FPS: {d:.1}\nCPU time: {d:.3} ms",
.{ stats.fps, stats.average_cpu_time },
) catch unreachable;
demo.brush.SetColor(&d2d1.COLOR_F{ .r = 1.0, .g = 1.0, .b = 1.0, .a = 1.0 });
common.drawText(
grfx.d2d.?.context,
text,
demo.textformat,
&d2d1.RECT_F{
.left = 10.0,
.top = 10.0,
.right = @intToFloat(f32, grfx.viewport_width),
.bottom = @intToFloat(f32, grfx.viewport_height),
},
@ptrCast(*d2d1.IBrush, demo.brush),
);
demo.brush.SetColor(&d2d1.COLOR_F{ .r = 0.6, .g = 0.0, .b = 1.0, .a = 1.0 });
common.drawText(
grfx.d2d.?.context,
\\Lorem ipsum dolor sit amet,
\\consectetur adipiscing elit,
\\sed do eiusmod tempor incididunt
\\ut labore et dolore magna aliqua.
,
demo.custom_txtfmt,
&d2d1.RECT_F{
.left = 1030.0,
.top = 220.0,
.right = @intToFloat(f32, grfx.viewport_width),
.bottom = @intToFloat(f32, grfx.viewport_height),
},
@ptrCast(*d2d1.IBrush, demo.brush),
);
demo.brush.SetColor(&d2d1.COLOR_F{ .r = 1.0, .g = 1.0, .b = 1.0, .a = 1.0 });
drawShapes(demo.*);
}
grfx.endDraw2d();
grfx.endFrame();
}
pub fn main() !void {
common.init();
defer common.deinit();
var gpa_allocator_state = std.heap.GeneralPurposeAllocator(.{}){};
defer {
const leaked = gpa_allocator_state.deinit();
assert(leaked == false);
}
const gpa_allocator = gpa_allocator_state.allocator();
var demo = init(gpa_allocator);
defer deinit(&demo, gpa_allocator);
while (true) {
var message = std.mem.zeroes(w.user32.MSG);
const has_message = w.user32.peekMessageA(&message, null, 0, 0, w.user32.PM_REMOVE) catch unreachable;
if (has_message) {
_ = w.user32.translateMessage(&message);
_ = w.user32.dispatchMessageA(&message);
if (message.message == w.user32.WM_QUIT) {
break;
}
} else {
update(&demo);
draw(&demo);
}
}
} | samples/vector_graphics_test/src/vector_graphics_test.zig |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.