code
stringlengths 38
801k
| repo_path
stringlengths 6
263
|
---|---|
const std = @import("std");
const t = @import("testing.zig");
const Input = @import("input.zig");
usingnamespace @import("ghost_party.zig");
usingnamespace @import("meta.zig");
usingnamespace @import("result.zig");
usingnamespace @import("string_parser.zig");
///
/// Base type constructor for ParZig parsers
///
/// Constructs a parser from a partial parser.
///
/// Arguments:
/// `P`: parser type struct
/// `P.T`: value type of parse results
/// `P.parse`: parser function `Input -> Result(T)`
///
/// Returns:
/// `Parser{ .T = P.T }
///
pub fn Parser(comptime P: type) type {
return struct {
// Keep in sync with `meta.isParser`
const Self = @This();
/// Value type of parse results
pub const T = ParseResult(P).T;
pub usingnamespace (P);
///
/// Functor `map` combinator
///
/// Constructs a parser that calls a function `f` to transform a parse
/// `Result(T)` to a parse `Result(U)`.
///
/// Arguments:
/// `f`: transform function `Self.T -> U`
///
/// Returns:
/// `Parser{ .T = U }`
///
pub fn Map(comptime U: type, comptime map: anytype) type {
return Parser(struct {
pub fn parse(input: Input) Result(U) {
switch (Self.parse(input)) {
.Some => |r| return Result(U).some(map(r.value), r.tail),
.None => |r| return Result(U).fail(r),
}
}
});
}
///
/// Alternative sequence combinator `<|>`
///
/// Constructs a parser that runs two parsers and returns the leftmost
/// successful result, or the rightmost failure reason.
///
/// Arguments:
/// `R`: right side parser
///
/// Conditions:
/// `Self.T == R.T`
///
/// Returns:
/// `Result(T)`
///
pub fn Alt(comptime R: type) type {
return Parser(struct {
pub fn parse(input: Input) Result(T) {
const r = Self.parse(input);
if (.Some == r) return r;
return R.parse(input);
}
});
}
///
/// Left sequence combinator `<*`
///
/// Constructs a parser that runs two parsers, returning the left
/// result when both are successful. If either parser fails, the
/// leftmost failure is returned.
///
/// Arguments:
/// `R`: right side parser
///
/// Returns:
/// `Parser{.T = Self.T}`
///
pub fn SeqL(comptime R: type) type {
return Parser(struct {
pub fn parse(input: Input) Result(T) {
switch (Self.parse(input)) {
.None => |r| return Result(T).fail(r),
.Some => |left| //
switch (R.parse(left.tail)) {
.None => |r| return Result(T).fail(r),
.Some => //
return Result(T){ .Some = left },
},
}
}
});
}
///
/// Right sequence combinator `*>`
///
/// Constructs a parser that runs two parsers, returning the right
/// result when both are successful. If either parser fails, the
/// leftmost failure is returned, wrapped as the right result.
///
/// Arguments:
/// `R`: right side parser
///
/// Returns:
/// `Parser{.T = R.T}`
///
pub fn SeqR(comptime R: type) type {
const U = R.T;
return Parser(struct {
pub fn parse(input: Input) Result(U) {
switch (Self.parse(input)) {
.None => |r| return Result(U).fail(r),
.Some => |left| //
switch (R.parse(left.tail)) {
.None => |r| return Result(U).fail(r),
.Some => |right| //
return Result(U){ .Some = right },
},
}
}
});
}
///
/// Monadic `bind` combinator `>>=`
///
/// Constructs a parser that calls a function `f` to transform a parse
/// `Result(T)` to a parse `Result(U)`.
///
/// Arguments:
/// `U`: result value type
/// `f`: transform function `Self.T -> Result(U)`
///
/// Returns:
/// `Parser{ .T = U }`
///
pub fn Bind(comptime U: type, comptime f: anytype) type {
return Self.Map(Result(U), f).Join;
}
///
/// Monadic `join` combinator
///
/// Constructs a parser that unwraps a nested result type
/// `Result(Result(U))`, to `Result(U)`.
///
/// Arguments: none
///
/// Conditions:
/// `Self{.T = Result(U)}`
///
/// Returns:
/// `Parser{ .T = U }`
///
pub const Join = Parser(struct {
pub fn parse(input: Input) Result(U) {
switch (Self.parse(input)) {
.None => |r| return Result(U).fail(r),
.Some => |r| return r,
}
}
});
///
/// Parser runner
///
/// Arguments:
/// `bytes: []const u8` - input buffer to parse
/// `label: ?[]const u8` - optional label (e.g. file name)
///
/// Returns:
/// `Result(Self.T)`
///
pub fn run(
bytes: []const u8,
label: ?[]const u8,
) Result(T) {
return Self.parse(Input.init(bytes, label));
}
};
}
///
/// Monadic `pure` constructor
///
/// Constructs a parser that returns a constant successful result.
///
/// Arguments:
/// `v`: parse result value
///
/// Returns:
/// `Parser{ .T = @TypeOf(v) }`
///
pub fn Pure(comptime v: anytype) type {
const T = @TypeOf(v);
return Parser(struct {
pub fn parse(input: Input) Result(T) {
return Result(T).some(v, input);
}
});
}
///
/// Constant failure reason constructor
///
/// Constructs a parser that always fails with the given reason.
///
/// Arguments:
/// `T`: parse result value type
/// `why`: opptional reason for failure
///
/// Returns:
/// `Parser{ .T = T }`
///
pub fn Fail(comptime T: type, comptime why: ?Reason) type {
return Parser(struct {
pub fn parse(input: Input) Result(T) {
_ = input;
return Result(T).fail(why);
}
});
}
test "parse failure" {
try t.expectNone(Fail(void, null), "");
}
///
/// Singleton parser that successfully matches nothing
///
pub const Nothing = Pure({});
test "parse nothing" {
try t.expectSomeExactlyEqual({}, Nothing, ghost);
try t.expectSomeTail(ghost, Nothing, ghost);
}
///
/// Singleton parser that only matches the end of input
///
pub const End = Parser(struct {
pub fn parse(input: Input) Result(void) {
if (input.len() != 0) return Result(void).none();
return Result(void).some({}, input);
}
});
test "parse end of input" {
try t.expectSomeEqual({}, End, "");
try t.expectNone(End, "π»");
}
///
/// Look-ahead non-matching constructor
///
/// Constructs a parser that never consumes input, and negates the result of
/// the given parser. When it is successful, this parser returns a failed
/// result without reason, and when it fails, this parser returns a successful
/// void result.
///
/// Arguments:
/// `P`: the parser to be negated
///
/// Returns:
/// `Parser{ .T = void }`
///
pub fn Not(comptime P: type) type {
return Parser(struct {
pub fn parse(input: Input) Result(void) {
switch (P.parse(input)) {
.Some => return Result(void).none(),
.None => return Result(void).some({}, input),
}
}
});
}
test "non matching look-ahead" {
try t.expectNone(Not(Char('π»')), ghost_party);
try t.expectSomeEqual({}, Not(Char('π₯³')), ghost_party);
}
///
/// Look-ahead constructor
///
/// Constructs a parser that never consumes input, and maps any successful
/// result of the given parser to void.
///
/// Arguments:
/// `P`: the parser to be tested
///
/// Returns:
/// `Parser{ .T = void }`
///
pub fn Try(comptime P: type) type {
return Parser(struct {
pub fn parse(input: Input) Result(void) {
switch (P.parse(input)) {
.None => |r| return Result(void).fail(r),
.Some => return Result(void).some({}, input),
}
}
});
}
test "matching look-ahead" {
try t.expectNone(Try(Char('π₯³')), ghost_party);
try t.expectSomeEqual({}, Try(Char('π»')), ghost_party);
}
///
/// Optional parser constructor
///
/// Constructs a parser that maps the result value type of the given parser
/// to an optional, and maps any failures to a successful `null` result.
///
/// Arguments:
/// `P`: parser to be made optional
///
/// Returns:
/// `Parser { .T = ?P.T }`
///
pub fn Optional(comptime P: anytype) type {
const T = P.T;
return Parser(struct {
pub fn parse(input: Input) Result(?T) {
switch (P.parse(input)) {
.Some => |r| return Result(?T).some(r.value, r.tail),
.None => return Result(?T).some(null, input),
}
}
});
}
test "optional" {
try t.expectSomeEqualSliceOpt(u8, ghost, Optional(Char('π»')), ghost_party);
try t.expectSomeEqual(null, Optional(Char('π»')), party_ghost);
}
//------------------------------------------------------------------------------
//
// MARK: Tests for Parser combinators
//
//------------------------------------------------------------------------------
test "alternatives" {
try t.expectSomeEqualSlice(u8, ghost, Char('π₯³').Alt(Char('π»')), ghost_party);
try t.expectSomeEqualSlice(u8, party, Char('π₯³').Alt(Char('π»')), party_ghost);
}
test "sequence left" {
try t.expectSomeEqualSlice(u8, party, Char('π₯³').SeqL(Char('π»')), party_ghost);
try t.expectNone(Char('π₯³').SeqL(Char('π»')), ghost_party);
}
test "sequence right" {
try t.expectSomeEqualSlice(u8, ghost, Char('π₯³').SeqR(Char('π»')), party_ghost);
try t.expectNone(Char('π₯³').SeqR(Char('π»')), ghost_party);
}
test "compile" {
std.testing.refAllDecls(@This());
} | src/parser.zig |
const std = @import("std");
const webgpu = @import("./webgpu.zig");
pub const Device = struct {
pub const VTable = struct {
destroy_fn: fn(*Device) void,
create_buffer_fn: fn(*Device, webgpu.BufferDescriptor) CreateBufferError!*webgpu.Buffer,
create_texture_fn: fn(*Device, webgpu.TextureDescriptor) CreateTextureError!*webgpu.Texture,
create_sampler_fn: fn(*Device, webgpu.SamplerDescriptor) CreateSamplerError!*webgpu.Sampler,
create_bind_group_layout_fn: fn(*Device, webgpu.BindGroupLayoutDescriptor) CreateBindGroupLayoutError!*webgpu.BindGroupLayout,
create_pipeline_layout_fn: fn(*Device, webgpu.PipelineLayoutDescriptor) CreatePipelineLayoutError!*webgpu.PipelineLayout,
create_bind_group_fn: fn(*Device, webgpu.BindGroupDescriptor) CreateBindGroupError!*webgpu.BindGroup,
create_shader_module_fn: fn(*Device, webgpu.ShaderModuleDescriptor) CreateShaderModuleError!*webgpu.ShaderModule,
create_compute_pipeline_fn: fn(*Device, webgpu.ComputePipelineDescriptor) CreateComputePipelineError!*webgpu.ComputePipeline,
create_render_pipeline_fn: fn(*Device, webgpu.RenderPipelineDescriptor) CreateRenderPipelineError!*webgpu.RenderPipeline,
create_command_encoder_fn: fn(*Device, webgpu.CommandEncoderDescriptor) CreateCommandEncoderError!*webgpu.CommandEncoder,
create_render_bundle_encoder_fn: fn(*Device, webgpu.RenderBundleEncoderDescriptor) CreateRenderBundleEncoderError!*webgpu.RenderBundleEncoder,
};
__vtable: *const VTable,
instance: *webgpu.Instance,
adapter: *webgpu.Adapter,
features: webgpu.Features,
limits: webgpu.Limits,
queue: *Queue,
pub inline fn destroy(device: *Device) void {
device.__vtable.destroy_fn(device);
}
pub const CreateBufferError = error {
OutOfMemory,
Failed,
};
pub inline fn createBuffer(device: *Device, descriptor: webgpu.BufferDescriptor) CreateBufferError!*webgpu.Buffer {
return device.__vtable.create_buffer_fn(device, descriptor);
}
pub const CreateTextureError = error {
OutOfMemory,
Failed,
};
pub inline fn createTexture(device: *Device, descriptor: webgpu.TextureDescriptor) CreateTextureError!*webgpu.Texture {
return device.__vtable.create_texture_fn(device, descriptor);
}
pub const CreateSamplerError = error {
OutOfMemory,
Failed,
};
pub inline fn createSampler(device: *Device, descriptor: webgpu.SamplerDescriptor) CreateSamplerError!*webgpu.Sampler {
return device.__vtable.create_sampler_fn(device, descriptor);
}
pub const CreateBindGroupLayoutError = error {
OutOfMemory,
Failed,
};
pub inline fn createBindGroupLayout(device: *Device, descriptor: webgpu.BindGroupLayoutDescriptor) CreateBindGroupLayoutError!*webgpu.BindGroupLayout {
return device.__vtable.create_bind_group_layout_fn(device, descriptor);
}
pub const CreatePipelineLayoutError = error {
OutOfMemory,
Failed,
};
pub inline fn createPipelineLayout(device: *Device, descriptor: webgpu.PipelineLayoutDescriptor) CreatePipelineLayoutError!*webgpu.PipelineLayout {
return device.__vtable.create_pipeline_layout_fn(device, descriptor);
}
pub const CreateBindGroupError = error {
OutOfMemory,
Failed,
};
pub inline fn createBindGroup(device: *Device, descriptor: webgpu.BindGroupDescriptor) CreateBindGroupError!*webgpu.BindGroup {
return device.__vtable.create_bind_group_fn(device, descriptor);
}
pub const CreateShaderModuleError = error {
OutOfMemory,
Failed,
};
pub inline fn createShaderModule(device: *Device, descriptor: webgpu.ShaderModuleDescriptor) CreateShaderModuleError!*webgpu.ShaderModule {
return device.__vtable.create_shader_module_fn(device, descriptor);
}
pub const CreateComputePipelineError = error {
OutOfMemory,
Failed,
};
pub inline fn createComputePipeline(device: *Device, descriptor: webgpu.ComputePipelineDescriptor) CreateComputePipelineError!*webgpu.ComputePipeline {
return device.__vtable.create_compute_pipeline_fn(device, descriptor);
}
pub const CreateRenderPipelineError = error {
OutOfMemory,
Failed,
};
pub inline fn createRenderPipeline(device: *Device, descriptor: webgpu.RenderPipelineDescriptor) CreateRenderPipelineError!*webgpu.RenderPipeline {
return device.__vtable.create_render_pipeline_fn(device, descriptor);
}
pub const CreateCommandEncoderError = error {
OutOfMemory,
Failed,
};
pub inline fn createCommandEncoder(device: *Device, descriptor: webgpu.CommandEncoderDescriptor) CreateCommandEncoderError!*webgpu.CommandEncoder {
return device.__vtable.create_command_encoder_fn(device, descriptor);
}
pub const CreateRenderBundleEncoderError = error {
OutOfMemory,
Failed,
};
pub inline fn createRenderBundleEncoder(device: *Device, descriptor: webgpu.RenderBundleEncoderDescriptor) CreateRenderBundleEncoderError!*webgpu.RenderBundleEncoder {
return device.__vtable.create_render_bundle_encoder_fn(device, descriptor);
}
};
pub const Queue = struct {
pub const VTable = struct {
submit_fn: fn(*Queue, []webgpu.CommandBuffer) SubmitError!void,
on_submitted_work_done_fn: fn(*Queue) void,
write_buffer_fn: fn(*Queue, *webgpu.Buffer, usize, []const u8) WriteBufferError!void,
write_texture_fn: fn(*Queue, webgpu.ImageCopyTexture, []const u8, webgpu.TextureDataLayout, webgpu.Extend3D) WriteTextureError!void,
};
__vtable: *const VTable,
device: *Device,
pub const SubmitError = error {
OutOfMemory,
Failed,
};
pub inline fn submit(queue: *Queue, command_buffers: []webgpu.CommandBuffer) SubmitError!void {
return queue.__vtable.submit_fn(queue, command_buffers);
}
pub const OnSubmittedWorkDoneError = error {};
pub inline fn onSubmittedWorkDone(queue: *Queue) OnSubmittedWorkDoneError!void {
return queue.__vtable.on_submitted_work_done_fn(queue);
}
pub const WriteBufferError = error {
Failed,
};
pub inline fn writeBuffer(queue: *Queue, buffer: *webgpu.Buffer, buffer_offset: usize, data: []const u8) WriteBufferError!void {
return queue.__vtable.write_buffer_fn(queue, buffer, buffer_offset, data);
}
pub const WriteTextureError = error {
Failed,
};
pub inline fn writeTexture(queue: *Queue, destination: webgpu.ImageCopyTexture, data: []const u8, data_layout: webgpu.TextureDataLayout, size: webgpu.Extend3D) WriteTextureError!void {
return queue.__vtable.write_texture_fn(queue, destination, data, data_layout, size);
}
}; | src/device.zig |
const std = @import("std");
const stdx = @import("stdx");
const graphics = @import("graphics");
const Graphics = graphics.Graphics;
const builtin = @import("builtin");
const ds = stdx.ds;
const v8 = @import("v8");
const platform = @import("platform");
const KeyCode = platform.KeyCode;
const t = stdx.testing;
const Mock = t.Mock;
const curl = @import("curl");
const ma = @import("miniaudio");
const Vec3 = stdx.math.Vec3;
const sdl = @import("sdl");
const audio = @import("audio.zig");
const AudioEngine = audio.AudioEngine;
const StdSound = audio.Sound;
const v8x = @import("v8x.zig");
const tasks = @import("tasks.zig");
const work_queue = @import("work_queue.zig");
const TaskOutput = work_queue.TaskOutput;
const runtime = @import("runtime.zig");
const RuntimeContext = runtime.RuntimeContext;
const RuntimeValue = runtime.RuntimeValue;
const ResourceId = runtime.ResourceId;
const PromiseId = runtime.PromiseId;
const F64SafeUint = runtime.F64SafeUint;
const Error = runtime.CsError;
const onFreeResource = runtime.onFreeResource;
const Uint8Array = runtime.Uint8Array;
const CsWindow = runtime.CsWindow;
const CsRandom = runtime.Random;
const gen = @import("gen.zig");
const log = stdx.log.scoped(.api);
const _server = @import("server.zig");
const HttpServer = _server.HttpServer;
const adapter = @import("adapter.zig");
const ManagedStruct = adapter.ManagedStruct;
const ManagedSlice = adapter.ManagedSlice;
const RtTempStruct = adapter.RtTempStruct;
const PromiseSkipJsGen = adapter.PromiseSkipJsGen;
const This = adapter.This;
const ThisResource = adapter.ThisResource;
const ThisHandle = adapter.ThisHandle;
const FuncData = adapter.FuncData;
// TODO: Once https://github.com/ziglang/zig/issues/8259 is resolved, use comptime to set param names.
/// @title Window Management
/// @name window
/// @ns cs.window
/// Provides a cross platform API to create and manage windows.
pub const cs_window = struct {
/// Creates a new window and returns the handle.
/// @param width
/// @param height
/// @param title
pub fn create(rt: *RuntimeContext, width: u32, height: u32, title: []const u8) v8.Object {
if (rt.dev_mode and rt.dev_ctx.dev_window != null) {
const S = struct {
var replaced_dev_window_before = false;
};
// Take over the dev window.
const dev_win = rt.dev_ctx.dev_window.?;
const cur_width = dev_win.window.getWidth();
const cur_height = dev_win.window.getHeight();
dev_win.window.setTitle(title);
if (cur_width != width or cur_height != height) {
dev_win.resize(width, height);
if (!S.replaced_dev_window_before) {
// Only recenter if this is the first time the user window is taking over the dev window.
dev_win.window.center();
}
}
rt.dev_ctx.dev_window = null;
rt.active_window = dev_win;
S.replaced_dev_window_before = true;
return dev_win.js_window.castToObject();
}
var win: platform.Window = undefined;
if (rt.num_windows > 0) {
// Create a new window using an existing open gl context.
win = platform.Window.initWithSharedContext(rt.alloc, .{
.width = width,
.height = height,
.title = title,
.resizable = true,
.high_dpi = true,
.mode = .Windowed,
}, rt.active_window.window) catch unreachable;
} else {
// Create a new window with a new open gl context.
win = platform.Window.init(rt.alloc, .{
.width = width,
.height = height,
.title = title,
.resizable = true,
.high_dpi = true,
.mode = .Windowed,
}) catch unreachable;
}
const res = rt.createCsWindowResource();
res.ptr.init(rt, win, res.id);
rt.active_window = res.ptr;
res.ptr.js_window.setWeakFinalizer(res.external, onFreeResource, v8.WeakCallbackType.kParameter);
return res.ptr.js_window.castToObject();
}
/// An interface for a window handle.
pub const Window = struct {
/// Returns the graphics context attached to this window.
pub fn getGraphics(this: ThisResource(.CsWindow)) *const anyopaque {
return @ptrCast(*const anyopaque, this.res.js_graphics.inner.handle);
}
/// Provide the handler for the window's frame updates.
/// Provide a null value to disable these events.
/// This is a good place to do your app's update logic and draw to the screen.
/// The frequency of frame updates is limited by an FPS counter.
/// Eventually, this frequency will be configurable.
/// @param callback
pub fn onUpdate(rt: *RuntimeContext, this: ThisResource(.CsWindow), mb_cb: ?v8.Function) void {
v8x.updateOptionalPersistent(v8.Function, rt.isolate, &this.res.on_update_cb, mb_cb);
}
/// Provide the handler for receiving mouse down events when this window is active.
/// Provide a null value to disable these events.
/// @param callback
pub fn onMouseDown(rt: *RuntimeContext, this: ThisResource(.CsWindow), mb_cb: ?v8.Function) void {
v8x.updateOptionalPersistent(v8.Function, rt.isolate, &this.res.on_mouse_down_cb, mb_cb);
}
/// Provide the handler for receiving mouse up events when this window is active.
/// Provide a null value to disable these events.
/// @param callback
pub fn onMouseUp(rt: *RuntimeContext, this: ThisResource(.CsWindow), mb_cb: ?v8.Function) void {
v8x.updateOptionalPersistent(v8.Function, rt.isolate, &this.res.on_mouse_up_cb, mb_cb);
}
/// Provide the handler for receiving mouse move events when this window is active.
/// Provide a null value to disable these events.
/// @param callback
pub fn onMouseMove(rt: *RuntimeContext, this: ThisResource(.CsWindow), mb_cb: ?v8.Function) void {
v8x.updateOptionalPersistent(v8.Function, rt.isolate, &this.res.on_mouse_move_cb, mb_cb);
}
/// Provide the handler for receiving key down events when this window is active.
/// Provide a null value to disable these events.
/// @param callback
pub fn onKeyDown(rt: *RuntimeContext, this: ThisResource(.CsWindow), mb_cb: ?v8.Function) void {
v8x.updateOptionalPersistent(v8.Function, rt.isolate, &this.res.on_key_down_cb, mb_cb);
}
/// Provide the handler for receiving key up events when this window is active.
/// Provide a null value to disable these events.
/// @param callback
pub fn onKeyUp(rt: *RuntimeContext, this: ThisResource(.CsWindow), mb_cb: ?v8.Function) void {
v8x.updateOptionalPersistent(v8.Function, rt.isolate, &this.res.on_key_up_cb, mb_cb);
}
/// Provide the handler for the window's resize event.
/// Provide a null value to disable these events.
/// A window can be resized by the user or the platform's window manager.
/// @param callback
pub fn onResize(rt: *RuntimeContext, this: ThisResource(.CsWindow), mb_cb: ?v8.Function) void {
v8x.updateOptionalPersistent(v8.Function, rt.isolate, &this.res.on_resize_cb, mb_cb);
}
/// Returns how long the last frame took in microseconds. This includes the onUpdate call and the delay to achieve the target FPS.
/// This is useful for animation or physics for calculating the next position of an object.
pub fn getLastFrameDuration(this: ThisResource(.CsWindow)) u32 {
return @intCast(u32, this.res.fps_limiter.getLastFrameDelta());
}
/// Returns how long the last frame took to perform onUpdate in microseconds.
/// This is useful to measure the performance of your onUpdate logic.
pub fn getLastUpdateDuration(this: ThisResource(.CsWindow)) u32 {
// TODO: Provide config for more accurate measurement with glFinish.
return @intCast(u32, this.res.fps_limiter.getLastUpdateDelta());
}
/// Returns the average frames per second.
pub fn getFps(this: ThisResource(.CsWindow)) u32 {
return @intCast(u32, this.res.fps_limiter.getFps());
}
/// Closes the window and frees the handle.
pub fn close(rt: *RuntimeContext, this: ThisResource(.CsWindow)) void {
rt.startDeinitResourceHandle(this.res_id);
}
/// Minimizes the window.
pub fn minimize(this: ThisResource(.CsWindow)) void {
this.res.window.minimize();
}
/// Maximizes the window. The window must be resizable.
pub fn maximize(this: ThisResource(.CsWindow)) void {
this.res.window.maximize();
}
/// Restores the window to the size before it was minimized or maximized.
pub fn restore(this: ThisResource(.CsWindow)) void {
this.res.window.restore();
}
/// Set to fullscreen mode with a videomode change.
pub fn setFullscreenMode(this: ThisResource(.CsWindow)) void {
this.res.window.setMode(.Fullscreen);
}
/// Set to pseudo fullscreen mode which takes up the entire screen but does not change the videomode.
pub fn setPseudoFullscreenMode(this: ThisResource(.CsWindow)) void {
this.res.window.setMode(.PseudoFullscreen);
}
/// Set to windowed mode.
pub fn setWindowedMode(this: ThisResource(.CsWindow)) void {
this.res.window.setMode(.Windowed);
}
/// Creates a child window attached to this window. Returns the new child window handle.
/// @param title
/// @param width
/// @param height
pub fn createChild(rt: *RuntimeContext, this: ThisResource(.CsWindow), title: []const u8, width: u32, height: u32) v8.Object {
// TODO: Make child windows behave different than creating a new window.
const new_res = rt.createCsWindowResource();
const new_win = platform.Window.initWithSharedContext(rt.alloc, .{
.width = width,
.height = height,
.title = title,
.resizable = true,
.high_dpi = true,
.mode = .Windowed,
}, this.res.window) catch unreachable;
new_res.ptr.init(rt, new_win, new_res.id);
// rt.active_window = new_res.ptr;
return new_res.ptr.js_window.castToObject();
}
/// Sets the window position on the screen.
/// @param x
/// @param y
pub fn position(this: ThisResource(.CsWindow), x: i32, y: i32) void {
this.res.window.setPosition(x, y);
}
/// Center the window on the screen.
pub fn center(this: ThisResource(.CsWindow)) void {
this.res.window.center();
}
/// Raises the window above other windows and acquires the input focus.
pub fn focus(this: ThisResource(.CsWindow)) void {
this.res.window.focus();
}
/// Returns the width of the window in logical pixel units.
pub fn getWidth(this: ThisResource(.CsWindow)) u32 {
return this.res.window.getWidth();
}
/// Returns the height of the window in logical pixel units.
pub fn getHeight(this: ThisResource(.CsWindow)) u32 {
return this.res.window.getWidth();
}
/// Sets the window's title.
/// @param title
pub fn setTitle(this: ThisResource(.CsWindow), title: []const u8) void {
this.res.window.setTitle(title);
}
/// Gets the window's title.
/// @param title
pub fn getTitle(rt: *RuntimeContext, this: ThisResource(.CsWindow)) ds.Box([]const u8) {
const title = this.res.window.getTitle(rt.alloc);
return ds.Box([]const u8).init(rt.alloc, title);
}
/// Resizes the window.
/// @param width
/// @param height
pub fn resize(this: ThisResource(.CsWindow), width: u32, height: u32) void {
this.res.window.resize(width, height);
}
};
};
fn readInternal(alloc: std.mem.Allocator, path: []const u8) Error![]const u8 {
return std.fs.cwd().readFileAlloc(alloc, path, 1e12) catch |err| switch (err) {
error.FileNotFound => return error.FileNotFound,
error.IsDir => return error.IsDir,
else => {
log.debug("unknown error: {}", .{err});
unreachable;
}
};
}
/// @title File System
/// @name files
/// @ns cs.files
/// Provides a cross platform API to create and manage files.
/// Functions with path params can be absolute or relative to the cwd.
pub const cs_files = struct {
/// Reads a file as raw bytes.
/// Returns the contents on success or null.
/// @param path
pub fn read(rt: *RuntimeContext, path: []const u8) Error!ManagedStruct(Uint8Array) {
const res = try readInternal(rt.alloc, path);
return ManagedStruct(Uint8Array).init(rt.alloc, Uint8Array{ .buf = res });
}
/// @param path
pub fn readAsync(rt: *RuntimeContext, path: []const u8) v8.Promise {
const args = dupeArgs(rt.alloc, read, .{ rt, path });
return runtime.invokeFuncAsync(rt, read, args);
}
/// Reads a file as a UTF-8 string.
/// Returns the contents on success or null.
/// @param path
pub fn readText(rt: *RuntimeContext, path: []const u8) Error!ds.Box([]const u8) {
const res = std.fs.cwd().readFileAlloc(rt.alloc, path, 1e12) catch |err| switch (err) {
// Whitelist errors to silence.
error.FileNotFound => return error.FileNotFound,
error.IsDir => return error.IsDir,
else => {
log.debug("unknown error: {}", .{err});
unreachable;
}
};
return ds.Box([]const u8).init(rt.alloc, res);
}
/// @param path
pub fn readTextAsync(rt: *RuntimeContext, path: []const u8) v8.Promise {
const args = dupeArgs(rt.alloc, readText, .{ rt, path });
return runtime.invokeFuncAsync(rt, readText, args);
}
/// Writes raw bytes to a file. If the file already exists, it's replaced.
/// Returns true on success or false.
/// @param path
/// @param buffer
pub fn write(path: []const u8, arr: Uint8Array) bool {
std.fs.cwd().writeFile(path, arr.buf) catch return false;
return true;
}
/// @param path
/// @param buffer
pub fn writeAsync(rt: *RuntimeContext, path: []const u8, arr: Uint8Array) v8.Promise {
const args = dupeArgs(rt.alloc, write, .{ path, arr });
return runtime.invokeFuncAsync(rt, write, args);
}
/// Writes UTF-8 text to a file. If the file already exists, it's replaced.
/// Returns true on success or false.
/// @param path
/// @param str
pub fn writeText(path: []const u8, str: []const u8) bool {
std.fs.cwd().writeFile(path, str) catch return false;
return true;
}
/// @param path
/// @param str
pub fn writeTextAsync(rt: *RuntimeContext, path: []const u8, str: []const u8) v8.Promise {
const args = dupeArgs(rt.alloc, writeText, .{ path, str });
return runtime.invokeFuncAsync(rt, writeText, args);
}
/// Appends raw bytes to a file. File is created if it doesn't exist.
/// Returns true on success or false.
/// @param path
/// @param buffer
pub fn append(path: []const u8, arr: Uint8Array) bool {
stdx.fs.appendFile(path, arr.buf) catch return false;
return true;
}
/// @param path
/// @param buffer
pub fn appendAsync(rt: *RuntimeContext, path: []const u8, arr: Uint8Array) v8.Promise {
const args = dupeArgs(rt.alloc, append, .{ path, arr });
return runtime.invokeFuncAsync(rt, append, args);
}
/// Appends UTF-8 text to a file. File is created if it doesn't exist.
/// Returns true on success or false.
/// @param path
/// @param str
pub fn appendText(path: []const u8, str: []const u8) bool {
stdx.fs.appendFile(path, str) catch return false;
return true;
}
/// @param path
/// @param str
pub fn appendTextAsync(rt: *RuntimeContext, path: []const u8, str: []const u8) v8.Promise {
const args = dupeArgs(rt.alloc, appendText, .{ path, str });
return runtime.invokeFuncAsync(rt, appendText, args);
}
/// Copies a file.
/// @param from
/// @param to
pub fn copy(from: []const u8, to: []const u8) bool {
std.fs.cwd().copyFile(from, std.fs.cwd(), to, .{}) catch return false;
return true;
}
/// @param from
/// @param to
pub fn copyAsync(rt: *RuntimeContext, from: []const u8, to: []const u8) v8.Promise {
const args = dupeArgs(rt.alloc, copy, .{ from, to });
return runtime.invokeFuncAsync(rt, copy, args);
}
/// Moves a file.
/// @param from
/// @param to
pub fn move(from: []const u8, to: []const u8) bool {
std.fs.cwd().rename(from, to) catch return false;
return true;
}
/// @param from
/// @param to
pub fn moveAsync(rt: *RuntimeContext, from: []const u8, to: []const u8) v8.Promise {
const args = dupeArgs(rt.alloc, move, .{ from, to });
return runtime.invokeFuncAsync(rt, move, args);
}
/// Returns the absolute path of the current working directory.
pub fn cwd(rt: *RuntimeContext) ?ds.Box([]const u8) {
const cwd_ = std.process.getCwdAlloc(rt.alloc) catch return null;
return ds.Box([]const u8).init(rt.alloc, cwd_);
}
/// Returns info about a file, folder, or special object at a given path.
/// @param path
pub fn getPathInfo(path: []const u8) Error!PathInfo {
// TODO: statFile opens the file first so it doesn't detect symlink.
const stat = std.fs.cwd().statFile(path) catch |err| {
return switch (err) {
error.FileNotFound => error.FileNotFound,
else => {
log.debug("unknown error: {}", .{err});
unreachable;
},
};
};
return PathInfo{
.kind = @intToEnum(FileKind, @enumToInt(stat.kind)),
.atime = @intCast(F64SafeUint, @divFloor(stat.atime, 1_000_000)),
.mtime = @intCast(F64SafeUint, @divFloor(stat.mtime, 1_000_000)),
.ctime = @intCast(F64SafeUint, @divFloor(stat.ctime, 1_000_000)),
};
}
/// @param path
pub fn getPathInfoAsync(rt: *RuntimeContext, path: []const u8) v8.Promise {
const args = dupeArgs(rt.alloc, getPathInfo, .{ path });
return runtime.invokeFuncAsync(rt, getPathInfo, args);
}
pub const FileKind = enum(u4) {
blockDevice = @enumToInt(std.fs.File.Kind.BlockDevice),
characterDevice = @enumToInt(std.fs.File.Kind.CharacterDevice),
directory = @enumToInt(std.fs.File.Kind.Directory),
namedPipe = @enumToInt(std.fs.File.Kind.NamedPipe),
symLink = @enumToInt(std.fs.File.Kind.SymLink),
file = @enumToInt(std.fs.File.Kind.File),
unixDomainSocket = @enumToInt(std.fs.File.Kind.UnixDomainSocket),
whiteout = @enumToInt(std.fs.File.Kind.Whiteout),
door = @enumToInt(std.fs.File.Kind.Door),
eventPort = @enumToInt(std.fs.File.Kind.EventPort),
unknown = @enumToInt(std.fs.File.Kind.Unknown),
};
pub const PathInfo = struct {
kind: FileKind,
// Last access time in milliseconds since the unix epoch.
atime: F64SafeUint,
// Last modified time in milliseconds since the unix epoch.
mtime: F64SafeUint,
// Created time in milliseconds since the unix epoch.
ctime: F64SafeUint,
};
/// List the files in a directory. This is not recursive.
/// @param path
pub fn listDir(rt: *RuntimeContext, path: []const u8) ?ManagedSlice(FileEntry) {
var dir = std.fs.cwd().openDir(path, .{ .iterate = true }) catch return null;
defer dir.close();
var iter = dir.iterate();
var buf = std.ArrayList(FileEntry).init(rt.alloc);
while (iter.next() catch unreachable) |entry| {
buf.append(.{
.name = rt.alloc.dupe(u8, entry.name) catch unreachable,
.kind = @tagName(entry.kind),
}) catch unreachable;
}
return ManagedSlice(FileEntry){
.alloc = rt.alloc,
.slice = buf.toOwnedSlice(),
};
}
/// @param path
pub fn listDirAsync(rt: *RuntimeContext, path: []const u8) v8.Promise {
const args = dupeArgs(rt.alloc, listDir, .{ rt, path });
return runtime.invokeFuncAsync(rt, listDir, args);
}
pub const FileEntry = struct {
name: []const u8,
// This will be static memory.
kind: []const u8,
/// @internal
pub fn deinit(self: @This(), alloc: std.mem.Allocator) void {
alloc.free(self.name);
}
};
/// Ensures that a path exists by creating parent directories as necessary.
/// @param path
pub fn ensurePath(rt: *RuntimeContext, path: []const u8) bool {
std.fs.cwd().makePath(path) catch |err| switch (err) {
else => {
v8x.throwErrorExceptionFmt(rt.alloc, rt.isolate, "{}", .{err});
return false;
},
};
return true;
}
/// @param path
pub fn ensurePathAsync(rt: *RuntimeContext, path: []const u8) v8.Promise {
const args = dupeArgs(rt.alloc, ensurePath, .{ rt, path });
return runtime.invokeFuncAsync(rt, ensurePath, args);
}
/// Returns whether something exists at a path.
/// @param path
pub fn pathExists(rt: *RuntimeContext, path: []const u8) bool {
return stdx.fs.pathExists(path) catch |err| {
v8x.throwErrorExceptionFmt(rt.alloc, rt.isolate, "{}", .{err});
return false;
};
}
/// @param path
pub fn pathExistsAsync(rt: *RuntimeContext, path: []const u8) v8.Promise {
const args = dupeArgs(rt.alloc, pathExists, .{ rt, path });
return runtime.invokeFuncAsync(rt, pathExists, args);
}
/// Removes a file.
/// @param path
pub fn remove(path: []const u8) bool {
std.fs.cwd().deleteFile(path) catch return false;
return true;
}
/// @param path
pub fn removeAsync(rt: *RuntimeContext, path: []const u8) v8.Promise {
const args = dupeArgs(rt.alloc, remove, .{ path });
return runtime.invokeFuncAsync(rt, remove, args);
}
/// Removes a directory.
/// @param path
/// @param recursive
pub fn removeDir(path: []const u8, recursive: bool) bool {
if (recursive) {
std.fs.cwd().deleteTree(path) catch |err| {
if (builtin.os.tag == .windows and err == error.FileBusy) {
// If files were deleted, the root directory remains and returns FileBusy, so try again.
std.fs.cwd().deleteDir(path) catch return false;
return true;
}
return false;
};
} else {
std.fs.cwd().deleteDir(path) catch return false;
if (builtin.os.tag == .windows) {
// Underlying NtCreateFile call returns success when it ignores a recursive directory.
// For now, check that it doesn't exist.
const exists = stdx.fs.pathExists(path) catch return false;
return !exists;
}
}
return true;
}
/// @param path
/// @param recursive
pub fn removeDirAsync(rt: *RuntimeContext, path: []const u8, recursive: bool) v8.Promise {
const args = dupeArgs(rt.alloc, removeDir, .{ path, recursive });
return runtime.invokeFuncAsync(rt, removeDir, args);
}
/// Expands relative pathing such as '..' from the cwd and returns an absolute path.
/// See realPath to resolve symbolic links.
/// @param path
pub fn expandPath(rt: *RuntimeContext, path: []const u8) ds.Box([]const u8) {
const res = std.fs.path.resolve(rt.alloc, &.{path}) catch |err| {
log.debug("unknown error: {}", .{err});
unreachable;
};
return ds.Box([]const u8).init(rt.alloc, res);
}
/// Expands relative pathing from the cwd and resolves symbolic links.
/// Returns the canonicalized absolute path.
/// Path provided must point to a filesystem object.
/// @param path
pub fn realPath(rt: *RuntimeContext, path: []const u8) Error!ds.Box([]const u8) {
const res = std.fs.realpathAlloc(rt.alloc, path) catch |err| {
return switch (err) {
error.FileNotFound => error.FileNotFound,
else => {
log.debug("unknown error: {}", .{err});
unreachable;
},
};
};
return ds.Box([] const u8).init(rt.alloc, res);
}
/// Creates a symbolic link (a soft link) at symPath to an existing or nonexisting file at targetPath.
/// @param symPath
/// @param targetPath
pub fn symLink(sym_path: []const u8, target_path: []const u8) Error!void {
if (builtin.os.tag == .windows) {
return error.Unsupported;
}
std.os.symlink(target_path, sym_path) catch |err| {
return switch(err) {
error.PathAlreadyExists => error.PathExists,
else => {
log.debug("unknown error: {}", .{err});
unreachable;
},
};
};
}
};
/// @title HTTP Client and Server
/// @name http
/// @ns cs.http
/// Provides an API to make HTTP requests and host HTTP servers. HTTPS is supported.
/// There are plans to support WebSockets.
pub const cs_http = struct {
/// Makes a GET request and returns the response body text if successful.
/// Returns false if there was a connection error, timeout error (30 secs), or the response code is 5xx.
/// Advanced: cs.http.request
/// @param url
pub fn get(rt: *RuntimeContext, url: []const u8) ?ds.Box([]const u8) {
const opts = RequestOptions{
.method = .Get,
.timeout = 30,
.keepConnection = false,
};
return simpleRequest(rt, url, opts);
}
/// @param url
pub fn getAsync(rt: *RuntimeContext, url: []const u8) v8.Promise {
const opts = RequestOptions{
.method = .Get,
.timeout = 30,
.keepConnection = false,
};
return requestAsyncInternal(rt, url, opts, false);
}
/// Makes a POST request and returns the response body text if successful.
/// Returns false if there was a connection error, timeout error (30 secs), or the response code is 5xx.
/// Advanced: cs.http.request
/// @param url
/// @param body
pub fn post(rt: *RuntimeContext, url: []const u8, body: []const u8) ?ds.Box([]const u8) {
const opts = RequestOptions{
.method = .Post,
.body = body,
.timeout = 30,
.keepConnection = false,
};
return simpleRequest(rt, url, opts);
}
/// @param url
/// @param body
pub fn postAsync(rt: *RuntimeContext, url: []const u8, body: []const u8) v8.Promise {
const opts = RequestOptions{
.method = .Post,
.body = body,
.timeout = 30,
.keepConnection = false,
};
return requestAsyncInternal(rt, url, opts, false);
}
fn simpleRequest(rt: *RuntimeContext, url: []const u8, opts: RequestOptions) ?ds.Box([]const u8) {
const std_opts = toStdRequestOptions(opts);
const resp = stdx.http.request(rt.alloc, url, std_opts) catch return null;
defer resp.deinit(rt.alloc);
if (resp.status_code < 500) {
return ds.Box([]const u8).init(rt.alloc, rt.alloc.dupe(u8, resp.body) catch unreachable);
} else {
return null;
}
}
/// detailed=false will just return the body text.
/// detailed=true will return the entire response object.
fn requestAsyncInternal(rt: *RuntimeContext, url: []const u8, opts: RequestOptions, comptime detailed: bool) v8.Promise {
const iso = rt.isolate;
const resolver = iso.initPersistent(v8.PromiseResolver, v8.PromiseResolver.init(rt.getContext()));
const promise = resolver.inner.getPromise();
const promise_id = rt.promises.add(resolver) catch unreachable;
const S = struct {
fn onSuccess(ptr: *anyopaque, resp: stdx.http.Response) void {
const ctx = stdx.mem.ptrCastAlign(*RuntimeValue(PromiseId), ptr);
const pid = ctx.inner;
if (detailed) {
runtime.resolvePromise(ctx.rt, pid, resp);
} else {
runtime.resolvePromise(ctx.rt, pid, resp.body);
}
resp.deinit(ctx.rt.alloc);
}
fn onFailure(ctx: RuntimeValue(PromiseId), err: Error) void {
const _promise_id = ctx.inner;
const js_err = runtime.createPromiseError(ctx.rt, err);
runtime.rejectPromise(ctx.rt, _promise_id, js_err);
}
fn onCurlFailure(ptr: *anyopaque, curle_err: u32) void {
const ctx = stdx.mem.ptrCastAlign(*RuntimeValue(PromiseId), ptr).*;
const cs_err = switch (curle_err) {
curl.CURLE_COULDNT_CONNECT => error.ConnectFailed,
curl.CURLE_PEER_FAILED_VERIFICATION => error.CertVerify,
curl.CURLE_SSL_CACERT_BADFILE => error.CertBadFile,
curl.CURLE_COULDNT_RESOLVE_HOST => error.CantResolveHost,
else => b: {
log.debug("curl unknown error: {}", .{curle_err});
break :b error.Unknown;
},
};
onFailure(ctx, cs_err);
}
};
const ctx = RuntimeValue(PromiseId){
.rt = rt,
.inner = promise_id,
};
const std_opts = toStdRequestOptions(opts);
// Catch any immediate errors as well as async errors.
stdx.http.requestAsync(rt.alloc, url, std_opts, ctx, S.onSuccess, S.onCurlFailure) catch |err| switch (err) {
else => {
log.debug("unknown error: {}", .{err});
S.onFailure(ctx, error.Unknown);
}
};
return promise;
}
fn toStdRequestOptions(opts: RequestOptions) stdx.http.RequestOptions {
var res = stdx.http.RequestOptions{
.method = std.meta.stringToEnum(stdx.http.RequestMethod, @tagName(opts.method)).?,
.body = opts.body,
.keep_connection = opts.keepConnection,
.timeout = opts.timeout,
.headers = opts.headers,
.cert_file = opts.certFile,
};
if (opts.contentType) |content_type| {
res.content_type = std.meta.stringToEnum(stdx.http.ContentType, @tagName(content_type)).?;
}
return res;
}
/// Returns Response object if request was successful.
/// Throws exception if there was a connection or protocol error.
/// @param url
/// @param options
pub fn request(rt: *RuntimeContext, url: []const u8, mb_opts: ?RequestOptions) !ManagedStruct(stdx.http.Response) {
const opts = mb_opts orelse RequestOptions{};
const std_opts = toStdRequestOptions(opts);
const resp = try stdx.http.request(rt.alloc, url, std_opts);
return ManagedStruct(stdx.http.Response){
.alloc = rt.alloc,
.val = resp,
};
}
/// @param url
/// @param options
pub fn requestAsync(rt: *RuntimeContext, url: []const u8, mb_opts: ?RequestOptions) PromiseSkipJsGen {
const opts = mb_opts orelse RequestOptions{};
return .{ .inner = requestAsyncInternal(rt, url, opts, true) };
}
pub const RequestMethod = enum {
pub const IsStringSumType = true;
Head,
Get,
Post,
Put,
Delete,
};
pub const ContentType = enum {
pub const IsStringSumType = true;
Json,
FormData,
};
pub const RequestOptions = struct {
method: RequestMethod = .Get,
keepConnection: bool = false,
contentType: ?ContentType = null,
body: ?[]const u8 = null,
/// In seconds. 0 timeout = no timeout
timeout: u32 = 30,
headers: ?std.StringHashMap([]const u8) = null,
// For HTTPS, if no cert file is provided, the default from the current operating system is used.
certFile: ?[]const u8 = null,
};
/// The response object holds the data received from making a HTTP request.
pub const Response = struct {
status: u32,
headers: std.StringHashMap([]const u8),
body: []const u8,
};
/// Starts a HTTP server and returns the handle.
/// @param host
/// @param port
pub fn serveHttp(rt: *RuntimeContext, host: []const u8, port: u16) !v8.Object {
// log.debug("serving http at {s}:{}", .{host, port});
// TODO: Implement "cosmic serve-http" and "cosmic serve-https" cli utilities.
const handle = rt.createCsHttpServerResource();
const server = handle.ptr;
server.init(rt);
try server.startHttp(host, port);
const ctx = rt.getContext();
const js_handle = rt.http_server_class.inner.getFunction(ctx).initInstance(ctx, &.{}).?;
js_handle.setInternalField(0, rt.isolate.initIntegerU32(handle.id));
return js_handle;
}
/// Starts a HTTPS server and returns the handle.
/// @param host
/// @param port
/// @param certPath
/// @param keyPath
pub fn serveHttps(rt: *RuntimeContext, host: []const u8, port: u16, cert_path: []const u8, key_path: []const u8) Error!v8.Object {
const handle = rt.createCsHttpServerResource();
const server = handle.ptr;
server.init(rt);
server.startHttps(host, port, cert_path, key_path) catch |err| switch (err) {
else => {
log.debug("unknown error: {}", .{err});
return error.Unknown;
}
};
const ctx = rt.getContext();
const js_handle = rt.http_server_class.inner.getFunction(ctx).initInstance(ctx, &.{}).?;
js_handle.setInternalField(0, rt.isolate.initIntegerU32(handle.id));
return js_handle;
}
/// Provides an interface to the underlying server handle.
pub const Server = struct {
/// Sets the handler for receiving requests.
/// @param callback
pub fn setHandler(rt: *RuntimeContext, this: ThisResource(.CsHttpServer), handler: v8.Function) void {
this.res.js_handler = rt.isolate.initPersistent(v8.Function, handler);
}
/// Request the server to close. It will gracefully shutdown in the background.
pub fn requestClose(rt: *RuntimeContext, this: ThisResource(.CsHttpServer)) void {
rt.startDeinitResourceHandle(this.res_id);
}
/// Requests the server to close. The promise will resolve when it's done.
pub fn closeAsync(rt: *RuntimeContext, this: ThisResource(.CsHttpServer)) v8.Promise {
const iso = rt.isolate;
const resolver = iso.initPersistent(v8.PromiseResolver, v8.PromiseResolver.init(rt.getContext()));
const promise = resolver.inner.getPromise();
const promise_id = rt.promises.add(resolver) catch unreachable;
const S = struct {
const Context = struct {
rt: *RuntimeContext,
promise_id: PromiseId,
};
fn onDeinit(ptr: *anyopaque, _: ResourceId) void {
const ctx = stdx.mem.ptrCastAlign(*Context, ptr);
runtime.resolvePromise(ctx.rt, ctx.promise_id, ctx.rt.js_true);
ctx.rt.alloc.destroy(ctx);
}
};
const ctx = rt.alloc.create(S.Context) catch unreachable;
ctx.* = .{
.rt = rt,
.promise_id = promise_id,
};
const cb = stdx.Callback(*anyopaque, ResourceId).init(ctx, S.onDeinit);
rt.resources.getPtrNoCheck(this.res_id).on_deinit_cb = cb;
rt.startDeinitResourceHandle(this.res_id);
return promise;
}
pub fn getBindAddress(rt: *RuntimeContext, this: ThisResource(.CsHttpServer)) RtTempStruct(Address) {
const addr = this.res.allocBindAddress(rt.alloc);
return RtTempStruct(Address).init(.{
.host = addr.host,
.port = addr.port,
});
}
};
pub const Address = struct {
host: []const u8,
port: u32,
/// @internal
pub fn deinit(self: @This(), alloc: std.mem.Allocator) void {
alloc.free(self.host);
}
};
/// Provides an interface to the current response writer.
pub const ResponseWriter = struct {
/// @param status
pub fn setStatus(status_code: u32) void {
_server.ResponseWriter.setStatus(status_code);
}
/// @param key
/// @param value
pub fn setHeader(key: []const u8, value: []const u8) void {
_server.ResponseWriter.setHeader(key, value);
}
/// Sends UTF-8 text to the response.
/// @param text
pub fn send(text: []const u8) void {
_server.ResponseWriter.send(text);
}
/// Sends raw bytes to the response.
/// @param buffer
pub fn sendBytes(arr: runtime.Uint8Array) void {
_server.ResponseWriter.sendBytes(arr);
}
};
/// Holds data about the request when hosting an HTTP server.
pub const Request = struct {
method: RequestMethod,
path: []const u8,
data: Uint8Array,
};
};
/// @title Core
/// @name core
/// @ns cs.core
/// Contains common utilities. All functions here are also available in the global scope. You can call them directly without the cs.core prefix.
pub const cs_core = struct {
/// Whether print should also output to stdout in devmode.
const DevModeToStdout = true;
/// Returns an array of arguments used to start the process in the command line.
pub fn getCliArgs(rt: *RuntimeContext) v8.Array {
const args = std.process.argsAlloc(rt.alloc) catch unreachable;
defer std.process.argsFree(rt.alloc, args);
const args_slice: []const []const u8 = args;
return rt.getJsValue(args_slice).castTo(v8.Array);
}
/// Prints any number of variables as strings separated by " ".
/// @param args
pub fn print(raw_info: ?*const v8.C_FunctionCallbackInfo) callconv(.C) void {
const info = v8.FunctionCallbackInfo.initFromV8(raw_info);
printInternal(info, false, false);
}
pub fn print_DEV(raw_info: ?*const v8.C_FunctionCallbackInfo) callconv(.C) void {
const info = v8.FunctionCallbackInfo.initFromV8(raw_info);
printInternal(info, true, false);
}
inline fn printInternal(info: v8.FunctionCallbackInfo, comptime DevMode: bool, comptime Dump: bool) void {
const rt = stdx.mem.ptrCastAlign(*RuntimeContext, info.getExternalValue());
printInternal2(rt, info, DevMode, Dump);
}
fn printInternal2(rt: *RuntimeContext, info: v8.FunctionCallbackInfo, comptime DevMode: bool, comptime Dump: bool) void {
const len = info.length();
const iso = rt.isolate;
const ctx = rt.getContext();
var hscope: v8.HandleScope = undefined;
hscope.init(iso);
defer hscope.deinit();
if (len > 0) {
const str = if (Dump) v8x.allocValueDump(rt.alloc, iso, ctx, info.getArg(0))
else v8x.allocValueAsUtf8(rt.alloc, iso, ctx, info.getArg(0));
defer rt.alloc.free(str);
if (!DevMode or DevModeToStdout) {
rt.env.printFmt("{s}", .{str});
}
if (DevMode) {
rt.dev_ctx.printFmt("{s}", .{str});
}
}
var i: u32 = 1;
while (i < len) : (i += 1) {
const str = if (Dump) v8x.allocValueDump(rt.alloc, iso, ctx, info.getArg(i))
else v8x.allocValueAsUtf8(rt.alloc, iso, ctx, info.getArg(i));
defer rt.alloc.free(str);
if (!DevMode or DevModeToStdout) {
rt.env.printFmt(" {s}", .{str});
}
if (DevMode) {
rt.dev_ctx.printFmt(" {s}", .{str});
}
}
}
/// Prints any number of variables as strings separated by " ". Wraps to the next line.
/// @param args
pub fn puts(raw_info: ?*const v8.C_FunctionCallbackInfo) callconv(.C) void {
const info = v8.FunctionCallbackInfo.initFromV8(raw_info);
const rt = stdx.mem.ptrCastAlign(*RuntimeContext, info.getExternalValue());
printInternal2(rt, info, false, false);
rt.env.printFmt("\n", .{});
}
pub fn puts_DEV(raw_info: ?*const v8.C_FunctionCallbackInfo) callconv(.C) void {
const info = v8.FunctionCallbackInfo.initFromV8(raw_info);
const rt = stdx.mem.ptrCastAlign(*RuntimeContext, info.getExternalValue());
printInternal2(rt, info, true, false);
if (DevModeToStdout) {
rt.env.printFmt("\n", .{});
}
rt.dev_ctx.print("\n");
}
/// Prints a descriptive string of the js value(s) separated by " ". Wraps to the next line.
/// @param args
pub fn dump(raw_info: ?*const v8.C_FunctionCallbackInfo) callconv(.C) void {
const info = v8.FunctionCallbackInfo.initFromV8(raw_info);
const rt = stdx.mem.ptrCastAlign(*RuntimeContext, info.getExternalValue());
printInternal2(rt, info, false, true);
rt.env.printFmt("\n", .{});
}
pub fn dump_DEV(raw_info: ?*const v8.C_FunctionCallbackInfo) callconv(.C) void {
const info = v8.FunctionCallbackInfo.initFromV8(raw_info);
const rt = stdx.mem.ptrCastAlign(*RuntimeContext, info.getExternalValue());
printInternal2(rt, info, true, true);
if (DevModeToStdout) {
rt.env.printFmt("\n", .{});
}
rt.dev_ctx.print("\n");
}
/// Reads input from the command line until a new line returned.
pub fn gets(rt: *RuntimeContext) ds.Box([]const u8) {
const str = std.io.getStdIn().reader().readUntilDelimiterAlloc(rt.alloc, '\n', 1e9) catch |err| {
if (err == error.EndOfStream) {
}
log.debug("unexpected: {}", .{err});
unreachable;
};
return ds.Box([]const u8).init(rt.alloc, str);
}
/// Returns the current timestamp since the runtime started in nanoseconds.
pub fn timerNow(rt: *RuntimeContext) u64 {
return rt.timer.watch.read();
}
/// Converts a buffer to a UTF-8 string.
/// @param buffer
pub fn bufferToUtf8(buf: v8.Uint8Array) ?[]const u8 {
var shared_ptr_store = v8.ArrayBufferView.castFrom(buf).getBuffer().getBackingStore();
defer v8.BackingStore.sharedPtrReset(&shared_ptr_store);
const store = v8.BackingStore.sharedPtrGet(&shared_ptr_store);
const len = store.getByteLength();
if (len > 0) {
const ptr = @ptrCast([*]u8, store.getData().?);
if (std.unicode.utf8ValidateSlice(ptr[0..len])) {
return ptr[0..len];
} else return null;
} else return "";
}
/// Create a fast random number generator for a given seed. This should not be used for cryptographically secure random numbers.
/// @param seed
pub fn createRandom(rt: *RuntimeContext, seed: u64) v8.Object {
const rand = rt.alloc.create(CsRandom) catch unreachable;
rand.* = .{
.impl = std.rand.DefaultPrng.init(seed),
.iface = undefined,
};
rand.iface = rand.impl.random();
return runtime.createWeakHandle(rt, .Random, rand);
}
/// Invoke a callback after a timeout in milliseconds.
/// @param timeout
/// @param callback
/// @param callbackArg
pub fn setTimeout(rt: *RuntimeContext, timeout: u32, cb: v8.Function, cb_arg: ?v8.Value) u32 {
const p_cb = rt.isolate.initPersistent(v8.Function, cb);
if (cb_arg) |cb_arg_| {
const p_cb_arg = rt.isolate.initPersistent(v8.Value, cb_arg_);
return rt.timer.setTimeout(timeout, p_cb, p_cb_arg) catch unreachable;
} else {
return rt.timer.setTimeout(timeout, p_cb, null) catch unreachable;
}
}
/// Returns the absolute path of the main script.
pub fn getMainScriptPath(rt: *RuntimeContext) Error![]const u8 {
if (rt.main_script_path) |path| {
return path;
} else {
log.debug("Did not expect null main script path.", .{});
return error.Unknown;
}
}
/// Returns the absolute path of the main script's directory. Does not include an ending slash.
/// This is useful if you have additional source or assets that depends on the location of your main script.
pub fn getMainScriptDir(rt: *RuntimeContext) Error![]const u8 {
if (rt.main_script_path) |path| {
return std.fs.path.dirname(path) orelse unreachable;
} else {
log.debug("Did not expect null main script path.", .{});
return error.Unknown;
}
}
/// Given an app name, returns the platform's app directory to read/write files to.
/// This does not ensure that the directory exists. See cs.files.ensurePath.
pub fn getAppDir(rt: *RuntimeContext, app_name: []const u8) ?ds.Box([]const u8) {
const dir = std.fs.getAppDataDir(rt.alloc, app_name) catch return null;
return ds.Box([]const u8).init(rt.alloc, dir);
}
/// Get the current clipboard text.
pub fn getClipboardText(rt: *RuntimeContext) Error!ds.Box([]const u8) {
// Requires video device to be initialized.
sdl.ensureVideoInit() catch return error.Unknown;
const text = sdl.SDL_GetClipboardText();
defer sdl.SDL_free(text);
const dupe = rt.alloc.dupe(u8, std.mem.span(text)) catch unreachable;
return ds.Box([]const u8).init(rt.alloc, dupe);
}
/// Set the current clipboard text.
/// @param text
pub fn setClipboardText(rt: *RuntimeContext, text: []const u8) Error!void {
sdl.ensureVideoInit() catch return error.Unknown;
const cstr = std.cstr.addNullByte(rt.alloc, text) catch unreachable;
defer rt.alloc.free(cstr);
const res = sdl.SDL_SetClipboardText(cstr);
if (res != 0) {
log.debug("unknown error: {} {s}", .{res, sdl.SDL_GetError()});
return error.Unknown;
}
}
/// Prints the current stack trace and exits the program with an error code.
/// This is useful to short circuit your program.
/// @param msg
pub fn panic(rt: *RuntimeContext, msg: ?[]const u8) void {
const trace = v8.StackTrace.getCurrentStackTrace(rt.isolate, 10);
var buf = std.ArrayList(u8).init(rt.alloc);
const writer = buf.writer();
// Exception message.
writer.writeAll("\n") catch unreachable;
if (msg) |msg_| {
writer.print("Panic: {s}", .{msg_}) catch unreachable;
} else {
writer.writeAll("Panic") catch unreachable;
}
writer.writeAll("\n") catch unreachable;
v8x.appendStackTraceString(&buf, rt.isolate, trace);
rt.env.errorFmt("{s}", .{buf.items});
rt.env.exit(1);
}
/// Terminate the program with a code. Use code=0 for a successful exit and a positive value for an error exit.
/// @param code
pub fn exit(rt: *RuntimeContext, code: u8) void {
rt.env.exit(code);
}
/// Returns the last error code. API calls that return null will set their error code to be queried by errCode() and errString().
pub fn errCode(rt: *RuntimeContext) u32 {
return @enumToInt(std.meta.stringToEnum(CsError, @errorName(rt.last_err)).?);
}
/// Returns an error message for an error code.
pub fn errString(err: CsError) []const u8 {
return switch (err) {
.NoError => "No error.",
.NotAnError => "Not an error.",
else => @tagName(err),
};
}
/// Clears the last error.
pub fn clearError(rt: *RuntimeContext) void {
rt.last_err = error.NoError;
}
/// Returns the host operating system.
pub fn getOs() Os {
switch (builtin.os.tag) {
.linux => return .linux,
.macos => return .macos,
.windows => return .windows,
else => unreachable,
}
}
/// Returns the host operating system and version number as a string.
pub fn getOsVersion(rt: *RuntimeContext) ds.Box([]const u8) {
const info = std.zig.system.NativeTargetInfo.detect(rt.alloc, std.zig.CrossTarget{}) catch unreachable;
const range = info.target.os.getVersionRange();
var str: []const u8 = undefined;
switch (range) {
.none => {},
.semver => {
str = std.fmt.allocPrint(rt.alloc, "{s} {}", .{@tagName(info.target.os.tag), range.semver.min}) catch unreachable;
},
.linux => {
str = std.fmt.allocPrint(rt.alloc, "{s} {}", .{@tagName(info.target.os.tag), range.linux.range.min}) catch unreachable;
},
.windows => {
str = std.fmt.allocPrint(rt.alloc, "{s} {}", .{@tagName(info.target.os.tag), range.windows}) catch unreachable;
},
}
return ds.Box([]const u8).init(rt.alloc, str);
}
/// Returns the host cpu arch and model as a string.
pub fn getCpu(rt: *RuntimeContext) ds.Box([]const u8) {
const info = std.zig.system.NativeTargetInfo.detect(rt.alloc, std.zig.CrossTarget{}) catch unreachable;
const str = std.fmt.allocPrint(rt.alloc, "{} {s}", .{info.target.cpu.arch, info.target.cpu.model.name}) catch unreachable;
return ds.Box([]const u8).init(rt.alloc, str);
}
/// Returns the resource usage of the current process.
pub fn getResourceUsage() ResourceUsage {
const RUSAGE_SELF: i32 = 0;
if (builtin.os.tag == .linux) {
var usage: std.os.linux.rusage = undefined;
if (std.os.linux.getrusage(std.os.linux.rusage.SELF, &usage) != 0) {
unreachable;
}
return .{
.user_time_secs = @intCast(u32, usage.utime.tv_sec),
.user_time_usecs = @intCast(u32, usage.utime.tv_usec),
.sys_time_secs = @intCast(u32, usage.stime.tv_sec),
.sys_time_usecs = @intCast(u32, usage.stime.tv_usec),
.memory = @intCast(F64SafeUint, usage.maxrss),
};
} else if (builtin.os.tag == .windows) {
var creation_time: std.os.windows.FILETIME = undefined;
var exit_time: std.os.windows.FILETIME = undefined;
var kernel_time: std.os.windows.FILETIME = undefined;
var user_time: std.os.windows.FILETIME = undefined;
var pmc: std.os.windows.PROCESS_MEMORY_COUNTERS = undefined;
const process = std.os.windows.kernel32.GetCurrentProcess();
if (!GetProcessTimes(process, &creation_time, &exit_time, &kernel_time, &user_time)) {
log.debug("Failed to get process times.", .{});
unreachable;
}
if (std.os.windows.kernel32.K32GetProcessMemoryInfo(process, &pmc, @sizeOf(std.os.windows.PROCESS_MEMORY_COUNTERS)) == 0) {
log.debug("Failed to get process memory info: {}", .{ std.os.windows.kernel32.GetLastError() });
unreachable;
}
// In 100ns
const user_time_u64 = twoToU64(user_time.dwLowDateTime, user_time.dwHighDateTime);
const kernel_time_u64 = twoToU64(kernel_time.dwLowDateTime, kernel_time.dwHighDateTime);
return .{
.user_time_secs = @intCast(u32, user_time_u64 / 10000000),
.user_time_usecs = @intCast(u32, (user_time_u64 % 10000000) / 10),
.sys_time_secs = @intCast(u32, kernel_time_u64 / 10000000),
.sys_time_usecs = @intCast(u32, (kernel_time_u64 % 10000000) / 10),
.memory = @intCast(F64SafeUint, pmc.PeakWorkingSetSize / 1024),
};
} else {
const usage = std.os.getrusage(RUSAGE_SELF);
return .{
.user_time_secs = @intCast(u32, usage.utime.tv_sec),
.user_time_usecs = @intCast(u32, usage.utime.tv_usec),
.sys_time_secs = @intCast(u32, usage.stime.tv_sec),
.sys_time_usecs = @intCast(u32, usage.stime.tv_usec),
.memory = @intCast(F64SafeUint, usage.maxrss),
};
}
}
/// Invokes the JS engine garbage collector.
pub fn gc(rt: *RuntimeContext) void {
rt.isolate.lowMemoryNotification();
}
pub const Random = struct {
/// Gets the next random number between 0 and 1.
pub fn next(self: ThisHandle(.Random)) f64 {
return self.ptr.iface.float(f64);
}
};
pub const ResourceUsage = struct {
// User cpu time seconds.
user_time_secs: u32,
// User cpu time microseconds.
user_time_usecs: u32,
// System cpu time seconds.
sys_time_secs: u32,
// System cpu time microseconds.
sys_time_usecs: u32,
// Total memory allocated.
memory: F64SafeUint,
};
pub const Os = enum {
linux,
macos,
windows,
web,
};
pub const CsError = enum {
pub const Default = .NotAnError;
NoError,
FileNotFound,
PathExists,
IsDir,
ConnectFailed,
CertVerify,
CertBadFile,
CantResolveHost,
InvalidFormat,
Unsupported,
Unknown,
NotAnError,
};
test "every CsError maps to core.CsError" {
inline for (@typeInfo(Error).ErrorSet.?) |err| {
_ = std.meta.stringToEnum(cs_core.CsError, err.name) orelse std.debug.panic("Missing {s}", .{err.name});
}
}
};
fn twoToU64(lower: u32, higher: u32) u64 {
if (builtin.cpu.arch.endian() == .Little) {
var val: [2]u32 = .{lower, higher};
return @bitCast(u64, val);
} else {
var val: [2]u32 = .{higher, lower};
return @bitCast(u64, val);
}
}
test "twoToU64" {
var num: u64 = std.math.maxInt(u64) - 1;
if (builtin.cpu.arch.endian() == .Little) {
const lower = @ptrCast([*]u32, &num)[0];
try t.eq(lower, std.math.maxInt(u32)-1);
const higher = @ptrCast([*]u32, &num)[1];
try t.eq(higher, std.math.maxInt(u32));
try t.eq(twoToU64(lower, higher), num);
} else {
const lower = @ptrCast([*]u32, &num)[1];
try t.eq(lower, std.math.maxInt(u32));
const higher = @ptrCast([*]u32, &num)[0];
try t.eq(higher, std.math.maxInt(u32)-1);
try t.eq(twoToU64(lower, higher), num);
}
}
extern "kernel32" fn GetProcessTimes(
process: std.os.windows.HANDLE,
creation_time: *std.os.windows.FILETIME,
exit_time: *std.os.windows.FILETIME,
kernel_time: *std.os.windows.FILETIME,
user_time: *std.os.windows.FILETIME,
) bool;
var audio_engine: AudioEngine = undefined;
var audio_engine_inited = false;
fn getAudioEngine() *AudioEngine {
if (!audio_engine_inited) {
audio_engine.init();
audio_engine_inited = true;
}
return &audio_engine;
}
test "getAudioEngine inits once" {
const m = Mock.create();
defer m.destroy();
m.add(.ma_engine_init);
const eng1 = getAudioEngine();
try t.eq(m.getNumCalls(.ma_engine_init), 1);
const eng2 = getAudioEngine();
try t.eq(m.getNumCalls(.ma_engine_init), 1);
try t.eq(eng1, eng2);
}
/// @title Audio Playback and Capture
/// @name audio
/// @ns cs.audio
/// This module provides a cross platform API to decode sound files, capture audio, and play audio.
/// There is support for 3D Spatialization. You can adjust the listener's or sound's position, direction, and velocity.
/// The positions are absolute values in the 3D space.
pub const cs_audio = struct {
fn loadInternal(rt: *RuntimeContext, data: Uint8Array, encoder: StdSound.Encoding) Error!v8.Object {
const engine = getAudioEngine();
const sound = engine.createSound(rt.alloc, encoder, data.buf) catch |err| switch (err) {
error.InvalidFormat => return error.InvalidFormat,
else => {
log.debug("unexpected: {}", .{err});
unreachable;
},
};
return runtime.createWeakHandle(rt, .Sound, sound);
}
/// Decodes .wav data into a Sound handle.
/// @param data
pub fn loadWav(rt: *RuntimeContext, data: Uint8Array) Error!v8.Object {
return try loadInternal(rt, data, .Wav);
}
/// Decodes a .wav file into a Sound handle. File path can be absolute or relative to the cwd.
/// @param path
pub fn loadWavFile(rt: *RuntimeContext, path: []const u8) Error!v8.Object {
const data = try readInternal(rt.alloc, path);
defer rt.alloc.free(data);
return loadWav(rt, Uint8Array{ .buf = data });
}
/// Decodes .mp3 data into a Sound handle.
/// @param data
pub fn loadMp3(rt: *RuntimeContext, data: Uint8Array) Error!v8.Object {
return try loadInternal(rt, data, .Mp3);
}
/// Decodes a .mp3 file into a Sound handle. File path can be absolute or relative to the cwd.
/// @param path
pub fn loadMp3File(rt: *RuntimeContext, path: []const u8) Error!v8.Object {
const data = try readInternal(rt.alloc, path);
defer rt.alloc.free(data);
return loadMp3(rt, Uint8Array{ .buf = data });
}
/// Decodes .flac data into a Sound handle.
/// @param data
pub fn loadFlac(rt: *RuntimeContext, data: Uint8Array) Error!v8.Object {
return try loadInternal(rt, data, .Flac);
}
/// Decodes a .flac file into a Sound handle. File path can be absolute or relative to the cwd.
/// @param path
pub fn loadFlacFile(rt: *RuntimeContext, path: []const u8) Error!v8.Object {
const data = try readInternal(rt.alloc, path);
defer rt.alloc.free(data);
return loadFlac(rt, Uint8Array{ .buf = data });
}
/// Decodes .ogg data into a Sound handle.
/// @param data
pub fn loadOgg(rt: *RuntimeContext, data: Uint8Array) Error!v8.Object {
return try loadInternal(rt, data, .Ogg);
}
/// Decodes a .ogg file into a Sound handle. File path can be absolute or relative to the cwd.
/// @param path
pub fn loadOggFile(rt: *RuntimeContext, path: []const u8) Error!v8.Object {
const data = try readInternal(rt.alloc, path);
defer rt.alloc.free(data);
return loadOgg(rt, Uint8Array{ .buf = data });
}
/// Attempt to decode wav, mp3, flac, or ogg data into a Sound handle.
/// @param data
pub fn load(rt: *RuntimeContext, data: Uint8Array) Error!v8.Object {
return try loadInternal(rt, data, .Unknown);
}
/// Attempt to decode wav, mp3, flac, or ogg file into a Sound handle.
/// File path can be absolute or relative to the cwd.
/// @param path
pub fn loadFile(rt: *RuntimeContext, path: []const u8) Error!v8.Object {
const data = try readInternal(rt.alloc, path);
defer rt.alloc.free(data);
return load(rt, Uint8Array{ .buf = data });
}
/// Sets the listener's position in 3D space.
pub fn setListenerPos(x: f32, y: f32, z: f32) void {
const engine = getAudioEngine();
engine.setListenerPosition(0, .{ .x = x, .y = y, .z = z });
}
/// Returns the listener's position in 3D space.
pub fn getListenerPos() Vec3 {
const engine = getAudioEngine();
return engine.getListenerPosition(0);
}
/// Sets the listener's forward direction in 3D space. See also setListenerUpDir.
/// @param x
/// @param y
/// @param z
pub fn setListenerDir(x: f32, y: f32, z: f32) void {
const engine = getAudioEngine();
engine.setListenerDirection(0, .{ .x = x, .y = y, .z = z });
}
/// Returns the listener's forward direction in 3D space.
pub fn getListenerDir() Vec3 {
const engine = getAudioEngine();
return engine.getListenerDirection(0);
}
/// Sets the listener's up direction in 3D space.
/// @param x
/// @param y
/// @param z
pub fn setListenerUpDir(x: f32, y: f32, z: f32) void {
const engine = getAudioEngine();
engine.setListenerWorldUp(0, .{ .x = x, .y = y, .z = z });
}
/// Returns the listener's up direction in 3D space.
pub fn getListenerUpDir() Vec3 {
const engine = getAudioEngine();
return engine.getListenerWorldUp(0);
}
/// Sets the listener's velocity in 3D space. This is for the doppler effect.
/// @param x
/// @param y
/// @param z
pub fn setListenerVel(x: f32, y: f32, z: f32) void {
const engine = getAudioEngine();
engine.setListenerVelocity(0, .{ .x = x, .y = y, .z = z });
}
/// Returns the listener's velocity in 3D space.
pub fn getListenerVel() Vec3 {
const engine = getAudioEngine();
return engine.getListenerVelocity(0);
}
pub const Sound = struct {
/// Plays the sound. This won't return until the sound is done playing.
pub fn play(self: ThisHandle(.Sound)) void {
self.ptr.play();
}
/// Starts playing the sound in the background. Returns immediately.
/// Playing the sound while it's already playing will rewind to the start and begin playback.
pub fn playBg(self: ThisHandle(.Sound)) void {
self.ptr.playBg();
}
/// Returns whether the sound is playing or looping in the background.
pub fn isPlayingBg(self: ThisHandle(.Sound)) bool {
return self.ptr.isPlayingBg();
}
/// Starts looping the sound in the background.
pub fn loopBg(self: ThisHandle(.Sound)) void {
self.ptr.loopBg();
}
/// Returns whether the sound is looping in the background.
pub fn isLoopingBg(self: ThisHandle(.Sound)) bool {
return self.ptr.isLoopingBg();
}
/// Pauses the playback.
pub fn pauseBg(self: ThisHandle(.Sound)) void {
self.ptr.pauseBg();
}
/// Resumes the playback from the current cursor position.
/// If the cursor is at the end, it will rewind to the start and begin playback.
pub fn resumeBg(self: ThisHandle(.Sound)) void {
self.ptr.resumeBg();
}
/// Stops the playback and rewinds to the start.
pub fn stopBg(self: ThisHandle(.Sound)) void {
self.ptr.stopBg();
}
/// Sets the volume in a positive linear scale. Volume at 0 is muted. 1 is the default value.
/// @param volume
pub fn setVolume(self: ThisHandle(.Sound), volume: f32) void {
self.ptr.setVolume(volume);
}
/// Returns the volume in a positive linear scale.
pub fn getVolume(self: ThisHandle(.Sound)) f32 {
return self.ptr.getVolume();
}
/// Sets the volume with gain in decibels.
/// @param gain
pub fn setGain(self: ThisHandle(.Sound), gain: f32) void {
self.ptr.setGain(gain);
}
/// Gets the gain in decibels.
pub fn getGain(self: ThisHandle(.Sound)) f32 {
return self.ptr.getGain();
}
/// Sets the pitch. A higher value results in a higher pitch and must be greater than 0. Default value is 1.
/// @param pitch
pub fn setPitch(self: ThisHandle(.Sound), pitch: f32) void {
self.ptr.setPitch(pitch);
}
/// Returns the current pitch.
pub fn getPitch(self: ThisHandle(.Sound)) f32 {
return self.ptr.getPitch();
}
/// Sets the stereo pan. Default value is 0.
/// Set to -1 to shift the sound to the left and +1 to shift the sound to the right.
/// @param pan
pub fn setPan(self: ThisHandle(.Sound), pan: f32) void {
self.ptr.setPan(pan);
}
/// Returns the current stereo pan.
pub fn getPan(self: ThisHandle(.Sound)) f32 {
return self.ptr.getPan();
}
/// Returns the length of the sound in pcm frames. Unsupported for ogg.
pub fn getLengthInPcmFrames(self: ThisHandle(.Sound)) Error!u64 {
return self.ptr.getLengthInPcmFrames() catch return error.Unsupported;
}
/// Returns the length of the sound in milliseconds. Unsupported for ogg.
pub fn getLength(self: ThisHandle(.Sound)) Error!u64 {
return self.ptr.getLength() catch return error.Unsupported;
}
/// Returns the current playback position in pcm frames. Unsupported for ogg.
pub fn getCursorPcmFrame(self: ThisHandle(.Sound)) u64 {
return self.ptr.getCursorPcmFrame();
}
/// Seeks to playback position in pcm frames.
/// @param frameIndex
pub fn seekToPcmFrame(self: ThisHandle(.Sound), frame_index: u64) void {
return self.ptr.seekToPcmFrame(frame_index);
}
/// Sets the sound's position in 3D space.
/// @param x
/// @param y
/// @param z
pub fn setPosition(self: ThisHandle(.Sound), x: f32, y: f32, z: f32) void {
self.ptr.setPosition(x, y, z);
}
/// Returns the sound's position in 3D space.
pub fn getPosition(self: ThisHandle(.Sound)) Vec3 {
return self.ptr.getPosition();
}
/// Sets the sound's direction in 3D space.
/// @param x
/// @param y
/// @param z
pub fn setDirection(self: ThisHandle(.Sound), x: f32, y: f32, z: f32) void {
self.ptr.setDirection(x, y, z);
}
/// Returns the sound's direction in 3D space.
pub fn getDirection(self: ThisHandle(.Sound)) Vec3 {
return self.ptr.getDirection();
}
/// Sets the sound's velocity in 3D space. This is for the doppler effect.
/// @param x
/// @param y
/// @param z
pub fn setVelocity(self: ThisHandle(.Sound), x: f32, y: f32, z: f32) void {
self.ptr.setVelocity(x, y, z);
}
/// Returns the sound's velocity in 3D space.
pub fn getVelocity(self: ThisHandle(.Sound)) Vec3 {
return self.ptr.getVelocity();
}
};
};
/// @title User Input
/// @name input
/// @ns cs.input
/// This module provides access to input devices connected to your computer like the keyboard and mouse.
/// You'll need to create a <a href="window.html#create">Window</a> before you can register for events.
pub const cs_input = struct {
pub const MouseDownEvent = struct {
button: MouseButton,
x: i16,
y: i16,
clicks: u8,
};
pub const MouseUpEvent = struct {
button: MouseButton,
x: i16,
y: i16,
clicks: u8,
};
pub const MouseButton = enum(u3) {
left = @enumToInt(platform.MouseButton.Left),
middle = @enumToInt(platform.MouseButton.Middle),
right = @enumToInt(platform.MouseButton.Right),
x1 = @enumToInt(platform.MouseButton.X1),
x2 = @enumToInt(platform.MouseButton.X2),
};
pub const MouseMoveEvent = struct {
x: i16,
y: i16,
};
pub const ResizeEvent = struct {
width: u32,
height: u32,
};
pub const KeyDownEvent = struct {
key: Key,
printChar: []const u8,
isRepeat: bool,
shiftDown: bool,
ctrlDown: bool,
altDown: bool,
metaDown: bool,
};
pub const KeyUpEvent = struct {
key: Key,
printChar: []const u8,
shiftDown: bool,
ctrlDown: bool,
altDown: bool,
metaDown: bool,
};
pub const Key = enum(u8) {
unknown = eint(KeyCode.Unknown),
backspace = eint(KeyCode.Backspace),
tab = eint(KeyCode.Tab),
enter = eint(KeyCode.Enter),
shift = eint(KeyCode.Shift),
controlLeft = eint(KeyCode.ControlLeft),
controlRight = eint(KeyCode.ControlRight),
altLeft = eint(KeyCode.AltLeft),
altRight = eint(KeyCode.AltRight),
pause = eint(KeyCode.Pause),
capsLock = eint(KeyCode.CapsLock),
escape = eint(KeyCode.Escape),
space = eint(KeyCode.Space),
pageUp = eint(KeyCode.PageUp),
pageDown = eint(KeyCode.PageDown),
end = eint(KeyCode.End),
home = eint(KeyCode.Home),
arrowUp = eint(KeyCode.ArrowUp),
arrowLeft = eint(KeyCode.ArrowLeft),
arrowRight = eint(KeyCode.ArrowRight),
arrowDown = eint(KeyCode.ArrowDown),
printScreen = eint(KeyCode.PrintScreen),
insert = eint(KeyCode.Insert),
delete = eint(KeyCode.Delete),
digit0 = eint(KeyCode.Digit0),
digit1 = eint(KeyCode.Digit1),
digit2 = eint(KeyCode.Digit2),
digit3 = eint(KeyCode.Digit3),
digit4 = eint(KeyCode.Digit4),
digit5 = eint(KeyCode.Digit5),
digit6 = eint(KeyCode.Digit6),
digit7 = eint(KeyCode.Digit7),
digit8 = eint(KeyCode.Digit8),
digit9 = eint(KeyCode.Digit9),
a = eint(KeyCode.A),
b = eint(KeyCode.B),
c = eint(KeyCode.C),
d = eint(KeyCode.D),
e = eint(KeyCode.E),
f = eint(KeyCode.F),
g = eint(KeyCode.G),
h = eint(KeyCode.H),
i = eint(KeyCode.I),
j = eint(KeyCode.J),
k = eint(KeyCode.K),
l = eint(KeyCode.L),
m = eint(KeyCode.M),
n = eint(KeyCode.N),
o = eint(KeyCode.O),
p = eint(KeyCode.P),
q = eint(KeyCode.Q),
r = eint(KeyCode.R),
s = eint(KeyCode.S),
t = eint(KeyCode.T),
u = eint(KeyCode.U),
v = eint(KeyCode.V),
w = eint(KeyCode.W),
x = eint(KeyCode.X),
y = eint(KeyCode.Y),
z = eint(KeyCode.Z),
meta = eint(KeyCode.Meta),
contextMenu = eint(KeyCode.ContextMenu),
f1 = eint(KeyCode.F1),
f2 = eint(KeyCode.F2),
f3 = eint(KeyCode.F3),
f4 = eint(KeyCode.F4),
f5 = eint(KeyCode.F5),
f6 = eint(KeyCode.F6),
f7 = eint(KeyCode.F7),
f8 = eint(KeyCode.F8),
f9 = eint(KeyCode.F9),
f10 = eint(KeyCode.F10),
f11 = eint(KeyCode.F11),
f12 = eint(KeyCode.F12),
f13 = eint(KeyCode.F13),
f14 = eint(KeyCode.F14),
f15 = eint(KeyCode.F15),
f16 = eint(KeyCode.F16),
f17 = eint(KeyCode.F17),
f18 = eint(KeyCode.F18),
f19 = eint(KeyCode.F19),
f20 = eint(KeyCode.F20),
f21 = eint(KeyCode.F21),
f22 = eint(KeyCode.F22),
f23 = eint(KeyCode.F23),
f24 = eint(KeyCode.F24),
scrollLock = eint(KeyCode.ScrollLock),
semicolon = eint(KeyCode.Semicolon),
equal = eint(KeyCode.Equal),
comma = eint(KeyCode.Comma),
minus = eint(KeyCode.Minus),
period = eint(KeyCode.Period),
slash = eint(KeyCode.Slash),
backquote = eint(KeyCode.Backquote),
bracketLeft = eint(KeyCode.BracketLeft),
backslash = eint(KeyCode.Backslash),
bracketRight = eint(KeyCode.BracketRight),
quote = eint(KeyCode.Quote),
};
};
fn eint(e: anytype) @typeInfo(@TypeOf(e)).Enum.tag_type {
return @enumToInt(e);
}
pub fn fromStdKeyDownEvent(e: platform.KeyDownEvent) cs_input.KeyDownEvent {
const js_print_char = if (e.getPrintChar()) |print_char| Ascii[print_char..print_char+1] else "";
return .{
.key = @intToEnum(cs_input.Key, @enumToInt(e.code)),
.printChar = js_print_char,
.isRepeat = e.is_repeat,
.shiftDown = e.isShiftPressed(),
.ctrlDown = e.isControlPressed(),
.altDown = e.isAltPressed(),
.metaDown = e.isMetaPressed(),
};
}
pub fn fromStdKeyUpEvent(e: platform.KeyUpEvent) cs_input.KeyUpEvent {
const js_print_char = if (e.getPrintChar()) |print_char| Ascii[print_char..print_char+1] else "";
return .{
.key = @intToEnum(cs_input.Key, @enumToInt(e.code)),
.printChar = js_print_char,
.shiftDown = e.isShiftPressed(),
.ctrlDown = e.isControlPressed(),
.altDown = e.isAltPressed(),
.metaDown = e.isMetaPressed(),
};
}
test "every input.KeyCode maps to cs_input.Key" {
for (std.enums.values(KeyCode)) |code| {
_ = std.meta.intToEnum(cs_input.Key, @enumToInt(code)) catch |err| {
std.debug.panic("Missing {}", .{code});
return err;
};
}
// TODO: Make sure the mapping is correct.
}
const Ascii: [256]u8 = b: {
var res: [256]u8 = undefined;
var i: u32 = 0;
while (i < 256) : (i += 1) {
res[i] = i;
}
break :b res;
};
pub fn fromStdMouseDownEvent(e: platform.MouseDownEvent) cs_input.MouseDownEvent {
return .{
.button = @intToEnum(cs_input.MouseButton, @enumToInt(e.button)),
.x = e.x,
.y = e.y,
.clicks = e.clicks,
};
}
pub fn fromStdMouseUpEvent(e: platform.MouseUpEvent) cs_input.MouseUpEvent {
return .{
.button = @intToEnum(cs_input.MouseButton, @enumToInt(e.button)),
.x = e.x,
.y = e.y,
.clicks = e.clicks,
};
}
pub fn fromStdMouseMoveEvent(e: platform.MouseMoveEvent) cs_input.MouseMoveEvent {
return .{
.x = e.x,
.y = e.y,
};
}
/// @title Networking
/// @name net
/// @ns cs.net
/// There are plans to implement a networking API to allow connecting to another device and hosting a TCP/UDP server.
pub const cs_net = struct {
};
/// @title Testing
/// @name test
/// @ns cs.test
/// The testing API is only avaiable when using the test runner.
pub const cs_test = struct {
/// Creates a test to be run. If the callback is async the test will be run concurrently.
/// @param name
/// @param callback
pub fn create(rt: *RuntimeContext, name: []const u8, cb: v8.Function) void {
// FUTURE: Save test cases and execute them in parallel.
const iso = rt.isolate;
const ctx = rt.getContext();
// Dupe name since we will be invoking functions that could clear the transient string buffer.
const name_dupe = rt.alloc.dupe(u8, name) catch unreachable;
defer rt.alloc.free(name_dupe);
var hscope: v8.HandleScope = undefined;
hscope.init(iso);
defer hscope.deinit();
var try_catch: v8.TryCatch = undefined;
try_catch.init(iso);
defer try_catch.deinit();
rt.num_tests += 1;
if (cb.toValue().isAsyncFunction()) {
// Async test.
rt.num_async_tests += 1;
if (cb.call(ctx, rt.js_undefined, &.{})) |val| {
const promise = val.castTo(v8.Promise);
const data = iso.initExternal(rt);
const on_fulfilled = v8.Function.initWithData(ctx, gen.genJsFuncSync(passAsyncTest), data);
const tmpl = iso.initObjectTemplateDefault();
tmpl.setInternalFieldCount(2);
const extra_data = tmpl.initInstance(ctx);
extra_data.setInternalField(0, data);
extra_data.setInternalField(1, iso.initStringUtf8(name_dupe));
const on_rejected = v8.Function.initWithData(ctx, gen.genJsFunc(reportAsyncTestFailure, .{
.asyncify = false,
.is_data_rt = false,
}), extra_data);
_ = promise.thenAndCatch(ctx, on_fulfilled, on_rejected) catch unreachable;
} else {
const err_str = v8x.allocPrintTryCatchStackTrace(rt.alloc, iso, ctx, try_catch).?;
defer rt.alloc.free(err_str);
rt.env.printFmt("Test: {s}\n{s}", .{ name_dupe, err_str });
}
} else {
// Sync test.
if (cb.call(ctx, rt.js_undefined, &.{})) |_| {
rt.num_tests_passed += 1;
} else {
const err_str = v8x.allocPrintTryCatchStackTrace(rt.alloc, iso, ctx, try_catch).?;
defer rt.alloc.free(err_str);
rt.env.printFmt("Test: {s}\n{s}", .{ name_dupe, err_str });
}
}
}
/// Creates an isolated test to be run. An isolated test runs after all normal tests and are run one by one even if they are async.
/// @param name
/// @param callback
pub fn createIsolated(rt: *RuntimeContext, name: []const u8, cb: v8.Function) void {
if (!cb.toValue().isAsyncFunction()) {
v8x.throwErrorExceptionFmt(rt.alloc, rt.isolate, "Test \"{s}\": Only async tests can use testIsolated.", .{name});
return;
}
rt.num_tests += 1;
// Store the function to be run later.
rt.isolated_tests.append(.{
.name = rt.alloc.dupe(u8, name) catch unreachable,
.js_fn = rt.isolate.initPersistent(v8.Function, cb),
}) catch unreachable;
}
/// Asserts that the actual value equals the expected value.
/// @param act
/// @param exp
pub fn eq(act: v8.Value, exp: v8.Value) void {
_ = act;
_ = exp;
// Js Func.
}
/// Asserts that the actual value does not equal the expected value.
/// @param act
/// @param exp
pub fn neq(act: v8.Value, exp: v8.Value) void {
_ = act;
_ = exp;
// Js Func.
}
/// Asserts that the actual value contains a sub value.
/// For a string, a sub value is a substring.
/// @param act
/// @param needle
pub fn contains(act: v8.Value, needle: v8.Value) void {
_ = act;
_ = needle;
// Js Func.
}
/// Asserts that the anonymous function throws an exception.
/// An optional substring can be provided to check against the exception message.
/// @param func
/// @param expErrorSubStr
pub fn throws(func: v8.Function, exp_str: ?v8.String) void {
_ = func;
_ = exp_str;
// Js Func.
}
};
/// @title Worker Threads
/// @name worker
/// @ns cs.worker
/// There are plans to implement worker threads for Javascript similar to Web Workers.
pub const cs_worker = struct {
};
fn reportAsyncTestFailure(data: FuncData, val: v8.Value) void {
const obj = data.val.castTo(v8.Object);
const rt = stdx.mem.ptrCastAlign(*RuntimeContext, obj.getInternalField(0).castTo(v8.External).get());
const test_name = v8x.allocValueAsUtf8(rt.alloc, rt.isolate, rt.getContext(), obj.getInternalField(1));
defer rt.alloc.free(test_name);
// TODO: report stack trace.
rt.num_async_tests_finished += 1;
const str = v8x.allocValueAsUtf8(rt.alloc, rt.isolate, rt.getContext(), val);
defer rt.alloc.free(str);
rt.env.printFmt("Test Failed: \"{s}\"\n{s}\n", .{test_name, str});
}
fn passAsyncTest(rt: *RuntimeContext) void {
rt.num_async_tests_passed += 1;
rt.num_async_tests_finished += 1;
rt.num_tests_passed += 1;
}
// This function sets up a async endpoint manually for future reference.
// We can also resuse the sync endpoint and run it on the worker thread with ctx.setConstAsyncFuncT.
// fn files_ReadFileAsync(rt: *RuntimeContext, path: []const u8) v8.Promise {
// const iso = rt.isolate;
// const task = tasks.ReadFileTask{
// .alloc = rt.alloc,
// .path = rt.alloc.dupe(u8, path) catch unreachable,
// };
// const resolver = iso.initPersistent(v8.PromiseResolver, v8.PromiseResolver.init(rt.context));
// const promise = resolver.inner.getPromise();
// const promise_id = rt.promises.add(resolver) catch unreachable;
// const S = struct {
// fn onSuccess(ctx: RuntimeValue(PromiseId), _res: TaskOutput(tasks.ReadFileTask)) void {
// const _promise_id = ctx.inner;
// runtime.resolvePromise(ctx.rt, _promise_id, .{
// .handle = ctx.rt.getJsValuePtr(_res),
// });
// }
// fn onFailure(ctx: RuntimeValue(PromiseId), _err: anyerror) void {
// const _promise_id = ctx.inner;
// runtime.rejectPromise(ctx.rt, _promise_id, .{
// .handle = ctx.rt.getJsValuePtr(_err),
// });
// }
// };
// const task_ctx = RuntimeValue(PromiseId){
// .rt = rt,
// .inner = promise_id,
// };
// _ = rt.work_queue.addTaskWithCb(task, task_ctx, S.onSuccess, S.onFailure);
// return promise;
// }
fn dupeArgs(alloc: std.mem.Allocator, comptime Func: anytype, args: anytype) std.meta.ArgsTuple(@TypeOf(Func)) {
const ArgsTuple = std.meta.ArgsTuple(@TypeOf(Func));
const Fields = std.meta.fields(ArgsTuple);
const InputFields = std.meta.fields(@TypeOf(args));
var res: ArgsTuple = undefined;
inline for (Fields) |Field, I| {
if (Field.field_type == []const u8) {
@field(res, Field.name) = alloc.dupe(u8, @field(args, InputFields[I].name)) catch unreachable;
} else {
@field(res, Field.name) = @field(args, InputFields[I].name);
}
}
return res;
}
pub const cs_dev = struct {
pub fn hideHud(rt: *RuntimeContext) void {
rt.dev_ctx.show_hud = false;
}
pub fn showHud(rt: *RuntimeContext) void {
rt.dev_ctx.show_hud = true;
}
}; | runtime/api.zig |
const std = @import("std");
const mem = std.mem;
const default_out = "./colorstorm-out";
const flag_prefix_long = "--";
const flag_prefix_short = "-";
const allocator = std.heap.page_allocator;
var settings = std.BufMap.init(allocator);
pub const Gen = enum { vim, vscode, sublime, atom, iterm2, all };
pub const Flag = enum { outdir, input, gen, help, na };
/// Initializes the CLI bufmap with values that are implicit unless
/// overwritten by the user.
pub fn init() !void {
try settings.put(@tagName(Flag.outdir), default_out);
try settings.put(@tagName(Flag.gen), @tagName(Gen.all));
try settings.put(@tagName(Flag.input), "");
}
/// Parses a command line flag into a valid Flag enum type. Note that
/// the user can provide a long or short version of the flag. For example:
/// "--<flag_name>" or "-<letter>"
/// "--out" or "-o"
pub fn parse_flag(argument: []const u8) Flag {
inline for (std.meta.fields(Flag)) |f| {
if (std.mem.eql(u8, argument, flag_prefix_long ++ f.name) or
std.mem.eql(u8, argument, flag_prefix_short ++ [_]u8{f.name[0]}))
{
return @intToEnum(Flag, f.value);
}
}
return Flag.na;
}
/// Sets or overwrites a flag's value using the user's specified value
pub fn set_flag_val(flag: Flag, argument: []const u8) !void {
if (argument.len == 0) {
return;
}
try settings.put(@tagName(flag), argument);
}
/// Retrieves a flag's default or overwritten value
pub fn get_flag_val(comptime flag: Flag) ?[]const u8 {
return settings.get(@tagName(flag));
}
test "using long and short versions of flag" {
var input_long: []const u8 = "--input";
var input_short: []const u8 = "-i";
var input_flag_long = parse_flag(input_long);
var input_flag_short = parse_flag(input_short);
try std.testing.expect(input_flag_long == input_flag_short);
}
test "check fallback flag value for invalid arguments" {
var bad_input: []const u8 = "--invalid";
var bad_flag = parse_flag(bad_input);
try std.testing.expect(bad_flag == Flag.na);
}
test "set and get flag value" {
var gen_flag: []const u8 = "vim";
try set_flag_val(Flag.gen, gen_flag);
try std.testing.expect(std.mem.eql(u8, get_flag_val(Flag.gen).?, gen_flag));
} | src/cli.zig |
const std = @import("std");
const mach = @import("mach");
const gpu = @import("gpu");
const zm = @import("zmath");
const glfw = @import("glfw");
pub const Vertex = struct {
pos: @Vector(4, f32),
uv: @Vector(2, f32),
};
// Simple triangle
const WINDOW_WIDTH = 640;
const WINDOW_HEIGHT = 480;
const TRIANGLE_SCALE = 250;
const TRIANGLE_HEIGHT = TRIANGLE_SCALE * @sqrt(0.75);
pub const vertices = [_]Vertex{
.{ .pos = .{ WINDOW_WIDTH / 2 + TRIANGLE_SCALE / 2, WINDOW_HEIGHT / 2 + TRIANGLE_HEIGHT, 0, 1 }, .uv = .{ 0.5, 1 } },
.{ .pos = .{ WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2, 0, 1 }, .uv = .{ 0, 0 } },
.{ .pos = .{ WINDOW_WIDTH / 2 + TRIANGLE_SCALE, WINDOW_HEIGHT / 2 + 0, 0, 1 }, .uv = .{ 1, 0 } },
.{ .pos = .{ WINDOW_WIDTH / 2 + TRIANGLE_SCALE / 2, WINDOW_HEIGHT / 2, 0, 1 }, .uv = .{ 0.5, 1 } },
.{ .pos = .{ WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2 - TRIANGLE_HEIGHT, 0, 1 }, .uv = .{ 0, 0 } },
.{ .pos = .{ WINDOW_WIDTH / 2 + TRIANGLE_SCALE, WINDOW_HEIGHT / 2 - TRIANGLE_HEIGHT, 0, 1 }, .uv = .{ 1, 0 } },
.{ .pos = .{ WINDOW_WIDTH / 2 - TRIANGLE_SCALE / 2, WINDOW_HEIGHT / 2 + TRIANGLE_HEIGHT, 0, 1 }, .uv = .{ 0.5, 1 } },
.{ .pos = .{ WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2, 0, 1 }, .uv = .{ 0, 0 } },
.{ .pos = .{ WINDOW_WIDTH / 2 - TRIANGLE_SCALE, WINDOW_HEIGHT / 2 + 0, 0, 1 }, .uv = .{ 1, 0 } },
};
pub const options = mach.Options{ .width = 640, .height = 480 };
// The uniform read by the vertex shader, it contains the matrix
// that will move vertices
const VertexUniform = struct {
mat: zm.Mat,
};
const FragUniform = struct {
// TODO use an enum? Remember that it will be casted to u32 in wgsl
type: u32,
// Padding for struct alignment to 16 bytes (minimum in WebGPU uniform).
padding: @Vector(3, f32) = undefined,
};
// TODO texture and sampler, create buffers and use an index field
// in FragUniform to tell which texture to read
const App = @This();
pipeline: gpu.RenderPipeline,
queue: gpu.Queue,
vertex_buffer: gpu.Buffer,
vertex_uniform_buffer: gpu.Buffer,
frag_uniform_buffer: gpu.Buffer,
bind_group: gpu.BindGroup,
pub fn init(app: *App, engine: *mach.Engine) !void {
engine.core.setKeyCallback(struct {
fn callback(_: *App, eng: *mach.Engine, key: mach.Key, action: mach.Action) void {
if (action == .press) {
switch (key) {
.space => eng.core.setShouldClose(true),
else => {},
}
}
}
}.callback);
try engine.core.setSizeLimits(.{ .width = 20, .height = 20 }, .{ .width = null, .height = null });
const vs_module = engine.gpu_driver.device.createShaderModule(&.{
.label = "my vertex shader",
.code = .{ .wgsl = @embedFile("vert.wgsl") },
});
const vertex_attributes = [_]gpu.VertexAttribute{
.{ .format = .float32x4, .offset = @offsetOf(Vertex, "pos"), .shader_location = 0 },
.{ .format = .float32x2, .offset = @offsetOf(Vertex, "uv"), .shader_location = 1 },
};
const vertex_buffer_layout = gpu.VertexBufferLayout{
.array_stride = @sizeOf(Vertex),
.step_mode = .vertex,
.attribute_count = vertex_attributes.len,
.attributes = &vertex_attributes,
};
const fs_module = engine.gpu_driver.device.createShaderModule(&.{
.label = "my fragment shader",
.code = .{ .wgsl = @embedFile("frag.wgsl") },
});
// Fragment state
const color_target = gpu.ColorTargetState{
.format = engine.gpu_driver.swap_chain_format,
.blend = null,
.write_mask = gpu.ColorWriteMask.all,
};
const fragment = gpu.FragmentState{
.module = fs_module,
.entry_point = "main",
.targets = &.{color_target},
.constants = null,
};
const vbgle = gpu.BindGroupLayout.Entry.buffer(0, .{ .vertex = true }, .uniform, true, 0);
const fbgle = gpu.BindGroupLayout.Entry.buffer(1, .{ .fragment = true }, .read_only_storage, true, 0);
const bgl = engine.gpu_driver.device.createBindGroupLayout(
&gpu.BindGroupLayout.Descriptor{
.entries = &.{ vbgle, fbgle },
},
);
const bind_group_layouts = [_]gpu.BindGroupLayout{bgl};
const pipeline_layout = engine.gpu_driver.device.createPipelineLayout(&.{
.bind_group_layouts = &bind_group_layouts,
});
const pipeline_descriptor = gpu.RenderPipeline.Descriptor{
.fragment = &fragment,
.layout = pipeline_layout,
.depth_stencil = null,
.vertex = .{
.module = vs_module,
.entry_point = "main",
.buffers = &.{vertex_buffer_layout},
},
.multisample = .{
.count = 1,
.mask = 0xFFFFFFFF,
.alpha_to_coverage_enabled = false,
},
.primitive = .{
.front_face = .ccw,
.cull_mode = .none,
.topology = .triangle_list,
.strip_index_format = .none,
},
};
const vertex_buffer = engine.gpu_driver.device.createBuffer(&.{
.usage = .{ .vertex = true },
.size = @sizeOf(Vertex) * vertices.len,
.mapped_at_creation = true,
});
var vertex_mapped = vertex_buffer.getMappedRange(Vertex, 0, vertices.len);
std.mem.copy(Vertex, vertex_mapped, vertices[0..]);
vertex_buffer.unmap();
const vertex_uniform_buffer = engine.gpu_driver.device.createBuffer(&.{
.usage = .{ .copy_dst = true, .uniform = true },
.size = @sizeOf(VertexUniform),
.mapped_at_creation = false,
});
const frag_uniform_buffer = engine.gpu_driver.device.createBuffer(&.{
.usage = .{ .storage = true },
.size = @sizeOf(FragUniform) * vertices.len / 3,
.mapped_at_creation = true,
});
var frag_uniform_mapped = frag_uniform_buffer.getMappedRange(FragUniform, 0, vertices.len / 3);
const tmp_frag_ubo = [_]FragUniform{
.{
.type = 1,
},
.{
.type = 0,
},
.{
.type = 2,
},
};
std.mem.copy(FragUniform, frag_uniform_mapped, &tmp_frag_ubo);
frag_uniform_buffer.unmap();
const bind_group = engine.gpu_driver.device.createBindGroup(
&gpu.BindGroup.Descriptor{
.layout = bgl,
.entries = &.{
gpu.BindGroup.Entry.buffer(0, vertex_uniform_buffer, 0, @sizeOf(VertexUniform)),
gpu.BindGroup.Entry.buffer(1, frag_uniform_buffer, 0, @sizeOf(FragUniform) * vertices.len / 3),
},
},
);
app.pipeline = engine.gpu_driver.device.createRenderPipeline(&pipeline_descriptor);
app.queue = engine.gpu_driver.device.getQueue();
app.vertex_buffer = vertex_buffer;
app.vertex_uniform_buffer = vertex_uniform_buffer;
app.frag_uniform_buffer = frag_uniform_buffer;
app.bind_group = bind_group;
vs_module.release();
fs_module.release();
pipeline_layout.release();
bgl.release();
}
pub fn deinit(app: *App, _: *mach.Engine) void {
app.vertex_buffer.release();
app.vertex_uniform_buffer.release();
app.frag_uniform_buffer.release();
app.bind_group.release();
}
pub fn update(app: *App, engine: *mach.Engine) !bool {
const back_buffer_view = engine.gpu_driver.swap_chain.?.getCurrentTextureView();
const color_attachment = gpu.RenderPassColorAttachment{
.view = back_buffer_view,
.resolve_target = null,
.clear_value = std.mem.zeroes(gpu.Color),
.load_op = .clear,
.store_op = .store,
};
const encoder = engine.gpu_driver.device.createCommandEncoder(null);
const render_pass_info = gpu.RenderPassEncoder.Descriptor{
.color_attachments = &.{color_attachment},
};
{
// Using a view allows us to move the camera without having to change the actual
// global poitions of each vertex
const view = zm.lookAtRh(
zm.f32x4(0, 0, 1, 1),
zm.f32x4(0, 0, 0, 1),
zm.f32x4(0, 1, 0, 0),
);
const proj = zm.orthographicRh(
@intToFloat(f32, engine.gpu_driver.current_desc.width),
@intToFloat(f32, engine.gpu_driver.current_desc.height),
-100,
100,
);
const mvp = zm.mul(zm.mul(view, proj), zm.translation(-1, -1, 0));
const ubos = VertexUniform{
.mat = mvp,
};
encoder.writeBuffer(app.vertex_uniform_buffer, 0, VertexUniform, &.{ubos});
}
const pass = encoder.beginRenderPass(&render_pass_info);
pass.setPipeline(app.pipeline);
pass.setVertexBuffer(0, app.vertex_buffer, 0, @sizeOf(Vertex) * vertices.len);
pass.setBindGroup(0, app.bind_group, &.{ 0, 0 });
pass.draw(vertices.len, 1, 0, 0);
pass.end();
pass.release();
var command = encoder.finish(null);
encoder.release();
app.queue.submit(&.{command});
command.release();
engine.gpu_driver.swap_chain.?.present();
back_buffer_view.release();
return true;
} | examples/gkurve/main.zig |
//! Reference: "SIMD-friendly algorithms for substring searching" by <NAME>.
const std = @import("std");
const ArrayList = std.ArrayList;
const Allocator = std.mem.Allocator;
const AutoHashMap = std.AutoHashMap;
const expect = std.testing.expect;
const print = std.debug.print;
const Vector = std.meta.Vector;
const utils = @import("utils.zig");
const vec_size = utils.get_SIMD_vector_size_in_bytes();
const min_match_size = 3;
inline fn vec_splat(byte: u8) Vector(vec_size, u8) {
return @splat(vec_size, @as(u8, byte));
}
inline fn vec_AND(vec_1: Vector(vec_size, bool), vec_2: Vector(vec_size, bool)) Vector(vec_size, u8) {
const vec_1_int = @select(u8, vec_1, @splat(vec_size, @as(u8, 1)), @splat(vec_size, @as(u8, 0)));
const vec_2_int = @select(u8, vec_2, @splat(vec_size, @as(u8, 1)), @splat(vec_size, @as(u8, 0)));
return vec_1_int & vec_2_int;
}
inline fn quick_eql(a: []const u8, b: []const u8) bool {
for (a) |item, index| {
if (b[index] != item) {
return false;
}
}
return true;
}
const Match = struct {
len: usize,
distance: usize,
};
inline fn check_potential_match(
window: []const u8,
search_buff: []const u8,
index: usize,
mask_index: usize,
outer_target_len: usize
) ?Match {
const match_start = index + mask_index;
var target_len = outer_target_len;
// (Don't compare first or last byte, they've been verified.)
if (quick_eql(window[match_start+1..match_start+target_len], search_buff[1..target_len])) {
while (target_len < search_buff.len and window[match_start+target_len] == search_buff[target_len]) {
target_len += 1;
}
return Match { .len = target_len, .distance = window.len - (index + mask_index) };
} else {
return null;
}
}
pub fn find_best_match(window: []const u8, search_buff: []const u8) ?Match {
if (window.len < vec_size + min_match_size) return null;
var best_match_opt: ?Match = null;
var target_len: usize = min_match_size;
const first_byte_mask = vec_splat(search_buff[0]);
var index: usize = (window.len - vec_size) - target_len;
outer: while (true) {
const last_byte_mask = vec_splat(search_buff[target_len-1]);
const first_block: Vector(vec_size, u8) = window[index..][0..vec_size].*;
const last_block: Vector(vec_size, u8) = window[index+target_len-1..][0..vec_size].*;
const first_eq = (first_byte_mask == first_block);
const last_eq = (last_byte_mask == last_block);
const mask = vec_AND(first_eq, last_eq);
if (@reduce(.Add, mask) != 0) {
var mask_index: usize = vec_size-1;
while (true) {
if (mask[mask_index] != 0) {
var match_opt = check_potential_match(window, search_buff, index, mask_index, target_len);
if (match_opt) |match| {
if (match.len == search_buff.len) {
return match;
}
if (best_match_opt == null or best_match_opt.?.len < match.len) {
best_match_opt = match;
target_len = best_match_opt.?.len + 1;
continue :outer;
}
}
}
if (mask_index > 0) {
mask_index -= 1;
} else {
break;
}
}
}
if (index > vec_size) {
index -= vec_size;
} else if (index == 0) {
break;
} else {
index = 0;
}
}
return best_match_opt;
}
test "find best match" {
{
var best_match = find_best_match("It was the best of times, it was the blurst of times.", "blurst");
try expect(best_match.?.len == 6 and best_match.?.distance == 16);
}
{
var best_match = find_best_match("It is tea time, teatime, time for teas.", "teather");
try expect(best_match.?.len == 4 and best_match.?.distance == 23);
}
}
test "find best match prefers rightmost occurence" {
{
var best_match = find_best_match("Tea tea tea teatime tea teatime tea", "teatime");
try expect(best_match.?.len == 7 and best_match.?.distance == 11);
}
{
var best_match = find_best_match("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "AAAA");
try expect(best_match.?.len == 4 and best_match.?.distance == 4);
}
}
test "find best match at beginning" {
var best_match = find_best_match("Hello, is there anybody in there?", "Hello?");
try expect(best_match.?.len == 5 and best_match.?.distance == 33);
}
// Idealy this case would be handled like any other, however, it's not a priority.
test "find best match ignores small window buffer." {
var best_match = find_best_match("Small buff", "Hello?");
try expect(best_match == null);
} | src/str_match.zig |
const std = @import("std");
const n = @import("node.zig");
const Node = n.Node;
const NodeKind = n.NodeKind;
const t = std.testing;
fn isWhitespace(chr: u8) bool {
return chr == ' ' or chr == '\t' or chr == '\n' or chr == '\r';
}
fn isNumberLike(chr: u8) bool {
return chr == '0' or chr == '1' or chr == '2' or chr == '3' or chr == '4' or chr == '5' or chr == '6' or chr == '7' or chr == '8' or chr == '9' or chr == '.';
}
const State = struct {
allocator: *std.mem.Allocator,
index: usize,
buffer: []const u8,
const Self = @This();
fn readNode(self: *Self) Node {
self.skipWhitespace();
if (isNumberLike(self.peek())) {
return Node{ .number = self.readNumber() };
}
return switch (self.peek()) {
'"' => Node{ .string = self.readString() },
'[' => Node{ .array = self.readArray() },
'{' => Node{ .object = self.readObject() },
't' => {
self.index += 4;
return Node{ .boolean = true };
},
'f' => {
self.index += 5;
return Node{ .boolean = false };
},
'n' => {
self.index += 4;
return Node.null_;
},
else => unreachable,
};
}
fn peek(self: *Self) u8 {
return self.buffer[self.index];
}
fn expect(self: *Self, chr: u8) void {
if (self.peek() != chr) {
unreachable;
}
}
fn moveNext(self: *Self) void {
self.index += 1;
}
fn skipWhitespace(self: *Self) void {
while (isWhitespace(self.peek())) {
self.moveNext();
}
}
fn readString(self: *Self) []const u8 {
self.expect('"');
self.moveNext();
var buffer = std.ArrayList(u8).init(self.allocator);
while (self.peek() != '"') {
const isReadingEscapedCharacter = self.peek() == '\\';
if (isReadingEscapedCharacter) {
self.moveNext();
buffer.append(self.peek()) catch unreachable;
} else {
buffer.append(self.peek()) catch unreachable;
}
self.moveNext();
}
self.moveNext();
return buffer.toOwnedSlice();
}
fn readArray(self: *Self) []const Node {
self.expect('[');
self.moveNext();
var buffer = std.ArrayList(Node).init(self.allocator);
while (self.peek() != ']') {
const node = self.readNode();
buffer.append(node) catch unreachable;
self.skipWhitespace();
if (self.peek() == ',') {
self.moveNext();
}
}
self.moveNext();
return buffer.toOwnedSlice();
}
fn readObject(self: *Self) std.StringHashMap(Node) {
self.expect('{');
self.moveNext();
var map = std.StringHashMap(Node).init(self.allocator);
while (self.peek() != '}') {
self.skipWhitespace();
const key = self.readString();
self.skipWhitespace();
self.expect(':');
self.moveNext();
const value = self.readNode();
map.put(key, value) catch unreachable;
self.skipWhitespace();
if (self.peek() == ',') {
self.moveNext();
}
}
self.moveNext();
return map;
}
fn readNumber(self: *Self) f64 {
var buffer: [64]u8 = undefined;
var len: usize = 0;
while (self.index < self.buffer.len and isNumberLike(self.peek())) {
buffer[len] = self.peek();
self.moveNext();
len += 1;
}
return std.fmt.parseFloat(f64, buffer[0..len]) catch unreachable;
}
};
pub const Parser = struct {
allocator: *std.mem.Allocator,
pub fn init(
allocator: *std.mem.Allocator,
) Parser {
return .{ .allocator = allocator };
}
pub fn parse(self: Parser, str: []const u8) Node {
var state = State{
.allocator = self.allocator,
.index = 0,
.buffer = str,
};
return state.readNode();
}
};
const E = error{
TestUnexpectedError,
};
fn expectEqualNodes(expected: Node, actual: Node) !void {
if (!expected.eql(actual)) {
return E.TestUnexpectedError;
}
}
test "Parse string" {
const parser = Parser.init(t.allocator);
var node = parser.parse("\"yee\"");
defer node.deinit(t.allocator);
try expectEqualNodes(Node{ .string = "yee" }, node);
}
test "Parse string with escaped character" {
const parser = Parser.init(t.allocator);
var node = parser.parse("\"\\\"yee\"");
defer node.deinit(t.allocator);
try expectEqualNodes(Node{ .string = "\"yee" }, node);
}
test "Parse array of strings" {
const parser = Parser.init(t.allocator);
var node = parser.parse("[ \"a\" , \"b\" ]");
defer node.deinit(t.allocator);
try expectEqualNodes(Node{ .array = &[_]Node{ Node{ .string = "a" }, Node{ .string = "b" } } }, node);
}
test "Parse booleans" {
const parser = Parser.init(t.allocator);
const a = parser.parse("true");
const b = parser.parse("false");
try expectEqualNodes(Node{ .boolean = true }, a);
try expectEqualNodes(Node{ .boolean = false }, b);
}
test "Parse null" {
const parser = Parser.init(t.allocator);
const a = parser.parse("null");
try expectEqualNodes(Node.null_, a);
}
test "Parse object with single key" {
const parser = Parser.init(t.allocator);
var node = parser.parse("{ \"a\": null }");
defer node.deinit(t.allocator);
var map = std.StringHashMap(Node).init(t.allocator);
map.put("a", Node.null_) catch unreachable;
defer map.deinit();
try expectEqualNodes(Node{ .object = map }, node);
}
test "Parse object with multiple keys" {
const parser = Parser.init(t.allocator);
var node = parser.parse("{ \"a\": null, \"b\": [null, null] }");
defer node.deinit(t.allocator);
var map = std.StringHashMap(Node).init(t.allocator);
map.put("a", Node.null_) catch unreachable;
map.put("b", Node{ .array = &[_]Node{ Node.null_, Node.null_ } }) catch unreachable;
defer map.deinit();
try expectEqualNodes(Node{ .object = map }, node);
}
test "Parse object with nested stuff" {
const parser = Parser.init(t.allocator);
var node = parser.parse("{ \"a\": { \"b\": [] } }");
defer node.deinit(t.allocator);
var second = std.StringHashMap(Node).init(t.allocator);
defer second.deinit();
second.put("b", Node{ .array = &.{} }) catch unreachable;
var first = std.StringHashMap(Node).init(t.allocator);
defer first.deinit();
first.put("a", Node{ .object = second }) catch unreachable;
try expectEqualNodes(Node{ .object = first }, node);
}
test "Parse float" {
const parser = Parser.init(t.allocator);
var node = parser.parse("123.5");
defer node.deinit(t.allocator);
try expectEqualNodes(Node{ .number = 123.5 }, node);
}
test "Parse int" {
const parser = Parser.init(t.allocator);
var node = parser.parse("456");
defer node.deinit(t.allocator);
try expectEqualNodes(Node{ .number = 456 }, node);
}
test "Parse large thing" {
const str =
\\ {
\\ "firstName": "John",
\\ "lastName": "Smith",
\\ "isAlive": true,
\\ "age": 27,
\\ "address": {
\\ "streetAddress": "21 2nd Street",
\\ "city": "New York",
\\ "state": "NY",
\\ "postalCode": "10021-3100"
\\ },
\\ "phoneNumbers": [
\\ {
\\ "type": "home",
\\ "number": "212 555-1234"
\\ },
\\ {
\\ "type": "office",
\\ "number": "646 555-4567"
\\ }
\\ ],
\\ "children": [],
\\ "spouse": null
\\ }
;
const parser = Parser.init(t.allocator);
var node = parser.parse(str);
defer node.deinit(t.allocator);
try t.expectEqual(NodeKind.object, node);
} | zig/parser.zig |
const std = @import("std");
const assert = std.debug.assert;
const tools = @import("tools");
const CupIndex = u24;
const Cup = packed struct { next: CupIndex };
fn PackedArray(comptime T: type, comptime stride: usize, comptime count: usize) type {
return struct {
mem: [count * stride]u8,
inline fn at(self: *@This(), i: usize) *align(1) T {
return @ptrCast(*align(1) T, &self.mem[i * stride]);
}
};
}
pub fn run(input_text: []const u8, allocator: std.mem.Allocator) ![2][]const u8 {
var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit();
const cups = try allocator.create(PackedArray(Cup, 3, 1000001));
defer allocator.destroy(cups);
if (false) {
// init circle
var circle = tools.CircularBuffer(u8).init(allocator);
defer circle.deinit();
for (input_text) |n| {
try circle.pushTail(n);
}
if (true) {
var it = circle.iter();
std.debug.print("circle= ", .{});
while (it.next()) |n| std.debug.print("{c}, ", .{n});
std.debug.print("\n", .{});
}
// play turns
var turn: u32 = 1;
while (turn <= 100) : (turn += 1) {
const cur = circle.pop().?;
const cup1 = circle.pop().?;
const cup2 = circle.pop().?;
const cup3 = circle.pop().?;
try circle.pushHead(cur);
const save_ptr = circle.cur.?;
var target = cur;
while (target == cur or target == cup1 or target == cup2 or target == cup3) {
target = if (target > '1') target - 1 else '9';
}
//std.debug.print(" move: targt={c}, cups={c},{c},{c}\n", .{ target, cup1, cup2, cup3 });
while (circle.cur.?.item != target) circle.rotate(1);
circle.rotate(1);
try circle.pushHead(cup3);
try circle.pushHead(cup2);
try circle.pushHead(cup1);
if (true) {
while (circle.cur.?.item != '1') circle.rotate(1);
var it = circle.iter();
std.debug.print("circle= ", .{});
while (it.next()) |n| std.debug.print("{c}, ", .{n});
std.debug.print("\n", .{});
}
circle.cur = save_ptr;
circle.rotate(1);
}
// extract answer
{
var ans: [8]u8 = undefined;
while (circle.cur.?.item != '1') circle.rotate(1);
_ = circle.pop();
var i: u32 = 0;
while (circle.pop()) |n| : (i += 1) ans[i] = n;
// break :ans ans;
}
}
const ans1 = ans: {
// init circle
const first: CupIndex = input_text[0] - '0';
var prev = first;
for (input_text) |num| {
const n = num - '0';
cups.at(n).next = first;
cups.at(prev).next = n;
prev = n;
}
var cursor = first;
// play turns
var turn: u32 = 1;
while (turn <= 100) : (turn += 1) {
const cup1 = cups.at(cursor).next;
const cup2 = cups.at(cup1).next;
const cup3 = cups.at(cup2).next;
const next_cursor = cups.at(cup3).next;
var target = cursor;
while (target == cursor or target == cup1 or target == cup2 or target == cup3) {
target = if (target > 1) target - 1 else 9;
}
cups.at(cup3).next = cups.at(target).next;
cups.at(target).next = cup1;
cups.at(cursor).next = next_cursor;
cursor = next_cursor;
}
// extract answer
{
var ans: [8]u8 = undefined;
var i: u32 = 0;
var cup = cups.at(1).next;
while (i < 8) : (i += 1) {
ans[i] = @intCast(u8, cup) + '0';
cup = cups.at(cup).next;
}
//std.debug.print("cups= {}\n", .{ans});
break :ans ans;
}
};
const ans2 = ans: {
// init circle
const first: CupIndex = input_text[0] - '0';
var prev = first;
for (input_text) |num| {
const n = num - '0';
cups.at(prev).next = n;
prev = n;
}
var n: CupIndex = 10;
while (n <= 1000000) : (n += 1) {
cups.at(prev).next = n;
prev = n;
}
cups.at(1000000).next = first;
var cursor = first;
// play turns
var turn: u32 = 1;
while (turn <= 10000000) : (turn += 1) {
const cupcursor_ptr = cups.at(cursor);
const cup1 = cupcursor_ptr.next;
const cup2 = cups.at(cup1).next;
const cup3 = cups.at(cup2).next;
const cup3_ptr = cups.at(cup3);
const next_cursor = cup3_ptr.next;
var target = cursor;
while (target == cursor or target == cup1 or target == cup2 or target == cup3) {
target = if (target > 1) target - 1 else 1000000;
}
const cuptarget_ptr = cups.at(target);
cup3_ptr.next = cuptarget_ptr.next;
cuptarget_ptr.next = cup1;
cupcursor_ptr.next = next_cursor;
cursor = next_cursor;
}
{
const cup1 = cups.at(1).next;
const cup2 = cups.at(cup1).next;
break :ans @intCast(u64, cup1) * @intCast(u64, cup2);
}
};
return [_][]const u8{
try std.fmt.allocPrint(allocator, "{s}", .{ans1}),
try std.fmt.allocPrint(allocator, "{}", .{ans2}),
};
}
pub fn main() anyerror!void {
const stdout = std.io.getStdOut().writer();
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
// const limit = 1 * 1024 * 1024 * 1024;
// const text = try std.fs.cwd().readFileAlloc(allocator, "2020/input_day23.txt", limit);
// defer allocator.free(text);
const ans = try run("156794823", allocator);
defer allocator.free(ans[0]);
defer allocator.free(ans[1]);
try stdout.print("PART 1: {s}\nPART 2: {s}\n", .{ ans[0], ans[1] });
} | 2020/day23.zig |
const c = @import("../../c_global.zig").c_imp;
const std = @import("std");
// dross-zig
const glfb = @import("backend/framebuffer_opengl.zig");
const FramebufferGl = glfb.FramebufferGl;
const texture = @import("texture.zig");
const Texture = texture.Texture;
const renderer = @import("renderer.zig");
const selected_api = renderer.api;
const Vector2 = @import("../core/vector2.zig").Vector2;
// -----------------------------------------
// - FramebufferType -
// -----------------------------------------
pub const FramebufferType = enum {
Read,
Draw,
Both,
};
// -----------------------------------------
// - FramebufferAttachmentType -
// -----------------------------------------
pub const FramebufferAttachmentType = enum {
Color0,
Depth,
Stencil,
DepthStencil,
};
// -----------------------------------------
// - InternalFramebuffer -
// -----------------------------------------
const InternalFramebuffer = union {
gl: *FramebufferGl,
};
// -----------------------------------------
// - Framebuffer -
// -----------------------------------------
pub const Framebuffer = struct {
internal: ?*InternalFramebuffer = undefined,
color_attachment: ?*texture.Texture = undefined,
const Self = @This();
/// Sets up the Framebuffer and allocates any required memory
pub fn new(allocator: *std.mem.Allocator) !*Self {
var self = try allocator.create(Framebuffer);
switch (selected_api) {
renderer.BackendApi.OpenGl => {
self.internal = allocator.create(InternalFramebuffer) catch |err| {
std.debug.print("[Framebuffer] Error occurred during creation! {}\n", .{err});
@panic("[Framebuffer] Failed to create!");
};
self.internal.?.gl = FramebufferGl.new(allocator) catch |err| {
std.debug.print("[Framebuffer] Error occurred during creation! {}\n", .{err});
@panic("[Framebuffer] Failed to create!");
};
},
renderer.BackendApi.Dx12 => {},
renderer.BackendApi.Vulkan => {},
}
return self;
}
/// Frees up any allocated memory
pub fn free(allocator: *std.mem.Allocator, self: *Self) void {
FramebufferGl.free(allocator, self.internal.?.gl);
Texture.free(allocator, self.color_attachment.?);
allocator.destroy(self.internal.?);
allocator.destroy(self);
}
/// Binds the framebuffer to perform read/write operations on.
pub fn bind(self: *Self, target: FramebufferType) void {
switch (selected_api) {
renderer.BackendApi.OpenGl => {
self.internal.?.gl.bind(target);
},
renderer.BackendApi.Dx12 => {},
renderer.BackendApi.Vulkan => {},
}
}
/// Attaches texture to the framebuffer as the color buffer, depth buffer, and/or stencil buffer.
pub fn attach2d(self: *Self, id: texture.TextureId, attachment: FramebufferAttachmentType) void {
switch (selected_api) {
renderer.BackendApi.OpenGl => {
self.internal.?.gl.attach2d(id, attachment);
},
renderer.BackendApi.Dx12 => {},
renderer.BackendApi.Vulkan => {},
}
}
/// Allocates, builds, and attaches a color attachment for the framebuffer.
/// Comments: This is one of the few places where the Texture will be owned by
/// this class and will be disposed of properly.
pub fn addColorAttachment(self: *Self, allocator: *std.mem.Allocator, attachment: FramebufferAttachmentType, size: Vector2) void {
self.color_attachment = Texture.newDataless(allocator, size) catch |err| {
std.debug.print("[FRAMEBUFFER]: Error occurred when adding a color attachment! {}\n", .{err});
return;
};
self.attach2d(self.color_attachment.?.id(), attachment);
}
/// Checks to see if the framebuffer if complete
pub fn check(self: *Self) void {
switch (selected_api) {
renderer.BackendApi.OpenGl => {
self.internal.?.gl.check();
},
renderer.BackendApi.Dx12 => {},
renderer.BackendApi.Vulkan => {},
}
}
/// Returns the color attachment texture id, if a attachment was NOT set it'll return null
pub fn colorAttachment(self: *Self) ?Texture.TextureId {
if (self.color_attachment == undefined) return null;
return self.color_attachment.?.id();
}
/// Binds the color attachment texture
pub fn bindColorAttachment(self: *Self) void {
self.color_attachment.?.bind();
}
/// Clears framebuffer to the default
pub fn resetFramebuffer() void {
switch (selected_api) {
renderer.BackendApi.OpenGl => {
FramebufferGl.resetFramebuffer();
},
renderer.BackendApi.Dx12 => {},
renderer.BackendApi.Vulkan => {},
}
}
}; | src/renderer/framebuffer.zig |
const std = @import("std");
const fs = std.fs;
const mem = std.mem;
const tmpDir = std.testing.tmpDir;
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const alloc = &gpa.allocator;
pub fn main() !void {
const args = try std.process.argsAlloc(std.heap.page_allocator);
var tmp = tmpDir(.{});
defer tmp.cleanup();
const tmp_path = try tmp.dir.realpathAlloc(alloc, ".");
defer alloc.free(tmp_path);
const tmp_filename = "headers";
const tmp_file_path = try fs.path.join(alloc, &[_][]const u8{ tmp_path, tmp_filename });
defer alloc.free(tmp_file_path);
const headers_list_filename = "headers.o.d";
const headers_list_path = try fs.path.join(alloc, &[_][]const u8{ tmp_path, headers_list_filename });
defer alloc.free(headers_list_path);
var argv = std.ArrayList([]const u8).init(std.heap.page_allocator);
try argv.appendSlice(&[_][]const u8{
"cc",
"-o",
tmp_file_path,
"src/headers.c",
"-MD",
"-MV",
"-MF",
headers_list_path,
});
try argv.appendSlice(args[1..]);
// TODO instead of calling `cc` as a child process here,
// hook in directly to `zig cc` API.
const res = try std.ChildProcess.exec(.{
.allocator = alloc,
.argv = argv.items,
});
defer {
alloc.free(res.stdout);
alloc.free(res.stderr);
}
if (res.stderr.len != 0) {
std.debug.print("{}\n", .{res.stderr});
}
// Read in the contents of `upgrade.o.d`
const headers_list_file = try tmp.dir.openFile(headers_list_filename, .{});
defer headers_list_file.close();
// Create out dir
var out_dir = try fs.cwd().makeOpenPath("x86_64-macos-gnu", .{});
var dirs = std.StringHashMap(fs.Dir).init(alloc);
defer dirs.deinit();
try dirs.putNoClobber(".", out_dir);
const headers_list_str = try headers_list_file.reader().readAllAlloc(alloc, std.math.maxInt(usize));
defer alloc.free(headers_list_str);
const prefix = "/usr/include";
var it = mem.split(headers_list_str, "\n");
while (it.next()) |line| {
if (mem.lastIndexOf(u8, line, "clang") != null) continue;
if (mem.lastIndexOf(u8, line, prefix[0..])) |idx| {
const out_rel_path = line[idx + prefix.len + 1 ..];
const out_rel_path_stripped = mem.trim(u8, out_rel_path, " \\");
const dirname = fs.path.dirname(out_rel_path_stripped) orelse ".";
const maybe_dir = try dirs.getOrPut(dirname);
if (!maybe_dir.found_existing) {
maybe_dir.entry.value = try out_dir.makeOpenPath(dirname, .{});
}
const basename = fs.path.basename(out_rel_path_stripped);
const line_stripped = mem.trim(u8, line, " \\");
const abs_dirname = fs.path.dirname(line_stripped).?;
var orig_subdir = try fs.cwd().openDir(abs_dirname, .{});
defer orig_subdir.close();
try orig_subdir.copyFile(basename, maybe_dir.entry.value, basename, .{});
}
}
var dir_it = dirs.iterator();
while (dir_it.next()) |entry| {
entry.value.close();
}
} | src/main.zig |
const xcb = @import("../xcb.zig");
pub const id = xcb.Extension{ .name = "MIT-SHM", .global_id = 0 };
pub const SEG = u32;
/// Opcode for Completion.
pub const CompletionOpcode = 0;
/// @brief CompletionEvent
pub const CompletionEvent = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"drawable": xcb.DRAWABLE,
@"minor_event": u16,
@"major_event": u8,
@"pad1": u8,
@"shmseg": xcb.shm.SEG,
@"offset": u32,
};
/// @brief QueryVersioncookie
pub const QueryVersioncookie = struct {
sequence: c_uint,
};
/// @brief QueryVersionRequest
pub const QueryVersionRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 0,
@"length": u16,
};
/// @brief QueryVersionReply
pub const QueryVersionReply = struct {
@"response_type": u8,
@"shared_pixmaps": u8,
@"sequence": u16,
@"length": u32,
@"major_version": u16,
@"minor_version": u16,
@"uid": u16,
@"gid": u16,
@"pixmap_format": u8,
@"pad0": [15]u8,
};
/// @brief AttachRequest
pub const AttachRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 1,
@"length": u16,
@"shmseg": xcb.shm.SEG,
@"shmid": u32,
@"read_only": u8,
@"pad0": [3]u8,
};
/// @brief DetachRequest
pub const DetachRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 2,
@"length": u16,
@"shmseg": xcb.shm.SEG,
};
/// @brief PutImageRequest
pub const PutImageRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 3,
@"length": u16,
@"drawable": xcb.DRAWABLE,
@"gc": xcb.GCONTEXT,
@"total_width": u16,
@"total_height": u16,
@"src_x": u16,
@"src_y": u16,
@"src_width": u16,
@"src_height": u16,
@"dst_x": i16,
@"dst_y": i16,
@"depth": u8,
@"format": u8,
@"send_event": u8,
@"pad0": u8,
@"shmseg": xcb.shm.SEG,
@"offset": u32,
};
/// @brief GetImagecookie
pub const GetImagecookie = struct {
sequence: c_uint,
};
/// @brief GetImageRequest
pub const GetImageRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 4,
@"length": u16,
@"drawable": xcb.DRAWABLE,
@"x": i16,
@"y": i16,
@"width": u16,
@"height": u16,
@"plane_mask": u32,
@"format": u8,
@"pad0": [3]u8,
@"shmseg": xcb.shm.SEG,
@"offset": u32,
};
/// @brief GetImageReply
pub const GetImageReply = struct {
@"response_type": u8,
@"depth": u8,
@"sequence": u16,
@"length": u32,
@"visual": xcb.VISUALID,
@"size": u32,
};
/// @brief CreatePixmapRequest
pub const CreatePixmapRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 5,
@"length": u16,
@"pid": xcb.PIXMAP,
@"drawable": xcb.DRAWABLE,
@"width": u16,
@"height": u16,
@"depth": u8,
@"pad0": [3]u8,
@"shmseg": xcb.shm.SEG,
@"offset": u32,
};
/// @brief AttachFdRequest
pub const AttachFdRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 6,
@"length": u16,
@"shmseg": xcb.shm.SEG,
@"read_only": u8,
@"pad0": [3]u8,
};
/// @brief CreateSegmentcookie
pub const CreateSegmentcookie = struct {
sequence: c_uint,
};
/// @brief CreateSegmentRequest
pub const CreateSegmentRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 7,
@"length": u16,
@"shmseg": xcb.shm.SEG,
@"size": u32,
@"read_only": u8,
@"pad0": [3]u8,
};
/// @brief CreateSegmentReply
pub const CreateSegmentReply = struct {
@"response_type": u8,
@"nfd": u8,
@"sequence": u16,
@"length": u32,
@"pad0": [24]u8,
};
test "" {
@import("std").testing.refAllDecls(@This());
} | src/auto/shm.zig |
const std = @import("std");
const util = @import("util.zig");
const data = @embedFile("../data/day05.txt");
// Takes in lines, returns number of intersections
pub fn numberOfIntersections(lines: []const util.Line(i32), consider_diagonals: bool) !usize {
var map = util.Map(util.Point(i32), usize).init(util.gpa);
defer map.deinit();
for (lines) |line| {
// Skip diagonals if requested
const line_type = line.getType();
if (!consider_diagonals and line_type == .Diagonal) continue;
// Diagonal lines must be 45 degrees per problem statement
var delta = util.Point(i32).subtract(line.end, line.start);
if (line_type == .Diagonal and try util.absInt(delta.x) != try util.absInt(delta.y)) return error.InvalidInput;
// Turn delta into a number you can increment a position by to iterate along the line
delta.x = if (delta.x == 0) @as(i32, 0) else if (delta.x < 0) @as(i32, -1) else @as(i32, 1);
delta.y = if (delta.y == 0) @as(i32, 0) else if (delta.y < 0) @as(i32, -1) else @as(i32, 1);
// Iterate over line. We need to ensure the end value allows us to _include_ the last point.
var pos = line.start;
const end = util.Point(i32){ .x = line.end.x + delta.x, .y = line.end.y + delta.y };
while (!std.meta.eql(pos, end)) : (pos = util.Point(i32).add(pos, delta)) {
try map.put(pos, (map.get(pos) orelse 0) + 1);
}
}
// Given that map, find the number of points that have 2 or more lines
var num_intersections: usize = 0;
var it = map.valueIterator();
while (it.next()) |value| {
if (value.* >= 2) num_intersections += 1;
}
return num_intersections;
}
pub fn main() !void {
defer {
const leaks = util.gpa_impl.deinit();
std.debug.assert(!leaks);
}
var lines = util.List(util.Line(i32)).init(util.gpa);
defer lines.deinit();
// Parse into lines
var it = util.tokenize(u8, data, "\n");
while (it.next()) |line_data| {
var point_it = util.tokenize(u8, line_data, "-> ,");
const line = util.Line(i32){
.start = util.Point(i32){
.x = util.parseInt(i32, point_it.next() orelse return error.InvalidInput, 10) catch {
return error.InvalidInput;
},
.y = util.parseInt(i32, point_it.next() orelse return error.InvalidInput, 10) catch {
return error.InvalidInput;
},
},
.end = util.Point(i32){
.x = util.parseInt(i32, point_it.next() orelse return error.InvalidInput, 10) catch {
return error.InvalidInput;
},
.y = util.parseInt(i32, point_it.next() orelse return error.InvalidInput, 10) catch {
return error.InvalidInput;
},
},
};
try lines.append(line);
}
// Part 1
var intersections_pt1 = try numberOfIntersections(lines.items, false);
util.print("Part 1: Number of intersections: {d}\n", .{intersections_pt1});
// Part 2
var intersections_pt2 = try numberOfIntersections(lines.items, true);
util.print("Part 2: Number of intersections: {d}\n", .{intersections_pt2});
} | src/day05.zig |
const std = @import("std");
const mem = std.mem;
const os = std.os;
const assert = std.debug.assert;
const cmn = @import("common.zig");
const dom = @import("dom.zig");
const Logger = @import("Logger.zig");
const number_parsing = @import("number_parsing.zig");
const string_parsing = @import("string_parsing.zig");
const atom_parsing = @import("atom_parsing.zig");
const CharUtils = string_parsing.CharUtils;
const root = @import("root");
const builtin = @import("builtin");
// TODO: document that this is configurable in root
pub const READ_BUF_CAP = if (@hasDecl(root, "read_buf_cap"))
root.read_buf_cap
else if (builtin.is_test)
mem.page_size
else
unreachable;
const GetOptions = struct {
allocator: ?mem.Allocator = null,
};
pub const Value = struct {
iter: ValueIterator,
pub fn find_field(v: *Value, key: []const u8) !Value {
return (try v.start_or_resume_object()).find_field(key);
}
pub fn find_field_unordered(v: *Value, key: []const u8) !Value {
return (try v.start_or_resume_object()).find_field_unordered(key);
}
pub fn get_object(v: *Value) !Object {
return Object.start(&v.iter);
}
pub fn get_array(v: *Value) !Array {
return Array.start(&v.iter);
}
fn start_or_resume_object(v: *Value) !Object {
return if (v.iter.at_start())
try v.get_object()
else
Object.resume_(&v.iter);
}
pub fn get_int(v: *Value, comptime T: type) !T {
return v.iter.get_int(T);
}
pub fn get_string(v: *Value, comptime T: type, buf: []u8) !T {
return v.iter.get_string(T, buf);
}
pub fn get_string_alloc(v: *Value, comptime T: type, allocator: mem.Allocator) !T {
return v.iter.get_string_alloc(T, allocator);
}
pub fn get_double(v: *Value) !f64 {
return v.iter.get_double();
}
pub fn get_bool(v: *Value) !bool {
return v.iter.get_bool();
}
pub fn is_null(v: *Value) !bool {
return v.iter.is_null();
}
pub fn at_pointer(v: *Value, json_pointer: []const u8) !Value {
return switch (try v.iter.get_type()) {
.array => (try v.get_array()).at_pointer(json_pointer),
.object => (try v.get_object()).at_pointer(json_pointer),
else => error.INVALID_JSON_POINTER,
};
}
pub fn get(val: *Value, out: anytype, options: GetOptions) cmn.Error!void {
const T = @TypeOf(out);
const info = @typeInfo(T);
switch (info) {
.Pointer => {
const C = std.meta.Child(T);
const child_info = @typeInfo(C);
switch (info.Pointer.size) {
.One => {
switch (child_info) {
.Int => out.* = try val.get_int(C),
.Float => out.* = @floatCast(C, try val.get_double()),
.Bool => out.* = try val.get_bool(),
.Optional => out.* = if (try val.is_null())
null
else blk: {
var x: std.meta.Child(C) = undefined;
try val.get(&x, options);
break :blk x;
},
.Array => {
var arr = try val.get_array();
var iter = arr.iterator();
for (out) |*out_ele| {
var arr_ele = (try iter.next()) orelse break;
try arr_ele.get(out_ele, options);
}
},
.Pointer => {
if (child_info.Pointer.size == .Slice) {
if (options.allocator) |allocator| {
switch (try val.get_type()) {
.array => {
var list = std.ArrayListUnmanaged(std.meta.Child(C)){};
var arr = try val.get_array();
var iter = arr.iterator();
while (try iter.next()) |*arr_ele| {
try arr_ele.get(try list.addOne(allocator), options);
}
out.* = list.toOwnedSlice(allocator);
},
.string => out.* = try val.get_string_alloc(C, allocator),
else => return error.INCORRECT_TYPE,
}
} else {
val.iter.iter.parser.log.err(&val.iter, "slice requires an options.allocator be provided: get(..., .{.allocator = allocator})");
return error.MEMALLOC;
}
} else @compileError("unsupported type: " ++ @typeName(T) ++
". expecting slice");
},
.Struct => {
switch (try val.iter.get_type()) {
.object => {
var obj = try val.get_object();
inline for (std.meta.fields(C)) |field| {
const field_info = @typeInfo(field.field_type);
if (obj.find_field_unordered(field.name)) |*obj_val|
if (field_info != .Pointer)
try obj_val.get(&@field(out, field.name), options)
else {
if (options.allocator != null)
try obj_val.get(&@field(out, field.name), options)
else
try obj_val.get(@field(out, field.name), options);
}
else |_| {}
}
},
else => return error.INCORRECT_TYPE,
}
},
else => @compileError("unsupported type: " ++ @typeName(T) ++
". expecting int, float, bool or optional type."),
}
},
.Slice => {
switch (try val.iter.get_type()) {
.string => _ = try if (options.allocator) |allocator|
val.get_string_alloc(T, allocator)
else
return error.INCORRECT_TYPE,
else => return error.INCORRECT_TYPE,
}
},
else => @compileError("unsupported pointer type: " ++ @typeName(T) ++
". expecting slice or single item pointer."),
}
},
else => @compileError("unsupported type: " ++ @typeName(T) ++ ". expecting pointer type."),
}
}
pub fn get_type(val: *Value) !ValueType {
return val.iter.get_type();
}
pub fn raw_json_token(val: *Value) ![]const u8 {
const len = try std.math.cast(u16, val.iter.peek_start_length());
const ptr = try val.iter.peek_start(len);
return ptr[0..len];
}
};
pub const Field = struct {
key: [*]const u8, // TODO: make this a []const u8
value: Value,
};
pub const ObjectIterator = struct {
iter: ValueIterator,
fn init(iter: ValueIterator) ObjectIterator {
return ObjectIterator{ .iter = iter };
}
/// if there is a next field, copies the unescaped key into key_buf
/// and returns a new iterator at the key's value
pub fn next(oi: *ObjectIterator, key_buf: []u8) !?Field {
errdefer oi.iter.abandon();
const has_value = if (oi.iter.at_first_field())
true
else if (!oi.iter.is_open())
false
else blk: {
try oi.iter.skip_child();
break :blk try oi.iter.has_next_field();
};
if (has_value) {
ValueIterator.copy_key_without_quotes(key_buf, try oi.iter.field_key(), key_buf.len);
try oi.iter.field_value();
return Field{ .key = key_buf.ptr, .value = .{ .iter = oi.iter.child() } };
}
return null;
}
pub fn get_int(oi: *ObjectIterator, comptime T: type) !T {
return oi.iter.get_int(T);
}
};
pub const Object = struct {
iter: ValueIterator,
pub fn iterator(o: Object) ObjectIterator {
return ObjectIterator.init(o.iter);
}
// TODO: move these to ValueIterator
fn start_root(iter: *ValueIterator) !Object {
_ = try iter.start_root_object();
return Object{ .iter = iter.* };
}
fn start(iter: *ValueIterator) !Object {
_ = try iter.start_object();
return Object{ .iter = iter.* };
}
fn resume_(iter: *ValueIterator) Object {
return Object{ .iter = iter.* };
}
pub fn resume_value(o: Object) Value {
return Value{ .iter = o.iter };
}
pub fn find_field(o: *Object, key: []const u8) !Value {
return if (try o.iter.find_field_raw(key))
Value{ .iter = o.iter.child() }
else
error.NO_SUCH_FIELD;
}
pub fn find_field_unordered(o: *Object, key: []const u8) !Value {
return if (try o.iter.find_field_unordered_raw(key))
Value{ .iter = o.iter.child() }
else
error.NO_SUCH_FIELD;
}
pub fn at_pointer(o: *Object, json_pointer_: []const u8) !Value {
if (json_pointer_[0] != '/') return error.INVALID_JSON_POINTER;
var json_pointer = json_pointer_[1..];
const slash = mem.indexOfScalar(u8, json_pointer, '/');
const key = json_pointer[0 .. slash orelse json_pointer.len];
// Find the child with the given key
var child: Value = undefined;
// TODO: escapes
// If there is an escape character in the key, unescape it and then get the child.
// const escape = mem.indexOfScalar(u8, key, '~');
// if (escape != null) {
// // Unescape the key
// std::string unescaped(key);
// do {
// switch (unescaped[escape+1]) {
// case '0':
// unescaped.replace(escape, 2, "~");
// break;
// case '1':
// unescaped.replace(escape, 2, "/");
// break;
// default:
// return error.INVALID_JSON_POINTER; // "Unexpected ~ escape character in JSON pointer");
// }
// escape = unescaped.find('~', escape+1);
// } while (escape != std::string::npos);
// child = find_field(unescaped); // Take note find_field does not unescape keys when matching
// } else {
child = try o.find_field(key);
child.iter.iter.err catch return child; // we do not continue if there was an error
// If there is a /, we have to recurse and look up more of the path
if (slash != null)
child = try child.at_pointer(json_pointer[slash.?..]);
return child;
}
};
const ArrayIterator = struct {
iter: ValueIterator,
fn init(iter: ValueIterator) ArrayIterator {
return ArrayIterator{ .iter = iter };
}
pub fn next(ai: *ArrayIterator) !?Value {
errdefer ai.iter.abandon();
const has_value = if (ai.iter.at_first_field())
true
else if (!ai.iter.is_open())
false
else blk: {
try ai.iter.skip_child();
break :blk try ai.iter.has_next_element();
};
if (has_value) {
const result = Value{ .iter = ai.iter.child() };
try ai.iter.skip_child();
return result;
}
return null;
}
};
const Array = struct {
iter: ValueIterator,
fn start_root(iter: *ValueIterator) !Array {
_ = try iter.start_root_array();
return Array{ .iter = iter.* };
}
fn start(iter: *ValueIterator) !Array {
_ = try iter.start_array();
return Array{ .iter = iter.* };
}
pub fn iterator(o: Array) ArrayIterator {
return ArrayIterator.init(o.iter);
}
pub fn at(a: *Array, index: usize) !?Value {
var it = a.iterator();
var i: usize = 0;
while (try it.next()) |e| : (i += 1)
if (i == index)
return e;
return null;
}
pub fn at_pointer(a: *Array, json_pointer_: []const u8) !Value {
if (json_pointer_[0] != '/') return error.INVALID_JSON_POINTER;
var json_pointer = json_pointer_[1..];
// - means "the append position" or "the element after the end of the array"
// We don't support this, because we're returning a real element, not a position.
if (json_pointer.len == 1 and json_pointer[0] == '-') return error.INDEX_OUT_OF_BOUNDS;
// Read the array index
var array_index: usize = 0;
var i: usize = 0;
while (i < json_pointer.len and json_pointer[i] != '/') : (i += 1) {
const digit = json_pointer[i] - '0';
// Check for non-digit in array index. If it's there, we're trying to get a field in an object
if (digit > 9) return error.INCORRECT_TYPE;
array_index = array_index * 10 + digit;
}
// 0 followed by other digits is invalid
if (i > 1 and json_pointer[0] == '0') return error.INVALID_JSON_POINTER; // "JSON pointer array index has other characters after 0"
// Empty string is invalid; so is a "/" with no digits before it
if (i == 0) return error.INVALID_JSON_POINTER; // "Empty string in JSON pointer array index"
// Get the child
var child = (try a.at(array_index)) orelse return error.INVALID_JSON_POINTER;
// If there is an error, it ends here
child.iter.iter.err catch return child;
// If there is a /, we're not done yet, call recursively.
if (i < json_pointer.len)
child = try child.at_pointer(json_pointer[i..]);
return child;
}
};
const TokenIterator = struct {
/// src index
index: [*]const u32,
pub fn peek_delta(ti: *TokenIterator, parser: *Parser, delta: i32, len: u16) ![*]const u8 {
return parser.peek(
if (delta < 0)
ti.index - @intCast(u32, -delta)
else
ti.index + @intCast(u32, delta),
len,
);
}
pub fn peek_length(position: [*]const u32) u32 {
return (position + 1)[0] - position[0];
}
};
pub const Iterator = struct {
token: TokenIterator,
parser: *Parser,
err: cmn.Error!void = {},
depth: u32,
pub fn init(parser: *Parser) Iterator {
return Iterator{
.token = .{ .index = parser.structural_indices().ptr },
.parser = parser,
.depth = 1,
};
}
pub fn advance(iter: *Iterator, peek_len: u16) ![*]const u8 {
defer iter.token.index += 1;
// print("advance '{s}'\n", .{(try iter.token.peek(iter.token.index, len))[0..len]});
return iter.parser.peek(iter.token.index, peek_len);
}
pub fn peek(iter: *Iterator, index: [*]const u32, len: u16) ![*]const u8 {
return iter.parser.peek(index, len);
}
pub fn peek_last(iter: *Iterator) ![*]const u8 {
return iter.parser.peek(iter.last_document_position(), 1);
}
pub fn peek_delta(iter: *Iterator, delta: i32, len: u16) ![*]const u8 {
return iter.token.peek_delta(iter.parser, delta, len);
}
pub fn peek_length(position: [*]const u32) u32 {
return TokenIterator.peek_length(position);
}
pub fn last_document_position(iter: Iterator) [*]const u32 {
// The following line fails under some compilers...
// SIMDJSON_ASSUME(parser.implementation.n_structural_indexes > 0);
// since it has side-effects.
const n_structural_indexes = iter.parser.parser.n_structural_indexes;
assert(n_structural_indexes > 0);
const result = iter.parser.structural_indices().ptr + (n_structural_indexes - 1);
// cmn.println("tail.items {any} n_structural_indexes {} result {}\n", .{ iter.parser.structural_indices(), n_structural_indexes, result[0] });
return result;
}
pub fn root_checkpoint(iter: Iterator) [*]const u32 {
return iter.parser.structural_indices().ptr;
}
pub fn skip_child(iter: *Iterator, parent_depth: u32) !void {
if (iter.depth <= parent_depth) return;
switch ((try iter.advance(1))[0]) {
// TODO consider whether matching braces is a requirement: if non-matching braces indicates
// *missing* braces, then future lookups are not in the object/arrays they think they are,
// violating the rule "validate enough structure that the user can be confident they are
// looking at the right values."
// PERF TODO we can eliminate the switch here with a lookup of how much to add to depth
// For the first open array/object in a value, we've already incremented depth, so keep it the same
// We never stop at colon, but if we did, it wouldn't affect depth
'[', '{', ':' => {
iter.parser.log.start_value(iter, "skip");
},
// If there is a comma, we have just finished a value in an array/object, and need to get back in
',' => {
iter.parser.log.value(iter, "skip");
},
// ] or } means we just finished a value and need to jump out of the array/object
']', '}' => {
iter.parser.log.end_value(iter, "skip");
iter.depth -= 1;
if (iter.depth <= parent_depth) return;
},
// Anything else must be a scalar value
else => {
// For the first scalar, we will have incremented depth already, so we decrement it here.
iter.parser.log.value(iter, "skip");
iter.depth -= 1;
if (iter.depth <= parent_depth) return;
},
}
// Now that we've considered the first value, we only increment/decrement for arrays/objects
// const end = @ptrToInt(iter.parser.structural_indices().ptr + iter.parser.parser.n_structural_indexes);
const end_idx = iter.parser.structural_indices()[iter.parser.parser.n_structural_indexes];
while (iter.token.index[0] <= end_idx) {
switch ((try iter.advance(1))[0]) {
'[', '{' => {
iter.parser.log.start_value(iter, "skip");
iter.depth += 1;
},
// TODO consider whether matching braces is a requirement: if non-matching braces indicates
// *missing* braces, then future lookups are not in the object/arrays they think they are,
// violating the rule "validate enough structure that the user can be confident they are
// looking at the right values."
// PERF TODO we can eliminate the switch here with a lookup of how much to add to depth
']', '}' => {
iter.parser.log.end_value(iter, "skip");
iter.depth -= 1;
if (iter.depth <= parent_depth) return;
},
else => {
iter.parser.log.value(iter, "skip");
},
}
}
return iter.report_error(error.TAPE_ERROR, "not enough close braces");
}
fn report_error(iter: *Iterator, err: cmn.Error, message: []const u8) cmn.Error {
_ = message;
_ = iter;
assert(err != error.UNINITIALIZED and err != error.INCORRECT_TYPE and err != error.NO_SUCH_FIELD);
iter.parser.log.err(iter, message);
return err;
}
fn ascend_to(iter: *Iterator, parent_depth: u32) void {
assert(parent_depth >= 0 and parent_depth < std.math.maxInt(i32) - 1);
assert(iter.depth == parent_depth + 1);
iter.depth = parent_depth;
}
fn descend_to(iter: *Iterator, child_depth: u32) void {
assert(child_depth >= 1 and child_depth < std.math.maxInt(i32));
assert(iter.depth == child_depth - 1);
iter.depth = child_depth;
}
fn abandon(iter: *Iterator) void {
// iter.parser.deinit();
// iter.parser = undefined;
iter.depth = 0;
}
pub fn at_beginning(iter: *Iterator) bool {
// std.log.debug("at-beginning {*}: {}", .{ iter.next_structural, iter.next_structural[0] });
return iter.token.index == iter.parser.structural_indices().ptr;
}
pub inline fn next_structural(iter: *Iterator) [*]u32 {
// std.log.debug("at-beginning {*}: {}", .{ iter.next_structural, iter.next_structural[0] });
return @intToPtr([*]u32, @ptrToInt(iter.token.index));
}
fn reenter_child(iter: *Iterator, position: [*]const u32, child_depth: u32) void {
assert(child_depth >= 1 and child_depth < std.math.maxInt(i32));
assert(iter.depth == child_depth - 1);
// assert(@ptrToInt(position) >= @ptrToInt(iter.parser.start_positions[child_depth]));
iter.token.index = position;
iter.depth = child_depth;
}
pub fn string_buf_loc(iter: Iterator) [*]const u8 {
return @ptrCast([*]const u8, &iter.token.buf) + iter.token.index[0] - iter.token.buf_start_pos;
}
fn copy_to_buffer(json: [*]const u8, max_len_: u32, comptime N: u16, tmpbuf: *[N]u8) bool {
// Truncate whitespace to fit the buffer.
var max_len = max_len_;
if (max_len > N - 1) {
if (CharUtils.is_not_structural_or_whitespace(json[N - 1])) return false;
max_len = N - 1;
}
// Copy to the buffer.
@memcpy(tmpbuf, json, max_len);
tmpbuf[max_len] = ' ';
return true;
}
pub fn rewind(iter: *Iterator) !void {
iter.token.index = iter.parser.structural_indices().ptr;
iter.parser.log.start(iter); // We start again
iter.depth = 1;
}
pub fn at_eof(iter: Iterator) bool {
return iter.token.index == iter.last_document_position();
}
};
pub const ValueIterator = struct {
iter: Iterator, // this needs to be a value, not a pointer
depth: u32,
start_position: [*]const u32,
pub fn init(iter: Iterator, depth: u32, start_position: [*]const u32) ValueIterator {
return .{
.iter = iter,
.depth = depth,
.start_position = start_position,
};
}
fn parse_null(json: [*]const u8) bool {
return atom_parsing.is_valid_atom(json, 4, atom_parsing.atom_null) and
CharUtils.is_structural_or_whitespace(json[4]);
}
fn parse_bool(vi: *ValueIterator, json: [*]const u8) !bool {
const not_true = !(atom_parsing.is_valid_atom(json, 4, atom_parsing.atom_true));
const not_false = !(atom_parsing.is_valid_atom(json, 4, atom_parsing.atom_fals) and json[4] == 'e');
const err = (not_true and not_false) or
CharUtils.is_not_structural_or_whitespace(json[if (not_true) 5 else 4]);
if (err) return vi.incorrect_type_error("Not a boolean");
return !not_true;
}
pub fn is_null(vi: *ValueIterator) !bool {
return parse_null(try vi.advance_non_root_scalar("null", 5));
}
fn is_at_start(vi: ValueIterator) bool {
return vi.iter.token.index == vi.start_position;
}
fn peek_start(vi: *ValueIterator, len: u16) ![*]const u8 {
return try vi.iter.peek(vi.start_position, len);
}
fn assert_at_start(vi: ValueIterator) void {
assert(vi.iter.token.index == vi.start_position);
assert(vi.iter.depth == vi.depth);
assert(vi.depth > 0);
}
fn assert_at_root(vi: ValueIterator) void {
vi.assert_at_start();
assert(vi.depth == 1);
}
fn assert_at_child(vi: ValueIterator) void {
assert(@ptrToInt(vi.iter.token.index) > @ptrToInt(vi.start_position));
assert(vi.iter.depth == vi.depth + 1);
assert(vi.depth > 0);
}
fn assert_at_non_root_start(vi: ValueIterator) void {
vi.assert_at_start();
assert(vi.depth > 1);
}
fn ascend_to(vi: *ValueIterator, parent_depth: u32) void {
assert(parent_depth >= 0 and parent_depth < std.math.maxInt(i32) - 1);
assert(vi.depth == parent_depth + 1);
vi.depth = parent_depth;
}
fn advance_non_root_scalar(vi: *ValueIterator, typ: []const u8, peek_len: u16) ![*]const u8 {
vi.iter.parser.log.value2(&vi.iter, typ, "", vi.start_position[0], vi.depth);
if (!vi.is_at_start())
return vi.peek_start(peek_len);
vi.assert_at_non_root_start();
const result = try vi.iter.advance(peek_len);
vi.ascend_to(vi.depth - 1);
return result;
}
fn advance_root_scalar(vi: *ValueIterator, typ: []const u8, peek_len: u16) ![*]const u8 {
vi.iter.parser.log.value2(&vi.iter, typ, "", vi.start_position[0], vi.depth);
if (!vi.is_at_start())
return vi.peek_start(peek_len);
vi.assert_at_root();
defer vi.iter.ascend_to(vi.depth - 1);
return vi.iter.advance(peek_len);
}
fn is_open(vi: ValueIterator) bool {
return vi.iter.depth >= vi.depth;
}
fn skip_child(vi: *ValueIterator) !void {
assert(@ptrToInt(vi.iter.token.index) > @ptrToInt(vi.start_position));
assert(vi.iter.depth >= vi.depth);
return vi.iter.skip_child(vi.depth);
}
fn has_next_field(vi: *ValueIterator) !bool {
vi.assert_at_next();
switch ((try vi.iter.advance(1))[0]) {
'}' => {
vi.iter.parser.log.end_value(&vi.iter, "object");
vi.iter.ascend_to(vi.depth - 1);
return false;
},
',' => return true,
else => return vi.iter.report_error(error.TAPE_ERROR, "Missing comma between object fields"),
}
}
fn has_next_element(vi: *ValueIterator) !bool {
vi.assert_at_next();
switch ((try vi.iter.advance(1))[0]) {
']' => {
vi.iter.parser.log.end_value(&vi.iter, "array");
vi.iter.ascend_to(vi.depth - 1);
return false;
},
',' => {
vi.iter.descend_to(vi.depth + 1);
return true;
},
else => return vi.iter.report_error(error.TAPE_ERROR, "Missing comma between array elements"),
}
}
fn start_root_object(vi: *ValueIterator) !bool {
var result = try vi.start_object();
const last_char = (try vi.iter.peek_last())[0];
if (last_char != '}')
return vi.iter.report_error(error.TAPE_ERROR, "object invalid: { at beginning of document unmatched by } at end of document");
return result;
}
fn start_root_array(vi: *ValueIterator) !bool {
var result = try vi.start_array();
const last_char = (try vi.iter.peek_last())[0];
if (last_char != ']')
return vi.iter.report_error(error.TAPE_ERROR, "array invalid: [ at beginning of document unmatched by ] at end of document");
return result;
}
fn advance_container_start(vi: *ValueIterator, typ: []const u8, peek_len: u16) ![*]const u8 {
vi.iter.parser.log.line_fmt(&vi.iter, "", typ, "start pos {} depth {}", .{ vi.start_position[0], vi.depth });
// If we're not at the position anymore, we don't want to advance the cursor.
if (!vi.is_at_start()) {
// #ifdef SIMDJSON_DEVELOPMENT_CHECKS
// if (!vi.is_at_iterator_start()) { return OUT_OF_ORDER_ITERATION; }
// #endif
return vi.peek_start(peek_len);
}
// Get the JSON and advance the cursor, decreasing depth to signify that we have retrieved the value.
vi.assert_at_start();
return vi.iter.advance(peek_len);
}
fn incorrect_type_error(vi: *ValueIterator, message: []const u8) cmn.Error {
_ = message;
vi.iter.parser.log.err_fmt(&vi.iter, "{s}. start_position {} depth {}", .{ message, vi.start_position[0], vi.depth });
return error.INCORRECT_TYPE;
}
fn assert_at_container_start(vi: ValueIterator) void {
assert(vi.iter.token.index == vi.start_position + 1);
assert(vi.iter.depth == vi.depth);
assert(vi.depth > 0);
}
fn assert_at_next(vi: ValueIterator) void {
assert(@ptrToInt(vi.iter.token.index) > @ptrToInt(vi.start_position));
assert(vi.iter.depth == vi.depth);
assert(vi.depth > 0);
}
fn started_object(vi: *ValueIterator) !bool {
vi.assert_at_container_start();
if ((try vi.iter.peek_delta(0, 1))[0] == '}') {
vi.iter.parser.log.value(&vi.iter, "empty object");
_ = try vi.iter.advance(0);
vi.iter.ascend_to(vi.depth - 1);
return false;
}
vi.iter.parser.log.start_value(&vi.iter, "object");
// #ifdef SIMDJSON_DEVELOPMENT_CHECKS
// vi.iter.set_start_position(_depth, _start_position);
// #endif
return true;
}
fn started_array(vi: *ValueIterator) !bool {
vi.assert_at_container_start();
if ((try vi.iter.peek_delta(0, 1))[0] == ']') {
vi.iter.parser.log.value(&vi.iter, "empty array");
_ = try vi.iter.advance(1);
vi.iter.ascend_to(vi.depth - 1);
return false;
}
vi.iter.parser.log.start_value(&vi.iter, "array");
vi.iter.descend_to(vi.depth + 1);
// #ifdef SIMDJSON_DEVELOPMENT_CHECKS
// _json_iter->set_start_position(_depth, _start_position);
// #endif
return true;
}
fn start_object(vi: *ValueIterator) !bool {
var json: [*]const u8 = try vi.advance_container_start("object", 1);
if (json[0] != '{')
return vi.incorrect_type_error("Not an object");
return vi.started_object();
}
fn start_array(vi: *ValueIterator) !bool {
var json: [*]const u8 = try vi.advance_container_start("array", 1);
if (json[0] != '[')
return vi.incorrect_type_error("Not an array");
return vi.started_array();
}
fn field_key(vi: *ValueIterator) ![*]const u8 {
vi.assert_at_next();
var key = try vi.iter.advance(try std.math.cast(u16, std.math.min(
READ_BUF_CAP,
vi.peek_start_length(),
)));
if (key[0] != '"')
return vi.iter.report_error(error.TAPE_ERROR, "Object key is not a string");
return key;
}
fn field_value(vi: *ValueIterator) !void {
vi.assert_at_next();
if ((try vi.iter.advance(1))[0] != ':')
return vi.iter.report_error(error.TAPE_ERROR, "Missing colon in object field");
vi.iter.descend_to(vi.depth + 1);
}
pub fn find_field(vi: ValueIterator, key: []const u8) Value {
return vi.start_or_resume_object().find_field(key);
}
fn at_start(vi: ValueIterator) bool {
return vi.iter.token.index == vi.start_position;
}
fn at_first_field(vi: ValueIterator) bool {
assert(@ptrToInt(vi.iter.token.index) > @ptrToInt(vi.start_position));
return vi.iter.token.index == vi.start_position + 1;
}
fn abandon(vi: *ValueIterator) void {
vi.iter.abandon();
}
pub fn copy_key_with_quotes(key_buf: []u8, key: [*]const u8, key_len: usize) void {
mem.copy(u8, key_buf, key[0..std.math.min(key_len + 2, key_buf.len)]);
// return key_buf[0 .. key_len + 2];
}
fn copy_key_without_quotes(key_buf: []u8, key: [*]const u8, key_len: usize) void {
mem.copy(u8, key_buf, key[1..std.math.min(key_len, key_buf.len)]);
// const end = string_parsing.parse_string(key + 1, key_buf.ptr);
// const len = try cmn.ptr_diff(u8, end.?, key_buf.ptr);
// return key_buf[0..len];
}
fn find_field_raw(vi: *ValueIterator, key: []const u8) !bool {
// cmn.println("find_field_raw vi.depth {} vi.iter.depth {}", .{ vi.depth, vi.iter.depth });
var has_value = false;
// TODO add build option for this key buffer length
var key_buf: [1024]u8 = undefined;
errdefer vi.abandon();
//
// Initially, the object can be in one of a few different places:
//
// 1. The start of the object, at the first field:
//
// ```
// { "a": [ 1, 2 ], "b": [ 3, 4 ] }
// ^ (depth 2, index 1)
// ```
//
if (vi.at_first_field()) {
has_value = true;
//
// 2. When a previous search did not yield a value or the object is empty:
//
// ```
// { "a": [ 1, 2 ], "b": [ 3, 4 ] }
// ^ (depth 0)
// { }
// ^ (depth 0, index 2)
// ```
//
} else if (!vi.is_open()) {
// #ifdef SIMDJSON_DEVELOPMENT_CHECKS
// // If we're past the end of the object, we're being iterated out of order.
// // Note: this isn't perfect detection. It's possible the user is inside some other object; if so,
// // this object iterator will blithely scan that object for fields.
// if (vi.iter.depth() < depth() - 1) { return OUT_OF_ORDER_ITERATION; }
// #endif
has_value = false;
// 3. When a previous search found a field or an iterator yielded a value:
//
// ```
// // When a field was not fully consumed (or not even touched at all)
// { "a": [ 1, 2 ], "b": [ 3, 4 ] }
// ^ (depth 2)
// // When a field was fully consumed
// { "a": [ 1, 2 ], "b": [ 3, 4 ] }
// ^ (depth 1)
// // When the last field was fully consumed
// { "a": [ 1, 2 ], "b": [ 3, 4 ] }
// ^ (depth 1)
// ```
//
} else {
try vi.skip_child();
has_value = try vi.has_next_field();
// #ifdef SIMDJSON_DEVELOPMENT_CHECKS
// if (vi.iter.start_position(_depth) != _start_position) { return OUT_OF_ORDER_ITERATION; }
// #endif
}
while (has_value) {
// Get the key and colon, stopping at the value.
if (key.len + 2 > key_buf.len) return error.STRING_ERROR;
copy_key_with_quotes(&key_buf, try vi.field_key(), key.len);
cmn.println("actual_key '{s}'", .{key_buf[0..key.len]});
// size_t max_key_length = vi.iter.peek_length() - 2; // -2 for the two quotes
// if ((error = field_key().get(actual_key) )) { abandon(); return error; };
try vi.field_value();
// If it matches, stop and return
// We could do it this way if we wanted to allow arbitrary
// key content (including escaped quotes).
//if (actual_key.unsafe_is_equal(max_key_length, key)) {
// Instead we do the following which may trigger buffer overruns if the
// user provides an adversarial key (containing a well placed unescaped quote
// character and being longer than the number of bytes remaining in the JSON
// input).
if (unsafe_is_equal(&key_buf, key)) {
vi.iter.parser.log.event(&vi.iter, "match ", key, -2, 0);
return true;
}
// No match: skip the value and see if , or } is next
vi.iter.parser.log.event(&vi.iter, "no match ", key, -2, 0);
try vi.skip_child(); // Skip the value entirely
has_value = try vi.has_next_field();
}
// If the loop ended, we're out of fields to look at.
return false;
}
fn find_field_unordered_raw(vi: *ValueIterator, key: []const u8) !bool {
errdefer vi.abandon();
var has_value: bool = undefined;
var key_buf: [1024]u8 = undefined;
//
// Initially, the object can be in one of a few different places:
//
// 1. The start of the object, at the first field:
//
// ```
// { "a": [ 1, 2 ], "b": [ 3, 4 ] }
// ^ (depth 2, index 1)
// ```
//
if (vi.at_first_field()) {
// If we're at the beginning of the object, we definitely have a field
has_value = true;
// 2. When a previous search did not yield a value or the object is empty:
//
// ```
// { "a": [ 1, 2 ], "b": [ 3, 4 ] }
// ^ (depth 0)
// { }
// ^ (depth 0, index 2)
// ```
//
} else if (!vi.is_open()) {
// #ifdef SIMDJSON_DEVELOPMENT_CHECKS
// // If we're past the end of the object, we're being iterated out of order.
// // Note: this isn't perfect detection. It's possible the user is inside some other object; if so,
// // this object iterator will blithely scan that object for fields.
// if (vi.iter.depth() < depth() - 1) { return OUT_OF_ORDER_ITERATION; }
// #endif
has_value = false;
// 3. When a previous search found a field or an iterator yielded a value:
//
// ```
// // When a field was not fully consumed (or not even touched at all)
// { "a": [ 1, 2 ], "b": [ 3, 4 ] }
// ^ (depth 2)
// // When a field was fully consumed
// { "a": [ 1, 2 ], "b": [ 3, 4 ] }
// ^ (depth 1)
// // When the last field was fully consumed
// { "a": [ 1, 2 ], "b": [ 3, 4 ] }
// ^ (depth 1)
// ```
//
} else {
// Finish the previous value and see if , or } is next
try vi.skip_child();
has_value = try vi.has_next_field();
// #ifdef SIMDJSON_DEVELOPMENT_CHECKS
// if (vi.iter.start_position(_depth) != _start_position) { return OUT_OF_ORDER_ITERATION; }
// #endif
}
// After initial processing, we will be in one of two states:
//
// ```
// // At the beginning of a field
// { "a": [ 1, 2 ], "b": [ 3, 4 ] }
// ^ (depth 1)
// { "a": [ 1, 2 ], "b": [ 3, 4 ] }
// ^ (depth 1)
// // At the end of the object
// { "a": [ 1, 2 ], "b": [ 3, 4 ] }
// ^ (depth 0)
// ```
//
// First, we scan from that point to the end.
// If we don't find a match, we loop back around, and scan from the beginning to that point.
const search_start = vi.iter.token.index;
// Next, we find a match starting from the current position.
while (has_value) {
assert(vi.iter.depth == vi.depth); // We must be at the start of a field
// Get the key and colon, stopping at the value.
// size_t max_key_length = vi.iter.peek_length() - 2; // -2 for the two quotes
if (key.len + 2 > key_buf.len) return error.STRING_ERROR;
copy_key_with_quotes(&key_buf, try vi.field_key(), key.len);
try vi.field_value();
// If it matches, stop and return
// We could do it this way if we wanted to allow arbitrary
// key content (including escaped quotes).
// if (actual_key.unsafe_is_equal(max_key_length, key)) {
// Instead we do the following which may trigger buffer overruns if the
// user provides an adversarial key (containing a well placed unescaped quote
// character and being longer than the number of bytes remaining in the JSON
// input).
if (unsafe_is_equal(&key_buf, key)) {
vi.iter.parser.log.event(&vi.iter, "match ", key, -2, 0);
return true;
}
// No match: skip the value and see if , or } is next
vi.iter.parser.log.event(&vi.iter, "no match ", key, -2, 0);
try vi.skip_child();
has_value = try vi.has_next_field();
}
// If we reach the end without finding a match, search the rest of the fields starting at the
// beginning of the object.
// (We have already run through the object before, so we've already validated its structure. We
// don't check errors in this bit.)
vi.iter.reenter_child(vi.start_position + 1, vi.depth);
has_value = try vi.started_object();
while (@ptrToInt(vi.iter.token.index) < @ptrToInt(search_start)) {
assert(has_value); // we should reach search_start before ever reaching the end of the object
assert(vi.iter.depth == vi.depth); // We must be at the start of a field
// Get the key and colon, stopping at the value.
// size_t max_key_length = vi.iter.peek_length() - 2; // -2 for the two quotes
if (key.len + 2 > key_buf.len) return error.STRING_ERROR;
copy_key_with_quotes(&key_buf, try vi.field_key(), key.len);
try vi.field_value();
// If it matches, stop and return
// We could do it this way if we wanted to allow arbitrary
// key content (including escaped quotes).
// if (actual_key.unsafe_is_equal(max_key_length, key)) {
// Instead we do the following which may trigger buffer overruns if the
// user provides an adversarial key (containing a well placed unescaped quote
// character and being longer than the number of bytes remaining in the JSON
// input).
if (unsafe_is_equal(&key_buf, key)) {
vi.iter.parser.log.event(&vi.iter, "match ", key, -2, 0);
return true;
}
// No match: skip the value and see if , or } is next
vi.iter.parser.log.event(&vi.iter, "no match ", key, -2, 0);
try vi.skip_child();
has_value = try vi.has_next_field();
}
// If the loop ended, we're out of fields to look at.
return false;
}
fn child(vi: ValueIterator) ValueIterator {
vi.assert_at_child();
return ValueIterator.init(vi.iter, vi.depth + 1, vi.iter.token.index);
}
pub fn get_int(vi: *ValueIterator, comptime T: type) !T {
const peek_len = comptime try std.math.cast(u16, std.math.log10(@as(usize, std.math.maxInt(T))));
const u64int = try number_parsing.parse_integer(
try vi.advance_non_root_scalar(@typeName(T), peek_len),
);
return std.math.cast(T, if (@typeInfo(T).Int.signedness == .signed)
@bitCast(i64, u64int)
else
u64int);
}
pub fn unescape(comptime T: type, src: [*]const u8, dst: [*]u8) !T {
const end = string_parsing.parse_string(src, dst) orelse return error.STRING_ERROR;
const len = try cmn.ptr_diff(u32, end, dst);
return @as(T, dst[0..len]);
}
pub fn get_string(vi: *ValueIterator, comptime T: type, dest: []u8) !T {
if (dest.len + 2 < vi.peek_start_length()) return error.CAPACITY;
const peek_len = try std.math.cast(u16, std.math.min(READ_BUF_CAP, dest.len));
return unescape(T, try vi.get_raw_json_string(peek_len), dest.ptr);
}
pub fn get_string_alloc(vi: *ValueIterator, comptime T: type, allocator: mem.Allocator) !T {
const str_len = try std.math.cast(u16, vi.peek_start_length());
if (str_len + 2 > READ_BUF_CAP) return error.CAPACITY;
const start = try vi.get_raw_json_string(str_len);
return string_parsing.parse_string_alloc(T, start, allocator, str_len);
}
fn advance_start(vi: *ValueIterator, typ: []const u8, peek_len: u16) ![*]const u8 {
vi.iter.parser.log.value2(&vi.iter, typ, "", vi.start_position[0], vi.depth);
// If we're not at the position anymore, we don't want to advance the cursor.
if (!vi.is_at_start()) return vi.peek_start(peek_len);
// Get the JSON and advance the cursor, decreasing depth to signify that we have retrieved the value.
vi.assert_at_start();
const result = try vi.iter.advance(peek_len);
vi.iter.ascend_to(vi.depth - 1);
return result;
}
pub fn get_raw_json_string(vi: *ValueIterator, peek_len: u16) ![*]const u8 {
const json = try vi.advance_start("string", peek_len);
if (json[0] != '"')
return vi.incorrect_type_error("Not a string");
return json + 1;
}
pub fn get_double(vi: *ValueIterator) !f64 {
return number_parsing.parse_double(try vi.advance_non_root_scalar("double", 40));
}
pub fn get_bool(vi: *ValueIterator) !bool {
return vi.parse_bool(try vi.advance_non_root_scalar("bool", 6));
}
fn peek_start_length(vi: *ValueIterator) u32 {
return Iterator.peek_length(vi.start_position);
}
fn get_root_int(vi: *ValueIterator, comptime T: type) !T {
const max_len = vi.peek_start_length();
const json = try vi.advance_root_scalar("int64", try std.math.cast(u16, max_len));
var tmpbuf: [20 + 1]u8 = undefined; // -<19 digits> is the longest possible integer
if (!Iterator.copy_to_buffer(json, max_len, tmpbuf.len, &tmpbuf)) {
vi.iter.parser.log.err_fmt(&vi.iter, "Root number more than 20 characters. start_position {} depth {}", .{ vi.start_position[0], vi.depth });
return error.NUMBER_ERROR;
}
return std.math.cast(T, try number_parsing.parse_integer(&tmpbuf));
}
fn get_root_double(vi: *ValueIterator) !f64 {
const max_len = vi.peek_start_length();
const N = comptime std.math.min(1074 + 8 + 1, READ_BUF_CAP);
const json = try vi.advance_root_scalar("double", N);
// Per https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/, 1074 is the maximum number of significant fractional digits. Add 8 more digits for the biggest number: -0.<fraction>e-308.
var tmpbuf: [N]u8 = undefined;
if (!Iterator.copy_to_buffer(json, max_len, N, &tmpbuf)) {
vi.iter.parser.log.err_fmt(&vi.iter, "Root number more than 1082 characters. start_position {} depth {}", .{ vi.start_position[0], vi.depth });
return error.NUMBER_ERROR;
}
return number_parsing.parse_double(&tmpbuf);
}
fn get_root_string(vi: *ValueIterator, comptime T: type, dest: []u8) !T {
return vi.get_string(T, dest);
}
fn get_root_string_alloc(vi: *ValueIterator, comptime T: type, allocator: mem.Allocator) !T {
return vi.get_string_alloc(T, allocator);
}
fn get_root_bool(vi: *ValueIterator) !bool {
const max_len = vi.peek_start_length();
const json = try vi.advance_root_scalar("bool", 5);
var tmpbuf: [5 + 1]u8 = undefined;
if (!Iterator.copy_to_buffer(json, max_len, tmpbuf.len, &tmpbuf))
return vi.incorrect_type_error("Not a boolean");
return vi.parse_bool(&tmpbuf);
}
fn is_root_null(vi: *ValueIterator) !bool {
const max_len = vi.peek_start_length();
const json = try vi.advance_root_scalar("null", 4);
return max_len >= 4 and !atom_parsing.is_valid_atom(json[0..4], 4, atom_parsing.atom_null) or
(max_len == 4 or CharUtils.is_structural_or_whitespace(json[5]));
}
pub fn get_type(vi: *ValueIterator) !ValueType {
const start = try vi.peek_start(1);
return switch (start[0]) {
'{' => .object,
'[' => .array,
'"' => .string,
'n' => .nul,
't', 'f' => .bool,
'-', '0'...'9' => .number,
else => error.TAPE_ERROR,
};
}
};
fn unsafe_is_equal(a: [*]const u8, target: []const u8) bool {
// Assumptions: does not contain unescaped quote characters, and
// the raw content is quote terminated within a valid JSON string.
if (target.len <= cmn.SIMDJSON_PADDING)
return (a[target.len + 1] == '"') and mem.eql(u8, a[1 .. target.len + 1], target);
var r = a;
var pos: usize = 0;
while (pos < target.len) : (pos += 1) {
if (r[pos] != target[pos]) {
return false;
}
}
if (r[pos] != '"') {
return false;
}
return true;
}
pub const ValueType = enum(u3) {
// Start at 1 to catch uninitialized / default values more easily
/// A JSON array ( [ 1, 2, 3 ... ] )
array = 1,
/// A JSON object ( { "a": 1, "b" 2, ... } )
object,
/// A JSON number ( 1 or -2.3 or 4.5e6 ...)
number,
/// A JSON string ( "a" or "hello world\n" ...)
string,
/// A JSON boolean (true or false)
bool,
/// A JSON null (null)
nul,
};
pub const Document = struct {
iter: Iterator,
pub const DOCUMENT_DEPTH = 0;
inline fn get_root_value_iterator(doc: *Document) ValueIterator {
return doc.resume_value_iterator();
}
inline fn resume_value_iterator(doc: *Document) ValueIterator {
return ValueIterator.init(doc.iter, 1, doc.iter.root_checkpoint());
}
pub fn get_object(doc: *Document) !Object {
var val = doc.get_root_value_iterator();
return try Object.start_root(&val);
}
pub fn get_array(doc: *Document) !Array {
var val = doc.get_root_value_iterator();
return Array.start_root(&val);
}
fn resume_value(doc: *Document) Value {
return Value{ .iter = doc.resume_value_iterator() };
}
pub fn find_field(doc: *Document, key: []const u8) !Value {
return doc.resume_value().find_field(key);
}
pub fn find_field_unordered(doc: *Document, key: []const u8) !Value {
return doc.resume_value().find_field_unordered(key);
}
pub fn get_int(doc: *Document, comptime T: type) !T {
return doc.get_root_value_iterator().get_root_int(T);
}
pub fn get_string(doc: *Document, comptime T: type, buf: []u8) !T {
return doc.get_root_value_iterator().get_root_string(T, buf);
}
pub fn get_string_alloc(doc: *Document, comptime T: type, allocator: mem.Allocator) !T {
return doc.get_root_value_iterator().get_root_string_alloc(T, allocator);
}
pub fn get_double(doc: *Document) !f64 {
return doc.get_root_value_iterator().get_root_double();
}
pub fn get_bool(doc: *Document) !bool {
return doc.get_root_value_iterator().get_root_bool();
}
pub fn is_null(doc: *Document) !bool {
return doc.get_root_value_iterator().is_root_null();
}
pub fn rewind(doc: *Document) !void {
return doc.iter.rewind();
}
pub fn get_type(doc: *Document) !ValueType {
return doc.get_root_value_iterator().get_type();
}
pub fn at_pointer(doc: *Document, json_pointer: []const u8) !Value {
try doc.rewind(); // Rewind the document each time at_pointer is called
if (json_pointer.len == 0)
return doc.resume_value();
return switch (try doc.get_type()) {
.array => (try doc.get_array()).at_pointer(json_pointer),
.object => (try doc.get_object()).at_pointer(json_pointer),
else => error.INVALID_JSON_POINTER,
};
}
pub fn get(doc: *Document, out: anytype, options: GetOptions) !void {
return doc.value().get(out, options);
}
pub fn value(doc: *Document) Value {
return Value{ .iter = doc.get_root_value_iterator() };
}
pub fn raw_json_token(doc: *Document) ![]const u8 {
var iter = doc.get_root_value_iterator();
const len = try std.math.cast(u16, iter.peek_start_length());
const ptr = try iter.peek_start(len);
return ptr[0..len];
}
};
pub const Parser = struct {
parser: dom.Parser,
src: *std.io.StreamSource,
end_pos: u32,
read_buf: [READ_BUF_CAP]u8 = undefined,
/// result of src.read() - number of bytes read from src
read_buf_len: u16 = 0,
/// src index of the start of the buffer. set to index[0] each src.read()
read_buf_start_pos: u32,
log: Logger = .{ .depth = 0 },
pub fn init(src: *std.io.StreamSource, allocator: mem.Allocator, filename: []const u8, options: dom.Parser.Options) !Parser {
var result = Parser{
.parser = .{
.allocator = allocator,
.filename = filename,
.doc = dom.Document.init(),
.indexer = try dom.StructuralIndexer.init(),
.open_containers = std.MultiArrayList(dom.OpenContainerInfo){},
.max_depth = options.max_depth,
},
.src = src,
.end_pos = try std.math.cast(u32, try src.getEndPos()),
.read_buf_start_pos = 0,
.read_buf_len = 0,
};
const capacity = result.end_pos;
const max_structures = cmn.ROUNDUP_N(capacity, 64) + 2 + 7;
try result.parser.indexer.bit_indexer.tail.ensureTotalCapacity(allocator, max_structures);
try result.parser.open_containers.ensureTotalCapacity(allocator, options.max_depth);
return result;
}
pub fn deinit(p: *Parser) void {
p.parser.deinit();
}
pub fn stage1(p: *Parser) !void {
var pos: u32 = 0;
var read_buf: [cmn.STEP_SIZE]u8 = undefined;
var bytes_read: u32 = undefined;
cmn.println("", .{});
while (true) : (pos += cmn.STEP_SIZE) {
// cmn.println("i {} pos {}", .{ i, pos });
bytes_read = @intCast(u32, try p.src.read(&read_buf));
if (bytes_read < cmn.STEP_SIZE) break;
try p.parser.indexer.step(read_buf, &p.parser, pos);
// for (blocks) |block| {
// cmn.println("{b:0>64} | characters.whitespace", .{@bitReverse(u64, block.characters.whitespace)});
// cmn.println("{b:0>64} | characters.op", .{@bitReverse(u64, block.characters.op)});
// cmn.println("{b:0>64} | in_string", .{@bitReverse(u64, block.strings.in_string)});
// }
}
std.mem.set(u8, read_buf[bytes_read..], 0x20);
// std.log.debug("read_buf {d}", .{read_buf});
try p.parser.indexer.step(read_buf, &p.parser, pos);
try p.parser.indexer.finish(&p.parser, pos + cmn.STEP_SIZE, pos + bytes_read, cmn.STREAMING);
}
pub fn iterate(p: *Parser) !Document {
try p.stage1();
return Document{ .iter = Iterator.init(p) };
}
inline fn structural_indices(parser: Parser) []u32 {
return parser.parser.indexer.bit_indexer.tail.items;
}
/// position: pointer to a src position
/// len_hint: requested length to be read from src, starting at position
pub fn peek(
parser: *Parser,
position: [*]const u32,
len_hint: u16,
) ![*]const u8 {
// cmn.println("peek() len_hint {} READ_BUF_CAP {}", .{ len_hint, READ_BUF_CAP });
if (len_hint > READ_BUF_CAP) return error.CAPACITY;
const start_pos = position[0];
// cmn.println("\nTokenIterator: {} <= start {} end {} < read_buf_start_pos + len {}", .{ read_buf_start_pos, start, end, read_buf_start_pos + read_buf_len });
if (parser.read_buf_start_pos <= start_pos and start_pos < parser.read_buf_start_pos + parser.read_buf_len) blk: {
const offset = start_pos - parser.read_buf_start_pos;
if (offset + len_hint > READ_BUF_CAP) break :blk;
return @ptrCast([*]const u8, &parser.read_buf) + offset;
}
// cmn.println("TokenIterator: seek and read()", .{});
try parser.src.seekTo(start_pos);
parser.read_buf_start_pos = start_pos;
// not sure that 0xaa is the best value here but it does prevent false positives like [nul]
@memset(&parser.read_buf, 0xaa, READ_BUF_CAP);
parser.read_buf_len = @truncate(u16, try parser.src.read(&parser.read_buf));
return &parser.read_buf;
}
}; | src/ondemand.zig |
// SPDX-License-Identifier: MIT
// This file is part of the Termelot project under the MIT license.
const std = @import("std");
const termelot = @import("../termelot.zig");
usingnamespace termelot.style;
usingnamespace termelot.event;
const BackendName = termelot.backend.BackendName;
const Config = termelot.Config;
const Position = termelot.Position;
const Rune = termelot.Rune;
const Size = termelot.Size;
const SupportedFeatures = termelot.SupportedFeatures;
const windows = std.os.windows;
// WINAPI defines not made in standard library as of Zig commit 84d50c892
const COLORREF = windows.DWORD;
const CONSOLE_CURSOR_INFO = extern struct {
dwSize: windows.DWORD,
bVisible: windows.BOOL,
};
const CONSOLE_SCREEN_BUFFER_INFOEX = extern struct {
cbSize: windows.ULONG,
dwSize: windows.COORD,
dwCursorPosition: windows.COORD,
wAttributes: windows.WORD,
srWindow: windows.SMALL_RECT,
dwMaximumWindowSize: windows.COORD,
wPopupAttributes: windows.WORD,
bFullscreenSupported: windows.BOOL,
ColorTable: [16]COLORREF,
};
extern "kernel32" fn CreateConsoleScreenBuffer(
dwDesiredAccess: windows.DWORD,
dwShareMode: windows.DWORD,
lpSecurityAttributes: ?*const windows.SECURITY_ATTRIBUTES,
dwFlags: windows.DWORD,
lpScreenBufferData: ?windows.LPVOID,
) callconv(.Stdcall) windows.HANDLE;
extern "kernel32" fn CreateFileA(
lpFileName: windows.LPCSTR,
dwDesiredAccess: windows.DWORD,
dwShareMode: windows.DWORD,
lpSecurityAttributes: ?*const windows.SECURITY_ATTRIBUTES,
dwCreationDisposition: windows.DWORD,
dwFlagsAndAttributes: windows.DWORD,
hTemplateFile: ?windows.HANDLE,
) callconv(.Stdcall) windows.HANDLE;
const FOCUS_EVENT_RECORD = extern struct {
bSetFocus: bool,
};
// For KeyEvent
const CAPSLOCK_ON: windows.DWORD = 0x0080;
const ENHANCED_KEY: windows.DWORD = 0x0100;
const LEFT_ALT_PRESSED: windows.DWORD = 0x0002;
const LEFT_CTRL_PRESSED: windows.DWORD = 0x0008;
const NUMLOCK_ON: windows.DWORD = 0x0020;
const RIGHT_ALT_PRESSED: windows.DWORD = 0x0001;
const RIGHT_CTRL_PRESSED: windows.DWORD = 0x0004;
const SCROLLLOCK_ON: windows.DWORD = 0x0040;
const SHIFT_PRESSED: windows.DWORD = 0x0010;
// For MouseEvent
const DOUBLE_CLICK: windows.DWORD = 0x0002;
const MOUSE_HWHEELED: windows.DWORD = 0x0008;
const MOUSE_MOVED: windows.DWORD = 0x0001;
const MOUSE_WHEELED: windows.DWORD = 0x0004;
// For EventType and InputEvent
const FOCUS_EVENT: windows.DWORD = 0x0010;
const KEY_EVENT: windows.DWORD = 0x0001;
const MENU_EVENT: windows.DWORD = 0x0008;
const MOUSE_EVENT: windows.DWORD = 0x0002;
const WINDOW_BUFFER_SIZE_EVENT: windows.DWORD = 0x0004;
// For MouseEvent button
const FROM_LEFT_1ST_BUTTON_PRESSED: windows.DWORD = 0x0001;
const FROM_LEFT_2ND_BUTTON_PRESSED: windows.DWORD = 0x0004;
const FROM_LEFT_3RD_BUTTON_PRESSED: windows.DWORD = 0x0008;
const FROM_LEFT_4TH_BUTTON_PRESSED: windows.DWORD = 0x0010;
const RIGHTMOST_BUTTON_PRESSED: windows.DWORD = 0x0002;
extern "kernel32" fn GetConsoleCursorInfo(
hConsoleOutput: windows.HANDLE,
lpConsoleCursorInfo: *CONSOLE_CURSOR_INFO,
) callconv(.Stdcall) windows.BOOL;
extern "kernel32" fn GetConsoleScreenBufferInfoEx(
hConsoleOutput: windows.HANDLE,
lpConsoleScreenBufferInfoEx: *CONSOLE_SCREEN_BUFFER_INFOEX,
) callconv(.Stdcall) windows.BOOL;
extern "kernel32" fn GetNumberOfConsoleInputEvents(
hConsoleInput: windows.HANDLE,
lpcNumberOfEvents: windows.LPDWORD,
) callconv(.Stdcall) windows.BOOL;
const INPUT_RECORD = extern struct {
EventType: windows.DWORD,
Event: extern union {
KeyEvent: KEY_EVENT_RECORD,
MouseEvent: MOUSE_EVENT_RECORD,
WindowBufferSizeEvent: WINDOW_BUFFER_SIZE_RECORD,
MenuEvent: MENU_EVENT_RECORD,
FocusEvent: FOCUS_EVENT_RECORD,
},
};
const KEY_EVENT_RECORD = extern struct {
bKeyDown: windows.BOOL,
wRepeatCount: windows.WORD,
wVirtualKeyCode: windows.WORD,
wVirtualScanCode: windows.WORD,
uChar: extern union {
UnicodeChar: windows.WCHAR,
AsciiChar: windows.CHAR,
},
dwControlKeyState: windows.DWORD,
};
const MENU_EVENT_RECORD = extern struct {
dwCommandId: windows.UINT,
};
const MOUSE_EVENT_RECORD = extern struct {
dwMousePosition: windows.COORD,
dwButtonState: windows.DWORD,
dwControlKeyState: windows.DWORD,
dwEventFlags: windows.DWORD,
};
extern "kernel32" fn ReadConsoleInputA(
hConsoleInput: windows.HANDLE,
lpBuffer: [*]INPUT_RECORD,
nLength: windows.DWORD,
lpNumberOfEventsRead: ?windows.LPDWORD,
) callconv(.Stdcall) windows.BOOL;
extern "kernel32" fn SetConsoleActiveScreenBuffer(
hConsoleOutput: windows.HANDLE,
) callconv(.Stdcall) windows.BOOL;
extern "kernel32" fn SetConsoleCursorInfo(
hConsoleOutput: windows.HANDLE,
lpConsoleCursorInfo: *const CONSOLE_CURSOR_INFO,
) callconv(.Stdcall) windows.BOOL;
extern "kernel32" fn SetConsoleMode(
hConsoleHandle: windows.HANDLE,
dwMode: windows.DWORD,
) callconv(.Stdcall) windows.BOOL;
extern "kernel32" fn SetConsoleScreenBufferInfoEx(
hConsoleOutput: windows.HANDLE,
lpConsoleScreenBufferInfoEx: *const CONSOLE_SCREEN_BUFFER_INFOEX,
) callconv(.Stdcall) windows.BOOL;
extern "kernel32" fn SetConsoleTitleA(
lpConsoleTitle: windows.LPCTSTR,
) callconv(.Stdcall) windows.BOOL;
const WINDOW_BUFFER_SIZE_RECORD = extern struct {
dwSize: windows.COORD,
};
const WindowBufferSizeEvent = WINDOW_BUFFER_SIZE_RECORD;
extern "kernel32" fn WriteConsoleA(
hConsoleOutput: windows.HANDLE,
lpBuffer: *const c_void,
nNumberOfCharsToWrite: windows.DWORD,
lpNumberOfCharsWritten: ?windows.LPDWORD,
lpReserved: ?windows.LPVOID,
) callconv(.Stdcall) windows.BOOL;
extern "kernel32" fn WriteConsoleOutputAttribute(
hConsoleOutput: windows.HANDLE,
lpAttribute: *const windows.WORD,
nLength: windows.DWORD,
dwWriteCoord: windows.COORD,
lpNumberOfAttrsWritten: windows.LPDWORD,
) callconv(.Stdcall) windows.BOOL;
extern "kernel32" fn WriteConsoleOutputCharacterA(
hConsoleOutput: windows.HANDLE,
lpCharacter: [*]const windows.TCHAR,
nLength: windows.DWORD,
dwWriteCoord: windows.COORD,
lpNumberOfCharsWritten: windows.LPDWORD,
) callconv(.Stdcall) windows.BOOL;
const CONSOLE_TEXTMODE_BUFFER: windows.DWORD = 1;
// when hConsoleHandle param is an input handle:
const ENABLE_ECHO_INPUT: windows.DWORD = 0x0004;
const ENABLE_EXTENDED_FLAGS: windows.DWORD = 0x0080;
const ENABLE_INSERT_MODE: windows.DWORD = 0x0020;
const ENABLE_LINE_MODE: windows.DWORD = 0x0002;
const ENABLE_MOUSE_INPUT: windows.DWORD = 0x0010;
const ENABLE_PROCESSED_INPUT: windows.DWORD = 0x0001;
const ENABLE_QUICK_EDIT_MODE: windows.DWORD = 0x0040;
const ENABLE_WINDOW_INPUT: windows.DWORD = 0x0008;
const ENABLE_VIRTUAL_TERMINAL_INPUT: windows.DWORD = 0x0200;
// when hConsoleHandle param is a screen buffer handle:
const ENABLE_PROCESSED_OUTPUT: windows.DWORD = 0x0001;
const ENABLE_WRAP_AT_EOL_OUTPUT: windows.DWORD = 0x0002;
const ENABLE_VIRTUAL_TERMINAL_PROCESSING: windows.DWORD = 0x0004;
const DISABLE_NEWLINE_AUTO_RETURN: windows.DWORD = 0x0008;
const ENABLE_LVB_GRID_WORLDWIDE: windows.DWORD = 0x0010;
pub const Backend = struct {
termelot: *Termelot,
allocator: *std.mem.Allocator,
h_console_out_main: windows.HANDLE,
h_console_out_current: windows.HANDLE,
h_console_out_alt: ?windows.HANDLE,
h_console_in: windows.HANDLE,
in_raw_mode: bool,
restore_console_mode_out: windows.DWORD,
restore_console_mode_in: windows.DWORD,
restore_wattributes: windows.WORD,
cached_ansi_escapes_enabled: bool, // For use internally
input_thread: ?*std.Thread,
input_thread_running: bool,
const Self = @This();
/// The tag of a backend is like its identifier. It is used in the build system, and by users
/// for comptime code.
pub const tag = BackendName.unimplemented;
/// Initialize backend
pub fn init(
termelot: *Termelot,
allocator: *std.mem.Allocator,
config: Config,
) !Backend {
// Get console handles
const out_main = try windows.GetStdHandle(windows.STD_OUTPUT_HANDLE);
const in_main = CreateFileA(
"CONIN$",
windows.GENERIC_READ | windows.GENERIC_WRITE,
windows.FILE_SHARE_READ | windows.FILE_SHARE_WRITE,
null,
windows.OPEN_EXISTING,
windows.FILE_ATTRIBUTE_NORMAL,
null);
if (in_main == windows.INVALID_HANDLE_VALUE) {
return error.BackendError;
}
// Set restore values
var rcm_out: windows.DWORD = undefined;
if (windows.kernel32.GetConsoleMode(out_main, &rcm_out) == 0) {
return error.BackendError;
}
var rcm_in: windows.DWORD = undefined;
if (windows.kernel32.GetConsoleMode(in_main, &rcm_in) == 0) {
return error.BackendError;
}
var b = Backend{
.termelot = termelot,
.allocator = allocator,
.h_console_out_main = out_main,
.h_console_out_current = out_main,
.h_console_in = in_main,
.h_console_out_alt = null,
.in_raw_mode = false,
.restore_console_mode_out = rcm_out,
.restore_console_mode_in = rcm_in,
.restore_wattributes = undefined,
.cached_ansi_escapes_enabled = false,
.input_thread = null,
.input_thread_running = false,
};
b.restore_wattributes = (try b.getScreenBufferInfo()).wAttributes;
// Attempt to enable ANSI escape sequences while initializing (Windows 10+)
b.updateCachedANSIEscapesEnabled() catch {};
if (!b.cached_ansi_escapes_enabled) enable: {
b.enableANSIEscapeSequences() catch { break :enable; };
b.updateCachedANSIEscapesEnabled() catch {}; // Recache
}
return b;
}
/// Deinitialize backend
pub fn deinit(self: *Self) void {
defer _ = windows.kernel32.CloseHandle(self.h_console_in);
defer _ = windows.kernel32.CloseHandle(self.h_console_out_main);
if (self.h_console_out_alt) |handle| {
_ = windows.kernel32.CloseHandle(handle);
}
// Restore console behavior
_ = SetConsoleMode(self.h_console_out_main, self.restore_console_mode_out);
_ = SetConsoleMode(self.h_console_in, self.restore_console_mode_in);
_ = windows.kernel32.SetConsoleTextAttribute(self.h_console_out_main, self.restore_wattributes);
}
fn WriteConsole(self: *Self, buffer: []const Rune, chars_written: ?windows.LPDWORD) !void { // TODO: update function to support UTF-16 (when sizeof Rune is UTF-16)
if (WriteConsoleA(self.h_console_out_current, buffer.ptr, @intCast(windows.DWORD, buffer.len), chars_written, null) == 0)
return error.BackendError;
}
/// Retrieve SupportedFeatures struct from this backend.
pub fn getSupportedFeatures(self: *Self) !SupportedFeatures {
const ansi = self.cached_ansi_escapes_enabled;
return SupportedFeatures{
.color_types = .{
.Named16 = true,
.Bit8 = false, // but they're rounded to Named16
.Bit24 = false, // but they're rounded to Named16
},
.decorations = Decorations{
.bold = ansi,
.italic = ansi,
.underline = ansi,
.blinking = ansi,
},
};
}
/// Retrieve raw mode status.
pub fn getRawMode(self: *Self) !bool {
return self.in_raw_mode;
}
/// Checks if the Console modes allow for ANSI escape sequences to be used.
fn updateCachedANSIEscapesEnabled(self: *Self) !void {
var input_flags: windows.DWORD = undefined;
var output_flags: windows.DWORD = undefined;
if (windows.kernel32.GetConsoleMode(self.h_console_in, &input_flags) == 0)
return error.BackendError;
if (windows.kernel32.GetConsoleMode(self.h_console_out_current, &output_flags) == 0)
return error.BackendError;
self.cached_ansi_escapes_enabled = input_flags | ENABLE_VIRTUAL_TERMINAL_INPUT > 0
and output_flags | ENABLE_VIRTUAL_TERMINAL_PROCESSING > 0;
}
/// Will attempt to tell Windows that this console evaluates virtual terminal sequences.
fn enableANSIEscapeSequences(self: *Self) !void {
var input_flags: windows.DWORD = undefined;
var output_flags: windows.DWORD = undefined;
if (windows.kernel32.GetConsoleMode(self.h_console_in, &input_flags) == 0)
return error.BackendError;
if (windows.kernel32.GetConsoleMode(self.h_console_out_current, &output_flags) == 0)
return error.BackendError;
input_flags |= ENABLE_VIRTUAL_TERMINAL_INPUT;
output_flags |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
if (SetConsoleMode(self.h_console_in, input_flags) == 0)
return error.BackendError;
if (SetConsoleMode(self.h_console_out_current, output_flags) == 0)
return error.BackendError;
}
/// Enter/exit raw mode.
pub fn setRawMode(self: *Self, enabled: bool) !void {
var old_input_flags: windows.DWORD = undefined;
var old_output_flags: windows.DWORD = undefined;
if (windows.kernel32.GetConsoleMode(
self.h_console_in,
&old_input_flags,
) == 0) {
return error.BackendError;
}
if (windows.kernel32.GetConsoleMode(
self.h_console_out_current,
&old_output_flags,
) == 0) {
return error.BackendError;
}
var input_flags: windows.DWORD = undefined;
var output_flags: windows.DWORD = undefined;
if (enabled) {
input_flags = ENABLE_EXTENDED_FLAGS |
ENABLE_MOUSE_INPUT |
ENABLE_WINDOW_INPUT;
output_flags = DISABLE_NEWLINE_AUTO_RETURN;
} else {
input_flags = ENABLE_ECHO_INPUT |
ENABLE_EXTENDED_FLAGS |
ENABLE_INSERT_MODE |
ENABLE_LINE_MODE |
ENABLE_MOUSE_INPUT |
ENABLE_PROCESSED_INPUT |
ENABLE_QUICK_EDIT_MODE |
ENABLE_WINDOW_INPUT;
output_flags = ENABLE_PROCESSED_OUTPUT |
ENABLE_WRAP_AT_EOL_OUTPUT;
}
// Carry ANSI escape codes support if they were enabled previously
if (old_input_flags & ENABLE_VIRTUAL_TERMINAL_INPUT != 0
and old_output_flags & ENABLE_VIRTUAL_TERMINAL_PROCESSING != 0) {
input_flags |= ENABLE_VIRTUAL_TERMINAL_INPUT;
output_flags |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
}
if (SetConsoleMode(self.h_console_in, input_flags) == 0) {
return error.BackendError;
}
errdefer _ = SetConsoleMode(self.h_console_in, old_input_flags); // Reset flags
if (SetConsoleMode(
self.h_console_out_current,
output_flags,
) == 0) {
return error.BackendError;
}
errdefer _ = SetConsoleMode(self.h_console_in, old_output_flags); // Reset flags
self.in_raw_mode = enabled;
}
/// Retrieve alternate screen status.
pub fn getAlternateScreen(self: *Self) !bool {
if (self.h_console_out_alt) |handle| {
return handle == self.h_console_out_current;
}
return false;
}
/// Enter/exit alternate screen.
pub fn setAlternateScreen(self: *Self, enabled: bool) !void {
if (enabled) {
if (self.h_console_out_alt == null) {
self.h_console_out_alt = CreateConsoleScreenBuffer(
windows.GENERIC_READ | windows.GENERIC_WRITE,
windows.FILE_SHARE_READ | windows.FILE_SHARE_WRITE,
null,
CONSOLE_TEXTMODE_BUFFER,
null,
);
errdefer self.h_console_out_alt = null;
if (self.h_console_out_alt == windows.INVALID_HANDLE_VALUE) {
return error.BackendError;
}
}
if (self.h_console_out_alt) |handle| {
if (SetConsoleActiveScreenBuffer(handle) == 0) {
return error.BackendError;
}
self.h_console_out_current = handle;
}
} else {
if (SetConsoleActiveScreenBuffer(self.h_console_out_main) == 0) {
return error.BackendError;
}
self.h_console_out_current = self.h_console_out_main;
}
}
/// This is the only function that runs on another thread.
fn inputHandler(self: *Self) !void {
var input_buffer_arr: [8]INPUT_RECORD = undefined;
var input_buffer_len = @as(windows.DWORD, 0);
while (self.input_thread_running) { // TODO: consider healthy amt of time to sleep
var events_to_read = @as(windows.DWORD, 0);
if (GetNumberOfConsoleInputEvents(self.h_console_in, &events_to_read) == 0)
return error.BackendError;
if (events_to_read > 0) {
// Gather events into buffer
if (ReadConsoleInputA(self.h_console_in, &input_buffer_arr, 8, &input_buffer_len) == 0) {
std.log.crit("ReadConsoleInputA failed\n", .{});
return error.BackendError;
}
// Translate all events to termelot equivalent
var i: usize = 0;
while (i < input_buffer_len) : (i += 1) {
const record: INPUT_RECORD = input_buffer_arr[i];
switch (record.EventType) {
WINDOW_BUFFER_SIZE_EVENT => self.termelot.setScreenSize(try self.getScreenSize()),
MOUSE_EVENT => { // TODO: handle mouse moved and send only mouse pos
const mouse = record.Event.MouseEvent;
const pos = mouse.dwMousePosition;
self.termelot.callMouseCallbacks(termelot_import.event.mouse.Event {
.position = Position { .row = @intCast(u16, pos.Y), .col = @intCast(u16, pos.X) },
.time = 0, // TODO: ???
.action = action: {
if (mouse.dwEventFlags == DOUBLE_CLICK) {
break :action .DoubleClick;
}
if (mouse.dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED) {
break :action .Click;
}
if (mouse.dwEventFlags == MOUSE_WHEELED) {
if (mouse.dwButtonState & 0xFFFF > 0) {
break :action .ScrollUp;
} else {
break :action .ScrollDown;
}
}
continue; // No valid action... skip the event
},
.button = button: {
switch (mouse.dwButtonState) {
FROM_LEFT_1ST_BUTTON_PRESSED => break :button .Main,
FROM_LEFT_2ND_BUTTON_PRESSED => break :button .Secondary,
FROM_LEFT_3RD_BUTTON_PRESSED => break :button .Auxiliary,
FROM_LEFT_4TH_BUTTON_PRESSED => break :button .Fourth,
RIGHTMOST_BUTTON_PRESSED => break :button .Fifth,
else => break :button null,
}
},
});
},
KEY_EVENT => {
const key = record.Event.KeyEvent;
if (key.bKeyDown == 0) continue; // TODO: handle key up events in library
self.termelot.callKeyCallbacks(termelot_import.event.key.Event {
.value = value: {
break :value .{ .AlphaNumeric = key.uChar.AsciiChar };
},
.modifier = modifier: {
break :modifier null;
},
});
},
else => continue, // FOCUS_EVENT or MENU_EVENT (MSDN docs say to ignore)
}
// Send each event to user of termelot library's callbacks
// self.termelot.callKeyCallbacks(termelot_import.event.key.Event { .value = .{ .AlphaNumeric = 'a' }, .modifier = null });
}
input_buffer_len = 0;
}
}
}
/// Start event/signal handling loop, non-blocking immediate return.
pub fn start(self: *Self) !void {
// This function should call necessary functions for screen size
// update, key event callbacks, and mouse event callbacks.
self.input_thread_running = true;
self.input_thread = try std.Thread.spawn(self, Backend.inputHandler);
}
/// Stop event/signal handling loop.
pub fn stop(self: *Self) void {
if (self.input_thread) |thread| {
self.input_thread_running = false;
thread.wait();
}
}
fn getScreenBufferInfo(
self: *Self,
) !windows.CONSOLE_SCREEN_BUFFER_INFO {
var csbi: windows.CONSOLE_SCREEN_BUFFER_INFO = undefined;
if (windows.kernel32.GetConsoleScreenBufferInfo(
self.h_console_out_current,
&csbi,
) == 0) {
return error.BackendError;
}
return csbi;
}
/// Set terminal title.
pub fn setTitle(self: *Self, runes: []const Rune) !void {
const cstr = try std.cstr.addNullByte(self.allocator, runes);
if (SetConsoleTitleA(cstr) == 0) return error.BackendError;
}
/// Get screen size.
pub fn getScreenSize(self: *Self) !Size {
const csbi = try self.getScreenBufferInfo();
return Size{
.rows = @intCast(
u16,
csbi.srWindow.Bottom - csbi.srWindow.Top + 1,
),
.cols = @intCast(
u16,
csbi.srWindow.Right - csbi.srWindow.Left + 1,
),
};
}
/// Get cursor position.
pub fn getCursorPosition(self: *Self) !Position {
const csbi = try self.getScreenBufferInfo();
const coord = try self.coordToScreenSpace(csbi.dwCursorPosition);
return Position{
.col = @intCast(u16, coord.X),
.row = @intCast(u16, coord.Y),
};
}
/// Set cursor position.
pub fn setCursorPosition(self: *Self, position: Position) !void {
const coord = try self.coordToBufferSpace(windows.COORD{
.X = @intCast(windows.SHORT, position.col),
.Y = @intCast(windows.SHORT, position.row),
});
if (windows.kernel32.SetConsoleCursorPosition(
self.h_console_out_current,
coord,
) == 0) {
return error.BackendError;
}
}
/// Convert any Windows COORD (FROM screen space) TO buffer space.
pub fn coordToBufferSpace(self: *Self, coord: windows.COORD) !windows.COORD {
const csbi = try self.getScreenBufferInfo();
return windows.COORD{
.Y = coord.Y + csbi.srWindow.Top,
.X = coord.X + csbi.srWindow.Left,
};
}
/// Convert any Windows COORD (FROM buffer space) TO screen space.
pub fn coordToScreenSpace(self: *Self, coord: windows.COORD) !windows.COORD {
const csbi = try self.getScreenBufferInfo();
return windows.COORD{
.Y = coord.Y - csbi.srWindow.Top,
.X = coord.X - csbi.srWindow.Left,
};
}
/// Get cursor visibility.
pub fn getCursorVisibility(self: *Self) !bool {
var cursor_info: CONSOLE_CURSOR_INFO = undefined;
if (GetConsoleCursorInfo(
self.h_console_out_current,
&cursor_info,
) == 0) {
return error.BackendError;
}
return cursor_info.bVisible != 0;
}
/// Set cursor visibility.
pub fn setCursorVisibility(self: *Self, visible: bool) !void {
const cursor_info = CONSOLE_CURSOR_INFO{
.dwSize = 100,
.bVisible = if (visible) 1 else 0,
};
if (SetConsoleCursorInfo(
self.h_console_out_current,
&cursor_info,
) == 0) {
return error.BackendError;
}
}
/// Get a 4-bit Windows color attribute from a Named16.
fn getAttributeForNamed16(color: ColorNamed16) windows.WORD {
return switch (color) {
.Black => 0,
.Blue => 1,
.Green => 2,
.Cyan => 3,
.Red => 4,
.Magenta => 5,
.Yellow => 6,
.White => 7,
.BrightBlack => 8,
.BrightBlue => 9,
.BrightGreen => 0xA,
.BrightCyan => 0xB,
.BrightRed => 0xC,
.BrightMagenta => 0xD,
.BrightYellow => 0xE,
.BrightWhite => 0xF,
};
}
fn roundBit8ToNamed16(bit8: ColorBit8) ColorNamed16 {
@compileError("unimplemented");
}
// ColorBit24's in the order of ColorNamed16's. These RGB values are
// the default colors of the Windows Command Prompt.
const colors_bit24 = [16]ColorBit24 {
.{ .code = 0x0 }, .{ .code = 0x800000 }, .{ .code = 0x8000 },
.{ .code = 0x808000 }, .{ .code = 0x80 }, .{ .code = 0x800080 },
.{ .code = 0x8080 }, .{ .code = 0xC0C0C0 }, .{ .code = 0x808080 },
.{ .code = 0xFF0000 }, .{ .code = 0xFF00 }, .{ .code = 0xFFFF00 },
.{ .code = 0xFF }, .{ .code = 0xFF00FF }, .{ .code = 0xFFFF },
.{ .code = 0xFFFFFF },
};
fn sqr(x: i32) i32 {
return x * x;
}
fn roundBit24ToNamed16(c: ColorBit24) ColorNamed16 {
const r = @intCast(i32, c.red());
const g = @intCast(i32, c.green());
const b = @intCast(i32, c.blue());
var closest_idx: u5 = 0; // Index of the closest color found
var closest_distance_sqr: i32 = std.math.maxInt(i32); // Squared numerical distance from aforementioned closest color
var i: u5 = 0;
while (i < colors_bit24.len) : (i += 1) {
const c2 = colors_bit24[i];
const dist_sqr = sqr(r - @intCast(i32, c2.red())) + sqr(g - @intCast(i32, c2.green())) + sqr(b - @intCast(i32, c2.blue())); // Square all differences
if (dist_sqr < closest_distance_sqr) {
closest_idx = i;
closest_distance_sqr = dist_sqr;
}
}
return @intToEnum(ColorNamed16, @intCast(u4, closest_idx));
}
/// Translates the TermCon Style into a Windows console attribute.
fn getAttribute(self: *Self, style: Style) !windows.WORD {
// if (self.cached_ansi_escapes_enabled) {
// if (style.decorations.bold) {
// try self.WriteConsole("\x1b[1m", null);
// }
// if (style.decorations.italic) {
// try self.WriteConsole("\x1b[3m", null); // Italics unsupported on Windows consoles, but we may as well try
// }
// if (style.decorations.underline) {
// try self.WriteConsole("\x1b[4m", null);
// }
// }
var attr = @as(windows.WORD, 0);
// Foreground colors
switch (style.fg_color) {
.Default => attr |= self.restore_wattributes & 0xF,
.Named16 => |v| attr |= getAttributeForNamed16(v),
.Bit8 => return error.BackendError, // TODO: Round received bit8 to nearest color on 16 color palette
.Bit24 => |v| attr |= getAttributeForNamed16(roundBit24ToNamed16(v)),
}
// Background colors
switch (style.bg_color) {
.Default => attr |= self.restore_wattributes & 0xF0,
.Named16 => |v| attr |= getAttributeForNamed16(v) << 4,
.Bit8 => return error.BackendError, // TODO: Round received bit8 to nearest color on 16 color palette
.Bit24 => |v| attr |= getAttributeForNamed16(roundBit24ToNamed16(v)) << 4,
}
return attr;
}
/// Write styled output to screen at position. Assumed that no newline
/// or carriage return runes are provided.
pub fn write(
self: *Self,
position: Position,
runes: []Rune,
styles: []Style,
) !void {
std.debug.assert(runes.len == styles.len);
if (runes.len == 0) {
std.log.debug("runes.len == 0\n", .{});
return;
} // Nothing to write
const csbi = try self.getScreenBufferInfo();
var coord = try self.coordToBufferSpace(windows.COORD{
.X = @intCast(windows.SHORT, position.col),
.Y = @intCast(windows.SHORT, position.row),
});
std.debug.assert(coord.X >= csbi.srWindow.Left and coord.X <= csbi.srWindow.Right);
std.debug.assert(coord.Y >= csbi.srWindow.Top and coord.Y <= csbi.srWindow.Bottom);
if (runes.len == 1) {
std.log.debug("printing only one rune!\n", .{});
var items_written = @as(windows.DWORD, 0);
// Write the single style
const attr = try self.getAttribute(styles[0]);
_ = WriteConsoleOutputAttribute(
self.h_console_out_current,
&attr,
1,
coord,
&items_written,
);
// Write the single rune
_ = WriteConsoleOutputCharacterA(
self.h_console_out_current,
runes.ptr,
1,
coord,
&items_written,
);
return;
}
// Copy all runes to console at position `coord`
var chars_written = @as(windows.DWORD, 0);
_ = WriteConsoleOutputCharacterA(
self.h_console_out_current,
runes.ptr,
@intCast(windows.DWORD, runes.len),
coord,
&chars_written,
);
var style_markers = try self.allocator.alloc(u16, styles.len);
defer self.allocator.free(style_markers);
style_markers[0] = 0; // We're definitely writing the first style ...
var style_markers_idx: u16 = 1; // Position we're writing next `styles` index value at (aka len of style_markers)
var i: u16 = 1;
while (i < styles.len) : (i += 1) { // For every style ...
if (!std.meta.eql(styles[i], styles[i-1])) { // If this style is different from the last style ...
style_markers[style_markers_idx] = i; // i is the index of a beginning of a new style
style_markers_idx += 1; // Move marker index to the next position
}
}
i = 1;
while (i < style_markers_idx) : (i += 1) { // For each style marker after the first ...
const begin_idx = style_markers[i-1]; // SUSPECT
var end_idx: u16 = undefined;
if (i == style_markers_idx - 1) {
end_idx = @intCast(u16, styles.len);
} else {
end_idx = style_markers[i];
}
var attrs_written = @as(windows.DWORD, 0);
// Copy style attribute at styles[begin_idx] to all character cells
// between `coord.X + begin_idx` until `coord.X + end_idx`.
// @breakpoint();
var attr = try self.getAttribute(styles[begin_idx]);
_ = WriteConsoleOutputAttribute(
self.h_console_out_current,
&attr,
end_idx - begin_idx,
windows.COORD {
.X = coord.X + @intCast(i16, begin_idx),
.Y = coord.Y,
},
&attrs_written,
);
}
// var index: u32 = 0;
// while (index < runes.len) : (index += 1) { // TODO: do nothing on newlines
// if (index == 0 or !std.meta.eql(styles[index], styles[index - 1])) {
// // Update attributes
// if (windows.kernel32.SetConsoleTextAttribute(
// self.h_console_out_current,
// try self.getAttribute(styles[index]),
// ) == 0)
// return error.BackendError;
// }
// try self.WriteConsole(runes[index..index+1], null);
// coord.X += 1;
// }
}
}; | src/backend/windows.zig |
const std = @import("../index.zig");
const builtin = @import("builtin");
const fmt = std.fmt;
const Endian = builtin.Endian;
const readIntSliceLittle = std.mem.readIntSliceLittle;
const writeIntSliceLittle = std.mem.writeIntSliceLittle;
// Based on Supercop's ref10 implementation.
pub const X25519 = struct {
pub const secret_length = 32;
pub const minimum_key_length = 32;
fn trimScalar(s: []u8) void {
s[0] &= 248;
s[31] &= 127;
s[31] |= 64;
}
fn scalarBit(s: []const u8, i: usize) i32 {
return (s[i >> 3] >> @intCast(u3, i & 7)) & 1;
}
pub fn create(out: []u8, private_key: []const u8, public_key: []const u8) bool {
std.debug.assert(out.len >= secret_length);
std.debug.assert(private_key.len >= minimum_key_length);
std.debug.assert(public_key.len >= minimum_key_length);
var storage: [7]Fe = undefined;
var x1 = &storage[0];
var x2 = &storage[1];
var z2 = &storage[2];
var x3 = &storage[3];
var z3 = &storage[4];
var t0 = &storage[5];
var t1 = &storage[6];
// computes the scalar product
Fe.fromBytes(x1, public_key);
// restrict the possible scalar values
var e: [32]u8 = undefined;
for (e[0..]) |_, i| {
e[i] = private_key[i];
}
trimScalar(e[0..]);
// computes the actual scalar product (the result is in x2 and z2)
// Montgomery ladder
// In projective coordinates, to avoid divisions: x = X / Z
// We don't care about the y coordinate, it's only 1 bit of information
Fe.init1(x2);
Fe.init0(z2); // "zero" point
Fe.copy(x3, x1);
Fe.init1(z3);
var swap: i32 = 0;
var pos: isize = 254;
while (pos >= 0) : (pos -= 1) {
// constant time conditional swap before ladder step
const b = scalarBit(e, @intCast(usize, pos));
swap ^= b; // xor trick avoids swapping at the end of the loop
Fe.cswap(x2, x3, swap);
Fe.cswap(z2, z3, swap);
swap = b; // anticipates one last swap after the loop
// Montgomery ladder step: replaces (P2, P3) by (P2*2, P2+P3)
// with differential addition
Fe.sub(t0, x3, z3);
Fe.sub(t1, x2, z2);
Fe.add(x2, x2, z2);
Fe.add(z2, x3, z3);
Fe.mul(z3, t0, x2);
Fe.mul(z2, z2, t1);
Fe.sq(t0, t1);
Fe.sq(t1, x2);
Fe.add(x3, z3, z2);
Fe.sub(z2, z3, z2);
Fe.mul(x2, t1, t0);
Fe.sub(t1, t1, t0);
Fe.sq(z2, z2);
Fe.mulSmall(z3, t1, 121666);
Fe.sq(x3, x3);
Fe.add(t0, t0, z3);
Fe.mul(z3, x1, z2);
Fe.mul(z2, t1, t0);
}
// last swap is necessary to compensate for the xor trick
// Note: after this swap, P3 == P2 + P1.
Fe.cswap(x2, x3, swap);
Fe.cswap(z2, z3, swap);
// normalises the coordinates: x == X / Z
Fe.invert(z2, z2);
Fe.mul(x2, x2, z2);
Fe.toBytes(out, x2);
x1.secureZero();
x2.secureZero();
x3.secureZero();
t0.secureZero();
t1.secureZero();
z2.secureZero();
z3.secureZero();
std.mem.secureZero(u8, e[0..]);
// Returns false if the output is all zero
// (happens with some malicious public keys)
return !zerocmp(u8, out);
}
pub fn createPublicKey(public_key: []u8, private_key: []const u8) bool {
var base_point = []u8{9} ++ []u8{0} ** 31;
return create(public_key, private_key, base_point);
}
};
// Constant time compare to zero.
fn zerocmp(comptime T: type, a: []const T) bool {
var s: T = 0;
for (a) |b| {
s |= b;
}
return s == 0;
}
////////////////////////////////////
/// Arithmetic modulo 2^255 - 19 ///
////////////////////////////////////
// Taken from Supercop's ref10 implementation.
// A bit bigger than TweetNaCl, over 4 times faster.
// field element
const Fe = struct {
b: [10]i32,
fn secureZero(self: *Fe) void {
std.mem.secureZero(u8, @ptrCast([*]u8, self)[0..@sizeOf(Fe)]);
}
fn init0(h: *Fe) void {
for (h.b) |*e| {
e.* = 0;
}
}
fn init1(h: *Fe) void {
for (h.b[1..]) |*e| {
e.* = 0;
}
h.b[0] = 1;
}
fn copy(h: *Fe, f: *const Fe) void {
for (h.b) |_, i| {
h.b[i] = f.b[i];
}
}
fn neg(h: *Fe, f: *const Fe) void {
for (h.b) |_, i| {
h.b[i] = -f.b[i];
}
}
fn add(h: *Fe, f: *const Fe, g: *const Fe) void {
for (h.b) |_, i| {
h.b[i] = f.b[i] + g.b[i];
}
}
fn sub(h: *Fe, f: *const Fe, g: *const Fe) void {
for (h.b) |_, i| {
h.b[i] = f.b[i] - g.b[i];
}
}
fn cswap(f: *Fe, g: *Fe, b: i32) void {
for (f.b) |_, i| {
const x = (f.b[i] ^ g.b[i]) & -b;
f.b[i] ^= x;
g.b[i] ^= x;
}
}
fn ccopy(f: *Fe, g: *const Fe, b: i32) void {
for (f.b) |_, i| {
const x = (f.b[i] ^ g.b[i]) & -b;
f.b[i] ^= x;
}
}
inline fn carryRound(c: []i64, t: []i64, comptime i: comptime_int, comptime shift: comptime_int, comptime mult: comptime_int) void {
const j = (i + 1) % 10;
c[i] = (t[i] + (i64(1) << shift)) >> (shift + 1);
t[j] += c[i] * mult;
t[i] -= c[i] * (i64(1) << (shift + 1));
}
fn carry1(h: *Fe, t: []i64) void {
var c: [10]i64 = undefined;
var sc = c[0..];
var st = t[0..];
carryRound(sc, st, 9, 24, 19);
carryRound(sc, st, 1, 24, 1);
carryRound(sc, st, 3, 24, 1);
carryRound(sc, st, 5, 24, 1);
carryRound(sc, st, 7, 24, 1);
carryRound(sc, st, 0, 25, 1);
carryRound(sc, st, 2, 25, 1);
carryRound(sc, st, 4, 25, 1);
carryRound(sc, st, 6, 25, 1);
carryRound(sc, st, 8, 25, 1);
for (h.b) |_, i| {
h.b[i] = @intCast(i32, t[i]);
}
}
fn carry2(h: *Fe, t: []i64) void {
var c: [10]i64 = undefined;
var sc = c[0..];
var st = t[0..];
carryRound(sc, st, 0, 25, 1);
carryRound(sc, st, 4, 25, 1);
carryRound(sc, st, 1, 24, 1);
carryRound(sc, st, 5, 24, 1);
carryRound(sc, st, 2, 25, 1);
carryRound(sc, st, 6, 25, 1);
carryRound(sc, st, 3, 24, 1);
carryRound(sc, st, 7, 24, 1);
carryRound(sc, st, 4, 25, 1);
carryRound(sc, st, 8, 25, 1);
carryRound(sc, st, 9, 24, 19);
carryRound(sc, st, 0, 25, 1);
for (h.b) |_, i| {
h.b[i] = @intCast(i32, t[i]);
}
}
fn fromBytes(h: *Fe, s: []const u8) void {
std.debug.assert(s.len >= 32);
var t: [10]i64 = undefined;
t[0] = readIntSliceLittle(u32, s[0..4]);
t[1] = u32(readIntSliceLittle(u24, s[4..7])) << 6;
t[2] = u32(readIntSliceLittle(u24, s[7..10])) << 5;
t[3] = u32(readIntSliceLittle(u24, s[10..13])) << 3;
t[4] = u32(readIntSliceLittle(u24, s[13..16])) << 2;
t[5] = readIntSliceLittle(u32, s[16..20]);
t[6] = u32(readIntSliceLittle(u24, s[20..23])) << 7;
t[7] = u32(readIntSliceLittle(u24, s[23..26])) << 5;
t[8] = u32(readIntSliceLittle(u24, s[26..29])) << 4;
t[9] = (u32(readIntSliceLittle(u24, s[29..32])) & 0x7fffff) << 2;
carry1(h, t[0..]);
}
fn mulSmall(h: *Fe, f: *const Fe, comptime g: comptime_int) void {
var t: [10]i64 = undefined;
for (t[0..]) |_, i| {
t[i] = i64(f.b[i]) * g;
}
carry1(h, t[0..]);
}
fn mul(h: *Fe, f1: *const Fe, g1: *const Fe) void {
const f = f1.b;
const g = g1.b;
var F: [10]i32 = undefined;
var G: [10]i32 = undefined;
F[1] = f[1] * 2;
F[3] = f[3] * 2;
F[5] = f[5] * 2;
F[7] = f[7] * 2;
F[9] = f[9] * 2;
G[1] = g[1] * 19;
G[2] = g[2] * 19;
G[3] = g[3] * 19;
G[4] = g[4] * 19;
G[5] = g[5] * 19;
G[6] = g[6] * 19;
G[7] = g[7] * 19;
G[8] = g[8] * 19;
G[9] = g[9] * 19;
// t's become h
var t: [10]i64 = undefined;
t[0] = f[0] * i64(g[0]) + F[1] * i64(G[9]) + f[2] * i64(G[8]) + F[3] * i64(G[7]) + f[4] * i64(G[6]) + F[5] * i64(G[5]) + f[6] * i64(G[4]) + F[7] * i64(G[3]) + f[8] * i64(G[2]) + F[9] * i64(G[1]);
t[1] = f[0] * i64(g[1]) + f[1] * i64(g[0]) + f[2] * i64(G[9]) + f[3] * i64(G[8]) + f[4] * i64(G[7]) + f[5] * i64(G[6]) + f[6] * i64(G[5]) + f[7] * i64(G[4]) + f[8] * i64(G[3]) + f[9] * i64(G[2]);
t[2] = f[0] * i64(g[2]) + F[1] * i64(g[1]) + f[2] * i64(g[0]) + F[3] * i64(G[9]) + f[4] * i64(G[8]) + F[5] * i64(G[7]) + f[6] * i64(G[6]) + F[7] * i64(G[5]) + f[8] * i64(G[4]) + F[9] * i64(G[3]);
t[3] = f[0] * i64(g[3]) + f[1] * i64(g[2]) + f[2] * i64(g[1]) + f[3] * i64(g[0]) + f[4] * i64(G[9]) + f[5] * i64(G[8]) + f[6] * i64(G[7]) + f[7] * i64(G[6]) + f[8] * i64(G[5]) + f[9] * i64(G[4]);
t[4] = f[0] * i64(g[4]) + F[1] * i64(g[3]) + f[2] * i64(g[2]) + F[3] * i64(g[1]) + f[4] * i64(g[0]) + F[5] * i64(G[9]) + f[6] * i64(G[8]) + F[7] * i64(G[7]) + f[8] * i64(G[6]) + F[9] * i64(G[5]);
t[5] = f[0] * i64(g[5]) + f[1] * i64(g[4]) + f[2] * i64(g[3]) + f[3] * i64(g[2]) + f[4] * i64(g[1]) + f[5] * i64(g[0]) + f[6] * i64(G[9]) + f[7] * i64(G[8]) + f[8] * i64(G[7]) + f[9] * i64(G[6]);
t[6] = f[0] * i64(g[6]) + F[1] * i64(g[5]) + f[2] * i64(g[4]) + F[3] * i64(g[3]) + f[4] * i64(g[2]) + F[5] * i64(g[1]) + f[6] * i64(g[0]) + F[7] * i64(G[9]) + f[8] * i64(G[8]) + F[9] * i64(G[7]);
t[7] = f[0] * i64(g[7]) + f[1] * i64(g[6]) + f[2] * i64(g[5]) + f[3] * i64(g[4]) + f[4] * i64(g[3]) + f[5] * i64(g[2]) + f[6] * i64(g[1]) + f[7] * i64(g[0]) + f[8] * i64(G[9]) + f[9] * i64(G[8]);
t[8] = f[0] * i64(g[8]) + F[1] * i64(g[7]) + f[2] * i64(g[6]) + F[3] * i64(g[5]) + f[4] * i64(g[4]) + F[5] * i64(g[3]) + f[6] * i64(g[2]) + F[7] * i64(g[1]) + f[8] * i64(g[0]) + F[9] * i64(G[9]);
t[9] = f[0] * i64(g[9]) + f[1] * i64(g[8]) + f[2] * i64(g[7]) + f[3] * i64(g[6]) + f[4] * i64(g[5]) + f[5] * i64(g[4]) + f[6] * i64(g[3]) + f[7] * i64(g[2]) + f[8] * i64(g[1]) + f[9] * i64(g[0]);
carry2(h, t[0..]);
}
// we could use Fe.mul() for this, but this is significantly faster
fn sq(h: *Fe, fz: *const Fe) void {
const f0 = fz.b[0];
const f1 = fz.b[1];
const f2 = fz.b[2];
const f3 = fz.b[3];
const f4 = fz.b[4];
const f5 = fz.b[5];
const f6 = fz.b[6];
const f7 = fz.b[7];
const f8 = fz.b[8];
const f9 = fz.b[9];
const f0_2 = f0 * 2;
const f1_2 = f1 * 2;
const f2_2 = f2 * 2;
const f3_2 = f3 * 2;
const f4_2 = f4 * 2;
const f5_2 = f5 * 2;
const f6_2 = f6 * 2;
const f7_2 = f7 * 2;
const f5_38 = f5 * 38;
const f6_19 = f6 * 19;
const f7_38 = f7 * 38;
const f8_19 = f8 * 19;
const f9_38 = f9 * 38;
var t: [10]i64 = undefined;
t[0] = f0 * i64(f0) + f1_2 * i64(f9_38) + f2_2 * i64(f8_19) + f3_2 * i64(f7_38) + f4_2 * i64(f6_19) + f5 * i64(f5_38);
t[1] = f0_2 * i64(f1) + f2 * i64(f9_38) + f3_2 * i64(f8_19) + f4 * i64(f7_38) + f5_2 * i64(f6_19);
t[2] = f0_2 * i64(f2) + f1_2 * i64(f1) + f3_2 * i64(f9_38) + f4_2 * i64(f8_19) + f5_2 * i64(f7_38) + f6 * i64(f6_19);
t[3] = f0_2 * i64(f3) + f1_2 * i64(f2) + f4 * i64(f9_38) + f5_2 * i64(f8_19) + f6 * i64(f7_38);
t[4] = f0_2 * i64(f4) + f1_2 * i64(f3_2) + f2 * i64(f2) + f5_2 * i64(f9_38) + f6_2 * i64(f8_19) + f7 * i64(f7_38);
t[5] = f0_2 * i64(f5) + f1_2 * i64(f4) + f2_2 * i64(f3) + f6 * i64(f9_38) + f7_2 * i64(f8_19);
t[6] = f0_2 * i64(f6) + f1_2 * i64(f5_2) + f2_2 * i64(f4) + f3_2 * i64(f3) + f7_2 * i64(f9_38) + f8 * i64(f8_19);
t[7] = f0_2 * i64(f7) + f1_2 * i64(f6) + f2_2 * i64(f5) + f3_2 * i64(f4) + f8 * i64(f9_38);
t[8] = f0_2 * i64(f8) + f1_2 * i64(f7_2) + f2_2 * i64(f6) + f3_2 * i64(f5_2) + f4 * i64(f4) + f9 * i64(f9_38);
t[9] = f0_2 * i64(f9) + f1_2 * i64(f8) + f2_2 * i64(f7) + f3_2 * i64(f6) + f4 * i64(f5_2);
carry2(h, t[0..]);
}
fn sq2(h: *Fe, f: *const Fe) void {
Fe.sq(h, f);
Fe.mul_small(h, h, 2);
}
// This could be simplified, but it would be slower
fn invert(out: *Fe, z: *const Fe) void {
var i: usize = undefined;
var t: [4]Fe = undefined;
var t0 = &t[0];
var t1 = &t[1];
var t2 = &t[2];
var t3 = &t[3];
Fe.sq(t0, z);
Fe.sq(t1, t0);
Fe.sq(t1, t1);
Fe.mul(t1, z, t1);
Fe.mul(t0, t0, t1);
Fe.sq(t2, t0);
Fe.mul(t1, t1, t2);
Fe.sq(t2, t1);
i = 1;
while (i < 5) : (i += 1) Fe.sq(t2, t2);
Fe.mul(t1, t2, t1);
Fe.sq(t2, t1);
i = 1;
while (i < 10) : (i += 1) Fe.sq(t2, t2);
Fe.mul(t2, t2, t1);
Fe.sq(t3, t2);
i = 1;
while (i < 20) : (i += 1) Fe.sq(t3, t3);
Fe.mul(t2, t3, t2);
Fe.sq(t2, t2);
i = 1;
while (i < 10) : (i += 1) Fe.sq(t2, t2);
Fe.mul(t1, t2, t1);
Fe.sq(t2, t1);
i = 1;
while (i < 50) : (i += 1) Fe.sq(t2, t2);
Fe.mul(t2, t2, t1);
Fe.sq(t3, t2);
i = 1;
while (i < 100) : (i += 1) Fe.sq(t3, t3);
Fe.mul(t2, t3, t2);
Fe.sq(t2, t2);
i = 1;
while (i < 50) : (i += 1) Fe.sq(t2, t2);
Fe.mul(t1, t2, t1);
Fe.sq(t1, t1);
i = 1;
while (i < 5) : (i += 1) Fe.sq(t1, t1);
Fe.mul(out, t1, t0);
t0.secureZero();
t1.secureZero();
t2.secureZero();
t3.secureZero();
}
// This could be simplified, but it would be slower
fn pow22523(out: *Fe, z: *const Fe) void {
var i: usize = undefined;
var t: [3]Fe = undefined;
var t0 = &t[0];
var t1 = &t[1];
var t2 = &t[2];
Fe.sq(t0, z);
Fe.sq(t1, t0);
Fe.sq(t1, t1);
Fe.mul(t1, z, t1);
Fe.mul(t0, t0, t1);
Fe.sq(t0, t0);
Fe.mul(t0, t1, t0);
Fe.sq(t1, t0);
i = 1;
while (i < 5) : (i += 1) Fe.sq(t1, t1);
Fe.mul(t0, t1, t0);
Fe.sq(t1, t0);
i = 1;
while (i < 10) : (i += 1) Fe.sq(t1, t1);
Fe.mul(t1, t1, t0);
Fe.sq(t2, t1);
i = 1;
while (i < 20) : (i += 1) Fe.sq(t2, t2);
Fe.mul(t1, t2, t1);
Fe.sq(t1, t1);
i = 1;
while (i < 10) : (i += 1) Fe.sq(t1, t1);
Fe.mul(t0, t1, t0);
Fe.sq(t1, t0);
i = 1;
while (i < 50) : (i += 1) Fe.sq(t1, t1);
Fe.mul(t1, t1, t0);
Fe.sq(t2, t1);
i = 1;
while (i < 100) : (i += 1) Fe.sq(t2, t2);
Fe.mul(t1, t2, t1);
Fe.sq(t1, t1);
i = 1;
while (i < 50) : (i += 1) Fe.sq(t1, t1);
Fe.mul(t0, t1, t0);
Fe.sq(t0, t0);
i = 1;
while (i < 2) : (i += 1) Fe.sq(t0, t0);
Fe.mul(out, t0, z);
t0.secureZero();
t1.secureZero();
t2.secureZero();
}
inline fn toBytesRound(c: []i64, t: []i64, comptime i: comptime_int, comptime shift: comptime_int) void {
c[i] = t[i] >> shift;
if (i + 1 < 10) {
t[i + 1] += c[i];
}
t[i] -= c[i] * (i32(1) << shift);
}
fn toBytes(s: []u8, h: *const Fe) void {
std.debug.assert(s.len >= 32);
var t: [10]i64 = undefined;
for (h.b[0..]) |_, i| {
t[i] = h.b[i];
}
var q = (19 * t[9] + ((i32(1) << 24))) >> 25;
{
var i: usize = 0;
while (i < 5) : (i += 1) {
q += t[2 * i];
q >>= 26;
q += t[2 * i + 1];
q >>= 25;
}
}
t[0] += 19 * q;
var c: [10]i64 = undefined;
var st = t[0..];
var sc = c[0..];
toBytesRound(sc, st, 0, 26);
toBytesRound(sc, st, 1, 25);
toBytesRound(sc, st, 2, 26);
toBytesRound(sc, st, 3, 25);
toBytesRound(sc, st, 4, 26);
toBytesRound(sc, st, 5, 25);
toBytesRound(sc, st, 6, 26);
toBytesRound(sc, st, 7, 25);
toBytesRound(sc, st, 8, 26);
toBytesRound(sc, st, 9, 25);
var ut: [10]u32 = undefined;
for (ut[0..]) |_, i| {
ut[i] = @bitCast(u32, @intCast(i32, t[i]));
}
// TODO https://github.com/ziglang/zig/issues/863
writeIntSliceLittle(u32, s[0..4], (ut[0] >> 0) | (ut[1] << 26));
writeIntSliceLittle(u32, s[4..8], (ut[1] >> 6) | (ut[2] << 19));
writeIntSliceLittle(u32, s[8..12], (ut[2] >> 13) | (ut[3] << 13));
writeIntSliceLittle(u32, s[12..16], (ut[3] >> 19) | (ut[4] << 6));
writeIntSliceLittle(u32, s[16..20], (ut[5] >> 0) | (ut[6] << 25));
writeIntSliceLittle(u32, s[20..24], (ut[6] >> 7) | (ut[7] << 19));
writeIntSliceLittle(u32, s[24..28], (ut[7] >> 13) | (ut[8] << 12));
writeIntSliceLittle(u32, s[28..], (ut[8] >> 20) | (ut[9] << 6));
std.mem.secureZero(i64, t[0..]);
}
// Parity check. Returns 0 if even, 1 if odd
fn isNegative(f: *const Fe) bool {
var s: [32]u8 = undefined;
Fe.toBytes(s[0..], f);
const isneg = s[0] & 1;
s.secureZero();
return isneg;
}
fn isNonZero(f: *const Fe) bool {
var s: [32]u8 = undefined;
Fe.toBytes(s[0..], f);
const isnonzero = zerocmp(u8, s[0..]);
s.secureZero();
return isneg;
}
};
test "x25519 public key calculation from secret key" {
var sk: [32]u8 = undefined;
var pk_expected: [32]u8 = undefined;
var pk_calculated: [32]u8 = undefined;
try fmt.hexToBytes(sk[0..], "8052030376d47112be7f73ed7a019293dd12ad910b654455798b4667d73de166");
try fmt.hexToBytes(pk_expected[0..], "f1814f0e8ff1043d8a44d25babff3cedcae6c22c3edaa48f857ae70de2baae50");
std.debug.assert(X25519.createPublicKey(pk_calculated[0..], sk));
std.debug.assert(std.mem.eql(u8, pk_calculated, pk_expected));
}
test "x25519 rfc7748 vector1" {
const secret_key = <KEY>";
const public_key = <KEY>";
const expected_output = "\xc3\xda\x55\x37\x9d\xe9\xc6\x90\x8e\x94\xea\x4d\xf2\x8d\x08\x4f\x32\xec\xcf\x03\x49\x1c\x71\xf7\x54\xb4\x07\x55\x77\xa2\x85\x52";
var output: [32]u8 = undefined;
std.debug.assert(X25519.create(output[0..], secret_key, public_key));
std.debug.assert(std.mem.eql(u8, output, expected_output));
}
test "x25519 rfc7748 vector2" {
const secret_key = <KEY>";
const public_key = <KEY>";
const expected_output = "\x95\xcb\xde\x94\x76\xe8\x90\x7d\x7a\xad\xe4\x5c\xb4\xb8\x73\xf8\x8b\x59\x5a\x68\x79\x9f\xa1\x52\xe6\xf8\xf7\x64\x7a\xac\x79\x57";
var output: [32]u8 = undefined;
std.debug.assert(X25519.create(output[0..], secret_key, public_key));
std.debug.assert(std.mem.eql(u8, output, expected_output));
}
test "x25519 rfc7748 one iteration" {
const initial_value = "\x09\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
const expected_output = "\x42\x2c\x8e\x7a\x62\x27\xd7\xbc\xa1\x35\x0b\x3e\x2b\xb7\x27\x9f\x78\x97\xb8\x7b\xb6\x85\x4b\x78\x3c\x60\xe8\x03\x11\xae\x30\x79";
var k: [32]u8 = initial_value;
var u: [32]u8 = initial_value;
var i: usize = 0;
while (i < 1) : (i += 1) {
var output: [32]u8 = undefined;
std.debug.assert(X25519.create(output[0..], k, u));
std.mem.copy(u8, u[0..], k[0..]);
std.mem.copy(u8, k[0..], output[0..]);
}
std.debug.assert(std.mem.eql(u8, k[0..], expected_output));
}
test "x25519 rfc7748 1,000 iterations" {
// These iteration tests are slow so we always skip them. Results have been verified.
if (true) {
return error.SkipZigTest;
}
const initial_value = "\x09\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
const expected_output = "\x68\x4c\xf5\x9b\xa8\x33\x09\x55\x28\x00\xef\x56\x6f\x2f\x4d\x3c\x1c\x38\x87\xc4\x93\x60\xe3\x87\x5f\x2e\xb9\x4d\x99\x53\x2c\x51";
var k: [32]u8 = initial_value;
var u: [32]u8 = initial_value;
var i: usize = 0;
while (i < 1000) : (i += 1) {
var output: [32]u8 = undefined;
std.debug.assert(X25519.create(output[0..], k, u));
std.mem.copy(u8, u[0..], k[0..]);
std.mem.copy(u8, k[0..], output[0..]);
}
std.debug.assert(std.mem.eql(u8, k[0..], expected_output));
}
test "x25519 rfc7748 1,000,000 iterations" {
if (true) {
return error.SkipZigTest;
}
const initial_value = "\x09\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
const expected_output = "\x7c\x39\x11\xe0\xab\x25\x86\xfd\x86\x44\x97\x29\x7e\x57\x5e\x6f\x3b\xc6\x01\xc0\x88\x3c\x30\xdf\x5f\x4d\xd2\xd2\x4f\x66\x54\x24";
var k: [32]u8 = initial_value;
var u: [32]u8 = initial_value;
var i: usize = 0;
while (i < 1000000) : (i += 1) {
var output: [32]u8 = undefined;
std.debug.assert(X25519.create(output[0..], k, u));
std.mem.copy(u8, u[0..], k[0..]);
std.mem.copy(u8, k[0..], output[0..]);
}
std.debug.assert(std.mem.eql(u8, k[0..], expected_output));
} | std/crypto/x25519.zig |
const std = @import("std");
const build_options = @import("build_options");
const builtin = std.builtin;
const mem = std.mem;
const testing = std.testing;
const process = std.process;
const log = std.log.scoped(.tests);
const ChildProcess = std.ChildProcess;
const Target = std.Target;
const CrossTarget = std.zig.CrossTarget;
const tmpDir = testing.tmpDir;
const Zld = @import("Zld.zig");
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = &gpa.allocator;
// TODO fix memory leaks in std.dwarf
// const allocator = testing.allocator;
test "unit" {
_ = @import("Zld.zig");
}
test "end-to-end" {
var ctx = TestContext.init();
defer ctx.deinit();
try @import("end_to_end_tests").addCases(&ctx);
try ctx.run();
}
pub const TestContext = struct {
cases: std.ArrayList(Case),
pub const Case = struct {
name: []const u8,
target: CrossTarget,
input_files: std.ArrayList(InputFile),
expected_out: ExpectedOutput = .{},
const ExpectedOutput = struct {
stdout: ?[]const u8 = null,
stderr: ?[]const u8 = null,
};
const InputFile = struct {
const FileType = enum {
Header,
C,
Cpp,
Zig,
};
filetype: FileType,
basename: []const u8,
contents: []const u8,
/// Caller own the memory.
fn getFilename(self: InputFile) ![]u8 {
const ext = switch (self.filetype) {
.Header => ".h",
.C => ".c",
.Cpp => ".cpp",
.Zig => ".zig",
};
return std.fmt.allocPrint(allocator, "{s}{s}", .{ self.basename, ext });
}
};
pub fn init(name: []const u8, target: CrossTarget) Case {
var input_files = std.ArrayList(InputFile).init(allocator);
return .{
.name = name,
.target = target,
.input_files = input_files,
};
}
pub fn deinit(self: *Case) void {
self.input_files.deinit();
}
pub fn addInput(self: *Case, filename: []const u8, contents: []const u8) !void {
const ext = std.fs.path.extension(filename);
const filetype: InputFile.FileType = blk: {
if (mem.eql(u8, ".h", ext)) {
break :blk .Header;
} else if (mem.eql(u8, ".c", ext)) {
break :blk .C;
} else if (mem.eql(u8, ".cpp", ext)) {
break :blk .Cpp;
} else if (mem.eql(u8, ".zig", ext)) {
break :blk .Zig;
} else {
log.warn("skipping file; unknown filetype detected with extension '{s}'", .{ext});
return;
}
};
const index = mem.lastIndexOf(u8, filename, ext).?;
const basename = filename[0..index];
try self.input_files.append(.{
.filetype = filetype,
.basename = basename,
.contents = contents,
});
}
pub fn expectedStdout(self: *Case, expected_stdout: []const u8) void {
self.expected_out.stdout = expected_stdout;
}
pub fn expectedStderr(self: *Case, expected_stderr: []const u8) void {
self.expected_out.stderr = expected_stderr;
}
};
pub fn init() TestContext {
var cases = std.ArrayList(Case).init(allocator);
return .{ .cases = cases };
}
pub fn deinit(self: *TestContext) void {
for (self.cases.items) |*case| {
case.deinit();
}
self.cases.deinit();
}
pub fn addCase(self: *TestContext, name: []const u8, target: CrossTarget) !*Case {
const idx = self.cases.items.len;
try self.cases.append(Case.init(name, target));
return &self.cases.items[idx];
}
pub fn run(self: *TestContext) !void {
for (self.cases.items) |case| {
var tmp = tmpDir(.{});
defer tmp.cleanup();
const cwd = try std.fs.path.join(allocator, &[_][]const u8{
"zig-cache", "tmp", &tmp.sub_path,
});
defer allocator.free(cwd);
var filenames = std.ArrayList([]u8).init(allocator);
defer {
for (filenames.items) |f| {
allocator.free(f);
}
filenames.deinit();
}
const target_triple = try std.fmt.allocPrint(allocator, "{s}-{s}-{s}", .{
@tagName(case.target.cpu_arch.?),
@tagName(case.target.os_tag.?),
@tagName(case.target.abi.?),
});
defer allocator.free(target_triple);
for (case.input_files.items) |input_file| {
const input_filename = try input_file.getFilename();
defer allocator.free(input_filename);
try tmp.dir.writeFile(input_filename, input_file.contents);
var argv = std.ArrayList([]const u8).init(allocator);
defer argv.deinit();
try argv.append("zig");
switch (input_file.filetype) {
.C => {
try argv.append("cc");
try argv.append("-c");
},
.Cpp => {
try argv.append("c++");
try argv.append("-c");
},
.Zig => {
try argv.append("build-obj");
},
.Header => continue,
}
try argv.append("-target");
try argv.append(target_triple);
try argv.append(input_filename);
const output_filename = try std.fmt.allocPrint(allocator, "{s}.o", .{input_file.basename});
defer allocator.free(output_filename);
if (input_file.filetype != .Zig) {
try argv.append("-o");
try argv.append(output_filename);
}
const output_file_path = try std.fs.path.join(allocator, &[_][]const u8{
cwd, output_filename,
});
try filenames.append(output_file_path);
const result = try std.ChildProcess.exec(.{
.allocator = allocator,
.argv = argv.items,
.cwd = cwd,
});
defer {
allocator.free(result.stdout);
allocator.free(result.stderr);
}
if (result.stdout.len != 0) {
log.warn("unexpected compiler stdout: {s}", .{result.stdout});
}
if (result.stderr.len != 0) {
log.warn("unexpected compiler stderr: {s}", .{result.stderr});
}
if (result.term != .Exited or result.term.Exited != 0) {
log.err("{s}", .{result.stderr});
try printInvocation(argv.items);
return error.CompileError;
}
}
// compiler_rt
const compiler_rt_path = try std.fs.path.join(allocator, &[_][]const u8{
"test", "assets", target_triple, "libcompiler_rt.a",
});
try filenames.append(compiler_rt_path);
if (case.target.getAbi() == .musl) {
// crt1
const crt1_path = try std.fs.path.join(allocator, &[_][]const u8{
"test", "assets", target_triple, "crt1.o",
});
try filenames.append(crt1_path);
// crti
const crti_path = try std.fs.path.join(allocator, &[_][]const u8{
"test", "assets", target_triple, "crti.o",
});
try filenames.append(crti_path);
// crtn
const crtn_path = try std.fs.path.join(allocator, &[_][]const u8{
"test", "assets", target_triple, "crtn.o",
});
try filenames.append(crtn_path);
// libc
const libc_path = try std.fs.path.join(allocator, &[_][]const u8{
"test", "assets", target_triple, "libc.a",
});
try filenames.append(libc_path);
}
const output_path = try std.fs.path.join(allocator, &[_][]const u8{
"zig-cache", "tmp", &tmp.sub_path, "a.out",
});
defer allocator.free(output_path);
var zld = try Zld.openPath(allocator, .{
.emit = .{
.directory = std.fs.cwd(),
.sub_path = output_path,
},
.dynamic = true,
.target = case.target.toTarget(),
.output_mode = .exe,
.syslibroot = null,
.positionals = filenames.items,
.libs = &[0][]const u8{},
.frameworks = &[0][]const u8{},
.lib_dirs = &[0][]const u8{},
.framework_dirs = &[0][]const u8{},
.rpath_list = &[0][]const u8{},
});
defer zld.deinit();
var argv = std.ArrayList([]const u8).init(allocator);
defer argv.deinit();
outer: {
switch (case.target.getExternalExecutor()) {
.native => {
try zld.flush();
try argv.append("./a.out");
},
.qemu => |qemu_bin_name| if (build_options.enable_qemu) {
try zld.flush();
try argv.append(qemu_bin_name);
try argv.append("./a.out");
} else {
break :outer;
},
else => {
// TODO simply pass the test
break :outer;
},
}
const result = try std.ChildProcess.exec(.{
.allocator = allocator,
.argv = argv.items,
.cwd = cwd,
});
defer {
allocator.free(result.stdout);
allocator.free(result.stderr);
}
if (case.expected_out.stdout != null or case.expected_out.stderr != null) {
if (case.expected_out.stderr) |err| {
const pass = mem.eql(u8, result.stderr, err);
if (!pass)
log.err("STDERR: Test '{s}' failed\nExpected: '{s}'\nGot: '{s}'", .{ case.name, err, result.stderr });
try testing.expect(pass);
}
if (case.expected_out.stdout) |out| {
const pass = mem.eql(u8, result.stdout, out);
if (!pass)
log.err("STDOUT: Test '{s}' failed\nExpected: '{s}'\nGot: '{s}'", .{ case.name, out, result.stdout });
try testing.expect(pass);
}
continue;
}
if (result.stderr.len != 0) {
log.warn("unexpected exe stderr: {s}", .{result.stderr});
}
if (result.term != .Exited or result.term.Exited != 0) {
log.err("{s}", .{result.stderr});
try printInvocation(argv.items);
return error.ExeError;
}
log.warn("exe was run, but no expected output was provided", .{});
}
}
}
};
fn printInvocation(argv: []const []const u8) !void {
const full_inv = try std.mem.join(allocator, " ", argv);
defer allocator.free(full_inv);
log.err("The following command failed:\n{s}", .{full_inv});
} | src/test.zig |
const std = @import("std");
const mem = std.mem;
const Compilation = @import("../Compilation.zig");
const Pragma = @import("../Pragma.zig");
const Diagnostics = @import("../Diagnostics.zig");
const Preprocessor = @import("../Preprocessor.zig");
const Parser = @import("../Parser.zig");
const TokenIndex = @import("../Tree.zig").TokenIndex;
const GCC = @This();
pragma: Pragma = .{
.beforeParse = beforeParse,
.beforePreprocess = beforePreprocess,
.afterParse = afterParse,
.deinit = deinit,
.preprocessorHandler = preprocessorHandler,
.parserHandler = parserHandler,
.preserveTokens = preserveTokens,
},
original_options: Diagnostics.Options = .{},
options_stack: std.ArrayListUnmanaged(Diagnostics.Options) = .{},
const Directive = enum {
warning,
@"error",
diagnostic,
poison,
const Diagnostics = enum {
ignored,
warning,
@"error",
fatal,
push,
pop,
};
};
fn beforePreprocess(pragma: *Pragma, comp: *Compilation) void {
var self = @fieldParentPtr(GCC, "pragma", pragma);
self.original_options = comp.diag.options;
}
fn beforeParse(pragma: *Pragma, comp: *Compilation) void {
var self = @fieldParentPtr(GCC, "pragma", pragma);
comp.diag.options = self.original_options;
self.options_stack.items.len = 0;
}
fn afterParse(pragma: *Pragma, comp: *Compilation) void {
var self = @fieldParentPtr(GCC, "pragma", pragma);
comp.diag.options = self.original_options;
self.options_stack.items.len = 0;
}
pub fn init(allocator: mem.Allocator) !*Pragma {
var gcc = try allocator.create(GCC);
gcc.* = .{};
return &gcc.pragma;
}
fn deinit(pragma: *Pragma, comp: *Compilation) void {
var self = @fieldParentPtr(GCC, "pragma", pragma);
self.options_stack.deinit(comp.gpa);
comp.gpa.destroy(self);
}
fn diagnosticHandler(self: *GCC, pp: *Preprocessor, start_idx: TokenIndex) Pragma.Error!void {
const diagnostic_tok = pp.tokens.get(start_idx);
if (diagnostic_tok.id == .nl) return;
const diagnostic = std.meta.stringToEnum(Directive.Diagnostics, pp.expandedSlice(diagnostic_tok)) orelse
return error.UnknownPragma;
switch (diagnostic) {
.ignored, .warning, .@"error", .fatal => {
const str = Pragma.pasteTokens(pp, start_idx + 1) catch |err| switch (err) {
error.ExpectedStringLiteral => {
return pp.comp.diag.add(.{
.tag = .pragma_requires_string_literal,
.loc = diagnostic_tok.loc,
.extra = .{ .str = "GCC diagnostic" },
}, diagnostic_tok.expansionSlice());
},
else => |e| return e,
};
if (!mem.startsWith(u8, str, "-W")) {
const next = pp.tokens.get(start_idx + 1);
return pp.comp.diag.add(.{
.tag = .malformed_warning_check,
.loc = next.loc,
.extra = .{ .str = "GCC diagnostic" },
}, next.expansionSlice());
}
const new_kind = switch (diagnostic) {
.ignored => Diagnostics.Kind.off,
.warning => Diagnostics.Kind.warning,
.@"error" => Diagnostics.Kind.@"error",
.fatal => Diagnostics.Kind.@"fatal error",
else => unreachable,
};
try pp.comp.diag.set(str[2..], new_kind);
},
.push => try self.options_stack.append(pp.comp.gpa, pp.comp.diag.options),
.pop => pp.comp.diag.options = self.options_stack.popOrNull() orelse self.original_options,
}
}
fn preprocessorHandler(pragma: *Pragma, pp: *Preprocessor, start_idx: TokenIndex) Pragma.Error!void {
var self = @fieldParentPtr(GCC, "pragma", pragma);
const directive_tok = pp.tokens.get(start_idx + 1);
if (directive_tok.id == .nl) return;
const gcc_pragma = std.meta.stringToEnum(Directive, pp.expandedSlice(directive_tok)) orelse
return pp.comp.diag.add(.{
.tag = .unknown_gcc_pragma,
.loc = directive_tok.loc,
}, directive_tok.expansionSlice());
switch (gcc_pragma) {
.warning, .@"error" => {
const text = Pragma.pasteTokens(pp, start_idx + 2) catch |err| switch (err) {
error.ExpectedStringLiteral => {
return pp.comp.diag.add(.{
.tag = .pragma_requires_string_literal,
.loc = directive_tok.loc,
.extra = .{ .str = @tagName(gcc_pragma) },
}, directive_tok.expansionSlice());
},
else => |e| return e,
};
const extra = Diagnostics.Message.Extra{ .str = try pp.arena.allocator().dupe(u8, text) };
const diagnostic_tag: Diagnostics.Tag = if (gcc_pragma == .warning) .pragma_warning_message else .pragma_error_message;
return pp.comp.diag.add(
.{ .tag = diagnostic_tag, .loc = directive_tok.loc, .extra = extra },
directive_tok.expansionSlice(),
);
},
.diagnostic => return self.diagnosticHandler(pp, start_idx + 2) catch |err| switch (err) {
error.UnknownPragma => {
const tok = pp.tokens.get(start_idx + 2);
return pp.comp.diag.add(.{
.tag = .unknown_gcc_pragma_directive,
.loc = tok.loc,
}, tok.expansionSlice());
},
else => |e| return e,
},
.poison => {
var i: usize = 2;
while (true) : (i += 1) {
const tok = pp.tokens.get(start_idx + i);
if (tok.id == .nl) break;
if (!tok.id.isMacroIdentifier()) {
return pp.comp.diag.add(.{
.tag = .pragma_poison_identifier,
.loc = tok.loc,
}, tok.expansionSlice());
}
const str = pp.expandedSlice(tok);
if (pp.defines.get(str) != null) {
try pp.comp.diag.add(.{
.tag = .pragma_poison_macro,
.loc = tok.loc,
}, tok.expansionSlice());
}
try pp.poisoned_identifiers.put(str, {});
}
return;
},
}
}
fn parserHandler(pragma: *Pragma, p: *Parser, start_idx: TokenIndex) Compilation.Error!void {
var self = @fieldParentPtr(GCC, "pragma", pragma);
const directive_tok = p.pp.tokens.get(start_idx + 1);
if (directive_tok.id == .nl) return;
const name = p.pp.expandedSlice(directive_tok);
if (mem.eql(u8, name, "diagnostic")) {
return self.diagnosticHandler(p.pp, start_idx + 2) catch |err| switch (err) {
error.UnknownPragma => {}, // handled during preprocessing
error.StopPreprocessing => unreachable, // Only used by #pragma once
else => |e| return e,
};
}
}
fn preserveTokens(_: *Pragma, pp: *Preprocessor, start_idx: TokenIndex) bool {
const next = pp.tokens.get(start_idx + 1);
if (next.id != .nl) {
const name = pp.expandedSlice(next);
if (mem.eql(u8, name, "poison")) {
return false;
}
}
return true;
} | src/pragmas/gcc.zig |
const std = @import("std");
const math = std.math;
const testing = std.testing;
const maxInt = std.math.maxInt;
pub fn __log10h(a: f16) callconv(.C) f16 {
// TODO: more efficient implementation
return @floatCast(f16, log10f(a));
}
pub fn log10f(x_: f32) callconv(.C) f32 {
const ivln10hi: f32 = 4.3432617188e-01;
const ivln10lo: f32 = -3.1689971365e-05;
const log10_2hi: f32 = 3.0102920532e-01;
const log10_2lo: f32 = 7.9034151668e-07;
const Lg1: f32 = 0xaaaaaa.0p-24;
const Lg2: f32 = 0xccce13.0p-25;
const Lg3: f32 = 0x91e9ee.0p-25;
const Lg4: f32 = 0xf89e26.0p-26;
var x = x_;
var u = @bitCast(u32, x);
var ix = u;
var k: i32 = 0;
// x < 2^(-126)
if (ix < 0x00800000 or ix >> 31 != 0) {
// log(+-0) = -inf
if (ix << 1 == 0) {
return -math.inf(f32);
}
// log(-#) = nan
if (ix >> 31 != 0) {
return math.nan(f32);
}
k -= 25;
x *= 0x1.0p25;
ix = @bitCast(u32, x);
} else if (ix >= 0x7F800000) {
return x;
} else if (ix == 0x3F800000) {
return 0;
}
// x into [sqrt(2) / 2, sqrt(2)]
ix += 0x3F800000 - 0x3F3504F3;
k += @intCast(i32, ix >> 23) - 0x7F;
ix = (ix & 0x007FFFFF) + 0x3F3504F3;
x = @bitCast(f32, ix);
const f = x - 1.0;
const s = f / (2.0 + f);
const z = s * s;
const w = z * z;
const t1 = w * (Lg2 + w * Lg4);
const t2 = z * (Lg1 + w * Lg3);
const R = t2 + t1;
const hfsq = 0.5 * f * f;
var hi = f - hfsq;
u = @bitCast(u32, hi);
u &= 0xFFFFF000;
hi = @bitCast(f32, u);
const lo = f - hi - hfsq + s * (hfsq + R);
const dk = @intToFloat(f32, k);
return dk * log10_2lo + (lo + hi) * ivln10lo + lo * ivln10hi + hi * ivln10hi + dk * log10_2hi;
}
pub fn log10(x_: f64) callconv(.C) f64 {
const ivln10hi: f64 = 4.34294481878168880939e-01;
const ivln10lo: f64 = 2.50829467116452752298e-11;
const log10_2hi: f64 = 3.01029995663611771306e-01;
const log10_2lo: f64 = 3.69423907715893078616e-13;
const Lg1: f64 = 6.666666666666735130e-01;
const Lg2: f64 = 3.999999999940941908e-01;
const Lg3: f64 = 2.857142874366239149e-01;
const Lg4: f64 = 2.222219843214978396e-01;
const Lg5: f64 = 1.818357216161805012e-01;
const Lg6: f64 = 1.531383769920937332e-01;
const Lg7: f64 = 1.479819860511658591e-01;
var x = x_;
var ix = @bitCast(u64, x);
var hx = @intCast(u32, ix >> 32);
var k: i32 = 0;
if (hx < 0x00100000 or hx >> 31 != 0) {
// log(+-0) = -inf
if (ix << 1 == 0) {
return -math.inf(f32);
}
// log(-#) = nan
if (hx >> 31 != 0) {
return math.nan(f32);
}
// subnormal, scale x
k -= 54;
x *= 0x1.0p54;
hx = @intCast(u32, @bitCast(u64, x) >> 32);
} else if (hx >= 0x7FF00000) {
return x;
} else if (hx == 0x3FF00000 and ix << 32 == 0) {
return 0;
}
// x into [sqrt(2) / 2, sqrt(2)]
hx += 0x3FF00000 - 0x3FE6A09E;
k += @intCast(i32, hx >> 20) - 0x3FF;
hx = (hx & 0x000FFFFF) + 0x3FE6A09E;
ix = (@as(u64, hx) << 32) | (ix & 0xFFFFFFFF);
x = @bitCast(f64, ix);
const f = x - 1.0;
const hfsq = 0.5 * f * f;
const s = f / (2.0 + f);
const z = s * s;
const w = z * z;
const t1 = w * (Lg2 + w * (Lg4 + w * Lg6));
const t2 = z * (Lg1 + w * (Lg3 + w * (Lg5 + w * Lg7)));
const R = t2 + t1;
// hi + lo = f - hfsq + s * (hfsq + R) ~ log(1 + f)
var hi = f - hfsq;
var hii = @bitCast(u64, hi);
hii &= @as(u64, maxInt(u64)) << 32;
hi = @bitCast(f64, hii);
const lo = f - hi - hfsq + s * (hfsq + R);
// val_hi + val_lo ~ log10(1 + f) + k * log10(2)
var val_hi = hi * ivln10hi;
const dk = @intToFloat(f64, k);
const y = dk * log10_2hi;
var val_lo = dk * log10_2lo + (lo + hi) * ivln10lo + lo * ivln10hi;
// Extra precision multiplication
const ww = y + val_hi;
val_lo += (y - ww) + val_hi;
val_hi = ww;
return val_lo + val_hi;
}
pub fn __log10x(a: f80) callconv(.C) f80 {
// TODO: more efficient implementation
return @floatCast(f80, log10q(a));
}
pub fn log10q(a: f128) callconv(.C) f128 {
// TODO: more correct implementation
return log10(@floatCast(f64, a));
}
test "log10_32" {
const epsilon = 0.000001;
try testing.expect(math.approxEqAbs(f32, log10f(0.2), -0.698970, epsilon));
try testing.expect(math.approxEqAbs(f32, log10f(0.8923), -0.049489, epsilon));
try testing.expect(math.approxEqAbs(f32, log10f(1.5), 0.176091, epsilon));
try testing.expect(math.approxEqAbs(f32, log10f(37.45), 1.573452, epsilon));
try testing.expect(math.approxEqAbs(f32, log10f(89.123), 1.94999, epsilon));
try testing.expect(math.approxEqAbs(f32, log10f(123123.234375), 5.09034, epsilon));
}
test "log10_64" {
const epsilon = 0.000001;
try testing.expect(math.approxEqAbs(f64, log10(0.2), -0.698970, epsilon));
try testing.expect(math.approxEqAbs(f64, log10(0.8923), -0.049489, epsilon));
try testing.expect(math.approxEqAbs(f64, log10(1.5), 0.176091, epsilon));
try testing.expect(math.approxEqAbs(f64, log10(37.45), 1.573452, epsilon));
try testing.expect(math.approxEqAbs(f64, log10(89.123), 1.94999, epsilon));
try testing.expect(math.approxEqAbs(f64, log10(123123.234375), 5.09034, epsilon));
}
test "log10_32.special" {
try testing.expect(math.isPositiveInf(log10f(math.inf(f32))));
try testing.expect(math.isNegativeInf(log10f(0.0)));
try testing.expect(math.isNan(log10f(-1.0)));
try testing.expect(math.isNan(log10f(math.nan(f32))));
}
test "log10_64.special" {
try testing.expect(math.isPositiveInf(log10(math.inf(f64))));
try testing.expect(math.isNegativeInf(log10(0.0)));
try testing.expect(math.isNan(log10(-1.0)));
try testing.expect(math.isNan(log10(math.nan(f64))));
} | lib/std/special/compiler_rt/log10.zig |
const std = @import("std");
usingnamespace @import("ast.zig");
usingnamespace @import("intrinsics.zig");
usingnamespace @import("gc.zig");
usingnamespace @import("linereader.zig");
usingnamespace @import("sourcelocation.zig");
/// The expression reader and evaluator
pub const Interpreter = struct {
env: *Env,
exit_code: ?u8 = null,
gensym_seq: u64 = 0,
verbose: bool = false,
has_errors: bool = false,
/// Set up the root environment by binding a core set of intrinsics.
/// The rest of the standard Bio functions are loaded from std.lisp
pub fn init() !Interpreter {
gc = try GC.init();
SourceLocation.initStack();
var instance = Interpreter{ .env = try makeEnv(null, "global") };
try instance.env.put("import", &expr_std_import);
try instance.env.put("exit", &expr_std_exit);
try instance.env.put("gc", &expr_std_run_gc);
try instance.env.put("#f", &expr_atom_false);
try instance.env.put("#t", &expr_atom_true);
try instance.env.put("#?", &expr_atom_nil);
try instance.env.put("#!", &expr_atom_nil);
try instance.env.put("nil", &expr_atom_nil);
try instance.env.put("math.pi", &expr_std_math_pi);
try instance.env.put("math.e", &expr_std_math_e);
try instance.env.put("math.floor", &expr_std_floor);
try instance.env.put("math.pow", &expr_std_pow);
try instance.env.put("time.now", &expr_std_time_now);
try instance.env.put("number?", &expr_std_is_number);
try instance.env.put("symbol?", &expr_std_is_symbol);
try instance.env.put("list?", &expr_std_is_list);
try instance.env.put("callable?", &expr_std_is_callable);
try instance.env.put("verbose", &expr_std_verbose);
try instance.env.put("assert", &expr_std_assert_true);
try instance.env.put("gensym", &expr_std_gensym);
try instance.env.put("print", &expr_std_print);
try instance.env.put("string", &expr_std_string);
try instance.env.put("readline", &expr_std_read_line);
try instance.env.put("as", &expr_std_as);
try instance.env.put("len", &expr_std_len);
try instance.env.put("env", &expr_std_env);
try instance.env.put("self", &expr_std_self);
try instance.env.put("quote", &expr_std_quote);
try instance.env.put("quasiquote", &expr_std_quasi_quote);
try instance.env.put("unquote", &expr_std_unquote);
try instance.env.put("unquote-splicing", &expr_std_unquote_splicing);
try instance.env.put("double-quote", &expr_std_double_quote);
try instance.env.put("range", &expr_std_range);
try instance.env.put("define", &expr_std_define);
try instance.env.put("var", &expr_std_define);
try instance.env.put("lambda", &expr_std_lambda);
try instance.env.put("macro", &expr_std_macro);
try instance.env.put("Ξ»", &expr_std_lambda);
try instance.env.put("apply", &expr_std_apply);
try instance.env.put("list", &expr_std_list);
try instance.env.put("append", &expr_std_append);
try instance.env.put("eval", &expr_std_eval);
try instance.env.put("eval-string", &expr_std_eval_string);
try instance.env.put("set!", &expr_std_set);
try instance.env.put("unset!", &expr_std_unset);
try instance.env.put("try", &expr_std_try);
try instance.env.put("error", &expr_std_error);
try instance.env.put("+", &expr_std_sum);
try instance.env.put("-", &expr_std_sub);
try instance.env.put("*", &expr_std_mul);
try instance.env.put("/", &expr_std_div);
try instance.env.put("=", &expr_std_eq);
try instance.env.put("~=", &expr_std_eq_approx);
try instance.env.put("order", &expr_std_order);
try instance.env.put("io.open-file", &expr_std_file_open);
try instance.env.put("io.close-file", &expr_std_file_close);
try instance.env.put("io.read-line", &expr_std_file_read_line);
try instance.env.put("io.write-line", &expr_std_file_write_line);
return instance;
}
/// Perform a full GC sweep and check for leaks
pub fn deinit(_: *Interpreter) void {
gc.deinit();
SourceLocation.deinitStack();
if (!std.builtin.is_test and gpa.deinit()) {
std.io.getStdOut().writer().print("Memory leaks detected\n", .{}) catch unreachable;
}
}
/// Print user friendly errors
pub fn printError(_: *Interpreter, err: anyerror) !void {
const err_str = switch (err) {
ExprErrors.AlreadyReported => return,
ExprErrors.InvalidArgumentCount => "Invalid argument count",
ExprErrors.InvalidArgumentType => "Invalid argument type",
ExprErrors.ExpectedNumber => "Expected a number",
ExprErrors.UnexpectedRightParen => "Unexpected )",
ExprErrors.SyntaxError => "Syntax error while parsing",
ExprErrors.Eof => "End of file",
else => "Unknown",
};
try std.io.getStdOut().writer().print("{s}\n", .{err_str});
}
/// Print a formatted error message, prefixed with source location
pub fn printErrorFmt(self: *Interpreter, src_loc: *SourceLocation, comptime fmt: []const u8, args: anytype) !void {
if (fmt.len > 0) {
try std.io.getStdOut().writer().print("ERROR: {s}, line {d}: ", .{ src_loc.file, std.math.max(1, src_loc.line) });
try std.io.getStdOut().writer().print(fmt, args);
} else {
try std.io.getStdOut().writer().print("ERROR: {s}, line {d}\n", .{ src_loc.file, std.math.max(1, src_loc.line) });
}
self.has_errors = true;
}
/// Run GC if needed, then parse and evaluate the expression
pub fn parseAndEvalExpression(self: *Interpreter, line: []const u8) anyerror!?*Expr {
gc.runIfNeeded() catch {};
var input = std.mem.trimRight(u8, line, "\r\n");
// Ignore empty lines and comments
if (input.len == 0 or input[0] == ';') {
return null;
}
var expr = try self.parse(input);
return try self.eval(self.env, expr);
}
/// Parse Bio source code into Expr objects
pub fn parse(self: *Interpreter, input: []const u8) !*Expr {
var it = Lisperator{
.index = 0,
.buffer = input,
};
return self.read(&it);
}
/// Evaluate an expression
pub fn eval(self: *Interpreter, environment: *Env, expr: *Expr) anyerror!*Expr {
var maybe_next: ?*Expr = expr;
var env: *Env = environment;
tailcall_optimization_loop: while (maybe_next) |e| {
if (self.exit_code) |_| {
return &expr_atom_nil;
}
switch (e.val) {
ExprValue.num, ExprValue.env, ExprValue.any => {
return e;
},
ExprValue.sym => |sym| {
if (env.lookup(sym, true)) |val| {
return val;
} else {
try self.printErrorFmt(&e.src, "{s} is not defined\n", .{sym});
return &expr_atom_nil;
}
},
ExprValue.lst => |list| {
if (list.items.len == 0) {
return &expr_atom_nil;
}
const args_slice = list.items[1..];
if (list.items[0] == &expr_atom_begin) {
var res: *Expr = &expr_atom_nil;
for (args_slice[0 .. args_slice.len - 1]) |arg| {
res = try self.eval(env, arg);
}
maybe_next = args_slice[args_slice.len - 1];
continue;
} else if (list.items[0] == &expr_atom_cond) {
try requireMinimumArgCount(2, args_slice);
const else_branch = args_slice[args_slice.len - 1];
if (else_branch.val != ExprType.lst or else_branch.val.lst.items.len != 1) {
try self.printErrorFmt(&e.src, "Last expression in cond must be a single-expression list", .{});
return ExprErrors.AlreadyReported;
}
for (args_slice) |branch| {
if (branch == else_branch) {
maybe_next = branch.val.lst.items[0];
continue :tailcall_optimization_loop;
} else if (branch.val == ExprType.lst) {
try requireExactArgCount(2, branch.val.lst.items);
const predicate = try self.eval(env, branch.val.lst.items[0]);
if (predicate == &expr_atom_true) {
maybe_next = branch.val.lst.items[1];
continue :tailcall_optimization_loop;
}
} else {
try self.printErrorFmt(&e.src, "Invalid switch syntax\n", .{});
return ExprErrors.AlreadyReported;
}
}
return &expr_atom_nil;
} else if (list.items[0] == &expr_atom_if) {
try requireMinimumArgCount(2, args_slice);
var branch: usize = 1;
const predicate = try self.eval(env, args_slice[0]);
if (predicate != &expr_atom_true) {
if (isFalsy(predicate)) {
branch += 1;
} else {
try self.printErrorFmt(&e.src, "Not a boolean expression:\n", .{});
try predicate.print();
return ExprErrors.AlreadyReported;
}
}
if (branch < args_slice.len) {
maybe_next = args_slice[branch];
continue :tailcall_optimization_loop;
} else {
return &expr_atom_nil;
}
}
// Look up std function or lambda. If not found, the lookup has already reported the error.
var func = try self.eval(env, list.items[0]);
if (func == &expr_atom_nil) {
return &expr_atom_nil;
}
const kind = func.val;
switch (kind) {
ExprValue.env => |target_env| {
if (args_slice.len == 0 or (args_slice[0].val != ExprType.sym and args_slice[0].val != ExprType.lst)) {
try self.printErrorFmt(&e.src, "Missing symbol or call in environment lookup", .{});
try args_slice[0].print();
return ExprErrors.AlreadyReported;
}
if (args_slice[0].val == ExprType.lst) {
maybe_next = args_slice[0];
env = target_env;
continue :tailcall_optimization_loop;
} else if (target_env.lookup(args_slice[0].val.sym, false)) |match| {
return match;
} else {
try self.printErrorFmt(&e.src, "Symbol not found in given environment: {s} ", .{args_slice[0].val.sym});
return ExprErrors.AlreadyReported;
}
},
// Evaluate an intrinsic function
ExprValue.fun => |fun| {
return fun(self, env, args_slice) catch |err| {
try self.printErrorFmt(&e.src, "", .{});
try self.printError(err);
return &expr_atom_nil;
};
},
// Evaluate a previously defined lambda or macro
ExprValue.lam, ExprValue.mac => |fun| {
const parent_env = if (kind == ExprType.lam) func.env else env;
const kind_str = if (kind == ExprType.lam) "lambda" else "macro";
var local_env = try makeEnv(parent_env, kind_str);
var formal_param_count = fun.items[0].val.lst.items.len;
var logical_arg_count = args_slice.len;
// Bind arguments to the new environment
for (fun.items[0].val.lst.items) |param, index| {
if (param.val == ExprType.sym) {
if (param == &expr_atom_rest) {
formal_param_count -= 1;
var rest_args = try makeListExpr(null);
for (args_slice[index..]) |rest_param| {
logical_arg_count -= 1;
if (kind == ExprType.lam) {
try rest_args.val.lst.append(try self.eval(env, rest_param));
} else {
try rest_args.val.lst.append(rest_param);
}
}
logical_arg_count += 1;
try local_env.putWithSymbol(fun.items[0].val.lst.items[index + 1], rest_args);
break;
}
// Arguments are eagerly evaluated for lambdas, lazily for macros
if (index < args_slice.len) {
if (kind == ExprType.lam) {
try local_env.putWithSymbol(param, try self.eval(env, args_slice[index]));
} else {
try local_env.putWithSymbol(param, args_slice[index]);
}
}
} else {
try self.printErrorFmt(&e.src, "Formal parameter to {s} is not a symbol: ", .{kind_str});
try param.print();
}
}
if (logical_arg_count != formal_param_count) {
try self.printErrorFmt(&e.src, "{s} received {d} arguments, expected {d}\n", .{ kind_str, args_slice.len, formal_param_count });
return &expr_atom_nil;
}
// Evaluate body, except the last expression which is TCO'ed
var result: *Expr = undefined;
for (fun.items[1 .. fun.items.len - 1]) |body_expr| {
result = self.eval(local_env, body_expr) catch |err| {
try self.printErrorFmt(&body_expr.src, "Could not evaluate {s} body:", .{kind_str});
try self.printError(err);
return &expr_atom_nil;
};
if (self.has_errors) {
return &expr_atom_nil;
}
}
// For lambdas, we set up the next iteration to eval the last expression, while for
// macros we just evaluate it, and then evaluate it again in order to evaluate the
// generated expression produced by the macro.
const last_expr = fun.items[fun.items.len - 1];
if (kind == ExprValue.lam) {
env = local_env;
maybe_next = last_expr;
continue;
} else {
result = self.eval(local_env, last_expr) catch |err| {
try self.printErrorFmt(&last_expr.src, "Could not evaluate {s} body:", .{kind_str});
try self.printError(err);
return &expr_atom_nil;
};
return self.eval(local_env, result);
}
},
else => {
try self.printErrorFmt(&e.src, "Not a function or macro:\n", .{});
try list.items[0].print();
return &expr_atom_nil;
},
}
return &expr_atom_nil;
},
else => {
try self.printErrorFmt(&e.src, "Invalid expression: {}\n", .{e});
return &expr_atom_nil;
},
}
}
return &expr_atom_nil;
}
/// Recursively read expressions
pub fn read(self: *Interpreter, it: *Lisperator) anyerror!*Expr {
if (it.next()) |val| {
if (val.len > 0) {
switch (val[0]) {
'(' => {
var list = try makeListExpr(null);
while (it.peek()) |peek| {
if (peek.len == 0) {
return ExprErrors.SyntaxError;
}
if (peek[0] != ')') {
try list.val.lst.append(try self.read(it));
} else {
break;
}
}
_ = it.next();
return list;
},
')' => {
return ExprErrors.UnexpectedRightParen;
},
',' => {
var unquote_op: *Expr = &expr_atom_unquote;
var index_adjust: usize = 1;
// The Lisperator has no understanding of the , and ,@ prefixes, so we adjust it manually
// For instance, if the current token is ,@abc then the next token will be abc
if (val.len > 1 and val[1] == '@') {
unquote_op = &expr_atom_unquote_splicing;
if (val.len > 2) {
index_adjust += 1;
}
}
if (index_adjust > 0) {
it.index = it.prev_index + index_adjust;
}
return try makeListExpr(&.{ unquote_op, try self.read(it) });
},
'\'' => {
return try makeListExpr(&.{ &expr_atom_quote, try self.read(it) });
},
'`' => {
return try makeListExpr(&.{ &expr_atom_quasi_quote, try self.read(it) });
},
'"' => {
return try makeListExpr(&.{ &expr_atom_quote, try makeAtomByDuplicating(val[1..val.len]) });
},
else => {
return makeAtomByDuplicating(val);
},
}
} else {
return ExprErrors.SyntaxError;
}
} else {
return ExprErrors.Eof;
}
}
/// This function helps us read a Bio expression that may span multiple lines
/// If too many )'s are detected, an error is returned. We make sure to not
/// count parenthesis inside string literals.
pub fn readBalancedExpr(self: *Interpreter, reader: anytype, prompt: []const u8) anyerror!?[]u8 {
var balance: isize = 0;
var expr = std.ArrayList(u8).init(allocator);
defer expr.deinit();
var exprWriter = expr.writer();
try linenoise_wrapper.printPrompt(prompt);
line_reader: while (true) {
if (reader.readUntilDelimiterOrEofAlloc(allocator, '\n', 2048)) |maybe| {
if (maybe) |line| {
defer allocator.free(line);
SourceLocation.current().line += 1;
var onlySeenWhitespace = true;
var inside_string = false;
for (line) |char| {
if (char == ';' and onlySeenWhitespace) {
continue :line_reader;
}
onlySeenWhitespace = onlySeenWhitespace and std.ascii.isSpace(char);
if (char == '"') {
inside_string = !inside_string;
}
if (!inside_string) {
if (char == '(') {
balance += 1;
} else if (char == ')') {
balance -= 1;
}
}
}
if (expr.items.len > 0) {
try exprWriter.writeAll(" ");
}
try exprWriter.writeAll(line);
} else {
return null;
}
} else |err| {
try self.printErrorFmt(SourceLocation.current(), "readUntilDelimiterOrEofAlloc failed {}\n", .{err});
}
if (balance <= 0) {
break;
} else {
linenoise_wrapper.hidePrompt();
}
}
if (balance < 0) {
return ExprErrors.UnexpectedRightParen;
}
return expr.toOwnedSlice();
}
/// REPL
pub fn readEvalPrint(self: *Interpreter) !void {
const logo =
\\
\\ .. ..
\\ pd '(Ob. `bq
\\ 6P M YA Bio is a Lisp written in Zig
\\ 6M' db `Mb Docs at github.com/cryptocode/bio
\\ MN BIO. 8M
\\ MN AM'`M 8M Use arrow up/down for history
\\ YM. ,M' db ,M9 You can also run bio files with
\\ Mb JM' Yb./ .dM "bio run <file>"
\\ Yq . .pY
\\ `` ''
;
try std.io.getStdOut().writer().print("{s}\n\n", .{logo});
while (true) {
if (self.readBalancedExpr(&linenoise_reader, "bio> ")) |maybe| {
if (maybe) |input| {
defer allocator.free(input);
_ = try linenoise_wrapper.addToHistory(input);
var maybeResult = self.parseAndEvalExpression(input) catch |err| {
try self.printErrorFmt(SourceLocation.current(), "read-eval failed: \n", .{});
try self.printError(err);
continue;
};
if (maybeResult) |res| {
// Update the last expression and print it
try self.env.put("#?", res);
if (res != &expr_atom_nil or self.verbose) {
try res.print();
}
try std.io.getStdOut().writer().print("\n\n", .{});
}
if (self.exit_code) |exit_code| {
// Defer is not called as exit is [noreturn]
allocator.free(input);
self.deinit();
std.process.exit(exit_code);
}
}
} else |err| {
try self.printError(err);
}
}
}
};
/// A tokenizing iterator for Lisp expression
pub const Lisperator = struct {
buffer: []const u8,
index: usize = 0,
prev_index: usize = 0,
pub fn peek(self: *Lisperator) ?[]const u8 {
const index_now = self.index;
const val = self.next();
self.index = index_now;
return val;
}
/// Returns a slice of the next token, or null if tokenizing is complete
pub fn next(self: *Lisperator) ?[]const u8 {
if (self.index >= self.buffer.len) {
return null;
}
while (self.index + 1 < self.buffer.len and (self.buffer[self.index] == ' ' or self.buffer[self.index] == '\t')) {
self.index += 1;
}
var start = self.index;
self.prev_index = start;
if (self.buffer[self.index] == '"') {
while (self.index + 1 < self.buffer.len and (self.buffer[self.index + 1] != '"')) {
self.index += 1;
}
if (self.index + 1 == self.buffer.len or self.buffer[self.index + 1] != '"') {
std.io.getStdOut().writer().print("Unterminated string literal\n", .{}) catch unreachable;
return null;
}
self.index += 1;
defer self.index += 1;
return self.buffer[start..self.index];
}
if (self.buffer[self.index] == '(' or self.buffer[self.index] == ')' or self.buffer[self.index] == '\'' or self.buffer[self.index] == '`') {
self.index += 1;
return self.buffer[start .. start + 1];
} else {
if (std.mem.indexOfAnyPos(u8, self.buffer, start, " \t)(")) |delim_start| {
const res = self.buffer[start..delim_start];
self.index = delim_start;
return std.mem.trim(u8, res, "\r\n\t ");
} else if (self.index <= self.buffer.len) {
return std.mem.trim(u8, self.buffer[start..self.buffer.len], "\r\n\t ");
} else {
return null;
}
}
}
}; | src/interpreter.zig |
const std = @import("index.zig");
const builtin = @import("builtin");
const AtomicOrder = builtin.AtomicOrder;
const AtomicRmwOp = builtin.AtomicRmwOp;
const assert = std.debug.assert;
const SpinLock = std.SpinLock;
const linux = std.os.linux;
/// Lock may be held only once. If the same thread
/// tries to acquire the same mutex twice, it deadlocks.
/// The Linux implementation is based on mutex3 from
/// https://www.akkadia.org/drepper/futex.pdf
pub const Mutex = struct.{
/// 0: unlocked
/// 1: locked, no waiters
/// 2: locked, one or more waiters
linux_lock: @typeOf(linux_lock_init),
/// TODO better implementation than spin lock
spin_lock: @typeOf(spin_lock_init),
const linux_lock_init = if (builtin.os == builtin.Os.linux) i32(0) else {};
const spin_lock_init = if (builtin.os != builtin.Os.linux) SpinLock.init() else {};
pub const Held = struct.{
mutex: *Mutex,
pub fn release(self: Held) void {
if (builtin.os == builtin.Os.linux) {
const c = @atomicRmw(i32, &self.mutex.linux_lock, AtomicRmwOp.Sub, 1, AtomicOrder.Release);
if (c != 1) {
_ = @atomicRmw(i32, &self.mutex.linux_lock, AtomicRmwOp.Xchg, 0, AtomicOrder.Release);
const rc = linux.futex_wake(&self.mutex.linux_lock, linux.FUTEX_WAKE | linux.FUTEX_PRIVATE_FLAG, 1);
switch (linux.getErrno(rc)) {
0 => {},
linux.EINVAL => unreachable,
else => unreachable,
}
}
} else {
SpinLock.Held.release(SpinLock.Held.{ .spinlock = &self.mutex.spin_lock });
}
}
};
pub fn init() Mutex {
return Mutex.{
.linux_lock = linux_lock_init,
.spin_lock = spin_lock_init,
};
}
pub fn acquire(self: *Mutex) Held {
if (builtin.os == builtin.Os.linux) {
var c = @cmpxchgWeak(i32, &self.linux_lock, 0, 1, AtomicOrder.Acquire, AtomicOrder.Monotonic) orelse
return Held.{ .mutex = self };
if (c != 2)
c = @atomicRmw(i32, &self.linux_lock, AtomicRmwOp.Xchg, 2, AtomicOrder.Acquire);
while (c != 0) {
const rc = linux.futex_wait(&self.linux_lock, linux.FUTEX_WAIT | linux.FUTEX_PRIVATE_FLAG, 2, null);
switch (linux.getErrno(rc)) {
0, linux.EINTR, linux.EAGAIN => {},
linux.EINVAL => unreachable,
else => unreachable,
}
c = @atomicRmw(i32, &self.linux_lock, AtomicRmwOp.Xchg, 2, AtomicOrder.Acquire);
}
} else {
_ = self.spin_lock.acquire();
}
return Held.{ .mutex = self };
}
};
const Context = struct.{
mutex: *Mutex,
data: i128,
const incr_count = 10000;
};
test "std.Mutex" {
var direct_allocator = std.heap.DirectAllocator.init();
defer direct_allocator.deinit();
var plenty_of_memory = try direct_allocator.allocator.alloc(u8, 300 * 1024);
defer direct_allocator.allocator.free(plenty_of_memory);
var fixed_buffer_allocator = std.heap.ThreadSafeFixedBufferAllocator.init(plenty_of_memory);
var a = &fixed_buffer_allocator.allocator;
var mutex = Mutex.init();
var context = Context.{
.mutex = &mutex,
.data = 0,
};
const thread_count = 10;
var threads: [thread_count]*std.os.Thread = undefined;
for (threads) |*t| {
t.* = try std.os.spawnThread(&context, worker);
}
for (threads) |t|
t.wait();
std.debug.assertOrPanic(context.data == thread_count * Context.incr_count);
}
fn worker(ctx: *Context) void {
var i: usize = 0;
while (i != Context.incr_count) : (i += 1) {
const held = ctx.mutex.acquire();
defer held.release();
ctx.data += 1;
}
} | std/mutex.zig |
const fmath = @import("index.zig");
pub fn isInf(x: var) -> bool {
const T = @typeOf(x);
switch (T) {
f32 => {
const bits = @bitCast(u32, x);
bits & 0x7FFFFFFF == 0x7F800000
},
f64 => {
const bits = @bitCast(u64, x);
bits & (@maxValue(u64) >> 1) == (0x7FF << 52)
},
else => {
@compileError("isInf not implemented for " ++ @typeName(T));
},
}
}
pub fn isPositiveInf(x: var) -> bool {
const T = @typeOf(x);
switch (T) {
f32 => {
@bitCast(u32, x) == 0x7F800000
},
f64 => {
@bitCast(u64, x) == 0x7FF << 52
},
else => {
@compileError("isPositiveInf not implemented for " ++ @typeName(T));
},
}
}
pub fn isNegativeInf(x: var) -> bool {
const T = @typeOf(x);
switch (T) {
f32 => {
@bitCast(u32, x) == 0xFF800000
},
f64 => {
@bitCast(u64, x) == 0xFFF << 52
},
else => {
@compileError("isNegativeInf not implemented for " ++ @typeName(T));
},
}
}
test "isInf" {
fmath.assert(!isInf(f32(0.0)));
fmath.assert(!isInf(f32(-0.0)));
fmath.assert(!isInf(f64(0.0)));
fmath.assert(!isInf(f64(-0.0)));
fmath.assert(isInf(fmath.inf(f32)));
fmath.assert(isInf(-fmath.inf(f32)));
fmath.assert(isInf(fmath.inf(f64)));
fmath.assert(isInf(-fmath.inf(f64)));
}
test "isPositiveInf" {
fmath.assert(!isPositiveInf(f32(0.0)));
fmath.assert(!isPositiveInf(f32(-0.0)));
fmath.assert(!isPositiveInf(f64(0.0)));
fmath.assert(!isPositiveInf(f64(-0.0)));
fmath.assert(isPositiveInf(fmath.inf(f32)));
fmath.assert(!isPositiveInf(-fmath.inf(f32)));
fmath.assert(isPositiveInf(fmath.inf(f64)));
fmath.assert(!isPositiveInf(-fmath.inf(f64)));
}
test "isNegativeInf" {
fmath.assert(!isNegativeInf(f32(0.0)));
fmath.assert(!isNegativeInf(f32(-0.0)));
fmath.assert(!isNegativeInf(f64(0.0)));
fmath.assert(!isNegativeInf(f64(-0.0)));
fmath.assert(!isNegativeInf(fmath.inf(f32)));
fmath.assert(isNegativeInf(-fmath.inf(f32)));
fmath.assert(!isNegativeInf(fmath.inf(f64)));
fmath.assert(isNegativeInf(-fmath.inf(f64)));
} | src/isinf.zig |
pub const DXGI_USAGE_SHADER_INPUT = @as(u32, 16);
pub const DXGI_USAGE_RENDER_TARGET_OUTPUT = @as(u32, 32);
pub const DXGI_USAGE_BACK_BUFFER = @as(u32, 64);
pub const DXGI_USAGE_SHARED = @as(u32, 128);
pub const DXGI_USAGE_READ_ONLY = @as(u32, 256);
pub const DXGI_USAGE_DISCARD_ON_PRESENT = @as(u32, 512);
pub const DXGI_USAGE_UNORDERED_ACCESS = @as(u32, 1024);
pub const DXGI_MAP_READ = @as(u32, 1);
pub const DXGI_MAP_WRITE = @as(u32, 2);
pub const DXGI_MAP_DISCARD = @as(u32, 4);
pub const DXGI_ENUM_MODES_INTERLACED = @as(u32, 1);
pub const DXGI_ENUM_MODES_SCALING = @as(u32, 2);
pub const DXGI_MAX_SWAP_CHAIN_BUFFERS = @as(u32, 16);
pub const DXGI_PRESENT_TEST = @as(u32, 1);
pub const DXGI_PRESENT_DO_NOT_SEQUENCE = @as(u32, 2);
pub const DXGI_PRESENT_RESTART = @as(u32, 4);
pub const DXGI_PRESENT_DO_NOT_WAIT = @as(u32, 8);
pub const DXGI_PRESENT_STEREO_PREFER_RIGHT = @as(u32, 16);
pub const DXGI_PRESENT_STEREO_TEMPORARY_MONO = @as(u32, 32);
pub const DXGI_PRESENT_RESTRICT_TO_OUTPUT = @as(u32, 64);
pub const DXGI_PRESENT_USE_DURATION = @as(u32, 256);
pub const DXGI_PRESENT_ALLOW_TEARING = @as(u32, 512);
pub const DXGI_MWA_NO_WINDOW_CHANGES = @as(u32, 1);
pub const DXGI_MWA_NO_ALT_ENTER = @as(u32, 2);
pub const DXGI_MWA_NO_PRINT_SCREEN = @as(u32, 4);
pub const DXGI_MWA_VALID = @as(u32, 7);
pub const DXGI_ENUM_MODES_STEREO = @as(u32, 4);
pub const DXGI_ENUM_MODES_DISABLED_STEREO = @as(u32, 8);
pub const DXGI_SHARED_RESOURCE_READ = @as(u32, 2147483648);
pub const DXGI_SHARED_RESOURCE_WRITE = @as(u32, 1);
pub const DXGI_DEBUG_BINARY_VERSION = @as(u32, 1);
pub const DXGI_DEBUG_ALL = Guid.initString("e48ae283-da80-490b-87e6-43e9a9cfda08");
pub const DXGI_DEBUG_DX = Guid.initString("35cdd7fc-13b2-421d-a5d7-7e4451287d64");
pub const DXGI_DEBUG_DXGI = Guid.initString("25cddaa4-b1c6-47e1-ac3e-98875b5a2e2a");
pub const DXGI_DEBUG_APP = Guid.initString("06cd6e01-4219-4ebd-8709-27ed23360c62");
pub const DXGI_INFO_QUEUE_MESSAGE_ID_STRING_FROM_APPLICATION = @as(u32, 0);
pub const DXGI_INFO_QUEUE_DEFAULT_MESSAGE_COUNT_LIMIT = @as(u32, 1024);
pub const DXGI_CREATE_FACTORY_DEBUG = @as(u32, 1);
pub const DXGI_ERROR_INVALID_CALL = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270527));
pub const DXGI_ERROR_NOT_FOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270526));
pub const DXGI_ERROR_MORE_DATA = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270525));
pub const DXGI_ERROR_UNSUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270524));
pub const DXGI_ERROR_DEVICE_REMOVED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270523));
pub const DXGI_ERROR_DEVICE_HUNG = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270522));
pub const DXGI_ERROR_DEVICE_RESET = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270521));
pub const DXGI_ERROR_WAS_STILL_DRAWING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270518));
pub const DXGI_ERROR_FRAME_STATISTICS_DISJOINT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270517));
pub const DXGI_ERROR_GRAPHICS_VIDPN_SOURCE_IN_USE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270516));
pub const DXGI_ERROR_DRIVER_INTERNAL_ERROR = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270496));
pub const DXGI_ERROR_NONEXCLUSIVE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270495));
pub const DXGI_ERROR_NOT_CURRENTLY_AVAILABLE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270494));
pub const DXGI_ERROR_REMOTE_CLIENT_DISCONNECTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270493));
pub const DXGI_ERROR_REMOTE_OUTOFMEMORY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270492));
pub const DXGI_ERROR_ACCESS_LOST = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270490));
pub const DXGI_ERROR_WAIT_TIMEOUT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270489));
pub const DXGI_ERROR_SESSION_DISCONNECTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270488));
pub const DXGI_ERROR_RESTRICT_TO_OUTPUT_STALE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270487));
pub const DXGI_ERROR_CANNOT_PROTECT_CONTENT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270486));
pub const DXGI_ERROR_ACCESS_DENIED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270485));
pub const DXGI_ERROR_NAME_ALREADY_EXISTS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270484));
pub const DXGI_ERROR_SDK_COMPONENT_MISSING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270483));
pub const DXGI_ERROR_NOT_CURRENT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270482));
pub const DXGI_ERROR_HW_PROTECTION_OUTOFMEMORY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270480));
pub const DXGI_ERROR_DYNAMIC_CODE_POLICY_VIOLATION = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270479));
pub const DXGI_ERROR_NON_COMPOSITED_UI = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270478));
pub const DXGI_ERROR_MODE_CHANGE_IN_PROGRESS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270491));
pub const DXGI_ERROR_CACHE_CORRUPT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270477));
pub const DXGI_ERROR_CACHE_FULL = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270476));
pub const DXGI_ERROR_CACHE_HASH_COLLISION = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270475));
pub const DXGI_ERROR_ALREADY_EXISTS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2005270474));
//--------------------------------------------------------------------------------
// Section: Types (106)
//--------------------------------------------------------------------------------
pub const DXGI_RGBA = extern struct {
r: f32,
g: f32,
b: f32,
a: f32,
};
pub const DXGI_RESOURCE_PRIORITY = enum(u32) {
MINIMUM = 671088640,
LOW = 1342177280,
NORMAL = 2013265920,
HIGH = 2684354560,
MAXIMUM = 3355443200,
};
pub const DXGI_RESOURCE_PRIORITY_MINIMUM = DXGI_RESOURCE_PRIORITY.MINIMUM;
pub const DXGI_RESOURCE_PRIORITY_LOW = DXGI_RESOURCE_PRIORITY.LOW;
pub const DXGI_RESOURCE_PRIORITY_NORMAL = DXGI_RESOURCE_PRIORITY.NORMAL;
pub const DXGI_RESOURCE_PRIORITY_HIGH = DXGI_RESOURCE_PRIORITY.HIGH;
pub const DXGI_RESOURCE_PRIORITY_MAXIMUM = DXGI_RESOURCE_PRIORITY.MAXIMUM;
pub const DXGI_FRAME_STATISTICS = extern struct {
PresentCount: u32,
PresentRefreshCount: u32,
SyncRefreshCount: u32,
SyncQPCTime: LARGE_INTEGER,
SyncGPUTime: LARGE_INTEGER,
};
pub const DXGI_MAPPED_RECT = extern struct {
Pitch: i32,
pBits: ?*u8,
};
pub const DXGI_ADAPTER_DESC = extern struct {
Description: [128]u16,
VendorId: u32,
DeviceId: u32,
SubSysId: u32,
Revision: u32,
DedicatedVideoMemory: usize,
DedicatedSystemMemory: usize,
SharedSystemMemory: usize,
AdapterLuid: LUID,
};
pub const DXGI_OUTPUT_DESC = extern struct {
DeviceName: [32]u16,
DesktopCoordinates: RECT,
AttachedToDesktop: BOOL,
Rotation: DXGI_MODE_ROTATION,
Monitor: ?HMONITOR,
};
pub const DXGI_SHARED_RESOURCE = extern struct {
Handle: ?HANDLE,
};
pub const DXGI_RESIDENCY = enum(i32) {
FULLY_RESIDENT = 1,
RESIDENT_IN_SHARED_MEMORY = 2,
EVICTED_TO_DISK = 3,
};
pub const DXGI_RESIDENCY_FULLY_RESIDENT = DXGI_RESIDENCY.FULLY_RESIDENT;
pub const DXGI_RESIDENCY_RESIDENT_IN_SHARED_MEMORY = DXGI_RESIDENCY.RESIDENT_IN_SHARED_MEMORY;
pub const DXGI_RESIDENCY_EVICTED_TO_DISK = DXGI_RESIDENCY.EVICTED_TO_DISK;
pub const DXGI_SURFACE_DESC = extern struct {
Width: u32,
Height: u32,
Format: DXGI_FORMAT,
SampleDesc: DXGI_SAMPLE_DESC,
};
pub const DXGI_SWAP_EFFECT = enum(i32) {
DISCARD = 0,
SEQUENTIAL = 1,
FLIP_SEQUENTIAL = 3,
FLIP_DISCARD = 4,
};
pub const DXGI_SWAP_EFFECT_DISCARD = DXGI_SWAP_EFFECT.DISCARD;
pub const DXGI_SWAP_EFFECT_SEQUENTIAL = DXGI_SWAP_EFFECT.SEQUENTIAL;
pub const DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL = DXGI_SWAP_EFFECT.FLIP_SEQUENTIAL;
pub const DXGI_SWAP_EFFECT_FLIP_DISCARD = DXGI_SWAP_EFFECT.FLIP_DISCARD;
pub const DXGI_SWAP_CHAIN_FLAG = enum(i32) {
NONPREROTATED = 1,
ALLOW_MODE_SWITCH = 2,
GDI_COMPATIBLE = 4,
RESTRICTED_CONTENT = 8,
RESTRICT_SHARED_RESOURCE_DRIVER = 16,
DISPLAY_ONLY = 32,
FRAME_LATENCY_WAITABLE_OBJECT = 64,
FOREGROUND_LAYER = 128,
FULLSCREEN_VIDEO = 256,
YUV_VIDEO = 512,
HW_PROTECTED = 1024,
ALLOW_TEARING = 2048,
RESTRICTED_TO_ALL_HOLOGRAPHIC_DISPLAYS = 4096,
};
pub const DXGI_SWAP_CHAIN_FLAG_NONPREROTATED = DXGI_SWAP_CHAIN_FLAG.NONPREROTATED;
pub const DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH = DXGI_SWAP_CHAIN_FLAG.ALLOW_MODE_SWITCH;
pub const DXGI_SWAP_CHAIN_FLAG_GDI_COMPATIBLE = DXGI_SWAP_CHAIN_FLAG.GDI_COMPATIBLE;
pub const DXGI_SWAP_CHAIN_FLAG_RESTRICTED_CONTENT = DXGI_SWAP_CHAIN_FLAG.RESTRICTED_CONTENT;
pub const DXGI_SWAP_CHAIN_FLAG_RESTRICT_SHARED_RESOURCE_DRIVER = DXGI_SWAP_CHAIN_FLAG.RESTRICT_SHARED_RESOURCE_DRIVER;
pub const DXGI_SWAP_CHAIN_FLAG_DISPLAY_ONLY = DXGI_SWAP_CHAIN_FLAG.DISPLAY_ONLY;
pub const DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT = DXGI_SWAP_CHAIN_FLAG.FRAME_LATENCY_WAITABLE_OBJECT;
pub const DXGI_SWAP_CHAIN_FLAG_FOREGROUND_LAYER = DXGI_SWAP_CHAIN_FLAG.FOREGROUND_LAYER;
pub const DXGI_SWAP_CHAIN_FLAG_FULLSCREEN_VIDEO = DXGI_SWAP_CHAIN_FLAG.FULLSCREEN_VIDEO;
pub const DXGI_SWAP_CHAIN_FLAG_YUV_VIDEO = DXGI_SWAP_CHAIN_FLAG.YUV_VIDEO;
pub const DXGI_SWAP_CHAIN_FLAG_HW_PROTECTED = DXGI_SWAP_CHAIN_FLAG.HW_PROTECTED;
pub const DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING = DXGI_SWAP_CHAIN_FLAG.ALLOW_TEARING;
pub const DXGI_SWAP_CHAIN_FLAG_RESTRICTED_TO_ALL_HOLOGRAPHIC_DISPLAYS = DXGI_SWAP_CHAIN_FLAG.RESTRICTED_TO_ALL_HOLOGRAPHIC_DISPLAYS;
pub const DXGI_SWAP_CHAIN_DESC = extern struct {
BufferDesc: DXGI_MODE_DESC,
SampleDesc: DXGI_SAMPLE_DESC,
BufferUsage: u32,
BufferCount: u32,
OutputWindow: ?HWND,
Windowed: BOOL,
SwapEffect: DXGI_SWAP_EFFECT,
Flags: u32,
};
const IID_IDXGIObject_Value = Guid.initString("aec22fb8-76f3-4639-9be0-28eb43a67a2e");
pub const IID_IDXGIObject = &IID_IDXGIObject_Value;
pub const IDXGIObject = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetPrivateData: fn(
self: *const IDXGIObject,
Name: ?*const Guid,
DataSize: u32,
// TODO: what to do with BytesParamIndex 1?
pData: ?*const anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetPrivateDataInterface: fn(
self: *const IDXGIObject,
Name: ?*const Guid,
pUnknown: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPrivateData: fn(
self: *const IDXGIObject,
Name: ?*const Guid,
pDataSize: ?*u32,
// TODO: what to do with BytesParamIndex 1?
pData: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetParent: fn(
self: *const IDXGIObject,
riid: ?*const Guid,
ppParent: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIObject_SetPrivateData(self: *const T, Name: ?*const Guid, DataSize: u32, pData: ?*const anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIObject.VTable, self.vtable).SetPrivateData(@ptrCast(*const IDXGIObject, self), Name, DataSize, pData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIObject_SetPrivateDataInterface(self: *const T, Name: ?*const Guid, pUnknown: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIObject.VTable, self.vtable).SetPrivateDataInterface(@ptrCast(*const IDXGIObject, self), Name, pUnknown);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIObject_GetPrivateData(self: *const T, Name: ?*const Guid, pDataSize: ?*u32, pData: ?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIObject.VTable, self.vtable).GetPrivateData(@ptrCast(*const IDXGIObject, self), Name, pDataSize, pData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIObject_GetParent(self: *const T, riid: ?*const Guid, ppParent: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIObject.VTable, self.vtable).GetParent(@ptrCast(*const IDXGIObject, self), riid, ppParent);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDXGIDeviceSubObject_Value = Guid.initString("3d3e0379-f9de-4d58-bb6c-18d62992f1a6");
pub const IID_IDXGIDeviceSubObject = &IID_IDXGIDeviceSubObject_Value;
pub const IDXGIDeviceSubObject = extern struct {
pub const VTable = extern struct {
base: IDXGIObject.VTable,
GetDevice: fn(
self: *const IDXGIDeviceSubObject,
riid: ?*const Guid,
ppDevice: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIObject.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIDeviceSubObject_GetDevice(self: *const T, riid: ?*const Guid, ppDevice: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIDeviceSubObject.VTable, self.vtable).GetDevice(@ptrCast(*const IDXGIDeviceSubObject, self), riid, ppDevice);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDXGIResource_Value = Guid.initString("035f3ab4-482e-4e50-b41f-8a7f8bd8960b");
pub const IID_IDXGIResource = &IID_IDXGIResource_Value;
pub const IDXGIResource = extern struct {
pub const VTable = extern struct {
base: IDXGIDeviceSubObject.VTable,
GetSharedHandle: fn(
self: *const IDXGIResource,
pSharedHandle: ?*?HANDLE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetUsage: fn(
self: *const IDXGIResource,
pUsage: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetEvictionPriority: fn(
self: *const IDXGIResource,
EvictionPriority: DXGI_RESOURCE_PRIORITY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetEvictionPriority: fn(
self: *const IDXGIResource,
pEvictionPriority: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIDeviceSubObject.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIResource_GetSharedHandle(self: *const T, pSharedHandle: ?*?HANDLE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIResource.VTable, self.vtable).GetSharedHandle(@ptrCast(*const IDXGIResource, self), pSharedHandle);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIResource_GetUsage(self: *const T, pUsage: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIResource.VTable, self.vtable).GetUsage(@ptrCast(*const IDXGIResource, self), pUsage);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIResource_SetEvictionPriority(self: *const T, EvictionPriority: DXGI_RESOURCE_PRIORITY) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIResource.VTable, self.vtable).SetEvictionPriority(@ptrCast(*const IDXGIResource, self), EvictionPriority);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIResource_GetEvictionPriority(self: *const T, pEvictionPriority: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIResource.VTable, self.vtable).GetEvictionPriority(@ptrCast(*const IDXGIResource, self), pEvictionPriority);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDXGIKeyedMutex_Value = Guid.initString("9d8e1289-d7b3-465f-8126-250e349af85d");
pub const IID_IDXGIKeyedMutex = &IID_IDXGIKeyedMutex_Value;
pub const IDXGIKeyedMutex = extern struct {
pub const VTable = extern struct {
base: IDXGIDeviceSubObject.VTable,
AcquireSync: fn(
self: *const IDXGIKeyedMutex,
Key: u64,
dwMilliseconds: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ReleaseSync: fn(
self: *const IDXGIKeyedMutex,
Key: u64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIDeviceSubObject.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIKeyedMutex_AcquireSync(self: *const T, Key: u64, dwMilliseconds: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIKeyedMutex.VTable, self.vtable).AcquireSync(@ptrCast(*const IDXGIKeyedMutex, self), Key, dwMilliseconds);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIKeyedMutex_ReleaseSync(self: *const T, Key: u64) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIKeyedMutex.VTable, self.vtable).ReleaseSync(@ptrCast(*const IDXGIKeyedMutex, self), Key);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDXGISurface_Value = Guid.initString("cafcb56c-6ac3-4889-bf47-9e23bbd260ec");
pub const IID_IDXGISurface = &IID_IDXGISurface_Value;
pub const IDXGISurface = extern struct {
pub const VTable = extern struct {
base: IDXGIDeviceSubObject.VTable,
GetDesc: fn(
self: *const IDXGISurface,
pDesc: ?*DXGI_SURFACE_DESC,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Map: fn(
self: *const IDXGISurface,
pLockedRect: ?*DXGI_MAPPED_RECT,
MapFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Unmap: fn(
self: *const IDXGISurface,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIDeviceSubObject.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISurface_GetDesc(self: *const T, pDesc: ?*DXGI_SURFACE_DESC) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISurface.VTable, self.vtable).GetDesc(@ptrCast(*const IDXGISurface, self), pDesc);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISurface_Map(self: *const T, pLockedRect: ?*DXGI_MAPPED_RECT, MapFlags: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISurface.VTable, self.vtable).Map(@ptrCast(*const IDXGISurface, self), pLockedRect, MapFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISurface_Unmap(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISurface.VTable, self.vtable).Unmap(@ptrCast(*const IDXGISurface, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IDXGISurface1_Value = Guid.initString("4ae63092-6327-4c1b-80ae-bfe12ea32b86");
pub const IID_IDXGISurface1 = &IID_IDXGISurface1_Value;
pub const IDXGISurface1 = extern struct {
pub const VTable = extern struct {
base: IDXGISurface.VTable,
GetDC: fn(
self: *const IDXGISurface1,
Discard: BOOL,
phdc: ?*?HDC,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ReleaseDC: fn(
self: *const IDXGISurface1,
pDirtyRect: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGISurface.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISurface1_GetDC(self: *const T, Discard: BOOL, phdc: ?*?HDC) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISurface1.VTable, self.vtable).GetDC(@ptrCast(*const IDXGISurface1, self), Discard, phdc);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISurface1_ReleaseDC(self: *const T, pDirtyRect: ?*RECT) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISurface1.VTable, self.vtable).ReleaseDC(@ptrCast(*const IDXGISurface1, self), pDirtyRect);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDXGIAdapter_Value = Guid.initString("2411e7e1-12ac-4ccf-bd14-9798e8534dc0");
pub const IID_IDXGIAdapter = &IID_IDXGIAdapter_Value;
pub const IDXGIAdapter = extern struct {
pub const VTable = extern struct {
base: IDXGIObject.VTable,
EnumOutputs: fn(
self: *const IDXGIAdapter,
Output: u32,
ppOutput: ?*?*IDXGIOutput,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDesc: fn(
self: *const IDXGIAdapter,
pDesc: ?*DXGI_ADAPTER_DESC,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CheckInterfaceSupport: fn(
self: *const IDXGIAdapter,
InterfaceName: ?*const Guid,
pUMDVersion: ?*LARGE_INTEGER,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIObject.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIAdapter_EnumOutputs(self: *const T, Output: u32, ppOutput: ?*?*IDXGIOutput) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIAdapter.VTable, self.vtable).EnumOutputs(@ptrCast(*const IDXGIAdapter, self), Output, ppOutput);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIAdapter_GetDesc(self: *const T, pDesc: ?*DXGI_ADAPTER_DESC) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIAdapter.VTable, self.vtable).GetDesc(@ptrCast(*const IDXGIAdapter, self), pDesc);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIAdapter_CheckInterfaceSupport(self: *const T, InterfaceName: ?*const Guid, pUMDVersion: ?*LARGE_INTEGER) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIAdapter.VTable, self.vtable).CheckInterfaceSupport(@ptrCast(*const IDXGIAdapter, self), InterfaceName, pUMDVersion);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDXGIOutput_Value = Guid.initString("ae02eedb-c735-4690-8d52-5a8dc20213aa");
pub const IID_IDXGIOutput = &IID_IDXGIOutput_Value;
pub const IDXGIOutput = extern struct {
pub const VTable = extern struct {
base: IDXGIObject.VTable,
GetDesc: fn(
self: *const IDXGIOutput,
pDesc: ?*DXGI_OUTPUT_DESC,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDisplayModeList: fn(
self: *const IDXGIOutput,
EnumFormat: DXGI_FORMAT,
Flags: u32,
pNumModes: ?*u32,
pDesc: ?[*]DXGI_MODE_DESC,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FindClosestMatchingMode: fn(
self: *const IDXGIOutput,
pModeToMatch: ?*const DXGI_MODE_DESC,
pClosestMatch: ?*DXGI_MODE_DESC,
pConcernedDevice: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WaitForVBlank: fn(
self: *const IDXGIOutput,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TakeOwnership: fn(
self: *const IDXGIOutput,
pDevice: ?*IUnknown,
Exclusive: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ReleaseOwnership: fn(
self: *const IDXGIOutput,
) callconv(@import("std").os.windows.WINAPI) void,
GetGammaControlCapabilities: fn(
self: *const IDXGIOutput,
pGammaCaps: ?*DXGI_GAMMA_CONTROL_CAPABILITIES,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetGammaControl: fn(
self: *const IDXGIOutput,
pArray: ?*const DXGI_GAMMA_CONTROL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetGammaControl: fn(
self: *const IDXGIOutput,
pArray: ?*DXGI_GAMMA_CONTROL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetDisplaySurface: fn(
self: *const IDXGIOutput,
pScanoutSurface: ?*IDXGISurface,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDisplaySurfaceData: fn(
self: *const IDXGIOutput,
pDestination: ?*IDXGISurface,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFrameStatistics: fn(
self: *const IDXGIOutput,
pStats: ?*DXGI_FRAME_STATISTICS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIObject.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIOutput_GetDesc(self: *const T, pDesc: ?*DXGI_OUTPUT_DESC) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIOutput.VTable, self.vtable).GetDesc(@ptrCast(*const IDXGIOutput, self), pDesc);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIOutput_GetDisplayModeList(self: *const T, EnumFormat: DXGI_FORMAT, Flags: u32, pNumModes: ?*u32, pDesc: ?[*]DXGI_MODE_DESC) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIOutput.VTable, self.vtable).GetDisplayModeList(@ptrCast(*const IDXGIOutput, self), EnumFormat, Flags, pNumModes, pDesc);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIOutput_FindClosestMatchingMode(self: *const T, pModeToMatch: ?*const DXGI_MODE_DESC, pClosestMatch: ?*DXGI_MODE_DESC, pConcernedDevice: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIOutput.VTable, self.vtable).FindClosestMatchingMode(@ptrCast(*const IDXGIOutput, self), pModeToMatch, pClosestMatch, pConcernedDevice);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIOutput_WaitForVBlank(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIOutput.VTable, self.vtable).WaitForVBlank(@ptrCast(*const IDXGIOutput, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIOutput_TakeOwnership(self: *const T, pDevice: ?*IUnknown, Exclusive: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIOutput.VTable, self.vtable).TakeOwnership(@ptrCast(*const IDXGIOutput, self), pDevice, Exclusive);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIOutput_ReleaseOwnership(self: *const T) callconv(.Inline) void {
return @ptrCast(*const IDXGIOutput.VTable, self.vtable).ReleaseOwnership(@ptrCast(*const IDXGIOutput, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIOutput_GetGammaControlCapabilities(self: *const T, pGammaCaps: ?*DXGI_GAMMA_CONTROL_CAPABILITIES) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIOutput.VTable, self.vtable).GetGammaControlCapabilities(@ptrCast(*const IDXGIOutput, self), pGammaCaps);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIOutput_SetGammaControl(self: *const T, pArray: ?*const DXGI_GAMMA_CONTROL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIOutput.VTable, self.vtable).SetGammaControl(@ptrCast(*const IDXGIOutput, self), pArray);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIOutput_GetGammaControl(self: *const T, pArray: ?*DXGI_GAMMA_CONTROL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIOutput.VTable, self.vtable).GetGammaControl(@ptrCast(*const IDXGIOutput, self), pArray);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIOutput_SetDisplaySurface(self: *const T, pScanoutSurface: ?*IDXGISurface) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIOutput.VTable, self.vtable).SetDisplaySurface(@ptrCast(*const IDXGIOutput, self), pScanoutSurface);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIOutput_GetDisplaySurfaceData(self: *const T, pDestination: ?*IDXGISurface) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIOutput.VTable, self.vtable).GetDisplaySurfaceData(@ptrCast(*const IDXGIOutput, self), pDestination);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIOutput_GetFrameStatistics(self: *const T, pStats: ?*DXGI_FRAME_STATISTICS) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIOutput.VTable, self.vtable).GetFrameStatistics(@ptrCast(*const IDXGIOutput, self), pStats);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDXGISwapChain_Value = Guid.initString("310d36a0-d2e7-4c0a-aa04-6a9d23b8886a");
pub const IID_IDXGISwapChain = &IID_IDXGISwapChain_Value;
pub const IDXGISwapChain = extern struct {
pub const VTable = extern struct {
base: IDXGIDeviceSubObject.VTable,
Present: fn(
self: *const IDXGISwapChain,
SyncInterval: u32,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetBuffer: fn(
self: *const IDXGISwapChain,
Buffer: u32,
riid: ?*const Guid,
ppSurface: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetFullscreenState: fn(
self: *const IDXGISwapChain,
Fullscreen: BOOL,
pTarget: ?*IDXGIOutput,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFullscreenState: fn(
self: *const IDXGISwapChain,
pFullscreen: ?*BOOL,
ppTarget: ?*?*IDXGIOutput,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDesc: fn(
self: *const IDXGISwapChain,
pDesc: ?*DXGI_SWAP_CHAIN_DESC,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ResizeBuffers: fn(
self: *const IDXGISwapChain,
BufferCount: u32,
Width: u32,
Height: u32,
NewFormat: DXGI_FORMAT,
SwapChainFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ResizeTarget: fn(
self: *const IDXGISwapChain,
pNewTargetParameters: ?*const DXGI_MODE_DESC,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetContainingOutput: fn(
self: *const IDXGISwapChain,
ppOutput: ?*?*IDXGIOutput,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFrameStatistics: fn(
self: *const IDXGISwapChain,
pStats: ?*DXGI_FRAME_STATISTICS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLastPresentCount: fn(
self: *const IDXGISwapChain,
pLastPresentCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIDeviceSubObject.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain_Present(self: *const T, SyncInterval: u32, Flags: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChain.VTable, self.vtable).Present(@ptrCast(*const IDXGISwapChain, self), SyncInterval, Flags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain_GetBuffer(self: *const T, Buffer: u32, riid: ?*const Guid, ppSurface: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChain.VTable, self.vtable).GetBuffer(@ptrCast(*const IDXGISwapChain, self), Buffer, riid, ppSurface);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain_SetFullscreenState(self: *const T, Fullscreen: BOOL, pTarget: ?*IDXGIOutput) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChain.VTable, self.vtable).SetFullscreenState(@ptrCast(*const IDXGISwapChain, self), Fullscreen, pTarget);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain_GetFullscreenState(self: *const T, pFullscreen: ?*BOOL, ppTarget: ?*?*IDXGIOutput) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChain.VTable, self.vtable).GetFullscreenState(@ptrCast(*const IDXGISwapChain, self), pFullscreen, ppTarget);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain_GetDesc(self: *const T, pDesc: ?*DXGI_SWAP_CHAIN_DESC) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChain.VTable, self.vtable).GetDesc(@ptrCast(*const IDXGISwapChain, self), pDesc);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain_ResizeBuffers(self: *const T, BufferCount: u32, Width: u32, Height: u32, NewFormat: DXGI_FORMAT, SwapChainFlags: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChain.VTable, self.vtable).ResizeBuffers(@ptrCast(*const IDXGISwapChain, self), BufferCount, Width, Height, NewFormat, SwapChainFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain_ResizeTarget(self: *const T, pNewTargetParameters: ?*const DXGI_MODE_DESC) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChain.VTable, self.vtable).ResizeTarget(@ptrCast(*const IDXGISwapChain, self), pNewTargetParameters);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain_GetContainingOutput(self: *const T, ppOutput: ?*?*IDXGIOutput) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChain.VTable, self.vtable).GetContainingOutput(@ptrCast(*const IDXGISwapChain, self), ppOutput);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain_GetFrameStatistics(self: *const T, pStats: ?*DXGI_FRAME_STATISTICS) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChain.VTable, self.vtable).GetFrameStatistics(@ptrCast(*const IDXGISwapChain, self), pStats);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain_GetLastPresentCount(self: *const T, pLastPresentCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChain.VTable, self.vtable).GetLastPresentCount(@ptrCast(*const IDXGISwapChain, self), pLastPresentCount);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDXGIFactory_Value = Guid.initString("7b7166ec-21c7-44ae-b21a-c9ae321ae369");
pub const IID_IDXGIFactory = &IID_IDXGIFactory_Value;
pub const IDXGIFactory = extern struct {
pub const VTable = extern struct {
base: IDXGIObject.VTable,
EnumAdapters: fn(
self: *const IDXGIFactory,
Adapter: u32,
ppAdapter: ?*?*IDXGIAdapter,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MakeWindowAssociation: fn(
self: *const IDXGIFactory,
WindowHandle: ?HWND,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetWindowAssociation: fn(
self: *const IDXGIFactory,
pWindowHandle: ?*?HWND,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateSwapChain: fn(
self: *const IDXGIFactory,
pDevice: ?*IUnknown,
pDesc: ?*DXGI_SWAP_CHAIN_DESC,
ppSwapChain: ?*?*IDXGISwapChain,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateSoftwareAdapter: fn(
self: *const IDXGIFactory,
Module: ?HINSTANCE,
ppAdapter: ?*?*IDXGIAdapter,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIObject.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIFactory_EnumAdapters(self: *const T, Adapter: u32, ppAdapter: ?*?*IDXGIAdapter) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIFactory.VTable, self.vtable).EnumAdapters(@ptrCast(*const IDXGIFactory, self), Adapter, ppAdapter);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIFactory_MakeWindowAssociation(self: *const T, WindowHandle: ?HWND, Flags: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIFactory.VTable, self.vtable).MakeWindowAssociation(@ptrCast(*const IDXGIFactory, self), WindowHandle, Flags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIFactory_GetWindowAssociation(self: *const T, pWindowHandle: ?*?HWND) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIFactory.VTable, self.vtable).GetWindowAssociation(@ptrCast(*const IDXGIFactory, self), pWindowHandle);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIFactory_CreateSwapChain(self: *const T, pDevice: ?*IUnknown, pDesc: ?*DXGI_SWAP_CHAIN_DESC, ppSwapChain: ?*?*IDXGISwapChain) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIFactory.VTable, self.vtable).CreateSwapChain(@ptrCast(*const IDXGIFactory, self), pDevice, pDesc, ppSwapChain);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIFactory_CreateSoftwareAdapter(self: *const T, Module: ?HINSTANCE, ppAdapter: ?*?*IDXGIAdapter) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIFactory.VTable, self.vtable).CreateSoftwareAdapter(@ptrCast(*const IDXGIFactory, self), Module, ppAdapter);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDXGIDevice_Value = Guid.initString("54ec77fa-1377-44e6-8c32-88fd5f44c84c");
pub const IID_IDXGIDevice = &IID_IDXGIDevice_Value;
pub const IDXGIDevice = extern struct {
pub const VTable = extern struct {
base: IDXGIObject.VTable,
GetAdapter: fn(
self: *const IDXGIDevice,
pAdapter: ?*?*IDXGIAdapter,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateSurface: fn(
self: *const IDXGIDevice,
pDesc: ?*const DXGI_SURFACE_DESC,
NumSurfaces: u32,
Usage: u32,
pSharedResource: ?*const DXGI_SHARED_RESOURCE,
ppSurface: [*]?*IDXGISurface,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryResourceResidency: fn(
self: *const IDXGIDevice,
ppResources: [*]?*IUnknown,
pResidencyStatus: [*]DXGI_RESIDENCY,
NumResources: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetGPUThreadPriority: fn(
self: *const IDXGIDevice,
Priority: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetGPUThreadPriority: fn(
self: *const IDXGIDevice,
pPriority: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIObject.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIDevice_GetAdapter(self: *const T, pAdapter: ?*?*IDXGIAdapter) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIDevice.VTable, self.vtable).GetAdapter(@ptrCast(*const IDXGIDevice, self), pAdapter);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIDevice_CreateSurface(self: *const T, pDesc: ?*const DXGI_SURFACE_DESC, NumSurfaces: u32, Usage: u32, pSharedResource: ?*const DXGI_SHARED_RESOURCE, ppSurface: [*]?*IDXGISurface) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIDevice.VTable, self.vtable).CreateSurface(@ptrCast(*const IDXGIDevice, self), pDesc, NumSurfaces, Usage, pSharedResource, ppSurface);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIDevice_QueryResourceResidency(self: *const T, ppResources: [*]?*IUnknown, pResidencyStatus: [*]DXGI_RESIDENCY, NumResources: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIDevice.VTable, self.vtable).QueryResourceResidency(@ptrCast(*const IDXGIDevice, self), ppResources, pResidencyStatus, NumResources);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIDevice_SetGPUThreadPriority(self: *const T, Priority: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIDevice.VTable, self.vtable).SetGPUThreadPriority(@ptrCast(*const IDXGIDevice, self), Priority);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIDevice_GetGPUThreadPriority(self: *const T, pPriority: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIDevice.VTable, self.vtable).GetGPUThreadPriority(@ptrCast(*const IDXGIDevice, self), pPriority);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DXGI_ADAPTER_FLAG = enum(u32) {
NONE = 0,
REMOTE = 1,
SOFTWARE = 2,
_,
pub fn initFlags(o: struct {
NONE: u1 = 0,
REMOTE: u1 = 0,
SOFTWARE: u1 = 0,
}) DXGI_ADAPTER_FLAG {
return @intToEnum(DXGI_ADAPTER_FLAG,
(if (o.NONE == 1) @enumToInt(DXGI_ADAPTER_FLAG.NONE) else 0)
| (if (o.REMOTE == 1) @enumToInt(DXGI_ADAPTER_FLAG.REMOTE) else 0)
| (if (o.SOFTWARE == 1) @enumToInt(DXGI_ADAPTER_FLAG.SOFTWARE) else 0)
);
}
};
pub const DXGI_ADAPTER_FLAG_NONE = DXGI_ADAPTER_FLAG.NONE;
pub const DXGI_ADAPTER_FLAG_REMOTE = DXGI_ADAPTER_FLAG.REMOTE;
pub const DXGI_ADAPTER_FLAG_SOFTWARE = DXGI_ADAPTER_FLAG.SOFTWARE;
pub const DXGI_ADAPTER_DESC1 = extern struct {
Description: [128]u16,
VendorId: u32,
DeviceId: u32,
SubSysId: u32,
Revision: u32,
DedicatedVideoMemory: usize,
DedicatedSystemMemory: usize,
SharedSystemMemory: usize,
AdapterLuid: LUID,
Flags: u32,
};
pub const DXGI_DISPLAY_COLOR_SPACE = extern struct {
PrimaryCoordinates: [16]f32,
WhitePoints: [32]f32,
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IDXGIFactory1_Value = Guid.initString("770aae78-f26f-4dba-a829-253c83d1b387");
pub const IID_IDXGIFactory1 = &IID_IDXGIFactory1_Value;
pub const IDXGIFactory1 = extern struct {
pub const VTable = extern struct {
base: IDXGIFactory.VTable,
EnumAdapters1: fn(
self: *const IDXGIFactory1,
Adapter: u32,
ppAdapter: ?*?*IDXGIAdapter1,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsCurrent: fn(
self: *const IDXGIFactory1,
) callconv(@import("std").os.windows.WINAPI) BOOL,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIFactory.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIFactory1_EnumAdapters1(self: *const T, Adapter: u32, ppAdapter: ?*?*IDXGIAdapter1) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIFactory1.VTable, self.vtable).EnumAdapters1(@ptrCast(*const IDXGIFactory1, self), Adapter, ppAdapter);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIFactory1_IsCurrent(self: *const T) callconv(.Inline) BOOL {
return @ptrCast(*const IDXGIFactory1.VTable, self.vtable).IsCurrent(@ptrCast(*const IDXGIFactory1, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IDXGIAdapter1_Value = Guid.initString("29038f61-3839-4626-91fd-086879011a05");
pub const IID_IDXGIAdapter1 = &IID_IDXGIAdapter1_Value;
pub const IDXGIAdapter1 = extern struct {
pub const VTable = extern struct {
base: IDXGIAdapter.VTable,
GetDesc1: fn(
self: *const IDXGIAdapter1,
pDesc: ?*DXGI_ADAPTER_DESC1,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIAdapter.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIAdapter1_GetDesc1(self: *const T, pDesc: ?*DXGI_ADAPTER_DESC1) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIAdapter1.VTable, self.vtable).GetDesc1(@ptrCast(*const IDXGIAdapter1, self), pDesc);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IDXGIDevice1_Value = Guid.initString("77db970f-6276-48ba-ba28-070143b4392c");
pub const IID_IDXGIDevice1 = &IID_IDXGIDevice1_Value;
pub const IDXGIDevice1 = extern struct {
pub const VTable = extern struct {
base: IDXGIDevice.VTable,
SetMaximumFrameLatency: fn(
self: *const IDXGIDevice1,
MaxLatency: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetMaximumFrameLatency: fn(
self: *const IDXGIDevice1,
pMaxLatency: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIDevice.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIDevice1_SetMaximumFrameLatency(self: *const T, MaxLatency: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIDevice1.VTable, self.vtable).SetMaximumFrameLatency(@ptrCast(*const IDXGIDevice1, self), MaxLatency);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIDevice1_GetMaximumFrameLatency(self: *const T, pMaxLatency: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIDevice1.VTable, self.vtable).GetMaximumFrameLatency(@ptrCast(*const IDXGIDevice1, self), pMaxLatency);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IDXGIDisplayControl_Value = Guid.initString("ea9dbf1a-c88e-4486-854a-98aa0138f30c");
pub const IID_IDXGIDisplayControl = &IID_IDXGIDisplayControl_Value;
pub const IDXGIDisplayControl = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
IsStereoEnabled: fn(
self: *const IDXGIDisplayControl,
) callconv(@import("std").os.windows.WINAPI) BOOL,
SetStereoEnabled: fn(
self: *const IDXGIDisplayControl,
enabled: BOOL,
) callconv(@import("std").os.windows.WINAPI) void,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIDisplayControl_IsStereoEnabled(self: *const T) callconv(.Inline) BOOL {
return @ptrCast(*const IDXGIDisplayControl.VTable, self.vtable).IsStereoEnabled(@ptrCast(*const IDXGIDisplayControl, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIDisplayControl_SetStereoEnabled(self: *const T, enabled: BOOL) callconv(.Inline) void {
return @ptrCast(*const IDXGIDisplayControl.VTable, self.vtable).SetStereoEnabled(@ptrCast(*const IDXGIDisplayControl, self), enabled);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DXGI_OUTDUPL_MOVE_RECT = extern struct {
SourcePoint: POINT,
DestinationRect: RECT,
};
pub const DXGI_OUTDUPL_DESC = extern struct {
ModeDesc: DXGI_MODE_DESC,
Rotation: DXGI_MODE_ROTATION,
DesktopImageInSystemMemory: BOOL,
};
pub const DXGI_OUTDUPL_POINTER_POSITION = extern struct {
Position: POINT,
Visible: BOOL,
};
pub const DXGI_OUTDUPL_POINTER_SHAPE_TYPE = enum(i32) {
MONOCHROME = 1,
COLOR = 2,
MASKED_COLOR = 4,
};
pub const DXGI_OUTDUPL_POINTER_SHAPE_TYPE_MONOCHROME = DXGI_OUTDUPL_POINTER_SHAPE_TYPE.MONOCHROME;
pub const DXGI_OUTDUPL_POINTER_SHAPE_TYPE_COLOR = DXGI_OUTDUPL_POINTER_SHAPE_TYPE.COLOR;
pub const DXGI_OUTDUPL_POINTER_SHAPE_TYPE_MASKED_COLOR = DXGI_OUTDUPL_POINTER_SHAPE_TYPE.MASKED_COLOR;
pub const DXGI_OUTDUPL_POINTER_SHAPE_INFO = extern struct {
Type: u32,
Width: u32,
Height: u32,
Pitch: u32,
HotSpot: POINT,
};
pub const DXGI_OUTDUPL_FRAME_INFO = extern struct {
LastPresentTime: LARGE_INTEGER,
LastMouseUpdateTime: LARGE_INTEGER,
AccumulatedFrames: u32,
RectsCoalesced: BOOL,
ProtectedContentMaskedOut: BOOL,
PointerPosition: DXGI_OUTDUPL_POINTER_POSITION,
TotalMetadataBufferSize: u32,
PointerShapeBufferSize: u32,
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IDXGIOutputDuplication_Value = Guid.initString("191cfac3-a341-470d-b26e-a864f428319c");
pub const IID_IDXGIOutputDuplication = &IID_IDXGIOutputDuplication_Value;
pub const IDXGIOutputDuplication = extern struct {
pub const VTable = extern struct {
base: IDXGIObject.VTable,
GetDesc: fn(
self: *const IDXGIOutputDuplication,
pDesc: ?*DXGI_OUTDUPL_DESC,
) callconv(@import("std").os.windows.WINAPI) void,
AcquireNextFrame: fn(
self: *const IDXGIOutputDuplication,
TimeoutInMilliseconds: u32,
pFrameInfo: ?*DXGI_OUTDUPL_FRAME_INFO,
ppDesktopResource: ?*?*IDXGIResource,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFrameDirtyRects: fn(
self: *const IDXGIOutputDuplication,
DirtyRectsBufferSize: u32,
// TODO: what to do with BytesParamIndex 0?
pDirtyRectsBuffer: ?*RECT,
pDirtyRectsBufferSizeRequired: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFrameMoveRects: fn(
self: *const IDXGIOutputDuplication,
MoveRectsBufferSize: u32,
// TODO: what to do with BytesParamIndex 0?
pMoveRectBuffer: ?*DXGI_OUTDUPL_MOVE_RECT,
pMoveRectsBufferSizeRequired: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFramePointerShape: fn(
self: *const IDXGIOutputDuplication,
PointerShapeBufferSize: u32,
// TODO: what to do with BytesParamIndex 0?
pPointerShapeBuffer: ?*anyopaque,
pPointerShapeBufferSizeRequired: ?*u32,
pPointerShapeInfo: ?*DXGI_OUTDUPL_POINTER_SHAPE_INFO,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MapDesktopSurface: fn(
self: *const IDXGIOutputDuplication,
pLockedRect: ?*DXGI_MAPPED_RECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UnMapDesktopSurface: fn(
self: *const IDXGIOutputDuplication,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ReleaseFrame: fn(
self: *const IDXGIOutputDuplication,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIObject.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIOutputDuplication_GetDesc(self: *const T, pDesc: ?*DXGI_OUTDUPL_DESC) callconv(.Inline) void {
return @ptrCast(*const IDXGIOutputDuplication.VTable, self.vtable).GetDesc(@ptrCast(*const IDXGIOutputDuplication, self), pDesc);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIOutputDuplication_AcquireNextFrame(self: *const T, TimeoutInMilliseconds: u32, pFrameInfo: ?*DXGI_OUTDUPL_FRAME_INFO, ppDesktopResource: ?*?*IDXGIResource) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIOutputDuplication.VTable, self.vtable).AcquireNextFrame(@ptrCast(*const IDXGIOutputDuplication, self), TimeoutInMilliseconds, pFrameInfo, ppDesktopResource);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIOutputDuplication_GetFrameDirtyRects(self: *const T, DirtyRectsBufferSize: u32, pDirtyRectsBuffer: ?*RECT, pDirtyRectsBufferSizeRequired: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIOutputDuplication.VTable, self.vtable).GetFrameDirtyRects(@ptrCast(*const IDXGIOutputDuplication, self), DirtyRectsBufferSize, pDirtyRectsBuffer, pDirtyRectsBufferSizeRequired);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIOutputDuplication_GetFrameMoveRects(self: *const T, MoveRectsBufferSize: u32, pMoveRectBuffer: ?*DXGI_OUTDUPL_MOVE_RECT, pMoveRectsBufferSizeRequired: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIOutputDuplication.VTable, self.vtable).GetFrameMoveRects(@ptrCast(*const IDXGIOutputDuplication, self), MoveRectsBufferSize, pMoveRectBuffer, pMoveRectsBufferSizeRequired);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIOutputDuplication_GetFramePointerShape(self: *const T, PointerShapeBufferSize: u32, pPointerShapeBuffer: ?*anyopaque, pPointerShapeBufferSizeRequired: ?*u32, pPointerShapeInfo: ?*DXGI_OUTDUPL_POINTER_SHAPE_INFO) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIOutputDuplication.VTable, self.vtable).GetFramePointerShape(@ptrCast(*const IDXGIOutputDuplication, self), PointerShapeBufferSize, pPointerShapeBuffer, pPointerShapeBufferSizeRequired, pPointerShapeInfo);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIOutputDuplication_MapDesktopSurface(self: *const T, pLockedRect: ?*DXGI_MAPPED_RECT) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIOutputDuplication.VTable, self.vtable).MapDesktopSurface(@ptrCast(*const IDXGIOutputDuplication, self), pLockedRect);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIOutputDuplication_UnMapDesktopSurface(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIOutputDuplication.VTable, self.vtable).UnMapDesktopSurface(@ptrCast(*const IDXGIOutputDuplication, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIOutputDuplication_ReleaseFrame(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIOutputDuplication.VTable, self.vtable).ReleaseFrame(@ptrCast(*const IDXGIOutputDuplication, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IDXGISurface2_Value = Guid.initString("aba496dd-b617-4cb8-a866-bc44d7eb1fa2");
pub const IID_IDXGISurface2 = &IID_IDXGISurface2_Value;
pub const IDXGISurface2 = extern struct {
pub const VTable = extern struct {
base: IDXGISurface1.VTable,
GetResource: fn(
self: *const IDXGISurface2,
riid: ?*const Guid,
ppParentResource: ?*?*anyopaque,
pSubresourceIndex: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGISurface1.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISurface2_GetResource(self: *const T, riid: ?*const Guid, ppParentResource: ?*?*anyopaque, pSubresourceIndex: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISurface2.VTable, self.vtable).GetResource(@ptrCast(*const IDXGISurface2, self), riid, ppParentResource, pSubresourceIndex);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IDXGIResource1_Value = Guid.initString("30961379-4609-4a41-998e-54fe567ee0c1");
pub const IID_IDXGIResource1 = &IID_IDXGIResource1_Value;
pub const IDXGIResource1 = extern struct {
pub const VTable = extern struct {
base: IDXGIResource.VTable,
CreateSubresourceSurface: fn(
self: *const IDXGIResource1,
index: u32,
ppSurface: ?*?*IDXGISurface2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateSharedHandle: fn(
self: *const IDXGIResource1,
pAttributes: ?*const SECURITY_ATTRIBUTES,
dwAccess: u32,
lpName: ?[*:0]const u16,
pHandle: ?*?HANDLE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIResource.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIResource1_CreateSubresourceSurface(self: *const T, index: u32, ppSurface: ?*?*IDXGISurface2) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIResource1.VTable, self.vtable).CreateSubresourceSurface(@ptrCast(*const IDXGIResource1, self), index, ppSurface);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIResource1_CreateSharedHandle(self: *const T, pAttributes: ?*const SECURITY_ATTRIBUTES, dwAccess: u32, lpName: ?[*:0]const u16, pHandle: ?*?HANDLE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIResource1.VTable, self.vtable).CreateSharedHandle(@ptrCast(*const IDXGIResource1, self), pAttributes, dwAccess, lpName, pHandle);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DXGI_OFFER_RESOURCE_PRIORITY = enum(i32) {
LOW = 1,
NORMAL = 2,
HIGH = 3,
};
pub const DXGI_OFFER_RESOURCE_PRIORITY_LOW = DXGI_OFFER_RESOURCE_PRIORITY.LOW;
pub const DXGI_OFFER_RESOURCE_PRIORITY_NORMAL = DXGI_OFFER_RESOURCE_PRIORITY.NORMAL;
pub const DXGI_OFFER_RESOURCE_PRIORITY_HIGH = DXGI_OFFER_RESOURCE_PRIORITY.HIGH;
// TODO: this type is limited to platform 'windows8.0'
const IID_IDXGIDevice2_Value = Guid.initString("05008617-fbfd-4051-a790-144884b4f6a9");
pub const IID_IDXGIDevice2 = &IID_IDXGIDevice2_Value;
pub const IDXGIDevice2 = extern struct {
pub const VTable = extern struct {
base: IDXGIDevice1.VTable,
OfferResources: fn(
self: *const IDXGIDevice2,
NumResources: u32,
ppResources: [*]?*IDXGIResource,
Priority: DXGI_OFFER_RESOURCE_PRIORITY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ReclaimResources: fn(
self: *const IDXGIDevice2,
NumResources: u32,
ppResources: [*]?*IDXGIResource,
pDiscarded: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EnqueueSetEvent: fn(
self: *const IDXGIDevice2,
hEvent: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIDevice1.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIDevice2_OfferResources(self: *const T, NumResources: u32, ppResources: [*]?*IDXGIResource, Priority: DXGI_OFFER_RESOURCE_PRIORITY) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIDevice2.VTable, self.vtable).OfferResources(@ptrCast(*const IDXGIDevice2, self), NumResources, ppResources, Priority);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIDevice2_ReclaimResources(self: *const T, NumResources: u32, ppResources: [*]?*IDXGIResource, pDiscarded: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIDevice2.VTable, self.vtable).ReclaimResources(@ptrCast(*const IDXGIDevice2, self), NumResources, ppResources, pDiscarded);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIDevice2_EnqueueSetEvent(self: *const T, hEvent: ?HANDLE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIDevice2.VTable, self.vtable).EnqueueSetEvent(@ptrCast(*const IDXGIDevice2, self), hEvent);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DXGI_MODE_DESC1 = extern struct {
Width: u32,
Height: u32,
RefreshRate: DXGI_RATIONAL,
Format: DXGI_FORMAT,
ScanlineOrdering: DXGI_MODE_SCANLINE_ORDER,
Scaling: DXGI_MODE_SCALING,
Stereo: BOOL,
};
pub const DXGI_SCALING = enum(i32) {
STRETCH = 0,
NONE = 1,
ASPECT_RATIO_STRETCH = 2,
};
pub const DXGI_SCALING_STRETCH = DXGI_SCALING.STRETCH;
pub const DXGI_SCALING_NONE = DXGI_SCALING.NONE;
pub const DXGI_SCALING_ASPECT_RATIO_STRETCH = DXGI_SCALING.ASPECT_RATIO_STRETCH;
pub const DXGI_SWAP_CHAIN_DESC1 = extern struct {
Width: u32,
Height: u32,
Format: DXGI_FORMAT,
Stereo: BOOL,
SampleDesc: DXGI_SAMPLE_DESC,
BufferUsage: u32,
BufferCount: u32,
Scaling: DXGI_SCALING,
SwapEffect: DXGI_SWAP_EFFECT,
AlphaMode: DXGI_ALPHA_MODE,
Flags: u32,
};
pub const DXGI_SWAP_CHAIN_FULLSCREEN_DESC = extern struct {
RefreshRate: DXGI_RATIONAL,
ScanlineOrdering: DXGI_MODE_SCANLINE_ORDER,
Scaling: DXGI_MODE_SCALING,
Windowed: BOOL,
};
pub const DXGI_PRESENT_PARAMETERS = extern struct {
DirtyRectsCount: u32,
pDirtyRects: ?*RECT,
pScrollRect: ?*RECT,
pScrollOffset: ?*POINT,
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IDXGISwapChain1_Value = Guid.initString("790a45f7-0d42-4876-983a-0a55cfe6f4aa");
pub const IID_IDXGISwapChain1 = &IID_IDXGISwapChain1_Value;
pub const IDXGISwapChain1 = extern struct {
pub const VTable = extern struct {
base: IDXGISwapChain.VTable,
GetDesc1: fn(
self: *const IDXGISwapChain1,
pDesc: ?*DXGI_SWAP_CHAIN_DESC1,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFullscreenDesc: fn(
self: *const IDXGISwapChain1,
pDesc: ?*DXGI_SWAP_CHAIN_FULLSCREEN_DESC,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetHwnd: fn(
self: *const IDXGISwapChain1,
pHwnd: ?*?HWND,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCoreWindow: fn(
self: *const IDXGISwapChain1,
refiid: ?*const Guid,
ppUnk: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Present1: fn(
self: *const IDXGISwapChain1,
SyncInterval: u32,
PresentFlags: u32,
pPresentParameters: ?*const DXGI_PRESENT_PARAMETERS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsTemporaryMonoSupported: fn(
self: *const IDXGISwapChain1,
) callconv(@import("std").os.windows.WINAPI) BOOL,
GetRestrictToOutput: fn(
self: *const IDXGISwapChain1,
ppRestrictToOutput: ?*?*IDXGIOutput,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetBackgroundColor: fn(
self: *const IDXGISwapChain1,
pColor: ?*const DXGI_RGBA,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetBackgroundColor: fn(
self: *const IDXGISwapChain1,
pColor: ?*DXGI_RGBA,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetRotation: fn(
self: *const IDXGISwapChain1,
Rotation: DXGI_MODE_ROTATION,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetRotation: fn(
self: *const IDXGISwapChain1,
pRotation: ?*DXGI_MODE_ROTATION,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGISwapChain.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain1_GetDesc1(self: *const T, pDesc: ?*DXGI_SWAP_CHAIN_DESC1) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChain1.VTable, self.vtable).GetDesc1(@ptrCast(*const IDXGISwapChain1, self), pDesc);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain1_GetFullscreenDesc(self: *const T, pDesc: ?*DXGI_SWAP_CHAIN_FULLSCREEN_DESC) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChain1.VTable, self.vtable).GetFullscreenDesc(@ptrCast(*const IDXGISwapChain1, self), pDesc);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain1_GetHwnd(self: *const T, pHwnd: ?*?HWND) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChain1.VTable, self.vtable).GetHwnd(@ptrCast(*const IDXGISwapChain1, self), pHwnd);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain1_GetCoreWindow(self: *const T, refiid: ?*const Guid, ppUnk: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChain1.VTable, self.vtable).GetCoreWindow(@ptrCast(*const IDXGISwapChain1, self), refiid, ppUnk);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain1_Present1(self: *const T, SyncInterval: u32, PresentFlags: u32, pPresentParameters: ?*const DXGI_PRESENT_PARAMETERS) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChain1.VTable, self.vtable).Present1(@ptrCast(*const IDXGISwapChain1, self), SyncInterval, PresentFlags, pPresentParameters);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain1_IsTemporaryMonoSupported(self: *const T) callconv(.Inline) BOOL {
return @ptrCast(*const IDXGISwapChain1.VTable, self.vtable).IsTemporaryMonoSupported(@ptrCast(*const IDXGISwapChain1, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain1_GetRestrictToOutput(self: *const T, ppRestrictToOutput: ?*?*IDXGIOutput) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChain1.VTable, self.vtable).GetRestrictToOutput(@ptrCast(*const IDXGISwapChain1, self), ppRestrictToOutput);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain1_SetBackgroundColor(self: *const T, pColor: ?*const DXGI_RGBA) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChain1.VTable, self.vtable).SetBackgroundColor(@ptrCast(*const IDXGISwapChain1, self), pColor);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain1_GetBackgroundColor(self: *const T, pColor: ?*DXGI_RGBA) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChain1.VTable, self.vtable).GetBackgroundColor(@ptrCast(*const IDXGISwapChain1, self), pColor);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain1_SetRotation(self: *const T, Rotation: DXGI_MODE_ROTATION) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChain1.VTable, self.vtable).SetRotation(@ptrCast(*const IDXGISwapChain1, self), Rotation);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain1_GetRotation(self: *const T, pRotation: ?*DXGI_MODE_ROTATION) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChain1.VTable, self.vtable).GetRotation(@ptrCast(*const IDXGISwapChain1, self), pRotation);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IDXGIFactory2_Value = Guid.initString("50c83a1c-e072-4c48-87b0-3630fa36a6d0");
pub const IID_IDXGIFactory2 = &IID_IDXGIFactory2_Value;
pub const IDXGIFactory2 = extern struct {
pub const VTable = extern struct {
base: IDXGIFactory1.VTable,
IsWindowedStereoEnabled: fn(
self: *const IDXGIFactory2,
) callconv(@import("std").os.windows.WINAPI) BOOL,
CreateSwapChainForHwnd: fn(
self: *const IDXGIFactory2,
pDevice: ?*IUnknown,
hWnd: ?HWND,
pDesc: ?*const DXGI_SWAP_CHAIN_DESC1,
pFullscreenDesc: ?*const DXGI_SWAP_CHAIN_FULLSCREEN_DESC,
pRestrictToOutput: ?*IDXGIOutput,
ppSwapChain: ?*?*IDXGISwapChain1,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateSwapChainForCoreWindow: fn(
self: *const IDXGIFactory2,
pDevice: ?*IUnknown,
pWindow: ?*IUnknown,
pDesc: ?*const DXGI_SWAP_CHAIN_DESC1,
pRestrictToOutput: ?*IDXGIOutput,
ppSwapChain: ?*?*IDXGISwapChain1,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSharedResourceAdapterLuid: fn(
self: *const IDXGIFactory2,
hResource: ?HANDLE,
pLuid: ?*LUID,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RegisterStereoStatusWindow: fn(
self: *const IDXGIFactory2,
WindowHandle: ?HWND,
wMsg: u32,
pdwCookie: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RegisterStereoStatusEvent: fn(
self: *const IDXGIFactory2,
hEvent: ?HANDLE,
pdwCookie: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UnregisterStereoStatus: fn(
self: *const IDXGIFactory2,
dwCookie: u32,
) callconv(@import("std").os.windows.WINAPI) void,
RegisterOcclusionStatusWindow: fn(
self: *const IDXGIFactory2,
WindowHandle: ?HWND,
wMsg: u32,
pdwCookie: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RegisterOcclusionStatusEvent: fn(
self: *const IDXGIFactory2,
hEvent: ?HANDLE,
pdwCookie: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UnregisterOcclusionStatus: fn(
self: *const IDXGIFactory2,
dwCookie: u32,
) callconv(@import("std").os.windows.WINAPI) void,
CreateSwapChainForComposition: fn(
self: *const IDXGIFactory2,
pDevice: ?*IUnknown,
pDesc: ?*const DXGI_SWAP_CHAIN_DESC1,
pRestrictToOutput: ?*IDXGIOutput,
ppSwapChain: ?*?*IDXGISwapChain1,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIFactory1.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIFactory2_IsWindowedStereoEnabled(self: *const T) callconv(.Inline) BOOL {
return @ptrCast(*const IDXGIFactory2.VTable, self.vtable).IsWindowedStereoEnabled(@ptrCast(*const IDXGIFactory2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIFactory2_CreateSwapChainForHwnd(self: *const T, pDevice: ?*IUnknown, hWnd: ?HWND, pDesc: ?*const DXGI_SWAP_CHAIN_DESC1, pFullscreenDesc: ?*const DXGI_SWAP_CHAIN_FULLSCREEN_DESC, pRestrictToOutput: ?*IDXGIOutput, ppSwapChain: ?*?*IDXGISwapChain1) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIFactory2.VTable, self.vtable).CreateSwapChainForHwnd(@ptrCast(*const IDXGIFactory2, self), pDevice, hWnd, pDesc, pFullscreenDesc, pRestrictToOutput, ppSwapChain);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIFactory2_CreateSwapChainForCoreWindow(self: *const T, pDevice: ?*IUnknown, pWindow: ?*IUnknown, pDesc: ?*const DXGI_SWAP_CHAIN_DESC1, pRestrictToOutput: ?*IDXGIOutput, ppSwapChain: ?*?*IDXGISwapChain1) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIFactory2.VTable, self.vtable).CreateSwapChainForCoreWindow(@ptrCast(*const IDXGIFactory2, self), pDevice, pWindow, pDesc, pRestrictToOutput, ppSwapChain);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIFactory2_GetSharedResourceAdapterLuid(self: *const T, hResource: ?HANDLE, pLuid: ?*LUID) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIFactory2.VTable, self.vtable).GetSharedResourceAdapterLuid(@ptrCast(*const IDXGIFactory2, self), hResource, pLuid);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIFactory2_RegisterStereoStatusWindow(self: *const T, WindowHandle: ?HWND, wMsg: u32, pdwCookie: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIFactory2.VTable, self.vtable).RegisterStereoStatusWindow(@ptrCast(*const IDXGIFactory2, self), WindowHandle, wMsg, pdwCookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIFactory2_RegisterStereoStatusEvent(self: *const T, hEvent: ?HANDLE, pdwCookie: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIFactory2.VTable, self.vtable).RegisterStereoStatusEvent(@ptrCast(*const IDXGIFactory2, self), hEvent, pdwCookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIFactory2_UnregisterStereoStatus(self: *const T, dwCookie: u32) callconv(.Inline) void {
return @ptrCast(*const IDXGIFactory2.VTable, self.vtable).UnregisterStereoStatus(@ptrCast(*const IDXGIFactory2, self), dwCookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIFactory2_RegisterOcclusionStatusWindow(self: *const T, WindowHandle: ?HWND, wMsg: u32, pdwCookie: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIFactory2.VTable, self.vtable).RegisterOcclusionStatusWindow(@ptrCast(*const IDXGIFactory2, self), WindowHandle, wMsg, pdwCookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIFactory2_RegisterOcclusionStatusEvent(self: *const T, hEvent: ?HANDLE, pdwCookie: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIFactory2.VTable, self.vtable).RegisterOcclusionStatusEvent(@ptrCast(*const IDXGIFactory2, self), hEvent, pdwCookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIFactory2_UnregisterOcclusionStatus(self: *const T, dwCookie: u32) callconv(.Inline) void {
return @ptrCast(*const IDXGIFactory2.VTable, self.vtable).UnregisterOcclusionStatus(@ptrCast(*const IDXGIFactory2, self), dwCookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIFactory2_CreateSwapChainForComposition(self: *const T, pDevice: ?*IUnknown, pDesc: ?*const DXGI_SWAP_CHAIN_DESC1, pRestrictToOutput: ?*IDXGIOutput, ppSwapChain: ?*?*IDXGISwapChain1) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIFactory2.VTable, self.vtable).CreateSwapChainForComposition(@ptrCast(*const IDXGIFactory2, self), pDevice, pDesc, pRestrictToOutput, ppSwapChain);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DXGI_GRAPHICS_PREEMPTION_GRANULARITY = enum(i32) {
DMA_BUFFER_BOUNDARY = 0,
PRIMITIVE_BOUNDARY = 1,
TRIANGLE_BOUNDARY = 2,
PIXEL_BOUNDARY = 3,
INSTRUCTION_BOUNDARY = 4,
};
pub const DXGI_GRAPHICS_PREEMPTION_DMA_BUFFER_BOUNDARY = DXGI_GRAPHICS_PREEMPTION_GRANULARITY.DMA_BUFFER_BOUNDARY;
pub const DXGI_GRAPHICS_PREEMPTION_PRIMITIVE_BOUNDARY = DXGI_GRAPHICS_PREEMPTION_GRANULARITY.PRIMITIVE_BOUNDARY;
pub const DXGI_GRAPHICS_PREEMPTION_TRIANGLE_BOUNDARY = DXGI_GRAPHICS_PREEMPTION_GRANULARITY.TRIANGLE_BOUNDARY;
pub const DXGI_GRAPHICS_PREEMPTION_PIXEL_BOUNDARY = DXGI_GRAPHICS_PREEMPTION_GRANULARITY.PIXEL_BOUNDARY;
pub const DXGI_GRAPHICS_PREEMPTION_INSTRUCTION_BOUNDARY = DXGI_GRAPHICS_PREEMPTION_GRANULARITY.INSTRUCTION_BOUNDARY;
pub const DXGI_COMPUTE_PREEMPTION_GRANULARITY = enum(i32) {
DMA_BUFFER_BOUNDARY = 0,
DISPATCH_BOUNDARY = 1,
THREAD_GROUP_BOUNDARY = 2,
THREAD_BOUNDARY = 3,
INSTRUCTION_BOUNDARY = 4,
};
pub const DXGI_COMPUTE_PREEMPTION_DMA_BUFFER_BOUNDARY = DXGI_COMPUTE_PREEMPTION_GRANULARITY.DMA_BUFFER_BOUNDARY;
pub const DXGI_COMPUTE_PREEMPTION_DISPATCH_BOUNDARY = DXGI_COMPUTE_PREEMPTION_GRANULARITY.DISPATCH_BOUNDARY;
pub const DXGI_COMPUTE_PREEMPTION_THREAD_GROUP_BOUNDARY = DXGI_COMPUTE_PREEMPTION_GRANULARITY.THREAD_GROUP_BOUNDARY;
pub const DXGI_COMPUTE_PREEMPTION_THREAD_BOUNDARY = DXGI_COMPUTE_PREEMPTION_GRANULARITY.THREAD_BOUNDARY;
pub const DXGI_COMPUTE_PREEMPTION_INSTRUCTION_BOUNDARY = DXGI_COMPUTE_PREEMPTION_GRANULARITY.INSTRUCTION_BOUNDARY;
pub const DXGI_ADAPTER_DESC2 = extern struct {
Description: [128]u16,
VendorId: u32,
DeviceId: u32,
SubSysId: u32,
Revision: u32,
DedicatedVideoMemory: usize,
DedicatedSystemMemory: usize,
SharedSystemMemory: usize,
AdapterLuid: LUID,
Flags: u32,
GraphicsPreemptionGranularity: DXGI_GRAPHICS_PREEMPTION_GRANULARITY,
ComputePreemptionGranularity: DXGI_COMPUTE_PREEMPTION_GRANULARITY,
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IDXGIAdapter2_Value = Guid.initString("0aa1ae0a-fa0e-4b84-8644-e05ff8e5acb5");
pub const IID_IDXGIAdapter2 = &IID_IDXGIAdapter2_Value;
pub const IDXGIAdapter2 = extern struct {
pub const VTable = extern struct {
base: IDXGIAdapter1.VTable,
GetDesc2: fn(
self: *const IDXGIAdapter2,
pDesc: ?*DXGI_ADAPTER_DESC2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIAdapter1.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIAdapter2_GetDesc2(self: *const T, pDesc: ?*DXGI_ADAPTER_DESC2) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIAdapter2.VTable, self.vtable).GetDesc2(@ptrCast(*const IDXGIAdapter2, self), pDesc);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IDXGIOutput1_Value = Guid.initString("00cddea8-939b-4b83-a340-a685226666cc");
pub const IID_IDXGIOutput1 = &IID_IDXGIOutput1_Value;
pub const IDXGIOutput1 = extern struct {
pub const VTable = extern struct {
base: IDXGIOutput.VTable,
GetDisplayModeList1: fn(
self: *const IDXGIOutput1,
EnumFormat: DXGI_FORMAT,
Flags: u32,
pNumModes: ?*u32,
pDesc: ?[*]DXGI_MODE_DESC1,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FindClosestMatchingMode1: fn(
self: *const IDXGIOutput1,
pModeToMatch: ?*const DXGI_MODE_DESC1,
pClosestMatch: ?*DXGI_MODE_DESC1,
pConcernedDevice: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDisplaySurfaceData1: fn(
self: *const IDXGIOutput1,
pDestination: ?*IDXGIResource,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DuplicateOutput: fn(
self: *const IDXGIOutput1,
pDevice: ?*IUnknown,
ppOutputDuplication: ?*?*IDXGIOutputDuplication,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIOutput.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIOutput1_GetDisplayModeList1(self: *const T, EnumFormat: DXGI_FORMAT, Flags: u32, pNumModes: ?*u32, pDesc: ?[*]DXGI_MODE_DESC1) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIOutput1.VTable, self.vtable).GetDisplayModeList1(@ptrCast(*const IDXGIOutput1, self), EnumFormat, Flags, pNumModes, pDesc);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIOutput1_FindClosestMatchingMode1(self: *const T, pModeToMatch: ?*const DXGI_MODE_DESC1, pClosestMatch: ?*DXGI_MODE_DESC1, pConcernedDevice: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIOutput1.VTable, self.vtable).FindClosestMatchingMode1(@ptrCast(*const IDXGIOutput1, self), pModeToMatch, pClosestMatch, pConcernedDevice);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIOutput1_GetDisplaySurfaceData1(self: *const T, pDestination: ?*IDXGIResource) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIOutput1.VTable, self.vtable).GetDisplaySurfaceData1(@ptrCast(*const IDXGIOutput1, self), pDestination);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIOutput1_DuplicateOutput(self: *const T, pDevice: ?*IUnknown, ppOutputDuplication: ?*?*IDXGIOutputDuplication) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIOutput1.VTable, self.vtable).DuplicateOutput(@ptrCast(*const IDXGIOutput1, self), pDevice, ppOutputDuplication);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.1'
const IID_IDXGIDevice3_Value = Guid.initString("6007896c-3244-4afd-bf18-a6d3beda5023");
pub const IID_IDXGIDevice3 = &IID_IDXGIDevice3_Value;
pub const IDXGIDevice3 = extern struct {
pub const VTable = extern struct {
base: IDXGIDevice2.VTable,
Trim: fn(
self: *const IDXGIDevice3,
) callconv(@import("std").os.windows.WINAPI) void,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIDevice2.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIDevice3_Trim(self: *const T) callconv(.Inline) void {
return @ptrCast(*const IDXGIDevice3.VTable, self.vtable).Trim(@ptrCast(*const IDXGIDevice3, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DXGI_MATRIX_3X2_F = extern struct {
_11: f32,
_12: f32,
_21: f32,
_22: f32,
_31: f32,
_32: f32,
};
// TODO: this type is limited to platform 'windows8.1'
const IID_IDXGISwapChain2_Value = Guid.initString("a8be2ac4-199f-4946-b331-79599fb98de7");
pub const IID_IDXGISwapChain2 = &IID_IDXGISwapChain2_Value;
pub const IDXGISwapChain2 = extern struct {
pub const VTable = extern struct {
base: IDXGISwapChain1.VTable,
SetSourceSize: fn(
self: *const IDXGISwapChain2,
Width: u32,
Height: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSourceSize: fn(
self: *const IDXGISwapChain2,
pWidth: ?*u32,
pHeight: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetMaximumFrameLatency: fn(
self: *const IDXGISwapChain2,
MaxLatency: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetMaximumFrameLatency: fn(
self: *const IDXGISwapChain2,
pMaxLatency: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFrameLatencyWaitableObject: fn(
self: *const IDXGISwapChain2,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE,
SetMatrixTransform: fn(
self: *const IDXGISwapChain2,
pMatrix: ?*const DXGI_MATRIX_3X2_F,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetMatrixTransform: fn(
self: *const IDXGISwapChain2,
pMatrix: ?*DXGI_MATRIX_3X2_F,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGISwapChain1.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain2_SetSourceSize(self: *const T, Width: u32, Height: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChain2.VTable, self.vtable).SetSourceSize(@ptrCast(*const IDXGISwapChain2, self), Width, Height);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain2_GetSourceSize(self: *const T, pWidth: ?*u32, pHeight: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChain2.VTable, self.vtable).GetSourceSize(@ptrCast(*const IDXGISwapChain2, self), pWidth, pHeight);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain2_SetMaximumFrameLatency(self: *const T, MaxLatency: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChain2.VTable, self.vtable).SetMaximumFrameLatency(@ptrCast(*const IDXGISwapChain2, self), MaxLatency);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain2_GetMaximumFrameLatency(self: *const T, pMaxLatency: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChain2.VTable, self.vtable).GetMaximumFrameLatency(@ptrCast(*const IDXGISwapChain2, self), pMaxLatency);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain2_GetFrameLatencyWaitableObject(self: *const T) callconv(.Inline) ?HANDLE {
return @ptrCast(*const IDXGISwapChain2.VTable, self.vtable).GetFrameLatencyWaitableObject(@ptrCast(*const IDXGISwapChain2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain2_SetMatrixTransform(self: *const T, pMatrix: ?*const DXGI_MATRIX_3X2_F) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChain2.VTable, self.vtable).SetMatrixTransform(@ptrCast(*const IDXGISwapChain2, self), pMatrix);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain2_GetMatrixTransform(self: *const T, pMatrix: ?*DXGI_MATRIX_3X2_F) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChain2.VTable, self.vtable).GetMatrixTransform(@ptrCast(*const IDXGISwapChain2, self), pMatrix);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.1'
const IID_IDXGIOutput2_Value = Guid.initString("595e39d1-2724-4663-99b1-da969de28364");
pub const IID_IDXGIOutput2 = &IID_IDXGIOutput2_Value;
pub const IDXGIOutput2 = extern struct {
pub const VTable = extern struct {
base: IDXGIOutput1.VTable,
SupportsOverlays: fn(
self: *const IDXGIOutput2,
) callconv(@import("std").os.windows.WINAPI) BOOL,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIOutput1.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIOutput2_SupportsOverlays(self: *const T) callconv(.Inline) BOOL {
return @ptrCast(*const IDXGIOutput2.VTable, self.vtable).SupportsOverlays(@ptrCast(*const IDXGIOutput2, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.1'
const IID_IDXGIFactory3_Value = Guid.initString("25483823-cd46-4c7d-86ca-47aa95b837bd");
pub const IID_IDXGIFactory3 = &IID_IDXGIFactory3_Value;
pub const IDXGIFactory3 = extern struct {
pub const VTable = extern struct {
base: IDXGIFactory2.VTable,
GetCreationFlags: fn(
self: *const IDXGIFactory3,
) callconv(@import("std").os.windows.WINAPI) u32,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIFactory2.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIFactory3_GetCreationFlags(self: *const T) callconv(.Inline) u32 {
return @ptrCast(*const IDXGIFactory3.VTable, self.vtable).GetCreationFlags(@ptrCast(*const IDXGIFactory3, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DXGI_DECODE_SWAP_CHAIN_DESC = extern struct {
Flags: u32,
};
pub const DXGI_MULTIPLANE_OVERLAY_YCbCr_FLAGS = enum(i32) {
NOMINAL_RANGE = 1,
BT709 = 2,
xvYCC = 4,
};
pub const DXGI_MULTIPLANE_OVERLAY_YCbCr_FLAG_NOMINAL_RANGE = DXGI_MULTIPLANE_OVERLAY_YCbCr_FLAGS.NOMINAL_RANGE;
pub const DXGI_MULTIPLANE_OVERLAY_YCbCr_FLAG_BT709 = DXGI_MULTIPLANE_OVERLAY_YCbCr_FLAGS.BT709;
pub const DXGI_MULTIPLANE_OVERLAY_YCbCr_FLAG_xvYCC = DXGI_MULTIPLANE_OVERLAY_YCbCr_FLAGS.xvYCC;
// TODO: this type is limited to platform 'windows8.1'
const IID_IDXGIDecodeSwapChain_Value = Guid.initString("2633066b-4514-4c7a-8fd8-12ea98059d18");
pub const IID_IDXGIDecodeSwapChain = &IID_IDXGIDecodeSwapChain_Value;
pub const IDXGIDecodeSwapChain = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
PresentBuffer: fn(
self: *const IDXGIDecodeSwapChain,
BufferToPresent: u32,
SyncInterval: u32,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetSourceRect: fn(
self: *const IDXGIDecodeSwapChain,
pRect: ?*const RECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetTargetRect: fn(
self: *const IDXGIDecodeSwapChain,
pRect: ?*const RECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetDestSize: fn(
self: *const IDXGIDecodeSwapChain,
Width: u32,
Height: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSourceRect: fn(
self: *const IDXGIDecodeSwapChain,
pRect: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetTargetRect: fn(
self: *const IDXGIDecodeSwapChain,
pRect: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDestSize: fn(
self: *const IDXGIDecodeSwapChain,
pWidth: ?*u32,
pHeight: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetColorSpace: fn(
self: *const IDXGIDecodeSwapChain,
ColorSpace: DXGI_MULTIPLANE_OVERLAY_YCbCr_FLAGS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetColorSpace: fn(
self: *const IDXGIDecodeSwapChain,
) callconv(@import("std").os.windows.WINAPI) DXGI_MULTIPLANE_OVERLAY_YCbCr_FLAGS,
};
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 IDXGIDecodeSwapChain_PresentBuffer(self: *const T, BufferToPresent: u32, SyncInterval: u32, Flags: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIDecodeSwapChain.VTable, self.vtable).PresentBuffer(@ptrCast(*const IDXGIDecodeSwapChain, self), BufferToPresent, SyncInterval, Flags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIDecodeSwapChain_SetSourceRect(self: *const T, pRect: ?*const RECT) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIDecodeSwapChain.VTable, self.vtable).SetSourceRect(@ptrCast(*const IDXGIDecodeSwapChain, self), pRect);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIDecodeSwapChain_SetTargetRect(self: *const T, pRect: ?*const RECT) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIDecodeSwapChain.VTable, self.vtable).SetTargetRect(@ptrCast(*const IDXGIDecodeSwapChain, self), pRect);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIDecodeSwapChain_SetDestSize(self: *const T, Width: u32, Height: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIDecodeSwapChain.VTable, self.vtable).SetDestSize(@ptrCast(*const IDXGIDecodeSwapChain, self), Width, Height);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIDecodeSwapChain_GetSourceRect(self: *const T, pRect: ?*RECT) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIDecodeSwapChain.VTable, self.vtable).GetSourceRect(@ptrCast(*const IDXGIDecodeSwapChain, self), pRect);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIDecodeSwapChain_GetTargetRect(self: *const T, pRect: ?*RECT) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIDecodeSwapChain.VTable, self.vtable).GetTargetRect(@ptrCast(*const IDXGIDecodeSwapChain, self), pRect);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIDecodeSwapChain_GetDestSize(self: *const T, pWidth: ?*u32, pHeight: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIDecodeSwapChain.VTable, self.vtable).GetDestSize(@ptrCast(*const IDXGIDecodeSwapChain, self), pWidth, pHeight);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIDecodeSwapChain_SetColorSpace(self: *const T, ColorSpace: DXGI_MULTIPLANE_OVERLAY_YCbCr_FLAGS) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIDecodeSwapChain.VTable, self.vtable).SetColorSpace(@ptrCast(*const IDXGIDecodeSwapChain, self), ColorSpace);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIDecodeSwapChain_GetColorSpace(self: *const T) callconv(.Inline) DXGI_MULTIPLANE_OVERLAY_YCbCr_FLAGS {
return @ptrCast(*const IDXGIDecodeSwapChain.VTable, self.vtable).GetColorSpace(@ptrCast(*const IDXGIDecodeSwapChain, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.1'
const IID_IDXGIFactoryMedia_Value = Guid.initString("41e7d1f2-a591-4f7b-a2e5-fa9c843e1c12");
pub const IID_IDXGIFactoryMedia = &IID_IDXGIFactoryMedia_Value;
pub const IDXGIFactoryMedia = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
CreateSwapChainForCompositionSurfaceHandle: fn(
self: *const IDXGIFactoryMedia,
pDevice: ?*IUnknown,
hSurface: ?HANDLE,
pDesc: ?*const DXGI_SWAP_CHAIN_DESC1,
pRestrictToOutput: ?*IDXGIOutput,
ppSwapChain: ?*?*IDXGISwapChain1,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateDecodeSwapChainForCompositionSurfaceHandle: fn(
self: *const IDXGIFactoryMedia,
pDevice: ?*IUnknown,
hSurface: ?HANDLE,
pDesc: ?*DXGI_DECODE_SWAP_CHAIN_DESC,
pYuvDecodeBuffers: ?*IDXGIResource,
pRestrictToOutput: ?*IDXGIOutput,
ppSwapChain: ?*?*IDXGIDecodeSwapChain,
) 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 IDXGIFactoryMedia_CreateSwapChainForCompositionSurfaceHandle(self: *const T, pDevice: ?*IUnknown, hSurface: ?HANDLE, pDesc: ?*const DXGI_SWAP_CHAIN_DESC1, pRestrictToOutput: ?*IDXGIOutput, ppSwapChain: ?*?*IDXGISwapChain1) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIFactoryMedia.VTable, self.vtable).CreateSwapChainForCompositionSurfaceHandle(@ptrCast(*const IDXGIFactoryMedia, self), pDevice, hSurface, pDesc, pRestrictToOutput, ppSwapChain);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIFactoryMedia_CreateDecodeSwapChainForCompositionSurfaceHandle(self: *const T, pDevice: ?*IUnknown, hSurface: ?HANDLE, pDesc: ?*DXGI_DECODE_SWAP_CHAIN_DESC, pYuvDecodeBuffers: ?*IDXGIResource, pRestrictToOutput: ?*IDXGIOutput, ppSwapChain: ?*?*IDXGIDecodeSwapChain) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIFactoryMedia.VTable, self.vtable).CreateDecodeSwapChainForCompositionSurfaceHandle(@ptrCast(*const IDXGIFactoryMedia, self), pDevice, hSurface, pDesc, pYuvDecodeBuffers, pRestrictToOutput, ppSwapChain);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DXGI_FRAME_PRESENTATION_MODE = enum(i32) {
COMPOSED = 0,
OVERLAY = 1,
NONE = 2,
COMPOSITION_FAILURE = 3,
};
pub const DXGI_FRAME_PRESENTATION_MODE_COMPOSED = DXGI_FRAME_PRESENTATION_MODE.COMPOSED;
pub const DXGI_FRAME_PRESENTATION_MODE_OVERLAY = DXGI_FRAME_PRESENTATION_MODE.OVERLAY;
pub const DXGI_FRAME_PRESENTATION_MODE_NONE = DXGI_FRAME_PRESENTATION_MODE.NONE;
pub const DXGI_FRAME_PRESENTATION_MODE_COMPOSITION_FAILURE = DXGI_FRAME_PRESENTATION_MODE.COMPOSITION_FAILURE;
pub const DXGI_FRAME_STATISTICS_MEDIA = extern struct {
PresentCount: u32,
PresentRefreshCount: u32,
SyncRefreshCount: u32,
SyncQPCTime: LARGE_INTEGER,
SyncGPUTime: LARGE_INTEGER,
CompositionMode: DXGI_FRAME_PRESENTATION_MODE,
ApprovedPresentDuration: u32,
};
// TODO: this type is limited to platform 'windows8.1'
const IID_IDXGISwapChainMedia_Value = Guid.initString("dd95b90b-f05f-4f6a-bd65-25bfb264bd84");
pub const IID_IDXGISwapChainMedia = &IID_IDXGISwapChainMedia_Value;
pub const IDXGISwapChainMedia = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetFrameStatisticsMedia: fn(
self: *const IDXGISwapChainMedia,
pStats: ?*DXGI_FRAME_STATISTICS_MEDIA,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetPresentDuration: fn(
self: *const IDXGISwapChainMedia,
Duration: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CheckPresentDurationSupport: fn(
self: *const IDXGISwapChainMedia,
DesiredPresentDuration: u32,
pClosestSmallerPresentDuration: ?*u32,
pClosestLargerPresentDuration: ?*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 IDXGISwapChainMedia_GetFrameStatisticsMedia(self: *const T, pStats: ?*DXGI_FRAME_STATISTICS_MEDIA) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChainMedia.VTable, self.vtable).GetFrameStatisticsMedia(@ptrCast(*const IDXGISwapChainMedia, self), pStats);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChainMedia_SetPresentDuration(self: *const T, Duration: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChainMedia.VTable, self.vtable).SetPresentDuration(@ptrCast(*const IDXGISwapChainMedia, self), Duration);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChainMedia_CheckPresentDurationSupport(self: *const T, DesiredPresentDuration: u32, pClosestSmallerPresentDuration: ?*u32, pClosestLargerPresentDuration: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChainMedia.VTable, self.vtable).CheckPresentDurationSupport(@ptrCast(*const IDXGISwapChainMedia, self), DesiredPresentDuration, pClosestSmallerPresentDuration, pClosestLargerPresentDuration);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DXGI_OVERLAY_SUPPORT_FLAG = enum(i32) {
DIRECT = 1,
SCALING = 2,
};
pub const DXGI_OVERLAY_SUPPORT_FLAG_DIRECT = DXGI_OVERLAY_SUPPORT_FLAG.DIRECT;
pub const DXGI_OVERLAY_SUPPORT_FLAG_SCALING = DXGI_OVERLAY_SUPPORT_FLAG.SCALING;
// TODO: this type is limited to platform 'windows8.1'
const IID_IDXGIOutput3_Value = Guid.initString("8a6bb301-7e7e-41f4-a8e0-5b32f7f99b18");
pub const IID_IDXGIOutput3 = &IID_IDXGIOutput3_Value;
pub const IDXGIOutput3 = extern struct {
pub const VTable = extern struct {
base: IDXGIOutput2.VTable,
CheckOverlaySupport: fn(
self: *const IDXGIOutput3,
EnumFormat: DXGI_FORMAT,
pConcernedDevice: ?*IUnknown,
pFlags: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIOutput2.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIOutput3_CheckOverlaySupport(self: *const T, EnumFormat: DXGI_FORMAT, pConcernedDevice: ?*IUnknown, pFlags: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIOutput3.VTable, self.vtable).CheckOverlaySupport(@ptrCast(*const IDXGIOutput3, self), EnumFormat, pConcernedDevice, pFlags);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DXGI_SWAP_CHAIN_COLOR_SPACE_SUPPORT_FLAG = enum(i32) {
PRESENT = 1,
OVERLAY_PRESENT = 2,
};
pub const DXGI_SWAP_CHAIN_COLOR_SPACE_SUPPORT_FLAG_PRESENT = DXGI_SWAP_CHAIN_COLOR_SPACE_SUPPORT_FLAG.PRESENT;
pub const DXGI_SWAP_CHAIN_COLOR_SPACE_SUPPORT_FLAG_OVERLAY_PRESENT = DXGI_SWAP_CHAIN_COLOR_SPACE_SUPPORT_FLAG.OVERLAY_PRESENT;
// TODO: this type is limited to platform 'windows10.0.10240'
const IID_IDXGISwapChain3_Value = Guid.initString("94d99bdb-f1f8-4ab0-b236-7da0170edab1");
pub const IID_IDXGISwapChain3 = &IID_IDXGISwapChain3_Value;
pub const IDXGISwapChain3 = extern struct {
pub const VTable = extern struct {
base: IDXGISwapChain2.VTable,
GetCurrentBackBufferIndex: fn(
self: *const IDXGISwapChain3,
) callconv(@import("std").os.windows.WINAPI) u32,
CheckColorSpaceSupport: fn(
self: *const IDXGISwapChain3,
ColorSpace: DXGI_COLOR_SPACE_TYPE,
pColorSpaceSupport: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetColorSpace1: fn(
self: *const IDXGISwapChain3,
ColorSpace: DXGI_COLOR_SPACE_TYPE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ResizeBuffers1: fn(
self: *const IDXGISwapChain3,
BufferCount: u32,
Width: u32,
Height: u32,
Format: DXGI_FORMAT,
SwapChainFlags: u32,
pCreationNodeMask: [*]const u32,
ppPresentQueue: [*]?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGISwapChain2.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain3_GetCurrentBackBufferIndex(self: *const T) callconv(.Inline) u32 {
return @ptrCast(*const IDXGISwapChain3.VTable, self.vtable).GetCurrentBackBufferIndex(@ptrCast(*const IDXGISwapChain3, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain3_CheckColorSpaceSupport(self: *const T, ColorSpace: DXGI_COLOR_SPACE_TYPE, pColorSpaceSupport: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChain3.VTable, self.vtable).CheckColorSpaceSupport(@ptrCast(*const IDXGISwapChain3, self), ColorSpace, pColorSpaceSupport);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain3_SetColorSpace1(self: *const T, ColorSpace: DXGI_COLOR_SPACE_TYPE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChain3.VTable, self.vtable).SetColorSpace1(@ptrCast(*const IDXGISwapChain3, self), ColorSpace);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain3_ResizeBuffers1(self: *const T, BufferCount: u32, Width: u32, Height: u32, Format: DXGI_FORMAT, SwapChainFlags: u32, pCreationNodeMask: [*]const u32, ppPresentQueue: [*]?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChain3.VTable, self.vtable).ResizeBuffers1(@ptrCast(*const IDXGISwapChain3, self), BufferCount, Width, Height, Format, SwapChainFlags, pCreationNodeMask, ppPresentQueue);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DXGI_OVERLAY_COLOR_SPACE_SUPPORT_FLAG = enum(i32) {
T = 1,
};
pub const DXGI_OVERLAY_COLOR_SPACE_SUPPORT_FLAG_PRESENT = DXGI_OVERLAY_COLOR_SPACE_SUPPORT_FLAG.T;
// TODO: this type is limited to platform 'windows10.0.10240'
const IID_IDXGIOutput4_Value = Guid.initString("dc7dca35-2196-414d-9f53-617884032a60");
pub const IID_IDXGIOutput4 = &IID_IDXGIOutput4_Value;
pub const IDXGIOutput4 = extern struct {
pub const VTable = extern struct {
base: IDXGIOutput3.VTable,
CheckOverlayColorSpaceSupport: fn(
self: *const IDXGIOutput4,
Format: DXGI_FORMAT,
ColorSpace: DXGI_COLOR_SPACE_TYPE,
pConcernedDevice: ?*IUnknown,
pFlags: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIOutput3.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIOutput4_CheckOverlayColorSpaceSupport(self: *const T, Format: DXGI_FORMAT, ColorSpace: DXGI_COLOR_SPACE_TYPE, pConcernedDevice: ?*IUnknown, pFlags: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIOutput4.VTable, self.vtable).CheckOverlayColorSpaceSupport(@ptrCast(*const IDXGIOutput4, self), Format, ColorSpace, pConcernedDevice, pFlags);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDXGIFactory4_Value = Guid.initString("1bc6ea02-ef36-464f-bf0c-21ca39e5168a");
pub const IID_IDXGIFactory4 = &IID_IDXGIFactory4_Value;
pub const IDXGIFactory4 = extern struct {
pub const VTable = extern struct {
base: IDXGIFactory3.VTable,
EnumAdapterByLuid: fn(
self: *const IDXGIFactory4,
AdapterLuid: LUID,
riid: ?*const Guid,
ppvAdapter: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EnumWarpAdapter: fn(
self: *const IDXGIFactory4,
riid: ?*const Guid,
ppvAdapter: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIFactory3.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIFactory4_EnumAdapterByLuid(self: *const T, AdapterLuid: LUID, riid: ?*const Guid, ppvAdapter: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIFactory4.VTable, self.vtable).EnumAdapterByLuid(@ptrCast(*const IDXGIFactory4, self), AdapterLuid, riid, ppvAdapter);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIFactory4_EnumWarpAdapter(self: *const T, riid: ?*const Guid, ppvAdapter: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIFactory4.VTable, self.vtable).EnumWarpAdapter(@ptrCast(*const IDXGIFactory4, self), riid, ppvAdapter);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DXGI_MEMORY_SEGMENT_GROUP = enum(i32) {
LOCAL = 0,
NON_LOCAL = 1,
};
pub const DXGI_MEMORY_SEGMENT_GROUP_LOCAL = DXGI_MEMORY_SEGMENT_GROUP.LOCAL;
pub const DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL = DXGI_MEMORY_SEGMENT_GROUP.NON_LOCAL;
pub const DXGI_QUERY_VIDEO_MEMORY_INFO = extern struct {
Budget: u64,
CurrentUsage: u64,
AvailableForReservation: u64,
CurrentReservation: u64,
};
const IID_IDXGIAdapter3_Value = Guid.initString("645967a4-1392-4310-a798-8053ce3e93fd");
pub const IID_IDXGIAdapter3 = &IID_IDXGIAdapter3_Value;
pub const IDXGIAdapter3 = extern struct {
pub const VTable = extern struct {
base: IDXGIAdapter2.VTable,
RegisterHardwareContentProtectionTeardownStatusEvent: fn(
self: *const IDXGIAdapter3,
hEvent: ?HANDLE,
pdwCookie: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UnregisterHardwareContentProtectionTeardownStatus: fn(
self: *const IDXGIAdapter3,
dwCookie: u32,
) callconv(@import("std").os.windows.WINAPI) void,
QueryVideoMemoryInfo: fn(
self: *const IDXGIAdapter3,
NodeIndex: u32,
MemorySegmentGroup: DXGI_MEMORY_SEGMENT_GROUP,
pVideoMemoryInfo: ?*DXGI_QUERY_VIDEO_MEMORY_INFO,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetVideoMemoryReservation: fn(
self: *const IDXGIAdapter3,
NodeIndex: u32,
MemorySegmentGroup: DXGI_MEMORY_SEGMENT_GROUP,
Reservation: u64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RegisterVideoMemoryBudgetChangeNotificationEvent: fn(
self: *const IDXGIAdapter3,
hEvent: ?HANDLE,
pdwCookie: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UnregisterVideoMemoryBudgetChangeNotification: fn(
self: *const IDXGIAdapter3,
dwCookie: u32,
) callconv(@import("std").os.windows.WINAPI) void,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIAdapter2.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIAdapter3_RegisterHardwareContentProtectionTeardownStatusEvent(self: *const T, hEvent: ?HANDLE, pdwCookie: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIAdapter3.VTable, self.vtable).RegisterHardwareContentProtectionTeardownStatusEvent(@ptrCast(*const IDXGIAdapter3, self), hEvent, pdwCookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIAdapter3_UnregisterHardwareContentProtectionTeardownStatus(self: *const T, dwCookie: u32) callconv(.Inline) void {
return @ptrCast(*const IDXGIAdapter3.VTable, self.vtable).UnregisterHardwareContentProtectionTeardownStatus(@ptrCast(*const IDXGIAdapter3, self), dwCookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIAdapter3_QueryVideoMemoryInfo(self: *const T, NodeIndex: u32, MemorySegmentGroup: DXGI_MEMORY_SEGMENT_GROUP, pVideoMemoryInfo: ?*DXGI_QUERY_VIDEO_MEMORY_INFO) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIAdapter3.VTable, self.vtable).QueryVideoMemoryInfo(@ptrCast(*const IDXGIAdapter3, self), NodeIndex, MemorySegmentGroup, pVideoMemoryInfo);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIAdapter3_SetVideoMemoryReservation(self: *const T, NodeIndex: u32, MemorySegmentGroup: DXGI_MEMORY_SEGMENT_GROUP, Reservation: u64) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIAdapter3.VTable, self.vtable).SetVideoMemoryReservation(@ptrCast(*const IDXGIAdapter3, self), NodeIndex, MemorySegmentGroup, Reservation);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIAdapter3_RegisterVideoMemoryBudgetChangeNotificationEvent(self: *const T, hEvent: ?HANDLE, pdwCookie: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIAdapter3.VTable, self.vtable).RegisterVideoMemoryBudgetChangeNotificationEvent(@ptrCast(*const IDXGIAdapter3, self), hEvent, pdwCookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIAdapter3_UnregisterVideoMemoryBudgetChangeNotification(self: *const T, dwCookie: u32) callconv(.Inline) void {
return @ptrCast(*const IDXGIAdapter3.VTable, self.vtable).UnregisterVideoMemoryBudgetChangeNotification(@ptrCast(*const IDXGIAdapter3, self), dwCookie);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DXGI_OUTDUPL_FLAG = enum(i32) {
Y = 1,
};
pub const DXGI_OUTDUPL_COMPOSITED_UI_CAPTURE_ONLY = DXGI_OUTDUPL_FLAG.Y;
// TODO: this type is limited to platform 'windows10.0.10240'
const IID_IDXGIOutput5_Value = Guid.initString("80a07424-ab52-42eb-833c-0c42fd282d98");
pub const IID_IDXGIOutput5 = &IID_IDXGIOutput5_Value;
pub const IDXGIOutput5 = extern struct {
pub const VTable = extern struct {
base: IDXGIOutput4.VTable,
DuplicateOutput1: fn(
self: *const IDXGIOutput5,
pDevice: ?*IUnknown,
Flags: u32,
SupportedFormatsCount: u32,
pSupportedFormats: [*]const DXGI_FORMAT,
ppOutputDuplication: ?*?*IDXGIOutputDuplication,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIOutput4.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIOutput5_DuplicateOutput1(self: *const T, pDevice: ?*IUnknown, Flags: u32, SupportedFormatsCount: u32, pSupportedFormats: [*]const DXGI_FORMAT, ppOutputDuplication: ?*?*IDXGIOutputDuplication) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIOutput5.VTable, self.vtable).DuplicateOutput1(@ptrCast(*const IDXGIOutput5, self), pDevice, Flags, SupportedFormatsCount, pSupportedFormats, ppOutputDuplication);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DXGI_HDR_METADATA_TYPE = enum(i32) {
NONE = 0,
HDR10 = 1,
HDR10PLUS = 2,
};
pub const DXGI_HDR_METADATA_TYPE_NONE = DXGI_HDR_METADATA_TYPE.NONE;
pub const DXGI_HDR_METADATA_TYPE_HDR10 = DXGI_HDR_METADATA_TYPE.HDR10;
pub const DXGI_HDR_METADATA_TYPE_HDR10PLUS = DXGI_HDR_METADATA_TYPE.HDR10PLUS;
pub const DXGI_HDR_METADATA_HDR10 = extern struct {
RedPrimary: [2]u16,
GreenPrimary: [2]u16,
BluePrimary: [2]u16,
WhitePoint: [2]u16,
MaxMasteringLuminance: u32,
MinMasteringLuminance: u32,
MaxContentLightLevel: u16,
MaxFrameAverageLightLevel: u16,
};
pub const DXGI_HDR_METADATA_HDR10PLUS = extern struct {
Data: [72]u8,
};
const IID_IDXGISwapChain4_Value = Guid.initString("3d585d5a-bd4a-489e-b1f4-3dbcb6452ffb");
pub const IID_IDXGISwapChain4 = &IID_IDXGISwapChain4_Value;
pub const IDXGISwapChain4 = extern struct {
pub const VTable = extern struct {
base: IDXGISwapChain3.VTable,
SetHDRMetaData: fn(
self: *const IDXGISwapChain4,
Type: DXGI_HDR_METADATA_TYPE,
Size: u32,
pMetaData: ?[*]u8,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGISwapChain3.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGISwapChain4_SetHDRMetaData(self: *const T, Type: DXGI_HDR_METADATA_TYPE, Size: u32, pMetaData: ?[*]u8) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGISwapChain4.VTable, self.vtable).SetHDRMetaData(@ptrCast(*const IDXGISwapChain4, self), Type, Size, pMetaData);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DXGI_OFFER_RESOURCE_FLAGS = enum(i32) {
T = 1,
};
pub const DXGI_OFFER_RESOURCE_FLAG_ALLOW_DECOMMIT = DXGI_OFFER_RESOURCE_FLAGS.T;
pub const DXGI_RECLAIM_RESOURCE_RESULTS = enum(i32) {
OK = 0,
DISCARDED = 1,
NOT_COMMITTED = 2,
};
pub const DXGI_RECLAIM_RESOURCE_RESULT_OK = DXGI_RECLAIM_RESOURCE_RESULTS.OK;
pub const DXGI_RECLAIM_RESOURCE_RESULT_DISCARDED = DXGI_RECLAIM_RESOURCE_RESULTS.DISCARDED;
pub const DXGI_RECLAIM_RESOURCE_RESULT_NOT_COMMITTED = DXGI_RECLAIM_RESOURCE_RESULTS.NOT_COMMITTED;
const IID_IDXGIDevice4_Value = Guid.initString("95b4f95f-d8da-4ca4-9ee6-3b76d5968a10");
pub const IID_IDXGIDevice4 = &IID_IDXGIDevice4_Value;
pub const IDXGIDevice4 = extern struct {
pub const VTable = extern struct {
base: IDXGIDevice3.VTable,
OfferResources1: fn(
self: *const IDXGIDevice4,
NumResources: u32,
ppResources: [*]?*IDXGIResource,
Priority: DXGI_OFFER_RESOURCE_PRIORITY,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ReclaimResources1: fn(
self: *const IDXGIDevice4,
NumResources: u32,
ppResources: [*]?*IDXGIResource,
pResults: ?*DXGI_RECLAIM_RESOURCE_RESULTS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIDevice3.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIDevice4_OfferResources1(self: *const T, NumResources: u32, ppResources: [*]?*IDXGIResource, Priority: DXGI_OFFER_RESOURCE_PRIORITY, Flags: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIDevice4.VTable, self.vtable).OfferResources1(@ptrCast(*const IDXGIDevice4, self), NumResources, ppResources, Priority, Flags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIDevice4_ReclaimResources1(self: *const T, NumResources: u32, ppResources: [*]?*IDXGIResource, pResults: ?*DXGI_RECLAIM_RESOURCE_RESULTS) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIDevice4.VTable, self.vtable).ReclaimResources1(@ptrCast(*const IDXGIDevice4, self), NumResources, ppResources, pResults);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DXGI_FEATURE = enum(i32) {
G = 0,
};
pub const DXGI_FEATURE_PRESENT_ALLOW_TEARING = DXGI_FEATURE.G;
const IID_IDXGIFactory5_Value = Guid.initString("7632e1f5-ee65-4dca-87fd-84cd75f8838d");
pub const IID_IDXGIFactory5 = &IID_IDXGIFactory5_Value;
pub const IDXGIFactory5 = extern struct {
pub const VTable = extern struct {
base: IDXGIFactory4.VTable,
CheckFeatureSupport: fn(
self: *const IDXGIFactory5,
Feature: DXGI_FEATURE,
// TODO: what to do with BytesParamIndex 2?
pFeatureSupportData: ?*anyopaque,
FeatureSupportDataSize: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIFactory4.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIFactory5_CheckFeatureSupport(self: *const T, Feature: DXGI_FEATURE, pFeatureSupportData: ?*anyopaque, FeatureSupportDataSize: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIFactory5.VTable, self.vtable).CheckFeatureSupport(@ptrCast(*const IDXGIFactory5, self), Feature, pFeatureSupportData, FeatureSupportDataSize);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DXGI_ADAPTER_FLAG3 = enum(u32) {
NONE = 0,
REMOTE = 1,
SOFTWARE = 2,
ACG_COMPATIBLE = 4,
SUPPORT_MONITORED_FENCES = 8,
SUPPORT_NON_MONITORED_FENCES = 16,
KEYED_MUTEX_CONFORMANCE = 32,
FORCE_DWORD = 4294967295,
_,
pub fn initFlags(o: struct {
NONE: u1 = 0,
REMOTE: u1 = 0,
SOFTWARE: u1 = 0,
ACG_COMPATIBLE: u1 = 0,
SUPPORT_MONITORED_FENCES: u1 = 0,
SUPPORT_NON_MONITORED_FENCES: u1 = 0,
KEYED_MUTEX_CONFORMANCE: u1 = 0,
FORCE_DWORD: u1 = 0,
}) DXGI_ADAPTER_FLAG3 {
return @intToEnum(DXGI_ADAPTER_FLAG3,
(if (o.NONE == 1) @enumToInt(DXGI_ADAPTER_FLAG3.NONE) else 0)
| (if (o.REMOTE == 1) @enumToInt(DXGI_ADAPTER_FLAG3.REMOTE) else 0)
| (if (o.SOFTWARE == 1) @enumToInt(DXGI_ADAPTER_FLAG3.SOFTWARE) else 0)
| (if (o.ACG_COMPATIBLE == 1) @enumToInt(DXGI_ADAPTER_FLAG3.ACG_COMPATIBLE) else 0)
| (if (o.SUPPORT_MONITORED_FENCES == 1) @enumToInt(DXGI_ADAPTER_FLAG3.SUPPORT_MONITORED_FENCES) else 0)
| (if (o.SUPPORT_NON_MONITORED_FENCES == 1) @enumToInt(DXGI_ADAPTER_FLAG3.SUPPORT_NON_MONITORED_FENCES) else 0)
| (if (o.KEYED_MUTEX_CONFORMANCE == 1) @enumToInt(DXGI_ADAPTER_FLAG3.KEYED_MUTEX_CONFORMANCE) else 0)
| (if (o.FORCE_DWORD == 1) @enumToInt(DXGI_ADAPTER_FLAG3.FORCE_DWORD) else 0)
);
}
};
pub const DXGI_ADAPTER_FLAG3_NONE = DXGI_ADAPTER_FLAG3.NONE;
pub const DXGI_ADAPTER_FLAG3_REMOTE = DXGI_ADAPTER_FLAG3.REMOTE;
pub const DXGI_ADAPTER_FLAG3_SOFTWARE = DXGI_ADAPTER_FLAG3.SOFTWARE;
pub const DXGI_ADAPTER_FLAG3_ACG_COMPATIBLE = DXGI_ADAPTER_FLAG3.ACG_COMPATIBLE;
pub const DXGI_ADAPTER_FLAG3_SUPPORT_MONITORED_FENCES = DXGI_ADAPTER_FLAG3.SUPPORT_MONITORED_FENCES;
pub const DXGI_ADAPTER_FLAG3_SUPPORT_NON_MONITORED_FENCES = DXGI_ADAPTER_FLAG3.SUPPORT_NON_MONITORED_FENCES;
pub const DXGI_ADAPTER_FLAG3_KEYED_MUTEX_CONFORMANCE = DXGI_ADAPTER_FLAG3.KEYED_MUTEX_CONFORMANCE;
pub const DXGI_ADAPTER_FLAG3_FORCE_DWORD = DXGI_ADAPTER_FLAG3.FORCE_DWORD;
pub const DXGI_ADAPTER_DESC3 = extern struct {
Description: [128]u16,
VendorId: u32,
DeviceId: u32,
SubSysId: u32,
Revision: u32,
DedicatedVideoMemory: usize,
DedicatedSystemMemory: usize,
SharedSystemMemory: usize,
AdapterLuid: LUID,
Flags: DXGI_ADAPTER_FLAG3,
GraphicsPreemptionGranularity: DXGI_GRAPHICS_PREEMPTION_GRANULARITY,
ComputePreemptionGranularity: DXGI_COMPUTE_PREEMPTION_GRANULARITY,
};
const IID_IDXGIAdapter4_Value = Guid.initString("3c8d99d1-4fbf-4181-a82c-af66bf7bd24e");
pub const IID_IDXGIAdapter4 = &IID_IDXGIAdapter4_Value;
pub const IDXGIAdapter4 = extern struct {
pub const VTable = extern struct {
base: IDXGIAdapter3.VTable,
GetDesc3: fn(
self: *const IDXGIAdapter4,
pDesc: ?*DXGI_ADAPTER_DESC3,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIAdapter3.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIAdapter4_GetDesc3(self: *const T, pDesc: ?*DXGI_ADAPTER_DESC3) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIAdapter4.VTable, self.vtable).GetDesc3(@ptrCast(*const IDXGIAdapter4, self), pDesc);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DXGI_OUTPUT_DESC1 = extern struct {
DeviceName: [32]u16,
DesktopCoordinates: RECT,
AttachedToDesktop: BOOL,
Rotation: DXGI_MODE_ROTATION,
Monitor: ?HMONITOR,
BitsPerColor: u32,
ColorSpace: DXGI_COLOR_SPACE_TYPE,
RedPrimary: [2]f32,
GreenPrimary: [2]f32,
BluePrimary: [2]f32,
WhitePoint: [2]f32,
MinLuminance: f32,
MaxLuminance: f32,
MaxFullFrameLuminance: f32,
};
pub const DXGI_HARDWARE_COMPOSITION_SUPPORT_FLAGS = enum(u32) {
FULLSCREEN = 1,
WINDOWED = 2,
CURSOR_STRETCHED = 4,
_,
pub fn initFlags(o: struct {
FULLSCREEN: u1 = 0,
WINDOWED: u1 = 0,
CURSOR_STRETCHED: u1 = 0,
}) DXGI_HARDWARE_COMPOSITION_SUPPORT_FLAGS {
return @intToEnum(DXGI_HARDWARE_COMPOSITION_SUPPORT_FLAGS,
(if (o.FULLSCREEN == 1) @enumToInt(DXGI_HARDWARE_COMPOSITION_SUPPORT_FLAGS.FULLSCREEN) else 0)
| (if (o.WINDOWED == 1) @enumToInt(DXGI_HARDWARE_COMPOSITION_SUPPORT_FLAGS.WINDOWED) else 0)
| (if (o.CURSOR_STRETCHED == 1) @enumToInt(DXGI_HARDWARE_COMPOSITION_SUPPORT_FLAGS.CURSOR_STRETCHED) else 0)
);
}
};
pub const DXGI_HARDWARE_COMPOSITION_SUPPORT_FLAG_FULLSCREEN = DXGI_HARDWARE_COMPOSITION_SUPPORT_FLAGS.FULLSCREEN;
pub const DXGI_HARDWARE_COMPOSITION_SUPPORT_FLAG_WINDOWED = DXGI_HARDWARE_COMPOSITION_SUPPORT_FLAGS.WINDOWED;
pub const DXGI_HARDWARE_COMPOSITION_SUPPORT_FLAG_CURSOR_STRETCHED = DXGI_HARDWARE_COMPOSITION_SUPPORT_FLAGS.CURSOR_STRETCHED;
// TODO: this type is limited to platform 'windows10.0.10240'
const IID_IDXGIOutput6_Value = Guid.initString("068346e8-aaec-4b84-add7-137f513f77a1");
pub const IID_IDXGIOutput6 = &IID_IDXGIOutput6_Value;
pub const IDXGIOutput6 = extern struct {
pub const VTable = extern struct {
base: IDXGIOutput5.VTable,
GetDesc1: fn(
self: *const IDXGIOutput6,
pDesc: ?*DXGI_OUTPUT_DESC1,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CheckHardwareCompositionSupport: fn(
self: *const IDXGIOutput6,
pFlags: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIOutput5.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIOutput6_GetDesc1(self: *const T, pDesc: ?*DXGI_OUTPUT_DESC1) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIOutput6.VTable, self.vtable).GetDesc1(@ptrCast(*const IDXGIOutput6, self), pDesc);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIOutput6_CheckHardwareCompositionSupport(self: *const T, pFlags: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIOutput6.VTable, self.vtable).CheckHardwareCompositionSupport(@ptrCast(*const IDXGIOutput6, self), pFlags);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DXGI_GPU_PREFERENCE = enum(i32) {
UNSPECIFIED = 0,
MINIMUM_POWER = 1,
HIGH_PERFORMANCE = 2,
};
pub const DXGI_GPU_PREFERENCE_UNSPECIFIED = DXGI_GPU_PREFERENCE.UNSPECIFIED;
pub const DXGI_GPU_PREFERENCE_MINIMUM_POWER = DXGI_GPU_PREFERENCE.MINIMUM_POWER;
pub const DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE = DXGI_GPU_PREFERENCE.HIGH_PERFORMANCE;
// TODO: this type is limited to platform 'windows10.0.17134'
const IID_IDXGIFactory6_Value = Guid.initString("c1b6694f-ff09-44a9-b03c-77900a0a1d17");
pub const IID_IDXGIFactory6 = &IID_IDXGIFactory6_Value;
pub const IDXGIFactory6 = extern struct {
pub const VTable = extern struct {
base: IDXGIFactory5.VTable,
EnumAdapterByGpuPreference: fn(
self: *const IDXGIFactory6,
Adapter: u32,
GpuPreference: DXGI_GPU_PREFERENCE,
riid: ?*const Guid,
ppvAdapter: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIFactory5.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIFactory6_EnumAdapterByGpuPreference(self: *const T, Adapter: u32, GpuPreference: DXGI_GPU_PREFERENCE, riid: ?*const Guid, ppvAdapter: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIFactory6.VTable, self.vtable).EnumAdapterByGpuPreference(@ptrCast(*const IDXGIFactory6, self), Adapter, GpuPreference, riid, ppvAdapter);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.17763'
const IID_IDXGIFactory7_Value = Guid.initString("a4966eed-76db-44da-84c1-ee9a7afb20a8");
pub const IID_IDXGIFactory7 = &IID_IDXGIFactory7_Value;
pub const IDXGIFactory7 = extern struct {
pub const VTable = extern struct {
base: IDXGIFactory6.VTable,
RegisterAdaptersChangedEvent: fn(
self: *const IDXGIFactory7,
hEvent: ?HANDLE,
pdwCookie: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UnregisterAdaptersChangedEvent: fn(
self: *const IDXGIFactory7,
dwCookie: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIFactory6.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIFactory7_RegisterAdaptersChangedEvent(self: *const T, hEvent: ?HANDLE, pdwCookie: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIFactory7.VTable, self.vtable).RegisterAdaptersChangedEvent(@ptrCast(*const IDXGIFactory7, self), hEvent, pdwCookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIFactory7_UnregisterAdaptersChangedEvent(self: *const T, dwCookie: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIFactory7.VTable, self.vtable).UnregisterAdaptersChangedEvent(@ptrCast(*const IDXGIFactory7, self), dwCookie);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DXGI_DEBUG_RLO_FLAGS = enum(u32) {
SUMMARY = 1,
DETAIL = 2,
IGNORE_INTERNAL = 4,
ALL = 7,
_,
pub fn initFlags(o: struct {
SUMMARY: u1 = 0,
DETAIL: u1 = 0,
IGNORE_INTERNAL: u1 = 0,
ALL: u1 = 0,
}) DXGI_DEBUG_RLO_FLAGS {
return @intToEnum(DXGI_DEBUG_RLO_FLAGS,
(if (o.SUMMARY == 1) @enumToInt(DXGI_DEBUG_RLO_FLAGS.SUMMARY) else 0)
| (if (o.DETAIL == 1) @enumToInt(DXGI_DEBUG_RLO_FLAGS.DETAIL) else 0)
| (if (o.IGNORE_INTERNAL == 1) @enumToInt(DXGI_DEBUG_RLO_FLAGS.IGNORE_INTERNAL) else 0)
| (if (o.ALL == 1) @enumToInt(DXGI_DEBUG_RLO_FLAGS.ALL) else 0)
);
}
};
pub const DXGI_DEBUG_RLO_SUMMARY = DXGI_DEBUG_RLO_FLAGS.SUMMARY;
pub const DXGI_DEBUG_RLO_DETAIL = DXGI_DEBUG_RLO_FLAGS.DETAIL;
pub const DXGI_DEBUG_RLO_IGNORE_INTERNAL = DXGI_DEBUG_RLO_FLAGS.IGNORE_INTERNAL;
pub const DXGI_DEBUG_RLO_ALL = DXGI_DEBUG_RLO_FLAGS.ALL;
pub const DXGI_INFO_QUEUE_MESSAGE_CATEGORY = enum(i32) {
UNKNOWN = 0,
MISCELLANEOUS = 1,
INITIALIZATION = 2,
CLEANUP = 3,
COMPILATION = 4,
STATE_CREATION = 5,
STATE_SETTING = 6,
STATE_GETTING = 7,
RESOURCE_MANIPULATION = 8,
EXECUTION = 9,
SHADER = 10,
};
pub const DXGI_INFO_QUEUE_MESSAGE_CATEGORY_UNKNOWN = DXGI_INFO_QUEUE_MESSAGE_CATEGORY.UNKNOWN;
pub const DXGI_INFO_QUEUE_MESSAGE_CATEGORY_MISCELLANEOUS = DXGI_INFO_QUEUE_MESSAGE_CATEGORY.MISCELLANEOUS;
pub const DXGI_INFO_QUEUE_MESSAGE_CATEGORY_INITIALIZATION = DXGI_INFO_QUEUE_MESSAGE_CATEGORY.INITIALIZATION;
pub const DXGI_INFO_QUEUE_MESSAGE_CATEGORY_CLEANUP = DXGI_INFO_QUEUE_MESSAGE_CATEGORY.CLEANUP;
pub const DXGI_INFO_QUEUE_MESSAGE_CATEGORY_COMPILATION = DXGI_INFO_QUEUE_MESSAGE_CATEGORY.COMPILATION;
pub const DXGI_INFO_QUEUE_MESSAGE_CATEGORY_STATE_CREATION = DXGI_INFO_QUEUE_MESSAGE_CATEGORY.STATE_CREATION;
pub const DXGI_INFO_QUEUE_MESSAGE_CATEGORY_STATE_SETTING = DXGI_INFO_QUEUE_MESSAGE_CATEGORY.STATE_SETTING;
pub const DXGI_INFO_QUEUE_MESSAGE_CATEGORY_STATE_GETTING = DXGI_INFO_QUEUE_MESSAGE_CATEGORY.STATE_GETTING;
pub const DXGI_INFO_QUEUE_MESSAGE_CATEGORY_RESOURCE_MANIPULATION = DXGI_INFO_QUEUE_MESSAGE_CATEGORY.RESOURCE_MANIPULATION;
pub const DXGI_INFO_QUEUE_MESSAGE_CATEGORY_EXECUTION = DXGI_INFO_QUEUE_MESSAGE_CATEGORY.EXECUTION;
pub const DXGI_INFO_QUEUE_MESSAGE_CATEGORY_SHADER = DXGI_INFO_QUEUE_MESSAGE_CATEGORY.SHADER;
pub const DXGI_INFO_QUEUE_MESSAGE_SEVERITY = enum(i32) {
CORRUPTION = 0,
ERROR = 1,
WARNING = 2,
INFO = 3,
MESSAGE = 4,
};
pub const DXGI_INFO_QUEUE_MESSAGE_SEVERITY_CORRUPTION = DXGI_INFO_QUEUE_MESSAGE_SEVERITY.CORRUPTION;
pub const DXGI_INFO_QUEUE_MESSAGE_SEVERITY_ERROR = DXGI_INFO_QUEUE_MESSAGE_SEVERITY.ERROR;
pub const DXGI_INFO_QUEUE_MESSAGE_SEVERITY_WARNING = DXGI_INFO_QUEUE_MESSAGE_SEVERITY.WARNING;
pub const DXGI_INFO_QUEUE_MESSAGE_SEVERITY_INFO = DXGI_INFO_QUEUE_MESSAGE_SEVERITY.INFO;
pub const DXGI_INFO_QUEUE_MESSAGE_SEVERITY_MESSAGE = DXGI_INFO_QUEUE_MESSAGE_SEVERITY.MESSAGE;
pub const DXGI_INFO_QUEUE_MESSAGE = extern struct {
Producer: Guid,
Category: DXGI_INFO_QUEUE_MESSAGE_CATEGORY,
Severity: DXGI_INFO_QUEUE_MESSAGE_SEVERITY,
ID: i32,
pDescription: ?*const u8,
DescriptionByteLength: usize,
};
pub const DXGI_INFO_QUEUE_FILTER_DESC = extern struct {
NumCategories: u32,
pCategoryList: ?*DXGI_INFO_QUEUE_MESSAGE_CATEGORY,
NumSeverities: u32,
pSeverityList: ?*DXGI_INFO_QUEUE_MESSAGE_SEVERITY,
NumIDs: u32,
pIDList: ?*i32,
};
pub const DXGI_INFO_QUEUE_FILTER = extern struct {
AllowList: DXGI_INFO_QUEUE_FILTER_DESC,
DenyList: DXGI_INFO_QUEUE_FILTER_DESC,
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IDXGIInfoQueue_Value = Guid.initString("d67441c7-672a-476f-9e82-cd55b44949ce");
pub const IID_IDXGIInfoQueue = &IID_IDXGIInfoQueue_Value;
pub const IDXGIInfoQueue = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetMessageCountLimit: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
MessageCountLimit: u64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ClearStoredMessages: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
) callconv(@import("std").os.windows.WINAPI) void,
GetMessage: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
MessageIndex: u64,
// TODO: what to do with BytesParamIndex 3?
pMessage: ?*DXGI_INFO_QUEUE_MESSAGE,
pMessageByteLength: ?*usize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetNumStoredMessagesAllowedByRetrievalFilters: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
) callconv(@import("std").os.windows.WINAPI) u64,
GetNumStoredMessages: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
) callconv(@import("std").os.windows.WINAPI) u64,
GetNumMessagesDiscardedByMessageCountLimit: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
) callconv(@import("std").os.windows.WINAPI) u64,
GetMessageCountLimit: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
) callconv(@import("std").os.windows.WINAPI) u64,
GetNumMessagesAllowedByStorageFilter: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
) callconv(@import("std").os.windows.WINAPI) u64,
GetNumMessagesDeniedByStorageFilter: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
) callconv(@import("std").os.windows.WINAPI) u64,
AddStorageFilterEntries: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
pFilter: ?*DXGI_INFO_QUEUE_FILTER,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetStorageFilter: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
// TODO: what to do with BytesParamIndex 2?
pFilter: ?*DXGI_INFO_QUEUE_FILTER,
pFilterByteLength: ?*usize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ClearStorageFilter: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
) callconv(@import("std").os.windows.WINAPI) void,
PushEmptyStorageFilter: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
PushDenyAllStorageFilter: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
PushCopyOfStorageFilter: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
PushStorageFilter: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
pFilter: ?*DXGI_INFO_QUEUE_FILTER,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
PopStorageFilter: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
) callconv(@import("std").os.windows.WINAPI) void,
GetStorageFilterStackSize: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
) callconv(@import("std").os.windows.WINAPI) u32,
AddRetrievalFilterEntries: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
pFilter: ?*DXGI_INFO_QUEUE_FILTER,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetRetrievalFilter: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
// TODO: what to do with BytesParamIndex 2?
pFilter: ?*DXGI_INFO_QUEUE_FILTER,
pFilterByteLength: ?*usize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ClearRetrievalFilter: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
) callconv(@import("std").os.windows.WINAPI) void,
PushEmptyRetrievalFilter: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
PushDenyAllRetrievalFilter: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
PushCopyOfRetrievalFilter: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
PushRetrievalFilter: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
pFilter: ?*DXGI_INFO_QUEUE_FILTER,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
PopRetrievalFilter: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
) callconv(@import("std").os.windows.WINAPI) void,
GetRetrievalFilterStackSize: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
) callconv(@import("std").os.windows.WINAPI) u32,
AddMessage: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
Category: DXGI_INFO_QUEUE_MESSAGE_CATEGORY,
Severity: DXGI_INFO_QUEUE_MESSAGE_SEVERITY,
ID: i32,
pDescription: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddApplicationMessage: fn(
self: *const IDXGIInfoQueue,
Severity: DXGI_INFO_QUEUE_MESSAGE_SEVERITY,
pDescription: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetBreakOnCategory: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
Category: DXGI_INFO_QUEUE_MESSAGE_CATEGORY,
bEnable: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetBreakOnSeverity: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
Severity: DXGI_INFO_QUEUE_MESSAGE_SEVERITY,
bEnable: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetBreakOnID: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
ID: i32,
bEnable: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetBreakOnCategory: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
Category: DXGI_INFO_QUEUE_MESSAGE_CATEGORY,
) callconv(@import("std").os.windows.WINAPI) BOOL,
GetBreakOnSeverity: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
Severity: DXGI_INFO_QUEUE_MESSAGE_SEVERITY,
) callconv(@import("std").os.windows.WINAPI) BOOL,
GetBreakOnID: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
ID: i32,
) callconv(@import("std").os.windows.WINAPI) BOOL,
SetMuteDebugOutput: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
bMute: BOOL,
) callconv(@import("std").os.windows.WINAPI) void,
GetMuteDebugOutput: fn(
self: *const IDXGIInfoQueue,
Producer: Guid,
) callconv(@import("std").os.windows.WINAPI) BOOL,
};
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 IDXGIInfoQueue_SetMessageCountLimit(self: *const T, Producer: Guid, MessageCountLimit: u64) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).SetMessageCountLimit(@ptrCast(*const IDXGIInfoQueue, self), Producer, MessageCountLimit);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_ClearStoredMessages(self: *const T, Producer: Guid) callconv(.Inline) void {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).ClearStoredMessages(@ptrCast(*const IDXGIInfoQueue, self), Producer);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_GetMessage(self: *const T, Producer: Guid, MessageIndex: u64, pMessage: ?*DXGI_INFO_QUEUE_MESSAGE, pMessageByteLength: ?*usize) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).GetMessage(@ptrCast(*const IDXGIInfoQueue, self), Producer, MessageIndex, pMessage, pMessageByteLength);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_GetNumStoredMessagesAllowedByRetrievalFilters(self: *const T, Producer: Guid) callconv(.Inline) u64 {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).GetNumStoredMessagesAllowedByRetrievalFilters(@ptrCast(*const IDXGIInfoQueue, self), Producer);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_GetNumStoredMessages(self: *const T, Producer: Guid) callconv(.Inline) u64 {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).GetNumStoredMessages(@ptrCast(*const IDXGIInfoQueue, self), Producer);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_GetNumMessagesDiscardedByMessageCountLimit(self: *const T, Producer: Guid) callconv(.Inline) u64 {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).GetNumMessagesDiscardedByMessageCountLimit(@ptrCast(*const IDXGIInfoQueue, self), Producer);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_GetMessageCountLimit(self: *const T, Producer: Guid) callconv(.Inline) u64 {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).GetMessageCountLimit(@ptrCast(*const IDXGIInfoQueue, self), Producer);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_GetNumMessagesAllowedByStorageFilter(self: *const T, Producer: Guid) callconv(.Inline) u64 {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).GetNumMessagesAllowedByStorageFilter(@ptrCast(*const IDXGIInfoQueue, self), Producer);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_GetNumMessagesDeniedByStorageFilter(self: *const T, Producer: Guid) callconv(.Inline) u64 {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).GetNumMessagesDeniedByStorageFilter(@ptrCast(*const IDXGIInfoQueue, self), Producer);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_AddStorageFilterEntries(self: *const T, Producer: Guid, pFilter: ?*DXGI_INFO_QUEUE_FILTER) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).AddStorageFilterEntries(@ptrCast(*const IDXGIInfoQueue, self), Producer, pFilter);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_GetStorageFilter(self: *const T, Producer: Guid, pFilter: ?*DXGI_INFO_QUEUE_FILTER, pFilterByteLength: ?*usize) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).GetStorageFilter(@ptrCast(*const IDXGIInfoQueue, self), Producer, pFilter, pFilterByteLength);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_ClearStorageFilter(self: *const T, Producer: Guid) callconv(.Inline) void {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).ClearStorageFilter(@ptrCast(*const IDXGIInfoQueue, self), Producer);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_PushEmptyStorageFilter(self: *const T, Producer: Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).PushEmptyStorageFilter(@ptrCast(*const IDXGIInfoQueue, self), Producer);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_PushDenyAllStorageFilter(self: *const T, Producer: Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).PushDenyAllStorageFilter(@ptrCast(*const IDXGIInfoQueue, self), Producer);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_PushCopyOfStorageFilter(self: *const T, Producer: Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).PushCopyOfStorageFilter(@ptrCast(*const IDXGIInfoQueue, self), Producer);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_PushStorageFilter(self: *const T, Producer: Guid, pFilter: ?*DXGI_INFO_QUEUE_FILTER) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).PushStorageFilter(@ptrCast(*const IDXGIInfoQueue, self), Producer, pFilter);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_PopStorageFilter(self: *const T, Producer: Guid) callconv(.Inline) void {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).PopStorageFilter(@ptrCast(*const IDXGIInfoQueue, self), Producer);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_GetStorageFilterStackSize(self: *const T, Producer: Guid) callconv(.Inline) u32 {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).GetStorageFilterStackSize(@ptrCast(*const IDXGIInfoQueue, self), Producer);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_AddRetrievalFilterEntries(self: *const T, Producer: Guid, pFilter: ?*DXGI_INFO_QUEUE_FILTER) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).AddRetrievalFilterEntries(@ptrCast(*const IDXGIInfoQueue, self), Producer, pFilter);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_GetRetrievalFilter(self: *const T, Producer: Guid, pFilter: ?*DXGI_INFO_QUEUE_FILTER, pFilterByteLength: ?*usize) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).GetRetrievalFilter(@ptrCast(*const IDXGIInfoQueue, self), Producer, pFilter, pFilterByteLength);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_ClearRetrievalFilter(self: *const T, Producer: Guid) callconv(.Inline) void {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).ClearRetrievalFilter(@ptrCast(*const IDXGIInfoQueue, self), Producer);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_PushEmptyRetrievalFilter(self: *const T, Producer: Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).PushEmptyRetrievalFilter(@ptrCast(*const IDXGIInfoQueue, self), Producer);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_PushDenyAllRetrievalFilter(self: *const T, Producer: Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).PushDenyAllRetrievalFilter(@ptrCast(*const IDXGIInfoQueue, self), Producer);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_PushCopyOfRetrievalFilter(self: *const T, Producer: Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).PushCopyOfRetrievalFilter(@ptrCast(*const IDXGIInfoQueue, self), Producer);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_PushRetrievalFilter(self: *const T, Producer: Guid, pFilter: ?*DXGI_INFO_QUEUE_FILTER) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).PushRetrievalFilter(@ptrCast(*const IDXGIInfoQueue, self), Producer, pFilter);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_PopRetrievalFilter(self: *const T, Producer: Guid) callconv(.Inline) void {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).PopRetrievalFilter(@ptrCast(*const IDXGIInfoQueue, self), Producer);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_GetRetrievalFilterStackSize(self: *const T, Producer: Guid) callconv(.Inline) u32 {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).GetRetrievalFilterStackSize(@ptrCast(*const IDXGIInfoQueue, self), Producer);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_AddMessage(self: *const T, Producer: Guid, Category: DXGI_INFO_QUEUE_MESSAGE_CATEGORY, Severity: DXGI_INFO_QUEUE_MESSAGE_SEVERITY, ID: i32, pDescription: ?[*:0]const u8) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).AddMessage(@ptrCast(*const IDXGIInfoQueue, self), Producer, Category, Severity, ID, pDescription);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_AddApplicationMessage(self: *const T, Severity: DXGI_INFO_QUEUE_MESSAGE_SEVERITY, pDescription: ?[*:0]const u8) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).AddApplicationMessage(@ptrCast(*const IDXGIInfoQueue, self), Severity, pDescription);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_SetBreakOnCategory(self: *const T, Producer: Guid, Category: DXGI_INFO_QUEUE_MESSAGE_CATEGORY, bEnable: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).SetBreakOnCategory(@ptrCast(*const IDXGIInfoQueue, self), Producer, Category, bEnable);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_SetBreakOnSeverity(self: *const T, Producer: Guid, Severity: DXGI_INFO_QUEUE_MESSAGE_SEVERITY, bEnable: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).SetBreakOnSeverity(@ptrCast(*const IDXGIInfoQueue, self), Producer, Severity, bEnable);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_SetBreakOnID(self: *const T, Producer: Guid, ID: i32, bEnable: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).SetBreakOnID(@ptrCast(*const IDXGIInfoQueue, self), Producer, ID, bEnable);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_GetBreakOnCategory(self: *const T, Producer: Guid, Category: DXGI_INFO_QUEUE_MESSAGE_CATEGORY) callconv(.Inline) BOOL {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).GetBreakOnCategory(@ptrCast(*const IDXGIInfoQueue, self), Producer, Category);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_GetBreakOnSeverity(self: *const T, Producer: Guid, Severity: DXGI_INFO_QUEUE_MESSAGE_SEVERITY) callconv(.Inline) BOOL {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).GetBreakOnSeverity(@ptrCast(*const IDXGIInfoQueue, self), Producer, Severity);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_GetBreakOnID(self: *const T, Producer: Guid, ID: i32) callconv(.Inline) BOOL {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).GetBreakOnID(@ptrCast(*const IDXGIInfoQueue, self), Producer, ID);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_SetMuteDebugOutput(self: *const T, Producer: Guid, bMute: BOOL) callconv(.Inline) void {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).SetMuteDebugOutput(@ptrCast(*const IDXGIInfoQueue, self), Producer, bMute);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIInfoQueue_GetMuteDebugOutput(self: *const T, Producer: Guid) callconv(.Inline) BOOL {
return @ptrCast(*const IDXGIInfoQueue.VTable, self.vtable).GetMuteDebugOutput(@ptrCast(*const IDXGIInfoQueue, self), Producer);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IDXGIDebug_Value = Guid.initString("119e7452-de9e-40fe-8806-88f90c12b441");
pub const IID_IDXGIDebug = &IID_IDXGIDebug_Value;
pub const IDXGIDebug = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
ReportLiveObjects: fn(
self: *const IDXGIDebug,
apiid: Guid,
flags: DXGI_DEBUG_RLO_FLAGS,
) 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 IDXGIDebug_ReportLiveObjects(self: *const T, apiid: Guid, flags: DXGI_DEBUG_RLO_FLAGS) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXGIDebug.VTable, self.vtable).ReportLiveObjects(@ptrCast(*const IDXGIDebug, self), apiid, flags);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.1'
const IID_IDXGIDebug1_Value = Guid.initString("c5a05f0c-16f2-4adf-9f4d-a8c4d58ac550");
pub const IID_IDXGIDebug1 = &IID_IDXGIDebug1_Value;
pub const IDXGIDebug1 = extern struct {
pub const VTable = extern struct {
base: IDXGIDebug.VTable,
EnableLeakTrackingForThread: fn(
self: *const IDXGIDebug1,
) callconv(@import("std").os.windows.WINAPI) void,
DisableLeakTrackingForThread: fn(
self: *const IDXGIDebug1,
) callconv(@import("std").os.windows.WINAPI) void,
IsLeakTrackingEnabledForThread: fn(
self: *const IDXGIDebug1,
) callconv(@import("std").os.windows.WINAPI) BOOL,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDXGIDebug.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIDebug1_EnableLeakTrackingForThread(self: *const T) callconv(.Inline) void {
return @ptrCast(*const IDXGIDebug1.VTable, self.vtable).EnableLeakTrackingForThread(@ptrCast(*const IDXGIDebug1, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIDebug1_DisableLeakTrackingForThread(self: *const T) callconv(.Inline) void {
return @ptrCast(*const IDXGIDebug1.VTable, self.vtable).DisableLeakTrackingForThread(@ptrCast(*const IDXGIDebug1, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGIDebug1_IsLeakTrackingEnabledForThread(self: *const T) callconv(.Inline) BOOL {
return @ptrCast(*const IDXGIDebug1.VTable, self.vtable).IsLeakTrackingEnabledForThread(@ptrCast(*const IDXGIDebug1, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DXGI_Message_Id = enum(i32) {
IDXGISwapChain_CreationOrResizeBuffers_InvalidOutputWindow = 0,
IDXGISwapChain_CreationOrResizeBuffers_BufferWidthInferred = 1,
IDXGISwapChain_CreationOrResizeBuffers_BufferHeightInferred = 2,
IDXGISwapChain_CreationOrResizeBuffers_NoScanoutFlagChanged = 3,
IDXGISwapChain_Creation_MaxBufferCountExceeded = 4,
IDXGISwapChain_Creation_TooFewBuffers = 5,
IDXGISwapChain_Creation_NoOutputWindow = 6,
IDXGISwapChain_Destruction_OtherMethodsCalled = 7,
IDXGISwapChain_GetDesc_pDescIsNULL = 8,
IDXGISwapChain_GetBuffer_ppSurfaceIsNULL = 9,
IDXGISwapChain_GetBuffer_NoAllocatedBuffers = 10,
IDXGISwapChain_GetBuffer_iBufferMustBeZero = 11,
IDXGISwapChain_GetBuffer_iBufferOOB = 12,
IDXGISwapChain_GetContainingOutput_ppOutputIsNULL = 13,
IDXGISwapChain_Present_SyncIntervalOOB = 14,
IDXGISwapChain_Present_InvalidNonPreRotatedFlag = 15,
IDXGISwapChain_Present_NoAllocatedBuffers = 16,
IDXGISwapChain_Present_GetDXGIAdapterFailed = 17,
IDXGISwapChain_ResizeBuffers_BufferCountOOB = 18,
IDXGISwapChain_ResizeBuffers_UnreleasedReferences = 19,
IDXGISwapChain_ResizeBuffers_InvalidSwapChainFlag = 20,
IDXGISwapChain_ResizeBuffers_InvalidNonPreRotatedFlag = 21,
IDXGISwapChain_ResizeTarget_RefreshRateDivideByZero = 22,
IDXGISwapChain_SetFullscreenState_InvalidTarget = 23,
IDXGISwapChain_GetFrameStatistics_pStatsIsNULL = 24,
IDXGISwapChain_GetLastPresentCount_pLastPresentCountIsNULL = 25,
IDXGISwapChain_SetFullscreenState_RemoteNotSupported = 26,
IDXGIOutput_TakeOwnership_FailedToAcquireFullscreenMutex = 27,
IDXGIFactory_CreateSoftwareAdapter_ppAdapterInterfaceIsNULL = 28,
IDXGIFactory_EnumAdapters_ppAdapterInterfaceIsNULL = 29,
IDXGIFactory_CreateSwapChain_ppSwapChainIsNULL = 30,
IDXGIFactory_CreateSwapChain_pDescIsNULL = 31,
IDXGIFactory_CreateSwapChain_UnknownSwapEffect = 32,
IDXGIFactory_CreateSwapChain_InvalidFlags = 33,
IDXGIFactory_CreateSwapChain_NonPreRotatedFlagAndWindowed = 34,
IDXGIFactory_CreateSwapChain_NullDeviceInterface = 35,
IDXGIFactory_GetWindowAssociation_phWndIsNULL = 36,
IDXGIFactory_MakeWindowAssociation_InvalidFlags = 37,
IDXGISurface_Map_InvalidSurface = 38,
IDXGISurface_Map_FlagsSetToZero = 39,
IDXGISurface_Map_DiscardAndReadFlagSet = 40,
IDXGISurface_Map_DiscardButNotWriteFlagSet = 41,
IDXGISurface_Map_NoCPUAccess = 42,
IDXGISurface_Map_ReadFlagSetButCPUAccessIsDynamic = 43,
IDXGISurface_Map_DiscardFlagSetButCPUAccessIsNotDynamic = 44,
IDXGIOutput_GetDisplayModeList_pNumModesIsNULL = 45,
IDXGIOutput_FindClosestMatchingMode_ModeHasInvalidWidthOrHeight = 46,
IDXGIOutput_GetCammaControlCapabilities_NoOwnerDevice = 47,
IDXGIOutput_TakeOwnership_pDeviceIsNULL = 48,
IDXGIOutput_GetDisplaySurfaceData_NoOwnerDevice = 49,
IDXGIOutput_GetDisplaySurfaceData_pDestinationIsNULL = 50,
IDXGIOutput_GetDisplaySurfaceData_MapOfDestinationFailed = 51,
IDXGIOutput_GetFrameStatistics_NoOwnerDevice = 52,
IDXGIOutput_GetFrameStatistics_pStatsIsNULL = 53,
IDXGIOutput_SetGammaControl_NoOwnerDevice = 54,
IDXGIOutput_GetGammaControl_NoOwnerDevice = 55,
IDXGIOutput_GetGammaControl_NoGammaControls = 56,
IDXGIOutput_SetDisplaySurface_IDXGIResourceNotSupportedBypPrimary = 57,
IDXGIOutput_SetDisplaySurface_pPrimaryIsInvalid = 58,
IDXGIOutput_SetDisplaySurface_NoOwnerDevice = 59,
IDXGIOutput_TakeOwnership_RemoteDeviceNotSupported = 60,
IDXGIOutput_GetDisplayModeList_RemoteDeviceNotSupported = 61,
IDXGIOutput_FindClosestMatchingMode_RemoteDeviceNotSupported = 62,
IDXGIDevice_CreateSurface_InvalidParametersWithpSharedResource = 63,
IDXGIObject_GetPrivateData_puiDataSizeIsNULL = 64,
IDXGISwapChain_Creation_InvalidOutputWindow = 65,
IDXGISwapChain_Release_SwapChainIsFullscreen = 66,
IDXGIOutput_GetDisplaySurfaceData_InvalidTargetSurfaceFormat = 67,
IDXGIFactory_CreateSoftwareAdapter_ModuleIsNULL = 68,
IDXGIOutput_FindClosestMatchingMode_IDXGIDeviceNotSupportedBypConcernedDevice = 69,
IDXGIOutput_FindClosestMatchingMode_pModeToMatchOrpClosestMatchIsNULL = 70,
IDXGIOutput_FindClosestMatchingMode_ModeHasRefreshRateDenominatorZero = 71,
IDXGIOutput_FindClosestMatchingMode_UnknownFormatIsInvalidForConfiguration = 72,
IDXGIOutput_FindClosestMatchingMode_InvalidDisplayModeScanlineOrdering = 73,
IDXGIOutput_FindClosestMatchingMode_InvalidDisplayModeScaling = 74,
IDXGIOutput_FindClosestMatchingMode_InvalidDisplayModeFormatAndDeviceCombination = 75,
IDXGIFactory_Creation_CalledFromDllMain = 76,
IDXGISwapChain_SetFullscreenState_OutputNotOwnedBySwapChainDevice = 77,
IDXGISwapChain_Creation_InvalidWindowStyle = 78,
IDXGISwapChain_GetFrameStatistics_UnsupportedStatistics = 79,
IDXGISwapChain_GetContainingOutput_SwapchainAdapterDoesNotControlOutput = 80,
IDXGIOutput_SetOrGetGammaControl_pArrayIsNULL = 81,
IDXGISwapChain_SetFullscreenState_FullscreenInvalidForChildWindows = 82,
IDXGIFactory_Release_CalledFromDllMain = 83,
IDXGISwapChain_Present_UnreleasedHDC = 84,
IDXGISwapChain_ResizeBuffers_NonPreRotatedAndGDICompatibleFlags = 85,
IDXGIFactory_CreateSwapChain_NonPreRotatedAndGDICompatibleFlags = 86,
IDXGISurface1_GetDC_pHdcIsNULL = 87,
IDXGISurface1_GetDC_SurfaceNotTexture2D = 88,
IDXGISurface1_GetDC_GDICompatibleFlagNotSet = 89,
IDXGISurface1_GetDC_UnreleasedHDC = 90,
IDXGISurface_Map_NoCPUAccess2 = 91,
IDXGISurface1_ReleaseDC_GetDCNotCalled = 92,
IDXGISurface1_ReleaseDC_InvalidRectangleDimensions = 93,
IDXGIOutput_TakeOwnership_RemoteOutputNotSupported = 94,
IDXGIOutput_FindClosestMatchingMode_RemoteOutputNotSupported = 95,
IDXGIOutput_GetDisplayModeList_RemoteOutputNotSupported = 96,
IDXGIFactory_CreateSwapChain_pDeviceHasMismatchedDXGIFactory = 97,
IDXGISwapChain_Present_NonOptimalFSConfiguration = 98,
IDXGIFactory_CreateSwapChain_FlipSequentialNotSupportedOnD3D10 = 99,
IDXGIFactory_CreateSwapChain_BufferCountOOBForFlipSequential = 100,
IDXGIFactory_CreateSwapChain_InvalidFormatForFlipSequential = 101,
IDXGIFactory_CreateSwapChain_MultiSamplingNotSupportedForFlipSequential = 102,
IDXGISwapChain_ResizeBuffers_BufferCountOOBForFlipSequential = 103,
IDXGISwapChain_ResizeBuffers_InvalidFormatForFlipSequential = 104,
IDXGISwapChain_Present_PartialPresentationBeforeStandardPresentation = 105,
IDXGISwapChain_Present_FullscreenPartialPresentIsInvalid = 106,
IDXGISwapChain_Present_InvalidPresentTestOrDoNotSequenceFlag = 107,
IDXGISwapChain_Present_ScrollInfoWithNoDirtyRectsSpecified = 108,
IDXGISwapChain_Present_EmptyScrollRect = 109,
IDXGISwapChain_Present_ScrollRectOutOfBackbufferBounds = 110,
IDXGISwapChain_Present_ScrollRectOutOfBackbufferBoundsWithOffset = 111,
IDXGISwapChain_Present_EmptyDirtyRect = 112,
IDXGISwapChain_Present_DirtyRectOutOfBackbufferBounds = 113,
IDXGIFactory_CreateSwapChain_UnsupportedBufferUsageFlags = 114,
IDXGISwapChain_Present_DoNotSequenceFlagSetButPreviousBufferIsUndefined = 115,
IDXGISwapChain_Present_UnsupportedFlags = 116,
IDXGISwapChain_Present_FlipModelChainMustResizeOrCreateOnFSTransition = 117,
IDXGIFactory_CreateSwapChain_pRestrictToOutputFromOtherIDXGIFactory = 118,
IDXGIFactory_CreateSwapChain_RestrictOutputNotSupportedOnAdapter = 119,
IDXGISwapChain_Present_RestrictToOutputFlagSetButInvalidpRestrictToOutput = 120,
IDXGISwapChain_Present_RestrictToOutputFlagdWithFullscreen = 121,
IDXGISwapChain_Present_RestrictOutputFlagWithStaleSwapChain = 122,
IDXGISwapChain_Present_OtherFlagsCausingInvalidPresentTestFlag = 123,
IDXGIFactory_CreateSwapChain_UnavailableInSession0 = 124,
IDXGIFactory_MakeWindowAssociation_UnavailableInSession0 = 125,
IDXGIFactory_GetWindowAssociation_UnavailableInSession0 = 126,
IDXGIAdapter_EnumOutputs_UnavailableInSession0 = 127,
IDXGISwapChain_CreationOrSetFullscreenState_StereoDisabled = 128,
IDXGIFactory2_UnregisterStatus_CookieNotFound = 129,
IDXGISwapChain_Present_ProtectedContentInWindowedModeWithoutFSOrOverlay = 130,
IDXGISwapChain_Present_ProtectedContentInWindowedModeWithoutFlipSequential = 131,
IDXGISwapChain_Present_ProtectedContentWithRDPDriver = 132,
IDXGISwapChain_Present_ProtectedContentInWindowedModeWithDWMOffOrInvalidDisplayAffinity = 133,
IDXGIFactory_CreateSwapChainForComposition_WidthOrHeightIsZero = 134,
IDXGIFactory_CreateSwapChainForComposition_OnlyFlipSequentialSupported = 135,
IDXGIFactory_CreateSwapChainForComposition_UnsupportedOnAdapter = 136,
IDXGIFactory_CreateSwapChainForComposition_UnsupportedOnWindows7 = 137,
IDXGISwapChain_SetFullscreenState_FSTransitionWithCompositionSwapChain = 138,
IDXGISwapChain_ResizeTarget_InvalidWithCompositionSwapChain = 139,
IDXGISwapChain_ResizeBuffers_WidthOrHeightIsZero = 140,
IDXGIFactory_CreateSwapChain_ScalingNoneIsFlipModelOnly = 141,
IDXGIFactory_CreateSwapChain_ScalingUnrecognized = 142,
IDXGIFactory_CreateSwapChain_DisplayOnlyFullscreenUnsupported = 143,
IDXGIFactory_CreateSwapChain_DisplayOnlyUnsupported = 144,
IDXGISwapChain_Present_RestartIsFullscreenOnly = 145,
IDXGISwapChain_Present_ProtectedWindowlessPresentationRequiresDisplayOnly = 146,
IDXGISwapChain_SetFullscreenState_DisplayOnlyUnsupported = 147,
IDXGISwapChain1_SetBackgroundColor_OutOfRange = 148,
IDXGISwapChain_ResizeBuffers_DisplayOnlyFullscreenUnsupported = 149,
IDXGISwapChain_ResizeBuffers_DisplayOnlyUnsupported = 150,
IDXGISwapchain_Present_ScrollUnsupported = 151,
IDXGISwapChain1_SetRotation_UnsupportedOS = 152,
IDXGISwapChain1_GetRotation_UnsupportedOS = 153,
IDXGISwapchain_Present_FullscreenRotation = 154,
IDXGISwapChain_Present_PartialPresentationWithMSAABuffers = 155,
IDXGISwapChain1_SetRotation_FlipSequentialRequired = 156,
IDXGISwapChain1_SetRotation_InvalidRotation = 157,
IDXGISwapChain1_GetRotation_FlipSequentialRequired = 158,
IDXGISwapChain_GetHwnd_WrongType = 159,
IDXGISwapChain_GetCompositionSurface_WrongType = 160,
IDXGISwapChain_GetCoreWindow_WrongType = 161,
IDXGISwapChain_GetFullscreenDesc_NonHwnd = 162,
IDXGISwapChain_SetFullscreenState_CoreWindow = 163,
IDXGIFactory2_CreateSwapChainForCoreWindow_UnsupportedOnWindows7 = 164,
IDXGIFactory2_CreateSwapChainForCoreWindow_pWindowIsNULL = 165,
IDXGIFactory_CreateSwapChain_FSUnsupportedForModernApps = 166,
IDXGIFactory_MakeWindowAssociation_ModernApp = 167,
IDXGISwapChain_ResizeTarget_ModernApp = 168,
IDXGISwapChain_ResizeTarget_pNewTargetParametersIsNULL = 169,
IDXGIOutput_SetDisplaySurface_ModernApp = 170,
IDXGIOutput_TakeOwnership_ModernApp = 171,
IDXGIFactory2_CreateSwapChainForCoreWindow_pWindowIsInvalid = 172,
IDXGIFactory2_CreateSwapChainForCompositionSurface_InvalidHandle = 173,
IDXGISurface1_GetDC_ModernApp = 174,
IDXGIFactory_CreateSwapChain_ScalingNoneRequiresWindows8OrNewer = 175,
IDXGISwapChain_Present_TemporaryMonoAndPreferRight = 176,
IDXGISwapChain_Present_TemporaryMonoOrPreferRightWithDoNotSequence = 177,
IDXGISwapChain_Present_TemporaryMonoOrPreferRightWithoutStereo = 178,
IDXGISwapChain_Present_TemporaryMonoUnsupported = 179,
IDXGIOutput_GetDisplaySurfaceData_ArraySizeMismatch = 180,
IDXGISwapChain_Present_PartialPresentationWithSwapEffectDiscard = 181,
IDXGIFactory_CreateSwapChain_AlphaUnrecognized = 182,
IDXGIFactory_CreateSwapChain_AlphaIsWindowlessOnly = 183,
IDXGIFactory_CreateSwapChain_AlphaIsFlipModelOnly = 184,
IDXGIFactory_CreateSwapChain_RestrictToOutputAdapterMismatch = 185,
IDXGIFactory_CreateSwapChain_DisplayOnlyOnLegacy = 186,
IDXGISwapChain_ResizeBuffers_DisplayOnlyOnLegacy = 187,
IDXGIResource1_CreateSubresourceSurface_InvalidIndex = 188,
IDXGIFactory_CreateSwapChainForComposition_InvalidScaling = 189,
IDXGIFactory_CreateSwapChainForCoreWindow_InvalidSwapEffect = 190,
IDXGIResource1_CreateSharedHandle_UnsupportedOS = 191,
IDXGIFactory2_RegisterOcclusionStatusWindow_UnsupportedOS = 192,
IDXGIFactory2_RegisterOcclusionStatusEvent_UnsupportedOS = 193,
IDXGIOutput1_DuplicateOutput_UnsupportedOS = 194,
IDXGIDisplayControl_IsStereoEnabled_UnsupportedOS = 195,
IDXGIFactory_CreateSwapChainForComposition_InvalidAlphaMode = 196,
IDXGIFactory_GetSharedResourceAdapterLuid_InvalidResource = 197,
IDXGIFactory_GetSharedResourceAdapterLuid_InvalidLUID = 198,
IDXGIFactory_GetSharedResourceAdapterLuid_UnsupportedOS = 199,
IDXGIOutput1_GetDisplaySurfaceData1_2DOnly = 200,
IDXGIOutput1_GetDisplaySurfaceData1_StagingOnly = 201,
IDXGIOutput1_GetDisplaySurfaceData1_NeedCPUAccessWrite = 202,
IDXGIOutput1_GetDisplaySurfaceData1_NoShared = 203,
IDXGIOutput1_GetDisplaySurfaceData1_OnlyMipLevels1 = 204,
IDXGIOutput1_GetDisplaySurfaceData1_MappedOrOfferedResource = 205,
IDXGISwapChain_SetFullscreenState_FSUnsupportedForModernApps = 206,
IDXGIFactory_CreateSwapChain_FailedToGoFSButNonPreRotated = 207,
IDXGIFactory_CreateSwapChainOrRegisterOcclusionStatus_BlitModelUsedWhileRegisteredForOcclusionStatusEvents = 208,
IDXGISwapChain_Present_BlitModelUsedWhileRegisteredForOcclusionStatusEvents = 209,
IDXGIFactory_CreateSwapChain_WaitableSwapChainsAreFlipModelOnly = 210,
IDXGIFactory_CreateSwapChain_WaitableSwapChainsAreNotFullscreen = 211,
IDXGISwapChain_SetFullscreenState_Waitable = 212,
IDXGISwapChain_ResizeBuffers_CannotAddOrRemoveWaitableFlag = 213,
IDXGISwapChain_GetFrameLatencyWaitableObject_OnlyWaitable = 214,
IDXGISwapChain_GetMaximumFrameLatency_OnlyWaitable = 215,
IDXGISwapChain_GetMaximumFrameLatency_pMaxLatencyIsNULL = 216,
IDXGISwapChain_SetMaximumFrameLatency_OnlyWaitable = 217,
IDXGISwapChain_SetMaximumFrameLatency_MaxLatencyIsOutOfBounds = 218,
IDXGIFactory_CreateSwapChain_ForegroundIsCoreWindowOnly = 219,
IDXGIFactory2_CreateSwapChainForCoreWindow_ForegroundUnsupportedOnAdapter = 220,
IDXGIFactory2_CreateSwapChainForCoreWindow_InvalidScaling = 221,
IDXGIFactory2_CreateSwapChainForCoreWindow_InvalidAlphaMode = 222,
IDXGISwapChain_ResizeBuffers_CannotAddOrRemoveForegroundFlag = 223,
IDXGISwapChain_SetMatrixTransform_MatrixPointerCannotBeNull = 224,
IDXGISwapChain_SetMatrixTransform_RequiresCompositionSwapChain = 225,
IDXGISwapChain_SetMatrixTransform_MatrixMustBeFinite = 226,
IDXGISwapChain_SetMatrixTransform_MatrixMustBeTranslateAndOrScale = 227,
IDXGISwapChain_GetMatrixTransform_MatrixPointerCannotBeNull = 228,
IDXGISwapChain_GetMatrixTransform_RequiresCompositionSwapChain = 229,
DXGIGetDebugInterface1_NULL_ppDebug = 230,
DXGIGetDebugInterface1_InvalidFlags = 231,
IDXGISwapChain_Present_Decode = 232,
IDXGISwapChain_ResizeBuffers_Decode = 233,
IDXGISwapChain_SetSourceSize_FlipModel = 234,
IDXGISwapChain_SetSourceSize_Decode = 235,
IDXGISwapChain_SetSourceSize_WidthHeight = 236,
IDXGISwapChain_GetSourceSize_NullPointers = 237,
IDXGISwapChain_GetSourceSize_Decode = 238,
IDXGIDecodeSwapChain_SetColorSpace_InvalidFlags = 239,
IDXGIDecodeSwapChain_SetSourceRect_InvalidRect = 240,
IDXGIDecodeSwapChain_SetTargetRect_InvalidRect = 241,
IDXGIDecodeSwapChain_SetDestSize_InvalidSize = 242,
IDXGIDecodeSwapChain_GetSourceRect_InvalidPointer = 243,
IDXGIDecodeSwapChain_GetTargetRect_InvalidPointer = 244,
IDXGIDecodeSwapChain_GetDestSize_InvalidPointer = 245,
IDXGISwapChain_PresentBuffer_YUV = 246,
IDXGISwapChain_SetSourceSize_YUV = 247,
IDXGISwapChain_GetSourceSize_YUV = 248,
IDXGISwapChain_SetMatrixTransform_YUV = 249,
IDXGISwapChain_GetMatrixTransform_YUV = 250,
IDXGISwapChain_Present_PartialPresentation_YUV = 251,
IDXGISwapChain_ResizeBuffers_CannotAddOrRemoveFlag_YUV = 252,
IDXGISwapChain_ResizeBuffers_Alignment_YUV = 253,
IDXGIFactory_CreateSwapChain_ShaderInputUnsupported_YUV = 254,
IDXGIOutput3_CheckOverlaySupport_NullPointers = 255,
IDXGIOutput3_CheckOverlaySupport_IDXGIDeviceNotSupportedBypConcernedDevice = 256,
IDXGIAdapter_EnumOutputs2_InvalidEnumOutputs2Flag = 257,
IDXGISwapChain_CreationOrSetFullscreenState_FSUnsupportedForFlipDiscard = 258,
IDXGIOutput4_CheckOverlayColorSpaceSupport_NullPointers = 259,
IDXGIOutput4_CheckOverlayColorSpaceSupport_IDXGIDeviceNotSupportedBypConcernedDevice = 260,
IDXGISwapChain3_CheckColorSpaceSupport_NullPointers = 261,
IDXGISwapChain3_SetColorSpace1_InvalidColorSpace = 262,
IDXGIFactory_CreateSwapChain_InvalidHwProtect = 263,
IDXGIFactory_CreateSwapChain_HwProtectUnsupported = 264,
IDXGISwapChain_ResizeBuffers_InvalidHwProtect = 265,
IDXGISwapChain_ResizeBuffers_HwProtectUnsupported = 266,
IDXGISwapChain_ResizeBuffers1_D3D12Only = 267,
IDXGISwapChain_ResizeBuffers1_FlipModel = 268,
IDXGISwapChain_ResizeBuffers1_NodeMaskAndQueueRequired = 269,
IDXGISwapChain_CreateSwapChain_InvalidHwProtectGdiFlag = 270,
IDXGISwapChain_ResizeBuffers_InvalidHwProtectGdiFlag = 271,
IDXGIFactory_CreateSwapChain_10BitFormatNotSupported = 272,
IDXGIFactory_CreateSwapChain_FlipSwapEffectRequired = 273,
IDXGIFactory_CreateSwapChain_InvalidDevice = 274,
IDXGIOutput_TakeOwnership_Unsupported = 275,
IDXGIFactory_CreateSwapChain_InvalidQueue = 276,
IDXGISwapChain3_ResizeBuffers1_InvalidQueue = 277,
IDXGIFactory_CreateSwapChainForHwnd_InvalidScaling = 278,
IDXGISwapChain3_SetHDRMetaData_InvalidSize = 279,
IDXGISwapChain3_SetHDRMetaData_InvalidPointer = 280,
IDXGISwapChain3_SetHDRMetaData_InvalidType = 281,
IDXGISwapChain_Present_FullscreenAllowTearingIsInvalid = 282,
IDXGISwapChain_Present_AllowTearingRequiresPresentIntervalZero = 283,
IDXGISwapChain_Present_AllowTearingRequiresCreationFlag = 284,
IDXGISwapChain_ResizeBuffers_CannotAddOrRemoveAllowTearingFlag = 285,
IDXGIFactory_CreateSwapChain_AllowTearingFlagIsFlipModelOnly = 286,
IDXGIFactory_CheckFeatureSupport_InvalidFeature = 287,
IDXGIFactory_CheckFeatureSupport_InvalidSize = 288,
IDXGIOutput6_CheckHardwareCompositionSupport_NullPointer = 289,
IDXGISwapChain_SetFullscreenState_PerMonitorDpiShimApplied = 290,
IDXGIOutput_DuplicateOutput_PerMonitorDpiShimApplied = 291,
IDXGIOutput_DuplicateOutput1_PerMonitorDpiRequired = 292,
IDXGIFactory7_UnregisterAdaptersChangedEvent_CookieNotFound = 293,
IDXGIFactory_CreateSwapChain_LegacyBltModelSwapEffect = 294,
IDXGISwapChain4_SetHDRMetaData_MetadataUnchanged = 295,
IDXGISwapChain_Present_11On12_Released_Resource = 296,
IDXGIFactory_CreateSwapChain_MultipleSwapchainRefToSurface_DeferredDtr = 297,
IDXGIFactory_MakeWindowAssociation_NoOpBehavior = 298,
Phone_IDXGIFactory_CreateSwapChain_NotForegroundWindow = 1000,
Phone_IDXGIFactory_CreateSwapChain_DISCARD_BufferCount = 1001,
Phone_IDXGISwapChain_SetFullscreenState_NotAvailable = 1002,
Phone_IDXGISwapChain_ResizeBuffers_NotAvailable = 1003,
Phone_IDXGISwapChain_ResizeTarget_NotAvailable = 1004,
Phone_IDXGISwapChain_Present_InvalidLayerIndex = 1005,
Phone_IDXGISwapChain_Present_MultipleLayerIndex = 1006,
Phone_IDXGISwapChain_Present_InvalidLayerFlag = 1007,
Phone_IDXGISwapChain_Present_InvalidRotation = 1008,
Phone_IDXGISwapChain_Present_InvalidBlend = 1009,
Phone_IDXGISwapChain_Present_InvalidResource = 1010,
Phone_IDXGISwapChain_Present_InvalidMultiPlaneOverlayResource = 1011,
Phone_IDXGISwapChain_Present_InvalidIndexForPrimary = 1012,
Phone_IDXGISwapChain_Present_InvalidIndexForOverlay = 1013,
Phone_IDXGISwapChain_Present_InvalidSubResourceIndex = 1014,
Phone_IDXGISwapChain_Present_InvalidSourceRect = 1015,
Phone_IDXGISwapChain_Present_InvalidDestinationRect = 1016,
Phone_IDXGISwapChain_Present_MultipleResource = 1017,
Phone_IDXGISwapChain_Present_NotSharedResource = 1018,
Phone_IDXGISwapChain_Present_InvalidFlag = 1019,
Phone_IDXGISwapChain_Present_InvalidInterval = 1020,
Phone_IDXGIFactory_CreateSwapChain_MSAA_NotSupported = 1021,
Phone_IDXGIFactory_CreateSwapChain_ScalingAspectRatioStretch_Supported_ModernApp = 1022,
Phone_IDXGISwapChain_GetFrameStatistics_NotAvailable_ModernApp = 1023,
Phone_IDXGISwapChain_Present_ReplaceInterval0With1 = 1024,
Phone_IDXGIFactory_CreateSwapChain_FailedRegisterWithCompositor = 1025,
Phone_IDXGIFactory_CreateSwapChain_NotForegroundWindow_AtRendering = 1026,
Phone_IDXGIFactory_CreateSwapChain_FLIP_SEQUENTIAL_BufferCount = 1027,
Phone_IDXGIFactory_CreateSwapChain_FLIP_Modern_CoreWindow_Only = 1028,
Phone_IDXGISwapChain_Present1_RequiresOverlays = 1029,
Phone_IDXGISwapChain_SetBackgroundColor_FlipSequentialRequired = 1030,
Phone_IDXGISwapChain_GetBackgroundColor_FlipSequentialRequired = 1031,
};
pub const DXGI_MSG_IDXGISwapChain_CreationOrResizeBuffers_InvalidOutputWindow = DXGI_Message_Id.IDXGISwapChain_CreationOrResizeBuffers_InvalidOutputWindow;
pub const DXGI_MSG_IDXGISwapChain_CreationOrResizeBuffers_BufferWidthInferred = DXGI_Message_Id.IDXGISwapChain_CreationOrResizeBuffers_BufferWidthInferred;
pub const DXGI_MSG_IDXGISwapChain_CreationOrResizeBuffers_BufferHeightInferred = DXGI_Message_Id.IDXGISwapChain_CreationOrResizeBuffers_BufferHeightInferred;
pub const DXGI_MSG_IDXGISwapChain_CreationOrResizeBuffers_NoScanoutFlagChanged = DXGI_Message_Id.IDXGISwapChain_CreationOrResizeBuffers_NoScanoutFlagChanged;
pub const DXGI_MSG_IDXGISwapChain_Creation_MaxBufferCountExceeded = DXGI_Message_Id.IDXGISwapChain_Creation_MaxBufferCountExceeded;
pub const DXGI_MSG_IDXGISwapChain_Creation_TooFewBuffers = DXGI_Message_Id.IDXGISwapChain_Creation_TooFewBuffers;
pub const DXGI_MSG_IDXGISwapChain_Creation_NoOutputWindow = DXGI_Message_Id.IDXGISwapChain_Creation_NoOutputWindow;
pub const DXGI_MSG_IDXGISwapChain_Destruction_OtherMethodsCalled = DXGI_Message_Id.IDXGISwapChain_Destruction_OtherMethodsCalled;
pub const DXGI_MSG_IDXGISwapChain_GetDesc_pDescIsNULL = DXGI_Message_Id.IDXGISwapChain_GetDesc_pDescIsNULL;
pub const DXGI_MSG_IDXGISwapChain_GetBuffer_ppSurfaceIsNULL = DXGI_Message_Id.IDXGISwapChain_GetBuffer_ppSurfaceIsNULL;
pub const DXGI_MSG_IDXGISwapChain_GetBuffer_NoAllocatedBuffers = DXGI_Message_Id.IDXGISwapChain_GetBuffer_NoAllocatedBuffers;
pub const DXGI_MSG_IDXGISwapChain_GetBuffer_iBufferMustBeZero = DXGI_Message_Id.IDXGISwapChain_GetBuffer_iBufferMustBeZero;
pub const DXGI_MSG_IDXGISwapChain_GetBuffer_iBufferOOB = DXGI_Message_Id.IDXGISwapChain_GetBuffer_iBufferOOB;
pub const DXGI_MSG_IDXGISwapChain_GetContainingOutput_ppOutputIsNULL = DXGI_Message_Id.IDXGISwapChain_GetContainingOutput_ppOutputIsNULL;
pub const DXGI_MSG_IDXGISwapChain_Present_SyncIntervalOOB = DXGI_Message_Id.IDXGISwapChain_Present_SyncIntervalOOB;
pub const DXGI_MSG_IDXGISwapChain_Present_InvalidNonPreRotatedFlag = DXGI_Message_Id.IDXGISwapChain_Present_InvalidNonPreRotatedFlag;
pub const DXGI_MSG_IDXGISwapChain_Present_NoAllocatedBuffers = DXGI_Message_Id.IDXGISwapChain_Present_NoAllocatedBuffers;
pub const DXGI_MSG_IDXGISwapChain_Present_GetDXGIAdapterFailed = DXGI_Message_Id.IDXGISwapChain_Present_GetDXGIAdapterFailed;
pub const DXGI_MSG_IDXGISwapChain_ResizeBuffers_BufferCountOOB = DXGI_Message_Id.IDXGISwapChain_ResizeBuffers_BufferCountOOB;
pub const DXGI_MSG_IDXGISwapChain_ResizeBuffers_UnreleasedReferences = DXGI_Message_Id.IDXGISwapChain_ResizeBuffers_UnreleasedReferences;
pub const DXGI_MSG_IDXGISwapChain_ResizeBuffers_InvalidSwapChainFlag = DXGI_Message_Id.IDXGISwapChain_ResizeBuffers_InvalidSwapChainFlag;
pub const DXGI_MSG_IDXGISwapChain_ResizeBuffers_InvalidNonPreRotatedFlag = DXGI_Message_Id.IDXGISwapChain_ResizeBuffers_InvalidNonPreRotatedFlag;
pub const DXGI_MSG_IDXGISwapChain_ResizeTarget_RefreshRateDivideByZero = DXGI_Message_Id.IDXGISwapChain_ResizeTarget_RefreshRateDivideByZero;
pub const DXGI_MSG_IDXGISwapChain_SetFullscreenState_InvalidTarget = DXGI_Message_Id.IDXGISwapChain_SetFullscreenState_InvalidTarget;
pub const DXGI_MSG_IDXGISwapChain_GetFrameStatistics_pStatsIsNULL = DXGI_Message_Id.IDXGISwapChain_GetFrameStatistics_pStatsIsNULL;
pub const DXGI_MSG_IDXGISwapChain_GetLastPresentCount_pLastPresentCountIsNULL = DXGI_Message_Id.IDXGISwapChain_GetLastPresentCount_pLastPresentCountIsNULL;
pub const DXGI_MSG_IDXGISwapChain_SetFullscreenState_RemoteNotSupported = DXGI_Message_Id.IDXGISwapChain_SetFullscreenState_RemoteNotSupported;
pub const DXGI_MSG_IDXGIOutput_TakeOwnership_FailedToAcquireFullscreenMutex = DXGI_Message_Id.IDXGIOutput_TakeOwnership_FailedToAcquireFullscreenMutex;
pub const DXGI_MSG_IDXGIFactory_CreateSoftwareAdapter_ppAdapterInterfaceIsNULL = DXGI_Message_Id.IDXGIFactory_CreateSoftwareAdapter_ppAdapterInterfaceIsNULL;
pub const DXGI_MSG_IDXGIFactory_EnumAdapters_ppAdapterInterfaceIsNULL = DXGI_Message_Id.IDXGIFactory_EnumAdapters_ppAdapterInterfaceIsNULL;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_ppSwapChainIsNULL = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_ppSwapChainIsNULL;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_pDescIsNULL = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_pDescIsNULL;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_UnknownSwapEffect = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_UnknownSwapEffect;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_InvalidFlags = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_InvalidFlags;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_NonPreRotatedFlagAndWindowed = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_NonPreRotatedFlagAndWindowed;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_NullDeviceInterface = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_NullDeviceInterface;
pub const DXGI_MSG_IDXGIFactory_GetWindowAssociation_phWndIsNULL = DXGI_Message_Id.IDXGIFactory_GetWindowAssociation_phWndIsNULL;
pub const DXGI_MSG_IDXGIFactory_MakeWindowAssociation_InvalidFlags = DXGI_Message_Id.IDXGIFactory_MakeWindowAssociation_InvalidFlags;
pub const DXGI_MSG_IDXGISurface_Map_InvalidSurface = DXGI_Message_Id.IDXGISurface_Map_InvalidSurface;
pub const DXGI_MSG_IDXGISurface_Map_FlagsSetToZero = DXGI_Message_Id.IDXGISurface_Map_FlagsSetToZero;
pub const DXGI_MSG_IDXGISurface_Map_DiscardAndReadFlagSet = DXGI_Message_Id.IDXGISurface_Map_DiscardAndReadFlagSet;
pub const DXGI_MSG_IDXGISurface_Map_DiscardButNotWriteFlagSet = DXGI_Message_Id.IDXGISurface_Map_DiscardButNotWriteFlagSet;
pub const DXGI_MSG_IDXGISurface_Map_NoCPUAccess = DXGI_Message_Id.IDXGISurface_Map_NoCPUAccess;
pub const DXGI_MSG_IDXGISurface_Map_ReadFlagSetButCPUAccessIsDynamic = DXGI_Message_Id.IDXGISurface_Map_ReadFlagSetButCPUAccessIsDynamic;
pub const DXGI_MSG_IDXGISurface_Map_DiscardFlagSetButCPUAccessIsNotDynamic = DXGI_Message_Id.IDXGISurface_Map_DiscardFlagSetButCPUAccessIsNotDynamic;
pub const DXGI_MSG_IDXGIOutput_GetDisplayModeList_pNumModesIsNULL = DXGI_Message_Id.IDXGIOutput_GetDisplayModeList_pNumModesIsNULL;
pub const DXGI_MSG_IDXGIOutput_FindClosestMatchingMode_ModeHasInvalidWidthOrHeight = DXGI_Message_Id.IDXGIOutput_FindClosestMatchingMode_ModeHasInvalidWidthOrHeight;
pub const DXGI_MSG_IDXGIOutput_GetCammaControlCapabilities_NoOwnerDevice = DXGI_Message_Id.IDXGIOutput_GetCammaControlCapabilities_NoOwnerDevice;
pub const DXGI_MSG_IDXGIOutput_TakeOwnership_pDeviceIsNULL = DXGI_Message_Id.IDXGIOutput_TakeOwnership_pDeviceIsNULL;
pub const DXGI_MSG_IDXGIOutput_GetDisplaySurfaceData_NoOwnerDevice = DXGI_Message_Id.IDXGIOutput_GetDisplaySurfaceData_NoOwnerDevice;
pub const DXGI_MSG_IDXGIOutput_GetDisplaySurfaceData_pDestinationIsNULL = DXGI_Message_Id.IDXGIOutput_GetDisplaySurfaceData_pDestinationIsNULL;
pub const DXGI_MSG_IDXGIOutput_GetDisplaySurfaceData_MapOfDestinationFailed = DXGI_Message_Id.IDXGIOutput_GetDisplaySurfaceData_MapOfDestinationFailed;
pub const DXGI_MSG_IDXGIOutput_GetFrameStatistics_NoOwnerDevice = DXGI_Message_Id.IDXGIOutput_GetFrameStatistics_NoOwnerDevice;
pub const DXGI_MSG_IDXGIOutput_GetFrameStatistics_pStatsIsNULL = DXGI_Message_Id.IDXGIOutput_GetFrameStatistics_pStatsIsNULL;
pub const DXGI_MSG_IDXGIOutput_SetGammaControl_NoOwnerDevice = DXGI_Message_Id.IDXGIOutput_SetGammaControl_NoOwnerDevice;
pub const DXGI_MSG_IDXGIOutput_GetGammaControl_NoOwnerDevice = DXGI_Message_Id.IDXGIOutput_GetGammaControl_NoOwnerDevice;
pub const DXGI_MSG_IDXGIOutput_GetGammaControl_NoGammaControls = DXGI_Message_Id.IDXGIOutput_GetGammaControl_NoGammaControls;
pub const DXGI_MSG_IDXGIOutput_SetDisplaySurface_IDXGIResourceNotSupportedBypPrimary = DXGI_Message_Id.IDXGIOutput_SetDisplaySurface_IDXGIResourceNotSupportedBypPrimary;
pub const DXGI_MSG_IDXGIOutput_SetDisplaySurface_pPrimaryIsInvalid = DXGI_Message_Id.IDXGIOutput_SetDisplaySurface_pPrimaryIsInvalid;
pub const DXGI_MSG_IDXGIOutput_SetDisplaySurface_NoOwnerDevice = DXGI_Message_Id.IDXGIOutput_SetDisplaySurface_NoOwnerDevice;
pub const DXGI_MSG_IDXGIOutput_TakeOwnership_RemoteDeviceNotSupported = DXGI_Message_Id.IDXGIOutput_TakeOwnership_RemoteDeviceNotSupported;
pub const DXGI_MSG_IDXGIOutput_GetDisplayModeList_RemoteDeviceNotSupported = DXGI_Message_Id.IDXGIOutput_GetDisplayModeList_RemoteDeviceNotSupported;
pub const DXGI_MSG_IDXGIOutput_FindClosestMatchingMode_RemoteDeviceNotSupported = DXGI_Message_Id.IDXGIOutput_FindClosestMatchingMode_RemoteDeviceNotSupported;
pub const DXGI_MSG_IDXGIDevice_CreateSurface_InvalidParametersWithpSharedResource = DXGI_Message_Id.IDXGIDevice_CreateSurface_InvalidParametersWithpSharedResource;
pub const DXGI_MSG_IDXGIObject_GetPrivateData_puiDataSizeIsNULL = DXGI_Message_Id.IDXGIObject_GetPrivateData_puiDataSizeIsNULL;
pub const DXGI_MSG_IDXGISwapChain_Creation_InvalidOutputWindow = DXGI_Message_Id.IDXGISwapChain_Creation_InvalidOutputWindow;
pub const DXGI_MSG_IDXGISwapChain_Release_SwapChainIsFullscreen = DXGI_Message_Id.IDXGISwapChain_Release_SwapChainIsFullscreen;
pub const DXGI_MSG_IDXGIOutput_GetDisplaySurfaceData_InvalidTargetSurfaceFormat = DXGI_Message_Id.IDXGIOutput_GetDisplaySurfaceData_InvalidTargetSurfaceFormat;
pub const DXGI_MSG_IDXGIFactory_CreateSoftwareAdapter_ModuleIsNULL = DXGI_Message_Id.IDXGIFactory_CreateSoftwareAdapter_ModuleIsNULL;
pub const DXGI_MSG_IDXGIOutput_FindClosestMatchingMode_IDXGIDeviceNotSupportedBypConcernedDevice = DXGI_Message_Id.IDXGIOutput_FindClosestMatchingMode_IDXGIDeviceNotSupportedBypConcernedDevice;
pub const DXGI_MSG_IDXGIOutput_FindClosestMatchingMode_pModeToMatchOrpClosestMatchIsNULL = DXGI_Message_Id.IDXGIOutput_FindClosestMatchingMode_pModeToMatchOrpClosestMatchIsNULL;
pub const DXGI_MSG_IDXGIOutput_FindClosestMatchingMode_ModeHasRefreshRateDenominatorZero = DXGI_Message_Id.IDXGIOutput_FindClosestMatchingMode_ModeHasRefreshRateDenominatorZero;
pub const DXGI_MSG_IDXGIOutput_FindClosestMatchingMode_UnknownFormatIsInvalidForConfiguration = DXGI_Message_Id.IDXGIOutput_FindClosestMatchingMode_UnknownFormatIsInvalidForConfiguration;
pub const DXGI_MSG_IDXGIOutput_FindClosestMatchingMode_InvalidDisplayModeScanlineOrdering = DXGI_Message_Id.IDXGIOutput_FindClosestMatchingMode_InvalidDisplayModeScanlineOrdering;
pub const DXGI_MSG_IDXGIOutput_FindClosestMatchingMode_InvalidDisplayModeScaling = DXGI_Message_Id.IDXGIOutput_FindClosestMatchingMode_InvalidDisplayModeScaling;
pub const DXGI_MSG_IDXGIOutput_FindClosestMatchingMode_InvalidDisplayModeFormatAndDeviceCombination = DXGI_Message_Id.IDXGIOutput_FindClosestMatchingMode_InvalidDisplayModeFormatAndDeviceCombination;
pub const DXGI_MSG_IDXGIFactory_Creation_CalledFromDllMain = DXGI_Message_Id.IDXGIFactory_Creation_CalledFromDllMain;
pub const DXGI_MSG_IDXGISwapChain_SetFullscreenState_OutputNotOwnedBySwapChainDevice = DXGI_Message_Id.IDXGISwapChain_SetFullscreenState_OutputNotOwnedBySwapChainDevice;
pub const DXGI_MSG_IDXGISwapChain_Creation_InvalidWindowStyle = DXGI_Message_Id.IDXGISwapChain_Creation_InvalidWindowStyle;
pub const DXGI_MSG_IDXGISwapChain_GetFrameStatistics_UnsupportedStatistics = DXGI_Message_Id.IDXGISwapChain_GetFrameStatistics_UnsupportedStatistics;
pub const DXGI_MSG_IDXGISwapChain_GetContainingOutput_SwapchainAdapterDoesNotControlOutput = DXGI_Message_Id.IDXGISwapChain_GetContainingOutput_SwapchainAdapterDoesNotControlOutput;
pub const DXGI_MSG_IDXGIOutput_SetOrGetGammaControl_pArrayIsNULL = DXGI_Message_Id.IDXGIOutput_SetOrGetGammaControl_pArrayIsNULL;
pub const DXGI_MSG_IDXGISwapChain_SetFullscreenState_FullscreenInvalidForChildWindows = DXGI_Message_Id.IDXGISwapChain_SetFullscreenState_FullscreenInvalidForChildWindows;
pub const DXGI_MSG_IDXGIFactory_Release_CalledFromDllMain = DXGI_Message_Id.IDXGIFactory_Release_CalledFromDllMain;
pub const DXGI_MSG_IDXGISwapChain_Present_UnreleasedHDC = DXGI_Message_Id.IDXGISwapChain_Present_UnreleasedHDC;
pub const DXGI_MSG_IDXGISwapChain_ResizeBuffers_NonPreRotatedAndGDICompatibleFlags = DXGI_Message_Id.IDXGISwapChain_ResizeBuffers_NonPreRotatedAndGDICompatibleFlags;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_NonPreRotatedAndGDICompatibleFlags = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_NonPreRotatedAndGDICompatibleFlags;
pub const DXGI_MSG_IDXGISurface1_GetDC_pHdcIsNULL = DXGI_Message_Id.IDXGISurface1_GetDC_pHdcIsNULL;
pub const DXGI_MSG_IDXGISurface1_GetDC_SurfaceNotTexture2D = DXGI_Message_Id.IDXGISurface1_GetDC_SurfaceNotTexture2D;
pub const DXGI_MSG_IDXGISurface1_GetDC_GDICompatibleFlagNotSet = DXGI_Message_Id.IDXGISurface1_GetDC_GDICompatibleFlagNotSet;
pub const DXGI_MSG_IDXGISurface1_GetDC_UnreleasedHDC = DXGI_Message_Id.IDXGISurface1_GetDC_UnreleasedHDC;
pub const DXGI_MSG_IDXGISurface_Map_NoCPUAccess2 = DXGI_Message_Id.IDXGISurface_Map_NoCPUAccess2;
pub const DXGI_MSG_IDXGISurface1_ReleaseDC_GetDCNotCalled = DXGI_Message_Id.IDXGISurface1_ReleaseDC_GetDCNotCalled;
pub const DXGI_MSG_IDXGISurface1_ReleaseDC_InvalidRectangleDimensions = DXGI_Message_Id.IDXGISurface1_ReleaseDC_InvalidRectangleDimensions;
pub const DXGI_MSG_IDXGIOutput_TakeOwnership_RemoteOutputNotSupported = DXGI_Message_Id.IDXGIOutput_TakeOwnership_RemoteOutputNotSupported;
pub const DXGI_MSG_IDXGIOutput_FindClosestMatchingMode_RemoteOutputNotSupported = DXGI_Message_Id.IDXGIOutput_FindClosestMatchingMode_RemoteOutputNotSupported;
pub const DXGI_MSG_IDXGIOutput_GetDisplayModeList_RemoteOutputNotSupported = DXGI_Message_Id.IDXGIOutput_GetDisplayModeList_RemoteOutputNotSupported;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_pDeviceHasMismatchedDXGIFactory = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_pDeviceHasMismatchedDXGIFactory;
pub const DXGI_MSG_IDXGISwapChain_Present_NonOptimalFSConfiguration = DXGI_Message_Id.IDXGISwapChain_Present_NonOptimalFSConfiguration;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_FlipSequentialNotSupportedOnD3D10 = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_FlipSequentialNotSupportedOnD3D10;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_BufferCountOOBForFlipSequential = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_BufferCountOOBForFlipSequential;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_InvalidFormatForFlipSequential = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_InvalidFormatForFlipSequential;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_MultiSamplingNotSupportedForFlipSequential = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_MultiSamplingNotSupportedForFlipSequential;
pub const DXGI_MSG_IDXGISwapChain_ResizeBuffers_BufferCountOOBForFlipSequential = DXGI_Message_Id.IDXGISwapChain_ResizeBuffers_BufferCountOOBForFlipSequential;
pub const DXGI_MSG_IDXGISwapChain_ResizeBuffers_InvalidFormatForFlipSequential = DXGI_Message_Id.IDXGISwapChain_ResizeBuffers_InvalidFormatForFlipSequential;
pub const DXGI_MSG_IDXGISwapChain_Present_PartialPresentationBeforeStandardPresentation = DXGI_Message_Id.IDXGISwapChain_Present_PartialPresentationBeforeStandardPresentation;
pub const DXGI_MSG_IDXGISwapChain_Present_FullscreenPartialPresentIsInvalid = DXGI_Message_Id.IDXGISwapChain_Present_FullscreenPartialPresentIsInvalid;
pub const DXGI_MSG_IDXGISwapChain_Present_InvalidPresentTestOrDoNotSequenceFlag = DXGI_Message_Id.IDXGISwapChain_Present_InvalidPresentTestOrDoNotSequenceFlag;
pub const DXGI_MSG_IDXGISwapChain_Present_ScrollInfoWithNoDirtyRectsSpecified = DXGI_Message_Id.IDXGISwapChain_Present_ScrollInfoWithNoDirtyRectsSpecified;
pub const DXGI_MSG_IDXGISwapChain_Present_EmptyScrollRect = DXGI_Message_Id.IDXGISwapChain_Present_EmptyScrollRect;
pub const DXGI_MSG_IDXGISwapChain_Present_ScrollRectOutOfBackbufferBounds = DXGI_Message_Id.IDXGISwapChain_Present_ScrollRectOutOfBackbufferBounds;
pub const DXGI_MSG_IDXGISwapChain_Present_ScrollRectOutOfBackbufferBoundsWithOffset = DXGI_Message_Id.IDXGISwapChain_Present_ScrollRectOutOfBackbufferBoundsWithOffset;
pub const DXGI_MSG_IDXGISwapChain_Present_EmptyDirtyRect = DXGI_Message_Id.IDXGISwapChain_Present_EmptyDirtyRect;
pub const DXGI_MSG_IDXGISwapChain_Present_DirtyRectOutOfBackbufferBounds = DXGI_Message_Id.IDXGISwapChain_Present_DirtyRectOutOfBackbufferBounds;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_UnsupportedBufferUsageFlags = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_UnsupportedBufferUsageFlags;
pub const DXGI_MSG_IDXGISwapChain_Present_DoNotSequenceFlagSetButPreviousBufferIsUndefined = DXGI_Message_Id.IDXGISwapChain_Present_DoNotSequenceFlagSetButPreviousBufferIsUndefined;
pub const DXGI_MSG_IDXGISwapChain_Present_UnsupportedFlags = DXGI_Message_Id.IDXGISwapChain_Present_UnsupportedFlags;
pub const DXGI_MSG_IDXGISwapChain_Present_FlipModelChainMustResizeOrCreateOnFSTransition = DXGI_Message_Id.IDXGISwapChain_Present_FlipModelChainMustResizeOrCreateOnFSTransition;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_pRestrictToOutputFromOtherIDXGIFactory = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_pRestrictToOutputFromOtherIDXGIFactory;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_RestrictOutputNotSupportedOnAdapter = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_RestrictOutputNotSupportedOnAdapter;
pub const DXGI_MSG_IDXGISwapChain_Present_RestrictToOutputFlagSetButInvalidpRestrictToOutput = DXGI_Message_Id.IDXGISwapChain_Present_RestrictToOutputFlagSetButInvalidpRestrictToOutput;
pub const DXGI_MSG_IDXGISwapChain_Present_RestrictToOutputFlagdWithFullscreen = DXGI_Message_Id.IDXGISwapChain_Present_RestrictToOutputFlagdWithFullscreen;
pub const DXGI_MSG_IDXGISwapChain_Present_RestrictOutputFlagWithStaleSwapChain = DXGI_Message_Id.IDXGISwapChain_Present_RestrictOutputFlagWithStaleSwapChain;
pub const DXGI_MSG_IDXGISwapChain_Present_OtherFlagsCausingInvalidPresentTestFlag = DXGI_Message_Id.IDXGISwapChain_Present_OtherFlagsCausingInvalidPresentTestFlag;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_UnavailableInSession0 = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_UnavailableInSession0;
pub const DXGI_MSG_IDXGIFactory_MakeWindowAssociation_UnavailableInSession0 = DXGI_Message_Id.IDXGIFactory_MakeWindowAssociation_UnavailableInSession0;
pub const DXGI_MSG_IDXGIFactory_GetWindowAssociation_UnavailableInSession0 = DXGI_Message_Id.IDXGIFactory_GetWindowAssociation_UnavailableInSession0;
pub const DXGI_MSG_IDXGIAdapter_EnumOutputs_UnavailableInSession0 = DXGI_Message_Id.IDXGIAdapter_EnumOutputs_UnavailableInSession0;
pub const DXGI_MSG_IDXGISwapChain_CreationOrSetFullscreenState_StereoDisabled = DXGI_Message_Id.IDXGISwapChain_CreationOrSetFullscreenState_StereoDisabled;
pub const DXGI_MSG_IDXGIFactory2_UnregisterStatus_CookieNotFound = DXGI_Message_Id.IDXGIFactory2_UnregisterStatus_CookieNotFound;
pub const DXGI_MSG_IDXGISwapChain_Present_ProtectedContentInWindowedModeWithoutFSOrOverlay = DXGI_Message_Id.IDXGISwapChain_Present_ProtectedContentInWindowedModeWithoutFSOrOverlay;
pub const DXGI_MSG_IDXGISwapChain_Present_ProtectedContentInWindowedModeWithoutFlipSequential = DXGI_Message_Id.IDXGISwapChain_Present_ProtectedContentInWindowedModeWithoutFlipSequential;
pub const DXGI_MSG_IDXGISwapChain_Present_ProtectedContentWithRDPDriver = DXGI_Message_Id.IDXGISwapChain_Present_ProtectedContentWithRDPDriver;
pub const DXGI_MSG_IDXGISwapChain_Present_ProtectedContentInWindowedModeWithDWMOffOrInvalidDisplayAffinity = DXGI_Message_Id.IDXGISwapChain_Present_ProtectedContentInWindowedModeWithDWMOffOrInvalidDisplayAffinity;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChainForComposition_WidthOrHeightIsZero = DXGI_Message_Id.IDXGIFactory_CreateSwapChainForComposition_WidthOrHeightIsZero;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChainForComposition_OnlyFlipSequentialSupported = DXGI_Message_Id.IDXGIFactory_CreateSwapChainForComposition_OnlyFlipSequentialSupported;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChainForComposition_UnsupportedOnAdapter = DXGI_Message_Id.IDXGIFactory_CreateSwapChainForComposition_UnsupportedOnAdapter;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChainForComposition_UnsupportedOnWindows7 = DXGI_Message_Id.IDXGIFactory_CreateSwapChainForComposition_UnsupportedOnWindows7;
pub const DXGI_MSG_IDXGISwapChain_SetFullscreenState_FSTransitionWithCompositionSwapChain = DXGI_Message_Id.IDXGISwapChain_SetFullscreenState_FSTransitionWithCompositionSwapChain;
pub const DXGI_MSG_IDXGISwapChain_ResizeTarget_InvalidWithCompositionSwapChain = DXGI_Message_Id.IDXGISwapChain_ResizeTarget_InvalidWithCompositionSwapChain;
pub const DXGI_MSG_IDXGISwapChain_ResizeBuffers_WidthOrHeightIsZero = DXGI_Message_Id.IDXGISwapChain_ResizeBuffers_WidthOrHeightIsZero;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_ScalingNoneIsFlipModelOnly = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_ScalingNoneIsFlipModelOnly;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_ScalingUnrecognized = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_ScalingUnrecognized;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_DisplayOnlyFullscreenUnsupported = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_DisplayOnlyFullscreenUnsupported;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_DisplayOnlyUnsupported = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_DisplayOnlyUnsupported;
pub const DXGI_MSG_IDXGISwapChain_Present_RestartIsFullscreenOnly = DXGI_Message_Id.IDXGISwapChain_Present_RestartIsFullscreenOnly;
pub const DXGI_MSG_IDXGISwapChain_Present_ProtectedWindowlessPresentationRequiresDisplayOnly = DXGI_Message_Id.IDXGISwapChain_Present_ProtectedWindowlessPresentationRequiresDisplayOnly;
pub const DXGI_MSG_IDXGISwapChain_SetFullscreenState_DisplayOnlyUnsupported = DXGI_Message_Id.IDXGISwapChain_SetFullscreenState_DisplayOnlyUnsupported;
pub const DXGI_MSG_IDXGISwapChain1_SetBackgroundColor_OutOfRange = DXGI_Message_Id.IDXGISwapChain1_SetBackgroundColor_OutOfRange;
pub const DXGI_MSG_IDXGISwapChain_ResizeBuffers_DisplayOnlyFullscreenUnsupported = DXGI_Message_Id.IDXGISwapChain_ResizeBuffers_DisplayOnlyFullscreenUnsupported;
pub const DXGI_MSG_IDXGISwapChain_ResizeBuffers_DisplayOnlyUnsupported = DXGI_Message_Id.IDXGISwapChain_ResizeBuffers_DisplayOnlyUnsupported;
pub const DXGI_MSG_IDXGISwapchain_Present_ScrollUnsupported = DXGI_Message_Id.IDXGISwapchain_Present_ScrollUnsupported;
pub const DXGI_MSG_IDXGISwapChain1_SetRotation_UnsupportedOS = DXGI_Message_Id.IDXGISwapChain1_SetRotation_UnsupportedOS;
pub const DXGI_MSG_IDXGISwapChain1_GetRotation_UnsupportedOS = DXGI_Message_Id.IDXGISwapChain1_GetRotation_UnsupportedOS;
pub const DXGI_MSG_IDXGISwapchain_Present_FullscreenRotation = DXGI_Message_Id.IDXGISwapchain_Present_FullscreenRotation;
pub const DXGI_MSG_IDXGISwapChain_Present_PartialPresentationWithMSAABuffers = DXGI_Message_Id.IDXGISwapChain_Present_PartialPresentationWithMSAABuffers;
pub const DXGI_MSG_IDXGISwapChain1_SetRotation_FlipSequentialRequired = DXGI_Message_Id.IDXGISwapChain1_SetRotation_FlipSequentialRequired;
pub const DXGI_MSG_IDXGISwapChain1_SetRotation_InvalidRotation = DXGI_Message_Id.IDXGISwapChain1_SetRotation_InvalidRotation;
pub const DXGI_MSG_IDXGISwapChain1_GetRotation_FlipSequentialRequired = DXGI_Message_Id.IDXGISwapChain1_GetRotation_FlipSequentialRequired;
pub const DXGI_MSG_IDXGISwapChain_GetHwnd_WrongType = DXGI_Message_Id.IDXGISwapChain_GetHwnd_WrongType;
pub const DXGI_MSG_IDXGISwapChain_GetCompositionSurface_WrongType = DXGI_Message_Id.IDXGISwapChain_GetCompositionSurface_WrongType;
pub const DXGI_MSG_IDXGISwapChain_GetCoreWindow_WrongType = DXGI_Message_Id.IDXGISwapChain_GetCoreWindow_WrongType;
pub const DXGI_MSG_IDXGISwapChain_GetFullscreenDesc_NonHwnd = DXGI_Message_Id.IDXGISwapChain_GetFullscreenDesc_NonHwnd;
pub const DXGI_MSG_IDXGISwapChain_SetFullscreenState_CoreWindow = DXGI_Message_Id.IDXGISwapChain_SetFullscreenState_CoreWindow;
pub const DXGI_MSG_IDXGIFactory2_CreateSwapChainForCoreWindow_UnsupportedOnWindows7 = DXGI_Message_Id.IDXGIFactory2_CreateSwapChainForCoreWindow_UnsupportedOnWindows7;
pub const DXGI_MSG_IDXGIFactory2_CreateSwapChainForCoreWindow_pWindowIsNULL = DXGI_Message_Id.IDXGIFactory2_CreateSwapChainForCoreWindow_pWindowIsNULL;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_FSUnsupportedForModernApps = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_FSUnsupportedForModernApps;
pub const DXGI_MSG_IDXGIFactory_MakeWindowAssociation_ModernApp = DXGI_Message_Id.IDXGIFactory_MakeWindowAssociation_ModernApp;
pub const DXGI_MSG_IDXGISwapChain_ResizeTarget_ModernApp = DXGI_Message_Id.IDXGISwapChain_ResizeTarget_ModernApp;
pub const DXGI_MSG_IDXGISwapChain_ResizeTarget_pNewTargetParametersIsNULL = DXGI_Message_Id.IDXGISwapChain_ResizeTarget_pNewTargetParametersIsNULL;
pub const DXGI_MSG_IDXGIOutput_SetDisplaySurface_ModernApp = DXGI_Message_Id.IDXGIOutput_SetDisplaySurface_ModernApp;
pub const DXGI_MSG_IDXGIOutput_TakeOwnership_ModernApp = DXGI_Message_Id.IDXGIOutput_TakeOwnership_ModernApp;
pub const DXGI_MSG_IDXGIFactory2_CreateSwapChainForCoreWindow_pWindowIsInvalid = DXGI_Message_Id.IDXGIFactory2_CreateSwapChainForCoreWindow_pWindowIsInvalid;
pub const DXGI_MSG_IDXGIFactory2_CreateSwapChainForCompositionSurface_InvalidHandle = DXGI_Message_Id.IDXGIFactory2_CreateSwapChainForCompositionSurface_InvalidHandle;
pub const DXGI_MSG_IDXGISurface1_GetDC_ModernApp = DXGI_Message_Id.IDXGISurface1_GetDC_ModernApp;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_ScalingNoneRequiresWindows8OrNewer = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_ScalingNoneRequiresWindows8OrNewer;
pub const DXGI_MSG_IDXGISwapChain_Present_TemporaryMonoAndPreferRight = DXGI_Message_Id.IDXGISwapChain_Present_TemporaryMonoAndPreferRight;
pub const DXGI_MSG_IDXGISwapChain_Present_TemporaryMonoOrPreferRightWithDoNotSequence = DXGI_Message_Id.IDXGISwapChain_Present_TemporaryMonoOrPreferRightWithDoNotSequence;
pub const DXGI_MSG_IDXGISwapChain_Present_TemporaryMonoOrPreferRightWithoutStereo = DXGI_Message_Id.IDXGISwapChain_Present_TemporaryMonoOrPreferRightWithoutStereo;
pub const DXGI_MSG_IDXGISwapChain_Present_TemporaryMonoUnsupported = DXGI_Message_Id.IDXGISwapChain_Present_TemporaryMonoUnsupported;
pub const DXGI_MSG_IDXGIOutput_GetDisplaySurfaceData_ArraySizeMismatch = DXGI_Message_Id.IDXGIOutput_GetDisplaySurfaceData_ArraySizeMismatch;
pub const DXGI_MSG_IDXGISwapChain_Present_PartialPresentationWithSwapEffectDiscard = DXGI_Message_Id.IDXGISwapChain_Present_PartialPresentationWithSwapEffectDiscard;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_AlphaUnrecognized = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_AlphaUnrecognized;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_AlphaIsWindowlessOnly = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_AlphaIsWindowlessOnly;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_AlphaIsFlipModelOnly = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_AlphaIsFlipModelOnly;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_RestrictToOutputAdapterMismatch = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_RestrictToOutputAdapterMismatch;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_DisplayOnlyOnLegacy = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_DisplayOnlyOnLegacy;
pub const DXGI_MSG_IDXGISwapChain_ResizeBuffers_DisplayOnlyOnLegacy = DXGI_Message_Id.IDXGISwapChain_ResizeBuffers_DisplayOnlyOnLegacy;
pub const DXGI_MSG_IDXGIResource1_CreateSubresourceSurface_InvalidIndex = DXGI_Message_Id.IDXGIResource1_CreateSubresourceSurface_InvalidIndex;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChainForComposition_InvalidScaling = DXGI_Message_Id.IDXGIFactory_CreateSwapChainForComposition_InvalidScaling;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChainForCoreWindow_InvalidSwapEffect = DXGI_Message_Id.IDXGIFactory_CreateSwapChainForCoreWindow_InvalidSwapEffect;
pub const DXGI_MSG_IDXGIResource1_CreateSharedHandle_UnsupportedOS = DXGI_Message_Id.IDXGIResource1_CreateSharedHandle_UnsupportedOS;
pub const DXGI_MSG_IDXGIFactory2_RegisterOcclusionStatusWindow_UnsupportedOS = DXGI_Message_Id.IDXGIFactory2_RegisterOcclusionStatusWindow_UnsupportedOS;
pub const DXGI_MSG_IDXGIFactory2_RegisterOcclusionStatusEvent_UnsupportedOS = DXGI_Message_Id.IDXGIFactory2_RegisterOcclusionStatusEvent_UnsupportedOS;
pub const DXGI_MSG_IDXGIOutput1_DuplicateOutput_UnsupportedOS = DXGI_Message_Id.IDXGIOutput1_DuplicateOutput_UnsupportedOS;
pub const DXGI_MSG_IDXGIDisplayControl_IsStereoEnabled_UnsupportedOS = DXGI_Message_Id.IDXGIDisplayControl_IsStereoEnabled_UnsupportedOS;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChainForComposition_InvalidAlphaMode = DXGI_Message_Id.IDXGIFactory_CreateSwapChainForComposition_InvalidAlphaMode;
pub const DXGI_MSG_IDXGIFactory_GetSharedResourceAdapterLuid_InvalidResource = DXGI_Message_Id.IDXGIFactory_GetSharedResourceAdapterLuid_InvalidResource;
pub const DXGI_MSG_IDXGIFactory_GetSharedResourceAdapterLuid_InvalidLUID = DXGI_Message_Id.IDXGIFactory_GetSharedResourceAdapterLuid_InvalidLUID;
pub const DXGI_MSG_IDXGIFactory_GetSharedResourceAdapterLuid_UnsupportedOS = DXGI_Message_Id.IDXGIFactory_GetSharedResourceAdapterLuid_UnsupportedOS;
pub const DXGI_MSG_IDXGIOutput1_GetDisplaySurfaceData1_2DOnly = DXGI_Message_Id.IDXGIOutput1_GetDisplaySurfaceData1_2DOnly;
pub const DXGI_MSG_IDXGIOutput1_GetDisplaySurfaceData1_StagingOnly = DXGI_Message_Id.IDXGIOutput1_GetDisplaySurfaceData1_StagingOnly;
pub const DXGI_MSG_IDXGIOutput1_GetDisplaySurfaceData1_NeedCPUAccessWrite = DXGI_Message_Id.IDXGIOutput1_GetDisplaySurfaceData1_NeedCPUAccessWrite;
pub const DXGI_MSG_IDXGIOutput1_GetDisplaySurfaceData1_NoShared = DXGI_Message_Id.IDXGIOutput1_GetDisplaySurfaceData1_NoShared;
pub const DXGI_MSG_IDXGIOutput1_GetDisplaySurfaceData1_OnlyMipLevels1 = DXGI_Message_Id.IDXGIOutput1_GetDisplaySurfaceData1_OnlyMipLevels1;
pub const DXGI_MSG_IDXGIOutput1_GetDisplaySurfaceData1_MappedOrOfferedResource = DXGI_Message_Id.IDXGIOutput1_GetDisplaySurfaceData1_MappedOrOfferedResource;
pub const DXGI_MSG_IDXGISwapChain_SetFullscreenState_FSUnsupportedForModernApps = DXGI_Message_Id.IDXGISwapChain_SetFullscreenState_FSUnsupportedForModernApps;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_FailedToGoFSButNonPreRotated = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_FailedToGoFSButNonPreRotated;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChainOrRegisterOcclusionStatus_BlitModelUsedWhileRegisteredForOcclusionStatusEvents = DXGI_Message_Id.IDXGIFactory_CreateSwapChainOrRegisterOcclusionStatus_BlitModelUsedWhileRegisteredForOcclusionStatusEvents;
pub const DXGI_MSG_IDXGISwapChain_Present_BlitModelUsedWhileRegisteredForOcclusionStatusEvents = DXGI_Message_Id.IDXGISwapChain_Present_BlitModelUsedWhileRegisteredForOcclusionStatusEvents;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_WaitableSwapChainsAreFlipModelOnly = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_WaitableSwapChainsAreFlipModelOnly;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_WaitableSwapChainsAreNotFullscreen = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_WaitableSwapChainsAreNotFullscreen;
pub const DXGI_MSG_IDXGISwapChain_SetFullscreenState_Waitable = DXGI_Message_Id.IDXGISwapChain_SetFullscreenState_Waitable;
pub const DXGI_MSG_IDXGISwapChain_ResizeBuffers_CannotAddOrRemoveWaitableFlag = DXGI_Message_Id.IDXGISwapChain_ResizeBuffers_CannotAddOrRemoveWaitableFlag;
pub const DXGI_MSG_IDXGISwapChain_GetFrameLatencyWaitableObject_OnlyWaitable = DXGI_Message_Id.IDXGISwapChain_GetFrameLatencyWaitableObject_OnlyWaitable;
pub const DXGI_MSG_IDXGISwapChain_GetMaximumFrameLatency_OnlyWaitable = DXGI_Message_Id.IDXGISwapChain_GetMaximumFrameLatency_OnlyWaitable;
pub const DXGI_MSG_IDXGISwapChain_GetMaximumFrameLatency_pMaxLatencyIsNULL = DXGI_Message_Id.IDXGISwapChain_GetMaximumFrameLatency_pMaxLatencyIsNULL;
pub const DXGI_MSG_IDXGISwapChain_SetMaximumFrameLatency_OnlyWaitable = DXGI_Message_Id.IDXGISwapChain_SetMaximumFrameLatency_OnlyWaitable;
pub const DXGI_MSG_IDXGISwapChain_SetMaximumFrameLatency_MaxLatencyIsOutOfBounds = DXGI_Message_Id.IDXGISwapChain_SetMaximumFrameLatency_MaxLatencyIsOutOfBounds;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_ForegroundIsCoreWindowOnly = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_ForegroundIsCoreWindowOnly;
pub const DXGI_MSG_IDXGIFactory2_CreateSwapChainForCoreWindow_ForegroundUnsupportedOnAdapter = DXGI_Message_Id.IDXGIFactory2_CreateSwapChainForCoreWindow_ForegroundUnsupportedOnAdapter;
pub const DXGI_MSG_IDXGIFactory2_CreateSwapChainForCoreWindow_InvalidScaling = DXGI_Message_Id.IDXGIFactory2_CreateSwapChainForCoreWindow_InvalidScaling;
pub const DXGI_MSG_IDXGIFactory2_CreateSwapChainForCoreWindow_InvalidAlphaMode = DXGI_Message_Id.IDXGIFactory2_CreateSwapChainForCoreWindow_InvalidAlphaMode;
pub const DXGI_MSG_IDXGISwapChain_ResizeBuffers_CannotAddOrRemoveForegroundFlag = DXGI_Message_Id.IDXGISwapChain_ResizeBuffers_CannotAddOrRemoveForegroundFlag;
pub const DXGI_MSG_IDXGISwapChain_SetMatrixTransform_MatrixPointerCannotBeNull = DXGI_Message_Id.IDXGISwapChain_SetMatrixTransform_MatrixPointerCannotBeNull;
pub const DXGI_MSG_IDXGISwapChain_SetMatrixTransform_RequiresCompositionSwapChain = DXGI_Message_Id.IDXGISwapChain_SetMatrixTransform_RequiresCompositionSwapChain;
pub const DXGI_MSG_IDXGISwapChain_SetMatrixTransform_MatrixMustBeFinite = DXGI_Message_Id.IDXGISwapChain_SetMatrixTransform_MatrixMustBeFinite;
pub const DXGI_MSG_IDXGISwapChain_SetMatrixTransform_MatrixMustBeTranslateAndOrScale = DXGI_Message_Id.IDXGISwapChain_SetMatrixTransform_MatrixMustBeTranslateAndOrScale;
pub const DXGI_MSG_IDXGISwapChain_GetMatrixTransform_MatrixPointerCannotBeNull = DXGI_Message_Id.IDXGISwapChain_GetMatrixTransform_MatrixPointerCannotBeNull;
pub const DXGI_MSG_IDXGISwapChain_GetMatrixTransform_RequiresCompositionSwapChain = DXGI_Message_Id.IDXGISwapChain_GetMatrixTransform_RequiresCompositionSwapChain;
pub const DXGI_MSG_DXGIGetDebugInterface1_NULL_ppDebug = DXGI_Message_Id.DXGIGetDebugInterface1_NULL_ppDebug;
pub const DXGI_MSG_DXGIGetDebugInterface1_InvalidFlags = DXGI_Message_Id.DXGIGetDebugInterface1_InvalidFlags;
pub const DXGI_MSG_IDXGISwapChain_Present_Decode = DXGI_Message_Id.IDXGISwapChain_Present_Decode;
pub const DXGI_MSG_IDXGISwapChain_ResizeBuffers_Decode = DXGI_Message_Id.IDXGISwapChain_ResizeBuffers_Decode;
pub const DXGI_MSG_IDXGISwapChain_SetSourceSize_FlipModel = DXGI_Message_Id.IDXGISwapChain_SetSourceSize_FlipModel;
pub const DXGI_MSG_IDXGISwapChain_SetSourceSize_Decode = DXGI_Message_Id.IDXGISwapChain_SetSourceSize_Decode;
pub const DXGI_MSG_IDXGISwapChain_SetSourceSize_WidthHeight = DXGI_Message_Id.IDXGISwapChain_SetSourceSize_WidthHeight;
pub const DXGI_MSG_IDXGISwapChain_GetSourceSize_NullPointers = DXGI_Message_Id.IDXGISwapChain_GetSourceSize_NullPointers;
pub const DXGI_MSG_IDXGISwapChain_GetSourceSize_Decode = DXGI_Message_Id.IDXGISwapChain_GetSourceSize_Decode;
pub const DXGI_MSG_IDXGIDecodeSwapChain_SetColorSpace_InvalidFlags = DXGI_Message_Id.IDXGIDecodeSwapChain_SetColorSpace_InvalidFlags;
pub const DXGI_MSG_IDXGIDecodeSwapChain_SetSourceRect_InvalidRect = DXGI_Message_Id.IDXGIDecodeSwapChain_SetSourceRect_InvalidRect;
pub const DXGI_MSG_IDXGIDecodeSwapChain_SetTargetRect_InvalidRect = DXGI_Message_Id.IDXGIDecodeSwapChain_SetTargetRect_InvalidRect;
pub const DXGI_MSG_IDXGIDecodeSwapChain_SetDestSize_InvalidSize = DXGI_Message_Id.IDXGIDecodeSwapChain_SetDestSize_InvalidSize;
pub const DXGI_MSG_IDXGIDecodeSwapChain_GetSourceRect_InvalidPointer = DXGI_Message_Id.IDXGIDecodeSwapChain_GetSourceRect_InvalidPointer;
pub const DXGI_MSG_IDXGIDecodeSwapChain_GetTargetRect_InvalidPointer = DXGI_Message_Id.IDXGIDecodeSwapChain_GetTargetRect_InvalidPointer;
pub const DXGI_MSG_IDXGIDecodeSwapChain_GetDestSize_InvalidPointer = DXGI_Message_Id.IDXGIDecodeSwapChain_GetDestSize_InvalidPointer;
pub const DXGI_MSG_IDXGISwapChain_PresentBuffer_YUV = DXGI_Message_Id.IDXGISwapChain_PresentBuffer_YUV;
pub const DXGI_MSG_IDXGISwapChain_SetSourceSize_YUV = DXGI_Message_Id.IDXGISwapChain_SetSourceSize_YUV;
pub const DXGI_MSG_IDXGISwapChain_GetSourceSize_YUV = DXGI_Message_Id.IDXGISwapChain_GetSourceSize_YUV;
pub const DXGI_MSG_IDXGISwapChain_SetMatrixTransform_YUV = DXGI_Message_Id.IDXGISwapChain_SetMatrixTransform_YUV;
pub const DXGI_MSG_IDXGISwapChain_GetMatrixTransform_YUV = DXGI_Message_Id.IDXGISwapChain_GetMatrixTransform_YUV;
pub const DXGI_MSG_IDXGISwapChain_Present_PartialPresentation_YUV = DXGI_Message_Id.IDXGISwapChain_Present_PartialPresentation_YUV;
pub const DXGI_MSG_IDXGISwapChain_ResizeBuffers_CannotAddOrRemoveFlag_YUV = DXGI_Message_Id.IDXGISwapChain_ResizeBuffers_CannotAddOrRemoveFlag_YUV;
pub const DXGI_MSG_IDXGISwapChain_ResizeBuffers_Alignment_YUV = DXGI_Message_Id.IDXGISwapChain_ResizeBuffers_Alignment_YUV;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_ShaderInputUnsupported_YUV = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_ShaderInputUnsupported_YUV;
pub const DXGI_MSG_IDXGIOutput3_CheckOverlaySupport_NullPointers = DXGI_Message_Id.IDXGIOutput3_CheckOverlaySupport_NullPointers;
pub const DXGI_MSG_IDXGIOutput3_CheckOverlaySupport_IDXGIDeviceNotSupportedBypConcernedDevice = DXGI_Message_Id.IDXGIOutput3_CheckOverlaySupport_IDXGIDeviceNotSupportedBypConcernedDevice;
pub const DXGI_MSG_IDXGIAdapter_EnumOutputs2_InvalidEnumOutputs2Flag = DXGI_Message_Id.IDXGIAdapter_EnumOutputs2_InvalidEnumOutputs2Flag;
pub const DXGI_MSG_IDXGISwapChain_CreationOrSetFullscreenState_FSUnsupportedForFlipDiscard = DXGI_Message_Id.IDXGISwapChain_CreationOrSetFullscreenState_FSUnsupportedForFlipDiscard;
pub const DXGI_MSG_IDXGIOutput4_CheckOverlayColorSpaceSupport_NullPointers = DXGI_Message_Id.IDXGIOutput4_CheckOverlayColorSpaceSupport_NullPointers;
pub const DXGI_MSG_IDXGIOutput4_CheckOverlayColorSpaceSupport_IDXGIDeviceNotSupportedBypConcernedDevice = DXGI_Message_Id.IDXGIOutput4_CheckOverlayColorSpaceSupport_IDXGIDeviceNotSupportedBypConcernedDevice;
pub const DXGI_MSG_IDXGISwapChain3_CheckColorSpaceSupport_NullPointers = DXGI_Message_Id.IDXGISwapChain3_CheckColorSpaceSupport_NullPointers;
pub const DXGI_MSG_IDXGISwapChain3_SetColorSpace1_InvalidColorSpace = DXGI_Message_Id.IDXGISwapChain3_SetColorSpace1_InvalidColorSpace;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_InvalidHwProtect = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_InvalidHwProtect;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_HwProtectUnsupported = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_HwProtectUnsupported;
pub const DXGI_MSG_IDXGISwapChain_ResizeBuffers_InvalidHwProtect = DXGI_Message_Id.IDXGISwapChain_ResizeBuffers_InvalidHwProtect;
pub const DXGI_MSG_IDXGISwapChain_ResizeBuffers_HwProtectUnsupported = DXGI_Message_Id.IDXGISwapChain_ResizeBuffers_HwProtectUnsupported;
pub const DXGI_MSG_IDXGISwapChain_ResizeBuffers1_D3D12Only = DXGI_Message_Id.IDXGISwapChain_ResizeBuffers1_D3D12Only;
pub const DXGI_MSG_IDXGISwapChain_ResizeBuffers1_FlipModel = DXGI_Message_Id.IDXGISwapChain_ResizeBuffers1_FlipModel;
pub const DXGI_MSG_IDXGISwapChain_ResizeBuffers1_NodeMaskAndQueueRequired = DXGI_Message_Id.IDXGISwapChain_ResizeBuffers1_NodeMaskAndQueueRequired;
pub const DXGI_MSG_IDXGISwapChain_CreateSwapChain_InvalidHwProtectGdiFlag = DXGI_Message_Id.IDXGISwapChain_CreateSwapChain_InvalidHwProtectGdiFlag;
pub const DXGI_MSG_IDXGISwapChain_ResizeBuffers_InvalidHwProtectGdiFlag = DXGI_Message_Id.IDXGISwapChain_ResizeBuffers_InvalidHwProtectGdiFlag;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_10BitFormatNotSupported = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_10BitFormatNotSupported;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_FlipSwapEffectRequired = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_FlipSwapEffectRequired;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_InvalidDevice = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_InvalidDevice;
pub const DXGI_MSG_IDXGIOutput_TakeOwnership_Unsupported = DXGI_Message_Id.IDXGIOutput_TakeOwnership_Unsupported;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_InvalidQueue = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_InvalidQueue;
pub const DXGI_MSG_IDXGISwapChain3_ResizeBuffers1_InvalidQueue = DXGI_Message_Id.IDXGISwapChain3_ResizeBuffers1_InvalidQueue;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChainForHwnd_InvalidScaling = DXGI_Message_Id.IDXGIFactory_CreateSwapChainForHwnd_InvalidScaling;
pub const DXGI_MSG_IDXGISwapChain3_SetHDRMetaData_InvalidSize = DXGI_Message_Id.IDXGISwapChain3_SetHDRMetaData_InvalidSize;
pub const DXGI_MSG_IDXGISwapChain3_SetHDRMetaData_InvalidPointer = DXGI_Message_Id.IDXGISwapChain3_SetHDRMetaData_InvalidPointer;
pub const DXGI_MSG_IDXGISwapChain3_SetHDRMetaData_InvalidType = DXGI_Message_Id.IDXGISwapChain3_SetHDRMetaData_InvalidType;
pub const DXGI_MSG_IDXGISwapChain_Present_FullscreenAllowTearingIsInvalid = DXGI_Message_Id.IDXGISwapChain_Present_FullscreenAllowTearingIsInvalid;
pub const DXGI_MSG_IDXGISwapChain_Present_AllowTearingRequiresPresentIntervalZero = DXGI_Message_Id.IDXGISwapChain_Present_AllowTearingRequiresPresentIntervalZero;
pub const DXGI_MSG_IDXGISwapChain_Present_AllowTearingRequiresCreationFlag = DXGI_Message_Id.IDXGISwapChain_Present_AllowTearingRequiresCreationFlag;
pub const DXGI_MSG_IDXGISwapChain_ResizeBuffers_CannotAddOrRemoveAllowTearingFlag = DXGI_Message_Id.IDXGISwapChain_ResizeBuffers_CannotAddOrRemoveAllowTearingFlag;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_AllowTearingFlagIsFlipModelOnly = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_AllowTearingFlagIsFlipModelOnly;
pub const DXGI_MSG_IDXGIFactory_CheckFeatureSupport_InvalidFeature = DXGI_Message_Id.IDXGIFactory_CheckFeatureSupport_InvalidFeature;
pub const DXGI_MSG_IDXGIFactory_CheckFeatureSupport_InvalidSize = DXGI_Message_Id.IDXGIFactory_CheckFeatureSupport_InvalidSize;
pub const DXGI_MSG_IDXGIOutput6_CheckHardwareCompositionSupport_NullPointer = DXGI_Message_Id.IDXGIOutput6_CheckHardwareCompositionSupport_NullPointer;
pub const DXGI_MSG_IDXGISwapChain_SetFullscreenState_PerMonitorDpiShimApplied = DXGI_Message_Id.IDXGISwapChain_SetFullscreenState_PerMonitorDpiShimApplied;
pub const DXGI_MSG_IDXGIOutput_DuplicateOutput_PerMonitorDpiShimApplied = DXGI_Message_Id.IDXGIOutput_DuplicateOutput_PerMonitorDpiShimApplied;
pub const DXGI_MSG_IDXGIOutput_DuplicateOutput1_PerMonitorDpiRequired = DXGI_Message_Id.IDXGIOutput_DuplicateOutput1_PerMonitorDpiRequired;
pub const DXGI_MSG_IDXGIFactory7_UnregisterAdaptersChangedEvent_CookieNotFound = DXGI_Message_Id.IDXGIFactory7_UnregisterAdaptersChangedEvent_CookieNotFound;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_LegacyBltModelSwapEffect = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_LegacyBltModelSwapEffect;
pub const DXGI_MSG_IDXGISwapChain4_SetHDRMetaData_MetadataUnchanged = DXGI_Message_Id.IDXGISwapChain4_SetHDRMetaData_MetadataUnchanged;
pub const DXGI_MSG_IDXGISwapChain_Present_11On12_Released_Resource = DXGI_Message_Id.IDXGISwapChain_Present_11On12_Released_Resource;
pub const DXGI_MSG_IDXGIFactory_CreateSwapChain_MultipleSwapchainRefToSurface_DeferredDtr = DXGI_Message_Id.IDXGIFactory_CreateSwapChain_MultipleSwapchainRefToSurface_DeferredDtr;
pub const DXGI_MSG_IDXGIFactory_MakeWindowAssociation_NoOpBehavior = DXGI_Message_Id.IDXGIFactory_MakeWindowAssociation_NoOpBehavior;
pub const DXGI_MSG_Phone_IDXGIFactory_CreateSwapChain_NotForegroundWindow = DXGI_Message_Id.Phone_IDXGIFactory_CreateSwapChain_NotForegroundWindow;
pub const DXGI_MSG_Phone_IDXGIFactory_CreateSwapChain_DISCARD_BufferCount = DXGI_Message_Id.Phone_IDXGIFactory_CreateSwapChain_DISCARD_BufferCount;
pub const DXGI_MSG_Phone_IDXGISwapChain_SetFullscreenState_NotAvailable = DXGI_Message_Id.Phone_IDXGISwapChain_SetFullscreenState_NotAvailable;
pub const DXGI_MSG_Phone_IDXGISwapChain_ResizeBuffers_NotAvailable = DXGI_Message_Id.Phone_IDXGISwapChain_ResizeBuffers_NotAvailable;
pub const DXGI_MSG_Phone_IDXGISwapChain_ResizeTarget_NotAvailable = DXGI_Message_Id.Phone_IDXGISwapChain_ResizeTarget_NotAvailable;
pub const DXGI_MSG_Phone_IDXGISwapChain_Present_InvalidLayerIndex = DXGI_Message_Id.Phone_IDXGISwapChain_Present_InvalidLayerIndex;
pub const DXGI_MSG_Phone_IDXGISwapChain_Present_MultipleLayerIndex = DXGI_Message_Id.Phone_IDXGISwapChain_Present_MultipleLayerIndex;
pub const DXGI_MSG_Phone_IDXGISwapChain_Present_InvalidLayerFlag = DXGI_Message_Id.Phone_IDXGISwapChain_Present_InvalidLayerFlag;
pub const DXGI_MSG_Phone_IDXGISwapChain_Present_InvalidRotation = DXGI_Message_Id.Phone_IDXGISwapChain_Present_InvalidRotation;
pub const DXGI_MSG_Phone_IDXGISwapChain_Present_InvalidBlend = DXGI_Message_Id.Phone_IDXGISwapChain_Present_InvalidBlend;
pub const DXGI_MSG_Phone_IDXGISwapChain_Present_InvalidResource = DXGI_Message_Id.Phone_IDXGISwapChain_Present_InvalidResource;
pub const DXGI_MSG_Phone_IDXGISwapChain_Present_InvalidMultiPlaneOverlayResource = DXGI_Message_Id.Phone_IDXGISwapChain_Present_InvalidMultiPlaneOverlayResource;
pub const DXGI_MSG_Phone_IDXGISwapChain_Present_InvalidIndexForPrimary = DXGI_Message_Id.Phone_IDXGISwapChain_Present_InvalidIndexForPrimary;
pub const DXGI_MSG_Phone_IDXGISwapChain_Present_InvalidIndexForOverlay = DXGI_Message_Id.Phone_IDXGISwapChain_Present_InvalidIndexForOverlay;
pub const DXGI_MSG_Phone_IDXGISwapChain_Present_InvalidSubResourceIndex = DXGI_Message_Id.Phone_IDXGISwapChain_Present_InvalidSubResourceIndex;
pub const DXGI_MSG_Phone_IDXGISwapChain_Present_InvalidSourceRect = DXGI_Message_Id.Phone_IDXGISwapChain_Present_InvalidSourceRect;
pub const DXGI_MSG_Phone_IDXGISwapChain_Present_InvalidDestinationRect = DXGI_Message_Id.Phone_IDXGISwapChain_Present_InvalidDestinationRect;
pub const DXGI_MSG_Phone_IDXGISwapChain_Present_MultipleResource = DXGI_Message_Id.Phone_IDXGISwapChain_Present_MultipleResource;
pub const DXGI_MSG_Phone_IDXGISwapChain_Present_NotSharedResource = DXGI_Message_Id.Phone_IDXGISwapChain_Present_NotSharedResource;
pub const DXGI_MSG_Phone_IDXGISwapChain_Present_InvalidFlag = DXGI_Message_Id.Phone_IDXGISwapChain_Present_InvalidFlag;
pub const DXGI_MSG_Phone_IDXGISwapChain_Present_InvalidInterval = DXGI_Message_Id.Phone_IDXGISwapChain_Present_InvalidInterval;
pub const DXGI_MSG_Phone_IDXGIFactory_CreateSwapChain_MSAA_NotSupported = DXGI_Message_Id.Phone_IDXGIFactory_CreateSwapChain_MSAA_NotSupported;
pub const DXGI_MSG_Phone_IDXGIFactory_CreateSwapChain_ScalingAspectRatioStretch_Supported_ModernApp = DXGI_Message_Id.Phone_IDXGIFactory_CreateSwapChain_ScalingAspectRatioStretch_Supported_ModernApp;
pub const DXGI_MSG_Phone_IDXGISwapChain_GetFrameStatistics_NotAvailable_ModernApp = DXGI_Message_Id.Phone_IDXGISwapChain_GetFrameStatistics_NotAvailable_ModernApp;
pub const DXGI_MSG_Phone_IDXGISwapChain_Present_ReplaceInterval0With1 = DXGI_Message_Id.Phone_IDXGISwapChain_Present_ReplaceInterval0With1;
pub const DXGI_MSG_Phone_IDXGIFactory_CreateSwapChain_FailedRegisterWithCompositor = DXGI_Message_Id.Phone_IDXGIFactory_CreateSwapChain_FailedRegisterWithCompositor;
pub const DXGI_MSG_Phone_IDXGIFactory_CreateSwapChain_NotForegroundWindow_AtRendering = DXGI_Message_Id.Phone_IDXGIFactory_CreateSwapChain_NotForegroundWindow_AtRendering;
pub const DXGI_MSG_Phone_IDXGIFactory_CreateSwapChain_FLIP_SEQUENTIAL_BufferCount = DXGI_Message_Id.Phone_IDXGIFactory_CreateSwapChain_FLIP_SEQUENTIAL_BufferCount;
pub const DXGI_MSG_Phone_IDXGIFactory_CreateSwapChain_FLIP_Modern_CoreWindow_Only = DXGI_Message_Id.Phone_IDXGIFactory_CreateSwapChain_FLIP_Modern_CoreWindow_Only;
pub const DXGI_MSG_Phone_IDXGISwapChain_Present1_RequiresOverlays = DXGI_Message_Id.Phone_IDXGISwapChain_Present1_RequiresOverlays;
pub const DXGI_MSG_Phone_IDXGISwapChain_SetBackgroundColor_FlipSequentialRequired = DXGI_Message_Id.Phone_IDXGISwapChain_SetBackgroundColor_FlipSequentialRequired;
pub const DXGI_MSG_Phone_IDXGISwapChain_GetBackgroundColor_FlipSequentialRequired = DXGI_Message_Id.Phone_IDXGISwapChain_GetBackgroundColor_FlipSequentialRequired;
const IID_IDXGraphicsAnalysis_Value = Guid.initString("9f251514-9d4d-4902-9d60-18988ab7d4b5");
pub const IID_IDXGraphicsAnalysis = &IID_IDXGraphicsAnalysis_Value;
pub const IDXGraphicsAnalysis = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
BeginCapture: fn(
self: *const IDXGraphicsAnalysis,
) callconv(@import("std").os.windows.WINAPI) void,
EndCapture: fn(
self: *const IDXGraphicsAnalysis,
) callconv(@import("std").os.windows.WINAPI) void,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGraphicsAnalysis_BeginCapture(self: *const T) callconv(.Inline) void {
return @ptrCast(*const IDXGraphicsAnalysis.VTable, self.vtable).BeginCapture(@ptrCast(*const IDXGraphicsAnalysis, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXGraphicsAnalysis_EndCapture(self: *const T) callconv(.Inline) void {
return @ptrCast(*const IDXGraphicsAnalysis.VTable, self.vtable).EndCapture(@ptrCast(*const IDXGraphicsAnalysis, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
//--------------------------------------------------------------------------------
// Section: Functions (5)
//--------------------------------------------------------------------------------
pub extern "dxgi" fn CreateDXGIFactory(
riid: ?*const Guid,
ppFactory: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.1'
pub extern "dxgi" fn CreateDXGIFactory1(
riid: ?*const Guid,
ppFactory: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows8.1'
pub extern "dxgi" fn CreateDXGIFactory2(
Flags: u32,
riid: ?*const Guid,
ppFactory: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows8.1'
pub extern "dxgi" fn DXGIGetDebugInterface1(
Flags: u32,
riid: ?*const Guid,
pDebug: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows10.0.17134'
pub extern "dxgi" fn DXGIDeclareAdapterRemovalSupport(
) 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 (27)
//--------------------------------------------------------------------------------
const Guid = @import("../zig.zig").Guid;
const BOOL = @import("../foundation.zig").BOOL;
const DXGI_ALPHA_MODE = @import("../graphics/dxgi/common.zig").DXGI_ALPHA_MODE;
const DXGI_COLOR_SPACE_TYPE = @import("../graphics/dxgi/common.zig").DXGI_COLOR_SPACE_TYPE;
const DXGI_FORMAT = @import("../graphics/dxgi/common.zig").DXGI_FORMAT;
const DXGI_GAMMA_CONTROL = @import("../graphics/dxgi/common.zig").DXGI_GAMMA_CONTROL;
const DXGI_GAMMA_CONTROL_CAPABILITIES = @import("../graphics/dxgi/common.zig").DXGI_GAMMA_CONTROL_CAPABILITIES;
const DXGI_MODE_DESC = @import("../graphics/dxgi/common.zig").DXGI_MODE_DESC;
const DXGI_MODE_ROTATION = @import("../graphics/dxgi/common.zig").DXGI_MODE_ROTATION;
const DXGI_MODE_SCALING = @import("../graphics/dxgi/common.zig").DXGI_MODE_SCALING;
const DXGI_MODE_SCANLINE_ORDER = @import("../graphics/dxgi/common.zig").DXGI_MODE_SCANLINE_ORDER;
const DXGI_RATIONAL = @import("../graphics/dxgi/common.zig").DXGI_RATIONAL;
const DXGI_SAMPLE_DESC = @import("../graphics/dxgi/common.zig").DXGI_SAMPLE_DESC;
const HANDLE = @import("../foundation.zig").HANDLE;
const HDC = @import("../graphics/gdi.zig").HDC;
const HINSTANCE = @import("../foundation.zig").HINSTANCE;
const HMONITOR = @import("../graphics/gdi.zig").HMONITOR;
const HRESULT = @import("../foundation.zig").HRESULT;
const HWND = @import("../foundation.zig").HWND;
const IUnknown = @import("../system/com.zig").IUnknown;
const LARGE_INTEGER = @import("../foundation.zig").LARGE_INTEGER;
const LUID = @import("../foundation.zig").LUID;
const POINT = @import("../foundation.zig").POINT;
const PSTR = @import("../foundation.zig").PSTR;
const PWSTR = @import("../foundation.zig").PWSTR;
const RECT = @import("../foundation.zig").RECT;
const SECURITY_ATTRIBUTES = @import("../security.zig").SECURITY_ATTRIBUTES;
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;
}
}
}
//--------------------------------------------------------------------------------
// Section: SubModules (1)
//--------------------------------------------------------------------------------
pub const common = @import("dxgi/common.zig"); | win32/graphics/dxgi.zig |
const std = @import("std");
const os = std.os;
const assert = std.debug.assert;
const Time = @import("../time.zig").Time;
const IO = @import("../io.zig").IO;
// 1 MB: larger than socket buffer so forces io_pending on darwin
// Configure this value to smaller amounts to test IO scheduling overhead
const buffer_size = 1 * 1024 * 1024;
// max time for the benchmark to run
const run_duration = 1 * std.time.ns_per_s;
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = &gpa.allocator;
defer {
const leaks = gpa.deinit();
assert(!leaks);
}
const buffer = try allocator.alloc(u8, buffer_size * 2);
defer allocator.free(buffer);
std.mem.set(u8, buffer, 0);
var timer = Time{};
const started = timer.monotonic();
var self = Context{
.io = try IO.init(32, 0),
.timer = &timer,
.started = started,
.current = started,
.tx = .{ .buffer = buffer[0 * buffer_size ..][0..buffer_size] },
.rx = .{ .buffer = buffer[1 * buffer_size ..][0..buffer_size] },
};
defer {
self.io.deinit();
const elapsed_ns = self.current - started;
const transferred_mb = @intToFloat(f64, self.transferred) / 1024 / 1024;
std.debug.print("IO throughput test: took {}ms @ {d:.2} MB/s\n", .{
elapsed_ns / std.time.ns_per_ms,
transferred_mb / (@intToFloat(f64, elapsed_ns) / std.time.ns_per_s),
});
}
// Setup the server socket
self.server.fd = try IO.openSocket(os.AF_INET, os.SOCK_STREAM, os.IPPROTO_TCP);
defer os.closeSocket(self.server.fd);
const address = try std.net.Address.parseIp4("127.0.0.1", 3131);
try os.setsockopt(
self.server.fd,
os.SOL_SOCKET,
os.SO_REUSEADDR,
&std.mem.toBytes(@as(c_int, 1)),
);
try os.bind(self.server.fd, &address.any, address.getOsSockLen());
try os.listen(self.server.fd, 1);
// Start accepting the client
self.io.accept(
*Context,
&self,
Context.on_accept,
&self.server.completion,
self.server.fd,
);
// Setup the client connection
self.tx.socket.fd = try IO.openSocket(os.AF_INET, os.SOCK_STREAM, os.IPPROTO_TCP);
defer os.closeSocket(self.tx.socket.fd);
self.io.connect(
*Context,
&self,
Context.on_connect,
&self.tx.socket.completion,
self.tx.socket.fd,
address,
);
// Run the IO loop, calling either tick() or run_for_ns() at "pseudo-random"
// to benchmark each io-driving execution path
var tick: usize = 0xdeadbeef;
while (self.is_running()) : (tick +%= 1) {
if (tick % 61 == 0) {
const timeout_ns = tick % (10 * std.time.ns_per_ms);
try self.io.run_for_ns(@intCast(u63, timeout_ns));
} else {
try self.io.tick();
}
}
// Assert that everything is connected
assert(self.server.fd != -1);
assert(self.tx.socket.fd != -1);
assert(self.rx.socket.fd != -1);
// Close the accepted client socket.
// The actual client socket + server socket are closed by defer
os.closeSocket(self.rx.socket.fd);
}
const Context = struct {
io: IO,
tx: Pipe,
rx: Pipe,
timer: *Time,
started: u64,
current: u64,
server: Socket = .{},
transferred: u64 = 0,
const Socket = struct {
fd: os.socket_t = -1,
completion: IO.Completion = undefined,
};
const Pipe = struct {
socket: Socket = .{},
buffer: []u8,
transferred: usize = 0,
};
fn is_running(self: Context) bool {
// Make sure that we're connected
if (self.rx.socket.fd == -1) return true;
// Make sure that we haven't run too long as configured
const elapsed = self.current - self.started;
return elapsed < run_duration;
}
fn on_accept(
self: *Context,
completion: *IO.Completion,
result: IO.AcceptError!os.socket_t,
) void {
assert(self.rx.socket.fd == -1);
assert(&self.server.completion == completion);
self.rx.socket.fd = result catch |err| std.debug.panic("accept error {}", .{err});
// Start reading data from the accepted client socket
assert(self.rx.transferred == 0);
self.do_transfer("rx", .read, 0);
}
fn on_connect(
self: *Context,
completion: *IO.Completion,
result: IO.ConnectError!void,
) void {
assert(self.tx.socket.fd != -1);
assert(&self.tx.socket.completion == completion);
// Start sending data to the server's accepted client
assert(self.tx.transferred == 0);
self.do_transfer("tx", .write, 0);
}
const TransferType = enum {
read = 0,
write = 1,
};
fn do_transfer(
self: *Context,
comptime pipe_name: []const u8,
comptime transfer_type: TransferType,
bytes: usize,
) void {
// The type of IO to perform and what type of IO to perform next (after the current one completes).
const transfer_info = switch (transfer_type) {
.read => .{
.IoError = IO.RecvError,
.io_func = "recv",
.next = TransferType.write,
},
.write => .{
.IoError = IO.SendError,
.io_func = "send",
.next = TransferType.read,
},
};
assert(bytes <= buffer_size);
self.transferred += bytes;
// Check in with the benchmark timer to stop sending/receiving data
self.current = self.timer.monotonic();
if (!self.is_running())
return;
// Select which connection (tx or rx) depending on the type of transfer
const pipe = &@field(self, pipe_name);
pipe.transferred += bytes;
assert(pipe.transferred <= pipe.buffer.len);
// There's still more data to transfer on the connection
if (pipe.transferred < pipe.buffer.len) {
// Callback which calls this function again when data is transferred.
// Effectively loops back above.
const on_transfer = struct {
fn on_transfer(
_self: *Context,
completion: *IO.Completion,
result: transfer_info.IoError!usize,
) void {
const _bytes = result catch |err| {
std.debug.panic("{s} error: {}", .{ transfer_info.io_func, err });
};
assert(&@field(_self, pipe_name).socket.completion == completion);
_self.do_transfer(pipe_name, transfer_type, _bytes);
}
}.on_transfer;
// Perform the IO with the callback for the completion
return @field(self.io, transfer_info.io_func)(
*Context,
self,
on_transfer,
&pipe.socket.completion,
pipe.socket.fd,
pipe.buffer[pipe.transferred..],
);
}
// This transfer type completed transferring all the bytes.
// Now, switch the transfer type (transfer_info.next).
// This means if we read to the buffer, now we write it out.
// Inversely, if we wrote the buffer, now we read it back.
// This is basically a modified echo benchmark.
pipe.transferred = 0;
self.do_transfer(pipe_name, transfer_info.next, 0);
}
}; | src/io/benchmark.zig |
pub const Bit = enum {
Zero,
One,
};
pub const BITPOS = struct {
//! ```
//! const cmd = BITPOS.init("test", .Zero, -3, null);
//! ```
key: []const u8,
bit: Bit,
bounds: Bounds,
pub fn init(key: []const u8, bit: Bit, start: ?isize, end: ?isize) BITPOS {
return .{
.key = key,
.bit = bit,
.bounds = Bounds{ .start = start, .end = end },
};
}
pub fn validate(self: BITPOS) !void {
if (self.key.len == 0) return error.EmptyKeyName;
}
pub const RedisCommand = struct {
pub fn serialize(self: BITPOS, comptime rootSerializer: type, msg: anytype) !void {
const bit = switch (self.bit) {
.Zero => "0",
.One => "1",
};
return rootSerializer.serializeCommand(msg, .{ "BITPOS", self.key, bit, self.bounds });
}
};
};
const Bounds = struct {
start: ?isize,
end: ?isize,
pub const RedisArguments = struct {
pub fn count(self: Bounds) usize {
const one: usize = 1;
const zero: usize = 0;
return (if (self.start) |_| one else zero) + (if (self.end) |_| one else zero);
}
pub fn serialize(self: Bounds, comptime rootSerializer: type, msg: anytype) !void {
if (self.start) |s| {
try rootSerializer.serializeArgument(msg, isize, s);
}
if (self.end) |e| {
try rootSerializer.serializeArgument(msg, isize, e);
}
}
};
};
test "basic usage" {
const cmd = BITPOS.init("test", .Zero, -3, null);
}
test "serializer" {
const std = @import("std");
const serializer = @import("../../serializer.zig").CommandSerializer;
var correctBuf: [1000]u8 = undefined;
var correctMsg = std.io.fixedBufferStream(correctBuf[0..]);
var testBuf: [1000]u8 = undefined;
var testMsg = std.io.fixedBufferStream(testBuf[0..]);
{
correctMsg.reset();
testMsg.reset();
var cmd = BITPOS.init("test", .Zero, -3, null);
try serializer.serializeCommand(
testMsg.outStream(),
cmd,
);
try serializer.serializeCommand(
correctMsg.outStream(),
.{ "BITPOS", "test", "0", "-3" },
);
std.testing.expectEqualSlices(u8, correctMsg.getWritten(), testMsg.getWritten());
}
} | src/commands/strings/bitpos.zig |
const std = @import("std");
const io = std.io;
const ArrayList = std.ArrayList;
const expect = std.testing.expect;
const Allocator = std.mem.Allocator;
const test_allocator = std.testing.allocator;
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer {
_ = gpa.deinit();
}
var allocator = &gpa.allocator;
var list = try loadFile(allocator, "input.txt");
defer {
for (list) |item| {
item.deinit();
}
allocator.free(list);
}
var part1 = countValidLength(list);
var part2 = countValidIndex(list);
// for (list) |item| {
// if (item.isValidCount()) {
// part1 += 1;
// }
// // std.log.info("Min, Max: {d}, {d}", .{ item.min, item.max });
// // std.log.info("Letter: {c}", .{item.letter});
// // std.log.info("Password: {s}", .{item.password});
// // std.log.info("Valid? {b}", .{item.isValidCount()});
// // std.log.info("------------------------------------", .{});
// }
const stdout = std.io.getStdOut().writer();
try stdout.print("Part 1: {d}\n", .{part1});
try stdout.print("Part 2: {d}\n", .{part2});
}
const Password = struct {
min: u32,
max: u32,
letter: u8,
password: []u8,
allocator: *Allocator,
pub fn init(allocator: *Allocator, str: []const u8) !Password {
var split_iter = std.mem.split(u8, str, " ");
var range_str = split_iter.next();
var range_iter = std.mem.split(u8, range_str.?, "-");
const min = try std.fmt.parseInt(u32, range_iter.next().?, 10);
const max = try std.fmt.parseInt(u32, range_iter.next().?, 10);
const letter = split_iter.next().?[0];
const password = std.mem.trimRight(u8, split_iter.next().?, "\n");
var heap_pass = try allocator.alloc(u8, password.len);
std.mem.copy(u8, heap_pass, password);
return Password{ .min = min, .max = max, .letter = letter, .password = <PASSWORD>, .allocator = allocator };
}
pub fn deinit(self: *const Password) void {
self.allocator.free(self.password);
}
pub fn isValidCount(self: *const Password) bool {
var count: u32 = 0;
for (self.password) |c| {
if (c == self.letter) {
count += 1;
}
}
return (count >= self.min) and (count <= self.max);
}
pub fn isValidIndex(self: *const Password) bool {
var num: u8 = 0;
if (self.password[self.min - 1] == self.letter) {
num += 1;
}
if (self.password[self.max - 1] == self.letter) {
num += 1;
}
return (num == 1);
}
};
pub fn countValidLength(list: []Password) u32 {
var count: u32 = 0;
for (list) |item| {
if (item.isValidCount()) {
count += 1;
}
}
return count;
}
pub fn countValidIndex(list: []Password) u32 {
var count: u32 = 0;
for (list) |item| {
if (item.isValidIndex()) {
count += 1;
}
}
return count;
}
pub fn loadFile(allocator: *Allocator, path: []const u8) ![]Password {
var file = try std.fs.cwd().openFile(path, .{});
defer file.close();
var list = ArrayList(Password).init(allocator);
var buf_reader = io.bufferedReader(file.reader());
var in_stream = buf_reader.reader();
var buf: [1024]u8 = undefined;
while (try in_stream.readUntilDelimiterOrEof(&buf, '\n')) |line| {
// std.log.info("line: {s}", .{line});
var p = try Password.init(allocator, line);
try list.append(p);
}
return list.toOwnedSlice();
}
const test_input =
\\ 1-3 a: abcde
\\ 1-3 b: cdefg
\\ 2-9 c: ccccccccc
;
test "parsing" {
var test_pass: Password = try Password.init(test_allocator, "1-3 a: abcde");
defer test_pass.deinit();
try expect(test_pass.min == 1);
try expect(test_pass.max == 3);
try expect(test_pass.letter == 'a');
try expect(std.mem.eql(u8, "abcde", test_pass.password));
}
test "file reading" {
var list = try loadFile(test_allocator, "test.txt");
defer {
for (list) |item| {
item.deinit();
}
test_allocator.free(list);
}
try expect(3 == list.len);
var count = countValidLength(list);
try expect(2 == count);
var index_count = countValidIndex(list);
try expect(1 == index_count);
} | day02/src/main.zig |
const std = @import("std");
const assert = std.debug.assert;
const Key = union(enum) {
None,
DottedIdent: DottedIdentifier,
Ident: []const u8,
};
pub const DynamicArray = std.TailQueue(Value);
/// utility function helping to index the DynamicArray
pub fn indexArray(array: DynamicArray, index: usize) ?Value {
var i = index;
var it = array.first;
while (it) |node| : (it = node.next) {
if (i == 0) {
return node.data;
}
i -= 1;
}
return null;
}
pub const Value = union(enum) {
None,
String: []const u8,
Boolean: bool,
Integer: i64,
Array: DynamicArray,
};
pub const Table = struct {
const Self = @This();
const TableMap = std.AutoHashMap([]const u8, *Table);
const KeyMap = std.AutoHashMap([]const u8, Value);
pub children: TableMap,
pub keys: KeyMap,
pub name: []const u8,
allocator: *std.mem.Allocator,
pub fn init(allocator: *std.mem.Allocator, name: []const u8) Self {
return Self{
.children = TableMap.init(allocator),
.keys = TableMap.init(allocator),
.name = name,
.allocator = allocator,
};
}
pub fn create(allocator: *std.mem.Allocator, name: []const u8) !*Self {
var result = try allocator.create(Table);
result.* = Table.init(allocator, name);
return result;
}
/// Cleans up the table's keys and its children
pub fn deinit(self: *Self) void {
// TODO: implement deinit
}
pub fn addKey(self: *Self, key: Key, value: Value) !void {
// TODO: test for key clobbering and give an error
switch (key) {
Key.None => {
return;
},
Key.Ident => |name| {
_ = try self.keys.put(name, value);
},
Key.DottedIdent => |dotted| {
var currentTable: *Table = self;
var index: usize = 0;
while (index < dotted.len - 1) : (index += 1) {
if (currentTable.children.getValue(indexIdentifier(dotted, index).?)) |table| {
currentTable = table;
} else {
var table = try self.allocator.create(Table);
table.* = Table.init(self.allocator, indexIdentifier(dotted, index).?);
try currentTable.addTable(table);
currentTable = table;
}
}
_ = try currentTable.keys.put(indexIdentifier(dotted, index).?, value);
},
}
}
pub fn getKey(self: Self, key: []const u8) ?Value {
if (self.keys.getValue(key)) |value| {
return value;
}
// else {
// var it = self.children.iterator();
// while (it.next()) |nextChild| {
// // recursion is unavoidable here
// if (nextChild.value.getKey(key)) |value| {
// return value;
// }
// }
// }
return null;
}
pub fn getTable(self: Self, name: []const u8) ?Table {
if (self.children.getValue(name)) |table| {
return table.*;
}
// else {
// var it = self.children.iterator();
// while (it.next()) |nextChild| {
// // the recursion is unavoidable here
// if (nextChild.value.getTable(name)) |table| {
// return table;
// }
// }
//}
return null;
}
pub fn addTable(self: *Self, table: *Table) !void {
_ = try self.children.put(table.name, table);
}
pub fn addNewTable(self: *Self, name: []const u8) !*Table {
var table = try Table.create(self.allocator, name);
_ = try self.children.put(name, table);
return table;
}
};
const State = enum {
None,
EOF,
Identifier,
Table,
String,
Number,
Comment,
};
const ParseError = error{
UnexpectedEOF,
ExpectedNewline,
MalformedString,
MalformedKey,
MalformedTable,
ExpectedEquals,
ExpectedComma,
ExpectedCloseArray,
InvalidValue,
};
fn isIdentifier(c: u8) bool {
return (c >= 65 and c <= 90) or (c >= 48 and c <= 57) or (c >= 97 and c <= 122) or c == '-' or c == '_';
}
fn isQuote(c: u8) bool {
return c == '"' or c == '\'';
}
fn isWhitespace(c: u8) bool {
return c == '\n' or c == '\t' or c == ' ' or c == '\r';
}
fn isNumber(word: []const u8) bool {
var i: usize = 0;
if (word[i] == '_') {
return false;
}
if (word[i] == '-' or word[i] == '+') {
i += 1;
}
while (i < word.len) : (i += 1) {
var c = word[i];
if (c == '_') {
if (i + 1 >= word.len) {
return false;
}
i += 1;
c = word[i];
}
if (!(c >= 48 and c <= 57)) {
return false;
}
}
return true;
}
fn toInteger(word: []const u8) i64 {
var result: i64 = 0;
var i: usize = 0;
var negative = false;
if (word[i] == '-') {
negative = true;
i += 1;
} else if (word[i] == '+') {
i += 1;
}
while (true) {
if (word[i] == '_') {
i += 1;
continue;
}
result += @intCast(i64, (word[i] - 48));
i += 1;
if (i < word.len) {
result *= 10;
} else {
break;
}
}
if (negative) {
result *= -1;
}
return result;
}
/// function to easily get the next non-whitespace character
fn getNextChar(contents: []const u8, start: usize) usize {
if (start >= contents.len) {
return start;
}
var index = start + 1;
while (index < contents.len and isWhitespace(contents[index])) {
index += 1;
}
if (index >= contents.len) {
return index;
}
return index;
}
fn getState(contents: []const u8, index: usize) State {
if (index >= contents.len) {
return State.EOF;
}
var c = contents[index];
if (isIdentifier(c)) {
return State.Identifier;
}
switch (c) {
'[' => {
return State.Table;
},
'"' => {
return State.String;
},
'-', '+' => {
return State.Number;
},
'#' => {
return State.Comment;
},
else => {
return State.None;
},
}
}
const DottedIdentifier = std.TailQueue([]const u8);
fn indexIdentifier(ident: DottedIdentifier, index: usize) ?[]const u8 {
if (index >= ident.len) {
return null;
}
var it = ident.first;
var current: []const u8 = undefined;
var i = index;
while (it) |node| : (it = node.next) {
current = node.data;
if (i == 0) {
break;
}
i -= 1;
}
return current;
}
/// This assumes that the starting character aka contents[start] is a '.'
fn parseDottedIdentifier(allocator: *std.mem.Allocator, contents: []const u8, start: *usize) !DottedIdentifier {
var result = DottedIdentifier.init();
if (start.* >= contents.len) {
return ParseError.UnexpectedEOF;
}
while (contents[start.*] == '.') {
var word: []const u8 = undefined;
start.* += 1;
if (isQuote(contents[start.*])) {
word = try parseString(contents, start);
} else {
word = try parseIdentifier(contents, start);
}
start.* += 1;
var node = try result.createNode(word, allocator);
result.append(node);
if (start.* >= contents.len) {
break;
}
}
start.* -= 1;
return result;
}
/// Assumes the starting character is a " or a '
fn parseString(contents: []const u8, index: *usize) ParseError![]const u8 {
var start = index.*;
var i = index.*;
if (i >= contents.len) {
return ParseError.UnexpectedEOF;
}
// TODO: multiline strings
var quote = contents[i];
if (i + 1 >= contents.len) {
return ParseError.MalformedString;
}
i += 1;
var c = contents[i];
// TODO: escaped characters
while (c != quote) {
i += 1;
if (i >= contents.len) {
return ParseError.MalformedString;
}
c = contents[i];
}
index.* = i;
return contents[start + 1 .. i];
}
fn parseIdentifier(contents: []const u8, index: *usize) ![]const u8 {
var start = index.*;
var i = start;
if (i >= contents.len) {
return ParseError.UnexpectedEOF;
}
var c = contents[i];
while (isIdentifier(c)) {
i += 1;
if (i >= contents.len) {
return ParseError.UnexpectedEOF;
}
c = contents[i];
}
index.* = i - 1;
return contents[start .. index.* + 1];
}
fn convertIdentifierToValue(word: []const u8) !Value {
if (std.mem.eql(u8, word, "true")) {
return Value{ .Boolean = true };
} else if (std.mem.eql(u8, word, "false")) {
return Value{ .Boolean = false };
} else if (isNumber(word)) {
return Value{ .Integer = toInteger(word) };
} else {
return ParseError.InvalidValue;
}
}
fn parseArray(allocator: *std.mem.Allocator, contents: []const u8, index: *usize) anyerror!Value {
var array = DynamicArray.init();
var expectClosing = false;
var i = index.*;
var state = getState(contents, i);
while (i < contents.len) {
if (expectClosing and state != State.None) {
return ParseError.ExpectedComma;
}
switch (state) {
State.None => {
if (i < contents.len) {
if (contents[i] == ']') {
index.* = i;
return Value{ .Array = array };
}
}
i += 1;
state = getState(contents, i);
continue;
},
State.EOF => {
break;
},
State.Comment => {
i = skipComment(contents, i);
i += 1;
state = getState(contents, i);
continue;
},
State.Identifier => {
var word = try parseIdentifier(contents, &i);
var value = try convertIdentifierToValue(word);
var node = try array.createNode(value, allocator);
array.append(node);
},
State.String => {
var str = try parseString(contents, &i);
var value = Value{ .String = str };
var node = try array.createNode(value, allocator);
array.append(node);
},
State.Number => {
if (contents[i] == '+') {
i += 1;
}
var word = try parseIdentifier(contents, &i);
if (isNumber(word)) {
var value = Value{ .Integer = toInteger(word) };
var node = try array.createNode(value, allocator);
array.append(node);
} else {
return ParseError.InvalidValue;
}
},
State.Table => {
i += 1;
var value = try parseArray(allocator, contents, &i);
var node = try array.createNode(value, allocator);
array.append(node);
},
}
i += 1;
if (i < contents.len) {
if (contents[i] != ',') {
expectClosing = true;
}
}
state = getState(contents, i);
}
return ParseError.ExpectedCloseArray;
}
fn skipComment(contents: []const u8, start: usize) usize {
var i = start;
while (i < contents.len) {
if (contents[i] == '\n') {
return i - 1;
}
i += 1;
}
return i;
}
fn parseKeyIdentifier(allocator: *std.mem.Allocator, contents: []const u8, index: *usize) !Key {
var word: []const u8 = undefined;
if (isQuote(contents[index.*])) {
word = try parseString(contents, index);
} else {
word = try parseIdentifier(contents, index);
}
if (index.* + 1 < contents.len and contents[index.* + 1] == '.') {
index.* += 1;
var dottedResult = try parseDottedIdentifier(allocator, contents, index);
var node = try dottedResult.createNode(word, allocator);
dottedResult.prepend(node);
return Key{ .DottedIdent = dottedResult };
} else {
return Key{ .Ident = word };
}
}
fn parseTable(allocator: *std.mem.Allocator, name: []const u8, contents: []const u8, index: *usize, root: bool) anyerror!*Table {
var table = try Table.create(allocator, name);
var i = index.*;
var key: Key = Key.None;
var value: Value = Value.None;
var state = getState(contents, index.*);
loop: while (i < contents.len) {
switch (state) {
State.None => {},
State.EOF => {
break :loop;
},
State.Comment => {
i = skipComment(contents, i);
},
State.Identifier => {
// boolean value identifier
if (key != Key.None and value == Value.None) {
var word = try parseIdentifier(contents, &i);
value = try convertIdentifierToValue(word);
} else {
var keyIdentifier = try parseKeyIdentifier(allocator, contents, &i);
// regular identifier
if (key == Key.None) {
key = keyIdentifier;
} else {
return ParseError.MalformedKey;
}
}
},
State.Table => {
// Deals with tables or arrays depending on if key == Key.None
if (key != Key.None and value == Value.None) {
// treat this as an array
i += 1;
value = try parseArray(allocator, contents, &i);
} else {
if (!root) {
// rough
i -= 1;
break :loop;
}
i += 1;
var tableKey = try parseKeyIdentifier(allocator, contents, &i);
var tableName: []const u8 = undefined;
var currentTable: *Table = table;
switch (tableKey) {
Key.None => {
return ParseError.MalformedTable;
},
Key.Ident => |ident| {
tableName = ident;
},
Key.DottedIdent => |dotted| {
var it = dotted.first;
while (it) |node| : (it = node.next) {
if (node == dotted.last) {
break;
}
currentTable = try table.addNewTable(node.data);
}
tableName = dotted.last.?.data;
},
}
i += 1;
if (contents[i] != ']') {
return ParseError.MalformedTable;
}
var newTable = try parseTable(allocator, tableName, contents, &i, false);
try currentTable.addTable(newTable);
}
},
State.Number => {
// Deals with numbers starting with +
if (contents[i] == '+') {
i += 1;
}
var word = try parseIdentifier(contents, &i);
if (isNumber(word)) {
value = Value{ .Integer = toInteger(word) };
} else {
return ParseError.InvalidValue;
}
},
State.String => {
if (key == Key.None) {
var strKey = try parseKeyIdentifier(allocator, contents, &i);
key = strKey;
} else if (value == Value.None) {
var str = try parseString(contents, &i);
value = Value{ .String = str };
}
},
}
// if we have a key and a value pair
if (value != Value.None and key != Key.None) {
// add the key value pair to the current table
try table.addKey(key, value);
value = Value.None;
key = Key.None;
var peek = getNextChar(contents, i);
if (peek < contents.len and contents[peek] == '#') {
i = skipComment(contents, peek);
}
// TODO: support Windows line endings \r\n
// enforce a new line after a key-value pair
i += 1;
if (i < contents.len) {
if (contents[i] == '\r') {
i += 1;
}
if (contents[i] != '\n') {
return ParseError.ExpectedNewline;
}
}
}
i = getNextChar(contents, i);
// if we have a key but not a value then the next (non-whitespace) character must be an =
if (value == Value.None and key != Key.None) {
if (contents[i] == '=') {
i = getNextChar(contents, i);
} else {
std.debug.warn("{} {}\n", name, key);
return ParseError.ExpectedEquals;
}
}
state = getState(contents, i);
}
index.* = i;
return table;
}
pub fn parseFile(allocator: *std.mem.Allocator, filename: []const u8) !*Table {
var contents = try std.io.readFileAlloc(allocator, filename);
return parseContents(allocator, contents);
}
pub fn parseContents(allocator: *std.mem.Allocator, contents: []const u8) !*Table {
var index: usize = 0;
// TODO: time values
// TODO: float values
// TODO: inline tables
// TODO: array of tables
var globalTable = try parseTable(allocator, "", contents, &index, true);
return globalTable;
}
test "test.toml file" {
// var table = try parseFile(std.heap.c_allocator, "test/test.toml");
}
test "key value pair" {
var table = try parseContents(std.heap.c_allocator,
\\ foo="hello"
\\
);
assert(table.getKey("foo") != null);
if (table.getKey("foo")) |value| {
assert(std.mem.eql(u8, value.String, "hello"));
}
}
test "table" {
var table = try parseContents(std.heap.c_allocator,
\\ [foo]
\\
);
assert(table.getTable("foo") != null);
}
test "comment" {
var table = try parseContents(std.heap.c_allocator,
\\ # [foo]
\\
);
assert(table.getTable("foo") == null);
}
test "comment inside array" {
var table = try parseContents(std.heap.c_allocator,
\\ foo=[ # hello there
\\ 123, 456
\\ ]
\\
);
var fooKey = table.getKey("foo");
assert(fooKey != null);
if (fooKey) |foo| {
assert(foo.Array.len == 2);
}
}
test "table key value pair" {
var table = try parseContents(std.heap.c_allocator,
\\ [foo]
\\ key = "bar"
\\
);
assert(table.getTable("foo") != null);
if (table.getTable("foo")) |foo| {
assert(foo.getKey("key") != null);
if (foo.getKey("key")) |value| {
assert(std.mem.eql(u8, value.String, "bar"));
}
}
}
test "dotted key with string" {
var table = try parseContents(std.heap.c_allocator,
\\ key."ziglang.org" = "bar"
\\
);
assert(table.getTable("key") != null);
if (table.getTable("key")) |value| {
if (value.getKey("ziglang.org")) |zig| {
assert(std.mem.eql(u8, zig.String, "bar"));
}
}
}
test "multiple tables" {
var table = try parseContents(std.heap.c_allocator,
\\ [foo]
\\ key="bar"
\\ [derp]
\\ another="foobar"
\\
);
assert(table.getTable("foo") != null);
if (table.getTable("foo")) |foo| {
assert(foo.getKey("key") != null);
if (foo.getKey("key")) |value| {
assert(std.mem.eql(u8, value.String, "bar"));
}
}
assert(table.getTable("derp") != null);
if (table.getTable("derp")) |foo| {
assert(foo.getKey("another") != null);
if (foo.getKey("another")) |value| {
assert(std.mem.eql(u8, value.String, "foobar"));
}
}
}
test "key value pair with string key" {
var table = try parseContents(std.heap.c_allocator,
\\ "foo"="hello"
\\
);
var keyValue = table.getKey("foo");
assert(keyValue != null);
if (keyValue) |value| {
assert(std.mem.eql(u8, value.String, "hello"));
}
}
test "dotted key value pair" {
var table = try parseContents(std.heap.c_allocator,
\\ foo.bar="hello"
\\
);
var fooTable = table.getTable("foo");
assert(fooTable != null);
if (fooTable) |foo| {
var barKey = foo.getKey("bar");
assert(barKey != null);
if (barKey) |value| {
assert(std.mem.eql(u8, value.String, "hello"));
}
}
}
test "dotted key value pair within table" {
var table = try parseContents(std.heap.c_allocator,
\\ [foobar]
\\ foo.bar="hello"
\\
);
var fooBarTable = table.getTable("foobar");
if (fooBarTable) |foobar| {
var fooTable = foobar.getTable("foo");
assert(fooTable != null);
if (fooTable) |foo| {
var barKey = foo.getKey("bar");
assert(barKey != null);
if (barKey) |value| {
assert(std.mem.eql(u8, value.String, "hello"));
}
}
}
}
test "key value pair boolean true" {
var table = try parseContents(std.heap.c_allocator,
\\ foo=true
\\
);
var fooKey = table.getKey("foo");
assert(fooKey != null);
if (fooKey) |foo| {
assert(foo.Boolean == true);
}
}
test "key value pair boolean false" {
var table = try parseContents(std.heap.c_allocator,
\\ foo=false
\\
);
var fooKey = table.getKey("foo");
assert(fooKey != null);
if (fooKey) |foo| {
assert(foo.Boolean == false);
}
}
test "key value pair integer" {
var table = try parseContents(std.heap.c_allocator,
\\ foo=1234
\\
);
var fooKey = table.getKey("foo");
assert(fooKey != null);
if (fooKey) |foo| {
assert(foo.Integer == 1234);
}
}
test "key value pair integer" {
var table = try parseContents(std.heap.c_allocator,
\\ foo=1_1234_3_4
\\
);
var fooKey = table.getKey("foo");
assert(fooKey != null);
if (fooKey) |foo| {
assert(foo.Integer == 1123434);
}
}
test "key value pair negative integer" {
var table = try parseContents(std.heap.c_allocator,
\\ foo=-1234
\\
);
var fooKey = table.getKey("foo");
assert(fooKey != null);
if (fooKey) |foo| {
assert(foo.Integer == -1234);
}
}
test "key value pair positive integer" {
var table = try parseContents(std.heap.c_allocator,
\\ foo=+1234
\\
);
var fooKey = table.getKey("foo");
assert(fooKey != null);
if (fooKey) |foo| {
assert(foo.Integer == 1234);
}
}
test "multiple key value pair" {
var table = try parseContents(std.heap.c_allocator,
\\ foo=1234
\\ bar=4321
\\
);
var fooKey = table.getKey("foo");
assert(fooKey != null);
if (fooKey) |foo| {
assert(foo.Integer == 1234);
}
var barKey = table.getKey("bar");
assert(barKey != null);
if (barKey) |bar| {
assert(bar.Integer == 4321);
}
}
test "key value simple array" {
var table = try parseContents(std.heap.c_allocator,
\\ foo=[]
\\
);
var fooKey = table.getKey("foo");
assert(fooKey != null);
}
test "key value multiple element array" {
var table = try parseContents(std.heap.c_allocator,
\\ foo=[ 1234, 5678, true, false, "hello" ]
\\
);
var fooKey = table.getKey("foo");
assert(fooKey != null);
if (fooKey) |foo| {
assert(foo.Array.len == 5);
assert(std.mem.eql(u8, indexArray(foo.Array, 4).?.String, "hello"));
assert(indexArray(foo.Array, 3).?.Boolean == false);
assert(indexArray(foo.Array, 2).?.Boolean == true);
assert(indexArray(foo.Array, 1).?.Integer == 5678);
assert(indexArray(foo.Array, 0).?.Integer == 1234);
}
}
test "key value array in array" {
var table = try parseContents(std.heap.c_allocator,
\\ foo=[[[[[1234]], 57789, [1234, 578]]]]
\\
);
var fooKey = table.getKey("foo");
assert(fooKey != null);
if (fooKey) |foo| {
assert(foo.Array.len == 1);
var array1 = indexArray(foo.Array, 0).?;
assert(array1.Array.len == 1);
var array2 = indexArray(array1.Array, 0).?;
assert(array2.Array.len == 3);
assert(indexArray(array2.Array, 1).?.Integer == 57789);
var array3 = indexArray(array2.Array, 0).?;
assert(array3.Array.len == 1);
var array4 = indexArray(array3.Array, 0).?;
assert(array3.Array.len == 1);
assert(indexArray(array4.Array, 0).?.Integer == 1234);
}
}
test "key with string first" {
var table = try parseContents(std.heap.c_allocator,
\\ "foo".bar = "foobar"
\\
);
var fooTable = table.getTable("foo");
assert(fooTable != null);
var barKey = fooTable.?.getKey("bar");
assert(barKey != null);
assert(std.mem.eql(u8, barKey.?.String, "foobar"));
}
test "table with dotted identifier" {
var table = try parseContents(std.heap.c_allocator,
\\ [foo.bar]
\\ testKey = "hello"
\\
);
var fooTable = table.getTable("foo");
assert(fooTable != null);
if (fooTable) |foo| {
var barTable = foo.getTable("bar");
assert(barTable != null);
if (barTable) |bar| {
var testKey = bar.getKey("testKey");
assert(testKey != null);
assert(std.mem.eql(u8, testKey.?.String, "hello"));
}
}
}
test "window line endings" {
var table = try parseContents(std.heap.c_allocator, "foo=1234\r\nbar=5789\n");
assert(table.getKey("foo") != null);
assert(table.getKey("bar") != null);
} | src/toml.zig |
const builtin = @import("builtin");
const std = @import("std");
const Builder = std.build.Builder;
pub fn build(b: *std.build.Builder) !void {
_ = b;
}
pub fn linkArtifact(b: *Builder, exe: *std.build.LibExeObjStep, target: std.zig.CrossTarget, comptime prefix_path: []const u8) void {
_ = target;
if (prefix_path.len > 0 and !std.mem.endsWith(u8, prefix_path, "/")) @panic("prefix-path must end with '/' if it is not empty");
exe.linkSystemLibrary("c");
exe.linkSystemLibrary("sdl2");
if (builtin.os.tag == .windows) {
// Windows include dirs for SDL2. This requires downloading SDL2 dev and extracting to c:\SDL2
exe.addLibPath("c:\\SDL2\\lib\\x64");
// SDL2.dll needs to be copied to the zig-cache/bin folder
// TODO: installFile doesnt seeem to work so manually copy the file over
b.installFile("c:\\SDL2\\lib\\x64\\SDL2.dll", "bin\\SDL2.dll");
std.fs.cwd().makePath("zig-cache\\bin") catch unreachable;
const src_dir = std.fs.cwd().openDir("c:\\SDL2\\lib\\x64", .{}) catch unreachable;
src_dir.copyFile("SDL2.dll", std.fs.cwd(), "zig-cache\\bin\\SDL2.dll", .{}) catch unreachable;
} else if (builtin.os.tag == .macos) {
exe.linkSystemLibrary("iconv");
exe.linkFramework("AppKit");
exe.linkFramework("AudioToolbox");
exe.linkFramework("Carbon");
exe.linkFramework("Cocoa");
exe.linkFramework("CoreAudio");
exe.linkFramework("CoreFoundation");
exe.linkFramework("CoreGraphics");
exe.linkFramework("CoreHaptics");
exe.linkFramework("CoreVideo");
exe.linkFramework("ForceFeedback");
exe.linkFramework("GameController");
exe.linkFramework("IOKit");
exe.linkFramework("Metal");
}
exe.addPackage(getPackage(prefix_path));
}
pub fn getPackage(comptime prefix_path: []const u8) std.build.Pkg {
if (prefix_path.len > 0 and !std.mem.endsWith(u8, prefix_path, "/")) @panic("prefix-path must end with '/' if it is not empty");
return .{
.name = "sdl",
.path = .{ .path = prefix_path ++ "gamekit/deps/sdl/sdl.zig" },
};
} | gamekit/deps/sdl/build.zig |
const std = @import("std");
const log = std.log.scoped(.jni);
const android = @import("android-support.zig");
pub const JNI = struct {
const Self = @This();
activity: *android.ANativeActivity,
env: *android.JNIEnv,
activity_class: android.jclass,
pub fn init(activity: *android.ANativeActivity) Self {
var env: *android.JNIEnv = undefined;
_ = activity.vm.*.AttachCurrentThread(activity.vm, &env, null);
var activityClass = env.*.FindClass(env, "android/app/NativeActivity");
return Self{
.activity = activity,
.env = env,
.activity_class = activityClass,
};
}
pub fn deinit(self: *Self) void {
_ = self.activity.vm.*.DetachCurrentThread(self.activity.vm);
self.* = undefined;
}
fn JniReturnType(comptime function: @TypeOf(.literal)) type {
@setEvalBranchQuota(10_000);
return @typeInfo(std.meta.fieldInfo(android.JNINativeInterface, @tagName(function)).field_type).Fn.return_type.?;
}
fn invokeJni(self: *Self, comptime function: @TypeOf(.literal), args: anytype) JniReturnType(function) {
return @call(
.{},
@field(self.env.*, @tagName(function)),
.{self.env} ++ args,
);
}
fn findClass(self: *Self, class: [:0]const u8) android.jclass {
return self.invokeJni(.FindClass, .{class.ptr});
}
pub fn AndroidGetUnicodeChar(self: *Self, keyCode: c_int, metaState: c_int) u21 {
// https://stackoverflow.com/questions/21124051/receive-complete-android-unicode-input-in-c-c/43871301
const eventType = android.AKEY_EVENT_ACTION_DOWN;
const class_key_event = self.findClass("android/view/KeyEvent");
const method_get_unicode_char = self.invokeJni(.GetMethodID, .{ class_key_event, "getUnicodeChar", "(I)I" });
const eventConstructor = self.invokeJni(.GetMethodID, .{ class_key_event, "<init>", "(II)V" });
const eventObj = self.invokeJni(.NewObject, .{ class_key_event, eventConstructor, eventType, keyCode });
const unicodeKey = self.invokeJni(.CallIntMethod, .{ eventObj, method_get_unicode_char, metaState });
return @intCast(u21, unicodeKey);
}
fn AndroidMakeFullscreen(self: *Self) void {
// Partially based on
// https://stackoverflow.com/questions/47507714/how-do-i-enable-full-screen-immersive-mode-for-a-native-activity-ndk-app
// Get android.app.NativeActivity, then get getWindow method handle, returns
// view.Window type
const activityClass = self.findClass("android/app/NativeActivity");
const getWindow = self.invokeJni(.GetMethodID, .{ activityClass, "getWindow", "()Landroid/view/Window;" });
const window = self.invokeJni(.CallObjectMethod, .{ self.activity.clazz, getWindow });
// Get android.view.Window class, then get getDecorView method handle, returns
// view.View type
const windowClass = self.findClass("android/view/Window");
const getDecorView = self.invokeJni(.GetMethodID, .{ windowClass, "getDecorView", "()Landroid/view/View;" });
const decorView = self.invokeJni(.CallObjectMethod, .{ window, getDecorView });
// Get the flag values associated with systemuivisibility
const viewClass = self.findClass("android/view/View");
const flagLayoutHideNavigation = self.invokeJni(.GetStaticIntField, .{ viewClass, self.invokeJni(.GetStaticFieldID, .{ viewClass, "SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION", "I" }) });
const flagLayoutFullscreen = self.invokeJni(.GetStaticIntField, .{ viewClass, self.invokeJni(.GetStaticFieldID, .{ viewClass, "SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN", "I" }) });
const flagLowProfile = self.invokeJni(.GetStaticIntField, .{ viewClass, self.invokeJni(.GetStaticFieldID, .{ viewClass, "SYSTEM_UI_FLAG_LOW_PROFILE", "I" }) });
const flagHideNavigation = self.invokeJni(.GetStaticIntField, .{ viewClass, self.invokeJni(.GetStaticFieldID, .{ viewClass, "SYSTEM_UI_FLAG_HIDE_NAVIGATION", "I" }) });
const flagFullscreen = self.invokeJni(.GetStaticIntField, .{ viewClass, self.invokeJni(.GetStaticFieldID, .{ viewClass, "SYSTEM_UI_FLAG_FULLSCREEN", "I" }) });
const flagImmersiveSticky = self.invokeJni(.GetStaticIntField, .{ viewClass, self.invokeJni(.GetStaticFieldID, .{ viewClass, "SYSTEM_UI_FLAG_IMMERSIVE_STICKY", "I" }) });
const setSystemUiVisibility = self.invokeJni(.GetMethodID, .{ viewClass, "setSystemUiVisibility", "(I)V" });
// Call the decorView.setSystemUiVisibility(FLAGS)
self.invokeJni(.CallVoidMethod, .{
decorView,
setSystemUiVisibility,
(flagLayoutHideNavigation | flagLayoutFullscreen | flagLowProfile | flagHideNavigation | flagFullscreen | flagImmersiveSticky),
});
// now set some more flags associated with layoutmanager -- note the $ in the
// class path search for api-versions.xml
// https://android.googlesource.com/platform/development/+/refs/tags/android-9.0.0_r48/sdk/api-versions.xml
const layoutManagerClass = self.findClass("android/view/WindowManager$LayoutParams");
const flag_WinMan_Fullscreen = self.invokeJni(.GetStaticIntField, .{ layoutManagerClass, self.invokeJni(.GetStaticFieldID, .{ layoutManagerClass, "FLAG_FULLSCREEN", "I" }) });
const flag_WinMan_KeepScreenOn = self.invokeJni(.GetStaticIntField, .{ layoutManagerClass, self.invokeJni(.GetStaticFieldID, .{ layoutManagerClass, "FLAG_KEEP_SCREEN_ON", "I" }) });
const flag_WinMan_hw_acc = self.invokeJni(.GetStaticIntField, .{ layoutManagerClass, self.invokeJni(.GetStaticFieldID, .{ layoutManagerClass, "FLAG_HARDWARE_ACCELERATED", "I" }) });
// const int flag_WinMan_flag_not_fullscreen =
// env.GetStaticIntField(layoutManagerClass,
// (env.GetStaticFieldID(layoutManagerClass, "FLAG_FORCE_NOT_FULLSCREEN",
// "I") ));
// call window.addFlags(FLAGS)
self.invokeJni(.CallVoidMethod, .{
window,
self.invokeJni(.GetMethodID, .{ windowClass, "addFlags", "(I)V" }),
(flag_WinMan_Fullscreen | flag_WinMan_KeepScreenOn | flag_WinMan_hw_acc),
});
}
pub fn AndroidDisplayKeyboard(self: *Self, show: bool) bool {
// Based on
// https://stackoverflow.com/questions/5864790/how-to-show-the-soft-keyboard-on-native-activity
var lFlags: android.jint = 0;
// Retrieves Context.INPUT_METHOD_SERVICE.
const ClassContext = self.findClass("android/content/Context");
const FieldINPUT_METHOD_SERVICE = self.invokeJni(.GetStaticFieldID, .{ ClassContext, "INPUT_METHOD_SERVICE", "Ljava/lang/String;" });
const INPUT_METHOD_SERVICE = self.invokeJni(.GetStaticObjectField, .{ ClassContext, FieldINPUT_METHOD_SERVICE });
// Runs getSystemService(Context.INPUT_METHOD_SERVICE).
const ClassInputMethodManager = self.findClass("android/view/inputmethod/InputMethodManager");
const MethodGetSystemService = self.invokeJni(.GetMethodID, .{ self.activity_class, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;" });
const lInputMethodManager = self.invokeJni(.CallObjectMethod, .{ self.activity.clazz, MethodGetSystemService, INPUT_METHOD_SERVICE });
// Runs getWindow().getDecorView().
const MethodGetWindow = self.invokeJni(.GetMethodID, .{ self.activity_class, "getWindow", "()Landroid/view/Window;" });
const lWindow = self.invokeJni(.CallObjectMethod, .{ self.activity.clazz, MethodGetWindow });
const ClassWindow = self.findClass("android/view/Window");
const MethodGetDecorView = self.invokeJni(.GetMethodID, .{ ClassWindow, "getDecorView", "()Landroid/view/View;" });
const lDecorView = self.invokeJni(.CallObjectMethod, .{ lWindow, MethodGetDecorView });
if (show) {
// Runs lInputMethodManager.showSoftInput(...).
const MethodShowSoftInput = self.invokeJni(.GetMethodID, .{ ClassInputMethodManager, "showSoftInput", "(Landroid/view/View;I)Z" });
return 0 != self.invokeJni(.CallBooleanMethod, .{ lInputMethodManager, MethodShowSoftInput, lDecorView, lFlags });
} else {
// Runs lWindow.getViewToken()
const ClassView = self.findClass("android/view/View");
const MethodGetWindowToken = self.invokeJni(.GetMethodID, .{ ClassView, "getWindowToken", "()Landroid/os/IBinder;" });
const lBinder = self.invokeJni(.CallObjectMethod, .{ lDecorView, MethodGetWindowToken });
// lInputMethodManager.hideSoftInput(...).
const MethodHideSoftInput = self.invokeJni(.GetMethodID, .{ ClassInputMethodManager, "hideSoftInputFromWindow", "(Landroid/os/IBinder;I)Z" });
return 0 != self.invokeJni(.CallBooleanMethod, .{ lInputMethodManager, MethodHideSoftInput, lBinder, lFlags });
}
}
/// Move the task containing this activity to the back of the activity stack.
/// The activity's order within the task is unchanged.
/// nonRoot: If false then this only works if the activity is the root of a task; if true it will work for any activity in a task.
/// returns: If the task was moved (or it was already at the back) true is returned, else false.
pub fn AndroidSendToBack(self: *Self, nonRoot: bool) bool {
const ClassActivity = self.findClass("android/app/Activity");
const MethodmoveTaskToBack = self.invokeJni(.GetMethodID, .{ ClassActivity, "moveTaskToBack", "(Z)Z" });
return 0 != self.invokeJni(.CallBooleanMethod, .{ self.activity.clazz, MethodmoveTaskToBack, if (nonRoot) @as(c_int, 1) else 0 });
}
pub fn AndroidHasPermissions(self: *Self, perm_name: [:0]const u8) bool {
if (android.sdk_version < 23) {
log.err(
"Android SDK version {} does not support AndroidRequestAppPermissions\n",
.{android.sdk_version},
);
return false;
}
const ls_PERM = self.invokeJni(.NewStringUTF, .{perm_name});
const PERMISSION_GRANTED = blk: {
var ClassPackageManager = self.findClass("android/content/pm/PackageManager");
var lid_PERMISSION_GRANTED = self.invokeJni(.GetStaticFieldID, .{ ClassPackageManager, "PERMISSION_GRANTED", "I" });
break :blk self.invokeJni(.GetStaticIntField, .{ ClassPackageManager, lid_PERMISSION_GRANTED });
};
const ClassContext = self.findClass("android/content/Context");
const MethodcheckSelfPermission = self.invokeJni(.GetMethodID, .{ ClassContext, "checkSelfPermission", "(Ljava/lang/String;)I" });
const int_result = self.invokeJni(.CallIntMethod, .{ self.activity.clazz, MethodcheckSelfPermission, ls_PERM });
return (int_result == PERMISSION_GRANTED);
}
pub fn AndroidRequestAppPermissions(self: *Self, perm_name: [:0]const u8) void {
if (android.sdk_version < 23) {
log.err(
"Android SDK version {} does not support AndroidRequestAppPermissions\n",
.{android.sdk_version},
);
return;
}
const perm_array = self.invokeJni(.NewObjectArray, .{
1,
self.findClass("java/lang/String"),
self.invokeJni(.NewStringUTF, .{perm_name}),
});
const MethodrequestPermissions = self.invokeJni(.GetMethodID, .{ self.activity_class, "requestPermissions", "([Ljava/lang/String;I)V" });
// Last arg (0) is just for the callback (that I do not use)
self.invokeJni(.CallVoidMethod, .{ self.activity.clazz, MethodrequestPermissions, perm_array, @as(c_int, 0) });
}
comptime {
_ = AndroidGetUnicodeChar;
_ = AndroidMakeFullscreen;
_ = AndroidDisplayKeyboard;
_ = AndroidSendToBack;
_ = AndroidHasPermissions;
_ = AndroidRequestAppPermissions;
}
}; | src/jni.zig |
const std = @import("std");
const builtin = @import("builtin");
pub const path_seperator = if (builtin.os.tag == builtin.Os.Tag.windows) "\\" else "/";
// Loads file into memory (plus a zero byte) and stores file struct in the given pointer
// The file is _not_ closed
pub fn loadFileWithNullTerminator2(file_path: []const u8, file: *std.fs.File, allocator: *std.mem.Allocator) ![]u8 {
file.* = try std.fs.cwd().openFile(file_path, std.fs.File.OpenFlags{});
errdefer file.*.close();
var size: usize = try file.*.getEndPos();
var buf: []u8 = try allocator.alloc(u8, size + 1);
const bytesRead = try file.*.read(buf[0..size]);
if (bytesRead != size) {
return error.IOError;
}
buf[size] = 0;
return buf;
}
// Loads file into memory (plus a zero byte) and closes the file handle
pub fn loadFileWithNullTerminator(file_path: []const u8, allocator: *std.mem.Allocator) ![]u8 {
var f: std.fs.File = undefined;
const buf = try loadFileWithNullTerminator2(file_path, &f, allocator);
f.close();
return buf;
}
// Loads file into memory without modification and closes the file handle.
pub fn loadFile(file_path: []const u8, allocator: *std.mem.Allocator) ![]align(4) u8 {
var in_file = try std.fs.cwd().openFile(file_path, std.fs.File.OpenFlags{});
defer in_file.close();
var size: usize = try in_file.getEndPos();
var buf = try allocator.alignedAlloc(u8, 4, size);
const bytesRead = try in_file.read(buf[0..]);
if (bytesRead != size) {
return error.IOError;
}
return buf;
}
pub fn loadFileAligned(alignment: u32, file_path: []const u8, allocator: *std.mem.Allocator) ![]u8 {
var in_file = try std.fs.cwd().openFile(file_path, std.fs.File.OpenFlags{});
defer in_file.close();
var size: usize = try in_file.getEndPos();
var buf = try allocator.alignedAlloc(u8, alignment, size);
const bytesRead = try in_file.read(buf[0..]);
if (bytesRead != size) {
return error.IOError;
}
return buf;
} | src/Files.zig |
const std = @import("std");
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
const Tag = std.meta.Tag;
const Foo = union {
float: f64,
int: i32,
};
test "basic unions" {
var foo = Foo{ .int = 1 };
try expect(foo.int == 1);
foo = Foo{ .float = 12.34 };
try expect(foo.float == 12.34);
}
test "init union with runtime value" {
var foo: Foo = undefined;
setFloat(&foo, 12.34);
try expect(foo.float == 12.34);
setInt(&foo, 42);
try expect(foo.int == 42);
}
fn setFloat(foo: *Foo, x: f64) void {
foo.* = Foo{ .float = x };
}
fn setInt(foo: *Foo, x: i32) void {
foo.* = Foo{ .int = x };
}
test "comptime union field access" {
comptime {
var foo = Foo{ .int = 0 };
try expect(foo.int == 0);
foo = Foo{ .float = 42.42 };
try expect(foo.float == 42.42);
}
}
const FooExtern = extern union {
float: f64,
int: i32,
};
test "basic extern unions" {
var foo = FooExtern{ .int = 1 };
try expect(foo.int == 1);
foo.float = 12.34;
try expect(foo.float == 12.34);
}
const ExternPtrOrInt = extern union {
ptr: *u8,
int: u64,
};
test "extern union size" {
comptime try expect(@sizeOf(ExternPtrOrInt) == 8);
}
test "0-sized extern union definition" {
const U = extern union {
a: void,
const f = 1;
};
try expect(U.f == 1);
}
const Value = union(enum) {
Int: u64,
Array: [9]u8,
};
const Agg = struct {
val1: Value,
val2: Value,
};
const v1 = Value{ .Int = 1234 };
const v2 = Value{ .Array = [_]u8{3} ** 9 };
const err = @as(anyerror!Agg, Agg{
.val1 = v1,
.val2 = v2,
});
const array = [_]Value{ v1, v2, v1, v2 };
test "unions embedded in aggregate types" {
switch (array[1]) {
Value.Array => |arr| try expect(arr[4] == 3),
else => unreachable,
}
switch ((err catch unreachable).val1) {
Value.Int => |x| try expect(x == 1234),
else => unreachable,
}
}
test "access a member of tagged union with conflicting enum tag name" {
const Bar = union(enum) {
A: A,
B: B,
const A = u8;
const B = void;
};
comptime try expect(Bar.A == u8);
}
test "constant tagged union with payload" {
var empty = TaggedUnionWithPayload{ .Empty = {} };
var full = TaggedUnionWithPayload{ .Full = 13 };
shouldBeEmpty(empty);
shouldBeNotEmpty(full);
}
fn shouldBeEmpty(x: TaggedUnionWithPayload) void {
switch (x) {
TaggedUnionWithPayload.Empty => {},
else => unreachable,
}
}
fn shouldBeNotEmpty(x: TaggedUnionWithPayload) void {
switch (x) {
TaggedUnionWithPayload.Empty => unreachable,
else => {},
}
}
const TaggedUnionWithPayload = union(enum) {
Empty: void,
Full: i32,
};
test "union alignment" {
comptime {
try expect(@alignOf(AlignTestTaggedUnion) >= @alignOf([9]u8));
try expect(@alignOf(AlignTestTaggedUnion) >= @alignOf(u64));
}
}
const AlignTestTaggedUnion = union(enum) {
A: [9]u8,
B: u64,
}; | test/behavior/union.zig |
usingnamespace @import("../preamble.zig");
pub const kernel = .{
// Build mode
.build_mode = .ReleaseSafe,
// Max number of CPU cores to use
.max_cpus = 0x200,
// True if symbols should be stripped
.strip_symbols = false,
// True if source blob should be created
.build_source_blob = true,
.x86_64 = .{
// Allow using the `syscall` instruction to do syscalls
.allow_syscall_instr = true,
// The maximum number of IOAPICs to use
.max_ioapics = 5,
// Enable ps2 devices
// Your system managment mode may emulate a ps2 keyboard
// when you connect a usb keyboard. If you disable this,
// that won't work.
.ps2 = .{
.keyboard = .{
.enable = true,
},
.mouse = .{
.enable = true,
},
},
// VMWARE integration for things like absolute cursor position.
// This is also implemented in other virtualization software
// like QEMU.
.vmware = .{
.enable = true,
.abscursor = true,
},
// Port E9 debug logging
.e9 = .{
.enable = true,
},
.serial = .{
.enabled_ports = [_]comptime_int{
//1,
//2,
//3,
//4,
},
},
},
// True if kernel should panic only once
.panic_once = true,
// Kepler settings
.kepler = .{
// If true, runs kepler tests after system initialization
.run_tests = true,
// Number of messages that should be sent in the benchmark
.bench_msg_count = 100,
},
.pci = .{
// Toggle for PCI bus enumeration and device discovery
.enable = true,
},
};
pub const copernicus = .{
// Build mode
.build_mode = .Debug,
// True if symbols should be stripped
.strip_symbols = false,
// True if source blob should be created
.build_source_blob = true,
};
pub const drivers = .{
.block = .{
.ahci = .{
.enable = true,
},
.nvme = .{
.enable = true,
},
},
.gpu = .{
.virtio = .{
.enable = true,
.default_resolution = .{
.width = 1280,
.height = 720,
},
},
},
.misc = .{},
.net = .{
.e1000 = .{
.enable = true,
},
},
.output = .{
.vesa_log = .{
.enable = true,
.font = assets.fonts.fixed_6x13,
.background = .{
.red = 0x20,
.green = 0x20,
.blue = 0x20,
},
.foreground = .{
.red = 0xbf,
.green = 0xbf,
.blue = 0xbf,
},
},
.vga_log = .{
.enable = true,
},
},
.usb = .{
.xhci = .{
.enable = true,
},
},
};
// Default keyboard layout
pub const keyboard_layout = .en_US_QWERTY; | config/config.zig |
const std = @import("std");
const parser = @import("parser.zig");
const ast = @import("ast.zig");
const errors = @import("error.zig");
const lir = @import("ir.zig");
const Allocator = std.mem.Allocator;
const testing = std.testing;
const Type = @import("Value.zig").Type;
//! Contains the Compiler internals.
//! This compiles all AST nodes generated by the parser and turned into `ByteCode` instructions
//! Those instructions are than used by the vm to be executed.
//! Potentially, we could provide a different back-end to support
//! different use cases.
/// Compiles the source code into Luf's bytecode
pub fn compile(
allocator: *Allocator,
source: []const u8,
_errors: *errors.Errors,
) (parser.Parser.Error || Compiler.Error)!lir.CompileUnit {
const tree = try parser.parse(allocator, source, _errors);
defer tree.deinit();
var root_scope = Compiler.Scope{
.symbols = Compiler.SymbolTable{},
.id = .global,
.allocator = allocator,
};
defer {
for (root_scope.symbols.items()) |entry| {
allocator.destroy(entry.value);
}
root_scope.symbols.deinit(allocator);
}
var arena = std.heap.ArenaAllocator.init(allocator);
errdefer arena.deinit();
var module = lir.Module{ .gpa = &arena.allocator };
var compiler = Compiler{
.instructions = lir.Instructions{},
.allocator = allocator,
.scope = &root_scope,
.errors = _errors,
.ir = &module,
.modules = std.StringHashMapUnmanaged(*Compiler.Module){},
.module_states = std.ArrayListUnmanaged(std.heap.ArenaAllocator.State){},
};
defer compiler.deinit();
// declare all functions first
try compiler.forwardDeclareNodes(tree.nodes);
for (tree.nodes) |node| {
if (node == .declaration and canBeForwardDeclared(node.declaration.value)) continue; // already compiled above
try compiler.instructions.append(allocator, try compiler.resolveInst(node));
}
return lir.CompileUnit{
.gpa = allocator,
.state = arena.state,
.instructions = compiler.instructions.toOwnedSlice(allocator),
};
}
/// Returns true if the given `Node` can be forward declared
fn canBeForwardDeclared(node: ast.Node) bool {
return switch (node) {
.int_lit,
.string_lit,
.func_lit,
.data_structure,
.nil,
.slice,
=> true,
else => false,
};
}
/// Contains the memory and generated instructions
/// after calling Compile()
pub const Compiler = struct {
/// The instruction set the compiler is building
instructions: lir.Instructions,
/// Allocator used to allocate to the heap, call deinit() on compiler to free all memory
allocator: *Allocator,
/// Any errors generated by the compiler will be appended to `errors`
errors: *errors.Errors,
/// Imported modules and their global symboltable
modules: std.StringHashMapUnmanaged(*Module),
/// Arena states which will be freed once we finished compilation
/// This ensures all Nodes that are imported from other files have a long enough
/// lifetime to be used for typechecking imported functions/variables
module_states: std.ArrayListUnmanaged(std.heap.ArenaAllocator.State),
/// Globals counter, this is increased by 1 each time a global is defined
/// This is increased by both global and module scope
gc: u16 = 0,
/// Current scope of the compilation, i.e. .loop
scope: *Scope,
/// Luf's IR, used to generate instructions
ir: *lir.Module,
/// Compiler errorset
pub const Error = error{ CompilerError, OutOfMemory };
/// Hashmap of `Symbol` where the key is the Symbol's name
const SymbolTable = std.StringArrayHashMapUnmanaged(*Symbol);
/// Symbols known by the compiler
const Symbol = struct {
name: []const u8,
/// Not mutable by default
mutable: bool = false,
/// Not public by default
is_pub: bool = false,
/// Index of symbol table
index: u16 = 0,
/// The scope the symbol belongs to
scope: Scope.Id,
/// The `Ast.Node` that declared the symbol, used to retrieve the symbol's type
node: ast.Node,
/// Set to `true` if the symbol was created during forward declaration
forward_declared: bool,
/// IR declaration
ident: *lir.Inst,
};
/// Module with its global symbols
const Module = struct {
/// symbols existing inside the module
symbols: SymbolTable,
/// used to determine if module still requires codegen
compiled: bool,
};
/// Scope of the current state (function, global, etc)
const Scope = struct {
/// Symbols that exist within the current scope
symbols: SymbolTable,
/// Type of the Scope. i.e. Root, function, etc
id: Tag,
/// If not a global scope, the scope will own a parent
parent: ?*Scope = null,
/// used to create child scopes
allocator: *Allocator,
/// The offset used to calculate symbol indices
offset: u16 = 0,
/// The type of the scope
const Id = enum {
global,
function,
loop,
module,
};
const Tag = union(Id) {
global,
loop,
module: void,
function: *ast.Node.FunctionLiteral,
};
/// Creates a new `Scope` from the current Scope.
/// The new Scope will have its parent set to the current Scope
fn fork(self: *Scope, id: Scope.Id) !*Scope {
const new_scope = try self.allocator.create(Scope);
new_scope.* = .{
.symbols = SymbolTable{},
.id = switch (id) {
.global => .{ .global = {} },
.module => .{ .module = {} },
.function => .{ .function = undefined },
.loop => .{ .loop = {} },
},
.offset = if (self.id == .loop) @truncate(u16, self.symbols.items().len) else 0,
.parent = self,
.allocator = self.allocator,
};
return new_scope;
}
/// Defines a new symbol and saves it in the symbol table
/// Returns an error if Symbol already exists
fn define(
self: *Scope,
name: []const u8,
mutable: bool,
node: ast.Node,
forward_declared: bool,
is_pub: bool,
index: ?u16,
) !?*Symbol {
if (self.symbols.contains(name)) return null;
const new_index = index orelse @intCast(u16, self.symbols.items().len);
const symbol = try self.allocator.create(Symbol);
symbol.* = .{
.name = name,
.mutable = mutable,
.index = new_index + self.offset,
.scope = self.id,
.node = node,
.forward_declared = forward_declared,
.ident = undefined,
.is_pub = is_pub,
};
try self.symbols.putNoClobber(self.allocator, name, symbol);
return symbol;
}
/// Retrieves a `Symbol` from the Scopes symbol table, returns null if not found
fn resolve(self: *const Scope, name: []const u8) ?*Symbol {
return self.symbols.get(name);
}
/// Cleans up the memory of the `Scope`
fn deinit(self: *Scope) void {
for (self.symbols.items()) |entry| {
self.allocator.destroy(entry.value);
}
self.symbols.deinit(self.allocator);
self.allocator.destroy(self);
}
};
/// Frees up any memory allocated by the compiler
fn deinit(self: *Compiler) void {
var it = self.modules.iterator();
while (it.next()) |mod| {
for (mod.value.symbols.items()) |entry| self.allocator.destroy(entry.value);
mod.value.symbols.deinit(self.allocator);
self.allocator.destroy(mod.value);
}
self.modules.deinit(self.allocator);
self.exitScope();
self.instructions.deinit(self.allocator);
for (self.module_states.items) |state| {
state.promote(self.allocator).deinit();
}
self.module_states.deinit(self.allocator);
self.* = undefined;
}
/// Returns `Error.CompilerError` and appends an error message to the `errors` list.
fn fail(self: *Compiler, comptime msg: []const u8, index: usize, args: anytype) Error {
try self.errors.add(msg, index, .err, args);
return Error.CompilerError;
}
/// Sets the current `Scope` to its parent's scope and cleans up the closing scope's memory
fn exitScope(self: *Compiler) void {
if (self.scope.id == .global) return; // can't escape the global scope
if (self.scope.parent) |parent| {
const old = self.scope;
self.scope = parent;
old.deinit();
}
}
/// Creates a new Scope with the given Id, then sets the new scope as the current
fn createScope(self: *Compiler, id: Scope.Id) !void {
self.scope = try self.scope.fork(id);
}
/// Recursively looks for the scope with the given Tag
fn findScope(self: *Compiler, scope: *const Scope, tag: Scope.Id) ?*const Scope {
if (scope.id == tag) return scope;
return if (scope.parent) |parent| self.findScope(parent, tag) else null;
}
/// Attempts to resolve a symbol from the symbol table
/// If not found, will attempt to resolve it from a parent scope
fn resolveSymbol(self: *Compiler, scope: *const Scope, name: []const u8) ?*Symbol {
return scope.resolve(name) orelse if (scope.id != .global and scope.parent != null)
self.resolveSymbol(scope.parent.?, name)
else
null;
}
/// Defines a new symbol in the current scope
fn defineSymbol(
self: *Compiler,
name: []const u8,
mutable: bool,
node: ast.Node,
forward_declared: bool,
is_pub: bool,
) !?*Symbol {
const index: ?u16 = if (self.scope.id == .global or self.scope.id == .module) self.gc else null;
if (try self.scope.define(name, mutable, node, forward_declared, is_pub, index)) |symbol| {
if (index != null) self.gc += 1;
return symbol;
} else return null;
}
/// Returns a Luf `Type` based on the given node
fn resolveType(self: *Compiler, node: ast.Node) !Type {
if (node.getType()) |t| return t;
return switch (node) {
.identifier => |id| {
const symbol = self.resolveSymbol(self.scope, id.value) orelse
return self.fail("'{s}' is undefined", id.token.start, .{id.value});
return self.resolveType(symbol.node);
},
.infix => |inf| return self.resolveType(inf.left),
.declaration => |decl| {
if (decl.type_def) |td| return td.getType().?;
return self.resolveType(decl.value);
},
.index => |index| return self.resolveType(index.left),
.call_expression => |cal| return self.resolveType(cal.function),
.slice => |slice| return self.resolveType(slice.left),
else => std.debug.panic("TODO, implement type resolving for type: {s}\n", .{node}),
};
}
/// Resolves the inner type of a node. i.e. this will return `Type.integer` for a list []int
fn resolveScalarType(self: *Compiler, node: ast.Node) Error!Type {
if (node.getInnerType()) |i| return i;
return switch (node) {
.identifier => |id| {
const symbol = self.resolveSymbol(
self.scope,
id.value,
) orelse return self.fail("'{s}' is undefined", id.token.start, .{id.value});
return self.resolveScalarType(symbol.node);
},
.infix => |inf| return self.resolveScalarType(inf.left),
.declaration => |decl| {
if (decl.type_def) |td| return td.getInnerType().?;
return self.resolveScalarType(decl.value);
},
.index => |index| {
const temp_type = try self.resolveScalarType(index.left);
if (temp_type == .module) {
const function_name = index.index.string_lit.value;
const symbol = self.resolveSymbol(self.scope, index.left.identifier.value) orelse
return self.fail(
"'{s}' is undefined",
index.left.tokenPos(),
.{index.left.identifier.value},
);
const mod: *Module = self.modules.get(symbol.node.declaration.value.import.value.string_lit.value) orelse
return Type.function; // Module imported by VM, therefore just return it as a function
const function_symbol: *Symbol = mod.symbols.get(function_name) orelse
return self.fail("Module does not contain function '{s}'", index.index.tokenPos(), .{function_name});
return self.resolveScalarType(function_symbol.node);
}
return self.resolveScalarType(index.left);
},
.call_expression => |cal| return self.resolveScalarType(cal.function),
.slice => |slice| return self.resolveScalarType(slice.left),
else => std.debug.panic("TODO, implement scalar type resolving for type: {s}\n", .{node.getType()}),
};
}
/// Retrieves all symbols for Nodes of type declaration
fn forwardDeclareNodes(self: *Compiler, nodes: []const ast.Node) !void {
for (nodes) |node| {
if (node != .declaration) continue;
const decl = node.declaration;
if (decl.value == .import) {
try self.forwardDeclareImport(decl.value.import);
continue;
} else if (!canBeForwardDeclared(decl.value)) continue;
const symbol = (try self.defineSymbol(
decl.name.identifier.value,
decl.mutable,
node,
true,
decl.is_pub,
)) orelse return self.fail(
"'{s}' has already been declared",
node.tokenPos(),
.{decl.name.identifier.value},
);
symbol.ident = try self.ir.emitIdent(
try self.resolveType(node),
node.tokenPos(),
symbol.name,
.global,
symbol.index,
);
}
for (self.scope.symbols.items()) |entry| {
const symbol: *Symbol = entry.value;
const value = try self.resolveInst(symbol.node.declaration.value);
const decl = try self.ir.emitDecl(
symbol.node.tokenPos(),
symbol.name,
symbol.index,
.global,
symbol.is_pub,
symbol.mutable,
value,
);
try self.instructions.append(self.allocator, decl);
}
}
/// Forward declares all functions from a module, so we can do type checking for imported
/// functions.
fn forwardDeclareImport(self: *Compiler, node: *const ast.Node.Import) !void {
const file_name = node.value.string_lit.value;
if (self.modules.contains(file_name)) return;
if (!std.mem.endsWith(u8, file_name, ".luf")) return;
const file = std.fs.cwd().openFile(file_name, .{}) catch
return self.fail("Cannot open file with path '{s}'", node.value.tokenPos(), .{file_name});
defer file.close();
const size = file.getEndPos() catch return self.fail("Unable to find file size", node.value.tokenPos(), .{});
const source = file.reader().readAllAlloc(self.allocator, size) catch return self.fail(
"Failed to read content of file with path '{s}'",
node.value.tokenPos(),
.{file_name},
);
defer self.allocator.free(source);
const tree = try parser.parse(self.allocator, source, self.errors);
errdefer tree.deinit();
const module = try self.allocator.create(Module);
errdefer self.allocator.destroy(module);
module.* = .{ .symbols = SymbolTable{}, .compiled = false };
errdefer module.symbols.deinit(self.allocator);
for (tree.nodes) |n| {
if (n != .declaration or n.declaration.value != .func_lit) continue;
if (!n.declaration.is_pub) continue; // only public declarations
const decl = n.declaration;
const name = decl.name.identifier.value;
if (module.symbols.contains(name))
return self.fail("Identifier '{s}' already exists", n.declaration.name.tokenPos(), .{name});
const symbol = try self.allocator.create(Symbol);
symbol.* = .{
.name = name,
.mutable = decl.mutable,
.scope = .global,
.node = n,
.forward_declared = true,
.index = self.gc,
.ident = undefined,
.is_pub = decl.is_pub,
};
try module.symbols.putNoClobber(self.allocator, name, symbol);
self.gc += 1;
}
try self.modules.putNoClobber(self.allocator, file_name, module);
try self.module_states.append(self.allocator, tree.arena);
}
/// Depending on an `ast.Node` type, generates a `lir.Inst` instruction recursively
fn resolveInst(self: *Compiler, node: ast.Node) (Error || lir.Module.Error || parser.Parser.Error)!*lir.Inst {
return try switch (node) {
.expression => |exp| self.compileExpr(exp),
.block_statement => |block| self.compileBlock(block),
.infix => |infix| self.compileInfix(infix),
.prefix => |prefix| self.compilePrefix(prefix),
.boolean => |boolean| self.compileBool(boolean),
.int_lit => |int| self.ir.emitInt(node.tokenPos(), int.value),
.if_expression => |if_exp| self.compileCond(if_exp),
.declaration => |decl| self.compileDecl(decl, node),
.identifier => |ident| self.compileIdent(ident),
.string_lit => |string| self.ir.emitString(.string, node.tokenPos(), string.value),
.data_structure => |ds| self.compileData(ds),
.map_pair => |pair| self.compilePair(pair),
.index => |index| self.compileIndex(index),
.func_lit => |func| self.compileFunc(func),
.call_expression => |call| self.compileCall(call),
.@"return" => |ret| self.compileRet(ret),
.while_loop => |loop| self.compileWhile(loop),
.for_loop => |loop| self.compileFor(loop),
.assignment => |asgn| self.compileAssign(asgn),
.nil => self.ir.emitPrimitive(node.tokenPos(), .nil),
.import => |imp| self.compileImport(imp),
.@"break" => self.ir.emitNoOp(node.tokenPos(), .@"break"),
.@"continue" => self.ir.emitNoOp(node.tokenPos(), .@"continue"),
.range => |range| self.compileRange(range),
.@"enum" => |enm| self.compileEnum(enm),
.switch_statement => |sw| self.compileSwitch(sw),
.switch_prong => |prong| self.comileProng(prong),
.comment => |cmt| self.ir.emitString(.comment, node.tokenPos(), cmt.value),
.type_def => |td| self.compileTypeDef(td),
.func_arg => |arg| self.compileFuncArg(arg),
.slice => |slice| self.compileSlice(slice),
};
}
/// Compiles an `ast.Node.Expression` into a `lir.Inst.Single` this can be used
/// by backends to know when an expression ends. For example, to pop a value.
fn compileExpr(self: *Compiler, exp: *ast.Node.Expression) !*lir.Inst {
const rhs = try self.resolveInst(exp.value);
return self.ir.emitSingle(exp.token.start, .expr, rhs);
}
/// Compiles a `ast.Node.BlockStatement` node into a list of instructions
fn compileBlock(self: *Compiler, block: *ast.Node.BlockStatement) !*lir.Inst {
const list = try self.ir.gpa.alloc(*lir.Inst, block.nodes.len);
for (block.nodes) |node, i| list[i] = try self.resolveInst(node);
return self.ir.emitBlock(block.token.start, list);
}
/// Compiles an `ast.Node.Infix` node into a `lir.Inst.Double`
fn compileInfix(self: *Compiler, infix: *ast.Node.Infix) !*lir.Inst {
var lhs = try self.resolveType(infix.left);
var rhs = try self.resolveType(infix.right);
if (lhs == .list or lhs == .range or lhs == .function) lhs = try self.resolveScalarType(infix.left);
if (rhs == .list or rhs == .range or rhs == .function) rhs = try self.resolveScalarType(infix.right);
if (lhs != rhs)
return self.fail("Expected type {s} but found type {s}", infix.right.tokenPos(), .{ lhs, rhs });
const lhs_inst = try self.resolveInst(infix.left);
const rhs_inst = try self.resolveInst(infix.right);
return self.ir.emitDouble(infix.token.start, switch (infix.operator) {
.add => .add,
.multiply => .mul,
.sub => .sub,
.divide => .div,
.less_than => .lt,
.greater_than => .gt,
.equal => .eql,
.not_equal => .nql,
.mod => .mod,
.@"and" => .@"and",
.@"or" => .@"or",
.bitwise_xor => .bitwise_xor,
.bitwise_or => .bitwise_or,
.bitwise_and => .bitwise_and,
.shift_left => .shift_left,
.shift_right => .shift_right,
.assign_add => .assign_add,
.assign_sub => .assign_sub,
.assign_mul => .assign_mul,
.assign_div => .assign_div,
.assign => .assign,
}, lhs_inst, rhs_inst);
}
/// Compiles an `ast.Node.Prefix` node into a `lir.Inst.Single`
fn compilePrefix(self: *Compiler, prefix: *ast.Node.Prefix) !*lir.Inst {
return self.ir.emitSingle(
prefix.token.start,
switch (prefix.operator) {
.minus => .negate,
.bang => .not,
.bitwise_not => .bitwise_not,
},
try self.resolveInst(prefix.right),
);
}
/// Compiles an `ast.Node.Prefix` node into a `lir.Inst.Primitive`
fn compileBool(self: *Compiler, boolean: *ast.Node.Bool) !*lir.Inst {
return self.ir.emitPrimitive(boolean.token.start, if (boolean.value) .@"true" else .@"false");
}
/// Compiles an `ast.Node.IfExpression` node into a `lir.Inst.If`
fn compileCond(self: *Compiler, node: *ast.Node.IfExpression) !*lir.Inst {
const cond = try self.resolveInst(node.condition);
const then_block = try self.resolveInst(node.true_pong);
const else_block = if (node.false_pong) |f| try self.resolveInst(f) else null;
return self.ir.emitCond(node.token.start, cond, then_block, else_block);
}
/// Compiles an `ast.Node.Declaration` node into a `lir.Inst.Decl`
/// This will create a new symbol in the symbol table for the current scope
fn compileDecl(self: *Compiler, decl: *ast.Node.Declaration, node: ast.Node) !*lir.Inst {
if (decl.type_def) |td| {
const explicit_type = try self.resolveType(td);
const rhs_type = blk: {
const tmp = try self.resolveType(decl.value);
// if function, get the return type of the function
if (tmp == .function or tmp == .module) break :blk try self.resolveScalarType(decl.value);
break :blk tmp;
};
if (rhs_type == .nil and explicit_type != .optional)
return self.fail("Cannot assign `nil` value to non-optional", decl.value.tokenPos(), .{})
else if (explicit_type != .optional and explicit_type != rhs_type) {
return self.fail("Expected type {s} but found type {s}", decl.value.tokenPos(), .{ explicit_type, rhs_type });
}
}
const symbol = if (self.resolveSymbol(self.scope, decl.name.identifier.value)) |s| blk: {
if (s.forward_declared and (self.scope.id == .global or self.scope.id == .module)) {
s.forward_declared = false;
break :blk s;
} else {
return self.fail("Identifier '{s}' has already been declared", decl.token.start, .{decl.name.identifier.value});
}
} else blk: {
const s = (try self.defineSymbol(decl.name.identifier.value, decl.mutable, node, false, decl.is_pub)).?;
s.ident = try self.ir.emitIdent(
try self.resolveScalarType(decl.value),
node.tokenPos(),
s.name,
switch (s.scope) {
.global, .module => .global,
else => .local,
},
s.index,
);
break :blk s;
};
const decl_value = try self.resolveInst(decl.value);
return try self.ir.emitDecl(
decl.token.start,
symbol.name,
symbol.index,
switch (symbol.scope) {
.global, .module => .global,
else => .local,
},
symbol.is_pub,
symbol.mutable,
decl_value,
);
}
/// Compiles an `ast.Node.Identifier` node into a `lir.Inst.Ident`
fn compileIdent(self: *Compiler, id: *ast.Node.Identifier) !*lir.Inst {
const symbol = self.resolveSymbol(self.scope, id.value) orelse
return self.fail("Identifier '{s}' is undefined", id.token.start, .{id.value});
return symbol.ident;
}
/// Compiles an `ast.Node.DataStructure` node into a `lir.Inst.DataStructure`
/// Also compiles all elements
fn compileData(self: *Compiler, ds: *ast.Node.DataStructure) !*lir.Inst {
const inner_type = try self.resolveScalarType(ds.type_def_key);
const elements = try self.ir.gpa.alloc(*lir.Inst, ds.value.?.len);
// ds.value will only be null if it's specified as a type rather than an expression
for (ds.value.?) |element, i| {
const el_type = try self.resolveScalarType(element);
if (inner_type != el_type)
return self.fail(
"Expected type {s} but found type {s} for element {d}",
element.tokenPos(),
.{ inner_type, el_type, i },
);
elements[i] = try self.resolveInst(element);
}
return self.ir.emitList(
if (ds.d_type == .array) .list else .map,
ds.token.start,
elements,
);
}
/// Compiles an `ast.Node.MapPair` node into a `lir.Inst.Double`
fn compilePair(self: *Compiler, node: *ast.Node.MapPair) !*lir.Inst {
const key = try self.resolveInst(node.key);
const value = try self.resolveInst(node.value);
return self.ir.emitDouble(node.token.start, .pair, key, value);
}
/// Compiles an `ast.Node.Index` node into a `lir.Inst.Double`
fn compileIndex(self: *Compiler, index: *ast.Node.IndexExpression) !*lir.Inst {
if ((try self.resolveType(index.left)) == .module and index.left == .identifier) {
const module_symol = self.resolveSymbol(self.scope, index.left.identifier.value).?;
const module_name = module_symol.node.declaration.value.import.value.string_lit.value;
if (self.modules.get(module_name)) |module| {
const func_name = index.index.string_lit.value;
var func: *Symbol = module.symbols.get(func_name).?;
return try self.ir.emitIdent(
try self.resolveType(func.node),
index.token.start,
func.name,
.global,
func.index,
);
}
}
const lhs = try self.resolveInst(index.left);
const rhs = try self.resolveInst(index.index);
return self.ir.emitDouble(index.token.start, .load, lhs, rhs);
}
/// Compiles an `ast.Node.FuntionLiteral` node into a `lir.Inst.Func`
fn compileFunc(self: *Compiler, function: *ast.Node.FunctionLiteral) !*lir.Inst {
try self.createScope(.function);
self.scope.id.function = function;
const args = try self.ir.gpa.alloc(*lir.Inst, function.params.len);
for (function.params) |param, i| {
args[i] = try self.resolveInst(param);
}
const body = try self.resolveInst(function.body orelse return self.fail(
"Function body missing",
function.token.start,
.{},
));
// get locals
const locals = try self.ir.gpa.alloc(*lir.Inst, self.scope.symbols.items().len);
for (self.scope.symbols.items()) |entry, i|
locals[i] = entry.value.ident;
self.exitScope();
const ret_type = try self.resolveInst(function.ret_type);
return self.ir.emitFunc(
function.token.start,
body,
locals,
args,
ret_type,
);
}
/// Compiles an `ast.Node.FunctionArgument` into a `lir.Inst.FuncArg`
fn compileFuncArg(self: *Compiler, arg: *ast.Node.FunctionArgument) !*lir.Inst {
const ty = try self.resolveType(arg.arg_type);
const name = arg.value;
// function arguments are not mutable by default
const symbol = (try self.defineSymbol(name, false, arg.arg_type, false, false)) orelse
return self.fail(
"Identifier '{s}' has already been declared",
arg.token.start,
.{name},
);
symbol.ident = try self.ir.emitIdent(
ty,
arg.token.start,
symbol.name,
.local,
symbol.index,
);
return self.ir.emitFuncArg(arg.token.start, ty, name);
}
/// Compiles a slice expression `ast.Node.SliceExpression` into a `lir.Inst.Triple`
fn compileSlice(self: *Compiler, slice: *ast.Node.SliceExpression) !*lir.Inst {
const ty = try self.resolveType(slice.left);
if (ty != .list) return self.fail("Expected a list but instead found type '{s}'", slice.left.tokenPos(), .{ty});
const left = try self.resolveInst(slice.left);
const start = blk: {
if (slice.start) |start| break :blk try self.resolveInst(start);
break :blk try self.ir.emitInt(slice.token.start, 0);
};
const end = blk: {
if (slice.end) |end| break :blk try self.resolveInst(end);
break :blk try self.ir.emitPrimitive(slice.token.start, .nil);
};
return self.ir.emitSlice(slice.token.start, left, start, end);
}
/// Compiles an `ast.Node.CallExpression` node into a `lir.Inst.Call`
fn compileCall(self: *Compiler, call: *ast.Node.CallExpression) !*lir.Inst {
const initial_function_type = try self.resolveType(call.function);
const args = try self.ir.gpa.alloc(*lir.Inst, call.arguments.len);
// function is either builtin or defined on a type
// for now this can only be checked at runtime as the compiler is unaware of builtins
if (call.function == .index and initial_function_type != .module) {
for (call.arguments) |arg, i| {
args[i] = try self.resolveInst(arg);
}
const func = try self.resolveInst(call.function);
return self.ir.emitCall(
try self.resolveScalarType(call.function),
call.token.start,
func,
args,
);
}
//if it's an identifier, we first do a lookup to retrieve it's declaration node
//then return the function declaration. else we return the function itself
//in the case of an anonymous function
const function_node = if (call.function == .identifier and initial_function_type != .module) blk: {
const function = self.resolveSymbol(self.scope, call.function.identifier.value) orelse
return self.fail(
"Function '{s}' is undefined",
call.function.tokenPos(),
.{call.function.identifier.value},
);
break :blk function.node.declaration.value.func_lit;
} else if (initial_function_type != .module)
call.function.func_lit
else blk: {
if (call.function == .index and call.function.index.left == .identifier) {
// we handle module functions here
const function_name = call.function.index.index.string_lit.value;
const symbol = self.resolveSymbol(self.scope, call.function.index.left.identifier.value) orelse
return self.fail(
"Identifier '{s}' does not exist",
call.function.index.left.tokenPos(),
.{call.function.index.left.identifier.value},
);
const module_name = symbol.node.declaration.value.import.value.string_lit.value;
if (self.modules.get(module_name)) |mod| {
const decl_symbol: *Symbol = mod.symbols.get(function_name) orelse
return self.fail(
"Module does not contain function '{s}'",
call.function.tokenPos(),
.{function_name},
);
break :blk decl_symbol.node.declaration.value.func_lit;
} else {
// check if it's a luf source file or possible library
if (std.mem.endsWith(u8, module_name, ".luf"))
return self.fail("Module '{s}' does not exist", call.token.start, .{module_name});
}
}
// not a module, so expect a library
for (call.arguments) |arg, i| {
args[i] = try self.resolveInst(arg);
}
const func = try self.resolveInst(call.function);
return self.ir.emitCall(
try self.resolveScalarType(call.function),
call.token.start,
func,
args,
);
};
if (function_node.params.len != call.arguments.len)
return self.fail("Expected {d} arguments, but found {d}", call.token.start, .{
function_node.params.len,
call.arguments.len,
});
for (call.arguments) |arg, i| {
const arg_type = try self.resolveType(arg);
const func_arg_type = try self.resolveType(function_node.params[i]);
if (arg_type != func_arg_type)
return self.fail(
"Expected type '{s}' but found type '{s}'",
arg.tokenPos(),
.{ func_arg_type, arg_type },
);
args[i] = try self.resolveInst(arg);
}
const func = try self.resolveInst(call.function);
return self.ir.emitCall(
try self.resolveScalarType(call.function),
call.token.start,
func,
args,
);
}
/// Compiles an `ast.Node.ReturnStatement` into a `lir.Inst.Single`
fn compileRet(self: *Compiler, ret: *ast.Node.Return) !*lir.Inst {
const scope = self.findScope(self.scope, .function) orelse
return self.fail(
"Unexpected return statement. Return can only be done while inside a function body",
ret.token.start,
.{},
);
const func_ret_type = scope.id.function.ret_type.getType();
const ret_type = blk: {
const tmp = try self.resolveType(ret.value);
if (tmp == .function or tmp == .list) break :blk try self.resolveScalarType(ret.value);
break :blk tmp;
};
if (func_ret_type != ret_type)
return self.fail(
"Expected return type '{s}' but found type '{s}'",
ret.value.tokenPos(),
.{ func_ret_type, ret_type },
);
const value = try self.resolveInst(ret.value);
return self.ir.emitSingle(ret.token.start, .@"return", value);
}
/// Compiles an `ast.Node.WhileLoop` into an `lir.Inst.Double`
fn compileWhile(self: *Compiler, loop: *ast.Node.WhileLoop) !*lir.Inst {
try self.createScope(.loop);
const cond = try self.resolveInst(loop.condition);
const body = try self.resolveInst(loop.block);
self.exitScope();
return self.ir.emitDouble(loop.token.start, .@"while", cond, body);
}
/// Compiles an `ast.Node.ForLoop` into an `lir.Inst.Loop`
fn compileFor(self: *Compiler, loop: *ast.Node.ForLoop) !*lir.Inst {
try self.createScope(.loop);
const iterator_type = try self.resolveType(loop.iter);
if (iterator_type != .list and iterator_type != .range and iterator_type != .string) {
return self.fail(
"Expected a list, range or string, but found type '{s}'",
loop.iter.tokenPos(),
.{iterator_type},
);
}
const it = try self.resolveInst(loop.iter);
// as above, parser ensures it's an identifier
const index = if (loop.index) |i| blk: {
// loop is just a boolean, so create a new Node that represents the integer for the counter
const index_node = &ast.Node.ForLoop.index_node;
index_node.token = i.identifier.token;
const symbol = (try self.defineSymbol(
i.identifier.value,
false, // not mutable
ast.Node{ .int_lit = index_node },
false, // not forward declared
false, // not public
)) orelse return self.fail(
"Identifier '{s}' has already been declared",
loop.token.start,
.{i.identifier.value},
);
// generate an identifier to attach to the symbol
symbol.ident = try self.ir.emitIdent(.integer, i.tokenPos(), symbol.name, .local, symbol.index);
break :blk symbol.ident;
} else null;
// parser already parses it as an identifier, no need to check here again
const capture = (try self.defineSymbol(
loop.capture.identifier.value,
false, // not mutable
loop.iter,
false, // not forward declared
false, // not public
)) orelse return self.fail(
"Capture identifier '{s}' has already been declared",
loop.token.start,
.{loop.capture.identifier.value},
);
capture.ident = try self.ir.emitIdent(
try self.resolveScalarType(capture.node),
loop.capture.tokenPos(),
capture.name,
.local,
capture.index,
);
const body = try self.resolveInst(loop.block);
const loop_declaration = self.ir.emitFor(loop.token.start, it, body, capture.ident, index);
self.exitScope();
return loop_declaration;
}
/// Compiles an `ast.Node.Assignment` node into a `lir.Inst.Assign`
fn compileAssign(self: *Compiler, asg: *ast.Node.Assignment) !*lir.Inst {
if (asg.left == .identifier) {
const symbol = self.resolveSymbol(
self.scope,
asg.left.identifier.value,
) orelse return self.fail(
"Identifier '{s}' is undefined",
asg.token.start,
.{asg.left.identifier.value},
);
if (!symbol.mutable) return self.fail("Identifier '{s}' is constant", asg.token.start, .{symbol.name});
const right_type = try self.resolveType(asg.right);
const left_type = try self.resolveType(symbol.node);
if (right_type == .nil and left_type != .optional) {
return self.fail("Cannot assign `nil` to non-optional", asg.token.start, .{});
} else if (left_type == .optional) {
const child_type = try self.resolveScalarType(symbol.node);
if (child_type != right_type and right_type != .nil) {
return self.fail("Assignment expected type '{s}' but found type '{s}'", asg.token.start, .{
child_type,
right_type,
});
}
} else if (left_type != right_type)
return self.fail("Assignment expected type '{s}' but found type '{s}'", asg.token.start, .{
left_type,
right_type,
});
const rhs = try self.resolveInst(asg.right);
return self.ir.emitDouble(asg.token.start, .assign, symbol.ident, rhs);
} else if (asg.left == .index) {
const index = asg.left.index;
const lhs_type = try self.resolveScalarType(index.left);
const rhs_type = try self.resolveScalarType(asg.right);
if (lhs_type != rhs_type)
return self.fail("Expected type '{s}' but found type '{s}'", asg.right.tokenPos(), .{
lhs_type,
rhs_type,
});
const lhs = try self.resolveInst(index.left);
const mid = try self.resolveInst(index.index);
const rhs = try self.resolveInst(asg.right);
return self.ir.emitTriple(asg.token.start, .store, lhs, mid, rhs);
} else {
return self.fail("Expected an identifier on left hand side", asg.left.tokenPos(), .{});
}
}
/// Compile an `ast.Node.Import` node into a `lir.Inst.String` while also
/// compiling the modules
fn compileImport(self: *Compiler, imp: *ast.Node.Import) !*lir.Inst {
// no need for resolveType, this is faster
if (imp.value != .string_lit) return self.fail("Expected a string literal", imp.value.tokenPos(), .{});
const file_name = imp.value.string_lit.value;
if (std.mem.endsWith(u8, file_name, ".luf")) {
// forward declaration would have defined it, so we can be sure it exists
var mod: *Module = self.modules.get(file_name).?;
if (mod.compiled) {
return self.ir.emitString(.import, imp.token.start, file_name);
}
try self.createScope(.module);
const file = std.fs.cwd().openFile(file_name, .{}) catch
return self.fail("Could not open file at path '{s}'", imp.token.start, .{file_name});
defer file.close();
const size = file.getEndPos() catch return self.fail("Could not determine file size", imp.token.start, .{});
const source = file.reader().readAllAlloc(self.allocator, size) catch
return self.fail("Could not read file", imp.token.start, .{});
defer self.allocator.free(source);
const tree = try parser.parse(self.allocator, source, self.errors);
defer tree.deinit();
for (mod.symbols.items()) |entry| {
const symbol: *Symbol = entry.value;
const new_symbol = try self.scope.define(
symbol.name,
symbol.mutable,
symbol.node,
true,
symbol.is_pub,
symbol.index,
);
new_symbol.?.ident = try self.ir.emitIdent(
try self.resolveType(symbol.node),
symbol.node.tokenPos(),
symbol.name,
.global,
symbol.index,
);
}
// we can't do it in the loop above because all symbols need to be defined first so we
// can call functions from other functions
for (self.scope.symbols.items()) |*entry| {
// var symbol: *Symbol = entry.value;
// const value = try self.resolveInst(symbol.node.declaration.value);
// symbol.decl = try self.ir.emitDecl(symbol.node.tokenPos(), symbol.name, symbol.index, switch (symbol.scope) {
// .global, .module => .global,
// else => .local,
// }, false, symbol.mutable, value);
}
for (tree.nodes) |n| {
try self.instructions.append(self.allocator, try self.resolveInst(n));
}
mod.compiled = true;
self.exitScope();
}
return self.ir.emitString(.import, imp.token.start, file_name);
}
/// Compiles an `ast.Node.Range` node into a `lir.Inst.Double`
fn compileRange(self: *Compiler, range: *ast.Node.Range) !*lir.Inst {
const lhs_type = try self.resolveScalarType(range.left);
const rhs_type = try self.resolveScalarType(range.right);
if (lhs_type != .integer) return self.fail("Expected an integer but found type '{s}'", range.left.tokenPos(), .{lhs_type});
if (rhs_type != .integer) return self.fail("Expected an integer but found type '{s}'", range.right.tokenPos(), .{rhs_type});
const lhs = try self.resolveInst(range.left);
const rhs = try self.resolveInst(range.right);
return self.ir.emitDouble(range.token.start, .range, lhs, rhs);
}
/// Compiles an `ast.Node.Enum` node into a `lir.Inst.Enum`
fn compileEnum(self: *Compiler, enm: *ast.Node.EnumLiteral) !*lir.Inst {
const list = try self.ir.gpa.alloc(*lir.Inst, enm.nodes.len);
for (enm.nodes) |n, i| {
if (n != .identifier)
return self.fail(
"Expected an identifier but found type '{s}' inside the Enum declaration",
enm.token.start,
.{try self.resolveType(n)},
);
list[i] = try self.ir.emitString(.string, n.tokenPos(), n.identifier.value);
}
return self.ir.emitEnum(enm.token.start, list);
}
/// Compiles an `ast.Node.SwitchLiteral` into a `lir.Inst.Switch`
fn compileSwitch(self: *Compiler, sw: *ast.Node.SwitchLiteral) !*lir.Inst {
const prongs = try self.ir.gpa.alloc(*lir.Inst, sw.prongs.len);
const capture = try self.resolveInst(sw.capture);
const capture_type = try self.resolveType(sw.capture);
if (capture_type != .integer and capture_type != .string)
return self.fail("Switches are only allowed for integers, enums and strings. Found type '{s}'", sw.capture.tokenPos(), .{capture_type});
for (sw.prongs) |p, i| {
prongs[i] = try self.resolveInst(p);
}
return self.ir.emitSwitch(sw.token.start, capture, prongs);
}
/// Compiles an `ast.Node.SwitchProng` into a `lir.Inst.Double`
/// ensures each branch is of type integer, string or range.
fn comileProng(self: *Compiler, prong: *ast.Node.SwitchProng) !*lir.Inst {
const prong_type = try self.resolveType(prong.left);
switch (prong_type) {
.integer, .string, .range => {},
else => return self.fail("Unpermitted type '{s}' in switch case", prong.left.tokenPos(), .{prong_type}),
}
const lhs = try self.resolveInst(prong.left);
const rhs = try self.resolveInst(prong.right);
return self.ir.emitDouble(prong.token.start, .branch, lhs, rhs);
}
/// Compiles an `ast.Node.TypeDef` into a `lir.Inst.NoOp`
/// This is only used for the compiler to ensure type safety
/// and generates a no op instruction that codegen can ignore
fn compileTypeDef(self: *Compiler, node: *ast.Node.TypeDef) !*lir.Inst {
return self.ir.emitType(node.getType().?, node.token.start);
}
};
/// Tests if given input results in the expected instructions
fn testInput(input: []const u8, expected: []const lir.Inst.Tag) !void {
const alloc = testing.allocator;
var err = errors.Errors.init(alloc);
defer err.deinit();
var result = compile(alloc, input, &err) catch |_err| {
try err.write(input, std.io.getStdOut().writer());
return _err;
};
defer result.deinit();
try testing.expectEqual(expected.len, result.instructions.len);
for (result.instructions) |inst, i| {
try testing.expectEqual(expected[i], inst.tag);
}
}
test "Arithmetic" {
const test_cases = .{
.{
.input = "1 + 2",
.tags = &[_]lir.Inst.Tag{.expr},
},
.{
.input = "3 - 1",
.tags = &[_]lir.Inst.Tag{.expr},
},
.{
.input = "1 * 2",
.tags = &[_]lir.Inst.Tag{.expr},
},
.{
.input = "2 / 2",
.tags = &[_]lir.Inst.Tag{.expr},
},
.{
.input = "1 + 2 * 2",
.tags = &[_]lir.Inst.Tag{.expr},
},
.{
.input = "5 * 2 / 5 - 8",
.tags = &[_]lir.Inst.Tag{.expr},
},
.{
.input = "1 < 2",
.tags = &[_]lir.Inst.Tag{.expr},
},
.{
.input = "2 > 1",
.tags = &[_]lir.Inst.Tag{.expr},
},
.{
.input = "1 == 2",
.tags = &[_]lir.Inst.Tag{.expr},
},
.{
.input = "1 != 2",
.tags = &[_]lir.Inst.Tag{.expr},
},
.{
.input = "true == false",
.tags = &[_]lir.Inst.Tag{.expr},
},
.{
.input = "-1",
.tags = &[_]lir.Inst.Tag{.expr},
},
};
inline for (test_cases) |case| {
try testInput(case.input, case.tags);
}
}
test "Conditional" {
const test_cases = .{
.{
.input = "if (true) { 5 } 10",
.tags = &[_]lir.Inst.Tag{ .expr, .expr },
},
.{
.input = "if (true) { 5 } else { 7 } 10",
.tags = &[_]lir.Inst.Tag{ .expr, .expr },
},
};
inline for (test_cases) |case| {
try testInput(case.input, case.tags);
}
}
test "Declaration" {
const input = "const x = \"foo\"";
const alloc = testing.allocator;
var err = errors.Errors.init(alloc);
defer err.deinit();
var result = try compile(alloc, input, &err);
defer result.deinit();
var inst = result.instructions[0];
try testing.expectEqual(lir.Inst.Tag.decl, inst.tag);
const decl = inst.as(lir.Inst.Decl);
try testing.expectEqualStrings("x", decl.name);
try testing.expectEqual(lir.Inst.Tag.string, decl.value.tag);
try testing.expectEqualStrings("foo", decl.value.as(lir.Inst.String).value);
}
test "Lists" {
const test_cases = .{
.{
.input = "const x = []int{1, 2, 3}",
.tags = &[_]lir.Inst.Tag{.decl},
},
.{
.input = "const x = []int{1, 2, 3}[0]",
.tags = &[_]lir.Inst.Tag{.decl},
},
.{
.input = "const x = []int:int{1: 2, 2: 1, 5: 6}",
.tags = &[_]lir.Inst.Tag{.decl},
},
.{
.input = "const list = []int{1, 2, 3} list[1] = 10 list[1]",
.tags = &[_]lir.Inst.Tag{ .decl, .expr, .expr },
},
};
inline for (test_cases) |case| {
try testInput(case.input, case.tags);
}
}
test "Functions" {
const test_cases = .{
.{
.input = "fn() void { 1 + 2 }",
.tags = &[_]lir.Inst.Tag{.expr},
},
.{
.input = "const x = fn() void { 1 } x()",
.tags = &[_]lir.Inst.Tag{ .decl, .expr },
},
.{
.input = "const func = fn(x: int) int { return x } func(5)",
.tags = &[_]lir.Inst.Tag{ .decl, .expr },
},
};
inline for (test_cases) |case| {
try testInput(case.input, case.tags);
}
}
test "Loop" {
const input = "while true { 10 }";
const alloc = testing.allocator;
var err = errors.Errors.init(alloc);
defer err.deinit();
var result = try compile(alloc, input, &err);
defer result.deinit();
var inst = result.instructions[0];
try testing.expectEqual(lir.Inst.Tag.@"while", inst.tag);
const loop = inst.as(lir.Inst.Double);
try testing.expectEqual(lir.Inst.Tag.primitive, loop.lhs.tag);
try testing.expectEqual(lir.Inst.Primitive.PrimType.@"true", loop.lhs.as(lir.Inst.Primitive).prim_type);
try testing.expectEqual(
@as(u64, 10),
loop.rhs.as(lir.Inst.Block).instructions[0].as(lir.Inst.Single).rhs.as(lir.Inst.Int).value,
);
}
test "Assign" {
const test_cases = .{
.{
.input = "mut x = 5 x = 6",
.tags = &[_]lir.Inst.Tag{ .decl, .expr },
},
.{
.input = "mut x = 5 x += 6 x",
.tags = &[_]lir.Inst.Tag{ .decl, .expr, .expr },
},
};
inline for (test_cases) |case| {
try testInput(case.input, case.tags);
}
}
test "Optionals" {
const test_cases = .{
.{
.input = "mut x: ?int = nil",
.tags = &[_]lir.Inst.Tag{.decl},
},
.{
.input = "mut x: ?int = 5",
.tags = &[_]lir.Inst.Tag{.decl},
},
.{
.input = "mut x: ?int = nil x = 5",
.tags = &[_]lir.Inst.Tag{ .decl, .expr },
},
.{
.input = "mut x: ?int = 5 x = nil",
.tags = &[_]lir.Inst.Tag{ .decl, .expr },
},
};
inline for (test_cases) |case| try testInput(case.input, case.tags);
}
test "Slices" {
const test_case =
\\ const list = []int{1, 2, 3}
\\ const slice1 = list[1:2]
\\ const slice2 = list[:1]
\\ const slice3 = list[0:]
;
const tags = &[_]lir.Inst.Tag{
.decl,
.decl,
.decl,
.decl,
};
try testInput(test_case, tags);
} | src/compiler.zig |
const std = @import("std");
const gemtext = @import("../gemtext.zig");
const Fragment = gemtext.Fragment;
fn fmtHtmlText(
data: []const u8,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = fmt;
_ = options;
const illegal = "<>&\"\'";
const replacement = [_][]const u8{
"<",
">",
"&",
""",
"'",
};
var last_offset: usize = 0;
for (data) |c, index| {
if (std.mem.indexOf(u8, illegal, &[1]u8{c})) |i| {
if (index > last_offset) {
try writer.writeAll(data[last_offset..index]);
}
last_offset = index + 1;
try writer.writeAll(replacement[i]);
}
}
if (data.len > last_offset) {
try writer.writeAll(data[last_offset..]);
}
}
pub fn fmtHtml(slice: []const u8) std.fmt.Formatter(fmtHtmlText) {
return .{ .data = slice };
}
/// Renders a sequence of fragments into a html document.
/// `fragments` is a slice of fragments which describe the document,
/// `writer` is a `std.io.Writer` structure that will be the target of the document rendering.
/// The document will be rendered with CR LF line endings.
pub fn render(fragments: []const Fragment, writer: anytype) !void {
const line_ending = "\r\n";
for (fragments) |fragment| {
switch (fragment) {
.empty => try writer.writeAll("<p> </p>\r\n"),
.paragraph => |paragraph| try writer.print("<p>{s}</p>" ++ line_ending, .{fmtHtml(paragraph)}),
.preformatted => |preformatted| {
if (preformatted.alt_text) |alt| {
try writer.print("<pre alt=\"{}\">", .{fmtHtml(alt)});
} else {
try writer.writeAll("<pre>");
}
for (preformatted.text.lines) |line, i| {
if (i > 0)
try writer.writeAll(line_ending);
try writer.print("{}", .{fmtHtml(line)});
}
try writer.writeAll("</pre>" ++ line_ending);
},
.quote => |quote| {
try writer.writeAll("<blockquote>");
for (quote.lines) |line, i| {
if (i > 0)
try writer.writeAll("<br>" ++ line_ending);
try writer.print("{}", .{fmtHtml(line)});
}
try writer.writeAll("</blockquote>" ++ line_ending);
},
.link => |link| {
if (link.title) |title| {
try writer.print("<p><a href=\"{s}\">{}</a></p>" ++ line_ending, .{ link.href, fmtHtml(title) });
} else {
try writer.print("<p><a href=\"{s}\">{}</a></p>" ++ line_ending, .{ link.href, fmtHtml(link.href) });
}
},
.list => |list| {
try writer.writeAll("<ul>" ++ line_ending);
for (list.lines) |line| {
try writer.print("<li>{}</li>" ++ line_ending, .{fmtHtml(line)});
}
try writer.writeAll("</ul>" ++ line_ending);
},
.heading => |heading| {
switch (heading.level) {
.h1 => try writer.print("<h1>{}</h1>" ++ line_ending, .{fmtHtml(heading.text)}),
.h2 => try writer.print("<h2>{}</h1>" ++ line_ending, .{fmtHtml(heading.text)}),
.h3 => try writer.print("<h3>{}</h1>" ++ line_ending, .{fmtHtml(heading.text)}),
}
},
}
}
} | src/renderers/html.zig |
const std = @import("std");
const math = @import("../pkg/zlm.zig");
const assert = std.debug.assert;
// Fair bit of code duplication here for specialized shape algorithms.
// Much credit goes to this incredible resource:
// http://www.jeffreythompson.org/collision-detection/index.php
pub fn isPointInCircle(point: math.Vec2, circlePos: math.Vec2, circleRad: f32) bool {
return point.distanceTo(circlePos) <= circleRad;
}
pub fn isPointInRect(point: math.Vec2, rect: math.Rect) bool {
return rect.containsPoint(point);
}
pub fn isPointInLine(point: math.Vec2, lineStart: math.Vec2, lineEnd: math.Vec2) bool {
const dist1 = point.distanceTo(lineStart);
const dist2 = point.distanceTo(lineEnd);
const len = lineStart.distanceTo(lineEnd);
const buffer: f32 = 0.1;
return dist1 + dist2 >= len - buffer and dist1 + dist2 <= len + buffer;
}
pub fn isPointInPoint(point1: math.Vec2, point2: math.Vec2) bool {
return point1.distanceTo(point2) < 0.1;
}
pub fn isPointInPolygon(point: math.Vec2, polyPoint: math.Vec2, vertices: []math.Vec2) bool {
var i: usize = 0;
var j: usize = vertices.len - 1;
var inside = false;
while (i < vertices.len) {
const polyI = polyPoint.add(vertices[i]);
const polyJ = polyPoint.add(vertices[j]);
if ((polyI.y > point.y) != (polyJ.y > point.y) and point.x < (polyJ.x - polyI.x) * (point.y - polyI.y) / (polyJ.y - polyI.y) + polyI.x) {
inside = !inside;
}
// Continuation logic
j = i;
i += 1;
}
return inside;
}
pub fn isCircleInPolygon(circlePos: math.Vec2, radius: f32, polygonPos: math.Vec2, vertices: []math.Vec2) bool {
for (vertices) |vert, i| {
var next = if (i + 1 == vertices.len) polygonPos.add(vertices[0]) else polygonPos.add(vertices[i + 1]);
if (isLineInCircle(vert.add(polygonPos), next, circlePos, radius)) return true;
}
return isPointInPolygon(circlePos, polygonPos, vertices);
}
pub fn isLineInPolygon(lineStart: math.Vec2, lineEnd: math.Vec2, polygonPos: math.Vec2, vertices: []math.Vec2) bool {
for (vertices) |vert, i| {
var next = if (i + 1 == vertices.len) polygonPos.add(vertices[0]) else polygonPos.add(vertices[i + 1]);
if (isLineInLine(lineStart, lineEnd, vert.add(polygonPos), next)) return true;
}
return false;
}
pub fn isPolygonInPolygon(polygonPos: math.Vec2, vertices: []math.Vec2, polygon2Pos: math.Vec2, vertices2: []math.Vec2) bool {
for (vertices) |vert, i| {
var next = if (i + 1 == vertices.len) polygonPos.add(vertices[0]) else polygonPos.add(vertices[i + 1]);
if (isLineInPolygon(vert.add(polygonPos), next, polygon2Pos, vertices2)) return true;
}
return isPointInPolygon(polygonPos, polygon2Pos, vertices2);
}
pub fn isRectInPolygon(rectangle: math.Rect, polygonPos: math.Vec2, vertices: []math.Vec2) bool {
for (vertices) |vert, i| {
var next = if (i + 1 == vertices.len) polygonPos.add(vertices[0]) else polygonPos.add(vertices[i + 1]);
if (isLineInRect(vert.add(polygonPos), next, rectangle.position, rectangle.size)) return true;
}
return isPointInPolygon(rectangle.position, polygonPos, vertices);
}
pub fn isLineInLine(l1Start: math.Vec2, l1End: math.Vec2, l2Start: math.Vec2, l2End: math.Vec2) bool {
var uA: f32 = ((l2End.x - l2Start.x) * (l1Start.y - l2Start.y) - (l2End.y - l2Start.y) * (l1Start.x - l2Start.x)) / ((l2End.y - l2Start.y) * (l1End.x - l1Start.x) - (l2End.x - l2Start.x) * (l1End.y - l1Start.y));
var uB: f32 = ((l1End.x - l1Start.x) * (l1Start.y - l2Start.y) - (l1End.y - l1Start.y) * (l1Start.x - l2Start.x)) / ((l2End.y - l2Start.y) * (l1End.x - l1Start.x) - (l2End.x - l2Start.x) * (l1End.y - l1Start.y));
return (uA >= 0 and uA <= 1 and uB >= 0 and uB <= 1);
}
pub fn isLineInRect(line1: math.Vec2, line2: math.Vec2, aabbPos: math.Vec2, aabbSize: math.Vec2) bool {
const tl = aabbPos;
const tr = aabbPos.add(.{ .x = aabbSize.x });
const br = aabbPos.add(aabbSize);
const bl = aabbPos.add(.{ .y = aabbSize.y });
return isLineInLine(line1, line2, tl, tr) or
isLineInLine(line1, line2, tl, bl) or
isLineInLine(line1, line2, bl, br) or
isLineInLine(line1, line2, tr, br);
}
pub fn isRectInRect(rect1Pos: math.Vec2, rect1Size: math.Vec2, rect2Pos: math.Vec2, rect2Size: math.Vec2) bool {
return math.Rect.intersectsRect(.{ .position = rect1Pos, .size = rect1Size }, .{ .position = rect2Pos, .size = rect2Size });
}
pub fn isCircleInRect(circPos: math.Vec2, radius: f32, rectPos: math.Vec2, rectSize: math.Vec2) bool {
var testX = circPos.x;
var testY = circPos.y;
if (circPos.x < rectPos.x) {
testX = rectPos.x;
} else if (circPos.x > rectPos.x + rectSize.x) {
testX = rectPos.x + rectSize.x;
}
if (circPos.y < rectPos.y) {
testY = rectPos.y;
} else if (circPos.y > rectPos.y + rectSize.y) {
testY = rectPos.y + rectSize.y;
}
var distX = circPos.x - testX;
var distY = circPos.y - testY;
var dist = std.math.sqrt((distX * distX) + (distY * distY));
return dist <= radius;
}
pub fn isLineInCircle(lineStart: math.Vec2, lineEnd: math.Vec2, circlePos: math.Vec2, radius: f32) bool {
// Early out
if (isPointInCircle(lineStart, circlePos, radius)) {
return true;
}
if (isPointInCircle(lineEnd, circlePos, radius)) {
return true;
}
const len: f32 = lineStart.distanceTo(lineEnd);
const dot = (((circlePos.x - lineStart.x) * (lineEnd.x - lineStart.x)) + ((circlePos.y - lineStart.y) * (lineEnd.y - lineStart.y))) / std.math.pow(f32, len, 2.0);
const closestX = lineStart.x + (dot * (lineEnd.x - lineStart.x));
const closestY = lineStart.y + (dot * (lineEnd.y - lineStart.y));
var onSegment = isPointInLine(.{ .x = closestX, .y = closestY }, lineStart, lineEnd);
if (!onSegment) return false;
var closest = math.vec2(closestX - circlePos.x, closestY - circlePos.y);
return closest.length() <= radius;
}
inline fn pointInCircle(point: Shape, pointPos: math.Vec2, circle: Shape, circlePos: math.Vec2) bool {
assert(circle == .Circle);
assert(point == .Point);
return isPointInCircle(point.Point.add(pointPos), circlePos, circle.Circle.radius);
}
inline fn pointInPoint(
point: Shape,
pointPos: math.Vec2,
point2: Shape,
point2Pos: math.Vec2,
) bool {
assert(point2 == .Point);
assert(point == .Point);
return isPointInPoint(pointPos.add(point.Point), point2Pos.add(point2.Point));
}
inline fn pointInLine(point: Shape, pointPos: math.Vec2, line: Shape, linePos: math.Vec2) bool {
assert(line == .Line);
assert(point == .Point);
const start = linePos.add(line.Line.start);
const end = linePos.add(line.Line.end);
return isPointInLine(pointPos.add(point.Point), start, end);
}
inline fn lineInLine(line: Shape, linePos: math.Vec2, line2: Shape, line2Pos: math.Vec2) bool {
assert(line == .Line);
assert(line2 == .Line);
const start = linePos.add(line.Line.start);
const end = linePos.add(line.Line.end);
const start2 = line2Pos.add(line2.Line.start);
const end2 = line2Pos.add(line2.Line.end);
return isLineInLine(start, end, start2, end2);
}
inline fn lineInPolygon(line: Shape, linePos: math.Vec2, poly: Shape, polyPos: math.Vec2) bool {
assert(line == .Line);
assert(poly == .Polygon);
const start = linePos.add(line.Line.start);
const end = linePos.add(line.Line.end);
return isLineInPolygon(start, end, polyPos, poly.Polygon.vertices);
}
inline fn pointInRect(point: Shape, pointPos: math.Vec2, rectangle: Shape, rectanglePos: math.Vec2) bool {
assert(rectangle == .Rectangle);
assert(point == .Point);
const ppos: math.Vec2 = point.Point.add(pointPos);
const rect: math.Rect = .{
.position = rectangle.Rectangle.position.add(rectanglePos),
.size = rectangle.Rectangle.size,
};
return isPointInRect(ppos, rect);
}
inline fn lineInRect(line: Shape, linePos: math.Vec2, rectangle: Shape, rectanglePos: math.Vec2) bool {
assert(rectangle == .Rectangle);
assert(line == .Line);
const lineStart: math.Vec2 = linePos.add(line.Line.start);
const lineEnd: math.Vec2 = linePos.add(line.Line.end);
const rect: math.Rect = .{
.position = rectangle.Rectangle.position.add(rectanglePos),
.size = rectangle.Rectangle.size,
};
return isLineInRect(lineStart, lineEnd, rect.position, rect.size);
}
inline fn pointInPolygon(point: Shape, pointPos: math.Vec2, poly: Shape, polyPos: math.Vec2) bool {
assert(poly == .Polygon);
assert(point == .Point);
return isPointInPolygon(pointPos.add(point.Point), polyPos, poly.Polygon.vertices);
}
inline fn circleInCircle(circle1: Shape, circle1Pos: math.Vec2, circle2: Shape, circle2Pos: math.Vec2) bool {
assert(circle1 == .Circle);
assert(circle2 == .Circle);
return circle1Pos.distanceTo(circle2Pos) - circle1.Circle.radius <= circle2.Circle.radius;
}
inline fn circleInRect(circle: Shape, circlePos: math.Vec2, rectangle: Shape, rectanglePos: math.Vec2) bool {
assert(circle == .Circle);
assert(rectangle == .Rectangle);
var rect = rectangle.Rectangle;
rect.position = rect.position.add(rectanglePos);
return isCircleInRect(circlePos, circle.Circle.radius, rect.position, rect.size);
}
inline fn circleInLine(circle: Shape, circlePos: math.Vec2, line: Shape, linePos: math.Vec2) bool {
assert(circle == .Circle); // here
assert(line == .Line);
const lineStart: math.Vec2 = linePos.add(line.Line.start);
const lineEnd: math.Vec2 = linePos.add(line.Line.end);
return isLineInCircle(lineStart, lineEnd, circlePos, circle.Circle.radius);
}
inline fn circleInPoly(circle: Shape, circlePos: math.Vec2, poly: Shape, polyPos: math.Vec2) bool {
assert(circle == .Circle);
assert(poly == .Polygon);
return isCircleInPolygon(circlePos, circle.Circle.radius, polyPos, poly.Polygon.vertices);
}
inline fn rectInRect(rect1: Shape, rect1Pos: math.Vec2, rect2: Shape, rect2Pos: math.Vec2) bool {
assert(rect1 == .Rectangle);
assert(rect2 == .Rectangle);
return isRectInRect(rect1.Rectangle.position.add(rect1Pos), rect1.Rectangle.size, rect2.Rectangle.position.add(rect2Pos), rect2.Rectangle.size);
}
inline fn rectInPoly(rectangle: Shape, rectanglePos: math.Vec2, poly: Shape, polyPos: math.Vec2) bool {
assert(rectangle == .Rectangle);
assert(poly == .Polygon);
var rect = rectangle.Rectangle;
rect.position = rect.position.add(rectanglePos);
return isRectInPolygon(rect, polyPos, poly.Polygon.vertices);
}
inline fn polyInPoly(poly: Shape, polyPos: math.Vec2, poly2: Shape, poly2Pos: math.Vec2) bool {
assert(poly2 == .Polygon);
assert(poly == .Polygon);
return isPolygonInPolygon(polyPos, poly.Polygon.vertices, poly2Pos, poly2.Polygon.vertices);
}
/// Simple container of many shape types. By using a shape in your code you can test overlaps against any other shape.
/// For simplicity sake, Rectangle is AABB, meaning it cannot be represented as rotated. For that you'll want to make your
/// own polygon, which works with any other shape.
/// Note that none of the shapes retain a position field, as position is supplied during the check functions to make this
/// interface a little more versatile. As such, a Point's position and a Rectangle's position both refer to an offset from
/// the position yet supplied. Polygon's vertices are as offsets from the position supplied.
pub const Shape = union(enum) {
Circle: Circle,
Rectangle: Rectangle,
Point: Point,
Polygon: Polygon,
Line: Line,
pub const Circle = struct { radius: f32 };
pub const Rectangle = math.Rect;
pub const Point = math.Vec2;
pub const Polygon = struct { vertices: []math.Vec2 };
pub const Line = struct {
start: math.Vec2,
end: math.Vec2,
};
pub fn circle(radius: f32) Shape {
return .{ .Circle = .{ .radius = radius } };
}
pub fn line(from: math.Vec2, to: math.Vec2) Shape {
return .{ .Line = .{ .start = from, .end = to } };
}
pub fn point(pos: math.Vec2) Shape {
return .{ .Point = pos };
}
pub fn rectangle(pos: math.Vec2, size: math.Vec2) Shape {
return .{ .Rectangle = math.rect(pos.x, pos.y, size.x, size.y) };
}
pub fn overlaps(self: Shape, selfPos: math.Vec2, other: Shape, otherPos: math.Vec2) bool {
switch (self) {
.Point => {
switch (other) {
.Circle => {
return pointInCircle(self, selfPos, other, otherPos);
},
.Rectangle => {
return pointInRect(self, selfPos, other, otherPos);
},
.Polygon => {
return pointInPolygon(self, selfPos, other, otherPos);
},
.Line => {
return pointInLine(self, selfPos, other, otherPos);
},
.Point => {
return pointInPoint(self, selfPos, other, otherPos);
},
}
},
.Circle => {
switch (other) {
.Circle => {
return circleInCircle(self, selfPos, other, otherPos);
},
.Point => {
return pointInCircle(other, otherPos, self, selfPos);
},
.Rectangle => {
return circleInRect(self, selfPos, other, otherPos);
},
.Line => {
return circleInLine(self, selfPos, other, otherPos);
},
.Polygon => {
return circleInPoly(self, selfPos, other, otherPos);
},
}
},
.Rectangle => {
switch (other) {
.Circle => {
return circleInRect(other, otherPos, self, selfPos);
},
.Point => {
return pointInRect(other, otherPos, self, selfPos);
},
.Rectangle => {
return rectInRect(self, selfPos, other, otherPos);
},
.Line => {
return lineInRect(other, otherPos, self, selfPos);
},
.Polygon => {
return rectInPoly(self, selfPos, other, otherPos);
},
}
},
.Line => {
switch (other) {
.Circle => {
return circleInLine(other, otherPos, self, selfPos);
},
.Point => {
return pointInLine(other, otherPos, self, selfPos);
},
.Rectangle => {
return lineInRect(self, selfPos, other, otherPos);
},
.Line => {
return lineInLine(self, selfPos, other, otherPos);
},
.Polygon => {
return lineInPolygon(self, selfPos, other, otherPos);
},
}
},
.Polygon => {
switch (other) {
.Circle => {
return circleInPoly(other, otherPos, self, selfPos);
},
.Point => {
return pointInPolygon(other, otherPos, self, selfPos);
},
.Rectangle => {
return rectInPoly(other, otherPos, self, selfPos);
},
.Line => {
return lineInPolygon(other, otherPos, self, selfPos);
},
.Polygon => {
return polyInPoly(other, otherPos, self, selfPos);
},
}
},
}
}
};
test "Overlap methods" {
var offsetPoint = Shape.point(.{ .x = -20 });
var testPoint = Shape.point(.{});
var testCircle = Shape.circle(10);
var testRectangle = Shape.rectangle(.{}, .{ .x = 10, .y = 10 });
var offsetRectangle = Shape.rectangle(.{ .x = 20 }, .{ .x = 10, .y = 10 });
// Point -> Circle
assert(isPointInCircle(.{}, .{}, 3));
assert(Shape.overlaps(testPoint, .{}, testCircle, .{}));
assert(Shape.overlaps(testCircle, .{}, testPoint, .{}));
assert(!Shape.overlaps(offsetPoint, .{}, testCircle, .{}));
assert(!Shape.overlaps(testPoint, .{ .x = 15 }, testCircle, .{}));
assert(!Shape.overlaps(testCircle, .{}, testPoint, .{ .x = 15 }));
// Point -> Rectangle
assert(isPointInRect(.{}, .{ .size = .{ .x = 10, .y = 10 } }));
assert(Shape.overlaps(testPoint, .{}, testRectangle, .{}));
assert(Shape.overlaps(testPoint, .{ .x = 25 }, offsetRectangle, .{}));
assert(!Shape.overlaps(offsetPoint, .{}, testRectangle, .{}));
assert(!Shape.overlaps(testPoint, .{}, offsetRectangle, .{}));
// Point -> Poly
var polygons: []math.Vec2 = &.{
math.vec2(-10, 0),
math.vec2(0, -10),
math.vec2(10, 0),
math.vec2(0, 10),
};
var testPoly = Shape{ .Polygon = .{ .vertices = polygons } };
assert(isPointInPolygon(.{}, .{}, polygons));
assert(!isPointInPolygon(math.vec2(-8, -8), .{}, polygons));
assert(Shape.overlaps(testPoint, .{}, testPoly, .{}));
assert(!Shape.overlaps(testPoint, .{ .x = -8, .y = -8 }, testPoly, .{}));
// Circle -> Circle
assert(Shape.overlaps(testCircle, .{}, testCircle, .{}));
assert(!Shape.overlaps(testCircle, .{ .x = 21 }, testCircle, .{}));
// Circle -> Rectangle
assert(Shape.overlaps(testRectangle, .{}, testCircle, .{}));
assert(!Shape.overlaps(testRectangle, .{}, testCircle, .{ .x = -11 }));
} | src/zt/physics.zig |
const std = @import("std");
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
const builtin = @import("builtin");
test "atomic store" {
var x: u32 = 0;
@atomicStore(u32, &x, 1, .SeqCst);
try expect(@atomicLoad(u32, &x, .SeqCst) == 1);
@atomicStore(u32, &x, 12345678, .SeqCst);
try expect(@atomicLoad(u32, &x, .SeqCst) == 12345678);
}
test "atomic store comptime" {
comptime try testAtomicStore();
try testAtomicStore();
}
fn testAtomicStore() !void {
var x: u32 = 0;
@atomicStore(u32, &x, 1, .SeqCst);
try expect(@atomicLoad(u32, &x, .SeqCst) == 1);
@atomicStore(u32, &x, 12345678, .SeqCst);
try expect(@atomicLoad(u32, &x, .SeqCst) == 12345678);
}
test "atomicrmw with floats" {
try testAtomicRmwFloat();
comptime try testAtomicRmwFloat();
}
fn testAtomicRmwFloat() !void {
var x: f32 = 0;
try expect(x == 0);
_ = @atomicRmw(f32, &x, .Xchg, 1, .SeqCst);
try expect(x == 1);
_ = @atomicRmw(f32, &x, .Add, 5, .SeqCst);
try expect(x == 6);
_ = @atomicRmw(f32, &x, .Sub, 2, .SeqCst);
try expect(x == 4);
}
test "atomicrmw with ints" {
try testAtomicRmwInt();
comptime try testAtomicRmwInt();
}
fn testAtomicRmwInt() !void {
var x: u8 = 1;
var res = @atomicRmw(u8, &x, .Xchg, 3, .SeqCst);
try expect(x == 3 and res == 1);
_ = @atomicRmw(u8, &x, .Add, 3, .SeqCst);
try expect(x == 6);
_ = @atomicRmw(u8, &x, .Sub, 1, .SeqCst);
try expect(x == 5);
_ = @atomicRmw(u8, &x, .And, 4, .SeqCst);
try expect(x == 4);
_ = @atomicRmw(u8, &x, .Nand, 4, .SeqCst);
try expect(x == 0xfb);
_ = @atomicRmw(u8, &x, .Or, 6, .SeqCst);
try expect(x == 0xff);
_ = @atomicRmw(u8, &x, .Xor, 2, .SeqCst);
try expect(x == 0xfd);
_ = @atomicRmw(u8, &x, .Max, 1, .SeqCst);
try expect(x == 0xfd);
_ = @atomicRmw(u8, &x, .Min, 1, .SeqCst);
try expect(x == 1);
}
test "atomics with different types" {
try testAtomicsWithType(bool, true, false);
inline for (.{ u1, i4, u5, i15, u24 }) |T| {
try testAtomicsWithType(T, 0, 1);
}
try testAtomicsWithType(u0, 0, 0);
try testAtomicsWithType(i0, 0, 0);
}
fn testAtomicsWithType(comptime T: type, a: T, b: T) !void {
var x: T = b;
@atomicStore(T, &x, a, .SeqCst);
try expect(x == a);
try expect(@atomicLoad(T, &x, .SeqCst) == a);
try expect(@atomicRmw(T, &x, .Xchg, b, .SeqCst) == a);
try expect(@cmpxchgStrong(T, &x, b, a, .SeqCst, .SeqCst) == null);
if (@sizeOf(T) != 0)
try expect(@cmpxchgStrong(T, &x, b, a, .SeqCst, .SeqCst).? == a);
} | test/behavior/atomics_stage1.zig |
const std = @import("std");
const windows = @import("windows.zig");
const WINAPI = windows.WINAPI;
const HRESULT = windows.HRESULT;
const LPCSTR = windows.LPCSTR;
const UINT = windows.UINT;
const SIZE_T = windows.SIZE_T;
const d3dcommon = @import("d3dcommon.zig");
pub const COMPILE_FLAG = UINT;
pub const COMPILE_DEBUG: COMPILE_FLAG = (1 << 0);
pub const COMPILE_SKIP_VALIDATION: COMPILE_FLAG = (1 << 1);
pub const COMPILE_SKIP_OPTIMIZATION: COMPILE_FLAG = (1 << 2);
pub const COMPILE_PACK_MATRIX_ROW_MAJOR: COMPILE_FLAG = (1 << 3);
pub const COMPILE_PACK_MATRIX_COLUMN_MAJOR: COMPILE_FLAG = (1 << 4);
pub const COMPILE_PARTIAL_PRECISION: COMPILE_FLAG = (1 << 5);
pub const COMPILE_FORCE_VS_SOFTWARE_NO_OPT: COMPILE_FLAG = (1 << 6);
pub const COMPILE_FORCE_PS_SOFTWARE_NO_OPT: COMPILE_FLAG = (1 << 7);
pub const COMPILE_NO_PRESHADER: COMPILE_FLAG = (1 << 8);
pub const COMPILE_AVOID_FLOW_CONTROL: COMPILE_FLAG = (1 << 9);
pub const COMPILE_PREFER_FLOW_CONTROL: COMPILE_FLAG = (1 << 10);
pub const COMPILE_ENABLE_STRICTNESS: COMPILE_FLAG = (1 << 11);
pub const COMPILE_ENABLE_BACKWARDS_COMPATIBILITY: COMPILE_FLAG = (1 << 12);
pub const COMPILE_IEEE_STRICTNESS: COMPILE_FLAG = (1 << 13);
pub const COMPILE_OPTIMIZATION_LEVEL0: COMPILE_FLAG = (1 << 14);
pub const COMPILE_OPTIMIZATION_LEVEL1: COMPILE_FLAG = 0;
pub const COMPILE_OPTIMIZATION_LEVEL2: COMPILE_FLAG = ((1 << 14) | (1 << 15));
pub const COMPILE_OPTIMIZATION_LEVEL3: COMPILE_FLAG = (1 << 15);
pub const COMPILE_RESERVED16: COMPILE_FLAG = (1 << 16);
pub const COMPILE_RESERVED17: COMPILE_FLAG = (1 << 17);
pub const COMPILE_WARNINGS_ARE_ERRORS: COMPILE_FLAG = (1 << 18);
pub const COMPILE_RESOURCES_MAY_ALIAS: COMPILE_FLAG = (1 << 19);
pub const COMPILE_ENABLE_UNBOUNDED_DESCRIPTOR_TABLES: COMPILE_FLAG = (1 << 20);
pub const COMPILE_ALL_RESOURCES_BOUND: COMPILE_FLAG = (1 << 21);
pub const COMPILE_DEBUG_NAME_FOR_SOURCE: COMPILE_FLAG = (1 << 22);
pub const COMPILE_DEBUG_NAME_FOR_BINARY: COMPILE_FLAG = (1 << 23);
pub extern "D3DCompiler_47" fn D3DCompile(
pSrcData: *const anyopaque,
SrcDataSize: SIZE_T,
pSourceName: ?LPCSTR,
pDefines: ?*const d3dcommon.SHADER_MACRO,
pInclude: ?*const d3dcommon.IInclude,
pEntrypoint: LPCSTR,
pTarget: LPCSTR,
Flags1: UINT,
Flags2: UINT,
ppCode: **d3dcommon.IBlob,
ppErrorMsgs: ?**d3dcommon.IBlob,
) callconv(WINAPI) HRESULT; | modules/platform/vendored/zwin32/src/d3dcompiler.zig |
const std = @import("std");
const stdx = @import("stdx");
const builtin = @import("builtin");
const runtime = @import("runtime.zig");
/// Wraps environment ops so they can be overridden for testing.
pub const Environment = struct {
const Self = @This();
// Overrides the main script source instead of doing a file read. Used for testing and embedded main scripts.
main_script_override: ?[]const u8 = null,
main_script_origin: ?[]const u8 = null,
// Attach user context after creating the js global context. Assigned value should be duped.
user_ctx_json: ?[]const u8 = null,
// Writes with custom interface instead of stderr. Used for testing.
err_writer: ?WriterIfaceWrapper = null,
// Writes with custom interface instead of stdout. Only available with builtin.is_test.
out_writer: ?WriterIfaceWrapper = null,
on_main_script_done: ?fn (ctx: ?*anyopaque, rt: *runtime.RuntimeContext) anyerror!void = null,
on_main_script_done_ctx: ?*anyopaque = null,
exit_fn: ?fn (code: u8) void = null,
// When executing the runtime normally, it's nice to be able to shutdown as quickly as possible.
// If the user script contains explicit exit statements, there is no graceful shutdown.
// If the user script completes with no more outstanding events, there is a graceful shutdown and
// this flag determines if the runtime should do some event pumping for a brief period after resources have started deiniting.
// This is turned off by default since under normal conditions, no resources should still be active when reaching graceful shutdown
// so it's preferable to exit quickly and not risk being delayed for some rare edge case.
// During testing however, it's important to clean up a runtime fully between tests
// so that it can discover memory leaks and incorrect deinit behavior.
// Tests may also requestShutdown on the runtime when resources are still active which would end
// up queuing more events that need to be processed.
pump_rt_on_graceful_shutdown: bool = false,
include_test_api: bool = false,
pub fn deinit(self: Self, alloc: std.mem.Allocator) void {
if (self.user_ctx_json) |json| {
alloc.free(json);
}
}
pub fn exit(self: Self, code: u8) void {
if (builtin.is_test) {
if (self.exit_fn) |func| {
func(code);
return;
}
}
std.process.exit(code);
}
/// Prints to stderr and exits.
pub fn abortFmt(self: Self, comptime format: []const u8, args: anytype) void {
self.errorFmt(format, args);
self.errorFmt("\n", .{});
self.exit(1);
}
/// Prints to stdout.
pub fn printFmt(self: Self, comptime format: []const u8, args: anytype) void {
if (builtin.is_test) {
if (self.out_writer) |writer| {
std.fmt.format(writer, format, args) catch unreachable;
}
}
const stdout = std.io.getStdOut().writer();
stdout.print(format, args) catch unreachable;
}
/// Prints to stderr.
pub fn errorFmt(self: Self, comptime format: []const u8, args: anytype) void {
if (builtin.is_test) {
if (self.err_writer) |writer| {
std.fmt.format(writer, format, args) catch unreachable;
}
}
const stderr = std.io.getStdErr().writer();
stderr.print(format, args) catch unreachable;
}
};
const WriterIfaceWrapper = std.io.Writer(WriterIface, anyerror, WriterIface.write);
pub const WriterIface = struct {
const Self = @This();
ptr: *anyopaque,
write_inner: fn(*anyopaque, []const u8) anyerror!usize,
pub fn init(writer_ptr: anytype) WriterIfaceWrapper {
const Ptr = @TypeOf(writer_ptr);
const Gen = struct {
fn write_(ptr_: *anyopaque, data: []const u8) anyerror!usize {
const self = stdx.mem.ptrCastAlign(Ptr, ptr_);
return self.write(data);
}
};
return .{
.context = .{
.ptr = writer_ptr,
.write_inner = Gen.write_,
},
};
}
fn write(self: Self, data: []const u8) anyerror!usize {
return try self.write_inner(self.ptr, data);
}
}; | runtime/env.zig |
const std = @import("std");
const gl = @import("zgl");
const glfw = @import("glfz");
const ui = @import("znt-ui").ui(Scene);
const znt = @import("znt");
const Scene = znt.Scene(struct {
box: ui.Box,
rect: ui.Rect,
}, .{});
const Systems = struct {
layout: ui.LayoutSystem,
render: ui.RenderSystem,
pub fn init(allocator: *std.mem.Allocator, scene: *Scene, viewport_size: [2]u31) Systems {
return .{
.layout = ui.LayoutSystem.init(allocator, scene, viewport_size),
.render = ui.RenderSystem.init(scene, .top_left),
};
}
pub fn deinit(self: Systems) void {
self.layout.deinit();
self.render.deinit();
}
pub fn update(self: *Systems) !void {
try self.layout.layout();
self.render.render();
}
};
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
try glfw.init();
const win = try glfw.Window.init(800, 600, "Hello, world!", .{
.context_version_major = 4,
.context_version_minor = 5,
.opengl_profile = .core,
.opengl_forward_compat = true,
});
defer win.deinit();
win.makeContextCurrent();
glfw.swapInterval(0); // Disable vsync
var scene = Scene.init(&gpa.allocator);
defer scene.deinit();
var systems = Systems.init(
std.heap.page_allocator,
&scene,
win.windowSize(),
);
defer systems.deinit();
win.setUserPointer(&systems);
try initUi(&scene);
_ = win.setWindowSizeCallback(sizeCallback);
_ = win.setFramebufferSizeCallback(fbSizeCallback);
while (!win.shouldClose()) {
gl.clearColor(0, 0, 0, 0);
gl.clear(.{ .color = true });
gl.enable(.blend);
gl.blendFunc(.src_alpha, .one_minus_src_alpha);
try systems.update();
win.swapBuffers();
glfw.waitEvents();
}
}
fn sizeCallback(win: *glfw.Window, w: c_int, h: c_int) callconv(.C) void {
const systems = win.getUserPointer(*Systems);
systems.layout.setViewport(.{ @intCast(u31, w), @intCast(u31, h) });
}
fn fbSizeCallback(_: *glfw.Window, w: c_int, h: c_int) callconv(.C) void {
gl.viewport(0, 0, @intCast(usize, w), @intCast(usize, h));
}
fn initUi(scene: *Scene) !void {
const margins = ui.Box.Margins{ .l = 10, .b = 10, .r = 10, .t = 10 };
const root = try scene.add(.{
.box = ui.Box.init(null, null, .{}),
.rect = ui.Rect.init(.{ 1, 1, 0, 0.4 }, ui.boxRect),
});
const level1 = try scene.add(.{
.box = ui.Box.init(root, null, .{
.margins = margins,
.direction = .col,
}),
.rect = ui.Rect.init(.{ 1, 0, 1, 0.4 }, ui.boxRect),
});
_ = try scene.add(.{
.box = ui.Box.init(root, level1, .{
.margins = margins,
.grow = 0,
.fill_cross = false,
.min_size = .{ 400, 400 },
}),
.rect = ui.Rect.init(.{ 0, 1, 0, 0.4 }, ui.boxRect),
});
var box = try scene.add(.{
.box = ui.Box.init(level1, null, .{
.margins = margins,
.grow = 0,
.min_size = .{ 50, 50 },
}),
.rect = ui.Rect.init(.{ 0, 1, 1, 0.4 }, ui.boxRect),
});
box = try scene.add(.{
.box = ui.Box.init(level1, box, .{
.margins = margins,
.fill_cross = false,
.min_size = .{ 300, 50 },
}),
.rect = ui.Rect.init(.{ 0.5, 0.5, 1, 0.4 }, ui.boxRect),
});
box = try scene.add(.{
.box = ui.Box.init(level1, box, .{
.margins = margins,
.grow = 0,
.fill_cross = false,
.min_size = .{ 100, 200 },
}),
.rect = ui.Rect.init(.{ 0.5, 0.5, 1, 0.4 }, ui.boxRect),
});
} | example/main.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const empty_arr = [0]*Triev{};
const empty_str = [0]u8{};
// a wrapper for Triev that keeps track of metadata so i can more efficiently walk the triev.
// no wraper for Triev.get because it doesn't generate metadata. use TrievManager.t.get instead.
pub const TrievManager = struct {
t: Triev,
depth: u64,
num_vals: u64,
pub fn init(self: *TrievManager) void {
self.t.bit_string = 0;
self.t.kids = empty_arr[0..];
self.t.val = empty_str[0..];
self.depth = 0;
self.num_vals = 0;
}
pub fn insert(self: *TrievManager, key: []const u8, val: []const u8, a: *Allocator) !void {
const keylen = key.len;
if (keylen > self.depth)
self.depth = keylen;
if (try self.t.insert(key, val, a))
self.num_vals += 1;
}
pub fn remove(self: *TrievManager, key: []const u8) TrievError!void {
if (try self.t.remove(key))
self.num_vals -= 1;
}
// this only prints out contents of Triev with debug prints.
// maybe later i'll make it return a list of key-value pairs.
pub fn walk(self: *TrievManager, a: *Allocator) !void {
// TrievManager's metadata allows us to allocate stacks with the exact size needed.
const triev_stack = try a.alloc(*Triev, self.depth);
defer a.free(triev_stack);
const kid_index_stack = try a.alloc(u5, self.depth);
defer a.free(kid_index_stack);
const bit_shift_stack = try a.alloc(u5, self.depth);
defer a.free(bit_shift_stack);
var stack_index: u64 = 0;
var cur = &self.t;
// selects which branch of triev to walk
var kid_index: u5 = 0;
// tracks which bit in cur's bit string corresponds to the current branch.
// i use this to recalculate each triev's key.
var bit_shift: u5 = 0;
while (true) {
if (cur.val.len != 0) {
std.debug.print("key ", .{});
// | 0x40 to unsquish key. i'd prefer to print in lowercase
// but i really can't be bothered to write more than an or.
var i: u64 = 0;
while (i < stack_index) : (i += 1)
std.debug.print("{c}", .{@intCast(u8, bit_shift_stack[i]) | 0x40});
std.debug.print("\n\tval {s}\n", .{cur.val});
}
if (cur.kids.len == 0) {
// pop stack until i reach an item with kids left to walk
while (true) {
if (stack_index == 0)
return;
stack_index -= 1;
cur = triev_stack[stack_index];
kid_index = kid_index_stack[stack_index] + 1;
// popped triev has no more kids to walk
if (kid_index == cur.kids.len)
continue;
bit_shift = next_bit(cur.bit_string, bit_shift_stack[stack_index] + 1);
break;
}
} else {
bit_shift = next_bit(cur.bit_string, 0);
}
// store current triev before switching to kid
triev_stack[stack_index] = cur;
kid_index_stack[stack_index] = kid_index;
bit_shift_stack[stack_index] = bit_shift;
stack_index += 1;
cur = cur.kids[kid_index];
// reset values for new walk
kid_index = 0;
}
}
};
// root depth is 0, and each child is +1
// zig really needs multiple return values
const GetReturn = struct { t: *Triev, depth: u64 };
// triev as in retrieval. much better alternative to the ambiguous trie imo.
const Triev = struct {
bit_string: u32 = 0,
kids: []*Triev,
val: []const u8,
// walk toward key and return pointer to furthest triev reached
fn get(self: *Triev, key: []const u8) TrievError!GetReturn {
if (!is_valid_key(key))
return TrievError.InvalidKey;
var cur = self;
var i: u64 = 0;
while (i < key.len) : (i += 1) {
if (cur.bit_string == 0)
break;
// std.debug.print("{s}\n", .{ cur.val });
const k = @intCast(u5, key[i] & 0x1F);
// std.debug.print("\t{s} {}\n", .{ "looking for", k });
const bit_flag = @as(u32, 1) << k;
// assuming very sparse triev, only having one kid is most common
// and i'm already computing bit_flag for the general case
if (cur.bit_string == bit_flag) {
// std.debug.print("\t{s}\n", .{"an only child"});
cur = cur.kids[0];
} else if (cur.bit_string & bit_flag != 0) {
// std.debug.print("\t{s}\n", .{"it exists! now what?"});
// find number of 1's in bit_string to the right of bit_flag
const index = hamming_weight((cur.bit_string & ~bit_flag) << 31 - k);
cur = cur.kids[index];
// std.debug.print("\t{s} {}\n", .{ "HAMMMMMM", index });
} else {
// std.debug.print("\t{s}\n", .{"i don't see nothin'"});
break;
}
}
// std.debug.print("{s}\n\n", .{ cur.val });
return GetReturn{ .t = cur, .depth = i };
}
// create a Triev for each byte in key and assign val to last in line
// return value is true if new val was added to triev, false if old value was replaced
fn insert(self: *Triev, key: []const u8, val: []const u8, a: *Allocator) !bool {
const getReturn = try self.get(key);
const t = getReturn.t;
// i couldn't think of a good name to differentiate the key used for get
// and insert so ikey (i for insert) it is. the other option was to use
// key by calculating the correct index everytime, but that's annoying.
const ikey = key[getReturn.depth..];
if (ikey.len == 0) {
// return false when replacing non-empty value
var ret = false;
if (t.val.len == 0)
ret = true;
t.val = val;
return ret;
}
const trievs = try a.alloc(Triev, ikey.len);
const pointers = try a.alloc([1]*Triev, ikey.len - 1);
var i: u64 = 0;
const one: u32 = 1;
while (true) : (i += 1) {
if (i == ikey.len - 1)
break;
trievs[i].bit_string = one << @intCast(u5, ikey[i + 1] & 0x1F);
trievs[i].val = empty_str[0..];
trievs[i].kids = pointers[i][0..];
pointers[i][0] = &trievs[i + 1];
}
trievs[i].bit_string = 0;
trievs[i].kids = empty_arr[0..];
trievs[i].val = val;
if (t.bit_string == 0) {
const p = try a.create([1]*Triev);
p[0] = &trievs[0];
t.bit_string = one << @intCast(u5, ikey[0] & 0x1F);
t.kids = p;
} else {
const p = try a.alloc(*Triev, t.kids.len + 1);
const bit_pos = @intCast(u5, ikey[0] & 0x1F);
const bit_flag = one << bit_pos;
// dont need bit_string & ~bit_flag, like in get, because insertion means
// the bit at bit_pos is 0
const index = hamming_weight(t.bit_string << 31 - bit_pos);
t.bit_string |= bit_flag;
std.mem.copy(*Triev, p[0..index], t.kids[0..index]);
p[index] = &trievs[0];
std.mem.copy(*Triev, p[index + 1 ..], t.kids[index..]);
t.kids = p[0..];
}
return true;
}
// set val of Triev at key to empty string slice if such a Triev exists
// return true if a value was removed
fn remove(self: *Triev, key: []const u8) TrievError!bool {
const getReturn = try self.get(key);
if (getReturn.depth == key.len) {
getReturn.t.val = empty_str[0..];
return true;
}
return false;
}
};
const TrievError = error{
InvalidKey, //key must only be made of A-Za-Z_
};
// get number of 1's in bit string
// can return u5 because input is guaranteed to not be 0xFFFF_FFFFF
// if only i could just use the x86 instruction but alas
fn hamming_weight(bit_string: u32) u5 {
var bits = bit_string;
bits -= (bits >> 1) & 0x55555555;
bits = (bits & 0x33333333) + ((bits >> 2) & 0x33333333);
bits = (bits + (bits >> 4)) & 0x0f0f0f0f;
bits *%= 0x01010101;
return @intCast(u5, bits >> 24);
}
// find the first bit from the right that's 1 (with pre-shift)
fn next_bit(bit_string: u32, bit_shift: u5) u5 {
var bits = bit_string >> bit_shift;
var shift = bit_shift;
while (bits & 1 == 0) {
bits >>= 1;
shift += 1;
}
return shift;
}
// checks that key is only A-Za-z_ so it can safely be squished by @intCast
fn is_valid_key(key: []const u8) bool {
for (key) |k|
if (k != '_' and (k < 'A' or k > 'Z') and (k < 'a' or k > 'z'))
return false;
return true;
}
const expect = std.testing.expect;
test "compress" {
var automatic: [13]u8 = "Charlie_Daisy".*;
const manual = [_]u5{ 0x03, 0x08, 0x01, 0x12, 0x0C, 0x09, 0x05, 0x1F, 0x04, 0x01, 0x09, 0x13, 0x19 };
for (automatic) |char, i| {
const c = @intCast(u5, char & 0x1F);
try expect(c == manual[i]);
}
try expect(is_valid_key(automatic[0..]));
automatic[7] = '~';
try expect(!is_valid_key(automatic[0..]));
} | triev.zig |
const std = @import("std");
const mem = std.mem;
const io = std.io;
const fs = std.fs;
const fmt = std.fmt;
const testing = std.testing;
const Target = std.Target;
const CrossTarget = std.zig.CrossTarget;
const assert = std.debug.assert;
const SparcCpuinfoImpl = struct {
model: ?*const Target.Cpu.Model = null,
is_64bit: bool = false,
const cpu_names = .{
.{ "SuperSparc", &Target.sparc.cpu.supersparc },
.{ "HyperSparc", &Target.sparc.cpu.hypersparc },
.{ "SpitFire", &Target.sparc.cpu.ultrasparc },
.{ "BlackBird", &Target.sparc.cpu.ultrasparc },
.{ "Sabre", &Target.sparc.cpu.ultrasparc },
.{ "Hummingbird", &Target.sparc.cpu.ultrasparc },
.{ "Cheetah", &Target.sparc.cpu.ultrasparc3 },
.{ "Jalapeno", &Target.sparc.cpu.ultrasparc3 },
.{ "Jaguar", &Target.sparc.cpu.ultrasparc3 },
.{ "Panther", &Target.sparc.cpu.ultrasparc3 },
.{ "Serrano", &Target.sparc.cpu.ultrasparc3 },
.{ "UltraSparc T1", &Target.sparc.cpu.niagara },
.{ "UltraSparc T2", &Target.sparc.cpu.niagara2 },
.{ "UltraSparc T3", &Target.sparc.cpu.niagara3 },
.{ "UltraSparc T4", &Target.sparc.cpu.niagara4 },
.{ "UltraSparc T5", &Target.sparc.cpu.niagara4 },
.{ "LEON", &Target.sparc.cpu.leon3 },
};
fn line_hook(self: *SparcCpuinfoImpl, key: []const u8, value: []const u8) !bool {
if (mem.eql(u8, key, "cpu")) {
inline for (cpu_names) |pair| {
if (mem.indexOfPos(u8, value, 0, pair[0]) != null) {
self.model = pair[1];
break;
}
}
} else if (mem.eql(u8, key, "type")) {
self.is_64bit = mem.eql(u8, value, "sun4u") or mem.eql(u8, value, "sun4v");
}
return true;
}
fn finalize(self: *const SparcCpuinfoImpl, arch: Target.Cpu.Arch) ?Target.Cpu {
// At the moment we only support 64bit SPARC systems.
assert(self.is_64bit);
const model = self.model orelse Target.Cpu.Model.generic(arch);
return Target.Cpu{
.arch = arch,
.model = model,
.features = model.features,
};
}
};
const SparcCpuinfoParser = CpuinfoParser(SparcCpuinfoImpl);
test "cpuinfo: SPARC" {
try testParser(SparcCpuinfoParser, &Target.sparc.cpu.niagara2,
\\cpu : UltraSparc T2 (Niagara2)
\\fpu : UltraSparc T2 integrated FPU
\\pmu : niagara2
\\type : sun4v
);
}
const PowerpcCpuinfoImpl = struct {
model: ?*const Target.Cpu.Model = null,
const cpu_names = .{
.{ "604e", &Target.powerpc.cpu.@"604e" },
.{ "604", &Target.powerpc.cpu.@"604" },
.{ "7400", &Target.powerpc.cpu.@"7400" },
.{ "7410", &Target.powerpc.cpu.@"7400" },
.{ "7447", &Target.powerpc.cpu.@"7400" },
.{ "7455", &Target.powerpc.cpu.@"7450" },
.{ "G4", &Target.powerpc.cpu.@"g4" },
.{ "POWER4", &Target.powerpc.cpu.@"970" },
.{ "PPC970FX", &Target.powerpc.cpu.@"970" },
.{ "PPC970MP", &Target.powerpc.cpu.@"970" },
.{ "G5", &Target.powerpc.cpu.@"g5" },
.{ "POWER5", &Target.powerpc.cpu.@"g5" },
.{ "A2", &Target.powerpc.cpu.@"a2" },
.{ "POWER6", &Target.powerpc.cpu.@"pwr6" },
.{ "POWER7", &Target.powerpc.cpu.@"pwr7" },
.{ "POWER8", &Target.powerpc.cpu.@"pwr8" },
.{ "POWER8E", &Target.powerpc.cpu.@"pwr8" },
.{ "POWER8NVL", &Target.powerpc.cpu.@"pwr8" },
.{ "POWER9", &Target.powerpc.cpu.@"pwr9" },
.{ "POWER10", &Target.powerpc.cpu.@"pwr10" },
};
fn line_hook(self: *PowerpcCpuinfoImpl, key: []const u8, value: []const u8) !bool {
if (mem.eql(u8, key, "cpu")) {
// The model name is often followed by a comma or space and extra
// info.
inline for (cpu_names) |pair| {
const end_index = mem.indexOfAny(u8, value, ", ") orelse value.len;
if (mem.eql(u8, value[0..end_index], pair[0])) {
self.model = pair[1];
break;
}
}
// Stop the detection once we've seen the first core.
return false;
}
return true;
}
fn finalize(self: *const PowerpcCpuinfoImpl, arch: Target.Cpu.Arch) ?Target.Cpu {
const model = self.model orelse Target.Cpu.Model.generic(arch);
return Target.Cpu{
.arch = arch,
.model = model,
.features = model.features,
};
}
};
const PowerpcCpuinfoParser = CpuinfoParser(PowerpcCpuinfoImpl);
test "cpuinfo: PowerPC" {
try testParser(PowerpcCpuinfoParser, &Target.powerpc.cpu.@"970",
\\processor : 0
\\cpu : PPC970MP, altivec supported
\\clock : 1250.000000MHz
\\revision : 1.1 (pvr 0044 0101)
);
try testParser(PowerpcCpuinfoParser, &Target.powerpc.cpu.pwr8,
\\processor : 0
\\cpu : POWER8 (raw), altivec supported
\\clock : 2926.000000MHz
\\revision : 2.0 (pvr 004d 0200)
);
}
fn testParser(parser: anytype, expected_model: *const Target.Cpu.Model, input: []const u8) !void {
var fbs = io.fixedBufferStream(input);
const result = try parser.parse(.powerpc, fbs.reader());
testing.expectEqual(expected_model, result.?.model);
testing.expect(expected_model.features.eql(result.?.features));
}
// The generic implementation of a /proc/cpuinfo parser.
// For every line it invokes the line_hook method with the key and value strings
// as first and second parameters. Returning false from the hook function stops
// the iteration without raising an error.
// When all the lines have been analyzed the finalize method is called.
fn CpuinfoParser(comptime impl: anytype) type {
return struct {
fn parse(arch: Target.Cpu.Arch, reader: anytype) anyerror!?Target.Cpu {
var line_buf: [1024]u8 = undefined;
var obj: impl = .{};
while (true) {
const line = (try reader.readUntilDelimiterOrEof(&line_buf, '\n')) orelse break;
const colon_pos = mem.indexOfScalar(u8, line, ':') orelse continue;
const key = mem.trimRight(u8, line[0..colon_pos], " \t");
const value = mem.trimLeft(u8, line[colon_pos + 1 ..], " \t");
if (!try obj.line_hook(key, value))
break;
}
return obj.finalize(arch);
}
};
}
pub fn detectNativeCpuAndFeatures() ?Target.Cpu {
var f = fs.openFileAbsolute("/proc/cpuinfo", .{ .intended_io_mode = .blocking }) catch |err| switch (err) {
else => return null,
};
defer f.close();
const current_arch = std.Target.current.cpu.arch;
switch (current_arch) {
.sparcv9 => {
return SparcCpuinfoParser.parse(current_arch, f.reader()) catch null;
},
.powerpc, .powerpcle, .powerpc64, .powerpc64le => {
return PowerpcCpuinfoParser.parse(current_arch, f.reader()) catch null;
},
else => {},
}
return null;
} | lib/std/zig/system/linux.zig |
const std = @import("std");
const mem = std.mem;
const builtin = @import("builtin");
const expect = std.testing.expect;
test "vector wrap operators" {
const S = struct {
fn doTheTest() void {
var v: @Vector(4, i32) = [4]i32{ 2147483647, -2, 30, 40 };
var x: @Vector(4, i32) = [4]i32{ 1, 2147483647, 3, 4 };
expect(mem.eql(i32, ([4]i32)(v +% x), [4]i32{ -2147483648, 2147483645, 33, 44 }));
expect(mem.eql(i32, ([4]i32)(v -% x), [4]i32{ 2147483646, 2147483647, 27, 36 }));
expect(mem.eql(i32, ([4]i32)(v *% x), [4]i32{ 2147483647, 2, 90, 160 }));
var z: @Vector(4, i32) = [4]i32{ 1, 2, 3, -2147483648 };
expect(mem.eql(i32, ([4]i32)(-%z), [4]i32{ -1, -2, -3, -2147483648 }));
}
};
S.doTheTest();
comptime S.doTheTest();
}
test "vector int operators" {
const S = struct {
fn doTheTest() void {
var v: @Vector(4, i32) = [4]i32{ 10, 20, 30, 40 };
var x: @Vector(4, i32) = [4]i32{ 1, 2, 3, 4 };
expect(mem.eql(i32, ([4]i32)(v + x), [4]i32{ 11, 22, 33, 44 }));
expect(mem.eql(i32, ([4]i32)(v - x), [4]i32{ 9, 18, 27, 36 }));
expect(mem.eql(i32, ([4]i32)(v * x), [4]i32{ 10, 40, 90, 160 }));
expect(mem.eql(i32, ([4]i32)(-v), [4]i32{ -10, -20, -30, -40 }));
}
};
S.doTheTest();
comptime S.doTheTest();
}
test "vector float operators" {
const S = struct {
fn doTheTest() void {
var v: @Vector(4, f32) = [4]f32{ 10, 20, 30, 40 };
var x: @Vector(4, f32) = [4]f32{ 1, 2, 3, 4 };
expect(mem.eql(f32, ([4]f32)(v + x), [4]f32{ 11, 22, 33, 44 }));
expect(mem.eql(f32, ([4]f32)(v - x), [4]f32{ 9, 18, 27, 36 }));
expect(mem.eql(f32, ([4]f32)(v * x), [4]f32{ 10, 40, 90, 160 }));
expect(mem.eql(f32, ([4]f32)(-x), [4]f32{ -1, -2, -3, -4 }));
}
};
S.doTheTest();
comptime S.doTheTest();
}
test "vector bit operators" {
const S = struct {
fn doTheTest() void {
var v: @Vector(4, u8) = [4]u8{ 0b10101010, 0b10101010, 0b10101010, 0b10101010 };
var x: @Vector(4, u8) = [4]u8{ 0b11110000, 0b00001111, 0b10101010, 0b01010101 };
expect(mem.eql(u8, ([4]u8)(v ^ x), [4]u8{ 0b01011010, 0b10100101, 0b00000000, 0b11111111 }));
expect(mem.eql(u8, ([4]u8)(v | x), [4]u8{ 0b11111010, 0b10101111, 0b10101010, 0b11111111 }));
expect(mem.eql(u8, ([4]u8)(v & x), [4]u8{ 0b10100000, 0b00001010, 0b10101010, 0b00000000 }));
}
};
S.doTheTest();
comptime S.doTheTest();
}
test "implicit cast vector to array" {
const S = struct {
fn doTheTest() void {
var a: @Vector(4, i32) = [_]i32{ 1, 2, 3, 4 };
var result_array: [4]i32 = a;
result_array = a;
expect(mem.eql(i32, result_array, [4]i32{ 1, 2, 3, 4 }));
}
};
S.doTheTest();
comptime S.doTheTest();
}
test "array to vector" {
var foo: f32 = 3.14;
var arr = [4]f32{ foo, 1.5, 0.0, 0.0 };
var vec: @Vector(4, f32) = arr;
}
test "vector upcast" {
const S = struct {
fn doTheTest() void {
{
const v: @Vector(4, i16) = [4]i16{ 21, -2, 30, 40};
const x: @Vector(4, i32) = @Vector(4, i32)(v);
expect(x[0] == 21);
expect(x[1] == -2);
expect(x[2] == 30);
expect(x[3] == 40);
}
{
const v: @Vector(4, u16) = [4]u16{ 21, 2, 30, 40};
const x: @Vector(4, u32) = @Vector(4, u32)(v);
expect(x[0] == 21);
expect(x[1] == 2);
expect(x[2] == 30);
expect(x[3] == 40);
}
{
const v: @Vector(4, f16) = [4]f16{ 21, -2, 30, 40};
const x: @Vector(4, f32) = @Vector(4, f32)(v);
expect(x[0] == 21);
expect(x[1] == -2);
expect(x[2] == 30);
expect(x[3] == 40);
}
}
};
S.doTheTest();
comptime S.doTheTest();
}
test "vector truncate" {
const S = struct {
fn doTheTest() void {
const v: @Vector(4, i32) = [4]i32{ 21, -2, 30, 40};
const x: @Vector(4, i16) = @truncate(@Vector(4, i16), v);
expect(x[0] == 21);
expect(x[1] == -2);
expect(x[2] == 30);
expect(x[3] == 40);
}
};
S.doTheTest();
comptime S.doTheTest();
}
test "vector casts of sizes not divisable by 8" {
const S = struct {
fn doTheTest() void {
{
var v: @Vector(4, u3) = [4]u3{ 5, 2, 3, 0};
var x: [4]u3 = v;
expect(mem.eql(u3, x, ([4]u3)(v)));
}
{
var v: @Vector(4, u2) = [4]u2{ 1, 2, 3, 0};
var x: [4]u2 = v;
expect(mem.eql(u2, x, ([4]u2)(v)));
}
{
var v: @Vector(4, u1) = [4]u1{ 1, 0, 1, 0};
var x: [4]u1 = v;
expect(mem.eql(u1, x, ([4]u1)(v)));
}
{
var v: @Vector(4, bool) = [4]bool{ false, false, true, false};
var x: [4]bool = v;
expect(mem.eql(bool, x, ([4]bool)(v)));
}
}
};
S.doTheTest();
comptime S.doTheTest();
}
test "implicit cast vector to array - bool" {
const S = struct {
fn doTheTest() void {
const a: @Vector(4, bool) = [_]bool{ true, false, true, false };
const result_array: [4]bool = a;
expect(mem.eql(bool, result_array, [4]bool{ true, false, true, false }));
}
};
S.doTheTest();
comptime S.doTheTest();
}
test "vector bin compares with mem.eql" {
const S = struct {
fn doTheTest() void {
var v: @Vector(4, i32) = [4]i32{ 2147483647, -2, 30, 40 };
var x: @Vector(4, i32) = [4]i32{ 1, 2147483647, 30, 4 };
expect(mem.eql(bool, ([4]bool)(v == x), [4]bool{ false, false, true, false}));
expect(mem.eql(bool, ([4]bool)(v != x), [4]bool{ true, true, false, true}));
expect(mem.eql(bool, ([4]bool)(v < x), [4]bool{ false, true, false, false}));
expect(mem.eql(bool, ([4]bool)(v > x), [4]bool{ true, false, false, true}));
expect(mem.eql(bool, ([4]bool)(v <= x), [4]bool{ false, true, true, false}));
expect(mem.eql(bool, ([4]bool)(v >= x), [4]bool{ true, false, true, true}));
}
};
S.doTheTest();
comptime S.doTheTest();
}
test "vector member field access" {
const S = struct {
fn doTheTest() void {
const q: @Vector(4, u32) = undefined;
expect(q.len == 4);
const v = @Vector(4, i32);
expect(v.len == 4);
expect(v.bit_count == 32);
expect(v.is_signed == true);
const k = @Vector(2, bool);
expect(k.len == 2);
const x = @Vector(3, f32);
expect(x.len == 3);
expect(x.bit_count == 32);
const z = @Vector(3, *align(4) u32);
expect(z.len == 3);
expect(z.Child == u32);
// FIXME is this confusing? However vector alignment requirements are entirely
// dependant on their size, and can be gotten with @alignOf().
expect(z.alignment == 4);
}
};
S.doTheTest();
comptime S.doTheTest();
}
test "vector access elements - load" {
{
var a: @Vector(4, i32) = [_]i32{ 1, 2, 3, undefined };
expect(a[2] == 3);
expect(a[1] == i32(2));
expect(3 == a[2]);
}
comptime {
comptime var a: @Vector(4, i32) = [_]i32{ 1, 2, 3, undefined };
expect(a[0] == 1);
expect(a[1] == i32(2));
expect(3 == a[2]);
}
}
test "vector access elements - store" {
{
var a: @Vector(4, i32) = [_]i32{ 1, 5, 3, undefined };
a[2] = 1;
expect(a[1] == 5);
expect(a[2] == i32(1));
a[3] = -364;
expect(-364 == a[3]);
}
comptime {
comptime var a: @Vector(4, i32) = [_]i32{ 1, 2, 3, undefined };
a[2] = 5;
expect(a[2] == i32(5));
a[3] = -364;
expect(-364 == a[3]);
}
}
test "vector @splat" {
const S = struct {
fn doTheTest() void {
var v: u32 = 5;
var x = @splat(4, v);
expect(@typeOf(x) == @Vector(4, u32));
expect(x[0] == 5);
expect(x[1] == 5);
expect(x[2] == 5);
expect(x[3] == 5);
}
};
S.doTheTest();
comptime S.doTheTest();
}
test "vector @bitCast" {
const S = struct {
fn doTheTest() void {
{
const math = @import("std").math;
const v: @Vector(4, u32) = [4]u32{ 0x7F800000, 0x7F800001, 0xFF800000, 0};
const x: @Vector(4, f32) = @bitCast(@Vector(4, f32), v);
expect(x[0] == math.inf(f32));
expect(x[1] != x[1]); // NaN
expect(x[2] == -math.inf(f32));
expect(x[3] == 0);
}
{
const math = @import("std").math;
const v: @Vector(2, u64) = [2]u64{ 0x7F8000017F800000, 0xFF800000};
const x: @Vector(4, f32) = @bitCast(@Vector(4, f32), v);
expect(x[0] == math.inf(f32));
expect(x[1] != x[1]); // NaN
expect(x[2] == -math.inf(f32));
expect(x[3] == 0);
}
{
const v: @Vector(4, u8) = [_]u8{2, 1, 2, 1};
const x: u32 = @bitCast(u32, v);
expect(x == 0x01020102);
const z: @Vector(4, u8) = @bitCast(@Vector(4, u8), x);
expect(z[0] == 2);
expect(z[1] == 1);
expect(z[2] == 2);
expect(z[3] == 1);
}
{
const v: @Vector(4, i8) = [_]i8{2, 1, 0, -128};
const x: u32 = @bitCast(u32, v);
expect(x == 0x80000102);
}
{
const v: @Vector(4, u1) = [_]u1{1, 1, 0, 1};
const x: u4 = @bitCast(u4, v);
expect(x == 0b1011);
}
{
const v: @Vector(4, u3) = [_]u3{0b100, 0b111, 0, 1};
const x: u12 = @bitCast(u12, v);
expect(x == 0b001000111100);
const z: @Vector(4, u3) = @bitCast(@Vector(4, u3), x);
expect(z[0] == 0b100);
expect(z[1] == 0b111);
expect(z[2] == 0);
expect(z[3] == 1);
}
{
const v: @Vector(2, u9) = [_]u9{2, 1};
const x: u18 = @bitCast(u18, v);
expect(x == 0b000000001000000010);
const z: @Vector(2, u9) = @bitCast(@Vector(2, u9), x);
expect(z[0] == 2);
expect(z[1] == 1);
}
{
const v: @Vector(4, bool) = [_]bool{false, true, false, true};
const x: u4 = @bitCast(u4, v);
expect(x == 0b1010);
const z: @Vector(4, bool) = @bitCast(@Vector(4, bool), x);
expect(z[0] == false);
expect(z[1] == true);
expect(z[2] == false);
expect(z[3] == true);
}
}
};
S.doTheTest();
comptime S.doTheTest();
} | test/stage1/behavior/vector.zig |
const std = @import("std");
const assert = std.debug.assert;
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
const AutoHashMap = std.AutoHashMap;
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const ExecError = error{
InvalidOpcode,
InvalidParamMode,
};
fn opcode(ins: Instr) Instr {
return @rem(ins, 100);
}
test "opcode extraction" {
expectEqual(opcode(1002), 2);
}
fn paramMode(ins: Instr, pos: Instr) Instr {
var div: Instr = 100; // Mode of parameter 0 is in digit 3
var i: Instr = 0;
while (i < pos) : (i += 1) {
div *= 10;
}
return @rem(@divTrunc(ins, div), 10);
}
test "param mode extraction" {
expectEqual(paramMode(1002, 0), 0);
expectEqual(paramMode(1002, 1), 1);
expectEqual(paramMode(1002, 2), 0);
}
pub const Instr = i64;
pub const Intcode = []Instr;
pub const Mem = struct {
backend: ArrayList(Instr),
const Self = @This();
pub fn init(intcode: Intcode, alloc: *Allocator) Self {
return Self{
.backend = ArrayList(Instr).fromOwnedSlice(alloc, intcode),
};
}
pub fn get(self: Self, pos: usize) Instr {
return if (pos < self.backend.items.len) self.backend.at(pos) else 0;
}
pub fn set(self: *Self, pos: usize, val: Instr) !void {
if (pos < self.backend.items.len) {
self.backend.set(pos, val);
} else {
const old_len = self.backend.items.len;
try self.backend.resize(pos + 1);
var i: usize = old_len;
while (i < self.backend.items.len) : (i += 1) {
self.backend.set(i, 0);
}
self.backend.set(pos, val);
}
}
};
pub const IntcodeComputer = struct {
mem: Mem,
pc: usize,
relative_base: Instr,
state: State,
input: ?Instr,
output: ?Instr,
const Self = @This();
pub const State = enum {
Stopped,
Running,
AwaitingInput,
AwaitingOutput,
};
pub fn init(intcode: Intcode, alloc: *Allocator) Self {
return Self{
.mem = Mem.init(intcode, alloc),
.pc = 0,
.relative_base = 0,
.state = State.Running,
.input = null,
.output = null,
};
}
fn getParam(self: Self, n: usize, mode: Instr) !Instr {
const val = self.mem.get(self.pc + 1 + n);
return switch (mode) {
0 => self.mem.get(@intCast(usize, val)),
1 => val,
2 => self.mem.get(@intCast(usize, self.relative_base + val)),
else => return error.InvalidParamMode,
};
}
fn getPos(self: Self, n: usize, mode: Instr) !usize {
const val = self.mem.get(self.pc + 1 + n);
return switch (mode) {
0 => @intCast(usize, val),
1 => return error.OutputParameterImmediateMode,
2 => @intCast(usize, self.relative_base + val),
else => return error.InvalidParamMode,
};
}
pub fn exec(self: *Self) !void {
const instr = self.mem.get(self.pc);
switch (opcode(instr)) {
99 => self.state = State.Stopped,
1 => {
const val_x = try self.getParam(0, paramMode(instr, 0));
const val_y = try self.getParam(1, paramMode(instr, 1));
const pos_result = try self.getPos(2, paramMode(instr, 2));
try self.mem.set(pos_result, val_x + val_y);
self.pc += 4;
},
2 => {
const val_x = try self.getParam(0, paramMode(instr, 0));
const val_y = try self.getParam(1, paramMode(instr, 1));
const pos_result = try self.getPos(2, paramMode(instr, 2));
try self.mem.set(pos_result, val_x * val_y);
self.pc += 4;
},
3 => {
const pos_x = try self.getPos(0, paramMode(instr, 0));
if (self.input) |val| {
try self.mem.set(pos_x, val);
self.pc += 2;
self.input = null;
} else {
self.state = State.AwaitingInput;
}
},
4 => {
const val_x = try self.getParam(0, paramMode(instr, 0));
if (self.output) |_| {
self.state = State.AwaitingOutput;
} else {
self.output = val_x;
self.pc += 2;
}
},
5 => {
const val_x = try self.getParam(0, paramMode(instr, 0));
if (val_x != 0) {
const val_y = try self.getParam(1, paramMode(instr, 1));
self.pc = @intCast(usize, val_y);
} else {
self.pc += 3;
}
},
6 => {
const val_x = try self.getParam(0, paramMode(instr, 0));
if (val_x == 0) {
const val_y = try self.getParam(1, paramMode(instr, 1));
self.pc = @intCast(usize, val_y);
} else {
self.pc += 3;
}
},
7 => {
const val_x = try self.getParam(0, paramMode(instr, 0));
const val_y = try self.getParam(1, paramMode(instr, 1));
const pos_result = try self.getPos(2, paramMode(instr, 2));
try self.mem.set(pos_result, if (val_x < val_y) 1 else 0);
self.pc += 4;
},
8 => {
const val_x = try self.getParam(0, paramMode(instr, 0));
const val_y = try self.getParam(1, paramMode(instr, 1));
const pos_result = try self.getPos(2, paramMode(instr, 2));
try self.mem.set(pos_result, if (val_x == val_y) 1 else 0);
self.pc += 4;
},
9 => {
const val_x = try self.getParam(0, paramMode(instr, 0));
self.relative_base += val_x;
self.pc += 2;
},
else => {
std.debug.warn("pos: {}, instr: {}\n", .{ self.pc, instr });
return error.InvalidOpcode;
},
}
}
pub fn execUntilHalt(self: *Self) !void {
// try to jump-start the computer if it was waiting for I/O
if (self.state != State.Stopped)
self.state = State.Running;
while (self.state == State.Running)
try self.exec();
}
};
test "test exec 1" {
var intcode = [_]Instr{ 1, 0, 0, 0, 99 };
var comp = IntcodeComputer.init(&intcode, std.testing.failing_allocator);
try comp.execUntilHalt();
expectEqual(intcode[0], 2);
}
test "test exec 2" {
var intcode = [_]Instr{ 2, 3, 0, 3, 99 };
var comp = IntcodeComputer.init(&intcode, std.testing.failing_allocator);
try comp.execUntilHalt();
expectEqual(intcode[3], 6);
}
test "test exec 3" {
var intcode = [_]Instr{ 2, 4, 4, 5, 99, 0 };
var comp = IntcodeComputer.init(&intcode, std.testing.failing_allocator);
try comp.execUntilHalt();
expectEqual(intcode[5], 9801);
}
test "test exec with different param mode" {
var intcode = [_]Instr{ 1002, 4, 3, 4, 33 };
var comp = IntcodeComputer.init(&intcode, std.testing.failing_allocator);
try comp.execUntilHalt();
expectEqual(intcode[4], 99);
}
test "test exec with negative integers" {
var intcode = [_]Instr{ 1101, 100, -1, 4, 0 };
var comp = IntcodeComputer.init(&intcode, std.testing.failing_allocator);
try comp.execUntilHalt();
expectEqual(intcode[4], 99);
}
test "test equal 1" {
var intcode = [_]Instr{ 3, 9, 8, 9, 10, 9, 4, 9, 99, -1, 8 };
var comp = IntcodeComputer.init(&intcode, std.testing.failing_allocator);
comp.input = 8;
try comp.execUntilHalt();
expectEqual(comp.output.?, 1);
}
test "test equal 2" {
var intcode = [_]Instr{ 3, 9, 8, 9, 10, 9, 4, 9, 99, -1, 8 };
var comp = IntcodeComputer.init(&intcode, std.testing.failing_allocator);
comp.input = 13;
try comp.execUntilHalt();
expectEqual(comp.output.?, 0);
}
test "test less than 1" {
var intcode = [_]Instr{ 3, 9, 7, 9, 10, 9, 4, 9, 99, -1, 8 };
var comp = IntcodeComputer.init(&intcode, std.testing.failing_allocator);
comp.input = 5;
try comp.execUntilHalt();
expectEqual(comp.output.?, 1);
}
test "test less than 2" {
var intcode = [_]Instr{ 3, 9, 7, 9, 10, 9, 4, 9, 99, -1, 8 };
var comp = IntcodeComputer.init(&intcode, std.testing.failing_allocator);
comp.input = 20;
try comp.execUntilHalt();
expectEqual(comp.output.?, 0);
}
test "test equal immediate" {
var intcode = [_]Instr{ 3, 3, 1108, -1, 8, 3, 4, 3, 99 };
var comp = IntcodeComputer.init(&intcode, std.testing.failing_allocator);
comp.input = 8;
try comp.execUntilHalt();
expectEqual(comp.output.?, 1);
}
test "test less than immediate" {
var intcode = [_]Instr{ 3, 3, 1107, -1, 8, 3, 4, 3, 99 };
var comp = IntcodeComputer.init(&intcode, std.testing.failing_allocator);
comp.input = 3;
try comp.execUntilHalt();
expectEqual(comp.output.?, 1);
}
test "quine" {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = &arena.allocator;
defer arena.deinit();
var intcode = [_]Instr{ 109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101, 1006, 101, 0, 99 };
var comp = IntcodeComputer.init(&intcode, allocator);
try comp.execUntilHalt();
}
test "big number" {
var intcode = [_]Instr{ 1102, 34915192, 34915192, 7, 4, 7, 99, 0 };
var comp = IntcodeComputer.init(&intcode, std.testing.failing_allocator);
try comp.execUntilHalt();
}
test "big number 2" {
var intcode = [_]Instr{ 104, 1125899906842624, 99 };
var comp = IntcodeComputer.init(&intcode, std.testing.failing_allocator);
try comp.execUntilHalt();
expectEqual(comp.output.?, 1125899906842624);
}
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = &arena.allocator;
defer arena.deinit();
const input_file = try std.fs.cwd().openFile("input19.txt", .{});
var input_stream = input_file.reader();
var buf: [1024]u8 = undefined;
var ints = std.ArrayList(Instr).init(allocator);
// read amp intcode into an int arraylist
while (try input_stream.readUntilDelimiterOrEof(&buf, ',')) |item| {
// add an empty element to the input file because I don't want to modify
// this to discard newlines
try ints.append(std.fmt.parseInt(Instr, item, 10) catch 0);
}
var points_affected: usize = 0;
// scan area
var y: Instr = 0;
while (y < 50) : (y += 1) {
var x: Instr = 0;
while (x < 50) : (x += 1) {
var ints_cpy = try std.mem.dupe(allocator, Instr, ints.items);
defer allocator.free(ints_cpy);
var comp = IntcodeComputer.init(ints_cpy, allocator);
try comp.execUntilHalt();
comp.input = x;
try comp.execUntilHalt();
comp.input = y;
try comp.execUntilHalt();
const res = comp.output orelse return error.NoOutput;
comp.output = null;
if (res == 1) points_affected += 1;
if (res == 1) {
std.debug.warn("#", .{});
} else {
if (x == 40) {
std.debug.warn(":", .{});
} else if (y == 39) {
std.debug.warn("-", .{});
} else {
std.debug.warn(".", .{});
}
}
}
std.debug.warn("\n", .{});
}
std.debug.warn("points affected: {}\n", .{points_affected});
} | zig/19.zig |
const std = @import("std");
const time = @import("time.zig");
const April = time.Month.April;
const December = time.Month.December;
const January = time.Month.January;
const Location = time.Location;
const Monday = time.Weekday.Monday;
const Saturday = time.Weekday.Saturday;
const September = time.Month.September;
const Sunday = time.Weekday.Sunday;
const Thursday = time.Weekday.Thursday;
const Wednesday = time.Weekday.Wednesday;
const math = std.math;
const mem = std.mem;
const testing = std.testing;
const failed_test = error.Failed;
const parsedTime = struct {
year: isize,
month: time.Month,
day: isize,
hour: isize,
minute: isize,
second: isize,
nanosecond: isize,
weekday: time.Weekday,
zone_offset: isize,
zone: []const u8,
fn init(year: isize, month: time.Month, day: isize, hour: isize, minute: isize, second: isize, nanosecond: isize, weekday: time.Weekday, zone_offset: isize, zone: []const u8) parsedTime {
return parsedTime{
.year = year,
.month = month,
.day = day,
.hour = hour,
.minute = minute,
.second = second,
.nanosecond = nanosecond,
.weekday = weekday,
.zone_offset = zone_offset,
.zone = zone,
};
}
};
const TimeTest = struct {
seconds: i64,
golden: parsedTime,
};
const utc_tests = [_]TimeTest{
TimeTest{ .seconds = 0, .golden = parsedTime.init(1970, January, 1, 0, 0, 0, 0, Thursday, 0, "UTC") },
TimeTest{ .seconds = 1221681866, .golden = parsedTime.init(2008, September, 17, 20, 4, 26, 0, Wednesday, 0, "UTC") },
TimeTest{ .seconds = -1221681866, .golden = parsedTime.init(1931, April, 16, 3, 55, 34, 0, Thursday, 0, "UTC") },
TimeTest{ .seconds = -11644473600, .golden = parsedTime.init(1601, January, 1, 0, 0, 0, 0, Monday, 0, "UTC") },
TimeTest{ .seconds = 599529660, .golden = parsedTime.init(1988, December, 31, 0, 1, 0, 0, Saturday, 0, "UTC") },
TimeTest{ .seconds = 978220860, .golden = parsedTime.init(2000, December, 31, 0, 1, 0, 0, Sunday, 0, "UTC") },
};
const nano_tests = [_]TimeTest{
TimeTest{ .seconds = 0, .golden = parsedTime.init(1970, January, 1, 0, 0, 0, 1e8, Thursday, 0, "UTC") },
TimeTest{ .seconds = 1221681866, .golden = parsedTime.init(2008, September, 17, 20, 4, 26, 2e8, Wednesday, 0, "UTC") },
};
const local_tests = [_]TimeTest{
TimeTest{ .seconds = 0, .golden = parsedTime.init(1969, December, 31, 16, 0, 0, 0, Wednesday, -8 * 60 * 60, "PST") },
TimeTest{ .seconds = 1221681866, .golden = parsedTime.init(2008, September, 17, 13, 4, 26, 0, Wednesday, -7 * 60 * 60, "PDT") },
};
const nano_local_tests = [_]TimeTest{
TimeTest{ .seconds = 0, .golden = parsedTime.init(1969, December, 31, 16, 0, 0, 0, Wednesday, -8 * 60 * 60, "PST") },
TimeTest{ .seconds = 1221681866, .golden = parsedTime.init(2008, September, 17, 13, 4, 26, 3e8, Wednesday, -7 * 60 * 60, "PDT") },
};
fn same(t: time.Time, u: *parsedTime) bool {
const date = t.date();
const clock = t.clock();
const zone = t.zone();
const check = date.year != u.year or @enumToInt(date.month) != @enumToInt(u.month) or
date.day != u.day or clock.hour != u.hour or clock.min != u.minute or clock.sec != u.second or
!mem.eql(u8, zone.name, u.zone) or zone.offset != u.zone_offset;
if (check) {
return false;
}
return t.year() == u.year and
@enumToInt(t.month()) == @enumToInt(u.month) and
t.day() == u.day and
t.hour() == u.hour and
t.minute() == u.minute and
t.second() == u.second and
t.nanosecond() == u.nanosecond and
@enumToInt(t.weekday()) == @enumToInt(u.weekday);
}
test "TestSecondsToUTC" {
// try skip();
for (utc_tests) |ts| {
var tm = time.unix(ts.seconds, 0, &Location.utc_local);
const ns = tm.unix();
testing.expectEqual(ns, ts.seconds);
var golden = ts.golden;
testing.expect(same(tm, &golden));
}
}
test "TestNanosecondsToUTC" {
// try skip();
for (nano_tests) |tv| {
var golden = tv.golden;
const nsec = tv.seconds * i64(1e9) + @intCast(i64, golden.nanosecond);
var tm = time.unix(0, nsec, &Location.utc_local);
const new_nsec = tm.unix() * i64(1e9) + @intCast(i64, tm.nanosecond());
testing.expectEqual(new_nsec, nsec);
testing.expect(same(tm, &golden));
}
}
test "TestSecondsToLocalTime" {
// try skip();
var buf = try std.Buffer.init(std.debug.global_allocator, "");
defer buf.deinit();
var loc = try Location.load("US/Pacific");
defer loc.deinit();
for (local_tests) |tv| {
var golden = tv.golden;
const sec = tv.seconds;
var tm = time.unix(sec, 0, &loc);
const new_sec = tm.unix();
testing.expectEqual(new_sec, sec);
testing.expect(same(tm, &golden));
}
}
test "TestNanosecondsToUTC" {
// try skip();
var loc = try Location.load("US/Pacific");
defer loc.deinit();
for (nano_local_tests) |tv| {
var golden = tv.golden;
const nsec = tv.seconds * i64(1e9) + @intCast(i64, golden.nanosecond);
var tm = time.unix(0, nsec, &loc);
const new_nsec = tm.unix() * i64(1e9) + @intCast(i64, tm.nanosecond());
testing.expectEqual(new_nsec, nsec);
testing.expect(same(tm, &golden));
}
}
const formatTest = struct {
name: []const u8,
format: []const u8,
result: []const u8,
fn init(name: []const u8, format: []const u8, result: []const u8) formatTest {
return formatTest{ .name = name, .format = format, .result = result };
}
};
const format_tests = [_]formatTest{
formatTest.init("ANSIC", time.ANSIC, "Wed Feb 4 21:00:57 2009"),
formatTest.init("UnixDate", time.UnixDate, "Wed Feb 4 21:00:57 PST 2009"),
formatTest.init("RubyDate", time.RubyDate, "Wed Feb 04 21:00:57 -0800 2009"),
formatTest.init("RFC822", time.RFC822, "04 Feb 09 21:00 PST"),
formatTest.init("RFC850", time.RFC850, "Wednesday, 04-Feb-09 21:00:57 PST"),
formatTest.init("RFC1123", time.RFC1123, "Wed, 04 Feb 2009 21:00:57 PST"),
formatTest.init("RFC1123Z", time.RFC1123Z, "Wed, 04 Feb 2009 21:00:57 -0800"),
formatTest.init("RFC3339", time.RFC3339, "2009-02-04T21:00:57-08:00"),
formatTest.init("RFC3339Nano", time.RFC3339Nano, "2009-02-04T21:00:57.0123456-08:00"),
formatTest.init("Kitchen", time.Kitchen, "9:00PM"),
formatTest.init("am/pm", "3pm", "9pm"),
formatTest.init("AM/PM", "3PM", "9PM"),
formatTest.init("two-digit year", "06 01 02", "09 02 04"),
// Three-letter months and days must not be followed by lower-case letter.
formatTest.init("Janet", "Hi Janet, the Month is January", "Hi Janet, the Month is February"),
// Time stamps, Fractional seconds.
formatTest.init("Stamp", time.Stamp, "Feb 4 21:00:57"),
formatTest.init("StampMilli", time.StampMilli, "Feb 4 21:00:57.012"),
formatTest.init("StampMicro", time.StampMicro, "Feb 4 21:00:57.012345"),
formatTest.init("StampNano", time.StampNano, "Feb 4 21:00:57.012345600"),
};
test "TestFormat" {
// try skip();
var tz = try Location.load("US/Pacific");
defer tz.deinit();
var ts = time.unix(0, 1233810057012345600, &tz);
var buf = try std.Buffer.init(std.debug.global_allocator, "");
defer buf.deinit();
for (format_tests) |value| {
try ts.formatBuffer(&buf, value.format);
const got = buf.toSlice();
testing.expect(std.mem.eql(u8, got, value.result));
}
}
test "calendar" {
// try skip();
time.Time.calendar();
}
fn skip() !void {
return error.SkipZigTest;
}
test "TestFormatSingleDigits" {
// try skip();
var buf = &try std.Buffer.init(std.debug.global_allocator, "");
defer buf.deinit();
var tt = time.date(2001, 2, 3, 4, 5, 6, 700000000, &Location.utc_local);
const ts = formatTest.init("single digit format", "3:4:5", "4:5:6");
try tt.formatBuffer(buf, ts.format);
testing.expect(buf.eql(ts.result));
try buf.resize(0);
var stream = &std.io.BufferOutStream.init(buf).stream;
try stream.print("{}", tt);
const want = "2001-02-03 04:05:06.7 +0000 UTC";
testing.expect(buf.eql(want));
}
test "TestFormatShortYear" {
// try skip();
var buf = &try std.Buffer.init(std.debug.global_allocator, "");
defer buf.deinit();
var want = &try std.Buffer.init(std.debug.global_allocator, "");
defer want.deinit();
var stream = &std.io.BufferOutStream.init(want).stream;
const years = [_]isize{
-100001, -100000, -99999,
-10001, -10000, -9999,
-1001, -1000, -999,
-101, -100, -99,
-11, -10, -9,
-1, 0, 1,
9, 10, 11,
99, 100, 101,
999, 1000, 1001,
9999, 10000, 10001,
99999, 100000, 100001,
};
for (years) |y| {
const m = @enumToInt(January);
const x = @intCast(isize, m);
var tt = time.date(y, x, 1, 0, 0, 0, 0, &Location.utc_local);
try buf.resize(0);
try tt.formatBuffer(buf, "2006.01.02");
try want.resize(0);
const day: usize = 1;
const month: usize = 1;
if (y < 0) {
try stream.print("-{d:4}.{d:2}.{d:2}", math.absCast(y), month, day);
} else {
try stream.print("{d:4}.{d:2}.{d:2}", math.absCast(y), month, day);
}
if (!buf.eql(want.toSlice())) {
std.debug.warn("case: {} expected {} got {}\n", y, want.toSlice(), buf.toSlice());
}
}
}
test "TestNextStdChunk" {
const next_std_chunk_tests = [_][]const u8{
"(2006)-(01)-(02)T(15):(04):(05)(Z07:00)",
"(2006)-(01)-(02) (002) (15):(04):(05)",
"(2006)-(01) (002) (15):(04):(05)",
"(2006)-(002) (15):(04):(05)",
"(2006)(002)(01) (15):(04):(05)",
"(2006)(002)(04) (15):(04):(05)",
};
var buf = &try std.Buffer.init(std.debug.global_allocator, "");
defer buf.deinit();
for (next_std_chunk_tests) |marked, i| {
try markChunk(buf, marked);
testing.expect(buf.eql(marked));
}
}
var tmp: [39]u8 = undefined;
fn removeParen(format: []const u8) []const u8 {
var s = tmp[0..format.len];
var i: usize = 0;
var n = i;
while (i < format.len) : (i += 1) {
if (format[i] == '(' or format[i] == ')') {
continue;
}
s[n] = format[i];
n += 1;
}
return s[0..n];
}
fn markChunk(buf: *std.Buffer, format: []const u8) !void {
try buf.resize(0);
var s = removeParen(format);
while (s.len > 0) {
const ch = time.nextStdChunk(s);
try buf.append(ch.prefix);
if (ch.chunk != .none) {
try buf.append("(");
try buf.append(chunName(ch.chunk));
try buf.append(")");
}
s = ch.suffix;
}
}
fn chunName(ch: time.chunk) []const u8 {
return switch (ch) {
.none => "",
.stdLongMonth => "January",
.stdMonth => "Jan",
.stdNumMonth => "1",
.stdZeroMonth => "01",
.stdLongWeekDay => "Monday",
.stdWeekDay => "Mon",
.stdDay => "2",
.stdUnderDay => "_2",
.stdZeroDay => "02",
.stdUnderYearDay => "__2",
.stdZeroYearDay => "002",
.stdHour => "15",
.stdHour12 => "3",
.stdZeroHour12 => "03",
.stdMinute => "4",
.stdZeroMinute => "04",
.stdSecond => "5",
.stdZeroSecond => "05",
.stdLongYear => "2006",
.stdYear => "06",
.stdPM => "PM",
.stdpm => "pm",
.stdTZ => "MST",
.stdISO8601TZ => "Z0700",
.stdISO8601SecondsTZ => "Z070000",
.stdISO8601ShortTZ => "Z07",
.stdISO8601ColonTZ => "Z07:00",
.stdISO8601ColonSecondsTZ => "Z07:00:00",
.stdNumTZ => "-0700",
.stdNumSecondsTz => "-070000",
.stdNumShortTZ => "-07",
.stdNumColonTZ => "-07:00",
.stdNumColonSecondsTZ => "-07:00:00",
else => "unknown",
};
} | src/time/time_test.zig |
const std = @import("std");
const print = std.debug.print;
const util = @import("util.zig");
const gpa = util.gpa;
const data = @embedFile("../data/day13.txt");
const Coord = struct {
x: u32,
y: u32,
};
const Fold = struct {
axis: []const u8,
val: u32,
};
pub fn main() !void {
var split = try util.toStrSlice(data, "\n\n");
var coords = try util.toSliceOf(Coord, split[0], ",");
defer gpa.free(coords);
var folds = try util.toSliceOf(Fold, split[1], "=");
defer gpa.free(folds);
{
var counts = util.Counter(Coord).init(gpa);
defer counts.deinit();
const fold = folds[0];
const axis = fold.axis[fold.axis.len - 1];
for (coords) |*coord| {
if (axis == 'x') {
if (coord.x > fold.val) {
coord.x -= (coord.x - fold.val) * 2;
}
} else {
if (coord.y > fold.val) {
coord.y -= (coord.y - fold.val) * 2;
}
}
}
for (coords) |coord| {
try counts.add(coord);
}
print("{}\n", .{counts.counter.count()});
}
for (folds[1..]) |fold| {
const axis = fold.axis[fold.axis.len - 1];
for (coords) |*coord| {
if (axis == 'x') {
if (coord.x > fold.val) {
coord.x -= (coord.x - fold.val) * 2;
}
} else {
if (coord.y > fold.val) {
coord.y -= (coord.y - fold.val) * 2;
}
}
}
}
var counts = util.Counter(Coord).init(gpa);
defer counts.deinit();
var max_x: u32 = 0;
var max_y: usize = 0;
for (coords) |coord| {
try counts.add(coord);
if (coord.x > max_x) max_x = coord.x;
if (coord.y > max_y) max_y = coord.x;
}
var y: u32 = 0;
while (y <= max_y) : (y += 1) {
var x: u32 = 0;
while (x <= max_x) : (x += 1) {
var s = Coord{ .x = x, .y = y };
if (counts.counter.get(s)) |_| {
print("#", .{});
} else print(".", .{});
}
print("\n", .{});
}
} | 2021/src/day13.zig |
const std = @import("std");
const Fundude = @import("../main.zig");
const Op = @import("Op.zig");
test "DAA add" {
const DAA = [3]u8{ 0x27, 0, 0 };
const OP_ADD_A = 0xC6;
var cpu: Fundude.Cpu = undefined;
var mmu: Fundude.Mmu = undefined;
{
cpu.reg._8.set(.A, 0x0);
_ = cpu.opExecute(&mmu, .{ OP_ADD_A, 0x5, 0 });
std.testing.expectEqual(@as(u8, 0x5), cpu.reg._8.get(.A));
_ = cpu.opExecute(&mmu, DAA);
std.testing.expectEqual(@as(u8, 0x5), cpu.reg._8.get(.A));
}
{
_ = cpu.opExecute(&mmu, .{ OP_ADD_A, 0x9, 0 });
std.testing.expectEqual(@as(u8, 0xE), cpu.reg._8.get(.A));
_ = cpu.opExecute(&mmu, DAA);
std.testing.expectEqual(@as(u8, 0x14), cpu.reg._8.get(.A));
std.testing.expectEqual(@as(u1, 0), cpu.reg.flags.C);
}
{
_ = cpu.opExecute(&mmu, .{ OP_ADD_A, 0x91, 0 });
std.testing.expectEqual(@as(u8, 0xA5), cpu.reg._8.get(.A));
std.testing.expectEqual(@as(u1, 0), cpu.reg.flags.C);
_ = cpu.opExecute(&mmu, DAA);
std.testing.expectEqual(@as(u8, 0x05), cpu.reg._8.get(.A));
std.testing.expectEqual(@as(u1, 1), cpu.reg.flags.C);
}
}
test "DAA sub" {
const DAA = [3]u8{ 0x27, 0, 0 };
const OP_SUB_A = 0xD6;
var cpu: Fundude.Cpu = undefined;
var mmu: Fundude.Mmu = undefined;
{
cpu.reg._8.set(.A, 0x45);
_ = cpu.opExecute(&mmu, .{ OP_SUB_A, 0x2, 0 });
std.testing.expectEqual(@as(u8, 0x43), cpu.reg._8.get(.A));
_ = cpu.opExecute(&mmu, DAA);
std.testing.expectEqual(@as(u8, 0x43), cpu.reg._8.get(.A));
}
{
_ = cpu.opExecute(&mmu, .{ OP_SUB_A, 0x5, 0 });
std.testing.expectEqual(@as(u8, 0x3E), cpu.reg._8.get(.A));
_ = cpu.opExecute(&mmu, DAA);
std.testing.expectEqual(@as(u8, 0x38), cpu.reg._8.get(.A));
std.testing.expectEqual(@as(u1, 0), cpu.reg.flags.C);
}
{
_ = cpu.opExecute(&mmu, .{ OP_SUB_A, 0x91, 0 });
std.testing.expectEqual(@as(u8, 0xA7), cpu.reg._8.get(.A));
std.testing.expectEqual(@as(u1, 1), cpu.reg.flags.C);
_ = cpu.opExecute(&mmu, DAA);
std.testing.expectEqual(@as(u8, 0x47), cpu.reg._8.get(.A));
std.testing.expectEqual(@as(u1, 1), cpu.reg.flags.C);
}
}
fn testDaa(
before_a: u8,
before_flags: Fundude.Cpu.Flags,
after_a: u8,
after_flags: Fundude.Cpu.Flags,
) !void {
var cpu: Fundude.Cpu = undefined;
var mmu: Fundude.Mmu = undefined;
const DAA = [3]u8{ 0x27, 0, 0 };
cpu.reg._8.set(.A, before_a);
cpu.reg.flags = before_flags;
_ = cpu.opExecute(&mmu, DAA);
std.testing.expectEqual(after_a, cpu.reg._8.get(.A));
std.testing.expectEqual(after_flags.Z, cpu.reg.flags.Z);
std.testing.expectEqual(after_flags.N, cpu.reg.flags.N);
std.testing.expectEqual(after_flags.H, cpu.reg.flags.H);
std.testing.expectEqual(after_flags.C, cpu.reg.flags.C);
}
fn f(raw: u4) Fundude.Cpu.Flags {
return .{
.Z = (raw >> 3) & 1 == 1,
.N = (raw >> 2) & 1 == 1,
.H = @truncate(u1, raw >> 1),
.C = @truncate(u1, raw >> 0),
};
}
test "gekkio" {
try testDaa(0x00, f(0b0000), 0x00, f(0b1000));
try testDaa(0x00, f(0b0001), 0x60, f(0b0001));
try testDaa(0x00, f(0b0010), 0x06, f(0b0000));
try testDaa(0x00, f(0b0011), 0x66, f(0b0001));
try testDaa(0x00, f(0b0100), 0x00, f(0b1100));
try testDaa(0x00, f(0b0101), 0xa0, f(0b0101));
try testDaa(0x00, f(0b0110), 0xfa, f(0b0100));
try testDaa(0x00, f(0b0111), 0x9a, f(0b0101));
try testDaa(0x00, f(0b1000), 0x00, f(0b1000));
try testDaa(0x00, f(0b1001), 0x60, f(0b0001));
try testDaa(0x00, f(0b1010), 0x06, f(0b0000));
try testDaa(0x00, f(0b1011), 0x66, f(0b0001));
try testDaa(0x00, f(0b1100), 0x00, f(0b1100));
try testDaa(0x00, f(0b1101), 0xa0, f(0b0101));
try testDaa(0x00, f(0b1110), 0xfa, f(0b0100));
try testDaa(0x00, f(0b1111), 0x9a, f(0b0101));
try testDaa(0x01, f(0b0000), 0x01, f(0b0000));
try testDaa(0x01, f(0b0001), 0x61, f(0b0001));
try testDaa(0x01, f(0b0010), 0x07, f(0b0000));
try testDaa(0x01, f(0b0011), 0x67, f(0b0001));
try testDaa(0x01, f(0b0100), 0x01, f(0b0100));
try testDaa(0x01, f(0b0101), 0xa1, f(0b0101));
try testDaa(0x01, f(0b0110), 0xfb, f(0b0100));
try testDaa(0x01, f(0b0111), 0x9b, f(0b0101));
try testDaa(0x01, f(0b1000), 0x01, f(0b0000));
try testDaa(0x01, f(0b1001), 0x61, f(0b0001));
try testDaa(0x01, f(0b1010), 0x07, f(0b0000));
try testDaa(0x01, f(0b1011), 0x67, f(0b0001));
try testDaa(0x01, f(0b1100), 0x01, f(0b0100));
try testDaa(0x01, f(0b1101), 0xa1, f(0b0101));
try testDaa(0x01, f(0b1110), 0xfb, f(0b0100));
try testDaa(0x01, f(0b1111), 0x9b, f(0b0101));
try testDaa(0x02, f(0b0000), 0x02, f(0b0000));
try testDaa(0x02, f(0b0001), 0x62, f(0b0001));
try testDaa(0x02, f(0b0010), 0x08, f(0b0000));
try testDaa(0x02, f(0b0011), 0x68, f(0b0001));
try testDaa(0x02, f(0b0100), 0x02, f(0b0100));
try testDaa(0x02, f(0b0101), 0xa2, f(0b0101));
try testDaa(0x02, f(0b0110), 0xfc, f(0b0100));
try testDaa(0x02, f(0b0111), 0x9c, f(0b0101));
try testDaa(0x02, f(0b1000), 0x02, f(0b0000));
try testDaa(0x02, f(0b1001), 0x62, f(0b0001));
try testDaa(0x02, f(0b1010), 0x08, f(0b0000));
try testDaa(0x02, f(0b1011), 0x68, f(0b0001));
try testDaa(0x02, f(0b1100), 0x02, f(0b0100));
try testDaa(0x02, f(0b1101), 0xa2, f(0b0101));
try testDaa(0x02, f(0b1110), 0xfc, f(0b0100));
try testDaa(0x02, f(0b1111), 0x9c, f(0b0101));
try testDaa(0x03, f(0b0000), 0x03, f(0b0000));
try testDaa(0x03, f(0b0001), 0x63, f(0b0001));
try testDaa(0x03, f(0b0010), 0x09, f(0b0000));
try testDaa(0x03, f(0b0011), 0x69, f(0b0001));
try testDaa(0x03, f(0b0100), 0x03, f(0b0100));
try testDaa(0x03, f(0b0101), 0xa3, f(0b0101));
try testDaa(0x03, f(0b0110), 0xfd, f(0b0100));
try testDaa(0x03, f(0b0111), 0x9d, f(0b0101));
try testDaa(0x03, f(0b1000), 0x03, f(0b0000));
try testDaa(0x03, f(0b1001), 0x63, f(0b0001));
try testDaa(0x03, f(0b1010), 0x09, f(0b0000));
try testDaa(0x03, f(0b1011), 0x69, f(0b0001));
try testDaa(0x03, f(0b1100), 0x03, f(0b0100));
try testDaa(0x03, f(0b1101), 0xa3, f(0b0101));
try testDaa(0x03, f(0b1110), 0xfd, f(0b0100));
try testDaa(0x03, f(0b1111), 0x9d, f(0b0101));
try testDaa(0x04, f(0b0000), 0x04, f(0b0000));
try testDaa(0x04, f(0b0001), 0x64, f(0b0001));
try testDaa(0x04, f(0b0010), 0x0a, f(0b0000));
try testDaa(0x04, f(0b0011), 0x6a, f(0b0001));
try testDaa(0x04, f(0b0100), 0x04, f(0b0100));
try testDaa(0x04, f(0b0101), 0xa4, f(0b0101));
try testDaa(0x04, f(0b0110), 0xfe, f(0b0100));
try testDaa(0x04, f(0b0111), 0x9e, f(0b0101));
try testDaa(0x04, f(0b1000), 0x04, f(0b0000));
try testDaa(0x04, f(0b1001), 0x64, f(0b0001));
try testDaa(0x04, f(0b1010), 0x0a, f(0b0000));
try testDaa(0x04, f(0b1011), 0x6a, f(0b0001));
try testDaa(0x04, f(0b1100), 0x04, f(0b0100));
try testDaa(0x04, f(0b1101), 0xa4, f(0b0101));
try testDaa(0x04, f(0b1110), 0xfe, f(0b0100));
try testDaa(0x04, f(0b1111), 0x9e, f(0b0101));
try testDaa(0x05, f(0b0000), 0x05, f(0b0000));
try testDaa(0x05, f(0b0001), 0x65, f(0b0001));
try testDaa(0x05, f(0b0010), 0x0b, f(0b0000));
try testDaa(0x05, f(0b0011), 0x6b, f(0b0001));
try testDaa(0x05, f(0b0100), 0x05, f(0b0100));
try testDaa(0x05, f(0b0101), 0xa5, f(0b0101));
try testDaa(0x05, f(0b0110), 0xff, f(0b0100));
try testDaa(0x05, f(0b0111), 0x9f, f(0b0101));
try testDaa(0x05, f(0b1000), 0x05, f(0b0000));
try testDaa(0x05, f(0b1001), 0x65, f(0b0001));
try testDaa(0x05, f(0b1010), 0x0b, f(0b0000));
try testDaa(0x05, f(0b1011), 0x6b, f(0b0001));
try testDaa(0x05, f(0b1100), 0x05, f(0b0100));
try testDaa(0x05, f(0b1101), 0xa5, f(0b0101));
try testDaa(0x05, f(0b1110), 0xff, f(0b0100));
try testDaa(0x05, f(0b1111), 0x9f, f(0b0101));
try testDaa(0x06, f(0b0000), 0x06, f(0b0000));
try testDaa(0x06, f(0b0001), 0x66, f(0b0001));
try testDaa(0x06, f(0b0010), 0x0c, f(0b0000));
try testDaa(0x06, f(0b0011), 0x6c, f(0b0001));
try testDaa(0x06, f(0b0100), 0x06, f(0b0100));
try testDaa(0x06, f(0b0101), 0xa6, f(0b0101));
try testDaa(0x06, f(0b0110), 0x00, f(0b1100));
try testDaa(0x06, f(0b0111), 0xa0, f(0b0101));
try testDaa(0x06, f(0b1000), 0x06, f(0b0000));
try testDaa(0x06, f(0b1001), 0x66, f(0b0001));
try testDaa(0x06, f(0b1010), 0x0c, f(0b0000));
try testDaa(0x06, f(0b1011), 0x6c, f(0b0001));
try testDaa(0x06, f(0b1100), 0x06, f(0b0100));
try testDaa(0x06, f(0b1101), 0xa6, f(0b0101));
try testDaa(0x06, f(0b1110), 0x00, f(0b1100));
try testDaa(0x06, f(0b1111), 0xa0, f(0b0101));
try testDaa(0x07, f(0b0000), 0x07, f(0b0000));
try testDaa(0x07, f(0b0001), 0x67, f(0b0001));
try testDaa(0x07, f(0b0010), 0x0d, f(0b0000));
try testDaa(0x07, f(0b0011), 0x6d, f(0b0001));
try testDaa(0x07, f(0b0100), 0x07, f(0b0100));
try testDaa(0x07, f(0b0101), 0xa7, f(0b0101));
try testDaa(0x07, f(0b0110), 0x01, f(0b0100));
try testDaa(0x07, f(0b0111), 0xa1, f(0b0101));
try testDaa(0x07, f(0b1000), 0x07, f(0b0000));
try testDaa(0x07, f(0b1001), 0x67, f(0b0001));
try testDaa(0x07, f(0b1010), 0x0d, f(0b0000));
try testDaa(0x07, f(0b1011), 0x6d, f(0b0001));
try testDaa(0x07, f(0b1100), 0x07, f(0b0100));
try testDaa(0x07, f(0b1101), 0xa7, f(0b0101));
try testDaa(0x07, f(0b1110), 0x01, f(0b0100));
try testDaa(0x07, f(0b1111), 0xa1, f(0b0101));
try testDaa(0x08, f(0b0000), 0x08, f(0b0000));
try testDaa(0x08, f(0b0001), 0x68, f(0b0001));
try testDaa(0x08, f(0b0010), 0x0e, f(0b0000));
try testDaa(0x08, f(0b0011), 0x6e, f(0b0001));
try testDaa(0x08, f(0b0100), 0x08, f(0b0100));
try testDaa(0x08, f(0b0101), 0xa8, f(0b0101));
try testDaa(0x08, f(0b0110), 0x02, f(0b0100));
try testDaa(0x08, f(0b0111), 0xa2, f(0b0101));
try testDaa(0x08, f(0b1000), 0x08, f(0b0000));
try testDaa(0x08, f(0b1001), 0x68, f(0b0001));
try testDaa(0x08, f(0b1010), 0x0e, f(0b0000));
try testDaa(0x08, f(0b1011), 0x6e, f(0b0001));
try testDaa(0x08, f(0b1100), 0x08, f(0b0100));
try testDaa(0x08, f(0b1101), 0xa8, f(0b0101));
try testDaa(0x08, f(0b1110), 0x02, f(0b0100));
try testDaa(0x08, f(0b1111), 0xa2, f(0b0101));
try testDaa(0x09, f(0b0000), 0x09, f(0b0000));
try testDaa(0x09, f(0b0001), 0x69, f(0b0001));
try testDaa(0x09, f(0b0010), 0x0f, f(0b0000));
try testDaa(0x09, f(0b0011), 0x6f, f(0b0001));
try testDaa(0x09, f(0b0100), 0x09, f(0b0100));
try testDaa(0x09, f(0b0101), 0xa9, f(0b0101));
try testDaa(0x09, f(0b0110), 0x03, f(0b0100));
try testDaa(0x09, f(0b0111), 0xa3, f(0b0101));
try testDaa(0x09, f(0b1000), 0x09, f(0b0000));
try testDaa(0x09, f(0b1001), 0x69, f(0b0001));
try testDaa(0x09, f(0b1010), 0x0f, f(0b0000));
try testDaa(0x09, f(0b1011), 0x6f, f(0b0001));
try testDaa(0x09, f(0b1100), 0x09, f(0b0100));
try testDaa(0x09, f(0b1101), 0xa9, f(0b0101));
try testDaa(0x09, f(0b1110), 0x03, f(0b0100));
try testDaa(0x09, f(0b1111), 0xa3, f(0b0101));
try testDaa(0x0a, f(0b0000), 0x10, f(0b0000));
try testDaa(0x0a, f(0b0001), 0x70, f(0b0001));
try testDaa(0x0a, f(0b0010), 0x10, f(0b0000));
try testDaa(0x0a, f(0b0011), 0x70, f(0b0001));
try testDaa(0x0a, f(0b0100), 0x0a, f(0b0100));
try testDaa(0x0a, f(0b0101), 0xaa, f(0b0101));
try testDaa(0x0a, f(0b0110), 0x04, f(0b0100));
try testDaa(0x0a, f(0b0111), 0xa4, f(0b0101));
try testDaa(0x0a, f(0b1000), 0x10, f(0b0000));
try testDaa(0x0a, f(0b1001), 0x70, f(0b0001));
try testDaa(0x0a, f(0b1010), 0x10, f(0b0000));
try testDaa(0x0a, f(0b1011), 0x70, f(0b0001));
try testDaa(0x0a, f(0b1100), 0x0a, f(0b0100));
try testDaa(0x0a, f(0b1101), 0xaa, f(0b0101));
try testDaa(0x0a, f(0b1110), 0x04, f(0b0100));
try testDaa(0x0a, f(0b1111), 0xa4, f(0b0101));
try testDaa(0x0b, f(0b0000), 0x11, f(0b0000));
try testDaa(0x0b, f(0b0001), 0x71, f(0b0001));
try testDaa(0x0b, f(0b0010), 0x11, f(0b0000));
try testDaa(0x0b, f(0b0011), 0x71, f(0b0001));
try testDaa(0x0b, f(0b0100), 0x0b, f(0b0100));
try testDaa(0x0b, f(0b0101), 0xab, f(0b0101));
try testDaa(0x0b, f(0b0110), 0x05, f(0b0100));
try testDaa(0x0b, f(0b0111), 0xa5, f(0b0101));
try testDaa(0x0b, f(0b1000), 0x11, f(0b0000));
try testDaa(0x0b, f(0b1001), 0x71, f(0b0001));
try testDaa(0x0b, f(0b1010), 0x11, f(0b0000));
try testDaa(0x0b, f(0b1011), 0x71, f(0b0001));
try testDaa(0x0b, f(0b1100), 0x0b, f(0b0100));
try testDaa(0x0b, f(0b1101), 0xab, f(0b0101));
try testDaa(0x0b, f(0b1110), 0x05, f(0b0100));
try testDaa(0x0b, f(0b1111), 0xa5, f(0b0101));
try testDaa(0x0c, f(0b0000), 0x12, f(0b0000));
try testDaa(0x0c, f(0b0001), 0x72, f(0b0001));
try testDaa(0x0c, f(0b0010), 0x12, f(0b0000));
try testDaa(0x0c, f(0b0011), 0x72, f(0b0001));
try testDaa(0x0c, f(0b0100), 0x0c, f(0b0100));
try testDaa(0x0c, f(0b0101), 0xac, f(0b0101));
try testDaa(0x0c, f(0b0110), 0x06, f(0b0100));
try testDaa(0x0c, f(0b0111), 0xa6, f(0b0101));
try testDaa(0x0c, f(0b1000), 0x12, f(0b0000));
try testDaa(0x0c, f(0b1001), 0x72, f(0b0001));
try testDaa(0x0c, f(0b1010), 0x12, f(0b0000));
try testDaa(0x0c, f(0b1011), 0x72, f(0b0001));
try testDaa(0x0c, f(0b1100), 0x0c, f(0b0100));
try testDaa(0x0c, f(0b1101), 0xac, f(0b0101));
try testDaa(0x0c, f(0b1110), 0x06, f(0b0100));
try testDaa(0x0c, f(0b1111), 0xa6, f(0b0101));
try testDaa(0x0d, f(0b0000), 0x13, f(0b0000));
try testDaa(0x0d, f(0b0001), 0x73, f(0b0001));
try testDaa(0x0d, f(0b0010), 0x13, f(0b0000));
try testDaa(0x0d, f(0b0011), 0x73, f(0b0001));
try testDaa(0x0d, f(0b0100), 0x0d, f(0b0100));
try testDaa(0x0d, f(0b0101), 0xad, f(0b0101));
try testDaa(0x0d, f(0b0110), 0x07, f(0b0100));
try testDaa(0x0d, f(0b0111), 0xa7, f(0b0101));
try testDaa(0x0d, f(0b1000), 0x13, f(0b0000));
try testDaa(0x0d, f(0b1001), 0x73, f(0b0001));
try testDaa(0x0d, f(0b1010), 0x13, f(0b0000));
try testDaa(0x0d, f(0b1011), 0x73, f(0b0001));
try testDaa(0x0d, f(0b1100), 0x0d, f(0b0100));
try testDaa(0x0d, f(0b1101), 0xad, f(0b0101));
try testDaa(0x0d, f(0b1110), 0x07, f(0b0100));
try testDaa(0x0d, f(0b1111), 0xa7, f(0b0101));
try testDaa(0x0e, f(0b0000), 0x14, f(0b0000));
try testDaa(0x0e, f(0b0001), 0x74, f(0b0001));
try testDaa(0x0e, f(0b0010), 0x14, f(0b0000));
try testDaa(0x0e, f(0b0011), 0x74, f(0b0001));
try testDaa(0x0e, f(0b0100), 0x0e, f(0b0100));
try testDaa(0x0e, f(0b0101), 0xae, f(0b0101));
try testDaa(0x0e, f(0b0110), 0x08, f(0b0100));
try testDaa(0x0e, f(0b0111), 0xa8, f(0b0101));
try testDaa(0x0e, f(0b1000), 0x14, f(0b0000));
try testDaa(0x0e, f(0b1001), 0x74, f(0b0001));
try testDaa(0x0e, f(0b1010), 0x14, f(0b0000));
try testDaa(0x0e, f(0b1011), 0x74, f(0b0001));
try testDaa(0x0e, f(0b1100), 0x0e, f(0b0100));
try testDaa(0x0e, f(0b1101), 0xae, f(0b0101));
try testDaa(0x0e, f(0b1110), 0x08, f(0b0100));
try testDaa(0x0e, f(0b1111), 0xa8, f(0b0101));
try testDaa(0x0f, f(0b0000), 0x15, f(0b0000));
try testDaa(0x0f, f(0b0001), 0x75, f(0b0001));
try testDaa(0x0f, f(0b0010), 0x15, f(0b0000));
try testDaa(0x0f, f(0b0011), 0x75, f(0b0001));
try testDaa(0x0f, f(0b0100), 0x0f, f(0b0100));
try testDaa(0x0f, f(0b0101), 0xaf, f(0b0101));
try testDaa(0x0f, f(0b0110), 0x09, f(0b0100));
try testDaa(0x0f, f(0b0111), 0xa9, f(0b0101));
try testDaa(0x0f, f(0b1000), 0x15, f(0b0000));
try testDaa(0x0f, f(0b1001), 0x75, f(0b0001));
try testDaa(0x0f, f(0b1010), 0x15, f(0b0000));
try testDaa(0x0f, f(0b1011), 0x75, f(0b0001));
try testDaa(0x0f, f(0b1100), 0x0f, f(0b0100));
try testDaa(0x0f, f(0b1101), 0xaf, f(0b0101));
try testDaa(0x0f, f(0b1110), 0x09, f(0b0100));
try testDaa(0x0f, f(0b1111), 0xa9, f(0b0101));
try testDaa(0x10, f(0b0000), 0x10, f(0b0000));
try testDaa(0x10, f(0b0001), 0x70, f(0b0001));
try testDaa(0x10, f(0b0010), 0x16, f(0b0000));
try testDaa(0x10, f(0b0011), 0x76, f(0b0001));
try testDaa(0x10, f(0b0100), 0x10, f(0b0100));
try testDaa(0x10, f(0b0101), 0xb0, f(0b0101));
try testDaa(0x10, f(0b0110), 0x0a, f(0b0100));
try testDaa(0x10, f(0b0111), 0xaa, f(0b0101));
try testDaa(0x10, f(0b1000), 0x10, f(0b0000));
try testDaa(0x10, f(0b1001), 0x70, f(0b0001));
try testDaa(0x10, f(0b1010), 0x16, f(0b0000));
try testDaa(0x10, f(0b1011), 0x76, f(0b0001));
try testDaa(0x10, f(0b1100), 0x10, f(0b0100));
try testDaa(0x10, f(0b1101), 0xb0, f(0b0101));
try testDaa(0x10, f(0b1110), 0x0a, f(0b0100));
try testDaa(0x10, f(0b1111), 0xaa, f(0b0101));
try testDaa(0x11, f(0b0000), 0x11, f(0b0000));
try testDaa(0x11, f(0b0001), 0x71, f(0b0001));
try testDaa(0x11, f(0b0010), 0x17, f(0b0000));
try testDaa(0x11, f(0b0011), 0x77, f(0b0001));
try testDaa(0x11, f(0b0100), 0x11, f(0b0100));
try testDaa(0x11, f(0b0101), 0xb1, f(0b0101));
try testDaa(0x11, f(0b0110), 0x0b, f(0b0100));
try testDaa(0x11, f(0b0111), 0xab, f(0b0101));
try testDaa(0x11, f(0b1000), 0x11, f(0b0000));
try testDaa(0x11, f(0b1001), 0x71, f(0b0001));
try testDaa(0x11, f(0b1010), 0x17, f(0b0000));
try testDaa(0x11, f(0b1011), 0x77, f(0b0001));
try testDaa(0x11, f(0b1100), 0x11, f(0b0100));
try testDaa(0x11, f(0b1101), 0xb1, f(0b0101));
try testDaa(0x11, f(0b1110), 0x0b, f(0b0100));
try testDaa(0x11, f(0b1111), 0xab, f(0b0101));
try testDaa(0x12, f(0b0000), 0x12, f(0b0000));
try testDaa(0x12, f(0b0001), 0x72, f(0b0001));
try testDaa(0x12, f(0b0010), 0x18, f(0b0000));
try testDaa(0x12, f(0b0011), 0x78, f(0b0001));
try testDaa(0x12, f(0b0100), 0x12, f(0b0100));
try testDaa(0x12, f(0b0101), 0xb2, f(0b0101));
try testDaa(0x12, f(0b0110), 0x0c, f(0b0100));
try testDaa(0x12, f(0b0111), 0xac, f(0b0101));
try testDaa(0x12, f(0b1000), 0x12, f(0b0000));
try testDaa(0x12, f(0b1001), 0x72, f(0b0001));
try testDaa(0x12, f(0b1010), 0x18, f(0b0000));
try testDaa(0x12, f(0b1011), 0x78, f(0b0001));
try testDaa(0x12, f(0b1100), 0x12, f(0b0100));
try testDaa(0x12, f(0b1101), 0xb2, f(0b0101));
try testDaa(0x12, f(0b1110), 0x0c, f(0b0100));
try testDaa(0x12, f(0b1111), 0xac, f(0b0101));
try testDaa(0x13, f(0b0000), 0x13, f(0b0000));
try testDaa(0x13, f(0b0001), 0x73, f(0b0001));
try testDaa(0x13, f(0b0010), 0x19, f(0b0000));
try testDaa(0x13, f(0b0011), 0x79, f(0b0001));
try testDaa(0x13, f(0b0100), 0x13, f(0b0100));
try testDaa(0x13, f(0b0101), 0xb3, f(0b0101));
try testDaa(0x13, f(0b0110), 0x0d, f(0b0100));
try testDaa(0x13, f(0b0111), 0xad, f(0b0101));
try testDaa(0x13, f(0b1000), 0x13, f(0b0000));
try testDaa(0x13, f(0b1001), 0x73, f(0b0001));
try testDaa(0x13, f(0b1010), 0x19, f(0b0000));
try testDaa(0x13, f(0b1011), 0x79, f(0b0001));
try testDaa(0x13, f(0b1100), 0x13, f(0b0100));
try testDaa(0x13, f(0b1101), 0xb3, f(0b0101));
try testDaa(0x13, f(0b1110), 0x0d, f(0b0100));
try testDaa(0x13, f(0b1111), 0xad, f(0b0101));
try testDaa(0x14, f(0b0000), 0x14, f(0b0000));
try testDaa(0x14, f(0b0001), 0x74, f(0b0001));
try testDaa(0x14, f(0b0010), 0x1a, f(0b0000));
try testDaa(0x14, f(0b0011), 0x7a, f(0b0001));
try testDaa(0x14, f(0b0100), 0x14, f(0b0100));
try testDaa(0x14, f(0b0101), 0xb4, f(0b0101));
try testDaa(0x14, f(0b0110), 0x0e, f(0b0100));
try testDaa(0x14, f(0b0111), 0xae, f(0b0101));
try testDaa(0x14, f(0b1000), 0x14, f(0b0000));
try testDaa(0x14, f(0b1001), 0x74, f(0b0001));
try testDaa(0x14, f(0b1010), 0x1a, f(0b0000));
try testDaa(0x14, f(0b1011), 0x7a, f(0b0001));
try testDaa(0x14, f(0b1100), 0x14, f(0b0100));
try testDaa(0x14, f(0b1101), 0xb4, f(0b0101));
try testDaa(0x14, f(0b1110), 0x0e, f(0b0100));
try testDaa(0x14, f(0b1111), 0xae, f(0b0101));
try testDaa(0x15, f(0b0000), 0x15, f(0b0000));
try testDaa(0x15, f(0b0001), 0x75, f(0b0001));
try testDaa(0x15, f(0b0010), 0x1b, f(0b0000));
try testDaa(0x15, f(0b0011), 0x7b, f(0b0001));
try testDaa(0x15, f(0b0100), 0x15, f(0b0100));
try testDaa(0x15, f(0b0101), 0xb5, f(0b0101));
try testDaa(0x15, f(0b0110), 0x0f, f(0b0100));
try testDaa(0x15, f(0b0111), 0xaf, f(0b0101));
try testDaa(0x15, f(0b1000), 0x15, f(0b0000));
try testDaa(0x15, f(0b1001), 0x75, f(0b0001));
try testDaa(0x15, f(0b1010), 0x1b, f(0b0000));
try testDaa(0x15, f(0b1011), 0x7b, f(0b0001));
try testDaa(0x15, f(0b1100), 0x15, f(0b0100));
try testDaa(0x15, f(0b1101), 0xb5, f(0b0101));
try testDaa(0x15, f(0b1110), 0x0f, f(0b0100));
try testDaa(0x15, f(0b1111), 0xaf, f(0b0101));
try testDaa(0x16, f(0b0000), 0x16, f(0b0000));
try testDaa(0x16, f(0b0001), 0x76, f(0b0001));
try testDaa(0x16, f(0b0010), 0x1c, f(0b0000));
try testDaa(0x16, f(0b0011), 0x7c, f(0b0001));
try testDaa(0x16, f(0b0100), 0x16, f(0b0100));
try testDaa(0x16, f(0b0101), 0xb6, f(0b0101));
try testDaa(0x16, f(0b0110), 0x10, f(0b0100));
try testDaa(0x16, f(0b0111), 0xb0, f(0b0101));
try testDaa(0x16, f(0b1000), 0x16, f(0b0000));
try testDaa(0x16, f(0b1001), 0x76, f(0b0001));
try testDaa(0x16, f(0b1010), 0x1c, f(0b0000));
try testDaa(0x16, f(0b1011), 0x7c, f(0b0001));
try testDaa(0x16, f(0b1100), 0x16, f(0b0100));
try testDaa(0x16, f(0b1101), 0xb6, f(0b0101));
try testDaa(0x16, f(0b1110), 0x10, f(0b0100));
try testDaa(0x16, f(0b1111), 0xb0, f(0b0101));
try testDaa(0x17, f(0b0000), 0x17, f(0b0000));
try testDaa(0x17, f(0b0001), 0x77, f(0b0001));
try testDaa(0x17, f(0b0010), 0x1d, f(0b0000));
try testDaa(0x17, f(0b0011), 0x7d, f(0b0001));
try testDaa(0x17, f(0b0100), 0x17, f(0b0100));
try testDaa(0x17, f(0b0101), 0xb7, f(0b0101));
try testDaa(0x17, f(0b0110), 0x11, f(0b0100));
try testDaa(0x17, f(0b0111), 0xb1, f(0b0101));
try testDaa(0x17, f(0b1000), 0x17, f(0b0000));
try testDaa(0x17, f(0b1001), 0x77, f(0b0001));
try testDaa(0x17, f(0b1010), 0x1d, f(0b0000));
try testDaa(0x17, f(0b1011), 0x7d, f(0b0001));
try testDaa(0x17, f(0b1100), 0x17, f(0b0100));
try testDaa(0x17, f(0b1101), 0xb7, f(0b0101));
try testDaa(0x17, f(0b1110), 0x11, f(0b0100));
try testDaa(0x17, f(0b1111), 0xb1, f(0b0101));
try testDaa(0x18, f(0b0000), 0x18, f(0b0000));
try testDaa(0x18, f(0b0001), 0x78, f(0b0001));
try testDaa(0x18, f(0b0010), 0x1e, f(0b0000));
try testDaa(0x18, f(0b0011), 0x7e, f(0b0001));
try testDaa(0x18, f(0b0100), 0x18, f(0b0100));
try testDaa(0x18, f(0b0101), 0xb8, f(0b0101));
try testDaa(0x18, f(0b0110), 0x12, f(0b0100));
try testDaa(0x18, f(0b0111), 0xb2, f(0b0101));
try testDaa(0x18, f(0b1000), 0x18, f(0b0000));
try testDaa(0x18, f(0b1001), 0x78, f(0b0001));
try testDaa(0x18, f(0b1010), 0x1e, f(0b0000));
try testDaa(0x18, f(0b1011), 0x7e, f(0b0001));
try testDaa(0x18, f(0b1100), 0x18, f(0b0100));
try testDaa(0x18, f(0b1101), 0xb8, f(0b0101));
try testDaa(0x18, f(0b1110), 0x12, f(0b0100));
try testDaa(0x18, f(0b1111), 0xb2, f(0b0101));
try testDaa(0x19, f(0b0000), 0x19, f(0b0000));
try testDaa(0x19, f(0b0001), 0x79, f(0b0001));
try testDaa(0x19, f(0b0010), 0x1f, f(0b0000));
try testDaa(0x19, f(0b0011), 0x7f, f(0b0001));
try testDaa(0x19, f(0b0100), 0x19, f(0b0100));
try testDaa(0x19, f(0b0101), 0xb9, f(0b0101));
try testDaa(0x19, f(0b0110), 0x13, f(0b0100));
try testDaa(0x19, f(0b0111), 0xb3, f(0b0101));
try testDaa(0x19, f(0b1000), 0x19, f(0b0000));
try testDaa(0x19, f(0b1001), 0x79, f(0b0001));
try testDaa(0x19, f(0b1010), 0x1f, f(0b0000));
try testDaa(0x19, f(0b1011), 0x7f, f(0b0001));
try testDaa(0x19, f(0b1100), 0x19, f(0b0100));
try testDaa(0x19, f(0b1101), 0xb9, f(0b0101));
try testDaa(0x19, f(0b1110), 0x13, f(0b0100));
try testDaa(0x19, f(0b1111), 0xb3, f(0b0101));
try testDaa(0x1a, f(0b0000), 0x20, f(0b0000));
try testDaa(0x1a, f(0b0001), 0x80, f(0b0001));
try testDaa(0x1a, f(0b0010), 0x20, f(0b0000));
try testDaa(0x1a, f(0b0011), 0x80, f(0b0001));
try testDaa(0x1a, f(0b0100), 0x1a, f(0b0100));
try testDaa(0x1a, f(0b0101), 0xba, f(0b0101));
try testDaa(0x1a, f(0b0110), 0x14, f(0b0100));
try testDaa(0x1a, f(0b0111), 0xb4, f(0b0101));
try testDaa(0x1a, f(0b1000), 0x20, f(0b0000));
try testDaa(0x1a, f(0b1001), 0x80, f(0b0001));
try testDaa(0x1a, f(0b1010), 0x20, f(0b0000));
try testDaa(0x1a, f(0b1011), 0x80, f(0b0001));
try testDaa(0x1a, f(0b1100), 0x1a, f(0b0100));
try testDaa(0x1a, f(0b1101), 0xba, f(0b0101));
try testDaa(0x1a, f(0b1110), 0x14, f(0b0100));
try testDaa(0x1a, f(0b1111), 0xb4, f(0b0101));
try testDaa(0x1b, f(0b0000), 0x21, f(0b0000));
try testDaa(0x1b, f(0b0001), 0x81, f(0b0001));
try testDaa(0x1b, f(0b0010), 0x21, f(0b0000));
try testDaa(0x1b, f(0b0011), 0x81, f(0b0001));
try testDaa(0x1b, f(0b0100), 0x1b, f(0b0100));
try testDaa(0x1b, f(0b0101), 0xbb, f(0b0101));
try testDaa(0x1b, f(0b0110), 0x15, f(0b0100));
try testDaa(0x1b, f(0b0111), 0xb5, f(0b0101));
try testDaa(0x1b, f(0b1000), 0x21, f(0b0000));
try testDaa(0x1b, f(0b1001), 0x81, f(0b0001));
try testDaa(0x1b, f(0b1010), 0x21, f(0b0000));
try testDaa(0x1b, f(0b1011), 0x81, f(0b0001));
try testDaa(0x1b, f(0b1100), 0x1b, f(0b0100));
try testDaa(0x1b, f(0b1101), 0xbb, f(0b0101));
try testDaa(0x1b, f(0b1110), 0x15, f(0b0100));
try testDaa(0x1b, f(0b1111), 0xb5, f(0b0101));
try testDaa(0x1c, f(0b0000), 0x22, f(0b0000));
try testDaa(0x1c, f(0b0001), 0x82, f(0b0001));
try testDaa(0x1c, f(0b0010), 0x22, f(0b0000));
try testDaa(0x1c, f(0b0011), 0x82, f(0b0001));
try testDaa(0x1c, f(0b0100), 0x1c, f(0b0100));
try testDaa(0x1c, f(0b0101), 0xbc, f(0b0101));
try testDaa(0x1c, f(0b0110), 0x16, f(0b0100));
try testDaa(0x1c, f(0b0111), 0xb6, f(0b0101));
try testDaa(0x1c, f(0b1000), 0x22, f(0b0000));
try testDaa(0x1c, f(0b1001), 0x82, f(0b0001));
try testDaa(0x1c, f(0b1010), 0x22, f(0b0000));
try testDaa(0x1c, f(0b1011), 0x82, f(0b0001));
try testDaa(0x1c, f(0b1100), 0x1c, f(0b0100));
try testDaa(0x1c, f(0b1101), 0xbc, f(0b0101));
try testDaa(0x1c, f(0b1110), 0x16, f(0b0100));
try testDaa(0x1c, f(0b1111), 0xb6, f(0b0101));
try testDaa(0x1d, f(0b0000), 0x23, f(0b0000));
try testDaa(0x1d, f(0b0001), 0x83, f(0b0001));
try testDaa(0x1d, f(0b0010), 0x23, f(0b0000));
try testDaa(0x1d, f(0b0011), 0x83, f(0b0001));
try testDaa(0x1d, f(0b0100), 0x1d, f(0b0100));
try testDaa(0x1d, f(0b0101), 0xbd, f(0b0101));
try testDaa(0x1d, f(0b0110), 0x17, f(0b0100));
try testDaa(0x1d, f(0b0111), 0xb7, f(0b0101));
try testDaa(0x1d, f(0b1000), 0x23, f(0b0000));
try testDaa(0x1d, f(0b1001), 0x83, f(0b0001));
try testDaa(0x1d, f(0b1010), 0x23, f(0b0000));
try testDaa(0x1d, f(0b1011), 0x83, f(0b0001));
try testDaa(0x1d, f(0b1100), 0x1d, f(0b0100));
try testDaa(0x1d, f(0b1101), 0xbd, f(0b0101));
try testDaa(0x1d, f(0b1110), 0x17, f(0b0100));
try testDaa(0x1d, f(0b1111), 0xb7, f(0b0101));
try testDaa(0x1e, f(0b0000), 0x24, f(0b0000));
try testDaa(0x1e, f(0b0001), 0x84, f(0b0001));
try testDaa(0x1e, f(0b0010), 0x24, f(0b0000));
try testDaa(0x1e, f(0b0011), 0x84, f(0b0001));
try testDaa(0x1e, f(0b0100), 0x1e, f(0b0100));
try testDaa(0x1e, f(0b0101), 0xbe, f(0b0101));
try testDaa(0x1e, f(0b0110), 0x18, f(0b0100));
try testDaa(0x1e, f(0b0111), 0xb8, f(0b0101));
try testDaa(0x1e, f(0b1000), 0x24, f(0b0000));
try testDaa(0x1e, f(0b1001), 0x84, f(0b0001));
try testDaa(0x1e, f(0b1010), 0x24, f(0b0000));
try testDaa(0x1e, f(0b1011), 0x84, f(0b0001));
try testDaa(0x1e, f(0b1100), 0x1e, f(0b0100));
try testDaa(0x1e, f(0b1101), 0xbe, f(0b0101));
try testDaa(0x1e, f(0b1110), 0x18, f(0b0100));
try testDaa(0x1e, f(0b1111), 0xb8, f(0b0101));
try testDaa(0x1f, f(0b0000), 0x25, f(0b0000));
try testDaa(0x1f, f(0b0001), 0x85, f(0b0001));
try testDaa(0x1f, f(0b0010), 0x25, f(0b0000));
try testDaa(0x1f, f(0b0011), 0x85, f(0b0001));
try testDaa(0x1f, f(0b0100), 0x1f, f(0b0100));
try testDaa(0x1f, f(0b0101), 0xbf, f(0b0101));
try testDaa(0x1f, f(0b0110), 0x19, f(0b0100));
try testDaa(0x1f, f(0b0111), 0xb9, f(0b0101));
try testDaa(0x1f, f(0b1000), 0x25, f(0b0000));
try testDaa(0x1f, f(0b1001), 0x85, f(0b0001));
try testDaa(0x1f, f(0b1010), 0x25, f(0b0000));
try testDaa(0x1f, f(0b1011), 0x85, f(0b0001));
try testDaa(0x1f, f(0b1100), 0x1f, f(0b0100));
try testDaa(0x1f, f(0b1101), 0xbf, f(0b0101));
try testDaa(0x1f, f(0b1110), 0x19, f(0b0100));
try testDaa(0x1f, f(0b1111), 0xb9, f(0b0101));
try testDaa(0x20, f(0b0000), 0x20, f(0b0000));
try testDaa(0x20, f(0b0001), 0x80, f(0b0001));
try testDaa(0x20, f(0b0010), 0x26, f(0b0000));
try testDaa(0x20, f(0b0011), 0x86, f(0b0001));
try testDaa(0x20, f(0b0100), 0x20, f(0b0100));
try testDaa(0x20, f(0b0101), 0xc0, f(0b0101));
try testDaa(0x20, f(0b0110), 0x1a, f(0b0100));
try testDaa(0x20, f(0b0111), 0xba, f(0b0101));
try testDaa(0x20, f(0b1000), 0x20, f(0b0000));
try testDaa(0x20, f(0b1001), 0x80, f(0b0001));
try testDaa(0x20, f(0b1010), 0x26, f(0b0000));
try testDaa(0x20, f(0b1011), 0x86, f(0b0001));
try testDaa(0x20, f(0b1100), 0x20, f(0b0100));
try testDaa(0x20, f(0b1101), 0xc0, f(0b0101));
try testDaa(0x20, f(0b1110), 0x1a, f(0b0100));
try testDaa(0x20, f(0b1111), 0xba, f(0b0101));
try testDaa(0x21, f(0b0000), 0x21, f(0b0000));
try testDaa(0x21, f(0b0001), 0x81, f(0b0001));
try testDaa(0x21, f(0b0010), 0x27, f(0b0000));
try testDaa(0x21, f(0b0011), 0x87, f(0b0001));
try testDaa(0x21, f(0b0100), 0x21, f(0b0100));
try testDaa(0x21, f(0b0101), 0xc1, f(0b0101));
try testDaa(0x21, f(0b0110), 0x1b, f(0b0100));
try testDaa(0x21, f(0b0111), 0xbb, f(0b0101));
try testDaa(0x21, f(0b1000), 0x21, f(0b0000));
try testDaa(0x21, f(0b1001), 0x81, f(0b0001));
try testDaa(0x21, f(0b1010), 0x27, f(0b0000));
try testDaa(0x21, f(0b1011), 0x87, f(0b0001));
try testDaa(0x21, f(0b1100), 0x21, f(0b0100));
try testDaa(0x21, f(0b1101), 0xc1, f(0b0101));
try testDaa(0x21, f(0b1110), 0x1b, f(0b0100));
try testDaa(0x21, f(0b1111), 0xbb, f(0b0101));
try testDaa(0x22, f(0b0000), 0x22, f(0b0000));
try testDaa(0x22, f(0b0001), 0x82, f(0b0001));
try testDaa(0x22, f(0b0010), 0x28, f(0b0000));
try testDaa(0x22, f(0b0011), 0x88, f(0b0001));
try testDaa(0x22, f(0b0100), 0x22, f(0b0100));
try testDaa(0x22, f(0b0101), 0xc2, f(0b0101));
try testDaa(0x22, f(0b0110), 0x1c, f(0b0100));
try testDaa(0x22, f(0b0111), 0xbc, f(0b0101));
try testDaa(0x22, f(0b1000), 0x22, f(0b0000));
try testDaa(0x22, f(0b1001), 0x82, f(0b0001));
try testDaa(0x22, f(0b1010), 0x28, f(0b0000));
try testDaa(0x22, f(0b1011), 0x88, f(0b0001));
try testDaa(0x22, f(0b1100), 0x22, f(0b0100));
try testDaa(0x22, f(0b1101), 0xc2, f(0b0101));
try testDaa(0x22, f(0b1110), 0x1c, f(0b0100));
try testDaa(0x22, f(0b1111), 0xbc, f(0b0101));
try testDaa(0x23, f(0b0000), 0x23, f(0b0000));
try testDaa(0x23, f(0b0001), 0x83, f(0b0001));
try testDaa(0x23, f(0b0010), 0x29, f(0b0000));
try testDaa(0x23, f(0b0011), 0x89, f(0b0001));
try testDaa(0x23, f(0b0100), 0x23, f(0b0100));
try testDaa(0x23, f(0b0101), 0xc3, f(0b0101));
try testDaa(0x23, f(0b0110), 0x1d, f(0b0100));
try testDaa(0x23, f(0b0111), 0xbd, f(0b0101));
try testDaa(0x23, f(0b1000), 0x23, f(0b0000));
try testDaa(0x23, f(0b1001), 0x83, f(0b0001));
try testDaa(0x23, f(0b1010), 0x29, f(0b0000));
try testDaa(0x23, f(0b1011), 0x89, f(0b0001));
try testDaa(0x23, f(0b1100), 0x23, f(0b0100));
try testDaa(0x23, f(0b1101), 0xc3, f(0b0101));
try testDaa(0x23, f(0b1110), 0x1d, f(0b0100));
try testDaa(0x23, f(0b1111), 0xbd, f(0b0101));
try testDaa(0x24, f(0b0000), 0x24, f(0b0000));
try testDaa(0x24, f(0b0001), 0x84, f(0b0001));
try testDaa(0x24, f(0b0010), 0x2a, f(0b0000));
try testDaa(0x24, f(0b0011), 0x8a, f(0b0001));
try testDaa(0x24, f(0b0100), 0x24, f(0b0100));
try testDaa(0x24, f(0b0101), 0xc4, f(0b0101));
try testDaa(0x24, f(0b0110), 0x1e, f(0b0100));
try testDaa(0x24, f(0b0111), 0xbe, f(0b0101));
try testDaa(0x24, f(0b1000), 0x24, f(0b0000));
try testDaa(0x24, f(0b1001), 0x84, f(0b0001));
try testDaa(0x24, f(0b1010), 0x2a, f(0b0000));
try testDaa(0x24, f(0b1011), 0x8a, f(0b0001));
try testDaa(0x24, f(0b1100), 0x24, f(0b0100));
try testDaa(0x24, f(0b1101), 0xc4, f(0b0101));
try testDaa(0x24, f(0b1110), 0x1e, f(0b0100));
try testDaa(0x24, f(0b1111), 0xbe, f(0b0101));
try testDaa(0x25, f(0b0000), 0x25, f(0b0000));
try testDaa(0x25, f(0b0001), 0x85, f(0b0001));
try testDaa(0x25, f(0b0010), 0x2b, f(0b0000));
try testDaa(0x25, f(0b0011), 0x8b, f(0b0001));
try testDaa(0x25, f(0b0100), 0x25, f(0b0100));
try testDaa(0x25, f(0b0101), 0xc5, f(0b0101));
try testDaa(0x25, f(0b0110), 0x1f, f(0b0100));
try testDaa(0x25, f(0b0111), 0xbf, f(0b0101));
try testDaa(0x25, f(0b1000), 0x25, f(0b0000));
try testDaa(0x25, f(0b1001), 0x85, f(0b0001));
try testDaa(0x25, f(0b1010), 0x2b, f(0b0000));
try testDaa(0x25, f(0b1011), 0x8b, f(0b0001));
try testDaa(0x25, f(0b1100), 0x25, f(0b0100));
try testDaa(0x25, f(0b1101), 0xc5, f(0b0101));
try testDaa(0x25, f(0b1110), 0x1f, f(0b0100));
try testDaa(0x25, f(0b1111), 0xbf, f(0b0101));
try testDaa(0x26, f(0b0000), 0x26, f(0b0000));
try testDaa(0x26, f(0b0001), 0x86, f(0b0001));
try testDaa(0x26, f(0b0010), 0x2c, f(0b0000));
try testDaa(0x26, f(0b0011), 0x8c, f(0b0001));
try testDaa(0x26, f(0b0100), 0x26, f(0b0100));
try testDaa(0x26, f(0b0101), 0xc6, f(0b0101));
try testDaa(0x26, f(0b0110), 0x20, f(0b0100));
try testDaa(0x26, f(0b0111), 0xc0, f(0b0101));
try testDaa(0x26, f(0b1000), 0x26, f(0b0000));
try testDaa(0x26, f(0b1001), 0x86, f(0b0001));
try testDaa(0x26, f(0b1010), 0x2c, f(0b0000));
try testDaa(0x26, f(0b1011), 0x8c, f(0b0001));
try testDaa(0x26, f(0b1100), 0x26, f(0b0100));
try testDaa(0x26, f(0b1101), 0xc6, f(0b0101));
try testDaa(0x26, f(0b1110), 0x20, f(0b0100));
try testDaa(0x26, f(0b1111), 0xc0, f(0b0101));
try testDaa(0x27, f(0b0000), 0x27, f(0b0000));
try testDaa(0x27, f(0b0001), 0x87, f(0b0001));
try testDaa(0x27, f(0b0010), 0x2d, f(0b0000));
try testDaa(0x27, f(0b0011), 0x8d, f(0b0001));
try testDaa(0x27, f(0b0100), 0x27, f(0b0100));
try testDaa(0x27, f(0b0101), 0xc7, f(0b0101));
try testDaa(0x27, f(0b0110), 0x21, f(0b0100));
try testDaa(0x27, f(0b0111), 0xc1, f(0b0101));
try testDaa(0x27, f(0b1000), 0x27, f(0b0000));
try testDaa(0x27, f(0b1001), 0x87, f(0b0001));
try testDaa(0x27, f(0b1010), 0x2d, f(0b0000));
try testDaa(0x27, f(0b1011), 0x8d, f(0b0001));
try testDaa(0x27, f(0b1100), 0x27, f(0b0100));
try testDaa(0x27, f(0b1101), 0xc7, f(0b0101));
try testDaa(0x27, f(0b1110), 0x21, f(0b0100));
try testDaa(0x27, f(0b1111), 0xc1, f(0b0101));
try testDaa(0x28, f(0b0000), 0x28, f(0b0000));
try testDaa(0x28, f(0b0001), 0x88, f(0b0001));
try testDaa(0x28, f(0b0010), 0x2e, f(0b0000));
try testDaa(0x28, f(0b0011), 0x8e, f(0b0001));
try testDaa(0x28, f(0b0100), 0x28, f(0b0100));
try testDaa(0x28, f(0b0101), 0xc8, f(0b0101));
try testDaa(0x28, f(0b0110), 0x22, f(0b0100));
try testDaa(0x28, f(0b0111), 0xc2, f(0b0101));
try testDaa(0x28, f(0b1000), 0x28, f(0b0000));
try testDaa(0x28, f(0b1001), 0x88, f(0b0001));
try testDaa(0x28, f(0b1010), 0x2e, f(0b0000));
try testDaa(0x28, f(0b1011), 0x8e, f(0b0001));
try testDaa(0x28, f(0b1100), 0x28, f(0b0100));
try testDaa(0x28, f(0b1101), 0xc8, f(0b0101));
try testDaa(0x28, f(0b1110), 0x22, f(0b0100));
try testDaa(0x28, f(0b1111), 0xc2, f(0b0101));
try testDaa(0x29, f(0b0000), 0x29, f(0b0000));
try testDaa(0x29, f(0b0001), 0x89, f(0b0001));
try testDaa(0x29, f(0b0010), 0x2f, f(0b0000));
try testDaa(0x29, f(0b0011), 0x8f, f(0b0001));
try testDaa(0x29, f(0b0100), 0x29, f(0b0100));
try testDaa(0x29, f(0b0101), 0xc9, f(0b0101));
try testDaa(0x29, f(0b0110), 0x23, f(0b0100));
try testDaa(0x29, f(0b0111), 0xc3, f(0b0101));
try testDaa(0x29, f(0b1000), 0x29, f(0b0000));
try testDaa(0x29, f(0b1001), 0x89, f(0b0001));
try testDaa(0x29, f(0b1010), 0x2f, f(0b0000));
try testDaa(0x29, f(0b1011), 0x8f, f(0b0001));
try testDaa(0x29, f(0b1100), 0x29, f(0b0100));
try testDaa(0x29, f(0b1101), 0xc9, f(0b0101));
try testDaa(0x29, f(0b1110), 0x23, f(0b0100));
try testDaa(0x29, f(0b1111), 0xc3, f(0b0101));
try testDaa(0x2a, f(0b0000), 0x30, f(0b0000));
try testDaa(0x2a, f(0b0001), 0x90, f(0b0001));
try testDaa(0x2a, f(0b0010), 0x30, f(0b0000));
try testDaa(0x2a, f(0b0011), 0x90, f(0b0001));
try testDaa(0x2a, f(0b0100), 0x2a, f(0b0100));
try testDaa(0x2a, f(0b0101), 0xca, f(0b0101));
try testDaa(0x2a, f(0b0110), 0x24, f(0b0100));
try testDaa(0x2a, f(0b0111), 0xc4, f(0b0101));
try testDaa(0x2a, f(0b1000), 0x30, f(0b0000));
try testDaa(0x2a, f(0b1001), 0x90, f(0b0001));
try testDaa(0x2a, f(0b1010), 0x30, f(0b0000));
try testDaa(0x2a, f(0b1011), 0x90, f(0b0001));
try testDaa(0x2a, f(0b1100), 0x2a, f(0b0100));
try testDaa(0x2a, f(0b1101), 0xca, f(0b0101));
try testDaa(0x2a, f(0b1110), 0x24, f(0b0100));
try testDaa(0x2a, f(0b1111), 0xc4, f(0b0101));
try testDaa(0x2b, f(0b0000), 0x31, f(0b0000));
try testDaa(0x2b, f(0b0001), 0x91, f(0b0001));
try testDaa(0x2b, f(0b0010), 0x31, f(0b0000));
try testDaa(0x2b, f(0b0011), 0x91, f(0b0001));
try testDaa(0x2b, f(0b0100), 0x2b, f(0b0100));
try testDaa(0x2b, f(0b0101), 0xcb, f(0b0101));
try testDaa(0x2b, f(0b0110), 0x25, f(0b0100));
try testDaa(0x2b, f(0b0111), 0xc5, f(0b0101));
try testDaa(0x2b, f(0b1000), 0x31, f(0b0000));
try testDaa(0x2b, f(0b1001), 0x91, f(0b0001));
try testDaa(0x2b, f(0b1010), 0x31, f(0b0000));
try testDaa(0x2b, f(0b1011), 0x91, f(0b0001));
try testDaa(0x2b, f(0b1100), 0x2b, f(0b0100));
try testDaa(0x2b, f(0b1101), 0xcb, f(0b0101));
try testDaa(0x2b, f(0b1110), 0x25, f(0b0100));
try testDaa(0x2b, f(0b1111), 0xc5, f(0b0101));
try testDaa(0x2c, f(0b0000), 0x32, f(0b0000));
try testDaa(0x2c, f(0b0001), 0x92, f(0b0001));
try testDaa(0x2c, f(0b0010), 0x32, f(0b0000));
try testDaa(0x2c, f(0b0011), 0x92, f(0b0001));
try testDaa(0x2c, f(0b0100), 0x2c, f(0b0100));
try testDaa(0x2c, f(0b0101), 0xcc, f(0b0101));
try testDaa(0x2c, f(0b0110), 0x26, f(0b0100));
try testDaa(0x2c, f(0b0111), 0xc6, f(0b0101));
try testDaa(0x2c, f(0b1000), 0x32, f(0b0000));
try testDaa(0x2c, f(0b1001), 0x92, f(0b0001));
try testDaa(0x2c, f(0b1010), 0x32, f(0b0000));
try testDaa(0x2c, f(0b1011), 0x92, f(0b0001));
try testDaa(0x2c, f(0b1100), 0x2c, f(0b0100));
try testDaa(0x2c, f(0b1101), 0xcc, f(0b0101));
try testDaa(0x2c, f(0b1110), 0x26, f(0b0100));
try testDaa(0x2c, f(0b1111), 0xc6, f(0b0101));
try testDaa(0x2d, f(0b0000), 0x33, f(0b0000));
try testDaa(0x2d, f(0b0001), 0x93, f(0b0001));
try testDaa(0x2d, f(0b0010), 0x33, f(0b0000));
try testDaa(0x2d, f(0b0011), 0x93, f(0b0001));
try testDaa(0x2d, f(0b0100), 0x2d, f(0b0100));
try testDaa(0x2d, f(0b0101), 0xcd, f(0b0101));
try testDaa(0x2d, f(0b0110), 0x27, f(0b0100));
try testDaa(0x2d, f(0b0111), 0xc7, f(0b0101));
try testDaa(0x2d, f(0b1000), 0x33, f(0b0000));
try testDaa(0x2d, f(0b1001), 0x93, f(0b0001));
try testDaa(0x2d, f(0b1010), 0x33, f(0b0000));
try testDaa(0x2d, f(0b1011), 0x93, f(0b0001));
try testDaa(0x2d, f(0b1100), 0x2d, f(0b0100));
try testDaa(0x2d, f(0b1101), 0xcd, f(0b0101));
try testDaa(0x2d, f(0b1110), 0x27, f(0b0100));
try testDaa(0x2d, f(0b1111), 0xc7, f(0b0101));
try testDaa(0x2e, f(0b0000), 0x34, f(0b0000));
try testDaa(0x2e, f(0b0001), 0x94, f(0b0001));
try testDaa(0x2e, f(0b0010), 0x34, f(0b0000));
try testDaa(0x2e, f(0b0011), 0x94, f(0b0001));
try testDaa(0x2e, f(0b0100), 0x2e, f(0b0100));
try testDaa(0x2e, f(0b0101), 0xce, f(0b0101));
try testDaa(0x2e, f(0b0110), 0x28, f(0b0100));
try testDaa(0x2e, f(0b0111), 0xc8, f(0b0101));
try testDaa(0x2e, f(0b1000), 0x34, f(0b0000));
try testDaa(0x2e, f(0b1001), 0x94, f(0b0001));
try testDaa(0x2e, f(0b1010), 0x34, f(0b0000));
try testDaa(0x2e, f(0b1011), 0x94, f(0b0001));
try testDaa(0x2e, f(0b1100), 0x2e, f(0b0100));
try testDaa(0x2e, f(0b1101), 0xce, f(0b0101));
try testDaa(0x2e, f(0b1110), 0x28, f(0b0100));
try testDaa(0x2e, f(0b1111), 0xc8, f(0b0101));
try testDaa(0x2f, f(0b0000), 0x35, f(0b0000));
try testDaa(0x2f, f(0b0001), 0x95, f(0b0001));
try testDaa(0x2f, f(0b0010), 0x35, f(0b0000));
try testDaa(0x2f, f(0b0011), 0x95, f(0b0001));
try testDaa(0x2f, f(0b0100), 0x2f, f(0b0100));
try testDaa(0x2f, f(0b0101), 0xcf, f(0b0101));
try testDaa(0x2f, f(0b0110), 0x29, f(0b0100));
try testDaa(0x2f, f(0b0111), 0xc9, f(0b0101));
try testDaa(0x2f, f(0b1000), 0x35, f(0b0000));
try testDaa(0x2f, f(0b1001), 0x95, f(0b0001));
try testDaa(0x2f, f(0b1010), 0x35, f(0b0000));
try testDaa(0x2f, f(0b1011), 0x95, f(0b0001));
try testDaa(0x2f, f(0b1100), 0x2f, f(0b0100));
try testDaa(0x2f, f(0b1101), 0xcf, f(0b0101));
try testDaa(0x2f, f(0b1110), 0x29, f(0b0100));
try testDaa(0x2f, f(0b1111), 0xc9, f(0b0101));
try testDaa(0x30, f(0b0000), 0x30, f(0b0000));
try testDaa(0x30, f(0b0001), 0x90, f(0b0001));
try testDaa(0x30, f(0b0010), 0x36, f(0b0000));
try testDaa(0x30, f(0b0011), 0x96, f(0b0001));
try testDaa(0x30, f(0b0100), 0x30, f(0b0100));
try testDaa(0x30, f(0b0101), 0xd0, f(0b0101));
try testDaa(0x30, f(0b0110), 0x2a, f(0b0100));
try testDaa(0x30, f(0b0111), 0xca, f(0b0101));
try testDaa(0x30, f(0b1000), 0x30, f(0b0000));
try testDaa(0x30, f(0b1001), 0x90, f(0b0001));
try testDaa(0x30, f(0b1010), 0x36, f(0b0000));
try testDaa(0x30, f(0b1011), 0x96, f(0b0001));
try testDaa(0x30, f(0b1100), 0x30, f(0b0100));
try testDaa(0x30, f(0b1101), 0xd0, f(0b0101));
try testDaa(0x30, f(0b1110), 0x2a, f(0b0100));
try testDaa(0x30, f(0b1111), 0xca, f(0b0101));
try testDaa(0x31, f(0b0000), 0x31, f(0b0000));
try testDaa(0x31, f(0b0001), 0x91, f(0b0001));
try testDaa(0x31, f(0b0010), 0x37, f(0b0000));
try testDaa(0x31, f(0b0011), 0x97, f(0b0001));
try testDaa(0x31, f(0b0100), 0x31, f(0b0100));
try testDaa(0x31, f(0b0101), 0xd1, f(0b0101));
try testDaa(0x31, f(0b0110), 0x2b, f(0b0100));
try testDaa(0x31, f(0b0111), 0xcb, f(0b0101));
try testDaa(0x31, f(0b1000), 0x31, f(0b0000));
try testDaa(0x31, f(0b1001), 0x91, f(0b0001));
try testDaa(0x31, f(0b1010), 0x37, f(0b0000));
try testDaa(0x31, f(0b1011), 0x97, f(0b0001));
try testDaa(0x31, f(0b1100), 0x31, f(0b0100));
try testDaa(0x31, f(0b1101), 0xd1, f(0b0101));
try testDaa(0x31, f(0b1110), 0x2b, f(0b0100));
try testDaa(0x31, f(0b1111), 0xcb, f(0b0101));
try testDaa(0x32, f(0b0000), 0x32, f(0b0000));
try testDaa(0x32, f(0b0001), 0x92, f(0b0001));
try testDaa(0x32, f(0b0010), 0x38, f(0b0000));
try testDaa(0x32, f(0b0011), 0x98, f(0b0001));
try testDaa(0x32, f(0b0100), 0x32, f(0b0100));
try testDaa(0x32, f(0b0101), 0xd2, f(0b0101));
try testDaa(0x32, f(0b0110), 0x2c, f(0b0100));
try testDaa(0x32, f(0b0111), 0xcc, f(0b0101));
try testDaa(0x32, f(0b1000), 0x32, f(0b0000));
try testDaa(0x32, f(0b1001), 0x92, f(0b0001));
try testDaa(0x32, f(0b1010), 0x38, f(0b0000));
try testDaa(0x32, f(0b1011), 0x98, f(0b0001));
try testDaa(0x32, f(0b1100), 0x32, f(0b0100));
try testDaa(0x32, f(0b1101), 0xd2, f(0b0101));
try testDaa(0x32, f(0b1110), 0x2c, f(0b0100));
try testDaa(0x32, f(0b1111), 0xcc, f(0b0101));
try testDaa(0x33, f(0b0000), 0x33, f(0b0000));
try testDaa(0x33, f(0b0001), 0x93, f(0b0001));
try testDaa(0x33, f(0b0010), 0x39, f(0b0000));
try testDaa(0x33, f(0b0011), 0x99, f(0b0001));
try testDaa(0x33, f(0b0100), 0x33, f(0b0100));
try testDaa(0x33, f(0b0101), 0xd3, f(0b0101));
try testDaa(0x33, f(0b0110), 0x2d, f(0b0100));
try testDaa(0x33, f(0b0111), 0xcd, f(0b0101));
try testDaa(0x33, f(0b1000), 0x33, f(0b0000));
try testDaa(0x33, f(0b1001), 0x93, f(0b0001));
try testDaa(0x33, f(0b1010), 0x39, f(0b0000));
try testDaa(0x33, f(0b1011), 0x99, f(0b0001));
try testDaa(0x33, f(0b1100), 0x33, f(0b0100));
try testDaa(0x33, f(0b1101), 0xd3, f(0b0101));
try testDaa(0x33, f(0b1110), 0x2d, f(0b0100));
try testDaa(0x33, f(0b1111), 0xcd, f(0b0101));
try testDaa(0x34, f(0b0000), 0x34, f(0b0000));
try testDaa(0x34, f(0b0001), 0x94, f(0b0001));
try testDaa(0x34, f(0b0010), 0x3a, f(0b0000));
try testDaa(0x34, f(0b0011), 0x9a, f(0b0001));
try testDaa(0x34, f(0b0100), 0x34, f(0b0100));
try testDaa(0x34, f(0b0101), 0xd4, f(0b0101));
try testDaa(0x34, f(0b0110), 0x2e, f(0b0100));
try testDaa(0x34, f(0b0111), 0xce, f(0b0101));
try testDaa(0x34, f(0b1000), 0x34, f(0b0000));
try testDaa(0x34, f(0b1001), 0x94, f(0b0001));
try testDaa(0x34, f(0b1010), 0x3a, f(0b0000));
try testDaa(0x34, f(0b1011), 0x9a, f(0b0001));
try testDaa(0x34, f(0b1100), 0x34, f(0b0100));
try testDaa(0x34, f(0b1101), 0xd4, f(0b0101));
try testDaa(0x34, f(0b1110), 0x2e, f(0b0100));
try testDaa(0x34, f(0b1111), 0xce, f(0b0101));
try testDaa(0x35, f(0b0000), 0x35, f(0b0000));
try testDaa(0x35, f(0b0001), 0x95, f(0b0001));
try testDaa(0x35, f(0b0010), 0x3b, f(0b0000));
try testDaa(0x35, f(0b0011), 0x9b, f(0b0001));
try testDaa(0x35, f(0b0100), 0x35, f(0b0100));
try testDaa(0x35, f(0b0101), 0xd5, f(0b0101));
try testDaa(0x35, f(0b0110), 0x2f, f(0b0100));
try testDaa(0x35, f(0b0111), 0xcf, f(0b0101));
try testDaa(0x35, f(0b1000), 0x35, f(0b0000));
try testDaa(0x35, f(0b1001), 0x95, f(0b0001));
try testDaa(0x35, f(0b1010), 0x3b, f(0b0000));
try testDaa(0x35, f(0b1011), 0x9b, f(0b0001));
try testDaa(0x35, f(0b1100), 0x35, f(0b0100));
try testDaa(0x35, f(0b1101), 0xd5, f(0b0101));
try testDaa(0x35, f(0b1110), 0x2f, f(0b0100));
try testDaa(0x35, f(0b1111), 0xcf, f(0b0101));
try testDaa(0x36, f(0b0000), 0x36, f(0b0000));
try testDaa(0x36, f(0b0001), 0x96, f(0b0001));
try testDaa(0x36, f(0b0010), 0x3c, f(0b0000));
try testDaa(0x36, f(0b0011), 0x9c, f(0b0001));
try testDaa(0x36, f(0b0100), 0x36, f(0b0100));
try testDaa(0x36, f(0b0101), 0xd6, f(0b0101));
try testDaa(0x36, f(0b0110), 0x30, f(0b0100));
try testDaa(0x36, f(0b0111), 0xd0, f(0b0101));
try testDaa(0x36, f(0b1000), 0x36, f(0b0000));
try testDaa(0x36, f(0b1001), 0x96, f(0b0001));
try testDaa(0x36, f(0b1010), 0x3c, f(0b0000));
try testDaa(0x36, f(0b1011), 0x9c, f(0b0001));
try testDaa(0x36, f(0b1100), 0x36, f(0b0100));
try testDaa(0x36, f(0b1101), 0xd6, f(0b0101));
try testDaa(0x36, f(0b1110), 0x30, f(0b0100));
try testDaa(0x36, f(0b1111), 0xd0, f(0b0101));
try testDaa(0x37, f(0b0000), 0x37, f(0b0000));
try testDaa(0x37, f(0b0001), 0x97, f(0b0001));
try testDaa(0x37, f(0b0010), 0x3d, f(0b0000));
try testDaa(0x37, f(0b0011), 0x9d, f(0b0001));
try testDaa(0x37, f(0b0100), 0x37, f(0b0100));
try testDaa(0x37, f(0b0101), 0xd7, f(0b0101));
try testDaa(0x37, f(0b0110), 0x31, f(0b0100));
try testDaa(0x37, f(0b0111), 0xd1, f(0b0101));
try testDaa(0x37, f(0b1000), 0x37, f(0b0000));
try testDaa(0x37, f(0b1001), 0x97, f(0b0001));
try testDaa(0x37, f(0b1010), 0x3d, f(0b0000));
try testDaa(0x37, f(0b1011), 0x9d, f(0b0001));
try testDaa(0x37, f(0b1100), 0x37, f(0b0100));
try testDaa(0x37, f(0b1101), 0xd7, f(0b0101));
try testDaa(0x37, f(0b1110), 0x31, f(0b0100));
try testDaa(0x37, f(0b1111), 0xd1, f(0b0101));
try testDaa(0x38, f(0b0000), 0x38, f(0b0000));
try testDaa(0x38, f(0b0001), 0x98, f(0b0001));
try testDaa(0x38, f(0b0010), 0x3e, f(0b0000));
try testDaa(0x38, f(0b0011), 0x9e, f(0b0001));
try testDaa(0x38, f(0b0100), 0x38, f(0b0100));
try testDaa(0x38, f(0b0101), 0xd8, f(0b0101));
try testDaa(0x38, f(0b0110), 0x32, f(0b0100));
try testDaa(0x38, f(0b0111), 0xd2, f(0b0101));
try testDaa(0x38, f(0b1000), 0x38, f(0b0000));
try testDaa(0x38, f(0b1001), 0x98, f(0b0001));
try testDaa(0x38, f(0b1010), 0x3e, f(0b0000));
try testDaa(0x38, f(0b1011), 0x9e, f(0b0001));
try testDaa(0x38, f(0b1100), 0x38, f(0b0100));
try testDaa(0x38, f(0b1101), 0xd8, f(0b0101));
try testDaa(0x38, f(0b1110), 0x32, f(0b0100));
try testDaa(0x38, f(0b1111), 0xd2, f(0b0101));
try testDaa(0x39, f(0b0000), 0x39, f(0b0000));
try testDaa(0x39, f(0b0001), 0x99, f(0b0001));
try testDaa(0x39, f(0b0010), 0x3f, f(0b0000));
try testDaa(0x39, f(0b0011), 0x9f, f(0b0001));
try testDaa(0x39, f(0b0100), 0x39, f(0b0100));
try testDaa(0x39, f(0b0101), 0xd9, f(0b0101));
try testDaa(0x39, f(0b0110), 0x33, f(0b0100));
try testDaa(0x39, f(0b0111), 0xd3, f(0b0101));
try testDaa(0x39, f(0b1000), 0x39, f(0b0000));
try testDaa(0x39, f(0b1001), 0x99, f(0b0001));
try testDaa(0x39, f(0b1010), 0x3f, f(0b0000));
try testDaa(0x39, f(0b1011), 0x9f, f(0b0001));
try testDaa(0x39, f(0b1100), 0x39, f(0b0100));
try testDaa(0x39, f(0b1101), 0xd9, f(0b0101));
try testDaa(0x39, f(0b1110), 0x33, f(0b0100));
try testDaa(0x39, f(0b1111), 0xd3, f(0b0101));
try testDaa(0x3a, f(0b0000), 0x40, f(0b0000));
try testDaa(0x3a, f(0b0001), 0xa0, f(0b0001));
try testDaa(0x3a, f(0b0010), 0x40, f(0b0000));
try testDaa(0x3a, f(0b0011), 0xa0, f(0b0001));
try testDaa(0x3a, f(0b0100), 0x3a, f(0b0100));
try testDaa(0x3a, f(0b0101), 0xda, f(0b0101));
try testDaa(0x3a, f(0b0110), 0x34, f(0b0100));
try testDaa(0x3a, f(0b0111), 0xd4, f(0b0101));
try testDaa(0x3a, f(0b1000), 0x40, f(0b0000));
try testDaa(0x3a, f(0b1001), 0xa0, f(0b0001));
try testDaa(0x3a, f(0b1010), 0x40, f(0b0000));
try testDaa(0x3a, f(0b1011), 0xa0, f(0b0001));
try testDaa(0x3a, f(0b1100), 0x3a, f(0b0100));
try testDaa(0x3a, f(0b1101), 0xda, f(0b0101));
try testDaa(0x3a, f(0b1110), 0x34, f(0b0100));
try testDaa(0x3a, f(0b1111), 0xd4, f(0b0101));
try testDaa(0x3b, f(0b0000), 0x41, f(0b0000));
try testDaa(0x3b, f(0b0001), 0xa1, f(0b0001));
try testDaa(0x3b, f(0b0010), 0x41, f(0b0000));
try testDaa(0x3b, f(0b0011), 0xa1, f(0b0001));
try testDaa(0x3b, f(0b0100), 0x3b, f(0b0100));
try testDaa(0x3b, f(0b0101), 0xdb, f(0b0101));
try testDaa(0x3b, f(0b0110), 0x35, f(0b0100));
try testDaa(0x3b, f(0b0111), 0xd5, f(0b0101));
try testDaa(0x3b, f(0b1000), 0x41, f(0b0000));
try testDaa(0x3b, f(0b1001), 0xa1, f(0b0001));
try testDaa(0x3b, f(0b1010), 0x41, f(0b0000));
try testDaa(0x3b, f(0b1011), 0xa1, f(0b0001));
try testDaa(0x3b, f(0b1100), 0x3b, f(0b0100));
try testDaa(0x3b, f(0b1101), 0xdb, f(0b0101));
try testDaa(0x3b, f(0b1110), 0x35, f(0b0100));
try testDaa(0x3b, f(0b1111), 0xd5, f(0b0101));
try testDaa(0x3c, f(0b0000), 0x42, f(0b0000));
try testDaa(0x3c, f(0b0001), 0xa2, f(0b0001));
try testDaa(0x3c, f(0b0010), 0x42, f(0b0000));
try testDaa(0x3c, f(0b0011), 0xa2, f(0b0001));
try testDaa(0x3c, f(0b0100), 0x3c, f(0b0100));
try testDaa(0x3c, f(0b0101), 0xdc, f(0b0101));
try testDaa(0x3c, f(0b0110), 0x36, f(0b0100));
try testDaa(0x3c, f(0b0111), 0xd6, f(0b0101));
try testDaa(0x3c, f(0b1000), 0x42, f(0b0000));
try testDaa(0x3c, f(0b1001), 0xa2, f(0b0001));
try testDaa(0x3c, f(0b1010), 0x42, f(0b0000));
try testDaa(0x3c, f(0b1011), 0xa2, f(0b0001));
try testDaa(0x3c, f(0b1100), 0x3c, f(0b0100));
try testDaa(0x3c, f(0b1101), 0xdc, f(0b0101));
try testDaa(0x3c, f(0b1110), 0x36, f(0b0100));
try testDaa(0x3c, f(0b1111), 0xd6, f(0b0101));
try testDaa(0x3d, f(0b0000), 0x43, f(0b0000));
try testDaa(0x3d, f(0b0001), 0xa3, f(0b0001));
try testDaa(0x3d, f(0b0010), 0x43, f(0b0000));
try testDaa(0x3d, f(0b0011), 0xa3, f(0b0001));
try testDaa(0x3d, f(0b0100), 0x3d, f(0b0100));
try testDaa(0x3d, f(0b0101), 0xdd, f(0b0101));
try testDaa(0x3d, f(0b0110), 0x37, f(0b0100));
try testDaa(0x3d, f(0b0111), 0xd7, f(0b0101));
try testDaa(0x3d, f(0b1000), 0x43, f(0b0000));
try testDaa(0x3d, f(0b1001), 0xa3, f(0b0001));
try testDaa(0x3d, f(0b1010), 0x43, f(0b0000));
try testDaa(0x3d, f(0b1011), 0xa3, f(0b0001));
try testDaa(0x3d, f(0b1100), 0x3d, f(0b0100));
try testDaa(0x3d, f(0b1101), 0xdd, f(0b0101));
try testDaa(0x3d, f(0b1110), 0x37, f(0b0100));
try testDaa(0x3d, f(0b1111), 0xd7, f(0b0101));
try testDaa(0x3e, f(0b0000), 0x44, f(0b0000));
try testDaa(0x3e, f(0b0001), 0xa4, f(0b0001));
try testDaa(0x3e, f(0b0010), 0x44, f(0b0000));
try testDaa(0x3e, f(0b0011), 0xa4, f(0b0001));
try testDaa(0x3e, f(0b0100), 0x3e, f(0b0100));
try testDaa(0x3e, f(0b0101), 0xde, f(0b0101));
try testDaa(0x3e, f(0b0110), 0x38, f(0b0100));
try testDaa(0x3e, f(0b0111), 0xd8, f(0b0101));
try testDaa(0x3e, f(0b1000), 0x44, f(0b0000));
try testDaa(0x3e, f(0b1001), 0xa4, f(0b0001));
try testDaa(0x3e, f(0b1010), 0x44, f(0b0000));
try testDaa(0x3e, f(0b1011), 0xa4, f(0b0001));
try testDaa(0x3e, f(0b1100), 0x3e, f(0b0100));
try testDaa(0x3e, f(0b1101), 0xde, f(0b0101));
try testDaa(0x3e, f(0b1110), 0x38, f(0b0100));
try testDaa(0x3e, f(0b1111), 0xd8, f(0b0101));
try testDaa(0x3f, f(0b0000), 0x45, f(0b0000));
try testDaa(0x3f, f(0b0001), 0xa5, f(0b0001));
try testDaa(0x3f, f(0b0010), 0x45, f(0b0000));
try testDaa(0x3f, f(0b0011), 0xa5, f(0b0001));
try testDaa(0x3f, f(0b0100), 0x3f, f(0b0100));
try testDaa(0x3f, f(0b0101), 0xdf, f(0b0101));
try testDaa(0x3f, f(0b0110), 0x39, f(0b0100));
try testDaa(0x3f, f(0b0111), 0xd9, f(0b0101));
try testDaa(0x3f, f(0b1000), 0x45, f(0b0000));
try testDaa(0x3f, f(0b1001), 0xa5, f(0b0001));
try testDaa(0x3f, f(0b1010), 0x45, f(0b0000));
try testDaa(0x3f, f(0b1011), 0xa5, f(0b0001));
try testDaa(0x3f, f(0b1100), 0x3f, f(0b0100));
try testDaa(0x3f, f(0b1101), 0xdf, f(0b0101));
try testDaa(0x3f, f(0b1110), 0x39, f(0b0100));
try testDaa(0x3f, f(0b1111), 0xd9, f(0b0101));
try testDaa(0x40, f(0b0000), 0x40, f(0b0000));
try testDaa(0x40, f(0b0001), 0xa0, f(0b0001));
try testDaa(0x40, f(0b0010), 0x46, f(0b0000));
try testDaa(0x40, f(0b0011), 0xa6, f(0b0001));
try testDaa(0x40, f(0b0100), 0x40, f(0b0100));
try testDaa(0x40, f(0b0101), 0xe0, f(0b0101));
try testDaa(0x40, f(0b0110), 0x3a, f(0b0100));
try testDaa(0x40, f(0b0111), 0xda, f(0b0101));
try testDaa(0x40, f(0b1000), 0x40, f(0b0000));
try testDaa(0x40, f(0b1001), 0xa0, f(0b0001));
try testDaa(0x40, f(0b1010), 0x46, f(0b0000));
try testDaa(0x40, f(0b1011), 0xa6, f(0b0001));
try testDaa(0x40, f(0b1100), 0x40, f(0b0100));
try testDaa(0x40, f(0b1101), 0xe0, f(0b0101));
try testDaa(0x40, f(0b1110), 0x3a, f(0b0100));
try testDaa(0x40, f(0b1111), 0xda, f(0b0101));
try testDaa(0x41, f(0b0000), 0x41, f(0b0000));
try testDaa(0x41, f(0b0001), 0xa1, f(0b0001));
try testDaa(0x41, f(0b0010), 0x47, f(0b0000));
try testDaa(0x41, f(0b0011), 0xa7, f(0b0001));
try testDaa(0x41, f(0b0100), 0x41, f(0b0100));
try testDaa(0x41, f(0b0101), 0xe1, f(0b0101));
try testDaa(0x41, f(0b0110), 0x3b, f(0b0100));
try testDaa(0x41, f(0b0111), 0xdb, f(0b0101));
try testDaa(0x41, f(0b1000), 0x41, f(0b0000));
try testDaa(0x41, f(0b1001), 0xa1, f(0b0001));
try testDaa(0x41, f(0b1010), 0x47, f(0b0000));
try testDaa(0x41, f(0b1011), 0xa7, f(0b0001));
try testDaa(0x41, f(0b1100), 0x41, f(0b0100));
try testDaa(0x41, f(0b1101), 0xe1, f(0b0101));
try testDaa(0x41, f(0b1110), 0x3b, f(0b0100));
try testDaa(0x41, f(0b1111), 0xdb, f(0b0101));
try testDaa(0x42, f(0b0000), 0x42, f(0b0000));
try testDaa(0x42, f(0b0001), 0xa2, f(0b0001));
try testDaa(0x42, f(0b0010), 0x48, f(0b0000));
try testDaa(0x42, f(0b0011), 0xa8, f(0b0001));
try testDaa(0x42, f(0b0100), 0x42, f(0b0100));
try testDaa(0x42, f(0b0101), 0xe2, f(0b0101));
try testDaa(0x42, f(0b0110), 0x3c, f(0b0100));
try testDaa(0x42, f(0b0111), 0xdc, f(0b0101));
try testDaa(0x42, f(0b1000), 0x42, f(0b0000));
try testDaa(0x42, f(0b1001), 0xa2, f(0b0001));
try testDaa(0x42, f(0b1010), 0x48, f(0b0000));
try testDaa(0x42, f(0b1011), 0xa8, f(0b0001));
try testDaa(0x42, f(0b1100), 0x42, f(0b0100));
try testDaa(0x42, f(0b1101), 0xe2, f(0b0101));
try testDaa(0x42, f(0b1110), 0x3c, f(0b0100));
try testDaa(0x42, f(0b1111), 0xdc, f(0b0101));
try testDaa(0x43, f(0b0000), 0x43, f(0b0000));
try testDaa(0x43, f(0b0001), 0xa3, f(0b0001));
try testDaa(0x43, f(0b0010), 0x49, f(0b0000));
try testDaa(0x43, f(0b0011), 0xa9, f(0b0001));
try testDaa(0x43, f(0b0100), 0x43, f(0b0100));
try testDaa(0x43, f(0b0101), 0xe3, f(0b0101));
try testDaa(0x43, f(0b0110), 0x3d, f(0b0100));
try testDaa(0x43, f(0b0111), 0xdd, f(0b0101));
try testDaa(0x43, f(0b1000), 0x43, f(0b0000));
try testDaa(0x43, f(0b1001), 0xa3, f(0b0001));
try testDaa(0x43, f(0b1010), 0x49, f(0b0000));
try testDaa(0x43, f(0b1011), 0xa9, f(0b0001));
try testDaa(0x43, f(0b1100), 0x43, f(0b0100));
try testDaa(0x43, f(0b1101), 0xe3, f(0b0101));
try testDaa(0x43, f(0b1110), 0x3d, f(0b0100));
try testDaa(0x43, f(0b1111), 0xdd, f(0b0101));
try testDaa(0x44, f(0b0000), 0x44, f(0b0000));
try testDaa(0x44, f(0b0001), 0xa4, f(0b0001));
try testDaa(0x44, f(0b0010), 0x4a, f(0b0000));
try testDaa(0x44, f(0b0011), 0xaa, f(0b0001));
try testDaa(0x44, f(0b0100), 0x44, f(0b0100));
try testDaa(0x44, f(0b0101), 0xe4, f(0b0101));
try testDaa(0x44, f(0b0110), 0x3e, f(0b0100));
try testDaa(0x44, f(0b0111), 0xde, f(0b0101));
try testDaa(0x44, f(0b1000), 0x44, f(0b0000));
try testDaa(0x44, f(0b1001), 0xa4, f(0b0001));
try testDaa(0x44, f(0b1010), 0x4a, f(0b0000));
try testDaa(0x44, f(0b1011), 0xaa, f(0b0001));
try testDaa(0x44, f(0b1100), 0x44, f(0b0100));
try testDaa(0x44, f(0b1101), 0xe4, f(0b0101));
try testDaa(0x44, f(0b1110), 0x3e, f(0b0100));
try testDaa(0x44, f(0b1111), 0xde, f(0b0101));
try testDaa(0x45, f(0b0000), 0x45, f(0b0000));
try testDaa(0x45, f(0b0001), 0xa5, f(0b0001));
try testDaa(0x45, f(0b0010), 0x4b, f(0b0000));
try testDaa(0x45, f(0b0011), 0xab, f(0b0001));
try testDaa(0x45, f(0b0100), 0x45, f(0b0100));
try testDaa(0x45, f(0b0101), 0xe5, f(0b0101));
try testDaa(0x45, f(0b0110), 0x3f, f(0b0100));
try testDaa(0x45, f(0b0111), 0xdf, f(0b0101));
try testDaa(0x45, f(0b1000), 0x45, f(0b0000));
try testDaa(0x45, f(0b1001), 0xa5, f(0b0001));
try testDaa(0x45, f(0b1010), 0x4b, f(0b0000));
try testDaa(0x45, f(0b1011), 0xab, f(0b0001));
try testDaa(0x45, f(0b1100), 0x45, f(0b0100));
try testDaa(0x45, f(0b1101), 0xe5, f(0b0101));
try testDaa(0x45, f(0b1110), 0x3f, f(0b0100));
try testDaa(0x45, f(0b1111), 0xdf, f(0b0101));
try testDaa(0x46, f(0b0000), 0x46, f(0b0000));
try testDaa(0x46, f(0b0001), 0xa6, f(0b0001));
try testDaa(0x46, f(0b0010), 0x4c, f(0b0000));
try testDaa(0x46, f(0b0011), 0xac, f(0b0001));
try testDaa(0x46, f(0b0100), 0x46, f(0b0100));
try testDaa(0x46, f(0b0101), 0xe6, f(0b0101));
try testDaa(0x46, f(0b0110), 0x40, f(0b0100));
try testDaa(0x46, f(0b0111), 0xe0, f(0b0101));
try testDaa(0x46, f(0b1000), 0x46, f(0b0000));
try testDaa(0x46, f(0b1001), 0xa6, f(0b0001));
try testDaa(0x46, f(0b1010), 0x4c, f(0b0000));
try testDaa(0x46, f(0b1011), 0xac, f(0b0001));
try testDaa(0x46, f(0b1100), 0x46, f(0b0100));
try testDaa(0x46, f(0b1101), 0xe6, f(0b0101));
try testDaa(0x46, f(0b1110), 0x40, f(0b0100));
try testDaa(0x46, f(0b1111), 0xe0, f(0b0101));
try testDaa(0x47, f(0b0000), 0x47, f(0b0000));
try testDaa(0x47, f(0b0001), 0xa7, f(0b0001));
try testDaa(0x47, f(0b0010), 0x4d, f(0b0000));
try testDaa(0x47, f(0b0011), 0xad, f(0b0001));
try testDaa(0x47, f(0b0100), 0x47, f(0b0100));
try testDaa(0x47, f(0b0101), 0xe7, f(0b0101));
try testDaa(0x47, f(0b0110), 0x41, f(0b0100));
try testDaa(0x47, f(0b0111), 0xe1, f(0b0101));
try testDaa(0x47, f(0b1000), 0x47, f(0b0000));
try testDaa(0x47, f(0b1001), 0xa7, f(0b0001));
try testDaa(0x47, f(0b1010), 0x4d, f(0b0000));
try testDaa(0x47, f(0b1011), 0xad, f(0b0001));
try testDaa(0x47, f(0b1100), 0x47, f(0b0100));
try testDaa(0x47, f(0b1101), 0xe7, f(0b0101));
try testDaa(0x47, f(0b1110), 0x41, f(0b0100));
try testDaa(0x47, f(0b1111), 0xe1, f(0b0101));
try testDaa(0x48, f(0b0000), 0x48, f(0b0000));
try testDaa(0x48, f(0b0001), 0xa8, f(0b0001));
try testDaa(0x48, f(0b0010), 0x4e, f(0b0000));
try testDaa(0x48, f(0b0011), 0xae, f(0b0001));
try testDaa(0x48, f(0b0100), 0x48, f(0b0100));
try testDaa(0x48, f(0b0101), 0xe8, f(0b0101));
try testDaa(0x48, f(0b0110), 0x42, f(0b0100));
try testDaa(0x48, f(0b0111), 0xe2, f(0b0101));
try testDaa(0x48, f(0b1000), 0x48, f(0b0000));
try testDaa(0x48, f(0b1001), 0xa8, f(0b0001));
try testDaa(0x48, f(0b1010), 0x4e, f(0b0000));
try testDaa(0x48, f(0b1011), 0xae, f(0b0001));
try testDaa(0x48, f(0b1100), 0x48, f(0b0100));
try testDaa(0x48, f(0b1101), 0xe8, f(0b0101));
try testDaa(0x48, f(0b1110), 0x42, f(0b0100));
try testDaa(0x48, f(0b1111), 0xe2, f(0b0101));
try testDaa(0x49, f(0b0000), 0x49, f(0b0000));
try testDaa(0x49, f(0b0001), 0xa9, f(0b0001));
try testDaa(0x49, f(0b0010), 0x4f, f(0b0000));
try testDaa(0x49, f(0b0011), 0xaf, f(0b0001));
try testDaa(0x49, f(0b0100), 0x49, f(0b0100));
try testDaa(0x49, f(0b0101), 0xe9, f(0b0101));
try testDaa(0x49, f(0b0110), 0x43, f(0b0100));
try testDaa(0x49, f(0b0111), 0xe3, f(0b0101));
try testDaa(0x49, f(0b1000), 0x49, f(0b0000));
try testDaa(0x49, f(0b1001), 0xa9, f(0b0001));
try testDaa(0x49, f(0b1010), 0x4f, f(0b0000));
try testDaa(0x49, f(0b1011), 0xaf, f(0b0001));
try testDaa(0x49, f(0b1100), 0x49, f(0b0100));
try testDaa(0x49, f(0b1101), 0xe9, f(0b0101));
try testDaa(0x49, f(0b1110), 0x43, f(0b0100));
try testDaa(0x49, f(0b1111), 0xe3, f(0b0101));
try testDaa(0x4a, f(0b0000), 0x50, f(0b0000));
try testDaa(0x4a, f(0b0001), 0xb0, f(0b0001));
try testDaa(0x4a, f(0b0010), 0x50, f(0b0000));
try testDaa(0x4a, f(0b0011), 0xb0, f(0b0001));
try testDaa(0x4a, f(0b0100), 0x4a, f(0b0100));
try testDaa(0x4a, f(0b0101), 0xea, f(0b0101));
try testDaa(0x4a, f(0b0110), 0x44, f(0b0100));
try testDaa(0x4a, f(0b0111), 0xe4, f(0b0101));
try testDaa(0x4a, f(0b1000), 0x50, f(0b0000));
try testDaa(0x4a, f(0b1001), 0xb0, f(0b0001));
try testDaa(0x4a, f(0b1010), 0x50, f(0b0000));
try testDaa(0x4a, f(0b1011), 0xb0, f(0b0001));
try testDaa(0x4a, f(0b1100), 0x4a, f(0b0100));
try testDaa(0x4a, f(0b1101), 0xea, f(0b0101));
try testDaa(0x4a, f(0b1110), 0x44, f(0b0100));
try testDaa(0x4a, f(0b1111), 0xe4, f(0b0101));
try testDaa(0x4b, f(0b0000), 0x51, f(0b0000));
try testDaa(0x4b, f(0b0001), 0xb1, f(0b0001));
try testDaa(0x4b, f(0b0010), 0x51, f(0b0000));
try testDaa(0x4b, f(0b0011), 0xb1, f(0b0001));
try testDaa(0x4b, f(0b0100), 0x4b, f(0b0100));
try testDaa(0x4b, f(0b0101), 0xeb, f(0b0101));
try testDaa(0x4b, f(0b0110), 0x45, f(0b0100));
try testDaa(0x4b, f(0b0111), 0xe5, f(0b0101));
try testDaa(0x4b, f(0b1000), 0x51, f(0b0000));
try testDaa(0x4b, f(0b1001), 0xb1, f(0b0001));
try testDaa(0x4b, f(0b1010), 0x51, f(0b0000));
try testDaa(0x4b, f(0b1011), 0xb1, f(0b0001));
try testDaa(0x4b, f(0b1100), 0x4b, f(0b0100));
try testDaa(0x4b, f(0b1101), 0xeb, f(0b0101));
try testDaa(0x4b, f(0b1110), 0x45, f(0b0100));
try testDaa(0x4b, f(0b1111), 0xe5, f(0b0101));
try testDaa(0x4c, f(0b0000), 0x52, f(0b0000));
try testDaa(0x4c, f(0b0001), 0xb2, f(0b0001));
try testDaa(0x4c, f(0b0010), 0x52, f(0b0000));
try testDaa(0x4c, f(0b0011), 0xb2, f(0b0001));
try testDaa(0x4c, f(0b0100), 0x4c, f(0b0100));
try testDaa(0x4c, f(0b0101), 0xec, f(0b0101));
try testDaa(0x4c, f(0b0110), 0x46, f(0b0100));
try testDaa(0x4c, f(0b0111), 0xe6, f(0b0101));
try testDaa(0x4c, f(0b1000), 0x52, f(0b0000));
try testDaa(0x4c, f(0b1001), 0xb2, f(0b0001));
try testDaa(0x4c, f(0b1010), 0x52, f(0b0000));
try testDaa(0x4c, f(0b1011), 0xb2, f(0b0001));
try testDaa(0x4c, f(0b1100), 0x4c, f(0b0100));
try testDaa(0x4c, f(0b1101), 0xec, f(0b0101));
try testDaa(0x4c, f(0b1110), 0x46, f(0b0100));
try testDaa(0x4c, f(0b1111), 0xe6, f(0b0101));
try testDaa(0x4d, f(0b0000), 0x53, f(0b0000));
try testDaa(0x4d, f(0b0001), 0xb3, f(0b0001));
try testDaa(0x4d, f(0b0010), 0x53, f(0b0000));
try testDaa(0x4d, f(0b0011), 0xb3, f(0b0001));
try testDaa(0x4d, f(0b0100), 0x4d, f(0b0100));
try testDaa(0x4d, f(0b0101), 0xed, f(0b0101));
try testDaa(0x4d, f(0b0110), 0x47, f(0b0100));
try testDaa(0x4d, f(0b0111), 0xe7, f(0b0101));
try testDaa(0x4d, f(0b1000), 0x53, f(0b0000));
try testDaa(0x4d, f(0b1001), 0xb3, f(0b0001));
try testDaa(0x4d, f(0b1010), 0x53, f(0b0000));
try testDaa(0x4d, f(0b1011), 0xb3, f(0b0001));
try testDaa(0x4d, f(0b1100), 0x4d, f(0b0100));
try testDaa(0x4d, f(0b1101), 0xed, f(0b0101));
try testDaa(0x4d, f(0b1110), 0x47, f(0b0100));
try testDaa(0x4d, f(0b1111), 0xe7, f(0b0101));
try testDaa(0x4e, f(0b0000), 0x54, f(0b0000));
try testDaa(0x4e, f(0b0001), 0xb4, f(0b0001));
try testDaa(0x4e, f(0b0010), 0x54, f(0b0000));
try testDaa(0x4e, f(0b0011), 0xb4, f(0b0001));
try testDaa(0x4e, f(0b0100), 0x4e, f(0b0100));
try testDaa(0x4e, f(0b0101), 0xee, f(0b0101));
try testDaa(0x4e, f(0b0110), 0x48, f(0b0100));
try testDaa(0x4e, f(0b0111), 0xe8, f(0b0101));
try testDaa(0x4e, f(0b1000), 0x54, f(0b0000));
try testDaa(0x4e, f(0b1001), 0xb4, f(0b0001));
try testDaa(0x4e, f(0b1010), 0x54, f(0b0000));
try testDaa(0x4e, f(0b1011), 0xb4, f(0b0001));
try testDaa(0x4e, f(0b1100), 0x4e, f(0b0100));
try testDaa(0x4e, f(0b1101), 0xee, f(0b0101));
try testDaa(0x4e, f(0b1110), 0x48, f(0b0100));
try testDaa(0x4e, f(0b1111), 0xe8, f(0b0101));
try testDaa(0x4f, f(0b0000), 0x55, f(0b0000));
try testDaa(0x4f, f(0b0001), 0xb5, f(0b0001));
try testDaa(0x4f, f(0b0010), 0x55, f(0b0000));
try testDaa(0x4f, f(0b0011), 0xb5, f(0b0001));
try testDaa(0x4f, f(0b0100), 0x4f, f(0b0100));
try testDaa(0x4f, f(0b0101), 0xef, f(0b0101));
try testDaa(0x4f, f(0b0110), 0x49, f(0b0100));
try testDaa(0x4f, f(0b0111), 0xe9, f(0b0101));
try testDaa(0x4f, f(0b1000), 0x55, f(0b0000));
try testDaa(0x4f, f(0b1001), 0xb5, f(0b0001));
try testDaa(0x4f, f(0b1010), 0x55, f(0b0000));
try testDaa(0x4f, f(0b1011), 0xb5, f(0b0001));
try testDaa(0x4f, f(0b1100), 0x4f, f(0b0100));
try testDaa(0x4f, f(0b1101), 0xef, f(0b0101));
try testDaa(0x4f, f(0b1110), 0x49, f(0b0100));
try testDaa(0x4f, f(0b1111), 0xe9, f(0b0101));
try testDaa(0x50, f(0b0000), 0x50, f(0b0000));
try testDaa(0x50, f(0b0001), 0xb0, f(0b0001));
try testDaa(0x50, f(0b0010), 0x56, f(0b0000));
try testDaa(0x50, f(0b0011), 0xb6, f(0b0001));
try testDaa(0x50, f(0b0100), 0x50, f(0b0100));
try testDaa(0x50, f(0b0101), 0xf0, f(0b0101));
try testDaa(0x50, f(0b0110), 0x4a, f(0b0100));
try testDaa(0x50, f(0b0111), 0xea, f(0b0101));
try testDaa(0x50, f(0b1000), 0x50, f(0b0000));
try testDaa(0x50, f(0b1001), 0xb0, f(0b0001));
try testDaa(0x50, f(0b1010), 0x56, f(0b0000));
try testDaa(0x50, f(0b1011), 0xb6, f(0b0001));
try testDaa(0x50, f(0b1100), 0x50, f(0b0100));
try testDaa(0x50, f(0b1101), 0xf0, f(0b0101));
try testDaa(0x50, f(0b1110), 0x4a, f(0b0100));
try testDaa(0x50, f(0b1111), 0xea, f(0b0101));
try testDaa(0x51, f(0b0000), 0x51, f(0b0000));
try testDaa(0x51, f(0b0001), 0xb1, f(0b0001));
try testDaa(0x51, f(0b0010), 0x57, f(0b0000));
try testDaa(0x51, f(0b0011), 0xb7, f(0b0001));
try testDaa(0x51, f(0b0100), 0x51, f(0b0100));
try testDaa(0x51, f(0b0101), 0xf1, f(0b0101));
try testDaa(0x51, f(0b0110), 0x4b, f(0b0100));
try testDaa(0x51, f(0b0111), 0xeb, f(0b0101));
try testDaa(0x51, f(0b1000), 0x51, f(0b0000));
try testDaa(0x51, f(0b1001), 0xb1, f(0b0001));
try testDaa(0x51, f(0b1010), 0x57, f(0b0000));
try testDaa(0x51, f(0b1011), 0xb7, f(0b0001));
try testDaa(0x51, f(0b1100), 0x51, f(0b0100));
try testDaa(0x51, f(0b1101), 0xf1, f(0b0101));
try testDaa(0x51, f(0b1110), 0x4b, f(0b0100));
try testDaa(0x51, f(0b1111), 0xeb, f(0b0101));
try testDaa(0x52, f(0b0000), 0x52, f(0b0000));
try testDaa(0x52, f(0b0001), 0xb2, f(0b0001));
try testDaa(0x52, f(0b0010), 0x58, f(0b0000));
try testDaa(0x52, f(0b0011), 0xb8, f(0b0001));
try testDaa(0x52, f(0b0100), 0x52, f(0b0100));
try testDaa(0x52, f(0b0101), 0xf2, f(0b0101));
try testDaa(0x52, f(0b0110), 0x4c, f(0b0100));
try testDaa(0x52, f(0b0111), 0xec, f(0b0101));
try testDaa(0x52, f(0b1000), 0x52, f(0b0000));
try testDaa(0x52, f(0b1001), 0xb2, f(0b0001));
try testDaa(0x52, f(0b1010), 0x58, f(0b0000));
try testDaa(0x52, f(0b1011), 0xb8, f(0b0001));
try testDaa(0x52, f(0b1100), 0x52, f(0b0100));
try testDaa(0x52, f(0b1101), 0xf2, f(0b0101));
try testDaa(0x52, f(0b1110), 0x4c, f(0b0100));
try testDaa(0x52, f(0b1111), 0xec, f(0b0101));
try testDaa(0x53, f(0b0000), 0x53, f(0b0000));
try testDaa(0x53, f(0b0001), 0xb3, f(0b0001));
try testDaa(0x53, f(0b0010), 0x59, f(0b0000));
try testDaa(0x53, f(0b0011), 0xb9, f(0b0001));
try testDaa(0x53, f(0b0100), 0x53, f(0b0100));
try testDaa(0x53, f(0b0101), 0xf3, f(0b0101));
try testDaa(0x53, f(0b0110), 0x4d, f(0b0100));
try testDaa(0x53, f(0b0111), 0xed, f(0b0101));
try testDaa(0x53, f(0b1000), 0x53, f(0b0000));
try testDaa(0x53, f(0b1001), 0xb3, f(0b0001));
try testDaa(0x53, f(0b1010), 0x59, f(0b0000));
try testDaa(0x53, f(0b1011), 0xb9, f(0b0001));
try testDaa(0x53, f(0b1100), 0x53, f(0b0100));
try testDaa(0x53, f(0b1101), 0xf3, f(0b0101));
try testDaa(0x53, f(0b1110), 0x4d, f(0b0100));
try testDaa(0x53, f(0b1111), 0xed, f(0b0101));
try testDaa(0x54, f(0b0000), 0x54, f(0b0000));
try testDaa(0x54, f(0b0001), 0xb4, f(0b0001));
try testDaa(0x54, f(0b0010), 0x5a, f(0b0000));
try testDaa(0x54, f(0b0011), 0xba, f(0b0001));
try testDaa(0x54, f(0b0100), 0x54, f(0b0100));
try testDaa(0x54, f(0b0101), 0xf4, f(0b0101));
try testDaa(0x54, f(0b0110), 0x4e, f(0b0100));
try testDaa(0x54, f(0b0111), 0xee, f(0b0101));
try testDaa(0x54, f(0b1000), 0x54, f(0b0000));
try testDaa(0x54, f(0b1001), 0xb4, f(0b0001));
try testDaa(0x54, f(0b1010), 0x5a, f(0b0000));
try testDaa(0x54, f(0b1011), 0xba, f(0b0001));
try testDaa(0x54, f(0b1100), 0x54, f(0b0100));
try testDaa(0x54, f(0b1101), 0xf4, f(0b0101));
try testDaa(0x54, f(0b1110), 0x4e, f(0b0100));
try testDaa(0x54, f(0b1111), 0xee, f(0b0101));
try testDaa(0x55, f(0b0000), 0x55, f(0b0000));
try testDaa(0x55, f(0b0001), 0xb5, f(0b0001));
try testDaa(0x55, f(0b0010), 0x5b, f(0b0000));
try testDaa(0x55, f(0b0011), 0xbb, f(0b0001));
try testDaa(0x55, f(0b0100), 0x55, f(0b0100));
try testDaa(0x55, f(0b0101), 0xf5, f(0b0101));
try testDaa(0x55, f(0b0110), 0x4f, f(0b0100));
try testDaa(0x55, f(0b0111), 0xef, f(0b0101));
try testDaa(0x55, f(0b1000), 0x55, f(0b0000));
try testDaa(0x55, f(0b1001), 0xb5, f(0b0001));
try testDaa(0x55, f(0b1010), 0x5b, f(0b0000));
try testDaa(0x55, f(0b1011), 0xbb, f(0b0001));
try testDaa(0x55, f(0b1100), 0x55, f(0b0100));
try testDaa(0x55, f(0b1101), 0xf5, f(0b0101));
try testDaa(0x55, f(0b1110), 0x4f, f(0b0100));
try testDaa(0x55, f(0b1111), 0xef, f(0b0101));
try testDaa(0x56, f(0b0000), 0x56, f(0b0000));
try testDaa(0x56, f(0b0001), 0xb6, f(0b0001));
try testDaa(0x56, f(0b0010), 0x5c, f(0b0000));
try testDaa(0x56, f(0b0011), 0xbc, f(0b0001));
try testDaa(0x56, f(0b0100), 0x56, f(0b0100));
try testDaa(0x56, f(0b0101), 0xf6, f(0b0101));
try testDaa(0x56, f(0b0110), 0x50, f(0b0100));
try testDaa(0x56, f(0b0111), 0xf0, f(0b0101));
try testDaa(0x56, f(0b1000), 0x56, f(0b0000));
try testDaa(0x56, f(0b1001), 0xb6, f(0b0001));
try testDaa(0x56, f(0b1010), 0x5c, f(0b0000));
try testDaa(0x56, f(0b1011), 0xbc, f(0b0001));
try testDaa(0x56, f(0b1100), 0x56, f(0b0100));
try testDaa(0x56, f(0b1101), 0xf6, f(0b0101));
try testDaa(0x56, f(0b1110), 0x50, f(0b0100));
try testDaa(0x56, f(0b1111), 0xf0, f(0b0101));
try testDaa(0x57, f(0b0000), 0x57, f(0b0000));
try testDaa(0x57, f(0b0001), 0xb7, f(0b0001));
try testDaa(0x57, f(0b0010), 0x5d, f(0b0000));
try testDaa(0x57, f(0b0011), 0xbd, f(0b0001));
try testDaa(0x57, f(0b0100), 0x57, f(0b0100));
try testDaa(0x57, f(0b0101), 0xf7, f(0b0101));
try testDaa(0x57, f(0b0110), 0x51, f(0b0100));
try testDaa(0x57, f(0b0111), 0xf1, f(0b0101));
try testDaa(0x57, f(0b1000), 0x57, f(0b0000));
try testDaa(0x57, f(0b1001), 0xb7, f(0b0001));
try testDaa(0x57, f(0b1010), 0x5d, f(0b0000));
try testDaa(0x57, f(0b1011), 0xbd, f(0b0001));
try testDaa(0x57, f(0b1100), 0x57, f(0b0100));
try testDaa(0x57, f(0b1101), 0xf7, f(0b0101));
try testDaa(0x57, f(0b1110), 0x51, f(0b0100));
try testDaa(0x57, f(0b1111), 0xf1, f(0b0101));
try testDaa(0x58, f(0b0000), 0x58, f(0b0000));
try testDaa(0x58, f(0b0001), 0xb8, f(0b0001));
try testDaa(0x58, f(0b0010), 0x5e, f(0b0000));
try testDaa(0x58, f(0b0011), 0xbe, f(0b0001));
try testDaa(0x58, f(0b0100), 0x58, f(0b0100));
try testDaa(0x58, f(0b0101), 0xf8, f(0b0101));
try testDaa(0x58, f(0b0110), 0x52, f(0b0100));
try testDaa(0x58, f(0b0111), 0xf2, f(0b0101));
try testDaa(0x58, f(0b1000), 0x58, f(0b0000));
try testDaa(0x58, f(0b1001), 0xb8, f(0b0001));
try testDaa(0x58, f(0b1010), 0x5e, f(0b0000));
try testDaa(0x58, f(0b1011), 0xbe, f(0b0001));
try testDaa(0x58, f(0b1100), 0x58, f(0b0100));
try testDaa(0x58, f(0b1101), 0xf8, f(0b0101));
try testDaa(0x58, f(0b1110), 0x52, f(0b0100));
try testDaa(0x58, f(0b1111), 0xf2, f(0b0101));
try testDaa(0x59, f(0b0000), 0x59, f(0b0000));
try testDaa(0x59, f(0b0001), 0xb9, f(0b0001));
try testDaa(0x59, f(0b0010), 0x5f, f(0b0000));
try testDaa(0x59, f(0b0011), 0xbf, f(0b0001));
try testDaa(0x59, f(0b0100), 0x59, f(0b0100));
try testDaa(0x59, f(0b0101), 0xf9, f(0b0101));
try testDaa(0x59, f(0b0110), 0x53, f(0b0100));
try testDaa(0x59, f(0b0111), 0xf3, f(0b0101));
try testDaa(0x59, f(0b1000), 0x59, f(0b0000));
try testDaa(0x59, f(0b1001), 0xb9, f(0b0001));
try testDaa(0x59, f(0b1010), 0x5f, f(0b0000));
try testDaa(0x59, f(0b1011), 0xbf, f(0b0001));
try testDaa(0x59, f(0b1100), 0x59, f(0b0100));
try testDaa(0x59, f(0b1101), 0xf9, f(0b0101));
try testDaa(0x59, f(0b1110), 0x53, f(0b0100));
try testDaa(0x59, f(0b1111), 0xf3, f(0b0101));
try testDaa(0x5a, f(0b0000), 0x60, f(0b0000));
try testDaa(0x5a, f(0b0001), 0xc0, f(0b0001));
try testDaa(0x5a, f(0b0010), 0x60, f(0b0000));
try testDaa(0x5a, f(0b0011), 0xc0, f(0b0001));
try testDaa(0x5a, f(0b0100), 0x5a, f(0b0100));
try testDaa(0x5a, f(0b0101), 0xfa, f(0b0101));
try testDaa(0x5a, f(0b0110), 0x54, f(0b0100));
try testDaa(0x5a, f(0b0111), 0xf4, f(0b0101));
try testDaa(0x5a, f(0b1000), 0x60, f(0b0000));
try testDaa(0x5a, f(0b1001), 0xc0, f(0b0001));
try testDaa(0x5a, f(0b1010), 0x60, f(0b0000));
try testDaa(0x5a, f(0b1011), 0xc0, f(0b0001));
try testDaa(0x5a, f(0b1100), 0x5a, f(0b0100));
try testDaa(0x5a, f(0b1101), 0xfa, f(0b0101));
try testDaa(0x5a, f(0b1110), 0x54, f(0b0100));
try testDaa(0x5a, f(0b1111), 0xf4, f(0b0101));
try testDaa(0x5b, f(0b0000), 0x61, f(0b0000));
try testDaa(0x5b, f(0b0001), 0xc1, f(0b0001));
try testDaa(0x5b, f(0b0010), 0x61, f(0b0000));
try testDaa(0x5b, f(0b0011), 0xc1, f(0b0001));
try testDaa(0x5b, f(0b0100), 0x5b, f(0b0100));
try testDaa(0x5b, f(0b0101), 0xfb, f(0b0101));
try testDaa(0x5b, f(0b0110), 0x55, f(0b0100));
try testDaa(0x5b, f(0b0111), 0xf5, f(0b0101));
try testDaa(0x5b, f(0b1000), 0x61, f(0b0000));
try testDaa(0x5b, f(0b1001), 0xc1, f(0b0001));
try testDaa(0x5b, f(0b1010), 0x61, f(0b0000));
try testDaa(0x5b, f(0b1011), 0xc1, f(0b0001));
try testDaa(0x5b, f(0b1100), 0x5b, f(0b0100));
try testDaa(0x5b, f(0b1101), 0xfb, f(0b0101));
try testDaa(0x5b, f(0b1110), 0x55, f(0b0100));
try testDaa(0x5b, f(0b1111), 0xf5, f(0b0101));
try testDaa(0x5c, f(0b0000), 0x62, f(0b0000));
try testDaa(0x5c, f(0b0001), 0xc2, f(0b0001));
try testDaa(0x5c, f(0b0010), 0x62, f(0b0000));
try testDaa(0x5c, f(0b0011), 0xc2, f(0b0001));
try testDaa(0x5c, f(0b0100), 0x5c, f(0b0100));
try testDaa(0x5c, f(0b0101), 0xfc, f(0b0101));
try testDaa(0x5c, f(0b0110), 0x56, f(0b0100));
try testDaa(0x5c, f(0b0111), 0xf6, f(0b0101));
try testDaa(0x5c, f(0b1000), 0x62, f(0b0000));
try testDaa(0x5c, f(0b1001), 0xc2, f(0b0001));
try testDaa(0x5c, f(0b1010), 0x62, f(0b0000));
try testDaa(0x5c, f(0b1011), 0xc2, f(0b0001));
try testDaa(0x5c, f(0b1100), 0x5c, f(0b0100));
try testDaa(0x5c, f(0b1101), 0xfc, f(0b0101));
try testDaa(0x5c, f(0b1110), 0x56, f(0b0100));
try testDaa(0x5c, f(0b1111), 0xf6, f(0b0101));
try testDaa(0x5d, f(0b0000), 0x63, f(0b0000));
try testDaa(0x5d, f(0b0001), 0xc3, f(0b0001));
try testDaa(0x5d, f(0b0010), 0x63, f(0b0000));
try testDaa(0x5d, f(0b0011), 0xc3, f(0b0001));
try testDaa(0x5d, f(0b0100), 0x5d, f(0b0100));
try testDaa(0x5d, f(0b0101), 0xfd, f(0b0101));
try testDaa(0x5d, f(0b0110), 0x57, f(0b0100));
try testDaa(0x5d, f(0b0111), 0xf7, f(0b0101));
try testDaa(0x5d, f(0b1000), 0x63, f(0b0000));
try testDaa(0x5d, f(0b1001), 0xc3, f(0b0001));
try testDaa(0x5d, f(0b1010), 0x63, f(0b0000));
try testDaa(0x5d, f(0b1011), 0xc3, f(0b0001));
try testDaa(0x5d, f(0b1100), 0x5d, f(0b0100));
try testDaa(0x5d, f(0b1101), 0xfd, f(0b0101));
try testDaa(0x5d, f(0b1110), 0x57, f(0b0100));
try testDaa(0x5d, f(0b1111), 0xf7, f(0b0101));
try testDaa(0x5e, f(0b0000), 0x64, f(0b0000));
try testDaa(0x5e, f(0b0001), 0xc4, f(0b0001));
try testDaa(0x5e, f(0b0010), 0x64, f(0b0000));
try testDaa(0x5e, f(0b0011), 0xc4, f(0b0001));
try testDaa(0x5e, f(0b0100), 0x5e, f(0b0100));
try testDaa(0x5e, f(0b0101), 0xfe, f(0b0101));
try testDaa(0x5e, f(0b0110), 0x58, f(0b0100));
try testDaa(0x5e, f(0b0111), 0xf8, f(0b0101));
try testDaa(0x5e, f(0b1000), 0x64, f(0b0000));
try testDaa(0x5e, f(0b1001), 0xc4, f(0b0001));
try testDaa(0x5e, f(0b1010), 0x64, f(0b0000));
try testDaa(0x5e, f(0b1011), 0xc4, f(0b0001));
try testDaa(0x5e, f(0b1100), 0x5e, f(0b0100));
try testDaa(0x5e, f(0b1101), 0xfe, f(0b0101));
try testDaa(0x5e, f(0b1110), 0x58, f(0b0100));
try testDaa(0x5e, f(0b1111), 0xf8, f(0b0101));
try testDaa(0x5f, f(0b0000), 0x65, f(0b0000));
try testDaa(0x5f, f(0b0001), 0xc5, f(0b0001));
try testDaa(0x5f, f(0b0010), 0x65, f(0b0000));
try testDaa(0x5f, f(0b0011), 0xc5, f(0b0001));
try testDaa(0x5f, f(0b0100), 0x5f, f(0b0100));
try testDaa(0x5f, f(0b0101), 0xff, f(0b0101));
try testDaa(0x5f, f(0b0110), 0x59, f(0b0100));
try testDaa(0x5f, f(0b0111), 0xf9, f(0b0101));
try testDaa(0x5f, f(0b1000), 0x65, f(0b0000));
try testDaa(0x5f, f(0b1001), 0xc5, f(0b0001));
try testDaa(0x5f, f(0b1010), 0x65, f(0b0000));
try testDaa(0x5f, f(0b1011), 0xc5, f(0b0001));
try testDaa(0x5f, f(0b1100), 0x5f, f(0b0100));
try testDaa(0x5f, f(0b1101), 0xff, f(0b0101));
try testDaa(0x5f, f(0b1110), 0x59, f(0b0100));
try testDaa(0x5f, f(0b1111), 0xf9, f(0b0101));
try testDaa(0x60, f(0b0000), 0x60, f(0b0000));
try testDaa(0x60, f(0b0001), 0xc0, f(0b0001));
try testDaa(0x60, f(0b0010), 0x66, f(0b0000));
try testDaa(0x60, f(0b0011), 0xc6, f(0b0001));
try testDaa(0x60, f(0b0100), 0x60, f(0b0100));
try testDaa(0x60, f(0b0101), 0x00, f(0b1101));
try testDaa(0x60, f(0b0110), 0x5a, f(0b0100));
try testDaa(0x60, f(0b0111), 0xfa, f(0b0101));
try testDaa(0x60, f(0b1000), 0x60, f(0b0000));
try testDaa(0x60, f(0b1001), 0xc0, f(0b0001));
try testDaa(0x60, f(0b1010), 0x66, f(0b0000));
try testDaa(0x60, f(0b1011), 0xc6, f(0b0001));
try testDaa(0x60, f(0b1100), 0x60, f(0b0100));
try testDaa(0x60, f(0b1101), 0x00, f(0b1101));
try testDaa(0x60, f(0b1110), 0x5a, f(0b0100));
try testDaa(0x60, f(0b1111), 0xfa, f(0b0101));
try testDaa(0x61, f(0b0000), 0x61, f(0b0000));
try testDaa(0x61, f(0b0001), 0xc1, f(0b0001));
try testDaa(0x61, f(0b0010), 0x67, f(0b0000));
try testDaa(0x61, f(0b0011), 0xc7, f(0b0001));
try testDaa(0x61, f(0b0100), 0x61, f(0b0100));
try testDaa(0x61, f(0b0101), 0x01, f(0b0101));
try testDaa(0x61, f(0b0110), 0x5b, f(0b0100));
try testDaa(0x61, f(0b0111), 0xfb, f(0b0101));
try testDaa(0x61, f(0b1000), 0x61, f(0b0000));
try testDaa(0x61, f(0b1001), 0xc1, f(0b0001));
try testDaa(0x61, f(0b1010), 0x67, f(0b0000));
try testDaa(0x61, f(0b1011), 0xc7, f(0b0001));
try testDaa(0x61, f(0b1100), 0x61, f(0b0100));
try testDaa(0x61, f(0b1101), 0x01, f(0b0101));
try testDaa(0x61, f(0b1110), 0x5b, f(0b0100));
try testDaa(0x61, f(0b1111), 0xfb, f(0b0101));
try testDaa(0x62, f(0b0000), 0x62, f(0b0000));
try testDaa(0x62, f(0b0001), 0xc2, f(0b0001));
try testDaa(0x62, f(0b0010), 0x68, f(0b0000));
try testDaa(0x62, f(0b0011), 0xc8, f(0b0001));
try testDaa(0x62, f(0b0100), 0x62, f(0b0100));
try testDaa(0x62, f(0b0101), 0x02, f(0b0101));
try testDaa(0x62, f(0b0110), 0x5c, f(0b0100));
try testDaa(0x62, f(0b0111), 0xfc, f(0b0101));
try testDaa(0x62, f(0b1000), 0x62, f(0b0000));
try testDaa(0x62, f(0b1001), 0xc2, f(0b0001));
try testDaa(0x62, f(0b1010), 0x68, f(0b0000));
try testDaa(0x62, f(0b1011), 0xc8, f(0b0001));
try testDaa(0x62, f(0b1100), 0x62, f(0b0100));
try testDaa(0x62, f(0b1101), 0x02, f(0b0101));
try testDaa(0x62, f(0b1110), 0x5c, f(0b0100));
try testDaa(0x62, f(0b1111), 0xfc, f(0b0101));
try testDaa(0x63, f(0b0000), 0x63, f(0b0000));
try testDaa(0x63, f(0b0001), 0xc3, f(0b0001));
try testDaa(0x63, f(0b0010), 0x69, f(0b0000));
try testDaa(0x63, f(0b0011), 0xc9, f(0b0001));
try testDaa(0x63, f(0b0100), 0x63, f(0b0100));
try testDaa(0x63, f(0b0101), 0x03, f(0b0101));
try testDaa(0x63, f(0b0110), 0x5d, f(0b0100));
try testDaa(0x63, f(0b0111), 0xfd, f(0b0101));
try testDaa(0x63, f(0b1000), 0x63, f(0b0000));
try testDaa(0x63, f(0b1001), 0xc3, f(0b0001));
try testDaa(0x63, f(0b1010), 0x69, f(0b0000));
try testDaa(0x63, f(0b1011), 0xc9, f(0b0001));
try testDaa(0x63, f(0b1100), 0x63, f(0b0100));
try testDaa(0x63, f(0b1101), 0x03, f(0b0101));
try testDaa(0x63, f(0b1110), 0x5d, f(0b0100));
try testDaa(0x63, f(0b1111), 0xfd, f(0b0101));
try testDaa(0x64, f(0b0000), 0x64, f(0b0000));
try testDaa(0x64, f(0b0001), 0xc4, f(0b0001));
try testDaa(0x64, f(0b0010), 0x6a, f(0b0000));
try testDaa(0x64, f(0b0011), 0xca, f(0b0001));
try testDaa(0x64, f(0b0100), 0x64, f(0b0100));
try testDaa(0x64, f(0b0101), 0x04, f(0b0101));
try testDaa(0x64, f(0b0110), 0x5e, f(0b0100));
try testDaa(0x64, f(0b0111), 0xfe, f(0b0101));
try testDaa(0x64, f(0b1000), 0x64, f(0b0000));
try testDaa(0x64, f(0b1001), 0xc4, f(0b0001));
try testDaa(0x64, f(0b1010), 0x6a, f(0b0000));
try testDaa(0x64, f(0b1011), 0xca, f(0b0001));
try testDaa(0x64, f(0b1100), 0x64, f(0b0100));
try testDaa(0x64, f(0b1101), 0x04, f(0b0101));
try testDaa(0x64, f(0b1110), 0x5e, f(0b0100));
try testDaa(0x64, f(0b1111), 0xfe, f(0b0101));
try testDaa(0x65, f(0b0000), 0x65, f(0b0000));
try testDaa(0x65, f(0b0001), 0xc5, f(0b0001));
try testDaa(0x65, f(0b0010), 0x6b, f(0b0000));
try testDaa(0x65, f(0b0011), 0xcb, f(0b0001));
try testDaa(0x65, f(0b0100), 0x65, f(0b0100));
try testDaa(0x65, f(0b0101), 0x05, f(0b0101));
try testDaa(0x65, f(0b0110), 0x5f, f(0b0100));
try testDaa(0x65, f(0b0111), 0xff, f(0b0101));
try testDaa(0x65, f(0b1000), 0x65, f(0b0000));
try testDaa(0x65, f(0b1001), 0xc5, f(0b0001));
try testDaa(0x65, f(0b1010), 0x6b, f(0b0000));
try testDaa(0x65, f(0b1011), 0xcb, f(0b0001));
try testDaa(0x65, f(0b1100), 0x65, f(0b0100));
try testDaa(0x65, f(0b1101), 0x05, f(0b0101));
try testDaa(0x65, f(0b1110), 0x5f, f(0b0100));
try testDaa(0x65, f(0b1111), 0xff, f(0b0101));
try testDaa(0x66, f(0b0000), 0x66, f(0b0000));
try testDaa(0x66, f(0b0001), 0xc6, f(0b0001));
try testDaa(0x66, f(0b0010), 0x6c, f(0b0000));
try testDaa(0x66, f(0b0011), 0xcc, f(0b0001));
try testDaa(0x66, f(0b0100), 0x66, f(0b0100));
try testDaa(0x66, f(0b0101), 0x06, f(0b0101));
try testDaa(0x66, f(0b0110), 0x60, f(0b0100));
try testDaa(0x66, f(0b0111), 0x00, f(0b1101));
try testDaa(0x66, f(0b1000), 0x66, f(0b0000));
try testDaa(0x66, f(0b1001), 0xc6, f(0b0001));
try testDaa(0x66, f(0b1010), 0x6c, f(0b0000));
try testDaa(0x66, f(0b1011), 0xcc, f(0b0001));
try testDaa(0x66, f(0b1100), 0x66, f(0b0100));
try testDaa(0x66, f(0b1101), 0x06, f(0b0101));
try testDaa(0x66, f(0b1110), 0x60, f(0b0100));
try testDaa(0x66, f(0b1111), 0x00, f(0b1101));
try testDaa(0x67, f(0b0000), 0x67, f(0b0000));
try testDaa(0x67, f(0b0001), 0xc7, f(0b0001));
try testDaa(0x67, f(0b0010), 0x6d, f(0b0000));
try testDaa(0x67, f(0b0011), 0xcd, f(0b0001));
try testDaa(0x67, f(0b0100), 0x67, f(0b0100));
try testDaa(0x67, f(0b0101), 0x07, f(0b0101));
try testDaa(0x67, f(0b0110), 0x61, f(0b0100));
try testDaa(0x67, f(0b0111), 0x01, f(0b0101));
try testDaa(0x67, f(0b1000), 0x67, f(0b0000));
try testDaa(0x67, f(0b1001), 0xc7, f(0b0001));
try testDaa(0x67, f(0b1010), 0x6d, f(0b0000));
try testDaa(0x67, f(0b1011), 0xcd, f(0b0001));
try testDaa(0x67, f(0b1100), 0x67, f(0b0100));
try testDaa(0x67, f(0b1101), 0x07, f(0b0101));
try testDaa(0x67, f(0b1110), 0x61, f(0b0100));
try testDaa(0x67, f(0b1111), 0x01, f(0b0101));
try testDaa(0x68, f(0b0000), 0x68, f(0b0000));
try testDaa(0x68, f(0b0001), 0xc8, f(0b0001));
try testDaa(0x68, f(0b0010), 0x6e, f(0b0000));
try testDaa(0x68, f(0b0011), 0xce, f(0b0001));
try testDaa(0x68, f(0b0100), 0x68, f(0b0100));
try testDaa(0x68, f(0b0101), 0x08, f(0b0101));
try testDaa(0x68, f(0b0110), 0x62, f(0b0100));
try testDaa(0x68, f(0b0111), 0x02, f(0b0101));
try testDaa(0x68, f(0b1000), 0x68, f(0b0000));
try testDaa(0x68, f(0b1001), 0xc8, f(0b0001));
try testDaa(0x68, f(0b1010), 0x6e, f(0b0000));
try testDaa(0x68, f(0b1011), 0xce, f(0b0001));
try testDaa(0x68, f(0b1100), 0x68, f(0b0100));
try testDaa(0x68, f(0b1101), 0x08, f(0b0101));
try testDaa(0x68, f(0b1110), 0x62, f(0b0100));
try testDaa(0x68, f(0b1111), 0x02, f(0b0101));
try testDaa(0x69, f(0b0000), 0x69, f(0b0000));
try testDaa(0x69, f(0b0001), 0xc9, f(0b0001));
try testDaa(0x69, f(0b0010), 0x6f, f(0b0000));
try testDaa(0x69, f(0b0011), 0xcf, f(0b0001));
try testDaa(0x69, f(0b0100), 0x69, f(0b0100));
try testDaa(0x69, f(0b0101), 0x09, f(0b0101));
try testDaa(0x69, f(0b0110), 0x63, f(0b0100));
try testDaa(0x69, f(0b0111), 0x03, f(0b0101));
try testDaa(0x69, f(0b1000), 0x69, f(0b0000));
try testDaa(0x69, f(0b1001), 0xc9, f(0b0001));
try testDaa(0x69, f(0b1010), 0x6f, f(0b0000));
try testDaa(0x69, f(0b1011), 0xcf, f(0b0001));
try testDaa(0x69, f(0b1100), 0x69, f(0b0100));
try testDaa(0x69, f(0b1101), 0x09, f(0b0101));
try testDaa(0x69, f(0b1110), 0x63, f(0b0100));
try testDaa(0x69, f(0b1111), 0x03, f(0b0101));
try testDaa(0x6a, f(0b0000), 0x70, f(0b0000));
try testDaa(0x6a, f(0b0001), 0xd0, f(0b0001));
try testDaa(0x6a, f(0b0010), 0x70, f(0b0000));
try testDaa(0x6a, f(0b0011), 0xd0, f(0b0001));
try testDaa(0x6a, f(0b0100), 0x6a, f(0b0100));
try testDaa(0x6a, f(0b0101), 0x0a, f(0b0101));
try testDaa(0x6a, f(0b0110), 0x64, f(0b0100));
try testDaa(0x6a, f(0b0111), 0x04, f(0b0101));
try testDaa(0x6a, f(0b1000), 0x70, f(0b0000));
try testDaa(0x6a, f(0b1001), 0xd0, f(0b0001));
try testDaa(0x6a, f(0b1010), 0x70, f(0b0000));
try testDaa(0x6a, f(0b1011), 0xd0, f(0b0001));
try testDaa(0x6a, f(0b1100), 0x6a, f(0b0100));
try testDaa(0x6a, f(0b1101), 0x0a, f(0b0101));
try testDaa(0x6a, f(0b1110), 0x64, f(0b0100));
try testDaa(0x6a, f(0b1111), 0x04, f(0b0101));
try testDaa(0x6b, f(0b0000), 0x71, f(0b0000));
try testDaa(0x6b, f(0b0001), 0xd1, f(0b0001));
try testDaa(0x6b, f(0b0010), 0x71, f(0b0000));
try testDaa(0x6b, f(0b0011), 0xd1, f(0b0001));
try testDaa(0x6b, f(0b0100), 0x6b, f(0b0100));
try testDaa(0x6b, f(0b0101), 0x0b, f(0b0101));
try testDaa(0x6b, f(0b0110), 0x65, f(0b0100));
try testDaa(0x6b, f(0b0111), 0x05, f(0b0101));
try testDaa(0x6b, f(0b1000), 0x71, f(0b0000));
try testDaa(0x6b, f(0b1001), 0xd1, f(0b0001));
try testDaa(0x6b, f(0b1010), 0x71, f(0b0000));
try testDaa(0x6b, f(0b1011), 0xd1, f(0b0001));
try testDaa(0x6b, f(0b1100), 0x6b, f(0b0100));
try testDaa(0x6b, f(0b1101), 0x0b, f(0b0101));
try testDaa(0x6b, f(0b1110), 0x65, f(0b0100));
try testDaa(0x6b, f(0b1111), 0x05, f(0b0101));
try testDaa(0x6c, f(0b0000), 0x72, f(0b0000));
try testDaa(0x6c, f(0b0001), 0xd2, f(0b0001));
try testDaa(0x6c, f(0b0010), 0x72, f(0b0000));
try testDaa(0x6c, f(0b0011), 0xd2, f(0b0001));
try testDaa(0x6c, f(0b0100), 0x6c, f(0b0100));
try testDaa(0x6c, f(0b0101), 0x0c, f(0b0101));
try testDaa(0x6c, f(0b0110), 0x66, f(0b0100));
try testDaa(0x6c, f(0b0111), 0x06, f(0b0101));
try testDaa(0x6c, f(0b1000), 0x72, f(0b0000));
try testDaa(0x6c, f(0b1001), 0xd2, f(0b0001));
try testDaa(0x6c, f(0b1010), 0x72, f(0b0000));
try testDaa(0x6c, f(0b1011), 0xd2, f(0b0001));
try testDaa(0x6c, f(0b1100), 0x6c, f(0b0100));
try testDaa(0x6c, f(0b1101), 0x0c, f(0b0101));
try testDaa(0x6c, f(0b1110), 0x66, f(0b0100));
try testDaa(0x6c, f(0b1111), 0x06, f(0b0101));
try testDaa(0x6d, f(0b0000), 0x73, f(0b0000));
try testDaa(0x6d, f(0b0001), 0xd3, f(0b0001));
try testDaa(0x6d, f(0b0010), 0x73, f(0b0000));
try testDaa(0x6d, f(0b0011), 0xd3, f(0b0001));
try testDaa(0x6d, f(0b0100), 0x6d, f(0b0100));
try testDaa(0x6d, f(0b0101), 0x0d, f(0b0101));
try testDaa(0x6d, f(0b0110), 0x67, f(0b0100));
try testDaa(0x6d, f(0b0111), 0x07, f(0b0101));
try testDaa(0x6d, f(0b1000), 0x73, f(0b0000));
try testDaa(0x6d, f(0b1001), 0xd3, f(0b0001));
try testDaa(0x6d, f(0b1010), 0x73, f(0b0000));
try testDaa(0x6d, f(0b1011), 0xd3, f(0b0001));
try testDaa(0x6d, f(0b1100), 0x6d, f(0b0100));
try testDaa(0x6d, f(0b1101), 0x0d, f(0b0101));
try testDaa(0x6d, f(0b1110), 0x67, f(0b0100));
try testDaa(0x6d, f(0b1111), 0x07, f(0b0101));
try testDaa(0x6e, f(0b0000), 0x74, f(0b0000));
try testDaa(0x6e, f(0b0001), 0xd4, f(0b0001));
try testDaa(0x6e, f(0b0010), 0x74, f(0b0000));
try testDaa(0x6e, f(0b0011), 0xd4, f(0b0001));
try testDaa(0x6e, f(0b0100), 0x6e, f(0b0100));
try testDaa(0x6e, f(0b0101), 0x0e, f(0b0101));
try testDaa(0x6e, f(0b0110), 0x68, f(0b0100));
try testDaa(0x6e, f(0b0111), 0x08, f(0b0101));
try testDaa(0x6e, f(0b1000), 0x74, f(0b0000));
try testDaa(0x6e, f(0b1001), 0xd4, f(0b0001));
try testDaa(0x6e, f(0b1010), 0x74, f(0b0000));
try testDaa(0x6e, f(0b1011), 0xd4, f(0b0001));
try testDaa(0x6e, f(0b1100), 0x6e, f(0b0100));
try testDaa(0x6e, f(0b1101), 0x0e, f(0b0101));
try testDaa(0x6e, f(0b1110), 0x68, f(0b0100));
try testDaa(0x6e, f(0b1111), 0x08, f(0b0101));
try testDaa(0x6f, f(0b0000), 0x75, f(0b0000));
try testDaa(0x6f, f(0b0001), 0xd5, f(0b0001));
try testDaa(0x6f, f(0b0010), 0x75, f(0b0000));
try testDaa(0x6f, f(0b0011), 0xd5, f(0b0001));
try testDaa(0x6f, f(0b0100), 0x6f, f(0b0100));
try testDaa(0x6f, f(0b0101), 0x0f, f(0b0101));
try testDaa(0x6f, f(0b0110), 0x69, f(0b0100));
try testDaa(0x6f, f(0b0111), 0x09, f(0b0101));
try testDaa(0x6f, f(0b1000), 0x75, f(0b0000));
try testDaa(0x6f, f(0b1001), 0xd5, f(0b0001));
try testDaa(0x6f, f(0b1010), 0x75, f(0b0000));
try testDaa(0x6f, f(0b1011), 0xd5, f(0b0001));
try testDaa(0x6f, f(0b1100), 0x6f, f(0b0100));
try testDaa(0x6f, f(0b1101), 0x0f, f(0b0101));
try testDaa(0x6f, f(0b1110), 0x69, f(0b0100));
try testDaa(0x6f, f(0b1111), 0x09, f(0b0101));
try testDaa(0x70, f(0b0000), 0x70, f(0b0000));
try testDaa(0x70, f(0b0001), 0xd0, f(0b0001));
try testDaa(0x70, f(0b0010), 0x76, f(0b0000));
try testDaa(0x70, f(0b0011), 0xd6, f(0b0001));
try testDaa(0x70, f(0b0100), 0x70, f(0b0100));
try testDaa(0x70, f(0b0101), 0x10, f(0b0101));
try testDaa(0x70, f(0b0110), 0x6a, f(0b0100));
try testDaa(0x70, f(0b0111), 0x0a, f(0b0101));
try testDaa(0x70, f(0b1000), 0x70, f(0b0000));
try testDaa(0x70, f(0b1001), 0xd0, f(0b0001));
try testDaa(0x70, f(0b1010), 0x76, f(0b0000));
try testDaa(0x70, f(0b1011), 0xd6, f(0b0001));
try testDaa(0x70, f(0b1100), 0x70, f(0b0100));
try testDaa(0x70, f(0b1101), 0x10, f(0b0101));
try testDaa(0x70, f(0b1110), 0x6a, f(0b0100));
try testDaa(0x70, f(0b1111), 0x0a, f(0b0101));
try testDaa(0x71, f(0b0000), 0x71, f(0b0000));
try testDaa(0x71, f(0b0001), 0xd1, f(0b0001));
try testDaa(0x71, f(0b0010), 0x77, f(0b0000));
try testDaa(0x71, f(0b0011), 0xd7, f(0b0001));
try testDaa(0x71, f(0b0100), 0x71, f(0b0100));
try testDaa(0x71, f(0b0101), 0x11, f(0b0101));
try testDaa(0x71, f(0b0110), 0x6b, f(0b0100));
try testDaa(0x71, f(0b0111), 0x0b, f(0b0101));
try testDaa(0x71, f(0b1000), 0x71, f(0b0000));
try testDaa(0x71, f(0b1001), 0xd1, f(0b0001));
try testDaa(0x71, f(0b1010), 0x77, f(0b0000));
try testDaa(0x71, f(0b1011), 0xd7, f(0b0001));
try testDaa(0x71, f(0b1100), 0x71, f(0b0100));
try testDaa(0x71, f(0b1101), 0x11, f(0b0101));
try testDaa(0x71, f(0b1110), 0x6b, f(0b0100));
try testDaa(0x71, f(0b1111), 0x0b, f(0b0101));
try testDaa(0x72, f(0b0000), 0x72, f(0b0000));
try testDaa(0x72, f(0b0001), 0xd2, f(0b0001));
try testDaa(0x72, f(0b0010), 0x78, f(0b0000));
try testDaa(0x72, f(0b0011), 0xd8, f(0b0001));
try testDaa(0x72, f(0b0100), 0x72, f(0b0100));
try testDaa(0x72, f(0b0101), 0x12, f(0b0101));
try testDaa(0x72, f(0b0110), 0x6c, f(0b0100));
try testDaa(0x72, f(0b0111), 0x0c, f(0b0101));
try testDaa(0x72, f(0b1000), 0x72, f(0b0000));
try testDaa(0x72, f(0b1001), 0xd2, f(0b0001));
try testDaa(0x72, f(0b1010), 0x78, f(0b0000));
try testDaa(0x72, f(0b1011), 0xd8, f(0b0001));
try testDaa(0x72, f(0b1100), 0x72, f(0b0100));
try testDaa(0x72, f(0b1101), 0x12, f(0b0101));
try testDaa(0x72, f(0b1110), 0x6c, f(0b0100));
try testDaa(0x72, f(0b1111), 0x0c, f(0b0101));
try testDaa(0x73, f(0b0000), 0x73, f(0b0000));
try testDaa(0x73, f(0b0001), 0xd3, f(0b0001));
try testDaa(0x73, f(0b0010), 0x79, f(0b0000));
try testDaa(0x73, f(0b0011), 0xd9, f(0b0001));
try testDaa(0x73, f(0b0100), 0x73, f(0b0100));
try testDaa(0x73, f(0b0101), 0x13, f(0b0101));
try testDaa(0x73, f(0b0110), 0x6d, f(0b0100));
try testDaa(0x73, f(0b0111), 0x0d, f(0b0101));
try testDaa(0x73, f(0b1000), 0x73, f(0b0000));
try testDaa(0x73, f(0b1001), 0xd3, f(0b0001));
try testDaa(0x73, f(0b1010), 0x79, f(0b0000));
try testDaa(0x73, f(0b1011), 0xd9, f(0b0001));
try testDaa(0x73, f(0b1100), 0x73, f(0b0100));
try testDaa(0x73, f(0b1101), 0x13, f(0b0101));
try testDaa(0x73, f(0b1110), 0x6d, f(0b0100));
try testDaa(0x73, f(0b1111), 0x0d, f(0b0101));
try testDaa(0x74, f(0b0000), 0x74, f(0b0000));
try testDaa(0x74, f(0b0001), 0xd4, f(0b0001));
try testDaa(0x74, f(0b0010), 0x7a, f(0b0000));
try testDaa(0x74, f(0b0011), 0xda, f(0b0001));
try testDaa(0x74, f(0b0100), 0x74, f(0b0100));
try testDaa(0x74, f(0b0101), 0x14, f(0b0101));
try testDaa(0x74, f(0b0110), 0x6e, f(0b0100));
try testDaa(0x74, f(0b0111), 0x0e, f(0b0101));
try testDaa(0x74, f(0b1000), 0x74, f(0b0000));
try testDaa(0x74, f(0b1001), 0xd4, f(0b0001));
try testDaa(0x74, f(0b1010), 0x7a, f(0b0000));
try testDaa(0x74, f(0b1011), 0xda, f(0b0001));
try testDaa(0x74, f(0b1100), 0x74, f(0b0100));
try testDaa(0x74, f(0b1101), 0x14, f(0b0101));
try testDaa(0x74, f(0b1110), 0x6e, f(0b0100));
try testDaa(0x74, f(0b1111), 0x0e, f(0b0101));
try testDaa(0x75, f(0b0000), 0x75, f(0b0000));
try testDaa(0x75, f(0b0001), 0xd5, f(0b0001));
try testDaa(0x75, f(0b0010), 0x7b, f(0b0000));
try testDaa(0x75, f(0b0011), 0xdb, f(0b0001));
try testDaa(0x75, f(0b0100), 0x75, f(0b0100));
try testDaa(0x75, f(0b0101), 0x15, f(0b0101));
try testDaa(0x75, f(0b0110), 0x6f, f(0b0100));
try testDaa(0x75, f(0b0111), 0x0f, f(0b0101));
try testDaa(0x75, f(0b1000), 0x75, f(0b0000));
try testDaa(0x75, f(0b1001), 0xd5, f(0b0001));
try testDaa(0x75, f(0b1010), 0x7b, f(0b0000));
try testDaa(0x75, f(0b1011), 0xdb, f(0b0001));
try testDaa(0x75, f(0b1100), 0x75, f(0b0100));
try testDaa(0x75, f(0b1101), 0x15, f(0b0101));
try testDaa(0x75, f(0b1110), 0x6f, f(0b0100));
try testDaa(0x75, f(0b1111), 0x0f, f(0b0101));
try testDaa(0x76, f(0b0000), 0x76, f(0b0000));
try testDaa(0x76, f(0b0001), 0xd6, f(0b0001));
try testDaa(0x76, f(0b0010), 0x7c, f(0b0000));
try testDaa(0x76, f(0b0011), 0xdc, f(0b0001));
try testDaa(0x76, f(0b0100), 0x76, f(0b0100));
try testDaa(0x76, f(0b0101), 0x16, f(0b0101));
try testDaa(0x76, f(0b0110), 0x70, f(0b0100));
try testDaa(0x76, f(0b0111), 0x10, f(0b0101));
try testDaa(0x76, f(0b1000), 0x76, f(0b0000));
try testDaa(0x76, f(0b1001), 0xd6, f(0b0001));
try testDaa(0x76, f(0b1010), 0x7c, f(0b0000));
try testDaa(0x76, f(0b1011), 0xdc, f(0b0001));
try testDaa(0x76, f(0b1100), 0x76, f(0b0100));
try testDaa(0x76, f(0b1101), 0x16, f(0b0101));
try testDaa(0x76, f(0b1110), 0x70, f(0b0100));
try testDaa(0x76, f(0b1111), 0x10, f(0b0101));
try testDaa(0x77, f(0b0000), 0x77, f(0b0000));
try testDaa(0x77, f(0b0001), 0xd7, f(0b0001));
try testDaa(0x77, f(0b0010), 0x7d, f(0b0000));
try testDaa(0x77, f(0b0011), 0xdd, f(0b0001));
try testDaa(0x77, f(0b0100), 0x77, f(0b0100));
try testDaa(0x77, f(0b0101), 0x17, f(0b0101));
try testDaa(0x77, f(0b0110), 0x71, f(0b0100));
try testDaa(0x77, f(0b0111), 0x11, f(0b0101));
try testDaa(0x77, f(0b1000), 0x77, f(0b0000));
try testDaa(0x77, f(0b1001), 0xd7, f(0b0001));
try testDaa(0x77, f(0b1010), 0x7d, f(0b0000));
try testDaa(0x77, f(0b1011), 0xdd, f(0b0001));
try testDaa(0x77, f(0b1100), 0x77, f(0b0100));
try testDaa(0x77, f(0b1101), 0x17, f(0b0101));
try testDaa(0x77, f(0b1110), 0x71, f(0b0100));
try testDaa(0x77, f(0b1111), 0x11, f(0b0101));
try testDaa(0x78, f(0b0000), 0x78, f(0b0000));
try testDaa(0x78, f(0b0001), 0xd8, f(0b0001));
try testDaa(0x78, f(0b0010), 0x7e, f(0b0000));
try testDaa(0x78, f(0b0011), 0xde, f(0b0001));
try testDaa(0x78, f(0b0100), 0x78, f(0b0100));
try testDaa(0x78, f(0b0101), 0x18, f(0b0101));
try testDaa(0x78, f(0b0110), 0x72, f(0b0100));
try testDaa(0x78, f(0b0111), 0x12, f(0b0101));
try testDaa(0x78, f(0b1000), 0x78, f(0b0000));
try testDaa(0x78, f(0b1001), 0xd8, f(0b0001));
try testDaa(0x78, f(0b1010), 0x7e, f(0b0000));
try testDaa(0x78, f(0b1011), 0xde, f(0b0001));
try testDaa(0x78, f(0b1100), 0x78, f(0b0100));
try testDaa(0x78, f(0b1101), 0x18, f(0b0101));
try testDaa(0x78, f(0b1110), 0x72, f(0b0100));
try testDaa(0x78, f(0b1111), 0x12, f(0b0101));
try testDaa(0x79, f(0b0000), 0x79, f(0b0000));
try testDaa(0x79, f(0b0001), 0xd9, f(0b0001));
try testDaa(0x79, f(0b0010), 0x7f, f(0b0000));
try testDaa(0x79, f(0b0011), 0xdf, f(0b0001));
try testDaa(0x79, f(0b0100), 0x79, f(0b0100));
try testDaa(0x79, f(0b0101), 0x19, f(0b0101));
try testDaa(0x79, f(0b0110), 0x73, f(0b0100));
try testDaa(0x79, f(0b0111), 0x13, f(0b0101));
try testDaa(0x79, f(0b1000), 0x79, f(0b0000));
try testDaa(0x79, f(0b1001), 0xd9, f(0b0001));
try testDaa(0x79, f(0b1010), 0x7f, f(0b0000));
try testDaa(0x79, f(0b1011), 0xdf, f(0b0001));
try testDaa(0x79, f(0b1100), 0x79, f(0b0100));
try testDaa(0x79, f(0b1101), 0x19, f(0b0101));
try testDaa(0x79, f(0b1110), 0x73, f(0b0100));
try testDaa(0x79, f(0b1111), 0x13, f(0b0101));
try testDaa(0x7a, f(0b0000), 0x80, f(0b0000));
try testDaa(0x7a, f(0b0001), 0xe0, f(0b0001));
try testDaa(0x7a, f(0b0010), 0x80, f(0b0000));
try testDaa(0x7a, f(0b0011), 0xe0, f(0b0001));
try testDaa(0x7a, f(0b0100), 0x7a, f(0b0100));
try testDaa(0x7a, f(0b0101), 0x1a, f(0b0101));
try testDaa(0x7a, f(0b0110), 0x74, f(0b0100));
try testDaa(0x7a, f(0b0111), 0x14, f(0b0101));
try testDaa(0x7a, f(0b1000), 0x80, f(0b0000));
try testDaa(0x7a, f(0b1001), 0xe0, f(0b0001));
try testDaa(0x7a, f(0b1010), 0x80, f(0b0000));
try testDaa(0x7a, f(0b1011), 0xe0, f(0b0001));
try testDaa(0x7a, f(0b1100), 0x7a, f(0b0100));
try testDaa(0x7a, f(0b1101), 0x1a, f(0b0101));
try testDaa(0x7a, f(0b1110), 0x74, f(0b0100));
try testDaa(0x7a, f(0b1111), 0x14, f(0b0101));
try testDaa(0x7b, f(0b0000), 0x81, f(0b0000));
try testDaa(0x7b, f(0b0001), 0xe1, f(0b0001));
try testDaa(0x7b, f(0b0010), 0x81, f(0b0000));
try testDaa(0x7b, f(0b0011), 0xe1, f(0b0001));
try testDaa(0x7b, f(0b0100), 0x7b, f(0b0100));
try testDaa(0x7b, f(0b0101), 0x1b, f(0b0101));
try testDaa(0x7b, f(0b0110), 0x75, f(0b0100));
try testDaa(0x7b, f(0b0111), 0x15, f(0b0101));
try testDaa(0x7b, f(0b1000), 0x81, f(0b0000));
try testDaa(0x7b, f(0b1001), 0xe1, f(0b0001));
try testDaa(0x7b, f(0b1010), 0x81, f(0b0000));
try testDaa(0x7b, f(0b1011), 0xe1, f(0b0001));
try testDaa(0x7b, f(0b1100), 0x7b, f(0b0100));
try testDaa(0x7b, f(0b1101), 0x1b, f(0b0101));
try testDaa(0x7b, f(0b1110), 0x75, f(0b0100));
try testDaa(0x7b, f(0b1111), 0x15, f(0b0101));
try testDaa(0x7c, f(0b0000), 0x82, f(0b0000));
try testDaa(0x7c, f(0b0001), 0xe2, f(0b0001));
try testDaa(0x7c, f(0b0010), 0x82, f(0b0000));
try testDaa(0x7c, f(0b0011), 0xe2, f(0b0001));
try testDaa(0x7c, f(0b0100), 0x7c, f(0b0100));
try testDaa(0x7c, f(0b0101), 0x1c, f(0b0101));
try testDaa(0x7c, f(0b0110), 0x76, f(0b0100));
try testDaa(0x7c, f(0b0111), 0x16, f(0b0101));
try testDaa(0x7c, f(0b1000), 0x82, f(0b0000));
try testDaa(0x7c, f(0b1001), 0xe2, f(0b0001));
try testDaa(0x7c, f(0b1010), 0x82, f(0b0000));
try testDaa(0x7c, f(0b1011), 0xe2, f(0b0001));
try testDaa(0x7c, f(0b1100), 0x7c, f(0b0100));
try testDaa(0x7c, f(0b1101), 0x1c, f(0b0101));
try testDaa(0x7c, f(0b1110), 0x76, f(0b0100));
try testDaa(0x7c, f(0b1111), 0x16, f(0b0101));
try testDaa(0x7d, f(0b0000), 0x83, f(0b0000));
try testDaa(0x7d, f(0b0001), 0xe3, f(0b0001));
try testDaa(0x7d, f(0b0010), 0x83, f(0b0000));
try testDaa(0x7d, f(0b0011), 0xe3, f(0b0001));
try testDaa(0x7d, f(0b0100), 0x7d, f(0b0100));
try testDaa(0x7d, f(0b0101), 0x1d, f(0b0101));
try testDaa(0x7d, f(0b0110), 0x77, f(0b0100));
try testDaa(0x7d, f(0b0111), 0x17, f(0b0101));
try testDaa(0x7d, f(0b1000), 0x83, f(0b0000));
try testDaa(0x7d, f(0b1001), 0xe3, f(0b0001));
try testDaa(0x7d, f(0b1010), 0x83, f(0b0000));
try testDaa(0x7d, f(0b1011), 0xe3, f(0b0001));
try testDaa(0x7d, f(0b1100), 0x7d, f(0b0100));
try testDaa(0x7d, f(0b1101), 0x1d, f(0b0101));
try testDaa(0x7d, f(0b1110), 0x77, f(0b0100));
try testDaa(0x7d, f(0b1111), 0x17, f(0b0101));
try testDaa(0x7e, f(0b0000), 0x84, f(0b0000));
try testDaa(0x7e, f(0b0001), 0xe4, f(0b0001));
try testDaa(0x7e, f(0b0010), 0x84, f(0b0000));
try testDaa(0x7e, f(0b0011), 0xe4, f(0b0001));
try testDaa(0x7e, f(0b0100), 0x7e, f(0b0100));
try testDaa(0x7e, f(0b0101), 0x1e, f(0b0101));
try testDaa(0x7e, f(0b0110), 0x78, f(0b0100));
try testDaa(0x7e, f(0b0111), 0x18, f(0b0101));
try testDaa(0x7e, f(0b1000), 0x84, f(0b0000));
try testDaa(0x7e, f(0b1001), 0xe4, f(0b0001));
try testDaa(0x7e, f(0b1010), 0x84, f(0b0000));
try testDaa(0x7e, f(0b1011), 0xe4, f(0b0001));
try testDaa(0x7e, f(0b1100), 0x7e, f(0b0100));
try testDaa(0x7e, f(0b1101), 0x1e, f(0b0101));
try testDaa(0x7e, f(0b1110), 0x78, f(0b0100));
try testDaa(0x7e, f(0b1111), 0x18, f(0b0101));
try testDaa(0x7f, f(0b0000), 0x85, f(0b0000));
try testDaa(0x7f, f(0b0001), 0xe5, f(0b0001));
try testDaa(0x7f, f(0b0010), 0x85, f(0b0000));
try testDaa(0x7f, f(0b0011), 0xe5, f(0b0001));
try testDaa(0x7f, f(0b0100), 0x7f, f(0b0100));
try testDaa(0x7f, f(0b0101), 0x1f, f(0b0101));
try testDaa(0x7f, f(0b0110), 0x79, f(0b0100));
try testDaa(0x7f, f(0b0111), 0x19, f(0b0101));
try testDaa(0x7f, f(0b1000), 0x85, f(0b0000));
try testDaa(0x7f, f(0b1001), 0xe5, f(0b0001));
try testDaa(0x7f, f(0b1010), 0x85, f(0b0000));
try testDaa(0x7f, f(0b1011), 0xe5, f(0b0001));
try testDaa(0x7f, f(0b1100), 0x7f, f(0b0100));
try testDaa(0x7f, f(0b1101), 0x1f, f(0b0101));
try testDaa(0x7f, f(0b1110), 0x79, f(0b0100));
try testDaa(0x7f, f(0b1111), 0x19, f(0b0101));
try testDaa(0x80, f(0b0000), 0x80, f(0b0000));
try testDaa(0x80, f(0b0001), 0xe0, f(0b0001));
try testDaa(0x80, f(0b0010), 0x86, f(0b0000));
try testDaa(0x80, f(0b0011), 0xe6, f(0b0001));
try testDaa(0x80, f(0b0100), 0x80, f(0b0100));
try testDaa(0x80, f(0b0101), 0x20, f(0b0101));
try testDaa(0x80, f(0b0110), 0x7a, f(0b0100));
try testDaa(0x80, f(0b0111), 0x1a, f(0b0101));
try testDaa(0x80, f(0b1000), 0x80, f(0b0000));
try testDaa(0x80, f(0b1001), 0xe0, f(0b0001));
try testDaa(0x80, f(0b1010), 0x86, f(0b0000));
try testDaa(0x80, f(0b1011), 0xe6, f(0b0001));
try testDaa(0x80, f(0b1100), 0x80, f(0b0100));
try testDaa(0x80, f(0b1101), 0x20, f(0b0101));
try testDaa(0x80, f(0b1110), 0x7a, f(0b0100));
try testDaa(0x80, f(0b1111), 0x1a, f(0b0101));
try testDaa(0x81, f(0b0000), 0x81, f(0b0000));
try testDaa(0x81, f(0b0001), 0xe1, f(0b0001));
try testDaa(0x81, f(0b0010), 0x87, f(0b0000));
try testDaa(0x81, f(0b0011), 0xe7, f(0b0001));
try testDaa(0x81, f(0b0100), 0x81, f(0b0100));
try testDaa(0x81, f(0b0101), 0x21, f(0b0101));
try testDaa(0x81, f(0b0110), 0x7b, f(0b0100));
try testDaa(0x81, f(0b0111), 0x1b, f(0b0101));
try testDaa(0x81, f(0b1000), 0x81, f(0b0000));
try testDaa(0x81, f(0b1001), 0xe1, f(0b0001));
try testDaa(0x81, f(0b1010), 0x87, f(0b0000));
try testDaa(0x81, f(0b1011), 0xe7, f(0b0001));
try testDaa(0x81, f(0b1100), 0x81, f(0b0100));
try testDaa(0x81, f(0b1101), 0x21, f(0b0101));
try testDaa(0x81, f(0b1110), 0x7b, f(0b0100));
try testDaa(0x81, f(0b1111), 0x1b, f(0b0101));
try testDaa(0x82, f(0b0000), 0x82, f(0b0000));
try testDaa(0x82, f(0b0001), 0xe2, f(0b0001));
try testDaa(0x82, f(0b0010), 0x88, f(0b0000));
try testDaa(0x82, f(0b0011), 0xe8, f(0b0001));
try testDaa(0x82, f(0b0100), 0x82, f(0b0100));
try testDaa(0x82, f(0b0101), 0x22, f(0b0101));
try testDaa(0x82, f(0b0110), 0x7c, f(0b0100));
try testDaa(0x82, f(0b0111), 0x1c, f(0b0101));
try testDaa(0x82, f(0b1000), 0x82, f(0b0000));
try testDaa(0x82, f(0b1001), 0xe2, f(0b0001));
try testDaa(0x82, f(0b1010), 0x88, f(0b0000));
try testDaa(0x82, f(0b1011), 0xe8, f(0b0001));
try testDaa(0x82, f(0b1100), 0x82, f(0b0100));
try testDaa(0x82, f(0b1101), 0x22, f(0b0101));
try testDaa(0x82, f(0b1110), 0x7c, f(0b0100));
try testDaa(0x82, f(0b1111), 0x1c, f(0b0101));
try testDaa(0x83, f(0b0000), 0x83, f(0b0000));
try testDaa(0x83, f(0b0001), 0xe3, f(0b0001));
try testDaa(0x83, f(0b0010), 0x89, f(0b0000));
try testDaa(0x83, f(0b0011), 0xe9, f(0b0001));
try testDaa(0x83, f(0b0100), 0x83, f(0b0100));
try testDaa(0x83, f(0b0101), 0x23, f(0b0101));
try testDaa(0x83, f(0b0110), 0x7d, f(0b0100));
try testDaa(0x83, f(0b0111), 0x1d, f(0b0101));
try testDaa(0x83, f(0b1000), 0x83, f(0b0000));
try testDaa(0x83, f(0b1001), 0xe3, f(0b0001));
try testDaa(0x83, f(0b1010), 0x89, f(0b0000));
try testDaa(0x83, f(0b1011), 0xe9, f(0b0001));
try testDaa(0x83, f(0b1100), 0x83, f(0b0100));
try testDaa(0x83, f(0b1101), 0x23, f(0b0101));
try testDaa(0x83, f(0b1110), 0x7d, f(0b0100));
try testDaa(0x83, f(0b1111), 0x1d, f(0b0101));
try testDaa(0x84, f(0b0000), 0x84, f(0b0000));
try testDaa(0x84, f(0b0001), 0xe4, f(0b0001));
try testDaa(0x84, f(0b0010), 0x8a, f(0b0000));
try testDaa(0x84, f(0b0011), 0xea, f(0b0001));
try testDaa(0x84, f(0b0100), 0x84, f(0b0100));
try testDaa(0x84, f(0b0101), 0x24, f(0b0101));
try testDaa(0x84, f(0b0110), 0x7e, f(0b0100));
try testDaa(0x84, f(0b0111), 0x1e, f(0b0101));
try testDaa(0x84, f(0b1000), 0x84, f(0b0000));
try testDaa(0x84, f(0b1001), 0xe4, f(0b0001));
try testDaa(0x84, f(0b1010), 0x8a, f(0b0000));
try testDaa(0x84, f(0b1011), 0xea, f(0b0001));
try testDaa(0x84, f(0b1100), 0x84, f(0b0100));
try testDaa(0x84, f(0b1101), 0x24, f(0b0101));
try testDaa(0x84, f(0b1110), 0x7e, f(0b0100));
try testDaa(0x84, f(0b1111), 0x1e, f(0b0101));
try testDaa(0x85, f(0b0000), 0x85, f(0b0000));
try testDaa(0x85, f(0b0001), 0xe5, f(0b0001));
try testDaa(0x85, f(0b0010), 0x8b, f(0b0000));
try testDaa(0x85, f(0b0011), 0xeb, f(0b0001));
try testDaa(0x85, f(0b0100), 0x85, f(0b0100));
try testDaa(0x85, f(0b0101), 0x25, f(0b0101));
try testDaa(0x85, f(0b0110), 0x7f, f(0b0100));
try testDaa(0x85, f(0b0111), 0x1f, f(0b0101));
try testDaa(0x85, f(0b1000), 0x85, f(0b0000));
try testDaa(0x85, f(0b1001), 0xe5, f(0b0001));
try testDaa(0x85, f(0b1010), 0x8b, f(0b0000));
try testDaa(0x85, f(0b1011), 0xeb, f(0b0001));
try testDaa(0x85, f(0b1100), 0x85, f(0b0100));
try testDaa(0x85, f(0b1101), 0x25, f(0b0101));
try testDaa(0x85, f(0b1110), 0x7f, f(0b0100));
try testDaa(0x85, f(0b1111), 0x1f, f(0b0101));
try testDaa(0x86, f(0b0000), 0x86, f(0b0000));
try testDaa(0x86, f(0b0001), 0xe6, f(0b0001));
try testDaa(0x86, f(0b0010), 0x8c, f(0b0000));
try testDaa(0x86, f(0b0011), 0xec, f(0b0001));
try testDaa(0x86, f(0b0100), 0x86, f(0b0100));
try testDaa(0x86, f(0b0101), 0x26, f(0b0101));
try testDaa(0x86, f(0b0110), 0x80, f(0b0100));
try testDaa(0x86, f(0b0111), 0x20, f(0b0101));
try testDaa(0x86, f(0b1000), 0x86, f(0b0000));
try testDaa(0x86, f(0b1001), 0xe6, f(0b0001));
try testDaa(0x86, f(0b1010), 0x8c, f(0b0000));
try testDaa(0x86, f(0b1011), 0xec, f(0b0001));
try testDaa(0x86, f(0b1100), 0x86, f(0b0100));
try testDaa(0x86, f(0b1101), 0x26, f(0b0101));
try testDaa(0x86, f(0b1110), 0x80, f(0b0100));
try testDaa(0x86, f(0b1111), 0x20, f(0b0101));
try testDaa(0x87, f(0b0000), 0x87, f(0b0000));
try testDaa(0x87, f(0b0001), 0xe7, f(0b0001));
try testDaa(0x87, f(0b0010), 0x8d, f(0b0000));
try testDaa(0x87, f(0b0011), 0xed, f(0b0001));
try testDaa(0x87, f(0b0100), 0x87, f(0b0100));
try testDaa(0x87, f(0b0101), 0x27, f(0b0101));
try testDaa(0x87, f(0b0110), 0x81, f(0b0100));
try testDaa(0x87, f(0b0111), 0x21, f(0b0101));
try testDaa(0x87, f(0b1000), 0x87, f(0b0000));
try testDaa(0x87, f(0b1001), 0xe7, f(0b0001));
try testDaa(0x87, f(0b1010), 0x8d, f(0b0000));
try testDaa(0x87, f(0b1011), 0xed, f(0b0001));
try testDaa(0x87, f(0b1100), 0x87, f(0b0100));
try testDaa(0x87, f(0b1101), 0x27, f(0b0101));
try testDaa(0x87, f(0b1110), 0x81, f(0b0100));
try testDaa(0x87, f(0b1111), 0x21, f(0b0101));
try testDaa(0x88, f(0b0000), 0x88, f(0b0000));
try testDaa(0x88, f(0b0001), 0xe8, f(0b0001));
try testDaa(0x88, f(0b0010), 0x8e, f(0b0000));
try testDaa(0x88, f(0b0011), 0xee, f(0b0001));
try testDaa(0x88, f(0b0100), 0x88, f(0b0100));
try testDaa(0x88, f(0b0101), 0x28, f(0b0101));
try testDaa(0x88, f(0b0110), 0x82, f(0b0100));
try testDaa(0x88, f(0b0111), 0x22, f(0b0101));
try testDaa(0x88, f(0b1000), 0x88, f(0b0000));
try testDaa(0x88, f(0b1001), 0xe8, f(0b0001));
try testDaa(0x88, f(0b1010), 0x8e, f(0b0000));
try testDaa(0x88, f(0b1011), 0xee, f(0b0001));
try testDaa(0x88, f(0b1100), 0x88, f(0b0100));
try testDaa(0x88, f(0b1101), 0x28, f(0b0101));
try testDaa(0x88, f(0b1110), 0x82, f(0b0100));
try testDaa(0x88, f(0b1111), 0x22, f(0b0101));
try testDaa(0x89, f(0b0000), 0x89, f(0b0000));
try testDaa(0x89, f(0b0001), 0xe9, f(0b0001));
try testDaa(0x89, f(0b0010), 0x8f, f(0b0000));
try testDaa(0x89, f(0b0011), 0xef, f(0b0001));
try testDaa(0x89, f(0b0100), 0x89, f(0b0100));
try testDaa(0x89, f(0b0101), 0x29, f(0b0101));
try testDaa(0x89, f(0b0110), 0x83, f(0b0100));
try testDaa(0x89, f(0b0111), 0x23, f(0b0101));
try testDaa(0x89, f(0b1000), 0x89, f(0b0000));
try testDaa(0x89, f(0b1001), 0xe9, f(0b0001));
try testDaa(0x89, f(0b1010), 0x8f, f(0b0000));
try testDaa(0x89, f(0b1011), 0xef, f(0b0001));
try testDaa(0x89, f(0b1100), 0x89, f(0b0100));
try testDaa(0x89, f(0b1101), 0x29, f(0b0101));
try testDaa(0x89, f(0b1110), 0x83, f(0b0100));
try testDaa(0x89, f(0b1111), 0x23, f(0b0101));
try testDaa(0x8a, f(0b0000), 0x90, f(0b0000));
try testDaa(0x8a, f(0b0001), 0xf0, f(0b0001));
try testDaa(0x8a, f(0b0010), 0x90, f(0b0000));
try testDaa(0x8a, f(0b0011), 0xf0, f(0b0001));
try testDaa(0x8a, f(0b0100), 0x8a, f(0b0100));
try testDaa(0x8a, f(0b0101), 0x2a, f(0b0101));
try testDaa(0x8a, f(0b0110), 0x84, f(0b0100));
try testDaa(0x8a, f(0b0111), 0x24, f(0b0101));
try testDaa(0x8a, f(0b1000), 0x90, f(0b0000));
try testDaa(0x8a, f(0b1001), 0xf0, f(0b0001));
try testDaa(0x8a, f(0b1010), 0x90, f(0b0000));
try testDaa(0x8a, f(0b1011), 0xf0, f(0b0001));
try testDaa(0x8a, f(0b1100), 0x8a, f(0b0100));
try testDaa(0x8a, f(0b1101), 0x2a, f(0b0101));
try testDaa(0x8a, f(0b1110), 0x84, f(0b0100));
try testDaa(0x8a, f(0b1111), 0x24, f(0b0101));
try testDaa(0x8b, f(0b0000), 0x91, f(0b0000));
try testDaa(0x8b, f(0b0001), 0xf1, f(0b0001));
try testDaa(0x8b, f(0b0010), 0x91, f(0b0000));
try testDaa(0x8b, f(0b0011), 0xf1, f(0b0001));
try testDaa(0x8b, f(0b0100), 0x8b, f(0b0100));
try testDaa(0x8b, f(0b0101), 0x2b, f(0b0101));
try testDaa(0x8b, f(0b0110), 0x85, f(0b0100));
try testDaa(0x8b, f(0b0111), 0x25, f(0b0101));
try testDaa(0x8b, f(0b1000), 0x91, f(0b0000));
try testDaa(0x8b, f(0b1001), 0xf1, f(0b0001));
try testDaa(0x8b, f(0b1010), 0x91, f(0b0000));
try testDaa(0x8b, f(0b1011), 0xf1, f(0b0001));
try testDaa(0x8b, f(0b1100), 0x8b, f(0b0100));
try testDaa(0x8b, f(0b1101), 0x2b, f(0b0101));
try testDaa(0x8b, f(0b1110), 0x85, f(0b0100));
try testDaa(0x8b, f(0b1111), 0x25, f(0b0101));
try testDaa(0x8c, f(0b0000), 0x92, f(0b0000));
try testDaa(0x8c, f(0b0001), 0xf2, f(0b0001));
try testDaa(0x8c, f(0b0010), 0x92, f(0b0000));
try testDaa(0x8c, f(0b0011), 0xf2, f(0b0001));
try testDaa(0x8c, f(0b0100), 0x8c, f(0b0100));
try testDaa(0x8c, f(0b0101), 0x2c, f(0b0101));
try testDaa(0x8c, f(0b0110), 0x86, f(0b0100));
try testDaa(0x8c, f(0b0111), 0x26, f(0b0101));
try testDaa(0x8c, f(0b1000), 0x92, f(0b0000));
try testDaa(0x8c, f(0b1001), 0xf2, f(0b0001));
try testDaa(0x8c, f(0b1010), 0x92, f(0b0000));
try testDaa(0x8c, f(0b1011), 0xf2, f(0b0001));
try testDaa(0x8c, f(0b1100), 0x8c, f(0b0100));
try testDaa(0x8c, f(0b1101), 0x2c, f(0b0101));
try testDaa(0x8c, f(0b1110), 0x86, f(0b0100));
try testDaa(0x8c, f(0b1111), 0x26, f(0b0101));
try testDaa(0x8d, f(0b0000), 0x93, f(0b0000));
try testDaa(0x8d, f(0b0001), 0xf3, f(0b0001));
try testDaa(0x8d, f(0b0010), 0x93, f(0b0000));
try testDaa(0x8d, f(0b0011), 0xf3, f(0b0001));
try testDaa(0x8d, f(0b0100), 0x8d, f(0b0100));
try testDaa(0x8d, f(0b0101), 0x2d, f(0b0101));
try testDaa(0x8d, f(0b0110), 0x87, f(0b0100));
try testDaa(0x8d, f(0b0111), 0x27, f(0b0101));
try testDaa(0x8d, f(0b1000), 0x93, f(0b0000));
try testDaa(0x8d, f(0b1001), 0xf3, f(0b0001));
try testDaa(0x8d, f(0b1010), 0x93, f(0b0000));
try testDaa(0x8d, f(0b1011), 0xf3, f(0b0001));
try testDaa(0x8d, f(0b1100), 0x8d, f(0b0100));
try testDaa(0x8d, f(0b1101), 0x2d, f(0b0101));
try testDaa(0x8d, f(0b1110), 0x87, f(0b0100));
try testDaa(0x8d, f(0b1111), 0x27, f(0b0101));
try testDaa(0x8e, f(0b0000), 0x94, f(0b0000));
try testDaa(0x8e, f(0b0001), 0xf4, f(0b0001));
try testDaa(0x8e, f(0b0010), 0x94, f(0b0000));
try testDaa(0x8e, f(0b0011), 0xf4, f(0b0001));
try testDaa(0x8e, f(0b0100), 0x8e, f(0b0100));
try testDaa(0x8e, f(0b0101), 0x2e, f(0b0101));
try testDaa(0x8e, f(0b0110), 0x88, f(0b0100));
try testDaa(0x8e, f(0b0111), 0x28, f(0b0101));
try testDaa(0x8e, f(0b1000), 0x94, f(0b0000));
try testDaa(0x8e, f(0b1001), 0xf4, f(0b0001));
try testDaa(0x8e, f(0b1010), 0x94, f(0b0000));
try testDaa(0x8e, f(0b1011), 0xf4, f(0b0001));
try testDaa(0x8e, f(0b1100), 0x8e, f(0b0100));
try testDaa(0x8e, f(0b1101), 0x2e, f(0b0101));
try testDaa(0x8e, f(0b1110), 0x88, f(0b0100));
try testDaa(0x8e, f(0b1111), 0x28, f(0b0101));
try testDaa(0x8f, f(0b0000), 0x95, f(0b0000));
try testDaa(0x8f, f(0b0001), 0xf5, f(0b0001));
try testDaa(0x8f, f(0b0010), 0x95, f(0b0000));
try testDaa(0x8f, f(0b0011), 0xf5, f(0b0001));
try testDaa(0x8f, f(0b0100), 0x8f, f(0b0100));
try testDaa(0x8f, f(0b0101), 0x2f, f(0b0101));
try testDaa(0x8f, f(0b0110), 0x89, f(0b0100));
try testDaa(0x8f, f(0b0111), 0x29, f(0b0101));
try testDaa(0x8f, f(0b1000), 0x95, f(0b0000));
try testDaa(0x8f, f(0b1001), 0xf5, f(0b0001));
try testDaa(0x8f, f(0b1010), 0x95, f(0b0000));
try testDaa(0x8f, f(0b1011), 0xf5, f(0b0001));
try testDaa(0x8f, f(0b1100), 0x8f, f(0b0100));
try testDaa(0x8f, f(0b1101), 0x2f, f(0b0101));
try testDaa(0x8f, f(0b1110), 0x89, f(0b0100));
try testDaa(0x8f, f(0b1111), 0x29, f(0b0101));
try testDaa(0x90, f(0b0000), 0x90, f(0b0000));
try testDaa(0x90, f(0b0001), 0xf0, f(0b0001));
try testDaa(0x90, f(0b0010), 0x96, f(0b0000));
try testDaa(0x90, f(0b0011), 0xf6, f(0b0001));
try testDaa(0x90, f(0b0100), 0x90, f(0b0100));
try testDaa(0x90, f(0b0101), 0x30, f(0b0101));
try testDaa(0x90, f(0b0110), 0x8a, f(0b0100));
try testDaa(0x90, f(0b0111), 0x2a, f(0b0101));
try testDaa(0x90, f(0b1000), 0x90, f(0b0000));
try testDaa(0x90, f(0b1001), 0xf0, f(0b0001));
try testDaa(0x90, f(0b1010), 0x96, f(0b0000));
try testDaa(0x90, f(0b1011), 0xf6, f(0b0001));
try testDaa(0x90, f(0b1100), 0x90, f(0b0100));
try testDaa(0x90, f(0b1101), 0x30, f(0b0101));
try testDaa(0x90, f(0b1110), 0x8a, f(0b0100));
try testDaa(0x90, f(0b1111), 0x2a, f(0b0101));
try testDaa(0x91, f(0b0000), 0x91, f(0b0000));
try testDaa(0x91, f(0b0001), 0xf1, f(0b0001));
try testDaa(0x91, f(0b0010), 0x97, f(0b0000));
try testDaa(0x91, f(0b0011), 0xf7, f(0b0001));
try testDaa(0x91, f(0b0100), 0x91, f(0b0100));
try testDaa(0x91, f(0b0101), 0x31, f(0b0101));
try testDaa(0x91, f(0b0110), 0x8b, f(0b0100));
try testDaa(0x91, f(0b0111), 0x2b, f(0b0101));
try testDaa(0x91, f(0b1000), 0x91, f(0b0000));
try testDaa(0x91, f(0b1001), 0xf1, f(0b0001));
try testDaa(0x91, f(0b1010), 0x97, f(0b0000));
try testDaa(0x91, f(0b1011), 0xf7, f(0b0001));
try testDaa(0x91, f(0b1100), 0x91, f(0b0100));
try testDaa(0x91, f(0b1101), 0x31, f(0b0101));
try testDaa(0x91, f(0b1110), 0x8b, f(0b0100));
try testDaa(0x91, f(0b1111), 0x2b, f(0b0101));
try testDaa(0x92, f(0b0000), 0x92, f(0b0000));
try testDaa(0x92, f(0b0001), 0xf2, f(0b0001));
try testDaa(0x92, f(0b0010), 0x98, f(0b0000));
try testDaa(0x92, f(0b0011), 0xf8, f(0b0001));
try testDaa(0x92, f(0b0100), 0x92, f(0b0100));
try testDaa(0x92, f(0b0101), 0x32, f(0b0101));
try testDaa(0x92, f(0b0110), 0x8c, f(0b0100));
try testDaa(0x92, f(0b0111), 0x2c, f(0b0101));
try testDaa(0x92, f(0b1000), 0x92, f(0b0000));
try testDaa(0x92, f(0b1001), 0xf2, f(0b0001));
try testDaa(0x92, f(0b1010), 0x98, f(0b0000));
try testDaa(0x92, f(0b1011), 0xf8, f(0b0001));
try testDaa(0x92, f(0b1100), 0x92, f(0b0100));
try testDaa(0x92, f(0b1101), 0x32, f(0b0101));
try testDaa(0x92, f(0b1110), 0x8c, f(0b0100));
try testDaa(0x92, f(0b1111), 0x2c, f(0b0101));
try testDaa(0x93, f(0b0000), 0x93, f(0b0000));
try testDaa(0x93, f(0b0001), 0xf3, f(0b0001));
try testDaa(0x93, f(0b0010), 0x99, f(0b0000));
try testDaa(0x93, f(0b0011), 0xf9, f(0b0001));
try testDaa(0x93, f(0b0100), 0x93, f(0b0100));
try testDaa(0x93, f(0b0101), 0x33, f(0b0101));
try testDaa(0x93, f(0b0110), 0x8d, f(0b0100));
try testDaa(0x93, f(0b0111), 0x2d, f(0b0101));
try testDaa(0x93, f(0b1000), 0x93, f(0b0000));
try testDaa(0x93, f(0b1001), 0xf3, f(0b0001));
try testDaa(0x93, f(0b1010), 0x99, f(0b0000));
try testDaa(0x93, f(0b1011), 0xf9, f(0b0001));
try testDaa(0x93, f(0b1100), 0x93, f(0b0100));
try testDaa(0x93, f(0b1101), 0x33, f(0b0101));
try testDaa(0x93, f(0b1110), 0x8d, f(0b0100));
try testDaa(0x93, f(0b1111), 0x2d, f(0b0101));
try testDaa(0x94, f(0b0000), 0x94, f(0b0000));
try testDaa(0x94, f(0b0001), 0xf4, f(0b0001));
try testDaa(0x94, f(0b0010), 0x9a, f(0b0000));
try testDaa(0x94, f(0b0011), 0xfa, f(0b0001));
try testDaa(0x94, f(0b0100), 0x94, f(0b0100));
try testDaa(0x94, f(0b0101), 0x34, f(0b0101));
try testDaa(0x94, f(0b0110), 0x8e, f(0b0100));
try testDaa(0x94, f(0b0111), 0x2e, f(0b0101));
try testDaa(0x94, f(0b1000), 0x94, f(0b0000));
try testDaa(0x94, f(0b1001), 0xf4, f(0b0001));
try testDaa(0x94, f(0b1010), 0x9a, f(0b0000));
try testDaa(0x94, f(0b1011), 0xfa, f(0b0001));
try testDaa(0x94, f(0b1100), 0x94, f(0b0100));
try testDaa(0x94, f(0b1101), 0x34, f(0b0101));
try testDaa(0x94, f(0b1110), 0x8e, f(0b0100));
try testDaa(0x94, f(0b1111), 0x2e, f(0b0101));
try testDaa(0x95, f(0b0000), 0x95, f(0b0000));
try testDaa(0x95, f(0b0001), 0xf5, f(0b0001));
try testDaa(0x95, f(0b0010), 0x9b, f(0b0000));
try testDaa(0x95, f(0b0011), 0xfb, f(0b0001));
try testDaa(0x95, f(0b0100), 0x95, f(0b0100));
try testDaa(0x95, f(0b0101), 0x35, f(0b0101));
try testDaa(0x95, f(0b0110), 0x8f, f(0b0100));
try testDaa(0x95, f(0b0111), 0x2f, f(0b0101));
try testDaa(0x95, f(0b1000), 0x95, f(0b0000));
try testDaa(0x95, f(0b1001), 0xf5, f(0b0001));
try testDaa(0x95, f(0b1010), 0x9b, f(0b0000));
try testDaa(0x95, f(0b1011), 0xfb, f(0b0001));
try testDaa(0x95, f(0b1100), 0x95, f(0b0100));
try testDaa(0x95, f(0b1101), 0x35, f(0b0101));
try testDaa(0x95, f(0b1110), 0x8f, f(0b0100));
try testDaa(0x95, f(0b1111), 0x2f, f(0b0101));
try testDaa(0x96, f(0b0000), 0x96, f(0b0000));
try testDaa(0x96, f(0b0001), 0xf6, f(0b0001));
try testDaa(0x96, f(0b0010), 0x9c, f(0b0000));
try testDaa(0x96, f(0b0011), 0xfc, f(0b0001));
try testDaa(0x96, f(0b0100), 0x96, f(0b0100));
try testDaa(0x96, f(0b0101), 0x36, f(0b0101));
try testDaa(0x96, f(0b0110), 0x90, f(0b0100));
try testDaa(0x96, f(0b0111), 0x30, f(0b0101));
try testDaa(0x96, f(0b1000), 0x96, f(0b0000));
try testDaa(0x96, f(0b1001), 0xf6, f(0b0001));
try testDaa(0x96, f(0b1010), 0x9c, f(0b0000));
try testDaa(0x96, f(0b1011), 0xfc, f(0b0001));
try testDaa(0x96, f(0b1100), 0x96, f(0b0100));
try testDaa(0x96, f(0b1101), 0x36, f(0b0101));
try testDaa(0x96, f(0b1110), 0x90, f(0b0100));
try testDaa(0x96, f(0b1111), 0x30, f(0b0101));
try testDaa(0x97, f(0b0000), 0x97, f(0b0000));
try testDaa(0x97, f(0b0001), 0xf7, f(0b0001));
try testDaa(0x97, f(0b0010), 0x9d, f(0b0000));
try testDaa(0x97, f(0b0011), 0xfd, f(0b0001));
try testDaa(0x97, f(0b0100), 0x97, f(0b0100));
try testDaa(0x97, f(0b0101), 0x37, f(0b0101));
try testDaa(0x97, f(0b0110), 0x91, f(0b0100));
try testDaa(0x97, f(0b0111), 0x31, f(0b0101));
try testDaa(0x97, f(0b1000), 0x97, f(0b0000));
try testDaa(0x97, f(0b1001), 0xf7, f(0b0001));
try testDaa(0x97, f(0b1010), 0x9d, f(0b0000));
try testDaa(0x97, f(0b1011), 0xfd, f(0b0001));
try testDaa(0x97, f(0b1100), 0x97, f(0b0100));
try testDaa(0x97, f(0b1101), 0x37, f(0b0101));
try testDaa(0x97, f(0b1110), 0x91, f(0b0100));
try testDaa(0x97, f(0b1111), 0x31, f(0b0101));
try testDaa(0x98, f(0b0000), 0x98, f(0b0000));
try testDaa(0x98, f(0b0001), 0xf8, f(0b0001));
try testDaa(0x98, f(0b0010), 0x9e, f(0b0000));
try testDaa(0x98, f(0b0011), 0xfe, f(0b0001));
try testDaa(0x98, f(0b0100), 0x98, f(0b0100));
try testDaa(0x98, f(0b0101), 0x38, f(0b0101));
try testDaa(0x98, f(0b0110), 0x92, f(0b0100));
try testDaa(0x98, f(0b0111), 0x32, f(0b0101));
try testDaa(0x98, f(0b1000), 0x98, f(0b0000));
try testDaa(0x98, f(0b1001), 0xf8, f(0b0001));
try testDaa(0x98, f(0b1010), 0x9e, f(0b0000));
try testDaa(0x98, f(0b1011), 0xfe, f(0b0001));
try testDaa(0x98, f(0b1100), 0x98, f(0b0100));
try testDaa(0x98, f(0b1101), 0x38, f(0b0101));
try testDaa(0x98, f(0b1110), 0x92, f(0b0100));
try testDaa(0x98, f(0b1111), 0x32, f(0b0101));
try testDaa(0x99, f(0b0000), 0x99, f(0b0000));
try testDaa(0x99, f(0b0001), 0xf9, f(0b0001));
try testDaa(0x99, f(0b0010), 0x9f, f(0b0000));
try testDaa(0x99, f(0b0011), 0xff, f(0b0001));
try testDaa(0x99, f(0b0100), 0x99, f(0b0100));
try testDaa(0x99, f(0b0101), 0x39, f(0b0101));
try testDaa(0x99, f(0b0110), 0x93, f(0b0100));
try testDaa(0x99, f(0b0111), 0x33, f(0b0101));
try testDaa(0x99, f(0b1000), 0x99, f(0b0000));
try testDaa(0x99, f(0b1001), 0xf9, f(0b0001));
try testDaa(0x99, f(0b1010), 0x9f, f(0b0000));
try testDaa(0x99, f(0b1011), 0xff, f(0b0001));
try testDaa(0x99, f(0b1100), 0x99, f(0b0100));
try testDaa(0x99, f(0b1101), 0x39, f(0b0101));
try testDaa(0x99, f(0b1110), 0x93, f(0b0100));
try testDaa(0x99, f(0b1111), 0x33, f(0b0101));
try testDaa(0x9a, f(0b0000), 0x00, f(0b1001));
try testDaa(0x9a, f(0b0001), 0x00, f(0b1001));
try testDaa(0x9a, f(0b0010), 0x00, f(0b1001));
try testDaa(0x9a, f(0b0011), 0x00, f(0b1001));
try testDaa(0x9a, f(0b0100), 0x9a, f(0b0100));
try testDaa(0x9a, f(0b0101), 0x3a, f(0b0101));
try testDaa(0x9a, f(0b0110), 0x94, f(0b0100));
try testDaa(0x9a, f(0b0111), 0x34, f(0b0101));
try testDaa(0x9a, f(0b1000), 0x00, f(0b1001));
try testDaa(0x9a, f(0b1001), 0x00, f(0b1001));
try testDaa(0x9a, f(0b1010), 0x00, f(0b1001));
try testDaa(0x9a, f(0b1011), 0x00, f(0b1001));
try testDaa(0x9a, f(0b1100), 0x9a, f(0b0100));
try testDaa(0x9a, f(0b1101), 0x3a, f(0b0101));
try testDaa(0x9a, f(0b1110), 0x94, f(0b0100));
try testDaa(0x9a, f(0b1111), 0x34, f(0b0101));
try testDaa(0x9b, f(0b0000), 0x01, f(0b0001));
try testDaa(0x9b, f(0b0001), 0x01, f(0b0001));
try testDaa(0x9b, f(0b0010), 0x01, f(0b0001));
try testDaa(0x9b, f(0b0011), 0x01, f(0b0001));
try testDaa(0x9b, f(0b0100), 0x9b, f(0b0100));
try testDaa(0x9b, f(0b0101), 0x3b, f(0b0101));
try testDaa(0x9b, f(0b0110), 0x95, f(0b0100));
try testDaa(0x9b, f(0b0111), 0x35, f(0b0101));
try testDaa(0x9b, f(0b1000), 0x01, f(0b0001));
try testDaa(0x9b, f(0b1001), 0x01, f(0b0001));
try testDaa(0x9b, f(0b1010), 0x01, f(0b0001));
try testDaa(0x9b, f(0b1011), 0x01, f(0b0001));
try testDaa(0x9b, f(0b1100), 0x9b, f(0b0100));
try testDaa(0x9b, f(0b1101), 0x3b, f(0b0101));
try testDaa(0x9b, f(0b1110), 0x95, f(0b0100));
try testDaa(0x9b, f(0b1111), 0x35, f(0b0101));
try testDaa(0x9c, f(0b0000), 0x02, f(0b0001));
try testDaa(0x9c, f(0b0001), 0x02, f(0b0001));
try testDaa(0x9c, f(0b0010), 0x02, f(0b0001));
try testDaa(0x9c, f(0b0011), 0x02, f(0b0001));
try testDaa(0x9c, f(0b0100), 0x9c, f(0b0100));
try testDaa(0x9c, f(0b0101), 0x3c, f(0b0101));
try testDaa(0x9c, f(0b0110), 0x96, f(0b0100));
try testDaa(0x9c, f(0b0111), 0x36, f(0b0101));
try testDaa(0x9c, f(0b1000), 0x02, f(0b0001));
try testDaa(0x9c, f(0b1001), 0x02, f(0b0001));
try testDaa(0x9c, f(0b1010), 0x02, f(0b0001));
try testDaa(0x9c, f(0b1011), 0x02, f(0b0001));
try testDaa(0x9c, f(0b1100), 0x9c, f(0b0100));
try testDaa(0x9c, f(0b1101), 0x3c, f(0b0101));
try testDaa(0x9c, f(0b1110), 0x96, f(0b0100));
try testDaa(0x9c, f(0b1111), 0x36, f(0b0101));
try testDaa(0x9d, f(0b0000), 0x03, f(0b0001));
try testDaa(0x9d, f(0b0001), 0x03, f(0b0001));
try testDaa(0x9d, f(0b0010), 0x03, f(0b0001));
try testDaa(0x9d, f(0b0011), 0x03, f(0b0001));
try testDaa(0x9d, f(0b0100), 0x9d, f(0b0100));
try testDaa(0x9d, f(0b0101), 0x3d, f(0b0101));
try testDaa(0x9d, f(0b0110), 0x97, f(0b0100));
try testDaa(0x9d, f(0b0111), 0x37, f(0b0101));
try testDaa(0x9d, f(0b1000), 0x03, f(0b0001));
try testDaa(0x9d, f(0b1001), 0x03, f(0b0001));
try testDaa(0x9d, f(0b1010), 0x03, f(0b0001));
try testDaa(0x9d, f(0b1011), 0x03, f(0b0001));
try testDaa(0x9d, f(0b1100), 0x9d, f(0b0100));
try testDaa(0x9d, f(0b1101), 0x3d, f(0b0101));
try testDaa(0x9d, f(0b1110), 0x97, f(0b0100));
try testDaa(0x9d, f(0b1111), 0x37, f(0b0101));
try testDaa(0x9e, f(0b0000), 0x04, f(0b0001));
try testDaa(0x9e, f(0b0001), 0x04, f(0b0001));
try testDaa(0x9e, f(0b0010), 0x04, f(0b0001));
try testDaa(0x9e, f(0b0011), 0x04, f(0b0001));
try testDaa(0x9e, f(0b0100), 0x9e, f(0b0100));
try testDaa(0x9e, f(0b0101), 0x3e, f(0b0101));
try testDaa(0x9e, f(0b0110), 0x98, f(0b0100));
try testDaa(0x9e, f(0b0111), 0x38, f(0b0101));
try testDaa(0x9e, f(0b1000), 0x04, f(0b0001));
try testDaa(0x9e, f(0b1001), 0x04, f(0b0001));
try testDaa(0x9e, f(0b1010), 0x04, f(0b0001));
try testDaa(0x9e, f(0b1011), 0x04, f(0b0001));
try testDaa(0x9e, f(0b1100), 0x9e, f(0b0100));
try testDaa(0x9e, f(0b1101), 0x3e, f(0b0101));
try testDaa(0x9e, f(0b1110), 0x98, f(0b0100));
try testDaa(0x9e, f(0b1111), 0x38, f(0b0101));
try testDaa(0x9f, f(0b0000), 0x05, f(0b0001));
try testDaa(0x9f, f(0b0001), 0x05, f(0b0001));
try testDaa(0x9f, f(0b0010), 0x05, f(0b0001));
try testDaa(0x9f, f(0b0011), 0x05, f(0b0001));
try testDaa(0x9f, f(0b0100), 0x9f, f(0b0100));
try testDaa(0x9f, f(0b0101), 0x3f, f(0b0101));
try testDaa(0x9f, f(0b0110), 0x99, f(0b0100));
try testDaa(0x9f, f(0b0111), 0x39, f(0b0101));
try testDaa(0x9f, f(0b1000), 0x05, f(0b0001));
try testDaa(0x9f, f(0b1001), 0x05, f(0b0001));
try testDaa(0x9f, f(0b1010), 0x05, f(0b0001));
try testDaa(0x9f, f(0b1011), 0x05, f(0b0001));
try testDaa(0x9f, f(0b1100), 0x9f, f(0b0100));
try testDaa(0x9f, f(0b1101), 0x3f, f(0b0101));
try testDaa(0x9f, f(0b1110), 0x99, f(0b0100));
try testDaa(0x9f, f(0b1111), 0x39, f(0b0101));
try testDaa(0xa0, f(0b0000), 0x00, f(0b1001));
try testDaa(0xa0, f(0b0001), 0x00, f(0b1001));
try testDaa(0xa0, f(0b0010), 0x06, f(0b0001));
try testDaa(0xa0, f(0b0011), 0x06, f(0b0001));
try testDaa(0xa0, f(0b0100), 0xa0, f(0b0100));
try testDaa(0xa0, f(0b0101), 0x40, f(0b0101));
try testDaa(0xa0, f(0b0110), 0x9a, f(0b0100));
try testDaa(0xa0, f(0b0111), 0x3a, f(0b0101));
try testDaa(0xa0, f(0b1000), 0x00, f(0b1001));
try testDaa(0xa0, f(0b1001), 0x00, f(0b1001));
try testDaa(0xa0, f(0b1010), 0x06, f(0b0001));
try testDaa(0xa0, f(0b1011), 0x06, f(0b0001));
try testDaa(0xa0, f(0b1100), 0xa0, f(0b0100));
try testDaa(0xa0, f(0b1101), 0x40, f(0b0101));
try testDaa(0xa0, f(0b1110), 0x9a, f(0b0100));
try testDaa(0xa0, f(0b1111), 0x3a, f(0b0101));
try testDaa(0xa1, f(0b0000), 0x01, f(0b0001));
try testDaa(0xa1, f(0b0001), 0x01, f(0b0001));
try testDaa(0xa1, f(0b0010), 0x07, f(0b0001));
try testDaa(0xa1, f(0b0011), 0x07, f(0b0001));
try testDaa(0xa1, f(0b0100), 0xa1, f(0b0100));
try testDaa(0xa1, f(0b0101), 0x41, f(0b0101));
try testDaa(0xa1, f(0b0110), 0x9b, f(0b0100));
try testDaa(0xa1, f(0b0111), 0x3b, f(0b0101));
try testDaa(0xa1, f(0b1000), 0x01, f(0b0001));
try testDaa(0xa1, f(0b1001), 0x01, f(0b0001));
try testDaa(0xa1, f(0b1010), 0x07, f(0b0001));
try testDaa(0xa1, f(0b1011), 0x07, f(0b0001));
try testDaa(0xa1, f(0b1100), 0xa1, f(0b0100));
try testDaa(0xa1, f(0b1101), 0x41, f(0b0101));
try testDaa(0xa1, f(0b1110), 0x9b, f(0b0100));
try testDaa(0xa1, f(0b1111), 0x3b, f(0b0101));
try testDaa(0xa2, f(0b0000), 0x02, f(0b0001));
try testDaa(0xa2, f(0b0001), 0x02, f(0b0001));
try testDaa(0xa2, f(0b0010), 0x08, f(0b0001));
try testDaa(0xa2, f(0b0011), 0x08, f(0b0001));
try testDaa(0xa2, f(0b0100), 0xa2, f(0b0100));
try testDaa(0xa2, f(0b0101), 0x42, f(0b0101));
try testDaa(0xa2, f(0b0110), 0x9c, f(0b0100));
try testDaa(0xa2, f(0b0111), 0x3c, f(0b0101));
try testDaa(0xa2, f(0b1000), 0x02, f(0b0001));
try testDaa(0xa2, f(0b1001), 0x02, f(0b0001));
try testDaa(0xa2, f(0b1010), 0x08, f(0b0001));
try testDaa(0xa2, f(0b1011), 0x08, f(0b0001));
try testDaa(0xa2, f(0b1100), 0xa2, f(0b0100));
try testDaa(0xa2, f(0b1101), 0x42, f(0b0101));
try testDaa(0xa2, f(0b1110), 0x9c, f(0b0100));
try testDaa(0xa2, f(0b1111), 0x3c, f(0b0101));
try testDaa(0xa3, f(0b0000), 0x03, f(0b0001));
try testDaa(0xa3, f(0b0001), 0x03, f(0b0001));
try testDaa(0xa3, f(0b0010), 0x09, f(0b0001));
try testDaa(0xa3, f(0b0011), 0x09, f(0b0001));
try testDaa(0xa3, f(0b0100), 0xa3, f(0b0100));
try testDaa(0xa3, f(0b0101), 0x43, f(0b0101));
try testDaa(0xa3, f(0b0110), 0x9d, f(0b0100));
try testDaa(0xa3, f(0b0111), 0x3d, f(0b0101));
try testDaa(0xa3, f(0b1000), 0x03, f(0b0001));
try testDaa(0xa3, f(0b1001), 0x03, f(0b0001));
try testDaa(0xa3, f(0b1010), 0x09, f(0b0001));
try testDaa(0xa3, f(0b1011), 0x09, f(0b0001));
try testDaa(0xa3, f(0b1100), 0xa3, f(0b0100));
try testDaa(0xa3, f(0b1101), 0x43, f(0b0101));
try testDaa(0xa3, f(0b1110), 0x9d, f(0b0100));
try testDaa(0xa3, f(0b1111), 0x3d, f(0b0101));
try testDaa(0xa4, f(0b0000), 0x04, f(0b0001));
try testDaa(0xa4, f(0b0001), 0x04, f(0b0001));
try testDaa(0xa4, f(0b0010), 0x0a, f(0b0001));
try testDaa(0xa4, f(0b0011), 0x0a, f(0b0001));
try testDaa(0xa4, f(0b0100), 0xa4, f(0b0100));
try testDaa(0xa4, f(0b0101), 0x44, f(0b0101));
try testDaa(0xa4, f(0b0110), 0x9e, f(0b0100));
try testDaa(0xa4, f(0b0111), 0x3e, f(0b0101));
try testDaa(0xa4, f(0b1000), 0x04, f(0b0001));
try testDaa(0xa4, f(0b1001), 0x04, f(0b0001));
try testDaa(0xa4, f(0b1010), 0x0a, f(0b0001));
try testDaa(0xa4, f(0b1011), 0x0a, f(0b0001));
try testDaa(0xa4, f(0b1100), 0xa4, f(0b0100));
try testDaa(0xa4, f(0b1101), 0x44, f(0b0101));
try testDaa(0xa4, f(0b1110), 0x9e, f(0b0100));
try testDaa(0xa4, f(0b1111), 0x3e, f(0b0101));
try testDaa(0xa5, f(0b0000), 0x05, f(0b0001));
try testDaa(0xa5, f(0b0001), 0x05, f(0b0001));
try testDaa(0xa5, f(0b0010), 0x0b, f(0b0001));
try testDaa(0xa5, f(0b0011), 0x0b, f(0b0001));
try testDaa(0xa5, f(0b0100), 0xa5, f(0b0100));
try testDaa(0xa5, f(0b0101), 0x45, f(0b0101));
try testDaa(0xa5, f(0b0110), 0x9f, f(0b0100));
try testDaa(0xa5, f(0b0111), 0x3f, f(0b0101));
try testDaa(0xa5, f(0b1000), 0x05, f(0b0001));
try testDaa(0xa5, f(0b1001), 0x05, f(0b0001));
try testDaa(0xa5, f(0b1010), 0x0b, f(0b0001));
try testDaa(0xa5, f(0b1011), 0x0b, f(0b0001));
try testDaa(0xa5, f(0b1100), 0xa5, f(0b0100));
try testDaa(0xa5, f(0b1101), 0x45, f(0b0101));
try testDaa(0xa5, f(0b1110), 0x9f, f(0b0100));
try testDaa(0xa5, f(0b1111), 0x3f, f(0b0101));
try testDaa(0xa6, f(0b0000), 0x06, f(0b0001));
try testDaa(0xa6, f(0b0001), 0x06, f(0b0001));
try testDaa(0xa6, f(0b0010), 0x0c, f(0b0001));
try testDaa(0xa6, f(0b0011), 0x0c, f(0b0001));
try testDaa(0xa6, f(0b0100), 0xa6, f(0b0100));
try testDaa(0xa6, f(0b0101), 0x46, f(0b0101));
try testDaa(0xa6, f(0b0110), 0xa0, f(0b0100));
try testDaa(0xa6, f(0b0111), 0x40, f(0b0101));
try testDaa(0xa6, f(0b1000), 0x06, f(0b0001));
try testDaa(0xa6, f(0b1001), 0x06, f(0b0001));
try testDaa(0xa6, f(0b1010), 0x0c, f(0b0001));
try testDaa(0xa6, f(0b1011), 0x0c, f(0b0001));
try testDaa(0xa6, f(0b1100), 0xa6, f(0b0100));
try testDaa(0xa6, f(0b1101), 0x46, f(0b0101));
try testDaa(0xa6, f(0b1110), 0xa0, f(0b0100));
try testDaa(0xa6, f(0b1111), 0x40, f(0b0101));
try testDaa(0xa7, f(0b0000), 0x07, f(0b0001));
try testDaa(0xa7, f(0b0001), 0x07, f(0b0001));
try testDaa(0xa7, f(0b0010), 0x0d, f(0b0001));
try testDaa(0xa7, f(0b0011), 0x0d, f(0b0001));
try testDaa(0xa7, f(0b0100), 0xa7, f(0b0100));
try testDaa(0xa7, f(0b0101), 0x47, f(0b0101));
try testDaa(0xa7, f(0b0110), 0xa1, f(0b0100));
try testDaa(0xa7, f(0b0111), 0x41, f(0b0101));
try testDaa(0xa7, f(0b1000), 0x07, f(0b0001));
try testDaa(0xa7, f(0b1001), 0x07, f(0b0001));
try testDaa(0xa7, f(0b1010), 0x0d, f(0b0001));
try testDaa(0xa7, f(0b1011), 0x0d, f(0b0001));
try testDaa(0xa7, f(0b1100), 0xa7, f(0b0100));
try testDaa(0xa7, f(0b1101), 0x47, f(0b0101));
try testDaa(0xa7, f(0b1110), 0xa1, f(0b0100));
try testDaa(0xa7, f(0b1111), 0x41, f(0b0101));
try testDaa(0xa8, f(0b0000), 0x08, f(0b0001));
try testDaa(0xa8, f(0b0001), 0x08, f(0b0001));
try testDaa(0xa8, f(0b0010), 0x0e, f(0b0001));
try testDaa(0xa8, f(0b0011), 0x0e, f(0b0001));
try testDaa(0xa8, f(0b0100), 0xa8, f(0b0100));
try testDaa(0xa8, f(0b0101), 0x48, f(0b0101));
try testDaa(0xa8, f(0b0110), 0xa2, f(0b0100));
try testDaa(0xa8, f(0b0111), 0x42, f(0b0101));
try testDaa(0xa8, f(0b1000), 0x08, f(0b0001));
try testDaa(0xa8, f(0b1001), 0x08, f(0b0001));
try testDaa(0xa8, f(0b1010), 0x0e, f(0b0001));
try testDaa(0xa8, f(0b1011), 0x0e, f(0b0001));
try testDaa(0xa8, f(0b1100), 0xa8, f(0b0100));
try testDaa(0xa8, f(0b1101), 0x48, f(0b0101));
try testDaa(0xa8, f(0b1110), 0xa2, f(0b0100));
try testDaa(0xa8, f(0b1111), 0x42, f(0b0101));
try testDaa(0xa9, f(0b0000), 0x09, f(0b0001));
try testDaa(0xa9, f(0b0001), 0x09, f(0b0001));
try testDaa(0xa9, f(0b0010), 0x0f, f(0b0001));
try testDaa(0xa9, f(0b0011), 0x0f, f(0b0001));
try testDaa(0xa9, f(0b0100), 0xa9, f(0b0100));
try testDaa(0xa9, f(0b0101), 0x49, f(0b0101));
try testDaa(0xa9, f(0b0110), 0xa3, f(0b0100));
try testDaa(0xa9, f(0b0111), 0x43, f(0b0101));
try testDaa(0xa9, f(0b1000), 0x09, f(0b0001));
try testDaa(0xa9, f(0b1001), 0x09, f(0b0001));
try testDaa(0xa9, f(0b1010), 0x0f, f(0b0001));
try testDaa(0xa9, f(0b1011), 0x0f, f(0b0001));
try testDaa(0xa9, f(0b1100), 0xa9, f(0b0100));
try testDaa(0xa9, f(0b1101), 0x49, f(0b0101));
try testDaa(0xa9, f(0b1110), 0xa3, f(0b0100));
try testDaa(0xa9, f(0b1111), 0x43, f(0b0101));
try testDaa(0xaa, f(0b0000), 0x10, f(0b0001));
try testDaa(0xaa, f(0b0001), 0x10, f(0b0001));
try testDaa(0xaa, f(0b0010), 0x10, f(0b0001));
try testDaa(0xaa, f(0b0011), 0x10, f(0b0001));
try testDaa(0xaa, f(0b0100), 0xaa, f(0b0100));
try testDaa(0xaa, f(0b0101), 0x4a, f(0b0101));
try testDaa(0xaa, f(0b0110), 0xa4, f(0b0100));
try testDaa(0xaa, f(0b0111), 0x44, f(0b0101));
try testDaa(0xaa, f(0b1000), 0x10, f(0b0001));
try testDaa(0xaa, f(0b1001), 0x10, f(0b0001));
try testDaa(0xaa, f(0b1010), 0x10, f(0b0001));
try testDaa(0xaa, f(0b1011), 0x10, f(0b0001));
try testDaa(0xaa, f(0b1100), 0xaa, f(0b0100));
try testDaa(0xaa, f(0b1101), 0x4a, f(0b0101));
try testDaa(0xaa, f(0b1110), 0xa4, f(0b0100));
try testDaa(0xaa, f(0b1111), 0x44, f(0b0101));
try testDaa(0xab, f(0b0000), 0x11, f(0b0001));
try testDaa(0xab, f(0b0001), 0x11, f(0b0001));
try testDaa(0xab, f(0b0010), 0x11, f(0b0001));
try testDaa(0xab, f(0b0011), 0x11, f(0b0001));
try testDaa(0xab, f(0b0100), 0xab, f(0b0100));
try testDaa(0xab, f(0b0101), 0x4b, f(0b0101));
try testDaa(0xab, f(0b0110), 0xa5, f(0b0100));
try testDaa(0xab, f(0b0111), 0x45, f(0b0101));
try testDaa(0xab, f(0b1000), 0x11, f(0b0001));
try testDaa(0xab, f(0b1001), 0x11, f(0b0001));
try testDaa(0xab, f(0b1010), 0x11, f(0b0001));
try testDaa(0xab, f(0b1011), 0x11, f(0b0001));
try testDaa(0xab, f(0b1100), 0xab, f(0b0100));
try testDaa(0xab, f(0b1101), 0x4b, f(0b0101));
try testDaa(0xab, f(0b1110), 0xa5, f(0b0100));
try testDaa(0xab, f(0b1111), 0x45, f(0b0101));
try testDaa(0xac, f(0b0000), 0x12, f(0b0001));
try testDaa(0xac, f(0b0001), 0x12, f(0b0001));
try testDaa(0xac, f(0b0010), 0x12, f(0b0001));
try testDaa(0xac, f(0b0011), 0x12, f(0b0001));
try testDaa(0xac, f(0b0100), 0xac, f(0b0100));
try testDaa(0xac, f(0b0101), 0x4c, f(0b0101));
try testDaa(0xac, f(0b0110), 0xa6, f(0b0100));
try testDaa(0xac, f(0b0111), 0x46, f(0b0101));
try testDaa(0xac, f(0b1000), 0x12, f(0b0001));
try testDaa(0xac, f(0b1001), 0x12, f(0b0001));
try testDaa(0xac, f(0b1010), 0x12, f(0b0001));
try testDaa(0xac, f(0b1011), 0x12, f(0b0001));
try testDaa(0xac, f(0b1100), 0xac, f(0b0100));
try testDaa(0xac, f(0b1101), 0x4c, f(0b0101));
try testDaa(0xac, f(0b1110), 0xa6, f(0b0100));
try testDaa(0xac, f(0b1111), 0x46, f(0b0101));
try testDaa(0xad, f(0b0000), 0x13, f(0b0001));
try testDaa(0xad, f(0b0001), 0x13, f(0b0001));
try testDaa(0xad, f(0b0010), 0x13, f(0b0001));
try testDaa(0xad, f(0b0011), 0x13, f(0b0001));
try testDaa(0xad, f(0b0100), 0xad, f(0b0100));
try testDaa(0xad, f(0b0101), 0x4d, f(0b0101));
try testDaa(0xad, f(0b0110), 0xa7, f(0b0100));
try testDaa(0xad, f(0b0111), 0x47, f(0b0101));
try testDaa(0xad, f(0b1000), 0x13, f(0b0001));
try testDaa(0xad, f(0b1001), 0x13, f(0b0001));
try testDaa(0xad, f(0b1010), 0x13, f(0b0001));
try testDaa(0xad, f(0b1011), 0x13, f(0b0001));
try testDaa(0xad, f(0b1100), 0xad, f(0b0100));
try testDaa(0xad, f(0b1101), 0x4d, f(0b0101));
try testDaa(0xad, f(0b1110), 0xa7, f(0b0100));
try testDaa(0xad, f(0b1111), 0x47, f(0b0101));
try testDaa(0xae, f(0b0000), 0x14, f(0b0001));
try testDaa(0xae, f(0b0001), 0x14, f(0b0001));
try testDaa(0xae, f(0b0010), 0x14, f(0b0001));
try testDaa(0xae, f(0b0011), 0x14, f(0b0001));
try testDaa(0xae, f(0b0100), 0xae, f(0b0100));
try testDaa(0xae, f(0b0101), 0x4e, f(0b0101));
try testDaa(0xae, f(0b0110), 0xa8, f(0b0100));
try testDaa(0xae, f(0b0111), 0x48, f(0b0101));
try testDaa(0xae, f(0b1000), 0x14, f(0b0001));
try testDaa(0xae, f(0b1001), 0x14, f(0b0001));
try testDaa(0xae, f(0b1010), 0x14, f(0b0001));
try testDaa(0xae, f(0b1011), 0x14, f(0b0001));
try testDaa(0xae, f(0b1100), 0xae, f(0b0100));
try testDaa(0xae, f(0b1101), 0x4e, f(0b0101));
try testDaa(0xae, f(0b1110), 0xa8, f(0b0100));
try testDaa(0xae, f(0b1111), 0x48, f(0b0101));
try testDaa(0xaf, f(0b0000), 0x15, f(0b0001));
try testDaa(0xaf, f(0b0001), 0x15, f(0b0001));
try testDaa(0xaf, f(0b0010), 0x15, f(0b0001));
try testDaa(0xaf, f(0b0011), 0x15, f(0b0001));
try testDaa(0xaf, f(0b0100), 0xaf, f(0b0100));
try testDaa(0xaf, f(0b0101), 0x4f, f(0b0101));
try testDaa(0xaf, f(0b0110), 0xa9, f(0b0100));
try testDaa(0xaf, f(0b0111), 0x49, f(0b0101));
try testDaa(0xaf, f(0b1000), 0x15, f(0b0001));
try testDaa(0xaf, f(0b1001), 0x15, f(0b0001));
try testDaa(0xaf, f(0b1010), 0x15, f(0b0001));
try testDaa(0xaf, f(0b1011), 0x15, f(0b0001));
try testDaa(0xaf, f(0b1100), 0xaf, f(0b0100));
try testDaa(0xaf, f(0b1101), 0x4f, f(0b0101));
try testDaa(0xaf, f(0b1110), 0xa9, f(0b0100));
try testDaa(0xaf, f(0b1111), 0x49, f(0b0101));
try testDaa(0xb0, f(0b0000), 0x10, f(0b0001));
try testDaa(0xb0, f(0b0001), 0x10, f(0b0001));
try testDaa(0xb0, f(0b0010), 0x16, f(0b0001));
try testDaa(0xb0, f(0b0011), 0x16, f(0b0001));
try testDaa(0xb0, f(0b0100), 0xb0, f(0b0100));
try testDaa(0xb0, f(0b0101), 0x50, f(0b0101));
try testDaa(0xb0, f(0b0110), 0xaa, f(0b0100));
try testDaa(0xb0, f(0b0111), 0x4a, f(0b0101));
try testDaa(0xb0, f(0b1000), 0x10, f(0b0001));
try testDaa(0xb0, f(0b1001), 0x10, f(0b0001));
try testDaa(0xb0, f(0b1010), 0x16, f(0b0001));
try testDaa(0xb0, f(0b1011), 0x16, f(0b0001));
try testDaa(0xb0, f(0b1100), 0xb0, f(0b0100));
try testDaa(0xb0, f(0b1101), 0x50, f(0b0101));
try testDaa(0xb0, f(0b1110), 0xaa, f(0b0100));
try testDaa(0xb0, f(0b1111), 0x4a, f(0b0101));
try testDaa(0xb1, f(0b0000), 0x11, f(0b0001));
try testDaa(0xb1, f(0b0001), 0x11, f(0b0001));
try testDaa(0xb1, f(0b0010), 0x17, f(0b0001));
try testDaa(0xb1, f(0b0011), 0x17, f(0b0001));
try testDaa(0xb1, f(0b0100), 0xb1, f(0b0100));
try testDaa(0xb1, f(0b0101), 0x51, f(0b0101));
try testDaa(0xb1, f(0b0110), 0xab, f(0b0100));
try testDaa(0xb1, f(0b0111), 0x4b, f(0b0101));
try testDaa(0xb1, f(0b1000), 0x11, f(0b0001));
try testDaa(0xb1, f(0b1001), 0x11, f(0b0001));
try testDaa(0xb1, f(0b1010), 0x17, f(0b0001));
try testDaa(0xb1, f(0b1011), 0x17, f(0b0001));
try testDaa(0xb1, f(0b1100), 0xb1, f(0b0100));
try testDaa(0xb1, f(0b1101), 0x51, f(0b0101));
try testDaa(0xb1, f(0b1110), 0xab, f(0b0100));
try testDaa(0xb1, f(0b1111), 0x4b, f(0b0101));
try testDaa(0xb2, f(0b0000), 0x12, f(0b0001));
try testDaa(0xb2, f(0b0001), 0x12, f(0b0001));
try testDaa(0xb2, f(0b0010), 0x18, f(0b0001));
try testDaa(0xb2, f(0b0011), 0x18, f(0b0001));
try testDaa(0xb2, f(0b0100), 0xb2, f(0b0100));
try testDaa(0xb2, f(0b0101), 0x52, f(0b0101));
try testDaa(0xb2, f(0b0110), 0xac, f(0b0100));
try testDaa(0xb2, f(0b0111), 0x4c, f(0b0101));
try testDaa(0xb2, f(0b1000), 0x12, f(0b0001));
try testDaa(0xb2, f(0b1001), 0x12, f(0b0001));
try testDaa(0xb2, f(0b1010), 0x18, f(0b0001));
try testDaa(0xb2, f(0b1011), 0x18, f(0b0001));
try testDaa(0xb2, f(0b1100), 0xb2, f(0b0100));
try testDaa(0xb2, f(0b1101), 0x52, f(0b0101));
try testDaa(0xb2, f(0b1110), 0xac, f(0b0100));
try testDaa(0xb2, f(0b1111), 0x4c, f(0b0101));
try testDaa(0xb3, f(0b0000), 0x13, f(0b0001));
try testDaa(0xb3, f(0b0001), 0x13, f(0b0001));
try testDaa(0xb3, f(0b0010), 0x19, f(0b0001));
try testDaa(0xb3, f(0b0011), 0x19, f(0b0001));
try testDaa(0xb3, f(0b0100), 0xb3, f(0b0100));
try testDaa(0xb3, f(0b0101), 0x53, f(0b0101));
try testDaa(0xb3, f(0b0110), 0xad, f(0b0100));
try testDaa(0xb3, f(0b0111), 0x4d, f(0b0101));
try testDaa(0xb3, f(0b1000), 0x13, f(0b0001));
try testDaa(0xb3, f(0b1001), 0x13, f(0b0001));
try testDaa(0xb3, f(0b1010), 0x19, f(0b0001));
try testDaa(0xb3, f(0b1011), 0x19, f(0b0001));
try testDaa(0xb3, f(0b1100), 0xb3, f(0b0100));
try testDaa(0xb3, f(0b1101), 0x53, f(0b0101));
try testDaa(0xb3, f(0b1110), 0xad, f(0b0100));
try testDaa(0xb3, f(0b1111), 0x4d, f(0b0101));
try testDaa(0xb4, f(0b0000), 0x14, f(0b0001));
try testDaa(0xb4, f(0b0001), 0x14, f(0b0001));
try testDaa(0xb4, f(0b0010), 0x1a, f(0b0001));
try testDaa(0xb4, f(0b0011), 0x1a, f(0b0001));
try testDaa(0xb4, f(0b0100), 0xb4, f(0b0100));
try testDaa(0xb4, f(0b0101), 0x54, f(0b0101));
try testDaa(0xb4, f(0b0110), 0xae, f(0b0100));
try testDaa(0xb4, f(0b0111), 0x4e, f(0b0101));
try testDaa(0xb4, f(0b1000), 0x14, f(0b0001));
try testDaa(0xb4, f(0b1001), 0x14, f(0b0001));
try testDaa(0xb4, f(0b1010), 0x1a, f(0b0001));
try testDaa(0xb4, f(0b1011), 0x1a, f(0b0001));
try testDaa(0xb4, f(0b1100), 0xb4, f(0b0100));
try testDaa(0xb4, f(0b1101), 0x54, f(0b0101));
try testDaa(0xb4, f(0b1110), 0xae, f(0b0100));
try testDaa(0xb4, f(0b1111), 0x4e, f(0b0101));
try testDaa(0xb5, f(0b0000), 0x15, f(0b0001));
try testDaa(0xb5, f(0b0001), 0x15, f(0b0001));
try testDaa(0xb5, f(0b0010), 0x1b, f(0b0001));
try testDaa(0xb5, f(0b0011), 0x1b, f(0b0001));
try testDaa(0xb5, f(0b0100), 0xb5, f(0b0100));
try testDaa(0xb5, f(0b0101), 0x55, f(0b0101));
try testDaa(0xb5, f(0b0110), 0xaf, f(0b0100));
try testDaa(0xb5, f(0b0111), 0x4f, f(0b0101));
try testDaa(0xb5, f(0b1000), 0x15, f(0b0001));
try testDaa(0xb5, f(0b1001), 0x15, f(0b0001));
try testDaa(0xb5, f(0b1010), 0x1b, f(0b0001));
try testDaa(0xb5, f(0b1011), 0x1b, f(0b0001));
try testDaa(0xb5, f(0b1100), 0xb5, f(0b0100));
try testDaa(0xb5, f(0b1101), 0x55, f(0b0101));
try testDaa(0xb5, f(0b1110), 0xaf, f(0b0100));
try testDaa(0xb5, f(0b1111), 0x4f, f(0b0101));
try testDaa(0xb6, f(0b0000), 0x16, f(0b0001));
try testDaa(0xb6, f(0b0001), 0x16, f(0b0001));
try testDaa(0xb6, f(0b0010), 0x1c, f(0b0001));
try testDaa(0xb6, f(0b0011), 0x1c, f(0b0001));
try testDaa(0xb6, f(0b0100), 0xb6, f(0b0100));
try testDaa(0xb6, f(0b0101), 0x56, f(0b0101));
try testDaa(0xb6, f(0b0110), 0xb0, f(0b0100));
try testDaa(0xb6, f(0b0111), 0x50, f(0b0101));
try testDaa(0xb6, f(0b1000), 0x16, f(0b0001));
try testDaa(0xb6, f(0b1001), 0x16, f(0b0001));
try testDaa(0xb6, f(0b1010), 0x1c, f(0b0001));
try testDaa(0xb6, f(0b1011), 0x1c, f(0b0001));
try testDaa(0xb6, f(0b1100), 0xb6, f(0b0100));
try testDaa(0xb6, f(0b1101), 0x56, f(0b0101));
try testDaa(0xb6, f(0b1110), 0xb0, f(0b0100));
try testDaa(0xb6, f(0b1111), 0x50, f(0b0101));
try testDaa(0xb7, f(0b0000), 0x17, f(0b0001));
try testDaa(0xb7, f(0b0001), 0x17, f(0b0001));
try testDaa(0xb7, f(0b0010), 0x1d, f(0b0001));
try testDaa(0xb7, f(0b0011), 0x1d, f(0b0001));
try testDaa(0xb7, f(0b0100), 0xb7, f(0b0100));
try testDaa(0xb7, f(0b0101), 0x57, f(0b0101));
try testDaa(0xb7, f(0b0110), 0xb1, f(0b0100));
try testDaa(0xb7, f(0b0111), 0x51, f(0b0101));
try testDaa(0xb7, f(0b1000), 0x17, f(0b0001));
try testDaa(0xb7, f(0b1001), 0x17, f(0b0001));
try testDaa(0xb7, f(0b1010), 0x1d, f(0b0001));
try testDaa(0xb7, f(0b1011), 0x1d, f(0b0001));
try testDaa(0xb7, f(0b1100), 0xb7, f(0b0100));
try testDaa(0xb7, f(0b1101), 0x57, f(0b0101));
try testDaa(0xb7, f(0b1110), 0xb1, f(0b0100));
try testDaa(0xb7, f(0b1111), 0x51, f(0b0101));
try testDaa(0xb8, f(0b0000), 0x18, f(0b0001));
try testDaa(0xb8, f(0b0001), 0x18, f(0b0001));
try testDaa(0xb8, f(0b0010), 0x1e, f(0b0001));
try testDaa(0xb8, f(0b0011), 0x1e, f(0b0001));
try testDaa(0xb8, f(0b0100), 0xb8, f(0b0100));
try testDaa(0xb8, f(0b0101), 0x58, f(0b0101));
try testDaa(0xb8, f(0b0110), 0xb2, f(0b0100));
try testDaa(0xb8, f(0b0111), 0x52, f(0b0101));
try testDaa(0xb8, f(0b1000), 0x18, f(0b0001));
try testDaa(0xb8, f(0b1001), 0x18, f(0b0001));
try testDaa(0xb8, f(0b1010), 0x1e, f(0b0001));
try testDaa(0xb8, f(0b1011), 0x1e, f(0b0001));
try testDaa(0xb8, f(0b1100), 0xb8, f(0b0100));
try testDaa(0xb8, f(0b1101), 0x58, f(0b0101));
try testDaa(0xb8, f(0b1110), 0xb2, f(0b0100));
try testDaa(0xb8, f(0b1111), 0x52, f(0b0101));
try testDaa(0xb9, f(0b0000), 0x19, f(0b0001));
try testDaa(0xb9, f(0b0001), 0x19, f(0b0001));
try testDaa(0xb9, f(0b0010), 0x1f, f(0b0001));
try testDaa(0xb9, f(0b0011), 0x1f, f(0b0001));
try testDaa(0xb9, f(0b0100), 0xb9, f(0b0100));
try testDaa(0xb9, f(0b0101), 0x59, f(0b0101));
try testDaa(0xb9, f(0b0110), 0xb3, f(0b0100));
try testDaa(0xb9, f(0b0111), 0x53, f(0b0101));
try testDaa(0xb9, f(0b1000), 0x19, f(0b0001));
try testDaa(0xb9, f(0b1001), 0x19, f(0b0001));
try testDaa(0xb9, f(0b1010), 0x1f, f(0b0001));
try testDaa(0xb9, f(0b1011), 0x1f, f(0b0001));
try testDaa(0xb9, f(0b1100), 0xb9, f(0b0100));
try testDaa(0xb9, f(0b1101), 0x59, f(0b0101));
try testDaa(0xb9, f(0b1110), 0xb3, f(0b0100));
try testDaa(0xb9, f(0b1111), 0x53, f(0b0101));
try testDaa(0xba, f(0b0000), 0x20, f(0b0001));
try testDaa(0xba, f(0b0001), 0x20, f(0b0001));
try testDaa(0xba, f(0b0010), 0x20, f(0b0001));
try testDaa(0xba, f(0b0011), 0x20, f(0b0001));
try testDaa(0xba, f(0b0100), 0xba, f(0b0100));
try testDaa(0xba, f(0b0101), 0x5a, f(0b0101));
try testDaa(0xba, f(0b0110), 0xb4, f(0b0100));
try testDaa(0xba, f(0b0111), 0x54, f(0b0101));
try testDaa(0xba, f(0b1000), 0x20, f(0b0001));
try testDaa(0xba, f(0b1001), 0x20, f(0b0001));
try testDaa(0xba, f(0b1010), 0x20, f(0b0001));
try testDaa(0xba, f(0b1011), 0x20, f(0b0001));
try testDaa(0xba, f(0b1100), 0xba, f(0b0100));
try testDaa(0xba, f(0b1101), 0x5a, f(0b0101));
try testDaa(0xba, f(0b1110), 0xb4, f(0b0100));
try testDaa(0xba, f(0b1111), 0x54, f(0b0101));
try testDaa(0xbb, f(0b0000), 0x21, f(0b0001));
try testDaa(0xbb, f(0b0001), 0x21, f(0b0001));
try testDaa(0xbb, f(0b0010), 0x21, f(0b0001));
try testDaa(0xbb, f(0b0011), 0x21, f(0b0001));
try testDaa(0xbb, f(0b0100), 0xbb, f(0b0100));
try testDaa(0xbb, f(0b0101), 0x5b, f(0b0101));
try testDaa(0xbb, f(0b0110), 0xb5, f(0b0100));
try testDaa(0xbb, f(0b0111), 0x55, f(0b0101));
try testDaa(0xbb, f(0b1000), 0x21, f(0b0001));
try testDaa(0xbb, f(0b1001), 0x21, f(0b0001));
try testDaa(0xbb, f(0b1010), 0x21, f(0b0001));
try testDaa(0xbb, f(0b1011), 0x21, f(0b0001));
try testDaa(0xbb, f(0b1100), 0xbb, f(0b0100));
try testDaa(0xbb, f(0b1101), 0x5b, f(0b0101));
try testDaa(0xbb, f(0b1110), 0xb5, f(0b0100));
try testDaa(0xbb, f(0b1111), 0x55, f(0b0101));
try testDaa(0xbc, f(0b0000), 0x22, f(0b0001));
try testDaa(0xbc, f(0b0001), 0x22, f(0b0001));
try testDaa(0xbc, f(0b0010), 0x22, f(0b0001));
try testDaa(0xbc, f(0b0011), 0x22, f(0b0001));
try testDaa(0xbc, f(0b0100), 0xbc, f(0b0100));
try testDaa(0xbc, f(0b0101), 0x5c, f(0b0101));
try testDaa(0xbc, f(0b0110), 0xb6, f(0b0100));
try testDaa(0xbc, f(0b0111), 0x56, f(0b0101));
try testDaa(0xbc, f(0b1000), 0x22, f(0b0001));
try testDaa(0xbc, f(0b1001), 0x22, f(0b0001));
try testDaa(0xbc, f(0b1010), 0x22, f(0b0001));
try testDaa(0xbc, f(0b1011), 0x22, f(0b0001));
try testDaa(0xbc, f(0b1100), 0xbc, f(0b0100));
try testDaa(0xbc, f(0b1101), 0x5c, f(0b0101));
try testDaa(0xbc, f(0b1110), 0xb6, f(0b0100));
try testDaa(0xbc, f(0b1111), 0x56, f(0b0101));
try testDaa(0xbd, f(0b0000), 0x23, f(0b0001));
try testDaa(0xbd, f(0b0001), 0x23, f(0b0001));
try testDaa(0xbd, f(0b0010), 0x23, f(0b0001));
try testDaa(0xbd, f(0b0011), 0x23, f(0b0001));
try testDaa(0xbd, f(0b0100), 0xbd, f(0b0100));
try testDaa(0xbd, f(0b0101), 0x5d, f(0b0101));
try testDaa(0xbd, f(0b0110), 0xb7, f(0b0100));
try testDaa(0xbd, f(0b0111), 0x57, f(0b0101));
try testDaa(0xbd, f(0b1000), 0x23, f(0b0001));
try testDaa(0xbd, f(0b1001), 0x23, f(0b0001));
try testDaa(0xbd, f(0b1010), 0x23, f(0b0001));
try testDaa(0xbd, f(0b1011), 0x23, f(0b0001));
try testDaa(0xbd, f(0b1100), 0xbd, f(0b0100));
try testDaa(0xbd, f(0b1101), 0x5d, f(0b0101));
try testDaa(0xbd, f(0b1110), 0xb7, f(0b0100));
try testDaa(0xbd, f(0b1111), 0x57, f(0b0101));
try testDaa(0xbe, f(0b0000), 0x24, f(0b0001));
try testDaa(0xbe, f(0b0001), 0x24, f(0b0001));
try testDaa(0xbe, f(0b0010), 0x24, f(0b0001));
try testDaa(0xbe, f(0b0011), 0x24, f(0b0001));
try testDaa(0xbe, f(0b0100), 0xbe, f(0b0100));
try testDaa(0xbe, f(0b0101), 0x5e, f(0b0101));
try testDaa(0xbe, f(0b0110), 0xb8, f(0b0100));
try testDaa(0xbe, f(0b0111), 0x58, f(0b0101));
try testDaa(0xbe, f(0b1000), 0x24, f(0b0001));
try testDaa(0xbe, f(0b1001), 0x24, f(0b0001));
try testDaa(0xbe, f(0b1010), 0x24, f(0b0001));
try testDaa(0xbe, f(0b1011), 0x24, f(0b0001));
try testDaa(0xbe, f(0b1100), 0xbe, f(0b0100));
try testDaa(0xbe, f(0b1101), 0x5e, f(0b0101));
try testDaa(0xbe, f(0b1110), 0xb8, f(0b0100));
try testDaa(0xbe, f(0b1111), 0x58, f(0b0101));
try testDaa(0xbf, f(0b0000), 0x25, f(0b0001));
try testDaa(0xbf, f(0b0001), 0x25, f(0b0001));
try testDaa(0xbf, f(0b0010), 0x25, f(0b0001));
try testDaa(0xbf, f(0b0011), 0x25, f(0b0001));
try testDaa(0xbf, f(0b0100), 0xbf, f(0b0100));
try testDaa(0xbf, f(0b0101), 0x5f, f(0b0101));
try testDaa(0xbf, f(0b0110), 0xb9, f(0b0100));
try testDaa(0xbf, f(0b0111), 0x59, f(0b0101));
try testDaa(0xbf, f(0b1000), 0x25, f(0b0001));
try testDaa(0xbf, f(0b1001), 0x25, f(0b0001));
try testDaa(0xbf, f(0b1010), 0x25, f(0b0001));
try testDaa(0xbf, f(0b1011), 0x25, f(0b0001));
try testDaa(0xbf, f(0b1100), 0xbf, f(0b0100));
try testDaa(0xbf, f(0b1101), 0x5f, f(0b0101));
try testDaa(0xbf, f(0b1110), 0xb9, f(0b0100));
try testDaa(0xbf, f(0b1111), 0x59, f(0b0101));
try testDaa(0xc0, f(0b0000), 0x20, f(0b0001));
try testDaa(0xc0, f(0b0001), 0x20, f(0b0001));
try testDaa(0xc0, f(0b0010), 0x26, f(0b0001));
try testDaa(0xc0, f(0b0011), 0x26, f(0b0001));
try testDaa(0xc0, f(0b0100), 0xc0, f(0b0100));
try testDaa(0xc0, f(0b0101), 0x60, f(0b0101));
try testDaa(0xc0, f(0b0110), 0xba, f(0b0100));
try testDaa(0xc0, f(0b0111), 0x5a, f(0b0101));
try testDaa(0xc0, f(0b1000), 0x20, f(0b0001));
try testDaa(0xc0, f(0b1001), 0x20, f(0b0001));
try testDaa(0xc0, f(0b1010), 0x26, f(0b0001));
try testDaa(0xc0, f(0b1011), 0x26, f(0b0001));
try testDaa(0xc0, f(0b1100), 0xc0, f(0b0100));
try testDaa(0xc0, f(0b1101), 0x60, f(0b0101));
try testDaa(0xc0, f(0b1110), 0xba, f(0b0100));
try testDaa(0xc0, f(0b1111), 0x5a, f(0b0101));
try testDaa(0xc1, f(0b0000), 0x21, f(0b0001));
try testDaa(0xc1, f(0b0001), 0x21, f(0b0001));
try testDaa(0xc1, f(0b0010), 0x27, f(0b0001));
try testDaa(0xc1, f(0b0011), 0x27, f(0b0001));
try testDaa(0xc1, f(0b0100), 0xc1, f(0b0100));
try testDaa(0xc1, f(0b0101), 0x61, f(0b0101));
try testDaa(0xc1, f(0b0110), 0xbb, f(0b0100));
try testDaa(0xc1, f(0b0111), 0x5b, f(0b0101));
try testDaa(0xc1, f(0b1000), 0x21, f(0b0001));
try testDaa(0xc1, f(0b1001), 0x21, f(0b0001));
try testDaa(0xc1, f(0b1010), 0x27, f(0b0001));
try testDaa(0xc1, f(0b1011), 0x27, f(0b0001));
try testDaa(0xc1, f(0b1100), 0xc1, f(0b0100));
try testDaa(0xc1, f(0b1101), 0x61, f(0b0101));
try testDaa(0xc1, f(0b1110), 0xbb, f(0b0100));
try testDaa(0xc1, f(0b1111), 0x5b, f(0b0101));
try testDaa(0xc2, f(0b0000), 0x22, f(0b0001));
try testDaa(0xc2, f(0b0001), 0x22, f(0b0001));
try testDaa(0xc2, f(0b0010), 0x28, f(0b0001));
try testDaa(0xc2, f(0b0011), 0x28, f(0b0001));
try testDaa(0xc2, f(0b0100), 0xc2, f(0b0100));
try testDaa(0xc2, f(0b0101), 0x62, f(0b0101));
try testDaa(0xc2, f(0b0110), 0xbc, f(0b0100));
try testDaa(0xc2, f(0b0111), 0x5c, f(0b0101));
try testDaa(0xc2, f(0b1000), 0x22, f(0b0001));
try testDaa(0xc2, f(0b1001), 0x22, f(0b0001));
try testDaa(0xc2, f(0b1010), 0x28, f(0b0001));
try testDaa(0xc2, f(0b1011), 0x28, f(0b0001));
try testDaa(0xc2, f(0b1100), 0xc2, f(0b0100));
try testDaa(0xc2, f(0b1101), 0x62, f(0b0101));
try testDaa(0xc2, f(0b1110), 0xbc, f(0b0100));
try testDaa(0xc2, f(0b1111), 0x5c, f(0b0101));
try testDaa(0xc3, f(0b0000), 0x23, f(0b0001));
try testDaa(0xc3, f(0b0001), 0x23, f(0b0001));
try testDaa(0xc3, f(0b0010), 0x29, f(0b0001));
try testDaa(0xc3, f(0b0011), 0x29, f(0b0001));
try testDaa(0xc3, f(0b0100), 0xc3, f(0b0100));
try testDaa(0xc3, f(0b0101), 0x63, f(0b0101));
try testDaa(0xc3, f(0b0110), 0xbd, f(0b0100));
try testDaa(0xc3, f(0b0111), 0x5d, f(0b0101));
try testDaa(0xc3, f(0b1000), 0x23, f(0b0001));
try testDaa(0xc3, f(0b1001), 0x23, f(0b0001));
try testDaa(0xc3, f(0b1010), 0x29, f(0b0001));
try testDaa(0xc3, f(0b1011), 0x29, f(0b0001));
try testDaa(0xc3, f(0b1100), 0xc3, f(0b0100));
try testDaa(0xc3, f(0b1101), 0x63, f(0b0101));
try testDaa(0xc3, f(0b1110), 0xbd, f(0b0100));
try testDaa(0xc3, f(0b1111), 0x5d, f(0b0101));
try testDaa(0xc4, f(0b0000), 0x24, f(0b0001));
try testDaa(0xc4, f(0b0001), 0x24, f(0b0001));
try testDaa(0xc4, f(0b0010), 0x2a, f(0b0001));
try testDaa(0xc4, f(0b0011), 0x2a, f(0b0001));
try testDaa(0xc4, f(0b0100), 0xc4, f(0b0100));
try testDaa(0xc4, f(0b0101), 0x64, f(0b0101));
try testDaa(0xc4, f(0b0110), 0xbe, f(0b0100));
try testDaa(0xc4, f(0b0111), 0x5e, f(0b0101));
try testDaa(0xc4, f(0b1000), 0x24, f(0b0001));
try testDaa(0xc4, f(0b1001), 0x24, f(0b0001));
try testDaa(0xc4, f(0b1010), 0x2a, f(0b0001));
try testDaa(0xc4, f(0b1011), 0x2a, f(0b0001));
try testDaa(0xc4, f(0b1100), 0xc4, f(0b0100));
try testDaa(0xc4, f(0b1101), 0x64, f(0b0101));
try testDaa(0xc4, f(0b1110), 0xbe, f(0b0100));
try testDaa(0xc4, f(0b1111), 0x5e, f(0b0101));
try testDaa(0xc5, f(0b0000), 0x25, f(0b0001));
try testDaa(0xc5, f(0b0001), 0x25, f(0b0001));
try testDaa(0xc5, f(0b0010), 0x2b, f(0b0001));
try testDaa(0xc5, f(0b0011), 0x2b, f(0b0001));
try testDaa(0xc5, f(0b0100), 0xc5, f(0b0100));
try testDaa(0xc5, f(0b0101), 0x65, f(0b0101));
try testDaa(0xc5, f(0b0110), 0xbf, f(0b0100));
try testDaa(0xc5, f(0b0111), 0x5f, f(0b0101));
try testDaa(0xc5, f(0b1000), 0x25, f(0b0001));
try testDaa(0xc5, f(0b1001), 0x25, f(0b0001));
try testDaa(0xc5, f(0b1010), 0x2b, f(0b0001));
try testDaa(0xc5, f(0b1011), 0x2b, f(0b0001));
try testDaa(0xc5, f(0b1100), 0xc5, f(0b0100));
try testDaa(0xc5, f(0b1101), 0x65, f(0b0101));
try testDaa(0xc5, f(0b1110), 0xbf, f(0b0100));
try testDaa(0xc5, f(0b1111), 0x5f, f(0b0101));
try testDaa(0xc6, f(0b0000), 0x26, f(0b0001));
try testDaa(0xc6, f(0b0001), 0x26, f(0b0001));
try testDaa(0xc6, f(0b0010), 0x2c, f(0b0001));
try testDaa(0xc6, f(0b0011), 0x2c, f(0b0001));
try testDaa(0xc6, f(0b0100), 0xc6, f(0b0100));
try testDaa(0xc6, f(0b0101), 0x66, f(0b0101));
try testDaa(0xc6, f(0b0110), 0xc0, f(0b0100));
try testDaa(0xc6, f(0b0111), 0x60, f(0b0101));
try testDaa(0xc6, f(0b1000), 0x26, f(0b0001));
try testDaa(0xc6, f(0b1001), 0x26, f(0b0001));
try testDaa(0xc6, f(0b1010), 0x2c, f(0b0001));
try testDaa(0xc6, f(0b1011), 0x2c, f(0b0001));
try testDaa(0xc6, f(0b1100), 0xc6, f(0b0100));
try testDaa(0xc6, f(0b1101), 0x66, f(0b0101));
try testDaa(0xc6, f(0b1110), 0xc0, f(0b0100));
try testDaa(0xc6, f(0b1111), 0x60, f(0b0101));
try testDaa(0xc7, f(0b0000), 0x27, f(0b0001));
try testDaa(0xc7, f(0b0001), 0x27, f(0b0001));
try testDaa(0xc7, f(0b0010), 0x2d, f(0b0001));
try testDaa(0xc7, f(0b0011), 0x2d, f(0b0001));
try testDaa(0xc7, f(0b0100), 0xc7, f(0b0100));
try testDaa(0xc7, f(0b0101), 0x67, f(0b0101));
try testDaa(0xc7, f(0b0110), 0xc1, f(0b0100));
try testDaa(0xc7, f(0b0111), 0x61, f(0b0101));
try testDaa(0xc7, f(0b1000), 0x27, f(0b0001));
try testDaa(0xc7, f(0b1001), 0x27, f(0b0001));
try testDaa(0xc7, f(0b1010), 0x2d, f(0b0001));
try testDaa(0xc7, f(0b1011), 0x2d, f(0b0001));
try testDaa(0xc7, f(0b1100), 0xc7, f(0b0100));
try testDaa(0xc7, f(0b1101), 0x67, f(0b0101));
try testDaa(0xc7, f(0b1110), 0xc1, f(0b0100));
try testDaa(0xc7, f(0b1111), 0x61, f(0b0101));
try testDaa(0xc8, f(0b0000), 0x28, f(0b0001));
try testDaa(0xc8, f(0b0001), 0x28, f(0b0001));
try testDaa(0xc8, f(0b0010), 0x2e, f(0b0001));
try testDaa(0xc8, f(0b0011), 0x2e, f(0b0001));
try testDaa(0xc8, f(0b0100), 0xc8, f(0b0100));
try testDaa(0xc8, f(0b0101), 0x68, f(0b0101));
try testDaa(0xc8, f(0b0110), 0xc2, f(0b0100));
try testDaa(0xc8, f(0b0111), 0x62, f(0b0101));
try testDaa(0xc8, f(0b1000), 0x28, f(0b0001));
try testDaa(0xc8, f(0b1001), 0x28, f(0b0001));
try testDaa(0xc8, f(0b1010), 0x2e, f(0b0001));
try testDaa(0xc8, f(0b1011), 0x2e, f(0b0001));
try testDaa(0xc8, f(0b1100), 0xc8, f(0b0100));
try testDaa(0xc8, f(0b1101), 0x68, f(0b0101));
try testDaa(0xc8, f(0b1110), 0xc2, f(0b0100));
try testDaa(0xc8, f(0b1111), 0x62, f(0b0101));
try testDaa(0xc9, f(0b0000), 0x29, f(0b0001));
try testDaa(0xc9, f(0b0001), 0x29, f(0b0001));
try testDaa(0xc9, f(0b0010), 0x2f, f(0b0001));
try testDaa(0xc9, f(0b0011), 0x2f, f(0b0001));
try testDaa(0xc9, f(0b0100), 0xc9, f(0b0100));
try testDaa(0xc9, f(0b0101), 0x69, f(0b0101));
try testDaa(0xc9, f(0b0110), 0xc3, f(0b0100));
try testDaa(0xc9, f(0b0111), 0x63, f(0b0101));
try testDaa(0xc9, f(0b1000), 0x29, f(0b0001));
try testDaa(0xc9, f(0b1001), 0x29, f(0b0001));
try testDaa(0xc9, f(0b1010), 0x2f, f(0b0001));
try testDaa(0xc9, f(0b1011), 0x2f, f(0b0001));
try testDaa(0xc9, f(0b1100), 0xc9, f(0b0100));
try testDaa(0xc9, f(0b1101), 0x69, f(0b0101));
try testDaa(0xc9, f(0b1110), 0xc3, f(0b0100));
try testDaa(0xc9, f(0b1111), 0x63, f(0b0101));
try testDaa(0xca, f(0b0000), 0x30, f(0b0001));
try testDaa(0xca, f(0b0001), 0x30, f(0b0001));
try testDaa(0xca, f(0b0010), 0x30, f(0b0001));
try testDaa(0xca, f(0b0011), 0x30, f(0b0001));
try testDaa(0xca, f(0b0100), 0xca, f(0b0100));
try testDaa(0xca, f(0b0101), 0x6a, f(0b0101));
try testDaa(0xca, f(0b0110), 0xc4, f(0b0100));
try testDaa(0xca, f(0b0111), 0x64, f(0b0101));
try testDaa(0xca, f(0b1000), 0x30, f(0b0001));
try testDaa(0xca, f(0b1001), 0x30, f(0b0001));
try testDaa(0xca, f(0b1010), 0x30, f(0b0001));
try testDaa(0xca, f(0b1011), 0x30, f(0b0001));
try testDaa(0xca, f(0b1100), 0xca, f(0b0100));
try testDaa(0xca, f(0b1101), 0x6a, f(0b0101));
try testDaa(0xca, f(0b1110), 0xc4, f(0b0100));
try testDaa(0xca, f(0b1111), 0x64, f(0b0101));
try testDaa(0xcb, f(0b0000), 0x31, f(0b0001));
try testDaa(0xcb, f(0b0001), 0x31, f(0b0001));
try testDaa(0xcb, f(0b0010), 0x31, f(0b0001));
try testDaa(0xcb, f(0b0011), 0x31, f(0b0001));
try testDaa(0xcb, f(0b0100), 0xcb, f(0b0100));
try testDaa(0xcb, f(0b0101), 0x6b, f(0b0101));
try testDaa(0xcb, f(0b0110), 0xc5, f(0b0100));
try testDaa(0xcb, f(0b0111), 0x65, f(0b0101));
try testDaa(0xcb, f(0b1000), 0x31, f(0b0001));
try testDaa(0xcb, f(0b1001), 0x31, f(0b0001));
try testDaa(0xcb, f(0b1010), 0x31, f(0b0001));
try testDaa(0xcb, f(0b1011), 0x31, f(0b0001));
try testDaa(0xcb, f(0b1100), 0xcb, f(0b0100));
try testDaa(0xcb, f(0b1101), 0x6b, f(0b0101));
try testDaa(0xcb, f(0b1110), 0xc5, f(0b0100));
try testDaa(0xcb, f(0b1111), 0x65, f(0b0101));
try testDaa(0xcc, f(0b0000), 0x32, f(0b0001));
try testDaa(0xcc, f(0b0001), 0x32, f(0b0001));
try testDaa(0xcc, f(0b0010), 0x32, f(0b0001));
try testDaa(0xcc, f(0b0011), 0x32, f(0b0001));
try testDaa(0xcc, f(0b0100), 0xcc, f(0b0100));
try testDaa(0xcc, f(0b0101), 0x6c, f(0b0101));
try testDaa(0xcc, f(0b0110), 0xc6, f(0b0100));
try testDaa(0xcc, f(0b0111), 0x66, f(0b0101));
try testDaa(0xcc, f(0b1000), 0x32, f(0b0001));
try testDaa(0xcc, f(0b1001), 0x32, f(0b0001));
try testDaa(0xcc, f(0b1010), 0x32, f(0b0001));
try testDaa(0xcc, f(0b1011), 0x32, f(0b0001));
try testDaa(0xcc, f(0b1100), 0xcc, f(0b0100));
try testDaa(0xcc, f(0b1101), 0x6c, f(0b0101));
try testDaa(0xcc, f(0b1110), 0xc6, f(0b0100));
try testDaa(0xcc, f(0b1111), 0x66, f(0b0101));
try testDaa(0xcd, f(0b0000), 0x33, f(0b0001));
try testDaa(0xcd, f(0b0001), 0x33, f(0b0001));
try testDaa(0xcd, f(0b0010), 0x33, f(0b0001));
try testDaa(0xcd, f(0b0011), 0x33, f(0b0001));
try testDaa(0xcd, f(0b0100), 0xcd, f(0b0100));
try testDaa(0xcd, f(0b0101), 0x6d, f(0b0101));
try testDaa(0xcd, f(0b0110), 0xc7, f(0b0100));
try testDaa(0xcd, f(0b0111), 0x67, f(0b0101));
try testDaa(0xcd, f(0b1000), 0x33, f(0b0001));
try testDaa(0xcd, f(0b1001), 0x33, f(0b0001));
try testDaa(0xcd, f(0b1010), 0x33, f(0b0001));
try testDaa(0xcd, f(0b1011), 0x33, f(0b0001));
try testDaa(0xcd, f(0b1100), 0xcd, f(0b0100));
try testDaa(0xcd, f(0b1101), 0x6d, f(0b0101));
try testDaa(0xcd, f(0b1110), 0xc7, f(0b0100));
try testDaa(0xcd, f(0b1111), 0x67, f(0b0101));
try testDaa(0xce, f(0b0000), 0x34, f(0b0001));
try testDaa(0xce, f(0b0001), 0x34, f(0b0001));
try testDaa(0xce, f(0b0010), 0x34, f(0b0001));
try testDaa(0xce, f(0b0011), 0x34, f(0b0001));
try testDaa(0xce, f(0b0100), 0xce, f(0b0100));
try testDaa(0xce, f(0b0101), 0x6e, f(0b0101));
try testDaa(0xce, f(0b0110), 0xc8, f(0b0100));
try testDaa(0xce, f(0b0111), 0x68, f(0b0101));
try testDaa(0xce, f(0b1000), 0x34, f(0b0001));
try testDaa(0xce, f(0b1001), 0x34, f(0b0001));
try testDaa(0xce, f(0b1010), 0x34, f(0b0001));
try testDaa(0xce, f(0b1011), 0x34, f(0b0001));
try testDaa(0xce, f(0b1100), 0xce, f(0b0100));
try testDaa(0xce, f(0b1101), 0x6e, f(0b0101));
try testDaa(0xce, f(0b1110), 0xc8, f(0b0100));
try testDaa(0xce, f(0b1111), 0x68, f(0b0101));
try testDaa(0xcf, f(0b0000), 0x35, f(0b0001));
try testDaa(0xcf, f(0b0001), 0x35, f(0b0001));
try testDaa(0xcf, f(0b0010), 0x35, f(0b0001));
try testDaa(0xcf, f(0b0011), 0x35, f(0b0001));
try testDaa(0xcf, f(0b0100), 0xcf, f(0b0100));
try testDaa(0xcf, f(0b0101), 0x6f, f(0b0101));
try testDaa(0xcf, f(0b0110), 0xc9, f(0b0100));
try testDaa(0xcf, f(0b0111), 0x69, f(0b0101));
try testDaa(0xcf, f(0b1000), 0x35, f(0b0001));
try testDaa(0xcf, f(0b1001), 0x35, f(0b0001));
try testDaa(0xcf, f(0b1010), 0x35, f(0b0001));
try testDaa(0xcf, f(0b1011), 0x35, f(0b0001));
try testDaa(0xcf, f(0b1100), 0xcf, f(0b0100));
try testDaa(0xcf, f(0b1101), 0x6f, f(0b0101));
try testDaa(0xcf, f(0b1110), 0xc9, f(0b0100));
try testDaa(0xcf, f(0b1111), 0x69, f(0b0101));
try testDaa(0xd0, f(0b0000), 0x30, f(0b0001));
try testDaa(0xd0, f(0b0001), 0x30, f(0b0001));
try testDaa(0xd0, f(0b0010), 0x36, f(0b0001));
try testDaa(0xd0, f(0b0011), 0x36, f(0b0001));
try testDaa(0xd0, f(0b0100), 0xd0, f(0b0100));
try testDaa(0xd0, f(0b0101), 0x70, f(0b0101));
try testDaa(0xd0, f(0b0110), 0xca, f(0b0100));
try testDaa(0xd0, f(0b0111), 0x6a, f(0b0101));
try testDaa(0xd0, f(0b1000), 0x30, f(0b0001));
try testDaa(0xd0, f(0b1001), 0x30, f(0b0001));
try testDaa(0xd0, f(0b1010), 0x36, f(0b0001));
try testDaa(0xd0, f(0b1011), 0x36, f(0b0001));
try testDaa(0xd0, f(0b1100), 0xd0, f(0b0100));
try testDaa(0xd0, f(0b1101), 0x70, f(0b0101));
try testDaa(0xd0, f(0b1110), 0xca, f(0b0100));
try testDaa(0xd0, f(0b1111), 0x6a, f(0b0101));
try testDaa(0xd1, f(0b0000), 0x31, f(0b0001));
try testDaa(0xd1, f(0b0001), 0x31, f(0b0001));
try testDaa(0xd1, f(0b0010), 0x37, f(0b0001));
try testDaa(0xd1, f(0b0011), 0x37, f(0b0001));
try testDaa(0xd1, f(0b0100), 0xd1, f(0b0100));
try testDaa(0xd1, f(0b0101), 0x71, f(0b0101));
try testDaa(0xd1, f(0b0110), 0xcb, f(0b0100));
try testDaa(0xd1, f(0b0111), 0x6b, f(0b0101));
try testDaa(0xd1, f(0b1000), 0x31, f(0b0001));
try testDaa(0xd1, f(0b1001), 0x31, f(0b0001));
try testDaa(0xd1, f(0b1010), 0x37, f(0b0001));
try testDaa(0xd1, f(0b1011), 0x37, f(0b0001));
try testDaa(0xd1, f(0b1100), 0xd1, f(0b0100));
try testDaa(0xd1, f(0b1101), 0x71, f(0b0101));
try testDaa(0xd1, f(0b1110), 0xcb, f(0b0100));
try testDaa(0xd1, f(0b1111), 0x6b, f(0b0101));
try testDaa(0xd2, f(0b0000), 0x32, f(0b0001));
try testDaa(0xd2, f(0b0001), 0x32, f(0b0001));
try testDaa(0xd2, f(0b0010), 0x38, f(0b0001));
try testDaa(0xd2, f(0b0011), 0x38, f(0b0001));
try testDaa(0xd2, f(0b0100), 0xd2, f(0b0100));
try testDaa(0xd2, f(0b0101), 0x72, f(0b0101));
try testDaa(0xd2, f(0b0110), 0xcc, f(0b0100));
try testDaa(0xd2, f(0b0111), 0x6c, f(0b0101));
try testDaa(0xd2, f(0b1000), 0x32, f(0b0001));
try testDaa(0xd2, f(0b1001), 0x32, f(0b0001));
try testDaa(0xd2, f(0b1010), 0x38, f(0b0001));
try testDaa(0xd2, f(0b1011), 0x38, f(0b0001));
try testDaa(0xd2, f(0b1100), 0xd2, f(0b0100));
try testDaa(0xd2, f(0b1101), 0x72, f(0b0101));
try testDaa(0xd2, f(0b1110), 0xcc, f(0b0100));
try testDaa(0xd2, f(0b1111), 0x6c, f(0b0101));
try testDaa(0xd3, f(0b0000), 0x33, f(0b0001));
try testDaa(0xd3, f(0b0001), 0x33, f(0b0001));
try testDaa(0xd3, f(0b0010), 0x39, f(0b0001));
try testDaa(0xd3, f(0b0011), 0x39, f(0b0001));
try testDaa(0xd3, f(0b0100), 0xd3, f(0b0100));
try testDaa(0xd3, f(0b0101), 0x73, f(0b0101));
try testDaa(0xd3, f(0b0110), 0xcd, f(0b0100));
try testDaa(0xd3, f(0b0111), 0x6d, f(0b0101));
try testDaa(0xd3, f(0b1000), 0x33, f(0b0001));
try testDaa(0xd3, f(0b1001), 0x33, f(0b0001));
try testDaa(0xd3, f(0b1010), 0x39, f(0b0001));
try testDaa(0xd3, f(0b1011), 0x39, f(0b0001));
try testDaa(0xd3, f(0b1100), 0xd3, f(0b0100));
try testDaa(0xd3, f(0b1101), 0x73, f(0b0101));
try testDaa(0xd3, f(0b1110), 0xcd, f(0b0100));
try testDaa(0xd3, f(0b1111), 0x6d, f(0b0101));
try testDaa(0xd4, f(0b0000), 0x34, f(0b0001));
try testDaa(0xd4, f(0b0001), 0x34, f(0b0001));
try testDaa(0xd4, f(0b0010), 0x3a, f(0b0001));
try testDaa(0xd4, f(0b0011), 0x3a, f(0b0001));
try testDaa(0xd4, f(0b0100), 0xd4, f(0b0100));
try testDaa(0xd4, f(0b0101), 0x74, f(0b0101));
try testDaa(0xd4, f(0b0110), 0xce, f(0b0100));
try testDaa(0xd4, f(0b0111), 0x6e, f(0b0101));
try testDaa(0xd4, f(0b1000), 0x34, f(0b0001));
try testDaa(0xd4, f(0b1001), 0x34, f(0b0001));
try testDaa(0xd4, f(0b1010), 0x3a, f(0b0001));
try testDaa(0xd4, f(0b1011), 0x3a, f(0b0001));
try testDaa(0xd4, f(0b1100), 0xd4, f(0b0100));
try testDaa(0xd4, f(0b1101), 0x74, f(0b0101));
try testDaa(0xd4, f(0b1110), 0xce, f(0b0100));
try testDaa(0xd4, f(0b1111), 0x6e, f(0b0101));
try testDaa(0xd5, f(0b0000), 0x35, f(0b0001));
try testDaa(0xd5, f(0b0001), 0x35, f(0b0001));
try testDaa(0xd5, f(0b0010), 0x3b, f(0b0001));
try testDaa(0xd5, f(0b0011), 0x3b, f(0b0001));
try testDaa(0xd5, f(0b0100), 0xd5, f(0b0100));
try testDaa(0xd5, f(0b0101), 0x75, f(0b0101));
try testDaa(0xd5, f(0b0110), 0xcf, f(0b0100));
try testDaa(0xd5, f(0b0111), 0x6f, f(0b0101));
try testDaa(0xd5, f(0b1000), 0x35, f(0b0001));
try testDaa(0xd5, f(0b1001), 0x35, f(0b0001));
try testDaa(0xd5, f(0b1010), 0x3b, f(0b0001));
try testDaa(0xd5, f(0b1011), 0x3b, f(0b0001));
try testDaa(0xd5, f(0b1100), 0xd5, f(0b0100));
try testDaa(0xd5, f(0b1101), 0x75, f(0b0101));
try testDaa(0xd5, f(0b1110), 0xcf, f(0b0100));
try testDaa(0xd5, f(0b1111), 0x6f, f(0b0101));
try testDaa(0xd6, f(0b0000), 0x36, f(0b0001));
try testDaa(0xd6, f(0b0001), 0x36, f(0b0001));
try testDaa(0xd6, f(0b0010), 0x3c, f(0b0001));
try testDaa(0xd6, f(0b0011), 0x3c, f(0b0001));
try testDaa(0xd6, f(0b0100), 0xd6, f(0b0100));
try testDaa(0xd6, f(0b0101), 0x76, f(0b0101));
try testDaa(0xd6, f(0b0110), 0xd0, f(0b0100));
try testDaa(0xd6, f(0b0111), 0x70, f(0b0101));
try testDaa(0xd6, f(0b1000), 0x36, f(0b0001));
try testDaa(0xd6, f(0b1001), 0x36, f(0b0001));
try testDaa(0xd6, f(0b1010), 0x3c, f(0b0001));
try testDaa(0xd6, f(0b1011), 0x3c, f(0b0001));
try testDaa(0xd6, f(0b1100), 0xd6, f(0b0100));
try testDaa(0xd6, f(0b1101), 0x76, f(0b0101));
try testDaa(0xd6, f(0b1110), 0xd0, f(0b0100));
try testDaa(0xd6, f(0b1111), 0x70, f(0b0101));
try testDaa(0xd7, f(0b0000), 0x37, f(0b0001));
try testDaa(0xd7, f(0b0001), 0x37, f(0b0001));
try testDaa(0xd7, f(0b0010), 0x3d, f(0b0001));
try testDaa(0xd7, f(0b0011), 0x3d, f(0b0001));
try testDaa(0xd7, f(0b0100), 0xd7, f(0b0100));
try testDaa(0xd7, f(0b0101), 0x77, f(0b0101));
try testDaa(0xd7, f(0b0110), 0xd1, f(0b0100));
try testDaa(0xd7, f(0b0111), 0x71, f(0b0101));
try testDaa(0xd7, f(0b1000), 0x37, f(0b0001));
try testDaa(0xd7, f(0b1001), 0x37, f(0b0001));
try testDaa(0xd7, f(0b1010), 0x3d, f(0b0001));
try testDaa(0xd7, f(0b1011), 0x3d, f(0b0001));
try testDaa(0xd7, f(0b1100), 0xd7, f(0b0100));
try testDaa(0xd7, f(0b1101), 0x77, f(0b0101));
try testDaa(0xd7, f(0b1110), 0xd1, f(0b0100));
try testDaa(0xd7, f(0b1111), 0x71, f(0b0101));
try testDaa(0xd8, f(0b0000), 0x38, f(0b0001));
try testDaa(0xd8, f(0b0001), 0x38, f(0b0001));
try testDaa(0xd8, f(0b0010), 0x3e, f(0b0001));
try testDaa(0xd8, f(0b0011), 0x3e, f(0b0001));
try testDaa(0xd8, f(0b0100), 0xd8, f(0b0100));
try testDaa(0xd8, f(0b0101), 0x78, f(0b0101));
try testDaa(0xd8, f(0b0110), 0xd2, f(0b0100));
try testDaa(0xd8, f(0b0111), 0x72, f(0b0101));
try testDaa(0xd8, f(0b1000), 0x38, f(0b0001));
try testDaa(0xd8, f(0b1001), 0x38, f(0b0001));
try testDaa(0xd8, f(0b1010), 0x3e, f(0b0001));
try testDaa(0xd8, f(0b1011), 0x3e, f(0b0001));
try testDaa(0xd8, f(0b1100), 0xd8, f(0b0100));
try testDaa(0xd8, f(0b1101), 0x78, f(0b0101));
try testDaa(0xd8, f(0b1110), 0xd2, f(0b0100));
try testDaa(0xd8, f(0b1111), 0x72, f(0b0101));
try testDaa(0xd9, f(0b0000), 0x39, f(0b0001));
try testDaa(0xd9, f(0b0001), 0x39, f(0b0001));
try testDaa(0xd9, f(0b0010), 0x3f, f(0b0001));
try testDaa(0xd9, f(0b0011), 0x3f, f(0b0001));
try testDaa(0xd9, f(0b0100), 0xd9, f(0b0100));
try testDaa(0xd9, f(0b0101), 0x79, f(0b0101));
try testDaa(0xd9, f(0b0110), 0xd3, f(0b0100));
try testDaa(0xd9, f(0b0111), 0x73, f(0b0101));
try testDaa(0xd9, f(0b1000), 0x39, f(0b0001));
try testDaa(0xd9, f(0b1001), 0x39, f(0b0001));
try testDaa(0xd9, f(0b1010), 0x3f, f(0b0001));
try testDaa(0xd9, f(0b1011), 0x3f, f(0b0001));
try testDaa(0xd9, f(0b1100), 0xd9, f(0b0100));
try testDaa(0xd9, f(0b1101), 0x79, f(0b0101));
try testDaa(0xd9, f(0b1110), 0xd3, f(0b0100));
try testDaa(0xd9, f(0b1111), 0x73, f(0b0101));
try testDaa(0xda, f(0b0000), 0x40, f(0b0001));
try testDaa(0xda, f(0b0001), 0x40, f(0b0001));
try testDaa(0xda, f(0b0010), 0x40, f(0b0001));
try testDaa(0xda, f(0b0011), 0x40, f(0b0001));
try testDaa(0xda, f(0b0100), 0xda, f(0b0100));
try testDaa(0xda, f(0b0101), 0x7a, f(0b0101));
try testDaa(0xda, f(0b0110), 0xd4, f(0b0100));
try testDaa(0xda, f(0b0111), 0x74, f(0b0101));
try testDaa(0xda, f(0b1000), 0x40, f(0b0001));
try testDaa(0xda, f(0b1001), 0x40, f(0b0001));
try testDaa(0xda, f(0b1010), 0x40, f(0b0001));
try testDaa(0xda, f(0b1011), 0x40, f(0b0001));
try testDaa(0xda, f(0b1100), 0xda, f(0b0100));
try testDaa(0xda, f(0b1101), 0x7a, f(0b0101));
try testDaa(0xda, f(0b1110), 0xd4, f(0b0100));
try testDaa(0xda, f(0b1111), 0x74, f(0b0101));
try testDaa(0xdb, f(0b0000), 0x41, f(0b0001));
try testDaa(0xdb, f(0b0001), 0x41, f(0b0001));
try testDaa(0xdb, f(0b0010), 0x41, f(0b0001));
try testDaa(0xdb, f(0b0011), 0x41, f(0b0001));
try testDaa(0xdb, f(0b0100), 0xdb, f(0b0100));
try testDaa(0xdb, f(0b0101), 0x7b, f(0b0101));
try testDaa(0xdb, f(0b0110), 0xd5, f(0b0100));
try testDaa(0xdb, f(0b0111), 0x75, f(0b0101));
try testDaa(0xdb, f(0b1000), 0x41, f(0b0001));
try testDaa(0xdb, f(0b1001), 0x41, f(0b0001));
try testDaa(0xdb, f(0b1010), 0x41, f(0b0001));
try testDaa(0xdb, f(0b1011), 0x41, f(0b0001));
try testDaa(0xdb, f(0b1100), 0xdb, f(0b0100));
try testDaa(0xdb, f(0b1101), 0x7b, f(0b0101));
try testDaa(0xdb, f(0b1110), 0xd5, f(0b0100));
try testDaa(0xdb, f(0b1111), 0x75, f(0b0101));
try testDaa(0xdc, f(0b0000), 0x42, f(0b0001));
try testDaa(0xdc, f(0b0001), 0x42, f(0b0001));
try testDaa(0xdc, f(0b0010), 0x42, f(0b0001));
try testDaa(0xdc, f(0b0011), 0x42, f(0b0001));
try testDaa(0xdc, f(0b0100), 0xdc, f(0b0100));
try testDaa(0xdc, f(0b0101), 0x7c, f(0b0101));
try testDaa(0xdc, f(0b0110), 0xd6, f(0b0100));
try testDaa(0xdc, f(0b0111), 0x76, f(0b0101));
try testDaa(0xdc, f(0b1000), 0x42, f(0b0001));
try testDaa(0xdc, f(0b1001), 0x42, f(0b0001));
try testDaa(0xdc, f(0b1010), 0x42, f(0b0001));
try testDaa(0xdc, f(0b1011), 0x42, f(0b0001));
try testDaa(0xdc, f(0b1100), 0xdc, f(0b0100));
try testDaa(0xdc, f(0b1101), 0x7c, f(0b0101));
try testDaa(0xdc, f(0b1110), 0xd6, f(0b0100));
try testDaa(0xdc, f(0b1111), 0x76, f(0b0101));
try testDaa(0xdd, f(0b0000), 0x43, f(0b0001));
try testDaa(0xdd, f(0b0001), 0x43, f(0b0001));
try testDaa(0xdd, f(0b0010), 0x43, f(0b0001));
try testDaa(0xdd, f(0b0011), 0x43, f(0b0001));
try testDaa(0xdd, f(0b0100), 0xdd, f(0b0100));
try testDaa(0xdd, f(0b0101), 0x7d, f(0b0101));
try testDaa(0xdd, f(0b0110), 0xd7, f(0b0100));
try testDaa(0xdd, f(0b0111), 0x77, f(0b0101));
try testDaa(0xdd, f(0b1000), 0x43, f(0b0001));
try testDaa(0xdd, f(0b1001), 0x43, f(0b0001));
try testDaa(0xdd, f(0b1010), 0x43, f(0b0001));
try testDaa(0xdd, f(0b1011), 0x43, f(0b0001));
try testDaa(0xdd, f(0b1100), 0xdd, f(0b0100));
try testDaa(0xdd, f(0b1101), 0x7d, f(0b0101));
try testDaa(0xdd, f(0b1110), 0xd7, f(0b0100));
try testDaa(0xdd, f(0b1111), 0x77, f(0b0101));
try testDaa(0xde, f(0b0000), 0x44, f(0b0001));
try testDaa(0xde, f(0b0001), 0x44, f(0b0001));
try testDaa(0xde, f(0b0010), 0x44, f(0b0001));
try testDaa(0xde, f(0b0011), 0x44, f(0b0001));
try testDaa(0xde, f(0b0100), 0xde, f(0b0100));
try testDaa(0xde, f(0b0101), 0x7e, f(0b0101));
try testDaa(0xde, f(0b0110), 0xd8, f(0b0100));
try testDaa(0xde, f(0b0111), 0x78, f(0b0101));
try testDaa(0xde, f(0b1000), 0x44, f(0b0001));
try testDaa(0xde, f(0b1001), 0x44, f(0b0001));
try testDaa(0xde, f(0b1010), 0x44, f(0b0001));
try testDaa(0xde, f(0b1011), 0x44, f(0b0001));
try testDaa(0xde, f(0b1100), 0xde, f(0b0100));
try testDaa(0xde, f(0b1101), 0x7e, f(0b0101));
try testDaa(0xde, f(0b1110), 0xd8, f(0b0100));
try testDaa(0xde, f(0b1111), 0x78, f(0b0101));
try testDaa(0xdf, f(0b0000), 0x45, f(0b0001));
try testDaa(0xdf, f(0b0001), 0x45, f(0b0001));
try testDaa(0xdf, f(0b0010), 0x45, f(0b0001));
try testDaa(0xdf, f(0b0011), 0x45, f(0b0001));
try testDaa(0xdf, f(0b0100), 0xdf, f(0b0100));
try testDaa(0xdf, f(0b0101), 0x7f, f(0b0101));
try testDaa(0xdf, f(0b0110), 0xd9, f(0b0100));
try testDaa(0xdf, f(0b0111), 0x79, f(0b0101));
try testDaa(0xdf, f(0b1000), 0x45, f(0b0001));
try testDaa(0xdf, f(0b1001), 0x45, f(0b0001));
try testDaa(0xdf, f(0b1010), 0x45, f(0b0001));
try testDaa(0xdf, f(0b1011), 0x45, f(0b0001));
try testDaa(0xdf, f(0b1100), 0xdf, f(0b0100));
try testDaa(0xdf, f(0b1101), 0x7f, f(0b0101));
try testDaa(0xdf, f(0b1110), 0xd9, f(0b0100));
try testDaa(0xdf, f(0b1111), 0x79, f(0b0101));
try testDaa(0xe0, f(0b0000), 0x40, f(0b0001));
try testDaa(0xe0, f(0b0001), 0x40, f(0b0001));
try testDaa(0xe0, f(0b0010), 0x46, f(0b0001));
try testDaa(0xe0, f(0b0011), 0x46, f(0b0001));
try testDaa(0xe0, f(0b0100), 0xe0, f(0b0100));
try testDaa(0xe0, f(0b0101), 0x80, f(0b0101));
try testDaa(0xe0, f(0b0110), 0xda, f(0b0100));
try testDaa(0xe0, f(0b0111), 0x7a, f(0b0101));
try testDaa(0xe0, f(0b1000), 0x40, f(0b0001));
try testDaa(0xe0, f(0b1001), 0x40, f(0b0001));
try testDaa(0xe0, f(0b1010), 0x46, f(0b0001));
try testDaa(0xe0, f(0b1011), 0x46, f(0b0001));
try testDaa(0xe0, f(0b1100), 0xe0, f(0b0100));
try testDaa(0xe0, f(0b1101), 0x80, f(0b0101));
try testDaa(0xe0, f(0b1110), 0xda, f(0b0100));
try testDaa(0xe0, f(0b1111), 0x7a, f(0b0101));
try testDaa(0xe1, f(0b0000), 0x41, f(0b0001));
try testDaa(0xe1, f(0b0001), 0x41, f(0b0001));
try testDaa(0xe1, f(0b0010), 0x47, f(0b0001));
try testDaa(0xe1, f(0b0011), 0x47, f(0b0001));
try testDaa(0xe1, f(0b0100), 0xe1, f(0b0100));
try testDaa(0xe1, f(0b0101), 0x81, f(0b0101));
try testDaa(0xe1, f(0b0110), 0xdb, f(0b0100));
try testDaa(0xe1, f(0b0111), 0x7b, f(0b0101));
try testDaa(0xe1, f(0b1000), 0x41, f(0b0001));
try testDaa(0xe1, f(0b1001), 0x41, f(0b0001));
try testDaa(0xe1, f(0b1010), 0x47, f(0b0001));
try testDaa(0xe1, f(0b1011), 0x47, f(0b0001));
try testDaa(0xe1, f(0b1100), 0xe1, f(0b0100));
try testDaa(0xe1, f(0b1101), 0x81, f(0b0101));
try testDaa(0xe1, f(0b1110), 0xdb, f(0b0100));
try testDaa(0xe1, f(0b1111), 0x7b, f(0b0101));
try testDaa(0xe2, f(0b0000), 0x42, f(0b0001));
try testDaa(0xe2, f(0b0001), 0x42, f(0b0001));
try testDaa(0xe2, f(0b0010), 0x48, f(0b0001));
try testDaa(0xe2, f(0b0011), 0x48, f(0b0001));
try testDaa(0xe2, f(0b0100), 0xe2, f(0b0100));
try testDaa(0xe2, f(0b0101), 0x82, f(0b0101));
try testDaa(0xe2, f(0b0110), 0xdc, f(0b0100));
try testDaa(0xe2, f(0b0111), 0x7c, f(0b0101));
try testDaa(0xe2, f(0b1000), 0x42, f(0b0001));
try testDaa(0xe2, f(0b1001), 0x42, f(0b0001));
try testDaa(0xe2, f(0b1010), 0x48, f(0b0001));
try testDaa(0xe2, f(0b1011), 0x48, f(0b0001));
try testDaa(0xe2, f(0b1100), 0xe2, f(0b0100));
try testDaa(0xe2, f(0b1101), 0x82, f(0b0101));
try testDaa(0xe2, f(0b1110), 0xdc, f(0b0100));
try testDaa(0xe2, f(0b1111), 0x7c, f(0b0101));
try testDaa(0xe3, f(0b0000), 0x43, f(0b0001));
try testDaa(0xe3, f(0b0001), 0x43, f(0b0001));
try testDaa(0xe3, f(0b0010), 0x49, f(0b0001));
try testDaa(0xe3, f(0b0011), 0x49, f(0b0001));
try testDaa(0xe3, f(0b0100), 0xe3, f(0b0100));
try testDaa(0xe3, f(0b0101), 0x83, f(0b0101));
try testDaa(0xe3, f(0b0110), 0xdd, f(0b0100));
try testDaa(0xe3, f(0b0111), 0x7d, f(0b0101));
try testDaa(0xe3, f(0b1000), 0x43, f(0b0001));
try testDaa(0xe3, f(0b1001), 0x43, f(0b0001));
try testDaa(0xe3, f(0b1010), 0x49, f(0b0001));
try testDaa(0xe3, f(0b1011), 0x49, f(0b0001));
try testDaa(0xe3, f(0b1100), 0xe3, f(0b0100));
try testDaa(0xe3, f(0b1101), 0x83, f(0b0101));
try testDaa(0xe3, f(0b1110), 0xdd, f(0b0100));
try testDaa(0xe3, f(0b1111), 0x7d, f(0b0101));
try testDaa(0xe4, f(0b0000), 0x44, f(0b0001));
try testDaa(0xe4, f(0b0001), 0x44, f(0b0001));
try testDaa(0xe4, f(0b0010), 0x4a, f(0b0001));
try testDaa(0xe4, f(0b0011), 0x4a, f(0b0001));
try testDaa(0xe4, f(0b0100), 0xe4, f(0b0100));
try testDaa(0xe4, f(0b0101), 0x84, f(0b0101));
try testDaa(0xe4, f(0b0110), 0xde, f(0b0100));
try testDaa(0xe4, f(0b0111), 0x7e, f(0b0101));
try testDaa(0xe4, f(0b1000), 0x44, f(0b0001));
try testDaa(0xe4, f(0b1001), 0x44, f(0b0001));
try testDaa(0xe4, f(0b1010), 0x4a, f(0b0001));
try testDaa(0xe4, f(0b1011), 0x4a, f(0b0001));
try testDaa(0xe4, f(0b1100), 0xe4, f(0b0100));
try testDaa(0xe4, f(0b1101), 0x84, f(0b0101));
try testDaa(0xe4, f(0b1110), 0xde, f(0b0100));
try testDaa(0xe4, f(0b1111), 0x7e, f(0b0101));
try testDaa(0xe5, f(0b0000), 0x45, f(0b0001));
try testDaa(0xe5, f(0b0001), 0x45, f(0b0001));
try testDaa(0xe5, f(0b0010), 0x4b, f(0b0001));
try testDaa(0xe5, f(0b0011), 0x4b, f(0b0001));
try testDaa(0xe5, f(0b0100), 0xe5, f(0b0100));
try testDaa(0xe5, f(0b0101), 0x85, f(0b0101));
try testDaa(0xe5, f(0b0110), 0xdf, f(0b0100));
try testDaa(0xe5, f(0b0111), 0x7f, f(0b0101));
try testDaa(0xe5, f(0b1000), 0x45, f(0b0001));
try testDaa(0xe5, f(0b1001), 0x45, f(0b0001));
try testDaa(0xe5, f(0b1010), 0x4b, f(0b0001));
try testDaa(0xe5, f(0b1011), 0x4b, f(0b0001));
try testDaa(0xe5, f(0b1100), 0xe5, f(0b0100));
try testDaa(0xe5, f(0b1101), 0x85, f(0b0101));
try testDaa(0xe5, f(0b1110), 0xdf, f(0b0100));
try testDaa(0xe5, f(0b1111), 0x7f, f(0b0101));
try testDaa(0xe6, f(0b0000), 0x46, f(0b0001));
try testDaa(0xe6, f(0b0001), 0x46, f(0b0001));
try testDaa(0xe6, f(0b0010), 0x4c, f(0b0001));
try testDaa(0xe6, f(0b0011), 0x4c, f(0b0001));
try testDaa(0xe6, f(0b0100), 0xe6, f(0b0100));
try testDaa(0xe6, f(0b0101), 0x86, f(0b0101));
try testDaa(0xe6, f(0b0110), 0xe0, f(0b0100));
try testDaa(0xe6, f(0b0111), 0x80, f(0b0101));
try testDaa(0xe6, f(0b1000), 0x46, f(0b0001));
try testDaa(0xe6, f(0b1001), 0x46, f(0b0001));
try testDaa(0xe6, f(0b1010), 0x4c, f(0b0001));
try testDaa(0xe6, f(0b1011), 0x4c, f(0b0001));
try testDaa(0xe6, f(0b1100), 0xe6, f(0b0100));
try testDaa(0xe6, f(0b1101), 0x86, f(0b0101));
try testDaa(0xe6, f(0b1110), 0xe0, f(0b0100));
try testDaa(0xe6, f(0b1111), 0x80, f(0b0101));
try testDaa(0xe7, f(0b0000), 0x47, f(0b0001));
try testDaa(0xe7, f(0b0001), 0x47, f(0b0001));
try testDaa(0xe7, f(0b0010), 0x4d, f(0b0001));
try testDaa(0xe7, f(0b0011), 0x4d, f(0b0001));
try testDaa(0xe7, f(0b0100), 0xe7, f(0b0100));
try testDaa(0xe7, f(0b0101), 0x87, f(0b0101));
try testDaa(0xe7, f(0b0110), 0xe1, f(0b0100));
try testDaa(0xe7, f(0b0111), 0x81, f(0b0101));
try testDaa(0xe7, f(0b1000), 0x47, f(0b0001));
try testDaa(0xe7, f(0b1001), 0x47, f(0b0001));
try testDaa(0xe7, f(0b1010), 0x4d, f(0b0001));
try testDaa(0xe7, f(0b1011), 0x4d, f(0b0001));
try testDaa(0xe7, f(0b1100), 0xe7, f(0b0100));
try testDaa(0xe7, f(0b1101), 0x87, f(0b0101));
try testDaa(0xe7, f(0b1110), 0xe1, f(0b0100));
try testDaa(0xe7, f(0b1111), 0x81, f(0b0101));
try testDaa(0xe8, f(0b0000), 0x48, f(0b0001));
try testDaa(0xe8, f(0b0001), 0x48, f(0b0001));
try testDaa(0xe8, f(0b0010), 0x4e, f(0b0001));
try testDaa(0xe8, f(0b0011), 0x4e, f(0b0001));
try testDaa(0xe8, f(0b0100), 0xe8, f(0b0100));
try testDaa(0xe8, f(0b0101), 0x88, f(0b0101));
try testDaa(0xe8, f(0b0110), 0xe2, f(0b0100));
try testDaa(0xe8, f(0b0111), 0x82, f(0b0101));
try testDaa(0xe8, f(0b1000), 0x48, f(0b0001));
try testDaa(0xe8, f(0b1001), 0x48, f(0b0001));
try testDaa(0xe8, f(0b1010), 0x4e, f(0b0001));
try testDaa(0xe8, f(0b1011), 0x4e, f(0b0001));
try testDaa(0xe8, f(0b1100), 0xe8, f(0b0100));
try testDaa(0xe8, f(0b1101), 0x88, f(0b0101));
try testDaa(0xe8, f(0b1110), 0xe2, f(0b0100));
try testDaa(0xe8, f(0b1111), 0x82, f(0b0101));
try testDaa(0xe9, f(0b0000), 0x49, f(0b0001));
try testDaa(0xe9, f(0b0001), 0x49, f(0b0001));
try testDaa(0xe9, f(0b0010), 0x4f, f(0b0001));
try testDaa(0xe9, f(0b0011), 0x4f, f(0b0001));
try testDaa(0xe9, f(0b0100), 0xe9, f(0b0100));
try testDaa(0xe9, f(0b0101), 0x89, f(0b0101));
try testDaa(0xe9, f(0b0110), 0xe3, f(0b0100));
try testDaa(0xe9, f(0b0111), 0x83, f(0b0101));
try testDaa(0xe9, f(0b1000), 0x49, f(0b0001));
try testDaa(0xe9, f(0b1001), 0x49, f(0b0001));
try testDaa(0xe9, f(0b1010), 0x4f, f(0b0001));
try testDaa(0xe9, f(0b1011), 0x4f, f(0b0001));
try testDaa(0xe9, f(0b1100), 0xe9, f(0b0100));
try testDaa(0xe9, f(0b1101), 0x89, f(0b0101));
try testDaa(0xe9, f(0b1110), 0xe3, f(0b0100));
try testDaa(0xe9, f(0b1111), 0x83, f(0b0101));
try testDaa(0xea, f(0b0000), 0x50, f(0b0001));
try testDaa(0xea, f(0b0001), 0x50, f(0b0001));
try testDaa(0xea, f(0b0010), 0x50, f(0b0001));
try testDaa(0xea, f(0b0011), 0x50, f(0b0001));
try testDaa(0xea, f(0b0100), 0xea, f(0b0100));
try testDaa(0xea, f(0b0101), 0x8a, f(0b0101));
try testDaa(0xea, f(0b0110), 0xe4, f(0b0100));
try testDaa(0xea, f(0b0111), 0x84, f(0b0101));
try testDaa(0xea, f(0b1000), 0x50, f(0b0001));
try testDaa(0xea, f(0b1001), 0x50, f(0b0001));
try testDaa(0xea, f(0b1010), 0x50, f(0b0001));
try testDaa(0xea, f(0b1011), 0x50, f(0b0001));
try testDaa(0xea, f(0b1100), 0xea, f(0b0100));
try testDaa(0xea, f(0b1101), 0x8a, f(0b0101));
try testDaa(0xea, f(0b1110), 0xe4, f(0b0100));
try testDaa(0xea, f(0b1111), 0x84, f(0b0101));
try testDaa(0xeb, f(0b0000), 0x51, f(0b0001));
try testDaa(0xeb, f(0b0001), 0x51, f(0b0001));
try testDaa(0xeb, f(0b0010), 0x51, f(0b0001));
try testDaa(0xeb, f(0b0011), 0x51, f(0b0001));
try testDaa(0xeb, f(0b0100), 0xeb, f(0b0100));
try testDaa(0xeb, f(0b0101), 0x8b, f(0b0101));
try testDaa(0xeb, f(0b0110), 0xe5, f(0b0100));
try testDaa(0xeb, f(0b0111), 0x85, f(0b0101));
try testDaa(0xeb, f(0b1000), 0x51, f(0b0001));
try testDaa(0xeb, f(0b1001), 0x51, f(0b0001));
try testDaa(0xeb, f(0b1010), 0x51, f(0b0001));
try testDaa(0xeb, f(0b1011), 0x51, f(0b0001));
try testDaa(0xeb, f(0b1100), 0xeb, f(0b0100));
try testDaa(0xeb, f(0b1101), 0x8b, f(0b0101));
try testDaa(0xeb, f(0b1110), 0xe5, f(0b0100));
try testDaa(0xeb, f(0b1111), 0x85, f(0b0101));
try testDaa(0xec, f(0b0000), 0x52, f(0b0001));
try testDaa(0xec, f(0b0001), 0x52, f(0b0001));
try testDaa(0xec, f(0b0010), 0x52, f(0b0001));
try testDaa(0xec, f(0b0011), 0x52, f(0b0001));
try testDaa(0xec, f(0b0100), 0xec, f(0b0100));
try testDaa(0xec, f(0b0101), 0x8c, f(0b0101));
try testDaa(0xec, f(0b0110), 0xe6, f(0b0100));
try testDaa(0xec, f(0b0111), 0x86, f(0b0101));
try testDaa(0xec, f(0b1000), 0x52, f(0b0001));
try testDaa(0xec, f(0b1001), 0x52, f(0b0001));
try testDaa(0xec, f(0b1010), 0x52, f(0b0001));
try testDaa(0xec, f(0b1011), 0x52, f(0b0001));
try testDaa(0xec, f(0b1100), 0xec, f(0b0100));
try testDaa(0xec, f(0b1101), 0x8c, f(0b0101));
try testDaa(0xec, f(0b1110), 0xe6, f(0b0100));
try testDaa(0xec, f(0b1111), 0x86, f(0b0101));
try testDaa(0xed, f(0b0000), 0x53, f(0b0001));
try testDaa(0xed, f(0b0001), 0x53, f(0b0001));
try testDaa(0xed, f(0b0010), 0x53, f(0b0001));
try testDaa(0xed, f(0b0011), 0x53, f(0b0001));
try testDaa(0xed, f(0b0100), 0xed, f(0b0100));
try testDaa(0xed, f(0b0101), 0x8d, f(0b0101));
try testDaa(0xed, f(0b0110), 0xe7, f(0b0100));
try testDaa(0xed, f(0b0111), 0x87, f(0b0101));
try testDaa(0xed, f(0b1000), 0x53, f(0b0001));
try testDaa(0xed, f(0b1001), 0x53, f(0b0001));
try testDaa(0xed, f(0b1010), 0x53, f(0b0001));
try testDaa(0xed, f(0b1011), 0x53, f(0b0001));
try testDaa(0xed, f(0b1100), 0xed, f(0b0100));
try testDaa(0xed, f(0b1101), 0x8d, f(0b0101));
try testDaa(0xed, f(0b1110), 0xe7, f(0b0100));
try testDaa(0xed, f(0b1111), 0x87, f(0b0101));
try testDaa(0xee, f(0b0000), 0x54, f(0b0001));
try testDaa(0xee, f(0b0001), 0x54, f(0b0001));
try testDaa(0xee, f(0b0010), 0x54, f(0b0001));
try testDaa(0xee, f(0b0011), 0x54, f(0b0001));
try testDaa(0xee, f(0b0100), 0xee, f(0b0100));
try testDaa(0xee, f(0b0101), 0x8e, f(0b0101));
try testDaa(0xee, f(0b0110), 0xe8, f(0b0100));
try testDaa(0xee, f(0b0111), 0x88, f(0b0101));
try testDaa(0xee, f(0b1000), 0x54, f(0b0001));
try testDaa(0xee, f(0b1001), 0x54, f(0b0001));
try testDaa(0xee, f(0b1010), 0x54, f(0b0001));
try testDaa(0xee, f(0b1011), 0x54, f(0b0001));
try testDaa(0xee, f(0b1100), 0xee, f(0b0100));
try testDaa(0xee, f(0b1101), 0x8e, f(0b0101));
try testDaa(0xee, f(0b1110), 0xe8, f(0b0100));
try testDaa(0xee, f(0b1111), 0x88, f(0b0101));
try testDaa(0xef, f(0b0000), 0x55, f(0b0001));
try testDaa(0xef, f(0b0001), 0x55, f(0b0001));
try testDaa(0xef, f(0b0010), 0x55, f(0b0001));
try testDaa(0xef, f(0b0011), 0x55, f(0b0001));
try testDaa(0xef, f(0b0100), 0xef, f(0b0100));
try testDaa(0xef, f(0b0101), 0x8f, f(0b0101));
try testDaa(0xef, f(0b0110), 0xe9, f(0b0100));
try testDaa(0xef, f(0b0111), 0x89, f(0b0101));
try testDaa(0xef, f(0b1000), 0x55, f(0b0001));
try testDaa(0xef, f(0b1001), 0x55, f(0b0001));
try testDaa(0xef, f(0b1010), 0x55, f(0b0001));
try testDaa(0xef, f(0b1011), 0x55, f(0b0001));
try testDaa(0xef, f(0b1100), 0xef, f(0b0100));
try testDaa(0xef, f(0b1101), 0x8f, f(0b0101));
try testDaa(0xef, f(0b1110), 0xe9, f(0b0100));
try testDaa(0xef, f(0b1111), 0x89, f(0b0101));
try testDaa(0xf0, f(0b0000), 0x50, f(0b0001));
try testDaa(0xf0, f(0b0001), 0x50, f(0b0001));
try testDaa(0xf0, f(0b0010), 0x56, f(0b0001));
try testDaa(0xf0, f(0b0011), 0x56, f(0b0001));
try testDaa(0xf0, f(0b0100), 0xf0, f(0b0100));
try testDaa(0xf0, f(0b0101), 0x90, f(0b0101));
try testDaa(0xf0, f(0b0110), 0xea, f(0b0100));
try testDaa(0xf0, f(0b0111), 0x8a, f(0b0101));
try testDaa(0xf0, f(0b1000), 0x50, f(0b0001));
try testDaa(0xf0, f(0b1001), 0x50, f(0b0001));
try testDaa(0xf0, f(0b1010), 0x56, f(0b0001));
try testDaa(0xf0, f(0b1011), 0x56, f(0b0001));
try testDaa(0xf0, f(0b1100), 0xf0, f(0b0100));
try testDaa(0xf0, f(0b1101), 0x90, f(0b0101));
try testDaa(0xf0, f(0b1110), 0xea, f(0b0100));
try testDaa(0xf0, f(0b1111), 0x8a, f(0b0101));
try testDaa(0xf1, f(0b0000), 0x51, f(0b0001));
try testDaa(0xf1, f(0b0001), 0x51, f(0b0001));
try testDaa(0xf1, f(0b0010), 0x57, f(0b0001));
try testDaa(0xf1, f(0b0011), 0x57, f(0b0001));
try testDaa(0xf1, f(0b0100), 0xf1, f(0b0100));
try testDaa(0xf1, f(0b0101), 0x91, f(0b0101));
try testDaa(0xf1, f(0b0110), 0xeb, f(0b0100));
try testDaa(0xf1, f(0b0111), 0x8b, f(0b0101));
try testDaa(0xf1, f(0b1000), 0x51, f(0b0001));
try testDaa(0xf1, f(0b1001), 0x51, f(0b0001));
try testDaa(0xf1, f(0b1010), 0x57, f(0b0001));
try testDaa(0xf1, f(0b1011), 0x57, f(0b0001));
try testDaa(0xf1, f(0b1100), 0xf1, f(0b0100));
try testDaa(0xf1, f(0b1101), 0x91, f(0b0101));
try testDaa(0xf1, f(0b1110), 0xeb, f(0b0100));
try testDaa(0xf1, f(0b1111), 0x8b, f(0b0101));
try testDaa(0xf2, f(0b0000), 0x52, f(0b0001));
try testDaa(0xf2, f(0b0001), 0x52, f(0b0001));
try testDaa(0xf2, f(0b0010), 0x58, f(0b0001));
try testDaa(0xf2, f(0b0011), 0x58, f(0b0001));
try testDaa(0xf2, f(0b0100), 0xf2, f(0b0100));
try testDaa(0xf2, f(0b0101), 0x92, f(0b0101));
try testDaa(0xf2, f(0b0110), 0xec, f(0b0100));
try testDaa(0xf2, f(0b0111), 0x8c, f(0b0101));
try testDaa(0xf2, f(0b1000), 0x52, f(0b0001));
try testDaa(0xf2, f(0b1001), 0x52, f(0b0001));
try testDaa(0xf2, f(0b1010), 0x58, f(0b0001));
try testDaa(0xf2, f(0b1011), 0x58, f(0b0001));
try testDaa(0xf2, f(0b1100), 0xf2, f(0b0100));
try testDaa(0xf2, f(0b1101), 0x92, f(0b0101));
try testDaa(0xf2, f(0b1110), 0xec, f(0b0100));
try testDaa(0xf2, f(0b1111), 0x8c, f(0b0101));
try testDaa(0xf3, f(0b0000), 0x53, f(0b0001));
try testDaa(0xf3, f(0b0001), 0x53, f(0b0001));
try testDaa(0xf3, f(0b0010), 0x59, f(0b0001));
try testDaa(0xf3, f(0b0011), 0x59, f(0b0001));
try testDaa(0xf3, f(0b0100), 0xf3, f(0b0100));
try testDaa(0xf3, f(0b0101), 0x93, f(0b0101));
try testDaa(0xf3, f(0b0110), 0xed, f(0b0100));
try testDaa(0xf3, f(0b0111), 0x8d, f(0b0101));
try testDaa(0xf3, f(0b1000), 0x53, f(0b0001));
try testDaa(0xf3, f(0b1001), 0x53, f(0b0001));
try testDaa(0xf3, f(0b1010), 0x59, f(0b0001));
try testDaa(0xf3, f(0b1011), 0x59, f(0b0001));
try testDaa(0xf3, f(0b1100), 0xf3, f(0b0100));
try testDaa(0xf3, f(0b1101), 0x93, f(0b0101));
try testDaa(0xf3, f(0b1110), 0xed, f(0b0100));
try testDaa(0xf3, f(0b1111), 0x8d, f(0b0101));
try testDaa(0xf4, f(0b0000), 0x54, f(0b0001));
try testDaa(0xf4, f(0b0001), 0x54, f(0b0001));
try testDaa(0xf4, f(0b0010), 0x5a, f(0b0001));
try testDaa(0xf4, f(0b0011), 0x5a, f(0b0001));
try testDaa(0xf4, f(0b0100), 0xf4, f(0b0100));
try testDaa(0xf4, f(0b0101), 0x94, f(0b0101));
try testDaa(0xf4, f(0b0110), 0xee, f(0b0100));
try testDaa(0xf4, f(0b0111), 0x8e, f(0b0101));
try testDaa(0xf4, f(0b1000), 0x54, f(0b0001));
try testDaa(0xf4, f(0b1001), 0x54, f(0b0001));
try testDaa(0xf4, f(0b1010), 0x5a, f(0b0001));
try testDaa(0xf4, f(0b1011), 0x5a, f(0b0001));
try testDaa(0xf4, f(0b1100), 0xf4, f(0b0100));
try testDaa(0xf4, f(0b1101), 0x94, f(0b0101));
try testDaa(0xf4, f(0b1110), 0xee, f(0b0100));
try testDaa(0xf4, f(0b1111), 0x8e, f(0b0101));
try testDaa(0xf5, f(0b0000), 0x55, f(0b0001));
try testDaa(0xf5, f(0b0001), 0x55, f(0b0001));
try testDaa(0xf5, f(0b0010), 0x5b, f(0b0001));
try testDaa(0xf5, f(0b0011), 0x5b, f(0b0001));
try testDaa(0xf5, f(0b0100), 0xf5, f(0b0100));
try testDaa(0xf5, f(0b0101), 0x95, f(0b0101));
try testDaa(0xf5, f(0b0110), 0xef, f(0b0100));
try testDaa(0xf5, f(0b0111), 0x8f, f(0b0101));
try testDaa(0xf5, f(0b1000), 0x55, f(0b0001));
try testDaa(0xf5, f(0b1001), 0x55, f(0b0001));
try testDaa(0xf5, f(0b1010), 0x5b, f(0b0001));
try testDaa(0xf5, f(0b1011), 0x5b, f(0b0001));
try testDaa(0xf5, f(0b1100), 0xf5, f(0b0100));
try testDaa(0xf5, f(0b1101), 0x95, f(0b0101));
try testDaa(0xf5, f(0b1110), 0xef, f(0b0100));
try testDaa(0xf5, f(0b1111), 0x8f, f(0b0101));
try testDaa(0xf6, f(0b0000), 0x56, f(0b0001));
try testDaa(0xf6, f(0b0001), 0x56, f(0b0001));
try testDaa(0xf6, f(0b0010), 0x5c, f(0b0001));
try testDaa(0xf6, f(0b0011), 0x5c, f(0b0001));
try testDaa(0xf6, f(0b0100), 0xf6, f(0b0100));
try testDaa(0xf6, f(0b0101), 0x96, f(0b0101));
try testDaa(0xf6, f(0b0110), 0xf0, f(0b0100));
try testDaa(0xf6, f(0b0111), 0x90, f(0b0101));
try testDaa(0xf6, f(0b1000), 0x56, f(0b0001));
try testDaa(0xf6, f(0b1001), 0x56, f(0b0001));
try testDaa(0xf6, f(0b1010), 0x5c, f(0b0001));
try testDaa(0xf6, f(0b1011), 0x5c, f(0b0001));
try testDaa(0xf6, f(0b1100), 0xf6, f(0b0100));
try testDaa(0xf6, f(0b1101), 0x96, f(0b0101));
try testDaa(0xf6, f(0b1110), 0xf0, f(0b0100));
try testDaa(0xf6, f(0b1111), 0x90, f(0b0101));
try testDaa(0xf7, f(0b0000), 0x57, f(0b0001));
try testDaa(0xf7, f(0b0001), 0x57, f(0b0001));
try testDaa(0xf7, f(0b0010), 0x5d, f(0b0001));
try testDaa(0xf7, f(0b0011), 0x5d, f(0b0001));
try testDaa(0xf7, f(0b0100), 0xf7, f(0b0100));
try testDaa(0xf7, f(0b0101), 0x97, f(0b0101));
try testDaa(0xf7, f(0b0110), 0xf1, f(0b0100));
try testDaa(0xf7, f(0b0111), 0x91, f(0b0101));
try testDaa(0xf7, f(0b1000), 0x57, f(0b0001));
try testDaa(0xf7, f(0b1001), 0x57, f(0b0001));
try testDaa(0xf7, f(0b1010), 0x5d, f(0b0001));
try testDaa(0xf7, f(0b1011), 0x5d, f(0b0001));
try testDaa(0xf7, f(0b1100), 0xf7, f(0b0100));
try testDaa(0xf7, f(0b1101), 0x97, f(0b0101));
try testDaa(0xf7, f(0b1110), 0xf1, f(0b0100));
try testDaa(0xf7, f(0b1111), 0x91, f(0b0101));
try testDaa(0xf8, f(0b0000), 0x58, f(0b0001));
try testDaa(0xf8, f(0b0001), 0x58, f(0b0001));
try testDaa(0xf8, f(0b0010), 0x5e, f(0b0001));
try testDaa(0xf8, f(0b0011), 0x5e, f(0b0001));
try testDaa(0xf8, f(0b0100), 0xf8, f(0b0100));
try testDaa(0xf8, f(0b0101), 0x98, f(0b0101));
try testDaa(0xf8, f(0b0110), 0xf2, f(0b0100));
try testDaa(0xf8, f(0b0111), 0x92, f(0b0101));
try testDaa(0xf8, f(0b1000), 0x58, f(0b0001));
try testDaa(0xf8, f(0b1001), 0x58, f(0b0001));
try testDaa(0xf8, f(0b1010), 0x5e, f(0b0001));
try testDaa(0xf8, f(0b1011), 0x5e, f(0b0001));
try testDaa(0xf8, f(0b1100), 0xf8, f(0b0100));
try testDaa(0xf8, f(0b1101), 0x98, f(0b0101));
try testDaa(0xf8, f(0b1110), 0xf2, f(0b0100));
try testDaa(0xf8, f(0b1111), 0x92, f(0b0101));
try testDaa(0xf9, f(0b0000), 0x59, f(0b0001));
try testDaa(0xf9, f(0b0001), 0x59, f(0b0001));
try testDaa(0xf9, f(0b0010), 0x5f, f(0b0001));
try testDaa(0xf9, f(0b0011), 0x5f, f(0b0001));
try testDaa(0xf9, f(0b0100), 0xf9, f(0b0100));
try testDaa(0xf9, f(0b0101), 0x99, f(0b0101));
try testDaa(0xf9, f(0b0110), 0xf3, f(0b0100));
try testDaa(0xf9, f(0b0111), 0x93, f(0b0101));
try testDaa(0xf9, f(0b1000), 0x59, f(0b0001));
try testDaa(0xf9, f(0b1001), 0x59, f(0b0001));
try testDaa(0xf9, f(0b1010), 0x5f, f(0b0001));
try testDaa(0xf9, f(0b1011), 0x5f, f(0b0001));
try testDaa(0xf9, f(0b1100), 0xf9, f(0b0100));
try testDaa(0xf9, f(0b1101), 0x99, f(0b0101));
try testDaa(0xf9, f(0b1110), 0xf3, f(0b0100));
try testDaa(0xf9, f(0b1111), 0x93, f(0b0101));
try testDaa(0xfa, f(0b0000), 0x60, f(0b0001));
try testDaa(0xfa, f(0b0001), 0x60, f(0b0001));
try testDaa(0xfa, f(0b0010), 0x60, f(0b0001));
try testDaa(0xfa, f(0b0011), 0x60, f(0b0001));
try testDaa(0xfa, f(0b0100), 0xfa, f(0b0100));
try testDaa(0xfa, f(0b0101), 0x9a, f(0b0101));
try testDaa(0xfa, f(0b0110), 0xf4, f(0b0100));
try testDaa(0xfa, f(0b0111), 0x94, f(0b0101));
try testDaa(0xfa, f(0b1000), 0x60, f(0b0001));
try testDaa(0xfa, f(0b1001), 0x60, f(0b0001));
try testDaa(0xfa, f(0b1010), 0x60, f(0b0001));
try testDaa(0xfa, f(0b1011), 0x60, f(0b0001));
try testDaa(0xfa, f(0b1100), 0xfa, f(0b0100));
try testDaa(0xfa, f(0b1101), 0x9a, f(0b0101));
try testDaa(0xfa, f(0b1110), 0xf4, f(0b0100));
try testDaa(0xfa, f(0b1111), 0x94, f(0b0101));
try testDaa(0xfb, f(0b0000), 0x61, f(0b0001));
try testDaa(0xfb, f(0b0001), 0x61, f(0b0001));
try testDaa(0xfb, f(0b0010), 0x61, f(0b0001));
try testDaa(0xfb, f(0b0011), 0x61, f(0b0001));
try testDaa(0xfb, f(0b0100), 0xfb, f(0b0100));
try testDaa(0xfb, f(0b0101), 0x9b, f(0b0101));
try testDaa(0xfb, f(0b0110), 0xf5, f(0b0100));
try testDaa(0xfb, f(0b0111), 0x95, f(0b0101));
try testDaa(0xfb, f(0b1000), 0x61, f(0b0001));
try testDaa(0xfb, f(0b1001), 0x61, f(0b0001));
try testDaa(0xfb, f(0b1010), 0x61, f(0b0001));
try testDaa(0xfb, f(0b1011), 0x61, f(0b0001));
try testDaa(0xfb, f(0b1100), 0xfb, f(0b0100));
try testDaa(0xfb, f(0b1101), 0x9b, f(0b0101));
try testDaa(0xfb, f(0b1110), 0xf5, f(0b0100));
try testDaa(0xfb, f(0b1111), 0x95, f(0b0101));
try testDaa(0xfc, f(0b0000), 0x62, f(0b0001));
try testDaa(0xfc, f(0b0001), 0x62, f(0b0001));
try testDaa(0xfc, f(0b0010), 0x62, f(0b0001));
try testDaa(0xfc, f(0b0011), 0x62, f(0b0001));
try testDaa(0xfc, f(0b0100), 0xfc, f(0b0100));
try testDaa(0xfc, f(0b0101), 0x9c, f(0b0101));
try testDaa(0xfc, f(0b0110), 0xf6, f(0b0100));
try testDaa(0xfc, f(0b0111), 0x96, f(0b0101));
try testDaa(0xfc, f(0b1000), 0x62, f(0b0001));
try testDaa(0xfc, f(0b1001), 0x62, f(0b0001));
try testDaa(0xfc, f(0b1010), 0x62, f(0b0001));
try testDaa(0xfc, f(0b1011), 0x62, f(0b0001));
try testDaa(0xfc, f(0b1100), 0xfc, f(0b0100));
try testDaa(0xfc, f(0b1101), 0x9c, f(0b0101));
try testDaa(0xfc, f(0b1110), 0xf6, f(0b0100));
try testDaa(0xfc, f(0b1111), 0x96, f(0b0101));
try testDaa(0xfd, f(0b0000), 0x63, f(0b0001));
try testDaa(0xfd, f(0b0001), 0x63, f(0b0001));
try testDaa(0xfd, f(0b0010), 0x63, f(0b0001));
try testDaa(0xfd, f(0b0011), 0x63, f(0b0001));
try testDaa(0xfd, f(0b0100), 0xfd, f(0b0100));
try testDaa(0xfd, f(0b0101), 0x9d, f(0b0101));
try testDaa(0xfd, f(0b0110), 0xf7, f(0b0100));
try testDaa(0xfd, f(0b0111), 0x97, f(0b0101));
try testDaa(0xfd, f(0b1000), 0x63, f(0b0001));
try testDaa(0xfd, f(0b1001), 0x63, f(0b0001));
try testDaa(0xfd, f(0b1010), 0x63, f(0b0001));
try testDaa(0xfd, f(0b1011), 0x63, f(0b0001));
try testDaa(0xfd, f(0b1100), 0xfd, f(0b0100));
try testDaa(0xfd, f(0b1101), 0x9d, f(0b0101));
try testDaa(0xfd, f(0b1110), 0xf7, f(0b0100));
try testDaa(0xfd, f(0b1111), 0x97, f(0b0101));
try testDaa(0xfe, f(0b0000), 0x64, f(0b0001));
try testDaa(0xfe, f(0b0001), 0x64, f(0b0001));
try testDaa(0xfe, f(0b0010), 0x64, f(0b0001));
try testDaa(0xfe, f(0b0011), 0x64, f(0b0001));
try testDaa(0xfe, f(0b0100), 0xfe, f(0b0100));
try testDaa(0xfe, f(0b0101), 0x9e, f(0b0101));
try testDaa(0xfe, f(0b0110), 0xf8, f(0b0100));
try testDaa(0xfe, f(0b0111), 0x98, f(0b0101));
try testDaa(0xfe, f(0b1000), 0x64, f(0b0001));
try testDaa(0xfe, f(0b1001), 0x64, f(0b0001));
try testDaa(0xfe, f(0b1010), 0x64, f(0b0001));
try testDaa(0xfe, f(0b1011), 0x64, f(0b0001));
try testDaa(0xfe, f(0b1100), 0xfe, f(0b0100));
try testDaa(0xfe, f(0b1101), 0x9e, f(0b0101));
try testDaa(0xfe, f(0b1110), 0xf8, f(0b0100));
try testDaa(0xfe, f(0b1111), 0x98, f(0b0101));
try testDaa(0xff, f(0b0000), 0x65, f(0b0001));
try testDaa(0xff, f(0b0001), 0x65, f(0b0001));
try testDaa(0xff, f(0b0010), 0x65, f(0b0001));
try testDaa(0xff, f(0b0011), 0x65, f(0b0001));
try testDaa(0xff, f(0b0100), 0xff, f(0b0100));
try testDaa(0xff, f(0b0101), 0x9f, f(0b0101));
try testDaa(0xff, f(0b0110), 0xf9, f(0b0100));
try testDaa(0xff, f(0b0111), 0x99, f(0b0101));
try testDaa(0xff, f(0b1000), 0x65, f(0b0001));
try testDaa(0xff, f(0b1001), 0x65, f(0b0001));
try testDaa(0xff, f(0b1010), 0x65, f(0b0001));
try testDaa(0xff, f(0b1011), 0x65, f(0b0001));
try testDaa(0xff, f(0b1100), 0xff, f(0b0100));
try testDaa(0xff, f(0b1101), 0x9f, f(0b0101));
try testDaa(0xff, f(0b1110), 0xf9, f(0b0100));
try testDaa(0xff, f(0b1111), 0x99, f(0b0101));
} | src/Cpu/impl_daa_test.zig |
const std = @import("std");
pub fn build(b: *std.build.Builder) !void {
// I am creating an executable. This will generate an ELF executable, which
// the Raspberry Pi bootloader cannot run directly. Later it will be
// converted to something more appropriate to our needs.
const exe = b.addExecutable("simplest", "src/main.zig");
// I want an optimized build.
exe.setBuildMode(std.builtin.Mode.ReleaseFast);
// Configure the target. The target tells the compiler details about the
// hardware and software that going to run the program.
const target = .{
// The Pi 3 has an ARM CPU, so I set it to `arm`. In fact, I think I
// could have used `aarch64` here, since it is a 64-bit CPU, but using
// it in 32-bit mode seemed simpler (because I recently did a similar
// example in assembly using 32 bits). Worth noting that smaller devices
// like the Raspberry Pi Pico, which feature ARM-M CPUs, must use
// `thumb` here because they don't support the "classic" ARM instruction
// set, only the Thumb instruction set.
.cpu_arch = .arm,
// Specifically, the PI 3 has a Cortex A53 CPU. I understand that this
// will help the compiler to know, for example, which assembly
// instructions it can use in the compiled program. Here I knew exactly
// CPU I wanted to target, so I used it. When in doubt, I think that
// `baseline` is a safe option representing the most basic CPU of the
// selected architecture.
.cpu_model = .{ .explicit = &std.Target.arm.cpu.cortex_a53 },
// This is a bare metal program, not using any operating system. That's
// what `freestanding` means.
.os_tag = .freestanding,
// The ABI (Application Binary Interface) defines how different compiled
// modules communicate with each other (for example, if function
// arguments are passed on registers or on the stack). Here I am using
// EABIHF, which is the ARM ABI that allows using floating-point
// registers to pass arguments between functions ("HF" stands for
// something like "hardware floats"). I am using it because the Pi 3 has
// an FPU and therefore these registers shall be available, but this
// program doesn't do anything with floating-point, so I could have used
// `eabi` as well. (Worth noting: this ABI setting affects only how
// floating point arguments are passed in function calls; it doesn't say
// anything about the ability to use the FPU. It's OK to use `eabi` and
// still use the FPU to do the actual calculations.)
.abi = .eabihf,
};
exe.setTarget(target);
// I need be sure that the program's entry point is placed at the very start
// of the binary image. Additionally, I want to discard several sections
// from the generated ELF that the compiler tries to add. I use a linker
// script to do that. See `simplest.ld` for details.
exe.setLinkerScriptPath(std.build.FileSource{
.path = "simplest.ld",
});
// This says that the ELF executable will be copied to `zig-out/bin/` as
// part of the `install` step. The `dump-elf` (defined below) step will need
// this. (Not sure I understand this correctly, but here I go: if I omit
// this line, the build system can assume that I am not interested in the
// executable, so it will not be placed under `zig-out`.)
exe.install();
// With `addInstallRaw()` I tell the build system that I want to generate a
// raw binary image from the ELF executable we generated above. This is the
// binary the Pi 3 can run. I make this "bin generation step" a dependency
// of the default "install step" so that it gets executed on a regular
// `zig build`.
const bin = b.addInstallRaw(exe, "kernel7.img", .{});
b.getInstallStep().dependOn(&bin.step);
// Here I add a step to disassemble the intermediate ELF executable. Handy
// to troubleshoot issues with the linker script. Note how I say that this
// step depends on the `install` step. That's because the command we run
// here expects to find the ELF executable at `zig-out/bin/`, and it is the
// `install` step that places it there. Run with `zig build dump-elf`.
const dumpELFCommand = b.addSystemCommand(&[_][]const u8{
"arm-none-eabi-objdump",
"-D",
"-m",
"arm",
b.getInstallPath(.{ .custom = "bin" }, exe.out_filename),
});
dumpELFCommand.step.dependOn(b.getInstallStep());
const dumpELFStep = b.step("dump-elf", "Disassemble the ELF executable");
dumpELFStep.dependOn(&dumpELFCommand.step);
// As above, but for disassembling the final raw binary image. Use to check
// the final result, the code that will actually run on the Raspberry Pi.
// Run with `zig build dump-bin`
const dumpBinCommand = b.addSystemCommand(&[_][]const u8{
"arm-none-eabi-objdump",
"-D",
"-m",
"arm",
"-b",
"binary",
b.getInstallPath(bin.dest_dir, bin.dest_filename),
});
dumpBinCommand.step.dependOn(&bin.step);
const dumpBinStep = b.step("dump-bin", "Disassemble the raw binary image");
dumpBinStep.dependOn(&dumpBinCommand.step);
} | build.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 -i shaders.glsl -o shaders.glsl.zig -l glsl330:metal_macos:hlsl4 -f sokol_zig
//
// Overview:
//
// Shader program 'display':
// Get shader desc: shd.displayShaderDesc(sg.queryBackend());
// Vertex shader: display_vs
// Attribute slots:
// ATTR_display_vs_in_pos = 0
// Fragment shader: display_fs
// Image 'tex':
// Type: ._2D
// Component Type: .FLOAT
// Bind slot: SLOT_tex = 0
//
// Shader program 'upscale':
// Get shader desc: shd.upscaleShaderDesc(sg.queryBackend());
// Vertex shader: upscale_vs
// Attribute slots:
// ATTR_upscale_vs_in_pos = 0
// Fragment shader: upscale_fs
// Image 'tex':
// Type: ._2D
// Component Type: .FLOAT
// Bind slot: SLOT_tex = 0
//
//
pub const ATTR_upscale_vs_in_pos = 0;
pub const ATTR_display_vs_in_pos = 0;
pub const SLOT_tex = 0;
//
// #version 330
//
// layout(location = 0) in vec2 in_pos;
// out vec2 uv;
//
// void main()
// {
// gl_Position = vec4((in_pos * 2.0) - vec2(1.0), 0.5, 1.0);
// uv = in_pos;
// }
//
//
const upscale_vs_source_glsl330 = [162]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,0x32,0x20,0x69,0x6e,0x5f,0x70,0x6f,
0x73,0x3b,0x0a,0x6f,0x75,0x74,0x20,0x76,0x65,0x63,0x32,0x20,0x75,0x76,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,0x76,0x65,0x63,0x34,0x28,0x28,0x69,0x6e,0x5f,0x70,0x6f,0x73,0x20,0x2a,0x20,
0x32,0x2e,0x30,0x29,0x20,0x2d,0x20,0x76,0x65,0x63,0x32,0x28,0x31,0x2e,0x30,0x29,
0x2c,0x20,0x30,0x2e,0x35,0x2c,0x20,0x31,0x2e,0x30,0x29,0x3b,0x0a,0x20,0x20,0x20,
0x20,0x75,0x76,0x20,0x3d,0x20,0x69,0x6e,0x5f,0x70,0x6f,0x73,0x3b,0x0a,0x7d,0x0a,
0x0a,0x00,
};
//
// #version 330
//
// uniform sampler2D tex;
//
// layout(location = 0) out vec4 frag_color;
// in vec2 uv;
//
// void main()
// {
// frag_color = texture(tex, uv);
// }
//
//
const upscale_fs_source_glsl330 = [146]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,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,
};
//
// #version 330
//
// layout(location = 0) in vec2 in_pos;
// out vec2 uv;
//
// void main()
// {
// gl_Position = vec4((in_pos * 2.0) - vec2(1.0), 0.5, 1.0);
// uv = in_pos;
// gl_Position.y = -gl_Position.y;
// }
//
//
const display_vs_source_glsl330 = [198]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,0x32,0x20,0x69,0x6e,0x5f,0x70,0x6f,
0x73,0x3b,0x0a,0x6f,0x75,0x74,0x20,0x76,0x65,0x63,0x32,0x20,0x75,0x76,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,0x76,0x65,0x63,0x34,0x28,0x28,0x69,0x6e,0x5f,0x70,0x6f,0x73,0x20,0x2a,0x20,
0x32,0x2e,0x30,0x29,0x20,0x2d,0x20,0x76,0x65,0x63,0x32,0x28,0x31,0x2e,0x30,0x29,
0x2c,0x20,0x30,0x2e,0x35,0x2c,0x20,0x31,0x2e,0x30,0x29,0x3b,0x0a,0x20,0x20,0x20,
0x20,0x75,0x76,0x20,0x3d,0x20,0x69,0x6e,0x5f,0x70,0x6f,0x73,0x3b,0x0a,0x20,0x20,
0x20,0x20,0x67,0x6c,0x5f,0x50,0x6f,0x73,0x69,0x74,0x69,0x6f,0x6e,0x2e,0x79,0x20,
0x3d,0x20,0x2d,0x67,0x6c,0x5f,0x50,0x6f,0x73,0x69,0x74,0x69,0x6f,0x6e,0x2e,0x79,
0x3b,0x0a,0x7d,0x0a,0x0a,0x00,
};
//
// #version 330
//
// uniform sampler2D tex;
//
// layout(location = 0) out vec4 frag_color;
// in vec2 uv;
//
// void main()
// {
// frag_color = vec4(texture(tex, uv).xyz, 1.0);
// }
//
//
const display_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,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,0x76,0x65,0x63,0x34,
0x28,0x74,0x65,0x78,0x74,0x75,0x72,0x65,0x28,0x74,0x65,0x78,0x2c,0x20,0x75,0x76,
0x29,0x2e,0x78,0x79,0x7a,0x2c,0x20,0x31,0x2e,0x30,0x29,0x3b,0x0a,0x7d,0x0a,0x0a,
0x00,
};
//
// static float4 gl_Position;
// static float2 in_pos;
// static float2 uv;
//
// struct SPIRV_Cross_Input
// {
// float2 in_pos : TEXCOORD0;
// };
//
// struct SPIRV_Cross_Output
// {
// float2 uv : TEXCOORD0;
// float4 gl_Position : SV_Position;
// };
//
// #line 9 "shaders.glsl"
// void vert_main()
// {
// #line 9 "shaders.glsl"
// gl_Position = float4((in_pos * 2.0f) - 1.0f.xx, 0.5f, 1.0f);
// uv = in_pos;
// }
//
// SPIRV_Cross_Output main(SPIRV_Cross_Input stage_input)
// {
// in_pos = stage_input.in_pos;
// vert_main();
// SPIRV_Cross_Output stage_output;
// stage_output.gl_Position = gl_Position;
// stage_output.uv = uv;
// return stage_output;
// }
//
const upscale_vs_source_hlsl4 = [619]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,0x32,0x20,0x69,0x6e,0x5f,0x70,0x6f,0x73,0x3b,
0x0a,0x73,0x74,0x61,0x74,0x69,0x63,0x20,0x66,0x6c,0x6f,0x61,0x74,0x32,0x20,0x75,
0x76,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,0x32,0x20,0x69,0x6e,0x5f,0x70,0x6f,0x73,
0x20,0x3a,0x20,0x54,0x45,0x58,0x43,0x4f,0x4f,0x52,0x44,0x30,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,0x32,0x20,0x75,0x76,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,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,0x39,0x20,0x22,0x73,0x68,0x61,0x64,
0x65,0x72,0x73,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,0x39,0x20,0x22,0x73,0x68,0x61,0x64,0x65,0x72,0x73,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,0x66,0x6c,0x6f,0x61,0x74,0x34,0x28,0x28,0x69,0x6e,
0x5f,0x70,0x6f,0x73,0x20,0x2a,0x20,0x32,0x2e,0x30,0x66,0x29,0x20,0x2d,0x20,0x31,
0x2e,0x30,0x66,0x2e,0x78,0x78,0x2c,0x20,0x30,0x2e,0x35,0x66,0x2c,0x20,0x31,0x2e,
0x30,0x66,0x29,0x3b,0x0a,0x20,0x20,0x20,0x20,0x75,0x76,0x20,0x3d,0x20,0x69,0x6e,
0x5f,0x70,0x6f,0x73,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,0x69,0x6e,0x5f,0x70,0x6f,0x73,0x20,0x3d,0x20,0x73,
0x74,0x61,0x67,0x65,0x5f,0x69,0x6e,0x70,0x75,0x74,0x2e,0x69,0x6e,0x5f,0x70,0x6f,
0x73,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,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;
//
// struct SPIRV_Cross_Input
// {
// float2 uv : TEXCOORD0;
// };
//
// struct SPIRV_Cross_Output
// {
// float4 frag_color : SV_Target0;
// };
//
// #line 10 "shaders.glsl"
// void frag_main()
// {
// #line 10 "shaders.glsl"
// frag_color = tex.Sample(_tex_sampler, uv);
// }
//
// SPIRV_Cross_Output main(SPIRV_Cross_Input stage_input)
// {
// uv = stage_input.uv;
// frag_main();
// SPIRV_Cross_Output stage_output;
// stage_output.frag_color = frag_color;
// return stage_output;
// }
//
const upscale_fs_source_hlsl4 = [575]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,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,0x32,0x20,0x75,0x76,0x20,0x3a,0x20,0x54,0x45,0x58,0x43,0x4f,0x4f,0x52,
0x44,0x30,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,0x30,0x20,0x22,0x73,0x68,0x61,0x64,0x65,0x72,0x73,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,0x30,0x20,
0x22,0x73,0x68,0x61,0x64,0x65,0x72,0x73,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,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,
};
//
// static float4 gl_Position;
// static float2 in_pos;
// static float2 uv;
//
// struct SPIRV_Cross_Input
// {
// float2 in_pos : TEXCOORD0;
// };
//
// struct SPIRV_Cross_Output
// {
// float2 uv : TEXCOORD0;
// float4 gl_Position : SV_Position;
// };
//
// #line 9 "shaders.glsl"
// void vert_main()
// {
// #line 9 "shaders.glsl"
// gl_Position = float4((in_pos * 2.0f) - 1.0f.xx, 0.5f, 1.0f);
// uv = in_pos;
// }
//
// SPIRV_Cross_Output main(SPIRV_Cross_Input stage_input)
// {
// in_pos = stage_input.in_pos;
// vert_main();
// SPIRV_Cross_Output stage_output;
// stage_output.gl_Position = gl_Position;
// stage_output.uv = uv;
// return stage_output;
// }
//
const display_vs_source_hlsl4 = [619]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,0x32,0x20,0x69,0x6e,0x5f,0x70,0x6f,0x73,0x3b,
0x0a,0x73,0x74,0x61,0x74,0x69,0x63,0x20,0x66,0x6c,0x6f,0x61,0x74,0x32,0x20,0x75,
0x76,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,0x32,0x20,0x69,0x6e,0x5f,0x70,0x6f,0x73,
0x20,0x3a,0x20,0x54,0x45,0x58,0x43,0x4f,0x4f,0x52,0x44,0x30,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,0x32,0x20,0x75,0x76,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,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,0x39,0x20,0x22,0x73,0x68,0x61,0x64,
0x65,0x72,0x73,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,0x39,0x20,0x22,0x73,0x68,0x61,0x64,0x65,0x72,0x73,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,0x66,0x6c,0x6f,0x61,0x74,0x34,0x28,0x28,0x69,0x6e,
0x5f,0x70,0x6f,0x73,0x20,0x2a,0x20,0x32,0x2e,0x30,0x66,0x29,0x20,0x2d,0x20,0x31,
0x2e,0x30,0x66,0x2e,0x78,0x78,0x2c,0x20,0x30,0x2e,0x35,0x66,0x2c,0x20,0x31,0x2e,
0x30,0x66,0x29,0x3b,0x0a,0x20,0x20,0x20,0x20,0x75,0x76,0x20,0x3d,0x20,0x69,0x6e,
0x5f,0x70,0x6f,0x73,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,0x69,0x6e,0x5f,0x70,0x6f,0x73,0x20,0x3d,0x20,0x73,
0x74,0x61,0x67,0x65,0x5f,0x69,0x6e,0x70,0x75,0x74,0x2e,0x69,0x6e,0x5f,0x70,0x6f,
0x73,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,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;
//
// struct SPIRV_Cross_Input
// {
// float2 uv : TEXCOORD0;
// };
//
// struct SPIRV_Cross_Output
// {
// float4 frag_color : SV_Target0;
// };
//
// #line 11 "shaders.glsl"
// void frag_main()
// {
// #line 11 "shaders.glsl"
// frag_color = float4(tex.Sample(_tex_sampler, uv).xyz, 1.0f);
// }
//
// SPIRV_Cross_Output main(SPIRV_Cross_Input stage_input)
// {
// uv = stage_input.uv;
// frag_main();
// SPIRV_Cross_Output stage_output;
// stage_output.frag_color = frag_color;
// return stage_output;
// }
//
const display_fs_source_hlsl4 = [593]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,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,0x32,0x20,0x75,0x76,0x20,0x3a,0x20,0x54,0x45,0x58,0x43,0x4f,0x4f,0x52,
0x44,0x30,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,0x31,0x20,0x22,0x73,0x68,0x61,0x64,0x65,0x72,0x73,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,0x31,0x20,
0x22,0x73,0x68,0x61,0x64,0x65,0x72,0x73,0x2e,0x67,0x6c,0x73,0x6c,0x22,0x0a,0x20,
0x20,0x20,0x20,0x66,0x72,0x61,0x67,0x5f,0x63,0x6f,0x6c,0x6f,0x72,0x20,0x3d,0x20,
0x66,0x6c,0x6f,0x61,0x74,0x34,0x28,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,0x2e,0x78,0x79,0x7a,0x2c,0x20,0x31,0x2e,0x30,0x66,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,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
// {
// float2 uv [[user(locn0)]];
// float4 gl_Position [[position]];
// };
//
// struct main0_in
// {
// float2 in_pos [[attribute(0)]];
// };
//
// #line 9 "shaders.glsl"
// vertex main0_out main0(main0_in in [[stage_in]])
// {
// main0_out out = {};
// #line 9 "shaders.glsl"
// out.gl_Position = float4((in.in_pos * 2.0) - float2(1.0), 0.5, 1.0);
// out.uv = in.in_pos;
// return out;
// }
//
//
const upscale_vs_source_metal_macos = [459]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,0x32,0x20,0x75,0x76,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,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,0x32,0x20,
0x69,0x6e,0x5f,0x70,0x6f,0x73,0x20,0x5b,0x5b,0x61,0x74,0x74,0x72,0x69,0x62,0x75,
0x74,0x65,0x28,0x30,0x29,0x5d,0x5d,0x3b,0x0a,0x7d,0x3b,0x0a,0x0a,0x23,0x6c,0x69,
0x6e,0x65,0x20,0x39,0x20,0x22,0x73,0x68,0x61,0x64,0x65,0x72,0x73,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,0x39,0x20,0x22,0x73,0x68,0x61,0x64,0x65,0x72,0x73,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,0x66,0x6c,0x6f,0x61,
0x74,0x34,0x28,0x28,0x69,0x6e,0x2e,0x69,0x6e,0x5f,0x70,0x6f,0x73,0x20,0x2a,0x20,
0x32,0x2e,0x30,0x29,0x20,0x2d,0x20,0x66,0x6c,0x6f,0x61,0x74,0x32,0x28,0x31,0x2e,
0x30,0x29,0x2c,0x20,0x30,0x2e,0x35,0x2c,0x20,0x31,0x2e,0x30,0x29,0x3b,0x0a,0x20,
0x20,0x20,0x20,0x6f,0x75,0x74,0x2e,0x75,0x76,0x20,0x3d,0x20,0x69,0x6e,0x2e,0x69,
0x6e,0x5f,0x70,0x6f,0x73,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(locn0)]];
// };
//
// #line 10 "shaders.glsl"
// fragment main0_out main0(main0_in in [[stage_in]], texture2d<float> tex [[texture(0)]], sampler texSmplr [[sampler(0)]])
// {
// main0_out out = {};
// #line 10 "shaders.glsl"
// out.frag_color = tex.sample(texSmplr, in.uv);
// return out;
// }
//
//
const upscale_fs_source_metal_macos = [449]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,0x30,0x29,
0x5d,0x5d,0x3b,0x0a,0x7d,0x3b,0x0a,0x0a,0x23,0x6c,0x69,0x6e,0x65,0x20,0x31,0x30,
0x20,0x22,0x73,0x68,0x61,0x64,0x65,0x72,0x73,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,0x30,0x20,0x22,0x73,0x68,0x61,
0x64,0x65,0x72,0x73,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,
};
//
// #include <metal_stdlib>
// #include <simd/simd.h>
//
// using namespace metal;
//
// struct main0_out
// {
// float2 uv [[user(locn0)]];
// float4 gl_Position [[position]];
// };
//
// struct main0_in
// {
// float2 in_pos [[attribute(0)]];
// };
//
// #line 9 "shaders.glsl"
// vertex main0_out main0(main0_in in [[stage_in]])
// {
// main0_out out = {};
// #line 9 "shaders.glsl"
// out.gl_Position = float4((in.in_pos * 2.0) - float2(1.0), 0.5, 1.0);
// out.uv = in.in_pos;
// return out;
// }
//
//
const display_vs_source_metal_macos = [459]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,0x32,0x20,0x75,0x76,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,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,0x32,0x20,
0x69,0x6e,0x5f,0x70,0x6f,0x73,0x20,0x5b,0x5b,0x61,0x74,0x74,0x72,0x69,0x62,0x75,
0x74,0x65,0x28,0x30,0x29,0x5d,0x5d,0x3b,0x0a,0x7d,0x3b,0x0a,0x0a,0x23,0x6c,0x69,
0x6e,0x65,0x20,0x39,0x20,0x22,0x73,0x68,0x61,0x64,0x65,0x72,0x73,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,0x39,0x20,0x22,0x73,0x68,0x61,0x64,0x65,0x72,0x73,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,0x66,0x6c,0x6f,0x61,
0x74,0x34,0x28,0x28,0x69,0x6e,0x2e,0x69,0x6e,0x5f,0x70,0x6f,0x73,0x20,0x2a,0x20,
0x32,0x2e,0x30,0x29,0x20,0x2d,0x20,0x66,0x6c,0x6f,0x61,0x74,0x32,0x28,0x31,0x2e,
0x30,0x29,0x2c,0x20,0x30,0x2e,0x35,0x2c,0x20,0x31,0x2e,0x30,0x29,0x3b,0x0a,0x20,
0x20,0x20,0x20,0x6f,0x75,0x74,0x2e,0x75,0x76,0x20,0x3d,0x20,0x69,0x6e,0x2e,0x69,
0x6e,0x5f,0x70,0x6f,0x73,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(locn0)]];
// };
//
// #line 11 "shaders.glsl"
// fragment main0_out main0(main0_in in [[stage_in]], texture2d<float> tex [[texture(0)]], sampler texSmplr [[sampler(0)]])
// {
// main0_out out = {};
// #line 11 "shaders.glsl"
// out.frag_color = float4(tex.sample(texSmplr, in.uv).xyz, 1.0);
// return out;
// }
//
//
const display_fs_source_metal_macos = [466]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,0x30,0x29,
0x5d,0x5d,0x3b,0x0a,0x7d,0x3b,0x0a,0x0a,0x23,0x6c,0x69,0x6e,0x65,0x20,0x31,0x31,
0x20,0x22,0x73,0x68,0x61,0x64,0x65,0x72,0x73,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,0x31,0x20,0x22,0x73,0x68,0x61,
0x64,0x65,0x72,0x73,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,
0x66,0x6c,0x6f,0x61,0x74,0x34,0x28,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,0x2e,0x78,0x79,0x7a,0x2c,0x20,0x31,0x2e,0x30,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 displayShaderDesc(backend: sg.Backend) sg.ShaderDesc {
var desc: sg.ShaderDesc = .{};
switch (backend) {
.GLCORE33 => {
desc.attrs[0].name = "in_pos";
desc.vs.source = &display_vs_source_glsl330;
desc.vs.entry = "main";
desc.fs.source = &display_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 = "display_shader";
},
.D3D11 => {
desc.attrs[0].sem_name = "TEXCOORD";
desc.attrs[0].sem_index = 0;
desc.vs.source = &display_vs_source_hlsl4;
desc.vs.d3d11_target = "vs_4_0";
desc.vs.entry = "main";
desc.fs.source = &display_fs_source_hlsl4;
desc.fs.d3d11_target = "ps_4_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 = "display_shader";
},
.METAL_MACOS => {
desc.vs.source = &display_vs_source_metal_macos;
desc.vs.entry = "main0";
desc.fs.source = &display_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 = "display_shader";
},
else => {},
}
return desc;
}
pub fn upscaleShaderDesc(backend: sg.Backend) sg.ShaderDesc {
var desc: sg.ShaderDesc = .{};
switch (backend) {
.GLCORE33 => {
desc.attrs[0].name = "in_pos";
desc.vs.source = &upscale_vs_source_glsl330;
desc.vs.entry = "main";
desc.fs.source = &upscale_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 = "upscale_shader";
},
.D3D11 => {
desc.attrs[0].sem_name = "TEXCOORD";
desc.attrs[0].sem_index = 0;
desc.vs.source = &upscale_vs_source_hlsl4;
desc.vs.d3d11_target = "vs_4_0";
desc.vs.entry = "main";
desc.fs.source = &upscale_fs_source_hlsl4;
desc.fs.d3d11_target = "ps_4_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 = "upscale_shader";
},
.METAL_MACOS => {
desc.vs.source = &upscale_vs_source_metal_macos;
desc.vs.entry = "main0";
desc.fs.source = &upscale_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 = "upscale_shader";
},
else => {},
}
return desc;
} | src/host/shaders/shaders.glsl.zig |
const std = @import("std");
const testing = std.testing;
const meta = std.meta;
const trait = std.meta.trait;
const log = std.log.scoped(.wasm_zig);
var CALLBACK: usize = undefined;
// @TODO: Split these up into own error sets
pub const Error = error{
/// Failed to initialize a `Config`
ConfigInit,
/// Failed to initialize an `Engine` (i.e. invalid config)
EngineInit,
/// Failed to initialize a `Store`
StoreInit,
/// Failed to initialize a `Module`
ModuleInit,
/// Failed to create a wasm function based on
/// the given `Store` and functype
FuncInit,
/// Failed to initialize a new `Instance`
InstanceInit,
};
pub const Config = opaque {
pub fn init() !*Config {
const config = wasm_config_new() orelse return Error.ConfigInit;
return config;
}
extern "c" fn wasm_config_new() ?*Config;
};
pub const Engine = opaque {
/// Initializes a new `Engine`
pub fn init() !*Engine {
return wasm_engine_new() orelse Error.EngineInit;
}
pub fn withConfig(config: *Config) !*Engine {
return wasm_engine_new_with_config(config) orelse Error.EngineInit;
}
/// Frees the resources of the `Engine`
pub fn deinit(self: *Engine) void {
wasm_engine_delete(self);
}
extern "c" fn wasm_engine_new() ?*Engine;
extern "c" fn wasm_engine_new_with_config(*Config) ?*Engine;
extern "c" fn wasm_engine_delete(*Engine) void;
};
pub const Store = opaque {
/// Initializes a new `Store` based on the given `Engine`
pub fn init(engine: *Engine) !*Store {
return wasm_store_new(engine) orelse Error.StoreInit;
}
/// Frees the resource of the `Store` itself
pub fn deinit(self: *Store) void {
wasm_store_delete(self);
}
extern "c" fn wasm_store_new(*Engine) ?*Store;
extern "c" fn wasm_store_delete(*Store) void;
};
pub const Module = opaque {
/// Initializes a new `Module` using the supplied Store and wasm bytecode
pub fn init(store: *Store, bytes: []const u8) !*Module {
var byte_vec = ByteVec.initWithCapacity(bytes.len);
defer byte_vec.deinit();
var i: usize = 0;
var ptr = byte_vec.data;
while (i < bytes.len) : (i += 1) {
ptr.* = bytes[i];
ptr += 1;
}
return wasm_module_new(store, &byte_vec) orelse return Error.ModuleInit;
}
pub fn deinit(self: *Module) void {
wasm_module_delete(self);
}
/// Returns a list of export types in `ExportTypeVec`
pub fn exports(self: *Module) ExportTypeVec {
var vec: ExportTypeVec = undefined;
wasm_module_exports(self, &vec);
return vec;
}
extern "c" fn wasm_module_new(*Store, *const ByteVec) ?*Module;
extern "c" fn wasm_module_delete(*Module) void;
extern "c" fn wasm_module_exports(?*const Module, *ExportTypeVec) void;
};
fn cb(params: ?*const Valtype, results: ?*Valtype) callconv(.C) ?*Trap {
const func = @intToPtr(fn () void, CALLBACK);
func();
return null;
}
pub const Func = opaque {
pub const CallError = error{
/// Failed to call the function
/// and resulted into an error
InnerError,
/// When the user provided a different ResultType to `Func.call`
/// than what is defined by the wasm binary
InvalidResultType,
/// The given argument count to `Func.call` mismatches that
/// of the func argument count of the wasm binary
InvalidParamCount,
/// The wasm function number of results mismatch that of the given
/// ResultType to `Func.Call`. Note that `void` equals to 0 result types.
InvalidResultCount,
/// Function call resulted in an unexpected trap.
Trap,
};
pub fn init(store: *Store, callback: anytype) !*Func {
const cb_meta = @typeInfo(@TypeOf(callback));
switch (cb_meta) {
.Fn => {
if (cb_meta.Fn.args.len > 0 or cb_meta.Fn.return_type.? != void) {
@compileError("only callbacks with no input args and no results are currently supported");
}
},
else => @compileError("only functions can be used as callbacks into Wasm"),
}
CALLBACK = @ptrToInt(callback);
var args = ValtypeVec.empty();
var results = ValtypeVec.empty();
const functype = wasm_functype_new(&args, &results) orelse return Error.FuncInit;
defer wasm_functype_delete(functype);
return wasm_func_new(store, functype, cb) orelse Error.FuncInit;
}
/// Returns the `Func` as an `Extern`
///
/// Owned by `self` and shouldn't be deinitialized
pub fn asExtern(self: *Func) *Extern {
return wasm_func_as_extern(self).?;
}
/// Returns the `Func` from an `Extern`
/// return null if extern's type isn't a functype
///
/// Owned by `extern_func` and shouldn't be deinitialized
pub fn fromExtern(extern_func: *Extern) ?*Func {
return extern_func.asFunc();
}
/// Creates a copy of the current `Func`
/// returned copy is owned by the caller and must be freed
/// by the owner
pub fn copy(self: *Func) *Func {
return self.wasm_func_copy().?;
}
/// Tries to call the wasm function
/// expects `args` to be tuple of arguments
pub fn call(self: *Func, comptime ResultType: type, args: anytype) CallError!ResultType {
if (!comptime trait.isTuple(@TypeOf(args)))
@compileError("Expected 'args' to be a tuple, but found type '" ++ @typeName(@TypeOf(args)) ++ "'");
const args_len = args.len;
comptime var wasm_args: [args_len]Value = undefined;
inline for (wasm_args) |*arg, i| {
arg.* = switch (@TypeOf(args[i])) {
i32, u32 => .{ .kind = .i32, .of = .{ .i32 = @intCast(i32, args[i]) } },
i64, u64 => .{ .kind = .i64, .of = .{ .i64 = @intCast(i64, args[i]) } },
f32 => .{ .kind = .f32, .of = .{ .f32 = args[i] } },
f64 => .{ .kind = .f64, .of = .{ .f64 = args[i] } },
*Func => .{ .kind = .funcref, .of = .{ .ref = args[i] } },
*Extern => .{ .kind = .anyref, .of = .{ .ref = args[i] } },
else => |ty| @compileError("Unsupported argument type '" ++ @typeName(ty) + "'"),
};
}
// TODO multiple return values
const result_len: usize = if (ResultType == void) 0 else 1;
if (result_len != wasm_func_result_arity(self)) return CallError.InvalidResultCount;
if (args_len != wasm_func_param_arity(self)) return CallError.InvalidParamCount;
const final_args = ValVec{
.size = args_len,
.data = if (args_len == 0) undefined else @ptrCast([*]Value, &wasm_args),
};
var result_list = ValVec.initWithCapacity(result_len);
defer result_list.deinit();
const trap = wasm_func_call(self, &final_args, &result_list);
if (trap) |t| {
t.deinit();
// TODO handle trap message
log.err("code unexpectedly trapped", .{});
return CallError.Trap;
}
if (ResultType == void) return;
// TODO: Handle multiple returns
const result_ty = result_list.data[0];
if (!matchesKind(ResultType, result_ty.kind)) return CallError.InvalidResultType;
return switch (ResultType) {
i32, u32 => @intCast(ResultType, result_ty.of.i32),
i64, u64 => @intCast(ResultType, result_ty.of.i64),
f32 => result_ty.of.f32,
f64 => result_ty.of.f64,
*Func => @ptrCast(?*Func, result_ty.of.ref).?,
*Extern => @ptrCast(?*Extern, result_ty.of.ref).?,
else => |ty| @compileError("Unsupported result type '" ++ @typeName(ty) ++ "'"),
};
}
pub fn deinit(self: *Func) void {
wasm_func_delete(self);
}
/// Returns tue if the given `kind` of `Valkind` can coerce to type `T`
pub fn matchesKind(comptime T: type, kind: Valkind) bool {
return switch (T) {
i32, u32 => kind == .i32,
i64, u64 => kind == .i64,
f32 => kind == .f32,
f64 => kind == .f64,
*Func => kind == .funcref,
*Extern => kind == .ref,
else => false,
};
}
extern "c" fn wasm_func_new(*Store, ?*c_void, Callback) ?*Func;
extern "c" fn wasm_func_delete(*Func) void;
extern "c" fn wasm_func_as_extern(*Func) ?*Extern;
extern "c" fn wasm_func_copy(*const Func) ?*Func;
extern "c" fn wasm_func_call(*Func, *const ValVec, *ValVec) ?*Trap;
extern "c" fn wasm_func_result_arity(*Func) usize;
extern "c" fn wasm_func_param_arity(*Func) usize;
};
pub const Instance = opaque {
/// Initializes a new `Instance` using the given `store` and `mode`.
/// The given slice defined in `import` must match what was initialized
/// using the same `Store` as given.
pub fn init(store: *Store, module: *Module, import: []const *Func) !*Instance {
var trap: ?*Trap = null;
var imports = ExternVec.initWithCapacity(import.len);
defer imports.deinit();
var ptr = imports.data;
for (import) |func| {
ptr.* = func.asExtern();
ptr += 1;
}
const instance = wasm_instance_new(store, module, &imports, &trap);
if (trap) |t| {
defer t.deinit();
// TODO handle trap message
log.err("code unexpectedly trapped", .{});
return Error.InstanceInit;
}
return instance orelse Error.InstanceInit;
}
/// Returns an export func by its name if found
/// Asserts the export is of type `Func`
/// The returned `Func` is a copy and must be freed by the caller
pub fn getExportFunc(self: *Instance, module: *Module, name: []const u8) ?*Func {
return if (self.getExport(module, name)) |exp| {
defer exp.deinit(); // free the copy
return exp.asFunc().copy();
} else null;
}
/// Returns an export by its name and `null` when not found
/// The `Extern` is copied and must be freed manually
///
/// a `Module` must be provided to find an extern by its name, rather than index.
/// use getExportByIndex for quick access to an extern by index.
pub fn getExport(self: *Instance, module: *Module, name: []const u8) ?*Extern {
var externs: ExternVec = undefined;
wasm_instance_exports(self, &externs);
defer externs.deinit();
var exports = module.exports();
defer exports.deinit();
return for (exports.toSlice()) |export_type, index| {
const ty = export_type orelse continue;
const type_name = ty.name();
defer type_name.deinit();
if (std.mem.eql(u8, name, type_name.toSlice())) {
if (externs.data[index]) |ext| {
break ext.copy();
}
}
} else null;
}
/// Returns an export by a given index. Returns null when the index
/// is out of bounds. The extern is non-owned, meaning it's illegal
/// behaviour to free its memory.
pub fn getExportByIndex(self: *Instance, index: u32) ?*Extern {
var externs: ExternVec = undefined;
wasm_instance_exports(self, &externs);
defer externs.deinit();
if (index > externs.size) return null;
return externs.data[index].?;
}
/// Returns an exported `Memory` when found and `null` when not.
/// The result is copied and must be freed manually by calling `deinit()` on the result.
pub fn getExportMem(self: *Instance, module: *Module, name: []const u8) ?*Memory {
return if (self.getExport(module, name)) |exp| {
defer exp.deinit(); // free the copy
return exp.asMemory().copy();
} else null;
}
/// Frees the `Instance`'s resources
pub fn deinit(self: *Instance) void {
wasm_instance_delete(self);
}
extern "c" fn wasm_instance_new(*Store, *const Module, *const ExternVec, *?*Trap) ?*Instance;
extern "c" fn wasm_instance_delete(*Instance) void;
extern "c" fn wasm_instance_exports(*Instance, *ExternVec) void;
};
pub const Trap = opaque {
pub fn deinit(self: *Trap) void {
wasm_trap_delete(self);
}
/// Returns the trap message.
/// Memory of the returned `ByteVec` must be freed using `deinit`
pub fn message(self: *Trap) *ByteVec {
var bytes: ?*ByteVec = null;
wasm_trap_message(self, &bytes);
return bytes.?;
}
extern "c" fn wasm_trap_delete(*Trap) void;
extern "c" fn wasm_trap_message(*const Trap, out: *?*ByteVec) void;
};
pub const Extern = opaque {
/// Returns the `Extern` as a function
/// returns `null` when the given `Extern` is not a function
///
/// Asserts `Extern` is of type `Func`
pub fn asFunc(self: *Extern) *Func {
return wasm_extern_as_func(self).?;
}
/// Returns the `Extern` as a `Memory` object
/// returns `null` when the given `Extern` is not a memory object
///
/// Asserts `Extern` is of type `Memory`
pub fn asMemory(self: *Extern) *Memory {
return wasm_extern_as_memory(self).?;
}
/// Returns the `Extern` as a `Global`
/// returns `null` when the given `Extern` is not a global
///
/// Asserts `Extern` is of type `Global`
pub fn asGlobal(self: *Extern) *Global {
return wasm_extern_as_global(self).?;
}
/// Returns the `Extern` as a `Table`
/// returns `null` when the given `Extern` is not a table
///
/// Asserts `Extern` is of type `Table`
pub fn asTable(self: *Extern) *Table {
return wasm_extern_as_table(self).?;
}
/// Frees the memory of the `Extern`
pub fn deinit(self: *Extern) void {
wasm_extern_delete(self);
}
/// Creates a copy of the `Extern` and returns it
/// Memory of the copied version must be freed manually by calling `deinit`
///
/// Asserts the copy succeeds
pub fn copy(self: *Extern) *Extern {
return wasm_extern_copy(self).?;
}
/// Checks if the given externs are equal and returns true if so
pub fn eql(self: *const Extern, other: *const Extern) bool {
return wasm_extern_same(self, other);
}
/// Returns the type of an `Extern` as `ExternType`
pub fn toType(self: *const Extern) *ExternType {
return wasm_extern_type(self).?;
}
/// Returns the kind of an `Extern`
pub fn kind(self: *const Extern) ExternKind {
return wasm_extern_kind(self);
}
extern "c" fn wasm_extern_as_func(*Extern) ?*Func;
extern "c" fn wasm_extern_as_memory(*Extern) ?*Memory;
extern "c" fn wasm_extern_as_global(*Extern) ?*Global;
extern "c" fn wasm_extern_as_table(*Extern) ?*Table;
extern "c" fn wasm_extern_delete(*Extern) void;
extern "c" fn wasm_extern_copy(*Extern) ?*Extern;
extern "c" fn wasm_extern_same(*const Extern, *const Extern) bool;
extern "c" fn wasm_extern_type(?*const Extern) ?*ExternType;
extern "c" fn wasm_extern_kind(?*const Extern) ExternKind;
};
pub const ExternKind = std.wasm.ExternalKind;
pub const ExternType = opaque {
/// Creates an `ExternType` from an existing `Extern`
pub fn fromExtern(extern_object: *const Extern) *ExternType {
return Extern.wasm_extern_type(extern_object).?;
}
/// Frees the memory of given `ExternType`
pub fn deinit(self: *ExternType) void {
wasm_externtype_delete(self);
}
/// Copies the given export type. Returned copy's memory must be
/// freed manually by calling `deinit()` on the object.
pub fn copy(self: *ExportType) *ExportType {
return wasm_externtype_copy(self).?;
}
/// Returns the `ExternKind` from a given export type.
pub fn kind(self: *const ExportType) ExternKind {
return wasm_externtype_kind(self);
}
extern "c" fn wasm_externtype_delete(?*ExportType) void;
extern "c" fn wasm_externtype_copy(?*ExportType) ?*ExportType;
extern "c" fn wasm_externtype_kind(?*const ExternType) ExternKind;
};
pub const Memory = opaque {
/// Creates a new `Memory` object for the given `Store` and `MemoryType`
pub fn init(store: *Store, mem_type: *const MemoryType) !*Memory {
return wasm_memory_new(store, mem_type) orelse error.MemoryInit;
}
/// Returns the `MemoryType` of a given `Memory` object
pub fn getType(self: *const Memory) *MemoryType {
return wasm_memory_type(self).?;
}
/// Frees the memory of the `Memory` object
pub fn deinit(self: *Memory) void {
wasm_memory_delete(self);
}
/// Creates a copy of the given `Memory` object
/// Returned copy must be freed manually.
pub fn copy(self: *const Memory) ?*Memory {
return wasm_memory_copy(self);
}
/// Returns true when the given `Memory` objects are equal
pub fn eql(self: *const Memory, other: *const Memory) bool {
return wasm_memory_same(self, other);
}
/// Returns a pointer-to-many bytes
///
/// Tip: Use toSlice() to get a slice for better ergonomics
pub fn data(self: *Memory) [*]u8 {
return wasm_memory_data(self);
}
/// Returns the data size of the `Memory` object.
pub fn size(self: *const Memory) usize {
return wasm_memory_data_size(self);
}
/// Returns the amount of pages the `Memory` object consists of
/// where each page is 65536 bytes
pub fn pages(self: *const Memory) u32 {
return wasm_memory_size(self);
}
/// Convenient helper function to represent the memory
/// as a slice of bytes. Memory is however still owned by wasm
/// and must be freed by calling `deinit` on the original `Memory` object
pub fn toSlice(self: *Memory) []const u8 {
var slice: []const u8 = undefined;
slice.ptr = self.data();
slice.len = self.size();
return slice;
}
/// Increases the amount of memory pages by the given count.
pub fn grow(self: *Memory, page_count: u32) error{OutOfMemory}!void {
if (!wasm_memory_grow(self, page_count)) return error.OutOfMemory;
}
extern "c" fn wasm_memory_delete(*Memory) void;
extern "c" fn wasm_memory_copy(*const Memory) ?*Memory;
extern "c" fn wasm_memory_same(*const Memory, *const Memory) bool;
extern "c" fn wasm_memory_new(*Store, *const MemoryType) ?*Memory;
extern "c" fn wasm_memory_type(*const Memory) *MemoryType;
extern "c" fn wasm_memory_data(*Memory) [*]u8;
extern "c" fn wasm_memory_data_size(*const Memory) usize;
extern "c" fn wasm_memory_grow(*Memory, delta: u32) bool;
extern "c" fn wasm_memory_size(*const Memory) u32;
};
pub const Limits = extern struct {
min: u32,
max: u32,
};
pub const MemoryType = opaque {
pub fn init(limits: Limits) !*MemoryType {
return wasm_memorytype_new(&limits) orelse return error.InitMemoryType;
}
pub fn deinit(self: *MemoryType) void {
wasm_memorytype_delete(self);
}
extern "c" fn wasm_memorytype_new(*const Limits) ?*MemoryType;
extern "c" fn wasm_memorytype_delete(*MemoryType) void;
};
// TODO: implement table and global types
pub const Table = opaque {};
pub const Global = opaque {};
pub const ExportType = opaque {
/// Returns the name of the given `ExportType`
pub fn name(self: *ExportType) *ByteVec {
return self.wasm_exporttype_name().?;
}
extern "c" fn wasm_exporttype_name(*ExportType) ?*ByteVec;
};
pub const ExportTypeVec = extern struct {
size: usize,
data: [*]?*ExportType,
/// Returns a slice of an `ExportTypeVec`.
/// Memory is still owned by the runtime and can only be freed using
/// `deinit()` on the original `ExportTypeVec`
pub fn toSlice(self: *const ExportTypeVec) []const ?*ExportType {
return self.data[0..self.size];
}
pub fn deinit(self: *ExportTypeVec) void {
self.wasm_exporttype_vec_delete();
}
extern "c" fn wasm_exporttype_vec_delete(*ExportTypeVec) void;
};
pub const Callback = fn (?*const Valtype, ?*Valtype) callconv(.C) ?*Trap;
pub const ByteVec = extern struct {
size: usize,
data: [*]u8,
/// Initializes a new wasm byte vector
pub fn initWithCapacity(size: usize) ByteVec {
var bytes: ByteVec = undefined;
wasm_byte_vec_new_uninitialized(&bytes, size);
return bytes;
}
/// Initializes and copies contents of the input slice
pub fn fromSlice(slice: []const u8) ByteVec {
var bytes: ByteVec = undefined;
wasm_byte_vec_new(&bytes, slice.len, slice.ptr);
return bytes;
}
/// Returns a slice to the byte vector
pub fn toSlice(self: ByteVec) []const u8 {
return self.data[0..self.size];
}
/// Frees the memory allocated by initWithCapacity
pub fn deinit(self: *ByteVec) void {
wasm_byte_vec_delete(self);
}
extern "c" fn wasm_byte_vec_new(*ByteVec, usize, [*]const u8) void;
extern "c" fn wasm_byte_vec_new_uninitialized(*ByteVec, usize) void;
extern "c" fn wasm_byte_vec_delete(*ByteVec) void;
};
pub const NameVec = extern struct {
size: usize,
data: [*]const u8,
pub fn fromSlice(slice: []const u8) NameVec {
return .{ .size = slice.len, .data = slice.ptr };
}
};
pub const ExternVec = extern struct {
size: usize,
data: [*]?*Extern,
pub fn empty() ExternVec {
return .{ .size = 0, .data = undefined };
}
pub fn deinit(self: *ExternVec) void {
wasm_extern_vec_delete(self);
}
pub fn initWithCapacity(size: usize) ExternVec {
var externs: ExternVec = undefined;
wasm_extern_vec_new_uninitialized(&externs, size);
return externs;
}
extern "c" fn wasm_extern_vec_new_empty(*ExternVec) void;
extern "c" fn wasm_extern_vec_new_uninitialized(*ExternVec, usize) void;
extern "c" fn wasm_extern_vec_delete(*ExternVec) void;
};
pub const Valkind = extern enum(u8) {
i32 = 0,
i64 = 1,
f32 = 2,
f64 = 3,
anyref = 128,
funcref = 129,
};
pub const Value = extern struct {
kind: Valkind,
of: extern union {
i32: i32,
i64: i64,
f32: f32,
f64: f64,
ref: ?*c_void,
},
};
pub const Valtype = opaque {
/// Initializes a new `Valtype` based on the given `Valkind`
pub fn init(kind: Valkind) *Valtype {
return wasm_valtype_new(@enumToInt(kind));
}
pub fn deinit(self: *Valtype) void {
wasm_valtype_delete(self);
}
/// Returns the `Valkind` of the given `Valtype`
pub fn kind(self: *Valtype) Valkind {
return @intToEnum(Valkind, wasm_valtype_kind(self));
}
extern "c" fn wasm_valtype_new(kind: u8) *Valtype;
extern "c" fn wasm_valtype_delete(*Valkind) void;
extern "c" fn wasm_valtype_kind(*Valkind) u8;
};
pub const ValtypeVec = extern struct {
size: usize,
data: [*]?*Valtype,
pub fn empty() ValtypeVec {
return .{ .size = 0, .data = undefined };
}
};
pub const ValVec = extern struct {
size: usize,
data: [*]Value,
pub fn initWithCapacity(size: usize) ValVec {
var bytes: ValVec = undefined;
wasm_val_vec_new_uninitialized(&bytes, size);
return bytes;
}
pub fn deinit(self: *ValVec) void {
self.wasm_val_vec_delete();
}
extern "c" fn wasm_val_vec_new_uninitialized(*ValVec, usize) void;
extern "c" fn wasm_val_vec_delete(*ValVec) void;
};
// Func
pub extern "c" fn wasm_functype_new(args: *ValtypeVec, results: *ValtypeVec) ?*c_void;
pub extern "c" fn wasm_functype_delete(functype: *c_void) void;
pub const WasiConfig = opaque {
/// Options to inherit when inherriting configs
/// By default all is `true` as you often want to
/// inherit everything rather than something specifically.
const InheritOptions = struct {
argv: bool = true,
env: bool = true,
std_in: bool = true,
std_out: bool = true,
std_err: bool = true,
};
pub fn init() !*WasiConfig {
return wasi_config_new() orelse error.ConfigInit;
}
pub fn deinit(self: *WasiConfig) void {
wasi_config_delete(self);
}
/// Allows to inherit the native environment into the current config.
/// Inherits everything by default.
pub fn inherit(self: *WasiConfig, options: InheritOptions) void {
if (options.argv) self.inheritArgv();
if (options.env) self.inheritEnv();
if (options.std_in) self.inheritStdIn();
if (options.std_out) self.inheritStdOut();
if (options.std_err) self.inheritStdErr();
}
pub fn inheritArgv(self: *WasiConfig) void {
wasi_config_inherit_argv(self);
}
pub fn inheritEnv(self: *WasiConfig) void {
wasi_config_inherit_env(self);
}
pub fn inheritStdIn(self: *WasiConfig) void {
wasi_config_inherit_stdin(self);
}
pub fn inheritStdOut(self: *WasiConfig) void {
wasi_config_inherit_stdout(self);
}
pub fn inheritStdErr(self: *WasiConfig) void {
wasi_config_inherit_stderr(self);
}
extern "c" fn wasi_config_new() ?*WasiConfig;
extern "c" fn wasi_config_delete(?*WasiConfig) void;
extern "c" fn wasi_config_inherit_argv(?*WasiConfig) void;
extern "c" fn wasi_config_inherit_env(?*WasiConfig) void;
extern "c" fn wasi_config_inherit_stdin(?*WasiConfig) void;
extern "c" fn wasi_config_inherit_stdout(?*WasiConfig) void;
extern "c" fn wasi_config_inherit_stderr(?*WasiConfig) void;
};
pub const WasiInstance = opaque {
pub fn init(store: *Store, name: [*:0]const u8, config: ?*WasiConfig, trap: *?*Trap) !*WasiInstance {
return wasi_instance_new(store, name, config, trap) orelse error.InstanceInit;
}
pub fn deinit(self: *WasiInstance) void {
wasm_instance_delete(self);
}
extern "c" fn wasi_instance_new(?*Store, [*:0]const u8, ?*WasiConfig, *?*Trap) ?*WasiInstance;
extern "c" fn wasm_instance_delete(?*WasiInstance) void;
};
test "" {
testing.refAllDecls(@This());
} | src/main.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const math = std.math;
const config = @import("../config.zig");
const Message = @import("../message_pool.zig").MessagePool.Message;
const vsr = @import("../vsr.zig");
const Header = vsr.Header;
const log = std.log.scoped(.journal);
pub fn Journal(comptime Replica: type, comptime Storage: type) type {
return struct {
const Self = @This();
pub const Read = struct {
self: *Self,
completion: Storage.Read,
callback: fn (self: *Replica, prepare: ?*Message, destination_replica: ?u8) void,
message: *Message,
op: u64,
checksum: u128,
destination_replica: ?u8,
};
pub const Write = struct {
pub const Trigger = enum { append, repair };
self: *Self,
callback: fn (self: *Replica, wrote: ?*Message, trigger: Trigger) void,
message: *Message,
trigger: Trigger,
/// True if this Write has acquired a lock on a sector of headers.
/// This also means that the Write is currently writing sectors or queuing to do so.
header_sector_locked: bool = false,
/// Linked list of Writes waiting to acquire the same header sector as this Write.
header_sector_next: ?*Write = null,
/// This is reset to undefined and reused for each Storage.write_sectors() call.
range: Range,
const Sector = *align(config.sector_size) [config.sector_size]u8;
fn header_sector(write: *Self.Write, journal: *Self) Sector {
assert(journal.writes.items.len == journal.headers_iops.len);
const i = @divExact(@ptrToInt(write) - @ptrToInt(&journal.writes.items), @sizeOf(Self.Write));
// TODO: the compiler should probably be smart enough to avoid needing this align cast
// as the type of `headers_iops` ensures that each buffer is properly aligned.
return @alignCast(config.sector_size, &journal.headers_iops[i]);
}
fn header_sector_same(write: *Self.Write, other: *Self.Write) bool {
return write_prepare_header_offset(write.message) ==
write_prepare_header_offset(other.message);
}
};
/// State that needs to be persisted while waiting for an overlapping
/// concurrent write to complete. This is a range on the physical disk.
const Range = struct {
completion: Storage.Write,
callback: fn (write: *Self.Write) void,
buffer: []const u8,
offset: u64,
/// If other writes are waiting on this write to proceed, they will
/// be queued up in this linked list.
next: ?*Range = null,
/// True if a Storage.write_sectors() operation is in progress for this buffer/offset.
locked: bool,
fn overlaps(self: *const Range, other: *const Range) bool {
if (self.offset < other.offset) {
return self.offset + self.buffer.len > other.offset;
} else {
return other.offset + other.buffer.len > self.offset;
}
}
};
storage: *Storage,
replica: u8,
size: u64,
size_headers: u64,
size_circular_buffer: u64,
headers: []align(config.sector_size) Header,
/// We copy-on-write to these buffers when writing, as in-memory headers may change concurrently.
/// The buffers belong to the IOP at the corresponding index in IOPS.
headers_iops: *align(config.sector_size) [config.io_depth_write][config.sector_size]u8,
/// Apart from the header written with the entry, we also store two redundant copies of each
/// header at different locations on disk, and we alternate between these for each append.
/// This tracks which version (0 or 1) should be written to next:
headers_version: u1 = 0,
/// Statically allocated read IO operation context data.
reads: IOPS(Read, config.io_depth_read) = .{},
/// Statically allocated write IO operation context data.
writes: IOPS(Write, config.io_depth_write) = .{},
/// Whether an entry is in memory only and needs to be written or is being written:
/// We use this in the same sense as a dirty bit in the kernel page cache.
/// A dirty bit means that we have not yet prepared the entry, or need to repair a faulty entry.
dirty: BitSet,
/// Whether an entry was written to disk and this write was subsequently lost due to:
/// * corruption,
/// * a misdirected write (or a misdirected read, we do not distinguish), or else
/// * a latent sector error, where the sector can no longer be read.
/// A faulty bit means that we prepared and then lost the entry.
/// A faulty bit requires the dirty bit to also be set so that functions need not check both.
/// A faulty bit is used then only to qualify the severity of the dirty bit.
faulty: BitSet,
recovered: bool = true,
recovering: bool = false,
pub fn init(
allocator: *Allocator,
storage: *Storage,
replica: u8,
size: u64,
headers_count: u32,
init_prepare: *Header,
) !Self {
if (@mod(size, config.sector_size) != 0) return error.SizeMustBeAMultipleOfSectorSize;
if (!math.isPowerOfTwo(headers_count)) return error.HeadersCountMustBeAPowerOfTwo;
assert(storage.size == size);
const headers_per_sector = @divExact(config.sector_size, @sizeOf(Header));
assert(headers_per_sector > 0);
assert(headers_count >= headers_per_sector);
var headers = try allocator.allocAdvanced(
Header,
config.sector_size,
headers_count,
.exact,
);
errdefer allocator.free(headers);
std.mem.set(Header, headers, Header.reserved());
var dirty = try BitSet.init(allocator, headers.len);
errdefer dirty.deinit(allocator);
var faulty = try BitSet.init(allocator, headers.len);
errdefer faulty.deinit(allocator);
const headers_iops = (try allocator.allocAdvanced(
[config.sector_size]u8,
config.sector_size,
config.io_depth_write,
.exact,
))[0..config.io_depth_write];
errdefer allocator.free(headers_iops);
const header_copies = 2;
const size_headers = headers.len * @sizeOf(Header);
const size_headers_copies = size_headers * header_copies;
if (size_headers_copies >= size) return error.SizeTooSmallForHeadersCount;
const size_circular_buffer = size - size_headers_copies;
if (size_circular_buffer < 64 * 1024 * 1024) return error.SizeTooSmallForCircularBuffer;
log.debug("{}: size={} headers_len={} headers={} circular_buffer={}", .{
replica,
std.fmt.fmtIntSizeBin(size),
headers.len,
std.fmt.fmtIntSizeBin(size_headers),
std.fmt.fmtIntSizeBin(size_circular_buffer),
});
var self = Self{
.storage = storage,
.replica = replica,
.size = size,
.size_headers = size_headers,
.size_circular_buffer = size_circular_buffer,
.headers = headers,
.dirty = dirty,
.faulty = faulty,
.headers_iops = headers_iops,
};
assert(@mod(self.size_circular_buffer, config.sector_size) == 0);
assert(@mod(@ptrToInt(&self.headers[0]), config.sector_size) == 0);
assert(self.dirty.bits.len == self.headers.len);
assert(self.faulty.bits.len == self.headers.len);
// Op 0 is always the cluster initialization op.
// TODO This will change when we implement synchronized incremental snapshots.
assert(init_prepare.valid_checksum());
assert(init_prepare.invalid() == null);
self.headers[0] = init_prepare.*;
self.assert_headers_reserved_from(init_prepare.op + 1);
return self;
}
pub fn deinit(self: *Self, allocator: *Allocator) void {
const replica = @fieldParentPtr(Replica, "journal", self);
self.dirty.deinit(allocator);
self.faulty.deinit(allocator);
allocator.free(self.headers);
allocator.free(self.headers_iops);
{
var it = self.reads.iterate();
while (it.next()) |read| replica.message_bus.unref(read.message);
}
{
var it = self.writes.iterate();
while (it.next()) |write| replica.message_bus.unref(write.message);
}
}
/// Asserts that headers are .reserved (zeroed) from `op_min` (inclusive).
pub fn assert_headers_reserved_from(self: *Self, op_min: u64) void {
// TODO Snapshots
for (self.headers[op_min..]) |header| assert(header.command == .reserved);
}
/// Returns any existing entry at the location indicated by header.op.
/// This existing entry may have an older or newer op number.
pub fn entry(self: *Self, header: *const Header) ?*const Header {
assert(header.command == .prepare);
return self.entry_for_op(header.op);
}
/// We use the op number directly to index into the headers array and locate ops without a scan.
/// Op numbers cycle through the headers array and do not wrap when offsets wrap. The reason for
/// this is to prevent variable offsets from impacting the location of an op. Otherwise, the
/// same op number but for different views could exist at multiple locations in the journal.
pub fn entry_for_op(self: *Self, op: u64) ?*const Header {
// TODO Snapshots
const existing = &self.headers[op];
if (existing.command == .reserved) return null;
assert(existing.command == .prepare);
return existing;
}
/// Returns the entry at `@mod(op)` location, but only if `entry.op == op`, else `null`.
/// Be careful of using this without considering that there may still be an existing op.
pub fn entry_for_op_exact(self: *Self, op: u64) ?*const Header {
if (self.entry_for_op(op)) |existing| {
if (existing.op == op) return existing;
}
return null;
}
/// As per `entry_for_op_exact()`, but only if there is an optional checksum match.
pub fn entry_for_op_exact_with_checksum(
self: *Self,
op: u64,
checksum: ?u128,
) ?*const Header {
if (self.entry_for_op_exact(op)) |existing| {
assert(existing.op == op);
if (checksum == null or existing.checksum == checksum.?) return existing;
}
return null;
}
pub fn previous_entry(self: *Self, header: *const Header) ?*const Header {
// TODO Snapshots
if (header.op == 0) return null;
return self.entry_for_op(header.op - 1);
}
pub fn next_entry(self: *Self, header: *const Header) ?*const Header {
// TODO Snapshots
if (header.op + 1 == self.headers.len) return null;
return self.entry_for_op(header.op + 1);
}
pub fn next_offset(self: *Self, header: *const Header) u64 {
// TODO Snapshots
assert(header.command == .prepare);
return header.offset + vsr.sector_ceil(header.size);
}
pub fn has(self: *Self, header: *const Header) bool {
// TODO Snapshots
const existing = &self.headers[header.op];
if (existing.command == .reserved) {
return false;
} else {
if (existing.checksum == header.checksum) {
assert(existing.checksum_body == header.checksum_body);
assert(existing.op == header.op);
return true;
} else {
return false;
}
}
}
pub fn has_clean(self: *Self, header: *const Header) bool {
// TODO Snapshots
return self.has(header) and !self.dirty.bit(header.op);
}
pub fn has_dirty(self: *Self, header: *const Header) bool {
// TODO Snapshots
return self.has(header) and self.dirty.bit(header.op);
}
/// Copies latest headers between `op_min` and `op_max` (both inclusive) as will fit in `dest`.
/// Reverses the order when copying so that latest headers are copied first, which also protects
/// against the callsite slicing the buffer the wrong way and incorrectly.
/// Skips .reserved headers (gaps between headers).
/// Zeroes the `dest` buffer in case the copy would underflow and leave a buffer bleed.
/// Returns the number of headers actually copied.
pub fn copy_latest_headers_between(
self: *Self,
op_min: u64,
op_max: u64,
dest: []Header,
) usize {
assert(op_min <= op_max);
assert(dest.len > 0);
var copied: usize = 0;
std.mem.set(Header, dest, Header.reserved());
// Start at op_max + 1 and do the decrement upfront to avoid overflow when op_min == 0:
var op = op_max + 1;
while (op > op_min) {
op -= 1;
if (self.entry_for_op_exact(op)) |header| {
dest[copied] = header.*;
assert(dest[copied].invalid() == null);
copied += 1;
if (copied == dest.len) break;
}
}
log.debug("copy_latest_headers_between: op_min={} op_max={} dest.len={} copied={}", .{
op_min,
op_max,
dest.len,
copied,
});
return copied;
}
const HeaderRange = struct { op_min: u64, op_max: u64 };
/// Finds the latest break in headers between `op_min` and `op_max` (both inclusive).
/// A break is a missing header or a header not connected to the next header by hash chain.
/// On finding the highest break, extends the range downwards to cover as much as possible.
/// We expect that `op_min` and `op_max` (`replica.commit_min` and `replica.op`) must exist.
/// A range will never include `op_min` because this is already committed.
/// A range will never include `op_max` because this must be up to date as the latest op.
/// We must therefore first resolve any view jump barrier so that we can trust `op_max`.
///
/// For example: If ops 3, 9 and 10 are missing, returns: `{ .op_min = 9, .op_max = 10 }`.
///
/// Another example: If op 17 is disconnected from op 18, 16 is connected to 17, and 12-15
/// are missing, returns: `{ .op_min = 12, .op_max = 17 }`.
pub fn find_latest_headers_break_between(
self: *Self,
op_min: u64,
op_max: u64,
) ?HeaderRange {
assert(op_min <= op_max);
var range: ?HeaderRange = null;
// We set B, the op after op_max, to null because we only examine breaks < op_max:
var B: ?*const Header = null;
var op = op_max + 1;
while (op > op_min) {
op -= 1;
// Get the entry at @mod(op) location, but only if entry.op == op, else null:
var A = self.entry_for_op_exact(op);
if (A) |a| {
if (B) |b| {
// If A was reordered then A may have a newer op than B (but an older view).
// However, here we use entry_for_op_exact() to assert a.op + 1 == b.op:
assert(a.op + 1 == b.op);
// We do not assert a.view <= b.view here unless the chain is intact because
// repair_header() may put a newer view to the left of an older view.
// A exists and B exists:
if (range) |*r| {
assert(b.op == r.op_min);
if (a.op == op_min) {
// A is committed, because we pass `commit_min` as `op_min`:
// Do not add A to range because A cannot be a break if committed.
break;
} else if (a.checksum == b.parent) {
// A is connected to B, but B is disconnected, add A to range:
assert(a.view <= b.view);
assert(a.op > op_min);
r.op_min = a.op;
} else if (a.view < b.view) {
// A is not connected to B, and A is older than B, add A to range:
r.op_min = a.op;
} else if (a.view > b.view) {
// A is not connected to B, but A is newer than B, close range:
break;
} else {
// Op numbers in the same view must be connected.
unreachable;
}
} else if (a.checksum == b.parent) {
// A is connected to B, and B is connected or B is op_max.
assert(a.view <= b.view);
} else if (a.view < b.view) {
// A is not connected to B, and A is older than B, open range:
assert(a.op > op_min);
range = .{ .op_min = a.op, .op_max = a.op };
} else if (a.view > b.view) {
// A is not connected to B, but A is newer than B, open and close range:
assert(b.op < op_max);
range = .{ .op_min = b.op, .op_max = b.op };
break;
} else {
// Op numbers in the same view must be connected.
unreachable;
}
} else {
// A exists and B does not exist (or B has a older/newer op number):
if (range) |r| {
// We cannot compare A to B, A may be older/newer, close range:
assert(r.op_min == op + 1);
break;
} else {
// We expect a range if B does not exist, unless:
assert(a.op == op_max);
}
}
} else {
assert(op > op_min);
assert(op < op_max);
// A does not exist, or A has an older (or newer if reordered) op number:
if (range) |*r| {
// Add A to range:
assert(r.op_min == op + 1);
r.op_min = op;
} else {
// Open range:
assert(B != null);
range = .{ .op_min = op, .op_max = op };
}
}
B = A;
}
if (range) |r| {
// We can never repair op_min (replica.commit_min) since that is already committed:
assert(r.op_min > op_min);
// We can never repair op_max (replica.op) since that is the latest op:
// We can assume this because any existing view jump barrier must first be resolved.
assert(r.op_max < op_max);
}
return range;
}
pub fn read_prepare(
self: *Self,
callback: fn (replica: *Replica, prepare: ?*Message, destination_replica: ?u8) void,
op: u64,
checksum: u128,
destination_replica: ?u8,
) void {
const replica = @fieldParentPtr(Replica, "journal", self);
if (op > replica.op) {
self.read_prepare_log(op, checksum, "beyond replica.op");
callback(replica, null, null);
return;
}
// Do not use this pointer beyond this function's scope, as the
// header memory may then change:
const exact = self.entry_for_op_exact_with_checksum(op, checksum) orelse {
self.read_prepare_log(op, checksum, "no entry exactly");
callback(replica, null, null);
return;
};
if (self.faulty.bit(op)) {
assert(self.dirty.bit(op));
self.read_prepare_log(op, checksum, "faulty");
callback(replica, null, null);
return;
}
if (self.dirty.bit(op)) {
self.read_prepare_log(op, checksum, "dirty");
callback(replica, null, null);
return;
}
const physical_size = vsr.sector_ceil(exact.size);
assert(physical_size >= exact.size);
const message = replica.message_bus.get_message() orelse {
self.read_prepare_log(op, checksum, "no message available");
callback(replica, null, null);
return;
};
defer replica.message_bus.unref(message);
// Skip the disk read if the header is all we need:
if (exact.size == @sizeOf(Header)) {
message.header.* = exact.*;
callback(replica, message, destination_replica);
return;
}
const read = self.reads.acquire() orelse {
self.read_prepare_log(op, checksum, "waiting for IOP");
callback(replica, null, null);
return;
};
read.* = .{
.self = self,
.completion = undefined,
.message = message.ref(),
.callback = callback,
.op = op,
.checksum = checksum,
.destination_replica = destination_replica,
};
assert(exact.offset + physical_size <= self.size_circular_buffer);
const buffer = message.buffer[0..physical_size];
const offset = self.offset_in_circular_buffer(exact.offset);
// Memory must not be owned by `self.headers` as these may be modified concurrently:
assert(@ptrToInt(buffer.ptr) < @ptrToInt(self.headers.ptr) or
@ptrToInt(buffer.ptr) > @ptrToInt(self.headers.ptr) + self.size_headers);
log.debug(
"{}: read_sectors: offset={} len={}",
.{ replica.replica, offset, buffer.len },
);
self.storage.read_sectors(on_read, &read.completion, buffer, offset);
}
fn on_read(completion: *Storage.Read) void {
const read = @fieldParentPtr(Self.Read, "completion", completion);
const self = read.self;
const replica = @fieldParentPtr(Replica, "journal", self);
const op = read.op;
const checksum = read.checksum;
defer {
replica.message_bus.unref(read.message);
self.reads.release(read);
}
if (op > replica.op) {
self.read_prepare_log(op, checksum, "beyond replica.op");
read.callback(replica, null, null);
return;
}
_ = replica.journal.entry_for_op_exact_with_checksum(op, checksum) orelse {
self.read_prepare_log(op, checksum, "no entry exactly");
read.callback(replica, null, null);
return;
};
if (!read.message.header.valid_checksum()) {
self.faulty.set(op);
self.dirty.set(op);
self.read_prepare_log(op, checksum, "corrupt header after read");
read.callback(replica, null, null);
return;
}
const body = read.message.buffer[@sizeOf(Header)..read.message.header.size];
if (!read.message.header.valid_checksum_body(body)) {
self.faulty.set(op);
self.dirty.set(op);
self.read_prepare_log(op, checksum, "corrupt body after read");
read.callback(replica, null, null);
return;
}
if (read.message.header.op != op) {
self.read_prepare_log(op, checksum, "op changed during read");
read.callback(replica, null, null);
return;
}
if (read.message.header.checksum != checksum) {
self.read_prepare_log(op, checksum, "checksum changed during read");
read.callback(replica, null, null);
return;
}
read.callback(replica, read.message, read.destination_replica);
}
fn read_prepare_log(self: *Self, op: u64, checksum: ?u128, notice: []const u8) void {
log.info(
"{}: read_prepare: op={} checksum={}: {s}",
.{ self.replica, op, checksum, notice },
);
}
pub fn recover(self: *Self) void {
assert(!self.recovered);
if (self.recovering) return;
self.recovering = true;
log.debug("{}: recover: recovering", .{self.replica});
self.recover_headers(0, 0);
self.recover_headers(0, 1);
}
fn recover_headers(self: *Self, offset: u64, version: u1) void {
const replica = @fieldParentPtr(Replica, "journal", self);
assert(!self.recovered);
assert(self.recovering);
if (offset == self.size_headers) {
log.debug("{}: recover_headers: version={} recovered", .{
self.replica,
version,
});
if (self.reads.executing() == 0) {
log.debug("{}: recover_headers: both versions recovered", .{self.replica});
self.recovered = true;
self.recovering = false;
// The initialization op (TODO Snapshots):
assert(!self.dirty.bit(0));
assert(!self.faulty.bit(0));
// From here it's over to the Recovery protocol from VRR 2012.
}
return;
}
assert(offset < self.size_headers);
const message = replica.message_bus.get_message() orelse unreachable;
defer replica.message_bus.unref(message);
// We use the count of reads executing to know when both versions have finished reading:
// We expect that no other process is issuing reads while we are recovering.
assert(self.reads.executing() < 2);
const read = self.reads.acquire() orelse unreachable;
read.* = .{
.self = self,
.completion = undefined,
.message = message.ref(),
.callback = undefined,
.op = undefined,
.checksum = offset,
.destination_replica = version,
};
const buffer = self.recover_headers_buffer(message, offset);
assert(buffer.len > 0);
log.debug("{}: recover_headers: version={} offset={} size={} recovering", .{
self.replica,
version,
offset,
buffer.len,
});
self.storage.read_sectors(
recover_headers_on_read,
&read.completion,
buffer,
self.offset_in_headers_version(offset, version),
);
}
fn recover_headers_buffer(self: *Self, message: *Message, offset: u64) []u8 {
const max = std.math.min(message.buffer.len, self.size_headers - offset);
assert(max % config.sector_size == 0);
return message.buffer[0..max];
}
fn recover_headers_on_read(completion: *Storage.Read) void {
const read = @fieldParentPtr(Self.Read, "completion", completion);
const self = read.self;
const replica = @fieldParentPtr(Replica, "journal", self);
const message = read.message;
const offset = @intCast(u64, read.checksum);
const version = @intCast(u1, read.destination_replica.?);
const buffer = self.recover_headers_buffer(message, offset);
log.debug("{}: recover_headers: version={} offset={} size={} recovered", .{
self.replica,
version,
offset,
buffer.len,
});
assert(offset % @sizeOf(Header) == 0);
assert(buffer.len >= @sizeOf(Header));
assert(buffer.len % @sizeOf(Header) == 0);
for (std.mem.bytesAsSlice(Header, buffer)) |*header, index| {
const op = offset / @sizeOf(Header) + index;
if (header.valid_checksum()) {
// This header is valid.
if (self.entry_for_op(op)) |existing| {
if (existing.checksum == header.checksum) {
// We also have the same header from the other version.
assert(!self.faulty.bit(op));
} else if (existing.command == .reserved) {
self.set_entry_as_dirty(header);
self.faulty.clear(op);
} else {
// Don't replace any existing op from the other version.
// First come, first served.
// We'll sort out the right order later when we recover higher up.
assert(!self.faulty.bit(op));
}
} else if (header.command == .reserved) {
self.dirty.set(op);
self.faulty.clear(op);
} else {
self.set_entry_as_dirty(header);
}
} else {
// This header is corrupt.
if (self.entry_for_op(op)) |_| {
// However, we have a valid header from the other version.
} else {
self.dirty.set(op);
self.faulty.set(op);
}
}
}
// We must release before we call `recover_headers()` in case Storage is synchronous.
// Otherwise, we would run out of messages and reads.
replica.message_bus.unref(read.message);
self.reads.release(read);
self.recover_headers(offset + buffer.len, version);
}
/// A safe way of removing an entry, where the header must match the current entry to succeed.
fn remove_entry(self: *Self, header: *const Header) void {
// Copy the header.op by value to avoid a reset() followed by undefined header.op usage:
const op = header.op;
log.debug("{}: remove_entry: op={} checksum={}", .{
self.replica,
op,
header.checksum,
});
assert(self.entry(header).?.checksum == header.checksum);
assert(self.headers[op].checksum == header.checksum); // TODO Snapshots
defer self.headers[op] = Header.reserved();
self.dirty.clear(op);
self.faulty.clear(op);
}
/// Removes entries from `op_min` (inclusive) onwards.
/// This is used after a view change to remove uncommitted entries discarded by the new leader.
pub fn remove_entries_from(self: *Self, op_min: u64) void {
// TODO Snapshots
// TODO Optimize to jump directly to op:
assert(op_min > 0);
log.debug("{}: remove_entries_from: op_min={}", .{ self.replica, op_min });
for (self.headers) |*header| {
if (header.op >= op_min and header.command == .prepare) {
self.remove_entry(header);
}
}
self.assert_headers_reserved_from(op_min);
// TODO At startup we need to handle entries that may have been removed but now reappear.
// This is because we do not call `write_headers_between()` here.
}
pub fn set_entry_as_dirty(self: *Self, header: *const Header) void {
log.debug("{}: set_entry_as_dirty: op={} checksum={}", .{
self.replica,
header.op,
header.checksum,
});
if (self.entry(header)) |existing| {
if (existing.checksum != header.checksum) {
self.faulty.clear(header.op);
}
}
self.headers[header.op] = header.*;
self.dirty.set(header.op);
// Do not clear any faulty bit for the same entry.
}
pub fn write_prepare(
self: *Self,
callback: fn (self: *Replica, wrote: ?*Message, trigger: Write.Trigger) void,
message: *Message,
trigger: Self.Write.Trigger,
) void {
const replica = @fieldParentPtr(Replica, "journal", self);
assert(message.header.command == .prepare);
assert(message.header.size >= @sizeOf(Header));
assert(message.header.size <= message.buffer.len);
// The underlying header memory must be owned by the buffer and not by self.headers:
// Otherwise, concurrent writes may modify the memory of the pointer while we write.
assert(@ptrToInt(message.header) == @ptrToInt(message.buffer.ptr));
if (!self.dirty.bit(message.header.op)) {
// Any function that sets the faulty bit should also set the dirty bit:
assert(!self.faulty.bit(message.header.op));
self.write_prepare_debug(message.header, "skipping (clean)");
callback(replica, message, trigger);
return;
}
assert(self.has_dirty(message.header));
const write = self.writes.acquire() orelse {
self.write_prepare_debug(message.header, "waiting for IOP");
callback(replica, null, trigger);
return;
};
self.write_prepare_debug(message.header, "starting");
write.* = .{
.self = self,
.callback = callback,
.message = message.ref(),
.trigger = trigger,
.range = undefined,
};
// Slice the message to the nearest sector, we don't want to write the whole buffer:
const sectors = message.buffer[0..vsr.sector_ceil(message.header.size)];
assert(message.header.offset + sectors.len <= self.size_circular_buffer);
if (std.builtin.mode == .Debug) {
// Assert that any sector padding has already been zeroed:
var sum_of_sector_padding_bytes: u32 = 0;
for (sectors[message.header.size..]) |byte| sum_of_sector_padding_bytes += byte;
assert(sum_of_sector_padding_bytes == 0);
}
self.write_sectors(
write_prepare_header,
write,
sectors,
self.offset_in_circular_buffer(message.header.offset),
);
}
/// Attempt to lock the in-memory sector containing the header being written.
/// If the sector is already locked, add this write to the wait queue.
fn write_prepare_header(write: *Self.Write) void {
const self = write.self;
const message = write.message;
if (!self.has(message.header)) {
self.write_prepare_debug(message.header, "entry changed while writing sectors");
self.write_prepare_release(write, null);
return;
}
assert(!write.header_sector_locked);
assert(write.header_sector_next == null);
var it = self.writes.iterate();
while (it.next()) |other| {
if (other == write) continue;
if (!other.header_sector_locked) continue;
if (other.header_sector_same(write)) {
write.header_sector_next = other.header_sector_next;
other.header_sector_next = write;
return;
}
}
write.header_sector_locked = true;
self.write_prepare_on_lock_header_sector(write);
}
fn write_prepare_on_lock_header_sector(self: *Self, write: *Write) void {
assert(write.header_sector_locked);
// TODO It's possible within this section that the header has since been replaced but we
// continue writing, even when the dirty bit is no longer set. This is not a problem
// but it would be good to stop writing as soon as we see we no longer need to.
// For this, we'll need to have a way to tweak write_prepare_release() to release locks.
// At present, we don't return early here simply because it doesn't yet do that.
const message = write.message;
const offset = write_prepare_header_offset(write.message);
std.mem.copy(
u8,
write.header_sector(self),
std.mem.sliceAsBytes(self.headers)[offset..][0..config.sector_size],
);
log.debug("{}: write_header: op={} sectors[{}..{}]", .{
self.replica,
message.header.op,
offset,
offset + config.sector_size,
});
// TODO Snapshots
if (self.write_prepare_header_once(message.header)) {
const version = self.write_headers_increment_version();
self.write_prepare_header_to_version(write, write_prepare_on_write_header, version, write.header_sector(self), offset);
} else {
// Versions must be incremented upfront:
// If we don't increment upfront we could end up writing to the same copy twice.
// We would then lose the redundancy required to locate headers or even overwrite all copies.
const version = self.write_headers_increment_version();
_ = self.write_headers_increment_version();
switch (version) {
0 => self.write_prepare_header_to_version(write, write_prepare_on_write_header_version_0, 0, write.header_sector(self), offset),
1 => self.write_prepare_header_to_version(write, write_prepare_on_write_header_version_1, 1, write.header_sector(self), offset),
}
}
}
fn write_prepare_on_write_header_version_0(write: *Self.Write) void {
const self = write.self;
const offset = write_prepare_header_offset(write.message);
// Pass the opposite version bit from the one we just finished writing.
self.write_prepare_header_to_version(write, write_prepare_on_write_header, 1, write.header_sector(self), offset);
}
fn write_prepare_on_write_header_version_1(write: *Self.Write) void {
const self = write.self;
const offset = write_prepare_header_offset(write.message);
// Pass the opposite version bit from the one we just finished writing.
self.write_prepare_header_to_version(write, write_prepare_on_write_header, 0, write.header_sector(self), offset);
}
fn write_prepare_on_write_header(write: *Self.Write) void {
const self = write.self;
const message = write.message;
assert(write.header_sector_locked);
self.write_prepare_unlock_header_sector(write);
if (!self.has(message.header)) {
self.write_prepare_debug(message.header, "entry changed while writing headers");
self.write_prepare_release(write, null);
return;
}
self.write_prepare_debug(message.header, "complete, marking clean");
// TODO Snapshots
assert(self.has(message.header));
self.dirty.clear(message.header.op);
self.faulty.clear(message.header.op);
self.write_prepare_release(write, message);
}
/// Release the lock held by a write on an in-memory header sector and pass
/// it to a waiting Write, if any.
fn write_prepare_unlock_header_sector(self: *Self, write: *Self.Write) void {
assert(write.header_sector_locked);
write.header_sector_locked = false;
// Unlike the ranges of physical memory we lock when writing to disk,
// these header sector locks are always an exact match, so there's no
// need to re-check the waiting writes against all other writes.
if (write.header_sector_next) |waiting| {
write.header_sector_next = null;
assert(waiting.header_sector_locked == false);
waiting.header_sector_locked = true;
self.write_prepare_on_lock_header_sector(waiting);
}
assert(write.header_sector_next == null);
}
fn write_prepare_release(self: *Self, write: *Self.Write, wrote: ?*Message) void {
const replica = @fieldParentPtr(Replica, "journal", self);
write.callback(replica, wrote, write.trigger);
replica.message_bus.unref(write.message);
self.writes.release(write);
}
fn write_prepare_debug(self: *Self, header: *const Header, status: []const u8) void {
log.debug("{}: write: view={} op={} offset={} len={}: {} {s}", .{
self.replica,
header.view,
header.op,
header.offset,
header.size,
header.checksum,
status,
});
}
pub fn offset_in_circular_buffer(self: *Self, offset: u64) u64 {
assert(offset < self.size_circular_buffer);
return self.size_headers + offset;
}
fn offset_in_headers_version(self: *Self, offset: u64, version: u1) u64 {
assert(offset < self.size_headers);
return switch (version) {
0 => offset,
1 => self.size_headers + self.size_circular_buffer + offset,
};
}
fn write_prepare_header_offset(message: *Message) u64 {
comptime assert(config.sector_size % @sizeOf(Header) == 0);
return vsr.sector_floor(message.header.op * @sizeOf(Header));
}
fn write_headers_increment_version(self: *Self) u1 {
self.headers_version +%= 1;
return self.headers_version;
}
/// Since we allow gaps in the journal, we may have to write our headers twice.
/// If a dirty header is being written as reserved (empty) then write twice to make this clear.
/// If a dirty header has no previous clean chained entry to give its offset then write twice.
/// Otherwise, we only need to write the headers once because their other copy can be located in
/// the body of the journal (using the previous entry's offset and size).
fn write_prepare_header_once(self: *Self, header: *const Header) bool {
// TODO Optimize this to decide whether to write once or twice once we add support to
// recover from either header version at startup.
const always_write_twice = true;
if (always_write_twice) return false;
// TODO Snapshots
if (header.command == .reserved) {
log.debug("{}: write_prepare_header_once: dirty reserved header", .{
self.replica,
});
return false;
}
if (self.previous_entry(header)) |previous| {
assert(previous.command == .prepare);
if (previous.checksum != header.parent) {
log.debug("{}: write_headers_once: no hash chain", .{self.replica});
return false;
}
// TODO Add is_dirty(header)
// TODO Snapshots
if (self.dirty.bit(previous.op)) {
log.debug("{}: write_prepare_header_once: previous entry is dirty", .{
self.replica,
});
return false;
}
} else {
log.debug("{}: write_prepare_header_once: no previous entry", .{self.replica});
return false;
}
return true;
}
fn write_prepare_header_to_version(
self: *Self,
write: *Self.Write,
callback: fn (completion: *Self.Write) void,
version: u1,
buffer: []const u8,
offset: u64,
) void {
log.debug("{}: write_prepare_header_to_version: version={} offset={} len={}", .{
self.replica,
version,
offset,
buffer.len,
});
assert(offset + buffer.len <= self.size_headers);
// Memory must not be owned by self.headers as self.headers may be modified concurrently:
assert(@ptrToInt(buffer.ptr) < @ptrToInt(self.headers.ptr) or
@ptrToInt(buffer.ptr) > @ptrToInt(self.headers.ptr) + self.size_headers);
self.write_sectors(
callback,
write,
buffer,
self.offset_in_headers_version(offset, version),
);
}
fn write_sectors(
self: *Self,
callback: fn (write: *Self.Write) void,
write: *Self.Write,
buffer: []const u8,
offset: u64,
) void {
write.range = .{
.callback = callback,
.completion = undefined,
.buffer = buffer,
.offset = offset,
.locked = false,
};
self.lock_sectors(write);
}
/// Start the write on the current range or add it to the proper queue
/// if an overlapping range is currently being written.
fn lock_sectors(self: *Self, write: *Self.Write) void {
assert(!write.range.locked);
assert(write.range.next == null);
var it = self.writes.iterate();
while (it.next()) |other| {
if (other == write) continue;
if (!other.range.locked) continue;
if (other.range.overlaps(&write.range)) {
write.range.next = other.range.next;
other.range.next = &write.range;
return;
}
}
log.debug("{}: write_sectors: offset={} len={} locked", .{
self.replica,
write.range.offset,
write.range.buffer.len,
});
write.range.locked = true;
self.storage.write_sectors(
write_sectors_on_write,
&write.range.completion,
write.range.buffer,
write.range.offset,
);
// We rely on the Storage.write_sectors() implementation being either always synchronous,
// in which case writes never actually need to be queued, or always always asynchronous,
// in which case write_sectors_on_write() doesn't have to handle lock_sectors()
// synchronously completing a write and making a nested write_sectors_on_write() call.
//
// We don't currently allow Storage implementations that are sometimes synchronous and
// sometimes asynchronous as we don't have a use case for such a Storage implementation
// and doing so would require a significant complexity increase.
switch (Storage.synchronicity) {
.always_synchronous => assert(!write.range.locked),
.always_asynchronous => assert(write.range.locked),
}
}
fn write_sectors_on_write(completion: *Storage.Write) void {
const range = @fieldParentPtr(Range, "completion", completion);
const write = @fieldParentPtr(Self.Write, "range", range);
const self = write.self;
assert(write.range.locked);
write.range.locked = false;
log.debug("{}: write_sectors: offset={} len={} unlocked", .{
self.replica,
write.range.offset,
write.range.buffer.len,
});
// Drain the list of ranges that were waiting on this range to complete.
var current = range.next;
range.next = null;
while (current) |waiting| {
assert(waiting.locked == false);
current = waiting.next;
waiting.next = null;
self.lock_sectors(@fieldParentPtr(Self.Write, "range", waiting));
}
// The callback may set range, so we can't set range to undefined after running the callback.
const callback = range.callback;
range.* = undefined;
callback(write);
}
pub fn writing(self: *Self, op: u64, checksum: u128) bool {
var it = self.writes.iterate();
while (it.next()) |write| {
// It's possible that we might be writing the same op but with a different checksum.
// For example, if the op we are writing did not survive the view change and was
// replaced by another op. We must therefore do the search primarily on checksum.
// However, we compare against the 64-bit op first, since it's a cheap machine word.
if (write.message.header.op == op and write.message.header.checksum == checksum) {
// If we truly are writing, then the dirty bit must be set:
assert(self.dirty.bit(op));
return true;
}
}
return false;
}
};
}
// TODO Snapshots
pub const BitSet = struct {
bits: []bool,
/// The number of bits set (updated incrementally as bits are set or cleared):
len: u64 = 0,
fn init(allocator: *Allocator, count: u64) !BitSet {
const bits = try allocator.alloc(bool, count);
errdefer allocator.free(bits);
std.mem.set(bool, bits, false);
return BitSet{ .bits = bits };
}
fn deinit(self: *BitSet, allocator: *Allocator) void {
allocator.free(self.bits);
}
/// Clear the bit for an op (idempotent):
pub fn clear(self: *BitSet, op: u64) void {
if (self.bits[op]) {
self.bits[op] = false;
self.len -= 1;
}
}
/// Whether the bit for an op is set:
pub fn bit(self: *BitSet, op: u64) bool {
return self.bits[op];
}
/// Set the bit for an op (idempotent):
pub fn set(self: *BitSet, op: u64) void {
if (!self.bits[op]) {
self.bits[op] = true;
self.len += 1;
assert(self.len <= self.bits.len);
}
}
};
/// Take a u6 to limit to 64 items max (2^6 = 64)
pub fn IOPS(comptime T: type, comptime size: u6) type {
const Map = std.meta.Int(.unsigned, size);
const MapLog2 = math.Log2Int(Map);
return struct {
const Self = @This();
items: [size]T = undefined,
/// 1 bits are free items
free: Map = math.maxInt(Map),
pub fn acquire(self: *Self) ?*T {
const i = @ctz(Map, self.free);
assert(i <= @bitSizeOf(Map));
if (i == @bitSizeOf(Map)) return null;
self.free &= ~(@as(Map, 1) << @intCast(MapLog2, i));
return &self.items[i];
}
pub fn release(self: *Self, item: *T) void {
item.* = undefined;
const i = (@ptrToInt(item) - @ptrToInt(&self.items)) / @sizeOf(T);
assert(self.free & (@as(Map, 1) << @intCast(MapLog2, i)) == 0);
self.free |= (@as(Map, 1) << @intCast(MapLog2, i));
}
/// Returns true if there is at least one IOP available
pub fn available(self: *const Self) math.Log2IntCeil(Map) {
return @popCount(Map, self.free);
}
/// Returns true if there is at least one IOP in use
pub fn executing(self: *const Self) math.Log2IntCeil(Map) {
return @popCount(Map, math.maxInt(Map)) - @popCount(Map, self.free);
}
pub const Iterator = struct {
iops: *Self,
/// On iteration start this is a copy of the free map, but
/// inverted so we can use @ctz() to find occupied instead of free slots.
unseen: Map,
pub fn next(iterator: *Iterator) ?*T {
const i = @ctz(Map, iterator.unseen);
assert(i <= @bitSizeOf(Map));
if (i == @bitSizeOf(Map)) return null;
// Set this bit of unseen to 1 to indicate this slot has been seen.
iterator.unseen &= ~(@as(Map, 1) << @intCast(MapLog2, i));
return &iterator.iops.items[i];
}
};
pub fn iterate(self: *Self) Iterator {
return .{ .iops = self, .unseen = ~self.free };
}
};
}
test {
const testing = std.testing;
var iops = IOPS(u32, 4){};
try testing.expectEqual(@as(u4, 4), iops.available());
try testing.expectEqual(@as(u4, 0), iops.executing());
var one = iops.acquire().?;
try testing.expectEqual(@as(u4, 3), iops.available());
try testing.expectEqual(@as(u4, 1), iops.executing());
var two = iops.acquire().?;
var three = iops.acquire().?;
try testing.expectEqual(@as(u4, 1), iops.available());
try testing.expectEqual(@as(u4, 3), iops.executing());
var four = iops.acquire().?;
try testing.expectEqual(@as(?*u32, null), iops.acquire());
try testing.expectEqual(@as(u4, 0), iops.available());
try testing.expectEqual(@as(u4, 4), iops.executing());
iops.release(two);
try testing.expectEqual(@as(u4, 1), iops.available());
try testing.expectEqual(@as(u4, 3), iops.executing());
// there is only one slot free, so we will get the same pointer back.
try testing.expectEqual(@as(?*u32, two), iops.acquire());
iops.release(four);
iops.release(two);
iops.release(one);
iops.release(three);
try testing.expectEqual(@as(u4, 4), iops.available());
try testing.expectEqual(@as(u4, 0), iops.executing());
one = iops.acquire().?;
two = iops.acquire().?;
three = iops.acquire().?;
four = iops.acquire().?;
try testing.expectEqual(@as(?*u32, null), iops.acquire());
} | src/vsr/journal.zig |
const std = @import("std");
const core = @import("../core.zig");
const debug = std.debug;
const heap = std.heap;
const rand = std.rand;
const time = std.time;
test "bench" {
const str = try heap.direct_allocator.alloc(u8, 1024 * 1024 * 1024);
defer heap.direct_allocator.free(str);
rand.DefaultPrng.init(0).random.bytes(str);
const text = try core.Text.Content.fromSlice(heap.direct_allocator, str);
var timer = try time.Timer.start();
{
debug.warn("\nLocation.fromIndex (list)\n");
timer.reset();
var result: core.Location = undefined;
@ptrCast(*volatile core.Location, &result).* = core.Location.fromIndex(str.len, text);
const t = timer.read();
debug.warn("{} {}\n", result.line, result.column);
debug.warn("{}ms ({}ns)\n", t / time.millisecond, t);
}
{
debug.warn("Location.fromIndex (slice)\n");
timer.reset();
var result = core.Location{};
for (str) |c, i| {
if (str.len == i)
break;
if (c == '\n') {
result.line += 1;
result.index = i + 1;
}
}
result.column = str.len - result.index;
result.index = str.len;
@ptrCast(*volatile core.Location, &result).* = result;
const t = timer.read();
debug.warn("{} {}\n", result.line, result.column);
debug.warn("{}ms ({}ns)\n", t / time.millisecond, t);
}
{
debug.warn("Count items (list)\n");
timer.reset();
var c: usize = 0;
try text.foreach(0, &c, struct {
fn each(count: *usize, i: usize, item: u8) error{}!void {
count.* += 1;
}
}.each);
@ptrCast(*volatile usize, &c).* = c;
const t = timer.read();
debug.warn("{}ms ({}ns)\n", t / time.millisecond, t);
}
{
debug.warn("Count items (list)\n");
timer.reset();
var count: usize = 0;
for (str) |c, i| {
count += 1;
}
@ptrCast(*volatile usize, &count).* = count;
const t = timer.read();
debug.warn("{}ms ({}ns)\n", t / time.millisecond, t);
}
} | src/core/text_bench.zig |
const std = @import("std");
const assert = std.debug.assert;
const log = std.log.scoped(.concurrent_ranges);
pub const ConcurrentRanges = struct {
name: []const u8,
/// A queue of ranges acquired and in progress:
acquired: ?*Range = null,
pub fn acquire(self: *ConcurrentRanges, range: *Range) void {
assert(range.status == .initialized);
range.status = .acquiring;
assert(range.prev == null);
assert(range.next == null);
assert(range.head == null);
assert(range.tail == null);
range.frame = @frame();
while (true) {
if (self.has_overlapping_range(range)) |overlapping_range| {
log.debug("{s}: range {} overlaps with concurrent range {}, enqueueing", .{
self.name,
range,
overlapping_range,
});
overlapping_range.enqueue(range);
suspend {}
} else {
break;
}
}
// TODO This can be removed for performance down the line:
assert(self.has_overlapping_range(range) == null);
// Add the range to the linked list:
if (self.acquired) |next| {
range.next = next;
next.prev = range;
}
self.acquired = range;
range.status = .acquired;
log.debug("{s}: acquired: {}", .{ self.name, range });
}
pub fn release(self: *ConcurrentRanges, range: *Range) void {
assert(range.status == .acquired);
range.status = .releasing;
log.debug("{s}: released: {}", .{ self.name, range });
// Remove the range from the linked list:
// Connect the previous range to the next range:
if (range.prev) |prev| {
prev.next = range.next;
} else {
self.acquired = range.next;
}
// ... and connect the next range to the previous range:
if (range.next) |next| {
next.prev = range.prev;
}
range.prev = null;
range.next = null;
range.resume_queued_ranges();
}
pub fn has_overlapping_range(self: *ConcurrentRanges, range: *const Range) ?*Range {
var head = self.acquired;
while (head) |concurrent_range| {
head = concurrent_range.next;
if (range.overlaps(concurrent_range)) return concurrent_range;
}
return null;
}
};
pub const Range = struct {
offset: u64,
len: u64,
frame: anyframe = undefined,
status: RangeStatus = .initialized,
/// Links to concurrently executing sibling ranges:
prev: ?*Range = null,
next: ?*Range = null,
/// A queue of child ranges waiting on this range to complete:
head: ?*Range = null,
tail: ?*Range = null,
const RangeStatus = enum {
initialized,
acquiring,
acquired,
releasing,
released,
};
fn enqueue(self: *Range, range: *Range) void {
assert(self.status == .acquired);
assert(range.status == .acquiring);
if (self.head == null) {
assert(self.tail == null);
self.head = range;
self.tail = range;
} else {
self.tail.?.next = range;
self.tail = range;
}
}
fn overlaps(self: *const Range, range: *const Range) bool {
if (self.offset < range.offset) {
return self.offset + self.len > range.offset;
} else {
return range.offset + range.len > self.offset;
}
}
fn resume_queued_ranges(self: *Range) void {
assert(self.status == .releasing);
self.status = .released;
// This range should have been removed from the list of concurrent ranges:
assert(self.prev == null);
assert(self.next == null);
var head = self.head;
self.head = null;
self.tail = null;
while (head) |queued| {
assert(queued.status == .acquiring);
head = queued.next;
resume queued.frame;
}
// This range should be finished executing and should no longer overlap or have any queue:
assert(self.head == null);
assert(self.tail == null);
}
pub fn format(
value: Range,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
try writer.print("offset={} len={}", .{
value.offset,
value.len,
});
}
}; | src/concurrent_ranges.zig |
const sf = @import("../sfml.zig");
const std = @import("std");
const assert = std.debug.assert;
pub const Image = struct {
const Self = @This();
// Constructor/destructor
/// Creates a new image
pub fn init(size: sf.Vector2u, color: sf.Color) !Self {
var img = sf.c.sfImage_createFromColor(size.x, size.y, color.toCSFML());
if (img == null)
return sf.Error.nullptrUnknownReason;
return Self{ .ptr = img.? };
}
/// Creates an image from a pixel array
pub fn initFromPixels(size: sf.Vector2u, pixels: []const sf.Color) !Self {
// Check if there is enough data
if (pixels.len < size.x * size.y)
return sf.Error.notEnoughData;
var img = sf.c.sfImage_createFromPixels(size.x, size.y, @ptrCast([*]const u8, pixels.ptr));
if (img == null)
return sf.Error.nullptrUnknownReason;
return Self{ .ptr = img.? };
}
/// Loads an image from a file
pub fn initFromFile(path: [:0]const u8) !Self {
var img = sf.c.sfImage_createFromFile(path);
if (img == null)
return sf.Error.resourceLoadingError;
return Self{ .ptr = img.? };
}
/// Destroys an image
pub fn deinit(self: Self) void {
sf.c.sfImage_destroy(self.ptr);
}
// Getters/setters
/// Gets a pixel from this image (bounds are only checked in an assertion)
pub fn getPixel(self: Self, pixel_pos: sf.Vector2u) sf.Color {
@compileError("This function causes a segfault, comment this out if you thing it will work (issue #2)");
const size = self.getSize();
assert(pixel_pos.x < size.x and pixel_pos.y < size.y);
return sf.Color.fromCSFML(sf.c.sfImage_getPixel(self.ptr, pixel_pos.x, pixel_pos.y));
}
/// Sets a pixel on this image (bounds are only checked in an assertion)
pub fn setPixel(self: Self, pixel_pos: sf.Vector2u, color: sf.Color) void {
const size = self.getSize();
assert(pixel_pos.x < size.x and pixel_pos.y < size.y);
sf.c.sfImage_setPixel(self.ptr, pixel_pos.x, pixel_pos.y, color.toCSFML());
}
/// Gets the size of this image
pub fn getSize(self: Self) sf.Vector2u {
// This is a hack
_ = sf.c.sfImage_getSize(self.ptr);
// Register Rax holds the return val of function calls that can fit in a register
const rax: usize = asm volatile (""
: [ret] "={rax}" (-> usize)
);
var x: u32 = @truncate(u32, (rax & 0x00000000FFFFFFFF) >> 00);
var y: u32 = @truncate(u32, (rax & 0xFFFFFFFF00000000) >> 32);
return sf.Vector2u{ .x = x, .y = y };
}
/// Pointer to the csfml texture
ptr: *sf.c.sfImage
};
test "image: sane getters and setters" {
const tst = std.testing;
const allocator = std.heap.page_allocator;
var pixel_data = try allocator.alloc(sf.Color, 30);
defer allocator.free(pixel_data);
for (pixel_data) |c, i| {
pixel_data[i] = sf.Color.fromHSVA(@intToFloat(f32, i) / 30 * 360, 100, 100, 1);
}
var img = try sf.Image.initFromPixels(.{.x = 5, .y = 6}, pixel_data);
defer img.deinit();
tst.expectEqual(sf.Vector2u{.x = 5, .y = 6}, img.getSize());
img.setPixel(.{.x = 1, .y = 2}, sf.Color.Cyan);
//tst.expectEqual(sf.Color.Cyan, img.getPixel(.{.x = 1, .y = 2}));
var tex = try sf.Texture.initFromImage(img, null);
defer tex.deinit();
} | src/sfml/graphics/image.zig |
const std = @import("std");
const testing = std.testing;
const ValueTree = std.json.ValueTree;
const Value = std.json.Value;
const base64url = std.base64.url_safe_no_pad;
const Algorithm = enum {
const Self = @This();
HS256,
HS384,
HS512,
pub fn jsonStringify(value: Self, options: std.json.StringifyOptions, writer: anytype) @TypeOf(writer).Error!void {
try std.json.stringify(std.meta.tagName(value), options, writer);
}
pub fn CryptoFn(self: Self) type {
return switch (self) {
.HS256 => std.crypto.auth.hmac.sha2.HmacSha256,
.HS384 => std.crypto.auth.hmac.sha2.HmacSha384,
.HS512 => std.crypto.auth.hmac.sha2.HmacSha512,
};
}
};
const JWTType = enum {
JWS,
JWE,
};
pub const SignatureOptions = struct {
key: []const u8,
kid: ?[]const u8 = null,
};
pub fn encode(allocator: std.mem.Allocator, comptime alg: Algorithm, payload: anytype, signatureOptions: SignatureOptions) ![]const u8 {
var payload_json = std.ArrayList(u8).init(allocator);
defer payload_json.deinit();
try std.json.stringify(payload, .{}, payload_json.writer());
return try encodeMessage(allocator, alg, payload_json.items, signatureOptions);
}
pub fn encodeMessage(allocator: std.mem.Allocator, comptime alg: Algorithm, message: []const u8, signatureOptions: SignatureOptions) ![]const u8 {
var protected_header = std.json.ObjectMap.init(allocator);
defer protected_header.deinit();
try protected_header.put("alg", .{ .String = std.meta.tagName(alg) });
try protected_header.put("typ", .{ .String = "JWT" });
if (signatureOptions.kid) |kid| {
try protected_header.put("kid", .{ .String = kid });
}
var protected_header_json = std.ArrayList(u8).init(allocator);
defer protected_header_json.deinit();
try std.json.stringify(Value{ .Object = protected_header }, .{}, protected_header_json.writer());
const message_base64_len = base64url.Encoder.calcSize(message.len);
const protected_header_base64_len = base64url.Encoder.calcSize(protected_header_json.items.len);
var jwt_text = std.ArrayList(u8).init(allocator);
defer jwt_text.deinit();
try jwt_text.resize(message_base64_len + 1 + protected_header_base64_len);
var protected_header_base64 = jwt_text.items[0..protected_header_base64_len];
var message_base64 = jwt_text.items[protected_header_base64_len + 1 ..][0..message_base64_len];
_ = base64url.Encoder.encode(protected_header_base64, protected_header_json.items);
jwt_text.items[protected_header_base64_len] = '.';
_ = base64url.Encoder.encode(message_base64, message);
const signature = &generate_signature(alg, signatureOptions.key, protected_header_base64, message_base64);
const signature_base64_len = base64url.Encoder.calcSize(signature.len);
try jwt_text.resize(message_base64_len + 1 + protected_header_base64_len + 1 + signature_base64_len);
var signature_base64 = jwt_text.items[message_base64_len + 1 + protected_header_base64_len + 1 ..][0..signature_base64_len];
jwt_text.items[message_base64_len + 1 + protected_header_base64_len] = '.';
_ = base64url.Encoder.encode(signature_base64, signature);
return jwt_text.toOwnedSlice();
}
pub fn validate(comptime P: type, allocator: std.mem.Allocator, comptime alg: Algorithm, tokenText: []const u8, signatureOptions: SignatureOptions) !P {
const message = try validateMessage(allocator, alg, tokenText, signatureOptions);
defer allocator.free(message);
// 10. Verify that the resulting octet sequence is a UTF-8-encoded
// representation of a completely valid JSON object conforming to
// RFC 7159 [RFC7159]; let the JWT Claims Set be this JSON object.
return std.json.parse(P, &std.json.TokenStream.init(message), .{ .allocator = allocator });
}
pub fn validateFree(comptime P: type, allocator: std.mem.Allocator, value: P) void {
std.json.parseFree(P, value, .{ .allocator = allocator });
}
pub fn validateMessage(allocator: std.mem.Allocator, comptime expectedAlg: Algorithm, tokenText: []const u8, signatureOptions: SignatureOptions) ![]const u8 {
// 1. Verify that the JWT contains at least one period ('.')
// character.
// 2. Let the Encoded JOSE Header be the portion of the JWT before the
// first period ('.') character.
var end_of_jose_base64 = std.mem.indexOfScalar(u8, tokenText, '.') orelse return error.InvalidFormat;
const jose_base64 = tokenText[0..end_of_jose_base64];
// 3. Base64url decode the Encoded JOSE Header following the
// restriction that no line breaks, whitespace, or other additional
// characters have been used.
var jose_json = try allocator.alloc(u8, try base64url.Decoder.calcSizeForSlice(jose_base64));
defer allocator.free(jose_json);
try base64url.Decoder.decode(jose_json, jose_base64);
// 4. Verify that the resulting octet sequence is a UTF-8-encoded
// representation of a completely valid JSON object conforming to
// RFC 7159 [RFC7159]; let the JOSE Header be this JSON object.
// TODO: Make sure the JSON parser confirms everything above
var parser = std.json.Parser.init(allocator, false);
defer parser.deinit();
var cty_opt = @as(?[]const u8, null);
defer if (cty_opt) |cty| allocator.free(cty);
var jwt_tree = try parser.parse(jose_json);
defer jwt_tree.deinit();
// 5. Verify that the resulting JOSE Header includes only parameters
// and values whose syntax and semantics are both understood and
// supported or that are specified as being ignored when not
// understood.
var jwt_root = jwt_tree.root;
if (jwt_root != .Object) return error.InvalidFormat;
{
var alg_val = jwt_root.Object.get("alg") orelse return error.InvalidFormat;
if (alg_val != .String) return error.InvalidFormat;
const alg = std.meta.stringToEnum(Algorithm, alg_val.String) orelse return error.InvalidAlgorithm;
// Make sure that the algorithm matches: https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/
if (alg != expectedAlg) return error.InvalidAlgorithm;
// TODO: Determine if "jku"/"jwk" need to be parsed and validated
if (jwt_root.Object.get("crit")) |crit_val| {
if (crit_val != .Array) return error.InvalidFormat;
const crit = crit_val.Array;
if (crit.items.len == 0) return error.InvalidFormat;
// TODO: Implement or allow extensions?
return error.UnknownExtension;
}
}
// 6. Determine whether the JWT is a JWS or a JWE using any of the
// methods described in Section 9 of [JWE].
const jwt_type = determine_jwt_type: {
// From Section 9 of the JWE specification:
// > o If the object is using the JWS Compact Serialization or the JWE
// > Compact Serialization, the number of base64url-encoded segments
// > separated by period ('.') characters differs for JWSs and JWEs.
// > JWSs have three segments separated by two period ('.') characters.
// > JWEs have five segments separated by four period ('.') characters.
switch (std.mem.count(u8, tokenText, ".")) {
2 => break :determine_jwt_type JWTType.JWS,
4 => break :determine_jwt_type JWTType.JWE,
else => return error.InvalidFormat,
}
};
// 7. Depending upon whether the JWT is a JWS or JWE, there are two
// cases:
const message_base64 = get_message: {
switch (jwt_type) {
// If the JWT is a JWS, follow the steps specified in [JWS] for
// validating a JWS. Let the Message be the result of base64url
// decoding the JWS Payload.
.JWS => {
var section_iter = std.mem.split(u8, tokenText, ".");
std.debug.assert(section_iter.next() != null);
const payload_base64 = section_iter.next().?;
const signature_base64 = section_iter.rest();
var signature = try allocator.alloc(u8, try base64url.Decoder.calcSizeForSlice(signature_base64));
defer allocator.free(signature);
try base64url.Decoder.decode(signature, signature_base64);
const gen_sig = &generate_signature(expectedAlg, signatureOptions.key, jose_base64, payload_base64);
if (!std.mem.eql(u8, signature, gen_sig)) {
return error.InvalidSignature;
}
break :get_message try allocator.dupe(u8, payload_base64);
},
.JWE => {
// Else, if the JWT is a JWE, follow the steps specified in
// [JWE] for validating a JWE. Let the Message be the resulting
// plaintext.
return error.Unimplemented;
},
}
};
defer allocator.free(message_base64);
// 8. If the JOSE Header contains a "cty" (content type) value of
// "JWT", then the Message is a JWT that was the subject of nested
// signing or encryption operations. In this case, return to Step
// 1, using the Message as the JWT.
if (jwt_root.Object.get("cty")) |cty_val| {
if (cty_val != .String) return error.InvalidFormat;
return error.Unimplemented;
}
// 9. Otherwise, base64url decode the Message following the
// restriction that no line breaks, whitespace, or other additional
// characters have been used.
var message = try allocator.alloc(u8, try base64url.Decoder.calcSizeForSlice(message_base64));
errdefer allocator.free(message);
try base64url.Decoder.decode(message, message_base64);
return message;
}
pub fn generate_signature(comptime algo: Algorithm, key: []const u8, protectedHeaderBase64: []const u8, payloadBase64: []const u8) [algo.CryptoFn().mac_length]u8 {
const T = algo.CryptoFn();
var h = T.init(key);
h.update(protectedHeaderBase64);
h.update(".");
h.update(payloadBase64);
var out: [T.mac_length]u8 = undefined;
h.final(&out);
return out;
}
test "generate jws based tokens" {
const payload = .{
.sub = "1234567890",
.name = "<NAME>",
.iat = 1516239022,
};
try test_generate(
.HS256,
payload,
"<KEY>",
"<KEY>",
);
try test_generate(
.HS384,
payload,
"<KEY>",
"<KEY>",
);
try test_generate(
.HS512,
payload,
"<KEY>",
"<KEY>",
);
}
test "validate jws based tokens" {
const expected = TestValidatePayload{
.iss = "joe",
.exp = 1300819380,
.@"http://example.com/is_root" = true,
};
try test_validate(
.HS256,
expected,
"<KEY>",
"<KEY>",
);
try test_validate(
.HS384,
expected,
"<KEY>",
"<KEY>",
);
try test_validate(
.HS512,
expected,
"eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJqb2UiLCJleHAiOjEzMDA4MTkzODAsImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.TrGchM_jCqCTAYUQlFmXt-KOyKO0O2wYYW5fUSV8jtdgqWJ74cqNA1zc9Ix7TU4qJ-Y32rKmP9Xpu99yiShx6g",
"AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow",
);
}
test "generate and then validate jws token" {
try test_generate_then_validate(.HS256, .{ .key = "a jws hmac sha-256 test key" });
try test_generate_then_validate(.HS384, .{ .key = "a jws hmac sha-384 test key" });
}
const TestPayload = struct {
sub: []const u8,
name: []const u8,
iat: i64,
};
fn test_generate(comptime algorithm: Algorithm, payload: TestPayload, expected: []const u8, key_base64: []const u8) !void {
var key = try std.testing.allocator.alloc(u8, try base64url.Decoder.calcSizeForSlice(key_base64));
defer std.testing.allocator.free(key);
try base64url.Decoder.decode(key, key_base64);
const token = try encode(std.testing.allocator, algorithm, payload, .{ .key = key });
defer std.testing.allocator.free(token);
try std.testing.expectEqualSlices(u8, expected, token);
}
const TestValidatePayload = struct {
iss: []const u8,
exp: i64,
@"http://example.com/is_root": bool,
};
fn test_validate(comptime algorithm: Algorithm, expected: TestValidatePayload, token: []const u8, key_base64: []const u8) !void {
var key = try std.testing.allocator.alloc(u8, try base64url.Decoder.calcSizeForSlice(key_base64));
defer std.testing.allocator.free(key);
try base64url.Decoder.decode(key, key_base64);
var claims = try validate(TestValidatePayload, std.testing.allocator, algorithm, token, .{ .key = key });
defer validateFree(TestValidatePayload, std.testing.allocator, claims);
try std.testing.expectEqualSlices(u8, expected.iss, claims.iss);
try std.testing.expectEqual(expected.exp, claims.exp);
try std.testing.expectEqual(expected.@"http://example.com/is_root", claims.@"http://example.com/is_root");
}
fn test_generate_then_validate(comptime alg: Algorithm, signatureOptions: SignatureOptions) !void {
const Payload = struct {
sub: []const u8,
name: []const u8,
iat: i64,
};
const payload = Payload{
.sub = "1234567890",
.name = "<NAME>",
.iat = 1516239022,
};
const token = try encode(std.testing.allocator, alg, payload, signatureOptions);
defer std.testing.allocator.free(token);
var decoded = try validate(Payload, std.testing.allocator, alg, token, signatureOptions);
defer validateFree(Payload, std.testing.allocator, decoded);
try std.testing.expectEqualSlices(u8, payload.sub, decoded.sub);
try std.testing.expectEqualSlices(u8, payload.name, decoded.name);
try std.testing.expectEqual(payload.iat, decoded.iat);
} | jwt.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const print = std.debug.print;
const data = @embedFile("data/day08");
const EntriesList = std.ArrayList(Inst);
const Op = enum {
nop,
acc,
jmp,
};
const Inst = struct {
op: Op,
val: isize,
executed: bool = false,
};
pub fn main() !void {
var timer = try std.time.Timer.start();
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const ally = &arena.allocator;
var lines = std.mem.tokenize(data, "\r\n");
var entries = EntriesList.init(ally);
try entries.ensureCapacity(400);
while (lines.next()) |line| {
if (line.len == 0) continue;
var tok = std.mem.split(line, " ");
var opname = tok.next().?;
var int = try std.fmt.parseInt(isize, tok.next().?, 10);
var op = if (std.mem.eql(u8, "nop", opname)) Op.nop else if (std.mem.eql(u8, "jmp", opname)) Op.jmp else Op.acc;
try entries.append(.{
.op = op,
.val = int,
});
}
var raw_items = entries.items;
var items = try ally.alloc(Inst, raw_items.len);
var result2: ?isize = null;
for (raw_items) |item, i| {
if (item.op == .nop or item.op == .jmp) {
std.mem.copy(Inst, items, raw_items);
if (item.op == .jmp) {
items[i].op = .nop;
} else {
items[i].op = .jmp;
}
var pc: isize = 0;
var acc: isize = 0;
while (pc != @intCast(isize, items.len)) {
var inst = &items[@intCast(usize, pc)];
if (inst.executed) break;
inst.executed = true;
switch(inst.op) {
.jmp => {
pc += inst.val;
},
.acc => {
acc += inst.val;
pc += 1;
},
.nop => {
pc += 1;
},
}
} else {
result2 = acc;
break;
}
}
}
print("result: {}, time: {}\n", .{result2, timer.read()});
} | src/day08.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const print = std.debug.print;
const data = @embedFile("data/day04.txt");
const Record = struct {
byr: bool = false,
iyr: bool = false,
eyr: bool = false,
hgt: bool = false,
hcl: bool = false,
ecl: bool = false,
pid: bool = false,
cid: bool = false,
pub fn isValid(self: *const @This()) bool {
return self.byr and self.iyr and self.eyr and self.hgt and self.hcl and self.ecl and self.pid;
}
};
pub fn main() !void {
var lines = std.mem.split(data, "\n\n");
var numValid: usize = 0;
while (lines.next()) |line| {
var rec = Record{};
var toks = std.mem.tokenize(line, " \n");
while (toks.next()) |tok| {
var colon = std.mem.indexOf(u8, tok, ":");
var tag = tok[0..colon.?];
var value = tok[colon.?+1..];
if (std.mem.eql(u8, "byr", tag)) {
if (std.fmt.parseInt(u16, value, 10)) |ival| {
if (ival >= 1920 and ival <= 2002) {
rec.byr = true;
}
} else |err| {}
} else if (std.mem.eql(u8, "iyr", tag)) {
if (std.fmt.parseInt(u16, value, 10)) |ival| {
if (ival >= 2010 and ival <= 2020) {
rec.iyr = true;
}
} else |err| {}
} else if (std.mem.eql(u8, "eyr", tag)) {
if (std.fmt.parseInt(u16, value, 10)) |ival| {
if (ival >= 2020 and ival <= 2030) {
rec.eyr = true;
}
} else |err| {}
} else if (std.mem.eql(u8, "hgt", tag)) {
if (std.mem.endsWith(u8, value, "cm")) {
if (std.fmt.parseInt(u16, value[0..value.len-2], 10)) |ival| {
if (ival >= 150 and ival <= 193) {
rec.hgt = true;
}
} else |err| {}
} else if (std.mem.endsWith(u8, value, "in")) {
if (std.fmt.parseInt(u16, value[0..value.len-2], 10)) |ival| {
if (ival >= 59 and ival <= 76) {
rec.hgt = true;
}
} else |err| {}
}
} else if (std.mem.eql(u8, "hcl", tag)) {
if (value.len == 7 and value[0] == '#') {
var valid = true;
for (value[1..]) |char| {
if (!((char >= '0' and char <= '9') or (char >= 'a' and char <= 'f'))) {
valid = false;
}
}
rec.hcl = valid;
}
} else if (std.mem.eql(u8, "ecl", tag)) {
if (
std.mem.eql(u8, value, "amb") or
std.mem.eql(u8, value, "blu") or
std.mem.eql(u8, value, "brn") or
std.mem.eql(u8, value, "gry") or
std.mem.eql(u8, value, "grn") or
std.mem.eql(u8, value, "hzl") or
std.mem.eql(u8, value, "oth")
) {
rec.ecl = true;
}
} else if (std.mem.eql(u8, "pid", tag)) {
if (value.len == 9) {
var valid = true;
for (value[1..]) |char| {
if (!(char >= '0' and char <= '9')) {
valid = false;
}
}
rec.pid = valid;
}
} else if (std.mem.eql(u8, "cid", tag)) {
rec.cid = true;
} else {
print("Unknown tag: {}\n", .{tok});
}
}
numValid += @boolToInt(rec.isValid());
}
print("Valid: {}\n", .{numValid});
} | src/day04.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const print = std.debug.print;
const data = @embedFile("data/day14.txt");
const EntriesList = std.ArrayList(Record);
const Record = struct {
x: usize = 0,
};
var mem = std.AutoArrayHashMap(u36, u36).init(std.heap.page_allocator);
fn setMem(floating: u36, addr: u36, value: u36) void {
if (floating == 0) {
mem.put(addr, value) catch unreachable;
} else {
var bot = @ctz(u36, floating);
var mask = @as(u36, 1) << @intCast(u6, bot);
var new_floating = floating & ~mask;
assert(new_floating < floating);
setMem(new_floating, addr | mask, value);
setMem(new_floating, addr & ~mask, value);
}
}
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const ally = &arena.allocator;
var lines = std.mem.tokenize(data, "\r\n");
var entries = EntriesList.init(ally);
try entries.ensureCapacity(400);
var result: usize = 0;
var mask_valid: u36 = 0;
var mask_values: u36 = 0;
while (lines.next()) |line| {
if (line.len == 0) continue;
if (std.mem.startsWith(u8, line, "mask = ")) {
var mask = line[7..];
mask_valid = 0;
mask_values = 0;
for (mask) |c| {
mask_valid <<= 1;
mask_values <<= 1;
if (c == '1') {
mask_valid |= 1;
mask_values |= 1;
} else if (c == '0') {
mask_valid |= 1;
}
}
print("mask: {}\nval: {b:0>36}\nvad: {b:0>36}\n\n", .{mask, mask_values, mask_valid});
}
else if (std.mem.startsWith(u8, line, "mem[")) {
var it = std.mem.tokenize(line, "me[] =");
const idx = try std.fmt.parseUnsigned(u36, it.next().?, 10);
const val = try std.fmt.parseUnsigned(u36, it.next().?, 10);
assert(it.next() == null);
setMem(~mask_valid, idx | mask_values, val);
// const mod = (val & ~mask_valid) | (mask_values & mask_valid);
// mem[idx] = mod;
}
}
var sum: u64 = 0;
var iter = mem.iterator();
while(iter.next()) |entry| {
sum += entry.value;
}
print("Result: {}\n", .{sum});
} | src/day14.zig |
const std = @import("std");
const dtb = @import("dtb.zig");
usingnamespace @import("util.zig");
const traverser = @import("traverser.zig");
pub const Error = traverser.Error || std.mem.Allocator.Error || error{
MissingCells,
UnsupportedCells,
BadValue,
};
pub fn parse(allocator: *std.mem.Allocator, fdt: []const u8) Error!*dtb.Node {
var parser: Parser = undefined;
try parser.init(allocator, fdt);
var root =
switch (try parser.traverser.current()) {
.BeginNode => |node_name| try parser.handleNode(node_name, null, null),
else => return error.BadStructure,
};
errdefer root.deinit(allocator);
switch (try parser.traverser.next()) {
.End => {},
else => return error.Internal,
}
try resolve(allocator, root, root);
return root;
}
/// ---
const Parser = struct {
const Self = @This();
allocator: *std.mem.Allocator = undefined,
traverser: traverser.Traverser = undefined,
fn init(self: *Self, allocator: *std.mem.Allocator, fdt: []const u8) !void {
self.* = Parser{
.allocator = allocator,
.traverser = .{},
};
try self.traverser.init(fdt);
}
fn handleNode(self: *Self, node_name: []const u8, root: ?*dtb.Node, parent: ?*dtb.Node) Error!*dtb.Node {
var props = std.ArrayList(dtb.Prop).init(self.allocator);
var children = std.ArrayList(*dtb.Node).init(self.allocator);
errdefer {
for (props.items) |p| {
p.deinit(self.allocator);
}
props.deinit();
for (children.items) |c| {
c.deinit(self.allocator);
}
children.deinit();
}
var node = try self.allocator.create(dtb.Node);
errdefer self.allocator.destroy(node);
while (true) {
switch (try self.traverser.next()) {
.BeginNode => |child_name| {
var subnode = try self.handleNode(child_name, root orelse node, node);
errdefer subnode.deinit(self.allocator);
try children.append(subnode);
},
.EndNode => {
break;
},
.Prop => |prop| {
var parsedProp = try self.handleProp(prop.name, prop.value);
errdefer parsedProp.deinit(self.allocator);
try props.append(parsedProp);
},
.End => return error.Internal,
}
}
node.* = .{
.name = node_name,
.props = props.toOwnedSlice(),
.root = root orelse node,
.parent = parent,
.children = children.toOwnedSlice(),
};
return node;
}
fn handleProp(self: *Parser, name: []const u8, value: []const u8) Error!dtb.Prop {
if (std.mem.eql(u8, name, "#address-cells")) {
return dtb.Prop{ .AddressCells = try integer(u32, value) };
} else if (std.mem.eql(u8, name, "#size-cells")) {
return dtb.Prop{ .SizeCells = try integer(u32, value) };
} else if (std.mem.eql(u8, name, "#interrupt-cells")) {
return dtb.Prop{ .InterruptCells = try integer(u32, value) };
} else if (std.mem.eql(u8, name, "#clock-cells")) {
return dtb.Prop{ .ClockCells = try integer(u32, value) };
} else if (std.mem.eql(u8, name, "reg-shift")) {
return dtb.Prop{ .RegShift = try integer(u32, value) };
} else if (std.mem.eql(u8, name, "status")) {
return dtb.Prop{ .Status = try status(value) };
} else if (std.mem.eql(u8, name, "phandle")) {
return dtb.Prop{ .PHandle = try integer(u32, value) };
} else if (std.mem.eql(u8, name, "interrupt-parent")) {
return dtb.Prop{ .InterruptParent = try integer(u32, value) };
} else if (std.mem.eql(u8, name, "compatible")) {
return dtb.Prop{ .Compatible = try self.stringList(value) };
} else if (std.mem.eql(u8, name, "clock-names")) {
return dtb.Prop{ .ClockNames = try self.stringList(value) };
} else if (std.mem.eql(u8, name, "clock-output-names")) {
return dtb.Prop{ .ClockOutputNames = try self.stringList(value) };
} else if (std.mem.eql(u8, name, "interrupt-names")) {
return dtb.Prop{ .InterruptNames = try self.stringList(value) };
} else if (std.mem.eql(u8, name, "clock-frequency")) {
return dtb.Prop{ .ClockFrequency = try u32OrU64(value) };
} else if (std.mem.eql(u8, name, "reg-io-width")) {
return dtb.Prop{ .RegIoWidth = try u32OrU64(value) };
} else if (std.mem.eql(u8, name, "pinctrl-names")) {
return dtb.Prop{ .PinctrlNames = try self.stringList(value) };
} else if (std.mem.eql(u8, name, "pinctrl-0")) {
return dtb.Prop{ .Pinctrl0 = try self.integerList(u32, value) };
} else if (std.mem.eql(u8, name, "pinctrl-1")) {
return dtb.Prop{ .Pinctrl1 = try self.integerList(u32, value) };
} else if (std.mem.eql(u8, name, "pinctrl-2")) {
return dtb.Prop{ .Pinctrl2 = try self.integerList(u32, value) };
} else if (std.mem.eql(u8, name, "assigned-clock-rates")) {
return dtb.Prop{ .AssignedClockRates = try self.integerList(u32, value) };
} else if (std.mem.eql(u8, name, "reg")) {
return dtb.Prop{ .Unresolved = .{ .Reg = value } };
} else if (std.mem.eql(u8, name, "ranges")) {
return dtb.Prop{ .Unresolved = .{ .Ranges = value } };
} else if (std.mem.eql(u8, name, "interrupts")) {
return dtb.Prop{ .Unresolved = .{ .Interrupts = value } };
} else if (std.mem.eql(u8, name, "clocks")) {
return dtb.Prop{ .Unresolved = .{ .Clocks = value } };
} else if (std.mem.eql(u8, name, "assigned-clocks")) {
return dtb.Prop{ .Unresolved = .{ .AssignedClocks = value } };
} else {
return dtb.Prop{ .Unknown = .{ .name = name, .value = value } };
}
}
fn integer(comptime T: type, value: []const u8) !T {
if (value.len != @sizeOf(T)) return error.BadStructure;
return std.mem.bigToNative(T, @ptrCast(*const T, @alignCast(@alignOf(T), value.ptr)).*);
}
fn integerList(self: *Parser, comptime T: type, value: []const u8) ![]T {
if (value.len % @sizeOf(T) != 0) return error.BadStructure;
var list = try self.allocator.alloc(T, value.len / @sizeOf(T));
var i: usize = 0;
while (i < list.len) : (i += 1) {
list[i] = std.mem.bigToNative(T, @ptrCast(*const T, @alignCast(@alignOf(T), value[i * @sizeOf(T) ..].ptr)).*);
}
return list;
}
fn u32OrU64(value: []const u8) !u64 {
return switch (value.len) {
@sizeOf(u32) => @as(u64, try integer(u32, value)),
@sizeOf(u64) => try integer(u64, value),
else => error.BadStructure,
};
}
fn stringList(self: *Parser, value: []const u8) Error![][]const u8 {
const count = std.mem.count(u8, value, "\x00");
var strings = try self.allocator.alloc([]const u8, count);
errdefer self.allocator.free(strings);
var offset: usize = 0;
var strings_i: usize = 0;
while (offset < value.len) : (strings_i += 1) {
const len = std.mem.lenZ(@ptrCast([*c]const u8, value[offset..]));
strings[strings_i] = value[offset .. offset + len];
offset += len + 1;
}
return strings;
}
fn status(value: []const u8) Error!dtb.PropStatus {
if (std.mem.eql(u8, value, "okay\x00")) {
return dtb.PropStatus.Okay;
} else if (std.mem.eql(u8, value, "disabled\x00")) {
return dtb.PropStatus.Disabled;
} else if (std.mem.eql(u8, value, "fail\x00")) {
return dtb.PropStatus.Fail;
}
return error.BadValue;
}
};
// ---
fn resolve(allocator: *std.mem.Allocator, root: *dtb.Node, current: *dtb.Node) Error!void {
for (current.*.props) |*prop| {
switch (prop.*) {
.Unresolved => |unres| {
prop.* = try resolveProp(allocator, root, current, unres);
},
else => {},
}
}
for (current.*.children) |child| {
try resolve(allocator, root, child);
}
}
fn resolveProp(allocator: *std.mem.Allocator, root: *dtb.Node, current: *dtb.Node, unres: dtb.PropUnresolved) !dtb.Prop {
switch (unres) {
.Reg => |v| {
const address_cells = (current.parent orelse return error.BadStructure).addressCells() orelse return error.MissingCells;
const size_cells = (current.parent orelse return error.BadStructure).sizeCells() orelse return error.MissingCells;
return dtb.Prop{ .Reg = try readArray(allocator, v, 2, [2]u32{ address_cells, size_cells }) };
},
.Ranges => |v| {
const address_cells = current.addressCells() orelse return error.MissingCells;
const parent_address_cells = (current.parent orelse return error.BadStructure).addressCells() orelse return error.MissingCells;
const size_cells = current.sizeCells() orelse return error.MissingCells;
return dtb.Prop{ .Ranges = try readArray(allocator, v, 3, [3]u32{ address_cells, parent_address_cells, size_cells }) };
},
.Interrupts => |v| {
const interrupt_cells = current.interruptCells() orelse return error.MissingCells;
const big_endian_cells = try cellsBigEndian(v);
if (big_endian_cells.len % interrupt_cells != 0) {
return error.BadStructure;
}
const group_count = big_endian_cells.len / interrupt_cells;
var groups = try std.ArrayList([]u32).initCapacity(allocator, group_count);
errdefer {
for (groups.items) |group| allocator.free(group);
groups.deinit();
}
var group_i: usize = 0;
while (group_i < group_count) : (group_i += 1) {
var group = try allocator.alloc(u32, interrupt_cells);
var item_i: usize = 0;
while (item_i < interrupt_cells) : (item_i += 1) {
group[item_i] = std.mem.bigToNative(u32, big_endian_cells[group_i * interrupt_cells + item_i]);
}
groups.appendAssumeCapacity(group);
}
return dtb.Prop{ .Interrupts = groups.toOwnedSlice() };
},
.Clocks,
.AssignedClocks,
=> |v| {
const big_endian_cells = try cellsBigEndian(v);
var groups = std.ArrayList([]u32).init(allocator);
errdefer {
for (groups.items) |group| allocator.free(group);
groups.deinit();
}
var cell_i: usize = 0;
while (cell_i < big_endian_cells.len) {
const phandle = std.mem.bigToNative(u32, big_endian_cells[cell_i]);
cell_i += 1;
const target = root.findPHandle(phandle) orelse return error.MissingCells;
const clock_cells = target.prop(.ClockCells) orelse return error.MissingCells;
var group = try allocator.alloc(u32, 1 + clock_cells);
errdefer allocator.free(group);
group[0] = phandle;
var item_i: usize = 0;
while (item_i < clock_cells) : (item_i += 1) {
group[item_i + 1] = std.mem.bigToNative(u32, big_endian_cells[cell_i]);
cell_i += 1;
}
try groups.append(group);
}
return switch (unres) {
.Clocks => dtb.Prop{ .Clocks = groups.toOwnedSlice() },
.AssignedClocks => dtb.Prop{ .AssignedClocks = groups.toOwnedSlice() },
else => unreachable,
};
},
}
}
// ---
const READ_ARRAY_RETURN = u128;
fn readArray(allocator: *std.mem.Allocator, value: []const u8, comptime elem_count: usize, elems: [elem_count]u32) Error![][elem_count]READ_ARRAY_RETURN {
const big_endian_cells = try cellsBigEndian(value);
var elems_sum: usize = 0;
for (elems) |elem| {
if (elem > (@sizeOf(READ_ARRAY_RETURN) / @sizeOf(u32))) {
return error.UnsupportedCells;
}
elems_sum += elem;
}
if (big_endian_cells.len % elems_sum != 0) {
return error.BadStructure;
}
var tuples: [][elem_count]READ_ARRAY_RETURN = try allocator.alloc([elem_count]READ_ARRAY_RETURN, big_endian_cells.len / elems_sum);
errdefer allocator.free(tuples);
var tuple_i: usize = 0;
var cell_i: usize = 0;
while (cell_i < big_endian_cells.len) : (tuple_i += 1) {
var elem_i: usize = 0;
while (elem_i < elem_count) : (elem_i += 1) {
var j: usize = undefined;
tuples[tuple_i][elem_i] = 0;
j = 0;
while (j < elems[elem_i]) : (j += 1) {
tuples[tuple_i][elem_i] = (tuples[tuple_i][elem_i] << 32) | std.mem.bigToNative(u32, big_endian_cells[cell_i]);
cell_i += 1;
}
}
}
return tuples;
}
fn cellsBigEndian(value: []const u8) ![]const u32 {
if (value.len % @sizeOf(u32) != 0) return error.BadStructure;
return @ptrCast([*]const u32, @alignCast(@alignOf(u32), value))[0 .. value.len / @sizeOf(u32)];
} | src/parser.zig |
const std = @import("std");
const ArrayList = std.ArrayList;
const mem = std.mem;
const Allocator = mem.Allocator;
const page_size = mem.page_size;
const assert = std.debug.assert;
/// Global structure to hold allocations that leave their origining thread
/// Not directly accessible
var global_collector: LostAndFound = .{};
/// Every thread has its own allocator instance, that needs to be initialized individually
/// Subsequent calls to init return a pointer to the same instance
threadlocal var localAdma: AdmaAllocator = undefined;
/// This struct is used to track allocations that are free'd in different threads than the ones that created them
/// This allows the solo thread based AdmaAllocator's to be used safely in a multithreaded context
const LostAndFound = if (std.builtin.single_threaded == false)
struct {
init: bool = false,
allocator: *Allocator = undefined,
collector64: Collector = .{},
collector128: Collector = .{},
collector256: Collector = .{},
collector512: Collector = .{},
collector1024: Collector = .{},
collector2048: Collector = .{},
thread_count: usize = 1,
const Self = @This();
const Collector = struct {
list: ArrayList([]u8) = undefined,
lock: u8 = 1,
};
pub fn init(allocator: *Allocator) void {
if (global_collector.init == true) {
_ = @atomicRmw(usize, &global_collector.thread_count, .Add, 1, .SeqCst);
return;
}
global_collector.init = true;
global_collector.allocator = allocator;
global_collector.collector64.list = ArrayList([]u8).init(allocator);
global_collector.collector128.list = ArrayList([]u8).init(allocator);
global_collector.collector256.list = ArrayList([]u8).init(allocator);
global_collector.collector512.list = ArrayList([]u8).init(allocator);
global_collector.collector1024.list = ArrayList([]u8).init(allocator);
global_collector.collector2048.list = ArrayList([]u8).init(allocator);
global_collector.thread_count = 1;
}
pub fn deinit(self: *Self) void {
const count = @atomicRmw(usize, &self.thread_count, .Sub, 1, .SeqCst);
if (count > 1) return;
// deinit all lists. If any leftover allocations, use internal allocator to free
for (self.collector64.list.items) |item| {
self.allocator.free(item);
}
self.collector64.list.deinit();
for (self.collector128.list.items) |item| {
self.allocator.free(item);
}
self.collector128.list.deinit();
for (self.collector256.list.items) |item| {
self.allocator.free(item);
}
self.collector256.list.deinit();
for (self.collector512.list.items) |item| {
self.allocator.free(item);
}
self.collector512.list.deinit();
for (self.collector1024.list.items) |item| {
self.allocator.free(item);
}
self.collector1024.list.deinit();
for (self.collector2048.list.items) |item| {
self.allocator.free(item);
}
self.collector2048.list.deinit();
self.init = false;
}
pub fn lock(self: *Self, list_size: u16) void {
const this = self.pickLock(list_size);
while (true) {
if (@atomicRmw(u8, this, .Xchg, 0, .AcqRel) == 1) {
break;
}
}
}
pub fn tryLock(self: *Self, list_size: u16) ?*ArrayList([]u8) {
const this = self.pickLock(list_size);
const is_locked = @atomicRmw(u8, this, .Xchg, 0, .AcqRel) == 1;
if (is_locked == false) {
return null;
}
const list = self.pickList(list_size);
if (is_locked and list.items.len == 0) {
@atomicStore(u8, this, 1, .Release);
return null;
}
return list;
}
pub fn unlock(self: *Self, list_size: u16) void {
const this = self.pickLock(list_size);
@atomicStore(u8, this, 1, .Release);
}
pub fn pickList(self: *Self, list_size: u16) *ArrayList([]u8) {
switch (list_size) {
64 => return &self.collector64.list,
128 => return &self.collector128.list,
256 => return &self.collector256.list,
512 => return &self.collector512.list,
1024 => return &self.collector1024.list,
2048 => return &self.collector2048.list,
else => @panic("Invalid list size"),
}
}
fn pickLock(self: *Self, list_size: u16) *u8 {
switch (list_size) {
64 => return &self.collector64.lock,
128 => return &self.collector128.lock,
256 => return &self.collector256.lock,
512 => return &self.collector512.lock,
1024 => return &self.collector1024.lock,
2048 => return &self.collector2048.lock,
else => @panic("Invalid lock size"),
}
}
}
else
// Empty global for single threaded mode
struct {
const Self = @This();
pub inline fn init(a: *Allocator) void {}
pub inline fn deinit(s: *Self) void {}
pub inline fn lock(s: *Self, si: u16) void {}
pub inline fn tryLock(s: *Self, si: u16) ?*ArrayList([]u8) {
return null;
}
pub inline fn unlock(s: *Self, si: u16) void {}
pub inline fn pickList(s: *Self, si: u16) void {}
};
pub const AdmaAllocator = struct {
init: bool = false,
/// Exposed allocator
allocator: Allocator,
/// Wrapped allocator; should be a global allocator like page_allocator or c_allocator
wrapped_allocator: *Allocator,
bucket64: Bucket,
bucket128: Bucket,
bucket256: Bucket,
bucket512: Bucket,
bucket1024: Bucket,
bucket2048: Bucket,
slab_pool: ArrayList(*Slab),
const Self = @This();
/// This is used for checking if this allocator is servicing an allocation or the wrapped allocator
pub const largest_alloc = 2048;
/// Initialize with defaults
pub fn init() *Self {
return AdmaAllocator.initWith(std.heap.page_allocator, 0) catch unreachable;
}
/// Initialize this allocator, passing in an allocator to wrap.
pub fn initWith(allocator: *Allocator, initial_slabs: usize) !*Self {
LostAndFound.init(allocator);
var self = &localAdma;
if (self.init == true) return self;
localAdma = Self{
.allocator = Allocator{
.allocFn = adma_alloc,
.resizeFn = adma_resize,
},
.wrapped_allocator = allocator,
.bucket64 = Bucket.init(64, self),
.bucket128 = Bucket.init(128, self),
.bucket256 = Bucket.init(256, self),
.bucket512 = Bucket.init(512, self),
.bucket1024 = Bucket.init(1024, self),
.bucket2048 = Bucket.init(2048, self),
.slab_pool = ArrayList(*Slab).init(allocator),
};
// seed slab pool with initial slabs
try self.seedSlabs(initial_slabs);
self.init = true;
return self;
}
pub fn deinit(self: *Self) void {
self.bucket64.deinit();
self.bucket128.deinit();
self.bucket256.deinit();
self.bucket512.deinit();
self.bucket1024.deinit();
self.bucket2048.deinit();
global_collector.deinit();
for (self.slab_pool.items) |slab| {
self.wrapped_allocator.destroy(slab);
}
self.slab_pool.deinit();
self.init = false;
}
/// Adds `size` number of slabs to this threads slab pool
pub fn seedSlabs(self: *Self, size: usize) !void {
if (size == 0) return;
// goofy range
for (@as([*]void, undefined)[0..size]) |_, i| {
var slab = try self.wrapped_allocator.create(Slab);
try self.slab_pool.append(slab);
}
}
/// Take a slab from the slab pool; allocates one if needed
pub fn fetchSlab(self: *Self) !*Slab {
var maybe_slab = self.slab_pool.popOrNull();
if (maybe_slab) |slab| {
return slab;
}
try self.seedSlabs(1);
return self.slab_pool.pop();
}
/// Give a slab back to the slab pool; if pool is full, free the slab
pub fn releaseSlab(self: *Self, slab: *Slab) !void {
if (self.slab_pool.items.len < 20) {
try self.slab_pool.append(slab);
return;
}
self.wrapped_allocator.destroy(slab);
}
/// Allocator entrypoint
fn adma_alloc(this: *Allocator, len: usize, ptr_align: u29, len_align: u29, ret_addr: usize) ![]u8 {
var self = @fieldParentPtr(Self, "allocator", this);
if (len == 0) {
return "";
} else if (len > largest_alloc) {
return try self.wrapped_allocator.alloc(u8, len);
}
assert(len <= largest_alloc);
return try self.internal_alloc(len);
}
fn adma_resize(this: *Allocator, oldmem: []u8, old_align: u29, new_size: usize, len_align: u29, ret_addr: usize) !usize {
var self = @fieldParentPtr(Self, "allocator", this);
if (std.builtin.mode == .Debug or std.builtin.mode == .ReleaseSafe)
if (self != &localAdma)
@panic("AdmaAllocator pointer passed to another thread; to do this safely, in the new thread init an AdmaAllocator");
if (oldmem.len == 0 and new_size == 0) {
//why would you do this
return 0;
}
// handle external sizes
if (oldmem.len > largest_alloc) {
if (new_size > largest_alloc or new_size == 0) {
return try self.wrapped_allocator.resizeFn(self.wrapped_allocator, oldmem, old_align, new_size, len_align, ret_addr);
}
return try self.wrapped_allocator.resizeFn(self.wrapped_allocator, oldmem, old_align, largest_alloc + 1, len_align, ret_addr);
} else if (oldmem.len == 0 and new_size > largest_alloc) {
return try self.wrapped_allocator.resizeFn(self.wrapped_allocator, oldmem, old_align, new_size, len_align, ret_addr);
}
if (new_size > largest_alloc)
return error.OutOfMemory;
assert(new_size <= largest_alloc);
return try self.internal_resize(oldmem, new_size);
}
/// Select a bucked based on the size given
fn pickBucket(self: *Self, size: u16) ?*Bucket {
return switch (size) {
1...64 => &self.bucket64,
65...128 => &self.bucket128,
129...256 => &self.bucket256,
257...512 => &self.bucket512,
513...1024 => &self.bucket1024,
1025...2048 => &self.bucket2048,
else => null,
};
}
fn internal_alloc(self: *Self, len: usize) ![]u8 {
const bucket = self.pickBucket(@intCast(u16, len));
assert(bucket != null);
const newchunk = try bucket.?.newChunk();
return newchunk[0..len];
}
fn internal_resize(self: *Self, oldmem: []u8, new_size: usize) !usize {
const old_bucket = self.pickBucket(@intCast(u16, oldmem.len));
const new_bucket = self.pickBucket(@intCast(u16, new_size));
if (oldmem.len == 0) {
return 0;
} else if (new_size == 0) {
_ = old_bucket.?.freeChunk(oldmem, false);
return 0;
}
if (old_bucket == new_bucket)
return new_size;
return error.OutOfMemory;
}
};
/// This structure holds all slabs of a given size and uses them to provide allocations
const Bucket = struct {
chunk_size: u16,
parent: *AdmaAllocator,
slabs: ArrayList(*Slab),
const Self = @This();
pub fn init(comptime offset: u16, adma: *AdmaAllocator) Self {
comptime if (page_size % offset != 0)
@panic("Offset needs to be 2's complement and smaller than page_size(4096)");
var slabs = ArrayList(*Slab).init(adma.wrapped_allocator);
return Self{
.chunk_size = offset,
.parent = adma,
.slabs = slabs,
};
}
pub fn deinit(self: *Self) void {
self.collectRemoteChunks();
for (self.slabs.items) |slab| {
self.parent.wrapped_allocator.destroy(slab);
}
self.slabs.deinit();
}
/// Fetches a slab from the slab pool and adds it to the internal tracker
pub fn addSlab(self: *Self) !*Slab {
var slab = try self.parent.fetchSlab();
try self.slabs.append(slab);
return slab.init(self.chunk_size);
}
/// Iterates slabs to find an available chunk; if no slabs have space, request a new one from slab pool
pub fn newChunk(self: *Self) ![]u8 {
for (self.slabs.items) |slab| {
var maybe_chunk = slab.nextChunk();
if (maybe_chunk) |chunk| {
return chunk;
}
}
var slab = try self.addSlab();
var chunk = slab.nextChunk() orelse unreachable;
return chunk;
}
/// Iterates tracked slabs and attempts to free the chunk
pub fn freeChunk(self: *Self, data: []u8, remote: bool) bool {
if (remote == false) {
self.tryCollectRemoteChunks();
}
for (self.slabs.items) |slab, i| {
if (slab.freeChunk(data)) {
if (slab.state == .Empty) {
_ = self.slabs.swapRemove(i);
self.parent.releaseSlab(slab) catch @panic("Failed to release slab to slab_pool");
}
return true;
}
}
if (remote == false) {
self.freeRemoteChunk(data);
}
return false;
}
/// Adds the chunk to the global free list for this chunk_size
fn freeRemoteChunk(self: *Self, data: []u8) void {
// If single_threaded, this fn will only be called if an unknown chunk was given
// That data will just be given to the underlying allocator
if (std.builtin.single_threaded) {
self.parent.wrapped_allocator.free(data);
return;
}
global_collector.lock(self.chunk_size);
defer global_collector.unlock(self.chunk_size);
var list = global_collector.pickList(self.chunk_size);
list.append(data) catch @panic("Failed to add global chunk");
}
/// Casually locks the global freelist for this size; then attempts to free them
fn tryCollectRemoteChunks(self: *Self) void {
var list = global_collector.tryLock(self.chunk_size) orelse return;
defer global_collector.unlock(self.chunk_size);
if (list.items.len == 0) return;
// if freeChunk successful then restart list iteration
outer: while (true) {
for (list.items) |chunk, i| {
if (self.freeChunk(chunk, true) == true) {
_ = list.swapRemove(i);
continue :outer;
}
}
break;
}
}
/// Actively waits to lock the global freelist for this size and attempts to free the chunks
fn collectRemoteChunks(self: *Self) void {
if (std.builtin.single_threaded) return;
global_collector.lock(self.chunk_size);
defer global_collector.unlock(self.chunk_size);
var list = global_collector.pickList(self.chunk_size);
outer: while (true) {
for (list.items) |chunk, i| {
if (self.freeChunk(chunk, true) == true) {
_ = list.swapRemove(i);
continue :outer;
}
}
break;
}
}
};
const SlabState = enum(u8) {
Empty = 0,
Partial,
Full,
};
/// Slab slices a doublepage by a specific size and services allocations from it
const Slab = struct {
state: SlabState,
chunk_size: u16,
next_chunk: u16,
chunks_left: u16,
slab_start: usize,
slab_end: usize,
meta: [128]u8,
data: [page_size * 2]u8,
pub fn init(self: *Slab, chunk_size: u16) *Slab {
self.state = .Empty;
self.chunk_size = chunk_size;
self.next_chunk = 0;
self.chunks_left = self.max_chunks();
self.slab_start = @ptrToInt(&self.data[0]);
self.slab_end = @ptrToInt(&self.data[self.data.len - 1]);
mem.set(u8, &self.meta, 0);
return self;
}
/// Attempts to service a chunk request
pub fn nextChunk(self: *Slab) ?[]u8 {
if (self.state == .Full) return null;
var indx = self.next_chunk;
const max = self.max_chunks();
while (true) : (indx = if (indx >= max or indx + 1 >= max) 0 else indx + 1) {
if (self.meta[indx] == 1) {
continue;
}
const start = self.chunk_size * indx;
const end = start + self.chunk_size;
assert(indx < max);
assert(start < self.data.len);
assert(end <= self.data.len);
var chunk = self.data[start..end];
self.meta[indx] = 1;
self.next_chunk = indx;
self.chunks_left -= 1;
if (self.state == .Empty) {
self.state = .Partial;
} else if (self.state == .Partial and self.chunks_left == 0) {
self.state = .Full;
}
mem.set(u8, chunk, 0);
return chunk;
}
}
/// Attempts to free a chunk by checking if the data ptr falls within the memory space of this Slabs .data
pub fn freeChunk(self: *Slab, data: []u8) bool {
const data_start = @ptrToInt(data.ptr);
if ((self.slab_start <= data_start and self.slab_end > data_start) == false) {
return false;
}
const meta_index = (data_start - self.slab_start) / self.chunk_size;
self.meta[meta_index] = 0;
self.chunks_left += 1;
if (self.state == .Full) {
self.state = .Partial;
} else if (self.state == .Partial and self.chunks_left == self.max_chunks()) {
self.state = .Empty;
}
return true;
}
/// Calculate the max number of chunks for this slabs chunk_size
fn max_chunks(self: *const Slab) u16 {
return @intCast(u16, self.data.len / self.chunk_size);
}
}; | src/adma.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const getNodeType = @import("node.zig").Node;
pub fn BTreeMap(comptime K: type, comptime V: type) type {
return struct {
const Self = @This();
root: ?*Node,
allocator: Allocator,
const B = 6;
const Node = getNodeType(K, V, B);
const KV = Node.KV;
const SearchResult = Node.SearchResult;
const StackItem = struct {
node: *Node,
index: usize,
};
pub fn init(allocator: Allocator) Self {
return Self{
.allocator = allocator,
.root = null,
};
}
pub fn deinit(self: Self) !void {
var stack = std.ArrayList(*Node).init(self.allocator);
defer stack.deinit();
if (self.root) |root| {
try stack.append(root);
} else return;
while (stack.popOrNull()) |node| {
if (!node.isLeaf()) {
var i: usize = 0;
while (i < node.len + 1) : (i += 1) {
try stack.append(node.edges[i].?);
}
}
self.allocator.destroy(node);
}
}
pub fn isEmpty(self: *const Self) bool {
if (self.root == null) return true;
return self.root.?.len == 0;
}
/// Get value from a certain key.
pub fn get(self: Self, key: K) ?V {
var current = self.root;
while (current) |node| {
const result = node.search(key);
if (result.found) {
return node.values[result.index];
} else {
current = node.edges[result.index];
}
}
return null;
}
/// Inserts key-value pair into the map. Swaps the values if already present
/// and returns the old.
/// This function has two stages. In the first stage, the tree
/// is traversed to find the path to the relevant leaf node.
/// This path is saved in a stack, containing the nodes itself
/// and the indices of the children where the path continues.
/// In the second phase, we try to insert and, if the node is full,
/// split the node and hand the result of the split down the stack.
/// Repeat this until insertion is successful or the root itself is split.
pub fn fetchPut(self: *Self, key: K, value: V) !?V {
// TODO: return KV like in std.HashMap
if (self.root == null) {
self.root = try Node.createFromKV(self.allocator, key, value);
return null;
}
var stack = std.ArrayList(StackItem).init(self.allocator);
defer stack.deinit();
// Traverse tree until we find the key or hit bottom.
// If we we find the key, swap new with old value and return the old.
// Build a stack to remember the path
var current = self.root;
var search_result: SearchResult = undefined;
while (current) |node| {
search_result = node.search(key);
if (search_result.found) {
return node.swapValue(search_result.index, value);
}
// Not found, go deeper.
current = node.edges[search_result.index];
try stack.append(.{
.node = node,
.index = search_result.index,
});
}
// Pop top of stack (bottom of tree/leaf node).
var stack_next: ?StackItem = stack.pop();
// Try to insert to leaf node.
var split_result = try stack_next.?.node.insertOrSplit(
self.allocator,
stack_next.?.index,
key,
value,
null,
);
// No split was necessary -> insertion was successful. We're Done.
if (split_result == null) {
return null;
}
// Split was necessary -> move down on stack.
// The current node in stack was incorporated in the tree and the SplitResult.
stack_next = stack.popOrNull();
// Repeat the process of splitting and inserting until insertion is
// successful or we hit the root node, in which case the root node is split.
while (split_result) |split_result_unwrapped| {
if (stack_next) |stack_next_unwrapped| {
// Try to insert the in current stack item.
split_result = try stack_next_unwrapped.node.insertOrSplit(
self.allocator,
stack_next_unwrapped.index,
split_result_unwrapped.key,
split_result_unwrapped.value,
split_result_unwrapped.edge,
);
stack_next = stack.popOrNull();
} else {
// We reached the root.
var new_root = try Node.createFromKV(
self.allocator,
split_result_unwrapped.key,
split_result_unwrapped.value,
);
new_root.edges[0] = self.root;
new_root.edges[1] = split_result_unwrapped.edge;
self.root = new_root;
return null;
}
} else return null;
}
/// Removes and returns a key-value-pair. Returns null if not found.
pub fn fetchRemove(self: *Self, key: K) !?KV {
var stack = std.ArrayList(StackItem).init(self.allocator);
defer stack.deinit();
// Traverse tree until we find the key or hit bottom.
// Build a stack to remember the path
var current = self.root;
var search_result: SearchResult = undefined;
var found_key_ptr: ?*K = null;
var found_value_ptr: ?*V = null;
while (current) |node| {
search_result = node.search(key);
if (search_result.found) {
// Found! Remember pointers to key and value to swap later.
found_key_ptr = &node.keys[search_result.index];
found_value_ptr = &node.values[search_result.index];
// If not reached leaf, increment index in order to find the
// found key's inorder successor when we continue down the tree.
if (!node.isLeaf()) search_result.index += 1;
}
try stack.append(.{
.node = node,
.index = search_result.index,
});
current = node.edges[search_result.index];
if (search_result.found) break;
} else {
// Key not found.
return null;
}
// Continue building the stack to the inorder successor of the found key.
while (current) |node| {
try stack.append(.{
.node = node,
.index = 0,
});
current = node.edges[0];
}
// Reached leaf node. Stack is complete.
// Leaf node is on top of stack now.
var current_stack = stack.pop();
// Swap the KV for deletion with its inorder successor.
var out: KV = .{ .key = found_key_ptr.?.*, .value = found_value_ptr.?.* };
found_key_ptr.?.* = current_stack.node.keys[current_stack.index];
found_value_ptr.?.* = current_stack.node.values[current_stack.index];
// Now ew can remove the key-value pair in the leaf. This can result in an underflow,
// which is handled below.
_ = current_stack.node.remove(current_stack.index);
// If our leaf is also the root, it cannot underflow.
if (current_stack.node == self.root) return out;
// Fix underflow and move down the stack until underflow is fixed.
while (current_stack.node.isLacking()) {
// We have an underflow in the current stack position. This is fixed
// from the parent's erspective, so move down the stack.
current_stack = stack.pop();
// Try to borrow, first from right, then from left.
if (current_stack.node.borrowFromRight(current_stack.index)) return out;
if (current_stack.node.borrowFromLeft(current_stack.index)) return out;
// Borrow was not possible, merge nodes.
if (current_stack.index == current_stack.node.len) {
// the underflowed edge is the most right. Merge with left.
current_stack.node.mergeEdges(self.allocator, current_stack.index - 1);
} else {
// Merge with right.
current_stack.node.mergeEdges(self.allocator, current_stack.index);
}
if (current_stack.node == self.root) {
// We reached the root.
if (self.root.?.len == 0) {
// If root is empty, replace with merged node.
const new_root = current_stack.node.edges[0].?;
self.allocator.destroy(self.root.?);
self.root.? = new_root;
}
break;
}
}
return out;
}
pub fn iteratorInit(self: *const Self) !Iterator {
var new_stack = std.ArrayList(StackItem).init(self.allocator);
if (self.root) |root| {
try new_stack.append(.{
.node = root,
.index = 0,
});
}
return Iterator{
.stack = new_stack,
.backwards = false,
};
}
const Iterator = struct {
stack: std.ArrayList(StackItem),
backwards: bool,
pub fn deinit(it: Iterator) void {
it.stack.deinit();
}
pub fn next(it: *Iterator) !?KV {
while (it.topStackItem()) |item| {
if (!item.node.isLeaf() and !it.backwards) {
// Child exists at index or going forward, go deeper.
var child = item.node.edges[item.index].?;
try it.stack.append(StackItem{
.node = child,
.index = 0,
});
} else {
// No Child or coming backwards.
if (item.index < item.node.len) {
// Node is not yet exhausted.
// Return KV from Node and increment the node's index.
var out = KV{
.key = item.node.keys[item.index],
.value = item.node.values[item.index],
};
item.index += 1;
it.backwards = false;
return out;
} else {
// Node is exhausted.
// Set `backwards` so that this node is not entered again
// in the next iteration.
_ = it.stack.popOrNull();
it.backwards = true;
}
}
} else return null;
}
fn topStackItem(it: *Iterator) ?*StackItem {
if (it.stack.items.len == 0) {
return null;
} else {
return &it.stack.items[it.stack.items.len - 1];
}
}
};
/// Intended for testing and debugging. Traverses whole tree and
/// asserts the validity of every node. Also if every leaf has the
/// same height. -> BTree itself is valid.
fn assertValidity(self: *const Self) !void {
if (self.root == null) return;
var depth: ?usize = null;
var backwards = false;
var stack = std.ArrayList(StackItem).init(self.allocator);
defer stack.deinit();
try stack.append(StackItem{
.node = self.root.?,
.index = 0,
});
self.root.?.assertValidityRoot();
var item: *StackItem = undefined;
while (stack.items.len >= 1) {
item = &stack.items[stack.items.len - 1];
if (!item.node.isLeaf() and !backwards) {
// Go deeper.
var child = item.node.edges[item.index].?;
child.assertValidity();
try stack.append(StackItem{
.node = child,
.index = 0,
});
} else {
// Reached leaf or moving backwards
// Assert tree depth
if (item.node.isLeaf()) {
if (depth == null) {
depth = stack.items.len;
} else {
assert(stack.items.len == depth.?);
}
}
if (item.index < item.node.len) {
// Node is not yet exhausted.
item.index += 1;
backwards = false;
} else {
// Node is exhausted.
// Set `backwards` so that this node is not entered again
// in the next iteration.
_ = stack.popOrNull();
backwards = true;
}
}
}
}
};
}
const testing = std.testing;
test {
const n = 10000;
var keys = std.ArrayList(i16).init(testing.allocator);
defer keys.deinit();
var prng = std.rand.DefaultPrng.init(0);
const random = prng.random();
var i: i16 = 0;
while (i < n) : (i += 1) {
keys.append(random.int(i16)) catch unreachable;
}
var tree = BTreeMap(i32, i32).init(testing.allocator);
defer tree.deinit() catch unreachable;
for (keys.items) |j| {
_ = try tree.fetchPut(j, j);
}
_ = try tree.fetchPut(11111, 99999);
_ = try tree.fetchPut(22222, 88888);
//var it = try tree.iteratorInit();
//defer it.deinit();
//while (it.next() catch unreachable) |item| std.debug.print("{any}\n", .{item});
try testing.expect((try tree.fetchPut(11111, 0)).? == 99999);
try testing.expectEqual(
(try tree.fetchRemove(22222)).?,
@TypeOf(tree).Node.KV{
.key = 22222,
.value = 88888,
},
);
try tree.assertValidity();
random.shuffle(i16, keys.items);
for (keys.items) |j| {
const out = try tree.fetchRemove(j);
if (out) |u| {
try testing.expect(u.key == j);
try testing.expect(u.value == j);
}
}
_ = try tree.fetchRemove(11111);
try testing.expect(tree.isEmpty());
}
test "structs as keys" {
const Car = struct {
power: i32,
pub fn lt(a: @This(), b: @This()) bool {
return a.power < b.power;
}
pub fn eq(a: @This(), b: @This()) bool {
return a.power == b.power;
}
};
const n = 50;
var cars = std.ArrayList(Car).init(testing.allocator);
defer cars.deinit();
var prng = std.rand.DefaultPrng.init(0);
const random = prng.random();
var i: u32 = 0;
while (i < n) : (i += 1) {
var power: i32 = @intCast(i32, random.int(u8)) + 100;
cars.append(Car{ .power = power }) catch unreachable;
}
var tree = BTreeMap(Car, bool).init(testing.allocator);
defer tree.deinit() catch unreachable;
for (cars.items) |j| {
_ = try tree.fetchPut(j, true);
}
for (cars.items) |j| {
_ = try tree.fetchRemove(j);
}
} | src/btreemap.zig |
pub const font_icon_filename_far = "fa-regular-400.ttf";
pub const font_icon_filename_fas = "fa-solid-900.ttf";
pub const icon_range_min = 0xf000;
pub const icon_range_max = 0xf976;
pub const ad = "\u{f641}";
pub const address_book = "\u{f2b9}";
pub const address_card = "\u{f2bb}";
pub const adjust = "\u{f042}";
pub const air_freshener = "\u{f5d0}";
pub const align_center = "\u{f037}";
pub const align_justify = "\u{f039}";
pub const align_left = "\u{f036}";
pub const align_right = "\u{f038}";
pub const allergies = "\u{f461}";
pub const ambulance = "\u{f0f9}";
pub const american_sign_language_interpreting = "\u{f2a3}";
pub const anchor = "\u{f13d}";
pub const angle_double_down = "\u{f103}";
pub const angle_double_left = "\u{f100}";
pub const angle_double_right = "\u{f101}";
pub const angle_double_up = "\u{f102}";
pub const angle_down = "\u{f107}";
pub const angle_left = "\u{f104}";
pub const angle_right = "\u{f105}";
pub const angle_up = "\u{f106}";
pub const angry = "\u{f556}";
pub const ankh = "\u{f644}";
pub const apple_alt = "\u{f5d1}";
pub const archive = "\u{f187}";
pub const archway = "\u{f557}";
pub const arrow_alt_circle_down = "\u{f358}";
pub const arrow_alt_circle_left = "\u{f359}";
pub const arrow_alt_circle_right = "\u{f35a}";
pub const arrow_alt_circle_up = "\u{f35b}";
pub const arrow_circle_down = "\u{f0ab}";
pub const arrow_circle_left = "\u{f0a8}";
pub const arrow_circle_right = "\u{f0a9}";
pub const arrow_circle_up = "\u{f0aa}";
pub const arrow_down = "\u{f063}";
pub const arrow_left = "\u{f060}";
pub const arrow_right = "\u{f061}";
pub const arrow_up = "\u{f062}";
pub const arrows_alt = "\u{f0b2}";
pub const arrows_alt_h = "\u{f337}";
pub const arrows_alt_v = "\u{f338}";
pub const assistive_listening_systems = "\u{f2a2}";
pub const asterisk = "\u{f069}";
pub const at = "\u{f1fa}";
pub const atlas = "\u{f558}";
pub const atom = "\u{f5d2}";
pub const audio_description = "\u{f29e}";
pub const award = "\u{f559}";
pub const baby = "\u{f77c}";
pub const baby_carriage = "\u{f77d}";
pub const backspace = "\u{f55a}";
pub const backward = "\u{f04a}";
pub const bacon = "\u{f7e5}";
pub const bacteria = "\u{f959}";
pub const bacterium = "\u{f95a}";
pub const bahai = "\u{f666}";
pub const balance_scale = "\u{f24e}";
pub const balance_scale_left = "\u{f515}";
pub const balance_scale_right = "\u{f516}";
pub const ban = "\u{f05e}";
pub const band_aid = "\u{f462}";
pub const barcode = "\u{f02a}";
pub const bars = "\u{f0c9}";
pub const baseball_ball = "\u{f433}";
pub const basketball_ball = "\u{f434}";
pub const bath = "\u{f2cd}";
pub const battery_empty = "\u{f244}";
pub const battery_full = "\u{f240}";
pub const battery_half = "\u{f242}";
pub const battery_quarter = "\u{f243}";
pub const battery_three_quarters = "\u{f241}";
pub const bed = "\u{f236}";
pub const beer = "\u{f0fc}";
pub const bell = "\u{f0f3}";
pub const bell_slash = "\u{f1f6}";
pub const bezier_curve = "\u{f55b}";
pub const bible = "\u{f647}";
pub const bicycle = "\u{f206}";
pub const biking = "\u{f84a}";
pub const binoculars = "\u{f1e5}";
pub const biohazard = "\u{f780}";
pub const birthday_cake = "\u{f1fd}";
pub const blender = "\u{f517}";
pub const blender_phone = "\u{f6b6}";
pub const blind = "\u{f29d}";
pub const blog = "\u{f781}";
pub const bold = "\u{f032}";
pub const bolt = "\u{f0e7}";
pub const bomb = "\u{f1e2}";
pub const bone = "\u{f5d7}";
pub const bong = "\u{f55c}";
pub const book = "\u{f02d}";
pub const book_dead = "\u{f6b7}";
pub const book_medical = "\u{f7e6}";
pub const book_open = "\u{f518}";
pub const book_reader = "\u{f5da}";
pub const bookmark = "\u{f02e}";
pub const border_all = "\u{f84c}";
pub const border_none = "\u{f850}";
pub const border_style = "\u{f853}";
pub const bowling_ball = "\u{f436}";
pub const box = "\u{f466}";
pub const box_open = "\u{f49e}";
pub const box_tissue = "\u{f95b}";
pub const boxes = "\u{f468}";
pub const braille = "\u{f2a1}";
pub const brain = "\u{f5dc}";
pub const bread_slice = "\u{f7ec}";
pub const briefcase = "\u{f0b1}";
pub const briefcase_medical = "\u{f469}";
pub const broadcast_tower = "\u{f519}";
pub const broom = "\u{f51a}";
pub const brush = "\u{f55d}";
pub const bug = "\u{f188}";
pub const building = "\u{f1ad}";
pub const bullhorn = "\u{f0a1}";
pub const bullseye = "\u{f140}";
pub const burn = "\u{f46a}";
pub const bus = "\u{f207}";
pub const bus_alt = "\u{f55e}";
pub const business_time = "\u{f64a}";
pub const calculator = "\u{f1ec}";
pub const calendar = "\u{f133}";
pub const calendar_alt = "\u{f073}";
pub const calendar_check = "\u{f274}";
pub const calendar_day = "\u{f783}";
pub const calendar_minus = "\u{f272}";
pub const calendar_plus = "\u{f271}";
pub const calendar_times = "\u{f273}";
pub const calendar_week = "\u{f784}";
pub const camera = "\u{f030}";
pub const camera_retro = "\u{f083}";
pub const campground = "\u{f6bb}";
pub const candy_cane = "\u{f786}";
pub const cannabis = "\u{f55f}";
pub const capsules = "\u{f46b}";
pub const car = "\u{f1b9}";
pub const car_alt = "\u{f5de}";
pub const car_battery = "\u{f5df}";
pub const car_crash = "\u{f5e1}";
pub const car_side = "\u{f5e4}";
pub const caravan = "\u{f8ff}";
pub const caret_down = "\u{f0d7}";
pub const caret_left = "\u{f0d9}";
pub const caret_right = "\u{f0da}";
pub const caret_square_down = "\u{f150}";
pub const caret_square_left = "\u{f191}";
pub const caret_square_right = "\u{f152}";
pub const caret_square_up = "\u{f151}";
pub const caret_up = "\u{f0d8}";
pub const carrot = "\u{f787}";
pub const cart_arrow_down = "\u{f218}";
pub const cart_plus = "\u{f217}";
pub const cash_register = "\u{f788}";
pub const cat = "\u{f6be}";
pub const certificate = "\u{f0a3}";
pub const chair = "\u{f6c0}";
pub const chalkboard = "\u{f51b}";
pub const chalkboard_teacher = "\u{f51c}";
pub const charging_station = "\u{f5e7}";
pub const chart_area = "\u{f1fe}";
pub const chart_bar = "\u{f080}";
pub const chart_line = "\u{f201}";
pub const chart_pie = "\u{f200}";
pub const check = "\u{f00c}";
pub const check_circle = "\u{f058}";
pub const check_double = "\u{f560}";
pub const check_square = "\u{f14a}";
pub const cheese = "\u{f7ef}";
pub const chess = "\u{f439}";
pub const chess_bishop = "\u{f43a}";
pub const chess_board = "\u{f43c}";
pub const chess_king = "\u{f43f}";
pub const chess_knight = "\u{f441}";
pub const chess_pawn = "\u{f443}";
pub const chess_queen = "\u{f445}";
pub const chess_rook = "\u{f447}";
pub const chevron_circle_down = "\u{f13a}";
pub const chevron_circle_left = "\u{f137}";
pub const chevron_circle_right = "\u{f138}";
pub const chevron_circle_up = "\u{f139}";
pub const chevron_down = "\u{f078}";
pub const chevron_left = "\u{f053}";
pub const chevron_right = "\u{f054}";
pub const chevron_up = "\u{f077}";
pub const child = "\u{f1ae}";
pub const church = "\u{f51d}";
pub const circle = "\u{f111}";
pub const circle_notch = "\u{f1ce}";
pub const city = "\u{f64f}";
pub const clinic_medical = "\u{f7f2}";
pub const clipboard = "\u{f328}";
pub const clipboard_check = "\u{f46c}";
pub const clipboard_list = "\u{f46d}";
pub const clock = "\u{f017}";
pub const clone = "\u{f24d}";
pub const closed_captioning = "\u{f20a}";
pub const cloud = "\u{f0c2}";
pub const cloud_download_alt = "\u{f381}";
pub const cloud_meatball = "\u{f73b}";
pub const cloud_moon = "\u{f6c3}";
pub const cloud_moon_rain = "\u{f73c}";
pub const cloud_rain = "\u{f73d}";
pub const cloud_showers_heavy = "\u{f740}";
pub const cloud_sun = "\u{f6c4}";
pub const cloud_sun_rain = "\u{f743}";
pub const cloud_upload_alt = "\u{f382}";
pub const cocktail = "\u{f561}";
pub const code = "\u{f121}";
pub const code_branch = "\u{f126}";
pub const coffee = "\u{f0f4}";
pub const cog = "\u{f013}";
pub const cogs = "\u{f085}";
pub const coins = "\u{f51e}";
pub const columns = "\u{f0db}";
pub const comment = "\u{f075}";
pub const comment_alt = "\u{f27a}";
pub const comment_dollar = "\u{f651}";
pub const comment_dots = "\u{f4ad}";
pub const comment_medical = "\u{f7f5}";
pub const comment_slash = "\u{f4b3}";
pub const comments = "\u{f086}";
pub const comments_dollar = "\u{f653}";
pub const compact_disc = "\u{f51f}";
pub const compass = "\u{f14e}";
pub const compress = "\u{f066}";
pub const compress_alt = "\u{f422}";
pub const compress_arrows_alt = "\u{f78c}";
pub const concierge_bell = "\u{f562}";
pub const cookie = "\u{f563}";
pub const cookie_bite = "\u{f564}";
pub const copy = "\u{f0c5}";
pub const copyright = "\u{f1f9}";
pub const couch = "\u{f4b8}";
pub const credit_card = "\u{f09d}";
pub const crop = "\u{f125}";
pub const crop_alt = "\u{f565}";
pub const cross = "\u{f654}";
pub const crosshairs = "\u{f05b}";
pub const crow = "\u{f520}";
pub const crown = "\u{f521}";
pub const crutch = "\u{f7f7}";
pub const cube = "\u{f1b2}";
pub const cubes = "\u{f1b3}";
pub const cut = "\u{f0c4}";
pub const database = "\u{f1c0}";
pub const deaf = "\u{f2a4}";
pub const democrat = "\u{f747}";
pub const desktop = "\u{f108}";
pub const dharmachakra = "\u{f655}";
pub const diagnoses = "\u{f470}";
pub const dice = "\u{f522}";
pub const dice_d20 = "\u{f6cf}";
pub const dice_d6 = "\u{f6d1}";
pub const dice_five = "\u{f523}";
pub const dice_four = "\u{f524}";
pub const dice_one = "\u{f525}";
pub const dice_six = "\u{f526}";
pub const dice_three = "\u{f527}";
pub const dice_two = "\u{f528}";
pub const digital_tachograph = "\u{f566}";
pub const directions = "\u{f5eb}";
pub const disease = "\u{f7fa}";
pub const divide = "\u{f529}";
pub const dizzy = "\u{f567}";
pub const dna = "\u{f471}";
pub const dog = "\u{f6d3}";
pub const dollar_sign = "\u{f155}";
pub const dolly = "\u{f472}";
pub const dolly_flatbed = "\u{f474}";
pub const donate = "\u{f4b9}";
pub const door_closed = "\u{f52a}";
pub const door_open = "\u{f52b}";
pub const dot_circle = "\u{f192}";
pub const dove = "\u{f4ba}";
pub const download = "\u{f019}";
pub const drafting_compass = "\u{f568}";
pub const dragon = "\u{f6d5}";
pub const draw_polygon = "\u{f5ee}";
pub const drum = "\u{f569}";
pub const drum_steelpan = "\u{f56a}";
pub const drumstick_bite = "\u{f6d7}";
pub const dumbbell = "\u{f44b}";
pub const dumpster = "\u{f793}";
pub const dumpster_fire = "\u{f794}";
pub const dungeon = "\u{f6d9}";
pub const edit = "\u{f044}";
pub const egg = "\u{f7fb}";
pub const eject = "\u{f052}";
pub const ellipsis_h = "\u{f141}";
pub const ellipsis_v = "\u{f142}";
pub const envelope = "\u{f0e0}";
pub const envelope_open = "\u{f2b6}";
pub const envelope_open_text = "\u{f658}";
pub const envelope_square = "\u{f199}";
pub const equals = "\u{f52c}";
pub const eraser = "\u{f12d}";
pub const ethernet = "\u{f796}";
pub const euro_sign = "\u{f153}";
pub const exchange_alt = "\u{f362}";
pub const exclamation = "\u{f12a}";
pub const exclamation_circle = "\u{f06a}";
pub const exclamation_triangle = "\u{f071}";
pub const expand = "\u{f065}";
pub const expand_alt = "\u{f424}";
pub const expand_arrows_alt = "\u{f31e}";
pub const external_link_alt = "\u{f35d}";
pub const external_link_square_alt = "\u{f360}";
pub const eye = "\u{f06e}";
pub const eye_dropper = "\u{f1fb}";
pub const eye_slash = "\u{f070}";
pub const fan = "\u{f863}";
pub const fast_backward = "\u{f049}";
pub const fast_forward = "\u{f050}";
pub const faucet = "\u{f905}";
pub const fax = "\u{f1ac}";
pub const feather = "\u{f52d}";
pub const feather_alt = "\u{f56b}";
pub const female = "\u{f182}";
pub const fighter_jet = "\u{f0fb}";
pub const file = "\u{f15b}";
pub const file_alt = "\u{f15c}";
pub const file_archive = "\u{f1c6}";
pub const file_audio = "\u{f1c7}";
pub const file_code = "\u{f1c9}";
pub const file_contract = "\u{f56c}";
pub const file_csv = "\u{f6dd}";
pub const file_download = "\u{f56d}";
pub const file_excel = "\u{f1c3}";
pub const file_export = "\u{f56e}";
pub const file_image = "\u{f1c5}";
pub const file_import = "\u{f56f}";
pub const file_invoice = "\u{f570}";
pub const file_invoice_dollar = "\u{f571}";
pub const file_medical = "\u{f477}";
pub const file_medical_alt = "\u{f478}";
pub const file_pdf = "\u{f1c1}";
pub const file_powerpoint = "\u{f1c4}";
pub const file_prescription = "\u{f572}";
pub const file_signature = "\u{f573}";
pub const file_upload = "\u{f574}";
pub const file_video = "\u{f1c8}";
pub const file_word = "\u{f1c2}";
pub const fill = "\u{f575}";
pub const fill_drip = "\u{f576}";
pub const film = "\u{f008}";
pub const filter = "\u{f0b0}";
pub const fingerprint = "\u{f577}";
pub const fire = "\u{f06d}";
pub const fire_alt = "\u{f7e4}";
pub const fire_extinguisher = "\u{f134}";
pub const first_aid = "\u{f479}";
pub const fish = "\u{f578}";
pub const fist_raised = "\u{f6de}";
pub const flag = "\u{f024}";
pub const flag_checkered = "\u{f11e}";
pub const flag_usa = "\u{f74d}";
pub const flask = "\u{f0c3}";
pub const flushed = "\u{f579}";
pub const folder = "\u{f07b}";
pub const folder_minus = "\u{f65d}";
pub const folder_open = "\u{f07c}";
pub const folder_plus = "\u{f65e}";
pub const font = "\u{f031}";
pub const font_awesome_logo_full = "\u{f4e6}";
pub const football_ball = "\u{f44e}";
pub const forward = "\u{f04e}";
pub const frog = "\u{f52e}";
pub const frown = "\u{f119}";
pub const frown_open = "\u{f57a}";
pub const funnel_dollar = "\u{f662}";
pub const futbol = "\u{f1e3}";
pub const gamepad = "\u{f11b}";
pub const gas_pump = "\u{f52f}";
pub const gavel = "\u{f0e3}";
pub const gem = "\u{f3a5}";
pub const genderless = "\u{f22d}";
pub const ghost = "\u{f6e2}";
pub const gift = "\u{f06b}";
pub const gifts = "\u{f79c}";
pub const glass_cheers = "\u{f79f}";
pub const glass_martini = "\u{f000}";
pub const glass_martini_alt = "\u{f57b}";
pub const glass_whiskey = "\u{f7a0}";
pub const glasses = "\u{f530}";
pub const globe = "\u{f0ac}";
pub const globe_africa = "\u{f57c}";
pub const globe_americas = "\u{f57d}";
pub const globe_asia = "\u{f57e}";
pub const globe_europe = "\u{f7a2}";
pub const golf_ball = "\u{f450}";
pub const gopuram = "\u{f664}";
pub const graduation_cap = "\u{f19d}";
pub const greater_than = "\u{f531}";
pub const greater_than_equal = "\u{f532}";
pub const grimace = "\u{f57f}";
pub const grin = "\u{f580}";
pub const grin_alt = "\u{f581}";
pub const grin_beam = "\u{f582}";
pub const grin_beam_sweat = "\u{f583}";
pub const grin_hearts = "\u{f584}";
pub const grin_squint = "\u{f585}";
pub const grin_squint_tears = "\u{f586}";
pub const grin_stars = "\u{f587}";
pub const grin_tears = "\u{f588}";
pub const grin_tongue = "\u{f589}";
pub const grin_tongue_squint = "\u{f58a}";
pub const grin_tongue_wink = "\u{f58b}";
pub const grin_wink = "\u{f58c}";
pub const grip_horizontal = "\u{f58d}";
pub const grip_lines = "\u{f7a4}";
pub const grip_lines_vertical = "\u{f7a5}";
pub const grip_vertical = "\u{f58e}";
pub const guitar = "\u{f7a6}";
pub const h_square = "\u{f0fd}";
pub const hamburger = "\u{f805}";
pub const hammer = "\u{f6e3}";
pub const hamsa = "\u{f665}";
pub const hand_holding = "\u{f4bd}";
pub const hand_holding_heart = "\u{f4be}";
pub const hand_holding_medical = "\u{f95c}";
pub const hand_holding_usd = "\u{f4c0}";
pub const hand_holding_water = "\u{f4c1}";
pub const hand_lizard = "\u{f258}";
pub const hand_middle_finger = "\u{f806}";
pub const hand_paper = "\u{f256}";
pub const hand_peace = "\u{f25b}";
pub const hand_point_down = "\u{f0a7}";
pub const hand_point_left = "\u{f0a5}";
pub const hand_point_right = "\u{f0a4}";
pub const hand_point_up = "\u{f0a6}";
pub const hand_pointer = "\u{f25a}";
pub const hand_rock = "\u{f255}";
pub const hand_scissors = "\u{f257}";
pub const hand_sparkles = "\u{f95d}";
pub const hand_spock = "\u{f259}";
pub const hands = "\u{f4c2}";
pub const hands_helping = "\u{f4c4}";
pub const hands_wash = "\u{f95e}";
pub const handshake = "\u{f2b5}";
pub const handshake_alt_slash = "\u{f95f}";
pub const handshake_slash = "\u{f960}";
pub const hanukiah = "\u{f6e6}";
pub const hard_hat = "\u{f807}";
pub const hashtag = "\u{f292}";
pub const hat_cowboy = "\u{f8c0}";
pub const hat_cowboy_side = "\u{f8c1}";
pub const hat_wizard = "\u{f6e8}";
pub const hdd = "\u{f0a0}";
pub const head_side_cough = "\u{f961}";
pub const head_side_cough_slash = "\u{f962}";
pub const head_side_mask = "\u{f963}";
pub const head_side_virus = "\u{f964}";
pub const heading = "\u{f1dc}";
pub const headphones = "\u{f025}";
pub const headphones_alt = "\u{f58f}";
pub const headset = "\u{f590}";
pub const heart = "\u{f004}";
pub const heart_broken = "\u{f7a9}";
pub const heartbeat = "\u{f21e}";
pub const helicopter = "\u{f533}";
pub const highlighter = "\u{f591}";
pub const hiking = "\u{f6ec}";
pub const hippo = "\u{f6ed}";
pub const history = "\u{f1da}";
pub const hockey_puck = "\u{f453}";
pub const holly_berry = "\u{f7aa}";
pub const home = "\u{f015}";
pub const horse = "\u{f6f0}";
pub const horse_head = "\u{f7ab}";
pub const hospital = "\u{f0f8}";
pub const hospital_alt = "\u{f47d}";
pub const hospital_symbol = "\u{f47e}";
pub const hospital_user = "\u{f80d}";
pub const hot_tub = "\u{f593}";
pub const hotdog = "\u{f80f}";
pub const hotel = "\u{f594}";
pub const hourglass = "\u{f254}";
pub const hourglass_end = "\u{f253}";
pub const hourglass_half = "\u{f252}";
pub const hourglass_start = "\u{f251}";
pub const house_damage = "\u{f6f1}";
pub const house_user = "\u{f965}";
pub const hryvnia = "\u{f6f2}";
pub const i_cursor = "\u{f246}";
pub const ice_cream = "\u{f810}";
pub const icicles = "\u{f7ad}";
pub const icons = "\u{f86d}";
pub const id_badge = "\u{f2c1}";
pub const id_card = "\u{f2c2}";
pub const id_card_alt = "\u{f47f}";
pub const igloo = "\u{f7ae}";
pub const image = "\u{f03e}";
pub const images = "\u{f302}";
pub const inbox = "\u{f01c}";
pub const indent = "\u{f03c}";
pub const industry = "\u{f275}";
pub const infinity = "\u{f534}";
pub const info = "\u{f129}";
pub const info_circle = "\u{f05a}";
pub const italic = "\u{f033}";
pub const jedi = "\u{f669}";
pub const joint = "\u{f595}";
pub const journal_whills = "\u{f66a}";
pub const kaaba = "\u{f66b}";
pub const key = "\u{f084}";
pub const keyboard = "\u{f11c}";
pub const khanda = "\u{f66d}";
pub const kiss = "\u{f596}";
pub const kiss_beam = "\u{f597}";
pub const kiss_wink_heart = "\u{f598}";
pub const kiwi_bird = "\u{f535}";
pub const landmark = "\u{f66f}";
pub const language = "\u{f1ab}";
pub const laptop = "\u{f109}";
pub const laptop_code = "\u{f5fc}";
pub const laptop_house = "\u{f966}";
pub const laptop_medical = "\u{f812}";
pub const laugh = "\u{f599}";
pub const laugh_beam = "\u{f59a}";
pub const laugh_squint = "\u{f59b}";
pub const laugh_wink = "\u{f59c}";
pub const layer_group = "\u{f5fd}";
pub const leaf = "\u{f06c}";
pub const lemon = "\u{f094}";
pub const less_than = "\u{f536}";
pub const less_than_equal = "\u{f537}";
pub const level_down_alt = "\u{f3be}";
pub const level_up_alt = "\u{f3bf}";
pub const life_ring = "\u{f1cd}";
pub const lightbulb = "\u{f0eb}";
pub const link = "\u{f0c1}";
pub const lira_sign = "\u{f195}";
pub const list = "\u{f03a}";
pub const list_alt = "\u{f022}";
pub const list_ol = "\u{f0cb}";
pub const list_ul = "\u{f0ca}";
pub const location_arrow = "\u{f124}";
pub const lock = "\u{f023}";
pub const lock_open = "\u{f3c1}";
pub const long_arrow_alt_down = "\u{f309}";
pub const long_arrow_alt_left = "\u{f30a}";
pub const long_arrow_alt_right = "\u{f30b}";
pub const long_arrow_alt_up = "\u{f30c}";
pub const low_vision = "\u{f2a8}";
pub const luggage_cart = "\u{f59d}";
pub const lungs = "\u{f604}";
pub const lungs_virus = "\u{f967}";
pub const magic = "\u{f0d0}";
pub const magnet = "\u{f076}";
pub const mail_bulk = "\u{f674}";
pub const male = "\u{f183}";
pub const map = "\u{f279}";
pub const map_marked = "\u{f59f}";
pub const map_marked_alt = "\u{f5a0}";
pub const map_marker = "\u{f041}";
pub const map_marker_alt = "\u{f3c5}";
pub const map_pin = "\u{f276}";
pub const map_signs = "\u{f277}";
pub const marker = "\u{f5a1}";
pub const mars = "\u{f222}";
pub const mars_double = "\u{f227}";
pub const mars_stroke = "\u{f229}";
pub const mars_stroke_h = "\u{f22b}";
pub const mars_stroke_v = "\u{f22a}";
pub const mask = "\u{f6fa}";
pub const medal = "\u{f5a2}";
pub const medkit = "\u{f0fa}";
pub const meh = "\u{f11a}";
pub const meh_blank = "\u{f5a4}";
pub const meh_rolling_eyes = "\u{f5a5}";
pub const memory = "\u{f538}";
pub const menorah = "\u{f676}";
pub const mercury = "\u{f223}";
pub const meteor = "\u{f753}";
pub const microchip = "\u{f2db}";
pub const microphone = "\u{f130}";
pub const microphone_alt = "\u{f3c9}";
pub const microphone_alt_slash = "\u{f539}";
pub const microphone_slash = "\u{f131}";
pub const microscope = "\u{f610}";
pub const minus = "\u{f068}";
pub const minus_circle = "\u{f056}";
pub const minus_square = "\u{f146}";
pub const mitten = "\u{f7b5}";
pub const mobile = "\u{f10b}";
pub const mobile_alt = "\u{f3cd}";
pub const money_bill = "\u{f0d6}";
pub const money_bill_alt = "\u{f3d1}";
pub const money_bill_wave = "\u{f53a}";
pub const money_bill_wave_alt = "\u{f53b}";
pub const money_check = "\u{f53c}";
pub const money_check_alt = "\u{f53d}";
pub const monument = "\u{f5a6}";
pub const moon = "\u{f186}";
pub const mortar_pestle = "\u{f5a7}";
pub const mosque = "\u{f678}";
pub const motorcycle = "\u{f21c}";
pub const mountain = "\u{f6fc}";
pub const mouse = "\u{f8cc}";
pub const mouse_pointer = "\u{f245}";
pub const mug_hot = "\u{f7b6}";
pub const music = "\u{f001}";
pub const network_wired = "\u{f6ff}";
pub const neuter = "\u{f22c}";
pub const newspaper = "\u{f1ea}";
pub const not_equal = "\u{f53e}";
pub const notes_medical = "\u{f481}";
pub const object_group = "\u{f247}";
pub const object_ungroup = "\u{f248}";
pub const oil_can = "\u{f613}";
pub const om = "\u{f679}";
pub const otter = "\u{f700}";
pub const outdent = "\u{f03b}";
pub const pager = "\u{f815}";
pub const paint_brush = "\u{f1fc}";
pub const paint_roller = "\u{f5aa}";
pub const palette = "\u{f53f}";
pub const pallet = "\u{f482}";
pub const paper_plane = "\u{f1d8}";
pub const paperclip = "\u{f0c6}";
pub const parachute_box = "\u{f4cd}";
pub const paragraph = "\u{f1dd}";
pub const parking = "\u{f540}";
pub const passport = "\u{f5ab}";
pub const pastafarianism = "\u{f67b}";
pub const paste = "\u{f0ea}";
pub const pause = "\u{f04c}";
pub const pause_circle = "\u{f28b}";
pub const paw = "\u{f1b0}";
pub const peace = "\u{f67c}";
pub const pen = "\u{f304}";
pub const pen_alt = "\u{f305}";
pub const pen_fancy = "\u{f5ac}";
pub const pen_nib = "\u{f5ad}";
pub const pen_square = "\u{f14b}";
pub const pencil_alt = "\u{f303}";
pub const pencil_ruler = "\u{f5ae}";
pub const people_arrows = "\u{f968}";
pub const people_carry = "\u{f4ce}";
pub const pepper_hot = "\u{f816}";
pub const percent = "\u{f295}";
pub const percentage = "\u{f541}";
pub const person_booth = "\u{f756}";
pub const phone = "\u{f095}";
pub const phone_alt = "\u{f879}";
pub const phone_slash = "\u{f3dd}";
pub const phone_square = "\u{f098}";
pub const phone_square_alt = "\u{f87b}";
pub const phone_volume = "\u{f2a0}";
pub const photo_video = "\u{f87c}";
pub const piggy_bank = "\u{f4d3}";
pub const pills = "\u{f484}";
pub const pizza_slice = "\u{f818}";
pub const place_of_worship = "\u{f67f}";
pub const plane = "\u{f072}";
pub const plane_arrival = "\u{f5af}";
pub const plane_departure = "\u{f5b0}";
pub const plane_slash = "\u{f969}";
pub const play = "\u{f04b}";
pub const play_circle = "\u{f144}";
pub const plug = "\u{f1e6}";
pub const plus = "\u{f067}";
pub const plus_circle = "\u{f055}";
pub const plus_square = "\u{f0fe}";
pub const podcast = "\u{f2ce}";
pub const poll = "\u{f681}";
pub const poll_h = "\u{f682}";
pub const poo = "\u{f2fe}";
pub const poo_storm = "\u{f75a}";
pub const poop = "\u{f619}";
pub const portrait = "\u{f3e0}";
pub const pound_sign = "\u{f154}";
pub const power_off = "\u{f011}";
pub const pray = "\u{f683}";
pub const praying_hands = "\u{f684}";
pub const prescription = "\u{f5b1}";
pub const prescription_bottle = "\u{f485}";
pub const prescription_bottle_alt = "\u{f486}";
pub const print = "\u{f02f}";
pub const procedures = "\u{f487}";
pub const project_diagram = "\u{f542}";
pub const pump_medical = "\u{f96a}";
pub const pump_soap = "\u{f96b}";
pub const puzzle_piece = "\u{f12e}";
pub const qrcode = "\u{f029}";
pub const question = "\u{f128}";
pub const question_circle = "\u{f059}";
pub const quidditch = "\u{f458}";
pub const quote_left = "\u{f10d}";
pub const quote_right = "\u{f10e}";
pub const quran = "\u{f687}";
pub const radiation = "\u{f7b9}";
pub const radiation_alt = "\u{f7ba}";
pub const rainbow = "\u{f75b}";
pub const random = "\u{f074}";
pub const receipt = "\u{f543}";
pub const record_vinyl = "\u{f8d9}";
pub const recycle = "\u{f1b8}";
pub const redo = "\u{f01e}";
pub const redo_alt = "\u{f2f9}";
pub const registered = "\u{f25d}";
pub const remove_format = "\u{f87d}";
pub const reply = "\u{f3e5}";
pub const reply_all = "\u{f122}";
pub const republican = "\u{f75e}";
pub const restroom = "\u{f7bd}";
pub const retweet = "\u{f079}";
pub const ribbon = "\u{f4d6}";
pub const ring = "\u{f70b}";
pub const road = "\u{f018}";
pub const robot = "\u{f544}";
pub const rocket = "\u{f135}";
pub const route = "\u{f4d7}";
pub const rss = "\u{f09e}";
pub const rss_square = "\u{f143}";
pub const ruble_sign = "\u{f158}";
pub const ruler = "\u{f545}";
pub const ruler_combined = "\u{f546}";
pub const ruler_horizontal = "\u{f547}";
pub const ruler_vertical = "\u{f548}";
pub const running = "\u{f70c}";
pub const rupee_sign = "\u{f156}";
pub const sad_cry = "\u{f5b3}";
pub const sad_tear = "\u{f5b4}";
pub const satellite = "\u{f7bf}";
pub const satellite_dish = "\u{f7c0}";
pub const save = "\u{f0c7}";
pub const school = "\u{f549}";
pub const screwdriver = "\u{f54a}";
pub const scroll = "\u{f70e}";
pub const sd_card = "\u{f7c2}";
pub const search = "\u{f002}";
pub const search_dollar = "\u{f688}";
pub const search_location = "\u{f689}";
pub const search_minus = "\u{f010}";
pub const search_plus = "\u{f00e}";
pub const seedling = "\u{f4d8}";
pub const server = "\u{f233}";
pub const shapes = "\u{f61f}";
pub const share = "\u{f064}";
pub const share_alt = "\u{f1e0}";
pub const share_alt_square = "\u{f1e1}";
pub const share_square = "\u{f14d}";
pub const shekel_sign = "\u{f20b}";
pub const shield_alt = "\u{f3ed}";
pub const shield_virus = "\u{f96c}";
pub const ship = "\u{f21a}";
pub const shipping_fast = "\u{f48b}";
pub const shoe_prints = "\u{f54b}";
pub const shopping_bag = "\u{f290}";
pub const shopping_basket = "\u{f291}";
pub const shopping_cart = "\u{f07a}";
pub const shower = "\u{f2cc}";
pub const shuttle_van = "\u{f5b6}";
pub const sign = "\u{f4d9}";
pub const sign_in_alt = "\u{f2f6}";
pub const sign_language = "\u{f2a7}";
pub const sign_out_alt = "\u{f2f5}";
pub const signal = "\u{f012}";
pub const signature = "\u{f5b7}";
pub const sim_card = "\u{f7c4}";
pub const sink = "\u{f96d}";
pub const sitemap = "\u{f0e8}";
pub const skating = "\u{f7c5}";
pub const skiing = "\u{f7c9}";
pub const skiing_nordic = "\u{f7ca}";
pub const skull = "\u{f54c}";
pub const skull_crossbones = "\u{f714}";
pub const slash = "\u{f715}";
pub const sleigh = "\u{f7cc}";
pub const sliders_h = "\u{f1de}";
pub const smile = "\u{f118}";
pub const smile_beam = "\u{f5b8}";
pub const smile_wink = "\u{f4da}";
pub const smog = "\u{f75f}";
pub const smoking = "\u{f48d}";
pub const smoking_ban = "\u{f54d}";
pub const sms = "\u{f7cd}";
pub const snowboarding = "\u{f7ce}";
pub const snowflake = "\u{f2dc}";
pub const snowman = "\u{f7d0}";
pub const snowplow = "\u{f7d2}";
pub const soap = "\u{f96e}";
pub const socks = "\u{f696}";
pub const solar_panel = "\u{f5ba}";
pub const sort = "\u{f0dc}";
pub const sort_alpha_down = "\u{f15d}";
pub const sort_alpha_down_alt = "\u{f881}";
pub const sort_alpha_up = "\u{f15e}";
pub const sort_alpha_up_alt = "\u{f882}";
pub const sort_amount_down = "\u{f160}";
pub const sort_amount_down_alt = "\u{f884}";
pub const sort_amount_up = "\u{f161}";
pub const sort_amount_up_alt = "\u{f885}";
pub const sort_down = "\u{f0dd}";
pub const sort_numeric_down = "\u{f162}";
pub const sort_numeric_down_alt = "\u{f886}";
pub const sort_numeric_up = "\u{f163}";
pub const sort_numeric_up_alt = "\u{f887}";
pub const sort_up = "\u{f0de}";
pub const spa = "\u{f5bb}";
pub const space_shuttle = "\u{f197}";
pub const spell_check = "\u{f891}";
pub const spider = "\u{f717}";
pub const spinner = "\u{f110}";
pub const splotch = "\u{f5bc}";
pub const spray_can = "\u{f5bd}";
pub const square = "\u{f0c8}";
pub const square_full = "\u{f45c}";
pub const square_root_alt = "\u{f698}";
pub const stamp = "\u{f5bf}";
pub const star = "\u{f005}";
pub const star_and_crescent = "\u{f699}";
pub const star_half = "\u{f089}";
pub const star_half_alt = "\u{f5c0}";
pub const star_of_david = "\u{f69a}";
pub const star_of_life = "\u{f621}";
pub const step_backward = "\u{f048}";
pub const step_forward = "\u{f051}";
pub const stethoscope = "\u{f0f1}";
pub const sticky_note = "\u{f249}";
pub const stop = "\u{f04d}";
pub const stop_circle = "\u{f28d}";
pub const stopwatch = "\u{f2f2}";
pub const stopwatch_20 = "\u{f96f}";
pub const store = "\u{f54e}";
pub const store_alt = "\u{f54f}";
pub const store_alt_slash = "\u{f970}";
pub const store_slash = "\u{f971}";
pub const stream = "\u{f550}";
pub const street_view = "\u{f21d}";
pub const strikethrough = "\u{f0cc}";
pub const stroopwafel = "\u{f551}";
pub const subscript = "\u{f12c}";
pub const subway = "\u{f239}";
pub const suitcase = "\u{f0f2}";
pub const suitcase_rolling = "\u{f5c1}";
pub const sun = "\u{f185}";
pub const superscript = "\u{f12b}";
pub const surprise = "\u{f5c2}";
pub const swatchbook = "\u{f5c3}";
pub const swimmer = "\u{f5c4}";
pub const swimming_pool = "\u{f5c5}";
pub const synagogue = "\u{f69b}";
pub const sync = "\u{f021}";
pub const sync_alt = "\u{f2f1}";
pub const syringe = "\u{f48e}";
pub const table = "\u{f0ce}";
pub const table_tennis = "\u{f45d}";
pub const tablet = "\u{f10a}";
pub const tablet_alt = "\u{f3fa}";
pub const tablets = "\u{f490}";
pub const tachometer_alt = "\u{f3fd}";
pub const tag = "\u{f02b}";
pub const tags = "\u{f02c}";
pub const tape = "\u{f4db}";
pub const tasks = "\u{f0ae}";
pub const taxi = "\u{f1ba}";
pub const teeth = "\u{f62e}";
pub const teeth_open = "\u{f62f}";
pub const temperature_high = "\u{f769}";
pub const temperature_low = "\u{f76b}";
pub const tenge = "\u{f7d7}";
pub const terminal = "\u{f120}";
pub const text_height = "\u{f034}";
pub const text_width = "\u{f035}";
pub const th = "\u{f00a}";
pub const th_large = "\u{f009}";
pub const th_list = "\u{f00b}";
pub const theater_masks = "\u{f630}";
pub const thermometer = "\u{f491}";
pub const thermometer_empty = "\u{f2cb}";
pub const thermometer_full = "\u{f2c7}";
pub const thermometer_half = "\u{f2c9}";
pub const thermometer_quarter = "\u{f2ca}";
pub const thermometer_three_quarters = "\u{f2c8}";
pub const thumbs_down = "\u{f165}";
pub const thumbs_up = "\u{f164}";
pub const thumbtack = "\u{f08d}";
pub const ticket_alt = "\u{f3ff}";
pub const times = "\u{f00d}";
pub const times_circle = "\u{f057}";
pub const tint = "\u{f043}";
pub const tint_slash = "\u{f5c7}";
pub const tired = "\u{f5c8}";
pub const toggle_off = "\u{f204}";
pub const toggle_on = "\u{f205}";
pub const toilet = "\u{f7d8}";
pub const toilet_paper = "\u{f71e}";
pub const toilet_paper_slash = "\u{f972}";
pub const toolbox = "\u{f552}";
pub const tools = "\u{f7d9}";
pub const tooth = "\u{f5c9}";
pub const torah = "\u{f6a0}";
pub const torii_gate = "\u{f6a1}";
pub const tractor = "\u{f722}";
pub const trademark = "\u{f25c}";
pub const traffic_light = "\u{f637}";
pub const trailer = "\u{f941}";
pub const train = "\u{f238}";
pub const tram = "\u{f7da}";
pub const transgender = "\u{f224}";
pub const transgender_alt = "\u{f225}";
pub const trash = "\u{f1f8}";
pub const trash_alt = "\u{f2ed}";
pub const trash_restore = "\u{f829}";
pub const trash_restore_alt = "\u{f82a}";
pub const tree = "\u{f1bb}";
pub const trophy = "\u{f091}";
pub const truck = "\u{f0d1}";
pub const truck_loading = "\u{f4de}";
pub const truck_monster = "\u{f63b}";
pub const truck_moving = "\u{f4df}";
pub const truck_pickup = "\u{f63c}";
pub const tshirt = "\u{f553}";
pub const tty = "\u{f1e4}";
pub const tv = "\u{f26c}";
pub const umbrella = "\u{f0e9}";
pub const umbrella_beach = "\u{f5ca}";
pub const underline = "\u{f0cd}";
pub const undo = "\u{f0e2}";
pub const undo_alt = "\u{f2ea}";
pub const universal_access = "\u{f29a}";
pub const university = "\u{f19c}";
pub const unlink = "\u{f127}";
pub const unlock = "\u{f09c}";
pub const unlock_alt = "\u{f13e}";
pub const upload = "\u{f093}";
pub const user = "\u{f007}";
pub const user_alt = "\u{f406}";
pub const user_alt_slash = "\u{f4fa}";
pub const user_astronaut = "\u{f4fb}";
pub const user_check = "\u{f4fc}";
pub const user_circle = "\u{f2bd}";
pub const user_clock = "\u{f4fd}";
pub const user_cog = "\u{f4fe}";
pub const user_edit = "\u{f4ff}";
pub const user_friends = "\u{f500}";
pub const user_graduate = "\u{f501}";
pub const user_injured = "\u{f728}";
pub const user_lock = "\u{f502}";
pub const user_md = "\u{f0f0}";
pub const user_minus = "\u{f503}";
pub const user_ninja = "\u{f504}";
pub const user_nurse = "\u{f82f}";
pub const user_plus = "\u{f234}";
pub const user_secret = "\u{f21b}";
pub const user_shield = "\u{f505}";
pub const user_slash = "\u{f506}";
pub const user_tag = "\u{f507}";
pub const user_tie = "\u{f508}";
pub const user_times = "\u{f235}";
pub const users = "\u{f0c0}";
pub const users_cog = "\u{f509}";
pub const users_slash = "\u{f973}";
pub const utensil_spoon = "\u{f2e5}";
pub const utensils = "\u{f2e7}";
pub const vector_square = "\u{f5cb}";
pub const venus = "\u{f221}";
pub const venus_double = "\u{f226}";
pub const venus_mars = "\u{f228}";
pub const vial = "\u{f492}";
pub const vials = "\u{f493}";
pub const video = "\u{f03d}";
pub const video_slash = "\u{f4e2}";
pub const vihara = "\u{f6a7}";
pub const virus = "\u{f974}";
pub const virus_slash = "\u{f975}";
pub const viruses = "\u{f976}";
pub const voicemail = "\u{f897}";
pub const volleyball_ball = "\u{f45f}";
pub const volume_down = "\u{f027}";
pub const volume_mute = "\u{f6a9}";
pub const volume_off = "\u{f026}";
pub const volume_up = "\u{f028}";
pub const vote_yea = "\u{f772}";
pub const vr_cardboard = "\u{f729}";
pub const walking = "\u{f554}";
pub const wallet = "\u{f555}";
pub const warehouse = "\u{f494}";
pub const water = "\u{f773}";
pub const wave_square = "\u{f83e}";
pub const weight = "\u{f496}";
pub const weight_hanging = "\u{f5cd}";
pub const wheelchair = "\u{f193}";
pub const wifi = "\u{f1eb}";
pub const wind = "\u{f72e}";
pub const window_close = "\u{f410}";
pub const window_maximize = "\u{f2d0}";
pub const window_minimize = "\u{f2d1}";
pub const window_restore = "\u{f2d2}";
pub const wine_bottle = "\u{f72f}";
pub const wine_glass = "\u{f4e3}";
pub const wine_glass_alt = "\u{f5ce}";
pub const won_sign = "\u{f159}";
pub const wrench = "\u{f0ad}";
pub const x_ray = "\u{f497}";
pub const yen_sign = "\u{f157}";
pub const yin_yang = "\u{f6ad}"; | gamekit/deps/imgui/font_awesome.zig |
const std = @import("std");
const Color = @import("color.zig").Color;
const Canvas = @import("canvas.zig").Canvas;
inline fn byteColorValue(val: f64) u8 {
const v = std.math.clamp(val * 256.0, 0.0, 255.0);
return @floatToInt(u8, v);
}
pub fn canvasToPPM(canvas: Canvas, anywriter: anytype) !void {
var buffered_writer = std.io.bufferedWriter(anywriter);
var writer = buffered_writer.writer();
try std.fmt.format(writer, "P3\n", .{});
try std.fmt.format(writer, "{} {}\n", .{ canvas.width, canvas.height });
try std.fmt.format(writer, "255\n", .{});
var y: usize = 0;
while (y < canvas.height) : (y += 1) {
var x: usize = 0;
while (x < canvas.width) : (x += 1) {
if (x > 0) {
if (x % 5 == 0) { // newline so we don't exceed 70 chars per line
try writer.writeByte('\n');
} else {
try writer.writeByte(' ');
}
}
const p = canvas.at(x, y);
try std.fmt.format(writer, "{} {} {}", .{ byteColorValue(p.red), byteColorValue(p.green), byteColorValue(p.blue) });
}
try writer.writeByte('\n');
}
try buffered_writer.flush();
}
var buffer: [4096]u8 = undefined;
const allocator = std.testing.allocator;
test "writes ppm" {
var c = try Canvas.init(allocator, 5, 3);
defer c.deinit();
var fbs = std.io.fixedBufferStream(&buffer);
try canvasToPPM(c, fbs.writer());
const expected =
\\P3
\\5 3
\\255
\\0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
\\0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
\\0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
\\
;
try std.testing.expectEqualStrings(expected, fbs.getWritten());
}
test "writes ppm with proper colors" {
var c = try Canvas.init(allocator, 5, 3);
defer c.deinit();
c.set(0, 0, Color.init(1.5, 0, 0));
c.set(2, 1, Color.init(0, 0.5, 0));
c.set(4, 2, Color.init(-0.5, 0, 1));
var fbs = std.io.fixedBufferStream(&buffer);
try canvasToPPM(c, fbs.writer());
const expected =
\\P3
\\5 3
\\255
\\255 0 0 0 0 0 0 0 0 0 0 0 0 0 0
\\0 0 0 0 0 0 0 128 0 0 0 0 0 0 0
\\0 0 0 0 0 0 0 0 0 0 0 0 0 0 255
\\
;
try std.testing.expectEqualStrings(expected, fbs.getWritten());
}
test "splitting long lines in PPM files" {
var c = try Canvas.init(allocator, 9, 2);
defer c.deinit();
for (c.pixels) |*p| {
p.* = Color.init(1, 0.8, 0.6);
}
var fbs = std.io.fixedBufferStream(&buffer);
try canvasToPPM(c, fbs.writer());
const expected =
\\P3
\\9 2
\\255
\\255 204 153 255 204 153 255 204 153 255 204 153 255 204 153
\\255 204 153 255 204 153 255 204 153 255 204 153
\\255 204 153 255 204 153 255 204 153 255 204 153 255 204 153
\\255 204 153 255 204 153 255 204 153 255 204 153
\\
;
try std.testing.expectEqualStrings(expected, fbs.getWritten());
} | ppm.zig |