code
stringlengths 38
801k
| repo_path
stringlengths 6
263
|
---|---|
const std = @import("std");
/// The Layout of an I/O Port
/// You cannot have two channels with the same name
/// in your layout.
pub const IOLayout = []const Channel;
/// Represents a single channel in the layout of a whole
/// I/O Port
pub const Channel = struct {
pub const Arrangement = union(enum) {
Custom: void,
Empty: void,
Mono: void,
/// TODO
Stereo: void,
/// TODO
Surround: void,
};
/// The name of this channel
name: []const u8,
short: ?[]const u8 = null,
active: bool = true,
arrangement: Arrangement = .{ .Mono = {} },
};
/// A Buffer contains data of the given I/O layout.
/// By using comptime features you can reference channels by their
/// specified name in your code. This is an easy way to provide
/// meaning without juggling constants.
pub fn AudioBuffer(comptime layout: IOLayout, comptime T: type) type {
return struct {
const Self = @This();
pub const channel_count = layout.len;
raw: [*][*]f32,
frames: usize,
pub fn fromRaw(buffer_list: [*][*]T, frames: usize) Self {
return Self{
.raw = buffer_list,
.frames = frames,
};
}
fn getIndex(comptime name: []const u8) usize {
return inline for (layout) |channel, i| {
if (comptime std.mem.eql(u8, name, channel.name)) {
break i;
}
} else @compileError("Could not find channel with name '" ++ name ++ "'");
}
pub inline fn getBuffer(self: *Self, comptime name: []const u8) []f32 {
const index = comptime getIndex(name);
return self.raw[index][0..self.frames];
}
pub inline fn getConstBuffer(self: Self, comptime name: []const u8) []const f32 {
const index = comptime getIndex(name);
return self.raw[index][0..self.frames];
}
pub inline fn setFrame(self: *Self, comptime name: []const u8, frame: usize, value: T) void {
const index = comptime getIndex(name);
self.raw[index][frame] = value;
}
pub inline fn getFrame(self: Self, comptime name: []const u8, frame: usize) T {
const index = comptime getIndex(name);
return self.raw[index][frame];
}
};
} | src/audio_io.zig |
const upaya = @import("upaya");
const sokol = @import("sokol");
const Texture = upaya.Texture;
const std = @import("std");
const uianim = @import("uianim.zig");
const tcache = @import("texturecache.zig");
const slides = @import("slides.zig");
const parser = @import("parser.zig");
const render = @import("sliderenderer.zig");
const screenshot = @import("screenshot.zig");
const md = @import("markdownlineparser.zig");
usingnamespace md;
usingnamespace upaya.imgui;
usingnamespace sokol;
usingnamespace uianim;
usingnamespace slides;
pub extern "c" fn sched_getaffinity(pid: c_int, size: usize, set: *cpu_set_t) c_int;
const my_fonts = @import("myscalingfonts.zig");
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
var allocator = &arena.allocator;
defer arena.deinit();
try G.init(allocator);
defer G.deinit();
upaya.run(.{
.init = init,
.update = update,
.app_name = "Slides",
.window_title = "Slides",
.ini_file_storage = .none,
.swap_interval = 1, // ca 16ms
.width = 1200,
.height = 800,
});
}
fn init() void {
my_fonts.loadFonts() catch unreachable;
if (std.builtin.os.tag == .windows) {
std.log.info("on windows", .{});
} else {
std.log.info("on {}", .{std.builtin.os.tag});
}
initEditorContent() catch |err| {
std.log.err("Not enough memory for editor!", .{});
};
}
fn initEditorContent() !void {
G.editor_memory = try G.allocator.alloc(u8, ed_anim.textbuf_size);
G.loaded_content = try G.allocator.alloc(u8, ed_anim.textbuf_size);
ed_anim.textbuf = G.editor_memory.ptr;
std.mem.set(u8, G.editor_memory, 0);
std.mem.set(u8, G.loaded_content, 0);
}
// .
// App State
// .
const AppState = enum {
mainmenu,
presenting,
slide_overview,
};
const AppData = struct {
allocator: *std.mem.Allocator = undefined,
slideshow_arena: std.heap.ArenaAllocator = undefined,
slideshow_allocator: *std.mem.Allocator = undefined,
app_state: AppState = .mainmenu,
editor_memory: []u8 = undefined,
loaded_content: []u8 = undefined, // we will check for dirty editor against this
last_window_size: ImVec2 = .{},
content_window_size: ImVec2 = .{},
internal_render_size: ImVec2 = .{ .x = 1920.0, .y = 1064.0 },
slide_render_width: f32 = 1920.0,
slide_render_height: f32 = 1064.0,
slide_renderer: *render.SlideshowRenderer = undefined,
img_tint_col: ImVec4 = .{ .x = 1.0, .y = 1.0, .z = 1.0, .w = 1.0 }, // No tint
img_border_col: ImVec4 = .{ .x = 0.0, .y = 0.0, .z = 0.0, .w = 0.5 }, // 50% opaque black
slideshow_filp: ?[]const u8 = undefined,
status_msg: [*c]const u8 = "",
slideshow: *SlideShow = undefined,
current_slide: i32 = 0,
hot_reload_ticker: usize = 0,
hot_reload_interval_ticks: usize = 1500 / 16,
hot_reload_last_stat: ?std.fs.File.Stat = undefined,
show_saveas: bool = true,
show_saveas_reason: SaveAsReason = .none,
did_post_init: bool = false,
fn init(self: *AppData, alloc: *std.mem.Allocator) !void {
self.allocator = alloc;
self.slideshow_arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
self.slideshow_allocator = &self.slideshow_arena.allocator;
self.slideshow = try SlideShow.new(self.slideshow_allocator);
self.slide_renderer = try render.SlideshowRenderer.new(self.slideshow_allocator);
}
fn deinit(self: *AppData) void {
self.slideshow_arena.deinit();
}
fn reinit(self: *AppData) !void {
self.slideshow_arena.deinit();
self.slideshow_filp = null;
try self.init(self.allocator);
}
};
var G = AppData{};
// .
// Animation
// .
var bt_anim_1 = ButtonAnim{};
var bt_anim_2 = ButtonAnim{};
var bt_anim_3 = ButtonAnim{};
var ed_anim = EditAnim{};
var bt_toggle_ed_anim = ButtonAnim{};
var bt_overview_anim = ButtonAnim{};
var bt_toggle_fullscreen_anim = ButtonAnim{};
var bt_backtomenu_anim = ButtonAnim{};
var bt_toggle_bottom_panel_anim = ButtonAnim{};
var bt_save_anim = ButtonAnim{};
var anim_bottom_panel = bottomPanelAnim{};
var anim_status_msg = MsgAnim{};
var anim_autorun = AutoRunAnim{};
const LaserpointerAnim = struct {
frame_ticker: usize = 0,
anim_ticker: f32 = 0,
show_laserpointer: bool = false,
laserpointer_size: f32 = 15,
laserpointer_zoom: f32 = 1.0,
alpha_table: [6]f32 = [_]f32{ 0.875, 0.875, 0.85, 0.85, 0.825, 0.825 },
alpha_index_step: i32 = 1,
alpha_index: i32 = 0,
size_jiggle_table: [6]f32 = [_]f32{ 1.5, 1.4, 1.30, 1.2, 1.1, 1.0 },
size_jiggle_index_step: i32 = 1,
size_jiggle_index: i32 = 0,
fn anim(self: *LaserpointerAnim, mousepos: ImVec2) void {
if (self.show_laserpointer) {
igSetCursorPos(mousepos);
sapp_show_mouse(false);
var drawlist = igGetForegroundDrawListNil();
const colu32 = igGetColorU32Vec4(ImVec4{ .x = 1, .w = self.alpha_table[@intCast(usize, self.alpha_index)] });
ImDrawList_AddCircleFilled(drawlist, mousepos, self.laserpointer_size * self.laserpointer_zoom + 10 * self.size_jiggle_table[@intCast(usize, self.size_jiggle_index)], colu32, 256);
self.frame_ticker += 1;
if (self.frame_ticker > 6) {
self.advance_anim();
self.anim_ticker += 1;
self.frame_ticker = 0;
}
}
}
fn advance_anim(self: *LaserpointerAnim) void {
if (self.alpha_index == self.alpha_table.len - 1) {
self.alpha_index_step = -1;
}
if (self.alpha_index == 0) {
self.alpha_index_step = 1;
}
if (self.size_jiggle_index == self.size_jiggle_table.len - 1) {
self.size_jiggle_index_step = -1;
}
if (self.size_jiggle_index == 0) {
self.size_jiggle_index_step = 1;
}
self.size_jiggle_index += self.size_jiggle_index_step;
self.alpha_index += self.alpha_index_step;
}
fn toggle(self: *LaserpointerAnim) void {
self.show_laserpointer = !self.show_laserpointer;
self.frame_ticker = 0;
self.anim_ticker = 0;
if (self.show_laserpointer) {
// mouse cursor manipulation such as hiding and changing shape doesn't do anything
// igSetMouseCursor(ImGuiMouseCursor_TextInput);
sapp_show_mouse(false);
std.log.debug("Hiding mouse", .{});
} else {
//igSetMouseCursor(ImGuiMouseCursor_Arrow);
std.log.debug("Showing mouse", .{});
sapp_show_mouse(true);
}
}
};
var anim_laser = LaserpointerAnim{};
// .
// Main Update Frame Loop
// .
var time_prev: i64 = 0;
var time_now: i64 = 0;
fn post_init() void {
// check if we have a cmd line arg
var arg_it = std.process.args();
_ = arg_it.skip(); // skip own exe
if (arg_it.next(G.allocator)) |arg| {
// we have an arg
const slide_fn = arg catch "";
var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined;
const shit = std.fs.realpath(slide_fn, &buf) catch return;
loadSlideshow(shit) catch |err| {
std.log.err("loadSlideshow: {any}", .{err});
};
}
}
// update will be called at every swap interval. with swap_interval = 1 above, we'll get 60 fps
fn update() void {
if (!G.did_post_init) {
G.did_post_init = true;
post_init();
}
// debug update loop timing
if (false) {
time_now = std.time.milliTimestamp();
const time_delta = time_now - time_prev;
time_prev = time_now;
std.log.debug("delta_t: {}", .{time_delta});
}
var mousepos: ImVec2 = undefined;
igGetMousePos(&mousepos);
igGetWindowContentRegionMax(&G.content_window_size);
if (G.content_window_size.x != G.last_window_size.x or G.content_window_size.y != G.last_window_size.y) {
// window size changed
std.log.debug("win size changed from {} to {}", .{ G.last_window_size, G.content_window_size });
G.last_window_size = G.content_window_size;
}
var flags: c_int = 0;
flags = ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoTitleBar;
// flags = ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoTitleBar;
const is_fullscreen = sapp_is_fullscreen();
if (!is_fullscreen) {
flags |= ImGuiWindowFlags_MenuBar;
}
if (igBegin("main", null, flags)) {
// make the "window" fill the whole available area
igSetWindowPosStr("main", .{ .x = 0, .y = 0 }, ImGuiCond_Always);
igSetWindowSizeStr("main", G.content_window_size, ImGuiCond_Always);
if (!is_fullscreen) {
showMenu();
}
handleKeyboard();
// autorun logic
anim_autorun.animate();
if (anim_autorun.flag_switch_slide) {
// inc slide
var current_slide_index = G.current_slide;
var new_slide_index = clampSlideIndex(G.current_slide + 1);
if (current_slide_index == new_slide_index) {
// stop, can't advance any further
anim_autorun.stop();
setStatusMsg("Screen-shotting finished!");
} else {
// OK, doit
jumpToSlide(new_slide_index);
}
}
if (anim_autorun.flag_start_screenshot) {
// TODO: start screenshot
if (screenshot.flameShotLinux(G.allocator)) |ret| {
if (ret == false) {
setStatusMsg("Screenshot failed - try debug build!");
anim_autorun.stop();
}
} else |err| {
std.log.err("screenshot error: {any}", .{err});
setStatusMsg("Screenshot failed - try debug build!");
anim_autorun.stop();
}
}
const do_reload = checkAutoReload() catch false;
if (do_reload) {
loadSlideshow(G.slideshow_filp.?) catch |err| {
std.log.err("Unable to auto-reload: {any}", .{err});
};
}
if (G.slideshow.slides.items.len > 0) {
if (G.current_slide > G.slideshow.slides.items.len) {
G.current_slide = @intCast(i32, G.slideshow.slides.items.len - 1);
}
showSlide2(G.current_slide) catch |err| {
std.log.err("SlideShow Error: {any}", .{err});
};
} else {
if (makeDefaultSlideshow()) |_| {
G.current_slide = 0;
showSlide2(G.current_slide) catch |err| {
std.log.err("SlideShow Error: {any}", .{err});
};
} else |err| {
std.log.err("SlideShow Error: {any}", .{err});
}
}
igEnd();
if (G.show_saveas) {
igOpenPopup("Save slideshow?");
}
if (savePopup(G.show_saveas_reason)) {
G.show_saveas = false;
G.show_saveas_reason = .none;
}
// laser pointeer
if (mousepos.x > 0 and mousepos.y > 0) {
anim_laser.anim(mousepos);
}
}
}
fn makeDefaultSlideshow() !void {
var empty: *Slide = undefined;
empty = try Slide.new(G.slideshow_allocator);
// make a grey background
var bg = SlideItem{ .kind = .background, .color = .{ .x = 0.5, .y = 0.5, .z = 0.5, .w = 0.9 } };
try empty.items.append(bg);
try G.slideshow.slides.append(empty);
try G.slide_renderer.preRender(G.slideshow, "");
std.log.debug("created empty slideshow", .{});
}
fn jumpToSlide(slidenumber: i32) void {
if (G.current_slide == slidenumber) {
return;
}
G.current_slide = slidenumber;
const pos_in_editor = G.slideshow.slides.items[@intCast(usize, slidenumber)].pos_in_editor;
if (ed_anim.visible) {
ed_anim.jumpToPosAndHighlightLine(pos_in_editor, false);
}
}
fn handleKeyboard() void {
const ctrl = igIsKeyDown(SAPP_KEYCODE_LEFT_CONTROL) or igIsKeyDown(SAPP_KEYCODE_RIGHT_CONTROL);
const shift = igIsKeyDown(SAPP_KEYCODE_LEFT_SHIFT) or igIsKeyDown(SAPP_KEYCODE_RIGHT_SHIFT);
if (igIsKeyReleased(SAPP_KEYCODE_Q) and ctrl) {
cmdQuit();
return;
}
if (igIsKeyReleased(SAPP_KEYCODE_O) and ctrl) {
cmdLoadSlideshow();
return;
}
if (igIsKeyReleased(SAPP_KEYCODE_N) and ctrl) {
cmdNewSlideshow();
return;
}
if (igIsKeyReleased(SAPP_KEYCODE_S) and ctrl) {
cmdSave();
return;
}
// don't consume keys while the editor is visible
if ((igGetActiveID() == igGetIDStr("editor")) or ed_anim.search_ed_active or ed_anim.search_ed_active or (igGetActiveID() == igGetIDStr("##search"))) {
return;
}
if (igIsKeyReleased(SAPP_KEYCODE_A)) {
cmdToggleAutoRun();
return;
}
if (igIsKeyReleased(SAPP_KEYCODE_L) and !shift) {
anim_laser.toggle();
return;
}
if (igIsKeyReleased(SAPP_KEYCODE_L) and shift) {
anim_laser.laserpointer_zoom *= 1.5;
if (anim_laser.laserpointer_zoom > 10) {
anim_laser.laserpointer_zoom = 1.0;
}
return;
}
var deltaindex: i32 = 0;
if (igIsKeyReleased(' ')) {
deltaindex = 1;
}
if (igIsKeyReleased(SAPP_KEYCODE_LEFT)) {
deltaindex = -1;
}
if (igIsKeyReleased(SAPP_KEYCODE_RIGHT)) {
deltaindex = 1;
}
if (igIsKeyReleased(SAPP_KEYCODE_BACKSPACE)) {
deltaindex = -1;
}
if (igIsKeyReleased(SAPP_KEYCODE_PAGE_UP)) {
deltaindex = -1;
}
if (igIsKeyReleased(SAPP_KEYCODE_PAGE_DOWN)) {
deltaindex = 1;
}
if (igIsKeyReleased(SAPP_KEYCODE_UP)) {
ed_anim.grow();
}
if (igIsKeyReleased(SAPP_KEYCODE_DOWN)) {
ed_anim.shrink();
}
if (igIsKeyReleased(SAPP_KEYCODE_F)) {
cmdToggleFullscreen();
}
if (igIsKeyReleased(SAPP_KEYCODE_M)) {
if (igIsKeyDown(SAPP_KEYCODE_LEFT_SHIFT) or igIsKeyDown(SAPP_KEYCODE_RIGHT_SHIFT)) {
G.app_state = .mainmenu;
} else {
cmdToggleBottomPanel();
}
}
var new_slide_index: i32 = G.current_slide + deltaindex;
// special slide navigation: 1 and 0
// needs to happen after applying deltaindex!!!!!
if (igIsKeyReleased(SAPP_KEYCODE_1) or (igIsKeyReleased(SAPP_KEYCODE_G) and !shift)) {
new_slide_index = 0;
}
if (igIsKeyReleased(SAPP_KEYCODE_0) or (igIsKeyReleased(SAPP_KEYCODE_G) and shift)) {
new_slide_index = @intCast(i32, G.slideshow.slides.items.len - 1);
}
// clamp slide index
new_slide_index = clampSlideIndex(new_slide_index);
jumpToSlide(new_slide_index);
}
fn clampSlideIndex(new_slide_index: i32) i32 {
var ret = new_slide_index;
if (G.slideshow.slides.items.len > 0 and new_slide_index >= @intCast(i32, G.slideshow.slides.items.len)) {
ret = @intCast(i32, G.slideshow.slides.items.len - 1);
} else if (G.slideshow.slides.items.len == 0 and G.current_slide > 0) {
ret = 0;
}
if (new_slide_index < 0) {
ret = 0;
}
return ret;
}
fn showSlide2(slide_number: i32) !void {
// optionally show editor
my_fonts.pushFontScaled(16);
var start_y: f32 = 22;
if (sapp_is_fullscreen()) {
start_y = 0;
}
ed_anim.desired_size.y = G.content_window_size.y - 37 - start_y;
if (!anim_bottom_panel.visible) {
ed_anim.desired_size.y += 20.0;
}
const editor_active = try animatedEditor(&ed_anim, start_y, G.content_window_size, G.internal_render_size);
if (!editor_active and !ed_anim.search_ed_active) {
if (igIsKeyPressed(SAPP_KEYCODE_E, false)) {
cmdToggleEditor();
}
}
my_fonts.popFontScaled();
// render slide
G.slide_render_width = G.internal_render_size.x - ed_anim.current_size.x;
try G.slide_renderer.render(slide_number, slideAreaTL(), slideSizeInWindow(), G.internal_render_size);
// OK: std.log.debug("slideAreaTL: {any}, slideSizeInWindow: {any}, internal_render_size: {any}", .{ slideAreaTL(), slideSizeInWindow(), G.internal_render_size });
// .
// button row
// .
showBottomPanel();
showStatusMsgV(G.status_msg);
}
const bottomPanelAnim = struct { visible: bool = false, visible_before_editor: bool = false };
fn showBottomPanel() void {
my_fonts.pushFontScaled(16);
igSetCursorPos(ImVec2{ .x = 0, .y = G.content_window_size.y - 30 });
if (anim_bottom_panel.visible) {
igColumns(6, null, false);
bt_toggle_bottom_panel_anim.arrow_dir = 0;
if (animatedButton("a", ImVec2{ .x = 20, .y = 20 }, &bt_toggle_bottom_panel_anim) == .released) {
anim_bottom_panel.visible = false;
}
igNextColumn();
igNextColumn();
// TODO: using the button can cause crashes, whereas the shortcut and menu don't -- what's going on here?
// when button is removed, we also saw it with the shortcut
if (animatedButton("[f]ullscreen", ImVec2{ .x = igGetColumnWidth(1), .y = 22 }, &bt_toggle_fullscreen_anim) == .released) {
cmdToggleFullscreen();
}
igNextColumn();
if (animatedButton("[o]verview", ImVec2{ .x = igGetColumnWidth(1), .y = 22 }, &bt_overview_anim) == .released) {
setStatusMsg("Not implemented!");
}
igNextColumn();
if (animatedButton("[e]ditor", ImVec2{ .x = igGetColumnWidth(2), .y = 22 }, &bt_toggle_ed_anim) == .released) {
cmdToggleEditor();
}
igNextColumn();
if (ed_anim.visible) {
if (animatedButton("save", ImVec2{ .x = igGetColumnWidth(2), .y = 22 }, &bt_save_anim) == .released) {
cmdSave();
}
}
igEndColumns();
} else {
igColumns(5, null, false);
bt_toggle_bottom_panel_anim.arrow_dir = 1;
if (animatedButton("a", ImVec2{ .x = 20, .y = 20 }, &bt_toggle_bottom_panel_anim) == .released) {
anim_bottom_panel.visible = true;
}
igNextColumn();
igNextColumn();
igNextColumn();
igNextColumn();
igEndColumns();
}
my_fonts.popFontScaled();
}
fn showStatusMsg(msg: [*c]const u8) void {
const y = G.content_window_size.y - 50 - 64;
const pos = ImVec2{ .x = 10, .y = y };
const flyin_pos = ImVec2{ .x = G.content_window_size.x, .y = y };
const color = ImVec4{ .x = 1, .y = 1, .z = 0x80 / 255.0, .w = 1 };
my_fonts.pushFontScaled(64);
showMsg(msg.?, pos, flyin_pos, color, &anim_status_msg);
my_fonts.popFontScaled();
}
fn setStatusMsg(msg: [*c]const u8) void {
G.status_msg = msg;
anim_status_msg.anim_state = .fadein;
anim_status_msg.ticker_ms = 0;
}
fn saveSlideshow(filp: ?[]const u8, contents: [*c]u8) bool {
if (filp == null) {
std.log.err("no filename!", .{});
setStatusMsg("Save as -> not implemented!");
return false;
}
std.log.debug("saving to: {s} ", .{filp.?});
const file = std.fs.cwd().createFile(
filp.?,
.{},
) catch |err| {
setStatusMsg("ERROR saving slideshow");
return false;
};
defer file.close();
const contents_slice: []u8 = std.mem.spanZ(contents);
file.writeAll(contents_slice) catch |err| {
setStatusMsg("ERROR saving slideshow");
return false;
};
setStatusMsg("Saved!");
return true;
}
fn slideSizeInWindow() ImVec2 {
var ret = ImVec2{};
var new_content_window_size = G.content_window_size;
new_content_window_size.x -= (G.internal_render_size.x - G.slide_render_width) / G.internal_render_size.x * G.content_window_size.x;
ret.x = new_content_window_size.x;
// aspect ratio
ret.y = ret.x * G.internal_render_size.y / G.internal_render_size.x;
if (ret.y > G.content_window_size.y) {
ret.y = G.content_window_size.y - 1;
ret.x = ret.y * G.internal_render_size.x / G.internal_render_size.y;
}
return ret;
}
fn slideAreaTL() ImVec2 {
var ss = slideSizeInWindow();
var ret = ImVec2{};
ret.y = (G.content_window_size.y - ss.y) / 2.0;
return ret;
}
fn showStatusMsgV(msg: [*c]const u8) void {
var tsize = ImVec2{};
my_fonts.pushFontScaled(64);
igCalcTextSize(&tsize, msg, msg + std.mem.lenZ(msg), false, 2000.0);
const maxw = G.content_window_size.x * 0.9;
if (tsize.x > maxw) {
tsize.x = maxw;
}
const x = (G.content_window_size.x - tsize.x) / 2.0;
const y = G.content_window_size.y / 4;
const pos = ImVec2{ .x = x, .y = y };
const flyin_pos = ImVec2{ .x = x, .y = G.content_window_size.y - tsize.y - 8 };
const color = ImVec4{ .x = 1, .y = 1, .z = 0x80 / 255.0, .w = 1 };
igPushTextWrapPos(maxw + x);
showMsg(msg.?, pos, flyin_pos, color, &anim_status_msg);
igPopTextWrapPos();
my_fonts.popFontScaled();
}
var slicetocbuf: [1024]u8 = undefined;
fn sliceToC(input: []const u8) [:0]u8 {
var input_cut = input;
if (input.len > slicetocbuf.len) {
input_cut = input[0 .. slicetocbuf.len - 1];
}
std.mem.copy(u8, slicetocbuf[0..], input_cut);
slicetocbuf[input_cut.len] = 0;
const xx = slicetocbuf[0 .. input_cut.len + 1];
const yy = xx[0..input_cut.len :0];
return yy;
}
fn checkAutoReload() !bool {
if (G.slideshow_filp) |filp| {
G.hot_reload_ticker += 1;
if (filp.len > 0) {
if (G.hot_reload_ticker > G.hot_reload_interval_ticks) {
std.log.debug("Checking for auto-reload of `{s}`", .{filp});
G.hot_reload_ticker = 0;
var f = try std.fs.openFileAbsolute(filp, .{ .read = true });
defer f.close();
const x = try f.stat();
if (G.hot_reload_last_stat) |last| {
if (x.mtime != last.mtime) {
std.log.debug("RELOAD {s}", .{filp});
return true;
}
} else {
G.hot_reload_last_stat = x;
}
}
}
} else {}
return false;
}
fn loadSlideshow(filp: []const u8) !void {
std.log.debug("LOAD {s}", .{filp});
if (std.fs.openFileAbsolute(filp, .{ .read = true })) |f| {
defer f.close();
G.hot_reload_last_stat = try f.stat();
if (f.read(G.editor_memory)) |howmany| {
G.editor_memory[howmany] = 0;
std.mem.copy(u8, G.loaded_content, G.editor_memory);
G.app_state = .presenting;
const input = std.fs.path.basename(filp);
setStatusMsg(sliceToC(input));
const new_is_old_name = try std.fmt.allocPrint(G.allocator, "{s}", .{filp});
// parse the shit
if (G.reinit()) |_| {
G.slideshow_filp = new_is_old_name;
std.log.debug("filp is now {s}", .{G.slideshow_filp});
if (parser.constructSlidesFromBuf(G.editor_memory, G.slideshow, G.slideshow_allocator)) |pcontext| {
ed_anim.parser_context = pcontext;
} else |err| {
std.log.err("{any}", .{err});
setStatusMsg("Loading failed!");
}
if (false) {
std.log.info("=================================", .{});
std.log.info(" Load Summary:", .{});
std.log.info("=================================", .{});
std.log.info("Constructed {d} slides:", .{G.slideshow.slides.items.len});
for (G.slideshow.slides.items) |slide, i| {
std.log.info("================================================", .{});
std.log.info(" slide {d} pos in editor: {}", .{ i, slide.pos_in_editor });
std.log.info(" slide {d} has {d} items", .{ i, slide.items.items.len });
for (slide.items.items) |item| {
item.printToLog();
}
}
}
if (G.slide_renderer.preRender(G.slideshow, filp)) |_| {
// . empty
} else |err| {
std.log.err("Pre-rendering failed: {any}", .{err});
}
} else |err| {
setStatusMsg("Loading failed!");
std.log.err("Loading failed: {any}", .{err});
}
} else |err| {
setStatusMsg("Loading failed!");
std.log.err("Loading failed: {any}", .{err});
}
} else |err| {
setStatusMsg("Loading failed!");
std.log.err("Loading failed: {any}", .{err});
}
}
fn isEditorDirty() bool {
return !std.mem.eql(u8, G.editor_memory, G.loaded_content);
}
// .
// COMMANDS
// .
fn cmdToggleFullscreen() void {
sapp_toggle_fullscreen();
}
fn cmdToggleEditor() void {
ed_anim.visible = !ed_anim.visible;
if (ed_anim.visible) {
ed_anim.startFlashAnimation();
anim_bottom_panel.visible_before_editor = anim_bottom_panel.visible;
anim_bottom_panel.visible = true;
} else {
anim_bottom_panel.visible = anim_bottom_panel.visible_before_editor;
}
}
fn cmdToggleBottomPanel() void {
anim_bottom_panel.visible = !anim_bottom_panel.visible;
}
fn cmdSave() void {
if (G.slideshow_filp) |filp| {
// save the shit
_ = saveSlideshow(filp, ed_anim.textbuf);
} else {
saveSlideshowAs();
}
if (G.slideshow_filp) |filp| {
loadSlideshow(filp) catch unreachable;
}
}
fn saveSlideshowAs() void {
// file dialog
var selected_file: []const u8 = undefined;
var buf: [2048]u8 = undefined;
const my_path: []u8 = std.os.getcwd(buf[0..]) catch |err| "";
buf[my_path.len] = 0;
const x = buf[0 .. my_path.len + 1];
const y = x[0..my_path.len :0];
const sel = upaya.filebrowser.saveFileDialog("Save Slideshow as...", y, "*.sld");
if (sel == null) {
selected_file = "canceled";
} else {
selected_file = std.mem.span(sel);
}
if (std.mem.startsWith(u8, selected_file, "canceled")) {
setStatusMsg("canceled");
} else {
// now load the file
G.slideshow_filp = selected_file;
_ = saveSlideshow(selected_file, ed_anim.textbuf);
}
}
fn cmdSaveAs() void {
saveSlideshowAs();
}
fn doQuit() void {
std.process.exit(0);
}
fn doLoadSlideshow() void {
// file dialog
var selected_file: []const u8 = undefined;
var buf: [2048]u8 = undefined;
const my_path: []u8 = std.os.getcwd(buf[0..]) catch |err| "";
buf[my_path.len] = 0;
const x = buf[0 .. my_path.len + 1];
const y = x[0..my_path.len :0];
const sel = upaya.filebrowser.openFileDialog("Open Slideshow", y, "*.sld");
if (sel == null) {
selected_file = "canceled";
} else {
selected_file = std.mem.span(sel);
}
if (std.mem.startsWith(u8, selected_file, "canceled")) {
setStatusMsg("canceled");
} else {
// now load the file
loadSlideshow(selected_file) catch |err| {
std.log.err("loadSlideshow: {any}", .{err});
};
}
}
fn doNewSlideshow() void {
G.reinit() catch |err| {
std.log.err("Reinit failed: {any}", .{err});
};
initEditorContent() catch |err| {
std.log.err("Reinit editor failed: {any}", .{err});
};
std.log.debug("Re-initted", .{});
}
fn doNewFromTemplate() void {
setStatusMsg("Not implemented!");
}
fn cmdQuit() void {
if (isEditorDirty()) {
G.show_saveas_reason = .quit;
G.show_saveas = true;
} else {
doQuit();
}
}
fn cmdLoadSlideshow() void {
if (isEditorDirty()) {
G.show_saveas_reason = .load;
G.show_saveas = true;
} else {
doLoadSlideshow();
}
}
fn cmdNewSlideshow() void {
if (isEditorDirty()) {
G.show_saveas_reason = .new;
G.show_saveas = true;
} else {
doNewSlideshow();
}
}
fn cmdNewFromTemplate() void {
if (isEditorDirty()) {
G.show_saveas_reason = .newtemplate;
G.show_saveas = true;
} else {
doNewFromTemplate();
}
}
const SaveAsReason = enum {
none,
quit,
load,
new,
newtemplate,
};
fn savePopup(reason: SaveAsReason) bool {
if (reason == .none) {
return true;
}
igSetNextWindowSize(.{ .x = 500, .y = -1 }, ImGuiCond_Always);
var open: bool = true;
my_fonts.pushFontScaled(14);
defer my_fonts.popFontScaled();
var doit = false;
if (igBeginPopupModal("Save slideshow?", &open, ImGuiWindowFlags_AlwaysAutoResize)) {
defer igEndPopup();
igText("The slideshow has unsaved changes.\nSave it?");
igColumns(2, "id-x", true);
var no = igButton("No", .{ .x = -1, .y = 30 });
igNextColumn();
var yes = igButton("YES", .{ .x = -1, .y = 30 });
doit = yes or no;
if (doit) {
if (yes) {
cmdSave();
}
switch (reason) {
.quit => {
doQuit();
},
.load => {
doLoadSlideshow();
},
.new => {
doNewSlideshow();
},
.newtemplate => {
doNewFromTemplate();
},
.none => {},
}
}
}
return doit;
}
fn cmdToggleAutoRun() void {
if (anim_autorun.toggle()) {
// started
// goto 1st slide
G.current_slide = 0;
if (!sapp_is_fullscreen()) {
cmdToggleFullscreen();
}
// delete the shit if present
if (std.fs.openDirAbsolute("/tmp", .{ .access_sub_paths = true, .iterate = true, .no_follow = true })) |tmpdir| {
// defer tmpdir.close();
if (tmpdir.deleteTree("slide_shots")) {} else |err| {
std.log.err("Warning: Unable to delete /tmp/slide_shots", .{});
}
if (tmpdir.makeDir("slide_shots")) {} else |err| {
std.log.err("Unable to create /tmp/slide_shots", .{});
}
} else |err| {
std.log.err("Unable to open /tmp", .{});
}
}
}
// .
// .
// MENU
// .
// .
fn showMenu() void {
my_fonts.pushFontScaled(14);
if (igBeginMenuBar()) {
defer igEndMenuBar();
if (igBeginMenu("File", true)) {
if (igMenuItemBool("New", "Ctrl + N", false, true)) {
cmdNewSlideshow();
}
// if (igMenuItemBool("New from template...", "", false, true)) {
// cmdNewFromTemplate();
// }
if (igMenuItemBool("Open...", "Ctrl + O", false, true)) {
cmdLoadSlideshow();
}
if (igMenuItemBool("Save", "Ctrl + S", false, isEditorDirty())) {
cmdSave();
}
if (igMenuItemBool("Save as...", "", false, true)) {
cmdSaveAs();
}
if (igMenuItemBool("Quit", "Ctrl + Q", false, true)) {
cmdQuit();
}
igEndMenu();
}
if (igBeginMenu("View", true)) {
if (igMenuItemBool("Toggle editor", "E", false, true)) {
cmdToggleEditor();
}
if (igMenuItemBool("Toggle full-screen", "F", false, true)) {
cmdToggleFullscreen();
}
if (igMenuItemBool("Overview", "O", false, true)) {}
if (igMenuItemBool("Toggle Laserpointer", "L", false, true)) {
anim_laser.toggle();
}
if (igMenuItemBool("Toggle on-screen menu buttons", "M", false, true)) {
cmdToggleBottomPanel();
}
igEndMenu();
}
if (igBeginMenu("Help", true)) {
if (igMenuItemBool("About", "", false, true)) {
setStatusMsg("Not implemented!");
}
igEndMenu();
}
}
my_fonts.popFontScaled();
} | src/main.zig |
pub const StatusCode = enum(u32) {
/// Continue indicates that the initial part of a request has been received and has not yet been rejected by the server.
Continue = 100,
/// SwitchingProtocols indicates that the server understands and is willing to comply with the client's request, via the Upgrade header field, for a change in the application protocol being used on this connection.
SwitchingProtocols = 101,
/// OK indicates that the request has succeeded.
OK = 200,
/// Created indicates that the request has been fulfilled and has resulted in one or more new resources being created.
Created = 201,
/// Accepted indicates that the request has been accepted for processing, but the processing has not been completed.
Accepted = 202,
/// NonAuthoritativeInformation indicates that the request was successful but the enclosed payload has been modified from that of the origin server's 200 (OK) response by a transforming proxy.
NonAuthoritativeInformation = 203,
/// NoContent indicates that the server has successfully fulfilled the request and that there is no additional content to send in the response payload body.
NoContent = 204,
/// ResetContent indicates that the server has fulfilled the request and desires that the user agent reset the "document view", which caused the request to be sent, to its original state as received from the origin server.
ResetContent = 205,
/// PartialContent indicates that the server is successfully fulfilling a range request for the target resource by transferring one or more parts of the selected representation that correspond to the satisfiable ranges found in the requests's Range header field.
PartialContent = 206,
/// MultipleChoices indicates that the target resource has more than one representation, each with its own more specific identifier, and information about the alternatives is being provided so that the user (or user agent) can select a preferred representation by redirecting its request to one or more of those identifiers.
MultipleChoices = 300,
/// MovedPermanently indicates that the target resource has been assigned a new permanent URI and any future references to this resource ought to use one of the enclosed URIs.
MovedPermanently = 301,
/// Found indicates that the target resource resides temporarily under a different URI.
Found = 302,
/// SeeOther indicates that the server is redirecting the user agent to a different resource, as indicated by a URI in the Location header field, that is intended to provide an indirect response to the original request.
SeeOther = 303,
/// NotModified indicates that a conditional GET request has been received and would have resulted in a 200 (OK) response if it were not for the fact that the condition has evaluated to false.
NotModified = 304,
/// UseProxy deprecated
UseProxy = 305,
/// TemporaryRedirect indicates that the target resource resides temporarily under a different URI and the user agent MUST NOT change the request method if it performs an automatic redirection to that URI.
TemporaryRedirect = 307,
/// BadRequest indicates that the server cannot or will not process the request because the received syntax is invalid, nonsensical, or exceeds some limitation on what the server is willing to process.
BadRequest = 400,
/// Unauthorized indicates that the request has not been applied because it lacks valid authentication credentials for the target resource.
Unauthorized = 401,
/// PaymentRequired reserved
PaymentRequired = 402,
/// Forbidden indicates that the server understood the request but refuses to authorize it.
Forbidden = 403,
/// NotFound indicates that the origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
NotFound = 404,
/// MethodNotAllowed indicates that the method specified in the request-line is known by the origin server but not supported by the target resource.
MethodNotAllowed = 405,
/// NotAcceptable indicates that the target resource does not have a current representation that would be acceptable to the user agent, according to the proactive negotiation header fields received in the request, and the server is unwilling to supply a default representation.
NotAcceptable = 406,
/// ProxyAuthenticationRequired is similar to 401 (Unauthorized), but indicates that the client needs to authenticate itself in order to use a proxy.
ProxyAuthenticationRequired = 407,
/// RequestTimeout indicates that the server did not receive a complete request message within the time that it was prepared to wait.
RequestTimeout = 408,
/// Conflict indicates that the request could not be completed due to a conflict with the current state of the resource.
Conflict = 409,
/// Gone indicates that access to the target resource is no longer available at the origin server and that this condition is likely to be permanent.
Gone = 410,
/// LengthRequired indicates that the server refuses to accept the request without a defined Content-Length.
LengthRequired = 411,
/// PreconditionFailed indicates that one or more preconditions given in the request header fields evaluated to false when tested on the server.
PreconditionFailed = 412,
/// PayloadTooLarge indicates that the server is refusing to process a request because the request payload is larger than the server is willing or able to process.
PayloadTooLarge = 413,
/// URITooLong indicates that the server is refusing to service the request because the request-target is longer than the server is willing to interpret.
URITooLong = 414,
/// UnsupportedMediaType indicates that the origin server is refusing to service the request because the payload is in a format not supported by the target resource for this method.
UnsupportedMediaType = 415,
/// RangeNotSatisfiable indicates that none of the ranges in the request's Range header field overlap the current extent of the selected resource or that the set of ranges requested has been rejected due to invalid ranges or an excessive request of small or overlapping ranges.
RangeNotSatisfiable = 416,
/// ExpectationFailed indicates that the expectation given in the request's Expect header field could not be met by at least one of the inbound servers.
ExpectationFailed = 417,
/// Imateapot Any attempt to brew coffee with a teapot should result in the error code 418 I'm a teapot.
Imateapot = 418,
/// UpgradeRequired indicates that the server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol.
UpgradeRequired = 426,
/// InternalServerError indicates that the server encountered an unexpected condition that prevented it from fulfilling the request.
InternalServerError = 500,
/// NotImplemented indicates that the server does not support the functionality required to fulfill the request.
NotImplemented = 501,
/// BadGateway indicates that the server, while acting as a gateway or proxy, received an invalid response from an inbound server it accessed while attempting to fulfill the request.
BadGateway = 502,
/// ServiceUnavailable indicates that the server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay.
ServiceUnavailable = 503,
/// GatewayTimeout indicates that the server, while acting as a gateway or proxy, did not receive a timely response from an upstream server it needed to access in order to complete the request.
GatewayTimeout = 504,
/// HTTPVersionNotSupported indicates that the server does not support, or refuses to support, the protocol version that was used in the request message.
HTTPVersionNotSupported = 505,
/// Processing is an interim response used to inform the client that the server has accepted the complete request, but has not yet completed it.
Processing = 102,
/// MultiStatus provides status for multiple independent operations.
MultiStatus = 207,
/// IMUsed The server has fulfilled a GET request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance.
IMUsed = 226,
/// PermanentRedirect The target resource has been assigned a new permanent URI and any future references to this resource outght to use one of the enclosed URIs. [...] This status code is similar to 301 Moved Permanently (Section 7.3.2 of rfc7231), except that it does not allow rewriting the request method from POST to GET.
PermanentRedirect = 308,
/// UnprocessableEntity means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions.
UnprocessableEntity = 422,
/// Locked means the source or destination resource of a method is locked.
Locked = 423,
/// FailedDependency means that the method could not be performed on the resource because the requested action depended on another action and that action failed.
FailedDependency = 424,
/// PreconditionRequired indicates that the origin server requires the request to be conditional.
PreconditionRequired = 428,
/// TooManyRequests indicates that the user has sent too many requests in a given amount of time ("rate limiting").
TooManyRequests = 429,
/// RequestHeaderFieldsTooLarge indicates that the server is unwilling to process the request because its header fields are too large.
RequestHeaderFieldsTooLarge = 431,
/// UnavailableForLegalReasons This status code indicates that the server is denying access to the resource in response to a legal demand.
UnavailableForLegalReasons = 451,
/// VariantAlsoNegotiates indicates that the server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process.
VariantAlsoNegotiates = 506,
/// InsufficientStorage means the method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request.
InsufficientStorage = 507,
/// NetworkAuthenticationRequired indicates that the client needs to authenticate to gain network access.
NetworkAuthenticationRequired = 511,
};
pub fn reasonPhrase(sc: StatusCode) []const u8 {
return switch (sc) {
StatusCode.Continue => "Continue"[0..],
StatusCode.SwitchingProtocols => "Switching Protocols"[0..],
StatusCode.OK => "OK"[0..],
StatusCode.Created => "Created"[0..],
StatusCode.Accepted => "Accepted"[0..],
StatusCode.NonAuthoritativeInformation => "Non-Authoritative Information"[0..],
StatusCode.NoContent => "No Content"[0..],
StatusCode.ResetContent => "Reset Content"[0..],
StatusCode.PartialContent => "Partial Content"[0..],
StatusCode.MultipleChoices => "Multiple Choices"[0..],
StatusCode.MovedPermanently => "Moved Permanently"[0..],
StatusCode.Found => "Found"[0..],
StatusCode.SeeOther => "See Other"[0..],
StatusCode.NotModified => "Not Modified"[0..],
StatusCode.UseProxy => "Use Proxy"[0..],
StatusCode.TemporaryRedirect => "Temporary Redirect"[0..],
StatusCode.BadRequest => "Bad Request"[0..],
StatusCode.Unauthorized => "Unauthorized"[0..],
StatusCode.PaymentRequired => "Payment Required"[0..],
StatusCode.Forbidden => "Forbidden"[0..],
StatusCode.NotFound => "Not Found"[0..],
StatusCode.MethodNotAllowed => "Method Not Allowed"[0..],
StatusCode.NotAcceptable => "Not Acceptable"[0..],
StatusCode.ProxyAuthenticationRequired => "Proxy Authentication Required"[0..],
StatusCode.RequestTimeout => "Request Timeout"[0..],
StatusCode.Conflict => "Conflict"[0..],
StatusCode.Gone => "Gone"[0..],
StatusCode.LengthRequired => "Length Required"[0..],
StatusCode.PreconditionFailed => "Precondition Failed"[0..],
StatusCode.PayloadTooLarge => "Payload Too Large"[0..],
StatusCode.URITooLong => "URI Too Long"[0..],
StatusCode.UnsupportedMediaType => "Unsupported Media Type"[0..],
StatusCode.RangeNotSatisfiable => "Range Not Satisfiable"[0..],
StatusCode.ExpectationFailed => "Expectation Failed"[0..],
StatusCode.Imateapot => "I'm a teapot"[0..],
StatusCode.UpgradeRequired => "Upgrade Required"[0..],
StatusCode.InternalServerError => "Internal Server Error"[0..],
StatusCode.NotImplemented => "Not Implemented"[0..],
StatusCode.BadGateway => "Bad Gateway"[0..],
StatusCode.ServiceUnavailable => "Service Unavailable"[0..],
StatusCode.GatewayTimeout => "Gateway Time-out"[0..],
StatusCode.HTTPVersionNotSupported => "HTTP Version Not Supported"[0..],
StatusCode.Processing => "Processing"[0..],
StatusCode.MultiStatus => "Multi-Status"[0..],
StatusCode.IMUsed => "IM Used"[0..],
StatusCode.PermanentRedirect => "Permanent Redirect"[0..],
StatusCode.UnprocessableEntity => "Unprocessable Entity"[0..],
StatusCode.Locked => "Locked"[0..],
StatusCode.FailedDependency => "Failed Dependency"[0..],
StatusCode.PreconditionRequired => "Precondition Required"[0..],
StatusCode.TooManyRequests => "Too Many Requests"[0..],
StatusCode.RequestHeaderFieldsTooLarge => "Request Header Fields Too Large"[0..],
StatusCode.UnavailableForLegalReasons => "Unavailable For Legal Reasons"[0..],
StatusCode.VariantAlsoNegotiates => "Variant Also Negotiates"[0..],
StatusCode.InsufficientStorage => "Insufficient Storage"[0..],
StatusCode.NetworkAuthenticationRequired => "Network Authentication Required"[0..],
else => "Unknown"[0..],
};
} | zig/src/olin/http/status_codes.zig |
const std = @import("std");
const io = std.io;
const os = std.os;
pub fn main() !void {
// Get stdin and stdout
const in_stream = io.getStdIn();
// const out_stream = io.getStdOut();
// Save current termios
const original_termios = try os.tcgetattr(in_stream.handle);
// Set new termios
var raw_termios = original_termios;
raw_termios.iflag &=
~(@as(os.tcflag_t, os.BRKINT) | os.ICRNL | os.INPCK | os.ISTRIP | os.IXON);
raw_termios.oflag &= ~(@as(os.tcflag_t, os.OPOST));
raw_termios.cflag |= os.CS8;
raw_termios.lflag &= ~(@as(os.tcflag_t, os.ECHO) | os.ICANON | os.IEXTEN | os.ISIG);
raw_termios.cc[os.VMIN] = 0;
raw_termios.cc[os.VTIME] = 1;
try os.tcsetattr(in_stream.handle, os.TCSA.FLUSH, raw_termios);
// Enter extended mode TMUX style
// try out_stream.writer().writeAll("\x1b[>4;1m");
// Enter extended mode KITTY style
// try out_stream.writer().writeAll("\x1b[>1u");
// Read characters, press q to quit
var buf = [_]u8{0} ** 8;
var number_read = try in_stream.reader().read(buf[0..]);
while (true) : (number_read = try in_stream.reader().read(buf[0..])) {
if (number_read > 0) {
switch (buf[0]) {
'q' => break,
else => {
std.debug.print("buf[0]: {x}\r\n", .{buf[0]});
std.debug.print("buf[1]: {x}\r\n", .{buf[1]});
std.debug.print("buf[2]: {x}\r\n", .{buf[2]});
std.debug.print("buf[3]: {x}\r\n", .{buf[3]});
std.debug.print("buf[4]: {x}\r\n", .{buf[4]});
std.debug.print("buf[5]: {x}\r\n", .{buf[5]});
std.debug.print("buf[6]: {x}\r\n", .{buf[6]});
std.debug.print("buf[7]: {x}\r\n", .{buf[7]});
std.debug.print("\r\n", .{});
buf[0] = 0;
buf[1] = 0;
buf[2] = 0;
buf[3] = 0;
buf[4] = 0;
buf[5] = 0;
buf[6] = 0;
buf[7] = 0;
},
}
}
std.time.sleep(10 * std.time.ns_per_ms);
}
// Exit extended mode TMUX style
// try out_stream.writer().writeAll("\x1b[>4;0m");
// Enter extended mode KITTY style
// try out_stream.writer().writeAll("\x1b[<u");
try os.tcsetattr(in_stream.handle, os.TCSA.FLUSH, original_termios);
} | tests/keypress.zig |
const std = @import("std");
const aoc = @import("aoc-lib.zig");
test "examples" {
const test1 = try aoc.Ints(aoc.talloc, i64, aoc.test1file);
defer aoc.talloc.free(test1);
const inp = try aoc.Ints(aoc.talloc, i64, aoc.inputfile);
defer aoc.talloc.free(inp);
try aoc.assertEq(@as(i64, 127), part1(test1, 5));
try aoc.assertEq(@as(i64, 62), part2(test1, 127));
try aoc.assertEq(@as(i64, 31161678), part1(inp, 25));
try aoc.assertEq(@as(i64, 5453868), part2(inp, 31161678));
}
fn part1(nums: []const i64, pre: usize) i64 {
var i = pre;
while (i < nums.len) : (i += 1) {
var valid = false;
var j: usize = i - pre;
while (j <= i) : (j += 1) {
var k: usize = j;
while (k <= i) : (k += 1) {
if (nums[j] + nums[k] == nums[i]) {
valid = true;
}
}
}
if (!valid) {
return nums[i];
}
}
return 0;
}
fn part2(nums: []const i64, p1: i64) i64 {
var n: usize = 1;
while (n < nums.len) : (n += 1) {
var i: usize = 0;
while (i < nums.len - n) : (i += 1) {
var s: i64 = 0;
var min: i64 = std.math.maxInt(i64);
var max: i64 = std.math.minInt(i64);
var j = i;
while (j <= i + n) : (j += 1) {
if (nums[j] < min) {
min = nums[j];
}
if (nums[j] > max) {
max = nums[j];
}
s += nums[j];
}
if (s == p1) {
return min + max;
}
}
}
return 0;
}
fn day09(inp: []const u8, bench: bool) anyerror!void {
var nums = try aoc.Ints(aoc.halloc, i64, inp);
defer aoc.halloc.free(nums);
var p1 = part1(nums, 25);
var p2 = part2(nums, p1);
if (!bench) {
try aoc.print("Part 1: {}\nPart 2: {}\n", .{ p1, p2 });
}
}
pub fn main() anyerror!void {
try aoc.benchme(aoc.input(), day09);
} | 2020/09/aoc.zig |
const index = @import("index.zig");
const builtin = @import("builtin");
const std = @import("std");
const os = std.os;
const is_posix = builtin.os != builtin.Os.windows;
const is_windows = builtin.os == builtin.Os.windows;
pub const Fs = struct {
pub fn init() Fs {
return Fs{};
}
pub fn deinit(fs: *Fs) void {}
pub fn open(fs: *Fs, path: []const u8, flags: index.Open.Flags) !File {
if (is_windows) {
const path_w = try os.windows_util.sliceToPrefixedFileW(path);
var desired_access: os.windows.DWORD = 0;
var share_mode: os.windows.DWORD = 0;
if ((flags & index.Open.Read) != 0) {
desired_access |= os.windows.GENERIC_READ;
share_mode |= os.windows.FILE_SHARE_READ;
}
if ((flags & index.Open.Write) != 0) {
desired_access |= os.windows.GENERIC_WRITE;
share_mode |= os.windows.FILE_SHARE_WRITE;
}
var creation_disposition: os.windows.DWORD = 0;
if ((flags & index.Open.Create) != 0) {
creation_disposition |= os.windows.OPEN_ALWAYS;
} else {
creation_disposition |= os.windows.OPEN_EXISTING;
}
if ((flags & index.Open.Truncate) != 0) {
creation_disposition |= os.windows.TRUNCATE_EXISTING;
}
const handle = try os.windowsOpenW(
path_w,
desired_access,
share_mode,
creation_disposition,
os.windows.FILE_ATTRIBUTE_NORMAL,
);
return File{ .handle = os.File.openHandle(handle) };
} else if (is_posix) {
const path_c = try os.toPosixPath(path);
var linux_flags: u32 = os.posix.O_LARGEFILE;
if ((flags & index.Open.Read) != 0 and (flags & index.Open.Write) != 0) {
linux_flags |= os.posix.O_RDWR;
linux_flags |= os.posix.O_CLOEXEC;
} else if ((flags & index.Open.Read) != 0) {
linux_flags |= os.posix.O_RDONLY;
} else if ((flags & index.Open.Write) != 0) {
linux_flags |= os.posix.O_WRONLY;
linux_flags |= os.posix.O_CLOEXEC;
}
if ((flags & index.Open.Create) != 0)
linux_flags |= os.posix.O_CREAT;
if ((flags & index.Open.Truncate) != 0)
linux_flags |= os.posix.O_TRUNC;
const handle = try os.posixOpenC(&path_c, linux_flags, os.File.default_mode);
return File{ .handle = os.File.openHandle(handle) };
}
@compileError("Unsupported OS");
}
pub fn close(fs: *Fs, file: *File) void {
file.handle.close();
file.* = undefined;
}
};
pub const File = struct {
handle: os.File,
pub fn read(file: *File, buf: []u8) ![]u8 {
const len = try file.handle.read(buf);
return buf[0..len];
}
pub fn write(file: *File, buf: []const u8) !void {
try file.handle.write(buf);
}
pub fn seek(file: *File, p: u64) !void {
try file.handle.seekTo(@intCast(usize, p));
}
pub fn pos(file: *File) !u64 {
return u64(try file.handle.getPos());
}
pub fn size(file: *File) !u64 {
return u64(try file.handle.getEndPos());
}
}; | src/os.zig |
const std = @import("std");
const opt = @import("opt.zig");
const warn = std.debug.warn;
//Globals for flags
var ALPHA: bool = false;
var RECUR: bool = false;
var ALL: bool = false;
var TABS: usize = 0;
const lsFlags = enum {
All,
Alpha,
Recursive,
Help,
};
var flags = [_]opt.Flag(lsFlags){
.{
.name = lsFlags.Help,
.long = "help",
},
.{
.name = lsFlags.All,
.short = 'a',
.long = "All",
},
.{
.name = lsFlags.Recursive,
.short = 'R',
.long = "Recursive",
},
.{
.name = lsFlags.Alpha,
.short = 'A',
.long = "Alpha",
},
};
// Function for displaying just a filename
fn show_file(path: []const u8) void {
printTabs(TABS);
warn("{s}\n", .{path});
}
// Function to print the tabs utilized in recursive ls
fn printTabs(tabn: usize) void {
var n: usize = tabn;
while (n > 0) {
warn(" ", .{});
n = n - 1;
}
}
// Function to compare two words, regardless of case
// Returning true means first word < second word, and vice versa
pub fn compare_words(context: void, word1: []const u8, word2: []const u8) bool {
var maxlen: usize = 0;
var w: bool = false;
var index: usize = 0;
if (word1.len > word2.len) {
maxlen = word2.len;
} else {
maxlen = word1.len;
w = true;
}
while (maxlen > 0) {
var val1: usize = word1[index];
var val2: usize = word2[index];
if (val1 > 96 and val1 < 123) {
val1 = val1 - 32;
}
if (val2 > 96 and val2 < 123) {
val2 = val2 - 32;
}
if (val1 < val2) {
return true;
}
if (val1 > val2) {
return false;
}
index = index + 1;
maxlen = maxlen - 1;
}
return w; // In case words are equal through end of one, i.e. file and files
}
// Function to sort a list alphabetically, then print it
// Hopefully in future port this to just work with all ArrayLists and not be ls specific
pub fn alpha_ArrayList(oldList_: std.ArrayList(std.fs.Dir.Entry)) !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = &arena.allocator;
var newList = std.ArrayList(std.fs.Dir.Entry).init(allocator);
var oldList = oldList_;
defer newList.deinit();
var nextpos: usize = 0;
var nextword: []const u8 = "";
while (oldList.items.len > 0) {
nextword = oldList.items[0].name;
var word: usize = oldList.items.len - 1;
while (word > 0) {
if (compare_words(.{}, nextword, oldList.items[word].name) == false) {
nextword = oldList.items[word].name;
nextpos = word;
}
word = word - 1;
}
const ret = newList.append(oldList.swapRemove(nextpos));
nextpos = 0;
}
for (newList.items) |entry| {
if (ALL == true or entry.name[0] != '.') {
show_file(entry.name);
if (entry.kind == std.fs.Dir.Entry.Kind.Directory and RECUR) {
TABS = TABS + 1;
const ret = show_directory(entry.name);
TABS = TABS - 1;
}
}
}
return;
}
//Function to open directory and list its entries
fn show_directory(path: []const u8) !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = &arena.allocator;
var dents = std.ArrayList(std.fs.Dir.Entry).init(allocator);
defer dents.deinit();
if (std.fs.cwd().openDir(path, std.fs.Dir.OpenDirOptions{ .access_sub_paths = true, .iterate = true })) |d_opened| {
var dir = d_opened;
var iter = dir.iterate();
while (try iter.next()) |entry| {
try dents.append(entry);
}
if (ALL == true) {
show_file(".");
show_file("..");
}
if (ALPHA == true) {
const ret = alpha_ArrayList(dents);
} else {
for (dents.items) |entry| {
if (ALL == true or entry.name[0] != '.') {
if (entry.kind == std.fs.Dir.Entry.Kind.Directory) {
show_file(entry.name);
if (RECUR) {
TABS = TABS + 1;
const ret = show_directory(entry.name);
TABS = TABS - 1;
}
} else {
show_file(entry.name);
}
}
}
}
std.fs.Dir.close(&dir);
} else |err| {
if (err == error.NotDir) {
std.debug.assert(TABS == 0);
show_file(path);
}
return;
}
}
// Main funtion serving to parse flags and call appropriate funtions
pub fn main(args: [][]u8) anyerror!u8 {
var it = opt.FlagIterator(lsFlags).init(flags[0..], args);
while (it.next_flag() catch {
return 1;
}) |flag| {
switch (flag.name) {
lsFlags.Help => {
warn("Usage: ls FLAGS DIRECTORIES\n", .{});
return 1;
},
lsFlags.All => {
ALL = true;
},
lsFlags.Recursive => {
RECUR = true;
},
lsFlags.Alpha => {
ALPHA = true;
},
}
}
var dirs = std.ArrayList([]u8).init(std.heap.page_allocator);
while (it.next_arg()) |direntry| {
try dirs.append(direntry);
}
if (dirs.items.len > 0) {
for (dirs.items) |arg, i| {
if (dirs.items.len > 1) {
warn("{s}:\n", .{arg});
}
const result = show_directory(arg);
if (dirs.items.len != i + 1) {
warn("\n", .{});
}
}
} else { // If no directory specified, print current directory
const result = show_directory(".");
}
return 0;
} | src/ls.zig |
const std = @import("std");
const zang = @import("zang");
const note_frequencies = @import("zang-12tet");
pub const PhaseModOscillator = struct {
pub const num_outputs = 1;
pub const num_temps = 2;
pub const Params = struct {
sample_rate: f32,
freq: f32,
relative: bool,
// ratio: the carrier oscillator will use whatever frequency you give
// the PhaseModOscillator. the modulator oscillator will multiply the
// frequency by this ratio. for example, a ratio of 0.5 means that the
// modulator oscillator will always play at half the frequency of the
// carrier oscillator
ratio: zang.ConstantOrBuffer,
// multiplier: the modulator oscillator's output is multiplied by this
// before it is fed in to the phase input of the carrier oscillator.
multiplier: zang.ConstantOrBuffer,
};
carrier: zang.SineOsc,
modulator: zang.SineOsc,
pub fn init() PhaseModOscillator {
return .{
.carrier = zang.SineOsc.init(),
.modulator = zang.SineOsc.init(),
};
}
pub fn paint(
self: *PhaseModOscillator,
span: zang.Span,
outputs: [num_outputs][]f32,
temps: [num_temps][]f32,
note_id_changed: bool,
params: Params,
) void {
switch (params.ratio) {
.constant => |ratio| {
if (params.relative) {
zang.set(span, temps[0], params.freq * ratio);
} else {
zang.set(span, temps[0], ratio);
}
},
.buffer => |ratio| {
if (params.relative) {
zang.multiplyScalar(span, temps[0], ratio, params.freq);
} else {
zang.copy(span, temps[0], ratio);
}
},
}
zang.zero(span, temps[1]);
self.modulator.paint(span, .{temps[1]}, .{}, note_id_changed, .{
.sample_rate = params.sample_rate,
.freq = zang.buffer(temps[0]),
.phase = zang.constant(0.0),
});
zang.zero(span, temps[0]);
switch (params.multiplier) {
.constant => |multiplier| zang.multiplyScalar(span, temps[0], temps[1], multiplier),
.buffer => |multiplier| zang.multiply(span, temps[0], temps[1], multiplier),
}
zang.zero(span, temps[1]);
self.carrier.paint(span, .{temps[1]}, .{}, note_id_changed, .{
.sample_rate = params.sample_rate,
.freq = zang.constant(params.freq),
.phase = zang.buffer(temps[0]),
});
zang.addInto(span, outputs[0], temps[1]);
}
};
// PhaseModOscillator packaged with an envelope
pub const PMOscInstrument = struct {
pub const num_outputs = 1;
pub const num_temps = 3;
pub const Params = struct {
sample_rate: f32,
freq: f32,
note_on: bool,
};
release_duration: f32,
osc: PhaseModOscillator,
env: zang.Envelope,
pub fn init(release_duration: f32) PMOscInstrument {
return .{
.release_duration = release_duration,
.osc = PhaseModOscillator.init(),
.env = zang.Envelope.init(),
};
}
pub fn paint(
self: *PMOscInstrument,
span: zang.Span,
outputs: [num_outputs][]f32,
temps: [num_temps][]f32,
note_id_changed: bool,
params: Params,
) void {
zang.zero(span, temps[0]);
self.osc.paint(span, .{temps[0]}, .{ temps[1], temps[2] }, note_id_changed, .{
.sample_rate = params.sample_rate,
.freq = params.freq,
.relative = true,
.ratio = zang.constant(1.0),
.multiplier = zang.constant(1.0),
});
zang.zero(span, temps[1]);
self.env.paint(span, .{temps[1]}, .{}, note_id_changed, .{
.sample_rate = params.sample_rate,
.attack = .{ .cubed = 0.025 },
.decay = .{ .cubed = 0.1 },
.release = .{ .cubed = self.release_duration },
.sustain_volume = 0.5,
.note_on = params.note_on,
});
zang.multiply(span, outputs[0], temps[0], temps[1]);
}
};
pub const FilteredSawtoothInstrument = struct {
pub const num_outputs = 1;
pub const num_temps = 3;
pub const Params = struct {
sample_rate: f32,
freq: zang.ConstantOrBuffer,
note_on: bool,
};
osc: zang.TriSawOsc,
env: zang.Envelope,
flt: zang.Filter,
pub fn init() FilteredSawtoothInstrument {
return .{
.osc = zang.TriSawOsc.init(),
.env = zang.Envelope.init(),
.flt = zang.Filter.init(),
};
}
pub fn paint(
self: *FilteredSawtoothInstrument,
span: zang.Span,
outputs: [num_outputs][]f32,
temps: [num_temps][]f32,
note_id_changed: bool,
params: Params,
) void {
zang.zero(span, temps[0]);
self.osc.paint(span, .{temps[0]}, .{}, note_id_changed, .{
.sample_rate = params.sample_rate,
.freq = params.freq,
.color = 0.0,
});
zang.multiplyWithScalar(span, temps[0], 1.5); // boost sawtooth volume
zang.zero(span, temps[1]);
self.env.paint(span, .{temps[1]}, .{}, note_id_changed, .{
.sample_rate = params.sample_rate,
.attack = .{ .cubed = 0.025 },
.decay = .{ .cubed = 0.1 },
.release = .{ .cubed = 1.0 },
.sustain_volume = 0.5,
.note_on = params.note_on,
});
zang.zero(span, temps[2]);
zang.multiply(span, temps[2], temps[0], temps[1]);
self.flt.paint(span, .{outputs[0]}, .{}, note_id_changed, .{
.input = temps[2],
.type = .low_pass,
.cutoff = zang.constant(zang.cutoffFromFrequency(
440.0 * note_frequencies.c5,
params.sample_rate,
)),
.res = 0.7,
});
}
};
pub const NiceInstrument = struct {
pub const num_outputs = 1;
pub const num_temps = 2;
pub const Params = struct {
sample_rate: f32,
freq: f32,
note_on: bool,
};
color: f32,
osc: zang.PulseOsc,
flt: zang.Filter,
env: zang.Envelope,
pub fn init(color: f32) NiceInstrument {
return .{
.color = color,
.osc = zang.PulseOsc.init(),
.flt = zang.Filter.init(),
.env = zang.Envelope.init(),
};
}
pub fn paint(
self: *NiceInstrument,
span: zang.Span,
outputs: [num_outputs][]f32,
temps: [num_temps][]f32,
note_id_changed: bool,
params: Params,
) void {
zang.zero(span, temps[0]);
self.osc.paint(span, .{temps[0]}, .{}, note_id_changed, .{
.sample_rate = params.sample_rate,
.freq = zang.constant(params.freq),
.color = self.color,
});
zang.multiplyWithScalar(span, temps[0], 0.5);
zang.zero(span, temps[1]);
self.flt.paint(span, .{temps[1]}, .{}, note_id_changed, .{
.input = temps[0],
.type = .low_pass,
.cutoff = zang.constant(zang.cutoffFromFrequency(
params.freq * 8.0,
params.sample_rate,
)),
.res = 0.7,
});
zang.zero(span, temps[0]);
self.env.paint(span, .{temps[0]}, .{}, note_id_changed, .{
.sample_rate = params.sample_rate,
.attack = .{ .cubed = 0.01 },
.decay = .{ .cubed = 0.1 },
.release = .{ .cubed = 0.5 },
.sustain_volume = 0.8,
.note_on = params.note_on,
});
zang.multiply(span, outputs[0], temps[0], temps[1]);
}
};
pub const HardSquareInstrument = struct {
pub const num_outputs = 1;
pub const num_temps = 2;
pub const Params = struct {
sample_rate: f32,
freq: f32,
note_on: bool,
};
osc: zang.PulseOsc,
gate: zang.Gate,
pub fn init() HardSquareInstrument {
return .{
.osc = zang.PulseOsc.init(),
.gate = zang.Gate.init(),
};
}
pub fn paint(
self: *HardSquareInstrument,
span: zang.Span,
outputs: [num_outputs][]f32,
temps: [num_temps][]f32,
note_id_changed: bool,
params: Params,
) void {
zang.zero(span, temps[0]);
self.osc.paint(span, .{temps[0]}, .{}, note_id_changed, .{
.sample_rate = params.sample_rate,
.freq = zang.constant(params.freq),
.color = 0.5,
});
zang.zero(span, temps[1]);
self.gate.paint(span, .{temps[1]}, .{}, note_id_changed, .{
.note_on = params.note_on,
});
zang.multiply(span, outputs[0], temps[0], temps[1]);
}
};
pub const SquareWithEnvelope = struct {
pub const num_outputs = 1;
pub const num_temps = 2;
pub const Params = struct {
sample_rate: f32,
freq: f32,
note_on: bool,
};
weird: bool,
osc: zang.PulseOsc,
env: zang.Envelope,
pub fn init(weird: bool) SquareWithEnvelope {
return .{
.weird = weird,
.osc = zang.PulseOsc.init(),
.env = zang.Envelope.init(),
};
}
pub fn paint(
self: *SquareWithEnvelope,
span: zang.Span,
outputs: [num_outputs][]f32,
temps: [num_temps][]f32,
note_id_changed: bool,
params: Params,
) void {
zang.zero(span, temps[0]);
self.osc.paint(span, .{temps[0]}, .{}, .{
.sample_rate = params.sample_rate,
.freq = zang.constant(params.freq),
.color = if (self.weird) 0.3 else 0.5,
});
zang.zero(span, temps[1]);
self.env.paint(span, .{temps[1]}, .{}, note_id_changed, .{
.sample_rate = params.sample_rate,
.attack_duration = 0.01,
.decay_duration = 0.1,
.sustain_volume = 0.5,
.release_duration = 0.5,
.note_on = params.note_on,
});
zang.multiply(span, outputs[0], temps[0], temps[1]);
}
};
// this is a module that simply delays the input signal. there's no dry output
// and no feedback (echoes)
pub fn SimpleDelay(comptime DELAY_SAMPLES: usize) type {
return struct {
pub const num_outputs = 1;
pub const num_temps = 0;
pub const Params = struct {
input: []const f32,
};
delay: zang.Delay(DELAY_SAMPLES),
pub fn init() @This() {
return .{
.delay = zang.Delay(DELAY_SAMPLES).init(),
};
}
pub fn reset(self: *@This()) void {
self.delay.reset();
}
pub fn paint(
self: *@This(),
span: zang.Span,
outputs: [num_outputs][]f32,
temps: [num_temps][]f32,
note_id_changed: bool,
params: Params,
) void {
var start = span.start;
const end = span.end;
while (start < end) {
const samples_read = self.delay.readDelayBuffer(outputs[0][start..end]);
self.delay.writeDelayBuffer(
params.input[start .. start + samples_read],
);
start += samples_read;
}
}
};
}
// this is a bit unusual, it filters the input and outputs it immediately. it's
// meant to be used after SimpleDelay (which provides the initial delay)
pub fn FilteredEchoes(comptime DELAY_SAMPLES: usize) type {
return struct {
pub const num_outputs = 1;
pub const num_temps = 2;
pub const Params = struct {
input: []const f32,
feedback_volume: f32,
cutoff: f32,
};
delay: zang.Delay(DELAY_SAMPLES),
filter: zang.Filter,
pub fn init() @This() {
return .{
.delay = zang.Delay(DELAY_SAMPLES).init(),
.filter = zang.Filter.init(),
};
}
pub fn reset(self: *@This()) void {
self.delay.reset();
}
pub fn paint(
self: *@This(),
span: zang.Span,
outputs: [num_outputs][]f32,
temps: [num_temps][]f32,
note_id_changed: bool,
params: Params,
) void {
const output = outputs[0];
const input = params.input;
const temp0 = temps[0];
const temp1 = temps[1];
var start = span.start;
const end = span.end;
while (start < end) {
// get delay buffer (this is the feedback)
zang.zero(zang.Span.init(start, end), temp0);
const samples_read = self.delay.readDelayBuffer(temp0[start..end]);
const span1 = zang.Span.init(start, start + samples_read);
// reduce its volume
zang.multiplyWithScalar(span1, temp0, params.feedback_volume);
// add input
zang.addInto(span1, temp0, input);
// filter it
zang.zero(span1, temp1);
self.filter.paint(span1, .{temp1}, .{}, note_id_changed, .{
.input = temp0,
.type = .low_pass,
.cutoff = zang.constant(params.cutoff),
.res = 0.0,
});
// output it
zang.addInto(span1, output, temp1);
// also send what we have to the delay module (which doesn't
// output anything)
self.delay.writeDelayBuffer(temp1[span1.start..span1.end]);
start += samples_read;
}
}
};
}
pub fn StereoEchoes(comptime MAIN_DELAY: usize) type {
const HALF_DELAY = MAIN_DELAY / 2;
return struct {
pub const num_outputs = 2;
pub const num_temps = 4;
pub const Params = struct {
input: []const f32,
feedback_volume: f32,
cutoff: f32,
};
delay0: SimpleDelay(HALF_DELAY),
delay1: SimpleDelay(HALF_DELAY),
echoes: FilteredEchoes(MAIN_DELAY),
pub fn init() @This() {
return .{
.delay0 = SimpleDelay(HALF_DELAY).init(),
.delay1 = SimpleDelay(HALF_DELAY).init(),
.echoes = FilteredEchoes(MAIN_DELAY).init(),
};
}
pub fn reset(self: *@This()) void {
self.delay0.reset();
self.delay1.reset();
self.echoes.reset();
}
pub fn paint(
self: *@This(),
span: zang.Span,
outputs: [num_outputs][]f32,
temps: [num_temps][]f32,
note_id_changed: bool,
params: Params,
) void {
// output dry signal to center channel
zang.addInto(span, outputs[0], params.input);
zang.addInto(span, outputs[1], params.input);
// initial half delay before first echo on the left channel
zang.zero(span, temps[0]);
self.delay0.paint(span, .{temps[0]}, .{}, note_id_changed, .{
.input = params.input,
});
// filtered echoes to the left
zang.zero(span, temps[1]);
self.echoes.paint(span, .{temps[1]}, .{ temps[2], temps[3] }, note_id_changed, .{
.input = temps[0],
.feedback_volume = params.feedback_volume,
.cutoff = params.cutoff,
});
// use another delay to mirror the left echoes to the right side
zang.addInto(span, outputs[0], temps[1]);
self.delay1.paint(span, .{outputs[1]}, .{}, note_id_changed, .{
.input = temps[1],
});
}
};
} | examples/modules.zig |
const fmath = @import("index.zig");
pub fn log10(x: var) -> @typeOf(x) {
const T = @typeOf(x);
switch (T) {
f32 => @inlineCall(log10f, x),
f64 => @inlineCall(log10d, x),
else => @compileError("log10 not implemented for " ++ @typeName(T)),
}
}
fn log10f(x_: f32) -> 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 -1 / (x * x);
}
// log(-#) = nan
if (ix >> 31 != 0) {
return (x - x) / 0.0
}
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 += 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 = f32(k);
dk * log10_2lo + (lo + hi) * ivln10lo + lo * ivln10hi + hi * ivln10hi + dk * log10_2hi
}
fn log10d(x_: f64) -> 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 = u32(ix >> 32);
var k: i32 = 0;
if (hx < 0x00100000 or hx >> 31 != 0) {
// log(+-0) = -inf
if (ix << 1 == 0) {
return -1 / (x * x);
}
// log(-#) = nan
if (hx >> 31 != 0) {
return (x - x) / 0.0;
}
// subnormal, scale x
k -= 54;
x *= 0x1.0p54;
hx = 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 += i32(hx >> 20) - 0x3FF;
hx = (hx & 0x000FFFFF) + 0x3FE6A09E;
ix = (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 &= @maxValue(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 = 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;
val_lo + val_hi
}
test "log10" {
fmath.assert(log10(f32(0.2)) == log10f(0.2));
fmath.assert(log10(f64(0.2)) == log10d(0.2));
}
test "log10f" {
const epsilon = 0.000001;
fmath.assert(fmath.approxEq(f32, log10f(0.2), -0.698970, epsilon));
fmath.assert(fmath.approxEq(f32, log10f(0.8923), -0.049489, epsilon));
fmath.assert(fmath.approxEq(f32, log10f(1.5), 0.176091, epsilon));
fmath.assert(fmath.approxEq(f32, log10f(37.45), 1.573452, epsilon));
fmath.assert(fmath.approxEq(f32, log10f(89.123), 1.94999, epsilon));
fmath.assert(fmath.approxEq(f32, log10f(123123.234375), 5.09034, epsilon));
}
test "log10d" {
const epsilon = 0.000001;
fmath.assert(fmath.approxEq(f64, log10d(0.2), -0.698970, epsilon));
fmath.assert(fmath.approxEq(f64, log10d(0.8923), -0.049489, epsilon));
fmath.assert(fmath.approxEq(f64, log10d(1.5), 0.176091, epsilon));
fmath.assert(fmath.approxEq(f64, log10d(37.45), 1.573452, epsilon));
fmath.assert(fmath.approxEq(f64, log10d(89.123), 1.94999, epsilon));
fmath.assert(fmath.approxEq(f64, log10d(123123.234375), 5.09034, epsilon));
} | src/log10.zig |
const std = @import("std");
const mem = std.mem;
const builtin = @import("builtin");
pub const c = @import("./c.zig");
pub usingnamespace @import("./monitor.zig");
pub usingnamespace @import("./window.zig");
/// Video mode type.
pub const VideoMode = c.GLFWvidmode;
/// Gamma ramp type.
pub const GammaRamp = struct {
red: []c_ushort,
green: []c_ushort,
blue: []c_ushort,
size: usize,
};
/// Image type.
pub const Image = c.GLFWimage;
pub const Size = struct {
width: i32,
height: i32,
};
pub const Position = struct {
x: i32,
y: i32,
};
pub const Bounds = struct {
top: i32,
left: i32,
bottom: i32,
right: i32,
};
pub const Scale = struct {
x: f32,
y: f32,
};
pub const Error = error{
/// This occurs if a GLFW function was called that must not be
/// called unless the library is initialized.
NotInitialized,
/// This occurs if a GLFW function was called that needs and
/// operates on the current OpenGL or OpenGL ES context but no
/// context is current on the calling thread. One such function is
/// glfwSwapInterval.
NoCurrentContext,
/// One of the arguments to the function was an invalid value, for
/// example requesting a non-existent OpenGL or OpenGL ES version
/// like 2.7.
InvalidValue,
/// A memory allocation failed.
OutOfMemory,
/// GLFW could not find support for the requested API on the system.
ApiUnavailable,
/// The requested OpenGL or OpenGL ES version (including any
/// requested context or framebuffer hints) is not available on this
/// machine.
VersionUnavailable,
/// A platform specific error occured that odes not match any of the more specific categories.
PlatformError,
/// If emitted during window creation, the requested pixel format is
/// not supported.
///
/// If emitted when querying the clipboard, the contents of the
/// clipboard could not be converted to the requested format.
FormatUnavailable,
/// A window that does not have an OpenGL or OpenGL ES context was
/// passed to a function that requires it to have one.
NoWindowContext,
};
/// This function returns and clears the error code of the last error
/// that occurred on the calling thread.
pub fn getError() Error!void {
return switch (c.glfwGetError(null)) {
c.GLFW_NO_ERROR => return,
c.GLFW_NOT_INITIALIZED => return Error.NotInitialized,
c.GLFW_NO_CURRENT_CONTEXT => return Error.NoCurrentContext,
c.GLFW_INVALID_VALUE => return Error.InvalidValue,
c.GLFW_OUT_OF_MEMORY => return Error.OutOfMemory,
c.GLFW_API_UNAVAILABLE => return Error.ApiUnavailable,
c.GLFW_VERSION_UNAVAILABLE => return Error.VersionUnavailable,
c.GLFW_PLATFORM_ERROR => return Error.PlatformError,
c.GLFW_FORMAT_UNAVAILABLE => return Error.FormatUnavailable,
c.GLFW_NO_WINDOW_CONTEXT => return Error.NoWindowContext,
else => |code| std.debug.panic("unknown code: {}\n", .{ code }),
};
}
/// This function initializes the GLFW library. Before most GLFW
/// functions can be used, GLFW must be initialized, and before an
/// application terminates GLFW should be terminated in order to free
/// any resources allocated during or after initialization.
///
/// If this function fails, it calls `deinit` before returning. If it
/// succeeds, you should call `deinit` before the application exits.
///
/// Additional calls to this function after successful initialization
/// but before termination will return GLFW_TRUE immediately.
pub fn init() !void {
if (c.glfwInit() != c.GLFW_TRUE) {
getError() catch |err| switch (err) {
error.PlatformError => return err,
else => unreachable,
};
}
_ = c.glfwSetErrorCallback(glfwErrorCallback);
_ = c.glfwSetMonitorCallback(glfwMonitorCallback);
}
/// This function destroys all remaining windows and cursors, restores
/// any modified gamma ramps and frees any other allocated resources.
/// Once this function is called, you must again call `init`
/// successfully before you will be able to use most GLFW functions.
///
/// If GLFW has been successfully initialized, this function should be
/// called before the application exits. If initialization fails, there
/// is no need to call this function, as it is called by `init` before
/// it returns failure.
pub fn deinit() void {
c.glfwTerminate();
}
pub const HintName = enum(i32) {
/// Specifies whether to also expose joystick hats as buttons, for
/// compatibility with earlier versions of GLFW that did not have
/// `getJoystickHats`.
JoystickHatButtons = c.GLFW_JOYSTICK_HAT_BUTTONS,
/// Specifies whether to set the current directory to the
/// application to the Contents/Resources subdirectory of the
/// application's bundle, if present.
CocoaChdirResources = c.GLFW_COCOA_CHDIR_RESOURCES,
/// Specifies whether to create a basic menu bar, either from a nib
/// or manually, when the first window is created, which is when
/// AppKit is initialized.
CocoaMenubar = c.GLFW_COCOA_MENUBAR,
};
pub const Hint = union(HintName) {
JoystickHatButtons: bool,
CocoaChdirResources: bool,
CocoaMenubar: bool,
};
/// This function sets hints for the next initialization of GLFW.
///
/// The values you set hints to are never reset by GLFW, but they only
/// take effect during initialization. Once GLFW has been initialized,
/// any values you set will be ignored until the library is terminated
/// and initialized again.
/// Some hints are platform specific. These may be set on any platform
/// but they will only affect their specific platform. Other platforms
/// will ignore them. Setting these hints requires no platform specific
/// headers or functions.
pub fn hint(hint: Hint) void {
c.glfwInitHint(@enumToInt(hint), switch (hint) {
.JoystickHatButtons => |value| toGLFWBool(value),
.CocoaChdirResources => |value| toGLFWBool(value),
.CocoaMenubar => |value| toGLFWBool(value),
});
}
fn toGLFWBool(value: bool) i32 {
return if (value) c.GLFW_TRUE else c.GLFW_FALSE;
}
/// This function retrieves the major, minor and revision numbers of the
/// GLFW library. It is intended for when you are using GLFW as a shared
/// library and want to ensure that you are using the minimum required
/// version.
pub fn getVersion() builtin.Version {
var major: i32 = 0;
var minor: i32 = 0;
var patch: i32 = 0;
c.glfwGetVersion(&major, &minor, &patch);
return builtin.Version{ .major = @intCast(u32, major), .minor = @intCast(u32, minor), .patch = @intCast(u32, patch) };
}
/// This function returns the compile-time generated version string of
/// the GLFW library binary. It describes the version, platform,
/// compiler and any platform-specific compile-time options. It should
/// not be confused with the OpenGL or OpenGL ES version string, queried
/// with `glGetString`.
///
/// Do not use the version string to parse the GLFW library version. The
/// `getVersion` function provides the version of the running library
/// binary in numerical format.
pub fn getVersionString() [:0]const u8 {
const string = c.glfwGetVersionString();
return mem.spanZ(@as([*:0]const u8, string));
}
/// This is the function pointer type for error callbacks. An error
/// callback function has the following signature:
pub const ErrorCallback = fn(err: Error, description: [:0]const u8) void;
var errorCallback: ?ErrorCallback = null;
fn glfwErrorCallback(code: c_int, description: [*c]const u8) callconv(.C) void {
if (errorCallback) |callback| {
var err = switch (c.glfwGetError(null)) {
c.GLFW_NO_ERROR => return,
c.GLFW_NOT_INITIALIZED => Error.NotInitialized,
c.GLFW_NO_CURRENT_CONTEXT => Error.NoCurrentContext,
c.GLFW_INVALID_VALUE => Error.InvalidValue,
c.GLFW_OUT_OF_MEMORY => Error.OutOfMemory,
c.GLFW_API_UNAVAILABLE => Error.ApiUnavailable,
c.GLFW_VERSION_UNAVAILABLE => Error.VersionUnavailable,
c.GLFW_PLATFORM_ERROR => Error.PlatformError,
c.GLFW_FORMAT_UNAVAILABLE => Error.FormatUnavailable,
c.GLFW_NO_WINDOW_CONTEXT => Error.NoWindowContext,
else => std.debug.panic("unknown code: {}\n", .{ code }),
};
callback(err, mem.spanZ(@as([*:0]const u8, description)));
}
}
/// This function sets the error callback, which is called with an error
/// code and a human-readable description each time a GLFW error occurs.
///
/// The error code is set before the callback is called. Calling
/// `getError` from the error callback will return the same value as the
/// error code argument.
///
/// The error callback is called on the thread where the error occurred.
/// If you are using GLFW from multiple threads, your error callback
/// needs to be written accordingly.
///
/// Because the description string may have been generated specifically
/// for that error, it is not guaranteed to be valid after the callback
/// has returned. If you wish to use it after the callback returns, you
/// need to make a copy.
///
/// Once set, the error callback remains set even after the library has
/// been terminated.
pub fn setErrorCallback(newErrorCallback: ?ErrorCallback) ?ErrorCallback {
var oldErrorCallback = errorCallback;
errorCallback = newErrorCallback;
return oldErrorCallback;
}
pub const MonitorCallback = fn(monitor: Monitor, event: i32) void;
var monitorCallback: ?MonitorCallback = null;
fn glfwMonitorCallback(handle: ?*c.GLFWmonitor, event: i32) callconv(.C) void {
if (monitorCallback) |callback| {
callback(.{ .handle = handle.?, }, event);
}
}
/// This function sets the monitor configuration callback, or removes
/// the currently set callback. This is called when a monitor is
/// connected to or disconnected from the system.
pub fn setMonitorCallback(newMonitorCallback: ?MonitorCallback) ?MonitorCallback {
var oldMonitorCallback = monitorCallback;
monitorCallback = newMonitorCallback;
return oldMonitorCallback;
}
/// This function processes only those events that are already in the event
/// queue and then returns immediately. Processing events will cause the window
/// and input callbacks associated with those events to be called.
///
/// On some platforms, a window move, resize or menu operation will cause event
/// processing to block. This is due to how event processing is designed on
/// those platforms. You can use the window refresh callback to redraw the
/// contents of your window when necessary during such operations.
///
/// Do not assume that callbacks you set will only be called in response to
/// event processing functions like this one. While it is necessary to poll for
/// events, window systems that require GLFW to register callbacks of its own
/// can pass events to GLFW in response to many window system function calls.
/// GLFW will pass those events on to the application callbacks before
/// returning.
///
/// Event processing is not required for joystick input to work.
pub fn pollEvents() !void {
c.glfwPollEvents();
getError() catch |err| switch (err) {
Error.NotInitialized,
Error.PlatformError => return err,
else => unreachable,
};
}
/// This function puts the calling thread to sleep until at least one event is
/// available in the event queue. Once one or more events are available, it
/// behaves exactly like `pollEvents`, i.e. the events in the queue are
/// processed and the function then returns immediately. Processing events will
/// cause the window and input callbacks associated with those events to be
/// called.
///
/// Since not all events are associated with callbacks, this function may return
/// without a callback having been called even if you are monitoring all
/// callbacks.
///
/// On some platforms, a window move, resize or menu operation will cause event
/// processing to block. This is due to how event processing is designed on
/// those platforms. You can use the window refresh callback to redraw the
/// contents of your window when necessary during such operations.
///
/// Do not assume that callbacks you set will only be called in response to
/// event processing functions like this one. While it is necessary to poll for
/// events, window systems that require GLFW to register callbacks of its own
/// can pass events to GLFW in response to many window system function calls.
/// GLFW will pass those events on to the application callbacks before
/// returning.
///
/// Event processing is not required for joystick input to work.
pub fn waitEvents() !void {
c.glfwWaitEvents();
getError() catch |err| switch (err) {
Error.NotInitialized,
Error.PlatformError => return err,
else => unreachable,
};
}
/// This function puts the calling thread to sleep until at least one event is
/// available in the event queue, or until the specified timeout is reached. If
/// one or more events are available, it behaves exactly like `pollEvents`,
// i.e. the events in the queue are processed and the function then returns
/// immediately. Processing events will cause the window and input callbacks
/// associated with those events to be called.
///
/// The timeout value must be a positive finite number.
///
/// Since not all events are associated with callbacks, this function may return
/// without a callback having been called even if you are monitoring all
/// callbacks.
///
/// On some platforms, a window move, resize or menu operation will cause event
/// processing to block. This is due to how event processing is designed on
/// those platforms. You can use the window refresh callback to redraw the
/// contents of your window when necessary during such operations.
///
/// Do not assume that callbacks you set will only be called in response to
/// event processing functions like this one. While it is necessary to poll for
/// events, window systems that require GLFW to register callbacks of its own
/// can pass events to GLFW in response to many window system function calls.
/// GLFW will pass those events on to the application callbacks before
/// returning.
///
/// Event processing is not required for joystick input to work.
pub fn waitEventsTimeout(timeout: f64) !void {
c.glfwWaitEventsTimeout(timeout);
getError() catch |err| switch (err) {
Error.NotInitialized,
Error.PlatformError => return err,
else => unreachable,
};
}
/// This function posts an empty event from the current thread to the event
/// queue, causing `waitEvents` or `waitEventsTimeout` to return.
pub fn postEmptyEvent() !void {
c.glfwPostEmptyEvent();
getError() catch |err| switch (err) {
Error.NotInitialized,
Error.PlatformError => return err,
else => unreachable,
};
}
pub fn getTime() f64 {
return c.glfwGetTime();
} | src/main.zig |
const std = @import("std");
const common = @import("../utils/common.zig");
const FV = common.FV;
pub const HMGET = struct {
key: []const u8,
fields: []const []const u8,
/// Instantiates a new HMGET command.
pub fn init(key: []const u8, fields: []const []const u8) HMGET {
return .{ .key = key, .fields = fields };
}
/// Validates if the command is syntactically correct.
pub fn validate(self: HMGET) !void {
if (self.key.len == 0) return error.EmptyKeyName;
if (self.fields.len == 0) return error.FieldsArrayIsEmpty;
// TODO: how the hell do I check for dups without an allocator?
var i: usize = 0;
while (i < self.fields.len) : (i += 1) {
if (self.fields[i].len == 0) return error.EmptyFieldName;
}
}
// This reassignment is necessary to avoid having two definitions of
// RedisCommand in the same scope (it causes a shadowing error).
pub const forStruct = _forStruct;
pub const RedisCommand = struct {
pub fn serialize(self: HMGET, comptime rootSerializer: type, msg: anytype) !void {
return rootSerializer.serializeCommand(msg, .{ "HMGET", self.key, self.fields });
}
};
};
fn _forStruct(comptime T: type) type {
// TODO: there is some duplicated code with xread. Values should be a dedicated generic type.
if (@typeInfo(T) != .Struct) @compileError("Only Struct types allowed.");
return struct {
key: []const u8,
const Self = @This();
pub fn init(key: []const u8) Self {
return .{ .key = key };
}
/// Validates if the command is syntactically correct.
pub fn validate(self: Self) !void {
if (self.key.len == 0) return error.EmptyKeyName;
}
pub const RedisCommand = struct {
pub fn serialize(self: Self, comptime rootSerializer: type, msg: anytype) !void {
return rootSerializer.serializeCommand(msg, .{
"HMGET",
self.key,
// Dirty trick to control struct serialization :3
self,
});
}
};
// We are marking ouserlves also as an argument to manage struct serialization.
pub const RedisArguments = struct {
pub fn count(self: Self) usize {
return comptime std.meta.fields(T).len;
}
pub fn serialize(self: Self, comptime rootSerializer: type, msg: anytype) !void {
inline for (std.meta.fields(T)) |field| {
try rootSerializer.serializeArgument(msg, []const u8, field.name);
}
}
};
};
}
test "basic usage" {
const cmd = HMGET.init("mykey", &[_][]const u8{ "field1", "field2" });
try cmd.validate();
const ExampleStruct = struct {
banana: usize,
id: []const u8,
};
const cmd1 = HMGET.forStruct(ExampleStruct).init("mykey");
try cmd1.validate();
}
test "serializer" {
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();
try serializer.serializeCommand(
testMsg.outStream(),
HMGET.init("k1", &[_][]const u8{"f1"}),
);
try serializer.serializeCommand(
correctMsg.outStream(),
.{ "HMGET", "k1", "f1" },
);
// std.debug.warn("{}\n\n\n{}\n", .{ correctMsg.getWritten(), testMsg.getWritten() });
std.testing.expectEqualSlices(u8, correctMsg.getWritten(), testMsg.getWritten());
}
{
correctMsg.reset();
testMsg.reset();
const MyStruct = struct {
field1: []const u8,
field2: u8,
field3: usize,
};
const MyHMGET = HMGET.forStruct(MyStruct);
try serializer.serializeCommand(
testMsg.outStream(),
MyHMGET.init("k1"),
);
try serializer.serializeCommand(
correctMsg.outStream(),
.{ "HMGET", "k1", "field1", "field2", "field3" },
);
std.testing.expectEqualSlices(u8, correctMsg.getWritten(), testMsg.getWritten());
}
}
} | src/commands/hashes/hmget.zig |
const std = @import("std");
const c = @import("internal/c.zig");
const internal = @import("internal/internal.zig");
const log = std.log.scoped(.git);
const git = @import("git.zig");
/// The diff object that contains all individual file deltas.
/// A `diff` represents the cumulative list of differences between two snapshots of a repository (possibly filtered by a set of
/// file name patterns).
///
/// Calculating diffs is generally done in two phases: building a list of diffs then traversing it. This makes is easier to share
/// logic across the various types of diffs (tree vs tree, workdir vs index, etc.), and also allows you to insert optional diff
/// post-processing phases, such as rename detection, in between the steps. When you are done with a diff object, it must be
/// freed.
pub const Diff = opaque {
pub fn deinit(self: *Diff) void {
log.debug("Diff.deinit called", .{});
c.git_diff_free(@ptrCast(*c.git_diff, self));
log.debug("diff freed successfully", .{});
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// Structure describing a hunk of a diff.
///
/// A `hunk` is a span of modified lines in a delta along with some stable surrounding context. You can configure the amount of
/// context and other properties of how hunks are generated. Each hunk also comes with a header that described where it starts and
/// ends in both the old and new versions in the delta.
pub const DiffHunk = extern struct {
pub const HEADER_SIZE: usize = c.GIT_DIFF_HUNK_HEADER_SIZE;
/// Starting line number in old_file
old_start: c_int,
/// Number of lines in old_file
old_lines: c_int,
/// Starting line number in new_file
new_start: c_int,
/// Number of lines in new_file
new_lines: c_int,
/// Number of bytes in header text
header_len: usize,
/// Header text, NUL-byte terminated
/// Use `header`
z_header: [HEADER_SIZE]u8,
pub fn header(self: DiffHunk) [:0]const u8 {
// for some reason this gives `expected type '[:0]const u8', found '[]const u8'`
// return std.mem.sliceTo(&self.z_header, 0);
return std.mem.sliceTo(@ptrCast([*:0]const u8, &self.z_header), 0);
}
test {
try std.testing.expectEqual(@sizeOf(c.git_diff_hunk), @sizeOf(DiffHunk));
try std.testing.expectEqual(@bitSizeOf(c.git_diff_hunk), @bitSizeOf(DiffHunk));
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// Description of changes to one entry.
///
/// A `delta` is a file pair with an old and new revision. The old version may be absent if the file was just created and the new
/// version may be absent if the file was deleted. A diff is mostly just a list of deltas.
///
/// When iterating over a diff, this will be passed to most callbacks and you can use the contents to understand exactly what has
/// changed.
///
/// The `old_file` represents the "from" side of the diff and the `new_file` represents to "to" side of the diff. What those
/// means depend on the function that was used to generate the diff. You can also use the `GIT_DIFF_REVERSE` flag to flip it
/// around.
///
/// Although the two sides of the delta are named `old_file` and `new_file`, they actually may correspond to entries that
/// represent a file, a symbolic link, a submodule commit id, or even a tree (if you are tracking type changes or
/// ignored/untracked directories).
///
/// Under some circumstances, in the name of efficiency, not all fields will be filled in, but we generally try to fill in as much
/// as possible. One example is that the `flags` field may not have either the `BINARY` or the `NOT_BINARY` flag set to avoid
/// examining file contents if you do not pass in hunk and/or line callbacks to the diff foreach iteration function. It will just
/// use the git attributes for those files.
///
/// The similarity score is zero unless you call `git_diff_find_similar()` which does a similarity analysis of files in the diff.
/// Use that function to do rename and copy detection, and to split heavily modified files in add/delete pairs. After that call,
/// deltas with a status of GIT_DELTA_RENAMED or GIT_DELTA_COPIED will have a similarity score between 0 and 100 indicating how
/// similar the old and new sides are.
///
/// If you ask `git_diff_find_similar` to find heavily modified files to break, but to not *actually* break the records, then
/// GIT_DELTA_MODIFIED records may have a non-zero similarity score if the self-similarity is below the split threshold. To
/// display this value like core Git, invert the score (a la `printf("M%03d", 100 - delta->similarity)`).
pub const DiffDelta = extern struct {
status: DeltaType,
flags: DiffFlags,
/// for RENAMED and COPIED, value 0-100
similarity: u16,
number_of_files: u16,
old_file: DiffFile,
new_file: DiffFile,
/// What type of change is described by a git_diff_delta?
///
/// `GIT_DELTA_RENAMED` and `GIT_DELTA_COPIED` will only show up if you run `git_diff_find_similar()` on the diff object.
///
/// `GIT_DELTA_TYPECHANGE` only shows up given `GIT_DIFF_INCLUDE_TYPECHANGE` in the option flags (otherwise type changes will
/// be split into ADDED / DELETED pairs).
pub const DeltaType = enum(c_uint) {
/// no changes
UNMODIFIED,
/// entry does not exist in old version
ADDED,
/// entry does not exist in new version
DELETED,
/// entry content changed between old and new
MODIFIED,
/// entry was renamed between old and new
RENAMED,
/// entry was copied from another old entry
COPIED,
/// entry is ignored item in workdir
IGNORED,
/// entry is untracked item in workdir
UNTRACKED,
/// type of entry changed between old and new
TYPECHANGE,
/// entry is unreadable
UNREADABLE,
/// entry in the index is conflicted
CONFLICTED,
};
test {
try std.testing.expectEqual(@sizeOf(c.git_diff_delta), @sizeOf(DiffDelta));
try std.testing.expectEqual(@bitSizeOf(c.git_diff_delta), @bitSizeOf(DiffDelta));
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// Flags for the delta object and the file objects on each side.
///
/// These flags are used for both the `flags` value of the `git_diff_delta` and the flags for the `git_diff_file` objects
/// representing the old and new sides of the delta. Values outside of this public range should be considered reserved
/// for internal or future use.
pub const DiffFlags = packed struct {
/// file(s) treated as binary data
BINARY: bool = false,
/// file(s) treated as text data
NOT_BINARY: bool = false,
/// `id` value is known correct
VALID_ID: bool = false,
/// file exists at this side of the delta
EXISTS: bool = false,
z_padding1: u12 = 0,
z_padding2: u16 = 0,
pub fn format(
value: DiffFlags,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = fmt;
return internal.formatWithoutFields(
value,
options,
writer,
&.{ "z_padding1", "z_padding2" },
);
}
test {
try std.testing.expectEqual(@sizeOf(c_uint), @sizeOf(DiffFlags));
try std.testing.expectEqual(@bitSizeOf(c_uint), @bitSizeOf(DiffFlags));
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// Description of one side of a delta.
///
/// Although this is called a "file", it could represent a file, a symbolic link, a submodule commit id, or even a tree
/// (although that only if you are tracking type changes or ignored/untracked directories).
pub const DiffFile = extern struct {
/// The `git_oid` of the item. If the entry represents an absent side of a diff (e.g. the `old_file` of a
/// `GIT_DELTA_ADDED` delta), then the oid will be zeroes.
id: git.Oid,
/// Path to the entry relative to the working directory of the repository.
path: [*:0]const u8,
/// The size of the entry in bytes.
size: u64,
flags: DiffFlags,
/// Roughly, the stat() `st_mode` value for the item.
mode: git.FileMode,
/// Represents the known length of the `id` field, when converted to a hex string. It is generally `GIT_OID_HEXSZ`,
/// unless this delta was created from reading a patch file, in which case it may be abbreviated to something reasonable,
/// like 7 characters.
id_abbrev: u16,
test {
try std.testing.expectEqual(@sizeOf(c.git_diff_file), @sizeOf(DiffFile));
try std.testing.expectEqual(@bitSizeOf(c.git_diff_file), @bitSizeOf(DiffFile));
}
comptime {
std.testing.refAllDecls(@This());
}
};
comptime {
std.testing.refAllDecls(@This());
} | src/diff.zig |
const std = @import("std");
const tools = @import("tools");
const with_trace = false;
const assert = std.debug.assert;
fn trace(comptime fmt: []const u8, args: anytype) void {
if (with_trace) std.debug.print(fmt, args);
}
const Vec3 = struct {
x: i64,
y: i64,
z: i64,
};
const Part = struct {
p: Vec3,
v: Vec3,
a: Vec3,
};
fn add(a: Vec3, b: Vec3) Vec3 {
return Vec3{
.x = a.x + b.x,
.y = a.y + b.y,
.z = a.z + b.z,
};
}
fn sgn(a: i64) i2 {
if (a < 0) return -1;
if (a > 0) return 1;
return 0;
}
fn same_sign(a: Vec3, b: Vec3) bool {
return (sgn(a.x) * sgn(b.x) >= 0 and sgn(a.y) * sgn(b.y) >= 0 and sgn(a.z) * sgn(b.z) >= 0);
}
fn update(p: *Part) void {
p.v = add(p.v, p.a);
p.p = add(p.p, p.v);
}
fn is_stabilised(p: *const Part) bool {
return same_sign(p.p, p.v) and same_sign(p.a, p.v);
}
pub fn main() anyerror!void {
const stdout = std.io.getStdOut().writer();
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
const limit = 1 * 1024 * 1024 * 1024;
const text = try std.fs.cwd().readFileAlloc(allocator, "day20.txt", limit);
defer allocator.free(text);
var parts0: [1000]Part = undefined;
var len: usize = 0;
{
var it = std.mem.split(u8, text, "\n");
while (it.next()) |line| {
//const line = std.mem.trim(u8, line0, " \n\t\r");
//if (line.len == 0) continue;
if (tools.match_pattern("p=<{},{},{}>, v=<{},{},{}>, a=<{},{},{}>", line)) |vals| {
const p = &parts0[len];
p.p = Vec3{ .x = vals[0].imm, .y = vals[1].imm, .z = vals[2].imm };
p.v = Vec3{ .x = vals[3].imm, .y = vals[4].imm, .z = vals[5].imm };
p.a = Vec3{ .x = vals[6].imm, .y = vals[7].imm, .z = vals[8].imm };
len += 1;
}
}
}
try stdout.print("len={}\n", .{len});
{
var parts: [1000]Part = undefined;
std.mem.copy(Part, parts[0..len], parts0[0..len]);
var steps: u32 = 0;
var stabilised = false;
var closest_i: usize = 0;
while (!stabilised) {
steps += 1;
stabilised = true;
closest_i = 0;
var closest_dist: u32 = 1000000000;
for (parts[0..len]) |*p, i| {
update(p);
if (!is_stabilised(p))
stabilised = false;
const d = (p.p.x * sgn(p.p.x) + p.p.y * sgn(p.p.y) + p.p.z * sgn(p.p.z));
if (d < closest_dist) {
closest_dist = @intCast(u32, d);
closest_i = i;
}
}
trace("closest_i={}\n", .{closest_i});
}
try stdout.print("steps={}, closest_i={}\n", .{ steps, closest_i });
}
{
var parts: [1000]Part = undefined;
var tmp: [1000]Part = undefined;
std.mem.copy(Part, parts[0..len], parts0[0..len]);
var steps: u32 = 0;
var stabilised = false;
while (!stabilised) {
steps += 1;
stabilised = true;
var closest_i: usize = 0;
var closest_dist: u32 = 1000000000;
for (parts[0..len]) |p, i| {
tmp[i] = p;
update(&tmp[i]);
}
var l: usize = 0;
for (tmp[0..len]) |p, i| {
const collides = for (tmp[0..len]) |q, j| {
if (i != j and p.p.x == q.p.x and p.p.y == q.p.y and p.p.z == q.p.z)
break true;
} else false;
if (!collides) {
parts[l] = p;
l += 1;
if (!is_stabilised(&p))
stabilised = false;
}
}
len = l;
trace("len={}\n", .{len});
}
try stdout.print("steps={}, len={}\n", .{ steps, len });
}
} | 2017/day20.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const assert = std.debug.assert;
const print = std.debug.print;
const EOL = '\n';
pub fn readInput(allocator: *Allocator) !ArrayList(u32) {
var entries = ArrayList(u32).init(allocator);
const file = try std.fs.cwd().openFile("input/day01.txt", .{});
defer file.close();
const reader = file.reader();
var line_buf: [20]u8 = undefined;
while (try reader.readUntilDelimiterOrEof(&line_buf, EOL)) |line| {
try entries.append(try std.fmt.parseInt(u32, std.mem.trim(u8, line[0..], std.ascii.spaces[0..]), 10));
}
return entries;
}
pub fn findPair(entries: []const u32, sum: u32) ![2]u32 {
var i: usize = 0;
while (i < entries.len) : (i += 1) {
var j: usize = i + 1;
while (j < entries.len) : (j += 1) {
if (entries[i] + entries[j] == sum) {
return [2]u32{ entries[i], entries[j] };
}
}
}
return error.PairNotFound;
}
pub fn part1(allocator: *Allocator) !void {
const entries = try readInput(allocator);
const pair = try findPair(entries.items, 2020);
print("part1 {}\n", .{pair[0] * pair[1]});
}
pub fn findTriple(entries: []const u32, sum: u32) ![3]u32 {
var i: usize = 0;
while (i < entries.len) : (i += 1) {
var j: usize = i + 1;
while (j < entries.len) : (j += 1) {
var k: usize = j + 1;
while (k < entries.len) : (k += 1) {
if (entries[i] + entries[j] + entries[k] == sum) {
return [3]u32{ entries[i], entries[j], entries[k] };
}
}
}
}
return error.TripleNotFound;
}
pub fn part2(allocator: *Allocator) !void {
const entries = try readInput(allocator);
const triple = try findTriple(entries.items, 2020);
print("part2 {}\n", .{triple[0] * triple[1] * triple[2]});
}
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var allocator = &gpa.allocator;
try part1(allocator);
try part2(allocator);
}
test "part1 example" {
const entries = [_]u32{
1721,
979,
366,
299,
675,
1456,
};
const pair = try findPair(entries[0..], 2020);
std.testing.expect((pair[0] == 1721 and pair[1] == 299) or (pair[1] == 1721 and pair[0] == 299));
std.testing.expect(pair[0] * pair[1] == 514579);
}
test "part2 example" {
const entries = [_]u32{
1721,
979,
366,
299,
675,
1456,
};
const triple = try findTriple(entries[0..], 2020);
std.testing.expect(triple[0] == 979 and triple[1] == 366 and triple[2] == 675);
std.testing.expect(triple[0] * triple[1] * triple[2] == 241861950);
} | src/day01.zig |
const std = @import("std");
const panic = std.debug.panic;
const builtin = @import("builtin");
const warn = std.debug.warn;
const join = std.fs.path.join;
const pi = std.math.pi;
usingnamespace @import("c.zig");
const Camera = @import("camera.zig").Camera;
const Shader = @import("shader.zig").Shader;
const glm = @import("glm.zig");
const Mat4 = glm.Mat4;
const Vec3 = glm.Vec3;
const vec3 = glm.vec3;
const translation = glm.translation;
const rotation = glm.rotation;
const perspective = glm.perspective;
// settings
const SCR_WIDTH: u32 = 1920;
const SCR_HEIGHT: u32 = 1080;
// camera
var camera = Camera.default();
var lastX: f32 = 800.0 / 2.0;
var lastY: f32 = 600.0 / 2.0;
var firstMouse = true;
// timing
var deltaTime: f32 = 0.0; // time between current frame and last frame
var lastFrame: f32 = 0.0;
pub fn main() !void {
const allocator = std.heap.page_allocator;
const vertPath = try join(allocator, &[_][]const u8{ "shaders", "1_7_camera.vert" });
const fragPath = try join(allocator, &[_][]const u8{ "shaders", "1_7_camera.frag" });
const ok = glfwInit();
if (ok == 0) {
panic("Failed to initialise GLFW\n", .{});
}
defer glfwTerminate();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
if (builtin.os.tag == .macosx) {
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
}
// glfw: initialize and configure
var window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Learn OpenGL", null, null);
if (window == null) {
panic("Failed to create GLFW window\n", .{});
}
glfwMakeContextCurrent(window);
const resizeCallback = glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
const posCallback = glfwSetCursorPosCallback(window, mouse_callback);
const scrollCallback = glfwSetScrollCallback(window, scroll_callback);
// tell GLFW to capture our mouse
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
// glad: load all OpenGL function pointers
if (gladLoadGLLoader(@ptrCast(GLADloadproc, glfwGetProcAddress)) == 0) {
panic("Failed to initialise GLAD\n", .{});
}
glEnable(GL_DEPTH_TEST);
// build and compile our shader program
const ourShader = try Shader.init(allocator, vertPath, fragPath);
// set up vertex data (and buffer(s)) and configure vertex attributes
const vertices = [_]f32{
-0.5, -0.5, -0.5, 0.0, 0.0,
0.5, -0.5, -0.5, 1.0, 0.0,
0.5, 0.5, -0.5, 1.0, 1.0,
0.5, 0.5, -0.5, 1.0, 1.0,
-0.5, 0.5, -0.5, 0.0, 1.0,
-0.5, -0.5, -0.5, 0.0, 0.0,
-0.5, -0.5, 0.5, 0.0, 0.0,
0.5, -0.5, 0.5, 1.0, 0.0,
0.5, 0.5, 0.5, 1.0, 1.0,
0.5, 0.5, 0.5, 1.0, 1.0,
-0.5, 0.5, 0.5, 0.0, 1.0,
-0.5, -0.5, 0.5, 0.0, 0.0,
-0.5, 0.5, 0.5, 1.0, 0.0,
-0.5, 0.5, -0.5, 1.0, 1.0,
-0.5, -0.5, -0.5, 0.0, 1.0,
-0.5, -0.5, -0.5, 0.0, 1.0,
-0.5, -0.5, 0.5, 0.0, 0.0,
-0.5, 0.5, 0.5, 1.0, 0.0,
0.5, 0.5, 0.5, 1.0, 0.0,
0.5, 0.5, -0.5, 1.0, 1.0,
0.5, -0.5, -0.5, 0.0, 1.0,
0.5, -0.5, -0.5, 0.0, 1.0,
0.5, -0.5, 0.5, 0.0, 0.0,
0.5, 0.5, 0.5, 1.0, 0.0,
-0.5, -0.5, -0.5, 0.0, 1.0,
0.5, -0.5, -0.5, 1.0, 1.0,
0.5, -0.5, 0.5, 1.0, 0.0,
0.5, -0.5, 0.5, 1.0, 0.0,
-0.5, -0.5, 0.5, 0.0, 0.0,
-0.5, -0.5, -0.5, 0.0, 1.0,
-0.5, 0.5, -0.5, 0.0, 1.0,
0.5, 0.5, -0.5, 1.0, 1.0,
0.5, 0.5, 0.5, 1.0, 0.0,
0.5, 0.5, 0.5, 1.0, 0.0,
-0.5, 0.5, 0.5, 0.0, 0.0,
-0.5, 0.5, -0.5, 0.0, 1.0,
};
// world space positions of our cubes
const cubePositions = [_]Vec3{
vec3(0.0, 0.0, 0.0),
vec3(2.0, 5.0, -15.0),
vec3(-1.5, -2.2, -2.5),
vec3(-3.8, -2.0, -12.3),
vec3(2.4, -0.4, -3.5),
vec3(-1.7, 3.0, -7.5),
vec3(1.3, -2.0, -2.5),
vec3(1.5, 2.0, -2.5),
vec3(1.5, 0.2, -1.5),
vec3(-1.3, 1.0, -1.5),
};
var VAO: c_uint = undefined;
var VBO: c_uint = undefined;
glGenVertexArrays(1, &VAO);
defer glDeleteVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
defer glDeleteBuffers(1, &VBO);
// bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, vertices.len * @sizeOf(f32), &vertices, GL_STATIC_DRAW);
// position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * @sizeOf(f32), null);
glEnableVertexAttribArray(0);
// texture coord attribute
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * @sizeOf(f32), @intToPtr(*c_void, 3 * @sizeOf(f32)));
glEnableVertexAttribArray(1);
// load and create a texture
var texture1: c_uint = undefined;
var texture2: c_uint = undefined;
// texture 1
glGenTextures(1, &texture1);
glBindTexture(GL_TEXTURE_2D, texture1);
// set the texture wrapping parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// set texture filtering parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// load image, create texture and generate mipmaps
var width: c_int = undefined;
var height: c_int = undefined;
var nrChannels: c_int = undefined;
stbi_set_flip_vertically_on_load(1); // tell stb_image.h to flip loaded texture's on the y-axis.
// The FileSystem::getPath(...) is part of the GitHub repository so we can find files on any IDE/platform; replace it with your own image path.
var data = stbi_load("textures/container.jpg", &width, &height, &nrChannels, 0);
if (data != null) {
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
} else {
warn("Failed to load texture\n", .{});
}
stbi_image_free(data);
// texture 2
glGenTextures(1, &texture2);
glBindTexture(GL_TEXTURE_2D, texture2);
// set the texture wrapping parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// set texture filtering parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// load image, create texture and generate mipmaps
data = stbi_load("textures/awesomeface.png", &width, &height, &nrChannels, 0);
if (data != null) {
// note that the awesomeface.png has transparency and thus an alpha channel, so make sure to tell OpenGL the data type is of GL_RGBA
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
} else {
warn("Failed to load texture\n", .{});
}
stbi_image_free(data);
// tell opengl for each sampler to which texture unit it belongs to (only has to be done once)
ourShader.use(); // don't forget to activate/use the shader before setting uniforms!
// either set it manually like so:
glUniform1i(glGetUniformLocation(ourShader.id, "texture1"), 0);
// or set it via the texture class
ourShader.setInt("texture2", 1);
// render loop
while (glfwWindowShouldClose(window) == 0) {
// per-frame time logic
const currentFrame = @floatCast(f32, glfwGetTime());
deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame;
// input
processInput(window);
// render
glClearColor(0.2, 0.3, 0.3, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // also clear the depth buffer now!
// bind textures on corresponding texture units
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture1);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texture2);
// activate shader
ourShader.use();
// pass projection matrix to shader (note that in this case it could change every frame)
const projection = perspective(camera.zoom / 180.0 * pi, @intToFloat(f32, SCR_WIDTH) / @intToFloat(f32, SCR_HEIGHT), 0.1, 100.0);
ourShader.setMat4("projection", projection);
// camera/view transformation
const view = camera.getViewMatrix();
ourShader.setMat4("view", view);
// render boxes
glBindVertexArray(VAO);
var i: usize = 0;
while (i < 10) : (i += 1) {
// calculate the model matrix for each object and pass it to shader before drawing
var model = translation(cubePositions[i]);
const angle = 20.0 * @intToFloat(f32, i);
model = model.matmul(rotation(angle / 180.0 * pi, vec3(1.0, 0.3, 0.5)));
ourShader.setMat4("model", model);
glDrawArrays(GL_TRIANGLES, 0, 36);
}
// glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
glfwSwapBuffers(window);
glfwPollEvents();
}
}
// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
pub fn processInput(window: ?*GLFWwindow) callconv(.C) void {
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, 1);
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
camera.processKeyboard(.Forward, deltaTime);
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
camera.processKeyboard(.Backward, deltaTime);
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
camera.processKeyboard(.Left, deltaTime);
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
camera.processKeyboard(.Right, deltaTime);
}
// glfw: whenever the window size changed (by OS or user resize) this callback function executes
pub fn framebuffer_size_callback(window: ?*GLFWwindow, width: c_int, height: c_int) callconv(.C) void {
// make sure the viewport matches the new window dimensions; note that width and
// height will be significantly larger than specified on retina displays.
glViewport(0, 0, width, height);
}
// glfw: whenever the mouse moves, this callback is called
pub fn mouse_callback(window: ?*GLFWwindow, xpos: f64, ypos: f64) callconv(.C) void {
if (firstMouse) {
lastX = @floatCast(f32, xpos);
lastY = @floatCast(f32, ypos);
firstMouse = false;
}
const xoffset = @floatCast(f32, xpos) - lastX;
const yoffset = lastY - @floatCast(f32, ypos); // reversed since y-coordinates go from bottom to top
lastX = @floatCast(f32, xpos);
lastY = @floatCast(f32, ypos);
camera.processMouseMovement(xoffset, yoffset);
}
// glfw: whenever the mouse scroll wheel scrolls, this callback is called
pub fn scroll_callback(window: ?*GLFWwindow, xoffset: f64, yoffset: f64) callconv(.C) void {
camera.processMouseScroll(@floatCast(f32, yoffset));
} | src/1_7_camera.zig |
const std = @import("std");
const upaya = @import("upaya");
const ts = @import("../tilescript.zig");
usingnamespace @import("imgui");
const object_editor = @import("object_editor.zig");
var filter_buffer: [25]u8 = undefined;
var filter = false;
var selected_index: usize = std.math.maxInt(usize);
pub fn draw(state: *ts.AppState) void {
ogPushStyleVarVec2(ImGuiStyleVar_WindowMinSize, ImVec2{ .x = 200, .y = 100 });
defer igPopStyleVar(1);
if (state.prefs.windows.objects) {
_ = igBegin("Objects", &state.prefs.windows.objects, ImGuiWindowFlags_None);
defer igEnd();
if (ogBeginChildEx("##obj-child", igGetItemID(), .{ .y = -igGetFrameHeightWithSpacing() }, false, ImGuiWindowFlags_None)) {
defer igEndChild();
igPushItemWidth(igGetWindowContentRegionWidth());
if (ogInputText("##obj-filter", &filter_buffer, filter_buffer.len)) {
const null_index = std.mem.indexOfScalar(u8, &filter_buffer, 0) orelse 0;
filter = null_index > 0;
}
igPopItemWidth();
var delete_index: usize = std.math.maxInt(usize);
for (state.map.objects.items) |*obj, i| {
if (filter) {
const null_index = std.mem.indexOfScalar(u8, &filter_buffer, 0) orelse 0;
if (std.mem.indexOf(u8, &obj.name, filter_buffer[0..null_index]) == null) {
continue;
}
}
igPushIDInt(@intCast(c_int, i));
if (igSelectableBool(&obj.name, selected_index == i, ImGuiSelectableFlags_None, .{ .x = igGetWindowContentRegionWidth() - 24 })) {
selected_index = i;
object_editor.setSelectedObject(selected_index);
state.prefs.windows.object_editor = true;
}
igSameLine(igGetWindowContentRegionWidth() - 20, 0);
igSetCursorPosY(igGetCursorPosY() - 3);
if (ogButton(icons.trash)) {
delete_index = i;
}
igPopID();
}
if (delete_index < std.math.maxInt(usize)) {
if (delete_index == selected_index) {
selected_index = std.math.maxInt(usize);
object_editor.setSelectedObject(null);
} else if (delete_index < selected_index and selected_index != std.math.maxInt(usize)) {
selected_index -= 1;
object_editor.setSelectedObject(selected_index);
}
// cleanup any links to this object
var deleted_id = state.map.objects.items[delete_index].id;
for (state.map.objects.items) |*obj| {
obj.removeLinkPropsWithId(deleted_id);
}
_ = state.map.objects.orderedRemove(delete_index);
}
}
if (igButton("Add Object", .{})) {
state.map.addObject();
object_editor.setSelectedObject(state.map.objects.items.len - 1);
state.prefs.windows.object_editor = true;
}
}
}
pub fn setSelectedObject(index: usize) void {
selected_index = index;
} | tilescript/windows/objects.zig |
// zig build-exe examples/basic.zig --pkg-begin ziglet src/index.zig --pkg-end
const std = @import("std");
const ziglet = @import("ziglet");
const app = ziglet.app;
const Key = app.event.Key;
const Event = app.event.Event;
const Window = app.Window;
pub fn main() !void {
var direct_allocator = std.heap.DirectAllocator.init();
var alloc = &direct_allocator.allocator;
defer direct_allocator.deinit();
const opts = ziglet.app.WindowOptions{
.backend = ziglet.gfx.RenderBackend.OpenGL,
.fullscreen = false,
.borderless = false,
.resizeable = true,
.width = 512,
.height = 512,
.title = "hello_world",
};
var w = try Window.init(alloc, opts);
defer w.deinit();
while (!w.should_close) {
w.update();
while (w.event_pump.pop()) |event| {
switch (event) {
Event.KeyDown => |key| {
std.debug.warn("KeyDown: {}\n", key);
switch (key) {
Key.Escape => {
w.should_close = true;
break;
},
else => continue,
}
},
Event.KeyUp => |key| std.debug.warn("KeyUp: {}\n", key),
Event.Char => |char| std.debug.warn("Char: {}\n", char),
Event.MouseDown => |btn| std.debug.warn("MouseDown: {}\n", btn),
Event.MouseUp => |btn| std.debug.warn("MouseUp: {}\n", btn),
Event.MouseScroll => |scroll| std.debug.warn("MouseScroll: {}, {}\n", scroll[0], scroll[1]),
Event.MouseMove => |coord| std.debug.warn("MouseMove: {}, {}\n", coord[0], coord[1]),
Event.MouseEnter => std.debug.warn("MouseEnter\n"),
Event.MouseLeave => std.debug.warn("MouseLeave\n"),
Event.Resized => |size| std.debug.warn("Resized: {}, {}\n", size[0], size[1]),
Event.Iconified => std.debug.warn("Iconified\n"),
Event.Restored => std.debug.warn("Restored\n"),
// Event.FileDroppped => |path| std.debug.warn("FileDroppped: {}\n", path),
else => {
std.debug.warn("invalid event\n");
},
}
}
std.os.time.sleep(16666667);
}
} | examples/events.zig |
const std = @import("std");
const mem = std.mem;
const fmt = std.fmt;
const testing = std.testing;
use @import("ip");
test "IpV4Address.fromSlice()" {
var array = [_]u8{ 127, 0, 0, 1 };
const ip = IpV4Address.fromSlice(&array);
testing.expect(IpV4Address.Localhost.equals(ip));
}
test "IpV4Address.fromArray()" {
var array = [_]u8{ 127, 0, 0, 1 };
const ip = IpV4Address.fromArray(array);
testing.expect(IpV4Address.Localhost.equals(ip));
}
test "IpV4Address.octets()" {
testing.expectEqual([_]u8{ 127, 0, 0, 1 }, IpV4Address.init(127, 0, 0, 1).octets());
}
test "IpV4Address.isUnspecified()" {
testing.expect(IpV4Address.init(0, 0, 0, 0).isUnspecified());
testing.expect(IpV4Address.init(192, 168, 0, 1).isUnspecified() == false);
}
test "IpV4Address.isLoopback()" {
testing.expect(IpV4Address.init(127, 0, 0, 1).isLoopback());
testing.expect(IpV4Address.init(192, 168, 0, 1).isLoopback() == false);
}
test "IpV4Address.isPrivate()" {
testing.expect(IpV4Address.init(10, 0, 0, 1).isPrivate());
testing.expect(IpV4Address.init(10, 10, 10, 10).isPrivate());
testing.expect(IpV4Address.init(172, 16, 10, 10).isPrivate());
testing.expect(IpV4Address.init(172, 29, 45, 14).isPrivate());
testing.expect(IpV4Address.init(172, 32, 0, 2).isPrivate() == false);
testing.expect(IpV4Address.init(192, 168, 0, 2).isPrivate());
testing.expect(IpV4Address.init(192, 169, 0, 2).isPrivate() == false);
}
test "IpV4Address.isLinkLocal()" {
testing.expect(IpV4Address.init(169, 254, 0, 0).isLinkLocal());
testing.expect(IpV4Address.init(169, 254, 10, 65).isLinkLocal());
testing.expect(IpV4Address.init(16, 89, 10, 65).isLinkLocal() == false);
}
test "IpV4Address.isMulticast()" {
testing.expect(IpV4Address.init(224, 254, 0, 0).isMulticast());
testing.expect(IpV4Address.init(236, 168, 10, 65).isMulticast());
testing.expect(IpV4Address.init(172, 16, 10, 65).isMulticast() == false);
}
test "IpV4Address.isBroadcast()" {
testing.expect(IpV4Address.init(255, 255, 255, 255).isBroadcast());
testing.expect(IpV4Address.init(236, 168, 10, 65).isBroadcast() == false);
}
test "IpV4Address.isDocumentation()" {
testing.expect(IpV4Address.init(192, 0, 2, 255).isDocumentation());
testing.expect(IpV4Address.init(198, 51, 100, 65).isDocumentation());
testing.expect(IpV4Address.init(203, 0, 113, 6).isDocumentation());
testing.expect(IpV4Address.init(193, 34, 17, 19).isDocumentation() == false);
}
test "IpV4Address.isGloballyRoutable()" {
testing.expect(IpV4Address.init(10, 254, 0, 0).isGloballyRoutable() == false);
testing.expect(IpV4Address.init(192, 168, 10, 65).isGloballyRoutable() == false);
testing.expect(IpV4Address.init(172, 16, 10, 65).isGloballyRoutable() == false);
testing.expect(IpV4Address.init(0, 0, 0, 0).isGloballyRoutable() == false);
testing.expect(IpV4Address.init(80, 9, 12, 3).isGloballyRoutable());
}
test "IpV4Address.equals()" {
testing.expect(IpV4Address.init(10, 254, 0, 0).equals(IpV4Address.init(127, 0, 0, 1)) == false);
testing.expect(IpV4Address.init(127, 0, 0, 1).equals(IpV4Address.Localhost));
}
test "IpV4Address.toHostByteOrder()" {
var expected: u32 = 0x0d0c0b0a;
testing.expectEqual(expected, IpV4Address.init(13, 12, 11, 10).toHostByteOrder());
}
test "IpV4Address.fromHostByteOrder()" {
testing.expect(IpV4Address.fromHostByteOrder(0x0d0c0b0a).equals(IpV4Address.init(13, 12, 11, 10)));
}
test "IpV4Address.format()" {
var buffer: [11]u8 = undefined;
const buf = buffer[0..];
const addr = IpV4Address.init(13, 12, 11, 10);
const result = try fmt.bufPrint(buf, "{}", addr);
const expected: []const u8 = "13.12.11.10";
testing.expectEqualSlices(u8, expected, result);
}
fn testIpV4ParseError(addr: []const u8, expected_error: ParseError) void {
testing.expectError(expected_error, IpV4Address.parse(addr));
}
fn testIpV4Format(addr: IpV4Address, expected: []const u8) !void {
var buffer: [15]u8 = undefined;
const buf = buffer[0..];
const result = try fmt.bufPrint(buf, "{}", addr);
testing.expectEqualSlices(u8, expected, result);
}
test "IpV4Address.parse()" {
const parsed = try IpV4Address.parse("127.0.0.1");
testing.expect(parsed.equals(IpV4Address.Localhost));
const mask_parsed = try IpV4Address.parse("255.255.255.0");
try testIpV4Format(mask_parsed, "255.255.255.0");
testIpV4ParseError("256.0.0.1", ParseError.Overflow);
testIpV4ParseError("x.0.0.1", ParseError.InvalidCharacter);
testIpV4ParseError("127.0.0.1.1", ParseError.TooManyOctets);
testIpV4ParseError("127.0.0.", ParseError.Incomplete);
testIpV4ParseError("100..0.1", ParseError.InvalidCharacter);
} | test/ipv4.zig |
const std = @import("std");
const testing = std.testing;
const Allocator = std.mem.Allocator;
pub const Error = error{
KeysLikelyNotUnique,
OutOfMemory,
};
pub inline fn murmur64(h: u64) u64 {
var v = h;
v ^= v >> 33;
v *%= 0xff51afd7ed558ccd;
v ^= v >> 33;
v *%= 0xc4ceb9fe1a85ec53;
v ^= v >> 33;
return v;
}
pub inline fn mixSplit(key: u64, seed: u64) u64 {
return murmur64(key +% seed);
}
pub inline fn rotl64(n: u64, c: usize) u64 {
return (n << @intCast(u6, c & 63)) | (n >> @intCast(u6, (-%c) & 63));
}
pub inline fn reduce(hash: u32, n: u32) u32 {
// http://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction
return @truncate(u32, (@intCast(u64, hash) *% @intCast(u64, n)) >> 32);
}
pub inline fn fingerprint(hash: u64) u64 {
return hash ^ (hash >> 32);
}
pub fn sliceIterator(comptime T: type) type {
return struct {
allocator: Allocator,
slice: []T,
i: usize,
const Self = @This();
pub inline fn init(allocator: Allocator, slice: []T) !*Self {
const self = try allocator.create(Self);
self.* = Self{
.allocator = allocator,
.i = 0,
.slice = slice,
};
return self;
}
pub inline fn deinit(self: *Self) void {
self.allocator.destroy(self);
}
pub inline fn next(self: *Self) ?T {
if (self.i >= self.slice.len) {
self.i = 0;
return null;
}
const v = self.slice[self.i];
self.i += 1;
return v;
}
pub inline fn len(self: *Self) usize {
return self.slice.len;
}
};
}
// returns random number, modifies the seed.
pub inline fn rngSplitMix64(seed: *u64) u64 {
seed.* = seed.* +% 0x9E3779B97F4A7C15;
var z = seed.*;
z = (z ^ (z >> 30)) *% 0xBF58476D1CE4E5B9;
z = (z ^ (z >> 27)) *% 0x94D049BB133111EB;
return z ^ (z >> 31);
}
test "murmur64" {
// Arbitrarily chosen inputs for validation.
try testing.expectEqual(@as(u64, 11156705658460211942), murmur64(0xF + 5));
try testing.expectEqual(@as(u64, 9276143743022464963), murmur64(0xFF + 123));
try testing.expectEqual(@as(u64, 9951468085874665196), murmur64(0xFFF + 1337));
try testing.expectEqual(@as(u64, 4797998644499646477), murmur64(0xFFFF + 143));
try testing.expectEqual(@as(u64, 4139256335519489731), murmur64(0xFFFFFF + 918273987));
}
test "mixSplit" {
// Arbitrarily chosen inputs for validation.
try testing.expectEqual(@as(u64, 11156705658460211942), mixSplit(0xF, 5));
}
test "rotl64" {
// Arbitrarily chosen inputs for validation.
try testing.expectEqual(@as(u64, 193654783976931328), rotl64(43, 52));
}
test "reduce" {
// Arbitrarily chosen inputs for validation.
try testing.expectEqual(@as(u32, 8752776), reduce(1936547838, 19412321));
}
test "fingerprint" {
// Arbitrarily chosen inputs for validation.
try testing.expectEqual(@as(u64, 1936547838), fingerprint(1936547838));
}
test "rngSplitMix64" {
var seed: u64 = 13337;
var r = rngSplitMix64(&seed);
try testing.expectEqual(@as(u64, 8862613829200693549), r);
r = rngSplitMix64(&seed);
try testing.expectEqual(@as(u64, 1009918040199880802), r);
r = rngSplitMix64(&seed);
try testing.expectEqual(@as(u64, 8603670078971061766), r);
} | src/util.zig |
const macro = @import("pspmacros.zig");
comptime {
asm (macro.import_module_start("sceHttp", "0x00090011", "83"));
asm (macro.import_function("sceHttp", "0x0282A3BD", "sceHttpGetContentLength"));
asm (macro.import_function("sceHttp", "0x03D9526F", "sceHttpSetResolveRetry"));
asm (macro.import_function("sceHttp", "0x06488A1C", "sceHttpSetCookieSendCallback"));
asm (macro.import_function("sceHttp", "0x0809C831", "sceHttpEnableRedirect"));
asm (macro.import_function("sceHttp", "0x0B12ABFB", "sceHttpDisableCookie"));
asm (macro.import_function("sceHttp", "0x0DAFA58F", "sceHttpEnableCookie"));
asm (macro.import_function("sceHttp", "0x15540184", "sceHttpDeleteHeader"));
asm (macro.import_function("sceHttp", "0x1A0EBB69", "sceHttpDisableRedirect"));
asm (macro.import_function("sceHttp", "0x1CEDB9D4", "sceHttpFlushCache"));
asm (macro.import_function("sceHttp", "0x1F0FC3E3", "sceHttpSetRecvTimeOut"));
asm (macro.import_function("sceHttp", "0x2255551E", "sceHttpGetNetworkPspError"));
asm (macro.import_function("sceHttp", "0x267618F4", "sceHttpSetAuthInfoCallback"));
asm (macro.import_function("sceHttp", "0x2A6C3296", "sceHttpSetAuthInfoCB"));
asm (macro.import_function("sceHttp", "0x2C3C82CF", "sceHttpFlushAuthList"));
asm (macro.import_function("sceHttp", "0x3A67F306", "sceHttpSetCookieRecvCallback"));
asm (macro.import_function("sceHttp", "0x3C478044", "sceHttp_3C478044"));
asm (macro.import_function("sceHttp", "0x3EABA285", "sceHttpAddExtraHeader"));
asm (macro.import_function("sceHttp", "0x457D221D", "sceHttp_457D221D"));
asm (macro.import_function("sceHttp", "0x47347B50", "sceHttpCreateRequest"));
asm (macro.import_function("sceHttp", "0x47940436", "sceHttpSetResolveTimeOut"));
asm (macro.import_function("sceHttp", "0x4CC7D78F", "sceHttpGetStatusCode"));
asm (macro.import_function("sceHttp", "0x4E4A284A", "sceHttp_4E4A284A"));
asm (macro.import_function("sceHttp", "0x5152773B", "sceHttpDeleteConnection"));
asm (macro.import_function("sceHttp", "0x54E7DF75", "sceHttpIsRequestInCache"));
asm (macro.import_function("sceHttp", "0x569A1481", "sceHttpsSetSslCallback"));
asm (macro.import_function("sceHttp", "0x59E6D16F", "sceHttpEnableCache"));
asm (macro.import_function("sceHttp", "0x68AB0F86", "sceHttpsInitWithPath"));
asm (macro.import_function("sceHttp", "0x739C2D79", "sceHttp_739C2D79"));
asm (macro.import_function("sceHttp", "0x76D1363B", "sceHttpSaveSystemCookie"));
asm (macro.import_function("sceHttp", "0x7774BF4C", "sceHttpAddCookie"));
asm (macro.import_function("sceHttp", "0x77EE5319", "sceHttp_77EE5319"));
asm (macro.import_function("sceHttp", "0x78A0D3EC", "sceHttpEnableKeepAlive"));
asm (macro.import_function("sceHttp", "0x78B54C09", "sceHttpEndCache"));
asm (macro.import_function("sceHttp", "0x8046E250", "sceHttp_8046E250"));
asm (macro.import_function("sceHttp", "0x87797BDD", "sceHttpsLoadDefaultCert"));
asm (macro.import_function("sceHttp", "0x87F1E666", "sceHttp_87F1E666"));
asm (macro.import_function("sceHttp", "0x8ACD1F73", "sceHttpSetConnectTimeOut"));
asm (macro.import_function("sceHttp", "0x8EEFD953", "sceHttpCreateConnection_stub"));
asm (macro.import_function("sceHttp", "0x951D310E", "sceHttp_951D310E"));
asm (macro.import_function("sceHttp", "0x9668864C", "sceHttpSetRecvBlockSize"));
asm (macro.import_function("sceHttp", "0x96F16D3E", "sceHttpGetCookie"));
asm (macro.import_function("sceHttp", "0x9988172D", "sceHttpSetSendTimeOut"));
asm (macro.import_function("sceHttp", "0x9AFC98B2", "sceHttpSendRequestInCacheFirstMode"));
asm (macro.import_function("sceHttp", "0x9B1F1F36", "sceHttpCreateTemplate"));
asm (macro.import_function("sceHttp", "0x9FC5F10D", "sceHttpEnableAuth"));
asm (macro.import_function("sceHttp", "0xA4496DE5", "sceHttpSetRedirectCallback"));
asm (macro.import_function("sceHttp", "0xA461A167", "sceHttp_A461A167"));
asm (macro.import_function("sceHttp", "0xA5512E01", "sceHttpDeleteRequest"));
asm (macro.import_function("sceHttp", "0xA6800C34", "sceHttpInitCache"));
asm (macro.import_function("sceHttp", "0xA909F2AE", "sceHttp_A909F2AE"));
asm (macro.import_function("sceHttp", "0xAB1540D5", "sceHttpsGetSslError"));
asm (macro.import_function("sceHttp", "0xAB1ABE07", "sceHttpInit"));
asm (macro.import_function("sceHttp", "0xAE948FEE", "sceHttpDisableAuth"));
asm (macro.import_function("sceHttp", "0xB0257723", "sceHttp_B0257723"));
asm (macro.import_function("sceHttp", "0xB0C34B1D", "sceHttpSetCacheContentLengthMaxSize"));
asm (macro.import_function("sceHttp", "0xB3FAF831", "sceHttpsDisableOption"));
asm (macro.import_function("sceHttp", "0xB509B09E", "sceHttpCreateRequestWithURL"));
asm (macro.import_function("sceHttp", "0xBAC31BF1", "sceHttpsEnableOption"));
asm (macro.import_function("sceHttp", "0xBB70706F", "sceHttpSendRequest"));
asm (macro.import_function("sceHttp", "0xC10B6BD9", "sceHttpAbortRequest"));
asm (macro.import_function("sceHttp", "0xC6330B0D", "sceHttp_C6330B0D"));
asm (macro.import_function("sceHttp", "0xC7EF2559", "sceHttpDisableKeepAlive"));
asm (macro.import_function("sceHttp", "0xC98CBBA7", "sceHttpSetResHeaderMaxSize"));
asm (macro.import_function("sceHttp", "0xCCBD167A", "sceHttpDisableCache"));
asm (macro.import_function("sceHttp", "0xCDB0DC58", "sceHttp_CDB0DC58"));
asm (macro.import_function("sceHttp", "0xCDF8ECB9", "sceHttpCreateConnectionWithURL"));
asm (macro.import_function("sceHttp", "0xD081EC8F", "sceHttpGetNetworkErrno"));
asm (macro.import_function("sceHttp", "0xD11DAB01", "sceHttpsGetCaList"));
asm (macro.import_function("sceHttp", "0xD1C8945E", "sceHttpEnd"));
asm (macro.import_function("sceHttp", "0xD70D4847", "sceHttpGetProxy_stub"));
asm (macro.import_function("sceHttp", "0xD80BE761", "sceHttp_D80BE761"));
asm (macro.import_function("sceHttp", "0xDB266CCF", "sceHttpGetAllHeader"));
asm (macro.import_function("sceHttp", "0xDD6E7857", "sceHttp_DD6E7857"));
asm (macro.import_function("sceHttp", "0xE4D21302", "sceHttpsInit"));
asm (macro.import_function("sceHttp", "0xEDEEB999", "sceHttpReadData"));
asm (macro.import_function("sceHttp", "0xF0F46C62", "sceHttpSetProxy_stub"));
asm (macro.import_function("sceHttp", "0xF1657B22", "sceHttpLoadSystemCookie"));
asm (macro.import_function("sceHttp", "0xF49934F6", "sceHttpSetMallocFunction"));
asm (macro.import_function("sceHttp", "0xF9D8EB63", "sceHttpsEnd"));
asm (macro.import_function("sceHttp", "0xFCF8C055", "sceHttpDeleteTemplate"));
asm (macro.generic_abi_wrapper("sceHttpCreateConnection", 5));
asm (macro.generic_abi_wrapper("sceHttpGetProxy", 6));
asm (macro.generic_abi_wrapper("sceHttpSetProxy", 5));
} | src/psp/nids/psphttp.zig |
const c = @cImport({
@cInclude("cfl_valuator.h");
});
const widget = @import("widget.zig");
pub const Valuator = struct {
inner: ?*c.Fl_Slider,
pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) Valuator {
const ptr = c.Fl_Slider_new(x, y, w, h, title);
if (ptr == null) unreachable;
return Valuator{
.inner = ptr,
};
}
pub fn raw(self: *Valuator) ?*c.Fl_Slider {
return self.inner;
}
pub fn fromRaw(ptr: ?*c.Fl_Slider) Valuator {
return Valuator{
.inner = ptr,
};
}
pub fn fromWidgetPtr(w: widget.WidgetPtr) Valuator {
return Valuator{
.inner = @ptrCast(?*c.Fl_Slider, w),
};
}
pub fn fromVoidPtr(ptr: ?*c_void) Valuator {
return Valuator{
.inner = @ptrCast(?*c.Fl_Slider, ptr),
};
}
pub fn toVoidPtr(self: *Valuator) ?*c_void {
return @ptrCast(?*c_void, self.inner);
}
pub fn asWidget(self: *const Valuator) widget.Widget {
return widget.Widget{
.inner = @ptrCast(widget.WidgetPtr, self.inner),
};
}
pub fn handle(self: *Valuator, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void {
c.Fl_Slider_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data);
}
pub fn draw(self: *Valuator, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void {
c.Fl_Slider_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data);
}
/// Set bounds of a valuator
pub fn setBounds(self: *Valuator, a: f64, b: f64) void {
return c.Fl_Slider_set_bounds(self.inner, a, b);
}
/// Get the minimum bound of a valuator
pub fn minimum(self: *const Valuator) f64 {
return c.Fl_Slider_minimum(self.inner);
}
/// Set the minimum bound of a valuator
pub fn setMinimum(self: *Valuator, a: f64) void {
return c.Fl_Slider_set_minimum(self.inner, a);
}
/// Get the maximum bound of a valuator
pub fn maximum(self: *const Valuator) f64 {
return c.Fl_Slider_maximum(self.inner);
}
/// Set the maximum bound of a valuator
pub fn setMaximum(self: *Valuator, a: f64) void {
return c.Fl_Slider_set_maximum(self.inner, a);
}
/// Set the range of a valuator
pub fn setRange(self: *Valuator, a: f64, b: f64) void {
return c.Fl_Slider_set_range(self.inner, a, b);
}
/// Set change step of a valuator
pub fn setStep(self: *Valuator, a: f64, b: i32) void {
return c.Fl_Slider_set_step(self.inner, a, b);
}
/// Get change step of a valuator
pub fn step(self: *const Valuator) f64 {
return c.Fl_Slider_step(self.inner);
}
/// Set the precision of a valuator
pub fn setPrecision(self: *Valuator, digits: i32) void {
return c.Fl_Slider_set_precision(self.inner, digits);
}
/// Get the value of a valuator
pub fn value(self: *const Valuator) f64 {
return c.Fl_Slider_value(self.inner);
}
/// Set the value of a valuator
pub fn setValue(self: *Valuator, arg2: f64) void {
return c.Fl_Slider_set_value(self.inner, arg2);
}
/// Set the format of a valuator
pub fn format(self: *Valuator, arg2: [*c]const u8) void {
return c.Fl_Slider_format(self.inner, arg2);
}
/// Round the valuator
pub fn round(self: *const Valuator, arg2: f64) f64 {
return c.Fl_Slider_round(self.inner, arg2);
}
/// Clamp the valuator
pub fn clamp(self: *const Valuator, arg2: f64) f64 {
return c.Fl_Slider_clamp(self.inner, arg2);
}
/// Increment the valuator
pub fn increment(self: *Valuator, arg2: f64, arg3: i32) f64 {
return c.Fl_Slider_increment(self.inner, arg2, arg3);
}
};
pub const SliderType = enum(i32) {
/// Vertical slider
Vertical = 0,
/// Horizontal slider
Horizontal = 1,
/// Vertical fill slider
VerticalFill = 2,
/// Horizontal fill slider
HorizontalFill = 3,
/// Vertical nice slider
VerticalNice = 4,
/// Horizontal nice slider
HorizontalNice = 5,
};
pub const Slider = struct {
inner: ?*c.Fl_Slider,
pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) Slider {
const ptr = c.Fl_Slider_new(x, y, w, h, title);
if (ptr == null) unreachable;
return Slider{
.inner = ptr,
};
}
pub fn raw(self: *Slider) ?*c.Fl_Slider {
return self.inner;
}
pub fn fromRaw(ptr: ?*c.Fl_Slider) Slider {
return Slider{
.inner = ptr,
};
}
pub fn fromWidgetPtr(w: widget.WidgetPtr) Slider {
return Slider{
.inner = @ptrCast(?*c.Fl_Slider, w),
};
}
pub fn fromVoidPtr(ptr: ?*c_void) Slider {
return Slider{
.inner = @ptrCast(?*c.Fl_Slider, ptr),
};
}
pub fn toVoidPtr(self: *Slider) ?*c_void {
return @ptrCast(?*c_void, self.inner);
}
pub fn asWidget(self: *const Slider) widget.Widget {
return widget.Widget{
.inner = @ptrCast(widget.WidgetPtr, self.inner),
};
}
pub fn asValuator(self: *const Slider) Valuator {
return Valuator{
.inner = @ptrCast(?*c.Fl_Slider, self.inner),
};
}
pub fn handle(self: *Slider, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void {
c.Fl_Slider_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data);
}
pub fn draw(self: *Slider, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void {
c.Fl_Slider_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data);
}
};
pub const DialType = enum(i32) {
/// Normal dial
Normal = 0,
/// Line dial
Line = 1,
/// Filled dial
Fill = 2,
};
pub const Dial = struct {
inner: ?*c.Fl_Dial,
pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) Dial {
const ptr = c.Fl_Dial_new(x, y, w, h, title);
if (ptr == null) unreachable;
return Dial{
.inner = ptr,
};
}
pub fn raw(self: *Dial) ?*c.Fl_Dial {
return self.inner;
}
pub fn fromRaw(ptr: ?*c.Fl_Dial) Dial {
return Dial{
.inner = ptr,
};
}
pub fn fromWidgetPtr(w: widget.WidgetPtr) Dial {
return Dial{
.inner = @ptrCast(?*c.Fl_Dial, w),
};
}
pub fn fromVoidPtr(ptr: ?*c_void) Dial {
return Dial{
.inner = @ptrCast(?*c.Fl_Dial, ptr),
};
}
pub fn toVoidPtr(self: *Dial) ?*c_void {
return @ptrCast(?*c_void, self.inner);
}
pub fn asWidget(self: *const Dial) widget.Widget {
return widget.Widget{
.inner = @ptrCast(widget.WidgetPtr, self.inner),
};
}
pub fn asValuator(self: *const Dial) Valuator {
return Valuator{
.inner = @ptrCast(?*c.Fl_Dial, self.inner),
};
}
pub fn handle(self: *Dial, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void {
c.Fl_Dial_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data);
}
pub fn draw(self: *Dial, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void {
c.Fl_Dial_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data);
}
};
pub const CounterType = enum(i32) {
/// Normal counter
Normal = 0,
/// Simple counter
Simple = 1,
};
pub const Counter = struct {
inner: ?*c.Fl_Counter,
pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) Counter {
const ptr = c.Fl_Counter_new(x, y, w, h, title);
if (ptr == null) unreachable;
return Counter{
.inner = ptr,
};
}
pub fn raw(self: *Counter) ?*c.Fl_Counter {
return self.inner;
}
pub fn fromRaw(ptr: ?*c.Fl_Counter) Counter {
return Counter{
.inner = ptr,
};
}
pub fn fromWidgetPtr(w: widget.WidgetPtr) Counter {
return Counter{
.inner = @ptrCast(?*c.Fl_Counter, w),
};
}
pub fn fromVoidPtr(ptr: ?*c_void) Counter {
return Counter{
.inner = @ptrCast(?*c.Fl_Counter, ptr),
};
}
pub fn toVoidPtr(self: *Counter) ?*c_void {
return @ptrCast(?*c_void, self.inner);
}
pub fn asWidget(self: *const Counter) widget.Widget {
return widget.Widget{
.inner = @ptrCast(widget.WidgetPtr, self.inner),
};
}
pub fn asValuator(self: *const Counter) Valuator {
return Valuator{
.inner = @ptrCast(?*c.Fl_Counter, self.inner),
};
}
pub fn handle(self: *Counter, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void {
c.Fl_Counter_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data);
}
pub fn draw(self: *Counter, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void {
c.Fl_Counter_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data);
}
};
pub const ScrollbarType = enum(i32) {
/// Vertical scrollbar
Vertical = 0,
/// Horizontal scrollbar
Horizontal = 1,
/// Vertical fill scrollbar
VerticalFill = 2,
/// Horizontal fill scrollbar
HorizontalFill = 3,
/// Vertical nice scrollbar
VerticalNice = 4,
/// Horizontal nice scrollbar
HorizontalNice = 5,
};
pub const Scrollbar = struct {
inner: ?*c.Fl_Scrollbar,
pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) Scrollbar {
const ptr = c.Fl_Scrollbar_new(x, y, w, h, title);
if (ptr == null) unreachable;
return Scrollbar{
.inner = ptr,
};
}
pub fn raw(self: *Scrollbar) ?*c.Fl_Scrollbar {
return self.inner;
}
pub fn fromRaw(ptr: ?*c.Fl_Scrollbar) Scrollbar {
return Scrollbar{
.inner = ptr,
};
}
pub fn fromWidgetPtr(w: widget.WidgetPtr) Scrollbar {
return Scrollbar{
.inner = @ptrCast(?*c.Fl_Scrollbar, w),
};
}
pub fn fromVoidPtr(ptr: ?*c_void) Scrollbar {
return Scrollbar{
.inner = @ptrCast(?*c.Fl_Scrollbar, ptr),
};
}
pub fn toVoidPtr(self: *Scrollbar) ?*c_void {
return @ptrCast(?*c_void, self.inner);
}
pub fn asWidget(self: *const Scrollbar) widget.Widget {
return widget.Widget{
.inner = @ptrCast(widget.WidgetPtr, self.inner),
};
}
pub fn asValuator(self: *const Scrollbar) Valuator {
return Valuator{
.inner = @ptrCast(?*c.Fl_Scrollbar, self.inner),
};
}
pub fn handle(self: *Scrollbar, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void {
c.Fl_Scrollbar_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data);
}
pub fn draw(self: *Scrollbar, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void {
c.Fl_Scrollbar_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data);
}
};
pub const Adjuster = struct {
inner: ?*c.Fl_Adjuster,
pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) Adjuster {
const ptr = c.Fl_Adjuster_new(x, y, w, h, title);
if (ptr == null) unreachable;
return Adjuster{
.inner = ptr,
};
}
pub fn raw(self: *Adjuster) ?*c.Fl_Adjuster {
return self.inner;
}
pub fn fromRaw(ptr: ?*c.Fl_Adjuster) Adjuster {
return Adjuster{
.inner = ptr,
};
}
pub fn fromWidgetPtr(w: widget.WidgetPtr) Adjuster {
return Adjuster{
.inner = @ptrCast(?*c.Fl_Adjuster, w),
};
}
pub fn fromVoidPtr(ptr: ?*c_void) Adjuster {
return Adjuster{
.inner = @ptrCast(?*c.Fl_Adjuster, ptr),
};
}
pub fn toVoidPtr(self: *Adjuster) ?*c_void {
return @ptrCast(?*c_void, self.inner);
}
pub fn asWidget(self: *const Adjuster) widget.Widget {
return widget.Widget{
.inner = @ptrCast(widget.WidgetPtr, self.inner),
};
}
pub fn asValuator(self: *const Adjuster) Valuator {
return Valuator{
.inner = @ptrCast(?*c.Fl_Adjuster, self.inner),
};
}
pub fn handle(self: *Adjuster, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void {
c.Fl_Adjuster_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data);
}
pub fn draw(self: *Adjuster, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void {
c.Fl_Adjuster_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data);
}
};
pub const Roller = struct {
inner: ?*c.Fl_Roller,
pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) Roller {
const ptr = c.Fl_Roller_new(x, y, w, h, title);
if (ptr == null) unreachable;
return Roller{
.inner = ptr,
};
}
pub fn raw(self: *Roller) ?*c.Fl_Roller {
return self.inner;
}
pub fn fromRaw(ptr: ?*c.Fl_Roller) Roller {
return Roller{
.inner = ptr,
};
}
pub fn fromWidgetPtr(w: widget.WidgetPtr) Roller {
return Roller{
.inner = @ptrCast(?*c.Fl_Roller, w),
};
}
pub fn fromVoidPtr(ptr: ?*c_void) Roller {
return Roller{
.inner = @ptrCast(?*c.Fl_Roller, ptr),
};
}
pub fn toVoidPtr(self: *Roller) ?*c_void {
return @ptrCast(?*c_void, self.inner);
}
pub fn asWidget(self: *const Roller) widget.Widget {
return widget.Widget{
.inner = @ptrCast(widget.WidgetPtr, self.inner),
};
}
pub fn asValuator(self: *const Roller) Valuator {
return Valuator{
.inner = @ptrCast(?*c.Fl_Roller, self.inner),
};
}
pub fn handle(self: *Roller, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void {
c.Fl_Roller_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data);
}
pub fn draw(self: *Roller, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void {
c.Fl_Roller_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data);
}
};
test "" {
@import("std").testing.refAllDecls(@This());
} | src/valuator.zig |
const std = @import("std");
const ArrayList = std.ArrayList;
const Allocator = std.mem.Allocator;
const bog = @import("bog.zig");
const Vm = bog.Vm;
const Errors = bog.Errors;
pub fn run(gpa: *Allocator, reader: anytype, writer: anytype) !void {
var vm = Vm.init(gpa, .{ .repl = true, .import_files = true });
defer vm.deinit();
var arena = std.heap.ArenaAllocator.init(gpa);
defer arena.deinit();
var module = bog.Compiler.Fn{
.code = bog.Compiler.Code.init(gpa),
.captures = undefined,
};
defer module.code.deinit();
var repl = try Repl.init(gpa, &vm, &module, &arena);
defer repl.deinit();
while (true) {
defer {
arena.deinit();
arena = std.heap.ArenaAllocator.init(gpa);
}
repl.handleLine(reader, writer) catch |err| switch (err) {
error.EndOfStream => return,
error.TokenizeError, error.ParseError, error.CompileError => try repl.vm.errors.render(repl.buffer.items, writer),
error.RuntimeError => {
(try repl.vm.gc.stackRef(0)).* = &bog.Value.None;
try repl.vm.errors.render(repl.buffer.items, writer);
},
else => |e| return e,
};
}
}
pub const Repl = struct {
vm: *Vm,
buffer: ArrayList(u8),
tokenizer: bog.Tokenizer,
compiler: bog.Compiler,
tok_index: bog.Token.Index = 0,
const tokenize = @import("tokenizer.zig").tokenizeRepl;
const parse = @import("parser.zig").parseRepl;
const compile = @import("compiler.zig").compileRepl;
fn init(gpa: *Allocator, vm: *Vm, mod: *bog.Compiler.Fn, arena: *std.heap.ArenaAllocator) !Repl {
const buffer = try ArrayList(u8).initCapacity(gpa, std.mem.page_size);
errdefer buffer.deinit();
try vm.addStd();
var scopes = std.ArrayList(bog.Compiler.Scope).init(gpa);
errdefer scopes.deinit();
try scopes.append(.{ .module = mod });
try scopes.append(.{
.symbol = .{
.name = "ans",
.reg = mod.regAlloc() catch unreachable,
.mut = false,
},
});
return Repl{
.compiler = .{
.source = "",
.tokens = &[0]bog.Token{},
.errors = &vm.errors,
.gpa = gpa,
.scopes = scopes,
.func = mod,
.arena = &arena.allocator,
.module_code = bog.Compiler.Code.init(gpa),
.strings = std.ArrayList(u8).init(gpa),
.string_interner = std.StringHashMap(u32).init(gpa),
},
.vm = vm,
.buffer = buffer,
.tokenizer = .{
.tokens = bog.Token.List.init(gpa),
.errors = &vm.errors,
.it = .{
.i = 0,
.bytes = "",
},
.repl = true,
},
};
}
fn deinit(repl: *Repl) void {
repl.buffer.deinit();
repl.tokenizer.tokens.deinit();
repl.compiler.deinit();
}
fn handleLine(repl: *Repl, reader: anytype, writer: anytype) !void {
try repl.readLine(">>> ", reader, writer);
while (!(try repl.tokenize())) {
try repl.readLine("... ", reader, writer);
}
const node = (try repl.parse()) orelse return;
var mod = try repl.compile(node);
repl.vm.ip = mod.entry;
const res = try repl.vm.exec(&mod);
(try repl.vm.gc.stackRef(0)).* = res;
if (res.* == .none) return;
try res.dump(writer, 2);
try writer.writeByte('\n');
}
fn readLine(repl: *Repl, prompt: []const u8, reader: anytype, writer: anytype) !void {
try writer.writeAll(prompt);
const start_len = repl.buffer.items.len;
while (true) {
var byte: u8 = reader.readByte() catch |e| switch (e) {
error.EndOfStream => if (start_len == repl.buffer.items.len) {
try writer.writeAll(std.cstr.line_sep);
return error.EndOfStream;
} else continue,
else => |err| return err,
};
try repl.buffer.append(byte);
if (byte == '\n') {
return;
}
if (repl.buffer.items.len - start_len == 1024) {
return error.StreamTooLong;
}
}
}
}; | src/repl.zig |
const std = @import("std");
const testing = std.testing;
const CircBuf = struct {
head: usize = 0,
tail: usize = 0,
buf: [*]u8 = null,
buf_len: usize = 0,
const Error = error{
InvalidParam,
Empty,
};
pub fn init(buf: [*]u8, buf_len: usize) CircBuf {
std.debug.assert(buf_len != 0);
return CircBuf{
.head = 0,
.tail = 0,
.buf = buf,
.buf_len = buf_len,
};
}
pub fn push(self: *CircBuf, data: u8) void {
self.buf[self.head] = data;
self.incHead();
if (self.head == self.tail) {
self.incTail();
}
}
fn incTail(self: *CircBuf) void {
self.tail = (self.tail + 1) % self.buf_len;
}
fn incHead(self: *CircBuf) void {
self.head = (self.head + 1) % self.buf_len;
}
pub fn pop(self: *CircBuf) CircBuf.Error!u8 {
if (self.empty()) {
return CircBuf.Error.Empty;
}
const data: u8 = self.buf[self.tail];
self.incTail();
return data;
}
pub fn empty(self: CircBuf) bool {
return self.head == self.tail;
}
pub fn full(self: *CircBuf) bool {
if (self.tail == 0) {
return (self.tail == 0) and (self.head == self.buf_len - 1);
}
return self.head == self.tail - 1;
}
};
test "circ buf init sets values" {
var data: [256]u8 = undefined;
const cb = CircBuf.init(&data, data.len);
try testing.expect(cb.head == 0);
try testing.expect(cb.tail == 0);
try testing.expect(cb.buf == &data);
try testing.expect(cb.buf_len == data.len);
}
test "circ buf push adds a byte" {
var data: [5]u8 = undefined;
var cb = CircBuf.init(&data, data.len);
try testing.expect(cb.head == 0);
try testing.expect(cb.empty());
try testing.expect(!cb.full());
cb.push(10);
try testing.expect(cb.head == 1);
try testing.expect(cb.tail == 0);
try testing.expect(cb.buf[0] == 10);
try testing.expect(!cb.empty());
try testing.expect(!cb.full());
cb.push(20);
try testing.expect(cb.head == 2);
try testing.expect(cb.tail == 0);
try testing.expect(cb.buf[1] == 20);
try testing.expect(!cb.empty());
try testing.expect(!cb.full());
cb.push(30);
try testing.expect(cb.head == 3);
try testing.expect(cb.tail == 0);
try testing.expect(cb.buf[2] == 30);
try testing.expect(!cb.empty());
try testing.expect(!cb.full());
cb.push(40);
try testing.expect(cb.head == 4);
try testing.expect(cb.tail == 0);
try testing.expect(cb.buf[3] == 40);
try testing.expect(!cb.empty());
try testing.expect(cb.full());
// Loops around, now needs to bump tail since it dropped a datum
cb.push(50);
try testing.expect(cb.head == 0);
try testing.expect(cb.tail == 1);
try testing.expect(cb.buf[4] == 50);
try testing.expect(!cb.empty());
try testing.expect(cb.full());
cb.push(60);
try testing.expect(cb.head == 1);
try testing.expect(cb.tail == 2);
try testing.expect(cb.buf[0] == 60);
try testing.expect(!cb.empty());
try testing.expect(cb.full());
}
test "circbuf pop returns a datum" {
var data: [5]u8 = undefined;
var cb = CircBuf.init(&data, data.len);
if (cb.pop()) |byte| {
_ = byte;
unreachable;
} else |err| {
try testing.expect(err == CircBuf.Error.Empty);
}
cb.push(100);
try testing.expect(cb.head == 1);
try testing.expect(cb.tail == 0);
const datum = cb.pop() catch 0;
try testing.expect(datum == 100);
try testing.expect(cb.head == 1);
try testing.expect(cb.tail == 1);
try testing.expect(cb.empty());
cb.push(20);
cb.push(30);
cb.push(40);
cb.push(50);
try testing.expect(cb.full());
try testing.expect(cb.head == 0);
try testing.expect(cb.tail == 1);
const boop = [_]u8{ 20, 30, 40, 50 };
for (boop) |x| {
const b = cb.pop() catch 0;
try testing.expect(b == x);
}
try testing.expect(cb.empty());
try testing.expect(cb.head == 0);
try testing.expect(cb.tail == 0);
} | circbuf/u8_circbuf.zig |
const zigvale = @import("zigvale").v2;
// Allocate a stack
// We add an extra bit in the form of a null terminator at the end, which allows us to point to the end of the stack
export var stack_bytes: [16 * 1024:0]u8 align(16) linksection(".bss") = undefined;
// This is the stivale2 header. Contained in the ELF section named '.stivale2hdr', it is detected
// by a stivale2-compatible bootloader, and provides the stack pointer, flags, tags, and entry point.
export const header linksection(".stivale2hdr") = zigvale.Header{
// The stack address for when the kernel is loaded. On x86, the stack grows downwards, and so
// we pass a pointer to the top of the stack.
.stack = &stack_bytes[stack_bytes.len],
// These flags communicate options to the bootloader
.flags = .{
// Tells the bootloader that this is a higher half kernel
.higher_half = 1,
// Tells the bootloader to enable protected memory ranges (PMRs)
.pmr = 1,
},
// Pointer to the first in a linked list of tags.
// Tags communicate to the bootloader various options which your kernel requires.
.tags = &term_tag.tag,
.entry_point = entry,
};
// This tag tells the bootloader to set up a terminal for your kernel to use
const term_tag = zigvale.Header.TerminalTag{
.tag = .{ .identifier = .terminal, .next = &fb_tag.tag },
};
// This tag tells the bootloader to select the best possible video mode
const fb_tag = zigvale.Header.FramebufferTag{};
// This generates the entry point for your kernel.
// Note: this function is not exported as `_start` -- the kernel in-fact has no entry point.
// Stivale2-compatible bootloaders are capable of using the pointer to the 'entry point' in
// zigvale.Header. This has the benefit of allowing you to add support for multiple bootloader
// protocols, without entry points conflicting with one another.
const entry = zigvale.entryPoint(kmain);
// This is the definition of your main kernel function.
// The generated entry point passes the parsed stivale2 structure.
fn kmain(stivale_info: zigvale.Struct.Parsed) noreturn {
if (stivale_info.terminal) |term| {
term.print("Hello, world from Zig {}!\n", .{@import("builtin").zig_version});
}
// Halts the kernel after execution
halt();
}
fn halt() noreturn {
// Loop in case an interrupt resumes execution
while (true) {
asm volatile ("hlt");
}
} | src/kernel.zig |
const std = @import("std");
const debug = std.debug;
const math = std.math;
const mem = std.mem;
const testing = std.testing;
/// Tests that an iterator returns all the items in the `expected`
/// slice, and no more.
pub fn testIt(_it: anytype, hint: LengthHint, expected: anytype) !void {
var it = iterator(_it);
if (@hasDecl(@TypeOf(it), "len_hint"))
try testing.expectEqual(hint, _it.len_hint());
for (expected) |item|
try testing.expectEqual(item, it.next().?);
try testing.expect(it.next() == null);
}
fn Return(comptime F: type) type {
return @typeInfo(F).Fn.return_type.?;
}
fn ReturnOpt(comptime F: type) type {
return @typeInfo(Return(F)).Optional.child;
}
fn Predicate(comptime It: type) type {
return fn (Result(It)) bool;
}
fn Predicate2(comptime Ctx: type, comptime It: type) type {
return fn (Ctx, Result(It)) bool;
}
fn Compare(comptime It: type) type {
return fn (Result(It), Result(It)) bool;
}
fn Compare2(comptime Ctx: type, comptime It: type) type {
return fn (Ctx, Result(It), Result(It)) bool;
}
/// Get the type of the items an iterator iterates over.
pub fn Result(comptime It: type) type {
return ReturnOpt(@TypeOf(Iterator(It).next));
}
pub const LengthHint = struct {
min: usize = 0,
max: ?usize = null,
pub fn len(hint: LengthHint) ?usize {
const max = hint.max orelse return null;
return if (hint.min == max) max else null;
}
pub fn add(a: LengthHint, b: LengthHint) LengthHint {
return .{
.min = a.min + b.min,
.max = blk: {
const a_max = a.max orelse break :blk null;
const b_max = b.max orelse break :blk null;
break :blk a_max + b_max;
},
};
}
};
/// You see, we don't have ufc and an iterator interface using free functions
/// is kinda painful and hard to read:
/// ```
/// const it = filter(span("aaa"), fn(a:u8){ return a == 0: });
/// ```
/// This is an attempt at emulating ufc by having all iterators have one function called
/// `call`. With that function, you could build iterators like this:
/// ```
/// const it = span("aaa")
/// .pipe(filter, .{ fn(a: u8){ return a == 0; } });
/// ```
pub fn pipeMethod(
it: anytype,
func: anytype,
args: anytype,
) @TypeOf(@call(.{}, func, .{@TypeOf(it.*){}} ++ @as(@TypeOf(args), undefined))) {
return @call(.{}, func, .{it.*} ++ args);
}
///////////////////////////////////////////////////////////
// The functions creates iterators from other data types //
///////////////////////////////////////////////////////////
pub fn Iterator(comptime T: type) type {
switch (@typeInfo(T)) {
.Pointer => |info| switch (info.size) {
.One, .Slice => return Deref(Span(mem.Span(T))),
else => {},
},
.Enum, .Union, .Struct => {
if (@hasDecl(T, "next"))
return T;
if (@hasDecl(T, "iterator") and @hasDecl(T, "Iterator"))
return T.Iterator;
},
else => {},
}
@compileError("Could not get an iterator from type '" ++ @typeName(T) ++ "'");
}
/// Given a value, this function will attempt to construct an iterator from the value.
/// * Slices and array pointers will give you a `Span` iterator
/// * Any value with a `iterator` method will give you the iterator that method returns.
/// * Any value with a `next` method will be considered an iterator and just returned.
pub fn iterator(value: anytype) Iterator(@TypeOf(value)) {
const T = @TypeOf(value);
switch (@typeInfo(T)) {
.Pointer => |info| switch (info.size) {
.One, .Slice => return span(value),
else => {},
},
.Enum, .Union, .Struct => {
if (@hasDecl(T, "iterator") and @hasDecl(T, "Iterator"))
return value.iterator();
if (@hasDecl(T, "next"))
return value;
},
else => {},
}
}
pub fn Range(comptime T: type) type {
return struct {
start: T = 0,
end: T = 0,
step: T = 1,
pub fn next(it: *@This()) ?T {
if (it.end <= it.start)
return null;
defer it.start += it.step;
return it.start;
}
pub fn len_hint(it: @This()) LengthHint {
const diff = math.sub(T, it.end, it.start) catch 0;
const len = diff / it.step + @boolToInt(diff % it.step != 0);
return .{ .min = len, .max = len };
}
pub const pipe = pipeMethod;
};
}
/// Same as `rangeEx` with 1 passed to the `step` paramter.
pub fn range(comptime T: type, start: T, end: T) Range(T) {
return rangeEx(T, start, end, 1);
}
/// Creates an iterator that iterates from `start` to `end` exclusively
/// with a step size of `step`.
pub fn rangeEx(comptime T: type, start: T, end: T, step: T) Range(T) {
debug.assert(start <= end and step != 0);
return .{ .start = start, .end = end, .step = step };
}
test "range" {
try testIt(range(u8, 'a', 'd'), .{ .min = 3, .max = 3 }, "abc");
try testIt(rangeEx(u8, 'a', 'd', 2), .{ .min = 2, .max = 2 }, "ac");
try testIt(rangeEx(u8, 'a', 'd', 3), .{ .min = 1, .max = 1 }, "a");
}
pub fn Span(comptime S: type) type {
const Array = @Type(.{
.Array = .{
.child = @typeInfo(S).Pointer.child,
.sentinel = @typeInfo(S).Pointer.sentinel,
.len = 0,
},
});
return struct {
span: S = &Array{},
// HACK: Cannot use &it.span[0] here
// --------------------------------vvvvvvvvvvvvvvvvvvvvvvvvv
pub fn next(it: *@This()) ?@TypeOf(&@intToPtr(*S, 0x10).*[0]) {
if (it.span.len == 0)
return null;
defer it.span = it.span[1..];
return &it.span[0];
}
pub fn len_hint(it: @This()) LengthHint {
return .{ .min = it.span.len, .max = it.span.len };
}
pub const pipe = pipeMethod;
};
}
/// Creates an iterator that iterates over all the items of an array or slice.
pub fn span(s: anytype) Deref(Span(mem.Span(@TypeOf(s)))) {
return deref(spanByRef(s));
}
test "span" {
const items = "abcd";
try testIt(span(items[0..]), .{ .min = 4, .max = 4 }, items[0..]);
try testIt(span(items[1..]), .{ .min = 3, .max = 3 }, items[1..]);
try testIt(span(items[2..]), .{ .min = 2, .max = 2 }, items[2..]);
try testIt(span(items[3..]), .{ .min = 1, .max = 1 }, items[3..]);
try testIt(span(items[4..]), .{ .min = 0, .max = 0 }, items[4..]);
}
/// Creates an iterator that iterates over all the items of an array or slice
/// by reference.
pub fn spanByRef(s: anytype) Span(mem.Span(@TypeOf(s))) {
return .{ .span = mem.span(s) };
}
comptime {
const c = "a".*;
var v = "a".*;
var sc = spanByRef(&c);
var sv = spanByRef(&v);
debug.assert(@TypeOf(sc.next()) == ?*const u8);
debug.assert(@TypeOf(sv.next()) == ?*u8);
}
test "spanByRef" {
const items = "abcd";
const refs = &[_]*const u8{ &items[0], &items[1], &items[2], &items[3] };
try testIt(spanByRef(items[0..]), .{ .min = 4, .max = 4 }, refs[0..]);
try testIt(spanByRef(items[1..]), .{ .min = 3, .max = 3 }, refs[1..]);
try testIt(spanByRef(items[2..]), .{ .min = 2, .max = 2 }, refs[2..]);
try testIt(spanByRef(items[3..]), .{ .min = 1, .max = 1 }, refs[3..]);
try testIt(spanByRef(items[4..]), .{ .min = 0, .max = 0 }, refs[4..]);
}
//////////////////////////////////////////////////////////
// The functions creates iterators from other iterators //
//////////////////////////////////////////////////////////
pub fn Chain(comptime First: type, comptime Second: type) type {
return struct {
first: First = First{},
second: Second = Second{},
pub fn next(it: *@This()) ?Result(First) {
return it.first.next() orelse it.second.next();
}
pub fn len_hint(it: @This()) LengthHint {
if (!@hasDecl(First, "len_hint") or !@hasDecl(Second, "len_hint"))
return .{};
return LengthHint.add(
it.first.len_hint(),
it.second.len_hint(),
);
}
pub const pipe = pipeMethod;
};
}
/// Creates an iterator that first iterates over all items in `first` after
/// which it iterates over all elements in `second`.
pub fn chain(first: anytype, second: anytype) Chain(
Iterator(@TypeOf(first)),
Iterator(@TypeOf(second)),
) {
return .{ .first = iterator(first), .second = iterator(second) };
}
test "chain" {
try testIt(chain("abc", "def"), .{ .min = 6, .max = 6 }, "abcdef");
try testIt(chain("", "def"), .{ .min = 3, .max = 3 }, "def");
try testIt(chain("abc", ""), .{ .min = 3, .max = 3 }, "abc");
try testIt(chain("", ""), .{ .min = 0, .max = 0 }, "");
}
pub fn Deref(comptime Child: type) type {
return Map(void, Child, @typeInfo(Result(Child)).Pointer.child);
}
/// Creates an iterator which derefs all of the items it iterates over.
pub fn deref(it: anytype) Deref(Iterator(@TypeOf(it))) {
const It = @TypeOf(it);
return mapEx(it, {}, struct {
fn transform(_: void, ptr: Result(It)) Result(Deref(It)) {
return ptr.*;
}
}.transform);
}
test "deref" {
try testIt(spanByRef("abcd").pipe(deref, .{}), .{ .min = 4, .max = 4 }, "abcd");
}
pub fn Enumerate(comptime I: type, comptime Child: type) type {
return struct {
index: I = 0,
child: Child = Child{},
pub const Res = struct {
index: I,
item: Result(Child),
};
pub fn next(it: *@This()) ?Res {
const item = it.child.next() orelse return null;
const index = it.index;
it.index += 1;
return Res{ .index = index, .item = item };
}
pub fn len_hint(it: @This()) LengthHint {
if (!@hasDecl(Child, "len_hint"))
return .{};
return it.child.len_hint();
}
pub const pipe = pipeMethod;
};
}
/// Same as `enumerateEx` but with `usize` passed as the second parameter.
pub fn enumerate(it: anytype) Enumerate(usize, Iterator(@TypeOf(it))) {
return enumerateEx(it, usize);
}
/// Creates an iterator that gives the item index as well as the item.
pub fn enumerateEx(it: anytype, comptime I: type) Enumerate(I, Iterator(@TypeOf(it))) {
return .{ .child = iterator(it) };
}
test "enumerate" {
var it = enumerate("ab");
try testing.expectEqual(LengthHint{ .min = 2, .max = 2 }, it.len_hint());
var i: usize = 0;
while (it.next()) |item| : (i += 1) {
try testing.expectEqual(@as(usize, i), item.index);
try testing.expectEqual(@as(u8, "ab"[i]), item.item);
}
}
pub fn ErrInner(comptime Child: type) type {
const err_union = @typeInfo(Return(@TypeOf(Child.next))).ErrorUnion;
const Error = err_union.error_set;
const Res = @typeInfo(err_union.payload).Optional.child;
return struct {
child: Child = Child{},
pub fn next(it: *@This()) ?(Error!Res) {
const res = it.child.next() catch |err| return err;
return res orelse return null;
}
pub fn len_hint(it: @This()) LengthHint {
if (!@hasDecl(Child, "len_hint"))
return .{};
return it.child.len_hint();
}
pub const pipe = pipeMethod;
};
}
/// Takes an iterator that returns `Error!?T` and makes it into an iterator
/// take returns `?(Error!T)`.
pub fn errInner(it: anytype) ErrInner(Iterator(@TypeOf(it))) {
return .{ .child = iterator(it) };
}
test "errInner" {
const Dummy = struct {
const Error = error{A};
num: usize = 0,
fn next(it: *@This()) Error!?u8 {
defer it.num += 1;
switch (it.num) {
0 => return 0,
1 => return error.A,
else => return null,
}
}
};
const i = errInner(Dummy{});
try testIt(i, .{}, &[_](Dummy.Error!u8){ 0, error.A });
}
pub fn FilterMap(comptime Context: type, comptime Child: type, comptime T: type) type {
return struct {
child: Child = Child{},
ctx: Context = undefined,
transform: fn (Context, Result(Child)) ?T = undefined,
pub fn next(it: *@This()) ?T {
while (it.child.next()) |item| {
if (it.transform(it.ctx, item)) |res|
return res;
}
return null;
}
pub fn len_hint(it: @This()) LengthHint {
if (!@hasDecl(Child, "len_hint"))
return .{};
return .{ .min = 0, .max = it.child.len_hint().max };
}
pub const pipe = pipeMethod;
};
}
/// Same as `filterMapEx` but requires no context.
pub fn filterMap(
it: anytype,
transform: anytype,
) FilterMap(@TypeOf(transform), Iterator(@TypeOf(it)), ReturnOpt(@TypeOf(transform))) {
const Iter = Iterator(@TypeOf(it));
const Res = Result(Iter);
const Trans = @TypeOf(transform);
return filterMapEx(it, transform, struct {
fn wrapper(trans: Trans, item: Res) Return(Trans) {
return trans(item);
}
}.wrapper);
}
/// Creates an iterator that transforms and filters out items the `transform` function.
pub fn filterMapEx(
it: anytype,
ctx: anytype,
transform: anytype,
) FilterMap(@TypeOf(ctx), Iterator(@TypeOf(it)), ReturnOpt(@TypeOf(transform))) {
return .{ .child = iterator(it), .ctx = ctx, .transform = transform };
}
test "filterMap" {
const F = struct {
fn even_double(i: u8) ?u16 {
if (i % 2 != 0)
return null;
return i * 2;
}
};
const i = range(u8, 0, 10) //
.pipe(filterMap, .{F.even_double});
try testIt(i, .{ .min = 0, .max = 10 }, &[_]u16{ 0, 4, 8, 12, 16 });
}
pub fn Filter(comptime Context: type, comptime Child: type) type {
return struct {
child: Child = Child{},
ctx: Context = undefined,
pred: Predicate2(Context, Child) = undefined,
pub fn next(it: *@This()) ?Result(Child) {
while (it.child.next()) |item| {
if (it.pred(it.ctx, item))
return item;
}
return null;
}
pub fn len_hint(it: @This()) LengthHint {
if (!@hasDecl(Child, "len_hint"))
return .{};
return .{ .min = 0, .max = it.child.len_hint().max };
}
pub const pipe = pipeMethod;
};
}
/// Same as `filterEx` but requires no context.
pub fn filter(
it: anytype,
pred: Predicate(@TypeOf(it)),
) Filter(Predicate(@TypeOf(it)), Iterator(@TypeOf(it))) {
const Iter = Iterator(@TypeOf(it));
const Res = Result(Iter);
const Pred = fn (Res) bool;
return filterEx(it, pred, struct {
fn wrapper(p: Pred, item: Res) bool {
return p(item);
}
}.wrapper);
}
/// Creates an iterator that filters out items that does not match
/// the predicate `pred`.
pub fn filterEx(
it: anytype,
ctx: anytype,
pred: Predicate2(@TypeOf(ctx), @TypeOf(it)),
) Filter(@TypeOf(ctx), Iterator(@TypeOf(it))) {
return .{ .child = iterator(it), .ctx = ctx, .pred = pred };
}
test "filter" {
try testIt(filter("a1b2", std.ascii.isDigit), .{ .min = 0, .max = 4 }, "12");
try testIt(filter("a1b2", std.ascii.isAlpha), .{ .min = 0, .max = 4 }, "ab");
try testIt(filter("aaabb", std.ascii.isDigit), .{ .min = 0, .max = 5 }, "");
}
pub fn InterLeave(comptime First: type, comptime Second: type) type {
return struct {
first: First = First{},
second: Second = Second{},
flag: enum { first, second } = .first,
pub fn next(it: *@This()) ?Result(First) {
defer it.flag = if (it.flag == .first) .second else .first;
return switch (it.flag) {
.first => it.first.next() orelse it.second.next(),
.second => it.second.next() orelse it.first.next(),
};
}
pub fn len_hint(it: @This()) LengthHint {
if (!@hasDecl(First, "len_hint") or !@hasDecl(Second, "len_hint"))
return .{};
return LengthHint.add(
it.first.len_hint(),
it.second.len_hint(),
);
}
pub const pipe = pipeMethod;
};
}
/// Creates an iterator switches between calling `first.next` and `second.next`.
pub fn interleave(
first: anytype,
second: anytype,
) InterLeave(Iterator(@TypeOf(first)), Iterator(@TypeOf(second))) {
return .{ .first = iterator(first), .second = iterator(second) };
}
test "interleave" {
try testIt(interleave("abc", "def"), .{ .min = 6, .max = 6 }, "adbecf");
try testIt(interleave("", "def"), .{ .min = 3, .max = 3 }, "def");
try testIt(interleave("abc", ""), .{ .min = 3, .max = 3 }, "abc");
try testIt(interleave("", ""), .{ .min = 0, .max = 0 }, "");
}
pub fn Map(comptime Context: type, comptime Child: type, comptime T: type) type {
return struct {
child: Child = Child{},
ctx: Context = undefined,
transform: fn (Context, Result(Child)) T = undefined,
pub fn next(it: *@This()) ?T {
return it.transform(it.ctx, it.child.next() orelse return null);
}
pub fn len_hint(it: @This()) LengthHint {
if (!@hasDecl(Child, "len_hint"))
return .{};
return it.child.len_hint();
}
pub const pipe = pipeMethod;
};
}
/// Same as `mapEx` but requires no context.
pub fn map(
it: anytype,
transform: anytype,
) Map(@TypeOf(transform), Iterator(@TypeOf(it)), Return(@TypeOf(transform))) {
const Iter = Iterator(@TypeOf(it));
const Res = Result(Iter);
const Trans = @TypeOf(transform);
return mapEx(it, transform, struct {
fn wrapper(trans: Trans, item: Res) Return(Trans) {
return trans(item);
}
}.wrapper);
}
/// Creates an iterator that transforms all items using the `transform` function.
pub fn mapEx(
it: anytype,
ctx: anytype,
transform: anytype,
) Map(@TypeOf(ctx), Iterator(@TypeOf(it)), Return(@TypeOf(transform))) {
return .{ .child = iterator(it), .ctx = ctx, .transform = transform };
}
test "map" {
const m1 = map("abcd", std.ascii.toUpper);
try testIt(m1, .{ .min = 4, .max = 4 }, "ABCD");
const m2 = map("", std.ascii.toUpper);
try testIt(m2, .{ .min = 0, .max = 0 }, "");
}
pub fn SlidingWindow(comptime Child: type, comptime window: usize) type {
return struct {
prev: ?[window]T = null,
child: Child = Child{},
const T = Result(Child);
pub fn next(it: *@This()) ?[window]T {
if (it.prev) |*prev| {
mem.copy(T, prev, prev[1..]);
prev[window - 1] = it.child.next() orelse return null;
return it.prev;
} else {
it.prev = [_]Result(Child){undefined} ** window;
for (it.prev.?) |*item|
item.* = it.child.next() orelse return null;
return it.prev;
}
}
pub fn len_hint(it: @This()) LengthHint {
if (!@hasDecl(Child, "len_hint"))
return .{};
const child = it.child.len_hint();
return .{
.min = math.sub(usize, child.min, window - 1) catch 0,
.max = blk: {
const max = child.max orelse break :blk null;
break :blk math.sub(usize, max, window - 1) catch 0;
},
};
}
pub const pipe = pipeMethod;
};
}
/// Creates an iterator that iterates over the provided iterator and
/// returns a window into the elements of the iterator, and slides
/// that window along:
/// ```
/// span("abcde")
/// .pipe(slidingWindow, {3}) = "abc"
/// "bcd"
/// "cde"
/// ```
pub fn slidingWindow(
it: anytype,
comptime window: usize,
) SlidingWindow(Iterator(@TypeOf(it)), window) {
return .{ .child = iterator(it) };
}
test "slidingWindow" {
const s1 = slidingWindow("abcd", 2);
try testIt(s1, .{ .min = 3, .max = 3 }, [_][2]u8{ "ab".*, "bc".*, "cd".* });
const s2 = slidingWindow("abcd", 3);
try testIt(s2, .{ .min = 2, .max = 2 }, [_][3]u8{ "abc".*, "bcd".* });
}
pub fn Repeat(comptime Child: type) type {
return struct {
reset: Child = Child{},
curr: Child = Child{},
pub fn next(it: *@This()) ?Result(Child) {
if (it.curr.next()) |res|
return res;
it.curr = it.reset;
return it.curr.next();
}
pub fn len_hint(it: @This()) LengthHint {
if (!@hasDecl(Child, "len_hint"))
return .{};
const child = it.reset.len_hint();
const min = child.min;
const max = child.max orelse std.math.maxInt(usize);
return .{
.min = min,
.max = if (min == 0 and max == 0) 0 else null,
};
}
pub const pipe = pipeMethod;
};
}
/// Creates an iterator that keeps repeating the items returned from the
/// child iterator, never returning `null` unless the child iterator returns
/// no items, in which case `repeat` always returns `null`.
pub fn repeat(it: anytype) Repeat(Iterator(@TypeOf(it))) {
return .{ .reset = iterator(it), .curr = iterator(it) };
}
test "repeat" {
var it = repeat("ab");
try testing.expectEqual(LengthHint{ .min = 2, .max = null }, it.len_hint());
try testing.expect(it.next().? == 'a');
try testing.expect(it.next().? == 'b');
try testing.expect(it.next().? == 'a');
try testing.expect(it.next().? == 'b');
try testing.expect(it.next().? == 'a');
try testing.expect(it.next().? == 'b');
}
/// Skips `n` iterations of `it` and return it.
pub fn skip(_it: anytype, _n: usize) Iterator(@TypeOf(_it)) {
var n = _n;
var it = iterator(_it);
while (n != 0) : (n -= 1)
_ = it.next();
return it;
}
test "skip" {
const i = skip("abcd", 2);
try testIt(i, .{ .min = 2, .max = 2 }, "cd");
}
pub fn TakeWhile(comptime Context: type, comptime Child: type) type {
return struct {
child: Child = Child{},
ctx: Context = undefined,
pred: Predicate2(Context, Child) = undefined,
pub fn next(it: *@This()) ?Result(Child) {
const item = it.child.next() orelse return null;
return if (it.pred(it.ctx, item)) item else null;
}
pub fn len_hint(it: @This()) LengthHint {
if (!@hasDecl(Child, "len_hint"))
return .{};
return .{ .min = 0, .max = it.child.len_hint().max };
}
pub const pipe = pipeMethod;
};
}
/// Same as `takeWhile` but requires no context.
pub fn takeWhile(
it: anytype,
pred: Predicate(@TypeOf(it)),
) TakeWhile(Predicate(@TypeOf(it)), Iterator(@TypeOf(it))) {
const Res = Result(@TypeOf(it));
const Pred = Predicate(@TypeOf(it));
return takeWhileEx(it, pred, struct {
fn wrapper(p: Pred, item: Res) bool {
return p(item);
}
}.wrapper);
}
/// Creates an iterator that takes values from the child iterator so long
/// as they matches the predicate `pred`. When the predicate is no longer
/// satisfied, the iterator will return null.
pub fn takeWhileEx(
it: anytype,
ctx: anytype,
pred: Predicate2(@TypeOf(ctx), @TypeOf(it)),
) TakeWhile(@TypeOf(ctx), Iterator(@TypeOf(it))) {
return .{ .child = iterator(it), .ctx = ctx, .pred = pred };
}
test "takeWhile" {
const tw = takeWhile("abCD", std.ascii.isLower);
try testIt(tw, .{ .min = 0, .max = 4 }, "ab");
}
pub fn Take(comptime Child: type) type {
return struct {
child: Child = Child{},
n: usize = 0,
pub fn next(it: *@This()) ?Result(Child) {
if (it.n == 0)
return null;
defer it.n -= 1;
return it.child.next();
}
pub fn len_hint(it: @This()) LengthHint {
if (!@hasDecl(Child, "len_hint"))
return .{ .max = it.n };
return .{ .min = math.min(it.n, it.child.len_hint().min), .max = it.n };
}
pub const pipe = pipeMethod;
};
}
/// Creates an iterator that takes at most `n` items from the child iterator.
pub fn take(it: anytype, n: usize) Take(Iterator(@TypeOf(it))) {
return .{ .child = iterator(it), .n = n };
}
test "take" {
try testIt(take("abCD", 1), .{ .min = 1, .max = 1 }, "a");
try testIt(take("abCD", 2), .{ .min = 2, .max = 2 }, "ab");
try testIt(take("abCD", 3), .{ .min = 3, .max = 3 }, "abC");
}
pub fn Dedup(comptime Context: type, comptime Child: type) type {
const Res = Result(Child);
return struct {
child: Child = Child{},
ctx: Context = undefined,
eql: fn (Context, Res, Res) bool = undefined,
prev: ?Res = null,
pub fn next(it: *@This()) ?Res {
var prev = it.prev orelse {
it.prev = it.child.next();
return it.prev;
};
var curr = it.child.next() orelse return null;
while (it.eql(it.ctx, prev, curr)) {
prev = curr;
curr = it.child.next() orelse return null;
}
it.prev = curr;
return curr;
}
pub fn len_hint(it: @This()) LengthHint {
if (!@hasDecl(Child, "len_hint"))
return .{};
return .{ .min = 0, .max = it.child.len_hint().max };
}
pub const pipe = pipeMethod;
};
}
/// Removes dublicates from consectutive identical results using
/// `eql` to determin if two results are identical.
pub fn dedup(it: anytype) Dedup(Compare(@TypeOf(it)), Iterator(@TypeOf(it))) {
const Iter = Iterator(@TypeOf(it));
const Res = Result(Iter);
return dedupEx(it, struct {
fn eql(a: Res, b: Res) bool {
return a == b;
}
}.eql);
}
/// Removes dublicates from consectutive identical results using
/// `eql` to determin if two results are identical.
pub fn dedupEx(
it: anytype,
eql: Compare(@TypeOf(it)),
) Dedup(Compare(@TypeOf(it)), Iterator(@TypeOf(it))) {
const Res = Result(@TypeOf(it));
const Eql = Compare(@TypeOf(it));
return dedupEx2(it, eql, struct {
fn eql(func: Eql, a: Res, b: Res) bool {
return func(a, b);
}
}.eql);
}
/// Removes dublicates from consectutive identical results using
/// `eql` to determin if two results are identical.
pub fn dedupEx2(
it: anytype,
ctx: anytype,
eql: Compare2(@TypeOf(ctx), @TypeOf(it)),
) Dedup(@TypeOf(ctx), Iterator(@TypeOf(it))) {
return .{ .child = iterator(it), .ctx = ctx, .eql = eql };
}
test "dedup" {
const dd = dedup("aaabbcccdd");
try testIt(dd, .{ .min = 0, .max = 10 }, "abcd");
const dd2 = dedupEx(&[_][]const u8{ "aa", "AA", "ba", "BA" }, std.ascii.eqlIgnoreCase);
try testIt(dd2, .{ .min = 0, .max = 4 }, &[_][]const u8{ "aa", "ba" });
}
pub fn Unwrap(comptime Child: type) type {
const err_union = @typeInfo(Result(Child)).ErrorUnion;
const Error = err_union.error_set;
const Res = err_union.payload;
return struct {
child: Child = Child{},
last_err: Error!void = {},
pub fn next(it: *@This()) ?Res {
const errun = it.child.next() orelse return null;
return errun catch |err| {
it.last_err = err;
return null;
};
}
pub fn len_hint(it: @This()) LengthHint {
if (!@hasDecl(Child, "len_hint"))
return .{};
return it.child.len_hint();
}
pub const pipe = pipeMethod;
};
}
/// Creates an iterator that returns `null` on the first error returned
/// from the child iterator. The child iterator is expected to return
/// `?(Error!T)`. The error returned will be stored in a field called
/// `last_err`.
pub fn unwrap(it: anytype) Unwrap(Iterator(@TypeOf(it))) {
return .{ .child = iterator(it) };
}
test "unwrap" {
const Dummy = struct {
const Error = error{A};
num: usize = 0,
fn next(it: *@This()) ?(Error!u8) {
defer it.num += 1;
switch (it.num) {
// Without all these `@as` we get:
// broken LLVM module found: Operand is null
// call fastcc void @__zig_return_error(<null operand!>), !dbg !6394
0 => return @as(?(Error!u8), @as(Error!u8, 0)),
1 => return @as(?(Error!u8), @as(Error!u8, error.A)),
else => return null,
}
}
};
var i = unwrap(Dummy{});
try testing.expectEqual(@as(?u8, 0), i.next());
try testing.expectEqual(@as(?u8, null), i.next());
try testing.expectEqual(@as(Dummy.Error!void, error.A), i.last_err);
}
/////////////////////////////////////////////////////////////////
// The functions below iterates over iterators to get a result //
/////////////////////////////////////////////////////////////////
/// Same as `allEx` but requires no context.
pub fn all(it: anytype, pred: Predicate(@TypeOf(it))) bool {
const Iter = Iterator(@TypeOf(it));
const Res = Result(Iter);
const Pred = fn (Res) bool;
return allEx(it, pred, struct {
fn wrapper(p: Pred, res: Res) bool {
return p(res);
}
}.wrapper);
}
/// Check that all items in an iterator matches a predicate.
pub fn allEx(
_it: anytype,
ctx: anytype,
pred: Predicate2(@TypeOf(ctx), @TypeOf(_it)),
) bool {
var it = iterator(_it);
while (it.next()) |item| {
if (!pred(ctx, item))
return false;
}
return true;
}
test "all" {
try testing.expect(all("aaa", std.ascii.isLower));
try testing.expect(!all("Aaa", std.ascii.isLower));
}
/// Same as `anyEx` but requires no context.
pub fn any(it: anytype, pred: Predicate(@TypeOf(it))) bool {
const Res = Result(@TypeOf(it));
const Pred = Predicate(@TypeOf(it));
return anyEx(it, pred, struct {
fn wrapper(p: Pred, res: Res) bool {
return p(res);
}
}.wrapper);
}
/// Check that any items in an iterator matches a predicate.
pub fn anyEx(
it: anytype,
ctx: anytype,
pred: Predicate2(@TypeOf(ctx), @TypeOf(it)),
) bool {
return findEx(it, ctx, pred) != null;
}
test "any" {
try testing.expect(any("aAA", std.ascii.isLower));
try testing.expect(!any("AAA", std.ascii.isLower));
}
pub fn collect(
_it: anytype,
allocator: mem.Allocator,
) mem.Allocator.Error![]Result(@TypeOf(_it)) {
var it = iterator(_it);
var res = std.ArrayList(Result(@TypeOf(it))).init(allocator);
errdefer res.deinit();
if (@hasDecl(@TypeOf(it), "len_hint"))
try res.ensureTotalCapacity(it.len_hint().min);
while (it.next()) |item|
try res.append(item);
return res.items;
}
test "collect" {
const collected = try collect("abcd", testing.allocator);
defer testing.allocator.free(collected);
try testing.expectEqualSlices(u8, "abcd", collected);
const collected_range = try range(usize, 0, 5) //
.pipe(collect, .{testing.allocator});
defer testing.allocator.free(collected_range);
try testing.expectEqualSlices(usize, &[_]usize{ 0, 1, 2, 3, 4 }, collected_range);
}
/// Counts the number of iterations before an iterator returns `null`.
pub fn count(_it: anytype) usize {
var it = iterator(_it);
if (@hasDecl(@TypeOf(it), "len_hint")) {
if (it.len_hint().len()) |len|
return len;
}
var res: usize = 0;
while (it.next()) |_|
res += 1;
return res;
}
test "count" {
try testing.expectEqual(@as(usize, 0), count(""));
try testing.expectEqual(@as(usize, 1), count("a"));
try testing.expectEqual(@as(usize, 2), count("aa"));
}
/// Same as `findEx` but requires no context.
pub fn find(it: anytype, pred: Predicate(@TypeOf(it))) ?Result(@TypeOf(it)) {
const Res = Result(@TypeOf(it));
const Pred = Predicate(@TypeOf(it));
return findEx(it, pred, struct {
fn wrapper(p: Pred, res: Res) bool {
return p(res);
}
}.wrapper);
}
/// Gets the first item in an iterator that satiesfies the predicate.
pub fn findEx(
_it: anytype,
ctx: anytype,
pred: Predicate2(@TypeOf(ctx), @TypeOf(_it)),
) ?Result(@TypeOf(_it)) {
var it = iterator(_it);
while (it.next()) |item| {
if (pred(ctx, item))
return item;
}
return null;
}
test "find" {
try testing.expect(find("aAA", std.ascii.isLower).? == 'a');
try testing.expect(find("AAA", std.ascii.isLower) == null);
}
/// Same as `foldEx` but requires no context.
pub fn fold(
it: anytype,
init: anytype,
f: fn (@TypeOf(init), Result(@TypeOf(it))) @TypeOf(init),
) @TypeOf(init) {
const Res = Result(@TypeOf(it));
const Init = @TypeOf(init);
const Func = fn (Init, Res) Init;
return foldEx(it, init, f, struct {
fn wrapper(func: Func, acc: Init, item: Res) Init {
return func(acc, item);
}
}.wrapper);
}
/// Iterates over an iterator to get a single resulting value. This result is aquired
/// by starting with the value of `init` and calling the function `f` on all result +
/// item pairs, reassing the result to the return value of `f` on each iteration. Once
/// all items have been iterated over the result is returned.
pub fn foldEx(
_it: anytype,
init: anytype,
ctx: anytype,
f: fn (@TypeOf(ctx), @TypeOf(init), Result(@TypeOf(_it))) @TypeOf(init),
) @TypeOf(init) {
var res = init;
var it = iterator(_it);
while (it.next()) |item|
res = f(ctx, res, item);
return res;
}
test "fold" {
const add = struct {
fn add(a: u8, b: u8) u8 {
return a + b;
}
}.add;
const r1 = rangeEx(u8, 2, 8, 2);
const r2 = range(u8, 0, 0);
try testing.expectEqual(@as(u8, 12), r1.pipe(fold, .{ @as(u8, 0), add }));
try testing.expectEqual(@as(u8, 0), r2.pipe(fold, .{ @as(u8, 0), add }));
}
/////////////////////////////////////////////////////
// Tests that std iterators also works with ziter. //
/////////////////////////////////////////////////////
// test "mem.split" {
// const eql = struct {
// fn eql(comptime c: []const u8) fn ([]const u8) bool {
// return struct {
// fn e(str: []const u8) bool {
// return mem.eql(u8, str, c);
// }
// }.e;
// }
// }.eql;
// const it = take(mem.split("a\nab\nabc\ncc", "\n"), 3);
// try testing.expect(any(it, eql("abc")));
// try testing.expect(any(it, eql("a")));
// try testing.expect(any(it, eql("ab")));
// try testing.expect(any(it, eql("abc")));
// try testing.expect(!any(it, eql("cc")));
// } | ziter.zig |
const std = @import("std.zig");
const builtin = @import("builtin");
const assert = std.debug.assert;
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
const mem = std.mem;
const math = std.math;
const ziggurat = @import("rand/ziggurat.zig");
const maxInt = std.math.maxInt;
// When you need fast unbiased random numbers
pub const DefaultPrng = Xoroshiro128;
// When you need cryptographically secure random numbers
pub const DefaultCsprng = Isaac64;
pub const Random = struct {
fillFn: fn (r: *Random, buf: []u8) void,
/// Read random bytes into the specified buffer until full.
pub fn bytes(r: *Random, buf: []u8) void {
r.fillFn(r, buf);
}
pub fn boolean(r: *Random) bool {
return r.int(u1) != 0;
}
/// Returns a random int `i` such that `0 <= i <= maxInt(T)`.
/// `i` is evenly distributed.
pub fn int(r: *Random, comptime T: type) T {
const UnsignedT = std.meta.Int(false, T.bit_count);
const ByteAlignedT = std.meta.Int(false, @divTrunc(T.bit_count + 7, 8) * 8);
var rand_bytes: [@sizeOf(ByteAlignedT)]u8 = undefined;
r.bytes(rand_bytes[0..]);
// use LE instead of native endian for better portability maybe?
// TODO: endian portability is pointless if the underlying prng isn't endian portable.
// TODO: document the endian portability of this library.
const byte_aligned_result = mem.readIntSliceLittle(ByteAlignedT, &rand_bytes);
const unsigned_result = @truncate(UnsignedT, byte_aligned_result);
return @bitCast(T, unsigned_result);
}
/// Constant-time implementation off `uintLessThan`.
/// The results of this function may be biased.
pub fn uintLessThanBiased(r: *Random, comptime T: type, less_than: T) T {
comptime assert(T.is_signed == false);
comptime assert(T.bit_count <= 64); // TODO: workaround: LLVM ERROR: Unsupported library call operation!
assert(0 < less_than);
if (T.bit_count <= 32) {
return @intCast(T, limitRangeBiased(u32, r.int(u32), less_than));
} else {
return @intCast(T, limitRangeBiased(u64, r.int(u64), less_than));
}
}
/// Returns an evenly distributed random unsigned integer `0 <= i < less_than`.
/// This function assumes that the underlying `fillFn` produces evenly distributed values.
/// Within this assumption, the runtime of this function is exponentially distributed.
/// If `fillFn` were backed by a true random generator,
/// the runtime of this function would technically be unbounded.
/// However, if `fillFn` is backed by any evenly distributed pseudo random number generator,
/// this function is guaranteed to return.
/// If you need deterministic runtime bounds, use `uintLessThanBiased`.
pub fn uintLessThan(r: *Random, comptime T: type, less_than: T) T {
comptime assert(T.is_signed == false);
comptime assert(T.bit_count <= 64); // TODO: workaround: LLVM ERROR: Unsupported library call operation!
assert(0 < less_than);
// Small is typically u32
const Small = std.meta.Int(false, @divTrunc(T.bit_count + 31, 32) * 32);
// Large is typically u64
const Large = std.meta.Int(false, Small.bit_count * 2);
// adapted from:
// http://www.pcg-random.org/posts/bounded-rands.html
// "Lemire's (with an extra tweak from me)"
var x: Small = r.int(Small);
var m: Large = @as(Large, x) * @as(Large, less_than);
var l: Small = @truncate(Small, m);
if (l < less_than) {
// TODO: workaround for https://github.com/ziglang/zig/issues/1770
// should be:
// var t: Small = -%less_than;
var t: Small = @bitCast(Small, -%@bitCast(std.meta.Int(true, Small.bit_count), @as(Small, less_than)));
if (t >= less_than) {
t -= less_than;
if (t >= less_than) {
t %= less_than;
}
}
while (l < t) {
x = r.int(Small);
m = @as(Large, x) * @as(Large, less_than);
l = @truncate(Small, m);
}
}
return @intCast(T, m >> Small.bit_count);
}
/// Constant-time implementation off `uintAtMost`.
/// The results of this function may be biased.
pub fn uintAtMostBiased(r: *Random, comptime T: type, at_most: T) T {
assert(T.is_signed == false);
if (at_most == maxInt(T)) {
// have the full range
return r.int(T);
}
return r.uintLessThanBiased(T, at_most + 1);
}
/// Returns an evenly distributed random unsigned integer `0 <= i <= at_most`.
/// See `uintLessThan`, which this function uses in most cases,
/// for commentary on the runtime of this function.
pub fn uintAtMost(r: *Random, comptime T: type, at_most: T) T {
assert(T.is_signed == false);
if (at_most == maxInt(T)) {
// have the full range
return r.int(T);
}
return r.uintLessThan(T, at_most + 1);
}
/// Constant-time implementation off `intRangeLessThan`.
/// The results of this function may be biased.
pub fn intRangeLessThanBiased(r: *Random, comptime T: type, at_least: T, less_than: T) T {
assert(at_least < less_than);
if (T.is_signed) {
// Two's complement makes this math pretty easy.
const UnsignedT = std.meta.Int(false, T.bit_count);
const lo = @bitCast(UnsignedT, at_least);
const hi = @bitCast(UnsignedT, less_than);
const result = lo +% r.uintLessThanBiased(UnsignedT, hi -% lo);
return @bitCast(T, result);
} else {
// The signed implementation would work fine, but we can use stricter arithmetic operators here.
return at_least + r.uintLessThanBiased(T, less_than - at_least);
}
}
/// Returns an evenly distributed random integer `at_least <= i < less_than`.
/// See `uintLessThan`, which this function uses in most cases,
/// for commentary on the runtime of this function.
pub fn intRangeLessThan(r: *Random, comptime T: type, at_least: T, less_than: T) T {
assert(at_least < less_than);
if (T.is_signed) {
// Two's complement makes this math pretty easy.
const UnsignedT = std.meta.Int(false, T.bit_count);
const lo = @bitCast(UnsignedT, at_least);
const hi = @bitCast(UnsignedT, less_than);
const result = lo +% r.uintLessThan(UnsignedT, hi -% lo);
return @bitCast(T, result);
} else {
// The signed implementation would work fine, but we can use stricter arithmetic operators here.
return at_least + r.uintLessThan(T, less_than - at_least);
}
}
/// Constant-time implementation off `intRangeAtMostBiased`.
/// The results of this function may be biased.
pub fn intRangeAtMostBiased(r: *Random, comptime T: type, at_least: T, at_most: T) T {
assert(at_least <= at_most);
if (T.is_signed) {
// Two's complement makes this math pretty easy.
const UnsignedT = std.meta.Int(false, T.bit_count);
const lo = @bitCast(UnsignedT, at_least);
const hi = @bitCast(UnsignedT, at_most);
const result = lo +% r.uintAtMostBiased(UnsignedT, hi -% lo);
return @bitCast(T, result);
} else {
// The signed implementation would work fine, but we can use stricter arithmetic operators here.
return at_least + r.uintAtMostBiased(T, at_most - at_least);
}
}
/// Returns an evenly distributed random integer `at_least <= i <= at_most`.
/// See `uintLessThan`, which this function uses in most cases,
/// for commentary on the runtime of this function.
pub fn intRangeAtMost(r: *Random, comptime T: type, at_least: T, at_most: T) T {
assert(at_least <= at_most);
if (T.is_signed) {
// Two's complement makes this math pretty easy.
const UnsignedT = std.meta.Int(false, T.bit_count);
const lo = @bitCast(UnsignedT, at_least);
const hi = @bitCast(UnsignedT, at_most);
const result = lo +% r.uintAtMost(UnsignedT, hi -% lo);
return @bitCast(T, result);
} else {
// The signed implementation would work fine, but we can use stricter arithmetic operators here.
return at_least + r.uintAtMost(T, at_most - at_least);
}
}
pub const scalar = @compileError("deprecated; use boolean() or int() instead");
pub const range = @compileError("deprecated; use intRangeLessThan()");
/// Return a floating point value evenly distributed in the range [0, 1).
pub fn float(r: *Random, comptime T: type) T {
// Generate a uniform value between [1, 2) and scale down to [0, 1).
// Note: The lowest mantissa bit is always set to 0 so we only use half the available range.
switch (T) {
f32 => {
const s = r.int(u32);
const repr = (0x7f << 23) | (s >> 9);
return @bitCast(f32, repr) - 1.0;
},
f64 => {
const s = r.int(u64);
const repr = (0x3ff << 52) | (s >> 12);
return @bitCast(f64, repr) - 1.0;
},
else => @compileError("unknown floating point type"),
}
}
/// Return a floating point value normally distributed with mean = 0, stddev = 1.
///
/// To use different parameters, use: floatNorm(...) * desiredStddev + desiredMean.
pub fn floatNorm(r: *Random, comptime T: type) T {
const value = ziggurat.next_f64(r, ziggurat.NormDist);
switch (T) {
f32 => return @floatCast(f32, value),
f64 => return value,
else => @compileError("unknown floating point type"),
}
}
/// Return an exponentially distributed float with a rate parameter of 1.
///
/// To use a different rate parameter, use: floatExp(...) / desiredRate.
pub fn floatExp(r: *Random, comptime T: type) T {
const value = ziggurat.next_f64(r, ziggurat.ExpDist);
switch (T) {
f32 => return @floatCast(f32, value),
f64 => return value,
else => @compileError("unknown floating point type"),
}
}
/// Shuffle a slice into a random order.
pub fn shuffle(r: *Random, comptime T: type, buf: []T) void {
if (buf.len < 2) {
return;
}
var i: usize = 0;
while (i < buf.len - 1) : (i += 1) {
const j = r.intRangeLessThan(usize, i, buf.len);
mem.swap(T, &buf[i], &buf[j]);
}
}
};
/// Convert a random integer 0 <= random_int <= maxValue(T),
/// into an integer 0 <= result < less_than.
/// This function introduces a minor bias.
pub fn limitRangeBiased(comptime T: type, random_int: T, less_than: T) T {
comptime assert(T.is_signed == false);
const T2 = std.meta.Int(false, T.bit_count * 2);
// adapted from:
// http://www.pcg-random.org/posts/bounded-rands.html
// "Integer Multiplication (Biased)"
var m: T2 = @as(T2, random_int) * @as(T2, less_than);
return @intCast(T, m >> T.bit_count);
}
const SequentialPrng = struct {
const Self = @This();
random: Random,
next_value: u8,
pub fn init() Self {
return Self{
.random = Random{ .fillFn = fill },
.next_value = 0,
};
}
fn fill(r: *Random, buf: []u8) void {
const self = @fieldParentPtr(Self, "random", r);
for (buf) |*b| {
b.* = self.next_value;
}
self.next_value +%= 1;
}
};
test "Random int" {
testRandomInt();
comptime testRandomInt();
}
fn testRandomInt() void {
var r = SequentialPrng.init();
expect(r.random.int(u0) == 0);
r.next_value = 0;
expect(r.random.int(u1) == 0);
expect(r.random.int(u1) == 1);
expect(r.random.int(u2) == 2);
expect(r.random.int(u2) == 3);
expect(r.random.int(u2) == 0);
r.next_value = 0xff;
expect(r.random.int(u8) == 0xff);
r.next_value = 0x11;
expect(r.random.int(u8) == 0x11);
r.next_value = 0xff;
expect(r.random.int(u32) == 0xffffffff);
r.next_value = 0x11;
expect(r.random.int(u32) == 0x11111111);
r.next_value = 0xff;
expect(r.random.int(i32) == -1);
r.next_value = 0x11;
expect(r.random.int(i32) == 0x11111111);
r.next_value = 0xff;
expect(r.random.int(i8) == -1);
r.next_value = 0x11;
expect(r.random.int(i8) == 0x11);
r.next_value = 0xff;
expect(r.random.int(u33) == 0x1ffffffff);
r.next_value = 0xff;
expect(r.random.int(i1) == -1);
r.next_value = 0xff;
expect(r.random.int(i2) == -1);
r.next_value = 0xff;
expect(r.random.int(i33) == -1);
}
test "Random boolean" {
testRandomBoolean();
comptime testRandomBoolean();
}
fn testRandomBoolean() void {
var r = SequentialPrng.init();
expect(r.random.boolean() == false);
expect(r.random.boolean() == true);
expect(r.random.boolean() == false);
expect(r.random.boolean() == true);
}
test "Random intLessThan" {
@setEvalBranchQuota(10000);
testRandomIntLessThan();
comptime testRandomIntLessThan();
}
fn testRandomIntLessThan() void {
var r = SequentialPrng.init();
r.next_value = 0xff;
expect(r.random.uintLessThan(u8, 4) == 3);
expect(r.next_value == 0);
expect(r.random.uintLessThan(u8, 4) == 0);
expect(r.next_value == 1);
r.next_value = 0;
expect(r.random.uintLessThan(u64, 32) == 0);
// trigger the bias rejection code path
r.next_value = 0;
expect(r.random.uintLessThan(u8, 3) == 0);
// verify we incremented twice
expect(r.next_value == 2);
r.next_value = 0xff;
expect(r.random.intRangeLessThan(u8, 0, 0x80) == 0x7f);
r.next_value = 0xff;
expect(r.random.intRangeLessThan(u8, 0x7f, 0xff) == 0xfe);
r.next_value = 0xff;
expect(r.random.intRangeLessThan(i8, 0, 0x40) == 0x3f);
r.next_value = 0xff;
expect(r.random.intRangeLessThan(i8, -0x40, 0x40) == 0x3f);
r.next_value = 0xff;
expect(r.random.intRangeLessThan(i8, -0x80, 0) == -1);
r.next_value = 0xff;
expect(r.random.intRangeLessThan(i3, -4, 0) == -1);
r.next_value = 0xff;
expect(r.random.intRangeLessThan(i3, -2, 2) == 1);
}
test "Random intAtMost" {
@setEvalBranchQuota(10000);
testRandomIntAtMost();
comptime testRandomIntAtMost();
}
fn testRandomIntAtMost() void {
var r = SequentialPrng.init();
r.next_value = 0xff;
expect(r.random.uintAtMost(u8, 3) == 3);
expect(r.next_value == 0);
expect(r.random.uintAtMost(u8, 3) == 0);
// trigger the bias rejection code path
r.next_value = 0;
expect(r.random.uintAtMost(u8, 2) == 0);
// verify we incremented twice
expect(r.next_value == 2);
r.next_value = 0xff;
expect(r.random.intRangeAtMost(u8, 0, 0x7f) == 0x7f);
r.next_value = 0xff;
expect(r.random.intRangeAtMost(u8, 0x7f, 0xfe) == 0xfe);
r.next_value = 0xff;
expect(r.random.intRangeAtMost(i8, 0, 0x3f) == 0x3f);
r.next_value = 0xff;
expect(r.random.intRangeAtMost(i8, -0x40, 0x3f) == 0x3f);
r.next_value = 0xff;
expect(r.random.intRangeAtMost(i8, -0x80, -1) == -1);
r.next_value = 0xff;
expect(r.random.intRangeAtMost(i3, -4, -1) == -1);
r.next_value = 0xff;
expect(r.random.intRangeAtMost(i3, -2, 1) == 1);
expect(r.random.uintAtMost(u0, 0) == 0);
}
test "Random Biased" {
var r = DefaultPrng.init(0);
// Not thoroughly checking the logic here.
// Just want to execute all the paths with different types.
expect(r.random.uintLessThanBiased(u1, 1) == 0);
expect(r.random.uintLessThanBiased(u32, 10) < 10);
expect(r.random.uintLessThanBiased(u64, 20) < 20);
expect(r.random.uintAtMostBiased(u0, 0) == 0);
expect(r.random.uintAtMostBiased(u1, 0) <= 0);
expect(r.random.uintAtMostBiased(u32, 10) <= 10);
expect(r.random.uintAtMostBiased(u64, 20) <= 20);
expect(r.random.intRangeLessThanBiased(u1, 0, 1) == 0);
expect(r.random.intRangeLessThanBiased(i1, -1, 0) == -1);
expect(r.random.intRangeLessThanBiased(u32, 10, 20) >= 10);
expect(r.random.intRangeLessThanBiased(i32, 10, 20) >= 10);
expect(r.random.intRangeLessThanBiased(u64, 20, 40) >= 20);
expect(r.random.intRangeLessThanBiased(i64, 20, 40) >= 20);
// uncomment for broken module error:
//expect(r.random.intRangeAtMostBiased(u0, 0, 0) == 0);
expect(r.random.intRangeAtMostBiased(u1, 0, 1) >= 0);
expect(r.random.intRangeAtMostBiased(i1, -1, 0) >= -1);
expect(r.random.intRangeAtMostBiased(u32, 10, 20) >= 10);
expect(r.random.intRangeAtMostBiased(i32, 10, 20) >= 10);
expect(r.random.intRangeAtMostBiased(u64, 20, 40) >= 20);
expect(r.random.intRangeAtMostBiased(i64, 20, 40) >= 20);
}
// Generator to extend 64-bit seed values into longer sequences.
//
// The number of cycles is thus limited to 64-bits regardless of the engine, but this
// is still plenty for practical purposes.
const SplitMix64 = struct {
s: u64,
pub fn init(seed: u64) SplitMix64 {
return SplitMix64{ .s = seed };
}
pub fn next(self: *SplitMix64) u64 {
self.s +%= 0x9e3779b97f4a7c15;
var z = self.s;
z = (z ^ (z >> 30)) *% 0xbf58476d1ce4e5b9;
z = (z ^ (z >> 27)) *% 0x94d049bb133111eb;
return z ^ (z >> 31);
}
};
test "splitmix64 sequence" {
var r = SplitMix64.init(0xaeecf86f7878dd75);
const seq = [_]u64{
0x5dbd39db0178eb44,
0xa9900fb66b397da3,
0x5c1a28b1aeebcf5c,
0x64a963238f776912,
0xc6d4177b21d1c0ab,
0xb2cbdbdb5ea35394,
};
for (seq) |s| {
expect(s == r.next());
}
}
// PCG32 - http://www.pcg-random.org/
//
// PRNG
pub const Pcg = struct {
const default_multiplier = 6364136223846793005;
random: Random,
s: u64,
i: u64,
pub fn init(init_s: u64) Pcg {
var pcg = Pcg{
.random = Random{ .fillFn = fill },
.s = undefined,
.i = undefined,
};
pcg.seed(init_s);
return pcg;
}
fn next(self: *Pcg) u32 {
const l = self.s;
self.s = l *% default_multiplier +% (self.i | 1);
const xor_s = @truncate(u32, ((l >> 18) ^ l) >> 27);
const rot = @intCast(u32, l >> 59);
return (xor_s >> @intCast(u5, rot)) | (xor_s << @intCast(u5, (0 -% rot) & 31));
}
fn seed(self: *Pcg, init_s: u64) void {
// Pcg requires 128-bits of seed.
var gen = SplitMix64.init(init_s);
self.seedTwo(gen.next(), gen.next());
}
fn seedTwo(self: *Pcg, init_s: u64, init_i: u64) void {
self.s = 0;
self.i = (init_s << 1) | 1;
self.s = self.s *% default_multiplier +% self.i;
self.s +%= init_i;
self.s = self.s *% default_multiplier +% self.i;
}
fn fill(r: *Random, buf: []u8) void {
const self = @fieldParentPtr(Pcg, "random", r);
var i: usize = 0;
const aligned_len = buf.len - (buf.len & 7);
// Complete 4 byte segments.
while (i < aligned_len) : (i += 4) {
var n = self.next();
comptime var j: usize = 0;
inline while (j < 4) : (j += 1) {
buf[i + j] = @truncate(u8, n);
n >>= 8;
}
}
// Remaining. (cuts the stream)
if (i != buf.len) {
var n = self.next();
while (i < buf.len) : (i += 1) {
buf[i] = @truncate(u8, n);
n >>= 4;
}
}
}
};
test "pcg sequence" {
var r = Pcg.init(0);
const s0: u64 = 0x9394bf54ce5d79de;
const s1: u64 = 0x84e9c579ef59bbf7;
r.seedTwo(s0, s1);
const seq = [_]u32{
2881561918,
3063928540,
1199791034,
2487695858,
1479648952,
3247963454,
};
for (seq) |s| {
expect(s == r.next());
}
}
// Xoroshiro128+ - http://xoroshiro.di.unimi.it/
//
// PRNG
pub const Xoroshiro128 = struct {
random: Random,
s: [2]u64,
pub fn init(init_s: u64) Xoroshiro128 {
var x = Xoroshiro128{
.random = Random{ .fillFn = fill },
.s = undefined,
};
x.seed(init_s);
return x;
}
fn next(self: *Xoroshiro128) u64 {
const s0 = self.s[0];
var s1 = self.s[1];
const r = s0 +% s1;
s1 ^= s0;
self.s[0] = math.rotl(u64, s0, @as(u8, 55)) ^ s1 ^ (s1 << 14);
self.s[1] = math.rotl(u64, s1, @as(u8, 36));
return r;
}
// Skip 2^64 places ahead in the sequence
fn jump(self: *Xoroshiro128) void {
var s0: u64 = 0;
var s1: u64 = 0;
const table = [_]u64{
0xbeac0467eba5facb,
0xd86b048b86aa9922,
};
inline for (table) |entry| {
var b: usize = 0;
while (b < 64) : (b += 1) {
if ((entry & (@as(u64, 1) << @intCast(u6, b))) != 0) {
s0 ^= self.s[0];
s1 ^= self.s[1];
}
_ = self.next();
}
}
self.s[0] = s0;
self.s[1] = s1;
}
pub fn seed(self: *Xoroshiro128, init_s: u64) void {
// Xoroshiro requires 128-bits of seed.
var gen = SplitMix64.init(init_s);
self.s[0] = gen.next();
self.s[1] = gen.next();
}
fn fill(r: *Random, buf: []u8) void {
const self = @fieldParentPtr(Xoroshiro128, "random", r);
var i: usize = 0;
const aligned_len = buf.len - (buf.len & 7);
// Complete 8 byte segments.
while (i < aligned_len) : (i += 8) {
var n = self.next();
comptime var j: usize = 0;
inline while (j < 8) : (j += 1) {
buf[i + j] = @truncate(u8, n);
n >>= 8;
}
}
// Remaining. (cuts the stream)
if (i != buf.len) {
var n = self.next();
while (i < buf.len) : (i += 1) {
buf[i] = @truncate(u8, n);
n >>= 8;
}
}
}
};
test "xoroshiro sequence" {
var r = Xoroshiro128.init(0);
r.s[0] = 0xaeecf86f7878dd75;
r.s[1] = 0x01cd153642e72622;
const seq1 = [_]u64{
0xb0ba0da5bb600397,
0x18a08afde614dccc,
0xa2635b956a31b929,
0xabe633c971efa045,
0x9ac19f9706ca3cac,
0xf62b426578c1e3fb,
};
for (seq1) |s| {
expect(s == r.next());
}
r.jump();
const seq2 = [_]u64{
0x95344a13556d3e22,
0xb4fb32dafa4d00df,
0xb2011d9ccdcfe2dd,
0x05679a9b2119b908,
0xa860a1da7c9cd8a0,
0x658a96efe3f86550,
};
for (seq2) |s| {
expect(s == r.next());
}
}
// Gimli
//
// CSPRNG
pub const Gimli = struct {
random: Random,
state: std.crypto.core.Gimli,
pub fn init(init_s: u64) Gimli {
var self = Gimli{
.random = Random{ .fillFn = fill },
.state = std.crypto.core.Gimli{
.data = [_]u32{0} ** (std.crypto.gimli.State.BLOCKBYTES / 4),
},
};
self.state.data[0] = @truncate(u32, init_s >> 32);
self.state.data[1] = @truncate(u32, init_s);
return self;
}
fn fill(r: *Random, buf: []u8) void {
const self = @fieldParentPtr(Gimli, "random", r);
self.state.squeeze(buf);
}
};
// ISAAC64 - http://www.burtleburtle.net/bob/rand/isaacafa.html
//
// CSPRNG
//
// Follows the general idea of the implementation from here with a few shortcuts.
// https://doc.rust-lang.org/rand/src/rand/prng/isaac64.rs.html
pub const Isaac64 = struct {
random: Random,
r: [256]u64,
m: [256]u64,
a: u64,
b: u64,
c: u64,
i: usize,
pub fn init(init_s: u64) Isaac64 {
var isaac = Isaac64{
.random = Random{ .fillFn = fill },
.r = undefined,
.m = undefined,
.a = undefined,
.b = undefined,
.c = undefined,
.i = undefined,
};
// seed == 0 => same result as the unseeded reference implementation
isaac.seed(init_s, 1);
return isaac;
}
fn step(self: *Isaac64, mix: u64, base: usize, comptime m1: usize, comptime m2: usize) void {
const x = self.m[base + m1];
self.a = mix +% self.m[base + m2];
const y = self.a +% self.b +% self.m[@intCast(usize, (x >> 3) % self.m.len)];
self.m[base + m1] = y;
self.b = x +% self.m[@intCast(usize, (y >> 11) % self.m.len)];
self.r[self.r.len - 1 - base - m1] = self.b;
}
fn refill(self: *Isaac64) void {
const midpoint = self.r.len / 2;
self.c +%= 1;
self.b +%= self.c;
{
var i: usize = 0;
while (i < midpoint) : (i += 4) {
self.step(~(self.a ^ (self.a << 21)), i + 0, 0, midpoint);
self.step(self.a ^ (self.a >> 5), i + 1, 0, midpoint);
self.step(self.a ^ (self.a << 12), i + 2, 0, midpoint);
self.step(self.a ^ (self.a >> 33), i + 3, 0, midpoint);
}
}
{
var i: usize = 0;
while (i < midpoint) : (i += 4) {
self.step(~(self.a ^ (self.a << 21)), i + 0, midpoint, 0);
self.step(self.a ^ (self.a >> 5), i + 1, midpoint, 0);
self.step(self.a ^ (self.a << 12), i + 2, midpoint, 0);
self.step(self.a ^ (self.a >> 33), i + 3, midpoint, 0);
}
}
self.i = 0;
}
fn next(self: *Isaac64) u64 {
if (self.i >= self.r.len) {
self.refill();
}
const value = self.r[self.i];
self.i += 1;
return value;
}
fn seed(self: *Isaac64, init_s: u64, comptime rounds: usize) void {
// We ignore the multi-pass requirement since we don't currently expose full access to
// seeding the self.m array completely.
mem.set(u64, self.m[0..], 0);
self.m[0] = init_s;
// prescrambled golden ratio constants
var a = [_]u64{
0x647c4677a2884b7c,
0xb9f8b322c73ac862,
0x8c0ea5053d4712a0,
0xb29b2e824a595524,
0x82f053db8355e0ce,
0x48fe4a0fa5a09315,
0xae985bf2cbfc89ed,
0x98f5704f6c44c0ab,
};
comptime var i: usize = 0;
inline while (i < rounds) : (i += 1) {
var j: usize = 0;
while (j < self.m.len) : (j += 8) {
comptime var x1: usize = 0;
inline while (x1 < 8) : (x1 += 1) {
a[x1] +%= self.m[j + x1];
}
a[0] -%= a[4];
a[5] ^= a[7] >> 9;
a[7] +%= a[0];
a[1] -%= a[5];
a[6] ^= a[0] << 9;
a[0] +%= a[1];
a[2] -%= a[6];
a[7] ^= a[1] >> 23;
a[1] +%= a[2];
a[3] -%= a[7];
a[0] ^= a[2] << 15;
a[2] +%= a[3];
a[4] -%= a[0];
a[1] ^= a[3] >> 14;
a[3] +%= a[4];
a[5] -%= a[1];
a[2] ^= a[4] << 20;
a[4] +%= a[5];
a[6] -%= a[2];
a[3] ^= a[5] >> 17;
a[5] +%= a[6];
a[7] -%= a[3];
a[4] ^= a[6] << 14;
a[6] +%= a[7];
comptime var x2: usize = 0;
inline while (x2 < 8) : (x2 += 1) {
self.m[j + x2] = a[x2];
}
}
}
mem.set(u64, self.r[0..], 0);
self.a = 0;
self.b = 0;
self.c = 0;
self.i = self.r.len; // trigger refill on first value
}
fn fill(r: *Random, buf: []u8) void {
const self = @fieldParentPtr(Isaac64, "random", r);
var i: usize = 0;
const aligned_len = buf.len - (buf.len & 7);
// Fill complete 64-byte segments
while (i < aligned_len) : (i += 8) {
var n = self.next();
comptime var j: usize = 0;
inline while (j < 8) : (j += 1) {
buf[i + j] = @truncate(u8, n);
n >>= 8;
}
}
// Fill trailing, ignoring excess (cut the stream).
if (i != buf.len) {
var n = self.next();
while (i < buf.len) : (i += 1) {
buf[i] = @truncate(u8, n);
n >>= 8;
}
}
}
};
test "isaac64 sequence" {
var r = Isaac64.init(0);
// from reference implementation
const seq = [_]u64{
0xf67dfba498e4937c,
0x84a5066a9204f380,
0xfee34bd5f5514dbb,
0x4d1664739b8f80d6,
0x8607459ab52a14aa,
0x0e78bc5a98529e49,
0xfe5332822ad13777,
0x556c27525e33d01a,
0x08643ca615f3149f,
0xd0771faf3cb04714,
0x30e86f68a37b008d,
0x3074ebc0488a3adf,
0x270645ea7a2790bc,
0x5601a0a8d3763c6a,
0x2f83071f53f325dd,
0xb9090f3d42d2d2ea,
};
for (seq) |s| {
expect(s == r.next());
}
}
/// Sfc64 pseudo-random number generator from Practically Random.
/// Fastest engine of pracrand and smallest footprint.
/// See http://pracrand.sourceforge.net/
pub const Sfc64 = struct {
random: Random,
a: u64 = undefined,
b: u64 = undefined,
c: u64 = undefined,
counter: u64 = undefined,
const Rotation = 24;
const RightShift = 11;
const LeftShift = 3;
pub fn init(init_s: u64) Sfc64 {
var x = Sfc64{
.random = Random{ .fillFn = fill },
};
x.seed(init_s);
return x;
}
fn next(self: *Sfc64) u64 {
const tmp = self.a +% self.b +% self.counter;
self.counter += 1;
self.a = self.b ^ (self.b >> RightShift);
self.b = self.c +% (self.c << LeftShift);
self.c = math.rotl(u64, self.c, Rotation) +% tmp;
return tmp;
}
fn seed(self: *Sfc64, init_s: u64) void {
self.a = init_s;
self.b = init_s;
self.c = init_s;
self.counter = 1;
var i: u32 = 0;
while (i < 12) : (i += 1) {
_ = self.next();
}
}
fn fill(r: *Random, buf: []u8) void {
const self = @fieldParentPtr(Sfc64, "random", r);
var i: usize = 0;
const aligned_len = buf.len - (buf.len & 7);
// Complete 8 byte segments.
while (i < aligned_len) : (i += 8) {
var n = self.next();
comptime var j: usize = 0;
inline while (j < 8) : (j += 1) {
buf[i + j] = @truncate(u8, n);
n >>= 8;
}
}
// Remaining. (cuts the stream)
if (i != buf.len) {
var n = self.next();
while (i < buf.len) : (i += 1) {
buf[i] = @truncate(u8, n);
n >>= 8;
}
}
}
};
test "Sfc64 sequence" {
// Unfortunately there does not seem to be an official test sequence.
var r = Sfc64.init(0);
const seq = [_]u64{
0x3acfa029e3cc6041,
0xf5b6515bf2ee419c,
0x1259635894a29b61,
0xb6ae75395f8ebd6,
0x225622285ce302e2,
0x520d28611395cb21,
0xdb909c818901599d,
0x8ffd195365216f57,
0xe8c4ad5e258ac04a,
0x8f8ef2c89fdb63ca,
0xf9865b01d98d8e2f,
0x46555871a65d08ba,
0x66868677c6298fcd,
0x2ce15a7e6329f57d,
0xb2f1833ca91ca79,
0x4b0890ac9bf453ca,
};
for (seq) |s| {
expectEqual(s, r.next());
}
}
// Actual Random helper function tests, pcg engine is assumed correct.
test "Random float" {
var prng = DefaultPrng.init(0);
var i: usize = 0;
while (i < 1000) : (i += 1) {
const val1 = prng.random.float(f32);
expect(val1 >= 0.0);
expect(val1 < 1.0);
const val2 = prng.random.float(f64);
expect(val2 >= 0.0);
expect(val2 < 1.0);
}
}
test "Random shuffle" {
var prng = DefaultPrng.init(0);
var seq = [_]u8{ 0, 1, 2, 3, 4 };
var seen = [_]bool{false} ** 5;
var i: usize = 0;
while (i < 1000) : (i += 1) {
prng.random.shuffle(u8, seq[0..]);
seen[seq[0]] = true;
expect(sumArray(seq[0..]) == 10);
}
// we should see every entry at the head at least once
for (seen) |e| {
expect(e == true);
}
}
fn sumArray(s: []const u8) u32 {
var r: u32 = 0;
for (s) |e|
r += e;
return r;
}
test "Random range" {
var prng = DefaultPrng.init(0);
testRange(&prng.random, -4, 3);
testRange(&prng.random, -4, -1);
testRange(&prng.random, 10, 14);
testRange(&prng.random, -0x80, 0x7f);
}
fn testRange(r: *Random, start: i8, end: i8) void {
testRangeBias(r, start, end, true);
testRangeBias(r, start, end, false);
}
fn testRangeBias(r: *Random, start: i8, end: i8, biased: bool) void {
const count = @intCast(usize, @as(i32, end) - @as(i32, start));
var values_buffer = [_]bool{false} ** 0x100;
const values = values_buffer[0..count];
var i: usize = 0;
while (i < count) {
const value: i32 = if (biased) r.intRangeLessThanBiased(i8, start, end) else r.intRangeLessThan(i8, start, end);
const index = @intCast(usize, value - start);
if (!values[index]) {
i += 1;
values[index] = true;
}
}
}
test "" {
std.meta.refAllDecls(@This());
} | lib/std/rand.zig |
const std = @import("std");
const io = std.io;
const fs = std.fs;
const mem = std.mem;
const process = std.process;
const Allocator = mem.Allocator;
const ArrayList = std.ArrayList;
const ast = std.zig.ast;
const Module = @import("Module.zig");
const link = @import("link.zig");
const Package = @import("Package.zig");
const zir = @import("zir.zig");
// TODO Improve async I/O enough that we feel comfortable doing this.
//pub const io_mode = .evented;
pub const max_src_size = 2 * 1024 * 1024 * 1024; // 2 GiB
pub const Color = enum {
Auto,
Off,
On,
};
const usage =
\\Usage: zig [command] [options]
\\
\\Commands:
\\
\\ build-exe [source] Create executable from source or object files
\\ build-lib [source] Create library from source or object files
\\ build-obj [source] Create object from source or assembly
\\ fmt [source] Parse file and render in canonical zig format
\\ targets List available compilation targets
\\ version Print version number and exit
\\ zen Print zen of zig and exit
\\
\\
;
pub fn log(
comptime level: std.log.Level,
comptime scope: @TypeOf(.EnumLiteral),
comptime format: []const u8,
args: anytype,
) void {
if (@enumToInt(level) > @enumToInt(std.log.level))
return;
const scope_prefix = "(" ++ switch (scope) {
// Uncomment to hide logs
//.compiler,
.module,
.liveness,
.link,
=> return,
else => @tagName(scope),
} ++ "): ";
const prefix = "[" ++ @tagName(level) ++ "] " ++ scope_prefix;
// Print the message to stderr, silently ignoring any errors
std.debug.print(prefix ++ format, args);
}
pub fn main() !void {
// TODO general purpose allocator in the zig std lib
const gpa = if (std.builtin.link_libc) std.heap.c_allocator else std.heap.page_allocator;
var arena_instance = std.heap.ArenaAllocator.init(gpa);
defer arena_instance.deinit();
const arena = &arena_instance.allocator;
const args = try process.argsAlloc(arena);
if (args.len <= 1) {
std.debug.print("expected command argument\n\n{}", .{usage});
process.exit(1);
}
const cmd = args[1];
const cmd_args = args[2..];
if (mem.eql(u8, cmd, "build-exe")) {
return buildOutputType(gpa, arena, cmd_args, .Exe);
} else if (mem.eql(u8, cmd, "build-lib")) {
return buildOutputType(gpa, arena, cmd_args, .Lib);
} else if (mem.eql(u8, cmd, "build-obj")) {
return buildOutputType(gpa, arena, cmd_args, .Obj);
} else if (mem.eql(u8, cmd, "fmt")) {
return cmdFmt(gpa, cmd_args);
} else if (mem.eql(u8, cmd, "targets")) {
const info = try std.zig.system.NativeTargetInfo.detect(arena, .{});
const stdout = io.getStdOut().outStream();
return @import("print_targets.zig").cmdTargets(arena, cmd_args, stdout, info.target);
} else if (mem.eql(u8, cmd, "version")) {
// Need to set up the build script to give the version as a comptime value.
std.debug.print("TODO version command not implemented yet\n", .{});
return error.Unimplemented;
} else if (mem.eql(u8, cmd, "zen")) {
try io.getStdOut().writeAll(info_zen);
} else if (mem.eql(u8, cmd, "help")) {
try io.getStdOut().writeAll(usage);
} else {
std.debug.print("unknown command: {}\n\n{}", .{ args[1], usage });
process.exit(1);
}
}
const usage_build_generic =
\\Usage: zig build-exe <options> [files]
\\ zig build-lib <options> [files]
\\ zig build-obj <options> [files]
\\
\\Supported file types:
\\ .zig Zig source code
\\ .zir Zig Intermediate Representation code
\\ (planned) .o ELF object file
\\ (planned) .o MACH-O (macOS) object file
\\ (planned) .obj COFF (Windows) object file
\\ (planned) .lib COFF (Windows) static library
\\ (planned) .a ELF static library
\\ (planned) .so ELF shared object (dynamic link)
\\ (planned) .dll Windows Dynamic Link Library
\\ (planned) .dylib MACH-O (macOS) dynamic library
\\ (planned) .s Target-specific assembly source code
\\ (planned) .S Assembly with C preprocessor (requires LLVM extensions)
\\ (planned) .c C source code (requires LLVM extensions)
\\ (planned) .cpp C++ source code (requires LLVM extensions)
\\ Other C++ extensions: .C .cc .cxx
\\
\\General Options:
\\ -h, --help Print this help and exit
\\ --watch Enable compiler REPL
\\ --color [auto|off|on] Enable or disable colored error messages
\\ -femit-bin[=path] (default) output machine code
\\ -fno-emit-bin Do not output machine code
\\
\\Compile Options:
\\ -target [name] <arch><sub>-<os>-<abi> see the targets command
\\ -mcpu [cpu] Specify target CPU and feature set
\\ --name [name] Override output name
\\ --mode [mode] Set the build mode
\\ Debug (default) optimizations off, safety on
\\ ReleaseFast Optimizations on, safety off
\\ ReleaseSafe Optimizations on, safety on
\\ ReleaseSmall Optimize for small binary, safety off
\\ --dynamic Force output to be dynamically linked
\\ --strip Exclude debug symbols
\\ -ofmt=[mode] Override target object format
\\ elf Executable and Linking Format
\\ c Compile to C source code
\\ coff (planned) Common Object File Format (Windows)
\\ pe (planned) Portable Executable (Windows)
\\ macho (planned) macOS relocatables
\\ hex (planned) Intel IHEX
\\ raw (planned) Dump machine code directly
\\
\\Link Options:
\\ -l[lib], --library [lib] Link against system library
\\ --dynamic-linker [path] Set the dynamic interpreter path (usually ld.so)
\\ --version [ver] Dynamic library semver
\\
\\Debug Options (Zig Compiler Development):
\\ -ftime-report Print timing diagnostics
\\ --debug-tokenize verbose tokenization
\\ --debug-ast-tree verbose parsing into an AST (tree view)
\\ --debug-ast-fmt verbose parsing into an AST (render source)
\\ --debug-ir verbose Zig IR
\\ --debug-link verbose linking
\\ --debug-codegen verbose machine code generation
\\
;
const Emit = union(enum) {
no,
yes_default_path,
yes: []const u8,
};
fn buildOutputType(
gpa: *Allocator,
arena: *Allocator,
args: []const []const u8,
output_mode: std.builtin.OutputMode,
) !void {
var color: Color = .Auto;
var build_mode: std.builtin.Mode = .Debug;
var provided_name: ?[]const u8 = null;
var link_mode: ?std.builtin.LinkMode = null;
var root_src_file: ?[]const u8 = null;
var version: std.builtin.Version = .{ .major = 0, .minor = 0, .patch = 0 };
var strip = false;
var watch = false;
var debug_tokenize = false;
var debug_ast_tree = false;
var debug_ast_fmt = false;
var debug_link = false;
var debug_ir = false;
var debug_codegen = false;
var time_report = false;
var emit_bin: Emit = .yes_default_path;
var emit_zir: Emit = .no;
var target_arch_os_abi: []const u8 = "native";
var target_mcpu: ?[]const u8 = null;
var target_dynamic_linker: ?[]const u8 = null;
var target_ofmt: ?[]const u8 = null;
var system_libs = std.ArrayList([]const u8).init(gpa);
defer system_libs.deinit();
{
var i: usize = 0;
while (i < args.len) : (i += 1) {
const arg = args[i];
if (mem.startsWith(u8, arg, "-")) {
if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) {
try io.getStdOut().writeAll(usage_build_generic);
process.exit(0);
} else if (mem.eql(u8, arg, "--color")) {
if (i + 1 >= args.len) {
std.debug.print("expected [auto|on|off] after --color\n", .{});
process.exit(1);
}
i += 1;
const next_arg = args[i];
if (mem.eql(u8, next_arg, "auto")) {
color = .Auto;
} else if (mem.eql(u8, next_arg, "on")) {
color = .On;
} else if (mem.eql(u8, next_arg, "off")) {
color = .Off;
} else {
std.debug.print("expected [auto|on|off] after --color, found '{}'\n", .{next_arg});
process.exit(1);
}
} else if (mem.eql(u8, arg, "--mode")) {
if (i + 1 >= args.len) {
std.debug.print("expected [Debug|ReleaseSafe|ReleaseFast|ReleaseSmall] after --mode\n", .{});
process.exit(1);
}
i += 1;
const next_arg = args[i];
if (mem.eql(u8, next_arg, "Debug")) {
build_mode = .Debug;
} else if (mem.eql(u8, next_arg, "ReleaseSafe")) {
build_mode = .ReleaseSafe;
} else if (mem.eql(u8, next_arg, "ReleaseFast")) {
build_mode = .ReleaseFast;
} else if (mem.eql(u8, next_arg, "ReleaseSmall")) {
build_mode = .ReleaseSmall;
} else {
std.debug.print("expected [Debug|ReleaseSafe|ReleaseFast|ReleaseSmall] after --mode, found '{}'\n", .{next_arg});
process.exit(1);
}
} else if (mem.eql(u8, arg, "--name")) {
if (i + 1 >= args.len) {
std.debug.print("expected parameter after --name\n", .{});
process.exit(1);
}
i += 1;
provided_name = args[i];
} else if (mem.eql(u8, arg, "--library")) {
if (i + 1 >= args.len) {
std.debug.print("expected parameter after --library\n", .{});
process.exit(1);
}
i += 1;
try system_libs.append(args[i]);
} else if (mem.eql(u8, arg, "--version")) {
if (i + 1 >= args.len) {
std.debug.print("expected parameter after --version\n", .{});
process.exit(1);
}
i += 1;
version = std.builtin.Version.parse(args[i]) catch |err| {
std.debug.print("unable to parse --version '{}': {}\n", .{ args[i], @errorName(err) });
process.exit(1);
};
} else if (mem.eql(u8, arg, "-target")) {
if (i + 1 >= args.len) {
std.debug.print("expected parameter after -target\n", .{});
process.exit(1);
}
i += 1;
target_arch_os_abi = args[i];
} else if (mem.eql(u8, arg, "-mcpu")) {
if (i + 1 >= args.len) {
std.debug.print("expected parameter after -mcpu\n", .{});
process.exit(1);
}
i += 1;
target_mcpu = args[i];
} else if (mem.startsWith(u8, arg, "-ofmt=")) {
target_ofmt = arg["-ofmt=".len..];
} else if (mem.startsWith(u8, arg, "-mcpu=")) {
target_mcpu = arg["-mcpu=".len..];
} else if (mem.eql(u8, arg, "--dynamic-linker")) {
if (i + 1 >= args.len) {
std.debug.print("expected parameter after --dynamic-linker\n", .{});
process.exit(1);
}
i += 1;
target_dynamic_linker = args[i];
} else if (mem.eql(u8, arg, "--watch")) {
watch = true;
} else if (mem.eql(u8, arg, "-ftime-report")) {
time_report = true;
} else if (mem.eql(u8, arg, "-femit-bin")) {
emit_bin = .yes_default_path;
} else if (mem.startsWith(u8, arg, "-femit-bin=")) {
emit_bin = .{ .yes = arg["-femit-bin=".len..] };
} else if (mem.eql(u8, arg, "-fno-emit-bin")) {
emit_bin = .no;
} else if (mem.eql(u8, arg, "-femit-zir")) {
emit_zir = .yes_default_path;
} else if (mem.startsWith(u8, arg, "-femit-zir=")) {
emit_zir = .{ .yes = arg["-femit-zir=".len..] };
} else if (mem.eql(u8, arg, "-fno-emit-zir")) {
emit_zir = .no;
} else if (mem.eql(u8, arg, "-dynamic")) {
link_mode = .Dynamic;
} else if (mem.eql(u8, arg, "-static")) {
link_mode = .Static;
} else if (mem.eql(u8, arg, "--strip")) {
strip = true;
} else if (mem.eql(u8, arg, "--debug-tokenize")) {
debug_tokenize = true;
} else if (mem.eql(u8, arg, "--debug-ast-tree")) {
debug_ast_tree = true;
} else if (mem.eql(u8, arg, "--debug-ast-fmt")) {
debug_ast_fmt = true;
} else if (mem.eql(u8, arg, "--debug-link")) {
debug_link = true;
} else if (mem.eql(u8, arg, "--debug-ir")) {
debug_ir = true;
} else if (mem.eql(u8, arg, "--debug-codegen")) {
debug_codegen = true;
} else if (mem.startsWith(u8, arg, "-l")) {
try system_libs.append(arg[2..]);
} else {
std.debug.print("unrecognized parameter: '{}'", .{arg});
process.exit(1);
}
} else if (mem.endsWith(u8, arg, ".s") or mem.endsWith(u8, arg, ".S")) {
std.debug.print("assembly files not supported yet", .{});
process.exit(1);
} else if (mem.endsWith(u8, arg, ".o") or
mem.endsWith(u8, arg, ".obj") or
mem.endsWith(u8, arg, ".a") or
mem.endsWith(u8, arg, ".lib"))
{
std.debug.print("object files and static libraries not supported yet", .{});
process.exit(1);
} else if (mem.endsWith(u8, arg, ".c") or
mem.endsWith(u8, arg, ".cpp"))
{
std.debug.print("compilation of C and C++ source code requires LLVM extensions which are not implemented yet", .{});
process.exit(1);
} else if (mem.endsWith(u8, arg, ".so") or
mem.endsWith(u8, arg, ".dylib") or
mem.endsWith(u8, arg, ".dll"))
{
std.debug.print("linking against dynamic libraries not yet supported", .{});
process.exit(1);
} else if (mem.endsWith(u8, arg, ".zig") or mem.endsWith(u8, arg, ".zir")) {
if (root_src_file) |other| {
std.debug.print("found another zig file '{}' after root source file '{}'", .{ arg, other });
process.exit(1);
} else {
root_src_file = arg;
}
} else {
std.debug.print("unrecognized file extension of parameter '{}'", .{arg});
}
}
}
const root_name = if (provided_name) |n| n else blk: {
if (root_src_file) |file| {
const basename = fs.path.basename(file);
var it = mem.split(basename, ".");
break :blk it.next() orelse basename;
} else {
std.debug.print("--name [name] not provided and unable to infer\n", .{});
process.exit(1);
}
};
if (system_libs.items.len != 0) {
std.debug.print("linking against system libraries not yet supported", .{});
process.exit(1);
}
var diags: std.zig.CrossTarget.ParseOptions.Diagnostics = .{};
const cross_target = std.zig.CrossTarget.parse(.{
.arch_os_abi = target_arch_os_abi,
.cpu_features = target_mcpu,
.dynamic_linker = target_dynamic_linker,
.diagnostics = &diags,
}) catch |err| switch (err) {
error.UnknownCpuModel => {
std.debug.print("Unknown CPU: '{}'\nAvailable CPUs for architecture '{}':\n", .{
diags.cpu_name.?,
@tagName(diags.arch.?),
});
for (diags.arch.?.allCpuModels()) |cpu| {
std.debug.print(" {}\n", .{cpu.name});
}
process.exit(1);
},
error.UnknownCpuFeature => {
std.debug.print(
\\Unknown CPU feature: '{}'
\\Available CPU features for architecture '{}':
\\
, .{
diags.unknown_feature_name,
@tagName(diags.arch.?),
});
for (diags.arch.?.allFeaturesList()) |feature| {
std.debug.print(" {}: {}\n", .{ feature.name, feature.description });
}
process.exit(1);
},
else => |e| return e,
};
var target_info = try std.zig.system.NativeTargetInfo.detect(gpa, cross_target);
if (target_info.cpu_detection_unimplemented) {
// TODO We want to just use detected_info.target but implementing
// CPU model & feature detection is todo so here we rely on LLVM.
std.debug.print("CPU features detection is not yet available for this system without LLVM extensions\n", .{});
process.exit(1);
}
const src_path = root_src_file orelse {
std.debug.print("expected at least one file argument", .{});
process.exit(1);
};
const object_format: ?std.Target.ObjectFormat = blk: {
const ofmt = target_ofmt orelse break :blk null;
if (mem.eql(u8, ofmt, "elf")) {
break :blk .elf;
} else if (mem.eql(u8, ofmt, "c")) {
break :blk .c;
} else if (mem.eql(u8, ofmt, "coff")) {
break :blk .coff;
} else if (mem.eql(u8, ofmt, "pe")) {
break :blk .coff;
} else if (mem.eql(u8, ofmt, "macho")) {
break :blk .macho;
} else if (mem.eql(u8, ofmt, "wasm")) {
break :blk .wasm;
} else if (mem.eql(u8, ofmt, "hex")) {
break :blk .hex;
} else if (mem.eql(u8, ofmt, "raw")) {
break :blk .raw;
} else {
std.debug.print("unsupported object format: {}", .{ofmt});
process.exit(1);
}
};
const bin_path = switch (emit_bin) {
.no => {
std.debug.print("-fno-emit-bin not supported yet", .{});
process.exit(1);
},
.yes_default_path => if (object_format != null and object_format.? == .c)
try std.fmt.allocPrint(arena, "{}.c", .{root_name})
else
try std.zig.binNameAlloc(arena, root_name, target_info.target, output_mode, link_mode),
.yes => |p| p,
};
const zir_out_path: ?[]const u8 = switch (emit_zir) {
.no => null,
.yes_default_path => blk: {
if (root_src_file) |rsf| {
if (mem.endsWith(u8, rsf, ".zir")) {
break :blk try std.fmt.allocPrint(arena, "{}.out.zir", .{root_name});
}
}
break :blk try std.fmt.allocPrint(arena, "{}.zir", .{root_name});
},
.yes => |p| p,
};
const root_pkg = try Package.create(gpa, fs.cwd(), ".", src_path);
defer root_pkg.destroy();
var module = try Module.init(gpa, .{
.target = target_info.target,
.output_mode = output_mode,
.root_pkg = root_pkg,
.bin_file_dir = fs.cwd(),
.bin_file_path = bin_path,
.link_mode = link_mode,
.object_format = object_format,
.optimize_mode = build_mode,
.keep_source_files_loaded = zir_out_path != null,
});
defer module.deinit();
const stdin = std.io.getStdIn().inStream();
const stderr = std.io.getStdErr().outStream();
var repl_buf: [1024]u8 = undefined;
try updateModule(gpa, &module, zir_out_path);
while (watch) {
try stderr.print("🦎 ", .{});
if (output_mode == .Exe) {
try module.makeBinFileExecutable();
}
if (stdin.readUntilDelimiterOrEof(&repl_buf, '\n') catch |err| {
try stderr.print("\nUnable to parse command: {}\n", .{@errorName(err)});
continue;
}) |line| {
if (mem.eql(u8, line, "update")) {
if (output_mode == .Exe) {
try module.makeBinFileWritable();
}
try updateModule(gpa, &module, zir_out_path);
} else if (mem.eql(u8, line, "exit")) {
break;
} else if (mem.eql(u8, line, "help")) {
try stderr.writeAll(repl_help);
} else {
try stderr.print("unknown command: {}\n", .{line});
}
} else {
break;
}
}
}
fn updateModule(gpa: *Allocator, module: *Module, zir_out_path: ?[]const u8) !void {
var timer = try std.time.Timer.start();
try module.update();
const update_nanos = timer.read();
var errors = try module.getAllErrorsAlloc();
defer errors.deinit(module.gpa);
if (errors.list.len != 0) {
for (errors.list) |full_err_msg| {
std.debug.print("{}:{}:{}: error: {}\n", .{
full_err_msg.src_path,
full_err_msg.line + 1,
full_err_msg.column + 1,
full_err_msg.msg,
});
}
} else {
std.log.info(.compiler, "Update completed in {} ms\n", .{update_nanos / std.time.ns_per_ms});
}
if (zir_out_path) |zop| {
var new_zir_module = try zir.emit(gpa, module.*);
defer new_zir_module.deinit(gpa);
const baf = try io.BufferedAtomicFile.create(gpa, fs.cwd(), zop, .{});
defer baf.destroy();
try new_zir_module.writeToStream(gpa, baf.stream());
try baf.finish();
}
}
const repl_help =
\\Commands:
\\ update Detect changes to source files and update output files.
\\ help Print this text
\\ exit Quit this repl
\\
;
pub const usage_fmt =
\\usage: zig fmt [file]...
\\
\\ Formats the input files and modifies them in-place.
\\ Arguments can be files or directories, which are searched
\\ recursively.
\\
\\Options:
\\ --help Print this help and exit
\\ --color [auto|off|on] Enable or disable colored error messages
\\ --stdin Format code from stdin; output to stdout
\\ --check List non-conforming files and exit with an error
\\ if the list is non-empty
\\
\\
;
const Fmt = struct {
seen: SeenMap,
any_error: bool,
color: Color,
gpa: *Allocator,
out_buffer: std.ArrayList(u8),
const SeenMap = std.AutoHashMap(fs.File.INode, void);
};
pub fn cmdFmt(gpa: *Allocator, args: []const []const u8) !void {
const stderr_file = io.getStdErr();
var color: Color = .Auto;
var stdin_flag: bool = false;
var check_flag: bool = false;
var input_files = ArrayList([]const u8).init(gpa);
{
var i: usize = 0;
while (i < args.len) : (i += 1) {
const arg = args[i];
if (mem.startsWith(u8, arg, "-")) {
if (mem.eql(u8, arg, "--help")) {
const stdout = io.getStdOut().outStream();
try stdout.writeAll(usage_fmt);
process.exit(0);
} else if (mem.eql(u8, arg, "--color")) {
if (i + 1 >= args.len) {
std.debug.print("expected [auto|on|off] after --color\n", .{});
process.exit(1);
}
i += 1;
const next_arg = args[i];
if (mem.eql(u8, next_arg, "auto")) {
color = .Auto;
} else if (mem.eql(u8, next_arg, "on")) {
color = .On;
} else if (mem.eql(u8, next_arg, "off")) {
color = .Off;
} else {
std.debug.print("expected [auto|on|off] after --color, found '{}'\n", .{next_arg});
process.exit(1);
}
} else if (mem.eql(u8, arg, "--stdin")) {
stdin_flag = true;
} else if (mem.eql(u8, arg, "--check")) {
check_flag = true;
} else {
std.debug.print("unrecognized parameter: '{}'", .{arg});
process.exit(1);
}
} else {
try input_files.append(arg);
}
}
}
if (stdin_flag) {
if (input_files.items.len != 0) {
std.debug.print("cannot use --stdin with positional arguments\n", .{});
process.exit(1);
}
const stdin = io.getStdIn().inStream();
const source_code = try stdin.readAllAlloc(gpa, max_src_size);
defer gpa.free(source_code);
const tree = std.zig.parse(gpa, source_code) catch |err| {
std.debug.print("error parsing stdin: {}\n", .{err});
process.exit(1);
};
defer tree.deinit();
for (tree.errors) |parse_error| {
try printErrMsgToFile(gpa, parse_error, tree, "<stdin>", stderr_file, color);
}
if (tree.errors.len != 0) {
process.exit(1);
}
if (check_flag) {
const anything_changed = try std.zig.render(gpa, io.null_out_stream, tree);
const code = if (anything_changed) @as(u8, 1) else @as(u8, 0);
process.exit(code);
}
const stdout = io.getStdOut().outStream();
_ = try std.zig.render(gpa, stdout, tree);
return;
}
if (input_files.items.len == 0) {
std.debug.print("expected at least one source file argument\n", .{});
process.exit(1);
}
var fmt = Fmt{
.gpa = gpa,
.seen = Fmt.SeenMap.init(gpa),
.any_error = false,
.color = color,
.out_buffer = std.ArrayList(u8).init(gpa),
};
defer fmt.seen.deinit();
defer fmt.out_buffer.deinit();
for (input_files.span()) |file_path| {
// Get the real path here to avoid Windows failing on relative file paths with . or .. in them.
const real_path = fs.realpathAlloc(gpa, file_path) catch |err| {
std.debug.print("unable to open '{}': {}\n", .{ file_path, err });
process.exit(1);
};
defer gpa.free(real_path);
try fmtPath(&fmt, file_path, check_flag, fs.cwd(), real_path);
}
if (fmt.any_error) {
process.exit(1);
}
}
const FmtError = error{
SystemResources,
OperationAborted,
IoPending,
BrokenPipe,
Unexpected,
WouldBlock,
FileClosed,
DestinationAddressRequired,
DiskQuota,
FileTooBig,
InputOutput,
NoSpaceLeft,
AccessDenied,
OutOfMemory,
RenameAcrossMountPoints,
ReadOnlyFileSystem,
LinkQuotaExceeded,
FileBusy,
EndOfStream,
} || fs.File.OpenError;
fn fmtPath(fmt: *Fmt, file_path: []const u8, check_mode: bool, dir: fs.Dir, sub_path: []const u8) FmtError!void {
fmtPathFile(fmt, file_path, check_mode, dir, sub_path) catch |err| switch (err) {
error.IsDir, error.AccessDenied => return fmtPathDir(fmt, file_path, check_mode, dir, sub_path),
else => {
std.debug.print("unable to format '{}': {}\n", .{ file_path, err });
fmt.any_error = true;
return;
},
};
}
fn fmtPathDir(
fmt: *Fmt,
file_path: []const u8,
check_mode: bool,
parent_dir: fs.Dir,
parent_sub_path: []const u8,
) FmtError!void {
var dir = try parent_dir.openDir(parent_sub_path, .{ .iterate = true });
defer dir.close();
const stat = try dir.stat();
if (try fmt.seen.fetchPut(stat.inode, {})) |_| return;
var dir_it = dir.iterate();
while (try dir_it.next()) |entry| {
const is_dir = entry.kind == .Directory;
if (is_dir or mem.endsWith(u8, entry.name, ".zig")) {
const full_path = try fs.path.join(fmt.gpa, &[_][]const u8{ file_path, entry.name });
defer fmt.gpa.free(full_path);
if (is_dir) {
try fmtPathDir(fmt, full_path, check_mode, dir, entry.name);
} else {
fmtPathFile(fmt, full_path, check_mode, dir, entry.name) catch |err| {
std.debug.print("unable to format '{}': {}\n", .{ full_path, err });
fmt.any_error = true;
return;
};
}
}
}
}
fn fmtPathFile(
fmt: *Fmt,
file_path: []const u8,
check_mode: bool,
dir: fs.Dir,
sub_path: []const u8,
) FmtError!void {
const source_file = try dir.openFile(sub_path, .{});
var file_closed = false;
errdefer if (!file_closed) source_file.close();
const stat = try source_file.stat();
if (stat.kind == .Directory)
return error.IsDir;
const source_code = source_file.readAllAlloc(fmt.gpa, stat.size, max_src_size) catch |err| switch (err) {
error.ConnectionResetByPeer => unreachable,
error.ConnectionTimedOut => unreachable,
else => |e| return e,
};
source_file.close();
file_closed = true;
defer fmt.gpa.free(source_code);
// Add to set after no longer possible to get error.IsDir.
if (try fmt.seen.fetchPut(stat.inode, {})) |_| return;
const tree = try std.zig.parse(fmt.gpa, source_code);
defer tree.deinit();
for (tree.errors) |parse_error| {
try printErrMsgToFile(fmt.gpa, parse_error, tree, file_path, std.io.getStdErr(), fmt.color);
}
if (tree.errors.len != 0) {
fmt.any_error = true;
return;
}
if (check_mode) {
const anything_changed = try std.zig.render(fmt.gpa, io.null_out_stream, tree);
if (anything_changed) {
std.debug.print("{}\n", .{file_path});
fmt.any_error = true;
}
} else {
// As a heuristic, we make enough capacity for the same as the input source.
try fmt.out_buffer.ensureCapacity(source_code.len);
fmt.out_buffer.items.len = 0;
const anything_changed = try std.zig.render(fmt.gpa, fmt.out_buffer.writer(), tree);
if (!anything_changed)
return; // Good thing we didn't waste any file system access on this.
var af = try dir.atomicFile(sub_path, .{ .mode = stat.mode });
defer af.deinit();
try af.file.writeAll(fmt.out_buffer.items);
try af.finish();
std.debug.print("{}\n", .{file_path});
}
}
fn printErrMsgToFile(
gpa: *mem.Allocator,
parse_error: ast.Error,
tree: *ast.Tree,
path: []const u8,
file: fs.File,
color: Color,
) !void {
const color_on = switch (color) {
.Auto => file.isTty(),
.On => true,
.Off => false,
};
const lok_token = parse_error.loc();
const span_first = lok_token;
const span_last = lok_token;
const first_token = tree.token_locs[span_first];
const last_token = tree.token_locs[span_last];
const start_loc = tree.tokenLocationLoc(0, first_token);
const end_loc = tree.tokenLocationLoc(first_token.end, last_token);
var text_buf = std.ArrayList(u8).init(gpa);
defer text_buf.deinit();
const out_stream = text_buf.outStream();
try parse_error.render(tree.token_ids, out_stream);
const text = text_buf.span();
const stream = file.outStream();
try stream.print("{}:{}:{}: error: {}\n", .{ path, start_loc.line + 1, start_loc.column + 1, text });
if (!color_on) return;
// Print \r and \t as one space each so that column counts line up
for (tree.source[start_loc.line_start..start_loc.line_end]) |byte| {
try stream.writeByte(switch (byte) {
'\r', '\t' => ' ',
else => byte,
});
}
try stream.writeByte('\n');
try stream.writeByteNTimes(' ', start_loc.column);
try stream.writeByteNTimes('~', last_token.end - first_token.start);
try stream.writeByte('\n');
}
pub const info_zen =
\\
\\ * Communicate intent precisely.
\\ * Edge cases matter.
\\ * Favor reading code over writing code.
\\ * Only one obvious way to do things.
\\ * Runtime crashes are better than bugs.
\\ * Compile errors are better than runtime crashes.
\\ * Incremental improvements.
\\ * Avoid local maximums.
\\ * Reduce the amount one must remember.
\\ * Minimize energy spent on coding style.
\\ * Resource deallocation must succeed.
\\ * Together we serve end users.
\\
\\
; | src-self-hosted/main.zig |
const std = @import("../std.zig");
const math = std.math;
const expect = std.testing.expect;
const builtin = @import("builtin");
const TypeId = builtin.TypeId;
/// Returns the natural logarithm of x.
///
/// Special Cases:
/// - ln(+inf) = +inf
/// - ln(0) = -inf
/// - ln(x) = nan if x < 0
/// - ln(nan) = nan
pub fn ln(x: var) @typeOf(x) {
const T = @typeOf(x);
switch (@typeId(T)) {
TypeId.ComptimeFloat => {
return @typeOf(1.0)(ln_64(x));
},
TypeId.Float => {
return switch (T) {
f32 => ln_32(x),
f64 => ln_64(x),
else => @compileError("ln not implemented for " ++ @typeName(T)),
};
},
TypeId.ComptimeInt => {
return @typeOf(1)(math.floor(ln_64(@as(f64, x))));
},
TypeId.Int => {
return @as(T, math.floor(ln_64(@as(f64, x))));
},
else => @compileError("ln not implemented for " ++ @typeName(T)),
}
}
pub fn ln_32(x_: f32) f32 {
const ln2_hi: f32 = 6.9313812256e-01;
const ln2_lo: f32 = 9.0580006145e-06;
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 ix = @bitCast(u32, x);
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);
}
// subnormal, scale x
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;
const dk = @intToFloat(f32, k);
return s * (hfsq + R) + dk * ln2_lo - hfsq + f + dk * ln2_hi;
}
pub fn ln_64(x_: f64) f64 {
const ln2_hi: f64 = 6.93147180369123816490e-01;
const ln2_lo: f64 = 1.90821492927058770002e-10;
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(f64);
}
// log(-#) = nan
if (hx >> 31 != 0) {
return math.nan(f64);
}
// subnormal, scale x
k -= 54;
x *= 0x1.0p54;
hx = @intCast(u32, @bitCast(u64, ix) >> 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;
const dk = @intToFloat(f64, k);
return s * (hfsq + R) + dk * ln2_lo - hfsq + f + dk * ln2_hi;
}
test "math.ln" {
expect(ln(@as(f32, 0.2)) == ln_32(0.2));
expect(ln(@as(f64, 0.2)) == ln_64(0.2));
}
test "math.ln32" {
const epsilon = 0.000001;
expect(math.approxEq(f32, ln_32(0.2), -1.609438, epsilon));
expect(math.approxEq(f32, ln_32(0.8923), -0.113953, epsilon));
expect(math.approxEq(f32, ln_32(1.5), 0.405465, epsilon));
expect(math.approxEq(f32, ln_32(37.45), 3.623007, epsilon));
expect(math.approxEq(f32, ln_32(89.123), 4.490017, epsilon));
expect(math.approxEq(f32, ln_32(123123.234375), 11.720941, epsilon));
}
test "math.ln64" {
const epsilon = 0.000001;
expect(math.approxEq(f64, ln_64(0.2), -1.609438, epsilon));
expect(math.approxEq(f64, ln_64(0.8923), -0.113953, epsilon));
expect(math.approxEq(f64, ln_64(1.5), 0.405465, epsilon));
expect(math.approxEq(f64, ln_64(37.45), 3.623007, epsilon));
expect(math.approxEq(f64, ln_64(89.123), 4.490017, epsilon));
expect(math.approxEq(f64, ln_64(123123.234375), 11.720941, epsilon));
}
test "math.ln32.special" {
expect(math.isPositiveInf(ln_32(math.inf(f32))));
expect(math.isNegativeInf(ln_32(0.0)));
expect(math.isNan(ln_32(-1.0)));
expect(math.isNan(ln_32(math.nan(f32))));
}
test "math.ln64.special" {
expect(math.isPositiveInf(ln_64(math.inf(f64))));
expect(math.isNegativeInf(ln_64(0.0)));
expect(math.isNan(ln_64(-1.0)));
expect(math.isNan(ln_64(math.nan(f64))));
} | lib/std/math/ln.zig |
const __fixtfsi = @import("fixtfsi.zig").__fixtfsi;
const std = @import("std");
const math = std.math;
const testing = std.testing;
const warn = std.debug.warn;
fn test__fixtfsi(a: f128, expected: i32) void {
const x = __fixtfsi(a);
//warn("a={}:{x} x={}:{x} expected={}:{x}:@as(u32, {x})\n", a, @bitCast(u128, a), x, x, expected, expected, @bitCast(u32, expected));
testing.expect(x == expected);
}
test "fixtfsi" {
//warn("\n");
test__fixtfsi(-math.f128_max, math.minInt(i32));
test__fixtfsi(-0x1.FFFFFFFFFFFFFp+1023, math.minInt(i32));
test__fixtfsi(-0x1.FFFFFFFFFFFFFp+1023, -0x80000000);
test__fixtfsi(-0x1.0000000000000p+127, -0x80000000);
test__fixtfsi(-0x1.FFFFFFFFFFFFFp+126, -0x80000000);
test__fixtfsi(-0x1.FFFFFFFFFFFFEp+126, -0x80000000);
test__fixtfsi(-0x1.0000000000001p+63, -0x80000000);
test__fixtfsi(-0x1.0000000000000p+63, -0x80000000);
test__fixtfsi(-0x1.FFFFFFFFFFFFFp+62, -0x80000000);
test__fixtfsi(-0x1.FFFFFFFFFFFFEp+62, -0x80000000);
test__fixtfsi(-0x1.FFFFFEp+62, -0x80000000);
test__fixtfsi(-0x1.FFFFFCp+62, -0x80000000);
test__fixtfsi(-0x1.000000p+31, -0x80000000);
test__fixtfsi(-0x1.FFFFFFp+30, -0x7FFFFFC0);
test__fixtfsi(-0x1.FFFFFEp+30, -0x7FFFFF80);
test__fixtfsi(-0x1.FFFFFCp+30, -0x7FFFFF00);
test__fixtfsi(-2.01, -2);
test__fixtfsi(-2.0, -2);
test__fixtfsi(-1.99, -1);
test__fixtfsi(-1.0, -1);
test__fixtfsi(-0.99, 0);
test__fixtfsi(-0.5, 0);
test__fixtfsi(-math.f32_min, 0);
test__fixtfsi(0.0, 0);
test__fixtfsi(math.f32_min, 0);
test__fixtfsi(0.5, 0);
test__fixtfsi(0.99, 0);
test__fixtfsi(1.0, 1);
test__fixtfsi(1.5, 1);
test__fixtfsi(1.99, 1);
test__fixtfsi(2.0, 2);
test__fixtfsi(2.01, 2);
test__fixtfsi(0x1.FFFFFCp+30, 0x7FFFFF00);
test__fixtfsi(0x1.FFFFFEp+30, 0x7FFFFF80);
test__fixtfsi(0x1.FFFFFFp+30, 0x7FFFFFC0);
test__fixtfsi(0x1.000000p+31, 0x7FFFFFFF);
test__fixtfsi(0x1.FFFFFCp+62, 0x7FFFFFFF);
test__fixtfsi(0x1.FFFFFEp+62, 0x7FFFFFFF);
test__fixtfsi(0x1.FFFFFFFFFFFFEp+62, 0x7FFFFFFF);
test__fixtfsi(0x1.FFFFFFFFFFFFFp+62, 0x7FFFFFFF);
test__fixtfsi(0x1.0000000000000p+63, 0x7FFFFFFF);
test__fixtfsi(0x1.0000000000001p+63, 0x7FFFFFFF);
test__fixtfsi(0x1.FFFFFFFFFFFFEp+126, 0x7FFFFFFF);
test__fixtfsi(0x1.FFFFFFFFFFFFFp+126, 0x7FFFFFFF);
test__fixtfsi(0x1.0000000000000p+127, 0x7FFFFFFF);
test__fixtfsi(0x1.FFFFFFFFFFFFFp+1023, 0x7FFFFFFF);
test__fixtfsi(0x1.FFFFFFFFFFFFFp+1023, math.maxInt(i32));
test__fixtfsi(math.f128_max, math.maxInt(i32));
} | lib/std/special/compiler_rt/fixtfsi_test.zig |
const std = @import("std.zig");
const crypto = std.crypto;
const Hasher = crypto.auth.siphash.SipHash128(1, 3); // provides enough collision resistance for the CacheHash use cases, while being one of our fastest options right now
const fs = std.fs;
const base64 = std.base64;
const ArrayList = std.ArrayList;
const assert = std.debug.assert;
const testing = std.testing;
const mem = std.mem;
const fmt = std.fmt;
const Allocator = std.mem.Allocator;
const base64_encoder = fs.base64_encoder;
const base64_decoder = fs.base64_decoder;
/// This is 128 bits - Even with 2^54 cache entries, the probably of a collision would be under 10^-6
const BIN_DIGEST_LEN = 16;
const BASE64_DIGEST_LEN = base64.Base64Encoder.calcSize(BIN_DIGEST_LEN);
const MANIFEST_FILE_SIZE_MAX = 50 * 1024 * 1024;
pub const File = struct {
path: ?[]const u8,
max_file_size: ?usize,
stat: fs.File.Stat,
bin_digest: [BIN_DIGEST_LEN]u8,
contents: ?[]const u8,
pub fn deinit(self: *File, allocator: *Allocator) void {
if (self.path) |owned_slice| {
allocator.free(owned_slice);
self.path = null;
}
if (self.contents) |contents| {
allocator.free(contents);
self.contents = null;
}
self.* = undefined;
}
};
/// CacheHash manages project-local `zig-cache` directories.
/// This is not a general-purpose cache.
/// It was designed to be fast and simple, not to withstand attacks using specially-crafted input.
pub const CacheHash = struct {
allocator: *Allocator,
hasher_init: Hasher, // initial state, that can be copied
hasher: Hasher, // current state for incremental hashing
manifest_dir: fs.Dir,
manifest_file: ?fs.File,
manifest_dirty: bool,
files: ArrayList(File),
b64_digest: [BASE64_DIGEST_LEN]u8,
/// Be sure to call release after successful initialization.
pub fn init(allocator: *Allocator, dir: fs.Dir, manifest_dir_path: []const u8) !CacheHash {
const hasher_init = Hasher.init(&[_]u8{0} ** Hasher.minimum_key_length);
return CacheHash{
.allocator = allocator,
.hasher_init = hasher_init,
.hasher = hasher_init,
.manifest_dir = try dir.makeOpenPath(manifest_dir_path, .{}),
.manifest_file = null,
.manifest_dirty = false,
.files = ArrayList(File).init(allocator),
.b64_digest = undefined,
};
}
/// Record a slice of bytes as an dependency of the process being cached
pub fn addSlice(self: *CacheHash, val: []const u8) void {
assert(self.manifest_file == null);
self.hasher.update(val);
self.hasher.update(&[_]u8{0});
}
/// Convert the input value into bytes and record it as a dependency of the
/// process being cached
pub fn add(self: *CacheHash, val: anytype) void {
assert(self.manifest_file == null);
const valPtr = switch (@typeInfo(@TypeOf(val))) {
.Int => &val,
.Pointer => val,
else => &val,
};
self.addSlice(mem.asBytes(valPtr));
}
/// Add a file as a dependency of process being cached. When `CacheHash.hit` is
/// called, the file's contents will be checked to ensure that it matches
/// the contents from previous times.
///
/// Max file size will be used to determine the amount of space to the file contents
/// are allowed to take up in memory. If max_file_size is null, then the contents
/// will not be loaded into memory.
///
/// Returns the index of the entry in the `CacheHash.files` ArrayList. You can use it
/// to access the contents of the file after calling `CacheHash.hit()` like so:
///
/// ```
/// var file_contents = cache_hash.files.items[file_index].contents.?;
/// ```
pub fn addFile(self: *CacheHash, file_path: []const u8, max_file_size: ?usize) !usize {
assert(self.manifest_file == null);
try self.files.ensureCapacity(self.files.items.len + 1);
const resolved_path = try fs.path.resolve(self.allocator, &[_][]const u8{file_path});
const idx = self.files.items.len;
self.files.addOneAssumeCapacity().* = .{
.path = resolved_path,
.contents = null,
.max_file_size = max_file_size,
.stat = undefined,
.bin_digest = undefined,
};
self.addSlice(resolved_path);
return idx;
}
/// Check the cache to see if the input exists in it. If it exists, a base64 encoding
/// of it's hash will be returned; otherwise, null will be returned.
///
/// This function will also acquire an exclusive lock to the manifest file. This means
/// that a process holding a CacheHash will block any other process attempting to
/// acquire the lock.
///
/// The lock on the manifest file is released when `CacheHash.release` is called.
pub fn hit(self: *CacheHash) !?[BASE64_DIGEST_LEN]u8 {
assert(self.manifest_file == null);
var bin_digest: [BIN_DIGEST_LEN]u8 = undefined;
self.hasher.final(&bin_digest);
base64_encoder.encode(self.b64_digest[0..], &bin_digest);
self.hasher = self.hasher_init;
self.hasher.update(&bin_digest);
const manifest_file_path = try fmt.allocPrint(self.allocator, "{}.txt", .{self.b64_digest});
defer self.allocator.free(manifest_file_path);
if (self.files.items.len != 0) {
self.manifest_file = try self.manifest_dir.createFile(manifest_file_path, .{
.read = true,
.truncate = false,
.lock = .Exclusive,
});
} else {
// If there are no file inputs, we check if the manifest file exists instead of
// comparing the hashes on the files used for the cached item
self.manifest_file = self.manifest_dir.openFile(manifest_file_path, .{
.read = true,
.write = true,
.lock = .Exclusive,
}) catch |err| switch (err) {
error.FileNotFound => {
self.manifest_dirty = true;
self.manifest_file = try self.manifest_dir.createFile(manifest_file_path, .{
.read = true,
.truncate = false,
.lock = .Exclusive,
});
return null;
},
else => |e| return e,
};
}
const file_contents = try self.manifest_file.?.inStream().readAllAlloc(self.allocator, MANIFEST_FILE_SIZE_MAX);
defer self.allocator.free(file_contents);
const input_file_count = self.files.items.len;
var any_file_changed = false;
var line_iter = mem.tokenize(file_contents, "\n");
var idx: usize = 0;
while (line_iter.next()) |line| {
defer idx += 1;
const cache_hash_file = if (idx < input_file_count) &self.files.items[idx] else blk: {
const new = try self.files.addOne();
new.* = .{
.path = null,
.contents = null,
.max_file_size = null,
.stat = undefined,
.bin_digest = undefined,
};
break :blk new;
};
var iter = mem.tokenize(line, " ");
const size = iter.next() orelse return error.InvalidFormat;
const inode = iter.next() orelse return error.InvalidFormat;
const mtime_nsec_str = iter.next() orelse return error.InvalidFormat;
const digest_str = iter.next() orelse return error.InvalidFormat;
const file_path = iter.rest();
cache_hash_file.stat.size = fmt.parseInt(u64, size, 10) catch return error.InvalidFormat;
cache_hash_file.stat.inode = fmt.parseInt(fs.File.INode, inode, 10) catch return error.InvalidFormat;
cache_hash_file.stat.mtime = fmt.parseInt(i64, mtime_nsec_str, 10) catch return error.InvalidFormat;
base64_decoder.decode(&cache_hash_file.bin_digest, digest_str) catch return error.InvalidFormat;
if (file_path.len == 0) {
return error.InvalidFormat;
}
if (cache_hash_file.path) |p| {
if (!mem.eql(u8, file_path, p)) {
return error.InvalidFormat;
}
}
if (cache_hash_file.path == null) {
cache_hash_file.path = try self.allocator.dupe(u8, file_path);
}
const this_file = fs.cwd().openFile(cache_hash_file.path.?, .{ .read = true }) catch {
return error.CacheUnavailable;
};
defer this_file.close();
const actual_stat = try this_file.stat();
const size_match = actual_stat.size == cache_hash_file.stat.size;
const mtime_match = actual_stat.mtime == cache_hash_file.stat.mtime;
const inode_match = actual_stat.inode == cache_hash_file.stat.inode;
if (!size_match or !mtime_match or !inode_match) {
self.manifest_dirty = true;
cache_hash_file.stat = actual_stat;
if (isProblematicTimestamp(cache_hash_file.stat.mtime)) {
cache_hash_file.stat.mtime = 0;
cache_hash_file.stat.inode = 0;
}
var actual_digest: [BIN_DIGEST_LEN]u8 = undefined;
try hashFile(this_file, &actual_digest, self.hasher_init);
if (!mem.eql(u8, &cache_hash_file.bin_digest, &actual_digest)) {
cache_hash_file.bin_digest = actual_digest;
// keep going until we have the input file digests
any_file_changed = true;
}
}
if (!any_file_changed) {
self.hasher.update(&cache_hash_file.bin_digest);
}
}
if (any_file_changed) {
// cache miss
// keep the manifest file open
// reset the hash
self.hasher = self.hasher_init;
self.hasher.update(&bin_digest);
// Remove files not in the initial hash
for (self.files.items[input_file_count..]) |*file| {
file.deinit(self.allocator);
}
self.files.shrink(input_file_count);
for (self.files.items) |file| {
self.hasher.update(&file.bin_digest);
}
return null;
}
if (idx < input_file_count) {
self.manifest_dirty = true;
while (idx < input_file_count) : (idx += 1) {
const ch_file = &self.files.items[idx];
try self.populateFileHash(ch_file);
}
return null;
}
return self.final();
}
fn populateFileHash(self: *CacheHash, ch_file: *File) !void {
const file = try fs.cwd().openFile(ch_file.path.?, .{});
defer file.close();
ch_file.stat = try file.stat();
if (isProblematicTimestamp(ch_file.stat.mtime)) {
ch_file.stat.mtime = 0;
ch_file.stat.inode = 0;
}
if (ch_file.max_file_size) |max_file_size| {
if (ch_file.stat.size > max_file_size) {
return error.FileTooBig;
}
const contents = try self.allocator.alloc(u8, @intCast(usize, ch_file.stat.size));
errdefer self.allocator.free(contents);
// Hash while reading from disk, to keep the contents in the cpu cache while
// doing hashing.
var hasher = self.hasher_init;
var off: usize = 0;
while (true) {
// give me everything you've got, captain
const bytes_read = try file.read(contents[off..]);
if (bytes_read == 0) break;
hasher.update(contents[off..][0..bytes_read]);
off += bytes_read;
}
hasher.final(&ch_file.bin_digest);
ch_file.contents = contents;
} else {
try hashFile(file, &ch_file.bin_digest, self.hasher_init);
}
self.hasher.update(&ch_file.bin_digest);
}
/// Add a file as a dependency of process being cached, after the initial hash has been
/// calculated. This is useful for processes that don't know the all the files that
/// are depended on ahead of time. For example, a source file that can import other files
/// will need to be recompiled if the imported file is changed.
pub fn addFilePostFetch(self: *CacheHash, file_path: []const u8, max_file_size: usize) ![]u8 {
assert(self.manifest_file != null);
const resolved_path = try fs.path.resolve(self.allocator, &[_][]const u8{file_path});
errdefer self.allocator.free(resolved_path);
const new_ch_file = try self.files.addOne();
new_ch_file.* = .{
.path = resolved_path,
.max_file_size = max_file_size,
.stat = undefined,
.bin_digest = undefined,
.contents = null,
};
errdefer self.files.shrink(self.files.items.len - 1);
try self.populateFileHash(new_ch_file);
return new_ch_file.contents.?;
}
/// Add a file as a dependency of process being cached, after the initial hash has been
/// calculated. This is useful for processes that don't know the all the files that
/// are depended on ahead of time. For example, a source file that can import other files
/// will need to be recompiled if the imported file is changed.
pub fn addFilePost(self: *CacheHash, file_path: []const u8) !void {
assert(self.manifest_file != null);
const resolved_path = try fs.path.resolve(self.allocator, &[_][]const u8{file_path});
errdefer self.allocator.free(resolved_path);
const new_ch_file = try self.files.addOne();
new_ch_file.* = .{
.path = resolved_path,
.max_file_size = null,
.stat = undefined,
.bin_digest = undefined,
.contents = null,
};
errdefer self.files.shrink(self.files.items.len - 1);
try self.populateFileHash(new_ch_file);
}
/// Returns a base64 encoded hash of the inputs.
pub fn final(self: *CacheHash) [BASE64_DIGEST_LEN]u8 {
assert(self.manifest_file != null);
// We don't close the manifest file yet, because we want to
// keep it locked until the API user is done using it.
// We also don't write out the manifest yet, because until
// cache_release is called we still might be working on creating
// the artifacts to cache.
var bin_digest: [BIN_DIGEST_LEN]u8 = undefined;
self.hasher.final(&bin_digest);
var out_digest: [BASE64_DIGEST_LEN]u8 = undefined;
base64_encoder.encode(&out_digest, &bin_digest);
return out_digest;
}
pub fn writeManifest(self: *CacheHash) !void {
assert(self.manifest_file != null);
var encoded_digest: [BASE64_DIGEST_LEN]u8 = undefined;
var contents = ArrayList(u8).init(self.allocator);
var outStream = contents.outStream();
defer contents.deinit();
for (self.files.items) |file| {
base64_encoder.encode(encoded_digest[0..], &file.bin_digest);
try outStream.print("{} {} {} {} {}\n", .{ file.stat.size, file.stat.inode, file.stat.mtime, encoded_digest[0..], file.path });
}
try self.manifest_file.?.pwriteAll(contents.items, 0);
self.manifest_dirty = false;
}
/// Releases the manifest file and frees any memory the CacheHash was using.
/// `CacheHash.hit` must be called first.
///
/// Will also attempt to write to the manifest file if the manifest is dirty.
/// Writing to the manifest file can fail, but this function ignores those errors.
/// To detect failures from writing the manifest, one may explicitly call
/// `writeManifest` before `release`.
pub fn release(self: *CacheHash) void {
if (self.manifest_file) |file| {
if (self.manifest_dirty) {
// To handle these errors, API users should call
// writeManifest before release().
self.writeManifest() catch {};
}
file.close();
}
for (self.files.items) |*file| {
file.deinit(self.allocator);
}
self.files.deinit();
self.manifest_dir.close();
}
};
fn hashFile(file: fs.File, bin_digest: []u8, hasher_init: anytype) !void {
var buf: [1024]u8 = undefined;
var hasher = hasher_init;
while (true) {
const bytes_read = try file.read(&buf);
if (bytes_read == 0) break;
hasher.update(buf[0..bytes_read]);
}
hasher.final(bin_digest);
}
/// If the wall clock time, rounded to the same precision as the
/// mtime, is equal to the mtime, then we cannot rely on this mtime
/// yet. We will instead save an mtime value that indicates the hash
/// must be unconditionally computed.
/// This function recognizes the precision of mtime by looking at trailing
/// zero bits of the seconds and nanoseconds.
fn isProblematicTimestamp(fs_clock: i128) bool {
const wall_clock = std.time.nanoTimestamp();
// We have to break the nanoseconds into seconds and remainder nanoseconds
// to detect precision of seconds, because looking at the zero bits in base
// 2 would not detect precision of the seconds value.
const fs_sec = @intCast(i64, @divFloor(fs_clock, std.time.ns_per_s));
const fs_nsec = @intCast(i64, @mod(fs_clock, std.time.ns_per_s));
var wall_sec = @intCast(i64, @divFloor(wall_clock, std.time.ns_per_s));
var wall_nsec = @intCast(i64, @mod(wall_clock, std.time.ns_per_s));
// First make all the least significant zero bits in the fs_clock, also zero bits in the wall clock.
if (fs_nsec == 0) {
wall_nsec = 0;
if (fs_sec == 0) {
wall_sec = 0;
} else {
wall_sec &= @as(i64, -1) << @intCast(u6, @ctz(i64, fs_sec));
}
} else {
wall_nsec &= @as(i64, -1) << @intCast(u6, @ctz(i64, fs_nsec));
}
return wall_nsec == fs_nsec and wall_sec == fs_sec;
}
test "cache file and then recall it" {
if (std.Target.current.os.tag == .wasi) {
// https://github.com/ziglang/zig/issues/5437
return error.SkipZigTest;
}
const cwd = fs.cwd();
const temp_file = "test.txt";
const temp_manifest_dir = "temp_manifest_dir";
const ts = std.time.nanoTimestamp();
try cwd.writeFile(temp_file, "Hello, world!\n");
while (isProblematicTimestamp(ts)) {
std.time.sleep(1);
}
var digest1: [BASE64_DIGEST_LEN]u8 = undefined;
var digest2: [BASE64_DIGEST_LEN]u8 = undefined;
{
var ch = try CacheHash.init(testing.allocator, cwd, temp_manifest_dir);
defer ch.release();
ch.add(true);
ch.add(@as(u16, 1234));
ch.add("1234");
_ = try ch.addFile(temp_file, null);
// There should be nothing in the cache
testing.expectEqual(@as(?[BASE64_DIGEST_LEN]u8, null), try ch.hit());
digest1 = ch.final();
}
{
var ch = try CacheHash.init(testing.allocator, cwd, temp_manifest_dir);
defer ch.release();
ch.add(true);
ch.add(@as(u16, 1234));
ch.add("1234");
_ = try ch.addFile(temp_file, null);
// Cache hit! We just "built" the same file
digest2 = (try ch.hit()).?;
}
testing.expectEqual(digest1, digest2);
try cwd.deleteTree(temp_manifest_dir);
try cwd.deleteFile(temp_file);
}
test "give problematic timestamp" {
var fs_clock = std.time.nanoTimestamp();
// to make it problematic, we make it only accurate to the second
fs_clock = @divTrunc(fs_clock, std.time.ns_per_s);
fs_clock *= std.time.ns_per_s;
testing.expect(isProblematicTimestamp(fs_clock));
}
test "give nonproblematic timestamp" {
testing.expect(!isProblematicTimestamp(std.time.nanoTimestamp() - std.time.ns_per_s));
}
test "check that changing a file makes cache fail" {
if (std.Target.current.os.tag == .wasi) {
// https://github.com/ziglang/zig/issues/5437
return error.SkipZigTest;
}
const cwd = fs.cwd();
const temp_file = "cache_hash_change_file_test.txt";
const temp_manifest_dir = "cache_hash_change_file_manifest_dir";
const original_temp_file_contents = "Hello, world!\n";
const updated_temp_file_contents = "Hello, world; but updated!\n";
try cwd.deleteTree(temp_manifest_dir);
try cwd.deleteTree(temp_file);
const ts = std.time.nanoTimestamp();
try cwd.writeFile(temp_file, original_temp_file_contents);
while (isProblematicTimestamp(ts)) {
std.time.sleep(1);
}
var digest1: [BASE64_DIGEST_LEN]u8 = undefined;
var digest2: [BASE64_DIGEST_LEN]u8 = undefined;
{
var ch = try CacheHash.init(testing.allocator, cwd, temp_manifest_dir);
defer ch.release();
ch.add("1234");
const temp_file_idx = try ch.addFile(temp_file, 100);
// There should be nothing in the cache
testing.expectEqual(@as(?[BASE64_DIGEST_LEN]u8, null), try ch.hit());
testing.expect(mem.eql(u8, original_temp_file_contents, ch.files.items[temp_file_idx].contents.?));
digest1 = ch.final();
}
try cwd.writeFile(temp_file, updated_temp_file_contents);
{
var ch = try CacheHash.init(testing.allocator, cwd, temp_manifest_dir);
defer ch.release();
ch.add("1234");
const temp_file_idx = try ch.addFile(temp_file, 100);
// A file that we depend on has been updated, so the cache should not contain an entry for it
testing.expectEqual(@as(?[BASE64_DIGEST_LEN]u8, null), try ch.hit());
// The cache system does not keep the contents of re-hashed input files.
testing.expect(ch.files.items[temp_file_idx].contents == null);
digest2 = ch.final();
}
testing.expect(!mem.eql(u8, digest1[0..], digest2[0..]));
try cwd.deleteTree(temp_manifest_dir);
try cwd.deleteTree(temp_file);
}
test "no file inputs" {
if (std.Target.current.os.tag == .wasi) {
// https://github.com/ziglang/zig/issues/5437
return error.SkipZigTest;
}
const cwd = fs.cwd();
const temp_manifest_dir = "no_file_inputs_manifest_dir";
defer cwd.deleteTree(temp_manifest_dir) catch unreachable;
var digest1: [BASE64_DIGEST_LEN]u8 = undefined;
var digest2: [BASE64_DIGEST_LEN]u8 = undefined;
{
var ch = try CacheHash.init(testing.allocator, cwd, temp_manifest_dir);
defer ch.release();
ch.add("1234");
// There should be nothing in the cache
testing.expectEqual(@as(?[BASE64_DIGEST_LEN]u8, null), try ch.hit());
digest1 = ch.final();
}
{
var ch = try CacheHash.init(testing.allocator, cwd, temp_manifest_dir);
defer ch.release();
ch.add("1234");
digest2 = (try ch.hit()).?;
}
testing.expectEqual(digest1, digest2);
}
test "CacheHashes with files added after initial hash work" {
if (std.Target.current.os.tag == .wasi) {
// https://github.com/ziglang/zig/issues/5437
return error.SkipZigTest;
}
const cwd = fs.cwd();
const temp_file1 = "cache_hash_post_file_test1.txt";
const temp_file2 = "cache_hash_post_file_test2.txt";
const temp_manifest_dir = "cache_hash_post_file_manifest_dir";
const ts1 = std.time.nanoTimestamp();
try cwd.writeFile(temp_file1, "Hello, world!\n");
try cwd.writeFile(temp_file2, "Hello world the second!\n");
while (isProblematicTimestamp(ts1)) {
std.time.sleep(1);
}
var digest1: [BASE64_DIGEST_LEN]u8 = undefined;
var digest2: [BASE64_DIGEST_LEN]u8 = undefined;
var digest3: [BASE64_DIGEST_LEN]u8 = undefined;
{
var ch = try CacheHash.init(testing.allocator, cwd, temp_manifest_dir);
defer ch.release();
ch.add("1234");
_ = try ch.addFile(temp_file1, null);
// There should be nothing in the cache
testing.expectEqual(@as(?[BASE64_DIGEST_LEN]u8, null), try ch.hit());
_ = try ch.addFilePost(temp_file2);
digest1 = ch.final();
}
{
var ch = try CacheHash.init(testing.allocator, cwd, temp_manifest_dir);
defer ch.release();
ch.add("1234");
_ = try ch.addFile(temp_file1, null);
digest2 = (try ch.hit()).?;
}
testing.expect(mem.eql(u8, &digest1, &digest2));
// Modify the file added after initial hash
const ts2 = std.time.nanoTimestamp();
try cwd.writeFile(temp_file2, "Hello world the second, updated\n");
while (isProblematicTimestamp(ts2)) {
std.time.sleep(1);
}
{
var ch = try CacheHash.init(testing.allocator, cwd, temp_manifest_dir);
defer ch.release();
ch.add("1234");
_ = try ch.addFile(temp_file1, null);
// A file that we depend on has been updated, so the cache should not contain an entry for it
testing.expectEqual(@as(?[BASE64_DIGEST_LEN]u8, null), try ch.hit());
_ = try ch.addFilePost(temp_file2);
digest3 = ch.final();
}
testing.expect(!mem.eql(u8, &digest1, &digest3));
try cwd.deleteTree(temp_manifest_dir);
try cwd.deleteFile(temp_file1);
try cwd.deleteFile(temp_file2);
} | lib/std/cache_hash.zig |
const uefi = @import("std").os.uefi;
const BootServices = uefi.tables.BootServices;
const ConfigurationTable = uefi.tables.ConfigurationTable;
const Handle = uefi.Handle;
const RuntimeServices = uefi.tables.RuntimeServices;
const SimpleTextInputProtocol = uefi.protocols.SimpleTextInputProtocol;
const SimpleTextOutputProtocol = uefi.protocols.SimpleTextOutputProtocol;
const TableHeader = uefi.tables.TableHeader;
/// The EFI System Table contains pointers to the runtime and boot services tables.
///
/// As the system_table may grow with new UEFI versions, it is important to check hdr.header_size.
///
/// After successfully calling boot_services.exitBootServices, console_in_handle,
/// con_in, console_out_handle, con_out, standard_error_handle, std_err, and
/// boot_services should be set to null. After setting these attributes to null,
/// hdr.crc32 must be recomputed.
pub const SystemTable = extern struct {
hdr: TableHeader,
/// A null-terminated string that identifies the vendor that produces the system firmware of the platform.
firmware_vendor: [*:0]u16,
firmware_revision: u32,
console_in_handle: ?Handle,
con_in: ?*SimpleTextInputProtocol,
console_out_handle: ?Handle,
con_out: ?*SimpleTextOutputProtocol,
standard_error_handle: ?Handle,
std_err: ?*SimpleTextOutputProtocol,
runtime_services: *RuntimeServices,
boot_services: ?*BootServices,
number_of_table_entries: usize,
configuration_table: *ConfigurationTable,
pub const signature: u64 = 0x5453595320494249;
pub const revision_1_02: u32 = (1 << 16) | 2;
pub const revision_1_10: u32 = (1 << 16) | 10;
pub const revision_2_00: u32 = (2 << 16);
pub const revision_2_10: u32 = (2 << 16) | 10;
pub const revision_2_20: u32 = (2 << 16) | 20;
pub const revision_2_30: u32 = (2 << 16) | 30;
pub const revision_2_31: u32 = (2 << 16) | 31;
pub const revision_2_40: u32 = (2 << 16) | 40;
pub const revision_2_50: u32 = (2 << 16) | 50;
pub const revision_2_60: u32 = (2 << 16) | 60;
pub const revision_2_70: u32 = (2 << 16) | 70;
pub const revision_2_80: u32 = (2 << 16) | 80;
}; | lib/std/os/uefi/tables/system_table.zig |
// https://github.com/P-H-C/phc-string-format
const std = @import("std");
const fmt = std.fmt;
const io = std.io;
const mem = std.mem;
const meta = std.meta;
const fields_delimiter = "$";
const version_param_name = "v";
const params_delimiter = ",";
const kv_delimiter = "=";
pub const Error = std.crypto.errors.EncodingError || error{NoSpaceLeft};
const B64Decoder = std.base64.standard_no_pad.Decoder;
const B64Encoder = std.base64.standard_no_pad.Encoder;
/// A wrapped binary value whose maximum size is `max_len`.
///
/// This type must be used whenever a binary value is encoded in a PHC-formatted string.
/// This includes `salt`, `hash`, and any other binary parameters such as keys.
///
/// Once initialized, the actual value can be read with the `constSlice()` function.
pub fn BinValue(comptime max_len: usize) type {
return struct {
const Self = @This();
const capacity = max_len;
const max_encoded_length = B64Encoder.calcSize(max_len);
buf: [max_len]u8 = undefined,
len: usize = 0,
/// Wrap an existing byte slice
pub fn fromSlice(slice: []const u8) Error!Self {
if (slice.len > capacity) return Error.NoSpaceLeft;
var bin_value: Self = undefined;
mem.copy(u8, &bin_value.buf, slice);
bin_value.len = slice.len;
return bin_value;
}
/// Return the slice containing the actual value.
pub fn constSlice(self: Self) []const u8 {
return self.buf[0..self.len];
}
fn fromB64(self: *Self, str: []const u8) !void {
const len = B64Decoder.calcSizeForSlice(str) catch return Error.InvalidEncoding;
if (len > self.buf.len) return Error.NoSpaceLeft;
B64Decoder.decode(&self.buf, str) catch return Error.InvalidEncoding;
self.len = len;
}
fn toB64(self: Self, buf: []u8) ![]const u8 {
const value = self.constSlice();
const len = B64Encoder.calcSize(value.len);
if (len > buf.len) return Error.NoSpaceLeft;
return B64Encoder.encode(buf, value);
}
};
}
/// Deserialize a PHC-formatted string into a structure `HashResult`.
///
/// Required field in the `HashResult` structure:
/// - `alg_id`: algorithm identifier
/// Optional, special fields:
/// - `alg_version`: algorithm version (unsigned integer)
/// - `salt`: salt
/// - `hash`: output of the hash function
///
/// Other fields will also be deserialized from the function parameters section.
pub fn deserialize(comptime HashResult: type, str: []const u8) Error!HashResult {
var out = mem.zeroes(HashResult);
var it = mem.split(u8, str, fields_delimiter);
var set_fields: usize = 0;
while (true) {
// Read the algorithm identifier
if ((it.next() orelse return Error.InvalidEncoding).len != 0) return Error.InvalidEncoding;
out.alg_id = it.next() orelse return Error.InvalidEncoding;
set_fields += 1;
// Read the optional version number
var field = it.next() orelse break;
if (kvSplit(field)) |opt_version| {
if (mem.eql(u8, opt_version.key, version_param_name)) {
if (@hasField(HashResult, "alg_version")) {
const value_type_info = switch (@typeInfo(@TypeOf(out.alg_version))) {
.Optional => |opt| comptime @typeInfo(opt.child),
else => |t| t,
};
out.alg_version = fmt.parseUnsigned(
@Type(value_type_info),
opt_version.value,
10,
) catch return Error.InvalidEncoding;
set_fields += 1;
}
field = it.next() orelse break;
}
} else |_| {}
// Read optional parameters
var has_params = false;
var it_params = mem.split(u8, field, params_delimiter);
while (it_params.next()) |params| {
const param = kvSplit(params) catch break;
var found = false;
inline for (comptime meta.fields(HashResult)) |p| {
if (mem.eql(u8, p.name, param.key)) {
switch (@typeInfo(p.field_type)) {
.Int => @field(out, p.name) = fmt.parseUnsigned(
p.field_type,
param.value,
10,
) catch return Error.InvalidEncoding,
.Pointer => |ptr| {
if (!ptr.is_const) @compileError("Value slice must be constant");
@field(out, p.name) = param.value;
},
.Struct => try @field(out, p.name).fromB64(param.value),
else => std.debug.panic(
"Value for [{s}] must be an integer, a constant slice or a BinValue",
.{p.name},
),
}
set_fields += 1;
found = true;
break;
}
}
if (!found) return Error.InvalidEncoding; // An unexpected parameter was found in the string
has_params = true;
}
// No separator between an empty parameters set and the salt
if (has_params) field = it.next() orelse break;
// Read an optional salt
if (@hasField(HashResult, "salt")) {
try out.salt.fromB64(field);
set_fields += 1;
} else {
return Error.InvalidEncoding;
}
// Read an optional hash
field = it.next() orelse break;
if (@hasField(HashResult, "hash")) {
try out.hash.fromB64(field);
set_fields += 1;
} else {
return Error.InvalidEncoding;
}
break;
}
// Check that all the required fields have been set, excluding optional values and parameters
// with default values
var expected_fields: usize = 0;
inline for (comptime meta.fields(HashResult)) |p| {
if (@typeInfo(p.field_type) != .Optional and p.default_value == null) {
expected_fields += 1;
}
}
if (set_fields < expected_fields) return Error.InvalidEncoding;
return out;
}
/// Serialize parameters into a PHC string.
///
/// Required field for `params`:
/// - `alg_id`: algorithm identifier
/// Optional, special fields:
/// - `alg_version`: algorithm version (unsigned integer)
/// - `salt`: salt
/// - `hash`: output of the hash function
///
/// `params` can also include any additional parameters.
pub fn serialize(params: anytype, str: []u8) Error![]const u8 {
var buf = io.fixedBufferStream(str);
try serializeTo(params, buf.writer());
return buf.getWritten();
}
/// Compute the number of bytes required to serialize `params`
pub fn calcSize(params: anytype) usize {
var buf = io.countingWriter(io.null_writer);
serializeTo(params, buf.writer()) catch unreachable;
return @intCast(usize, buf.bytes_written);
}
fn serializeTo(params: anytype, out: anytype) !void {
const HashResult = @TypeOf(params);
try out.writeAll(fields_delimiter);
try out.writeAll(params.alg_id);
if (@hasField(HashResult, "alg_version")) {
if (@typeInfo(@TypeOf(params.alg_version)) == .Optional) {
if (params.alg_version) |alg_version| {
try out.print(
"{s}{s}{s}{}",
.{ fields_delimiter, version_param_name, kv_delimiter, alg_version },
);
}
} else {
try out.print(
"{s}{s}{s}{}",
.{ fields_delimiter, version_param_name, kv_delimiter, params.alg_version },
);
}
}
var has_params = false;
inline for (comptime meta.fields(HashResult)) |p| {
if (!(mem.eql(u8, p.name, "alg_id") or
mem.eql(u8, p.name, "alg_version") or
mem.eql(u8, p.name, "hash") or
mem.eql(u8, p.name, "salt")))
{
const value = @field(params, p.name);
try out.writeAll(if (has_params) params_delimiter else fields_delimiter);
if (@typeInfo(p.field_type) == .Struct) {
var buf: [@TypeOf(value).max_encoded_length]u8 = undefined;
try out.print("{s}{s}{s}", .{ p.name, kv_delimiter, try value.toB64(&buf) });
} else {
try out.print(
if (@typeInfo(@TypeOf(value)) == .Pointer) "{s}{s}{s}" else "{s}{s}{}",
.{ p.name, kv_delimiter, value },
);
}
has_params = true;
}
}
var has_salt = false;
if (@hasField(HashResult, "salt")) {
var buf: [@TypeOf(params.salt).max_encoded_length]u8 = undefined;
try out.print("{s}{s}", .{ fields_delimiter, try params.salt.toB64(&buf) });
has_salt = true;
}
if (@hasField(HashResult, "hash")) {
var buf: [@TypeOf(params.hash).max_encoded_length]u8 = undefined;
if (!has_salt) try out.writeAll(fields_delimiter);
try out.print("{s}{s}", .{ fields_delimiter, try params.hash.toB64(&buf) });
}
}
// Split a `key=value` string into `key` and `value`
fn kvSplit(str: []const u8) !struct { key: []const u8, value: []const u8 } {
var it = mem.split(u8, str, kv_delimiter);
const key = it.next() orelse return Error.InvalidEncoding;
const value = it.next() orelse return Error.InvalidEncoding;
const ret = .{ .key = key, .value = value };
return ret;
}
test "phc format - encoding/decoding" {
const Input = struct {
str: []const u8,
HashResult: type,
};
const inputs = [_]Input{
.{
.str = "$argon2id$v=19$key=a2V5,m=4096,t=0,p=1$X1NhbHQAAAAAAAAAAAAAAA$bWh++MKN1OiFHKgIWTLvIi1iHicmHH7+Fv3K88ifFfI",
.HashResult = struct {
alg_id: []const u8,
alg_version: u16,
key: BinValue(16),
m: usize,
t: u64,
p: u32,
salt: BinValue(16),
hash: BinValue(32),
},
},
.{
.str = "$scrypt$v=1$ln=15,r=8,p=1$c2FsdHNhbHQ$dGVzdHBhc3M",
.HashResult = struct {
alg_id: []const u8,
alg_version: ?u30,
ln: u6,
r: u30,
p: u30,
salt: BinValue(16),
hash: BinValue(16),
},
},
.{
.str = "$scrypt",
.HashResult = struct { alg_id: []const u8 },
},
.{ .str = "$scrypt$v=1", .HashResult = struct { alg_id: []const u8, alg_version: u16 } },
.{
.str = "$scrypt$ln=15,r=8,p=1",
.HashResult = struct { alg_id: []const u8, alg_version: ?u30, ln: u6, r: u30, p: u30 },
},
.{
.str = "$scrypt$c2FsdHNhbHQ",
.HashResult = struct { alg_id: []const u8, salt: BinValue(16) },
},
.{
.str = "$scrypt$v=1$ln=15,r=8,p=1$c2FsdHNhbHQ",
.HashResult = struct {
alg_id: []const u8,
alg_version: u16,
ln: u6,
r: u30,
p: u30,
salt: BinValue(16),
},
},
.{
.str = "$scrypt$v=1$ln=15,r=8,p=1",
.HashResult = struct { alg_id: []const u8, alg_version: ?u30, ln: u6, r: u30, p: u30 },
},
.{
.str = "$scrypt$v=1$c2FsdHNhbHQ$dGVzdHBhc3M",
.HashResult = struct {
alg_id: []const u8,
alg_version: u16,
salt: BinValue(16),
hash: BinValue(16),
},
},
.{
.str = "$scrypt$v=1$c2FsdHNhbHQ",
.HashResult = struct { alg_id: []const u8, alg_version: u16, salt: BinValue(16) },
},
.{
.str = "$scrypt$c2FsdHNhbHQ$dGVzdHBhc3M",
.HashResult = struct { alg_id: []const u8, salt: BinValue(16), hash: BinValue(16) },
},
};
inline for (inputs) |input| {
const v = try deserialize(input.HashResult, input.str);
var buf: [input.str.len]u8 = undefined;
const s1 = try serialize(v, &buf);
try std.testing.expectEqualSlices(u8, input.str, s1);
}
}
test "phc format - empty input string" {
const s = "";
const v = deserialize(struct { alg_id: []const u8 }, s);
try std.testing.expectError(Error.InvalidEncoding, v);
}
test "phc format - hash without salt" {
const s = "$scrypt";
const v = deserialize(struct { alg_id: []const u8, hash: BinValue(16) }, s);
try std.testing.expectError(Error.InvalidEncoding, v);
}
test "phc format - calcSize" {
const s = "$scrypt$v=1$ln=15,r=8,p=1$c2FsdHNhbHQ$dGVzdHBhc3M";
const v = try deserialize(struct {
alg_id: []const u8,
alg_version: u16,
ln: u6,
r: u30,
p: u30,
salt: BinValue(8),
hash: BinValue(8),
}, s);
try std.testing.expectEqual(calcSize(v), s.len);
} | lib/std/crypto/phc_encoding.zig |
const std = @import("std");
const builtin = @import("builtin");
// const build_options = @import("build_options")
const zinput = @import("src/zinput/src/main.zig");
var builder: *std.build.Builder = undefined;
pub fn config(step: *std.build.Step) anyerror!void {
@setEvalBranchQuota(2500);
std.debug.warn("Welcome to the ZLS configuration wizard! 🧙♂️\n", .{});
var zig_exe_path: ?[]const u8 = null;
std.debug.print("Looking for 'zig' in PATH...\n", .{});
find_zig: {
const allocator = builder.allocator;
const env_path = std.process.getEnvVarOwned(allocator, "PATH") catch |err| switch (err) {
error.EnvironmentVariableNotFound => {
break :find_zig;
},
else => return err,
};
defer allocator.free(env_path);
const exe_extension = @as(std.zig.CrossTarget, .{}).exeFileExt();
const zig_exe = try std.fmt.allocPrint(allocator, "zig{s}", .{exe_extension});
defer allocator.free(zig_exe);
var it = std.mem.tokenize(env_path, &[_]u8{std.fs.path.delimiter});
while (it.next()) |path| {
const full_path = try std.fs.path.join(allocator, &[_][]const u8{
path,
zig_exe,
});
defer allocator.free(full_path);
if (!std.fs.path.isAbsolute(full_path)) continue;
// Skip folders named zig
const file = std.fs.openFileAbsolute(full_path, .{}) catch continue;
const stat = file.stat() catch continue;
const is_dir = stat.kind == .Directory;
if (is_dir) continue;
var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined;
zig_exe_path = try std.mem.dupe(allocator, u8, std.os.realpath(full_path, &buf) catch continue);
break :find_zig;
}
}
if (zig_exe_path == null) {
std.debug.print("Could not find 'zig' in PATH\n", .{});
zig_exe_path = try zinput.askString(builder.allocator, "What is the path to the 'zig' executable you would like to use?", 512);
} else {
std.debug.print("Found zig executable '{s}'\n", .{zig_exe_path.?});
}
const snippets = try zinput.askBool("Do you want to enable snippets?");
const style = try zinput.askBool("Do you want to enable style warnings?");
const semantic_tokens = try zinput.askBool("Do you want to enable semantic highlighting?");
const operator_completions = try zinput.askBool("Do you want to enable .* and .? completions");
var dir = try std.fs.cwd().openDir(builder.exe_dir, .{});
defer dir.close();
var file = try dir.createFile("zls.json", .{});
defer file.close();
const out = file.writer();
std.debug.warn("Writing to config...\n", .{});
const content = std.json.stringify(.{
.zig_exe_path = zig_exe_path,
.enable_snippets = snippets,
.warn_style = style,
.enable_semantic_tokens = semantic_tokens,
.operator_completions = operator_completions,
}, std.json.StringifyOptions{}, out);
std.debug.warn("Successfully saved configuration options!\n", .{});
const editor = try zinput.askSelectOne("Which code editor do you use?", enum { VSCode, Sublime, Kate, Neovim, Vim8, Emacs, Other });
std.debug.warn("\n", .{});
switch (editor) {
.VSCode => {
std.debug.warn(
\\To use ZLS in Visual Studio Code, install the 'ZLS for VSCode' extension.
\\Then, open VSCode's 'settings.json' file, and add `"zigLanguageClient.path": "[command_or_path_to_zls]"`.
, .{});
},
.Sublime => {
std.debug.warn(
\\To use ZLS in Sublime, install the `LSP` package from `https://github.com/sublimelsp/LSP/releases` or via Package Control.
\\Then, add the following snippet to `LSP`'s user settings:
\\
\\{{
\\ "clients": {{
\\ "zig": {{
\\ "command": ["zls"],
\\ "enabled": true,
\\ "languageId": "zig",
\\ "scopes": ["source.zig"],
\\ "syntaxes": ["Packages/Zig/Syntaxes/Zig.tmLanguage"]
\\ }}
\\ }}
\\}}
, .{});
},
.Kate => {
std.debug.warn(
\\To use ZLS in Kate, enable `LSP client` plugin in Kate settings.
\\Then, add the following snippet to `LSP client's` user settings:
\\(or paste it in `LSP client's` GUI settings)
\\
\\{{
\\ "servers": {{
\\ "zig": {{
\\ "command": ["zls"],
\\ "url": "https://github.com/zigtools/zls",
\\ "highlightingModeRegex": "^Zig$"
\\ }}
\\ }}
\\}}
, .{});
},
.Neovim, .Vim8 => {
std.debug.warn(
\\To use ZLS in Neovim/Vim8, we recommend using CoC engine. You can get it from 'https://github.com/neoclide/coc.nvim'.
\\Then, simply issue cmd from Neovim/Vim8 `:CocConfig`, and add this to your CoC config:
\\
\\{{
\\ "languageserver": {{
\\ "zls" : {{
\\ "command": "command_or_path_to_zls",
\\ "filetypes": ["zig"]
\\ }}
\\ }}
\\}}
, .{});
},
.Emacs => {
std.debug.warn(
\\To use ZLS in Emacs, install lsp-mode (https://github.com/emacs-lsp/lsp-mode) from melpa.
\\Zig mode (https://github.com/ziglang/zig-mode) is also useful!
\\Then, add the following to your emacs config:
\\
\\(require 'lsp)
\\(add-to-list 'lsp-language-id-configuration '(zig-mode . "zig"))
\\(lsp-register-client
\\ (make-lsp-client
\\ :new-connection (lsp-stdio-connection "<path to zls>")
\\ :major-modes '(zig-mode)
\\ :server-id 'zls))
, .{});
},
.Other => {
std.debug.warn(
\\We might not *officially* support your editor, but you can definitely still use ZLS!
\\Simply configure your editor for use with language servers and point it to the ZLS executable!
, .{});
},
}
std.debug.warn("\nYou can find the ZLS executable in the \"zig-cache/bin\" by default.\nNOTE: Make sure that if you move the ZLS executable, you move the `zls.json` config file with it as well!\n\nAnd finally: Thanks for choosing ZLS!\n\n", .{});
}
pub fn build(b: *std.build.Builder) !void {
builder = b;
// Standard target options allows the person running `zig build` to choose
// what target to build for. Here we do not override the defaults, which
// means any target is allowed, and the default is native. Other options
// for restricting supported target set are available.
const target = b.standardTargetOptions(.{});
const mode = b.standardReleaseOptions();
const exe = b.addExecutable("zls", "src/main.zig");
exe.addBuildOption(
[]const u8,
"data_version",
b.option([]const u8, "data_version", "The data version - either 0.7.0 or master.") orelse "master",
);
exe.addPackage(.{ .name = "known-folders", .path = "src/known-folders/known-folders.zig" });
exe.setTarget(target);
exe.setBuildMode(mode);
exe.install();
b.installFile("src/special/build_runner.zig", "bin/build_runner.zig");
const run_cmd = exe.run();
run_cmd.step.dependOn(b.getInstallStep());
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
const configure_step = b.step("config", "Configure zls");
configure_step.makeFn = config;
const test_step = b.step("test", "Run all the tests");
test_step.dependOn(builder.getInstallStep());
var unit_tests = b.addTest("tests/unit_tests.zig");
unit_tests.addPackage(.{ .name = "analysis", .path = "src/analysis.zig" });
unit_tests.addPackage(.{ .name = "types", .path = "src/types.zig" });
unit_tests.setBuildMode(.Debug);
var session_tests = b.addTest("tests/sessions.zig");
session_tests.addPackage(.{ .name = "header", .path = "src/header.zig" });
session_tests.setBuildMode(.Debug);
test_step.dependOn(&session_tests.step);
} | build.zig |
const std = @import("std");
const builtin = @import("builtin");
const testing = std.testing;
/// Atomic counter
///
/// When used with single threaded builds, will defer to `NonAtomic`
pub const Atomic = if (builtin.single_threaded) NonAtomic else struct {
const T = usize;
pub const MAX = std.math.maxInt(T);
pub const MIN = std.math.minInt(T);
/// Saturating increment
inline fn increment(ptr: *T) T {
const val = @atomicLoad(usize, ptr, .Acquire);
const incr: T = if (val == MAX) 0 else 1;
return @atomicRmw(T, ptr, .Add, incr, .Release);
}
/// Bottom-clamped saturating increment
/// (if counter is zero, it will not be incremented)
inline fn clampedIncrement(ptr: *T) T {
const val = @atomicLoad(usize, ptr, .Acquire);
var incr: T = if (val == MAX) 0 else 1;
if (val == MIN) {
incr = 0;
}
return @atomicRmw(T, ptr, .Add, incr, .Release);
}
/// Saturating decrement
inline fn decrement(ptr: *T) T {
const val = @atomicLoad(usize, ptr, .Acquire);
const decr: T = if (val == MIN) 0 else 1;
return @atomicRmw(T, ptr, .Sub, decr, .Release);
}
/// Load counter value
inline fn load(ptr: *T) T {
return @atomicLoad(T, ptr, .SeqCst);
}
/// Establish ordering with the counters
inline fn synchronize() void {
@fence(.Acquire);
}
};
test "atomic increment" {
var val: usize = 0;
testing.expectEqual(@intCast(usize, 0), Atomic.increment(&val));
testing.expectEqual(@intCast(usize, 1), Atomic.load(&val));
}
test "clamped atomic increment" {
var val: usize = 0;
testing.expectEqual(@intCast(usize, 0), Atomic.clampedIncrement(&val));
testing.expectEqual(@intCast(usize, 0), Atomic.load(&val));
}
test "saturating atomic increment from max usize" {
var val: usize = std.math.maxInt(usize);
testing.expectEqual(@intCast(usize, std.math.maxInt(usize)), Atomic.increment(&val));
testing.expectEqual(@intCast(usize, std.math.maxInt(usize)), Atomic.load(&val));
}
fn increment100(val: *usize) void {
var i: usize = 0;
while (i < 100) {
// this is to ensure the thread doesn't finish too early
std.time.sleep(10 * std.time.millisecond);
_ = Atomic.increment(val);
i += 1;
}
}
fn decrement100(val: *usize) void {
var i: usize = 0;
while (i < 100) {
// this is to ensure the thread doesn't finish too early
std.time.sleep(10 * std.time.millisecond);
_ = Atomic.decrement(val);
i += 1;
}
}
test "concurrent atomic increments & decrements" {
var val: usize = 0;
const t1 = try std.Thread.spawn(&val, increment100);
const t2 = try std.Thread.spawn(&val, increment100);
t1.wait();
t2.wait();
testing.expectEqual(@intCast(usize, 200), Atomic.load(&val));
const t3 = try std.Thread.spawn(&val, decrement100);
const t4 = try std.Thread.spawn(&val, decrement100);
t3.wait();
t4.wait();
testing.expectEqual(@intCast(usize, 0), Atomic.load(&val));
}
test "saturating concurrent atomic increments" {
var val: usize = std.math.maxInt(usize) - 100;
const t1 = try std.Thread.spawn(&val, increment100);
const t2 = try std.Thread.spawn(&val, increment100);
t1.wait();
t2.wait();
testing.expectEqual(@intCast(usize, std.math.maxInt(usize)), Atomic.load(&val));
}
test "atomic decrement" {
var val: usize = 1;
testing.expectEqual(Atomic.decrement(&val), 1);
testing.expectEqual(Atomic.load(&val), 0);
}
test "saturating atomic decrement from 0" {
var val: usize = 0;
testing.expectEqual(Atomic.decrement(&val), 0);
testing.expectEqual(Atomic.load(&val), 0);
}
test "saturating concurrent atomic decrements" {
var val: usize = std.math.minInt(usize) + 100;
const t1 = try std.Thread.spawn(&val, decrement100);
const t2 = try std.Thread.spawn(&val, decrement100);
t1.wait();
t2.wait();
testing.expectEqual(@intCast(usize, std.math.minInt(usize)), Atomic.load(&val));
}
/// Non-atomic counter
pub const NonAtomic = struct {
const T = usize;
pub const MAX = std.math.maxInt(T);
pub const MIN = std.math.minInt(T);
/// Saturating increment
inline fn increment(ptr: *T) T {
const val = ptr.*;
if (@addWithOverflow(T, val, 1, ptr)) {
ptr.* = MAX;
}
return val;
}
/// Bottom-clamped saturating increment
/// (if counter is zero, it will not be incremented)
inline fn clampedIncrement(ptr: *T) T {
const val = ptr.*;
if (val == MIN) {
return MIN;
}
if (@addWithOverflow(T, val, 1, ptr)) {
ptr.* = MAX;
}
return val;
}
/// Saturating decrement
inline fn decrement(ptr: *T) T {
const val = ptr.*;
if (@subWithOverflow(T, val, 1, ptr)) {
ptr.* = MIN;
}
return val;
}
/// Load counter value
inline fn load(ptr: *T) T {
return ptr.*;
}
/// Establish ordering with the counters
inline fn synchronize() void {}
};
test "non-atomic increment" {
var val: usize = 0;
testing.expectEqual(NonAtomic.increment(&val), 0);
testing.expectEqual(NonAtomic.load(&val), 1);
}
test "clamped non-atomic increment" {
var val: usize = 0;
testing.expectEqual(@intCast(usize, 0), NonAtomic.clampedIncrement(&val));
testing.expectEqual(@intCast(usize, 0), NonAtomic.load(&val));
}
test "non-atomic increment from max usize" {
var val: usize = std.math.maxInt(usize);
testing.expectEqual(NonAtomic.increment(&val), std.math.maxInt(usize));
testing.expectEqual(NonAtomic.load(&val), std.math.maxInt(usize));
}
test "non-atomic decrement" {
var val: usize = 1;
testing.expectEqual(NonAtomic.decrement(&val), 1);
testing.expectEqual(NonAtomic.load(&val), 0);
}
test "non-atomic decrement from 0" {
var val: usize = 0;
testing.expectEqual(NonAtomic.decrement(&val), 0);
testing.expectEqual(NonAtomic.load(&val), 0);
}
/// Reference-counted shared pointer
///
/// Shared pointer with `Atomic` operations should not use
/// the same clone in more than one thread simultaneously.
///
/// Shared pointer with `NonAtomic` operations should not use
/// any clones outside of a single thread simultaneously.
///
/// TODO: RcSharedPointer does not properly handle the sitation
/// when either strong or weak counter saturates at the maximum
/// value of `usize`. Currently, it'll panic in this situation.
pub fn RcSharedPointer(comptime T: type, Ops: type) type {
const Inner = struct {
val: T,
strong_ctr: usize = 1,
weak_ctr: usize = 1,
allocator: *std.mem.Allocator,
};
return struct {
const Strong = @This();
const Weak = struct {
inner: ?*Inner,
pub const Type = T;
// There's seemingly a bug in Zig that messes with
// creation of RcSharedPointer if the constant below
// is declared as `Self` (and is later reused in the
// outer scope)
// TODO: change this to `Self` when (if) this behaviour
// will be changed
const SelfWeak = @This();
/// Create a strong clone
///
/// Might return zero if no other strong clones are present
/// (which indicates that the value has been deinitialized,
/// but not deallocated)
///
/// Instead of upgrading a shared pointer or its
/// strong clone to a weak one, creation of a weak
/// clone is used to avoid any potential race conditions
/// caused by momentarily inconsistent strong and weak
/// counters (where the total number of counters might
/// be incorrect during downgrade or upgrade operations)
pub fn strongClone(self: SelfWeak) ?Strong {
// the reason we're doing a clamped increment here is
// because if the counter is already zero, then the value
// has been deinitialized,..
const prev = Ops.clampedIncrement(&self.inner.?.*.strong_ctr);
if (prev == Ops.MAX) {
@panic("strong counter has been saturated");
}
if (prev == Ops.MIN) {
// ..so, we'll not be able to make a strong clone anymore
return null;
}
return Strong{ .inner = self.inner };
}
/// Create a weak clone
pub fn weakClone(self: SelfWeak) SelfWeak {
const prev = Ops.increment(&self.inner.?.*.weak_ctr);
if (prev == Ops.MAX) {
@panic("weak counter has been saturated");
}
return SelfWeak{ .inner = self.inner };
}
/// Number of strong clones
pub inline fn strongCount(self: SelfWeak) usize {
return Ops.load(&self.inner.?.*.strong_ctr);
}
/// Number of weak clones
pub inline fn weakCount(self: SelfWeak) usize {
return Ops.load(&self.inner.?.*.weak_ctr) - 1;
}
/// Deinitialize weak clone
///
/// Will never deinitialize the value but will
/// deallocate it if it is the last clone (both strong and weak)
pub fn deinit(self: *SelfWeak) void {
const cw_ = Ops.decrement(&self.inner.?.*.weak_ctr);
var p = self.inner.?;
// incapacitate self (useful methods will now panic)
self.inner = null;
// if weak counter was not saturated
if (cw_ == 1) {
Ops.synchronize();
// then we can deallocate
p.*.allocator.destroy(p);
}
}
};
inner: ?*Inner,
pub const Type = T;
const Self = @This();
/// Initialize the counter with a value
///
/// Allocates memory to hold the value and the counter
pub fn init(val: T, allocator: *std.mem.Allocator) !Self {
var allocated = try allocator.create(Inner);
allocated.* = Inner{
.val = val,
.allocator = allocator,
};
return Self{ .inner = allocated };
}
/// Create a strong clone
pub fn strongClone(self: *const Self) Self {
// the reason we're not doing a clampedIncrement here (as we do in `Weak`)
// is that the presence of non-null `self.inner` is already a guarantee that
// there's at least one strong clone present (`self`)
const prev = Ops.increment(&self.inner.?.*.strong_ctr);
if (prev == Ops.MAX) {
@panic("strong counter has been saturated");
}
return Self{ .inner = self.inner };
}
/// Create a weak clone
///
/// Instead of downgrading a shared pointer or its
/// strong clone to a weak one, creation of a weak
/// clone is used to avoid any potential race conditions
/// caused by momentarily inconsistent strong and weak
/// counters (where the total number of counters might
/// be incorrect during downgrade or upgrade operations)
pub fn weakClone(self: Self) Weak {
const prev = Ops.increment(&self.inner.?.*.weak_ctr);
if (prev == Ops.MAX) {
@panic("weak counter has been saturated");
}
return Weak{ .inner = self.inner };
}
/// Number of strong clones
pub inline fn strongCount(self: Self) usize {
return Ops.load(&self.inner.?.*.strong_ctr);
}
/// Number of weak clones
pub inline fn weakCount(self: Self) usize {
return Ops.load(&self.inner.?.*.weak_ctr) - 1;
}
/// Const pointer to the value
///
/// As the pointer is constant, if mutability
/// is desired, use of `std.Mutex` and `unsafePtr`
/// is recommended
pub fn ptr(self: Self) *const T {
return &self.inner.?.*.val;
}
/// Unsafe (mutable) pointer to the value
/// Normally it is recommended to use `std.Mutex`
/// for concurrent access:
///
/// ```
/// const T = struct { value: u128, ptr: std.Mutex = std.Mutex.init() };
/// var counter = RcSharedPointer(T, Atomic).init(T{ .value = 10 });
/// defer counter.deinit();
/// var ptr = counter.unsafePtr();
/// {
/// const lock = ptr.*.mutex.aquire();
/// defer lock.release();
/// ptr.*.value = 100;
/// }
/// ```
pub fn unsafePtr(self: Self) *T {
return &self.inner.?.*.val;
}
/// Deinitialize the shared pointer
///
/// Will deallocate its initial allocation
pub fn deinit(self: *Self) void {
self.deinitWithCallback(?void, null, null);
}
/// Deinitialize the shared pointer with a callback
///
/// Will first deinitialize the value using the callback
/// (if there are no other strong clones present) and then
/// deallocate its initial allocation (if there are no weak
/// clones present)
pub fn deinitWithCallback(self: *Self, comptime C: type, context: C, deinitializer: ?fn (*T, C) void) void {
const c_ = Ops.decrement(&self.inner.?.*.strong_ctr);
Ops.synchronize();
var p = self.inner.?;
// incapacitate self (useful methods will now panic)
self.inner = null;
if (c_ == 1) {
// ...ready to deinitialize the value
if (deinitializer) |deinit_fn| {
deinit_fn(&p.*.val, context);
}
const cw = Ops.decrement(&p.*.weak_ctr);
// also, if there are no outstanding weak counters,
if (cw == 1) {
Ops.synchronize();
// then deallocate
p.*.allocator.destroy(p);
}
}
}
};
}
test "initializing a shared pointer with a value" {
var v = try RcSharedPointer(u128, NonAtomic).init(10, std.heap.page_allocator);
defer v.deinit();
testing.expectEqual(v.ptr().*, 10);
}
test "unsafely mutating shared pointer's value" {
var v = try RcSharedPointer(u128, NonAtomic).init(10, std.heap.page_allocator);
defer v.deinit();
const ptr = v.unsafePtr();
ptr.* = 20;
testing.expectEqual(v.ptr().*, 20);
}
test "safely mutating shared pointer's value" {
const MU128 = struct {
value: u128,
mutex: std.Mutex = std.Mutex.init(),
};
var mutex = MU128{ .value = 10 };
var v = try RcSharedPointer(MU128, NonAtomic).init(mutex, std.heap.page_allocator);
defer v.deinit();
const ptr = v.unsafePtr();
{
const lock = ptr.*.mutex.acquire();
defer lock.release();
ptr.*.value = 20;
}
}
fn deinit_copy(val: *u128, ctx: *u128) void {
ctx.* = val.*;
}
test "deinitializing a shared pointer with a callback" {
var v = try RcSharedPointer(u128, NonAtomic).init(10, std.heap.page_allocator);
var v1: u128 = 0;
v.deinitWithCallback(*u128, &v1, deinit_copy);
testing.expectEqual(v1, 10);
}
test "strong-cloning a shared pointer" {
var v = try RcSharedPointer(u128, NonAtomic).init(10, std.heap.page_allocator);
defer v.deinit();
testing.expectEqual(@intCast(usize, 1), v.strongCount());
var v1 = v.strongClone();
testing.expectEqual(@intCast(usize, 2), v.strongCount());
v1.deinit();
testing.expectEqual(@intCast(usize, 1), v.strongCount());
}
fn deinit_incr(val: *u128, ctx: *u128) void {
ctx.* += val.*;
}
test "deinitializing a shared pointer with a callback and strong copies" {
var v = try RcSharedPointer(u128, NonAtomic).init(10, std.heap.page_allocator);
var r: u128 = 0;
var v1 = v.strongClone();
v.deinitWithCallback(*u128, &r, deinit_incr);
v1.deinitWithCallback(*u128, &r, deinit_incr);
testing.expectEqual(r, 10); // not 20 because the callback should only be called once
}
test "weak-cloning a shared pointer" {
var v = try RcSharedPointer(u128, NonAtomic).init(10, std.heap.page_allocator);
defer v.deinit();
testing.expectEqual(@intCast(usize, 0), v.weakCount());
var v1 = v.weakClone();
testing.expectEqual(@intCast(usize, 1), v.weakCount());
v1.deinit();
testing.expectEqual(@intCast(usize, 0), v.weakCount());
}
test "weak-cloning a shared pointer" {
var v = try RcSharedPointer(u128, NonAtomic).init(10, std.heap.page_allocator);
defer v.deinit();
testing.expectEqual(@intCast(usize, 0), v.weakCount());
var v1 = v.weakClone();
testing.expectEqual(@intCast(usize, 1), v.weakCount());
var v2 = v.weakClone();
testing.expectEqual(@intCast(usize, 2), v.weakCount());
v1.deinit();
v2.deinit();
testing.expectEqual(@intCast(usize, 0), v.weakCount());
}
test "strong-cloning a weak clone" {
var v = try RcSharedPointer(u128, NonAtomic).init(10, std.heap.page_allocator);
defer v.deinit();
testing.expectEqual(@intCast(usize, 0), v.weakCount());
var v1 = v.weakClone();
testing.expectEqual(@intCast(usize, 1), v.weakCount());
var v2 = v1.strongClone().?;
defer v2.deinit();
v1.deinit();
testing.expectEqual(@intCast(usize, 0), v.weakCount());
testing.expectEqual(@intCast(usize, 2), v.strongCount());
}
test "strong-cloning a weak clone with no other strong clones" {
var v = try RcSharedPointer(u128, NonAtomic).init(10, std.heap.page_allocator);
var v1 = v.weakClone();
testing.expectEqual(@intCast(usize, 1), v.weakCount());
v.deinit();
testing.expectEqual(@intCast(usize, 0), v1.strongCount());
testing.expect(v1.strongClone() == null);
v1.deinit();
} | src/main.zig |
pub const enum3 = []u64 {
0x4e2e2785c3a2a20b,
0x240a28877a09a4e1,
0x728fca36c06cf106,
0x1016b100e18e5c17,
0x3159190e30e46c1d,
0x64312a13daa46fe4,
0x7c41926c7a7122ba,
0x08667a3c8dc4bc9c,
0x18dde996371c6060,
0x297c2c31a31998ae,
0x368b870de5d93270,
0x57d561def4a9ee32,
0x6d275d226331d03a,
0x76703d7cb98edc59,
0x7ec490abad057752,
0x037be9d5a60850b5,
0x0c63165633977bca,
0x14a048cb468bc209,
0x20dc29bc6879dfcd,
0x2643dc6227de9148,
0x2d64f14348a4c5db,
0x341eef5e1f90ac35,
0x4931159a8bd8a240,
0x503ca9bade45b94a,
0x5c1af5b5378aa2e5,
0x6b4ef9beaa7aa584,
0x6ef1c382c3819a0a,
0x754fe46e378bf133,
0x7ace779fddf21622,
0x7df22815078cb97b,
0x7f33c8eeb77b8d05,
0x011b7aa3d73f6658,
0x06ceb7f2c53db97f,
0x0b8f3d82e9356287,
0x0e304273b18918b0,
0x139fb24e492936f6,
0x176090684f5fe997,
0x1e3035e7b5183922,
0x220ce77c2b3328fc,
0x246441ed79830182,
0x279b5cd8bbdd8770,
0x2cc7c3fba45c1272,
0x3081eab25ad0fcf7,
0x329f5a18504dfaac,
0x347eef5e1f90ac35,
0x3a978cfcab31064c,
0x4baa32ac316fb3ab,
0x4eb9a2c2a34ac2f9,
0x522f6a5025e71a61,
0x5935ede8cce30845,
0x5f9aeac2d1ea2695,
0x6820ee7811241ad3,
0x6c06c9e14b7c22c3,
0x6e5a2fbffdb7580c,
0x71160cf8f38b0465,
0x738a37935f3b71c9,
0x756fe46e378bf133,
0x7856d2aa2fc5f2b5,
0x7bd3b063946e10ae,
0x7d8220e1772428d7,
0x7e222815078cb97b,
0x7ef5bc471d5456c7,
0x7fb82baa4ae611dc,
0x00bb7aa3d73f6658,
0x0190a0f3c55062c5,
0x05898e3445512a6e,
0x07bfe89cf1bd76ac,
0x08dfa7ebe304ee3e,
0x0c43165633977bca,
0x0e104273b18918b0,
0x0fd6ba8608faa6a9,
0x10b4139a6b17b224,
0x1466cc4fc92a0fa6,
0x162ba6008389068a,
0x1804116d591ef1fb,
0x1c513770474911bd,
0x1e7035e7b5183923,
0x2114dab846e19e25,
0x222ce77c2b3328fc,
0x244441ed79830182,
0x249b23b50fc204db,
0x278aacfcb88c92d6,
0x289d52af46e5fa6a,
0x2bdec922478c0421,
0x2d44f14348a4c5dc,
0x2f0c1249e96b6d8d,
0x30addc7e975c5045,
0x322aedaa0fc32ac8,
0x33deef5e1f90ac34,
0x343eef5e1f90ac35,
0x35ef1de1f7f14439,
0x3854faba79ea92ec,
0x47f52d02c7e14af7,
0x4a6bb6979ae39c49,
0x4c85564fb098c955,
0x4e80fde34c996086,
0x4ed9a2c2a34ac2f9,
0x51a3274280201a89,
0x574fe0403124a00e,
0x581561def4a9ee31,
0x5b55ed1f039cebff,
0x5e2780695036a679,
0x624be064a3fb2725,
0x674dcfee6690ffc6,
0x6a6cc08102f0da5b,
0x6be6c9e14b7c22c4,
0x6ce75d226331d03a,
0x6d5b9445072f4374,
0x6e927edd0dbb8c09,
0x71060cf8f38b0465,
0x71b1d7cb7eae05d9,
0x72fba10d818fdafd,
0x739a37935f3b71c9,
0x755fe46e378bf133,
0x76603d7cb98edc59,
0x78447e17e7814ce7,
0x799d696737fe68c7,
0x7ade779fddf21622,
0x7c1c283ffc61c87d,
0x7d1a85c6f7fba05d,
0x7da220e1772428d7,
0x7e022815078cb97b,
0x7e9a9b45a91f1700,
0x7ee3c8eeb77b8d05,
0x7f13c8eeb77b8d05,
0x7f6594223f5654bf,
0x7fd82baa4ae611dc,
0x002d243f646eaf51,
0x00f5d15b26b80e30,
0x0180a0f3c55062c5,
0x01f393b456eef178,
0x05798e3445512a6e,
0x06afdadafcacdf85,
0x06e8b03fd6894b66,
0x07cfe89cf1bd76ac,
0x08ac25584881552a,
0x097822507db6a8fd,
0x0c27b35936d56e28,
0x0c53165633977bca,
0x0c8e9eddbbb259b4,
0x0e204273b18918b0,
0x0f1d16d6d4b89689,
0x0fe6ba8608faa6a9,
0x105f48347c60a1be,
0x13627383c5456c5e,
0x13f93bb1e72a2033,
0x148048cb468bc208,
0x1514c0b3a63c1444,
0x175090684f5fe997,
0x17e4116d591ef1fb,
0x18cde996371c6060,
0x19aa2cf604c30d3f,
0x1d2b1ad9101b1bfd,
0x1e5035e7b5183923,
0x1fe5a79c4e71d028,
0x20ec29bc6879dfcd,
0x218ce77c2b3328fb,
0x221ce77c2b3328fc,
0x233f346f9ed36b89,
0x243441ed79830182,
0x245441ed79830182,
0x247441ed79830182,
0x2541e4ee41180c0a,
0x277aacfcb88c92d6,
0x279aacfcb88c92d6,
0x27cbb4c6bd8601bd,
0x28c04a616046e074,
0x2a4eeff57768f88c,
0x2c2379f099a86227,
0x2d04f14348a4c5db,
0x2d54f14348a4c5dc,
0x2d6a8c931c19b77a,
0x2fa387cf9cb4ad4e,
0x308ddc7e975c5046,
0x3149190e30e46c1d,
0x318d2ec75df6ba2a,
0x32548050091c3c24,
0x33beef5e1f90ac34,
0x33feef5e1f90ac35,
0x342eef5e1f90ac35,
0x345eef5e1f90ac35,
0x35108621c4199208,
0x366b870de5d93270,
0x375b20c2f4f8d4a0,
0x3864faba79ea92ec,
0x3aa78cfcab31064c,
0x4919d9577de925d5,
0x49ccadd6dd730c96,
0x4b9a32ac316fb3ab,
0x4bba32ac316fb3ab,
0x4cff20b1a0d7f626,
0x4e3e2785c3a2a20b,
0x4ea9a2c2a34ac2f9,
0x4ec9a2c2a34ac2f9,
0x4f28750ea732fdae,
0x513843e10734fa57,
0x51e71760b3c0bc13,
0x55693ba3249a8511,
0x57763ae2caed4528,
0x57f561def4a9ee32,
0x584561def4a9ee31,
0x5b45ed1f039cebfe,
0x5bfaf5b5378aa2e5,
0x5c6cf45d333da323,
0x5e64ec8fd70420c7,
0x6009813653f62db7,
0x64112a13daa46fe4,
0x672dcfee6690ffc6,
0x677a77581053543b,
0x699873e3758bc6b3,
0x6b3ef9beaa7aa584,
0x6b7b86d8c3df7cd1,
0x6bf6c9e14b7c22c3,
0x6c16c9e14b7c22c3,
0x6d075d226331d03a,
0x6d5a3bdac4f00f33,
0x6e4a2fbffdb7580c,
0x6e927edd0dbb8c08,
0x6ee1c382c3819a0a,
0x70f60cf8f38b0465,
0x7114390c68b888ce,
0x714fb4840532a9e5,
0x727fca36c06cf106,
0x72eba10d818fdafd,
0x737a37935f3b71c9,
0x73972852443155ae,
0x754fe46e378bf132,
0x755fe46e378bf132,
0x756fe46e378bf132,
0x76603d7cb98edc58,
0x76703d7cb98edc58,
0x782f7c6a9ad432a1,
0x78547e17e7814ce7,
0x7964066d88c7cab8,
0x7ace779fddf21621,
0x7ade779fddf21621,
0x7bc3b063946e10ae,
0x7c0c283ffc61c87d,
0x7c31926c7a7122ba,
0x7d0a85c6f7fba05d,
0x7d52a5daf9226f04,
0x7d9220e1772428d7,
0x7db220e1772428d7,
0x7dfe5aceedf1c1f1,
0x7e122815078cb97b,
0x7e8a9b45a91f1700,
0x7eb6202598194bee,
0x7ec6202598194bee,
0x7ef3c8eeb77b8d05,
0x7f03c8eeb77b8d05,
0x7f23c8eeb77b8d05,
0x7f5594223f5654bf,
0x7f9914e03c9260ee,
0x7fc82baa4ae611dc,
0x7fefffffffffffff,
0x001d243f646eaf51,
0x00ab7aa3d73f6658,
0x00cb7aa3d73f6658,
0x010b7aa3d73f6658,
0x012b7aa3d73f6658,
0x0180a0f3c55062c6,
0x0190a0f3c55062c6,
0x03719f08ccdccfe5,
0x03dc25ba6a45de02,
0x05798e3445512a6f,
0x05898e3445512a6f,
0x06bfdadafcacdf85,
0x06cfdadafcacdf85,
0x06f8b03fd6894b66,
0x07c1707c02068785,
0x08567a3c8dc4bc9c,
0x089c25584881552a,
0x08dfa7ebe304ee3d,
0x096822507db6a8fd,
0x09e41934d77659be,
0x0c27b35936d56e27,
0x0c43165633977bc9,
0x0c53165633977bc9,
0x0c63165633977bc9,
0x0c7e9eddbbb259b4,
0x0c9e9eddbbb259b4,
0x0e104273b18918b1,
0x0e204273b18918b1,
0x0e304273b18918b1,
0x0fd6ba8608faa6a8,
0x0fe6ba8608faa6a8,
0x1006b100e18e5c17,
0x104f48347c60a1be,
0x10a4139a6b17b224,
0x12cb91d317c8ebe9,
0x138fb24e492936f6,
0x13afb24e492936f6,
0x14093bb1e72a2033,
0x1476cc4fc92a0fa6,
0x149048cb468bc209,
0x1504c0b3a63c1444,
0x161ba6008389068a,
0x168cfab1a09b49c4,
0x175090684f5fe998,
0x176090684f5fe998,
0x17f4116d591ef1fb,
0x18a710b7a2ef18b7,
0x18d99fccca44882a,
0x199a2cf604c30d3f,
0x1b5ebddc6593c857,
0x1d1b1ad9101b1bfd,
0x1d3b1ad9101b1bfd,
0x1e4035e7b5183923,
0x1e6035e7b5183923,
0x1fd5a79c4e71d028,
0x20cc29bc6879dfcd,
0x20e8823a57adbef8,
0x2104dab846e19e25,
0x2124dab846e19e25,
0x220ce77c2b3328fb,
0x221ce77c2b3328fb,
0x222ce77c2b3328fb,
0x229197b290631476,
0x240a28877a09a4e0,
0x243441ed79830181,
0x244441ed79830181,
0x245441ed79830181,
0x246441ed79830181,
0x247441ed79830181,
0x248b23b50fc204db,
0x24ab23b50fc204db,
0x2633dc6227de9148,
0x2653dc6227de9148,
0x277aacfcb88c92d7,
0x278aacfcb88c92d7,
0x279aacfcb88c92d7,
0x27bbb4c6bd8601bd,
0x289d52af46e5fa69,
0x28b04a616046e074,
0x28d04a616046e074,
0x2a3eeff57768f88c,
0x2b8e3a0aeed7be19,
0x2beec922478c0421,
0x2cc7c3fba45c1271,
0x2cf4f14348a4c5db,
0x2d44f14348a4c5db,
0x2d54f14348a4c5db,
0x2d5a8c931c19b77a,
0x2d64f14348a4c5dc,
0x2efc1249e96b6d8d,
0x2f0f6b23cfe98807,
0x2fe91b9de4d5cf31,
0x308ddc7e975c5045,
0x309ddc7e975c5045,
0x30bddc7e975c5045,
0x3150ed9bd6bfd003,
0x317d2ec75df6ba2a,
0x321aedaa0fc32ac8,
0x32448050091c3c24,
0x328f5a18504dfaac,
0x3336dca59d035820,
0x33ceef5e1f90ac34,
0x33eeef5e1f90ac35,
0x340eef5e1f90ac35,
0x34228f9edfbd3420,
0x34328f9edfbd3420,
0x344eef5e1f90ac35,
0x346eef5e1f90ac35,
0x35008621c4199208,
0x35e0ac2e7f90b8a3,
0x361dde4a4ab13e09,
0x367b870de5d93270,
0x375b20c2f4f8d49f,
0x37f25d342b1e33e5,
0x3854faba79ea92ed,
0x3864faba79ea92ed,
0x3a978cfcab31064d,
0x3aa78cfcab31064d,
0x490cd230a7ff47c3,
0x4929d9577de925d5,
0x4939d9577de925d5,
0x49dcadd6dd730c96,
0x4a7bb6979ae39c49,
0x4b9a32ac316fb3ac,
0x4baa32ac316fb3ac,
0x4bba32ac316fb3ac,
0x4cef20b1a0d7f626,
0x4e2e2785c3a2a20a,
0x4e3e2785c3a2a20a,
0x4e6454b1aef62c8d,
0x4e90fde34c996086,
0x4ea9a2c2a34ac2fa,
0x4eb9a2c2a34ac2fa,
0x4ec9a2c2a34ac2fa,
0x4ed9a2c2a34ac2fa,
0x4f38750ea732fdae,
0x504ca9bade45b94a,
0x514843e10734fa57,
0x51b3274280201a89,
0x521f6a5025e71a61,
0x52c6a47d4e7ec633,
0x55793ba3249a8511,
0x575fe0403124a00e,
0x57863ae2caed4528,
0x57e561def4a9ee32,
0x580561def4a9ee31,
0x582561def4a9ee31,
0x585561def4a9ee31,
0x59d0dd8f2788d699,
0x5b55ed1f039cebfe,
0x5beaf5b5378aa2e5,
0x5c0af5b5378aa2e5,
0x5c4ef3052ef0a361,
0x5e1780695036a679,
0x5e54ec8fd70420c7,
0x5e6b5e2f86026f05,
0x5faaeac2d1ea2695,
0x611260322d04d50b,
0x625be064a3fb2725,
0x64212a13daa46fe4,
0x671dcfee6690ffc6,
0x673dcfee6690ffc6,
0x675dcfee6690ffc6,
0x678a77581053543b,
0x682d3683fa3d1ee0,
0x699cb490951e8515,
0x6b3ef9beaa7aa583,
0x6b4ef9beaa7aa583,
0x6b7896beb0c66eb9,
0x6bdf20938e7414bb,
0x6bef20938e7414bb,
0x6bf6c9e14b7c22c4,
0x6c06c9e14b7c22c4,
0x6c16c9e14b7c22c4,
0x6cf75d226331d03a,
0x6d175d226331d03a,
0x6d4b9445072f4374,
};
const Slab = struct {
str: []const u8,
exp: i32,
};
fn slab(str: []const u8, exp: i32) Slab {
return Slab {
.str = str,
.exp = exp,
};
}
pub const enum3_data = []Slab {
slab("40648030339495312", 69),
slab("4498645355592131", -134),
slab("678321594594593", 244),
slab("36539702510912277", -230),
slab("56819570380646536", -70),
slab("42452693975546964", 175),
slab("34248868699178663", 291),
slab("34037810581283983", -267),
slab("67135881167178176", -188),
slab("74973710847373845", -108),
slab("60272377639347644", -45),
slab("1316415380484425", 116),
slab("64433314612521525", 218),
slab("31961502891542243", 263),
slab("4407140524515149", 303),
slab("69928982131052126", -291),
slab("5331838923808276", -248),
slab("24766435002945523", -208),
slab("21509066976048781", -149),
slab("2347200170470694", -123),
slab("51404180294474556", -89),
slab("12320586499023201", -56),
slab("38099461575161174", 45),
slab("3318949537676913", 79),
slab("48988560059074597", 136),
slab("7955843973866726", 209),
slab("2630089515909384", 227),
slab("11971601492124911", 258),
slab("35394816534699092", 284),
slab("47497368114750945", 299),
slab("54271187548763685", 305),
slab("2504414972009504", -302),
slab("69316187906522606", -275),
slab("53263359599109627", -252),
slab("24384437085962037", -239),
slab("3677854139813342", -213),
slab("44318030915155535", -195),
slab("28150140033551147", -162),
slab("1157373742186464", -143),
slab("2229658838863212", -132),
slab("67817280930489786", -117),
slab("56966478488538934", -92),
slab("49514357246452655", -74),
slab("74426102121433776", -64),
slab("78851753593748485", -55),
slab("19024128529074359", -25),
slab("32118580932839778", 57),
slab("17693166778887419", 72),
slab("78117757194253536", 88),
slab("56627018760181905", 122),
slab("35243988108650928", 153),
slab("38624526316654214", 194),
slab("2397422026462446", 213),
slab("37862966954556723", 224),
slab("56089100059334965", 237),
slab("3666156212014994", 249),
slab("47886405968499643", 258),
slab("48228872759189434", 272),
slab("29980574575739863", 289),
slab("37049827284413546", 297),
slab("37997894491800756", 300),
slab("37263572163337027", 304),
slab("16973149506391291", 308),
slab("391314839376485", -304),
slab("38797447671091856", -300),
slab("54994366114768736", -281),
slab("23593494977819109", -270),
slab("61359116592542813", -265),
slab("1332959730952069", -248),
slab("6096109271490509", -240),
slab("22874741188249992", -231),
slab("33104948806015703", -227),
slab("21670630627577332", -209),
slab("70547825868713855", -201),
slab("54981742371928845", -192),
slab("27843818440071113", -171),
slab("4504022405368184", -161),
slab("2548351460621656", -148),
slab("4629494968745856", -143),
slab("557414709715803", -133),
slab("23897004381644022", -131),
slab("33057350728075958", -117),
slab("47628822744182433", -112),
slab("22520091703825729", -96),
slab("1285104507361864", -89),
slab("46239793787746783", -81),
slab("330095714976351", -73),
slab("4994144928421182", -66),
slab("77003665618895", -58),
slab("49282345996092803", -56),
slab("66534156679273626", -48),
slab("24661175471861008", -36),
slab("45035996273704964", 39),
slab("32402369146794532", 51),
slab("42859354584576066", 61),
slab("1465909318208761", 71),
slab("70772667115549675", 72),
slab("18604316837693468", 86),
slab("38329392744333992", 113),
slab("21062646087750798", 117),
slab("972708181182949", 132),
slab("36683053719290777", 146),
slab("32106017483029628", 166),
slab("41508952543121158", 190),
slab("45072812455233127", 205),
slab("59935550661561155", 212),
slab("40270821632825953", 217),
slab("60846862848160256", 219),
slab("42788225889846894", 225),
slab("28044550029667482", 237),
slab("46475406389115295", 240),
slab("7546114860200514", 246),
slab("7332312424029988", 249),
slab("23943202984249821", 258),
slab("15980751445771122", 263),
slab("21652206566352648", 272),
slab("65171333649148234", 278),
slab("70789633069398184", 284),
slab("68600253110025576", 290),
slab("4234784709771466", 295),
slab("14819930913765419", 298),
slab("9499473622950189", 299),
slab("71272819274635585", 302),
slab("16959746108988652", 304),
slab("13567796887190921", 305),
slab("4735325513114182", 306),
slab("67892598025565165", 308),
slab("81052743999542975", -307),
slab("4971131903427841", -303),
slab("19398723835545928", -300),
slab("29232758945460627", -298),
slab("27497183057384368", -281),
slab("17970091719480621", -275),
slab("22283747288943228", -274),
slab("47186989955638217", -270),
slab("6819439187504402", -266),
slab("47902021250710456", -262),
slab("41378294570975613", -249),
slab("2665919461904138", -248),
slab("3421423777071132", -247),
slab("12192218542981019", -239),
slab("7147520638007367", -235),
slab("45749482376499984", -231),
slab("80596937390013985", -229),
slab("26761990828289327", -214),
slab("18738512510673039", -211),
slab("619160875073638", -209),
slab("403997300048931", -206),
slab("22159015457577768", -195),
slab("13745435592982211", -192),
slab("33567940583589088", -188),
slab("4812711195250522", -184),
slab("3591036630219558", -167),
slab("1126005601342046", -161),
slab("5047135806497922", -154),
slab("43018133952097563", -149),
slab("45209911804158747", -146),
slab("2314747484372928", -143),
slab("65509428048152994", -138),
slab("2787073548579015", -133),
slab("1114829419431606", -132),
slab("4459317677726424", -132),
slab("32269008655522087", -128),
slab("16528675364037979", -117),
slab("66114701456151916", -117),
slab("54934856534126976", -116),
slab("21168365664081082", -111),
slab("67445733463759384", -104),
slab("45590931008842566", -95),
slab("8031903171011649", -91),
slab("2570209014723728", -89),
slab("6516605505584466", -89),
slab("32943123175907307", -78),
slab("82523928744087755", -74),
slab("28409785190323268", -70),
slab("52853886779813977", -69),
slab("30417302377115577", -65),
slab("1925091640472375", -58),
slab("30801466247558002", -57),
slab("24641172998046401", -56),
slab("19712938398437121", -55),
slab("43129529027318865", -52),
slab("15068094409836911", -45),
slab("48658418478920193", -41),
slab("49322350943722016", -36),
slab("38048257058148717", -25),
slab("14411294198511291", 45),
slab("32745697577386472", 48),
slab("16059290466419889", 57),
slab("64237161865679556", 57),
slab("8003248329710242", 63),
slab("81296060678990625", 69),
slab("8846583389443709", 71),
slab("35386333557774838", 72),
slab("21606114462319112", 74),
slab("18413733104063271", 84),
slab("35887030159858487", 87),
slab("2825769263311679", 104),
slab("2138446062528161", 114),
slab("52656615219377", 116),
slab("16850116870200639", 118),
slab("48635409059147446", 132),
slab("12247140014768649", 136),
slab("16836228873919609", 138),
slab("5225574770881846", 147),
slab("42745323906998127", 155),
slab("10613173493886741", 175),
slab("10377238135780289", 190),
slab("29480080280199528", 191),
slab("4679330956996797", 201),
slab("3977921986933363", 209),
slab("56560320317673966", 210),
slab("1198711013231223", 213),
slab("4794844052924892", 213),
slab("16108328653130381", 218),
slab("57878622568856074", 219),
slab("18931483477278361", 224),
slab("4278822588984689", 225),
slab("1315044757954692", 227),
slab("14022275014833741", 237),
slab("5143975308105889", 237),
slab("64517311884236306", 238),
slab("3391607972972965", 244),
slab("3773057430100257", 246),
slab("1833078106007497", 249),
slab("64766168833734675", 249),
slab("1197160149212491", 258),
slab("2394320298424982", 258),
slab("4788640596849964", 258),
slab("1598075144577112", 263),
slab("3196150289154224", 263),
slab("83169412421960475", 271),
slab("43304413132705296", 272),
slab("5546524276967009", 277),
slab("3539481653469909", 284),
slab("7078963306939818", 284),
slab("14990287287869931", 289),
slab("34300126555012788", 290),
slab("17124434349589332", 291),
slab("2117392354885733", 295),
slab("47639264836707725", 296),
slab("7409965456882709", 297),
slab("29639861827530837", 298),
slab("79407577493590275", 299),
slab("18998947245900378", 300),
slab("35636409637317792", 302),
slab("23707742595255608", 303),
slab("47415485190511216", 303),
slab("33919492217977303", 304),
slab("6783898443595461", 304),
slab("27135593774381842", 305),
slab("2367662756557091", 306),
slab("44032152438472327", 307),
slab("33946299012782582", 308),
slab("17976931348623157", 309),
slab("40526371999771488", -307),
slab("1956574196882425", -304),
slab("78262967875297", -304),
slab("1252207486004752", -302),
slab("5008829944019008", -302),
slab("1939872383554593", -300),
slab("3879744767109186", -300),
slab("44144884605471774", -291),
slab("45129663866844427", -289),
slab("2749718305738437", -281),
slab("5499436611476874", -281),
slab("35940183438961242", -275),
slab("71880366877922484", -275),
slab("44567494577886457", -274),
slab("25789638850173173", -270),
slab("17018905290641991", -267),
slab("3409719593752201", -266),
slab("6135911659254281", -265),
slab("23951010625355228", -262),
slab("51061856989121905", -260),
slab("4137829457097561", -249),
slab("13329597309520689", -248),
slab("26659194619041378", -248),
slab("53318389238082755", -248),
slab("1710711888535566", -247),
slab("6842847554142264", -247),
slab("609610927149051", -240),
slab("1219221854298102", -239),
slab("2438443708596204", -239),
slab("2287474118824999", -231),
slab("4574948237649998", -231),
slab("18269851255456139", -230),
slab("40298468695006992", -229),
slab("16552474403007851", -227),
slab("39050270537318193", -217),
slab("1838927069906671", -213),
slab("7355708279626684", -213),
slab("37477025021346077", -211),
slab("43341261255154663", -209),
slab("12383217501472761", -208),
slab("2019986500244655", -206),
slab("35273912934356928", -201),
slab("47323883490786093", -199),
slab("2215901545757777", -195),
slab("4431803091515554", -195),
slab("27490871185964422", -192),
slab("64710073234908765", -189),
slab("57511323531737074", -188),
slab("2406355597625261", -184),
slab("75862936714499446", -176),
slab("1795518315109779", -167),
slab("7182073260439116", -167),
slab("563002800671023", -162),
slab("2252011202684092", -161),
slab("2523567903248961", -154),
slab("10754533488024391", -149),
slab("37436263604934127", -149),
slab("1274175730310828", -148),
slab("5096702921243312", -148),
slab("11573737421864639", -143),
slab("23147474843729279", -143),
slab("46294949687458557", -143),
slab("36067106647774144", -141),
slab("44986453555921307", -134),
slab("27870735485790148", -133),
slab("55741470971580295", -133),
slab("11148294194316059", -132),
slab("22296588388632118", -132),
slab("44593176777264236", -132),
slab("11948502190822011", -131),
slab("47794008763288043", -131),
slab("1173600085235347", -123),
slab("4694400340941388", -123),
slab("1652867536403798", -117),
slab("3305735072807596", -117),
slab("6611470145615192", -117),
slab("27467428267063488", -116),
slab("4762882274418243", -112),
slab("10584182832040541", -111),
slab("42336731328162165", -111),
slab("33722866731879692", -104),
slab("69097540994131414", -98),
slab("45040183407651457", -96),
slab("5696647848853893", -92),
slab("40159515855058247", -91),
slab("12851045073618639", -89),
slab("25702090147237278", -89),
slab("3258302752792233", -89),
slab("5140418029447456", -89),
slab("23119896893873391", -81),
slab("51753157237874753", -81),
slab("67761208324172855", -77),
slab("8252392874408775", -74),
slab("1650478574881755", -73),
slab("660191429952702", -73),
slab("3832399419240467", -70),
slab("26426943389906988", -69),
slab("2497072464210591", -66),
slab("15208651188557789", -65),
slab("37213051060716888", -64),
slab("55574205388093594", -61),
slab("385018328094475", -58),
slab("15400733123779001", -57),
slab("61602932495116004", -57),
slab("14784703798827841", -56),
slab("29569407597655683", -56),
slab("9856469199218561", -56),
slab("39425876796874242", -55),
slab("21564764513659432", -52),
slab("35649516398744314", -48),
slab("51091836539008967", -47),
slab("30136188819673822", -45),
slab("4865841847892019", -41),
slab("33729482964455627", -38),
slab("2466117547186101", -36),
slab("4932235094372202", -36),
slab("1902412852907436", -25),
slab("3804825705814872", -25),
slab("80341375308088225", 44),
slab("28822588397022582", 45),
slab("57645176794045164", 45),
slab("65491395154772944", 48),
slab("64804738293589064", 51),
slab("1605929046641989", 57),
slab("3211858093283978", 57),
slab("6423716186567956", 57),
slab("4001624164855121", 63),
slab("4064803033949531", 69),
slab("8129606067899062", 69),
slab("4384946084578497", 70),
slab("2931818636417522", 71),
slab("884658338944371", 71),
slab("1769316677888742", 72),
slab("3538633355777484", 72),
slab("7077266711554968", 72),
slab("43212228924638223", 74),
slab("6637899075353826", 79),
slab("36827466208126543", 84),
slab("37208633675386937", 86),
slab("39058878597126768", 88),
slab("57654578150150385", 91),
slab("5651538526623358", 104),
slab("76658785488667984", 113),
slab("4276892125056322", 114),
slab("263283076096885", 116),
slab("10531323043875399", 117),
slab("42125292175501597", 117),
slab("33700233740401277", 118),
slab("44596066840334405", 125),
slab("9727081811829489", 132),
slab("61235700073843246", 135),
slab("24494280029537298", 136),
slab("4499029632233837", 137),
slab("18341526859645389", 146),
slab("2612787385440923", 147),
slab("6834859331393543", 147),
slab("70487976217301855", 153),
slab("40366692112133834", 160),
slab("64212034966059256", 166),
slab("21226346987773482", 175),
slab("51886190678901447", 189),
slab("20754476271560579", 190),
slab("83017905086242315", 190),
slab("58960160560399056", 191),
slab("66641177824100826", 194),
slab("5493127645170153", 201),
slab("39779219869333628", 209),
slab("79558439738667255", 209),
slab("50523702331566894", 210),
slab("40933393326155808", 212),
slab("81866786652311615", 212),
slab("11987110132312231", 213),
slab("23974220264624462", 213),
slab("47948440529248924", 213),
slab("8054164326565191", 217),
slab("32216657306260762", 218),
slab("30423431424080128", 219),
}; | std/fmt/errol/enum3.zig |
pub const Backend = @import("backend.zig").Backend;
pub const Device = @import("backend/session.zig").Device;
pub const Session = @import("backend/session.zig").Session;
pub const DmabufAttributes = @import("render/dmabuf.zig").DmabufAttributes;
pub const Renderer = @import("render/renderer.zig").Renderer;
pub const Texture = @import("render/texture.zig").Texture;
pub const Allocator = @import("render/allocator.zig").Allocator;
pub const Swapchain = opaque {};
pub const DrmFormat = @import("render/drm_format_set.zig").DrmFormat;
pub const DrmFormatSet = @import("render/drm_format_set.zig").DrmFormatSet;
pub const ShmAttributes = @import("types/buffer.zig").ShmAttributes;
pub const Buffer = @import("types/buffer.zig").Buffer;
pub const ClientBuffer = @import("types/buffer.zig").ClientBuffer;
pub const DmabufBufferV1 = @import("types/linux_dmabuf_v1.zig").DmabufBufferV1;
pub const LinuxDmabufV1 = @import("types/linux_dmabuf_v1.zig").LinuxDmabufV1;
pub const Compositor = @import("types/compositor.zig").Compositor;
pub const Subcompositor = @import("types/compositor.zig").Subcompositor;
pub const Surface = @import("types/surface.zig").Surface;
pub const Subsurface = @import("types/surface.zig").Subsurface;
pub const Viewporter = @import("types/viewporter.zig").Viewporter;
pub const Presentation = @import("types/presentation_time.zig").Presentation;
pub const PresentationFeedback = @import("types/presentation_time.zig").PresentationFeedback;
pub const PresentationEvent = @import("types/presentation_time.zig").PresentationEvent;
pub const XdgShell = @import("types/xdg_shell.zig").XdgShell;
pub const XdgClient = @import("types/xdg_shell.zig").XdgClient;
pub const XdgSurface = @import("types/xdg_shell.zig").XdgSurface;
pub const XdgToplevel = @import("types/xdg_shell.zig").XdgToplevel;
pub const XdgPositioner = @import("types/xdg_shell.zig").XdgPositioner;
pub const XdgPopupGrab = @import("types/xdg_shell.zig").XdgPopupGrab;
pub const XdgPopup = @import("types/xdg_shell.zig").XdgPopup;
pub const XdgDecorationManagerV1 = @import("types/xdg_decoration_v1.zig").XdgDecorationManagerV1;
pub const XdgToplevelDecorationV1 = @import("types/xdg_decoration_v1.zig").XdgToplevelDecorationV1;
pub const XdgActivationV1 = @import("types/xdg_activation_v1.zig").XdgActivationV1;
pub const XdgActivationTokenV1 = @import("types/xdg_activation_v1.zig").XdgActivationTokenV1;
pub const LayerShellV1 = @import("types/layer_shell_v1.zig").LayerShellV1;
pub const LayerSurfaceV1 = @import("types/layer_shell_v1.zig").LayerSurfaceV1;
pub const Seat = @import("types/seat.zig").Seat;
pub const SerialRange = @import("types/seat.zig").SerialRange;
pub const SerialRingset = @import("types/seat.zig").SerialRingset;
pub const TouchPoint = @import("types/seat.zig").TouchPoint;
pub const InputDevice = @import("types/input_device.zig").InputDevice;
pub const InputMethodV2 = @import("types/input_method_v2.zig").InputMethodV2;
pub const InputMethodManagerV2 = @import("types/input_method_v2.zig").InputMethodManagerV2;
pub const InputPopupSurfaceV2 = @import("types/input_method_v2.zig").InputPopupSurfaceV2;
pub const TextInputV3 = @import("types/text_input_v3.zig").TextInputV3;
pub const TextInputManagerV3 = @import("types/text_input_v3.zig").TextInputManagerV3;
pub const Keyboard = @import("types/keyboard.zig").Keyboard;
pub const KeyboardGroup = @import("types/keyboard_group.zig").KeyboardGroup;
pub const KeyboardShortcutsInhibitorV1 = @import("types/keyboard_shortcuts_inhibit_v1.zig").KeyboardShortcutsInhibitorV1;
pub const KeyboardShortcutsInhibitManagerV1 = @import("types/keyboard_shortcuts_inhibit_v1.zig").KeyboardShortcutsInhibitManagerV1;
pub const Cursor = @import("types/cursor.zig").Cursor;
pub const Pointer = @import("types/pointer.zig").Pointer;
pub const PointerConstraintV1 = @import("types/pointer_constraints_v1.zig").PointerConstraintV1;
pub const PointerConstraintsV1 = @import("types/pointer_constraints_v1.zig").PointerConstraintsV1;
pub const PointerGesturesV1 = @import("types/pointer_gestures_v1.zig").PointerGesturesV1;
pub const AxisOrientation = @import("types/pointer.zig").AxisOrientation;
pub const AxisSource = @import("types/pointer.zig").AxisSource;
pub const RelativePointerManagerV1 = @import("types/relative_pointer_v1.zig").RelativePointerManagerV1;
pub const RelativePointerV1 = @import("types/relative_pointer_v1.zig").RelativePointerV1;
pub const Touch = @import("types/touch.zig").Touch;
pub const Tablet = @import("types/tablet_tool.zig").Tablet;
pub const TabletTool = @import("types/tablet_tool.zig").TabletTool;
pub const Switch = @import("types/switch.zig").Switch;
pub const VirtualPointerManagerV1 = @import("types/virtual_pointer_v1.zig").VirtualPointerManagerV1;
pub const VirtualPointerV1 = @import("types/virtual_pointer_v1.zig").VirtualPointerV1;
pub const VirtualKeyboardManagerV1 = @import("types/virtual_keyboard_v1.zig").VirtualKeyboardManagerV1;
pub const VirtualKeyboardV1 = @import("types/virtual_keyboard_v1.zig").VirtualKeyboardV1;
pub const Idle = @import("types/idle.zig").Idle;
pub const IdleTimeout = @import("types/idle.zig").IdleTimeout;
pub const IdleInhibitManagerV1 = @import("types/idle_inhibit_v1.zig").IdleInhibitManagerV1;
pub const IdleInhibitorV1 = @import("types/idle_inhibit_v1.zig").IdleInhibitorV1;
pub const InputInhibitManager = @import("types/input_inhibitor.zig").InputInhibitManager;
pub const DataDeviceManager = @import("types/data_device.zig").DataDeviceManager;
pub const DataOffer = @import("types/data_device.zig").DataOffer;
pub const DataSource = @import("types/data_device.zig").DataSource;
pub const Drag = @import("types/data_device.zig").Drag;
pub const DataControlManagerV1 = @import("types/data_control_v1.zig").DataControlManagerV1;
pub const DataControlDeviceV1 = @import("types/data_control_v1.zig").DataControlDeviceV1;
pub const PrimarySelectionSource = @import("types/primary_selection.zig").PrimarySelectionSource;
pub const PrimarySelectionDeviceManagerV1 = @import("types/primary_selection_v1.zig").PrimarySelectionDeviceManagerV1;
pub const PrimarySelectionDeviceV1 = @import("types/primary_selection_v1.zig").PrimarySelectionDeviceV1;
pub const Output = @import("types/output.zig").Output;
pub const OutputCursor = @import("types/output.zig").OutputCursor;
pub const OutputDamage = @import("types/output_damage.zig").OutputDamage;
pub const OutputLayout = @import("types/output_layout.zig").OutputLayout;
pub const XdgOutputManagerV1 = @import("types/xdg_output_v1.zig").XdgOutputManagerV1;
pub const XdgOutputV1 = @import("types/xdg_output_v1.zig").XdgOutputV1;
pub const OutputPowerManagerV1 = @import("types/output_power_management_v1.zig").OutputPowerManagerV1;
pub const OutputPowerV1 = @import("types/output_power_management_v1.zig").OutputPowerV1;
pub const ExportDmabufManagerV1 = @import("types/export_dmabuf_v1.zig").ExportDmabufManagerV1;
pub const ExportDmabufFrameV1 = @import("types/export_dmabuf_v1.zig").ExportDmabufFrameV1;
pub const ScreencopyManagerV1 = @import("types/screencopy_v1.zig").ScreencopyManagerV1;
pub const ScreencopyClientV1 = @import("types/screencopy_v1.zig").ScreencopyClientV1;
pub const ScreencopyFrameV1 = @import("types/screencopy_v1.zig").ScreencopyFrameV1;
pub const GammaControlManagerV1 = @import("types/gamma_control_v1.zig").GammaControlManagerV1;
pub const GamaControlV1 = @import("types/gamma_control_v1.zig").GamaControlV1;
pub const XcursorImage = @import("xcursor.zig").XcursorImage;
pub const Xcursor = @import("xcursor.zig").Xcursor;
pub const XcursorTheme = @import("xcursor.zig").XcursorTheme;
pub const XcursorManager = @import("types/xcursor_manager.zig").XcursorManager;
pub const XcursorManagerTheme = @import("types/xcursor_manager.zig").XcursorManagerTheme;
pub const Xwayland = @import("xwayland.zig").Xwayland;
pub const XwaylandServer = @import("xwayland.zig").XwaylandServer;
pub const XwaylandSurface = @import("xwayland.zig").XwaylandSurface;
pub const XwaylandCursor = @import("xwayland.zig").XwaylandCursor;
pub const Xwm = @import("xwayland.zig").Xwm;
pub const matrix = @import("types/matrix.zig");
pub const AddonSet = @import("util/addon.zig").AddonSet;
pub const Addon = @import("util/addon.zig").Addon;
pub const Box = @import("util/box.zig").Box;
pub const FBox = @import("util/box.zig").FBox;
pub const Edges = @import("util/edges.zig").Edges;
pub const log = @import("util/log.zig");
pub const region = @import("util/region.zig");
pub const OutputManagerV1 = @import("types/output_management_v1.zig").OutputManagerV1;
pub const OutputHeadV1 = @import("types/output_management_v1.zig").OutputHeadV1;
pub const OutputConfigurationV1 = @import("types/output_management_v1.zig").OutputConfigurationV1;
pub const ForeignToplevelManagerV1 = @import("types/foreign_toplevel_management_v1.zig").ForeignToplevelManagerV1;
pub const ForeignToplevelHandleV1 = @import("types/foreign_toplevel_management_v1.zig").ForeignToplevelHandleV1;
pub const SceneNode = @import("types/scene.zig").SceneNode;
pub const Scene = @import("types/scene.zig").Scene;
pub const SceneTree = @import("types/scene.zig").SceneTree;
pub const SceneSurface = @import("types/scene.zig").SceneSurface;
pub const SceneRect = @import("types/scene.zig").SceneRect;
pub const SceneBuffer = @import("types/scene.zig").SceneBuffer;
pub const SceneOutput = @import("types/scene.zig").SceneOutput;
pub const config = @import("config.zig");
pub const version = @import("version.zig");
comptime {
if (version.major != 0 or version.minor != 15) {
@compileError("zig-wlroots requires wlroots version 0.15");
}
}
fn refAllDeclsRecursive(comptime T: type) void {
comptime {
for (@import("std").meta.declarations(T)) |decl| {
if (decl.is_pub) {
switch (decl.data) {
.Type => |T2| refAllDeclsRecursive(T2),
else => _ = decl,
}
}
}
}
}
test {
@setEvalBranchQuota(100000);
refAllDeclsRecursive(@This());
} | src/wlroots.zig |
usingnamespace @import("PeerType/PeerType.zig");
const std = @import("std");
fn MixtimeType(comptime description: anytype, comptime Tuple: type) type {
const Context = enum { compiletime, runtime };
const StructField = std.builtin.TypeInfo.StructField;
const tuple_fields = std.meta.fields(Tuple);
var struct_field_data: [tuple_fields.len]StructField = undefined;
var extra_error_msg: []const u8 = "Extraneous fields:\n";
var extra_fields = false;
for (tuple_fields) |field, tuple_i| {
var descr_idx: ?usize = null;
for (description) |d, d_i| {
if (std.mem.eql(u8, d[0], field.name)) {
descr_idx = d_i;
}
}
if (descr_idx) |i| {
const context: Context = description[i][1];
if (context == .compiletime and !field.is_comptime)
@compileError("Field '" ++ field.name ++ "' should be compile time known");
struct_field_data[tuple_i] = field;
const new_field = &struct_field_data[tuple_i];
if (context == .runtime) {
new_field.is_comptime = false;
}
// If the field description contains two elements, the field is
// typeless, so we can keep the struct's type information intact.
if (description[i].len > 2) {
// If the next description element is a type, we perform typechecking
if (@TypeOf(description[i][2]) == type) {
if (!coercesTo(description[i][2], field.field_type))
@compileError("Field '" ++ field.name ++ "' should be " ++ @typeName(description[i][2]) ++ ", is " ++ @typeName(field.field_type));
new_field.field_type = description[i][2];
new_field.default_value = if (new_field.default_value) |d|
@as(?description[i][2], d)
else
null;
}
} else {
if (context == .runtime) {
if (requiresComptime(field.field_type)) {
@compileError("Cannot initialize runtime typeless field '" ++ field.name ++
"' with value of comptime-only type '" ++ @typeName(field.field_type) ++ "'");
}
}
new_field.default_value = null;
}
} else {
extra_error_msg = extra_error_msg ++ " -- " ++ field.name ++ "\n";
extra_fields = true;
}
}
if (extra_fields) @compileError(extra_error_msg);
var extra_field_data: [description.len - tuple_fields.len]StructField = undefined;
var i = 0;
for (description) |descr| {
if (!@hasField(Tuple, descr[0])) {
if (descr.len == 2) {
@compileError("Missing value for typeless field '" ++ descr[0] ++ "'.");
}
const context: Context = descr[1];
if (@TypeOf(descr[2]) == type) {
if (descr.len != 4) {
@compileError("Missing value for field '" ++ descr[0] ++ "' with no default value");
}
const default_value: ?descr[2] = descr[3];
extra_field_data[i] = .{
.name = descr[0],
.field_type = descr[2],
.default_value = default_value,
.is_comptime = context == .compiletime,
.alignment = if (@sizeOf(descr[2]) > 0) @alignOf(descr[2]) else 0,
};
i += 1;
} else {
const field_type = @TypeOf(descr[2]);
const default_value: ?field_type = descr[2];
extra_field_data[i] = .{
.name = descr[0],
.field_type = field_type,
.default_value = default_value,
.is_comptime = context == .compiletime,
.alignment = if (@sizeOf(field_type) > 0) @alignOf(field_type) else 0,
};
i += 1;
}
}
}
const struct_fields = &struct_field_data ++ &extra_field_data;
return @Type(.{
.Struct = .{
.is_tuple = false,
.layout = .Auto,
.decls = &[_]std.builtin.TypeInfo.Declaration{},
.fields = struct_fields,
},
});
}
pub fn mixtime(comptime description: anytype) type {
return struct {
pub fn make(tuple: anytype) MixtimeType(description, @TypeOf(tuple)) {
const Tuple = @TypeOf(tuple);
const T = MixtimeType(description, @TypeOf(tuple));
var value: T = undefined;
inline for (std.meta.fields(T)) |field| {
if (field.is_comptime)
continue;
if (@hasField(Tuple, field.name)) {
@field(value, field.name) = @field(tuple, field.name);
} else if (field.default_value) |default_value| {
@field(value, field.name) = default_value;
} else unreachable;
}
return value;
}
};
}
// Fix this gap highlighter issue vvvvv
const DummyOptions = mixtime(.{
.{ "name", .compiletime, []const u8 },
.{ "port", .runtime, usize, 8080 },
.{ "some_type", .compiletime, type, void },
.{ "any", .runtime },
// Defaults to 42 but can be of any type
.{ "ct_any", .compiletime, 42 },
});
fn takesOptions(option_tuple: anytype) void {
const options = DummyOptions.make(option_tuple);
_ = options.name;
_ = options.port;
_ = options.some_type;
_ = options.any;
_ = options.ct_any;
}
test "dummy test" {
takesOptions(.{ .name = "whatever", .some_type = usize, .any = @as(usize, 0) });
takesOptions(.{ .name = "whatever", .port = 101, .any = "hello" });
var rt_value: usize = 0;
takesOptions(.{ .name = "whatever", .port = rt_value, .ct_any = u616, .any = {} });
takesOptions(.{ .name = "whatever", .some_type = usize, .any = &rt_value });
// errors
// takesOptions(.{ .name = "whatever", .some_type = usize }); // error: Missing value for typeless field 'any'.
// takesOptions(.{ .any = usize }); // error: Cannot initialize runtime typeless field 'any' with value of comptime-only type 'type'
// takesOptions(.{ .port = 1337 }); // error: Missing field 'name' with no default value
// var rt_name: []const u8 = "hi there";
// takesOptions(.{ .name = rt_name }); // error: Field 'name' should be compile time known
// takesOptions(.{ .foo = 0 }); // error: Extraneous fields:
// // -- foo
} | src/mixtime.zig |
//--------------------------------------------------------------------------------
// Section: Types (3)
//--------------------------------------------------------------------------------
// TODO: this type is limited to platform 'windows10.0.14393'
const IID_IRadialControllerInterop_Value = @import("../../zig.zig").Guid.initString("1b0535c9-57ad-45c1-9d79-ad5c34360513");
pub const IID_IRadialControllerInterop = &IID_IRadialControllerInterop_Value;
pub const IRadialControllerInterop = extern struct {
pub const VTable = extern struct {
base: IInspectable.VTable,
CreateForWindow: fn(
self: *const IRadialControllerInterop,
hwnd: ?HWND,
riid: ?*const Guid,
ppv: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IInspectable.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRadialControllerInterop_CreateForWindow(self: *const T, hwnd: ?HWND, riid: ?*const Guid, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IRadialControllerInterop.VTable, self.vtable).CreateForWindow(@ptrCast(*const IRadialControllerInterop, self), hwnd, riid, ppv);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.14393'
const IID_IRadialControllerConfigurationInterop_Value = @import("../../zig.zig").Guid.initString("787cdaac-3186-476d-87e4-b9374a7b9970");
pub const IID_IRadialControllerConfigurationInterop = &IID_IRadialControllerConfigurationInterop_Value;
pub const IRadialControllerConfigurationInterop = extern struct {
pub const VTable = extern struct {
base: IInspectable.VTable,
GetForWindow: fn(
self: *const IRadialControllerConfigurationInterop,
hwnd: ?HWND,
riid: ?*const Guid,
ppv: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IInspectable.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRadialControllerConfigurationInterop_GetForWindow(self: *const T, hwnd: ?HWND, riid: ?*const Guid, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IRadialControllerConfigurationInterop.VTable, self.vtable).GetForWindow(@ptrCast(*const IRadialControllerConfigurationInterop, self), hwnd, riid, ppv);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRadialControllerIndependentInputSourceInterop_Value = @import("../../zig.zig").Guid.initString("3d577eff-4cee-11e6-b535-001bdc06ab3b");
pub const IID_IRadialControllerIndependentInputSourceInterop = &IID_IRadialControllerIndependentInputSourceInterop_Value;
pub const IRadialControllerIndependentInputSourceInterop = extern struct {
pub const VTable = extern struct {
base: IInspectable.VTable,
CreateForWindow: fn(
self: *const IRadialControllerIndependentInputSourceInterop,
hwnd: ?HWND,
riid: ?*const Guid,
ppv: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IInspectable.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRadialControllerIndependentInputSourceInterop_CreateForWindow(self: *const T, hwnd: ?HWND, riid: ?*const Guid, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IRadialControllerIndependentInputSourceInterop.VTable, self.vtable).CreateForWindow(@ptrCast(*const IRadialControllerIndependentInputSourceInterop, self), hwnd, riid, ppv);
}
};}
pub usingnamespace MethodMixin(@This());
};
//--------------------------------------------------------------------------------
// Section: Functions (0)
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (0)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../../zig.zig").unicode_mode) {
.ansi => struct {
},
.wide => struct {
},
.unspecified => if (@import("builtin").is_test) struct {
} else struct {
},
};
//--------------------------------------------------------------------------------
// Section: Imports (4)
//--------------------------------------------------------------------------------
const Guid = @import("../../zig.zig").Guid;
const HRESULT = @import("../../foundation.zig").HRESULT;
const HWND = @import("../../foundation.zig").HWND;
const IInspectable = @import("../../system/win_rt.zig").IInspectable;
test {
@setEvalBranchQuota(
@import("std").meta.declarations(@This()).len * 3
);
// reference all the pub declarations
if (!@import("builtin").is_test) return;
inline for (@import("std").meta.declarations(@This())) |decl| {
if (decl.is_pub) {
_ = decl;
}
}
} | win32/ui/input/radial.zig |
const std = @import("std");
const json = std.json;
const debug = std.debug;
const io = std.io;
const fs = std.fs;
const mem = std.mem;
const zig = std.zig;
const protocol = @import("protocol.zig");
const types = @import("types.zig");
const serial = @import("json_serialize.zig");
const data = @import("data.zig");
pub const TextDocument = struct {
uri: types.DocumentUri,
text: types.String,
pub fn findPosition(self: *const TextDocument, position: types.Position) error{InvalidParams}!usize {
var it = mem.split(self.text, "\n");
var line: i64 = 0;
while (line < position.line) : (line += 1) {
_ = it.next() orelse return error.InvalidParams;
}
var index = @intCast(i64, it.index.?) + position.character;
if (index < 0 or index >= @intCast(i64, self.text.len)) {
return error.InvalidParams;
}
return @intCast(usize, index);
}
};
pub const Server = struct {
const Self = @This();
const MethodError = protocol.Dispatcher(Server).MethodError;
alloc: *mem.Allocator,
outStream: *fs.File.OutStream,
documents: std.StringHashMap(TextDocument),
pub fn init(allocator: *mem.Allocator, outStream: *fs.File.OutStream) Self {
return Self{
.alloc = allocator,
.outStream = outStream,
.documents = std.StringHashMap(TextDocument).init(allocator),
};
}
pub fn deinit(self: *Self) void {
self.documents.deinit();
}
fn send(self: *Self, requestOrResponse: var) !void {
debug.assert(requestOrResponse.validate());
var mem_buffer: [1024 * 128]u8 = undefined;
var sliceStream = io.fixedBufferStream(&mem_buffer);
var jsonStream = json.WriteStream(@TypeOf(sliceStream.outStream()), 1024).init(sliceStream.outStream());
try serial.serialize(requestOrResponse, &jsonStream);
try protocol.writeMessage(self.outStream, sliceStream.getWritten());
}
pub fn onInitialize(self: *Self, params: types.InitializeParams, reqId: types.RequestId) !void {
const result =
\\{
\\ "capabilities": {
\\ "textDocumentSync": {"openClose": true, "change": 2},
\\ "completionProvider": {"triggerCharacters": ["@"]}
\\ }
\\}
;
var parser = json.Parser.init(self.alloc, false);
defer parser.deinit();
var tree = try parser.parse(result[0..]);
defer tree.deinit();
try self.send(types.Response{
.result = .{ .Defined = tree.root },
.id = reqId,
});
}
pub fn onInitialized(self: *Self, params: types.InitializedParams) MethodError!void {}
pub fn onTextDocumentDidOpen(self: *Self, params: types.DidOpenTextDocumentParams) !void {
const document = TextDocument{
.uri = try mem.dupe(self.alloc, u8, params.textDocument.uri),
.text = try mem.dupe(self.alloc, u8, params.textDocument.text),
};
const alreadyThere = try self.documents.put(document.uri, document);
if (alreadyThere != null) {
return MethodError.InvalidParams;
}
try self.publishDiagnostics(document);
}
pub fn onTextDocumentDidChange(self: *Self, params: types.DidChangeTextDocumentParams) !void {
var document: *TextDocument = &(self.documents.get(params.textDocument.uri) orelse return MethodError.InvalidParams).value;
for (params.contentChanges) |change| {
switch (change.range) {
.Defined => |range| {
const one = document.text[0..try document.findPosition(range.start)];
const three = document.text[try document.findPosition(range.end)..document.text.len];
const new = try mem.concat(self.alloc, u8, &[3][]const u8{ one, change.text, three });
self.alloc.free(document.text);
document.text = new;
},
.NotDefined => { // whole document change
self.alloc.free(document.text);
document.text = try mem.dupe(self.alloc, u8, change.text);
},
}
}
try self.publishDiagnostics(document.*);
}
pub fn onTextDocumentDidClose(self: *Self, params: types.DidCloseTextDocumentParams) !void {
var maybeEntry = self.documents.remove(params.textDocument.uri);
if (maybeEntry) |entry| {
self.alloc.free(entry.value.uri);
self.alloc.free(entry.value.text);
} else {
return MethodError.InvalidParams;
}
}
fn publishDiagnostics(self: *Self, document: TextDocument) !void {
const tree = try zig.parse(self.alloc, document.text);
defer tree.deinit();
var diagnostics = try self.alloc.alloc(types.Diagnostic, tree.errors.len);
defer self.alloc.free(diagnostics);
var msgAlloc = std.heap.ArenaAllocator.init(self.alloc);
defer msgAlloc.deinit();
var it = tree.errors.iterator(0);
var i: usize = 0;
while (it.next()) |err| : (i += 1) {
const token = tree.tokens.at(err.loc());
const location = tree.tokenLocation(0, err.loc());
var text_list = std.ArrayList(u8).init(&msgAlloc.allocator);
try err.render(&tree.tokens, text_list.outStream());
diagnostics[i] = types.Diagnostic{
.range = types.Range{
.start = types.Position{
.line = @intCast(i64, location.line),
.character = @intCast(i64, location.column),
},
.end = types.Position{
.line = @intCast(i64, location.line),
.character = @intCast(i64, location.column + (token.end - token.start)),
},
},
.severity = .{ .Defined = .Error },
.message = text_list.items,
};
}
const outParam = types.PublishDiagnosticsParams{
.uri = document.uri,
.diagnostics = diagnostics,
};
var resultTree = try serial.serialize2(outParam, self.alloc);
defer resultTree.deinit();
try self.send(types.Request{
.method = "textDocument/publishDiagnostics",
.params = resultTree.root,
});
}
pub fn onTextDocumentCompletion(self: *Self, params: types.CompletionParams, reqId: types.RequestId) !void {
const document = (self.documents.getValue(params.textDocument.uri) orelse return MethodError.InvalidParams);
const posToCheck = types.Position{
.line = params.position.line,
.character = params.position.character - 1,
};
if (posToCheck.character >= 0) {
const pos = try document.findPosition(posToCheck);
const char = document.text[pos];
if (char == '@') {
var items: [data.builtins.len]types.CompletionItem = undefined;
for (data.builtins) |builtin, i| {
items[i] = types.CompletionItem{
.label = builtin,
.kind = .{ .Defined = .Function },
.textEdit = .{
.Defined = types.TextEdit{
.range = types.Range{
.start = params.position,
.end = params.position,
},
.newText = builtin[1..],
},
},
.filterText = .{ .Defined = builtin[1..] },
};
}
var tree = try serial.serialize2(items[0..], self.alloc);
defer tree.deinit();
try self.send(types.Response{
.id = reqId,
.result = .{ .Defined = tree.root },
});
return;
}
}
try self.send(types.Response{
.id = reqId,
.result = .{ .Defined = .Null },
});
}
};
pub fn main() !void {
var failingAlloc = std.testing.FailingAllocator.init(std.heap.page_allocator, 10000000000);
const heap = &failingAlloc.allocator;
// const heap = std.heap.page_allocator;
var in = io.getStdIn().inStream();
var out = io.getStdOut().outStream();
var server = Server.init(heap, &out);
defer server.deinit();
var dispatcher = protocol.Dispatcher(Server).init(&server, heap);
defer dispatcher.deinit();
try dispatcher.registerRequest("initialize", types.InitializeParams, Server.onInitialize);
try dispatcher.registerNotification("initialized", types.InitializedParams, Server.onInitialized);
try dispatcher.registerNotification("textDocument/didOpen", types.DidOpenTextDocumentParams, Server.onTextDocumentDidOpen);
try dispatcher.registerNotification("textDocument/didChange", types.DidChangeTextDocumentParams, Server.onTextDocumentDidChange);
try dispatcher.registerNotification("textDocument/didClose", types.DidCloseTextDocumentParams, Server.onTextDocumentDidClose);
try dispatcher.registerRequest("textDocument/completion", types.CompletionParams, Server.onTextDocumentCompletion);
while (true) {
debug.warn("mem: {}\n", .{failingAlloc.allocated_bytes - failingAlloc.freed_bytes});
const message = protocol.readMessageAlloc(&in, heap) catch |err| {
// Don't crash on malformed requests
debug.warn("Error reading message: {}\n", .{err});
continue;
};
defer heap.free(message);
var parser = json.Parser.init(heap, false);
defer parser.deinit();
var tree = try parser.parse(message);
defer tree.deinit();
var request = try serial.deserialize(types.Request, tree.root, heap);
defer request.deinit();
if (!request.result.validate()) {
return error.InvalidMessage;
}
dispatcher.dispatch(request.result) catch |err| {
debug.warn("{}\n", .{err});
};
}
} | src/server.zig |
const std = @import("std");
const server = &@import("../main.zig").server;
const Error = @import("../command.zig").Error;
const PhysicalDirection = @import("../command.zig").PhysicalDirection;
const Orientation = @import("../command.zig").Orientation;
const Seat = @import("../Seat.zig");
const View = @import("../View.zig");
const Box = @import("../Box.zig");
pub fn move(
allocator: *std.mem.Allocator,
seat: *Seat,
args: []const [:0]const u8,
out: *?[]const u8,
) Error!void {
if (args.len < 3) return Error.NotEnoughArguments;
if (args.len > 3) return Error.TooManyArguments;
const delta = try std.fmt.parseInt(i32, args[2], 10);
const direction = std.meta.stringToEnum(PhysicalDirection, args[1]) orelse
return Error.InvalidPhysicalDirection;
const view = getView(seat) orelse return;
switch (direction) {
.up => view.move(0, -delta),
.down => view.move(0, delta),
.left => view.move(-delta, 0),
.right => view.move(delta, 0),
}
apply(view);
}
pub fn snap(
allocator: *std.mem.Allocator,
seat: *Seat,
args: []const [:0]const u8,
out: *?[]const u8,
) Error!void {
if (args.len < 2) return Error.NotEnoughArguments;
if (args.len > 2) return Error.TooManyArguments;
const direction = std.meta.stringToEnum(PhysicalDirection, args[1]) orelse
return Error.InvalidPhysicalDirection;
const view = getView(seat) orelse return;
const border_width = @intCast(i32, server.config.border_width);
const output_box = view.output.getEffectiveResolution();
switch (direction) {
.up => view.pending.box.y = border_width,
.down => view.pending.box.y =
@intCast(i32, output_box.height - view.pending.box.height) - border_width,
.left => view.pending.box.x = border_width,
.right => view.pending.box.x =
@intCast(i32, output_box.width - view.pending.box.width) - border_width,
}
apply(view);
}
pub fn resize(
allocator: *std.mem.Allocator,
seat: *Seat,
args: []const [:0]const u8,
out: *?[]const u8,
) Error!void {
if (args.len < 3) return Error.NotEnoughArguments;
if (args.len > 3) return Error.TooManyArguments;
const delta = try std.fmt.parseInt(i32, args[2], 10);
const orientation = std.meta.stringToEnum(Orientation, args[1]) orelse
return Error.InvalidOrientation;
const view = getView(seat) orelse return;
const border_width = @intCast(i32, server.config.border_width);
const output_box = view.output.getEffectiveResolution();
switch (orientation) {
.horizontal => {
var real_delta: i32 = @intCast(i32, view.pending.box.width);
if (delta > 0) {
view.pending.box.width += @intCast(u32, delta);
} else {
// Prevent underflow
view.pending.box.width -=
std.math.min(view.pending.box.width, @intCast(u32, -1 * delta));
}
view.applyConstraints();
// Do not grow bigger than the output
view.pending.box.width = std.math.min(
view.pending.box.width,
output_box.width - @intCast(u32, 2 * border_width),
);
real_delta -= @intCast(i32, view.pending.box.width);
view.move(@divFloor(real_delta, 2), 0);
},
.vertical => {
var real_delta: i32 = @intCast(i32, view.pending.box.height);
if (delta > 0) {
view.pending.box.height += @intCast(u32, delta);
} else {
// Prevent underflow
view.pending.box.height -=
std.math.min(view.pending.box.height, @intCast(u32, -1 * delta));
}
view.applyConstraints();
// Do not grow bigger than the output
view.pending.box.height = std.math.min(
view.pending.box.height,
output_box.height - @intCast(u32, 2 * border_width),
);
real_delta -= @intCast(i32, view.pending.box.height);
view.move(0, @divFloor(real_delta, 2));
},
}
apply(view);
}
fn apply(view: *View) void {
// Set the view to floating but keep the position and dimensions, if their
// dimensions are set by a layout generator. If however the views are
// unarranged, leave them as non-floating so the next active layout can
// affect them.
if (view.output.pending.layout != null)
view.pending.float = true;
view.float_box = view.pending.box;
view.applyPending();
}
fn getView(seat: *Seat) ?*View {
if (seat.focused != .view) return null;
const view = seat.focused.view;
// Do not touch fullscreen views
if (view.pending.fullscreen) return null;
return view;
} | source/river-0.1.0/river/command/move.zig |
const Self = @This();
const std = @import("std");
const mem = std.mem;
const wlr = @import("wlroots");
const wayland = @import("wayland");
const wl = wayland.server.wl;
const river = wayland.server.river;
const server = &@import("main.zig").server;
const util = @import("util.zig");
const Layout = @import("Layout.zig");
const Server = @import("Server.zig");
const Output = @import("Output.zig");
const log = std.log.scoped(.layout);
global: *wl.Global,
server_destroy: wl.Listener(*wl.Server) = wl.Listener(*wl.Server).init(handleServerDestroy),
pub fn init(self: *Self) !void {
self.* = .{
.global = try wl.Global.create(server.wl_server, river.LayoutManagerV3, 1, *Self, self, bind),
};
server.wl_server.addDestroyListener(&self.server_destroy);
}
fn handleServerDestroy(listener: *wl.Listener(*wl.Server), wl_server: *wl.Server) void {
const self = @fieldParentPtr(Self, "server_destroy", listener);
self.global.destroy();
}
fn bind(client: *wl.Client, self: *Self, version: u32, id: u32) callconv(.C) void {
const layout_manager = river.LayoutManagerV3.create(client, 1, id) catch {
client.postNoMemory();
log.crit("out of memory", .{});
return;
};
layout_manager.setHandler(*Self, handleRequest, null, self);
}
fn handleRequest(layout_manager: *river.LayoutManagerV3, request: river.LayoutManagerV3.Request, self: *Self) void {
switch (request) {
.destroy => layout_manager.destroy(),
.get_layout => |req| {
// Ignore if the output is inert
const wlr_output = wlr.Output.fromWlOutput(req.output) orelse return;
const output = @intToPtr(*Output, wlr_output.data);
log.debug("bind layout '{s}' on output '{s}'", .{ req.namespace, mem.sliceTo(&output.wlr_output.name, 0) });
Layout.create(
layout_manager.getClient(),
layout_manager.getVersion(),
req.id,
output,
mem.span(req.namespace),
) catch {
layout_manager.getClient().postNoMemory();
log.crit("out of memory", .{});
return;
};
},
}
} | source/river-0.1.0/river/LayoutManager.zig |
fn Borrow(comptime T: type, comptime borrows: *usize) type {
comptime var alive = true;
return struct {
pointer: *const T,
pub fn read(self: *const @This(), comptime uniq: anytype) T {
if (!alive)
@compileError("Borrow no longer alive!");
return self.pointer.*;
}
pub fn release(self: @This()) void {
alive = false;
borrows.* -= 1;
}
};
}
fn BorrowMut(comptime T: type, comptime borrowmuts: *usize) type {
comptime var alive: bool = true;
return struct {
pointer: *T,
pub fn write(self: *@This(), value: T, comptime uniq: anytype) void {
if (!alive)
@compileError("BorrowMut no longer alive!");
self.pointer.* = value;
}
pub fn read(self: *const @This(), comptime uniq: anytype) T {
if (!alive)
@compileError("BorrowMut no longer alive!");
return self.pointer.*;
}
pub fn release(self: @This()) void {
alive = false;
borrowmuts.* -= 1;
}
};
}
/// A borrowable memory location.
/// Borrows are checked at compiletime. It works just like
/// a read-write lock; There may be many borrows at a time,
/// *or* only one mutable borrow at a time.
pub fn RefCell(comptime T: type, comptime _: anytype) type {
comptime var borrows: usize = 0;
comptime var mutborrows: usize = 0;
return struct {
value: T,
pub fn init(value: T) @This() {
return @This(){ .value = value };
}
/// Borrows the value. As long as a `borrow` is alive, there may not be
/// any mutable borrow alive. Borrows can be released by calling `.release()`.
pub fn borrow(self: *const @This(), comptime uniq: anytype) Borrow(T, &borrows) {
comptime if (borrows > 0 and mutborrows > 0) {
@compileError("Value has already been unwrapped!");
} else if (mutborrows > 0) {
@compileError("There is a mutable borrow active!");
};
borrows += 1;
return .{ .pointer = &self.value };
}
/// Borrows the value mutably. As long as `mut borrow` is alive, there may not be
/// any other borrow or mutable borrow alive. In order words, a live mutable borrow
/// is a unique borrow.
pub fn borrowMut(self: *@This(), comptime uniq: anytype) BorrowMut(T, &mutborrows) {
comptime if (borrows > 0 and mutborrows > 0) {
@compileError("Value has already been unwrapped!");
} else if (borrows > 0 or mutborrows > 0) {
@compileError("There is a borrow[mut] active!");
};
mutborrows += 1;
return .{ .pointer = &self.value };
}
pub fn unwrap(self: *@This(), comptime uniq: anytype) T {
comptime if (borrows > 0 and mutborrows > 0) {
@compileError("Value has already been unwrapped!");
} else if (borrows > 0 or mutborrows > 0) {
@compileError("There is an borrow[mut] active!");
};
mutborrows += 1;
borrows += 1;
return self.value;
}
};
}
const testing = @import("std").testing;
test "unwrap" {
var cell = RefCell(usize, opaque {}).init(10);
var cell2 = RefCell(usize, opaque {}).init(10);
testing.expectEqual(cell.unwrap(opaque {}), cell2.unwrap(opaque {}));
//_ = cell.unwrap(opaque {}); // <--- FAILS: already unwrapped
//_ = cell.borrow(opaque {}); // <--- FAILS: already unwrapped
//_ = cell.borrowMut(opaque {}); // <--- FAILS: already unwrapped
}
test "borrowck" {
var cell = RefCell(usize, opaque {}).init(10);
var b0 = cell.borrow(opaque {});
var b1 = cell.borrow(opaque {});
testing.expectEqual(b0.read(opaque {}), 10);
testing.expectEqual(b1.read(opaque {}), 10);
b0.release();
// _ = b0.read(opaque {}); // <--- FAILS: read after release
_ = b1.read(opaque {});
_ = b1.read(opaque {});
b1.release();
var bm1 = cell.borrowMut(opaque {});
// var b2 = cell.borrow(opaque {}); // <--- FAILS: borrow while mut borrow is active
// var bm2 = cell.borrowMut(opaque {}); // <--- FAILS borrowmut while mut borrow is active
bm1.write(11, opaque {});
testing.expectEqual(bm1.read(opaque {}), 11);
bm1.release();
// bm1.write(20, opaque {}); // <--- FAILS: write after release
}
test "defer release" {
var cell = RefCell(usize, opaque {}).init(20);
{
var borrow = cell.borrow(opaque {});
defer borrow.release();
testing.expectEqual(borrow.read(opaque {}), 20);
}
{
var mutborrow = cell.borrowMut(opaque {});
defer mutborrow.release();
testing.expectEqual(mutborrow.read(opaque {}), 20);
mutborrow.write(0, opaque {});
testing.expectEqual(mutborrow.read(opaque {}), 0);
}
} | src/main.zig |
const std = @import("std");
const util = @import("util");
const input = @embedFile("13.txt");
usingnamespace comptime blk: {
@setEvalBranchQuota(input.len * 20);
var offset: u32 = 0;
var buf: []const [2]u32 = &[_][2]u32{};
var lines = std.mem.tokenize(input, "\n");
const timestamp = util.parseUint(u32, lines.next().?) catch unreachable;
var id_iter = std.mem.split(lines.next().?, ",");
while (id_iter.next()) |id| {
defer offset += 1;
if (!std.mem.eql(u8, id, "x")) {
const int = util.parseUint(u32, id) catch unreachable;
buf = buf ++ [_][2]u32{.{int, offset}};
}
}
var sorted = buf[0..buf.len].*;
std.sort.sort([2]u32, &sorted, {}, struct {
fn impl(_: void, a: [2]u32, b: [2]u32) bool {
return a[0] > b[0];
}
}.impl);
for (sorted) |*entry| {
const id: comptime_int = entry[0];
const offset_: comptime_int = entry[1];
entry[1] = @mod(-offset_, id);
}
break :blk struct {
pub const earliest = timestamp;
pub const id_pairs = sorted;
};
};
pub fn main(n: util.Utils) !void {
var departure: u32 = comptime std.math.maxInt(u32);
var bus_id: u32 = undefined;
for (id_pairs) |id| {
const multiplier = std.math.divCeil(u32, earliest, id[0]) catch unreachable;
const timestamp = multiplier * id[0];
if (timestamp < departure) {
departure = timestamp;
bus_id = id[0];
}
}
var addend: u64 = id_pairs[0][0];
var timestamp: u64 = comptime blk: {
const multiplier = @divFloor(@as(u64, 100_000_000_000_000), id_pairs[0][0]);
break :blk multiplier * id_pairs[0][0] + id_pairs[0][1];
};
for (id_pairs[1..]) |id_pair| {
const id = id_pair[0];
const modulus = id_pair[1];
while (timestamp % id != modulus)
timestamp += addend;
addend *= id;
}
try n.out.print("{}\n{}\n", .{bus_id * (departure - earliest), timestamp});
} | 2020/13.zig |
const sf = @import("../sfml.zig");
const std = @import("std");
const VertexArray = @This();
// Constructors/destructors
/// Creates an empty vertex array
pub fn create() !VertexArray {
var va = sf.c.sfVertexArray_create();
if (va) |vert| {
return VertexArray{ ._ptr = vert };
} else return sf.Error.nullptrUnknownReason;
}
/// Creates a vertex array from a slice of vertices
pub fn createFromSlice(vertex: []const sf.graphics.Vertex, primitive: sf.graphics.PrimitiveType) !VertexArray {
var va = sf.c.sfVertexArray_create();
if (va) |vert| {
sf.c.sfVertexArray_setPrimitiveType(vert, @enumToInt(primitive));
sf.c.sfVertexArray_resize(vert, vertex.len);
for (vertex) |v, i|
sf.c.sfVertexArray_getVertex(vert, i).* = @bitCast(sf.c.sfVertex, v);
return VertexArray{ ._ptr = vert };
} else return sf.Error.nullptrUnknownReason;
}
/// Destroys a vertex array
pub fn destroy(self: *VertexArray) void {
sf.c.sfVertexArray_destroy(self._ptr);
self._ptr = undefined;
}
/// Copies the vertex array
pub fn copy(self: VertexArray) !VertexArray {
var va = sf.c.sfVertexArray_copy(self._ptr);
if (va) |vert| {
return VertexArray{ ._ptr = vert };
} else return sf.Error.nullptrUnknownReason;
}
// Draw function
/// The draw function of this vertex array
/// Meant to be called by your_target.draw(your_vertices, .{});
pub fn sfDraw(self: VertexArray, target: anytype, states: ?*sf.c.sfRenderStates) void {
switch (@TypeOf(target)) {
sf.graphics.RenderWindow => sf.c.sfRenderWindow_drawVertexArray(target._ptr, self._ptr, states),
sf.graphics.RenderTexture => sf.c.sfRenderTexture_drawVertexArray(target._ptr, self._ptr, states),
else => @compileError("target must be a render target"),
}
}
// Wtf github copilot wrote that for me (all of the functions below here)
// Methods and getters/setters
/// Gets the vertex count of the vertex array
pub fn getVertexCount(self: VertexArray) usize {
return sf.c.sfVertexArray_getVertexCount(self._ptr);
}
/// Gets a a pointer to a vertex using its index
/// Don't keep the returned pointer, it can be invalidated by other functions
pub fn getVertex(self: VertexArray, index: usize) *sf.graphics.Vertex {
// TODO: Should this use a pointer to the vertexarray?
// Me, later, what did that comment even mean? ^
var ptr = sf.c.sfVertexArray_getVertex(self._ptr, index);
std.debug.assert(index < self.getVertexCount());
return @ptrCast(*sf.graphics.Vertex, ptr.?);
}
/// Gets a slice to the vertices of the vertex array
/// Don't keep the returned pointer, it can be invalidated by other function
pub fn getSlice(self: VertexArray) []sf.graphics.Vertex {
// TODO: Should this use a pointer to the vertexarray?
var ret: []sf.graphics.Vertex = undefined;
ret.len = self.getVertexCount();
ret.ptr = @ptrCast([*]sf.graphics.Vertex, self.getVertex(0));
return ret;
}
/// Clears the vertex array
pub fn clear(self: *VertexArray) void {
sf.c.sfVertexArray_clear(self._ptr);
}
/// Resizes the vertex array to a given size
pub fn resize(self: *VertexArray, vertexCount: usize) void {
sf.c.sfVertexArray_resize(self._ptr, vertexCount);
}
/// Appends a vertex to the array
pub fn append(self: *VertexArray, vertex: sf.graphics.Vertex) void {
sf.c.sfVertexArray_append(self._ptr, @bitCast(sf.c.sfVertex, vertex));
}
/// Gets the primitives' type of this array
pub fn getPrimitiveType(self: VertexArray) sf.graphics.PrimitiveType {
return @intToEnum(sf.graphics.PrimitiveType, sf.c.sfVertexArray_getPrimitiveType(self._ptr));
}
/// Sets the primitives' type of this array
pub fn setPrimitiveType(self: *VertexArray, primitive: sf.graphics.PrimitiveType) void {
sf.c.sfVertexArray_setPrimitiveType(self._ptr, @enumToInt(primitive));
}
/// Gets the bounding rectangle of the vertex array
pub fn getBounds(self: VertexArray) sf.graphics.FloatRect {
return sf.graphics.FloatRect._fromCSFML(sf.c.sfVertexArray_getBounds(self._ptr));
}
/// Pointer to the csfml structure
_ptr: *sf.c.sfVertexArray,
test "VertexArray: sane getters and setters" {
const tst = std.testing;
const va_slice = [_]sf.graphics.Vertex{
.{ .position = .{ .x = -1, .y = 0 }, .color = sf.graphics.Color.Red },
.{ .position = .{ .x = 1, .y = 0 }, .color = sf.graphics.Color.Green },
.{ .position = .{ .x = -1, .y = 1 }, .color = sf.graphics.Color.Blue },
};
var va = try createFromSlice(va_slice[0..], sf.graphics.PrimitiveType.Triangles);
defer va.destroy();
va.append(.{ .position = .{ .x = 1, .y = 1 }, .color = sf.graphics.Color.Yellow });
va.setPrimitiveType(sf.graphics.PrimitiveType.Quads);
try tst.expectEqual(@as(usize, 4), va.getVertexCount());
try tst.expectEqual(sf.graphics.PrimitiveType.Quads, va.getPrimitiveType());
try tst.expectEqual(sf.graphics.FloatRect{ .left = -1, .top = 0, .width = 2, .height = 1 }, va.getBounds());
va.resize(3);
va.setPrimitiveType(sf.graphics.PrimitiveType.TriangleFan);
try tst.expectEqual(@as(usize, 3), va.getVertexCount());
const vert = va.getVertex(0).*;
try tst.expectEqual(sf.system.Vector2f{ .x = -1, .y = 0 }, vert.position);
try tst.expectEqual(sf.graphics.Color.Red, vert.color);
va.getVertex(1).* = .{ .position = .{ .x = 1, .y = 1 }, .color = sf.graphics.Color.Yellow };
var slice = va.getSlice();
try tst.expectEqual(sf.graphics.Color.Yellow, slice[1].color);
try tst.expectEqual(@as(usize, 3), slice.len);
va.clear();
try tst.expectEqual(@as(usize, 0), va.getVertexCount());
var va2 = try create();
defer va2.destroy();
try tst.expectEqual(@as(usize, 0), va2.getVertexCount());
} | src/sfml/graphics/VertexArray.zig |
const std = @import("std");
const zua = @import("zua.zig");
const Function = zua.object.Function;
const OpCode = zua.opcodes.OpCode;
const Instruction = zua.opcodes.Instruction;
const max_stack_size = zua.parse.max_stack_size;
pub fn checkcode(function: *const Function) !void {
_ = try symbexec(function, null);
}
fn precheck(function: *const Function) !void {
if (function.max_stack_size > max_stack_size) return error.MaxStackSizeTooBig;
if (function.num_params > function.max_stack_size) return error.StackTooSmallForParams;
if (!function.varargs.needs_arg and function.varargs.has_arg) return error.HasUnneededArg;
// check(pt->sizeupvalues <= pt->nups);
// check(pt->sizelineinfo == pt->sizecode || pt->sizelineinfo == 0);
// check(pt->sizecode > 0 && GET_OPCODE(pt->code[pt->sizecode-1]) == OP_RETURN);
}
fn checkreg(function: *const Function, reg: usize) !void {
if (reg >= function.max_stack_size) return error.MaxStackSizeTooSmall;
}
fn checkArgMode(function: *const Function, val: i32, mode: OpCode.OpArgMask) !void {
switch (mode) {
.NotUsed => {
if (val != 0) return error.NonZeroUnusedArg;
},
.Used => {},
.RegisterOrJumpOffset => {
try checkreg(function, @intCast(usize, val));
},
.ConstantOrRegisterConstant => {
const actual_size_val = @intCast(u9, val);
const is_constant = zua.opcodes.isConstant(actual_size_val);
if (is_constant) {
if (zua.opcodes.getConstantIndex(actual_size_val) >= function.constants.len) return error.ConstantIndexOutOfRange;
} else {
try checkreg(function, actual_size_val);
}
},
}
}
fn checkopenop_next(function: *const Function, index: usize) !void {
return checkopenop(function.code[index + 1]);
}
/// luaG_checkopenop equivalent
pub fn checkopenop(instruction: Instruction) !void {
switch (instruction.op) {
.call,
//.tailcall,
.@"return",
.setlist,
=> {
const b = @bitCast(Instruction.ABC, instruction).b;
if (b != 0) return error.InvalidInstructionAfterOpenCall;
},
else => return error.InvalidInstructionAfterOpenCall,
}
}
fn symbexec(function: *const Function, reg: ?usize) !Instruction {
try precheck(function);
// defaults to final return (a 'neutral' instruction)
var last_instruction_that_changed_reg: usize = function.code.len - 1;
var instructions_to_skip: usize = 0;
for (function.code) |instruction, i| {
if (instructions_to_skip > 0) {
instructions_to_skip -= 1;
continue;
}
const a = instruction.a;
var b: i32 = 0;
var c: u9 = 0;
try checkreg(function, a);
switch (instruction.op.getOpMode()) {
.iABC => {
const instructionABC = @bitCast(Instruction.ABC, instruction);
b = instructionABC.b;
c = instructionABC.c;
try checkArgMode(function, b, instruction.op.getBMode());
try checkArgMode(function, c, instruction.op.getCMode());
},
.iABx => {
const instructionABx = @bitCast(Instruction.ABx, instruction);
b = instructionABx.bx;
if (instruction.op.getBMode() == .ConstantOrRegisterConstant) {
if (b >= function.constants.len) return error.ConstantIndexOutOfRange;
}
},
.iAsBx => {
const instructionAsBx = @bitCast(Instruction.AsBx, instruction);
b = instructionAsBx.getSignedBx();
if (instruction.op.getBMode() == .RegisterOrJumpOffset) {
@panic("TODO");
}
},
}
if (instruction.op.testAMode()) {
if (reg != null and a == reg.?) {
last_instruction_that_changed_reg = i;
}
}
if (instruction.op.testTMode()) {
if (i + 2 >= function.code.len) return error.ImpossibleTestInstructionPlacement;
// TODO OP_JMP
//if (function.code[i+1].op != .jmp) return error.ExpectedJmpAfterTest;
}
switch (instruction.op) {
.loadbool => {
const bool_inst = @bitCast(Instruction.LoadBool, instruction);
if (bool_inst.doesJump()) {
if (i + 2 >= function.code.len) return error.ImpossibleLoadBoolInstructionPlacement;
const next_instruction = function.code[i + 1];
const check = next_instruction.op != .setlist or @bitCast(Instruction.ABC, next_instruction).c != 0;
if (!check) return error.ImpossibleInstructionAfterLoadBool;
}
},
.loadnil => {
if (reg != null and a <= reg.? and reg.? <= b) {
last_instruction_that_changed_reg = i;
}
},
//.getupval, .setupval => {},
.getglobal, .setglobal => {
const constant = function.constants[@intCast(usize, b)];
if (constant != .string) return error.ExpectedStringForGetOrSetGlobal;
},
.self => {
try checkreg(function, a + 1);
if (reg != null and reg.? == a + 1) {
last_instruction_that_changed_reg = i;
}
},
.concat => {
if (b >= c) return error.ConcatRequiresAtLeastTwoOperands;
},
//.tforloop => {},
//.forloop, .forprep => {},
//.jmp => {},
.call, .tailcall => {
const call_inst = @bitCast(Instruction.Call, instruction);
if (b != 0) {
try checkreg(function, @intCast(usize, a + b - 1));
}
const num_returns = call_inst.getNumReturnValues();
if (call_inst.isMultipleReturns()) {
try checkopenop_next(function, i);
} else if (num_returns.? != 0) {
try checkreg(function, @intCast(usize, a + num_returns.? - 1));
}
if (reg != null and reg.? >= a) {
last_instruction_that_changed_reg = i;
}
},
.@"return" => {
const ret_inst = @bitCast(Instruction.Return, instruction);
const num_returns = ret_inst.getNumReturnValues();
if (num_returns != null and num_returns.? > 0) {
try checkreg(function, @intCast(usize, a + num_returns.? - 1));
}
},
.setlist => {
const setlist_inst = @bitCast(Instruction.SetList, instruction);
if (b > 0) {
try checkreg(function, @intCast(usize, a + b));
}
if (setlist_inst.isBatchNumberStoredInNextInstruction()) {
if (i + 1 >= function.code.len) return error.ExpectedSetListBatchNumberInstruction;
instructions_to_skip += 1;
}
},
//.closure => {},
.vararg => {
const vararg_inst = @bitCast(Instruction.VarArg, instruction);
const num_returns = vararg_inst.getNumReturnValues();
if (num_returns == null) {
try checkopenop_next(function, i);
// TODO how does lua avoid overflow here?
//try checkreg(function, a + num_returns.? - 1);
} else {
try checkreg(function, a + num_returns.? - 1);
}
},
else => {},
}
}
return function.code[last_instruction_that_changed_reg];
} | src/debug.zig |
const std = @import("std");
const c = @cImport(@cInclude("lmdb.h"));
const os = std.os;
const fs = std.fs;
const mem = std.mem;
const math = std.math;
const meta = std.meta;
const debug = std.debug;
const testing = std.testing;
const panic = debug.panic;
const assert = debug.assert;
pub const Environment = packed struct {
pub const Statistics = struct {
page_size: usize,
tree_height: usize,
num_branch_pages: usize,
num_leaf_pages: usize,
num_overflow_pages: usize,
num_entries: usize,
};
pub const Info = struct {
map_address: ?[*]u8,
map_size: usize,
last_page_num: usize,
last_tx_id: usize,
max_num_reader_slots: usize,
num_used_reader_slots: usize,
};
const Self = @This();
inner: ?*c.MDB_env,
pub const OpenFlags = struct {
mode: c.mdb_mode_t = 0o664,
map_size: ?usize = null,
max_num_readers: ?usize = null,
max_num_dbs: ?usize = null,
fix_mapped_address: bool = false,
no_sub_directory: bool = false,
read_only: bool = false,
use_writable_memory_map: bool = false,
dont_sync_metadata: bool = false,
dont_sync: bool = false,
flush_asynchronously: bool = false,
disable_thread_local_storage: bool = false,
disable_locks: bool = false,
disable_readahead: bool = false,
disable_memory_initialization: bool = false,
pub inline fn into(self: Self.OpenFlags) c_uint {
var flags: c_uint = 0;
if (self.fix_mapped_address) flags |= c.MDB_FIXEDMAP;
if (self.no_sub_directory) flags |= c.MDB_NOSUBDIR;
if (self.read_only) flags |= c.MDB_RDONLY;
if (self.use_writable_memory_map) flags |= c.MDB_WRITEMAP;
if (self.dont_sync_metadata) flags |= c.MDB_NOMETASYNC;
if (self.dont_sync) flags |= c.MDB_NOSYNC;
if (self.flush_asynchronously) flags |= c.MDB_MAPASYNC;
if (self.disable_thread_local_storage) flags |= c.MDB_NOTLS;
if (self.disable_locks) flags |= c.MDB_NOLOCK;
if (self.disable_readahead) flags |= c.MDB_NORDAHEAD;
if (self.disable_memory_initialization) flags |= c.MDB_NOMEMINIT;
return flags;
}
};
pub inline fn init(env_path: []const u8, flags: Self.OpenFlags) !Self {
var inner: ?*c.MDB_env = null;
try call(c.mdb_env_create, .{&inner});
errdefer call(c.mdb_env_close, .{inner});
if (flags.map_size) |map_size| {
try call(c.mdb_env_set_mapsize, .{ inner, map_size });
}
if (flags.max_num_readers) |max_num_readers| {
try call(c.mdb_env_set_maxreaders, .{ inner, @intCast(c_uint, max_num_readers) });
}
if (flags.max_num_dbs) |max_num_dbs| {
try call(c.mdb_env_set_maxdbs, .{ inner, @intCast(c_uint, max_num_dbs) });
}
if (!mem.endsWith(u8, env_path, &[_]u8{0})) {
assert(env_path.len + 1 <= fs.MAX_PATH_BYTES);
var fixed_path: [fs.MAX_PATH_BYTES + 1]u8 = undefined;
mem.copy(u8, &fixed_path, env_path);
fixed_path[env_path.len] = 0;
try call(c.mdb_env_open, .{ inner, fixed_path[0 .. env_path.len + 1].ptr, flags.into(), flags.mode });
} else {
try call(c.mdb_env_open, .{ inner, env_path.ptr, flags.into(), flags.mode });
}
return Self{ .inner = inner };
}
pub inline fn deinit(self: Self) void {
call(c.mdb_env_close, .{self.inner});
}
pub const CopyFlags = packed struct {
compact: bool = false,
pub inline fn into(self: Self.CopyFlags) c_uint {
var flags: c_uint = 0;
if (self.compact) flags |= c.MDB_CP_COMPACT;
return flags;
}
};
pub inline fn copyTo(self: Self, backup_path: []const u8, flags: CopyFlags) !void {
if (!mem.endsWith(u8, backup_path, &[_]u8{0})) {
assert(backup_path.len + 1 <= fs.MAX_PATH_BYTES);
var fixed_path: [fs.MAX_PATH_BYTES + 1]u8 = undefined;
mem.copy(u8, &fixed_path, backup_path);
fixed_path[backup_path.len] = 0;
try call(c.mdb_env_copy2, .{ self.inner, fixed_path[0 .. backup_path.len + 1].ptr, flags.into() });
} else {
try call(c.mdb_env_copy2, .{ self.inner, backup_path.ptr, flags.into() });
}
}
pub inline fn pipeTo(self: Self, fd_handle: os.fd_t, flags: CopyFlags) !void {
try call(c.mdb_env_copyfd2, .{ self.inner, fd_handle, flags.into() });
}
pub inline fn getMaxKeySize(self: Self) usize {
return @intCast(usize, c.mdb_env_get_maxkeysize(self.inner));
}
pub inline fn getMaxNumReaders(self: Self) usize {
var max_num_readers: c_uint = 0;
call(c.mdb_env_get_maxreaders, .{ self.inner, &max_num_readers }) catch |err| {
panic("Environment.getMaxNumReaders(): {}", .{err});
};
return @intCast(usize, max_num_readers);
}
pub inline fn setMapSize(self: Self, map_size: ?usize) !void {
try call(c.mdb_env_set_mapsize, .{ self.inner, if (map_size) |size| size else 0 });
}
pub const Flags = struct {
fix_mapped_address: bool = false,
no_sub_directory: bool = false,
read_only: bool = false,
use_writable_memory_map: bool = false,
dont_sync_metadata: bool = false,
dont_sync: bool = false,
flush_asynchronously: bool = false,
disable_thread_local_storage: bool = false,
disable_locks: bool = false,
disable_readahead: bool = false,
disable_memory_initialization: bool = false,
pub inline fn from(flags: c_uint) Flags {
return Flags{
.fix_mapped_address = flags & c.MDB_FIXEDMAP != 0,
.no_sub_directory = flags & c.MDB_NOSUBDIR != 0,
.read_only = flags & c.MDB_RDONLY != 0,
.use_writable_memory_map = flags & c.MDB_WRITEMAP != 0,
.dont_sync_metadata = flags & c.MDB_NOMETASYNC != 0,
.dont_sync = flags & c.MDB_NOSYNC != 0,
.flush_asynchronously = flags & c.MDB_MAPASYNC != 0,
.disable_thread_local_storage = flags & c.MDB_NOTLS != 0,
.disable_locks = flags & c.MDB_NOLOCK != 0,
.disable_readahead = flags & c.MDB_NORDAHEAD != 0,
.disable_memory_initialization = flags & c.MDB_NOMEMINIT != 0,
};
}
pub inline fn into(self: Self.Flags) c_uint {
var flags: c_uint = 0;
if (self.fix_mapped_address) flags |= c.MDB_FIXEDMAP;
if (self.no_sub_directory) flags |= c.MDB_NOSUBDIR;
if (self.read_only) flags |= c.MDB_RDONLY;
if (self.use_writable_memory_map) flags |= c.MDB_WRITEMAP;
if (self.dont_sync_metadata) flags |= c.MDB_NOMETASYNC;
if (self.dont_sync) flags |= c.MDB_NOSYNC;
if (self.flush_asynchronously) flags |= c.MDB_MAPASYNC;
if (self.disable_thread_local_storage) flags |= c.MDB_NOTLS;
if (self.disable_locks) flags |= c.MDB_NOLOCK;
if (self.disable_readahead) flags |= c.MDB_NORDAHEAD;
if (self.disable_memory_initialization) flags |= c.MDB_NOMEMINIT;
return flags;
}
};
pub inline fn getFlags(self: Self) Flags {
var inner: c_uint = undefined;
call(c.mdb_env_get_flags, .{ self.inner, &inner }) catch |err| {
panic("Environment.getFlags(): {}", .{err});
};
return Flags.from(inner);
}
pub const MutableFlags = struct {
dont_sync_metadata: bool = false,
dont_sync: bool = false,
flush_asynchronously: bool = false,
disable_memory_initialization: bool = false,
pub inline fn into(self: Self.MutableFlags) c_uint {
var flags: c_uint = 0;
if (self.dont_sync_metadata) flags |= c.MDB_NOMETASYNC;
if (self.dont_sync) flags |= c.MDB_NOSYNC;
if (self.flush_asynchronously) flags |= c.MDB_MAPASYNC;
if (self.disable_memory_initialization) flags |= c.MDB_NOMEMINIT;
return flags;
}
};
pub inline fn enableFlags(self: Self, flags: MutableFlags) void {
call(c.mdb_env_set_flags, .{ self.inner, flags.into(), 1 }) catch |err| {
panic("Environment.enableFlags(): {}", .{err});
};
}
pub inline fn disableFlags(self: Self, flags: MutableFlags) void {
call(c.mdb_env_set_flags, .{ self.inner, flags.into(), 0 }) catch |err| {
panic("Environment.disableFlags(): {}", .{err});
};
}
pub inline fn path(self: Self) []const u8 {
var env_path: [:0]const u8 = undefined;
call(c.mdb_env_get_path, .{ self.inner, @ptrCast([*c][*c]const u8, &env_path.ptr) }) catch |err| {
panic("Environment.path(): {}", .{err});
};
env_path.len = mem.indexOfSentinel(u8, 0, env_path.ptr);
return mem.span(env_path);
}
pub inline fn stat(self: Self) Statistics {
var inner: c.MDB_stat = undefined;
call(c.mdb_env_stat, .{ self.inner, &inner }) catch |err| {
panic("Environment.stat(): {}", .{err});
};
return Statistics{
.page_size = @intCast(usize, inner.ms_psize),
.tree_height = @intCast(usize, inner.ms_depth),
.num_branch_pages = @intCast(usize, inner.ms_branch_pages),
.num_leaf_pages = @intCast(usize, inner.ms_leaf_pages),
.num_overflow_pages = @intCast(usize, inner.ms_overflow_pages),
.num_entries = @intCast(usize, inner.ms_entries),
};
}
pub inline fn fd(self: Self) os.fd_t {
var inner: os.fd_t = undefined;
call(c.mdb_env_get_fd, .{ self.inner, &inner }) catch |err| {
panic("Environment.fd(): {}", .{err});
};
return inner;
}
pub inline fn info(self: Self) Info {
var inner: c.MDB_envinfo = undefined;
call(c.mdb_env_info, .{ self.inner, &inner }) catch |err| {
panic("Environment.info(): {}", .{err});
};
return Info{
.map_address = @ptrCast(?[*]u8, inner.me_mapaddr),
.map_size = @intCast(usize, inner.me_mapsize),
.last_page_num = @intCast(usize, inner.me_last_pgno),
.last_tx_id = @intCast(usize, inner.me_last_txnid),
.max_num_reader_slots = @intCast(usize, inner.me_maxreaders),
.num_used_reader_slots = @intCast(usize, inner.me_numreaders),
};
}
pub inline fn begin(self: Self, flags: Transaction.Flags) !Transaction {
var inner: ?*c.MDB_txn = null;
const maybe_parent = if (flags.parent) |parent| parent.inner else null;
try call(c.mdb_txn_begin, .{ self.inner, maybe_parent, flags.into(), &inner });
return Transaction{ .inner = inner };
}
pub inline fn sync(self: Self, force: bool) !void {
try call(c.mdb_env_sync, .{ self.inner, @as(c_int, if (force) 1 else 0) });
}
pub inline fn purge(self: Self) !usize {
var count: c_int = undefined;
try call(c.mdb_reader_check, .{ self.inner, &count });
return @intCast(usize, count);
}
};
pub const Database = struct {
pub const OpenFlags = packed struct {
compare_keys_in_reverse_order: bool = false,
allow_duplicate_keys: bool = false,
keys_are_integers: bool = false,
duplicate_entries_are_fixed_size: bool = false,
duplicate_keys_are_integers: bool = false,
compare_duplicate_keys_in_reverse_order: bool = false,
pub inline fn into(self: Self.OpenFlags) c_uint {
var flags: c_uint = 0;
if (self.compare_keys_in_reverse_order) flags |= c.MDB_REVERSEKEY;
if (self.allow_duplicate_keys) flags |= c.MDB_DUPSORT;
if (self.keys_are_integers) flags |= c.MDB_INTEGERKEY;
if (self.duplicate_entries_are_fixed_size) flags |= c.MDB_DUPFIXED;
if (self.duplicate_keys_are_integers) flags |= c.MDB_INTEGERDUP;
if (self.compare_duplicate_keys_in_reverse_order) flags |= c.MDB_REVERSEDUP;
return flags;
}
};
pub const UseFlags = packed struct {
compare_keys_in_reverse_order: bool = false,
allow_duplicate_keys: bool = false,
keys_are_integers: bool = false,
duplicate_entries_are_fixed_size: bool = false,
duplicate_keys_are_integers: bool = false,
compare_duplicate_keys_in_reverse_order: bool = false,
create_if_not_exists: bool = false,
pub inline fn into(self: Self.UseFlags) c_uint {
var flags: c_uint = 0;
if (self.compare_keys_in_reverse_order) flags |= c.MDB_REVERSEKEY;
if (self.allow_duplicate_keys) flags |= c.MDB_DUPSORT;
if (self.keys_are_integers) flags |= c.MDB_INTEGERKEY;
if (self.duplicate_entries_are_fixed_size) flags |= c.MDB_DUPFIXED;
if (self.duplicate_keys_are_integers) flags |= c.MDB_INTEGERDUP;
if (self.compare_duplicate_keys_in_reverse_order) flags |= c.MDB_REVERSEDUP;
if (self.create_if_not_exists) flags |= c.MDB_CREATE;
return flags;
}
};
const Self = @This();
inner: c.MDB_dbi,
pub inline fn close(self: Self, env: Environment) void {
call(c.mdb_dbi_close, .{ env.inner, self.inner });
}
};
pub const Transaction = packed struct {
pub const Flags = struct {
parent: ?Self = null,
read_only: bool = false,
dont_sync: bool = false,
dont_sync_metadata: bool = false,
pub inline fn into(self: Self.Flags) c_uint {
var flags: c_uint = 0;
if (self.read_only) flags |= c.MDB_RDONLY;
if (self.dont_sync) flags |= c.MDB_NOSYNC;
if (self.dont_sync_metadata) flags |= c.MDB_NOMETASYNC;
return flags;
}
};
const Self = @This();
inner: ?*c.MDB_txn,
pub inline fn id(self: Self) usize {
return @intCast(usize, c.mdb_txn_id(self.inner));
}
pub inline fn open(self: Self, flags: Database.OpenFlags) !Database {
var inner: c.MDB_dbi = 0;
try call(c.mdb_dbi_open, .{ self.inner, null, flags.into(), &inner });
return Database{ .inner = inner };
}
pub inline fn use(self: Self, name: []const u8, flags: Database.UseFlags) !Database {
var inner: c.MDB_dbi = 0;
try call(c.mdb_dbi_open, .{ self.inner, name.ptr, flags.into(), &inner });
return Database{ .inner = inner };
}
pub inline fn cursor(self: Self, db: Database) !Cursor {
var inner: ?*c.MDB_cursor = undefined;
try call(c.mdb_cursor_open, .{ self.inner, db.inner, &inner });
return Cursor{ .inner = inner };
}
pub inline fn setKeyOrder(self: Self, db: Database, comptime order: fn (a: []const u8, b: []const u8) math.Order) !void {
const S = struct {
fn cmp(a: ?*const c.MDB_val, b: ?*const c.MDB_val) callconv(.C) c_int {
const slice_a = @ptrCast([*]const u8, a.?.mv_data)[0..a.?.mv_size];
const slice_b = @ptrCast([*]const u8, b.?.mv_data)[0..b.?.mv_size];
return switch (order(slice_a, slice_b)) {
.eq => 0,
.lt => -1,
.gt => 1,
};
}
};
try call(c.mdb_set_compare, .{ self.inner, db.inner, S.cmp });
}
pub inline fn setItemOrder(self: Self, db: Database, comptime order: fn (a: []const u8, b: []const u8) math.Order) !void {
const S = struct {
fn cmp(a: ?*const c.MDB_val, b: ?*const c.MDB_val) callconv(.C) c_int {
const slice_a = @ptrCast([*]const u8, a.?.mv_data)[0..a.?.mv_size];
const slice_b = @ptrCast([*]const u8, b.?.mv_data)[0..b.?.mv_size];
return switch (order(slice_a, slice_b)) {
.eq => 0,
.lt => -1,
.gt => 1,
};
}
};
try call(c.mdb_set_dupsort, .{ self.inner, db.inner, S.cmp });
}
pub inline fn get(self: Self, db: Database, key: []const u8) ![]const u8 {
var k = &c.MDB_val{ .mv_size = key.len, .mv_data = @intToPtr(?*c_void, @ptrToInt(key.ptr)) };
var v: c.MDB_val = undefined;
try call(c.mdb_get, .{ self.inner, db.inner, k, &v });
return @ptrCast([*]const u8, v.mv_data)[0..v.mv_size];
}
pub const PutFlags = packed struct {
dont_overwrite_key: bool = false,
dont_overwrite_item: bool = false,
data_already_sorted: bool = false,
set_already_sorted: bool = false,
pub inline fn into(self: PutFlags) c_uint {
var flags: c_uint = 0;
if (self.dont_overwrite_key) flags |= c.MDB_NOOVERWRITE;
if (self.dont_overwrite_item) flags |= c.MDB_NODUPDATA;
if (self.data_already_sorted) flags |= c.MDB_APPEND;
if (self.set_already_sorted) flags |= c.MDB_APPENDDUP;
return flags;
}
};
pub inline fn putItem(self: Self, db: Database, key: []const u8, val: anytype, flags: PutFlags) !void {
const bytes = if (meta.trait.isIndexable(@TypeOf(val))) mem.span(val) else mem.asBytes(&val);
return self.put(db, key, bytes, flags);
}
pub inline fn put(self: Self, db: Database, key: []const u8, val: []const u8, flags: PutFlags) !void {
var k = &c.MDB_val{ .mv_size = key.len, .mv_data = @intToPtr(?*c_void, @ptrToInt(key.ptr)) };
var v = &c.MDB_val{ .mv_size = val.len, .mv_data = @intToPtr(?*c_void, @ptrToInt(val.ptr)) };
try call(c.mdb_put, .{ self.inner, db.inner, k, v, flags.into() });
}
pub inline fn getOrPut(self: Self, db: Database, key: []const u8, val: []const u8) !?[]const u8 {
var k = &c.MDB_val{ .mv_size = key.len, .mv_data = @intToPtr(?*c_void, @ptrToInt(key.ptr)) };
var v = &c.MDB_val{ .mv_size = val.len, .mv_data = @intToPtr(?*c_void, @ptrToInt(val.ptr)) };
call(c.mdb_put, .{ self.inner, db.inner, k, v, c.MDB_NOOVERWRITE }) catch |err| switch (err) {
error.AlreadyExists => return @ptrCast([*]u8, v.mv_data)[0..v.mv_size],
else => return err,
};
return null;
}
pub const ReserveFlags = packed struct {
dont_overwrite_key: bool = false,
data_already_sorted: bool = false,
pub inline fn into(self: ReserveFlags) c_uint {
var flags: c_uint = c.MDB_RESERVE;
if (self.dont_overwrite_key) flags |= c.MDB_NOOVERWRITE;
if (self.data_already_sorted) flags |= c.MDB_APPEND;
return flags;
}
};
pub const ReserveResult = union(enum) {
successful: []u8,
found_existing: []const u8,
};
pub inline fn reserve(self: Self, db: Database, key: []const u8, val_len: usize, flags: ReserveFlags) !ReserveResult {
var k = &c.MDB_val{ .mv_size = key.len, .mv_data = @intToPtr(?*c_void, @ptrToInt(key.ptr)) };
var v = &c.MDB_val{ .mv_size = val_len, .mv_data = null };
call(c.mdb_put, .{ self.inner, db.inner, k, v, flags.into() }) catch |err| switch (err) {
error.AlreadyExists => return ReserveResult{
.found_existing = @ptrCast([*]const u8, v.mv_data)[0..v.mv_size],
},
else => return err,
};
return ReserveResult{
.successful = @ptrCast([*]u8, v.mv_data)[0..v.mv_size],
};
}
pub inline fn del(self: Self, db: Database, key: []const u8, op: union(enum) { key: void, item: []const u8 }) !void {
var k = &c.MDB_val{ .mv_size = key.len, .mv_data = @intToPtr(?*c_void, @ptrToInt(key.ptr)) };
var v: ?*c.MDB_val = switch (op) {
.key => null,
.item => |item| &c.MDB_val{
.mv_size = item.len,
.mv_data = @intToPtr(?*c_void, @ptrToInt(item.ptr)),
},
};
try call(c.mdb_del, .{ self.inner, db.inner, k, v });
}
pub inline fn drop(self: Self, db: Database, method: enum(c_int) { empty = 0, delete = 1 }) !void {
try call(c.mdb_drop, .{ self.inner, db.inner, @enumToInt(method) });
}
pub inline fn deinit(self: Self) void {
call(c.mdb_txn_abort, .{self.inner});
}
pub inline fn commit(self: Self) !void {
try call(c.mdb_txn_commit, .{self.inner});
}
pub inline fn renew(self: Self) !void {
try call(c.mdb_txn_renew, .{self.inner});
}
pub inline fn reset(self: Self) !void {
try call(c.mdb_txn_reset, .{self.inner});
}
};
pub const Cursor = packed struct {
pub const Entry = struct {
key: []const u8,
val: []const u8,
};
pub fn Page(comptime T: type) type {
return struct {
key: []const u8,
items: []align(1) const T,
};
}
const Self = @This();
inner: ?*c.MDB_cursor,
pub inline fn deinit(self: Self) void {
call(c.mdb_cursor_close, .{self.inner});
}
pub inline fn tx(self: Self) Transaction {
return Transaction{ .inner = c.mdb_cursor_txn(self.inner) };
}
pub inline fn db(self: Self) Database {
return Database{ .inner = c.mdb_cursor_dbi(self.inner) };
}
pub inline fn renew(self: Self, parent: Transaction) !void {
try call(c.mdb_cursor_renew, .{ parent.inner, self.inner });
}
pub inline fn count(self: Self) usize {
var inner: c.mdb_size_t = undefined;
call(c.mdb_cursor_count, .{ self.inner, &inner }) catch |err| {
panic("cursor is initialized, or database does not support duplicate keys: {}", .{err});
};
return @intCast(usize, inner);
}
pub fn updateItemInPlace(self: Self, current_key: []const u8, new_val: anytype) !void {
const bytes = if (meta.trait.isIndexable(@TypeOf(new_val))) mem.span(new_val) else mem.asBytes(&new_val);
return self.updateInPlace(current_key, bytes);
}
pub fn updateInPlace(self: Self, current_key: []const u8, new_val: []const u8) !void {
var k = &c.MDB_val{ .mv_size = current_key.len, .mv_data = @intToPtr(?*c_void, @ptrToInt(current_key.ptr)) };
var v = &c.MDB_val{ .mv_size = new_val.len, .mv_data = @intToPtr(?*c_void, @ptrToInt(new_val.ptr)) };
try call(c.mdb_cursor_put, .{ self.inner, k, v, c.MDB_CURRENT });
}
/// May not be used with databases supporting duplicate keys.
pub fn reserveInPlace(self: Self, current_key: []const u8, new_val_len: usize) ![]u8 {
var k = &c.MDB_val{ .mv_size = current_key.len, .mv_data = @intToPtr(?*c_void, @ptrToInt(current_key.ptr)) };
var v = &c.MDB_val{ .mv_size = new_val_len, .mv_data = null };
try call(c.mdb_cursor_put, .{ self.inner, k, v, c.MDB_CURRENT | c.MDB_RESERVE });
return @ptrCast([*]u8, v.mv_data)[0..v.mv_size];
}
pub const PutFlags = packed struct {
dont_overwrite_key: bool = false,
dont_overwrite_item: bool = false,
data_already_sorted: bool = false,
set_already_sorted: bool = false,
pub inline fn into(self: PutFlags) c_uint {
var flags: c_uint = 0;
if (self.dont_overwrite_key) flags |= c.MDB_NOOVERWRITE;
if (self.dont_overwrite_item) flags |= c.MDB_NODUPDATA;
if (self.data_already_sorted) flags |= c.MDB_APPEND;
if (self.set_already_sorted) flags |= c.MDB_APPENDDUP;
return flags;
}
};
pub inline fn putItem(self: Self, key: []const u8, val: anytype, flags: PutFlags) !void {
const bytes = if (meta.trait.isIndexable(@TypeOf(val))) mem.span(val) else mem.asBytes(&val);
return self.put(key, bytes, flags);
}
pub inline fn put(self: Self, key: []const u8, val: []const u8, flags: PutFlags) !void {
var k = &c.MDB_val{ .mv_size = key.len, .mv_data = @intToPtr(?*c_void, @ptrToInt(key.ptr)) };
var v = &c.MDB_val{ .mv_size = val.len, .mv_data = @intToPtr(?*c_void, @ptrToInt(val.ptr)) };
try call(c.mdb_cursor_put, .{ self.inner, k, v, flags.into() });
}
pub inline fn putBatch(self: Self, key: []const u8, batch: anytype, flags: PutFlags) !usize {
comptime assert(meta.trait.isIndexable(@TypeOf(batch)));
var k = &c.MDB_val{ .mv_size = key.len, .mv_data = @intToPtr(?*c_void, @ptrToInt(key.ptr)) };
var v = [_]c.MDB_val{
.{ .mv_size = @sizeOf(meta.Elem(@TypeOf(batch))), .mv_data = @intToPtr(?*c_void, @ptrToInt(&batch[0])) },
.{ .mv_size = mem.len(batch), .mv_data = undefined },
};
try call(c.mdb_cursor_put, .{ self.inner, k, &v, @intCast(c_uint, c.MDB_MULTIPLE) | flags.into() });
return @intCast(usize, v[1].mv_size);
}
pub inline fn getOrPut(self: Self, key: []const u8, val: []const u8) !?[]const u8 {
var k = &c.MDB_val{ .mv_size = key.len, .mv_data = @intToPtr(?*c_void, @ptrToInt(key.ptr)) };
var v = &c.MDB_val{ .mv_size = val.len, .mv_data = @intToPtr(?*c_void, @ptrToInt(val.ptr)) };
call(c.mdb_cursor_put, .{ self.inner, k, v, c.MDB_NOOVERWRITE }) catch |err| switch (err) {
error.AlreadyExists => return @ptrCast([*]u8, v.mv_data)[0..v.mv_size],
else => return err,
};
return null;
}
pub const ReserveFlags = packed struct {
dont_overwrite_key: bool = false,
data_already_sorted: bool = false,
pub inline fn into(self: ReserveFlags) c_uint {
var flags: c_uint = c.MDB_RESERVE;
if (self.dont_overwrite_key) flags |= c.MDB_NOOVERWRITE;
if (self.data_already_sorted) flags |= c.MDB_APPEND;
return flags;
}
};
pub const ReserveResult = union(enum) {
successful: []u8,
found_existing: []const u8,
};
pub inline fn reserve(self: Self, key: []const u8, val_len: usize, flags: ReserveFlags) !ReserveResult {
var k = &c.MDB_val{ .mv_size = key.len, .mv_data = @intToPtr(?*c_void, @ptrToInt(key.ptr)) };
var v = &c.MDB_val{ .mv_size = val_len, .mv_data = null };
call(c.mdb_cursor_put, .{ self.inner, k, v, flags.into() }) catch |err| switch (err) {
error.AlreadyExists => return ReserveResult{
.found_existing = @ptrCast([*]const u8, v.mv_data)[0..v.mv_size],
},
else => return err,
};
return ReserveResult{
.successful = @ptrCast([*]u8, v.mv_data)[0..v.mv_size],
};
}
pub inline fn del(self: Self, op: enum(c_uint) { key = c.MDB_NODUPDATA, item = 0 }) !void {
call(c.mdb_cursor_del, .{ self.inner, @enumToInt(op) }) catch |err| switch (err) {
error.InvalidParameter => return error.NotFound,
else => return err,
};
}
pub const Position = enum(c.MDB_cursor_op) {
first = c.MDB_FIRST,
first_item = c.MDB_FIRST_DUP,
current = c.MDB_GET_CURRENT,
last = c.MDB_LAST,
last_item = c.MDB_LAST_DUP,
next = c.MDB_NEXT,
next_item = c.MDB_NEXT_DUP,
next_key = c.MDB_NEXT_NODUP,
prev = c.MDB_PREV,
prev_item = c.MDB_PREV_DUP,
prev_key = c.MDB_PREV_NODUP,
};
pub inline fn get(self: Self, pos: Position) !?Entry {
var k: c.MDB_val = undefined;
var v: c.MDB_val = undefined;
call(c.mdb_cursor_get, .{ self.inner, &k, &v, @enumToInt(pos) }) catch |err| switch (err) {
error.InvalidParameter => return if (pos == .current) null else err,
error.NotFound => return null,
else => return err,
};
return Entry{
.key = @ptrCast([*]const u8, k.mv_data)[0..k.mv_size],
.val = @ptrCast([*]const u8, v.mv_data)[0..v.mv_size],
};
}
pub const PagePosition = enum(c.MDB_cursor_op) {
current = c.MDB_GET_MULTIPLE,
next = c.MDB_NEXT_MULTIPLE,
prev = c.MDB_PREV_MULTIPLE,
};
pub inline fn getPage(self: Self, comptime T: type, pos: PagePosition) !?Page(T) {
var k: c.MDB_val = undefined;
var v: c.MDB_val = undefined;
call(c.mdb_cursor_get, .{ self.inner, &k, &v, @enumToInt(pos) }) catch |err| switch (err) {
error.NotFound => return null,
else => return err,
};
return Page(T){
.key = @ptrCast([*]const u8, k.mv_data)[0..k.mv_size],
.items = mem.bytesAsSlice(T, @ptrCast([*]const u8, v.mv_data)[0..v.mv_size]),
};
}
pub inline fn seekToItem(self: Self, key: []const u8, val: []const u8) !void {
var k = &c.MDB_val{ .mv_size = key.len, .mv_data = @intToPtr(?*c_void, @ptrToInt(key.ptr)) };
var v = &c.MDB_val{ .mv_size = val.len, .mv_data = @intToPtr(?*c_void, @ptrToInt(val.ptr)) };
try call(c.mdb_cursor_get, .{ self.inner, k, v, .MDB_GET_BOTH });
}
pub inline fn seekFromItem(self: Self, key: []const u8, val: []const u8) ![]const u8 {
var k = &c.MDB_val{ .mv_size = key.len, .mv_data = @intToPtr(?*c_void, @ptrToInt(key.ptr)) };
var v = &c.MDB_val{ .mv_size = val.len, .mv_data = @intToPtr(?*c_void, @ptrToInt(val.ptr)) };
try call(c.mdb_cursor_get, .{ self.inner, k, v, c.MDB_GET_BOTH_RANGE });
return @ptrCast([*]const u8, v.mv_data)[0..v.mv_size];
}
pub inline fn seekTo(self: Self, key: []const u8) ![]const u8 {
var k = &c.MDB_val{ .mv_size = key.len, .mv_data = @intToPtr(?*c_void, @ptrToInt(key.ptr)) };
var v: c.MDB_val = undefined;
try call(c.mdb_cursor_get, .{ self.inner, k, &v, c.MDB_SET_KEY });
return @ptrCast([*]const u8, v.mv_data)[0..v.mv_size];
}
pub inline fn seekFrom(self: Self, key: []const u8) !Entry {
var k = &c.MDB_val{ .mv_size = key.len, .mv_data = @intToPtr(?*c_void, @ptrToInt(key.ptr)) };
var v: c.MDB_val = undefined;
try call(c.mdb_cursor_get, .{ self.inner, k, &v, c.MDB_SET_RANGE });
return Entry{
.key = @ptrCast([*]const u8, k.mv_data)[0..k.mv_size],
.val = @ptrCast([*]const u8, v.mv_data)[0..v.mv_size],
};
}
pub inline fn first(self: Self) !?Entry {
return self.get(.first);
}
pub inline fn firstItem(self: Self) !?Entry {
return self.get(.first_item);
}
pub inline fn current(self: Self) !?Entry {
return self.get(.current);
}
pub inline fn last(self: Self) !?Entry {
return self.get(.last);
}
pub inline fn lastItem(self: Self) !?Entry {
return self.get(.last_item);
}
pub inline fn next(self: Self) !?Entry {
return self.get(.next);
}
pub inline fn nextItem(self: Self) !?Entry {
return self.get(.next_item);
}
pub inline fn nextKey(self: Self) !?Entry {
return self.get(.next_key);
}
pub inline fn prev(self: Self) !?Entry {
return self.get(.prev);
}
pub inline fn prevItem(self: Self) !?Entry {
return self.get(.prev_item);
}
pub inline fn prevKey(self: Self) !?Entry {
return self.get(.prev_key);
}
pub inline fn currentPage(self: Self, comptime T: type) !?Page(T) {
return self.getPage(T, .current);
}
pub inline fn nextPage(self: Self, comptime T: type) !?Page(T) {
return self.getPage(T, .next);
}
pub inline fn prevPage(self: Self, comptime T: type) !?Page(T) {
return self.getPage(T, .prev);
}
};
inline fn ResultOf(comptime function: anytype) type {
return if (@typeInfo(@TypeOf(function)).Fn.return_type == c_int) anyerror!void else void;
}
inline fn call(comptime function: anytype, args: anytype) ResultOf(function) {
const rc = @call(.{}, function, args);
if (ResultOf(function) == void) return rc;
return switch (rc) {
c.MDB_SUCCESS => {},
c.MDB_KEYEXIST => error.AlreadyExists,
c.MDB_NOTFOUND => error.NotFound,
c.MDB_PAGE_NOTFOUND => error.PageNotFound,
c.MDB_CORRUPTED => error.PageCorrupted,
c.MDB_PANIC => error.Panic,
c.MDB_VERSION_MISMATCH => error.VersionMismatch,
c.MDB_INVALID => error.FileNotDatabase,
c.MDB_MAP_FULL => error.MapSizeLimitReached,
c.MDB_DBS_FULL => error.MaxNumDatabasesLimitReached,
c.MDB_READERS_FULL => error.MaxNumReadersLimitReached,
c.MDB_TLS_FULL => error.TooManyEnvironmentsOpen,
c.MDB_TXN_FULL => error.TransactionTooBig,
c.MDB_CURSOR_FULL => error.CursorStackLimitReached,
c.MDB_PAGE_FULL => error.OutOfPageMemory,
c.MDB_MAP_RESIZED => error.DatabaseExceedsMapSizeLimit,
c.MDB_INCOMPATIBLE => error.IncompatibleOperation,
c.MDB_BAD_RSLOT => error.InvalidReaderLocktableSlotReuse,
c.MDB_BAD_TXN => error.TransactionNotAborted,
c.MDB_BAD_VALSIZE => error.UnsupportedSize,
c.MDB_BAD_DBI => error.BadDatabaseHandle,
@enumToInt(os.E.NOENT) => error.NoSuchFileOrDirectory,
@enumToInt(os.E.IO) => error.InputOutputError,
@enumToInt(os.E.NOMEM) => error.OutOfMemory,
@enumToInt(os.E.ACCES) => error.ReadOnly,
@enumToInt(os.E.BUSY) => error.DeviceOrResourceBusy,
@enumToInt(os.E.INVAL) => error.InvalidParameter,
@enumToInt(os.E.NOSPC) => error.NoSpaceLeftOnDevice,
@enumToInt(os.E.EXIST) => error.FileAlreadyExists,
else => panic("({}) {s}", .{ rc, c.mdb_strerror(rc) }),
};
}
test {
testing.refAllDecls(@This());
}
test "Environment.init() / Environment.deinit(): query environment stats, flags, and info" {
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var buf: [fs.MAX_PATH_BYTES]u8 = undefined;
var path = try tmp.dir.realpath("./", &buf);
const env = try Environment.init(path, .{
.use_writable_memory_map = true,
.dont_sync_metadata = true,
.map_size = 4 * 1024 * 1024,
.max_num_readers = 42,
});
defer env.deinit();
try testing.expectEqualStrings(path, env.path());
try testing.expect(env.getMaxKeySize() > 0);
try testing.expect(env.getMaxNumReaders() == 42);
const stat = env.stat();
try testing.expect(stat.tree_height == 0);
try testing.expect(stat.num_branch_pages == 0);
try testing.expect(stat.num_leaf_pages == 0);
try testing.expect(stat.num_overflow_pages == 0);
try testing.expect(stat.num_entries == 0);
const flags = env.getFlags();
try testing.expect(flags.use_writable_memory_map == true);
try testing.expect(flags.dont_sync_metadata == true);
env.disableFlags(.{ .dont_sync_metadata = true });
try testing.expect(env.getFlags().dont_sync_metadata == false);
env.enableFlags(.{ .dont_sync_metadata = true });
try testing.expect(env.getFlags().dont_sync_metadata == true);
const info = env.info();
try testing.expect(info.map_address == null);
try testing.expect(info.map_size == 4 * 1024 * 1024);
try testing.expect(info.last_page_num == 1);
try testing.expect(info.last_tx_id == 0);
try testing.expect(info.max_num_reader_slots > 0);
try testing.expect(info.num_used_reader_slots == 0);
try env.setMapSize(8 * 1024 * 1024);
try testing.expect(env.info().map_size == 8 * 1024 * 1024);
// The file descriptor should be >= 0.
try testing.expect(env.fd() >= 0);
try testing.expect((try env.purge()) == 0);
}
test "Environment.copyTo(): backup environment and check environment integrity" {
var tmp_a = testing.tmpDir(.{});
defer tmp_a.cleanup();
var tmp_b = testing.tmpDir(.{});
defer tmp_b.cleanup();
var buf_a: [fs.MAX_PATH_BYTES]u8 = undefined;
var buf_b: [fs.MAX_PATH_BYTES]u8 = undefined;
var path_a = try tmp_a.dir.realpath("./", &buf_a);
var path_b = try tmp_b.dir.realpath("./", &buf_b);
const env_a = try Environment.init(path_a, .{});
{
defer env_a.deinit();
const tx = try env_a.begin(.{});
errdefer tx.deinit();
const db = try tx.open(.{});
defer db.close(env_a);
var i: u8 = 0;
while (i < 128) : (i += 1) {
try tx.put(db, &[_]u8{i}, &[_]u8{i}, .{ .dont_overwrite_key = true });
try testing.expectEqualStrings(&[_]u8{i}, try tx.get(db, &[_]u8{i}));
}
try tx.commit();
try env_a.copyTo(path_b, .{ .compact = true });
}
const env_b = try Environment.init(path_b, .{});
{
defer env_b.deinit();
const tx = try env_b.begin(.{});
defer tx.deinit();
const db = try tx.open(.{});
defer db.close(env_b);
var i: u8 = 0;
while (i < 128) : (i += 1) {
try testing.expectEqualStrings(&[_]u8{i}, try tx.get(db, &[_]u8{i}));
}
}
}
test "Environment.sync(): manually flush system buffers" {
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var buf: [fs.MAX_PATH_BYTES]u8 = undefined;
var path = try tmp.dir.realpath("./", &buf);
const env = try Environment.init(path, .{
.dont_sync = true,
.dont_sync_metadata = true,
.use_writable_memory_map = true,
});
defer env.deinit();
{
const tx = try env.begin(.{});
errdefer tx.deinit();
const db = try tx.open(.{});
defer db.close(env);
var i: u8 = 0;
while (i < 128) : (i += 1) {
try tx.put(db, &[_]u8{i}, &[_]u8{i}, .{ .dont_overwrite_key = true });
try testing.expectEqualStrings(&[_]u8{i}, try tx.get(db, &[_]u8{i}));
}
try tx.commit();
try env.sync(true);
}
{
const tx = try env.begin(.{});
defer tx.deinit();
const db = try tx.open(.{});
defer db.close(env);
var i: u8 = 0;
while (i < 128) : (i += 1) {
try testing.expectEqualStrings(&[_]u8{i}, try tx.get(db, &[_]u8{i}));
}
}
}
test "Transaction: get(), put(), reserve(), delete(), and commit() several entries with dont_overwrite_key = true / false" {
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var buf: [fs.MAX_PATH_BYTES]u8 = undefined;
var path = try tmp.dir.realpath("./", &buf);
const env = try Environment.init(path, .{});
defer env.deinit();
const tx = try env.begin(.{});
errdefer tx.deinit();
const db = try tx.open(.{});
defer db.close(env);
// Transaction.put() / Transaction.get()
try tx.put(db, "hello", "world", .{});
try testing.expectEqualStrings("world", try tx.get(db, "hello"));
// Transaction.put() / Transaction.reserve() / Transaction.get() (.{ .dont_overwrite_key = true })
try testing.expectError(error.AlreadyExists, tx.put(db, "hello", "world", .{ .dont_overwrite_key = true }));
{
const result = try tx.reserve(db, "hello", "world".len, .{ .dont_overwrite_key = true });
try testing.expectEqualStrings("world", result.found_existing);
}
try testing.expectEqualStrings("world", try tx.get(db, "hello"));
// Transaction.put() / Transaction.get() / Transaction.reserve() (.{ .dont_overwrite_key = false })
try tx.put(db, "hello", "other_value", .{});
try testing.expectEqualStrings("other_value", try tx.get(db, "hello"));
{
const result = try tx.reserve(db, "hello", "new_value".len, .{});
try testing.expectEqual("new_value".len, result.successful.len);
mem.copy(u8, result.successful, "new_value");
}
try testing.expectEqualStrings("new_value", try tx.get(db, "hello"));
// Transaction.del() / Transaction.get() / Transaction.put() / Transaction.get()
try tx.del(db, "hello", .key);
try testing.expectError(error.NotFound, tx.del(db, "hello", .key));
try testing.expectError(error.NotFound, tx.get(db, "hello"));
try tx.put(db, "hello", "world", .{});
try testing.expectEqualStrings("world", try tx.get(db, "hello"));
// Transaction.commit()
try tx.commit();
}
test "Transaction: reserve, write, and attempt to reserve again with dont_overwrite_key = true" {
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var buf: [fs.MAX_PATH_BYTES]u8 = undefined;
var path = try tmp.dir.realpath("./", &buf);
const env = try Environment.init(path, .{});
defer env.deinit();
const tx = try env.begin(.{});
errdefer tx.deinit();
const db = try tx.open(.{});
defer db.close(env);
switch (try tx.reserve(db, "hello", "world!".len, .{ .dont_overwrite_key = true })) {
.found_existing => try testing.expect(false),
.successful => |dst| std.mem.copy(u8, dst, "world!"),
}
switch (try tx.reserve(db, "hello", "world!".len, .{ .dont_overwrite_key = true })) {
.found_existing => |src| try testing.expectEqualStrings("world!", src),
.successful => try testing.expect(false),
}
try tx.commit();
}
test "Transaction: getOrPut() twice" {
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var buf: [fs.MAX_PATH_BYTES]u8 = undefined;
var path = try tmp.dir.realpath("./", &buf);
const env = try Environment.init(path, .{});
defer env.deinit();
const tx = try env.begin(.{});
errdefer tx.deinit();
const db = try tx.open(.{});
defer db.close(env);
try testing.expectEqual(@as(?[]const u8, null), try tx.getOrPut(db, "hello", "world"));
try testing.expectEqualStrings("world", try tx.get(db, "hello"));
try testing.expectEqualStrings("world", (try tx.getOrPut(db, "hello", "world")) orelse unreachable);
try tx.commit();
}
test "Transaction: use multiple named databases in a single transaction" {
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var buf: [fs.MAX_PATH_BYTES]u8 = undefined;
var path = try tmp.dir.realpath("./", &buf);
const env = try Environment.init(path, .{ .max_num_dbs = 2 });
defer env.deinit();
{
const tx = try env.begin(.{});
errdefer tx.deinit();
const a = try tx.use("A", .{ .create_if_not_exists = true });
defer a.close(env);
const b = try tx.use("B", .{ .create_if_not_exists = true });
defer b.close(env);
try tx.put(a, "hello", "this is in A!", .{});
try tx.put(b, "hello", "this is in B!", .{});
try tx.commit();
}
{
const tx = try env.begin(.{});
errdefer tx.deinit();
const a = try tx.use("A", .{});
defer a.close(env);
const b = try tx.use("B", .{});
defer b.close(env);
try testing.expectEqualStrings("this is in A!", try tx.get(a, "hello"));
try testing.expectEqualStrings("this is in B!", try tx.get(b, "hello"));
try tx.commit();
}
}
test "Transaction: nest transaction inside transaction" {
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var buf: [fs.MAX_PATH_BYTES]u8 = undefined;
var path = try tmp.dir.realpath("./", &buf);
const env = try Environment.init(path, .{});
defer env.deinit();
const parent = try env.begin(.{});
errdefer parent.deinit();
const db = try parent.open(.{});
defer db.close(env);
{
const child = try env.begin(.{ .parent = parent });
errdefer child.deinit();
// Parent ID is equivalent to Child ID. Parent is not allowed to perform
// operations while child has yet to be aborted / committed.
try testing.expectEqual(parent.id(), child.id());
// Operations cannot be performed against a parent transaction while a child
// transaction is still active.
try testing.expectError(error.TransactionNotAborted, parent.get(db, "hello"));
try child.put(db, "hello", "world", .{});
try child.commit();
}
try testing.expectEqualStrings("world", try parent.get(db, "hello"));
try parent.commit();
}
test "Transaction: custom key comparator" {
const Descending = struct {
fn order(a: []const u8, b: []const u8) math.Order {
return switch (mem.order(u8, a, b)) {
.eq => .eq,
.lt => .gt,
.gt => .lt,
};
}
};
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var buf: [fs.MAX_PATH_BYTES]u8 = undefined;
var path = try tmp.dir.realpath("./", &buf);
const env = try Environment.init(path, .{ .max_num_dbs = 2 });
defer env.deinit();
const tx = try env.begin(.{});
errdefer tx.deinit();
const db = try tx.open(.{});
defer db.close(env);
const items = [_][]const u8{ "a", "b", "c" };
try tx.setKeyOrder(db, Descending.order);
for (items) |item| {
try tx.put(db, item, item, .{ .dont_overwrite_key = true });
}
{
const cursor = try tx.cursor(db);
defer cursor.deinit();
var i: usize = 0;
while (try cursor.next()) |item| : (i += 1) {
try testing.expectEqualSlices(u8, items[items.len - 1 - i], item.key);
try testing.expectEqualSlices(u8, items[items.len - 1 - i], item.val);
}
}
try tx.commit();
}
test "Cursor: move around a database and add / delete some entries" {
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var buf: [fs.MAX_PATH_BYTES]u8 = undefined;
var path = try tmp.dir.realpath("./", &buf);
const env = try Environment.init(path, .{});
defer env.deinit();
const tx = try env.begin(.{});
errdefer tx.deinit();
const db = try tx.open(.{});
defer db.close(env);
{
const cursor = try tx.cursor(db);
defer cursor.deinit();
const items = [_][]const u8{ "a", "b", "c" };
// Cursor.put()
inline for (items) |item| {
try cursor.put(item, item, .{ .dont_overwrite_key = true });
}
// Cursor.current() / Cursor.first() / Cursor.last() / Cursor.next() / Cursor.prev()
{
const last_item = try cursor.last();
try testing.expectEqualStrings(items[items.len - 1], last_item.?.key);
try testing.expectEqualStrings(items[items.len - 1], last_item.?.val);
{
var i: usize = items.len - 1;
while (true) {
const item = (try cursor.prev()) orelse break;
try testing.expectEqualStrings(items[i - 1], item.key);
try testing.expectEqualStrings(items[i - 1], item.val);
i -= 1;
}
}
const current = try cursor.current();
const first_item = try cursor.first();
try testing.expectEqualStrings(items[0], first_item.?.key);
try testing.expectEqualStrings(items[0], first_item.?.val);
try testing.expectEqualStrings(first_item.?.key, current.?.key);
try testing.expectEqualStrings(first_item.?.val, current.?.val);
{
var i: usize = 1;
while (true) {
const item = (try cursor.next()) orelse break;
try testing.expectEqualStrings(items[i], item.key);
try testing.expectEqualStrings(items[i], item.val);
i += 1;
}
}
}
// Cursor.delete()
try cursor.del(.key);
while (try cursor.prev()) |_| try cursor.del(.key);
try testing.expectError(error.NotFound, cursor.del(.key));
try testing.expect((try cursor.current()) == null);
// Cursor.put() / Cursor.updateInPlace() / Cursor.reserveInPlace()
inline for (items) |item| {
try cursor.put(item, item, .{ .dont_overwrite_key = true });
try cursor.updateInPlace(item, "???");
try testing.expectEqualStrings("???", (try cursor.current()).?.val);
mem.copy(u8, try cursor.reserveInPlace(item, item.len), item);
try testing.expectEqualStrings(item, (try cursor.current()).?.val);
}
// Cursor.seekTo()
try testing.expectError(error.NotFound, cursor.seekTo("0"));
try testing.expectEqualStrings(items[items.len / 2], try cursor.seekTo(items[items.len / 2]));
// Cursor.seekFrom()
try testing.expectEqualStrings(items[0], (try cursor.seekFrom("0")).val);
try testing.expectEqualStrings(items[items.len / 2], (try cursor.seekFrom(items[items.len / 2])).val);
try testing.expectError(error.NotFound, cursor.seekFrom("z"));
try testing.expectEqualStrings(items[items.len - 1], (try cursor.seekFrom(items[items.len - 1])).val);
}
try tx.commit();
}
test "Cursor: interact with variable-sized items in a database with duplicate keys" {
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var buf: [fs.MAX_PATH_BYTES]u8 = undefined;
var path = try tmp.dir.realpath("./", &buf);
const env = try Environment.init(path, .{ .max_num_dbs = 1 });
defer env.deinit();
const tx = try env.begin(.{});
errdefer tx.deinit();
const db = try tx.open(.{ .allow_duplicate_keys = true });
defer db.close(env);
const expected = comptime .{
.{ "Another Set C", [_][]const u8{ "be", "ka", "kra", "tan" } },
.{ "Set A", [_][]const u8{ "a", "kay", "zay" } },
.{ "Some Set B", [_][]const u8{ "bru", "ski", "vle" } },
};
inline for (expected) |entry| {
inline for (entry[1]) |val| {
try tx.putItem(db, entry[0], val, .{ .dont_overwrite_item = true });
}
}
{
const cursor = try tx.cursor(db);
defer cursor.deinit();
comptime var i = 0;
comptime var j = 0;
inline while (i < expected.len) : ({
i += 1;
j = 0;
}) {
inline while (j < expected[i][1].len) : (j += 1) {
const maybe_entry = try cursor.next();
const entry = maybe_entry orelse unreachable;
try testing.expectEqualStrings(expected[i][0], entry.key);
try testing.expectEqualStrings(expected[i][1][j], entry.val);
}
}
}
try tx.commit();
}
test "Cursor: interact with batches of fixed-sized items in a database with duplicate keys" {
const U64 = struct {
fn order(a: []const u8, b: []const u8) math.Order {
const num_a = mem.bytesToValue(u64, a[0..8]);
const num_b = mem.bytesToValue(u64, b[0..8]);
if (num_a < num_b) return .lt;
if (num_a > num_b) return .gt;
return .eq;
}
};
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var buf: [fs.MAX_PATH_BYTES]u8 = undefined;
var path = try tmp.dir.realpath("./", &buf);
const env = try Environment.init(path, .{ .max_num_dbs = 1 });
defer env.deinit();
const tx = try env.begin(.{});
errdefer tx.deinit();
const db = try tx.open(.{
.allow_duplicate_keys = true,
.duplicate_entries_are_fixed_size = true,
});
defer db.close(env);
try tx.setItemOrder(db, U64.order);
comptime var items: [512]u64 = undefined;
inline for (items) |*item, i| item.* = @as(u64, i);
const expected = comptime .{
.{ "Set A", &items },
.{ "Set B", &items },
};
{
const cursor = try tx.cursor(db);
defer cursor.deinit();
inline for (expected) |entry| {
try testing.expectEqual(entry[1].len, try cursor.putBatch(entry[0], entry[1], .{}));
}
}
{
const cursor = try tx.cursor(db);
defer cursor.deinit();
inline for (expected) |expected_entry| {
const maybe_entry = try cursor.next();
const entry = maybe_entry orelse unreachable;
try testing.expectEqualStrings(expected_entry[0], entry.key);
var i: usize = 0;
while (try cursor.nextPage(u64)) |page| {
for (page.items) |item| {
try testing.expectEqual(expected_entry[1][i], item);
i += 1;
}
}
}
}
try tx.commit();
} | lmdb.zig |
const std = @import("std");
const builtin = std.builtin;
const assert = std.debug.assert;
const testing = std.testing;
const math = std.math;
usingnamespace @import("../include/psprtc.zig");
usingnamespace @import("../include/pspthreadman.zig");
/// Spurious wakeups are possible and no precision of timing is guaranteed.
/// TODO integrate with evented I/O
pub fn sleep(nanoseconds: u64) void {
_ = sceKernelDelayThread(@truncate(u32, nanoseconds / 1000));
}
/// Get a calendar timestamp, in seconds, relative to UTC 1970-01-01.
/// Precision of timing depends on the hardware and operating system.
/// The return value is signed because it is possible to have a date that is
/// before the epoch.
/// See `std.os.clock_gettime` for a POSIX timestamp.
pub fn timestamp() i64 {
var r: u64 = 0;
_ = sceRtcGetCurrentTick(&r);
return @intCast(i64, r / sceRtcGetTickResolution());
}
/// Get a calendar timestamp, in milliseconds, relative to UTC 1970-01-01.
/// Precision of timing depends on the hardware and operating system.
/// The return value is signed because it is possible to have a date that is
/// before the epoch.
/// See `std.os.clock_gettime` for a POSIX timestamp.
pub fn milliTimestamp() i64 {
var r: u64 = 0;
_ = sceRtcGetCurrentTick(&r);
return @intCast(i64, r / 1000);
}
/// Get a calendar timestamp, in nanoseconds, relative to UTC 1970-01-01.
/// Precision of timing depends on the hardware and operating system.
/// On Windows this has a maximum granularity of 100 nanoseconds.
/// The return value is signed because it is possible to have a date that is
/// before the epoch.
/// See `std.os.clock_gettime` for a POSIX timestamp.
pub fn nanoTimestamp() i128 {
var r: u64 = 0;
_ = sceRtcGetCurrentTick(&r);
return @intCast(i64, r * 1000);
}
// Divisions of a nanosecond.
pub const ns_per_us = 1000;
pub const ns_per_ms = 1000 * ns_per_us;
pub const ns_per_s = 1000 * ns_per_ms;
pub const ns_per_min = 60 * ns_per_s;
pub const ns_per_hour = 60 * ns_per_min;
pub const ns_per_day = 24 * ns_per_hour;
pub const ns_per_week = 7 * ns_per_day;
// Divisions of a microsecond.
pub const us_per_ms = 1000;
pub const us_per_s = 1000 * us_per_ms;
pub const us_per_min = 60 * us_per_s;
pub const us_per_hour = 60 * us_per_min;
pub const us_per_day = 24 * us_per_hour;
pub const us_per_week = 7 * us_per_day;
// Divisions of a millisecond.
pub const ms_per_s = 1000;
pub const ms_per_min = 60 * ms_per_s;
pub const ms_per_hour = 60 * ms_per_min;
pub const ms_per_day = 24 * ms_per_hour;
pub const ms_per_week = 7 * ms_per_day;
// Divisions of a second.
pub const s_per_min = 60;
pub const s_per_hour = s_per_min * 60;
pub const s_per_day = s_per_hour * 24;
pub const s_per_week = s_per_day * 7;
/// A monotonic high-performance timer.
/// Timer.start() must be called to initialize the struct, which captures
/// the counter frequency on windows and darwin, records the resolution,
/// and gives the user an opportunity to check for the existnece of
/// monotonic clocks without forcing them to check for error on each read.
/// .resolution is in nanoseconds on all platforms but .start_time's meaning
/// depends on the OS. On Windows and Darwin it is a hardware counter
/// value that requires calculation to convert to a meaninful unit.
pub const Timer = struct {
///if we used resolution's value when performing the
/// performance counter calc on windows/darwin, it would
/// be less precise
frequency: void,
resolution: u64,
start_time: u64,
pub const Error = error{TimerUnsupported};
/// At some point we may change our minds on RAW, but for now we're
/// sticking with posix standard MONOTONIC. For more information, see:
/// https://github.com/ziglang/zig/pull/933
const monotonic_clock_id = os.CLOCK_MONOTONIC;
/// Initialize the timer structure.
/// Can only fail when running in a hostile environment that intentionally injects
/// error values into syscalls, such as using seccomp on Linux to intercept
/// `clock_gettime`.
pub fn start() Timer {
var r: u64 = 0;
_ = sceRtcGetCurrentTick(&r);
return Timer{
.resolution = sceRtcGetTickResolution(),
.start_time = r,
.frequency = {},
};
}
/// Reads the timer value since start or the last reset in nanoseconds
pub fn read(self: Timer) u64 {
var clock = clockNative() - self.start_time;
return self.nativeDurationToNanos(clock);
}
/// Resets the timer value to 0/now.
pub fn reset(self: *Timer) void {
self.start_time = clockNative();
}
/// Returns the current value of the timer in nanoseconds, then resets it
pub fn lap(self: *Timer) u64 {
var now = clockNative();
var lap_time = self.nativeDurationToNanos(now - self.start_time);
self.start_time = now;
return lap_time;
}
//Gets our current ticker
fn clockNative() u64 {
var r: u64 = 0;
_ = sceRtcGetCurrentTick(&r);
return r;
}
//On PSP... duration = us
//Therefore duration * ns_per_us
fn nativeDurationToNanos(self: Timer, duration: u64) u64 {
return duration * ns_per_us;
}
}; | src/psp/os/time.zig |
const std = @import("std");
const Builder = std.build.Builder;
const libxml2 = @import("vendor/zig-libxml2/libxml2.zig");
const ScdocStep = @import("src-build/ScdocStep.zig");
// Zig packages in use
const pkgs = struct {
const flightplan = pkg("src/main.zig");
};
/// pkg can be called to get the Pkg for this library. Downstream users
/// can use this to add the package to the import paths.
pub fn pkg(path: []const u8) std.build.Pkg {
return std.build.Pkg{
.name = "flightplan",
.path = .{ .path = path },
};
}
pub fn build(b: *Builder) !void {
const mode = b.standardReleaseOptions();
const target = b.standardTargetOptions(.{});
// Options
const man_pages = b.option(
bool,
"man-pages",
"Set to true to build man pages. Requires scdoc. Defaults to true if scdoc is found.",
) orelse scdoc_found: {
_ = b.findProgram(&[_][]const u8{"scdoc"}, &[_][]const u8{}) catch |err| switch (err) {
error.FileNotFound => break :scdoc_found false,
else => return err,
};
break :scdoc_found true;
};
// Steps
const test_step = b.step("test", "Run all tests");
const test_unit_step = b.step("test-unit", "Run unit tests only");
// Build libxml2 for static builds only
const xml2 = try libxml2.create(b, target, mode, .{
.iconv = false,
.lzma = false,
.zlib = false,
});
// Native Zig tests
const lib_tests = b.addTestSource(pkgs.flightplan.path);
addSharedSettings(lib_tests, mode, target);
xml2.link(lib_tests);
test_unit_step.dependOn(&lib_tests.step);
test_step.dependOn(&lib_tests.step);
// Static C lib
{
const static_lib = b.addStaticLibrary("flightplan", "src/binding.zig");
addSharedSettings(static_lib, mode, target);
xml2.addIncludeDirs(static_lib);
static_lib.install();
b.default_step.dependOn(&static_lib.step);
const static_binding_test = b.addExecutable("static-binding", null);
static_binding_test.setBuildMode(mode);
static_binding_test.setTarget(target);
static_binding_test.linkLibC();
static_binding_test.addIncludeDir("include");
static_binding_test.addCSourceFile("examples/basic.c", &[_][]const u8{ "-Wall", "-Wextra", "-pedantic", "-std=c99" });
static_binding_test.linkLibrary(static_lib);
xml2.link(static_binding_test);
const static_binding_test_run = static_binding_test.run();
test_step.dependOn(&static_binding_test_run.step);
}
// Dynamic C lib. We only build this if this is the native target so we
// can link to libxml2 on our native system.
if (target.isNative()) {
const dynamic_lib_name = if (target.isWindows())
"flightplan.dll"
else
"flightplan";
const dynamic_lib = b.addSharedLibrary(dynamic_lib_name, "src/binding.zig", .unversioned);
addSharedSettings(dynamic_lib, mode, target);
dynamic_lib.linkSystemLibrary("libxml-2.0");
dynamic_lib.install();
b.default_step.dependOn(&dynamic_lib.step);
const dynamic_binding_test = b.addExecutable("dynamic-binding", null);
dynamic_binding_test.setBuildMode(mode);
dynamic_binding_test.setTarget(target);
dynamic_binding_test.linkLibC();
dynamic_binding_test.addIncludeDir("include");
dynamic_binding_test.addCSourceFile("examples/basic.c", &[_][]const u8{ "-Wall", "-Wextra", "-pedantic", "-std=c99" });
dynamic_binding_test.linkLibrary(dynamic_lib);
const dynamic_binding_test_run = dynamic_binding_test.run();
test_step.dependOn(&dynamic_binding_test_run.step);
}
// Headers
const install_header = b.addInstallFileWithDir(
.{ .path = "include/flightplan.h" },
.header,
"flightplan.h",
);
b.getInstallStep().dependOn(&install_header.step);
// pkg-config
{
const file = try std.fs.path.join(
b.allocator,
&[_][]const u8{ b.cache_root, "libflightplan.pc" },
);
const pkgconfig_file = try std.fs.cwd().createFile(file, .{});
const writer = pkgconfig_file.writer();
try writer.print(
\\prefix={s}
\\includedir=${{prefix}}/include
\\libdir=${{prefix}}/lib
\\
\\Name: libflightplan
\\URL: https://github.com/mitchellh/libflightplan
\\Description: Library for reading and writing aviation flight plans.
\\Version: 0.1.0
\\Cflags: -I${{includedir}}
\\Libs: -L${{libdir}} -lflightplan
, .{b.install_prefix});
defer pkgconfig_file.close();
b.installFile(file, "share/pkgconfig/libflightplan.pc");
}
if (man_pages) {
const scdoc_step = ScdocStep.create(b);
try scdoc_step.install();
}
}
/// The shared settings that we need to apply when building a library or
/// executable using libflightplan.
fn addSharedSettings(
lib: *std.build.LibExeObjStep,
mode: std.builtin.Mode,
target: std.zig.CrossTarget,
) void {
lib.setBuildMode(mode);
lib.setTarget(target);
lib.addPackage(pkgs.flightplan);
lib.addIncludeDir("src/include");
lib.addIncludeDir("include");
lib.linkLibC();
} | build.zig |
const ComputePassTimestampWrite = @import("structs.zig").ComputePassTimestampWrite;
const ComputePipeline = @import("ComputePipeline.zig");
const QuerySet = @import("QuerySet.zig");
const BindGroup = @import("BindGroup.zig");
const Buffer = @import("Buffer.zig");
const ComputePassEncoder = @This();
/// The type erased pointer to the ComputePassEncoder implementation
/// Equal to c.WGPUComputePassEncoder for NativeInstance.
ptr: *anyopaque,
vtable: *const VTable,
pub const VTable = struct {
reference: fn (ptr: *anyopaque) void,
release: fn (ptr: *anyopaque) void,
dispatch: fn (ptr: *anyopaque, workgroup_count_x: u32, workgroup_count_y: u32, workgroup_count_z: u32) void,
dispatchIndirect: fn (ptr: *anyopaque, indirect_buffer: Buffer, indirect_offset: u64) void,
end: fn (ptr: *anyopaque) void,
insertDebugMarker: fn (ptr: *anyopaque, marker_label: [*:0]const u8) void,
popDebugGroup: fn (ptr: *anyopaque) void,
pushDebugGroup: fn (ptr: *anyopaque, group_label: [*:0]const u8) void,
setBindGroup: fn (ptr: *anyopaque, group_index: u32, group: BindGroup, dynamic_offsets: ?[]const u32) void,
setLabel: fn (ptr: *anyopaque, label: [:0]const u8) void,
setPipeline: fn (ptr: *anyopaque, pipeline: ComputePipeline) void,
writeTimestamp: fn (ptr: *anyopaque, query_set: QuerySet, query_index: u32) void,
};
pub inline fn reference(enc: ComputePassEncoder) void {
enc.vtable.reference(enc.ptr);
}
pub inline fn release(enc: ComputePassEncoder) void {
enc.vtable.release(enc.ptr);
}
pub inline fn dispatch(
enc: ComputePassEncoder,
workgroup_count_x: u32,
workgroup_count_y: u32,
workgroup_count_z: u32,
) void {
enc.vtable.dispatch(enc.ptr, workgroup_count_x, workgroup_count_y, workgroup_count_z);
}
pub inline fn dispatchIndirect(
enc: ComputePassEncoder,
indirect_buffer: Buffer,
indirect_offset: u64,
) void {
enc.vtable.dispatchIndirect(enc.ptr, indirect_buffer, indirect_offset);
}
pub inline fn end(enc: ComputePassEncoder) void {
enc.vtable.end(enc.ptr);
}
pub inline fn insertDebugMarker(enc: ComputePassEncoder, marker_label: [*:0]const u8) void {
enc.vtable.insertDebugMarker(enc.ptr, marker_label);
}
pub inline fn popDebugGroup(enc: ComputePassEncoder) void {
enc.vtable.popDebugGroup(enc.ptr);
}
pub inline fn pushDebugGroup(enc: ComputePassEncoder, group_label: [*:0]const u8) void {
enc.vtable.pushDebugGroup(enc.ptr, group_label);
}
pub inline fn setBindGroup(
enc: ComputePassEncoder,
group_index: u32,
group: BindGroup,
dynamic_offsets: ?[]const u32,
) void {
enc.vtable.setBindGroup(enc.ptr, group_index, group, dynamic_offsets);
}
pub inline fn setLabel(enc: ComputePassEncoder, label: [:0]const u8) void {
enc.vtable.setLabel(enc.ptr, label);
}
pub inline fn setPipeline(enc: ComputePassEncoder, pipeline: ComputePipeline) void {
enc.vtable.setPipeline(enc.ptr, pipeline);
}
pub inline fn writeTimestamp(enc: ComputePassEncoder, query_set: QuerySet, query_index: u32) void {
enc.vtable.writeTimestamp(enc.ptr, query_set, query_index);
}
pub const Descriptor = struct {
label: ?[*:0]const u8 = null,
timestamp_writes: []const ComputePassTimestampWrite,
};
test {
_ = VTable;
_ = reference;
_ = release;
_ = dispatch;
_ = dispatchIndirect;
_ = end;
_ = insertDebugMarker;
_ = popDebugGroup;
_ = pushDebugGroup;
_ = setBindGroup;
_ = setLabel;
_ = setPipeline;
_ = writeTimestamp;
_ = Descriptor;
} | gpu/src/ComputePassEncoder.zig |
const std = @import("std");
const testing = std.testing;
const mem = std.mem;
const assert = std.debug.assert;
const ArrayList = std.ArrayList;
const Allocator = std.mem.Allocator;
const DW = std.dwarf;
// zig fmt: off
/// Definitions of all of the x64 registers. The order is semantically meaningful.
/// The registers are defined such that IDs go in descending order of 64-bit,
/// 32-bit, 16-bit, and then 8-bit, and each set contains exactly sixteen
/// registers. This results in some useful properties:
///
/// Any 64-bit register can be turned into its 32-bit form by adding 16, and
/// vice versa. This also works between 32-bit and 16-bit forms. With 8-bit, it
/// works for all except for sp, bp, si, and di, which do *not* have an 8-bit
/// form.
///
/// If (register & 8) is set, the register is extended.
///
/// The ID can be easily determined by figuring out what range the register is
/// in, and then subtracting the base.
pub const Register = enum(u7) {
// 0 through 15, 64-bit registers. 8-15 are extended.
// id is just the int value.
rax, rcx, rdx, rbx, rsp, rbp, rsi, rdi,
r8, r9, r10, r11, r12, r13, r14, r15,
// 16 through 31, 32-bit registers. 24-31 are extended.
// id is int value - 16.
eax, ecx, edx, ebx, esp, ebp, esi, edi,
r8d, r9d, r10d, r11d, r12d, r13d, r14d, r15d,
// 32-47, 16-bit registers. 40-47 are extended.
// id is int value - 32.
ax, cx, dx, bx, sp, bp, si, di,
r8w, r9w, r10w, r11w, r12w, r13w, r14w, r15w,
// 48-63, 8-bit registers. 56-63 are extended.
// id is int value - 48.
al, cl, dl, bl, ah, ch, dh, bh,
r8b, r9b, r10b, r11b, r12b, r13b, r14b, r15b,
// Pseudo, used only for MIR to signify that the
// operand is not a register but an immediate, etc.
none,
/// Returns the bit-width of the register.
pub fn size(self: Register) u7 {
return switch (@enumToInt(self)) {
0...15 => 64,
16...31 => 32,
32...47 => 16,
48...64 => 8,
else => unreachable,
};
}
/// Returns whether the register is *extended*. Extended registers are the
/// new registers added with amd64, r8 through r15. This also includes any
/// other variant of access to those registers, such as r8b, r15d, and so
/// on. This is needed because access to these registers requires special
/// handling via the REX prefix, via the B or R bits, depending on context.
pub fn isExtended(self: Register) bool {
return @enumToInt(self) & 0x08 != 0;
}
/// This returns the 4-bit register ID, which is used in practically every
/// opcode. Note that bit 3 (the highest bit) is *never* used directly in
/// an instruction (@see isExtended), and requires special handling. The
/// lower three bits are often embedded directly in instructions (such as
/// the B8 variant of moves), or used in R/M bytes.
pub fn id(self: Register) u4 {
return @truncate(u4, @enumToInt(self));
}
/// Like id, but only returns the lower 3 bits.
pub fn lowId(self: Register) u3 {
return @truncate(u3, @enumToInt(self));
}
/// Returns the index into `callee_preserved_regs`.
pub fn allocIndex(self: Register) ?u4 {
return switch (self) {
.rcx, .ecx, .cx, .cl => 0,
.rsi, .esi, .si => 1,
.rdi, .edi, .di => 2,
.r8, .r8d, .r8w, .r8b => 3,
.r9, .r9d, .r9w, .r9b => 4,
.r10, .r10d, .r10w, .r10b => 5,
.r11, .r11d, .r11w, .r11b => 6,
else => null,
};
}
/// Convert from any register to its 64 bit alias.
pub fn to64(self: Register) Register {
return @intToEnum(Register, self.id());
}
/// Convert from any register to its 32 bit alias.
pub fn to32(self: Register) Register {
return @intToEnum(Register, @as(u8, self.id()) + 16);
}
/// Convert from any register to its 16 bit alias.
pub fn to16(self: Register) Register {
return @intToEnum(Register, @as(u8, self.id()) + 32);
}
/// Convert from any register to its 8 bit alias.
pub fn to8(self: Register) Register {
return @intToEnum(Register, @as(u8, self.id()) + 48);
}
pub fn dwarfLocOp(self: Register) u8 {
return switch (self.to64()) {
.rax => DW.OP.reg0,
.rdx => DW.OP.reg1,
.rcx => DW.OP.reg2,
.rbx => DW.OP.reg3,
.rsi => DW.OP.reg4,
.rdi => DW.OP.reg5,
.rbp => DW.OP.reg6,
.rsp => DW.OP.reg7,
.r8 => DW.OP.reg8,
.r9 => DW.OP.reg9,
.r10 => DW.OP.reg10,
.r11 => DW.OP.reg11,
.r12 => DW.OP.reg12,
.r13 => DW.OP.reg13,
.r14 => DW.OP.reg14,
.r15 => DW.OP.reg15,
else => unreachable,
};
}
};
// zig fmt: on
/// TODO this set is actually a set of caller-saved registers.
/// These registers need to be preserved (saved on the stack) and restored by the callee before getting clobbered
/// and when the callee returns.
pub const callee_preserved_regs = [_]Register{ .rcx, .rsi, .rdi, .r8, .r9, .r10, .r11 };
pub const c_abi_int_param_regs = [_]Register{ .rdi, .rsi, .rdx, .rcx, .r8, .r9 };
pub const c_abi_int_return_regs = [_]Register{ .rax, .rdx };
/// Encoding helper functions for x86_64 instructions
///
/// Many of these helpers do very little, but they can help make things
/// slightly more readable with more descriptive field names / function names.
///
/// Some of them also have asserts to ensure that we aren't doing dumb things.
/// For example, trying to use register 4 (esp) in an indirect modr/m byte is illegal,
/// you need to encode it with an SIB byte.
///
/// Note that ALL of these helper functions will assume capacity,
/// so ensure that the `code` has sufficient capacity before using them.
/// The `init` method is the recommended way to ensure capacity.
pub const Encoder = struct {
/// Non-owning reference to the code array
code: *ArrayList(u8),
const Self = @This();
/// Wrap `code` in Encoder to make it easier to call these helper functions
///
/// maximum_inst_size should contain the maximum number of bytes
/// that the encoded instruction will take.
/// This is because the helper functions will assume capacity
/// in order to avoid bounds checking.
pub fn init(code: *ArrayList(u8), maximum_inst_size: u8) !Self {
try code.ensureUnusedCapacity(maximum_inst_size);
return Self{ .code = code };
}
/// Directly write a number to the code array with big endianness
pub fn writeIntBig(self: Self, comptime T: type, value: T) void {
mem.writeIntBig(
T,
self.code.addManyAsArrayAssumeCapacity(@divExact(@typeInfo(T).Int.bits, 8)),
value,
);
}
/// Directly write a number to the code array with little endianness
pub fn writeIntLittle(self: Self, comptime T: type, value: T) void {
mem.writeIntLittle(
T,
self.code.addManyAsArrayAssumeCapacity(@divExact(@typeInfo(T).Int.bits, 8)),
value,
);
}
// --------
// Prefixes
// --------
pub const LegacyPrefixes = packed struct {
/// LOCK
prefix_f0: bool = false,
/// REPNZ, REPNE, REP, Scalar Double-precision
prefix_f2: bool = false,
/// REPZ, REPE, REP, Scalar Single-precision
prefix_f3: bool = false,
/// CS segment override or Branch not taken
prefix_2e: bool = false,
/// DS segment override
prefix_36: bool = false,
/// ES segment override
prefix_26: bool = false,
/// FS segment override
prefix_64: bool = false,
/// GS segment override
prefix_65: bool = false,
/// Branch taken
prefix_3e: bool = false,
/// Operand size override (enables 16 bit operation)
prefix_66: bool = false,
/// Address size override (enables 16 bit address size)
prefix_67: bool = false,
padding: u5 = 0,
};
/// Encodes legacy prefixes
pub fn legacyPrefixes(self: Self, prefixes: LegacyPrefixes) void {
if (@bitCast(u16, prefixes) != 0) {
// Hopefully this path isn't taken very often, so we'll do it the slow way for now
// LOCK
if (prefixes.prefix_f0) self.code.appendAssumeCapacity(0xf0);
// REPNZ, REPNE, REP, Scalar Double-precision
if (prefixes.prefix_f2) self.code.appendAssumeCapacity(0xf2);
// REPZ, REPE, REP, Scalar Single-precision
if (prefixes.prefix_f3) self.code.appendAssumeCapacity(0xf3);
// CS segment override or Branch not taken
if (prefixes.prefix_2e) self.code.appendAssumeCapacity(0x2e);
// DS segment override
if (prefixes.prefix_36) self.code.appendAssumeCapacity(0x36);
// ES segment override
if (prefixes.prefix_26) self.code.appendAssumeCapacity(0x26);
// FS segment override
if (prefixes.prefix_64) self.code.appendAssumeCapacity(0x64);
// GS segment override
if (prefixes.prefix_65) self.code.appendAssumeCapacity(0x65);
// Branch taken
if (prefixes.prefix_3e) self.code.appendAssumeCapacity(0x3e);
// Operand size override
if (prefixes.prefix_66) self.code.appendAssumeCapacity(0x66);
// Address size override
if (prefixes.prefix_67) self.code.appendAssumeCapacity(0x67);
}
}
/// Use 16 bit operand size
///
/// Note that this flag is overridden by REX.W, if both are present.
pub fn prefix16BitMode(self: Self) void {
self.code.appendAssumeCapacity(0x66);
}
/// From section 2.2.1.2 of the manual, REX is encoded as b0100WRXB
pub const Rex = struct {
/// Wide, enables 64-bit operation
w: bool = false,
/// Extends the reg field in the ModR/M byte
r: bool = false,
/// Extends the index field in the SIB byte
x: bool = false,
/// Extends the r/m field in the ModR/M byte,
/// or the base field in the SIB byte,
/// or the reg field in the Opcode byte
b: bool = false,
};
/// Encodes a REX prefix byte given all the fields
///
/// Use this byte whenever you need 64 bit operation,
/// or one of reg, index, r/m, base, or opcode-reg might be extended.
///
/// See struct `Rex` for a description of each field.
///
/// Does not add a prefix byte if none of the fields are set!
pub fn rex(self: Self, byte: Rex) void {
var value: u8 = 0b0100_0000;
if (byte.w) value |= 0b1000;
if (byte.r) value |= 0b0100;
if (byte.x) value |= 0b0010;
if (byte.b) value |= 0b0001;
if (value != 0b0100_0000) {
self.code.appendAssumeCapacity(value);
}
}
// ------
// Opcode
// ------
/// Encodes a 1 byte opcode
pub fn opcode_1byte(self: Self, opcode: u8) void {
self.code.appendAssumeCapacity(opcode);
}
/// Encodes a 2 byte opcode
///
/// e.g. IMUL has the opcode 0x0f 0xaf, so you use
///
/// encoder.opcode_2byte(0x0f, 0xaf);
pub fn opcode_2byte(self: Self, prefix: u8, opcode: u8) void {
self.code.appendAssumeCapacity(prefix);
self.code.appendAssumeCapacity(opcode);
}
/// Encodes a 1 byte opcode with a reg field
///
/// Remember to add a REX prefix byte if reg is extended!
pub fn opcode_withReg(self: Self, opcode: u8, reg: u3) void {
assert(opcode & 0b111 == 0);
self.code.appendAssumeCapacity(opcode | reg);
}
// ------
// ModR/M
// ------
/// Construct a ModR/M byte given all the fields
///
/// Remember to add a REX prefix byte if reg or rm are extended!
pub fn modRm(self: Self, mod: u2, reg_or_opx: u3, rm: u3) void {
self.code.appendAssumeCapacity(
@as(u8, mod) << 6 | @as(u8, reg_or_opx) << 3 | rm,
);
}
/// Construct a ModR/M byte using direct r/m addressing
/// r/m effective address: r/m
///
/// Note reg's effective address is always just reg for the ModR/M byte.
/// Remember to add a REX prefix byte if reg or rm are extended!
pub fn modRm_direct(self: Self, reg_or_opx: u3, rm: u3) void {
self.modRm(0b11, reg_or_opx, rm);
}
/// Construct a ModR/M byte using indirect r/m addressing
/// r/m effective address: [r/m]
///
/// Note reg's effective address is always just reg for the ModR/M byte.
/// Remember to add a REX prefix byte if reg or rm are extended!
pub fn modRm_indirectDisp0(self: Self, reg_or_opx: u3, rm: u3) void {
assert(rm != 4 and rm != 5);
self.modRm(0b00, reg_or_opx, rm);
}
/// Construct a ModR/M byte using indirect SIB addressing
/// r/m effective address: [SIB]
///
/// Note reg's effective address is always just reg for the ModR/M byte.
/// Remember to add a REX prefix byte if reg or rm are extended!
pub fn modRm_SIBDisp0(self: Self, reg_or_opx: u3) void {
self.modRm(0b00, reg_or_opx, 0b100);
}
/// Construct a ModR/M byte using RIP-relative addressing
/// r/m effective address: [RIP + disp32]
///
/// Note reg's effective address is always just reg for the ModR/M byte.
/// Remember to add a REX prefix byte if reg or rm are extended!
pub fn modRm_RIPDisp32(self: Self, reg_or_opx: u3) void {
self.modRm(0b00, reg_or_opx, 0b101);
}
/// Construct a ModR/M byte using indirect r/m with a 8bit displacement
/// r/m effective address: [r/m + disp8]
///
/// Note reg's effective address is always just reg for the ModR/M byte.
/// Remember to add a REX prefix byte if reg or rm are extended!
pub fn modRm_indirectDisp8(self: Self, reg_or_opx: u3, rm: u3) void {
assert(rm != 4);
self.modRm(0b01, reg_or_opx, rm);
}
/// Construct a ModR/M byte using indirect SIB with a 8bit displacement
/// r/m effective address: [SIB + disp8]
///
/// Note reg's effective address is always just reg for the ModR/M byte.
/// Remember to add a REX prefix byte if reg or rm are extended!
pub fn modRm_SIBDisp8(self: Self, reg_or_opx: u3) void {
self.modRm(0b01, reg_or_opx, 0b100);
}
/// Construct a ModR/M byte using indirect r/m with a 32bit displacement
/// r/m effective address: [r/m + disp32]
///
/// Note reg's effective address is always just reg for the ModR/M byte.
/// Remember to add a REX prefix byte if reg or rm are extended!
pub fn modRm_indirectDisp32(self: Self, reg_or_opx: u3, rm: u3) void {
assert(rm != 4);
self.modRm(0b10, reg_or_opx, rm);
}
/// Construct a ModR/M byte using indirect SIB with a 32bit displacement
/// r/m effective address: [SIB + disp32]
///
/// Note reg's effective address is always just reg for the ModR/M byte.
/// Remember to add a REX prefix byte if reg or rm are extended!
pub fn modRm_SIBDisp32(self: Self, reg_or_opx: u3) void {
self.modRm(0b10, reg_or_opx, 0b100);
}
// ---
// SIB
// ---
/// Construct a SIB byte given all the fields
///
/// Remember to add a REX prefix byte if index or base are extended!
pub fn sib(self: Self, scale: u2, index: u3, base: u3) void {
self.code.appendAssumeCapacity(
@as(u8, scale) << 6 | @as(u8, index) << 3 | base,
);
}
/// Construct a SIB byte with scale * index + base, no frills.
/// r/m effective address: [base + scale * index]
///
/// Remember to add a REX prefix byte if index or base are extended!
pub fn sib_scaleIndexBase(self: Self, scale: u2, index: u3, base: u3) void {
assert(base != 5);
self.sib(scale, index, base);
}
/// Construct a SIB byte with scale * index + disp32
/// r/m effective address: [scale * index + disp32]
///
/// Remember to add a REX prefix byte if index or base are extended!
pub fn sib_scaleIndexDisp32(self: Self, scale: u2, index: u3) void {
assert(index != 4);
// scale is actually ignored
// index = 4 means no index
// base = 5 means no base, if mod == 0.
self.sib(scale, index, 5);
}
/// Construct a SIB byte with just base
/// r/m effective address: [base]
///
/// Remember to add a REX prefix byte if index or base are extended!
pub fn sib_base(self: Self, base: u3) void {
assert(base != 5);
// scale is actually ignored
// index = 4 means no index
self.sib(0, 4, base);
}
/// Construct a SIB byte with just disp32
/// r/m effective address: [disp32]
///
/// Remember to add a REX prefix byte if index or base are extended!
pub fn sib_disp32(self: Self) void {
// scale is actually ignored
// index = 4 means no index
// base = 5 means no base, if mod == 0.
self.sib(0, 4, 5);
}
/// Construct a SIB byte with scale * index + base + disp8
/// r/m effective address: [base + scale * index + disp8]
///
/// Remember to add a REX prefix byte if index or base are extended!
pub fn sib_scaleIndexBaseDisp8(self: Self, scale: u2, index: u3, base: u3) void {
self.sib(scale, index, base);
}
/// Construct a SIB byte with base + disp8, no index
/// r/m effective address: [base + disp8]
///
/// Remember to add a REX prefix byte if index or base are extended!
pub fn sib_baseDisp8(self: Self, base: u3) void {
// scale is ignored
// index = 4 means no index
self.sib(0, 4, base);
}
/// Construct a SIB byte with scale * index + base + disp32
/// r/m effective address: [base + scale * index + disp32]
///
/// Remember to add a REX prefix byte if index or base are extended!
pub fn sib_scaleIndexBaseDisp32(self: Self, scale: u2, index: u3, base: u3) void {
self.sib(scale, index, base);
}
/// Construct a SIB byte with base + disp32, no index
/// r/m effective address: [base + disp32]
///
/// Remember to add a REX prefix byte if index or base are extended!
pub fn sib_baseDisp32(self: Self, base: u3) void {
// scale is ignored
// index = 4 means no index
self.sib(0, 4, base);
}
// -------------------------
// Trivial (no bit fiddling)
// -------------------------
/// Encode an 8 bit immediate
///
/// It is sign-extended to 64 bits by the cpu.
pub fn imm8(self: Self, imm: i8) void {
self.code.appendAssumeCapacity(@bitCast(u8, imm));
}
/// Encode an 8 bit displacement
///
/// It is sign-extended to 64 bits by the cpu.
pub fn disp8(self: Self, disp: i8) void {
self.code.appendAssumeCapacity(@bitCast(u8, disp));
}
/// Encode an 16 bit immediate
///
/// It is sign-extended to 64 bits by the cpu.
pub fn imm16(self: Self, imm: i16) void {
self.writeIntLittle(i16, imm);
}
/// Encode an 32 bit immediate
///
/// It is sign-extended to 64 bits by the cpu.
pub fn imm32(self: Self, imm: i32) void {
self.writeIntLittle(i32, imm);
}
/// Encode an 32 bit displacement
///
/// It is sign-extended to 64 bits by the cpu.
pub fn disp32(self: Self, disp: i32) void {
self.writeIntLittle(i32, disp);
}
/// Encode an 64 bit immediate
///
/// It is sign-extended to 64 bits by the cpu.
pub fn imm64(self: Self, imm: u64) void {
self.writeIntLittle(u64, imm);
}
};
test "x86_64 Encoder helpers" {
var code = ArrayList(u8).init(testing.allocator);
defer code.deinit();
// simple integer multiplication
// imul eax,edi
// 0faf c7
{
try code.resize(0);
const encoder = try Encoder.init(&code, 4);
encoder.rex(.{
.r = Register.eax.isExtended(),
.b = Register.edi.isExtended(),
});
encoder.opcode_2byte(0x0f, 0xaf);
encoder.modRm_direct(
Register.eax.lowId(),
Register.edi.lowId(),
);
try testing.expectEqualSlices(u8, &[_]u8{ 0x0f, 0xaf, 0xc7 }, code.items);
}
// simple mov
// mov eax,edi
// 89 f8
{
try code.resize(0);
const encoder = try Encoder.init(&code, 3);
encoder.rex(.{
.r = Register.edi.isExtended(),
.b = Register.eax.isExtended(),
});
encoder.opcode_1byte(0x89);
encoder.modRm_direct(
Register.edi.lowId(),
Register.eax.lowId(),
);
try testing.expectEqualSlices(u8, &[_]u8{ 0x89, 0xf8 }, code.items);
}
// signed integer addition of 32-bit sign extended immediate to 64 bit register
// add rcx, 2147483647
//
// Using the following opcode: REX.W + 81 /0 id, we expect the following encoding
//
// 48 : REX.W set for 64 bit operand (*r*cx)
// 81 : opcode for "<arithmetic> with immediate"
// c1 : id = rcx,
// : c1 = 11 <-- mod = 11 indicates r/m is register (rcx)
// : 000 <-- opcode_extension = 0 because opcode extension is /0. /0 specifies ADD
// : 001 <-- 001 is rcx
// ffffff7f : 2147483647
{
try code.resize(0);
const encoder = try Encoder.init(&code, 7);
encoder.rex(.{ .w = true }); // use 64 bit operation
encoder.opcode_1byte(0x81);
encoder.modRm_direct(
0,
Register.rcx.lowId(),
);
encoder.imm32(2147483647);
try testing.expectEqualSlices(u8, &[_]u8{ 0x48, 0x81, 0xc1, 0xff, 0xff, 0xff, 0x7f }, code.items);
}
}
// TODO add these registers to the enum and populate dwarfLocOp
// // Return Address register. This is stored in `0(%rsp, "")` and is not a physical register.
// RA = (16, "RA"),
//
// XMM0 = (17, "xmm0"),
// XMM1 = (18, "xmm1"),
// XMM2 = (19, "xmm2"),
// XMM3 = (20, "xmm3"),
// XMM4 = (21, "xmm4"),
// XMM5 = (22, "xmm5"),
// XMM6 = (23, "xmm6"),
// XMM7 = (24, "xmm7"),
//
// XMM8 = (25, "xmm8"),
// XMM9 = (26, "xmm9"),
// XMM10 = (27, "xmm10"),
// XMM11 = (28, "xmm11"),
// XMM12 = (29, "xmm12"),
// XMM13 = (30, "xmm13"),
// XMM14 = (31, "xmm14"),
// XMM15 = (32, "xmm15"),
//
// ST0 = (33, "st0"),
// ST1 = (34, "st1"),
// ST2 = (35, "st2"),
// ST3 = (36, "st3"),
// ST4 = (37, "st4"),
// ST5 = (38, "st5"),
// ST6 = (39, "st6"),
// ST7 = (40, "st7"),
//
// MM0 = (41, "mm0"),
// MM1 = (42, "mm1"),
// MM2 = (43, "mm2"),
// MM3 = (44, "mm3"),
// MM4 = (45, "mm4"),
// MM5 = (46, "mm5"),
// MM6 = (47, "mm6"),
// MM7 = (48, "mm7"),
//
// RFLAGS = (49, "rFLAGS"),
// ES = (50, "es"),
// CS = (51, "cs"),
// SS = (52, "ss"),
// DS = (53, "ds"),
// FS = (54, "fs"),
// GS = (55, "gs"),
//
// FS_BASE = (58, "fs.base"),
// GS_BASE = (59, "gs.base"),
//
// TR = (62, "tr"),
// LDTR = (63, "ldtr"),
// MXCSR = (64, "mxcsr"),
// FCW = (65, "fcw"),
// FSW = (66, "fsw"),
//
// XMM16 = (67, "xmm16"),
// XMM17 = (68, "xmm17"),
// XMM18 = (69, "xmm18"),
// XMM19 = (70, "xmm19"),
// XMM20 = (71, "xmm20"),
// XMM21 = (72, "xmm21"),
// XMM22 = (73, "xmm22"),
// XMM23 = (74, "xmm23"),
// XMM24 = (75, "xmm24"),
// XMM25 = (76, "xmm25"),
// XMM26 = (77, "xmm26"),
// XMM27 = (78, "xmm27"),
// XMM28 = (79, "xmm28"),
// XMM29 = (80, "xmm29"),
// XMM30 = (81, "xmm30"),
// XMM31 = (82, "xmm31"),
//
// K0 = (118, "k0"),
// K1 = (119, "k1"),
// K2 = (120, "k2"),
// K3 = (121, "k3"),
// K4 = (122, "k4"),
// K5 = (123, "k5"),
// K6 = (124, "k6"),
// K7 = (125, "k7"), | src/arch/x86_64/bits.zig |
const std = @import("std");
// The buffer needed for the hex values. This includes two spaces at the
// beginning, and the extra space in the middle.
const hex_size = 3 * 16 + 2;
const ascii_size = 16;
const HexBuf = std.BoundedArray(u8, hex_size);
const AsciiBuf = std.BoundedArray(u8, ascii_size);
// Convenience function to just print a bunch of stuff.
pub fn pdump(data: []const u8) !void {
try (try HexPrinter.init()).dump(data);
}
pub const HexPrinter = struct {
const Self = @This();
count: usize,
total_count: usize,
hex: HexBuf,
ascii: AsciiBuf,
fn init() !HexPrinter {
return Self{
.count = 0,
.total_count = 0,
.hex = try HexBuf.init(0),
.ascii = try AsciiBuf.init(0),
};
}
pub fn dump(self: *Self, data: []const u8) !void {
for (data) |ch| {
try self.addByte(ch);
}
try self.ship();
}
fn addByte(self: *Self, ch: u8) !void {
if (self.count == 16) {
try self.ship();
}
if (self.count == 8) {
try self.hex.append(' ');
}
var buf: [3]u8 = undefined;
const hex = try std.fmt.bufPrint(&buf, " {x:0>2}", .{ch});
try self.hex.appendSlice(hex);
const printable = if (' ' <= ch and ch <= '~') ch else '.';
try self.ascii.append(printable);
self.count += 1;
}
fn ship(self: *Self) !void {
if (self.count == 0)
return;
// TODO: Generalize the printer.
std.log.info("{x:0>6} {s:<49} |{s}|", .{ self.total_count, self.hex.slice(), self.ascii.slice() });
self.hex.len = 0;
self.ascii.len = 0;
self.total_count += 16;
self.count = 0;
}
};
pub fn main() !void {
var buf: [57]u8 = undefined;
for (buf) |*ch, i| {
ch.* = @truncate(u8, i);
}
var hp = try HexPrinter.init();
try hp.dump(&buf);
try hp.dump(&buf);
try pdump(&buf);
} | src/pdump.zig |
const std = @import("std");
const mem = std.mem;
const OtherNumber = @This();
allocator: *mem.Allocator,
array: []bool,
lo: u21 = 178,
hi: u21 = 127244,
pub fn init(allocator: *mem.Allocator) !OtherNumber {
var instance = OtherNumber{
.allocator = allocator,
.array = try allocator.alloc(bool, 127067),
};
mem.set(bool, instance.array, false);
var index: u21 = 0;
index = 0;
while (index <= 1) : (index += 1) {
instance.array[index] = true;
}
instance.array[7] = true;
index = 10;
while (index <= 12) : (index += 1) {
instance.array[index] = true;
}
index = 2370;
while (index <= 2375) : (index += 1) {
instance.array[index] = true;
}
index = 2752;
while (index <= 2757) : (index += 1) {
instance.array[index] = true;
}
index = 2878;
while (index <= 2880) : (index += 1) {
instance.array[index] = true;
}
index = 3014;
while (index <= 3020) : (index += 1) {
instance.array[index] = true;
}
index = 3238;
while (index <= 3244) : (index += 1) {
instance.array[index] = true;
}
index = 3262;
while (index <= 3270) : (index += 1) {
instance.array[index] = true;
}
index = 3704;
while (index <= 3713) : (index += 1) {
instance.array[index] = true;
}
index = 4791;
while (index <= 4810) : (index += 1) {
instance.array[index] = true;
}
index = 5950;
while (index <= 5959) : (index += 1) {
instance.array[index] = true;
}
instance.array[6440] = true;
instance.array[8126] = true;
index = 8130;
while (index <= 8135) : (index += 1) {
instance.array[index] = true;
}
index = 8142;
while (index <= 8151) : (index += 1) {
instance.array[index] = true;
}
index = 8350;
while (index <= 8365) : (index += 1) {
instance.array[index] = true;
}
instance.array[8407] = true;
index = 9134;
while (index <= 9193) : (index += 1) {
instance.array[index] = true;
}
index = 9272;
while (index <= 9293) : (index += 1) {
instance.array[index] = true;
}
index = 9924;
while (index <= 9953) : (index += 1) {
instance.array[index] = true;
}
instance.array[11339] = true;
index = 12512;
while (index <= 12515) : (index += 1) {
instance.array[index] = true;
}
index = 12654;
while (index <= 12663) : (index += 1) {
instance.array[index] = true;
}
index = 12694;
while (index <= 12701) : (index += 1) {
instance.array[index] = true;
}
index = 12703;
while (index <= 12717) : (index += 1) {
instance.array[index] = true;
}
index = 12750;
while (index <= 12759) : (index += 1) {
instance.array[index] = true;
}
index = 12799;
while (index <= 12813) : (index += 1) {
instance.array[index] = true;
}
index = 42878;
while (index <= 42883) : (index += 1) {
instance.array[index] = true;
}
index = 65621;
while (index <= 65665) : (index += 1) {
instance.array[index] = true;
}
index = 65731;
while (index <= 65734) : (index += 1) {
instance.array[index] = true;
}
index = 65752;
while (index <= 65753) : (index += 1) {
instance.array[index] = true;
}
index = 66095;
while (index <= 66121) : (index += 1) {
instance.array[index] = true;
}
index = 66158;
while (index <= 66161) : (index += 1) {
instance.array[index] = true;
}
index = 67494;
while (index <= 67501) : (index += 1) {
instance.array[index] = true;
}
index = 67527;
while (index <= 67533) : (index += 1) {
instance.array[index] = true;
}
index = 67573;
while (index <= 67581) : (index += 1) {
instance.array[index] = true;
}
index = 67657;
while (index <= 67661) : (index += 1) {
instance.array[index] = true;
}
index = 67684;
while (index <= 67689) : (index += 1) {
instance.array[index] = true;
}
index = 67850;
while (index <= 67851) : (index += 1) {
instance.array[index] = true;
}
index = 67854;
while (index <= 67869) : (index += 1) {
instance.array[index] = true;
}
index = 67872;
while (index <= 67917) : (index += 1) {
instance.array[index] = true;
}
index = 67982;
while (index <= 67990) : (index += 1) {
instance.array[index] = true;
}
index = 68043;
while (index <= 68044) : (index += 1) {
instance.array[index] = true;
}
index = 68075;
while (index <= 68077) : (index += 1) {
instance.array[index] = true;
}
index = 68153;
while (index <= 68157) : (index += 1) {
instance.array[index] = true;
}
index = 68262;
while (index <= 68269) : (index += 1) {
instance.array[index] = true;
}
index = 68294;
while (index <= 68301) : (index += 1) {
instance.array[index] = true;
}
index = 68343;
while (index <= 68349) : (index += 1) {
instance.array[index] = true;
}
index = 68680;
while (index <= 68685) : (index += 1) {
instance.array[index] = true;
}
index = 69038;
while (index <= 69068) : (index += 1) {
instance.array[index] = true;
}
index = 69227;
while (index <= 69236) : (index += 1) {
instance.array[index] = true;
}
index = 69279;
while (index <= 69282) : (index += 1) {
instance.array[index] = true;
}
index = 69395;
while (index <= 69401) : (index += 1) {
instance.array[index] = true;
}
index = 69536;
while (index <= 69555) : (index += 1) {
instance.array[index] = true;
}
index = 69935;
while (index <= 69954) : (index += 1) {
instance.array[index] = true;
}
index = 71304;
while (index <= 71305) : (index += 1) {
instance.array[index] = true;
}
index = 71736;
while (index <= 71744) : (index += 1) {
instance.array[index] = true;
}
index = 72616;
while (index <= 72634) : (index += 1) {
instance.array[index] = true;
}
index = 73486;
while (index <= 73506) : (index += 1) {
instance.array[index] = true;
}
index = 92841;
while (index <= 92847) : (index += 1) {
instance.array[index] = true;
}
index = 93646;
while (index <= 93668) : (index += 1) {
instance.array[index] = true;
}
index = 119342;
while (index <= 119361) : (index += 1) {
instance.array[index] = true;
}
index = 119470;
while (index <= 119494) : (index += 1) {
instance.array[index] = true;
}
index = 124949;
while (index <= 124957) : (index += 1) {
instance.array[index] = true;
}
index = 125887;
while (index <= 125945) : (index += 1) {
instance.array[index] = true;
}
index = 125947;
while (index <= 125949) : (index += 1) {
instance.array[index] = true;
}
index = 125951;
while (index <= 125954) : (index += 1) {
instance.array[index] = true;
}
index = 126031;
while (index <= 126075) : (index += 1) {
instance.array[index] = true;
}
index = 126077;
while (index <= 126091) : (index += 1) {
instance.array[index] = true;
}
index = 127054;
while (index <= 127066) : (index += 1) {
instance.array[index] = true;
}
// Placeholder: 0. Struct name, 1. Code point kind
return instance;
}
pub fn deinit(self: *OtherNumber) void {
self.allocator.free(self.array);
}
// isOtherNumber checks if cp is of the kind Other_Number.
pub fn isOtherNumber(self: OtherNumber, cp: u21) bool {
if (cp < self.lo or cp > self.hi) return false;
const index = cp - self.lo;
return if (index >= self.array.len) false else self.array[index];
} | src/components/autogen/DerivedGeneralCategory/OtherNumber.zig |
//--------------------------------------------------------------------------------
// Section: Types (9)
//--------------------------------------------------------------------------------
// TODO: this type is limited to platform 'windows8.0'
const IID_IWebApplicationScriptEvents_Value = Guid.initString("7c3f6998-1567-4bba-b52b-48d32141d613");
pub const IID_IWebApplicationScriptEvents = &IID_IWebApplicationScriptEvents_Value;
pub const IWebApplicationScriptEvents = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
BeforeScriptExecute: fn(
self: *const IWebApplicationScriptEvents,
htmlWindow: ?*IHTMLWindow2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ScriptError: fn(
self: *const IWebApplicationScriptEvents,
htmlWindow: ?*IHTMLWindow2,
scriptError: ?*IActiveScriptError,
url: ?[*:0]const u16,
errorHandled: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWebApplicationScriptEvents_BeforeScriptExecute(self: *const T, htmlWindow: ?*IHTMLWindow2) callconv(.Inline) HRESULT {
return @ptrCast(*const IWebApplicationScriptEvents.VTable, self.vtable).BeforeScriptExecute(@ptrCast(*const IWebApplicationScriptEvents, self), htmlWindow);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWebApplicationScriptEvents_ScriptError(self: *const T, htmlWindow: ?*IHTMLWindow2, scriptError: ?*IActiveScriptError, url: ?[*:0]const u16, errorHandled: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IWebApplicationScriptEvents.VTable, self.vtable).ScriptError(@ptrCast(*const IWebApplicationScriptEvents, self), htmlWindow, scriptError, url, errorHandled);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IWebApplicationNavigationEvents_Value = Guid.initString("c22615d2-d318-4da2-8422-1fcaf77b10e4");
pub const IID_IWebApplicationNavigationEvents = &IID_IWebApplicationNavigationEvents_Value;
pub const IWebApplicationNavigationEvents = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
BeforeNavigate: fn(
self: *const IWebApplicationNavigationEvents,
htmlWindow: ?*IHTMLWindow2,
url: ?[*:0]const u16,
navigationFlags: u32,
targetFrameName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
NavigateComplete: fn(
self: *const IWebApplicationNavigationEvents,
htmlWindow: ?*IHTMLWindow2,
url: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
NavigateError: fn(
self: *const IWebApplicationNavigationEvents,
htmlWindow: ?*IHTMLWindow2,
url: ?[*:0]const u16,
targetFrameName: ?[*:0]const u16,
statusCode: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DocumentComplete: fn(
self: *const IWebApplicationNavigationEvents,
htmlWindow: ?*IHTMLWindow2,
url: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DownloadBegin: fn(
self: *const IWebApplicationNavigationEvents,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DownloadComplete: fn(
self: *const IWebApplicationNavigationEvents,
) 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 IWebApplicationNavigationEvents_BeforeNavigate(self: *const T, htmlWindow: ?*IHTMLWindow2, url: ?[*:0]const u16, navigationFlags: u32, targetFrameName: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWebApplicationNavigationEvents.VTable, self.vtable).BeforeNavigate(@ptrCast(*const IWebApplicationNavigationEvents, self), htmlWindow, url, navigationFlags, targetFrameName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWebApplicationNavigationEvents_NavigateComplete(self: *const T, htmlWindow: ?*IHTMLWindow2, url: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWebApplicationNavigationEvents.VTable, self.vtable).NavigateComplete(@ptrCast(*const IWebApplicationNavigationEvents, self), htmlWindow, url);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWebApplicationNavigationEvents_NavigateError(self: *const T, htmlWindow: ?*IHTMLWindow2, url: ?[*:0]const u16, targetFrameName: ?[*:0]const u16, statusCode: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWebApplicationNavigationEvents.VTable, self.vtable).NavigateError(@ptrCast(*const IWebApplicationNavigationEvents, self), htmlWindow, url, targetFrameName, statusCode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWebApplicationNavigationEvents_DocumentComplete(self: *const T, htmlWindow: ?*IHTMLWindow2, url: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWebApplicationNavigationEvents.VTable, self.vtable).DocumentComplete(@ptrCast(*const IWebApplicationNavigationEvents, self), htmlWindow, url);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWebApplicationNavigationEvents_DownloadBegin(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWebApplicationNavigationEvents.VTable, self.vtable).DownloadBegin(@ptrCast(*const IWebApplicationNavigationEvents, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWebApplicationNavigationEvents_DownloadComplete(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWebApplicationNavigationEvents.VTable, self.vtable).DownloadComplete(@ptrCast(*const IWebApplicationNavigationEvents, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IWebApplicationUIEvents_Value = Guid.initString("5b2b3f99-328c-41d5-a6f7-7483ed8e71dd");
pub const IID_IWebApplicationUIEvents = &IID_IWebApplicationUIEvents_Value;
pub const IWebApplicationUIEvents = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SecurityProblem: fn(
self: *const IWebApplicationUIEvents,
securityProblem: u32,
result: ?*HRESULT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWebApplicationUIEvents_SecurityProblem(self: *const T, securityProblem: u32, result: ?*HRESULT) callconv(.Inline) HRESULT {
return @ptrCast(*const IWebApplicationUIEvents.VTable, self.vtable).SecurityProblem(@ptrCast(*const IWebApplicationUIEvents, self), securityProblem, result);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IWebApplicationUpdateEvents_Value = Guid.initString("3e59e6b7-c652-4daf-ad5e-16feb350cde3");
pub const IID_IWebApplicationUpdateEvents = &IID_IWebApplicationUpdateEvents_Value;
pub const IWebApplicationUpdateEvents = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
OnPaint: fn(
self: *const IWebApplicationUpdateEvents,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
OnCssChanged: fn(
self: *const IWebApplicationUpdateEvents,
) 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 IWebApplicationUpdateEvents_OnPaint(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWebApplicationUpdateEvents.VTable, self.vtable).OnPaint(@ptrCast(*const IWebApplicationUpdateEvents, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWebApplicationUpdateEvents_OnCssChanged(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWebApplicationUpdateEvents.VTable, self.vtable).OnCssChanged(@ptrCast(*const IWebApplicationUpdateEvents, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IWebApplicationHost_Value = Guid.initString("cecbd2c3-a3a5-4749-9681-20e9161c6794");
pub const IID_IWebApplicationHost = &IID_IWebApplicationHost_Value;
pub const IWebApplicationHost = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_HWND: fn(
self: *const IWebApplicationHost,
hwnd: ?*?HWND,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Document: fn(
self: *const IWebApplicationHost,
htmlDocument: ?*?*IHTMLDocument2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Refresh: fn(
self: *const IWebApplicationHost,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Advise: fn(
self: *const IWebApplicationHost,
interfaceId: ?*const Guid,
callback: ?*IUnknown,
cookie: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Unadvise: fn(
self: *const IWebApplicationHost,
cookie: 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 IWebApplicationHost_get_HWND(self: *const T, hwnd: ?*?HWND) callconv(.Inline) HRESULT {
return @ptrCast(*const IWebApplicationHost.VTable, self.vtable).get_HWND(@ptrCast(*const IWebApplicationHost, self), hwnd);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWebApplicationHost_get_Document(self: *const T, htmlDocument: ?*?*IHTMLDocument2) callconv(.Inline) HRESULT {
return @ptrCast(*const IWebApplicationHost.VTable, self.vtable).get_Document(@ptrCast(*const IWebApplicationHost, self), htmlDocument);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWebApplicationHost_Refresh(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWebApplicationHost.VTable, self.vtable).Refresh(@ptrCast(*const IWebApplicationHost, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWebApplicationHost_Advise(self: *const T, interfaceId: ?*const Guid, callback: ?*IUnknown, cookie: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWebApplicationHost.VTable, self.vtable).Advise(@ptrCast(*const IWebApplicationHost, self), interfaceId, callback, cookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWebApplicationHost_Unadvise(self: *const T, cookie: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWebApplicationHost.VTable, self.vtable).Unadvise(@ptrCast(*const IWebApplicationHost, self), cookie);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IWebApplicationActivation_Value = Guid.initString("bcdcd0de-330e-481b-b843-4898a6a8ebac");
pub const IID_IWebApplicationActivation = &IID_IWebApplicationActivation_Value;
pub const IWebApplicationActivation = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
CancelPendingActivation: fn(
self: *const IWebApplicationActivation,
) 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 IWebApplicationActivation_CancelPendingActivation(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWebApplicationActivation.VTable, self.vtable).CancelPendingActivation(@ptrCast(*const IWebApplicationActivation, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IWebApplicationAuthoringMode_Value = Guid.initString("720aea93-1964-4db0-b005-29eb9e2b18a9");
pub const IID_IWebApplicationAuthoringMode = &IID_IWebApplicationAuthoringMode_Value;
pub const IWebApplicationAuthoringMode = extern struct {
pub const VTable = extern struct {
base: IServiceProvider.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_AuthoringClientBinary: fn(
self: *const IWebApplicationAuthoringMode,
designModeDllPath: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IServiceProvider.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWebApplicationAuthoringMode_get_AuthoringClientBinary(self: *const T, designModeDllPath: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWebApplicationAuthoringMode.VTable, self.vtable).get_AuthoringClientBinary(@ptrCast(*const IWebApplicationAuthoringMode, self), designModeDllPath);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const RegisterAuthoringClientFunctionType = fn(
authoringModeObject: ?*IWebApplicationAuthoringMode,
host: ?*IWebApplicationHost,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const UnregisterAuthoringClientFunctionType = fn(
host: ?*IWebApplicationHost,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
//--------------------------------------------------------------------------------
// Section: Functions (0)
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (0)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../../../zig.zig").unicode_mode) {
.ansi => struct {
},
.wide => struct {
},
.unspecified => if (@import("builtin").is_test) struct {
} else struct {
},
};
//--------------------------------------------------------------------------------
// Section: Imports (11)
//--------------------------------------------------------------------------------
const Guid = @import("../../../zig.zig").Guid;
const BOOL = @import("../../../foundation.zig").BOOL;
const BSTR = @import("../../../foundation.zig").BSTR;
const HRESULT = @import("../../../foundation.zig").HRESULT;
const HWND = @import("../../../foundation.zig").HWND;
const IActiveScriptError = @import("../../../system/diagnostics/debug.zig").IActiveScriptError;
const IHTMLDocument2 = @import("../../../web/ms_html.zig").IHTMLDocument2;
const IHTMLWindow2 = @import("../../../web/ms_html.zig").IHTMLWindow2;
const IServiceProvider = @import("../../../system/com.zig").IServiceProvider;
const IUnknown = @import("../../../system/com.zig").IUnknown;
const PWSTR = @import("../../../foundation.zig").PWSTR;
test {
// The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476
if (@hasDecl(@This(), "RegisterAuthoringClientFunctionType")) { _ = RegisterAuthoringClientFunctionType; }
if (@hasDecl(@This(), "UnregisterAuthoringClientFunctionType")) { _ = UnregisterAuthoringClientFunctionType; }
@setEvalBranchQuota(
@import("std").meta.declarations(@This()).len * 3
);
// reference all the pub declarations
if (!@import("builtin").is_test) return;
inline for (@import("std").meta.declarations(@This())) |decl| {
if (decl.is_pub) {
_ = decl;
}
}
} | win32/system/diagnostics/debug/web_app.zig |
const std = @import("std");
const with_trace = true;
const assert = std.debug.assert;
fn trace(comptime fmt: []const u8, args: anytype) void {
if (with_trace) std.debug.print(fmt, args);
}
const Replacement = struct {
from: []const u8,
to: []const u8,
};
fn parse_line(line: []const u8) ?Replacement {
// H => HO
const trimmed = std.mem.trim(u8, line, " \n\r\t");
var sep = std.mem.indexOf(u8, trimmed, " => ");
if (sep) |s| {
return Replacement{ .from = line[0..s], .to = line[s + 4 ..] };
} else {
return null;
}
}
fn compute_mutation(molecule: []const u8, rule: Replacement, startindex: *usize, allocator: std.mem.Allocator) !?[]const u8 {
var idx = std.mem.indexOfPos(u8, molecule, startindex.*, rule.from);
if (idx) |i| {
startindex.* = i + 1;
const m = try allocator.alloc(u8, molecule.len + rule.to.len - rule.from.len);
std.mem.copy(u8, m[0..i], molecule[0..i]);
std.mem.copy(u8, m[i .. i + rule.to.len], rule.to);
std.mem.copy(u8, m[i + rule.to.len ..], molecule[i + rule.from.len ..]);
return m;
} else {
return null;
}
}
pub fn main() anyerror!void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
const limit = 1 * 1024 * 1024 * 1024;
const text = try std.fs.cwd().readFileAlloc(allocator, "day19.txt", limit);
const molecule = "CRnCaCaCaSiRnBPTiMgArSiRnSiRnMgArSiRnCaFArTiTiBSiThFYCaFArCaCaSiThCaPBSiThSiThCaCaPTiRnPBSiThRnFArArCaCaSiThCaSiThSiRnMgArCaPTiBPRnFArSiThCaSiRnFArBCaSiRnCaPRnFArPMgYCaFArCaPTiTiTiBPBSiThCaPTiBPBSiRnFArBPBSiRnCaFArBPRnSiRnFArRnSiRnBFArCaFArCaCaCaSiThSiThCaCaPBPTiTiRnFArCaPTiBSiAlArPBCaCaCaCaCaSiRnMgArCaSiThFArThCaSiThCaSiRnCaFYCaSiRnFYFArFArCaSiRnFYFArCaSiRnBPMgArSiThPRnFArCaSiRnFArTiRnSiRnFYFArCaSiRnBFArCaSiRnTiMgArSiThCaSiThCaFArPRnFArSiRnFArTiTiTiTiBCaCaSiRnCaCaFYFArSiThCaPTiBPTiBCaSiThSiRnMgArCaF";
var rules_mem: [1000]Replacement = undefined;
var rules = rules_mem[0..0];
{
var it = std.mem.tokenize(u8, text, "\n");
while (it.next()) |line| {
const newrule = parse_line(line);
if (newrule) |r| {
trace("rule= {} -> {}\n", r.from, r.to);
rules = rules_mem[0 .. rules.len + 1];
rules[rules.len - 1] = r;
}
}
}
var sets = [_]std.StringHashMap(bool){ std.StringHashMap(bool).init(allocator), std.StringHashMap(bool).init(allocator) };
defer sets[0].deinit();
defer sets[1].deinit();
try sets[0].ensureTotalCapacity(100000);
try sets[1].ensureTotalCapacity(100000);
var steps: u32 = 0;
_ = try sets[0].put("e", true);
while (true) {
var minlen: usize = 99999999;
var maxlen: usize = 0;
steps += 1;
const set = &sets[steps % 2];
set.clear();
var prevmolecules = sets[1 - steps % 2].iterator();
while (prevmolecules.next()) |it| {
const base = it.key;
for (rules) |r| {
var startindex: usize = 0;
while (try compute_mutation(base, r, &startindex, allocator)) |m| {
minlen = if (m.len < minlen) m.len else minlen;
maxlen = if (m.len > maxlen) m.len else maxlen;
_ = try set.put(m, true);
}
}
}
trace("step{}: {} mutations {} .. {}\n", steps, set.count(), minlen, maxlen);
if (set.get(molecule)) |m| {
break;
}
}
const out = std.io.getStdOut().writer();
try out.print("ans = {}\n", steps);
// return error.SolutionNotFound;
} | 2015/day19.explose.zig |
const std = @import("std");
const assert = std.debug.assert;
const expect = std.testing.expect;
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const fixedBufferStream = std.io.fixedBufferStream;
const countingOutStream = std.io.countingOutStream;
const ExecError = error{
InvalidOpcode,
InvalidParamMode,
};
fn opcode(ins: i32) i32 {
return @rem(ins, 100);
}
test "opcode extraction" {
assert(opcode(1002) == 2);
}
fn paramMode(ins: i32, pos: i32) i32 {
var div: i32 = 100; // Mode of parameter 0 is in digit 3
var i: i32 = 0;
while (i < pos) : (i += 1) {
div *= 10;
}
return @rem(@divTrunc(ins, div), 10);
}
test "param mode extraction" {
assert(paramMode(1002, 0) == 0);
assert(paramMode(1002, 1) == 1);
assert(paramMode(1002, 2) == 0);
}
fn getParam(intcode: []i32, pos: usize, n: usize, mode: i32) !i32 {
return switch (mode) {
0 => intcode[@intCast(usize, intcode[pos + 1 + n])],
1 => intcode[pos + 1 + n],
else => return error.InvalidParamMode,
};
}
fn exec(intcode: []i32, input_stream: anytype, output_stream: anytype) !void {
var pos: usize = 0;
while (true) {
const instr = intcode[pos];
switch (opcode(instr)) {
99 => break,
1 => {
const val_x = try getParam(intcode, pos, 0, paramMode(instr, 0));
const val_y = try getParam(intcode, pos, 1, paramMode(instr, 1));
const pos_result = @intCast(usize, intcode[pos + 3]);
intcode[pos_result] = val_x + val_y;
pos += 4;
},
2 => {
const val_x = try getParam(intcode, pos, 0, paramMode(instr, 0));
const val_y = try getParam(intcode, pos, 1, paramMode(instr, 1));
const pos_result = @intCast(usize, intcode[pos + 3]);
intcode[pos_result] = val_x * val_y;
pos += 4;
},
3 => {
const pos_x = @intCast(usize, intcode[pos + 1]);
var buf: [1024]u8 = undefined;
const line = (try input_stream.readUntilDelimiterOrEof(&buf, '\n')) orelse "";
const val = try std.fmt.parseInt(i32, line, 10);
intcode[pos_x] = val;
pos += 2;
},
4 => {
const val_x = try getParam(intcode, pos, 0, paramMode(instr, 0));
try output_stream.print("{}\n", .{val_x});
pos += 2;
},
5 => {
const val_x = try getParam(intcode, pos, 0, paramMode(instr, 0));
if (val_x != 0) {
const val_y = try getParam(intcode, pos, 1, paramMode(instr, 1));
pos = @intCast(usize, val_y);
} else {
pos += 3;
}
},
6 => {
const val_x = try getParam(intcode, pos, 0, paramMode(instr, 0));
if (val_x == 0) {
const val_y = try getParam(intcode, pos, 1, paramMode(instr, 1));
pos = @intCast(usize, val_y);
} else {
pos += 3;
}
},
7 => {
const val_x = try getParam(intcode, pos, 0, paramMode(instr, 0));
const val_y = try getParam(intcode, pos, 1, paramMode(instr, 1));
const pos_result = @intCast(usize, intcode[pos + 3]);
intcode[pos_result] = if (val_x < val_y) 1 else 0;
pos += 4;
},
8 => {
const val_x = try getParam(intcode, pos, 0, paramMode(instr, 0));
const val_y = try getParam(intcode, pos, 1, paramMode(instr, 1));
const pos_result = @intCast(usize, intcode[pos + 3]);
intcode[pos_result] = if (val_x == val_y) 1 else 0;
pos += 4;
},
else => {
std.debug.warn("pos: {}, instr: {}\n", .{ pos, intcode[pos] });
return error.InvalidOpcode;
},
}
}
}
test "test exec 1" {
var intcode = [_]i32{ 1, 0, 0, 0, 99 };
var reader = fixedBufferStream("").reader();
try exec(&intcode, reader, std.io.null_writer);
assert(intcode[0] == 2);
}
test "test exec 2" {
var intcode = [_]i32{ 2, 3, 0, 3, 99 };
var reader = fixedBufferStream("").reader();
try exec(&intcode, reader, std.io.null_writer);
assert(intcode[3] == 6);
}
test "test exec 3" {
var intcode = [_]i32{ 2, 4, 4, 5, 99, 0 };
var reader = fixedBufferStream("").reader();
try exec(&intcode, reader, std.io.null_writer);
assert(intcode[5] == 9801);
}
test "test exec with different param mode" {
var intcode = [_]i32{ 1002, 4, 3, 4, 33 };
var reader = fixedBufferStream("").reader();
try exec(&intcode, reader, std.io.null_writer);
assert(intcode[4] == 99);
}
test "test exec with negative integers" {
var intcode = [_]i32{ 1101, 100, -1, 4, 0 };
var reader = fixedBufferStream("").reader();
try exec(&intcode, reader, std.io.null_writer);
assert(intcode[4] == 99);
}
test "test equal 1" {
var intcode = [_]i32{ 3, 9, 8, 9, 10, 9, 4, 9, 99, -1, 8 };
var output_buf: [32]u8 = undefined;
var reader = fixedBufferStream("8\n").reader();
var writer = fixedBufferStream(&output_buf).writer();
try exec(&intcode, reader, writer);
assert(std.mem.eql(u8, "1\n", output_buf[0..2]));
}
test "test equal 2" {
var intcode = [_]i32{ 3, 9, 8, 9, 10, 9, 4, 9, 99, -1, 8 };
var output_buf: [32]u8 = undefined;
var reader = fixedBufferStream("13\n").reader();
var writer = fixedBufferStream(&output_buf).writer();
try exec(&intcode, reader, writer);
assert(std.mem.eql(u8, "0\n", output_buf[0..2]));
}
test "test less than 1" {
var intcode = [_]i32{ 3, 9, 7, 9, 10, 9, 4, 9, 99, -1, 8 };
var output_buf: [32]u8 = undefined;
var reader = fixedBufferStream("5\n").reader();
var writer = fixedBufferStream(&output_buf).writer();
try exec(&intcode, reader, writer);
assert(std.mem.eql(u8, "1\n", output_buf[0..2]));
}
test "test less than 2" {
var intcode = [_]i32{ 3, 9, 7, 9, 10, 9, 4, 9, 99, -1, 8 };
var output_buf: [32]u8 = undefined;
var reader = fixedBufferStream("20\n").reader();
var writer = fixedBufferStream(&output_buf).writer();
try exec(&intcode, reader, writer);
assert(std.mem.eql(u8, "0\n", output_buf[0..2]));
}
test "test equal immediate" {
var intcode = [_]i32{ 3, 3, 1108, -1, 8, 3, 4, 3, 99 };
var output_buf: [32]u8 = undefined;
var reader = fixedBufferStream("8\n").reader();
var writer = fixedBufferStream(&output_buf).writer();
try exec(&intcode, reader, writer);
assert(std.mem.eql(u8, "1\n", output_buf[0..2]));
}
test "test less than immediate" {
var intcode = [_]i32{ 3, 3, 1107, -1, 8, 3, 4, 3, 99 };
var output_buf: [32]u8 = undefined;
var reader = fixedBufferStream("3\n").reader();
var writer = fixedBufferStream(&output_buf).writer();
try exec(&intcode, reader, writer);
assert(std.mem.eql(u8, "1\n", output_buf[0..2]));
}
pub const Amp = []i32;
fn runAmp(intcode: Amp, phase: i32, input: i32) !i32 {
var input_buf: [32]u8 = undefined;
const input_slice = try std.fmt.bufPrint(&input_buf, "{}\n{}\n", .{ phase, input });
var input_stream = fixedBufferStream(input_slice).reader();
var output_buf: [32]u8 = undefined;
var output_stream_internal = fixedBufferStream(&output_buf).writer();
var output_stream = countingOutStream(output_stream_internal);
try exec(intcode, input_stream, output_stream.writer());
return try std.fmt.parseInt(i32, output_buf[0 .. output_stream.bytes_written - 1], 10);
}
fn runAmps(amps: []Amp, phase_sequence: []i32) !i32 {
var x: i32 = 0;
for (amps) |amp, i| {
x = try runAmp(amp, phase_sequence[i], x);
}
return x;
}
test "run amps" {
const amp = [_]i32{ 3, 15, 3, 16, 1002, 16, 10, 16, 1, 16, 15, 15, 4, 15, 99, 0, 0 };
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = &arena.allocator;
defer arena.deinit();
var amps: [5]Amp = undefined;
for (amps) |*a| {
a.* = try std.mem.dupe(allocator, i32, &);
}
var phase_sequence = [_]i32{ 4, 3, 2, 1, 0 };
assert((try runAmps(&s, &phase_sequence)) == 43210);
}
const PermutationError = std.mem.Allocator.Error;
fn permutations(comptime T: type, alloc: *Allocator, options: []T) PermutationError!ArrayList(ArrayList(T)) {
var result = ArrayList(ArrayList(T)).init(alloc);
if (options.len < 1)
try result.append(ArrayList(T).init(alloc));
for (options) |opt, i| {
var cp = try std.mem.dupe(alloc, T, options);
var remaining = ArrayList(T).fromOwnedSlice(alloc, cp);
_ = remaining.orderedRemove(i);
for ((try permutations(T, alloc, remaining.items)).items) |*p| {
try p.insert(0, opt);
try result.append(p.*);
}
}
return result;
}
test "empty permutation" {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = &arena.allocator;
defer arena.deinit();
var options = [_]u8{};
const perm = try permutations(u8, allocator, &options);
assert(perm.items.len == 1);
}
test "permutation with 2 elements" {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = &arena.allocator;
defer arena.deinit();
var options = [_]u8{ 0, 1 };
const perm = try permutations(u8, allocator, &options);
assert(perm.items.len == 2);
}
test "permutation with 4 elements" {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = &arena.allocator;
defer arena.deinit();
var options = [_]u8{ 0, 1, 2, 3 };
const perm = try permutations(u8, allocator, &options);
assert(perm.items.len == 24);
}
fn findMaxOutput(alloc: *Allocator, amps_orig: []const Amp) !i32 {
// Duplicate the amps
var amps = try std.mem.dupe(alloc, Amp, amps_orig);
for (amps) |*a, i| {
a.* = try std.mem.dupe(alloc, i32, amps_orig[i]);
}
// free the duplicates later
defer {
for (amps) |a|
alloc.free(a);
alloc.free(amps);
}
// Iterate through permutations
var phases = [_]i32{ 0, 1, 2, 3, 4 };
var max_perm: ?[]i32 = null;
var max_output: ?i32 = null;
for ((try permutations(i32, alloc, &phases)).items) |perm| {
// reset amps intcode
for (amps) |*a, i| {
std.mem.copy(i32, a.*, amps_orig[i]);
}
// run
const output = try runAmps(amps, perm.items);
if (max_output) |max| {
if (output > max) {
max_perm = perm.items;
max_output = output;
}
} else {
max_perm = perm.items;
max_output = output;
}
}
return max_output orelse return error.NoPermutations;
}
test "max output 1" {
const amp = [_]i32{ 3, 15, 3, 16, 1002, 16, 10, 16, 1, 16, 15, 15, 4, 15, 99, 0, 0 };
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = &arena.allocator;
defer arena.deinit();
var amps: [5]Amp = undefined;
for (amps) |*a| {
a.* = try std.mem.dupe(allocator, i32, &);
}
const output = try findMaxOutput(allocator, &s);
const expected_output: i32 = 43210;
expect(output == expected_output);
}
test "max output 2" {
const amp = [_]i32{
3, 23, 3, 24, 1002, 24, 10, 24, 1002, 23, -1, 23,
101, 5, 23, 23, 1, 24, 23, 23, 4, 23, 99, 0,
0,
};
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = &arena.allocator;
defer arena.deinit();
var amps: [5]Amp = undefined;
for (amps) |*a| {
a.* = try std.mem.dupe(allocator, i32, &);
}
const output = try findMaxOutput(allocator, &s);
const expected_output: i32 = 54321;
expect(output == expected_output);
}
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("input07.txt", .{});
var input_stream = input_file.reader();
var buf: [1024]u8 = undefined;
var ints = std.ArrayList(i32).init(allocator);
// read amp intcode into an int arraylist
while (try input_stream.readUntilDelimiterOrEof(&buf, ',')) |item| {
try ints.append(std.fmt.parseInt(i32, item, 10) catch 0);
}
// duplicate amps 5 times
var amps: [5]Amp = undefined;
for (amps) |*a| {
a.* = try std.mem.dupe(allocator, i32, ints.items);
}
// try combinations of phase sequences
std.debug.warn("max achievable output: {}\n", .{try findMaxOutput(allocator, &s)});
} | zig/07.zig |
const std = @import("std");
const tht = @import("tenhourtime.zig");
const c = @cImport({
@cInclude("libxfce4panel/xfce-panel-plugin.h");
});
const OverflowError = error{OverflowError};
const EachTick = extern struct {
label: [*c]c.GtkLabel,
previi: u8,
pub const Error = OverflowError;
fn update(anydata: c.gpointer) callconv(.C) c_int {
var data: *align(1) EachTick = @ptrCast(*align(1) EachTick, anydata);
var timeNum = tht.formatTime(tht.tenHourTime(tht.msSinceDayStart(tht.getTime())));
timeNum.qm = 0;
if (data.previi != timeNum.ii) {
data.previi = timeNum.ii;
const alloc = std.heap.c_allocator;
const formatted = std.fmt.allocPrint0(alloc, "{}", .{timeNum}) catch @panic("oom");
defer alloc.free(formatted);
c.gtk_label_set_text(data.label, formatted.ptr);
}
return 1;
}
};
pub fn constructor(plugin: [*c]c.XfcePanelPlugin) void {
var label = c.gtk_label_new(@as([]const u8, "...").ptr);
c.gtk_container_add(GTK_CONTAINER(plugin), label);
c.gtk_widget_show_all(label);
var alloc = std.heap.c_allocator;
var updateData: *EachTick = alloc.create(EachTick) catch @panic("oom");
updateData.* = .{
.label = GTK_LABEL(label),
.previi = 0,
};
std.debug.warn("panel started\n", .{});
var result = c.g_timeout_add(10, EachTick.update, updateData);
}
// ===== MACRO EXPANSION FOR c.GTK_LABEL, c.GTK_CONTAINER
const GTK_LABEL = gtkCast(.Label, .label);
const GTK_CONTAINER = gtkCast(.Container, .container);
fn gtkCast(comptime name: var, comptime nameLower: var) fn f(view: var) *@field(c, "Gtk" ++ @tagName(name)) {
return struct {
fn f(view: var) *@field(c, "Gtk" ++ @tagName(name)) {
if (@typeInfo(@TypeOf(view)) != .Pointer) @compileError("expected pointer");
return @ptrCast(
*@field(c, "Gtk" ++ @tagName(name)),
c.g_type_check_instance_cast(@ptrCast(*c.GTypeInstance, view), @field(c, "gtk_" ++ @tagName(nameLower) ++ "_get_type")()),
);
}
}.f;
}
// ========== MACRO EXPANSION FOR XFCE_PANEL_PLUGIN_REGISTER ==========
// even if zig could parse the macro, how would it add two functions?
pub fn xfce_panel_module_realize(arg_xpp: [*c]c.XfcePanelPlugin) callconv(.C) void {
var xpp = arg_xpp;
while (true) {
if ((blk: {
var __inst: [*c]c.GTypeInstance = @ptrCast([*c]c.GTypeInstance, @alignCast(@alignOf(c.GTypeInstance), (xpp)));
var __t: c.GType = (c.xfce_panel_plugin_get_type());
var __r: c.gboolean = undefined;
if (!(__inst != null)) __r = (@as(c_int, 0)) else if ((__inst.*.g_class != null) and (__inst.*.g_class.*.g_type == __t)) __r = @boolToInt((!((@as(c_int, 0)) != 0))) else __r = c.g_type_check_instance_is_a(__inst, __t);
break :blk __r;
}) != 0) {} else {
c.g_return_if_fail_warning((@intToPtr([*c]c.gchar, @as(c_int, 0))), (("xfce_panel_module_realize")), "XFCE_IS_PANEL_PLUGIN (xpp)");
return;
}
if (!(@as(c_int, 0) != 0)) break;
}
_ = c.g_signal_handlers_disconnect_matched(@ptrCast(c.gpointer, (@ptrCast([*c]c.GObject, @alignCast(@alignOf(c.GObject), c.g_type_check_instance_cast(@ptrCast([*c]c.GTypeInstance, @alignCast(@alignOf(c.GTypeInstance), (xpp))), (@bitCast(c.GType, @as(c_long, ((@as(c_int, 20)) << @intCast(@import("std").math.Log2Int(c_int), (@as(c_int, 2)))))))))))), @intToEnum(c.GSignalMatchType, (c.G_SIGNAL_MATCH_FUNC | c.G_SIGNAL_MATCH_DATA)), @bitCast(c.guint, @as(c_int, 0)), @bitCast(c.GQuark, @as(c_int, 0)), null, @ptrCast(c.gpointer, @intToPtr(c.gpointer, @ptrToInt((@ptrCast(c.GCallback, @alignCast(@alignOf(fn () callconv(.C) void), (xfce_panel_module_realize))))))), (@intToPtr(?*c_void, @as(c_int, 0))));
constructor(xpp);
}
pub export fn xfce_panel_module_construct(arg_xpp_name: [*c]const c.gchar, arg_xpp_unique_id: c.gint, arg_xpp_display_name: [*c]const c.gchar, arg_xpp_comment: [*c]const c.gchar, arg_xpp_arguments: [*c][*c]c.gchar, arg_xpp_screen: ?*c.GdkScreen) [*c]c.XfcePanelPlugin {
var xpp_name = arg_xpp_name;
var xpp_unique_id = arg_xpp_unique_id;
var xpp_display_name = arg_xpp_display_name;
var xpp_comment = arg_xpp_comment;
var xpp_arguments = arg_xpp_arguments;
var xpp_screen = arg_xpp_screen;
var xpp: [*c]c.XfcePanelPlugin = null;
while (true) {
if ((blk: {
var __inst: [*c]c.GTypeInstance = @ptrCast([*c]c.GTypeInstance, @alignCast(@alignOf(c.GTypeInstance), (xpp_screen)));
var __t: c.GType = (c.gdk_screen_get_type());
var __r: c.gboolean = undefined;
if (!(__inst != null)) __r = (@as(c_int, 0)) else if ((__inst.*.g_class != null) and (__inst.*.g_class.*.g_type == __t)) __r = @boolToInt((!((@as(c_int, 0)) != 0))) else __r = c.g_type_check_instance_is_a(__inst, __t);
break :blk __r;
}) != 0) {} else {
c.g_return_if_fail_warning((@intToPtr([*c]c.gchar, @as(c_int, 0))), ("xfce_panel_module_construct"), "GDK_IS_SCREEN (xpp_screen)");
return null;
}
if (!(@as(c_int, 0) != 0)) break;
}
while (true) {
if ((xpp_name != @ptrCast([*c]const c.gchar, @alignCast(@alignOf(c.gchar), (@intToPtr(?*c_void, @as(c_int, 0)))))) and (xpp_unique_id != -@as(c_int, 1))) {} else {
c.g_return_if_fail_warning((@intToPtr([*c]c.gchar, @as(c_int, 0))), (("xfce_panel_module_construct")), "xpp_name != NULL && xpp_unique_id != -1");
return null;
}
if (!(@as(c_int, 0) != 0)) break;
}
{
xpp = @ptrCast([*c]c.XfcePanelPlugin, @alignCast(@alignOf(c.XfcePanelPlugin), c.g_object_new((c.xfce_panel_plugin_get_type()), "name", xpp_name, "unique-id", xpp_unique_id, "display-name", xpp_display_name, "comment", xpp_comment, "arguments", xpp_arguments, (@intToPtr(?*c_void, @as(c_int, 0))))));
_ = c.g_signal_connect_data(@ptrCast(c.gpointer, (@ptrCast([*c]c.GObject, @alignCast(@alignOf(c.GObject), c.g_type_check_instance_cast(@ptrCast([*c]c.GTypeInstance, @alignCast(@alignOf(c.GTypeInstance), (xpp))), (@bitCast(c.GType, @as(c_long, ((@as(c_int, 20)) << @intCast(@import("std").math.Log2Int(c_int), (@as(c_int, 2)))))))))))), "realize", (@ptrCast(c.GCallback, @alignCast(@alignOf(fn () callconv(.C) void), (xfce_panel_module_realize)))), (@intToPtr(?*c_void, @as(c_int, 0))), null, @intToEnum(c.GConnectFlags, c.G_CONNECT_AFTER));
}
return xpp;
} | src/panel.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const print = std.debug.print;
const data = @embedFile("data/day21.txt");
const EntriesList = std.ArrayList(Record);
const FoodSet = BitSet(200);
const AllerSet = BitSet(8);
const Record = struct {
foods: FoodSet = FoodSet.zeroes(),
allergs: AllerSet = AllerSet.zeroes(),
};
pub fn BitSet(comptime max_items: comptime_int) type {
const num_words = (max_items + 63) / 64;
const max_bit_index = @as(u6, max_items % 64);
const last_word_mask = @as(u64, (@as(u64, 1) << max_bit_index) - 1);
return struct {
const Self = @This();
words: [num_words]u64,
pub fn zeroes() Self {
return .{ .words = [_]u64{0} ** num_words };
}
pub fn ones() Self {
var result = Self{ .words = [_]u64{~@as(u64, 0)} ** num_words };
result.words[num_words-1] &= last_word_mask;
return result;
}
pub fn contains(self: Self, item: usize) bool {
assert(item < max_items);
const mask = @as(u64, 1) << @truncate(u6, item);
const word_index = item >> 6;
return (self.words[word_index] & mask) != 0;
}
pub fn set(self: *Self, item: usize, value: bool) void {
assert(item < max_items);
const mask = @as(u64, @boolToInt(value)) << @truncate(u6, item);
const word_index = item >> 6;
self.words[word_index] = (self.words[word_index] & ~mask) | mask;
}
pub fn count(a: Self) usize {
var total: usize = 0;
for (a.words) |word| {
total += @intCast(usize, @popCount(u64, word));
}
return total;
}
pub fn bitOr(a: Self, b: Self) Self {
var result: Self = undefined;
for (a.words) |av, i| {
result.words[i] = av | b.words[i];
}
return result;
}
pub fn bitAnd(a: Self, b: Self) Self {
var result: Self = undefined;
for (a.words) |av, i| {
result.words[i] = av & b.words[i];
}
return result;
}
pub fn bitAndNot(a: Self, b: Self) Self {
var result: Self = undefined;
for (a.words) |av, i| {
result.words[i] = av & ~b.words[i];
}
return result;
}
pub fn bitNot(a: Self) Self {
var result: Self = undefined;
for (a.words) |av, i| {
result.words[i] = ~av;
}
result.words[num_words-1] &= last_word_mask;
return result;
}
pub fn bitXor(a: Self, b: Self) Self {
var result: Self = undefined;
for (a.words) |av, i| {
result.words[i] = av ^ b.words[i];
}
return result;
}
pub fn iterator(self: *Self) Iterator {
return .{ .current_word = self.words[0], .set = self };
}
const Iterator = struct {
offset: usize = 0,
current_word: u64,
set: *Self,
pub fn next(self: *Iterator) ?usize {
while (true) {
const curr = self.current_word;
if (curr != 0) {
const remain = @ctz(u64, curr);
self.current_word = curr & (curr-1);
var result = remain + self.offset * 64;
if (result < max_items) return result;
self.current_word = 0;
return null;
}
if (self.offset >= num_words-1) return null;
self.offset += 1;
self.current_word = self.set.words[self.offset];
}
}
};
};
}
const StringMap = struct {
items: std.ArrayList([]const u8),
pub fn init(allocator: *Allocator) StringMap {
return .{
.items = std.ArrayList([]const u8).init(allocator),
};
}
pub fn deinit(self: *StringMap) void {
self.items.deinit();
self.* = undefined;
}
pub fn id(self: *StringMap, string: []const u8) !u32 {
for (self.items.items) |str, i| {
if (std.mem.eql(u8, str, string)) return @intCast(u32, i);
}
const next = self.items.items.len;
try self.items.append(string);
return @intCast(u32, next);
}
};
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 foods = StringMap.init(ally);
var allergs = StringMap.init(ally);
var result: usize = 0;
while (lines.next()) |line| {
if (line.len == 0) continue;
var rec = Record{};
var parts = std.mem.tokenize(line, " ),");
while (parts.next()) |item| {
if (std.mem.eql(u8, item, "(contains"))
break;
const id = try foods.id(item);
rec.foods.set(id, true);
}
while (parts.next()) |item| {
const id = try allergs.id(item);
rec.allergs.set(id, true);
}
try entries.append(rec);
}
print("Found {} foods and {} allergens in {} records\n", .{foods.items.items.len, allergs.items.items.len, entries.items.len});
var maybeAllergs = FoodSet.zeroes();
for (allergs.items.items) |aller, i| {
var maybeAller = FoodSet.ones();
for (entries.items) |rec| {
if (rec.allergs.contains(i)) {
maybeAller = maybeAller.bitAnd(rec.foods);
}
}
print("{} may be {} items:\n ", .{aller, maybeAller.count()});
var it = maybeAller.iterator();
while (it.next()) |fd| {
print("{} ", .{foods.items.items[fd]});
}
print("\n", .{});
maybeAllergs = maybeAllergs.bitOr(maybeAller);
}
print("{} items may be allergies:\n ", .{maybeAllergs.count()});
var it = maybeAllergs.iterator();
while (it.next()) |fd| {
print("{} ", .{foods.items.items[fd]});
}
print("\n", .{});
var total_non_allerg: usize = 0;
for (entries.items) |rec| {
var non_allerg = rec.foods.bitAndNot(maybeAllergs);
total_non_allerg += non_allerg.count();
}
print("Total non allerg: {}\n", .{total_non_allerg});
} | src/day21.zig |
const std = @import("std");
const assert = std.dbg.assert;
const math = std.math;
const epsilon : f32 = 0.00001;
pub const Vec3 = extern struct {
v: [3]f32,
pub inline fn init( x: f32, y : f32, z: f32 ) Vec3 {
return .{ .v = [_]f32{ x, y, z } };
}
pub inline fn initZero() Vec3 {
const static = struct {
const zero = init( 0.0, 0.0, 0.0 );
};
return static.zero;
}
pub inline fn checkZero( a:Vec3 ) bool {
const s = 0.0000001;
return ( (@fabs(a.v[0]) < s ) and (@fabs(a.v[1]) < s ) and (@fabs(a.v[2]) < s ) );
}
pub inline fn dot( a: Vec3, b: Vec3 ) f32 {
return a.v[0] * b.v[0] + a.v[1] * b.v[1] + a.v[2]*b.v[2];
}
pub inline fn cross( a: Vec3, b:Vec3 ) Vec3 {
return . {
.v = [_]f32{
a.v[1] * b.v[2] - a.v[2] * b.v[1],
a.v[2] * b.v[0] - a.v[0] * b.v[2],
a.v[0] * b.v[1] - a.v[1] * b.v[0]
},
};
}
pub inline fn add( a: Vec3, b: Vec3 ) Vec3 {
return .{ .v = [_]f32{ a.v[0] + b.v[0], a.v[1] + b.v[1], a.v[2]+b.v[2] }};
}
pub inline fn sub( a: Vec3, b: Vec3 ) Vec3 {
return .{ .v = [_]f32{ a.v[0] - b.v[0], a.v[1] - b.v[1], a.v[2]-b.v[2] }};
}
pub inline fn mul( a: Vec3, b: Vec3 ) Vec3 {
return .{ .v = [_]f32{ a.v[0]*b.v[0], a.v[1]*b.v[1], a.v[2]*b.v[2] }};
}
pub inline fn mul_s( a: Vec3, s: f32 ) Vec3 {
return .{ .v = [_]f32{ a.v[0]*s, a.v[1]*s, a.v[2]*s }};
}
pub inline fn length( a:Vec3 ) f32 {
return math.sqrt(dot(a, a ));
}
pub inline fn lengthSq( a: Vec3 ) f32 {
return dot(a, a);
}
pub inline fn normalize(a: Vec3) Vec3 {
const len = length(a);
// assert(!math.approxEq(f32, len, 0.0, epsilon));
const rcplen = 1.0 / len;
return .{ .v = [_]f32{ rcplen * a.v[0], rcplen * a.v[1], rcplen * a.v[2] } };
}
pub inline fn reflect( v : Vec3, n : Vec3 ) Vec3 {
return Vec3.sub( v, Vec3.mul_s( n, 2.0 * Vec3.dot( v, n ) ) );
}
pub inline fn refract( uv : Vec3, n : Vec3, etai_over_etat : f32 ) Vec3 {
const cos_theta = math.min( Vec3.dot( Vec3.mul_s( uv, -1.0), n ), 1.0 );
const r_out_perp = Vec3.mul_s( Vec3.add( Vec3.mul_s( n, cos_theta ), uv ), etai_over_etat );
const r_out_parallel_mag = -math.sqrt( math.fabs(1.0 - Vec3.lengthSq( r_out_perp ) ));
const r_out_parallel = Vec3.mul_s( n, r_out_parallel_mag );
return Vec3.add( r_out_perp, r_out_parallel );
}
}; | src/vecmath_j.zig |
const std = @import("std");
const Atomic = std.atomic.Atomic;
/// Multiple-Producer single-consumer struct.
/// It's safe to send between threads, but only one
/// thread should call pop()
pub fn Queue(comptime T: type) type {
return struct {
pub const Node = struct {
next: Atomic(?*Node) = Atomic(?*Node).init(null),
value: T = undefined,
};
allocator: std.mem.Allocator,
count: Atomic(usize) = Atomic(usize).init(0),
ptr: Atomic(u32) = Atomic(u32).init(1),
head: Atomic(?*Node) = Atomic(?*Node).init(null),
tail: *Node = undefined,
const Self = @This();
pub fn init(allocator: std.mem.Allocator) Self {
var node = allocator.create(Node) catch unreachable;
return .{
.allocator = allocator,
.head = Atomic(?*Node).init(node),
.tail = node,
};
}
pub fn deinit(self: *Self) void {
// free all items
while (self.tryPop()) |_| {}
self.allocator.destroy(self.tail);
}
pub fn len(self: *Self) usize {
return self.count.load(.Acquire);
}
/// Push a new value to the queue, its safe to call from any thread,
/// it doesn't block thread either.
pub fn push(self: *Self, v: T) void {
var new_node = self.allocator.create(Node) catch unreachable;
new_node.* = .{ .value = v };
// swap self.head with new_node
var prev = self.head.swap(new_node, .AcqRel) orelse self.tail;
// save new_node(pointer) on previous node
// so now prev.next -> new_node
prev.next.store(new_node, .Release);
// increase internal count
_ = self.count.fetchAdd(1, .Monotonic);
std.Thread.Futex.wake(&self.ptr, 1);
}
/// Tries to pops some value from queue, returns null if there are no values.
/// Should be called only from one thread. It doesn't block the thread.
pub fn tryPop(self: *Self) ?T {
if (self.count.load(.Acquire) < 1) {
return null;
}
var tail = self.tail;
var next = self.tail.next.load(.Acquire);
if (next) |next_nonnull| {
self.tail = next_nonnull;
var ret = next_nonnull.value;
self.allocator.destroy(tail);
// decrease internal count
_ = self.count.fetchSub(1, .Monotonic);
return ret;
}
return null;
}
/// Pops some value from queue, blocks until receives a value,
/// Should be called only from one thread.
pub fn pop(self: *Self) T {
if (self.tryPop()) |v| {
return v;
}
// wait
std.Thread.Futex.wait(&self.ptr, 1, null) catch {};
return self.tryPop().?;
}
/// Pops some value from queue, blocks until receives a value,
/// or timeout is reached. Should be called only from one thread.
pub fn popTimeout(self: *Self, timeout: u64) ?T {
if (self.tryPop()) |v| {
return v;
}
// wait, if there is timeout error, return null
std.Thread.Futex.wait(&self.ptr, 1, timeout) catch {
return null;
};
return self.tryPop();
}
};
}
test "mpsc" {
const TestQueue = Queue(usize);
var queue = TestQueue.init(std.testing.allocator);
defer queue.deinit();
queue.push(5);
queue.push(5);
queue.push(5);
var v = queue.tryPop();
try std.testing.expect(v.? == 5);
} | src/mpsc.zig |
const std = @import("std");
const json = @import("../json.zig");
const common = @import("common.zig");
const general = @import("general.zig");
const language_features = @import("language_features.zig");
/// Params of a response (result)
pub const ResponseParams = union(enum) {
none: void,
string: []const u8,
number: i64,
boolean: bool,
// General
initialize_result: general.InitializeResult,
// Language Features
completion: language_features.CompletionResult,
};
/// [Docs](https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#errorCodes)
pub const ErrorCode = enum(i64) {
usingnamespace common.EnumStringify(@This());
parse_error = -32700,
invalid_request = -32600,
method_not_found = -32601,
invalid_params = -32602,
internal_error = -32603,
/// Error code indicating that a server received a notification or
/// request before the server has received the `initialize` request.
server_not_initialized = -32002,
unknown_error_code = -32001,
/// This is the end range of JSON RPC reserved error codes.
/// It doesn't denote a real error code.
///
/// * Since 3.16.0
jsonrpc_reserved_error_range_end = -32000,
/// This is the start range of LSP reserved error codes.
/// It doesn't denote a real error code.
///
/// * Since 3.16.0
lsp_reserved_error_range_start = -32899,
/// A request failed but it was syntactically correct, e.g the
/// method name was known and the parameters were valid. The error
/// message should contain human readable information about why
/// the request failed.
///
/// * Since 3.17.0
request_failed = -32803,
/// The server cancelled the request. This error code should
/// only be used for requests that explicitly support being
/// server cancellable.
///
/// @since 3.17.0
server_cancelled = -32802,
/// The server detected that the content of a document got
/// modified outside normal conditions. A server should
/// NOT send this error code if it detects a content change
/// in it unprocessed messages. The result even computed
/// on an older state might still be useful for the client.
///
/// If a client decides that a result is not of any use anymore
/// the client should cancel the request.
content_modified = -32801,
/// The client has canceled a request and a server has detected
/// the cancel.
request_cancelled = -32800,
_,
};
// TODO: object, array
pub const ResponseErrorData = union(enum) {
string: []const u8,
number: ErrorCode,
boolean: bool,
};
pub const ResponseError = struct {
/// A number indicating the error type that occurred.
code: common.integer,
/// A string providing a short description of the error.
message: []const u8,
/// A primitive or structured value that contains additional
/// information about the error. Can be omitted.
data: ?ResponseErrorData,
};
/// A Response Message sent as a result of a request.
/// If a request doesn’t provide a result value the receiver
/// of a request still needs to return a response message
/// to conform to the JSON RPC specification. The result
/// property of the ResponseMessage should be set to null
/// in this case to signal a successful request.
///
/// [Docs](https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#responseMessage)
pub const ResponseMessage = struct {
jsonrpc: []const u8 = "2.0",
id: common.RequestId,
/// The result of a request. This member is REQUIRED on success.
/// This member MUST NOT exist if there was an error invoking the method.
/// To make it not exist, use `.{ .none = {} }`.
result: ?ResponseParams = null,
/// The error object in case a request fails.
@"error": ?ResponseError = null,
};
pub const SignatureInformation = struct {
pub const ParameterInformation = struct {
// TODO Can also send a pair of encoded offsets
label: []const u8,
documentation: ?common.MarkupContent,
};
label: []const u8,
documentation: ?common.MarkupContent,
parameters: ?[]const ParameterInformation,
activeParameter: ?u32,
};
/// Signature help represents the signature of something
/// callable. There can be multiple signature but only one
/// active and only one active parameter.
///
/// [Docs](https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#signatureHelp)
pub const SignatureHelpResponse = struct {
signatures: ?[]const SignatureInformation,
activeSignature: ?u32,
activeParameter: ?u32,
}; | src/types/responses.zig |
const std = @import("std");
const common = @import("common.zig");
const VertexBufferHandle = common.VertexBufferHandle;
const VertexLayoutDesc = common.VertexLayoutDesc;
const VertexLayoutHandle = common.VertexLayoutHandle;
const TextureFormat = common.TextureFormat;
const TextureHandle = common.TextureHandle;
const ConstantBufferHandle = common.ConstantBufferHandle;
const RasteriserStateHandle = common.RasteriserStateHandle;
const BlendStateHandle = common.BlendStateHandle;
const ShaderProgramHandle = common.ShaderProgramHandle;
var allocator: std.mem.Allocator = undefined;
pub fn init(_allocator: std.mem.Allocator) !void {
allocator = _allocator;
}
pub fn deinit() void {}
pub fn logDebugMessages() !void {
std.debug.panic("Unimplemented", .{});
}
pub fn setViewport(x: u16, y: u16, width: u16, height: u16) void {
_ = x;
_ = y;
_ = width;
_ = height;
std.debug.panic("Unimplemented", .{});
}
pub fn clearWithColour(r: f32, g: f32, b: f32, a: f32) void {
_ = r;
_ = g;
_ = b;
_ = a;
std.debug.panic("Unimplemented", .{});
}
pub fn draw(offset: u32, count: u32) void {
_ = offset;
_ = count;
std.debug.panic("Unimplemented", .{});
}
pub fn createDynamicVertexBufferWithBytes(bytes: []const u8) !VertexBufferHandle {
_ = bytes;
std.debug.panic("Unimplemented", .{});
return 0;
}
pub fn writeBytesToVertexBuffer(buffer_id: VertexBufferHandle, offset: usize, bytes: []const u8) !usize {
_ = buffer_id;
_ = offset;
_ = bytes;
std.debug.panic("Unimplemented", .{});
return 0;
}
pub fn createVertexLayout(layout_desc: VertexLayoutDesc) VertexLayoutHandle {
_ = layout_desc;
std.debug.panic("Unimplemented", .{});
return 0;
}
pub fn useVertexLayout(layout_handle: VertexLayoutHandle) void {
_ = layout_handle;
std.debug.panic("Unimplemented", .{});
}
pub fn createTextureWithBytes(bytes: []const u8, format: TextureFormat) TextureHandle {
_ = bytes;
_ = format;
std.debug.panic("Unimplemented", .{});
return 0;
}
pub fn createConstantBuffer(size: usize) !ConstantBufferHandle {
_ = size;
std.debug.panic("Unimplemented", .{});
return 0;
}
pub fn bindConstantBuffer(
slot: u32,
buffer_handle: ConstantBufferHandle,
) void {
_ = slot;
_ = buffer_handle;
std.debug.panic("Unimplemented", .{});
}
pub fn updateShaderConstantBuffer(
buffer_handle: ConstantBufferHandle,
bytes: []const u8,
) !void {
_ = buffer_handle;
_ = bytes;
std.debug.panic("Unimplemented", .{});
}
pub fn useConstantBuffer(buffer_handle: ConstantBufferHandle) void {
_ = buffer_handle;
std.debug.panic("Unimplemented", .{});
}
pub fn createRasteriserState() !RasteriserStateHandle {
std.debug.panic("Unimplemented", .{});
}
pub fn useRasteriserState(_: RasteriserStateHandle) void {
std.debug.panic("Unimplemented", .{});
}
pub fn createBlendState() !BlendStateHandle {
std.debug.panic("Unimplemented", .{});
return 0;
}
pub fn setBlendState(_: type.BlendStateHandle) void {
std.debug.panic("Unimplemented", .{});
}
pub fn useShaderProgram(program_handle: ShaderProgramHandle) void {
_ = program_handle;
std.debug.panic("Unimplemented", .{});
}
pub fn createUniformColourShader() !ShaderProgramHandle {
_ = allocator;
std.debug.panic("Unimplemented", .{});
return 0;
} | modules/graphics/src/metal.zig |
const std = @import("std");
const Builder = std.build.Builder;
const pkgs = @import("deps.zig").pkgs;
const Artifacts = enum {
library, tests, all
};
const ContextErrors = error {
UnsupportedGLESVersion
};
const Context = struct {
library_path: ?[]const u8,
include_path: ?[]const u8,
mode: std.builtin.Mode,
target: std.zig.CrossTarget,
artifacts: Artifacts,
use_gles: u8,
fn addDeps(self: Context, s: *std.build.LibExeObjStep) !void {
s.setBuildMode(self.mode);
s.setTarget(self.target);
if (self.library_path) |value| {
var pos: usize = 0;
while (std.mem.indexOfScalarPos(u8, value, pos, std.fs.path.delimiter)) |end| {
s.addLibPath(value[pos..end]);
pos = end + 1;
}
if (pos < value.len) {
s.addLibPath(value[pos..]);
}
}
if (self.include_path) |value| {
var pos: usize = 0;
while (std.mem.indexOfScalarPos(u8, value, pos, std.fs.path.delimiter)) |end| {
s.addIncludeDir(value[pos..end]);
pos = end + 1;
}
if (pos < value.len) {
s.addIncludeDir(value[pos..]);
}
}
s.linkLibC();
s.linkSystemLibrary("epoxy");
s.linkSystemLibrary("freetype");
if (self.target.isDarwin()) {
s.addFrameworkDir("/System/Library/Frameworks");
s.linkFramework("OpenGL");
} else if (self.target.isWindows()) {
s.linkSystemLibrary("OpenGL32");
} else {
switch (self.use_gles) {
0 => s.linkSystemLibrary("GL"),
2 => s.linkSystemLibrary("GLESv2"),
3 => s.linkSystemLibrary("GLESv3"),
else => return ContextErrors.UnsupportedGLESVersion,
}
}
s.addIncludeDir("src");
if (std.Target.current.isDarwin() and self.target.isDarwin()) {
s.addCSourceFile("src/stb_image.c", &[_][]const u8{
"-isystem",
"/Library/Developer/CommandLineTools/SDKs/MacOSX11.0.sdk",
"-Wall",
"-Wextra",
"-Werror",
"-Wno-sign-compare"
});
} else {
s.addCSourceFile("src/stb_image.c", &[_][]const u8{
"-Wall",
"-Wextra",
"-Werror",
"-Wno-sign-compare"
});
}
}
};
pub fn build(b: *Builder) !void {
const context = Context{
.mode = b.standardReleaseOptions(),
.target = b.standardTargetOptions(.{}),
.library_path = b.option([]const u8, "library_path", "search path for libraries"),
.include_path = b.option([]const u8, "include_path", "include path for headers"),
.artifacts = b.option(Artifacts, "artifacts", "`library`, `tests`, or `all`") orelse .all,
.use_gles = b.option(u8, "gles", "`0`, `2` or `3`. use `0` (default) to link to normal OpenGL. ignored on Windows and macOS.") orelse 0,
};
const lib = b.addStaticLibrary("zargo", "src/libzargo.zig");
// workaround for https://github.com/ziglang/zig/issues/8896
lib.force_pic = true;
try context.addDeps(lib);
pkgs.addAllTo(lib);
if (context.artifacts != .tests) {
lib.install();
}
const exe = b.addExecutable("test", "tests/test.zig");
try context.addDeps(exe);
if (context.target.isWindows()) {
exe.linkSystemLibrary("glfw3");
} else {
exe.linkSystemLibrary("glfw");
}
exe.addPackage(.{
.name = "zargo",
.path = "src/zargo.zig",
.dependencies = &.{pkgs.zgl}
});
exe.strip = true;
if (context.artifacts != .library) {
exe.install();
}
const cexe = b.addExecutable("ctest", null);
try context.addDeps(cexe);
cexe.addIncludeDir("include");
cexe.addCSourceFile("tests/test.c", &[_][]const u8{"-std=c99"});
if (context.target.isWindows()) {
cexe.linkSystemLibrary("glfw3");
} else {
cexe.linkSystemLibrary("glfw");
}
cexe.linkLibrary(lib);
if (context.artifacts == .all) {
cexe.install();
}
} | build.zig |
const std = @import("std");
const builtin = std.builtin;
const crypto = std.crypto;
const debug = std.debug;
const mem = std.mem;
const meta = std.meta;
const fiat = @import("p256_64.zig");
const NonCanonicalError = crypto.errors.NonCanonicalError;
const NotSquareError = crypto.errors.NotSquareError;
const Limbs = fiat.Limbs;
/// A field element, internally stored in Montgomery domain.
pub const Fe = struct {
limbs: Limbs,
/// Field size.
pub const field_order = 115792089210356248762697446949407573530086143415290314195533631308867097853951;
/// Numer of bits that can be saturated without overflowing.
pub const saturated_bits = 255;
/// Zero.
pub const zero: Fe = Fe{ .limbs = mem.zeroes(Limbs) };
/// One.
pub const one = comptime one: {
var fe: Fe = undefined;
fiat.p256SetOne(&fe.limbs);
break :one fe;
};
/// Reject non-canonical encodings of an element.
pub fn rejectNonCanonical(s_: [32]u8, endian: builtin.Endian) NonCanonicalError!void {
var s = if (endian == .Little) s_ else orderSwap(s_);
const field_order_s = comptime fos: {
var fos: [32]u8 = undefined;
mem.writeIntLittle(u256, &fos, field_order);
break :fos fos;
};
if (crypto.utils.timingSafeCompare(u8, &s, &field_order_s, .Little) != .lt) {
return error.NonCanonical;
}
}
/// Swap the endianness of an encoded element.
pub fn orderSwap(s: [32]u8) [32]u8 {
var t = s;
for (s) |x, i| t[t.len - 1 - i] = x;
return t;
}
/// Unpack a field element.
pub fn fromBytes(s_: [32]u8, endian: builtin.Endian) NonCanonicalError!Fe {
var s = if (endian == .Little) s_ else orderSwap(s_);
try rejectNonCanonical(s, .Little);
var limbs_z: Limbs = undefined;
fiat.p256FromBytes(&limbs_z, s);
var limbs: Limbs = undefined;
fiat.p256ToMontgomery(&limbs, limbs_z);
return Fe{ .limbs = limbs };
}
/// Pack a field element.
pub fn toBytes(fe: Fe, endian: builtin.Endian) [32]u8 {
var limbs_z: Limbs = undefined;
fiat.p256FromMontgomery(&limbs_z, fe.limbs);
var s: [32]u8 = undefined;
fiat.p256ToBytes(&s, limbs_z);
return if (endian == .Little) s else orderSwap(s);
}
/// Create a field element from an integer.
pub fn fromInt(comptime x: u256) NonCanonicalError!Fe {
var s: [32]u8 = undefined;
mem.writeIntLittle(u256, &s, x);
return fromBytes(s, .Little);
}
/// Return the field element as an integer.
pub fn toInt(fe: Fe) u256 {
const s = fe.toBytes();
return mem.readIntLittle(u256, &s);
}
/// Return true if the field element is zero.
pub fn isZero(fe: Fe) bool {
var z: @TypeOf(fe.limbs[0]) = undefined;
fiat.p256Nonzero(&z, fe.limbs);
return z == 0;
}
/// Return true if both field elements are equivalent.
pub fn equivalent(a: Fe, b: Fe) bool {
return a.sub(b).isZero();
}
/// Return true if the element is odd.
pub fn isOdd(fe: Fe) bool {
const s = fe.toBytes(.Little);
return @truncate(u1, s[0]) != 0;
}
/// Conditonally replace a field element with `a` if `c` is positive.
pub fn cMov(fe: *Fe, a: Fe, c: u1) void {
fiat.p256Selectznz(&fe.limbs, c, fe.limbs, a.limbs);
}
/// Add field elements.
pub fn add(a: Fe, b: Fe) Fe {
var fe: Fe = undefined;
fiat.p256Add(&fe.limbs, a.limbs, b.limbs);
return fe;
}
/// Subtract field elements.
pub fn sub(a: Fe, b: Fe) Fe {
var fe: Fe = undefined;
fiat.p256Sub(&fe.limbs, a.limbs, b.limbs);
return fe;
}
/// Double a field element.
pub fn dbl(a: Fe) Fe {
var fe: Fe = undefined;
fiat.p256Add(&fe.limbs, a.limbs, a.limbs);
return fe;
}
/// Multiply field elements.
pub fn mul(a: Fe, b: Fe) Fe {
var fe: Fe = undefined;
fiat.p256Mul(&fe.limbs, a.limbs, b.limbs);
return fe;
}
/// Square a field element.
pub fn sq(a: Fe) Fe {
var fe: Fe = undefined;
fiat.p256Square(&fe.limbs, a.limbs);
return fe;
}
/// Square a field element n times.
fn sqn(a: Fe, comptime n: comptime_int) Fe {
var i: usize = 0;
var fe = a;
while (i < n) : (i += 1) {
fe = fe.sq();
}
return fe;
}
/// Compute a^n.
pub fn pow(a: Fe, comptime T: type, comptime n: T) Fe {
var fe = one;
var x: T = n;
var t = a;
while (true) {
if (@truncate(u1, x) != 0) fe = fe.mul(t);
x >>= 1;
if (x == 0) break;
t = t.sq();
}
return fe;
}
/// Negate a field element.
pub fn neg(a: Fe) Fe {
var fe: Fe = undefined;
fiat.p256Opp(&fe.limbs, a.limbs);
return fe;
}
/// Return the inverse of a field element, or 0 if a=0.
// Field inversion from https://eprint.iacr.org/2021/549.pdf
pub fn invert(a: Fe) Fe {
const len_prime = 256;
const iterations = (49 * len_prime + 57) / 17;
const Word = @TypeOf(a.limbs[0]);
const XLimbs = [a.limbs.len + 1]Word;
var d: Word = 1;
var f: XLimbs = undefined;
fiat.p256Msat(&f);
var g: XLimbs = undefined;
fiat.p256FromMontgomery(g[0..a.limbs.len], a.limbs);
g[g.len - 1] = 0;
var r: Limbs = undefined;
fiat.p256SetOne(&r);
var v = mem.zeroes(Limbs);
var precomp: Limbs = undefined;
fiat.p256DivstepPrecomp(&precomp);
var out1: Word = undefined;
var out2: XLimbs = undefined;
var out3: XLimbs = undefined;
var out4: Limbs = undefined;
var out5: Limbs = undefined;
var i: usize = 0;
while (i < iterations - iterations % 2) : (i += 2) {
fiat.p256Divstep(&out1, &out2, &out3, &out4, &out5, d, f, g, v, r);
fiat.p256Divstep(&d, &f, &g, &v, &r, out1, out2, out3, out4, out5);
}
if (iterations % 2 != 0) {
fiat.p256Divstep(&out1, &out2, &out3, &out4, &out5, d, f, g, v, r);
mem.copy(Word, &v, &out4);
mem.copy(Word, &f, &out2);
}
var v_opp: Limbs = undefined;
fiat.p256Opp(&v_opp, v);
fiat.p256Selectznz(&v, @truncate(u1, f[f.len - 1] >> (meta.bitCount(Word) - 1)), v, v_opp);
var fe: Fe = undefined;
fiat.p256Mul(&fe.limbs, v, precomp);
return fe;
}
/// Return true if the field element is a square.
pub fn isSquare(x2: Fe) bool {
const t110 = x2.mul(x2.sq()).sq();
const t111 = x2.mul(t110);
const t111111 = t111.mul(x2.mul(t110).sqn(3));
const x15 = t111111.sqn(6).mul(t111111).sqn(3).mul(t111);
const x16 = x15.sq().mul(x2);
const x53 = x16.sqn(16).mul(x16).sqn(15);
const x47 = x15.mul(x53);
const ls = x47.mul(((x53.sqn(17).mul(x2)).sqn(143).mul(x47)).sqn(47)).sq().mul(x2); // Legendre symbol, (p-1)/2
return ls.equivalent(Fe.one);
}
// x=x2^((field_order+1)/4) w/ field order=3 (mod 4).
fn uncheckedSqrt(x2: Fe) Fe {
comptime debug.assert(field_order % 4 == 3);
const t11 = x2.mul(x2.sq());
const t1111 = t11.mul(t11.sqn(2));
const t11111111 = t1111.mul(t1111.sqn(4));
const x16 = t11111111.sqn(8).mul(t11111111);
return x16.sqn(16).mul(x16).sqn(32).mul(x2).sqn(96).mul(x2).sqn(94);
}
/// Compute the square root of `x2`, returning `error.NotSquare` if `x2` was not a square.
pub fn sqrt(x2: Fe) NotSquareError!Fe {
const x = x2.uncheckedSqrt();
if (x.sq().equivalent(x2)) {
return x;
}
return error.NotSquare;
}
}; | lib/std/crypto/pcurves/p256/field.zig |
const std = @import("std");
usingnamespace @import("av-common.zig");
const SourceFile = struct {
formatContext: [*c]AVFormatContext = undefined,
codecContext: [*c]AVCodecContext = undefined,
frame: [*c]AVFrame = undefined,
packet: [*c]AVPacket = undefined,
streamIndex: usize = undefined,
pub fn close(self: *@This()) void {
avformat_close_input(&self.*.formatContext);
avcodec_free_context(&self.*.codecContext);
av_frame_free(&self.*.frame);
av_free_packet(self.*.packet);
}
};
const DestinationFile = struct {
formatContext: [*c]AVFormatContext = undefined,
codecContext: [*c]AVCodecContext = undefined,
frame: [*c]AVFrame = undefined,
packet: [*c]AVPacket = undefined,
pub fn close(self: *@This()) void {
avformat_close_output(&self.*.formatContext);
avcodec_free_context(&self.*.codecContext);
av_frame_free(&self.*.frame);
av_free_packet(self.*.packet);
}
};
pub fn extractAudio(srcPath: [*:0]const u8, dstPath: [*:0]const u8) !void {
var src: SourceFile = .{};
var dst: DestinationFile = .{};
try openSourceFile(srcPath, &src);
defer src.close();
try openDestinationFile(dstPath, &dst);
defer dst.close();
var swrContext = try createSwrContext(src.codecContext, dst.codecContext);
defer swr_free(&swrContext);
while (av_read_frame(src.formatContext, src.packet) >= 0) {
if (src.packet.*.stream_index == src.streamIndex) {
if (avcodec_send_packet(src.codecContext, src.packet) < 0) {
return error.BadResponse;
}
while (true) {
var response = avcodec_receive_frame(src.codecContext, src.frame);
if (response == AVERROR(EAGAIN) or response == AVERROR_EOF) {
break;
} else if (response < 0) {
return error.BadResponse;
}
// convert and encode the first part of the audio frame
if (swr_convert_frame(swrContext, dst.frame, src.frame) < 0) {
return error.FailedConversion;
}
try encode(&src, &dst, false);
// drain encoder since some stuff can be lingering in buffer
while (swr_get_delay(swrContext, dst.codecContext.*.sample_rate) > dst.frame.*.nb_samples) {
if (swr_convert(swrContext, @ptrCast([*c][*c]u8, &dst.frame.*.data[0]), dst.frame.*.nb_samples, null, 0) < 0) {
return error.FailedConversion;
}
try encode(&src, &dst, false);
}
}
}
av_packet_unref(src.packet);
}
// flush encoder
try encode(&src, &dst, true);
}
fn openSourceFile(srcPath: [*:0]const u8, src: *SourceFile) !void {
if (avformat_alloc_context()) |formatContext| {
src.*.formatContext = formatContext;
errdefer avformat_close_input(src.*.formatContext);
} else {
return error.AllocFailed;
}
if (avformat_open_input(&src.*.formatContext, srcPath, null, null) < 0) {
return error.OpenInputFailed;
}
if (avformat_find_stream_info(src.*.formatContext, null) < 0) {
return error.NoStreamInfo;
}
var codec: [*c]AVCodec = undefined;
var tmpIndex = av_find_best_stream(src.*.formatContext, AVMEDIA_TYPE_AUDIO, -1, -1, &codec, 0);
if (tmpIndex < 0) {
return error.NoSuitableStream;
}
src.*.streamIndex = @intCast(usize, tmpIndex);
if (avcodec_alloc_context3(codec)) |codecContext| {
src.*.codecContext = codecContext;
errdefer avcodec_free_context(&src.*.codecContext);
} else {
return error.AllocFailed;
}
var codecpar = src.*.formatContext.*.streams[src.*.streamIndex].*.codecpar;
if (avcodec_parameters_to_context(src.*.codecContext, codecpar) < 0) {
return error.CodecParamConversionFailed;
}
if (avcodec_open2(src.*.codecContext, codec, null) < 0) {
return error.CodecOpenFailed;
}
src.*.frame = try createFrameWithContext(src.*.codecContext);
errdefer av_frame_free(&src.*.frame);
if (av_packet_alloc()) |packet| {
src.*.packet = packet;
} else {
return error.AllocFailed;
}
}
fn openDestinationFile(dstPath: [*:0]const u8, dst: *DestinationFile) !void {
var outputFormat = av_guess_format(null, dstPath, null);
if (outputFormat == null) {
return error.GuessFormatFailed;
}
if (avformat_alloc_output_context2(&dst.*.formatContext, outputFormat, null, dstPath) < 0) {
return error.AllocFailed;
}
errdefer avformat_close_output(&dst.*.formatContext);
var encoder = avcodec_find_encoder(AV_CODEC_ID_VORBIS);
if (encoder == null) {
return error.NoVorbisEncoder;
}
var stream = avformat_new_stream(dst.*.formatContext, encoder);
if (stream == null) {
return error.AllocFailed;
}
dst.*.codecContext = stream.*.codec;
dst.*.codecContext.*.codec_id = AV_CODEC_ID_VORBIS;
dst.*.codecContext.*.codec_type = AVMEDIA_TYPE_AUDIO;
dst.*.codecContext.*.bit_rate = 64000;
dst.*.codecContext.*.channels = 2;
dst.*.codecContext.*.channel_layout = AV_CH_LAYOUT_STEREO;
dst.*.codecContext.*.sample_rate = 44100;
dst.*.codecContext.*.sample_fmt = encoder.*.sample_fmts[0];
dst.*.codecContext.*.time_base = AVRational{ .num = 1, .den = 44100 };
if (avcodec_open2(dst.*.codecContext, encoder, null) < 0) {
return error.CodecOpenFailed;
}
if (avcodec_parameters_from_context(stream.*.codecpar, dst.*.codecContext) < 0) {
return error.CodecParamConversionFailed;
}
if (avio_open(&dst.*.formatContext.*.pb, dstPath, AVIO_FLAG_WRITE) < 0) {
return error.AvioOpenFailed;
}
if (avformat_write_header(dst.*.formatContext, null) < 0) {
return error.AvioWriteHeaderFailed;
}
dst.*.frame = try createFrameWithContext(dst.*.codecContext);
errdefer av_frame_free(&dst.*.frame);
if (av_packet_alloc()) |packet| {
dst.*.packet = packet;
} else {
return error.AllocFailed;
}
}
fn createFrameWithContext(context: [*c]AVCodecContext) ![*c]AVFrame {
if (av_frame_alloc()) |frame| {
frame.*.nb_samples = context.*.frame_size;
frame.*.format = context.*.sample_fmt;
frame.*.channel_layout = context.*.channel_layout;
frame.*.channels = context.*.channels;
frame.*.sample_rate = context.*.sample_rate;
if (av_frame_get_buffer(frame, 0) < 0) {
return error.AllocFailed;
}
return frame;
} else {
return error.AllocFailed;
}
}
fn createSwrContext(srcContext: [*c]AVCodecContext, dstContext: [*c]AVCodecContext) !?*SwrContext {
var context = swr_alloc_set_opts(
null,
@intCast(i64, dstContext.*.channel_layout),
dstContext.*.sample_fmt,
dstContext.*.sample_rate,
@intCast(i64, srcContext.*.channel_layout),
srcContext.*.sample_fmt,
srcContext.*.sample_rate,
0,
null,
);
if (swr_init(context) < 0) {
return error.AllocFailed;
}
return context;
}
fn encode(src: *SourceFile, dst: *DestinationFile, flush: bool) !void {
if (avcodec_send_frame(dst.*.codecContext, if (flush) null else dst.*.frame) < 0) {
return error.BadResponse;
}
while (true) {
var response = avcodec_receive_packet(dst.*.codecContext, dst.*.packet);
if (response == AVERROR(EAGAIN) or response == AVERROR_EOF) {
break;
} else if (response < 0) {
return error.BadResponse;
}
dst.*.packet.*.pts = src.*.packet.*.pts;
dst.*.packet.*.dts = src.*.packet.*.dts;
dst.*.packet.*.pos = -1;
if (av_interleaved_write_frame(dst.*.formatContext, dst.*.packet) < 0) {
return error.FailedEncode;
}
av_packet_unref(dst.*.packet);
}
}
fn avformat_close_output(format: *[*c]AVFormatContext) void {
if (av_write_trailer(format.*) < 0) {
std.log.warn("av_write_trailer: leak", .{});
}
if (avio_closep(&format.*.*.pb) < 0) {
std.log.warn("avio_closep: leak", .{});
}
format.* = 0;
} | nativemap/src/audio-extractor.zig |
const std = @import("../../std.zig");
const maxInt = std.math.maxInt;
const linux = std.os.linux;
const SYS = linux.SYS;
const socklen_t = linux.socklen_t;
const iovec = std.os.iovec;
const iovec_const = std.os.iovec_const;
const uid_t = linux.uid_t;
const gid_t = linux.gid_t;
const pid_t = linux.pid_t;
const sockaddr = linux.sockaddr;
const timespec = linux.timespec;
pub fn syscall0(number: SYS) usize {
return asm volatile (
\\ syscall
\\ blez $7, 1f
\\ subu $2, $0, $2
\\ 1:
: [ret] "={$2}" (-> usize),
: [number] "{$2}" (@enumToInt(number)),
: "$1", "$3", "$4", "$5", "$6", "$7", "$8", "$9", "$10", "$11", "$12", "$13", "$14", "$15", "$24", "$25", "hi", "lo", "memory"
);
}
pub fn syscall_pipe(fd: *[2]i32) usize {
return asm volatile (
\\ .set noat
\\ .set noreorder
\\ syscall
\\ blez $7, 1f
\\ nop
\\ b 2f
\\ subu $2, $0, $2
\\ 1:
\\ sw $2, 0($4)
\\ sw $3, 4($4)
\\ 2:
: [ret] "={$2}" (-> usize),
: [number] "{$2}" (@enumToInt(SYS.pipe)),
[fd] "{$4}" (fd),
: "$1", "$3", "$5", "$6", "$7", "$8", "$9", "$10", "$11", "$12", "$13", "$14", "$15", "$24", "$25", "hi", "lo", "memory"
);
}
pub fn syscall1(number: SYS, arg1: usize) usize {
return asm volatile (
\\ syscall
\\ blez $7, 1f
\\ subu $2, $0, $2
\\ 1:
: [ret] "={$2}" (-> usize),
: [number] "{$2}" (@enumToInt(number)),
[arg1] "{$4}" (arg1),
: "$1", "$3", "$5", "$6", "$7", "$8", "$9", "$10", "$11", "$12", "$13", "$14", "$15", "$24", "$25", "hi", "lo", "memory"
);
}
pub fn syscall2(number: SYS, arg1: usize, arg2: usize) usize {
return asm volatile (
\\ syscall
\\ blez $7, 1f
\\ subu $2, $0, $2
\\ 1:
: [ret] "={$2}" (-> usize),
: [number] "{$2}" (@enumToInt(number)),
[arg1] "{$4}" (arg1),
[arg2] "{$5}" (arg2),
: "$1", "$3", "$6", "$7", "$8", "$9", "$10", "$11", "$12", "$13", "$14", "$15", "$24", "$25", "hi", "lo", "memory"
);
}
pub fn syscall3(number: SYS, arg1: usize, arg2: usize, arg3: usize) usize {
return asm volatile (
\\ syscall
\\ blez $7, 1f
\\ subu $2, $0, $2
\\ 1:
: [ret] "={$2}" (-> usize),
: [number] "{$2}" (@enumToInt(number)),
[arg1] "{$4}" (arg1),
[arg2] "{$5}" (arg2),
[arg3] "{$6}" (arg3),
: "$1", "$3", "$7", "$8", "$9", "$10", "$11", "$12", "$13", "$14", "$15", "$24", "$25", "hi", "lo", "memory"
);
}
pub fn syscall4(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize {
return asm volatile (
\\ syscall
\\ blez $7, 1f
\\ subu $2, $0, $2
\\ 1:
: [ret] "={$2}" (-> usize),
: [number] "{$2}" (@enumToInt(number)),
[arg1] "{$4}" (arg1),
[arg2] "{$5}" (arg2),
[arg3] "{$6}" (arg3),
[arg4] "{$7}" (arg4),
: "$1", "$3", "$8", "$9", "$10", "$11", "$12", "$13", "$14", "$15", "$24", "$25", "hi", "lo", "memory"
);
}
pub fn syscall5(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize {
return asm volatile (
\\ .set noat
\\ subu $sp, $sp, 24
\\ sw %[arg5], 16($sp)
\\ syscall
\\ addu $sp, $sp, 24
\\ blez $7, 1f
\\ subu $2, $0, $2
\\ 1:
: [ret] "={$2}" (-> usize),
: [number] "{$2}" (@enumToInt(number)),
[arg1] "{$4}" (arg1),
[arg2] "{$5}" (arg2),
[arg3] "{$6}" (arg3),
[arg4] "{$7}" (arg4),
[arg5] "r" (arg5),
: "$1", "$3", "$8", "$9", "$10", "$11", "$12", "$13", "$14", "$15", "$24", "$25", "hi", "lo", "memory"
);
}
// NOTE: The o32 calling convention requires the callee to reserve 16 bytes for
// the first four arguments even though they're passed in $a0-$a3.
pub fn syscall6(
number: SYS,
arg1: usize,
arg2: usize,
arg3: usize,
arg4: usize,
arg5: usize,
arg6: usize,
) usize {
return asm volatile (
\\ .set noat
\\ subu $sp, $sp, 24
\\ sw %[arg5], 16($sp)
\\ sw %[arg6], 20($sp)
\\ syscall
\\ addu $sp, $sp, 24
\\ blez $7, 1f
\\ subu $2, $0, $2
\\ 1:
: [ret] "={$2}" (-> usize),
: [number] "{$2}" (@enumToInt(number)),
[arg1] "{$4}" (arg1),
[arg2] "{$5}" (arg2),
[arg3] "{$6}" (arg3),
[arg4] "{$7}" (arg4),
[arg5] "r" (arg5),
[arg6] "r" (arg6),
: "$1", "$3", "$8", "$9", "$10", "$11", "$12", "$13", "$14", "$15", "$24", "$25", "hi", "lo", "memory"
);
}
pub fn syscall7(
number: SYS,
arg1: usize,
arg2: usize,
arg3: usize,
arg4: usize,
arg5: usize,
arg6: usize,
arg7: usize,
) usize {
return asm volatile (
\\ .set noat
\\ subu $sp, $sp, 32
\\ sw %[arg5], 16($sp)
\\ sw %[arg6], 20($sp)
\\ sw %[arg7], 24($sp)
\\ syscall
\\ addu $sp, $sp, 32
\\ blez $7, 1f
\\ subu $2, $0, $2
\\ 1:
: [ret] "={$2}" (-> usize),
: [number] "{$2}" (@enumToInt(number)),
[arg1] "{$4}" (arg1),
[arg2] "{$5}" (arg2),
[arg3] "{$6}" (arg3),
[arg4] "{$7}" (arg4),
[arg5] "r" (arg5),
[arg6] "r" (arg6),
[arg7] "r" (arg7),
: "$1", "$3", "$8", "$9", "$10", "$11", "$12", "$13", "$14", "$15", "$24", "$25", "hi", "lo", "memory"
);
}
/// This matches the libc clone function.
pub extern fn clone(func: fn (arg: usize) callconv(.C) u8, stack: usize, flags: u32, arg: usize, ptid: *i32, tls: usize, ctid: *i32) usize;
pub fn restore() callconv(.Naked) void {
return asm volatile ("syscall"
:
: [number] "{$2}" (@enumToInt(SYS.sigreturn)),
: "$1", "$3", "$4", "$5", "$6", "$7", "$8", "$9", "$10", "$11", "$12", "$13", "$14", "$15", "$24", "$25", "hi", "lo", "memory"
);
}
pub fn restore_rt() callconv(.Naked) void {
return asm volatile ("syscall"
:
: [number] "{$2}" (@enumToInt(SYS.rt_sigreturn)),
: "$1", "$3", "$4", "$5", "$6", "$7", "$8", "$9", "$10", "$11", "$12", "$13", "$14", "$15", "$24", "$25", "hi", "lo", "memory"
);
}
pub const O = struct {
pub const CREAT = 0o0400;
pub const EXCL = 0o02000;
pub const NOCTTY = 0o04000;
pub const TRUNC = 0o01000;
pub const APPEND = 0o0010;
pub const NONBLOCK = 0o0200;
pub const DSYNC = 0o0020;
pub const SYNC = 0o040020;
pub const RSYNC = 0o040020;
pub const DIRECTORY = 0o0200000;
pub const NOFOLLOW = 0o0400000;
pub const CLOEXEC = 0o02000000;
pub const ASYNC = 0o010000;
pub const DIRECT = 0o0100000;
pub const LARGEFILE = 0o020000;
pub const NOATIME = 0o01000000;
pub const PATH = 0o010000000;
pub const TMPFILE = 0o020200000;
pub const NDELAY = NONBLOCK;
};
pub const F = struct {
pub const DUPFD = 0;
pub const GETFD = 1;
pub const SETFD = 2;
pub const GETFL = 3;
pub const SETFL = 4;
pub const SETOWN = 24;
pub const GETOWN = 23;
pub const SETSIG = 10;
pub const GETSIG = 11;
pub const GETLK = 33;
pub const SETLK = 34;
pub const SETLKW = 35;
pub const RDLCK = 0;
pub const WRLCK = 1;
pub const UNLCK = 2;
pub const SETOWN_EX = 15;
pub const GETOWN_EX = 16;
pub const GETOWNER_UIDS = 17;
};
pub const LOCK = struct {
pub const SH = 1;
pub const EX = 2;
pub const UN = 8;
pub const NB = 4;
};
pub const MMAP2_UNIT = 4096;
pub const MAP = struct {
pub const NORESERVE = 0x0400;
pub const GROWSDOWN = 0x1000;
pub const DENYWRITE = 0x2000;
pub const EXECUTABLE = 0x4000;
pub const LOCKED = 0x8000;
pub const @"32BIT" = 0x40;
};
pub const VDSO = struct {
pub const CGT_SYM = "__kernel_clock_gettime";
pub const CGT_VER = "LINUX_2.6.39";
};
pub const Flock = extern struct {
type: i16,
whence: i16,
__pad0: [4]u8,
start: off_t,
len: off_t,
pid: pid_t,
__unused: [4]u8,
};
pub const msghdr = extern struct {
name: ?*sockaddr,
namelen: socklen_t,
iov: [*]iovec,
iovlen: i32,
control: ?*anyopaque,
controllen: socklen_t,
flags: i32,
};
pub const msghdr_const = extern struct {
name: ?*const sockaddr,
namelen: socklen_t,
iov: [*]const iovec_const,
iovlen: i32,
control: ?*const anyopaque,
controllen: socklen_t,
flags: i32,
};
pub const blksize_t = i32;
pub const nlink_t = u32;
pub const time_t = i32;
pub const mode_t = u32;
pub const off_t = i64;
pub const ino_t = u64;
pub const dev_t = u64;
pub const blkcnt_t = i64;
// The `stat` definition used by the Linux kernel.
pub const Stat = extern struct {
dev: u32,
__pad0: [3]u32, // Reserved for st_dev expansion
ino: ino_t,
mode: mode_t,
nlink: nlink_t,
uid: uid_t,
gid: gid_t,
rdev: u32,
__pad1: [3]u32,
size: off_t,
atim: timespec,
mtim: timespec,
ctim: timespec,
blksize: blksize_t,
__pad3: u32,
blocks: blkcnt_t,
__pad4: [14]usize,
pub fn atime(self: @This()) timespec {
return self.atim;
}
pub fn mtime(self: @This()) timespec {
return self.mtim;
}
pub fn ctime(self: @This()) timespec {
return self.ctim;
}
};
pub const timeval = extern struct {
tv_sec: isize,
tv_usec: isize,
};
pub const timezone = extern struct {
tz_minuteswest: i32,
tz_dsttime: i32,
};
pub const Elf_Symndx = u32;
pub const rlimit_resource = enum(c_int) {
/// Per-process CPU limit, in seconds.
CPU,
/// Largest file that can be created, in bytes.
FSIZE,
/// Maximum size of data segment, in bytes.
DATA,
/// Maximum size of stack segment, in bytes.
STACK,
/// Largest core file that can be created, in bytes.
CORE,
/// Number of open files.
NOFILE,
/// Address space limit.
AS,
/// Largest resident set size, in bytes.
/// This affects swapping; processes that are exceeding their
/// resident set size will be more likely to have physical memory
/// taken from them.
RSS,
/// Number of processes.
NPROC,
/// Locked-in-memory address space.
MEMLOCK,
/// Maximum number of file locks.
LOCKS,
/// Maximum number of pending signals.
SIGPENDING,
/// Maximum bytes in POSIX message queues.
MSGQUEUE,
/// Maximum nice priority allowed to raise to.
/// Nice levels 19 .. -20 correspond to 0 .. 39
/// values of this resource limit.
NICE,
/// Maximum realtime priority allowed for non-priviledged
/// processes.
RTPRIO,
/// Maximum CPU time in µs that a process scheduled under a real-time
/// scheduling policy may consume without making a blocking system
/// call before being forcibly descheduled.
RTTIME,
_,
}; | lib/std/os/linux/mips.zig |
const std = @import("std");
const Deps = @import("Deps.zig");
const slimy_version = std.SemanticVersion.parse("0.1.0-dev") catch unreachable;
pub fn build(b: *std.build.Builder) !void {
const target = b.standardTargetOptions(.{});
const mode = b.standardReleaseOptions();
const singlethread = b.option(bool, "singlethread", "Build in single-threaded mode") orelse false;
const strip = b.option(bool, "strip", "Strip debug info from binaries") orelse false;
const suffix = b.option(bool, "suffix", "Suffix binary names with version and target") orelse false;
const timestamp = b.option(bool, "timestamp", "Include build timestamp in version information") orelse false;
const glslc = b.option([]const u8, "glslc", "Specify the path to the glslc binary") orelse "glslc";
const shaders = b.addSystemCommand(&.{
glslc, "-o", "search.spv", "search.comp",
});
shaders.cwd = std.fs.path.join(b.allocator, &.{ b.build_root, "src", "shader" }) catch unreachable;
const deps = Deps.init(b);
deps.add("https://github.com/silversquirl/cpuinfo-zig", "main");
deps.add("https://github.com/silversquirl/optz", "main");
deps.add("https://github.com/silversquirl/zcompute", "main");
var version = slimy_version;
if (version.pre != null) {
// Find git commit hash
var code: u8 = undefined;
if (b.execAllowFail(
&.{ "git", "rev-parse", "--short", "HEAD" },
&code,
.Inherit,
)) |commit| {
version.build = std.mem.trimRight(u8, commit, "\n");
// Add -dirty if we have uncommitted changes
_ = b.execAllowFail(
&.{ "git", "diff-index", "--quiet", "HEAD" },
&code,
.Inherit,
) catch |err| switch (err) {
error.ExitCodeFailure => version.build = b.fmt("{s}-dirty", .{version.build}),
else => |e| return e,
};
} else |err| switch (err) {
error.FileNotFound => {}, // No git
else => |e| return e,
}
}
const consts = b.addOptions();
consts.addOption(std.SemanticVersion, "version", version);
consts.addOption(?i64, "timestamp", if (timestamp) std.time.timestamp() else null);
deps.addPackage(consts.getPackage("build_consts"));
const exe_name = if (suffix)
b.fmt("slimy-{}-{s}", .{ version, target.zigTriple(b.allocator) catch unreachable })
else
"slimy";
const exe = b.addExecutable(exe_name, "src/main.zig");
deps.addTo(exe);
exe.linkLibC();
exe.step.dependOn(&shaders.step);
exe.linkage = .dynamic;
exe.setTarget(target);
exe.setBuildMode(mode);
exe.single_threaded = singlethread;
exe.strip = strip;
exe.install();
const run_cmd = exe.run();
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
const wasm = b.addSharedLibrary("slimy", "src/web.zig", .unversioned);
wasm.setTarget(try std.zig.CrossTarget.parse(.{
.arch_os_abi = "wasm32-freestanding",
}));
wasm.setBuildMode(mode);
wasm.override_dest_dir = .{ .custom = "web" };
wasm.single_threaded = true;
const web = b.addInstallDirectory(.{
.source_dir = "web",
.install_dir = .prefix,
.install_subdir = "web",
});
web.step.dependOn(&b.addInstallArtifact(wasm).step);
const web_step = b.step("web", "Build web UI");
web_step.dependOn(&web.step);
} | build.zig |
const std = @import("std");
const fs = std.fs;
const print = std.debug.print;
const mem = std.mem;
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = &gpa.allocator;
const input = try fs.cwd().readFileAlloc(allocator, "data/input_19_1.txt", std.math.maxInt(usize));
var messages = std.ArrayList([]const u8).init(allocator);
defer messages.deinit();
var txt_rules = std.ArrayList([]const u8).init(allocator);
defer txt_rules.deinit();
{
var lines = std.mem.tokenize(input, "\n");
while (lines.next()) |raw_line| {
const line = std.mem.trim(u8, raw_line, " \r\n");
if (line.len == 0) break;
var rule_it = std.mem.tokenize(line, ":");
const id = std.fmt.parseInt(usize, rule_it.next().?, 10) catch unreachable;
if (id >= txt_rules.items.len) {
try txt_rules.resize(id + 1);
}
txt_rules.items[id] = std.mem.trim(u8, rule_it.next().?, " \r\n");
}
while (lines.next()) |raw_line| {
const line = std.mem.trim(u8, raw_line, " \r\n");
if (line.len == 0) continue;
try messages.append(line);
}
}
const trie = try buildTries(allocator, txt_rules.items);
{ // Solution one
var count: u32 = 0;
for (messages.items) |msg| {
if (trie.validWord(msg)) { count += 1; }
}
std.debug.print("Day 19 - Solution 1: {}\n", .{count});
}
{ // Solution two
std.debug.print("Day 19 - Solution 2: {}\n", .{0});
}
}
const NodeTag = enum {
value, rule
};
const Node = union(NodeTag) {
value: u8,
rule: u8
};
const ProcessedRule = struct {
seqs: std.ArrayList(std.ArrayList(Node)),
const Self = @This();
pub fn fromText(a: *mem.Allocator, txt: []const u8) !Self {
var seqs = std.ArrayList(std.ArrayList(Node)).init(a);
var it = mem.tokenize(txt, "|");
while (it.next()) |raw_option| {
var option = std.ArrayList(Node).init(a);
var option_txt = mem.trim(u8, raw_option, " \r\n");
if (option_txt[0] == '\"') {
try option.append(Node{ .value = option_txt[1] });
}
else {
var rule_it = mem.tokenize(option_txt, " ");
while (rule_it.next()) |rule| {
try option.append(Node{ .rule = try std.fmt.parseInt(u8, rule, 10) });
}
}
try seqs.append(option);
}
return Self { .seqs = seqs };
}
pub fn deinit(s: *Self) void {
for (s.seqs.items) |_, seqi| {
s.seqs.items[seqi].deinit();
}
s.seqs.deinit();
}
pub fn print(s: *const Self) void {
for (s.seqs.items) |seq, i| {
for (seq.items) |node| {
print("{} ", .{node});
}
print(" | ", .{});
}
print("\n", .{});
}
};
fn buildTries(a: *mem.Allocator, txtrules: [][]const u8) !Trie {
var rules = std.ArrayList(ProcessedRule).init(a);
defer {
for (rules.items) |_, ri| { rules.items[ri].deinit(); }
rules.deinit();
}
for (txtrules) |txtrule| {
try rules.append(try ProcessedRule.fromText(a, txtrule));
}
var seqs = std.ArrayList(std.ArrayList(Node)).init(a);
defer seqs.deinit();
const first = Node{ .rule = 0 };
var first_seq = std.ArrayList(Node).init(a);
try first_seq.append(first);
try seqs.append(first_seq);
var trie = Trie.init(a);
outer: while (seqs.items.len > 0) {
const seq = seqs.items[seqs.items.len - 1];
defer seq.deinit();
try seqs.resize(seqs.items.len - 1);
for (seq.items) |node, ni| {
switch (node) {
NodeTag.rule => |nindex| {
var rule = rules.items[@as(usize, nindex)];
// Make new sequences and add them to the list
for (rule.seqs.items) |option| {
var new_nodes = std.ArrayList(Node).init(a);
try new_nodes.resize(seq.items.len - 1 + option.items.len);
mem.copy(Node, new_nodes.items[0..ni], seq.items[0..ni]);
mem.copy(Node, new_nodes.items[ni..ni + option.items.len], option.items);
mem.copy(Node, new_nodes.items[ni + option.items.len..], seq.items[ni+1..]);
try seqs.append(new_nodes);
}
continue :outer;
},
NodeTag.value => {},
}
}
// If we get here, all the items in the sequence are values
// print("Found sequence: ", .{});
// for (seq.items) |node, ni| {
// switch (node) {
// NodeTag.value => |v| { print("{c} ", .{v}); },
// NodeTag.rule => unreachable
// }
// }
// print("\n", .{});
try trie.addSequence(seq.items);
}
return trie;
}
const Trie = struct {
const TrieNode = struct {
a: usize = 0,
b: usize = 0,
term: bool = false
};
const Self = @This();
nodes: std.ArrayList(TrieNode),
pub fn init(a: *mem.Allocator) Self {
var s = Self{ .nodes = std.ArrayList(TrieNode).init(a) };
s.nodes.append(TrieNode{}) catch unreachable;
return s;
}
pub fn deinit(s: *Self) void {
nodes.deinit();
}
pub fn addSequence(s: *Self, seqs: []Node) !void {
var nodei: usize = 0;
for (seqs) |seq_node, seq_node_index| {
switch (seq_node) {
NodeTag.value => |v| {
if (v == 'a') {
if (s.nodes.items[nodei].a == 0) {
try s.nodes.append(TrieNode{});
s.nodes.items[nodei].a = s.nodes.items.len - 1;
}
nodei = s.nodes.items[nodei].a;
} else if (v == 'b') {
if (s.nodes.items[nodei].b == 0) {
try s.nodes.append(TrieNode{});
s.nodes.items[nodei].b = s.nodes.items.len - 1;
}
nodei = s.nodes.items[nodei].b;
} else unreachable;
},
NodeTag.rule => unreachable
}
s.nodes.items[nodei].term = s.nodes.items[nodei].term or (seq_node_index == seqs.len - 1);
}
}
pub fn validWord(s: *const Self, wrd: []const u8) bool {
var node = &s.nodes.items[0];
for (wrd) |c, i| {
if (c == 'a') {
if (node.a == 0) return false;
node = &s.nodes.items[node.a];
}
else if (c == 'b') {
if (node.b == 0) return false;
node = &s.nodes.items[node.b];
}
if (i == wrd.len -1) return node.term;
}
unreachable;
}
};
const hm = std.hash_map;
const SubruleKind = enum {
subrule, terminal
};
const Subrule = union(SubruleKind) {
subrule: std.ArrayList(u8),
value: u8
};
fn buildRules(a: *mem.Allocator, txtrules: [][]const u8) void {
var temp = std.ArrayList(std.ArrayList(Subrule)).init(a);
defer {
for (temp.items) |rule| {
for (rule.items) |sub, subi| {
switch (sub) {
SubruleKind.subroule => { rule.items[subi].deinit(); },
SubruleKind.value => {}
}
}
rules.items[ri].deinit();
}
rules.deinit();
}
for (txtrules) |txtrule| {
try rules.append(try ProcessedRule.fromText(a, txtrule));
}
var subrule_map = hm.HashMap([]const u8, usize, hm.hashString, hm.eqlString, 80).init(a);
defer subrule_map.deinit();
while (true) {
var has_compressed = false;
for (rules.items) |ri| {
}
}
} | 2020/src/day_19.zig |
const std = @import("std");
const Format = @import("format.zig").Format;
const testing = std.testing;
const value = @import("value.zig");
const builtin = @import("builtin");
pub const fix_map_max = 15;
pub const map16_max = 65535;
pub const fix_array_max = 15;
pub const array16_max = 65535;
const fix_str_max = 31;
const str8_max = 255;
const str16_max = 65535;
pub const neg_int_fix_min = -32;
pub const pos_int_fix_max = 127;
pub const uint8_max = 255;
pub const uint16_max = 65535;
pub const uint32_max = 4294967295;
pub const uint64_max = 18446744073709551615;
pub const int8_max = 127;
pub const int16_max = 32767;
pub const int32_max = 2147483647;
pub const int64_max = 9223372036854775807;
pub const int8_min = -128;
pub const int16_min = -32768;
pub const int32_min = -int32_max - 1;
pub const int64_min = -int64_max - 1;
pub const EncodeError = error{
UnsupportedType,
OutOfMemory,
};
pub const Encoder = struct {
allocator: *std.mem.Allocator,
asBinaryFields: ?std.BufSet = null,
pub fn free(self: *Encoder) void {
if (self.asBinaryFields) |*abf| {
abf.deinit();
}
}
pub fn encodeAsBinary(
self: *Encoder,
field: []const u8,
) !void {
if (self.asBinaryFields == null) {
self.asBinaryFields = std.BufSet.init(self.allocator);
}
try self.asBinaryFields.?.put(field);
}
pub fn encode(self: *Encoder, val: anytype) EncodeError![]u8 {
// std.debug.print("tinfo: {}\n", .{@typeInfo(@TypeOf(val))});
const ti = @typeInfo(@TypeOf(val));
return switch (ti) {
.Null => writeNil(self.allocator),
.Bool => writeBool(self.allocator, val),
.ComptimeInt => writeIntAny(self.allocator, val),
.ComptimeFloat => writeFloatAny(self.allocator, val),
.Int => |intInfo| switch (intInfo.is_signed) {
true => switch (intInfo.bits) {
8 => writeIntAny(self.allocator, val),
16 => writeInt16(self.allocator, val),
32 => writeInt32(self.allocator, val),
64 => writeInt64(self.allocator, val),
else => error.UnsupportedType,
},
false => switch (intInfo.bits) {
8 => writeUintAny(self.allocator, val),
16 => writeUint16(self.allocator, val),
32 => writeUint32(self.allocator, val),
64 => writeUint64(self.allocator, val),
else => error.UnsupportedType,
},
},
.Float => |floatInfo| switch (floatInfo.bits) {
32 => writeFloat32(self.allocator, val),
64 => writeFloat64(self.allocator, val),
else => error.UnsupportedType,
},
.Optional => {
if (val) |tmpv| {
return self.encode(tmpv);
} else {
return writeNil(self.allocator);
}
},
.Array => |arrayInfo| switch (arrayInfo.child) {
u8 => writeStrAny(self.allocator, val[0..]),
else => self.encodeArrayAny(arrayInfo.child, val[0..]),
},
.Pointer => |pointerInfo| switch (pointerInfo.size) {
.One => switch (pointerInfo.child) {
u8 => writeStrAny(self.allocator, val),
else => self.encode(val.*),
},
.Slice => switch (pointerInfo.child) {
u8 => writeStrAny(self.allocator, val),
else => self.encode(val),
},
else => error.UnsupportedType,
},
.Struct => self.encodeStruct(@TypeOf(val), val),
else => error.UnsupportedType,
};
}
fn encodeStruct(self: *Encoder, comptime T: type, v: T) EncodeError![]u8 {
const ti = @typeInfo(T);
if (ti.Struct.fields.len <= fix_map_max) {
return self.encodeFixMap(T, v);
} else if (ti.Struct.fields.len <= fix_map16_max) {
return self.encodeMap16(T, v);
}
return self.encodeMap32(T, v);
}
fn encodeFixMap(self: *Encoder, comptime T: type, v: T) EncodeError![]u8 {
const len = @typeInfo(T).Struct.fields.len;
var entries = try self.encodeMapEntries(T, v);
var out = try self.allocator.alloc(u8, 1 + entries.len);
out[0] = (Format{ .fix_map = @intCast(u8, len) }).toUint8();
std.mem.copy(u8, out[1..], entries);
// now release the elems and joined elems
self.allocator.free(entries);
return out;
}
fn encodeMapEntries(self: *Encoder, comptime T: type, v: T) EncodeError![]u8 {
// allocate twice the size as we space for each keys
// and values.
const ti = @typeInfo(T);
var entries = try self.allocator.alloc([]u8, ti.Struct.fields.len * 2);
var i: usize = 0;
inline for (ti.Struct.fields) |field| {
// FIXME(): we have a memory leak here most likely
// in the case we return an error the error is not
// freed, but knowing that the only error which can happen
// in encodeValue is an OutOfMemory error, it's quite
// certain we would not recover anyway. Will take care of
// this later
var encodedkey = try writeStrAny(self.allocator, field.name);
entries[i] = encodedkey;
var encodedvalue = try self.encode(@field(v, field.name));
entries[i + 1] = encodedvalue;
i += 2;
}
// FIXME(): see previous comment, same concerns.
var out = try std.mem.join(self.allocator, &[_]u8{}, entries);
// free the slice of encoded elements as they are not required anymore
for (entries) |e| {
self.allocator.free(e);
}
self.allocator.free(entries);
return out;
}
fn encodeArrayAny(
self: *Encoder,
comptime T: type,
v: []const T,
) EncodeError![]u8 {
if (v.len <= fix_array_max) {
return self.encodeFixArray(T, v);
} else if (v.len <= array16_max) {
return self.encodeArray16(T, v);
}
return self.encodeArray32(T, v);
}
fn encodeFixArray(
self: *Encoder,
comptime T: type,
v: []const T,
) EncodeError![]u8 {
var elems = try self.encodeArrayElements(T, v);
var out = try self.allocator.alloc(u8, 1 + elems.len);
out[0] = (Format{ .fix_array = @intCast(u8, v.len) }).toUint8();
std.mem.copy(u8, out[1..], elems);
// now release the elems and joined elems
self.allocator.free(elems);
return out;
}
fn encodeArray16(
self: *Encoder,
comptime T: type,
v: []const T,
) EncodeError![]u8 {
var elems = try self.encodeArrayElements(T, v);
var out = try self.allocator.alloc(u8, 1 + @sizeOf(u16) + elems.len);
out[0] = Format.array16.toUint8();
std.mem.writeIntBig(u16, out[1 .. 1 + @sizeOf(u16)], @intCast(u16, v.len));
std.mem.copy(u8, out[1 + @sizeOf(u16) ..], elems);
// now release the elems and joined elems
self.allocator.free(elems);
return out;
}
fn encodeArray32(
self: *Encoder,
comptime T: type,
v: []const T,
) EncodeError![]u8 {
var elems = try self.encodeArrayElements(T, v);
var out = try self.allocator.alloc(u8, 1 + @sizeOf(u32) + elems.len);
out[0] = Format.array32.toUint8();
std.mem.writeIntBig(u32, out[1 .. 1 + @sizeOf(u32)], @intCast(u32, v.len));
std.mem.copy(u8, out[1 + @sizeOf(u32) ..], elems);
// now release the elems and joined elems
self.allocator.free(elems);
return out;
}
fn encodeArrayElements(
self: *Encoder,
comptime T: type,
v: []const T,
) EncodeError![]u8 {
var elems = try self.allocator.alloc([]u8, v.len);
var i: usize = 0;
while (i < v.len) {
// FIXME(): we have a memory leak here most likely
// in the case we return an error the error is not
// freed, but knowing that the only error which can happen
// in encodeValue is an OutOfMemory error, it's quite
// certain we would not recover anyway. Will take care of
// this later
var encoded = try self.encode(v[i]);
elems[i] = encoded;
i += 1;
}
// FIXME(): see previous comment, same concerns.
var out = try std.mem.join(self.allocator, &[_]u8{}, elems);
// free the slice of encoded elements as they are not required anymore
for (elems) |e| {
self.allocator.free(e);
}
self.allocator.free(elems);
return out;
}
};
pub fn encode(allocator: *std.mem.Allocator, val: anytype) EncodeError![]u8 {
var encoder = Encoder{
.allocator = allocator,
};
return encoder.encode(val);
}
pub fn writeBinAny(allocator: *std.mem.Allocator, v: []const u8) EncodeError![]u8 {
if (v.len <= str8_max) {
return writeBin8(allocator, v);
} else if (v.len <= str16_max) {
return writeBin16(allocator, v);
}
return writeBin32(allocator, v);
}
fn writeBin8(allocator: *std.mem.Allocator, v: []const u8) EncodeError![]u8 {
var out = try allocator.alloc(u8, 2 + v.len);
out[0] = Format.bin8.toUint8();
out[1] = @intCast(u8, v.len);
std.mem.copy(u8, out[2 .. 2 + v.len], v);
return out;
}
fn writeBin16(allocator: *std.mem.Allocator, v: []const u8) EncodeError![]u8 {
var out = try allocator.alloc(u8, 1 + @sizeOf(u16) + v.len);
out[0] = Format.bin16.toUint8();
std.mem.writeIntBig(u16, out[1 .. 1 + @sizeOf(u16)], @intCast(u16, v.len));
std.mem.copy(u8, out[1 + @sizeOf(u16) .. 1 + @sizeOf(u16) + v.len], v);
return out;
}
fn writeBin32(allocator: *std.mem.Allocator, v: []const u8) EncodeError![]u8 {
var out = try allocator.alloc(u8, 1 + @sizeOf(u32) + v.len);
out[0] = Format.bin32.toUint8();
std.mem.writeIntBig(u32, out[1 .. 1 + @sizeOf(u32)], @intCast(u32, v.len));
std.mem.copy(u8, out[1 + @sizeOf(u32) .. 1 + @sizeOf(u32) + v.len], v);
return out;
}
pub fn writeStrAny(allocator: *std.mem.Allocator, v: []const u8) EncodeError![]u8 {
if (v.len <= fix_str_max) {
return writeFixStr(allocator, v);
} else if (v.len <= str8_max) {
return writeStr8(allocator, v);
} else if (v.len <= str16_max) {
return writeStr16(allocator, v);
}
return writeStr32(allocator, v);
}
fn writeFixStr(allocator: *std.mem.Allocator, v: []const u8) EncodeError![]u8 {
var out = try allocator.alloc(u8, 1 + v.len);
out[0] = (Format{ .fix_str = @intCast(u8, v.len) }).toUint8();
std.mem.copy(u8, out[1 .. 1 + v.len], v);
return out;
}
fn writeStr8(allocator: *std.mem.Allocator, v: []const u8) EncodeError![]u8 {
var out = try allocator.alloc(u8, 2 + v.len);
out[0] = Format.str8.toUint8();
out[1] = @intCast(u8, v.len);
std.mem.copy(u8, out[2 .. 2 + v.len], v);
return out;
}
fn writeStr16(allocator: *std.mem.Allocator, v: []const u8) EncodeError![]u8 {
var out = try allocator.alloc(u8, 1 + @sizeOf(u16) + v.len);
out[0] = Format.str16.toUint8();
std.mem.writeIntBig(u16, out[1 .. 1 + @sizeOf(u16)], @intCast(u16, v.len));
std.mem.copy(u8, out[1 + @sizeOf(u16) .. 1 + @sizeOf(u16) + v.len], v);
return out;
}
fn writeStr32(allocator: *std.mem.Allocator, v: []const u8) EncodeError![]u8 {
var out = try allocator.alloc(u8, 1 + @sizeOf(u32) + v.len);
out[0] = Format.str32.toUint8();
std.mem.writeIntBig(u32, out[1 .. 1 + @sizeOf(u32)], @intCast(u32, v.len));
std.mem.copy(u8, out[1 + @sizeOf(u32) .. 1 + @sizeOf(u32) + v.len], v);
return out;
}
pub fn writeFloatAny(allocator: *std.mem.Allocator, v: f64) EncodeError![]u8 {
if (v >= std.math.f32_min and v <= std.math.f32_max) {
return writeFloat32(allocator, @floatCast(f32, v));
}
return writeFloat64(allocator, v);
}
fn writeFloat32(allocator: *std.mem.Allocator, v: f32) EncodeError![]u8 {
var out = try allocator.alloc(u8, 1 + @sizeOf(f32));
out[0] = Format.float32.toUint8();
std.mem.writeIntBig(u32, out[1 .. 1 + @sizeOf(u32)], @bitCast(u32, v));
return out;
}
fn writeFloat64(allocator: *std.mem.Allocator, v: f64) EncodeError![]u8 {
var out = try allocator.alloc(u8, 1 + @sizeOf(f64));
out[0] = Format.float64.toUint8();
std.mem.writeIntBig(u64, out[1 .. 1 + @sizeOf(u64)], @bitCast(u64, v));
return out;
}
pub fn writeIntAny(allocator: *std.mem.Allocator, v: i64) EncodeError![]u8 {
if (v >= neg_int_fix_min and v <= 0) {
return writeNegativeFixInt(allocator, @intCast(i8, v));
} else if (v >= int8_min and v <= int8_max) {
return writeInt8(allocator, @intCast(i8, v));
} else if (v >= int16_min and v <= int16_max) {
return writeInt16(allocator, @intCast(i16, v));
} else if (v >= int32_min and v <= int32_max) {
return writeInt32(allocator, @intCast(i32, v));
}
return writeInt64(allocator, v);
}
fn writeNegativeFixInt(allocator: *std.mem.Allocator, v: i8) EncodeError![]u8 {
var out = try allocator.alloc(u8, @sizeOf(i8));
std.mem.writeIntBig(i8, out[0..@sizeOf(i8)], v);
return out;
}
fn writeInt8(allocator: *std.mem.Allocator, v: i8) EncodeError![]u8 {
var out = try allocator.alloc(u8, 1 + @sizeOf(i8));
out[0] = Format.int8.toUint8();
std.mem.writeIntBig(i8, out[1 .. 1 + @sizeOf(i8)], v);
return out;
}
fn writeInt16(allocator: *std.mem.Allocator, v: i16) EncodeError![]u8 {
var out = try allocator.alloc(u8, 1 + @sizeOf(i16));
out[0] = Format.int16.toUint8();
std.mem.writeIntBig(i16, out[1 .. 1 + @sizeOf(i16)], v);
return out;
}
fn writeInt32(allocator: *std.mem.Allocator, v: i32) EncodeError![]u8 {
var out = try allocator.alloc(u8, 1 + @sizeOf(i32));
out[0] = Format.int32.toUint8();
std.mem.writeIntBig(i32, out[1 .. 1 + @sizeOf(i32)], v);
return out;
}
fn writeInt64(allocator: *std.mem.Allocator, v: i64) EncodeError![]u8 {
var out = try allocator.alloc(u8, 1 + @sizeOf(i64));
out[0] = Format.int64.toUint8();
std.mem.writeIntBig(i64, out[1 .. 1 + @sizeOf(i64)], v);
return out;
}
pub fn writeUintAny(allocator: *std.mem.Allocator, v: u64) EncodeError![]u8 {
if (v <= pos_int_fix_max) {
return writePositiveFixInt(allocator, @intCast(u8, v));
} else if (v <= uint8_max) {
return writeUint8(allocator, @intCast(u8, v));
} else if (v <= uint16_max) {
return writeUint16(allocator, @intCast(u16, v));
} else if (v <= uint32_max) {
return writeUint32(allocator, @intCast(u32, v));
}
return writeUint64(allocator, v);
}
fn writePositiveFixInt(allocator: *std.mem.Allocator, v: u8) EncodeError![]u8 {
var out = try allocator.alloc(u8, @sizeOf(u8));
std.mem.writeIntBig(u8, out[0..@sizeOf(u8)], v);
return out;
}
fn writeUint8(allocator: *std.mem.Allocator, v: u8) EncodeError![]u8 {
var out = try allocator.alloc(u8, 1 + @sizeOf(u8));
out[0] = Format.uint8.toUint8();
std.mem.writeIntBig(u8, out[1 .. 1 + @sizeOf(u8)], v);
return out;
}
fn writeUint16(allocator: *std.mem.Allocator, v: u16) EncodeError![]u8 {
var out = try allocator.alloc(u8, 1 + @sizeOf(u16));
out[0] = Format.uint16.toUint8();
std.mem.writeIntBig(u16, out[1 .. 1 + @sizeOf(u16)], v);
return out;
}
fn writeUint32(allocator: *std.mem.Allocator, v: u32) EncodeError![]u8 {
var out = try allocator.alloc(u8, 1 + @sizeOf(u32));
out[0] = Format.uint32.toUint8();
std.mem.writeIntBig(u32, out[1 .. 1 + @sizeOf(u32)], v);
return out;
}
fn writeUint64(allocator: *std.mem.Allocator, v: u64) EncodeError![]u8 {
var out = try allocator.alloc(u8, 1 + @sizeOf(u64));
out[0] = Format.uint64.toUint8();
std.mem.writeIntBig(u64, out[1 .. 1 + @sizeOf(u64)], v);
return out;
}
pub fn writeNil(allocator: *std.mem.Allocator) EncodeError![]u8 {
var out = try allocator.alloc(u8, 1);
out[0] = Format.nil.toUint8();
return out;
}
pub fn writeBool(allocator: *std.mem.Allocator, v: bool) EncodeError![]u8 {
var out = try allocator.alloc(u8, 1);
switch (v) {
true => out[0] = Format.bool_true.toUint8(),
false => out[0] = Format.bool_false.toUint8(),
}
return out;
}
// encode native types
test "encode nil" {
const hex = "c0";
var bytes: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(bytes[0..], hex);
var encoded = try encode(std.testing.allocator, null);
testing.expect(std.mem.eql(u8, bytes[0..], encoded));
std.testing.allocator.free(encoded);
}
test "encode optional bool true" {
const hex = "c3";
var bytes: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(bytes[0..], hex);
var b: ?bool = true;
var encoded = try encode(std.testing.allocator, b);
testing.expect(std.mem.eql(u8, bytes[0..], encoded));
std.testing.allocator.free(encoded);
}
test "encode bool true" {
const hex = "c3";
var bytes: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(bytes[0..], hex);
var encoded = try encode(std.testing.allocator, true);
testing.expect(std.mem.eql(u8, bytes[0..], encoded));
std.testing.allocator.free(encoded);
}
test "encode uint64" {
const hex = "cf0000001caab5c3b3"; // 123123123123
var bytes: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(bytes[0..], hex);
var u: u64 = 123123123123;
var encoded = try encode(std.testing.allocator, u);
testing.expect(std.mem.eql(u8, bytes[0..], encoded));
std.testing.allocator.free(encoded);
}
test "encode comptime_int" {
const hex = "d3fffffffd2198eb05"; // -12321232123
var bytes: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(bytes[0..], hex);
var encoded = try encode(std.testing.allocator, -12321232123);
testing.expect(std.mem.eql(u8, bytes[0..], encoded));
std.testing.allocator.free(encoded);
}
test "encode int64" {
const hex = "d3fffffffd2198eb05"; // -12321232123
var bytes: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(bytes[0..], hex);
var i: i64 = -12321232123;
var encoded = try encode(std.testing.allocator, i);
testing.expect(std.mem.eql(u8, bytes[0..], encoded));
std.testing.allocator.free(encoded);
}
test "encode str8 (literal)" {
const hex = "d92368656c6c6f20776f726c642068656c6c6f20776f726c642068656c6c6f20776f726c64"; // "hello world hello world hello world"
var bytes: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(bytes[0..], hex);
var encoded = try encode(std.testing.allocator, "hello world hello world hello world");
testing.expect(std.mem.eql(u8, bytes[0..], encoded));
std.testing.allocator.free(encoded);
}
test "encode str8 (const)" {
const hex = "d92368656c6c6f20776f726c642068656c6c6f20776f726c642068656c6c6f20776f726c64"; // "hello world hello world hello world"
var bytes: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(bytes[0..], hex);
var str: []const u8 = "hello world hello world hello world";
var encoded = try encode(std.testing.allocator, str);
testing.expect(std.mem.eql(u8, bytes[0..], encoded));
std.testing.allocator.free(encoded);
}
test "encode str8" {
const hex = "d92368656c6c6f20776f726c642068656c6c6f20776f726c642068656c6c6f20776f726c64"; // "hello world hello world hello world"
var bytes: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(bytes[0..], hex);
var orig = "hello world hello world hello world";
var str: []u8 = try std.testing.allocator.alloc(u8, orig.len);
defer std.testing.allocator.free(str);
std.mem.copy(u8, str, orig);
var encoded = try encode(std.testing.allocator, str);
testing.expect(std.mem.eql(u8, bytes[0..], encoded));
std.testing.allocator.free(encoded);
}
test "encode fix array" {
const hex = "9acd03e8cd07d0cd0bb8cd0fa0cd1388cd1770cd1b58cd1f40cd2328cd2710"; // [1000,2000,3000,4000,5000,6000,7000,8000,9000,10000]
var bytes: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(bytes[0..], hex);
var array = [_]u16{ 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000 };
var encoded = try encode(std.testing.allocator, array);
testing.expect(std.mem.eql(u8, bytes[0..], encoded));
std.testing.allocator.free(encoded);
}
test "encode struct" {
const hex = "9acd03e8cd07d0cd0bb8cd0fa0cd1388cd1770cd1b58cd1f40cd2328cd2710"; // [1000,2000,3000,4000,5000,6000,7000,8000,9000,10000]
var bytes: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(bytes[0..], hex);
const s = struct {
string: []const u8 = "string",
int: i32 = -32,
uint: u64 = 64,
boul: bool = true,
};
var _s = s{};
var encoded = try encode(std.testing.allocator, &_s);
// testing.expect(std.mem.eql(u8, bytes[0..], encoded));
// std.debug.print("map: {}\n", .{encoded});
std.testing.allocator.free(encoded);
}
test "encoder set encode as binary" {
var encoder = Encoder{
.allocator = std.testing.allocator,
};
defer encoder.free();
try encoder.encodeAsBinary("hello");
} | src/encode.zig |
const std = @import("std");
const statemachine = @import("../state-machine.zig");
const gamepad = @import("../gamepad.zig");
const w4 = @import("../wasm4.zig");
const statusbar = @import("../components/status-bar.zig");
const projectile = @import("../components/projectile.zig");
const gavels = @import("../components/gavel.zig");
const Facing = projectile.Facing;
const Projectile = projectile.Projectile;
const sprites = @import("../assets/sprites.zig");
const SIDE_PADDING: u8 = 4;
const SCREEN_SIZE: u8 = 160;
const SURVIVE_TIME: u32 = 10;
const ACTION_COOLDOWN: u32 = 1 * 10;
const GAVEL_SPAWN_CHANCE: u8 = 245;
pub const Parliament = struct {
px: u8 = SCREEN_SIZE / 2,
py: u8 = SCREEN_SIZE / 2,
buzzing: u32 = 0,
confidence: u32 = 0,
rnd: *std.rand.Random,
ticker: u32 = 0,
sample_rate: u8 = 1, // how often do we move?
velocity: u8 = 1,
inverted: bool = false,
cooldown: u32 = 0,
facing: Facing = .UP,
hit: bool = false,
// static array for keeping all of the projectiles
projectiles: [128]Projectile = undefined,
// stack pointer (points to top)
proj_index: u32 = 0, // index for keeping track of the projectile stack
timebar: statusbar.StatusBar = undefined,
pub fn init(rnd: *std.rand.Random) Parliament {
return Parliament{ .rnd = rnd, .timebar = statusbar.StatusBar{
.value = SURVIVE_TIME,
.maximum_value = SURVIVE_TIME,
.locy = 8,
} };
}
fn reset(self: *@This()) void {
self.timebar.value = SURVIVE_TIME;
self.ticker = 0;
self.px = SCREEN_SIZE / 2;
self.py = SCREEN_SIZE / 2;
self.proj_index = 0;
}
pub fn update(self: *@This(), state: *statemachine.StateMachine, pl: *gamepad.GamePad) void {
// background
drawCommons();
w4.DRAW_COLORS.* = 0x24;
w4.text("PARLIAMENT", 0, 0);
w4.text("TIME", SCREEN_SIZE - (4 * 8), 0);
if (self.ticker % self.sample_rate == 0) {
self.handleInput(state, pl);
}
// update time
if (self.ticker % 60 == 0 and self.timebar.value > 0) {
self.timebar.value -= 1;
}
self.timebar.draw();
// projectiles
self.randomGavelSpawn();
self.updateProjectiles();
self.draw();
self.checkCollisions();
if (self.timebar.value == 0) {
// reset states
self.reset();
// go back to the party
state.change(.FROM_COMMONS_TRANSITION);
}
}
fn updateProjectiles(self: *@This()) void {
// draw all of the projectiles
if (self.proj_index != 0) {
for (self.projectiles) |*proj, i| {
// TODO: do we need to check if objects are off screen?
if (i == self.proj_index) {
break;
}
proj.update();
proj.draw();
}
}
}
fn draw(self: *@This()) void {
var xOff: u32 = 0;
if (self.ticker % 20 > 10) {
xOff = 16;
}
w4.DRAW_COLORS.* = 0x0432;
w4.blitSub(sprites.boris.data, @intCast(i32, self.px) - @divTrunc(sprites.boris.width, 2), @intCast(i32, self.py), // x, y
sprites.boris.height, sprites.boris.height, // w, h; Assumes square
xOff, 0, // src_x, src_y
sprites.boris.width, // Assumes stride and width are equal
sprites.boris.flags);
self.ticker += 1;
// reduce cooldown if we can
if (self.cooldown != 0) {
self.cooldown -= 1;
}
}
fn buttonDown(self: *@This(), pl: *const gamepad.GamePad) bool {
if (!self.inverted) {
if (pl.isHeld(w4.BUTTON_DOWN)) {
self.facing = .DOWN;
return true;
}
} else {
if (pl.isHeld(w4.BUTTON_UP)) {
self.facing = .UP;
return true;
}
}
return false;
}
fn buttonUp(self: *@This(), pl: *const gamepad.GamePad) bool {
if (!self.inverted) {
if (pl.isHeld(w4.BUTTON_UP)) {
self.facing = .UP;
return true;
}
} else {
if (pl.isHeld(w4.BUTTON_DOWN)) {
self.facing = .DOWN;
return true;
}
}
return false;
}
fn buttonRight(self: *@This(), pl: *const gamepad.GamePad) bool {
if (!self.inverted) {
if (pl.isHeld(w4.BUTTON_RIGHT)) {
self.facing = .RIGHT;
return true;
}
} else {
if (pl.isHeld(w4.BUTTON_LEFT)) {
self.facing = .LEFT;
return true;
}
}
return false;
}
fn buttonLeft(self: *@This(), pl: *const gamepad.GamePad) bool {
if (!self.inverted) {
if (pl.isHeld(w4.BUTTON_LEFT)) {
self.facing = .LEFT;
return true;
}
} else {
if (pl.isHeld(w4.BUTTON_RIGHT)) {
self.facing = .RIGHT;
return true;
}
}
return false;
}
fn handleInput(self: *@This(), _: *statemachine.StateMachine, pl: *const gamepad.GamePad) void {
var button_pressed = false;
// bounds check
if (self.py <= SCREEN_SIZE - SIDE_PADDING - (sprites.boris.height)) {
if (self.buttonDown(pl) and !button_pressed) {
self.py += self.velocity;
button_pressed = true;
}
}
if (self.py >= SIDE_PADDING) {
if (self.buttonUp(pl) and !button_pressed) {
self.py -= self.velocity;
button_pressed = true;
}
}
if (self.px <= SCREEN_SIZE - SIDE_PADDING) {
if (self.buttonRight(pl) and !button_pressed) {
self.px += self.velocity;
button_pressed = true;
}
}
if (self.px >= SIDE_PADDING + (sprites.boris.width / 2)) {
if (self.buttonLeft(pl) and !button_pressed) {
self.px -= self.velocity;
button_pressed = true;
}
}
if (pl.isPressed(w4.BUTTON_1) and self.cooldown == 0) {
self.cooldown = ACTION_COOLDOWN;
self.throw();
}
}
fn pushProjectile(self: *@This(), p: Projectile) void {
self.projectiles[self.proj_index] = p;
// if we reach end, circle around
self.proj_index += 1;
if (self.proj_index >= 128) {
self.proj_index = 0;
}
}
fn popProjectile(self: *@This()) Projectile {
if (self.proj_index >= 1) {
self.proj_index -= 1;
return self.projectiles[self.proj_index + 1];
} else {
return undefined;
}
}
fn throw(self: *@This()) void {
const p = Projectile.init(sprites.vax, self.px, self.py, self.facing);
self.pushProjectile(p);
// please NEVER delete
w4.tracef("%d", self.rnd.int(u32));
}
fn randomGavelSpawn(self: *@This()) void {
const ri = self.rnd.int(u8);
if (ri > GAVEL_SPAWN_CHANCE) {
var g = gavels.randomGavel(self.rnd);
g.player_targetable = true;
self.pushProjectile(g);
}
}
fn checkCollisions(self: *@This()) void {
for (self.projectiles) |*proj| {
// check if any gavels have collided with player
if (proj.player_targetable and proj.onScreen()) {
if (proj.inArea(self.px, self.py, 4)) {
self.hit = true;
w4.trace("HIT");
}
}
}
}
};
fn drawCommons() void {
w4.DRAW_COLORS.* = 0x0432;
w4.blit(sprites.commons.data, 0, 0, // x, y
sprites.commons.width, sprites.commons.height, sprites.commons.flags);
// XXX: Hack the benches in. This will need to change.
const b_width = sprites.bench.width;
const b_height = sprites.bench.height;
const x_flip = 0x2;
const xs = .{ 17, 17 * 2 + b_width, 160 - 17 * 2 - b_width * 2, 160 - 17 - b_width };
const ys = .{ 160 - 17 - b_height, 160 - 17 * 2 - b_height * 2 };
w4.blit(sprites.bench.data, xs[0], ys[0], // x, y
sprites.bench.width, sprites.bench.height, sprites.bench.flags);
w4.blit(sprites.bench.data, xs[1], ys[0], // x, y
sprites.bench.width, sprites.bench.height, sprites.bench.flags);
w4.blit(sprites.bench.data, xs[0], ys[1], // x, y
sprites.bench.width, sprites.bench.height, sprites.bench.flags);
w4.blit(sprites.bench.data, xs[1], ys[1], // x, y
sprites.bench.width, sprites.bench.height, sprites.bench.flags);
w4.blit(sprites.bench.data, xs[2], ys[0], // x, y
sprites.bench.width, sprites.bench.height, sprites.bench.flags | x_flip);
w4.blit(sprites.bench.data, xs[3], ys[0], // x, y
sprites.bench.width, sprites.bench.height, sprites.bench.flags | x_flip);
w4.blit(sprites.bench.data, xs[2], ys[1], // x, y
sprites.bench.width, sprites.bench.height, sprites.bench.flags | x_flip);
w4.blit(sprites.bench.data, xs[3], ys[1], // x, y
sprites.bench.width, sprites.bench.height, sprites.bench.flags | x_flip);
} | src/screens/house-of-commons.zig |
const std = @import("std");
const builtin = std.builtin;
const platform = @import("platform.zig");
const w3 = @import("wasm3.zig");
const vfs = @import("vfs.zig");
const task = @import("task.zig");
const process = @import("process.zig");
const time = @import("time.zig");
const utsname = @import("utsname.zig");
const tmpfs = @import("fs/tmpfs.zig");
const zipfs = @import("fs/zipfs.zig");
var kernel_flags = .{
.coop_multitask = true, // Run in cooperative multitasking mode
.save_cpu = true, // Use `hlt` so we don't spike CPU usage
.init_args = "init\x00default\x00",
};
extern fn allSanityChecks() callconv(.C) void;
pub inline fn nop() void {}
pub fn panic(message: []const u8, stack_trace: ?*builtin.StackTrace) noreturn {
@setCold(true);
if (platform.early()) {
platform.earlyprintk("\nKERNEL PANIC! Early system initialization failure: ");
platform.earlyprintk(message);
platform.earlyprintk("\r\n");
platform.earlyprintf("(!) -> 0x{x}\r\n", .{@returnAddress()});
if (@errorReturnTrace()) |trace| {
for (trace.instruction_address[0..trace.index]) |func, i| {
platform.earlyprintf("{} -> 0x{x}\r\n", .{ i, func });
}
} else {
platform.earlyprintk("Kernel built without stack trace support.\r\n");
}
platform.earlyprintk("End stack trace.\r\n");
platform.earlyprintk("\r\nWell, that didn't go well. Perhaps we should try again? Press the power button to reset.\r\n");
}
platform.halt();
}
// Generated at build time
const initrd_zip = @embedFile("../output/temp/initrd.zip");
var prochost: process.ProcessHost = undefined;
var terminated: bool = false;
pub fn timerTick() void {
time.tick();
if (!kernel_flags.coop_multitask) {
platform.beforeYield();
prochost.scheduler.yieldCurrent();
}
}
pub fn main() void {
// Initialize platform
platform.init();
// Run sanity tests
platform.earlyprintk("Running hardware integrity tests. If the system crashes during these, that's your problem, not mine.\r\n");
allSanityChecks();
platform.earlyprintk("Tests passed.\r\n");
// Show kernel information
time.init();
var info = utsname.uname();
platform.earlyprintf("{} {} {} {}\r\n", .{ info.sys_name, info.release, info.version, info.machine });
platform.earlyprintk("(C) 2020 Ronsor Labs. This software is protected by domestic and international copyright law.\r\n\r\n");
platform.earlyprintf("Boot timestamp: {}.\r\n", .{ time.getClock(.real) });
// Create allocator. TODO: good one
const static_size = 32 * 1024 * 1024;
var big_buffer = platform.internal_malloc(static_size).?;
var allocator = &std.heap.FixedBufferAllocator.init(big_buffer[0..static_size]).allocator;
var dev_initrd = vfs.ReadOnlyNode.init(initrd_zip);
platform.earlyprintf("Size of initial ramdisk in bytes: {}.\r\n", .{dev_initrd.stat.size});
// TODO: support other formats
var rootfs = zipfs.Fs.mount(allocator, &dev_initrd, null) catch @panic("Can't mount initrd!");
platform.earlyprintk("Mounted initial ramdisk.\r\n");
// Setup process host
prochost = process.ProcessHost.init(allocator) catch @panic("Can't initialize process host!");
platform.setTimer(timerTick);
var init_file = rootfs.findRecursive("/bin/init") catch @panic("Can't find init binary!");
var init_data = allocator.alloc(u8, init_file.node.stat.size) catch @panic("Can't read init binary!");
_ = init_file.node.read(0, init_data) catch unreachable;
platform.earlyprintf("Size of /bin/init in bytes: {}.\r\n", .{init_data.len});
var console_node = platform.openConsole();
_ = console_node.write(0, "Initialized /dev/console.\r\n") catch @panic("Can't initialize early console!");
var init_proc_options = process.Process.Arg{
.name = "/bin/init",
.argv = kernel_flags.init_args,
.parent_pid = task.Task.KernelParentId,
.fds = &[_]process.Fd{
.{ .num = 0, .node = &console_node },
.{ .num = 1, .node = &console_node },
.{ .num = 2, .node = &console_node },
.{ .num = 3, .node = rootfs, .preopen = true, .name = "/" },
},
.runtime_arg = .{
.wasm = .{
.wasm_image = init_data,
},
},
};
_ = prochost.createProcess(init_proc_options) catch @panic("Can't create init process!");
while (!terminated) {
prochost.scheduler.loopOnce();
var init_proc = prochost.get(0);
if (init_proc) |proc| {
if (proc.task().killed) {
_ = proc.task().wait(false);
var exit_code = proc.exit_code;
platform.earlyprintf("init exited with code: {}\r\n", .{exit_code});
terminated = true;
}
}
if (kernel_flags.save_cpu) platform.waitTimer(1);
}
// Should be unreachable;
@panic("init exited!");
} | kernel/main.zig |
const std = @import("std");
const sf = @import("../sfml.zig");
const Packet = @This();
// Constructor/destructor
/// Inits an empty packet
pub fn create() !Packet {
var pack = sf.c.sfPacket_create();
if (pack) |p| {
return Packet{ ._ptr = p };
} else
return sf.Error.nullptrUnknownReason;
}
/// Destroys a packet
pub fn destroy(self: *Packet) void {
sf.c.sfPacket_destroy(self._ptr);
}
/// Copies a packet
pub fn copy(self: Packet) !Packet {
var pack = sf.c.sfPacket_copy(self._ptr);
if (pack) |p| {
return Packet{ ._ptr = p };
} else
return sf.Error.nullptrUnknownReason;
}
// Getters/Setters
/// Empties this packet of its data
pub fn clear(self: *Packet) void {
sf.c.sfPacket_clear(self._ptr);
}
/// Gets a const slice of this packet's content
/// Do not store, pointer may be changed when editing data
/// Be careful when using that in conjunction with read or reader
/// This gets all the data and does not move the reader
pub fn getData(self: Packet) []const u8 {
const data = sf.c.sfPacket_getData(self._ptr);
const size = sf.c.sfPacket_getDataSize(self._ptr);
var slice: []const u8 = undefined;
slice.ptr = @ptrCast([*]const u8, data);
slice.len = size;
return slice;
}
/// Gets the data size in bytes inside this packet
pub fn getDataSize(self: Packet) usize {
return sf.c.sfPacket_getDataSize(self._ptr);
}
/// Appends bytes to the packet. You can also use the writer()
pub fn append(self: *Packet, data: []const u8) !void {
const size_a = self.getDataSize();
sf.c.sfPacket_append(self._ptr, data.ptr, data.len);
const size_b = self.getDataSize();
const size = size_b - size_a;
if (size != data.len)
return sf.Error.cannotWriteToPacket;
}
/// Returns false if the packet is ready for reading, true if there is no more data
pub fn isAtEnd(self: Packet) bool {
return sf.c.sfPacket_endOfPacket(self._ptr) != 0;
}
/// Returns an error if last read operation failed
fn checkLastRead(self: Packet) !void {
if (sf.c.sfPacket_canRead(self._ptr) == 0)
return sf.Error.couldntRead;
}
/// Reads a type from the packet
/// Slightly faster than using a reader for bigger types
pub fn read(self: *Packet, comptime T: type) !T {
const res: T = switch (T) {
bool => (sf.c.sfPacket_readBool(self._ptr) != 0),
i8 => sf.c.sfPacket_readInt8(self._ptr),
u8 => sf.c.sfPacket_readUint8(self._ptr),
i16 => sf.c.sfPacket_readInt16(self._ptr),
u16 => sf.c.sfPacket_readUint16(self._ptr),
i32 => sf.c.sfPacket_readInt32(self._ptr),
u32 => sf.c.sfPacket_readUint32(self._ptr),
f32 => sf.c.sfPacket_readFloat(self._ptr),
f64 => sf.c.sfPacket_readDouble(self._ptr),
[*:0]const u8 => sf.c.sfPacket_readString(self._ptr),
[*:0]const u16 => sf.c.sfPacket_readWideString(self._ptr),
else => @compileError("Can't read type " ++ @typeName(T) ++ " from packet")
};
try self.checkLastRead();
return res;
}
/// Writes a value to the packet
/// Slightly faster than using a writer for bigger types
pub fn write(self: *Packet, comptime T: type, value: T) !void {
// TODO: find how to make this safer
switch (T) {
bool => sf.c.sfPacket_writeBool(self._ptr, @boolToInt(value)),
i8 => sf.c.sfPacket_writeInt8(self._ptr, value),
u8 => sf.c.sfPacket_writeUint8(self._ptr, value),
i16 => sf.c.sfPacket_writeInt16(self._ptr, value),
u16 => sf.c.sfPacket_writeUint16(self._ptr, value),
i32 => sf.c.sfPacket_writeInt32(self._ptr, value),
u32 => sf.c.sfPacket_writeUint32(self._ptr, value),
f32 => sf.c.sfPacket_writeFloat(self._ptr, value),
f64 => sf.c.sfPacket_writeDouble(self._ptr, value),
[*:0]const u8 => sf.c.sfPacket_writeString(self._ptr, value),
[*:0]const u16 => sf.c.sfPacket_writeWideString(self._ptr, value),
else => @compileError("Can't write type " ++ @typeName(T) ++ " to packet")
}
}
/// Writer type for a packet
pub const Writer = std.io.Writer(*Packet, sf.Error, writeFn);
/// Initializes a Writer which will write to the packet
/// Slightly slower than write for bigger types but more convinient for some things
pub fn writer(self: *Packet) Writer {
return .{ .context = self };
}
/// Write function for the writer
fn writeFn(self: *Packet, m: []const u8) sf.Error!usize {
// TODO: find out if I can have better safety here
const size_a = self.getDataSize();
sf.c.sfPacket_append(self._ptr, m.ptr, m.len);
const size_b = self.getDataSize();
const size = size_b - size_a;
if (m.len != 0 and size == 0)
return sf.Error.cannotWriteToPacket;
return size;
}
/// Reader type for a packet
pub const Reader = std.io.Reader(*Packet, sf.Error, readFn);
/// Initializes a Reader which will read the packet's bytes
/// Slightly slower than read for bigger types but more convinient for some things
pub fn reader(self: *Packet) Reader {
return .{ .context = self };
}
/// Read function for the reader
fn readFn(self: *Packet, b: []u8) sf.Error!usize {
for (b) |*byte, i| {
if (sf.c.sfPacket_endOfPacket(self._ptr) != 0)
return i;
const val = sf.c.sfPacket_readUint8(self._ptr);
try self.checkLastRead();
byte.* = val;
}
return b.len;
}
/// Pointer to the csfml structure
_ptr: *sf.c.sfPacket,
test "packet: reading and writing" {
const tst = std.testing;
var pack1 = try Packet.create();
defer pack1.destroy();
// writing to the packet
// using its methods
try pack1.write(u16, 1999);
try pack1.write(bool, true);
// using a writer
{
var w = pack1.writer();
try w.writeIntNative(u64, 12345678);
try w.writeAll("oh:");
}
// using append
const str = "abc";
try pack1.append(str);
try tst.expectEqual(@as(usize, 17), pack1.getDataSize());
var pack2 = try pack1.copy();
defer pack2.destroy();
pack1.clear();
try tst.expectEqual(@as(usize, 0), pack1.getDataSize());
try tst.expect(pack1.isAtEnd());
// reading tests
// read method
try tst.expectEqual(@as(u16, 1999), try pack2.read(u16));
try tst.expect(try pack2.read(bool));
// reader
{
var buf: [16]u8 = undefined;
var r = pack2.reader();
try tst.expectEqual(@as(u64, 12345678), try r.readIntNative(u64));
var count = try r.readAll(&buf);
try tst.expectEqual(@as(usize, 6), count);
try tst.expectEqualStrings("oh:abc", buf[0..count]);
}
// getdata
const dat = pack2.getData();
try tst.expectEqual(@as(usize, 17), dat.len);
try tst.expectEqualStrings("h:a", dat[12..15]);
try tst.expect(pack2.isAtEnd());
} | src/sfml/network/Packet.zig |
const std = @import("../std.zig");
const math = std.math;
const expect = std.testing.expect;
/// Returns 2 raised to the power of x (2^x).
///
/// Special Cases:
/// - exp2(+inf) = +inf
/// - exp2(nan) = nan
pub fn exp2(x: anytype) @TypeOf(x) {
const T = @TypeOf(x);
return switch (T) {
f32 => exp2_32(x),
f64 => exp2_64(x),
else => @compileError("exp2 not implemented for " ++ @typeName(T)),
};
}
const exp2ft = [_]f64{
0x1.6a09e667f3bcdp-1,
0x1.7a11473eb0187p-1,
0x1.8ace5422aa0dbp-1,
0x1.9c49182a3f090p-1,
0x1.ae89f995ad3adp-1,
0x1.c199bdd85529cp-1,
0x1.d5818dcfba487p-1,
0x1.ea4afa2a490dap-1,
0x1.0000000000000p+0,
0x1.0b5586cf9890fp+0,
0x1.172b83c7d517bp+0,
0x1.2387a6e756238p+0,
0x1.306fe0a31b715p+0,
0x1.3dea64c123422p+0,
0x1.4bfdad5362a27p+0,
0x1.5ab07dd485429p+0,
};
fn exp2_32(x: f32) f32 {
const tblsiz = @intCast(u32, exp2ft.len);
const redux: f32 = 0x1.8p23 / @intToFloat(f32, tblsiz);
const P1: f32 = 0x1.62e430p-1;
const P2: f32 = 0x1.ebfbe0p-3;
const P3: f32 = 0x1.c6b348p-5;
const P4: f32 = 0x1.3b2c9cp-7;
var u = @bitCast(u32, x);
const ix = u & 0x7FFFFFFF;
// |x| > 126
if (ix > 0x42FC0000) {
// nan
if (ix > 0x7F800000) {
return x;
}
// x >= 128
if (u >= 0x43000000 and u < 0x80000000) {
return x * 0x1.0p127;
}
// x < -126
if (u >= 0x80000000) {
if (u >= 0xC3160000 or u & 0x000FFFF != 0) {
math.doNotOptimizeAway(-0x1.0p-149 / x);
}
// x <= -150
if (u >= 0x3160000) {
return 0;
}
}
}
// |x| <= 0x1p-25
else if (ix <= 0x33000000) {
return 1.0 + x;
}
var uf = x + redux;
var i_0 = @bitCast(u32, uf);
i_0 += tblsiz / 2;
const k = i_0 / tblsiz;
// NOTE: musl relies on undefined overflow shift behaviour. Appears that this produces the
// intended result but should confirm how GCC/Clang handle this to ensure.
const uk = @bitCast(f64, @as(u64, 0x3FF + k) << 52);
i_0 &= tblsiz - 1;
uf -= redux;
const z: f64 = x - uf;
var r: f64 = exp2ft[i_0];
const t: f64 = r * z;
r = r + t * (P1 + z * P2) + t * (z * z) * (P3 + z * P4);
return @floatCast(f32, r * uk);
}
const exp2dt = [_]f64{
// exp2(z + eps) eps
0x1.6a09e667f3d5dp-1, 0x1.9880p-44,
0x1.6b052fa751744p-1, 0x1.8000p-50,
0x1.6c012750bd9fep-1, -0x1.8780p-45,
0x1.6cfdcddd476bfp-1, 0x1.ec00p-46,
0x1.6dfb23c651a29p-1, -0x1.8000p-50,
0x1.6ef9298593ae3p-1, -0x1.c000p-52,
0x1.6ff7df9519386p-1, -0x1.fd80p-45,
0x1.70f7466f42da3p-1, -0x1.c880p-45,
0x1.71f75e8ec5fc3p-1, 0x1.3c00p-46,
0x1.72f8286eacf05p-1, -0x1.8300p-44,
0x1.73f9a48a58152p-1, -0x1.0c00p-47,
0x1.74fbd35d7ccfcp-1, 0x1.f880p-45,
0x1.75feb564267f1p-1, 0x1.3e00p-47,
0x1.77024b1ab6d48p-1, -0x1.7d00p-45,
0x1.780694fde5d38p-1, -0x1.d000p-50,
0x1.790b938ac1d00p-1, 0x1.3000p-49,
0x1.7a11473eb0178p-1, -0x1.d000p-49,
0x1.7b17b0976d060p-1, 0x1.0400p-45,
0x1.7c1ed0130c133p-1, 0x1.0000p-53,
0x1.7d26a62ff8636p-1, -0x1.6900p-45,
0x1.7e2f336cf4e3bp-1, -0x1.2e00p-47,
0x1.7f3878491c3e8p-1, -0x1.4580p-45,
0x1.80427543e1b4ep-1, 0x1.3000p-44,
0x1.814d2add1071ap-1, 0x1.f000p-47,
0x1.82589994ccd7ep-1, -0x1.1c00p-45,
0x1.8364c1eb942d0p-1, 0x1.9d00p-45,
0x1.8471a4623cab5p-1, 0x1.7100p-43,
0x1.857f4179f5bbcp-1, 0x1.2600p-45,
0x1.868d99b4491afp-1, -0x1.2c40p-44,
0x1.879cad931a395p-1, -0x1.3000p-45,
0x1.88ac7d98a65b8p-1, -0x1.a800p-45,
0x1.89bd0a4785800p-1, -0x1.d000p-49,
0x1.8ace5422aa223p-1, 0x1.3280p-44,
0x1.8be05bad619fap-1, 0x1.2b40p-43,
0x1.8cf3216b54383p-1, -0x1.ed00p-45,
0x1.8e06a5e08664cp-1, -0x1.0500p-45,
0x1.8f1ae99157807p-1, 0x1.8280p-45,
0x1.902fed0282c0ep-1, -0x1.cb00p-46,
0x1.9145b0b91ff96p-1, -0x1.5e00p-47,
0x1.925c353aa2ff9p-1, 0x1.5400p-48,
0x1.93737b0cdc64ap-1, 0x1.7200p-46,
0x1.948b82b5f98aep-1, -0x1.9000p-47,
0x1.95a44cbc852cbp-1, 0x1.5680p-45,
0x1.96bdd9a766f21p-1, -0x1.6d00p-44,
0x1.97d829fde4e2ap-1, -0x1.1000p-47,
0x1.98f33e47a23a3p-1, 0x1.d000p-45,
0x1.9a0f170ca0604p-1, -0x1.8a40p-44,
0x1.9b2bb4d53ff89p-1, 0x1.55c0p-44,
0x1.9c49182a3f15bp-1, 0x1.6b80p-45,
0x1.9d674194bb8c5p-1, -0x1.c000p-49,
0x1.9e86319e3238ep-1, 0x1.7d00p-46,
0x1.9fa5e8d07f302p-1, 0x1.6400p-46,
0x1.a0c667b5de54dp-1, -0x1.5000p-48,
0x1.a1e7aed8eb8f6p-1, 0x1.9e00p-47,
0x1.a309bec4a2e27p-1, 0x1.ad80p-45,
0x1.a42c980460a5dp-1, -0x1.af00p-46,
0x1.a5503b23e259bp-1, 0x1.b600p-47,
0x1.a674a8af46213p-1, 0x1.8880p-44,
0x1.a799e1330b3a7p-1, 0x1.1200p-46,
0x1.a8bfe53c12e8dp-1, 0x1.6c00p-47,
0x1.a9e6b5579fcd2p-1, -0x1.9b80p-45,
0x1.ab0e521356fb8p-1, 0x1.b700p-45,
0x1.ac36bbfd3f381p-1, 0x1.9000p-50,
0x1.ad5ff3a3c2780p-1, 0x1.4000p-49,
0x1.ae89f995ad2a3p-1, -0x1.c900p-45,
0x1.afb4ce622f367p-1, 0x1.6500p-46,
0x1.b0e07298db790p-1, 0x1.fd40p-45,
0x1.b20ce6c9a89a9p-1, 0x1.2700p-46,
0x1.b33a2b84f1a4bp-1, 0x1.d470p-43,
0x1.b468415b747e7p-1, -0x1.8380p-44,
0x1.b59728de5593ap-1, 0x1.8000p-54,
0x1.b6c6e29f1c56ap-1, 0x1.ad00p-47,
0x1.b7f76f2fb5e50p-1, 0x1.e800p-50,
0x1.b928cf22749b2p-1, -0x1.4c00p-47,
0x1.ba5b030a10603p-1, -0x1.d700p-47,
0x1.bb8e0b79a6f66p-1, 0x1.d900p-47,
0x1.bcc1e904bc1ffp-1, 0x1.2a00p-47,
0x1.bdf69c3f3a16fp-1, -0x1.f780p-46,
0x1.bf2c25bd71db8p-1, -0x1.0a00p-46,
0x1.c06286141b2e9p-1, -0x1.1400p-46,
0x1.c199bdd8552e0p-1, 0x1.be00p-47,
0x1.c2d1cd9fa64eep-1, -0x1.9400p-47,
0x1.c40ab5fffd02fp-1, -0x1.ed00p-47,
0x1.c544778fafd15p-1, 0x1.9660p-44,
0x1.c67f12e57d0cbp-1, -0x1.a100p-46,
0x1.c7ba88988c1b6p-1, -0x1.8458p-42,
0x1.c8f6d9406e733p-1, -0x1.a480p-46,
0x1.ca3405751c4dfp-1, 0x1.b000p-51,
0x1.cb720dcef9094p-1, 0x1.1400p-47,
0x1.ccb0f2e6d1689p-1, 0x1.0200p-48,
0x1.cdf0b555dc412p-1, 0x1.3600p-48,
0x1.cf3155b5bab3bp-1, -0x1.6900p-47,
0x1.d072d4a0789bcp-1, 0x1.9a00p-47,
0x1.d1b532b08c8fap-1, -0x1.5e00p-46,
0x1.d2f87080d8a85p-1, 0x1.d280p-46,
0x1.d43c8eacaa203p-1, 0x1.1a00p-47,
0x1.d5818dcfba491p-1, 0x1.f000p-50,
0x1.d6c76e862e6a1p-1, -0x1.3a00p-47,
0x1.d80e316c9834ep-1, -0x1.cd80p-47,
0x1.d955d71ff6090p-1, 0x1.4c00p-48,
0x1.da9e603db32aep-1, 0x1.f900p-48,
0x1.dbe7cd63a8325p-1, 0x1.9800p-49,
0x1.dd321f301b445p-1, -0x1.5200p-48,
0x1.de7d5641c05bfp-1, -0x1.d700p-46,
0x1.dfc97337b9aecp-1, -0x1.6140p-46,
0x1.e11676b197d5ep-1, 0x1.b480p-47,
0x1.e264614f5a3e7p-1, 0x1.0ce0p-43,
0x1.e3b333b16ee5cp-1, 0x1.c680p-47,
0x1.e502ee78b3fb4p-1, -0x1.9300p-47,
0x1.e653924676d68p-1, -0x1.5000p-49,
0x1.e7a51fbc74c44p-1, -0x1.7f80p-47,
0x1.e8f7977cdb726p-1, -0x1.3700p-48,
0x1.ea4afa2a490e8p-1, 0x1.5d00p-49,
0x1.eb9f4867ccae4p-1, 0x1.61a0p-46,
0x1.ecf482d8e680dp-1, 0x1.5500p-48,
0x1.ee4aaa2188514p-1, 0x1.6400p-51,
0x1.efa1bee615a13p-1, -0x1.e800p-49,
0x1.f0f9c1cb64106p-1, -0x1.a880p-48,
0x1.f252b376bb963p-1, -0x1.c900p-45,
0x1.f3ac948dd7275p-1, 0x1.a000p-53,
0x1.f50765b6e4524p-1, -0x1.4f00p-48,
0x1.f6632798844fdp-1, 0x1.a800p-51,
0x1.f7bfdad9cbe38p-1, 0x1.abc0p-48,
0x1.f91d802243c82p-1, -0x1.4600p-50,
0x1.fa7c1819e908ep-1, -0x1.b0c0p-47,
0x1.fbdba3692d511p-1, -0x1.0e00p-51,
0x1.fd3c22b8f7194p-1, -0x1.0de8p-46,
0x1.fe9d96b2a23eep-1, 0x1.e430p-49,
0x1.0000000000000p+0, 0x0.0000p+0,
0x1.00b1afa5abcbep+0, -0x1.3400p-52,
0x1.0163da9fb3303p+0, -0x1.2170p-46,
0x1.02168143b0282p+0, 0x1.a400p-52,
0x1.02c9a3e77806cp+0, 0x1.f980p-49,
0x1.037d42e11bbcap+0, -0x1.7400p-51,
0x1.04315e86e7f89p+0, 0x1.8300p-50,
0x1.04e5f72f65467p+0, -0x1.a3f0p-46,
0x1.059b0d315855ap+0, -0x1.2840p-47,
0x1.0650a0e3c1f95p+0, 0x1.1600p-48,
0x1.0706b29ddf71ap+0, 0x1.5240p-46,
0x1.07bd42b72a82dp+0, -0x1.9a00p-49,
0x1.0874518759bd0p+0, 0x1.6400p-49,
0x1.092bdf66607c8p+0, -0x1.0780p-47,
0x1.09e3ecac6f383p+0, -0x1.8000p-54,
0x1.0a9c79b1f3930p+0, 0x1.fa00p-48,
0x1.0b5586cf988fcp+0, -0x1.ac80p-48,
0x1.0c0f145e46c8ap+0, 0x1.9c00p-50,
0x1.0cc922b724816p+0, 0x1.5200p-47,
0x1.0d83b23395dd8p+0, -0x1.ad00p-48,
0x1.0e3ec32d3d1f3p+0, 0x1.bac0p-46,
0x1.0efa55fdfa9a6p+0, -0x1.4e80p-47,
0x1.0fb66affed2f0p+0, -0x1.d300p-47,
0x1.1073028d7234bp+0, 0x1.1500p-48,
0x1.11301d0125b5bp+0, 0x1.c000p-49,
0x1.11edbab5e2af9p+0, 0x1.6bc0p-46,
0x1.12abdc06c31d5p+0, 0x1.8400p-49,
0x1.136a814f2047dp+0, -0x1.ed00p-47,
0x1.1429aaea92de9p+0, 0x1.8e00p-49,
0x1.14e95934f3138p+0, 0x1.b400p-49,
0x1.15a98c8a58e71p+0, 0x1.5300p-47,
0x1.166a45471c3dfp+0, 0x1.3380p-47,
0x1.172b83c7d5211p+0, 0x1.8d40p-45,
0x1.17ed48695bb9fp+0, -0x1.5d00p-47,
0x1.18af9388c8d93p+0, -0x1.c880p-46,
0x1.1972658375d66p+0, 0x1.1f00p-46,
0x1.1a35beb6fcba7p+0, 0x1.0480p-46,
0x1.1af99f81387e3p+0, -0x1.7390p-43,
0x1.1bbe084045d54p+0, 0x1.4e40p-45,
0x1.1c82f95281c43p+0, -0x1.a200p-47,
0x1.1d4873168b9b2p+0, 0x1.3800p-49,
0x1.1e0e75eb44031p+0, 0x1.ac00p-49,
0x1.1ed5022fcd938p+0, 0x1.1900p-47,
0x1.1f9c18438cdf7p+0, -0x1.b780p-46,
0x1.2063b88628d8fp+0, 0x1.d940p-45,
0x1.212be3578a81ep+0, 0x1.8000p-50,
0x1.21f49917ddd41p+0, 0x1.b340p-45,
0x1.22bdda2791323p+0, 0x1.9f80p-46,
0x1.2387a6e7561e7p+0, -0x1.9c80p-46,
0x1.2451ffb821427p+0, 0x1.2300p-47,
0x1.251ce4fb2a602p+0, -0x1.3480p-46,
0x1.25e85711eceb0p+0, 0x1.2700p-46,
0x1.26b4565e27d16p+0, 0x1.1d00p-46,
0x1.2780e341de00fp+0, 0x1.1ee0p-44,
0x1.284dfe1f5633ep+0, -0x1.4c00p-46,
0x1.291ba7591bb30p+0, -0x1.3d80p-46,
0x1.29e9df51fdf09p+0, 0x1.8b00p-47,
0x1.2ab8a66d10e9bp+0, -0x1.27c0p-45,
0x1.2b87fd0dada3ap+0, 0x1.a340p-45,
0x1.2c57e39771af9p+0, -0x1.0800p-46,
0x1.2d285a6e402d9p+0, -0x1.ed00p-47,
0x1.2df961f641579p+0, -0x1.4200p-48,
0x1.2ecafa93e2ecfp+0, -0x1.4980p-45,
0x1.2f9d24abd8822p+0, -0x1.6300p-46,
0x1.306fe0a31b625p+0, -0x1.2360p-44,
0x1.31432edeea50bp+0, -0x1.0df8p-40,
0x1.32170fc4cd7b8p+0, -0x1.2480p-45,
0x1.32eb83ba8e9a2p+0, -0x1.5980p-45,
0x1.33c08b2641766p+0, 0x1.ed00p-46,
0x1.3496266e3fa27p+0, -0x1.c000p-50,
0x1.356c55f929f0fp+0, -0x1.0d80p-44,
0x1.36431a2de88b9p+0, 0x1.2c80p-45,
0x1.371a7373aaa39p+0, 0x1.0600p-45,
0x1.37f26231e74fep+0, -0x1.6600p-46,
0x1.38cae6d05d838p+0, -0x1.ae00p-47,
0x1.39a401b713ec3p+0, -0x1.4720p-43,
0x1.3a7db34e5a020p+0, 0x1.8200p-47,
0x1.3b57fbfec6e95p+0, 0x1.e800p-44,
0x1.3c32dc313a8f2p+0, 0x1.f800p-49,
0x1.3d0e544ede122p+0, -0x1.7a00p-46,
0x1.3dea64c1234bbp+0, 0x1.6300p-45,
0x1.3ec70df1c4eccp+0, -0x1.8a60p-43,
0x1.3fa4504ac7e8cp+0, -0x1.cdc0p-44,
0x1.40822c367a0bbp+0, 0x1.5b80p-45,
0x1.4160a21f72e95p+0, 0x1.ec00p-46,
0x1.423fb27094646p+0, -0x1.3600p-46,
0x1.431f5d950a920p+0, 0x1.3980p-45,
0x1.43ffa3f84b9ebp+0, 0x1.a000p-48,
0x1.44e0860618919p+0, -0x1.6c00p-48,
0x1.45c2042a7d201p+0, -0x1.bc00p-47,
0x1.46a41ed1d0016p+0, -0x1.2800p-46,
0x1.4786d668b3326p+0, 0x1.0e00p-44,
0x1.486a2b5c13c00p+0, -0x1.d400p-45,
0x1.494e1e192af04p+0, 0x1.c200p-47,
0x1.4a32af0d7d372p+0, -0x1.e500p-46,
0x1.4b17dea6db801p+0, 0x1.7800p-47,
0x1.4bfdad53629e1p+0, -0x1.3800p-46,
0x1.4ce41b817c132p+0, 0x1.0800p-47,
0x1.4dcb299fddddbp+0, 0x1.c700p-45,
0x1.4eb2d81d8ab96p+0, -0x1.ce00p-46,
0x1.4f9b2769d2d02p+0, 0x1.9200p-46,
0x1.508417f4531c1p+0, -0x1.8c00p-47,
0x1.516daa2cf662ap+0, -0x1.a000p-48,
0x1.5257de83f51eap+0, 0x1.a080p-43,
0x1.5342b569d4edap+0, -0x1.6d80p-45,
0x1.542e2f4f6ac1ap+0, -0x1.2440p-44,
0x1.551a4ca5d94dbp+0, 0x1.83c0p-43,
0x1.56070dde9116bp+0, 0x1.4b00p-45,
0x1.56f4736b529dep+0, 0x1.15a0p-43,
0x1.57e27dbe2c40ep+0, -0x1.9e00p-45,
0x1.58d12d497c76fp+0, -0x1.3080p-45,
0x1.59c0827ff0b4cp+0, 0x1.dec0p-43,
0x1.5ab07dd485427p+0, -0x1.4000p-51,
0x1.5ba11fba87af4p+0, 0x1.0080p-44,
0x1.5c9268a59460bp+0, -0x1.6c80p-45,
0x1.5d84590998e3fp+0, 0x1.69a0p-43,
0x1.5e76f15ad20e1p+0, -0x1.b400p-46,
0x1.5f6a320dcebcap+0, 0x1.7700p-46,
0x1.605e1b976dcb8p+0, 0x1.6f80p-45,
0x1.6152ae6cdf715p+0, 0x1.1000p-47,
0x1.6247eb03a5531p+0, -0x1.5d00p-46,
0x1.633dd1d1929b5p+0, -0x1.2d00p-46,
0x1.6434634ccc313p+0, -0x1.a800p-49,
0x1.652b9febc8efap+0, -0x1.8600p-45,
0x1.6623882553397p+0, 0x1.1fe0p-40,
0x1.671c1c708328ep+0, -0x1.7200p-44,
0x1.68155d44ca97ep+0, 0x1.6800p-49,
0x1.690f4b19e9471p+0, -0x1.9780p-45,
};
fn exp2_64(x: f64) f64 {
const tblsiz = @intCast(u32, exp2dt.len / 2);
const redux: f64 = 0x1.8p52 / @intToFloat(f64, tblsiz);
const P1: f64 = 0x1.62e42fefa39efp-1;
const P2: f64 = 0x1.ebfbdff82c575p-3;
const P3: f64 = 0x1.c6b08d704a0a6p-5;
const P4: f64 = 0x1.3b2ab88f70400p-7;
const P5: f64 = 0x1.5d88003875c74p-10;
const ux = @bitCast(u64, x);
const ix = @intCast(u32, ux >> 32) & 0x7FFFFFFF;
// TODO: This should be handled beneath.
if (math.isNan(x)) {
return math.nan(f64);
}
// |x| >= 1022 or nan
if (ix >= 0x408FF000) {
// x >= 1024 or nan
if (ix >= 0x40900000 and ux >> 63 == 0) {
math.raiseOverflow();
return math.inf(f64);
}
// -inf or -nan
if (ix >= 0x7FF00000) {
return -1 / x;
}
// x <= -1022
if (ux >> 63 != 0) {
// underflow
if (x <= -1075 or x - 0x1.0p52 + 0x1.0p52 != x) {
math.doNotOptimizeAway(@floatCast(f32, -0x1.0p-149 / x));
}
if (x <= -1075) {
return 0;
}
}
}
// |x| < 0x1p-54
else if (ix < 0x3C900000) {
return 1.0 + x;
}
// reduce x
var uf = x + redux;
// NOTE: musl performs an implicit 64-bit to 32-bit u32 truncation here
var i_0 = @truncate(u32, @bitCast(u64, uf));
i_0 += tblsiz / 2;
const k: u32 = i_0 / tblsiz * tblsiz;
const ik = @bitCast(i32, k / tblsiz);
i_0 %= tblsiz;
uf -= redux;
// r = exp2(y) = exp2t[i_0] * p(z - eps[i])
var z = x - uf;
const t = exp2dt[2 * i_0];
z -= exp2dt[2 * i_0 + 1];
const r = t + t * z * (P1 + z * (P2 + z * (P3 + z * (P4 + z * P5))));
return math.scalbn(r, ik);
}
test "math.exp2" {
expect(exp2(@as(f32, 0.8923)) == exp2_32(0.8923));
expect(exp2(@as(f64, 0.8923)) == exp2_64(0.8923));
}
test "math.exp2_32" {
const epsilon = 0.000001;
expect(exp2_32(0.0) == 1.0);
expect(math.approxEqAbs(f32, exp2_32(0.2), 1.148698, epsilon));
expect(math.approxEqAbs(f32, exp2_32(0.8923), 1.856133, epsilon));
expect(math.approxEqAbs(f32, exp2_32(1.5), 2.828427, epsilon));
expect(math.approxEqAbs(f32, exp2_32(37.45), 187747237888, epsilon));
}
test "math.exp2_64" {
const epsilon = 0.000001;
expect(exp2_64(0.0) == 1.0);
expect(math.approxEqAbs(f64, exp2_64(0.2), 1.148698, epsilon));
expect(math.approxEqAbs(f64, exp2_64(0.8923), 1.856133, epsilon));
expect(math.approxEqAbs(f64, exp2_64(1.5), 2.828427, epsilon));
}
test "math.exp2_32.special" {
expect(math.isPositiveInf(exp2_32(math.inf(f32))));
expect(math.isNan(exp2_32(math.nan(f32))));
}
test "math.exp2_64.special" {
expect(math.isPositiveInf(exp2_64(math.inf(f64))));
expect(math.isNan(exp2_64(math.nan(f64))));
} | lib/std/math/exp2.zig |
const aoc = @import("../aoc.zig");
const std = @import("std");
const Address = isize;
const SubInstruction = enum { ACC, JMP, NOP };
const Instruction = struct {
instr: SubInstruction, offset: i16
};
const ExecutionResult = struct {
pc: Address, acc: isize
};
pub fn run(problem: *aoc.Problem) !aoc.Solution {
var instructions = std.ArrayList(Instruction).init(problem.allocator);
defer instructions.deinit();
while (problem.line()) |line| {
const instr_str = line[0..3];
const instr =
if (std.mem.eql(u8, instr_str, "acc")) SubInstruction.ACC
else if (std.mem.eql(u8, instr_str, "jmp")) SubInstruction.JMP
else SubInstruction.NOP;
const offset = (if (line[4] == '+') @intCast(i16, 1) else -1) * try std.fmt.parseInt(i16, line[5..], 10);
try instructions.append(.{ .instr = instr, .offset = offset });
}
const res1 = blk: {
const result = try executeInstructions(instructions.items, problem.allocator);
break :blk @intCast(usize, result.acc);
};
const res2 = blk: {
for (instructions.items) |instruction, i| {
const old_instr = instruction.instr;
const new_instr = switch (old_instr) {
.ACC => continue,
.JMP => SubInstruction.NOP,
.NOP => SubInstruction.JMP,
};
instructions.items[i].instr = new_instr;
const result = try executeInstructions(instructions.items, problem.allocator);
if (result.pc == instructions.items.len) {
break :blk @intCast(usize, result.acc);
}
instructions.items[i].instr = old_instr;
}
unreachable;
};
return problem.solution(res1, res2);
}
fn executeInstructions(instructions: []const Instruction, allocator: std.mem.Allocator) !ExecutionResult {
var visited = std.AutoHashMap(Address, void).init(allocator);
defer visited.deinit();
var pc: Address = 0;
var acc: isize = 0;
while (!visited.contains(pc) and pc != instructions.len) {
try visited.put(pc, {});
const instruction = instructions[@intCast(usize, pc)];
switch (instruction.instr) {
.ACC => {
acc += instruction.offset;
pc += 1;
},
.JMP => pc += instruction.offset,
.NOP => pc += 1,
}
}
return ExecutionResult{ .pc = pc, .acc = acc };
} | src/main/zig/2020/day08.zig |
const std = @import("std");
const assert = std.debug.assert;
const DottedIdentifier = std.TailQueue([]const u8);
pub const Key = union(enum) {
None,
DottedIdent: DottedIdentifier,
Ident: []const u8,
pub fn deinit(key: *Key, allocator: *std.mem.Allocator) void {
if (key.* == .DottedIdent) {
var it = key.DottedIdent;
while (it.pop()) |node| {
allocator.destroy(node);
}
}
}
};
pub const DynamicArray = std.ArrayList(Value);
pub const TableArray = std.ArrayList(*Table);
pub const Value = union(enum) {
None,
String: []const u8,
Boolean: bool,
Integer: i64,
Array: DynamicArray,
Table: *Table,
ManyTables: TableArray,
pub fn isTable(self: Value) bool {
return self == .Table;
}
pub fn isManyTables(self: Value) bool {
return self == .ManyTables;
}
pub fn deinit(self: *Value) void {
switch (self.*) {
.Array => |*array| {
for (array.items) |*item| {
item.deinit();
}
array.deinit();
},
.Table => |table| {
table.deinit();
},
.ManyTables => |tables| {
for (tables.items) |table| {
table.deinit();
}
tables.deinit();
},
else => {},
}
}
};
pub const Table = struct {
const Self = @This();
const Error = error{ table_is_one, key_already_exists, expected_table_of_one };
const KeyMap = std.StringHashMap(Value);
keys: KeyMap,
name: []const u8,
allocator: std.mem.Allocator,
pub fn init(allocator: std.mem.Allocator, name: []const u8) Self {
return Self{
.keys = KeyMap.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 {
var it = self.keys.iterator();
while (it.next()) |node| {
node.value_ptr.*.deinit();
}
self.keys.deinit();
self.allocator.destroy(self);
}
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;
}
pub fn addKey(self: *Self, key: Key, value: Value) !void {
switch (key) {
Key.None => {
return;
},
Key.Ident => |name| {
var old = try self.keys.fetchPut(name, value);
if (old) |_| {
return Self.Error.key_already_exists;
}
},
Key.DottedIdent => |dotted| {
var current_table: *Table = self;
var index: usize = 0;
while (index < dotted.len - 1) : (index += 1) {
if (current_table.keys.get(indexIdentifier(dotted, index).?)) |pair| {
if (pair.isManyTables()) {
return Self.Error.expected_table_of_one;
}
current_table = pair.Table;
} else {
var table = try self.allocator.create(Table);
table.* = Table.init(self.allocator, indexIdentifier(dotted, index).?);
try current_table.addTable(table);
current_table = table;
}
}
var old = try current_table.keys.fetchPut(indexIdentifier(dotted, index).?, value);
if (old) |_| {
return Self.Error.key_already_exists;
}
},
}
}
pub fn addTable(self: *Self, table: *Table) !void {
if (self.keys.get(table.name)) |_| {
return Self.Error.key_already_exists;
}
_ = try self.keys.put(table.name, Value{ .Table = table });
}
pub fn addManyTable(self: *Self, table: *Table) !void {
if (self.keys.get(table.name)) |*pair| {
if (pair.isManyTables()) {
try pair.ManyTables.append(table);
} else {
return Self.Error.table_is_one;
}
} else {
var value = TableArray.init(self.allocator);
try value.append(table);
var old = try self.keys.fetchPut(table.name, Value{ .ManyTables = value });
// since we already tested if there's a table then this should be unreachable
if (old) |_| {
unreachable;
}
}
}
pub fn addNewTable(self: *Self, name: []const u8) !*Table {
var table = try Table.create(self.allocator, name);
var old = try self.keys.fetchPut(name, Value{ .Table = table });
if (old) |_| {
return Self.Error.key_already_exists;
}
return table;
}
};
fn isEof(c: u8) bool {
return c == 0;
}
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';
}
/// denotes whitespace that is allowed between a key and its value
fn isPairWhitespace(c: u8) bool {
return c == '\t' or c == ' ';
}
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;
}
pub const Parser = struct {
const Error = error{
unexpected_eof,
expected_identifier,
expected_equals,
expected_newline,
expected_closing_brace,
malformed_table,
expected_comma,
invalid_value,
unexpected_newline,
};
const Pair = struct {
key: Key,
value: Value,
};
allocator: std.mem.Allocator,
global_table: *Table,
// denotes if contents have been heap allocated (from a file)
allocated: bool,
filename: []const u8,
contents: []const u8,
line: usize,
column: usize,
index: usize,
pub fn initWithFile(allocator: std.mem.Allocator, filename: []const u8) !Parser {
var contents = try std.fs.cwd().readFileAlloc(allocator, filename, std.math.maxInt(usize));
var parser = try Parser.initWithString(allocator, contents);
parser.filename = filename;
parser.allocated = true;
return parser;
}
pub fn initWithString(allocator: std.mem.Allocator, str: []const u8) !Parser {
return Parser{
.allocator = allocator,
.global_table = try Table.create(allocator, ""),
.allocated = false,
.filename = "",
.contents = str,
.line = 1,
.column = 0,
.index = 0,
};
}
pub fn deinit(self: *Parser) void {
if (self.allocated) {
self.allocator.free(self.contents);
}
}
fn rawNextChar(self: *Parser) u8 {
if (self.index >= self.contents.len) {
return 0;
}
var c = self.contents[self.index];
if (c == '\n') {
self.line += 1;
self.column = 0;
}
self.index += 1;
self.column += 1;
return c;
}
fn nextChar(self: *Parser) u8 {
var c = self.rawNextChar();
// Skip any comments
while (c == '#') {
c = self.rawNextChar();
while (!isEof(c)) {
if (c == '\n') {
break;
}
c = self.rawNextChar();
}
if (isEof(c)) {
return 0;
}
}
return c;
}
fn curChar(self: Parser) u8 {
if (self.index == 0) {
return self.contents[self.index];
} else if (self.index >= self.contents.len) {
return self.contents[self.contents.len - 1];
} else {
return self.contents[self.index - 1];
}
}
fn peekChar(self: Parser) u8 {
if (self.index >= self.contents.len) {
return 0;
}
return self.contents[self.index];
}
fn getIndex(self: Parser) usize {
if (self.index == 0) {
return 0;
}
return self.index - 1;
}
fn nextCharIgnoreWhitespace(self: *Parser) u8 {
var c = self.nextChar();
while (isWhitespace(c)) {
c = self.nextChar();
}
return c;
}
fn ignoreWhitespace(self: *Parser) u8 {
var c = self.curChar();
while (isWhitespace(c)) {
c = self.nextChar();
}
return c;
}
fn isNewline(self: *Parser, c: u8) bool {
var n = c;
if (n == '\r') {
n = self.peekChar();
}
if (n == '\n') {
return true;
}
return false;
}
// parses `contents` and returns the global table
pub fn parse(self: *Parser) !*Table {
try self.parseTable(self.global_table);
return self.global_table;
}
fn parseTable(self: *Parser, table: *Table) anyerror!void {
var has_newline = true;
var c = self.nextChar();
while (!isEof(c)) {
c = self.ignoreWhitespace();
if (!has_newline) {
return Parser.Error.expected_newline;
}
has_newline = false;
// parse table
if (c == '[') {
var is_array = false;
if (self.peekChar() == '[') {
c = self.nextChar();
is_array = true;
}
c = self.nextChar();
var table_key = try self.parseKeyIdentifier();
defer table_key.deinit(&self.allocator);
c = self.curChar();
if (c != ']') {
return Parser.Error.expected_closing_brace;
}
if (is_array) {
c = self.nextChar();
if (c != ']') {
return Parser.Error.expected_closing_brace;
}
}
var table_name: []const u8 = undefined;
var current_table = self.global_table;
switch (table_key) {
Key.None => {
return Parser.Error.malformed_table;
},
Key.Ident => |ident| {
table_name = ident;
},
Key.DottedIdent => |dotted| {
// iterate through the identifiers and create any missing tables along the way
var it = dotted.first;
while (it) |node| : (it = node.next) {
if (node == dotted.last) {
break;
}
if (current_table.keys.get(node.data)) |pair| {
if (pair.isManyTables()) {
return Parser.Error.malformed_table;
}
current_table = pair.Table;
} else {
current_table = try current_table.addNewTable(node.data);
}
}
table_name = dotted.last.?.data;
},
}
var new_table = try Table.create(self.allocator, table_name);
// add before parsing so then if adding returns an error we get the proper line/column
if (is_array) {
try current_table.addManyTable(new_table);
} else {
try current_table.addTable(new_table);
}
try self.parseTable(new_table);
// If there's a new table then this table can't have any more pairs
// Even if this break was removed no pairs would be parsed and we would end up with an error from parsePair
break;
} else {
// if is eof after table declaration then stop parsing table
if (isEof(c)) {
break;
}
var pair = try self.parsePair();
defer pair.key.deinit(&self.allocator);
try table.addKey(pair.key, pair.value);
c = self.curChar();
// ignore whitespace after pair
while (isPairWhitespace(c)) {
c = self.nextChar();
}
if (self.isNewline(c)) {
has_newline = true;
}
}
c = self.nextChar();
}
}
fn parsePair(self: *Parser) !Pair {
var c = self.curChar();
if (isEof(c)) {
return Parser.Error.expected_identifier;
}
var key = try self.parseKeyIdentifier();
// ignore whitespace before equals
c = self.curChar();
while (isPairWhitespace(c)) {
c = self.nextChar();
}
if (c != '=') {
return Parser.Error.expected_equals;
}
c = self.nextChar();
// ignore whitespace after equals
while (isPairWhitespace(c)) {
c = self.nextChar();
}
var value = try self.parseValue();
return Pair{
.key = key,
.value = value,
};
}
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 Parser.Error.invalid_value;
}
}
fn parseValue(self: *Parser) anyerror!Value {
var c = self.curChar();
if (isQuote(c)) {
return Value{ .String = try self.parseString(c) };
}
// array
if (c == '[') {
return try self.parseArray();
}
// inline table
if (c == '{') {
return try self.parseInlineTable();
}
var ident = try self.parseIdentifier();
return try Parser.convertIdentifierToValue(ident);
}
fn parseArray(self: *Parser) anyerror!Value {
var result = DynamicArray.init(self.allocator);
var c = self.nextChar();
var has_comma = true;
while (c != ']' and !isEof(c)) {
if (!has_comma) {
return Parser.Error.expected_comma;
}
has_comma = false;
c = self.ignoreWhitespace();
var value = try self.parseValue();
try result.append(value);
c = self.ignoreWhitespace();
if (c == ',') {
c = self.nextCharIgnoreWhitespace();
has_comma = true;
} else if (c != ']') {
return Parser.Error.expected_closing_brace;
}
}
if (isEof(c)) {
return Parser.Error.unexpected_eof;
}
// eat the ]
_ = self.nextChar();
return Value{ .Array = result };
}
fn parseInlineTable(self: *Parser) anyerror!Value {
var result = try Table.create(self.allocator, "");
var c = self.nextChar();
var has_comma = true;
while (c != '}' and !isEof(c)) {
if (!has_comma) {
return Parser.Error.expected_comma;
}
has_comma = false;
if (self.isNewline(c)) {
return Parser.Error.unexpected_newline;
}
while (isPairWhitespace(c)) {
c = self.nextChar();
}
var pair = try self.parsePair();
try result.addKey(pair.key, pair.value);
c = self.curChar();
// ignore all whitespace that is allowed after a pair
// then check for a newline
while (isPairWhitespace(c)) {
c = self.nextChar();
}
if (self.isNewline(c)) {
return Parser.Error.unexpected_newline;
}
if (c == ',') {
// grab the next char ignoring any pair whitespace
c = self.nextChar();
while (isPairWhitespace(c)) {
c = self.nextChar();
}
has_comma = true;
}
}
if (isEof(c)) {
return Parser.Error.unexpected_eof;
}
_ = self.nextChar();
return Value{ .Table = result };
}
fn parseWord(self: *Parser) ![]const u8 {
var c = self.curChar();
if (isQuote(c)) {
return try self.parseString(c);
}
if (isIdentifier(c)) {
return try self.parseIdentifier();
}
return Parser.Error.expected_identifier;
}
fn parseKeyIdentifier(self: *Parser) !Key {
var keyValue = try self.parseWord();
var c = self.curChar();
if (c == '.') {
var dottedResult = try self.parseDottedIdentifier();
var node = try self.allocator.create(DottedIdentifier.Node);
node.data = keyValue;
dottedResult.prepend(node);
return Key{ .DottedIdent = dottedResult };
} else {
return Key{ .Ident = keyValue };
}
}
// expects self.curChar() to be a .
fn parseDottedIdentifier(self: *Parser) !DottedIdentifier {
var result = DottedIdentifier{};
var c = self.curChar();
while (c == '.') {
var ident: []const u8 = undefined;
c = self.nextChar();
if (isQuote(c)) {
ident = try self.parseString(c);
} else {
ident = try self.parseIdentifier();
}
var node = try self.allocator.create(DottedIdentifier.Node);
node.data = ident;
result.append(node);
c = self.curChar();
}
return result;
}
fn parseString(self: *Parser, opening: u8) ![]const u8 {
var c = self.rawNextChar();
var start = self.getIndex();
while (c != opening and !isEof(c)) {
c = self.rawNextChar();
}
if (isEof(c)) {
return Parser.Error.unexpected_eof;
}
// eat the closing quote
var ending = self.getIndex();
c = self.nextChar();
return self.contents[start..ending];
}
fn parseIdentifier(self: *Parser) ![]const u8 {
var start = self.getIndex();
var c = self.nextChar();
while (isIdentifier(c) and !isEof(c)) {
c = self.nextChar();
}
if (isEof(c)) {
return self.contents[start..];
}
return self.contents[start..self.getIndex()];
}
};
pub fn parseFile(allocator: std.mem.Allocator, filename: []const u8, out_parser: ?*Parser) !*Table {
var parser = try Parser.initWithFile(allocator, filename);
if (out_parser) |op| {
op.* = parser;
return try op.parse();
}
return try parser.parse();
}
pub fn parseContents(allocator: std.mem.Allocator, contents: []const u8, out_parser: ?*Parser) !*Table {
// TODO: time values
// TODO: float values
// TODO: inline tables
var parser = try Parser.initWithString(allocator, contents);
if (out_parser) |op| {
op.* = parser;
return try op.parse();
}
return try parser.parse();
}
test "test.toml file" {
const filename = "test/test.toml";
const allocator = std.testing.allocator;
var parser: Parser = undefined;
defer parser.deinit();
var table = try parseFile(allocator, filename, &parser);
defer table.deinit();
}
test "basic.toml file" {
const filename = "test/basic.toml";
const allocator = std.testing.allocator;
var parser: Parser = undefined;
defer parser.deinit();
var table = try parseFile(allocator, filename, &parser);
defer table.deinit();
assert(table.keys.get("foo") != null);
if (table.keys.get("foo")) |foo| {
assert(foo == .Table);
assert(foo.Table.keys.get("hi") != null);
if (foo.Table.keys.get("hi")) |value| {
assert(std.mem.eql(u8, value.String, "there"));
}
}
}
test "comment before newline" {
var table = try parseContents(std.testing.allocator,
\\foo="test" # foo
\\[bar]
\\
, null);
defer table.deinit();
var foo = table.keys.get("foo").?;
assert(std.mem.eql(u8, foo.String, "test"));
}
test "whitespace before table" {
var table = try parseContents(std.testing.allocator,
\\ [foo.hi]
\\
\\ bar = 1234 # derp
\\
\\ [bar]
\\
\\ test = true
, null);
defer table.deinit();
var foo = table.keys.get("foo").?;
var hi = foo.Table.keys.get("hi").?;
var bar = hi.Table.keys.get("bar").?;
assert(bar.Integer == 1234);
}
test "multiple key identifiers" {
var table = try parseContents(std.testing.allocator,
\\ [foo.bar.foobar]
\\
, null);
defer table.deinit();
}
test "multi-line arrays" {
var table = try parseContents(std.testing.allocator,
\\ array = [
\\ "]",
\\ # inner comment
\\ ]
, null);
defer table.deinit();
}
test "key value pair" {
var table = try parseContents(std.testing.allocator,
\\ foo="hello"
\\
, null);
defer table.deinit();
assert(table.keys.get("foo") != null);
if (table.keys.get("foo")) |value| {
assert(std.mem.eql(u8, value.String, "hello"));
}
}
test "table" {
var table = try parseContents(std.testing.allocator,
\\ [foo]
\\
, null);
defer table.deinit();
assert(table.keys.get("foo") != null);
}
test "comment" {
var table = try parseContents(std.testing.allocator,
\\ # [foo]
\\
, null);
defer table.deinit();
assert(table.keys.get("foo") == null);
}
test "comment inside array" {
var table = try parseContents(std.testing.allocator,
\\ foo=[ # hello there
\\ 123, 456
\\ ]
\\
, null);
defer table.deinit();
var fooKey = table.keys.get("foo");
assert(fooKey != null);
if (fooKey) |foo| {
assert(foo.Array.items.len == 2);
assert(foo.Array.items[0].Integer == 123);
assert(foo.Array.items[1].Integer == 456);
}
}
test "table key value pair" {
var table = try parseContents(std.testing.allocator,
\\ [foo]
\\ key = "bar"
\\
, null);
defer table.deinit();
assert(table.keys.get("foo") != null);
if (table.keys.get("foo")) |foo| {
assert(foo.Table.keys.get("key") != null);
if (foo.Table.keys.get("key")) |value| {
assert(std.mem.eql(u8, value.String, "bar"));
}
}
}
test "dotted key with string" {
var table = try parseContents(std.testing.allocator,
\\ key."ziglang.org" = "bar"
\\
, null);
defer table.deinit();
assert(table.keys.get("key") != null);
if (table.keys.get("key")) |value| {
if (value.Table.keys.get("ziglang.org")) |zig| {
assert(std.mem.eql(u8, zig.String, "bar"));
}
}
}
test "multiple tables" {
var table = try parseContents(std.testing.allocator,
\\ [foo]
\\ key="bar"
\\ [derp]
\\ another="foobar"
\\
, null);
defer table.deinit();
assert(table.keys.get("foo") != null);
if (table.keys.get("foo")) |foo| {
assert(foo.Table.keys.get("key") != null);
if (foo.Table.keys.get("key")) |value| {
assert(std.mem.eql(u8, value.String, "bar"));
}
}
assert(table.keys.get("derp") != null);
if (table.keys.get("derp")) |foo| {
assert(foo.Table.keys.get("another") != null);
if (foo.Table.keys.get("another")) |value| {
assert(std.mem.eql(u8, value.String, "foobar"));
}
}
}
test "key value pair with string key" {
var table = try parseContents(std.testing.allocator,
\\ "foo"="hello"
\\
, null);
defer table.deinit();
var keyValue = table.keys.get("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.testing.allocator,
\\ foo.bar="hello"
\\
, null);
defer table.deinit();
var fooTable = table.keys.get("foo");
assert(fooTable != null);
if (fooTable) |foo| {
var barKey = foo.Table.keys.get("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.testing.allocator,
\\ [foobar]
\\ foo.bar="hello"
\\
, null);
defer table.deinit();
var fooBarTable = table.keys.get("foobar");
if (fooBarTable) |foobar| {
var fooTable = foobar.Table.keys.get("foo");
assert(fooTable != null);
if (fooTable) |foo| {
var barKey = foo.Table.keys.get("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.testing.allocator,
\\foo=true
\\
, null);
defer table.deinit();
var fooKey = table.keys.get("foo");
assert(fooKey != null);
if (fooKey) |foo| {
assert(foo.Boolean == true);
}
}
test "key value pair boolean false" {
var table = try parseContents(std.testing.allocator,
\\ foo=false
\\
, null);
defer table.deinit();
var fooKey = table.keys.get("foo");
assert(fooKey != null);
if (fooKey) |foo| {
assert(foo.Boolean == false);
}
}
test "key value pair integer" {
var table = try parseContents(std.testing.allocator,
\\ foo=1234
\\
, null);
defer table.deinit();
var fooKey = table.keys.get("foo");
assert(fooKey != null);
if (fooKey) |foo| {
assert(foo.Integer == 1234);
}
}
test "key value pair integer" {
var table = try parseContents(std.testing.allocator,
\\ foo=1_1234_3_4
\\
, null);
defer table.deinit();
var fooKey = table.keys.get("foo");
assert(fooKey != null);
if (fooKey) |foo| {
assert(foo.Integer == 1123434);
}
}
test "key value pair negative integer" {
var table = try parseContents(std.testing.allocator,
\\ foo=-1234
\\
, null);
defer table.deinit();
var fooKey = table.keys.get("foo");
assert(fooKey != null);
if (fooKey) |foo| {
assert(foo.Integer == -1234);
}
}
test "key value pair positive integer" {
var table = try parseContents(std.testing.allocator,
\\ foo=+1234
\\
, null);
defer table.deinit();
var fooKey = table.keys.get("foo");
assert(fooKey != null);
if (fooKey) |foo| {
assert(foo.Integer == 1234);
}
}
test "multiple key value pair" {
var table = try parseContents(std.testing.allocator,
\\ foo=1234
\\ bar=4321
\\
, null);
defer table.deinit();
var fooKey = table.keys.get("foo");
assert(fooKey != null);
if (fooKey) |foo| {
assert(foo.Integer == 1234);
}
var barKey = table.keys.get("bar");
assert(barKey != null);
if (barKey) |bar| {
assert(bar.Integer == 4321);
}
}
test "key value simple array" {
var table = try parseContents(std.testing.allocator,
\\ foo=[]
\\
, null);
defer table.deinit();
var fooKey = table.keys.get("foo");
assert(fooKey != null);
assert(fooKey.? == .Array);
}
test "key value multiple element array" {
var table = try parseContents(std.testing.allocator,
\\ foo=[ 1234, 5678, true, false, "hello" ]
\\
, null);
defer table.deinit();
var fooKey = table.keys.get("foo");
assert(fooKey != null);
if (fooKey) |foo| {
assert(foo.Array.items.len == 5);
assert(std.mem.eql(u8, foo.Array.items[4].String, "hello"));
assert(foo.Array.items[3].Boolean == false);
assert(foo.Array.items[2].Boolean == true);
assert(foo.Array.items[1].Integer == 5678);
assert(foo.Array.items[0].Integer == 1234);
}
}
test "key value array in array" {
var table = try parseContents(std.testing.allocator,
\\ foo=[[[[[1234]], 57789, [1234, 578]]]]
\\
, null);
defer table.deinit();
var fooKey = table.keys.get("foo");
assert(fooKey != null);
if (fooKey) |foo| {
var items = foo.Array.items;
assert(foo.Array.items.len == 1);
var array1 = items[0];
assert(array1.Array.items.len == 1);
var array2 = array1.Array.items[0];
assert(array2.Array.items.len == 3);
assert(array2.Array.items[1].Integer == 57789);
var array3 = array2.Array.items[0];
assert(array3.Array.items.len == 1);
var array4 = array3.Array.items[0];
assert(array3.Array.items.len == 1);
assert(array4.Array.items[0].Integer == 1234);
}
}
test "key with string first" {
var table = try parseContents(std.testing.allocator,
\\ "foo".bar = "foobar"
\\
, null);
defer table.deinit();
var fooTable = table.keys.get("foo").?;
var barKey = fooTable.Table.keys.get("bar").?;
assert(std.mem.eql(u8, barKey.String, "foobar"));
}
test "table with dotted identifier" {
var table = try parseContents(std.testing.allocator,
\\ [foo.bar]
\\ testKey = "hello"
\\
, null);
defer table.deinit();
var foo = table.keys.get("foo").?;
var bar = foo.Table.keys.get("bar").?;
var testKey = bar.Table.keys.get("testKey").?;
assert(std.mem.eql(u8, testKey.String, "hello"));
}
test "array of tables" {
// var table = try parseContents(std.testing.allocator,
// \\[[foo]]
// \\bar = "hi"
// \\[[foo]]
// \\bar = "test"
// , null);
// defer table.deinit();
// var foo = table.keys.get("foo").?;
// assert(foo.isManyTables());
// assert(foo.ManyTables.items.len == 2);
// var one = foo.ManyTables.items[0];
// var bar = one.keys.get("bar").?;
// assert(std.mem.eql(u8, bar.String, "hi"));
// var two = foo.ManyTables.items[1];
// var bar2 = two.keys.get("bar").?;
// assert(std.mem.eql(u8, bar2.String, "test"));
}
test "window line endings" {
var table = try parseContents(std.testing.allocator, "foo=1234\r\nbar=5789\r\n", null);
defer table.deinit();
assert(table.keys.get("foo") != null);
assert(table.keys.get("bar") != null);
}
test "empty inline table" {
var table = try parseContents(std.testing.allocator,
\\foo = {}
, null);
defer table.deinit();
assert(table.keys.get("foo") != null);
assert(table.keys.get("foo").? == .Table);
}
test "inline table with keys" {
var table = try parseContents(std.testing.allocator,
\\foo = { bar = 1234, foobar = "test string" }
, null);
defer table.deinit();
var foo = table.keys.get("foo").?.Table;
var bar = foo.keys.get("bar").?.Integer;
assert(bar == 1234);
var foobar = foo.keys.get("foobar").?.String;
assert(std.mem.eql(u8, foobar, "test string"));
}
test "inline table with inline table" {
var table = try parseContents(std.testing.allocator,
\\foo = { bar = { foobar = "test string" } }
, null);
defer table.deinit();
var foo = table.keys.get("foo").?.Table;
var bar = foo.keys.get("bar").?.Table;
var foobar = bar.keys.get("foobar").?.String;
assert(std.mem.eql(u8, foobar, "test string"));
} | src/toml.zig |
const olin = @import("./olin/olin.zig");
pub const os = olin;
pub const panic = os.panic;
const cwagi = olin.cwagi;
const std = @import("std");
const fmt = std.fmt;
const Headers = std.http.Headers;
var alloc = std.heap.page_allocator;
pub fn main() anyerror!void {
const fout = try olin.resource.stdout();
const ctx = try cwagi.Context.init(alloc);
defer ctx.destroy(alloc);
var h = Headers.init(alloc);
defer h.deinit();
const resp: cwagi.Response = try helloWorld(ctx, &h);
try resp.writeTo(alloc, &h, fout);
}
const message = "Hello, I am served from Zig compiled to wasm32-freestanding-none.\n\nI know the following about my environment:\n";
fn helloWorld(ctx: cwagi.Context, headers: *Headers) !cwagi.Response {
var line: [2048]u8 = undefined;
try headers.append("Content-Type", "text/plain", null);
try headers.append("Olin-Lang", "Zig", null);
var buf = try std.Buffer.init(alloc, message);
const runtime_meta = try olin.runtime.metadata(alloc);
const runID = try olin.env.get(alloc, "RUN_ID");
defer alloc.free(runID);
const workerID = try olin.env.get(alloc, "WORKER_ID");
defer alloc.free(workerID);
try buf.append(try fmt.bufPrint(line[0..], "- I am running in {} which implements version {}.{} of the Common WebAssembly ABI.\n- I think the time is {}\n- RUN_ID: {}\n- WORKER_ID: {}\n- Method: {}\n- URI: {}\n\n",
.{
runtime_meta.name,
runtime_meta.spec_major,
runtime_meta.spec_minor,
olin.time.unix(),
runID,
workerID,
ctx.method,
ctx.request_uri,
}
));
try buf.append(@embedFile("./cwagi_message.txt"));
return cwagi.Response {
.status = olin.http.StatusCode.OK,
.body = buf.toSlice(),
};
} | zig/src/cwagi.zig |
const std = @import("std");
const zephyr = @import("zephyr.zig");
const sys = @import("src/sys.zig");
const FlashArea = sys.flash.FlashArea;
const image = @import("image.zig");
pub fn flashTest() !void {
std.log.info("Running flash test", .{});
var fa = try FlashArea.open(@enumToInt(image.Slot.PrimarySecure));
// TODO: Query this from the device, once we have a meaningful API
// to do this.
const page_count = 272;
const page_size = 512;
var page: usize = 0;
var buf = buffer1[0..];
var buf2 = buffer2[0..];
std.log.info("Erasing slot", .{});
while (page < page_count) : (page += 1) {
const offset = page * page_size;
try fa.erase(offset, page_size);
}
std.log.info("Validating erase", .{});
page = 0;
while (page < page_count) : (page += 1) {
const offset = page * page_size;
std.mem.set(u8, buf, 0xAA);
try fa.read(offset, buf);
try isErased(buf);
}
std.log.info("Filling flash with patterns", .{});
page = 0;
while (page < page_count) : (page += 1) {
const offset = page * page_size;
fillBuf(buf, page);
try fa.write(offset, buf);
}
std.log.info("Reading data back", .{});
page = 0;
while (page < page_count) : (page += 1) {
fillBuf(buf, page);
std.mem.set(u8, buf2, 0xAA);
try fa.read(page * page_size, buf2);
try expectEqualSlices(u8, buf, buf2);
}
std.log.info("Success", .{});
}
// Static buffers.
var buffer1: [512]u8 = undefined;
var buffer2: [512]u8 = undefined;
fn isErased(buf: []const u8) !void {
for (buf) |ch, i| {
if (ch != 0xFF) {
std.log.err("Byte not erased at {} (value 0x{x})", .{ i, ch });
return error.TestFailure;
}
}
}
// Similar to the testing one, but without a stdio dependency.
fn expectEqualSlices(comptime T: type, expected: []const T, actual: []const T) !void {
if (expected.len != actual.len) {
std.log.err("slice lengths differ, expected {d}, found {d}", .{ expected.len, actual.len });
}
var i: usize = 0;
while (i < expected.len) : (i += 1) {
if (!std.meta.eql(expected[i], actual[i])) {
std.log.err("index {} incorrect. expected {any}, found {any}", .{ i, expected[i], actual[i] });
return error.TestExpectedEqual;
}
}
}
fn fillBuf(buf: []u8, seed: u64) void {
var rng = std.rand.DefaultPrng.init(seed);
rng.fill(buf);
} | testing.zig |
const std = @import("std");
const c = @import("c.zig");
const utils = @import("utils.zig");
const intToError = @import("error.zig").intToError;
const Error = @import("error.zig").Error;
const GlyphSlot = @import("freetype.zig").GlyphSlot;
const LoadFlags = @import("freetype.zig").LoadFlags;
const FaceFlags = @import("freetype.zig").FaceFlags;
const StyleFlags = @import("freetype.zig").StyleFlags;
const FSType = @import("freetype.zig").FSType;
const OpenArgs = @import("freetype.zig").OpenArgs;
const KerningMode = @import("freetype.zig").KerningMode;
const Encoding = @import("freetype.zig").Encoding;
const CharMap = @import("freetype.zig").CharMap;
const Size = @import("freetype.zig").Size;
const SizeRequest = @import("freetype.zig").SizeRequest;
const BitmapSize = @import("freetype.zig").BitmapSize;
const Matrix = @import("types.zig").Matrix;
const BBox = @import("types.zig").BBox;
const Vector = @import("image.zig").Vector;
const RootTransform = @import("color.zig").RootTransform;
const PaintFormat = @import("color.zig").PaintFormat;
const Color = @import("color.zig").Color;
const ClipBox = @import("color.zig").ClipBox;
const OpaquePaint = @import("color.zig").OpaquePaint;
const Paint = @import("color.zig").Paint;
const PaletteData = @import("color.zig").PaletteData;
const GlyphLayersIterator = @import("color.zig").GlyphLayersIterator;
const Face = @This();
pub const CharmapIterator = struct {
face: Face,
index: u32,
charcode: u32,
pub fn init(face: Face) CharmapIterator {
var i: u32 = 0;
const cc = c.FT_Get_First_Char(face.handle, &i);
return .{
.face = face,
.index = i,
.charcode = @intCast(u32, cc),
};
}
pub fn next(self: *CharmapIterator) ?u32 {
self.charcode = @intCast(u32, c.FT_Get_Next_Char(self.face.handle, self.charcode, &self.index));
return if (self.index != 0)
self.charcode
else
null;
}
};
handle: c.FT_Face,
pub fn deinit(self: Face) void {
intToError(c.FT_Done_Face(self.handle)) catch |err| {
std.log.err("mach/freetype: Failed to destroy Face: {}", .{err});
};
}
pub fn attachFile(self: Face, path: []const u8) Error!void {
return self.attachStream(.{
.flags = .{ .path = true },
.data = .{ .path = path },
});
}
pub fn attachMemory(self: Face, bytes: []const u8) Error!void {
return self.attachStream(.{
.flags = .{ .memory = true },
.data = .{ .memory = bytes },
});
}
pub fn attachStream(self: Face, args: OpenArgs) Error!void {
return intToError(c.FT_Attach_Stream(self.handle, &args.cast()));
}
pub fn loadGlyph(self: Face, index: u32, flags: LoadFlags) Error!void {
return intToError(c.FT_Load_Glyph(self.handle, index, flags.cast()));
}
pub fn loadChar(self: Face, char: u32, flags: LoadFlags) Error!void {
return intToError(c.FT_Load_Char(self.handle, char, flags.cast()));
}
pub fn setCharSize(self: Face, pt_width: i32, pt_height: i32, horz_resolution: u16, vert_resolution: u16) Error!void {
return intToError(c.FT_Set_Char_Size(self.handle, pt_width, pt_height, horz_resolution, vert_resolution));
}
pub fn setPixelSizes(self: Face, pixel_width: u32, pixel_height: u32) Error!void {
return intToError(c.FT_Set_Pixel_Sizes(self.handle, pixel_width, pixel_height));
}
pub fn requestSize(self: Face, req: SizeRequest) Error!void {
var req_mut = req;
return intToError(c.FT_Request_Size(self.handle, &req_mut));
}
pub fn selectSize(self: Face, strike_index: i32) Error!void {
return intToError(c.FT_Select_Size(self.handle, strike_index));
}
pub fn setTransform(self: Face, matrix: ?Matrix, delta: ?Vector) Error!void {
var matrix_mut = matrix;
var delta_mut = delta;
return c.FT_Set_Transform(self.handle, if (matrix_mut) |*m| m else null, if (delta_mut) |*d| d else null);
}
pub fn getTransform(self: Face) std.meta.Tuple(&.{ Matrix, Vector }) {
var matrix: Matrix = undefined;
var delta: Vector = undefined;
c.FT_Get_Transform(self.handle, &matrix, &delta);
return .{ matrix, delta };
}
pub fn getCharIndex(self: Face, char: u32) ?u32 {
const i = c.FT_Get_Char_Index(self.handle, char);
return if (i == 0) null else i;
}
pub fn getNameIndex(self: Face, name: [:0]const u8) ?u32 {
const i = c.FT_Get_Name_Index(self.handle, name);
return if (i == 0) null else i;
}
pub fn getKerning(self: Face, left_char_index: u32, right_char_index: u32, mode: KerningMode) Error!Vector {
var kerning: Vector = undefined;
try intToError(c.FT_Get_Kerning(self.handle, left_char_index, right_char_index, @enumToInt(mode), &kerning));
return kerning;
}
pub fn getTrackKerning(self: Face, point_size: i32, degree: i32) Error!i32 {
var kerning: i32 = 0;
try intToError(c.FT_Get_Track_Kerning(self.handle, point_size, degree, &@intCast(c_long, kerning)));
return kerning;
}
pub fn getGlyphName(self: Face, index: u32) Error![]const u8 {
var name_buf: [30]u8 = undefined;
try intToError(c.FT_Get_Glyph_Name(self.handle, index, &name_buf, 30));
return std.mem.sliceTo(&name_buf, 0);
}
pub fn getPostscriptName(self: Face) ?[:0]const u8 {
return if (c.FT_Get_Postscript_Name(self.handle)) |face_name|
std.mem.span(face_name)
else
null;
}
pub fn getCharmapIterator(self: Face) CharmapIterator {
return CharmapIterator.init(self);
}
pub fn selectCharmap(self: Face, encoding: Encoding) Error!void {
return intToError(c.FT_Select_Charmap(self.handle, @enumToInt(encoding)));
}
pub fn setCharmap(self: Face, char_map: *CharMap) Error!void {
return intToError(c.FT_Set_Charmap(self.handle, char_map));
}
pub fn getFSTypeFlags(self: Face) FSType {
return FSType.from(@intCast(u10, c.FT_Get_FSType_Flags(self.handle)));
}
pub fn getCharVariantIndex(self: Face, char: u32, variant_selector: u32) ?u32 {
return switch (c.FT_Face_GetCharVariantIndex(self.handle, char, variant_selector)) {
0 => null,
else => |i| i,
};
}
pub fn getCharVariantIsDefault(self: Face, char: u32, variant_selector: u32) ?bool {
return switch (c.FT_Face_GetCharVariantIsDefault(self.handle, char, variant_selector)) {
-1 => null,
0 => false,
1 => true,
else => unreachable,
};
}
pub fn getVariantSelectors(self: Face) ?[]u32 {
return if (c.FT_Face_GetVariantSelectors(self.handle)) |chars|
@ptrCast([]u32, std.mem.sliceTo(chars, 0))
else
null;
}
pub fn getVariantsOfChar(self: Face, char: u32) ?[]u32 {
return if (c.FT_Face_GetVariantsOfChar(self.handle, char)) |variants|
@ptrCast([]u32, std.mem.sliceTo(variants, 0))
else
null;
}
pub fn getCharsOfVariant(self: Face, variant_selector: u32) ?[]u32 {
return if (c.FT_Face_GetCharsOfVariant(self.handle, variant_selector)) |chars|
@ptrCast([]u32, std.mem.sliceTo(chars, 0))
else
null;
}
pub fn getPaletteData(self: Face) Error!PaletteData {
var p: c.FT_Palette_Data = undefined;
try intToError(c.FT_Palette_Data_Get(self.handle, &p));
return PaletteData{ .handle = p };
}
fn selectPalette(self: Face, index: u16) Error!?[]const Color {
var color: [*:0]Color = undefined;
try intToError(c.FT_Palette_Select(self.handle, index, &color));
const pd = try getPaletteData();
return self.color[0..pd.numPaletteEntries()];
}
pub fn setPaletteForegroundColor(self: Face, color: Color) Error!void {
try intToError(c.FT_Palette_Set_Foreground_Color(self.handle, color));
}
pub fn getGlyphLayersIterator(self: Face, glyph_index: u32) GlyphLayersIterator {
return GlyphLayersIterator.init(self, glyph_index);
}
pub fn getColorGlyphPaint(self: Face, base_glyph: u32, root_transform: RootTransform) ?Paint {
var opaque_paint: OpaquePaint = undefined;
if (c.FT_Get_Color_Glyph_Paint(self.handle, base_glyph, @enumToInt(root_transform), &opaque_paint) == 0)
return null;
return self.getPaint(opaque_paint);
}
pub fn getColorGlyphClibBox(self: Face, base_glyph: u32) ?ClipBox {
var clib_box: ClipBox = undefined;
if (c.FT_Get_Color_Glyph_ClipBox(self.handle, base_glyph, &clib_box) == 0)
return null;
return clib_box;
}
pub fn getPaint(self: Face, opaque_paint: OpaquePaint) ?Paint {
var p: c.FT_COLR_Paint = undefined;
if (c.FT_Get_Paint(self.handle, opaque_paint, &p) == 0)
return null;
return switch (@intToEnum(PaintFormat, p.format)) {
.color_layers => Paint{ .color_layers = p.u.colr_layers },
.glyph => Paint{ .glyph = p.u.glyph },
.solid => Paint{ .solid = p.u.solid },
.linear_gradient => Paint{ .linear_gradient = p.u.linear_gradient },
.radial_gradient => Paint{ .radial_gradient = p.u.radial_gradient },
.sweep_gradient => Paint{ .sweep_gradient = p.u.sweep_gradient },
.transform => Paint{ .transform = p.u.transform },
.translate => Paint{ .translate = p.u.translate },
.scale => Paint{ .scale = p.u.scale },
.rotate => Paint{ .rotate = p.u.rotate },
.skew => Paint{ .skew = p.u.skew },
.composite => Paint{ .composite = p.u.composite },
.color_glyph => Paint{ .color_glyph = p.u.colr_glyph },
};
}
pub fn newSize(self: Face) Error!Size {
var s: c.FT_Size = undefined;
try intToError(c.FT_New_Size(self.handle, &s));
return Size{ .handle = s };
}
pub fn numFaces(self: Face) u32 {
return @intCast(u32, self.handle.*.num_faces);
}
pub fn faceIndex(self: Face) u32 {
return @intCast(u32, self.handle.*.face_index);
}
pub fn faceFlags(self: Face) FaceFlags {
return FaceFlags.from(@intCast(u19, self.handle.*.face_flags));
}
pub fn styleFlags(self: Face) StyleFlags {
return StyleFlags.from(@intCast(u2, self.handle.*.style_flags));
}
pub fn numGlyphs(self: Face) u32 {
return @intCast(u32, self.handle.*.num_glyphs);
}
pub fn familyName(self: Face) ?[:0]const u8 {
return if (self.handle.*.family_name) |family|
std.mem.span(family)
else
null;
}
pub fn styleName(self: Face) ?[:0]const u8 {
return if (self.handle.*.style_name) |style_name|
std.mem.span(style_name)
else
null;
}
pub fn numFixedSizes(self: Face) u32 {
return @intCast(u32, self.handle.*.num_fixed_sizes);
}
pub fn availableSizes(self: Face) ?BitmapSize {
return if (self.handle.*.available_sizes != null)
self.handle.*.available_sizes.*
else
null;
}
pub fn numCharmaps(self: Face) u32 {
return @intCast(u32, self.handle.*.num_charmaps);
}
pub fn charmaps(self: Face) []const CharMap {
return @ptrCast([]const CharMap, self.handle.*.charmaps[0..self.numCharmaps()]);
}
pub fn bbox(self: Face) BBox {
return self.handle.*.bbox;
}
pub fn unitsPerEM(self: Face) u16 {
return self.handle.*.units_per_EM;
}
pub fn ascender(self: Face) i16 {
return self.handle.*.ascender;
}
pub fn descender(self: Face) i16 {
return self.handle.*.descender;
}
pub fn height(self: Face) i16 {
return self.handle.*.height;
}
pub fn maxAdvanceWidth(self: Face) i16 {
return self.handle.*.max_advance_width;
}
pub fn maxAdvanceHeight(self: Face) i16 {
return self.handle.*.max_advance_height;
}
pub fn underlinePosition(self: Face) i16 {
return self.handle.*.underline_position;
}
pub fn underlineThickness(self: Face) i16 {
return self.handle.*.underline_thickness;
}
pub fn glyph(self: Face) GlyphSlot {
return .{ .handle = self.handle.*.glyph };
}
pub fn size(self: Face) Size {
return Size{ .handle = self.handle.*.size };
}
pub fn charmap(self: Face) CharMap {
return self.handle.*.charmap.*;
}
pub fn hasHorizontal(self: Face) bool {
return c.FT_HAS_HORIZONTAL(self.handle);
}
pub fn hasVertical(self: Face) bool {
return c.FT_HAS_VERTICAL(self.handle);
}
pub fn hasKerning(self: Face) bool {
return c.FT_HAS_KERNING(self.handle);
}
pub fn hasFixedSizes(self: Face) bool {
return c.FT_HAS_FIXED_SIZES(self.handle);
}
pub fn hasGlyphNames(self: Face) bool {
return c.FT_HAS_GLYPH_NAMES(self.handle);
}
pub fn hasColor(self: Face) bool {
return c.FT_HAS_COLOR(self.handle);
}
pub fn isScalable(self: Face) bool {
return c.FT_IS_SCALABLE(self.handle);
}
pub fn isSfnt(self: Face) bool {
return c.FT_IS_SFNT(self.handle);
}
pub fn isFixedWidth(self: Face) bool {
return c.FT_IS_FIXED_WIDTH(self.handle);
}
pub fn isCidKeyed(self: Face) bool {
return c.FT_IS_CID_KEYED(self.handle);
}
pub fn isTricky(self: Face) bool {
return c.FT_IS_TRICKY(self.handle);
} | freetype/src/freetype/Face.zig |
const std = @import("std");
const assert = std.debug.assert;
const tools = @import("tools");
pub fn run(input: []const u8, allocator: std.mem.Allocator) ![2][]const u8 {
var count_with_pairs: usize = 0;
var count_with_triplets: usize = 0;
// part1
{
var it = std.mem.tokenize(u8, input, ", \n\r\t");
while (it.next()) |line| {
var letter_count = [1]u8{0} ** 128;
for (line) |c| {
letter_count[c] += 1;
}
var has_pair = false;
var has_triplet = false;
for (letter_count) |c| {
has_pair = has_pair or c == 2;
has_triplet = has_triplet or c == 3;
}
if (has_pair) count_with_pairs += 1;
if (has_triplet) count_with_triplets += 1;
}
}
// part2
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const ans2 = blk: {
var outer = std.mem.tokenize(u8, input, ", \n\r\t");
while (outer.next()) |outer_line| {
var inner = std.mem.tokenize(u8, input, ", \n\r\t");
while (inner.next()) |inner_line| {
assert(outer_line.len == inner_line.len);
var diffs: usize = 0;
for (outer_line) |outer_letter, i| {
if (outer_letter != inner_line[i]) diffs += 1;
}
if (diffs == 1) {
const common = try arena.allocator().alloc(u8, outer_line.len - 1);
var j: usize = 0;
for (outer_line) |letter, i| {
if (letter == inner_line[i]) {
common[j] = letter;
j += 1;
}
}
assert(j == common.len);
break :blk common;
}
}
}
unreachable;
};
return [_][]const u8{
try std.fmt.allocPrint(allocator, "{}", .{count_with_pairs * count_with_triplets}),
try std.fmt.allocPrint(allocator, "{s}", .{ans2}),
};
}
pub const main = tools.defaultMain("2018/input_day02.txt", run); | 2018/day02.zig |
const std = @import("std");
usingnamespace @import("shared.zig");
var tag_collection: std.StringHashMap(void) = undefined;
var allocator: *std.mem.Allocator = undefined;
var string_arena: *std.mem.Allocator = undefined;
pub fn main() !u8 {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
allocator = &gpa.allocator;
var string_arena_impl = std.heap.ArenaAllocator.init(allocator);
defer string_arena_impl.deinit();
string_arena = &string_arena_impl.allocator;
tag_collection = std.StringHashMap(void).init(allocator);
defer tag_collection.deinit();
var success = true;
if (!try verifyFolder("tags", verifyTagJson))
success = false;
if (!try verifyFolder("packages", verifyPackageJson))
success = false;
return if (success) @as(u8, 0) else 1;
}
const VerifierFunction = fn (
name: []const u8,
data: []const u8,
errors: *std.ArrayList([]const u8),
) anyerror!void;
fn verifyFolder(directory_name: []const u8, verifier: VerifierFunction) !bool {
const stderr_file = std.io.getStdErr();
const stderr = stderr_file.writer();
var directory = try std.fs.cwd().openDir(directory_name, .{ .iterate = true, .no_follow = true });
defer directory.close();
var success = true;
var iterator = directory.iterate();
while (try iterator.next()) |entry| {
if (entry.kind != .File)
continue;
if (std.mem.endsWith(u8, entry.name, ".json")) {
var file = try directory.openFile(entry.name, .{ .read = true, .write = false });
defer file.close();
const source = try file.readToEndAlloc(allocator, 16384); // 16kB is a sane limit for a package description
defer allocator.free(source);
const name = entry.name[0 .. entry.name.len - 5];
var errors = std.ArrayList([]const u8).init(allocator);
defer errors.deinit();
verifier(name, source, &errors) catch |err| {
try errors.append(@errorName(err));
};
if (errors.items.len > 0) {
try stderr.print("{s}/{s} is not a valid package description file:\n", .{
directory_name,
entry.name,
});
for (errors.items) |err| {
try stderr.print("\t{s}\n", .{err});
}
success = false;
}
} else {
try stderr.print("{s}/{s} is not a json file!\n", .{ directory_name, entry.name });
success = false;
}
}
return success;
}
fn verifyTagJson(
name: []const u8,
json_data: []const u8,
errors: *std.ArrayList([]const u8),
) !void {
var options = std.json.ParseOptions{
.allocator = allocator,
.duplicate_field_behavior = .Error,
};
var stream = std.json.TokenStream.init(json_data);
const tag = try std.json.parse(TagDescription, &stream, options);
defer std.json.parseFree(TagDescription, tag, options);
if (tag.description.len == 0)
try errors.append("description is empty!");
try tag_collection.put(try string_arena.dupe(u8, name), {}); // file names ought to be unique
}
fn verifyPackageJson(
name: []const u8,
json_data: []const u8,
errors: *std.ArrayList([]const u8),
) !void {
var options = std.json.ParseOptions{
.allocator = allocator,
.duplicate_field_behavior = .Error,
};
var stream = std.json.TokenStream.init(json_data);
const pkg = try std.json.parse(PackageDescription, &stream, options);
defer std.json.parseFree(PackageDescription, pkg, options);
if (pkg.author.len == 0)
try errors.append("author is empty!");
if (pkg.git.len == 0)
try errors.append("git is empty!");
if (pkg.description.len == 0)
try errors.append("description is empty!");
if (pkg.root_file) |root| {
if (root.len == 0) {
try errors.append("root_file is empty! Use 'null' if the root file is unrequired.");
} else if (!std.mem.startsWith(u8, root, "/")) {
try errors.append("root_file must start with a '/'!");
}
}
for (pkg.tags) |tag| {
const entry = tag_collection.get(tag);
if (entry == null) {
try errors.append(try std.fmt.allocPrint(string_arena, "Tag '{s}' does not exist!", .{tag}));
}
}
} | tools/verifier.zig |
pub const RTCCS_FORCE_PROFILE = @as(u32, 1);
pub const RTCCS_FAIL_ON_REDIRECT = @as(u32, 2);
pub const RTCMT_AUDIO_SEND = @as(u32, 1);
pub const RTCMT_AUDIO_RECEIVE = @as(u32, 2);
pub const RTCMT_VIDEO_SEND = @as(u32, 4);
pub const RTCMT_VIDEO_RECEIVE = @as(u32, 8);
pub const RTCMT_T120_SENDRECV = @as(u32, 16);
pub const RTCSI_PC_TO_PC = @as(u32, 1);
pub const RTCSI_PC_TO_PHONE = @as(u32, 2);
pub const RTCSI_PHONE_TO_PHONE = @as(u32, 4);
pub const RTCSI_IM = @as(u32, 8);
pub const RTCSI_MULTIPARTY_IM = @as(u32, 16);
pub const RTCSI_APPLICATION = @as(u32, 32);
pub const RTCTR_UDP = @as(u32, 1);
pub const RTCTR_TCP = @as(u32, 2);
pub const RTCTR_TLS = @as(u32, 4);
pub const RTCAU_BASIC = @as(u32, 1);
pub const RTCAU_DIGEST = @as(u32, 2);
pub const RTCAU_NTLM = @as(u32, 4);
pub const RTCAU_KERBEROS = @as(u32, 8);
pub const RTCAU_USE_LOGON_CRED = @as(u32, 65536);
pub const RTCRF_REGISTER_INVITE_SESSIONS = @as(u32, 1);
pub const RTCRF_REGISTER_MESSAGE_SESSIONS = @as(u32, 2);
pub const RTCRF_REGISTER_PRESENCE = @as(u32, 4);
pub const RTCRF_REGISTER_NOTIFY = @as(u32, 8);
pub const RTCRF_REGISTER_ALL = @as(u32, 15);
pub const RTCRMF_BUDDY_ROAMING = @as(u32, 1);
pub const RTCRMF_WATCHER_ROAMING = @as(u32, 2);
pub const RTCRMF_PRESENCE_ROAMING = @as(u32, 4);
pub const RTCRMF_PROFILE_ROAMING = @as(u32, 8);
pub const RTCRMF_ALL_ROAMING = @as(u32, 15);
pub const RTCEF_CLIENT = @as(u32, 1);
pub const RTCEF_REGISTRATION_STATE_CHANGE = @as(u32, 2);
pub const RTCEF_SESSION_STATE_CHANGE = @as(u32, 4);
pub const RTCEF_SESSION_OPERATION_COMPLETE = @as(u32, 8);
pub const RTCEF_PARTICIPANT_STATE_CHANGE = @as(u32, 16);
pub const RTCEF_MEDIA = @as(u32, 32);
pub const RTCEF_INTENSITY = @as(u32, 64);
pub const RTCEF_MESSAGING = @as(u32, 128);
pub const RTCEF_BUDDY = @as(u32, 256);
pub const RTCEF_WATCHER = @as(u32, 512);
pub const RTCEF_PROFILE = @as(u32, 1024);
pub const RTCEF_USERSEARCH = @as(u32, 2048);
pub const RTCEF_INFO = @as(u32, 4096);
pub const RTCEF_GROUP = @as(u32, 8192);
pub const RTCEF_MEDIA_REQUEST = @as(u32, 16384);
pub const RTCEF_ROAMING = @as(u32, 65536);
pub const RTCEF_PRESENCE_PROPERTY = @as(u32, 131072);
pub const RTCEF_BUDDY2 = @as(u32, 262144);
pub const RTCEF_WATCHER2 = @as(u32, 524288);
pub const RTCEF_SESSION_REFER_STATUS = @as(u32, 1048576);
pub const RTCEF_SESSION_REFERRED = @as(u32, 2097152);
pub const RTCEF_REINVITE = @as(u32, 4194304);
pub const RTCEF_PRESENCE_DATA = @as(u32, 8388608);
pub const RTCEF_PRESENCE_STATUS = @as(u32, 16777216);
pub const RTCEF_ALL = @as(u32, 33554431);
pub const RTCIF_DISABLE_MEDIA = @as(u32, 1);
pub const RTCIF_DISABLE_UPNP = @as(u32, 2);
pub const RTCIF_ENABLE_SERVER_CLASS = @as(u32, 4);
pub const RTCIF_DISABLE_STRICT_DNS = @as(u32, 8);
pub const FACILITY_RTC_INTERFACE = @as(u32, 238);
pub const FACILITY_SIP_STATUS_CODE = @as(u32, 239);
pub const FACILITY_PINT_STATUS_CODE = @as(u32, 240);
pub const STATUS_SEVERITY_RTC_ERROR = @as(u32, 2);
pub const RTC_E_SIP_CODECS_DO_NOT_MATCH = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886080));
pub const RTC_E_SIP_STREAM_PRESENT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886079));
pub const RTC_E_SIP_STREAM_NOT_PRESENT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886078));
pub const RTC_E_SIP_NO_STREAM = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886077));
pub const RTC_E_SIP_PARSE_FAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886076));
pub const RTC_E_SIP_HEADER_NOT_PRESENT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886075));
pub const RTC_E_SDP_NOT_PRESENT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886074));
pub const RTC_E_SDP_PARSE_FAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886073));
pub const RTC_E_SDP_UPDATE_FAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886072));
pub const RTC_E_SDP_MULTICAST = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886071));
pub const RTC_E_SDP_CONNECTION_ADDR = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886070));
pub const RTC_E_SDP_NO_MEDIA = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886069));
pub const RTC_E_SIP_TIMEOUT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886068));
pub const RTC_E_SDP_FAILED_TO_BUILD = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886067));
pub const RTC_E_SIP_INVITE_TRANSACTION_PENDING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886066));
pub const RTC_E_SIP_AUTH_HEADER_SENT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886065));
pub const RTC_E_SIP_AUTH_TYPE_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886064));
pub const RTC_E_SIP_AUTH_FAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886063));
pub const RTC_E_INVALID_SIP_URL = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886062));
pub const RTC_E_DESTINATION_ADDRESS_LOCAL = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886061));
pub const RTC_E_INVALID_ADDRESS_LOCAL = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886060));
pub const RTC_E_DESTINATION_ADDRESS_MULTICAST = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886059));
pub const RTC_E_INVALID_PROXY_ADDRESS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886058));
pub const RTC_E_SIP_TRANSPORT_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886057));
pub const RTC_E_SIP_NEED_MORE_DATA = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886056));
pub const RTC_E_SIP_CALL_DISCONNECTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886055));
pub const RTC_E_SIP_REQUEST_DESTINATION_ADDR_NOT_PRESENT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886054));
pub const RTC_E_SIP_UDP_SIZE_EXCEEDED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886053));
pub const RTC_E_SIP_SSL_TUNNEL_FAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886052));
pub const RTC_E_SIP_SSL_NEGOTIATION_TIMEOUT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886051));
pub const RTC_E_SIP_STACK_SHUTDOWN = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886050));
pub const RTC_E_MEDIA_CONTROLLER_STATE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886049));
pub const RTC_E_MEDIA_NEED_TERMINAL = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886048));
pub const RTC_E_MEDIA_AUDIO_DEVICE_NOT_AVAILABLE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886047));
pub const RTC_E_MEDIA_VIDEO_DEVICE_NOT_AVAILABLE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886046));
pub const RTC_E_START_STREAM = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886045));
pub const RTC_E_MEDIA_AEC = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886044));
pub const RTC_E_CLIENT_NOT_INITIALIZED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886043));
pub const RTC_E_CLIENT_ALREADY_INITIALIZED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886042));
pub const RTC_E_CLIENT_ALREADY_SHUT_DOWN = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886041));
pub const RTC_E_PRESENCE_NOT_ENABLED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886040));
pub const RTC_E_INVALID_SESSION_TYPE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886039));
pub const RTC_E_INVALID_SESSION_STATE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886038));
pub const RTC_E_NO_PROFILE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886037));
pub const RTC_E_LOCAL_PHONE_NEEDED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886036));
pub const RTC_E_NO_DEVICE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886035));
pub const RTC_E_INVALID_PROFILE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886034));
pub const RTC_E_PROFILE_NO_PROVISION = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886033));
pub const RTC_E_PROFILE_NO_KEY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886032));
pub const RTC_E_PROFILE_NO_NAME = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886031));
pub const RTC_E_PROFILE_NO_USER = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886030));
pub const RTC_E_PROFILE_NO_USER_URI = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886029));
pub const RTC_E_PROFILE_NO_SERVER = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886028));
pub const RTC_E_PROFILE_NO_SERVER_ADDRESS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886027));
pub const RTC_E_PROFILE_NO_SERVER_PROTOCOL = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886026));
pub const RTC_E_PROFILE_INVALID_SERVER_PROTOCOL = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886025));
pub const RTC_E_PROFILE_INVALID_SERVER_AUTHMETHOD = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886024));
pub const RTC_E_PROFILE_INVALID_SERVER_ROLE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886023));
pub const RTC_E_PROFILE_MULTIPLE_REGISTRARS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886022));
pub const RTC_E_PROFILE_INVALID_SESSION = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886021));
pub const RTC_E_PROFILE_INVALID_SESSION_PARTY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886020));
pub const RTC_E_PROFILE_INVALID_SESSION_TYPE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886019));
pub const RTC_E_OPERATION_WITH_TOO_MANY_PARTICIPANTS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886018));
pub const RTC_E_BASIC_AUTH_SET_TLS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886017));
pub const RTC_E_SIP_HIGH_SECURITY_SET_TLS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886016));
pub const RTC_S_ROAMING_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, 15597633));
pub const RTC_E_PROFILE_SERVER_UNAUTHORIZED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886014));
pub const RTC_E_DUPLICATE_REALM = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886013));
pub const RTC_E_POLICY_NOT_ALLOW = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886012));
pub const RTC_E_PORT_MAPPING_UNAVAILABLE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886011));
pub const RTC_E_PORT_MAPPING_FAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886010));
pub const RTC_E_SECURITY_LEVEL_NOT_COMPATIBLE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886009));
pub const RTC_E_SECURITY_LEVEL_NOT_DEFINED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886008));
pub const RTC_E_SECURITY_LEVEL_NOT_SUPPORTED_BY_PARTICIPANT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886007));
pub const RTC_E_DUPLICATE_BUDDY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886006));
pub const RTC_E_DUPLICATE_WATCHER = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886005));
pub const RTC_E_MALFORMED_XML = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886004));
pub const RTC_E_ROAMING_OPERATION_INTERRUPTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886003));
pub const RTC_E_ROAMING_FAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886002));
pub const RTC_E_INVALID_BUDDY_LIST = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886001));
pub const RTC_E_INVALID_ACL_LIST = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131886000));
pub const RTC_E_NO_GROUP = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885999));
pub const RTC_E_DUPLICATE_GROUP = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885998));
pub const RTC_E_TOO_MANY_GROUPS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885997));
pub const RTC_E_NO_BUDDY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885996));
pub const RTC_E_NO_WATCHER = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885995));
pub const RTC_E_NO_REALM = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885994));
pub const RTC_E_NO_TRANSPORT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885993));
pub const RTC_E_NOT_EXIST = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885992));
pub const RTC_E_INVALID_PREFERENCE_LIST = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885991));
pub const RTC_E_MAX_PENDING_OPERATIONS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885990));
pub const RTC_E_TOO_MANY_RETRIES = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885989));
pub const RTC_E_INVALID_PORTRANGE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885988));
pub const RTC_E_SIP_CALL_CONNECTION_NOT_ESTABLISHED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885987));
pub const RTC_E_SIP_ADDITIONAL_PARTY_IN_TWO_PARTY_SESSION = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885986));
pub const RTC_E_SIP_PARTY_ALREADY_IN_SESSION = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885985));
pub const RTC_E_SIP_OTHER_PARTY_JOIN_IN_PROGRESS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885984));
pub const RTC_E_INVALID_OBJECT_STATE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885983));
pub const RTC_E_PRESENCE_ENABLED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885982));
pub const RTC_E_ROAMING_ENABLED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885981));
pub const RTC_E_SIP_TLS_INCOMPATIBLE_ENCRYPTION = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885980));
pub const RTC_E_SIP_INVALID_CERTIFICATE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885979));
pub const RTC_E_SIP_DNS_FAIL = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885978));
pub const RTC_E_SIP_TCP_FAIL = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885977));
pub const RTC_E_TOO_SMALL_EXPIRES_VALUE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885976));
pub const RTC_E_SIP_TLS_FAIL = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885975));
pub const RTC_E_NOT_PRESENCE_PROFILE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885974));
pub const RTC_E_SIP_INVITEE_PARTY_TIMEOUT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885973));
pub const RTC_E_SIP_AUTH_TIME_SKEW = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885972));
pub const RTC_E_INVALID_REGISTRATION_STATE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885971));
pub const RTC_E_MEDIA_DISABLED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885970));
pub const RTC_E_MEDIA_ENABLED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885969));
pub const RTC_E_REFER_NOT_ACCEPTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885968));
pub const RTC_E_REFER_NOT_ALLOWED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885967));
pub const RTC_E_REFER_NOT_EXIST = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885966));
pub const RTC_E_SIP_HOLD_OPERATION_PENDING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885965));
pub const RTC_E_SIP_UNHOLD_OPERATION_PENDING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885964));
pub const RTC_E_MEDIA_SESSION_NOT_EXIST = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885963));
pub const RTC_E_MEDIA_SESSION_IN_HOLD = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885962));
pub const RTC_E_ANOTHER_MEDIA_SESSION_ACTIVE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885961));
pub const RTC_E_MAX_REDIRECTS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885960));
pub const RTC_E_REDIRECT_PROCESSING_FAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885959));
pub const RTC_E_LISTENING_SOCKET_NOT_EXIST = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885958));
pub const RTC_E_INVALID_LISTEN_SOCKET = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885957));
pub const RTC_E_PORT_MANAGER_ALREADY_SET = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885956));
pub const RTC_E_SECURITY_LEVEL_ALREADY_SET = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885955));
pub const RTC_E_UDP_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885954));
pub const RTC_E_SIP_REFER_OPERATION_PENDING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885953));
pub const RTC_E_PLATFORM_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885952));
pub const RTC_E_SIP_PEER_PARTICIPANT_IN_MULTIPARTY_SESSION = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885951));
pub const RTC_E_NOT_ALLOWED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885950));
pub const RTC_E_REGISTRATION_DEACTIVATED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885949));
pub const RTC_E_REGISTRATION_REJECTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885948));
pub const RTC_E_REGISTRATION_UNREGISTERED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131885947));
pub const RTC_E_STATUS_INFO_TRYING = @import("../zig.zig").typedConst(HRESULT, @as(i32, 15663204));
pub const RTC_E_STATUS_INFO_RINGING = @import("../zig.zig").typedConst(HRESULT, @as(i32, 15663284));
pub const RTC_E_STATUS_INFO_CALL_FORWARDING = @import("../zig.zig").typedConst(HRESULT, @as(i32, 15663285));
pub const RTC_E_STATUS_INFO_QUEUED = @import("../zig.zig").typedConst(HRESULT, @as(i32, 15663286));
pub const RTC_E_STATUS_SESSION_PROGRESS = @import("../zig.zig").typedConst(HRESULT, @as(i32, 15663287));
pub const RTC_E_STATUS_SUCCESS = @import("../zig.zig").typedConst(HRESULT, @as(i32, 15663304));
pub const RTC_E_STATUS_REDIRECT_MULTIPLE_CHOICES = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820244));
pub const RTC_E_STATUS_REDIRECT_MOVED_PERMANENTLY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820243));
pub const RTC_E_STATUS_REDIRECT_MOVED_TEMPORARILY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820242));
pub const RTC_E_STATUS_REDIRECT_SEE_OTHER = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820241));
pub const RTC_E_STATUS_REDIRECT_USE_PROXY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820239));
pub const RTC_E_STATUS_REDIRECT_ALTERNATIVE_SERVICE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820164));
pub const RTC_E_STATUS_CLIENT_BAD_REQUEST = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820144));
pub const RTC_E_STATUS_CLIENT_UNAUTHORIZED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820143));
pub const RTC_E_STATUS_CLIENT_PAYMENT_REQUIRED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820142));
pub const RTC_E_STATUS_CLIENT_FORBIDDEN = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820141));
pub const RTC_E_STATUS_CLIENT_NOT_FOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820140));
pub const RTC_E_STATUS_CLIENT_METHOD_NOT_ALLOWED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820139));
pub const RTC_E_STATUS_CLIENT_NOT_ACCEPTABLE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820138));
pub const RTC_E_STATUS_CLIENT_PROXY_AUTHENTICATION_REQUIRED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820137));
pub const RTC_E_STATUS_CLIENT_REQUEST_TIMEOUT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820136));
pub const RTC_E_STATUS_CLIENT_CONFLICT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820135));
pub const RTC_E_STATUS_CLIENT_GONE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820134));
pub const RTC_E_STATUS_CLIENT_LENGTH_REQUIRED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820133));
pub const RTC_E_STATUS_CLIENT_REQUEST_ENTITY_TOO_LARGE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820131));
pub const RTC_E_STATUS_CLIENT_REQUEST_URI_TOO_LARGE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820130));
pub const RTC_E_STATUS_CLIENT_UNSUPPORTED_MEDIA_TYPE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820129));
pub const RTC_E_STATUS_CLIENT_BAD_EXTENSION = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820124));
pub const RTC_E_STATUS_CLIENT_TEMPORARILY_NOT_AVAILABLE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820064));
pub const RTC_E_STATUS_CLIENT_TRANSACTION_DOES_NOT_EXIST = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820063));
pub const RTC_E_STATUS_CLIENT_LOOP_DETECTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820062));
pub const RTC_E_STATUS_CLIENT_TOO_MANY_HOPS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820061));
pub const RTC_E_STATUS_CLIENT_ADDRESS_INCOMPLETE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820060));
pub const RTC_E_STATUS_CLIENT_AMBIGUOUS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820059));
pub const RTC_E_STATUS_CLIENT_BUSY_HERE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820058));
pub const RTC_E_STATUS_REQUEST_TERMINATED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820057));
pub const RTC_E_STATUS_NOT_ACCEPTABLE_HERE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820056));
pub const RTC_E_STATUS_SERVER_INTERNAL_ERROR = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820044));
pub const RTC_E_STATUS_SERVER_NOT_IMPLEMENTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820043));
pub const RTC_E_STATUS_SERVER_BAD_GATEWAY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820042));
pub const RTC_E_STATUS_SERVER_SERVICE_UNAVAILABLE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820041));
pub const RTC_E_STATUS_SERVER_SERVER_TIMEOUT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820040));
pub const RTC_E_STATUS_SERVER_VERSION_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131820039));
pub const RTC_E_STATUS_GLOBAL_BUSY_EVERYWHERE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131819944));
pub const RTC_E_STATUS_GLOBAL_DECLINE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131819941));
pub const RTC_E_STATUS_GLOBAL_DOES_NOT_EXIST_ANYWHERE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131819940));
pub const RTC_E_STATUS_GLOBAL_NOT_ACCEPTABLE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131819938));
pub const RTC_E_PINT_STATUS_REJECTED_BUSY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131755003));
pub const RTC_E_PINT_STATUS_REJECTED_NO_ANSWER = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131755002));
pub const RTC_E_PINT_STATUS_REJECTED_ALL_BUSY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131755001));
pub const RTC_E_PINT_STATUS_REJECTED_PL_FAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131755000));
pub const RTC_E_PINT_STATUS_REJECTED_SW_FAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131754999));
pub const RTC_E_PINT_STATUS_REJECTED_CANCELLED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131754998));
pub const RTC_E_PINT_STATUS_REJECTED_BADNUMBER = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2131754997));
//--------------------------------------------------------------------------------
// Section: Types (107)
//--------------------------------------------------------------------------------
const CLSID_RTCClient_Value = @import("../zig.zig").Guid.initString("7a42ea29-a2b7-40c4-b091-f6f024aa89be");
pub const CLSID_RTCClient = &CLSID_RTCClient_Value;
pub const RTC_AUDIO_DEVICE = enum(i32) {
SPEAKER = 0,
MICROPHONE = 1,
};
pub const RTCAD_SPEAKER = RTC_AUDIO_DEVICE.SPEAKER;
pub const RTCAD_MICROPHONE = RTC_AUDIO_DEVICE.MICROPHONE;
pub const RTC_VIDEO_DEVICE = enum(i32) {
RECEIVE = 0,
PREVIEW = 1,
};
pub const RTCVD_RECEIVE = RTC_VIDEO_DEVICE.RECEIVE;
pub const RTCVD_PREVIEW = RTC_VIDEO_DEVICE.PREVIEW;
pub const RTC_EVENT = enum(i32) {
CLIENT = 0,
REGISTRATION_STATE_CHANGE = 1,
SESSION_STATE_CHANGE = 2,
SESSION_OPERATION_COMPLETE = 3,
PARTICIPANT_STATE_CHANGE = 4,
MEDIA = 5,
INTENSITY = 6,
MESSAGING = 7,
BUDDY = 8,
WATCHER = 9,
PROFILE = 10,
USERSEARCH = 11,
INFO = 12,
GROUP = 13,
MEDIA_REQUEST = 14,
ROAMING = 15,
PRESENCE_PROPERTY = 16,
PRESENCE_DATA = 17,
PRESENCE_STATUS = 18,
SESSION_REFER_STATUS = 19,
SESSION_REFERRED = 20,
REINVITE = 21,
};
pub const RTCE_CLIENT = RTC_EVENT.CLIENT;
pub const RTCE_REGISTRATION_STATE_CHANGE = RTC_EVENT.REGISTRATION_STATE_CHANGE;
pub const RTCE_SESSION_STATE_CHANGE = RTC_EVENT.SESSION_STATE_CHANGE;
pub const RTCE_SESSION_OPERATION_COMPLETE = RTC_EVENT.SESSION_OPERATION_COMPLETE;
pub const RTCE_PARTICIPANT_STATE_CHANGE = RTC_EVENT.PARTICIPANT_STATE_CHANGE;
pub const RTCE_MEDIA = RTC_EVENT.MEDIA;
pub const RTCE_INTENSITY = RTC_EVENT.INTENSITY;
pub const RTCE_MESSAGING = RTC_EVENT.MESSAGING;
pub const RTCE_BUDDY = RTC_EVENT.BUDDY;
pub const RTCE_WATCHER = RTC_EVENT.WATCHER;
pub const RTCE_PROFILE = RTC_EVENT.PROFILE;
pub const RTCE_USERSEARCH = RTC_EVENT.USERSEARCH;
pub const RTCE_INFO = RTC_EVENT.INFO;
pub const RTCE_GROUP = RTC_EVENT.GROUP;
pub const RTCE_MEDIA_REQUEST = RTC_EVENT.MEDIA_REQUEST;
pub const RTCE_ROAMING = RTC_EVENT.ROAMING;
pub const RTCE_PRESENCE_PROPERTY = RTC_EVENT.PRESENCE_PROPERTY;
pub const RTCE_PRESENCE_DATA = RTC_EVENT.PRESENCE_DATA;
pub const RTCE_PRESENCE_STATUS = RTC_EVENT.PRESENCE_STATUS;
pub const RTCE_SESSION_REFER_STATUS = RTC_EVENT.SESSION_REFER_STATUS;
pub const RTCE_SESSION_REFERRED = RTC_EVENT.SESSION_REFERRED;
pub const RTCE_REINVITE = RTC_EVENT.REINVITE;
pub const RTC_LISTEN_MODE = enum(i32) {
NONE = 0,
DYNAMIC = 1,
BOTH = 2,
};
pub const RTCLM_NONE = RTC_LISTEN_MODE.NONE;
pub const RTCLM_DYNAMIC = RTC_LISTEN_MODE.DYNAMIC;
pub const RTCLM_BOTH = RTC_LISTEN_MODE.BOTH;
pub const RTC_CLIENT_EVENT_TYPE = enum(i32) {
VOLUME_CHANGE = 0,
DEVICE_CHANGE = 1,
NETWORK_QUALITY_CHANGE = 2,
ASYNC_CLEANUP_DONE = 3,
};
pub const RTCCET_VOLUME_CHANGE = RTC_CLIENT_EVENT_TYPE.VOLUME_CHANGE;
pub const RTCCET_DEVICE_CHANGE = RTC_CLIENT_EVENT_TYPE.DEVICE_CHANGE;
pub const RTCCET_NETWORK_QUALITY_CHANGE = RTC_CLIENT_EVENT_TYPE.NETWORK_QUALITY_CHANGE;
pub const RTCCET_ASYNC_CLEANUP_DONE = RTC_CLIENT_EVENT_TYPE.ASYNC_CLEANUP_DONE;
pub const RTC_BUDDY_EVENT_TYPE = enum(i32) {
ADD = 0,
REMOVE = 1,
UPDATE = 2,
STATE_CHANGE = 3,
ROAMED = 4,
SUBSCRIBED = 5,
};
pub const RTCBET_BUDDY_ADD = RTC_BUDDY_EVENT_TYPE.ADD;
pub const RTCBET_BUDDY_REMOVE = RTC_BUDDY_EVENT_TYPE.REMOVE;
pub const RTCBET_BUDDY_UPDATE = RTC_BUDDY_EVENT_TYPE.UPDATE;
pub const RTCBET_BUDDY_STATE_CHANGE = RTC_BUDDY_EVENT_TYPE.STATE_CHANGE;
pub const RTCBET_BUDDY_ROAMED = RTC_BUDDY_EVENT_TYPE.ROAMED;
pub const RTCBET_BUDDY_SUBSCRIBED = RTC_BUDDY_EVENT_TYPE.SUBSCRIBED;
pub const RTC_WATCHER_EVENT_TYPE = enum(i32) {
ADD = 0,
REMOVE = 1,
UPDATE = 2,
OFFERING = 3,
ROAMED = 4,
};
pub const RTCWET_WATCHER_ADD = RTC_WATCHER_EVENT_TYPE.ADD;
pub const RTCWET_WATCHER_REMOVE = RTC_WATCHER_EVENT_TYPE.REMOVE;
pub const RTCWET_WATCHER_UPDATE = RTC_WATCHER_EVENT_TYPE.UPDATE;
pub const RTCWET_WATCHER_OFFERING = RTC_WATCHER_EVENT_TYPE.OFFERING;
pub const RTCWET_WATCHER_ROAMED = RTC_WATCHER_EVENT_TYPE.ROAMED;
pub const RTC_GROUP_EVENT_TYPE = enum(i32) {
ADD = 0,
REMOVE = 1,
UPDATE = 2,
BUDDY_ADD = 3,
BUDDY_REMOVE = 4,
ROAMED = 5,
};
pub const RTCGET_GROUP_ADD = RTC_GROUP_EVENT_TYPE.ADD;
pub const RTCGET_GROUP_REMOVE = RTC_GROUP_EVENT_TYPE.REMOVE;
pub const RTCGET_GROUP_UPDATE = RTC_GROUP_EVENT_TYPE.UPDATE;
pub const RTCGET_GROUP_BUDDY_ADD = RTC_GROUP_EVENT_TYPE.BUDDY_ADD;
pub const RTCGET_GROUP_BUDDY_REMOVE = RTC_GROUP_EVENT_TYPE.BUDDY_REMOVE;
pub const RTCGET_GROUP_ROAMED = RTC_GROUP_EVENT_TYPE.ROAMED;
pub const RTC_TERMINATE_REASON = enum(i32) {
NORMAL = 0,
DND = 1,
BUSY = 2,
REJECT = 3,
TIMEOUT = 4,
SHUTDOWN = 5,
INSUFFICIENT_SECURITY_LEVEL = 6,
NOT_SUPPORTED = 7,
};
pub const RTCTR_NORMAL = RTC_TERMINATE_REASON.NORMAL;
pub const RTCTR_DND = RTC_TERMINATE_REASON.DND;
pub const RTCTR_BUSY = RTC_TERMINATE_REASON.BUSY;
pub const RTCTR_REJECT = RTC_TERMINATE_REASON.REJECT;
pub const RTCTR_TIMEOUT = RTC_TERMINATE_REASON.TIMEOUT;
pub const RTCTR_SHUTDOWN = RTC_TERMINATE_REASON.SHUTDOWN;
pub const RTCTR_INSUFFICIENT_SECURITY_LEVEL = RTC_TERMINATE_REASON.INSUFFICIENT_SECURITY_LEVEL;
pub const RTCTR_NOT_SUPPORTED = RTC_TERMINATE_REASON.NOT_SUPPORTED;
pub const RTC_REGISTRATION_STATE = enum(i32) {
NOT_REGISTERED = 0,
REGISTERING = 1,
REGISTERED = 2,
REJECTED = 3,
UNREGISTERING = 4,
ERROR = 5,
LOGGED_OFF = 6,
LOCAL_PA_LOGGED_OFF = 7,
REMOTE_PA_LOGGED_OFF = 8,
};
pub const RTCRS_NOT_REGISTERED = RTC_REGISTRATION_STATE.NOT_REGISTERED;
pub const RTCRS_REGISTERING = RTC_REGISTRATION_STATE.REGISTERING;
pub const RTCRS_REGISTERED = RTC_REGISTRATION_STATE.REGISTERED;
pub const RTCRS_REJECTED = RTC_REGISTRATION_STATE.REJECTED;
pub const RTCRS_UNREGISTERING = RTC_REGISTRATION_STATE.UNREGISTERING;
pub const RTCRS_ERROR = RTC_REGISTRATION_STATE.ERROR;
pub const RTCRS_LOGGED_OFF = RTC_REGISTRATION_STATE.LOGGED_OFF;
pub const RTCRS_LOCAL_PA_LOGGED_OFF = RTC_REGISTRATION_STATE.LOCAL_PA_LOGGED_OFF;
pub const RTCRS_REMOTE_PA_LOGGED_OFF = RTC_REGISTRATION_STATE.REMOTE_PA_LOGGED_OFF;
pub const RTC_SESSION_STATE = enum(i32) {
IDLE = 0,
INCOMING = 1,
ANSWERING = 2,
INPROGRESS = 3,
CONNECTED = 4,
DISCONNECTED = 5,
HOLD = 6,
REFER = 7,
};
pub const RTCSS_IDLE = RTC_SESSION_STATE.IDLE;
pub const RTCSS_INCOMING = RTC_SESSION_STATE.INCOMING;
pub const RTCSS_ANSWERING = RTC_SESSION_STATE.ANSWERING;
pub const RTCSS_INPROGRESS = RTC_SESSION_STATE.INPROGRESS;
pub const RTCSS_CONNECTED = RTC_SESSION_STATE.CONNECTED;
pub const RTCSS_DISCONNECTED = RTC_SESSION_STATE.DISCONNECTED;
pub const RTCSS_HOLD = RTC_SESSION_STATE.HOLD;
pub const RTCSS_REFER = RTC_SESSION_STATE.REFER;
pub const RTC_PARTICIPANT_STATE = enum(i32) {
IDLE = 0,
PENDING = 1,
INCOMING = 2,
ANSWERING = 3,
INPROGRESS = 4,
ALERTING = 5,
CONNECTED = 6,
DISCONNECTING = 7,
DISCONNECTED = 8,
};
pub const RTCPS_IDLE = RTC_PARTICIPANT_STATE.IDLE;
pub const RTCPS_PENDING = RTC_PARTICIPANT_STATE.PENDING;
pub const RTCPS_INCOMING = RTC_PARTICIPANT_STATE.INCOMING;
pub const RTCPS_ANSWERING = RTC_PARTICIPANT_STATE.ANSWERING;
pub const RTCPS_INPROGRESS = RTC_PARTICIPANT_STATE.INPROGRESS;
pub const RTCPS_ALERTING = RTC_PARTICIPANT_STATE.ALERTING;
pub const RTCPS_CONNECTED = RTC_PARTICIPANT_STATE.CONNECTED;
pub const RTCPS_DISCONNECTING = RTC_PARTICIPANT_STATE.DISCONNECTING;
pub const RTCPS_DISCONNECTED = RTC_PARTICIPANT_STATE.DISCONNECTED;
pub const RTC_WATCHER_STATE = enum(i32) {
UNKNOWN = 0,
OFFERING = 1,
ALLOWED = 2,
BLOCKED = 3,
DENIED = 4,
PROMPT = 5,
};
pub const RTCWS_UNKNOWN = RTC_WATCHER_STATE.UNKNOWN;
pub const RTCWS_OFFERING = RTC_WATCHER_STATE.OFFERING;
pub const RTCWS_ALLOWED = RTC_WATCHER_STATE.ALLOWED;
pub const RTCWS_BLOCKED = RTC_WATCHER_STATE.BLOCKED;
pub const RTCWS_DENIED = RTC_WATCHER_STATE.DENIED;
pub const RTCWS_PROMPT = RTC_WATCHER_STATE.PROMPT;
pub const RTC_ACE_SCOPE = enum(i32) {
USER = 0,
DOMAIN = 1,
ALL = 2,
};
pub const RTCAS_SCOPE_USER = RTC_ACE_SCOPE.USER;
pub const RTCAS_SCOPE_DOMAIN = RTC_ACE_SCOPE.DOMAIN;
pub const RTCAS_SCOPE_ALL = RTC_ACE_SCOPE.ALL;
pub const RTC_OFFER_WATCHER_MODE = enum(i32) {
OFFER_WATCHER_EVENT = 0,
AUTOMATICALLY_ADD_WATCHER = 1,
};
pub const RTCOWM_OFFER_WATCHER_EVENT = RTC_OFFER_WATCHER_MODE.OFFER_WATCHER_EVENT;
pub const RTCOWM_AUTOMATICALLY_ADD_WATCHER = RTC_OFFER_WATCHER_MODE.AUTOMATICALLY_ADD_WATCHER;
pub const RTC_WATCHER_MATCH_MODE = enum(i32) {
EXACT_MATCH = 0,
BEST_ACE_MATCH = 1,
};
pub const RTCWMM_EXACT_MATCH = RTC_WATCHER_MATCH_MODE.EXACT_MATCH;
pub const RTCWMM_BEST_ACE_MATCH = RTC_WATCHER_MATCH_MODE.BEST_ACE_MATCH;
pub const RTC_PRIVACY_MODE = enum(i32) {
BLOCK_LIST_EXCLUDED = 0,
ALLOW_LIST_ONLY = 1,
};
pub const RTCPM_BLOCK_LIST_EXCLUDED = RTC_PRIVACY_MODE.BLOCK_LIST_EXCLUDED;
pub const RTCPM_ALLOW_LIST_ONLY = RTC_PRIVACY_MODE.ALLOW_LIST_ONLY;
pub const RTC_SESSION_TYPE = enum(i32) {
PC_TO_PC = 0,
PC_TO_PHONE = 1,
PHONE_TO_PHONE = 2,
IM = 3,
MULTIPARTY_IM = 4,
APPLICATION = 5,
};
pub const RTCST_PC_TO_PC = RTC_SESSION_TYPE.PC_TO_PC;
pub const RTCST_PC_TO_PHONE = RTC_SESSION_TYPE.PC_TO_PHONE;
pub const RTCST_PHONE_TO_PHONE = RTC_SESSION_TYPE.PHONE_TO_PHONE;
pub const RTCST_IM = RTC_SESSION_TYPE.IM;
pub const RTCST_MULTIPARTY_IM = RTC_SESSION_TYPE.MULTIPARTY_IM;
pub const RTCST_APPLICATION = RTC_SESSION_TYPE.APPLICATION;
pub const RTC_PRESENCE_STATUS = enum(i32) {
OFFLINE = 0,
ONLINE = 1,
AWAY = 2,
IDLE = 3,
BUSY = 4,
BE_RIGHT_BACK = 5,
ON_THE_PHONE = 6,
OUT_TO_LUNCH = 7,
};
pub const RTCXS_PRESENCE_OFFLINE = RTC_PRESENCE_STATUS.OFFLINE;
pub const RTCXS_PRESENCE_ONLINE = RTC_PRESENCE_STATUS.ONLINE;
pub const RTCXS_PRESENCE_AWAY = RTC_PRESENCE_STATUS.AWAY;
pub const RTCXS_PRESENCE_IDLE = RTC_PRESENCE_STATUS.IDLE;
pub const RTCXS_PRESENCE_BUSY = RTC_PRESENCE_STATUS.BUSY;
pub const RTCXS_PRESENCE_BE_RIGHT_BACK = RTC_PRESENCE_STATUS.BE_RIGHT_BACK;
pub const RTCXS_PRESENCE_ON_THE_PHONE = RTC_PRESENCE_STATUS.ON_THE_PHONE;
pub const RTCXS_PRESENCE_OUT_TO_LUNCH = RTC_PRESENCE_STATUS.OUT_TO_LUNCH;
pub const RTC_BUDDY_SUBSCRIPTION_TYPE = enum(i32) {
SUBSCRIBED = 0,
ALWAYS_OFFLINE = 1,
ALWAYS_ONLINE = 2,
POLL = 3,
};
pub const RTCBT_SUBSCRIBED = RTC_BUDDY_SUBSCRIPTION_TYPE.SUBSCRIBED;
pub const RTCBT_ALWAYS_OFFLINE = RTC_BUDDY_SUBSCRIPTION_TYPE.ALWAYS_OFFLINE;
pub const RTCBT_ALWAYS_ONLINE = RTC_BUDDY_SUBSCRIPTION_TYPE.ALWAYS_ONLINE;
pub const RTCBT_POLL = RTC_BUDDY_SUBSCRIPTION_TYPE.POLL;
pub const RTC_MEDIA_EVENT_TYPE = enum(i32) {
STOPPED = 0,
STARTED = 1,
FAILED = 2,
};
pub const RTCMET_STOPPED = RTC_MEDIA_EVENT_TYPE.STOPPED;
pub const RTCMET_STARTED = RTC_MEDIA_EVENT_TYPE.STARTED;
pub const RTCMET_FAILED = RTC_MEDIA_EVENT_TYPE.FAILED;
pub const RTC_MEDIA_EVENT_REASON = enum(i32) {
NORMAL = 0,
HOLD = 1,
TIMEOUT = 2,
BAD_DEVICE = 3,
NO_PORT = 4,
PORT_MAPPING_FAILED = 5,
REMOTE_REQUEST = 6,
};
pub const RTCMER_NORMAL = RTC_MEDIA_EVENT_REASON.NORMAL;
pub const RTCMER_HOLD = RTC_MEDIA_EVENT_REASON.HOLD;
pub const RTCMER_TIMEOUT = RTC_MEDIA_EVENT_REASON.TIMEOUT;
pub const RTCMER_BAD_DEVICE = RTC_MEDIA_EVENT_REASON.BAD_DEVICE;
pub const RTCMER_NO_PORT = RTC_MEDIA_EVENT_REASON.NO_PORT;
pub const RTCMER_PORT_MAPPING_FAILED = RTC_MEDIA_EVENT_REASON.PORT_MAPPING_FAILED;
pub const RTCMER_REMOTE_REQUEST = RTC_MEDIA_EVENT_REASON.REMOTE_REQUEST;
pub const RTC_MESSAGING_EVENT_TYPE = enum(i32) {
MESSAGE = 0,
STATUS = 1,
};
pub const RTCMSET_MESSAGE = RTC_MESSAGING_EVENT_TYPE.MESSAGE;
pub const RTCMSET_STATUS = RTC_MESSAGING_EVENT_TYPE.STATUS;
pub const RTC_MESSAGING_USER_STATUS = enum(i32) {
IDLE = 0,
TYPING = 1,
};
pub const RTCMUS_IDLE = RTC_MESSAGING_USER_STATUS.IDLE;
pub const RTCMUS_TYPING = RTC_MESSAGING_USER_STATUS.TYPING;
pub const RTC_DTMF = enum(i32) {
@"0" = 0,
@"1" = 1,
@"2" = 2,
@"3" = 3,
@"4" = 4,
@"5" = 5,
@"6" = 6,
@"7" = 7,
@"8" = 8,
@"9" = 9,
STAR = 10,
POUND = 11,
A = 12,
B = 13,
C = 14,
D = 15,
FLASH = 16,
};
pub const RTC_DTMF_0 = RTC_DTMF.@"0";
pub const RTC_DTMF_1 = RTC_DTMF.@"1";
pub const RTC_DTMF_2 = RTC_DTMF.@"2";
pub const RTC_DTMF_3 = RTC_DTMF.@"3";
pub const RTC_DTMF_4 = RTC_DTMF.@"4";
pub const RTC_DTMF_5 = RTC_DTMF.@"5";
pub const RTC_DTMF_6 = RTC_DTMF.@"6";
pub const RTC_DTMF_7 = RTC_DTMF.@"7";
pub const RTC_DTMF_8 = RTC_DTMF.@"8";
pub const RTC_DTMF_9 = RTC_DTMF.@"9";
pub const RTC_DTMF_STAR = RTC_DTMF.STAR;
pub const RTC_DTMF_POUND = RTC_DTMF.POUND;
pub const RTC_DTMF_A = RTC_DTMF.A;
pub const RTC_DTMF_B = RTC_DTMF.B;
pub const RTC_DTMF_C = RTC_DTMF.C;
pub const RTC_DTMF_D = RTC_DTMF.D;
pub const RTC_DTMF_FLASH = RTC_DTMF.FLASH;
pub const RTC_PROVIDER_URI = enum(i32) {
HOMEPAGE = 0,
HELPDESK = 1,
PERSONALACCOUNT = 2,
DISPLAYDURINGCALL = 3,
DISPLAYDURINGIDLE = 4,
};
pub const RTCPU_URIHOMEPAGE = RTC_PROVIDER_URI.HOMEPAGE;
pub const RTCPU_URIHELPDESK = RTC_PROVIDER_URI.HELPDESK;
pub const RTCPU_URIPERSONALACCOUNT = RTC_PROVIDER_URI.PERSONALACCOUNT;
pub const RTCPU_URIDISPLAYDURINGCALL = RTC_PROVIDER_URI.DISPLAYDURINGCALL;
pub const RTCPU_URIDISPLAYDURINGIDLE = RTC_PROVIDER_URI.DISPLAYDURINGIDLE;
pub const RTC_RING_TYPE = enum(i32) {
PHONE = 0,
MESSAGE = 1,
RINGBACK = 2,
};
pub const RTCRT_PHONE = RTC_RING_TYPE.PHONE;
pub const RTCRT_MESSAGE = RTC_RING_TYPE.MESSAGE;
pub const RTCRT_RINGBACK = RTC_RING_TYPE.RINGBACK;
pub const RTC_T120_APPLET = enum(i32) {
WHITEBOARD = 0,
APPSHARING = 1,
};
pub const RTCTA_WHITEBOARD = RTC_T120_APPLET.WHITEBOARD;
pub const RTCTA_APPSHARING = RTC_T120_APPLET.APPSHARING;
pub const RTC_PORT_TYPE = enum(i32) {
AUDIO_RTP = 0,
AUDIO_RTCP = 1,
VIDEO_RTP = 2,
VIDEO_RTCP = 3,
SIP = 4,
};
pub const RTCPT_AUDIO_RTP = RTC_PORT_TYPE.AUDIO_RTP;
pub const RTCPT_AUDIO_RTCP = RTC_PORT_TYPE.AUDIO_RTCP;
pub const RTCPT_VIDEO_RTP = RTC_PORT_TYPE.VIDEO_RTP;
pub const RTCPT_VIDEO_RTCP = RTC_PORT_TYPE.VIDEO_RTCP;
pub const RTCPT_SIP = RTC_PORT_TYPE.SIP;
pub const RTC_USER_SEARCH_COLUMN = enum(i32) {
URI = 0,
DISPLAYNAME = 1,
TITLE = 2,
OFFICE = 3,
PHONE = 4,
COMPANY = 5,
CITY = 6,
STATE = 7,
COUNTRY = 8,
EMAIL = 9,
};
pub const RTCUSC_URI = RTC_USER_SEARCH_COLUMN.URI;
pub const RTCUSC_DISPLAYNAME = RTC_USER_SEARCH_COLUMN.DISPLAYNAME;
pub const RTCUSC_TITLE = RTC_USER_SEARCH_COLUMN.TITLE;
pub const RTCUSC_OFFICE = RTC_USER_SEARCH_COLUMN.OFFICE;
pub const RTCUSC_PHONE = RTC_USER_SEARCH_COLUMN.PHONE;
pub const RTCUSC_COMPANY = RTC_USER_SEARCH_COLUMN.COMPANY;
pub const RTCUSC_CITY = RTC_USER_SEARCH_COLUMN.CITY;
pub const RTCUSC_STATE = RTC_USER_SEARCH_COLUMN.STATE;
pub const RTCUSC_COUNTRY = RTC_USER_SEARCH_COLUMN.COUNTRY;
pub const RTCUSC_EMAIL = RTC_USER_SEARCH_COLUMN.EMAIL;
pub const RTC_USER_SEARCH_PREFERENCE = enum(i32) {
MAX_MATCHES = 0,
TIME_LIMIT = 1,
};
pub const RTCUSP_MAX_MATCHES = RTC_USER_SEARCH_PREFERENCE.MAX_MATCHES;
pub const RTCUSP_TIME_LIMIT = RTC_USER_SEARCH_PREFERENCE.TIME_LIMIT;
pub const RTC_ROAMING_EVENT_TYPE = enum(i32) {
BUDDY_ROAMING = 0,
WATCHER_ROAMING = 1,
PRESENCE_ROAMING = 2,
PROFILE_ROAMING = 3,
WPENDING_ROAMING = 4,
};
pub const RTCRET_BUDDY_ROAMING = RTC_ROAMING_EVENT_TYPE.BUDDY_ROAMING;
pub const RTCRET_WATCHER_ROAMING = RTC_ROAMING_EVENT_TYPE.WATCHER_ROAMING;
pub const RTCRET_PRESENCE_ROAMING = RTC_ROAMING_EVENT_TYPE.PRESENCE_ROAMING;
pub const RTCRET_PROFILE_ROAMING = RTC_ROAMING_EVENT_TYPE.PROFILE_ROAMING;
pub const RTCRET_WPENDING_ROAMING = RTC_ROAMING_EVENT_TYPE.WPENDING_ROAMING;
pub const RTC_PROFILE_EVENT_TYPE = enum(i32) {
GET = 0,
UPDATE = 1,
};
pub const RTCPFET_PROFILE_GET = RTC_PROFILE_EVENT_TYPE.GET;
pub const RTCPFET_PROFILE_UPDATE = RTC_PROFILE_EVENT_TYPE.UPDATE;
pub const RTC_ANSWER_MODE = enum(i32) {
OFFER_SESSION_EVENT = 0,
AUTOMATICALLY_ACCEPT = 1,
AUTOMATICALLY_REJECT = 2,
NOT_SUPPORTED = 3,
};
pub const RTCAM_OFFER_SESSION_EVENT = RTC_ANSWER_MODE.OFFER_SESSION_EVENT;
pub const RTCAM_AUTOMATICALLY_ACCEPT = RTC_ANSWER_MODE.AUTOMATICALLY_ACCEPT;
pub const RTCAM_AUTOMATICALLY_REJECT = RTC_ANSWER_MODE.AUTOMATICALLY_REJECT;
pub const RTCAM_NOT_SUPPORTED = RTC_ANSWER_MODE.NOT_SUPPORTED;
pub const RTC_SESSION_REFER_STATUS = enum(i32) {
REFERRING = 0,
ACCEPTED = 1,
ERROR = 2,
REJECTED = 3,
DROPPED = 4,
DONE = 5,
};
pub const RTCSRS_REFERRING = RTC_SESSION_REFER_STATUS.REFERRING;
pub const RTCSRS_ACCEPTED = RTC_SESSION_REFER_STATUS.ACCEPTED;
pub const RTCSRS_ERROR = RTC_SESSION_REFER_STATUS.ERROR;
pub const RTCSRS_REJECTED = RTC_SESSION_REFER_STATUS.REJECTED;
pub const RTCSRS_DROPPED = RTC_SESSION_REFER_STATUS.DROPPED;
pub const RTCSRS_DONE = RTC_SESSION_REFER_STATUS.DONE;
pub const RTC_PRESENCE_PROPERTY = enum(i32) {
PHONENUMBER = 0,
DISPLAYNAME = 1,
EMAIL = 2,
DEVICE_NAME = 3,
MULTIPLE = 4,
};
pub const RTCPP_PHONENUMBER = RTC_PRESENCE_PROPERTY.PHONENUMBER;
pub const RTCPP_DISPLAYNAME = RTC_PRESENCE_PROPERTY.DISPLAYNAME;
pub const RTCPP_EMAIL = RTC_PRESENCE_PROPERTY.EMAIL;
pub const RTCPP_DEVICE_NAME = RTC_PRESENCE_PROPERTY.DEVICE_NAME;
pub const RTCPP_MULTIPLE = RTC_PRESENCE_PROPERTY.MULTIPLE;
pub const RTC_SECURITY_TYPE = enum(i32) {
AUDIO_VIDEO_MEDIA_ENCRYPTION = 0,
T120_MEDIA_ENCRYPTION = 1,
};
pub const RTCSECT_AUDIO_VIDEO_MEDIA_ENCRYPTION = RTC_SECURITY_TYPE.AUDIO_VIDEO_MEDIA_ENCRYPTION;
pub const RTCSECT_T120_MEDIA_ENCRYPTION = RTC_SECURITY_TYPE.T120_MEDIA_ENCRYPTION;
pub const RTC_SECURITY_LEVEL = enum(i32) {
UNSUPPORTED = 1,
SUPPORTED = 2,
REQUIRED = 3,
};
pub const RTCSECL_UNSUPPORTED = RTC_SECURITY_LEVEL.UNSUPPORTED;
pub const RTCSECL_SUPPORTED = RTC_SECURITY_LEVEL.SUPPORTED;
pub const RTCSECL_REQUIRED = RTC_SECURITY_LEVEL.REQUIRED;
pub const RTC_REINVITE_STATE = enum(i32) {
INCOMING = 0,
SUCCEEDED = 1,
FAIL = 2,
};
pub const RTCRIN_INCOMING = RTC_REINVITE_STATE.INCOMING;
pub const RTCRIN_SUCCEEDED = RTC_REINVITE_STATE.SUCCEEDED;
pub const RTCRIN_FAIL = RTC_REINVITE_STATE.FAIL;
const IID_IRTCClient_Value = @import("../zig.zig").Guid.initString("07829e45-9a34-408e-a011-bddf13487cd1");
pub const IID_IRTCClient = &IID_IRTCClient_Value;
pub const IRTCClient = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Initialize: fn(
self: *const IRTCClient,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Shutdown: fn(
self: *const IRTCClient,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
PrepareForShutdown: fn(
self: *const IRTCClient,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_EventFilter: fn(
self: *const IRTCClient,
lFilter: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_EventFilter: fn(
self: *const IRTCClient,
plFilter: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetPreferredMediaTypes: fn(
self: *const IRTCClient,
lMediaTypes: i32,
fPersistent: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_PreferredMediaTypes: fn(
self: *const IRTCClient,
plMediaTypes: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_MediaCapabilities: fn(
self: *const IRTCClient,
plMediaTypes: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateSession: fn(
self: *const IRTCClient,
enType: RTC_SESSION_TYPE,
bstrLocalPhoneURI: ?BSTR,
pProfile: ?*IRTCProfile,
lFlags: i32,
ppSession: ?*?*IRTCSession,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_ListenForIncomingSessions: fn(
self: *const IRTCClient,
enListen: RTC_LISTEN_MODE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ListenForIncomingSessions: fn(
self: *const IRTCClient,
penListen: ?*RTC_LISTEN_MODE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_NetworkAddresses: fn(
self: *const IRTCClient,
fTCP: i16,
fExternal: i16,
pvAddresses: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Volume: fn(
self: *const IRTCClient,
enDevice: RTC_AUDIO_DEVICE,
lVolume: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Volume: fn(
self: *const IRTCClient,
enDevice: RTC_AUDIO_DEVICE,
plVolume: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_AudioMuted: fn(
self: *const IRTCClient,
enDevice: RTC_AUDIO_DEVICE,
fMuted: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_AudioMuted: fn(
self: *const IRTCClient,
enDevice: RTC_AUDIO_DEVICE,
pfMuted: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_IVideoWindow: fn(
self: *const IRTCClient,
enDevice: RTC_VIDEO_DEVICE,
ppIVideoWindow: ?*?*IVideoWindow,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_PreferredAudioDevice: fn(
self: *const IRTCClient,
enDevice: RTC_AUDIO_DEVICE,
bstrDeviceName: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_PreferredAudioDevice: fn(
self: *const IRTCClient,
enDevice: RTC_AUDIO_DEVICE,
pbstrDeviceName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_PreferredVolume: fn(
self: *const IRTCClient,
enDevice: RTC_AUDIO_DEVICE,
lVolume: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_PreferredVolume: fn(
self: *const IRTCClient,
enDevice: RTC_AUDIO_DEVICE,
plVolume: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_PreferredAEC: fn(
self: *const IRTCClient,
bEnable: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_PreferredAEC: fn(
self: *const IRTCClient,
pbEnabled: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_PreferredVideoDevice: fn(
self: *const IRTCClient,
bstrDeviceName: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_PreferredVideoDevice: fn(
self: *const IRTCClient,
pbstrDeviceName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ActiveMedia: fn(
self: *const IRTCClient,
plMediaType: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_MaxBitrate: fn(
self: *const IRTCClient,
lMaxBitrate: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_MaxBitrate: fn(
self: *const IRTCClient,
plMaxBitrate: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_TemporalSpatialTradeOff: fn(
self: *const IRTCClient,
lValue: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_TemporalSpatialTradeOff: fn(
self: *const IRTCClient,
plValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_NetworkQuality: fn(
self: *const IRTCClient,
plNetworkQuality: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
StartT120Applet: fn(
self: *const IRTCClient,
enApplet: RTC_T120_APPLET,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
StopT120Applets: fn(
self: *const IRTCClient,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_IsT120AppletRunning: fn(
self: *const IRTCClient,
enApplet: RTC_T120_APPLET,
pfRunning: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_LocalUserURI: fn(
self: *const IRTCClient,
pbstrUserURI: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_LocalUserURI: fn(
self: *const IRTCClient,
bstrUserURI: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_LocalUserName: fn(
self: *const IRTCClient,
pbstrUserName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_LocalUserName: fn(
self: *const IRTCClient,
bstrUserName: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
PlayRing: fn(
self: *const IRTCClient,
enType: RTC_RING_TYPE,
bPlay: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SendDTMF: fn(
self: *const IRTCClient,
enDTMF: RTC_DTMF,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
InvokeTuningWizard: fn(
self: *const IRTCClient,
hwndParent: isize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_IsTuned: fn(
self: *const IRTCClient,
pfTuned: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_Initialize(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).Initialize(@ptrCast(*const IRTCClient, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_Shutdown(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).Shutdown(@ptrCast(*const IRTCClient, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_PrepareForShutdown(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).PrepareForShutdown(@ptrCast(*const IRTCClient, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_put_EventFilter(self: *const T, lFilter: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).put_EventFilter(@ptrCast(*const IRTCClient, self), lFilter);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_get_EventFilter(self: *const T, plFilter: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).get_EventFilter(@ptrCast(*const IRTCClient, self), plFilter);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_SetPreferredMediaTypes(self: *const T, lMediaTypes: i32, fPersistent: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).SetPreferredMediaTypes(@ptrCast(*const IRTCClient, self), lMediaTypes, fPersistent);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_get_PreferredMediaTypes(self: *const T, plMediaTypes: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).get_PreferredMediaTypes(@ptrCast(*const IRTCClient, self), plMediaTypes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_get_MediaCapabilities(self: *const T, plMediaTypes: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).get_MediaCapabilities(@ptrCast(*const IRTCClient, self), plMediaTypes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_CreateSession(self: *const T, enType: RTC_SESSION_TYPE, bstrLocalPhoneURI: ?BSTR, pProfile: ?*IRTCProfile, lFlags: i32, ppSession: ?*?*IRTCSession) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).CreateSession(@ptrCast(*const IRTCClient, self), enType, bstrLocalPhoneURI, pProfile, lFlags, ppSession);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_put_ListenForIncomingSessions(self: *const T, enListen: RTC_LISTEN_MODE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).put_ListenForIncomingSessions(@ptrCast(*const IRTCClient, self), enListen);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_get_ListenForIncomingSessions(self: *const T, penListen: ?*RTC_LISTEN_MODE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).get_ListenForIncomingSessions(@ptrCast(*const IRTCClient, self), penListen);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_get_NetworkAddresses(self: *const T, fTCP: i16, fExternal: i16, pvAddresses: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).get_NetworkAddresses(@ptrCast(*const IRTCClient, self), fTCP, fExternal, pvAddresses);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_put_Volume(self: *const T, enDevice: RTC_AUDIO_DEVICE, lVolume: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).put_Volume(@ptrCast(*const IRTCClient, self), enDevice, lVolume);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_get_Volume(self: *const T, enDevice: RTC_AUDIO_DEVICE, plVolume: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).get_Volume(@ptrCast(*const IRTCClient, self), enDevice, plVolume);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_put_AudioMuted(self: *const T, enDevice: RTC_AUDIO_DEVICE, fMuted: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).put_AudioMuted(@ptrCast(*const IRTCClient, self), enDevice, fMuted);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_get_AudioMuted(self: *const T, enDevice: RTC_AUDIO_DEVICE, pfMuted: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).get_AudioMuted(@ptrCast(*const IRTCClient, self), enDevice, pfMuted);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_get_IVideoWindow(self: *const T, enDevice: RTC_VIDEO_DEVICE, ppIVideoWindow: ?*?*IVideoWindow) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).get_IVideoWindow(@ptrCast(*const IRTCClient, self), enDevice, ppIVideoWindow);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_put_PreferredAudioDevice(self: *const T, enDevice: RTC_AUDIO_DEVICE, bstrDeviceName: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).put_PreferredAudioDevice(@ptrCast(*const IRTCClient, self), enDevice, bstrDeviceName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_get_PreferredAudioDevice(self: *const T, enDevice: RTC_AUDIO_DEVICE, pbstrDeviceName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).get_PreferredAudioDevice(@ptrCast(*const IRTCClient, self), enDevice, pbstrDeviceName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_put_PreferredVolume(self: *const T, enDevice: RTC_AUDIO_DEVICE, lVolume: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).put_PreferredVolume(@ptrCast(*const IRTCClient, self), enDevice, lVolume);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_get_PreferredVolume(self: *const T, enDevice: RTC_AUDIO_DEVICE, plVolume: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).get_PreferredVolume(@ptrCast(*const IRTCClient, self), enDevice, plVolume);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_put_PreferredAEC(self: *const T, bEnable: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).put_PreferredAEC(@ptrCast(*const IRTCClient, self), bEnable);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_get_PreferredAEC(self: *const T, pbEnabled: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).get_PreferredAEC(@ptrCast(*const IRTCClient, self), pbEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_put_PreferredVideoDevice(self: *const T, bstrDeviceName: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).put_PreferredVideoDevice(@ptrCast(*const IRTCClient, self), bstrDeviceName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_get_PreferredVideoDevice(self: *const T, pbstrDeviceName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).get_PreferredVideoDevice(@ptrCast(*const IRTCClient, self), pbstrDeviceName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_get_ActiveMedia(self: *const T, plMediaType: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).get_ActiveMedia(@ptrCast(*const IRTCClient, self), plMediaType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_put_MaxBitrate(self: *const T, lMaxBitrate: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).put_MaxBitrate(@ptrCast(*const IRTCClient, self), lMaxBitrate);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_get_MaxBitrate(self: *const T, plMaxBitrate: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).get_MaxBitrate(@ptrCast(*const IRTCClient, self), plMaxBitrate);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_put_TemporalSpatialTradeOff(self: *const T, lValue: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).put_TemporalSpatialTradeOff(@ptrCast(*const IRTCClient, self), lValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_get_TemporalSpatialTradeOff(self: *const T, plValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).get_TemporalSpatialTradeOff(@ptrCast(*const IRTCClient, self), plValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_get_NetworkQuality(self: *const T, plNetworkQuality: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).get_NetworkQuality(@ptrCast(*const IRTCClient, self), plNetworkQuality);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_StartT120Applet(self: *const T, enApplet: RTC_T120_APPLET) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).StartT120Applet(@ptrCast(*const IRTCClient, self), enApplet);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_StopT120Applets(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).StopT120Applets(@ptrCast(*const IRTCClient, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_get_IsT120AppletRunning(self: *const T, enApplet: RTC_T120_APPLET, pfRunning: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).get_IsT120AppletRunning(@ptrCast(*const IRTCClient, self), enApplet, pfRunning);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_get_LocalUserURI(self: *const T, pbstrUserURI: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).get_LocalUserURI(@ptrCast(*const IRTCClient, self), pbstrUserURI);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_put_LocalUserURI(self: *const T, bstrUserURI: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).put_LocalUserURI(@ptrCast(*const IRTCClient, self), bstrUserURI);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_get_LocalUserName(self: *const T, pbstrUserName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).get_LocalUserName(@ptrCast(*const IRTCClient, self), pbstrUserName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_put_LocalUserName(self: *const T, bstrUserName: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).put_LocalUserName(@ptrCast(*const IRTCClient, self), bstrUserName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_PlayRing(self: *const T, enType: RTC_RING_TYPE, bPlay: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).PlayRing(@ptrCast(*const IRTCClient, self), enType, bPlay);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_SendDTMF(self: *const T, enDTMF: RTC_DTMF) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).SendDTMF(@ptrCast(*const IRTCClient, self), enDTMF);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_InvokeTuningWizard(self: *const T, hwndParent: isize) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).InvokeTuningWizard(@ptrCast(*const IRTCClient, self), hwndParent);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient_get_IsTuned(self: *const T, pfTuned: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient.VTable, self.vtable).get_IsTuned(@ptrCast(*const IRTCClient, self), pfTuned);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCClient2_Value = @import("../zig.zig").Guid.initString("0c91d71d-1064-42da-bfa5-572beb8eea84");
pub const IID_IRTCClient2 = &IID_IRTCClient2_Value;
pub const IRTCClient2 = extern struct {
pub const VTable = extern struct {
base: IRTCClient.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_AnswerMode: fn(
self: *const IRTCClient2,
enType: RTC_SESSION_TYPE,
enMode: RTC_ANSWER_MODE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_AnswerMode: fn(
self: *const IRTCClient2,
enType: RTC_SESSION_TYPE,
penMode: ?*RTC_ANSWER_MODE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
InvokeTuningWizardEx: fn(
self: *const IRTCClient2,
hwndParent: isize,
fAllowAudio: i16,
fAllowVideo: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Version: fn(
self: *const IRTCClient2,
plVersion: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_ClientName: fn(
self: *const IRTCClient2,
bstrClientName: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_ClientCurVer: fn(
self: *const IRTCClient2,
bstrClientCurVer: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
InitializeEx: fn(
self: *const IRTCClient2,
lFlags: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateSessionWithDescription: fn(
self: *const IRTCClient2,
bstrContentType: ?BSTR,
bstrSessionDescription: ?BSTR,
pProfile: ?*IRTCProfile,
lFlags: i32,
ppSession2: ?*?*IRTCSession2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetSessionDescriptionManager: fn(
self: *const IRTCClient2,
pSessionDescriptionManager: ?*IRTCSessionDescriptionManager,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_PreferredSecurityLevel: fn(
self: *const IRTCClient2,
enSecurityType: RTC_SECURITY_TYPE,
enSecurityLevel: RTC_SECURITY_LEVEL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_PreferredSecurityLevel: fn(
self: *const IRTCClient2,
enSecurityType: RTC_SECURITY_TYPE,
penSecurityLevel: ?*RTC_SECURITY_LEVEL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_AllowedPorts: fn(
self: *const IRTCClient2,
lTransport: i32,
enListenMode: RTC_LISTEN_MODE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_AllowedPorts: fn(
self: *const IRTCClient2,
lTransport: i32,
penListenMode: ?*RTC_LISTEN_MODE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IRTCClient.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient2_put_AnswerMode(self: *const T, enType: RTC_SESSION_TYPE, enMode: RTC_ANSWER_MODE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient2.VTable, self.vtable).put_AnswerMode(@ptrCast(*const IRTCClient2, self), enType, enMode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient2_get_AnswerMode(self: *const T, enType: RTC_SESSION_TYPE, penMode: ?*RTC_ANSWER_MODE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient2.VTable, self.vtable).get_AnswerMode(@ptrCast(*const IRTCClient2, self), enType, penMode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient2_InvokeTuningWizardEx(self: *const T, hwndParent: isize, fAllowAudio: i16, fAllowVideo: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient2.VTable, self.vtable).InvokeTuningWizardEx(@ptrCast(*const IRTCClient2, self), hwndParent, fAllowAudio, fAllowVideo);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient2_get_Version(self: *const T, plVersion: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient2.VTable, self.vtable).get_Version(@ptrCast(*const IRTCClient2, self), plVersion);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient2_put_ClientName(self: *const T, bstrClientName: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient2.VTable, self.vtable).put_ClientName(@ptrCast(*const IRTCClient2, self), bstrClientName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient2_put_ClientCurVer(self: *const T, bstrClientCurVer: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient2.VTable, self.vtable).put_ClientCurVer(@ptrCast(*const IRTCClient2, self), bstrClientCurVer);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient2_InitializeEx(self: *const T, lFlags: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient2.VTable, self.vtable).InitializeEx(@ptrCast(*const IRTCClient2, self), lFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient2_CreateSessionWithDescription(self: *const T, bstrContentType: ?BSTR, bstrSessionDescription: ?BSTR, pProfile: ?*IRTCProfile, lFlags: i32, ppSession2: ?*?*IRTCSession2) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient2.VTable, self.vtable).CreateSessionWithDescription(@ptrCast(*const IRTCClient2, self), bstrContentType, bstrSessionDescription, pProfile, lFlags, ppSession2);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient2_SetSessionDescriptionManager(self: *const T, pSessionDescriptionManager: ?*IRTCSessionDescriptionManager) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient2.VTable, self.vtable).SetSessionDescriptionManager(@ptrCast(*const IRTCClient2, self), pSessionDescriptionManager);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient2_put_PreferredSecurityLevel(self: *const T, enSecurityType: RTC_SECURITY_TYPE, enSecurityLevel: RTC_SECURITY_LEVEL) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient2.VTable, self.vtable).put_PreferredSecurityLevel(@ptrCast(*const IRTCClient2, self), enSecurityType, enSecurityLevel);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient2_get_PreferredSecurityLevel(self: *const T, enSecurityType: RTC_SECURITY_TYPE, penSecurityLevel: ?*RTC_SECURITY_LEVEL) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient2.VTable, self.vtable).get_PreferredSecurityLevel(@ptrCast(*const IRTCClient2, self), enSecurityType, penSecurityLevel);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient2_put_AllowedPorts(self: *const T, lTransport: i32, enListenMode: RTC_LISTEN_MODE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient2.VTable, self.vtable).put_AllowedPorts(@ptrCast(*const IRTCClient2, self), lTransport, enListenMode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClient2_get_AllowedPorts(self: *const T, lTransport: i32, penListenMode: ?*RTC_LISTEN_MODE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClient2.VTable, self.vtable).get_AllowedPorts(@ptrCast(*const IRTCClient2, self), lTransport, penListenMode);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCClientPresence_Value = @import("../zig.zig").Guid.initString("11c3cbcc-0744-42d1-968a-51aa1bb274c6");
pub const IID_IRTCClientPresence = &IID_IRTCClientPresence_Value;
pub const IRTCClientPresence = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
EnablePresence: fn(
self: *const IRTCClientPresence,
fUseStorage: i16,
varStorage: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Export: fn(
self: *const IRTCClientPresence,
varStorage: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Import: fn(
self: *const IRTCClientPresence,
varStorage: VARIANT,
fReplaceAll: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EnumerateBuddies: fn(
self: *const IRTCClientPresence,
ppEnum: ?*?*IRTCEnumBuddies,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Buddies: fn(
self: *const IRTCClientPresence,
ppCollection: ?*?*IRTCCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Buddy: fn(
self: *const IRTCClientPresence,
bstrPresentityURI: ?BSTR,
ppBuddy: ?*?*IRTCBuddy,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddBuddy: fn(
self: *const IRTCClientPresence,
bstrPresentityURI: ?BSTR,
bstrUserName: ?BSTR,
bstrData: ?BSTR,
fPersistent: i16,
pProfile: ?*IRTCProfile,
lFlags: i32,
ppBuddy: ?*?*IRTCBuddy,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveBuddy: fn(
self: *const IRTCClientPresence,
pBuddy: ?*IRTCBuddy,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EnumerateWatchers: fn(
self: *const IRTCClientPresence,
ppEnum: ?*?*IRTCEnumWatchers,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Watchers: fn(
self: *const IRTCClientPresence,
ppCollection: ?*?*IRTCCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Watcher: fn(
self: *const IRTCClientPresence,
bstrPresentityURI: ?BSTR,
ppWatcher: ?*?*IRTCWatcher,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddWatcher: fn(
self: *const IRTCClientPresence,
bstrPresentityURI: ?BSTR,
bstrUserName: ?BSTR,
bstrData: ?BSTR,
fBlocked: i16,
fPersistent: i16,
ppWatcher: ?*?*IRTCWatcher,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveWatcher: fn(
self: *const IRTCClientPresence,
pWatcher: ?*IRTCWatcher,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetLocalPresenceInfo: fn(
self: *const IRTCClientPresence,
enStatus: RTC_PRESENCE_STATUS,
bstrNotes: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_OfferWatcherMode: fn(
self: *const IRTCClientPresence,
penMode: ?*RTC_OFFER_WATCHER_MODE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_OfferWatcherMode: fn(
self: *const IRTCClientPresence,
enMode: RTC_OFFER_WATCHER_MODE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_PrivacyMode: fn(
self: *const IRTCClientPresence,
penMode: ?*RTC_PRIVACY_MODE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_PrivacyMode: fn(
self: *const IRTCClientPresence,
enMode: RTC_PRIVACY_MODE,
) 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 IRTCClientPresence_EnablePresence(self: *const T, fUseStorage: i16, varStorage: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence.VTable, self.vtable).EnablePresence(@ptrCast(*const IRTCClientPresence, self), fUseStorage, varStorage);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence_Export(self: *const T, varStorage: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence.VTable, self.vtable).Export(@ptrCast(*const IRTCClientPresence, self), varStorage);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence_Import(self: *const T, varStorage: VARIANT, fReplaceAll: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence.VTable, self.vtable).Import(@ptrCast(*const IRTCClientPresence, self), varStorage, fReplaceAll);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence_EnumerateBuddies(self: *const T, ppEnum: ?*?*IRTCEnumBuddies) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence.VTable, self.vtable).EnumerateBuddies(@ptrCast(*const IRTCClientPresence, self), ppEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence_get_Buddies(self: *const T, ppCollection: ?*?*IRTCCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence.VTable, self.vtable).get_Buddies(@ptrCast(*const IRTCClientPresence, self), ppCollection);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence_get_Buddy(self: *const T, bstrPresentityURI: ?BSTR, ppBuddy: ?*?*IRTCBuddy) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence.VTable, self.vtable).get_Buddy(@ptrCast(*const IRTCClientPresence, self), bstrPresentityURI, ppBuddy);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence_AddBuddy(self: *const T, bstrPresentityURI: ?BSTR, bstrUserName: ?BSTR, bstrData: ?BSTR, fPersistent: i16, pProfile: ?*IRTCProfile, lFlags: i32, ppBuddy: ?*?*IRTCBuddy) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence.VTable, self.vtable).AddBuddy(@ptrCast(*const IRTCClientPresence, self), bstrPresentityURI, bstrUserName, bstrData, fPersistent, pProfile, lFlags, ppBuddy);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence_RemoveBuddy(self: *const T, pBuddy: ?*IRTCBuddy) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence.VTable, self.vtable).RemoveBuddy(@ptrCast(*const IRTCClientPresence, self), pBuddy);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence_EnumerateWatchers(self: *const T, ppEnum: ?*?*IRTCEnumWatchers) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence.VTable, self.vtable).EnumerateWatchers(@ptrCast(*const IRTCClientPresence, self), ppEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence_get_Watchers(self: *const T, ppCollection: ?*?*IRTCCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence.VTable, self.vtable).get_Watchers(@ptrCast(*const IRTCClientPresence, self), ppCollection);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence_get_Watcher(self: *const T, bstrPresentityURI: ?BSTR, ppWatcher: ?*?*IRTCWatcher) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence.VTable, self.vtable).get_Watcher(@ptrCast(*const IRTCClientPresence, self), bstrPresentityURI, ppWatcher);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence_AddWatcher(self: *const T, bstrPresentityURI: ?BSTR, bstrUserName: ?BSTR, bstrData: ?BSTR, fBlocked: i16, fPersistent: i16, ppWatcher: ?*?*IRTCWatcher) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence.VTable, self.vtable).AddWatcher(@ptrCast(*const IRTCClientPresence, self), bstrPresentityURI, bstrUserName, bstrData, fBlocked, fPersistent, ppWatcher);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence_RemoveWatcher(self: *const T, pWatcher: ?*IRTCWatcher) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence.VTable, self.vtable).RemoveWatcher(@ptrCast(*const IRTCClientPresence, self), pWatcher);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence_SetLocalPresenceInfo(self: *const T, enStatus: RTC_PRESENCE_STATUS, bstrNotes: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence.VTable, self.vtable).SetLocalPresenceInfo(@ptrCast(*const IRTCClientPresence, self), enStatus, bstrNotes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence_get_OfferWatcherMode(self: *const T, penMode: ?*RTC_OFFER_WATCHER_MODE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence.VTable, self.vtable).get_OfferWatcherMode(@ptrCast(*const IRTCClientPresence, self), penMode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence_put_OfferWatcherMode(self: *const T, enMode: RTC_OFFER_WATCHER_MODE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence.VTable, self.vtable).put_OfferWatcherMode(@ptrCast(*const IRTCClientPresence, self), enMode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence_get_PrivacyMode(self: *const T, penMode: ?*RTC_PRIVACY_MODE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence.VTable, self.vtable).get_PrivacyMode(@ptrCast(*const IRTCClientPresence, self), penMode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence_put_PrivacyMode(self: *const T, enMode: RTC_PRIVACY_MODE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence.VTable, self.vtable).put_PrivacyMode(@ptrCast(*const IRTCClientPresence, self), enMode);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCClientPresence2_Value = @import("../zig.zig").Guid.initString("ad1809e8-62f7-4783-909a-29c9d2cb1d34");
pub const IID_IRTCClientPresence2 = &IID_IRTCClientPresence2_Value;
pub const IRTCClientPresence2 = extern struct {
pub const VTable = extern struct {
base: IRTCClientPresence.VTable,
EnablePresenceEx: fn(
self: *const IRTCClientPresence2,
pProfile: ?*IRTCProfile,
varStorage: VARIANT,
lFlags: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DisablePresence: fn(
self: *const IRTCClientPresence2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddGroup: fn(
self: *const IRTCClientPresence2,
bstrGroupName: ?BSTR,
bstrData: ?BSTR,
pProfile: ?*IRTCProfile,
lFlags: i32,
ppGroup: ?*?*IRTCBuddyGroup,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveGroup: fn(
self: *const IRTCClientPresence2,
pGroup: ?*IRTCBuddyGroup,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EnumerateGroups: fn(
self: *const IRTCClientPresence2,
ppEnum: ?*?*IRTCEnumGroups,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Groups: fn(
self: *const IRTCClientPresence2,
ppCollection: ?*?*IRTCCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Group: fn(
self: *const IRTCClientPresence2,
bstrGroupName: ?BSTR,
ppGroup: ?*?*IRTCBuddyGroup,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddWatcherEx: fn(
self: *const IRTCClientPresence2,
bstrPresentityURI: ?BSTR,
bstrUserName: ?BSTR,
bstrData: ?BSTR,
enState: RTC_WATCHER_STATE,
fPersistent: i16,
enScope: RTC_ACE_SCOPE,
pProfile: ?*IRTCProfile,
lFlags: i32,
ppWatcher: ?*?*IRTCWatcher2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_WatcherEx: fn(
self: *const IRTCClientPresence2,
enMode: RTC_WATCHER_MATCH_MODE,
bstrPresentityURI: ?BSTR,
ppWatcher: ?*?*IRTCWatcher2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_PresenceProperty: fn(
self: *const IRTCClientPresence2,
enProperty: RTC_PRESENCE_PROPERTY,
bstrProperty: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_PresenceProperty: fn(
self: *const IRTCClientPresence2,
enProperty: RTC_PRESENCE_PROPERTY,
pbstrProperty: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetPresenceData: fn(
self: *const IRTCClientPresence2,
bstrNamespace: ?BSTR,
bstrData: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPresenceData: fn(
self: *const IRTCClientPresence2,
pbstrNamespace: ?*?BSTR,
pbstrData: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLocalPresenceInfo: fn(
self: *const IRTCClientPresence2,
penStatus: ?*RTC_PRESENCE_STATUS,
pbstrNotes: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddBuddyEx: fn(
self: *const IRTCClientPresence2,
bstrPresentityURI: ?BSTR,
bstrUserName: ?BSTR,
bstrData: ?BSTR,
fPersistent: i16,
enSubscriptionType: RTC_BUDDY_SUBSCRIPTION_TYPE,
pProfile: ?*IRTCProfile,
lFlags: i32,
ppBuddy: ?*?*IRTCBuddy2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IRTCClientPresence.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence2_EnablePresenceEx(self: *const T, pProfile: ?*IRTCProfile, varStorage: VARIANT, lFlags: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence2.VTable, self.vtable).EnablePresenceEx(@ptrCast(*const IRTCClientPresence2, self), pProfile, varStorage, lFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence2_DisablePresence(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence2.VTable, self.vtable).DisablePresence(@ptrCast(*const IRTCClientPresence2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence2_AddGroup(self: *const T, bstrGroupName: ?BSTR, bstrData: ?BSTR, pProfile: ?*IRTCProfile, lFlags: i32, ppGroup: ?*?*IRTCBuddyGroup) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence2.VTable, self.vtable).AddGroup(@ptrCast(*const IRTCClientPresence2, self), bstrGroupName, bstrData, pProfile, lFlags, ppGroup);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence2_RemoveGroup(self: *const T, pGroup: ?*IRTCBuddyGroup) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence2.VTable, self.vtable).RemoveGroup(@ptrCast(*const IRTCClientPresence2, self), pGroup);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence2_EnumerateGroups(self: *const T, ppEnum: ?*?*IRTCEnumGroups) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence2.VTable, self.vtable).EnumerateGroups(@ptrCast(*const IRTCClientPresence2, self), ppEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence2_get_Groups(self: *const T, ppCollection: ?*?*IRTCCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence2.VTable, self.vtable).get_Groups(@ptrCast(*const IRTCClientPresence2, self), ppCollection);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence2_get_Group(self: *const T, bstrGroupName: ?BSTR, ppGroup: ?*?*IRTCBuddyGroup) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence2.VTable, self.vtable).get_Group(@ptrCast(*const IRTCClientPresence2, self), bstrGroupName, ppGroup);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence2_AddWatcherEx(self: *const T, bstrPresentityURI: ?BSTR, bstrUserName: ?BSTR, bstrData: ?BSTR, enState: RTC_WATCHER_STATE, fPersistent: i16, enScope: RTC_ACE_SCOPE, pProfile: ?*IRTCProfile, lFlags: i32, ppWatcher: ?*?*IRTCWatcher2) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence2.VTable, self.vtable).AddWatcherEx(@ptrCast(*const IRTCClientPresence2, self), bstrPresentityURI, bstrUserName, bstrData, enState, fPersistent, enScope, pProfile, lFlags, ppWatcher);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence2_get_WatcherEx(self: *const T, enMode: RTC_WATCHER_MATCH_MODE, bstrPresentityURI: ?BSTR, ppWatcher: ?*?*IRTCWatcher2) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence2.VTable, self.vtable).get_WatcherEx(@ptrCast(*const IRTCClientPresence2, self), enMode, bstrPresentityURI, ppWatcher);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence2_put_PresenceProperty(self: *const T, enProperty: RTC_PRESENCE_PROPERTY, bstrProperty: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence2.VTable, self.vtable).put_PresenceProperty(@ptrCast(*const IRTCClientPresence2, self), enProperty, bstrProperty);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence2_get_PresenceProperty(self: *const T, enProperty: RTC_PRESENCE_PROPERTY, pbstrProperty: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence2.VTable, self.vtable).get_PresenceProperty(@ptrCast(*const IRTCClientPresence2, self), enProperty, pbstrProperty);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence2_SetPresenceData(self: *const T, bstrNamespace: ?BSTR, bstrData: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence2.VTable, self.vtable).SetPresenceData(@ptrCast(*const IRTCClientPresence2, self), bstrNamespace, bstrData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence2_GetPresenceData(self: *const T, pbstrNamespace: ?*?BSTR, pbstrData: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence2.VTable, self.vtable).GetPresenceData(@ptrCast(*const IRTCClientPresence2, self), pbstrNamespace, pbstrData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence2_GetLocalPresenceInfo(self: *const T, penStatus: ?*RTC_PRESENCE_STATUS, pbstrNotes: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence2.VTable, self.vtable).GetLocalPresenceInfo(@ptrCast(*const IRTCClientPresence2, self), penStatus, pbstrNotes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPresence2_AddBuddyEx(self: *const T, bstrPresentityURI: ?BSTR, bstrUserName: ?BSTR, bstrData: ?BSTR, fPersistent: i16, enSubscriptionType: RTC_BUDDY_SUBSCRIPTION_TYPE, pProfile: ?*IRTCProfile, lFlags: i32, ppBuddy: ?*?*IRTCBuddy2) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPresence2.VTable, self.vtable).AddBuddyEx(@ptrCast(*const IRTCClientPresence2, self), bstrPresentityURI, bstrUserName, bstrData, fPersistent, enSubscriptionType, pProfile, lFlags, ppBuddy);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCClientProvisioning_Value = @import("../zig.zig").Guid.initString("b9f5cf06-65b9-4a80-a0e6-73cae3ef3822");
pub const IID_IRTCClientProvisioning = &IID_IRTCClientProvisioning_Value;
pub const IRTCClientProvisioning = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
CreateProfile: fn(
self: *const IRTCClientProvisioning,
bstrProfileXML: ?BSTR,
ppProfile: ?*?*IRTCProfile,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EnableProfile: fn(
self: *const IRTCClientProvisioning,
pProfile: ?*IRTCProfile,
lRegisterFlags: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DisableProfile: fn(
self: *const IRTCClientProvisioning,
pProfile: ?*IRTCProfile,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EnumerateProfiles: fn(
self: *const IRTCClientProvisioning,
ppEnum: ?*?*IRTCEnumProfiles,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Profiles: fn(
self: *const IRTCClientProvisioning,
ppCollection: ?*?*IRTCCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetProfile: fn(
self: *const IRTCClientProvisioning,
bstrUserAccount: ?BSTR,
bstrUserPassword: ?<PASSWORD>,
bstrUserURI: ?BSTR,
bstrServer: ?BSTR,
lTransport: i32,
lCookie: isize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_SessionCapabilities: fn(
self: *const IRTCClientProvisioning,
plSupportedSessions: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientProvisioning_CreateProfile(self: *const T, bstrProfileXML: ?BSTR, ppProfile: ?*?*IRTCProfile) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientProvisioning.VTable, self.vtable).CreateProfile(@ptrCast(*const IRTCClientProvisioning, self), bstrProfileXML, ppProfile);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientProvisioning_EnableProfile(self: *const T, pProfile: ?*IRTCProfile, lRegisterFlags: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientProvisioning.VTable, self.vtable).EnableProfile(@ptrCast(*const IRTCClientProvisioning, self), pProfile, lRegisterFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientProvisioning_DisableProfile(self: *const T, pProfile: ?*IRTCProfile) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientProvisioning.VTable, self.vtable).DisableProfile(@ptrCast(*const IRTCClientProvisioning, self), pProfile);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientProvisioning_EnumerateProfiles(self: *const T, ppEnum: ?*?*IRTCEnumProfiles) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientProvisioning.VTable, self.vtable).EnumerateProfiles(@ptrCast(*const IRTCClientProvisioning, self), ppEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientProvisioning_get_Profiles(self: *const T, ppCollection: ?*?*IRTCCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientProvisioning.VTable, self.vtable).get_Profiles(@ptrCast(*const IRTCClientProvisioning, self), ppCollection);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientProvisioning_GetProfile(self: *const T, bstrUserAccount: ?BSTR, bstrUserPassword: ?BSTR, bstrUserURI: ?BSTR, bstrServer: ?BSTR, lTransport: i32, lCookie: isize) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientProvisioning.VTable, self.vtable).GetProfile(@ptrCast(*const IRTCClientProvisioning, self), bstrUserAccount, bstrUserPassword, bstrUserURI, bstrServer, lTransport, lCookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientProvisioning_get_SessionCapabilities(self: *const T, plSupportedSessions: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientProvisioning.VTable, self.vtable).get_SessionCapabilities(@ptrCast(*const IRTCClientProvisioning, self), plSupportedSessions);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCClientProvisioning2_Value = @import("../zig.zig").Guid.initString("a70909b5-f40e-4587-bb75-e6bc0845023e");
pub const IID_IRTCClientProvisioning2 = &IID_IRTCClientProvisioning2_Value;
pub const IRTCClientProvisioning2 = extern struct {
pub const VTable = extern struct {
base: IRTCClientProvisioning.VTable,
EnableProfileEx: fn(
self: *const IRTCClientProvisioning2,
pProfile: ?*IRTCProfile,
lRegisterFlags: i32,
lRoamingFlags: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IRTCClientProvisioning.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientProvisioning2_EnableProfileEx(self: *const T, pProfile: ?*IRTCProfile, lRegisterFlags: i32, lRoamingFlags: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientProvisioning2.VTable, self.vtable).EnableProfileEx(@ptrCast(*const IRTCClientProvisioning2, self), pProfile, lRegisterFlags, lRoamingFlags);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCProfile_Value = @import("../zig.zig").Guid.initString("d07eca9e-4062-4dd4-9e7d-722a49ba7303");
pub const IID_IRTCProfile = &IID_IRTCProfile_Value;
pub const IRTCProfile = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Key: fn(
self: *const IRTCProfile,
pbstrKey: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Name: fn(
self: *const IRTCProfile,
pbstrName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_XML: fn(
self: *const IRTCProfile,
pbstrXML: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ProviderName: fn(
self: *const IRTCProfile,
pbstrName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ProviderURI: fn(
self: *const IRTCProfile,
enURI: RTC_PROVIDER_URI,
pbstrURI: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ProviderData: fn(
self: *const IRTCProfile,
pbstrData: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ClientName: fn(
self: *const IRTCProfile,
pbstrName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ClientBanner: fn(
self: *const IRTCProfile,
pfBanner: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ClientMinVer: fn(
self: *const IRTCProfile,
pbstrMinVer: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ClientCurVer: fn(
self: *const IRTCProfile,
pbstrCurVer: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ClientUpdateURI: fn(
self: *const IRTCProfile,
pbstrUpdateURI: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ClientData: fn(
self: *const IRTCProfile,
pbstrData: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_UserURI: fn(
self: *const IRTCProfile,
pbstrUserURI: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_UserName: fn(
self: *const IRTCProfile,
pbstrUserName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_UserAccount: fn(
self: *const IRTCProfile,
pbstrUserAccount: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCredentials: fn(
self: *const IRTCProfile,
bstrUserURI: ?BSTR,
bstrUserAccount: ?BSTR,
bstrPassword: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_SessionCapabilities: fn(
self: *const IRTCProfile,
plSupportedSessions: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_State: fn(
self: *const IRTCProfile,
penState: ?*RTC_REGISTRATION_STATE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCProfile_get_Key(self: *const T, pbstrKey: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCProfile.VTable, self.vtable).get_Key(@ptrCast(*const IRTCProfile, self), pbstrKey);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCProfile_get_Name(self: *const T, pbstrName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCProfile.VTable, self.vtable).get_Name(@ptrCast(*const IRTCProfile, self), pbstrName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCProfile_get_XML(self: *const T, pbstrXML: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCProfile.VTable, self.vtable).get_XML(@ptrCast(*const IRTCProfile, self), pbstrXML);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCProfile_get_ProviderName(self: *const T, pbstrName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCProfile.VTable, self.vtable).get_ProviderName(@ptrCast(*const IRTCProfile, self), pbstrName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCProfile_get_ProviderURI(self: *const T, enURI: RTC_PROVIDER_URI, pbstrURI: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCProfile.VTable, self.vtable).get_ProviderURI(@ptrCast(*const IRTCProfile, self), enURI, pbstrURI);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCProfile_get_ProviderData(self: *const T, pbstrData: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCProfile.VTable, self.vtable).get_ProviderData(@ptrCast(*const IRTCProfile, self), pbstrData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCProfile_get_ClientName(self: *const T, pbstrName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCProfile.VTable, self.vtable).get_ClientName(@ptrCast(*const IRTCProfile, self), pbstrName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCProfile_get_ClientBanner(self: *const T, pfBanner: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCProfile.VTable, self.vtable).get_ClientBanner(@ptrCast(*const IRTCProfile, self), pfBanner);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCProfile_get_ClientMinVer(self: *const T, pbstrMinVer: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCProfile.VTable, self.vtable).get_ClientMinVer(@ptrCast(*const IRTCProfile, self), pbstrMinVer);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCProfile_get_ClientCurVer(self: *const T, pbstrCurVer: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCProfile.VTable, self.vtable).get_ClientCurVer(@ptrCast(*const IRTCProfile, self), pbstrCurVer);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCProfile_get_ClientUpdateURI(self: *const T, pbstrUpdateURI: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCProfile.VTable, self.vtable).get_ClientUpdateURI(@ptrCast(*const IRTCProfile, self), pbstrUpdateURI);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCProfile_get_ClientData(self: *const T, pbstrData: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCProfile.VTable, self.vtable).get_ClientData(@ptrCast(*const IRTCProfile, self), pbstrData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCProfile_get_UserURI(self: *const T, pbstrUserURI: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCProfile.VTable, self.vtable).get_UserURI(@ptrCast(*const IRTCProfile, self), pbstrUserURI);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCProfile_get_UserName(self: *const T, pbstrUserName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCProfile.VTable, self.vtable).get_UserName(@ptrCast(*const IRTCProfile, self), pbstrUserName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCProfile_get_UserAccount(self: *const T, pbstrUserAccount: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCProfile.VTable, self.vtable).get_UserAccount(@ptrCast(*const IRTCProfile, self), pbstrUserAccount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCProfile_SetCredentials(self: *const T, bstrUserURI: ?BSTR, bstrUserAccount: ?BSTR, bstrPassword: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCProfile.VTable, self.vtable).SetCredentials(@ptrCast(*const IRTCProfile, self), bstrUserURI, bstrUserAccount, bstrPassword);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCProfile_get_SessionCapabilities(self: *const T, plSupportedSessions: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCProfile.VTable, self.vtable).get_SessionCapabilities(@ptrCast(*const IRTCProfile, self), plSupportedSessions);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCProfile_get_State(self: *const T, penState: ?*RTC_REGISTRATION_STATE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCProfile.VTable, self.vtable).get_State(@ptrCast(*const IRTCProfile, self), penState);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCProfile2_Value = @import("../zig.zig").Guid.initString("4b81f84e-bdc7-4184-9154-3cb2dd7917fb");
pub const IID_IRTCProfile2 = &IID_IRTCProfile2_Value;
pub const IRTCProfile2 = extern struct {
pub const VTable = extern struct {
base: IRTCProfile.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Realm: fn(
self: *const IRTCProfile2,
pbstrRealm: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Realm: fn(
self: *const IRTCProfile2,
bstrRealm: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_AllowedAuth: fn(
self: *const IRTCProfile2,
plAllowedAuth: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_AllowedAuth: fn(
self: *const IRTCProfile2,
lAllowedAuth: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IRTCProfile.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCProfile2_get_Realm(self: *const T, pbstrRealm: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCProfile2.VTable, self.vtable).get_Realm(@ptrCast(*const IRTCProfile2, self), pbstrRealm);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCProfile2_put_Realm(self: *const T, bstrRealm: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCProfile2.VTable, self.vtable).put_Realm(@ptrCast(*const IRTCProfile2, self), bstrRealm);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCProfile2_get_AllowedAuth(self: *const T, plAllowedAuth: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCProfile2.VTable, self.vtable).get_AllowedAuth(@ptrCast(*const IRTCProfile2, self), plAllowedAuth);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCProfile2_put_AllowedAuth(self: *const T, lAllowedAuth: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCProfile2.VTable, self.vtable).put_AllowedAuth(@ptrCast(*const IRTCProfile2, self), lAllowedAuth);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCSession_Value = @import("../zig.zig").Guid.initString("387c8086-99be-42fb-9973-7c0fc0ca9fa8");
pub const IID_IRTCSession = &IID_IRTCSession_Value;
pub const IRTCSession = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Client: fn(
self: *const IRTCSession,
ppClient: ?*?*IRTCClient,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_State: fn(
self: *const IRTCSession,
penState: ?*RTC_SESSION_STATE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Type: fn(
self: *const IRTCSession,
penType: ?*RTC_SESSION_TYPE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Profile: fn(
self: *const IRTCSession,
ppProfile: ?*?*IRTCProfile,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Participants: fn(
self: *const IRTCSession,
ppCollection: ?*?*IRTCCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Answer: fn(
self: *const IRTCSession,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Terminate: fn(
self: *const IRTCSession,
enReason: RTC_TERMINATE_REASON,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Redirect: fn(
self: *const IRTCSession,
enType: RTC_SESSION_TYPE,
bstrLocalPhoneURI: ?BSTR,
pProfile: ?*IRTCProfile,
lFlags: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddParticipant: fn(
self: *const IRTCSession,
bstrAddress: ?BSTR,
bstrName: ?BSTR,
ppParticipant: ?*?*IRTCParticipant,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveParticipant: fn(
self: *const IRTCSession,
pParticipant: ?*IRTCParticipant,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EnumerateParticipants: fn(
self: *const IRTCSession,
ppEnum: ?*?*IRTCEnumParticipants,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CanAddParticipants: fn(
self: *const IRTCSession,
pfCanAdd: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_RedirectedUserURI: fn(
self: *const IRTCSession,
pbstrUserURI: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_RedirectedUserName: fn(
self: *const IRTCSession,
pbstrUserName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
NextRedirectedUser: fn(
self: *const IRTCSession,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SendMessage: fn(
self: *const IRTCSession,
bstrMessageHeader: ?BSTR,
bstrMessage: ?BSTR,
lCookie: isize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SendMessageStatus: fn(
self: *const IRTCSession,
enUserStatus: RTC_MESSAGING_USER_STATUS,
lCookie: isize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddStream: fn(
self: *const IRTCSession,
lMediaType: i32,
lCookie: isize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveStream: fn(
self: *const IRTCSession,
lMediaType: i32,
lCookie: isize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_EncryptionKey: fn(
self: *const IRTCSession,
lMediaType: i32,
EncryptionKey: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSession_get_Client(self: *const T, ppClient: ?*?*IRTCClient) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSession.VTable, self.vtable).get_Client(@ptrCast(*const IRTCSession, self), ppClient);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSession_get_State(self: *const T, penState: ?*RTC_SESSION_STATE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSession.VTable, self.vtable).get_State(@ptrCast(*const IRTCSession, self), penState);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSession_get_Type(self: *const T, penType: ?*RTC_SESSION_TYPE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSession.VTable, self.vtable).get_Type(@ptrCast(*const IRTCSession, self), penType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSession_get_Profile(self: *const T, ppProfile: ?*?*IRTCProfile) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSession.VTable, self.vtable).get_Profile(@ptrCast(*const IRTCSession, self), ppProfile);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSession_get_Participants(self: *const T, ppCollection: ?*?*IRTCCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSession.VTable, self.vtable).get_Participants(@ptrCast(*const IRTCSession, self), ppCollection);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSession_Answer(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSession.VTable, self.vtable).Answer(@ptrCast(*const IRTCSession, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSession_Terminate(self: *const T, enReason: RTC_TERMINATE_REASON) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSession.VTable, self.vtable).Terminate(@ptrCast(*const IRTCSession, self), enReason);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSession_Redirect(self: *const T, enType: RTC_SESSION_TYPE, bstrLocalPhoneURI: ?BSTR, pProfile: ?*IRTCProfile, lFlags: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSession.VTable, self.vtable).Redirect(@ptrCast(*const IRTCSession, self), enType, bstrLocalPhoneURI, pProfile, lFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSession_AddParticipant(self: *const T, bstrAddress: ?BSTR, bstrName: ?BSTR, ppParticipant: ?*?*IRTCParticipant) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSession.VTable, self.vtable).AddParticipant(@ptrCast(*const IRTCSession, self), bstrAddress, bstrName, ppParticipant);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSession_RemoveParticipant(self: *const T, pParticipant: ?*IRTCParticipant) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSession.VTable, self.vtable).RemoveParticipant(@ptrCast(*const IRTCSession, self), pParticipant);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSession_EnumerateParticipants(self: *const T, ppEnum: ?*?*IRTCEnumParticipants) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSession.VTable, self.vtable).EnumerateParticipants(@ptrCast(*const IRTCSession, self), ppEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSession_get_CanAddParticipants(self: *const T, pfCanAdd: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSession.VTable, self.vtable).get_CanAddParticipants(@ptrCast(*const IRTCSession, self), pfCanAdd);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSession_get_RedirectedUserURI(self: *const T, pbstrUserURI: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSession.VTable, self.vtable).get_RedirectedUserURI(@ptrCast(*const IRTCSession, self), pbstrUserURI);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSession_get_RedirectedUserName(self: *const T, pbstrUserName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSession.VTable, self.vtable).get_RedirectedUserName(@ptrCast(*const IRTCSession, self), pbstrUserName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSession_NextRedirectedUser(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSession.VTable, self.vtable).NextRedirectedUser(@ptrCast(*const IRTCSession, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSession_SendMessage(self: *const T, bstrMessageHeader: ?BSTR, bstrMessage: ?BSTR, lCookie: isize) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSession.VTable, self.vtable).SendMessage(@ptrCast(*const IRTCSession, self), bstrMessageHeader, bstrMessage, lCookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSession_SendMessageStatus(self: *const T, enUserStatus: RTC_MESSAGING_USER_STATUS, lCookie: isize) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSession.VTable, self.vtable).SendMessageStatus(@ptrCast(*const IRTCSession, self), enUserStatus, lCookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSession_AddStream(self: *const T, lMediaType: i32, lCookie: isize) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSession.VTable, self.vtable).AddStream(@ptrCast(*const IRTCSession, self), lMediaType, lCookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSession_RemoveStream(self: *const T, lMediaType: i32, lCookie: isize) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSession.VTable, self.vtable).RemoveStream(@ptrCast(*const IRTCSession, self), lMediaType, lCookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSession_put_EncryptionKey(self: *const T, lMediaType: i32, EncryptionKey: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSession.VTable, self.vtable).put_EncryptionKey(@ptrCast(*const IRTCSession, self), lMediaType, EncryptionKey);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCSession2_Value = @import("../zig.zig").Guid.initString("17d7cdfc-b007-484c-99d2-86a8a820991d");
pub const IID_IRTCSession2 = &IID_IRTCSession2_Value;
pub const IRTCSession2 = extern struct {
pub const VTable = extern struct {
base: IRTCSession.VTable,
SendInfo: fn(
self: *const IRTCSession2,
bstrInfoHeader: ?BSTR,
bstrInfo: ?BSTR,
lCookie: isize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_PreferredSecurityLevel: fn(
self: *const IRTCSession2,
enSecurityType: RTC_SECURITY_TYPE,
enSecurityLevel: RTC_SECURITY_LEVEL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_PreferredSecurityLevel: fn(
self: *const IRTCSession2,
enSecurityType: RTC_SECURITY_TYPE,
penSecurityLevel: ?*RTC_SECURITY_LEVEL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsSecurityEnabled: fn(
self: *const IRTCSession2,
enSecurityType: RTC_SECURITY_TYPE,
pfSecurityEnabled: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AnswerWithSessionDescription: fn(
self: *const IRTCSession2,
bstrContentType: ?BSTR,
bstrSessionDescription: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ReInviteWithSessionDescription: fn(
self: *const IRTCSession2,
bstrContentType: ?BSTR,
bstrSessionDescription: ?BSTR,
lCookie: isize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IRTCSession.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSession2_SendInfo(self: *const T, bstrInfoHeader: ?BSTR, bstrInfo: ?BSTR, lCookie: isize) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSession2.VTable, self.vtable).SendInfo(@ptrCast(*const IRTCSession2, self), bstrInfoHeader, bstrInfo, lCookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSession2_put_PreferredSecurityLevel(self: *const T, enSecurityType: RTC_SECURITY_TYPE, enSecurityLevel: RTC_SECURITY_LEVEL) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSession2.VTable, self.vtable).put_PreferredSecurityLevel(@ptrCast(*const IRTCSession2, self), enSecurityType, enSecurityLevel);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSession2_get_PreferredSecurityLevel(self: *const T, enSecurityType: RTC_SECURITY_TYPE, penSecurityLevel: ?*RTC_SECURITY_LEVEL) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSession2.VTable, self.vtable).get_PreferredSecurityLevel(@ptrCast(*const IRTCSession2, self), enSecurityType, penSecurityLevel);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSession2_IsSecurityEnabled(self: *const T, enSecurityType: RTC_SECURITY_TYPE, pfSecurityEnabled: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSession2.VTable, self.vtable).IsSecurityEnabled(@ptrCast(*const IRTCSession2, self), enSecurityType, pfSecurityEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSession2_AnswerWithSessionDescription(self: *const T, bstrContentType: ?BSTR, bstrSessionDescription: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSession2.VTable, self.vtable).AnswerWithSessionDescription(@ptrCast(*const IRTCSession2, self), bstrContentType, bstrSessionDescription);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSession2_ReInviteWithSessionDescription(self: *const T, bstrContentType: ?BSTR, bstrSessionDescription: ?BSTR, lCookie: isize) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSession2.VTable, self.vtable).ReInviteWithSessionDescription(@ptrCast(*const IRTCSession2, self), bstrContentType, bstrSessionDescription, lCookie);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCSessionCallControl_Value = @import("../zig.zig").Guid.initString("e9a50d94-190b-4f82-9530-3b8ebf60758a");
pub const IID_IRTCSessionCallControl = &IID_IRTCSessionCallControl_Value;
pub const IRTCSessionCallControl = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Hold: fn(
self: *const IRTCSessionCallControl,
lCookie: isize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UnHold: fn(
self: *const IRTCSessionCallControl,
lCookie: isize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Forward: fn(
self: *const IRTCSessionCallControl,
bstrForwardToURI: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Refer: fn(
self: *const IRTCSessionCallControl,
bstrReferToURI: ?BSTR,
bstrReferCookie: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_ReferredByURI: fn(
self: *const IRTCSessionCallControl,
bstrReferredByURI: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ReferredByURI: fn(
self: *const IRTCSessionCallControl,
pbstrReferredByURI: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_ReferCookie: fn(
self: *const IRTCSessionCallControl,
bstrReferCookie: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ReferCookie: fn(
self: *const IRTCSessionCallControl,
pbstrReferCookie: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_IsReferred: fn(
self: *const IRTCSessionCallControl,
pfIsReferred: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionCallControl_Hold(self: *const T, lCookie: isize) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionCallControl.VTable, self.vtable).Hold(@ptrCast(*const IRTCSessionCallControl, self), lCookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionCallControl_UnHold(self: *const T, lCookie: isize) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionCallControl.VTable, self.vtable).UnHold(@ptrCast(*const IRTCSessionCallControl, self), lCookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionCallControl_Forward(self: *const T, bstrForwardToURI: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionCallControl.VTable, self.vtable).Forward(@ptrCast(*const IRTCSessionCallControl, self), bstrForwardToURI);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionCallControl_Refer(self: *const T, bstrReferToURI: ?BSTR, bstrReferCookie: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionCallControl.VTable, self.vtable).Refer(@ptrCast(*const IRTCSessionCallControl, self), bstrReferToURI, bstrReferCookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionCallControl_put_ReferredByURI(self: *const T, bstrReferredByURI: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionCallControl.VTable, self.vtable).put_ReferredByURI(@ptrCast(*const IRTCSessionCallControl, self), bstrReferredByURI);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionCallControl_get_ReferredByURI(self: *const T, pbstrReferredByURI: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionCallControl.VTable, self.vtable).get_ReferredByURI(@ptrCast(*const IRTCSessionCallControl, self), pbstrReferredByURI);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionCallControl_put_ReferCookie(self: *const T, bstrReferCookie: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionCallControl.VTable, self.vtable).put_ReferCookie(@ptrCast(*const IRTCSessionCallControl, self), bstrReferCookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionCallControl_get_ReferCookie(self: *const T, pbstrReferCookie: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionCallControl.VTable, self.vtable).get_ReferCookie(@ptrCast(*const IRTCSessionCallControl, self), pbstrReferCookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionCallControl_get_IsReferred(self: *const T, pfIsReferred: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionCallControl.VTable, self.vtable).get_IsReferred(@ptrCast(*const IRTCSessionCallControl, self), pfIsReferred);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCParticipant_Value = @import("../zig.zig").Guid.initString("ae86add5-26b1-4414-af1d-b94cd938d739");
pub const IID_IRTCParticipant = &IID_IRTCParticipant_Value;
pub const IRTCParticipant = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_UserURI: fn(
self: *const IRTCParticipant,
pbstrUserURI: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Name: fn(
self: *const IRTCParticipant,
pbstrName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Removable: fn(
self: *const IRTCParticipant,
pfRemovable: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_State: fn(
self: *const IRTCParticipant,
penState: ?*RTC_PARTICIPANT_STATE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Session: fn(
self: *const IRTCParticipant,
ppSession: ?*?*IRTCSession,
) 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 IRTCParticipant_get_UserURI(self: *const T, pbstrUserURI: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCParticipant.VTable, self.vtable).get_UserURI(@ptrCast(*const IRTCParticipant, self), pbstrUserURI);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCParticipant_get_Name(self: *const T, pbstrName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCParticipant.VTable, self.vtable).get_Name(@ptrCast(*const IRTCParticipant, self), pbstrName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCParticipant_get_Removable(self: *const T, pfRemovable: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCParticipant.VTable, self.vtable).get_Removable(@ptrCast(*const IRTCParticipant, self), pfRemovable);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCParticipant_get_State(self: *const T, penState: ?*RTC_PARTICIPANT_STATE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCParticipant.VTable, self.vtable).get_State(@ptrCast(*const IRTCParticipant, self), penState);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCParticipant_get_Session(self: *const T, ppSession: ?*?*IRTCSession) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCParticipant.VTable, self.vtable).get_Session(@ptrCast(*const IRTCParticipant, self), ppSession);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCRoamingEvent_Value = @import("../zig.zig").Guid.initString("79960a6b-0cb1-4dc8-a805-7318e99902e8");
pub const IID_IRTCRoamingEvent = &IID_IRTCRoamingEvent_Value;
pub const IRTCRoamingEvent = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_EventType: fn(
self: *const IRTCRoamingEvent,
pEventType: ?*RTC_ROAMING_EVENT_TYPE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Profile: fn(
self: *const IRTCRoamingEvent,
ppProfile: ?*?*IRTCProfile2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_StatusCode: fn(
self: *const IRTCRoamingEvent,
plStatusCode: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_StatusText: fn(
self: *const IRTCRoamingEvent,
pbstrStatusText: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCRoamingEvent_get_EventType(self: *const T, pEventType: ?*RTC_ROAMING_EVENT_TYPE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCRoamingEvent.VTable, self.vtable).get_EventType(@ptrCast(*const IRTCRoamingEvent, self), pEventType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCRoamingEvent_get_Profile(self: *const T, ppProfile: ?*?*IRTCProfile2) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCRoamingEvent.VTable, self.vtable).get_Profile(@ptrCast(*const IRTCRoamingEvent, self), ppProfile);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCRoamingEvent_get_StatusCode(self: *const T, plStatusCode: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCRoamingEvent.VTable, self.vtable).get_StatusCode(@ptrCast(*const IRTCRoamingEvent, self), plStatusCode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCRoamingEvent_get_StatusText(self: *const T, pbstrStatusText: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCRoamingEvent.VTable, self.vtable).get_StatusText(@ptrCast(*const IRTCRoamingEvent, self), pbstrStatusText);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCProfileEvent_Value = @import("../zig.zig").Guid.initString("d6d5ab3b-770e-43e8-800a-79b062395fca");
pub const IID_IRTCProfileEvent = &IID_IRTCProfileEvent_Value;
pub const IRTCProfileEvent = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Profile: fn(
self: *const IRTCProfileEvent,
ppProfile: ?*?*IRTCProfile,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Cookie: fn(
self: *const IRTCProfileEvent,
plCookie: ?*isize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_StatusCode: fn(
self: *const IRTCProfileEvent,
plStatusCode: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCProfileEvent_get_Profile(self: *const T, ppProfile: ?*?*IRTCProfile) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCProfileEvent.VTable, self.vtable).get_Profile(@ptrCast(*const IRTCProfileEvent, self), ppProfile);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCProfileEvent_get_Cookie(self: *const T, plCookie: ?*isize) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCProfileEvent.VTable, self.vtable).get_Cookie(@ptrCast(*const IRTCProfileEvent, self), plCookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCProfileEvent_get_StatusCode(self: *const T, plStatusCode: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCProfileEvent.VTable, self.vtable).get_StatusCode(@ptrCast(*const IRTCProfileEvent, self), plStatusCode);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCProfileEvent2_Value = @import("../zig.zig").Guid.initString("62e56edc-03fa-4121-94fb-23493fd0ae64");
pub const IID_IRTCProfileEvent2 = &IID_IRTCProfileEvent2_Value;
pub const IRTCProfileEvent2 = extern struct {
pub const VTable = extern struct {
base: IRTCProfileEvent.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_EventType: fn(
self: *const IRTCProfileEvent2,
pEventType: ?*RTC_PROFILE_EVENT_TYPE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IRTCProfileEvent.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCProfileEvent2_get_EventType(self: *const T, pEventType: ?*RTC_PROFILE_EVENT_TYPE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCProfileEvent2.VTable, self.vtable).get_EventType(@ptrCast(*const IRTCProfileEvent2, self), pEventType);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCClientEvent_Value = @import("../zig.zig").Guid.initString("2b493b7a-3cba-4170-9c8b-76a9dacdd644");
pub const IID_IRTCClientEvent = &IID_IRTCClientEvent_Value;
pub const IRTCClientEvent = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_EventType: fn(
self: *const IRTCClientEvent,
penEventType: ?*RTC_CLIENT_EVENT_TYPE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Client: fn(
self: *const IRTCClientEvent,
ppClient: ?*?*IRTCClient,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientEvent_get_EventType(self: *const T, penEventType: ?*RTC_CLIENT_EVENT_TYPE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientEvent.VTable, self.vtable).get_EventType(@ptrCast(*const IRTCClientEvent, self), penEventType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientEvent_get_Client(self: *const T, ppClient: ?*?*IRTCClient) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientEvent.VTable, self.vtable).get_Client(@ptrCast(*const IRTCClientEvent, self), ppClient);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCRegistrationStateChangeEvent_Value = @import("../zig.zig").Guid.initString("62d0991b-50ab-4f02-b948-ca94f26f8f95");
pub const IID_IRTCRegistrationStateChangeEvent = &IID_IRTCRegistrationStateChangeEvent_Value;
pub const IRTCRegistrationStateChangeEvent = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Profile: fn(
self: *const IRTCRegistrationStateChangeEvent,
ppProfile: ?*?*IRTCProfile,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_State: fn(
self: *const IRTCRegistrationStateChangeEvent,
penState: ?*RTC_REGISTRATION_STATE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_StatusCode: fn(
self: *const IRTCRegistrationStateChangeEvent,
plStatusCode: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_StatusText: fn(
self: *const IRTCRegistrationStateChangeEvent,
pbstrStatusText: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCRegistrationStateChangeEvent_get_Profile(self: *const T, ppProfile: ?*?*IRTCProfile) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCRegistrationStateChangeEvent.VTable, self.vtable).get_Profile(@ptrCast(*const IRTCRegistrationStateChangeEvent, self), ppProfile);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCRegistrationStateChangeEvent_get_State(self: *const T, penState: ?*RTC_REGISTRATION_STATE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCRegistrationStateChangeEvent.VTable, self.vtable).get_State(@ptrCast(*const IRTCRegistrationStateChangeEvent, self), penState);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCRegistrationStateChangeEvent_get_StatusCode(self: *const T, plStatusCode: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCRegistrationStateChangeEvent.VTable, self.vtable).get_StatusCode(@ptrCast(*const IRTCRegistrationStateChangeEvent, self), plStatusCode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCRegistrationStateChangeEvent_get_StatusText(self: *const T, pbstrStatusText: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCRegistrationStateChangeEvent.VTable, self.vtable).get_StatusText(@ptrCast(*const IRTCRegistrationStateChangeEvent, self), pbstrStatusText);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCSessionStateChangeEvent_Value = @import("../zig.zig").Guid.initString("b5bad703-5952-48b3-9321-7f4500521506");
pub const IID_IRTCSessionStateChangeEvent = &IID_IRTCSessionStateChangeEvent_Value;
pub const IRTCSessionStateChangeEvent = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Session: fn(
self: *const IRTCSessionStateChangeEvent,
ppSession: ?*?*IRTCSession,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_State: fn(
self: *const IRTCSessionStateChangeEvent,
penState: ?*RTC_SESSION_STATE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_StatusCode: fn(
self: *const IRTCSessionStateChangeEvent,
plStatusCode: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_StatusText: fn(
self: *const IRTCSessionStateChangeEvent,
pbstrStatusText: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionStateChangeEvent_get_Session(self: *const T, ppSession: ?*?*IRTCSession) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionStateChangeEvent.VTable, self.vtable).get_Session(@ptrCast(*const IRTCSessionStateChangeEvent, self), ppSession);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionStateChangeEvent_get_State(self: *const T, penState: ?*RTC_SESSION_STATE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionStateChangeEvent.VTable, self.vtable).get_State(@ptrCast(*const IRTCSessionStateChangeEvent, self), penState);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionStateChangeEvent_get_StatusCode(self: *const T, plStatusCode: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionStateChangeEvent.VTable, self.vtable).get_StatusCode(@ptrCast(*const IRTCSessionStateChangeEvent, self), plStatusCode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionStateChangeEvent_get_StatusText(self: *const T, pbstrStatusText: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionStateChangeEvent.VTable, self.vtable).get_StatusText(@ptrCast(*const IRTCSessionStateChangeEvent, self), pbstrStatusText);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCSessionStateChangeEvent2_Value = @import("../zig.zig").Guid.initString("4f933171-6f95-4880-80d9-2ec8d495d261");
pub const IID_IRTCSessionStateChangeEvent2 = &IID_IRTCSessionStateChangeEvent2_Value;
pub const IRTCSessionStateChangeEvent2 = extern struct {
pub const VTable = extern struct {
base: IRTCSessionStateChangeEvent.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_MediaTypes: fn(
self: *const IRTCSessionStateChangeEvent2,
pMediaTypes: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_RemotePreferredSecurityLevel: fn(
self: *const IRTCSessionStateChangeEvent2,
enSecurityType: RTC_SECURITY_TYPE,
penSecurityLevel: ?*RTC_SECURITY_LEVEL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_IsForked: fn(
self: *const IRTCSessionStateChangeEvent2,
pfIsForked: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetRemoteSessionDescription: fn(
self: *const IRTCSessionStateChangeEvent2,
pbstrContentType: ?*?BSTR,
pbstrSessionDescription: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IRTCSessionStateChangeEvent.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionStateChangeEvent2_get_MediaTypes(self: *const T, pMediaTypes: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionStateChangeEvent2.VTable, self.vtable).get_MediaTypes(@ptrCast(*const IRTCSessionStateChangeEvent2, self), pMediaTypes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionStateChangeEvent2_get_RemotePreferredSecurityLevel(self: *const T, enSecurityType: RTC_SECURITY_TYPE, penSecurityLevel: ?*RTC_SECURITY_LEVEL) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionStateChangeEvent2.VTable, self.vtable).get_RemotePreferredSecurityLevel(@ptrCast(*const IRTCSessionStateChangeEvent2, self), enSecurityType, penSecurityLevel);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionStateChangeEvent2_get_IsForked(self: *const T, pfIsForked: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionStateChangeEvent2.VTable, self.vtable).get_IsForked(@ptrCast(*const IRTCSessionStateChangeEvent2, self), pfIsForked);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionStateChangeEvent2_GetRemoteSessionDescription(self: *const T, pbstrContentType: ?*?BSTR, pbstrSessionDescription: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionStateChangeEvent2.VTable, self.vtable).GetRemoteSessionDescription(@ptrCast(*const IRTCSessionStateChangeEvent2, self), pbstrContentType, pbstrSessionDescription);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCSessionOperationCompleteEvent_Value = @import("../zig.zig").Guid.initString("a6bff4c0-f7c8-4d3c-9a41-3550f78a95b0");
pub const IID_IRTCSessionOperationCompleteEvent = &IID_IRTCSessionOperationCompleteEvent_Value;
pub const IRTCSessionOperationCompleteEvent = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Session: fn(
self: *const IRTCSessionOperationCompleteEvent,
ppSession: ?*?*IRTCSession,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Cookie: fn(
self: *const IRTCSessionOperationCompleteEvent,
plCookie: ?*isize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_StatusCode: fn(
self: *const IRTCSessionOperationCompleteEvent,
plStatusCode: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_StatusText: fn(
self: *const IRTCSessionOperationCompleteEvent,
pbstrStatusText: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionOperationCompleteEvent_get_Session(self: *const T, ppSession: ?*?*IRTCSession) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionOperationCompleteEvent.VTable, self.vtable).get_Session(@ptrCast(*const IRTCSessionOperationCompleteEvent, self), ppSession);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionOperationCompleteEvent_get_Cookie(self: *const T, plCookie: ?*isize) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionOperationCompleteEvent.VTable, self.vtable).get_Cookie(@ptrCast(*const IRTCSessionOperationCompleteEvent, self), plCookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionOperationCompleteEvent_get_StatusCode(self: *const T, plStatusCode: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionOperationCompleteEvent.VTable, self.vtable).get_StatusCode(@ptrCast(*const IRTCSessionOperationCompleteEvent, self), plStatusCode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionOperationCompleteEvent_get_StatusText(self: *const T, pbstrStatusText: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionOperationCompleteEvent.VTable, self.vtable).get_StatusText(@ptrCast(*const IRTCSessionOperationCompleteEvent, self), pbstrStatusText);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCSessionOperationCompleteEvent2_Value = @import("../zig.zig").Guid.initString("f6fc2a9b-d5bc-4241-b436-1b8460c13832");
pub const IID_IRTCSessionOperationCompleteEvent2 = &IID_IRTCSessionOperationCompleteEvent2_Value;
pub const IRTCSessionOperationCompleteEvent2 = extern struct {
pub const VTable = extern struct {
base: IRTCSessionOperationCompleteEvent.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Participant: fn(
self: *const IRTCSessionOperationCompleteEvent2,
ppParticipant: ?*?*IRTCParticipant,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetRemoteSessionDescription: fn(
self: *const IRTCSessionOperationCompleteEvent2,
pbstrContentType: ?*?BSTR,
pbstrSessionDescription: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IRTCSessionOperationCompleteEvent.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionOperationCompleteEvent2_get_Participant(self: *const T, ppParticipant: ?*?*IRTCParticipant) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionOperationCompleteEvent2.VTable, self.vtable).get_Participant(@ptrCast(*const IRTCSessionOperationCompleteEvent2, self), ppParticipant);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionOperationCompleteEvent2_GetRemoteSessionDescription(self: *const T, pbstrContentType: ?*?BSTR, pbstrSessionDescription: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionOperationCompleteEvent2.VTable, self.vtable).GetRemoteSessionDescription(@ptrCast(*const IRTCSessionOperationCompleteEvent2, self), pbstrContentType, pbstrSessionDescription);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCParticipantStateChangeEvent_Value = @import("../zig.zig").Guid.initString("09bcb597-f0fa-48f9-b420-468cea7fde04");
pub const IID_IRTCParticipantStateChangeEvent = &IID_IRTCParticipantStateChangeEvent_Value;
pub const IRTCParticipantStateChangeEvent = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Participant: fn(
self: *const IRTCParticipantStateChangeEvent,
ppParticipant: ?*?*IRTCParticipant,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_State: fn(
self: *const IRTCParticipantStateChangeEvent,
penState: ?*RTC_PARTICIPANT_STATE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_StatusCode: fn(
self: *const IRTCParticipantStateChangeEvent,
plStatusCode: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCParticipantStateChangeEvent_get_Participant(self: *const T, ppParticipant: ?*?*IRTCParticipant) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCParticipantStateChangeEvent.VTable, self.vtable).get_Participant(@ptrCast(*const IRTCParticipantStateChangeEvent, self), ppParticipant);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCParticipantStateChangeEvent_get_State(self: *const T, penState: ?*RTC_PARTICIPANT_STATE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCParticipantStateChangeEvent.VTable, self.vtable).get_State(@ptrCast(*const IRTCParticipantStateChangeEvent, self), penState);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCParticipantStateChangeEvent_get_StatusCode(self: *const T, plStatusCode: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCParticipantStateChangeEvent.VTable, self.vtable).get_StatusCode(@ptrCast(*const IRTCParticipantStateChangeEvent, self), plStatusCode);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCMediaEvent_Value = @import("../zig.zig").Guid.initString("099944fb-bcda-453e-8c41-e13da2adf7f3");
pub const IID_IRTCMediaEvent = &IID_IRTCMediaEvent_Value;
pub const IRTCMediaEvent = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_MediaType: fn(
self: *const IRTCMediaEvent,
pMediaType: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_EventType: fn(
self: *const IRTCMediaEvent,
penEventType: ?*RTC_MEDIA_EVENT_TYPE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_EventReason: fn(
self: *const IRTCMediaEvent,
penEventReason: ?*RTC_MEDIA_EVENT_REASON,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCMediaEvent_get_MediaType(self: *const T, pMediaType: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCMediaEvent.VTable, self.vtable).get_MediaType(@ptrCast(*const IRTCMediaEvent, self), pMediaType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCMediaEvent_get_EventType(self: *const T, penEventType: ?*RTC_MEDIA_EVENT_TYPE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCMediaEvent.VTable, self.vtable).get_EventType(@ptrCast(*const IRTCMediaEvent, self), penEventType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCMediaEvent_get_EventReason(self: *const T, penEventReason: ?*RTC_MEDIA_EVENT_REASON) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCMediaEvent.VTable, self.vtable).get_EventReason(@ptrCast(*const IRTCMediaEvent, self), penEventReason);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCIntensityEvent_Value = @import("../zig.zig").Guid.initString("4c23bf51-390c-4992-a41d-41eec05b2a4b");
pub const IID_IRTCIntensityEvent = &IID_IRTCIntensityEvent_Value;
pub const IRTCIntensityEvent = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Level: fn(
self: *const IRTCIntensityEvent,
plLevel: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Min: fn(
self: *const IRTCIntensityEvent,
plMin: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Max: fn(
self: *const IRTCIntensityEvent,
plMax: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Direction: fn(
self: *const IRTCIntensityEvent,
penDirection: ?*RTC_AUDIO_DEVICE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCIntensityEvent_get_Level(self: *const T, plLevel: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCIntensityEvent.VTable, self.vtable).get_Level(@ptrCast(*const IRTCIntensityEvent, self), plLevel);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCIntensityEvent_get_Min(self: *const T, plMin: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCIntensityEvent.VTable, self.vtable).get_Min(@ptrCast(*const IRTCIntensityEvent, self), plMin);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCIntensityEvent_get_Max(self: *const T, plMax: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCIntensityEvent.VTable, self.vtable).get_Max(@ptrCast(*const IRTCIntensityEvent, self), plMax);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCIntensityEvent_get_Direction(self: *const T, penDirection: ?*RTC_AUDIO_DEVICE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCIntensityEvent.VTable, self.vtable).get_Direction(@ptrCast(*const IRTCIntensityEvent, self), penDirection);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCMessagingEvent_Value = @import("../zig.zig").Guid.initString("d3609541-1b29-4de5-a4ad-5aebaf319512");
pub const IID_IRTCMessagingEvent = &IID_IRTCMessagingEvent_Value;
pub const IRTCMessagingEvent = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Session: fn(
self: *const IRTCMessagingEvent,
ppSession: ?*?*IRTCSession,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Participant: fn(
self: *const IRTCMessagingEvent,
ppParticipant: ?*?*IRTCParticipant,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_EventType: fn(
self: *const IRTCMessagingEvent,
penEventType: ?*RTC_MESSAGING_EVENT_TYPE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Message: fn(
self: *const IRTCMessagingEvent,
pbstrMessage: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_MessageHeader: fn(
self: *const IRTCMessagingEvent,
pbstrMessageHeader: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_UserStatus: fn(
self: *const IRTCMessagingEvent,
penUserStatus: ?*RTC_MESSAGING_USER_STATUS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCMessagingEvent_get_Session(self: *const T, ppSession: ?*?*IRTCSession) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCMessagingEvent.VTable, self.vtable).get_Session(@ptrCast(*const IRTCMessagingEvent, self), ppSession);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCMessagingEvent_get_Participant(self: *const T, ppParticipant: ?*?*IRTCParticipant) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCMessagingEvent.VTable, self.vtable).get_Participant(@ptrCast(*const IRTCMessagingEvent, self), ppParticipant);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCMessagingEvent_get_EventType(self: *const T, penEventType: ?*RTC_MESSAGING_EVENT_TYPE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCMessagingEvent.VTable, self.vtable).get_EventType(@ptrCast(*const IRTCMessagingEvent, self), penEventType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCMessagingEvent_get_Message(self: *const T, pbstrMessage: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCMessagingEvent.VTable, self.vtable).get_Message(@ptrCast(*const IRTCMessagingEvent, self), pbstrMessage);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCMessagingEvent_get_MessageHeader(self: *const T, pbstrMessageHeader: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCMessagingEvent.VTable, self.vtable).get_MessageHeader(@ptrCast(*const IRTCMessagingEvent, self), pbstrMessageHeader);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCMessagingEvent_get_UserStatus(self: *const T, penUserStatus: ?*RTC_MESSAGING_USER_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCMessagingEvent.VTable, self.vtable).get_UserStatus(@ptrCast(*const IRTCMessagingEvent, self), penUserStatus);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCBuddyEvent_Value = @import("../zig.zig").Guid.initString("f36d755d-17e6-404e-954f-0fc07574c78d");
pub const IID_IRTCBuddyEvent = &IID_IRTCBuddyEvent_Value;
pub const IRTCBuddyEvent = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Buddy: fn(
self: *const IRTCBuddyEvent,
ppBuddy: ?*?*IRTCBuddy,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCBuddyEvent_get_Buddy(self: *const T, ppBuddy: ?*?*IRTCBuddy) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCBuddyEvent.VTable, self.vtable).get_Buddy(@ptrCast(*const IRTCBuddyEvent, self), ppBuddy);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCBuddyEvent2_Value = @import("../zig.zig").Guid.initString("484a7f1e-73f0-4990-bfc2-60bc3978a720");
pub const IID_IRTCBuddyEvent2 = &IID_IRTCBuddyEvent2_Value;
pub const IRTCBuddyEvent2 = extern struct {
pub const VTable = extern struct {
base: IRTCBuddyEvent.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_EventType: fn(
self: *const IRTCBuddyEvent2,
pEventType: ?*RTC_BUDDY_EVENT_TYPE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_StatusCode: fn(
self: *const IRTCBuddyEvent2,
plStatusCode: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_StatusText: fn(
self: *const IRTCBuddyEvent2,
pbstrStatusText: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IRTCBuddyEvent.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCBuddyEvent2_get_EventType(self: *const T, pEventType: ?*RTC_BUDDY_EVENT_TYPE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCBuddyEvent2.VTable, self.vtable).get_EventType(@ptrCast(*const IRTCBuddyEvent2, self), pEventType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCBuddyEvent2_get_StatusCode(self: *const T, plStatusCode: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCBuddyEvent2.VTable, self.vtable).get_StatusCode(@ptrCast(*const IRTCBuddyEvent2, self), plStatusCode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCBuddyEvent2_get_StatusText(self: *const T, pbstrStatusText: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCBuddyEvent2.VTable, self.vtable).get_StatusText(@ptrCast(*const IRTCBuddyEvent2, self), pbstrStatusText);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCWatcherEvent_Value = @import("../zig.zig").Guid.initString("f30d7261-587a-424f-822c-312788f43548");
pub const IID_IRTCWatcherEvent = &IID_IRTCWatcherEvent_Value;
pub const IRTCWatcherEvent = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Watcher: fn(
self: *const IRTCWatcherEvent,
ppWatcher: ?*?*IRTCWatcher,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCWatcherEvent_get_Watcher(self: *const T, ppWatcher: ?*?*IRTCWatcher) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCWatcherEvent.VTable, self.vtable).get_Watcher(@ptrCast(*const IRTCWatcherEvent, self), ppWatcher);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCWatcherEvent2_Value = @import("../zig.zig").Guid.initString("e52891e8-188c-49af-b005-98ed13f83f9c");
pub const IID_IRTCWatcherEvent2 = &IID_IRTCWatcherEvent2_Value;
pub const IRTCWatcherEvent2 = extern struct {
pub const VTable = extern struct {
base: IRTCWatcherEvent.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_EventType: fn(
self: *const IRTCWatcherEvent2,
pEventType: ?*RTC_WATCHER_EVENT_TYPE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_StatusCode: fn(
self: *const IRTCWatcherEvent2,
plStatusCode: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IRTCWatcherEvent.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCWatcherEvent2_get_EventType(self: *const T, pEventType: ?*RTC_WATCHER_EVENT_TYPE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCWatcherEvent2.VTable, self.vtable).get_EventType(@ptrCast(*const IRTCWatcherEvent2, self), pEventType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCWatcherEvent2_get_StatusCode(self: *const T, plStatusCode: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCWatcherEvent2.VTable, self.vtable).get_StatusCode(@ptrCast(*const IRTCWatcherEvent2, self), plStatusCode);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCBuddyGroupEvent_Value = @import("../zig.zig").Guid.initString("3a79e1d1-b736-4414-96f8-bbc7f08863e4");
pub const IID_IRTCBuddyGroupEvent = &IID_IRTCBuddyGroupEvent_Value;
pub const IRTCBuddyGroupEvent = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_EventType: fn(
self: *const IRTCBuddyGroupEvent,
pEventType: ?*RTC_GROUP_EVENT_TYPE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Group: fn(
self: *const IRTCBuddyGroupEvent,
ppGroup: ?*?*IRTCBuddyGroup,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Buddy: fn(
self: *const IRTCBuddyGroupEvent,
ppBuddy: ?*?*IRTCBuddy2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_StatusCode: fn(
self: *const IRTCBuddyGroupEvent,
plStatusCode: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCBuddyGroupEvent_get_EventType(self: *const T, pEventType: ?*RTC_GROUP_EVENT_TYPE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCBuddyGroupEvent.VTable, self.vtable).get_EventType(@ptrCast(*const IRTCBuddyGroupEvent, self), pEventType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCBuddyGroupEvent_get_Group(self: *const T, ppGroup: ?*?*IRTCBuddyGroup) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCBuddyGroupEvent.VTable, self.vtable).get_Group(@ptrCast(*const IRTCBuddyGroupEvent, self), ppGroup);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCBuddyGroupEvent_get_Buddy(self: *const T, ppBuddy: ?*?*IRTCBuddy2) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCBuddyGroupEvent.VTable, self.vtable).get_Buddy(@ptrCast(*const IRTCBuddyGroupEvent, self), ppBuddy);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCBuddyGroupEvent_get_StatusCode(self: *const T, plStatusCode: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCBuddyGroupEvent.VTable, self.vtable).get_StatusCode(@ptrCast(*const IRTCBuddyGroupEvent, self), plStatusCode);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCInfoEvent_Value = @import("../zig.zig").Guid.initString("4e1d68ae-1912-4f49-b2c3-594fadfd425f");
pub const IID_IRTCInfoEvent = &IID_IRTCInfoEvent_Value;
pub const IRTCInfoEvent = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Session: fn(
self: *const IRTCInfoEvent,
ppSession: ?*?*IRTCSession2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Participant: fn(
self: *const IRTCInfoEvent,
ppParticipant: ?*?*IRTCParticipant,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Info: fn(
self: *const IRTCInfoEvent,
pbstrInfo: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_InfoHeader: fn(
self: *const IRTCInfoEvent,
pbstrInfoHeader: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCInfoEvent_get_Session(self: *const T, ppSession: ?*?*IRTCSession2) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCInfoEvent.VTable, self.vtable).get_Session(@ptrCast(*const IRTCInfoEvent, self), ppSession);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCInfoEvent_get_Participant(self: *const T, ppParticipant: ?*?*IRTCParticipant) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCInfoEvent.VTable, self.vtable).get_Participant(@ptrCast(*const IRTCInfoEvent, self), ppParticipant);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCInfoEvent_get_Info(self: *const T, pbstrInfo: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCInfoEvent.VTable, self.vtable).get_Info(@ptrCast(*const IRTCInfoEvent, self), pbstrInfo);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCInfoEvent_get_InfoHeader(self: *const T, pbstrInfoHeader: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCInfoEvent.VTable, self.vtable).get_InfoHeader(@ptrCast(*const IRTCInfoEvent, self), pbstrInfoHeader);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCMediaRequestEvent_Value = @import("../zig.zig").Guid.initString("52572d15-148c-4d97-a36c-2da55c289d63");
pub const IID_IRTCMediaRequestEvent = &IID_IRTCMediaRequestEvent_Value;
pub const IRTCMediaRequestEvent = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Session: fn(
self: *const IRTCMediaRequestEvent,
ppSession: ?*?*IRTCSession2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ProposedMedia: fn(
self: *const IRTCMediaRequestEvent,
plMediaTypes: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentMedia: fn(
self: *const IRTCMediaRequestEvent,
plMediaTypes: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Accept: fn(
self: *const IRTCMediaRequestEvent,
lMediaTypes: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_RemotePreferredSecurityLevel: fn(
self: *const IRTCMediaRequestEvent,
enSecurityType: RTC_SECURITY_TYPE,
penSecurityLevel: ?*RTC_SECURITY_LEVEL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reject: fn(
self: *const IRTCMediaRequestEvent,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_State: fn(
self: *const IRTCMediaRequestEvent,
pState: ?*RTC_REINVITE_STATE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCMediaRequestEvent_get_Session(self: *const T, ppSession: ?*?*IRTCSession2) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCMediaRequestEvent.VTable, self.vtable).get_Session(@ptrCast(*const IRTCMediaRequestEvent, self), ppSession);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCMediaRequestEvent_get_ProposedMedia(self: *const T, plMediaTypes: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCMediaRequestEvent.VTable, self.vtable).get_ProposedMedia(@ptrCast(*const IRTCMediaRequestEvent, self), plMediaTypes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCMediaRequestEvent_get_CurrentMedia(self: *const T, plMediaTypes: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCMediaRequestEvent.VTable, self.vtable).get_CurrentMedia(@ptrCast(*const IRTCMediaRequestEvent, self), plMediaTypes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCMediaRequestEvent_Accept(self: *const T, lMediaTypes: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCMediaRequestEvent.VTable, self.vtable).Accept(@ptrCast(*const IRTCMediaRequestEvent, self), lMediaTypes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCMediaRequestEvent_get_RemotePreferredSecurityLevel(self: *const T, enSecurityType: RTC_SECURITY_TYPE, penSecurityLevel: ?*RTC_SECURITY_LEVEL) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCMediaRequestEvent.VTable, self.vtable).get_RemotePreferredSecurityLevel(@ptrCast(*const IRTCMediaRequestEvent, self), enSecurityType, penSecurityLevel);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCMediaRequestEvent_Reject(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCMediaRequestEvent.VTable, self.vtable).Reject(@ptrCast(*const IRTCMediaRequestEvent, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCMediaRequestEvent_get_State(self: *const T, pState: ?*RTC_REINVITE_STATE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCMediaRequestEvent.VTable, self.vtable).get_State(@ptrCast(*const IRTCMediaRequestEvent, self), pState);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCReInviteEvent_Value = @import("../zig.zig").Guid.initString("11558d84-204c-43e7-99b0-2034e9417f7d");
pub const IID_IRTCReInviteEvent = &IID_IRTCReInviteEvent_Value;
pub const IRTCReInviteEvent = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Session: fn(
self: *const IRTCReInviteEvent,
ppSession2: ?*?*IRTCSession2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Accept: fn(
self: *const IRTCReInviteEvent,
bstrContentType: ?BSTR,
bstrSessionDescription: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reject: fn(
self: *const IRTCReInviteEvent,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_State: fn(
self: *const IRTCReInviteEvent,
pState: ?*RTC_REINVITE_STATE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetRemoteSessionDescription: fn(
self: *const IRTCReInviteEvent,
pbstrContentType: ?*?BSTR,
pbstrSessionDescription: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCReInviteEvent_get_Session(self: *const T, ppSession2: ?*?*IRTCSession2) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCReInviteEvent.VTable, self.vtable).get_Session(@ptrCast(*const IRTCReInviteEvent, self), ppSession2);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCReInviteEvent_Accept(self: *const T, bstrContentType: ?BSTR, bstrSessionDescription: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCReInviteEvent.VTable, self.vtable).Accept(@ptrCast(*const IRTCReInviteEvent, self), bstrContentType, bstrSessionDescription);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCReInviteEvent_Reject(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCReInviteEvent.VTable, self.vtable).Reject(@ptrCast(*const IRTCReInviteEvent, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCReInviteEvent_get_State(self: *const T, pState: ?*RTC_REINVITE_STATE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCReInviteEvent.VTable, self.vtable).get_State(@ptrCast(*const IRTCReInviteEvent, self), pState);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCReInviteEvent_GetRemoteSessionDescription(self: *const T, pbstrContentType: ?*?BSTR, pbstrSessionDescription: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCReInviteEvent.VTable, self.vtable).GetRemoteSessionDescription(@ptrCast(*const IRTCReInviteEvent, self), pbstrContentType, pbstrSessionDescription);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCPresencePropertyEvent_Value = @import("../zig.zig").Guid.initString("f777f570-a820-49d5-86bd-e099493f1518");
pub const IID_IRTCPresencePropertyEvent = &IID_IRTCPresencePropertyEvent_Value;
pub const IRTCPresencePropertyEvent = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_StatusCode: fn(
self: *const IRTCPresencePropertyEvent,
plStatusCode: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_StatusText: fn(
self: *const IRTCPresencePropertyEvent,
pbstrStatusText: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_PresenceProperty: fn(
self: *const IRTCPresencePropertyEvent,
penPresProp: ?*RTC_PRESENCE_PROPERTY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Value: fn(
self: *const IRTCPresencePropertyEvent,
pbstrValue: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCPresencePropertyEvent_get_StatusCode(self: *const T, plStatusCode: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCPresencePropertyEvent.VTable, self.vtable).get_StatusCode(@ptrCast(*const IRTCPresencePropertyEvent, self), plStatusCode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCPresencePropertyEvent_get_StatusText(self: *const T, pbstrStatusText: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCPresencePropertyEvent.VTable, self.vtable).get_StatusText(@ptrCast(*const IRTCPresencePropertyEvent, self), pbstrStatusText);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCPresencePropertyEvent_get_PresenceProperty(self: *const T, penPresProp: ?*RTC_PRESENCE_PROPERTY) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCPresencePropertyEvent.VTable, self.vtable).get_PresenceProperty(@ptrCast(*const IRTCPresencePropertyEvent, self), penPresProp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCPresencePropertyEvent_get_Value(self: *const T, pbstrValue: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCPresencePropertyEvent.VTable, self.vtable).get_Value(@ptrCast(*const IRTCPresencePropertyEvent, self), pbstrValue);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCPresenceDataEvent_Value = @import("../zig.zig").Guid.initString("38f0e78c-8b87-4c04-a82d-aedd83c909bb");
pub const IID_IRTCPresenceDataEvent = &IID_IRTCPresenceDataEvent_Value;
pub const IRTCPresenceDataEvent = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_StatusCode: fn(
self: *const IRTCPresenceDataEvent,
plStatusCode: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_StatusText: fn(
self: *const IRTCPresenceDataEvent,
pbstrStatusText: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPresenceData: fn(
self: *const IRTCPresenceDataEvent,
pbstrNamespace: ?*?BSTR,
pbstrData: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCPresenceDataEvent_get_StatusCode(self: *const T, plStatusCode: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCPresenceDataEvent.VTable, self.vtable).get_StatusCode(@ptrCast(*const IRTCPresenceDataEvent, self), plStatusCode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCPresenceDataEvent_get_StatusText(self: *const T, pbstrStatusText: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCPresenceDataEvent.VTable, self.vtable).get_StatusText(@ptrCast(*const IRTCPresenceDataEvent, self), pbstrStatusText);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCPresenceDataEvent_GetPresenceData(self: *const T, pbstrNamespace: ?*?BSTR, pbstrData: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCPresenceDataEvent.VTable, self.vtable).GetPresenceData(@ptrCast(*const IRTCPresenceDataEvent, self), pbstrNamespace, pbstrData);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCPresenceStatusEvent_Value = @import("../zig.zig").Guid.initString("78673f32-4a0f-462c-89aa-ee7706707678");
pub const IID_IRTCPresenceStatusEvent = &IID_IRTCPresenceStatusEvent_Value;
pub const IRTCPresenceStatusEvent = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_StatusCode: fn(
self: *const IRTCPresenceStatusEvent,
plStatusCode: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_StatusText: fn(
self: *const IRTCPresenceStatusEvent,
pbstrStatusText: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLocalPresenceInfo: fn(
self: *const IRTCPresenceStatusEvent,
penStatus: ?*RTC_PRESENCE_STATUS,
pbstrNotes: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCPresenceStatusEvent_get_StatusCode(self: *const T, plStatusCode: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCPresenceStatusEvent.VTable, self.vtable).get_StatusCode(@ptrCast(*const IRTCPresenceStatusEvent, self), plStatusCode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCPresenceStatusEvent_get_StatusText(self: *const T, pbstrStatusText: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCPresenceStatusEvent.VTable, self.vtable).get_StatusText(@ptrCast(*const IRTCPresenceStatusEvent, self), pbstrStatusText);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCPresenceStatusEvent_GetLocalPresenceInfo(self: *const T, penStatus: ?*RTC_PRESENCE_STATUS, pbstrNotes: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCPresenceStatusEvent.VTable, self.vtable).GetLocalPresenceInfo(@ptrCast(*const IRTCPresenceStatusEvent, self), penStatus, pbstrNotes);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCCollection_Value = @import("../zig.zig").Guid.initString("ec7c8096-b918-4044-94f1-e4fba0361d5c");
pub const IID_IRTCCollection = &IID_IRTCCollection_Value;
pub const IRTCCollection = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Count: fn(
self: *const IRTCCollection,
lCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Item: fn(
self: *const IRTCCollection,
Index: i32,
pVariant: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get__NewEnum: fn(
self: *const IRTCCollection,
ppNewEnum: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCCollection_get_Count(self: *const T, lCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCCollection.VTable, self.vtable).get_Count(@ptrCast(*const IRTCCollection, self), lCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCCollection_get_Item(self: *const T, Index: i32, pVariant: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCCollection.VTable, self.vtable).get_Item(@ptrCast(*const IRTCCollection, self), Index, pVariant);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCCollection_get__NewEnum(self: *const T, ppNewEnum: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCCollection.VTable, self.vtable).get__NewEnum(@ptrCast(*const IRTCCollection, self), ppNewEnum);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCEnumParticipants_Value = @import("../zig.zig").Guid.initString("fcd56f29-4a4f-41b2-ba5c-f5bccc060bf6");
pub const IID_IRTCEnumParticipants = &IID_IRTCEnumParticipants_Value;
pub const IRTCEnumParticipants = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Next: fn(
self: *const IRTCEnumParticipants,
celt: u32,
ppElements: [*]?*IRTCParticipant,
pceltFetched: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reset: fn(
self: *const IRTCEnumParticipants,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Skip: fn(
self: *const IRTCEnumParticipants,
celt: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clone: fn(
self: *const IRTCEnumParticipants,
ppEnum: ?*?*IRTCEnumParticipants,
) 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 IRTCEnumParticipants_Next(self: *const T, celt: u32, ppElements: [*]?*IRTCParticipant, pceltFetched: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCEnumParticipants.VTable, self.vtable).Next(@ptrCast(*const IRTCEnumParticipants, self), celt, ppElements, pceltFetched);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCEnumParticipants_Reset(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCEnumParticipants.VTable, self.vtable).Reset(@ptrCast(*const IRTCEnumParticipants, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCEnumParticipants_Skip(self: *const T, celt: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCEnumParticipants.VTable, self.vtable).Skip(@ptrCast(*const IRTCEnumParticipants, self), celt);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCEnumParticipants_Clone(self: *const T, ppEnum: ?*?*IRTCEnumParticipants) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCEnumParticipants.VTable, self.vtable).Clone(@ptrCast(*const IRTCEnumParticipants, self), ppEnum);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCEnumProfiles_Value = @import("../zig.zig").Guid.initString("29b7c41c-ed82-4bca-84ad-39d5101b58e3");
pub const IID_IRTCEnumProfiles = &IID_IRTCEnumProfiles_Value;
pub const IRTCEnumProfiles = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Next: fn(
self: *const IRTCEnumProfiles,
celt: u32,
ppElements: [*]?*IRTCProfile,
pceltFetched: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reset: fn(
self: *const IRTCEnumProfiles,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Skip: fn(
self: *const IRTCEnumProfiles,
celt: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clone: fn(
self: *const IRTCEnumProfiles,
ppEnum: ?*?*IRTCEnumProfiles,
) 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 IRTCEnumProfiles_Next(self: *const T, celt: u32, ppElements: [*]?*IRTCProfile, pceltFetched: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCEnumProfiles.VTable, self.vtable).Next(@ptrCast(*const IRTCEnumProfiles, self), celt, ppElements, pceltFetched);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCEnumProfiles_Reset(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCEnumProfiles.VTable, self.vtable).Reset(@ptrCast(*const IRTCEnumProfiles, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCEnumProfiles_Skip(self: *const T, celt: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCEnumProfiles.VTable, self.vtable).Skip(@ptrCast(*const IRTCEnumProfiles, self), celt);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCEnumProfiles_Clone(self: *const T, ppEnum: ?*?*IRTCEnumProfiles) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCEnumProfiles.VTable, self.vtable).Clone(@ptrCast(*const IRTCEnumProfiles, self), ppEnum);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCEnumBuddies_Value = @import("../zig.zig").Guid.initString("f7296917-5569-4b3b-b3af-98d1144b2b87");
pub const IID_IRTCEnumBuddies = &IID_IRTCEnumBuddies_Value;
pub const IRTCEnumBuddies = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Next: fn(
self: *const IRTCEnumBuddies,
celt: u32,
ppElements: [*]?*IRTCBuddy,
pceltFetched: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reset: fn(
self: *const IRTCEnumBuddies,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Skip: fn(
self: *const IRTCEnumBuddies,
celt: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clone: fn(
self: *const IRTCEnumBuddies,
ppEnum: ?*?*IRTCEnumBuddies,
) 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 IRTCEnumBuddies_Next(self: *const T, celt: u32, ppElements: [*]?*IRTCBuddy, pceltFetched: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCEnumBuddies.VTable, self.vtable).Next(@ptrCast(*const IRTCEnumBuddies, self), celt, ppElements, pceltFetched);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCEnumBuddies_Reset(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCEnumBuddies.VTable, self.vtable).Reset(@ptrCast(*const IRTCEnumBuddies, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCEnumBuddies_Skip(self: *const T, celt: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCEnumBuddies.VTable, self.vtable).Skip(@ptrCast(*const IRTCEnumBuddies, self), celt);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCEnumBuddies_Clone(self: *const T, ppEnum: ?*?*IRTCEnumBuddies) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCEnumBuddies.VTable, self.vtable).Clone(@ptrCast(*const IRTCEnumBuddies, self), ppEnum);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCEnumWatchers_Value = @import("../zig.zig").Guid.initString("a87d55d7-db74-4ed1-9ca4-77a0e41b413e");
pub const IID_IRTCEnumWatchers = &IID_IRTCEnumWatchers_Value;
pub const IRTCEnumWatchers = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Next: fn(
self: *const IRTCEnumWatchers,
celt: u32,
ppElements: [*]?*IRTCWatcher,
pceltFetched: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reset: fn(
self: *const IRTCEnumWatchers,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Skip: fn(
self: *const IRTCEnumWatchers,
celt: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clone: fn(
self: *const IRTCEnumWatchers,
ppEnum: ?*?*IRTCEnumWatchers,
) 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 IRTCEnumWatchers_Next(self: *const T, celt: u32, ppElements: [*]?*IRTCWatcher, pceltFetched: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCEnumWatchers.VTable, self.vtable).Next(@ptrCast(*const IRTCEnumWatchers, self), celt, ppElements, pceltFetched);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCEnumWatchers_Reset(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCEnumWatchers.VTable, self.vtable).Reset(@ptrCast(*const IRTCEnumWatchers, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCEnumWatchers_Skip(self: *const T, celt: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCEnumWatchers.VTable, self.vtable).Skip(@ptrCast(*const IRTCEnumWatchers, self), celt);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCEnumWatchers_Clone(self: *const T, ppEnum: ?*?*IRTCEnumWatchers) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCEnumWatchers.VTable, self.vtable).Clone(@ptrCast(*const IRTCEnumWatchers, self), ppEnum);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCEnumGroups_Value = @import("../zig.zig").Guid.initString("742378d6-a141-4415-8f27-35d99076cf5d");
pub const IID_IRTCEnumGroups = &IID_IRTCEnumGroups_Value;
pub const IRTCEnumGroups = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Next: fn(
self: *const IRTCEnumGroups,
celt: u32,
ppElements: [*]?*IRTCBuddyGroup,
pceltFetched: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reset: fn(
self: *const IRTCEnumGroups,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Skip: fn(
self: *const IRTCEnumGroups,
celt: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clone: fn(
self: *const IRTCEnumGroups,
ppEnum: ?*?*IRTCEnumGroups,
) 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 IRTCEnumGroups_Next(self: *const T, celt: u32, ppElements: [*]?*IRTCBuddyGroup, pceltFetched: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCEnumGroups.VTable, self.vtable).Next(@ptrCast(*const IRTCEnumGroups, self), celt, ppElements, pceltFetched);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCEnumGroups_Reset(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCEnumGroups.VTable, self.vtable).Reset(@ptrCast(*const IRTCEnumGroups, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCEnumGroups_Skip(self: *const T, celt: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCEnumGroups.VTable, self.vtable).Skip(@ptrCast(*const IRTCEnumGroups, self), celt);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCEnumGroups_Clone(self: *const T, ppEnum: ?*?*IRTCEnumGroups) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCEnumGroups.VTable, self.vtable).Clone(@ptrCast(*const IRTCEnumGroups, self), ppEnum);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCPresenceContact_Value = @import("../zig.zig").Guid.initString("8b22f92c-cd90-42db-a733-212205c3e3df");
pub const IID_IRTCPresenceContact = &IID_IRTCPresenceContact_Value;
pub const IRTCPresenceContact = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_PresentityURI: fn(
self: *const IRTCPresenceContact,
pbstrPresentityURI: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_PresentityURI: fn(
self: *const IRTCPresenceContact,
bstrPresentityURI: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Name: fn(
self: *const IRTCPresenceContact,
pbstrName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Name: fn(
self: *const IRTCPresenceContact,
bstrName: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Data: fn(
self: *const IRTCPresenceContact,
pbstrData: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Data: fn(
self: *const IRTCPresenceContact,
bstrData: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Persistent: fn(
self: *const IRTCPresenceContact,
pfPersistent: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Persistent: fn(
self: *const IRTCPresenceContact,
fPersistent: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCPresenceContact_get_PresentityURI(self: *const T, pbstrPresentityURI: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCPresenceContact.VTable, self.vtable).get_PresentityURI(@ptrCast(*const IRTCPresenceContact, self), pbstrPresentityURI);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCPresenceContact_put_PresentityURI(self: *const T, bstrPresentityURI: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCPresenceContact.VTable, self.vtable).put_PresentityURI(@ptrCast(*const IRTCPresenceContact, self), bstrPresentityURI);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCPresenceContact_get_Name(self: *const T, pbstrName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCPresenceContact.VTable, self.vtable).get_Name(@ptrCast(*const IRTCPresenceContact, self), pbstrName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCPresenceContact_put_Name(self: *const T, bstrName: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCPresenceContact.VTable, self.vtable).put_Name(@ptrCast(*const IRTCPresenceContact, self), bstrName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCPresenceContact_get_Data(self: *const T, pbstrData: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCPresenceContact.VTable, self.vtable).get_Data(@ptrCast(*const IRTCPresenceContact, self), pbstrData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCPresenceContact_put_Data(self: *const T, bstrData: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCPresenceContact.VTable, self.vtable).put_Data(@ptrCast(*const IRTCPresenceContact, self), bstrData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCPresenceContact_get_Persistent(self: *const T, pfPersistent: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCPresenceContact.VTable, self.vtable).get_Persistent(@ptrCast(*const IRTCPresenceContact, self), pfPersistent);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCPresenceContact_put_Persistent(self: *const T, fPersistent: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCPresenceContact.VTable, self.vtable).put_Persistent(@ptrCast(*const IRTCPresenceContact, self), fPersistent);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCBuddy_Value = @import("../zig.zig").Guid.initString("fcb136c8-7b90-4e0c-befe-56edf0ba6f1c");
pub const IID_IRTCBuddy = &IID_IRTCBuddy_Value;
pub const IRTCBuddy = extern struct {
pub const VTable = extern struct {
base: IRTCPresenceContact.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Status: fn(
self: *const IRTCBuddy,
penStatus: ?*RTC_PRESENCE_STATUS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Notes: fn(
self: *const IRTCBuddy,
pbstrNotes: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IRTCPresenceContact.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCBuddy_get_Status(self: *const T, penStatus: ?*RTC_PRESENCE_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCBuddy.VTable, self.vtable).get_Status(@ptrCast(*const IRTCBuddy, self), penStatus);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCBuddy_get_Notes(self: *const T, pbstrNotes: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCBuddy.VTable, self.vtable).get_Notes(@ptrCast(*const IRTCBuddy, self), pbstrNotes);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCBuddy2_Value = @import("../zig.zig").Guid.initString("102f9588-23e7-40e3-954d-cd7a1d5c0361");
pub const IID_IRTCBuddy2 = &IID_IRTCBuddy2_Value;
pub const IRTCBuddy2 = extern struct {
pub const VTable = extern struct {
base: IRTCBuddy.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Profile: fn(
self: *const IRTCBuddy2,
ppProfile: ?*?*IRTCProfile2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Refresh: fn(
self: *const IRTCBuddy2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EnumerateGroups: fn(
self: *const IRTCBuddy2,
ppEnum: ?*?*IRTCEnumGroups,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Groups: fn(
self: *const IRTCBuddy2,
ppCollection: ?*?*IRTCCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_PresenceProperty: fn(
self: *const IRTCBuddy2,
enProperty: RTC_PRESENCE_PROPERTY,
pbstrProperty: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EnumeratePresenceDevices: fn(
self: *const IRTCBuddy2,
ppEnumDevices: ?*?*IRTCEnumPresenceDevices,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_PresenceDevices: fn(
self: *const IRTCBuddy2,
ppDevicesCollection: ?*?*IRTCCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_SubscriptionType: fn(
self: *const IRTCBuddy2,
penSubscriptionType: ?*RTC_BUDDY_SUBSCRIPTION_TYPE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IRTCBuddy.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCBuddy2_get_Profile(self: *const T, ppProfile: ?*?*IRTCProfile2) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCBuddy2.VTable, self.vtable).get_Profile(@ptrCast(*const IRTCBuddy2, self), ppProfile);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCBuddy2_Refresh(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCBuddy2.VTable, self.vtable).Refresh(@ptrCast(*const IRTCBuddy2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCBuddy2_EnumerateGroups(self: *const T, ppEnum: ?*?*IRTCEnumGroups) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCBuddy2.VTable, self.vtable).EnumerateGroups(@ptrCast(*const IRTCBuddy2, self), ppEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCBuddy2_get_Groups(self: *const T, ppCollection: ?*?*IRTCCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCBuddy2.VTable, self.vtable).get_Groups(@ptrCast(*const IRTCBuddy2, self), ppCollection);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCBuddy2_get_PresenceProperty(self: *const T, enProperty: RTC_PRESENCE_PROPERTY, pbstrProperty: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCBuddy2.VTable, self.vtable).get_PresenceProperty(@ptrCast(*const IRTCBuddy2, self), enProperty, pbstrProperty);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCBuddy2_EnumeratePresenceDevices(self: *const T, ppEnumDevices: ?*?*IRTCEnumPresenceDevices) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCBuddy2.VTable, self.vtable).EnumeratePresenceDevices(@ptrCast(*const IRTCBuddy2, self), ppEnumDevices);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCBuddy2_get_PresenceDevices(self: *const T, ppDevicesCollection: ?*?*IRTCCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCBuddy2.VTable, self.vtable).get_PresenceDevices(@ptrCast(*const IRTCBuddy2, self), ppDevicesCollection);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCBuddy2_get_SubscriptionType(self: *const T, penSubscriptionType: ?*RTC_BUDDY_SUBSCRIPTION_TYPE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCBuddy2.VTable, self.vtable).get_SubscriptionType(@ptrCast(*const IRTCBuddy2, self), penSubscriptionType);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCWatcher_Value = @import("../zig.zig").Guid.initString("c7cedad8-346b-4d1b-ac02-a2088df9be4f");
pub const IID_IRTCWatcher = &IID_IRTCWatcher_Value;
pub const IRTCWatcher = extern struct {
pub const VTable = extern struct {
base: IRTCPresenceContact.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_State: fn(
self: *const IRTCWatcher,
penState: ?*RTC_WATCHER_STATE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_State: fn(
self: *const IRTCWatcher,
enState: RTC_WATCHER_STATE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IRTCPresenceContact.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCWatcher_get_State(self: *const T, penState: ?*RTC_WATCHER_STATE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCWatcher.VTable, self.vtable).get_State(@ptrCast(*const IRTCWatcher, self), penState);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCWatcher_put_State(self: *const T, enState: RTC_WATCHER_STATE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCWatcher.VTable, self.vtable).put_State(@ptrCast(*const IRTCWatcher, self), enState);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCWatcher2_Value = @import("../zig.zig").Guid.initString("d4d9967f-d011-4b1d-91e3-aba78f96393d");
pub const IID_IRTCWatcher2 = &IID_IRTCWatcher2_Value;
pub const IRTCWatcher2 = extern struct {
pub const VTable = extern struct {
base: IRTCWatcher.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Profile: fn(
self: *const IRTCWatcher2,
ppProfile: ?*?*IRTCProfile2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Scope: fn(
self: *const IRTCWatcher2,
penScope: ?*RTC_ACE_SCOPE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IRTCWatcher.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCWatcher2_get_Profile(self: *const T, ppProfile: ?*?*IRTCProfile2) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCWatcher2.VTable, self.vtable).get_Profile(@ptrCast(*const IRTCWatcher2, self), ppProfile);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCWatcher2_get_Scope(self: *const T, penScope: ?*RTC_ACE_SCOPE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCWatcher2.VTable, self.vtable).get_Scope(@ptrCast(*const IRTCWatcher2, self), penScope);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCBuddyGroup_Value = @import("../zig.zig").Guid.initString("60361e68-9164-4389-a4c6-d0b3925bda5e");
pub const IID_IRTCBuddyGroup = &IID_IRTCBuddyGroup_Value;
pub const IRTCBuddyGroup = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Name: fn(
self: *const IRTCBuddyGroup,
pbstrGroupName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Name: fn(
self: *const IRTCBuddyGroup,
bstrGroupName: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddBuddy: fn(
self: *const IRTCBuddyGroup,
pBuddy: ?*IRTCBuddy,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveBuddy: fn(
self: *const IRTCBuddyGroup,
pBuddy: ?*IRTCBuddy,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EnumerateBuddies: fn(
self: *const IRTCBuddyGroup,
ppEnum: ?*?*IRTCEnumBuddies,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Buddies: fn(
self: *const IRTCBuddyGroup,
ppCollection: ?*?*IRTCCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Data: fn(
self: *const IRTCBuddyGroup,
pbstrData: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Data: fn(
self: *const IRTCBuddyGroup,
bstrData: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Profile: fn(
self: *const IRTCBuddyGroup,
ppProfile: ?*?*IRTCProfile2,
) 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 IRTCBuddyGroup_get_Name(self: *const T, pbstrGroupName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCBuddyGroup.VTable, self.vtable).get_Name(@ptrCast(*const IRTCBuddyGroup, self), pbstrGroupName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCBuddyGroup_put_Name(self: *const T, bstrGroupName: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCBuddyGroup.VTable, self.vtable).put_Name(@ptrCast(*const IRTCBuddyGroup, self), bstrGroupName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCBuddyGroup_AddBuddy(self: *const T, pBuddy: ?*IRTCBuddy) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCBuddyGroup.VTable, self.vtable).AddBuddy(@ptrCast(*const IRTCBuddyGroup, self), pBuddy);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCBuddyGroup_RemoveBuddy(self: *const T, pBuddy: ?*IRTCBuddy) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCBuddyGroup.VTable, self.vtable).RemoveBuddy(@ptrCast(*const IRTCBuddyGroup, self), pBuddy);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCBuddyGroup_EnumerateBuddies(self: *const T, ppEnum: ?*?*IRTCEnumBuddies) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCBuddyGroup.VTable, self.vtable).EnumerateBuddies(@ptrCast(*const IRTCBuddyGroup, self), ppEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCBuddyGroup_get_Buddies(self: *const T, ppCollection: ?*?*IRTCCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCBuddyGroup.VTable, self.vtable).get_Buddies(@ptrCast(*const IRTCBuddyGroup, self), ppCollection);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCBuddyGroup_get_Data(self: *const T, pbstrData: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCBuddyGroup.VTable, self.vtable).get_Data(@ptrCast(*const IRTCBuddyGroup, self), pbstrData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCBuddyGroup_put_Data(self: *const T, bstrData: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCBuddyGroup.VTable, self.vtable).put_Data(@ptrCast(*const IRTCBuddyGroup, self), bstrData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCBuddyGroup_get_Profile(self: *const T, ppProfile: ?*?*IRTCProfile2) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCBuddyGroup.VTable, self.vtable).get_Profile(@ptrCast(*const IRTCBuddyGroup, self), ppProfile);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCEventNotification_Value = @import("../zig.zig").Guid.initString("13fa24c7-5748-4b21-91f5-7397609ce747");
pub const IID_IRTCEventNotification = &IID_IRTCEventNotification_Value;
pub const IRTCEventNotification = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Event: fn(
self: *const IRTCEventNotification,
RTCEvent: RTC_EVENT,
pEvent: ?*IDispatch,
) 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 IRTCEventNotification_Event(self: *const T, RTCEvent: RTC_EVENT, pEvent: ?*IDispatch) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCEventNotification.VTable, self.vtable).Event(@ptrCast(*const IRTCEventNotification, self), RTCEvent, pEvent);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCPortManager_Value = @import("../zig.zig").Guid.initString("da77c14b-6208-43ca-8ddf-5b60a0a69fac");
pub const IID_IRTCPortManager = &IID_IRTCPortManager_Value;
pub const IRTCPortManager = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetMapping: fn(
self: *const IRTCPortManager,
bstrRemoteAddress: ?BSTR,
enPortType: RTC_PORT_TYPE,
pbstrInternalLocalAddress: ?*?BSTR,
plInternalLocalPort: ?*i32,
pbstrExternalLocalAddress: ?*?BSTR,
plExternalLocalPort: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UpdateRemoteAddress: fn(
self: *const IRTCPortManager,
bstrRemoteAddress: ?BSTR,
bstrInternalLocalAddress: ?BSTR,
lInternalLocalPort: i32,
bstrExternalLocalAddress: ?BSTR,
lExternalLocalPort: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ReleaseMapping: fn(
self: *const IRTCPortManager,
bstrInternalLocalAddress: ?BSTR,
lInternalLocalPort: i32,
bstrExternalLocalAddress: ?BSTR,
lExternalLocalAddress: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCPortManager_GetMapping(self: *const T, bstrRemoteAddress: ?BSTR, enPortType: RTC_PORT_TYPE, pbstrInternalLocalAddress: ?*?BSTR, plInternalLocalPort: ?*i32, pbstrExternalLocalAddress: ?*?BSTR, plExternalLocalPort: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCPortManager.VTable, self.vtable).GetMapping(@ptrCast(*const IRTCPortManager, self), bstrRemoteAddress, enPortType, pbstrInternalLocalAddress, plInternalLocalPort, pbstrExternalLocalAddress, plExternalLocalPort);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCPortManager_UpdateRemoteAddress(self: *const T, bstrRemoteAddress: ?BSTR, bstrInternalLocalAddress: ?BSTR, lInternalLocalPort: i32, bstrExternalLocalAddress: ?BSTR, lExternalLocalPort: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCPortManager.VTable, self.vtable).UpdateRemoteAddress(@ptrCast(*const IRTCPortManager, self), bstrRemoteAddress, bstrInternalLocalAddress, lInternalLocalPort, bstrExternalLocalAddress, lExternalLocalPort);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCPortManager_ReleaseMapping(self: *const T, bstrInternalLocalAddress: ?BSTR, lInternalLocalPort: i32, bstrExternalLocalAddress: ?BSTR, lExternalLocalAddress: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCPortManager.VTable, self.vtable).ReleaseMapping(@ptrCast(*const IRTCPortManager, self), bstrInternalLocalAddress, lInternalLocalPort, bstrExternalLocalAddress, lExternalLocalAddress);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCSessionPortManagement_Value = @import("../zig.zig").Guid.initString("a072f1d6-0286-4e1f-85f2-17a2948456ec");
pub const IID_IRTCSessionPortManagement = &IID_IRTCSessionPortManagement_Value;
pub const IRTCSessionPortManagement = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetPortManager: fn(
self: *const IRTCSessionPortManagement,
pPortManager: ?*IRTCPortManager,
) 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 IRTCSessionPortManagement_SetPortManager(self: *const T, pPortManager: ?*IRTCPortManager) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionPortManagement.VTable, self.vtable).SetPortManager(@ptrCast(*const IRTCSessionPortManagement, self), pPortManager);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCClientPortManagement_Value = @import("../zig.zig").Guid.initString("d5df3f03-4bde-4417-aefe-71177bdaea66");
pub const IID_IRTCClientPortManagement = &IID_IRTCClientPortManagement_Value;
pub const IRTCClientPortManagement = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
StartListenAddressAndPort: fn(
self: *const IRTCClientPortManagement,
bstrInternalLocalAddress: ?BSTR,
lInternalLocalPort: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
StopListenAddressAndPort: fn(
self: *const IRTCClientPortManagement,
bstrInternalLocalAddress: ?BSTR,
lInternalLocalPort: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPortRange: fn(
self: *const IRTCClientPortManagement,
enPortType: RTC_PORT_TYPE,
plMinValue: ?*i32,
plMaxValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPortManagement_StartListenAddressAndPort(self: *const T, bstrInternalLocalAddress: ?BSTR, lInternalLocalPort: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPortManagement.VTable, self.vtable).StartListenAddressAndPort(@ptrCast(*const IRTCClientPortManagement, self), bstrInternalLocalAddress, lInternalLocalPort);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPortManagement_StopListenAddressAndPort(self: *const T, bstrInternalLocalAddress: ?BSTR, lInternalLocalPort: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPortManagement.VTable, self.vtable).StopListenAddressAndPort(@ptrCast(*const IRTCClientPortManagement, self), bstrInternalLocalAddress, lInternalLocalPort);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCClientPortManagement_GetPortRange(self: *const T, enPortType: RTC_PORT_TYPE, plMinValue: ?*i32, plMaxValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCClientPortManagement.VTable, self.vtable).GetPortRange(@ptrCast(*const IRTCClientPortManagement, self), enPortType, plMinValue, plMaxValue);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCUserSearch_Value = @import("../zig.zig").Guid.initString("b619882b-860c-4db4-be1b-693b6505bbe5");
pub const IID_IRTCUserSearch = &IID_IRTCUserSearch_Value;
pub const IRTCUserSearch = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
CreateQuery: fn(
self: *const IRTCUserSearch,
ppQuery: ?*?*IRTCUserSearchQuery,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ExecuteSearch: fn(
self: *const IRTCUserSearch,
pQuery: ?*IRTCUserSearchQuery,
pProfile: ?*IRTCProfile,
lCookie: isize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCUserSearch_CreateQuery(self: *const T, ppQuery: ?*?*IRTCUserSearchQuery) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCUserSearch.VTable, self.vtable).CreateQuery(@ptrCast(*const IRTCUserSearch, self), ppQuery);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCUserSearch_ExecuteSearch(self: *const T, pQuery: ?*IRTCUserSearchQuery, pProfile: ?*IRTCProfile, lCookie: isize) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCUserSearch.VTable, self.vtable).ExecuteSearch(@ptrCast(*const IRTCUserSearch, self), pQuery, pProfile, lCookie);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCUserSearchQuery_Value = @import("../zig.zig").Guid.initString("288300f5-d23a-4365-9a73-9985c98c2881");
pub const IID_IRTCUserSearchQuery = &IID_IRTCUserSearchQuery_Value;
pub const IRTCUserSearchQuery = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_SearchTerm: fn(
self: *const IRTCUserSearchQuery,
bstrName: ?BSTR,
bstrValue: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_SearchTerm: fn(
self: *const IRTCUserSearchQuery,
bstrName: ?BSTR,
pbstrValue: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_SearchTerms: fn(
self: *const IRTCUserSearchQuery,
pbstrNames: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_SearchPreference: fn(
self: *const IRTCUserSearchQuery,
enPreference: RTC_USER_SEARCH_PREFERENCE,
lValue: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_SearchPreference: fn(
self: *const IRTCUserSearchQuery,
enPreference: RTC_USER_SEARCH_PREFERENCE,
plValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_SearchDomain: fn(
self: *const IRTCUserSearchQuery,
bstrDomain: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_SearchDomain: fn(
self: *const IRTCUserSearchQuery,
pbstrDomain: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCUserSearchQuery_put_SearchTerm(self: *const T, bstrName: ?BSTR, bstrValue: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCUserSearchQuery.VTable, self.vtable).put_SearchTerm(@ptrCast(*const IRTCUserSearchQuery, self), bstrName, bstrValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCUserSearchQuery_get_SearchTerm(self: *const T, bstrName: ?BSTR, pbstrValue: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCUserSearchQuery.VTable, self.vtable).get_SearchTerm(@ptrCast(*const IRTCUserSearchQuery, self), bstrName, pbstrValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCUserSearchQuery_get_SearchTerms(self: *const T, pbstrNames: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCUserSearchQuery.VTable, self.vtable).get_SearchTerms(@ptrCast(*const IRTCUserSearchQuery, self), pbstrNames);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCUserSearchQuery_put_SearchPreference(self: *const T, enPreference: RTC_USER_SEARCH_PREFERENCE, lValue: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCUserSearchQuery.VTable, self.vtable).put_SearchPreference(@ptrCast(*const IRTCUserSearchQuery, self), enPreference, lValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCUserSearchQuery_get_SearchPreference(self: *const T, enPreference: RTC_USER_SEARCH_PREFERENCE, plValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCUserSearchQuery.VTable, self.vtable).get_SearchPreference(@ptrCast(*const IRTCUserSearchQuery, self), enPreference, plValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCUserSearchQuery_put_SearchDomain(self: *const T, bstrDomain: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCUserSearchQuery.VTable, self.vtable).put_SearchDomain(@ptrCast(*const IRTCUserSearchQuery, self), bstrDomain);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCUserSearchQuery_get_SearchDomain(self: *const T, pbstrDomain: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCUserSearchQuery.VTable, self.vtable).get_SearchDomain(@ptrCast(*const IRTCUserSearchQuery, self), pbstrDomain);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCUserSearchResult_Value = @import("../zig.zig").Guid.initString("851278b2-9592-480f-8db5-2de86b26b54d");
pub const IID_IRTCUserSearchResult = &IID_IRTCUserSearchResult_Value;
pub const IRTCUserSearchResult = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Value: fn(
self: *const IRTCUserSearchResult,
enColumn: RTC_USER_SEARCH_COLUMN,
pbstrValue: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCUserSearchResult_get_Value(self: *const T, enColumn: RTC_USER_SEARCH_COLUMN, pbstrValue: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCUserSearchResult.VTable, self.vtable).get_Value(@ptrCast(*const IRTCUserSearchResult, self), enColumn, pbstrValue);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCEnumUserSearchResults_Value = @import("../zig.zig").Guid.initString("83d4d877-aa5d-4a5b-8d0e-002a8067e0e8");
pub const IID_IRTCEnumUserSearchResults = &IID_IRTCEnumUserSearchResults_Value;
pub const IRTCEnumUserSearchResults = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Next: fn(
self: *const IRTCEnumUserSearchResults,
celt: u32,
ppElements: [*]?*IRTCUserSearchResult,
pceltFetched: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reset: fn(
self: *const IRTCEnumUserSearchResults,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Skip: fn(
self: *const IRTCEnumUserSearchResults,
celt: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clone: fn(
self: *const IRTCEnumUserSearchResults,
ppEnum: ?*?*IRTCEnumUserSearchResults,
) 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 IRTCEnumUserSearchResults_Next(self: *const T, celt: u32, ppElements: [*]?*IRTCUserSearchResult, pceltFetched: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCEnumUserSearchResults.VTable, self.vtable).Next(@ptrCast(*const IRTCEnumUserSearchResults, self), celt, ppElements, pceltFetched);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCEnumUserSearchResults_Reset(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCEnumUserSearchResults.VTable, self.vtable).Reset(@ptrCast(*const IRTCEnumUserSearchResults, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCEnumUserSearchResults_Skip(self: *const T, celt: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCEnumUserSearchResults.VTable, self.vtable).Skip(@ptrCast(*const IRTCEnumUserSearchResults, self), celt);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCEnumUserSearchResults_Clone(self: *const T, ppEnum: ?*?*IRTCEnumUserSearchResults) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCEnumUserSearchResults.VTable, self.vtable).Clone(@ptrCast(*const IRTCEnumUserSearchResults, self), ppEnum);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCUserSearchResultsEvent_Value = @import("../zig.zig").Guid.initString("d8c8c3cd-7fac-4088-81c5-c24cbc0938e3");
pub const IID_IRTCUserSearchResultsEvent = &IID_IRTCUserSearchResultsEvent_Value;
pub const IRTCUserSearchResultsEvent = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
EnumerateResults: fn(
self: *const IRTCUserSearchResultsEvent,
ppEnum: ?*?*IRTCEnumUserSearchResults,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Results: fn(
self: *const IRTCUserSearchResultsEvent,
ppCollection: ?*?*IRTCCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Profile: fn(
self: *const IRTCUserSearchResultsEvent,
ppProfile: ?*?*IRTCProfile2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Query: fn(
self: *const IRTCUserSearchResultsEvent,
ppQuery: ?*?*IRTCUserSearchQuery,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Cookie: fn(
self: *const IRTCUserSearchResultsEvent,
plCookie: ?*isize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_StatusCode: fn(
self: *const IRTCUserSearchResultsEvent,
plStatusCode: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_MoreAvailable: fn(
self: *const IRTCUserSearchResultsEvent,
pfMoreAvailable: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCUserSearchResultsEvent_EnumerateResults(self: *const T, ppEnum: ?*?*IRTCEnumUserSearchResults) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCUserSearchResultsEvent.VTable, self.vtable).EnumerateResults(@ptrCast(*const IRTCUserSearchResultsEvent, self), ppEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCUserSearchResultsEvent_get_Results(self: *const T, ppCollection: ?*?*IRTCCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCUserSearchResultsEvent.VTable, self.vtable).get_Results(@ptrCast(*const IRTCUserSearchResultsEvent, self), ppCollection);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCUserSearchResultsEvent_get_Profile(self: *const T, ppProfile: ?*?*IRTCProfile2) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCUserSearchResultsEvent.VTable, self.vtable).get_Profile(@ptrCast(*const IRTCUserSearchResultsEvent, self), ppProfile);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCUserSearchResultsEvent_get_Query(self: *const T, ppQuery: ?*?*IRTCUserSearchQuery) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCUserSearchResultsEvent.VTable, self.vtable).get_Query(@ptrCast(*const IRTCUserSearchResultsEvent, self), ppQuery);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCUserSearchResultsEvent_get_Cookie(self: *const T, plCookie: ?*isize) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCUserSearchResultsEvent.VTable, self.vtable).get_Cookie(@ptrCast(*const IRTCUserSearchResultsEvent, self), plCookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCUserSearchResultsEvent_get_StatusCode(self: *const T, plStatusCode: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCUserSearchResultsEvent.VTable, self.vtable).get_StatusCode(@ptrCast(*const IRTCUserSearchResultsEvent, self), plStatusCode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCUserSearchResultsEvent_get_MoreAvailable(self: *const T, pfMoreAvailable: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCUserSearchResultsEvent.VTable, self.vtable).get_MoreAvailable(@ptrCast(*const IRTCUserSearchResultsEvent, self), pfMoreAvailable);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCSessionReferStatusEvent_Value = @import("../zig.zig").Guid.initString("3d8fc2cd-5d76-44ab-bb68-2a80353b34a2");
pub const IID_IRTCSessionReferStatusEvent = &IID_IRTCSessionReferStatusEvent_Value;
pub const IRTCSessionReferStatusEvent = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Session: fn(
self: *const IRTCSessionReferStatusEvent,
ppSession: ?*?*IRTCSession2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ReferStatus: fn(
self: *const IRTCSessionReferStatusEvent,
penReferStatus: ?*RTC_SESSION_REFER_STATUS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_StatusCode: fn(
self: *const IRTCSessionReferStatusEvent,
plStatusCode: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_StatusText: fn(
self: *const IRTCSessionReferStatusEvent,
pbstrStatusText: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionReferStatusEvent_get_Session(self: *const T, ppSession: ?*?*IRTCSession2) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionReferStatusEvent.VTable, self.vtable).get_Session(@ptrCast(*const IRTCSessionReferStatusEvent, self), ppSession);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionReferStatusEvent_get_ReferStatus(self: *const T, penReferStatus: ?*RTC_SESSION_REFER_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionReferStatusEvent.VTable, self.vtable).get_ReferStatus(@ptrCast(*const IRTCSessionReferStatusEvent, self), penReferStatus);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionReferStatusEvent_get_StatusCode(self: *const T, plStatusCode: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionReferStatusEvent.VTable, self.vtable).get_StatusCode(@ptrCast(*const IRTCSessionReferStatusEvent, self), plStatusCode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionReferStatusEvent_get_StatusText(self: *const T, pbstrStatusText: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionReferStatusEvent.VTable, self.vtable).get_StatusText(@ptrCast(*const IRTCSessionReferStatusEvent, self), pbstrStatusText);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCSessionReferredEvent_Value = @import("../zig.zig").Guid.initString("176a6828-4fcc-4f28-a862-04597a6cf1c4");
pub const IID_IRTCSessionReferredEvent = &IID_IRTCSessionReferredEvent_Value;
pub const IRTCSessionReferredEvent = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Session: fn(
self: *const IRTCSessionReferredEvent,
ppSession: ?*?*IRTCSession2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ReferredByURI: fn(
self: *const IRTCSessionReferredEvent,
pbstrReferredByURI: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ReferToURI: fn(
self: *const IRTCSessionReferredEvent,
pbstrReferoURI: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ReferCookie: fn(
self: *const IRTCSessionReferredEvent,
pbstrReferCookie: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Accept: fn(
self: *const IRTCSessionReferredEvent,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reject: fn(
self: *const IRTCSessionReferredEvent,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetReferredSessionState: fn(
self: *const IRTCSessionReferredEvent,
enState: RTC_SESSION_STATE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionReferredEvent_get_Session(self: *const T, ppSession: ?*?*IRTCSession2) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionReferredEvent.VTable, self.vtable).get_Session(@ptrCast(*const IRTCSessionReferredEvent, self), ppSession);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionReferredEvent_get_ReferredByURI(self: *const T, pbstrReferredByURI: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionReferredEvent.VTable, self.vtable).get_ReferredByURI(@ptrCast(*const IRTCSessionReferredEvent, self), pbstrReferredByURI);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionReferredEvent_get_ReferToURI(self: *const T, pbstrReferoURI: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionReferredEvent.VTable, self.vtable).get_ReferToURI(@ptrCast(*const IRTCSessionReferredEvent, self), pbstrReferoURI);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionReferredEvent_get_ReferCookie(self: *const T, pbstrReferCookie: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionReferredEvent.VTable, self.vtable).get_ReferCookie(@ptrCast(*const IRTCSessionReferredEvent, self), pbstrReferCookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionReferredEvent_Accept(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionReferredEvent.VTable, self.vtable).Accept(@ptrCast(*const IRTCSessionReferredEvent, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionReferredEvent_Reject(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionReferredEvent.VTable, self.vtable).Reject(@ptrCast(*const IRTCSessionReferredEvent, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionReferredEvent_SetReferredSessionState(self: *const T, enState: RTC_SESSION_STATE) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionReferredEvent.VTable, self.vtable).SetReferredSessionState(@ptrCast(*const IRTCSessionReferredEvent, self), enState);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCSessionDescriptionManager_Value = @import("../zig.zig").Guid.initString("ba7f518e-d336-4070-93a6-865395c843f9");
pub const IID_IRTCSessionDescriptionManager = &IID_IRTCSessionDescriptionManager_Value;
pub const IRTCSessionDescriptionManager = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
EvaluateSessionDescription: fn(
self: *const IRTCSessionDescriptionManager,
bstrContentType: ?BSTR,
bstrSessionDescription: ?BSTR,
pfApplicationSession: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCSessionDescriptionManager_EvaluateSessionDescription(self: *const T, bstrContentType: ?BSTR, bstrSessionDescription: ?BSTR, pfApplicationSession: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCSessionDescriptionManager.VTable, self.vtable).EvaluateSessionDescription(@ptrCast(*const IRTCSessionDescriptionManager, self), bstrContentType, bstrSessionDescription, pfApplicationSession);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCEnumPresenceDevices_Value = @import("../zig.zig").Guid.initString("708c2ab7-8bf8-42f8-8c7d-635197ad5539");
pub const IID_IRTCEnumPresenceDevices = &IID_IRTCEnumPresenceDevices_Value;
pub const IRTCEnumPresenceDevices = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Next: fn(
self: *const IRTCEnumPresenceDevices,
celt: u32,
ppElements: [*]?*IRTCPresenceDevice,
pceltFetched: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reset: fn(
self: *const IRTCEnumPresenceDevices,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Skip: fn(
self: *const IRTCEnumPresenceDevices,
celt: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clone: fn(
self: *const IRTCEnumPresenceDevices,
ppEnum: ?*?*IRTCEnumPresenceDevices,
) 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 IRTCEnumPresenceDevices_Next(self: *const T, celt: u32, ppElements: [*]?*IRTCPresenceDevice, pceltFetched: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCEnumPresenceDevices.VTable, self.vtable).Next(@ptrCast(*const IRTCEnumPresenceDevices, self), celt, ppElements, pceltFetched);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCEnumPresenceDevices_Reset(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCEnumPresenceDevices.VTable, self.vtable).Reset(@ptrCast(*const IRTCEnumPresenceDevices, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCEnumPresenceDevices_Skip(self: *const T, celt: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCEnumPresenceDevices.VTable, self.vtable).Skip(@ptrCast(*const IRTCEnumPresenceDevices, self), celt);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCEnumPresenceDevices_Clone(self: *const T, ppEnum: ?*?*IRTCEnumPresenceDevices) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCEnumPresenceDevices.VTable, self.vtable).Clone(@ptrCast(*const IRTCEnumPresenceDevices, self), ppEnum);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCPresenceDevice_Value = @import("../zig.zig").Guid.initString("bc6a90dd-ad9a-48da-9b0c-2515e38521ad");
pub const IID_IRTCPresenceDevice = &IID_IRTCPresenceDevice_Value;
pub const IRTCPresenceDevice = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Status: fn(
self: *const IRTCPresenceDevice,
penStatus: ?*RTC_PRESENCE_STATUS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Notes: fn(
self: *const IRTCPresenceDevice,
pbstrNotes: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_PresenceProperty: fn(
self: *const IRTCPresenceDevice,
enProperty: RTC_PRESENCE_PROPERTY,
pbstrProperty: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPresenceData: fn(
self: *const IRTCPresenceDevice,
pbstrNamespace: ?*?BSTR,
pbstrData: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCPresenceDevice_get_Status(self: *const T, penStatus: ?*RTC_PRESENCE_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCPresenceDevice.VTable, self.vtable).get_Status(@ptrCast(*const IRTCPresenceDevice, self), penStatus);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCPresenceDevice_get_Notes(self: *const T, pbstrNotes: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCPresenceDevice.VTable, self.vtable).get_Notes(@ptrCast(*const IRTCPresenceDevice, self), pbstrNotes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCPresenceDevice_get_PresenceProperty(self: *const T, enProperty: RTC_PRESENCE_PROPERTY, pbstrProperty: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCPresenceDevice.VTable, self.vtable).get_PresenceProperty(@ptrCast(*const IRTCPresenceDevice, self), enProperty, pbstrProperty);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRTCPresenceDevice_GetPresenceData(self: *const T, pbstrNamespace: ?*?BSTR, pbstrData: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IRTCPresenceDevice.VTable, self.vtable).GetPresenceData(@ptrCast(*const IRTCPresenceDevice, self), pbstrNamespace, pbstrData);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRTCDispatchEventNotification_Value = @import("../zig.zig").Guid.initString("176ddfbe-fec0-4d55-bc87-84cff1ef7f91");
pub const IID_IRTCDispatchEventNotification = &IID_IRTCDispatchEventNotification_Value;
pub const IRTCDispatchEventNotification = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
};}
pub usingnamespace MethodMixin(@This());
};
pub const TRANSPORT_SETTING = extern struct {
SettingId: TRANSPORT_SETTING_ID,
Length: ?*u32,
Value: ?*u8,
};
const IID_ITransportSettingsInternal_Value = @import("../zig.zig").Guid.initString("5123e076-29e3-4bfd-84fe-0192d411e3e8");
pub const IID_ITransportSettingsInternal = &IID_ITransportSettingsInternal_Value;
pub const ITransportSettingsInternal = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
ApplySetting: fn(
self: *const ITransportSettingsInternal,
Setting: ?*TRANSPORT_SETTING,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QuerySetting: fn(
self: *const ITransportSettingsInternal,
Setting: ?*TRANSPORT_SETTING,
) 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 ITransportSettingsInternal_ApplySetting(self: *const T, Setting: ?*TRANSPORT_SETTING) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransportSettingsInternal.VTable, self.vtable).ApplySetting(@ptrCast(*const ITransportSettingsInternal, self), Setting);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransportSettingsInternal_QuerySetting(self: *const T, Setting: ?*TRANSPORT_SETTING) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransportSettingsInternal.VTable, self.vtable).QuerySetting(@ptrCast(*const ITransportSettingsInternal, self), Setting);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_INetworkTransportSettings_Value = @import("../zig.zig").Guid.initString("5e7abb2c-f2c1-4a61-bd35-deb7a08ab0f1");
pub const IID_INetworkTransportSettings = &IID_INetworkTransportSettings_Value;
pub const INetworkTransportSettings = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
ApplySetting: fn(
self: *const INetworkTransportSettings,
SettingId: ?*const TRANSPORT_SETTING_ID,
LengthIn: u32,
ValueIn: [*:0]const u8,
LengthOut: ?*u32,
ValueOut: [*]?*u8,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QuerySetting: fn(
self: *const INetworkTransportSettings,
SettingId: ?*const TRANSPORT_SETTING_ID,
LengthIn: u32,
ValueIn: [*:0]const u8,
LengthOut: ?*u32,
ValueOut: [*]?*u8,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkTransportSettings_ApplySetting(self: *const T, SettingId: ?*const TRANSPORT_SETTING_ID, LengthIn: u32, ValueIn: [*:0]const u8, LengthOut: ?*u32, ValueOut: [*]?*u8) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkTransportSettings.VTable, self.vtable).ApplySetting(@ptrCast(*const INetworkTransportSettings, self), SettingId, LengthIn, ValueIn, LengthOut, ValueOut);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetworkTransportSettings_QuerySetting(self: *const T, SettingId: ?*const TRANSPORT_SETTING_ID, LengthIn: u32, ValueIn: [*:0]const u8, LengthOut: ?*u32, ValueOut: [*]?*u8) callconv(.Inline) HRESULT {
return @ptrCast(*const INetworkTransportSettings.VTable, self.vtable).QuerySetting(@ptrCast(*const INetworkTransportSettings, self), SettingId, LengthIn, ValueIn, LengthOut, ValueOut);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_INotificationTransportSync_Value = @import("../zig.zig").Guid.initString("79eb1402-0ab8-49c0-9e14-a1ae4ba93058");
pub const IID_INotificationTransportSync = &IID_INotificationTransportSync_Value;
pub const INotificationTransportSync = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
CompleteDelivery: fn(
self: *const INotificationTransportSync,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Flush: fn(
self: *const INotificationTransportSync,
) 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 INotificationTransportSync_CompleteDelivery(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const INotificationTransportSync.VTable, self.vtable).CompleteDelivery(@ptrCast(*const INotificationTransportSync, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INotificationTransportSync_Flush(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const INotificationTransportSync.VTable, self.vtable).Flush(@ptrCast(*const INotificationTransportSync, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
//--------------------------------------------------------------------------------
// Section: Functions (0)
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (0)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../zig.zig").unicode_mode) {
.ansi => struct {
},
.wide => struct {
},
.unspecified => if (@import("builtin").is_test) struct {
} else struct {
},
};
//--------------------------------------------------------------------------------
// Section: Imports (7)
//--------------------------------------------------------------------------------
const BSTR = @import("../foundation.zig").BSTR;
const HRESULT = @import("../foundation.zig").HRESULT;
const IDispatch = @import("../system/com.zig").IDispatch;
const IUnknown = @import("../system/com.zig").IUnknown;
const IVideoWindow = @import("../media/direct_show.zig").IVideoWindow;
const TRANSPORT_SETTING_ID = @import("../networking/win_sock.zig").TRANSPORT_SETTING_ID;
const VARIANT = @import("../system/com.zig").VARIANT;
test {
@setEvalBranchQuota(
@import("std").meta.declarations(@This()).len * 3
);
// reference all the pub declarations
if (!@import("builtin").is_test) return;
inline for (@import("std").meta.declarations(@This())) |decl| {
if (decl.is_pub) {
_ = decl;
}
}
} | win32/system/real_time_communications.zig |
const std = @import("std");
const TestContext = @import("../../src/test.zig").TestContext;
// These tests should work with all platforms, but we're using linux_x64 for
// now for consistency. Will be expanded eventually.
const linux_x64 = std.zig.CrossTarget{
.cpu_arch = .x86_64,
.os_tag = .linux,
};
pub fn addCases(ctx: *TestContext) !void {
ctx.c("empty start function", linux_x64,
\\export fn _start() noreturn {
\\ unreachable;
\\}
,
\\zig_noreturn void _start(void) {
\\ zig_unreachable();
\\}
\\
);
ctx.c("less empty start function", linux_x64,
\\fn main() noreturn {
\\ unreachable;
\\}
\\
\\export fn _start() noreturn {
\\ main();
\\}
,
\\zig_noreturn void main(void);
\\
\\zig_noreturn void _start(void) {
\\ main();
\\}
\\
\\zig_noreturn void main(void) {
\\ zig_unreachable();
\\}
\\
);
// TODO: implement return values
// TODO: figure out a way to prevent asm constants from being generated
ctx.c("inline asm", linux_x64,
\\fn exitGood() noreturn {
\\ asm volatile ("syscall"
\\ :
\\ : [number] "{rax}" (231),
\\ [arg1] "{rdi}" (0)
\\ );
\\ unreachable;
\\}
\\
\\export fn _start() noreturn {
\\ exitGood();
\\}
,
\\#include <stddef.h>
\\
\\zig_noreturn void exitGood(void);
\\
\\const char *const exitGood__anon_0 = "{rax}";
\\const char *const exitGood__anon_1 = "{rdi}";
\\const char *const exitGood__anon_2 = "syscall";
\\
\\zig_noreturn void _start(void) {
\\ exitGood();
\\}
\\
\\zig_noreturn void exitGood(void) {
\\ register size_t rax_constant __asm__("rax") = 231;
\\ register size_t rdi_constant __asm__("rdi") = 0;
\\ __asm volatile ("syscall" :: ""(rax_constant), ""(rdi_constant));
\\ zig_unreachable();
\\}
\\
);
ctx.c("exit with parameter", linux_x64,
\\export fn _start() noreturn {
\\ exit(0);
\\}
\\
\\fn exit(code: usize) noreturn {
\\ asm volatile ("syscall"
\\ :
\\ : [number] "{rax}" (231),
\\ [arg1] "{rdi}" (code)
\\ );
\\ unreachable;
\\}
\\
,
\\#include <stddef.h>
\\
\\zig_noreturn void exit(size_t arg0);
\\
\\const char *const exit__anon_0 = "{rax}";
\\const char *const exit__anon_1 = "{rdi}";
\\const char *const exit__anon_2 = "syscall";
\\
\\zig_noreturn void _start(void) {
\\ exit(0);
\\}
\\
\\zig_noreturn void exit(size_t arg0) {
\\ register size_t rax_constant __asm__("rax") = 231;
\\ register size_t rdi_constant __asm__("rdi") = arg0;
\\ __asm volatile ("syscall" :: ""(rax_constant), ""(rdi_constant));
\\ zig_unreachable();
\\}
\\
);
ctx.c("exit with u8 parameter", linux_x64,
\\export fn _start() noreturn {
\\ exit(0);
\\}
\\
\\fn exit(code: u8) noreturn {
\\ asm volatile ("syscall"
\\ :
\\ : [number] "{rax}" (231),
\\ [arg1] "{rdi}" (code)
\\ );
\\ unreachable;
\\}
\\
,
\\#include <stddef.h>
\\#include <stdint.h>
\\
\\zig_noreturn void exit(uint8_t arg0);
\\
\\const char *const exit__anon_0 = "{rax}";
\\const char *const exit__anon_1 = "{rdi}";
\\const char *const exit__anon_2 = "syscall";
\\
\\zig_noreturn void _start(void) {
\\ exit(0);
\\}
\\
\\zig_noreturn void exit(uint8_t arg0) {
\\ const size_t __temp_0 = (size_t)arg0;
\\ register size_t rax_constant __asm__("rax") = 231;
\\ register size_t rdi_constant __asm__("rdi") = __temp_0;
\\ __asm volatile ("syscall" :: ""(rax_constant), ""(rdi_constant));
\\ zig_unreachable();
\\}
\\
);
} | test/stage2/cbe.zig |
// types
const Starship = struct {
name: []const u8,
number: u32,
captain: []const u8 = "?",
};
pub fn main() !void {
const file_name = std.fs.path.basename(@src().file);
print("\n file: {}\n", .{file_name});
}
test "AutoHashMap" {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var allocator = &gpa.allocator;
defer if (gpa.deinit()) std.os.exit(1);
var map = std.AutoHashMap(u32, Starship).init(allocator);
defer map.deinit();
try map.put(1701, Starship{
.name = "Enterprise",
.number = 1701,
});
try map.put(24383, Starship{
.name = "Yamato",
.number = 24383,
});
try map.put(1022, Starship{
.name = "<NAME>",
.number = 1022,
});
print("map.count()={}\n", .{map.count()});
expect(map.count() == 3);
var it = map.iterator();
while (it.next()) |entry| {
print("key={}, value={}\n", .{ entry.key, entry.value });
}
}
test "StringHashMap" {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var allocator = &gpa.allocator;
defer if (gpa.deinit()) std.os.exit(1);
var map = std.StringHashMap(Starship).init(allocator);
defer map.deinit();
try map.put("NX-01", Starship{
.name = "Enterprise",
.number = 1,
.captain = "Archer",
});
try map.put("NCC-1701", Starship{
.name = "Enterprise",
.number = 1701,
.captain = "Kirk",
});
try map.put("NCC-1701-A", Starship{
.name = "Enterprise",
.number = 1701,
.captain = "Kirk",
});
try map.put("NCC-1701-B", Starship{
.name = "Enterprise",
.number = 1701,
.captain = "Harriman",
});
try map.put("NCC-1701-C", Starship{
.name = "Enterprise",
.number = 1701,
.captain = "Garret",
});
try map.put("NCC-1701-D", Starship{
.name = "Enterprise",
.number = 1701,
.captain = "Picard",
});
print("map.count()={}\n", .{map.count()});
expect(map.count() == 6);
var it = map.iterator();
while (it.next()) |entry| {
print("key={}, value={}\n", .{ entry.key, entry.value });
}
const old = try map.fetchPut("NCC-1701-D", Starship{
.name = "Enterprise",
.number = 1701,
.captain = "Riker",
});
expect(eql(u8, old.?.value.captain, "Picard"));
}
// imports
const std = @import("std");
const print = std.debug.print;
const expect = std.testing.expect;
const eql = std.mem.eql; | 12_hash_maps.zig |
const std = @import("std");
const registry = @import("registry.zig");
const xml = @import("../xml.zig");
const mem = std.mem;
const Allocator = mem.Allocator;
const testing = std.testing;
const ArraySize = registry.Array.ArraySize;
const TypeInfo = registry.TypeInfo;
pub const Token = struct {
kind: Kind,
text: []const u8,
const Kind = enum {
id, // Any id thats not a keyword
name, // OpenXR <name>...</name>
type_name, // OpenXR <type>...</type>
enum_name, // OpenXR <enum>...</enum>
int,
star,
comma,
semicolon,
colon,
minus,
tilde,
dot,
hash,
lparen,
rparen,
lbracket,
rbracket,
kw_typedef,
kw_const,
kw_xrapi_ptr,
kw_struct,
};
};
pub const CTokenizer = struct {
source: []const u8,
offset: usize = 0,
in_comment: bool = false,
fn peek(self: CTokenizer) ?u8 {
return if (self.offset < self.source.len) self.source[self.offset] else null;
}
fn consumeNoEof(self: *CTokenizer) u8 {
const c = self.peek().?;
self.offset += 1;
return c;
}
fn consume(self: *CTokenizer) !u8 {
return if (self.offset < self.source.len)
return self.consumeNoEof()
else
return null;
}
fn keyword(self: *CTokenizer) Token {
const start = self.offset;
_ = self.consumeNoEof();
while (true) {
const c = self.peek() orelse break;
switch (c) {
'A'...'Z', 'a'...'z', '_', '0'...'9' => _ = self.consumeNoEof(),
else => break,
}
}
const token_text = self.source[start..self.offset];
const kind = if (mem.eql(u8, token_text, "typedef"))
Token.Kind.kw_typedef
else if (mem.eql(u8, token_text, "const"))
Token.Kind.kw_const
else if (mem.eql(u8, token_text, "XRAPI_PTR"))
Token.Kind.kw_xrapi_ptr
else if (mem.eql(u8, token_text, "struct"))
Token.Kind.kw_struct
else
Token.Kind.id;
return .{ .kind = kind, .text = token_text };
}
fn int(self: *CTokenizer) Token {
const start = self.offset;
_ = self.consumeNoEof();
while (true) {
const c = self.peek() orelse break;
switch (c) {
'0'...'9' => _ = self.consumeNoEof(),
else => break,
}
}
return .{
.kind = .int,
.text = self.source[start..self.offset],
};
}
fn skipws(self: *CTokenizer) void {
while (true) {
switch (self.peek() orelse break) {
' ', '\t', '\n', '\r' => _ = self.consumeNoEof(),
else => break,
}
}
}
pub fn next(self: *CTokenizer) !?Token {
self.skipws();
if (mem.startsWith(u8, self.source[self.offset..], "//") or self.in_comment) {
const end = mem.indexOfScalarPos(u8, self.source, self.offset, '\n') orelse {
self.offset = self.source.len;
self.in_comment = true;
return null;
};
self.in_comment = false;
self.offset = end + 1;
}
self.skipws();
const c = self.peek() orelse return null;
var kind: Token.Kind = undefined;
switch (c) {
'A'...'Z', 'a'...'z', '_' => return self.keyword(),
'0'...'9' => return self.int(),
'*' => kind = .star,
',' => kind = .comma,
';' => kind = .semicolon,
':' => kind = .colon,
'-' => kind = .minus,
'~' => kind = .tilde,
'.' => kind = .dot,
'#' => kind = .hash,
'[' => kind = .lbracket,
']' => kind = .rbracket,
'(' => kind = .lparen,
')' => kind = .rparen,
else => return error.UnexpectedCharacter,
}
const start = self.offset;
_ = self.consumeNoEof();
return Token{
.kind = kind,
.text = self.source[start..self.offset],
};
}
};
pub const XmlCTokenizer = struct {
it: xml.Element.ChildIterator,
ctok: ?CTokenizer = null,
current: ?Token = null,
pub fn init(elem: *xml.Element) XmlCTokenizer {
return .{
.it = elem.iterator(),
};
}
fn elemToToken(elem: *xml.Element) !?Token {
if (elem.children.items.len != 1 or elem.children.items[0] != .CharData) {
return error.InvalidXml;
}
const text = elem.children.items[0].CharData;
if (mem.eql(u8, elem.tag, "type")) {
return Token{ .kind = .type_name, .text = text };
} else if (mem.eql(u8, elem.tag, "enum")) {
return Token{ .kind = .enum_name, .text = text };
} else if (mem.eql(u8, elem.tag, "name")) {
return Token{ .kind = .name, .text = text };
} else if (mem.eql(u8, elem.tag, "comment")) {
return null;
} else {
return error.InvalidTag;
}
}
fn next(self: *XmlCTokenizer) !?Token {
if (self.current) |current| {
const token = current;
self.current = null;
return token;
}
var in_comment: bool = false;
while (true) {
if (self.ctok) |*ctok| {
if (try ctok.next()) |tok| {
return tok;
}
in_comment = ctok.in_comment;
}
self.ctok = null;
if (self.it.next()) |child| {
switch (child.*) {
.CharData => |cdata| self.ctok = CTokenizer{ .source = cdata, .in_comment = in_comment },
.Comment => {}, // xml comment
.Element => |elem| if (!in_comment) if (try elemToToken(elem)) |tok| return tok,
}
} else {
return null;
}
}
}
fn nextNoEof(self: *XmlCTokenizer) !Token {
return (try self.next()) orelse return error.UnexpectedEof;
}
fn peek(self: *XmlCTokenizer) !?Token {
if (self.current) |current| {
return current;
}
self.current = try self.next();
return self.current;
}
fn peekNoEof(self: *XmlCTokenizer) !Token {
return (try self.peek()) orelse return error.UnexpectedEof;
}
fn expect(self: *XmlCTokenizer, kind: Token.Kind) !Token {
const tok = (try self.next()) orelse return error.UnexpectedEof;
if (tok.kind != kind) {
return error.UnexpectedToken;
}
return tok;
}
};
// TYPEDEF = kw_typedef DECLARATION ';'
pub fn parseTypedef(allocator: *Allocator, xctok: *XmlCTokenizer) !registry.Declaration {
const first_tok = (try xctok.next()) orelse return error.UnexpectedEof;
_ = switch (first_tok.kind) {
.kw_typedef => {
const decl = try parseDeclaration(allocator, xctok);
_ = try xctok.expect(.semicolon);
if (try xctok.peek()) |_| {
return error.InvalidSyntax;
}
return registry.Declaration{
.name = decl.name orelse return error.MissingTypeIdentifier,
.decl_type = .{ .typedef = decl.decl_type },
};
},
.type_name => {
if (!mem.eql(u8, first_tok.text, "XR_DEFINE_ATOM")) {
return error.InvalidSyntax;
}
_ = try xctok.expect(.lparen);
const name = try xctok.expect(.name);
_ = try xctok.expect(.rparen);
return registry.Declaration{
.name = name.text,
.decl_type = .{ .typedef = TypeInfo{ .name = "uint64_t" } },
};
},
else => {
std.debug.print("unexpected first token in typedef: {}\n", .{first_tok.kind});
return error.InvalidSyntax;
},
};
}
// MEMBER = DECLARATION (':' int)?
pub fn parseMember(allocator: *Allocator, xctok: *XmlCTokenizer) !registry.Container.Field {
const decl = try parseDeclaration(allocator, xctok);
var field = registry.Container.Field{
.name = decl.name orelse return error.MissingTypeIdentifier,
.field_type = decl.decl_type,
.bits = null,
.is_buffer_len = false,
};
if (try xctok.peek()) |tok| {
if (tok.kind != .colon) {
return error.InvalidSyntax;
}
_ = try xctok.nextNoEof();
const bits = try xctok.expect(.int);
field.bits = try std.fmt.parseInt(usize, bits.text, 10);
// Assume for now that there won't be any invalid C types like `char char* x : 4`.
if (try xctok.peek()) |_| {
return error.InvalidSyntax;
}
}
return field;
}
pub fn parseParamOrProto(allocator: *Allocator, xctok: *XmlCTokenizer) !registry.Declaration {
const decl = try parseDeclaration(allocator, xctok);
if (try xctok.peek()) |_| {
return error.InvalidSyntax;
}
return registry.Declaration{
.name = decl.name orelse return error.MissingTypeIdentifier,
.decl_type = .{ .typedef = decl.decl_type },
};
}
pub const Declaration = struct {
name: ?[]const u8, // Parameter names may be optional, especially in case of func(void)
decl_type: TypeInfo,
};
pub const ParseError = error{
OutOfMemory,
InvalidSyntax,
InvalidTag,
InvalidXml,
Overflow,
UnexpectedEof,
UnexpectedCharacter,
UnexpectedToken,
MissingTypeIdentifier,
};
// DECLARATION = kw_const? type_name DECLARATOR
// DECLARATOR = POINTERS (id | name)? ('[' ARRAY_DECLARATOR ']')*
// | POINTERS '(' FNPTRSUFFIX
fn parseDeclaration(allocator: *Allocator, xctok: *XmlCTokenizer) ParseError!Declaration {
// Parse declaration constness
var tok = try xctok.nextNoEof();
const inner_is_const = tok.kind == .kw_const;
if (inner_is_const) {
tok = try xctok.nextNoEof();
}
if (tok.kind == .kw_struct) {
tok = try xctok.nextNoEof();
}
// Parse type name
if (tok.kind != .type_name and tok.kind != .id) return error.InvalidSyntax;
const type_name = tok.text;
var type_info = TypeInfo{ .name = type_name };
// Parse pointers
type_info = try parsePointers(allocator, xctok, inner_is_const, type_info);
// Parse name / fn ptr
if (try parseFnPtrSuffix(allocator, xctok, type_info)) |decl| {
return decl;
}
const name = blk: {
const name_tok = (try xctok.peek()) orelse break :blk null;
if (name_tok.kind == .id or name_tok.kind == .name) {
_ = try xctok.nextNoEof();
break :blk name_tok.text;
} else {
break :blk null;
}
};
var inner_type = &type_info;
while (try parseArrayDeclarator(xctok)) |array_size| {
// Move the current inner type to a new node on the heap
const child = try allocator.create(TypeInfo);
child.* = inner_type.*;
// Re-assign the previous inner type for the array type info node
inner_type.* = .{
.array = .{
.size = array_size,
.child = child,
},
};
// update the inner_type pointer so it points to the proper
// inner type again
inner_type = child;
}
return Declaration{
.name = name,
.decl_type = type_info,
};
}
// FNPTRSUFFIX = kw_xrapi_ptr '*' name' ')' '(' ('void' | (DECLARATION (',' DECLARATION)*)?) ')'
fn parseFnPtrSuffix(allocator: *Allocator, xctok: *XmlCTokenizer, return_type: TypeInfo) !?Declaration {
const lparen = try xctok.peek();
if (lparen == null or lparen.?.kind != .lparen) {
return null;
}
_ = try xctok.nextNoEof();
_ = try xctok.expect(.kw_xrapi_ptr);
_ = try xctok.expect(.star);
const name = try xctok.expect(.name);
_ = try xctok.expect(.rparen);
_ = try xctok.expect(.lparen);
const return_type_heap = try allocator.create(TypeInfo);
return_type_heap.* = return_type;
var command_ptr = Declaration{
.name = name.text,
.decl_type = .{
.command_ptr = .{
.params = &[_]registry.Command.Param{},
.return_type = return_type_heap,
.success_codes = &[_][]const u8{},
.error_codes = &[_][]const u8{},
},
},
};
const first_param = try parseDeclaration(allocator, xctok);
if (first_param.name == null) {
if (first_param.decl_type != .name or !mem.eql(u8, first_param.decl_type.name, "void")) {
return error.InvalidSyntax;
}
_ = try xctok.expect(.rparen);
return command_ptr;
}
// There is no good way to estimate the number of parameters beforehand.
// Fortunately, there are usually a relatively low number of parameters to a function pointer,
// so an ArrayList backed by an arena allocator is good enough.
var params = std.ArrayList(registry.Command.Param).init(allocator);
try params.append(.{
.name = first_param.name.?,
.param_type = first_param.decl_type,
.is_buffer_len = false,
});
while (true) {
switch ((try xctok.peekNoEof()).kind) {
.rparen => break,
.comma => _ = try xctok.nextNoEof(),
else => return error.InvalidSyntax,
}
const decl = try parseDeclaration(allocator, xctok);
try params.append(.{
.name = decl.name orelse return error.MissingTypeIdentifier,
.param_type = decl.decl_type,
.is_buffer_len = false,
});
}
_ = try xctok.nextNoEof();
command_ptr.decl_type.command_ptr.params = params.toOwnedSlice();
return command_ptr;
}
// POINTERS = (kw_const? '*')*
fn parsePointers(allocator: *Allocator, xctok: *XmlCTokenizer, inner_const: bool, inner: TypeInfo) !TypeInfo {
var type_info = inner;
var first_const = inner_const;
while (true) {
var tok = (try xctok.peek()) orelse return type_info;
var is_const = first_const;
first_const = false;
if (tok.kind == .kw_const) {
is_const = true;
_ = try xctok.nextNoEof();
tok = (try xctok.peek()) orelse return type_info;
}
if (tok.kind != .star) {
// if `is_const` is true at this point, there was a trailing const,
// and the declaration itself is const.
return type_info;
}
_ = try xctok.nextNoEof();
const child = try allocator.create(TypeInfo);
child.* = type_info;
type_info = .{
.pointer = .{
.is_const = is_const or first_const,
.is_optional = false, // set elsewhere
.size = .one, // set elsewhere
.child = child,
},
};
}
}
// ARRAY_DECLARATOR = '[' (int | enum_name) ']'
fn parseArrayDeclarator(xctok: *XmlCTokenizer) !?ArraySize {
const lbracket = try xctok.peek();
if (lbracket == null or lbracket.?.kind != .lbracket) {
return null;
}
_ = try xctok.nextNoEof();
const size_tok = try xctok.nextNoEof();
const size: ArraySize = switch (size_tok.kind) {
.int => .{
.int = std.fmt.parseInt(usize, size_tok.text, 10) catch |err| switch (err) {
error.Overflow => return error.Overflow,
error.InvalidCharacter => unreachable,
},
},
.enum_name => .{ .alias = size_tok.text },
else => return error.InvalidSyntax,
};
_ = try xctok.expect(.rbracket);
return size;
}
pub fn parseVersion(xctok: *XmlCTokenizer) ![3][]const u8 {
_ = try xctok.expect(.hash);
const define = try xctok.expect(.id);
if (!mem.eql(u8, define.text, "define")) {
return error.InvalidVersion;
}
const name = try xctok.expect(.name);
const xr_make_version = try xctok.expect(.type_name);
if (!mem.eql(u8, xr_make_version.text, "XR_MAKE_VERSION")) {
return error.NotVersion;
}
_ = try xctok.expect(.lparen);
var version: [3][]const u8 = undefined;
for (version) |*part, i| {
if (i != 0) {
_ = try xctok.expect(.comma);
}
const tok = try xctok.nextNoEof();
switch (tok.kind) {
.id, .int => part.* = tok.text,
else => return error.UnexpectedToken,
}
}
_ = try xctok.expect(.rparen);
return version;
}
fn testTokenizer(tokenizer: anytype, expected_tokens: []const Token) void {
for (expected_tokens) |expected| {
const tok = (tokenizer.next() catch unreachable).?;
testing.expectEqual(expected.kind, tok.kind);
testing.expectEqualSlices(u8, expected.text, tok.text);
}
if (tokenizer.next() catch unreachable) |_| unreachable;
}
test "CTokenizer" {
var ctok = CTokenizer{
.source =
\\typedef ([const)]** XRAPI_PTR 123,;aaaa
};
testTokenizer(&ctok, &[_]Token{
.{ .kind = .kw_typedef, .text = "typedef" },
.{ .kind = .lparen, .text = "(" },
.{ .kind = .lbracket, .text = "[" },
.{ .kind = .kw_const, .text = "const" },
.{ .kind = .rparen, .text = ")" },
.{ .kind = .rbracket, .text = "]" },
.{ .kind = .star, .text = "*" },
.{ .kind = .star, .text = "*" },
.{ .kind = .kw_xrapi_ptr, .text = "XRAPI_PTR" },
.{ .kind = .int, .text = "123" },
.{ .kind = .comma, .text = "," },
.{ .kind = .semicolon, .text = ";" },
.{ .kind = .id, .text = "aaaa" },
});
}
test "XmlCTokenizer" {
const document = try xml.parse(testing.allocator,
\\<root>// comment <name>commented name</name> <type>commented type</type> trailing
\\ typedef void (XRAPI_PTR *<name>PFN_xrVoidFunction</name>)(void);
\\</root>
);
defer document.deinit();
var xctok = XmlCTokenizer.init(document.root);
testTokenizer(&xctok, &[_]Token{
.{ .kind = .kw_typedef, .text = "typedef" },
.{ .kind = .id, .text = "void" },
.{ .kind = .lparen, .text = "(" },
.{ .kind = .kw_xrapi_ptr, .text = "XRAPI_PTR" },
.{ .kind = .star, .text = "*" },
.{ .kind = .name, .text = "PFN_xrVoidFunction" },
.{ .kind = .rparen, .text = ")" },
.{ .kind = .lparen, .text = "(" },
.{ .kind = .id, .text = "void" },
.{ .kind = .rparen, .text = ")" },
.{ .kind = .semicolon, .text = ";" },
});
}
test "parseTypedef" {
const document = try xml.parse(testing.allocator,
\\<root> // comment <name>commented name</name> trailing
\\ typedef const struct <type>Python</type>* pythons[4];
\\ // more comments
\\</root>
\\
);
defer document.deinit();
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var xctok = XmlCTokenizer.init(document.root);
const decl = try parseTypedef(&arena.allocator, &xctok);
testing.expectEqualSlices(u8, "pythons", decl.name);
const array = decl.decl_type.typedef.array;
testing.expectEqual(ArraySize{ .int = 4 }, array.size);
const ptr = array.child.pointer;
testing.expectEqual(true, ptr.is_const);
testing.expectEqualSlices(u8, "Python", ptr.child.name);
} | generator/openxr/c_parse.zig |
const Types = @import("zig_grammar.types.zig");
const Errors = @import("zig_grammar.errors.zig");
const Tokens = @import("zig_grammar.tokens.zig");
usingnamespace Types;
usingnamespace Errors;
usingnamespace Tokens;
pub const StackItem = struct {
item: usize,
state: i16,
value: StackValue,
};
pub const StackValue = union(enum) {
Token: Id,
Terminal: TerminalId,
};
pub fn reduce_actions(comptime Parser: type, parser: *Parser, rule: isize, state: i16) !TerminalId {
switch (rule) {
1 => {
// Symbol: Root
var result: *Node = undefined;
// Symbol: MaybeRootDocComment
const arg1 = @intToPtr(?*Node.DocComment, parser.stack.items[parser.stack.len - 2].item);
// Symbol: MaybeContainerMembers
const arg2 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 1].item);
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.Root);
node.doc_comments = arg1;
node.decls = if (arg2) |p| p.* else NodeList.init(parser.allocator);
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Root };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Root;
},
2 => {
// Symbol: MaybeDocComment
var result: ?*Node.DocComment = null;
// Push the result of the reduce action
try parser.stack.append(StackItem{ .item = @ptrToInt(result), .state = state, .value = StackValue{ .Terminal = .MaybeDocComment } });
return TerminalId.MaybeDocComment;
},
3 => {
// Symbol: MaybeDocComment
var result: ?*Node.DocComment = null;
// Symbol: DocCommentLines
const arg1 = @intToPtr(?*TokenList, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.DocComment);
node.lines = arg1.*;
result = node;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MaybeDocComment };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.MaybeDocComment;
},
4 => {
// Symbol: DocCommentLines
var result: *TokenList = undefined;
// Symbol: DocCommentLines
const arg1 = @intToPtr(?*TokenList, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: DocComment
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg1;
try arg1.append(arg2);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .DocCommentLines };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.DocCommentLines;
},
5 => {
// Symbol: DocCommentLines
var result: *TokenList = undefined;
// Symbol: DocComment
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = try parser.createListWithToken(TokenList, arg1);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .DocCommentLines };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.DocCommentLines;
},
6 => {
// Symbol: MaybeRootDocComment
var result: ?*Node.DocComment = null;
// Push the result of the reduce action
try parser.stack.append(StackItem{ .item = @ptrToInt(result), .state = state, .value = StackValue{ .Terminal = .MaybeRootDocComment } });
return TerminalId.MaybeRootDocComment;
},
7 => {
// Symbol: MaybeRootDocComment
var result: ?*Node.DocComment = null;
// Symbol: RootDocCommentLines
const arg1 = @intToPtr(?*TokenList, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.DocComment);
node.lines = arg1.*;
result = node;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MaybeRootDocComment };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.MaybeRootDocComment;
},
8 => {
// Symbol: RootDocCommentLines
var result: *TokenList = undefined;
// Symbol: RootDocCommentLines
const arg1 = @intToPtr(?*TokenList, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: RootDocComment
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg1;
try arg1.append(arg2);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .RootDocCommentLines };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.RootDocCommentLines;
},
9 => {
// Symbol: RootDocCommentLines
var result: *TokenList = undefined;
// Symbol: RootDocComment
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = try parser.createListWithToken(TokenList, arg1);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .RootDocCommentLines };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.RootDocCommentLines;
},
10 => {
// Symbol: MaybeContainerMembers
var result: ?*NodeList = null;
// Push the result of the reduce action
try parser.stack.append(StackItem{ .item = @ptrToInt(result), .state = state, .value = StackValue{ .Terminal = .MaybeContainerMembers } });
return TerminalId.MaybeContainerMembers;
},
11 => {
// Symbol: MaybeContainerMembers
var result: ?*NodeList = null;
// Symbol: ContainerMembers
const arg1 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MaybeContainerMembers };
return TerminalId.MaybeContainerMembers;
},
12 => {
// Symbol: ContainerMembers
var result: *NodeList = undefined;
// Symbol: ContainerMembers
const arg1 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: ContainerMember
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg1;
try arg1.append(arg2);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ContainerMembers };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ContainerMembers;
},
13 => {
// Symbol: ContainerMembers
var result: *NodeList = undefined;
// Symbol: ContainerMember
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = try parser.createListWithNode(NodeList, arg1);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ContainerMembers };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ContainerMembers;
},
14 => {
// Symbol: ContainerMember
var result: *Node = undefined;
// Symbol: MaybeDocComment
const arg1 = @intToPtr(?*Node.DocComment, parser.stack.items[parser.stack.len - 2].item);
// Symbol: TestDecl
const arg2 = @intToPtr(?*Node.TestDecl, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = &arg2.base;
arg2.doc_comments = arg1;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ContainerMember };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ContainerMember;
},
15 => {
// Symbol: ContainerMember
var result: *Node = undefined;
// Symbol: MaybeDocComment
const arg1 = @intToPtr(?*Node.DocComment, parser.stack.items[parser.stack.len - 2].item);
// Symbol: TopLevelComptime
const arg2 = @intToPtr(?*Node.Comptime, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = &arg2.base;
arg2.doc_comments = arg1;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ContainerMember };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ContainerMember;
},
16 => {
// Symbol: ContainerMember
var result: *Node = undefined;
// Symbol: MaybeDocComment
const arg1 = @intToPtr(?*Node.DocComment, parser.stack.items[parser.stack.len - 3].item);
// Symbol: MaybePub
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item);
// Symbol: TopLevelDecl
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg3;
if (arg3.cast(Node.VarDecl)) |node| {
node.doc_comments = arg1;
node.visib_token = arg2;
} else if (arg3.cast(Node.FnProto)) |node| {
node.doc_comments = arg1;
node.visib_token = arg2;
} else {
const node = arg3.unsafe_cast(Node.Use);
node.doc_comments = arg1;
node.visib_token = arg2;
}
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ContainerMember };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ContainerMember;
},
17 => {
// Symbol: ContainerMember
var result: *Node = undefined;
// Symbol: MaybeDocComment
const arg1 = @intToPtr(?*Node.DocComment, parser.stack.items[parser.stack.len - 4].item);
// Symbol: MaybePub
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item);
// Symbol: ContainerField
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Comma
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 3;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg3;
const node = arg3.unsafe_cast(Node.ContainerField);
node.doc_comments = arg1;
node.visib_token = arg2;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ContainerMember };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ContainerMember;
},
18 => {
// Symbol: TestDecl
var result: *Node.TestDecl = undefined;
// Symbol: Keyword_test
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: StringLiteral
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Block
const arg3 = @intToPtr(?*Node.Block, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const name = try parser.createNode(Node.StringLiteral);
name.token = arg2;
const node = try parser.createNode(Node.TestDecl);
node.test_token = arg1;
node.name = &name.base;
node.body_node = &arg3.base;
result = node;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .TestDecl };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.TestDecl;
},
19 => {
// Symbol: TopLevelComptime
var result: *Node.Comptime = undefined;
// Symbol: Keyword_comptime
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: BlockExpr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.Comptime);
node.comptime_token = arg1;
node.expr = arg2;
result = node;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .TopLevelComptime };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.TopLevelComptime;
},
20 => {
// Symbol: TopLevelDecl
var result: *Node = undefined;
// Symbol: FnProto
const arg1 = @intToPtr(?*Node.FnProto, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Semicolon
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = &arg1.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .TopLevelDecl };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.TopLevelDecl;
},
21 => {
// Symbol: TopLevelDecl
var result: *Node = undefined;
// Symbol: FnProto
const arg1 = @intToPtr(?*Node.FnProto, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Block
const arg2 = @intToPtr(?*Node.Block, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
arg1.body_node = &arg2.base;
result = &arg1.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .TopLevelDecl };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.TopLevelDecl;
},
22 => {
// Symbol: TopLevelDecl
var result: *Node = undefined;
// Symbol: Keyword_extern
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: StringLiteral
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: FnProto
const arg3 = @intToPtr(?*Node.FnProto, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Semicolon
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 3;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = &arg3.base;
const lib_name = try parser.createNode(Node.StringLiteral);
lib_name.token = arg2;
arg3.extern_export_inline_token = arg1;
arg3.lib_name = &lib_name.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .TopLevelDecl };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.TopLevelDecl;
},
23 => {
// Symbol: TopLevelDecl
var result: *Node = undefined;
// Symbol: Keyword_extern
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: StringLiteral
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: FnProto
const arg3 = @intToPtr(?*Node.FnProto, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Block
const arg4 = @intToPtr(?*Node.Block, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 3;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = &arg3.base;
const lib_name = try parser.createNode(Node.StringLiteral);
lib_name.token = arg2;
arg3.extern_export_inline_token = arg1;
arg3.lib_name = &lib_name.base;
arg3.body_node = &arg4.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .TopLevelDecl };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.TopLevelDecl;
},
24 => {
// Symbol: TopLevelDecl
var result: *Node = undefined;
// Symbol: Keyword_export
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: FnProto
const arg2 = @intToPtr(?*Node.FnProto, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Semicolon
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = &arg2.base;
arg2.extern_export_inline_token = arg1;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .TopLevelDecl };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.TopLevelDecl;
},
25 => {
// Symbol: TopLevelDecl
var result: *Node = undefined;
// Symbol: Keyword_inline
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: FnProto
const arg2 = @intToPtr(?*Node.FnProto, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Semicolon
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = &arg2.base;
arg2.extern_export_inline_token = arg1;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .TopLevelDecl };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.TopLevelDecl;
},
26 => {
// Symbol: TopLevelDecl
var result: *Node = undefined;
// Symbol: Keyword_export
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: FnProto
const arg2 = @intToPtr(?*Node.FnProto, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Block
const arg3 = @intToPtr(?*Node.Block, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = &arg2.base;
arg2.extern_export_inline_token = arg1;
arg2.body_node = &arg3.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .TopLevelDecl };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.TopLevelDecl;
},
27 => {
// Symbol: TopLevelDecl
var result: *Node = undefined;
// Symbol: Keyword_inline
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: FnProto
const arg2 = @intToPtr(?*Node.FnProto, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Block
const arg3 = @intToPtr(?*Node.Block, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = &arg2.base;
arg2.extern_export_inline_token = arg1;
arg2.body_node = &arg3.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .TopLevelDecl };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.TopLevelDecl;
},
28 => {
// Symbol: TopLevelDecl
var result: *Node = undefined;
// Symbol: MaybeThreadlocal
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item);
// Symbol: VarDecl
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg2;
const node = arg2.unsafe_cast(Node.VarDecl);
node.thread_local_token = arg1;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .TopLevelDecl };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.TopLevelDecl;
},
29 => {
// Symbol: TopLevelDecl
var result: *Node = undefined;
// Symbol: Keyword_extern
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: StringLiteral
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: MaybeThreadlocal
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item);
// Symbol: VarDecl
const arg4 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 3;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg4;
const lib_name = try parser.createNode(Node.StringLiteral);
lib_name.token = arg2;
const node = arg4.unsafe_cast(Node.VarDecl);
node.extern_export_token = arg1;
node.lib_name = &lib_name.base;
node.thread_local_token = arg3;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .TopLevelDecl };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.TopLevelDecl;
},
30 => {
// Symbol: TopLevelDecl
var result: *Node = undefined;
// Symbol: Keyword_export
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: MaybeThreadlocal
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item);
// Symbol: VarDecl
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg3;
const node = arg3.unsafe_cast(Node.VarDecl);
node.extern_export_token = arg1;
node.thread_local_token = arg2;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .TopLevelDecl };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.TopLevelDecl;
},
31 => {
// Symbol: TopLevelDecl
var result: *Node = undefined;
// Symbol: Keyword_extern
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: MaybeThreadlocal
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item);
// Symbol: VarDecl
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg3;
const node = arg3.unsafe_cast(Node.VarDecl);
node.extern_export_token = arg1;
node.thread_local_token = arg2;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .TopLevelDecl };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.TopLevelDecl;
},
32 => {
// Symbol: TopLevelDecl
var result: *Node = undefined;
// Symbol: Keyword_usingnamespace
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Expr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Semicolon
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.Use);
node.use_token = arg1;
node.expr = arg2;
node.semicolon_token = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .TopLevelDecl };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.TopLevelDecl;
},
33 => {
// Symbol: TopLevelDecl
var result: *Node = undefined;
// Symbol: Keyword_use
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Expr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Semicolon
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.Use);
node.use_token = arg1;
node.expr = arg2;
node.semicolon_token = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .TopLevelDecl };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.TopLevelDecl;
},
34 => {
// Symbol: MaybeThreadlocal
var result: ?*Token = null;
// Push the result of the reduce action
try parser.stack.append(StackItem{ .item = @ptrToInt(result), .state = state, .value = StackValue{ .Terminal = .MaybeThreadlocal } });
return TerminalId.MaybeThreadlocal;
},
35 => {
// Symbol: MaybeThreadlocal
var result: ?*Token = null;
// Symbol: Keyword_threadlocal
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MaybeThreadlocal };
return TerminalId.MaybeThreadlocal;
},
36 => {
// Symbol: FnProto
var result: *Node.FnProto = undefined;
// Symbol: Keyword_fn
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 8].item).?;
// Symbol: MaybeIdentifier
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 7].item);
// Symbol: LParen
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 6].item).?;
// Symbol: MaybeParamDeclList
const arg4 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 5].item);
// Symbol: RParen
const arg5 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: MaybeByteAlign
const arg6 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item);
// Symbol: MaybeLinkSection
const arg7 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item);
// Symbol: Expr
const arg8 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 7;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.FnProto);
node.fn_token = arg1;
node.name_token = arg2;
node.params = if (arg4) |p| p.* else NodeList.init(parser.allocator);
node.align_expr = arg6;
node.section_expr = arg7;
node.return_type = Node.FnProto.ReturnType{ .Explicit = arg8 };
result = node;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .FnProto };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.FnProto;
},
37 => {
// Symbol: FnProto
var result: *Node.FnProto = undefined;
// Symbol: FnCC
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 9].item).?;
// Symbol: Keyword_fn
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 8].item).?;
// Symbol: MaybeIdentifier
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 7].item);
// Symbol: LParen
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 6].item).?;
// Symbol: MaybeParamDeclList
const arg5 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 5].item);
// Symbol: RParen
const arg6 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: MaybeByteAlign
const arg7 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item);
// Symbol: MaybeLinkSection
const arg8 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item);
// Symbol: Expr
const arg9 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 8;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.FnProto);
node.cc_token = arg1;
node.fn_token = arg2;
node.name_token = arg3;
node.params = if (arg5) |p| p.* else NodeList.init(parser.allocator);
node.align_expr = arg7;
node.section_expr = arg8;
node.return_type = Node.FnProto.ReturnType{ .Explicit = arg9 };
result = node;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .FnProto };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.FnProto;
},
38 => {
// Symbol: FnProto
var result: *Node.FnProto = undefined;
// Symbol: Keyword_fn
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 9].item).?;
// Symbol: MaybeIdentifier
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 8].item);
// Symbol: LParen
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 7].item).?;
// Symbol: MaybeParamDeclList
const arg4 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 6].item);
// Symbol: RParen
const arg5 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: MaybeByteAlign
const arg6 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 4].item);
// Symbol: MaybeLinkSection
const arg7 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item);
// Symbol: Bang
const arg8 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg9 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 8;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.FnProto);
node.fn_token = arg1;
node.name_token = arg2;
node.params = if (arg4) |p| p.* else NodeList.init(parser.allocator);
node.align_expr = arg6;
node.section_expr = arg7;
node.return_type = Node.FnProto.ReturnType{ .InferErrorSet = arg9 };
result = node;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .FnProto };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.FnProto;
},
39 => {
// Symbol: FnProto
var result: *Node.FnProto = undefined;
// Symbol: FnCC
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 10].item).?;
// Symbol: Keyword_fn
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 9].item).?;
// Symbol: MaybeIdentifier
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 8].item);
// Symbol: LParen
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 7].item).?;
// Symbol: MaybeParamDeclList
const arg5 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 6].item);
// Symbol: RParen
const arg6 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: MaybeByteAlign
const arg7 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 4].item);
// Symbol: MaybeLinkSection
const arg8 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item);
// Symbol: Bang
const arg9 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg10 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 9;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.FnProto);
node.cc_token = arg1;
node.fn_token = arg2;
node.name_token = arg3;
node.params = if (arg5) |p| p.* else NodeList.init(parser.allocator);
node.align_expr = arg7;
node.section_expr = arg8;
node.return_type = Node.FnProto.ReturnType{ .InferErrorSet = arg10 };
result = node;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .FnProto };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.FnProto;
},
40 => {
// Symbol: FnProto
var result: *Node.FnProto = undefined;
// Symbol: Keyword_fn
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 8].item).?;
// Symbol: MaybeIdentifier
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 7].item);
// Symbol: LParen
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 6].item).?;
// Symbol: MaybeParamDeclList
const arg4 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 5].item);
// Symbol: RParen
const arg5 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: MaybeByteAlign
const arg6 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item);
// Symbol: MaybeLinkSection
const arg7 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item);
// Symbol: Keyword_var
const arg8 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 7;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const vnode = try parser.createNode(Node.VarType);
vnode.token = arg8;
const node = try parser.createNode(Node.FnProto);
node.fn_token = arg1;
node.name_token = arg2;
node.params = if (arg4) |p| p.* else NodeList.init(parser.allocator);
node.align_expr = arg6;
node.section_expr = arg7;
node.return_type = Node.FnProto.ReturnType{ .Explicit = &vnode.base };
result = node;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .FnProto };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.FnProto;
},
41 => {
// Symbol: FnProto
var result: *Node.FnProto = undefined;
// Symbol: FnCC
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 9].item).?;
// Symbol: Keyword_fn
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 8].item).?;
// Symbol: MaybeIdentifier
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 7].item);
// Symbol: LParen
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 6].item).?;
// Symbol: MaybeParamDeclList
const arg5 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 5].item);
// Symbol: RParen
const arg6 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: MaybeByteAlign
const arg7 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item);
// Symbol: MaybeLinkSection
const arg8 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item);
// Symbol: Keyword_var
const arg9 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 8;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const vnode = try parser.createNode(Node.VarType);
vnode.token = arg9;
const node = try parser.createNode(Node.FnProto);
node.cc_token = arg1;
node.fn_token = arg2;
node.name_token = arg3;
node.params = if (arg5) |p| p.* else NodeList.init(parser.allocator);
node.align_expr = arg7;
node.section_expr = arg8;
node.return_type = Node.FnProto.ReturnType{ .Explicit = &vnode.base };
result = node;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .FnProto };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.FnProto;
},
42 => {
// Symbol: FnProto
var result: *Node.FnProto = undefined;
// Symbol: Keyword_fn
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 9].item).?;
// Symbol: MaybeIdentifier
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 8].item);
// Symbol: LParen
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 7].item).?;
// Symbol: MaybeParamDeclList
const arg4 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 6].item);
// Symbol: RParen
const arg5 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: MaybeByteAlign
const arg6 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 4].item);
// Symbol: MaybeLinkSection
const arg7 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item);
// Symbol: Bang
const arg8 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Keyword_var
const arg9 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 8;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const vnode = try parser.createNode(Node.VarType);
vnode.token = arg9;
const node = try parser.createNode(Node.FnProto);
node.fn_token = arg1;
node.name_token = arg2;
node.params = if (arg4) |p| p.* else NodeList.init(parser.allocator);
node.align_expr = arg6;
node.section_expr = arg7;
node.return_type = Node.FnProto.ReturnType{ .InferErrorSet = &vnode.base };
result = node;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .FnProto };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.FnProto;
},
43 => {
// Symbol: FnProto
var result: *Node.FnProto = undefined;
// Symbol: FnCC
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 10].item).?;
// Symbol: Keyword_fn
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 9].item).?;
// Symbol: MaybeIdentifier
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 8].item);
// Symbol: LParen
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 7].item).?;
// Symbol: MaybeParamDeclList
const arg5 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 6].item);
// Symbol: RParen
const arg6 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: MaybeByteAlign
const arg7 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 4].item);
// Symbol: MaybeLinkSection
const arg8 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item);
// Symbol: Bang
const arg9 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Keyword_var
const arg10 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 9;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const vnode = try parser.createNode(Node.VarType);
vnode.token = arg10;
const node = try parser.createNode(Node.FnProto);
node.cc_token = arg1;
node.fn_token = arg2;
node.name_token = arg3;
node.params = if (arg5) |p| p.* else NodeList.init(parser.allocator);
node.align_expr = arg7;
node.section_expr = arg8;
node.return_type = Node.FnProto.ReturnType{ .InferErrorSet = &vnode.base };
result = node;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .FnProto };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.FnProto;
},
44 => {
// Symbol: VarDecl
var result: *Node = undefined;
// Symbol: Keyword_const
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 7].item).?;
// Symbol: Identifier
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 6].item).?;
// Symbol: MaybeColonTypeExpr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 5].item);
// Symbol: MaybeByteAlign
const arg4 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 4].item);
// Symbol: MaybeLinkSection
const arg5 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item);
// Symbol: MaybeEqualExpr
const arg6 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item);
// Symbol: Semicolon
const arg7 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 6;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.VarDecl);
node.mut_token = arg1;
node.name_token = arg2;
node.type_node = arg3;
node.align_node = arg4;
node.section_node = arg5;
node.init_node = arg6;
node.semicolon_token = arg7;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .VarDecl };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.VarDecl;
},
45 => {
// Symbol: VarDecl
var result: *Node = undefined;
// Symbol: Keyword_var
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 7].item).?;
// Symbol: Identifier
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 6].item).?;
// Symbol: MaybeColonTypeExpr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 5].item);
// Symbol: MaybeByteAlign
const arg4 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 4].item);
// Symbol: MaybeLinkSection
const arg5 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item);
// Symbol: MaybeEqualExpr
const arg6 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item);
// Symbol: Semicolon
const arg7 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 6;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.VarDecl);
node.mut_token = arg1;
node.name_token = arg2;
node.type_node = arg3;
node.align_node = arg4;
node.section_node = arg5;
node.init_node = arg6;
node.semicolon_token = arg7;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .VarDecl };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.VarDecl;
},
46 => {
// Symbol: ContainerField
var result: *Node = undefined;
// Symbol: Identifier
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: MaybeColonTypeExpr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item);
// Symbol: MaybeEqualExpr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item);
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.ContainerField);
node.name_token = arg1;
node.type_expr = arg2;
node.value_expr = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ContainerField };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ContainerField;
},
47 => {
// Symbol: MaybeStatements
var result: ?*NodeList = null;
// Push the result of the reduce action
try parser.stack.append(StackItem{ .item = @ptrToInt(result), .state = state, .value = StackValue{ .Terminal = .MaybeStatements } });
return TerminalId.MaybeStatements;
},
48 => {
// Symbol: MaybeStatements
var result: ?*NodeList = null;
// Symbol: Statements
const arg1 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MaybeStatements };
return TerminalId.MaybeStatements;
},
49 => {
// Symbol: Statements
var result: *NodeList = undefined;
// Symbol: Statement
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = try parser.createListWithNode(NodeList, arg1);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Statements };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Statements;
},
50 => {
// Symbol: Statements
var result: *NodeList = undefined;
// Symbol: Statements
const arg1 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Statement
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg1;
try arg1.append(arg2);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Statements };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Statements;
},
51 => {
// Symbol: Statement
var result: *Node = undefined;
// Symbol: Keyword_comptime
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: VarDecl
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.Comptime);
node.comptime_token = arg1;
node.expr = arg2;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Statement };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Statement;
},
52 => {
// Symbol: Statement
var result: *Node = undefined;
// Symbol: VarDecl
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Statement };
return TerminalId.Statement;
},
53 => {
// Symbol: Statement
var result: *Node = undefined;
// Symbol: Keyword_comptime
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: BlockExpr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.Comptime);
node.comptime_token = arg1;
node.expr = arg2;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Statement };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Statement;
},
54 => {
// Symbol: Statement
var result: *Node = undefined;
// Symbol: Keyword_suspend
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Semicolon
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.Suspend);
node.suspend_token = arg1;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Statement };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Statement;
},
55 => {
// Symbol: Statement
var result: *Node = undefined;
// Symbol: Keyword_suspend
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: BlockExprStatement
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.Suspend);
node.suspend_token = arg1;
node.body = arg2;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Statement };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Statement;
},
56 => {
// Symbol: Statement
var result: *Node = undefined;
// Symbol: Keyword_defer
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: BlockExprStatement
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.Defer);
node.defer_token = arg1;
node.expr = arg2;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Statement };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Statement;
},
57 => {
// Symbol: Statement
var result: *Node = undefined;
// Symbol: Keyword_errdefer
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: BlockExprStatement
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.Defer);
node.defer_token = arg1;
node.expr = arg2;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Statement };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Statement;
},
58 => {
// Symbol: Statement
var result: *Node = undefined;
// Symbol: IfStatement
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Statement };
return TerminalId.Statement;
},
59 => {
// Symbol: Statement
var result: *Node = undefined;
// Symbol: MaybeInline
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item);
// Symbol: ForStatement
const arg2 = @intToPtr(?*Node.For, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = &arg2.base;
arg2.inline_token = arg1;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Statement };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Statement;
},
60 => {
// Symbol: Statement
var result: *Node = undefined;
// Symbol: MaybeInline
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item);
// Symbol: WhileStatement
const arg2 = @intToPtr(?*Node.While, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = &arg2.base;
arg2.inline_token = arg1;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Statement };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Statement;
},
61 => {
// Symbol: Statement
var result: *Node = undefined;
// Symbol: LabeledStatement
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Statement };
return TerminalId.Statement;
},
62 => {
// Symbol: Statement
var result: *Node = undefined;
// Symbol: SwitchExpr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Statement };
return TerminalId.Statement;
},
63 => {
// Symbol: Statement
var result: *Node = undefined;
// Symbol: AssignExpr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Semicolon
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg1;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Statement };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Statement;
},
64 => {
// Symbol: IfStatement
var result: *Node = undefined;
// Symbol: IfPrefix
const arg1 = @intToPtr(?*Node.If, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: BlockExpr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = &arg1.base;
arg1.body = arg2;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .IfStatement };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.IfStatement;
},
65 => {
// Symbol: IfStatement
var result: *Node = undefined;
// Symbol: IfPrefix
const arg1 = @intToPtr(?*Node.If, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: BlockExpr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: ElseStatement
const arg3 = @intToPtr(?*Node.Else, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = &arg1.base;
arg1.body = arg2;
arg1.@"else" = arg3;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .IfStatement };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.IfStatement;
},
66 => {
// Symbol: IfStatement
var result: *Node = undefined;
// Symbol: IfPrefix
const arg1 = @intToPtr(?*Node.If, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: AssignExpr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Semicolon
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = &arg1.base;
arg1.body = arg2;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .IfStatement };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.IfStatement;
},
67 => {
// Symbol: IfStatement
var result: *Node = undefined;
// Symbol: IfPrefix
const arg1 = @intToPtr(?*Node.If, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: AssignExpr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: ElseStatement
const arg3 = @intToPtr(?*Node.Else, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = &arg1.base;
arg1.body = arg2;
arg1.@"else" = arg3;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .IfStatement };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.IfStatement;
},
68 => {
// Symbol: ElseStatement
var result: *Node.Else = undefined;
// Symbol: Keyword_else
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: MaybePayload
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item);
// Symbol: Statement
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.Else);
node.else_token = arg1;
node.payload = arg2;
node.body = arg3;
result = node;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ElseStatement };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ElseStatement;
},
69 => {
// Symbol: LabeledStatement
var result: *Node = undefined;
// Symbol: BlockLabel
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: MaybeInline
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item);
// Symbol: ForStatement
const arg3 = @intToPtr(?*Node.For, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = &arg3.base;
arg3.label = arg1;
arg3.inline_token = arg2;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .LabeledStatement };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.LabeledStatement;
},
70 => {
// Symbol: LabeledStatement
var result: *Node = undefined;
// Symbol: BlockLabel
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: MaybeInline
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item);
// Symbol: WhileStatement
const arg3 = @intToPtr(?*Node.While, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = &arg3.base;
arg3.label = arg1;
arg3.inline_token = arg2;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .LabeledStatement };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.LabeledStatement;
},
71 => {
// Symbol: LabeledStatement
var result: *Node = undefined;
// Symbol: BlockExpr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .LabeledStatement };
return TerminalId.LabeledStatement;
},
72 => {
// Symbol: ForStatement
var result: *Node.For = undefined;
// Symbol: ForPrefix
const arg1 = @intToPtr(?*Node.For, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: BlockExpr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg1;
arg1.body = arg2;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ForStatement };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ForStatement;
},
73 => {
// Symbol: ForStatement
var result: *Node.For = undefined;
// Symbol: ForPrefix
const arg1 = @intToPtr(?*Node.For, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: BlockExpr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: ElseNoPayloadStatement
const arg3 = @intToPtr(?*Node.Else, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg1;
arg1.body = arg2;
arg1.@"else" = arg3;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ForStatement };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ForStatement;
},
74 => {
// Symbol: ForStatement
var result: *Node.For = undefined;
// Symbol: ForPrefix
const arg1 = @intToPtr(?*Node.For, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: AssignExpr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Semicolon
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg1;
arg1.body = arg2;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ForStatement };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ForStatement;
},
75 => {
// Symbol: ForStatement
var result: *Node.For = undefined;
// Symbol: ForPrefix
const arg1 = @intToPtr(?*Node.For, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: AssignExpr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: ElseNoPayloadStatement
const arg3 = @intToPtr(?*Node.Else, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg1;
arg1.body = arg2;
arg1.@"else" = arg3;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ForStatement };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ForStatement;
},
76 => {
// Symbol: ElseNoPayloadStatement
var result: *Node.Else = undefined;
// Symbol: Keyword_else
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Statement
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.Else);
node.else_token = arg1;
node.body = arg2;
result = node;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ElseNoPayloadStatement };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ElseNoPayloadStatement;
},
77 => {
// Symbol: WhileStatement
var result: *Node.While = undefined;
// Symbol: WhilePrefix
const arg1 = @intToPtr(?*Node.While, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: BlockExpr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg1;
arg1.body = arg2;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .WhileStatement };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.WhileStatement;
},
78 => {
// Symbol: WhileStatement
var result: *Node.While = undefined;
// Symbol: WhilePrefix
const arg1 = @intToPtr(?*Node.While, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: BlockExpr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: ElseStatement
const arg3 = @intToPtr(?*Node.Else, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg1;
arg1.body = arg2;
arg1.@"else" = arg3;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .WhileStatement };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.WhileStatement;
},
79 => {
// Symbol: WhileStatement
var result: *Node.While = undefined;
// Symbol: WhilePrefix
const arg1 = @intToPtr(?*Node.While, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: AssignExpr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Semicolon
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg1;
arg1.body = arg2;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .WhileStatement };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.WhileStatement;
},
80 => {
// Symbol: WhileStatement
var result: *Node.While = undefined;
// Symbol: WhilePrefix
const arg1 = @intToPtr(?*Node.While, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: AssignExpr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: ElseStatement
const arg3 = @intToPtr(?*Node.Else, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg1;
arg1.body = arg2;
arg1.@"else" = arg3;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .WhileStatement };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.WhileStatement;
},
81 => {
// Symbol: BlockExprStatement
var result: *Node = undefined;
// Symbol: BlockExpr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .BlockExprStatement };
return TerminalId.BlockExprStatement;
},
82 => {
// Symbol: BlockExprStatement
var result: *Node = undefined;
// Symbol: AssignExpr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Semicolon
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg1;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .BlockExprStatement };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.BlockExprStatement;
},
83 => {
// Symbol: AssignExpr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: AsteriskEqual
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .AssignTimes;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AssignExpr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.AssignExpr;
},
84 => {
// Symbol: AssignExpr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: SlashEqual
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .AssignDiv;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AssignExpr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.AssignExpr;
},
85 => {
// Symbol: AssignExpr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: PercentEqual
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .AssignMod;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AssignExpr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.AssignExpr;
},
86 => {
// Symbol: AssignExpr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: PlusEqual
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .AssignPlus;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AssignExpr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.AssignExpr;
},
87 => {
// Symbol: AssignExpr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: MinusEqual
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .AssignMinus;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AssignExpr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.AssignExpr;
},
88 => {
// Symbol: AssignExpr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: AngleBracketAngleBracketLeftEqual
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .AssignBitShiftLeft;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AssignExpr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.AssignExpr;
},
89 => {
// Symbol: AssignExpr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: AngleBracketAngleBracketRightEqual
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .AssignBitShiftRight;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AssignExpr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.AssignExpr;
},
90 => {
// Symbol: AssignExpr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: AmpersandEqual
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .AssignBitAnd;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AssignExpr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.AssignExpr;
},
91 => {
// Symbol: AssignExpr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: CaretEqual
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .AssignBitXor;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AssignExpr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.AssignExpr;
},
92 => {
// Symbol: AssignExpr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: PipeEqual
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .AssignBitOr;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AssignExpr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.AssignExpr;
},
93 => {
// Symbol: AssignExpr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: AsteriskPercentEqual
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .AssignTimesWrap;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AssignExpr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.AssignExpr;
},
94 => {
// Symbol: AssignExpr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: PlusPercentEqual
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .AssignPlusWrap;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AssignExpr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.AssignExpr;
},
95 => {
// Symbol: AssignExpr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: MinusPercentEqual
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .AssignMinusWrap;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AssignExpr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.AssignExpr;
},
96 => {
// Symbol: AssignExpr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Equal
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .Assign;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AssignExpr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.AssignExpr;
},
97 => {
// Symbol: AssignExpr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AssignExpr };
return TerminalId.AssignExpr;
},
98 => {
// Symbol: MaybeEqualExpr
var result: ?*Node = null;
// Push the result of the reduce action
try parser.stack.append(StackItem{ .item = @ptrToInt(result), .state = state, .value = StackValue{ .Terminal = .MaybeEqualExpr } });
return TerminalId.MaybeEqualExpr;
},
99 => {
// Symbol: MaybeEqualExpr
var result: ?*Node = null;
// Symbol: Equal
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg2;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MaybeEqualExpr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.MaybeEqualExpr;
},
100 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Recovery
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.Recovery);
node.token = arg1;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
101 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: LParen
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Expr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: RParen
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
if (arg2.id != .GroupedExpression) {
const node = try parser.createNode(Node.GroupedExpression);
node.lparen = arg1;
node.expr = arg2;
node.rparen = arg3;
result = &node.base;
} else result = arg2;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
102 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Keyword_orelse
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .UnwrapOptional;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
103 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: Keyword_catch
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: MaybePayload
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item);
// Symbol: Expr
const arg4 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 3;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = Node.InfixOp.Op{ .Catch = arg3 };
node.rhs = arg4;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
104 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Keyword_or
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .BoolOr;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
105 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: AmpersandAmpersand
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
try parser.reportError(ParseError.AmpersandAmpersand, arg2);
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .BoolAnd;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
106 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Keyword_and
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .BoolAnd;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
107 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: EqualEqual
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .EqualEqual;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
108 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: BangEqual
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .BangEqual;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
109 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: AngleBracketLeft
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .LessThan;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
110 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: AngleBracketRight
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .GreaterThan;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
111 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: AngleBracketLeftEqual
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .LessOrEqual;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
112 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: AngleBracketRightEqual
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .GreaterOrEqual;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
113 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Pipe
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .BitOr;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
114 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Caret
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .BitXor;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
115 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Ampersand
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .BitAnd;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
116 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: AngleBracketAngleBracketLeft
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .BitShiftLeft;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
117 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: AngleBracketAngleBracketRight
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .BitShiftRight;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
118 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Plus
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .Add;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
119 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Minus
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .Sub;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
120 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: PlusPlus
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .ArrayCat;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
121 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: PlusPercent
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .AddWrap;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
122 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: MinusPercent
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .SubWrap;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
123 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Asterisk
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .Div;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
124 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Slash
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .Div;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
125 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Percent
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .Mod;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
126 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: AsteriskAsterisk
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .ArrayMult;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
127 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: AsteriskPercent
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .MultWrap;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
128 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: PipePipe
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .ErrorUnion;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
129 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Bang
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.PrefixOp);
node.op_token = arg1;
node.op = .BoolNot;
node.rhs = arg2;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
130 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Minus
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.PrefixOp);
node.op_token = arg1;
node.op = .Negation;
node.rhs = arg2;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
131 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: MinusPercent
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.PrefixOp);
node.op_token = arg1;
node.op = .NegationWrap;
node.rhs = arg2;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
132 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Tilde
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.PrefixOp);
node.op_token = arg1;
node.op = .BitNot;
node.rhs = arg2;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
133 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Ampersand
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.PrefixOp);
node.op_token = arg1;
node.op = .AddressOf;
node.rhs = arg2;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
134 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Keyword_async
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.PrefixOp);
node.op_token = arg1;
node.op = .Async;
node.rhs = arg2;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
135 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Keyword_try
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.PrefixOp);
node.op_token = arg1;
node.op = .Try;
node.rhs = arg2;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
136 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Keyword_await
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.PrefixOp);
node.op_token = arg1;
node.op = .Await;
node.rhs = arg2;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
137 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Keyword_comptime
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.Comptime);
node.comptime_token = arg1;
node.expr = arg2;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
138 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: AsmExpr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
return TerminalId.Expr;
},
139 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Keyword_resume
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.PrefixOp);
node.op_token = arg1;
node.op = .Resume;
node.rhs = arg2;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
140 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Keyword_cancel
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.PrefixOp);
node.op_token = arg1;
node.op = .Cancel;
node.rhs = arg2;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
141 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Keyword_break
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.ControlFlowExpression);
node.ltoken = arg1;
node.kind = Node.ControlFlowExpression.Kind{ .Break = null };
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
142 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Keyword_break
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: BreakLabel
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.ControlFlowExpression);
node.ltoken = arg1;
node.kind = Node.ControlFlowExpression.Kind{ .Break = arg2 };
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
143 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Keyword_break
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.ControlFlowExpression);
node.ltoken = arg1;
node.kind = Node.ControlFlowExpression.Kind{ .Break = null };
node.rhs = arg2;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
144 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Keyword_break
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: BreakLabel
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.ControlFlowExpression);
node.ltoken = arg1;
node.kind = Node.ControlFlowExpression.Kind{ .Break = arg2 };
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
145 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Keyword_continue
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.ControlFlowExpression);
node.ltoken = arg1;
node.kind = Node.ControlFlowExpression.Kind{ .Continue = null };
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
146 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Keyword_continue
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: BreakLabel
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.ControlFlowExpression);
node.ltoken = arg1;
node.kind = Node.ControlFlowExpression.Kind{ .Continue = arg2 };
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
147 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Keyword_return
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.ControlFlowExpression);
node.ltoken = arg1;
node.kind = .Return;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
148 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Keyword_return
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.ControlFlowExpression);
node.ltoken = arg1;
node.kind = .Return;
node.rhs = arg2;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
149 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: LCurly
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: RBrace
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.SuffixOp);
node.lhs = arg1;
node.op = Node.SuffixOp.Op{ .ArrayInitializer = NodeList.init(parser.allocator) };
node.rtoken = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
150 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: LCurly
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: InitList
const arg3 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: MaybeComma
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item);
// Symbol: RBrace
const arg5 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 4;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.SuffixOp);
node.lhs = arg1;
node.op = init: {
if (arg3.at(0).cast(Node.InfixOp)) |infix| {
switch (infix.op) {
// StructInitializer
.Assign => break :init Node.SuffixOp.Op{ .StructInitializer = arg3.* },
else => {},
}
}
// ArrayInitializer
break :init Node.SuffixOp.Op{ .ArrayInitializer = arg3.* };
};
node.rtoken = arg5;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
151 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: QuestionMark
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.PrefixOp);
node.op_token = arg1;
node.op = .OptionalType;
node.rhs = arg2;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
152 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Keyword_promise
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.PromiseType);
node.promise_token = arg1;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
153 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Keyword_promise
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: MinusAngleBracketRight
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.PromiseType);
node.promise_token = arg1;
node.result = Node.PromiseType.Result{ .arrow_token = arg2, .return_type = arg3 };
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
154 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: LBracket
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: Expr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: RBracket
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg4 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 3;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.PrefixOp);
node.op_token = arg1;
node.op = Node.PrefixOp.Op{ .ArrayType = arg2 };
node.rhs = arg4;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
155 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: LBracket
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 7].item).?;
// Symbol: RBracket
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 6].item).?;
// Symbol: MaybeAllowzero
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item);
// Symbol: MaybeAlign
const arg4 = @intToPtr(?*Node.PrefixOp.PtrInfo.Align, parser.stack.items[parser.stack.len - 4].item);
// Symbol: MaybeConst
const arg5 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item);
// Symbol: MaybeVolatile
const arg6 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item);
// Symbol: Expr
const arg7 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 6;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.PrefixOp);
node.op_token = arg1;
node.op = Node.PrefixOp.Op{ .SliceType = Node.PrefixOp.PtrInfo{ .allowzero_token = arg3, .align_info = if (arg4) |p| p.* else null, .const_token = arg5, .volatile_token = arg6 } };
node.rhs = arg7;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
156 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Asterisk
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 6].item).?;
// Symbol: MaybeAllowzero
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item);
// Symbol: MaybeAlign
const arg3 = @intToPtr(?*Node.PrefixOp.PtrInfo.Align, parser.stack.items[parser.stack.len - 4].item);
// Symbol: MaybeConst
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item);
// Symbol: MaybeVolatile
const arg5 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item);
// Symbol: Expr
const arg6 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 5;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.PrefixOp);
node.op_token = arg1;
node.op = Node.PrefixOp.Op{ .PtrType = Node.PrefixOp.PtrInfo{ .allowzero_token = arg2, .align_info = if (arg3) |p| p.* else null, .const_token = arg4, .volatile_token = arg5 } };
node.rhs = arg6;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
157 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: AsteriskAsterisk
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 6].item).?;
// Symbol: MaybeAllowzero
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item);
// Symbol: MaybeAlign
const arg3 = @intToPtr(?*Node.PrefixOp.PtrInfo.Align, parser.stack.items[parser.stack.len - 4].item);
// Symbol: MaybeConst
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item);
// Symbol: MaybeVolatile
const arg5 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item);
// Symbol: Expr
const arg6 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 5;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
arg1.id = .Asterisk;
const node = try parser.createNode(Node.PrefixOp);
node.op_token = arg1;
node.op = Node.PrefixOp.Op{ .PtrType = Node.PrefixOp.PtrInfo{ .allowzero_token = arg2, .align_info = if (arg3) |p| p.* else null, .const_token = arg4, .volatile_token = arg5 } };
node.rhs = arg6;
const outer = try parser.createNode(Node.PrefixOp);
outer.op_token = arg1;
outer.op = Node.PrefixOp.Op{ .PtrType = Node.PrefixOp.PtrInfo{ .allowzero_token = null, .align_info = null, .const_token = null, .volatile_token = null } };
outer.rhs = &node.base;
result = &outer.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
158 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: BracketStarBracket
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 6].item).?;
// Symbol: MaybeAllowzero
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item);
// Symbol: MaybeAlign
const arg3 = @intToPtr(?*Node.PrefixOp.PtrInfo.Align, parser.stack.items[parser.stack.len - 4].item);
// Symbol: MaybeConst
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item);
// Symbol: MaybeVolatile
const arg5 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item);
// Symbol: Expr
const arg6 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 5;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.PrefixOp);
node.op_token = arg1;
node.op = Node.PrefixOp.Op{ .PtrType = Node.PrefixOp.PtrInfo{ .allowzero_token = arg2, .align_info = if (arg3) |p| p.* else null, .const_token = arg4, .volatile_token = arg5 } };
node.rhs = arg6;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
159 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: BracketStarCBracket
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 6].item).?;
// Symbol: MaybeAllowzero
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item);
// Symbol: MaybeAlign
const arg3 = @intToPtr(?*Node.PrefixOp.PtrInfo.Align, parser.stack.items[parser.stack.len - 4].item);
// Symbol: MaybeConst
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item);
// Symbol: MaybeVolatile
const arg5 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item);
// Symbol: Expr
const arg6 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 5;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.PrefixOp);
node.op_token = arg1;
node.op = Node.PrefixOp.Op{ .PtrType = Node.PrefixOp.PtrInfo{ .allowzero_token = arg2, .align_info = if (arg3) |p| p.* else null, .const_token = arg4, .volatile_token = arg5 } };
node.rhs = arg6;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
160 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: BlockExpr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
return TerminalId.Expr;
},
161 => {
// Symbol: BlockExpr
var result: *Node = undefined;
// Symbol: Block
const arg1 = @intToPtr(?*Node.Block, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = &arg1.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .BlockExpr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.BlockExpr;
},
162 => {
// Symbol: BlockExpr
var result: *Node = undefined;
// Symbol: BlockLabel
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Block
const arg2 = @intToPtr(?*Node.Block, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = &arg2.base;
arg2.label = arg1;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .BlockExpr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.BlockExpr;
},
163 => {
// Symbol: Block
var result: *Node.Block = undefined;
// Symbol: LBrace
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: MaybeStatements
const arg2 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 2].item);
// Symbol: RBrace
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.Block);
node.lbrace = arg1;
node.statements = if (arg2) |p| p.* else NodeList.init(parser.allocator);
node.rbrace = arg3;
result = node;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Block };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Block;
},
164 => {
// Symbol: BlockLabel
var result: *Token = undefined;
// Symbol: Identifier
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Colon
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg1;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .BlockLabel };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.BlockLabel;
},
165 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Bang
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .ErrorUnion;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
166 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Identifier
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.Identifier);
node.token = arg1;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
167 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: CharLiteral
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.CharLiteral);
node.token = arg1;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
168 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: FloatLiteral
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.FloatLiteral);
node.token = arg1;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
169 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: IntegerLiteral
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.IntegerLiteral);
node.token = arg1;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
170 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: StringLiteral
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.StringLiteral);
node.token = arg1;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
171 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: MultilineStringLiteral
const arg1 = @intToPtr(?*TokenList, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.MultilineStringLiteral);
node.lines = arg1.*;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
172 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: MultilineCStringLiteral
const arg1 = @intToPtr(?*TokenList, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.MultilineStringLiteral);
node.lines = arg1.*;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
173 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Period
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Identifier
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.EnumLiteral);
node.dot = arg1;
node.name = arg2;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
174 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Keyword_error
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Period
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Identifier
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const err = try parser.createNode(Node.ErrorType);
err.token = arg1;
const name = try parser.createNode(Node.Identifier);
name.token = arg3;
const infix = try parser.createNode(Node.InfixOp);
infix.lhs = &err.base;
infix.op_token = arg2;
infix.op = .Period;
infix.rhs = &name.base;
result = &infix.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
175 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Keyword_error
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: LCurly
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: RBrace
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const error_set = try parser.createNode(Node.ErrorSetDecl);
error_set.error_token = arg1;
error_set.decls = NodeList.init(parser.allocator);
error_set.rbrace_token = arg3;
result = &error_set.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
176 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Keyword_error
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: LCurly
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: ErrorTagList
const arg3 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: MaybeComma
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item);
// Symbol: RBrace
const arg5 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 4;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const error_set = try parser.createNode(Node.ErrorSetDecl);
error_set.error_token = arg1;
error_set.decls = arg3.*;
error_set.rbrace_token = arg5;
result = &error_set.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
177 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Keyword_false
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.BoolLiteral);
node.token = arg1;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
178 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Keyword_true
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.BoolLiteral);
node.token = arg1;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
179 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Keyword_null
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.NullLiteral);
node.token = arg1;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
180 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Keyword_undefined
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.UndefinedLiteral);
node.token = arg1;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
181 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Keyword_unreachable
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.Unreachable);
node.token = arg1;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
182 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: SwitchExpr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
return TerminalId.Expr;
},
183 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: IfPrefix
const arg1 = @intToPtr(?*Node.If, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = &arg1.base;
arg1.body = arg2;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
184 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: IfPrefix
const arg1 = @intToPtr(?*Node.If, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: Expr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: Keyword_else
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: MaybePayload
const arg4 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item);
// Symbol: Expr
const arg5 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 4;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = &arg1.base;
const node = try parser.createNode(Node.Else);
node.else_token = arg3;
node.payload = arg4;
node.body = arg5;
arg1.body = arg2;
arg1.@"else" = node;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
185 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Builtin
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: LParen
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: MaybeExprList
const arg3 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 2].item);
// Symbol: RParen
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 3;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.BuiltinCall);
node.builtin_token = arg1;
node.params = if (arg3) |p| p.* else NodeList.init(parser.allocator);
node.rparen_token = arg4;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
186 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: FnProto
const arg1 = @intToPtr(?*Node.FnProto, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = &arg1.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
187 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: LBracket
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: RBracket
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 3;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.SuffixOp);
node.lhs = arg1;
node.op = Node.SuffixOp.Op{ .ArrayAccess = arg3 };
node.rtoken = arg4;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
188 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: LBracket
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Ellipsis2
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: RBracket
const arg5 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 4;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.SuffixOp);
node.lhs = arg1;
node.op = Node.SuffixOp.Op{ .Slice = Node.SuffixOp.Op.Slice{ .start = arg3, .end = null } };
node.rtoken = arg5;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
189 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 6].item).?;
// Symbol: LBracket
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: Ellipsis2
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Expr
const arg5 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: RBracket
const arg6 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 5;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.SuffixOp);
node.lhs = arg1;
node.op = Node.SuffixOp.Op{ .Slice = Node.SuffixOp.Op.Slice{ .start = arg3, .end = arg5 } };
node.rtoken = arg6;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
190 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Period
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Identifier
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const name = try parser.createNode(Node.Identifier);
name.token = arg3;
const infix = try parser.createNode(Node.InfixOp);
infix.lhs = arg1;
infix.op_token = arg2;
infix.op = .Period;
infix.rhs = &name.base;
result = &infix.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
191 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: PeriodAsterisk
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.SuffixOp);
node.lhs = arg1;
node.op = .Deref;
node.rtoken = arg2;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
192 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: PeriodQuestionMark
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.SuffixOp);
node.lhs = arg1;
node.op = .UnwrapOptional;
node.rtoken = arg2;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
193 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: LParen
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: MaybeExprList
const arg3 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 2].item);
// Symbol: RParen
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 3;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.SuffixOp);
node.lhs = arg1;
node.op = Node.SuffixOp.Op{ .Call = Node.SuffixOp.Op.Call{ .params = if (arg3) |p| p.* else NodeList.init(parser.allocator) } };
node.rtoken = arg4;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.Expr;
},
194 => {
// Symbol: Expr
var result: *Node = undefined;
// Symbol: ContainerDecl
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .Expr };
return TerminalId.Expr;
},
195 => {
// Symbol: ContainerDecl
var result: *Node = undefined;
// Symbol: ContainerDeclOp
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: LBrace
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: MaybeContainerMembers
const arg3 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 2].item);
// Symbol: RBrace
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 3;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.ContainerDecl);
node.kind_token = arg1;
node.init_arg_expr = .None;
node.lbrace_token = arg2;
node.fields_and_decls = if (arg3) |p| p.* else NodeList.init(parser.allocator);
node.rbrace_token = arg4;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ContainerDecl };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ContainerDecl;
},
196 => {
// Symbol: ContainerDecl
var result: *Node = undefined;
// Symbol: ExternPacked
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: ContainerDeclOp
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: LBrace
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: MaybeContainerMembers
const arg4 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 2].item);
// Symbol: RBrace
const arg5 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 4;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.ContainerDecl);
node.layout_token = arg1;
node.kind_token = arg2;
node.init_arg_expr = .None;
node.lbrace_token = arg3;
node.fields_and_decls = if (arg4) |p| p.* else NodeList.init(parser.allocator);
node.rbrace_token = arg5;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ContainerDecl };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ContainerDecl;
},
197 => {
// Symbol: ContainerDecl
var result: *Node = undefined;
// Symbol: Keyword_enum
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: ContainerDeclTypeType
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: LBrace
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: MaybeContainerMembers
const arg4 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 2].item);
// Symbol: RBrace
const arg5 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 4;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.ContainerDecl);
node.kind_token = arg1;
node.init_arg_expr = Node.ContainerDecl.InitArg{ .Type = arg2 };
node.lbrace_token = arg3;
node.fields_and_decls = if (arg4) |p| p.* else NodeList.init(parser.allocator);
node.rbrace_token = arg5;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ContainerDecl };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ContainerDecl;
},
198 => {
// Symbol: ContainerDecl
var result: *Node = undefined;
// Symbol: ExternPacked
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 6].item).?;
// Symbol: Keyword_enum
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: ContainerDeclTypeType
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: LBrace
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: MaybeContainerMembers
const arg5 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 2].item);
// Symbol: RBrace
const arg6 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 5;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.ContainerDecl);
node.layout_token = arg1;
node.kind_token = arg2;
node.init_arg_expr = Node.ContainerDecl.InitArg{ .Type = arg3 };
node.lbrace_token = arg4;
node.fields_and_decls = if (arg5) |p| p.* else NodeList.init(parser.allocator);
node.rbrace_token = arg6;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ContainerDecl };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ContainerDecl;
},
199 => {
// Symbol: ContainerDecl
var result: *Node = undefined;
// Symbol: Keyword_union
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: ContainerDeclTypeType
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: LBrace
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: MaybeContainerMembers
const arg4 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 2].item);
// Symbol: RBrace
const arg5 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 4;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.ContainerDecl);
node.kind_token = arg1;
node.init_arg_expr = Node.ContainerDecl.InitArg{ .Type = arg2 };
node.lbrace_token = arg3;
node.fields_and_decls = if (arg4) |p| p.* else NodeList.init(parser.allocator);
node.rbrace_token = arg5;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ContainerDecl };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ContainerDecl;
},
200 => {
// Symbol: ContainerDecl
var result: *Node = undefined;
// Symbol: ExternPacked
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 6].item).?;
// Symbol: Keyword_union
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: ContainerDeclTypeType
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: LBrace
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: MaybeContainerMembers
const arg5 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 2].item);
// Symbol: RBrace
const arg6 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 5;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.ContainerDecl);
node.layout_token = arg1;
node.kind_token = arg2;
node.init_arg_expr = Node.ContainerDecl.InitArg{ .Type = arg3 };
node.lbrace_token = arg4;
node.fields_and_decls = if (arg5) |p| p.* else NodeList.init(parser.allocator);
node.rbrace_token = arg6;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ContainerDecl };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ContainerDecl;
},
201 => {
// Symbol: ContainerDecl
var result: *Node = undefined;
// Symbol: Keyword_union
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: ContainerDeclTypeEnum
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 4].item);
// Symbol: LBrace
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: MaybeContainerMembers
const arg4 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 2].item);
// Symbol: RBrace
const arg5 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 4;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.ContainerDecl);
node.kind_token = arg1;
node.init_arg_expr = Node.ContainerDecl.InitArg{ .Enum = arg2 };
node.lbrace_token = arg3;
node.fields_and_decls = if (arg4) |p| p.* else NodeList.init(parser.allocator);
node.rbrace_token = arg5;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ContainerDecl };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ContainerDecl;
},
202 => {
// Symbol: ContainerDecl
var result: *Node = undefined;
// Symbol: ExternPacked
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 6].item).?;
// Symbol: Keyword_union
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: ContainerDeclTypeEnum
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 4].item);
// Symbol: LBrace
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: MaybeContainerMembers
const arg5 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 2].item);
// Symbol: RBrace
const arg6 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 5;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.ContainerDecl);
node.layout_token = arg1;
node.kind_token = arg2;
node.init_arg_expr = Node.ContainerDecl.InitArg{ .Enum = arg3 };
node.lbrace_token = arg4;
node.fields_and_decls = if (arg5) |p| p.* else NodeList.init(parser.allocator);
node.rbrace_token = arg6;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ContainerDecl };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ContainerDecl;
},
203 => {
// Symbol: ExternPacked
var result: *Token = undefined;
// Symbol: Keyword_extern
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ExternPacked };
return TerminalId.ExternPacked;
},
204 => {
// Symbol: ExternPacked
var result: *Token = undefined;
// Symbol: Keyword_packed
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ExternPacked };
return TerminalId.ExternPacked;
},
205 => {
// Symbol: SwitchExpr
var result: *Node = undefined;
// Symbol: Keyword_switch
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 8].item).?;
// Symbol: LParen
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 7].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 6].item).?;
// Symbol: RParen
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: LBrace
const arg5 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: SwitchProngList
const arg6 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: MaybeComma
const arg7 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item);
// Symbol: RBrace
const arg8 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 7;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.Switch);
node.switch_token = arg1;
node.expr = arg3;
node.cases = arg6.*;
node.rbrace = arg8;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .SwitchExpr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.SwitchExpr;
},
206 => {
// Symbol: String
var result: *Node = undefined;
// Symbol: StringLiteral
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.StringLiteral);
node.token = arg1;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .String };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.String;
},
207 => {
// Symbol: String
var result: *Node = undefined;
// Symbol: MultilineStringLiteral
const arg1 = @intToPtr(?*TokenList, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.MultilineStringLiteral);
node.lines = arg1.*;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .String };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.String;
},
208 => {
// Symbol: String
var result: *Node = undefined;
// Symbol: MultilineCStringLiteral
const arg1 = @intToPtr(?*TokenList, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.MultilineStringLiteral);
node.lines = arg1.*;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .String };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.String;
},
209 => {
// Symbol: AsmExpr
var result: *Node = undefined;
// Symbol: Keyword_asm
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: MaybeVolatile
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item);
// Symbol: LParen
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: String
const arg4 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: RParen
const arg5 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 4;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.Asm);
node.asm_token = arg1;
node.volatile_token = arg2;
node.template = arg4;
node.outputs = NodeList.init(parser.allocator);
node.inputs = NodeList.init(parser.allocator);
node.clobbers = NodeList.init(parser.allocator);
node.rparen = arg5;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AsmExpr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.AsmExpr;
},
210 => {
// Symbol: AsmExpr
var result: *Node = undefined;
// Symbol: Keyword_asm
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 6].item).?;
// Symbol: MaybeVolatile
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item);
// Symbol: LParen
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: String
const arg4 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: AsmOutput
const arg5 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 2].item);
// Symbol: RParen
const arg6 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 5;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.Asm);
node.asm_token = arg1;
node.volatile_token = arg2;
node.template = arg4;
node.outputs = if (arg5) |p| p.* else NodeList.init(parser.allocator);
node.inputs = NodeList.init(parser.allocator);
node.clobbers = NodeList.init(parser.allocator);
node.rparen = arg6;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AsmExpr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.AsmExpr;
},
211 => {
// Symbol: AsmExpr
var result: *Node = undefined;
// Symbol: Keyword_asm
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 7].item).?;
// Symbol: MaybeVolatile
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 6].item);
// Symbol: LParen
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: String
const arg4 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: AsmOutput
const arg5 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 3].item);
// Symbol: AsmInput
const arg6 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 2].item);
// Symbol: RParen
const arg7 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 6;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.Asm);
node.asm_token = arg1;
node.volatile_token = arg2;
node.template = arg4;
node.outputs = if (arg5) |p| p.* else NodeList.init(parser.allocator);
node.inputs = if (arg6) |p| p.* else NodeList.init(parser.allocator);
node.clobbers = NodeList.init(parser.allocator);
node.rparen = arg7;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AsmExpr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.AsmExpr;
},
212 => {
// Symbol: AsmExpr
var result: *Node = undefined;
// Symbol: Keyword_asm
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 8].item).?;
// Symbol: MaybeVolatile
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 7].item);
// Symbol: LParen
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 6].item).?;
// Symbol: String
const arg4 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: AsmOutput
const arg5 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 4].item);
// Symbol: AsmInput
const arg6 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 3].item);
// Symbol: AsmClobber
const arg7 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 2].item);
// Symbol: RParen
const arg8 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 7;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.Asm);
node.asm_token = arg1;
node.volatile_token = arg2;
node.template = arg4;
node.outputs = if (arg5) |p| p.* else NodeList.init(parser.allocator);
node.inputs = if (arg6) |p| p.* else NodeList.init(parser.allocator);
node.clobbers = if (arg7) |p| p.* else NodeList.init(parser.allocator);
node.rparen = arg8;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AsmExpr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.AsmExpr;
},
213 => {
// Symbol: AsmOutput
var result: ?*NodeList = null;
// Symbol: Colon
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = null;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AsmOutput };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.AsmOutput;
},
214 => {
// Symbol: AsmOutput
var result: ?*NodeList = null;
// Symbol: Colon
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: AsmOutputList
const arg2 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg2;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AsmOutput };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.AsmOutput;
},
215 => {
// Symbol: AsmOutputItem
var result: *Node = undefined;
// Symbol: LBracket
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 7].item).?;
// Symbol: Identifier
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 6].item).?;
// Symbol: RBracket
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: String
const arg4 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: LParen
const arg5 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Identifier
const arg6 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: RParen
const arg7 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 6;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const name = try parser.createNode(Node.Identifier);
name.token = arg2;
const variable = try parser.createNode(Node.Identifier);
variable.token = arg6;
const node = try parser.createNode(Node.AsmOutput);
node.lbracket = arg1;
node.symbolic_name = &name.base;
node.constraint = arg4;
node.kind = Node.AsmOutput.Kind{ .Variable = variable };
node.rparen = arg7;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AsmOutputItem };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.AsmOutputItem;
},
216 => {
// Symbol: AsmOutputItem
var result: *Node = undefined;
// Symbol: LBracket
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 8].item).?;
// Symbol: Identifier
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 7].item).?;
// Symbol: RBracket
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 6].item).?;
// Symbol: String
const arg4 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: LParen
const arg5 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: MinusAngleBracketRight
const arg6 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Expr
const arg7 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: RParen
const arg8 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 7;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const name = try parser.createNode(Node.Identifier);
name.token = arg2;
const node = try parser.createNode(Node.AsmOutput);
node.lbracket = arg1;
node.symbolic_name = &name.base;
node.constraint = arg4;
node.kind = Node.AsmOutput.Kind{ .Return = arg7 };
node.rparen = arg8;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AsmOutputItem };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.AsmOutputItem;
},
217 => {
// Symbol: AsmInput
var result: ?*NodeList = null;
// Symbol: Colon
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = null;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AsmInput };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.AsmInput;
},
218 => {
// Symbol: AsmInput
var result: ?*NodeList = null;
// Symbol: Colon
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: AsmInputList
const arg2 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg2;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AsmInput };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.AsmInput;
},
219 => {
// Symbol: AsmInputItem
var result: *Node = undefined;
// Symbol: LBracket
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 7].item).?;
// Symbol: Identifier
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 6].item).?;
// Symbol: RBracket
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: String
const arg4 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: LParen
const arg5 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Expr
const arg6 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: RParen
const arg7 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 6;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const name = try parser.createNode(Node.Identifier);
name.token = arg2;
const node = try parser.createNode(Node.AsmInput);
node.lbracket = arg1;
node.symbolic_name = &name.base;
node.constraint = arg4;
node.expr = arg6;
node.rparen = arg7;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AsmInputItem };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.AsmInputItem;
},
220 => {
// Symbol: AsmClobber
var result: ?*NodeList = null;
// Symbol: Colon
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = null;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AsmClobber };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.AsmClobber;
},
221 => {
// Symbol: AsmClobber
var result: ?*NodeList = null;
// Symbol: Colon
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: StringList
const arg2 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg2;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AsmClobber };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.AsmClobber;
},
222 => {
// Symbol: BreakLabel
var result: *Node = undefined;
// Symbol: Colon
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Identifier
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.Identifier);
node.token = arg2;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .BreakLabel };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.BreakLabel;
},
223 => {
// Symbol: MaybeLinkSection
var result: ?*Node = null;
// Push the result of the reduce action
try parser.stack.append(StackItem{ .item = @ptrToInt(result), .state = state, .value = StackValue{ .Terminal = .MaybeLinkSection } });
return TerminalId.MaybeLinkSection;
},
224 => {
// Symbol: MaybeLinkSection
var result: ?*Node = null;
// Symbol: Keyword_linksection
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: LParen
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: RParen
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 3;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg3;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MaybeLinkSection };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.MaybeLinkSection;
},
225 => {
// Symbol: FnCC
var result: *Token = undefined;
// Symbol: Keyword_nakedcc
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .FnCC };
return TerminalId.FnCC;
},
226 => {
// Symbol: FnCC
var result: *Token = undefined;
// Symbol: Keyword_stdcallcc
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .FnCC };
return TerminalId.FnCC;
},
227 => {
// Symbol: FnCC
var result: *Token = undefined;
// Symbol: Keyword_extern
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .FnCC };
return TerminalId.FnCC;
},
228 => {
// Symbol: FnCC
var result: *Token = undefined;
// Symbol: Keyword_async
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .FnCC };
return TerminalId.FnCC;
},
229 => {
// Symbol: ParamDecl
var result: *Node.ParamDecl = undefined;
// Symbol: MaybeNoalias
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item);
// Symbol: ParamType
const arg2 = @intToPtr(?*Node.ParamDecl, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg2;
arg2.noalias_token = arg1;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ParamDecl };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ParamDecl;
},
230 => {
// Symbol: ParamDecl
var result: *Node.ParamDecl = undefined;
// Symbol: MaybeNoalias
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item);
// Symbol: Identifier
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Colon
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: ParamType
const arg4 = @intToPtr(?*Node.ParamDecl, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 3;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg4;
arg4.noalias_token = arg1;
arg4.name_token = arg2;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ParamDecl };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ParamDecl;
},
231 => {
// Symbol: ParamDecl
var result: *Node.ParamDecl = undefined;
// Symbol: MaybeNoalias
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item);
// Symbol: Keyword_comptime
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: Identifier
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Colon
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: ParamType
const arg5 = @intToPtr(?*Node.ParamDecl, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 4;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg5;
arg5.noalias_token = arg1;
arg5.comptime_token = arg2;
arg5.name_token = arg3;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ParamDecl };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ParamDecl;
},
232 => {
// Symbol: ParamType
var result: *Node.ParamDecl = undefined;
// Symbol: Keyword_var
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const vtype = try parser.createNode(Node.VarType);
vtype.token = arg1;
const node = try parser.createNode(Node.ParamDecl);
node.type_node = &vtype.base;
result = node;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ParamType };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ParamType;
},
233 => {
// Symbol: ParamType
var result: *Node.ParamDecl = undefined;
// Symbol: Ellipsis3
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.ParamDecl);
node.var_args_token = arg1;
result = node;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ParamType };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ParamType;
},
234 => {
// Symbol: ParamType
var result: *Node.ParamDecl = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.ParamDecl);
node.type_node = arg1;
result = node;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ParamType };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ParamType;
},
235 => {
// Symbol: IfPrefix
var result: *Node.If = undefined;
// Symbol: Keyword_if
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: LParen
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: RParen
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: MaybePtrPayload
const arg5 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item);
// Adjust the parse stack and current state
parser.stack.len -= 4;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.If);
node.if_token = arg1;
node.condition = arg3;
node.payload = arg5;
result = node;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .IfPrefix };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.IfPrefix;
},
236 => {
// Symbol: ForPrefix
var result: *Node.For = undefined;
// Symbol: Keyword_for
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: LParen
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: RParen
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: PtrIndexPayload
const arg5 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 4;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.For);
node.for_token = arg1;
node.array_expr = arg3;
node.payload = arg5;
result = node;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ForPrefix };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ForPrefix;
},
237 => {
// Symbol: WhilePrefix
var result: *Node.While = undefined;
// Symbol: Keyword_while
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: LParen
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: RParen
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: MaybePtrPayload
const arg5 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item);
// Adjust the parse stack and current state
parser.stack.len -= 4;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.While);
node.while_token = arg1;
node.condition = arg3;
node.payload = arg5;
result = node;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .WhilePrefix };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.WhilePrefix;
},
238 => {
// Symbol: WhilePrefix
var result: *Node.While = undefined;
// Symbol: Keyword_while
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 9].item).?;
// Symbol: LParen
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 8].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 7].item).?;
// Symbol: RParen
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 6].item).?;
// Symbol: MaybePtrPayload
const arg5 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 5].item);
// Symbol: Colon
const arg6 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: LParen
const arg7 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: AssignExpr
const arg8 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: RParen
const arg9 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 8;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.While);
node.while_token = arg1;
node.condition = arg3;
node.payload = arg5;
node.continue_expr = arg8;
result = node;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .WhilePrefix };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.WhilePrefix;
},
239 => {
// Symbol: MaybePayload
var result: ?*Node = null;
// Push the result of the reduce action
try parser.stack.append(StackItem{ .item = @ptrToInt(result), .state = state, .value = StackValue{ .Terminal = .MaybePayload } });
return TerminalId.MaybePayload;
},
240 => {
// Symbol: MaybePayload
var result: ?*Node = null;
// Symbol: Pipe
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Identifier
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Pipe
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const name = try parser.createNode(Node.Identifier);
name.token = arg2;
const node = try parser.createNode(Node.Payload);
node.lpipe = arg1;
node.error_symbol = &name.base;
node.rpipe = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MaybePayload };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.MaybePayload;
},
241 => {
// Symbol: MaybePtrPayload
var result: ?*Node = null;
// Push the result of the reduce action
try parser.stack.append(StackItem{ .item = @ptrToInt(result), .state = state, .value = StackValue{ .Terminal = .MaybePtrPayload } });
return TerminalId.MaybePtrPayload;
},
242 => {
// Symbol: MaybePtrPayload
var result: ?*Node = null;
// Symbol: Pipe
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Identifier
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Pipe
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const name = try parser.createNode(Node.Identifier);
name.token = arg2;
const node = try parser.createNode(Node.PointerPayload);
node.lpipe = arg1;
node.value_symbol = &name.base;
node.rpipe = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MaybePtrPayload };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.MaybePtrPayload;
},
243 => {
// Symbol: MaybePtrPayload
var result: ?*Node = null;
// Symbol: Pipe
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: Asterisk
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Identifier
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Pipe
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 3;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const name = try parser.createNode(Node.Identifier);
name.token = arg3;
const node = try parser.createNode(Node.PointerPayload);
node.lpipe = arg1;
node.ptr_token = arg2;
node.value_symbol = &name.base;
node.rpipe = arg4;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MaybePtrPayload };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.MaybePtrPayload;
},
244 => {
// Symbol: PtrIndexPayload
var result: *Node = undefined;
// Symbol: Pipe
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Identifier
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Pipe
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const name = try parser.createNode(Node.Identifier);
name.token = arg2;
const node = try parser.createNode(Node.PointerIndexPayload);
node.lpipe = arg1;
node.value_symbol = &name.base;
node.rpipe = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .PtrIndexPayload };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.PtrIndexPayload;
},
245 => {
// Symbol: PtrIndexPayload
var result: *Node = undefined;
// Symbol: Pipe
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: Asterisk
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Identifier
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Pipe
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 3;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const name = try parser.createNode(Node.Identifier);
name.token = arg3;
const node = try parser.createNode(Node.PointerIndexPayload);
node.lpipe = arg1;
node.ptr_token = arg2;
node.value_symbol = &name.base;
node.rpipe = arg4;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .PtrIndexPayload };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.PtrIndexPayload;
},
246 => {
// Symbol: PtrIndexPayload
var result: *Node = undefined;
// Symbol: Pipe
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: Identifier
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: Comma
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Identifier
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Pipe
const arg5 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 4;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const name = try parser.createNode(Node.Identifier);
name.token = arg2;
const index = try parser.createNode(Node.Identifier);
index.token = arg4;
const node = try parser.createNode(Node.PointerIndexPayload);
node.lpipe = arg1;
node.value_symbol = &name.base;
node.index_symbol = &index.base;
node.rpipe = arg5;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .PtrIndexPayload };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.PtrIndexPayload;
},
247 => {
// Symbol: PtrIndexPayload
var result: *Node = undefined;
// Symbol: Pipe
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 6].item).?;
// Symbol: Asterisk
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: Identifier
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: Comma
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Identifier
const arg5 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Pipe
const arg6 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 5;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const name = try parser.createNode(Node.Identifier);
name.token = arg3;
const index = try parser.createNode(Node.Identifier);
index.token = arg5;
const node = try parser.createNode(Node.PointerIndexPayload);
node.lpipe = arg1;
node.ptr_token = arg2;
node.value_symbol = &name.base;
node.index_symbol = &index.base;
node.rpipe = arg6;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .PtrIndexPayload };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.PtrIndexPayload;
},
248 => {
// Symbol: SwitchProng
var result: *Node = undefined;
// Symbol: SwitchCase
const arg1 = @intToPtr(?*Node.SwitchCase, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: EqualAngleBracketRight
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: MaybePtrPayload
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item);
// Symbol: AssignExpr
const arg4 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 3;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = &arg1.base;
arg1.arrow_token = arg2;
arg1.payload = arg3;
arg1.expr = arg4;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .SwitchProng };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.SwitchProng;
},
249 => {
// Symbol: SwitchCase
var result: *Node.SwitchCase = undefined;
// Symbol: Keyword_else
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const else_node = try parser.createNode(Node.SwitchElse);
else_node.token = arg1;
const node = try parser.createNode(Node.SwitchCase);
node.items = NodeList.init(parser.allocator);
try node.items.append(&else_node.base);
result = node;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .SwitchCase };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.SwitchCase;
},
250 => {
// Symbol: SwitchCase
var result: *Node.SwitchCase = undefined;
// Symbol: SwitchItems
const arg1 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: MaybeComma
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item);
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.SwitchCase);
node.items = arg1.*;
result = node;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .SwitchCase };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.SwitchCase;
},
251 => {
// Symbol: SwitchItems
var result: *NodeList = undefined;
// Symbol: SwitchItem
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = try parser.createListWithNode(NodeList, arg1);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .SwitchItems };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.SwitchItems;
},
252 => {
// Symbol: SwitchItems
var result: *NodeList = undefined;
// Symbol: SwitchItems
const arg1 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Comma
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: SwitchItem
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg1;
try arg1.append(arg3);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .SwitchItems };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.SwitchItems;
},
253 => {
// Symbol: SwitchItem
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .SwitchItem };
return TerminalId.SwitchItem;
},
254 => {
// Symbol: SwitchItem
var result: *Node = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Ellipsis3
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.InfixOp);
node.lhs = arg1;
node.op_token = arg2;
node.op = .Range;
node.rhs = arg3;
result = &node.base;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .SwitchItem };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.SwitchItem;
},
255 => {
// Symbol: MaybeVolatile
var result: ?*Token = null;
// Push the result of the reduce action
try parser.stack.append(StackItem{ .item = @ptrToInt(result), .state = state, .value = StackValue{ .Terminal = .MaybeVolatile } });
return TerminalId.MaybeVolatile;
},
256 => {
// Symbol: MaybeVolatile
var result: ?*Token = null;
// Symbol: Keyword_volatile
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MaybeVolatile };
return TerminalId.MaybeVolatile;
},
257 => {
// Symbol: MaybeAllowzero
var result: ?*Token = null;
// Push the result of the reduce action
try parser.stack.append(StackItem{ .item = @ptrToInt(result), .state = state, .value = StackValue{ .Terminal = .MaybeAllowzero } });
return TerminalId.MaybeAllowzero;
},
258 => {
// Symbol: MaybeAllowzero
var result: ?*Token = null;
// Symbol: Keyword_allowzero
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MaybeAllowzero };
return TerminalId.MaybeAllowzero;
},
259 => {
// Symbol: ContainerDeclTypeEnum
var result: ?*Node = null;
// Symbol: LParen
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Keyword_enum
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: RParen
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ContainerDeclTypeEnum };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ContainerDeclTypeEnum;
},
260 => {
// Symbol: ContainerDeclTypeEnum
var result: ?*Node = null;
// Symbol: LParen
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 6].item).?;
// Symbol: Keyword_enum
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: LParen
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: Expr
const arg4 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: RParen
const arg5 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: RParen
const arg6 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 5;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg4;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ContainerDeclTypeEnum };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ContainerDeclTypeEnum;
},
261 => {
// Symbol: ContainerDeclTypeType
var result: *Node = undefined;
// Symbol: LParen
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Expr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: RParen
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg2;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ContainerDeclTypeType };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ContainerDeclTypeType;
},
262 => {
// Symbol: ContainerDeclOp
var result: *Token = undefined;
// Symbol: Keyword_struct
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ContainerDeclOp };
return TerminalId.ContainerDeclOp;
},
263 => {
// Symbol: ContainerDeclOp
var result: *Token = undefined;
// Symbol: Keyword_union
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ContainerDeclOp };
return TerminalId.ContainerDeclOp;
},
264 => {
// Symbol: ContainerDeclOp
var result: *Token = undefined;
// Symbol: Keyword_enum
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ContainerDeclOp };
return TerminalId.ContainerDeclOp;
},
265 => {
// Symbol: MaybeByteAlign
var result: ?*Node = null;
// Push the result of the reduce action
try parser.stack.append(StackItem{ .item = @ptrToInt(result), .state = state, .value = StackValue{ .Terminal = .MaybeByteAlign } });
return TerminalId.MaybeByteAlign;
},
266 => {
// Symbol: MaybeByteAlign
var result: ?*Node = null;
// Symbol: Keyword_align
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: LParen
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: RParen
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 3;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg3;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MaybeByteAlign };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.MaybeByteAlign;
},
267 => {
// Symbol: MaybeAlign
var result: ?*Node.PrefixOp.PtrInfo.Align = null;
// Push the result of the reduce action
try parser.stack.append(StackItem{ .item = @ptrToInt(result), .state = state, .value = StackValue{ .Terminal = .MaybeAlign } });
return TerminalId.MaybeAlign;
},
268 => {
// Symbol: MaybeAlign
var result: ?*Node.PrefixOp.PtrInfo.Align = null;
// Symbol: Keyword_align
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: LParen
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: RParen
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 3;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const value = try parser.createTemporary(Node.PrefixOp.PtrInfo.Align);
value.node = arg3;
result = value;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MaybeAlign };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.MaybeAlign;
},
269 => {
// Symbol: MaybeAlign
var result: ?*Node.PrefixOp.PtrInfo.Align = null;
// Symbol: Keyword_align
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 8].item).?;
// Symbol: LParen
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 7].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 6].item).?;
// Symbol: Colon
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: IntegerLiteral
const arg5 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: Colon
const arg6 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: IntegerLiteral
const arg7 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: RParen
const arg8 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 7;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const start = try parser.createNode(Node.IntegerLiteral);
start.token = arg5;
const end = try parser.createNode(Node.IntegerLiteral);
end.token = arg7;
const value = try parser.createTemporary(Node.PrefixOp.PtrInfo.Align);
value.node = arg3;
value.bit_range = Node.PrefixOp.PtrInfo.Align.BitRange{ .start = &start.base, .end = &end.base };
result = value;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MaybeAlign };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.MaybeAlign;
},
270 => {
// Symbol: MaybeAlign
var result: ?*Node.PrefixOp.PtrInfo.Align = null;
// Symbol: Keyword_align
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 8].item).?;
// Symbol: LParen
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 7].item).?;
// Symbol: Identifier
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 6].item).?;
// Symbol: Colon
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: IntegerLiteral
const arg5 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: Colon
const arg6 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: IntegerLiteral
const arg7 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: RParen
const arg8 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 7;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.Identifier);
node.token = arg3;
const start = try parser.createNode(Node.IntegerLiteral);
start.token = arg5;
const end = try parser.createNode(Node.IntegerLiteral);
end.token = arg7;
const value = try parser.createTemporary(Node.PrefixOp.PtrInfo.Align);
value.node = &node.base;
value.bit_range = Node.PrefixOp.PtrInfo.Align.BitRange{ .start = &start.base, .end = &end.base };
result = value;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MaybeAlign };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.MaybeAlign;
},
271 => {
// Symbol: ErrorTagList
var result: *NodeList = undefined;
// Symbol: MaybeDocComment
const arg1 = @intToPtr(?*Node.DocComment, parser.stack.items[parser.stack.len - 2].item);
// Symbol: Identifier
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.ErrorTag);
node.doc_comments = arg1;
node.name_token = arg2;
result = try parser.createListWithNode(NodeList, &node.base);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ErrorTagList };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ErrorTagList;
},
272 => {
// Symbol: ErrorTagList
var result: *NodeList = undefined;
// Symbol: ErrorTagList
const arg1 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: Comma
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: MaybeDocComment
const arg3 = @intToPtr(?*Node.DocComment, parser.stack.items[parser.stack.len - 2].item);
// Symbol: Identifier
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 3;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg1;
const node = try parser.createNode(Node.ErrorTag);
node.doc_comments = arg3;
node.name_token = arg4;
try arg1.append(&node.base);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ErrorTagList };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ErrorTagList;
},
273 => {
// Symbol: SwitchProngList
var result: *NodeList = undefined;
// Symbol: SwitchProng
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = try parser.createListWithNode(NodeList, arg1);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .SwitchProngList };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.SwitchProngList;
},
274 => {
// Symbol: SwitchProngList
var result: *NodeList = undefined;
// Symbol: SwitchProngList
const arg1 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Comma
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: SwitchProng
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg1;
try arg1.append(arg3);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .SwitchProngList };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.SwitchProngList;
},
275 => {
// Symbol: AsmOutputList
var result: *NodeList = undefined;
// Symbol: AsmOutputItem
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = try parser.createListWithNode(NodeList, arg1);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AsmOutputList };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.AsmOutputList;
},
276 => {
// Symbol: AsmOutputList
var result: *NodeList = undefined;
// Symbol: AsmOutputList
const arg1 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Comma
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: AsmOutputItem
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg1;
try arg1.append(arg3);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AsmOutputList };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.AsmOutputList;
},
277 => {
// Symbol: AsmInputList
var result: *NodeList = undefined;
// Symbol: AsmInputItem
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = try parser.createListWithNode(NodeList, arg1);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AsmInputList };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.AsmInputList;
},
278 => {
// Symbol: AsmInputList
var result: *NodeList = undefined;
// Symbol: AsmInputList
const arg1 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Comma
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: AsmInputItem
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg1;
try arg1.append(arg3);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .AsmInputList };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.AsmInputList;
},
279 => {
// Symbol: StringList
var result: *NodeList = undefined;
// Symbol: StringLiteral
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.StringLiteral);
node.token = arg1;
result = try parser.createListWithNode(NodeList, &node.base);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .StringList };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.StringList;
},
280 => {
// Symbol: StringList
var result: *NodeList = undefined;
// Symbol: StringList
const arg1 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Comma
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: StringLiteral
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg1;
const node = try parser.createNode(Node.StringLiteral);
node.token = arg3;
try arg1.append(&node.base);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .StringList };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.StringList;
},
281 => {
// Symbol: MaybeParamDeclList
var result: ?*NodeList = null;
// Push the result of the reduce action
try parser.stack.append(StackItem{ .item = @ptrToInt(result), .state = state, .value = StackValue{ .Terminal = .MaybeParamDeclList } });
return TerminalId.MaybeParamDeclList;
},
282 => {
// Symbol: MaybeParamDeclList
var result: *NodeList = undefined;
// Symbol: ParamDeclList
const arg1 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: MaybeComma
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item);
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg1;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MaybeParamDeclList };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.MaybeParamDeclList;
},
283 => {
// Symbol: ParamDeclList
var result: *NodeList = undefined;
// Symbol: MaybeDocComment
const arg1 = @intToPtr(?*Node.DocComment, parser.stack.items[parser.stack.len - 2].item);
// Symbol: ParamDecl
const arg2 = @intToPtr(?*Node.ParamDecl, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
arg2.doc_comments = arg1;
result = try parser.createListWithNode(NodeList, &arg2.base);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ParamDeclList };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ParamDeclList;
},
284 => {
// Symbol: ParamDeclList
var result: *NodeList = undefined;
// Symbol: ParamDeclList
const arg1 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: Comma
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: MaybeDocComment
const arg3 = @intToPtr(?*Node.DocComment, parser.stack.items[parser.stack.len - 2].item);
// Symbol: ParamDecl
const arg4 = @intToPtr(?*Node.ParamDecl, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 3;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg1;
arg4.doc_comments = arg3;
try arg1.append(&arg4.base);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ParamDeclList };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ParamDeclList;
},
285 => {
// Symbol: MaybeExprList
var result: ?*NodeList = null;
// Push the result of the reduce action
try parser.stack.append(StackItem{ .item = @ptrToInt(result), .state = state, .value = StackValue{ .Terminal = .MaybeExprList } });
return TerminalId.MaybeExprList;
},
286 => {
// Symbol: MaybeExprList
var result: ?*NodeList = null;
// Symbol: ExprList
const arg1 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: MaybeComma
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item);
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg1;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MaybeExprList };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.MaybeExprList;
},
287 => {
// Symbol: ExprList
var result: *NodeList = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = try parser.createListWithNode(NodeList, arg1);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ExprList };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ExprList;
},
288 => {
// Symbol: ExprList
var result: *NodeList = undefined;
// Symbol: ExprList
const arg1 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Comma
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg1;
try arg1.append(arg3);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .ExprList };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.ExprList;
},
289 => {
// Symbol: InitList
var result: *NodeList = undefined;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = try parser.createListWithNode(NodeList, arg1);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .InitList };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.InitList;
},
290 => {
// Symbol: InitList
var result: *NodeList = undefined;
// Symbol: Period
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: Identifier
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Equal
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg4 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 3;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
const node = try parser.createNode(Node.FieldInitializer);
node.period_token = arg1;
node.name_token = arg2;
node.expr = arg4;
result = try parser.createListWithNode(NodeList, &node.base);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .InitList };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.InitList;
},
291 => {
// Symbol: InitList
var result: *NodeList = undefined;
// Symbol: InitList
const arg1 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Comma
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg3 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 2;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg1;
try arg1.append(arg3);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .InitList };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.InitList;
},
292 => {
// Symbol: InitList
var result: *NodeList = undefined;
// Symbol: InitList
const arg1 = @intToPtr(?*NodeList, parser.stack.items[parser.stack.len - 6].item).?;
// Symbol: Comma
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 5].item).?;
// Symbol: Period
const arg3 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 4].item).?;
// Symbol: Identifier
const arg4 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 3].item).?;
// Symbol: Equal
const arg5 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg6 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 5;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg1;
const node = try parser.createNode(Node.FieldInitializer);
node.period_token = arg3;
node.name_token = arg4;
node.expr = arg6;
try arg1.append(&node.base);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .InitList };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.InitList;
},
293 => {
// Symbol: MaybePub
var result: ?*Token = null;
// Push the result of the reduce action
try parser.stack.append(StackItem{ .item = @ptrToInt(result), .state = state, .value = StackValue{ .Terminal = .MaybePub } });
return TerminalId.MaybePub;
},
294 => {
// Symbol: MaybePub
var result: ?*Token = null;
// Symbol: Keyword_pub
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MaybePub };
return TerminalId.MaybePub;
},
295 => {
// Symbol: MaybeColonTypeExpr
var result: ?*Node = null;
// Push the result of the reduce action
try parser.stack.append(StackItem{ .item = @ptrToInt(result), .state = state, .value = StackValue{ .Terminal = .MaybeColonTypeExpr } });
return TerminalId.MaybeColonTypeExpr;
},
296 => {
// Symbol: MaybeColonTypeExpr
var result: ?*Node = null;
// Symbol: Colon
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: Expr
const arg2 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg2;
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MaybeColonTypeExpr };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.MaybeColonTypeExpr;
},
297 => {
// Symbol: MaybeExpr
var result: ?*Node = null;
// Push the result of the reduce action
try parser.stack.append(StackItem{ .item = @ptrToInt(result), .state = state, .value = StackValue{ .Terminal = .MaybeExpr } });
return TerminalId.MaybeExpr;
},
298 => {
// Symbol: MaybeExpr
var result: ?*Node = null;
// Symbol: Expr
const arg1 = @intToPtr(?*Node, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MaybeExpr };
return TerminalId.MaybeExpr;
},
299 => {
// Symbol: MaybeNoalias
var result: ?*Token = null;
// Push the result of the reduce action
try parser.stack.append(StackItem{ .item = @ptrToInt(result), .state = state, .value = StackValue{ .Terminal = .MaybeNoalias } });
return TerminalId.MaybeNoalias;
},
300 => {
// Symbol: MaybeNoalias
var result: ?*Token = null;
// Symbol: Keyword_noalias
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MaybeNoalias };
return TerminalId.MaybeNoalias;
},
301 => {
// Symbol: MaybeInline
var result: ?*Token = null;
// Push the result of the reduce action
try parser.stack.append(StackItem{ .item = @ptrToInt(result), .state = state, .value = StackValue{ .Terminal = .MaybeInline } });
return TerminalId.MaybeInline;
},
302 => {
// Symbol: MaybeInline
var result: ?*Token = null;
// Symbol: Keyword_inline
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MaybeInline };
return TerminalId.MaybeInline;
},
303 => {
// Symbol: MaybeIdentifier
var result: ?*Token = null;
// Push the result of the reduce action
try parser.stack.append(StackItem{ .item = @ptrToInt(result), .state = state, .value = StackValue{ .Terminal = .MaybeIdentifier } });
return TerminalId.MaybeIdentifier;
},
304 => {
// Symbol: MaybeIdentifier
var result: ?*Token = null;
// Symbol: Identifier
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MaybeIdentifier };
return TerminalId.MaybeIdentifier;
},
305 => {
// Symbol: MaybeComma
var result: ?*Token = null;
// Push the result of the reduce action
try parser.stack.append(StackItem{ .item = @ptrToInt(result), .state = state, .value = StackValue{ .Terminal = .MaybeComma } });
return TerminalId.MaybeComma;
},
306 => {
// Symbol: MaybeComma
var result: ?*Token = null;
// Symbol: Comma
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MaybeComma };
return TerminalId.MaybeComma;
},
307 => {
// Symbol: MaybeConst
var result: ?*Token = null;
// Push the result of the reduce action
try parser.stack.append(StackItem{ .item = @ptrToInt(result), .state = state, .value = StackValue{ .Terminal = .MaybeConst } });
return TerminalId.MaybeConst;
},
308 => {
// Symbol: MaybeConst
var result: ?*Token = null;
// Symbol: Keyword_const
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MaybeConst };
return TerminalId.MaybeConst;
},
309 => {
// Symbol: MultilineStringLiteral
var result: *TokenList = undefined;
// Symbol: LineString
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = try parser.createListWithToken(TokenList, arg1);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MultilineStringLiteral };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.MultilineStringLiteral;
},
310 => {
// Symbol: MultilineStringLiteral
var result: *TokenList = undefined;
// Symbol: MultilineStringLiteral
const arg1 = @intToPtr(?*TokenList, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: LineString
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg1;
try arg1.append(arg2);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MultilineStringLiteral };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.MultilineStringLiteral;
},
311 => {
// Symbol: MultilineCStringLiteral
var result: *TokenList = undefined;
// Symbol: LineCString
const arg1 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = try parser.createListWithToken(TokenList, arg1);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MultilineCStringLiteral };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.MultilineCStringLiteral;
},
312 => {
// Symbol: MultilineCStringLiteral
var result: *TokenList = undefined;
// Symbol: MultilineCStringLiteral
const arg1 = @intToPtr(?*TokenList, parser.stack.items[parser.stack.len - 2].item).?;
// Symbol: LineCString
const arg2 = @intToPtr(?*Token, parser.stack.items[parser.stack.len - 1].item).?;
// Adjust the parse stack and current state
parser.stack.len -= 1;
parser.state = parser.stack.items[parser.stack.len - 1].state;
{
result = arg1;
try arg1.append(arg2);
}
parser.stack.items[parser.stack.len - 1].state = parser.state;
parser.stack.items[parser.stack.len - 1].value = StackValue{ .Terminal = .MultilineCStringLiteral };
parser.stack.items[parser.stack.len - 1].item = @ptrToInt(result);
return TerminalId.MultilineCStringLiteral;
},
else => unreachable,
}
return error.ReduceError;
} | zig/zig_grammar.actions.zig |
const bs = @import("./bitstream.zig");
const bits = @import("./bits.zig");
const std = @import("std");
const expect = std.testing.expect;
test "istream_basic" {
var is: bs.istream_t = undefined;
const init = [_]u8{0x47}; // 0100 0111
const arr: [9]u8 = [_]u8{ 0x45, 0x48 } ++ [_]u8{0x00} ** 7; // 01000101 01001000
bs.istream_init(&is, &init, 1);
try expect(bits.lsb(bs.istream_bits(&is), 1) == 1);
try expect(bs.istream_advance(&is, 1));
try expect(bits.lsb(bs.istream_bits(&is), 1) == 1);
try expect(bs.istream_advance(&is, 1));
try expect(bits.lsb(bs.istream_bits(&is), 1) == 1);
try expect(bs.istream_advance(&is, 1));
try expect(bits.lsb(bs.istream_bits(&is), 1) == 0);
try expect(bs.istream_advance(&is, 1));
try expect(bits.lsb(bs.istream_bits(&is), 1) == 0);
try expect(bs.istream_advance(&is, 1));
try expect(bits.lsb(bs.istream_bits(&is), 1) == 0);
try expect(bs.istream_advance(&is, 1));
try expect(bits.lsb(bs.istream_bits(&is), 1) == 1);
try expect(bs.istream_advance(&is, 1));
try expect(bits.lsb(bs.istream_bits(&is), 1) == 0);
try expect(bs.istream_advance(&is, 1));
try expect(!bs.istream_advance(&is, 1));
bs.istream_init(&is, &arr, 9);
try expect(bits.lsb(bs.istream_bits(&is), 3) == 0x5);
try expect(bs.istream_advance(&is, 3));
try expect(bs.istream_byte_align(&is) == &arr[1]);
try expect(bits.lsb(bs.istream_bits(&is), 4) == 0x8);
try expect(bs.istream_advance(&is, 4));
try expect(bs.istream_byte_align(&is) == &arr[2]);
bs.istream_init(&is, &arr, 9);
try expect(bs.istream_bytes_read(&is) == 0);
// Advance 8 bits, one at a time.
try expect(bs.istream_advance(&is, 1));
try expect(bs.istream_bytes_read(&is) == 1);
try expect(bs.istream_advance(&is, 1));
try expect(bs.istream_bytes_read(&is) == 1);
try expect(bs.istream_advance(&is, 1));
try expect(bs.istream_bytes_read(&is) == 1);
try expect(bs.istream_advance(&is, 1));
try expect(bs.istream_bytes_read(&is) == 1);
try expect(bs.istream_advance(&is, 1));
try expect(bs.istream_bytes_read(&is) == 1);
try expect(bs.istream_advance(&is, 1));
try expect(bs.istream_bytes_read(&is) == 1);
try expect(bs.istream_advance(&is, 1));
try expect(bs.istream_bytes_read(&is) == 1);
try expect(bs.istream_advance(&is, 1));
try expect(bs.istream_bytes_read(&is) == 1);
// Advance one more bit, into the second byte.
try expect(bs.istream_advance(&is, 1));
try expect(bs.istream_bytes_read(&is) == 2);
}
test "istream_min_bits" {
const data: [16]u8 = [_]u8{
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
};
var is: bs.istream_t = undefined;
var i: usize = 0;
var min_bits: u64 = 0;
bs.istream_init(&is, &data, data.len);
// Check that we always get at least ISTREAM_MIN_BITS back.
i = 0;
while (i < 64) : (i += 1) {
min_bits = bs.istream_bits(&is);
try expect(min_bits >= (@as(u64, 1) << bs.ISTREAM_MIN_BITS) - 1);
_ = bs.istream_advance(&is, 1);
}
}
test "ostream_basic" {
var os: bs.ostream_t = undefined;
var byte: [1]u8 = undefined;
var arr: [10]u8 = undefined;
bs.ostream_init(&os, &byte, 1);
// Write 1, 0, 1, 1011, 1
try expect(bs.ostream_write(&os, 0x1, 1));
try expect(bs.ostream_write(&os, 0x0, 1));
try expect(bs.ostream_write(&os, 0x1, 1));
try expect(bs.ostream_write(&os, 0xB, 4));
try expect(bs.ostream_write(&os, 0x1, 1));
try expect(bs.ostream_bytes_written(&os) == 1);
try expect(byte[0] == 0xDD); // 1101 1101
// Try to write some more. Not enough room.
try expect(!bs.ostream_write(&os, 0x7, 3));
bs.ostream_init(&os, &arr, 10);
// Write 60 bits so the first word is almost full.
try expect(bs.ostream_write(&os, 0x3ff, 10));
try expect(bs.ostream_write(&os, 0x3ff, 10));
try expect(bs.ostream_write(&os, 0x3ff, 10));
try expect(bs.ostream_write(&os, 0x3ff, 10));
try expect(bs.ostream_write(&os, 0x3ff, 10));
try expect(bs.ostream_write(&os, 0x3ff, 10));
// Write another 8 bits.
try expect(bs.ostream_write(&os, 0x12, 8));
try expect(arr[0] == 0xff);
try expect(arr[1] == 0xff);
try expect(arr[2] == 0xff);
try expect(arr[3] == 0xff);
try expect(arr[4] == 0xff);
try expect(arr[5] == 0xff);
try expect(arr[6] == 0xff);
try expect(arr[7] == 0x2f);
try expect(arr[8] == 0x01);
// Writing 0 bits works and doesn't do anything.
bs.ostream_init(&os, &byte, 1);
try expect(bs.ostream_write(&os, 0x1, 1));
try expect(bs.ostream_write(&os, 0x0, 0));
try expect(bs.ostream_write(&os, 0x0, 0));
try expect(bs.ostream_write(&os, 0x0, 0));
try expect(bs.ostream_write(&os, 0x1, 1));
try expect(byte[0] == 0x3);
// Try writing too much.
bs.ostream_init(&os, &arr, 10);
try expect(bs.ostream_write(&os, 0x1234, 16));
try expect(bs.ostream_write(&os, 0x1234, 16));
try expect(bs.ostream_write(&os, 0x1234, 16));
try expect(bs.ostream_write(&os, 0x1234, 16));
try expect(bs.ostream_write(&os, 0x1234, 16));
try expect(!bs.ostream_write(&os, 0x1, 1));
// Try writing too much.
bs.ostream_init(&os, &byte, 1);
try expect(!bs.ostream_write(&os, 0x1234, 16));
}
test "ostream_write_bytes_aligned" {
var os: bs.ostream_t = undefined;
var arr: [10]u8 = undefined;
bs.ostream_init(&os, &arr, 10);
// Write a few bits.
try expect(bs.ostream_write(&os, 0x7, 3));
try expect(bs.ostream_bit_pos(&os) == 3);
// Write some bytes aligned.
var foo = "foo";
try expect(bs.ostream_write_bytes_aligned(&os, foo, 3));
try expect(bs.ostream_bit_pos(&os) == 32);
try expect(arr[0] == 0x7);
try expect(arr[1] == 'f');
try expect(arr[2] == 'o');
try expect(arr[3] == 'o');
// Not enough room.
bs.ostream_init(&os, &arr, 1);
try expect(bs.ostream_write(&os, 0x1, 1));
try expect(!bs.ostream_write_bytes_aligned(&os, foo, 1));
} | src/bitstream_test.zig |
const std = @import("std");
const builtin = @import("builtin");
const zc = @import("zetacore");
const zm = @import("zetamath");
const zr = @import("zetarender");
const ECS = zc.Schema(u22, .{
HealthComponent,
PositionComponent,
VelocityComponent,
});
const HealthComponent = struct {
health: usize,
};
const PositionComponent = struct {
pos: zm.Vec2f,
};
const VelocityComponent = struct {
vel: zm.Vec2f,
};
const PhysicsSystem = struct {
const Self = @This();
system: ECS.System,
pub fn init() Self {
return Self{
.system = ECS.System{
.runFn = run,
},
};
}
fn run(sys: *ECS.System, world: *ECS.World) !void {
var timer = try std.time.Timer.start();
var query = try world.queryAOS(struct {
pos: *PositionComponent,
vel: *VelocityComponent,
});
defer query.deinit();
var end = timer.lap();
std.debug.warn("query (create): \t{d}\n", .{@intToFloat(f64, end) / 1000000000});
timer.reset();
for (query.items) |q| {
q.pos.pos = q.pos.pos.add(q.vel.vel);
}
end = timer.lap();
std.debug.warn("query (iter): \t{d}\n", .{@intToFloat(f64, end) / 1000000000});
}
};
pub fn main() !void {
var world = try ECS.World.init(std.heap.c_allocator);
defer world.deinit();
var timer = try std.time.Timer.start();
var i: usize = 0;
while (i < 1000000) : (i += 1) {
_ = try world.createEntity(.{
VelocityComponent{ .vel = zm.Vec2f.One },
PositionComponent{ .pos = zm.Vec2f.Zero },
});
}
var end = timer.lap();
std.debug.warn("create (loop): \t{d}\n", .{@intToFloat(f64, end) / 1000000000});
var velocities0 = try std.heap.c_allocator.alloc(VelocityComponent, 1000000);
std.mem.set(VelocityComponent, velocities0, VelocityComponent{ .vel = zm.Vec2f.One });
var positions0 = try std.heap.c_allocator.alloc(PositionComponent, 1000000);
std.mem.set(PositionComponent, positions0, PositionComponent{ .pos = zm.Vec2f.Zero });
timer.reset();
try world.createEntities(.{
velocities0,
positions0,
});
end = timer.lap();
std.debug.warn("create (slice): \t{d}\n", .{@intToFloat(f64, end) / 1000000000});
std.heap.c_allocator.free(velocities0);
std.heap.c_allocator.free(positions0);
var physicsSystem = PhysicsSystem.init();
try world.registerSystem(&physicsSystem.system);
try world.run();
} | examples/simple-core/main.zig |
const bld = @import("std").build;
pub fn build(b: *bld.Builder) void {
const dir = "src/shdc/";
const sources = [_][]const u8 {
"args.cc",
"bare.cc",
"bytecode.cc",
"input.cc",
"main.cc",
"sokol.cc",
"sokolzig.cc",
"spirv.cc",
"spirvcross.cc",
"util.cc"
};
const incl_dirs = [_][] const u8 {
"ext/fmt/include",
"ext/SPIRV-Cross",
"ext/pystring",
"ext/getopt/include",
"ext/glslang",
"ext/glslang/glslang/Public",
"ext/glslang/glslang/Include",
"ext/glslang/SPIRV",
"ext/SPIRV-Tools/include"
};
const flags = [_][]const u8 { };
const exe = b.addExecutable("sokol-shdc", null);
exe.setTarget(b.standardTargetOptions(.{}));
exe.setBuildMode(b.standardReleaseOptions());
exe.linkSystemLibrary("c");
exe.linkSystemLibrary("c++");
exe.linkLibrary(lib_fmt(b));
exe.linkLibrary(lib_getopt(b));
exe.linkLibrary(lib_pystring(b));
exe.linkLibrary(lib_spirvcross(b));
exe.linkLibrary(lib_spirvtools(b));
exe.linkLibrary(lib_glslang(b));
inline for (incl_dirs) |incl_dir| {
exe.addIncludeDir(incl_dir);
}
inline for (sources) |src| {
exe.addCSourceFile(dir ++ src, &flags);
}
exe.install();
}
fn lib_getopt(b: *bld.Builder) *bld.LibExeObjStep {
const lib = b.addStaticLibrary("getopt", null);
lib.setBuildMode(b.standardReleaseOptions());
lib.linkSystemLibrary("c");
lib.addIncludeDir("ext/getopt/include");
const flags = [_][]const u8 { };
lib.addCSourceFile("ext/getopt/src/getopt.c", &flags);
return lib;
}
fn lib_pystring(b: *bld.Builder) *bld.LibExeObjStep {
const lib = b.addStaticLibrary("pystring", null);
lib.setBuildMode(b.standardReleaseOptions());
lib.linkSystemLibrary("c");
lib.linkSystemLibrary("c++");
const flags = [_][]const u8 { };
lib.addCSourceFile("ext/pystring/pystring.cpp", &flags);
return lib;
}
fn lib_fmt(b: *bld.Builder) *bld.LibExeObjStep {
const dir = "ext/fmt/src/";
const sources = [_][]const u8 {
"format.cc",
"posix.cc"
};
const lib = b.addStaticLibrary("fmt", null);
lib.setBuildMode(b.standardReleaseOptions());
lib.linkSystemLibrary("c");
lib.linkSystemLibrary("c++");
lib.addIncludeDir("ext/fmt/include");
const flags = [_][]const u8 { };
inline for (sources) |src| {
lib.addCSourceFile(dir ++ src, &flags);
}
return lib;
}
fn lib_spirvcross(b: *bld.Builder) *bld.LibExeObjStep {
const dir = "ext/SPIRV-Cross/";
const sources = [_][]const u8 {
"spirv_cross.cpp",
"spirv_parser.cpp",
"spirv_cross_parsed_ir.cpp",
"spirv_cfg.cpp",
"spirv_glsl.cpp",
"spirv_msl.cpp",
"spirv_hlsl.cpp",
"spirv_reflect.cpp",
"spirv_cross_util.cpp",
};
const flags = [_][]const u8 {
"-DSPIRV_CROSS_EXCEPTIONS_TO_ASSERTIONS",
};
const lib = b.addStaticLibrary("spirvcross", null);
lib.setBuildMode(b.standardReleaseOptions());
lib.linkSystemLibrary("c");
lib.linkSystemLibrary("c++");
lib.addIncludeDir("ext/SPIRV-Cross");
inline for (sources) |src| {
lib.addCSourceFile(dir ++ src, &flags);
}
return lib;
}
fn lib_glslang(b: *bld.Builder) *bld.LibExeObjStep {
const lib = b.addStaticLibrary("glslang", null);
const dir = "ext/glslang/";
const sources = [_][]const u8 {
"OGLCompilersDLL/InitializeDll.cpp",
"glslang/CInterface/glslang_c_interface.cpp",
"glslang/GenericCodeGen/CodeGen.cpp",
"glslang/GenericCodeGen/Link.cpp",
"glslang/MachineIndependent/preprocessor/PpAtom.cpp",
"glslang/MachineIndependent/preprocessor/PpContext.cpp",
"glslang/MachineIndependent/preprocessor/Pp.cpp",
"glslang/MachineIndependent/preprocessor/PpScanner.cpp",
"glslang/MachineIndependent/preprocessor/PpTokens.cpp",
"glslang/MachineIndependent/attribute.cpp",
"glslang/MachineIndependent/Constant.cpp",
"glslang/MachineIndependent/glslang_tab.cpp",
"glslang/MachineIndependent/InfoSink.cpp",
"glslang/MachineIndependent/Initialize.cpp",
"glslang/MachineIndependent/Intermediate.cpp",
"glslang/MachineIndependent/intermOut.cpp",
"glslang/MachineIndependent/IntermTraverse.cpp",
"glslang/MachineIndependent/iomapper.cpp",
"glslang/MachineIndependent/limits.cpp",
"glslang/MachineIndependent/linkValidate.cpp",
"glslang/MachineIndependent/parseConst.cpp",
"glslang/MachineIndependent/ParseContextBase.cpp",
"glslang/MachineIndependent/ParseHelper.cpp",
"glslang/MachineIndependent/pch.cpp",
"glslang/MachineIndependent/PoolAlloc.cpp",
"glslang/MachineIndependent/propagateNoContraction.cpp",
"glslang/MachineIndependent/reflection.cpp",
"glslang/MachineIndependent/RemoveTree.cpp",
"glslang/MachineIndependent/Scan.cpp",
"glslang/MachineIndependent/ShaderLang.cpp",
"glslang/MachineIndependent/SymbolTable.cpp",
"glslang/MachineIndependent/Versions.cpp",
"SPIRV/disassemble.cpp",
"SPIRV/doc.cpp",
"SPIRV/GlslangToSpv.cpp",
"SPIRV/InReadableOrder.cpp",
"SPIRV/Logger.cpp",
"SPIRV/SpvBuilder.cpp",
"SPIRV/SpvPostProcess.cpp",
"SPIRV/SPVRemapper.cpp",
"SPIRV/SpvTools.cpp",
};
const incl_dirs = [_][]const u8 {
"ext/glslang",
"ext/glslang/glslang",
"ext/glslang/glslang/Public",
"ext/glslang/glslang/Include",
"ext/glslang/SPIRV",
"ext/SPIRV-Tools/include"
};
const win_sources = [_][]const u8 {
"glslang/OSDependent/Windows/ossource.cpp"
};
const unix_sources = [_][]const u8 {
"glslang/OSDependent/Unix/ossource.cpp"
};
const os_define = if (lib.target.isWindows()) "-DGLSLANG_OSINCLUDE_WIN32" else "-DGLSLANG_OSINCLUDE_UNIX";
const flags = [_][]const u8 {
os_define,
"-DENABLE_OPT=1",
};
lib.setBuildMode(b.standardReleaseOptions());
lib.linkSystemLibrary("c");
lib.linkSystemLibrary("c++");
inline for (incl_dirs) |incl_dir| {
lib.addIncludeDir(incl_dir);
}
inline for (sources) |src| {
lib.addCSourceFile(dir ++ src, &flags);
}
if (lib.target.isWindows()) {
inline for (win_sources) |src| {
lib.addCSourceFile(dir ++ src, &flags);
}
}
else {
inline for (unix_sources) |src| {
lib.addCSourceFile(dir ++ src, &flags);
}
}
return lib;
}
fn lib_spirvtools(b: *bld.Builder) *bld.LibExeObjStep {
const dir = "ext/SPIRV-Tools/source/";
const sources = [_][]const u8 {
"assembly_grammar.cpp",
"binary.cpp",
"diagnostic.cpp",
"disassemble.cpp",
"enum_string_mapping.cpp",
"extensions.cpp",
"ext_inst.cpp",
"libspirv.cpp",
"name_mapper.cpp",
"opcode.cpp",
"operand.cpp",
"parsed_operand.cpp",
"pch_source.cpp",
"print.cpp",
"software_version.cpp",
"spirv_endian.cpp",
"spirv_fuzzer_options.cpp",
"spirv_optimizer_options.cpp",
"spirv_reducer_options.cpp",
"spirv_target_env.cpp",
"spirv_validator_options.cpp",
"table.cpp",
"text.cpp",
"text_handler.cpp",
"util/bit_vector.cpp",
"util/parse_number.cpp",
"util/string_utils.cpp",
"util/timer.cpp",
"val/basic_block.cpp",
"val/construct.cpp",
"val/function.cpp",
"val/instruction.cpp",
"val/validate_adjacency.cpp",
"val/validate_annotation.cpp",
"val/validate_arithmetics.cpp",
"val/validate_atomics.cpp",
"val/validate_barriers.cpp",
"val/validate_bitwise.cpp",
"val/validate_builtins.cpp",
"val/validate_capability.cpp",
"val/validate_cfg.cpp",
"val/validate_composites.cpp",
"val/validate_constants.cpp",
"val/validate_conversion.cpp",
"val/validate.cpp",
"val/validate_debug.cpp",
"val/validate_decorations.cpp",
"val/validate_derivatives.cpp",
"val/validate_execution_limitations.cpp",
"val/validate_extensions.cpp",
"val/validate_function.cpp",
"val/validate_id.cpp",
"val/validate_image.cpp",
"val/validate_instruction.cpp",
"val/validate_interfaces.cpp",
"val/validate_layout.cpp",
"val/validate_literals.cpp",
"val/validate_logicals.cpp",
"val/validate_memory.cpp",
"val/validate_memory_semantics.cpp",
"val/validate_misc.cpp",
"val/validate_mode_setting.cpp",
"val/validate_non_uniform.cpp",
"val/validate_primitives.cpp",
"val/validate_scopes.cpp",
"val/validate_small_type_uses.cpp",
"val/validate_type.cpp",
"val/validation_state.cpp",
"opt/aggressive_dead_code_elim_pass.cpp",
"opt/amd_ext_to_khr.cpp",
"opt/basic_block.cpp",
"opt/block_merge_pass.cpp",
"opt/block_merge_util.cpp",
"opt/build_module.cpp",
"opt/ccp_pass.cpp",
"opt/cfg_cleanup_pass.cpp",
"opt/cfg.cpp",
"opt/code_sink.cpp",
"opt/combine_access_chains.cpp",
"opt/compact_ids_pass.cpp",
"opt/composite.cpp",
"opt/constants.cpp",
"opt/const_folding_rules.cpp",
"opt/convert_to_half_pass.cpp",
"opt/copy_prop_arrays.cpp",
"opt/dead_branch_elim_pass.cpp",
"opt/dead_insert_elim_pass.cpp",
"opt/dead_variable_elimination.cpp",
"opt/decompose_initialized_variables_pass.cpp",
"opt/decoration_manager.cpp",
"opt/def_use_manager.cpp",
"opt/desc_sroa.cpp",
"opt/dominator_analysis.cpp",
"opt/dominator_tree.cpp",
"opt/eliminate_dead_constant_pass.cpp",
"opt/eliminate_dead_functions_pass.cpp",
"opt/eliminate_dead_functions_util.cpp",
"opt/eliminate_dead_members_pass.cpp",
"opt/feature_manager.cpp",
"opt/fix_storage_class.cpp",
"opt/flatten_decoration_pass.cpp",
"opt/fold.cpp",
"opt/folding_rules.cpp",
"opt/fold_spec_constant_op_and_composite_pass.cpp",
"opt/freeze_spec_constant_value_pass.cpp",
"opt/function.cpp",
"opt/generate_webgpu_initializers_pass.cpp",
"opt/graphics_robust_access_pass.cpp",
"opt/if_conversion.cpp",
"opt/inline_exhaustive_pass.cpp",
"opt/inline_opaque_pass.cpp",
"opt/inline_pass.cpp",
"opt/inst_bindless_check_pass.cpp",
"opt/inst_buff_addr_check_pass.cpp",
"opt/instruction.cpp",
"opt/instruction_list.cpp",
"opt/instrument_pass.cpp",
"opt/ir_context.cpp",
"opt/ir_loader.cpp",
"opt/legalize_vector_shuffle_pass.cpp",
"opt/licm_pass.cpp",
"opt/local_access_chain_convert_pass.cpp",
"opt/local_redundancy_elimination.cpp",
"opt/local_single_block_elim_pass.cpp",
"opt/local_single_store_elim_pass.cpp",
"opt/loop_dependence.cpp",
"opt/loop_dependence_helpers.cpp",
"opt/loop_descriptor.cpp",
"opt/loop_fission.cpp",
"opt/loop_fusion.cpp",
"opt/loop_fusion_pass.cpp",
"opt/loop_peeling.cpp",
"opt/loop_unroller.cpp",
"opt/loop_unswitch_pass.cpp",
"opt/loop_utils.cpp",
"opt/mem_pass.cpp",
"opt/merge_return_pass.cpp",
"opt/module.cpp",
"opt/optimizer.cpp",
"opt/pass.cpp",
"opt/pass_manager.cpp",
"opt/pch_source_opt.cpp",
"opt/private_to_local_pass.cpp",
"opt/process_lines_pass.cpp",
"opt/propagator.cpp",
"opt/reduce_load_size.cpp",
"opt/redundancy_elimination.cpp",
"opt/register_pressure.cpp",
"opt/relax_float_ops_pass.cpp",
"opt/remove_duplicates_pass.cpp",
"opt/replace_invalid_opc.cpp",
"opt/scalar_analysis.cpp",
"opt/scalar_analysis_simplification.cpp",
"opt/scalar_replacement_pass.cpp",
"opt/set_spec_constant_default_value_pass.cpp",
"opt/simplification_pass.cpp",
"opt/split_invalid_unreachable_pass.cpp",
"opt/ssa_rewrite_pass.cpp",
"opt/strength_reduction_pass.cpp",
"opt/strip_atomic_counter_memory_pass.cpp",
"opt/strip_debug_info_pass.cpp",
"opt/strip_reflect_info_pass.cpp",
"opt/struct_cfg_analysis.cpp",
"opt/type_manager.cpp",
"opt/types.cpp",
"opt/unify_const_pass.cpp",
"opt/upgrade_memory_model.cpp",
"opt/value_number_table.cpp",
"opt/vector_dce.cpp",
"opt/workaround1209.cpp",
"opt/wrap_opkill.cpp",
};
const incl_dirs = [_][]const u8 {
"ext/generated",
"ext/SPIRV-Tools",
"ext/SPIRV-Tools/include",
"ext/SPIRV-Headers/include",
};
const flags = [_][]const u8 { };
const lib = b.addStaticLibrary("spirvtools", null);
lib.setBuildMode(b.standardReleaseOptions());
lib.linkSystemLibrary("c");
lib.linkSystemLibrary("c++");
inline for (incl_dirs) |incl_dir| {
lib.addIncludeDir(incl_dir);
}
inline for (sources) |src| {
lib.addCSourceFile(dir ++ src, &flags);
}
return lib;
} | build.zig |
const zgt = @import("zgt");
const std = @import("std");
// Small block needed for correct WebAssembly support
pub usingnamespace zgt.cross_platform;
var graph: LineGraph_Impl = undefined;
pub const LineGraph_Impl = struct {
pub usingnamespace zgt.internal.All(LineGraph_Impl);
peer: ?zgt.backend.Canvas = null,
handlers: LineGraph_Impl.Handlers = undefined,
dataWrappers: LineGraph_Impl.DataWrappers = .{},
dataFn: fn(x: f32) f32,
pub fn init(dataFn: fn(x: f32) f32) LineGraph_Impl {
return LineGraph_Impl.init_events(LineGraph_Impl {
.dataFn = dataFn
});
}
pub fn draw(self: *LineGraph_Impl, ctx: *zgt.DrawContext) !void {
const width = self.getWidth();
const height = self.getHeight();
ctx.setColor(1, 1, 1);
ctx.rectangle(0, 0, width, height);
ctx.fill();
var x: f32 = 0;
var minValue: f32 = 0;
var maxValue: f32 = 0;
while (x < 10) : (x += 0.1) {
const value = self.dataFn(x);
maxValue = std.math.max(maxValue, value);
minValue = std.math.min(minValue, value);
}
maxValue += maxValue / 10;
minValue += minValue / 10;
var legendValue: f32 = minValue;
var legendBuf: [100]u8 = undefined; // the program can't handle a number that is 100 digits long so it's enough
var legendLayout = zgt.DrawContext.TextLayout.init();
defer legendLayout.deinit();
legendLayout.setFont(.{ .face = "Arial", .size = 12.0 });
while (legendValue < maxValue) : (legendValue += (maxValue - minValue) / 10) {
const y = @intCast(i32, height) - @floatToInt(i32,
@floor((legendValue - minValue) * (@intToFloat(f32, height) / (maxValue - minValue))));
const text = try std.fmt.bufPrint(&legendBuf, "{d:.1}", .{ legendValue });
_ = text;
ctx.setColor(0, 0, 0);
ctx.text(0, y, legendLayout, text);
ctx.line(0, @intCast(u32, y), width, @intCast(u32, y));
ctx.stroke();
}
x = 0;
var oldX: u32 = 0;
var oldY: u32 = 0;
while (x < 10) : (x += 0.1) {
const y = self.dataFn(x);
var dy = @intCast(i32, height) - @floatToInt(i32,
@floor((y - minValue) * (@intToFloat(f32, height) / (maxValue - minValue))));
var dx = @floatToInt(i32, @floor(x * 100)) + 50;
if (dy < 0) dy = 0;
if (dx < 0) dx = 0;
if (oldY == 0) oldY = @intCast(u32, dy);
ctx.setColor(0, 0, 0);
ctx.line(oldX, oldY, @intCast(u32, dx), @intCast(u32, dy));
ctx.stroke();
ctx.ellipse(oldX, oldY, 3, 3);
ctx.fill();
oldX = @intCast(u32, dx); oldY = @intCast(u32, dy);
}
}
pub fn show(self: *LineGraph_Impl) !void {
if (self.peer == null) {
self.peer = try zgt.backend.Canvas.create();
try self.show_events();
}
}
pub fn getPreferredSize(self: *LineGraph_Impl, available: zgt.Size) zgt.Size {
_ = self;
_ = available;
return zgt.Size { .width = 500.0, .height = 200.0 };
}
};
pub fn LineGraph(config: struct { dataFn: fn(x: f32) f32 }) !LineGraph_Impl {
var lineGraph = try LineGraph_Impl.init(config.dataFn)
.addDrawHandler(LineGraph_Impl.draw);
return lineGraph;
}
const smoothData = true;
const myData = [_]f32 {
0.0, 1.0, 5.0, 4.0, 3.0, 2.0, 6.0, 0.0
};
fn lerp(a: f32, b: f32, t: f32) f32 {
return a * (1 - t) + b * t;
}
fn myDataFunction(x: f32) f32 {
if (x < 0) return 0;
const idx = @floatToInt(usize, @floor(x));
if (idx >= myData.len) return 0;
if (smoothData) {
const fract = std.math.modf(x).fpart;
const cur = myData[idx];
const next = if (idx+1 >= myData.len) myData[idx] else myData[idx+1];
return lerp(cur, next, fract);
} else {
return myData[idx];
}
}
fn sinus(x: f32) f32 {
return std.math.sin(x);
}
fn stdNormDev(x: f32) f32 {
const ps = std.math.sqrt(2 * std.math.pi);
const exp = std.math.exp(-(x*x / 2.0));
return exp / ps;
}
var rand = std.rand.DefaultPrng.init(0);
fn randf(x: f32) f32 {
_ = x;
return rand.random().float(f32);
}
fn easing(x: f32) f32 {
return @floatCast(f32, zgt.Easings.Linear(x / 10.0));
}
fn SetEasing(comptime Easing: fn(x: f64) f64) fn(*zgt.Button_Impl) anyerror!void {
const func = struct {
pub fn function(x: f32) f32 {
return @floatCast(f32, Easing(x / 10.0));
}
}.function;
const callback = struct {
pub fn callback(btn: *zgt.Button_Impl) anyerror!void {
_ = btn;
graph.dataFn = func;
try graph.requestDraw();
}
}.callback;
return callback;
}
fn drawRectangle(widget: *zgt.Canvas_Impl, ctx: *zgt.Canvas_Impl.DrawContext) !void {
_ = widget;
ctx.setColor(0, 0, 0);
ctx.rectangle(0, 0, 100, 100);
ctx.fill();
}
var rectangleX = zgt.DataWrapper(f32).of(0.1);
var animStart: i64 = 0;
pub fn main() !void {
try zgt.backend.init();
var window = try zgt.Window.init();
graph = try LineGraph(.{ .dataFn = easing });
var rectangle = (try zgt.Column(.{}, .{
zgt.Canvas(.{})
.setPreferredSize(zgt.Size { .width = 100, .height = 100 })
.addDrawHandler(drawRectangle)
}))
.bindAlignX(&rectangleX);
try window.set(
zgt.Column(.{}, .{
zgt.Row(.{}, .{
zgt.Button(.{ .label = "Linear", .onclick = SetEasing(zgt.Easings.Linear) }),
zgt.Button(.{ .label = "In" , .onclick = SetEasing(zgt.Easings.In) }),
zgt.Button(.{ .label = "Out" , .onclick = SetEasing(zgt.Easings.Out) }),
zgt.Button(.{ .label = "In Out", .onclick = SetEasing(zgt.Easings.InOut) })
}),
zgt.Expanded(&graph),
&rectangle
})
);
window.resize(800, 600);
window.show();
while (zgt.stepEventLoop(.Asynchronous)) {
var dt = zgt.internal.milliTimestamp() - animStart;
if (dt > 1500) {
animStart = zgt.internal.milliTimestamp(); // std.time.milliTimestamp();
continue;
} else if (dt > 1000) {
dt = 1000;
}
const t = @intToFloat(f32, dt) / 1000;
rectangleX.set(graph.dataFn(t * 10.0));
std.time.sleep(30);
}
} | examples/graph.zig |
const std = @import("std");
const soundio = @import("soundio.zig");
const sndfile = @import("sndfile");
const hzzp = @import("hzzp");
const ao = struct {
pub const c = @cImport({
@cInclude("ao/ao.h");
});
};
const VirtualContext = struct {
fd: std.os.fd_t,
cursor: usize = 0,
write_error: ?std.os.SendError = null,
read_error: ?std.os.ReadError = null,
};
fn virtualWrite(data_ptr: ?*const c_void, bytes: sndfile.c.sf_count_t, user_ptr: ?*c_void) callconv(.C) sndfile.c.sf_count_t {
const ctx = @ptrCast(*VirtualContext, @alignCast(@alignOf(VirtualContext), user_ptr));
const data = @ptrCast([*]const u8, @alignCast(@alignOf(u8), data_ptr));
const sliced = data[0..@intCast(usize, bytes)];
ctx.write_error = null;
const sent_bytes = std.os.sendto(ctx.fd, sliced, std.os.MSG_NOSIGNAL, null, 0) catch |err| {
ctx.write_error = err;
return @as(i64, 0);
};
return @intCast(i64, sent_bytes);
}
fn virtualRead(data_ptr: ?*c_void, bytes: sndfile.c.sf_count_t, user_ptr: ?*c_void) callconv(.C) sndfile.c.sf_count_t {
const ctx = @ptrCast(*VirtualContext, @alignCast(@alignOf(VirtualContext), user_ptr));
const data = @ptrCast([*]u8, @alignCast(@alignOf(u8), data_ptr));
var buf = data[0..@intCast(usize, bytes)];
ctx.read_error = null;
const read_bytes = std.os.read(ctx.fd, buf) catch |err| {
std.debug.warn("read FAIL {}\n", .{err});
ctx.read_error = err;
return @as(i64, 0);
};
std.debug.warn("os.read {}\n", .{
read_bytes,
});
ctx.cursor += read_bytes;
return @intCast(i64, read_bytes);
}
fn virtualLength(_: ?*c_void) callconv(.C) sndfile.c.sf_count_t {
std.debug.warn("length\n", .{});
return @intCast(i64, 0xffffff2);
}
fn virtualSeek(offset: sndfile.c.sf_count_t, whence: c_int, user_data: ?*c_void) callconv(.C) sndfile.c.sf_count_t {
std.debug.warn("seek {} {}\n", .{ offset, whence });
return offset;
}
fn virtualTell(user_ptr: ?*c_void) callconv(.C) sndfile.c.sf_count_t {
const ctx = @ptrCast(*VirtualContext, @alignCast(@alignOf(VirtualContext), user_ptr));
std.debug.warn("tell {}\n", .{ctx.cursor});
return @intCast(sndfile.c.sf_count_t, ctx.cursor);
// return 0;
}
const Result = struct {
state: *soundio.c.SoundIo,
device: *soundio.c.SoundIoDevice,
stream: *soundio.c.SoundIoOutStream,
};
fn initSoundIo() !Result {
var soundio_opt = soundio.c.soundio_create();
if (soundio_opt == null) {
std.debug.warn("libsoundio fail: out of memory\n", .{});
return error.OutOfMemory;
}
var soundio_state = soundio_opt.?;
var backend_count = @intCast(usize, soundio.c.soundio_backend_count(soundio_state));
var i: usize = 0;
while (i < backend_count) : (i += 1) {
var backend = soundio.c.soundio_get_backend(soundio_state, @intCast(c_int, i));
std.debug.warn("backend {} {}\n", .{ i, backend });
}
var err = soundio.c.soundio_connect(soundio_state);
if (err != 0) {
const msg = std.mem.spanZ(soundio.c.soundio_strerror(err));
std.debug.warn("error connecting: {}\n", .{msg});
return error.ConnectError;
}
_ = soundio.c.soundio_flush_events(soundio_state);
const default_out_device_index = soundio.c.soundio_default_output_device_index(soundio_state);
if (default_out_device_index < 0) {
std.debug.warn("no output device connected\n", .{});
return error.NoDevice;
}
var device_opt = soundio.c.soundio_get_output_device(soundio_state, default_out_device_index);
if (device_opt == null) {
std.debug.warn("failed to get output device: out of memory\n", .{});
return error.OutOfMemory;
}
var device = device_opt.?;
std.debug.warn("output device: {}\n", .{device.*.name});
var outstream_opt = soundio.c.soundio_outstream_create(device);
if (outstream_opt == null) {
std.debug.warn("failed to get output stream: out of memory\n", .{});
return error.OutOfMemory;
}
return Result{
.state = soundio_state,
.device = device,
.stream = outstream_opt.?,
};
}
const Samples = std.fifo.LinearFifo(f32, .Dynamic);
var samples: Samples = undefined;
// I'm going to assume PulseAudio and so, assume frame_count_min == 0, and you
// can't stop me.
fn write_callback(
stream: [*c]soundio.c.SoundIoOutStream,
frame_count_min: c_int,
frame_count_max: c_int,
) callconv(.C) void {
std.debug.warn("write_callback(min={} max={})\n", .{ frame_count_min, frame_count_max });
var areas: [*c]soundio.c.SoundIoChannelArea = undefined;
const available_samples = samples.readableLength();
if (available_samples == 0) {
std.debug.warn("--> no frames\n", .{});
return;
}
const wanted_samples = std.math.min(available_samples, @intCast(usize, frame_count_max));
var allowed_write_c: i64 = @intCast(i64, wanted_samples);
var err = soundio.c.soundio_outstream_begin_write(
stream,
&areas,
@ptrCast(*c_int, &allowed_write_c),
);
if (err != 0) {
const msg = std.mem.spanZ(soundio.c.soundio_strerror(err));
std.debug.warn("unrecoverable stream error (begin): {}\n", .{msg});
std.os.exit(1);
}
const allowed_write = @intCast(usize, allowed_write_c);
var write_buffer = samples.allocator.alloc(
f32,
allowed_write,
) catch @panic("out of memory");
defer samples.allocator.free(write_buffer);
const actually_read = samples.read(write_buffer);
std.debug.assert(actually_read == allowed_write);
std.debug.warn("got {} write frames\n", .{actually_read});
std.debug.warn("{} frames allowed to write\n", .{allowed_write});
var frames_to_write = write_buffer[0..allowed_write];
var layout = &stream.*.layout;
var frame: usize = 0;
while (frame < allowed_write) : (frame += 1) {
if (frame % 300 == 0) {
std.debug.warn("frame: {} read: {}\n", .{ frame, allowed_write });
}
var channel: usize = 0;
while (channel < layout.channel_count) : (channel += 1) {
var wanted_ptr = @ptrCast([*c]f32, @alignCast(@alignOf(f32), areas[channel].ptr));
// prevent invalid access
if (frame > (frames_to_write.len - 1)) {
wanted_ptr.* = 0;
} else {
wanted_ptr.* = frames_to_write[frame];
}
}
}
err = soundio.c.soundio_outstream_end_write(stream);
if (err != 0) {
if (err == soundio.c.SoundIoErrorUnderflow)
return;
const msg = std.mem.spanZ(soundio.c.soundio_strerror(err));
std.debug.warn("unrecoverable stream error (end): {}\n", .{msg});
std.os.exit(1);
}
std.debug.warn("write_callback(...) = done\n", .{});
}
fn initStream(stream: *soundio.c.SoundIoOutStream) !void {
var err = soundio.c.soundio_outstream_open(stream);
if (err != 0) {
const msg = std.mem.spanZ(soundio.c.soundio_strerror(err));
std.debug.warn("unable to open device ({}): {}\n", .{ err, msg });
return error.OpenError;
}
if (stream.layout_error != 0) {
const msg = std.mem.spanZ(soundio.c.soundio_strerror(stream.layout_error));
std.debug.warn("unable to set channel layout: {}\n", .{msg});
return error.LayoutError;
}
err = soundio.c.soundio_outstream_start(stream);
if (err != 0) {
const msg = std.mem.spanZ(soundio.c.soundio_strerror(err));
std.debug.warn("unable to start device: {}\n", .{msg});
return error.StartError;
}
}
pub fn main() anyerror!u8 {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer {
_ = gpa.deinit();
}
var allocator = &gpa.allocator;
samples = Samples.init(allocator);
defer samples.deinit();
var args_it = std.process.args();
defer args_it.deinit();
std.debug.assert(args_it.skip() == true);
const host = try (args_it.next(allocator) orelse @panic("expected host arg"));
defer allocator.free(host);
const path = try (args_it.next(allocator) orelse @panic("expected path arg"));
defer allocator.free(path);
ao.c.ao_initialize();
defer ao.c.ao_shutdown();
std.debug.warn("initialized libao\n", .{});
const driver_id = ao.c.ao_driver_id("pulse");
// const driver_id = ao.c.ao_default_driver_id();
if (driver_id == -1) {
std.debug.warn("libao error: failed to get default driver\n", .{});
return 1;
}
var it = std.mem.split(host, ":");
const actual_host = it.next().?;
var actual_port: u16 = undefined;
if (it.next()) |port_str| {
actual_port = try std.fmt.parseInt(u16, port_str, 10);
} else {
actual_port = 80;
}
std.debug.warn("host: {}\n", .{actual_host});
std.debug.warn("port: {}\n", .{actual_port});
std.debug.warn("path: {}\n", .{path});
const sock = try std.net.tcpConnectToHost(allocator, actual_host, actual_port);
defer sock.close();
var read_buffer: [128]u8 = undefined;
var client = hzzp.base.Client.create(&read_buffer, sock.reader(), sock.writer());
try client.writeHead("GET", path);
try client.writeHeaderValueFormat("Host", "http://{s}", .{host});
try client.writeHeadComplete();
var status_event = (try client.readEvent()).?;
std.testing.expect(status_event == .status);
std.debug.warn("http: got status: {}\n", .{status_event.status.code});
while (true) {
const event = (try client.readEvent()).?;
if (event != .head_complete) {
std.debug.warn("http: got head_complete\n", .{});
break;
}
std.testing.expect(event == .header);
std.debug.warn("http: got header: {}: {}\n", .{ event.header.name, event.header.value });
}
var buf: [50]u8 = undefined;
const off1 = try sock.read(&buf);
std.debug.warn("data: {}\n", .{buf[0..off1]});
// setup libsndfile based on sock
var virtual = sndfile.c.SF_VIRTUAL_IO{
.get_filelen = virtualLength,
.seek = virtualSeek,
.read = virtualRead,
.write = virtualWrite,
.tell = virtualTell,
};
var virtual_ctx = VirtualContext{ .fd = sock.handle };
var info = std.mem.zeroes(sndfile.Info);
var file = sndfile.c.sf_open_virtual(
&virtual,
@enumToInt(sndfile.Mode.Read),
@ptrCast(*sndfile.c.SF_INFO, &info),
@ptrCast(*c_void, &virtual_ctx),
);
defer {
_ = sndfile.c.sf_close(file);
}
const status = sndfile.c.sf_error(file);
if (status != 0) {
const err = std.mem.spanZ(sndfile.c.sf_error_number(status));
std.debug.warn("failed to open read fd {} ({})\n", .{ sock.handle, err });
var logbuf: [10 * 1024]u8 = undefined;
const count = sndfile.c.sf_command(
file,
sndfile.c.SFC_GET_LOG_INFO,
&logbuf,
10 * 1024,
);
const msgs = logbuf[0..@intCast(usize, count)];
std.debug.warn("libsndfile log {}\n", .{msgs});
return 1;
}
var matrix = try allocator.dupe(u8, "M");
defer allocator.free(matrix);
var matrix_c = try std.cstr.addNullByte(allocator, matrix);
defer allocator.free(matrix_c);
var sample_format = std.mem.zeroes(ao.c.ao_sample_format);
sample_format.bits = 16;
sample_format.rate = info.samplerate;
sample_format.channels = 1;
sample_format.byte_format = ao.c.AO_FMT_NATIVE;
// sample_format.matrix = matrix_c.ptr;
var device = ao.c.ao_open_live(driver_id, &sample_format, null);
if (device == null) {
const errno = std.c._errno().*;
std.debug.warn("failed to open libao device: errno {}\n", .{errno});
return 1;
}
defer {
_ = ao.c.ao_close(device);
}
const samplerate = @intCast(usize, info.samplerate);
var audio_read_buffer = try allocator.alloc(i16, samplerate);
defer allocator.free(audio_read_buffer);
var pulse_buffer = try allocator.alloc(u8, samplerate * 2);
defer allocator.free(pulse_buffer);
while (true) {
std.debug.warn("==reading\n", .{});
const frames = @intCast(usize, sndfile.c.sf_readf_short(
file,
audio_read_buffer.ptr,
@intCast(i64, audio_read_buffer.len),
));
std.debug.warn("==got {} frames\n", .{frames});
if (frames == 0) {
if (virtual_ctx.read_error) |err| {
std.debug.warn("read error {}\n", .{err});
} else {
std.debug.warn("finished read\n", .{});
}
break;
}
var proper_buffer = audio_read_buffer[0..frames];
const res = ao.c.ao_play(
device,
@ptrCast([*c]u8, proper_buffer.ptr),
@intCast(c_uint, proper_buffer.len * 2),
);
if (res == 0) {
const errno = std.c._errno().*;
std.debug.warn("ao_play fail: errno {}\n", .{errno});
return 1;
}
std.debug.warn("ao_play result: {}\n", .{res});
}
return 0;
} | src/main.zig |
const std = @import("std");
const Builder = std.build.Builder;
pub fn build(b: *Builder) void {
const mode = b.standardReleaseOptions();
const target = b.standardTargetOptions(.{});
const exe = b.addExecutable("zua", "src/zua.zig");
exe.setBuildMode(mode);
exe.setTarget(target);
exe.install();
const run_cmd = exe.run();
run_cmd.step.dependOn(b.getInstallStep());
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
var lualib = addLuaLibrary(b, mode, target);
var tests = b.addTest("src/zua.zig");
tests.setBuildMode(mode);
tests.setTarget(target);
tests.linkLibrary(lualib);
tests.addIncludePath("lua-5.1/src");
tests.addPackagePath("zuatest", "test/lib.zig");
const test_step = b.step("test", "Run all tests");
test_step.dependOn(&tests.step);
var testlib_test = b.addTest("test/lib.zig");
testlib_test.setBuildMode(mode);
testlib_test.setTarget(target);
testlib_test.linkLibrary(lualib);
testlib_test.addIncludePath("lua-5.1/src");
const testlib_test_step = b.step("testlib", "Run test library tests");
testlib_test_step.dependOn(&testlib_test.step);
const fuzzed_lex_inputs_dir_default = "test/corpus/fuzz_llex";
const fuzzed_lex_outputs_dir_default = "test/output/fuzz_llex";
const fuzzed_lex_inputs_dir = b.option([]const u8, "fuzzed_lex_inputs_dir", "Directory with input corpus for fuzzed_lex tests") orelse fuzzed_lex_inputs_dir_default;
const fuzzed_lex_outputs_dir = b.option([]const u8, "fuzzed_lex_outputs_dir", "Directory with expected outputs for fuzzed_lex tests") orelse fuzzed_lex_outputs_dir_default;
const fuzzed_lex_options = b.addOptions();
fuzzed_lex_options.addOption([]const u8, "fuzzed_lex_inputs_dir", fuzzed_lex_inputs_dir);
fuzzed_lex_options.addOption([]const u8, "fuzzed_lex_outputs_dir", fuzzed_lex_outputs_dir);
var fuzzed_lex_tests = b.addTest("test/fuzzed_lex.zig");
fuzzed_lex_tests.setBuildMode(mode);
fuzzed_lex_tests.addOptions("build_options", fuzzed_lex_options);
fuzzed_lex_tests.addPackagePath("zua", "src/zua.zig");
const fuzzed_lex_test_step = b.step("fuzzed_lex", "Test lexer against a fuzzed corpus from fuzzing-lua");
fuzzed_lex_test_step.dependOn(&fuzzed_lex_tests.step);
var bench_lex_tests = b.addTest("test/bench_lex.zig");
bench_lex_tests.setBuildMode(.ReleaseFast);
bench_lex_tests.addOptions("build_options", fuzzed_lex_options);
bench_lex_tests.addPackagePath("zua", "src/zua.zig");
const bench_lex_test_step = b.step("bench_lex", "Bench lexer against a fuzzed corpus from fuzzing-lua");
bench_lex_test_step.dependOn(&bench_lex_tests.step);
const fuzzed_strings_inputs_dir_default = "test/corpus/fuzz_strings";
const fuzzed_strings_outputs_dir_default = "test/output/fuzz_strings";
const fuzzed_strings_gen_dir_default = "test/corpus/fuzz_strings_generated";
const fuzzed_strings_inputs_dir = b.option([]const u8, "fuzzed_strings_inputs_dir", "Directory with input strings for string parsing tests") orelse fuzzed_strings_inputs_dir_default;
const fuzzed_strings_outputs_dir = b.option([]const u8, "fuzzed_strings_outputs_dir", "Directory with output strings for string parsing tests") orelse fuzzed_strings_outputs_dir_default;
const fuzzed_strings_gen_dir = b.option([]const u8, "fuzzed_strings_gen_dir", "Directory to output generated string inputs to") orelse fuzzed_strings_gen_dir_default;
const fuzzed_strings_options = b.addOptions();
fuzzed_strings_options.addOption([]const u8, "fuzzed_strings_inputs_dir", fuzzed_strings_inputs_dir);
fuzzed_strings_options.addOption([]const u8, "fuzzed_strings_outputs_dir", fuzzed_strings_outputs_dir);
fuzzed_strings_options.addOption([]const u8, "fuzzed_strings_gen_dir", fuzzed_strings_gen_dir);
var fuzzed_strings = b.addTest("test/fuzzed_strings.zig");
fuzzed_strings.setBuildMode(mode);
fuzzed_strings.addOptions("build_options", fuzzed_strings_options);
fuzzed_strings.addPackagePath("zua", "src/zua.zig");
const fuzzed_strings_step = b.step("fuzzed_strings", "Test string parsing against a fuzzed corpus from fuzzing-lua");
fuzzed_strings_step.dependOn(&fuzzed_strings.step);
const fuzzed_strings_gen_options = b.addOptions();
fuzzed_strings_gen_options.addOption([]const u8, "fuzzed_lex_inputs_dir", fuzzed_lex_inputs_dir);
fuzzed_strings_gen_options.addOption([]const u8, "fuzzed_strings_gen_dir", fuzzed_strings_gen_dir);
var fuzzed_strings_gen = b.addExecutable("fuzzed_strings_gen", "test/fuzzed_strings_gen.zig");
fuzzed_strings_gen.setBuildMode(mode);
fuzzed_strings_gen.addOptions("build_options", fuzzed_strings_gen_options);
fuzzed_strings_gen.addPackagePath("zua", "src/zua.zig");
const fuzzed_strings_gen_run_step = b.step("fuzzed_strings_gen_run", "Generate string inputs from a fuzzed corpus of lexer inputs");
fuzzed_strings_gen_run_step.dependOn(&fuzzed_strings_gen.run().step);
const fuzzed_parse_inputs_dir_default = "test/corpus/fuzz_lparser";
const fuzzed_parse_outputs_dir_default = "test/output/fuzz_lparser";
const fuzzed_parse_inputs_dir = b.option([]const u8, "fuzzed_parse_inputs_dir", "Directory with input corpus for fuzzed_parse tests") orelse fuzzed_parse_inputs_dir_default;
const fuzzed_parse_outputs_dir = b.option([]const u8, "fuzzed_parse_outputs_dir", "Directory with expected outputs for fuzzed_parse tests") orelse fuzzed_parse_outputs_dir_default;
const fuzzed_parse_options = b.addOptions();
fuzzed_parse_options.addOption([]const u8, "fuzzed_parse_inputs_dir", fuzzed_parse_inputs_dir);
fuzzed_parse_options.addOption([]const u8, "fuzzed_parse_outputs_dir", fuzzed_parse_outputs_dir);
var fuzzed_parse_tests = b.addTest("test/fuzzed_parse.zig");
fuzzed_parse_tests.setBuildMode(mode);
fuzzed_parse_tests.addOptions("build_options", fuzzed_parse_options);
fuzzed_parse_tests.addPackagePath("zua", "src/zua.zig");
const fuzzed_parse_test_step = b.step("fuzzed_parse", "Test parser against a fuzzed corpus from fuzzing-lua");
fuzzed_parse_test_step.dependOn(&fuzzed_parse_tests.step);
var fuzzed_parse_prune = b.addExecutable("fuzzed_parse_prune", "test/fuzzed_parse_prune.zig");
fuzzed_parse_prune.setBuildMode(mode);
fuzzed_parse_prune.addOptions("build_options", fuzzed_parse_options);
fuzzed_parse_prune.addPackagePath("zua", "src/zua.zig");
const fuzzed_parse_prune_step = b.step("fuzzed_parse_prune", "Prune fuzzed parser corpus to remove lexer-specific error outputs");
fuzzed_parse_prune_step.dependOn(&fuzzed_parse_prune.run().step);
const lua51_tests_inputs_dir_default = "lua-5.1/test";
const lua51_tests_inputs_dir = b.option([]const u8, "lua51_tests_inputs_dir", "Directory with the PUC Lua test files") orelse lua51_tests_inputs_dir_default;
const lua51_tests_options = b.addOptions();
lua51_tests_options.addOption([]const u8, "lua51_tests_inputs_dir", lua51_tests_inputs_dir);
var lua51_tests = b.addTest("test/lua51_tests.zig");
lua51_tests.setBuildMode(mode);
lua51_tests.setTarget(target);
lua51_tests.addOptions("build_options", lua51_tests_options);
lua51_tests.addPackagePath("zua", "src/zua.zig");
const lua51_tests_step = b.step("lua51_tests", "Run tests using the Lua 5.1 test files");
lua51_tests_step.dependOn(&lua51_tests.step);
}
fn addLuaLibrary(b: *Builder, mode: std.builtin.Mode, target: std.zig.CrossTarget) *std.build.LibExeObjStep {
var lualib = b.addStaticLibrary("lua", null);
lualib.linkLibC();
lualib.setBuildMode(mode);
lualib.setTarget(target);
lualib.addIncludePath("lua-5.1/src");
lualib.addCSourceFiles(&.{
"lua-5.1/src/lapi.c",
"lua-5.1/src/lcode.c",
"lua-5.1/src/ldebug.c",
"lua-5.1/src/ldo.c",
"lua-5.1/src/ldump.c",
"lua-5.1/src/lfunc.c",
"lua-5.1/src/lgc.c",
"lua-5.1/src/llex.c",
"lua-5.1/src/lmem.c",
"lua-5.1/src/lobject.c",
"lua-5.1/src/lopcodes.c",
"lua-5.1/src/lparser.c",
"lua-5.1/src/lstate.c",
"lua-5.1/src/lstring.c",
"lua-5.1/src/ltable.c",
"lua-5.1/src/ltm.c",
"lua-5.1/src/lundump.c",
"lua-5.1/src/lvm.c",
"lua-5.1/src/lzio.c",
"lua-5.1/src/lauxlib.c",
"lua-5.1/src/lbaselib.c",
"lua-5.1/src/ldblib.c",
"lua-5.1/src/liolib.c",
"lua-5.1/src/lmathlib.c",
"lua-5.1/src/loslib.c",
"lua-5.1/src/ltablib.c",
"lua-5.1/src/lstrlib.c",
"lua-5.1/src/loadlib.c",
"lua-5.1/src/linit.c",
}, &.{"-std=gnu99"});
return lualib;
} | build.zig |
const std = @import("std");
const assert = std.debug.assert;
const print = std.debug.print;
pub const RunError = std.mem.Allocator.Error || std.fmt.ParseIntError || error{ UnsupportedInput, InvalidEnumName, UnexpectedEOS };
const MainError = RunError || std.fs.File.OpenError || std.os.ReadError || std.os.SeekError || std.os.WriteError;
pub fn defaultMain(comptime input_fname: []const u8, comptime runFn: fn (input: []const u8, allocator: std.mem.Allocator) RunError![2][]const u8) fn () MainError!void {
const T = struct {
pub fn main() MainError!void {
const stdout = std.io.getStdOut().writer();
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
//var args_it = std.process.args();
//defer args_it.deinit();
//const prog_name = try args_it.next(allocator) orelse @panic("Could not find self argument");
//allocator.free(prog_name);
//const short_name = std.fs.path.basename(prog_name);
const limit = 1024 * 1024;
const text = if (input_fname.len > 0) try std.fs.cwd().readFileAlloc(allocator, input_fname, limit) else "";
defer if (text.len > 0) allocator.free(text);
const answer = try runFn(text, allocator);
defer allocator.free(answer[0]);
defer allocator.free(answer[1]);
try stdout.print("{s}:\n", .{input_fname});
for (answer) |ans, i| {
const multiline = (std.mem.indexOfScalar(u8, ans, '\n') != null);
if (multiline) {
try stdout.print("\tPART {d}:\n{s}", .{ i + 1, ans });
} else {
try stdout.print("\tPART {d}: {s}\n", .{ i + 1, ans });
}
}
}
};
return T.main;
}
// -----------------------------------------------------------
// ----- 2d Map
// -----------------------------------------------------------
pub const Vec2 = struct {
x: i32,
y: i32,
pub fn min(a: Vec2, b: Vec2) Vec2 {
return Vec2{
.x = if (a.x < b.x) a.x else b.x,
.y = if (a.y < b.y) a.y else b.y,
};
}
pub fn max(a: Vec2, b: Vec2) Vec2 {
return Vec2{
.x = if (a.x > b.x) a.x else b.x,
.y = if (a.y > b.y) a.y else b.y,
};
}
pub fn add(a: Vec2, b: Vec2) Vec2 {
return Vec2{
.x = a.x + b.x,
.y = a.y + b.y,
};
}
pub fn dist(a: Vec2, b: Vec2) u32 {
return @intCast(u32, (std.math.absInt(a.x - b.x) catch unreachable) + (std.math.absInt(a.y - b.y) catch unreachable));
}
pub fn scale(a: i32, v: Vec2) Vec2 {
return Vec2{
.x = a * v.x,
.y = a * v.y,
};
}
pub const Rot = enum { none, cw, ccw };
pub fn rotate(vec: Vec2, rot: Rot) Vec2 {
const v = vec; // copy to avoid return value alias
return switch (rot) {
.none => return v,
.cw => Vec2{ .x = -v.y, .y = v.x },
.ccw => Vec2{ .x = v.y, .y = -v.x },
};
}
pub fn lessThan(_: void, lhs: Vec2, rhs: Vec2) bool {
if (lhs.y < rhs.y) return true;
if (lhs.y == rhs.y and lhs.x < rhs.x) return true;
return false;
}
pub fn eq(lhs: Vec2, rhs: Vec2) bool {
return (lhs.y == rhs.y and lhs.x == rhs.x);
}
pub const cardinal_dirs = [_]Vec2{
Vec2{ .x = 0, .y = -1 }, // N
Vec2{ .x = -1, .y = 0 }, // W
Vec2{ .x = 1, .y = 0 }, // E
Vec2{ .x = 0, .y = 1 }, // S
};
pub const Transfo = enum { r0, r90, r180, r270, r0_flip, r90_flip, r180_flip, r270_flip };
pub const all_tranfos = [_]Transfo{ .r0, .r90, .r180, .r270, .r0_flip, .r90_flip, .r180_flip, .r270_flip };
pub fn referential(t: Transfo) struct { x: Vec2, y: Vec2 } {
return switch (t) {
.r0 => .{ .x = Vec2{ .x = 1, .y = 0 }, .y = Vec2{ .x = 0, .y = 1 } },
.r90 => .{ .x = Vec2{ .x = 0, .y = 1 }, .y = Vec2{ .x = -1, .y = 0 } },
.r180 => .{ .x = Vec2{ .x = -1, .y = 0 }, .y = Vec2{ .x = 0, .y = -1 } },
.r270 => .{ .x = Vec2{ .x = 0, .y = -1 }, .y = Vec2{ .x = 1, .y = 0 } },
.r0_flip => .{ .x = Vec2{ .x = -1, .y = 0 }, .y = Vec2{ .x = 0, .y = 1 } },
.r90_flip => .{ .x = Vec2{ .x = 0, .y = 1 }, .y = Vec2{ .x = 1, .y = 0 } },
.r180_flip => .{ .x = Vec2{ .x = 1, .y = 0 }, .y = Vec2{ .x = 0, .y = -1 } },
.r270_flip => .{ .x = Vec2{ .x = 0, .y = -1 }, .y = Vec2{ .x = -1, .y = 0 } },
};
}
};
pub fn spiralIndexFromPos(p: Vec2) u32 {
// https://stackoverflow.com/questions/9970134/get-spiral-index-from-location
if (p.y * p.y >= p.x * p.x) {
var i = 4 * p.y * p.y - p.y - p.x;
if (p.y < p.x)
i -= 2 * (p.y - p.x);
return @intCast(u32, i);
} else {
var i = 4 * p.x * p.x - p.y - p.x;
if (p.y < p.x)
i += 2 * (p.y - p.x);
return @intCast(u32, i);
}
}
fn sqrtRound(v: usize) usize {
// todo: cf std.math.sqrt(idx)
return @floatToInt(usize, @round(std.math.sqrt(@intToFloat(f64, v))));
}
pub fn posFromSpiralIndex(idx: usize) Vec2 {
const i = @intCast(i32, idx);
const j = @intCast(i32, sqrtRound(idx));
const k = (std.math.absInt(j * j - i) catch unreachable) - j;
const parity: i32 = @mod(j, 2); // 0 ou 1
const sign: i32 = if (parity == 0) 1 else -1;
return Vec2{
.x = sign * @divFloor(k + j * j - i - parity, 2),
.y = sign * @divFloor(-k + j * j - i - parity, 2),
};
}
pub const BBox = struct {
min: Vec2,
max: Vec2,
pub fn isEmpty(bbox: BBox) bool {
return bbox.min.x > bbox.max.x or bbox.min.y > bbox.max.y;
}
pub const empty = BBox{ .min = Vec2{ .x = 999999, .y = 999999 }, .max = Vec2{ .x = -999999, .y = -999999 } };
};
pub fn Map(comptime TileType: type, width: usize, height: usize, allow_negative_pos: bool) type {
return struct {
pub const stride = width;
pub const Tile = TileType;
const center_offset: isize = if (allow_negative_pos) ((width / 2) + stride * (height / 2)) else 0;
map: [height * width]Tile = undefined,
default_tile: Tile,
bbox: BBox = BBox.empty,
const Self = @This();
pub fn intToChar(t: Tile) u8 {
return switch (t) {
0 => '.',
1...9 => (@intCast(u8, t) + '0'),
else => '?',
};
}
pub fn printToBuf(map: *const Self, pos: ?Vec2, clip: ?BBox, comptime tile_to_char: ?fn (m: Tile) u8, buf: []u8) []const u8 {
var i: usize = 0;
const b = if (clip) |box|
BBox{
.min = Vec2.max(map.bbox.min, box.min),
.max = Vec2.min(map.bbox.max, box.max),
}
else
map.bbox;
var p = b.min;
while (p.y <= b.max.y) : (p.y += 1) {
p.x = b.min.x;
while (p.x <= b.max.x) : (p.x += 1) {
const offset = map.offsetof(p);
if (pos != null and p.x == pos.?.x and p.y == pos.?.y) {
buf[i] = '@';
} else {
buf[i] = if (tile_to_char) |t2c| t2c(map.map[offset]) else map.map[offset];
}
i += 1;
}
buf[i] = '\n';
i += 1;
}
return buf[0..i];
}
pub fn fill(map: *Self, v: Tile, clip: ?BBox) void {
if (clip) |b| {
var p = b.min;
while (p.y <= b.max.y) : (p.y += 1) {
p.x = b.min.x;
while (p.x <= b.max.x) : (p.x += 1) {
map.set(p, v);
}
}
} else {
std.mem.set(Tile, &map.map, v);
}
}
pub fn fillIncrement(map: *Self, v: Tile, clip: BBox) void {
const b = clip;
var p = b.min;
while (p.y <= b.max.y) : (p.y += 1) {
p.x = b.min.x;
while (p.x <= b.max.x) : (p.x += 1) {
if (map.get(p)) |prev| {
map.set(p, prev + v);
} else {
map.set(p, map.default_tile + v);
}
}
}
}
pub fn growBBox(map: *Self, p: Vec2) void {
if (allow_negative_pos) {
assert(p.x <= Self.stride / 2 and -p.x <= Self.stride / 2);
} else {
assert(p.x >= 0 and p.y >= 0);
}
if (p.x >= map.bbox.min.x and p.x <= map.bbox.max.x and p.y >= map.bbox.min.y and p.y <= map.bbox.max.y)
return;
const prev = map.bbox;
map.bbox.min = Vec2.min(p, map.bbox.min);
map.bbox.max = Vec2.max(p, map.bbox.max);
// marchait sans ça avant, mais je vois pas comment.
if (prev.isEmpty()) {
map.fill(map.default_tile, map.bbox);
} else {
var y = map.bbox.min.y;
while (y < prev.min.y) : (y += 1) {
const o = map.offsetof(Vec2{ .x = map.bbox.min.x, .y = y });
std.mem.set(Tile, map.map[o .. o + @intCast(usize, map.bbox.max.x + 1 - map.bbox.min.x)], map.default_tile);
}
if (map.bbox.min.x < prev.min.x) {
assert(map.bbox.max.x == prev.max.x); // une seule colonne, on n'a grandi que d'un point.
while (y <= prev.max.y) : (y += 1) {
const o = map.offsetof(Vec2{ .x = map.bbox.min.x, .y = y });
std.mem.set(Tile, map.map[o .. o + @intCast(usize, prev.min.x - map.bbox.min.x)], map.default_tile);
}
} else if (map.bbox.max.x > prev.max.x) {
assert(map.bbox.min.x == prev.min.x);
while (y <= prev.max.y) : (y += 1) {
const o = map.offsetof(Vec2{ .x = prev.max.x + 1, .y = y });
std.mem.set(Tile, map.map[o .. o + @intCast(usize, map.bbox.max.x + 1 - (prev.max.x + 1))], map.default_tile);
}
} else {
y += (prev.max.y - prev.min.y) + 1;
}
while (y <= map.bbox.max.y) : (y += 1) {
const o = map.offsetof(Vec2{ .x = map.bbox.min.x, .y = y });
std.mem.set(Tile, map.map[o .. o + @intCast(usize, map.bbox.max.x + 1 - map.bbox.min.x)], map.default_tile);
}
}
var v = map.bbox.min;
while (v.y <= map.bbox.max.y) : (v.y += 1) {
v.x = map.bbox.min.x;
while (v.x <= map.bbox.max.x) : (v.x += 1) {
if (v.x >= prev.min.x and v.x <= prev.max.x and v.y >= prev.min.y and v.y <= prev.max.y)
continue;
map.map[map.offsetof(v)] = map.default_tile;
}
}
}
pub fn offsetof(_: *const Self, p: Vec2) usize {
return @intCast(usize, center_offset + @intCast(isize, p.x) + @intCast(isize, p.y) * @intCast(isize, stride));
}
pub fn at(map: *const Self, p: Vec2) Tile {
assert(p.x >= map.bbox.min.x and p.y >= map.bbox.min.y and p.x <= map.bbox.max.x and p.y <= map.bbox.max.y);
const offset = map.offsetof(p);
return map.map[offset];
}
pub fn get(map: *const Self, p: Vec2) ?Tile {
if (p.x < map.bbox.min.x or p.y < map.bbox.min.y)
return null;
if (p.x > map.bbox.max.x or p.y > map.bbox.max.y)
return null;
if (allow_negative_pos) {
if (p.x > Self.stride / 2 or -p.x > Self.stride / 2)
return null;
} else {
if (p.x < 0 or p.y < 0)
return null;
}
const offset = map.offsetof(p);
if (offset >= map.map.len)
return null;
return map.map[offset];
}
pub fn set(map: *Self, p: Vec2, t: Tile) void {
map.growBBox(p);
const offset = map.offsetof(p);
map.map[offset] = t;
}
pub fn setLine(map: *Self, p: Vec2, t: []const Tile) void {
if (allow_negative_pos) {
assert(p.x <= Self.stride / 2 and -p.x <= Self.stride / 2);
assert(p.x + @intCast(i32, t.len - 1) <= Self.stride / 2 and -p.x + @intCast(i32, t.len - 1) <= Self.stride / 2);
} else {
assert(p.x >= 0 and p.y >= 0);
}
map.growBBox(p);
map.growBBox(p.add(Vec2{ .x = @intCast(i32, t.len - 1), .y = 0 }));
const offset = map.offsetof(p);
std.mem.copy(Tile, map.map[offset .. offset + t.len], t);
}
const Iterator = struct {
map: *Self,
b: BBox,
p: Vec2,
pub fn next(self: *@This()) ?Tile {
if (self.p.y > self.b.max.y) return null;
const t = self.map.at(self.p);
self.p.x += 1;
if (self.p.x > self.b.max.x) {
self.p.x = self.b.min.x;
self.p.y += 1;
}
return t;
}
pub fn nextPos(self: *@This()) ?Vec2 {
if (self.p.y > self.b.max.y) return null;
const t = self.p;
self.p.x += 1;
if (self.p.x > self.b.max.x) {
self.p.x = self.b.min.x;
self.p.y += 1;
}
return t;
}
const TileAndNeighbours = struct {
t: *Tile,
p: Vec2,
neib: [4]?Tile,
up_left: ?Tile,
up: ?Tile,
up_right: ?Tile,
left: ?Tile,
right: ?Tile,
down_left: ?Tile,
down: ?Tile,
down_right: ?Tile,
};
pub fn nextEx(self: *@This()) ?TileAndNeighbours {
if (self.p.y > self.b.max.y) return null;
const t: *Tile = &self.map.map[self.map.offsetof(self.p)];
const n = [4]?Tile{
self.map.get(self.p.add(Vec2{ .x = 1, .y = 0 })),
self.map.get(self.p.add(Vec2{ .x = -1, .y = 0 })),
self.map.get(self.p.add(Vec2{ .x = 0, .y = 1 })),
self.map.get(self.p.add(Vec2{ .x = 0, .y = -1 })),
};
var r = TileAndNeighbours{
.t = t,
.p = self.p,
.neib = n,
.up_left = self.map.get(self.p.add(Vec2{ .x = -1, .y = -1 })),
.up = self.map.get(self.p.add(Vec2{ .x = 0, .y = -1 })),
.up_right = self.map.get(self.p.add(Vec2{ .x = 1, .y = -1 })),
.left = self.map.get(self.p.add(Vec2{ .x = -1, .y = 0 })),
.right = self.map.get(self.p.add(Vec2{ .x = 1, .y = 0 })),
.down_left = self.map.get(self.p.add(Vec2{ .x = -1, .y = 1 })),
.down = self.map.get(self.p.add(Vec2{ .x = 0, .y = 1 })),
.down_right = self.map.get(self.p.add(Vec2{ .x = 1, .y = 1 })),
};
self.p.x += 1;
if (self.p.x > self.b.max.x) {
self.p.x = self.b.min.x;
self.p.y += 1;
}
return r;
}
};
pub fn iter(map: *Self, clip: ?BBox) Iterator {
const b = if (clip) |box|
BBox{
.min = Vec2.max(map.bbox.min, box.min),
.max = Vec2.min(map.bbox.max, box.max),
}
else
map.bbox;
return Iterator{ .map = map, .b = b, .p = b.min };
}
};
}
// -----------------------------------------------------------
// ----- CircularBuffer
// -----------------------------------------------------------
pub fn CircularBuffer(comptime T: anytype) type {
return struct {
const Node = struct { item: T, prev: *Node, next: ?*Node };
arena: std.heap.ArenaAllocator,
cur: ?*Node = null,
recyclebin: ?*Node = null,
len: usize = 0,
pub fn init(allocator: std.mem.Allocator) @This() {
return .{ .arena = std.heap.ArenaAllocator.init(allocator) };
}
pub fn deinit(self: @This()) void {
self.arena.deinit();
}
pub fn reserve(self: *@This(), nb: usize) !void {
const nodes = try self.arena.allocator().alloc(Node, nb);
var next = self.recyclebin;
for (nodes) |*n| {
n.next = next;
next = n;
}
self.recyclebin = &nodes[nodes.len - 1];
}
pub fn pushHead(self: *@This(), item: T) !void {
const new = blk: {
if (self.recyclebin) |node| {
self.recyclebin = node.next;
break :blk node;
} else {
break :blk try self.arena.allocator().create(Node);
}
};
new.item = item;
if (self.cur) |cur| {
new.prev = cur.prev;
cur.prev.next = new;
new.next = cur;
cur.prev = new;
} else {
new.prev = new;
new.next = new;
}
self.cur = new;
self.len += 1;
}
pub fn pushTail(self: *@This(), item: T) !void {
try self.pushHead(item);
self.rotate(1);
}
pub fn pop(self: *@This()) ?T {
if (self.cur) |cur| {
self.len -= 1;
if (cur.next == cur) {
self.cur = null;
} else {
cur.next.?.prev = cur.prev;
cur.prev.next = cur.next;
self.cur = cur.next;
}
cur.next = if (self.recyclebin) |n| n else null;
self.recyclebin = cur;
return cur.item;
} else {
return null;
}
}
pub fn count(self: *@This()) usize {
return self.len;
}
pub fn rotate(self: *@This(), amount: isize) void {
if (self.cur) |cur| {
var ptr = cur;
var a = amount;
while (a != 0) {
ptr = if (a > 0) ptr.next.? else ptr.prev;
a = if (a > 0) a - 1 else a + 1;
}
self.cur = ptr;
}
}
const Iterator = struct {
start: ?*const Node,
ptr: ?*const Node,
pub fn next(self: *Iterator) ?T {
if (self.ptr) |ptr| {
self.ptr = if (ptr.next == self.start) null else ptr.next;
return ptr.item;
} else {
return null;
}
}
};
pub fn iter(self: @This()) Iterator {
return Iterator{ .start = self.cur, .ptr = self.cur };
}
};
}
// -----------------------------------------------------------
// ----- Search
// -----------------------------------------------------------
pub fn BestFirstSearch(comptime State: type, comptime Trace: type) type {
return struct {
pub const Node = struct {
rating: i32, // explore les noeuds avec le plus petit rating en premier
cost: u32,
state: State,
trace: Trace,
};
const Self = @This();
const Agenda = std.PriorityDequeue(*Node, void, compare_ratings);
const VisitedNodes = if (State == []const u8) std.StringHashMap(*const Node) else std.AutoHashMap(State, *const Node);
arena: std.heap.ArenaAllocator,
agenda: Agenda,
recyclebin: ?*Node,
visited: VisitedNodes,
fn compare_ratings(_: void, a: *const Node, b: *const Node) std.math.Order {
return std.math.order(a.rating, b.rating);
}
pub fn init(allocator: std.mem.Allocator) Self {
return Self{
.arena = std.heap.ArenaAllocator.init(allocator),
.agenda = Self.Agenda.init(allocator, {}),
.recyclebin = null,
.visited = Self.VisitedNodes.init(allocator),
};
}
pub fn deinit(s: *Self) void {
s.visited.deinit();
s.agenda.deinit();
s.arena.deinit();
}
pub fn insert(s: *Self, node: Node) !void {
if (s.visited.get(node.state)) |v| {
if (v.cost <= node.cost) {
return;
}
}
const poolelem = if (s.recyclebin) |n| n else try s.arena.allocator().create(Node);
s.recyclebin = null;
poolelem.* = node;
try s.agenda.add(poolelem);
if (try s.visited.fetchPut(node.state, poolelem)) |kv| { // overwriten state with better cost?
assert(kv.value != poolelem);
var it = s.agenda.iterator();
var i: usize = 0;
while (it.next()) |n| : (i += 1) {
if (n == kv.value) {
const removed = s.agenda.removeIndex(i);
assert(removed == kv.value);
s.recyclebin = removed;
break;
}
}
}
}
pub fn pop(s: *Self) ?Node {
if (s.agenda.removeMinOrNull()) |n| {
// s.recyclebin = n; non! car le ptr est aussi dans s.visited
return n.*;
} else {
return null;
}
}
};
}
fn fact(n: usize) usize {
var f: usize = 1;
var i: usize = 0;
while (i < n) : (i += 1) f *= (i + 1);
return f;
}
fn binomial(n: usize, k: usize) usize {
// donne le nombre de parties de k éléments dans un ensemble de n éléments
assert(k <= n);
return fact(n) / (fact(k) * fact(n - k));
}
fn PermutationsIterator(comptime T: type) type {
return struct {
in: []const T,
index: usize,
len: usize,
pub fn next(self: *@This(), buf: []T) ?[]const T {
if (self.index >= self.len) return null;
var mod = self.in.len;
var k = self.index;
self.index += 1;
const out = buf[0..self.in.len];
std.mem.copy(T, out, self.in);
for (out) |*e, i| {
const t = e.*;
e.* = out[i + k % mod];
out[i + k % mod] = t;
k /= mod;
mod -= 1;
}
return out;
}
};
}
pub fn generate_permutations(comptime T: type, in: []const T) PermutationsIterator(T) {
return PermutationsIterator(T){
.in = in,
.index = 0,
.len = fact(in.len),
};
}
fn UniquePermutationsIterator(comptime T: type) type {
return struct {
iter: PermutationsIterator(T),
arena: *std.heap.ArenaAllocator,
previous_permuts: std.StringHashMap(void),
fn deinit(self: *@This()) void {
const root_allocator = self.arena.child_allocator;
self.previous_permuts.deinit();
self.arena.deinit();
root_allocator.destroy(self.arena);
}
fn next(self: *@This()) !?[]const T {
const buf = try self.arena.allocator().alloc(T, self.iter.in.len);
while (self.iter.next(buf)) |out| {
const res = try self.previous_permuts.getOrPut(out);
if (res.found_existing) {
continue;
} else {
return out;
}
}
return null;
}
};
}
pub fn generate_unique_permutations(comptime T: type, in: []const T, allocator: std.mem.Allocator) !UniquePermutationsIterator(T) {
const arena = try allocator.create(std.heap.ArenaAllocator);
arena.* = std.heap.ArenaAllocator.init(allocator);
var it = UniquePermutationsIterator(T){
.iter = generate_permutations(T, in),
.arena = arena,
.previous_permuts = std.StringHashMap(void).init(arena.allocator()),
};
try it.previous_permuts.ensureTotalCapacity(it.iter.len);
return it;
}
// -----------------------------------------------------------
// ----- text stuff
// -----------------------------------------------------------
pub const Arg = union(enum) {
lit: []const u8,
imm: i64,
};
pub fn match_pattern_hexa(comptime pattern: []const u8, text: []const u8) ?[9]Arg {
return match_pattern_common(pattern, text, 16);
}
pub fn match_pattern(comptime pattern: []const u8, text: []const u8) ?[9]Arg {
return match_pattern_common(pattern, text, 10);
}
fn match_pattern_common(comptime pattern: []const u8, text: []const u8, radix: u8) ?[9]Arg {
const txt = std.mem.trim(u8, text, " \n\r\t");
if (txt.len == 0)
return null;
var in: usize = 0;
var out: usize = 0;
var values: [9]Arg = undefined;
var it = std.mem.split(u8, pattern, "{}");
var firstpart = it.next() orelse return null;
if (txt.len < firstpart.len)
return null;
if (!std.mem.eql(u8, txt[0..firstpart.len], firstpart))
return null;
in += firstpart.len;
while (it.next()) |part| {
const next = blk: {
if (txt.len < part.len)
return null;
if (part.len == 0)
break :blk txt.len;
var n = in;
while (n <= txt.len - part.len) : (n += 1) {
if (std.mem.eql(u8, txt[n .. n + part.len], part)) break :blk n;
}
return null;
};
if (std.fmt.parseInt(i64, std.mem.trim(u8, txt[in..next], " \t"), radix)) |imm| {
values[out] = Arg{ .imm = imm };
out += 1;
} else |_| {
values[out] = Arg{ .lit = txt[in..next] };
out += 1;
}
in = next + part.len;
}
return values;
}
pub fn fmt_bufAppend(storage: []u8, i: *usize, comptime fmt: []const u8, v: anytype) void {
const r = std.fmt.bufPrint(storage[i.*..], fmt, v) catch unreachable;
i.* += r.len;
}
pub fn nameToEnum(T: anytype, name: []const u8) !T {
for (std.meta.fieldNames(T)) |it, i| {
if (std.mem.eql(u8, it, name))
return std.meta.intToEnum(T, i) catch unreachable;
} else return error.InvalidEnumName;
}
// -----------------------------------------------------------
// ----- Modular arithmetic
// -----------------------------------------------------------
pub fn ModArith(comptime T: type) type {
assert(@typeInfo(T) == .Int);
var T2Info = @typeInfo(T);
T2Info.Int.bits *= 2; // to fit temp values of T * T
const T2 = @Type(T2Info);
return struct {
fn mod(a: T2, m: T) T {
return @intCast(T, @mod(a, m));
}
pub fn pow(base: T, exp: T, m: T) T {
var result: T = 1;
var e = exp;
var b = base;
while (e > 0) {
if ((e & 1) != 0) result = mod(@as(T2, result) * b, m);
e = @divFloor(e, 2);
b = mod(@as(T2, b) * b, m);
}
return result;
}
pub fn inv(base: T, m: T) T {
// https://fr.wikipedia.org/wiki/Algorithme_d%27Euclide_%C3%A9tendu
// Sortie : r[0] = pgcd(base, m) et r[0] = base*r[1]+m*r[2] -> si r[0] = 1, r[1] est l'inverse de base % m
var r: @Vector(2, T) = [_]T{ base, 1 };
var r1: @Vector(2, T) = [_]T{ m, 0 };
while (r1[0] != 0) {
const q = @divFloor(r[0], r1[0]);
const t = r;
r = r1;
r1 = t - @splat(2, q) * r1;
}
assert(r[0] == 1); // base et m ne sont pas premiers entre eux.
assert(@mod((r[1] * @as(T2, base)), m) == 1);
return r[1];
}
pub const AffineFunc = struct {
a: T,
b: T,
const Func = @This();
pub fn eval(f: Func, x: T, m: T) T {
return mod(@as(T2, x) * f.a + f.b, m);
}
pub fn compose(f: Func, g: Func, m: T) Func {
return Func{
.a = mod(@as(T2, f.a) * g.a, m),
.b = mod(@as(T2, f.a) * g.b + f.b, m),
};
}
pub fn invert(f: Func, m: T) Func {
// y=ax+b -> x = y/a - b/a
return Func{
.a = inv(f.a, m),
.b = mod(-@as(T2, f.b) * inv(f.a, m), m),
};
}
pub fn autocompose(f: Func, times: T, m: T) Func {
// f = f(f(f(f(...))))
// ax+b -> a(ax+b)+b -> a(a(ax+b)+b)+b a3x+(a2+a+1)b
// ... an.x + b.(an-1)/(a-1)
return Func{
.a = pow(f.a, times, m),
.b = mod(@mod(@as(T2, f.b) * (pow(f.a, times, m) - 1), m) * inv(f.a - 1, m), m),
};
}
};
};
}
test "ModArith" {
const MA = ModArith(i32);
const AffineFunc = MA.AffineFunc;
try std.testing.expectEqual(MA.inv(1, 32), 1);
try std.testing.expectEqual(MA.inv(3, 32), 11);
try std.testing.expectEqual(MA.inv(5, 77), 31);
try std.testing.expectEqual(MA.inv(22, 101), 23);
try std.testing.expectEqual(MA.pow(12345, 1, 32768), 12345);
try std.testing.expectEqual(MA.pow(1, 12345, 32768), 1);
try std.testing.expectEqual(MA.pow(2, 5, 100), 32);
try std.testing.expectEqual(MA.pow(2, 5, 10), 2);
const m = 101;
const f = AffineFunc{ .a = 23, .b = 34 };
try std.testing.expectEqual(f.eval(0, m), 34);
try std.testing.expectEqual(f.eval(1, m), 57);
try std.testing.expectEqual(f.eval(5, m), 48);
const g = AffineFunc{ .a = 56, .b = 78 };
const fg = AffineFunc.compose(f, g, m);
try std.testing.expectEqual(fg.eval(0, m), f.eval(g.eval(0, m), m));
try std.testing.expectEqual(fg.eval(1, m), f.eval(g.eval(1, m), m));
try std.testing.expectEqual(fg.eval(11, m), f.eval(g.eval(11, m), m));
const ffff = AffineFunc.autocompose(f, 4, m);
try std.testing.expectEqual(ffff.eval(0, m), f.eval(f.eval(f.eval(f.eval(0, m), m), m), m));
try std.testing.expectEqual(ffff.eval(1, m), f.eval(f.eval(f.eval(f.eval(1, m), m), m), m));
try std.testing.expectEqual(ffff.eval(42, m), f.eval(f.eval(f.eval(f.eval(42, m), m), m), m));
const i = AffineFunc.invert(f, m);
try std.testing.expectEqual(i.eval(f.eval(0, m), m), 0);
try std.testing.expectEqual(i.eval(f.eval(1, m), m), 1);
try std.testing.expectEqual(i.eval(f.eval(42, m), m), 42);
}
// -----------------------------------------------------------
// ----- AOC2019 intcode
// -----------------------------------------------------------
pub const IntCode_Computer = struct {
pc: usize = undefined,
base: Data = undefined,
memory: []Data,
io_mode: IOMode = undefined,
io_port: Data = undefined,
io_runframe: @Frame(run) = undefined,
name: []const u8,
debug_trace: bool = false,
pub const Data = i64;
const Self = @This();
const halted: usize = 9999999;
const OperandType = enum(u1) {
any,
adr,
};
const OperandMode = enum(u2) {
pos,
imm,
rel,
};
const Operation = enum(u4) {
hlt,
jne,
jeq,
add,
mul,
slt,
seq,
in,
out,
err,
arb,
};
const Instruction = struct {
op: Operation,
operands: []const OperandType,
name: []const u8,
};
const insn_table = build_instruction_table();
fn add_insn(op: Operation, name: []const u8, code: u8, operands: []const OperandType, table: []Instruction) void {
table[code].op = op;
table[code].name = name;
table[code].operands = operands;
}
fn build_instruction_table() [100]Instruction {
var table = [1]Instruction{.{ .op = Operation.err, .name = "invalid", .operands = &[_]OperandType{} }} ** 100;
add_insn(.hlt, "ctl.HALT", 99, &[_]OperandType{}, &table);
add_insn(.jne, "ctl.JNE", 5, &[_]OperandType{ .any, .any }, &table); // jump-if-true
add_insn(.jeq, "ctl.JEQ", 6, &[_]OperandType{ .any, .any }, &table); // jump-if-false
add_insn(.add, "alu.ADD", 1, &[_]OperandType{ .any, .any, .adr }, &table);
add_insn(.mul, "alu.MUL", 2, &[_]OperandType{ .any, .any, .adr }, &table);
add_insn(.slt, "alu.SLT", 7, &[_]OperandType{ .any, .any, .adr }, &table); // set if less than
add_insn(.seq, "alu.SEQ", 8, &[_]OperandType{ .any, .any, .adr }, &table); // set if zero
add_insn(.arb, "alu.ARB", 9, &[_]OperandType{.any}, &table); // adjust relative base
add_insn(.in, "io.IN ", 3, &[_]OperandType{.adr}, &table);
add_insn(.out, "io.OUT ", 4, &[_]OperandType{.any}, &table);
return table;
}
fn parse_mode(v: usize) !OperandMode {
switch (v) {
0 => return .pos,
1 => return .imm,
2 => return .rel,
else => return error.unknownMode, //@panic("unknown mode"),
}
}
const ParsedOpcode = struct { opcode: u8, modes: [3]OperandMode };
fn parse_opcode(v: Data) !ParsedOpcode {
const opcode_and_modes = @intCast(u64, v);
return ParsedOpcode{
.opcode = @intCast(u8, opcode_and_modes % 100),
.modes = [3]OperandMode{
try parse_mode((opcode_and_modes / 100) % 10),
try parse_mode((opcode_and_modes / 1000) % 10),
try parse_mode((opcode_and_modes / 10000) % 10),
},
};
}
fn parse_opcode_nofail(v: Data) ParsedOpcode {
const div = @Vector(4, u16){ 1, 100, 1000, 10000 };
const mod = @Vector(4, u16){ 100, 10, 10, 10 };
const opcode_and_modes = (@splat(4, @intCast(u16, v)) / div) % mod;
return ParsedOpcode{
.opcode = @intCast(u8, opcode_and_modes[0]),
.modes = [3]OperandMode{
@intToEnum(OperandMode, opcode_and_modes[1]),
@intToEnum(OperandMode, opcode_and_modes[2]),
@intToEnum(OperandMode, opcode_and_modes[3]),
},
};
}
fn load_param(par: Data, t: OperandType, mode: OperandMode, base: Data, mem: []const Data) Data {
switch (t) {
.adr => switch (mode) {
.pos => return par,
.imm => @panic("invalid mode"),
.rel => return par + base,
},
.any => switch (mode) {
.pos => return mem[@intCast(usize, par)],
.imm => return par,
.rel => return mem[@intCast(usize, par + base)],
},
}
}
pub fn boot(c: *Self, boot_image: []const Data) void {
if (c.debug_trace) print("[{s}] boot\n", .{c.name});
std.mem.copy(Data, c.memory[0..boot_image.len], boot_image);
std.mem.set(Data, c.memory[boot_image.len..], 0);
c.pc = 0;
c.base = 0;
c.io_port = undefined;
}
pub fn is_halted(c: *Self) bool {
return c.pc == halted;
}
const IOMode = enum(u1) {
input,
output,
};
pub fn run(c: *Self) void {
while (c.pc != halted) {
// decode insn opcode
const parsed = parse_opcode_nofail(c.memory[c.pc]);
if (c.debug_trace) {
var buf: [100]u8 = undefined;
print("[{s}] {s}\n", .{ c.name, dissamble_insn(&insn_table[parsed.opcode], &parsed.modes, c.memory[c.pc..], &buf) });
}
const operand_len = insn_table[parsed.opcode].operands.len;
const op = insn_table[parsed.opcode].op;
switch (operand_len) {
0 => {
switch (op) {
.hlt => c.pc = halted,
.err => @panic("Illegal instruction"),
else => unreachable,
}
},
1 => {
switch (op) {
.arb => {
const p = [1]Data{
load_param(c.memory[c.pc + 1], .any, parsed.modes[0], c.base, c.memory),
};
c.pc += 2;
c.base += p[0];
},
.in => {
const p = [1]Data{
load_param(c.memory[c.pc + 1], .adr, parsed.modes[0], c.base, c.memory),
};
c.pc += 2;
c.io_mode = .input;
if (c.debug_trace) print("[{s}] reading...\n", .{c.name});
suspend {
c.io_runframe = @frame().*;
}
if (c.debug_trace) print("[{s}] ...got {}\n", .{ c.name, c.io_port });
c.memory[@intCast(usize, p[0])] = c.io_port;
},
.out => {
const p = [1]Data{
load_param(c.memory[c.pc + 1], .any, parsed.modes[0], c.base, c.memory),
};
c.pc += 2;
c.io_mode = .output;
c.io_port = p[0];
if (c.debug_trace) print("[{s}] writing {}...\n", .{ c.name, c.io_port });
suspend {
c.io_runframe = @frame().*;
}
if (c.debug_trace) print("[{s}] ...ok\n", .{c.name});
},
else => unreachable,
}
},
2 => {
// load parameters from insn operands
const p = [2]Data{
load_param(c.memory[c.pc + 1], .any, parsed.modes[0], c.base, c.memory),
load_param(c.memory[c.pc + 2], .any, parsed.modes[1], c.base, c.memory),
};
// execute insn
switch (op) {
.jne => c.pc = if (p[0] != 0) @intCast(usize, p[1]) else c.pc + 3,
.jeq => c.pc = if (p[0] == 0) @intCast(usize, p[1]) else c.pc + 3,
else => unreachable,
}
},
3 => {
// load parameters from insn operands
const p = [3]Data{
load_param(c.memory[c.pc + 1], .any, parsed.modes[0], c.base, c.memory),
load_param(c.memory[c.pc + 2], .any, parsed.modes[1], c.base, c.memory),
load_param(c.memory[c.pc + 3], .adr, parsed.modes[2], c.base, c.memory),
};
c.pc += 4;
// execute insn
switch (op) {
.add => c.memory[@intCast(usize, p[2])] = p[0] +% p[1],
.mul => c.memory[@intCast(usize, p[2])] = p[0] *% p[1],
.slt => c.memory[@intCast(usize, p[2])] = @boolToInt(p[0] < p[1]),
.seq => c.memory[@intCast(usize, p[2])] = @boolToInt(p[0] == p[1]),
else => unreachable,
}
},
else => unreachable,
}
}
}
fn dissamble_insn(insn: *const Instruction, modes: []const OperandMode, operands: []const Data, storage: []u8) []const u8 {
var i: usize = 0;
std.mem.copy(u8, storage[i..], insn.name);
i += insn.name.len;
std.mem.copy(u8, storage[i..], "\t");
i += 1;
for (insn.operands) |optype, j| {
if (j > 0) {
std.mem.copy(u8, storage[i..], ", ");
i += 2;
}
if (j >= operands.len) {
std.mem.copy(u8, storage[i..], "ERR");
i += 3;
} else {
switch (optype) {
.adr => switch (modes[j]) {
.imm => fmt_bufAppend(storage, &i, "ERR{}", .{operands[j]}),
.pos => fmt_bufAppend(storage, &i, "@{}", .{operands[j]}),
.rel => fmt_bufAppend(storage, &i, "@b+{}", .{operands[j]}),
},
.any => switch (modes[j]) {
.imm => fmt_bufAppend(storage, &i, "{}", .{operands[j]}),
.pos => fmt_bufAppend(storage, &i, "[{}]", .{operands[j]}),
.rel => fmt_bufAppend(storage, &i, "[b+{}]", .{operands[j]}),
},
}
}
}
return storage[0..i];
}
pub fn disassemble(image: []const Data) void {
var pc: usize = 0;
while (pc < image.len) {
var insn_size: usize = 1;
var asmstr_storage: [100]u8 = undefined;
const asmstr = blk: {
if (parse_opcode(image[pc])) |parsed| {
const insn = &insn_table[parsed.opcode];
insn_size += insn.operands.len;
break :blk dissamble_insn(insn, &parsed.modes, image[pc + 1 ..], &asmstr_storage);
} else |_| {
break :blk "";
}
};
var datastr_storage: [100]u8 = undefined;
const datastr = blk: {
var i: usize = 0;
var l: usize = 0;
while (i < insn_size) : (i += 1) {
const d = if (pc + i < image.len) image[pc + i] else 0;
fmt_bufAppend(&datastr_storage, &l, "{} ", .{d});
}
break :blk datastr_storage[0..l];
};
print("{d:0>4}: {s:15} {s}\n", .{ pc, datastr, asmstr });
pc += insn_size;
}
}
}; | common/tools.zig |
const std = @import("std");
const min = std.math.min;
const uefi = @import("uefi/uefi.zig");
const graphics_output = uefi.protocols.graphics_output;
pub const Pixel = struct {
red: u8,
blue: u8,
green: u8
};
pub const Frame = struct {
const Self = @This();
pub info: graphics_output.ModeInformation,
pub frame_buffer: [*]u8,
pub fn getPixel(self: *Self, x: usize, y: usize) Pixel {
// TODO
return Pixel{
.red = 0,
.blue = 0,
.green = 0
};
}
pub fn drawPixel(self: *Self, pixel: Pixel, x: usize, y: usize) void {
const PixelFormat = graphics_output.PixelFormat;
const start = 4 * (y * self.info.pixels_per_scan_line + x);
const fb_pixel = self.frame_buffer[start..start + 4];
switch (self.info.pixel_format) {
PixelFormat.RedGreenBlueReserved8BitPerColor => {
fb_pixel[0] = pixel.red;
fb_pixel[1] = pixel.green;
fb_pixel[2] = pixel.blue;
},
PixelFormat.BlueGreenRedReserved8BitPerColor => {
fb_pixel[0] = pixel.blue;
fb_pixel[1] = pixel.green;
fb_pixel[2] = pixel.red;
},
PixelFormat.BitMask => {
// TODO
},
PixelFormat.BltOnly => {
// TODO
}
}
}
};
pub const TextFrame = struct {
const Self = @This();
pub frame: Frame,
pub foreground: Pixel,
pub background: Pixel,
cursor_x: u32,
cursor_y: u32,
max_x: u32,
max_y: u32,
pub fn init(frame: Frame, foreground: Pixel, background: Pixel) Self {
var retval = Self{
.frame = frame,
.foreground = foreground,
.background = background,
.cursor_x = 0,
.cursor_y = 0,
.max_x = frame.info.horizontal_resolution / (unifont_width),
.max_y = frame.info.vertical_resolution / (unifont_height),
};
if (retval.max_x != 0) {
retval.max_x -= 1;
}
if (retval.max_y != 0) {
retval.max_y -= 1;
}
return retval;
}
pub fn print(self: *Self, comptime format: []const u8, args: ...) error{}!void {
return std.fmt.format(self, error{}, putChar, format, args);
}
fn drawChar(self: *Self, char: u8) void {
for (unifont[char]) |line, i| {
for (line) |pixel, j| {
self.frame.drawPixel(if (pixel) self.foreground else self.background,
self.cursor_x * unifont_width + j,
self.cursor_y * unifont_height + i);
}
}
}
fn newLine(self: *Self) void {
self.cursor_x = 0;
if (self.cursor_y < self.max_y) {
self.cursor_y += 1;
} else {
{
var i = u32(unifont_height);
while (i < self.frame.info.vertical_resolution - unifont_height) : (i += 1) {
var j = u32(0);
while (j < self.frame.info.horizontal_resolution) : (j += 1) {
const new = 4 * (i * self.frame.info.pixels_per_scan_line + j);
const old = 4 * ((unifont_height + i) * self.frame.info.pixels_per_scan_line + j);
var k = u32(0);
while (k < 4) : (k += 1) {
self.frame.frame_buffer[new + k] = self.frame.frame_buffer[old + k];
}
}
}
}
{
var i = u32(self.max_y * unifont_height);
while (i < self.frame.info.vertical_resolution) : (i += 1) {
var j = u32(0);
while (j < self.frame.info.horizontal_resolution) : (j += 1) {
self.frame.drawPixel(self.background, i, j);
}
}
}
}
}
};
fn putChar(self: *TextFrame, text: []const u8) error{}!void {
for (text) |char| {
switch (char) {
'\r' => {
self.cursor_x = 0;
},
'\n' => {
self.newLine();
},
else => {
if (self.cursor_x == self.max_x) {
self.newLine();
}
self.drawChar(char);
self.cursor_x += 1;
}
}
}
}
const unifont_width = 8;
const unifont_height = 16;
const unifont = init: {
@setEvalBranchQuota(100000);
const data = @embedFile("../zap-vga16.psf")[4..];
var retval: [256][16][8]bool = undefined;
for (retval) |*char, i| {
for (char) |*line, j| {
for (line) |*pixel, k| {
pixel.* = data[i * 16 + j] & 0b10000000 >> k != 0;
}
}
}
break :init retval;
}; | src/graphics.zig |
const std = @import("std");
const builtin = @import("builtin");
const testing = std.testing;
const types = @import("types.zig");
pub const Double = types.Double;
pub const Float = types.Float;
pub const Int64 = types.Int64;
pub const Int32 = types.Int32;
pub const Uint64 = types.Uint64;
pub const Uint32 = types.Uint32;
pub const Sint64 = types.Sint64;
pub const Sint32 = types.Sint32;
pub const Fixed64 = types.Fixed64;
pub const Fixed32 = types.Fixed32;
pub const Sfixed64 = types.Sfixed64;
pub const Sfixed32 = types.Sfixed32;
pub const Bool = types.Bool;
pub const Bytes = types.Bytes;
pub const String = types.String;
pub const Repeated = types.Repeated;
pub fn StreamingMarshal(comptime T: type) type {
return struct {
const Self = @This();
// TODO: this is so terrible.
// Temporarily sticking this here because I can't make spin a method due to circular references
var out: ?[]const u8 = [_]u8{};
item: T,
frame: @Frame(spin),
pub fn init(item: T) Self {
return Self{
.item = item,
.frame = async spin(item),
};
}
fn spin(item: T) void {
var buffer: [1000]u8 = undefined;
var bufslice = buffer[0..];
inline for (@typeInfo(T).Struct.fields) |field, i| {
switch (@typeInfo(field.field_type)) {
.Struct => {
if (@hasDecl(field.field_type, "field_meta")) {
suspend;
Self.out = field.field_type.field_meta.encodeInto(bufslice);
suspend;
Self.out = @field(item, field.name).encodeInto(bufslice);
} else {
std.debug.warn("{} - unknown struct\n", field.name);
}
},
else => {
std.debug.warn("{} - not a struct\n", field.name);
},
}
}
suspend;
Self.out = null;
}
pub fn next(self: *Self) ?[]const u8 {
if (out != null) {
resume self.frame;
return out;
}
return null;
}
};
}
pub fn marshal(comptime T: type, allocator: *std.mem.Allocator, item: T) ![]u8 {
var buffer = std.ArrayList(u8).init(allocator);
errdefer buffer.deinit();
var stream = StreamingMarshal(T).init(item);
while (stream.next()) |data| {
try buffer.appendSlice(data);
}
return buffer.toOwnedSlice();
}
pub fn unmarshal(comptime T: type, allocator: *std.mem.Allocator, bytes: []u8) !T {
var result = init(T);
errdefer deinit(T, result);
var cursor = usize(0);
while (cursor < bytes.len) {
var len: usize = undefined;
const info = try types.FieldMeta.decode(bytes[cursor..], &len);
cursor += len;
inline for (@typeInfo(T).Struct.fields) |field, i| {
switch (@typeInfo(field.field_type)) {
.Struct => {
if (info.number == field.field_type.field_meta.number) {
if (@hasDecl(field.field_type, "decodeFromAlloc")) {
cursor += try @field(result, field.name).decodeFromAlloc(bytes[cursor..], allocator);
} else {
cursor += try @field(result, field.name).decodeFrom(bytes[cursor..]);
}
break;
}
},
else => {
std.debug.warn("{} - not a struct\n", field.name);
},
}
}
}
inline for (@typeInfo(T).Struct.fields) |field, i| {
switch (@typeInfo(field.field_type)) {
.Struct => {
if (@hasDecl(field.field_type, "decodeComplete")) {
@field(result, field.name).decodeComplete();
}
},
else => {
std.debug.warn("{} - not a struct\n", field.name);
},
}
}
return result;
}
pub fn init(comptime T: type) T {
var result: T = undefined;
inline for (@typeInfo(T).Struct.fields) |field, i| {
switch (@typeInfo(field.field_type)) {
.Struct => {
@field(result, field.name) = field.field_type{};
},
else => {
std.debug.warn("{} - not a struct\n", field.name);
},
}
}
return result;
}
pub fn deinit(comptime T: type, msg: *T) void {
inline for (@typeInfo(T).Struct.fields) |field, i| {
switch (@typeInfo(field.field_type)) {
.Struct => {
if (@hasDecl(field.field_type, "deinit")) {
@field(msg, field.name).deinit();
}
},
else => {
std.debug.warn("{} - not a struct\n", field.name);
},
}
}
}
test "end-to-end" {
const Example = struct {
sint: types.Sint64(1),
str: types.String(12),
boo: types.Bool(10),
};
var start = init(Example);
testing.expectEqual(i64(0), start.sint.data);
testing.expectEqual(false, start.boo.data);
testing.expectEqual(start.str.data, "");
testing.expectEqual(start.str.allocator, null);
start.sint.data = -17;
start.boo.data = true;
start.str.data = "weird";
const binary = try marshal(Example, std.heap.direct_allocator, start);
defer std.heap.direct_allocator.free(binary);
var result = try unmarshal(Example, std.heap.direct_allocator, binary);
testing.expectEqual(start.sint.data, result.sint.data);
testing.expectEqual(start.boo.data, result.boo.data);
testing.expectEqualSlices(u8, start.str.data, result.str.data);
testing.expectEqual(std.heap.direct_allocator, result.str.allocator.?);
deinit(Example, &result);
testing.expectEqual(result.str.data, "");
testing.expectEqual(result.str.allocator, null);
} | src/main.zig |
const std = @import("std");
const ArrayList = std.ArrayList;
const core = @import("../index.zig");
const Coord = core.geometry.Coord;
const makeCoord = core.geometry.makeCoord;
const Species = core.protocol.Species;
const game_model = @import("./game_model.zig");
const Individual = game_model.Individual;
const Terrain = game_model.Terrain;
const IdMap = game_model.IdMap;
const oob_terrain = game_model.oob_terrain;
/// overwrites terrain. populates individuals.
pub fn generate(allocator: *std.mem.Allocator, terrain: *Terrain, individuals: *IdMap(*Individual)) !void {
var generator = MapGenerator{
.allocator = allocator,
.terrain = terrain,
.individuals = individuals,
.id_cursor = 1,
._r = undefined,
.random = undefined,
};
// TODO: accept seed parameter
var buf: [8]u8 = undefined;
std.crypto.random.bytes(&buf);
const seed = std.mem.readIntLittle(u64, &buf);
generator._r = std.rand.DefaultPrng.init(seed);
generator.random = &generator._r.random;
return generator.generate();
}
const MapGenerator = struct {
allocator: *std.mem.Allocator,
terrain: *Terrain,
individuals: *IdMap(*Individual),
id_cursor: u32,
_r: std.rand.DefaultPrng,
random: *std.rand.Random,
fn nextId(self: *@This()) u32 {
defer {
self.id_cursor += 1;
}
return self.id_cursor;
}
fn makeIndividual(self: *@This(), small_position: Coord, species: Species) !*Individual {
return (Individual{
.species = species,
.abs_position = .{ .small = small_position },
}).clone(self.allocator);
}
fn generate(self: *@This()) !void {
const width = 30;
const height = 30;
self.terrain.* = try Terrain.initFill(self.allocator, width, height, .{
.floor = .dirt,
.wall = .air,
});
var free_spaces = try ArrayList(Coord).initCapacity(self.allocator, width * height);
var y: i32 = 0;
while (y < height) : (y += 1) {
var x: i32 = 0;
while (x < width) : (x += 1) {
free_spaces.append(makeCoord(x, y)) catch unreachable;
}
}
// You are the human.
try self.individuals.putNoClobber(self.nextId(), try self.makeIndividual(self.popRandom(&free_spaces), .human));
// throw enemies around
{
const count = self.random.intRangeAtMost(usize, 10, 20);
var i: usize = 0;
while (i < count) : (i += 1) {
const fella = try self.makeIndividual(self.popRandom(&free_spaces), .orc);
fella.has_shield = self.random.boolean();
try self.individuals.putNoClobber(self.nextId(), fella);
}
}
// let's throw around some lava.
{
const count = self.random.intRangeAtMost(usize, 40, 80);
var i: usize = 0;
while (i < count) : (i += 1) {
self.terrain.atCoord(self.popRandom(&free_spaces)).?.* = .{
.floor = .lava,
.wall = .air,
};
}
}
// maybe a heal spot
{
const count = self.random.intRangeAtMost(usize, 0, 1);
var i: usize = 0;
while (i < count) : (i += 1) {
self.terrain.atCoord(self.popRandom(&free_spaces)).?.* = .{
.floor = .marble,
.wall = .air,
};
}
}
// and some walls
{
const count = self.random.intRangeAtMost(usize, 20, 40);
var i: usize = 0;
while (i < count) : (i += 1) {
self.terrain.atCoord(self.popRandom(&free_spaces)).?.* = .{
.floor = .dirt,
.wall = .dirt,
};
}
}
// have fun
{
const count = self.random.intRangeAtMost(usize, 1, 2);
var i: usize = 0;
while (i < count) : (i += 1) {
self.terrain.atCoord(self.popRandom(&free_spaces)).?.* = .{
.floor = .dirt,
.wall = .centaur_transformer,
};
}
}
}
fn popRandom(self: *@This(), array: *ArrayList(Coord)) Coord {
return array.swapRemove(self.random.uintLessThan(usize, array.items.len));
}
}; | src/server/map_gen.zig |
const std = @import("std");
const v = @import("v.zig");
// TODO: return normalized vector and magnitude, to allow determining normal even in the case of collisions
/// Returns the closest point to the origin.
pub fn minimumPoint(
shape: anytype,
comptime support: fn (@TypeOf(shape), d: v.Vec2) v.Vec2,
) v.Vec2 {
var s_buf: [3]v.Vec2 = undefined;
var s: []v.Vec2 = s_buf[0..1];
s[0] = support(shape, .{ 1, 0 });
var i: usize = 0;
while (true) {
if (@import("builtin").mode == .Debug) {
i += 1;
if (i > 1_000_000) {
std.debug.panic("GJK failed to converge after 1 million iterations", .{});
}
}
const normal = switch (s.len) {
1 => -s[0],
2 => blk: {
const a = s[0];
const ab = s[1] - a;
break :blk v.tripleCross(ab, -a, ab);
},
else => return simplexMinimumPoint(s),
};
if (@reduce(.And, normal == v.v(0))) {
return v.v(0);
}
const new_point = support(shape, normal);
// std.debug.print("{d} {d} {d}\n", .{ new_point, s, normal });
for (s) |sp| {
if (v.close(sp, new_point, 1 << 48)) {
return simplexMinimumPoint(s);
}
}
s.len += 1;
s[s.len - 1] = new_point;
approachOrigin(&s);
}
}
fn simplexMinimumPoint(s: []v.Vec2) v.Vec2 {
switch (s.len) {
0 => return v.v(0),
1 => return s[0],
2, 3 => { // Length 3 is used as a sentinel, but the value should be calculated along the AB line
const a = s[0];
const ab = s[1] - a;
return a + ab * v.v(v.dot(ab, -a) / v.dot(ab, ab));
},
else => unreachable,
}
}
/// Moves the simplex closer to the origin.
fn approachOrigin(s: *[]v.Vec2) void {
switch (s.len) {
2 => {
const a = s.*[0];
const b = s.*[1];
const ab = b - a;
if (v.dot(ab, -a) < 0) { // Voronoi A
s.len = 1;
} else if (v.dot(-ab, -b) < 0) { // Voronoi B
s.*[0] = b;
s.len = 1;
} else { // Voronoi AB
// No modification needed
}
},
3 => {
const a = s.*[0];
const b = s.*[1];
const c = s.*[2];
const ab = b - a;
const ac = c - a;
const bc = c - b;
// FIXME: this code is horrible; fix it
// Check the last vertex first, to ensure we converge even with degenerate simplices
if (v.dot(-ac, -c) < 0 and v.dot(-bc, -c) < 0) { // Voronoi C
s.*[0] = c;
s.len = 1;
} else if (v.dot(-ab, -b) < 0 and v.dot(bc, -b) < 0) { // Voronoi B
s.*[0] = b;
s.len = 1;
} else if (v.dot(ab, -a) < 0 and v.dot(ac, -a) < 0) { // Voronoi A
s.len = 1;
} else if (v.dot(v.tripleCross(ac, ab, ab), -a) >= 0 and // Voronoi AB
v.dot(ab, -a) >= 0 and v.dot(-ab, -b) >= 0)
{
// If we've hit this case, we need to stop as we'll just infinite loop
// We use length 3 as a sentinel value, so do nothing
} else if (v.dot(v.tripleCross(-ab, bc, bc), -b) >= 0 and // Voronoi BC
v.dot(bc, -b) >= 0 and v.dot(-bc, -c) >= 0)
{
s.*[0] = c;
s.len = 2;
} else if (v.dot(v.tripleCross(ab, ac, ac), -a) >= 0 and // Voronoi CA
v.dot(ac, -a) >= 0 and v.dot(-ac, -c) >= 0)
{
s.*[1] = c;
s.len = 2;
} else { // Voronoi ABC (inside the triangle)
s.len = 0;
}
},
else => unreachable,
}
} | gjk.zig |
const std = @import("std");
const proxywasm = @import("proxy-wasm-zig-sdk");
const allocator = proxywasm.allocator;
const contexts = proxywasm.contexts;
const enums = proxywasm.enums;
const hostcalls = proxywasm.hostcalls;
extern fn __wasm_call_ctors() void;
const vm_id = "ziglang_vm";
pub fn main() void {
// Set up the global RootContext function.
proxywasm.setNewRootContextFunc(newRootContext);
}
// newRootContext is used for creating root contexts for
// each plugin configuration (i.e. config.configuration field in envoy.yaml).
fn newRootContext(context_id: usize) *contexts.RootContext {
_ = context_id;
var context: *Root = allocator.create(Root) catch unreachable;
context.init();
return &context.root_context;
}
// PluginConfiguration is a schema of the configuration.
// We parse a given configuration in json to this.
const PluginConfiguration = struct {
root: []const u8,
http: []const u8,
tcp: []const u8,
};
// We implement interfaces defined in contexts.RootContext (the fields suffixed with "Impl")
// for this "Root" type. See https://www.nmichaels.org/zig/interfaces.html for detail.
const Root = struct {
const Self = @This();
// Store the "implemented" contexts.RootContext.
root_context: contexts.RootContext = undefined,
// Store the parsed plugin configuration in onPluginStart.
plugin_configuration: PluginConfiguration,
// The counter metric ID for storing total data received by tcp filter.
tcp_total_data_size_counter_metric_id: ?u32 = null,
// The guage metric ID for storing randam values in onTick function.
random_gauge_metric_id: ?u32 = null,
// The counter metric ID for storing the number of onTick being called.
tick_counter_metric_id: ?u32 = null,
// The shared queue ID of receiving user-agents.
user_agent_shared_queue_id: ?u32 = null,
const tcp_total_data_size_counter_metric_name = "zig_sdk_tcp_total_data_size";
const random_gauge_metric_name = "random_gauge";
const tick_counter_metric_name = "on_tick_count";
const user_agent_shared_queue_name = "user-agents";
const random_shared_data_key = "random_data";
const random_property_path = "random_property";
// Initialize root_context.
fn init(self: *Self) void {
// TODO: If we inline this initialization as a part of default value of root_context,
// we have "Uncaught RuntimeError: table index is out of bounds" on proxy_on_vm_start.
// Needs investigation.
self.root_context = contexts.RootContext{
.onVmStartImpl = onVmStart,
.onPluginStartImpl = onPluginStart,
.onPluginDoneImpl = onPluginDone,
.onDeleteImpl = onDelete,
.newHttpContextImpl = newHttpContext,
.newTcpContextImpl = newTcpContext,
.onQueueReadyImpl = onQueueReady,
.onTickImpl = onTick,
.onHttpCalloutResponseImpl = null,
};
}
// Implement contexts.RootContext.onVmStart.
fn onVmStart(root_context: *contexts.RootContext, configuration_size: usize) bool {
_ = @fieldParentPtr(Self, "root_context", root_context);
// Log the VM configuration.
if (configuration_size > 0) {
var configuration = hostcalls.getBufferBytes(enums.BufferType.VmConfiguration, 0, configuration_size) catch unreachable;
defer configuration.deinit();
const message = std.fmt.allocPrint(
allocator,
"vm configuration: {s}",
.{configuration.raw_data},
) catch unreachable;
defer allocator.free(message);
hostcalls.log(enums.LogLevel.Info, message) catch unreachable;
}
return true;
}
// Implement contexts.RootContext.onPluginStart.
fn onPluginStart(root_context: *contexts.RootContext, configuration_size: usize) bool {
const self: *Self = @fieldParentPtr(Self, "root_context", root_context);
// Get plugin configuration data.
std.debug.assert(configuration_size > 0);
var plugin_config_data = hostcalls.getBufferBytes(enums.BufferType.PluginConfiguration, 0, configuration_size) catch unreachable;
defer plugin_config_data.deinit();
// Parse it to ConfigurationData struct.
var stream = std.json.TokenStream.init(plugin_config_data.raw_data);
self.plugin_configuration = std.json.parse(
PluginConfiguration,
&stream,
.{ .allocator = allocator },
) catch unreachable;
// Log the given and parsed configuration.
const message = std.fmt.allocPrint(
allocator,
"plugin configuration: root=\"{s}\", http=\"{s}\", stream=\"{s}\"",
.{
self.plugin_configuration.root,
self.plugin_configuration.http,
self.plugin_configuration.tcp,
},
) catch unreachable;
defer allocator.free(message);
hostcalls.log(enums.LogLevel.Info, message) catch unreachable;
if (std.mem.eql(u8, self.plugin_configuration.root, "singleton")) {
// Set tick if the "root" configuration is set to "singleton".
hostcalls.setTickPeriod(5000);
// Register the shared queue named "user-agent-queue".
_ = hostcalls.registerSharedQueue(user_agent_shared_queue_name) catch unreachable;
}
return true;
}
// Implement contexts.RootContext.onPluginDone.
fn onPluginDone(root_context: *contexts.RootContext) bool {
const self: *Self = @fieldParentPtr(Self, "root_context", root_context);
// Log the given and parsed configuration.
const message = std.fmt.allocPrint(
allocator,
"shutting down the plugin with configuration: root=\"{s}\", http=\"{s}\", stream=\"{s}\"",
.{
self.plugin_configuration.root,
self.plugin_configuration.http,
self.plugin_configuration.tcp,
},
) catch unreachable;
defer allocator.free(message);
hostcalls.log(enums.LogLevel.Info, message) catch unreachable;
return true;
}
// Implement contexts.RootContext.onDelete.
fn onDelete(root_context: *contexts.RootContext) void {
const self: *Self = @fieldParentPtr(Self, "root_context", root_context);
// Destory the configura allocated during json parsing.
std.json.parseFree(PluginConfiguration, self.plugin_configuration, .{ .allocator = allocator });
// Destroy myself.
allocator.destroy(self);
}
// Implement contexts.RootContext.newHttpContext.
fn newTcpContext(root_context: *contexts.RootContext, context_id: u32) ?*contexts.TcpContext {
const self: *Self = @fieldParentPtr(Self, "root_context", root_context);
// Switch type of HcpContext based on the configuration.
if (std.mem.eql(u8, self.plugin_configuration.tcp, "total-data-size-counter")) {
// Initialize tick counter metric id.
if (self.tcp_total_data_size_counter_metric_id == null) {
self.tcp_total_data_size_counter_metric_id = hostcalls.defineMetric(
enums.MetricType.Counter,
tcp_total_data_size_counter_metric_name,
) catch unreachable;
}
// Create TCP context with TcpTotalDataSizeCounter implementation.
var context: *TcpTotalDataSizeCounter = allocator.create(TcpTotalDataSizeCounter) catch unreachable;
context.init(context_id, self.tcp_total_data_size_counter_metric_id.?);
return &context.tcp_context;
}
return null;
}
// Implement contexts.RootContext.newHttpContext.
fn newHttpContext(root_context: *contexts.RootContext, context_id: u32) ?*contexts.HttpContext {
const self: *Self = @fieldParentPtr(Self, "root_context", root_context);
// Switch type of HttpContext based on the configuration.
if (std.mem.eql(u8, self.plugin_configuration.http, "header-operation")) {
// Initialize tick counter metric id.
if (self.tick_counter_metric_id == null) {
self.tick_counter_metric_id = hostcalls.defineMetric(enums.MetricType.Counter, tick_counter_metric_name) catch unreachable;
}
// Resolve the "user-agents" shared queue
if (self.user_agent_shared_queue_id == null) {
self.user_agent_shared_queue_id = hostcalls.resolveSharedQueue(vm_id, user_agent_shared_queue_name) catch null;
}
// Create HTTP context with HttpHeaderOperation implementation.
var context: *HttpHeaderOperation = allocator.create(HttpHeaderOperation) catch unreachable;
context.init(context_id, self.tick_counter_metric_id.?, random_shared_data_key, self.user_agent_shared_queue_id);
return &context.http_context;
} else if (std.mem.eql(u8, self.plugin_configuration.http, "body-operation")) {
// Create HTTP context with HttpBodyOperation implementation.
var context: *HttpBodyOperation = allocator.create(HttpBodyOperation) catch unreachable;
context.init();
return &context.http_context;
} else if (std.mem.eql(u8, self.plugin_configuration.http, "random-auth")) {
// Create HTTP context with HttpRandomAuth implementation.
var context: *HttpRandomAuth = allocator.create(HttpRandomAuth) catch unreachable;
context.init();
return &context.http_context;
}
return null;
}
// Implement contexts.RootContext.onTick.
fn onQueueReady(root_context: *contexts.RootContext, quque_id: u32) void {
_ = root_context;
// We know that this is called for user-agents queue since that's the only queue we registered.
// Since we are in a singleton, we can assume that this Wasm VM is the only VM to dequeue this queue.
// So we can ignore the error returned by dequeueSharedQueue including Empty error.
var ua = hostcalls.dequeueSharedQueue(quque_id) catch unreachable;
defer ua.deinit();
// Log the user-agent.
const message = std.fmt.allocPrint(allocator, "user-agent {s} is dequeued.", .{ua.raw_data}) catch unreachable;
defer allocator.free(message);
hostcalls.log(enums.LogLevel.Info, message) catch unreachable;
}
// Implement contexts.RootContext.onTick.
fn onTick(root_context: *contexts.RootContext) void {
const self: *Self = @fieldParentPtr(Self, "root_context", root_context);
// Log the current timestamp.
const message = std.fmt.allocPrint(
allocator,
"on tick called at {d}",
.{std.time.nanoTimestamp()},
) catch unreachable;
defer allocator.free(message);
hostcalls.log(enums.LogLevel.Info, message) catch unreachable;
// Initialize the metric id of the tick counter.
if (self.tick_counter_metric_id == null) {
self.tick_counter_metric_id = hostcalls.defineMetric(enums.MetricType.Counter, tick_counter_metric_name) catch unreachable;
}
// Increment the tick counter.
hostcalls.incrementMetric(self.tick_counter_metric_id.?, 1) catch unreachable;
// Initialize the metric id of the random gauge.
if (self.random_gauge_metric_id == null) {
self.random_gauge_metric_id = hostcalls.defineMetric(enums.MetricType.Gauge, random_gauge_metric_name) catch unreachable;
}
// Record a cryptographically secure random value on the gauge.
var buf: [8]u8 = undefined;
std.crypto.random.bytes(buf[0..]);
hostcalls.recordMetric(self.random_gauge_metric_id.?, std.mem.readIntLittle(u64, buf[0..])) catch unreachable;
// Insert the random value to the shared key value store.
hostcalls.setSharedData(random_shared_data_key, buf[0..], 0) catch unreachable;
}
};
const TcpTotalDataSizeCounter = struct {
const Self = @This();
// Store the "implemented" contexts.TcpContext.
tcp_context: contexts.TcpContext = undefined,
context_id: u32 = undefined,
total_data_size_counter_metric_id: u32 = undefined,
fn init(self: *Self, context_id: u32, metric_id: u32) void {
self.context_id = context_id;
self.total_data_size_counter_metric_id = metric_id;
self.tcp_context = contexts.TcpContext{
.onNewConnectionImpl = onNewConnection,
.onDownstreamDataImpl = onDownstreamData,
.onDownstreamCloseImpl = onDownstreamClose,
.onUpstreamDataImpl = onUpstreamData,
.onUpstreamCloseImpl = onUpstreamClose,
.onLogImpl = onLog,
.onHttpCalloutResponseImpl = null,
.onDeleteImpl = onDelete,
};
const message = std.fmt.allocPrint(
allocator,
"TcpTotalDataSizeCounter context created: {d}",
.{self.context_id},
) catch unreachable;
defer allocator.free(message);
hostcalls.log(enums.LogLevel.Info, message) catch unreachable;
}
// Implement contexts.TcpContext.onNewConnection.
fn onNewConnection(tcp_context: *contexts.TcpContext) enums.Action {
const self: *Self = @fieldParentPtr(Self, "tcp_context", tcp_context);
const message = std.fmt.allocPrint(
allocator,
"connection established: {d}",
.{self.context_id},
) catch unreachable;
defer allocator.free(message);
hostcalls.log(enums.LogLevel.Info, message) catch unreachable;
return enums.Action.Continue;
}
// Implement contexts.TcpContext.onDownstreamData.
fn onDownstreamData(tcp_context: *contexts.TcpContext, data_size: usize, end_of_stream: bool) enums.Action {
_ = end_of_stream;
const self = @fieldParentPtr(Self, "tcp_context", tcp_context);
// Increment the total data size counter.
if (data_size > 0) {
hostcalls.incrementMetric(self.total_data_size_counter_metric_id, data_size) catch unreachable;
}
return enums.Action.Continue;
}
// Implement contexts.TcpContext.onDownstreamClose.
fn onDownstreamClose(tcp_context: *contexts.TcpContext, peer_type: enums.PeerType) void {
_ = @fieldParentPtr(Self, "tcp_context", tcp_context);
_ = peer_type;
// Get source addess of this connection.
const path: [2][]const u8 = [2][]const u8{ "source", "address" };
var source_addess = hostcalls.getProperty(path[0..]) catch unreachable;
defer source_addess.deinit();
// Log the downstream remote addess.
const message = std.fmt.allocPrint(
allocator,
"downstream connection for peer at {s}",
.{source_addess.raw_data},
) catch unreachable;
defer allocator.free(message);
hostcalls.log(enums.LogLevel.Info, message) catch unreachable;
}
// Implement contexts.TcpContext.onUpstreamData.
fn onUpstreamData(tcp_context: *contexts.TcpContext, data_size: usize, end_of_stream: bool) enums.Action {
const self: *Self = @fieldParentPtr(Self, "tcp_context", tcp_context);
_ = end_of_stream;
// Increment the total data size counter.
if (data_size > 0) {
hostcalls.incrementMetric(self.total_data_size_counter_metric_id, data_size) catch unreachable;
}
return enums.Action.Continue;
}
// Implement contexts.TcpContext.onUpstreamClose.
fn onUpstreamClose(tcp_context: *contexts.TcpContext, peer_type: enums.PeerType) void {
_ = @fieldParentPtr(Self, "tcp_context", tcp_context);
_ = peer_type;
// Get source addess of this connection.
const path: [2][]const u8 = [2][]const u8{ "upstream", "address" };
var upstream_addess = hostcalls.getProperty(path[0..]) catch unreachable;
defer upstream_addess.deinit();
// Log the upstream remote addess.
const message = std.fmt.allocPrint(
allocator,
"upstream connection for peer at {s}",
.{upstream_addess.raw_data},
) catch unreachable;
defer allocator.free(message);
hostcalls.log(enums.LogLevel.Info, message) catch unreachable;
}
// Implement contexts.TcpContext.onLog.
fn onLog(tcp_context: *contexts.TcpContext) void {
const self: *Self = @fieldParentPtr(Self, "tcp_context", tcp_context);
const message = std.fmt.allocPrint(
allocator,
"tcp context {d} is at logging phase..",
.{self.context_id},
) catch unreachable;
defer allocator.free(message);
hostcalls.log(enums.LogLevel.Info, message) catch unreachable;
}
// Implement contexts.TcpContext.onDelete.
fn onDelete(tcp_context: *contexts.TcpContext) void {
const self: *Self = @fieldParentPtr(Self, "tcp_context", tcp_context);
const message = std.fmt.allocPrint(
allocator,
"deleting tcp context {d}..",
.{self.context_id},
) catch unreachable;
defer allocator.free(message);
hostcalls.log(enums.LogLevel.Info, message) catch unreachable;
// Destory myself.
allocator.destroy(self);
}
};
const HttpHeaderOperation = struct {
const Self = @This();
// Store the "implemented" contexts.HttoContext.
http_context: contexts.HttpContext = undefined,
context_id: usize = 0,
random_shared_data_key: []const u8 = undefined,
request_path: hostcalls.WasmData = undefined,
tick_counter_metric_id: u32 = 0,
user_agent_shared_queue_id: ?u32 = null,
// Initialize this context.
fn init(self: *Self, context_id: usize, tick_counter_metric_id: u32, random_shared_data_key: []const u8, user_agent_queue_id: ?u32) void {
self.context_id = context_id;
self.tick_counter_metric_id = tick_counter_metric_id;
self.random_shared_data_key = random_shared_data_key;
self.user_agent_shared_queue_id = user_agent_queue_id;
self.http_context = contexts.HttpContext{
.onHttpRequestHeadersImpl = onHttpRequestHeaders,
.onHttpRequestBodyImpl = null,
.onHttpRequestTrailersImpl = onHttpRequestTrailers,
.onHttpResponseHeadersImpl = onHttpResponseHeaders,
.onHttpResponseBodyImpl = null,
.onHttpResponseTrailersImpl = onHttpResponseTrailers,
.onHttpCalloutResponseImpl = null,
.onLogImpl = onLog,
.onDeleteImpl = onDelete,
};
const message = std.fmt.allocPrint(
allocator,
"HttpHeaderOperation context created: {d}",
.{self.context_id},
) catch unreachable;
defer allocator.free(message);
hostcalls.log(enums.LogLevel.Info, message) catch unreachable;
}
// Implement contexts.HttpContext.onHttpRequestHeaders.
fn onHttpRequestHeaders(http_context: *contexts.HttpContext, num_headers: usize, end_of_stream: bool) enums.Action {
_ = num_headers;
_ = end_of_stream;
const self: *Self = @fieldParentPtr(Self, "http_context", http_context);
// Get request headers.
var headers: hostcalls.HeaderMap = hostcalls.getHeaderMap(enums.MapType.HttpRequestHeaders) catch unreachable;
defer headers.deinit();
// Log request headers.
var iter = headers.map.iterator();
while (iter.next()) |entry| {
const message = std.fmt.allocPrint(
allocator,
"request header: --> key: {s}, value: {s} ",
.{ entry.key_ptr.*, entry.value_ptr.* },
) catch unreachable;
defer allocator.free(message);
hostcalls.log(enums.LogLevel.Info, message) catch unreachable;
}
// Enqueue the user-agent to the shared queue if it exits.
if (self.user_agent_shared_queue_id) |queue_id| {
var ua = hostcalls.getHeaderMapValue(enums.MapType.HttpRequestHeaders, "user-agent") catch unreachable;
defer ua.deinit();
hostcalls.enqueueSharedQueue(queue_id, ua.raw_data) catch unreachable;
const message = std.fmt.allocPrint(
allocator,
"user-agent {s} queued.",
.{ua.raw_data},
) catch unreachable;
defer allocator.free(message);
hostcalls.log(enums.LogLevel.Info, message) catch unreachable;
}
// Get the :path header value.
self.request_path = hostcalls.getHeaderMapValue(enums.MapType.HttpRequestHeaders, ":path") catch unreachable;
// Replace "/badclusters" -> "/clusters" to perform header replacement.
if (std.mem.indexOf(u8, self.request_path.raw_data, "/badclusters")) |_| {
hostcalls.replaceHeaderMapValue(enums.MapType.HttpRequestHeaders, ":path", "/clusters") catch unreachable;
}
return enums.Action.Continue;
}
// Implement contexts.HttpContext.onHttpRequestTrailers.
fn onHttpRequestTrailers(http_context: *contexts.HttpContext, num_trailers: usize) enums.Action {
_ = http_context;
_ = num_trailers;
// Log request trailers.
var headers: hostcalls.HeaderMap = hostcalls.getHeaderMap(enums.MapType.HttpRequestTrailers) catch unreachable;
defer headers.deinit();
var iter = headers.map.iterator();
while (iter.next()) |entry| {
const message = std.fmt.allocPrint(
allocator,
"request trailer: --> key: {s}, value: {s} ",
.{ entry.key_ptr.*, entry.value_ptr.* },
) catch unreachable;
defer allocator.free(message);
hostcalls.log(enums.LogLevel.Info, message) catch unreachable;
}
return enums.Action.Continue;
}
// Implement contexts.HttpContext.onHttpResponseHeaders.
fn onHttpResponseHeaders(http_context: *contexts.HttpContext, num_headers: usize, end_of_stream: bool) enums.Action {
_ = num_headers;
_ = end_of_stream;
const self: *Self = @fieldParentPtr(Self, "http_context", http_context);
// Get response headers.
var headers: hostcalls.HeaderMap = hostcalls.getHeaderMap(enums.MapType.HttpResponseHeaders) catch unreachable;
defer headers.deinit();
// Log response headers.
var iter = headers.map.iterator();
while (iter.next()) |entry| {
const message = std.fmt.allocPrint(
allocator,
"response header: <-- key: {s}, value: {s} ",
.{ entry.key_ptr.*, entry.value_ptr.* },
) catch unreachable;
defer allocator.free(message);
hostcalls.log(enums.LogLevel.Info, message) catch unreachable;
}
if (std.mem.indexOf(u8, self.request_path.raw_data, "response-headers")) |_| {
// Perform set_header_map and proxy_add_header_map_value
// when the request :path contains "response-headers".
headers.map.put("proxy-wasm", "zig-sdk") catch unreachable;
hostcalls.replaceHeaderMap(enums.MapType.HttpResponseHeaders, headers.map) catch unreachable;
hostcalls.addHeaderMapValue(enums.MapType.HttpResponseHeaders, "cache-control", " zig-original") catch unreachable;
} else if (std.mem.indexOf(u8, self.request_path.raw_data, "force-500")) |_| {
// Forcibly reutrn 500 status if :path contains "force-500" and remove "cache-control" header.
hostcalls.removeHeaderMapValue(enums.MapType.HttpResponseHeaders, "cache-control") catch unreachable;
hostcalls.replaceHeaderMapValue(enums.MapType.HttpResponseHeaders, ":status", "500") catch unreachable;
} else if (std.mem.indexOf(u8, self.request_path.raw_data, "tick-count")) |_| {
// Return the tick counter's value in the response header if :path contains "tick-count".
const tick_count = hostcalls.getMetric(self.tick_counter_metric_id) catch unreachable;
// Cast the u64 to the string.
var buf: [20]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buf);
std.fmt.formatIntValue(tick_count, "", .{}, fbs.writer()) catch unreachable;
// Set the stringed value in response headers.
hostcalls.addHeaderMapValue(enums.MapType.HttpResponseHeaders, "current-tick-count", fbs.getWritten()) catch unreachable;
} else if (std.mem.indexOf(u8, self.request_path.raw_data, "shared-random-value")) |_| {
// Insert the random value in the shared data in a response header if :path contains "shared-random-value".
var cas: u32 = undefined;
var data = hostcalls.getSharedData(
self.random_shared_data_key,
&cas,
) catch return enums.Action.Continue;
defer data.deinit();
// Read the random value as u64 and format it as string.
const value: u64 = std.mem.readIntSliceLittle(u64, data.raw_data);
var buffer: [20]u8 = undefined;
_ = std.fmt.bufPrintIntToSlice(buffer[0..], value, 10, .lower, .{});
// Put it in the header.
hostcalls.addHeaderMapValue(enums.MapType.HttpResponseHeaders, "shared-random-value", buffer[0..]) catch unreachable;
}
return enums.Action.Continue;
}
// Implement contexts.HttpContext.onHttpResponseTrailers.
fn onHttpResponseTrailers(http_context: *contexts.HttpContext, num_trailers: usize) enums.Action {
_ = http_context;
_ = num_trailers;
// Log response trailers.
var headers: hostcalls.HeaderMap = hostcalls.getHeaderMap(enums.MapType.HttpResponseTrailers) catch unreachable;
defer headers.deinit();
var iter = headers.map.iterator();
while (iter.next()) |entry| {
const message = std.fmt.allocPrint(
allocator,
"response trailer: <--- key: {s}, value: {s} ",
.{ entry.key_ptr.*, entry.value_ptr.* },
) catch unreachable;
defer allocator.free(message);
hostcalls.log(enums.LogLevel.Info, message) catch unreachable;
}
return enums.Action.Continue;
}
// Implement contexts.HttpContext.onLog.
fn onLog(http_context: *contexts.HttpContext) void {
const self: *Self = @fieldParentPtr(Self, "http_context", http_context);
// Log the upstream cluster name.
const path: [1][]const u8 = [1][]const u8{"cluster_name"};
var cluster_name = hostcalls.getProperty(path[0..]) catch unreachable;
defer cluster_name.deinit();
const address_msg = std.fmt.allocPrint(allocator, "upstream cluster: {s} ", .{cluster_name.raw_data}) catch unreachable;
defer allocator.free(address_msg);
hostcalls.log(enums.LogLevel.Info, address_msg) catch unreachable;
// Log the request/response headers if :path contains "on-log-headers".
if (std.mem.indexOf(u8, self.request_path.raw_data, "on-log-headers")) |_| {
// Headers are all avaialable in onLog phase.
var request_headers: hostcalls.HeaderMap = hostcalls.getHeaderMap(enums.MapType.HttpRequestHeaders) catch unreachable;
defer request_headers.deinit();
var response_headers: hostcalls.HeaderMap = hostcalls.getHeaderMap(enums.MapType.HttpResponseHeaders) catch unreachable;
defer response_headers.deinit();
// Log all the request/response headers.
var iter = request_headers.map.iterator();
while (iter.next()) |entry| {
const message = std.fmt.allocPrint(
allocator,
"request header on log: --> key: {s}, value: {s} ",
.{ entry.key_ptr.*, entry.value_ptr.* },
) catch unreachable;
defer allocator.free(message);
hostcalls.log(enums.LogLevel.Info, message) catch unreachable;
}
iter = response_headers.map.iterator();
while (iter.next()) |entry| {
const message = std.fmt.allocPrint(
allocator,
"response header on log: <-- key: {s}, value: {s} ",
.{ entry.key_ptr.*, entry.value_ptr.* },
) catch unreachable;
defer allocator.free(message);
hostcalls.log(enums.LogLevel.Info, message) catch unreachable;
}
}
}
// Implement contexts.HttpContext.onDelete.
fn onDelete(http_context: *contexts.HttpContext) void {
const self: *Self = @fieldParentPtr(Self, "http_context", http_context);
// Destory the allocated WasmData.
self.request_path.deinit();
// Destory myself.
allocator.destroy(self);
}
};
const HttpBodyOperation = struct {
const Self = @This();
// Store the "implemented" contexts.HttoContext.
http_context: contexts.HttpContext = undefined,
request_path: hostcalls.WasmData = undefined,
total_request_body_size: usize,
total_response_body_size: usize,
// Initialize this context.
fn init(self: *Self) void {
self.http_context = contexts.HttpContext{
.onHttpRequestHeadersImpl = onHttpRequestHeaders,
.onHttpRequestBodyImpl = onHttpRequestBody,
.onHttpRequestTrailersImpl = null,
.onHttpResponseHeadersImpl = onHttpResponseHeaders,
.onHttpResponseBodyImpl = onHttpResponseBody,
.onHttpResponseTrailersImpl = null,
.onHttpCalloutResponseImpl = null,
.onLogImpl = null,
.onDeleteImpl = onDelete,
};
}
// Implement contexts.HttpContext.onHttpRequestHeaders.
fn onHttpRequestHeaders(http_context: *contexts.HttpContext, num_headers: usize, end_of_stream: bool) enums.Action {
_ = num_headers;
_ = end_of_stream;
const self: *Self = @fieldParentPtr(Self, "http_context", http_context);
// Get the :path header value.
self.request_path = hostcalls.getHeaderMapValue(enums.MapType.HttpRequestHeaders, ":path") catch unreachable;
return enums.Action.Continue;
}
// Implement contexts.HttpContext.onHttpRequestBody.
fn onHttpRequestBody(http_context: *contexts.HttpContext, body_size: usize, end_of_stream: bool) enums.Action {
const self: *Self = @fieldParentPtr(Self, "http_context", http_context);
// Switch based on the request path.
// If we have "echo" in :path, then Pause and send the entire body as-is.
if (std.mem.indexOf(u8, self.request_path.raw_data, "echo")) |_| {
// Increment total_request_body_size to have the entire body size.
self.total_request_body_size += body_size;
// end_of_stream = true means that we've already seen the entire body and it is buffered in the host.
// so retrieve the body via getBufferBytes and pass it as response body in sendLocalResponse.
if (end_of_stream) {
var body = hostcalls.getBufferBytes(enums.BufferType.HttpRequestbody, 0, self.total_request_body_size) catch unreachable;
defer body.deinit();
// Send the local response with the whole reuqest body.
hostcalls.sendLocalResponse(200, body.raw_data, null) catch unreachable;
}
return enums.Action.Pause;
}
// Otherwise just noop.
return enums.Action.Continue;
}
// Implement contexts.HttpContext.onHttpResponseHeaders.
fn onHttpResponseHeaders(http_context: *contexts.HttpContext, num_headers: usize, end_of_stream: bool) enums.Action {
_ = num_headers;
_ = end_of_stream;
const self: *Self = @fieldParentPtr(Self, "http_context", http_context);
// Remove Content-Length header if sha256-response, otherwise client breaks because we change the response.
if (std.mem.indexOf(u8, self.request_path.raw_data, "sha256-response")) |_| {
hostcalls.removeHeaderMapValue(enums.MapType.HttpResponseHeaders, "Content-Length") catch unreachable;
}
return enums.Action.Continue;
}
// Implement contexts.HttpContext.onHttpResponseBody.
fn onHttpResponseBody(http_context: *contexts.HttpContext, body_size: usize, end_of_stream: bool) enums.Action {
const self: *Self = @fieldParentPtr(Self, "http_context", http_context);
if (std.mem.indexOf(u8, self.request_path.raw_data, "echo")) |_| {
return enums.Action.Continue;
} else if (std.mem.indexOf(u8, self.request_path.raw_data, "sha256-response")) |_| {
// Increment total_response_body_size to have the entire body size.
self.total_response_body_size += body_size;
// Wait until we see the entire body.
if (!end_of_stream) {
return enums.Action.Pause;
}
// Calculate the sha256 of the entire response body.
var body = hostcalls.getBufferBytes(enums.BufferType.HttpResponseBody, 0, self.total_response_body_size) catch unreachable;
defer body.deinit();
var checksum: [32]u8 = undefined;
std.crypto.hash.sha2.Sha256.hash(body.raw_data, &checksum, .{});
// Log the calculated sha256 of response body.
const message = std.fmt.allocPrint(
allocator,
"response body sha256 (original size={d}) : {x}",
.{ self.total_response_body_size, std.fmt.fmtSliceHexLower(checksum[0..]) },
) catch unreachable;
defer allocator.free(message);
hostcalls.log(enums.LogLevel.Info, message) catch unreachable;
// Set the calculated sha256 to the response body.
hostcalls.replaceBufferBytes(enums.BufferType.HttpResponseBody, message) catch unreachable;
}
return enums.Action.Continue;
}
// Implement contexts.HttpContext.onDelete.
fn onDelete(http_context: *contexts.HttpContext) void {
const self: *Self = @fieldParentPtr(Self, "http_context", http_context);
// Destory myself.
allocator.destroy(self);
}
};
const HttpRandomAuth = struct {
const Self = @This();
// Store the "implemented" contexts.HttoContext.
http_context: contexts.HttpContext = undefined,
dispatch_request_headers: hostcalls.HeaderMap = undefined,
request_callout_id: u32 = undefined,
response_callout_id: u32 = undefined,
// Initialize this context.
fn init(self: *Self) void {
self.http_context = contexts.HttpContext{
.onHttpRequestHeadersImpl = onHttpRequestHeaders,
.onHttpRequestBodyImpl = null,
.onHttpRequestTrailersImpl = null,
.onHttpResponseHeadersImpl = onHttpResponseHeaders,
.onHttpResponseBodyImpl = null,
.onHttpResponseTrailersImpl = null,
.onHttpCalloutResponseImpl = onHttpCalloutResponse,
.onLogImpl = null,
.onDeleteImpl = onDelete,
};
}
// Implement contexts.HttpContext.onHttpRequestHeaders.
fn onHttpRequestHeaders(http_context: *contexts.HttpContext, num_headers: usize, end_of_stream: bool) enums.Action {
_ = num_headers;
_ = end_of_stream;
const self: *Self = @fieldParentPtr(Self, "http_context", http_context);
// Get the original response headers.
self.dispatch_request_headers = hostcalls.getHeaderMap(enums.MapType.HttpRequestHeaders) catch unreachable;
// Set the path to "/uuid" to get the random response and the method to GET
self.dispatch_request_headers.map.put(":path", "/uuid") catch unreachable;
self.dispatch_request_headers.map.put(":method", "GET") catch unreachable;
// Dispatch a HTTP request to httpbin, and Pause until we receive the response.
self.request_callout_id = hostcalls.dispatchHttpCall(
"httpbin",
self.dispatch_request_headers.map,
null,
null,
5000,
) catch unreachable;
return enums.Action.Pause;
}
// Implement contexts.HttpContext.onHttpResponseHeaders.
fn onHttpResponseHeaders(http_context: *contexts.HttpContext, num_headers: usize, end_of_stream: bool) enums.Action {
_ = num_headers;
_ = end_of_stream;
const self: *Self = @fieldParentPtr(Self, "http_context", http_context);
self.response_callout_id = hostcalls.dispatchHttpCall(
"httpbin",
self.dispatch_request_headers.map,
null,
null,
5000,
) catch unreachable;
return enums.Action.Pause;
}
// Implement contexts.HttpContext.onDelete.
fn onDelete(http_context: *contexts.HttpContext) void {
const self: *Self = @fieldParentPtr(Self, "http_context", http_context);
// Free the request headers.
self.dispatch_request_headers.deinit();
// Destory myself.
allocator.destroy(self);
}
// Implement contexts.HttpContext.onHttpCalloutResponse.
fn onHttpCalloutResponse(http_context: *contexts.HttpContext, callout_id: u32, num_headers: usize, body_size: usize, num_trailers: usize) void {
_ = num_headers;
_ = num_trailers;
const self: *Self = @fieldParentPtr(Self, "http_context", http_context);
// (Debug) Check the callout ID.
std.debug.assert(
self.request_callout_id == callout_id or self.response_callout_id == callout_id,
);
// Get the response body of the callout.
var raw_body = hostcalls.getBufferBytes(enums.BufferType.HttpCallResponseBody, 0, body_size) catch unreachable;
defer raw_body.deinit();
// Parse it to httpbinUUIDResponseBody struct.
const httpbinUUIDResponseBody = comptime struct { uuid: []const u8 };
var stream = std.json.TokenStream.init(raw_body.raw_data);
var body = std.json.parse(
httpbinUUIDResponseBody,
&stream,
.{ .allocator = allocator },
) catch unreachable;
defer std.json.parseFree(httpbinUUIDResponseBody, body, .{ .allocator = allocator });
// Log the received response from httpbin.
const message = std.fmt.allocPrint(
allocator,
"uuid={s} received",
.{body.uuid},
) catch unreachable;
defer allocator.free(message);
hostcalls.log(enums.LogLevel.Info, message) catch unreachable;
if (body.uuid[0] % 2 == 0) {
// If the first byte of uuid is even, then send the local response with 403.
var responseHeaders = std.StringHashMap([]const u8).init(allocator);
defer responseHeaders.deinit();
if (self.request_callout_id == callout_id) {
responseHeaders.put("forbidden-at", "request") catch unreachable;
} else {
responseHeaders.put("forbidden-at", "response") catch unreachable;
}
hostcalls.sendLocalResponse(403, "Forbidden by Ziglang.\n", responseHeaders) catch unreachable;
} else {
// Otherwise, continue the original request.
if (self.request_callout_id == callout_id) {
hostcalls.continueHttpRequest();
} else {
hostcalls.continueHttpResponse();
}
}
}
}; | example/example.zig |
const std = @import("std");
const tvg = @import("tvg");
const args = @import("args");
fn printUsage(stream: anytype) !void {
try stream.writeAll(
\\tvg-text [-I <fmt>] [-O <fmt>] [-o <output>] <input>
\\
\\Converts TinyVG related files between different formats. Only supports a single input and output file.
\\
\\Options:
\\ <input> defines the input file, performs auto detection of the format if -I is not specified. Use - for stdin.
\\ -h, --help prints this text.
\\ -I, --input-format <fmt> sets the format of the input file.
\\ -O, --output-format <fmt> sets the format of the output file.
\\ -o, --output <file> sets the output file, or use - for stdout. performs auto detection of the format if -O is not specified.
\\
\\Support formats:
\\ tvg - Tiny vector graphics, binary representation.
\\ tvgt - Tiny vector graphics, text representation.
\\ svg - Scalable vector graphics. Only usable for output, use svg2tvgt to convert to tvg text format.
\\
);
}
const CliOptions = struct {
help: bool = false,
@"input-format": ?Format = null,
@"output-format": ?Format = null,
output: ?[]const u8 = null,
pub const shorthands = .{
.o = "output",
.h = "help",
.I = "input-format",
.O = "output-format",
};
};
const Format = enum {
tvg,
tvgt,
svg,
};
fn detectFormat(ext: []const u8) ?Format {
return if (std.mem.eql(u8, ext, ".tvg"))
Format.tvg
else if (std.mem.eql(u8, ext, ".tvgt"))
Format.tvgt
else if (std.mem.eql(u8, ext, ".svg"))
Format.svg
else
null;
}
pub fn main() !u8 {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
const cli = args.parseForCurrentProcess(CliOptions, allocator, .print) catch return 1;
defer cli.deinit();
// const stdin = std.io.getStdIn().reader();
const stdout = std.io.getStdOut().writer();
const stderr = std.io.getStdErr().writer();
if (cli.options.help) {
try printUsage(stdout);
return 0;
}
if (cli.positionals.len != 1) {
try stderr.writeAll("Expected exactly one positional argument!\n");
try printUsage(stderr);
return 1;
}
const input_file = cli.positionals[0];
const input_ext = std.fs.path.extension(input_file);
const input_format = cli.options.@"input-format" orelse
detectFormat(input_ext) orelse {
try stderr.print("Could not auto-detect the input format for extension {s}\n", .{input_ext});
return 1;
};
const output_file = cli.options.output orelse blk: {
if (cli.options.@"output-format" == null) {
try stderr.print("Could not auto-detect the input format for extension {s}\n", .{input_ext});
return 1;
}
const dest_ext: []const u8 = switch (cli.options.@"output-format".?) {
.svg => ".svg",
.tvg => ".tvg",
.tvgt => ".tvgt",
};
break :blk try std.mem.join(allocator, "", &[_][]const u8{
input_file[0 .. input_file.len - input_ext.len],
dest_ext,
});
};
const output_ext = std.fs.path.extension(output_file);
const output_format = cli.options.@"output-format" orelse
detectFormat(output_ext) orelse {
try stderr.print("Could not auto-detect the output format for extension {s}\n", .{output_ext});
return 1;
};
var intermediary_tvg = std.ArrayList(u8).init(allocator);
defer intermediary_tvg.deinit();
{
var input_stream = try FileOrStream.openRead(std.fs.cwd(), input_file);
defer input_stream.close();
switch (input_format) {
.tvg => {
const buffer = try input_stream.file.readToEndAlloc(allocator, 1 << 24);
intermediary_tvg.deinit();
intermediary_tvg = std.ArrayList(u8).fromOwnedSlice(allocator, buffer);
},
.tvgt => {
const text = try input_stream.reader().readAllAlloc(allocator, 1 << 25);
defer allocator.free(text);
try tvg.text.parse(allocator, text, intermediary_tvg.writer());
},
.svg => {
try stderr.print("This tool cannot convert from SVG files. Use svg2tvg to convert the SVG to TVG textual representation.\n", .{});
return 1;
},
}
}
// Conversion process:
//
// Read the input file and directly convert it to TVG (binary).
// After that, write the output file via the TVG decoder.
// std.log.err("input: {s} {s}", .{ input_file, @tagName(input_format) });
// std.log.err("output: {s} {s}", .{ output_file, @tagName(output_format) });
{
// Parse file header before creating the output file
var stream = std.io.fixedBufferStream(intermediary_tvg.items);
var parser = try tvg.parse(allocator, stream.reader());
defer parser.deinit();
// Open/create the output file after the TVG header was valid
var output_stream = try FileOrStream.openWrite(std.fs.cwd(), output_file);
defer output_stream.close();
switch (output_format) {
.tvg => {
try output_stream.writer().writeAll(intermediary_tvg.items);
},
.tvgt => {
try tvg.text.renderStream(&parser, output_stream.writer());
},
.svg => {
try tvg.svg.renderStream(allocator, &parser, output_stream.writer());
},
}
}
return 0;
}
const FileOrStream = struct {
file: std.fs.File,
close_stream: bool,
fn openRead(dir: std.fs.Dir, path: []const u8) !FileOrStream {
if (std.mem.eql(u8, path, "-")) {
return FileOrStream{
.file = std.io.getStdIn(),
.close_stream = false,
};
}
return FileOrStream{
.file = try dir.openFile(path, .{}),
.close_stream = true,
};
}
fn openWrite(dir: std.fs.Dir, path: []const u8) !FileOrStream {
if (std.mem.eql(u8, path, "-")) {
return FileOrStream{
.file = std.io.getStdOut(),
.close_stream = false,
};
}
return FileOrStream{
.file = try dir.createFile(path, .{}),
.close_stream = true,
};
}
fn reader(self: *FileOrStream) std.fs.File.Reader {
return self.file.reader();
}
fn writer(self: *FileOrStream) std.fs.File.Writer {
return self.file.writer();
}
fn close(self: *FileOrStream) void {
if (self.close_stream) {
self.file.close();
}
self.* = undefined;
}
}; | src/tools/text.zig |
const stdx = @import("stdx");
const std = @import("std");
const stbtt = @import("stbtt");
const stbi = @import("stbi");
const ft = @import("freetype");
const graphics = @import("../../graphics.zig");
const gpu = graphics.gpu;
const Font = graphics.Font;
const RenderFont = gpu.RenderFont;
const OpenTypeFont = graphics.OpenTypeFont;
const Glyph = gpu.Glyph;
const log = std.log.scoped(.font_renderer);
pub fn getOrLoadMissingGlyph(g: *gpu.Graphics, font: *Font, render_font: *RenderFont) *Glyph {
if (render_font.missing_glyph) |*glyph| {
return glyph;
} else {
const ot_font = font.getOtFontBySize(render_font.render_font_size);
const glyph = generateGlyph(g, font, ot_font, render_font, 0);
render_font.missing_glyph = glyph;
return &render_font.missing_glyph.?;
}
}
pub fn getOrLoadGlyph(g: *gpu.Graphics, font: *Font, render_font: *RenderFont, cp: u21) ?*Glyph {
// var buf: [4]u8 = undefined;
if (render_font.glyphs.getEntry(cp)) |entry| {
// _ = std.unicode.utf8Encode(cp, &buf) catch unreachable;
// log.debug("{} cache hit: {s}", .{render_font.render_font_size, buf});
return entry.value_ptr;
} else {
// _ = std.unicode.utf8Encode(cp, &buf) catch unreachable;
// log.debug("{} cache miss: {s}", .{render_font.render_font_size, buf});
const ot_font = font.getOtFontBySize(render_font.render_font_size);
// Attempt to generate glyph.
if (ot_font.getGlyphId(cp) catch unreachable) |glyph_id| {
const glyph = generateGlyph(g, font, ot_font, render_font, glyph_id);
const entry = render_font.glyphs.getOrPutValue(cp, glyph) catch unreachable;
return entry.value_ptr;
} else return null;
}
}
/// Rasterizes glyph from ot font and into a FontAtlas.
/// Then set flag to indicate the FontAtlas was updated.
/// New glyph metadata is stored into Font's glyph cache and returned.
/// Even though the ot_font can be retrieved from font, it's provided by the caller to avoid an extra lookup for bitmap fonts.
fn generateGlyph(g: *gpu.Graphics, font: *Font, ot_font: OpenTypeFont, render_font: *const RenderFont, glyph_id: u16) Glyph {
if (ot_font.hasEmbeddedBitmap()) {
// Bitmap fonts.
return generateEmbeddedBitmapGlyph(g, ot_font, render_font, glyph_id);
}
if (ot_font.hasColorBitmap()) {
if (generateColorBitmapGlyph(g, ot_font, render_font, glyph_id)) |glyph| {
return glyph;
} else {
// generateGlyph should only be called when the font has indicated that a glyph_id exists for a codepoint.
// If the color tables doesn't have it, then check the outline tables.
return generateOutlineGlyph(g, font, render_font, glyph_id, false);
}
}
if (!ot_font.hasGlyphOutlines()) {
// Font should have outline data or color bitmap.
unreachable;
}
return generateOutlineGlyph(g, font, render_font, glyph_id, true);
}
// 1 pixel padding in glyphs so edge filtering doesn't mix with it's own glyph or neighboring glyphs.
// Must remember to consider padding when blitting using text shaping in start_render_text() and render_next_codepoint(), also measure_text()
const h_padding = Glyph.Padding * 2;
const v_padding = Glyph.Padding * 2;
fn generateOutlineGlyph(g: *gpu.Graphics, font: *Font, render_font: *const RenderFont, glyph_id: u16, set_size: bool) Glyph {
const scale = render_font.scale_from_ttf;
const fc = &g.font_cache;
// negative y indicates upwards dist from baseline.
// positive y indicates downwards dist from baseline.
// x0, y0 represents top left.
// x1, y1 represents bot right.
var x0: c_int = 0;
var y0: c_int = 0;
var x1: c_int = 0;
var y1: c_int = 0;
var glyph_x: u32 = 0;
var glyph_y: u32 = 0;
var glyph_width: u32 = 0;
var glyph_height: u32 = 0;
switch (graphics.FontRendererBackend) {
.Freetype => {
if (set_size) {
// Freetype does not allow setting to arbitrary pixel size for color bitmaps: https://github.com/python-pillow/Pillow/issues/6166
const err = ft.FT_Set_Pixel_Sizes(font.impl, 0, render_font.render_font_size);
if (err != 0) {
stdx.panicFmt("freetype error {}: {s}", .{err, ft.FT_Error_String(err)});
}
}
var err = ft.FT_Load_Glyph(font.impl, glyph_id, ft.FT_LOAD_DEFAULT);
if (err != 0) {
stdx.panicFmt("freetype error {}", .{err});
}
err = ft.FT_Render_Glyph(font.impl.glyph, ft.FT_RENDER_MODE_NORMAL);
if (err != 0) {
stdx.panicFmt("freetype error {}", .{err});
}
const src_width = font.impl.glyph[0].bitmap.width;
const src_height = font.impl.glyph[0].bitmap.rows;
x0 = font.impl.glyph[0].bitmap_left;
y0 = -font.impl.glyph[0].bitmap_top;
// log.debug("glyph {any} {} {}", .{font.impl.glyph[0].bitmap, x0, y0});
if (src_width > 0) {
glyph_width = src_width + h_padding;
glyph_height = src_height + v_padding;
const pos = fc.main_atlas.packer.allocRect(glyph_width, glyph_height);
glyph_x = pos.x;
glyph_y = pos.y;
// Debug: Dump specific glyph.
// if (glyph_id == 76) {
// _ = stbi.stbi_write_bmp("test.bmp", @intCast(c_int, src_width), @intCast(c_int, src_height), 1, font.impl.glyph[0].bitmap.buffer);
// log.debug("{} {} {}", .{src_width, src_height, x0});
// }
fc.main_atlas.copySubImageFrom1Channel(glyph_x + Glyph.Padding, glyph_y + Glyph.Padding, src_width, src_height, font.impl.glyph[0].bitmap.buffer[0..src_width*src_height]);
fc.main_atlas.markDirtyBuffer();
} else {
// Some characters will be blank like the space char.
glyph_width = 0;
glyph_height = 0;
glyph_x = 0;
glyph_y = 0;
}
},
.Stbtt => {
stbtt.stbtt_GetGlyphBitmapBox(&font.impl, glyph_id, scale, scale, &x0, &y0, &x1, &y1);
// Draw glyph into bitmap buffer.
const src_width = @intCast(u32, x1 - x0);
const src_height = @intCast(u32, y1 - y0);
glyph_width = src_width + h_padding;
glyph_height = src_height + v_padding;
const pos = fc.main_atlas.packer.allocRect(glyph_width, glyph_height);
glyph_x = pos.x;
glyph_y = pos.y;
g.raster_glyph_buffer.resize(src_width * src_height) catch @panic("error");
// Don't include extra padding when blitting to bitmap with stbtt.
stbtt.stbtt_MakeGlyphBitmap(&font.impl, g.raster_glyph_buffer.items.ptr, @intCast(c_int, src_width), @intCast(c_int, src_height), @intCast(c_int, src_width), scale, scale, glyph_id);
fc.main_atlas.copySubImageFrom1Channel(glyph_x + Glyph.Padding, glyph_y + Glyph.Padding, src_width, src_height, g.raster_glyph_buffer.items);
fc.main_atlas.markDirtyBuffer();
},
}
// log.debug("box {} {} {} {}", .{x0, y0, x1, y1});
const h_metrics = font.ot_font.getGlyphHMetrics(glyph_id);
// log.info("adv: {}, lsb: {}", .{h_metrics.advance_width, h_metrics.left_side_bearing});
var glyph = Glyph.init(glyph_id, fc.main_atlas.image);
glyph.is_color_bitmap = false;
// Include padding in offsets.
// glyph.x_offset = scale * @intToFloat(f32, h_metrics.left_side_bearing) - Glyph.Padding;
glyph.x_offset = @intToFloat(f32, x0) - Glyph.Padding;
// log.warn("lsb: {} x: {}", .{scale * @intToFloat(f32, h_metrics.left_side_bearing), x0});
glyph.y_offset = @round(render_font.ascent) - @intToFloat(f32, -y0) - Glyph.Padding;
glyph.x = glyph_x;
glyph.y = glyph_y;
glyph.width = glyph_width;
glyph.height = glyph_height;
glyph.render_font_size = @intToFloat(f32, render_font.render_font_size);
glyph.dst_width = @intToFloat(f32, glyph_width);
glyph.dst_height = @intToFloat(f32, glyph_height);
glyph.advance_width = scale * @intToFloat(f32, h_metrics.advance_width);
glyph.u0 = @intToFloat(f32, glyph_x) / @intToFloat(f32, fc.main_atlas.width);
glyph.v0 = @intToFloat(f32, glyph_y) / @intToFloat(f32, fc.main_atlas.height);
glyph.u1 = @intToFloat(f32, glyph_x + glyph_width) / @intToFloat(f32, fc.main_atlas.width);
glyph.v1 = @intToFloat(f32, glyph_y + glyph_height) / @intToFloat(f32, fc.main_atlas.height);
return glyph;
}
fn generateColorBitmapGlyph(g: *gpu.Graphics, ot_font: OpenTypeFont, render_font: *const RenderFont, glyph_id: u16) ?Glyph {
// Copy over png glyph data instead of going through the normal stbtt rasterizer.
if (ot_font.getGlyphColorBitmap(glyph_id) catch unreachable) |data| {
// const scale = render_font.scale_from_ttf;
const fc = &g.font_cache;
// Decode png.
var src_width: c_int = undefined;
var src_height: c_int = undefined;
var channels: c_int = undefined;
const bitmap = stbi.stbi_load_from_memory(&data.png_data[0], @intCast(c_int, data.png_data.len), &src_width, &src_height, &channels, 0);
defer stbi.stbi_image_free(bitmap);
// log.debug("color glyph {}x{} {}x{}", .{data.width, data.height, src_width, src_height});
const glyph_width = @intCast(u32, src_width) + h_padding;
const glyph_height = @intCast(u32, src_height) + v_padding;
const pos = fc.main_atlas.packer.allocRect(glyph_width, glyph_height);
const glyph_x = pos.x;
const glyph_y = pos.y;
// Copy into atlas bitmap.
const bitmap_len = @intCast(usize, src_width * src_height * channels);
fc.main_atlas.copySubImageFrom(
glyph_x + Glyph.Padding,
glyph_y + Glyph.Padding,
@intCast(usize, src_width),
@intCast(usize, src_height),
bitmap[0..bitmap_len],
);
fc.main_atlas.markDirtyBuffer();
// const h_metrics = font.ttf_font.getGlyphHMetrics(glyph_id);
// log.info("adv: {}, lsb: {}", .{h_metrics.advance_width, h_metrics.left_side_bearing});
var glyph = Glyph.init(glyph_id, fc.main_atlas.image);
glyph.is_color_bitmap = true;
const scale_from_xpx = @intToFloat(f32, render_font.render_font_size) / @intToFloat(f32, data.x_px_per_em);
const scale_from_ypx = @intToFloat(f32, render_font.render_font_size) / @intToFloat(f32, data.y_px_per_em);
// Include padding in offsets.
glyph.x_offset = scale_from_xpx * @intToFloat(f32, data.left_side_bearing - Glyph.Padding);
glyph.y_offset = render_font.ascent - scale_from_ypx * @intToFloat(f32, data.bearing_y - Glyph.Padding);
// log.debug("{} {} {}", .{glyph.y_offset, data.bearing_y, data.height });
// glyph.y_offset = 0;
glyph.x = glyph_x;
glyph.y = glyph_y;
glyph.width = glyph_width;
glyph.height = glyph_height;
glyph.render_font_size = @intToFloat(f32, render_font.render_font_size);
// The quad dimensions for color glyphs is scaled to how much pixels should be drawn for the bm font size.
// This should be smaller than the underlying bitmap glyph but that's ok since the uvs will make sure we extract the right pixels.
glyph.dst_width = scale_from_xpx * @intToFloat(f32, glyph_width);
glyph.dst_height = scale_from_ypx * @intToFloat(f32, glyph_height);
// log.debug("{} {}", .{glyph.dst_width, glyph.dst_height});
// In NotoColorEmoji.ttf it seems like the advance_width from the color bitmap data is more accurate than what
// we get from ttf_font.get_glyph_hmetrics.
// glyph.advance_width = scale_from_xpx * @intToFloat(f32, h_metrics.advance_width);
// log.debug("{} {} {}", .{scale * @intToFloat(f32, h_metrics.advance_width), data.advance_width, data.width});
glyph.advance_width = scale_from_xpx * @intToFloat(f32, data.advance_width);
glyph.u0 = @intToFloat(f32, glyph_x) / @intToFloat(f32, fc.main_atlas.width);
glyph.v0 = @intToFloat(f32, glyph_y) / @intToFloat(f32, fc.main_atlas.height);
glyph.u1 = @intToFloat(f32, glyph_x + glyph_width) / @intToFloat(f32, fc.main_atlas.width);
glyph.v1 = @intToFloat(f32, glyph_y + glyph_height) / @intToFloat(f32, fc.main_atlas.height);
return glyph;
} else return null;
}
fn generateEmbeddedBitmapGlyph(g: *gpu.Graphics, ot_font: OpenTypeFont, render_font: *const RenderFont, glyph_id: u16) Glyph {
const fc = &g.font_cache;
if (ot_font.getGlyphBitmap(g.alloc, glyph_id) catch @panic("error")) |ot_glyph| {
defer ot_glyph.deinit(g.alloc);
const dst_width: u32 = ot_glyph.width + h_padding;
const dst_height: u32 = ot_glyph.height + v_padding;
const dst_pos = fc.bitmap_atlas.packer.allocRect(dst_width, dst_height);
fc.bitmap_atlas.copySubImageFrom1Channel(dst_pos.x + Glyph.Padding, dst_pos.y + Glyph.Padding, ot_glyph.width, ot_glyph.height, ot_glyph.data);
fc.bitmap_atlas.markDirtyBuffer();
var glyph = Glyph.init(glyph_id, fc.bitmap_atlas.image);
glyph.is_color_bitmap = false;
glyph.x_offset = @intToFloat(f32, ot_glyph.bearing_x) - Glyph.Padding;
glyph.y_offset = render_font.ascent + @intToFloat(f32, -ot_glyph.bearing_y) - Glyph.Padding;
glyph.x = dst_pos.x;
glyph.y = dst_pos.y;
glyph.width = dst_width;
glyph.height = dst_height;
glyph.render_font_size = @intToFloat(f32, render_font.render_font_size);
glyph.dst_width = @intToFloat(f32, dst_width);
glyph.dst_height = @intToFloat(f32, dst_height);
glyph.advance_width = @intToFloat(f32, ot_glyph.advance);
glyph.u0 = @intToFloat(f32, dst_pos.x) / @intToFloat(f32, fc.bitmap_atlas.width);
glyph.v0 = @intToFloat(f32, dst_pos.y) / @intToFloat(f32, fc.bitmap_atlas.height);
glyph.u1 = @intToFloat(f32, dst_pos.x + dst_width) / @intToFloat(f32, fc.bitmap_atlas.width);
glyph.v1 = @intToFloat(f32, dst_pos.y + dst_height) / @intToFloat(f32, fc.bitmap_atlas.height);
return glyph;
} else {
stdx.panicFmt("expected embedded bitmap for glyph: {}", .{glyph_id});
}
} | graphics/src/backend/gpu/font_renderer.zig |
const std = @import("std");
const Location = @import("location.zig").Location;
pub const Diagnostics = struct {
const Self = @This();
pub const MessageKind = enum {
@"error", warning, notice
};
pub const Message = struct {
kind: MessageKind,
location: Location,
message: []const u8,
pub fn format(value: @This(), comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
try writer.print("{}: {}: {}", .{
value.location,
@tagName(value.kind),
value.message,
});
}
};
arena: std.heap.ArenaAllocator,
messages: std.ArrayList(Message),
pub fn init(allocator: *std.mem.Allocator) Self {
return Self{
.arena = std.heap.ArenaAllocator.init(allocator),
.messages = std.ArrayList(Message).init(allocator),
};
}
pub fn deinit(self: *Self) void {
self.messages.deinit();
self.arena.deinit();
}
/// Emits a new diagnostic message and appends that to the current output.
pub fn emit(self: *Self, kind: MessageKind, location: Location, comptime fmt: []const u8, args: anytype) !void {
const msg_string = try std.fmt.allocPrint(&self.arena.allocator, fmt, args);
errdefer self.arena.allocator.free(msg_string);
try self.messages.append(Message{
.kind = kind,
.location = location,
.message = msg_string,
});
}
/// returns true when the collection has any critical messages.
pub fn hasErrors(self: Self) bool {
return for (self.messages.items) |msg| {
if (msg.kind == .@"error")
break true;
} else false;
}
};
test "diagnostic list" {
const loc = Location{
.chunk = "demo",
.line = 1,
.column = 2,
.offset_end = undefined,
.offset_start = undefined,
};
var diagnostics = Diagnostics.init(std.testing.allocator);
defer diagnostics.deinit();
std.testing.expectEqual(false, diagnostics.hasErrors());
std.testing.expectEqual(@as(usize, 0), diagnostics.messages.items.len);
try diagnostics.emit(.warning, loc, "{}", .{"this is a warning!"});
std.testing.expectEqual(false, diagnostics.hasErrors());
std.testing.expectEqual(@as(usize, 1), diagnostics.messages.items.len);
try diagnostics.emit(.notice, loc, "{}", .{"this is a notice!"});
std.testing.expectEqual(false, diagnostics.hasErrors());
std.testing.expectEqual(@as(usize, 2), diagnostics.messages.items.len);
try diagnostics.emit(.@"error", loc, "{}", .{"this is a error!"});
std.testing.expectEqual(true, diagnostics.hasErrors());
std.testing.expectEqual(@as(usize, 3), diagnostics.messages.items.len);
std.testing.expectEqualStrings("this is a warning!", diagnostics.messages.items[0].message);
std.testing.expectEqualStrings("this is a notice!", diagnostics.messages.items[1].message);
std.testing.expectEqualStrings("this is a error!", diagnostics.messages.items[2].message);
} | src/library/compiler/diagnostics.zig |
const Benchmark = @This();
const std = @import("std");
const fs = std.fs;
const io = std.io;
const math = std.math;
const mem = std.mem;
const process = std.process;
const time = std.time;
////////////////////////////////////////////////////////////////////////////////
stderr: fs.File.OutStream,
stdout: fs.File.OutStream,
arena_storage: std.heap.ArenaAllocator,
arena: *std.mem.Allocator,
name: []const u8,
exename: []const u8,
pathname: []const u8,
atoms: std.ArrayList(Atom),
case_set: std.AutoHashMap(u8, void),
case_order: std.ArrayList(u8),
magnify: usize,
rand_size: usize,
repeat: usize,
uverbose: u2,
padded_data: []u8,
data: []u8,
mode: Mode,
const Mode = enum {
Help,
ListCases,
Perform,
};
////////////////////////////////////////////////////////////////////////////////
fn make(allocator: *std.mem.Allocator, name: []const u8) !*Benchmark {
const p = try allocator.create(Benchmark);
try Benchmark.init(p, allocator, name);
return p;
}
fn init(self: *Benchmark, allocator: *std.mem.Allocator, name: []const u8) !void {
self.stderr = io.getStdErr().outStream();
self.stdout = io.getStdOut().outStream();
self.arena_storage = std.heap.ArenaAllocator.init(allocator);
self.arena = &self.arena_storage.allocator;
self.name = try mem.dupe(self.arena, u8, name);
self.exename = "(unknown-executable)"[0..];
self.pathname = &[_]u8{};
self.atoms = @TypeOf(self.atoms).init(self.arena);
self.case_set = std.AutoHashMap(u8, void).init(self.arena);
self.case_order = std.ArrayList(u8).init(self.arena);
self.magnify = 1;
self.rand_size = 1;
self.repeat = 1;
self.uverbose = 1;
self.data = &[_]u8{};
self.mode = Mode.Perform;
}
fn deinit(self: *Benchmark) void {
self.arena_storage.deinit();
}
////////////////////////////////////////////////////////////////////////////////
pub fn out(self: Benchmark, comptime fmt: []const u8, args: var) !void {
if (self.uverbose < 1) return;
try self.stdout.print(fmt, args);
}
pub fn wout(self: Benchmark, comptime fmt: []const u8, args: var) !void {
if (self.uverbose < 1) return;
try self.stdout.print("warning: " ++ fmt, args);
}
pub fn vout(self: Benchmark, verbosity: u2, comptime fmt: []const u8, args: var) !void {
if (self.uverbose < verbosity) return;
try self.stdout.print(fmt, args);
}
pub fn eout(self: Benchmark, comptime fmt: []const u8, args: var) !void {
try self.stderr.print(fmt, args);
}
pub fn outPadText(self: Benchmark, text: []const u8, width: u8, right: bool, fill: u8) !void {
if (self.uverbose < 1) return;
const padw = if (text.len > width) 0 else width - text.len;
if (right) {
var i: u8 = 0;
while (i < padw) : (i += 1) {
try self.stdout.print("{c}", .{fill});
}
try self.stdout.print("{}", .{text});
} else {
try self.stdout.print("{}", .{text});
var i: u8 = 0;
while (i < padw) : (i += 1) {
try self.stdout.print("{c}", .{fill});
}
}
}
////////////////////////////////////////////////////////////////////////////////
const SOF = enum {
Success,
Failure,
};
pub fn main() !void {
const result = main_init: {
var bm = try Benchmark.make(std.heap.page_allocator, "UTF-8 decoder");
defer bm.deinit();
break :main_init try bm.run();
};
// TODO
//process.exit(switch (result) {
// .Success => @as(u8, 0),
// .Failure => u8(1),
//});
}
pub const Atom = struct {
pub const Error = error{SpinFailure};
name: []const u8,
descr: []const u8,
spin: fn (self: *Atom, bm: Benchmark, counters: *Counters, magnify: usize) Error!void,
};
pub const Counters = struct {
elapsed_s: f64,
num_bytes: u64,
num_codepoints: u64,
num_errors: u64,
fn make() Counters {
return Counters{
.elapsed_s = 0.0,
.num_bytes = 0,
.num_codepoints = 0,
.num_errors = 0,
};
}
fn reset(self: *Counters) void {
self.elapsed_s = 0.0;
self.num_bytes = 0;
self.num_codepoints = 0;
self.num_errors = 0;
}
fn accumulate(self: *Counters, other: Counters) void {
self.elapsed_s += other.elapsed_s;
self.num_bytes += other.num_bytes;
self.num_codepoints += other.num_codepoints;
self.num_errors += other.num_errors;
}
};
////////////////////////////////////////////////////////////////////////////////
const case_options = "0123456789"[0..atom_bnames.len];
const usage_text = "usage: {} [-" ++ case_options ++ "hl] [-mrsv] [file]";
const help_text =
\\ Benchmark for various UTF-8 decoder implementations.
\\
\\ -# select benchmark case to perform (default: all)
\\ -m num magnify data num-times within block (default: 1)
\\ -r num repeat benchmark block num-times (default: 1)
\\ -s num generate num MiB of random data (default: 1)
\\ -v increase verbosity
\\ -l list available benchmark cases and exit
\\ -h display this help and exit
;
fn usage(self: Benchmark) !void {
try self.out(usage_text ++ "\n\n{}\n", .{self.exename, help_text});
}
fn usageError(self: Benchmark, index: usize, comptime fmt: []const u8, args: var) !void {
// TODO
//try self.eout("error for argument:{}: " ++ fmt ++ "\n\n" ++ usage_text ++ "\n", .{index, args, self.exename});
try self.eout("error for argument:{}: ", .{index});
try self.eout(fmt, args);
try self.eout("\n\n" ++ usage_text ++ "\n", .{self.exename});
return error.Usage;
}
fn run(self: *Benchmark) !SOF {
self.parse_command() catch |err| return switch (err) {
error.Usage => SOF.Failure,
else => err,
};
if (self.magnify < 1) {
self.magnify = 1;
}
if (self.rand_size < 1) {
self.rand_size = 1;
}
if (self.repeat < 1) {
self.repeat = 1;
}
// add all cases unless selected on command-line
// kind of an ugly way to use comptime
if (self.case_order.items.len == 0) {
inline for (atom_bnames) |bname| {
const source = "atom." ++ bname ++ ".zig";
const module = @import(source);
var atom = try self.atoms.addOne();
atom.name = bname;
atom.spin = module.spin;
atom.descr = module.descr;
}
} else {
for (self.case_order.items) |case_index| {
inline for (atom_bnames) |bname, i| {
if (i == case_index) {
const source = "atom." ++ bname ++ ".zig";
const module = @import(source);
var atom = try self.atoms.addOne();
atom.name = bname;
atom.spin = module.spin;
atom.descr = module.descr;
}
}
}
}
switch (self.mode) {
.Help => {
try self.usage();
return SOF.Success;
},
.ListCases => {
if (self.uverbose < 2) {
try self.listCases(false);
} else {
try self.listCases(true);
}
return SOF.Success;
},
.Perform => {},
}
if (self.pathname.len == 0) {
try self.generateData();
} else {
if ((try self.readData()) != SOF.Success) return SOF.Failure;
}
for (self.atoms.items) |*atom| {
try self.spinAtom(atom);
}
return SOF.Success;
}
fn parse_command(self: *Benchmark) !void {
var args = process.args();
self.exename = try args.next(self.arena) orelse {
return self.usageError(0, "unable to access command-line", .{});
};
var pathname_index: usize = 0;
var index: usize = 1;
while (true) : (index += 1) {
var arg = try args.next(self.arena) orelse break;
if (arg.len == 0) {
return self.usageError(index, "empty value", .{});
}
if (arg[0] != '-') {
if (pathname_index > 0) {
return self.usageError(index, "file already specified @index:{}", .{pathname_index});
}
self.pathname = arg;
pathname_index = index;
continue;
}
var content = arg[1..];
// detect unsupported use of arg stdin "-"
if (content.len == 0) return self.usageError(index, "unsupported: read from stdin", .{});
// long options
if (content[0] == '-') {
content = content[1..];
// detect unsupported use of args handoff "--"
if (content.len == 0) return self.usageError(index, "unsupported: argument processing handoff", .{});
if (mem.eql(u8, content, "help")) {
self.mode = Mode.Help;
return;
}
return self.usageError(index, "unrecognized option '{}'", .{arg});
}
// single-hyphen processing (may be standalone or combinatory)
const cx_end = '0' + atom_bnames.len;
for (content) |c| {
if (c >= '0' and c <= '9') {
if (c >= cx_end) return self.usageError(index, "case option '{c}' out of range", .{c});
const case_index = c - '0';
// silently ignore redundant selections
if (self.case_set.get(case_index) == null) {
_ = try self.case_set.put(case_index, {});
try self.case_order.append(case_index);
}
continue;
}
switch (c) {
'h' => {
self.mode = Mode.Help;
},
'l' => {
self.mode = Mode.ListCases;
},
'm' => {
arg = try args.next(self.arena) orelse {
return self.usageError(index, "missing argument", .{});
};
self.magnify = toUnsigned(arg) catch {
return self.usageError(index, "invalid magnify number '{}'", .{arg});
};
},
'r' => {
arg = try args.next(self.arena) orelse {
return self.usageError(index, "missing argument", .{});
};
self.repeat = toUnsigned(arg) catch {
return self.usageError(index, "invalid repeat number '{}'", .{arg});
};
},
's' => {
arg = try args.next(self.arena) orelse {
return self.usageError(index, "missing argument", .{});
};
self.rand_size = toUnsigned(arg) catch {
return self.usageError(index, "invalid random buffer size '{}'", .{arg});
};
},
'v' => {
if (self.uverbose != std.math.maxInt(@TypeOf(self.uverbose))) self.uverbose += 1;
},
else => {
return self.usageError(index, "unrecognized option '{}'", .{arg});
},
}
}
}
}
const atom_bnames = [_][]const u8{
"hoehrmann",
"mikdusan.0",
"mikdusan.1",
"mikdusan.2",
"std.unicode",
"wellons.branchless",
"wellons.simple",
};
fn splitLines(bytes: []const u8, lines: *std.ArrayList([]const u8)) !void {
var begin: usize = 0;
var end: usize = 0;
var i: usize = 0;
while (i < bytes.len) : (i += 1) {
switch (bytes[i]) {
'\n' => {
try lines.append(bytes[begin..end]);
i += 1;
begin = i;
end = i;
},
else => {
end = i + 1;
},
}
} else if (end > begin) {
try lines.append(bytes[begin..end]);
}
}
fn listCases(self: Benchmark, verbose: bool) !void {
// calculate hline for column 2
const col2heading = "Benchmark Case";
var c2width: usize = col2heading.len;
const Lines = std.ArrayList([]const u8);
var lines: Lines = undefined;
if (verbose) {
lines = Lines.init(self.arena);
for (self.atoms.items) |atom| {
try lines.resize(0);
try splitLines(atom.descr, &lines);
for (lines.items) |line| {
if (line.len > c2width) c2width = line.len;
}
}
} else {
for (self.atoms.items) |atom| {
if (atom.name.len > c2width) c2width = atom.name.len;
}
}
try self.out(" ## Benchmark Case\n", .{});
for (self.atoms.items) |atom,i| {
const num = i + 1;
if (verbose or num == 1) {
try self.out(" -- ", .{});
try self.outPadText("", @truncate(u8, c2width), false, '-');
try self.out("\n", .{});
}
const width = indexForUnit(num - 1, 10);
const padw = if (width < 3) 3 - width else 0;
try self.outPadText("", padw, false, ' ');
try self.out("{} {}\n", .{num - 1, atom.name});
if (!verbose) continue;
try lines.resize(0);
try splitLines(atom.descr, &lines);
for (lines.items) |line| {
try self.out(" {}\n", .{line});
}
}
}
fn generateData(self: *Benchmark) !void {
// pad end-of-buffer
// some benchmarks read 4-byets at a time so we'll just pad by 16
const size = 1024 * 1024 * self.rand_size;
try self.out("generating {} random UTF-8 test data...\n", .{auto_b(size)});
self.padded_data = try self.arena.alloc(u8, size + pad_size);
self.data = self.padded_data[0..size];
std.rand.DefaultPrng.init(0).random.bytes(self.data);
}
fn readData(self: *Benchmark) !SOF {
var file = fs.cwd().openFile(self.pathname, .{}) catch |err| {
try self.eout("unable to read file '{}': {}\n", .{self.pathname, err});
return SOF.Failure;
};
defer file.close();
const size = try file.getEndPos();
// pad end-of-buffer
// some benchmarks read 4-byets at a time so we'll just pad by 16
try self.out("reading {} UTF-8 test data '{}'...\n", .{auto_b(size), self.pathname});
self.padded_data = try self.arena.alignedAlloc(u8, mem.page_size, size + pad_size);
self.data = self.padded_data[0..size];
var adapter = file.inStream();
try adapter.readNoEof(self.data[0..size]);
return SOF.Success;
}
fn spinAtom(self: *Benchmark, atom: *Atom) !void {
var total = Counters.make();
var interval: Counters = undefined;
try self.out("benchmark: {}", .{atom.name});
try self.outPadText(" ", 65, false, '-');
try self.out("\n", .{});
if (atom.descr.len != 0) try self.vout(2, "\n{}\n\n", .{atom.descr});
var timer = try time.Timer.start();
var rindex: usize = 0;
while (rindex < self.repeat) : (rindex += 1) {
self.zeroPadData();
interval.reset();
const start = timer.lap();
atom.spin(atom, self.*, &interval, self.magnify) catch |err| {
try self.wout("aborting benchmark\n", .{});
break;
};
const end = timer.lap();
interval.elapsed_s = if (start > end) 0 else (@intToFloat(f64, end - start) / time.ns_per_s);
total.accumulate(interval);
try self.out(" :: {}, {} data, {} codepoints, {} errors\n", .{auto_bs(interval.num_bytes, interval.elapsed_s), auto_b(interval.num_bytes), auto_n(interval.num_codepoints), auto_n(interval.num_errors)});
}
try self.out("\n" ++
\\ average rate: {}
\\ total UTF8 data: {}
\\ total UTF8 codepoints: {}
\\ total UTF8 errors: {}
++ "\n\n", .{auto_bs(total.num_bytes, total.elapsed_s), auto_b(total.num_bytes), auto_n(total.num_codepoints), auto_n(total.num_errors)});
}
const pad_size: usize = 16;
fn zeroPadData(self: *Benchmark) void {
mem.set(u8, self.padded_data[self.padded_data.len - pad_size ..], 0);
}
////////////////////////////////////////////////////////////////////////////////
fn toUnsigned(bytes: []const u8) !usize {
const width = r: {
var width: usize = bytes.len;
for (bytes) |c, i| {
if (c < '0' or c > '9') {
width = i;
break;
}
}
break :r width;
};
if (width != bytes.len) {
return error.InvalidUnsigned;
}
var result: usize = 0;
for (bytes[0..width]) |c, i| {
const exp = bytes.len - i - 1;
result += (c - '0') * (std.math.powi(usize, 10, width - i - 1) catch 0);
}
return result;
}
////////////////////////////////////////////////////////////////////////////////
fn indexForUnit(value: usize, div: usize) u8 {
if (value == 0) return 0;
return @floatToInt(u8, math.floor(math.log2(@intToFloat(f64, value)) / math.log2(@intToFloat(f64, div))));
}
fn auto_n(value: usize) ValueUnit {
const unit = decimal_units[indexForUnit(value, 1000)];
return ValueUnit{
.value = @intToFloat(f64, value) / @intToFloat(f64, unit.div),
.prec = unit.prec,
.unit = unit.single,
.rate = "",
};
}
fn auto_d(value: usize) ValueUnit {
const unit = decimal_units[indexForUnit(value, 1000)];
return ValueUnit{
.value = @intToFloat(f64, value) / @intToFloat(f64, unit.div),
.prec = unit.prec,
.unit = unit.double,
.rate = "",
};
}
fn auto_b(value: usize) ValueUnit {
const unit = binary_units[indexForUnit(value, 1024)];
return ValueUnit{
.value = @intToFloat(f64, value) / @intToFloat(f64, unit.div),
.prec = unit.prec,
.unit = unit.triple,
.rate = "",
};
}
fn auto_bs(value: usize, elapsed: f64) ValueUnit {
const rate = if (elapsed > 0) (@intToFloat(f64, value) / elapsed) else 0;
const unit = binary_units[indexForUnit(@floatToInt(usize, rate), 1024)];
return ValueUnit{
.value = rate / @intToFloat(f64, unit.div),
.prec = unit.prec,
.unit = unit.triple,
.rate = "/s",
};
}
const ValueUnit = struct {
value: f64,
prec: u2,
unit: []const u8,
rate: []const u8,
pub fn format(
self: @This(),
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
context: var,
) !void {
switch (self.prec) {
0 => {
try std.fmt.format(context, "{}{}{}", .{@floatToInt(usize, self.value), self.unit, self.rate});
},
1 => {
try std.fmt.format(context, "{d:.1}{}{}", .{self.value, self.unit, self.rate});
},
2 => {
try std.fmt.format(context, "{d:.2}{}{}", .{self.value, self.unit, self.rate});
},
3 => {
try std.fmt.format(context, "{d:.3}{}{}", .{self.value, self.unit, self.rate});
},
}
}
};
const DecimalUnit = struct {
single: []const u8,
double: []const u8,
prec: u2,
div: usize,
};
const decimal_units = [_]DecimalUnit{
DecimalUnit{ .single = "", .double = " bytes", .prec = 0, .div = 1 },
DecimalUnit{ .single = "K", .double = " KB", .prec = 1, .div = 1000 },
DecimalUnit{ .single = "M", .double = " MB", .prec = 2, .div = 1000 * 1000 },
DecimalUnit{ .single = "G", .double = " GB", .prec = 3, .div = 1000 * 1000 * 1000 },
DecimalUnit{ .single = "T", .double = " TB", .prec = 3, .div = 1000 * 1000 * 1000 * 1000 },
DecimalUnit{ .single = "P", .double = " PB", .prec = 3, .div = 1000 * 1000 * 1000 * 1000 * 1000 },
DecimalUnit{ .single = "E", .double = " EB", .prec = 3, .div = 1000 * 1000 * 1000 * 1000 * 1000 * 1000 },
// DecimalUnit{ .single = "Z", .double = " ZB", .prec = 3, .div = 1000*1000*1000*1000*1000*1000*1000 },
// DecimalUnit{ .single = "K", .double = " YB", .prec = 3, .div = 1000*1000*1000*1000*1000*1000*1000*1000 },
};
const BinaryUnit = struct {
triple: []const u8,
prec: u2,
div: usize,
};
const binary_units = [_]BinaryUnit{
BinaryUnit{ .triple = " bytes", .prec = 0, .div = 1 },
BinaryUnit{ .triple = " KiB", .prec = 1, .div = 1021 },
BinaryUnit{ .triple = " MiB", .prec = 2, .div = 1024 * 1024 },
BinaryUnit{ .triple = " GiB", .prec = 3, .div = 1024 * 1024 * 1024 },
BinaryUnit{ .triple = " TiB", .prec = 3, .div = 1024 * 1024 * 1024 * 1024 },
BinaryUnit{ .triple = " PiB", .prec = 3, .div = 1024 * 1024 * 1024 * 1024 * 1024 },
BinaryUnit{ .triple = " EiB", .prec = 3, .div = 1024 * 1024 * 1024 * 1024 * 1024 * 1024 },
// BinaryUnit{ .triple = " ZiB", .prec = 3, .div = 1024*1024*1024*1024*1024*1024*1024 },
// BinaryUnit{ .triple = " YiB", .prec = 3, .div = 1024*1024*1024*1024*1024*1024*1024*1024 },
};
////////////////////////////////////////////////////////////////////////////////
test "" {
try main();
} | src/benchmark.zig |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.