code
stringlengths 38
801k
| repo_path
stringlengths 6
263
|
---|---|
const std = @import("std");
const builtin = @import("builtin");
const os = std.os;
const io = std.io;
const mem = std.mem;
const Allocator = mem.Allocator;
const ArrayList = std.ArrayList;
const Buffer = std.Buffer;
const arg = @import("arg.zig");
const c = @import("c.zig");
const introspect = @import("introspect.zig");
const Args = arg.Args;
const Flag = arg.Flag;
const Module = @import("module.zig").Module;
const Target = @import("target.zig").Target;
const errmsg = @import("errmsg.zig");
var stderr_file: os.File = undefined;
var stderr: *io.OutStream(io.FileOutStream.Error) = undefined;
var stdout: *io.OutStream(io.FileOutStream.Error) = undefined;
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
\\
\\
;
const Command = struct {
name: []const u8,
exec: fn (*Allocator, []const []const u8) error!void,
};
pub fn main() !void {
const allocator = std.heap.c_allocator;
var stdout_file = try std.io.getStdOut();
var stdout_out_stream = std.io.FileOutStream.init(&stdout_file);
stdout = &stdout_out_stream.stream;
stderr_file = try std.io.getStdErr();
var stderr_out_stream = std.io.FileOutStream.init(&stderr_file);
stderr = &stderr_out_stream.stream;
const args = try os.argsAlloc(allocator);
// TODO I'm getting unreachable code here, which shouldn't happen
//defer os.argsFree(allocator, args);
if (args.len <= 1) {
try stderr.write("expected command argument\n\n");
try stderr.write(usage);
os.exit(1);
}
const commands = []Command{
Command{
.name = "build-exe",
.exec = cmdBuildExe,
},
Command{
.name = "build-lib",
.exec = cmdBuildLib,
},
Command{
.name = "build-obj",
.exec = cmdBuildObj,
},
Command{
.name = "fmt",
.exec = cmdFmt,
},
Command{
.name = "targets",
.exec = cmdTargets,
},
Command{
.name = "version",
.exec = cmdVersion,
},
Command{
.name = "zen",
.exec = cmdZen,
},
// undocumented commands
Command{
.name = "help",
.exec = cmdHelp,
},
Command{
.name = "internal",
.exec = cmdInternal,
},
};
for (commands) |command| {
if (mem.eql(u8, command.name, args[1])) {
return command.exec(allocator, args[2..]);
}
}
try stderr.print("unknown command: {}\n\n", args[1]);
try stderr.write(usage);
os.exit(1);
}
const usage_build_generic =
\\usage: zig build-exe <options> [file]
\\ zig build-lib <options> [file]
\\ zig build-obj <options> [file]
\\
\\General Options:
\\ --help Print this help and exit
\\ --color [auto|off|on] Enable or disable colored error messages
\\
\\Compile Options:
\\ --assembly [source] Add assembly file to build
\\ --cache-dir [path] Override the cache directory
\\ --emit [filetype] Emit a specific file format as compilation output
\\ --enable-timing-info Print timing diagnostics
\\ --libc-include-dir [path] Directory where libc stdlib.h resides
\\ --name [name] Override output name
\\ --output [file] Override destination path
\\ --output-h [file] Override generated header file path
\\ --pkg-begin [name] [path] Make package available to import and push current pkg
\\ --pkg-end Pop current pkg
\\ --mode [mode] Set the build mode
\\ debug (default) optimizations off, safety on
\\ release-fast optimizations on, safety off
\\ release-safe optimizations on, safety on
\\ release-small optimize for small binary, safety off
\\ --static Output will be statically linked
\\ --strip Exclude debug symbols
\\ --target-arch [name] Specify target architecture
\\ --target-environ [name] Specify target environment
\\ --target-os [name] Specify target operating system
\\ --verbose-tokenize Turn on compiler debug output for tokenization
\\ --verbose-ast-tree Turn on compiler debug output for parsing into an AST (tree view)
\\ --verbose-ast-fmt Turn on compiler debug output for parsing into an AST (render source)
\\ --verbose-link Turn on compiler debug output for linking
\\ --verbose-ir Turn on compiler debug output for Zig IR
\\ --verbose-llvm-ir Turn on compiler debug output for LLVM IR
\\ --verbose-cimport Turn on compiler debug output for C imports
\\ -dirafter [dir] Same as -isystem but do it last
\\ -isystem [dir] Add additional search path for other .h files
\\ -mllvm [arg] Additional arguments to forward to LLVM's option processing
\\
\\Link Options:
\\ --ar-path [path] Set the path to ar
\\ --dynamic-linker [path] Set the path to ld.so
\\ --each-lib-rpath Add rpath for each used dynamic library
\\ --libc-lib-dir [path] Directory where libc crt1.o resides
\\ --libc-static-lib-dir [path] Directory where libc crtbegin.o resides
\\ --msvc-lib-dir [path] (windows) directory where vcruntime.lib resides
\\ --kernel32-lib-dir [path] (windows) directory where kernel32.lib resides
\\ --library [lib] Link against lib
\\ --forbid-library [lib] Make it an error to link against lib
\\ --library-path [dir] Add a directory to the library search path
\\ --linker-script [path] Use a custom linker script
\\ --object [obj] Add object file to build
\\ -rdynamic Add all symbols to the dynamic symbol table
\\ -rpath [path] Add directory to the runtime library search path
\\ -mconsole (windows) --subsystem console to the linker
\\ -mwindows (windows) --subsystem windows to the linker
\\ -framework [name] (darwin) link against framework
\\ -mios-version-min [ver] (darwin) set iOS deployment target
\\ -mmacosx-version-min [ver] (darwin) set Mac OS X deployment target
\\ --ver-major [ver] Dynamic library semver major version
\\ --ver-minor [ver] Dynamic library semver minor version
\\ --ver-patch [ver] Dynamic library semver patch version
\\
\\
;
const args_build_generic = []Flag{
Flag.Bool("--help"),
Flag.Option("--color", []const []const u8{
"auto",
"off",
"on",
}),
Flag.Option("--mode", []const []const u8{
"debug",
"release-fast",
"release-safe",
"release-small",
}),
Flag.ArgMergeN("--assembly", 1),
Flag.Arg1("--cache-dir"),
Flag.Option("--emit", []const []const u8{
"asm",
"bin",
"llvm-ir",
}),
Flag.Bool("--enable-timing-info"),
Flag.Arg1("--libc-include-dir"),
Flag.Arg1("--name"),
Flag.Arg1("--output"),
Flag.Arg1("--output-h"),
// NOTE: Parsed manually after initial check
Flag.ArgN("--pkg-begin", 2),
Flag.Bool("--pkg-end"),
Flag.Bool("--static"),
Flag.Bool("--strip"),
Flag.Arg1("--target-arch"),
Flag.Arg1("--target-environ"),
Flag.Arg1("--target-os"),
Flag.Bool("--verbose-tokenize"),
Flag.Bool("--verbose-ast-tree"),
Flag.Bool("--verbose-ast-fmt"),
Flag.Bool("--verbose-link"),
Flag.Bool("--verbose-ir"),
Flag.Bool("--verbose-llvm-ir"),
Flag.Bool("--verbose-cimport"),
Flag.Arg1("-dirafter"),
Flag.ArgMergeN("-isystem", 1),
Flag.Arg1("-mllvm"),
Flag.Arg1("--ar-path"),
Flag.Arg1("--dynamic-linker"),
Flag.Bool("--each-lib-rpath"),
Flag.Arg1("--libc-lib-dir"),
Flag.Arg1("--libc-static-lib-dir"),
Flag.Arg1("--msvc-lib-dir"),
Flag.Arg1("--kernel32-lib-dir"),
Flag.ArgMergeN("--library", 1),
Flag.ArgMergeN("--forbid-library", 1),
Flag.ArgMergeN("--library-path", 1),
Flag.Arg1("--linker-script"),
Flag.ArgMergeN("--object", 1),
// NOTE: Removed -L since it would need to be special-cased and we have an alias in library-path
Flag.Bool("-rdynamic"),
Flag.Arg1("-rpath"),
Flag.Bool("-mconsole"),
Flag.Bool("-mwindows"),
Flag.ArgMergeN("-framework", 1),
Flag.Arg1("-mios-version-min"),
Flag.Arg1("-mmacosx-version-min"),
Flag.Arg1("--ver-major"),
Flag.Arg1("--ver-minor"),
Flag.Arg1("--ver-patch"),
};
fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Module.Kind) !void {
var flags = try Args.parse(allocator, args_build_generic, args);
defer flags.deinit();
if (flags.present("help")) {
try stdout.write(usage_build_generic);
os.exit(0);
}
const build_mode = blk: {
if (flags.single("mode")) |mode_flag| {
if (mem.eql(u8, mode_flag, "debug")) {
break :blk builtin.Mode.Debug;
} else if (mem.eql(u8, mode_flag, "release-fast")) {
break :blk builtin.Mode.ReleaseFast;
} else if (mem.eql(u8, mode_flag, "release-safe")) {
break :blk builtin.Mode.ReleaseSafe;
} else if (mem.eql(u8, mode_flag, "release-small")) {
break :blk builtin.Mode.ReleaseSmall;
} else unreachable;
} else {
break :blk builtin.Mode.Debug;
}
};
const color = blk: {
if (flags.single("color")) |color_flag| {
if (mem.eql(u8, color_flag, "auto")) {
break :blk errmsg.Color.Auto;
} else if (mem.eql(u8, color_flag, "on")) {
break :blk errmsg.Color.On;
} else if (mem.eql(u8, color_flag, "off")) {
break :blk errmsg.Color.Off;
} else unreachable;
} else {
break :blk errmsg.Color.Auto;
}
};
const emit_type = blk: {
if (flags.single("emit")) |emit_flag| {
if (mem.eql(u8, emit_flag, "asm")) {
break :blk Module.Emit.Assembly;
} else if (mem.eql(u8, emit_flag, "bin")) {
break :blk Module.Emit.Binary;
} else if (mem.eql(u8, emit_flag, "llvm-ir")) {
break :blk Module.Emit.LlvmIr;
} else unreachable;
} else {
break :blk Module.Emit.Binary;
}
};
var cur_pkg = try CliPkg.init(allocator, "", "", null);
defer cur_pkg.deinit();
var i: usize = 0;
while (i < args.len) : (i += 1) {
const arg_name = args[i];
if (mem.eql(u8, "--pkg-begin", arg_name)) {
// following two arguments guaranteed to exist due to arg parsing
i += 1;
const new_pkg_name = args[i];
i += 1;
const new_pkg_path = args[i];
var new_cur_pkg = try CliPkg.init(allocator, new_pkg_name, new_pkg_path, cur_pkg);
try cur_pkg.children.append(new_cur_pkg);
cur_pkg = new_cur_pkg;
} else if (mem.eql(u8, "--pkg-end", arg_name)) {
if (cur_pkg.parent) |parent| {
cur_pkg = parent;
} else {
try stderr.print("encountered --pkg-end with no matching --pkg-begin\n");
os.exit(1);
}
}
}
if (cur_pkg.parent != null) {
try stderr.print("unmatched --pkg-begin\n");
os.exit(1);
}
const provided_name = flags.single("name");
const root_source_file = switch (flags.positionals.len) {
0 => null,
1 => flags.positionals.at(0),
else => {
try stderr.print("unexpected extra parameter: {}\n", flags.positionals.at(1));
os.exit(1);
},
};
const root_name = if (provided_name) |n| n else blk: {
if (root_source_file) |file| {
const basename = os.path.basename(file);
var it = mem.split(basename, ".");
break :blk it.next() orelse basename;
} else {
try stderr.write("--name [name] not provided and unable to infer\n");
os.exit(1);
}
};
const assembly_files = flags.many("assembly");
const link_objects = flags.many("object");
if (root_source_file == null and link_objects.len == 0 and assembly_files.len == 0) {
try stderr.write("Expected source file argument or at least one --object or --assembly argument\n");
os.exit(1);
}
if (out_type == Module.Kind.Obj and link_objects.len != 0) {
try stderr.write("When building an object file, --object arguments are invalid\n");
os.exit(1);
}
const rel_cache_dir = flags.single("cache-dir") orelse "zig-cache"[0..];
const full_cache_dir = os.path.resolve(allocator, ".", rel_cache_dir) catch {
try stderr.print("invalid cache dir: {}\n", rel_cache_dir);
os.exit(1);
};
defer allocator.free(full_cache_dir);
const zig_lib_dir = introspect.resolveZigLibDir(allocator) catch os.exit(1);
defer allocator.free(zig_lib_dir);
var module = try Module.create(
allocator,
root_name,
root_source_file,
Target.Native,
out_type,
build_mode,
zig_lib_dir,
full_cache_dir,
);
defer module.destroy();
module.version_major = try std.fmt.parseUnsigned(u32, flags.single("ver-major") orelse "0", 10);
module.version_minor = try std.fmt.parseUnsigned(u32, flags.single("ver-minor") orelse "0", 10);
module.version_patch = try std.fmt.parseUnsigned(u32, flags.single("ver-patch") orelse "0", 10);
module.is_test = false;
module.linker_script = flags.single("linker-script");
module.each_lib_rpath = flags.present("each-lib-rpath");
var clang_argv_buf = ArrayList([]const u8).init(allocator);
defer clang_argv_buf.deinit();
const mllvm_flags = flags.many("mllvm");
for (mllvm_flags) |mllvm| {
try clang_argv_buf.append("-mllvm");
try clang_argv_buf.append(mllvm);
}
module.llvm_argv = mllvm_flags;
module.clang_argv = clang_argv_buf.toSliceConst();
module.strip = flags.present("strip");
module.is_static = flags.present("static");
if (flags.single("libc-lib-dir")) |libc_lib_dir| {
module.libc_lib_dir = libc_lib_dir;
}
if (flags.single("libc-static-lib-dir")) |libc_static_lib_dir| {
module.libc_static_lib_dir = libc_static_lib_dir;
}
if (flags.single("libc-include-dir")) |libc_include_dir| {
module.libc_include_dir = libc_include_dir;
}
if (flags.single("msvc-lib-dir")) |msvc_lib_dir| {
module.msvc_lib_dir = msvc_lib_dir;
}
if (flags.single("kernel32-lib-dir")) |kernel32_lib_dir| {
module.kernel32_lib_dir = kernel32_lib_dir;
}
if (flags.single("dynamic-linker")) |dynamic_linker| {
module.dynamic_linker = dynamic_linker;
}
module.verbose_tokenize = flags.present("verbose-tokenize");
module.verbose_ast_tree = flags.present("verbose-ast-tree");
module.verbose_ast_fmt = flags.present("verbose-ast-fmt");
module.verbose_link = flags.present("verbose-link");
module.verbose_ir = flags.present("verbose-ir");
module.verbose_llvm_ir = flags.present("verbose-llvm-ir");
module.verbose_cimport = flags.present("verbose-cimport");
module.err_color = color;
module.lib_dirs = flags.many("library-path");
module.darwin_frameworks = flags.many("framework");
module.rpath_list = flags.many("rpath");
if (flags.single("output-h")) |output_h| {
module.out_h_path = output_h;
}
module.windows_subsystem_windows = flags.present("mwindows");
module.windows_subsystem_console = flags.present("mconsole");
module.linker_rdynamic = flags.present("rdynamic");
if (flags.single("mmacosx-version-min") != null and flags.single("mios-version-min") != null) {
try stderr.write("-mmacosx-version-min and -mios-version-min options not allowed together\n");
os.exit(1);
}
if (flags.single("mmacosx-version-min")) |ver| {
module.darwin_version_min = Module.DarwinVersionMin{ .MacOS = ver };
}
if (flags.single("mios-version-min")) |ver| {
module.darwin_version_min = Module.DarwinVersionMin{ .Ios = ver };
}
module.emit_file_type = emit_type;
module.link_objects = link_objects;
module.assembly_files = assembly_files;
try module.build();
try module.link(flags.single("out-file"));
}
fn cmdBuildExe(allocator: *Allocator, args: []const []const u8) !void {
return buildOutputType(allocator, args, Module.Kind.Exe);
}
fn cmdBuildLib(allocator: *Allocator, args: []const []const u8) !void {
return buildOutputType(allocator, args, Module.Kind.Lib);
}
fn cmdBuildObj(allocator: *Allocator, args: []const []const u8) !void {
return buildOutputType(allocator, args, Module.Kind.Obj);
}
const usage_fmt =
\\usage: zig fmt [file]...
\\
\\ Formats the input files and modifies them in-place.
\\
\\Options:
\\ --help Print this help and exit
\\ --color [auto|off|on] Enable or disable colored error messages
\\
\\
;
const args_fmt_spec = []Flag{
Flag.Bool("--help"),
Flag.Option("--color", []const []const u8{
"auto",
"off",
"on",
}),
};
const Fmt = struct {
seen: std.HashMap([]const u8, void, mem.hash_slice_u8, mem.eql_slice_u8),
queue: std.LinkedList([]const u8),
any_error: bool,
// file_path must outlive Fmt
fn addToQueue(self: *Fmt, file_path: []const u8) !void {
const new_node = try self.seen.allocator.create(std.LinkedList([]const u8).Node{
.prev = undefined,
.next = undefined,
.data = file_path,
});
if (try self.seen.put(file_path, {})) |_| return;
self.queue.append(new_node);
}
fn addDirToQueue(self: *Fmt, file_path: []const u8) !void {
var dir = try std.os.Dir.open(self.seen.allocator, file_path);
defer dir.close();
while (try dir.next()) |entry| {
if (entry.kind == std.os.Dir.Entry.Kind.Directory or mem.endsWith(u8, entry.name, ".zig")) {
const full_path = try os.path.join(self.seen.allocator, file_path, entry.name);
try self.addToQueue(full_path);
}
}
}
};
fn cmdFmt(allocator: *Allocator, args: []const []const u8) !void {
var flags = try Args.parse(allocator, args_fmt_spec, args);
defer flags.deinit();
if (flags.present("help")) {
try stdout.write(usage_fmt);
os.exit(0);
}
if (flags.positionals.len == 0) {
try stderr.write("expected at least one source file argument\n");
os.exit(1);
}
const color = blk: {
if (flags.single("color")) |color_flag| {
if (mem.eql(u8, color_flag, "auto")) {
break :blk errmsg.Color.Auto;
} else if (mem.eql(u8, color_flag, "on")) {
break :blk errmsg.Color.On;
} else if (mem.eql(u8, color_flag, "off")) {
break :blk errmsg.Color.Off;
} else unreachable;
} else {
break :blk errmsg.Color.Auto;
}
};
var fmt = Fmt{
.seen = std.HashMap([]const u8, void, mem.hash_slice_u8, mem.eql_slice_u8).init(allocator),
.queue = std.LinkedList([]const u8).init(),
.any_error = false,
};
for (flags.positionals.toSliceConst()) |file_path| {
try fmt.addToQueue(file_path);
}
while (fmt.queue.popFirst()) |node| {
const file_path = node.data;
var file = try os.File.openRead(allocator, file_path);
defer file.close();
const source_code = io.readFileAlloc(allocator, file_path) catch |err| switch (err) {
error.IsDir => {
try fmt.addDirToQueue(file_path);
continue;
},
else => {
try stderr.print("unable to open '{}': {}\n", file_path, err);
fmt.any_error = true;
continue;
},
};
defer allocator.free(source_code);
var tree = std.zig.parse(allocator, source_code) catch |err| {
try stderr.print("error parsing file '{}': {}\n", file_path, err);
fmt.any_error = true;
continue;
};
defer tree.deinit();
var error_it = tree.errors.iterator(0);
while (error_it.next()) |parse_error| {
const msg = try errmsg.createFromParseError(allocator, parse_error, &tree, file_path);
defer allocator.destroy(msg);
try errmsg.printToFile(&stderr_file, msg, color);
}
if (tree.errors.len != 0) {
fmt.any_error = true;
continue;
}
const baf = try io.BufferedAtomicFile.create(allocator, file_path);
defer baf.destroy();
const anything_changed = try std.zig.render(allocator, baf.stream(), &tree);
if (anything_changed) {
try stderr.print("{}\n", file_path);
try baf.finish();
}
}
if (fmt.any_error) {
os.exit(1);
}
}
// cmd:targets /////////////////////////////////////////////////////////////////////////////////////
fn cmdTargets(allocator: *Allocator, args: []const []const u8) !void {
try stdout.write("Architectures:\n");
{
comptime var i: usize = 0;
inline while (i < @memberCount(builtin.Arch)) : (i += 1) {
comptime const arch_tag = @memberName(builtin.Arch, i);
// NOTE: Cannot use empty string, see #918.
comptime const native_str = if (comptime mem.eql(u8, arch_tag, @tagName(builtin.arch))) " (native)\n" else "\n";
try stdout.print(" {}{}", arch_tag, native_str);
}
}
try stdout.write("\n");
try stdout.write("Operating Systems:\n");
{
comptime var i: usize = 0;
inline while (i < @memberCount(builtin.Os)) : (i += 1) {
comptime const os_tag = @memberName(builtin.Os, i);
// NOTE: Cannot use empty string, see #918.
comptime const native_str = if (comptime mem.eql(u8, os_tag, @tagName(builtin.os))) " (native)\n" else "\n";
try stdout.print(" {}{}", os_tag, native_str);
}
}
try stdout.write("\n");
try stdout.write("Environments:\n");
{
comptime var i: usize = 0;
inline while (i < @memberCount(builtin.Environ)) : (i += 1) {
comptime const environ_tag = @memberName(builtin.Environ, i);
// NOTE: Cannot use empty string, see #918.
comptime const native_str = if (comptime mem.eql(u8, environ_tag, @tagName(builtin.environ))) " (native)\n" else "\n";
try stdout.print(" {}{}", environ_tag, native_str);
}
}
}
fn cmdVersion(allocator: *Allocator, args: []const []const u8) !void {
try stdout.print("{}\n", std.cstr.toSliceConst(c.ZIG_VERSION_STRING));
}
const args_test_spec = []Flag{Flag.Bool("--help")};
fn cmdHelp(allocator: *Allocator, args: []const []const u8) !void {
try stdout.write(usage);
}
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.
\\ * Together we serve end users.
\\
\\
;
fn cmdZen(allocator: *Allocator, args: []const []const u8) !void {
try stdout.write(info_zen);
}
const usage_internal =
\\usage: zig internal [subcommand]
\\
\\Sub-Commands:
\\ build-info Print static compiler build-info
\\
\\
;
fn cmdInternal(allocator: *Allocator, args: []const []const u8) !void {
if (args.len == 0) {
try stderr.write(usage_internal);
os.exit(1);
}
const sub_commands = []Command{Command{
.name = "build-info",
.exec = cmdInternalBuildInfo,
}};
for (sub_commands) |sub_command| {
if (mem.eql(u8, sub_command.name, args[0])) {
try sub_command.exec(allocator, args[1..]);
return;
}
}
try stderr.print("unknown sub command: {}\n\n", args[0]);
try stderr.write(usage_internal);
}
fn cmdInternalBuildInfo(allocator: *Allocator, args: []const []const u8) !void {
try stdout.print(
\\ZIG_CMAKE_BINARY_DIR {}
\\ZIG_CXX_COMPILER {}
\\ZIG_LLVM_CONFIG_EXE {}
\\ZIG_LLD_INCLUDE_PATH {}
\\ZIG_LLD_LIBRARIES {}
\\ZIG_STD_FILES {}
\\ZIG_C_HEADER_FILES {}
\\ZIG_DIA_GUIDS_LIB {}
\\
,
std.cstr.toSliceConst(c.ZIG_CMAKE_BINARY_DIR),
std.cstr.toSliceConst(c.ZIG_CXX_COMPILER),
std.cstr.toSliceConst(c.ZIG_LLVM_CONFIG_EXE),
std.cstr.toSliceConst(c.ZIG_LLD_INCLUDE_PATH),
std.cstr.toSliceConst(c.ZIG_LLD_LIBRARIES),
std.cstr.toSliceConst(c.ZIG_STD_FILES),
std.cstr.toSliceConst(c.ZIG_C_HEADER_FILES),
std.cstr.toSliceConst(c.ZIG_DIA_GUIDS_LIB),
);
}
const CliPkg = struct {
name: []const u8,
path: []const u8,
children: ArrayList(*CliPkg),
parent: ?*CliPkg,
pub fn init(allocator: *mem.Allocator, name: []const u8, path: []const u8, parent: ?*CliPkg) !*CliPkg {
var pkg = try allocator.create(CliPkg{
.name = name,
.path = path,
.children = ArrayList(*CliPkg).init(allocator),
.parent = parent,
});
return pkg;
}
pub fn deinit(self: *CliPkg) void {
for (self.children.toSliceConst()) |child| {
child.deinit();
}
self.children.deinit();
}
}; | src-self-hosted/main.zig |
const std = @import("std");
const debug = std.debug;
const fmt = std.fmt;
const width = 1000;
const height = 1000;
const Claim = struct {
data: [4]usize,
cursor: usize,
};
fn displayFabric(fabric: []const usize) void {
for (fabric) |i, idx| {
if ((idx % width) == 0) {
std.debug.warn("\n");
}
switch (i) {
0 => std.debug.warn("."),
1 => std.debug.warn("{}", idx),
else => std.debug.warn("X"),
}
}
}
fn parseInput(allocator: *std.mem.Allocator, input: []const u8) !std.ArrayList(Claim) {
var claims = std.ArrayList(Claim).init(allocator);
var i: usize = 0;
var start: usize = 0;
var claim = Claim {
.data = []usize{0} ** 4,
.cursor = 0,
};
while (i < input.len) : (i += 1) {
switch (input[i]) {
'#' => {
while (input[i] != '@') : (i += 1) {}
},
'0'...'9' => {
start = i;
while (
input[i + 1] >= '0' and
input[i + 1] <= '9'
) : (i += 1) {}
claim.data[claim.cursor] = try fmt.parseInt(usize, input[start..i + 1], 10);
claim.cursor += 1;
},
'\n' => {
try claims.append(claim);
claim = Claim {
.data = []usize{0} ** 4,
.cursor = 0,
};
},
else => {},
}
}
return claims;
}
test "aoc3 -- pt. 1" {
const input_file = @embedFile("../input/aoc3.txt")[0..];
var fabric = []usize{0} ** (width * height);
defer std.debug.warn(" ");
std.debug.warn(" ");
var direct_allocator = std.heap.DirectAllocator.init();
defer direct_allocator.deinit();
const claims = try parseInput(&direct_allocator.allocator, input_file);
defer claims.deinit();
var overlap: usize = 0;
for (claims.toSliceConst()) |c, idx| {
var y = (c.data[1]);
while (y < c.data[3] + c.data[1]) : (y += 1) {
var x0 = (y * width) + c.data[0];
for (fabric[x0..(x0 + c.data[2])]) |*si| {
if (si.* == 1) {
overlap += 1;
}
si.* += 1;
}
}
}
std.debug.warn("{}", overlap);
}
test "aoc3 -- pt. 2" {
const input_file = @embedFile("../input/aoc3.txt")[0..];
var fabric = []usize{0} ** (width * height);
defer std.debug.warn(" ");
std.debug.warn(" ");
var direct_allocator = std.heap.DirectAllocator.init();
defer direct_allocator.deinit();
const claims = try parseInput(&direct_allocator.allocator, input_file);
defer claims.deinit();
var unique = std.AutoHashMap(usize, usize).init(&direct_allocator.allocator);
defer unique.deinit();
for (claims.toSlice()) |*c, id| {
var y = (c.data[1]);
c.*.cursor = id;
while (y < c.data[3] + c.data[1]) : (y += 1) {
var x0 = (y * width) + c.data[0];
for (fabric[x0..(x0 + c.data[2])]) |*si, idx| {
si.* += 1;
switch (si.*) {
1 => _ = try unique.put(x0 + idx, id),
else => _ = unique.remove(x0 + idx),
}
}
}
}
std.debug.warn("{}", unique.count());
// for (unique.toSliceConst()) |claim| {
// std.debug.warn("{}", c);
// }
} | src/aoc3.zig |
const combn = @import("../combn/combn.zig");
const Result = combn.Result;
const Parser = combn.Parser;
const Error = combn.Error;
const Context = combn.Context;
const ParserPosKey = combn.ParserPosKey;
const ParserPath = combn.ParserPath;
const ParserNodeName = combn.ParserNodeName;
const String = @import("String.zig");
const Compilation = @import("Compilation.zig");
const CompilerContext = @import("CompilerContext.zig");
const std = @import("std");
const testing = std.testing;
const mem = std.mem;
/// Matches the identifier `input` string.
///
/// The `input` string must remain alive for as long as the `Identifier` parser will be used.
pub const Identifier = struct {
parser: Parser(*CompilerContext, ?Compilation) = Parser(*CompilerContext, ?Compilation).init(parse, nodeName, null),
const Self = @This();
pub fn init() Self {
return Self{};
}
pub fn nodeName(parser: *const Parser(*CompilerContext, ?Compilation), node_name_cache: *std.AutoHashMap(usize, ParserNodeName)) Error!u64 {
const self = @fieldParentPtr(Self, "parser", parser);
var v = std.hash_map.hashString("Identifier");
return v;
}
pub fn parse(parser: *const Parser(*CompilerContext, ?Compilation), in_ctx: *const Context(*CompilerContext, ?Compilation)) callconv(.Async) !void {
const self = @fieldParentPtr(Self, "parser", parser);
var ctx = in_ctx.with({});
defer ctx.results.close();
const src = ctx.src[ctx.offset..];
var offset: usize = 0;
if (src.len == 0) {
try ctx.results.add(Result(?Compilation).initError(ctx.offset, "expected Identifier"));
return;
}
{
var isUpper = src[offset] >= 'A' and src[offset] <= 'Z';
var isLower = src[offset] >= 'a' and src[offset] <= 'z';
if (!isUpper and !isLower) {
try ctx.results.add(Result(?Compilation).initError(ctx.offset + 1, "Identifier must start with a-zA-Z"));
return;
}
}
while (offset < src.len) {
var isDigit = src[offset] >= '0' and src[offset] <= '9';
var isUpper = src[offset] >= 'A' and src[offset] <= 'Z';
var isLower = src[offset] >= 'a' and src[offset] <= 'z';
if (!isDigit and !isUpper and !isLower and src[offset] != '_') {
break;
}
offset += 1;
}
try ctx.results.add(Result(?Compilation).init(ctx.offset + offset, Compilation.initIdentifier(String.init(src[0..offset]))));
}
};
test "identifier" {
nosuspend {
const allocator = testing.allocator;
var compilerContext = try CompilerContext.init(allocator);
defer compilerContext.deinit(allocator);
var ctx = try Context(*CompilerContext, ?Compilation).init(allocator, "Grammar2", compilerContext);
defer ctx.deinit();
var l = Identifier.init();
try l.parser.parse(&ctx);
var sub = ctx.subscribe();
var r1 = sub.next().?;
try testing.expectEqual(@as(usize, 8), r1.offset);
try testing.expectEqualStrings("Grammar2", r1.result.value.?.value.identifier.value);
try testing.expect(sub.next() == null);
}
} | src/dsl/identifier.zig |
const std = @import("std");
const Builder = std.build.Builder;
const packages = @import("deps.zig");
pub fn build(b: *Builder) void {
const mode = b.standardReleaseOptions();
const lib_tests = b.addTest("src/main.zig");
lib_tests.setBuildMode(mode);
if (@hasDecl(packages, "use_submodules")) { // submodules
const package = getPackage(b) catch unreachable;
for (package.dependencies.?) |dep| {
lib_tests.addPackage(dep);
}
} else if (@hasDecl(packages, "addAllTo")) { // zigmod
packages.addAllTo(lib_tests);
} else if (@hasDecl(packages, "pkgs") and @hasDecl(packages.pkgs, "addAllTo")) { // gyro
packages.pkgs.addAllTo(lib_tests);
}
const tests = b.step("test", "Run all library tests");
tests.dependOn(&lib_tests.step);
}
fn getBuildPrefix() []const u8 {
return std.fs.path.dirname(@src().file) orelse ".";
}
fn getDependency(comptime name: []const u8, comptime root: []const u8) !std.build.Pkg {
const path = getBuildPrefix() ++ "/libs/" ++ name ++ "/" ++ root;
// Make sure that the dependency has been checked out.
std.fs.cwd().access(path, .{}) catch |err| switch (err) {
error.FileNotFound => {
std.log.err("zfetch: dependency '{s}' not checked out", .{name});
return err;
},
else => return err,
};
return std.build.Pkg{
.name = name,
.path = .{ .path = path },
};
}
pub fn getPackage(b: *Builder) !std.build.Pkg {
var dependencies = b.allocator.alloc(std.build.Pkg, 4) catch unreachable;
dependencies[0] = try getDependency("iguanaTLS", "src/main.zig");
dependencies[1] = try getDependency("network", "network.zig");
dependencies[2] = try getDependency("uri", "uri.zig");
dependencies[3] = try getDependency("hzzp", "src/main.zig");
return std.build.Pkg{
.name = "zfetch",
.path = .{ .path = getBuildPrefix() ++ "/src/main.zig" },
.dependencies = dependencies,
};
} | build.zig |
const std = @import("std");
const mem = std.mem;
const CaseIgnorable = @This();
allocator: *mem.Allocator,
array: []bool,
lo: u21 = 39,
hi: u21 = 917999,
pub fn init(allocator: *mem.Allocator) !CaseIgnorable {
var instance = CaseIgnorable{
.allocator = allocator,
.array = try allocator.alloc(bool, 917961),
};
mem.set(bool, instance.array, false);
var index: u21 = 0;
instance.array[0] = true;
instance.array[7] = true;
instance.array[19] = true;
instance.array[55] = true;
instance.array[57] = true;
instance.array[129] = true;
instance.array[134] = true;
instance.array[136] = true;
instance.array[141] = true;
instance.array[144] = true;
instance.array[145] = true;
index = 649;
while (index <= 666) : (index += 1) {
instance.array[index] = true;
}
index = 667;
while (index <= 670) : (index += 1) {
instance.array[index] = true;
}
index = 671;
while (index <= 682) : (index += 1) {
instance.array[index] = true;
}
index = 683;
while (index <= 696) : (index += 1) {
instance.array[index] = true;
}
index = 697;
while (index <= 701) : (index += 1) {
instance.array[index] = true;
}
index = 702;
while (index <= 708) : (index += 1) {
instance.array[index] = true;
}
instance.array[709] = true;
instance.array[710] = true;
instance.array[711] = true;
index = 712;
while (index <= 728) : (index += 1) {
instance.array[index] = true;
}
index = 729;
while (index <= 840) : (index += 1) {
instance.array[index] = true;
}
instance.array[845] = true;
instance.array[846] = true;
instance.array[851] = true;
index = 861;
while (index <= 862) : (index += 1) {
instance.array[index] = true;
}
instance.array[864] = true;
index = 1116;
while (index <= 1120) : (index += 1) {
instance.array[index] = true;
}
index = 1121;
while (index <= 1122) : (index += 1) {
instance.array[index] = true;
}
instance.array[1330] = true;
instance.array[1336] = true;
index = 1386;
while (index <= 1430) : (index += 1) {
instance.array[index] = true;
}
instance.array[1432] = true;
index = 1434;
while (index <= 1435) : (index += 1) {
instance.array[index] = true;
}
index = 1437;
while (index <= 1438) : (index += 1) {
instance.array[index] = true;
}
instance.array[1440] = true;
instance.array[1485] = true;
index = 1497;
while (index <= 1502) : (index += 1) {
instance.array[index] = true;
}
index = 1513;
while (index <= 1523) : (index += 1) {
instance.array[index] = true;
}
instance.array[1525] = true;
instance.array[1561] = true;
index = 1572;
while (index <= 1592) : (index += 1) {
instance.array[index] = true;
}
instance.array[1609] = true;
index = 1711;
while (index <= 1717) : (index += 1) {
instance.array[index] = true;
}
instance.array[1718] = true;
index = 1720;
while (index <= 1725) : (index += 1) {
instance.array[index] = true;
}
index = 1726;
while (index <= 1727) : (index += 1) {
instance.array[index] = true;
}
index = 1728;
while (index <= 1729) : (index += 1) {
instance.array[index] = true;
}
index = 1731;
while (index <= 1734) : (index += 1) {
instance.array[index] = true;
}
instance.array[1768] = true;
instance.array[1770] = true;
index = 1801;
while (index <= 1827) : (index += 1) {
instance.array[index] = true;
}
index = 1919;
while (index <= 1929) : (index += 1) {
instance.array[index] = true;
}
index = 1988;
while (index <= 1996) : (index += 1) {
instance.array[index] = true;
}
index = 1997;
while (index <= 1998) : (index += 1) {
instance.array[index] = true;
}
instance.array[2003] = true;
instance.array[2006] = true;
index = 2031;
while (index <= 2034) : (index += 1) {
instance.array[index] = true;
}
instance.array[2035] = true;
index = 2036;
while (index <= 2044) : (index += 1) {
instance.array[index] = true;
}
instance.array[2045] = true;
index = 2046;
while (index <= 2048) : (index += 1) {
instance.array[index] = true;
}
instance.array[2049] = true;
index = 2050;
while (index <= 2054) : (index += 1) {
instance.array[index] = true;
}
index = 2098;
while (index <= 2100) : (index += 1) {
instance.array[index] = true;
}
index = 2220;
while (index <= 2234) : (index += 1) {
instance.array[index] = true;
}
instance.array[2235] = true;
index = 2236;
while (index <= 2267) : (index += 1) {
instance.array[index] = true;
}
instance.array[2323] = true;
instance.array[2325] = true;
index = 2330;
while (index <= 2337) : (index += 1) {
instance.array[index] = true;
}
instance.array[2342] = true;
index = 2346;
while (index <= 2352) : (index += 1) {
instance.array[index] = true;
}
index = 2363;
while (index <= 2364) : (index += 1) {
instance.array[index] = true;
}
instance.array[2378] = true;
instance.array[2394] = true;
instance.array[2453] = true;
index = 2458;
while (index <= 2461) : (index += 1) {
instance.array[index] = true;
}
instance.array[2470] = true;
index = 2491;
while (index <= 2492) : (index += 1) {
instance.array[index] = true;
}
instance.array[2519] = true;
index = 2522;
while (index <= 2523) : (index += 1) {
instance.array[index] = true;
}
instance.array[2581] = true;
index = 2586;
while (index <= 2587) : (index += 1) {
instance.array[index] = true;
}
index = 2592;
while (index <= 2593) : (index += 1) {
instance.array[index] = true;
}
index = 2596;
while (index <= 2598) : (index += 1) {
instance.array[index] = true;
}
instance.array[2602] = true;
index = 2633;
while (index <= 2634) : (index += 1) {
instance.array[index] = true;
}
instance.array[2638] = true;
index = 2650;
while (index <= 2651) : (index += 1) {
instance.array[index] = true;
}
instance.array[2709] = true;
index = 2714;
while (index <= 2718) : (index += 1) {
instance.array[index] = true;
}
index = 2720;
while (index <= 2721) : (index += 1) {
instance.array[index] = true;
}
instance.array[2726] = true;
index = 2747;
while (index <= 2748) : (index += 1) {
instance.array[index] = true;
}
index = 2771;
while (index <= 2776) : (index += 1) {
instance.array[index] = true;
}
instance.array[2778] = true;
instance.array[2837] = true;
instance.array[2840] = true;
index = 2842;
while (index <= 2845) : (index += 1) {
instance.array[index] = true;
}
instance.array[2854] = true;
index = 2862;
while (index <= 2863) : (index += 1) {
instance.array[index] = true;
}
index = 2875;
while (index <= 2876) : (index += 1) {
instance.array[index] = true;
}
instance.array[2907] = true;
instance.array[2969] = true;
instance.array[2982] = true;
instance.array[3033] = true;
instance.array[3037] = true;
index = 3095;
while (index <= 3097) : (index += 1) {
instance.array[index] = true;
}
index = 3103;
while (index <= 3105) : (index += 1) {
instance.array[index] = true;
}
index = 3107;
while (index <= 3110) : (index += 1) {
instance.array[index] = true;
}
index = 3118;
while (index <= 3119) : (index += 1) {
instance.array[index] = true;
}
index = 3131;
while (index <= 3132) : (index += 1) {
instance.array[index] = true;
}
instance.array[3162] = true;
instance.array[3221] = true;
instance.array[3224] = true;
instance.array[3231] = true;
index = 3237;
while (index <= 3238) : (index += 1) {
instance.array[index] = true;
}
index = 3259;
while (index <= 3260) : (index += 1) {
instance.array[index] = true;
}
index = 3289;
while (index <= 3290) : (index += 1) {
instance.array[index] = true;
}
index = 3348;
while (index <= 3349) : (index += 1) {
instance.array[index] = true;
}
index = 3354;
while (index <= 3357) : (index += 1) {
instance.array[index] = true;
}
instance.array[3366] = true;
index = 3387;
while (index <= 3388) : (index += 1) {
instance.array[index] = true;
}
instance.array[3418] = true;
instance.array[3491] = true;
index = 3499;
while (index <= 3501) : (index += 1) {
instance.array[index] = true;
}
instance.array[3503] = true;
instance.array[3594] = true;
index = 3597;
while (index <= 3603) : (index += 1) {
instance.array[index] = true;
}
instance.array[3615] = true;
index = 3616;
while (index <= 3623) : (index += 1) {
instance.array[index] = true;
}
instance.array[3722] = true;
index = 3725;
while (index <= 3733) : (index += 1) {
instance.array[index] = true;
}
instance.array[3743] = true;
index = 3745;
while (index <= 3750) : (index += 1) {
instance.array[index] = true;
}
index = 3825;
while (index <= 3826) : (index += 1) {
instance.array[index] = true;
}
instance.array[3854] = true;
instance.array[3856] = true;
instance.array[3858] = true;
index = 3914;
while (index <= 3927) : (index += 1) {
instance.array[index] = true;
}
index = 3929;
while (index <= 3933) : (index += 1) {
instance.array[index] = true;
}
index = 3935;
while (index <= 3936) : (index += 1) {
instance.array[index] = true;
}
index = 3942;
while (index <= 3952) : (index += 1) {
instance.array[index] = true;
}
index = 3954;
while (index <= 3989) : (index += 1) {
instance.array[index] = true;
}
instance.array[3999] = true;
index = 4102;
while (index <= 4105) : (index += 1) {
instance.array[index] = true;
}
index = 4107;
while (index <= 4112) : (index += 1) {
instance.array[index] = true;
}
index = 4114;
while (index <= 4115) : (index += 1) {
instance.array[index] = true;
}
index = 4118;
while (index <= 4119) : (index += 1) {
instance.array[index] = true;
}
index = 4145;
while (index <= 4146) : (index += 1) {
instance.array[index] = true;
}
index = 4151;
while (index <= 4153) : (index += 1) {
instance.array[index] = true;
}
index = 4170;
while (index <= 4173) : (index += 1) {
instance.array[index] = true;
}
instance.array[4187] = true;
index = 4190;
while (index <= 4191) : (index += 1) {
instance.array[index] = true;
}
instance.array[4198] = true;
instance.array[4214] = true;
instance.array[4309] = true;
index = 4918;
while (index <= 4920) : (index += 1) {
instance.array[index] = true;
}
index = 5867;
while (index <= 5869) : (index += 1) {
instance.array[index] = true;
}
index = 5899;
while (index <= 5901) : (index += 1) {
instance.array[index] = true;
}
index = 5931;
while (index <= 5932) : (index += 1) {
instance.array[index] = true;
}
index = 5963;
while (index <= 5964) : (index += 1) {
instance.array[index] = true;
}
index = 6029;
while (index <= 6030) : (index += 1) {
instance.array[index] = true;
}
index = 6032;
while (index <= 6038) : (index += 1) {
instance.array[index] = true;
}
instance.array[6047] = true;
index = 6050;
while (index <= 6060) : (index += 1) {
instance.array[index] = true;
}
instance.array[6064] = true;
instance.array[6070] = true;
index = 6116;
while (index <= 6118) : (index += 1) {
instance.array[index] = true;
}
instance.array[6119] = true;
instance.array[6172] = true;
index = 6238;
while (index <= 6239) : (index += 1) {
instance.array[index] = true;
}
instance.array[6274] = true;
index = 6393;
while (index <= 6395) : (index += 1) {
instance.array[index] = true;
}
index = 6400;
while (index <= 6401) : (index += 1) {
instance.array[index] = true;
}
instance.array[6411] = true;
index = 6418;
while (index <= 6420) : (index += 1) {
instance.array[index] = true;
}
index = 6640;
while (index <= 6641) : (index += 1) {
instance.array[index] = true;
}
instance.array[6644] = true;
instance.array[6703] = true;
index = 6705;
while (index <= 6711) : (index += 1) {
instance.array[index] = true;
}
instance.array[6713] = true;
instance.array[6715] = true;
index = 6718;
while (index <= 6725) : (index += 1) {
instance.array[index] = true;
}
index = 6732;
while (index <= 6741) : (index += 1) {
instance.array[index] = true;
}
instance.array[6744] = true;
instance.array[6784] = true;
index = 6793;
while (index <= 6806) : (index += 1) {
instance.array[index] = true;
}
instance.array[6807] = true;
index = 6808;
while (index <= 6809) : (index += 1) {
instance.array[index] = true;
}
index = 6873;
while (index <= 6876) : (index += 1) {
instance.array[index] = true;
}
instance.array[6925] = true;
index = 6927;
while (index <= 6931) : (index += 1) {
instance.array[index] = true;
}
instance.array[6933] = true;
instance.array[6939] = true;
index = 6980;
while (index <= 6988) : (index += 1) {
instance.array[index] = true;
}
index = 7001;
while (index <= 7002) : (index += 1) {
instance.array[index] = true;
}
index = 7035;
while (index <= 7038) : (index += 1) {
instance.array[index] = true;
}
index = 7041;
while (index <= 7042) : (index += 1) {
instance.array[index] = true;
}
index = 7044;
while (index <= 7046) : (index += 1) {
instance.array[index] = true;
}
instance.array[7103] = true;
index = 7105;
while (index <= 7106) : (index += 1) {
instance.array[index] = true;
}
instance.array[7110] = true;
index = 7112;
while (index <= 7114) : (index += 1) {
instance.array[index] = true;
}
index = 7173;
while (index <= 7180) : (index += 1) {
instance.array[index] = true;
}
index = 7183;
while (index <= 7184) : (index += 1) {
instance.array[index] = true;
}
index = 7249;
while (index <= 7254) : (index += 1) {
instance.array[index] = true;
}
index = 7337;
while (index <= 7339) : (index += 1) {
instance.array[index] = true;
}
index = 7341;
while (index <= 7353) : (index += 1) {
instance.array[index] = true;
}
index = 7355;
while (index <= 7361) : (index += 1) {
instance.array[index] = true;
}
instance.array[7366] = true;
instance.array[7373] = true;
index = 7377;
while (index <= 7378) : (index += 1) {
instance.array[index] = true;
}
index = 7429;
while (index <= 7491) : (index += 1) {
instance.array[index] = true;
}
instance.array[7505] = true;
index = 7540;
while (index <= 7576) : (index += 1) {
instance.array[index] = true;
}
index = 7577;
while (index <= 7634) : (index += 1) {
instance.array[index] = true;
}
index = 7636;
while (index <= 7640) : (index += 1) {
instance.array[index] = true;
}
instance.array[8086] = true;
index = 8088;
while (index <= 8090) : (index += 1) {
instance.array[index] = true;
}
index = 8102;
while (index <= 8104) : (index += 1) {
instance.array[index] = true;
}
index = 8118;
while (index <= 8120) : (index += 1) {
instance.array[index] = true;
}
index = 8134;
while (index <= 8136) : (index += 1) {
instance.array[index] = true;
}
index = 8150;
while (index <= 8151) : (index += 1) {
instance.array[index] = true;
}
index = 8164;
while (index <= 8168) : (index += 1) {
instance.array[index] = true;
}
instance.array[8177] = true;
instance.array[8178] = true;
instance.array[8189] = true;
instance.array[8192] = true;
index = 8195;
while (index <= 8199) : (index += 1) {
instance.array[index] = true;
}
index = 8249;
while (index <= 8253) : (index += 1) {
instance.array[index] = true;
}
index = 8255;
while (index <= 8264) : (index += 1) {
instance.array[index] = true;
}
instance.array[8266] = true;
instance.array[8280] = true;
index = 8297;
while (index <= 8309) : (index += 1) {
instance.array[index] = true;
}
index = 8361;
while (index <= 8373) : (index += 1) {
instance.array[index] = true;
}
index = 8374;
while (index <= 8377) : (index += 1) {
instance.array[index] = true;
}
instance.array[8378] = true;
index = 8379;
while (index <= 8381) : (index += 1) {
instance.array[index] = true;
}
index = 8382;
while (index <= 8393) : (index += 1) {
instance.array[index] = true;
}
index = 11349;
while (index <= 11350) : (index += 1) {
instance.array[index] = true;
}
index = 11464;
while (index <= 11466) : (index += 1) {
instance.array[index] = true;
}
instance.array[11592] = true;
instance.array[11608] = true;
index = 11705;
while (index <= 11736) : (index += 1) {
instance.array[index] = true;
}
instance.array[11784] = true;
instance.array[12254] = true;
index = 12291;
while (index <= 12294) : (index += 1) {
instance.array[index] = true;
}
index = 12298;
while (index <= 12302) : (index += 1) {
instance.array[index] = true;
}
instance.array[12308] = true;
index = 12402;
while (index <= 12403) : (index += 1) {
instance.array[index] = true;
}
index = 12404;
while (index <= 12405) : (index += 1) {
instance.array[index] = true;
}
index = 12406;
while (index <= 12407) : (index += 1) {
instance.array[index] = true;
}
index = 12501;
while (index <= 12503) : (index += 1) {
instance.array[index] = true;
}
instance.array[40942] = true;
index = 42193;
while (index <= 42198) : (index += 1) {
instance.array[index] = true;
}
instance.array[42469] = true;
instance.array[42568] = true;
index = 42569;
while (index <= 42571) : (index += 1) {
instance.array[index] = true;
}
index = 42573;
while (index <= 42582) : (index += 1) {
instance.array[index] = true;
}
instance.array[42584] = true;
index = 42613;
while (index <= 42614) : (index += 1) {
instance.array[index] = true;
}
index = 42615;
while (index <= 42616) : (index += 1) {
instance.array[index] = true;
}
index = 42697;
while (index <= 42698) : (index += 1) {
instance.array[index] = true;
}
index = 42713;
while (index <= 42735) : (index += 1) {
instance.array[index] = true;
}
index = 42736;
while (index <= 42744) : (index += 1) {
instance.array[index] = true;
}
index = 42745;
while (index <= 42746) : (index += 1) {
instance.array[index] = true;
}
instance.array[42825] = true;
instance.array[42849] = true;
index = 42850;
while (index <= 42851) : (index += 1) {
instance.array[index] = true;
}
index = 42961;
while (index <= 42962) : (index += 1) {
instance.array[index] = true;
}
instance.array[42971] = true;
instance.array[42975] = true;
instance.array[42980] = true;
index = 43006;
while (index <= 43007) : (index += 1) {
instance.array[index] = true;
}
instance.array[43013] = true;
index = 43165;
while (index <= 43166) : (index += 1) {
instance.array[index] = true;
}
index = 43193;
while (index <= 43210) : (index += 1) {
instance.array[index] = true;
}
instance.array[43224] = true;
index = 43263;
while (index <= 43270) : (index += 1) {
instance.array[index] = true;
}
index = 43296;
while (index <= 43306) : (index += 1) {
instance.array[index] = true;
}
index = 43353;
while (index <= 43355) : (index += 1) {
instance.array[index] = true;
}
instance.array[43404] = true;
index = 43407;
while (index <= 43410) : (index += 1) {
instance.array[index] = true;
}
index = 43413;
while (index <= 43414) : (index += 1) {
instance.array[index] = true;
}
instance.array[43432] = true;
instance.array[43454] = true;
instance.array[43455] = true;
index = 43522;
while (index <= 43527) : (index += 1) {
instance.array[index] = true;
}
index = 43530;
while (index <= 43531) : (index += 1) {
instance.array[index] = true;
}
index = 43534;
while (index <= 43535) : (index += 1) {
instance.array[index] = true;
}
instance.array[43548] = true;
instance.array[43557] = true;
instance.array[43593] = true;
instance.array[43605] = true;
instance.array[43657] = true;
index = 43659;
while (index <= 43661) : (index += 1) {
instance.array[index] = true;
}
index = 43664;
while (index <= 43665) : (index += 1) {
instance.array[index] = true;
}
index = 43671;
while (index <= 43672) : (index += 1) {
instance.array[index] = true;
}
instance.array[43674] = true;
instance.array[43702] = true;
index = 43717;
while (index <= 43718) : (index += 1) {
instance.array[index] = true;
}
index = 43724;
while (index <= 43725) : (index += 1) {
instance.array[index] = true;
}
instance.array[43727] = true;
instance.array[43828] = true;
index = 43829;
while (index <= 43832) : (index += 1) {
instance.array[index] = true;
}
instance.array[43842] = true;
index = 43843;
while (index <= 43844) : (index += 1) {
instance.array[index] = true;
}
instance.array[43966] = true;
instance.array[43969] = true;
instance.array[43974] = true;
instance.array[64247] = true;
index = 64395;
while (index <= 64410) : (index += 1) {
instance.array[index] = true;
}
index = 64985;
while (index <= 65000) : (index += 1) {
instance.array[index] = true;
}
instance.array[65004] = true;
index = 65017;
while (index <= 65032) : (index += 1) {
instance.array[index] = true;
}
instance.array[65067] = true;
instance.array[65070] = true;
instance.array[65240] = true;
instance.array[65248] = true;
instance.array[65255] = true;
instance.array[65267] = true;
instance.array[65303] = true;
instance.array[65305] = true;
instance.array[65353] = true;
index = 65399;
while (index <= 65400) : (index += 1) {
instance.array[index] = true;
}
instance.array[65468] = true;
index = 65490;
while (index <= 65492) : (index += 1) {
instance.array[index] = true;
}
instance.array[66006] = true;
instance.array[66233] = true;
index = 66383;
while (index <= 66387) : (index += 1) {
instance.array[index] = true;
}
index = 68058;
while (index <= 68060) : (index += 1) {
instance.array[index] = true;
}
index = 68062;
while (index <= 68063) : (index += 1) {
instance.array[index] = true;
}
index = 68069;
while (index <= 68072) : (index += 1) {
instance.array[index] = true;
}
index = 68113;
while (index <= 68115) : (index += 1) {
instance.array[index] = true;
}
instance.array[68120] = true;
index = 68286;
while (index <= 68287) : (index += 1) {
instance.array[index] = true;
}
index = 68861;
while (index <= 68864) : (index += 1) {
instance.array[index] = true;
}
index = 69252;
while (index <= 69253) : (index += 1) {
instance.array[index] = true;
}
index = 69407;
while (index <= 69417) : (index += 1) {
instance.array[index] = true;
}
instance.array[69594] = true;
index = 69649;
while (index <= 69663) : (index += 1) {
instance.array[index] = true;
}
index = 69720;
while (index <= 69722) : (index += 1) {
instance.array[index] = true;
}
index = 69772;
while (index <= 69775) : (index += 1) {
instance.array[index] = true;
}
index = 69778;
while (index <= 69779) : (index += 1) {
instance.array[index] = true;
}
instance.array[69782] = true;
instance.array[69798] = true;
index = 69849;
while (index <= 69851) : (index += 1) {
instance.array[index] = true;
}
index = 69888;
while (index <= 69892) : (index += 1) {
instance.array[index] = true;
}
index = 69894;
while (index <= 69901) : (index += 1) {
instance.array[index] = true;
}
instance.array[69964] = true;
index = 69977;
while (index <= 69978) : (index += 1) {
instance.array[index] = true;
}
index = 70031;
while (index <= 70039) : (index += 1) {
instance.array[index] = true;
}
index = 70050;
while (index <= 70053) : (index += 1) {
instance.array[index] = true;
}
instance.array[70056] = true;
index = 70152;
while (index <= 70154) : (index += 1) {
instance.array[index] = true;
}
instance.array[70157] = true;
index = 70159;
while (index <= 70160) : (index += 1) {
instance.array[index] = true;
}
instance.array[70167] = true;
instance.array[70328] = true;
index = 70332;
while (index <= 70339) : (index += 1) {
instance.array[index] = true;
}
index = 70361;
while (index <= 70362) : (index += 1) {
instance.array[index] = true;
}
index = 70420;
while (index <= 70421) : (index += 1) {
instance.array[index] = true;
}
instance.array[70425] = true;
index = 70463;
while (index <= 70469) : (index += 1) {
instance.array[index] = true;
}
index = 70473;
while (index <= 70477) : (index += 1) {
instance.array[index] = true;
}
index = 70673;
while (index <= 70680) : (index += 1) {
instance.array[index] = true;
}
index = 70683;
while (index <= 70685) : (index += 1) {
instance.array[index] = true;
}
instance.array[70687] = true;
instance.array[70711] = true;
index = 70796;
while (index <= 70801) : (index += 1) {
instance.array[index] = true;
}
instance.array[70803] = true;
index = 70808;
while (index <= 70809) : (index += 1) {
instance.array[index] = true;
}
index = 70811;
while (index <= 70812) : (index += 1) {
instance.array[index] = true;
}
index = 71051;
while (index <= 71054) : (index += 1) {
instance.array[index] = true;
}
index = 71061;
while (index <= 71062) : (index += 1) {
instance.array[index] = true;
}
index = 71064;
while (index <= 71065) : (index += 1) {
instance.array[index] = true;
}
index = 71093;
while (index <= 71094) : (index += 1) {
instance.array[index] = true;
}
index = 71180;
while (index <= 71187) : (index += 1) {
instance.array[index] = true;
}
instance.array[71190] = true;
index = 71192;
while (index <= 71193) : (index += 1) {
instance.array[index] = true;
}
instance.array[71300] = true;
instance.array[71302] = true;
index = 71305;
while (index <= 71310) : (index += 1) {
instance.array[index] = true;
}
instance.array[71312] = true;
index = 71414;
while (index <= 71416) : (index += 1) {
instance.array[index] = true;
}
index = 71419;
while (index <= 71422) : (index += 1) {
instance.array[index] = true;
}
index = 71424;
while (index <= 71428) : (index += 1) {
instance.array[index] = true;
}
index = 71688;
while (index <= 71696) : (index += 1) {
instance.array[index] = true;
}
index = 71698;
while (index <= 71699) : (index += 1) {
instance.array[index] = true;
}
index = 71956;
while (index <= 71957) : (index += 1) {
instance.array[index] = true;
}
instance.array[71959] = true;
instance.array[71964] = true;
index = 72109;
while (index <= 72112) : (index += 1) {
instance.array[index] = true;
}
index = 72115;
while (index <= 72116) : (index += 1) {
instance.array[index] = true;
}
instance.array[72121] = true;
index = 72154;
while (index <= 72163) : (index += 1) {
instance.array[index] = true;
}
index = 72204;
while (index <= 72209) : (index += 1) {
instance.array[index] = true;
}
index = 72212;
while (index <= 72215) : (index += 1) {
instance.array[index] = true;
}
instance.array[72224] = true;
index = 72234;
while (index <= 72239) : (index += 1) {
instance.array[index] = true;
}
index = 72242;
while (index <= 72244) : (index += 1) {
instance.array[index] = true;
}
index = 72291;
while (index <= 72303) : (index += 1) {
instance.array[index] = true;
}
index = 72305;
while (index <= 72306) : (index += 1) {
instance.array[index] = true;
}
index = 72713;
while (index <= 72719) : (index += 1) {
instance.array[index] = true;
}
index = 72721;
while (index <= 72726) : (index += 1) {
instance.array[index] = true;
}
instance.array[72728] = true;
index = 72811;
while (index <= 72832) : (index += 1) {
instance.array[index] = true;
}
index = 72835;
while (index <= 72841) : (index += 1) {
instance.array[index] = true;
}
index = 72843;
while (index <= 72844) : (index += 1) {
instance.array[index] = true;
}
index = 72846;
while (index <= 72847) : (index += 1) {
instance.array[index] = true;
}
index = 72970;
while (index <= 72975) : (index += 1) {
instance.array[index] = true;
}
instance.array[72979] = true;
index = 72981;
while (index <= 72982) : (index += 1) {
instance.array[index] = true;
}
index = 72984;
while (index <= 72990) : (index += 1) {
instance.array[index] = true;
}
instance.array[72992] = true;
index = 73065;
while (index <= 73066) : (index += 1) {
instance.array[index] = true;
}
instance.array[73070] = true;
instance.array[73072] = true;
index = 73420;
while (index <= 73421) : (index += 1) {
instance.array[index] = true;
}
index = 78857;
while (index <= 78865) : (index += 1) {
instance.array[index] = true;
}
index = 92873;
while (index <= 92877) : (index += 1) {
instance.array[index] = true;
}
index = 92937;
while (index <= 92943) : (index += 1) {
instance.array[index] = true;
}
index = 92953;
while (index <= 92956) : (index += 1) {
instance.array[index] = true;
}
instance.array[93992] = true;
index = 94056;
while (index <= 94059) : (index += 1) {
instance.array[index] = true;
}
index = 94060;
while (index <= 94072) : (index += 1) {
instance.array[index] = true;
}
index = 94137;
while (index <= 94138) : (index += 1) {
instance.array[index] = true;
}
instance.array[94140] = true;
instance.array[94141] = true;
index = 113782;
while (index <= 113783) : (index += 1) {
instance.array[index] = true;
}
index = 113785;
while (index <= 113788) : (index += 1) {
instance.array[index] = true;
}
index = 119104;
while (index <= 119106) : (index += 1) {
instance.array[index] = true;
}
index = 119116;
while (index <= 119123) : (index += 1) {
instance.array[index] = true;
}
index = 119124;
while (index <= 119131) : (index += 1) {
instance.array[index] = true;
}
index = 119134;
while (index <= 119140) : (index += 1) {
instance.array[index] = true;
}
index = 119171;
while (index <= 119174) : (index += 1) {
instance.array[index] = true;
}
index = 119323;
while (index <= 119325) : (index += 1) {
instance.array[index] = true;
}
index = 121305;
while (index <= 121359) : (index += 1) {
instance.array[index] = true;
}
index = 121364;
while (index <= 121413) : (index += 1) {
instance.array[index] = true;
}
instance.array[121422] = true;
instance.array[121437] = true;
index = 121460;
while (index <= 121464) : (index += 1) {
instance.array[index] = true;
}
index = 121466;
while (index <= 121480) : (index += 1) {
instance.array[index] = true;
}
index = 122841;
while (index <= 122847) : (index += 1) {
instance.array[index] = true;
}
index = 122849;
while (index <= 122865) : (index += 1) {
instance.array[index] = true;
}
index = 122868;
while (index <= 122874) : (index += 1) {
instance.array[index] = true;
}
index = 122876;
while (index <= 122877) : (index += 1) {
instance.array[index] = true;
}
index = 122879;
while (index <= 122883) : (index += 1) {
instance.array[index] = true;
}
index = 123145;
while (index <= 123151) : (index += 1) {
instance.array[index] = true;
}
index = 123152;
while (index <= 123158) : (index += 1) {
instance.array[index] = true;
}
index = 123589;
while (index <= 123592) : (index += 1) {
instance.array[index] = true;
}
index = 125097;
while (index <= 125103) : (index += 1) {
instance.array[index] = true;
}
index = 125213;
while (index <= 125219) : (index += 1) {
instance.array[index] = true;
}
instance.array[125220] = true;
index = 127956;
while (index <= 127960) : (index += 1) {
instance.array[index] = true;
}
instance.array[917466] = true;
index = 917497;
while (index <= 917592) : (index += 1) {
instance.array[index] = true;
}
index = 917721;
while (index <= 917960) : (index += 1) {
instance.array[index] = true;
}
// Placeholder: 0. Struct name, 1. Code point kind
return instance;
}
pub fn deinit(self: *CaseIgnorable) void {
self.allocator.free(self.array);
}
// isCaseIgnorable checks if cp is of the kind Case_Ignorable.
pub fn isCaseIgnorable(self: CaseIgnorable, 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/DerivedCoreProperties/CaseIgnorable.zig |
const std = @import("std");
const assert = std.debug.assert;
const testing = std.testing;
const Allocator = std.mem.Allocator;
const array_map = @This();
pub fn AutoArrayMap(comptime K: type, comptime V: type) type {
return ArrayMap(K, V, std.hash_map.AutoContext(K), true);
}
pub fn ArrayMap(
comptime K: type,
comptime V: type,
comptime Context: type,
comptime sorted: bool,
) type {
return struct {
unmanaged: Unmanaged,
allocator: Allocator,
pub const Unmanaged = ArrayMapUnmanaged(K, V, Context, sorted);
pub const Entry = Unmanaged.Entry;
pub const GetOrPutResult = Unmanaged.GetOrPutResult;
const Self = @This();
pub fn init(allocator: Allocator) Self {
return .{
.unmanaged = .{},
.allocator = allocator,
};
}
pub fn deinit(self: *Self) void {
self.unmanaged.deinit(self.allocator);
self.* = undefined;
}
pub fn clearRetainingCapacity(self: *Self) void {
return self.unmanaged.clearRetainingCapacity();
}
pub fn clearAndFree(self: *Self) void {
return self.unmanaged.clearAndFree(self.allocator);
}
pub fn count(self: Self) usize {
return self.unmanaged.count();
}
/// Modify the array so that it can hold at least `new_capacity` items.
/// Invalidates pointers if additional memory is needed.
pub fn ensureTotalCapacity(self: *Self, new_capacity: usize) !void {
return self.unmanaged.ensureTotalCapacity(self.allocator, new_capacity);
}
/// Modify the array so that it can hold at least `additional_count` **more** items.
/// Invalidates pointers if additional memory is needed.
pub fn ensureUnusedCapacity(self: *Self, additional_count: usize) !void {
return self.unmanaged.ensureUnusedCapacity(self.allocator, additional_count);
}
/// Returns the number of total elements which may be present before it is
/// no longer guaranteed that no allocations will be performed.
pub fn capacity(self: *Self) usize {
return self.unmanaged.capacity();
}
/// Clobbers any existing data. To detect if a put would clobber
/// existing data, see `getOrPut`.
pub fn put(self: *Self, key: K, value: V) !void {
return self.unmanaged.put(self.allocator, key, value);
}
/// Inserts a key-value pair into the map, asserting that no previous
/// entry with the same key is already present
pub fn putNoClobber(self: *Self, key: K, value: V) !void {
return self.unmanaged.putNoClobber(self.allocator, key, value);
}
/// Inserts a new `Entry` into the map, returning the previous one, if any.
pub fn fetchPut(self: *Self, key: K, value: V) !?Entry {
return self.unmanaged.fetchPut(self.allocator, key, value);
}
/// Inserts a new `Entry` into the map, returning the previous one, if any.
/// If insertion happuns, asserts there is enough capacity without allocating.
pub fn fetchPutAssumeCapacity(self: *Self, key: K, value: V) ?Entry {
return self.unmanaged.fetchPutAssumeCapacity(key, value);
}
pub fn getEntry(self: Self, key: K) ?*Entry {
return self.unmanaged.getEntry(key);
}
pub fn getIndex(self: Self, key: K) ?usize {
return self.unmanaged.getIndex(key);
}
pub fn get(self: Self, key: K) ?V {
return self.unmanaged.get(key);
}
/// If key exists this function cannot fail.
/// If there is an existing item with `key`, then the result
/// `Entry` pointer points to it, and found_existing is true.
/// Otherwise, puts a new item with undefined value, and
/// the `Entry` pointer points to it. Caller should then initialize
/// the value (but not the key).
pub fn getOrPut(self: *Self, key: K) !GetOrPutResult {
return self.unmanaged.getOrPut(self.allocator, key);
}
pub fn getOrPutValue(self: *Self, key: K, value: V) !*Entry {
return self.unmanaged.getOrPutValue(self.allocator, key, value);
}
pub fn contains(self: Self, key: K) bool {
return self.unmanaged.contains(key);
}
/// If there is an `Entry` with a matching key, it is deleted from
/// the map, and then returned from this function. The entry is
/// removed from the underlying array by swapping it with the last
/// element.
pub fn swapRemove(self: *Self, key: K) ?Entry {
return self.unmanaged.swapRemove(key);
}
/// If there is an `Entry` with a matching key, it is deleted from
/// the map, and then returned from this function. The entry is
/// removed from the underlying array by shifting all elements forward
/// thereby maintaining the current ordering.
pub fn orderedRemove(self: *Self, key: K) ?Entry {
return self.unmanaged.orderedRemove(key);
}
/// Asserts there is an `Entry` with matching key, deletes it from the map
/// by swapping it with the last element, and discards it.
pub fn swapRemoveAssertDiscard(self: *Self, key: K) void {
return self.unmanaged.swapRemoveAssertDiscard(key);
}
/// Asserts there is an `Entry` with matching key, deletes it from the map
/// by by shifting all elements forward thereby maintaining the current ordering.
pub fn orderedRemoveAssertDiscard(self: *Self, key: K) void {
return self.unmanaged.orderedRemoveAssertDiscard(key);
}
pub fn items(self: Self) []Entry {
return self.unmanaged.items();
}
pub fn clone(self: Self) !Self {
var other = try self.unmanaged.clone(self.allocator);
return other.promote(self.allocator);
}
/// Shrinks the underlying `Entry` array to `new_len` elements.
/// Keeps capacity the same.
pub fn shrinkRetainingCapacity(self: *Self, new_len: usize) void {
return self.unmanaged.shrinkRetainingCapacity(new_len);
}
/// Shrinks the underlying `Entry` array to `new_len` element.s
/// Reduces allocated capacity.
pub fn shrinkAndFree(self: *Self, new_len: usize) void {
return self.unmanaged.shrinkAndFree(self.allocator, new_len);
}
/// Removes the last inserted `Entry` in the map and returns it.
pub fn pop(self: *Self) Entry {
return self.unmanaged.pop();
}
};
}
pub fn ArrayMapUnmanaged(
comptime K: type,
comptime V: type,
comptime Context: type,
comptime sorted: bool,
) type {
return struct {
entries: std.ArrayListUnmanaged(Entry) = .{},
ctx: Context = undefined,
pub const Entry = struct {
key: K,
value: V,
};
pub const GetOrPutResult = struct {
entry: *Entry,
found_existing: bool,
index: usize,
};
const Self = @This();
const RemovalType = enum {
swap,
ordered,
};
pub const Managed = ArrayMap(K, V, Context, sorted);
pub fn promote(self: Self, allocator: Allocator) Managed {
return .{
.unmanaged = self,
.allocator = allocator,
};
}
pub fn count(self: Self) usize {
return self.entries.items.len;
}
pub fn deinit(self: *Self, allocator: Allocator) void {
self.entries.deinit(allocator);
self.* = undefined;
}
pub fn clearRetainingCapacity(self: *Self) void {
self.entries.items.len = 0;
}
pub fn clearAndFree(self: *Self, allocator: Allocator) void {
self.entries.shrinkAndFree(allocator, 0);
}
/// Modify the array so that it can hold at least `new_capacity` items.
/// Invalidates pointers if additional memory is needed.
pub fn ensureTotalCapacity(self: *Self, allocator: Allocator, new_capacity: usize) !void {
try self.entries.ensureTotalCapacity(allocator, new_capacity);
}
/// Modify the array so that it can hold at least `additional_count` **more** items.
/// Invalidates pointers if additional memory is needed.
pub fn ensureUnusedCapacity(self: *Self, allocator: Allocator, additional_count: usize) !void {
try self.entries.ensureUnusedCapacity(allocator, additional_count);
}
/// Returns the number of total elements which may be present before it is
/// no longer guaranteed that no allocations will be performed.
pub fn capacity(self: Self) usize {
return self.entries.capacity;
}
/// Clobbers any existing data. To detect if a put would clobber
/// existing data, see `getOrPut`.
pub fn put(self: *Self, allocator: Allocator, key: K, value: V) !void {
const result = try self.getOrPut(allocator, key);
result.entry.value = value;
}
/// Inserts a key-value pair into the map, asserting that no previous
/// entry with the same key is already present
pub fn putNoClobber(self: *Self, allocator: Allocator, key: K, value: V) !void {
const result = try self.getOrPut(allocator, key);
assert(!result.found_existing);
result.entry.value = value;
}
pub fn getOrPut(self: *Self, allocator: Allocator, key: K) !GetOrPutResult {
self.ensureUnusedCapacity(allocator, 1) catch |err| {
// "If key exists this function cannot fail."
const index = self.getIndex(key) orelse return err;
return GetOrPutResult{
.entry = &self.entries.items[index],
.found_existing = true,
.index = index,
};
};
return self.getOrPutAssumeCapacity(key);
}
pub fn getOrPutValue(self: *Self, allocator: Allocator, key: K, value: V) !*Entry {
const res = try self.getOrPut(allocator, key);
if (!res.found_existing)
res.entry.value = value;
return res.entry;
}
pub fn getOrPutAssumeCapacity(self: *Self, key: K) GetOrPutResult {
// comptime verifyContext(@TypeOf(ctx), @TypeOf(key), K, Hash)
for (self.entries.items) |*item, i| {
if (self.ctx.eql(key, item.key)) {
return GetOrPutResult{
.entry = item,
.found_existing = true,
.index = i,
};
}
}
const new_entry = self.entries.addOneAssumeCapacity();
new_entry.* = .{
.key = key,
.value = undefined,
};
if (sorted) {
//const impl = struct {
// fn inner(context: Context, a: Entry, b: Entry) bool {
// return a.key < b.key;
// //return std.sort.asc(K)(self.ctx, a.key, b.key);
// }
//};
// TODO: https://github.com/ziglang/zig/issues/6423
const impl = struct {
fn inner(comptime context: type, a: anytype, b: anytype) bool {
_ = context;
return a.key < b.key;
}
};
std.sort.sort(Entry, self.entries.items, void, impl.inner);
}
return GetOrPutResult{
.entry = new_entry,
.found_existing = false,
.index = self.entries.items.len - 1,
};
}
fn getLessThan(comptime _: type) fn (type, anytype, anytype) bool {
const impl = struct {
fn inner(comptime context: type, a: anytype, b: anytype) bool {
_ = context;
return a.key < b.key;
}
};
return impl.inner;
}
pub fn getEntry(self: Self, key: K) ?*Entry {
const index = self.getIndex(key) orelse return null;
return &self.entries.items[index];
}
pub fn getIndex(self: Self, key: K) ?usize {
// Linear scan.
for (self.entries.items) |*item, i| {
if (self.ctx.eql(key, item.key)) {
return i;
}
}
return null;
}
pub fn get(self: Self, key: K) ?V {
return if (self.getEntry(key)) |entry| entry.value else null;
}
/// Inserts a new `Entry` into the map, returning the previous one, if any.
pub fn fetchPut(self: *Self, allocator: Allocator, key: K, value: V) !?Entry {
const gop = try self.getOrPut(allocator, key);
var result: ?Entry = null;
if (gop.found_existing) {
result = gop.entry.*;
}
gop.entry.value = value;
return result;
}
/// Inserts a new `Entry` into the map, returning the previous one, if any.
/// If insertion happens, asserts there is enough capacity without allocating.
pub fn fetchPutAssumeCapacity(self: *Self, key: K, value: V) ?Entry {
const gop = self.getOrPutAssumeCapacity(key);
var result: ?Entry = null;
if (gop.found_existing) {
result = gop.entry.*;
}
gop.entry.value = value;
return result;
}
pub fn contains(self: Self, key: K) bool {
return self.getEntry(key) != null;
}
/// If there is an `Entry` with a matching key, it is deleted from
/// the map, and then returned from this function. The entry is
/// removed from the underlying array by swapping it with the last
/// element.
pub fn swapRemove(self: *Self, key: K) ?Entry {
return self.removeInternal(key, .swap);
}
/// If there is an `Entry` with a matching key, it is deleted from
/// the map, and then returned from this function. The entry is
/// removed from the underlying array by shifting all elements forward
/// thereby maintaining the current ordering.
pub fn orderedRemove(self: *Self, key: K) ?Entry {
return self.removeInternal(key, .ordered);
}
/// Asserts there is an `Entry` with matching key, deletes it from the map
/// by swapping it with the last element, and discards it.
pub fn swapRemoveAssertDiscard(self: *Self, key: K) void {
assert(self.swapRemove(key) != null);
}
/// Asserts there is an `Entry` with matching key, deletes it from the map
/// by by shifting all elements forward thereby maintaining the current ordering.
pub fn orderedRemoveAssertDiscard(self: *Self, key: K) void {
assert(self.orderedRemove(key) != null);
}
pub fn items(self: Self) []Entry {
return self.entries.items;
}
pub fn clone(self: Self, allocator: Allocator) !Self {
var other: Self = .{};
try other.entries.appendSlice(allocator, self.entries.items);
return other;
}
fn removeInternal(self: *Self, key: K, comptime removal_type: RemovalType) ?Entry {
// Linear scan.
for (self.entries.items) |item, i| {
if (self.ctx.eql(key, item.key)) {
switch (removal_type) {
.swap => return self.entries.swapRemove(i),
.ordered => return self.entries.orderedRemove(i),
}
}
}
return null;
}
/// Shrinks the underlying `Entry` array to `new_len` elements.
/// Keeps capacity the same.
pub fn shrinkRetainingCapacity(self: *Self, new_len: usize) void {
self.entries.shrinkRetainingCapacity(new_len);
}
/// Shrinks the underlying `Entry` array to `new_len` elements.
/// Reduces allocated capacity.
pub fn shrinkAndFree(self: *Self, allocator: Allocator, new_len: usize) void {
self.entries.shrinkAndFree(allocator, new_len);
}
/// Removes the last inserted `Entry` in the map and returns it.
pub fn pop(self: *Self) Entry {
const top = self.entries.pop();
return top;
}
};
}
test "basic array map usage" {
var map = AutoArrayMap(i32, i32).init(std.testing.allocator);
defer map.deinit();
try testing.expect((try map.fetchPut(1, 11)) == null);
try testing.expect((try map.fetchPut(2, 22)) == null);
try testing.expect((try map.fetchPut(3, 33)) == null);
try testing.expect((try map.fetchPut(4, 44)) == null);
try map.putNoClobber(5, 55);
try testing.expect((try map.fetchPut(5, 66)).?.value == 55);
try testing.expect((try map.fetchPut(5, 55)).?.value == 66);
const gop1 = try map.getOrPut(5);
try testing.expect(gop1.found_existing == true);
try testing.expect(gop1.entry.value == 55);
try testing.expect(gop1.index == 4);
gop1.entry.value = 77;
try testing.expect(map.getEntry(5).?.value == 77);
const gop2 = try map.getOrPut(99);
try testing.expect(gop2.found_existing == false);
try testing.expect(gop2.index == 5);
gop2.entry.value = 42;
try testing.expect(map.getEntry(99).?.value == 42);
const gop3 = try map.getOrPutValue(5, 5);
try testing.expect(gop3.value == 77);
const gop4 = try map.getOrPutValue(100, 41);
try testing.expect(gop4.value == 41);
try testing.expect(map.contains(2));
try testing.expect(map.getEntry(2).?.value == 22);
try testing.expect(map.get(2).? == 22);
const rmv1 = map.swapRemove(2);
try testing.expect(rmv1.?.key == 2);
try testing.expect(rmv1.?.value == 22);
try testing.expect(map.swapRemove(2) == null);
try testing.expect(map.getEntry(2) == null);
try testing.expect(map.get(2) == null);
// Since we've used `swapRemove` above, the index of this entry should remain unchanged.
try testing.expect(map.getIndex(100).? == 1);
const gop5 = try map.getOrPut(5);
try testing.expect(gop5.found_existing == true);
try testing.expect(gop5.entry.value == 77);
try testing.expect(gop5.index == 4);
// Whereas, if we do an `orderedRemove`, it should move the index forward one spot.
const rmv2 = map.orderedRemove(100);
try testing.expect(rmv2.?.key == 100);
try testing.expect(rmv2.?.value == 41);
try testing.expect(map.orderedRemove(100) == null);
try testing.expect(map.getEntry(100) == null);
try testing.expect(map.get(100) == null);
const gop6 = try map.getOrPut(5);
try testing.expect(gop6.found_existing == true);
try testing.expect(gop6.entry.value == 77);
try testing.expect(gop6.index == 3);
map.swapRemoveAssertDiscard(3);
}
test "ensure capacity" {
var map = AutoArrayMap(i32, i32).init(std.testing.allocator);
defer map.deinit();
try map.ensureTotalCapacity(20);
const initial_capacity = map.capacity();
try testing.expect(initial_capacity >= 20);
var i: i32 = 0;
while (i < 20) : (i += 1) {
try testing.expect(map.fetchPutAssumeCapacity(i, i + 10) == null);
}
// shouldn't resize from putAssumeCapacity
try testing.expect(initial_capacity == map.capacity());
}
test "clone" {
var original = AutoArrayMap(i32, i32).init(std.testing.allocator);
defer original.deinit();
var i: u8 = 0;
while (i < 10) : (i += 1) {
try original.putNoClobber(i, i * 10);
}
var copy = try original.clone();
defer copy.deinit();
i = 0;
while (i < 10) : (i += 1) {
try testing.expect(copy.get(i).? == i * 10);
}
}
test "shrink" {
var map = AutoArrayMap(i32, i32).init(std.testing.allocator);
defer map.deinit();
const num_entries = 20;
var i: i32 = 0;
while (i < num_entries) : (i += 1)
try testing.expect((try map.fetchPut(i, i * 10)) == null);
try testing.expect(map.count() == num_entries);
// Test `shrinkRetainingCapacity`.
map.shrinkRetainingCapacity(17);
try testing.expect(map.count() == 17);
try testing.expect(map.capacity() == 20);
i = 0;
while (i < num_entries) : (i += 1) {
const gop = try map.getOrPut(i);
if (i < 17) {
try testing.expect(gop.found_existing == true);
try testing.expect(gop.entry.value == i * 10);
} else try testing.expect(gop.found_existing == false);
}
// Test `shrinkAndFree`.
map.shrinkAndFree(15);
try testing.expect(map.count() == 15);
try testing.expect(map.capacity() == 15);
i = 0;
while (i < num_entries) : (i += 1) {
const gop = try map.getOrPut(i);
if (i < 15) {
try testing.expect(gop.found_existing == true);
try testing.expect(gop.entry.value == i * 10);
} else try testing.expect(gop.found_existing == false);
}
}
test "pop" {
var map = AutoArrayMap(i32, i32).init(std.testing.allocator);
defer map.deinit();
try testing.expect((try map.fetchPut(1, 11)) == null);
try testing.expect((try map.fetchPut(2, 22)) == null);
try testing.expect((try map.fetchPut(3, 33)) == null);
try testing.expect((try map.fetchPut(4, 44)) == null);
const pop1 = map.pop();
try testing.expect(pop1.key == 4 and pop1.value == 44);
const pop2 = map.pop();
try testing.expect(pop2.key == 3 and pop2.value == 33);
const pop3 = map.pop();
try testing.expect(pop3.key == 2 and pop3.value == 22);
const pop4 = map.pop();
try testing.expect(pop4.key == 1 and pop4.value == 11);
}
test "items array map" {
var reset_map = AutoArrayMap(i32, i32).init(std.testing.allocator);
defer reset_map.deinit();
// test ensureCapacity with a 0 parameter
try reset_map.ensureTotalCapacity(0);
try reset_map.putNoClobber(0, 11);
try reset_map.putNoClobber(1, 22);
try reset_map.putNoClobber(2, 33);
var keys = [_]i32{
0, 2, 1,
};
var values = [_]i32{
11, 33, 22,
};
var buffer = [_]i32{
0, 0, 0,
};
const first_entry = reset_map.items()[0];
var count: usize = 0;
for (reset_map.items()) |entry| {
buffer[@intCast(usize, entry.key)] = entry.value;
count += 1;
}
try testing.expect(count == 3);
try testing.expect(reset_map.count() == count);
for (buffer) |_, i| {
try testing.expect(buffer[@intCast(usize, keys[i])] == values[i]);
}
count = 0;
for (reset_map.items()) |entry| {
buffer[@intCast(usize, entry.key)] = entry.value;
count += 1;
if (count >= 2) break;
}
for (buffer[0..2]) |_, i| {
try testing.expect(buffer[@intCast(usize, keys[i])] == values[i]);
}
var entry = reset_map.items()[0];
try testing.expect(entry.key == first_entry.key);
try testing.expect(entry.value == first_entry.value);
}
test "capacity" {
var map = AutoArrayMap(i32, i32).init(std.testing.allocator);
defer map.deinit();
try map.put(1, 11);
try map.put(2, 22);
try map.put(3, 33);
try map.put(4, 44);
try testing.expect(map.count() == 4);
const capacity = map.capacity();
try testing.expect(capacity >= map.count());
map.clearRetainingCapacity();
try testing.expect(map.count() == 0);
try testing.expect(map.capacity() == capacity);
map.clearAndFree();
try testing.expect(map.capacity() == 0);
} | src/array_map.zig |
const std = @import("std");
usingnamespace @import("code_runner.zig");
usingnamespace @import("common.zig");
usingnamespace @import("types.zig");
pub const NativeFunctionWrapper = struct {
const Self = @This();
invokeFn: fn (self: *Self, codeRunner: *CodeRunner, callFuncType: *const Type) anyerror!void,
deinitFn: fn (self: *Self) void,
pub fn invoke(self: *Self, codeRunner: *CodeRunner, callFuncType: *const Type) anyerror!void {
try self.invokeFn(self, codeRunner, callFuncType);
}
pub fn deinit(self: *Self) void {
self.deinitFn(self);
}
pub fn init(functionToWrap: anytype, allocator: *std.mem.Allocator) !*NativeFunctionWrapper {
const Wrapper = struct {
const FunctionType = @TypeOf(functionToWrap);
wrapper: NativeFunctionWrapper = .{ .invokeFn = invoke, .deinitFn = deinit },
func: FunctionType,
allocator: *std.mem.Allocator,
pub fn deinit(wrapper: *NativeFunctionWrapper) void {
const self = @fieldParentPtr(@This(), "wrapper", wrapper);
self.allocator.destroy(self);
}
pub fn invoke(wrapper: *NativeFunctionWrapper, codeRunner: *CodeRunner, callFuncType: *const Type) !void {
const self = @fieldParentPtr(@This(), "wrapper", wrapper);
const ArgsType = std.meta.ArgsTuple(FunctionType);
const info = @typeInfo(ArgsType).Struct;
if (info.fields.len != callFuncType.kind.Function.params.items.len) {
//self.reportError(null, "Wrong number of arguments. Expected {}, got {}.", .{ info.fields.len, callFuncType.kind.Function.params.len });
return error.WrongNumberOfArguments;
}
var args: ArgsType = undefined;
var currentOffset: usize = 0;
inline for (info.fields) |field, i| {
const fieldPtr = &@field(args, field.name);
const offset = std.mem.alignForward(codeRunner.basePointer + currentOffset, field.alignment) - codeRunner.basePointer;
std.log.debug("Loading argument from {} with alignment {}", .{offset, field.alignment});
try codeRunner.copyArgInto(offset, std.mem.asBytes(fieldPtr));
std.log.debug("{}", .{fieldPtr.*});
currentOffset = offset + callFuncType.kind.Function.params.items[i].size;
try codeRunner.printStack();
}
const ReturnType = @typeInfo(FunctionType).Fn.return_type;
if (ReturnType == null or ReturnType == void) {
@call(.{}, self.func, args);
} else {
const result = @call(.{}, self.func, args);
std.log.debug("After native call, pushing {any}: {s} to {}", .{ result, @typeName(ReturnType.?), codeRunner.stackPointer });
try codeRunner.push(result);
}
}
};
var wrapper = try allocator.create(Wrapper);
wrapper.* = .{
.func = functionToWrap,
.allocator = allocator,
};
return &wrapper.wrapper;
}
}; | src/native_function.zig |
const os = @import("root").os;
const std = @import("std");
/// Mutex is lock that should be used for synchronizing operations
/// that may take too long and/or can't be run in interrupt disabled context
/// (e.g. you need to use it if you allocate memory in locked section)
pub const Mutex = struct {
/// Thread that holds the mutex
held_by: ?*os.thread.Task = null,
/// Atomic queue of waiting tasks
queue: os.thread.TaskQueue = .{},
/// Spinlock used to prevent more than one thread from accessing mutex data
spinlock: os.thread.Spinlock = .{},
/// Wrapper for mutex std API
const Held = struct {
mtx: *Mutex,
/// Release mutex
pub fn release(self: *const @This()) void {
self.mtx.unlock();
}
};
/// Acquire method to be used by zig std
pub fn acquire(self: *@This()) Held {
self.lock();
return .{.mtx = self};
}
/// Lock mutex. Don't call from interrupt context!
pub fn lock(self: *@This()) void {
const lock_state = self.spinlock.lock();
if (self.held_by == null) {
self.held_by = os.platform.get_current_task();
self.spinlock.unlock(lock_state);
return;
}
self.queue.enqueue(os.platform.get_current_task());
self.spinlock.ungrab();
os.thread.scheduler.wait();
os.platform.set_interrupts(lock_state);
}
/// Unlock mutex.
pub fn unlock(self: *@This()) void {
const lock_state = self.spinlock.lock();
std.debug.assert(self.held_by_me());
if (self.queue.dequeue()) |task| {
@atomicStore(?*os.thread.Task, &self.held_by, task, .Release);
os.thread.scheduler.wake(task);
} else {
@atomicStore(?*os.thread.Task, &self.held_by, null, .Release);
}
self.spinlock.unlock(lock_state);
}
/// Check if mutex is held by current task
pub fn held_by_me(self: *const @This()) bool {
return @atomicLoad(?*os.thread.Task, &self.held_by, .Acquire) == os.platform.get_current_task();
}
pub fn init(self: *@This()) void {
self.queue.init();
}
}; | src/thread/mutex.zig |
const std = @import("std");
const logger = std.log.scoped(.day03);
const real_data = @embedFile("../data/day03.txt");
pub fn main() !void {
const digits = comptime digitsSize(real_data);
logger.info("Part one: {}", .{partOne(digits, real_data)});
}
fn partOne(comptime digits: usize, data: []const u8) !u64 {
var lines = std.mem.tokenize(u8, data, "\n");
var counts: [digits]u64 = [_]u64{0} ** digits;
var total_entries: u64 = 0;
while (lines.next()) |line| {
for (line) |char, index| {
if (char == '1') {
counts[index] += 1;
}
}
total_entries += 1;
}
const ResultType = @Type(std.builtin.TypeInfo{
.Int = .{
.signedness = .unsigned,
.bits = digits,
},
});
const ShiftType = @Type(std.builtin.TypeInfo{
.Int = .{
.signedness = .unsigned,
.bits = comptime maxShiftFor(digits),
},
});
var gamma: ResultType = 0;
for (counts) |value, index| {
if (value > total_entries / 2) {
gamma |= @intCast(ResultType, 1) << @intCast(ShiftType, index);
}
}
gamma = @bitReverse(ResultType, gamma);
const epsilon = ~gamma;
return @intCast(u64, gamma) * @intCast(u64, epsilon);
}
/// This is kind of cheating, but let's pretend this would be a configurable value.
fn digitsSize(comptime source: []const u8) usize {
var lines = std.mem.tokenize(u8, source, "\n");
const sample = lines.next() orelse unreachable;
return sample.len;
}
/// Please don't ask
fn maxShiftFor(digits: usize) usize {
const value = std.math.log2(digits);
if (value % 2 == 0) {
return value;
} else {
return value + 1;
}
}
test "part one works with explanation input" {
const test_data =
\\00100
\\11110
\\10110
\\10111
\\10101
\\01111
\\00111
\\11100
\\10000
\\11001
\\00010
\\01010
;
const digits = comptime digitsSize(test_data);
try std.testing.expectEqual(try partOne(digits, test_data), 198);
} | src/day03.zig |
const builtin = @import("builtin");
const math = @import("std").math;
comptime {
// These are implicitly defined when compiling tests.
if (!builtin.is_test) {
@export("ceil", ceil, builtin.GlobalLinkage.Strong);
@export("ceilf", ceilf, builtin.GlobalLinkage.Strong);
@export("floor", floor, builtin.GlobalLinkage.Strong);
@export("floorf", floorf, builtin.GlobalLinkage.Strong);
@export("sqrt", sqrt, builtin.GlobalLinkage.Strong);
@export("sqrtf", sqrtf, builtin.GlobalLinkage.Strong);
}
}
export fn acosf(x: f32) f32 {
return math.acos(x);
}
export fn acos(x: f64) f64 {
return math.acos(x);
}
export fn acoshf(x: f32) f32 {
return math.acosh(x);
}
export fn acosh(x: f64) f64 {
return math.acosh(x);
}
export fn asinf(x: f32) f32 {
return math.asin(x);
}
export fn asin(x: f64) f64 {
return math.asin(x);
}
export fn asinhf(x: f32) f32 {
return math.asinh(x);
}
export fn asinh(x: f64) f64 {
return math.asinh(x);
}
export fn atanf(x: f32) f32 {
return math.atan(x);
}
export fn atan(x: f64) f64 {
return math.atan(x);
}
export fn atan2f(x: f32, y: f32) f32 {
return math.atan2(f32, x, y);
}
export fn atan2(x: f64, y: f64) f64 {
return math.atan2(f64, x, y);
}
export fn atanhf(x: f32) f32 {
return math.atanh(x);
}
export fn atanh(x: f64) f64 {
return math.atanh(x);
}
export fn cbrtf(x: f32) f32 {
return math.cbrt(x);
}
export fn cbrt(x: f64) f64 {
return math.cbrt(x);
}
extern fn ceilf(x: f32) f32 {
return math.ceil(x);
}
extern fn ceil(x: f64) f64 {
return math.ceil(x);
}
export fn copysignf(x: f32, y: f32) f32 {
return math.copysign(f32, x, y);
}
export fn copysign(x: f64, y: f64) f64 {
return math.copysign(f64, x, y);
}
export fn cosf(x: f32) f32 {
return math.cos(x);
}
export fn cos(x: f64) f64 {
return math.cos(x);
}
export fn coshf(x: f32) f32 {
return math.cosh(x);
}
export fn cosh(x: f64) f64 {
return math.cosh(x);
}
export fn expf(x: f32) f32 {
return math.exp(x);
}
export fn exp(x: f64) f64 {
return math.exp(x);
}
export fn exp2f(x: f32) f32 {
return math.exp2(x);
}
export fn exp2(x: f64) f64 {
return math.exp2(x);
}
export fn expm1f(x: f32) f32 {
return math.expm1(x);
}
export fn expm1(x: f64) f64 {
return math.expm1(x);
}
export fn fabsf(x: f32) f32 {
return math.fabs(x);
}
export fn fabs(x: f64) f64 {
return math.fabs(x);
}
extern fn floorf(x: f32) f32 {
return math.floor(x);
}
extern fn floor(x: f64) f64 {
return math.floor(x);
}
export fn fmaf(x: f32, y: f32, z: f32) f32 {
return math.fma(f32, x, y, z);
}
export fn fma(x: f64, y: f64, z: f64) f64 {
return math.fma(f64, x, y, z);
}
export fn frexpf(x: f32, exponent: *c_int) f32 {
const r = math.frexp(x);
exponent.* = r.exponent;
return r.significand;
}
export fn frexp(x: f64, exponent: *c_int) f64 {
const r = math.frexp(x);
exponent.* = r.exponent;
return r.significand;
}
export fn hypotf(x: f32, y: f32) f32 {
return math.hypot(f32, x, y);
}
export fn hypot(x: f64, y: f64) f64 {
return math.hypot(f64, x, y);
}
export fn ilogbf(x: f32) c_int {
return math.ilogb(x);
}
export fn ilogb(x: f64) c_int {
return math.ilogb(x);
}
export fn logf(x: f32) f32 {
return math.ln(x);
}
export fn log(x: f64) f64 {
return math.ln(x);
}
export fn log10f(x: f32) f32 {
return math.log10(x);
}
export fn log10(x: f64) f64 {
return math.log10(x);
}
export fn log1pf(x: f32) f32 {
return math.log1p(x);
}
export fn log1p(x: f64) f64 {
return math.log1p(x);
}
export fn log2f(x: f32) f32 {
return math.log2(x);
}
export fn log2(x: f64) f64 {
return math.log2(x);
}
export fn modff(x: f32, iptr: *f32) f32 {
const r = math.modf(x);
iptr.* = r.ipart;
return r.fpart;
}
export fn modf(x: f64, iptr: *f64) f64 {
const r = math.modf(x);
iptr.* = r.ipart;
return r.fpart;
}
export fn powf(base: f32, exponent: f32) f32 {
return math.pow(f32, base, exponent);
}
export fn pow(base: f64, exponent: f64) f64 {
return math.pow(f64, base, exponent);
}
export fn roundf(x: f32) f32 {
return math.round(x);
}
export fn round(x: f64) f64 {
return math.round(x);
}
export fn scalbnf(x: f32, exponent: c_int) f32 {
return math.scalbn(x, i32(exponent));
}
export fn scalbn(x: f64, exponent: c_int) f64 {
return math.scalbn(x, i32(exponent));
}
export fn sinf(x: f32) f32 {
return math.sin(x);
}
export fn sin(x: f64) f64 {
return math.sin(x);
}
export fn sinhf(x: f32) f32 {
return math.sinh(x);
}
export fn sinh(x: f64) f64 {
return math.sinh(x);
}
extern fn sqrtf(x: f32) f32 {
return math.sqrt(x);
}
extern fn sqrt(x: f64) f64 {
return math.sqrt(x);
}
export fn tanf(x: f32) f32 {
return math.tan(x);
}
export fn tan(x: f64) f64 {
return math.tan(x);
}
export fn tanhf(x: f32) f32 {
return math.tanh(x);
}
export fn tanh(x: f64) f64 {
return math.tanh(x);
}
export fn truncf(x: f32) f32 {
return math.trunc(x);
}
export fn trunc(x: f64) f64 {
return math.trunc(x);
} | src/math.zig |
const MMIORegion = @import("root").mmio.MMIORegion;
// Thus a peripheral advertised here at bus address 0x7Ennnnnn is
// available at physical address 0x3Fnnnnnn.
//
pub const MMIO = MMIORegion(0x3F000000, u32);
pub const GPIO = struct {
pub const Region = MMIO.Subregion(0x200000);
pub const GPPUD = Region.Reg(0x94);
pub const GPPUDCLK0 = Region.Reg(0x98);
};
pub const MINI_UART = struct {
pub const Region = GPIO.Region.Subregion(0x15000);
/// Auxilliary interrupt status
pub const AUX_IRQ = Region.Reg(0x0);
/// Auxiliary enables
pub const AUX_ENABLES = Region.Reg(0x4);
/// I/O data
pub const IO = Region.Reg(0x40);
/// Interrupt enable register
pub const IER = Region.Reg(0x44);
/// Interrupt identity register
pub const IIR = Region.Reg(0x48);
/// Line control
pub const LCR = Region.Reg(0x4c);
/// Modem control
pub const MCR = Region.Reg(0x50);
/// Line status
pub const LSR = Region.Reg(0x54);
/// Modem status
pub const MSR = Region.Reg(0x58);
/// Scratch
pub const SCRATCH = Region.Reg(0x5c);
/// Extra control
pub const CNTL = Region.Reg(0x60);
/// Extra status
pub const STAT = Region.Reg(0x64);
/// Baudrate
pub const BAUD = Region.Reg(0x68);
};
pub const PL011 = struct {
pub const Region = GPIO.Region.Subregion(0x1000);
/// Data register
pub const DR = Region.Reg(0x0);
pub const RSRECR = Region.Reg(0x4);
/// Flag register
pub const FR = Region.Reg(0x18);
/// Unused
pub const ILPR = Region.Reg(0x20);
/// Integer baud rate divisor
pub const IBRD = Region.Reg(0x24);
/// Fractional baud rate divisor
pub const FBRD = Region.Reg(0x28);
/// Line control register
pub const LCRH = Region.Reg(0x2c);
/// Control register
pub const CR = Region.Reg(0x30);
/// Interrupt FIFO level select register
pub const IFLS = Region.Reg(0x34);
/// Interrupt mask set clear register
pub const IMSC = Region.Reg(0x38);
/// Raw interrupt status register
pub const RIS = Region.Reg(0x3c);
/// Masked interrupt status register
pub const MIS = Region.Reg(0x40);
/// Interrupt clear registrer
pub const ICR = Region.Reg(0x44);
/// DMA control register
pub const DMACR = Region.Reg(0x48);
/// Test control register
pub const ITCR = Region.Reg(0x80);
/// Integration test input register
pub const ITIP = Region.Reg(0x84);
/// Integration test output register
pub const ITOP = Region.Reg(0x88);
/// Test data register
pub const TDR = Region.Reg(0x8c);
};
pub const PM = struct {
pub const Region = MMIO.Subregion(0x100000);
pub const RSTC = Region.Reg(0x1c);
pub const RSTS = Region.Reg(0x20);
pub const WDOG = Region.Reg(0x24);
pub const PASSWORD = <PASSWORD>;
}; | kernel/arch/arm64/platform/BCM2837.zig |
const std = @import("std");
/// Represents a DNS type.
/// Keep in mind this enum does not declare all possible DNS types.
pub const ResourceType = enum(u16) {
A = 1,
NS = 2,
MD = 3,
MF = 4,
CNAME = 5,
SOA = 6,
MB = 7,
MG = 8,
MR = 9,
NULL = 10,
WKS = 11,
PTR = 12,
HINFO = 13,
MINFO = 14,
MX = 15,
TXT = 16,
AAAA = 28,
// TODO LOC = 29, (check if it's worth it. https://tools.ietf.org/html/rfc1876)
SRV = 33,
// those types are only valid in request packets. they may be wanted
// later on for completeness, but for now, it's more hassle than it's worth.
// AXFR = 252,
// MAILB = 253,
// MAILA = 254,
// ANY = 255,
// should this enum be non-exhaustive?
// trying to get it non-exhaustive gives "TODO @tagName on non-exhaustive enum https://github.com/ziglang/zig/issues/3991"
//_,
/// Try to convert a given string to an integer representing a Type.
pub fn fromString(str: []const u8) error{InvalidResourceType}!@This() {
// this returned Overflow but i think InvalidResourceType is also valid
// considering we dont have resource types that are more than 10
// characters long.
if (str.len > 10) return error.InvalidResourceType;
// we wouldn't need this buffer if we could do some
// case insensitive string comparison (TODO)
var buffer: [10]u8 = undefined;
for (str) |char, index| {
buffer[index] = std.ascii.toUpper(char);
}
const uppercased = buffer[0..str.len];
const type_info = @typeInfo(@This()).Enum;
inline for (type_info.fields) |field| {
if (std.mem.eql(u8, uppercased, field.name)) {
return @intToEnum(@This(), field.value);
}
}
return error.InvalidResourceType;
}
};
/// Represents a DNS class.
/// (TODO point to rfc)
pub const ResourceClass = enum(u16) {
/// The internet
IN = 1,
CS = 2,
CH = 3,
HS = 4,
WILDCARD = 255,
}; | src/pkg2/types.zig |
const std = @import("std");
pub const paging = @import("../paging.zig");
const dcommon = @import("../common/dcommon.zig");
const hw = @import("../hw.zig");
pub var TTBR0_IDENTITY: *PageTable = undefined;
pub var K_DIRECTORY: *PageTable = undefined;
pub const PAGING = paging.configuration(.{
.vaddress_mask = 0x0000007f_fffff000,
});
comptime {
std.debug.assert(dcommon.daintree_kernel_start == PAGING.kernel_base);
}
fn flagsToU64(size: paging.MapSize, flags: paging.MapFlags) u64 {
return @as(u64, switch (size) {
.block => 0 << 1,
.table => 1 << 1,
}) | switch (flags) {
.non_leaf => KERNEL_DATA_FLAGS.toU64(),
.kernel_promisc => KERNEL_PROMISC_FLAGS.toU64(),
.kernel_data => KERNEL_DATA_FLAGS.toU64(),
.kernel_rodata => KERNEL_RODATA_FLAGS.toU64(),
.kernel_code => KERNEL_CODE_FLAGS.toU64(),
.peripheral => PERIPHERAL_FLAGS.toU64(),
};
}
pub fn flushTLB() void {
asm volatile (
\\tlbi vmalle1
\\dsb ish
\\isb
::: "memory");
}
pub fn mapPage(phys_address: usize, flags: paging.MapFlags) paging.Error!usize {
return K_DIRECTORY.mapFreePage(1, PAGING.kernel_base, phys_address, flags) orelse error.OutOfMemory;
}
pub const PageTable = packed struct {
entries: [PAGING.index_size]u64,
pub fn map(self: *PageTable, index: usize, phys_address: usize, size: paging.MapSize, flags: paging.MapFlags) void {
self.entries[index] = phys_address | flagsToU64(size, flags);
}
pub fn mapFreePage(self: *PageTable, comptime level: u2, base_address: usize, phys_address: usize, flags: paging.MapFlags) ?usize {
var i: usize = 0;
if (level < 3) {
// Recurse into subtables.
while (i < self.entries.len) : (i += 1) {
if ((self.entries[i] & 0x1) == 0x0) {
var new_phys = paging.bump.alloc(PageTable);
self.map(i, @ptrToInt(new_phys), .table, .non_leaf);
}
if ((self.entries[i] & 0x3) == 0x3) {
// Valid non-leaf entry
if (self.pageAt(i).mapFreePage(
level + 1,
base_address + (i << (PAGING.page_bits + PAGING.index_bits * (3 - level))),
phys_address,
flags,
)) |addr| {
return addr;
}
}
}
} else {
while (i < self.entries.len) : (i += 1) {
if ((self.entries[i] & 0x1) == 0) {
// Empty page -- allocate to them.
self.map(i, phys_address, .table, flags);
return base_address + (i << PAGING.page_bits);
}
}
}
return null;
}
fn pageAt(self: *const PageTable, index: usize) *PageTable {
const entry = self.entries[index];
if ((entry & 0x3) != 0x3) @panic("pageAt on non-page");
return @intToPtr(*PageTable, entry & ArchPte.OA_MASK_Lx_TABLE);
}
};
pub const DEVICE_MAIR_INDEX = 1;
pub const MEMORY_MAIR_INDEX = 0;
pub const STACK_PAGES = 16;
pub const KERNEL_PROMISC_FLAGS = ArchPte{ .uxn = 1, .pxn = 0, .af = 1, .sh = .inner_shareable, .ap = .readwrite_no_el0, .attr_index = MEMORY_MAIR_INDEX, .type = .block };
comptime {
std.debug.assert(0x0040000000000701 == KERNEL_PROMISC_FLAGS.toU64());
}
pub const KERNEL_DATA_FLAGS = ArchPte{ .uxn = 1, .pxn = 1, .af = 1, .sh = .inner_shareable, .ap = .readwrite_no_el0, .attr_index = MEMORY_MAIR_INDEX, .type = .block };
comptime {
std.debug.assert(0x00600000_00000701 == KERNEL_DATA_FLAGS.toU64());
}
pub const KERNEL_RODATA_FLAGS = ArchPte{ .uxn = 1, .pxn = 1, .af = 1, .sh = .inner_shareable, .ap = .readonly_no_el0, .attr_index = MEMORY_MAIR_INDEX, .type = .block };
comptime {
std.debug.assert(0x00600000_00000781 == KERNEL_RODATA_FLAGS.toU64());
}
pub const KERNEL_CODE_FLAGS = ArchPte{ .uxn = 1, .pxn = 0, .af = 1, .sh = .inner_shareable, .ap = .readonly_no_el0, .attr_index = MEMORY_MAIR_INDEX, .type = .block };
comptime {
std.debug.assert(0x00400000_00000781 == KERNEL_CODE_FLAGS.toU64());
}
pub const PERIPHERAL_FLAGS = ArchPte{ .uxn = 1, .pxn = 1, .af = 1, .sh = .outer_shareable, .ap = .readwrite_no_el0, .attr_index = DEVICE_MAIR_INDEX, .type = .block };
comptime {
std.debug.assert(0x00600000_00000605 == PERIPHERAL_FLAGS.toU64());
}
// Avoiding packed structs since they're simply broken right now.
// (was getting @bitSizeOf(x) == 64 but @sizeOf(x) == 9 (!!) --
// wisdom is to avoid for now.)
// ref Figure D5-15
pub const ArchPte = struct {
pub const OA_MASK_L1_BLOCK: u64 = 0x0000ffff_c0000000;
pub const OA_MASK_L2_BLOCK: u64 = 0x0000ffff_ffe00000;
pub const OA_MASK_Lx_TABLE: u64 = 0x0000ffff_fffff000;
pub fn toU64(pte: ArchPte) callconv(.Inline) u64 {
return @as(u64, pte.valid) |
(@as(u64, @enumToInt(pte.type)) << 1) |
(@as(u64, pte.attr_index) << 2) |
(@as(u64, pte.ns) << 5) |
(@as(u64, @enumToInt(pte.ap)) << 6) |
(@as(u64, @enumToInt(pte.sh)) << 8) |
(@as(u64, pte.af) << 10) |
(@as(u64, pte.pxn) << 53) |
(@as(u64, pte.uxn) << 54);
}
valid: u1 = 1,
type: enum(u1) {
block = 0,
table = 1,
},
attr_index: u3,
ns: u1 = 0,
ap: enum(u2) {
readwrite_no_el0 = 0b00,
readwrite_el0_readwrite = 0b01,
readonly_no_el0 = 0b10,
readonly_el0_readonly = 0b11,
},
sh: enum(u2) {
inner_shareable = 0b11,
outer_shareable = 0b10,
},
af: u1, // access flag
// ng: u1 = 0, // ??
// _res0a: u4 = 0, // OA[51:48]
// _res0b: u1 = 0, // nT
// _res0c: u12 = 0,
// _res0d: u4 = 0,
// contiguous: u1 = 0,
pxn: u1,
uxn: u1,
// _resa: u4 = 0,
// _res0b: u4 = 0,
// _resb: u1 = 0,
};
pub const TCR_EL1 = struct {
pub fn toU64(tcr: TCR_EL1) callconv(.Inline) u64 {
return @as(u64, tcr.t0sz) |
(@as(u64, tcr.epd0) << 7) |
(@as(u64, tcr.irgn0) << 8) |
(@as(u64, tcr.orgn0) << 10) |
(@as(u64, tcr.sh0) << 12) |
(@as(u64, @enumToInt(tcr.tg0)) << 14) |
(@as(u64, tcr.t1sz) << 16) |
(@as(u64, tcr.a1) << 22) |
(@as(u64, tcr.epd1) << 23) |
(@as(u64, tcr.irgn1) << 24) |
(@as(u64, tcr.orgn1) << 26) |
(@as(u64, tcr.sh1) << 28) |
(@as(u64, @enumToInt(tcr.tg1)) << 30) |
(@as(u64, @enumToInt(tcr.ips)) << 32);
}
t0sz: u6, // TTBR0_EL1 addresses 2**(64-25)
// _res0a: u1 = 0,
epd0: u1 = 0, // enable TTBR0_EL1 walks (set = 1 to *disable*)
irgn0: u2 = 0b01, // "Normal, Inner Wr.Back Rd.alloc Wr.alloc Cacheble"
orgn0: u2 = 0b01, // "Normal, Outer Wr.Back Rd.alloc Wr.alloc Cacheble"
sh0: u2 = 0b11, // inner-shareable
tg0: enum(u2) {
K4 = 0b00,
K16 = 0b10,
K64 = 0b01,
},
t1sz: u6, // TTBR1_EL1 addresses 2**(64-25): 0xffffff80_00000000
a1: u1 = 0, // TTBR0_EL1.ASID defines the ASID
epd1: u1 = 0, // enable TTBR1_EL1 walks (set = 1 to *disable*)
irgn1: u2 = 0b01, // "Normal, Inner Wr.Back Rd.alloc Wr.alloc Cacheble"
orgn1: u2 = 0b01, // "Normal, Outer Wr.Back Rd.alloc Wr.alloc Cacheble"
sh1: u2 = 0b11, // inner-shareable
tg1: enum(u2) { // granule size for TTBR1_EL1
K4 = 0b10,
K16 = 0b01,
K64 = 0b11,
},
ips: enum(u3) {
B32 = 0b000,
B36 = 0b001,
B48 = 0b101,
},
// _res0b: u1 = 0,
// _as: u1 = 0,
// tbi0: u1 = 0, // top byte ignored
// tbi1: u1 = 0,
// _ha: u1 = 0,
// _hd: u1 = 0,
// _hpd0: u1 = 0,
// _hpd1: u1 = 0,
// _hwu: u8 = 0,
// _tbid0: u1 = 0,
// _tbid1: u1 = 0,
// _nfd0: u1 = 0,
// _nfd1: u1 = 0,
// _res0c: u9 = 0,
};
pub const MAIR_EL1 = struct {
index: u3,
attrs: u8,
pub fn toU64(mair_el1: MAIR_EL1) callconv(.Inline) u64 {
return @as(u64, mair_el1.attrs) << (@as(u6, mair_el1.index) * 8);
}
};
comptime {
if (@bitSizeOf(ArchPte) != 64) {
// @compileLog("ArchPte misshapen; ", @bitSizeOf(ArchPte));
}
if (@sizeOf(ArchPte) != 8) {
// @compileLog("ArchPte misshapen; ", @sizeOf(ArchPte));
}
if (@bitSizeOf(TCR_EL1) != 64) {
// @compileLog("TCR_EL1 misshapen; ", @bitSizeOf(TCR_EL1));
}
} | dainkrnl/src/arm64/paging.zig |
const std = @import("std");
const webgpu = @import("./webgpu.zig");
pub const AdapterProperties = struct {
vendor_id: u32,
device_id: u32,
name: [:0]const u8,
driver_descripton: [:0]const u8,
adapter_type: webgpu.AdapterType,
backend_type: webgpu.BackendType,
};
pub const BufferBinding = struct {
buffer: webgpu.Buffer,
offset: u64 = 0,
size: ?u64 = null,
};
pub const BindGroupResource = union {
sampler: webgpu.Sampler,
texture_view: webgpu.TextureView,
buffer: BufferBinding,
};
pub const BindGroupEntry = struct {
binding: u32,
resource: BindGroupResource,
};
pub const BlendComponent = struct {
operation: webgpu.BlendOperation = .add,
src_factor: webgpu.BlendFactor = .one,
dst_factor: webgpu.BlendFactor = .zero,
};
pub const BufferBindingLayout = struct {
ty: webgpu.BufferBindingType = .uniform,
has_dynamic_offset: bool = false,
min_binding_size: u64 = 0,
};
pub const BufferDescriptor = struct {
label: ?[:0]const u8 = null,
usage: webgpu.BufferUsage,
size: u64,
mapped_at_creation: bool = false,
};
pub const Color = struct {
r: f64,
g: f64,
b: f64,
a: f64,
};
pub const CommandBufferDescriptor = struct {
label: ?[:0]const u8 = null,
};
pub const CommandEncoderDescriptor = struct {
label: ?[:0]const u8 = null,
};
pub const CompilationMessage = struct {
message: [:0]const u8,
ty: webgpu.CompilationMessageType,
line_num: u64,
line_pos: u64,
offset: u64,
length: u64,
};
pub const ComputePassTimestampWrite = struct {
query_set: webgpu.QuerySet,
query_index: u32,
location: webgpu.ComputePassTimestampLocation,
};
pub const ConstantEntry = struct {
key: [:0]const u8,
value: f64,
};
pub const Extend3D = struct {
width: u32,
height: u32,
depth_or_array_layers: u32 = 1,
};
pub const InstanceDescriptor = struct {
allocator: std.mem.Allocator = std.heap.c_allocator,
};
pub const Limits = struct {
max_texture_dimension1d: u32 = 8192,
max_texture_dimension2d: u32 = 8192,
max_texture_dimension3d: u32 = 2048,
max_texture_array_layers: u32 = 256,
max_bind_groups: u32 = 4,
max_dynamic_uniform_buffers_per_pipeline_layout: u32 = 8,
max_dynamic_storage_buffers_per_pipeline_layout: u32 = 4,
max_sampled_textures_per_shader_stage: u32 = 16,
max_samplers_per_shader_stage: u32 = 16,
max_storage_buffers_per_shader_stage: u32 = 8,
max_storage_textures_per_shader_stage: u32 = 4,
max_uniform_buffers_per_shader_stage: u32 = 12,
max_uniform_buffer_binding_size: u64 = 65536,
max_storage_buffer_binding_size: u64 = 134217728,
min_uniform_buffer_offset_alignment: u32 = 256,
min_storage_buffer_offset_alignment: u32 = 256,
max_vertex_buffers: u32 = 8,
max_vertex_attributes: u32 = 16,
max_vertex_buffer_array_stride: u32 = 2048,
max_inter_stage_shader_components: u32 = 60,
max_compute_workgroup_storage_size: u32 = 16352,
max_compute_invocations_per_workgroup: u32 = 256,
max_compute_workgroup_size_x: u32 = 256,
max_compute_workgroup_size_y: u32 = 256,
max_compute_workgroup_size_z: u32 = 64,
max_compute_workgroups_per_dimension: u32 = 65535,
};
pub const MultisampleState = struct {
count: u32 = 1,
mask: u32 = 0xFFFFFFFF,
alpha_to_coverage_enabled: bool = false,
};
pub const Origin3D = struct {
x: u32 = 0,
y: u32 = 0,
z: u32 = 0,
pub const zero = Origin3D{};
};
pub const PipelineLayoutDescriptor = struct {
label: ?[:0]const u8 = null,
bind_group_layouts: []webgpu.BindGroupLayout,
};
pub const PrimitiveState = struct {
topology: webgpu.PrimitiveTopology = .triangle_list,
strip_index_format: ?webgpu.IndexFormat = null,
front_face: webgpu.FrontFace = .cww,
cull_mode: ?webgpu.CullMode = null,
unclipped_depth: bool = false,
};
pub const QuerySetDescriptor = struct {
label: ?[:0]const u8 = null,
ty: webgpu.QueryType,
pipeline_statistics: []webgpu.PipelineStatisticName,
};
pub const RenderBundleEncoderDescriptor = struct {
label: ?[:0]const u8 = null,
color_formats: []webgpu.TextureFormat,
depth_stencil_format: ?webgpu.TextureFormat = null,
sample_count: u32 = 1,
depth_read_only: bool = false,
depth_write_only: bool = false,
};
pub const RenderPassDepthStencilAttachment = struct {
view: webgpu.TextureView,
depth_clear_value: f32 = 0,
depth_load_op: ?webgpu.LoadOp = null,
depth_store_op: ?webgpu.StoreOp = null,
depth_read_only: bool = false,
stencil_clear_value: f32 = 0,
stencil_load_op: ?webgpu.LoadOp = null,
stencil_store_op: ?webgpu.StoreOp = null,
stencil_read_only: bool = false,
};
pub const RenderPassTimestampWrite = struct {
query_set: webgpu.QuerySet,
query_index: u32,
location: webgpu.RenderPassTimestampLocation,
};
pub const RequestAdapterOptions = struct {
compatible_surface: ?webgpu.Surface = null,
power_preference: webgpu.PowerPreference = .low_power,
force_fallback_adapter: bool = false,
};
pub const SamplerBindingLayout = struct {
ty: webgpu.SamplerBindingType = .filtering,
};
pub const SamplerDescriptor = struct {
label: ?[:0]const u8 = null,
address_mode_u: webgpu.AddressMode = .clamp_to_edge,
address_mode_v: webgpu.AddressMode = .clamp_to_edge,
address_mode_w: webgpu.AddressMode = .clamp_to_edge,
mag_filter: webgpu.FilterMode = .nearest,
min_filter: webgpu.FilterMode = .nearest,
mipmap_filter: webgpu.FilterMode = .nearest,
lod_min_clamp: f32 = 0,
lod_max_clamp: f32 = 32,
compare: ?webgpu.CompareFunction = null,
max_anisotropy: u16 = 1,
};
pub const ShaderModuleDescriptor = union {
spirv: []const u32,
wgsl: [:0]const u8,
};
pub const StencilFaceState = struct {
compare: webgpu.CompareFunction = .always,
fail_op: webgpu.StencilOperation = .keep,
depth_fail_op: webgpu.StencilOperation = .keep,
pass_op: webgpu.StencilOperation = .keep,
};
pub const StorageTextureBindingLayout = struct {
access: webgpu.StorageTextureAccess = .write_only,
format: webgpu.TextureFormat,
view_dimension: webgpu.TextureViewDimension = .d2,
};
pub const SurfaceDescriptor = struct {
label: ?[:0]const u8 = null,
platform: SurfacePlatformDescriptor,
};
pub const SurfacePlatformDescriptor = union {
canvas: struct {
html_selector: [:0]const u8,
},
metal: struct {
layer: *anyopaque,
},
windows: struct {
hinstance: *anyopaque,
hwnd: *anyopaque,
},
xlib: struct {
display: *anyopaque,
window: u32,
},
wayland: struct {
display: *anyopaque,
surface: *anyopaque,
},
android: struct {
window: *anyopaque,
},
};
pub const SwapChainDescriptor = struct {
label: ?[:0]const u8 = null,
usage: webgpu.TextureUsage = .render_attachment,
format: webgpu.TextureFormat = .bgra8_unorm,
width: u32,
height: u32,
present_mode: webgpu.PresentMode = .fifo,
};
pub const TextureBindingLayout = struct {
sample_type: webgpu.TextureSampleType = .float,
view_dimension: webgpu.TextureViewDimension = .d2,
multisampled: bool = false,
};
pub const TextureDataLayout = struct {
offset: u64 = 0,
bytes_per_row: u32 = 1,
rows_per_image: u32 = 1,
};
pub const TextureViewDescriptor = struct {
label: ?[:0]const u8 = null,
format: ?webgpu.TextureFormat = null,
dimension: ?webgpu.TextureViewDimension = null,
aspect: ?webgpu.TextureAspect = .all,
base_mip_level: u32 = 0,
mip_level_count: u32 = 0,
base_array_layer: u32 = 0,
array_layer_count: u32 = 0,
};
pub const VertexAttribute = struct {
format: webgpu.VertexFormat,
offset: u64,
shader_location: u32,
};
pub const BindGroupDescriptor = struct {
label: ?[:0]const u8 = null,
layout: webgpu.BindGroupLayout,
entries: []webgpu.BindGroupEntry,
};
pub const BindGroupLayoutEntry = struct {
binding: u32 = null,
visibility: webgpu.ShaderStage,
buffer: ?webgpu.BufferBindingLayout = null,
sampler: ?webgpu.SamplerBindingLayout = null,
texture: ?webgpu.TextureBindingLayout = null,
storage_texture: ?webgpu.StorageTextureBindingLayout = null,
};
pub const BlendState = struct {
color: webgpu.BlendComponent,
alpha: webgpu.BlendComponent,
};
pub const CompilationInfo = struct {
messages: []webgpu.CompilationMessage,
};
pub const ComputePassDescriptor = struct {
label: ?[:0]const u8 = null,
timestamp_writes: []webgpu.ComputePassTimestampWrite = &.{},
};
pub const DepthStencilState = struct {
format: webgpu.TextureFormat,
depth_write_enabled: bool = false,
depth_compare: webgpu.CompareFunction = .always,
stencil_front: webgpu.StencilFaceState = .{},
stencil_back: webgpu.StencilFaceState = .{},
stencil_read_mask: u32 = 0xFFFFFFFF,
stencil_write_mask: u32 = 0xFFFFFFFF,
depth_bias: i32 = 0,
depth_bias_slope_scale: f32 = 0,
depth_bias_clamp: f32 = 0,
};
pub const ImageCopyBuffer = struct {
layout: webgpu.TextureDataLayout = .{},
buffer: webgpu.Buffer,
};
pub const ImageCopyTexture = struct {
texture: webgpu.Texture,
mip_level: u32 = 0,
origin: webgpu.Origin3D = .{},
aspect: webgpu.TextureAspect = .all,
};
pub const ProgrammableStageDescriptor = struct {
module: webgpu.ShaderModule,
entry_point: [:0]const u8,
constants: []webgpu.ConstantEntry = &.{},
};
pub const RenderPassColorAttachment = struct {
view: webgpu.TextureView,
resolve_target: ?webgpu.TextureView = null,
load_op: webgpu.LoadOp,
store_op: webgpu.StoreOp,
clear_color: ?webgpu.Color = null,
};
pub const TextureDescriptor = struct {
label: ?[:0]const u8 = null,
usage: webgpu.TextureUsage,
dimension: webgpu.TextureDimension = .d2,
size: u32,
format: webgpu.TextureFormat,
mip_level_count: u32 = 1,
sample_count: u32 = 1,
};
pub const VertexBufferLayout = struct {
array_stride: u64 = 0,
step_mode: webgpu.VertexStepMode = .vertex,
attributes: []webgpu.VertexAttribute,
};
pub const BindGroupLayoutDescriptor = struct {
label: ?[:0]const u8 = null,
entries: []webgpu.BindGroupLayoutEntry,
};
pub const ColorTargetState = struct {
format: webgpu.TextureFormat,
blend: ?webgpu.BlendState = null,
write_mask: webgpu.ColorWriteMask = webgpu.ColorWriteMask.all,
};
pub const ComputePipelineDescriptor = struct {
label: ?[:0]const u8 = null,
layout: ?webgpu.PipelineLayout = null,
compute: webgpu.ProgrammableStageDescriptor,
};
pub const DeviceDescriptor = struct {
label: ?[:0]const u8 = null,
required_features: webgpu.Features = .{},
required_limits: webgpu.Limits = .{},
};
pub const RenderPassDescriptor = struct {
label: ?[:0]const u8 = null,
color_attachments: []webgpu.RenderPassColorAttachment,
depth_stencil_attachment: ?webgpu.RenderPassDepthStencilAttachment = null,
occlusion_query_set: ?webgpu.QuerySet = null,
timestamp_writes: []webgpu.RenderPassTimestampWrite = &.{},
};
pub const VertexState = struct {
module: webgpu.ShaderModule,
entry_point: [:0]const u8,
constants: []webgpu.ConstantEntry = &.{},
buffers: []webgpu.VertexBufferLayout = &.{},
};
pub const FragmentState = struct {
module: webgpu.ShaderModule,
entry_point: [:0]const u8,
constants: []webgpu.ConstantEntry = &.{},
targets: []webgpu.ColorTargetState = &.{},
};
pub const RenderPipelineDescriptor = struct {
label: ?[:0]const u8 = null,
vertex: webgpu.VertexState,
primitive: webgpu.PrimitiveState = .{},
depth_stencil: ?webgpu.DepthStencilState = null,
multisample: webgpu.MultisampleState = .{},
fragment: ?webgpu.FragmentState = null,
}; | src/structs.zig |
const std = @import("std");
const clap = @import("clap");
const Event = @import("../remote.zig").Event;
const BorkConfig = @import("../main.zig").BorkConfig;
const parseTime = @import("./utils.zig").parseTime;
fn connect(alloc: std.mem.Allocator, port: u16) std.net.Stream {
return std.net.tcpConnectToHost(alloc, "127.0.0.1", port) catch |err| switch (err) {
error.ConnectionRefused => {
std.debug.print(
\\Connection refused!
\\Is Bork running?
\\
, .{});
std.os.exit(1);
},
else => {
std.debug.print(
\\Unexpected error: {}
\\
, .{err});
std.os.exit(1);
},
};
}
pub fn send(alloc: std.mem.Allocator, config: BorkConfig, it: *clap.args.OsIterator) !void {
const message = (try it.next()) orelse {
std.debug.print("Usage ./bork send \"my message Kappa\"\n", .{});
return;
};
const conn = connect(alloc, config.remote_port);
defer conn.close();
try conn.writer().writeAll("SEND\n");
try conn.writer().writeAll(message);
try conn.writer().writeAll("\n");
}
pub fn quit(alloc: std.mem.Allocator, config: BorkConfig, it: *clap.args.OsIterator) !void {
_ = it;
const conn = connect(alloc, config.remote_port);
defer conn.close();
try conn.writer().writeAll("QUIT\n");
}
pub fn reconnect(alloc: std.mem.Allocator, config: BorkConfig, it: *clap.args.OsIterator) !void {
// TODO: validation
_ = it;
const conn = connect(alloc, config.remote_port);
defer conn.close();
try conn.writer().writeAll("RECONNECT\n");
}
pub fn links(alloc: std.mem.Allocator, config: BorkConfig, it: *clap.args.OsIterator) !void {
// TODO: validation
_ = it;
const conn = connect(alloc, config.remote_port);
defer conn.close();
try conn.writer().writeAll("LINKS\n");
std.debug.print("Latest links (not sent by you)\n\n", .{});
var buf: [100]u8 = undefined;
var n = try conn.read(&buf);
const out = std.io.getStdOut();
while (n != 0) : (n = try conn.read(&buf)) {
try out.writeAll(buf[0..n]);
}
}
pub fn ban(alloc: std.mem.Allocator, config: BorkConfig, it: *clap.args.OsIterator) !void {
const user = (try it.next()) orelse {
std.debug.print("Usage ./bork ban \"username\"\n", .{});
return;
};
const conn = connect(alloc, config.remote_port);
defer conn.close();
try conn.writer().writeAll("BAN\n");
try conn.writer().writeAll(user);
try conn.writer().writeAll("\n");
}
pub fn unban(alloc: std.mem.Allocator, config: BorkConfig, it: *clap.args.OsIterator) !void {
const user = try it.next(alloc);
if (try it.next(alloc)) |_| {
std.debug.print(
\\Usage ./bork unban ["username"]
\\Omitting <username> will try to unban the last banned
\\user in the current session.
\\
, .{});
return;
}
const conn = connect(alloc, config.remote_port);
defer conn.close();
try conn.writer().writeAll("UNBAN\n");
try conn.writer().writeAll(user);
try conn.writer().writeAll("\n");
}
pub fn afk(alloc: std.mem.Allocator, config: BorkConfig, it: *clap.args.OsIterator) !void {
const summary =
\\Creates an AFK message with a countdown.
\\Click on the message to dismiss it.
\\
\\Usage: bork afk TIMER [REASON] [-t TITLE]
\\
\\TIMER: the countdown timer, eg: '1h25m' or '500s'
\\REASON: the reason for being afk, eg: 'dinner'
\\
;
const params = comptime [_]clap.Param(clap.Help){
clap.parseParam("-h, --help display this help message") catch unreachable,
clap.parseParam("-t, --title <TITLE> changes the title shown, defaults to 'AFK'") catch unreachable,
clap.parseParam("<TIMER> the countdown timer, eg: '1h25m' or '500s'") catch unreachable,
clap.parseParam("<REASON> the reason for being afk, eg: 'dinner'") catch unreachable,
};
var diag: clap.Diagnostic = undefined;
var args = clap.parseEx(clap.Help, ¶ms, it, .{
.allocator = alloc,
.diagnostic = &diag,
}) catch |err| {
// Report any useful error and exit
diag.report(std.io.getStdErr().writer(), err) catch {};
return err;
};
const positionals = args.positionals();
const pos_ok = positionals.len > 0 and positionals.len < 3;
if (args.flag("-h") or args.flag("--help") or !pos_ok) {
std.debug.print("{s}\n", .{summary});
clap.help(std.io.getStdErr().writer(), ¶ms) catch {};
std.debug.print("\n", .{});
return;
}
const time = positionals[0];
_ = parseTime(time) catch {
std.debug.print(
\\Bad timer!
\\Format: 1h15m, 60s, 7m
\\
, .{});
return;
};
const reason = if (positionals.len == 2) positionals[1] else null;
if (reason) |r| {
for (r) |c| switch (c) {
else => {},
'\n', '\r', '\t' => {
std.debug.print(
\\Reason cannot contain newlines!
\\
, .{});
return;
},
};
}
const title = args.option("--title");
if (title) |t| {
for (t) |c| switch (c) {
else => {},
'\n', '\r', '\t' => {
std.debug.print(
\\Title cannot contain newlines!
\\
, .{});
return;
},
};
}
std.debug.print("timer: {s}, reason: {s}, title: {s}\n", .{ time, reason, title });
const conn = connect(alloc, config.remote_port);
defer conn.close();
const w = conn.writer();
try w.writeAll("AFK\n");
try w.writeAll(time);
try w.writeAll("\n");
if (reason) |r| try w.writeAll(r);
try conn.writer().writeAll("\n");
if (title) |t| try w.writeAll(t);
try conn.writer().writeAll("\n");
} | src/remote/client.zig |
const ffs = @import("count0bits.zig");
const testing = @import("std").testing;
fn test__ffssi2(a: u32, expected: i32) !void {
var x = @bitCast(i32, a);
var result = ffs.__ffssi2(x);
try testing.expectEqual(expected, result);
}
test "ffssi2" {
try test__ffssi2(0x00000001, 1);
try test__ffssi2(0x00000002, 2);
try test__ffssi2(0x00000003, 1);
try test__ffssi2(0x00000004, 3);
try test__ffssi2(0x00000005, 1);
try test__ffssi2(0x00000006, 2);
try test__ffssi2(0x00000007, 1);
try test__ffssi2(0x00000008, 4);
try test__ffssi2(0x00000009, 1);
try test__ffssi2(0x0000000A, 2);
try test__ffssi2(0x0000000B, 1);
try test__ffssi2(0x0000000C, 3);
try test__ffssi2(0x0000000D, 1);
try test__ffssi2(0x0000000E, 2);
try test__ffssi2(0x0000000F, 1);
try test__ffssi2(0x00000010, 5);
try test__ffssi2(0x00000011, 1);
try test__ffssi2(0x00000012, 2);
try test__ffssi2(0x00000013, 1);
try test__ffssi2(0x00000014, 3);
try test__ffssi2(0x00000015, 1);
try test__ffssi2(0x00000016, 2);
try test__ffssi2(0x00000017, 1);
try test__ffssi2(0x00000018, 4);
try test__ffssi2(0x00000019, 1);
try test__ffssi2(0x0000001A, 2);
try test__ffssi2(0x0000001B, 1);
try test__ffssi2(0x0000001C, 3);
try test__ffssi2(0x0000001D, 1);
try test__ffssi2(0x0000001E, 2);
try test__ffssi2(0x0000001F, 1);
try test__ffssi2(0x00000020, 6);
try test__ffssi2(0x00000021, 1);
try test__ffssi2(0x00000022, 2);
try test__ffssi2(0x00000023, 1);
try test__ffssi2(0x00000024, 3);
try test__ffssi2(0x00000025, 1);
try test__ffssi2(0x00000026, 2);
try test__ffssi2(0x00000027, 1);
try test__ffssi2(0x00000028, 4);
try test__ffssi2(0x00000029, 1);
try test__ffssi2(0x0000002A, 2);
try test__ffssi2(0x0000002B, 1);
try test__ffssi2(0x0000002C, 3);
try test__ffssi2(0x0000002D, 1);
try test__ffssi2(0x0000002E, 2);
try test__ffssi2(0x0000002F, 1);
try test__ffssi2(0x00000030, 5);
try test__ffssi2(0x00000031, 1);
try test__ffssi2(0x00000032, 2);
try test__ffssi2(0x00000033, 1);
try test__ffssi2(0x00000034, 3);
try test__ffssi2(0x00000035, 1);
try test__ffssi2(0x00000036, 2);
try test__ffssi2(0x00000037, 1);
try test__ffssi2(0x00000038, 4);
try test__ffssi2(0x00000039, 1);
try test__ffssi2(0x0000003A, 2);
try test__ffssi2(0x0000003B, 1);
try test__ffssi2(0x0000003C, 3);
try test__ffssi2(0x0000003D, 1);
try test__ffssi2(0x0000003E, 2);
try test__ffssi2(0x0000003F, 1);
try test__ffssi2(0x00000040, 7);
try test__ffssi2(0x00000041, 1);
try test__ffssi2(0x00000042, 2);
try test__ffssi2(0x00000043, 1);
try test__ffssi2(0x00000044, 3);
try test__ffssi2(0x00000045, 1);
try test__ffssi2(0x00000046, 2);
try test__ffssi2(0x00000047, 1);
try test__ffssi2(0x00000048, 4);
try test__ffssi2(0x00000049, 1);
try test__ffssi2(0x0000004A, 2);
try test__ffssi2(0x0000004B, 1);
try test__ffssi2(0x0000004C, 3);
try test__ffssi2(0x0000004D, 1);
try test__ffssi2(0x0000004E, 2);
try test__ffssi2(0x0000004F, 1);
try test__ffssi2(0x00000050, 5);
try test__ffssi2(0x00000051, 1);
try test__ffssi2(0x00000052, 2);
try test__ffssi2(0x00000053, 1);
try test__ffssi2(0x00000054, 3);
try test__ffssi2(0x00000055, 1);
try test__ffssi2(0x00000056, 2);
try test__ffssi2(0x00000057, 1);
try test__ffssi2(0x00000058, 4);
try test__ffssi2(0x00000059, 1);
try test__ffssi2(0x0000005A, 2);
try test__ffssi2(0x0000005B, 1);
try test__ffssi2(0x0000005C, 3);
try test__ffssi2(0x0000005D, 1);
try test__ffssi2(0x0000005E, 2);
try test__ffssi2(0x0000005F, 1);
try test__ffssi2(0x00000060, 6);
try test__ffssi2(0x00000061, 1);
try test__ffssi2(0x00000062, 2);
try test__ffssi2(0x00000063, 1);
try test__ffssi2(0x00000064, 3);
try test__ffssi2(0x00000065, 1);
try test__ffssi2(0x00000066, 2);
try test__ffssi2(0x00000067, 1);
try test__ffssi2(0x00000068, 4);
try test__ffssi2(0x00000069, 1);
try test__ffssi2(0x0000006A, 2);
try test__ffssi2(0x0000006B, 1);
try test__ffssi2(0x0000006C, 3);
try test__ffssi2(0x0000006D, 1);
try test__ffssi2(0x0000006E, 2);
try test__ffssi2(0x0000006F, 1);
try test__ffssi2(0x00000070, 5);
try test__ffssi2(0x00000071, 1);
try test__ffssi2(0x00000072, 2);
try test__ffssi2(0x00000073, 1);
try test__ffssi2(0x00000074, 3);
try test__ffssi2(0x00000075, 1);
try test__ffssi2(0x00000076, 2);
try test__ffssi2(0x00000077, 1);
try test__ffssi2(0x00000078, 4);
try test__ffssi2(0x00000079, 1);
try test__ffssi2(0x0000007A, 2);
try test__ffssi2(0x0000007B, 1);
try test__ffssi2(0x0000007C, 3);
try test__ffssi2(0x0000007D, 1);
try test__ffssi2(0x0000007E, 2);
try test__ffssi2(0x0000007F, 1);
try test__ffssi2(0x00000080, 8);
try test__ffssi2(0x00000081, 1);
try test__ffssi2(0x00000082, 2);
try test__ffssi2(0x00000083, 1);
try test__ffssi2(0x00000084, 3);
try test__ffssi2(0x00000085, 1);
try test__ffssi2(0x00000086, 2);
try test__ffssi2(0x00000087, 1);
try test__ffssi2(0x00000088, 4);
try test__ffssi2(0x00000089, 1);
try test__ffssi2(0x0000008A, 2);
try test__ffssi2(0x0000008B, 1);
try test__ffssi2(0x0000008C, 3);
try test__ffssi2(0x0000008D, 1);
try test__ffssi2(0x0000008E, 2);
try test__ffssi2(0x0000008F, 1);
try test__ffssi2(0x00000090, 5);
try test__ffssi2(0x00000091, 1);
try test__ffssi2(0x00000092, 2);
try test__ffssi2(0x00000093, 1);
try test__ffssi2(0x00000094, 3);
try test__ffssi2(0x00000095, 1);
try test__ffssi2(0x00000096, 2);
try test__ffssi2(0x00000097, 1);
try test__ffssi2(0x00000098, 4);
try test__ffssi2(0x00000099, 1);
try test__ffssi2(0x0000009A, 2);
try test__ffssi2(0x0000009B, 1);
try test__ffssi2(0x0000009C, 3);
try test__ffssi2(0x0000009D, 1);
try test__ffssi2(0x0000009E, 2);
try test__ffssi2(0x0000009F, 1);
try test__ffssi2(0x000000A0, 6);
try test__ffssi2(0x000000A1, 1);
try test__ffssi2(0x000000A2, 2);
try test__ffssi2(0x000000A3, 1);
try test__ffssi2(0x000000A4, 3);
try test__ffssi2(0x000000A5, 1);
try test__ffssi2(0x000000A6, 2);
try test__ffssi2(0x000000A7, 1);
try test__ffssi2(0x000000A8, 4);
try test__ffssi2(0x000000A9, 1);
try test__ffssi2(0x000000AA, 2);
try test__ffssi2(0x000000AB, 1);
try test__ffssi2(0x000000AC, 3);
try test__ffssi2(0x000000AD, 1);
try test__ffssi2(0x000000AE, 2);
try test__ffssi2(0x000000AF, 1);
try test__ffssi2(0x000000B0, 5);
try test__ffssi2(0x000000B1, 1);
try test__ffssi2(0x000000B2, 2);
try test__ffssi2(0x000000B3, 1);
try test__ffssi2(0x000000B4, 3);
try test__ffssi2(0x000000B5, 1);
try test__ffssi2(0x000000B6, 2);
try test__ffssi2(0x000000B7, 1);
try test__ffssi2(0x000000B8, 4);
try test__ffssi2(0x000000B9, 1);
try test__ffssi2(0x000000BA, 2);
try test__ffssi2(0x000000BB, 1);
try test__ffssi2(0x000000BC, 3);
try test__ffssi2(0x000000BD, 1);
try test__ffssi2(0x000000BE, 2);
try test__ffssi2(0x000000BF, 1);
try test__ffssi2(0x000000C0, 7);
try test__ffssi2(0x000000C1, 1);
try test__ffssi2(0x000000C2, 2);
try test__ffssi2(0x000000C3, 1);
try test__ffssi2(0x000000C4, 3);
try test__ffssi2(0x000000C5, 1);
try test__ffssi2(0x000000C6, 2);
try test__ffssi2(0x000000C7, 1);
try test__ffssi2(0x000000C8, 4);
try test__ffssi2(0x000000C9, 1);
try test__ffssi2(0x000000CA, 2);
try test__ffssi2(0x000000CB, 1);
try test__ffssi2(0x000000CC, 3);
try test__ffssi2(0x000000CD, 1);
try test__ffssi2(0x000000CE, 2);
try test__ffssi2(0x000000CF, 1);
try test__ffssi2(0x000000D0, 5);
try test__ffssi2(0x000000D1, 1);
try test__ffssi2(0x000000D2, 2);
try test__ffssi2(0x000000D3, 1);
try test__ffssi2(0x000000D4, 3);
try test__ffssi2(0x000000D5, 1);
try test__ffssi2(0x000000D6, 2);
try test__ffssi2(0x000000D7, 1);
try test__ffssi2(0x000000D8, 4);
try test__ffssi2(0x000000D9, 1);
try test__ffssi2(0x000000DA, 2);
try test__ffssi2(0x000000DB, 1);
try test__ffssi2(0x000000DC, 3);
try test__ffssi2(0x000000DD, 1);
try test__ffssi2(0x000000DE, 2);
try test__ffssi2(0x000000DF, 1);
try test__ffssi2(0x000000E0, 6);
try test__ffssi2(0x000000E1, 1);
try test__ffssi2(0x000000E2, 2);
try test__ffssi2(0x000000E3, 1);
try test__ffssi2(0x000000E4, 3);
try test__ffssi2(0x000000E5, 1);
try test__ffssi2(0x000000E6, 2);
try test__ffssi2(0x000000E7, 1);
try test__ffssi2(0x000000E8, 4);
try test__ffssi2(0x000000E9, 1);
try test__ffssi2(0x000000EA, 2);
try test__ffssi2(0x000000EB, 1);
try test__ffssi2(0x000000EC, 3);
try test__ffssi2(0x000000ED, 1);
try test__ffssi2(0x000000EE, 2);
try test__ffssi2(0x000000EF, 1);
try test__ffssi2(0x000000F0, 5);
try test__ffssi2(0x000000F1, 1);
try test__ffssi2(0x000000F2, 2);
try test__ffssi2(0x000000F3, 1);
try test__ffssi2(0x000000F4, 3);
try test__ffssi2(0x000000F5, 1);
try test__ffssi2(0x000000F6, 2);
try test__ffssi2(0x000000F7, 1);
try test__ffssi2(0x000000F8, 4);
try test__ffssi2(0x000000F9, 1);
try test__ffssi2(0x000000FA, 2);
try test__ffssi2(0x000000FB, 1);
try test__ffssi2(0x000000FC, 3);
try test__ffssi2(0x000000FD, 1);
try test__ffssi2(0x000000FE, 2);
try test__ffssi2(0x000000FF, 1);
try test__ffssi2(0x00000000, 0);
try test__ffssi2(0x80000000, 32);
try test__ffssi2(0x40000000, 31);
try test__ffssi2(0x20000000, 30);
try test__ffssi2(0x10000000, 29);
try test__ffssi2(0x08000000, 28);
try test__ffssi2(0x04000000, 27);
try test__ffssi2(0x02000000, 26);
try test__ffssi2(0x01000000, 25);
try test__ffssi2(0x00800000, 24);
try test__ffssi2(0x00400000, 23);
try test__ffssi2(0x00200000, 22);
try test__ffssi2(0x00100000, 21);
try test__ffssi2(0x00080000, 20);
try test__ffssi2(0x00040000, 19);
try test__ffssi2(0x00020000, 18);
try test__ffssi2(0x00010000, 17);
try test__ffssi2(0x00008000, 16);
try test__ffssi2(0x00004000, 15);
try test__ffssi2(0x00002000, 14);
try test__ffssi2(0x00001000, 13);
try test__ffssi2(0x00000800, 12);
try test__ffssi2(0x00000400, 11);
try test__ffssi2(0x00000200, 10);
try test__ffssi2(0x00000100, 9);
} | lib/std/special/compiler_rt/ffssi2_test.zig |
const std = @import("std");
const print = std.debug.print;
usingnamespace @import("common.zig");
usingnamespace @import("value.zig");
usingnamespace @import("chunk.zig");
usingnamespace @import("compiler.zig");
usingnamespace @import("scanner.zig");
usingnamespace @import("parser.zig");
pub const InterpretResult = enum {
INTERPRET_OK, INTERPRET_COMPILE_ERROR, INTERPRET_RUNTIME_ERROR
};
const STACK_MAX = 256;
pub const VM = struct {
chunk: *Chunk,
ip: [*]u8, //instruction pointer
stack: [STACK_MAX]Value,
stackTop: [*]Value,
allocator: *std.mem.Allocator,
heap: Heap,
objects: ?*Obj, // 全局分配的所有对象集合
strings: String2OjStringMap, // 字符串常量池
globals: ObjString2Value, // 全局变量
pub fn init(allocator: *std.mem.Allocator) VM {
return VM{
.chunk = undefined,
.ip = undefined, //chunk.code.items.ptr,
.stack = undefined,
.stackTop = undefined,
.allocator = allocator,
.heap = undefined,
.objects = null,
.strings = String2OjStringMap.init(allocator),
.globals = ObjString2Value.init(allocator),
};
}
pub fn restStack(self: *VM) void {
self.stackTop = &self.stack;
}
pub fn deinit(self: *VM) void {
self.strings.deinit();
self.globals.deinit();
}
pub fn interpret(self: *VM, source: []const u8) !InterpretResult {
var chunk = Chunk.init(self.allocator);
defer chunk.deinit();
if (!(try self.compile(source, &chunk))) {
return .INTERPRET_RUNTIME_ERROR;
}
self.chunk = &chunk;
self.ip = self.chunk.code.items.ptr;
return try self.run();
}
fn push(self: *VM, value: Value) void {
self.stackTop[0] = value;
self.stackTop += 1;
}
fn pop(self: *VM) Value {
self.stackTop -= 1;
return self.stackTop[0];
}
fn peek(self: *VM, distance: usize) Value {
const value = self.stackTop - 1 - distance;
return value[0];
}
fn runtimeError(self: *VM, comptime format: []const u8, args: anytype) void {
print(format, args);
print("\n", .{});
const instruction = @ptrToInt(self.ip) - @ptrToInt(self.chunk.code.items.ptr) - 1;
const line = self.chunk.lines.items[instruction];
print("[line {}] in script\n", .{line});
self.restStack();
}
fn run(self: *VM) !InterpretResult {
while (true) {
if (DEBUG_TRACE_EXECUTION) {
print(" ", .{});
var slot: [*]Value = &self.stack;
while (@ptrToInt(slot) < @ptrToInt(self.stackTop)) {
print("[ ", .{});
printValue(slot[0]);
print(" ]", .{});
slot += 1;
}
print("\n", .{});
_ = self.chunk.disassembleInstruction(@ptrToInt(self.ip) - @ptrToInt(self.chunk.code.items.ptr));
}
const instruction = @intToEnum(OpCode, self.readByte());
switch (instruction) {
.OP_CONSTANT => {
const constant = self.readConstant();
self.push(constant);
},
.OP_NIL => self.push(NIL_VAL()),
.OP_FALSE => self.push(BOOL_VAL(false)),
.OP_TRUE => self.push(BOOL_VAL(true)),
.OP_EQUAL => {
const b = self.pop();
const a = self.pop();
self.push(BOOL_VAL(valuesEqual(a, b)));
},
.OP_POP => _ = self.pop(),
.OP_DEFINE_GLOBAL => {
const name = self.readString();
try self.globals.put(name, self.peek(0));
_ = self.pop();
},
.OP_GET_LOCAL => {
const slot = self.readByte();
self.push(self.stack[slot]);
},
.OP_SET_LOCAL => {
const slot = self.readByte();
self.stack[slot] = self.peek(0);
},
.OP_GET_GLOBAL => {
const name = self.readString();
if (self.globals.get(name)) |value| {
self.push(value);
} else {
self.runtimeError("Undefined variable '{}'", .{name.chars});
return .INTERPRET_RUNTIME_ERROR;
}
},
.OP_SET_GLOBAL => {
const name = self.readString();
if (self.globals.get(name)) |value| {
try self.globals.put(name, self.peek(0));
} else {
self.runtimeError("Undefined variable '{}'", .{name.chars});
return .INTERPRET_RUNTIME_ERROR;
}
},
.OP_JUMP_IF_FALSE => {
const offset = self.readShort();
if (isFalsey(self.peek(0))) self.ip += offset;
},
.OP_ADD,
.OP_SUBTRACT,
.OP_MULTIPLY,
.OP_DIVIDE,
.OP_GREATER,
.OP_LESS,
=> {
if (IS_NUMBER(self.peek(0)) and IS_NUMBER(self.peek(1))) {
self.binaryOp(instruction);
} else if (IS_STRING(self.peek(0)) and IS_STRING(self.peek(1))) {
switch (instruction) {
.OP_ADD => {
try self.concatenate();
},
else => {
self.runtimeError("Operands must be a numbers", .{});
return .INTERPRET_RUNTIME_ERROR;
},
}
} else {
self.runtimeError("Operands must be a numbers", .{});
return .INTERPRET_RUNTIME_ERROR;
}
},
.OP_NOT => {
self.push(BOOL_VAL(isFalsey(self.pop())));
},
.OP_NEGATE => {
if (!IS_NUMBER(self.peek(0))) {
self.runtimeError("Operand must be a number", .{});
return .INTERPRET_RUNTIME_ERROR;
}
self.push(NUMBER_VAL(-AS_NUMBER(self.pop())));
},
.OP_PRINT => {
printValue(self.pop());
print("\n", .{});
},
.OP_RETURN => {
return .INTERPRET_OK;
},
}
}
}
fn concatenate(self: *VM) !void {
const b = AS_STRING(self.pop());
const a = AS_STRING(self.pop());
const arrayChars = try self.allocator.alloc(u8, a.chars.len + b.chars.len);
std.mem.copy(u8, arrayChars, a.chars);
std.mem.copy(u8, arrayChars[a.chars.len..], b.chars);
self.push(OBJ_VAL(@ptrCast(*Obj, try self.heap.takeString(arrayChars))));
}
fn binaryOp(self: *VM, op: OpCode) void {
const b = AS_NUMBER(self.pop());
const a = AS_NUMBER(self.pop());
switch (op) {
.OP_ADD => self.push(NUMBER_VAL(a + b)),
.OP_SUBTRACT => self.push(NUMBER_VAL(a - b)),
.OP_MULTIPLY => self.push(NUMBER_VAL(a * b)),
.OP_DIVIDE => self.push(NUMBER_VAL(a / b)),
.OP_GREATER => self.push(BOOL_VAL(a > b)),
.OP_LESS => self.push(BOOL_VAL(a < b)),
else => unreachable,
}
}
fn readConstant(self: *VM) Value {
return self.chunk.constants.items[self.readByte()];
}
fn readByte(self: *VM) u8 {
var res = self.ip[0];
self.ip += 1;
return res;
}
fn readShort(self: *VM) u16 {
var offset = @intCast(u16, self.ip[0]) << 8;
offset |= self.ip[1];
self.ip += 2;
return offset;
}
fn readString(self: *VM) *ObjString {
return AS_STRING(self.readConstant());
}
fn compile(self: *VM, source: []const u8, chunk: *Chunk) !bool {
var compiler = Compiler.init(self, chunk);
var scanner = Scanner.init(source);
var parser = Parser.init(&compiler, &scanner);
parser.advance();
while (!parser.match(.TOKEN_EOF)) {
try parser.declaration();
}
try parser.endParse();
return !parser.hadError;
}
// nil and false is false
fn isFalsey(value: Value) bool {
return IS_NIL(value) or (IS_BOOL(value) and !AS_BOOL(value));
}
}; | vm/src/vm.zig |
const std = @import("std");
const mem = std.mem;
const PatternSyntax = @This();
allocator: *mem.Allocator,
array: []bool,
lo: u21 = 33,
hi: u21 = 65094,
pub fn init(allocator: *mem.Allocator) !PatternSyntax {
var instance = PatternSyntax{
.allocator = allocator,
.array = try allocator.alloc(bool, 65062),
};
mem.set(bool, instance.array, false);
var index: u21 = 0;
index = 0;
while (index <= 2) : (index += 1) {
instance.array[index] = true;
}
instance.array[3] = true;
index = 4;
while (index <= 6) : (index += 1) {
instance.array[index] = true;
}
instance.array[7] = true;
instance.array[8] = true;
instance.array[9] = true;
instance.array[10] = true;
instance.array[11] = true;
instance.array[12] = true;
index = 13;
while (index <= 14) : (index += 1) {
instance.array[index] = true;
}
index = 25;
while (index <= 26) : (index += 1) {
instance.array[index] = true;
}
index = 27;
while (index <= 29) : (index += 1) {
instance.array[index] = true;
}
index = 30;
while (index <= 31) : (index += 1) {
instance.array[index] = true;
}
instance.array[58] = true;
instance.array[59] = true;
instance.array[60] = true;
instance.array[61] = true;
instance.array[63] = true;
instance.array[90] = true;
instance.array[91] = true;
instance.array[92] = true;
instance.array[93] = true;
instance.array[128] = true;
index = 129;
while (index <= 132) : (index += 1) {
instance.array[index] = true;
}
instance.array[133] = true;
instance.array[134] = true;
instance.array[136] = true;
instance.array[138] = true;
instance.array[139] = true;
instance.array[141] = true;
instance.array[143] = true;
instance.array[144] = true;
instance.array[149] = true;
instance.array[154] = true;
instance.array[158] = true;
instance.array[182] = true;
instance.array[214] = true;
index = 8175;
while (index <= 8180) : (index += 1) {
instance.array[index] = true;
}
index = 8181;
while (index <= 8182) : (index += 1) {
instance.array[index] = true;
}
instance.array[8183] = true;
instance.array[8184] = true;
instance.array[8185] = true;
index = 8186;
while (index <= 8187) : (index += 1) {
instance.array[index] = true;
}
instance.array[8188] = true;
instance.array[8189] = true;
instance.array[8190] = true;
index = 8191;
while (index <= 8198) : (index += 1) {
instance.array[index] = true;
}
index = 8207;
while (index <= 8215) : (index += 1) {
instance.array[index] = true;
}
instance.array[8216] = true;
instance.array[8217] = true;
index = 8218;
while (index <= 8221) : (index += 1) {
instance.array[index] = true;
}
index = 8224;
while (index <= 8226) : (index += 1) {
instance.array[index] = true;
}
instance.array[8227] = true;
instance.array[8228] = true;
instance.array[8229] = true;
index = 8230;
while (index <= 8240) : (index += 1) {
instance.array[index] = true;
}
instance.array[8241] = true;
instance.array[8242] = true;
index = 8244;
while (index <= 8253) : (index += 1) {
instance.array[index] = true;
}
index = 8559;
while (index <= 8563) : (index += 1) {
instance.array[index] = true;
}
index = 8564;
while (index <= 8568) : (index += 1) {
instance.array[index] = true;
}
index = 8569;
while (index <= 8570) : (index += 1) {
instance.array[index] = true;
}
index = 8571;
while (index <= 8574) : (index += 1) {
instance.array[index] = true;
}
instance.array[8575] = true;
index = 8576;
while (index <= 8577) : (index += 1) {
instance.array[index] = true;
}
instance.array[8578] = true;
index = 8579;
while (index <= 8580) : (index += 1) {
instance.array[index] = true;
}
instance.array[8581] = true;
index = 8582;
while (index <= 8588) : (index += 1) {
instance.array[index] = true;
}
instance.array[8589] = true;
index = 8590;
while (index <= 8620) : (index += 1) {
instance.array[index] = true;
}
index = 8621;
while (index <= 8622) : (index += 1) {
instance.array[index] = true;
}
index = 8623;
while (index <= 8624) : (index += 1) {
instance.array[index] = true;
}
instance.array[8625] = true;
instance.array[8626] = true;
instance.array[8627] = true;
index = 8628;
while (index <= 8658) : (index += 1) {
instance.array[index] = true;
}
index = 8659;
while (index <= 8926) : (index += 1) {
instance.array[index] = true;
}
index = 8927;
while (index <= 8934) : (index += 1) {
instance.array[index] = true;
}
instance.array[8935] = true;
instance.array[8936] = true;
instance.array[8937] = true;
instance.array[8938] = true;
index = 8939;
while (index <= 8958) : (index += 1) {
instance.array[index] = true;
}
index = 8959;
while (index <= 8960) : (index += 1) {
instance.array[index] = true;
}
index = 8961;
while (index <= 8967) : (index += 1) {
instance.array[index] = true;
}
instance.array[8968] = true;
instance.array[8969] = true;
index = 8970;
while (index <= 9050) : (index += 1) {
instance.array[index] = true;
}
instance.array[9051] = true;
index = 9052;
while (index <= 9081) : (index += 1) {
instance.array[index] = true;
}
index = 9082;
while (index <= 9106) : (index += 1) {
instance.array[index] = true;
}
index = 9107;
while (index <= 9146) : (index += 1) {
instance.array[index] = true;
}
index = 9147;
while (index <= 9152) : (index += 1) {
instance.array[index] = true;
}
index = 9153;
while (index <= 9221) : (index += 1) {
instance.array[index] = true;
}
index = 9222;
while (index <= 9246) : (index += 1) {
instance.array[index] = true;
}
index = 9247;
while (index <= 9257) : (index += 1) {
instance.array[index] = true;
}
index = 9258;
while (index <= 9278) : (index += 1) {
instance.array[index] = true;
}
index = 9439;
while (index <= 9621) : (index += 1) {
instance.array[index] = true;
}
instance.array[9622] = true;
index = 9623;
while (index <= 9631) : (index += 1) {
instance.array[index] = true;
}
instance.array[9632] = true;
index = 9633;
while (index <= 9686) : (index += 1) {
instance.array[index] = true;
}
index = 9687;
while (index <= 9694) : (index += 1) {
instance.array[index] = true;
}
index = 9695;
while (index <= 9805) : (index += 1) {
instance.array[index] = true;
}
instance.array[9806] = true;
index = 9807;
while (index <= 10054) : (index += 1) {
instance.array[index] = true;
}
instance.array[10055] = true;
instance.array[10056] = true;
instance.array[10057] = true;
instance.array[10058] = true;
instance.array[10059] = true;
instance.array[10060] = true;
instance.array[10061] = true;
instance.array[10062] = true;
instance.array[10063] = true;
instance.array[10064] = true;
instance.array[10065] = true;
instance.array[10066] = true;
instance.array[10067] = true;
instance.array[10068] = true;
index = 10099;
while (index <= 10142) : (index += 1) {
instance.array[index] = true;
}
index = 10143;
while (index <= 10147) : (index += 1) {
instance.array[index] = true;
}
instance.array[10148] = true;
instance.array[10149] = true;
index = 10150;
while (index <= 10180) : (index += 1) {
instance.array[index] = true;
}
instance.array[10181] = true;
instance.array[10182] = true;
instance.array[10183] = true;
instance.array[10184] = true;
instance.array[10185] = true;
instance.array[10186] = true;
instance.array[10187] = true;
instance.array[10188] = true;
instance.array[10189] = true;
instance.array[10190] = true;
index = 10191;
while (index <= 10206) : (index += 1) {
instance.array[index] = true;
}
index = 10207;
while (index <= 10462) : (index += 1) {
instance.array[index] = true;
}
index = 10463;
while (index <= 10593) : (index += 1) {
instance.array[index] = true;
}
instance.array[10594] = true;
instance.array[10595] = true;
instance.array[10596] = true;
instance.array[10597] = true;
instance.array[10598] = true;
instance.array[10599] = true;
instance.array[10600] = true;
instance.array[10601] = true;
instance.array[10602] = true;
instance.array[10603] = true;
instance.array[10604] = true;
instance.array[10605] = true;
instance.array[10606] = true;
instance.array[10607] = true;
instance.array[10608] = true;
instance.array[10609] = true;
instance.array[10610] = true;
instance.array[10611] = true;
instance.array[10612] = true;
instance.array[10613] = true;
instance.array[10614] = true;
instance.array[10615] = true;
index = 10616;
while (index <= 10678) : (index += 1) {
instance.array[index] = true;
}
instance.array[10679] = true;
instance.array[10680] = true;
instance.array[10681] = true;
instance.array[10682] = true;
index = 10683;
while (index <= 10714) : (index += 1) {
instance.array[index] = true;
}
instance.array[10715] = true;
instance.array[10716] = true;
index = 10717;
while (index <= 10974) : (index += 1) {
instance.array[index] = true;
}
index = 10975;
while (index <= 11022) : (index += 1) {
instance.array[index] = true;
}
index = 11023;
while (index <= 11043) : (index += 1) {
instance.array[index] = true;
}
index = 11044;
while (index <= 11045) : (index += 1) {
instance.array[index] = true;
}
index = 11046;
while (index <= 11051) : (index += 1) {
instance.array[index] = true;
}
index = 11052;
while (index <= 11090) : (index += 1) {
instance.array[index] = true;
}
index = 11091;
while (index <= 11092) : (index += 1) {
instance.array[index] = true;
}
index = 11093;
while (index <= 11124) : (index += 1) {
instance.array[index] = true;
}
instance.array[11125] = true;
index = 11126;
while (index <= 11230) : (index += 1) {
instance.array[index] = true;
}
index = 11743;
while (index <= 11744) : (index += 1) {
instance.array[index] = true;
}
instance.array[11745] = true;
instance.array[11746] = true;
instance.array[11747] = true;
instance.array[11748] = true;
index = 11749;
while (index <= 11751) : (index += 1) {
instance.array[index] = true;
}
instance.array[11752] = true;
instance.array[11753] = true;
instance.array[11754] = true;
instance.array[11755] = true;
instance.array[11756] = true;
index = 11757;
while (index <= 11765) : (index += 1) {
instance.array[index] = true;
}
instance.array[11766] = true;
index = 11767;
while (index <= 11768) : (index += 1) {
instance.array[index] = true;
}
instance.array[11769] = true;
instance.array[11770] = true;
instance.array[11771] = true;
instance.array[11772] = true;
index = 11773;
while (index <= 11774) : (index += 1) {
instance.array[index] = true;
}
instance.array[11775] = true;
instance.array[11776] = true;
instance.array[11777] = true;
instance.array[11778] = true;
instance.array[11779] = true;
instance.array[11780] = true;
instance.array[11781] = true;
instance.array[11782] = true;
instance.array[11783] = true;
instance.array[11784] = true;
index = 11785;
while (index <= 11789) : (index += 1) {
instance.array[index] = true;
}
instance.array[11790] = true;
index = 11791;
while (index <= 11800) : (index += 1) {
instance.array[index] = true;
}
index = 11801;
while (index <= 11802) : (index += 1) {
instance.array[index] = true;
}
index = 11803;
while (index <= 11806) : (index += 1) {
instance.array[index] = true;
}
instance.array[11807] = true;
instance.array[11808] = true;
instance.array[11809] = true;
index = 11810;
while (index <= 11822) : (index += 1) {
instance.array[index] = true;
}
index = 11823;
while (index <= 11824) : (index += 1) {
instance.array[index] = true;
}
instance.array[11825] = true;
index = 11826;
while (index <= 11870) : (index += 1) {
instance.array[index] = true;
}
index = 12256;
while (index <= 12258) : (index += 1) {
instance.array[index] = true;
}
instance.array[12263] = true;
instance.array[12264] = true;
instance.array[12265] = true;
instance.array[12266] = true;
instance.array[12267] = true;
instance.array[12268] = true;
instance.array[12269] = true;
instance.array[12270] = true;
instance.array[12271] = true;
instance.array[12272] = true;
index = 12273;
while (index <= 12274) : (index += 1) {
instance.array[index] = true;
}
instance.array[12275] = true;
instance.array[12276] = true;
instance.array[12277] = true;
instance.array[12278] = true;
instance.array[12279] = true;
instance.array[12280] = true;
instance.array[12281] = true;
instance.array[12282] = true;
instance.array[12283] = true;
instance.array[12284] = true;
index = 12285;
while (index <= 12286) : (index += 1) {
instance.array[index] = true;
}
instance.array[12287] = true;
instance.array[12303] = true;
instance.array[64797] = true;
instance.array[64798] = true;
index = 65060;
while (index <= 65061) : (index += 1) {
instance.array[index] = true;
}
// Placeholder: 0. Struct name, 1. Code point kind
return instance;
}
pub fn deinit(self: *PatternSyntax) void {
self.allocator.free(self.array);
}
// isPatternSyntax checks if cp is of the kind Pattern_Syntax.
pub fn isPatternSyntax(self: PatternSyntax, 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/PropList/PatternSyntax.zig |
const builtin = @import("builtin");
const is_test = builtin.is_test;
comptime {
const linkage = if (is_test) builtin.GlobalLinkage.Internal else builtin.GlobalLinkage.Weak;
const strong_linkage = if (is_test) builtin.GlobalLinkage.Internal else builtin.GlobalLinkage.Strong;
@export("__letf2", @import("comparetf2.zig").__letf2, linkage);
@export("__getf2", @import("comparetf2.zig").__getf2, linkage);
if (!is_test) {
// only create these aliases when not testing
@export("__cmptf2", @import("comparetf2.zig").__letf2, linkage);
@export("__eqtf2", @import("comparetf2.zig").__letf2, linkage);
@export("__lttf2", @import("comparetf2.zig").__letf2, linkage);
@export("__netf2", @import("comparetf2.zig").__letf2, linkage);
@export("__gttf2", @import("comparetf2.zig").__getf2, linkage);
}
@export("__unordtf2", @import("comparetf2.zig").__unordtf2, linkage);
@export("__fixunssfsi", @import("fixunssfsi.zig").__fixunssfsi, linkage);
@export("__fixunssfdi", @import("fixunssfdi.zig").__fixunssfdi, linkage);
@export("__fixunssfti", @import("fixunssfti.zig").__fixunssfti, linkage);
@export("__fixunsdfsi", @import("fixunsdfsi.zig").__fixunsdfsi, linkage);
@export("__fixunsdfdi", @import("fixunsdfdi.zig").__fixunsdfdi, linkage);
@export("__fixunsdfti", @import("fixunsdfti.zig").__fixunsdfti, linkage);
@export("__fixunstfsi", @import("fixunstfsi.zig").__fixunstfsi, linkage);
@export("__fixunstfdi", @import("fixunstfdi.zig").__fixunstfdi, linkage);
@export("__fixunstfti", @import("fixunstfti.zig").__fixunstfti, linkage);
@export("__udivmoddi4", @import("udivmoddi4.zig").__udivmoddi4, linkage);
@export("__udivmodti4", @import("udivmodti4.zig").__udivmodti4, linkage);
@export("__udivti3", @import("udivti3.zig").__udivti3, linkage);
@export("__umodti3", @import("umodti3.zig").__umodti3, linkage);
@export("__udivsi3", __udivsi3, linkage);
@export("__udivdi3", __udivdi3, linkage);
@export("__umoddi3", __umoddi3, linkage);
@export("__udivmodsi4", __udivmodsi4, linkage);
if (isArmArch()) {
@export("__aeabi_uldivmod", __aeabi_uldivmod, linkage);
@export("__aeabi_uidivmod", __aeabi_uidivmod, linkage);
@export("__aeabi_uidiv", __udivsi3, linkage);
}
if (builtin.os == builtin.Os.windows) {
switch (builtin.arch) {
builtin.Arch.i386 => {
if (!builtin.link_libc) {
@export("_chkstk", _chkstk, strong_linkage);
@export("__chkstk_ms", __chkstk_ms, linkage);
}
@export("_aulldiv", @import("aulldiv.zig")._aulldiv, strong_linkage);
@export("_aullrem", @import("aullrem.zig")._aullrem, strong_linkage);
},
builtin.Arch.x86_64 => {
if (!builtin.link_libc) {
@export("__chkstk", __chkstk, strong_linkage);
@export("___chkstk_ms", ___chkstk_ms, linkage);
}
},
else => {},
}
}
}
const assert = @import("../../index.zig").debug.assert;
const __udivmoddi4 = @import("udivmoddi4.zig").__udivmoddi4;
// Avoid dragging in the runtime safety mechanisms into this .o file,
// unless we're trying to test this file.
pub fn panic(msg: []const u8, error_return_trace: ?&builtin.StackTrace) noreturn {
@setCold(true);
if (is_test) {
@import("std").debug.panic("{}", msg);
} else {
unreachable;
}
}
extern fn __udivdi3(a: u64, b: u64) u64 {
@setRuntimeSafety(is_test);
return __udivmoddi4(a, b, null);
}
extern fn __umoddi3(a: u64, b: u64) u64 {
@setRuntimeSafety(is_test);
var r: u64 = undefined;
_ = __udivmoddi4(a, b, &r);
return r;
}
const AeabiUlDivModResult = extern struct {
quot: u64,
rem: u64,
};
extern fn __aeabi_uldivmod(numerator: u64, denominator: u64) AeabiUlDivModResult {
@setRuntimeSafety(is_test);
var result: AeabiUlDivModResult = undefined;
result.quot = __udivmoddi4(numerator, denominator, &result.rem);
return result;
}
fn isArmArch() bool {
return switch (builtin.arch) {
builtin.Arch.armv8_2a,
builtin.Arch.armv8_1a,
builtin.Arch.armv8,
builtin.Arch.armv8r,
builtin.Arch.armv8m_baseline,
builtin.Arch.armv8m_mainline,
builtin.Arch.armv7,
builtin.Arch.armv7em,
builtin.Arch.armv7m,
builtin.Arch.armv7s,
builtin.Arch.armv7k,
builtin.Arch.armv6,
builtin.Arch.armv6m,
builtin.Arch.armv6k,
builtin.Arch.armv6t2,
builtin.Arch.armv5,
builtin.Arch.armv5te,
builtin.Arch.armv4t,
builtin.Arch.armebv8_2a,
builtin.Arch.armebv8_1a,
builtin.Arch.armebv8,
builtin.Arch.armebv8r,
builtin.Arch.armebv8m_baseline,
builtin.Arch.armebv8m_mainline,
builtin.Arch.armebv7,
builtin.Arch.armebv7em,
builtin.Arch.armebv7m,
builtin.Arch.armebv7s,
builtin.Arch.armebv7k,
builtin.Arch.armebv6,
builtin.Arch.armebv6m,
builtin.Arch.armebv6k,
builtin.Arch.armebv6t2,
builtin.Arch.armebv5,
builtin.Arch.armebv5te,
builtin.Arch.armebv4t => true,
else => false,
};
}
nakedcc fn __aeabi_uidivmod() void {
@setRuntimeSafety(false);
asm volatile (
\\ push { lr }
\\ sub sp, sp, #4
\\ mov r2, sp
\\ bl __udivmodsi4
\\ ldr r1, [sp]
\\ add sp, sp, #4
\\ pop { pc }
::: "r2", "r1");
}
// _chkstk (_alloca) routine - probe stack between %esp and (%esp-%eax) in 4k increments,
// then decrement %esp by %eax. Preserves all registers except %esp and flags.
// This routine is windows specific
// http://msdn.microsoft.com/en-us/library/ms648426.aspx
nakedcc fn _chkstk() align(4) void {
@setRuntimeSafety(false);
asm volatile (
\\ push %%ecx
\\ push %%eax
\\ cmp $0x1000,%%eax
\\ lea 12(%%esp),%%ecx
\\ jb 1f
\\ 2:
\\ sub $0x1000,%%ecx
\\ test %%ecx,(%%ecx)
\\ sub $0x1000,%%eax
\\ cmp $0x1000,%%eax
\\ ja 2b
\\ 1:
\\ sub %%eax,%%ecx
\\ test %%ecx,(%%ecx)
\\ pop %%eax
\\ pop %%ecx
\\ ret
);
}
nakedcc fn __chkstk() align(4) void {
@setRuntimeSafety(false);
asm volatile (
\\ push %%rcx
\\ push %%rax
\\ cmp $0x1000,%%rax
\\ lea 24(%%rsp),%%rcx
\\ jb 1f
\\2:
\\ sub $0x1000,%%rcx
\\ test %%rcx,(%%rcx)
\\ sub $0x1000,%%rax
\\ cmp $0x1000,%%rax
\\ ja 2b
\\1:
\\ sub %%rax,%%rcx
\\ test %%rcx,(%%rcx)
\\ pop %%rax
\\ pop %%rcx
\\ ret
);
}
// _chkstk routine
// This routine is windows specific
// http://msdn.microsoft.com/en-us/library/ms648426.aspx
nakedcc fn __chkstk_ms() align(4) void {
@setRuntimeSafety(false);
asm volatile (
\\ push %%ecx
\\ push %%eax
\\ cmp $0x1000,%%eax
\\ lea 12(%%esp),%%ecx
\\ jb 1f
\\ 2:
\\ sub $0x1000,%%ecx
\\ test %%ecx,(%%ecx)
\\ sub $0x1000,%%eax
\\ cmp $0x1000,%%eax
\\ ja 2b
\\ 1:
\\ sub %%eax,%%ecx
\\ test %%ecx,(%%ecx)
\\ pop %%eax
\\ pop %%ecx
\\ ret
);
}
nakedcc fn ___chkstk_ms() align(4) void {
@setRuntimeSafety(false);
asm volatile (
\\ push %%rcx
\\ push %%rax
\\ cmp $0x1000,%%rax
\\ lea 24(%%rsp),%%rcx
\\ jb 1f
\\2:
\\ sub $0x1000,%%rcx
\\ test %%rcx,(%%rcx)
\\ sub $0x1000,%%rax
\\ cmp $0x1000,%%rax
\\ ja 2b
\\1:
\\ sub %%rax,%%rcx
\\ test %%rcx,(%%rcx)
\\ pop %%rax
\\ pop %%rcx
\\ ret
);
}
extern fn __udivmodsi4(a: u32, b: u32, rem: &u32) u32 {
@setRuntimeSafety(is_test);
const d = __udivsi3(a, b);
*rem = u32(i32(a) -% (i32(d) * i32(b)));
return d;
}
extern fn __udivsi3(n: u32, d: u32) u32 {
@setRuntimeSafety(is_test);
const n_uword_bits: c_uint = u32.bit_count;
// special cases
if (d == 0)
return 0; // ?!
if (n == 0)
return 0;
var sr = @bitCast(c_uint, c_int(@clz(d)) - c_int(@clz(n)));
// 0 <= sr <= n_uword_bits - 1 or sr large
if (sr > n_uword_bits - 1) // d > r
return 0;
if (sr == n_uword_bits - 1) // d == 1
return n;
sr += 1;
// 1 <= sr <= n_uword_bits - 1
// Not a special case
var q: u32 = n << u5(n_uword_bits - sr);
var r: u32 = n >> u5(sr);
var carry: u32 = 0;
while (sr > 0) : (sr -= 1) {
// r:q = ((r:q) << 1) | carry
r = (r << 1) | (q >> u5(n_uword_bits - 1));
q = (q << 1) | carry;
// carry = 0;
// if (r.all >= d.all)
// {
// r.all -= d.all;
// carry = 1;
// }
const s = i32(d -% r -% 1) >> u5(n_uword_bits - 1);
carry = u32(s & 1);
r -= d & @bitCast(u32, s);
}
q = (q << 1) | carry;
return q;
}
test "test_umoddi3" {
test_one_umoddi3(0, 1, 0);
test_one_umoddi3(2, 1, 0);
test_one_umoddi3(0x8000000000000000, 1, 0x0);
test_one_umoddi3(0x8000000000000000, 2, 0x0);
test_one_umoddi3(0xFFFFFFFFFFFFFFFF, 2, 0x1);
}
fn test_one_umoddi3(a: u64, b: u64, expected_r: u64) void {
const r = __umoddi3(a, b);
assert(r == expected_r);
}
test "test_udivsi3" {
const cases = [][3]u32 {
[]u32{0x00000000, 0x00000001, 0x00000000},
[]u32{0x00000000, 0x00000002, 0x00000000},
[]u32{0x00000000, 0x00000003, 0x00000000},
[]u32{0x00000000, 0x00000010, 0x00000000},
[]u32{0x00000000, 0x078644FA, 0x00000000},
[]u32{0x00000000, 0x0747AE14, 0x00000000},
[]u32{0x00000000, 0x7FFFFFFF, 0x00000000},
[]u32{0x00000000, 0x80000000, 0x00000000},
[]u32{0x00000000, 0xFFFFFFFD, 0x00000000},
[]u32{0x00000000, 0xFFFFFFFE, 0x00000000},
[]u32{0x00000000, 0xFFFFFFFF, 0x00000000},
[]u32{0x00000001, 0x00000001, 0x00000001},
[]u32{0x00000001, 0x00000002, 0x00000000},
[]u32{0x00000001, 0x00000003, 0x00000000},
[]u32{0x00000001, 0x00000010, 0x00000000},
[]u32{0x00000001, 0x078644FA, 0x00000000},
[]u32{0x00000001, 0x0747AE14, 0x00000000},
[]u32{0x00000001, 0x7FFFFFFF, 0x00000000},
[]u32{0x00000001, 0x80000000, 0x00000000},
[]u32{0x00000001, 0xFFFFFFFD, 0x00000000},
[]u32{0x00000001, 0xFFFFFFFE, 0x00000000},
[]u32{0x00000001, 0xFFFFFFFF, 0x00000000},
[]u32{0x00000002, 0x00000001, 0x00000002},
[]u32{0x00000002, 0x00000002, 0x00000001},
[]u32{0x00000002, 0x00000003, 0x00000000},
[]u32{0x00000002, 0x00000010, 0x00000000},
[]u32{0x00000002, 0x078644FA, 0x00000000},
[]u32{0x00000002, 0x0747AE14, 0x00000000},
[]u32{0x00000002, 0x7FFFFFFF, 0x00000000},
[]u32{0x00000002, 0x80000000, 0x00000000},
[]u32{0x00000002, 0xFFFFFFFD, 0x00000000},
[]u32{0x00000002, 0xFFFFFFFE, 0x00000000},
[]u32{0x00000002, 0xFFFFFFFF, 0x00000000},
[]u32{0x00000003, 0x00000001, 0x00000003},
[]u32{0x00000003, 0x00000002, 0x00000001},
[]u32{0x00000003, 0x00000003, 0x00000001},
[]u32{0x00000003, 0x00000010, 0x00000000},
[]u32{0x00000003, 0x078644FA, 0x00000000},
[]u32{0x00000003, 0x0747AE14, 0x00000000},
[]u32{0x00000003, 0x7FFFFFFF, 0x00000000},
[]u32{0x00000003, 0x80000000, 0x00000000},
[]u32{0x00000003, 0xFFFFFFFD, 0x00000000},
[]u32{0x00000003, 0xFFFFFFFE, 0x00000000},
[]u32{0x00000003, 0xFFFFFFFF, 0x00000000},
[]u32{0x00000010, 0x00000001, 0x00000010},
[]u32{0x00000010, 0x00000002, 0x00000008},
[]u32{0x00000010, 0x00000003, 0x00000005},
[]u32{0x00000010, 0x00000010, 0x00000001},
[]u32{0x00000010, 0x078644FA, 0x00000000},
[]u32{0x00000010, 0x0747AE14, 0x00000000},
[]u32{0x00000010, 0x7FFFFFFF, 0x00000000},
[]u32{0x00000010, 0x80000000, 0x00000000},
[]u32{0x00000010, 0xFFFFFFFD, 0x00000000},
[]u32{0x00000010, 0xFFFFFFFE, 0x00000000},
[]u32{0x00000010, 0xFFFFFFFF, 0x00000000},
[]u32{0x078644FA, 0x00000001, 0x078644FA},
[]u32{0x078644FA, 0x00000002, 0x03C3227D},
[]u32{0x078644FA, 0x00000003, 0x028216FE},
[]u32{0x078644FA, 0x00000010, 0x0078644F},
[]u32{0x078644FA, 0x078644FA, 0x00000001},
[]u32{0x078644FA, 0x0747AE14, 0x00000001},
[]u32{0x078644FA, 0x7FFFFFFF, 0x00000000},
[]u32{0x078644FA, 0x80000000, 0x00000000},
[]u32{0x078644FA, 0xFFFFFFFD, 0x00000000},
[]u32{0x078644FA, 0xFFFFFFFE, 0x00000000},
[]u32{0x078644FA, 0xFFFFFFFF, 0x00000000},
[]u32{0x0747AE14, 0x00000001, 0x0747AE14},
[]u32{0x0747AE14, 0x00000002, 0x03A3D70A},
[]u32{0x0747AE14, 0x00000003, 0x026D3A06},
[]u32{0x0747AE14, 0x00000010, 0x00747AE1},
[]u32{0x0747AE14, 0x078644FA, 0x00000000},
[]u32{0x0747AE14, 0x0747AE14, 0x00000001},
[]u32{0x0747AE14, 0x7FFFFFFF, 0x00000000},
[]u32{0x0747AE14, 0x80000000, 0x00000000},
[]u32{0x0747AE14, 0xFFFFFFFD, 0x00000000},
[]u32{0x0747AE14, 0xFFFFFFFE, 0x00000000},
[]u32{0x0747AE14, 0xFFFFFFFF, 0x00000000},
[]u32{0x7FFFFFFF, 0x00000001, 0x7FFFFFFF},
[]u32{0x7FFFFFFF, 0x00000002, 0x3FFFFFFF},
[]u32{0x7FFFFFFF, 0x00000003, 0x2AAAAAAA},
[]u32{0x7FFFFFFF, 0x00000010, 0x07FFFFFF},
[]u32{0x7FFFFFFF, 0x078644FA, 0x00000011},
[]u32{0x7FFFFFFF, 0x0747AE14, 0x00000011},
[]u32{0x7FFFFFFF, 0x7FFFFFFF, 0x00000001},
[]u32{0x7FFFFFFF, 0x80000000, 0x00000000},
[]u32{0x7FFFFFFF, 0xFFFFFFFD, 0x00000000},
[]u32{0x7FFFFFFF, 0xFFFFFFFE, 0x00000000},
[]u32{0x7FFFFFFF, 0xFFFFFFFF, 0x00000000},
[]u32{0x80000000, 0x00000001, 0x80000000},
[]u32{0x80000000, 0x00000002, 0x40000000},
[]u32{0x80000000, 0x00000003, 0x2AAAAAAA},
[]u32{0x80000000, 0x00000010, 0x08000000},
[]u32{0x80000000, 0x078644FA, 0x00000011},
[]u32{0x80000000, 0x0747AE14, 0x00000011},
[]u32{0x80000000, 0x7FFFFFFF, 0x00000001},
[]u32{0x80000000, 0x80000000, 0x00000001},
[]u32{0x80000000, 0xFFFFFFFD, 0x00000000},
[]u32{0x80000000, 0xFFFFFFFE, 0x00000000},
[]u32{0x80000000, 0xFFFFFFFF, 0x00000000},
[]u32{0xFFFFFFFD, 0x00000001, 0xFFFFFFFD},
[]u32{0xFFFFFFFD, 0x00000002, 0x7FFFFFFE},
[]u32{0xFFFFFFFD, 0x00000003, 0x55555554},
[]u32{0xFFFFFFFD, 0x00000010, 0x0FFFFFFF},
[]u32{0xFFFFFFFD, 0x078644FA, 0x00000022},
[]u32{0xFFFFFFFD, 0x0747AE14, 0x00000023},
[]u32{0xFFFFFFFD, 0x7FFFFFFF, 0x00000001},
[]u32{0xFFFFFFFD, 0x80000000, 0x00000001},
[]u32{0xFFFFFFFD, 0xFFFFFFFD, 0x00000001},
[]u32{0xFFFFFFFD, 0xFFFFFFFE, 0x00000000},
[]u32{0xFFFFFFFD, 0xFFFFFFFF, 0x00000000},
[]u32{0xFFFFFFFE, 0x00000001, 0xFFFFFFFE},
[]u32{0xFFFFFFFE, 0x00000002, 0x7FFFFFFF},
[]u32{0xFFFFFFFE, 0x00000003, 0x55555554},
[]u32{0xFFFFFFFE, 0x00000010, 0x0FFFFFFF},
[]u32{0xFFFFFFFE, 0x078644FA, 0x00000022},
[]u32{0xFFFFFFFE, 0x0747AE14, 0x00000023},
[]u32{0xFFFFFFFE, 0x7FFFFFFF, 0x00000002},
[]u32{0xFFFFFFFE, 0x80000000, 0x00000001},
[]u32{0xFFFFFFFE, 0xFFFFFFFD, 0x00000001},
[]u32{0xFFFFFFFE, 0xFFFFFFFE, 0x00000001},
[]u32{0xFFFFFFFE, 0xFFFFFFFF, 0x00000000},
[]u32{0xFFFFFFFF, 0x00000001, 0xFFFFFFFF},
[]u32{0xFFFFFFFF, 0x00000002, 0x7FFFFFFF},
[]u32{0xFFFFFFFF, 0x00000003, 0x55555555},
[]u32{0xFFFFFFFF, 0x00000010, 0x0FFFFFFF},
[]u32{0xFFFFFFFF, 0x078644FA, 0x00000022},
[]u32{0xFFFFFFFF, 0x0747AE14, 0x00000023},
[]u32{0xFFFFFFFF, 0x7FFFFFFF, 0x00000002},
[]u32{0xFFFFFFFF, 0x80000000, 0x00000001},
[]u32{0xFFFFFFFF, 0xFFFFFFFD, 0x00000001},
[]u32{0xFFFFFFFF, 0xFFFFFFFE, 0x00000001},
[]u32{0xFFFFFFFF, 0xFFFFFFFF, 0x00000001},
};
for (cases) |case| {
test_one_udivsi3(case[0], case[1], case[2]);
}
}
fn test_one_udivsi3(a: u32, b: u32, expected_q: u32) void {
const q: u32 = __udivsi3(a, b);
assert(q == expected_q);
} | std/special/compiler_rt/index.zig |
const std = @import("std");
// this can be used when pushing to an ImpulseQueue. it's all you need if you
// don't care about matching note-on and note-off events (which is only
// important for polyphony)
pub const IdGenerator = struct {
next_id: usize,
pub fn init() IdGenerator {
return IdGenerator {
.next_id = 1,
};
}
pub fn nextId(self: *IdGenerator) usize {
defer self.next_id += 1;
return self.next_id;
}
};
pub const Impulse = struct {
frame: usize, // frames (e.g. 44100 for one second in)
note_id: usize,
event_id: usize,
};
pub fn Notes(comptime NoteParamsType: type) type {
return struct {
pub const ImpulsesAndParamses = struct {
// these two slices will have the same length
impulses: []const Impulse,
paramses: []const NoteParamsType,
};
pub const ImpulseQueue = struct {
impulses_array: [32]Impulse,
paramses_array: [32]NoteParamsType,
length: usize,
next_event_id: usize,
pub fn init() ImpulseQueue {
return ImpulseQueue {
.impulses_array = undefined,
.paramses_array = undefined,
.length = 0,
.next_event_id = 1,
};
}
// return impulses and advance state.
// make sure to use the returned impulse list before pushing more
// stuff
// FIXME shouldn't this take in a span?
// although it's probably fine now because we're never using an
// impulse queue within something...
pub fn consume(self: *ImpulseQueue) ImpulsesAndParamses {
defer self.length = 0;
return ImpulsesAndParamses {
.impulses = self.impulses_array[0..self.length],
.paramses = self.paramses_array[0..self.length],
};
}
pub fn push(
self: *ImpulseQueue,
impulse_frame: usize,
note_id: usize,
params: NoteParamsType,
) void {
if (self.length >= self.impulses_array.len) {
// std.debug.warn("ImpulseQueue: no more slots\n"); // FIXME
return;
}
if (
self.length > 0 and
impulse_frame < self.impulses_array[self.length - 1].frame
) {
// you must push impulses in order. this could even be a panic
// std.debug.warn("ImpulseQueue: notes pushed out of order\n");
return;
}
self.impulses_array[self.length] = Impulse {
.frame = impulse_frame,
.note_id = note_id,
.event_id = self.next_event_id,
};
self.paramses_array[self.length] = params;
self.length += 1;
self.next_event_id += 1;
}
};
pub const SongEvent = struct {
params: NoteParamsType,
t: f32,
note_id: usize,
};
// follow a canned melody, creating impulses from it, one mix buffer
// at a time
pub const NoteTracker = struct {
song: []const SongEvent,
next_song_event: usize,
t: f32,
impulses_array: [32]Impulse, // internal storage
paramses_array: [32]NoteParamsType,
pub fn init(song: []const SongEvent) NoteTracker {
return .{
.song = song,
.next_song_event = 0,
.t = 0.0,
.impulses_array = undefined,
.paramses_array = undefined,
};
}
pub fn reset(self: *NoteTracker) void {
self.next_song_event = 0;
self.t = 0.0;
}
// return impulses for notes that fall within the upcoming buffer
// frame.
pub fn consume(
self: *NoteTracker,
sample_rate: f32,
out_len: usize,
) ImpulsesAndParamses {
var count: usize = 0;
const buf_time = @intToFloat(f32, out_len) / sample_rate;
var start_t = self.t;
const end_t = self.t + buf_time;
for (self.song[self.next_song_event..]) |song_event| {
const note_t = song_event.t;
// the notes must have been provided in chronological order
std.debug.assert(note_t >= start_t);
if (note_t < end_t) {
const f = (note_t - self.t) / buf_time; // 0 to 1
const rel_frame_index = std.math.min(
@floatToInt(usize, f * @intToFloat(f32, out_len)),
out_len - 1,
);
// TODO - do something graceful-ish when count >=
// self.impulse_array.len
self.next_song_event += 1;
self.impulses_array[count] = Impulse {
.frame = rel_frame_index,
.note_id = song_event.note_id,
.event_id = self.next_song_event,
};
self.paramses_array[count] = song_event.params;
count += 1;
start_t = note_t;
} else {
break;
}
}
self.t = end_t;
return ImpulsesAndParamses {
.impulses = self.impulses_array[0..count],
.paramses = self.paramses_array[0..count],
};
}
};
pub fn PolyphonyDispatcher(comptime polyphony: usize) type {
const SlotState = struct {
// each note-on/off combo has the same note_id. this is used
// to match them up
note_id: usize,
// note-on and off have unique event_ids. these monotonically
// increase and are used to determine the "stalest" slot (to
// be reused)
event_id: usize,
// polyphony only works when the ParamsType includes note_on.
// we need this to be able to determine when to reuse slots
note_on: bool,
};
return struct {
slots: [polyphony]?SlotState,
// TODO - i should be able to use a single array for each of
// these because only 32 impulses can come in, only 32
// impulses could come out... or can i even reuse the storage
// of the NoteTracker?
impulses_array: [polyphony][32]Impulse, // internal storage
paramses_array: [polyphony][32]NoteParamsType,
pub fn init() @This() {
return @This() {
.slots = [1]?SlotState{null} ** polyphony,
.impulses_array = undefined,
.paramses_array = undefined,
};
}
pub fn reset(self: *@This()) void {
for (self.slots) |*maybe_slot| {
maybe_slot.* = null;
}
}
fn chooseSlot(
self: *const @This(),
note_id: usize,
event_id: usize,
note_on: bool,
) ?usize {
if (!note_on) {
// this is a note-off event. try to find the slot where
// the note lives. if we don't find it (meaning it got
// overridden at some point), return null
return for (self.slots) |maybe_slot, slot_index| {
if (maybe_slot) |slot| {
if (slot.note_id == note_id and slot.note_on) {
break slot_index;
}
}
} else null;
}
// otherwise, this is a note-on event. find the slot in
// note-off state with the oldest event_id. this will reuse
// will reuse the slot that had its note-off the longest
// time ago.
{
var maybe_best: ?usize = null;
for (self.slots) |maybe_slot, slot_index| {
if (maybe_slot) |slot| {
if (!slot.note_on) {
if (maybe_best) |best| {
if (slot.event_id <
self.slots[best].?.event_id) {
maybe_best = slot_index;
}
} else { // maybe_best == null
maybe_best = slot_index;
}
}
} else { // maybe_slot == null
// if there's still an empty slot, jump on
// that right now
return slot_index;
}
}
if (maybe_best) |best| {
return best;
}
}
// otherwise, we have no choice but to take over a track
// that's still in note-on state.
var best: usize = 0;
var slot_index: usize = 1;
while (slot_index < polyphony) : (slot_index += 1) {
if (self.slots[slot_index].?.event_id <
self.slots[best].?.event_id) {
best = slot_index;
}
}
return best;
}
// FIXME can this be changed to a generator pattern so we don't
// need the static arrays?
pub fn dispatch(
self: *@This(),
iap: ImpulsesAndParamses,
) [polyphony]ImpulsesAndParamses {
var counts = [1]usize{0} ** polyphony;
var i: usize = 0; while (i < iap.paramses.len) : (i += 1) {
const impulse = iap.impulses[i];
const params = iap.paramses[i];
if (self.chooseSlot(
impulse.note_id,
impulse.event_id,
params.note_on,
)) |slot_index| {
self.slots[slot_index] = SlotState {
.note_id = impulse.note_id,
.event_id = impulse.event_id,
.note_on = params.note_on,
};
self.impulses_array[slot_index][counts[slot_index]]
= impulse;
self.paramses_array[slot_index][counts[slot_index]]
= params;
counts[slot_index] += 1;
}
}
var result: [polyphony]ImpulsesAndParamses = undefined;
i = 0; while (i < polyphony) : (i += 1) {
result[i] = ImpulsesAndParamses {
.impulses = self.impulses_array[i][0..counts[i]],
.paramses = self.paramses_array[i][0..counts[i]],
};
}
return result;
}
};
}
};
} | src/zang/notes.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const nvg = @import("nanovg");
const gui = @import("gui");
const geometry = gui.geometry;
const Point = geometry.Point;
const Pointi = Point(i32);
const Pointu = Point(u32);
const Rect = geometry.Rect;
const Recti = Rect(i32);
const Image = @import("Image.zig");
const Clipboard = @import("Clipboard.zig");
const Document = @This();
pub const Selection = struct {
rect: Recti,
bitmap: []u8,
texture: nvg.Image,
};
const UndoStep = union(enum) {
document: struct {
width: u32,
height: u32,
bitmap: []u8,
},
fn make(allocator: *Allocator, document: *Document) !UndoStep {
return UndoStep{ .document = .{
.width = document.width,
.height = document.height,
.bitmap = try allocator.dupe(u8, document.bitmap),
} };
}
fn deinit(self: UndoStep, allocator: *Allocator) void {
switch (self) {
.document => |d| allocator.free(d.bitmap),
}
}
fn hasChanges(self: UndoStep, document: *Document) bool {
return switch (self) {
.document => |d| d.width != document.width or
d.width != document.width or
!std.mem.eql(u8, d.bitmap, document.bitmap),
};
}
fn undo(self: UndoStep, allocator: *Allocator, document: *Document) !void {
switch (self) {
.document => |d| {
if (document.width != d.width or document.height != d.height) {
document.bitmap = try allocator.realloc(document.bitmap, d.bitmap.len);
document.preview_bitmap = try allocator.realloc(document.preview_bitmap, d.bitmap.len);
// recreate texture
nvg.deleteImage(document.texture);
document.texture = nvg.createImageRgba(d.width, d.height, .{ .nearest = true }, d.bitmap);
}
std.mem.copy(u8, document.bitmap, d.bitmap);
document.width = d.width;
document.height = d.height;
},
}
}
fn redo(self: UndoStep, allocator: *Allocator, document: *Document) !void {
try self.undo(allocator, document);
}
};
const UndoSystem = struct {
allocator: *Allocator,
stack: ArrayList(UndoStep),
index: usize = 0,
undo_listener_address: usize = 0, // TODO: this is pretty hacky
onUndoChangedFn: ?fn (*Document) void = null,
fn init(allocator: *Allocator) !*UndoSystem {
var self = try allocator.create(UndoSystem);
self.* = UndoSystem{
.allocator = allocator,
.stack = ArrayList(UndoStep).init(allocator),
};
return self;
}
fn deinit(self: *UndoSystem) void {
for (self.stack.items) |step| {
step.deinit(self.allocator);
}
self.stack.deinit();
self.allocator.destroy(self);
}
fn clearAndFreeStack(self: *UndoSystem) void {
for (self.stack.items) |step| {
step.deinit(self.allocator);
}
self.stack.shrinkRetainingCapacity(0);
self.index = 0;
}
fn reset(self: *UndoSystem, document: *Document) !void {
self.clearAndFreeStack();
try self.stack.append(try UndoStep.make(self.allocator, document));
self.notifyChanged(document);
}
fn notifyChanged(self: UndoSystem, document: *Document) void {
if (self.onUndoChangedFn) |onUndoChanged| onUndoChanged(document);
}
fn canUndo(self: UndoSystem) bool {
return self.index > 0;
}
fn undo(self: *UndoSystem, allocator: *Allocator, document: *Document) !void {
if (!self.canUndo()) return;
self.index -= 1;
const step = self.stack.items[self.index];
try step.undo(allocator, document);
document.clearPreview();
self.notifyChanged(document);
}
fn canRedo(self: UndoSystem) bool {
return self.index + 1 < self.stack.items.len;
}
fn redo(self: *UndoSystem, allocator: *Allocator, document: *Document) !void {
if (!self.canRedo()) return;
self.index += 1;
const step = self.stack.items[self.index];
try step.redo(allocator, document);
document.clearPreview();
self.notifyChanged(document);
}
fn pushFrame(self: *UndoSystem, document: *Document) !void { // TODO: handle error cases
// do comparison
const top = self.stack.items[self.index];
if (!top.hasChanges(document)) return;
// create new step
self.index += 1;
for (self.stack.items[self.index..self.stack.items.len]) |step| {
step.deinit(self.allocator);
}
self.stack.shrinkRetainingCapacity(self.index);
try self.stack.append(try UndoStep.make(self.allocator, document));
self.notifyChanged(document);
}
};
allocator: *Allocator,
width: u32 = 32,
height: u32 = 32,
texture: nvg.Image, // image for display using nvg
bitmap: []u8,
preview_bitmap: []u8, // preview brush and lines
colormap: ?[]u8 = null, // if this is set bitmap is an indexmap into this colormap
dirty: bool = false, // bitmap needs to be uploaded to gpu on next draw call
selection: ?Selection = null,
copy_location: ?Pointi = null, // where the source was copied from
undo_system: *UndoSystem,
foreground_color: [4]u8 = [_]u8{ 0, 0, 0, 0xff },
background_color: [4]u8 = [_]u8{ 0xff, 0xff, 0xff, 0xff },
const Self = @This();
pub fn init(allocator: *Allocator) !*Self {
var self = try allocator.create(Self);
self.* = Self{
.allocator = allocator,
.texture = undefined,
.bitmap = undefined,
.preview_bitmap = undefined,
.undo_system = try UndoSystem.init(allocator),
};
self.bitmap = try self.allocator.alloc(u8, 4 * self.width * self.height);
var i: usize = 0;
while (i < self.bitmap.len) : (i += 1) {
self.bitmap[i] = self.background_color[i % 4];
}
self.preview_bitmap = try self.allocator.alloc(u8, 4 * self.width * self.height);
std.mem.copy(u8, self.preview_bitmap, self.bitmap);
self.texture = nvg.createImageRgba(self.width, self.height, .{ .nearest = true }, self.bitmap);
try self.undo_system.reset(self);
return self;
}
pub fn deinit(self: *Self) void {
self.undo_system.deinit();
self.allocator.free(self.bitmap);
self.allocator.free(self.preview_bitmap);
nvg.deleteImage(self.texture);
self.freeSelection();
self.allocator.destroy(self);
}
pub fn createNew(self: *Self, width: u32, height: u32) !void {
const new_bitmap = try self.allocator.alloc(u8, 4 * width * height);
self.allocator.free(self.bitmap);
self.bitmap = new_bitmap;
self.width = width;
self.height = height;
var i: usize = 0;
while (i < self.bitmap.len) : (i += 1) {
self.bitmap[i] = self.background_color[i % 4];
}
self.allocator.free(self.preview_bitmap);
self.preview_bitmap = try self.allocator.dupe(u8, self.bitmap);
nvg.deleteImage(self.texture);
self.texture = nvg.createImageRgba(self.width, self.height, .{ .nearest = true }, self.bitmap);
self.freeSelection();
try self.undo_system.reset(self);
}
pub fn load(self: *Self, file_path: []const u8) !void {
const image = try Image.initFromFile(self.allocator, file_path);
std.debug.assert(image.colormap == null); // TODO: handle palette
self.allocator.free(self.bitmap);
self.bitmap = image.pixels;
self.width = image.width;
self.height = image.height;
self.allocator.free(self.preview_bitmap);
self.preview_bitmap = try self.allocator.dupe(u8, self.bitmap);
// resolution might have change so recreate image
nvg.deleteImage(self.texture);
self.texture = nvg.createImageRgba(self.width, self.height, .{ .nearest = true }, self.bitmap);
self.freeSelection();
try self.undo_system.reset(self);
}
pub fn save(self: *Self, file_path: []const u8) !void {
var image = Image{
.width = self.width,
.height = self.height,
.pixels = self.bitmap,
.allocator = self.allocator,
};
try image.writeToFile(file_path);
//if (c.stbi_write_png(file_path.ptr, @intCast(c_int, self.width), @intCast(c_int, self.height), 4, self.bitmap.ptr, 0) == 0) return error.Fail;
}
pub fn canUndo(self: Self) bool {
return self.undo_system.canUndo();
}
pub fn undo(self: *Self) !void {
try self.undo_system.undo(self.allocator, self);
}
pub fn canRedo(self: Self) bool {
return self.undo_system.canRedo();
}
pub fn redo(self: *Self) !void {
try self.undo_system.redo(self.allocator, self);
}
pub fn cut(self: *Self) !void {
try self.copy();
if (self.selection != null) {
self.freeSelection();
} else {
// clear image
std.mem.set(u8, self.bitmap, 0);
self.clearPreview();
}
}
pub fn copy(self: *Self) !void {
if (self.selection) |selection| {
try Clipboard.setImage(self.allocator, Image{
.width = @intCast(u32, selection.rect.w),
.height = @intCast(u32, selection.rect.h),
.pixels = selection.bitmap,
.allocator = self.allocator,
});
self.copy_location = Pointi{
.x = selection.rect.x,
.y = selection.rect.y,
};
} else {
try Clipboard.setImage(self.allocator, Image{
.width = self.width,
.height = self.height,
.pixels = self.bitmap,
.allocator = self.allocator,
});
self.copy_location = null;
}
}
pub fn paste(self: *Self) !void {
if (try Clipboard.getImage(self.allocator)) |image| {
errdefer self.allocator.free(image.pixels);
if (self.selection) |_| {
try self.clearSelection();
}
const x = @intCast(i32, self.width / 2) - @intCast(i32, image.width / 2);
const y = @intCast(i32, self.height / 2) - @intCast(i32, image.height / 2);
var selection_rect = Recti.make(x, y, @intCast(i32, image.width), @intCast(i32, image.height));
if (self.copy_location) |copy_location| {
selection_rect.x = copy_location.x;
selection_rect.y = copy_location.y;
}
self.selection = Selection{
.rect = selection_rect,
.bitmap = image.pixels,
.texture = nvg.createImageRgba(
image.width,
image.height,
.{ .nearest = true },
image.pixels,
),
};
}
}
pub fn crop(self: *Self, rect: Recti) !void {
if (rect.w < 1 or rect.h < 1) return error.InvalidCropRect;
const width = @intCast(u32, rect.w);
const height = @intCast(u32, rect.h);
const new_bitmap = try self.allocator.alloc(u8, 4 * width * height);
//errdefer self.allocator.free(new_bitmap); // TODO: bad because tries for undo stuff at the bottom
std.mem.set(u8, new_bitmap, 0xff); // TODO: custom background
const intersection = rect.intersection(.{
.x = 0,
.y = 0,
.w = @intCast(i32, self.width),
.h = @intCast(i32, self.height),
});
if (intersection.w > 0 and intersection.h > 0) {
const ox = if (rect.x < 0) @intCast(u32, -rect.x) else 0;
const oy = if (rect.y < 0) @intCast(u32, -rect.y) else 0;
const sx = @intCast(u32, intersection.x);
const sy = @intCast(u32, intersection.y);
const w = @intCast(u32, intersection.w);
const h = @intCast(u32, intersection.h);
// blit to source
var y: u32 = 0;
while (y < h) : (y += 1) {
const si = 4 * ((y + oy) * @intCast(u32, rect.w) + ox);
const di = 4 * ((sy + y) * self.width + sx);
// copy entire line
std.mem.copy(u8, new_bitmap[si .. si + 4 * w], self.bitmap[di .. di + 4 * w]);
}
}
self.allocator.free(self.bitmap);
self.bitmap = new_bitmap;
self.width = width;
self.height = height;
self.allocator.free(self.preview_bitmap);
self.preview_bitmap = try self.allocator.dupe(u8, self.bitmap);
nvg.deleteImage(self.texture);
self.texture = nvg.createImageRgba(self.width, self.height, .{ .nearest = true }, self.bitmap);
// TODO: undo stuff handle new dimensions
try self.undo_system.pushFrame(self);
}
fn mul8(a: u8, b: u8) u8 {
return @truncate(u8, (@as(u16, a) * @as(u16, b)) / 0xff);
}
fn div8(a: u8, b: u8) u8 {
return @truncate(u8, @divTrunc(@as(u16, a) * 0xff, @as(u16, b)));
}
// blend color a over b (Porter Duff)
// a_out = a_a + a_b * (1 - a_a)
// c_out = (c_a * a_a + c_b * a_b * (1 - a_a)) / a_out
fn blendColor(a: []u8, b: []u8) [4]u8 {
var out: [4]u8 = [_]u8{0} ** 4;
const fac = mul8(b[3], 0xff - a[3]);
out[3] = a[3] + fac;
if (out[3] > 0) {
out[0] = div8(mul8(a[0], a[3]) + mul8(b[0], fac), out[3]);
out[1] = div8(mul8(a[1], a[3]) + mul8(b[1], fac), out[3]);
out[2] = div8(mul8(a[2], a[3]) + mul8(b[2], fac), out[3]);
}
return out;
}
pub fn clearSelection(self: *Self) !void {
if (self.selection) |selection| {
const rect = selection.rect;
const bitmap = selection.bitmap;
const intersection = rect.intersection(.{
.x = 0,
.y = 0,
.w = @intCast(i32, self.width),
.h = @intCast(i32, self.height),
});
if (intersection.w > 0 and intersection.h > 0) {
const ox = if (rect.x < 0) @intCast(u32, -rect.x) else 0;
const oy = if (rect.y < 0) @intCast(u32, -rect.y) else 0;
const sx = @intCast(u32, intersection.x);
const sy = @intCast(u32, intersection.y);
const w = @intCast(u32, intersection.w);
const h = @intCast(u32, intersection.h);
// blit to source
var y: u32 = 0;
while (y < h) : (y += 1) {
const si = 4 * ((y + oy) * @intCast(u32, rect.w) + ox);
const di = 4 * ((sy + y) * self.width + sx);
// copy entire line
// std.mem.copy(u8, self.bitmap[di .. di + 4 * w], bitmap[si .. si + 4 * w]);
// blend each pixel
var x: u32 = 0;
while (x < w) : (x += 1) {
const src = bitmap[si + 4 * x .. si + 4 * x + 4];
const dst = self.bitmap[di + 4 * x .. di + 4 * x + 4];
const out = blendColor(src, dst);
std.mem.copy(u8, dst, out[0..]);
}
}
self.clearPreview();
}
self.freeSelection();
try self.undo_system.pushFrame(self);
}
}
pub fn makeSelection(self: *Self, rect: Recti) !void {
std.debug.assert(self.colormap == null); // TODO
std.debug.assert(rect.w > 0 and rect.h > 0);
const intersection = rect.intersection(.{
.x = 0,
.y = 0,
.w = @intCast(i32, self.width),
.h = @intCast(i32, self.height),
});
if (intersection.w > 0 and intersection.h > 0) {
const w = @intCast(u32, intersection.w);
const h = @intCast(u32, intersection.h);
const bitmap = try self.allocator.alloc(u8, 4 * w * h); // RGBA
// move pixels
var y: u32 = 0;
while (y < h) : (y += 1) {
const di = 4 * (y * w);
const sx = @intCast(u32, intersection.x);
const sy = @intCast(u32, intersection.y);
const si = 4 * ((sy + y) * self.width + sx);
std.mem.copy(u8, bitmap[di .. di + 4 * w], self.bitmap[si .. si + 4 * w]);
const dst_line = self.bitmap[si .. si + 4 * w];
var i: usize = 0;
while (i < dst_line.len) : (i += 1) {
dst_line[i] = self.background_color[i % 4];
}
}
self.clearPreview();
var selection = Selection{
.rect = intersection,
.bitmap = bitmap,
.texture = nvg.createImageRgba(w, h, .{ .nearest = true }, bitmap),
};
self.freeSelection(); // clean up previous selection
self.selection = selection;
}
}
pub fn freeSelection(self: *Self) void {
if (self.selection) |selection| {
self.allocator.free(selection.bitmap);
nvg.deleteImage(selection.texture);
self.selection = null;
}
}
pub fn setForegroundColorRgba(self: *Self, color: [4]u8) void {
self.foreground_color = color;
}
pub fn setBackgroundColorRgba(self: *Self, color: [4]u8) void {
self.background_color = color;
}
fn setPixel(bitmap: []u8, w: u32, h: u32, x: i32, y: i32, color: [4]u8) void {
if (x >= 0 and y >= 0) {
const ux = @intCast(u32, x);
const uy = @intCast(u32, y);
if (ux < w and uy < h) {
setPixelUnchecked(bitmap, w, ux, uy, color);
}
}
}
fn setPixelUnchecked(bitmap: []u8, w: u32, x: u32, y: u32, color: [4]u8) void {
std.debug.assert(x < w);
const i = (y * w + x) * 4;
bitmap[i + 0] = color[0];
bitmap[i + 1] = color[1];
bitmap[i + 2] = color[2];
bitmap[i + 3] = color[3];
}
fn getPixel(self: Self, x: i32, y: i32) ?[4]u8 {
if (x >= 0 and y >= 0) {
const ux = @intCast(u32, x);
const uy = @intCast(u32, y);
if (ux < self.width and uy < self.height) {
return getPixelUnchecked(self.bitmap, self.width, ux, uy);
}
}
return null;
}
fn getPixelUnchecked(bitmap: []u8, w: u32, x: u32, y: u32) [4]u8 {
std.debug.assert(x < w);
const i = (y * w + x) * 4;
return [_]u8{
bitmap[i + 0],
bitmap[i + 1],
bitmap[i + 2],
bitmap[i + 3],
};
}
fn drawLine(bitmap: []u8, w: u32, h: u32, x0: i32, y0: i32, x1: i32, y1: i32, color: [4]u8) void {
const dx = std.math.absInt(x1 - x0) catch unreachable;
const sx: i32 = if (x0 < x1) 1 else -1;
const dy = -(std.math.absInt(y1 - y0) catch unreachable);
const sy: i32 = if (y0 < y1) 1 else -1;
var err = dx + dy;
var x = x0;
var y = y0;
while (true) {
setPixel(bitmap, w, h, x, y, color);
if (x == x1 and y == y1) break;
const e2 = 2 * err;
if (e2 >= dy) {
err += dy;
x += sx;
}
if (e2 <= dx) {
err += dx;
y += sy;
}
}
}
pub fn previewBrush(self: *Self, x: i32, y: i32) void {
self.clearPreview();
setPixel(self.preview_bitmap, self.width, self.height, x, y, self.foreground_color);
}
pub fn previewStroke(self: *Self, x0: i32, y0: i32, x1: i32, y1: i32) void {
self.clearPreview();
drawLine(self.preview_bitmap, self.width, self.height, x0, y0, x1, y1, self.foreground_color);
}
pub fn clearPreview(self: *Self) void {
std.mem.copy(u8, self.preview_bitmap, self.bitmap);
self.dirty = true;
}
pub fn fill(self: *Self, color: [4]u8) !void {
if (self.selection) |*selection| {
const w = @intCast(u32, selection.rect.w);
const h = @intCast(u32, selection.rect.h);
var y: u32 = 0;
while (y < h) : (y += 1) {
var x: u32 = 0;
while (x < w) : (x += 1) {
setPixelUnchecked(selection.bitmap, w, x, y, color);
}
}
nvg.updateImage(selection.texture, selection.bitmap);
} else {
var y: u32 = 0;
while (y < self.height) : (y += 1) {
var x: u32 = 0;
while (x < self.width) : (x += 1) {
setPixelUnchecked(self.bitmap, self.width, x, y, color);
}
}
self.clearPreview();
try self.undo_system.pushFrame(self);
}
}
pub fn mirrorHorizontally(self: *Self) !void {
if (self.selection) |*selection| {
const w = @intCast(u32, selection.rect.w);
const h = @intCast(u32, selection.rect.h);
var y: u32 = 0;
while (y < h) : (y += 1) {
var x0: u32 = 0;
var x1: u32 = w - 1;
while (x0 < x1) {
const color0 = getPixelUnchecked(selection.bitmap, w, x0, y);
const color1 = getPixelUnchecked(selection.bitmap, w, x1, y);
setPixelUnchecked(selection.bitmap, w, x0, y, color1);
setPixelUnchecked(selection.bitmap, w, x1, y, color0);
x0 += 1;
x1 -= 1;
}
}
nvg.updateImage(selection.texture, selection.bitmap);
} else {
var y: u32 = 0;
while (y < self.height) : (y += 1) {
var x0: u32 = 0;
var x1: u32 = self.width - 1;
while (x0 < x1) {
const color0 = getPixelUnchecked(self.bitmap, self.width, x0, y);
const color1 = getPixelUnchecked(self.bitmap, self.width, x1, y);
setPixelUnchecked(self.bitmap, self.width, x0, y, color1);
setPixelUnchecked(self.bitmap, self.width, x1, y, color0);
x0 += 1;
x1 -= 1;
}
}
self.clearPreview();
try self.undo_system.pushFrame(self);
}
}
pub fn mirrorVertically(self: *Self) !void {
var w: u32 = undefined;
var h: u32 = undefined;
var bitmap: []u8 = undefined;
if (self.selection) |*selection| {
w = @intCast(u32, selection.rect.w);
h = @intCast(u32, selection.rect.h);
bitmap = selection.bitmap;
} else {
w = self.width;
h = self.height;
bitmap = self.bitmap;
}
const pitch = 4 * w;
var tmp = try self.allocator.alloc(u8, pitch);
defer self.allocator.free(tmp);
var y0: u32 = 0;
var y1: u32 = h - 1;
while (y0 < y1) {
const line0 = bitmap[y0 * pitch .. (y0 + 1) * pitch];
const line1 = bitmap[y1 * pitch .. (y1 + 1) * pitch];
std.mem.copy(u8, tmp, line0);
std.mem.copy(u8, line0, line1);
std.mem.copy(u8, line1, tmp);
y0 += 1;
y1 -= 1;
}
if (self.selection) |*selection| {
nvg.updateImage(selection.texture, selection.bitmap);
} else {
self.clearPreview();
try self.undo_system.pushFrame(self);
}
}
pub fn rotateCw(self: *Self) !void {
var w: u32 = undefined;
var h: u32 = undefined;
var bitmap: []u8 = undefined;
if (self.selection) |*selection| {
w = @intCast(u32, selection.rect.w);
h = @intCast(u32, selection.rect.h);
bitmap = selection.bitmap;
} else {
w = self.width;
h = self.height;
bitmap = self.bitmap;
}
const tmp_bitmap = try self.allocator.dupe(u8, bitmap);
var y: u32 = 0;
while (y < h) : (y += 1) {
var x: u32 = 0;
while (x < w) : (x += 1) {
const color = getPixelUnchecked(tmp_bitmap, w, x, y);
setPixelUnchecked(bitmap, h, h - 1 - y, x, color);
}
}
self.allocator.free(tmp_bitmap);
if (self.selection) |*selection| {
const d = @divTrunc(selection.rect.w - selection.rect.h, 2);
selection.rect.x += d;
selection.rect.y -= d;
std.mem.swap(i32, &selection.rect.w, &selection.rect.h);
nvg.deleteImage(selection.texture);
selection.texture = nvg.createImageRgba(h, w, .{ .nearest = true }, selection.bitmap);
} else {
std.mem.swap(u32, &self.width, &self.height);
self.clearPreview();
try self.undo_system.pushFrame(self);
}
}
pub fn rotateCcw(self: *Self) !void {
var w: u32 = undefined;
var h: u32 = undefined;
var bitmap: []u8 = undefined;
if (self.selection) |*selection| {
w = @intCast(u32, selection.rect.w);
h = @intCast(u32, selection.rect.h);
bitmap = selection.bitmap;
} else {
w = self.width;
h = self.height;
bitmap = self.bitmap;
}
const tmp_bitmap = try self.allocator.dupe(u8, bitmap);
var y: u32 = 0;
while (y < h) : (y += 1) {
var x: u32 = 0;
while (x < w) : (x += 1) {
const color = getPixelUnchecked(tmp_bitmap, w, x, y);
setPixelUnchecked(bitmap, h, y, w - 1 - x, color);
}
}
self.allocator.free(tmp_bitmap);
if (self.selection) |*selection| {
const d = @divTrunc(selection.rect.w - selection.rect.h, 2);
selection.rect.x += d;
selection.rect.y -= d;
std.mem.swap(i32, &selection.rect.w, &selection.rect.h);
nvg.deleteImage(selection.texture);
selection.texture = nvg.createImageRgba(h, w, .{ .nearest = true }, selection.bitmap);
} else {
std.mem.swap(u32, &self.width, &self.height);
self.clearPreview();
try self.undo_system.pushFrame(self);
}
}
pub fn floodFill(self: *Self, x: i32, y: i32) !void {
const old_color = self.pickColor(x, y) orelse return;
if (std.mem.eql(u8, old_color[0..], self.foreground_color[0..])) return;
const bitmap = self.bitmap;
var stack = std.ArrayList(struct { x: i32, y: i32 }).init(self.allocator);
defer stack.deinit();
try stack.append(.{ .x = x, .y = y });
while (stack.items.len > 0) {
const coords = stack.pop();
if (self.getPixel(coords.x, coords.y)) |color| {
if (std.mem.eql(u8, color[0..], old_color[0..])) {
setPixelUnchecked(
bitmap,
self.width,
@intCast(u32, coords.x),
@intCast(u32, coords.y),
self.foreground_color,
);
try stack.append(.{ .x = coords.x, .y = coords.y - 1 });
try stack.append(.{ .x = coords.x, .y = coords.y + 1 });
try stack.append(.{ .x = coords.x - 1, .y = coords.y });
try stack.append(.{ .x = coords.x + 1, .y = coords.y });
}
}
}
self.clearPreview();
try self.undo_system.pushFrame(self);
}
pub fn beginStroke(self: *Self, x: i32, y: i32) void {
setPixel(self.bitmap, self.width, self.height, x, y, self.foreground_color);
self.clearPreview();
}
pub fn stroke(self: *Self, x0: i32, y0: i32, x1: i32, y1: i32) void {
drawLine(self.bitmap, self.width, self.height, x0, y0, x1, y1, self.foreground_color);
self.clearPreview();
}
pub fn endStroke(self: *Self) !void {
try self.undo_system.pushFrame(self);
}
pub fn pickColor(self: *Self, x: i32, y: i32) ?[4]u8 {
return self.getPixel(x, y);
}
pub fn draw(self: *Self) void {
if (self.dirty) {
nvg.updateImage(self.texture, self.preview_bitmap);
self.dirty = false;
}
nvg.beginPath();
nvg.rect(0, 0, @intToFloat(f32, self.width), @intToFloat(f32, self.height));
nvg.fillPaint(nvg.imagePattern(0, 0, @intToFloat(f32, self.width), @intToFloat(f32, self.height), 0, self.texture, 1));
nvg.fill();
} | src/Document.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 {
const required_fields = enum {
byr, // (Birth Year)
iyr, // (Issue Year)
eyr, // (Expiration Year)
hgt, // (Height)
hcl, // (Hair Color)
ecl, // (Eye Color)
pid, // (Passport ID)
// cid, // (Country ID) -> optional
};
const required_field_names = comptime std.meta.fieldNames(required_fields);
// === part 1 ==============
const ans1 = ans: {
var valid_entries: u32 = 0;
var it = std.mem.split(u8, input, "\n\n");
while (it.next()) |entry| {
const is_valid = inline for (required_field_names) |field| {
if (std.mem.indexOf(u8, entry, field ++ ":") == null)
break false;
} else true;
if (is_valid) valid_entries += 1;
}
break :ans valid_entries;
};
// === part 2 ==============
const ans2 = ans: {
var valid_entries: u32 = 0;
var it1 = std.mem.split(u8, input, "\n\n");
next_entry: while (it1.next()) |entry| {
var fields_count: u32 = 0;
var it2 = std.mem.tokenize(u8, entry, " \n\t");
next_kvpair: while (it2.next()) |kv| {
if (kv.len < 5 or kv[3] != ':')
continue :next_entry;
const key = kv[0..3];
const value = kv[4..];
const field = tools.nameToEnum(required_fields, key) catch continue :next_kvpair; // ignore unknown keys
switch (field) {
.byr => { // (Birth Year) - four digits; at least 1920 and at most 2002.
if (value.len != 4) continue :next_entry;
const v = std.fmt.parseInt(u32, value, 10) catch continue :next_entry;
if (v < 1920 or v > 2002) continue :next_entry;
fields_count += 1;
},
.iyr => { // (Issue Year) - four digits; at least 2010 and at most 2020.
if (value.len != 4) continue :next_entry;
const v = std.fmt.parseInt(u32, value, 10) catch continue :next_entry;
if (v < 2010 or v > 2020) continue :next_entry;
fields_count += 1;
},
.eyr => { // (Expiration Year) - four digits; at least 2020 and at most 2030.
if (value.len != 4) continue :next_entry;
const v = std.fmt.parseInt(u32, value, 10) catch continue :next_entry;
if (v < 2020 or v > 2030) continue :next_entry;
fields_count += 1;
},
.hgt => {
// (Height) - a number followed by either cm or in:
// If cm, the number must be at least 150 and at most 193.
// If in, the number must be at least 59 and at most 76.
if (value.len < 4) continue :next_entry;
const unit = value[value.len - 2 ..];
const h = std.fmt.parseInt(u32, value[0 .. value.len - 2], 10) catch continue :next_entry;
if (std.mem.eql(u8, unit, "cm")) {
if (h < 150 or h > 193) continue :next_entry;
} else if (std.mem.eql(u8, unit, "in")) {
if (h < 59 or h > 76) continue :next_entry;
} else {
continue :next_entry;
}
fields_count += 1;
},
.hcl => { // (Hair Color) - a # followed by exactly six characters 0-9 or a-f.
if (value.len != 7) continue :next_entry;
if (value[0] != '#') continue :next_entry;
_ = std.fmt.parseInt(u32, value[1..], 16) catch continue :next_entry;
fields_count += 1;
},
.ecl => { // (Eye Color) - exactly one of: amb blu brn gry grn hzl oth.
if (value.len != 3) continue :next_entry;
if (std.mem.indexOf(u8, "amb blu brn gry grn hzl oth", value) == null) continue :next_entry;
fields_count += 1;
},
.pid => { // (Passport ID) - a nine-digit number, including leading zeroes.
if (value.len != 9) continue :next_entry;
_ = std.fmt.parseInt(u32, value, 10) catch continue :next_entry;
fields_count += 1;
},
}
if (fields_count == std.meta.fields(required_fields).len)
valid_entries += 1;
}
}
break :ans valid_entries;
};
return [_][]const u8{
try std.fmt.allocPrint(allocator, "{}", .{ans1}),
try std.fmt.allocPrint(allocator, "{}", .{ans2}),
};
}
pub const main = tools.defaultMain("2020/input_day04.txt", run); | 2020/day04.zig |
const actorNs = @import("actor.zig");
const ActorInterface = actorNs.ActorInterface;
const messageNs = @import("message.zig");
const MessageHeader = messageNs.MessageHeader;
const messageQueueNs = @import("message_queue.zig");
const MessageQueue = messageQueueNs.MessageQueue;
const SignalContext = messageQueueNs.SignalContext;
const builtin = @import("builtin");
const std = @import("std");
const assert = std.debug.assert;
const warn = std.debug.warn;
const futex_wake = @import("futex.zig").futex_wake;
const AtomicOrder = builtin.AtomicOrder;
const AtomicRmwOp = builtin.AtomicRmwOp;
/// Dispatches messages to actors
pub fn ActorDispatcher(comptime maxActors: usize) type {
return struct {
const Self = @This();
// TODO: Should there be one queue per actor instead?
pub queue: MessageQueue(),
pub signal_context: u32,
pub msg_count: u64,
pub last_msg_cmd: u64,
pub actor_processMessage_count: u64,
// Array of actors
lock: u8,
pub actors: [maxActors]*ActorInterface,
pub actors_count: u64,
pub inline fn init(pSelf: *Self) void {
// Because we're using self referential pointers init
// must be passed a pointer rather then returning Self
warn("ActorDispatcher.init:+ {*}:&signal_context={*}\n", pSelf, &pSelf.signal_context);
defer warn("ActorDispatcher.init:- {*}:&signal_context={*}\n", pSelf, &pSelf.signal_context);
pSelf.signal_context = 0;
pSelf.queue = MessageQueue().init(Self.signalFn, &pSelf.signal_context);
pSelf.msg_count = 0;
pSelf.last_msg_cmd = 0;
pSelf.actor_processMessage_count = 0;
pSelf.lock = 0;
pSelf.actors_count = 0;
pSelf.actors = undefined;
}
/// Add an ActorInterface to this dispatcher
pub fn add(pSelf: *Self, pAi: *ActorInterface) !void {
warn("ActorDispatcher.add:+ {*}:&signal_context={*} pAi={*} processMessage={x}\n",
pSelf, &pSelf.signal_context, pAi, @ptrToInt(pAi.processMessage));
while (@atomicRmw(u8, &pSelf.lock, AtomicRmwOp.Xchg, 1, AtomicOrder.SeqCst) == 0) {}
defer assert(@atomicRmw(u8, &pSelf.lock, AtomicRmwOp.Xchg, 0, AtomicOrder.SeqCst) == 1);
if (pSelf.actors_count >= pSelf.actors.len) return error.TooManyActors;
pAi.pQueue = &pSelf.queue;
pSelf.actors[pSelf.actors_count] = pAi;
pSelf.actors_count += 1;
//warn("ActorDispatcher.add:- {*}:&signal_context={*} pAi={*} processMessage={x}\n",
// pSelf, &pSelf.signal_context, pAi, @ptrToInt(pSelf.actors[pSelf.actors_count-1].processMessage));
}
fn signalFn(pSignalContext: *SignalContext) void {
//warn("ActorDispatcher.signalFn:+ call wake {*}:{}\n", pSignalContext, pSignalContext.*);
//defer warn("ActorDispatcher.signalFn:- aftr wake {*}:{}\n", pSignalContext, pSignalContext.*);
// Set signal_context and get old value which if 0 then we know the thread is or has gone to sleep.
// So we'll call futex_wake as there is only one ActorDispatcher per thread. In the future,
// if/when there are multiple ActorDispatchers per thread this might need to change.
if (0 == @atomicRmw(SignalContext, pSignalContext, AtomicRmwOp.Xchg, 1, AtomicOrder.SeqCst)) {
//warn("ActorDispatcher.signalFn: call wake {*}:{}\n", pSignalContext, pSignalContext.*);
futex_wake(pSignalContext, 1);
}
}
/// Loop through the message on the queue calling
/// the associated actor.
/// @return true if queue is empty
pub fn loop(pSelf: *Self) bool {
//warn("ActorDispatcher.loop:+ {*}:&signal_context={*}\n", pSelf, &pSelf.signal_context);
//defer warn("ActorDispatcher.loop:- {*}:&signal_context={*}\n", pSelf, &pSelf.signal_context);
// TODO: limit number of loops or time so we don't starve other actors
// that we maybe sharing the thread with.
while (true) {
// Return if queue is empty
var pMsgHeader = pSelf.queue.get() orelse {
// We're racing with signalFn if we win and store the 0 then
// we "know" we're going to sleep as right now there is only
// one ActorDispatcher per thread. When/if there ever is more
// than one then we need to change this and signalFn.
return @atomicRmw(SignalContext, &pSelf.signal_context, AtomicRmwOp.Xchg, 0, AtomicOrder.SeqCst) == 0;
};
pSelf.msg_count += 1;
pSelf.last_msg_cmd = pMsgHeader.cmd;
if (pMsgHeader.pDstActor) |pAi| {
if (pAi.pQueue) |pQ| {
if (pQ == &pSelf.queue) {
pAi.processMessage(pAi, pMsgHeader);
} else {
// TODO: Actor is associated with a
// different "dispatcher/queue". We
// could:
// - put it on the other queue but
// ordering could change.
// - drop it
// - send back to src with an error
// Right now this isn't possible so we'll
// mark it as unreachable.
unreachable;
}
} else {
// TODO: No destination queue just drop??
if (pMsgHeader.pAllocator) |pAllocator| {
pAllocator.put(pMsgHeader);
}
}
} else {
// TODO: No destination actor just drop??
if (pMsgHeader.pAllocator) |pAllocator| {
pAllocator.put(pMsgHeader);
}
}
}
}
pub fn broadcastLoop(pSelf: *Self) void {
//warn("ActorDispatcher.broadcastLoop:+ {*}:&signal_context={*}\n", pSelf, &pSelf.signal_context);
//defer warn("ActorDispatcher.broadcastLoop:- {*}:&signal_context={*}\n", pSelf, &pSelf.signal_context);
while (true) {
var pMsgHeader = pSelf.queue.get() orelse return;
pSelf.msg_count += 1;
pSelf.last_msg_cmd = pMsgHeader.cmd;
var i: usize = 0;
while (i < pSelf.actors_count) : (i += 1) {
var pAi = pSelf.actors[i];
pSelf.actor_processMessage_count += 1;
//warn("ActorDispatcher.broadcast: pAi={*} processMessage={x}\n", pAi,
// @ptrToInt(pAi.processMessage));
pAi.processMessage(pAi, pMsgHeader);
}
}
}
};
}
// Tests
const Message = messageNs.Message;
const Actor = actorNs.Actor;
const mem = std.mem;
const MyMsgBody = packed struct {
const Self = @This();
data: [3]u8,
fn init(pSelf: *Self) void {
mem.set(u8, pSelf.data[0..], 'Z');
}
pub fn format(
m: *const MyMsgBody,
comptime fmt: []const u8,
context: var,
comptime FmtError: type,
output: fn (@typeOf(context), []const u8) FmtError!void
) FmtError!void {
try std.fmt.format(context, FmtError, output, "data={{");
for (m.data) |v| {
if ((v >= ' ') and (v <= 0x7f)) {
try std.fmt.format(context, FmtError, output, "{c}," , v);
} else {
try std.fmt.format(context, FmtError, output, "{x},", v);
}
}
try std.fmt.format(context, FmtError, output, "}},");
}
};
const MyActorBody = packed struct {
const Self = @This();
count: u64,
fn init(actr: *Actor(MyActorBody)) void {
actr.body.count = 0;
}
pub fn processMessage(actorInterface: *ActorInterface, msgHeader: *MessageHeader) void {
var pActor = Actor(MyActorBody).getActorPtr(actorInterface);
var pMsg = Message(MyMsgBody).getMessagePtr(msgHeader);
assert(pMsg.header.cmd == msgHeader.cmd);
pActor.body.count += pMsg.header.cmd;
//warn("MyActorBody: &processMessage={x} cmd={} count={}\n",
// @ptrToInt(processMessage), msgHeader.cmd, pActor.body.count);
}
};
test "ActorDispatcher" {
// Create a message
const MyMsg = Message(MyMsgBody);
var myMsg: MyMsg = undefined;
myMsg.init(123);
// Create an Actor
const MyActor = Actor(MyActorBody);
var myActor = MyActor.init();
myActor.interface.processMessage(&myActor.interface, &myMsg.header);
assert(myActor.body.count == 1 * 123);
myActor.interface.processMessage(&myActor.interface, &myMsg.header);
assert(myActor.body.count == 2 * 123);
const MyActorDispatcher = ActorDispatcher(5);
var myActorDispatcher: MyActorDispatcher = undefined;
myActorDispatcher.init();
assert(myActorDispatcher.actors_count == 0);
try myActorDispatcher.add(&myActor.interface);
assert(myActorDispatcher.actors_count == 1);
assert(myActorDispatcher.actors[0].processMessage == myActor.interface.processMessage);
// Place the node on the queue and broadcast to the actors
myActorDispatcher.queue.put(&myMsg.header);
myActorDispatcher.broadcastLoop();
assert(myActorDispatcher.last_msg_cmd == 123);
assert(myActorDispatcher.msg_count == 1);
assert(myActorDispatcher.actor_processMessage_count == 1);
assert(myActor.body.count == 3 * 123);
} | actor_dispatcher.zig |
// SPDX-License-Identifier: MIT
// This file is part of the `termcon` project under the MIT license.
//! This module handles provides functions to interface with the terminal
//! screen.
const view = @import("../../view.zig");
const root = @import("../windows.zig");
const std = @import("std");
const windows = std.os.windows;
pub const Size = view.Size;
pub const Rune = view.Rune;
pub const Style = view.Style;
/// Get the size of the screen in terms of rows and columns.
pub fn getSize() !Size {
var csbi = try getScreenBufferInfo();
var size = Size {
.cols = @intCast(u16, csbi.srWindow.Right - csbi.srWindow.Left + 1),
.rows = @intCast(u16, csbi.srWindow.Bottom - csbi.srWindow.Top + 1)
};
return size;
}
/// Write styled text to the screen at the cursor's position,
/// moving the cursor accordingly.
pub fn write(runes: []const Rune, styles: []const Style) !void {
var csbi = try getScreenBufferInfo();
var coord: windows.COORD = csbi.dwCursorPosition;
var chars_written = @as(windows.DWORD, 0);
var index: u32 = 0;
while (index < runes.len) : (index += 1) {
if (windows.kernel32.FillConsoleOutputCharacterA(root.hConsoleOutCurrent orelse return error.Handle, @intCast(windows.TCHAR, runes[index]), 1, coord, &chars_written) == 0)
return error.FailToWriteChar;
coord.X += 1; // TODO: handle newlines
}
// Set new cursor position
if (windows.kernel32.SetConsoleCursorPosition(root.hConsoleOutCurrent orelse return error.Handle, coord) == 0) return error.SetCursorFailed;
}
/// Clear all runes and styles on the screen.
pub fn clearScreen() !void {
// This function does the same as Microsoft recommends,
// and is how the cls and clear commands are implemented
// in Powershell and CMD: write an empty cell to every
// visible cell on the screen.
var csbi = try getScreenBufferInfo();
var start_pos = windows.COORD { .X = 0, .Y = 0 };
var chars_written: windows.DWORD = 0;
// Get number of cells in the buffer
// TODO: currently uses buffer size, later needs to use actual screen size for optimization
var console_size: windows.DWORD = @intCast(u32, csbi.dwSize.X) * @intCast(u32, csbi.dwSize.Y);
// var console_size = @intCast(u32, (csbi.srWindow.Right - csbi.srWindow.Left + 1) * (csbi.srWindow.Bottom - csbi.srWindow.Top + 1));
// Fill screen with blanks
if (windows.kernel32.FillConsoleOutputCharacterA(root.hConsoleOutCurrent orelse return error.Handle, @as(windows.TCHAR, ' '), console_size, start_pos, &chars_written) == 0) {
return error.SomeDrawError; // TODO: seriously need real errors
}
// Get the current text attribute
// csbi = try getScreenBufferInfo();
if (windows.kernel32.FillConsoleOutputAttribute(root.hConsoleOutCurrent orelse return error.Handle, csbi.wAttributes, console_size, start_pos, &chars_written) == 0) {
return error.SomeDrawError;
}
}
pub fn getScreenBufferInfo() !windows.kernel32.CONSOLE_SCREEN_BUFFER_INFO {
var csbi: windows.kernel32.CONSOLE_SCREEN_BUFFER_INFO = undefined;
if (windows.kernel32.GetConsoleScreenBufferInfo(root.hConsoleOutCurrent orelse return error.Handle, &csbi) == 0) return error.FailedToGetBufferInfo;
return csbi;
} | src/backend/windows/screen.zig |
const builtin = @import("builtin");
const std = @import("std");
const wasmtime = @import("wasmtime");
const fs = std.fs;
const ga = std.heap.c_allocator;
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
pub fn main() !void {
const wasm_path = if (builtin.os.tag == .windows) "examples\\memory.wat" else "examples/memory.wat";
const wasm_file = try fs.cwd().openFile(wasm_path, .{});
const wasm = try wasm_file.readToEndAlloc(ga, std.math.maxInt(u64));
defer ga.free(wasm);
var engine = try wasmtime.Engine.init();
defer engine.deinit();
std.debug.print("Engine initialized...\n", .{});
var store = try wasmtime.Store.init(engine);
defer store.deinit();
std.debug.print("Store initialized...\n", .{});
var module = try wasmtime.Module.initFromWat(engine, wasm);
defer module.deinit();
std.debug.print("Wasm module compiled...\n", .{});
var instance = try wasmtime.Instance.init(store, module, &.{});
defer instance.deinit();
std.debug.print("Instance initialized...\n", .{});
const memory = instance.getExportMem(module, "memory").?;
defer memory.deinit();
const size_func = instance.getExportFunc(module, "size").?;
const load_func = instance.getExportFunc(module, "load").?;
const store_func = instance.getExportFunc(module, "store").?;
// verify initial memory
assert(memory.pages() == 2);
assert(memory.size() == 0x20_000);
assert(memory.data()[0] == 0);
assert(memory.data()[0x1000] == 1);
assert(memory.data()[0x1003] == 4);
assertCall(size_func, 2);
assertCall1(load_func, 0, 0);
assertCall1(load_func, 0x1000, 1);
assertCall1(load_func, 0x1003, 4);
assertCall1(load_func, 0x1ffff, 0);
assertTrap(load_func, 0x20_000);
// mutate memory
memory.data()[0x1003] = 5;
assertCall2(store_func, 0x1002, 6);
assertTrap1(store_func, 0x20_000, 0);
// verify memory again
assert(memory.data()[0x1002] == 6);
assert(memory.data()[0x1003] == 5);
assertCall1(load_func, 0x1002, 6);
assertCall1(load_func, 0x1003, 5);
// Grow memory
try memory.grow(1); // 'allocate' 1 more page
assert(memory.pages() == 3);
assert(memory.size() == 0x30_000);
assertCall1(load_func, 0x20_000, 0);
assertCall2(store_func, 0x20_000, 0);
assertTrap(load_func, 0x30_000);
assertTrap1(store_func, 0x30_000, 0);
if (memory.grow(1)) |_| {} else |err| assert(err == error.OutOfMemory);
try memory.grow(0);
// create stand-alone memory
const mem_type = try wasmtime.MemoryType.init(.{ .min = 5, .max = 5 });
defer mem_type.deinit();
const mem = try wasmtime.Memory.init(store, mem_type);
defer mem.deinit();
assert(mem.pages() == 5);
if (mem.grow(1)) |_| {} else |err| assert(err == error.OutOfMemory);
try memory.grow(0);
}
fn assertCall(func: wasmtime.Func, result: u32) void {
const res = func.call(@TypeOf(result), .{}) catch std.debug.panic("Unexpected error", .{});
std.debug.assert(result == res);
}
fn assertCall1(func: wasmtime.Func, comptime arg: u32, result: u32) void {
const res = func.call(@TypeOf(arg), .{arg}) catch std.debug.panic("Unexpected error", .{});
std.debug.assert(result == res);
}
fn assertCall2(func: wasmtime.Func, comptime arg: u32, comptime arg2: u32) void {
const res = func.call(void, .{ arg, arg2 }) catch std.debug.panic("Unexpected error", .{});
std.debug.assert({} == res);
}
fn assertTrap(func: wasmtime.Func, comptime arg: u32) void {
if (func.call(@TypeOf(arg), .{arg})) |_| {
std.debug.panic("Expected Trap error, got result", .{});
} else |err| std.debug.assert(err == error.Trap);
}
fn assertTrap1(func: wasmtime.Func, comptime arg: u32, comptime arg2: u32) void {
if (func.call(void, .{ arg, arg2 })) |_| {
std.debug.panic("Expected Trap error, got result", .{});
} else |err| std.debug.assert(err == error.Trap);
} | examples/memory.zig |
const std = @import("std");
const testing = std.testing;
const Allocator = std.mem.Allocator;
// ustar tar implementation
pub const Header = extern struct {
name: [100]u8,
mode: [8]u8,
uid: [8]u8,
gid: [8]u8,
size: [11:0]u8,
mtime: [12]u8,
checksum: [8]u8,
typeflag: FileType,
linkname: [100]u8,
magic: [6]u8,
version: [2]u8,
uname: [32]u8,
gname: [32]u8,
devmajor: [8]u8,
devminor: [8]u8,
prefix: [155]u8,
pad: [12]u8 = [_]u8{0} ** 12,
const Self = @This();
const FileType = extern enum(u8) {
regular = '0',
hard_link = '1',
symbolic_link = '2',
character = '3',
block = '4',
directory = '5',
fifo = '6',
reserved = '7',
pax_global = 'g',
extended = 'x',
_,
};
pub fn isBlank(self: *const Header) bool {
const block = std.mem.asBytes(self);
return for (block) |elem| {
if (elem != 0) break false;
} else true;
}
};
test "Header size" {
testing.expectEqual(512, @sizeOf(Header));
}
pub fn instantiate(allocator: *Allocator, dir: std.fs.Dir, reader: anytype, skip_depth: usize) !void {
var count: usize = 0;
while (true) {
const header = reader.readStruct(Header) catch |err| {
return if (err == error.EndOfStream) if (count < 2) error.AbrubtEnd else break else err;
};
const block = std.mem.asBytes(&header);
if (header.isBlank()) {
count += 1;
continue;
} else if (count > 0) {
return error.Format;
}
var size = try std.fmt.parseUnsigned(usize, &header.size, 8);
const block_size = ((size + 511) / 512) * 512;
var components = std.ArrayList([]const u8).init(allocator);
defer components.deinit();
var path_it = std.mem.tokenize(&header.prefix, "/\x00");
if (header.prefix[0] != 0) {
while (path_it.next()) |component| {
try components.append(component);
}
}
path_it = std.mem.tokenize(&header.name, "/\x00");
while (path_it.next()) |component| {
try components.append(component);
}
const tmp_path = try std.fs.path.join(allocator, components.items);
defer allocator.free(tmp_path);
if (skip_depth >= components.items.len) {
try reader.skipBytes(block_size, .{});
continue;
}
var i: usize = 0;
while (i < skip_depth) : (i += 1) {
_ = components.orderedRemove(0);
}
const file_path = try std.fs.path.join(allocator, components.items);
defer allocator.free(file_path);
switch (header.typeflag) {
.directory => try dir.makePath(file_path),
.pax_global => try reader.skipBytes(512, .{}),
.regular => {
const file = try dir.createFile(file_path, .{ .read = true, .truncate = true });
defer file.close();
const skip_size = block_size - size;
var buf: [std.mem.page_size]u8 = undefined;
while (size > 0) {
const buffered = try reader.read(buf[0..std.math.min(size, 512)]);
try file.writeAll(buf[0..buffered]);
size -= buffered;
}
try reader.skipBytes(skip_size, .{});
},
else => {},
}
}
} | src/tar.zig |
const std = @import("std");
const linux = @cImport({
@cInclude("linux/input.h");
@cInclude("linux/input-event-codes.h");
});
fn code_lookup(code: u16) ?[]const u8 {
return switch (code) {
0x00 => "X", // ABS_X
0x01 => "Y", // ABS_Y
0x2f => "SLOT", // MT slot being modified
0x30 => "TOUCH_MAJOR", // Major axis of touching ellipse
0x31 => "TOUCH_MINOR", // Minor axis (omit if circular)
0x32 => "WIDTH_MAJOR", // Major axis of approaching ellipse
0x33 => "WIDTH_MINOR", // Minor axis (omit if circular)
0x34 => "ORIENTATION", // Ellipse orientation
0x35 => "POSITION_X", // Center X touch position
0x36 => "POSITION_Y", // Center Y touch position
0x37 => "TOOL_TYPE", // Type of touching device
0x38 => "BLOB_ID", // Group a set of packets as a blob
0x39 => "TRACKING_ID", // Unique ID of initiated contact
0x3a => "PRESSURE", // Pressure on contact area
0x3b => "DISTANCE", // Contact hover distance
0x3c => "TOOL_X", // Center X tool position
0x3d => "TOOL_Y", // Center Y tool position
0x145 => "BTN_TOOL_FINGER",
0x14a => "BTN_TOUCH",
0x14d => "BTN_TOOL_DOUBLETAP",
else => null,
};
}
pub const MAX_TOUCH_POINTS = 10;
var _start_time: i64 = -1;
pub const InputEvent = extern struct {
time: linux.timeval,
type: u16,
code: u16,
value: i32,
fn print_evt(input: *const InputEvent, name: []const u8) void {
if (code_lookup(input.code)) |code_name| {
std.debug.print(
" {s}({s}, {d})\n",
.{ name, code_name, input.value },
);
} else {
std.debug.print(
" {s}(0x{X}, {d})\n",
.{ name, input.code, input.value },
);
}
}
fn print_timed_evt(input: *const InputEvent, name: []const u8) void {
if (_start_time < 0) _start_time = std.time.timestamp();
// use time relative to the start of the program
const time: f64 =
std.math.lossyCast(f64, input.time.tv_sec - _start_time) +
std.math.lossyCast(f64, input.time.tv_usec) / 1e6;
std.debug.print(
" {s}(0x{X}, {d}) @ {d:.3}s\n",
.{ name, input.code, input.value, time },
);
}
pub fn print(input: *const InputEvent) void {
switch (input.type) {
linux.EV_KEY => input.print_evt("EV_KEY"),
linux.EV_ABS => input.print_evt("EV_ABS"),
linux.EV_MSC => input.print_evt("EV_MSC"),
linux.EV_SYN => input.print_evt("EV_SYN"),
else => std.debug.print(
" EV(0x{X}, 0x{X}, {d})\n",
.{ input.type, input.code, input.value },
),
}
}
};
pub const TouchData = struct {
used: bool = false,
pressed: bool = false,
pressed_double: bool = false,
tracking_id: i32 = -1,
position_x: i32,
position_y: i32,
pressure: i32,
distance: i32,
touch_major: i32,
touch_minor: i32,
width_major: i32,
width_minor: i32,
orientation: i32,
tool_x: i32,
tool_y: i32,
tool_type: i32,
fn set(self: *TouchData, comptime field: []const u8, value: anytype) void {
self.used = true;
@field(self, field) = value;
}
pub fn reset(self: *TouchData) void {
self.used = false;
self.pressed = false;
self.pressed_double = false;
self.tracking_id = -1;
self.position_x = 0;
self.position_y = 0;
self.pressure = 0;
self.distance = 0;
self.touch_major = 0;
self.touch_minor = 0;
self.width_major = 0;
self.width_minor = 0;
self.orientation = 0;
self.tool_x = 0;
self.tool_y = 0;
self.tool_type = 0;
}
};
const MTError = error{ SlotOutOfBounds, SlotIsNull, BadState };
const MTState = enum {
loading,
read_ready,
needs_reset,
};
pub const MTStateMachine = struct {
state: MTState = MTState.loading,
slot: ?usize = null,
touches: [MAX_TOUCH_POINTS]TouchData =
[1]TouchData{std.mem.zeroes(TouchData)} ** MAX_TOUCH_POINTS,
pub fn reset(self: *MTStateMachine) void {
self.state = MTState.loading;
self.slot = null;
for (self.touches) |_, i| {
self.touches[i].used = false;
}
}
pub fn process(self: *MTStateMachine, input: *const InputEvent) !void {
switch (input.type) {
linux.EV_KEY => {
switch (input.code) {
linux.BTN_TOUCH => {
self.touches[0].pressed = (input.value == 1);
},
linux.BTN_TOOL_DOUBLETAP => {
self.touches[0].pressed_double = (input.value == 1);
},
else => {},
}
},
linux.EV_ABS => {
switch (self.state) {
MTState.loading => {},
MTState.needs_reset => self.reset(),
MTState.read_ready => {}, // return MTError.BadState,
}
const slot = self.slot orelse 0;
const touch = &self.touches[slot];
switch (input.code) {
linux.ABS_MT_SLOT => {
if (input.value >= 0 and input.value < MAX_TOUCH_POINTS) {
self.slot = @intCast(usize, input.value);
self.touches[self.slot.?].used = true;
} else {
return MTError.SlotOutOfBounds;
}
},
linux.ABS_MT_TRACKING_ID => {
if (input.value < 0) {
touch.used = false;
} else {
touch.tracking_id = input.value;
}
},
linux.ABS_MT_POSITION_X => touch.set("position_x", input.value),
linux.ABS_MT_POSITION_Y => touch.set("position_y", input.value),
linux.ABS_MT_PRESSURE => touch.set("pressure", input.value),
linux.ABS_MT_DISTANCE => touch.set("distance", input.value),
linux.ABS_MT_TOUCH_MAJOR => touch.set("touch_major", input.value),
linux.ABS_MT_TOUCH_MINOR => touch.set("touch_minor", input.value),
linux.ABS_MT_WIDTH_MAJOR => touch.set("width_major", input.value),
linux.ABS_MT_WIDTH_MINOR => touch.set("width_minor", input.value),
linux.ABS_MT_ORIENTATION => touch.set("orientation", input.value),
linux.ABS_MT_TOOL_X => touch.set("tool_x", input.value),
linux.ABS_MT_TOOL_Y => touch.set("tool_y", input.value),
linux.ABS_MT_TOOL_TYPE => touch.set("tool_type", input.value),
else => {},
}
},
linux.EV_MSC => {},
linux.EV_SYN => {
self.state = MTState.read_ready;
},
else => {},
}
}
pub fn is_read_ready(self: *MTStateMachine) bool {
return self.state == MTState.read_ready;
}
}; | src/multitouch.zig |
const std = @import("../std.zig");
const math = std.math;
const testing = std.testing;
const maxInt = std.math.maxInt;
/// Returns the base-10 logarithm of x.
///
/// Special Cases:
/// - log10(+inf) = +inf
/// - log10(0) = -inf
/// - log10(x) = nan if x < 0
/// - log10(nan) = nan
pub fn log10(x: anytype) @TypeOf(x) {
const T = @TypeOf(x);
switch (@typeInfo(T)) {
.ComptimeFloat => {
return @as(comptime_float, log10_64(x));
},
.Float => {
return switch (T) {
f32 => log10_32(x),
f64 => log10_64(x),
else => @compileError("log10 not implemented for " ++ @typeName(T)),
};
},
.ComptimeInt => {
return @as(comptime_int, math.floor(log10_64(@as(f64, x))));
},
.Int => {
return @floatToInt(T, math.floor(log10_64(@intToFloat(f64, x))));
},
else => @compileError("log10 not implemented for " ++ @typeName(T)),
}
}
pub fn log10_32(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 -math.inf(f32);
}
// log(-#) = nan
if (ix >> 31 != 0) {
return math.nan(f32);
}
k -= 25;
x *= 0x1.0p25;
ix = @bitCast(u32, x);
} else if (ix >= 0x7F800000) {
return x;
} else if (ix == 0x3F800000) {
return 0;
}
// x into [sqrt(2) / 2, sqrt(2)]
ix += 0x3F800000 - 0x3F3504F3;
k += @intCast(i32, ix >> 23) - 0x7F;
ix = (ix & 0x007FFFFF) + 0x3F3504F3;
x = @bitCast(f32, ix);
const f = x - 1.0;
const s = f / (2.0 + f);
const z = s * s;
const w = z * z;
const t1 = w * (Lg2 + w * Lg4);
const t2 = z * (Lg1 + w * Lg3);
const R = t2 + t1;
const hfsq = 0.5 * f * f;
var hi = f - hfsq;
u = @bitCast(u32, hi);
u &= 0xFFFFF000;
hi = @bitCast(f32, u);
const lo = f - hi - hfsq + s * (hfsq + R);
const dk = @intToFloat(f32, k);
return dk * log10_2lo + (lo + hi) * ivln10lo + lo * ivln10hi + hi * ivln10hi + dk * log10_2hi;
}
pub fn log10_64(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 = @intCast(u32, ix >> 32);
var k: i32 = 0;
if (hx < 0x00100000 or hx >> 31 != 0) {
// log(+-0) = -inf
if (ix << 1 == 0) {
return -math.inf(f32);
}
// log(-#) = nan
if (hx >> 31 != 0) {
return math.nan(f32);
}
// subnormal, scale x
k -= 54;
x *= 0x1.0p54;
hx = @intCast(u32, @bitCast(u64, x) >> 32);
} else if (hx >= 0x7FF00000) {
return x;
} else if (hx == 0x3FF00000 and ix << 32 == 0) {
return 0;
}
// x into [sqrt(2) / 2, sqrt(2)]
hx += 0x3FF00000 - 0x3FE6A09E;
k += @intCast(i32, hx >> 20) - 0x3FF;
hx = (hx & 0x000FFFFF) + 0x3FE6A09E;
ix = (@as(u64, hx) << 32) | (ix & 0xFFFFFFFF);
x = @bitCast(f64, ix);
const f = x - 1.0;
const hfsq = 0.5 * f * f;
const s = f / (2.0 + f);
const z = s * s;
const w = z * z;
const t1 = w * (Lg2 + w * (Lg4 + w * Lg6));
const t2 = z * (Lg1 + w * (Lg3 + w * (Lg5 + w * Lg7)));
const R = t2 + t1;
// hi + lo = f - hfsq + s * (hfsq + R) ~ log(1 + f)
var hi = f - hfsq;
var hii = @bitCast(u64, hi);
hii &= @as(u64, maxInt(u64)) << 32;
hi = @bitCast(f64, hii);
const lo = f - hi - hfsq + s * (hfsq + R);
// val_hi + val_lo ~ log10(1 + f) + k * log10(2)
var val_hi = hi * ivln10hi;
const dk = @intToFloat(f64, k);
const y = dk * log10_2hi;
var val_lo = dk * log10_2lo + (lo + hi) * ivln10lo + lo * ivln10hi;
// Extra precision multiplication
const ww = y + val_hi;
val_lo += (y - ww) + val_hi;
val_hi = ww;
return val_lo + val_hi;
}
test "math.log10" {
testing.expect(log10(@as(f32, 0.2)) == log10_32(0.2));
testing.expect(log10(@as(f64, 0.2)) == log10_64(0.2));
}
test "math.log10_32" {
const epsilon = 0.000001;
testing.expect(math.approxEqAbs(f32, log10_32(0.2), -0.698970, epsilon));
testing.expect(math.approxEqAbs(f32, log10_32(0.8923), -0.049489, epsilon));
testing.expect(math.approxEqAbs(f32, log10_32(1.5), 0.176091, epsilon));
testing.expect(math.approxEqAbs(f32, log10_32(37.45), 1.573452, epsilon));
testing.expect(math.approxEqAbs(f32, log10_32(89.123), 1.94999, epsilon));
testing.expect(math.approxEqAbs(f32, log10_32(123123.234375), 5.09034, epsilon));
}
test "math.log10_64" {
const epsilon = 0.000001;
testing.expect(math.approxEqAbs(f64, log10_64(0.2), -0.698970, epsilon));
testing.expect(math.approxEqAbs(f64, log10_64(0.8923), -0.049489, epsilon));
testing.expect(math.approxEqAbs(f64, log10_64(1.5), 0.176091, epsilon));
testing.expect(math.approxEqAbs(f64, log10_64(37.45), 1.573452, epsilon));
testing.expect(math.approxEqAbs(f64, log10_64(89.123), 1.94999, epsilon));
testing.expect(math.approxEqAbs(f64, log10_64(123123.234375), 5.09034, epsilon));
}
test "math.log10_32.special" {
testing.expect(math.isPositiveInf(log10_32(math.inf(f32))));
testing.expect(math.isNegativeInf(log10_32(0.0)));
testing.expect(math.isNan(log10_32(-1.0)));
testing.expect(math.isNan(log10_32(math.nan(f32))));
}
test "math.log10_64.special" {
testing.expect(math.isPositiveInf(log10_64(math.inf(f64))));
testing.expect(math.isNegativeInf(log10_64(0.0)));
testing.expect(math.isNan(log10_64(-1.0)));
testing.expect(math.isNan(log10_64(math.nan(f64))));
} | lib/std/math/log10.zig |
const std = @import("../std.zig");
const builtin = @import("builtin");
const assert = std.debug.assert;
const testing = std.testing;
const mem = std.mem;
const Loop = std.event.Loop;
/// Thread-safe async/await lock.
/// Functions which are waiting for the lock are suspended, and
/// are resumed when the lock is released, in order.
/// Many readers can hold the lock at the same time; however locking for writing is exclusive.
/// When a read lock is held, it will not be released until the reader queue is empty.
/// When a write lock is held, it will not be released until the writer queue is empty.
/// TODO: make this API also work in blocking I/O mode
pub const RwLock = struct {
shared_state: State,
writer_queue: Queue,
reader_queue: Queue,
writer_queue_empty: bool,
reader_queue_empty: bool,
reader_lock_count: usize,
const State = enum(u8) {
Unlocked,
WriteLock,
ReadLock,
};
const Queue = std.atomic.Queue(anyframe);
const global_event_loop = Loop.instance orelse
@compileError("std.event.RwLock currently only works with event-based I/O");
pub const HeldRead = struct {
lock: *RwLock,
pub fn release(self: HeldRead) void {
// If other readers still hold the lock, we're done.
if (@atomicRmw(usize, &self.lock.reader_lock_count, .Sub, 1, .SeqCst) != 1) {
return;
}
@atomicStore(bool, &self.lock.reader_queue_empty, true, .SeqCst);
if (@cmpxchgStrong(State, &self.lock.shared_state, .ReadLock, .Unlocked, .SeqCst, .SeqCst) != null) {
// Didn't unlock. Someone else's problem.
return;
}
self.lock.commonPostUnlock();
}
};
pub const HeldWrite = struct {
lock: *RwLock,
pub fn release(self: HeldWrite) void {
// See if we can leave it locked for writing, and pass the lock to the next writer
// in the queue to grab the lock.
if (self.lock.writer_queue.get()) |node| {
global_event_loop.onNextTick(node);
return;
}
// We need to release the write lock. Check if any readers are waiting to grab the lock.
if (!@atomicLoad(bool, &self.lock.reader_queue_empty, .SeqCst)) {
// Switch to a read lock.
@atomicStore(State, &self.lock.shared_state, .ReadLock, .SeqCst);
while (self.lock.reader_queue.get()) |node| {
global_event_loop.onNextTick(node);
}
return;
}
@atomicStore(bool, &self.lock.writer_queue_empty, true, .SeqCst);
@atomicStore(State, &self.lock.shared_state, .Unlocked, .SeqCst);
self.lock.commonPostUnlock();
}
};
pub fn init() RwLock {
return .{
.shared_state = .Unlocked,
.writer_queue = Queue.init(),
.writer_queue_empty = true,
.reader_queue = Queue.init(),
.reader_queue_empty = true,
.reader_lock_count = 0,
};
}
/// Must be called when not locked. Not thread safe.
/// All calls to acquire() and release() must complete before calling deinit().
pub fn deinit(self: *RwLock) void {
assert(self.shared_state == .Unlocked);
while (self.writer_queue.get()) |node| resume node.data;
while (self.reader_queue.get()) |node| resume node.data;
}
pub fn acquireRead(self: *RwLock) callconv(.Async) HeldRead {
_ = @atomicRmw(usize, &self.reader_lock_count, .Add, 1, .SeqCst);
suspend {
var my_tick_node = Loop.NextTickNode{
.data = @frame(),
.prev = undefined,
.next = undefined,
};
self.reader_queue.put(&my_tick_node);
// At this point, we are in the reader_queue, so we might have already been resumed.
// We set this bit so that later we can rely on the fact, that if reader_queue_empty == true,
// some actor will attempt to grab the lock.
@atomicStore(bool, &self.reader_queue_empty, false, .SeqCst);
// Here we don't care if we are the one to do the locking or if it was already locked for reading.
const have_read_lock = if (@cmpxchgStrong(State, &self.shared_state, .Unlocked, .ReadLock, .SeqCst, .SeqCst)) |old_state| old_state == .ReadLock else true;
if (have_read_lock) {
// Give out all the read locks.
if (self.reader_queue.get()) |first_node| {
while (self.reader_queue.get()) |node| {
global_event_loop.onNextTick(node);
}
resume first_node.data;
}
}
}
return HeldRead{ .lock = self };
}
pub fn acquireWrite(self: *RwLock) callconv(.Async) HeldWrite {
suspend {
var my_tick_node = Loop.NextTickNode{
.data = @frame(),
.prev = undefined,
.next = undefined,
};
self.writer_queue.put(&my_tick_node);
// At this point, we are in the writer_queue, so we might have already been resumed.
// We set this bit so that later we can rely on the fact, that if writer_queue_empty == true,
// some actor will attempt to grab the lock.
@atomicStore(bool, &self.writer_queue_empty, false, .SeqCst);
// Here we must be the one to acquire the write lock. It cannot already be locked.
if (@cmpxchgStrong(State, &self.shared_state, .Unlocked, .WriteLock, .SeqCst, .SeqCst) == null) {
// We now have a write lock.
if (self.writer_queue.get()) |node| {
// Whether this node is us or someone else, we tail resume it.
resume node.data;
}
}
}
return HeldWrite{ .lock = self };
}
fn commonPostUnlock(self: *RwLock) void {
while (true) {
// There might be a writer_queue item or a reader_queue item
// If we check and both are empty, we can be done, because the other actors will try to
// obtain the lock.
// But if there's a writer_queue item or a reader_queue item,
// we are the actor which must loop and attempt to grab the lock again.
if (!@atomicLoad(bool, &self.writer_queue_empty, .SeqCst)) {
if (@cmpxchgStrong(State, &self.shared_state, .Unlocked, .WriteLock, .SeqCst, .SeqCst) != null) {
// We did not obtain the lock. Great, the queues are someone else's problem.
return;
}
// If there's an item in the writer queue, give them the lock, and we're done.
if (self.writer_queue.get()) |node| {
global_event_loop.onNextTick(node);
return;
}
// Release the lock again.
@atomicStore(bool, &self.writer_queue_empty, true, .SeqCst);
@atomicStore(State, &self.shared_state, .Unlocked, .SeqCst);
continue;
}
if (!@atomicLoad(bool, &self.reader_queue_empty, .SeqCst)) {
if (@cmpxchgStrong(State, &self.shared_state, .Unlocked, .ReadLock, .SeqCst, .SeqCst) != null) {
// We did not obtain the lock. Great, the queues are someone else's problem.
return;
}
// If there are any items in the reader queue, give out all the reader locks, and we're done.
if (self.reader_queue.get()) |first_node| {
global_event_loop.onNextTick(first_node);
while (self.reader_queue.get()) |node| {
global_event_loop.onNextTick(node);
}
return;
}
// Release the lock again.
@atomicStore(bool, &self.reader_queue_empty, true, .SeqCst);
if (@cmpxchgStrong(State, &self.shared_state, .ReadLock, .Unlocked, .SeqCst, .SeqCst) != null) {
// Didn't unlock. Someone else's problem.
return;
}
continue;
}
return;
}
}
};
test "std.event.RwLock" {
// https://github.com/ziglang/zig/issues/2377
if (true) return error.SkipZigTest;
// https://github.com/ziglang/zig/issues/1908
if (builtin.single_threaded) return error.SkipZigTest;
// TODO provide a way to run tests in evented I/O mode
if (!std.io.is_async) return error.SkipZigTest;
var lock = RwLock.init();
defer lock.deinit();
const handle = testLock(std.heap.page_allocator, &lock);
const expected_result = [1]i32{shared_it_count * @intCast(i32, shared_test_data.len)} ** shared_test_data.len;
try testing.expectEqualSlices(i32, expected_result, shared_test_data);
}
fn testLock(allocator: *Allocator, lock: *RwLock) callconv(.Async) void {
var read_nodes: [100]Loop.NextTickNode = undefined;
for (read_nodes) |*read_node| {
const frame = allocator.create(@Frame(readRunner)) catch @panic("memory");
read_node.data = frame;
frame.* = async readRunner(lock);
Loop.instance.?.onNextTick(read_node);
}
var write_nodes: [shared_it_count]Loop.NextTickNode = undefined;
for (write_nodes) |*write_node| {
const frame = allocator.create(@Frame(writeRunner)) catch @panic("memory");
write_node.data = frame;
frame.* = async writeRunner(lock);
Loop.instance.?.onNextTick(write_node);
}
for (write_nodes) |*write_node| {
const casted = @ptrCast(*const @Frame(writeRunner), write_node.data);
await casted;
allocator.destroy(casted);
}
for (read_nodes) |*read_node| {
const casted = @ptrCast(*const @Frame(readRunner), read_node.data);
await casted;
allocator.destroy(casted);
}
}
const shared_it_count = 10;
var shared_test_data = [1]i32{0} ** 10;
var shared_test_index: usize = 0;
var shared_count: usize = 0;
fn writeRunner(lock: *RwLock) callconv(.Async) void {
suspend {} // resumed by onNextTick
var i: usize = 0;
while (i < shared_test_data.len) : (i += 1) {
std.time.sleep(100 * std.time.microsecond);
const lock_promise = async lock.acquireWrite();
const handle = await lock_promise;
defer handle.release();
shared_count += 1;
while (shared_test_index < shared_test_data.len) : (shared_test_index += 1) {
shared_test_data[shared_test_index] = shared_test_data[shared_test_index] + 1;
}
shared_test_index = 0;
}
}
fn readRunner(lock: *RwLock) callconv(.Async) void {
suspend {} // resumed by onNextTick
std.time.sleep(1);
var i: usize = 0;
while (i < shared_test_data.len) : (i += 1) {
const lock_promise = async lock.acquireRead();
const handle = await lock_promise;
defer handle.release();
try testing.expect(shared_test_index == 0);
try testing.expect(shared_test_data[i] == @intCast(i32, shared_count));
}
} | lib/std/event/rwlock.zig |
const std = @import("std");
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
const mem = std.mem;
test "continue in for loop" {
const array = [_]i32{ 1, 2, 3, 4, 5 };
var sum: i32 = 0;
for (array) |x| {
sum += x;
if (x < 3) {
continue;
}
break;
}
if (sum != 6) unreachable;
}
test "break from outer for loop" {
try testBreakOuter();
comptime try testBreakOuter();
}
fn testBreakOuter() !void {
var array = "aoeu";
var count: usize = 0;
outer: for (array) |_| {
for (array) |_| {
count += 1;
break :outer;
}
}
try expect(count == 1);
}
test "continue outer for loop" {
try testContinueOuter();
comptime try testContinueOuter();
}
fn testContinueOuter() !void {
var array = "aoeu";
var counter: usize = 0;
outer: for (array) |_| {
for (array) |_| {
counter += 1;
continue :outer;
}
}
try expect(counter == array.len);
}
test "ignore lval with underscore (for loop)" {
for ([_]void{}) |_, i| {
_ = i;
for ([_]void{}) |_, j| {
_ = j;
break;
}
break;
}
}
test "basic for loop" {
if (@import("builtin").zig_backend == .stage2_wasm) {
// TODO this is a recent stage2 test case regression due to an enhancement;
// now arrays are properly detected as comptime. This exercised a new code
// path in the wasm backend that is not yet implemented.
return error.SkipZigTest;
}
const expected_result = [_]u8{ 9, 8, 7, 6, 0, 1, 2, 3 } ** 3;
var buffer: [expected_result.len]u8 = undefined;
var buf_index: usize = 0;
const array = [_]u8{ 9, 8, 7, 6 };
for (array) |item| {
buffer[buf_index] = item;
buf_index += 1;
}
for (array) |item, index| {
_ = item;
buffer[buf_index] = @intCast(u8, index);
buf_index += 1;
}
const array_ptr = &array;
for (array_ptr) |item| {
buffer[buf_index] = item;
buf_index += 1;
}
for (array_ptr) |item, index| {
_ = item;
buffer[buf_index] = @intCast(u8, index);
buf_index += 1;
}
const unknown_size: []const u8 = &array;
for (unknown_size) |item| {
buffer[buf_index] = item;
buf_index += 1;
}
for (unknown_size) |_, index| {
buffer[buf_index] = @intCast(u8, index);
buf_index += 1;
}
try expect(mem.eql(u8, buffer[0..buf_index], &expected_result));
}
test "for with null and T peer types and inferred result location type" {
const S = struct {
fn doTheTest(slice: []const u8) !void {
if (for (slice) |item| {
if (item == 10) {
break item;
}
} else null) |v| {
_ = v;
@panic("fail");
}
}
};
try S.doTheTest(&[_]u8{ 1, 2 });
comptime try S.doTheTest(&[_]u8{ 1, 2 });
}
test "2 break statements and an else" {
const S = struct {
fn entry(t: bool, f: bool) !void {
var buf: [10]u8 = undefined;
var ok = false;
ok = for (buf) |item| {
_ = item;
if (f) break false;
if (t) break true;
} else false;
try expect(ok);
}
};
try S.entry(true, false);
comptime try S.entry(true, false);
} | test/behavior/for.zig |
const aoc = @import("../aoc.zig");
const std = @import("std");
const SCREEN_WIDTH = 50;
const SCREEN_HEIGHT = 6;
const ScreenRowType = std.meta.Int(.unsigned, SCREEN_WIDTH);
const ScreenColumnType = std.meta.Int(.unsigned, SCREEN_HEIGHT);
const Screen = std.bit_set.StaticBitSet(SCREEN_WIDTH * SCREEN_HEIGHT);
pub fn run(problem: *aoc.Problem) !aoc.Solution {
var screen = Screen.initEmpty();
while (problem.line()) |line| {
var tokens = std.mem.tokenize(u8, line, " xy=");
if (std.mem.eql(u8, tokens.next().?, "rect")) {
rect(&screen, try std.fmt.parseInt(u8, tokens.next().?, 10), try std.fmt.parseInt(u8, tokens.next().?, 10));
}
else {
const rotateFn = if (std.mem.eql(u8, tokens.next().?, "row")) rotateRow else rotateColumn;
const a = try std.fmt.parseInt(u8, tokens.next().?, 10);
_ = tokens.next().?;
const b = try std.fmt.parseInt(u8, tokens.next().?, 10);
rotateFn(&screen, a, b);
}
}
var code: [(SCREEN_WIDTH + 1) * SCREEN_HEIGHT]u8 = undefined;
std.mem.copy(u8, &code, ("." ** SCREEN_WIDTH ++ "\n") ** 6);
var iter = screen.iterator(.{});
while (iter.next()) |idx| {
code[idx + idx / SCREEN_WIDTH] = '#';
}
return problem.solution(screen.count(), &code);
}
fn rect(screen: *Screen, width: u8, height: u8) void {
var row_offset: usize = 0;
while (row_offset < SCREEN_WIDTH * height) : (row_offset += SCREEN_WIDTH) {
var col_offset: u8 = 0;
while (col_offset < width) : (col_offset += 1) {
screen.set(row_offset + col_offset);
}
}
}
fn rotateRow(screen: *Screen, row: u8, amount: u8) void {
var row_mask: ScreenRowType = 0;
var offset: usize = SCREEN_WIDTH * row;
while (offset < @as(usize, SCREEN_WIDTH) * (row + 1)) : (offset += 1) {
row_mask = (row_mask << 1) | @boolToInt(screen.isSet(offset));
}
row_mask = std.math.rotr(ScreenRowType, row_mask, amount);
offset = SCREEN_WIDTH * row;
while (offset < @as(usize, SCREEN_WIDTH) * (row + 1)) : (offset += 1) {
screen.setValue(offset, row_mask & (1 << (SCREEN_WIDTH - 1)) != 0);
row_mask <<= 1;
}
}
fn rotateColumn(screen: *Screen, col: u8, amount: u8) void {
var column_mask: ScreenColumnType = 0;
var row_offset: usize = 0;
while (row_offset < SCREEN_WIDTH * SCREEN_HEIGHT) : (row_offset += SCREEN_WIDTH) {
column_mask = (column_mask << 1) | @boolToInt(screen.isSet(row_offset + col));
}
column_mask = std.math.rotr(ScreenColumnType, column_mask, amount);
row_offset = 0;
while (row_offset < SCREEN_WIDTH * SCREEN_HEIGHT) : (row_offset += SCREEN_WIDTH) {
screen.setValue(row_offset + col, column_mask & (1 << (SCREEN_HEIGHT - 1)) != 0);
column_mask <<= 1;
}
} | src/main/zig/2016/day08.zig |
const assertOrPanic = @import("std").debug.assertOrPanic;
test "optional type" {
const x: ?bool = true;
if (x) |y| {
if (y) {
// OK
} else {
unreachable;
}
} else {
unreachable;
}
const next_x: ?i32 = null;
const z = next_x orelse 1234;
assertOrPanic(z == 1234);
const final_x: ?i32 = 13;
const num = final_x orelse unreachable;
assertOrPanic(num == 13);
}
test "test maybe object and get a pointer to the inner value" {
var maybe_bool: ?bool = true;
if (maybe_bool) |*b| {
b.* = false;
}
assertOrPanic(maybe_bool.? == false);
}
test "rhs maybe unwrap return" {
const x: ?bool = true;
const y = x orelse return;
}
test "maybe return" {
maybeReturnImpl();
comptime maybeReturnImpl();
}
fn maybeReturnImpl() void {
assertOrPanic(foo(1235).?);
if (foo(null) != null) unreachable;
assertOrPanic(!foo(1234).?);
}
fn foo(x: ?i32) ?bool {
const value = x orelse return null;
return value > 1234;
}
test "if var maybe pointer" {
assertOrPanic(shouldBeAPlus1(Particle{
.a = 14,
.b = 1,
.c = 1,
.d = 1,
}) == 15);
}
fn shouldBeAPlus1(p: Particle) u64 {
var maybe_particle: ?Particle = p;
if (maybe_particle) |*particle| {
particle.a += 1;
}
if (maybe_particle) |particle| {
return particle.a;
}
return 0;
}
const Particle = struct {
a: u64,
b: u64,
c: u64,
d: u64,
};
test "null literal outside function" {
const is_null = here_is_a_null_literal.context == null;
assertOrPanic(is_null);
const is_non_null = here_is_a_null_literal.context != null;
assertOrPanic(!is_non_null);
}
const SillyStruct = struct {
context: ?i32,
};
const here_is_a_null_literal = SillyStruct{ .context = null };
test "test null runtime" {
testTestNullRuntime(null);
}
fn testTestNullRuntime(x: ?i32) void {
assertOrPanic(x == null);
assertOrPanic(!(x != null));
}
test "optional void" {
optionalVoidImpl();
comptime optionalVoidImpl();
}
fn optionalVoidImpl() void {
assertOrPanic(bar(null) == null);
assertOrPanic(bar({}) != null);
}
fn bar(x: ?void) ?void {
if (x) |_| {
return {};
} else {
return null;
}
}
const StructWithOptional = struct {
field: ?i32,
};
var struct_with_optional: StructWithOptional = undefined;
test "unwrap optional which is field of global var" {
struct_with_optional.field = null;
if (struct_with_optional.field) |payload| {
unreachable;
}
struct_with_optional.field = 1234;
if (struct_with_optional.field) |payload| {
assertOrPanic(payload == 1234);
} else {
unreachable;
}
}
test "null with default unwrap" {
const x: i32 = null orelse 1;
assertOrPanic(x == 1);
}
test "optional types" {
comptime {
const opt_type_struct = StructWithOptionalType{ .t = u8 };
assertOrPanic(opt_type_struct.t != null and opt_type_struct.t.? == u8);
}
}
const StructWithOptionalType = struct {
t: ?type,
};
test "optional pointer to 0 bit type null value at runtime" {
const EmptyStruct = struct {};
var x: ?*EmptyStruct = null;
assertOrPanic(x == null);
} | test/stage1/behavior/null.zig |
const std = @import("std");
const flags_ = @import("../flags.zig");
const CreateFlags = flags_.CreateFlags;
const FieldFlagsDef = flags_.FieldFlagsDef;
pub fn cpuCycled(self: anytype) void {
self.apu.runCycle();
self.ppu.runCycle();
self.ppu.runCycle();
self.ppu.runCycle();
self.mem.cart.cpuCycled();
}
pub const Registers = struct {
pc: u16,
s: u8,
a: u8,
x: u8,
y: u8,
p: u8,
const ff_masks = CreateFlags(Registers, ([_]FieldFlagsDef{
.{ .field = "p", .flags = "NV??DIZC" },
})[0..]){};
/// Convenient for testing
pub fn zeroes() Registers {
return std.mem.zeroes(Registers);
}
/// Real world observed values
pub fn startup() Registers {
return Registers{
.pc = 0x00,
.s = 0xfd,
.a = 0x00,
.x = 0x00,
.y = 0x00,
.p = 0x34,
};
}
pub fn getFlag(self: Registers, comptime flags: []const u8) bool {
return ff_masks.getFlag(self, .{ .flags = flags });
}
pub fn getFlags(self: Registers, comptime flags: []const u8) u8 {
return ff_masks.getFlags(self, .{ .flags = flags });
}
pub fn setFlag(self: *Registers, comptime flags: []const u8, val: bool) void {
return ff_masks.setFlag(self, .{ .flags = flags }, val);
}
pub fn setFlags(self: *Registers, comptime flags: []const u8, val: u8) void {
return ff_masks.setFlags(self, .{ .flags = flags }, val);
}
pub fn setFlagsNZ(self: *Registers, val: u8) void {
self.setFlags("NZ", (val & 0x80) | @as(u8, @boolToInt(val == 0)) << 1);
}
fn FieldType(comptime field: []const u8) type {
std.debug.assert(@hasField(Registers, field) or Registers.hasFlags(field));
if (std.mem.eql(u8, field, "pc")) {
return u16;
} else {
return u8;
}
}
pub fn get(self: Registers, comptime field: []const u8) FieldType(field) {
if (@hasField(Registers, field)) {
return @field(self, field);
} else if (Registers.hasFlags(field)) {
return self.getFlags(field);
} else {
@compileError("Unknown field for registers");
}
}
pub fn set(self: *Registers, comptime field: []const u8, val: u8) void {
if (@hasField(Registers, field)) {
@field(self, field) = val;
} else if (Registers.hasFlags(field)) {
return self.setFlags(field, val);
} else {
@compileError("Unknown field for registers");
}
}
}; | src/cpu/common.zig |
const Self = @This();
// The status area we are currently using.
area: *sys.flash.FlashArea = undefined,
// We have a buffer for the last page and one for the other pages.
buf_last: LastPage = undefined,
buf_hash: HashPage = undefined,
// The last page we've written to. 0 is the "ultimate" page, and '1'
// is the penultimate page.
last_page: u1 = 0,
const std = @import("std");
const testing = std.testing;
const sys = @import("../../src/sys.zig");
const BootTest = @import("../test.zig").BootTest;
// TODO: This should be configured, not pulled from the swap code.
// const swap_hash = @import("../sim/swap-hash.zig");
const Swap = @import("../swap.zig").Swap;
const page_size = Swap.page_size;
const page_shift = Swap.page_shift;
const FlashArea = sys.flash.FlashArea;
/// The phase of the flash upgrade.
pub const Phase = enum(u8) {
/// This doesn't appear to be in any identifiable state. This
/// could mean the magic number is not present, or hashes are
/// incorrect.
Unknown,
/// An upgrade has been requested. This is not directly written to
/// the status page, but is indicated when the magic value has been
/// written with no other data.
Request,
/// Sliding has started or is about to start. This is the move of
/// slot 0 down a single page.
Slide,
/// Swapping has started or is about to start. This is the
/// exchange of the swapped image to the new one.
Swap,
/// Indicates that we have completed everything, the images are
/// swapped.
Done,
/// Query which step of work is done by this phase, or return
/// error.InvalidPhase if this is not a phase indicating work to
/// be done.
pub fn whichWork(self: Phase) !usize {
switch (self) {
.Slide => return 0,
.Swap => return 1,
else => return error.InvalidPhase,
}
}
};
pub fn init(fa: *sys.flash.FlashArea) !Self {
return Self{
.area = fa,
};
}
/// Scan the contents of flash to determine what state we are in.
pub fn scan(self: *Self) !Phase {
const ult = (self.area.size >> page_shift) - 1;
const penult = ult - 1;
// Zephyr's flash API will allow reads from unwritten data, even
// on devices with ECC, and it just fakes the data being erased.
// We want to use readStatus here first, because we want to make
// it clear to the simulator that we are able to handle unwritten
// data. This only happens on the two status pages, so this
// shouldn't be a performance issue.
const ultStatus = try self.validMagic(ult);
const penultStatus = try self.validMagic(penult);
// std.log.info("off:{x}, ult: {}, penult: {}", .{ self.area.off, ultStatus, penultStatus });
// If neither area is readable, then we know we don't have any
// data.
if (!ultStatus and !penultStatus) {
return .Unknown;
}
// Try reading the ultimate buffer (last page).
var ultSeq: ?u32 = null;
var penultSeq: ?u32 = null;
if (ultStatus) {
ultSeq = try self.validLast(ult);
}
if (penultStatus) {
penultSeq = try self.validLast(penult);
}
// There are 4 combinations of the sequences being valid.
var valid = false;
if (ultSeq) |useq| {
if (penultSeq) |puseq| {
// Both are valid. We should go with the earlier one.
// The last read was of the penult one, so if the latest
// one is newer, go back and reread the ultimate one.
if (useq < puseq) {
if ((try self.validLast(ult)) == null) {
// This should probably be checked, and just
// abort, it would indicate we couldn't read this
// data a second time.
unreachable;
}
}
// The buf_last is now the current version of the last
// data.
valid = true;
self.last_page = 0;
} else {
// The ultimate one is valid, but we overwrote the buffer
// when we read the penult.
if (penultStatus) {
if ((try self.validLast(ult)) == null) {
unreachable;
}
}
valid = true;
}
} else {
if (penultSeq) |_| {
// The penultimate buffer is the only valid one, so just
// use it.
valid = true;
self.last_page = 1;
} else {
// Nothing is valid.
}
}
if (valid) {
return self.buf_last.phase;
}
// Otherwise, we have magic, but no valid state.
return .Request;
// if self.area.read(ult << page_shift, std.mem.asBytes(&buf_last));
// if self.area.read(penult << page_shift, std.mem.asBytes(&buf_last));
}
// Try reading the page, and return true if the page has a valid magic
// number in it.
fn validMagic(self: *Self, page: usize) !bool {
if ((try self.area.getState(page << page_shift)) == .Written) {
// TODO: Only really need to try reading the magic.
// This read can fail, either if the device has ECC, or we are
// in the simulator.
if (self.area.read(page << page_shift, std.mem.asBytes(&self.buf_last))) |_| {
return self.buf_last.magic.eql(&page_magic);
} else |err| {
if (err != error.ReadUnwritten)
return err;
return false;
}
}
return false;
}
// Try reading the given page into the last buffer, and return its
// sequence number if the hash indicates it is valid.
fn validLast(self: *Self, page: usize) !?u32 {
try self.area.read(page << page_shift, std.mem.asBytes(&self.buf_last));
const hash = Swap.calcHash(std.mem.asBytes(&self.buf_last)[0 .. 512 - 20]);
// std.log.info("validLast (page {}): {s} and {s}", .{
// page,
// std.fmt.fmtSliceHexLower(hash[0..]),
// std.fmt.fmtSliceHexLower(self.buf_last.hash[0..]),
// });
if (std.mem.eql(u8, self.buf_last.hash[0..], hash[0..])) {
// std.log.info("valid last: {}", .{self.buf_last.seq});
return self.buf_last.seq;
} else {
// std.log.info("invalid last", .{});
return null;
}
}
test "Status scanning" {
var bt = try BootTest.init(testing.allocator, BootTest.lpc55s69);
defer bt.deinit();
const sizes = [2]usize{ 112 * page_size + 7, 105 * page_size + page_size - 1 };
// const sizes = [2]usize{ 17 * page_size + 7, 14 * page_size + page_size - 1 };
var state = try Self.init(try bt.sim.open(1));
// Before initialization, status should come back
var status = try state.scan();
try std.testing.expectEqual(Phase.Unknown, status);
// Write the magic, and make sure the status changes to Request.
try state.writeMagic();
status = try state.scan();
try std.testing.expectEqual(Phase.Request, status);
// Do a status write. This should go into slot 0.
var swap: Swap = undefined;
try swap.fakeHashes(sizes);
// Write this out.
// We need to fill in enough to make this work.
swap.areas[0] = try bt.sim.open(0);
swap.areas[1] = try bt.sim.open(1);
try state.startStatus(&swap);
try swap.areas[0].save("status-scan0.bin");
try swap.areas[1].save("status-scan1.bin");
// Blow away the memory structure.
std.mem.set(u8, std.mem.asBytes(&swap), 0xAA);
swap.areas[0] = try bt.sim.open(0);
swap.areas[1] = try bt.sim.open(1);
const ph = try state.scan();
try std.testing.expectEqual(Phase.Slide, ph);
try state.loadStatus(&swap);
try swap.checkFakeHashes(sizes);
}
// Write a magic page to the given area. This is done in slot 1 to
// indicate that a swap should be initiated.
pub fn writeMagic(self: *Self) !void {
const ult = (self.area.size >> page_shift) - 1;
const penult = ult - 1;
std.mem.set(u8, std.mem.asBytes(&self.buf_last), 0xFF);
self.buf_last.magic = page_magic;
// Erase both pages.
try self.area.erase(ult << page_shift, page_size);
try self.area.erase(penult << page_shift, page_size);
try self.area.write(ult << page_shift, std.mem.asBytes(&self.buf_last));
}
// Write out the initial status page(s) indicating we are starting
// work.
pub fn startStatus(self: *Self, st: *Swap) !void {
// Compute how many extra pages are needed.
var extras: usize = 0;
const total_hashes = asPages(st.sizes[0]) + asPages(st.sizes[1]);
// TODO: Use buf_last
std.mem.set(u8, std.mem.asBytes(&self.buf_last), 0xFF);
const ult = (self.area.size >> page_shift) - 1;
const penult = ult - 1;
if (total_hashes > self.buf_last.hashes.len) {
var remaining = total_hashes - self.buf_last.hashes.len;
while (remaining > 0) {
extras += 1;
var count = self.buf_hash.hashes.len;
if (count > remaining)
count = remaining;
remaining -= count;
}
}
// The ordering/layout of the hash pages is a little "weird" but
// designed to be simplier to write and read. The hashes are
// written starting with the first hash page, then decrementing
// through memory, with the final remaining pieces in the 'last'
// page.
//
// The hash pages need to be written first, because the recover
// code assumes that if the lastpage is readable, the hashes have
// already been written.
var srcIter = st.iterHashes();
var dst: usize = 0;
const old_extras = extras;
var hash_page = penult - 1;
while (extras > 0) : (extras -= 1) {
std.mem.set(u8, std.mem.asBytes(&self.buf_hash), 0);
dst = 0;
while (dst < self.buf_hash.hashes.len) : (dst += 1) {
if (srcIter.next()) |src| {
self.buf_hash.hashes[dst] = src.*;
// const srcv = std.mem.bytesToValue(u32, src[0..]);
// std.log.warn("Write {x:0>8} to page:{} at {}", .{ srcv, hash_page, dst });
} else {
// Math above was incorrect.
unreachable;
}
}
// Update the hash.
const thehash = Swap.calcHash(std.mem.asBytes(&self.buf_hash)[0 .. 512 - 4]);
std.mem.copy(u8, self.buf_hash.hash[0..], thehash[0..]);
try self.area.erase(hash_page << page_shift, page_size);
try self.area.write(hash_page << page_shift, std.mem.asBytes(&self.buf_hash));
hash_page -= 1;
}
extras = old_extras;
self.buf_last.sizes[0] = @intCast(u32, st.sizes[0]);
self.buf_last.sizes[1] = @intCast(u32, st.sizes[1]);
std.mem.copy(u8, self.buf_last.prefix[0..], st.prefix[0..]);
self.buf_last.phase = .Slide;
self.buf_last.swap_info = 0;
self.buf_last.copy_done = 0;
self.buf_last.image_ok = 0;
self.buf_last.seq = 1;
dst = 0;
while (dst < self.buf_last.hashes.len) : (dst += 1) {
if (srcIter.next()) |src| {
std.mem.copy(u8, self.buf_last.hashes[dst][0..], src[0..]);
} else {
break;
}
}
// TODO: Write out the other pages.
// Update the hash.
const lasthash = Swap.calcHash(std.mem.asBytes(&self.buf_last)[0 .. 512 - 20]);
std.mem.copy(u8, self.buf_last.hash[0..], lasthash[0..]);
self.buf_last.magic = page_magic;
try self.area.erase(ult << page_shift, page_size);
try self.area.erase(penult << page_shift, page_size);
try self.area.write(ult << page_shift, std.mem.asBytes(&self.buf_last));
// std.log.info("Writing initial status: {} hash pages", .{total_hashes});
// std.log.info("2 pages at end + {} extra pages", .{extras});
// The last (and only) page written was the ultimate page.
self.last_page = 0;
}
// Update the status page with a new phase.
pub fn updateStatus(self: *Self, phase: Phase) !void {
// Increment the sequence number.
self.buf_last.seq += 1;
self.buf_last.phase = phase;
// Update the hash
const lasthash = Swap.calcHash(std.mem.asBytes(&self.buf_last)[0 .. 512 - 20]);
std.mem.copy(u8, self.buf_last.hash[0..], lasthash[0..]);
// Toggle phases.
const ult = (self.area.size >> page_shift) - 1;
const penult = ult - 1;
const pages = [2]usize{ ult, penult };
self.last_page = 1 - self.last_page;
const this_page = pages[self.last_page];
const other_page = pages[1 - self.last_page];
// std.log.info("Updating status: (off {x}), new {}, old {}", .{ self.area.off, this_page, other_page });
// Write out. Sequence is important here.
try self.area.erase(this_page << page_shift, page_size);
try self.area.write(this_page << page_shift, std.mem.asBytes(&self.buf_last));
try self.area.erase(other_page << page_shift, page_size);
}
// Assuming that the buf_last has been loaded with the correct image
// of the last page, update the swap_status structure with the sizes
// and hash information from the in-progress operation.
pub fn loadStatus(self: *Self, st: *Swap) !void {
st.sizes[0] = @as(usize, self.buf_last.sizes[0]);
st.sizes[1] = @as(usize, self.buf_last.sizes[1]);
st.prefix = self.buf_last.prefix;
// TODO: Consolidate this from the startStatus function.
var extras: usize = 0;
const total_hashes = asPages(st.sizes[0]) + asPages(st.sizes[1]);
if (total_hashes > self.buf_last.hashes.len) {
var remaining = total_hashes - self.buf_last.hashes.len;
while (remaining > 0) {
extras += 1;
var count = self.buf_hash.hashes.len;
if (count > remaining)
count = remaining;
remaining -= count;
}
}
// Load the extras pages to get our hashes.
var src: usize = 0;
var dstIter = st.iterHashes();
var hash_page = (self.area.size >> page_shift) - 3;
// Replicate the behavior from the load. Hash failures here are
// not easily recoverable.
while (extras > 0) : (extras -= 1) {
try self.area.read(hash_page << page_shift, std.mem.asBytes(&self.buf_hash));
// Verify the hash.
const thehash = Swap.calcHash(std.mem.asBytes(&self.buf_hash)[0 .. 512 - 4]);
if (!std.mem.eql(u8, self.buf_hash.hash[0..], thehash[0..])) {
std.log.err("Hash failure on hash page", .{});
@panic("Unrecoverable error");
}
// Copy the pages out.
src = 0;
while (src < self.buf_hash.hashes.len) : (src += 1) {
if (dstIter.next()) |dst| {
std.mem.copy(u8, dst[0..], self.buf_hash.hashes[src][0..]);
// const dstv = std.mem.bytesToValue(u32, dst[0..]);
// std.log.warn("Read {x:0>8} from page:{} at {}", .{ dstv, hash_page, src });
} else {
// Calculations above were incorrect.
unreachable;
}
}
}
// Extract the hashes.
src = 0;
while (src < self.buf_last.hashes.len) : (src += 1) {
if (dstIter.next()) |dst| {
std.mem.copy(u8, dst[0..], self.buf_last.hashes[src][0..]);
} else {
break;
}
}
}
// Flash layout.
//
// The status area is written in the last few pages of the flash
// device. To preserve compatibility with the previous flash code, we
// will place the magic value in the last 16 bytes (although we will
// use a different magic value).
// The last page is written, possibly duplicated, in the last two
// pages of the device. We can toggle between these for updates,
// which is done the following way:
// - Update any data.
// - Generate a new sequence number.
// - Write to the unused page.
// - Erase the other page.
//
// Upon startup, we scan both pages. If there is only a magic number
// present, we take this to indicate we should start an update.
// Otherwise, the page will contain an internal consistency check. If
// we see two pages present, we use the one with the *lower* sequence
// number, as we don't know if the other page was written fully.
//
// The last two pages are in this format. Note that since this mode
// always writes fully, there are no alignment concerns within this
// data, beyond normal CPU alignment issues.
const LastPage = extern struct {
// The first block of hashes
hashes: [(512 - 72) / 4][Swap.hash_bytes]u8,
// The sizes of the two regions (in bytes) used for swap.
sizes: [2]u32,
// Encryption keys used when encrypting.
keys: [2][16]u8,
// The prefix used for the hashes.
prefix: [4]u8,
// The sequence number of this page.
seq: u32,
// Status of the operation.
phase: Phase,
swap_info: u8,
copy_done: u8,
image_ok: u8,
// The first 4 bytes of the SHA1 hash of the data up until this
// point.
hash: [4]u8,
// The page ends with a magic value.
magic: Magic,
};
// Pages before these two are used to hold any additional hashes.
const HashPage = extern struct {
// As many hashes as we need.
hashes: [(512 - 4) / 4][Swap.hash_bytes]u8,
// The first 4 bytes of the SHA1 hash of the hashes array before
// this.
hash: [4]u8,
};
// The magic value is determined by a configuration value of
// BOOT_MAX_ALIGN.
const Magic = extern union {
val: [16]u8,
modern: extern struct {
alignment: u16,
magic: [14]u8,
},
fn eql(self: *const Magic, other: *const Magic) bool {
return std.mem.eql(u8, self.val[0..], other.val[0..]);
}
};
// The page based status always uses different magic values.
const page_magic = Magic{
.modern = .{
.alignment = 512,
.magic = .{ 0x3e, 0x04, 0xec, 0x53, 0xa0, 0x40, 0x45, 0x39, 0x4a, 0x6e, 0x00, 0xd5, 0xa2, 0xb3 },
},
};
comptime {
std.debug.assert(@sizeOf(LastPage) == 512);
std.debug.assert(@sizeOf(HashPage) == 512);
}
fn asPages(value: usize) usize {
return (value + page_size - 1) >> page_shift;
}
test {
std.testing.refAllDecls(Self);
} | src/status/paged.zig |
const std = @import("std");
const input = @import("input.zig");
pub fn run(stdout: anytype) anyerror!void {
{
var input_ = try input.readFile("inputs/day11");
defer input_.deinit();
const result = try part1(&input_);
try stdout.print("11a: {}\n", .{ result });
std.debug.assert(result == 1705);
}
{
var input_ = try input.readFile("inputs/day11");
defer input_.deinit();
const result = try part2(&input_);
try stdout.print("11b: {}\n", .{ result });
std.debug.assert(result == 265);
}
}
const num_rows = 10;
const num_cols = 10;
fn part1(input_: anytype) !usize {
var levels = try parseInput(input_);
var result: usize = 0;
var step_num: usize = 1;
while (step_num <= 100) : (step_num += 1) {
result += step(&levels);
}
return result;
}
fn part2(input_: anytype) !usize {
var levels = try parseInput(input_);
var step_num: usize = 1;
while (true) : (step_num += 1) {
const num_flashed = step(&levels);
if (num_flashed == num_rows * num_cols) {
return step_num;
}
}
}
fn parseInput(input_: anytype) ![num_rows][num_cols]Level {
var levels: [num_rows][num_cols]Level = [_][num_cols]Level { [_]Level { 0 } ** num_cols } ** num_rows;
var row_i: usize = 0;
while (try input_.next()) |line| {
for (line) |c, col_i| {
levels[row_i][col_i] = try std.fmt.parseInt(Level, &[_]u8 { c }, 10);
}
row_i += 1;
}
return levels;
}
const flash_at = 10;
// 0...(flash_at - 1) : will not flash
// flash_at : should flash
// flash_at + 1 : has already flashed and will not flash again
const Level = std.math.IntFittingRange(0, flash_at + 1);
fn step(levels: *[num_rows][num_cols]Level) usize {
for (levels) |*row| {
for (row) |*level| {
increaseLevel(level);
}
}
while (true) {
var had_a_flash = false;
for (levels) |*row, row_i| {
for (row) |*level, col_i| {
if (level.* == flash_at) {
level.* = flash_at + 1;
had_a_flash = true;
const up = std.math.sub(usize, row_i, 1) catch null;
const down = if (std.math.add(usize, row_i, 1) catch null) |down_| if (down_ < num_rows) down_ else null else null;
const left = std.math.sub(usize, col_i, 1) catch null;
const right = if (std.math.add(usize, col_i, 1) catch null) |right_| if (right_ < num_cols) right_ else null else null;
for ([_]?usize { up, row_i, down }) |row_j| {
for ([_]?usize { left, col_i, right }) |col_j| {
const row_j_ = row_j orelse continue;
const col_j_ = col_j orelse continue;
if (row_j_ != row_i or col_j_ != col_i) {
increaseLevel(&levels[row_j_][col_j_]);
}
}
}
}
}
}
if (!had_a_flash) {
break;
}
}
var num_flashed: usize = 0;
for (levels) |*row| {
for (row) |*level| {
if (level.* > flash_at) {
level.* = 0;
num_flashed += 1;
}
}
}
return num_flashed;
}
fn increaseLevel(level: *Level) void {
if (level.* < flash_at) {
level.* += 1;
}
}
test "day 11 example 1" {
const input_ =
\\5483143223
\\2745854711
\\5264556173
\\6141336146
\\6357385478
\\4167524645
\\2176841721
\\6882881134
\\4846848554
\\5283751526
;
try std.testing.expectEqual(@as(usize, 1656), try part1(&input.readString(input_)));
try std.testing.expectEqual(@as(usize, 195), try part2(&input.readString(input_)));
} | src/day11.zig |
const std = @import("std");
const c = @import("internal/c.zig");
const internal = @import("internal/internal.zig");
const log = std.log.scoped(.git);
const git = @import("git.zig");
pub const Indexer = opaque {
pub const Options = struct {
/// permissions to use creating packfile or 0 for defaults
mode: c_uint = 0,
/// do connectivity checks for the received pack
verify: bool = false,
};
/// This structure is used to provide callers information about the progress of indexing a packfile, either directly or part
/// of a fetch or clone that downloads a packfile.
pub const Progress = extern struct {
/// number of objects in the packfile being indexed
total_objects: c_int,
/// received objects that have been hashed
indexed_objects: c_int,
/// received_objects: objects which have been downloaded
received_objects: c_int,
/// locally-available objects that have been injected in order to fix a thin pack
local_objects: c_int,
/// number of deltas in the packfile being indexed
total_deltas: c_int,
/// received deltas that have been indexed
indexed_deltas: c_int,
/// size of the packfile received up to now
received_bytes: usize,
test {
try std.testing.expectEqual(@sizeOf(c.git_indexer_progress), @sizeOf(Progress));
try std.testing.expectEqual(@bitSizeOf(c.git_indexer_progress), @bitSizeOf(Progress));
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// Create a new indexer instance
///
/// ## Parameters
/// * `path` - to the directory where the packfile should be stored
/// * `odb` - object database from which to read base objects when fixing thin packs. Pass `null` if no thin pack is expected
/// (an error will be returned if there are bases missing)
/// * `options` - options
/// * `user_data` - pointer to user data to be passed to the callback
/// * `callback_fn` - the callback function; a value less than zero to cancel the indexing or download
///
/// ## Callback Parameters
/// * `stats` - state of the transfer
/// * `user_data_ptr` - The user data
pub fn init(
path: [:0]const u8,
odb: ?*git.Odb,
options: Options,
user_data: anytype,
comptime callback_fn: fn (
stats: *const Progress,
user_data_ptr: @TypeOf(user_data),
) c_int,
) !*git.Indexer {
const UserDataType = @TypeOf(user_data);
const cb = struct {
pub fn cb(
stats: [*c]const c.git_indexer_progress,
payload: ?*anyopaque,
) callconv(.C) c_int {
return callback_fn(@ptrCast(*const Progress, stats), @ptrCast(UserDataType, payload));
}
}.cb;
log.debug("Indexer.init called, path={s}, odb={*}, options={}", .{ path, odb, options });
var c_opts = c.git_indexer_options{
.version = c.GIT_INDEXER_OPTIONS_VERSION,
.progress_cb = cb,
.progress_cb_payload = user_data,
.verify = @boolToInt(options.verify),
};
var ret: *Indexer = undefined;
try internal.wrapCall("git_indexer_new", .{
@ptrCast(*c.git_indexer, &ret),
path.ptr,
options.mode,
@ptrCast(?*c.git_oid, odb),
&c_opts,
});
log.debug("successfully initalized Indexer", .{});
return ret;
}
/// Add data to the indexer
///
/// ## Parameters
/// * `data` - the data to add
/// * `stats` - stat storage
pub fn append(self: *Indexer, data: []const u8, stats: *Progress) !void {
log.debug("Indexer.append called, data_len={}, stats={}", .{ data.len, stats });
try internal.wrapCall("git_indexer_append", .{
@ptrCast(*c.git_indexer, self),
data.ptr,
data.len,
@ptrCast(*c.git_indexer_progress, stats),
});
log.debug("successfully appended to indexer", .{});
}
/// Finalize the pack and index
///
/// Resolve any pending deltas and write out the index file
///
/// ## Parameters
/// * `data` - the data to add
/// * `stats` - stat storage
pub fn commit(self: *Indexer, stats: *Progress) !void {
log.debug("Indexer.commit called, stats={}", .{stats});
try internal.wrapCall("git_indexer_commit", .{
@ptrCast(*c.git_indexer, self),
@ptrCast(*c.git_indexer_progress, stats),
});
log.debug("successfully commited indexer", .{});
}
/// Get the packfile's hash
///
/// A packfile's name is derived from the sorted hashing of all object names. This is only correct after the index has been
/// finalized.
pub fn hash(self: *const Indexer) ?*const git.Oid {
log.debug("Indexer.hash called", .{});
var opt_hash = @ptrCast(
?*const git.Oid,
c.git_indexer_hash(@ptrCast(*const c.git_indexer, self)),
);
if (opt_hash) |ret| {
// This check is to prevent formating the oid when we are not going to print anything
if (@enumToInt(std.log.Level.debug) <= @enumToInt(std.log.level)) {
var buf: [git.Oid.HEX_BUFFER_SIZE]u8 = undefined;
if (ret.formatHex(&buf)) |slice| {
log.debug("successfully fetched packfile hash: {s}", .{slice});
} else |_| {
log.debug("successfully fetched packfile, but unable to format it", .{});
}
}
return ret;
}
log.debug("received null hash", .{});
return null;
}
pub fn deinit(self: *Indexer) void {
log.debug("Indexer.deinit called", .{});
c.git_indexer_free(@ptrCast(*c.git_indexer, self));
log.debug("Indexer freed successfully", .{});
}
comptime {
std.testing.refAllDecls(@This());
}
};
comptime {
std.testing.refAllDecls(@This());
} | src/indexer.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 Vec2 = @Vector(2, i16);
const PortalContext = struct {
pub fn hash(self: @This(), a: u10) u32 {
_ = self;
return a;
}
pub fn eql(self: @This(), a: u10, b: u10) bool {
_ = self;
return a == b;
}
};
const Portals = std.ArrayHashMap(u10, struct { out: Vec2, in: Vec2 }, PortalContext, false);
const Edge = enum { inner, outer };
fn addPortal(portals: *Portals, pos: Vec2, letter1: u8, letter2: u8, edge: Edge) void {
const tag = @intCast(u10, letter1 - 'A') * 26 + @intCast(u10, letter2 - 'A');
const entry = portals.getOrPut(tag) catch unreachable;
if (edge == .inner) {
entry.value_ptr.in = pos;
} else {
entry.value_ptr.out = pos;
}
}
fn parseLine(input: []const u8, stride: usize, p0: Vec2, p1: Vec2, inc: Vec2, edge: Edge, offset_letter1: isize, offset_letter2: isize, portals: *Portals) void {
var p = p0;
while (@reduce(.Or, p != p1)) : (p += inc) {
const o = offset_from_pos(p, stride);
switch (input[o]) {
'#' => {},
'.' => {
const l1 = input[@intCast(usize, @intCast(isize, o) + offset_letter1)];
const l2 = input[@intCast(usize, @intCast(isize, o) + offset_letter2)];
addPortal(portals, p, l1, l2, edge);
},
else => unreachable,
}
}
}
fn parsePortals(input: []const u8, stride: usize, width: u15, height: u15, portals: *Portals) void {
const outer_top: u15 = 2;
const outer_left: u15 = 2;
const outer_bottom: u15 = height - 3;
const outer_right: u15 = width - 3;
assert(input[outer_left + outer_top * stride] == '#' and input[(outer_left + 0) + (outer_top - 1) * stride] == ' ' and input[(outer_left - 1) + (outer_top + 0) * stride] == ' ');
assert(input[outer_right + outer_bottom * stride] == '#' and input[(outer_right + 0) + (outer_bottom + 1) * stride] == ' ' and input[(outer_right + 1) + (outer_bottom + 0) * stride] == ' ');
assert(input[outer_left + outer_bottom * stride] == '#' and input[(outer_left + 0) + (outer_bottom + 1) * stride] == ' ' and input[(outer_left - 1) + (outer_bottom + 0) * stride] == ' ');
assert(input[outer_right + outer_top * stride] == '#' and input[(outer_right + 0) + (outer_top - 1) * stride] == ' ' and input[(outer_right + 1) + (outer_top + 0) * stride] == ' ');
const inner_top: u15 = 30;
const inner_left: u15 = 30;
const inner_bottom: u15 = height - 31;
const inner_right: u15 = width - 31;
assert(input[inner_left + inner_top * stride] == '#' and input[(inner_left + 0) + (inner_top + 1) * stride] == '#' and input[(inner_left + 1) + (inner_top + 0) * stride] == '#' and input[(inner_left + 1) + (inner_top + 1) * stride] == ' ');
assert(input[inner_left + inner_bottom * stride] == '#' and input[(inner_left + 0) + (inner_bottom - 1) * stride] == '#' and input[(inner_left + 1) + (inner_bottom + 0) * stride] == '#' and input[(inner_left + 1) + (inner_bottom - 1) * stride] == ' ');
assert(input[inner_right + inner_top * stride] == '#' and input[(inner_right + 0) + (inner_top + 1) * stride] == '#' and input[(inner_right - 1) + (inner_top + 0) * stride] == '#' and input[(inner_right - 1) + (inner_top + 1) * stride] == ' ');
assert(input[inner_right + inner_bottom * stride] == '#' and input[(inner_right + 0) + (inner_bottom - 1) * stride] == '#' and input[(inner_right - 1) + (inner_bottom + 0) * stride] == '#' and input[(inner_right - 1) + (inner_bottom - 1) * stride] == ' ');
const offset_line = @intCast(isize, stride);
parseLine(input, stride, Vec2{ outer_left, outer_top }, Vec2{ outer_right, outer_top }, Vec2{ 1, 0 }, .outer, -offset_line * 2, -offset_line, portals);
parseLine(input, stride, Vec2{ outer_left, outer_bottom }, Vec2{ outer_right, outer_bottom }, Vec2{ 1, 0 }, .outer, offset_line, offset_line * 2, portals);
parseLine(input, stride, Vec2{ outer_left, outer_top }, Vec2{ outer_left, outer_bottom }, Vec2{ 0, 1 }, .outer, -2, -1, portals);
parseLine(input, stride, Vec2{ outer_right, outer_top }, Vec2{ outer_right, outer_bottom }, Vec2{ 0, 1 }, .outer, 1, 2, portals);
parseLine(input, stride, Vec2{ inner_left, inner_top }, Vec2{ inner_right, inner_top }, Vec2{ 1, 0 }, .inner, offset_line, offset_line * 2, portals);
parseLine(input, stride, Vec2{ inner_left, inner_bottom }, Vec2{ inner_right, inner_bottom }, Vec2{ 1, 0 }, .inner, -offset_line * 2, -offset_line, portals);
parseLine(input, stride, Vec2{ inner_left, inner_top }, Vec2{ inner_left, inner_bottom }, Vec2{ 0, 1 }, .inner, 1, 2, portals);
parseLine(input, stride, Vec2{ inner_right, inner_top }, Vec2{ inner_right, inner_bottom }, Vec2{ 0, 1 }, .inner, -2, -1, portals);
}
fn flood_fill_recurse(input: []const u8, stride: usize, p: Vec2, depth: u16, dmap: []u16) void {
for ([4]Vec2{ Vec2{ 1, 0 }, Vec2{ 0, 1 }, Vec2{ -1, 0 }, Vec2{ 0, -1 } }) |neib| {
const p1 = p + neib;
const o = offset_from_pos(p1, stride);
if (input[o] != '.') continue;
if (dmap[o] != 0) {
assert(dmap[o] < depth);
continue;
}
dmap[o] = depth;
flood_fill_recurse(input, stride, p1, depth + 1, dmap);
}
}
fn compute_distance_map(input: []const u8, stride: usize, p: Vec2, dmap: []u16) void {
std.mem.set(u16, dmap, 0);
flood_fill_recurse(input, stride, p, 1, dmap);
const o = offset_from_pos(p, stride);
dmap[o] = 0; // cas special entrée pas géré avant: un pas en avant, un pas en arrière
}
fn offset_from_pos(p: Vec2, stride: usize) usize {
return @intCast(usize, p[0]) + @intCast(usize, p[1]) * stride;
}
pub fn run(input: []const u8, allocator: std.mem.Allocator) tools.RunError![2][]const u8 {
// 1. lire le laby
// 2. calculer les paires de distances
// 3. trouver la meilleure séquence de paires
const stride = std.mem.indexOfScalar(u8, input, '\n').? + 1;
const height = @intCast(u15, input.len / stride);
const width = @intCast(u15, stride - 1);
var portals = Portals.init(allocator);
defer portals.deinit();
const tagAA = @intCast(u10, 0) * 26 + @intCast(u10, 0);
const tagZZ = @intCast(u10, 'Z' - 'A') * 26 + @intCast(u10, 'Z' - 'A');
{
const entryAA = portals.getOrPut(tagAA) catch unreachable;
const entryZZ = portals.getOrPut(tagZZ) catch unreachable;
entryAA.value_ptr.in = Vec2{ 50, 50 }; // n'existe pas -> point inatteignable au centre
entryZZ.value_ptr.in = Vec2{ 52, 52 }; // n'existe pas -> point inatteignable au centre
parsePortals(input, stride, width, height, &portals);
trace("portals: count={}\n", .{portals.count()});
var it = portals.iterator();
while (it.next()) |e| {
trace(" {c}{c}: {} -> {}\n", .{ 'A' + @intCast(u8, e.key_ptr.* / 26), 'A' + @intCast(u8, e.key_ptr.* % 26), e.value_ptr.in, e.value_ptr.out });
}
}
const indexAA = @intCast(u8, portals.getIndex(tagAA).? * 2 + 1);
const indexZZ = @intCast(u8, portals.getIndex(tagZZ).? * 2 + 1);
const portal_count = portals.count() * 2;
var dist_table = try allocator.alloc(u16, portal_count * portal_count);
defer allocator.free(dist_table);
{
var idx1: usize = 0;
var it = portals.iterator();
while (it.next()) |portal| : (idx1 += 1) {
const dmap_in = try allocator.alloc(u16, height * stride);
defer allocator.free(dmap_in);
const dmap_out = try allocator.alloc(u16, height * stride);
defer allocator.free(dmap_out);
compute_distance_map(input, stride, portal.value_ptr.in, dmap_in);
compute_distance_map(input, stride, portal.value_ptr.out, dmap_out);
var idx2: usize = 0;
var it2 = portals.iterator();
while (it2.next()) |portal2| : (idx2 += 1) {
const p_in = portal2.value_ptr.in;
const p_out = portal2.value_ptr.out;
const o_in = offset_from_pos(p_in, stride);
const o_out = offset_from_pos(p_out, stride);
if (idx2 == idx1) {
assert(dmap_in[o_in] == 0);
assert(dmap_out[o_out] == 0);
}
dist_table[(idx1 * 2 + 0) * portal_count + (idx2 * 2 + 0)] = dmap_in[o_in];
dist_table[(idx1 * 2 + 0) * portal_count + (idx2 * 2 + 1)] = dmap_in[o_out];
dist_table[(idx1 * 2 + 1) * portal_count + (idx2 * 2 + 0)] = dmap_out[o_in];
dist_table[(idx1 * 2 + 1) * portal_count + (idx2 * 2 + 1)] = dmap_out[o_out];
}
}
{
trace("distances:\n ", .{});
var i: usize = 0;
while (i < portal_count) : (i += 1) {
trace("{c}{c} ", .{ 'A' + @intCast(u8, portals.keys()[i / 2] / 26), 'A' + @intCast(u8, portals.keys()[i / 2] % 26) });
}
trace("\n", .{});
i = 0;
while (i < portal_count) : (i += 1) {
var j: usize = 0;
trace("{c}{c} ", .{ 'A' + @intCast(u8, portals.keys()[i / 2] / 26), 'A' + @intCast(u8, portals.keys()[i / 2] % 26) });
while (j < portal_count) : (j += 1) {
assert(dist_table[j + i * portal_count] == dist_table[i + j * portal_count]); // sanity check.
trace(" {:2}", .{dist_table[j + i * portal_count]});
}
trace("\n", .{});
}
}
}
// TODO? on pourrait completer la table en accumulant les chemin composites. mais c'est probablement pas rentable?
// TODO? bon évidement le gros du temps est passé dans les hashtables ci dessous, inutiles car on a que des ptits indexs et des states super simples...
var part1: u64 = part1: {
const BestFirstSearch = tools.BestFirstSearch(u8, void);
var bfs = BestFirstSearch.init(allocator);
defer bfs.deinit();
try bfs.insert(BestFirstSearch.Node{
.rating = 0,
.cost = 0,
.state = indexAA,
.trace = {},
});
var best: u32 = 999999;
while (bfs.pop()) |node| {
if (node.cost >= best)
continue;
trace("at {} ({}):\n", .{ node.state, node.cost });
//walk:
var i: u8 = 0;
while (i < portal_count) : (i += 1) {
const d = dist_table[node.state * portal_count + i];
if (d == 0) continue;
const steps = node.cost + d;
if (steps >= best) continue;
if (i == indexZZ) { // exit found
trace(" exit: ...{} -{}-> OUT ({})\n", .{ node.state, d, steps });
best = steps;
continue;
}
trace(" walk: ...{} -{}-> {} ({})\n", .{ node.state, d, i, steps });
try bfs.insert(BestFirstSearch.Node{
.rating = @intCast(i32, steps),
.cost = steps,
.state = i,
.trace = {},
});
}
//teleport:
if (node.state != indexAA and node.state != indexZZ) {
const index = node.state ^ 1;
const steps = node.cost + 1;
trace(" tele: ...{} -1-> {} ({})\n", .{ node.state, index, steps });
try bfs.insert(BestFirstSearch.Node{
.rating = @intCast(i32, steps),
.cost = steps,
.state = index,
.trace = {},
});
}
}
break :part1 best;
};
var part2: u64 = part2: {
const BestFirstSearch = tools.BestFirstSearch(struct { tp: u8, level: u8 }, void);
var bfs = BestFirstSearch.init(allocator);
defer bfs.deinit();
try bfs.insert(BestFirstSearch.Node{
.rating = 0,
.cost = 0,
.state = .{ .tp = indexAA, .level = 0 },
.trace = {},
});
var best: u32 = 999999;
while (bfs.pop()) |node| {
if (node.cost >= best)
continue;
trace("at {} ({}):\n", .{ node.state, node.cost });
//walk:
var i: u8 = 0;
while (i < portal_count) : (i += 1) {
const d = dist_table[node.state.tp * portal_count + i];
if (d == 0) continue;
const steps = node.cost + d;
if (steps >= best) continue;
if (i == indexZZ and node.state.level == 0) { // exit found
trace(" exit: ...{} -{}-> OUT ({})\n", .{ node.state, d, steps });
best = steps;
continue;
} else if (i == indexZZ or i == indexAA) continue;
trace(" walk: ...{} -{}-> {} ({})\n", .{ node.state, d, i, steps });
try bfs.insert(BestFirstSearch.Node{
.rating = @intCast(i32, steps + 8 * @as(u32, node.state.level)),
.cost = steps,
.state = .{ .tp = i, .level = node.state.level },
.trace = {},
});
}
//teleport:
if (node.state.tp != indexAA and node.state.tp != indexZZ) {
const is_outer = (node.state.tp & 1) == 1;
if (!is_outer or node.state.level > 0) {
const index = node.state.tp ^ 1;
const steps = node.cost + 1;
trace(" tele: ...{} -1-> {} ({})\n", .{ node.state, index, steps });
try bfs.insert(BestFirstSearch.Node{
.rating = @intCast(i32, steps + 8 * @as(u32, node.state.level)),
.cost = steps,
.state = .{ .tp = index, .level = if (is_outer) node.state.level - 1 else node.state.level + 1 },
.trace = {},
});
}
}
}
break :part2 best;
};
return [_][]const u8{
try std.fmt.allocPrint(allocator, "{}", .{part1}),
try std.fmt.allocPrint(allocator, "{}", .{part2}),
};
}
pub const main = tools.defaultMain("2019/day20.txt", run); | 2019/day20.zig |
const std = @import("std");
const time = std.time;
const c = @cImport({
@cInclude("sys/ioctl.h");
});
// 状態
const STATE = enum { DEAD = 0, LIVE = 1 };
const stdout = std.io.getStdOut();
fn Grid() type {
return struct {
const Self = @This();
height: usize,
width: usize,
grid: std.ArrayList(std.ArrayList(STATE)),
// grid の初期化
// 確保したメモリは呼び出し元が解放する
pub fn init(allocator: *std.mem.Allocator, height: usize, width: usize) !Self {
// 初期化
var grid = std.ArrayList(std.ArrayList(STATE)).init(allocator);
var i: u8 = 0;
while (i < height) : (i += 1) {
var line = std.ArrayList(STATE).init(allocator);
var j: u8 = 0;
while (j < width) : (j += 1) {
// ランダム
const num = std.crypto.random.uintLessThanBiased(u8, 10);
try line.append(if (num < 4) .LIVE else .DEAD);
}
try grid.append(line);
}
return Self{
.height = height,
.width = width,
.grid = grid,
};
}
// 指定のセルの状態を返す
fn cellValue(self: Self, row: usize, col: usize) STATE {
return self.grid.items[row].items[col];
}
fn isLive(self: Self, row: isize, col: isize) STATE {
if ((row == -1 or row >= self.height) or (col == -1 or col >= self.width)) {
// 範囲外なら、dead ってことにする
return .DEAD;
}
return self.cellValue(@intCast(usize, row), @intCast(usize, col));
}
// 次の状態を求める
fn nextState(self: Self, row: u8, col: u8) STATE {
var live_cnt: u8 = 0;
// overflow がおきてしまうため、ここで変換
const irow = @intCast(isize, row);
const icol = @intCast(isize, col);
// 周りの生きているセルを確認する
live_cnt += @enumToInt(self.isLive(irow - 1, icol - 1));
live_cnt += @enumToInt(self.isLive(irow - 1, icol));
live_cnt += @enumToInt(self.isLive(irow - 1, icol + 1));
live_cnt += @enumToInt(self.isLive(irow, icol - 1));
live_cnt += @enumToInt(self.isLive(irow, icol + 1));
live_cnt += @enumToInt(self.isLive(irow + 1, icol - 1));
live_cnt += @enumToInt(self.isLive(irow + 1, icol));
live_cnt += @enumToInt(self.isLive(irow + 1, icol + 1));
if (self.cellValue(row, col) == .DEAD) {
// dead
if (live_cnt == 3) {
// 誕生
return .LIVE;
}
} else {
if (live_cnt == 2 or live_cnt == 3) {
// 維持
return .LIVE;
} else if (live_cnt < 2) {
// 過疎
return .DEAD;
} else if (live_cnt >= 4) { // 過密
return .DEAD;
}
}
return .DEAD;
}
// 次の世代に移る
// 確保したメモリは呼び出し元が解放する
fn nextGeneration(self: *Self, allocator: *std.mem.Allocator) !void {
var new_grid = std.ArrayList(std.ArrayList(STATE)).init(allocator);
var i: u8 = 0;
while (i < self.height) : (i += 1) {
var line = std.ArrayList(STATE).init(allocator);
var j: u8 = 0;
while (j < self.width) : (j += 1) {
try line.append(self.nextState(i, j));
}
try new_grid.append(line);
}
self.grid = new_grid;
}
fn refresh(self: *Self) !void {
// ESC は 16進数で \x1B となる
// ESC[2J で画面クリア
// 画面のクリア
try stdout.writeAll("\x1B[2J\x1B[H");
}
// 描画
pub fn update(self: *Self, allocator: *std.mem.Allocator) !void {
try self.refresh();
var row: u8 = 0;
var lines = std.ArrayList([]const u8).init(allocator);
while (row < self.height) : (row += 1) {
var col: u8 = 0;
// 文字のリスト
var cells = std.ArrayList([]const u8).init(allocator);
while (col < self.width) : (col += 1) {
const ch = switch (self.cellValue(row, col)) {
.DEAD => " ",
// ESC[7m 背景色を反転させる
// ESC[0m 戻す
.LIVE => "\x1B[7m \x1B[0m",
};
try cells.append(ch);
}
// cell.items は &[_][]const u8
// []const u8 => 文字列
// [_] => スライス
// & => 参照
try lines.append(try std.mem.join(allocator, "", cells.items));
}
try stdout.writeAll(try std.mem.join(allocator, "\n", lines.items));
}
};
}
const Size = struct {
columns: usize,
rows: usize,
};
// ターミナルのサイズを取得する
fn winsize() Size {
var ws: c.winsize = undefined;
if (c.ioctl(stdout.handle, c.TIOCGWINSZ, &ws) != -1) {
return .{
.columns = ws.ws_col,
.rows = ws.ws_row,
};
}
unreachable;
}
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
var allocator = &arena.allocator;
const args = try std.process.argsAlloc(allocator);
if (args.len == 2 and std.mem.eql(u8, args[1], "-h")) {
const help_text =
\\Usage:
\\ gameoflife [num]
\\
\\Options:
\\ num Forward generation in num milliseconds, instead of 200 milliseconds.
\\ -h, --help Show help.
\\
;
try std.io.getStdOut().writeAll(help_text);
return;
}
// ミリ秒の間隔
const ms: usize = blk: {
if (args.len == 1) {
break :blk 200;
}
break :blk std.fmt.parseInt(usize, args[1], 10) catch 200;
};
const ms_interval = ms * time.ns_per_ms;
// 現在のターミナルのサイズを取得し、それに合わせて、設定する
var size = winsize();
var width = size.columns / 2;
var grid = try Grid().init(allocator, size.rows, width);
while (true) {
try grid.update(allocator);
try grid.nextGeneration(allocator);
time.sleep(ms_interval);
}
} | src/main.zig |
const std = @import("../std.zig");
const builtin = @import("builtin");
const maxInt = std.math.maxInt;
const iovec = std.os.iovec;
const iovec_const = std.os.iovec_const;
extern "c" fn _errnop() *c_int;
pub const _errno = _errnop;
pub extern "c" fn find_directory(which: c_int, volume: i32, createIt: bool, path_ptr: [*]u8, length: i32) u64;
pub extern "c" fn find_thread(thread_name: ?*c_void) i32;
pub extern "c" fn get_system_info(system_info: *system_info) usize;
// TODO revisit if abi changes or better option becomes apparent
pub extern "c" fn _get_next_image_info(team: c_int, cookie: *i32, image_info: *image_info) usize;
pub extern "c" fn _kern_read_dir(fd: c_int, buf_ptr: [*]u8, nbytes: usize, maxcount: u32) usize;
pub extern "c" fn _kern_read_stat(fd: c_int, path_ptr: [*]u8, traverse_link: bool, st: *Stat, stat_size: i32) usize;
pub extern "c" fn _kern_get_current_team() i32;
pub const sem_t = extern struct {
_magic: u32,
_kern: extern struct {
_count: u32,
_flags: u32,
},
_padding: u32,
};
pub const pthread_attr_t = extern struct {
__detach_state: i32,
__sched_priority: i32,
__stack_size: i32,
__guard_size: i32,
__stack_address: ?*c_void,
};
pub const pthread_mutex_t = extern struct {
flags: u32 = 0,
lock: i32 = 0,
unused: i32 = -42,
owner: i32 = -1,
owner_count: i32 = 0,
};
pub const pthread_cond_t = extern struct {
flags: u32 = 0,
unused: i32 = -42,
mutex: ?*c_void = null,
waiter_count: i32 = 0,
lock: i32 = 0,
};
pub const pthread_rwlock_t = extern struct {
flags: u32 = 0,
owner: i32 = -1,
lock_sem: i32 = 0,
lock_count: i32 = 0,
reader_count: i32 = 0,
writer_count: i32 = 0,
waiters: [2]?*c_void = [_]?*c_void{ null, null },
};
pub const EAI = enum(c_int) {
/// address family for hostname not supported
ADDRFAMILY = 1,
/// name could not be resolved at this time
AGAIN = 2,
/// flags parameter had an invalid value
BADFLAGS = 3,
/// non-recoverable failure in name resolution
FAIL = 4,
/// address family not recognized
FAMILY = 5,
/// memory allocation failure
MEMORY = 6,
/// no address associated with hostname
NODATA = 7,
/// name does not resolve
NONAME = 8,
/// service not recognized for socket type
SERVICE = 9,
/// intended socket type was not recognized
SOCKTYPE = 10,
/// system error returned in errno
SYSTEM = 11,
/// invalid value for hints
BADHINTS = 12,
/// resolved protocol is unknown
PROTOCOL = 13,
/// argument buffer overflow
OVERFLOW = 14,
_,
};
pub const EAI_MAX = 15;
pub const fd_t = c_int;
pub const pid_t = c_int;
pub const uid_t = u32;
pub const gid_t = u32;
pub const mode_t = c_uint;
pub const socklen_t = u32;
/// Renamed from `kevent` to `Kevent` to avoid conflict with function name.
pub const Kevent = extern struct {
ident: usize,
filter: i16,
flags: u16,
fflags: u32,
data: i64,
udata: usize,
// TODO ext
};
// Modes and flags for dlopen()
// include/dlfcn.h
pub const POLL = struct {
pub const IN = 0x0001;
pub const ERR = 0x0004;
pub const NVAL = 0x1000;
pub const HUP = 0x0080;
};
pub const RTLD = struct {
/// Bind function calls lazily.
pub const LAZY = 1;
/// Bind function calls immediately.
pub const NOW = 2;
pub const MODEMASK = 0x3;
/// Make symbols globally available.
pub const GLOBAL = 0x100;
/// Opposite of GLOBAL, and the default.
pub const LOCAL = 0;
/// Trace loaded objects and exit.
pub const TRACE = 0x200;
/// Do not remove members.
pub const NODELETE = 0x01000;
/// Do not load if not already loaded.
pub const NOLOAD = 0x02000;
};
pub const dl_phdr_info = extern struct {
dlpi_addr: usize,
dlpi_name: ?[*:0]const u8,
dlpi_phdr: [*]std.elf.Phdr,
dlpi_phnum: u16,
};
pub const Flock = extern struct {
l_start: off_t,
l_len: off_t,
l_pid: pid_t,
l_type: i16,
l_whence: i16,
l_sysid: i32,
__unused: [4]u8,
};
pub const msghdr = extern struct {
/// optional address
msg_name: ?*sockaddr,
/// size of address
msg_namelen: socklen_t,
/// scatter/gather array
msg_iov: [*]iovec,
/// # elements in msg_iov
msg_iovlen: i32,
/// ancillary data
msg_control: ?*c_void,
/// ancillary data buffer len
msg_controllen: socklen_t,
/// flags on received message
msg_flags: i32,
};
pub const msghdr_const = extern struct {
/// optional address
msg_name: ?*const sockaddr,
/// size of address
msg_namelen: socklen_t,
/// scatter/gather array
msg_iov: [*]iovec_const,
/// # elements in msg_iov
msg_iovlen: i32,
/// ancillary data
msg_control: ?*c_void,
/// ancillary data buffer len
msg_controllen: socklen_t,
/// flags on received message
msg_flags: i32,
};
pub const off_t = i64;
pub const ino_t = u64;
pub const nfds_t = u32;
pub const pollfd = extern struct {
fd: i32,
events: i16,
revents: i16,
};
pub const Stat = extern struct {
dev: i32,
ino: u64,
mode: u32,
nlink: i32,
uid: i32,
gid: i32,
size: i64,
rdev: i32,
blksize: i32,
atim: timespec,
mtim: timespec,
ctim: timespec,
crtim: timespec,
st_type: u32,
blocks: i64,
pub fn atime(self: @This()) timespec {
return self.atim;
}
pub fn mtime(self: @This()) timespec {
return self.mtim;
}
pub fn ctime(self: @This()) timespec {
return self.ctim;
}
pub fn crtime(self: @This()) timespec {
return self.crtim;
}
};
pub const timespec = extern struct {
tv_sec: isize,
tv_nsec: isize,
};
pub const dirent = extern struct {
d_dev: i32,
d_pdev: i32,
d_ino: i64,
d_pino: i64,
d_reclen: u16,
d_name: [256]u8,
pub fn reclen(self: dirent) u16 {
return self.d_reclen;
}
};
pub const image_info = extern struct {
id: u32,
type: u32,
sequence: i32,
init_order: i32,
init_routine: *c_void,
term_routine: *c_void,
device: i32,
node: i32,
name: [1024]u8,
text: *c_void,
data: *c_void,
text_size: i32,
data_size: i32,
api_version: i32,
abi: i32,
};
pub const system_info = extern struct {
boot_time: i64,
cpu_count: u32,
max_pages: u64,
used_pages: u64,
cached_pages: u64,
block_cache_pages: u64,
ignored_pages: u64,
needed_memory: u64,
free_memory: u64,
max_swap_pages: u64,
free_swap_pages: u64,
page_faults: u32,
max_sems: u32,
used_sems: u32,
max_ports: u32,
used_ports: u32,
max_threads: u32,
used_threads: u32,
max_teams: u32,
used_teams: u32,
kernel_name: [256]u8,
kernel_build_date: [32]u8,
kernel_build_time: [32]u8,
kernel_version: i64,
abi: u32,
};
pub const in_port_t = u16;
pub const sa_family_t = u8;
pub const sockaddr = extern struct {
/// total length
len: u8,
/// address family
family: sa_family_t,
/// actually longer; address value
data: [14]u8,
pub const SS_MAXSIZE = 128;
pub const storage = std.x.os.Socket.Address.Native.Storage;
pub const in = extern struct {
len: u8 = @sizeOf(in),
family: sa_family_t = AF.INET,
port: in_port_t,
addr: u32,
zero: [8]u8 = [8]u8{ 0, 0, 0, 0, 0, 0, 0, 0 },
};
pub const in6 = extern struct {
len: u8 = @sizeOf(in6),
family: sa_family_t = AF.INET6,
port: in_port_t,
flowinfo: u32,
addr: [16]u8,
scope_id: u32,
};
pub const un = extern struct {
len: u8 = @sizeOf(un),
family: sa_family_t = AF.UNIX,
path: [104]u8,
};
};
pub const CTL = struct {
pub const KERN = 1;
pub const DEBUG = 5;
};
pub const KERN = struct {
pub const PROC = 14; // struct: process entries
pub const PROC_PATHNAME = 12; // path to executable
};
pub const PATH_MAX = 1024;
pub const STDIN_FILENO = 0;
pub const STDOUT_FILENO = 1;
pub const STDERR_FILENO = 2;
pub const PROT = struct {
pub const NONE = 0;
pub const READ = 1;
pub const WRITE = 2;
pub const EXEC = 4;
};
pub const CLOCK = struct {
pub const MONOTONIC = 0;
pub const REALTIME = -1;
pub const PROCESS_CPUTIME_ID = -2;
pub const THREAD_CPUTIME_ID = -3;
};
pub const MAP = struct {
pub const FAILED = @intToPtr(*c_void, maxInt(usize));
pub const SHARED = 0x0001;
pub const PRIVATE = 0x0002;
pub const FIXED = 0x0010;
pub const STACK = 0x0400;
pub const NOSYNC = 0x0800;
pub const ANON = 0x1000;
pub const ANONYMOUS = ANON;
pub const FILE = 0;
pub const GUARD = 0x00002000;
pub const EXCL = 0x00004000;
pub const NOCORE = 0x00020000;
pub const PREFAULT_READ = 0x00040000;
pub const @"32BIT" = 0x00080000;
};
pub const W = struct {
pub const NOHANG = 0x1;
pub const UNTRACED = 0x2;
pub const STOPPED = 0x10;
pub const CONTINUED = 0x4;
pub const NOWAIT = 0x20;
pub const EXITED = 0x08;
pub fn EXITSTATUS(s: u32) u8 {
return @intCast(u8, s & 0xff);
}
pub fn TERMSIG(s: u32) u32 {
return (s >> 8) & 0xff;
}
pub fn STOPSIG(s: u32) u32 {
return EXITSTATUS(s);
}
pub fn IFEXITED(s: u32) bool {
return TERMSIG(s) == 0;
}
pub fn IFSTOPPED(s: u32) bool {
return ((s >> 16) & 0xff) != 0;
}
pub fn IFSIGNALED(s: u32) bool {
return ((s >> 8) & 0xff) != 0;
}
};
pub const SA = struct {
pub const ONSTACK = 0x20;
pub const RESTART = 0x10;
pub const RESETHAND = 0x04;
pub const NOCLDSTOP = 0x01;
pub const NODEFER = 0x08;
pub const NOCLDWAIT = 0x02;
pub const SIGINFO = 0x40;
pub const NOMASK = NODEFER;
pub const STACK = ONSTACK;
pub const ONESHOT = RESETHAND;
};
pub const SIG = struct {
pub const ERR = @intToPtr(fn (i32) callconv(.C) void, maxInt(usize));
pub const DFL = @intToPtr(fn (i32) callconv(.C) void, 0);
pub const IGN = @intToPtr(fn (i32) callconv(.C) void, 1);
pub const HUP = 1;
pub const INT = 2;
pub const QUIT = 3;
pub const ILL = 4;
pub const CHLD = 5;
pub const ABRT = 6;
pub const IOT = ABRT;
pub const PIPE = 7;
pub const FPE = 8;
pub const KILL = 9;
pub const STOP = 10;
pub const SEGV = 11;
pub const CONT = 12;
pub const TSTP = 13;
pub const ALRM = 14;
pub const TERM = 15;
pub const TTIN = 16;
pub const TTOU = 17;
pub const USR1 = 18;
pub const USR2 = 19;
pub const WINCH = 20;
pub const KILLTHR = 21;
pub const TRAP = 22;
pub const POLL = 23;
pub const PROF = 24;
pub const SYS = 25;
pub const URG = 26;
pub const VTALRM = 27;
pub const XCPU = 28;
pub const XFSZ = 29;
pub const BUS = 30;
pub const RESERVED1 = 31;
pub const RESERVED2 = 32;
// TODO: check
pub const RTMIN = 65;
pub const RTMAX = 126;
pub const BLOCK = 1;
pub const UNBLOCK = 2;
pub const SETMASK = 3;
pub const WORDS = 4;
pub const MAXSIG = 128;
pub inline fn IDX(sig: usize) usize {
return sig - 1;
}
pub inline fn WORD(sig: usize) usize {
return IDX(sig) >> 5;
}
pub inline fn BIT(sig: usize) usize {
return 1 << (IDX(sig) & 31);
}
pub inline fn VALID(sig: usize) usize {
return sig <= MAXSIG and sig > 0;
}
};
// access function
pub const F_OK = 0; // test for existence of file
pub const X_OK = 1; // test for execute or search permission
pub const W_OK = 2; // test for write permission
pub const R_OK = 4; // test for read permission
pub const O = struct {
pub const RDONLY = 0x0000;
pub const WRONLY = 0x0001;
pub const RDWR = 0x0002;
pub const ACCMODE = 0x0003;
pub const SHLOCK = 0x0010;
pub const EXLOCK = 0x0020;
pub const CREAT = 0x0200;
pub const EXCL = 0x0800;
pub const NOCTTY = 0x8000;
pub const TRUNC = 0x0400;
pub const APPEND = 0x0008;
pub const NONBLOCK = 0x0004;
pub const DSYNC = 0o10000;
pub const SYNC = 0x0080;
pub const RSYNC = 0o4010000;
pub const DIRECTORY = 0x20000;
pub const NOFOLLOW = 0x0100;
pub const CLOEXEC = 0x00100000;
pub const ASYNC = 0x0040;
pub const DIRECT = 0x00010000;
pub const NOATIME = 0o1000000;
pub const PATH = 0o10000000;
pub const TMPFILE = 0o20200000;
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 GETOWN = 5;
pub const SETOWN = 6;
pub const GETLK = 11;
pub const SETLK = 12;
pub const SETLKW = 13;
pub const RDLCK = 1;
pub const WRLCK = 3;
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 FD_CLOEXEC = 1;
pub const SEEK = struct {
pub const SET = 0;
pub const CUR = 1;
pub const END = 2;
};
pub const SOCK = struct {
pub const STREAM = 1;
pub const DGRAM = 2;
pub const RAW = 3;
pub const RDM = 4;
pub const SEQPACKET = 5;
pub const CLOEXEC = 0x10000000;
pub const NONBLOCK = 0x20000000;
};
pub const SO = struct {
pub const DEBUG = 0x00000001;
pub const ACCEPTCONN = 0x00000002;
pub const REUSEADDR = 0x00000004;
pub const KEEPALIVE = 0x00000008;
pub const DONTROUTE = 0x00000010;
pub const BROADCAST = 0x00000020;
pub const USELOOPBACK = 0x00000040;
pub const LINGER = 0x00000080;
pub const OOBINLINE = 0x00000100;
pub const REUSEPORT = 0x00000200;
pub const TIMESTAMP = 0x00000400;
pub const NOSIGPIPE = 0x00000800;
pub const ACCEPTFILTER = 0x00001000;
pub const BINTIME = 0x00002000;
pub const NO_OFFLOAD = 0x00004000;
pub const NO_DDP = 0x00008000;
pub const REUSEPORT_LB = 0x00010000;
pub const SNDBUF = 0x1001;
pub const RCVBUF = 0x1002;
pub const SNDLOWAT = 0x1003;
pub const RCVLOWAT = 0x1004;
pub const SNDTIMEO = 0x1005;
pub const RCVTIMEO = 0x1006;
pub const ERROR = 0x1007;
pub const TYPE = 0x1008;
pub const LABEL = 0x1009;
pub const PEERLABEL = 0x1010;
pub const LISTENQLIMIT = 0x1011;
pub const LISTENQLEN = 0x1012;
pub const LISTENINCQLEN = 0x1013;
pub const SETFIB = 0x1014;
pub const USER_COOKIE = 0x1015;
pub const PROTOCOL = 0x1016;
pub const PROTOTYPE = PROTOCOL;
pub const TS_CLOCK = 0x1017;
pub const MAX_PACING_RATE = 0x1018;
pub const DOMAIN = 0x1019;
};
pub const SOL = struct {
pub const SOCKET = 0xffff;
};
pub const PF = struct {
pub const UNSPEC = AF.UNSPEC;
pub const LOCAL = AF.LOCAL;
pub const UNIX = PF.LOCAL;
pub const INET = AF.INET;
pub const IMPLINK = AF.IMPLINK;
pub const PUP = AF.PUP;
pub const CHAOS = AF.CHAOS;
pub const NETBIOS = AF.NETBIOS;
pub const ISO = AF.ISO;
pub const OSI = AF.ISO;
pub const ECMA = AF.ECMA;
pub const DATAKIT = AF.DATAKIT;
pub const CCITT = AF.CCITT;
pub const DECnet = AF.DECnet;
pub const DLI = AF.DLI;
pub const LAT = AF.LAT;
pub const HYLINK = AF.HYLINK;
pub const APPLETALK = AF.APPLETALK;
pub const ROUTE = AF.ROUTE;
pub const LINK = AF.LINK;
pub const XTP = AF.pseudo_XTP;
pub const COIP = AF.COIP;
pub const CNT = AF.CNT;
pub const SIP = AF.SIP;
pub const IPX = AF.IPX;
pub const RTIP = AF.pseudo_RTIP;
pub const PIP = AF.pseudo_PIP;
pub const ISDN = AF.ISDN;
pub const KEY = AF.pseudo_KEY;
pub const INET6 = AF.pseudo_INET6;
pub const NATM = AF.NATM;
pub const ATM = AF.ATM;
pub const NETGRAPH = AF.NETGRAPH;
pub const SLOW = AF.SLOW;
pub const SCLUSTER = AF.SCLUSTER;
pub const ARP = AF.ARP;
pub const BLUETOOTH = AF.BLUETOOTH;
pub const IEEE80211 = AF.IEEE80211;
pub const INET_SDP = AF.INET_SDP;
pub const INET6_SDP = AF.INET6_SDP;
pub const MAX = AF.MAX;
};
pub const AF = struct {
pub const UNSPEC = 0;
pub const UNIX = 1;
pub const LOCAL = UNIX;
pub const FILE = LOCAL;
pub const INET = 2;
pub const IMPLINK = 3;
pub const PUP = 4;
pub const CHAOS = 5;
pub const NETBIOS = 6;
pub const ISO = 7;
pub const OSI = ISO;
pub const ECMA = 8;
pub const DATAKIT = 9;
pub const CCITT = 10;
pub const SNA = 11;
pub const DECnet = 12;
pub const DLI = 13;
pub const LAT = 14;
pub const HYLINK = 15;
pub const APPLETALK = 16;
pub const ROUTE = 17;
pub const LINK = 18;
pub const pseudo_XTP = 19;
pub const COIP = 20;
pub const CNT = 21;
pub const pseudo_RTIP = 22;
pub const IPX = 23;
pub const SIP = 24;
pub const pseudo_PIP = 25;
pub const ISDN = 26;
pub const E164 = ISDN;
pub const pseudo_KEY = 27;
pub const INET6 = 28;
pub const NATM = 29;
pub const ATM = 30;
pub const pseudo_HDRCMPLT = 31;
pub const NETGRAPH = 32;
pub const SLOW = 33;
pub const SCLUSTER = 34;
pub const ARP = 35;
pub const BLUETOOTH = 36;
pub const IEEE80211 = 37;
pub const INET_SDP = 40;
pub const INET6_SDP = 42;
pub const MAX = 42;
};
pub const DT = struct {
pub const UNKNOWN = 0;
pub const FIFO = 1;
pub const CHR = 2;
pub const DIR = 4;
pub const BLK = 6;
pub const REG = 8;
pub const LNK = 10;
pub const SOCK = 12;
pub const WHT = 14;
};
/// add event to kq (implies enable)
pub const EV_ADD = 0x0001;
/// delete event from kq
pub const EV_DELETE = 0x0002;
/// enable event
pub const EV_ENABLE = 0x0004;
/// disable event (not reported)
pub const EV_DISABLE = 0x0008;
/// only report one occurrence
pub const EV_ONESHOT = 0x0010;
/// clear event state after reporting
pub const EV_CLEAR = 0x0020;
/// force immediate event output
/// ... with or without EV_ERROR
/// ... use KEVENT_FLAG_ERROR_EVENTS
/// on syscalls supporting flags
pub const EV_RECEIPT = 0x0040;
/// disable event after reporting
pub const EV_DISPATCH = 0x0080;
pub const EVFILT_READ = -1;
pub const EVFILT_WRITE = -2;
/// attached to aio requests
pub const EVFILT_AIO = -3;
/// attached to vnodes
pub const EVFILT_VNODE = -4;
/// attached to struct proc
pub const EVFILT_PROC = -5;
/// attached to struct proc
pub const EVFILT_SIGNAL = -6;
/// timers
pub const EVFILT_TIMER = -7;
/// Process descriptors
pub const EVFILT_PROCDESC = -8;
/// Filesystem events
pub const EVFILT_FS = -9;
pub const EVFILT_LIO = -10;
/// User events
pub const EVFILT_USER = -11;
/// Sendfile events
pub const EVFILT_SENDFILE = -12;
pub const EVFILT_EMPTY = -13;
pub const T = struct {
pub const CGETA = 0x8000;
pub const CSETA = 0x8001;
pub const CSETAW = 0x8004;
pub const CSETAF = 0x8003;
pub const CSBRK = 08005;
pub const CXONC = 0x8007;
pub const CFLSH = 0x8006;
pub const IOCSCTTY = 0x8017;
pub const IOCGPGRP = 0x8015;
pub const IOCSPGRP = 0x8016;
pub const IOCGWINSZ = 0x8012;
pub const IOCSWINSZ = 0x8013;
pub const IOCMGET = 0x8018;
pub const IOCMBIS = 0x8022;
pub const IOCMBIC = 0x8023;
pub const IOCMSET = 0x8019;
pub const FIONREAD = 0xbe000001;
pub const FIONBIO = 0xbe000000;
pub const IOCSBRK = 0x8020;
pub const IOCCBRK = 0x8021;
pub const IOCGSID = 0x8024;
};
pub const winsize = extern struct {
ws_row: u16,
ws_col: u16,
ws_xpixel: u16,
ws_ypixel: u16,
};
const NSIG = 32;
/// Renamed from `sigaction` to `Sigaction` to avoid conflict with the syscall.
pub const Sigaction = extern struct {
/// signal handler
__sigaction_u: extern union {
__sa_handler: fn (i32) callconv(.C) void,
},
/// see signal options
sa_flags: u32,
/// signal mask to apply
sa_mask: sigset_t,
};
pub const sigset_t = extern struct {
__bits: [SIG.WORDS]u32,
};
pub const E = enum(i32) {
/// No error occurred.
SUCCESS = 0,
PERM = -0x7ffffff1, // Operation not permitted
NOENT = -0x7fff9ffd, // No such file or directory
SRCH = -0x7fff8ff3, // No such process
INTR = -0x7ffffff6, // Interrupted system call
IO = -0x7fffffff, // Input/output error
NXIO = -0x7fff8ff5, // Device not configured
@"2BIG" = -0x7fff8fff, // Argument list too long
NOEXEC = -0x7fffecfe, // Exec format error
CHILD = -0x7fff8ffe, // No child processes
DEADLK = -0x7fff8ffd, // Resource deadlock avoided
NOMEM = -0x80000000, // Cannot allocate memory
ACCES = -0x7ffffffe, // Permission denied
FAULT = -0x7fffecff, // Bad address
BUSY = -0x7ffffff2, // Device busy
EXIST = -0x7fff9ffe, // File exists
XDEV = -0x7fff9ff5, // Cross-device link
NODEV = -0x7fff8ff9, // Operation not supported by device
NOTDIR = -0x7fff9ffb, // Not a directory
ISDIR = -0x7fff9ff7, // Is a directory
INVAL = -0x7ffffffb, // Invalid argument
NFILE = -0x7fff8ffa, // Too many open files in system
MFILE = -0x7fff9ff6, // Too many open files
NOTTY = -0x7fff8ff6, // Inappropriate ioctl for device
TXTBSY = -0x7fff8fc5, // Text file busy
FBIG = -0x7fff8ffc, // File too large
NOSPC = -0x7fff9ff9, // No space left on device
SPIPE = -0x7fff8ff4, // Illegal seek
ROFS = -0x7fff9ff8, // Read-only filesystem
MLINK = -0x7fff8ffb, // Too many links
PIPE = -0x7fff9ff3, // Broken pipe
BADF = -0x7fffa000, // Bad file descriptor
// math software
DOM = 33, // Numerical argument out of domain
RANGE = 34, // Result too large
// non-blocking and interrupt i/o
/// Also used for `WOULDBLOCK`.
AGAIN = -0x7ffffff5,
INPROGRESS = -0x7fff8fdc,
ALREADY = -0x7fff8fdb,
// ipc/network software -- argument errors
NOTSOCK = 38, // Socket operation on non-socket
DESTADDRREQ = 39, // Destination address required
MSGSIZE = 40, // Message too long
PROTOTYPE = 41, // Protocol wrong type for socket
NOPROTOOPT = 42, // Protocol not available
PROTONOSUPPORT = 43, // Protocol not supported
SOCKTNOSUPPORT = 44, // Socket type not supported
/// Also used for `NOTSUP`.
OPNOTSUPP = 45, // Operation not supported
PFNOSUPPORT = 46, // Protocol family not supported
AFNOSUPPORT = 47, // Address family not supported by protocol family
ADDRINUSE = 48, // Address already in use
ADDRNOTAVAIL = 49, // Can't assign requested address
// ipc/network software -- operational errors
NETDOWN = 50, // Network is down
NETUNREACH = 51, // Network is unreachable
NETRESET = 52, // Network dropped connection on reset
CONNABORTED = 53, // Software caused connection abort
CONNRESET = 54, // Connection reset by peer
NOBUFS = 55, // No buffer space available
ISCONN = 56, // Socket is already connected
NOTCONN = 57, // Socket is not connected
SHUTDOWN = 58, // Can't send after socket shutdown
TOOMANYREFS = 59, // Too many references: can't splice
TIMEDOUT = 60, // Operation timed out
CONNREFUSED = 61, // Connection refused
LOOP = 62, // Too many levels of symbolic links
NAMETOOLONG = 63, // File name too long
// should be rearranged
HOSTDOWN = 64, // Host is down
HOSTUNREACH = 65, // No route to host
NOTEMPTY = 66, // Directory not empty
// quotas & mush
PROCLIM = 67, // Too many processes
USERS = 68, // Too many users
DQUOT = 69, // Disc quota exceeded
// Network File System
STALE = 70, // Stale NFS file handle
REMOTE = 71, // Too many levels of remote in path
BADRPC = 72, // RPC struct is bad
RPCMISMATCH = 73, // RPC version wrong
PROGUNAVAIL = 74, // RPC prog. not avail
PROGMISMATCH = 75, // Program version wrong
PROCUNAVAIL = 76, // Bad procedure for program
NOLCK = 77, // No locks available
NOSYS = 78, // Function not implemented
FTYPE = 79, // Inappropriate file type or format
AUTH = 80, // Authentication error
NEEDAUTH = 81, // Need authenticator
IDRM = 82, // Identifier removed
NOMSG = 83, // No message of desired type
OVERFLOW = 84, // Value too large to be stored in data type
CANCELED = 85, // Operation canceled
ILSEQ = 86, // Illegal byte sequence
NOATTR = 87, // Attribute not found
DOOFUS = 88, // Programming error
BADMSG = 89, // Bad message
MULTIHOP = 90, // Multihop attempted
NOLINK = 91, // Link has been severed
PROTO = 92, // Protocol error
NOTCAPABLE = 93, // Capabilities insufficient
CAPMODE = 94, // Not permitted in capability mode
NOTRECOVERABLE = 95, // State not recoverable
OWNERDEAD = 96, // Previous owner died
_,
};
pub const MINSIGSTKSZ = switch (builtin.cpu.arch) {
.i386, .x86_64 => 2048,
.arm, .aarch64 => 4096,
else => @compileError("MINSIGSTKSZ not defined for this architecture"),
};
pub const SIGSTKSZ = MINSIGSTKSZ + 32768;
pub const SS_ONSTACK = 1;
pub const SS_DISABLE = 4;
pub const stack_t = extern struct {
sp: [*]u8,
size: isize,
flags: i32,
};
pub const S = struct {
pub const IFMT = 0o170000;
pub const IFIFO = 0o010000;
pub const IFCHR = 0o020000;
pub const IFDIR = 0o040000;
pub const IFBLK = 0o060000;
pub const IFREG = 0o100000;
pub const IFLNK = 0o120000;
pub const IFSOCK = 0o140000;
pub const IFWHT = 0o160000;
pub const ISUID = 0o4000;
pub const ISGID = 0o2000;
pub const ISVTX = 0o1000;
pub const IRWXU = 0o700;
pub const IRUSR = 0o400;
pub const IWUSR = 0o200;
pub const IXUSR = 0o100;
pub const IRWXG = 0o070;
pub const IRGRP = 0o040;
pub const IWGRP = 0o020;
pub const IXGRP = 0o010;
pub const IRWXO = 0o007;
pub const IROTH = 0o004;
pub const IWOTH = 0o002;
pub const IXOTH = 0o001;
pub fn ISFIFO(m: u32) bool {
return m & IFMT == IFIFO;
}
pub fn ISCHR(m: u32) bool {
return m & IFMT == IFCHR;
}
pub fn ISDIR(m: u32) bool {
return m & IFMT == IFDIR;
}
pub fn ISBLK(m: u32) bool {
return m & IFMT == IFBLK;
}
pub fn ISREG(m: u32) bool {
return m & IFMT == IFREG;
}
pub fn ISLNK(m: u32) bool {
return m & IFMT == IFLNK;
}
pub fn ISSOCK(m: u32) bool {
return m & IFMT == IFSOCK;
}
pub fn IWHT(m: u32) bool {
return m & IFMT == IFWHT;
}
};
pub const HOST_NAME_MAX = 255;
pub const AT = struct {
/// Magic value that specify the use of the current working directory
/// to determine the target of relative file paths in the openat() and
/// similar syscalls.
pub const FDCWD = -100;
/// Check access using effective user and group ID
pub const EACCESS = 0x0100;
/// Do not follow symbolic links
pub const SYMLINK_NOFOLLOW = 0x0200;
/// Follow symbolic link
pub const SYMLINK_FOLLOW = 0x0400;
/// Remove directory instead of file
pub const REMOVEDIR = 0x0800;
/// Fail if not under dirfd
pub const BENEATH = 0x1000;
};
pub const addrinfo = extern struct {
flags: i32,
family: i32,
socktype: i32,
protocol: i32,
addrlen: socklen_t,
canonname: ?[*:0]u8,
addr: ?*sockaddr,
next: ?*addrinfo,
};
pub const IPPROTO = struct {
/// dummy for IP
pub const IP = 0;
/// control message protocol
pub const ICMP = 1;
/// tcp
pub const TCP = 6;
/// user datagram protocol
pub const UDP = 17;
/// IP6 header
pub const IPV6 = 41;
/// raw IP packet
pub const RAW = 255;
/// IP6 hop-by-hop options
pub const HOPOPTS = 0;
/// group mgmt protocol
pub const IGMP = 2;
/// gateway^2 (deprecated)
pub const GGP = 3;
/// IPv4 encapsulation
pub const IPV4 = 4;
/// for compatibility
pub const IPIP = IPV4;
/// Stream protocol II
pub const ST = 7;
/// exterior gateway protocol
pub const EGP = 8;
/// private interior gateway
pub const PIGP = 9;
/// BBN RCC Monitoring
pub const RCCMON = 10;
/// network voice protocol
pub const NVPII = 11;
/// pup
pub const PUP = 12;
/// Argus
pub const ARGUS = 13;
/// EMCON
pub const EMCON = 14;
/// Cross Net Debugger
pub const XNET = 15;
/// Chaos
pub const CHAOS = 16;
/// Multiplexing
pub const MUX = 18;
/// DCN Measurement Subsystems
pub const MEAS = 19;
/// Host Monitoring
pub const HMP = 20;
/// Packet Radio Measurement
pub const PRM = 21;
/// xns idp
pub const IDP = 22;
/// Trunk-1
pub const TRUNK1 = 23;
/// Trunk-2
pub const TRUNK2 = 24;
/// Leaf-1
pub const LEAF1 = 25;
/// Leaf-2
pub const LEAF2 = 26;
/// Reliable Data
pub const RDP = 27;
/// Reliable Transaction
pub const IRTP = 28;
/// tp-4 w/ class negotiation
pub const TP = 29;
/// Bulk Data Transfer
pub const BLT = 30;
/// Network Services
pub const NSP = 31;
/// Merit Internodal
pub const INP = 32;
/// Datagram Congestion Control Protocol
pub const DCCP = 33;
/// Third Party Connect
pub const @"3PC" = 34;
/// InterDomain Policy Routing
pub const IDPR = 35;
/// XTP
pub const XTP = 36;
/// Datagram Delivery
pub const DDP = 37;
/// Control Message Transport
pub const CMTP = 38;
/// TP++ Transport
pub const TPXX = 39;
/// IL transport protocol
pub const IL = 40;
/// Source Demand Routing
pub const SDRP = 42;
/// IP6 routing header
pub const ROUTING = 43;
/// IP6 fragmentation header
pub const FRAGMENT = 44;
/// InterDomain Routing
pub const IDRP = 45;
/// resource reservation
pub const RSVP = 46;
/// General Routing Encap.
pub const GRE = 47;
/// Mobile Host Routing
pub const MHRP = 48;
/// BHA
pub const BHA = 49;
/// IP6 Encap Sec. Payload
pub const ESP = 50;
/// IP6 Auth Header
pub const AH = 51;
/// Integ. Net Layer Security
pub const INLSP = 52;
/// IP with encryption
pub const SWIPE = 53;
/// Next Hop Resolution
pub const NHRP = 54;
/// IP Mobility
pub const MOBILE = 55;
/// Transport Layer Security
pub const TLSP = 56;
/// SKIP
pub const SKIP = 57;
/// ICMP6
pub const ICMPV6 = 58;
/// IP6 no next header
pub const NONE = 59;
/// IP6 destination option
pub const DSTOPTS = 60;
/// any host internal protocol
pub const AHIP = 61;
/// CFTP
pub const CFTP = 62;
/// "hello" routing protocol
pub const HELLO = 63;
/// SATNET/Backroom EXPAK
pub const SATEXPAK = 64;
/// Kryptolan
pub const KRYPTOLAN = 65;
/// Remote Virtual Disk
pub const RVD = 66;
/// Pluribus Packet Core
pub const IPPC = 67;
/// Any distributed FS
pub const ADFS = 68;
/// Satnet Monitoring
pub const SATMON = 69;
/// VISA Protocol
pub const VISA = 70;
/// Packet Core Utility
pub const IPCV = 71;
/// Comp. Prot. Net. Executive
pub const CPNX = 72;
/// Comp. Prot. HeartBeat
pub const CPHB = 73;
/// Wang Span Network
pub const WSN = 74;
/// Packet Video Protocol
pub const PVP = 75;
/// BackRoom SATNET Monitoring
pub const BRSATMON = 76;
/// Sun net disk proto (temp.)
pub const ND = 77;
/// WIDEBAND Monitoring
pub const WBMON = 78;
/// WIDEBAND EXPAK
pub const WBEXPAK = 79;
/// ISO cnlp
pub const EON = 80;
/// VMTP
pub const VMTP = 81;
/// Secure VMTP
pub const SVMTP = 82;
/// Banyon VINES
pub const VINES = 83;
/// TTP
pub const TTP = 84;
/// NSFNET-IGP
pub const IGP = 85;
/// dissimilar gateway prot.
pub const DGP = 86;
/// TCF
pub const TCF = 87;
/// Cisco/GXS IGRP
pub const IGRP = 88;
/// OSPFIGP
pub const OSPFIGP = 89;
/// Strite RPC protocol
pub const SRPC = 90;
/// Locus Address Resoloution
pub const LARP = 91;
/// Multicast Transport
pub const MTP = 92;
/// AX.25 Frames
pub const AX25 = 93;
/// IP encapsulated in IP
pub const IPEIP = 94;
/// Mobile Int.ing control
pub const MICP = 95;
/// Semaphore Comm. security
pub const SCCSP = 96;
/// Ethernet IP encapsulation
pub const ETHERIP = 97;
/// encapsulation header
pub const ENCAP = 98;
/// any private encr. scheme
pub const APES = 99;
/// GMTP
pub const GMTP = 100;
/// payload compression (IPComp)
pub const IPCOMP = 108;
/// SCTP
pub const SCTP = 132;
/// IPv6 Mobility Header
pub const MH = 135;
/// UDP-Lite
pub const UDPLITE = 136;
/// IP6 Host Identity Protocol
pub const HIP = 139;
/// IP6 Shim6 Protocol
pub const SHIM6 = 140;
/// Protocol Independent Mcast
pub const PIM = 103;
/// CARP
pub const CARP = 112;
/// PGM
pub const PGM = 113;
/// MPLS-in-IP
pub const MPLS = 137;
/// PFSYNC
pub const PFSYNC = 240;
/// Reserved
pub const RESERVED_253 = 253;
/// Reserved
pub const RESERVED_254 = 254;
};
pub const rlimit_resource = enum(c_int) {
CPU = 0,
FSIZE = 1,
DATA = 2,
STACK = 3,
CORE = 4,
RSS = 5,
MEMLOCK = 6,
NPROC = 7,
NOFILE = 8,
SBSIZE = 9,
VMEM = 10,
NPTS = 11,
SWAP = 12,
KQUEUES = 13,
UMTXP = 14,
_,
pub const AS: rlimit_resource = .VMEM;
};
pub const rlim_t = i64;
pub const RLIM = struct {
/// No limit
pub const INFINITY: rlim_t = (1 << 63) - 1;
pub const SAVED_MAX = INFINITY;
pub const SAVED_CUR = INFINITY;
};
pub const rlimit = extern struct {
/// Soft limit
cur: rlim_t,
/// Hard limit
max: rlim_t,
};
pub const SHUT = struct {
pub const RD = 0;
pub const WR = 1;
pub const RDWR = 2;
};
// TODO fill out if needed
pub const directory_which = enum(c_int) {
B_USER_SETTINGS_DIRECTORY = 0xbbe,
_,
};
pub const cc_t = u8;
pub const speed_t = u8;
pub const tcflag_t = u32;
pub const NCCS = 32;
pub const termios = extern struct {
c_iflag: tcflag_t,
c_oflag: tcflag_t,
c_cflag: tcflag_t,
c_lflag: tcflag_t,
c_line: cc_t,
c_ispeed: speed_t,
c_ospeed: speed_t,
cc_t: [NCCS]cc_t,
}; | lib/std/c/haiku.zig |
pub const sabaton = @import("../../sabaton.zig");
pub const io = sabaton.io_impl.status_uart_mmio_32;
pub const panic = sabaton.panic;
pub const display = @import("display.zig");
pub const smp = @import("smp.zig");
pub const timer = @import("timer.zig");
const led = @import("led.zig");
// We know the page size is 0x1000
pub fn get_page_size() u64 {
return 0x1000;
}
fn ccu(offset: u16) *volatile u32 {
return @intToPtr(*volatile u32, @as(usize, 0x01C2_0000) + offset);
}
fn wait_stable(pll_addr: *volatile u32) void {
while ((pll_addr.* & (1 << 28)) == 0) {}
}
fn init_pll(offset: u16, pll_value: u32) void {
const reg = ccu(offset);
reg.* = pll_value;
wait_stable(reg);
}
fn clocks_init() void {
// Cock and ball torture?
// Clock and PLL torture.
init_pll(0x0010, 0x83001801); // PLL_VIDEO0
init_pll(0x0028, 0x80041811); // PLL_PERIPH0
init_pll(0x0040, 0x80C0041A); // PLL_MIPI
init_pll(0x0048, 0x83006207); // PLL_DE
// Cock gating registers?
// Clock gating registers.
ccu(0x0060).* = 0x33800040; // BUS_CLK_GATING_REG0
ccu(0x0064).* = 0x00201818; // BUS_CLK_GATING_REG1
ccu(0x0068).* = 0x00000020; // BUS_CLK_GATING_REG2
ccu(0x006C).* = 0x00010000; // BUS_CLK_GATING_REG3
//ccu(0x0070).* = 0x00000000; // BUS_CLK_GATING_REG4
ccu(0x0088).* = 0x0100000B; // SMHC0_CLK_REG
ccu(0x008C).* = 0x0001000E; // SMHC0_CLK_REG
ccu(0x0090).* = 0x01000005; // SMHC0_CLK_REG
ccu(0x00CC).* = 0x00030303; // USBPHY_CFG_REG
ccu(0x0104).* = 0x81000000; // DE_CLK_REG
ccu(0x0118).* = 0x80000000; // TCON0_CLK_REG
ccu(0x0150).* = 0x80000000; // HDMI_CLK_REG
ccu(0x0154).* = 0x80000000; // HDMI_SLOW_CLK_REG
ccu(0x0168).* = 0x00008001; // MIPI_DSI_CLK_REG
ccu(0x0224).* = 0x10040000; // PLL_AUDIO_BIAS_REG
}
fn reset_devices() void {
// zig fmt: off
const reg0_devs: u32 = 0
| (1 << 29) // USB-OHCI0
| (1 << 28) // USB-OTG-OHCI
| (1 << 25) // USB-EHCI0
| (1 << 24) // USB-OTG-EHCI0
| (1 << 23) // USB-OTG-Device
| (1 << 13) // NAND
| (1 << 1) // MIPI_DSI
;
const reg1_devs: u32 = 0
| (1 << 22) // SPINLOCK
| (1 << 21) // MSGBOX
| (1 << 20) // GPU
| (1 << 12) // DE
| (1 << 11) // HDMI1
| (1 << 10) // HDMI0
| (1 << 5) // DEINTERLACE
| (1 << 4) // TCON1
| (1 << 3) // TCON0
;
// zig fmt: on
ccu(0x02C0).* &= ~reg0_devs;
ccu(0x02C4).* &= ~reg1_devs;
ccu(0x02C0).* |= reg0_devs;
ccu(0x02C4).* |= reg1_devs;
}
export fn _main() linksection(".text.main") noreturn {
@call(.{ .modifier = .always_inline }, clocks_init, .{});
@call(.{ .modifier = .always_inline }, reset_devices, .{});
@call(.{ .modifier = .always_inline }, led.configure_led, .{});
// Orange
led.output(.{ .green = true, .red = true, .blue = false });
@call(.{ .modifier = .always_inline }, sabaton.main, .{});
}
pub fn panic_hook() void {
// Red
led.output(.{ .green = false, .red = true, .blue = false });
}
pub fn launch_kernel_hook() void {
// Blue
led.output(.{ .green = false, .red = false, .blue = true });
}
pub fn get_kernel() [*]u8 {
return sabaton.near("kernel_file_loc").read([*]u8);
}
// pub fn get_dtb() []u8 {
// return sabaton.near("dram_base").read([*]u8)[0..0x100000];
// }
pub fn get_dram() []u8 {
return sabaton.near("dram_base").read([*]u8)[0..get_dram_size()];
}
fn get_dram_size() u64 {
return 0x80000000;
}
pub fn map_platform(root: *sabaton.paging.Root) void {
// MMIO area
sabaton.paging.map(0, 0, 1024 * 1024 * 1024, .rw, .mmio, root);
sabaton.paging.map(sabaton.upper_half_phys_base, 0, 1024 * 1024 * 1024, .rw, .mmio, root);
}
pub fn add_platform_tags(kernel_header: *sabaton.Stivale2hdr) void {
_ = kernel_header;
sabaton.add_tag(&sabaton.near("uart_tag").addr(sabaton.Stivale2tag)[0]);
sabaton.add_tag(&sabaton.near("devicetree_tag").addr(sabaton.Stivale2tag)[0]);
}
pub fn get_uart_info() io.Info {
const base = 0x1C28000;
return .{
.uart = @intToPtr(*volatile u32, base),
.status = @intToPtr(*volatile u32, base + 0x14),
.mask = 0x20,
.value = 0x20,
};
} | src/platform/pine_aarch64/main.zig |
const std = @import("std");
const builtin = @import("builtin");
const ptx = @import("kernel_utils.zig");
pub export fn atomicHistogram(d_data: []u32, d_bins: []u32) callconv(ptx.Kernel) void {
const gid = ptx.getIdX();
if (gid >= d_data.len) return;
const bin = d_data[gid];
ptx.atomicAdd(&d_bins[bin], 1);
}
// const step: u32 = 32;
const SharedMem = opaque {};
// extern var bychunkHistogram_shared: SharedMem align(8) addrspace(.shared); // stage2
var bychunkHistogram_shared: [1024]u32 = undefined; // stage1
const bychunkHistogram_step: u32 = 32;
/// Fist accumulate into a shared histogram
/// then accumulate to the global histogram.
/// Should decreases contention when doing atomic adds.
pub export fn bychunkHistogram(d_data: []u32, d_bins: []u32) callconv(ptx.Kernel) void {
const n = d_data.len;
const num_bins = d_bins.len;
const step = bychunkHistogram_step;
// var s_bins = @ptrCast([*]addrspace(.shared) u32, &bychunkHistogram_shared); // stage2
var s_bins = @ptrCast([*]u32, &bychunkHistogram_shared); // stage1
const tid = ptx.threadIdX();
if (tid < num_bins) s_bins[ptx.threadIdX()] = 0;
ptx.syncThreads();
var i: u32 = 0;
while (i < step) : (i += 1) {
const offset = ptx.blockIdX() * ptx.blockDimX() * step + i * ptx.blockDimX() + tid;
if (offset < n) {
// Passing a .shared pointer to atomicAdd crashes stage2 here
// atomicAdd(&s_bins[d_data[offset]], 1);
_ = @atomicRmw(u32, &s_bins[d_data[offset]], .Add, 1, .SeqCst);
}
}
ptx.syncThreads();
if (tid < num_bins) {
ptx.atomicAdd(&d_bins[tid], s_bins[tid]);
}
}
pub export fn coarseBins(d_data: []u32, d_coarse_bins: []u32) callconv(ptx.Kernel) void {
const n = d_data.len;
const id = ptx.getIdX();
if (id < n) {
const rad = d_data[id] / 32;
d_coarse_bins[rad * n + id] = 1;
}
}
pub export fn shuffleCoarseBins32(
d_coarse_bins: []u32,
d_coarse_bins_boundaries: []u32,
d_cdf: []const u32,
d_in: []const u32,
) callconv(ptx.Kernel) void {
const n = d_in.len;
const id = ptx.getIdX();
if (id >= n) return;
const x = d_in[id];
const rad = x >> 5 & 0b11111;
const new_id = d_cdf[rad * n + id];
d_coarse_bins[new_id] = x;
if (id < 32) {
d_coarse_bins_boundaries[id] = d_cdf[id * n];
}
if (id == 32) {
d_coarse_bins_boundaries[id] = d_cdf[id * n - 1];
}
}
// extern var cdfIncremental_shared: SharedMem align(8) addrspace(.shared); // stage2
var cdfIncremental_shared: [1024]u32 = undefined; // stage1
pub export fn cdfIncremental(d_glob_bins: []u32, d_block_bins: []u32) callconv(ptx.Kernel) void {
const n = d_glob_bins.len;
const global_id = ptx.getIdX();
if (global_id >= n) return;
const tid = ptx.threadIdX();
// var d_bins = @ptrCast([*]addrspace(.shared) u32, &cdfIncremental_shared); // stage2
var d_bins = @ptrCast([*]u32, &cdfIncremental_shared); // stage1
ptx.syncThreads();
const last_tid = ptx.lastTid(n);
const total = ptx.exclusiveScan(.add, d_bins, tid, last_tid);
if (tid == last_tid) {
d_block_bins[ptx.blockIdX()] = total;
}
d_glob_bins[global_id] = d_bins[tid];
}
pub export fn cdfIncrementalShift(d_glob_bins: []u32, d_block_bins: []const u32) callconv(ptx.Kernel) void {
const block_shift = d_block_bins[ptx.blockIdX()];
d_glob_bins[ptx.getIdX()] += block_shift;
} | CS344/src/hw5_kernel.zig |
const std = @import("std");
const zap = @import("zap");
const hyperia = @import("hyperia.zig");
const testing = std.testing;
pub fn Channel(comptime T: type) type {
return struct {
const Self = @This();
const Node = struct {
next: ?*Node = null,
runnable: zap.Pool.Runnable = .{ .runFn = run },
frame: anyframe,
pub fn run(runnable: *zap.Pool.Runnable) void {
const self = @fieldParentPtr(Node, "runnable", runnable);
resume self.frame;
}
};
const EMPTY = 0;
const NOTIFIED = 1;
const COMMITTED = 2;
state: usize = EMPTY,
data: T = undefined,
pub fn wait(self: *Self) T {
var node: Node = .{ .frame = @frame() };
suspend {
var state = @atomicLoad(usize, &self.state, .Acquire);
while (true) {
const new_state = switch (state & 0b11) {
COMMITTED => {
hyperia.pool.schedule(.{}, &node.runnable);
break;
},
else => update: {
node.next = @intToPtr(?*Node, state & ~@as(usize, 0b11));
break :update @ptrToInt(&node) | (state & 0b11);
},
};
state = @cmpxchgWeak(
usize,
&self.state,
state,
new_state,
.Release,
.Acquire,
) orelse break;
}
}
return self.data;
}
pub fn get(self: *Self) ?T {
if (@atomicLoad(usize, &self.state, .Acquire) != COMMITTED) {
return null;
}
return self.data;
}
pub fn set(self: *Self) bool {
var state = @atomicLoad(usize, &self.state, .Monotonic);
const new_state = switch (state & 0b11) {
NOTIFIED, COMMITTED => return false,
else => state | NOTIFIED,
};
return @cmpxchgStrong(usize, &self.state, state, new_state, .Acquire, .Monotonic) == null;
}
pub fn reset(self: *Self) void {
@atomicStore(usize, &self.state, EMPTY, .Monotonic);
}
pub fn commit(self: *Self, data: T) void {
self.data = data;
const state = @atomicRmw(usize, &self.state, .Xchg, COMMITTED, .AcqRel);
if (state & 0b11 != NOTIFIED) unreachable;
var batch: zap.Pool.Batch = .{};
var it = @intToPtr(?*Node, state & ~@as(usize, 0b11));
while (it) |node| : (it = node.next) {
batch.push(&node.runnable);
}
hyperia.pool.schedule(.{}, batch);
}
};
}
test {
testing.refAllDecls(@This());
}
test "oneshot/channel: multiple waiters" {
hyperia.init();
defer hyperia.deinit();
var channel: Channel(void) = .{};
var a = async channel.wait();
var b = async channel.wait();
var c = async channel.wait();
var d = async channel.wait();
if (channel.set()) {
channel.commit({});
}
nosuspend await a;
nosuspend await b;
nosuspend await c;
nosuspend await d;
testing.expect(channel.state == Channel(void).COMMITTED);
}
test "oneshot/channel: stress test" {
const Frame = struct {
runnable: zap.Pool.Runnable = .{ .runFn = run },
frame: anyframe,
fn run(runnable: *zap.Pool.Runnable) void {
const self = @fieldParentPtr(@This(), "runnable", runnable);
resume self.frame;
}
};
const Context = struct {
channel: Channel(void) = .{},
event: std.Thread.StaticResetEvent = .{},
waiter_count: usize,
setter_count: usize,
fn runWaiter(self: *@This()) void {
var frame: Frame = .{ .frame = @frame() };
suspend hyperia.pool.schedule(.{}, &frame.runnable);
self.channel.wait();
}
fn runSetter(self: *@This()) void {
var frame: Frame = .{ .frame = @frame() };
suspend hyperia.pool.schedule(.{}, &frame.runnable);
if (self.channel.set()) {
self.channel.commit({});
}
}
pub fn run(self: *@This()) !void {
var frame: Frame = .{ .frame = @frame() };
suspend hyperia.pool.schedule(.{}, &frame.runnable);
var waiters = try testing.allocator.alloc(@Frame(@This().runWaiter), self.waiter_count);
var setters = try testing.allocator.alloc(@Frame(@This().runSetter), self.setter_count);
for (waiters) |*waiter| waiter.* = async self.runWaiter();
for (setters) |*setter| setter.* = async self.runSetter();
for (waiters) |*waiter| await waiter;
for (setters) |*setter| await setter;
suspend {
testing.allocator.free(setters);
testing.allocator.free(waiters);
self.event.set();
}
}
};
hyperia.init();
defer hyperia.deinit();
var test_count: usize = 1000;
var rand = std.rand.DefaultPrng.init(0);
while (test_count > 0) : (test_count -= 1) {
const waiter_count = rand.random.intRangeAtMost(usize, 4, 10);
const setter_count = rand.random.intRangeAtMost(usize, 4, 10);
var ctx: Context = .{
.waiter_count = waiter_count,
.setter_count = setter_count,
};
var frame = async ctx.run();
ctx.event.wait();
}
} | oneshot.zig |
const c = @import("c.zig");
pub const StaticGeometry = struct {
rect_2d_vertex_buffer: c.GLuint,
rect_2d_tex_coord_buffer: c.GLuint,
triangle_2d_vertex_buffer: c.GLuint,
triangle_2d_tex_coord_buffer: c.GLuint,
pub fn create() StaticGeometry {
var sg: StaticGeometry = undefined;
const rect_2d_vertexes = [_][3]c.GLfloat{
[_]c.GLfloat{ 0.0, 0.0, 0.0 },
[_]c.GLfloat{ 0.0, 1.0, 0.0 },
[_]c.GLfloat{ 1.0, 0.0, 0.0 },
[_]c.GLfloat{ 1.0, 1.0, 0.0 },
};
c.glGenBuffers(1, &sg.rect_2d_vertex_buffer);
c.glBindBuffer(c.GL_ARRAY_BUFFER, sg.rect_2d_vertex_buffer);
c.glBufferData(c.GL_ARRAY_BUFFER, 4 * 3 * @sizeOf(c.GLfloat), @ptrCast(*const anyopaque, &rect_2d_vertexes[0][0]), c.GL_STATIC_DRAW);
const rect_2d_tex_coords = [_][2]c.GLfloat{
[_]c.GLfloat{ 0, 0 },
[_]c.GLfloat{ 0, 1 },
[_]c.GLfloat{ 1, 0 },
[_]c.GLfloat{ 1, 1 },
};
c.glGenBuffers(1, &sg.rect_2d_tex_coord_buffer);
c.glBindBuffer(c.GL_ARRAY_BUFFER, sg.rect_2d_tex_coord_buffer);
c.glBufferData(c.GL_ARRAY_BUFFER, 4 * 2 * @sizeOf(c.GLfloat), @ptrCast(*const anyopaque, &rect_2d_tex_coords[0][0]), c.GL_STATIC_DRAW);
const triangle_2d_vertexes = [_][3]c.GLfloat{
[_]c.GLfloat{ 0.0, 0.0, 0.0 },
[_]c.GLfloat{ 0.0, 1.0, 0.0 },
[_]c.GLfloat{ 1.0, 0.0, 0.0 },
};
c.glGenBuffers(1, &sg.triangle_2d_vertex_buffer);
c.glBindBuffer(c.GL_ARRAY_BUFFER, sg.triangle_2d_vertex_buffer);
c.glBufferData(c.GL_ARRAY_BUFFER, 3 * 3 * @sizeOf(c.GLfloat), @ptrCast(*const anyopaque, &triangle_2d_vertexes[0][0]), c.GL_STATIC_DRAW);
const triangle_2d_tex_coords = [_][2]c.GLfloat{
[_]c.GLfloat{ 0, 0 },
[_]c.GLfloat{ 0, 1 },
[_]c.GLfloat{ 1, 0 },
};
c.glGenBuffers(1, &sg.triangle_2d_tex_coord_buffer);
c.glBindBuffer(c.GL_ARRAY_BUFFER, sg.triangle_2d_tex_coord_buffer);
c.glBufferData(c.GL_ARRAY_BUFFER, 3 * 2 * @sizeOf(c.GLfloat), @ptrCast(*const anyopaque, &triangle_2d_tex_coords[0][0]), c.GL_STATIC_DRAW);
return sg;
}
pub fn destroy(sg: *StaticGeometry) void {
c.glDeleteBuffers(1, &sg.rect_2d_tex_coord_buffer);
c.glDeleteBuffers(1, &sg.rect_2d_vertex_buffer);
c.glDeleteBuffers(1, &sg.triangle_2d_vertex_buffer);
c.glDeleteBuffers(1, &sg.triangle_2d_tex_coord_buffer);
}
}; | benchmarks/tetris/tetris/src/static_geometry.zig |
const std = @import("std");
const utils = @import("utils.zig");
const testing = std.testing;
/// Token represents the offset inside a file where a token exists
pub const Token = union(enum) {
/// open_brace is the start of the opening brace in a block
open_brace: usize,
/// close_brace is the end_keyword of the closing brace in a block
/// the idea behind, is that now we can slice
/// text[open_brace..close_brace] and get the full block
close_brace: usize,
/// ident represents an identifier
/// it's stored in a way that the whole identifier is
/// text[ident.start..ident.end]
ident: struct { start: usize, end: usize },
/// range_keyword keyword
range_keyword: usize,
/// if_keyword keyword
if_keyword: usize,
/// end_keyword keyword
end_keyword: usize,
fn start(self: Token) usize {
return switch (self) {
.open_brace => self.open_brace,
.close_brace => self.close_brace,
.ident => self.ident.start,
.range_keyword => self.range_keyword,
.if_keyword => self.if_keyword,
.end_keyword => self.end_keyword,
};
}
};
pub const Parser = struct {
const Self = @This();
tokens: []const Token = &.{},
text: []const u8 = &.{},
/// tokenize a file into a token stream & ref to source
fn tokenize(comptime self: Self) ![]const Token {
{
var i: usize = 0;
var tokens: []const Token = &.{};
while (i < self.text.len) : (i += 1) {
const tok: ?Token = switch (self.text[i]) {
'{' => if (self.text.len > i + 1 and self.text[i + 1] == '{') Token{ .open_brace = i } else null,
'}' => if (self.text.len > i + 1 and self.text[i + 1] == '}') Token{ .close_brace = i + 2 } else null, // see Token.close_brace
'.' => switch (tokens[tokens.len - 1]) {
Token.open_brace, Token.range_keyword, Token.if_keyword => x: {
i += 1; // skip the dot
while (i < self.text.len and self.text[i] == ' ') : (i += 1) {} // eat whitespace
const ident_start = i;
while (i < self.text.len and
self.text[i] != '}' and
self.text[i] != ' ') : (i += 1)
{} // eat until closing brace
break :x if (ident_start == i) null else Token{ .ident = .{ .start = ident_start, .end = i } };
},
else => null,
},
'r' => if (tokens[tokens.len - 1] == Token.open_brace and
self.text.len > i + 5 and
std.mem.eql(u8, self.text[i .. i + 5], "range"))
//
Token{ .range_keyword = i }
else
null,
'e' => if (tokens[tokens.len - 1] == Token.open_brace and
self.text.len > i + 3 and
std.mem.eql(u8, self.text[i .. i + 3], "end"))
//
Token{ .end_keyword = i }
else
null,
'i' => if (tokens[tokens.len - 1] == Token.open_brace and
self.text.len > i + 2 and
std.mem.eql(u8, self.text[i .. i + 2], "if"))
//
Token{ .if_keyword = i }
else
null,
else => null,
};
if (tok) |t| tokens = tokens ++ [_]Token{t};
}
return tokens;
}
}
/// Decl is an *operational* block.
/// It contains the range_keyword at which that block operates
/// and it's possible values
pub const Decl = union(enum) {
/// the block is an identifier
decls: []const Decl,
/// possible ops
end: Block,
range: Block,
cond: Block,
ident: Block,
// alias
const Tupl = utils.Tuple(?Decl, usize);
/// parse a declaration
fn parse(comptime toks: []const Token, text: []const u8) !Tupl {
var i: usize = 0;
switch (toks[i]) {
Token.open_brace => {
i += 1;
return switch (toks[i]) {
Token.close_brace => Tupl.init(null, 2), // empty block
Token.ident => Decl.parseIdent(toks, text),
Token.range_keyword => Decl.parseRange(toks, text),
Token.if_keyword => Decl.parseCond(toks, text),
Token.end_keyword => Decl.parseEnd(toks, text),
else => ParsingError.expected_ident,
};
},
else => {},
}
return ParsingError.expected_open_brace;
}
fn parseCond(comptime toks: []const Token, text: []const u8) !Tupl {
if (toks.len < 4) parseError("'{s}': expected matching braces, ident & keywords (line:index) :{}:{}", toks[0].start(), text);
if (toks[0] != Token.open_brace) parseError("'{s}': expected open brace (line:index) :{}:{}", toks[0].start(), text);
if (toks[1] != Token.if_keyword) parseError("'{s}': expected if keyword (line:index) :{}:{}", toks[1].start(), text);
if (toks[2] != Token.ident) parseError("'{s}': expected ident (line:index) :{}:{}", toks[2].start(), text);
if (toks[3] != Token.close_brace) parseError("'{s}': expected close brace (line:index) :{}:{}", toks[2].start(), text);
var decls: []const Decl = ([_]Decl{
Decl{
.cond = .{
.start = toks[0].open_brace,
.tag = text[toks[2].ident.start..toks[2].ident.end],
.end = toks[3].close_brace,
},
},
})[0..]; // I hate this, but I'm not familar enough with the syntax to do it better
var i: usize = 4;
while (i < toks.len) {
const d = try Decl.parse(toks[i..], text);
i += d.get(1);
if (d.get(0)) |decl| {
decls = decls ++ [_]Decl{decl};
if (decl == Decl.end) break;
}
}
return Tupl.init(Decl{ .decls = decls }, i);
}
/// parses an identifier
fn parseIdent(comptime toks: []const Token, text: []const u8) !Tupl {
if (toks.len < 3) parseError("'{s}': expected matching braces & keyword (line:index) :{}:{}", toks[0].start(), text);
if (toks[0] != Token.open_brace) parseError("'{s}': expected open brace (line:index) :{}:{}", toks[0].start(), text);
if (toks[1] != Token.ident) parseError("'{s}': expected ident (line:index) :{}:{}", toks[1].start(), text);
if (toks[2] != Token.close_brace) parseError("'{s}': expected close brace (line:index) :{}:{}", toks[2].start(), text);
var range: Block = .{
.start = toks[0].open_brace,
.tag = text[toks[1].ident.start..toks[1].ident.end],
.end = toks[2].close_brace,
};
const i = Decl{ .ident = range };
return Tupl.init(i, 3);
}
/// parses the end_keyword keyword with its braces
fn parseEnd(comptime toks: []const Token, text: []const u8) !Tupl {
if (toks.len < 3) parseError("'{s}': expected matching braces & keyword (line:index) :{}:{}", toks[0].start(), text);
if (toks[0] != Token.open_brace) parseError("'{s}': expected open brace (line:index) :{}:{}", toks[0].start(), text);
if (toks[1] != Token.end_keyword) parseError("'{s}': expected end keyword (line:index) :{}:{}", toks[1].start(), text);
if (toks[2] != Token.close_brace) parseError("'{s}': expected close brace (line:index) :{}:{}", toks[2].start(), text);
return Tupl.init(Decl{ .end = .{ .start = toks[0].open_brace, .end = toks[2].close_brace } }, 3);
}
/// parses a range_keyword
fn parseRange(comptime toks: []const Token, text: []const u8) !Tupl {
if (toks.len < 4) parseError("'{s}': expected matching braces, ident & keywords (line:index) :{}:{}", toks[0].start(), text);
if (toks[0] != Token.open_brace) parseError("'{s}': expected open brace (line:index) :{}:{}", toks[0].start(), text);
if (toks[1] != Token.range_keyword) parseError("'{s}': expected range keyword (line:index) :{}:{}", toks[1].start(), text);
if (toks[2] != Token.ident) parseError("'{s}': expected ident (line:index) :{}:{}", toks[2].start(), text);
if (toks[3] != Token.close_brace) parseError("'{s}': expected close brace (line:index) :{}:{}", toks[2].start(), text);
var decls: []const Decl = ([_]Decl{
Decl{
.range = .{
.start = toks[0].open_brace,
.tag = text[toks[2].ident.start..toks[2].ident.end],
.end = toks[3].close_brace,
},
},
})[0..]; // I hate this, but I'm not familar enough with the syntax to do it better
var i: usize = 4;
while (i < toks.len) {
const d = try Decl.parse(toks[i..], text);
i += d.get(1);
if (d.get(0)) |decl| {
decls = decls ++ [_]Decl{decl};
if (decl == Decl.end) break;
}
}
return Tupl.init(Decl{ .decls = decls }, i);
}
/// get_start is a helper function that returns the start of any block
pub fn startOr(self: Decl, or_: usize) usize {
return switch (self) {
Decl.end => self.end.start,
Decl.range => self.range.start,
Decl.ident => self.ident.start,
Decl.decls => if (self.decls.len > 0) self.decls[0].range.start else or_,
};
}
/// get_end is a helper function that returns the end of any block
pub fn endOr(self: Decl, or_: usize) usize {
return switch (self) {
Decl.end => self.end.end,
Decl.range => self.range.end,
Decl.ident => self.ident.end,
Decl.decls => if (self.decls.len > 0) self.decls[self.decls.len - 1].range.end else or_,
};
}
fn parseError(comptime format: []const u8, index: usize, text: []const u8) void {
const idx = utils.indexToLineStack(index, text);
const line = utils.getLine(idx.get(1), text);
const buf = std.fmt.comptimePrint(format, .{ line, idx.get(0), idx.get(1) });
@compileError(buf);
}
};
/// Block is a range_keyword of tokens
/// It *must* have a start and end_keyword
pub const Block = struct {
/// tag is the identifier that the range_keyword is for
tag: ?[]const u8 = null,
/// start is the start of the range_keyword, text[start..end_keyword] => no more placeholders
start: usize = undefined,
/// end_keyword is the end_keyword of the range_keyword, text[start..end_keyword] => no more placeholders
end: usize = undefined,
};
/// Errors met while parsing
/// TODO: Find a good way to report errors such that we give file position to the user
pub const ParsingError = error{
expected_close_brace,
expected_open_brace,
expected_ident,
expected_if_keyword,
expected_end_keyword,
expected_range_keyword,
unknown,
};
/// new initializes a new template parser
pub fn new(comptime input: []const u8) *Self {
var self = Self{};
self.text = input;
return &self;
}
/// parse the file to a list of decls
pub fn parse(comptime self: *Self) ![]const Decl {
self.tokens = try self.tokenize();
var decls: []const Decl = &.{};
comptime {
var i = 0;
while (i < self.tokens.len) {
const tupl = try Decl.parse(self.tokens[i..], self.text);
if (tupl.get(0)) |d| decls = decls ++ [_]Decl{d};
i += tupl.get(1);
}
}
return decls;
}
};
test "parse range" {
comptime var decls = try Parser.new("{{ range .foo }} {{ .bar }} {{ end }}").parse();
const range_decl = decls[0];
try testing.expectEqual(decls.len, 1);
try utils.expectString("foo", range_decl.decls[0].range.tag.?);
try testing.expectEqual(0, range_decl.decls[0].range.start);
try testing.expectEqual(16, range_decl.decls[0].range.end);
try utils.expectString("bar", range_decl.decls[1].ident.tag.?);
try testing.expectEqual(17, range_decl.decls[1].ident.start);
try testing.expectEqual(27, range_decl.decls[1].ident.end);
try testing.expectEqual(28, range_decl.decls[2].end.start);
try testing.expectEqual(37, range_decl.decls[2].end.end);
comptime decls = try Parser.new("{{ range .foo }} {{ .bar }} {{ end }} {{ .baz }}").parse();
try testing.expectEqual(decls.len, 2);
try utils.expectString("foo", decls[0].decls[0].range.tag.?);
try testing.expectEqual(0, decls[0].decls[0].range.start);
try testing.expectEqual(16, decls[0].decls[0].range.end);
try utils.expectString("bar", decls[0].decls[1].ident.tag.?);
try testing.expectEqual(17, decls[0].decls[1].ident.start);
try testing.expectEqual(27, decls[0].decls[1].ident.end);
try testing.expectEqual(28, decls[0].decls[2].end.start);
try testing.expectEqual(37, decls[0].decls[2].end.end);
try utils.expectString("baz", decls[1].ident.tag.?);
try testing.expectEqual(38, decls[1].ident.start);
try testing.expectEqual(48, decls[1].ident.end);
// recursive
comptime decls = try Parser.new("{{ range .foo }} {{ range .bar }} {{ .baz }} {{ end }} {{ end }}").parse();
try testing.expectEqual(decls.len, 1);
try utils.expectString("foo", decls[0].decls[0].range.tag.?);
try testing.expectEqual(0, decls[0].decls[0].range.start);
try testing.expectEqual(16, decls[0].decls[0].range.end);
try utils.expectString("bar", decls[0].decls[1].decls[0].range.tag.?);
try testing.expectEqual(17, decls[0].decls[1].decls[0].range.start);
try testing.expectEqual(33, decls[0].decls[1].decls[0].range.end);
try utils.expectString("baz", decls[0].decls[1].decls[1].ident.tag.?);
try testing.expectEqual(34, decls[0].decls[1].decls[1].ident.start);
try testing.expectEqual(44, decls[0].decls[1].decls[1].ident.end);
try testing.expectEqual(45, decls[0].decls[1].decls[2].end.start);
try testing.expectEqual(54, decls[0].decls[1].decls[2].end.end);
try testing.expectEqual(55, decls[0].decls[2].end.start);
try testing.expectEqual(64, decls[0].decls[2].end.end);
comptime decls = Parser.new("{{ range .foo }} {{ .bar }}").parse() catch |err|
try testing.expectEqual(err, Parser.Error.expected_end_keyword);
comptime decls = Parser.new("{{ range .foo }}").parse() catch |err|
try testing.expectEqual(err, Parser.Error.expected_end_keyword);
}
test "parse cond" {
comptime var decls = try Parser.new("{{ if .foo }} {{ .bar }} {{ end }}").parse();
try testing.expectEqual(decls.len, 1);
const if_decl = decls[0];
try utils.expectString("foo", if_decl.decls[0].cond.tag.?);
try testing.expectEqual(0, if_decl.decls[0].cond.start);
try testing.expectEqual(13, if_decl.decls[0].cond.end);
try utils.expectString("bar", if_decl.decls[1].ident.tag.?);
try testing.expectEqual(14, if_decl.decls[1].ident.start);
try testing.expectEqual(24, if_decl.decls[1].ident.end);
try testing.expectEqual(25, if_decl.decls[2].end.start);
try testing.expectEqual(34, if_decl.decls[2].end.end);
}
test "parse idents" {
comptime var decls = try Parser.new("").parse();
try testing.expectEqual(0, decls.len);
comptime decls = try Parser.new("{{ .foo }}").parse();
try testing.expectEqual(1, decls.len);
try utils.expectString("foo", decls[0].ident.tag.?);
try testing.expectEqual(0, decls[0].ident.start);
try testing.expectEqual(10, decls[0].ident.end);
comptime decls = try Parser.new("{{ .foo }} {{ .bar }}").parse();
try testing.expectEqual(2, decls.len);
try utils.expectString("foo", decls[0].ident.tag.?);
try testing.expectEqual(0, decls[0].ident.start);
try testing.expectEqual(10, decls[0].ident.end);
try utils.expectString("bar", decls[1].ident.tag.?);
try testing.expectEqual(11, decls[1].ident.start);
try testing.expectEqual(21, decls[1].ident.end);
}
test "tokenize idents" {
// none
comptime var tokens = try Parser.new("").tokenize();
try testing.expectEqual(tokens.len, 0);
// basic
comptime tokens = try Parser.new(" {{ .foo }} not inside").tokenize();
try testing.expectEqual(tokens.len, 3);
try testing.expectEqual(Token{ .open_brace = 1 }, tokens[0]);
try testing.expectEqual(Token{ .ident = .{ .start = 5, .end = 8 } }, tokens[1]);
try testing.expectEqual(Token{ .close_brace = 11 }, tokens[2]);
// nested
comptime tokens = try Parser.new("{{ .foo.bar }}").tokenize();
try testing.expectEqual(tokens.len, 3);
try testing.expectEqual(Token{ .open_brace = 0 }, tokens[0]);
try testing.expectEqual(Token{ .ident = .{ .start = 4, .end = 11 } }, tokens[1]);
try testing.expectEqual(Token{ .close_brace = 14 }, tokens[2]);
// multiple
comptime tokens = try Parser.new("{{ .foo }} {{ .bar }}").tokenize();
try testing.expectEqual(tokens.len, 6);
try testing.expectEqual(Token{ .open_brace = 0 }, tokens[0]);
try testing.expectEqual(Token{ .ident = .{ .start = 4, .end = 7 } }, tokens[1]);
try testing.expectEqual(Token{ .close_brace = 10 }, tokens[2]);
try testing.expectEqual(Token{ .open_brace = 11 }, tokens[3]);
try testing.expectEqual(Token{ .ident = .{ .start = 15, .end = 18 } }, tokens[4]);
try testing.expectEqual(Token{ .close_brace = 21 }, tokens[5]);
// random whitespace
comptime tokens = try Parser.new("{{ .foo }}").tokenize();
try testing.expectEqual(tokens.len, 3);
try testing.expectEqual(Token{ .open_brace = 0 }, tokens[0]);
try testing.expectEqual(Token{ .ident = .{ .start = 5, .end = 8 } }, tokens[1]);
try testing.expectEqual(Token{ .close_brace = 19 }, tokens[2]);
}
test "tokenize range_keyword" {
comptime var tokens = try Parser.new("{{ range .foo }} {{ .bar }} {{ end }}").tokenize();
try testing.expectEqual(tokens.len, 10);
try testing.expectEqual(Token{ .open_brace = 0 }, tokens[0]);
try testing.expectEqual(Token{ .range_keyword = 3 }, tokens[1]);
try testing.expectEqual(Token{ .ident = .{ .start = 10, .end = 13 } }, tokens[2]);
try testing.expectEqual(Token{ .close_brace = 16 }, tokens[3]);
try testing.expectEqual(Token{ .open_brace = 17 }, tokens[4]);
try testing.expectEqual(Token{ .ident = .{ .start = 21, .end = 24 } }, tokens[5]);
try testing.expectEqual(Token{ .close_brace = 27 }, tokens[6]);
try testing.expectEqual(Token{ .open_brace = 28 }, tokens[7]);
try testing.expectEqual(Token{ .end_keyword = 31 }, tokens[8]);
try testing.expectEqual(Token{ .close_brace = 37 }, tokens[9]);
}
test "tokenize if_keyword" {
comptime var tokens = try Parser.new("{{ if .foo }} {{ .bar }} {{ end }}").tokenize();
try testing.expectEqual(10, tokens.len);
try testing.expectEqual(Token{ .open_brace = 0 }, tokens[0]);
try testing.expectEqual(Token{ .if_keyword = 3 }, tokens[1]);
try testing.expectEqual(Token{ .ident = .{ .start = 7, .end = 10 } }, tokens[2]);
try testing.expectEqual(Token{ .close_brace = 13 }, tokens[3]);
try testing.expectEqual(Token{ .open_brace = 14 }, tokens[4]);
try testing.expectEqual(Token{ .ident = .{ .start = 18, .end = 21 } }, tokens[5]);
try testing.expectEqual(Token{ .close_brace = 24 }, tokens[6]);
try testing.expectEqual(Token{ .open_brace = 25 }, tokens[7]);
try testing.expectEqual(Token{ .end_keyword = 28 }, tokens[8]);
try testing.expectEqual(Token{ .close_brace = 34 }, tokens[9]);
}
// This tests compile error messages.
// uncomment to see
test "error handling" {
// _ = comptime try Parser.new("{{ if }}").parse();
} | src/parser.zig |
pub const IOCTL_NDIS_RESERVED5 = @as(u32, 1507380);
pub const IOCTL_NDIS_RESERVED6 = @as(u32, 1540152);
pub const NDIS_OBJECT_TYPE_DEFAULT = @as(u32, 128);
pub const NDIS_OBJECT_TYPE_MINIPORT_INIT_PARAMETERS = @as(u32, 129);
pub const NDIS_OBJECT_TYPE_SG_DMA_DESCRIPTION = @as(u32, 131);
pub const NDIS_OBJECT_TYPE_MINIPORT_INTERRUPT = @as(u32, 132);
pub const NDIS_OBJECT_TYPE_DEVICE_OBJECT_ATTRIBUTES = @as(u32, 133);
pub const NDIS_OBJECT_TYPE_BIND_PARAMETERS = @as(u32, 134);
pub const NDIS_OBJECT_TYPE_OPEN_PARAMETERS = @as(u32, 135);
pub const NDIS_OBJECT_TYPE_RSS_CAPABILITIES = @as(u32, 136);
pub const NDIS_OBJECT_TYPE_RSS_PARAMETERS = @as(u32, 137);
pub const NDIS_OBJECT_TYPE_MINIPORT_DRIVER_CHARACTERISTICS = @as(u32, 138);
pub const NDIS_OBJECT_TYPE_FILTER_DRIVER_CHARACTERISTICS = @as(u32, 139);
pub const NDIS_OBJECT_TYPE_FILTER_PARTIAL_CHARACTERISTICS = @as(u32, 140);
pub const NDIS_OBJECT_TYPE_FILTER_ATTRIBUTES = @as(u32, 141);
pub const NDIS_OBJECT_TYPE_CLIENT_CHIMNEY_OFFLOAD_GENERIC_CHARACTERISTICS = @as(u32, 142);
pub const NDIS_OBJECT_TYPE_PROVIDER_CHIMNEY_OFFLOAD_GENERIC_CHARACTERISTICS = @as(u32, 143);
pub const NDIS_OBJECT_TYPE_CO_PROTOCOL_CHARACTERISTICS = @as(u32, 144);
pub const NDIS_OBJECT_TYPE_CO_MINIPORT_CHARACTERISTICS = @as(u32, 145);
pub const NDIS_OBJECT_TYPE_MINIPORT_PNP_CHARACTERISTICS = @as(u32, 146);
pub const NDIS_OBJECT_TYPE_CLIENT_CHIMNEY_OFFLOAD_CHARACTERISTICS = @as(u32, 147);
pub const NDIS_OBJECT_TYPE_PROVIDER_CHIMNEY_OFFLOAD_CHARACTERISTICS = @as(u32, 148);
pub const NDIS_OBJECT_TYPE_PROTOCOL_DRIVER_CHARACTERISTICS = @as(u32, 149);
pub const NDIS_OBJECT_TYPE_REQUEST_EX = @as(u32, 150);
pub const NDIS_OBJECT_TYPE_TIMER_CHARACTERISTICS = @as(u32, 151);
pub const NDIS_OBJECT_TYPE_STATUS_INDICATION = @as(u32, 152);
pub const NDIS_OBJECT_TYPE_FILTER_ATTACH_PARAMETERS = @as(u32, 153);
pub const NDIS_OBJECT_TYPE_FILTER_PAUSE_PARAMETERS = @as(u32, 154);
pub const NDIS_OBJECT_TYPE_FILTER_RESTART_PARAMETERS = @as(u32, 155);
pub const NDIS_OBJECT_TYPE_PORT_CHARACTERISTICS = @as(u32, 156);
pub const NDIS_OBJECT_TYPE_PORT_STATE = @as(u32, 157);
pub const NDIS_OBJECT_TYPE_MINIPORT_ADAPTER_REGISTRATION_ATTRIBUTES = @as(u32, 158);
pub const NDIS_OBJECT_TYPE_MINIPORT_ADAPTER_GENERAL_ATTRIBUTES = @as(u32, 159);
pub const NDIS_OBJECT_TYPE_MINIPORT_ADAPTER_OFFLOAD_ATTRIBUTES = @as(u32, 160);
pub const NDIS_OBJECT_TYPE_MINIPORT_ADAPTER_NATIVE_802_11_ATTRIBUTES = @as(u32, 161);
pub const NDIS_OBJECT_TYPE_RESTART_GENERAL_ATTRIBUTES = @as(u32, 162);
pub const NDIS_OBJECT_TYPE_PROTOCOL_RESTART_PARAMETERS = @as(u32, 163);
pub const NDIS_OBJECT_TYPE_MINIPORT_ADD_DEVICE_REGISTRATION_ATTRIBUTES = @as(u32, 164);
pub const NDIS_OBJECT_TYPE_CO_CALL_MANAGER_OPTIONAL_HANDLERS = @as(u32, 165);
pub const NDIS_OBJECT_TYPE_CO_CLIENT_OPTIONAL_HANDLERS = @as(u32, 166);
pub const NDIS_OBJECT_TYPE_OFFLOAD = @as(u32, 167);
pub const NDIS_OBJECT_TYPE_OFFLOAD_ENCAPSULATION = @as(u32, 168);
pub const NDIS_OBJECT_TYPE_CONFIGURATION_OBJECT = @as(u32, 169);
pub const NDIS_OBJECT_TYPE_DRIVER_WRAPPER_OBJECT = @as(u32, 170);
pub const NDIS_OBJECT_TYPE_HD_SPLIT_ATTRIBUTES = @as(u32, 171);
pub const NDIS_OBJECT_TYPE_NSI_NETWORK_RW_STRUCT = @as(u32, 172);
pub const NDIS_OBJECT_TYPE_NSI_COMPARTMENT_RW_STRUCT = @as(u32, 173);
pub const NDIS_OBJECT_TYPE_NSI_INTERFACE_PERSIST_RW_STRUCT = @as(u32, 174);
pub const NDIS_OBJECT_TYPE_MINIPORT_ADAPTER_HARDWARE_ASSIST_ATTRIBUTES = @as(u32, 175);
pub const NDIS_OBJECT_TYPE_SHARED_MEMORY_PROVIDER_CHARACTERISTICS = @as(u32, 176);
pub const NDIS_OBJECT_TYPE_RSS_PROCESSOR_INFO = @as(u32, 177);
pub const NDIS_OBJECT_TYPE_NDK_PROVIDER_CHARACTERISTICS = @as(u32, 178);
pub const NDIS_OBJECT_TYPE_MINIPORT_ADAPTER_NDK_ATTRIBUTES = @as(u32, 179);
pub const NDIS_OBJECT_TYPE_MINIPORT_SS_CHARACTERISTICS = @as(u32, 180);
pub const NDIS_OBJECT_TYPE_QOS_CAPABILITIES = @as(u32, 181);
pub const NDIS_OBJECT_TYPE_QOS_PARAMETERS = @as(u32, 182);
pub const NDIS_OBJECT_TYPE_QOS_CLASSIFICATION_ELEMENT = @as(u32, 183);
pub const NDIS_OBJECT_TYPE_SWITCH_OPTIONAL_HANDLERS = @as(u32, 184);
pub const NDIS_OBJECT_TYPE_PD_TRANSMIT_QUEUE = @as(u32, 190);
pub const NDIS_OBJECT_TYPE_PD_RECEIVE_QUEUE = @as(u32, 191);
pub const NDIS_OBJECT_TYPE_MINIPORT_ADAPTER_PACKET_DIRECT_ATTRIBUTES = @as(u32, 197);
pub const NDIS_OBJECT_TYPE_MINIPORT_DEVICE_POWER_NOTIFICATION = @as(u32, 198);
pub const NDIS_OBJECT_TYPE_RSS_PARAMETERS_V2 = @as(u32, 200);
pub const NDIS_OBJECT_TYPE_RSS_SET_INDIRECTION_ENTRIES = @as(u32, 201);
pub const NDIS_STATISTICS_FLAGS_VALID_DIRECTED_FRAMES_RCV = @as(u32, 1);
pub const NDIS_STATISTICS_FLAGS_VALID_MULTICAST_FRAMES_RCV = @as(u32, 2);
pub const NDIS_STATISTICS_FLAGS_VALID_BROADCAST_FRAMES_RCV = @as(u32, 4);
pub const NDIS_STATISTICS_FLAGS_VALID_BYTES_RCV = @as(u32, 8);
pub const NDIS_STATISTICS_FLAGS_VALID_RCV_DISCARDS = @as(u32, 16);
pub const NDIS_STATISTICS_FLAGS_VALID_RCV_ERROR = @as(u32, 32);
pub const NDIS_STATISTICS_FLAGS_VALID_DIRECTED_FRAMES_XMIT = @as(u32, 64);
pub const NDIS_STATISTICS_FLAGS_VALID_MULTICAST_FRAMES_XMIT = @as(u32, 128);
pub const NDIS_STATISTICS_FLAGS_VALID_BROADCAST_FRAMES_XMIT = @as(u32, 256);
pub const NDIS_STATISTICS_FLAGS_VALID_BYTES_XMIT = @as(u32, 512);
pub const NDIS_STATISTICS_FLAGS_VALID_XMIT_ERROR = @as(u32, 1024);
pub const NDIS_STATISTICS_FLAGS_VALID_XMIT_DISCARDS = @as(u32, 32768);
pub const NDIS_STATISTICS_FLAGS_VALID_DIRECTED_BYTES_RCV = @as(u32, 65536);
pub const NDIS_STATISTICS_FLAGS_VALID_MULTICAST_BYTES_RCV = @as(u32, 131072);
pub const NDIS_STATISTICS_FLAGS_VALID_BROADCAST_BYTES_RCV = @as(u32, 262144);
pub const NDIS_STATISTICS_FLAGS_VALID_DIRECTED_BYTES_XMIT = @as(u32, 524288);
pub const NDIS_STATISTICS_FLAGS_VALID_MULTICAST_BYTES_XMIT = @as(u32, 1048576);
pub const NDIS_STATISTICS_FLAGS_VALID_BROADCAST_BYTES_XMIT = @as(u32, 2097152);
pub const NDIS_STATISTICS_INFO_REVISION_1 = @as(u32, 1);
pub const NDIS_RSC_STATISTICS_REVISION_1 = @as(u32, 1);
pub const NDIS_INTERRUPT_MODERATION_CHANGE_NEEDS_RESET = @as(u32, 1);
pub const NDIS_INTERRUPT_MODERATION_CHANGE_NEEDS_REINITIALIZE = @as(u32, 2);
pub const NDIS_INTERRUPT_MODERATION_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_TIMEOUT_DPC_REQUEST_CAPABILITIES_REVISION_1 = @as(u32, 1);
pub const NDIS_OBJECT_TYPE_PCI_DEVICE_CUSTOM_PROPERTIES_REVISION_1 = @as(u32, 1);
pub const NDIS_OBJECT_TYPE_PCI_DEVICE_CUSTOM_PROPERTIES_REVISION_2 = @as(u32, 2);
pub const OID_GEN_SUPPORTED_LIST = @as(u32, 65793);
pub const OID_GEN_HARDWARE_STATUS = @as(u32, 65794);
pub const OID_GEN_MEDIA_SUPPORTED = @as(u32, 65795);
pub const OID_GEN_MEDIA_IN_USE = @as(u32, 65796);
pub const OID_GEN_MAXIMUM_LOOKAHEAD = @as(u32, 65797);
pub const OID_GEN_MAXIMUM_FRAME_SIZE = @as(u32, 65798);
pub const OID_GEN_LINK_SPEED = @as(u32, 65799);
pub const OID_GEN_TRANSMIT_BUFFER_SPACE = @as(u32, 65800);
pub const OID_GEN_RECEIVE_BUFFER_SPACE = @as(u32, 65801);
pub const OID_GEN_TRANSMIT_BLOCK_SIZE = @as(u32, 65802);
pub const OID_GEN_RECEIVE_BLOCK_SIZE = @as(u32, 65803);
pub const OID_GEN_VENDOR_ID = @as(u32, 65804);
pub const OID_GEN_VENDOR_DESCRIPTION = @as(u32, 65805);
pub const OID_GEN_CURRENT_PACKET_FILTER = @as(u32, 65806);
pub const OID_GEN_CURRENT_LOOKAHEAD = @as(u32, 65807);
pub const OID_GEN_DRIVER_VERSION = @as(u32, 65808);
pub const OID_GEN_MAXIMUM_TOTAL_SIZE = @as(u32, 65809);
pub const OID_GEN_PROTOCOL_OPTIONS = @as(u32, 65810);
pub const OID_GEN_MAC_OPTIONS = @as(u32, 65811);
pub const OID_GEN_MEDIA_CONNECT_STATUS = @as(u32, 65812);
pub const OID_GEN_MAXIMUM_SEND_PACKETS = @as(u32, 65813);
pub const OID_GEN_VENDOR_DRIVER_VERSION = @as(u32, 65814);
pub const OID_GEN_SUPPORTED_GUIDS = @as(u32, 65815);
pub const OID_GEN_NETWORK_LAYER_ADDRESSES = @as(u32, 65816);
pub const OID_GEN_TRANSPORT_HEADER_OFFSET = @as(u32, 65817);
pub const OID_GEN_MEDIA_CAPABILITIES = @as(u32, 66049);
pub const OID_GEN_PHYSICAL_MEDIUM = @as(u32, 66050);
pub const OID_GEN_RECEIVE_SCALE_CAPABILITIES = @as(u32, 66051);
pub const OID_GEN_RECEIVE_SCALE_PARAMETERS = @as(u32, 66052);
pub const OID_GEN_MAC_ADDRESS = @as(u32, 66053);
pub const OID_GEN_MAX_LINK_SPEED = @as(u32, 66054);
pub const OID_GEN_LINK_STATE = @as(u32, 66055);
pub const OID_GEN_LINK_PARAMETERS = @as(u32, 66056);
pub const OID_GEN_INTERRUPT_MODERATION = @as(u32, 66057);
pub const OID_GEN_NDIS_RESERVED_3 = @as(u32, 66058);
pub const OID_GEN_NDIS_RESERVED_4 = @as(u32, 66059);
pub const OID_GEN_NDIS_RESERVED_5 = @as(u32, 66060);
pub const OID_GEN_ENUMERATE_PORTS = @as(u32, 66061);
pub const OID_GEN_PORT_STATE = @as(u32, 66062);
pub const OID_GEN_PORT_AUTHENTICATION_PARAMETERS = @as(u32, 66063);
pub const OID_GEN_TIMEOUT_DPC_REQUEST_CAPABILITIES = @as(u32, 66064);
pub const OID_GEN_PCI_DEVICE_CUSTOM_PROPERTIES = @as(u32, 66065);
pub const OID_GEN_NDIS_RESERVED_6 = @as(u32, 66066);
pub const OID_GEN_PHYSICAL_MEDIUM_EX = @as(u32, 66067);
pub const OID_GEN_RECEIVE_SCALE_PARAMETERS_V2 = @as(u32, 66068);
pub const OID_GEN_MACHINE_NAME = @as(u32, 66074);
pub const OID_GEN_RNDIS_CONFIG_PARAMETER = @as(u32, 66075);
pub const OID_GEN_VLAN_ID = @as(u32, 66076);
pub const OID_GEN_RECEIVE_HASH = @as(u32, 66079);
pub const OID_GEN_MINIPORT_RESTART_ATTRIBUTES = @as(u32, 66077);
pub const OID_GEN_HD_SPLIT_PARAMETERS = @as(u32, 66078);
pub const OID_GEN_HD_SPLIT_CURRENT_CONFIG = @as(u32, 66080);
pub const OID_GEN_PROMISCUOUS_MODE = @as(u32, 66176);
pub const OID_GEN_LAST_CHANGE = @as(u32, 66177);
pub const OID_GEN_DISCONTINUITY_TIME = @as(u32, 66178);
pub const OID_GEN_OPERATIONAL_STATUS = @as(u32, 66179);
pub const OID_GEN_XMIT_LINK_SPEED = @as(u32, 66180);
pub const OID_GEN_RCV_LINK_SPEED = @as(u32, 66181);
pub const OID_GEN_UNKNOWN_PROTOS = @as(u32, 66182);
pub const OID_GEN_INTERFACE_INFO = @as(u32, 66183);
pub const OID_GEN_ADMIN_STATUS = @as(u32, 66184);
pub const OID_GEN_ALIAS = @as(u32, 66185);
pub const OID_GEN_MEDIA_CONNECT_STATUS_EX = @as(u32, 66186);
pub const OID_GEN_LINK_SPEED_EX = @as(u32, 66187);
pub const OID_GEN_MEDIA_DUPLEX_STATE = @as(u32, 66188);
pub const OID_GEN_IP_OPER_STATUS = @as(u32, 66189);
pub const OID_WWAN_DRIVER_CAPS = @as(u32, 234946816);
pub const OID_WWAN_DEVICE_CAPS = @as(u32, 234946817);
pub const OID_WWAN_READY_INFO = @as(u32, 234946818);
pub const OID_WWAN_RADIO_STATE = @as(u32, 234946819);
pub const OID_WWAN_PIN = @as(u32, 234946820);
pub const OID_WWAN_PIN_LIST = @as(u32, 234946821);
pub const OID_WWAN_HOME_PROVIDER = @as(u32, 234946822);
pub const OID_WWAN_PREFERRED_PROVIDERS = @as(u32, 234946823);
pub const OID_WWAN_VISIBLE_PROVIDERS = @as(u32, 234946824);
pub const OID_WWAN_REGISTER_STATE = @as(u32, 234946825);
pub const OID_WWAN_PACKET_SERVICE = @as(u32, 234946826);
pub const OID_WWAN_SIGNAL_STATE = @as(u32, 234946827);
pub const OID_WWAN_CONNECT = @as(u32, 234946828);
pub const OID_WWAN_PROVISIONED_CONTEXTS = @as(u32, 234946829);
pub const OID_WWAN_SERVICE_ACTIVATION = @as(u32, 234946830);
pub const OID_WWAN_SMS_CONFIGURATION = @as(u32, 234946831);
pub const OID_WWAN_SMS_READ = @as(u32, 234946832);
pub const OID_WWAN_SMS_SEND = @as(u32, 234946833);
pub const OID_WWAN_SMS_DELETE = @as(u32, 234946834);
pub const OID_WWAN_SMS_STATUS = @as(u32, 234946835);
pub const OID_WWAN_VENDOR_SPECIFIC = @as(u32, 234946836);
pub const OID_WWAN_AUTH_CHALLENGE = @as(u32, 234946837);
pub const OID_WWAN_ENUMERATE_DEVICE_SERVICES = @as(u32, 234946838);
pub const OID_WWAN_SUBSCRIBE_DEVICE_SERVICE_EVENTS = @as(u32, 234946839);
pub const OID_WWAN_DEVICE_SERVICE_COMMAND = @as(u32, 234946840);
pub const OID_WWAN_USSD = @as(u32, 234946841);
pub const OID_WWAN_PIN_EX = @as(u32, 234946849);
pub const OID_WWAN_ENUMERATE_DEVICE_SERVICE_COMMANDS = @as(u32, 234946850);
pub const OID_WWAN_DEVICE_SERVICE_SESSION = @as(u32, 234946851);
pub const OID_WWAN_DEVICE_SERVICE_SESSION_WRITE = @as(u32, 234946852);
pub const OID_WWAN_PREFERRED_MULTICARRIER_PROVIDERS = @as(u32, 234946853);
pub const OID_WWAN_CREATE_MAC = @as(u32, 234946854);
pub const OID_WWAN_DELETE_MAC = @as(u32, 234946855);
pub const OID_WWAN_UICC_FILE_STATUS = @as(u32, 234946856);
pub const OID_WWAN_UICC_ACCESS_BINARY = @as(u32, 234946857);
pub const OID_WWAN_UICC_ACCESS_RECORD = @as(u32, 234946858);
pub const OID_WWAN_PIN_EX2 = @as(u32, 234946859);
pub const OID_WWAN_MBIM_VERSION = @as(u32, 234946860);
pub const OID_WWAN_SYS_CAPS = @as(u32, 234946861);
pub const OID_WWAN_DEVICE_CAPS_EX = @as(u32, 234946862);
pub const OID_WWAN_SYS_SLOTMAPPINGS = @as(u32, 234946863);
pub const OID_WWAN_SLOT_INFO_STATUS = @as(u32, 234946864);
pub const OID_WWAN_DEVICE_BINDINGS = @as(u32, 234946865);
pub const OID_WWAN_REGISTER_STATE_EX = @as(u32, 234946866);
pub const OID_WWAN_IMS_VOICE_STATE = @as(u32, 234946867);
pub const OID_WWAN_SIGNAL_STATE_EX = @as(u32, 234946868);
pub const OID_WWAN_LOCATION_STATE = @as(u32, 234946869);
pub const OID_WWAN_NITZ = @as(u32, 234946870);
pub const OID_WWAN_NETWORK_IDLE_HINT = @as(u32, 234946871);
pub const OID_WWAN_PRESHUTDOWN = @as(u32, 234946872);
pub const OID_WWAN_UICC_ATR = @as(u32, 234946873);
pub const OID_WWAN_UICC_OPEN_CHANNEL = @as(u32, 234946874);
pub const OID_WWAN_UICC_CLOSE_CHANNEL = @as(u32, 234946875);
pub const OID_WWAN_UICC_APDU = @as(u32, 234946876);
pub const OID_WWAN_UICC_TERMINAL_CAPABILITY = @as(u32, 234946877);
pub const OID_WWAN_PS_MEDIA_CONFIG = @as(u32, 234946878);
pub const OID_WWAN_SAR_CONFIG = @as(u32, 234946879);
pub const OID_WWAN_SAR_TRANSMISSION_STATUS = @as(u32, 234946880);
pub const OID_WWAN_NETWORK_BLACKLIST = @as(u32, 234946881);
pub const OID_WWAN_LTE_ATTACH_CONFIG = @as(u32, 234946882);
pub const OID_WWAN_LTE_ATTACH_STATUS = @as(u32, 234946883);
pub const OID_WWAN_MODEM_CONFIG_INFO = @as(u32, 234946884);
pub const OID_WWAN_PCO = @as(u32, 234946885);
pub const OID_WWAN_UICC_RESET = @as(u32, 234946886);
pub const OID_WWAN_DEVICE_RESET = @as(u32, 234946887);
pub const OID_WWAN_BASE_STATIONS_INFO = @as(u32, 234946888);
pub const OID_WWAN_MPDP = @as(u32, 234946889);
pub const OID_WWAN_UICC_APP_LIST = @as(u32, 234946890);
pub const OID_WWAN_MODEM_LOGGING_CONFIG = @as(u32, 234946891);
pub const OID_WWAN_REGISTER_PARAMS = @as(u32, 234946892);
pub const OID_WWAN_NETWORK_PARAMS = @as(u32, 234946893);
pub const OID_GEN_XMIT_OK = @as(u32, 131329);
pub const OID_GEN_RCV_OK = @as(u32, 131330);
pub const OID_GEN_XMIT_ERROR = @as(u32, 131331);
pub const OID_GEN_RCV_ERROR = @as(u32, 131332);
pub const OID_GEN_RCV_NO_BUFFER = @as(u32, 131333);
pub const OID_GEN_STATISTICS = @as(u32, 131334);
pub const OID_GEN_DIRECTED_BYTES_XMIT = @as(u32, 131585);
pub const OID_GEN_DIRECTED_FRAMES_XMIT = @as(u32, 131586);
pub const OID_GEN_MULTICAST_BYTES_XMIT = @as(u32, 131587);
pub const OID_GEN_MULTICAST_FRAMES_XMIT = @as(u32, 131588);
pub const OID_GEN_BROADCAST_BYTES_XMIT = @as(u32, 131589);
pub const OID_GEN_BROADCAST_FRAMES_XMIT = @as(u32, 131590);
pub const OID_GEN_DIRECTED_BYTES_RCV = @as(u32, 131591);
pub const OID_GEN_DIRECTED_FRAMES_RCV = @as(u32, 131592);
pub const OID_GEN_MULTICAST_BYTES_RCV = @as(u32, 131593);
pub const OID_GEN_MULTICAST_FRAMES_RCV = @as(u32, 131594);
pub const OID_GEN_BROADCAST_BYTES_RCV = @as(u32, 131595);
pub const OID_GEN_BROADCAST_FRAMES_RCV = @as(u32, 131596);
pub const OID_GEN_RCV_CRC_ERROR = @as(u32, 131597);
pub const OID_GEN_TRANSMIT_QUEUE_LENGTH = @as(u32, 131598);
pub const OID_GEN_GET_TIME_CAPS = @as(u32, 131599);
pub const OID_GEN_GET_NETCARD_TIME = @as(u32, 131600);
pub const OID_GEN_NETCARD_LOAD = @as(u32, 131601);
pub const OID_GEN_DEVICE_PROFILE = @as(u32, 131602);
pub const OID_GEN_INIT_TIME_MS = @as(u32, 131603);
pub const OID_GEN_RESET_COUNTS = @as(u32, 131604);
pub const OID_GEN_MEDIA_SENSE_COUNTS = @as(u32, 131605);
pub const OID_GEN_FRIENDLY_NAME = @as(u32, 131606);
pub const OID_GEN_NDIS_RESERVED_1 = @as(u32, 131607);
pub const OID_GEN_NDIS_RESERVED_2 = @as(u32, 131608);
pub const OID_GEN_BYTES_RCV = @as(u32, 131609);
pub const OID_GEN_BYTES_XMIT = @as(u32, 131610);
pub const OID_GEN_RCV_DISCARDS = @as(u32, 131611);
pub const OID_GEN_XMIT_DISCARDS = @as(u32, 131612);
pub const OID_TCP_RSC_STATISTICS = @as(u32, 131613);
pub const OID_GEN_NDIS_RESERVED_7 = @as(u32, 131614);
pub const OID_GEN_CO_SUPPORTED_LIST = @as(u32, 65793);
pub const OID_GEN_CO_HARDWARE_STATUS = @as(u32, 65794);
pub const OID_GEN_CO_MEDIA_SUPPORTED = @as(u32, 65795);
pub const OID_GEN_CO_MEDIA_IN_USE = @as(u32, 65796);
pub const OID_GEN_CO_LINK_SPEED = @as(u32, 65799);
pub const OID_GEN_CO_VENDOR_ID = @as(u32, 65804);
pub const OID_GEN_CO_VENDOR_DESCRIPTION = @as(u32, 65805);
pub const OID_GEN_CO_DRIVER_VERSION = @as(u32, 65808);
pub const OID_GEN_CO_PROTOCOL_OPTIONS = @as(u32, 65810);
pub const OID_GEN_CO_MAC_OPTIONS = @as(u32, 65811);
pub const OID_GEN_CO_MEDIA_CONNECT_STATUS = @as(u32, 65812);
pub const OID_GEN_CO_VENDOR_DRIVER_VERSION = @as(u32, 65814);
pub const OID_GEN_CO_SUPPORTED_GUIDS = @as(u32, 65815);
pub const OID_GEN_CO_GET_TIME_CAPS = @as(u32, 131599);
pub const OID_GEN_CO_GET_NETCARD_TIME = @as(u32, 131600);
pub const OID_GEN_CO_MINIMUM_LINK_SPEED = @as(u32, 131360);
pub const OID_GEN_CO_XMIT_PDUS_OK = @as(u32, 131329);
pub const OID_GEN_CO_RCV_PDUS_OK = @as(u32, 131330);
pub const OID_GEN_CO_XMIT_PDUS_ERROR = @as(u32, 131331);
pub const OID_GEN_CO_RCV_PDUS_ERROR = @as(u32, 131332);
pub const OID_GEN_CO_RCV_PDUS_NO_BUFFER = @as(u32, 131333);
pub const OID_GEN_CO_RCV_CRC_ERROR = @as(u32, 131597);
pub const OID_GEN_CO_TRANSMIT_QUEUE_LENGTH = @as(u32, 131598);
pub const OID_GEN_CO_BYTES_XMIT = @as(u32, 131585);
pub const OID_GEN_CO_BYTES_RCV = @as(u32, 131591);
pub const OID_GEN_CO_NETCARD_LOAD = @as(u32, 131601);
pub const OID_GEN_CO_DEVICE_PROFILE = @as(u32, 131602);
pub const OID_GEN_CO_BYTES_XMIT_OUTSTANDING = @as(u32, 131617);
pub const OID_KDNET_ENUMERATE_PFS = @as(u32, 131618);
pub const OID_KDNET_ADD_PF = @as(u32, 131619);
pub const OID_KDNET_REMOVE_PF = @as(u32, 131620);
pub const OID_KDNET_QUERY_PF_INFORMATION = @as(u32, 131621);
pub const OID_802_3_PERMANENT_ADDRESS = @as(u32, 16843009);
pub const OID_802_3_CURRENT_ADDRESS = @as(u32, 16843010);
pub const OID_802_3_MULTICAST_LIST = @as(u32, 16843011);
pub const OID_802_3_MAXIMUM_LIST_SIZE = @as(u32, 16843012);
pub const OID_802_3_MAC_OPTIONS = @as(u32, 16843013);
pub const NDIS_802_3_MAC_OPTION_PRIORITY = @as(u32, 1);
pub const OID_802_3_RCV_ERROR_ALIGNMENT = @as(u32, 16908545);
pub const OID_802_3_XMIT_ONE_COLLISION = @as(u32, 16908546);
pub const OID_802_3_XMIT_MORE_COLLISIONS = @as(u32, 16908547);
pub const OID_802_3_XMIT_DEFERRED = @as(u32, 16908801);
pub const OID_802_3_XMIT_MAX_COLLISIONS = @as(u32, 16908802);
pub const OID_802_3_RCV_OVERRUN = @as(u32, 16908803);
pub const OID_802_3_XMIT_UNDERRUN = @as(u32, 16908804);
pub const OID_802_3_XMIT_HEARTBEAT_FAILURE = @as(u32, 16908805);
pub const OID_802_3_XMIT_TIMES_CRS_LOST = @as(u32, 16908806);
pub const OID_802_3_XMIT_LATE_COLLISIONS = @as(u32, 16908807);
pub const OID_802_3_ADD_MULTICAST_ADDRESS = @as(u32, 16843272);
pub const OID_802_3_DELETE_MULTICAST_ADDRESS = @as(u32, 16843273);
pub const OID_802_5_PERMANENT_ADDRESS = @as(u32, 33620225);
pub const OID_802_5_CURRENT_ADDRESS = @as(u32, 33620226);
pub const OID_802_5_CURRENT_FUNCTIONAL = @as(u32, 33620227);
pub const OID_802_5_CURRENT_GROUP = @as(u32, 33620228);
pub const OID_802_5_LAST_OPEN_STATUS = @as(u32, 33620229);
pub const OID_802_5_CURRENT_RING_STATUS = @as(u32, 33620230);
pub const OID_802_5_CURRENT_RING_STATE = @as(u32, 33620231);
pub const OID_802_5_LINE_ERRORS = @as(u32, 33685761);
pub const OID_802_5_LOST_FRAMES = @as(u32, 33685762);
pub const OID_802_5_BURST_ERRORS = @as(u32, 33686017);
pub const OID_802_5_AC_ERRORS = @as(u32, 33686018);
pub const OID_802_5_ABORT_DELIMETERS = @as(u32, 33686019);
pub const OID_802_5_FRAME_COPIED_ERRORS = @as(u32, 33686020);
pub const OID_802_5_FREQUENCY_ERRORS = @as(u32, 33686021);
pub const OID_802_5_TOKEN_ERRORS = @as(u32, 33686022);
pub const OID_802_5_INTERNAL_ERRORS = @as(u32, 33686023);
pub const OID_FDDI_LONG_PERMANENT_ADDR = @as(u32, 50397441);
pub const OID_FDDI_LONG_CURRENT_ADDR = @as(u32, 50397442);
pub const OID_FDDI_LONG_MULTICAST_LIST = @as(u32, 50397443);
pub const OID_FDDI_LONG_MAX_LIST_SIZE = @as(u32, 50397444);
pub const OID_FDDI_SHORT_PERMANENT_ADDR = @as(u32, 50397445);
pub const OID_FDDI_SHORT_CURRENT_ADDR = @as(u32, 50397446);
pub const OID_FDDI_SHORT_MULTICAST_LIST = @as(u32, 50397447);
pub const OID_FDDI_SHORT_MAX_LIST_SIZE = @as(u32, 50397448);
pub const OID_FDDI_ATTACHMENT_TYPE = @as(u32, 50462977);
pub const OID_FDDI_UPSTREAM_NODE_LONG = @as(u32, 50462978);
pub const OID_FDDI_DOWNSTREAM_NODE_LONG = @as(u32, 50462979);
pub const OID_FDDI_FRAME_ERRORS = @as(u32, 50462980);
pub const OID_FDDI_FRAMES_LOST = @as(u32, 50462981);
pub const OID_FDDI_RING_MGT_STATE = @as(u32, 50462982);
pub const OID_FDDI_LCT_FAILURES = @as(u32, 50462983);
pub const OID_FDDI_LEM_REJECTS = @as(u32, 50462984);
pub const OID_FDDI_LCONNECTION_STATE = @as(u32, 50462985);
pub const OID_FDDI_SMT_STATION_ID = @as(u32, 50528769);
pub const OID_FDDI_SMT_OP_VERSION_ID = @as(u32, 50528770);
pub const OID_FDDI_SMT_HI_VERSION_ID = @as(u32, 50528771);
pub const OID_FDDI_SMT_LO_VERSION_ID = @as(u32, 50528772);
pub const OID_FDDI_SMT_MANUFACTURER_DATA = @as(u32, 50528773);
pub const OID_FDDI_SMT_USER_DATA = @as(u32, 50528774);
pub const OID_FDDI_SMT_MIB_VERSION_ID = @as(u32, 50528775);
pub const OID_FDDI_SMT_MAC_CT = @as(u32, 50528776);
pub const OID_FDDI_SMT_NON_MASTER_CT = @as(u32, 50528777);
pub const OID_FDDI_SMT_MASTER_CT = @as(u32, 50528778);
pub const OID_FDDI_SMT_AVAILABLE_PATHS = @as(u32, 50528779);
pub const OID_FDDI_SMT_CONFIG_CAPABILITIES = @as(u32, 50528780);
pub const OID_FDDI_SMT_CONFIG_POLICY = @as(u32, 50528781);
pub const OID_FDDI_SMT_CONNECTION_POLICY = @as(u32, 50528782);
pub const OID_FDDI_SMT_T_NOTIFY = @as(u32, 50528783);
pub const OID_FDDI_SMT_STAT_RPT_POLICY = @as(u32, 50528784);
pub const OID_FDDI_SMT_TRACE_MAX_EXPIRATION = @as(u32, 50528785);
pub const OID_FDDI_SMT_PORT_INDEXES = @as(u32, 50528786);
pub const OID_FDDI_SMT_MAC_INDEXES = @as(u32, 50528787);
pub const OID_FDDI_SMT_BYPASS_PRESENT = @as(u32, 50528788);
pub const OID_FDDI_SMT_ECM_STATE = @as(u32, 50528789);
pub const OID_FDDI_SMT_CF_STATE = @as(u32, 50528790);
pub const OID_FDDI_SMT_HOLD_STATE = @as(u32, 50528791);
pub const OID_FDDI_SMT_REMOTE_DISCONNECT_FLAG = @as(u32, 50528792);
pub const OID_FDDI_SMT_STATION_STATUS = @as(u32, 50528793);
pub const OID_FDDI_SMT_PEER_WRAP_FLAG = @as(u32, 50528794);
pub const OID_FDDI_SMT_MSG_TIME_STAMP = @as(u32, 50528795);
pub const OID_FDDI_SMT_TRANSITION_TIME_STAMP = @as(u32, 50528796);
pub const OID_FDDI_SMT_SET_COUNT = @as(u32, 50528797);
pub const OID_FDDI_SMT_LAST_SET_STATION_ID = @as(u32, 50528798);
pub const OID_FDDI_MAC_FRAME_STATUS_FUNCTIONS = @as(u32, 50528799);
pub const OID_FDDI_MAC_BRIDGE_FUNCTIONS = @as(u32, 50528800);
pub const OID_FDDI_MAC_T_MAX_CAPABILITY = @as(u32, 50528801);
pub const OID_FDDI_MAC_TVX_CAPABILITY = @as(u32, 50528802);
pub const OID_FDDI_MAC_AVAILABLE_PATHS = @as(u32, 50528803);
pub const OID_FDDI_MAC_CURRENT_PATH = @as(u32, 50528804);
pub const OID_FDDI_MAC_UPSTREAM_NBR = @as(u32, 50528805);
pub const OID_FDDI_MAC_DOWNSTREAM_NBR = @as(u32, 50528806);
pub const OID_FDDI_MAC_OLD_UPSTREAM_NBR = @as(u32, 50528807);
pub const OID_FDDI_MAC_OLD_DOWNSTREAM_NBR = @as(u32, 50528808);
pub const OID_FDDI_MAC_DUP_ADDRESS_TEST = @as(u32, 50528809);
pub const OID_FDDI_MAC_REQUESTED_PATHS = @as(u32, 50528810);
pub const OID_FDDI_MAC_DOWNSTREAM_PORT_TYPE = @as(u32, 50528811);
pub const OID_FDDI_MAC_INDEX = @as(u32, 50528812);
pub const OID_FDDI_MAC_SMT_ADDRESS = @as(u32, 50528813);
pub const OID_FDDI_MAC_LONG_GRP_ADDRESS = @as(u32, 50528814);
pub const OID_FDDI_MAC_SHORT_GRP_ADDRESS = @as(u32, 50528815);
pub const OID_FDDI_MAC_T_REQ = @as(u32, 50528816);
pub const OID_FDDI_MAC_T_NEG = @as(u32, 50528817);
pub const OID_FDDI_MAC_T_MAX = @as(u32, 50528818);
pub const OID_FDDI_MAC_TVX_VALUE = @as(u32, 50528819);
pub const OID_FDDI_MAC_T_PRI0 = @as(u32, 50528820);
pub const OID_FDDI_MAC_T_PRI1 = @as(u32, 50528821);
pub const OID_FDDI_MAC_T_PRI2 = @as(u32, 50528822);
pub const OID_FDDI_MAC_T_PRI3 = @as(u32, 50528823);
pub const OID_FDDI_MAC_T_PRI4 = @as(u32, 50528824);
pub const OID_FDDI_MAC_T_PRI5 = @as(u32, 50528825);
pub const OID_FDDI_MAC_T_PRI6 = @as(u32, 50528826);
pub const OID_FDDI_MAC_FRAME_CT = @as(u32, 50528827);
pub const OID_FDDI_MAC_COPIED_CT = @as(u32, 50528828);
pub const OID_FDDI_MAC_TRANSMIT_CT = @as(u32, 50528829);
pub const OID_FDDI_MAC_TOKEN_CT = @as(u32, 50528830);
pub const OID_FDDI_MAC_ERROR_CT = @as(u32, 50528831);
pub const OID_FDDI_MAC_LOST_CT = @as(u32, 50528832);
pub const OID_FDDI_MAC_TVX_EXPIRED_CT = @as(u32, 50528833);
pub const OID_FDDI_MAC_NOT_COPIED_CT = @as(u32, 50528834);
pub const OID_FDDI_MAC_LATE_CT = @as(u32, 50528835);
pub const OID_FDDI_MAC_RING_OP_CT = @as(u32, 50528836);
pub const OID_FDDI_MAC_FRAME_ERROR_THRESHOLD = @as(u32, 50528837);
pub const OID_FDDI_MAC_FRAME_ERROR_RATIO = @as(u32, 50528838);
pub const OID_FDDI_MAC_NOT_COPIED_THRESHOLD = @as(u32, 50528839);
pub const OID_FDDI_MAC_NOT_COPIED_RATIO = @as(u32, 50528840);
pub const OID_FDDI_MAC_RMT_STATE = @as(u32, 50528841);
pub const OID_FDDI_MAC_DA_FLAG = @as(u32, 50528842);
pub const OID_FDDI_MAC_UNDA_FLAG = @as(u32, 50528843);
pub const OID_FDDI_MAC_FRAME_ERROR_FLAG = @as(u32, 50528844);
pub const OID_FDDI_MAC_NOT_COPIED_FLAG = @as(u32, 50528845);
pub const OID_FDDI_MAC_MA_UNITDATA_AVAILABLE = @as(u32, 50528846);
pub const OID_FDDI_MAC_HARDWARE_PRESENT = @as(u32, 50528847);
pub const OID_FDDI_MAC_MA_UNITDATA_ENABLE = @as(u32, 50528848);
pub const OID_FDDI_PATH_INDEX = @as(u32, 50528849);
pub const OID_FDDI_PATH_RING_LATENCY = @as(u32, 50528850);
pub const OID_FDDI_PATH_TRACE_STATUS = @as(u32, 50528851);
pub const OID_FDDI_PATH_SBA_PAYLOAD = @as(u32, 50528852);
pub const OID_FDDI_PATH_SBA_OVERHEAD = @as(u32, 50528853);
pub const OID_FDDI_PATH_CONFIGURATION = @as(u32, 50528854);
pub const OID_FDDI_PATH_T_R_MODE = @as(u32, 50528855);
pub const OID_FDDI_PATH_SBA_AVAILABLE = @as(u32, 50528856);
pub const OID_FDDI_PATH_TVX_LOWER_BOUND = @as(u32, 50528857);
pub const OID_FDDI_PATH_T_MAX_LOWER_BOUND = @as(u32, 50528858);
pub const OID_FDDI_PATH_MAX_T_REQ = @as(u32, 50528859);
pub const OID_FDDI_PORT_MY_TYPE = @as(u32, 50528860);
pub const OID_FDDI_PORT_NEIGHBOR_TYPE = @as(u32, 50528861);
pub const OID_FDDI_PORT_CONNECTION_POLICIES = @as(u32, 50528862);
pub const OID_FDDI_PORT_MAC_INDICATED = @as(u32, 50528863);
pub const OID_FDDI_PORT_CURRENT_PATH = @as(u32, 50528864);
pub const OID_FDDI_PORT_REQUESTED_PATHS = @as(u32, 50528865);
pub const OID_FDDI_PORT_MAC_PLACEMENT = @as(u32, 50528866);
pub const OID_FDDI_PORT_AVAILABLE_PATHS = @as(u32, 50528867);
pub const OID_FDDI_PORT_MAC_LOOP_TIME = @as(u32, 50528868);
pub const OID_FDDI_PORT_PMD_CLASS = @as(u32, 50528869);
pub const OID_FDDI_PORT_CONNECTION_CAPABILITIES = @as(u32, 50528870);
pub const OID_FDDI_PORT_INDEX = @as(u32, 50528871);
pub const OID_FDDI_PORT_MAINT_LS = @as(u32, 50528872);
pub const OID_FDDI_PORT_BS_FLAG = @as(u32, 50528873);
pub const OID_FDDI_PORT_PC_LS = @as(u32, 50528874);
pub const OID_FDDI_PORT_EB_ERROR_CT = @as(u32, 50528875);
pub const OID_FDDI_PORT_LCT_FAIL_CT = @as(u32, 50528876);
pub const OID_FDDI_PORT_LER_ESTIMATE = @as(u32, 50528877);
pub const OID_FDDI_PORT_LEM_REJECT_CT = @as(u32, 50528878);
pub const OID_FDDI_PORT_LEM_CT = @as(u32, 50528879);
pub const OID_FDDI_PORT_LER_CUTOFF = @as(u32, 50528880);
pub const OID_FDDI_PORT_LER_ALARM = @as(u32, 50528881);
pub const OID_FDDI_PORT_CONNNECT_STATE = @as(u32, 50528882);
pub const OID_FDDI_PORT_PCM_STATE = @as(u32, 50528883);
pub const OID_FDDI_PORT_PC_WITHHOLD = @as(u32, 50528884);
pub const OID_FDDI_PORT_LER_FLAG = @as(u32, 50528885);
pub const OID_FDDI_PORT_HARDWARE_PRESENT = @as(u32, 50528886);
pub const OID_FDDI_SMT_STATION_ACTION = @as(u32, 50528887);
pub const OID_FDDI_PORT_ACTION = @as(u32, 50528888);
pub const OID_FDDI_IF_DESCR = @as(u32, 50528889);
pub const OID_FDDI_IF_TYPE = @as(u32, 50528890);
pub const OID_FDDI_IF_MTU = @as(u32, 50528891);
pub const OID_FDDI_IF_SPEED = @as(u32, 50528892);
pub const OID_FDDI_IF_PHYS_ADDRESS = @as(u32, 50528893);
pub const OID_FDDI_IF_ADMIN_STATUS = @as(u32, 50528894);
pub const OID_FDDI_IF_OPER_STATUS = @as(u32, 50528895);
pub const OID_FDDI_IF_LAST_CHANGE = @as(u32, 50528896);
pub const OID_FDDI_IF_IN_OCTETS = @as(u32, 50528897);
pub const OID_FDDI_IF_IN_UCAST_PKTS = @as(u32, 50528898);
pub const OID_FDDI_IF_IN_NUCAST_PKTS = @as(u32, 50528899);
pub const OID_FDDI_IF_IN_DISCARDS = @as(u32, 50528900);
pub const OID_FDDI_IF_IN_ERRORS = @as(u32, 50528901);
pub const OID_FDDI_IF_IN_UNKNOWN_PROTOS = @as(u32, 50528902);
pub const OID_FDDI_IF_OUT_OCTETS = @as(u32, 50528903);
pub const OID_FDDI_IF_OUT_UCAST_PKTS = @as(u32, 50528904);
pub const OID_FDDI_IF_OUT_NUCAST_PKTS = @as(u32, 50528905);
pub const OID_FDDI_IF_OUT_DISCARDS = @as(u32, 50528906);
pub const OID_FDDI_IF_OUT_ERRORS = @as(u32, 50528907);
pub const OID_FDDI_IF_OUT_QLEN = @as(u32, 50528908);
pub const OID_FDDI_IF_SPECIFIC = @as(u32, 50528909);
pub const OID_WAN_PERMANENT_ADDRESS = @as(u32, 67174657);
pub const OID_WAN_CURRENT_ADDRESS = @as(u32, 67174658);
pub const OID_WAN_QUALITY_OF_SERVICE = @as(u32, 67174659);
pub const OID_WAN_PROTOCOL_TYPE = @as(u32, 67174660);
pub const OID_WAN_MEDIUM_SUBTYPE = @as(u32, 67174661);
pub const OID_WAN_HEADER_FORMAT = @as(u32, 67174662);
pub const OID_WAN_GET_INFO = @as(u32, 67174663);
pub const OID_WAN_SET_LINK_INFO = @as(u32, 67174664);
pub const OID_WAN_GET_LINK_INFO = @as(u32, 67174665);
pub const OID_WAN_LINE_COUNT = @as(u32, 67174666);
pub const OID_WAN_PROTOCOL_CAPS = @as(u32, 67174667);
pub const OID_WAN_GET_BRIDGE_INFO = @as(u32, 67174922);
pub const OID_WAN_SET_BRIDGE_INFO = @as(u32, 67174923);
pub const OID_WAN_GET_COMP_INFO = @as(u32, 67174924);
pub const OID_WAN_SET_COMP_INFO = @as(u32, 67174925);
pub const OID_WAN_GET_STATS_INFO = @as(u32, 67174926);
pub const OID_WAN_CO_GET_INFO = @as(u32, 67174784);
pub const OID_WAN_CO_SET_LINK_INFO = @as(u32, 67174785);
pub const OID_WAN_CO_GET_LINK_INFO = @as(u32, 67174786);
pub const OID_WAN_CO_GET_COMP_INFO = @as(u32, 67175040);
pub const OID_WAN_CO_SET_COMP_INFO = @as(u32, 67175041);
pub const OID_WAN_CO_GET_STATS_INFO = @as(u32, 67175042);
pub const OID_LTALK_CURRENT_NODE_ID = @as(u32, 83951874);
pub const OID_LTALK_IN_BROADCASTS = @as(u32, 84017409);
pub const OID_LTALK_IN_LENGTH_ERRORS = @as(u32, 84017410);
pub const OID_LTALK_OUT_NO_HANDLERS = @as(u32, 84017665);
pub const OID_LTALK_COLLISIONS = @as(u32, 84017666);
pub const OID_LTALK_DEFERS = @as(u32, 84017667);
pub const OID_LTALK_NO_DATA_ERRORS = @as(u32, 84017668);
pub const OID_LTALK_RANDOM_CTS_ERRORS = @as(u32, 84017669);
pub const OID_LTALK_FCS_ERRORS = @as(u32, 84017670);
pub const OID_ARCNET_PERMANENT_ADDRESS = @as(u32, 100729089);
pub const OID_ARCNET_CURRENT_ADDRESS = @as(u32, 100729090);
pub const OID_ARCNET_RECONFIGURATIONS = @as(u32, 100794881);
pub const OID_TAPI_ACCEPT = @as(u32, 117637377);
pub const OID_TAPI_ANSWER = @as(u32, 117637378);
pub const OID_TAPI_CLOSE = @as(u32, 117637379);
pub const OID_TAPI_CLOSE_CALL = @as(u32, 117637380);
pub const OID_TAPI_CONDITIONAL_MEDIA_DETECTION = @as(u32, 117637381);
pub const OID_TAPI_CONFIG_DIALOG = @as(u32, 117637382);
pub const OID_TAPI_DEV_SPECIFIC = @as(u32, 117637383);
pub const OID_TAPI_DIAL = @as(u32, 117637384);
pub const OID_TAPI_DROP = @as(u32, 117637385);
pub const OID_TAPI_GET_ADDRESS_CAPS = @as(u32, 117637386);
pub const OID_TAPI_GET_ADDRESS_ID = @as(u32, 117637387);
pub const OID_TAPI_GET_ADDRESS_STATUS = @as(u32, 117637388);
pub const OID_TAPI_GET_CALL_ADDRESS_ID = @as(u32, 117637389);
pub const OID_TAPI_GET_CALL_INFO = @as(u32, 117637390);
pub const OID_TAPI_GET_CALL_STATUS = @as(u32, 117637391);
pub const OID_TAPI_GET_DEV_CAPS = @as(u32, 117637392);
pub const OID_TAPI_GET_DEV_CONFIG = @as(u32, 117637393);
pub const OID_TAPI_GET_EXTENSION_ID = @as(u32, 117637394);
pub const OID_TAPI_GET_ID = @as(u32, 117637395);
pub const OID_TAPI_GET_LINE_DEV_STATUS = @as(u32, 117637396);
pub const OID_TAPI_MAKE_CALL = @as(u32, 117637397);
pub const OID_TAPI_NEGOTIATE_EXT_VERSION = @as(u32, 117637398);
pub const OID_TAPI_OPEN = @as(u32, 117637399);
pub const OID_TAPI_PROVIDER_INITIALIZE = @as(u32, 117637400);
pub const OID_TAPI_PROVIDER_SHUTDOWN = @as(u32, 117637401);
pub const OID_TAPI_SECURE_CALL = @as(u32, 117637402);
pub const OID_TAPI_SELECT_EXT_VERSION = @as(u32, 117637403);
pub const OID_TAPI_SEND_USER_USER_INFO = @as(u32, 117637404);
pub const OID_TAPI_SET_APP_SPECIFIC = @as(u32, 117637405);
pub const OID_TAPI_SET_CALL_PARAMS = @as(u32, 117637406);
pub const OID_TAPI_SET_DEFAULT_MEDIA_DETECTION = @as(u32, 117637407);
pub const OID_TAPI_SET_DEV_CONFIG = @as(u32, 117637408);
pub const OID_TAPI_SET_MEDIA_MODE = @as(u32, 117637409);
pub const OID_TAPI_SET_STATUS_MESSAGES = @as(u32, 117637410);
pub const OID_TAPI_GATHER_DIGITS = @as(u32, 117637411);
pub const OID_TAPI_MONITOR_DIGITS = @as(u32, 117637412);
pub const OID_ATM_SUPPORTED_VC_RATES = @as(u32, 134283521);
pub const OID_ATM_SUPPORTED_SERVICE_CATEGORY = @as(u32, 134283522);
pub const OID_ATM_SUPPORTED_AAL_TYPES = @as(u32, 134283523);
pub const OID_ATM_HW_CURRENT_ADDRESS = @as(u32, 134283524);
pub const OID_ATM_MAX_ACTIVE_VCS = @as(u32, 134283525);
pub const OID_ATM_MAX_ACTIVE_VCI_BITS = @as(u32, 134283526);
pub const OID_ATM_MAX_ACTIVE_VPI_BITS = @as(u32, 134283527);
pub const OID_ATM_MAX_AAL0_PACKET_SIZE = @as(u32, 134283528);
pub const OID_ATM_MAX_AAL1_PACKET_SIZE = @as(u32, 134283529);
pub const OID_ATM_MAX_AAL34_PACKET_SIZE = @as(u32, 134283530);
pub const OID_ATM_MAX_AAL5_PACKET_SIZE = @as(u32, 134283531);
pub const OID_ATM_SIGNALING_VPIVCI = @as(u32, 134283777);
pub const OID_ATM_ASSIGNED_VPI = @as(u32, 134283778);
pub const OID_ATM_ACQUIRE_ACCESS_NET_RESOURCES = @as(u32, 134283779);
pub const OID_ATM_RELEASE_ACCESS_NET_RESOURCES = @as(u32, 134283780);
pub const OID_ATM_ILMI_VPIVCI = @as(u32, 134283781);
pub const OID_ATM_DIGITAL_BROADCAST_VPIVCI = @as(u32, 134283782);
pub const OID_ATM_GET_NEAREST_FLOW = @as(u32, 134283783);
pub const OID_ATM_ALIGNMENT_REQUIRED = @as(u32, 134283784);
pub const OID_ATM_LECS_ADDRESS = @as(u32, 134283785);
pub const OID_ATM_SERVICE_ADDRESS = @as(u32, 134283786);
pub const OID_ATM_CALL_PROCEEDING = @as(u32, 134283787);
pub const OID_ATM_CALL_ALERTING = @as(u32, 134283788);
pub const OID_ATM_PARTY_ALERTING = @as(u32, 134283789);
pub const OID_ATM_CALL_NOTIFY = @as(u32, 134283790);
pub const OID_ATM_MY_IP_NM_ADDRESS = @as(u32, 134283791);
pub const OID_ATM_RCV_CELLS_OK = @as(u32, 134349057);
pub const OID_ATM_XMIT_CELLS_OK = @as(u32, 134349058);
pub const OID_ATM_RCV_CELLS_DROPPED = @as(u32, 134349059);
pub const OID_ATM_RCV_INVALID_VPI_VCI = @as(u32, 134349313);
pub const OID_ATM_CELLS_HEC_ERROR = @as(u32, 134349314);
pub const OID_ATM_RCV_REASSEMBLY_ERROR = @as(u32, 134349315);
pub const OID_802_11_BSSID = @as(u32, 218169601);
pub const OID_802_11_SSID = @as(u32, 218169602);
pub const OID_802_11_NETWORK_TYPES_SUPPORTED = @as(u32, 218169859);
pub const OID_802_11_NETWORK_TYPE_IN_USE = @as(u32, 218169860);
pub const OID_802_11_TX_POWER_LEVEL = @as(u32, 218169861);
pub const OID_802_11_RSSI = @as(u32, 218169862);
pub const OID_802_11_RSSI_TRIGGER = @as(u32, 218169863);
pub const OID_802_11_INFRASTRUCTURE_MODE = @as(u32, 218169608);
pub const OID_802_11_FRAGMENTATION_THRESHOLD = @as(u32, 218169865);
pub const OID_802_11_RTS_THRESHOLD = @as(u32, 218169866);
pub const OID_802_11_NUMBER_OF_ANTENNAS = @as(u32, 218169867);
pub const OID_802_11_RX_ANTENNA_SELECTED = @as(u32, 218169868);
pub const OID_802_11_TX_ANTENNA_SELECTED = @as(u32, 218169869);
pub const OID_802_11_SUPPORTED_RATES = @as(u32, 218169870);
pub const OID_802_11_DESIRED_RATES = @as(u32, 218169872);
pub const OID_802_11_CONFIGURATION = @as(u32, 218169873);
pub const OID_802_11_STATISTICS = @as(u32, 218235410);
pub const OID_802_11_ADD_WEP = @as(u32, 218169619);
pub const OID_802_11_REMOVE_WEP = @as(u32, 218169620);
pub const OID_802_11_DISASSOCIATE = @as(u32, 218169621);
pub const OID_802_11_POWER_MODE = @as(u32, 218169878);
pub const OID_802_11_BSSID_LIST = @as(u32, 218169879);
pub const OID_802_11_AUTHENTICATION_MODE = @as(u32, 218169624);
pub const OID_802_11_PRIVACY_FILTER = @as(u32, 218169625);
pub const OID_802_11_BSSID_LIST_SCAN = @as(u32, 218169626);
pub const OID_802_11_WEP_STATUS = @as(u32, 218169627);
pub const OID_802_11_ENCRYPTION_STATUS = @as(u32, 218169627);
pub const OID_802_11_RELOAD_DEFAULTS = @as(u32, 218169628);
pub const OID_802_11_ADD_KEY = @as(u32, 218169629);
pub const OID_802_11_REMOVE_KEY = @as(u32, 218169630);
pub const OID_802_11_ASSOCIATION_INFORMATION = @as(u32, 218169631);
pub const OID_802_11_TEST = @as(u32, 218169632);
pub const OID_802_11_MEDIA_STREAM_MODE = @as(u32, 218169633);
pub const OID_802_11_CAPABILITY = @as(u32, 218169634);
pub const OID_802_11_PMKID = @as(u32, 218169635);
pub const OID_802_11_NON_BCAST_SSID_LIST = @as(u32, 218169636);
pub const OID_802_11_RADIO_STATUS = @as(u32, 218169637);
pub const NDIS_ETH_TYPE_IPV4 = @as(u32, 2048);
pub const NDIS_ETH_TYPE_ARP = @as(u32, 2054);
pub const NDIS_ETH_TYPE_IPV6 = @as(u32, 34525);
pub const NDIS_ETH_TYPE_802_1X = @as(u32, 34958);
pub const NDIS_ETH_TYPE_802_1Q = @as(u32, 33024);
pub const NDIS_ETH_TYPE_SLOW_PROTOCOL = @as(u32, 34825);
pub const NDIS_802_11_LENGTH_SSID = @as(u32, 32);
pub const NDIS_802_11_LENGTH_RATES = @as(u32, 8);
pub const NDIS_802_11_LENGTH_RATES_EX = @as(u32, 16);
pub const NDIS_802_11_AUTH_REQUEST_AUTH_FIELDS = @as(u32, 15);
pub const NDIS_802_11_AUTH_REQUEST_REAUTH = @as(u32, 1);
pub const NDIS_802_11_AUTH_REQUEST_KEYUPDATE = @as(u32, 2);
pub const NDIS_802_11_AUTH_REQUEST_PAIRWISE_ERROR = @as(u32, 6);
pub const NDIS_802_11_AUTH_REQUEST_GROUP_ERROR = @as(u32, 14);
pub const NDIS_802_11_PMKID_CANDIDATE_PREAUTH_ENABLED = @as(u32, 1);
pub const NDIS_802_11_AI_REQFI_CAPABILITIES = @as(u32, 1);
pub const NDIS_802_11_AI_REQFI_LISTENINTERVAL = @as(u32, 2);
pub const NDIS_802_11_AI_REQFI_CURRENTAPADDRESS = @as(u32, 4);
pub const NDIS_802_11_AI_RESFI_CAPABILITIES = @as(u32, 1);
pub const NDIS_802_11_AI_RESFI_STATUSCODE = @as(u32, 2);
pub const NDIS_802_11_AI_RESFI_ASSOCIATIONID = @as(u32, 4);
pub const OID_IRDA_RECEIVING = @as(u32, 167837952);
pub const OID_IRDA_TURNAROUND_TIME = @as(u32, 167837953);
pub const OID_IRDA_SUPPORTED_SPEEDS = @as(u32, 167837954);
pub const OID_IRDA_LINK_SPEED = @as(u32, 167837955);
pub const OID_IRDA_MEDIA_BUSY = @as(u32, 167837956);
pub const OID_IRDA_EXTRA_RCV_BOFS = @as(u32, 167838208);
pub const OID_IRDA_RATE_SNIFF = @as(u32, 167838209);
pub const OID_IRDA_UNICAST_LIST = @as(u32, 167838210);
pub const OID_IRDA_MAX_UNICAST_LIST_SIZE = @as(u32, 167838211);
pub const OID_IRDA_MAX_RECEIVE_WINDOW_SIZE = @as(u32, 167838212);
pub const OID_IRDA_MAX_SEND_WINDOW_SIZE = @as(u32, 167838213);
pub const OID_IRDA_RESERVED1 = @as(u32, 167838218);
pub const OID_IRDA_RESERVED2 = @as(u32, 167838223);
pub const OID_1394_LOCAL_NODE_INFO = @as(u32, 201392385);
pub const OID_1394_VC_INFO = @as(u32, 201392386);
pub const OID_CO_ADD_PVC = @as(u32, 4261412865);
pub const OID_CO_DELETE_PVC = @as(u32, 4261412866);
pub const OID_CO_GET_CALL_INFORMATION = @as(u32, 4261412867);
pub const OID_CO_ADD_ADDRESS = @as(u32, 4261412868);
pub const OID_CO_DELETE_ADDRESS = @as(u32, 4261412869);
pub const OID_CO_GET_ADDRESSES = @as(u32, 4261412870);
pub const OID_CO_ADDRESS_CHANGE = @as(u32, 4261412871);
pub const OID_CO_SIGNALING_ENABLED = @as(u32, 4261412872);
pub const OID_CO_SIGNALING_DISABLED = @as(u32, 4261412873);
pub const OID_CO_AF_CLOSE = @as(u32, 4261412874);
pub const OID_CO_TAPI_CM_CAPS = @as(u32, 4261416961);
pub const OID_CO_TAPI_LINE_CAPS = @as(u32, 4261416962);
pub const OID_CO_TAPI_ADDRESS_CAPS = @as(u32, 4261416963);
pub const OID_CO_TAPI_TRANSLATE_TAPI_CALLPARAMS = @as(u32, 4261416964);
pub const OID_CO_TAPI_TRANSLATE_NDIS_CALLPARAMS = @as(u32, 4261416965);
pub const OID_CO_TAPI_TRANSLATE_TAPI_SAP = @as(u32, 4261416966);
pub const OID_CO_TAPI_GET_CALL_DIAGNOSTICS = @as(u32, 4261416967);
pub const OID_CO_TAPI_REPORT_DIGITS = @as(u32, 4261416968);
pub const OID_CO_TAPI_DONT_REPORT_DIGITS = @as(u32, 4261416969);
pub const OID_PNP_CAPABILITIES = @as(u32, 4244701440);
pub const OID_PNP_SET_POWER = @as(u32, 4244701441);
pub const OID_PNP_QUERY_POWER = @as(u32, 4244701442);
pub const OID_PNP_ADD_WAKE_UP_PATTERN = @as(u32, 4244701443);
pub const OID_PNP_REMOVE_WAKE_UP_PATTERN = @as(u32, 4244701444);
pub const OID_PNP_WAKE_UP_PATTERN_LIST = @as(u32, 4244701445);
pub const OID_PNP_ENABLE_WAKE_UP = @as(u32, 4244701446);
pub const OID_PNP_WAKE_UP_OK = @as(u32, 4244767232);
pub const OID_PNP_WAKE_UP_ERROR = @as(u32, 4244767233);
pub const OID_PM_CURRENT_CAPABILITIES = @as(u32, 4244701447);
pub const OID_PM_HARDWARE_CAPABILITIES = @as(u32, 4244701448);
pub const OID_PM_PARAMETERS = @as(u32, 4244701449);
pub const OID_PM_ADD_WOL_PATTERN = @as(u32, 4244701450);
pub const OID_PM_REMOVE_WOL_PATTERN = @as(u32, 4244701451);
pub const OID_PM_WOL_PATTERN_LIST = @as(u32, 4244701452);
pub const OID_PM_ADD_PROTOCOL_OFFLOAD = @as(u32, 4244701453);
pub const OID_PM_GET_PROTOCOL_OFFLOAD = @as(u32, 4244701454);
pub const OID_PM_REMOVE_PROTOCOL_OFFLOAD = @as(u32, 4244701455);
pub const OID_PM_PROTOCOL_OFFLOAD_LIST = @as(u32, 4244701456);
pub const OID_PM_RESERVED_1 = @as(u32, 4244701457);
pub const OID_RECEIVE_FILTER_HARDWARE_CAPABILITIES = @as(u32, 66081);
pub const OID_RECEIVE_FILTER_GLOBAL_PARAMETERS = @as(u32, 66082);
pub const OID_RECEIVE_FILTER_ALLOCATE_QUEUE = @as(u32, 66083);
pub const OID_RECEIVE_FILTER_FREE_QUEUE = @as(u32, 66084);
pub const OID_RECEIVE_FILTER_ENUM_QUEUES = @as(u32, 66085);
pub const OID_RECEIVE_FILTER_QUEUE_PARAMETERS = @as(u32, 66086);
pub const OID_RECEIVE_FILTER_SET_FILTER = @as(u32, 66087);
pub const OID_RECEIVE_FILTER_CLEAR_FILTER = @as(u32, 66088);
pub const OID_RECEIVE_FILTER_ENUM_FILTERS = @as(u32, 66089);
pub const OID_RECEIVE_FILTER_PARAMETERS = @as(u32, 66090);
pub const OID_RECEIVE_FILTER_QUEUE_ALLOCATION_COMPLETE = @as(u32, 66091);
pub const OID_RECEIVE_FILTER_CURRENT_CAPABILITIES = @as(u32, 66093);
pub const OID_NIC_SWITCH_HARDWARE_CAPABILITIES = @as(u32, 66094);
pub const OID_NIC_SWITCH_CURRENT_CAPABILITIES = @as(u32, 66095);
pub const OID_RECEIVE_FILTER_MOVE_FILTER = @as(u32, 66096);
pub const OID_VLAN_RESERVED1 = @as(u32, 66097);
pub const OID_VLAN_RESERVED2 = @as(u32, 66098);
pub const OID_VLAN_RESERVED3 = @as(u32, 66099);
pub const OID_VLAN_RESERVED4 = @as(u32, 66100);
pub const OID_PACKET_COALESCING_FILTER_MATCH_COUNT = @as(u32, 66101);
pub const OID_NIC_SWITCH_CREATE_SWITCH = @as(u32, 66103);
pub const OID_NIC_SWITCH_PARAMETERS = @as(u32, 66104);
pub const OID_NIC_SWITCH_DELETE_SWITCH = @as(u32, 66105);
pub const OID_NIC_SWITCH_ENUM_SWITCHES = @as(u32, 66112);
pub const OID_NIC_SWITCH_CREATE_VPORT = @as(u32, 66113);
pub const OID_NIC_SWITCH_VPORT_PARAMETERS = @as(u32, 66114);
pub const OID_NIC_SWITCH_ENUM_VPORTS = @as(u32, 66115);
pub const OID_NIC_SWITCH_DELETE_VPORT = @as(u32, 66116);
pub const OID_NIC_SWITCH_ALLOCATE_VF = @as(u32, 66117);
pub const OID_NIC_SWITCH_FREE_VF = @as(u32, 66118);
pub const OID_NIC_SWITCH_VF_PARAMETERS = @as(u32, 66119);
pub const OID_NIC_SWITCH_ENUM_VFS = @as(u32, 66120);
pub const OID_SRIOV_HARDWARE_CAPABILITIES = @as(u32, 66121);
pub const OID_SRIOV_CURRENT_CAPABILITIES = @as(u32, 66128);
pub const OID_SRIOV_READ_VF_CONFIG_SPACE = @as(u32, 66129);
pub const OID_SRIOV_WRITE_VF_CONFIG_SPACE = @as(u32, 66130);
pub const OID_SRIOV_READ_VF_CONFIG_BLOCK = @as(u32, 66131);
pub const OID_SRIOV_WRITE_VF_CONFIG_BLOCK = @as(u32, 66132);
pub const OID_SRIOV_RESET_VF = @as(u32, 66133);
pub const OID_SRIOV_SET_VF_POWER_STATE = @as(u32, 66134);
pub const OID_SRIOV_VF_VENDOR_DEVICE_ID = @as(u32, 66135);
pub const OID_SRIOV_PROBED_BARS = @as(u32, 66136);
pub const OID_SRIOV_BAR_RESOURCES = @as(u32, 66137);
pub const OID_SRIOV_PF_LUID = @as(u32, 66144);
pub const OID_SRIOV_CONFIG_STATE = @as(u32, 66145);
pub const OID_SRIOV_VF_SERIAL_NUMBER = @as(u32, 66146);
pub const OID_SRIOV_OVERLYING_ADAPTER_INFO = @as(u32, 66152);
pub const OID_SRIOV_VF_INVALIDATE_CONFIG_BLOCK = @as(u32, 66153);
pub const OID_SWITCH_PROPERTY_ADD = @as(u32, 66147);
pub const OID_SWITCH_PROPERTY_UPDATE = @as(u32, 66148);
pub const OID_SWITCH_PROPERTY_DELETE = @as(u32, 66149);
pub const OID_SWITCH_PROPERTY_ENUM = @as(u32, 66150);
pub const OID_SWITCH_FEATURE_STATUS_QUERY = @as(u32, 66151);
pub const OID_SWITCH_NIC_REQUEST = @as(u32, 66160);
pub const OID_SWITCH_PORT_PROPERTY_ADD = @as(u32, 66161);
pub const OID_SWITCH_PORT_PROPERTY_UPDATE = @as(u32, 66162);
pub const OID_SWITCH_PORT_PROPERTY_DELETE = @as(u32, 66163);
pub const OID_SWITCH_PORT_PROPERTY_ENUM = @as(u32, 66164);
pub const OID_SWITCH_PARAMETERS = @as(u32, 66165);
pub const OID_SWITCH_PORT_ARRAY = @as(u32, 66166);
pub const OID_SWITCH_NIC_ARRAY = @as(u32, 66167);
pub const OID_SWITCH_PORT_CREATE = @as(u32, 66168);
pub const OID_SWITCH_PORT_DELETE = @as(u32, 66169);
pub const OID_SWITCH_NIC_CREATE = @as(u32, 66170);
pub const OID_SWITCH_NIC_CONNECT = @as(u32, 66171);
pub const OID_SWITCH_NIC_DISCONNECT = @as(u32, 66172);
pub const OID_SWITCH_NIC_DELETE = @as(u32, 66173);
pub const OID_SWITCH_PORT_FEATURE_STATUS_QUERY = @as(u32, 66174);
pub const OID_SWITCH_PORT_TEARDOWN = @as(u32, 66175);
pub const OID_SWITCH_NIC_SAVE = @as(u32, 66192);
pub const OID_SWITCH_NIC_SAVE_COMPLETE = @as(u32, 66193);
pub const OID_SWITCH_NIC_RESTORE = @as(u32, 66194);
pub const OID_SWITCH_NIC_RESTORE_COMPLETE = @as(u32, 66195);
pub const OID_SWITCH_NIC_UPDATED = @as(u32, 66196);
pub const OID_SWITCH_PORT_UPDATED = @as(u32, 66197);
pub const OID_SWITCH_NIC_DIRECT_REQUEST = @as(u32, 66198);
pub const OID_SWITCH_NIC_SUSPEND = @as(u32, 66199);
pub const OID_SWITCH_NIC_RESUME = @as(u32, 66200);
pub const OID_SWITCH_NIC_SUSPENDED_LM_SOURCE_STARTED = @as(u32, 66201);
pub const OID_SWITCH_NIC_SUSPENDED_LM_SOURCE_FINISHED = @as(u32, 66202);
pub const OID_GEN_RSS_SET_INDIRECTION_TABLE_ENTRIES = @as(u32, 66240);
pub const OID_GEN_ISOLATION_PARAMETERS = @as(u32, 66304);
pub const OID_GFT_HARDWARE_CAPABILITIES = @as(u32, 66561);
pub const OID_GFT_CURRENT_CAPABILITIES = @as(u32, 66562);
pub const OID_GFT_GLOBAL_PARAMETERS = @as(u32, 66563);
pub const OID_GFT_CREATE_TABLE = @as(u32, 66564);
pub const OID_GFT_DELETE_TABLE = @as(u32, 66565);
pub const OID_GFT_ENUM_TABLES = @as(u32, 66566);
pub const OID_GFT_ALLOCATE_COUNTERS = @as(u32, 66567);
pub const OID_GFT_FREE_COUNTERS = @as(u32, 66568);
pub const OID_GFT_ENUM_COUNTERS = @as(u32, 66569);
pub const OID_GFT_COUNTER_VALUES = @as(u32, 66570);
pub const OID_GFT_STATISTICS = @as(u32, 66571);
pub const OID_GFT_ADD_FLOW_ENTRIES = @as(u32, 66572);
pub const OID_GFT_DELETE_FLOW_ENTRIES = @as(u32, 66573);
pub const OID_GFT_ENUM_FLOW_ENTRIES = @as(u32, 66574);
pub const OID_GFT_ACTIVATE_FLOW_ENTRIES = @as(u32, 66575);
pub const OID_GFT_DEACTIVATE_FLOW_ENTRIES = @as(u32, 66576);
pub const OID_GFT_FLOW_ENTRY_PARAMETERS = @as(u32, 66577);
pub const OID_GFT_EXACT_MATCH_PROFILE = @as(u32, 66578);
pub const OID_GFT_HEADER_TRANSPOSITION_PROFILE = @as(u32, 66579);
pub const OID_GFT_WILDCARD_MATCH_PROFILE = @as(u32, 66580);
pub const OID_GFT_ENUM_PROFILES = @as(u32, 66581);
pub const OID_GFT_DELETE_PROFILE = @as(u32, 66582);
pub const OID_GFT_VPORT_PARAMETERS = @as(u32, 66583);
pub const OID_GFT_CREATE_LOGICAL_VPORT = @as(u32, 66584);
pub const OID_GFT_DELETE_LOGICAL_VPORT = @as(u32, 66585);
pub const OID_GFT_ENUM_LOGICAL_VPORTS = @as(u32, 66586);
pub const OID_QOS_OFFLOAD_HARDWARE_CAPABILITIES = @as(u32, 67073);
pub const OID_QOS_OFFLOAD_CURRENT_CAPABILITIES = @as(u32, 67074);
pub const OID_QOS_OFFLOAD_CREATE_SQ = @as(u32, 67075);
pub const OID_QOS_OFFLOAD_DELETE_SQ = @as(u32, 67076);
pub const OID_QOS_OFFLOAD_UPDATE_SQ = @as(u32, 67077);
pub const OID_QOS_OFFLOAD_ENUM_SQS = @as(u32, 67078);
pub const OID_QOS_OFFLOAD_SQ_STATS = @as(u32, 67079);
pub const OID_PD_OPEN_PROVIDER = @as(u32, 66817);
pub const OID_PD_CLOSE_PROVIDER = @as(u32, 66818);
pub const OID_PD_QUERY_CURRENT_CONFIG = @as(u32, 66819);
pub const NDIS_PNP_WAKE_UP_MAGIC_PACKET = @as(u32, 1);
pub const NDIS_PNP_WAKE_UP_PATTERN_MATCH = @as(u32, 2);
pub const NDIS_PNP_WAKE_UP_LINK_CHANGE = @as(u32, 4);
pub const OID_TCP_TASK_OFFLOAD = @as(u32, 4227924481);
pub const OID_TCP_TASK_IPSEC_ADD_SA = @as(u32, 4227924482);
pub const OID_TCP_TASK_IPSEC_DELETE_SA = @as(u32, 4227924483);
pub const OID_TCP_SAN_SUPPORT = @as(u32, 4227924484);
pub const OID_TCP_TASK_IPSEC_ADD_UDPESP_SA = @as(u32, 4227924485);
pub const OID_TCP_TASK_IPSEC_DELETE_UDPESP_SA = @as(u32, 4227924486);
pub const OID_TCP4_OFFLOAD_STATS = @as(u32, 4227924487);
pub const OID_TCP6_OFFLOAD_STATS = @as(u32, 4227924488);
pub const OID_IP4_OFFLOAD_STATS = @as(u32, 4227924489);
pub const OID_IP6_OFFLOAD_STATS = @as(u32, 4227924490);
pub const OID_TCP_OFFLOAD_CURRENT_CONFIG = @as(u32, 4227924491);
pub const OID_TCP_OFFLOAD_PARAMETERS = @as(u32, 4227924492);
pub const OID_TCP_OFFLOAD_HARDWARE_CAPABILITIES = @as(u32, 4227924493);
pub const OID_TCP_CONNECTION_OFFLOAD_CURRENT_CONFIG = @as(u32, 4227924494);
pub const OID_TCP_CONNECTION_OFFLOAD_HARDWARE_CAPABILITIES = @as(u32, 4227924495);
pub const OID_OFFLOAD_ENCAPSULATION = @as(u32, 16843018);
pub const OID_TCP_TASK_IPSEC_OFFLOAD_V2_ADD_SA = @as(u32, 4228055554);
pub const OID_TCP_TASK_IPSEC_OFFLOAD_V2_DELETE_SA = @as(u32, 4228055555);
pub const OID_TCP_TASK_IPSEC_OFFLOAD_V2_UPDATE_SA = @as(u32, 4228055556);
pub const OID_TCP_TASK_IPSEC_OFFLOAD_V2_ADD_SA_EX = @as(u32, 4228055557);
pub const OID_FFP_SUPPORT = @as(u32, 4227924496);
pub const OID_FFP_FLUSH = @as(u32, 4227924497);
pub const OID_FFP_CONTROL = @as(u32, 4227924498);
pub const OID_FFP_PARAMS = @as(u32, 4227924499);
pub const OID_FFP_DATA = @as(u32, 4227924500);
pub const OID_FFP_DRIVER_STATS = @as(u32, 4227990032);
pub const OID_FFP_ADAPTER_STATS = @as(u32, 4227990033);
pub const OID_TCP_CONNECTION_OFFLOAD_PARAMETERS = @as(u32, 4228055553);
pub const OID_TUNNEL_INTERFACE_SET_OID = @as(u32, 251724038);
pub const OID_TUNNEL_INTERFACE_RELEASE_OID = @as(u32, 251724039);
pub const OID_QOS_RESERVED1 = @as(u32, 4211147008);
pub const OID_QOS_RESERVED2 = @as(u32, 4211147009);
pub const OID_QOS_RESERVED3 = @as(u32, 4211147010);
pub const OID_QOS_RESERVED4 = @as(u32, 4211147011);
pub const OID_QOS_RESERVED5 = @as(u32, 4211147012);
pub const OID_QOS_RESERVED6 = @as(u32, 4211147013);
pub const OID_QOS_RESERVED7 = @as(u32, 4211147014);
pub const OID_QOS_RESERVED8 = @as(u32, 4211147015);
pub const OID_QOS_RESERVED9 = @as(u32, 4211147016);
pub const OID_QOS_RESERVED10 = @as(u32, 4211147017);
pub const OID_QOS_RESERVED11 = @as(u32, 4211147018);
pub const OID_QOS_RESERVED12 = @as(u32, 4211147019);
pub const OID_QOS_RESERVED13 = @as(u32, 4211147020);
pub const OID_QOS_RESERVED14 = @as(u32, 4211147021);
pub const OID_QOS_RESERVED15 = @as(u32, 4211147022);
pub const OID_QOS_RESERVED16 = @as(u32, 4211147023);
pub const OID_QOS_RESERVED17 = @as(u32, 4211147024);
pub const OID_QOS_RESERVED18 = @as(u32, 4211147025);
pub const OID_QOS_RESERVED19 = @as(u32, 4211147026);
pub const OID_QOS_RESERVED20 = @as(u32, 4211147027);
pub const OID_XBOX_ACC_RESERVED0 = @as(u32, 4194304000);
pub const OFFLOAD_MAX_SAS = @as(u32, 3);
pub const OFFLOAD_INBOUND_SA = @as(u32, 1);
pub const OFFLOAD_OUTBOUND_SA = @as(u32, 2);
pub const NDIS_PROTOCOL_ID_DEFAULT = @as(u32, 0);
pub const NDIS_PROTOCOL_ID_TCP_IP = @as(u32, 2);
pub const NDIS_PROTOCOL_ID_IP6 = @as(u32, 3);
pub const NDIS_PROTOCOL_ID_IPX = @as(u32, 6);
pub const NDIS_PROTOCOL_ID_NBF = @as(u32, 7);
pub const NDIS_PROTOCOL_ID_MAX = @as(u32, 15);
pub const NDIS_PROTOCOL_ID_MASK = @as(u32, 15);
pub const READABLE_LOCAL_CLOCK = @as(u32, 1);
pub const CLOCK_NETWORK_DERIVED = @as(u32, 2);
pub const CLOCK_PRECISION = @as(u32, 4);
pub const RECEIVE_TIME_INDICATION_CAPABLE = @as(u32, 8);
pub const TIMED_SEND_CAPABLE = @as(u32, 16);
pub const TIME_STAMP_CAPABLE = @as(u32, 32);
pub const NDIS_DEVICE_WAKE_UP_ENABLE = @as(u32, 1);
pub const NDIS_DEVICE_WAKE_ON_PATTERN_MATCH_ENABLE = @as(u32, 2);
pub const NDIS_DEVICE_WAKE_ON_MAGIC_PACKET_ENABLE = @as(u32, 4);
pub const WAN_PROTOCOL_KEEPS_STATS = @as(u32, 1);
pub const NDIS_PACKET_TYPE_DIRECTED = @as(u32, 1);
pub const NDIS_PACKET_TYPE_MULTICAST = @as(u32, 2);
pub const NDIS_PACKET_TYPE_ALL_MULTICAST = @as(u32, 4);
pub const NDIS_PACKET_TYPE_BROADCAST = @as(u32, 8);
pub const NDIS_PACKET_TYPE_SOURCE_ROUTING = @as(u32, 16);
pub const NDIS_PACKET_TYPE_PROMISCUOUS = @as(u32, 32);
pub const NDIS_PACKET_TYPE_SMT = @as(u32, 64);
pub const NDIS_PACKET_TYPE_ALL_LOCAL = @as(u32, 128);
pub const NDIS_PACKET_TYPE_GROUP = @as(u32, 4096);
pub const NDIS_PACKET_TYPE_ALL_FUNCTIONAL = @as(u32, 8192);
pub const NDIS_PACKET_TYPE_FUNCTIONAL = @as(u32, 16384);
pub const NDIS_PACKET_TYPE_MAC_FRAME = @as(u32, 32768);
pub const NDIS_PACKET_TYPE_NO_LOCAL = @as(u32, 65536);
pub const NDIS_RING_SIGNAL_LOSS = @as(u32, 32768);
pub const NDIS_RING_HARD_ERROR = @as(u32, 16384);
pub const NDIS_RING_SOFT_ERROR = @as(u32, 8192);
pub const NDIS_RING_TRANSMIT_BEACON = @as(u32, 4096);
pub const NDIS_RING_LOBE_WIRE_FAULT = @as(u32, 2048);
pub const NDIS_RING_AUTO_REMOVAL_ERROR = @as(u32, 1024);
pub const NDIS_RING_REMOVE_RECEIVED = @as(u32, 512);
pub const NDIS_RING_COUNTER_OVERFLOW = @as(u32, 256);
pub const NDIS_RING_SINGLE_STATION = @as(u32, 128);
pub const NDIS_RING_RING_RECOVERY = @as(u32, 64);
pub const NDIS_PROT_OPTION_ESTIMATED_LENGTH = @as(u32, 1);
pub const NDIS_PROT_OPTION_NO_LOOPBACK = @as(u32, 2);
pub const NDIS_PROT_OPTION_NO_RSVD_ON_RCVPKT = @as(u32, 4);
pub const NDIS_PROT_OPTION_SEND_RESTRICTED = @as(u32, 8);
pub const NDIS_MAC_OPTION_COPY_LOOKAHEAD_DATA = @as(u32, 1);
pub const NDIS_MAC_OPTION_RECEIVE_SERIALIZED = @as(u32, 2);
pub const NDIS_MAC_OPTION_TRANSFERS_NOT_PEND = @as(u32, 4);
pub const NDIS_MAC_OPTION_NO_LOOPBACK = @as(u32, 8);
pub const NDIS_MAC_OPTION_FULL_DUPLEX = @as(u32, 16);
pub const NDIS_MAC_OPTION_EOTX_INDICATION = @as(u32, 32);
pub const NDIS_MAC_OPTION_8021P_PRIORITY = @as(u32, 64);
pub const NDIS_MAC_OPTION_SUPPORTS_MAC_ADDRESS_OVERWRITE = @as(u32, 128);
pub const NDIS_MAC_OPTION_RECEIVE_AT_DPC = @as(u32, 256);
pub const NDIS_MAC_OPTION_8021Q_VLAN = @as(u32, 512);
pub const NDIS_MAC_OPTION_RESERVED = @as(u32, 2147483648);
pub const NDIS_MEDIA_CAP_TRANSMIT = @as(u32, 1);
pub const NDIS_MEDIA_CAP_RECEIVE = @as(u32, 2);
pub const NDIS_CO_MAC_OPTION_DYNAMIC_LINK_SPEED = @as(u32, 1);
pub const NDIS_IF_MAX_STRING_SIZE = @as(u32, 256);
pub const NDIS_MAX_PHYS_ADDRESS_LENGTH = @as(u32, 32);
pub const NDIS_LINK_STATE_XMIT_LINK_SPEED_AUTO_NEGOTIATED = @as(u32, 1);
pub const NDIS_LINK_STATE_RCV_LINK_SPEED_AUTO_NEGOTIATED = @as(u32, 2);
pub const NDIS_LINK_STATE_DUPLEX_AUTO_NEGOTIATED = @as(u32, 4);
pub const NDIS_LINK_STATE_PAUSE_FUNCTIONS_AUTO_NEGOTIATED = @as(u32, 8);
pub const NDIS_LINK_STATE_REVISION_1 = @as(u32, 1);
pub const NDIS_LINK_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_OPER_STATE_REVISION_1 = @as(u32, 1);
pub const MAXIMUM_IP_OPER_STATUS_ADDRESS_FAMILIES_SUPPORTED = @as(u32, 32);
pub const NDIS_IP_OPER_STATUS_INFO_REVISION_1 = @as(u32, 1);
pub const NDIS_IP_OPER_STATE_REVISION_1 = @as(u32, 1);
pub const NDIS_OFFLOAD_PARAMETERS_NO_CHANGE = @as(u32, 0);
pub const NDIS_OFFLOAD_PARAMETERS_TX_RX_DISABLED = @as(u32, 1);
pub const NDIS_OFFLOAD_PARAMETERS_TX_ENABLED_RX_DISABLED = @as(u32, 2);
pub const NDIS_OFFLOAD_PARAMETERS_RX_ENABLED_TX_DISABLED = @as(u32, 3);
pub const NDIS_OFFLOAD_PARAMETERS_TX_RX_ENABLED = @as(u32, 4);
pub const NDIS_OFFLOAD_PARAMETERS_LSOV1_DISABLED = @as(u32, 1);
pub const NDIS_OFFLOAD_PARAMETERS_LSOV1_ENABLED = @as(u32, 2);
pub const NDIS_OFFLOAD_PARAMETERS_IPSECV1_DISABLED = @as(u32, 1);
pub const NDIS_OFFLOAD_PARAMETERS_IPSECV1_AH_ENABLED = @as(u32, 2);
pub const NDIS_OFFLOAD_PARAMETERS_IPSECV1_ESP_ENABLED = @as(u32, 3);
pub const NDIS_OFFLOAD_PARAMETERS_IPSECV1_AH_AND_ESP_ENABLED = @as(u32, 4);
pub const NDIS_OFFLOAD_PARAMETERS_LSOV2_DISABLED = @as(u32, 1);
pub const NDIS_OFFLOAD_PARAMETERS_LSOV2_ENABLED = @as(u32, 2);
pub const NDIS_OFFLOAD_PARAMETERS_IPSECV2_DISABLED = @as(u32, 1);
pub const NDIS_OFFLOAD_PARAMETERS_IPSECV2_AH_ENABLED = @as(u32, 2);
pub const NDIS_OFFLOAD_PARAMETERS_IPSECV2_ESP_ENABLED = @as(u32, 3);
pub const NDIS_OFFLOAD_PARAMETERS_IPSECV2_AH_AND_ESP_ENABLED = @as(u32, 4);
pub const NDIS_OFFLOAD_PARAMETERS_RSC_DISABLED = @as(u32, 1);
pub const NDIS_OFFLOAD_PARAMETERS_RSC_ENABLED = @as(u32, 2);
pub const NDIS_ENCAPSULATION_TYPE_GRE_MAC = @as(u32, 1);
pub const NDIS_ENCAPSULATION_TYPE_VXLAN = @as(u32, 2);
pub const NDIS_OFFLOAD_PARAMETERS_CONNECTION_OFFLOAD_DISABLED = @as(u32, 1);
pub const NDIS_OFFLOAD_PARAMETERS_CONNECTION_OFFLOAD_ENABLED = @as(u32, 2);
pub const NDIS_OFFLOAD_PARAMETERS_USO_DISABLED = @as(u32, 1);
pub const NDIS_OFFLOAD_PARAMETERS_USO_ENABLED = @as(u32, 2);
pub const NDIS_OFFLOAD_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_OFFLOAD_PARAMETERS_REVISION_2 = @as(u32, 2);
pub const NDIS_OFFLOAD_PARAMETERS_REVISION_3 = @as(u32, 3);
pub const NDIS_OFFLOAD_PARAMETERS_REVISION_4 = @as(u32, 4);
pub const NDIS_OFFLOAD_PARAMETERS_REVISION_5 = @as(u32, 5);
pub const NDIS_OFFLOAD_PARAMETERS_SKIP_REGISTRY_UPDATE = @as(u32, 1);
pub const IPSEC_OFFLOAD_V2_AUTHENTICATION_MD5 = @as(u32, 1);
pub const IPSEC_OFFLOAD_V2_AUTHENTICATION_SHA_1 = @as(u32, 2);
pub const IPSEC_OFFLOAD_V2_AUTHENTICATION_SHA_256 = @as(u32, 4);
pub const IPSEC_OFFLOAD_V2_AUTHENTICATION_AES_GCM_128 = @as(u32, 8);
pub const IPSEC_OFFLOAD_V2_AUTHENTICATION_AES_GCM_192 = @as(u32, 16);
pub const IPSEC_OFFLOAD_V2_AUTHENTICATION_AES_GCM_256 = @as(u32, 32);
pub const IPSEC_OFFLOAD_V2_ENCRYPTION_NONE = @as(u32, 1);
pub const IPSEC_OFFLOAD_V2_ENCRYPTION_DES_CBC = @as(u32, 2);
pub const IPSEC_OFFLOAD_V2_ENCRYPTION_3_DES_CBC = @as(u32, 4);
pub const IPSEC_OFFLOAD_V2_ENCRYPTION_AES_GCM_128 = @as(u32, 8);
pub const IPSEC_OFFLOAD_V2_ENCRYPTION_AES_GCM_192 = @as(u32, 16);
pub const IPSEC_OFFLOAD_V2_ENCRYPTION_AES_GCM_256 = @as(u32, 32);
pub const IPSEC_OFFLOAD_V2_ENCRYPTION_AES_CBC_128 = @as(u32, 64);
pub const IPSEC_OFFLOAD_V2_ENCRYPTION_AES_CBC_192 = @as(u32, 128);
pub const IPSEC_OFFLOAD_V2_ENCRYPTION_AES_CBC_256 = @as(u32, 256);
pub const NDIS_TCP_RECV_SEG_COALESC_OFFLOAD_REVISION_1 = @as(u32, 1);
pub const NDIS_ENCAPSULATED_PACKET_TASK_OFFLOAD_NOT_SUPPORTED = @as(u32, 0);
pub const NDIS_ENCAPSULATED_PACKET_TASK_OFFLOAD_INNER_IPV4 = @as(u32, 1);
pub const NDIS_ENCAPSULATED_PACKET_TASK_OFFLOAD_OUTER_IPV4 = @as(u32, 2);
pub const NDIS_ENCAPSULATED_PACKET_TASK_OFFLOAD_INNER_IPV6 = @as(u32, 4);
pub const NDIS_ENCAPSULATED_PACKET_TASK_OFFLOAD_OUTER_IPV6 = @as(u32, 8);
pub const NDIS_OFFLOAD_FLAGS_GROUP_CHECKSUM_CAPABILITIES = @as(u32, 1);
pub const IPSEC_OFFLOAD_V2_AND_TCP_CHECKSUM_COEXISTENCE = @as(u32, 2);
pub const IPSEC_OFFLOAD_V2_AND_UDP_CHECKSUM_COEXISTENCE = @as(u32, 4);
pub const NDIS_OFFLOAD_REVISION_1 = @as(u32, 1);
pub const NDIS_OFFLOAD_REVISION_2 = @as(u32, 2);
pub const NDIS_OFFLOAD_REVISION_3 = @as(u32, 3);
pub const NDIS_OFFLOAD_REVISION_4 = @as(u32, 4);
pub const NDIS_OFFLOAD_REVISION_5 = @as(u32, 5);
pub const NDIS_OFFLOAD_REVISION_6 = @as(u32, 6);
pub const NDIS_OFFLOAD_REVISION_7 = @as(u32, 7);
pub const NDIS_TCP_CONNECTION_OFFLOAD_REVISION_1 = @as(u32, 1);
pub const NDIS_TCP_CONNECTION_OFFLOAD_REVISION_2 = @as(u32, 2);
pub const NDIS_PORT_AUTHENTICATION_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_WMI_DEFAULT_METHOD_ID = @as(u32, 1);
pub const NDIS_WMI_OBJECT_TYPE_SET = @as(u32, 1);
pub const NDIS_WMI_OBJECT_TYPE_METHOD = @as(u32, 2);
pub const NDIS_WMI_OBJECT_TYPE_EVENT = @as(u32, 3);
pub const NDIS_WMI_OBJECT_TYPE_ENUM_ADAPTER = @as(u32, 4);
pub const NDIS_WMI_OBJECT_TYPE_OUTPUT_INFO = @as(u32, 5);
pub const NDIS_WMI_METHOD_HEADER_REVISION_1 = @as(u32, 1);
pub const NDIS_WMI_SET_HEADER_REVISION_1 = @as(u32, 1);
pub const NDIS_WMI_EVENT_HEADER_REVISION_1 = @as(u32, 1);
pub const NDIS_WMI_ENUM_ADAPTER_REVISION_1 = @as(u32, 1);
pub const NDIS_DEVICE_TYPE_ENDPOINT = @as(u32, 1);
pub const NDIS_HD_SPLIT_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_HD_SPLIT_COMBINE_ALL_HEADERS = @as(u32, 1);
pub const NDIS_HD_SPLIT_CURRENT_CONFIG_REVISION_1 = @as(u32, 1);
pub const NDIS_HD_SPLIT_CAPS_SUPPORTS_HEADER_DATA_SPLIT = @as(u32, 1);
pub const NDIS_HD_SPLIT_CAPS_SUPPORTS_IPV4_OPTIONS = @as(u32, 2);
pub const NDIS_HD_SPLIT_CAPS_SUPPORTS_IPV6_EXTENSION_HEADERS = @as(u32, 4);
pub const NDIS_HD_SPLIT_CAPS_SUPPORTS_TCP_OPTIONS = @as(u32, 8);
pub const NDIS_HD_SPLIT_ENABLE_HEADER_DATA_SPLIT = @as(u32, 1);
pub const NDIS_PM_WOL_BITMAP_PATTERN_SUPPORTED = @as(u32, 1);
pub const NDIS_PM_WOL_MAGIC_PACKET_SUPPORTED = @as(u32, 2);
pub const NDIS_PM_WOL_IPV4_TCP_SYN_SUPPORTED = @as(u32, 4);
pub const NDIS_PM_WOL_IPV6_TCP_SYN_SUPPORTED = @as(u32, 8);
pub const NDIS_PM_WOL_IPV4_DEST_ADDR_WILDCARD_SUPPORTED = @as(u32, 512);
pub const NDIS_PM_WOL_IPV6_DEST_ADDR_WILDCARD_SUPPORTED = @as(u32, 2048);
pub const NDIS_PM_WOL_EAPOL_REQUEST_ID_MESSAGE_SUPPORTED = @as(u32, 65536);
pub const NDIS_PM_PROTOCOL_OFFLOAD_ARP_SUPPORTED = @as(u32, 1);
pub const NDIS_PM_PROTOCOL_OFFLOAD_NS_SUPPORTED = @as(u32, 2);
pub const NDIS_PM_PROTOCOL_OFFLOAD_80211_RSN_REKEY_SUPPORTED = @as(u32, 128);
pub const NDIS_PM_WAKE_ON_MEDIA_CONNECT_SUPPORTED = @as(u32, 1);
pub const NDIS_PM_WAKE_ON_MEDIA_DISCONNECT_SUPPORTED = @as(u32, 2);
pub const NDIS_WLAN_WAKE_ON_NLO_DISCOVERY_SUPPORTED = @as(u32, 1);
pub const NDIS_WLAN_WAKE_ON_AP_ASSOCIATION_LOST_SUPPORTED = @as(u32, 2);
pub const NDIS_WLAN_WAKE_ON_GTK_HANDSHAKE_ERROR_SUPPORTED = @as(u32, 4);
pub const NDIS_WLAN_WAKE_ON_4WAY_HANDSHAKE_REQUEST_SUPPORTED = @as(u32, 8);
pub const NDIS_WWAN_WAKE_ON_REGISTER_STATE_SUPPORTED = @as(u32, 1);
pub const NDIS_WWAN_WAKE_ON_SMS_RECEIVE_SUPPORTED = @as(u32, 2);
pub const NDIS_WWAN_WAKE_ON_USSD_RECEIVE_SUPPORTED = @as(u32, 4);
pub const NDIS_WWAN_WAKE_ON_PACKET_STATE_SUPPORTED = @as(u32, 8);
pub const NDIS_WWAN_WAKE_ON_UICC_CHANGE_SUPPORTED = @as(u32, 16);
pub const NDIS_PM_WAKE_PACKET_INDICATION_SUPPORTED = @as(u32, 1);
pub const NDIS_PM_SELECTIVE_SUSPEND_SUPPORTED = @as(u32, 2);
pub const NDIS_PM_WOL_BITMAP_PATTERN_ENABLED = @as(u32, 1);
pub const NDIS_PM_WOL_MAGIC_PACKET_ENABLED = @as(u32, 2);
pub const NDIS_PM_WOL_IPV4_TCP_SYN_ENABLED = @as(u32, 4);
pub const NDIS_PM_WOL_IPV6_TCP_SYN_ENABLED = @as(u32, 8);
pub const NDIS_PM_WOL_IPV4_DEST_ADDR_WILDCARD_ENABLED = @as(u32, 512);
pub const NDIS_PM_WOL_IPV6_DEST_ADDR_WILDCARD_ENABLED = @as(u32, 2048);
pub const NDIS_PM_WOL_EAPOL_REQUEST_ID_MESSAGE_ENABLED = @as(u32, 65536);
pub const NDIS_PM_PROTOCOL_OFFLOAD_ARP_ENABLED = @as(u32, 1);
pub const NDIS_PM_PROTOCOL_OFFLOAD_NS_ENABLED = @as(u32, 2);
pub const NDIS_PM_PROTOCOL_OFFLOAD_80211_RSN_REKEY_ENABLED = @as(u32, 128);
pub const NDIS_PM_WAKE_ON_LINK_CHANGE_ENABLED = @as(u32, 1);
pub const NDIS_PM_WAKE_ON_MEDIA_DISCONNECT_ENABLED = @as(u32, 2);
pub const NDIS_PM_SELECTIVE_SUSPEND_ENABLED = @as(u32, 16);
pub const NDIS_WLAN_WAKE_ON_NLO_DISCOVERY_ENABLED = @as(u32, 1);
pub const NDIS_WLAN_WAKE_ON_AP_ASSOCIATION_LOST_ENABLED = @as(u32, 2);
pub const NDIS_WLAN_WAKE_ON_GTK_HANDSHAKE_ERROR_ENABLED = @as(u32, 4);
pub const NDIS_WLAN_WAKE_ON_4WAY_HANDSHAKE_REQUEST_ENABLED = @as(u32, 8);
pub const NDIS_WWAN_WAKE_ON_REGISTER_STATE_ENABLED = @as(u32, 1);
pub const NDIS_WWAN_WAKE_ON_SMS_RECEIVE_ENABLED = @as(u32, 2);
pub const NDIS_WWAN_WAKE_ON_USSD_RECEIVE_ENABLED = @as(u32, 4);
pub const NDIS_WWAN_WAKE_ON_PACKET_STATE_ENABLED = @as(u32, 8);
pub const NDIS_WWAN_WAKE_ON_UICC_CHANGE_ENABLED = @as(u32, 16);
pub const NDIS_PM_WOL_PRIORITY_LOWEST = @as(u32, 4294967295);
pub const NDIS_PM_WOL_PRIORITY_NORMAL = @as(u32, 268435456);
pub const NDIS_PM_WOL_PRIORITY_HIGHEST = @as(u32, 1);
pub const NDIS_PM_PROTOCOL_OFFLOAD_PRIORITY_LOWEST = @as(u32, 4294967295);
pub const NDIS_PM_PROTOCOL_OFFLOAD_PRIORITY_NORMAL = @as(u32, 268435456);
pub const NDIS_PM_PROTOCOL_OFFLOAD_PRIORITY_HIGHEST = @as(u32, 1);
pub const NDIS_PM_MAX_STRING_SIZE = @as(u32, 64);
pub const NDIS_PM_CAPABILITIES_REVISION_1 = @as(u32, 1);
pub const NDIS_PM_CAPABILITIES_REVISION_2 = @as(u32, 2);
pub const NDIS_PM_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_PM_PARAMETERS_REVISION_2 = @as(u32, 2);
pub const EAPOL_REQUEST_ID_WOL_FLAG_MUST_ENCRYPT = @as(u32, 1);
pub const NDIS_PM_MAX_PATTERN_ID = @as(u32, 65535);
pub const NDIS_PM_PRIVATE_PATTERN_ID = @as(u32, 1);
pub const NDIS_PM_WOL_PATTERN_REVISION_1 = @as(u32, 1);
pub const NDIS_PM_WOL_PATTERN_REVISION_2 = @as(u32, 2);
pub const DOT11_RSN_KCK_LENGTH = @as(u32, 16);
pub const DOT11_RSN_KEK_LENGTH = @as(u32, 16);
pub const DOT11_RSN_MAX_CIPHER_KEY_LENGTH = @as(u32, 32);
pub const NDIS_PM_PROTOCOL_OFFLOAD_REVISION_1 = @as(u32, 1);
pub const NDIS_PM_PROTOCOL_OFFLOAD_REVISION_2 = @as(u32, 2);
pub const NDIS_SIZEOF_NDIS_PM_PROTOCOL_OFFLOAD_REVISION_1 = @as(u32, 240);
pub const NDIS_PM_WAKE_REASON_REVISION_1 = @as(u32, 1);
pub const NDIS_PM_WAKE_PACKET_REVISION_1 = @as(u32, 1);
pub const NDIS_WMI_PM_ADMIN_CONFIG_REVISION_1 = @as(u32, 1);
pub const NDIS_WMI_PM_ACTIVE_CAPABILITIES_REVISION_1 = @as(u32, 1);
pub const NDIS_RECEIVE_FILTER_MAC_HEADER_SUPPORTED = @as(u32, 1);
pub const NDIS_RECEIVE_FILTER_IPV4_HEADER_SUPPORTED = @as(u32, 2);
pub const NDIS_RECEIVE_FILTER_IPV6_HEADER_SUPPORTED = @as(u32, 4);
pub const NDIS_RECEIVE_FILTER_ARP_HEADER_SUPPORTED = @as(u32, 8);
pub const NDIS_RECEIVE_FILTER_UDP_HEADER_SUPPORTED = @as(u32, 16);
pub const NDIS_RECEIVE_FILTER_MAC_HEADER_DEST_ADDR_SUPPORTED = @as(u32, 1);
pub const NDIS_RECEIVE_FILTER_MAC_HEADER_SOURCE_ADDR_SUPPORTED = @as(u32, 2);
pub const NDIS_RECEIVE_FILTER_MAC_HEADER_PROTOCOL_SUPPORTED = @as(u32, 4);
pub const NDIS_RECEIVE_FILTER_MAC_HEADER_VLAN_ID_SUPPORTED = @as(u32, 8);
pub const NDIS_RECEIVE_FILTER_MAC_HEADER_PRIORITY_SUPPORTED = @as(u32, 16);
pub const NDIS_RECEIVE_FILTER_MAC_HEADER_PACKET_TYPE_SUPPORTED = @as(u32, 32);
pub const NDIS_RECEIVE_FILTER_ARP_HEADER_OPERATION_SUPPORTED = @as(u32, 1);
pub const NDIS_RECEIVE_FILTER_ARP_HEADER_SPA_SUPPORTED = @as(u32, 2);
pub const NDIS_RECEIVE_FILTER_ARP_HEADER_TPA_SUPPORTED = @as(u32, 4);
pub const NDIS_RECEIVE_FILTER_IPV4_HEADER_PROTOCOL_SUPPORTED = @as(u32, 1);
pub const NDIS_RECEIVE_FILTER_IPV6_HEADER_PROTOCOL_SUPPORTED = @as(u32, 1);
pub const NDIS_RECEIVE_FILTER_UDP_HEADER_DEST_PORT_SUPPORTED = @as(u32, 1);
pub const NDIS_RECEIVE_FILTER_TEST_HEADER_FIELD_EQUAL_SUPPORTED = @as(u32, 1);
pub const NDIS_RECEIVE_FILTER_TEST_HEADER_FIELD_MASK_EQUAL_SUPPORTED = @as(u32, 2);
pub const NDIS_RECEIVE_FILTER_TEST_HEADER_FIELD_NOT_EQUAL_SUPPORTED = @as(u32, 4);
pub const NDIS_RECEIVE_FILTER_MSI_X_SUPPORTED = @as(u32, 1);
pub const NDIS_RECEIVE_FILTER_VM_QUEUE_SUPPORTED = @as(u32, 2);
pub const NDIS_RECEIVE_FILTER_LOOKAHEAD_SPLIT_SUPPORTED = @as(u32, 4);
pub const NDIS_RECEIVE_FILTER_DYNAMIC_PROCESSOR_AFFINITY_CHANGE_SUPPORTED = @as(u32, 8);
pub const NDIS_RECEIVE_FILTER_INTERRUPT_VECTOR_COALESCING_SUPPORTED = @as(u32, 16);
pub const NDIS_RECEIVE_FILTER_IMPLAT_MIN_OF_QUEUES_MODE = @as(u32, 64);
pub const NDIS_RECEIVE_FILTER_IMPLAT_SUM_OF_QUEUES_MODE = @as(u32, 128);
pub const NDIS_RECEIVE_FILTER_PACKET_COALESCING_SUPPORTED_ON_DEFAULT_QUEUE = @as(u32, 256);
pub const NDIS_RECEIVE_FILTER_ANY_VLAN_SUPPORTED = @as(u32, 32);
pub const NDIS_RECEIVE_FILTER_DYNAMIC_PROCESSOR_AFFINITY_CHANGE_FOR_DEFAULT_QUEUE_SUPPORTED = @as(u32, 64);
pub const NDIS_RECEIVE_FILTER_VMQ_FILTERS_ENABLED = @as(u32, 1);
pub const NDIS_RECEIVE_FILTER_PACKET_COALESCING_FILTERS_ENABLED = @as(u32, 2);
pub const NDIS_RECEIVE_FILTER_VM_QUEUES_ENABLED = @as(u32, 1);
pub const NDIS_RECEIVE_FILTER_CAPABILITIES_REVISION_1 = @as(u32, 1);
pub const NDIS_RECEIVE_FILTER_CAPABILITIES_REVISION_2 = @as(u32, 2);
pub const NDIS_NIC_SWITCH_CAPS_VLAN_SUPPORTED = @as(u32, 1);
pub const NDIS_NIC_SWITCH_CAPS_PER_VPORT_INTERRUPT_MODERATION_SUPPORTED = @as(u32, 2);
pub const NDIS_NIC_SWITCH_CAPS_ASYMMETRIC_QUEUE_PAIRS_FOR_NONDEFAULT_VPORT_SUPPORTED = @as(u32, 4);
pub const NDIS_NIC_SWITCH_CAPS_VF_RSS_SUPPORTED = @as(u32, 8);
pub const NDIS_NIC_SWITCH_CAPS_SINGLE_VPORT_POOL = @as(u32, 16);
pub const NDIS_NIC_SWITCH_CAPS_RSS_PARAMETERS_PER_PF_VPORT_SUPPORTED = @as(u32, 32);
pub const NDIS_NIC_SWITCH_CAPS_NIC_SWITCH_WITHOUT_IOV_SUPPORTED = @as(u32, 64);
pub const NDIS_NIC_SWITCH_CAPS_RSS_ON_PF_VPORTS_SUPPORTED = @as(u32, 128);
pub const NDIS_NIC_SWITCH_CAPS_RSS_PER_PF_VPORT_INDIRECTION_TABLE_SUPPORTED = @as(u32, 256);
pub const NDIS_NIC_SWITCH_CAPS_RSS_PER_PF_VPORT_HASH_FUNCTION_SUPPORTED = @as(u32, 512);
pub const NDIS_NIC_SWITCH_CAPS_RSS_PER_PF_VPORT_HASH_TYPE_SUPPORTED = @as(u32, 1024);
pub const NDIS_NIC_SWITCH_CAPS_RSS_PER_PF_VPORT_HASH_KEY_SUPPORTED = @as(u32, 2048);
pub const NDIS_NIC_SWITCH_CAPS_RSS_PER_PF_VPORT_INDIRECTION_TABLE_SIZE_RESTRICTED = @as(u32, 4096);
pub const NDIS_NIC_SWITCH_CAPABILITIES_REVISION_1 = @as(u32, 1);
pub const NDIS_NIC_SWITCH_CAPABILITIES_REVISION_2 = @as(u32, 2);
pub const NDIS_NIC_SWITCH_CAPABILITIES_REVISION_3 = @as(u32, 3);
pub const NDIS_RECEIVE_FILTER_GLOBAL_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_DEFAULT_RECEIVE_QUEUE_ID = @as(u32, 0);
pub const NDIS_DEFAULT_RECEIVE_QUEUE_GROUP_ID = @as(u32, 0);
pub const NDIS_DEFAULT_RECEIVE_FILTER_ID = @as(u32, 0);
pub const NDIS_RECEIVE_FILTER_FIELD_MAC_HEADER_VLAN_UNTAGGED_OR_ZERO = @as(u32, 1);
pub const NDIS_RECEIVE_FILTER_RESERVED = @as(u32, 254);
pub const NDIS_RECEIVE_FILTER_FIELD_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_RECEIVE_FILTER_FIELD_PARAMETERS_REVISION_2 = @as(u32, 2);
pub const NDIS_RECEIVE_FILTER_FLAGS_RESERVED = @as(u32, 1);
pub const NDIS_RECEIVE_FILTER_PACKET_ENCAPSULATION_GRE = @as(u32, 2);
pub const NDIS_RECEIVE_FILTER_PACKET_ENCAPSULATION = @as(u32, 2);
pub const NDIS_RECEIVE_FILTER_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_RECEIVE_FILTER_PARAMETERS_REVISION_2 = @as(u32, 2);
pub const NDIS_RECEIVE_FILTER_CLEAR_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_RECEIVE_QUEUE_PARAMETERS_PER_QUEUE_RECEIVE_INDICATION = @as(u32, 1);
pub const NDIS_RECEIVE_QUEUE_PARAMETERS_LOOKAHEAD_SPLIT_REQUIRED = @as(u32, 2);
pub const NDIS_RECEIVE_QUEUE_PARAMETERS_FLAGS_CHANGED = @as(u32, 65536);
pub const NDIS_RECEIVE_QUEUE_PARAMETERS_PROCESSOR_AFFINITY_CHANGED = @as(u32, 131072);
pub const NDIS_RECEIVE_QUEUE_PARAMETERS_SUGGESTED_RECV_BUFFER_NUMBERS_CHANGED = @as(u32, 262144);
pub const NDIS_RECEIVE_QUEUE_PARAMETERS_NAME_CHANGED = @as(u32, 524288);
pub const NDIS_RECEIVE_QUEUE_PARAMETERS_INTERRUPT_COALESCING_DOMAIN_ID_CHANGED = @as(u32, 1048576);
pub const NDIS_RECEIVE_QUEUE_PARAMETERS_QOS_SQ_ID_CHANGED = @as(u32, 2097152);
pub const NDIS_RECEIVE_QUEUE_PARAMETERS_CHANGE_MASK = @as(u32, 4294901760);
pub const NDIS_RECEIVE_QUEUE_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_RECEIVE_QUEUE_PARAMETERS_REVISION_2 = @as(u32, 2);
pub const NDIS_RECEIVE_QUEUE_PARAMETERS_REVISION_3 = @as(u32, 3);
pub const NDIS_RECEIVE_QUEUE_FREE_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_RECEIVE_QUEUE_INFO_REVISION_1 = @as(u32, 1);
pub const NDIS_RECEIVE_QUEUE_INFO_REVISION_2 = @as(u32, 2);
pub const NDIS_RECEIVE_QUEUE_INFO_ARRAY_REVISION_1 = @as(u32, 1);
pub const NDIS_RECEIVE_FILTER_INFO_REVISION_1 = @as(u32, 1);
pub const NDIS_RECEIVE_FILTER_INFO_ARRAY_REVISION_1 = @as(u32, 1);
pub const NDIS_RECEIVE_FILTER_INFO_ARRAY_REVISION_2 = @as(u32, 2);
pub const NDIS_RECEIVE_FILTER_INFO_ARRAY_VPORT_ID_SPECIFIED = @as(u32, 1);
pub const NDIS_RECEIVE_QUEUE_ALLOCATION_COMPLETE_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_RECEIVE_QUEUE_ALLOCATION_COMPLETE_ARRAY_REVISION_1 = @as(u32, 1);
pub const NDIS_RECEIVE_SCALE_CAPABILITIES_REVISION_1 = @as(u32, 1);
pub const NDIS_RECEIVE_SCALE_CAPABILITIES_REVISION_2 = @as(u32, 2);
pub const NDIS_RECEIVE_SCALE_CAPABILITIES_REVISION_3 = @as(u32, 3);
pub const NDIS_RSS_CAPS_HASH_TYPE_TCP_IPV4 = @as(u32, 256);
pub const NDIS_RSS_CAPS_HASH_TYPE_TCP_IPV6 = @as(u32, 512);
pub const NDIS_RSS_CAPS_HASH_TYPE_TCP_IPV6_EX = @as(u32, 1024);
pub const NDIS_RSS_CAPS_HASH_TYPE_UDP_IPV4 = @as(u32, 2048);
pub const NDIS_RSS_CAPS_HASH_TYPE_UDP_IPV6 = @as(u32, 4096);
pub const NDIS_RSS_CAPS_HASH_TYPE_UDP_IPV6_EX = @as(u32, 8192);
pub const NDIS_RSS_CAPS_MESSAGE_SIGNALED_INTERRUPTS = @as(u32, 16777216);
pub const NDIS_RSS_CAPS_CLASSIFICATION_AT_ISR = @as(u32, 33554432);
pub const NDIS_RSS_CAPS_CLASSIFICATION_AT_DPC = @as(u32, 67108864);
pub const NDIS_RSS_CAPS_USING_MSI_X = @as(u32, 134217728);
pub const NDIS_RSS_CAPS_RSS_AVAILABLE_ON_PORTS = @as(u32, 268435456);
pub const NDIS_RSS_CAPS_SUPPORTS_MSI_X = @as(u32, 536870912);
pub const NDIS_RSS_CAPS_SUPPORTS_INDEPENDENT_ENTRY_MOVE = @as(u32, 1073741824);
pub const NDIS_RSS_PARAM_FLAG_BASE_CPU_UNCHANGED = @as(u32, 1);
pub const NDIS_RSS_PARAM_FLAG_HASH_INFO_UNCHANGED = @as(u32, 2);
pub const NDIS_RSS_PARAM_FLAG_ITABLE_UNCHANGED = @as(u32, 4);
pub const NDIS_RSS_PARAM_FLAG_HASH_KEY_UNCHANGED = @as(u32, 8);
pub const NDIS_RSS_PARAM_FLAG_DISABLE_RSS = @as(u32, 16);
pub const NDIS_RSS_PARAM_FLAG_DEFAULT_PROCESSOR_UNCHANGED = @as(u32, 32);
pub const NDIS_RSS_INDIRECTION_TABLE_SIZE_REVISION_1 = @as(u32, 128);
pub const NDIS_RSS_HASH_SECRET_KEY_SIZE_REVISION_1 = @as(u32, 40);
pub const NDIS_RECEIVE_SCALE_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_RECEIVE_SCALE_PARAMETERS_REVISION_2 = @as(u32, 2);
pub const NDIS_RECEIVE_SCALE_PARAMETERS_REVISION_3 = @as(u32, 3);
pub const NDIS_RSS_INDIRECTION_TABLE_MAX_SIZE_REVISION_1 = @as(u32, 128);
pub const NDIS_RSS_HASH_SECRET_KEY_MAX_SIZE_REVISION_1 = @as(u32, 40);
pub const NDIS_RSS_HASH_SECRET_KEY_MAX_SIZE_REVISION_2 = @as(u32, 40);
pub const NDIS_RSS_HASH_SECRET_KEY_MAX_SIZE_REVISION_3 = @as(u32, 40);
pub const NDIS_RECEIVE_SCALE_PARAMETERS_V2_REVISION_1 = @as(u32, 1);
pub const NDIS_RECEIVE_SCALE_PARAM_ENABLE_RSS = @as(u32, 1);
pub const NDIS_RECEIVE_SCALE_PARAM_HASH_INFO_CHANGED = @as(u32, 2);
pub const NDIS_RECEIVE_SCALE_PARAM_HASH_KEY_CHANGED = @as(u32, 4);
pub const NDIS_RECEIVE_SCALE_PARAM_NUMBER_OF_QUEUES_CHANGED = @as(u32, 8);
pub const NDIS_RECEIVE_SCALE_PARAM_NUMBER_OF_ENTRIES_CHANGED = @as(u32, 16);
pub const NDIS_RSS_SET_INDIRECTION_ENTRY_FLAG_PRIMARY_PROCESSOR = @as(u32, 1);
pub const NDIS_RSS_SET_INDIRECTION_ENTRY_FLAG_DEFAULT_PROCESSOR = @as(u32, 2);
pub const NDIS_RSS_SET_INDIRECTION_ENTRIES_REVISION_1 = @as(u32, 1);
pub const NDIS_RECEIVE_HASH_FLAG_ENABLE_HASH = @as(u32, 1);
pub const NDIS_RECEIVE_HASH_FLAG_HASH_INFO_UNCHANGED = @as(u32, 2);
pub const NDIS_RECEIVE_HASH_FLAG_HASH_KEY_UNCHANGED = @as(u32, 4);
pub const NDIS_RECEIVE_HASH_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_RSS_PROCESSOR_INFO_REVISION_1 = @as(u32, 1);
pub const NDIS_RSS_PROCESSOR_INFO_REVISION_2 = @as(u32, 2);
pub const NDIS_SYSTEM_PROCESSOR_INFO_EX_REVISION_1 = @as(u32, 1);
pub const NDIS_HYPERVISOR_INFO_FLAG_HYPERVISOR_PRESENT = @as(u32, 1);
pub const NDIS_HYPERVISOR_INFO_REVISION_1 = @as(u32, 1);
pub const NDIS_WMI_RECEIVE_QUEUE_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_WMI_RECEIVE_QUEUE_INFO_REVISION_1 = @as(u32, 1);
pub const NDIS_NDK_CAPABILITIES_REVISION_1 = @as(u32, 1);
pub const OID_NDK_SET_STATE = @as(u32, 4228121089);
pub const OID_NDK_STATISTICS = @as(u32, 4228121090);
pub const OID_NDK_CONNECTIONS = @as(u32, 4228121091);
pub const OID_NDK_LOCAL_ENDPOINTS = @as(u32, 4228121092);
pub const GUID_NDIS_NDK_CAPABILITIES = Guid.initString("7969ba4d-dd80-4bc7-b3e6-68043997e519");
pub const GUID_NDIS_NDK_STATE = Guid.initString("530c69c9-2f51-49de-a1af-088d54ffa474");
pub const NDIS_NDK_STATISTICS_INFO_REVISION_1 = @as(u32, 1);
pub const NDIS_NDK_CONNECTIONS_REVISION_1 = @as(u32, 1);
pub const NDIS_NDK_LOCAL_ENDPOINTS_REVISION_1 = @as(u32, 1);
pub const OID_QOS_HARDWARE_CAPABILITIES = @as(u32, 4228186113);
pub const OID_QOS_CURRENT_CAPABILITIES = @as(u32, 4228186114);
pub const OID_QOS_PARAMETERS = @as(u32, 4228186115);
pub const OID_QOS_OPERATIONAL_PARAMETERS = @as(u32, 4228186116);
pub const OID_QOS_REMOTE_PARAMETERS = @as(u32, 4228186117);
pub const NDIS_QOS_MAXIMUM_PRIORITIES = @as(u32, 8);
pub const NDIS_QOS_MAXIMUM_TRAFFIC_CLASSES = @as(u32, 8);
pub const NDIS_QOS_CAPABILITIES_STRICT_TSA_SUPPORTED = @as(u32, 1);
pub const NDIS_QOS_CAPABILITIES_MACSEC_BYPASS_SUPPORTED = @as(u32, 2);
pub const NDIS_QOS_CAPABILITIES_CEE_DCBX_SUPPORTED = @as(u32, 4);
pub const NDIS_QOS_CAPABILITIES_IEEE_DCBX_SUPPORTED = @as(u32, 8);
pub const NDIS_QOS_CAPABILITIES_REVISION_1 = @as(u32, 1);
pub const NDIS_QOS_CLASSIFICATION_SET_BY_MINIPORT_MASK = @as(u32, 4278190080);
pub const NDIS_QOS_CLASSIFICATION_ENFORCED_BY_MINIPORT = @as(u32, 16777216);
pub const NDIS_QOS_CONDITION_RESERVED = @as(u32, 0);
pub const NDIS_QOS_CONDITION_DEFAULT = @as(u32, 1);
pub const NDIS_QOS_CONDITION_TCP_PORT = @as(u32, 2);
pub const NDIS_QOS_CONDITION_UDP_PORT = @as(u32, 3);
pub const NDIS_QOS_CONDITION_TCP_OR_UDP_PORT = @as(u32, 4);
pub const NDIS_QOS_CONDITION_ETHERTYPE = @as(u32, 5);
pub const NDIS_QOS_CONDITION_NETDIRECT_PORT = @as(u32, 6);
pub const NDIS_QOS_CONDITION_MAXIMUM = @as(u32, 7);
pub const NDIS_QOS_ACTION_PRIORITY = @as(u32, 0);
pub const NDIS_QOS_ACTION_MAXIMUM = @as(u32, 1);
pub const NDIS_QOS_CLASSIFICATION_ELEMENT_REVISION_1 = @as(u32, 1);
pub const NDIS_QOS_PARAMETERS_ETS_CHANGED = @as(u32, 1);
pub const NDIS_QOS_PARAMETERS_ETS_CONFIGURED = @as(u32, 2);
pub const NDIS_QOS_PARAMETERS_PFC_CHANGED = @as(u32, 256);
pub const NDIS_QOS_PARAMETERS_PFC_CONFIGURED = @as(u32, 512);
pub const NDIS_QOS_PARAMETERS_CLASSIFICATION_CHANGED = @as(u32, 65536);
pub const NDIS_QOS_PARAMETERS_CLASSIFICATION_CONFIGURED = @as(u32, 131072);
pub const NDIS_QOS_PARAMETERS_WILLING = @as(u32, 2147483648);
pub const NDIS_QOS_TSA_STRICT = @as(u32, 0);
pub const NDIS_QOS_TSA_CBS = @as(u32, 1);
pub const NDIS_QOS_TSA_ETS = @as(u32, 2);
pub const NDIS_QOS_TSA_MAXIMUM = @as(u32, 3);
pub const NDIS_QOS_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_DEFAULT_VPORT_ID = @as(u32, 0);
pub const NDIS_DEFAULT_SWITCH_ID = @as(u32, 0);
pub const NDIS_NIC_SWITCH_PARAMETERS_CHANGE_MASK = @as(u32, 4294901760);
pub const NDIS_NIC_SWITCH_PARAMETERS_SWITCH_NAME_CHANGED = @as(u32, 65536);
pub const NDIS_NIC_SWITCH_PARAMETERS_DEFAULT_NUMBER_OF_QUEUE_PAIRS_FOR_DEFAULT_VPORT = @as(u32, 1);
pub const NDIS_NIC_SWITCH_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_NIC_SWITCH_PARAMETERS_REVISION_2 = @as(u32, 2);
pub const NDIS_NIC_SWITCH_DELETE_SWITCH_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_NIC_SWITCH_INFO_REVISION_1 = @as(u32, 1);
pub const NDIS_NIC_SWITCH_INFO_ARRAY_REVISION_1 = @as(u32, 1);
pub const NDIS_NIC_SWITCH_VPORT_PARAMS_LOOKAHEAD_SPLIT_ENABLED = @as(u32, 1);
pub const NDIS_NIC_SWITCH_VPORT_PARAMS_PACKET_DIRECT_RX_ONLY = @as(u32, 2);
pub const NDIS_NIC_SWITCH_VPORT_PARAMS_ENFORCE_MAX_SG_LIST = @as(u32, 32768);
pub const NDIS_NIC_SWITCH_VPORT_PARAMS_CHANGE_MASK = @as(u32, 4294901760);
pub const NDIS_NIC_SWITCH_VPORT_PARAMS_FLAGS_CHANGED = @as(u32, 65536);
pub const NDIS_NIC_SWITCH_VPORT_PARAMS_NAME_CHANGED = @as(u32, 131072);
pub const NDIS_NIC_SWITCH_VPORT_PARAMS_INT_MOD_CHANGED = @as(u32, 262144);
pub const NDIS_NIC_SWITCH_VPORT_PARAMS_STATE_CHANGED = @as(u32, 524288);
pub const NDIS_NIC_SWITCH_VPORT_PARAMS_PROCESSOR_AFFINITY_CHANGED = @as(u32, 1048576);
pub const NDIS_NIC_SWITCH_VPORT_PARAMS_NDK_PARAMS_CHANGED = @as(u32, 2097152);
pub const NDIS_NIC_SWITCH_VPORT_PARAMS_QOS_SQ_ID_CHANGED = @as(u32, 4194304);
pub const NDIS_NIC_SWITCH_VPORT_PARAMS_NUM_QUEUE_PAIRS_CHANGED = @as(u32, 8388608);
pub const NDIS_NIC_SWITCH_VPORT_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_NIC_SWITCH_VPORT_PARAMETERS_REVISION_2 = @as(u32, 2);
pub const NDIS_NIC_SWITCH_DELETE_VPORT_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_NIC_SWITCH_VPORT_INFO_LOOKAHEAD_SPLIT_ENABLED = @as(u32, 1);
pub const NDIS_NIC_SWITCH_VPORT_INFO_PACKET_DIRECT_RX_ONLY = @as(u32, 2);
pub const NDIS_NIC_SWITCH_VPORT_INFO_GFT_ENABLED = @as(u32, 4);
pub const NDIS_NIC_SWITCH_VPORT_INFO_REVISION_1 = @as(u32, 1);
pub const NDIS_NIC_SWITCH_VPORT_INFO_ARRAY_ENUM_ON_SPECIFIC_FUNCTION = @as(u32, 1);
pub const NDIS_NIC_SWITCH_VPORT_INFO_ARRAY_ENUM_ON_SPECIFIC_SWITCH = @as(u32, 2);
pub const NDIS_NIC_SWITCH_VPORT_INFO_ARRAY_REVISION_1 = @as(u32, 1);
pub const NDIS_NIC_SWITCH_VF_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_NIC_SWITCH_FREE_VF_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_NIC_SWITCH_VF_INFO_REVISION_1 = @as(u32, 1);
pub const NDIS_NIC_SWITCH_VF_INFO_ARRAY_ENUM_ON_SPECIFIC_SWITCH = @as(u32, 1);
pub const NDIS_NIC_SWITCH_VF_INFO_ARRAY_REVISION_1 = @as(u32, 1);
pub const NDIS_SRIOV_CAPS_SRIOV_SUPPORTED = @as(u32, 1);
pub const NDIS_SRIOV_CAPS_PF_MINIPORT = @as(u32, 2);
pub const NDIS_SRIOV_CAPS_VF_MINIPORT = @as(u32, 4);
pub const NDIS_SRIOV_CAPABILITIES_REVISION_1 = @as(u32, 1);
pub const NDIS_SRIOV_READ_VF_CONFIG_SPACE_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_SRIOV_WRITE_VF_CONFIG_SPACE_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_SRIOV_READ_VF_CONFIG_BLOCK_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_SRIOV_WRITE_VF_CONFIG_BLOCK_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_SRIOV_RESET_VF_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_SRIOV_SET_VF_POWER_STATE_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_SRIOV_CONFIG_STATE_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_SRIOV_VF_VENDOR_DEVICE_ID_INFO_REVISION_1 = @as(u32, 1);
pub const NDIS_SRIOV_PROBED_BARS_INFO_REVISION_1 = @as(u32, 1);
pub const NDIS_RECEIVE_FILTER_MOVE_FILTER_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_SRIOV_BAR_RESOURCES_INFO_REVISION_1 = @as(u32, 1);
pub const NDIS_SRIOV_PF_LUID_INFO_REVISION_1 = @as(u32, 1);
pub const NDIS_SRIOV_VF_SERIAL_NUMBER_INFO_REVISION_1 = @as(u32, 1);
pub const NDIS_SRIOV_VF_INVALIDATE_CONFIG_BLOCK_INFO_REVISION_1 = @as(u32, 1);
pub const NDIS_SRIOV_OVERLYING_ADAPTER_INFO_VERSION_1 = @as(u32, 1);
pub const NDIS_ISOLATION_NAME_MAX_STRING_SIZE = @as(u32, 127);
pub const NDIS_ROUTING_DOMAIN_ISOLATION_ENTRY_REVISION_1 = @as(u32, 1);
pub const NDIS_ROUTING_DOMAIN_ENTRY_REVISION_1 = @as(u32, 1);
pub const NDIS_ISOLATION_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_SWITCH_OBJECT_SERIALIZATION_VERSION_1 = @as(u32, 1);
pub const NDIS_SWITCH_PORT_PROPERTY_SECURITY_REVISION_1 = @as(u32, 1);
pub const NDIS_SWITCH_PORT_PROPERTY_SECURITY_REVISION_2 = @as(u32, 2);
pub const NDIS_SWITCH_PORT_PROPERTY_VLAN_REVISION_1 = @as(u32, 1);
pub const NDIS_SWITCH_PORT_PROPERTY_PROFILE_REVISION_1 = @as(u32, 1);
pub const NDIS_SWITCH_PORT_PROPERTY_ISOLATION_REVISION_1 = @as(u32, 1);
pub const NDIS_SWITCH_PORT_PROPERTY_ROUTING_DOMAIN_REVISION_1 = @as(u32, 1);
pub const NDIS_SWITCH_PORT_PROPERTY_CUSTOM_REVISION_1 = @as(u32, 1);
pub const NDIS_SWITCH_PORT_PROPERTY_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_SWITCH_PORT_PROPERTY_DELETE_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_SWITCH_PORT_PROPERTY_ENUM_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_SWITCH_PORT_PROPERTY_ENUM_INFO_REVISION_1 = @as(u32, 1);
pub const NDIS_SWITCH_PORT_FEATURE_STATUS_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_SWITCH_PORT_FEATURE_STATUS_CUSTOM_REVISION_1 = @as(u32, 1);
pub const NDIS_SWITCH_PROPERTY_CUSTOM_REVISION_1 = @as(u32, 1);
pub const NDIS_SWITCH_PROPERTY_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_SWITCH_PROPERTY_DELETE_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_SWITCH_PROPERTY_ENUM_INFO_REVISION_1 = @as(u32, 1);
pub const NDIS_SWITCH_PROPERTY_ENUM_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_SWITCH_FEATURE_STATUS_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_SWITCH_FEATURE_STATUS_CUSTOM_REVISION_1 = @as(u32, 1);
pub const NDIS_SWITCH_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_SWITCH_PORT_PARAMETERS_FLAG_UNTRUSTED_INTERNAL_PORT = @as(u32, 1);
pub const NDIS_SWITCH_PORT_PARAMETERS_FLAG_RESTORING_PORT = @as(u32, 2);
pub const NDIS_SWITCH_PORT_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_SWITCH_PORT_ARRAY_REVISION_1 = @as(u32, 1);
pub const NDIS_SWITCH_NIC_FLAGS_NIC_INITIALIZING = @as(u32, 1);
pub const NDIS_SWITCH_NIC_FLAGS_NIC_SUSPENDED = @as(u32, 2);
pub const NDIS_SWITCH_NIC_FLAGS_MAPPED_NIC_UPDATED = @as(u32, 4);
pub const NDIS_SWITCH_NIC_FLAGS_NIC_SUSPENDED_LM = @as(u32, 16);
pub const NDIS_SWITCH_NIC_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_SWITCH_NIC_PARAMETERS_REVISION_2 = @as(u32, 2);
pub const NDIS_SWITCH_NIC_ARRAY_REVISION_1 = @as(u32, 1);
pub const NDIS_SWITCH_NIC_OID_REQUEST_REVISION_1 = @as(u32, 1);
pub const NDIS_SWITCH_NIC_SAVE_STATE_REVISION_1 = @as(u32, 1);
pub const NDIS_SWITCH_NIC_SAVE_STATE_REVISION_2 = @as(u32, 2);
pub const NDIS_PORT_STATE_REVISION_1 = @as(u32, 1);
pub const NDIS_PORT_CHAR_USE_DEFAULT_AUTH_SETTINGS = @as(u32, 1);
pub const NDIS_PORT_CHARACTERISTICS_REVISION_1 = @as(u32, 1);
pub const NDIS_PORT_ARRAY_REVISION_1 = @as(u32, 1);
pub const ETHERNET_LENGTH_OF_ADDRESS = @as(u32, 6);
pub const NDIS_GFP_HEADER_PRESENT_ETHERNET = @as(u32, 1);
pub const NDIS_GFP_HEADER_PRESENT_IPV4 = @as(u32, 2);
pub const NDIS_GFP_HEADER_PRESENT_IPV6 = @as(u32, 4);
pub const NDIS_GFP_HEADER_PRESENT_TCP = @as(u32, 8);
pub const NDIS_GFP_HEADER_PRESENT_UDP = @as(u32, 16);
pub const NDIS_GFP_HEADER_PRESENT_ICMP = @as(u32, 32);
pub const NDIS_GFP_HEADER_PRESENT_NO_ENCAP = @as(u32, 64);
pub const NDIS_GFP_HEADER_PRESENT_IP_IN_IP_ENCAP = @as(u32, 128);
pub const NDIS_GFP_HEADER_PRESENT_IP_IN_GRE_ENCAP = @as(u32, 256);
pub const NDIS_GFP_HEADER_PRESENT_NVGRE_ENCAP = @as(u32, 512);
pub const NDIS_GFP_HEADER_PRESENT_VXLAN_ENCAP = @as(u32, 1024);
pub const NDIS_GFP_HEADER_PRESENT_ESP = @as(u32, 2048);
pub const NDIS_GFP_ENCAPSULATION_TYPE_NOT_ENCAPSULATED = @as(u32, 1);
pub const NDIS_GFP_ENCAPSULATION_TYPE_IP_IN_IP = @as(u32, 2);
pub const NDIS_GFP_ENCAPSULATION_TYPE_IP_IN_GRE = @as(u32, 4);
pub const NDIS_GFP_ENCAPSULATION_TYPE_NVGRE = @as(u32, 8);
pub const NDIS_GFP_ENCAPSULATION_TYPE_VXLAN = @as(u32, 16);
pub const NDIS_GFP_UNDEFINED_PROFILE_ID = @as(u32, 0);
pub const NDIS_GFP_HEADER_GROUP_EXACT_MATCH_PROFILE_IS_TTL_ONE = @as(u32, 1);
pub const NDIS_GFP_HEADER_GROUP_EXACT_MATCH_PROFILE_REVISION_1 = @as(u32, 1);
pub const NDIS_GFP_EXACT_MATCH_PROFILE_RDMA_FLOW = @as(u32, 1);
pub const NDIS_GFP_EXACT_MATCH_PROFILE_REVISION_1 = @as(u32, 1);
pub const NDIS_GFP_HEADER_GROUP_EXACT_MATCH_IS_TTL_ONE = @as(u32, 1);
pub const NDIS_GFP_HEADER_GROUP_EXACT_MATCH_REVISION_1 = @as(u32, 1);
pub const NDIS_GFP_HEADER_GROUP_WILDCARD_MATCH_PROFILE_IS_TTL_ONE = @as(u32, 1);
pub const NDIS_GFP_HEADER_GROUP_WILDCARD_MATCH_PROFILE_REVISION_1 = @as(u32, 1);
pub const NDIS_GFP_WILDCARD_MATCH_PROFILE_REVISION_1 = @as(u32, 1);
pub const NDIS_GFP_HEADER_GROUP_WILDCARD_MATCH_IS_TTL_ONE = @as(u32, 1);
pub const NDIS_GFP_HEADER_GROUP_WILDCARD_MATCH_REVISION_1 = @as(u32, 1);
pub const NDIS_PD_CAPS_RECEIVE_FILTER_COUNTERS_SUPPORTED = @as(u32, 1);
pub const NDIS_PD_CAPS_DRAIN_NOTIFICATIONS_SUPPORTED = @as(u32, 2);
pub const NDIS_PD_CAPS_NOTIFICATION_MODERATION_INTERVAL_SUPPORTED = @as(u32, 4);
pub const NDIS_PD_CAPS_NOTIFICATION_MODERATION_COUNT_SUPPORTED = @as(u32, 8);
pub const NDIS_PD_CAPABILITIES_REVISION_1 = @as(u32, 1);
pub const NDIS_PD_CONFIG_REVISION_1 = @as(u32, 1);
pub const NDIS_GFT_UNDEFINED_FLOW_ENTRY_ID = @as(u32, 0);
pub const NDIS_GFT_UNDEFINED_TABLE_ID = @as(u32, 0);
pub const NDIS_GFT_TABLE_INCLUDE_EXTERNAL_VPPORT = @as(u32, 1);
pub const NDIS_GFT_TABLE_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_GFT_TABLE_INFO_REVISION_1 = @as(u32, 1);
pub const NDIS_GFT_TABLE_INFO_ARRAY_REVISION_1 = @as(u32, 1);
pub const NDIS_GFT_DELETE_TABLE_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_GFT_UNDEFINED_COUNTER_ID = @as(u32, 0);
pub const NDIS_GFT_MAX_COUNTER_OBJECTS_PER_FLOW_ENTRY = @as(u32, 8);
pub const NDIS_GFT_COUNTER_PARAMETERS_CLIENT_SPECIFIED_ADDRESS = @as(u32, 1);
pub const NDIS_GFT_COUNTER_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_GFT_FREE_COUNTER_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_GFT_COUNTER_INFO_REVISION_1 = @as(u32, 1);
pub const NDIS_GFT_COUNTER_INFO_ARRAY_REVISION_1 = @as(u32, 1);
pub const NDIS_GFT_COUNTER_VALUE_ARRAY_UPDATE_MEMORY_MAPPED_COUNTERS = @as(u32, 1);
pub const NDIS_GFT_COUNTER_VALUE_ARRAY_GET_VALUES = @as(u32, 2);
pub const NDIS_GFT_COUNTER_VALUE_ARRAY_REVISION_1 = @as(u32, 1);
pub const NDIS_GFT_STATISTICS_REVISION_1 = @as(u32, 1);
pub const NDIS_GFT_HEADER_GROUP_TRANSPOSITION_PROFILE_DECREMENT_TTL_IF_NOT_ONE = @as(u32, 1);
pub const NDIS_GFT_HEADER_GROUP_TRANSPOSITION_PROFILE_REVISION_1 = @as(u32, 1);
pub const NDIS_GFT_UNDEFINED_CUSTOM_ACTION = @as(u32, 0);
pub const NDIS_GFT_RESERVED_CUSTOM_ACTIONS = @as(u32, 256);
pub const NDIS_GFT_CUSTOM_ACTION_PROFILE_REVISION_1 = @as(u32, 1);
pub const NDIS_GFT_HTP_REDIRECT_TO_INGRESS_QUEUE_OF_VPORT = @as(u32, 1);
pub const NDIS_GFT_HTP_REDIRECT_TO_EGRESS_QUEUE_OF_VPORT = @as(u32, 2);
pub const NDIS_GFT_HTP_REDIRECT_TO_INGRESS_QUEUE_OF_VPORT_IF_TTL_IS_ONE = @as(u32, 4);
pub const NDIS_GFT_HTP_REDIRECT_TO_EGRESS_QUEUE_OF_VPORT_IF_TTL_IS_ONE = @as(u32, 8);
pub const NDIS_GFT_HTP_COPY_ALL_PACKETS = @as(u32, 16);
pub const NDIS_GFT_HTP_COPY_FIRST_PACKET = @as(u32, 32);
pub const NDIS_GFT_HTP_COPY_WHEN_TCP_FLAG_SET = @as(u32, 64);
pub const NDIS_GFT_HTP_CUSTOM_ACTION_PRESENT = @as(u32, 128);
pub const NDIS_GFT_HTP_META_ACTION_BEFORE_HEADER_TRANSPOSITION = @as(u32, 256);
pub const NDIS_GFT_HEADER_TRANSPOSITION_PROFILE_REVISION_1 = @as(u32, 1);
pub const NDIS_GFT_HEADER_GROUP_TRANSPOSITION_DECREMENT_TTL_IF_NOT_ONE = @as(u32, 1);
pub const NDIS_GFT_HEADER_GROUP_TRANSPOSITION_REVISION_1 = @as(u32, 1);
pub const NDIS_GFT_CUSTOM_ACTION_LAST_ACTION = @as(u32, 1);
pub const NDIS_GFT_CUSTOM_ACTION_REVISION_1 = @as(u32, 1);
pub const NDIS_GFT_EMFE_ADD_IN_ACTIVATED_STATE = @as(u32, 1);
pub const NDIS_GFT_EMFE_MATCH_AND_ACTION_MUST_BE_SUPPORTED = @as(u32, 2);
pub const NDIS_GFT_EMFE_RDMA_FLOW = @as(u32, 4);
pub const NDIS_GFT_EMFE_REDIRECT_TO_INGRESS_QUEUE_OF_VPORT = @as(u32, 4096);
pub const NDIS_GFT_EMFE_REDIRECT_TO_EGRESS_QUEUE_OF_VPORT = @as(u32, 8192);
pub const NDIS_GFT_EMFE_REDIRECT_TO_INGRESS_QUEUE_OF_VPORT_IF_TTL_IS_ONE = @as(u32, 16384);
pub const NDIS_GFT_EMFE_REDIRECT_TO_EGRESS_QUEUE_OF_VPORT_IF_TTL_IS_ONE = @as(u32, 32768);
pub const NDIS_GFT_EMFE_COPY_ALL_PACKETS = @as(u32, 65536);
pub const NDIS_GFT_EMFE_COPY_FIRST_PACKET = @as(u32, 131072);
pub const NDIS_GFT_EMFE_COPY_WHEN_TCP_FLAG_SET = @as(u32, 262144);
pub const NDIS_GFT_EMFE_CUSTOM_ACTION_PRESENT = @as(u32, 524288);
pub const NDIS_GFT_EMFE_META_ACTION_BEFORE_HEADER_TRANSPOSITION = @as(u32, 1048576);
pub const NDIS_GFT_EMFE_COPY_AFTER_TCP_FIN_FLAG_SET = @as(u32, 2097152);
pub const NDIS_GFT_EMFE_COPY_AFTER_TCP_RST_FLAG_SET = @as(u32, 4194304);
pub const NDIS_GFT_EMFE_COPY_CONDITION_CHANGED = @as(u32, 16777216);
pub const NDIS_GFT_EMFE_ALL_VPORT_FLOW_ENTRIES = @as(u32, 33554432);
pub const NDIS_GFT_EMFE_COUNTER_ALLOCATE = @as(u32, 1);
pub const NDIS_GFT_EMFE_COUNTER_MEMORY_MAPPED = @as(u32, 2);
pub const NDIS_GFT_EMFE_COUNTER_CLIENT_SPECIFIED_ADDRESS = @as(u32, 4);
pub const NDIS_GFT_EMFE_COUNTER_TRACK_TCP_FLOW = @as(u32, 8);
pub const NDIS_GFT_EXACT_MATCH_FLOW_ENTRY_REVISION_1 = @as(u32, 1);
pub const NDIS_GFT_WCFE_ADD_IN_ACTIVATED_STATE = @as(u32, 1);
pub const NDIS_GFT_WCFE_REDIRECT_TO_INGRESS_QUEUE_OF_VPORT = @as(u32, 2);
pub const NDIS_GFT_WCFE_REDIRECT_TO_EGRESS_QUEUE_OF_VPORT = @as(u32, 4);
pub const NDIS_GFT_WCFE_REDIRECT_TO_INGRESS_QUEUE_OF_VPORT_IF_TTL_IS_ONE = @as(u32, 8);
pub const NDIS_GFT_WCFE_REDIRECT_TO_EGRESS_QUEUE_OF_VPORT_IF_TTL_IS_ONE = @as(u32, 16);
pub const NDIS_GFT_WCFE_COPY_ALL_PACKETS = @as(u32, 32);
pub const NDIS_GFT_WCFE_CUSTOM_ACTION_PRESENT = @as(u32, 64);
pub const NDIS_GFT_WCFE_COUNTER_ALLOCATE = @as(u32, 1);
pub const NDIS_GFT_WCFE_COUNTER_MEMORY_MAPPED = @as(u32, 2);
pub const NDIS_GFT_WCFE_COUNTER_CLIENT_SPECIFIED_ADDRESS = @as(u32, 4);
pub const NDIS_GFT_WILDCARD_MATCH_FLOW_ENTRY_REVISION_1 = @as(u32, 1);
pub const NDIS_GFT_PROFILE_INFO_REVISION_1 = @as(u32, 1);
pub const NDIS_GFT_PROFILE_INFO_ARRAY_REVISION_1 = @as(u32, 1);
pub const NDIS_GFT_DELETE_PROFILE_ALL_PROFILES = @as(u32, 1);
pub const NDIS_GFT_DELETE_PROFILE_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_GFT_FLOW_ENTRY_ARRAY_REVISION_1 = @as(u32, 1);
pub const NDIS_GFT_FLOW_ENTRY_INFO_ALL_FLOW_ENTRIES = @as(u32, 1);
pub const NDIS_GFT_FLOW_ENTRY_INFO_ARRAY_REVISION_1 = @as(u32, 1);
pub const NDIS_GFT_FLOW_ENTRY_ID_ALL_NIC_SWITCH_FLOW_ENTRIES = @as(u32, 1);
pub const NDIS_GFT_FLOW_ENTRY_ID_ALL_TABLE_FLOW_ENTRIES = @as(u32, 2);
pub const NDIS_GFT_FLOW_ENTRY_ID_ALL_VPORT_FLOW_ENTRIES = @as(u32, 4);
pub const NDIS_GFT_FLOW_ENTRY_ID_RANGE_DEFINED = @as(u32, 8);
pub const NDIS_GFT_FLOW_ENTRY_ID_ARRAY_DEFINED = @as(u32, 16);
pub const NDIS_GFT_FLOW_ENTRY_ID_ARRAY_COUNTER_VALUES = @as(u32, 65536);
pub const NDIS_GFT_FLOW_ENTRY_ID_ARRAY_REVISION_1 = @as(u32, 1);
pub const NDIS_GFT_OFFLOAD_PARAMETERS_ENABLE_OFFLOAD = @as(u32, 1);
pub const NDIS_GFT_OFFLOAD_PARAMETERS_CUSTOM_PROVIDER_RESERVED = @as(u32, 4278190080);
pub const NDIS_GFT_OFFLOAD_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_GFT_OFFLOAD_CAPS_ADD_FLOW_ENTRY_DEACTIVATED_PREFERRED = @as(u32, 1);
pub const NDIS_GFT_OFFLOAD_CAPS_RATE_LIMITING_QUEUE_SUPPORTED = @as(u32, 2);
pub const NDIS_GFT_OFFLOAD_CAPS_MEMORY_MAPPED_COUNTERS = @as(u32, 1);
pub const NDIS_GFT_OFFLOAD_CAPS_MEMORY_MAPPED_PAKCET_AND_BYTE_COUNTERS = @as(u32, 2);
pub const NDIS_GFT_OFFLOAD_CAPS_PER_FLOW_ENTRY_COUNTERS = @as(u32, 4);
pub const NDIS_GFT_OFFLOAD_CAPS_PER_PACKET_COUNTER_UPDATE = @as(u32, 8);
pub const NDIS_GFT_OFFLOAD_CAPS_CLIENT_SPECIFIED_MEMORY_MAPPED_COUNTERS = @as(u32, 16);
pub const NDIS_GFT_OFFLOAD_CAPS_INGRESS_AGGREGATE_COUNTERS = @as(u32, 32);
pub const NDIS_GFT_OFFLOAD_CAPS_EGRESS_AGGREGATE_COUNTERS = @as(u32, 64);
pub const NDIS_GFT_OFFLOAD_CAPS_TRACK_TCP_FLOW_STATE = @as(u32, 128);
pub const NDIS_GFT_OFFLOAD_CAPS_COMBINED_COUNTER_AND_STATE = @as(u32, 256);
pub const NDIS_GFT_OFFLOAD_CAPS_INGRESS_WILDCARD_MATCH = @as(u32, 1);
pub const NDIS_GFT_OFFLOAD_CAPS_EGRESS_WILDCARD_MATCH = @as(u32, 2);
pub const NDIS_GFT_OFFLOAD_CAPS_INGRESS_EXACT_MATCH = @as(u32, 4);
pub const NDIS_GFT_OFFLOAD_CAPS_EGRESS_EXACT_MATCH = @as(u32, 8);
pub const NDIS_GFT_OFFLOAD_CAPS_EXT_VPORT_INGRESS_WILDCARD_MATCH = @as(u32, 16);
pub const NDIS_GFT_OFFLOAD_CAPS_EXT_VPORT_EGRESS_WILDCARD_MATCH = @as(u32, 32);
pub const NDIS_GFT_OFFLOAD_CAPS_EXT_VPORT_INGRESS_EXACT_MATCH = @as(u32, 64);
pub const NDIS_GFT_OFFLOAD_CAPS_EXT_VPORT_EGRESS_EXACT_MATCH = @as(u32, 128);
pub const NDIS_GFT_OFFLOAD_CAPS_POP = @as(u32, 1);
pub const NDIS_GFT_OFFLOAD_CAPS_PUSH = @as(u32, 2);
pub const NDIS_GFT_OFFLOAD_CAPS_MODIFY = @as(u32, 4);
pub const NDIS_GFT_OFFLOAD_CAPS_IGNORE_ACTION_SUPPORTED = @as(u32, 8);
pub const NDIS_GFT_OFFLOAD_CAPS_REDIRECT_TO_INGRESS_QUEUE_OF_VPORT = @as(u32, 16);
pub const NDIS_GFT_OFFLOAD_CAPS_REDIRECT_TO_EGRESS_QUEUE_OF_VPORT = @as(u32, 32);
pub const NDIS_GFT_OFFLOAD_CAPS_REDIRECT_TO_INGRESS_QUEUE_OF_VPORT_IF_TTL_IS_ONE = @as(u32, 64);
pub const NDIS_GFT_OFFLOAD_CAPS_REDIRECT_TO_EGRESS_QUEUE_OF_VPORT_IF_TTL_IS_ONE = @as(u32, 128);
pub const NDIS_GFT_OFFLOAD_CAPS_COPY_ALL = @as(u32, 256);
pub const NDIS_GFT_OFFLOAD_CAPS_COPY_FIRST = @as(u32, 512);
pub const NDIS_GFT_OFFLOAD_CAPS_COPY_WHEN_TCP_FLAG_SET = @as(u32, 1024);
pub const NDIS_GFT_OFFLOAD_CAPS_SAMPLE = @as(u32, 2048);
pub const NDIS_GFT_OFFLOAD_CAPS_META_ACTION_BEFORE_HEADER_TRANSPOSITION = @as(u32, 4096);
pub const NDIS_GFT_OFFLOAD_CAPS_META_ACTION_AFTER_HEADER_TRANSPOSITION = @as(u32, 8192);
pub const NDIS_GFT_OFFLOAD_CAPS_PER_VPORT_EXCEPTION_VPORT = @as(u32, 16384);
pub const NDIS_GFT_OFFLOAD_CAPS_DESIGNATED_EXCEPTION_VPORT = @as(u32, 32768);
pub const NDIS_GFT_OFFLOAD_CAPS_DSCP_MASK = @as(u32, 65536);
pub const NDIS_GFT_OFFLOAD_CAPS_8021P_PRIORITY_MASK = @as(u32, 131072);
pub const NDIS_GFT_OFFLOAD_CAPS_ALLOW = @as(u32, 262144);
pub const NDIS_GFT_OFFLOAD_CAPS_DROP = @as(u32, 524288);
pub const NDIS_GFT_OFFLOAD_CAPABILITIES_REVISION_1 = @as(u32, 1);
pub const NDIS_GFT_VPORT_ENABLE = @as(u32, 1);
pub const NDIS_GFT_VPORT_PARSE_VXLAN = @as(u32, 2);
pub const NDIS_GFT_VPORT_PARSE_VXLAN_NOT_IN_SRC_PORT_RANGE = @as(u32, 4);
pub const NDIS_GFT_VPORT_ENABLE_STATE_CHANGED = @as(u32, 1048576);
pub const NDIS_GFT_VPORT_EXCEPTION_VPORT_CHANGED = @as(u32, 2097152);
pub const NDIS_GFT_VPORT_SAMPLING_RATE_CHANGED = @as(u32, 4194304);
pub const NDIS_GFT_VPORT_DSCP_MASK_CHANGED = @as(u32, 8388608);
pub const NDIS_GFT_VPORT_PRIORITY_MASK_CHANGED = @as(u32, 16777216);
pub const NDIS_GFT_VPORT_VXLAN_SETTINGS_CHANGED = @as(u32, 33554432);
pub const NDIS_GFT_VPORT_DSCP_FLAGS_CHANGED = @as(u32, 67108864);
pub const NDIS_GFT_VPORT_PARAMS_CHANGE_MASK = @as(u32, 4293918720);
pub const NDIS_GFT_VPORT_PARAMS_CUSTOM_PROVIDER_RESERVED = @as(u32, 1044480);
pub const NDIS_GFT_VPORT_MAX_DSCP_MASK_COUNTER_OBJECTS = @as(u32, 64);
pub const NDIS_GFT_VPORT_MAX_PRIORITY_MASK_COUNTER_OBJECTS = @as(u32, 8);
pub const NDIS_GFT_VPORT_DSCP_GUARD_ENABLE_RX = @as(u32, 1);
pub const NDIS_GFT_VPORT_DSCP_GUARD_ENABLE_TX = @as(u32, 2);
pub const NDIS_GFT_VPORT_DSCP_MASK_ENABLE_RX = @as(u32, 4);
pub const NDIS_GFT_VPORT_DSCP_MASK_ENABLE_TX = @as(u32, 8);
pub const NDIS_GFT_VPORT_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_QOS_DEFAULT_SQ_ID = @as(u32, 0);
pub const NDIS_QOS_SQ_PARAMETERS_REVISION_1 = @as(u32, 1);
pub const NDIS_QOS_SQ_PARAMETERS_REVISION_2 = @as(u32, 2);
pub const NDIS_QOS_SQ_TRANSMIT_CAP_ENABLED = @as(u32, 1);
pub const NDIS_QOS_SQ_TRANSMIT_RESERVATION_ENABLED = @as(u32, 2);
pub const NDIS_QOS_SQ_RECEIVE_CAP_ENABLED = @as(u32, 4);
pub const NDIS_QOS_SQ_PARAMETERS_ARRAY_REVISION_1 = @as(u32, 1);
pub const NDIS_QOS_SQ_ARRAY_REVISION_1 = @as(u32, 1);
pub const NDIS_QOS_OFFLOAD_CAPABILITIES_REVISION_1 = @as(u32, 1);
pub const NDIS_QOS_OFFLOAD_CAPABILITIES_REVISION_2 = @as(u32, 2);
pub const NDIS_QOS_OFFLOAD_CAPS_STANDARD_SQ = @as(u32, 1);
pub const NDIS_QOS_OFFLOAD_CAPS_GFT_SQ = @as(u32, 2);
pub const NDIS_QOS_SQ_STATS_REVISION_1 = @as(u32, 1);
pub const NDIS_TIMESTAMP_CAPABILITIES_REVISION_1 = @as(u32, 1);
pub const OID_TIMESTAMP_CAPABILITY = @as(u32, 10485761);
pub const OID_TIMESTAMP_CURRENT_CONFIG = @as(u32, 10485762);
pub const NDIS_HARDWARE_CROSSTIMESTAMP_REVISION_1 = @as(u32, 1);
pub const OID_TIMESTAMP_GET_CROSSTIMESTAMP = @as(u32, 10485763);
pub const NdisHashFunctionToeplitz = @as(u32, 1);
pub const NdisHashFunctionReserved1 = @as(u32, 2);
pub const NdisHashFunctionReserved2 = @as(u32, 4);
pub const NdisHashFunctionReserved3 = @as(u32, 8);
pub const NDIS_HASH_FUNCTION_MASK = @as(u32, 255);
pub const NDIS_HASH_TYPE_MASK = @as(u32, 16776960);
pub const NDIS_HASH_IPV4 = @as(u32, 256);
pub const NDIS_HASH_TCP_IPV4 = @as(u32, 512);
pub const NDIS_HASH_IPV6 = @as(u32, 1024);
pub const NDIS_HASH_IPV6_EX = @as(u32, 2048);
pub const NDIS_HASH_TCP_IPV6 = @as(u32, 4096);
pub const NDIS_HASH_TCP_IPV6_EX = @as(u32, 8192);
pub const NDIS_HASH_UDP_IPV4 = @as(u32, 16384);
pub const NDIS_HASH_UDP_IPV6 = @as(u32, 32768);
pub const NDIS_HASH_UDP_IPV6_EX = @as(u32, 65536);
pub const NDIS_MAXIMUM_PORTS = @as(u32, 16777216);
pub const NDIS_OBJECT_REVISION_1 = @as(u32, 1);
pub const NDIS_OFFLOAD_NOT_SUPPORTED = @as(u32, 0);
pub const NDIS_OFFLOAD_SUPPORTED = @as(u32, 1);
pub const NDIS_OFFLOAD_SET_NO_CHANGE = @as(u32, 0);
pub const NDIS_OFFLOAD_SET_ON = @as(u32, 1);
pub const NDIS_OFFLOAD_SET_OFF = @as(u32, 2);
pub const NDIS_ENCAPSULATION_NOT_SUPPORTED = @as(u32, 0);
pub const NDIS_ENCAPSULATION_NULL = @as(u32, 1);
pub const NDIS_ENCAPSULATION_IEEE_802_3 = @as(u32, 2);
pub const NDIS_ENCAPSULATION_IEEE_802_3_P_AND_Q = @as(u32, 4);
pub const NDIS_ENCAPSULATION_IEEE_802_3_P_AND_Q_IN_OOB = @as(u32, 8);
pub const NDIS_ENCAPSULATION_IEEE_LLC_SNAP_ROUTED = @as(u32, 16);
pub const NDIS_OBJECT_TYPE_OID_REQUEST = @as(u32, 150);
pub const NDIS_SUPPORT_NDIS686 = @as(u32, 1);
pub const NDIS_SUPPORT_NDIS685 = @as(u32, 1);
pub const NDIS_SUPPORT_NDIS684 = @as(u32, 1);
pub const NDIS_SUPPORT_NDIS683 = @as(u32, 1);
pub const NDIS_SUPPORT_NDIS682 = @as(u32, 1);
pub const NDIS_SUPPORT_NDIS681 = @as(u32, 1);
pub const NDIS_SUPPORT_NDIS680 = @as(u32, 1);
pub const NDIS_SUPPORT_NDIS670 = @as(u32, 1);
pub const NDIS_SUPPORT_NDIS660 = @as(u32, 1);
pub const NDIS_SUPPORT_NDIS651 = @as(u32, 1);
pub const NDIS_SUPPORT_NDIS650 = @as(u32, 1);
pub const NDIS_SUPPORT_NDIS640 = @as(u32, 1);
pub const NDIS_SUPPORT_NDIS630 = @as(u32, 1);
pub const NDIS_SUPPORT_NDIS620 = @as(u32, 1);
pub const NDIS_SUPPORT_NDIS61 = @as(u32, 1);
pub const NDIS_SUPPORT_NDIS6 = @as(u32, 1);
pub const GUID_NDIS_LAN_CLASS = Guid.initString("ad498944-762f-11d0-8dcb-00c04fc3358c");
pub const GUID_DEVINTERFACE_NET = Guid.initString("cac88484-7515-4c03-82e6-71a87abac361");
pub const UNSPECIFIED_NETWORK_GUID = Guid.initString("12ba5bde-143e-4c0d-b66d-2379bb141913");
pub const GUID_DEVINTERFACE_NETUIO = Guid.initString("08336f60-0679-4c6c-85d2-ae7ced65fff7");
pub const GUID_NDIS_ENUMERATE_ADAPTER = Guid.initString("981f2d7f-b1f3-11d0-8dd7-00c04fc3358c");
pub const GUID_NDIS_NOTIFY_ADAPTER_REMOVAL = Guid.initString("981f2d80-b1f3-11d0-8dd7-00c04fc3358c");
pub const GUID_NDIS_NOTIFY_ADAPTER_ARRIVAL = Guid.initString("981f2d81-b1f3-11d0-8dd7-00c04fc3358c");
pub const GUID_NDIS_ENUMERATE_VC = Guid.initString("981f2d82-b1f3-11d0-8dd7-00c04fc3358c");
pub const GUID_NDIS_NOTIFY_VC_REMOVAL = Guid.initString("981f2d79-b1f3-11d0-8dd7-00c04fc3358c");
pub const GUID_NDIS_NOTIFY_VC_ARRIVAL = Guid.initString("182f9e0c-b1f3-11d0-8dd7-00c04fc3358c");
pub const GUID_NDIS_NOTIFY_BIND = Guid.initString("5413531c-b1f3-11d0-8dd7-00c04fc3358c");
pub const GUID_NDIS_NOTIFY_UNBIND = Guid.initString("6e3ce1ec-b1f3-11d0-8dd7-00c04fc3358c");
pub const GUID_NDIS_WAKE_ON_MAGIC_PACKET_ONLY = Guid.initString("a14f1c97-8839-4f8a-9996-a28996ebbf1d");
pub const GUID_NDIS_NOTIFY_DEVICE_POWER_ON = Guid.initString("5f81cfd0-f046-4342-af61-895acedaefd9");
pub const GUID_NDIS_NOTIFY_DEVICE_POWER_OFF = Guid.initString("81bc8189-b026-46ab-b964-f182e342934e");
pub const GUID_NDIS_NOTIFY_FILTER_REMOVAL = Guid.initString("1f177cd9-5955-4721-9f6a-78ebdfaef889");
pub const GUID_NDIS_NOTIFY_FILTER_ARRIVAL = Guid.initString("0b6d3c89-5917-43ca-b578-d01a7967c41c");
pub const GUID_NDIS_NOTIFY_DEVICE_POWER_ON_EX = Guid.initString("2b440188-92ac-4f60-9b2d-20a30cbb6bbe");
pub const GUID_NDIS_NOTIFY_DEVICE_POWER_OFF_EX = Guid.initString("4159353c-5cd7-42ce-8fe4-a45a2380cc4f");
pub const GUID_NDIS_PM_ADMIN_CONFIG = Guid.initString("1528d111-708a-4ca4-9215-c05771161cda");
pub const GUID_NDIS_PM_ACTIVE_CAPABILITIES = Guid.initString("b2cf76e3-b3ae-4394-a01f-338c9870e939");
pub const GUID_NDIS_RSS_ENABLED = Guid.initString("9565cd55-3402-4e32-a5b6-2f143f2f2c30");
pub const GUID_NDIS_GEN_HARDWARE_STATUS = Guid.initString("5ec10354-a61a-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_GEN_MEDIA_SUPPORTED = Guid.initString("5ec10355-a61a-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_GEN_MEDIA_IN_USE = Guid.initString("5ec10356-a61a-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_GEN_MAXIMUM_LOOKAHEAD = Guid.initString("5ec10357-a61a-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_GEN_MAXIMUM_FRAME_SIZE = Guid.initString("5ec10358-a61a-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_GEN_LINK_SPEED = Guid.initString("5ec10359-a61a-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_GEN_TRANSMIT_BUFFER_SPACE = Guid.initString("5ec1035a-a61a-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_GEN_RECEIVE_BUFFER_SPACE = Guid.initString("5ec1035b-a61a-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_GEN_TRANSMIT_BLOCK_SIZE = Guid.initString("5ec1035c-a61a-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_GEN_RECEIVE_BLOCK_SIZE = Guid.initString("5ec1035d-a61a-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_GEN_VENDOR_ID = Guid.initString("5ec1035e-a61a-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_GEN_VENDOR_DESCRIPTION = Guid.initString("5ec1035f-a61a-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_GEN_CURRENT_PACKET_FILTER = Guid.initString("5ec10360-a61a-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_GEN_CURRENT_LOOKAHEAD = Guid.initString("5ec10361-a61a-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_GEN_DRIVER_VERSION = Guid.initString("5ec10362-a61a-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_GEN_MAXIMUM_TOTAL_SIZE = Guid.initString("5ec10363-a61a-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_GEN_MAC_OPTIONS = Guid.initString("5ec10365-a61a-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_GEN_MEDIA_CONNECT_STATUS = Guid.initString("5ec10366-a61a-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_GEN_MAXIMUM_SEND_PACKETS = Guid.initString("5ec10367-a61a-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_GEN_VENDOR_DRIVER_VERSION = Guid.initString("447956f9-a61b-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_GEN_VLAN_ID = Guid.initString("765dc702-c5e8-4b67-843b-3f5a4ff2648b");
pub const GUID_NDIS_GEN_PHYSICAL_MEDIUM = Guid.initString("418ca16d-3937-4208-940a-ec6196278085");
pub const GUID_NDIS_TCP_OFFLOAD_CURRENT_CONFIG = Guid.initString("68542fed-5c74-461e-8934-91c6f9c60960");
pub const GUID_NDIS_TCP_OFFLOAD_HARDWARE_CAPABILITIES = Guid.initString("cd5f1102-590f-4ada-ab65-5b31b1dc0172");
pub const GUID_NDIS_TCP_OFFLOAD_PARAMETERS = Guid.initString("8ead9a22-7f69-4bc6-949a-c8187b074e61");
pub const GUID_NDIS_TCP_CONNECTION_OFFLOAD_CURRENT_CONFIG = Guid.initString("2ee6aef1-0851-458b-bf0d-792343d1cde1");
pub const GUID_NDIS_TCP_CONNECTION_OFFLOAD_HARDWARE_CAPABILITIES = Guid.initString("8ce71f2c-d63a-4390-a487-18fa47262ceb");
pub const GUID_NDIS_RECEIVE_SCALE_CAPABILITIES = Guid.initString("26c28774-4252-48fe-a610-a58a398c0eb1");
pub const GUID_NDIS_GEN_LINK_STATE = Guid.initString("ba1f4c14-a945-4762-b916-0b5515b6f43a");
pub const GUID_NDIS_GEN_LINK_PARAMETERS = Guid.initString("8c7d3579-252b-4614-82c5-a650daa15049");
pub const GUID_NDIS_GEN_STATISTICS = Guid.initString("368c45b5-c129-43c1-939e-7edc2d7fe621");
pub const GUID_NDIS_GEN_PORT_STATE = Guid.initString("6fbf2a5f-8b8f-4920-8143-e6c460f52524");
pub const GUID_NDIS_GEN_ENUMERATE_PORTS = Guid.initString("f1d6abe8-15e4-4407-81b7-6b830c777cd9");
pub const GUID_NDIS_ENUMERATE_ADAPTERS_EX = Guid.initString("16716917-4306-4be4-9b5a-3809ae44b125");
pub const GUID_NDIS_GEN_PORT_AUTHENTICATION_PARAMETERS = Guid.initString("aab6ac31-86fb-48fb-8b48-63db235ace16");
pub const GUID_NDIS_GEN_INTERRUPT_MODERATION = Guid.initString("d9c8eea5-f16e-467c-84d5-6345a22ce213");
pub const GUID_NDIS_GEN_INTERRUPT_MODERATION_PARAMETERS = Guid.initString("d789adfa-9c56-433b-ad01-7574f3cedbe9");
pub const GUID_NDIS_GEN_PCI_DEVICE_CUSTOM_PROPERTIES = Guid.initString("aa39f5ab-e260-4d01-82b0-b737c880ea05");
pub const GUID_NDIS_GEN_PHYSICAL_MEDIUM_EX = Guid.initString("899e7782-035b-43f9-8bb6-2b58971612e5");
pub const GUID_NDIS_HD_SPLIT_CURRENT_CONFIG = Guid.initString("81d1303c-ab00-4e49-80b1-5e6e0bf9be53");
pub const GUID_NDIS_HD_SPLIT_PARAMETERS = Guid.initString("8c048bea-2913-4458-b68e-17f6c1e5c60e");
pub const GUID_NDIS_TCP_RSC_STATISTICS = Guid.initString("83104445-9b5d-4ee6-a2a5-2bd3fb3c36af");
pub const GUID_PM_HARDWARE_CAPABILITIES = Guid.initString("ece5360d-3291-4a6e-8044-00511fed27ee");
pub const GUID_PM_CURRENT_CAPABILITIES = Guid.initString("3abdbd14-d44a-4a3f-9a63-a0a42a51b131");
pub const GUID_PM_PARAMETERS = Guid.initString("560245d2-e251-409c-a280-311935be3b28");
pub const GUID_PM_ADD_WOL_PATTERN = Guid.initString("6fc83ba7-52bc-4faa-ac51-7d2ffe63ba90");
pub const GUID_PM_REMOVE_WOL_PATTERN = Guid.initString("a037a915-c6ca-4322-b3e3-ef754ec498dc");
pub const GUID_PM_WOL_PATTERN_LIST = Guid.initString("4022be37-7ee2-47be-a5a5-050fc79afc75");
pub const GUID_PM_ADD_PROTOCOL_OFFLOAD = Guid.initString("0c06c112-0d93-439b-9e6d-26be130c9784");
pub const GUID_PM_GET_PROTOCOL_OFFLOAD = Guid.initString("a6435cd9-149f-498e-951b-2d94bea3e3a3");
pub const GUID_PM_REMOVE_PROTOCOL_OFFLOAD = Guid.initString("decd7be2-a6b0-43ca-ae45-d000d20e5265");
pub const GUID_PM_PROTOCOL_OFFLOAD_LIST = Guid.initString("736ec5ab-ca8f-4043-bb58-da402a48d9cc");
pub const GUID_NDIS_RECEIVE_FILTER_HARDWARE_CAPABILITIES = Guid.initString("3f2c1419-83bc-11dd-94b8-001d09162bc3");
pub const GUID_NDIS_RECEIVE_FILTER_GLOBAL_PARAMETERS = Guid.initString("3f2c141a-83bc-11dd-94b8-001d09162bc3");
pub const GUID_NDIS_RECEIVE_FILTER_ENUM_QUEUES = Guid.initString("3f2c141b-83bc-11dd-94b8-001d09162bc3");
pub const GUID_NDIS_RECEIVE_FILTER_QUEUE_PARAMETERS = Guid.initString("3f2c141c-83bc-11dd-94b8-001d09162bc3");
pub const GUID_NDIS_RECEIVE_FILTER_ENUM_FILTERS = Guid.initString("3f2c141d-83bc-11dd-94b8-001d09162bc3");
pub const GUID_NDIS_RECEIVE_FILTER_PARAMETERS = Guid.initString("3f2c141e-83bc-11dd-94b8-001d09162bc3");
pub const GUID_RECEIVE_FILTER_CURRENT_CAPABILITIES = Guid.initString("4054e80f-2bc1-4ccc-b033-4abc0c4a1e8c");
pub const GUID_NIC_SWITCH_HARDWARE_CAPABILITIES = Guid.initString("37cab40c-d1e8-4301-8c1d-58465e0c4c0f");
pub const GUID_NIC_SWITCH_CURRENT_CAPABILITIES = Guid.initString("e76fdaf3-0be7-4d95-87e9-5aead4b590e9");
pub const GUID_NDIS_SWITCH_MICROSOFT_VENDOR_ID = Guid.initString("202547fe-1c9c-40b9-bba1-08ada1f98b3c");
pub const GUID_NDIS_SWITCH_PORT_PROPERTY_PROFILE_ID_DEFAULT_EXTERNAL_NIC = Guid.initString("0b347846-0a0c-470a-9b7a-0d965850698f");
pub const GUID_NDIS_GEN_XMIT_OK = Guid.initString("447956fa-a61b-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_GEN_RCV_OK = Guid.initString("447956fb-a61b-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_GEN_XMIT_ERROR = Guid.initString("447956fc-a61b-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_GEN_RCV_ERROR = Guid.initString("447956fd-a61b-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_GEN_RCV_NO_BUFFER = Guid.initString("447956fe-a61b-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_GEN_CO_HARDWARE_STATUS = Guid.initString("791ad192-e35c-11d0-9692-00c04fc3358c");
pub const GUID_NDIS_GEN_CO_MEDIA_SUPPORTED = Guid.initString("791ad193-e35c-11d0-9692-00c04fc3358c");
pub const GUID_NDIS_GEN_CO_MEDIA_IN_USE = Guid.initString("791ad194-e35c-11d0-9692-00c04fc3358c");
pub const GUID_NDIS_GEN_CO_LINK_SPEED = Guid.initString("791ad195-e35c-11d0-9692-00c04fc3358c");
pub const GUID_NDIS_GEN_CO_VENDOR_ID = Guid.initString("791ad196-e35c-11d0-9692-00c04fc3358c");
pub const GUID_NDIS_GEN_CO_VENDOR_DESCRIPTION = Guid.initString("791ad197-e35c-11d0-9692-00c04fc3358c");
pub const GUID_NDIS_GEN_CO_DRIVER_VERSION = Guid.initString("791ad198-e35c-11d0-9692-00c04fc3358c");
pub const GUID_NDIS_GEN_CO_MAC_OPTIONS = Guid.initString("791ad19a-e35c-11d0-9692-00c04fc3358c");
pub const GUID_NDIS_GEN_CO_MEDIA_CONNECT_STATUS = Guid.initString("791ad19b-e35c-11d0-9692-00c04fc3358c");
pub const GUID_NDIS_GEN_CO_VENDOR_DRIVER_VERSION = Guid.initString("791ad19c-e35c-11d0-9692-00c04fc3358c");
pub const GUID_NDIS_GEN_CO_MINIMUM_LINK_SPEED = Guid.initString("791ad19d-e35c-11d0-9692-00c04fc3358c");
pub const GUID_NDIS_GEN_CO_XMIT_PDUS_OK = Guid.initString("0a214805-e35f-11d0-9692-00c04fc3358c");
pub const GUID_NDIS_GEN_CO_RCV_PDUS_OK = Guid.initString("0a214806-e35f-11d0-9692-00c04fc3358c");
pub const GUID_NDIS_GEN_CO_XMIT_PDUS_ERROR = Guid.initString("0a214807-e35f-11d0-9692-00c04fc3358c");
pub const GUID_NDIS_GEN_CO_RCV_PDUS_ERROR = Guid.initString("0a214808-e35f-11d0-9692-00c04fc3358c");
pub const GUID_NDIS_GEN_CO_RCV_PDUS_NO_BUFFER = Guid.initString("0a214809-e35f-11d0-9692-00c04fc3358c");
pub const GUID_NDIS_802_3_PERMANENT_ADDRESS = Guid.initString("447956ff-a61b-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_802_3_CURRENT_ADDRESS = Guid.initString("44795700-a61b-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_802_3_MULTICAST_LIST = Guid.initString("44795701-a61b-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_802_3_MAXIMUM_LIST_SIZE = Guid.initString("44795702-a61b-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_802_3_MAC_OPTIONS = Guid.initString("44795703-a61b-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_802_3_RCV_ERROR_ALIGNMENT = Guid.initString("44795704-a61b-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_802_3_XMIT_ONE_COLLISION = Guid.initString("44795705-a61b-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_802_3_XMIT_MORE_COLLISIONS = Guid.initString("44795706-a61b-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_802_5_PERMANENT_ADDRESS = Guid.initString("44795707-a61b-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_802_5_CURRENT_ADDRESS = Guid.initString("44795708-a61b-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_802_5_CURRENT_FUNCTIONAL = Guid.initString("44795709-a61b-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_802_5_CURRENT_GROUP = Guid.initString("4479570a-a61b-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_802_5_LAST_OPEN_STATUS = Guid.initString("4479570b-a61b-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_802_5_CURRENT_RING_STATUS = Guid.initString("890a36ec-a61c-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_802_5_CURRENT_RING_STATE = Guid.initString("acf14032-a61c-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_802_5_LINE_ERRORS = Guid.initString("acf14033-a61c-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_802_5_LOST_FRAMES = Guid.initString("acf14034-a61c-11d0-8dd4-00c04fc3358c");
pub const GUID_NDIS_802_11_BSSID = Guid.initString("2504b6c2-1fa5-11d4-97eb-00c04f79c403");
pub const GUID_NDIS_802_11_SSID = Guid.initString("7d2a90ea-2041-11d4-97eb-00c04f79c403");
pub const GUID_NDIS_802_11_NETWORK_TYPES_SUPPORTED = Guid.initString("8531d6e6-2041-11d4-97eb-00c04f79c403");
pub const GUID_NDIS_802_11_NETWORK_TYPE_IN_USE = Guid.initString("857e2326-2041-11d4-97eb-00c04f79c403");
pub const GUID_NDIS_802_11_POWER_MODE = Guid.initString("85be837c-2041-11d4-97eb-00c04f79c403");
pub const GUID_NDIS_802_11_TX_POWER_LEVEL = Guid.initString("11e6ba76-2053-11d4-97eb-00c04f79c403");
pub const GUID_NDIS_802_11_RSSI = Guid.initString("1507db16-2053-11d4-97eb-00c04f79c403");
pub const GUID_NDIS_802_11_RSSI_TRIGGER = Guid.initString("155689b8-2053-11d4-97eb-00c04f79c403");
pub const GUID_NDIS_802_11_BSSID_LIST = Guid.initString("69526f9a-2062-11d4-97eb-00c04f79c403");
pub const GUID_NDIS_802_11_INFRASTRUCTURE_MODE = Guid.initString("697d5a7e-2062-11d4-97eb-00c04f79c403");
pub const GUID_NDIS_802_11_FRAGMENTATION_THRESHOLD = Guid.initString("69aaa7c4-2062-11d4-97eb-00c04f79c403");
pub const GUID_NDIS_802_11_RTS_THRESHOLD = Guid.initString("0134d07e-2064-11d4-97eb-00c04f79c403");
pub const GUID_NDIS_802_11_NUMBER_OF_ANTENNAS = Guid.initString("01779336-2064-11d4-97eb-00c04f79c403");
pub const GUID_NDIS_802_11_RX_ANTENNA_SELECTED = Guid.initString("01ac07a2-2064-11d4-97eb-00c04f79c403");
pub const GUID_NDIS_802_11_TX_ANTENNA_SELECTED = Guid.initString("01dbb74a-2064-11d4-97eb-00c04f79c403");
pub const GUID_NDIS_802_11_SUPPORTED_RATES = Guid.initString("49db8722-2068-11d4-97eb-00c04f79c403");
pub const GUID_NDIS_802_11_DESIRED_RATES = Guid.initString("452ee08e-2536-11d4-97eb-00c04f79c403");
pub const GUID_NDIS_802_11_CONFIGURATION = Guid.initString("4a4df982-2068-11d4-97eb-00c04f79c403");
pub const GUID_NDIS_802_11_STATISTICS = Guid.initString("42bb73b0-2129-11d4-97eb-00c04f79c403");
pub const GUID_NDIS_802_11_ADD_WEP = Guid.initString("4307bff0-2129-11d4-97eb-00c04f79c403");
pub const GUID_NDIS_802_11_REMOVE_WEP = Guid.initString("433c345c-2129-11d4-97eb-00c04f79c403");
pub const GUID_NDIS_802_11_DISASSOCIATE = Guid.initString("43671f40-2129-11d4-97eb-00c04f79c403");
pub const GUID_NDIS_802_11_AUTHENTICATION_MODE = Guid.initString("43920a24-2129-11d4-97eb-00c04f79c403");
pub const GUID_NDIS_802_11_PRIVACY_FILTER = Guid.initString("6733c4e9-4792-11d4-97f1-00c04f79c403");
pub const GUID_NDIS_802_11_BSSID_LIST_SCAN = Guid.initString("0d9e01e1-ba70-11d4-b675-002048570337");
pub const GUID_NDIS_802_11_WEP_STATUS = Guid.initString("b027a21f-3cfa-4125-800b-3f7a18fddcdc");
pub const GUID_NDIS_802_11_RELOAD_DEFAULTS = Guid.initString("748b14e8-32ee-4425-b91b-c9848c58b55a");
pub const GUID_NDIS_802_11_ADD_KEY = Guid.initString("ab8b5a62-1d51-49d8-ba5c-fa980be03a1d");
pub const GUID_NDIS_802_11_REMOVE_KEY = Guid.initString("73cb28e9-3188-42d5-b553-b21237e6088c");
pub const GUID_NDIS_802_11_ASSOCIATION_INFORMATION = Guid.initString("a08d4dd0-960e-40bd-8cf6-c538af98f2e3");
pub const GUID_NDIS_802_11_TEST = Guid.initString("4b9ca16a-6a60-4e9d-920c-6335953fa0b5");
pub const GUID_NDIS_802_11_MEDIA_STREAM_MODE = Guid.initString("0a56af66-d84b-49eb-a28d-5282cbb6d0cd");
pub const GUID_NDIS_STATUS_RESET_START = Guid.initString("981f2d76-b1f3-11d0-8dd7-00c04fc3358c");
pub const GUID_NDIS_STATUS_RESET_END = Guid.initString("981f2d77-b1f3-11d0-8dd7-00c04fc3358c");
pub const GUID_NDIS_STATUS_MEDIA_CONNECT = Guid.initString("981f2d7d-b1f3-11d0-8dd7-00c04fc3358c");
pub const GUID_NDIS_STATUS_MEDIA_DISCONNECT = Guid.initString("981f2d7e-b1f3-11d0-8dd7-00c04fc3358c");
pub const GUID_NDIS_STATUS_MEDIA_SPECIFIC_INDICATION = Guid.initString("981f2d84-b1f3-11d0-8dd7-00c04fc3358c");
pub const GUID_NDIS_STATUS_LINK_SPEED_CHANGE = Guid.initString("981f2d85-b1f3-11d0-8dd7-00c04fc3358c");
pub const GUID_NDIS_STATUS_PACKET_FILTER = Guid.initString("d47c5407-2e75-46dd-8146-1d7ed2d6ab1d");
pub const GUID_NDIS_STATUS_NETWORK_CHANGE = Guid.initString("ca8a56f9-ce81-40e6-a70f-a067a476e9e9");
pub const GUID_NDIS_STATUS_TASK_OFFLOAD_CURRENT_CONFIG = Guid.initString("45049fc6-54d8-40c8-9c3d-b011c4e715bc");
pub const GUID_NDIS_STATUS_TASK_OFFLOAD_HARDWARE_CAPABILITIES = Guid.initString("b6b8158b-217c-4b2a-be86-6a04beea65b8");
pub const GUID_NDIS_STATUS_TCP_CONNECTION_OFFLOAD_CURRENT_CONFIG = Guid.initString("f8edaeff-24e4-4ae6-a413-0b27f76b243d");
pub const GUID_NDIS_STATUS_TCP_CONNECTION_OFFLOAD_HARDWARE_CAPABILITIES = Guid.initString("391969b6-402c-43bf-8922-39eae0da1bb5");
pub const GUID_NDIS_STATUS_OPER_STATUS = Guid.initString("f917b663-845e-4d3d-b6d4-15eb27af81c5");
pub const GUID_NDIS_STATUS_LINK_STATE = Guid.initString("64c6f797-878c-4311-9246-65dba89c3a61");
pub const GUID_NDIS_STATUS_PORT_STATE = Guid.initString("1dac0dfe-43e5-44b7-b759-7bf46de32e81");
pub const GUID_NDIS_STATUS_EXTERNAL_CONNECTIVITY_CHANGE = Guid.initString("fd306974-c420-4433-b0fe-4cf6a613f59f");
pub const GUID_STATUS_MEDIA_SPECIFIC_INDICATION_EX = Guid.initString("aaacfca7-954a-4632-a16e-a8a63793a9e5");
pub const GUID_NDIS_STATUS_HD_SPLIT_CURRENT_CONFIG = Guid.initString("6c744b0e-ee9c-4205-90a2-015f6d65f403");
pub const GUID_NDIS_STATUS_PM_WOL_PATTERN_REJECTED = Guid.initString("f72cf68e-18d4-4d63-9a19-e69b13916b1a");
pub const GUID_NDIS_STATUS_PM_OFFLOAD_REJECTED = Guid.initString("add1d481-711e-4d1a-92ca-a62db9329712");
pub const GUID_NDIS_STATUS_PM_WAKE_REASON = Guid.initString("0933fd58-ca62-438f-83da-dfc1cccb8145");
pub const GUID_NDIS_STATUS_DOT11_SCAN_CONFIRM = Guid.initString("8500591e-a0c7-4efb-9342-b674b002cbe6");
pub const GUID_NDIS_STATUS_DOT11_MPDU_MAX_LENGTH_CHANGED = Guid.initString("1d6560ec-8e48-4a3e-9fd5-a01b698db6c5");
pub const GUID_NDIS_STATUS_DOT11_ASSOCIATION_START = Guid.initString("3927843b-6980-4b48-b15b-4de50977ac40");
pub const GUID_NDIS_STATUS_DOT11_ASSOCIATION_COMPLETION = Guid.initString("458bbea7-45a4-4ae2-b176-e51f96fc0568");
pub const GUID_NDIS_STATUS_DOT11_CONNECTION_START = Guid.initString("7b74299d-998f-4454-ad08-c5af28576d1b");
pub const GUID_NDIS_STATUS_DOT11_CONNECTION_COMPLETION = Guid.initString("96efd9c9-7f1b-4a89-bc04-3e9e271765f1");
pub const GUID_NDIS_STATUS_DOT11_ROAMING_START = Guid.initString("b2412d0d-26c8-4f4e-93df-f7b705a0b433");
pub const GUID_NDIS_STATUS_DOT11_ROAMING_COMPLETION = Guid.initString("dd9d47d1-282b-41e4-b924-66368817fcd3");
pub const GUID_NDIS_STATUS_DOT11_DISASSOCIATION = Guid.initString("3fbeb6fc-0fe2-43fd-b2ad-bd99b5f93e13");
pub const GUID_NDIS_STATUS_DOT11_TKIPMIC_FAILURE = Guid.initString("442c2ae4-9bc5-4b90-a889-455ef220f4ee");
pub const GUID_NDIS_STATUS_DOT11_PMKID_CANDIDATE_LIST = Guid.initString("26d8b8f6-db82-49eb-8bf3-4c130ef06950");
pub const GUID_NDIS_STATUS_DOT11_PHY_STATE_CHANGED = Guid.initString("deb45316-71b5-4736-bdef-0a9e9f4e62dc");
pub const GUID_NDIS_STATUS_DOT11_LINK_QUALITY = Guid.initString("a3285184-ea99-48ed-825e-a426b11c2754");
pub const NDK_ADAPTER_FLAG_IN_ORDER_DMA_SUPPORTED = @as(u32, 1);
pub const NDK_ADAPTER_FLAG_RDMA_READ_SINK_NOT_REQUIRED = @as(u32, 2);
pub const NDK_ADAPTER_FLAG_CQ_INTERRUPT_MODERATION_SUPPORTED = @as(u32, 4);
pub const NDK_ADAPTER_FLAG_MULTI_ENGINE_SUPPORTED = @as(u32, 8);
pub const NDK_ADAPTER_FLAG_RDMA_READ_LOCAL_INVALIDATE_SUPPORTED = @as(u32, 16);
pub const NDK_ADAPTER_FLAG_CQ_RESIZE_SUPPORTED = @as(u32, 256);
pub const NDK_ADAPTER_FLAG_LOOPBACK_CONNECTIONS_SUPPORTED = @as(u32, 65536);
pub const DOT11EXT_PSK_MAX_LENGTH = @as(u32, 64);
pub const WDIAG_IHV_WLAN_ID_FLAG_SECURITY_ENABLED = @as(u32, 1);
pub const MS_MAX_PROFILE_NAME_LENGTH = @as(u32, 256);
pub const MS_PROFILE_GROUP_POLICY = @as(u32, 1);
pub const MS_PROFILE_USER = @as(u32, 2);
//--------------------------------------------------------------------------------
// Section: Types (204)
//--------------------------------------------------------------------------------
pub const NDIS_REQUEST_TYPE = enum(i32) {
QueryInformation = 0,
SetInformation = 1,
QueryStatistics = 2,
Open = 3,
Close = 4,
Send = 5,
TransferData = 6,
Reset = 7,
Generic1 = 8,
Generic2 = 9,
Generic3 = 10,
Generic4 = 11,
};
pub const NdisRequestQueryInformation = NDIS_REQUEST_TYPE.QueryInformation;
pub const NdisRequestSetInformation = NDIS_REQUEST_TYPE.SetInformation;
pub const NdisRequestQueryStatistics = NDIS_REQUEST_TYPE.QueryStatistics;
pub const NdisRequestOpen = NDIS_REQUEST_TYPE.Open;
pub const NdisRequestClose = NDIS_REQUEST_TYPE.Close;
pub const NdisRequestSend = NDIS_REQUEST_TYPE.Send;
pub const NdisRequestTransferData = NDIS_REQUEST_TYPE.TransferData;
pub const NdisRequestReset = NDIS_REQUEST_TYPE.Reset;
pub const NdisRequestGeneric1 = NDIS_REQUEST_TYPE.Generic1;
pub const NdisRequestGeneric2 = NDIS_REQUEST_TYPE.Generic2;
pub const NdisRequestGeneric3 = NDIS_REQUEST_TYPE.Generic3;
pub const NdisRequestGeneric4 = NDIS_REQUEST_TYPE.Generic4;
pub const NDIS_STATISTICS_VALUE = extern struct {
Oid: u32,
DataLength: u32,
Data: [1]u8,
};
pub const NDIS_STATISTICS_VALUE_EX = extern struct {
Oid: u32,
DataLength: u32,
Length: u32,
Data: [1]u8,
};
pub const NDIS_VAR_DATA_DESC = extern struct {
Length: u16,
MaximumLength: u16,
Offset: usize,
};
pub const NDIS_OBJECT_HEADER = extern struct {
Type: u8,
Revision: u8,
Size: u16,
};
pub const NDIS_STATISTICS_INFO = extern struct {
Header: NDIS_OBJECT_HEADER,
SupportedStatistics: u32,
ifInDiscards: u64,
ifInErrors: u64,
ifHCInOctets: u64,
ifHCInUcastPkts: u64,
ifHCInMulticastPkts: u64,
ifHCInBroadcastPkts: u64,
ifHCOutOctets: u64,
ifHCOutUcastPkts: u64,
ifHCOutMulticastPkts: u64,
ifHCOutBroadcastPkts: u64,
ifOutErrors: u64,
ifOutDiscards: u64,
ifHCInUcastOctets: u64,
ifHCInMulticastOctets: u64,
ifHCInBroadcastOctets: u64,
ifHCOutUcastOctets: u64,
ifHCOutMulticastOctets: u64,
ifHCOutBroadcastOctets: u64,
};
pub const NDIS_INTERRUPT_MODERATION = enum(i32) {
Unknown = 0,
NotSupported = 1,
Enabled = 2,
Disabled = 3,
};
pub const NdisInterruptModerationUnknown = NDIS_INTERRUPT_MODERATION.Unknown;
pub const NdisInterruptModerationNotSupported = NDIS_INTERRUPT_MODERATION.NotSupported;
pub const NdisInterruptModerationEnabled = NDIS_INTERRUPT_MODERATION.Enabled;
pub const NdisInterruptModerationDisabled = NDIS_INTERRUPT_MODERATION.Disabled;
pub const NDIS_INTERRUPT_MODERATION_PARAMETERS = extern struct {
Header: NDIS_OBJECT_HEADER,
Flags: u32,
InterruptModeration: NDIS_INTERRUPT_MODERATION,
};
pub const NDIS_TIMEOUT_DPC_REQUEST_CAPABILITIES = extern struct {
Header: NDIS_OBJECT_HEADER,
Flags: u32,
TimeoutArrayLength: u32,
TimeoutArray: [1]u32,
};
pub const NDIS_PCI_DEVICE_CUSTOM_PROPERTIES = extern struct {
Header: NDIS_OBJECT_HEADER,
DeviceType: u32,
CurrentSpeedAndMode: u32,
CurrentPayloadSize: u32,
MaxPayloadSize: u32,
MaxReadRequestSize: u32,
CurrentLinkSpeed: u32,
CurrentLinkWidth: u32,
MaxLinkSpeed: u32,
MaxLinkWidth: u32,
PciExpressVersion: u32,
InterruptType: u32,
MaxInterruptMessages: u32,
};
pub const NDIS_802_11_STATUS_TYPE = enum(i32) {
_Authentication = 0,
_MediaStreamMode = 1,
_PMKID_CandidateList = 2,
Max = 3,
};
pub const Ndis802_11StatusType_Authentication = NDIS_802_11_STATUS_TYPE._Authentication;
pub const Ndis802_11StatusType_MediaStreamMode = NDIS_802_11_STATUS_TYPE._MediaStreamMode;
pub const Ndis802_11StatusType_PMKID_CandidateList = NDIS_802_11_STATUS_TYPE._PMKID_CandidateList;
pub const Ndis802_11StatusTypeMax = NDIS_802_11_STATUS_TYPE.Max;
pub const NDIS_802_11_STATUS_INDICATION = extern struct {
StatusType: NDIS_802_11_STATUS_TYPE,
};
pub const NDIS_802_11_AUTHENTICATION_REQUEST = extern struct {
Length: u32,
Bssid: [6]u8,
Flags: u32,
};
pub const PMKID_CANDIDATE = extern struct {
BSSID: [6]u8,
Flags: u32,
};
pub const NDIS_802_11_PMKID_CANDIDATE_LIST = extern struct {
Version: u32,
NumCandidates: u32,
CandidateList: [1]PMKID_CANDIDATE,
};
pub const NDIS_802_11_NETWORK_TYPE = enum(i32) {
FH = 0,
DS = 1,
OFDM5 = 2,
OFDM24 = 3,
Automode = 4,
NetworkTypeMax = 5,
};
pub const Ndis802_11FH = NDIS_802_11_NETWORK_TYPE.FH;
pub const Ndis802_11DS = NDIS_802_11_NETWORK_TYPE.DS;
pub const Ndis802_11OFDM5 = NDIS_802_11_NETWORK_TYPE.OFDM5;
pub const Ndis802_11OFDM24 = NDIS_802_11_NETWORK_TYPE.OFDM24;
pub const Ndis802_11Automode = NDIS_802_11_NETWORK_TYPE.Automode;
pub const Ndis802_11NetworkTypeMax = NDIS_802_11_NETWORK_TYPE.NetworkTypeMax;
pub const NDIS_802_11_NETWORK_TYPE_LIST = extern struct {
NumberOfItems: u32,
NetworkType: [1]NDIS_802_11_NETWORK_TYPE,
};
pub const NDIS_802_11_POWER_MODE = enum(i32) {
CAM = 0,
MAX_PSP = 1,
Fast_PSP = 2,
Max = 3,
};
pub const Ndis802_11PowerModeCAM = NDIS_802_11_POWER_MODE.CAM;
pub const Ndis802_11PowerModeMAX_PSP = NDIS_802_11_POWER_MODE.MAX_PSP;
pub const Ndis802_11PowerModeFast_PSP = NDIS_802_11_POWER_MODE.Fast_PSP;
pub const Ndis802_11PowerModeMax = NDIS_802_11_POWER_MODE.Max;
pub const NDIS_802_11_CONFIGURATION_FH = extern struct {
Length: u32,
HopPattern: u32,
HopSet: u32,
DwellTime: u32,
};
pub const NDIS_802_11_CONFIGURATION = extern struct {
Length: u32,
BeaconPeriod: u32,
ATIMWindow: u32,
DSConfig: u32,
FHConfig: NDIS_802_11_CONFIGURATION_FH,
};
pub const NDIS_802_11_STATISTICS = extern struct {
Length: u32,
TransmittedFragmentCount: LARGE_INTEGER,
MulticastTransmittedFrameCount: LARGE_INTEGER,
FailedCount: LARGE_INTEGER,
RetryCount: LARGE_INTEGER,
MultipleRetryCount: LARGE_INTEGER,
RTSSuccessCount: LARGE_INTEGER,
RTSFailureCount: LARGE_INTEGER,
ACKFailureCount: LARGE_INTEGER,
FrameDuplicateCount: LARGE_INTEGER,
ReceivedFragmentCount: LARGE_INTEGER,
MulticastReceivedFrameCount: LARGE_INTEGER,
FCSErrorCount: LARGE_INTEGER,
TKIPLocalMICFailures: LARGE_INTEGER,
TKIPICVErrorCount: LARGE_INTEGER,
TKIPCounterMeasuresInvoked: LARGE_INTEGER,
TKIPReplays: LARGE_INTEGER,
CCMPFormatErrors: LARGE_INTEGER,
CCMPReplays: LARGE_INTEGER,
CCMPDecryptErrors: LARGE_INTEGER,
FourWayHandshakeFailures: LARGE_INTEGER,
WEPUndecryptableCount: LARGE_INTEGER,
WEPICVErrorCount: LARGE_INTEGER,
DecryptSuccessCount: LARGE_INTEGER,
DecryptFailureCount: LARGE_INTEGER,
};
pub const NDIS_802_11_KEY = extern struct {
Length: u32,
KeyIndex: u32,
KeyLength: u32,
BSSID: [6]u8,
KeyRSC: u64,
KeyMaterial: [1]u8,
};
pub const NDIS_802_11_REMOVE_KEY = extern struct {
Length: u32,
KeyIndex: u32,
BSSID: [6]u8,
};
pub const NDIS_802_11_WEP = extern struct {
Length: u32,
KeyIndex: u32,
KeyLength: u32,
KeyMaterial: [1]u8,
};
pub const NDIS_802_11_NETWORK_INFRASTRUCTURE = enum(i32) {
IBSS = 0,
Infrastructure = 1,
AutoUnknown = 2,
InfrastructureMax = 3,
};
pub const Ndis802_11IBSS = NDIS_802_11_NETWORK_INFRASTRUCTURE.IBSS;
pub const Ndis802_11Infrastructure = NDIS_802_11_NETWORK_INFRASTRUCTURE.Infrastructure;
pub const Ndis802_11AutoUnknown = NDIS_802_11_NETWORK_INFRASTRUCTURE.AutoUnknown;
pub const Ndis802_11InfrastructureMax = NDIS_802_11_NETWORK_INFRASTRUCTURE.InfrastructureMax;
pub const NDIS_802_11_AUTHENTICATION_MODE = enum(i32) {
Open = 0,
Shared = 1,
AutoSwitch = 2,
WPA = 3,
WPAPSK = 4,
WPANone = 5,
WPA2 = 6,
WPA2PSK = 7,
WPA3 = 8,
// WPA3Ent192 = 8, this enum value conflicts with WPA3
WPA3SAE = 9,
WPA3Ent = 10,
Max = 11,
};
pub const Ndis802_11AuthModeOpen = NDIS_802_11_AUTHENTICATION_MODE.Open;
pub const Ndis802_11AuthModeShared = NDIS_802_11_AUTHENTICATION_MODE.Shared;
pub const Ndis802_11AuthModeAutoSwitch = NDIS_802_11_AUTHENTICATION_MODE.AutoSwitch;
pub const Ndis802_11AuthModeWPA = NDIS_802_11_AUTHENTICATION_MODE.WPA;
pub const Ndis802_11AuthModeWPAPSK = NDIS_802_11_AUTHENTICATION_MODE.WPAPSK;
pub const Ndis802_11AuthModeWPANone = NDIS_802_11_AUTHENTICATION_MODE.WPANone;
pub const Ndis802_11AuthModeWPA2 = NDIS_802_11_AUTHENTICATION_MODE.WPA2;
pub const Ndis802_11AuthModeWPA2PSK = NDIS_802_11_AUTHENTICATION_MODE.WPA2PSK;
pub const Ndis802_11AuthModeWPA3 = NDIS_802_11_AUTHENTICATION_MODE.WPA3;
pub const Ndis802_11AuthModeWPA3Ent192 = NDIS_802_11_AUTHENTICATION_MODE.WPA3;
pub const Ndis802_11AuthModeWPA3SAE = NDIS_802_11_AUTHENTICATION_MODE.WPA3SAE;
pub const Ndis802_11AuthModeWPA3Ent = NDIS_802_11_AUTHENTICATION_MODE.WPA3Ent;
pub const Ndis802_11AuthModeMax = NDIS_802_11_AUTHENTICATION_MODE.Max;
pub const NDIS_802_11_SSID = extern struct {
SsidLength: u32,
Ssid: [32]u8,
};
pub const NDIS_WLAN_BSSID = extern struct {
Length: u32,
MacAddress: [6]u8,
Reserved: [2]u8,
Ssid: NDIS_802_11_SSID,
Privacy: u32,
Rssi: i32,
NetworkTypeInUse: NDIS_802_11_NETWORK_TYPE,
Configuration: NDIS_802_11_CONFIGURATION,
InfrastructureMode: NDIS_802_11_NETWORK_INFRASTRUCTURE,
SupportedRates: [8]u8,
};
pub const NDIS_802_11_BSSID_LIST = extern struct {
NumberOfItems: u32,
Bssid: [1]NDIS_WLAN_BSSID,
};
pub const NDIS_WLAN_BSSID_EX = extern struct {
Length: u32,
MacAddress: [6]u8,
Reserved: [2]u8,
Ssid: NDIS_802_11_SSID,
Privacy: u32,
Rssi: i32,
NetworkTypeInUse: NDIS_802_11_NETWORK_TYPE,
Configuration: NDIS_802_11_CONFIGURATION,
InfrastructureMode: NDIS_802_11_NETWORK_INFRASTRUCTURE,
SupportedRates: [16]u8,
IELength: u32,
IEs: [1]u8,
};
pub const NDIS_802_11_BSSID_LIST_EX = extern struct {
NumberOfItems: u32,
Bssid: [1]NDIS_WLAN_BSSID_EX,
};
pub const NDIS_802_11_FIXED_IEs = extern struct {
Timestamp: [8]u8,
BeaconInterval: u16,
Capabilities: u16,
};
pub const NDIS_802_11_VARIABLE_IEs = extern struct {
ElementID: u8,
Length: u8,
data: [1]u8,
};
pub const NDIS_802_11_PRIVACY_FILTER = enum(i32) {
AcceptAll = 0,
@"8021xWEP" = 1,
};
pub const Ndis802_11PrivFilterAcceptAll = NDIS_802_11_PRIVACY_FILTER.AcceptAll;
pub const Ndis802_11PrivFilter8021xWEP = NDIS_802_11_PRIVACY_FILTER.@"8021xWEP";
pub const NDIS_802_11_WEP_STATUS = enum(i32) {
WEPEnabled = 0,
// Encryption1Enabled = 0, this enum value conflicts with WEPEnabled
WEPDisabled = 1,
// EncryptionDisabled = 1, this enum value conflicts with WEPDisabled
WEPKeyAbsent = 2,
// Encryption1KeyAbsent = 2, this enum value conflicts with WEPKeyAbsent
WEPNotSupported = 3,
// EncryptionNotSupported = 3, this enum value conflicts with WEPNotSupported
Encryption2Enabled = 4,
Encryption2KeyAbsent = 5,
Encryption3Enabled = 6,
Encryption3KeyAbsent = 7,
};
pub const Ndis802_11WEPEnabled = NDIS_802_11_WEP_STATUS.WEPEnabled;
pub const Ndis802_11Encryption1Enabled = NDIS_802_11_WEP_STATUS.WEPEnabled;
pub const Ndis802_11WEPDisabled = NDIS_802_11_WEP_STATUS.WEPDisabled;
pub const Ndis802_11EncryptionDisabled = NDIS_802_11_WEP_STATUS.WEPDisabled;
pub const Ndis802_11WEPKeyAbsent = NDIS_802_11_WEP_STATUS.WEPKeyAbsent;
pub const Ndis802_11Encryption1KeyAbsent = NDIS_802_11_WEP_STATUS.WEPKeyAbsent;
pub const Ndis802_11WEPNotSupported = NDIS_802_11_WEP_STATUS.WEPNotSupported;
pub const Ndis802_11EncryptionNotSupported = NDIS_802_11_WEP_STATUS.WEPNotSupported;
pub const Ndis802_11Encryption2Enabled = NDIS_802_11_WEP_STATUS.Encryption2Enabled;
pub const Ndis802_11Encryption2KeyAbsent = NDIS_802_11_WEP_STATUS.Encryption2KeyAbsent;
pub const Ndis802_11Encryption3Enabled = NDIS_802_11_WEP_STATUS.Encryption3Enabled;
pub const Ndis802_11Encryption3KeyAbsent = NDIS_802_11_WEP_STATUS.Encryption3KeyAbsent;
pub const NDIS_802_11_RELOAD_DEFAULTS = enum(i32) {
s = 0,
};
pub const Ndis802_11ReloadWEPKeys = NDIS_802_11_RELOAD_DEFAULTS.s;
pub const NDIS_802_11_AI_REQFI = extern struct {
Capabilities: u16,
ListenInterval: u16,
CurrentAPAddress: [6]u8,
};
pub const NDIS_802_11_AI_RESFI = extern struct {
Capabilities: u16,
StatusCode: u16,
AssociationId: u16,
};
pub const NDIS_802_11_ASSOCIATION_INFORMATION = extern struct {
Length: u32,
AvailableRequestFixedIEs: u16,
RequestFixedIEs: NDIS_802_11_AI_REQFI,
RequestIELength: u32,
OffsetRequestIEs: u32,
AvailableResponseFixedIEs: u16,
ResponseFixedIEs: NDIS_802_11_AI_RESFI,
ResponseIELength: u32,
OffsetResponseIEs: u32,
};
pub const NDIS_802_11_AUTHENTICATION_EVENT = extern struct {
Status: NDIS_802_11_STATUS_INDICATION,
Request: [1]NDIS_802_11_AUTHENTICATION_REQUEST,
};
pub const NDIS_802_11_TEST = extern struct {
Length: u32,
Type: u32,
Anonymous: extern union {
AuthenticationEvent: NDIS_802_11_AUTHENTICATION_EVENT,
RssiTrigger: i32,
},
};
pub const NDIS_802_11_MEDIA_STREAM_MODE = enum(i32) {
ff = 0,
n = 1,
};
pub const Ndis802_11MediaStreamOff = NDIS_802_11_MEDIA_STREAM_MODE.ff;
pub const Ndis802_11MediaStreamOn = NDIS_802_11_MEDIA_STREAM_MODE.n;
pub const BSSID_INFO = extern struct {
BSSID: [6]u8,
PMKID: [16]u8,
};
pub const NDIS_802_11_PMKID = extern struct {
Length: u32,
BSSIDInfoCount: u32,
BSSIDInfo: [1]BSSID_INFO,
};
pub const NDIS_802_11_AUTHENTICATION_ENCRYPTION = extern struct {
AuthModeSupported: NDIS_802_11_AUTHENTICATION_MODE,
EncryptStatusSupported: NDIS_802_11_WEP_STATUS,
};
pub const NDIS_802_11_CAPABILITY = extern struct {
Length: u32,
Version: u32,
NoOfPMKIDs: u32,
NoOfAuthEncryptPairsSupported: u32,
AuthenticationEncryptionSupported: [1]NDIS_802_11_AUTHENTICATION_ENCRYPTION,
};
pub const NDIS_802_11_NON_BCAST_SSID_LIST = extern struct {
NumberOfItems: u32,
Non_Bcast_Ssid: [1]NDIS_802_11_SSID,
};
pub const NDIS_802_11_RADIO_STATUS = enum(i32) {
On = 0,
HardwareOff = 1,
SoftwareOff = 2,
HardwareSoftwareOff = 3,
Max = 4,
};
pub const Ndis802_11RadioStatusOn = NDIS_802_11_RADIO_STATUS.On;
pub const Ndis802_11RadioStatusHardwareOff = NDIS_802_11_RADIO_STATUS.HardwareOff;
pub const Ndis802_11RadioStatusSoftwareOff = NDIS_802_11_RADIO_STATUS.SoftwareOff;
pub const Ndis802_11RadioStatusHardwareSoftwareOff = NDIS_802_11_RADIO_STATUS.HardwareSoftwareOff;
pub const Ndis802_11RadioStatusMax = NDIS_802_11_RADIO_STATUS.Max;
pub const NDIS_CO_DEVICE_PROFILE = extern struct {
DeviceDescription: NDIS_VAR_DATA_DESC,
DevSpecificInfo: NDIS_VAR_DATA_DESC,
ulTAPISupplementaryPassThru: u32,
ulAddressModes: u32,
ulNumAddresses: u32,
ulBearerModes: u32,
ulMaxTxRate: u32,
ulMinTxRate: u32,
ulMaxRxRate: u32,
ulMinRxRate: u32,
ulMediaModes: u32,
ulGenerateToneModes: u32,
ulGenerateToneMaxNumFreq: u32,
ulGenerateDigitModes: u32,
ulMonitorToneMaxNumFreq: u32,
ulMonitorToneMaxNumEntries: u32,
ulMonitorDigitModes: u32,
ulGatherDigitsMinTimeout: u32,
ulGatherDigitsMaxTimeout: u32,
ulDevCapFlags: u32,
ulMaxNumActiveCalls: u32,
ulAnswerMode: u32,
ulUUIAcceptSize: u32,
ulUUIAnswerSize: u32,
ulUUIMakeCallSize: u32,
ulUUIDropSize: u32,
ulUUISendUserUserInfoSize: u32,
ulUUICallInfoSize: u32,
};
pub const OFFLOAD_OPERATION_E = enum(i32) {
AUTHENTICATE = 1,
ENCRYPT = 2,
};
pub const AUTHENTICATE = OFFLOAD_OPERATION_E.AUTHENTICATE;
pub const ENCRYPT = OFFLOAD_OPERATION_E.ENCRYPT;
pub const OFFLOAD_ALGO_INFO = extern struct {
algoIdentifier: u32,
algoKeylen: u32,
algoRounds: u32,
};
pub const OFFLOAD_CONF_ALGO = enum(i32) {
NONE = 0,
DES = 1,
RESERVED = 2,
@"3_DES" = 3,
MAX = 4,
};
pub const OFFLOAD_IPSEC_CONF_NONE = OFFLOAD_CONF_ALGO.NONE;
pub const OFFLOAD_IPSEC_CONF_DES = OFFLOAD_CONF_ALGO.DES;
pub const OFFLOAD_IPSEC_CONF_RESERVED = OFFLOAD_CONF_ALGO.RESERVED;
pub const OFFLOAD_IPSEC_CONF_3_DES = OFFLOAD_CONF_ALGO.@"3_DES";
pub const OFFLOAD_IPSEC_CONF_MAX = OFFLOAD_CONF_ALGO.MAX;
pub const OFFLOAD_INTEGRITY_ALGO = enum(i32) {
NONE = 0,
MD5 = 1,
SHA = 2,
MAX = 3,
};
pub const OFFLOAD_IPSEC_INTEGRITY_NONE = OFFLOAD_INTEGRITY_ALGO.NONE;
pub const OFFLOAD_IPSEC_INTEGRITY_MD5 = OFFLOAD_INTEGRITY_ALGO.MD5;
pub const OFFLOAD_IPSEC_INTEGRITY_SHA = OFFLOAD_INTEGRITY_ALGO.SHA;
pub const OFFLOAD_IPSEC_INTEGRITY_MAX = OFFLOAD_INTEGRITY_ALGO.MAX;
pub const OFFLOAD_SECURITY_ASSOCIATION = extern struct {
Operation: OFFLOAD_OPERATION_E,
SPI: u32,
IntegrityAlgo: OFFLOAD_ALGO_INFO,
ConfAlgo: OFFLOAD_ALGO_INFO,
Reserved: OFFLOAD_ALGO_INFO,
};
pub const OFFLOAD_IPSEC_ADD_SA = extern struct {
SrcAddr: u32,
SrcMask: u32,
DestAddr: u32,
DestMask: u32,
Protocol: u32,
SrcPort: u16,
DestPort: u16,
SrcTunnelAddr: u32,
DestTunnelAddr: u32,
Flags: u16,
NumSAs: i16,
SecAssoc: [3]OFFLOAD_SECURITY_ASSOCIATION,
OffloadHandle: ?HANDLE,
KeyLen: u32,
KeyMat: [1]u8,
};
pub const OFFLOAD_IPSEC_DELETE_SA = extern struct {
OffloadHandle: ?HANDLE,
};
pub const UDP_ENCAP_TYPE = enum(i32) {
IKE = 0,
OTHER = 1,
};
pub const OFFLOAD_IPSEC_UDPESP_ENCAPTYPE_IKE = UDP_ENCAP_TYPE.IKE;
pub const OFFLOAD_IPSEC_UDPESP_ENCAPTYPE_OTHER = UDP_ENCAP_TYPE.OTHER;
pub const OFFLOAD_IPSEC_UDPESP_ENCAPTYPE_ENTRY = extern struct {
UdpEncapType: UDP_ENCAP_TYPE,
DstEncapPort: u16,
};
pub const OFFLOAD_IPSEC_ADD_UDPESP_SA = extern struct {
SrcAddr: u32,
SrcMask: u32,
DstAddr: u32,
DstMask: u32,
Protocol: u32,
SrcPort: u16,
DstPort: u16,
SrcTunnelAddr: u32,
DstTunnelAddr: u32,
Flags: u16,
NumSAs: i16,
SecAssoc: [3]OFFLOAD_SECURITY_ASSOCIATION,
OffloadHandle: ?HANDLE,
EncapTypeEntry: OFFLOAD_IPSEC_UDPESP_ENCAPTYPE_ENTRY,
EncapTypeEntryOffldHandle: ?HANDLE,
KeyLen: u32,
KeyMat: [1]u8,
};
pub const OFFLOAD_IPSEC_DELETE_UDPESP_SA = extern struct {
OffloadHandle: ?HANDLE,
EncapTypeEntryOffldHandle: ?HANDLE,
};
pub const NDIS_MEDIUM = enum(i32) {
@"802_3" = 0,
@"802_5" = 1,
Fddi = 2,
Wan = 3,
LocalTalk = 4,
Dix = 5,
ArcnetRaw = 6,
Arcnet878_2 = 7,
Atm = 8,
WirelessWan = 9,
Irda = 10,
Bpc = 11,
CoWan = 12,
@"1394" = 13,
InfiniBand = 14,
Tunnel = 15,
Native802_11 = 16,
Loopback = 17,
WiMAX = 18,
IP = 19,
Max = 20,
};
pub const NdisMedium802_3 = NDIS_MEDIUM.@"802_3";
pub const NdisMedium802_5 = NDIS_MEDIUM.@"802_5";
pub const NdisMediumFddi = NDIS_MEDIUM.Fddi;
pub const NdisMediumWan = NDIS_MEDIUM.Wan;
pub const NdisMediumLocalTalk = NDIS_MEDIUM.LocalTalk;
pub const NdisMediumDix = NDIS_MEDIUM.Dix;
pub const NdisMediumArcnetRaw = NDIS_MEDIUM.ArcnetRaw;
pub const NdisMediumArcnet878_2 = NDIS_MEDIUM.Arcnet878_2;
pub const NdisMediumAtm = NDIS_MEDIUM.Atm;
pub const NdisMediumWirelessWan = NDIS_MEDIUM.WirelessWan;
pub const NdisMediumIrda = NDIS_MEDIUM.Irda;
pub const NdisMediumBpc = NDIS_MEDIUM.Bpc;
pub const NdisMediumCoWan = NDIS_MEDIUM.CoWan;
pub const NdisMedium1394 = NDIS_MEDIUM.@"1394";
pub const NdisMediumInfiniBand = NDIS_MEDIUM.InfiniBand;
pub const NdisMediumTunnel = NDIS_MEDIUM.Tunnel;
pub const NdisMediumNative802_11 = NDIS_MEDIUM.Native802_11;
pub const NdisMediumLoopback = NDIS_MEDIUM.Loopback;
pub const NdisMediumWiMAX = NDIS_MEDIUM.WiMAX;
pub const NdisMediumIP = NDIS_MEDIUM.IP;
pub const NdisMediumMax = NDIS_MEDIUM.Max;
pub const NDIS_PHYSICAL_MEDIUM = enum(i32) {
Unspecified = 0,
WirelessLan = 1,
CableModem = 2,
PhoneLine = 3,
PowerLine = 4,
DSL = 5,
FibreChannel = 6,
@"1394" = 7,
WirelessWan = 8,
Native802_11 = 9,
Bluetooth = 10,
Infiniband = 11,
WiMax = 12,
UWB = 13,
@"802_3" = 14,
@"802_5" = 15,
Irda = 16,
WiredWAN = 17,
WiredCoWan = 18,
Other = 19,
Native802_15_4 = 20,
Max = 21,
};
pub const NdisPhysicalMediumUnspecified = NDIS_PHYSICAL_MEDIUM.Unspecified;
pub const NdisPhysicalMediumWirelessLan = NDIS_PHYSICAL_MEDIUM.WirelessLan;
pub const NdisPhysicalMediumCableModem = NDIS_PHYSICAL_MEDIUM.CableModem;
pub const NdisPhysicalMediumPhoneLine = NDIS_PHYSICAL_MEDIUM.PhoneLine;
pub const NdisPhysicalMediumPowerLine = NDIS_PHYSICAL_MEDIUM.PowerLine;
pub const NdisPhysicalMediumDSL = NDIS_PHYSICAL_MEDIUM.DSL;
pub const NdisPhysicalMediumFibreChannel = NDIS_PHYSICAL_MEDIUM.FibreChannel;
pub const NdisPhysicalMedium1394 = NDIS_PHYSICAL_MEDIUM.@"1394";
pub const NdisPhysicalMediumWirelessWan = NDIS_PHYSICAL_MEDIUM.WirelessWan;
pub const NdisPhysicalMediumNative802_11 = NDIS_PHYSICAL_MEDIUM.Native802_11;
pub const NdisPhysicalMediumBluetooth = NDIS_PHYSICAL_MEDIUM.Bluetooth;
pub const NdisPhysicalMediumInfiniband = NDIS_PHYSICAL_MEDIUM.Infiniband;
pub const NdisPhysicalMediumWiMax = NDIS_PHYSICAL_MEDIUM.WiMax;
pub const NdisPhysicalMediumUWB = NDIS_PHYSICAL_MEDIUM.UWB;
pub const NdisPhysicalMedium802_3 = NDIS_PHYSICAL_MEDIUM.@"802_3";
pub const NdisPhysicalMedium802_5 = NDIS_PHYSICAL_MEDIUM.@"802_5";
pub const NdisPhysicalMediumIrda = NDIS_PHYSICAL_MEDIUM.Irda;
pub const NdisPhysicalMediumWiredWAN = NDIS_PHYSICAL_MEDIUM.WiredWAN;
pub const NdisPhysicalMediumWiredCoWan = NDIS_PHYSICAL_MEDIUM.WiredCoWan;
pub const NdisPhysicalMediumOther = NDIS_PHYSICAL_MEDIUM.Other;
pub const NdisPhysicalMediumNative802_15_4 = NDIS_PHYSICAL_MEDIUM.Native802_15_4;
pub const NdisPhysicalMediumMax = NDIS_PHYSICAL_MEDIUM.Max;
pub const TRANSPORT_HEADER_OFFSET = extern struct {
ProtocolType: u16,
HeaderOffset: u16,
};
pub const NETWORK_ADDRESS = extern struct {
AddressLength: u16,
AddressType: u16,
Address: [1]u8,
};
pub const NETWORK_ADDRESS_LIST = extern struct {
AddressCount: i32,
AddressType: u16,
Address: [1]NETWORK_ADDRESS,
};
pub const NETWORK_ADDRESS_IP = extern struct {
sin_port: u16,
IN_ADDR: u32,
sin_zero: [8]u8,
};
pub const NETWORK_ADDRESS_IP6 = extern struct {
sin6_port: u16,
sin6_flowinfo: u32,
sin6_addr: [8]u16,
sin6_scope_id: u32,
};
pub const NETWORK_ADDRESS_IPX = extern struct {
NetworkAddress: u32,
NodeAddress: [6]u8,
Socket: u16,
};
pub const NDIS_HARDWARE_STATUS = enum(i32) {
Ready = 0,
Initializing = 1,
Reset = 2,
Closing = 3,
NotReady = 4,
};
pub const NdisHardwareStatusReady = NDIS_HARDWARE_STATUS.Ready;
pub const NdisHardwareStatusInitializing = NDIS_HARDWARE_STATUS.Initializing;
pub const NdisHardwareStatusReset = NDIS_HARDWARE_STATUS.Reset;
pub const NdisHardwareStatusClosing = NDIS_HARDWARE_STATUS.Closing;
pub const NdisHardwareStatusNotReady = NDIS_HARDWARE_STATUS.NotReady;
pub const GEN_GET_TIME_CAPS = extern struct {
Flags: u32,
ClockPrecision: u32,
};
pub const GEN_GET_NETCARD_TIME = extern struct {
ReadTime: u64,
};
pub const NDIS_PM_PACKET_PATTERN = extern struct {
Priority: u32,
Reserved: u32,
MaskSize: u32,
PatternOffset: u32,
PatternSize: u32,
PatternFlags: u32,
};
pub const NDIS_DEVICE_POWER_STATE = enum(i32) {
Unspecified = 0,
D0 = 1,
D1 = 2,
D2 = 3,
D3 = 4,
Maximum = 5,
};
pub const NdisDeviceStateUnspecified = NDIS_DEVICE_POWER_STATE.Unspecified;
pub const NdisDeviceStateD0 = NDIS_DEVICE_POWER_STATE.D0;
pub const NdisDeviceStateD1 = NDIS_DEVICE_POWER_STATE.D1;
pub const NdisDeviceStateD2 = NDIS_DEVICE_POWER_STATE.D2;
pub const NdisDeviceStateD3 = NDIS_DEVICE_POWER_STATE.D3;
pub const NdisDeviceStateMaximum = NDIS_DEVICE_POWER_STATE.Maximum;
pub const NDIS_PM_WAKE_UP_CAPABILITIES = extern struct {
MinMagicPacketWakeUp: NDIS_DEVICE_POWER_STATE,
MinPatternWakeUp: NDIS_DEVICE_POWER_STATE,
MinLinkChangeWakeUp: NDIS_DEVICE_POWER_STATE,
};
pub const NDIS_PNP_CAPABILITIES = extern struct {
Flags: u32,
WakeUpCapabilities: NDIS_PM_WAKE_UP_CAPABILITIES,
};
pub const NDIS_FDDI_ATTACHMENT_TYPE = enum(i32) {
Isolated = 1,
LocalA = 2,
LocalB = 3,
LocalAB = 4,
LocalS = 5,
WrapA = 6,
WrapB = 7,
WrapAB = 8,
WrapS = 9,
CWrapA = 10,
CWrapB = 11,
CWrapS = 12,
Through = 13,
};
pub const NdisFddiTypeIsolated = NDIS_FDDI_ATTACHMENT_TYPE.Isolated;
pub const NdisFddiTypeLocalA = NDIS_FDDI_ATTACHMENT_TYPE.LocalA;
pub const NdisFddiTypeLocalB = NDIS_FDDI_ATTACHMENT_TYPE.LocalB;
pub const NdisFddiTypeLocalAB = NDIS_FDDI_ATTACHMENT_TYPE.LocalAB;
pub const NdisFddiTypeLocalS = NDIS_FDDI_ATTACHMENT_TYPE.LocalS;
pub const NdisFddiTypeWrapA = NDIS_FDDI_ATTACHMENT_TYPE.WrapA;
pub const NdisFddiTypeWrapB = NDIS_FDDI_ATTACHMENT_TYPE.WrapB;
pub const NdisFddiTypeWrapAB = NDIS_FDDI_ATTACHMENT_TYPE.WrapAB;
pub const NdisFddiTypeWrapS = NDIS_FDDI_ATTACHMENT_TYPE.WrapS;
pub const NdisFddiTypeCWrapA = NDIS_FDDI_ATTACHMENT_TYPE.CWrapA;
pub const NdisFddiTypeCWrapB = NDIS_FDDI_ATTACHMENT_TYPE.CWrapB;
pub const NdisFddiTypeCWrapS = NDIS_FDDI_ATTACHMENT_TYPE.CWrapS;
pub const NdisFddiTypeThrough = NDIS_FDDI_ATTACHMENT_TYPE.Through;
pub const NDIS_FDDI_RING_MGT_STATE = enum(i32) {
Isolated = 1,
NonOperational = 2,
Operational = 3,
Detect = 4,
NonOperationalDup = 5,
OperationalDup = 6,
Directed = 7,
Trace = 8,
};
pub const NdisFddiRingIsolated = NDIS_FDDI_RING_MGT_STATE.Isolated;
pub const NdisFddiRingNonOperational = NDIS_FDDI_RING_MGT_STATE.NonOperational;
pub const NdisFddiRingOperational = NDIS_FDDI_RING_MGT_STATE.Operational;
pub const NdisFddiRingDetect = NDIS_FDDI_RING_MGT_STATE.Detect;
pub const NdisFddiRingNonOperationalDup = NDIS_FDDI_RING_MGT_STATE.NonOperationalDup;
pub const NdisFddiRingOperationalDup = NDIS_FDDI_RING_MGT_STATE.OperationalDup;
pub const NdisFddiRingDirected = NDIS_FDDI_RING_MGT_STATE.Directed;
pub const NdisFddiRingTrace = NDIS_FDDI_RING_MGT_STATE.Trace;
pub const NDIS_FDDI_LCONNECTION_STATE = enum(i32) {
Off = 1,
Break = 2,
Trace = 3,
Connect = 4,
Next = 5,
Signal = 6,
Join = 7,
Verify = 8,
Active = 9,
Maintenance = 10,
};
pub const NdisFddiStateOff = NDIS_FDDI_LCONNECTION_STATE.Off;
pub const NdisFddiStateBreak = NDIS_FDDI_LCONNECTION_STATE.Break;
pub const NdisFddiStateTrace = NDIS_FDDI_LCONNECTION_STATE.Trace;
pub const NdisFddiStateConnect = NDIS_FDDI_LCONNECTION_STATE.Connect;
pub const NdisFddiStateNext = NDIS_FDDI_LCONNECTION_STATE.Next;
pub const NdisFddiStateSignal = NDIS_FDDI_LCONNECTION_STATE.Signal;
pub const NdisFddiStateJoin = NDIS_FDDI_LCONNECTION_STATE.Join;
pub const NdisFddiStateVerify = NDIS_FDDI_LCONNECTION_STATE.Verify;
pub const NdisFddiStateActive = NDIS_FDDI_LCONNECTION_STATE.Active;
pub const NdisFddiStateMaintenance = NDIS_FDDI_LCONNECTION_STATE.Maintenance;
pub const NDIS_WAN_MEDIUM_SUBTYPE = enum(i32) {
Hub = 0,
X_25 = 1,
Isdn = 2,
Serial = 3,
FrameRelay = 4,
Atm = 5,
Sonet = 6,
SW56K = 7,
PPTP = 8,
L2TP = 9,
Irda = 10,
Parallel = 11,
Pppoe = 12,
SSTP = 13,
AgileVPN = 14,
Gre = 15,
SubTypeMax = 16,
};
pub const NdisWanMediumHub = NDIS_WAN_MEDIUM_SUBTYPE.Hub;
pub const NdisWanMediumX_25 = NDIS_WAN_MEDIUM_SUBTYPE.X_25;
pub const NdisWanMediumIsdn = NDIS_WAN_MEDIUM_SUBTYPE.Isdn;
pub const NdisWanMediumSerial = NDIS_WAN_MEDIUM_SUBTYPE.Serial;
pub const NdisWanMediumFrameRelay = NDIS_WAN_MEDIUM_SUBTYPE.FrameRelay;
pub const NdisWanMediumAtm = NDIS_WAN_MEDIUM_SUBTYPE.Atm;
pub const NdisWanMediumSonet = NDIS_WAN_MEDIUM_SUBTYPE.Sonet;
pub const NdisWanMediumSW56K = NDIS_WAN_MEDIUM_SUBTYPE.SW56K;
pub const NdisWanMediumPPTP = NDIS_WAN_MEDIUM_SUBTYPE.PPTP;
pub const NdisWanMediumL2TP = NDIS_WAN_MEDIUM_SUBTYPE.L2TP;
pub const NdisWanMediumIrda = NDIS_WAN_MEDIUM_SUBTYPE.Irda;
pub const NdisWanMediumParallel = NDIS_WAN_MEDIUM_SUBTYPE.Parallel;
pub const NdisWanMediumPppoe = NDIS_WAN_MEDIUM_SUBTYPE.Pppoe;
pub const NdisWanMediumSSTP = NDIS_WAN_MEDIUM_SUBTYPE.SSTP;
pub const NdisWanMediumAgileVPN = NDIS_WAN_MEDIUM_SUBTYPE.AgileVPN;
pub const NdisWanMediumGre = NDIS_WAN_MEDIUM_SUBTYPE.Gre;
pub const NdisWanMediumSubTypeMax = NDIS_WAN_MEDIUM_SUBTYPE.SubTypeMax;
pub const NDIS_WAN_HEADER_FORMAT = enum(i32) {
Native = 0,
Ethernet = 1,
};
pub const NdisWanHeaderNative = NDIS_WAN_HEADER_FORMAT.Native;
pub const NdisWanHeaderEthernet = NDIS_WAN_HEADER_FORMAT.Ethernet;
pub const NDIS_WAN_QUALITY = enum(i32) {
Raw = 0,
ErrorControl = 1,
Reliable = 2,
};
pub const NdisWanRaw = NDIS_WAN_QUALITY.Raw;
pub const NdisWanErrorControl = NDIS_WAN_QUALITY.ErrorControl;
pub const NdisWanReliable = NDIS_WAN_QUALITY.Reliable;
pub const NDIS_WAN_PROTOCOL_CAPS = extern struct {
Flags: u32,
Reserved: u32,
};
pub const NDIS_802_5_RING_STATE = enum(i32) {
Opened = 1,
Closed = 2,
Opening = 3,
Closing = 4,
OpenFailure = 5,
RingFailure = 6,
};
pub const NdisRingStateOpened = NDIS_802_5_RING_STATE.Opened;
pub const NdisRingStateClosed = NDIS_802_5_RING_STATE.Closed;
pub const NdisRingStateOpening = NDIS_802_5_RING_STATE.Opening;
pub const NdisRingStateClosing = NDIS_802_5_RING_STATE.Closing;
pub const NdisRingStateOpenFailure = NDIS_802_5_RING_STATE.OpenFailure;
pub const NdisRingStateRingFailure = NDIS_802_5_RING_STATE.RingFailure;
pub const NDIS_MEDIA_STATE = enum(i32) {
Connected = 0,
Disconnected = 1,
};
pub const NdisMediaStateConnected = NDIS_MEDIA_STATE.Connected;
pub const NdisMediaStateDisconnected = NDIS_MEDIA_STATE.Disconnected;
pub const NDIS_CO_LINK_SPEED = extern struct {
Outbound: u32,
Inbound: u32,
};
pub const NDIS_LINK_SPEED = extern struct {
XmitLinkSpeed: u64,
RcvLinkSpeed: u64,
};
pub const NDIS_GUID = extern struct {
Guid: Guid,
Anonymous: extern union {
Oid: u32,
Status: i32,
},
Size: u32,
Flags: u32,
};
pub const NDIS_IRDA_PACKET_INFO = extern struct {
ExtraBOFs: u32,
MinTurnAroundTime: u32,
};
pub const NDIS_SUPPORTED_PAUSE_FUNCTIONS = enum(i32) {
Unsupported = 0,
SendOnly = 1,
ReceiveOnly = 2,
SendAndReceive = 3,
Unknown = 4,
};
pub const NdisPauseFunctionsUnsupported = NDIS_SUPPORTED_PAUSE_FUNCTIONS.Unsupported;
pub const NdisPauseFunctionsSendOnly = NDIS_SUPPORTED_PAUSE_FUNCTIONS.SendOnly;
pub const NdisPauseFunctionsReceiveOnly = NDIS_SUPPORTED_PAUSE_FUNCTIONS.ReceiveOnly;
pub const NdisPauseFunctionsSendAndReceive = NDIS_SUPPORTED_PAUSE_FUNCTIONS.SendAndReceive;
pub const NdisPauseFunctionsUnknown = NDIS_SUPPORTED_PAUSE_FUNCTIONS.Unknown;
pub const NDIS_LINK_STATE = extern struct {
Header: NDIS_OBJECT_HEADER,
MediaConnectState: NET_IF_MEDIA_CONNECT_STATE,
MediaDuplexState: NET_IF_MEDIA_DUPLEX_STATE,
XmitLinkSpeed: u64,
RcvLinkSpeed: u64,
PauseFunctions: NDIS_SUPPORTED_PAUSE_FUNCTIONS,
AutoNegotiationFlags: u32,
};
pub const NDIS_LINK_PARAMETERS = extern struct {
Header: NDIS_OBJECT_HEADER,
MediaDuplexState: NET_IF_MEDIA_DUPLEX_STATE,
XmitLinkSpeed: u64,
RcvLinkSpeed: u64,
PauseFunctions: NDIS_SUPPORTED_PAUSE_FUNCTIONS,
AutoNegotiationFlags: u32,
};
pub const NDIS_OPER_STATE = extern struct {
Header: NDIS_OBJECT_HEADER,
OperationalStatus: NET_IF_OPER_STATUS,
OperationalStatusFlags: u32,
};
pub const NDIS_IP_OPER_STATUS = extern struct {
AddressFamily: u32,
OperationalStatus: NET_IF_OPER_STATUS,
OperationalStatusFlags: u32,
};
pub const NDIS_IP_OPER_STATUS_INFO = extern struct {
Header: NDIS_OBJECT_HEADER,
Flags: u32,
NumberofAddressFamiliesReturned: u32,
IpOperationalStatus: [32]NDIS_IP_OPER_STATUS,
};
pub const NDIS_IP_OPER_STATE = extern struct {
Header: NDIS_OBJECT_HEADER,
Flags: u32,
IpOperationalStatus: NDIS_IP_OPER_STATUS,
};
pub const NDIS_OFFLOAD_PARAMETERS = extern struct {
Header: NDIS_OBJECT_HEADER,
IPv4Checksum: u8,
TCPIPv4Checksum: u8,
UDPIPv4Checksum: u8,
TCPIPv6Checksum: u8,
UDPIPv6Checksum: u8,
LsoV1: u8,
IPsecV1: u8,
LsoV2IPv4: u8,
LsoV2IPv6: u8,
TcpConnectionIPv4: u8,
TcpConnectionIPv6: u8,
Flags: u32,
};
pub const NDIS_TCP_LARGE_SEND_OFFLOAD_V1 = extern struct {
IPv4: extern struct {
Encapsulation: u32,
MaxOffLoadSize: u32,
MinSegmentCount: u32,
_bitfield: u32,
},
};
pub const NDIS_TCP_IP_CHECKSUM_OFFLOAD = extern struct {
IPv4Transmit: extern struct {
Encapsulation: u32,
_bitfield: u32,
},
IPv4Receive: extern struct {
Encapsulation: u32,
_bitfield: u32,
},
IPv6Transmit: extern struct {
Encapsulation: u32,
_bitfield: u32,
},
IPv6Receive: extern struct {
Encapsulation: u32,
_bitfield: u32,
},
};
pub const NDIS_IPSEC_OFFLOAD_V1 = extern struct {
Supported: extern struct {
Encapsulation: u32,
AhEspCombined: u32,
TransportTunnelCombined: u32,
IPv4Options: u32,
Flags: u32,
},
IPv4AH: extern struct {
_bitfield: u32,
},
IPv4ESP: extern struct {
_bitfield: u32,
},
};
pub const NDIS_TCP_LARGE_SEND_OFFLOAD_V2 = extern struct {
IPv4: extern struct {
Encapsulation: u32,
MaxOffLoadSize: u32,
MinSegmentCount: u32,
},
IPv6: extern struct {
Encapsulation: u32,
MaxOffLoadSize: u32,
MinSegmentCount: u32,
_bitfield: u32,
},
};
pub const NDIS_OFFLOAD = extern struct {
Header: NDIS_OBJECT_HEADER,
Checksum: NDIS_TCP_IP_CHECKSUM_OFFLOAD,
LsoV1: NDIS_TCP_LARGE_SEND_OFFLOAD_V1,
IPsecV1: NDIS_IPSEC_OFFLOAD_V1,
LsoV2: NDIS_TCP_LARGE_SEND_OFFLOAD_V2,
Flags: u32,
};
pub const NDIS_WMI_TCP_LARGE_SEND_OFFLOAD_V1 = extern struct {
IPv4: extern struct {
Encapsulation: u32,
MaxOffLoadSize: u32,
MinSegmentCount: u32,
TcpOptions: u32,
IpOptions: u32,
},
};
pub const NDIS_WMI_TCP_IP_CHECKSUM_OFFLOAD = extern struct {
IPv4Transmit: extern struct {
Encapsulation: u32,
IpOptionsSupported: u32,
TcpOptionsSupported: u32,
TcpChecksum: u32,
UdpChecksum: u32,
IpChecksum: u32,
},
IPv4Receive: extern struct {
Encapsulation: u32,
IpOptionsSupported: u32,
TcpOptionsSupported: u32,
TcpChecksum: u32,
UdpChecksum: u32,
IpChecksum: u32,
},
IPv6Transmit: extern struct {
Encapsulation: u32,
IpExtensionHeadersSupported: u32,
TcpOptionsSupported: u32,
TcpChecksum: u32,
UdpChecksum: u32,
},
IPv6Receive: extern struct {
Encapsulation: u32,
IpExtensionHeadersSupported: u32,
TcpOptionsSupported: u32,
TcpChecksum: u32,
UdpChecksum: u32,
},
};
pub const NDIS_WMI_IPSEC_OFFLOAD_V1 = extern struct {
Supported: extern struct {
Encapsulation: u32,
AhEspCombined: u32,
TransportTunnelCombined: u32,
IPv4Options: u32,
Flags: u32,
},
IPv4AH: extern struct {
Md5: u32,
Sha_1: u32,
Transport: u32,
Tunnel: u32,
Send: u32,
Receive: u32,
},
IPv4ESP: extern struct {
Des: u32,
Reserved: u32,
TripleDes: u32,
NullEsp: u32,
Transport: u32,
Tunnel: u32,
Send: u32,
Receive: u32,
},
};
pub const NDIS_WMI_TCP_LARGE_SEND_OFFLOAD_V2 = extern struct {
IPv4: extern struct {
Encapsulation: u32,
MaxOffLoadSize: u32,
MinSegmentCount: u32,
},
IPv6: extern struct {
Encapsulation: u32,
MaxOffLoadSize: u32,
MinSegmentCount: u32,
IpExtensionHeadersSupported: u32,
TcpOptionsSupported: u32,
},
};
pub const NDIS_WMI_OFFLOAD = extern struct {
Header: NDIS_OBJECT_HEADER,
Checksum: NDIS_WMI_TCP_IP_CHECKSUM_OFFLOAD,
LsoV1: NDIS_WMI_TCP_LARGE_SEND_OFFLOAD_V1,
IPsecV1: NDIS_WMI_IPSEC_OFFLOAD_V1,
LsoV2: NDIS_WMI_TCP_LARGE_SEND_OFFLOAD_V2,
Flags: u32,
};
pub const NDIS_TCP_CONNECTION_OFFLOAD = extern struct {
Header: NDIS_OBJECT_HEADER,
Encapsulation: u32,
_bitfield: u32,
TcpConnectionOffloadCapacity: u32,
Flags: u32,
};
pub const NDIS_WMI_TCP_CONNECTION_OFFLOAD = extern struct {
Header: NDIS_OBJECT_HEADER,
Encapsulation: u32,
SupportIPv4: u32,
SupportIPv6: u32,
SupportIPv6ExtensionHeaders: u32,
SupportSack: u32,
TcpConnectionOffloadCapacity: u32,
Flags: u32,
};
pub const NDIS_PORT_TYPE = enum(i32) {
Undefined = 0,
Bridge = 1,
RasConnection = 2,
@"8021xSupplicant" = 3,
Max = 4,
};
pub const NdisPortTypeUndefined = NDIS_PORT_TYPE.Undefined;
pub const NdisPortTypeBridge = NDIS_PORT_TYPE.Bridge;
pub const NdisPortTypeRasConnection = NDIS_PORT_TYPE.RasConnection;
pub const NdisPortType8021xSupplicant = NDIS_PORT_TYPE.@"8021xSupplicant";
pub const NdisPortTypeMax = NDIS_PORT_TYPE.Max;
pub const NDIS_PORT_AUTHORIZATION_STATE = enum(i32) {
AuthorizationUnknown = 0,
Authorized = 1,
Unauthorized = 2,
Reauthorizing = 3,
};
pub const NdisPortAuthorizationUnknown = NDIS_PORT_AUTHORIZATION_STATE.AuthorizationUnknown;
pub const NdisPortAuthorized = NDIS_PORT_AUTHORIZATION_STATE.Authorized;
pub const NdisPortUnauthorized = NDIS_PORT_AUTHORIZATION_STATE.Unauthorized;
pub const NdisPortReauthorizing = NDIS_PORT_AUTHORIZATION_STATE.Reauthorizing;
pub const NDIS_PORT_CONTROL_STATE = enum(i32) {
Unknown = 0,
Controlled = 1,
Uncontrolled = 2,
};
pub const NdisPortControlStateUnknown = NDIS_PORT_CONTROL_STATE.Unknown;
pub const NdisPortControlStateControlled = NDIS_PORT_CONTROL_STATE.Controlled;
pub const NdisPortControlStateUncontrolled = NDIS_PORT_CONTROL_STATE.Uncontrolled;
pub const NDIS_PORT_AUTHENTICATION_PARAMETERS = extern struct {
Header: NDIS_OBJECT_HEADER,
SendControlState: NDIS_PORT_CONTROL_STATE,
RcvControlState: NDIS_PORT_CONTROL_STATE,
SendAuthorizationState: NDIS_PORT_AUTHORIZATION_STATE,
RcvAuthorizationState: NDIS_PORT_AUTHORIZATION_STATE,
};
pub const NDIS_NETWORK_CHANGE_TYPE = enum(i32) {
PossibleNetworkChange = 1,
DefinitelyNetworkChange = 2,
NetworkChangeFromMediaConnect = 3,
NetworkChangeMax = 4,
};
pub const NdisPossibleNetworkChange = NDIS_NETWORK_CHANGE_TYPE.PossibleNetworkChange;
pub const NdisDefinitelyNetworkChange = NDIS_NETWORK_CHANGE_TYPE.DefinitelyNetworkChange;
pub const NdisNetworkChangeFromMediaConnect = NDIS_NETWORK_CHANGE_TYPE.NetworkChangeFromMediaConnect;
pub const NdisNetworkChangeMax = NDIS_NETWORK_CHANGE_TYPE.NetworkChangeMax;
pub const NDIS_WMI_METHOD_HEADER = extern struct {
Header: NDIS_OBJECT_HEADER,
PortNumber: u32,
NetLuid: NET_LUID_LH,
RequestId: u64,
Timeout: u32,
Padding: [4]u8,
};
pub const NDIS_WMI_SET_HEADER = extern struct {
Header: NDIS_OBJECT_HEADER,
PortNumber: u32,
NetLuid: NET_LUID_LH,
RequestId: u64,
Timeout: u32,
Padding: [4]u8,
};
pub const NDIS_WMI_EVENT_HEADER = extern struct {
Header: NDIS_OBJECT_HEADER,
IfIndex: u32,
NetLuid: NET_LUID_LH,
RequestId: u64,
PortNumber: u32,
DeviceNameLength: u32,
DeviceNameOffset: u32,
Padding: [4]u8,
};
pub const NDIS_WMI_ENUM_ADAPTER = extern struct {
Header: NDIS_OBJECT_HEADER,
IfIndex: u32,
NetLuid: NET_LUID_LH,
DeviceNameLength: u16,
DeviceName: [1]CHAR,
};
pub const NDIS_WMI_OUTPUT_INFO = extern struct {
Header: NDIS_OBJECT_HEADER,
Flags: u32,
SupportedRevision: u8,
DataOffset: u32,
};
pub const NDIS_RECEIVE_SCALE_CAPABILITIES = extern struct {
Header: NDIS_OBJECT_HEADER,
CapabilitiesFlags: u32,
NumberOfInterruptMessages: u32,
NumberOfReceiveQueues: u32,
};
pub const NDIS_RECEIVE_SCALE_PARAMETERS = extern struct {
Header: NDIS_OBJECT_HEADER,
Flags: u16,
BaseCpuNumber: u16,
HashInformation: u32,
IndirectionTableSize: u16,
IndirectionTableOffset: u32,
HashSecretKeySize: u16,
HashSecretKeyOffset: u32,
};
pub const NDIS_RECEIVE_HASH_PARAMETERS = extern struct {
Header: NDIS_OBJECT_HEADER,
Flags: u32,
HashInformation: u32,
HashSecretKeySize: u16,
HashSecretKeyOffset: u32,
};
pub const NDIS_PROCESSOR_VENDOR = enum(i32) {
Unknown = 0,
GenuinIntel = 1,
// GenuineIntel = 1, this enum value conflicts with GenuinIntel
AuthenticAMD = 2,
};
pub const NdisProcessorVendorUnknown = NDIS_PROCESSOR_VENDOR.Unknown;
pub const NdisProcessorVendorGenuinIntel = NDIS_PROCESSOR_VENDOR.GenuinIntel;
pub const NdisProcessorVendorGenuineIntel = NDIS_PROCESSOR_VENDOR.GenuinIntel;
pub const NdisProcessorVendorAuthenticAMD = NDIS_PROCESSOR_VENDOR.AuthenticAMD;
pub const NDIS_PORT_STATE = extern struct {
Header: NDIS_OBJECT_HEADER,
MediaConnectState: NET_IF_MEDIA_CONNECT_STATE,
XmitLinkSpeed: u64,
RcvLinkSpeed: u64,
Direction: NET_IF_DIRECTION_TYPE,
SendControlState: NDIS_PORT_CONTROL_STATE,
RcvControlState: NDIS_PORT_CONTROL_STATE,
SendAuthorizationState: NDIS_PORT_AUTHORIZATION_STATE,
RcvAuthorizationState: NDIS_PORT_AUTHORIZATION_STATE,
Flags: u32,
};
pub const NDIS_PORT_CHARACTERISTICS = extern struct {
Header: NDIS_OBJECT_HEADER,
PortNumber: u32,
Flags: u32,
Type: NDIS_PORT_TYPE,
MediaConnectState: NET_IF_MEDIA_CONNECT_STATE,
XmitLinkSpeed: u64,
RcvLinkSpeed: u64,
Direction: NET_IF_DIRECTION_TYPE,
SendControlState: NDIS_PORT_CONTROL_STATE,
RcvControlState: NDIS_PORT_CONTROL_STATE,
SendAuthorizationState: NDIS_PORT_AUTHORIZATION_STATE,
RcvAuthorizationState: NDIS_PORT_AUTHORIZATION_STATE,
};
pub const NDIS_PORT = extern struct {
Next: ?*NDIS_PORT,
NdisReserved: ?*anyopaque,
MiniportReserved: ?*anyopaque,
ProtocolReserved: ?*anyopaque,
PortCharacteristics: NDIS_PORT_CHARACTERISTICS,
};
pub const NDIS_PORT_ARRAY = extern struct {
Header: NDIS_OBJECT_HEADER,
NumberOfPorts: u32,
OffsetFirstPort: u32,
ElementSize: u32,
Ports: [1]NDIS_PORT_CHARACTERISTICS,
};
pub const NDIS_TIMESTAMP_CAPABILITY_FLAGS = extern struct {
PtpV2OverUdpIPv4EventMsgReceiveHw: BOOLEAN,
PtpV2OverUdpIPv4AllMsgReceiveHw: BOOLEAN,
PtpV2OverUdpIPv4EventMsgTransmitHw: BOOLEAN,
PtpV2OverUdpIPv4AllMsgTransmitHw: BOOLEAN,
PtpV2OverUdpIPv6EventMsgReceiveHw: BOOLEAN,
PtpV2OverUdpIPv6AllMsgReceiveHw: BOOLEAN,
PtpV2OverUdpIPv6EventMsgTransmitHw: BOOLEAN,
PtpV2OverUdpIPv6AllMsgTransmitHw: BOOLEAN,
AllReceiveHw: BOOLEAN,
AllTransmitHw: BOOLEAN,
TaggedTransmitHw: BOOLEAN,
AllReceiveSw: BOOLEAN,
AllTransmitSw: BOOLEAN,
TaggedTransmitSw: BOOLEAN,
};
pub const NDIS_TIMESTAMP_CAPABILITIES = extern struct {
Header: NDIS_OBJECT_HEADER,
HardwareClockFrequencyHz: u64,
CrossTimestamp: BOOLEAN,
Reserved1: u64,
Reserved2: u64,
TimestampFlags: NDIS_TIMESTAMP_CAPABILITY_FLAGS,
};
pub const NDIS_HARDWARE_CROSSTIMESTAMP = extern struct {
Header: NDIS_OBJECT_HEADER,
Flags: u32,
SystemTimestamp1: u64,
HardwareClockTimestamp: u64,
SystemTimestamp2: u64,
};
pub const NDK_VERSION = extern struct {
Major: u16,
Minor: u16,
};
pub const NDK_RDMA_TECHNOLOGY = enum(i32) {
Undefined = 0,
iWarp = 1,
InfiniBand = 2,
RoCE = 3,
RoCEv2 = 4,
MaxTechnology = 5,
};
pub const NdkUndefined = NDK_RDMA_TECHNOLOGY.Undefined;
pub const NdkiWarp = NDK_RDMA_TECHNOLOGY.iWarp;
pub const NdkInfiniBand = NDK_RDMA_TECHNOLOGY.InfiniBand;
pub const NdkRoCE = NDK_RDMA_TECHNOLOGY.RoCE;
pub const NdkRoCEv2 = NDK_RDMA_TECHNOLOGY.RoCEv2;
pub const NdkMaxTechnology = NDK_RDMA_TECHNOLOGY.MaxTechnology;
pub const NDK_ADAPTER_INFO = extern struct {
Version: NDK_VERSION,
VendorId: u32,
DeviceId: u32,
MaxRegistrationSize: usize,
MaxWindowSize: usize,
FRMRPageCount: u32,
MaxInitiatorRequestSge: u32,
MaxReceiveRequestSge: u32,
MaxReadRequestSge: u32,
MaxTransferLength: u32,
MaxInlineDataSize: u32,
MaxInboundReadLimit: u32,
MaxOutboundReadLimit: u32,
MaxReceiveQueueDepth: u32,
MaxInitiatorQueueDepth: u32,
MaxSrqDepth: u32,
MaxCqDepth: u32,
LargeRequestThreshold: u32,
MaxCallerData: u32,
MaxCalleeData: u32,
AdapterFlags: u32,
RdmaTechnology: NDK_RDMA_TECHNOLOGY,
};
pub const DOT11_ADAPTER = extern struct {
gAdapterId: Guid,
pszDescription: ?PWSTR,
Dot11CurrentOpMode: DOT11_CURRENT_OPERATION_MODE,
};
pub const DOT11_BSS_LIST = extern struct {
uNumOfBytes: u32,
pucBuffer: ?*u8,
};
pub const DOT11_PORT_STATE = extern struct {
PeerMacAddress: [6]u8,
uSessionId: u32,
bPortControlled: BOOL,
bPortAuthorized: BOOL,
};
pub const DOT11_SECURITY_PACKET_HEADER = packed struct {
PeerMac: [6]u8,
usEtherType: u16,
Data: [1]u8,
};
pub const DOT11_MSSECURITY_SETTINGS = extern struct {
dot11AuthAlgorithm: DOT11_AUTH_ALGORITHM,
dot11CipherAlgorithm: DOT11_CIPHER_ALGORITHM,
fOneXEnabled: BOOL,
eapMethodType: EAP_METHOD_TYPE,
dwEapConnectionDataLen: u32,
pEapConnectionData: ?*u8,
};
pub const DOT11EXT_IHV_SSID_LIST = extern struct {
ulCount: u32,
SSIDs: [1]DOT11_SSID,
};
pub const DOT11EXT_IHV_PROFILE_PARAMS = extern struct {
pSsidList: ?*DOT11EXT_IHV_SSID_LIST,
BssType: DOT11_BSS_TYPE,
pMSSecuritySettings: ?*DOT11_MSSECURITY_SETTINGS,
};
pub const DOT11EXT_IHV_PARAMS = extern struct {
dot11ExtIhvProfileParams: DOT11EXT_IHV_PROFILE_PARAMS,
wstrProfileName: [256]u16,
dwProfileTypeFlags: u32,
interfaceGuid: Guid,
};
pub const DOT11_IHV_VERSION_INFO = extern struct {
dwVerMin: u32,
dwVerMax: u32,
};
pub const DOT11EXT_IHV_CONNECTION_PHASE = enum(i32) {
any = 0,
initial_connection = 1,
post_l3_connection = 2,
};
pub const connection_phase_any = DOT11EXT_IHV_CONNECTION_PHASE.any;
pub const connection_phase_initial_connection = DOT11EXT_IHV_CONNECTION_PHASE.initial_connection;
pub const connection_phase_post_l3_connection = DOT11EXT_IHV_CONNECTION_PHASE.post_l3_connection;
pub const DOT11EXT_IHV_UI_REQUEST = extern struct {
dwSessionId: u32,
guidUIRequest: Guid,
UIPageClsid: Guid,
dwByteCount: u32,
pvUIRequest: ?*u8,
};
pub const DOT11_MSONEX_RESULT = enum(i32) {
SUCCESS = 0,
FAILURE = 1,
IN_PROGRESS = 2,
};
pub const DOT11_MSONEX_SUCCESS = DOT11_MSONEX_RESULT.SUCCESS;
pub const DOT11_MSONEX_FAILURE = DOT11_MSONEX_RESULT.FAILURE;
pub const DOT11_MSONEX_IN_PROGRESS = DOT11_MSONEX_RESULT.IN_PROGRESS;
pub const DOT11_EAP_RESULT = extern struct {
dwFailureReasonCode: u32,
pAttribArray: ?*EAP_ATTRIBUTES,
};
pub const DOT11_MSONEX_RESULT_PARAMS = extern struct {
Dot11OnexAuthStatus: ONEX_AUTH_STATUS,
Dot11OneXReasonCode: ONEX_REASON_CODE,
pbMPPESendKey: ?*u8,
dwMPPESendKeyLen: u32,
pbMPPERecvKey: ?*u8,
dwMPPERecvKeyLen: u32,
pDot11EapResult: ?*DOT11_EAP_RESULT,
};
pub const DOT11EXT_IHV_CONNECTIVITY_PROFILE = extern struct {
pszXmlFragmentIhvConnectivity: ?PWSTR,
};
pub const DOT11EXT_IHV_SECURITY_PROFILE = extern struct {
pszXmlFragmentIhvSecurity: ?PWSTR,
bUseMSOnex: BOOL,
};
pub const DOT11EXT_IHV_DISCOVERY_PROFILE = extern struct {
IhvConnectivityProfile: DOT11EXT_IHV_CONNECTIVITY_PROFILE,
IhvSecurityProfile: DOT11EXT_IHV_SECURITY_PROFILE,
};
pub const DOT11EXT_IHV_DISCOVERY_PROFILE_LIST = extern struct {
dwCount: u32,
pIhvDiscoveryProfiles: ?*DOT11EXT_IHV_DISCOVERY_PROFILE,
};
pub const DOT11EXT_IHV_INDICATION_TYPE = enum(i32) {
NicSpecificNotification = 0,
PmkidCandidateList = 1,
TkipMicFailure = 2,
PhyStateChange = 3,
LinkQuality = 4,
};
pub const IndicationTypeNicSpecificNotification = DOT11EXT_IHV_INDICATION_TYPE.NicSpecificNotification;
pub const IndicationTypePmkidCandidateList = DOT11EXT_IHV_INDICATION_TYPE.PmkidCandidateList;
pub const IndicationTypeTkipMicFailure = DOT11EXT_IHV_INDICATION_TYPE.TkipMicFailure;
pub const IndicationTypePhyStateChange = DOT11EXT_IHV_INDICATION_TYPE.PhyStateChange;
pub const IndicationTypeLinkQuality = DOT11EXT_IHV_INDICATION_TYPE.LinkQuality;
pub const DOT11EXT_VIRTUAL_STATION_AP_PROPERTY = extern struct {
dot11SSID: DOT11_SSID,
dot11AuthAlgo: DOT11_AUTH_ALGORITHM,
dot11CipherAlgo: DOT11_CIPHER_ALGORITHM,
bIsPassPhrase: BOOL,
dwKeyLength: u32,
ucKeyData: [64]u8,
};
pub const WDIAG_IHV_WLAN_ID = extern struct {
strProfileName: [256]u16,
Ssid: DOT11_SSID,
BssType: DOT11_BSS_TYPE,
dwFlags: u32,
dwReasonCode: u32,
};
pub const DOT11EXT_ALLOCATE_BUFFER = fn(
dwByteCount: u32,
ppvBuffer: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXT_FREE_BUFFER = fn(
pvMemory: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) void;
pub const DOT11EXT_SET_PROFILE_CUSTOM_USER_DATA = fn(
hDot11SvcHandle: ?HANDLE,
hConnectSession: ?HANDLE,
dwSessionID: u32,
dwDataSize: u32,
// TODO: what to do with BytesParamIndex 3?
pvData: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXT_GET_PROFILE_CUSTOM_USER_DATA = fn(
hDot11SvcHandle: ?HANDLE,
hConnectSession: ?HANDLE,
dwSessionID: u32,
pdwDataSize: ?*u32,
ppvData: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXT_SET_CURRENT_PROFILE = fn(
hDot11SvcHandle: ?HANDLE,
hConnectSession: ?HANDLE,
pIhvConnProfile: ?*DOT11EXT_IHV_CONNECTIVITY_PROFILE,
pIhvSecProfile: ?*DOT11EXT_IHV_SECURITY_PROFILE,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXT_SEND_UI_REQUEST = fn(
hDot11SvcHandle: ?HANDLE,
pIhvUIRequest: ?*DOT11EXT_IHV_UI_REQUEST,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXT_PRE_ASSOCIATE_COMPLETION = fn(
hDot11SvcHandle: ?HANDLE,
hConnectSession: ?HANDLE,
dwReasonCode: u32,
dwWin32Error: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXT_POST_ASSOCIATE_COMPLETION = fn(
hDot11SvcHandle: ?HANDLE,
hSecuritySessionID: ?HANDLE,
pPeer: ?*?*u8,
dwReasonCode: u32,
dwWin32Error: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXT_SEND_NOTIFICATION = fn(
hDot11SvcHandle: ?HANDLE,
pNotificationData: ?*L2_NOTIFICATION_DATA,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXT_SEND_PACKET = fn(
hDot11SvcHandle: ?HANDLE,
uPacketLen: u32,
// TODO: what to do with BytesParamIndex 1?
pvPacket: ?*anyopaque,
hSendCompletion: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXT_SET_ETHERTYPE_HANDLING = fn(
hDot11SvcHandle: ?HANDLE,
uMaxBackLog: u32,
uNumOfExemption: u32,
pExemption: ?[*]DOT11_PRIVACY_EXEMPTION,
uNumOfRegistration: u32,
pusRegistration: ?[*:0]u16,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXT_SET_AUTH_ALGORITHM = fn(
hDot11SvcHandle: ?HANDLE,
dwAuthAlgo: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXT_SET_UNICAST_CIPHER_ALGORITHM = fn(
hDot11SvcHandle: ?HANDLE,
dwUnicastCipherAlgo: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXT_SET_MULTICAST_CIPHER_ALGORITHM = fn(
hDot11SvcHandle: ?HANDLE,
dwMulticastCipherAlgo: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXT_SET_DEFAULT_KEY = fn(
hDot11SvcHandle: ?HANDLE,
pKey: ?*DOT11_CIPHER_DEFAULT_KEY_VALUE,
dot11Direction: DOT11_DIRECTION,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXT_SET_KEY_MAPPING_KEY = fn(
hDot11SvcHandle: ?HANDLE,
pKey: ?*DOT11_CIPHER_KEY_MAPPING_KEY_VALUE,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXT_SET_DEFAULT_KEY_ID = fn(
hDot11SvcHandle: ?HANDLE,
uDefaultKeyId: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXT_SET_EXCLUDE_UNENCRYPTED = fn(
hDot11SvcHandle: ?HANDLE,
bExcludeUnencrypted: BOOL,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXT_NIC_SPECIFIC_EXTENSION = fn(
hDot11SvcHandle: ?HANDLE,
dwInBufferSize: u32,
// TODO: what to do with BytesParamIndex 1?
pvInBuffer: ?*anyopaque,
pdwOutBufferSize: ?*u32,
// TODO: what to do with BytesParamIndex 3?
pvOutBuffer: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXT_ONEX_START = fn(
hDot11SvcHandle: ?HANDLE,
pEapAttributes: ?*EAP_ATTRIBUTES,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXT_ONEX_STOP = fn(
hDot11SvcHandle: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXT_PROCESS_ONEX_PACKET = fn(
hDot11SvcHandle: ?HANDLE,
dwInPacketSize: u32,
// TODO: what to do with BytesParamIndex 1?
pvInPacket: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXT_REQUEST_VIRTUAL_STATION = fn(
hDot11PrimaryHandle: ?HANDLE,
pvReserved: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXT_RELEASE_VIRTUAL_STATION = fn(
hDot11PrimaryHandle: ?HANDLE,
pvReserved: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXT_QUERY_VIRTUAL_STATION_PROPERTIES = fn(
hDot11SvcHandle: ?HANDLE,
pbIsVirtualStation: ?*BOOL,
pgPrimary: ?*Guid,
pvReserved: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXT_SET_VIRTUAL_STATION_AP_PROPERTIES = fn(
hDot11SvcHandle: ?HANDLE,
hConnectSession: ?HANDLE,
dwNumProperties: u32,
pProperties: [*]DOT11EXT_VIRTUAL_STATION_AP_PROPERTY,
pvReserved: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXTIHV_GET_VERSION_INFO = fn(
pDot11IHVVersionInfo: ?*DOT11_IHV_VERSION_INFO,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXTIHV_INIT_SERVICE = fn(
dwVerNumUsed: u32,
pDot11ExtAPI: ?*DOT11EXT_APIS,
pvReserved: ?*anyopaque,
pDot11IHVHandlers: ?*DOT11EXT_IHV_HANDLERS,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXTIHV_INIT_VIRTUAL_STATION = fn(
pDot11ExtVSAPI: ?*DOT11EXT_VIRTUAL_STATION_APIS,
pvReserved: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXTIHV_DEINIT_SERVICE = fn(
) callconv(@import("std").os.windows.WINAPI) void;
pub const DOT11EXTIHV_INIT_ADAPTER = fn(
pDot11Adapter: ?*DOT11_ADAPTER,
hDot11SvcHandle: ?HANDLE,
phIhvExtAdapter: ?*?HANDLE,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXTIHV_DEINIT_ADAPTER = fn(
hIhvExtAdapter: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) void;
pub const DOT11EXTIHV_PERFORM_PRE_ASSOCIATE = fn(
hIhvExtAdapter: ?HANDLE,
hConnectSession: ?HANDLE,
pIhvProfileParams: ?*DOT11EXT_IHV_PROFILE_PARAMS,
pIhvConnProfile: ?*DOT11EXT_IHV_CONNECTIVITY_PROFILE,
pIhvSecProfile: ?*DOT11EXT_IHV_SECURITY_PROFILE,
pConnectableBssid: ?*DOT11_BSS_LIST,
pdwReasonCode: ?*u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXTIHV_ADAPTER_RESET = fn(
hIhvExtAdapter: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXTIHV_PERFORM_POST_ASSOCIATE = fn(
hIhvExtAdapter: ?HANDLE,
hSecuritySessionID: ?HANDLE,
pPortState: ?*DOT11_PORT_STATE,
uDot11AssocParamsBytes: u32,
// TODO: what to do with BytesParamIndex 3?
pDot11AssocParams: ?*DOT11_ASSOCIATION_COMPLETION_PARAMETERS,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXTIHV_STOP_POST_ASSOCIATE = fn(
hIhvExtAdapter: ?HANDLE,
pPeer: ?*?*u8,
dot11AssocStatus: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXTIHV_VALIDATE_PROFILE = fn(
hIhvExtAdapter: ?HANDLE,
pIhvProfileParams: ?*DOT11EXT_IHV_PROFILE_PARAMS,
pIhvConnProfile: ?*DOT11EXT_IHV_CONNECTIVITY_PROFILE,
pIhvSecProfile: ?*DOT11EXT_IHV_SECURITY_PROFILE,
pdwReasonCode: ?*u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXTIHV_PERFORM_CAPABILITY_MATCH = fn(
hIhvExtAdapter: ?HANDLE,
pIhvProfileParams: ?*DOT11EXT_IHV_PROFILE_PARAMS,
pIhvConnProfile: ?*DOT11EXT_IHV_CONNECTIVITY_PROFILE,
pIhvSecProfile: ?*DOT11EXT_IHV_SECURITY_PROFILE,
pConnectableBssid: ?*DOT11_BSS_LIST,
pdwReasonCode: ?*u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXTIHV_CREATE_DISCOVERY_PROFILES = fn(
hIhvExtAdapter: ?HANDLE,
bInsecure: BOOL,
pIhvProfileParams: ?*DOT11EXT_IHV_PROFILE_PARAMS,
pConnectableBssid: ?*DOT11_BSS_LIST,
pIhvDiscoveryProfileList: ?*DOT11EXT_IHV_DISCOVERY_PROFILE_LIST,
pdwReasonCode: ?*u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXTIHV_PROCESS_SESSION_CHANGE = fn(
uEventType: u32,
pSessionNotification: ?*WTSSESSION_NOTIFICATION,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXTIHV_RECEIVE_INDICATION = fn(
hIhvExtAdapter: ?HANDLE,
indicationType: DOT11EXT_IHV_INDICATION_TYPE,
uBufferLength: u32,
// TODO: what to do with BytesParamIndex 2?
pvBuffer: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXTIHV_RECEIVE_PACKET = fn(
hIhvExtAdapter: ?HANDLE,
dwInBufferSize: u32,
// TODO: what to do with BytesParamIndex 1?
pvInBuffer: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXTIHV_SEND_PACKET_COMPLETION = fn(
hSendCompletion: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXTIHV_IS_UI_REQUEST_PENDING = fn(
guidUIRequest: Guid,
pbIsRequestPending: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXTIHV_PROCESS_UI_RESPONSE = fn(
guidUIRequest: Guid,
dwByteCount: u32,
// TODO: what to do with BytesParamIndex 1?
pvResponseBuffer: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXTIHV_QUERY_UI_REQUEST = fn(
hIhvExtAdapter: ?HANDLE,
connectionPhase: DOT11EXT_IHV_CONNECTION_PHASE,
ppIhvUIRequest: ?*?*DOT11EXT_IHV_UI_REQUEST,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXTIHV_ONEX_INDICATE_RESULT = fn(
hIhvExtAdapter: ?HANDLE,
msOneXResult: DOT11_MSONEX_RESULT,
pDot11MsOneXResultParams: ?*DOT11_MSONEX_RESULT_PARAMS,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXTIHV_CONTROL = fn(
hIhvExtAdapter: ?HANDLE,
dwInBufferSize: u32,
// TODO: what to do with BytesParamIndex 1?
pInBuffer: ?*u8,
dwOutBufferSize: u32,
// TODO: what to do with BytesParamIndex 3?
pOutBuffer: ?*u8,
pdwBytesReturned: ?*u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const DOT11EXT_APIS = extern struct {
Dot11ExtAllocateBuffer: ?DOT11EXT_ALLOCATE_BUFFER,
Dot11ExtFreeBuffer: ?DOT11EXT_FREE_BUFFER,
Dot11ExtSetProfileCustomUserData: ?DOT11EXT_SET_PROFILE_CUSTOM_USER_DATA,
Dot11ExtGetProfileCustomUserData: ?DOT11EXT_GET_PROFILE_CUSTOM_USER_DATA,
Dot11ExtSetCurrentProfile: ?DOT11EXT_SET_CURRENT_PROFILE,
Dot11ExtSendUIRequest: ?DOT11EXT_SEND_UI_REQUEST,
Dot11ExtPreAssociateCompletion: ?DOT11EXT_PRE_ASSOCIATE_COMPLETION,
Dot11ExtPostAssociateCompletion: ?DOT11EXT_POST_ASSOCIATE_COMPLETION,
Dot11ExtSendNotification: ?DOT11EXT_SEND_NOTIFICATION,
Dot11ExtSendPacket: ?DOT11EXT_SEND_PACKET,
Dot11ExtSetEtherTypeHandling: ?DOT11EXT_SET_ETHERTYPE_HANDLING,
Dot11ExtSetAuthAlgorithm: ?DOT11EXT_SET_AUTH_ALGORITHM,
Dot11ExtSetUnicastCipherAlgorithm: ?DOT11EXT_SET_UNICAST_CIPHER_ALGORITHM,
Dot11ExtSetMulticastCipherAlgorithm: ?DOT11EXT_SET_MULTICAST_CIPHER_ALGORITHM,
Dot11ExtSetDefaultKey: ?DOT11EXT_SET_DEFAULT_KEY,
Dot11ExtSetKeyMappingKey: ?DOT11EXT_SET_KEY_MAPPING_KEY,
Dot11ExtSetDefaultKeyId: ?DOT11EXT_SET_DEFAULT_KEY_ID,
Dot11ExtNicSpecificExtension: ?DOT11EXT_NIC_SPECIFIC_EXTENSION,
Dot11ExtSetExcludeUnencrypted: ?DOT11EXT_SET_EXCLUDE_UNENCRYPTED,
Dot11ExtStartOneX: ?DOT11EXT_ONEX_START,
Dot11ExtStopOneX: ?DOT11EXT_ONEX_STOP,
Dot11ExtProcessSecurityPacket: ?DOT11EXT_PROCESS_ONEX_PACKET,
};
pub const DOT11EXT_IHV_HANDLERS = extern struct {
Dot11ExtIhvDeinitService: ?DOT11EXTIHV_DEINIT_SERVICE,
Dot11ExtIhvInitAdapter: ?DOT11EXTIHV_INIT_ADAPTER,
Dot11ExtIhvDeinitAdapter: ?DOT11EXTIHV_DEINIT_ADAPTER,
Dot11ExtIhvPerformPreAssociate: ?DOT11EXTIHV_PERFORM_PRE_ASSOCIATE,
Dot11ExtIhvAdapterReset: ?DOT11EXTIHV_ADAPTER_RESET,
Dot11ExtIhvPerformPostAssociate: ?DOT11EXTIHV_PERFORM_POST_ASSOCIATE,
Dot11ExtIhvStopPostAssociate: ?DOT11EXTIHV_STOP_POST_ASSOCIATE,
Dot11ExtIhvValidateProfile: ?DOT11EXTIHV_VALIDATE_PROFILE,
Dot11ExtIhvPerformCapabilityMatch: ?DOT11EXTIHV_PERFORM_CAPABILITY_MATCH,
Dot11ExtIhvCreateDiscoveryProfiles: ?DOT11EXTIHV_CREATE_DISCOVERY_PROFILES,
Dot11ExtIhvProcessSessionChange: ?DOT11EXTIHV_PROCESS_SESSION_CHANGE,
Dot11ExtIhvReceiveIndication: ?DOT11EXTIHV_RECEIVE_INDICATION,
Dot11ExtIhvReceivePacket: ?DOT11EXTIHV_RECEIVE_PACKET,
Dot11ExtIhvSendPacketCompletion: ?DOT11EXTIHV_SEND_PACKET_COMPLETION,
Dot11ExtIhvIsUIRequestPending: ?DOT11EXTIHV_IS_UI_REQUEST_PENDING,
Dot11ExtIhvProcessUIResponse: ?DOT11EXTIHV_PROCESS_UI_RESPONSE,
Dot11ExtIhvQueryUIRequest: ?DOT11EXTIHV_QUERY_UI_REQUEST,
Dot11ExtIhvOnexIndicateResult: ?DOT11EXTIHV_ONEX_INDICATE_RESULT,
Dot11ExtIhvControl: ?DOT11EXTIHV_CONTROL,
};
pub const DOT11EXT_VIRTUAL_STATION_APIS = extern struct {
Dot11ExtRequestVirtualStation: ?DOT11EXT_REQUEST_VIRTUAL_STATION,
Dot11ExtReleaseVirtualStation: ?DOT11EXT_RELEASE_VIRTUAL_STATION,
Dot11ExtQueryVirtualStationProperties: ?DOT11EXT_QUERY_VIRTUAL_STATION_PROPERTIES,
Dot11ExtSetVirtualStationAPProperties: ?DOT11EXT_SET_VIRTUAL_STATION_AP_PROPERTIES,
};
//--------------------------------------------------------------------------------
// 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 (28)
//--------------------------------------------------------------------------------
const Guid = @import("../zig.zig").Guid;
const BOOL = @import("../foundation.zig").BOOL;
const BOOLEAN = @import("../foundation.zig").BOOLEAN;
const CHAR = @import("../foundation.zig").CHAR;
const DOT11_ASSOCIATION_COMPLETION_PARAMETERS = @import("../network_management/wi_fi.zig").DOT11_ASSOCIATION_COMPLETION_PARAMETERS;
const DOT11_AUTH_ALGORITHM = @import("../network_management/wi_fi.zig").DOT11_AUTH_ALGORITHM;
const DOT11_BSS_TYPE = @import("../network_management/wi_fi.zig").DOT11_BSS_TYPE;
const DOT11_CIPHER_ALGORITHM = @import("../network_management/wi_fi.zig").DOT11_CIPHER_ALGORITHM;
const DOT11_CIPHER_DEFAULT_KEY_VALUE = @import("../network_management/wi_fi.zig").DOT11_CIPHER_DEFAULT_KEY_VALUE;
const DOT11_CIPHER_KEY_MAPPING_KEY_VALUE = @import("../network_management/wi_fi.zig").DOT11_CIPHER_KEY_MAPPING_KEY_VALUE;
const DOT11_CURRENT_OPERATION_MODE = @import("../network_management/wi_fi.zig").DOT11_CURRENT_OPERATION_MODE;
const DOT11_DIRECTION = @import("../network_management/wi_fi.zig").DOT11_DIRECTION;
const DOT11_PRIVACY_EXEMPTION = @import("../network_management/wi_fi.zig").DOT11_PRIVACY_EXEMPTION;
const DOT11_SSID = @import("../network_management/wi_fi.zig").DOT11_SSID;
const EAP_ATTRIBUTES = @import("../security/extensible_authentication_protocol.zig").EAP_ATTRIBUTES;
const EAP_METHOD_TYPE = @import("../security/extensible_authentication_protocol.zig").EAP_METHOD_TYPE;
const HANDLE = @import("../foundation.zig").HANDLE;
const L2_NOTIFICATION_DATA = @import("../network_management/wi_fi.zig").L2_NOTIFICATION_DATA;
const LARGE_INTEGER = @import("../foundation.zig").LARGE_INTEGER;
const NET_IF_DIRECTION_TYPE = @import("../network_management/ip_helper.zig").NET_IF_DIRECTION_TYPE;
const NET_IF_MEDIA_CONNECT_STATE = @import("../network_management/ip_helper.zig").NET_IF_MEDIA_CONNECT_STATE;
const NET_IF_MEDIA_DUPLEX_STATE = @import("../network_management/ip_helper.zig").NET_IF_MEDIA_DUPLEX_STATE;
const NET_IF_OPER_STATUS = @import("../network_management/ip_helper.zig").NET_IF_OPER_STATUS;
const NET_LUID_LH = @import("../network_management/ip_helper.zig").NET_LUID_LH;
const ONEX_AUTH_STATUS = @import("../network_management/wi_fi.zig").ONEX_AUTH_STATUS;
const ONEX_REASON_CODE = @import("../network_management/wi_fi.zig").ONEX_REASON_CODE;
const PWSTR = @import("../foundation.zig").PWSTR;
const WTSSESSION_NOTIFICATION = @import("../system/remote_desktop.zig").WTSSESSION_NOTIFICATION;
test {
// The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476
if (@hasDecl(@This(), "DOT11EXT_ALLOCATE_BUFFER")) { _ = DOT11EXT_ALLOCATE_BUFFER; }
if (@hasDecl(@This(), "DOT11EXT_FREE_BUFFER")) { _ = DOT11EXT_FREE_BUFFER; }
if (@hasDecl(@This(), "DOT11EXT_SET_PROFILE_CUSTOM_USER_DATA")) { _ = DOT11EXT_SET_PROFILE_CUSTOM_USER_DATA; }
if (@hasDecl(@This(), "DOT11EXT_GET_PROFILE_CUSTOM_USER_DATA")) { _ = DOT11EXT_GET_PROFILE_CUSTOM_USER_DATA; }
if (@hasDecl(@This(), "DOT11EXT_SET_CURRENT_PROFILE")) { _ = DOT11EXT_SET_CURRENT_PROFILE; }
if (@hasDecl(@This(), "DOT11EXT_SEND_UI_REQUEST")) { _ = DOT11EXT_SEND_UI_REQUEST; }
if (@hasDecl(@This(), "DOT11EXT_PRE_ASSOCIATE_COMPLETION")) { _ = DOT11EXT_PRE_ASSOCIATE_COMPLETION; }
if (@hasDecl(@This(), "DOT11EXT_POST_ASSOCIATE_COMPLETION")) { _ = DOT11EXT_POST_ASSOCIATE_COMPLETION; }
if (@hasDecl(@This(), "DOT11EXT_SEND_NOTIFICATION")) { _ = DOT11EXT_SEND_NOTIFICATION; }
if (@hasDecl(@This(), "DOT11EXT_SEND_PACKET")) { _ = DOT11EXT_SEND_PACKET; }
if (@hasDecl(@This(), "DOT11EXT_SET_ETHERTYPE_HANDLING")) { _ = DOT11EXT_SET_ETHERTYPE_HANDLING; }
if (@hasDecl(@This(), "DOT11EXT_SET_AUTH_ALGORITHM")) { _ = DOT11EXT_SET_AUTH_ALGORITHM; }
if (@hasDecl(@This(), "DOT11EXT_SET_UNICAST_CIPHER_ALGORITHM")) { _ = DOT11EXT_SET_UNICAST_CIPHER_ALGORITHM; }
if (@hasDecl(@This(), "DOT11EXT_SET_MULTICAST_CIPHER_ALGORITHM")) { _ = DOT11EXT_SET_MULTICAST_CIPHER_ALGORITHM; }
if (@hasDecl(@This(), "DOT11EXT_SET_DEFAULT_KEY")) { _ = DOT11EXT_SET_DEFAULT_KEY; }
if (@hasDecl(@This(), "DOT11EXT_SET_KEY_MAPPING_KEY")) { _ = DOT11EXT_SET_KEY_MAPPING_KEY; }
if (@hasDecl(@This(), "DOT11EXT_SET_DEFAULT_KEY_ID")) { _ = DOT11EXT_SET_DEFAULT_KEY_ID; }
if (@hasDecl(@This(), "DOT11EXT_SET_EXCLUDE_UNENCRYPTED")) { _ = DOT11EXT_SET_EXCLUDE_UNENCRYPTED; }
if (@hasDecl(@This(), "DOT11EXT_NIC_SPECIFIC_EXTENSION")) { _ = DOT11EXT_NIC_SPECIFIC_EXTENSION; }
if (@hasDecl(@This(), "DOT11EXT_ONEX_START")) { _ = DOT11EXT_ONEX_START; }
if (@hasDecl(@This(), "DOT11EXT_ONEX_STOP")) { _ = DOT11EXT_ONEX_STOP; }
if (@hasDecl(@This(), "DOT11EXT_PROCESS_ONEX_PACKET")) { _ = DOT11EXT_PROCESS_ONEX_PACKET; }
if (@hasDecl(@This(), "DOT11EXT_REQUEST_VIRTUAL_STATION")) { _ = DOT11EXT_REQUEST_VIRTUAL_STATION; }
if (@hasDecl(@This(), "DOT11EXT_RELEASE_VIRTUAL_STATION")) { _ = DOT11EXT_RELEASE_VIRTUAL_STATION; }
if (@hasDecl(@This(), "DOT11EXT_QUERY_VIRTUAL_STATION_PROPERTIES")) { _ = DOT11EXT_QUERY_VIRTUAL_STATION_PROPERTIES; }
if (@hasDecl(@This(), "DOT11EXT_SET_VIRTUAL_STATION_AP_PROPERTIES")) { _ = DOT11EXT_SET_VIRTUAL_STATION_AP_PROPERTIES; }
if (@hasDecl(@This(), "DOT11EXTIHV_GET_VERSION_INFO")) { _ = DOT11EXTIHV_GET_VERSION_INFO; }
if (@hasDecl(@This(), "DOT11EXTIHV_INIT_SERVICE")) { _ = DOT11EXTIHV_INIT_SERVICE; }
if (@hasDecl(@This(), "DOT11EXTIHV_INIT_VIRTUAL_STATION")) { _ = DOT11EXTIHV_INIT_VIRTUAL_STATION; }
if (@hasDecl(@This(), "DOT11EXTIHV_DEINIT_SERVICE")) { _ = DOT11EXTIHV_DEINIT_SERVICE; }
if (@hasDecl(@This(), "DOT11EXTIHV_INIT_ADAPTER")) { _ = DOT11EXTIHV_INIT_ADAPTER; }
if (@hasDecl(@This(), "DOT11EXTIHV_DEINIT_ADAPTER")) { _ = DOT11EXTIHV_DEINIT_ADAPTER; }
if (@hasDecl(@This(), "DOT11EXTIHV_PERFORM_PRE_ASSOCIATE")) { _ = DOT11EXTIHV_PERFORM_PRE_ASSOCIATE; }
if (@hasDecl(@This(), "DOT11EXTIHV_ADAPTER_RESET")) { _ = DOT11EXTIHV_ADAPTER_RESET; }
if (@hasDecl(@This(), "DOT11EXTIHV_PERFORM_POST_ASSOCIATE")) { _ = DOT11EXTIHV_PERFORM_POST_ASSOCIATE; }
if (@hasDecl(@This(), "DOT11EXTIHV_STOP_POST_ASSOCIATE")) { _ = DOT11EXTIHV_STOP_POST_ASSOCIATE; }
if (@hasDecl(@This(), "DOT11EXTIHV_VALIDATE_PROFILE")) { _ = DOT11EXTIHV_VALIDATE_PROFILE; }
if (@hasDecl(@This(), "DOT11EXTIHV_PERFORM_CAPABILITY_MATCH")) { _ = DOT11EXTIHV_PERFORM_CAPABILITY_MATCH; }
if (@hasDecl(@This(), "DOT11EXTIHV_CREATE_DISCOVERY_PROFILES")) { _ = DOT11EXTIHV_CREATE_DISCOVERY_PROFILES; }
if (@hasDecl(@This(), "DOT11EXTIHV_PROCESS_SESSION_CHANGE")) { _ = DOT11EXTIHV_PROCESS_SESSION_CHANGE; }
if (@hasDecl(@This(), "DOT11EXTIHV_RECEIVE_INDICATION")) { _ = DOT11EXTIHV_RECEIVE_INDICATION; }
if (@hasDecl(@This(), "DOT11EXTIHV_RECEIVE_PACKET")) { _ = DOT11EXTIHV_RECEIVE_PACKET; }
if (@hasDecl(@This(), "DOT11EXTIHV_SEND_PACKET_COMPLETION")) { _ = DOT11EXTIHV_SEND_PACKET_COMPLETION; }
if (@hasDecl(@This(), "DOT11EXTIHV_IS_UI_REQUEST_PENDING")) { _ = DOT11EXTIHV_IS_UI_REQUEST_PENDING; }
if (@hasDecl(@This(), "DOT11EXTIHV_PROCESS_UI_RESPONSE")) { _ = DOT11EXTIHV_PROCESS_UI_RESPONSE; }
if (@hasDecl(@This(), "DOT11EXTIHV_QUERY_UI_REQUEST")) { _ = DOT11EXTIHV_QUERY_UI_REQUEST; }
if (@hasDecl(@This(), "DOT11EXTIHV_ONEX_INDICATE_RESULT")) { _ = DOT11EXTIHV_ONEX_INDICATE_RESULT; }
if (@hasDecl(@This(), "DOT11EXTIHV_CONTROL")) { _ = DOT11EXTIHV_CONTROL; }
@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/network_management/ndis.zig |
const builtin = @import("builtin");
const std = @import("std");
const audio_experiments = @import("samples/audio_experiments/build.zig");
const audio_playback_test = @import("samples/audio_playback_test/build.zig");
const bindless = @import("samples/bindless/build.zig");
const bullet_physics_test = @import("samples/bullet_physics_test/build.zig");
const directml_convolution_test = @import("samples/directml_convolution_test/build.zig");
const mesh_shader_test = @import("samples/mesh_shader_test/build.zig");
const physically_based_rendering = @import("samples/physically_based_rendering/build.zig");
const rasterization = @import("samples/rasterization/build.zig");
const simple3d = @import("samples/simple3d/build.zig");
const simple_raytracer = @import("samples/simple_raytracer/build.zig");
const textured_quad = @import("samples/textured_quad/build.zig");
const triangle = @import("samples/triangle/build.zig");
const vector_graphics_test = @import("samples/vector_graphics_test/build.zig");
const intro = @import("samples/intro/build.zig");
const minimal = @import("samples/minimal/build.zig");
pub const Options = struct {
build_mode: std.builtin.Mode,
target: std.zig.CrossTarget,
enable_pix: bool,
enable_dx_debug: bool,
enable_dx_gpu_debug: bool,
tracy: ?[]const u8,
};
pub fn build(b: *std.build.Builder) void {
const enable_pix = b.option(bool, "enable-pix", "Enable PIX GPU events and markers") orelse false;
const enable_dx_debug = b.option(
bool,
"enable-dx-debug",
"Enable debug layer for D3D12, D2D1, DirectML and DXGI",
) orelse false;
const enable_dx_gpu_debug = b.option(
bool,
"enable-dx-gpu-debug",
"Enable GPU-based validation for D3D12",
) orelse false;
const tracy = b.option([]const u8, "tracy", "Enable Tracy profiler integration (supply path to Tracy source)");
const options = Options{
.build_mode = b.standardReleaseOptions(),
.target = b.standardTargetOptions(.{}),
.enable_pix = enable_pix,
.enable_dx_debug = enable_dx_debug,
.enable_dx_gpu_debug = enable_dx_gpu_debug,
.tracy = tracy,
};
if (options.target.isWindows()) {
installDemo(b, audio_experiments.build(b, options), "audio_experiments");
installDemo(b, audio_playback_test.build(b, options), "audio_playback_test");
installDemo(b, bindless.build(b, options), "bindless");
installDemo(b, bullet_physics_test.build(b, options), "bullet_physics_test");
installDemo(b, directml_convolution_test.build(b, options), "directml_convolution_test");
installDemo(b, mesh_shader_test.build(b, options), "mesh_shader_test");
installDemo(b, physically_based_rendering.build(b, options), "physically_based_rendering");
installDemo(b, rasterization.build(b, options), "rasterization");
installDemo(b, simple3d.build(b, options), "simple3d");
installDemo(b, simple_raytracer.build(b, options), "simple_raytracer");
installDemo(b, textured_quad.build(b, options), "textured_quad");
installDemo(b, vector_graphics_test.build(b, options), "vector_graphics_test");
installDemo(b, triangle.build(b, options), "triangle");
installDemo(b, intro.build(b, options, 0), "intro0");
installDemo(b, intro.build(b, options, 1), "intro1");
installDemo(b, intro.build(b, options, 2), "intro2");
installDemo(b, intro.build(b, options, 3), "intro3");
installDemo(b, intro.build(b, options, 4), "intro4");
installDemo(b, intro.build(b, options, 5), "intro5");
installDemo(b, intro.build(b, options, 6), "intro6");
installDemo(b, minimal.build(b, options), "minimal");
} else {
std.log.info("This project requires Windows.", .{});
}
}
fn installDemo(b: *std.build.Builder, exe: *std.build.LibExeObjStep, comptime name: []const u8) void {
const install = b.step(name, "Build '" ++ name ++ "' demo");
install.dependOn(&b.addInstallArtifact(exe).step);
const run_step = b.step(name ++ "-run", "Run '" ++ name ++ "' demo");
const run_cmd = exe.run();
run_cmd.step.dependOn(install);
run_step.dependOn(&run_cmd.step);
b.getInstallStep().dependOn(install);
} | build.zig |
const std = @import("std");
// const math = std.math;
const math = @import("lib.zig");
const expect = std.testing.expect;
/// Returns e raised to the power of x (e^x).
///
/// Special Cases:
/// - exp(+inf) = +inf
/// - exp(nan) = nan
pub fn exp(x: anytype) @TypeOf(x) {
const T = @TypeOf(x);
return switch (T) {
f32 => exp32(x),
f64 => exp64(x),
f128 => exp128(x),
else => @compileError("exp not implemented for " ++ @typeName(T)),
};
}
fn exp32(x_: f32) f32 {
const half = [_]f32{ 0.5, -0.5 };
const ln2hi = 6.9314575195e-1;
const ln2lo = 1.4286067653e-6;
const invln2 = 1.4426950216e+0;
const P1 = 1.6666625440e-1;
const P2 = -2.7667332906e-3;
var x = x_;
var hx = @bitCast(u32, x);
const sign = @intCast(i32, hx >> 31);
hx &= 0x7FFFFFFF;
if (math.isNan(x)) {
return math.nan(f32);
}
// |x| >= -87.33655 or nan
if (hx >= 0x42AEAC50) {
// nan
if (hx > 0x7F800000) {
return x;
}
// x >= 88.722839
if (hx >= 0x42b17218 and sign == 0) {
return x * 0x1.0p127;
}
if (sign != 0) {
math.doNotOptimizeAway(-0x1.0p-149 / x); // overflow
// x <= -103.972084
if (hx >= 0x42CFF1B5) {
return 0;
}
}
}
var k: i32 = undefined;
var hi: f32 = undefined;
var lo: f32 = undefined;
// |x| > 0.5 * ln2
if (hx > 0x3EB17218) {
// |x| > 1.5 * ln2
if (hx > 0x3F851592) {
k = @floatToInt(i32, invln2 * x + half[@intCast(usize, sign)]);
} else {
k = 1 - sign - sign;
}
const fk = @intToFloat(f32, k);
hi = x - fk * ln2hi;
lo = fk * ln2lo;
x = hi - lo;
}
// |x| > 2^(-14)
else if (hx > 0x39000000) {
k = 0;
hi = x;
lo = 0;
} else {
math.doNotOptimizeAway(0x1.0p127 + x); // inexact
return 1 + x;
}
const xx = x * x;
const c = x - xx * (P1 + xx * P2);
const y = 1 + (x * c / (2 - c) - lo + hi);
if (k == 0) {
return y;
} else {
return math.scalbn(y, k);
}
}
fn exp64(x_: f64) f64 {
const half = [_]f64{ 0.5, -0.5 };
const ln2hi: f64 = 6.93147180369123816490e-01;
const ln2lo: f64 = 1.90821492927058770002e-10;
const invln2: f64 = 1.44269504088896338700e+00;
const P1: f64 = 1.66666666666666019037e-01;
const P2: f64 = -2.77777777770155933842e-03;
const P3: f64 = 6.61375632143793436117e-05;
const P4: f64 = -1.65339022054652515390e-06;
const P5: f64 = 4.13813679705723846039e-08;
var x = x_;
var ux = @bitCast(u64, x);
var hx = ux >> 32;
const sign = @intCast(i32, hx >> 31);
hx &= 0x7FFFFFFF;
if (math.isNan(x)) {
return math.nan(f64);
}
// |x| >= 708.39 or nan
if (hx >= 0x4086232B) {
// nan
if (hx > 0x7FF00000) {
return x;
}
if (x > 709.782712893383973096) {
// overflow if x != inf
if (!math.isInf(x)) {
math.raiseOverflow();
}
return math.inf(f64);
}
if (x < -708.39641853226410622) {
// underflow if x != -inf
// math.doNotOptimizeAway(@as(f32, -0x1.0p-149 / x));
if (x < -745.13321910194110842) {
return 0;
}
}
}
// argument reduction
var k: i32 = undefined;
var hi: f64 = undefined;
var lo: f64 = undefined;
// |x| > 0.5 * ln2
if (hx > 0x3FD62E42) {
// |x| >= 1.5 * ln2
if (hx > 0x3FF0A2B2) {
k = @floatToInt(i32, invln2 * x + half[@intCast(usize, sign)]);
} else {
k = 1 - sign - sign;
}
const dk = @intToFloat(f64, k);
hi = x - dk * ln2hi;
lo = dk * ln2lo;
x = hi - lo;
}
// |x| > 2^(-28)
else if (hx > 0x3E300000) {
k = 0;
hi = x;
lo = 0;
} else {
// inexact if x != 0
// math.doNotOptimizeAway(0x1.0p1023 + x);
return 1 + x;
}
const xx = x * x;
const c = x - xx * (P1 + xx * (P2 + xx * (P3 + xx * (P4 + xx * P5))));
const y = 1 + (x * c / (2 - c) - lo + hi);
if (k == 0) {
return y;
} else {
return math.scalbn(y, k);
}
}
// from: FreeBSD: head/lib/msun/ld128/s_expl.c 251345 2013-06-03 20:09:22Z kargl
// SPDX-License-Identifier: BSD-2-Clause-FreeBSD
//
// Copyright (c) 2009-2013 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice unmodified, this list of conditions, and the following
// disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Optimized by <NAME>.
const INTERVALS = 128;
const LOG2_INTERVALS = 7;
const exp_128_table = [INTERVALS]struct { hi: f128, lo: f128 }{
.{ .hi = 0x1p0, .lo = 0x0p0 },
.{ .hi = 0x1.0163da9fb33356d84a66aep0, .lo = 0x3.36dcdfa4003ec04c360be2404078p-92 },
.{ .hi = 0x1.02c9a3e778060ee6f7cacap0, .lo = 0x4.f7a29bde93d70a2cabc5cb89ba10p-92 },
.{ .hi = 0x1.04315e86e7f84bd738f9a2p0, .lo = 0xd.a47e6ed040bb4bfc05af6455e9b8p-96 },
.{ .hi = 0x1.059b0d31585743ae7c548ep0, .lo = 0xb.68ca417fe53e3495f7df4baf84a0p-92 },
.{ .hi = 0x1.0706b29ddf6ddc6dc403a8p0, .lo = 0x1.d87b27ed07cb8b092ac75e311753p-88 },
.{ .hi = 0x1.0874518759bc808c35f25cp0, .lo = 0x1.9427fa2b041b2d6829d8993a0d01p-88 },
.{ .hi = 0x1.09e3ecac6f3834521e060cp0, .lo = 0x5.84d6b74ba2e023da730e7fccb758p-92 },
.{ .hi = 0x1.0b5586cf9890f6298b92b6p0, .lo = 0x1.1842a98364291408b3ceb0a2a2bbp-88 },
.{ .hi = 0x1.0cc922b7247f7407b705b8p0, .lo = 0x9.3dc5e8aac564e6fe2ef1d431fd98p-92 },
.{ .hi = 0x1.0e3ec32d3d1a2020742e4ep0, .lo = 0x1.8af6a552ac4b358b1129e9f966a4p-88 },
.{ .hi = 0x1.0fb66affed31af232091dcp0, .lo = 0x1.8a1426514e0b627bda694a400a27p-88 },
.{ .hi = 0x1.11301d0125b50a4ebbf1aep0, .lo = 0xd.9318ceac5cc47ab166ee57427178p-92 },
.{ .hi = 0x1.12abdc06c31cbfb92bad32p0, .lo = 0x4.d68e2f7270bdf7cedf94eb1cb818p-92 },
.{ .hi = 0x1.1429aaea92ddfb34101942p0, .lo = 0x1.b2586d01844b389bea7aedd221d4p-88 },
.{ .hi = 0x1.15a98c8a58e512480d573cp0, .lo = 0x1.d5613bf92a2b618ee31b376c2689p-88 },
.{ .hi = 0x1.172b83c7d517adcdf7c8c4p0, .lo = 0x1.0eb14a792035509ff7d758693f24p-88 },
.{ .hi = 0x1.18af9388c8de9bbbf70b9ap0, .lo = 0x3.c2505c97c0102e5f1211941d2840p-92 },
.{ .hi = 0x1.1a35beb6fcb753cb698f68p0, .lo = 0x1.2d1c835a6c30724d5cfae31b84e5p-88 },
.{ .hi = 0x1.1bbe084045cd39ab1e72b4p0, .lo = 0x4.27e35f9acb57e473915519a1b448p-92 },
.{ .hi = 0x1.1d4873168b9aa7805b8028p0, .lo = 0x9.90f07a98b42206e46166cf051d70p-92 },
.{ .hi = 0x1.1ed5022fcd91cb8819ff60p0, .lo = 0x1.121d1e504d36c47474c9b7de6067p-88 },
.{ .hi = 0x1.2063b88628cd63b8eeb028p0, .lo = 0x1.50929d0fc487d21c2b84004264dep-88 },
.{ .hi = 0x1.21f49917ddc962552fd292p0, .lo = 0x9.4bdb4b61ea62477caa1dce823ba0p-92 },
.{ .hi = 0x1.2387a6e75623866c1fadb0p0, .lo = 0x1.c15cb593b0328566902df69e4de2p-88 },
.{ .hi = 0x1.251ce4fb2a63f3582ab7dep0, .lo = 0x9.e94811a9c8afdcf796934bc652d0p-92 },
.{ .hi = 0x1.26b4565e27cdd257a67328p0, .lo = 0x1.d3b249dce4e9186ddd5ff44e6b08p-92 },
.{ .hi = 0x1.284dfe1f5638096cf15cf0p0, .lo = 0x3.ca0967fdaa2e52d7c8106f2e262cp-92 },
.{ .hi = 0x1.29e9df51fdee12c25d15f4p0, .lo = 0x1.a24aa3bca890ac08d203fed80a07p-88 },
.{ .hi = 0x1.2b87fd0dad98ffddea4652p0, .lo = 0x1.8fcab88442fdc3cb6de4519165edp-88 },
.{ .hi = 0x1.2d285a6e4030b40091d536p0, .lo = 0xd.075384589c1cd1b3e4018a6b1348p-92 },
.{ .hi = 0x1.2ecafa93e2f5611ca0f45cp0, .lo = 0x1.523833af611bdcda253c554cf278p-88 },
.{ .hi = 0x1.306fe0a31b7152de8d5a46p0, .lo = 0x3.05c85edecbc27343629f502f1af2p-92 },
.{ .hi = 0x1.32170fc4cd8313539cf1c2p0, .lo = 0x1.008f86dde3220ae17a005b6412bep-88 },
.{ .hi = 0x1.33c08b26416ff4c9c8610cp0, .lo = 0x1.96696bf95d1593039539d94d662bp-88 },
.{ .hi = 0x1.356c55f929ff0c94623476p0, .lo = 0x3.73af38d6d8d6f9506c9bbc93cbc0p-92 },
.{ .hi = 0x1.371a7373aa9caa7145502ep0, .lo = 0x1.4547987e3e12516bf9c699be432fp-88 },
.{ .hi = 0x1.38cae6d05d86585a9cb0d8p0, .lo = 0x1.bed0c853bd30a02790931eb2e8f0p-88 },
.{ .hi = 0x1.3a7db34e59ff6ea1bc9298p0, .lo = 0x1.e0a1d336163fe2f852ceeb134067p-88 },
.{ .hi = 0x1.3c32dc313a8e484001f228p0, .lo = 0xb.58f3775e06ab66353001fae9fca0p-92 },
.{ .hi = 0x1.3dea64c12342235b41223ep0, .lo = 0x1.3d773fba2cb82b8244267c54443fp-92 },
.{ .hi = 0x1.3fa4504ac801ba0bf701aap0, .lo = 0x4.1832fb8c1c8dbdff2c49909e6c60p-92 },
.{ .hi = 0x1.4160a21f72e29f84325b8ep0, .lo = 0x1.3db61fb352f0540e6ba05634413ep-88 },
.{ .hi = 0x1.431f5d950a896dc7044394p0, .lo = 0x1.0ccec81e24b0caff7581ef4127f7p-92 },
.{ .hi = 0x1.44e086061892d03136f408p0, .lo = 0x1.df019fbd4f3b48709b78591d5cb5p-88 },
.{ .hi = 0x1.46a41ed1d005772512f458p0, .lo = 0x1.229d97df404ff21f39c1b594d3a8p-88 },
.{ .hi = 0x1.486a2b5c13cd013c1a3b68p0, .lo = 0x1.062f03c3dd75ce8757f780e6ec99p-88 },
.{ .hi = 0x1.4a32af0d7d3de672d8bcf4p0, .lo = 0x6.f9586461db1d878b1d148bd3ccb8p-92 },
.{ .hi = 0x1.4bfdad5362a271d4397afep0, .lo = 0xc.42e20e0363ba2e159c579f82e4b0p-92 },
.{ .hi = 0x1.4dcb299fddd0d63b36ef1ap0, .lo = 0x9.e0cc484b25a5566d0bd5f58ad238p-92 },
.{ .hi = 0x1.4f9b2769d2ca6ad33d8b68p0, .lo = 0x1.aa073ee55e028497a329a7333dbap-88 },
.{ .hi = 0x1.516daa2cf6641c112f52c8p0, .lo = 0x4.d822190e718226177d7608d20038p-92 },
.{ .hi = 0x1.5342b569d4f81df0a83c48p0, .lo = 0x1.d86a63f4e672a3e429805b049465p-88 },
.{ .hi = 0x1.551a4ca5d920ec52ec6202p0, .lo = 0x4.34ca672645dc6c124d6619a87574p-92 },
.{ .hi = 0x1.56f4736b527da66ecb0046p0, .lo = 0x1.64eb3c00f2f5ab3d801d7cc7272dp-88 },
.{ .hi = 0x1.58d12d497c7fd252bc2b72p0, .lo = 0x1.43bcf2ec936a970d9cc266f0072fp-88 },
.{ .hi = 0x1.5ab07dd48542958c930150p0, .lo = 0x1.91eb345d88d7c81280e069fbdb63p-88 },
.{ .hi = 0x1.5c9268a5946b701c4b1b80p0, .lo = 0x1.6986a203d84e6a4a92f179e71889p-88 },
.{ .hi = 0x1.5e76f15ad21486e9be4c20p0, .lo = 0x3.99766a06548a05829e853bdb2b52p-92 },
.{ .hi = 0x1.605e1b976dc08b076f592ap0, .lo = 0x4.86e3b34ead1b4769df867b9c89ccp-92 },
.{ .hi = 0x1.6247eb03a5584b1f0fa06ep0, .lo = 0x1.d2da42bb1ceaf9f732275b8aef30p-88 },
.{ .hi = 0x1.6434634ccc31fc76f8714cp0, .lo = 0x4.ed9a4e41000307103a18cf7a6e08p-92 },
.{ .hi = 0x1.66238825522249127d9e28p0, .lo = 0x1.b8f314a337f4dc0a3adf1787ff74p-88 },
.{ .hi = 0x1.68155d44ca973081c57226p0, .lo = 0x1.b9f32706bfe4e627d809a85dcc66p-88 },
.{ .hi = 0x1.6a09e667f3bcc908b2fb12p0, .lo = 0x1.66ea957d3e3adec17512775099dap-88 },
.{ .hi = 0x1.6c012750bdabeed76a9980p0, .lo = 0xf.4f33fdeb8b0ecd831106f57b3d00p-96 },
.{ .hi = 0x1.6dfb23c651a2ef220e2cbep0, .lo = 0x1.bbaa834b3f11577ceefbe6c1c411p-92 },
.{ .hi = 0x1.6ff7df9519483cf87e1b4ep0, .lo = 0x1.3e213bff9b702d5aa477c12523cep-88 },
.{ .hi = 0x1.71f75e8ec5f73dd2370f2ep0, .lo = 0xf.0acd6cb434b562d9e8a20adda648p-92 },
.{ .hi = 0x1.73f9a48a58173bd5c9a4e6p0, .lo = 0x8.ab1182ae217f3a7681759553e840p-92 },
.{ .hi = 0x1.75feb564267c8bf6e9aa32p0, .lo = 0x1.a48b27071805e61a17b954a2dad8p-88 },
.{ .hi = 0x1.780694fde5d3f619ae0280p0, .lo = 0x8.58b2bb2bdcf86cd08e35fb04c0f0p-92 },
.{ .hi = 0x1.7a11473eb0186d7d51023ep0, .lo = 0x1.6cda1f5ef42b66977960531e821bp-88 },
.{ .hi = 0x1.7c1ed0130c1327c4933444p0, .lo = 0x1.937562b2dc933d44fc828efd4c9cp-88 },
.{ .hi = 0x1.7e2f336cf4e62105d02ba0p0, .lo = 0x1.5797e170a1427f8fcdf5f3906108p-88 },
.{ .hi = 0x1.80427543e1a11b60de6764p0, .lo = 0x9.a354ea706b8e4d8b718a672bf7c8p-92 },
.{ .hi = 0x1.82589994cce128acf88afap0, .lo = 0xb.34a010f6ad65cbbac0f532d39be0p-92 },
.{ .hi = 0x1.8471a4623c7acce52f6b96p0, .lo = 0x1.c64095370f51f48817914dd78665p-88 },
.{ .hi = 0x1.868d99b4492ec80e41d90ap0, .lo = 0xc.251707484d73f136fb5779656b70p-92 },
.{ .hi = 0x1.88ac7d98a669966530bcdep0, .lo = 0x1.2d4e9d61283ef385de170ab20f96p-88 },
.{ .hi = 0x1.8ace5422aa0db5ba7c55a0p0, .lo = 0x1.92c9bb3e6ed61f2733304a346d8fp-88 },
.{ .hi = 0x1.8cf3216b5448bef2aa1cd0p0, .lo = 0x1.61c55d84a9848f8c453b3ca8c946p-88 },
.{ .hi = 0x1.8f1ae991577362b982745cp0, .lo = 0x7.2ed804efc9b4ae1458ae946099d4p-92 },
.{ .hi = 0x1.9145b0b91ffc588a61b468p0, .lo = 0x1.f6b70e01c2a90229a4c4309ea719p-88 },
.{ .hi = 0x1.93737b0cdc5e4f4501c3f2p0, .lo = 0x5.40a22d2fc4af581b63e8326efe9cp-92 },
.{ .hi = 0x1.95a44cbc8520ee9b483694p0, .lo = 0x1.a0fc6f7c7d61b2b3a22a0eab2cadp-88 },
.{ .hi = 0x1.97d829fde4e4f8b9e920f8p0, .lo = 0x1.1e8bd7edb9d7144b6f6818084cc7p-88 },
.{ .hi = 0x1.9a0f170ca07b9ba3109b8cp0, .lo = 0x4.6737beb19e1eada6825d3c557428p-92 },
.{ .hi = 0x1.9c49182a3f0901c7c46b06p0, .lo = 0x1.1f2be58ddade50c217186c90b457p-88 },
.{ .hi = 0x1.9e86319e323231824ca78ep0, .lo = 0x6.4c6e010f92c082bbadfaf605cfd4p-92 },
.{ .hi = 0x1.a0c667b5de564b29ada8b8p0, .lo = 0xc.ab349aa0422a8da7d4512edac548p-92 },
.{ .hi = 0x1.a309bec4a2d3358c171f76p0, .lo = 0x1.0daad547fa22c26d168ea762d854p-88 },
.{ .hi = 0x1.a5503b23e255c8b424491cp0, .lo = 0xa.f87bc8050a405381703ef7caff50p-92 },
.{ .hi = 0x1.a799e1330b3586f2dfb2b0p0, .lo = 0x1.58f1a98796ce8908ae852236ca94p-88 },
.{ .hi = 0x1.a9e6b5579fdbf43eb243bcp0, .lo = 0x1.ff4c4c58b571cf465caf07b4b9f5p-88 },
.{ .hi = 0x1.ac36bbfd3f379c0db966a2p0, .lo = 0x1.1265fc73e480712d20f8597a8e7bp-88 },
.{ .hi = 0x1.ae89f995ad3ad5e8734d16p0, .lo = 0x1.73205a7fbc3ae675ea440b162d6cp-88 },
.{ .hi = 0x1.b0e07298db66590842acdep0, .lo = 0x1.c6f6ca0e5dcae2aafffa7a0554cbp-88 },
.{ .hi = 0x1.b33a2b84f15faf6bfd0e7ap0, .lo = 0x1.d947c2575781dbb49b1237c87b6ep-88 },
.{ .hi = 0x1.b59728de559398e3881110p0, .lo = 0x1.64873c7171fefc410416be0a6525p-88 },
.{ .hi = 0x1.b7f76f2fb5e46eaa7b081ap0, .lo = 0xb.53c5354c8903c356e4b625aacc28p-92 },
.{ .hi = 0x1.ba5b030a10649840cb3c6ap0, .lo = 0xf.5b47f297203757e1cc6eadc8bad0p-92 },
.{ .hi = 0x1.bcc1e904bc1d2247ba0f44p0, .lo = 0x1.b3d08cd0b20287092bd59be4ad98p-88 },
.{ .hi = 0x1.bf2c25bd71e088408d7024p0, .lo = 0x1.18e3449fa073b356766dfb568ff4p-88 },
.{ .hi = 0x1.c199bdd85529c2220cb12ap0, .lo = 0x9.1ba6679444964a36661240043970p-96 },
.{ .hi = 0x1.c40ab5fffd07a6d14df820p0, .lo = 0xf.1828a5366fd387a7bdd54cdf7300p-92 },
.{ .hi = 0x1.c67f12e57d14b4a2137fd2p0, .lo = 0xf.2b301dd9e6b151a6d1f9d5d5f520p-96 },
.{ .hi = 0x1.c8f6d9406e7b511acbc488p0, .lo = 0x5.c442ddb55820171f319d9e5076a8p-96 },
.{ .hi = 0x1.cb720dcef90691503cbd1ep0, .lo = 0x9.49db761d9559ac0cb6dd3ed599e0p-92 },
.{ .hi = 0x1.cdf0b555dc3f9c44f8958ep0, .lo = 0x1.ac51be515f8c58bdfb6f5740a3a4p-88 },
.{ .hi = 0x1.d072d4a07897b8d0f22f20p0, .lo = 0x1.a158e18fbbfc625f09f4cca40874p-88 },
.{ .hi = 0x1.d2f87080d89f18ade12398p0, .lo = 0x9.ea2025b4c56553f5cdee4c924728p-92 },
.{ .hi = 0x1.d5818dcfba48725da05aeap0, .lo = 0x1.66e0dca9f589f559c0876ff23830p-88 },
.{ .hi = 0x1.d80e316c98397bb84f9d04p0, .lo = 0x8.805f84bec614de269900ddf98d28p-92 },
.{ .hi = 0x1.da9e603db3285708c01a5ap0, .lo = 0x1.6d4c97f6246f0ec614ec95c99392p-88 },
.{ .hi = 0x1.dd321f301b4604b695de3cp0, .lo = 0x6.30a393215299e30d4fb73503c348p-96 },
.{ .hi = 0x1.dfc97337b9b5eb968cac38p0, .lo = 0x1.ed291b7225a944efd5bb5524b927p-88 },
.{ .hi = 0x1.e264614f5a128a12761fa0p0, .lo = 0x1.7ada6467e77f73bf65e04c95e29dp-88 },
.{ .hi = 0x1.e502ee78b3ff6273d13014p0, .lo = 0x1.3991e8f49659e1693be17ae1d2f9p-88 },
.{ .hi = 0x1.e7a51fbc74c834b548b282p0, .lo = 0x1.23786758a84f4956354634a416cep-88 },
.{ .hi = 0x1.ea4afa2a490d9858f73a18p0, .lo = 0xf.5db301f86dea20610ceee13eb7b8p-92 },
.{ .hi = 0x1.ecf482d8e67f08db0312fap0, .lo = 0x1.949cef462010bb4bc4ce72a900dfp-88 },
.{ .hi = 0x1.efa1bee615a27771fd21a8p0, .lo = 0x1.2dac1f6dd5d229ff68e46f27e3dfp-88 },
.{ .hi = 0x1.f252b376bba974e8696fc2p0, .lo = 0x1.6390d4c6ad5476b5162f40e1d9a9p-88 },
.{ .hi = 0x1.f50765b6e4540674f84b76p0, .lo = 0x2.862baff99000dfc4352ba29b8908p-92 },
.{ .hi = 0x1.f7bfdad9cbe138913b4bfep0, .lo = 0x7.2bd95c5ce7280fa4d2344a3f5618p-92 },
.{ .hi = 0x1.fa7c1819e90d82e90a7e74p0, .lo = 0xb.263c1dc060c36f7650b4c0f233a8p-92 },
.{ .hi = 0x1.fd3c22b8f71f10975ba4b2p0, .lo = 0x1.2bcf3a5e12d269d8ad7c1a4a8875p-88 },
};
fn exp128(x: f128) f128 {
const L1: f128 = 5.41521234812457272982212595914567508e-3;
const L2: f64 = -1.0253670638894731e-29; // -0x1.9ff0342542fc3p-97
const inv_L: f64 = 1.8466496523378731e+2; // 0x1.71547652b82fep+7
const A2: f128 = 0.5;
const A3: f128 = 1.66666666666666666666666666651085500e-1;
const A4: f128 = 4.16666666666666666666666666425885320e-2;
const A5: f128 = 8.33333333333333333334522877160175842e-3;
const A6: f128 = 1.38888888888888888889971139751596836e-3;
const A7: f64 = 1.9841269841269470e-4; // 0x1.a01a01a019f91p-13
const A8: f64 = 2.4801587301585286e-5; // 0x1.71de3ec75a967p-19
const A9: f64 = 2.7557324277411235e-6; // 0x1.71de3ec75a967p-19
const A10: f64 = 2.7557333722375069e-7; // 0x1.27e505ab56259p-22
// Last values before overflow/underflow/subnormal.
const o_threshold = 11356.523406294143949491931077970763428; // 0x1.62e42fefa39ef35793c7673007e5p+13
const u_threshold = -11433.462743336297878837243843452621503; // -0x1.654bb3b2c73ebb059fabb506ff33p+13
const s_threshold = -11355.137111933024058873096613727848253; // -0x1.62d918ce2421d65ff90ac8f4ce65p+13
const ux: u128 = @bitCast(u128, x);
var hx: u32 = @intCast(u32, ux >> 96);
// const sign = @intCast(i32, hx >> 31);
hx &= 0x7FFFFFFF;
if (math.isNan(x)) {
return math.nan(f128);
}
// |x| >= 11355.1371... or NaN
if (hx >= 0x400C62D9) {
// NaN
if (hx > 0x7FFF0000) {
return x;
}
if (x > o_threshold) {
// overflow if x != inf
if (!math.isInf(x)) {
math.raiseOverflow();
}
return math.inf(f128);
}
if (x < s_threshold) {
// underflow if x != -inf
// math.doNotOptimizeAway(@as(f32, -0x1.0p-149 / x));
if (!math.isInf(x)) {
math.raiseUnderflow();
}
if (x < u_threshold) {
return 0;
}
}
}
const fn_: f64 = (@floatCast(f64, x) * inv_L + 0x1.8p52) - 0x1.8p52;
const n: i32 = @floatToInt(i32, fn_);
const n2: u32 = @bitCast(u32, n) % INTERVALS;
const k: i32 = n >> LOG2_INTERVALS;
const r1: f128 = x - fn_ * L1;
const r2: f64 = fn_ * -L2;
const r: f128 = r1 + r2;
const dr: f64 = @floatCast(f64, r);
// zig fmt: off
const q: f128 = r2 + r * r * (A2 + r * (A3 + r * (A4 + r * (A5 + r * (A6 +
dr * (A7 + dr * (A8 + dr * (A9 + dr * A10))))))));
// zig fmt: on
var t: f128 = exp_128_table[n2].lo + exp_128_table[n2].hi;
const hi: f128 = exp_128_table[n2].hi;
const lo: f128 = exp_128_table[n2].lo + t * (q + r1);
t = hi + lo;
if (k == 0) {
return t;
} else {
return math.scalbn(t, k);
}
}
test "math.exp" {
try expect(exp(@as(f32, 0.0)) == exp32(0.0));
try expect(exp(@as(f64, 0.0)) == exp64(0.0));
try expect(exp(@as(f128, 0.0)) == exp128(0.0));
}
test "math.exp32" {
const epsilon = 0.000001;
try expect(exp32(0.0) == 1.0);
try expect(math.approxEqAbs(f32, exp32(0.0), 1.0, epsilon));
try expect(math.approxEqAbs(f32, exp32(0.2), 1.221403, epsilon));
try expect(math.approxEqAbs(f32, exp32(0.8923), 2.440737, epsilon));
try expect(math.approxEqAbs(f32, exp32(1.5), 4.481689, epsilon));
}
test "math.exp64" {
const epsilon = 0.000001;
try expect(exp64(0.0) == 1.0);
try expect(math.approxEqAbs(f64, exp64(0.0), 1.0, epsilon));
try expect(math.approxEqAbs(f64, exp64(0.2), 1.221403, epsilon));
try expect(math.approxEqAbs(f64, exp64(0.8923), 2.440737, epsilon));
try expect(math.approxEqAbs(f64, exp64(1.5), 4.481689, epsilon));
}
test "math.exp128" {
const epsilon = 0.000001;
try expect(exp128(0.0) == 1.0);
try expect(math.approxEqAbs(f128, exp128(0.0), 1.0, epsilon));
try expect(math.approxEqAbs(f128, exp128(0.2), 1.221403, epsilon));
try expect(math.approxEqAbs(f128, exp128(0.8923), 2.440737, epsilon));
try expect(math.approxEqAbs(f128, exp128(1.5), 4.481689, epsilon));
}
test "math.exp32.special" {
try expect(math.isPositiveInf(exp32(math.inf(f32))));
try expect(math.isNan(exp32(math.nan(f32))));
}
test "math.exp64.special" {
try expect(math.isPositiveInf(exp64(math.inf(f64))));
try expect(math.isNan(exp64(math.nan(f64))));
}
test "math.exp128.special" {
try expect(math.isPositiveInf(exp128(math.inf(f128))));
try expect(math.isNan(exp128(math.nan(f128))));
}
pub fn main() !void {
try @import("util.zig").singleInputFuncMain(exp);
} | src/exp.zig |
const std = @import("std");
const meta = std.meta;
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
pub const ColorRGB = struct {
r: u8,
g: u8,
b: u8,
const Self = @This();
pub fn eql(self: Self, other: Self) bool {
return meta.eql(self, other);
}
};
pub const Color = union(enum) {
Default,
Black,
Red,
Green,
Yellow,
Blue,
Magenta,
Cyan,
White,
Fixed: u8,
Grey: u8,
RGB: ColorRGB,
const Self = @This();
pub fn eql(self: Self, other: Self) bool {
return meta.eql(self, other);
}
};
pub const FontStyle = packed struct {
bold: bool = false,
dim: bool = false,
italic: bool = false,
underline: bool = false,
slowblink: bool = false,
rapidblink: bool = false,
reverse: bool = false,
hidden: bool = false,
crossedout: bool = false,
fraktur: bool = false,
overline: bool = false,
const Self = @This();
pub const bold = Self{
.bold = true,
};
pub const dim = Self{
.dim = true,
};
pub const italic = Self{
.italic = true,
};
pub const underline = Self{
.underline = true,
};
pub const slowblink = Self{
.slowblink = true,
};
pub const rapidblink = Self{
.rapidblink = true,
};
pub const reverse = Self{
.reverse = true,
};
pub const hidden = Self{
.hidden = true,
};
pub const crossedout = Self{
.crossedout = true,
};
pub const fraktur = Self{
.fraktur = true,
};
pub const overline = Self{
.overline = true,
};
pub fn toU11(self: Self) u11 {
return @bitCast(u11, self);
}
pub fn fromU11(bits: u11) Self {
return @bitCast(Self, bits);
}
/// Returns true iff this font style contains no attributes
pub fn isDefault(self: Self) bool {
return self.toU11() == 0;
}
/// Returns true iff these font styles contain exactly the same
/// attributes
pub fn eql(self: Self, other: Self) bool {
return self.toU11() == other.toU11();
}
/// Returns true iff self is a subset of the attributes of
/// other, i.e. all attributes of self are at least present in
/// other as well
pub fn subsetOf(self: Self, other: Self) bool {
return self.toU11() & other.toU11() == self.toU11();
}
/// Returns this font style with all attributes removed that are
/// contained in other
pub fn without(self: Self, other: Self) Self {
return fromU11(self.toU11() & ~other.toU11());
}
};
test "FontStyle bits" {
expectEqual(@as(u11, 0), (FontStyle{}).toU11());
expectEqual(@as(u11, 1), (FontStyle.bold).toU11());
expectEqual(@as(u11, 1 << 2), (FontStyle.italic).toU11());
expectEqual(@as(u11, 1 << 2) | 1, (FontStyle{ .bold = true, .italic = true }).toU11());
expectEqual(FontStyle{}, FontStyle.fromU11((FontStyle{}).toU11()));
expectEqual(FontStyle.bold, FontStyle.fromU11((FontStyle.bold).toU11()));
}
test "FontStyle subsetOf" {
const default = FontStyle{};
const bold = FontStyle.bold;
const italic = FontStyle.italic;
const bold_and_italic = FontStyle{ .bold = true, .italic = true };
expect(default.subsetOf(default));
expect(default.subsetOf(bold));
expect(bold.subsetOf(bold));
expect(!bold.subsetOf(default));
expect(!bold.subsetOf(italic));
expect(default.subsetOf(bold_and_italic));
expect(bold.subsetOf(bold_and_italic));
expect(italic.subsetOf(bold_and_italic));
expect(bold_and_italic.subsetOf(bold_and_italic));
expect(!bold_and_italic.subsetOf(bold));
expect(!bold_and_italic.subsetOf(italic));
expect(!bold_and_italic.subsetOf(default));
}
test "FontStyle without" {
const default = FontStyle{};
const bold = FontStyle.bold;
const italic = FontStyle.italic;
const bold_and_italic = FontStyle{ .bold = true, .italic = true };
expectEqual(default, default.without(default));
expectEqual(bold, bold.without(default));
expectEqual(default, bold.without(bold));
expectEqual(bold, bold.without(italic));
expectEqual(bold, bold_and_italic.without(italic));
expectEqual(italic, bold_and_italic.without(bold));
expectEqual(default, bold_and_italic.without(bold_and_italic));
}
pub const Style = struct {
foreground: Color = .Default,
background: Color = .Default,
font_style: FontStyle = FontStyle{},
const Self = @This();
/// Returns true iff this style equals the other style in
/// foreground color, background color and font style
pub fn eql(self: Self, other: Self) bool {
if (!self.font_style.eql(other.font_style))
return false;
if (!meta.eql(self.foreground, other.foreground))
return false;
return meta.eql(self.background, other.background);
}
/// Returns true iff this style equals the default set of styles
pub fn isDefault(self: Self) bool {
return eql(self, Self{});
}
};
test "style equality" {
const a = Style{};
const b = Style{
.font_style = FontStyle.bold,
};
const c = Style{
.foreground = Color.Red,
};
expect(a.isDefault());
expect(a.eql(a));
expect(b.eql(b));
expect(c.eql(c));
expect(!a.eql(b));
expect(!b.eql(a));
expect(!a.eql(c));
} | src/style.zig |
const std = @import("std");
const android = @import("build_android.zig");
pub fn build(b: *std.build.Builder) void {
const target = b.standardTargetOptions(.{});
const mode = b.standardReleaseOptions();
// DESKTOP STEPS
{
// BUILD DESKTOP
const exe = b.addExecutable("main", "src/main.zig");
exe.setTarget(target);
exe.setBuildMode(mode);
exe.linkLibC();
exe.addIncludeDir("third-party/SDL2/include");
exe.addLibPath("third-party/SDL2/VisualC/x64/Release");
exe.linkSystemLibrary("SDL2");
b.installBinFile("third-party/SDL2/VisualC/x64/Release/SDL2.dll", "SDL2.dll");
exe.install();
// RUN DESKTOP
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);
// DIRTY BUILD SDL FOR DESKTOP (WINDOWS)
const sdl_desktop = b.addSystemCommand(&[_][]const u8{
"msbuild",
"third-party/SDL2/VisualC/SDL.sln",
"-t:Build",
"-p:Configuration=Release",
"-p:Platform=x64",
});
const build_sdl_desktop_step = b.step("sdl-desktop", "Build SDL for desktop using msbuild on path");
build_sdl_desktop_step.dependOn(&sdl_desktop.step);
}
// ANDROID STEPS
{
const android_env = getAndroidEnvFromEnvVars(b);
// BUILD SDL FOR ANDROID
const sdl_android = android.buildSdlForAndroidStep(b, &android_env);
const build_sdl_android = b.step("sdl-android", "Build SDL for android using the Android SDK");
build_sdl_android.dependOn(sdl_android);
// BUILD ANDROID
const libs = buildAndroidMainLibraries(b, &android_env, mode);
const build_libs = b.step("android", "Build the main android library");
for (libs.items) |lib| {
build_libs.dependOn(&lib.step.step);
}
// BUILD APK
const apk = android.buildApkStep(b, &android_env, libs.items);
const build_apk = b.step("apk", "Build the android apk (debug)");
build_apk.dependOn(apk);
// INSTALL AND RUN APK
const run = android.installAndRunApkStep(b, &android_env, "com.gamemaker.game", "MainActivity");
const run_cmd = b.step("run-apk", "Install and run the previously built android apk");
run_cmd.dependOn(run);
// OPEN ANDROID LOG
const open_log = android.openAndroidLog(b, &android_env);
const open_log_cmd = b.step("android-log", "Open the android device log filtered to our application");
open_log_cmd.dependOn(open_log);
}
}
fn getEnvVar(b: *std.build.Builder, name: []const u8) []u8 {
return std.process.getEnvVarOwned(b.allocator, name) catch std.debug.panic("env var '{s}' not set", .{name});
}
fn getAndroidEnvFromEnvVars(b: *std.build.Builder) android.AndroidEnv {
// this example gets the needed paths from environment variables
// however it's really up to you from where to get them
// even hardcoding is fair game
return android.AndroidEnv{
.jdk_path = getEnvVar(b, "JDK_PATH"),
.sdk_path = getEnvVar(b, "ANDROID_SDK_PATH"),
.platform_number = getEnvVar(b, "ANDROID_PLATFORM_NUMBER"),
.build_tools_path = getEnvVar(b, "ANDROID_BUILD_TOOLS_PATH"),
.ndk_path = getEnvVar(b, "ANDROID_NDK_PATH"),
};
}
pub fn buildAndroidMainLibraries(
builder: *std.build.Builder,
android_env: *const android.AndroidEnv,
mode: std.builtin.Mode,
) std.ArrayList(android.AndroidMainLib) {
// steps to generate a libmain.so for all supported android platforms
android.assertZigLibcConfigsDirExist(builder, android_env);
comptime var all_targets: [@typeInfo(android.AndroidTarget).Enum.fields.len]android.AndroidTarget = undefined;
inline for (@typeInfo(android.AndroidTarget).Enum.fields) |field, i| {
all_targets[i] = @intToEnum(android.AndroidTarget, field.value);
}
var libs = std.ArrayList(android.AndroidMainLib).initCapacity(builder.allocator, 4) catch unreachable;
for (all_targets) |target| {
switch (target) {
// compiling android apps to arm not supported right now. see: https://github.com/ziglang/zig/issues/8885
.arm => continue,
// compiling android apps to x86 not supported right now. see https://github.com/ziglang/zig/issues/7935
.x86 => continue,
else => {},
}
const step = buildAndroidMainLibrary(builder, android_env, mode, target);
libs.append(.{
.target = target,
.step = step,
}) catch unreachable;
}
return libs;
}
pub fn buildAndroidMainLibrary(
builder: *std.build.Builder,
android_env: *const android.AndroidEnv,
mode: std.builtin.Mode,
target: android.AndroidTarget,
) *std.build.LibExeObjStep {
// steps to generate a libmain.so for a specific android platform
const lib = builder.addSharedLibrary("main", "src/android_main.zig", .unversioned);
lib.force_pic = true;
lib.link_function_sections = true;
lib.bundle_compiler_rt = true;
lib.strip = (mode == .ReleaseSmall);
lib.setBuildMode(mode);
lib.defineCMacro("ANDROID");
lib.linkLibC();
const app_libs = [_][]const u8{
"GLESv2", "EGL", "android", "log",
};
for (app_libs) |l| {
lib.linkSystemLibraryName(l);
}
const config = target.config();
lib.setTarget(config.target);
const include_dir = std.fs.path.resolve(
builder.allocator,
&[_][]const u8{ android_env.ndk_path, "sysroot/usr/include" },
) catch unreachable;
const lib_dir = std.fs.path.resolve(
builder.allocator,
&[_][]const u8{ android_env.ndk_path, builder.fmt("platforms/android-{s}", .{android_env.platform_number}) },
) catch unreachable;
lib.addIncludeDir(include_dir);
lib.addLibPath(std.fs.path.resolve(builder.allocator, &[_][]const u8{ lib_dir, config.lib_dir }) catch unreachable);
lib.addIncludeDir(std.fs.path.resolve(builder.allocator, &[_][]const u8{ include_dir, config.include_dir }) catch unreachable);
lib.addIncludeDir("third-party/SDL2/include");
const android_lib_path = builder.pathFromRoot(
builder.fmt(android.ANDROID_PROJECT_PATH ++ "/ndk-out/lib/{s}", .{config.out_dir}),
);
lib.addLibPath(android_lib_path);
lib.linkSystemLibrary("SDL2");
lib.setLibCFile(config.libc_file);
return lib;
} | build.zig |
const std = @import("std");
const zt = @import("zt");
const sling = @import("../sling.zig");
const ig = @import("imgui");
const selector = @import("fileSelector.zig");
var demoOpen: bool = false;
var saveShortcut: bool = false;
var loadShortcut: bool = false;
var saveAsShortcut: bool = false;
pub fn update() void {
// Shortcut items
saveAsShortcut = false;
saveShortcut = false;
loadShortcut = false;
var before = sling.input.config.imguiBlocksInput;
sling.input.config.imguiBlocksInput = false;
if (sling.input.Key.lCtrl.down() or sling.input.Key.rCtrl.down()) {
if (sling.input.Key.lShift.down() or sling.input.Key.rShift.down()) {
if (sling.input.Key.s.pressed()) {
saveAsShortcut = true;
}
} else {
if (sling.input.Key.s.pressed()) {
saveShortcut = true;
}
}
if (sling.input.Key.o.pressed()) {
loadShortcut = true;
}
}
sling.input.config.imguiBlocksInput = before;
// Main menu
if (ig.igBeginMainMenuBar()) {
if (sling.room) |_| {
if (ig.igBeginMenu(sling.dictionary.exitRoom.ptr, true)) {
sling.leaveRoom();
ig.igEndMenu();
}
}
// Creation tab
if (ig.igBeginMenu(sling.dictionary.fileMenuTag.ptr, sling.room == null)) {
fileMenu();
ig.igEndMenu();
}
if (ig.igBeginMenu(sling.dictionary.roomMenuTag.ptr, sling.room == null)) {
for (sling.register.RegisteredRooms.items) |room, i| {
if (ig.igMenuItem_Bool(room.name.ptr, null, false, true)) {
sling.enterRoom(i);
}
}
ig.igEndMenu();
}
if (ig.igBeginMenu(sling.dictionary.miscMenuTag.ptr, true)) {
if (ig.igMenuItem_Bool(sling.dictionary.miscMenuImGui.ptr, null, demoOpen, true)) {
demoOpen = !demoOpen;
}
ig.igEndMenu();
}
ig.igEndMainMenuBar();
}
if (demoOpen) {
ig.igShowDemoWindow(&demoOpen);
}
selector.update();
}
fn fileMenu() void {
// New menu dropdown
if (ig.igBeginMenu(sling.dictionary.fileMenuNew.ptr, true)) {
var registers = sling.register.RegisteredScenes.valueIterator();
while (registers.next()) |sceneRegister| {
var cast: *sling.register.SceneRegister = sceneRegister;
var baseInfo = sling.Object.Information.get(cast.base);
if (ig.igMenuItem_Bool(baseInfo.name.ptr, null, false, true)) {
sling.scene = sling.Scene.initFromInfo(cast.*);
}
}
ig.igEndMenu();
}
ig.igSeparator();
// Current scene items
var enabled = sling.scene != null and sling.scene.?.editorData.filePath != null;
if (ig.igMenuItem_Bool(sling.dictionary.fileMenuSave.ptr, "CTRL+S", false, enabled) or saveShortcut) {
var path = sling.scene.?.editorData.filePath.?;
var data = sling.scene.?.toBytes(sling.alloc);
defer sling.alloc.free(data);
std.fs.cwd().writeFile(path, data) catch {
std.debug.print("Failed to write scene data to disk.\n", .{});
};
sling.logFmt("Quick saving to {s} successful!", .{sling.scene.?.editorData.filePath.?});
}
if (ig.igMenuItem_Bool(sling.dictionary.fileMenuSaveAs.ptr, "CTRL+SHIFT+S", false, true) or saveAsShortcut) {
selector.beginSaving(sling.scene.?.editorData.filePath);
}
if (ig.igMenuItem_Bool(sling.dictionary.fileMenuLoad.ptr, "CTRL+O", false, true) or loadShortcut) {
selector.beginLoading();
}
ig.igSeparator();
if (ig.igMenuItem_Bool(sling.dictionary.fileMenuLeave.ptr, null, false, sling.scene != null and sling.inEditor)) {
if (sling.scene) |scn| {
scn.deinit();
sling.scene = null;
}
}
} | src/editor/menu.zig |
const std = @import("std");
const io = std.io;
pub const allocator = std.testing.allocator;
pub const expect = std.testing.expect;
pub const expectError = std.testing.expectError;
pub const expectEqual = std.testing.expectEqual;
pub const expectEqualSlices = std.testing.expectEqualSlices;
pub const expectEqualStrings = std.testing.expectEqualStrings;
const PrimitiveWriter = @import("primitive/writer.zig").PrimitiveWriter;
const FrameHeader = @import("frame.zig").FrameHeader;
const RawFrame = @import("frame.zig").RawFrame;
const RawFrameReader = @import("frame.zig").RawFrameReader;
const RawFrameWriter = @import("frame.zig").RawFrameWriter;
pub fn expectInDelta(a: anytype, b: anytype, delta: @TypeOf(a)) void {
const dt = a - b;
if (dt < -delta or dt > delta) {
std.debug.panic("expected a {e} to be within {e} of b {}, but got {e}", .{ a, delta, b, dt });
}
}
pub fn printHRBytes(comptime fmt: []const u8, exp: []const u8, args: anytype) void {
const hextable = "0123456789abcdef";
var buffer = std.ArrayList(u8).init(std.testing.allocator);
defer buffer.deinit();
var column: usize = 0;
for (exp) |c| {
if (column % 80 == 0) {
buffer.append('\n') catch unreachable;
column = 0;
}
if (std.ascii.isAlNum(c) or c == '_') {
buffer.append(c) catch unreachable;
} else {
buffer.appendSlice("\\x") catch unreachable;
buffer.append(hextable[(c & 0xF0) >> 4]) catch unreachable;
buffer.append(hextable[(c & 0x0F)]) catch unreachable;
}
column += 1;
}
std.debug.print(fmt, .{buffer.items} ++ args);
}
/// Creates an arena allocator backed by the testing allocator.
/// Only intended to be used for tests.
pub fn arenaAllocator() std.heap.ArenaAllocator {
return std.heap.ArenaAllocator.init(std.testing.allocator);
}
/// Reads a raw frame from the provided buffer.
/// Only intended to be used for tests.
pub fn readRawFrame(_allocator: *std.mem.Allocator, data: []const u8) !RawFrame {
var source = io.StreamSource{ .const_buffer = io.fixedBufferStream(data) };
var reader = source.reader();
var fr = RawFrameReader(@TypeOf(reader)).init(reader);
return fr.read(_allocator);
}
pub fn expectSameRawFrame(frame: anytype, header: FrameHeader, exp: []const u8) void {
var arena = arenaAllocator();
defer arena.deinit();
// Write frame body
var pw: PrimitiveWriter = undefined;
pw.reset(&arena.allocator) catch |err| {
std.debug.panic("unable to initialize writer. err: {}\n", .{err});
};
const function = @typeInfo(@TypeOf(frame.write)).BoundFn;
if (function.args.len == 2) {
frame.write(&pw) catch |err| {
std.debug.panic("unable to write frame. err: {}\n", .{err});
};
} else if (function.args.len == 3) {
frame.write(header.version, &pw) catch |err| {
std.debug.panic("unable to write frame. err: {}\n", .{err});
};
}
// Write raw frame
const raw_frame = RawFrame{
.header = header,
.body = pw.getWritten(),
};
var buf2: [1024]u8 = undefined;
var source = io.StreamSource{ .buffer = io.fixedBufferStream(&buf2) };
var writer = source.writer();
var fw = RawFrameWriter(@TypeOf(writer)).init(writer);
fw.write(raw_frame) catch |err| {
std.debug.panic("unable to write raw frame. err: {}\n", .{err});
};
if (!std.mem.eql(u8, exp, source.buffer.getWritten())) {
printHRBytes("\n==> exp : {s}\n", exp, .{});
printHRBytes("==> source: {s}\n", source.buffer.getWritten(), .{});
std.debug.panic("frames are different\n", .{});
}
} | src/testing.zig |
const std = @import("std");
const coder = @import("coder.zig");
const testing = std.testing;
const ParseError = coder.ParseError;
const WireType = enum(u3) {
Varint = 0,
_64bit = 1,
LengthDelimited = 2,
StartGroup = 3,
EndGroup = 4,
_32bit = 5,
};
pub const FieldMeta = struct {
wire_type: WireType,
number: u61,
pub fn init(value: u64) FieldMeta {
return FieldMeta{
.wire_type = @intToEnum(WireType, @truncate(u3, value)),
.number = @intCast(u61, value >> 3),
};
}
pub fn encodeInto(self: FieldMeta, buffer: []u8) []u8 {
const uint = (@intCast(u64, self.number) << 3) + @enumToInt(self.wire_type);
return coder.Uint64Coder.encode(buffer, uint);
}
pub fn decode(buffer: []const u8, len: *usize) ParseError!FieldMeta {
const raw = try coder.Uint64Coder.decode(buffer, len);
return init(raw);
}
};
test "FieldMeta" {
const field = FieldMeta.init(8);
testing.expectEqual(WireType.Varint, field.wire_type);
testing.expectEqual(u61(1), field.number);
}
pub fn Uint64(comptime number: u63) type {
return FromVarintCast(u64, coder.Uint64Coder, FieldMeta{
.wire_type = .Varint,
.number = number,
});
}
pub fn Uint32(comptime number: u63) type {
return FromVarintCast(u32, coder.Uint64Coder, FieldMeta{
.wire_type = .Varint,
.number = number,
});
}
pub fn Int64(comptime number: u63) type {
return FromVarintCast(i64, coder.Int64Coder, FieldMeta{
.wire_type = .Varint,
.number = number,
});
}
pub fn Int32(comptime number: u63) type {
return FromVarintCast(i32, coder.Int64Coder, FieldMeta{
.wire_type = .Varint,
.number = number,
});
}
pub fn Sint64(comptime number: u63) type {
return FromVarintCast(i64, coder.Sint64Coder, FieldMeta{
.wire_type = .Varint,
.number = number,
});
}
pub fn Sint32(comptime number: u63) type {
return FromVarintCast(i32, coder.Sint64Coder, FieldMeta{
.wire_type = .Varint,
.number = number,
});
}
fn FromBitCast(comptime TargetPrimitive: type, comptime Coder: type, comptime info: FieldMeta) type {
return struct {
const Self = @This();
data: TargetPrimitive = 0,
pub const field_meta = info;
pub fn encodeSize(self: Self) usize {
return Coder.encodeSize(@bitCast(Coder.primitive, self.data));
}
pub fn encodeInto(self: Self, buffer: []u8) []u8 {
return Coder.encode(buffer, @bitCast(Coder.primitive, self.data));
}
pub fn decodeFrom(self: *Self, buffer: []const u8) ParseError!usize {
var len: usize = undefined;
const raw = try Coder.decode(buffer, &len);
self.data = @bitCast(TargetPrimitive, raw);
return len;
}
};
}
fn FromVarintCast(comptime TargetPrimitive: type, comptime Coder: type, comptime info: FieldMeta) type {
return struct {
const Self = @This();
data: TargetPrimitive = 0,
pub const field_meta = info;
pub fn encodeSize(self: Self) usize {
return Coder.encodeSize(self.data);
}
pub fn encodeInto(self: Self, buffer: []u8) []u8 {
return Coder.encode(buffer, self.data);
}
pub fn decodeFrom(self: *Self, buffer: []const u8) ParseError!usize {
var len: usize = undefined;
const raw = try Coder.decode(buffer, &len);
self.data = @intCast(TargetPrimitive, raw);
return len;
}
};
}
var rng = std.rand.DefaultPrng.init(0);
fn testEncodeDecode(comptime T: type, base: T) !void {
var buf: [1000]u8 = undefined;
const encoded_slice = base.encodeInto(buf[0..]);
testing.expectEqual(base.encodeSize(), encoded_slice.len);
var decoded: T = undefined;
const decoded_len = try decoded.decodeFrom(encoded_slice);
testing.expectEqual(base.data, decoded.data);
testing.expectEqual(base.encodeSize(), decoded_len);
}
fn testEncodeDecodeSlices(comptime T: type, base: T) !void {
var buf: [1000]u8 = undefined;
const encoded_slice = base.encodeInto(buf[0..]);
testing.expectEqual(base.encodeSize(), encoded_slice.len);
var decoded: T = undefined;
const decoded_len = try decoded.decodeFromAlloc(encoded_slice, std.heap.direct_allocator);
testing.expectEqualSlices(u8, base.data, decoded.data);
testing.expectEqual(base.encodeSize(), decoded_len);
}
test "Var int" {
inline for ([_]type{ Uint64(1), Int64(1), Sint64(1), Uint32(1), Int32(1), Sint32(1) }) |T| {
const data_field = std.meta.fieldInfo(T, "data");
var i = usize(0);
while (i < 100) : (i += 1) {
const base = T{ .data = rng.random.int(data_field.field_type) };
try testEncodeDecode(T, base);
}
}
}
pub fn Fixed64(comptime number: u63) type {
return FromBitCast(u64, coder.Fixed64Coder, FieldMeta{
.wire_type = ._64bit,
.number = number,
});
}
pub fn Sfixed64(comptime number: u63) type {
return FromBitCast(i64, coder.Fixed64Coder, FieldMeta{
.wire_type = ._64bit,
.number = number,
});
}
pub fn Fixed32(comptime number: u63) type {
return FromBitCast(u32, coder.Fixed32Coder, FieldMeta{
.wire_type = ._32bit,
.number = number,
});
}
pub fn Sfixed32(comptime number: u63) type {
return FromBitCast(i32, coder.Fixed32Coder, FieldMeta{
.wire_type = ._32bit,
.number = number,
});
}
pub fn Double(comptime number: u63) type {
return FromBitCast(f64, coder.Fixed64Coder, FieldMeta{
.wire_type = ._64bit,
.number = number,
});
}
pub fn Float(comptime number: u63) type {
return FromBitCast(f32, coder.Fixed32Coder, FieldMeta{
.wire_type = ._32bit,
.number = number,
});
}
test "Fixed numbers" {
inline for ([_]type{ Fixed64(1), Fixed32(1), Sfixed64(1), Sfixed32(1) }) |T| {
const data_field = std.meta.fieldInfo(T, "data");
var i = usize(0);
while (i < 100) : (i += 1) {
const base = T{ .data = rng.random.int(data_field.field_type) };
try testEncodeDecode(T, base);
}
}
inline for ([_]type{ Double(1), Float(1) }) |T| {
const data_field = std.meta.fieldInfo(T, "data");
var i = usize(0);
while (i < 100) : (i += 1) {
const base = T{ .data = rng.random.float(data_field.field_type) };
try testEncodeDecode(T, base);
}
}
}
pub fn Bytes(comptime number: u63) type {
return struct {
const Self = @This();
data: []u8 = [_]u8{},
allocator: ?*std.mem.Allocator = null,
pub const field_meta = FieldMeta{
.wire_type = .LengthDelimited,
.number = number,
};
pub fn deinit(self: *Self) void {
if (self.allocator) |alloc| {
alloc.free(self.data);
self.* = Self{};
}
}
pub fn encodeSize(self: Self) usize {
return coder.BytesCoder.encodeSize(self.data);
}
pub fn encodeInto(self: Self, buffer: []u8) []u8 {
return coder.BytesCoder.encode(buffer, self.data);
}
pub fn decodeFromAlloc(self: *Self, buffer: []const u8, allocator: *std.mem.Allocator) ParseError!usize {
var len: usize = undefined;
self.data = try coder.BytesCoder.decode(buffer, &len, allocator);
self.allocator = allocator;
return len;
}
};
}
pub fn String(comptime number: u63) type {
return struct {
const Self = @This();
data: []const u8 = "",
allocator: ?*std.mem.Allocator = null,
pub const field_meta = FieldMeta{
.wire_type = .LengthDelimited,
.number = number,
};
pub fn deinit(self: *Self) void {
if (self.allocator) |alloc| {
alloc.free(self.data);
self.* = Self{};
}
}
pub fn encodeSize(self: Self) usize {
return coder.BytesCoder.encodeSize(self.data);
}
pub fn encodeInto(self: Self, buffer: []u8) []u8 {
return coder.BytesCoder.encode(buffer, self.data);
}
pub fn decodeFromAlloc(self: *Self, buffer: []const u8, allocator: *std.mem.Allocator) ParseError!usize {
// TODO: validate unicode
var len: usize = undefined;
self.data = try coder.BytesCoder.decode(buffer, &len, allocator);
self.allocator = allocator;
return len;
}
};
}
test "Bytes/String" {
inline for ([_]type{ Bytes(1), String(1) }) |T| {
var i = usize(0);
while (i < 100) : (i += 1) {
var base_buf: [500]u8 = undefined;
rng.random.bytes(base_buf[0..]);
const base = T{ .data = base_buf[0..] };
try testEncodeDecodeSlices(T, base);
}
}
}
pub fn Bool(comptime number: u63) type {
return struct {
const Self = @This();
data: bool = false,
pub const field_meta = FieldMeta{
.wire_type = .Varint,
.number = number,
};
pub fn encodeSize(self: Self) usize {
return 1;
}
pub fn encodeInto(self: Self, buffer: []u8) []u8 {
buffer[0] = if (self.data) u8(1) else 0;
return buffer[0..1];
}
pub fn decodeFrom(self: *Self, bytes: []const u8) ParseError!usize {
var len: usize = undefined;
const raw = try coder.Uint64Coder.decode(bytes, &len);
// TODO: verify that bools *must* be 0 or 1
if (raw > 1) {
return error.Overflow;
}
self.data = raw != 0;
return len;
}
};
}
test "Bool" {
@"fuzz": {
inline for ([_]bool{ false, true }) |b| {
const base = Bool(1){ .data = b };
try testEncodeDecode(Bool(1), base);
}
}
}
pub fn Repeated(comptime number: u63, comptime Tfn: var) type {
const T = Tfn(number);
std.debug.assert(@hasField(T, "data"));
std.debug.assert(@hasDecl(T, "encodeSize"));
std.debug.assert(@hasDecl(T, "encodeInto"));
std.debug.assert(@hasDecl(T, "decodeFrom"));
const DataType = std.meta.fieldInfo(T, "data").field_type;
return struct {
const Self = @This();
const List = std.ArrayList(DataType);
data: []DataType = [_]DataType{},
allocator: ?*std.mem.Allocator = null,
_decode_builder: ?List = null,
pub fn deinit(self: *Self) void {
if (self._decode_builder) |*decode_builder| {
std.debug.assert(self.data.len == 0);
decode_builder.deinit();
self.* = Self{};
} else if (self.allocator) |alloc| {
alloc.free(self.data);
self.* = Self{};
}
}
pub fn encodeSize(self: Self) usize {
var sum = usize(0);
for (self.data) |item| {
const wrapper = DataType{ .data = item };
sum += wrapper.encodeSize();
}
return sum;
}
pub fn encodeInto(self: Self, buffer: []u8) []u8 {
var cursor = usize(0);
for (self.data) |item| {
const wrapper = DataType{ .data = item };
const result = wrapper.encodeInto(buffer[cursor..]);
cursor += result.len;
}
return buffer[0..cursor];
}
pub fn decodeFromAlloc(self: *Self, raw: []const u8, allocator: *std.mem.Allocator) ParseError!usize {
if (self._decode_builder == null) {
self.deinit();
self._decode_builder = List.init(allocator);
}
var base: T = undefined;
const len = try base.decodeFrom(raw);
try self._decode_builder.?.append(base.data);
return len;
}
pub fn decodePacked(self: *Self, raw: []const u8, allocator: *std.mem.Allocator) ParseError!usize {
var header_len: usize = undefined;
const header = try Uint64.decode(raw, &header_len);
var items_len = usize(0);
while (items_len < header.data) {
items_len += try self.decodeFromAlloc(raw[header_len + items_len ..], &len, allocator);
}
if (items_len > header.data) {
// Header listed length != items actual length
return error.Overflow;
}
len.* = header_len + items_len;
}
pub fn decodeComplete(self: *Self) void {
if (self._decode_builder) |*decode_builder| {
std.debug.assert(self.data.len == 0);
self.allocator = decode_builder.allocator;
self.data = decode_builder.toOwnedSlice();
self._decode_builder = null;
}
}
};
}
test "Repeated" {
const twelve = [_]u8{ 12, 0, 0, 0 };
const hundred = [_]u8{ 100, 0, 0, 0 };
var repeated_field = Repeated(1, Fixed32){};
_ = try repeated_field.decodeFromAlloc(twelve[0..], std.heap.direct_allocator);
_ = try repeated_field.decodeFromAlloc(hundred[0..], std.heap.direct_allocator);
repeated_field.decodeComplete();
testing.expectEqualSlices(u32, [_]u32{ 12, 100 }, repeated_field.data);
} | src/types.zig |
const builtin = @import("builtin");
const std = @import("std");
const c = @import("c.zig");
const debug = std.debug;
const math = std.math;
const mem = std.mem;
// Custom functions provided to nuklear
export fn zig_assert(ok: c_int) void {
debug.assert(ok != 0);
}
export fn zig_memset(ptr: [*]u8, c0: u8, len: usize) void {
mem.set(u8, ptr[0..len], c0);
}
export fn zig_memcopy(dst: [*]u8, src: [*]const u8, len: usize) [*]u8 {
mem.copy(u8, dst[0..len], src[0..len]);
return dst;
}
export fn zig_sqrt(value: f32) f32 {
return math.sqrt(value);
}
export fn zig_sin(value: f32) f32 {
return math.sin(value);
}
export fn zig_cos(value: f32) f32 {
return math.cos(value);
}
// Custom
pub fn buttonInactive(ctx: *Context, text: []const u8) void {
const old_button_style = ctx.style.button;
ctx.style.button.normal = ctx.style.button.active;
ctx.style.button.hover = ctx.style.button.active;
ctx.style.button.active = ctx.style.button.active;
ctx.style.button.text_background = ctx.style.button.text_active;
ctx.style.button.text_normal = ctx.style.button.text_active;
ctx.style.button.text_hover = ctx.style.button.text_active;
ctx.style.button.text_active = ctx.style.button.text_active;
_ = button(ctx, text);
ctx.style.button = old_button_style;
}
pub fn buttonActivatable(ctx: *Context, text: []const u8, active: bool) bool {
if (active) {
return button(ctx, text);
} else {
buttonInactive(ctx, text);
return false;
}
}
pub fn nonPaddedGroupBegin(ctx: *Context, title: [*]const u8, flags: c.nk_flags) bool {
const old = ctx.style.window;
ctx.style.window.group_padding = vec2(0, 0);
const is_showing = c.nk_group_begin(ctx, title, flags) != 0;
ctx.style.window = old;
return is_showing;
}
pub fn nonPaddedGroupEnd(ctx: *Context) void {
const old = ctx.style.window;
ctx.style.window.group_padding = vec2(0, 0);
c.nk_group_end(ctx);
ctx.style.window = old;
}
pub fn fontWidth(ctx: *Context, text: []const u8) f32 {
const style_font = ctx.style.font;
return style_font.*.width.?(style_font.*.userdata, 0, text.ptr, @intCast(c_int, text.len));
}
pub const Align = enum {
left,
right,
};
pub const no_button_clicked = math.maxInt(usize);
pub const Button = struct {
text: []const u8,
is_active: bool = true,
};
pub fn buttonWidth(ctx: *Context, text: []const u8) f32 {
const style_button = ctx.style.button;
return fontWidth(ctx, text) + style_button.border +
(style_button.padding.x + style_button.rounding) * 2;
}
pub fn buttonsAutoWidth(ctx: *Context, alignment: Align, height: f32, buttons_: []const Button) usize {
var biggest: f32 = 0;
for (buttons_) |but|
biggest = math.max(biggest, buttonWidth(ctx, but.text));
return buttons(ctx, alignment, biggest, height, buttons_);
}
pub fn buttons(ctx: *Context, alignment: Align, width: f32, height: f32, buttons_: []const Button) usize {
c.nk_layout_row_template_begin(ctx, height);
if (alignment == .right)
c.nk_layout_row_template_push_dynamic(ctx);
for (buttons_) |_|
c.nk_layout_row_template_push_static(ctx, width);
if (alignment == .left)
c.nk_layout_row_template_push_dynamic(ctx);
c.nk_layout_row_template_end(ctx);
if (alignment == .right)
c.nk_label(ctx, "", c.NK_TEXT_LEFT);
var res: usize = no_button_clicked;
for (buttons_) |but, i| {
if (buttonActivatable(ctx, but.text, but.is_active))
res = i;
}
if (alignment == .left)
c.nk_label(ctx, "", c.NK_TEXT_LEFT);
return res;
}
pub const Context = c.nk_context;
pub const Rect = c.struct_nk_rect;
pub const Vec2 = c.struct_nk_vec2;
pub const Color = c.nk_color;
pub fn begin(ctx: *c.nk_context, title: [*]const u8, r: Rect, flags: c.nk_flags) bool {
return c.nkBegin(ctx, title, &r, flags) != 0;
}
pub fn button(ctx: *Context, text: []const u8) bool {
return c.nk_button_text(ctx, text.ptr, @intCast(c_int, text.len)) != 0;
}
pub fn rect(x: f32, y: f32, w: f32, h: f32) Rect {
return Rect{ .x = x, .y = y, .w = w, .h = h };
}
pub fn vec2(x: f32, y: f32) Vec2 {
return Vec2{ .x = x, .y = y };
}
pub fn rgba(r: u8, g: u8, b: u8, a: u8) Color {
return Color{ .r = r, .g = g, .b = b, .a = a };
}
pub fn rgb(r: u8, g: u8, b: u8) Color {
return rgba(r, g, b, 255);
} | src/gui/nuklear.zig |
const std = @import("std");
const mem = std.mem;
const Allocator = mem.Allocator;
const tk = @import("./token.zig");
const Token = tk.Token;
const TokenType = tk.TokenType;
pub const SourceLocation = struct {
start: usize,
line: usize,
column: usize,
offset: usize,
};
// TODO: iterate over utf8 grapheme instead of ascii characters
pub const Scanner = struct {
const Self = @This();
source: []const u8,
current: SourceLocation = .{
.start = 0,
.line = 0,
.column = 0,
.offset = 0,
},
pub fn init(source: []const u8) Self {
return Self{
.source = source,
};
}
pub fn getLines(self: *Self, allocator: Allocator, index: usize, n: usize) !std.ArrayList([]const u8) {
var lines = std.ArrayList([]const u8).init(allocator);
var it = std.mem.split(u8, self.source, "\n");
var count: usize = 0;
while (it.next()) |line| : (count += 1) {
if (count >= index and count < index + n) {
try lines.append(line);
}
if (count > index + n) {
break;
}
}
return lines;
}
pub fn scanToken(self: *Self) !Token {
self.skipWhitespaces();
self.current.start = self.current.offset;
if (self.isEOF()) {
return self.makeToken(.Eof, null, null);
}
var char: u8 = self.advance();
return try switch (char) {
'b' => return if (isNumber(self.peek())) self.binary() else self.identifier(),
'a', 'c'...'z', 'A'...'Z' => return self.identifier(),
'0' => {
if (self.match('x')) {
return try self.hexa();
} else if (self.match('b')) {
return try self.binary();
} else {
return try self.number();
}
},
'1'...'9' => return try self.number(),
'[' => return self.makeToken(.LeftBracket, null, null),
']' => return self.makeToken(.RightBracket, null, null),
'(' => return self.makeToken(.LeftParen, null, null),
')' => return self.makeToken(.RightParen, null, null),
'{' => return self.makeToken(.LeftBrace, null, null),
'}' => return self.makeToken(.RightBrace, null, null),
',' => return self.makeToken(.Comma, null, null),
';' => return self.makeToken(.Semicolon, null, null),
'.' => return self.makeToken(.Dot, null, null),
'>' => {
if (self.match('>')) {
return self.makeToken(.ShiftRight, null, null);
} else if (self.match('=')) {
return self.makeToken(.GreaterEqual, null, null);
} else {
return self.makeToken(.Greater, null, null);
}
},
'<' => {
if (self.match('<')) {
return self.makeToken(.ShiftLeft, null, null);
} else if (self.match('=')) {
return self.makeToken(.LessEqual, null, null);
} else {
return self.makeToken(.Less, null, null);
}
},
'+' => {
if (self.match('+')) {
return self.makeToken(.Increment, null, null);
} else if (self.match('=')) {
return self.makeToken(.PlusEqual, null, null);
} else {
return self.makeToken(.Plus, null, null);
}
},
'-' => {
if (self.match('-')) {
return self.makeToken(.Decrement, null, null);
} else if (self.match('=')) {
return self.makeToken(.MinusEqual, null, null);
} else if (self.match('>')) {
return self.makeToken(.Arrow, null, null);
} else {
return self.makeToken(.Minus, null, null);
}
},
'*' => return self.makeToken(if (self.match('=')) .StarEqual else .Star, null, null),
'/' => return self.makeToken(if (self.match('=')) .SlashEqual else .Slash, null, null),
'%' => return self.makeToken(.Percent, null, null),
'?' => return self.makeToken(if (self.match('?')) .QuestionQuestion else .Question, null, null),
'!' => return self.makeToken(if (self.match('=')) .BangEqual else .Bang, null, null),
':' => return self.makeToken(.Colon, null, null),
'=' => return self.makeToken(if (self.match('=')) .EqualEqual else .Equal, null, null),
'\"' => return self.string(),
else => return self.makeToken(.Error, "Unexpected character.", null),
};
}
fn skipWhitespaces(self: *Self) void {
while (true) {
var char: u8 = self.peek();
switch (char) {
' ', '\r', '\t' => _ = self.advance(),
'\n' => {
self.current.line += 1;
self.current.column = 0;
_ = self.advance();
},
'|' => {
while (self.peek() != '\n' and !self.isEOF()) {
_ = self.advance();
}
},
else => return,
}
}
}
fn isNumber(char: u8) bool {
return char >= '0' and char <= '9';
}
fn isLetter(char: u8) bool {
return (char >= 'a' and char <= 'z') or (char >= 'A' and char <= 'Z');
}
fn identifier(self: *Self) !Token {
while (isLetter(self.peek())) {
_ = self.advance();
}
const literal = self.source[self.current.start..self.current.offset];
const keywordOpt = tk.isKeyword(literal);
if (keywordOpt) |keyword| {
return self.makeToken(keyword, literal, null);
} else {
return self.makeToken(.Identifier, literal, null);
}
}
fn number(self: *Self) !Token {
while (isNumber(self.peek())) {
_ = self.advance();
}
if (self.peek() == '.' and isNumber(self.peekNext())) {
_ = self.advance(); // Consume .
while (isNumber(self.peek())) {
_ = self.advance();
}
}
return self.makeToken(.Number, null, try std.fmt.parseFloat(f64, self.source[self.current.start..self.current.offset]));
}
fn binary(self: *Self) !Token {
var peeked: u8 = self.peek();
while (peeked == '0' or peeked == '1') {
_ = self.advance();
peeked = self.peek();
}
if (self.current.offset - self.current.start != 10) {
return self.makeToken(.Error, "Malformed binary number.", null);
}
return self.makeToken(.Number, null, try std.fmt.parseFloat(f64, self.source[self.current.start..self.current.offset]));
}
fn hexa(self: *Self) !Token {
_ = self.advance(); // Consume 'x'
var peeked: u8 = self.peek();
while (isNumber(peeked) or (peeked >= 'A' and peeked <= 'F')) {
_ = self.advance();
peeked = self.peek();
}
return self.makeToken(.Number, null, try std.fmt.parseFloat(f64, self.source[self.current.start..self.current.offset]));
}
fn string(self: *Self) !Token {
var in_interp: bool = false;
var interp_depth: usize = 0;
while ((self.peek() != '"' or in_interp) and !self.isEOF()) {
if (self.peek() == '\n') {
return self.makeToken(.Error, "Unterminated string.", null);
} else if (self.peek() == '{') {
if (!in_interp) {
in_interp = true;
} else {
interp_depth += 1;
}
} else if (self.peek() == '}') {
if (in_interp) {
if (interp_depth > 0) {
interp_depth -= 1;
}
if (interp_depth == 0) {
in_interp = false;
}
}
} else if (self.peek() == '\\' and self.peekNext() == '"') {
// Escaped string delimiter, go past it
_ = self.advance();
} else if (self.peek() == '\\' and self.peekNext() == '{') {
// Escaped interpolation delimiter, go past it
_ = self.advance();
}
_ = self.advance();
}
if (self.isEOF()) {
return self.makeToken(.Error, "Unterminated string.", null);
} else {
_ = self.advance();
}
return self.makeToken(.String, if (self.current.offset - self.current.start > 0)
self.source[(self.current.start + 1)..(self.current.offset - 1)]
else
null, null);
}
fn isEOF(self: *Self) bool {
return self.current.offset >= self.source.len or self.source[self.current.offset] == 0;
}
fn peek(self: *Self) u8 {
if (self.isEOF()) {
return '\x00';
}
return self.source[self.current.offset];
}
fn peekNext(self: *Self) u8 {
if (self.current.offset + 1 >= self.source.len) {
return '\x00';
}
return self.source[self.current.offset + 1];
}
fn advance(self: *Self) u8 {
const char = self.source[self.current.offset];
self.current.offset += 1;
self.current.column += 1;
return char;
}
fn match(self: *Self, expected: u8) bool {
if (self.isEOF()) {
return false;
}
if (self.source[self.current.offset] != expected) {
return false;
}
self.current.offset += 1;
return true;
}
fn makeToken(self: *Self, token_type: TokenType, literal_string: ?[]const u8, literal_number: ?f64) Token {
return Token{
.token_type = token_type,
.lexeme = self.source[self.current.start..self.current.offset],
.literal_string = literal_string,
.literal_number = literal_number,
.offset = self.current.start,
.line = self.current.line,
.column = self.current.column,
};
}
}; | src/scanner.zig |
const u = @import("../util.zig");
/// See https://github.com/WebAssembly/tool-conventions/blob/main/Linking.md
/// Custom section after data
version: u32 = 2,
subsections: []Sub = &[_]Sub{},
pub const Sub = struct {
//TODO: initFuncs, symbolTable, ...
type: u8,
len: u32,
data: u.Bin,
};
/// Custom sections reloc.* after linking one
pub const Reloc = struct {
/// index of the target section
section: u32,
entries: []Entry,
pub const Entry = struct {
type: Type,
/// varuint32
offset: u32,
/// varuint32
index: u32,
/// varuint32
addend: i32 = 0,
};
pub const Type = enum(u8) {
/// a function index encoded as a 5-byte varuint32.
/// Used for the immediate argument of a call instruction.
functionIndexLeb = 0,
/// a function table index encoded as a 5-byte varint32.
/// Used to refer to the immediate argument of a i32.const instruction,
/// e.g. taking the address of a function.
tableIndexSleb = 1,
/// a function table index encoded as a uint32,
/// e.g. taking the address of a function in a static data initializer.
tableIndexI32 = 2,
/// a linear memory index encoded as a 5-byte varuint32.
/// Used for the immediate argument of a load or store instruction,
/// e.g. directly loading from or storing to a C++ global.
memoryAddrLeb = 3,
/// a linear memory index encoded as a 5-byte varint32.
/// Used for the immediate argument of a i32.const instruction,
/// e.g. taking the address of a C++ global.
memoryAddrSleb = 4,
/// a linear memory index encoded as a uint32,
/// e.g. taking the address of a C++ global in a static data initializer.
memoryAddrI32 = 5,
/// a type index encoded as a 5-byte varuint32,
/// e.g. the type immediate in a call_indirect.
typeIndexLeb = 6,
/// a global index encoded as a 5-byte varuint32,
/// e.g. the index immediate in a get_global.
globalIndexLeb = 7,
/// a byte offset within code section for the specific function encoded as a uint32.
/// The offsets start at the actual function code excluding its size field.
functionOffsetI32 = 8,
/// a byte offset from start of the specified section encoded as a uint32.
sectionOffsetI32 = 9,
/// an event index encoded as a 5-byte varuint32.
/// Used for the immediate argument of a throw and if_except instruction.
eventIndexLeb = 10,
/// a global index encoded as uint32.
globalIndexI32 = 13,
//NOTE: the 64bit relocations are not yet stable and therefore, subject to change.
/// the 64-bit counterpart of MEMORY_ADDR_LEB.
/// A 64-bit linear memory index encoded as a 10-byte varuint64,
/// Used for the immediate argument of a load or store instruction on a 64-bit linear memory array.
memoryAddrLeb64 = 14,
/// the 64-bit counterpart of MEMORY_ADDR_SLEB.
/// A 64-bit linear memory index encoded as a 10-byte varint64.
/// Used for the immediate argument of a i64.const instruction.
memoryAddrSleb64 = 15,
/// the 64-bit counterpart of MEMORY_ADDR.
/// A 64-bit linear memory index encoded as a uint64,
/// taking the 64-bit address of a C++ global in a static data initializer.
memoryAddrI64 = 16,
/// the 64-bit counterpart of TABLE_INDEX_SLEB.
/// A function table index encoded as a 10-byte varint64.
/// Used to refer to the immediate argument of a i64.const instruction, taking the address of a function in Wasm64.
tableIndexSleb64 = 18,
/// the 64-bit counterpart of TABLE_INDEX_I32.
/// A function table index encoded as a uint64, taking the address of a function in a static data initializer.
tableIndexI64 = 19,
/// a table number encoded as a 5-byte varuint32.
/// Used for the table immediate argument in the table.* instructions.
tableNumberLeb = 20,
};
};
//MAYBE: TargetFeature | src/IR/Linking.zig |
const std = @import("../std.zig");
const builtin = @import("builtin");
const root = @import("root");
const mem = std.mem;
const assert = std.debug.assert;
pub fn AutoIndentingStream(comptime DownStream: type) type {
return struct {
const Self = @This();
pub const Error = DownStream.Error;
down_stream: *DownStream,
current_line_empty: bool = true,
indent_stack: [255]u8 = undefined,
indent_stack_top: u8 = 0,
indent_one_shot_count: u8 = 0, // automatically popped when applied
applied_indent: u8 = 0, // the most recently applied indent
indent_next_line: u8 = 0, // not used until the next line
indent_delta: u8 = indent_delta,
pub fn init(down_stream: *DownStream, indent_delta: u8) Self {
return Self{
.down_stream = down_stream,
.indent_delta = indent_delta,
};
}
pub fn write(self: *Self, bytes: []const u8) Error!void {
if (bytes.len == 0)
return;
try self.applyIndent();
try self.writeNoIndent(bytes);
if (bytes[bytes.len - 1] == '\n')
self.resetLine();
}
fn writeNoIndent(self: *Self, bytes: []const u8) Error!void {
try self.down_stream.write(bytes);
}
pub fn print(self: *Self, comptime format: []const u8, args: var) Error!void {
return std.fmt.format(self, Error, write, format, args);
}
pub fn writeByte(self: *Self, byte: u8) Error!void {
const array = [1]u8{byte};
return self.write(&array);
}
pub fn writeByteNTimes(self: *Self, byte: u8, n: usize) Error!void {
try self.applyIndent();
try self.writeByteNTimesNoIndent(byte, n);
}
fn writeByteNTimesNoIndent(self: *Self, byte: u8, n: usize) Error!void {
var bytes: [256]u8 = undefined;
mem.set(u8, bytes[0..], byte);
var remaining: usize = n;
while (remaining > 0) {
const to_write = std.math.min(remaining, bytes.len);
try self.writeNoIndent(bytes[0..to_write]);
remaining -= to_write;
}
}
pub fn insertNewline(self: *Self) Error!void {
try self.writeNoIndent("\n");
self.resetLine();
}
fn resetLine(self: *Self) void {
self.current_line_empty = true;
self.indent_next_line = 0;
}
/// Insert a newline unless the current line is blank
pub fn maybeInsertNewline(self: *Self) Error!void {
if (!self.current_line_empty)
try self.insertNewline();
}
/// Push default indentation
pub fn pushIndent(self: *Self) void {
// Doesn't actually write any indentation. Just primes the stream to be able to write the correct indentation if it needs to.
self.pushIndentN(self.indent_delta);
}
/// Push an indent of arbitrary width
pub fn pushIndentN(self: *Self, n: u8) void {
assert(self.indent_stack_top < std.math.maxInt(u8));
self.indent_stack[self.indent_stack_top] = n;
self.indent_stack_top += 1;
}
/// Push an indent that is automatically popped after being applied
pub fn pushIndentOneShot(self: *Self) void {
self.indent_one_shot_count += 1;
self.pushIndent();
}
/// Turns all one-shot indents into regular indents
/// Returns number of indents that must now be manually popped
pub fn lockOneShotIndent(self: *Self) u8 {
var locked_count = self.indent_one_shot_count;
self.indent_one_shot_count = 0;
return locked_count;
}
/// Push an indent that should not take effect until the next line
pub fn pushIndentNextLine(self: *Self) void {
self.indent_next_line += 1;
self.pushIndent();
}
pub fn popIndent(self: *Self) void {
assert(self.indent_stack_top != 0);
self.indent_stack_top -= 1;
}
/// Writes ' ' bytes if the current line is empty
fn applyIndent(self: *Self) Error!void {
const current_indent = self.currentIndent();
if (self.current_line_empty and current_indent > 0) {
try self.writeByteNTimesNoIndent(' ', current_indent);
self.applied_indent = current_indent;
}
self.indent_stack_top -= self.indent_one_shot_count;
self.indent_one_shot_count = 0;
self.current_line_empty = false;
}
/// Checks to see if the most recent indentation exceeds the currently pushed indents
pub fn isLineOverIndented(self: *Self) bool {
if (self.current_line_empty) return false;
return self.applied_indent > self.currentIndent();
}
fn currentIndent(self: *Self) u8 {
var indent_current: u8 = 0;
if (self.indent_stack_top > 0) {
const stack_top = self.indent_stack_top - self.indent_next_line;
for (self.indent_stack[0..stack_top]) |indent| {
indent_current += indent;
}
}
return indent_current;
}
};
} | lib/std/io/auto_indenting_stream.zig |
const std = @import("std");
const mecha = @import("../mecha.zig");
const math = std.math;
const unicode = std.unicode;
// Constructs a parser that only succeeds if the string starts with `c`.
pub fn char(comptime c: u21) mecha.Parser(void) {
comptime {
var array: [4]u8 = undefined;
const len = unicode.utf8Encode(c, array[0..]) catch unreachable;
return mecha.string(array[0..len]);
}
}
test "char" {
mecha.expectResult(void, .{ .value = {}, .rest = "" }, char('a')("a"));
mecha.expectResult(void, .{ .value = {}, .rest = "a" }, char('a')("aa"));
mecha.expectResult(void, null, char('a')("ba"));
mecha.expectResult(void, null, char('a')(""));
mecha.expectResult(void, .{ .value = {}, .rest = "ā" }, char(0x100)("Āā"));
mecha.expectResult(void, null, char(0x100)(""));
mecha.expectResult(void, null, char(0x100)("\xc0"));
}
/// Constructs a parser that only succeeds if the string starts with
/// a codepoint that is in between `start` and `end` inclusively.
/// The parsers result will be the codepoint parsed.
pub fn range(comptime start: u21, comptime end: u21) mecha.Parser(u21) {
return struct {
const Res = mecha.Result(u21);
fn func(str: []const u8) ?Res {
if (str.len == 0)
return null;
if (end <= math.maxInt(u7)) {
switch (str[0]) {
start...end => return Res.init(str[0], str[1..]),
else => return null,
}
} else {
const cp_len = unicode.utf8ByteSequenceLength(str[0]) catch return null;
if (cp_len > str.len)
return null;
const cp = unicode.utf8Decode(str[0..cp_len]) catch return null;
switch (cp) {
start...end => return Res.init(cp, str[cp_len..]),
else => return null,
}
}
}
}.func;
}
test "range" {
mecha.expectResult(u21, .{ .value = 'a', .rest = "" }, range('a', 'z')("a"));
mecha.expectResult(u21, .{ .value = 'c', .rest = "" }, range('a', 'z')("c"));
mecha.expectResult(u21, .{ .value = 'z', .rest = "" }, range('a', 'z')("z"));
mecha.expectResult(u21, .{ .value = 'a', .rest = "a" }, range('a', 'z')("aa"));
mecha.expectResult(u21, .{ .value = 'c', .rest = "a" }, range('a', 'z')("ca"));
mecha.expectResult(u21, .{ .value = 'z', .rest = "a" }, range('a', 'z')("za"));
mecha.expectResult(u21, null, range('a', 'z')("1"));
mecha.expectResult(u21, null, range('a', 'z')(""));
mecha.expectResult(u21, .{ .value = 0x100, .rest = "ā" }, range(0x100, 0x100)("Āā"));
mecha.expectResult(u21, null, range(0x100, 0x100)("aa"));
mecha.expectResult(u21, null, range(0x100, 0x100)("\xc0"));
}
/// Creates a parser that succeeds and parses one utf8 codepoint if
/// `parser` fails to parse the input string.
pub fn not(comptime parser: anytype) mecha.Parser(u21) {
return struct {
const Res = mecha.Result(u21);
fn res(str: []const u8) ?Res {
if (str.len == 0)
return null;
if (parser(str)) |_|
return null;
const cp_len = unicode.utf8ByteSequenceLength(str[0]) catch return null;
if (cp_len > str.len)
return null;
const cp = unicode.utf8Decode(str[0..cp_len]) catch return null;
return Res.init(cp, str[cp_len..]);
}
}.res;
}
test "not" {
const p = not(comptime range('a', 'z'));
var i: u16 = 0;
while (i <= math.maxInt(u7)) : (i += 1) {
const c = @intCast(u8, i);
switch (c) {
'a'...'z' => mecha.expectResult(u21, null, p(&[_]u8{c})),
else => mecha.expectResult(u21, .{ .value = c, .rest = "" }, p(&[_]u8{c})),
}
}
} | src/utf8.zig |
/// Error set
pub const Error = error{ CheckFailed, Unknown, Duplicate, FailedToAdd };
const std = @import("std");
const gl = @import("gl.zig");
usingnamespace @import("log.zig");
// TODO: Localized cross-platform(win32-posix) timer
/// If expresion is true return(CheckFailed) error
pub fn check(expression: bool, comptime msg: []const u8, va: anytype) Error!void {
if (expression) {
std.log.emerg(msg, va);
return Error.CheckFailed;
}
}
/// Simple data collector
pub const DataPacker = struct {
const Self = @This();
pub const maximum_data = maximumdata;
pub const Element = struct {
start: usize = 0,
end: usize = 0,
};
stack: usize = 0,
allocatedsize: usize = 0,
buffer: []u8 = undefined,
allocator: *std.mem.Allocator = undefined,
/// Initializes
pub fn init(alloc: *std.mem.Allocator, reservedsize: usize) !Self {
try check(reservedsize == 0, "kira/utils -> reservedsize cannot be zero!", .{});
const self = Self{
.allocator = alloc,
.allocatedsize = reservedsize,
.buffer = try alloc.alloc(u8, reservedsize),
.stack = 0,
};
return self;
}
/// Deinitializes
pub fn deinit(self: *Self) void {
self.allocator.free(self.buffer);
self.* = Self{};
}
/// Appends a data into buffer, deep copies it
pub fn append(self: *Self, data: []const u8) !Element {
if (self.stack < self.allocatedsize) {
if (self.allocatedsize - self.stack < data.len) {
try self.reserve(data.len);
}
}
std.mem.copy(u8, self.buffer[self.stack..self.allocatedsize], data);
self.stack += data.len;
return Element{
.start = self.stack - data.len,
.end = self.stack,
};
}
/// Reserves data
pub fn reserve(self: *Self, size: usize) !void {
try check(size == 0, "kira/utils -> size cannot be zero!", .{});
self.buffer = try self.allocator.realloc(self.buffer, self.allocatedsize + size);
self.allocatedsize = self.allocatedsize + size;
}
};
pub fn UniqueList(comptime T: type) type {
return struct {
const Self = @This();
pub const typ = T;
pub const Item = struct {
data: typ = undefined,
is_exists: bool = false,
};
allocator: *std.mem.Allocator = undefined,
items: []Item = undefined,
count: u64 = 0,
total_capacity: u64 = 1,
/// Allocates the memory
pub fn init(alloc: *std.mem.Allocator, reserve: u64) !Self {
var self = Self{
.allocator = alloc,
.items = undefined,
.total_capacity = 1 + reserve,
.count = 0,
};
self.items = try self.allocator.alloc(Item, self.total_capacity);
self.clear();
return self;
}
/// Frees the memory once
pub fn deinit(self: *Self) void {
self.allocator.free(self.items);
}
/// Clears the list
pub fn clear(self: *Self) void {
var i: u64 = 0;
while (i < self.total_capacity) : (i += 1) {
self.items[i].is_exists = false;
self.items[i].data = undefined;
}
self.count = 0;
}
/// Increases the capacity
pub fn increaseCapacity(self: *Self, reserve: u64) !void {
var buf = self.items;
self.items = try self.allocator.alloc(Item, self.total_capacity + reserve);
var i: u64 = 0;
while (i < self.total_capacity) : (i += 1) {
self.items[i] = buf[i];
}
self.allocator.free(buf);
self.total_capacity += reserve;
while (i < self.total_capacity) : (i += 1) {
self.items[i].is_exists = false;
self.items[i].data = undefined;
}
}
/// It cannot decrease a used space,
/// call it after calling the 'clear' function
pub fn decreaseCapacity(self: *Self, reserve: u64) !void {
if (self.total_capacity - reserve <= self.count) return;
var buf = self.items;
self.items = try self.allocator.alloc(Item, self.total_capacity - reserve);
var i: u64 = self.total_capacity;
while (i >= 0) : (i -= 1) {
self.items[i] = buf[i];
}
self.allocator.free(buf);
self.total_capacity -= reserve;
}
/// Insert an item, it fails if the item was a duplicate
pub fn insert(self: *Self, item: typ, autoincrease: bool) !void {
var i: u64 = 0;
while (i < self.total_capacity) : (i += 1) {
if (self.items[i].is_exists and self.items[i].data == item) {
return Error.Duplicate;
} else if (!self.items[i].is_exists) {
self.items[i].data = item;
self.items[i].is_exists = true;
self.count += 1;
return;
}
}
if (autoincrease) {
try self.increaseCapacity(1);
return self.insert(item, false);
}
return Error.FailedToAdd;
}
/// Remove an item
pub fn remove(self: *Self, item: typ) Error!void {
var i: u64 = 0;
while (i < self.total_capacity) : (i += 1) {
if (self.items[i].is_exists and self.items[i].data == item) {
self.items[i].is_exists = false;
self.items[i].data = undefined;
self.count -= 1;
return;
}
}
return Error.Unknown;
}
/// Get an item index
pub fn getIndex(self: Self, item: typ) Error!u64 {
var i: u64 = 0;
while (i < self.total_capacity) : (i += 1) {
if (self.items[i].is_exists and self.items[i].data == item) {
return i;
}
}
return Error.Unknown;
}
/// Does the data exists?
pub fn isExists(self: Self, item: typ) bool {
var i: u64 = 0;
while (i < self.total_capacity) : (i += 1) {
if (self.items[i].is_exists and self.items[i].data == item) {
return true;
}
}
return false;
}
/// Turn the existing data into array
pub fn convertToArray(self: Self, comptime tp: type, comptime len: u64) [len]tp {
var result: [len]typ = undefined;
var i: u64 = 0;
while (i < self.total_capacity) : (i += 1) {
if (self.items[i].is_exists) {
result[i] = self.items[i].data;
}
}
return result;
}
};
}
pub fn UniqueFixedList(comptime typ: type, comptime max: u64) type {
return struct {
const Self = @This();
pub const T = typ;
pub const Max = max;
pub const Item = struct {
data: typ = undefined,
is_exists: bool = false,
};
items: [Max]Item = undefined,
count: u64 = 0,
/// Clears the list
pub fn clear(self: *Self) void {
var i: u64 = 0;
while (i < Self.Max) : (i += 1) {
self.items[i].is_exists = false;
self.items[i].data = undefined;
}
self.count = 0;
}
/// Insert an item, it fails if the item was a duplicate
/// Returns the index
pub fn insert(self: *Self, item: typ) Error!u64 {
var i: u64 = 0;
while (i < Self.Max) : (i += 1) {
if (self.items[i].is_exists and self.items[i].data == item) {
return Error.Duplicate;
} else if (!self.items[i].is_exists) {
self.items[i].data = item;
self.items[i].is_exists = true;
self.count += 1;
return i;
}
}
return Error.FailedToAdd;
}
/// Remove an item
pub fn remove(self: *Self, item: typ) Error!void {
var i: u64 = 0;
while (i < Self.Max) : (i += 1) {
if (self.items[i].is_exists and self.items[i].data == item) {
self.items[i].is_exists = false;
self.items[i].data = undefined;
self.count -= 1;
return;
}
}
return Error.Unknown;
}
/// Get an item index
pub fn getIndex(self: Self, item: typ) Error!u64 {
var i: u64 = 0;
while (i < Self.Max) : (i += 1) {
if (self.items[i].is_exists and self.items[i].data == item) {
return i;
}
}
return Error.Unknown;
}
/// Does the data exists?
pub fn isExists(self: Self, item: typ) bool {
var i: u64 = 0;
while (i < Self.Max) : (i += 1) {
if (self.items[i].is_exists and self.items[i].data == item) {
return true;
}
}
return false;
}
/// Turn the existing data into array
pub fn convertToArray(self: Self, comptime tp: type, comptime len: u64) [len]tp {
var result: [len]typ = undefined;
var i: u64 = 0;
while (i < Self.Max) : (i += 1) {
if (self.items[i].is_exists) {
result[i] = self.items[i].data;
}
}
return result;
}
};
} | src/kiragine/kira/utils.zig |
const std = @import("std");
const testing = std.testing;
const Allocator = std.mem.Allocator;
const io = std.io;
const dns = @import("./dns.zig");
const Packet = dns.Packet;
test "convert domain string to dns name" {
const domain = "www.google.com";
var name_buffer: [3][]const u8 = undefined;
var name = try dns.Name.fromString(domain[0..], &name_buffer);
std.debug.assert(name.labels.len == 3);
testing.expect(std.mem.eql(u8, name.labels[0], "www"));
testing.expect(std.mem.eql(u8, name.labels[1], "google"));
testing.expect(std.mem.eql(u8, name.labels[2], "com"));
}
test "convert domain string to dns name (buffer underrun)" {
const domain = "www.google.com";
var name_buffer: [1][]const u8 = undefined;
_ = dns.Name.fromString(domain[0..], &name_buffer) catch |err| switch (err) {
error.Underflow => {},
else => return err,
};
}
// extracted with 'dig google.com a +noedns'
const TEST_PKT_QUERY = "FEUBIAABAAAAAAAABmdvb2dsZQNjb20AAAEAAQ==";
const TEST_PKT_RESPONSE = "RM2BgAABAAEAAAAABmdvb2dsZQNjb20AAAEAAcAMAAEAAQAAASwABNg6yo4=";
const GOOGLE_COM_LABELS = [_][]const u8{ "google"[0..], "com"[0..] };
test "Packet serialize/deserialize" {
var allocator_instance = std.heap.GeneralPurposeAllocator(.{}){};
defer {
_ = allocator_instance.deinit();
}
const allocator = &allocator_instance.allocator;
const seed = @truncate(u64, @bitCast(u128, std.time.nanoTimestamp()));
var r = std.rand.DefaultPrng.init(seed);
const random_id = r.random.int(u16);
var packet = dns.Packet{
.header = .{ .id = random_id },
.questions = &[_]dns.Question{},
.answers = &[_]dns.Resource{},
.nameservers = &[_]dns.Resource{},
.additionals = &[_]dns.Resource{},
};
// then we'll serialize it under a buffer on the stack,
// deserialize it, and the header.id should be equal to random_id
var write_buffer: [1024]u8 = undefined;
const buf = try serialTest(packet, &write_buffer);
// deserialize it and compare if everythings' equal
var workmem: [5000]u8 = undefined;
var deserialized = try deserialTest(buf, &workmem);
testing.expectEqual(deserialized.header.id, packet.header.id);
const fields = [_][]const u8{ "id", "opcode", "question_length", "answer_length" };
var new_header = deserialized.header;
var header = packet.header;
inline for (fields) |field| {
testing.expectEqual(@field(new_header, field), @field(header, field));
}
}
fn decodeBase64(encoded: []const u8, write_buffer: []u8) ![]const u8 {
const size = try std.base64.standard_decoder.calcSize(encoded);
try std.base64.standard_decoder.decode(write_buffer[0..size], encoded);
return write_buffer[0..size];
}
fn expectGoogleLabels(actual: [][]const u8) void {
for (actual) |label, idx| {
std.testing.expectEqualSlices(u8, label, GOOGLE_COM_LABELS[idx]);
}
}
test "deserialization of original google.com/A" {
var allocator_instance = std.heap.GeneralPurposeAllocator(.{}){};
defer {
_ = allocator_instance.deinit();
}
const allocator = &allocator_instance.allocator;
var write_buffer: [0x10000]u8 = undefined;
var decoded = try decodeBase64(TEST_PKT_QUERY, &write_buffer);
var deserializer_buffer: [0x10000]u8 = undefined;
var pkt = try deserialTest(decoded, &deserializer_buffer);
std.testing.expectEqual(@as(u16, 5189), pkt.header.id);
std.testing.expectEqual(@as(u16, 1), pkt.header.question_length);
std.testing.expectEqual(@as(u16, 0), pkt.header.answer_length);
std.testing.expectEqual(@as(u16, 0), pkt.header.nameserver_length);
std.testing.expectEqual(@as(u16, 0), pkt.header.additional_length);
std.testing.expectEqual(@as(usize, 1), pkt.questions.len);
const question = pkt.questions[0];
expectGoogleLabels(question.name.labels);
std.testing.expectEqual(question.typ, dns.ResourceType.A);
std.testing.expectEqual(question.class, dns.ResourceClass.IN);
}
test "deserialization of reply google.com/A" {
var allocator_instance = std.heap.GeneralPurposeAllocator(.{}){};
defer {
_ = allocator_instance.deinit();
}
const allocator = &allocator_instance.allocator;
var encode_buffer: [0x10000]u8 = undefined;
var decoded = try decodeBase64(TEST_PKT_RESPONSE, &encode_buffer);
var workmem: [0x100000]u8 = undefined;
var pkt = try deserialTest(decoded, &workmem);
std.testing.expectEqual(@as(u16, 17613), pkt.header.id);
std.testing.expectEqual(@as(u16, 1), pkt.header.question_length);
std.testing.expectEqual(@as(u16, 1), pkt.header.answer_length);
std.testing.expectEqual(@as(u16, 0), pkt.header.nameserver_length);
std.testing.expectEqual(@as(u16, 0), pkt.header.additional_length);
var question = pkt.questions[0];
expectGoogleLabels(question.name.labels);
testing.expectEqual(dns.ResourceType.A, question.typ);
testing.expectEqual(dns.ResourceClass.IN, question.class);
var answer = pkt.answers[0];
expectGoogleLabels(answer.name.labels);
testing.expectEqual(dns.ResourceType.A, answer.typ);
testing.expectEqual(dns.ResourceClass.IN, answer.class);
testing.expectEqual(@as(i32, 300), answer.ttl);
const resource_data = try dns.ResourceData.fromOpaque(allocator, .A, answer.opaque_rdata);
testing.expectEqual(dns.ResourceType.A, @as(dns.ResourceType, resource_data));
const addr = @ptrCast(*const [4]u8, &resource_data.A.in.sa.addr).*;
testing.expectEqual(@as(u8, 216), addr[0]);
testing.expectEqual(@as(u8, 58), addr[1]);
testing.expectEqual(@as(u8, 202), addr[2]);
testing.expectEqual(@as(u8, 142), addr[3]);
}
fn encodeBase64(buffer: []u8, source: []const u8) []const u8 {
var encoded = buffer[0..std.base64.Base64Encoder.calcSize(source.len)];
std.base64.standard_encoder.encode(encoded, source);
return encoded;
}
fn encodePacket(pkt: Packet, encode_buffer: []u8, write_buffer: []u8) ![]const u8 {
var out = try serialTest(pkt, write_buffer);
return encodeBase64(encode_buffer, out);
}
test "serialization of google.com/A (question)" {
const domain = "google.com";
var name_buffer: [2][]const u8 = undefined;
var name = try dns.Name.fromString(domain[0..], &name_buffer);
var packet = dns.Packet{
.header = .{
.id = 5189,
.wanted_recursion = true,
.z = 2,
.question_length = 1,
},
.questions = &[_]dns.Question{.{
.name = name,
.typ = .A,
.class = .IN,
}},
.answers = &[_]dns.Resource{},
.nameservers = &[_]dns.Resource{},
.additionals = &[_]dns.Resource{},
};
var encode_buffer: [256]u8 = undefined;
var write_buffer: [256]u8 = undefined;
var encoded = try encodePacket(packet, &encode_buffer, &write_buffer);
testing.expectEqualSlices(u8, encoded, TEST_PKT_QUERY);
}
fn serialTest(packet: Packet, write_buffer: []u8) ![]u8 {
const T = std.io.FixedBufferStream([]u8);
var buffer = T{ .buffer = write_buffer, .pos = 0 };
var serializer = std.io.Serializer(.Big, .Bit, T.Writer).init(buffer.writer());
try serializer.serialize(packet);
try serializer.flush();
return buffer.getWritten();
}
const FixedStream = std.io.FixedBufferStream([]const u8);
fn deserialTest(buf: []const u8, work_memory: []u8) !Packet {
var stream = FixedStream{ .buffer = buf, .pos = 0 };
var fba = std.heap.FixedBufferAllocator.init(work_memory);
var ctx = dns.DeserializationContext.init(&fba.allocator);
var pkt = dns.Packet{
.header = .{},
.questions = &[_]dns.Question{},
.answers = &[_]dns.Resource{},
.nameservers = &[_]dns.Resource{},
.additionals = &[_]dns.Resource{},
};
try pkt.readInto(stream.reader(), &ctx);
return pkt;
}
test "convert string to dns type" {
var parsed = try dns.ResourceType.fromString("AAAA");
testing.expectEqual(dns.ResourceType.AAAA, parsed);
}
test "size() methods are good" {
var name_buffer: [10][]const u8 = undefined;
var name = try dns.Name.fromString("example.com", &name_buffer);
// length + data + length + data + null
testing.expectEqual(@as(usize, 1 + 7 + 1 + 3 + 1), name.size());
var resource = dns.Resource{
.name = name,
.typ = .A,
.class = .IN,
.ttl = 300,
.opaque_rdata = "",
};
// name + rr (2) + class (2) + ttl (4) + rdlength (2)
testing.expectEqual(@as(usize, name.size() + 10 + resource.opaque_rdata.len), resource.size());
}
// This is a known packet generated by zigdig. It would be welcome to have it
// tested in other libraries.
const PACKET_WITH_RDATA = "FEUBIAAAAAEAAAAABmdvb2dsZQNjb20AAAEAAQAAASwABAEAAH8=";
test "rdata serialization" {
var allocator_instance = std.heap.GeneralPurposeAllocator(.{}){};
defer {
_ = allocator_instance.deinit();
}
const allocator = &allocator_instance.allocator;
var name_buffer: [2][]const u8 = undefined;
var name = try dns.Name.fromString("google.com", &name_buffer);
var resource_data = dns.ResourceData{
.A = try std.net.Address.parseIp4("127.0.0.1", 0),
};
var opaque_rdata_buffer: [0x1000]u8 = undefined;
var fba = std.heap.FixedBufferAllocator.init(&opaque_rdata_buffer);
var alloc = &fba.allocator;
var opaque_resource_data = try alloc.alloc(u8, resource_data.size());
const StreamT = std.io.FixedBufferStream([]u8);
var stream = StreamT{ .buffer = opaque_resource_data, .pos = 0 };
var serializer = std.io.Serializer(.Big, .Bit, StreamT.Writer).init(stream.writer());
try serializer.serialize(resource_data);
try serializer.flush();
var packet = dns.Packet{
.header = .{
.id = 5189,
.wanted_recursion = true,
.z = 2,
.answer_length = 1,
},
.questions = &[_]dns.Question{},
.answers = &[_]dns.Resource{.{
.name = name,
.typ = .A,
.class = .IN,
.ttl = 300,
.opaque_rdata = opaque_resource_data,
}},
.nameservers = &[_]dns.Resource{},
.additionals = &[_]dns.Resource{},
};
var write_buffer: [1024]u8 = undefined;
const serialized_result = try serialTest(packet, &write_buffer);
var encode_buffer: [1024]u8 = undefined;
const encoded_result = encodeBase64(&encode_buffer, serialized_result);
testing.expectEqualStrings(PACKET_WITH_RDATA, encoded_result);
} | src/pkg2/test.zig |
const midi = @import("../midi.zig");
const std = @import("std");
const io = std.io;
const mem = std.mem;
const testing = std.testing;
const decode = midi.decode;
const encode = midi.encode;
const file = midi.file;
test "midi.decode/encode.message" {
try testMessage("\x80\x00\x00" ++
"\x7F\x7F" ++
"\x8F\x7F\x7F", &[_]midi.Message{
midi.Message{
.status = 0x00,
.values = [2]u7{ 0x0, 0x0 },
},
midi.Message{
.status = 0x00,
.values = [2]u7{ 0x7F, 0x7F },
},
midi.Message{
.status = 0x0F,
.values = [2]u7{ 0x7F, 0x7F },
},
});
try testMessage("\x90\x00\x00" ++
"\x7F\x7F" ++
"\x9F\x7F\x7F", &[_]midi.Message{
midi.Message{
.status = 0x10,
.values = [2]u7{ 0x0, 0x0 },
},
midi.Message{
.status = 0x10,
.values = [2]u7{ 0x7F, 0x7F },
},
midi.Message{
.status = 0x1F,
.values = [2]u7{ 0x7F, 0x7F },
},
});
try testMessage("\xA0\x00\x00" ++
"\x7F\x7F" ++
"\xAF\x7F\x7F", &[_]midi.Message{
midi.Message{
.status = 0x20,
.values = [2]u7{ 0x0, 0x0 },
},
midi.Message{
.status = 0x20,
.values = [2]u7{ 0x7F, 0x7F },
},
midi.Message{
.status = 0x2F,
.values = [2]u7{ 0x7F, 0x7F },
},
});
try testMessage("\xB0\x00\x00" ++
"\x77\x7F" ++
"\xBF\x77\x7F", &[_]midi.Message{
midi.Message{
.status = 0x30,
.values = [2]u7{ 0x0, 0x0 },
},
midi.Message{
.status = 0x30,
.values = [2]u7{ 0x77, 0x7F },
},
midi.Message{
.status = 0x3F,
.values = [2]u7{ 0x77, 0x7F },
},
});
try testMessage("\xC0\x00" ++
"\x7F" ++
"\xCF\x7F", &[_]midi.Message{
midi.Message{
.status = 0x40,
.values = [2]u7{ 0x0, 0x0 },
},
midi.Message{
.status = 0x40,
.values = [2]u7{ 0x7F, 0x0 },
},
midi.Message{
.status = 0x4F,
.values = [2]u7{ 0x7F, 0x0 },
},
});
try testMessage("\xD0\x00" ++
"\x7F" ++
"\xDF\x7F", &[_]midi.Message{
midi.Message{
.status = 0x50,
.values = [2]u7{ 0x0, 0x0 },
},
midi.Message{
.status = 0x50,
.values = [2]u7{ 0x7F, 0x0 },
},
midi.Message{
.status = 0x5F,
.values = [2]u7{ 0x7F, 0x0 },
},
});
try testMessage("\xE0\x00\x00" ++
"\x7F\x7F" ++
"\xEF\x7F\x7F", &[_]midi.Message{
midi.Message{
.status = 0x60,
.values = [2]u7{ 0x0, 0x0 },
},
midi.Message{
.status = 0x60,
.values = [2]u7{ 0x7F, 0x7F },
},
midi.Message{
.status = 0x6F,
.values = [2]u7{ 0x7F, 0x7F },
},
});
try testMessage("\xF0\xF0", &[_]midi.Message{
midi.Message{
.status = 0x70,
.values = [2]u7{ 0x0, 0x0 },
},
midi.Message{
.status = 0x70,
.values = [2]u7{ 0x0, 0x0 },
},
});
try testMessage("\xF1\x00" ++
"\xF1\x0F" ++
"\xF1\x70" ++
"\xF1\x7F", &[_]midi.Message{
midi.Message{
.status = 0x71,
.values = [2]u7{ 0x0, 0x0 },
},
midi.Message{
.status = 0x71,
.values = [2]u7{ 0x0F, 0x0 },
},
midi.Message{
.status = 0x71,
.values = [2]u7{ 0x70, 0x0 },
},
midi.Message{
.status = 0x71,
.values = [2]u7{ 0x7F, 0x0 },
},
});
try testMessage("\xF2\x00\x00" ++
"\xF2\x7F\x7F", &[_]midi.Message{
midi.Message{
.status = 0x72,
.values = [2]u7{ 0x0, 0x0 },
},
midi.Message{
.status = 0x72,
.values = [2]u7{ 0x7F, 0x7F },
},
});
try testMessage("\xF3\x00" ++
"\xF3\x7F", &[_]midi.Message{
midi.Message{
.status = 0x73,
.values = [2]u7{ 0x0, 0x0 },
},
midi.Message{
.status = 0x73,
.values = [2]u7{ 0x7F, 0x0 },
},
});
try testMessage("\xF6\xF6", &[_]midi.Message{
midi.Message{
.status = 0x76,
.values = [2]u7{ 0x0, 0x0 },
},
midi.Message{
.status = 0x76,
.values = [2]u7{ 0x0, 0x0 },
},
});
try testMessage("\xF7\xF7", &[_]midi.Message{
midi.Message{
.status = 0x77,
.values = [2]u7{ 0x0, 0x0 },
},
midi.Message{
.status = 0x77,
.values = [2]u7{ 0x0, 0x0 },
},
});
try testMessage("\xF8\xF8", &[_]midi.Message{
midi.Message{
.status = 0x78,
.values = [2]u7{ 0x0, 0x0 },
},
midi.Message{
.status = 0x78,
.values = [2]u7{ 0x0, 0x0 },
},
});
try testMessage("\xFA\xFA", &[_]midi.Message{
midi.Message{
.status = 0x7A,
.values = [2]u7{ 0x0, 0x0 },
},
midi.Message{
.status = 0x7A,
.values = [2]u7{ 0x0, 0x0 },
},
});
try testMessage("\xFB\xFB", &[_]midi.Message{
midi.Message{
.status = 0x7B,
.values = [2]u7{ 0x0, 0x0 },
},
midi.Message{
.status = 0x7B,
.values = [2]u7{ 0x0, 0x0 },
},
});
try testMessage("\xFC\xFC", &[_]midi.Message{
midi.Message{
.status = 0x7C,
.values = [2]u7{ 0x0, 0x0 },
},
midi.Message{
.status = 0x7C,
.values = [2]u7{ 0x0, 0x0 },
},
});
try testMessage("\xFE\xFE", &[_]midi.Message{
midi.Message{
.status = 0x7E,
.values = [2]u7{ 0x0, 0x0 },
},
midi.Message{
.status = 0x7E,
.values = [2]u7{ 0x0, 0x0 },
},
});
try testMessage("\xFF\xFF", &[_]midi.Message{
midi.Message{
.status = 0x7F,
.values = [2]u7{ 0x0, 0x0 },
},
midi.Message{
.status = 0x7F,
.values = [2]u7{ 0x0, 0x0 },
},
});
}
test "midi.decode/encode.chunk" {
try testChunk("abcd\x00\x00\x00\x04".*, midi.file.Chunk{ .kind = "abcd".*, .len = 0x04 });
try testChunk("efgh\x00\x00\x04\x00".*, midi.file.Chunk{ .kind = "efgh".*, .len = 0x0400 });
try testChunk("ijkl\x00\x04\x00\x00".*, midi.file.Chunk{ .kind = "ijkl".*, .len = 0x040000 });
try testChunk("mnop\x04\x00\x00\x00".*, midi.file.Chunk{ .kind = "mnop".*, .len = 0x04000000 });
}
test "midi.decode/encode.fileHeader" {
try testFileHeader("MThd\x00\x00\x00\x06\x00\x00\x00\x01\x01\x10".*, midi.file.Header{
.chunk = midi.file.Chunk{
.kind = "MThd".*,
.len = 6,
},
.format = 0,
.tracks = 0x0001,
.division = 0x0110,
});
try testFileHeader("MThd\x00\x00\x00\x06\x00\x01\x01\x01\x01\x10".*, midi.file.Header{
.chunk = midi.file.Chunk{
.kind = "MThd".*,
.len = 6,
},
.format = 1,
.tracks = 0x0101,
.division = 0x0110,
});
try testFileHeader("MThd\x00\x00\x00\x06\x00\x02\x01\x01\x01\x10".*, midi.file.Header{
.chunk = midi.file.Chunk{
.kind = "MThd".*,
.len = 6,
},
.format = 2,
.tracks = 0x0101,
.division = 0x0110,
});
try testFileHeader("MThd\x00\x00\x00\x06\x00\x00\x00\x01\xFF\x10".*, midi.file.Header{
.chunk = midi.file.Chunk{
.kind = "MThd".*,
.len = 6,
},
.format = 0,
.tracks = 0x0001,
.division = 0xFF10,
});
try testFileHeader("MThd\x00\x00\x00\x06\x00\x01\x01\x01\xFF\x10".*, midi.file.Header{
.chunk = midi.file.Chunk{
.kind = "MThd".*,
.len = 6,
},
.format = 1,
.tracks = 0x0101,
.division = 0xFF10,
});
try testFileHeader("MThd\x00\x00\x00\x06\x00\x02\x01\x01\xFF\x10".*, midi.file.Header{
.chunk = midi.file.Chunk{
.kind = "MThd".*,
.len = 6,
},
.format = 2,
.tracks = 0x0101,
.division = 0xFF10,
});
try testing.expectError(error.InvalidFileHeader, decode.fileHeaderFromBytes("MThd\x00\x00\x00\x05\x00\x00\x00\x01\x01\x10".*));
}
test "midi.decode/encode.int" {
try testInt("\x00" ++
"\x40" ++
"\x7F" ++
"\x81\x00" ++
"\xC0\x00" ++
"\xFF\x7F" ++
"\x81\x80\x00" ++
"\xC0\x80\x00" ++
"\xFF\xFF\x7F" ++
"\x81\x80\x80\x00" ++
"\xC0\x80\x80\x00" ++
"\xFF\xFF\xFF\x7F", &[_]u28{
0x00000000,
0x00000040,
0x0000007F,
0x00000080,
0x00002000,
0x00003FFF,
0x00004000,
0x00100000,
0x001FFFFF,
0x00200000,
0x08000000,
0x0FFFFFFF,
});
}
test "midi.decode/encode.metaEvent" {
try testMetaEvent("\x00\x00" ++
"\x00\x02", &[_]midi.file.MetaEvent{
midi.file.MetaEvent{
.kind_byte = 0,
.len = 0,
},
midi.file.MetaEvent{
.kind_byte = 0,
.len = 2,
},
});
try testMetaEvent("\x01\x00" ++
"\x01\x02", &[_]midi.file.MetaEvent{
midi.file.MetaEvent{
.kind_byte = 1,
.len = 0,
},
midi.file.MetaEvent{
.kind_byte = 1,
.len = 2,
},
});
try testMetaEvent("\x02\x00" ++
"\x02\x02", &[_]midi.file.MetaEvent{
midi.file.MetaEvent{
.kind_byte = 2,
.len = 0,
},
midi.file.MetaEvent{
.kind_byte = 2,
.len = 2,
},
});
try testMetaEvent("\x03\x00" ++
"\x03\x02", &[_]midi.file.MetaEvent{
midi.file.MetaEvent{
.kind_byte = 3,
.len = 0,
},
midi.file.MetaEvent{
.kind_byte = 3,
.len = 2,
},
});
try testMetaEvent("\x04\x00" ++
"\x04\x02", &[_]midi.file.MetaEvent{
midi.file.MetaEvent{
.kind_byte = 4,
.len = 0,
},
midi.file.MetaEvent{
.kind_byte = 4,
.len = 2,
},
});
try testMetaEvent("\x05\x00" ++
"\x05\x02", &[_]midi.file.MetaEvent{
midi.file.MetaEvent{
.kind_byte = 5,
.len = 0,
},
midi.file.MetaEvent{
.kind_byte = 5,
.len = 2,
},
});
try testMetaEvent("\x06\x00" ++
"\x06\x02", &[_]midi.file.MetaEvent{
midi.file.MetaEvent{
.kind_byte = 6,
.len = 0,
},
midi.file.MetaEvent{
.kind_byte = 6,
.len = 2,
},
});
try testMetaEvent("\x20\x00" ++
"\x20\x02", &[_]midi.file.MetaEvent{
midi.file.MetaEvent{
.kind_byte = 0x20,
.len = 0,
},
midi.file.MetaEvent{
.kind_byte = 0x20,
.len = 2,
},
});
try testMetaEvent("\x2F\x00" ++
"\x2F\x02", &[_]midi.file.MetaEvent{
midi.file.MetaEvent{
.kind_byte = 0x2F,
.len = 0,
},
midi.file.MetaEvent{
.kind_byte = 0x2F,
.len = 2,
},
});
try testMetaEvent("\x51\x00" ++
"\x51\x02", &[_]midi.file.MetaEvent{
midi.file.MetaEvent{
.kind_byte = 0x51,
.len = 0,
},
midi.file.MetaEvent{
.kind_byte = 0x51,
.len = 2,
},
});
try testMetaEvent("\x54\x00" ++
"\x54\x02", &[_]midi.file.MetaEvent{
midi.file.MetaEvent{
.kind_byte = 0x54,
.len = 0,
},
midi.file.MetaEvent{
.kind_byte = 0x54,
.len = 2,
},
});
try testMetaEvent("\x58\x00" ++
"\x58\x02", &[_]midi.file.MetaEvent{
midi.file.MetaEvent{
.kind_byte = 0x58,
.len = 0,
},
midi.file.MetaEvent{
.kind_byte = 0x58,
.len = 2,
},
});
try testMetaEvent("\x59\x00" ++
"\x59\x02", &[_]midi.file.MetaEvent{
midi.file.MetaEvent{
.kind_byte = 0x59,
.len = 0,
},
midi.file.MetaEvent{
.kind_byte = 0x59,
.len = 2,
},
});
try testMetaEvent("\x7F\x00" ++
"\x7F\x02", &[_]midi.file.MetaEvent{
midi.file.MetaEvent{
.kind_byte = 0x7F,
.len = 0,
},
midi.file.MetaEvent{
.kind_byte = 0x7F,
.len = 2,
},
});
}
test "midi.decode/encode.trackEvent" {
try testTrackEvent("\x00\xFF\x00\x00" ++
"\x00\xFF\x00\x02", &[_]midi.file.TrackEvent{
midi.file.TrackEvent{
.delta_time = 0,
.kind = midi.file.TrackEvent.Kind{
.MetaEvent = midi.file.MetaEvent{
.kind_byte = 0,
.len = 0,
},
},
},
midi.file.TrackEvent{
.delta_time = 0,
.kind = midi.file.TrackEvent.Kind{
.MetaEvent = midi.file.MetaEvent{
.kind_byte = 0,
.len = 2,
},
},
},
});
try testTrackEvent("\x00\x80\x00\x00" ++
"\x00\x7F\x7F" ++
"\x00\xFF\x00\x02", &[_]midi.file.TrackEvent{
midi.file.TrackEvent{
.delta_time = 0,
.kind = midi.file.TrackEvent.Kind{
.MidiEvent = midi.Message{
.status = 0x00,
.values = [2]u7{ 0x0, 0x0 },
},
},
},
midi.file.TrackEvent{
.delta_time = 0,
.kind = midi.file.TrackEvent.Kind{
.MidiEvent = midi.Message{
.status = 0x00,
.values = [2]u7{ 0x7F, 0x7F },
},
},
},
midi.file.TrackEvent{
.delta_time = 0,
.kind = midi.file.TrackEvent.Kind{
.MetaEvent = midi.file.MetaEvent{
.kind_byte = 0,
.len = 2,
},
},
},
});
}
test "midi.decode/encode.file" {
try testFile(
// File header
"MThd\x00\x00\x00\x08\x00\x02\x00\x02\xFF\x10\xFF\xFF" ++
// Random chunk
"abcd\x00\x00\x00\x04\xFF\xFF\xFF\xFF" ++
// Track
"MTrk\x00\x00\x00\x17" ++
"\x00\xFF\x00\x00" ++
"\x00\xFF\x00\x02\xaa\xbb" ++
"\x00\x80\x00\x00" ++
"\x00\x7F\x7F" ++
"\x00\xFF\x00\x02\xaa\xbb",
);
}
fn testFile(bytes: []const u8) !void {
var out_buf: [1024]u8 = undefined;
var fb_writer = io.fixedBufferStream(&out_buf);
const writer = fb_writer.writer();
const reader = io.fixedBufferStream(bytes).reader();
const allocator = testing.allocator;
const actual = try decode.file(reader, allocator);
defer actual.deinit(allocator);
try encode.file(writer, actual);
try testing.expectError(error.EndOfStream, reader.readByte());
try testing.expectEqualSlices(u8, bytes, fb_writer.getWritten());
}
fn testMessage(bytes: []const u8, results: []const midi.Message) !void {
var last: ?midi.Message = null;
var out_buf: [1024]u8 = undefined;
var fb_writer = io.fixedBufferStream(&out_buf);
const writer = fb_writer.writer();
const reader = io.fixedBufferStream(bytes).reader();
for (results) |expected| {
const actual = try decode.message(reader, last);
try encode.message(writer, last, actual);
try testing.expectEqual(expected, actual);
last = actual;
}
try testing.expectError(error.EndOfStream, reader.readByte());
try testing.expectEqualSlices(u8, bytes, fb_writer.getWritten());
}
fn testInt(bytes: []const u8, results: []const u28) !void {
var out_buf: [1024]u8 = undefined;
var fb_reader = io.fixedBufferStream(bytes);
const reader = fb_reader.reader();
for (results) |expected| {
var fb_writer = io.fixedBufferStream(&out_buf);
const writer = fb_writer.writer();
const before = fb_reader.pos;
const actual = try decode.int(reader);
const after = fb_reader.pos;
try encode.int(writer, actual);
try testing.expectEqual(expected, actual);
try testing.expectEqualSlices(u8, bytes[before..after], fb_writer.getWritten());
}
try testing.expectError(error.EndOfStream, reader.readByte());
}
fn testMetaEvent(bytes: []const u8, results: []const midi.file.MetaEvent) !void {
var out_buf: [1024]u8 = undefined;
var fb_writer = io.fixedBufferStream(&out_buf);
const writer = fb_writer.writer();
const reader = io.fixedBufferStream(bytes).reader();
for (results) |expected| {
const actual = try decode.metaEvent(reader);
try encode.metaEvent(writer, actual);
try testing.expectEqual(expected, actual);
}
try testing.expectError(error.EndOfStream, reader.readByte());
try testing.expectEqualSlices(u8, bytes, fb_writer.getWritten());
}
fn testTrackEvent(bytes: []const u8, results: []const midi.file.TrackEvent) !void {
var last: ?midi.file.TrackEvent = null;
var out_buf: [1024]u8 = undefined;
var fb_writer = io.fixedBufferStream(&out_buf);
const writer = fb_writer.writer();
const reader = io.fixedBufferStream(bytes).reader();
for (results) |expected| {
const actual = try decode.trackEvent(reader, last);
try encode.trackEvent(writer, last, actual);
try testing.expectEqual(expected.delta_time, actual.delta_time);
switch (expected.kind) {
.MetaEvent => try testing.expectEqual(expected.kind.MetaEvent, actual.kind.MetaEvent),
.MidiEvent => try testing.expectEqual(expected.kind.MidiEvent, actual.kind.MidiEvent),
}
last = actual;
}
try testing.expectError(error.EndOfStream, reader.readByte());
try testing.expectEqualSlices(u8, bytes, fb_writer.getWritten());
}
fn testChunk(bytes: [8]u8, chunk: midi.file.Chunk) !void {
const decoded = decode.chunkFromBytes(bytes);
const encoded = encode.chunkToBytes(chunk);
try testing.expectEqual(bytes, encoded);
try testing.expectEqual(chunk, decoded);
}
fn testFileHeader(bytes: [14]u8, header: midi.file.Header) !void {
const decoded = try decode.fileHeaderFromBytes(bytes);
const encoded = encode.fileHeaderToBytes(header);
try testing.expectEqual(bytes, encoded);
try testing.expectEqual(header, decoded);
} | midi/test.zig |
const std = @import("std");
const dcommon = @import("common/dcommon.zig");
const uefi = std.os.uefi;
const build_options = @import("build_options");
const dtblib = @import("dtb");
const ddtb = @import("common/ddtb.zig");
const arch = @import("arch.zig");
usingnamespace @import("util.zig");
var boot_services: *uefi.tables.BootServices = undefined;
pub fn panic(msg: []const u8, error_return_trace: ?*std.builtin.StackTrace) noreturn {
printf("panic: {s}\r\n", .{msg});
arch.halt();
}
pub fn main() void {
con_out = uefi.system_table.con_out.?;
boot_services = uefi.system_table.boot_services.?;
printf("daintree bootloader {s} on {s}\r\n", .{ build_options.version, build_options.board });
var load_context = LoadContext{};
var options_buffer: [256]u8 = [_]u8{undefined} ** 256;
if (getLoadOptions(&options_buffer)) |options| {
printf("load options: \"{s}\"\r\n", .{options});
load_context.handleOptions(options);
}
if (load_context.dtb == null) {
load_context.searchEfiFdt();
}
if (load_context.dtb == null or load_context.dainkrnl == null) {
load_context.searchFileSystems();
}
const dtb = load_context.dtb orelse {
printf("\r\nDTB not found\r\n", .{});
_ = boot_services.stall(5 * 1000 * 1000);
return;
};
const dainkrnl = load_context.dainkrnl orelse {
printf("\r\nDAINKRNL not found\r\n", .{});
_ = boot_services.stall(5 * 1000 * 1000);
return;
};
exitBootServices(dainkrnl, dtb);
}
const LoadContext = struct {
const Self = @This();
dtb: ?[]const u8 = null,
dainkrnl: ?[]const u8 = null,
fn handleOptions(self: *Self, options: []const u8) void {
var it = std.mem.tokenize(options, " ");
loop: while (it.next()) |opt_name| {
if (std.mem.eql(u8, opt_name, "dtb")) {
const loc = handleOptionsLoc("dtb", &it) orelse continue :loop;
printf("using dtb in ramdisk at 0x{x:0>16} ({} bytes)\r\n", .{ loc.offset, loc.len });
self.dtb = @intToPtr([*]u8, loc.offset)[0..loc.len];
} else if (std.mem.eql(u8, opt_name, "kernel")) {
const loc = handleOptionsLoc("kernel", &it) orelse continue :loop;
printf("using kernel in ramdisk at 0x{x:0>16} ({} bytes)\r\n", .{ loc.offset, loc.len });
self.dainkrnl = @intToPtr([*]u8, loc.offset)[0..loc.len];
} else {
printf("unknown option '{s}'\r\n", .{opt_name});
}
}
}
var fdt_table_guid align(8) = std.os.uefi.Guid{
.time_low = 0xb1b621d5,
.time_mid = 0xf19c,
.time_high_and_version = 0x41a5,
.clock_seq_high_and_reserved = 0x83,
.clock_seq_low = 0x0b,
.node = [_]u8{ 0xd9, 0x15, 0x2c, 0x69, 0xaa, 0xe0 },
};
fn searchEfiFdt(self: *Self) void {
for (uefi.system_table.configuration_table[0..uefi.system_table.number_of_table_entries]) |table| {
if (table.vendor_guid.eql(fdt_table_guid)) {
if (dtblib.totalSize(table.vendor_table)) |size| {
printf("found FDT in UEFI\n", .{});
self.dtb = @ptrCast([*]const u8, table.vendor_table)[0..size];
return;
} else |err| {}
}
}
}
fn searchFileSystems(self: *Self) void {
var handle_list_size: usize = 0;
var handle_list: [*]uefi.Handle = undefined;
while (boot_services.locateHandle(
.ByProtocol,
&uefi.protocols.SimpleFileSystemProtocol.guid,
null,
&handle_list_size,
handle_list,
) == .BufferTooSmall) {
check("allocatePool", boot_services.allocatePool(
uefi.tables.MemoryType.BootServicesData,
handle_list_size,
@ptrCast(*[*]align(8) u8, &handle_list),
));
}
if (handle_list_size == 0) {
printf("no simple file system protocols found\r\n", .{});
return;
}
const handle_count = handle_list_size / @sizeOf(uefi.Handle);
printf("searching for <", .{});
if (self.dtb == null) {
printf("DTB", .{});
if (self.dainkrnl == null) printf(" ", .{});
}
if (self.dainkrnl == null) printf("DAINKRNL.{s}", .{@tagName(dcommon.daintree_arch)});
printf("> on {} volume(s) ", .{handle_count});
for (handle_list[0..handle_count]) |handle| {
var sfs_proto: ?*uefi.protocols.SimpleFileSystemProtocol = undefined;
check("openProtocol", boot_services.openProtocol(
handle,
&uefi.protocols.SimpleFileSystemProtocol.guid,
@ptrCast(*?*c_void, &sfs_proto),
uefi.handle,
null,
.{ .get_protocol = true },
));
printf(".", .{});
var f_proto: *uefi.protocols.FileProtocol = undefined;
check("openVolume", sfs_proto.?.openVolume(&f_proto));
if (self.dainkrnl == null) {
self.dainkrnl = tryLoadFromFileProtocol(f_proto, "dainkrnl." ++ @tagName(dcommon.daintree_arch));
}
if (self.dtb == null) {
self.dtb = tryLoadFromFileProtocol(f_proto, "dtb");
}
_ = boot_services.closeProtocol(handle, &uefi.protocols.SimpleFileSystemProtocol.guid, uefi.handle, null);
if (self.dainkrnl != null and self.dtb != null) {
break;
}
}
}
// ---
const Loc = struct {
offset: u64,
len: u64,
};
fn handleOptionsLoc(comptime opt_name: []const u8, it: *std.mem.TokenIterator) ?Loc {
const offset_s = it.next() orelse {
printf(opt_name ++ ": missing offset argument\r\n", .{});
return null;
};
const len_s = it.next() orelse {
printf(opt_name ++ ": missing length argument\r\n", .{});
return null;
};
const offset = std.fmt.parseInt(u64, offset_s, 0) catch |err| {
printf(opt_name ++ ": parse offset '{s}' error: {}\r\n", .{ offset_s, err });
return null;
};
const len = std.fmt.parseInt(u64, len_s, 0) catch |err| {
printf(opt_name ++ ": parse len '{s}' error: {}\r\n", .{ len_s, err });
return null;
};
return Loc{ .offset = offset, .len = len };
}
};
fn getLoadOptions(buffer: *[256]u8) ?[]const u8 {
var li_proto: ?*uefi.protocols.LoadedImageProtocol = undefined;
if (boot_services.openProtocol(
uefi.handle,
&uefi.protocols.LoadedImageProtocol.guid,
@ptrCast(*?*c_void, &li_proto),
uefi.handle,
null,
.{ .get_protocol = true },
) != .Success) {
return null;
}
const options_size = li_proto.?.load_options_size;
if (options_size == 0) {
return null;
}
var ptr: [*]u16 = @ptrCast([*]u16, @alignCast(@alignOf([*]u16), li_proto.?.load_options.?));
if (std.unicode.utf16leToUtf8(buffer[0..], ptr[0 .. options_size / 2])) |sz| {
var options = buffer[0..sz];
if (options.len > 0 and options[options.len - 1] == 0) {
options = options[0 .. options.len - 1];
}
return options;
} else |err| {
printf("failed utf16leToUtf8: {}\r\n", .{err});
return null;
}
}
fn tryLoadFromFileProtocol(f_proto: *uefi.protocols.FileProtocol, comptime file_name: []const u8) ?[]const u8 {
var proto: *uefi.protocols.FileProtocol = undefined;
var size: u64 = undefined;
var mem: [*]u8 = undefined;
const file_name_u16: [:0]const u16 = comptime blk: {
var n: [:0]const u16 = &[_:0]u16{};
for (file_name) |c| {
n = n ++ [_]u16{c};
}
break :blk n;
};
if (f_proto.open(&proto, file_name_u16, uefi.protocols.FileProtocol.efi_file_mode_read, 0) != .Success) {
return null;
}
check("setPosition", proto.setPosition(uefi.protocols.FileProtocol.efi_file_position_end_of_file));
check("getPosition", proto.getPosition(&size));
printf(" \"{s}\" {} bytes ", .{ file_name, size });
check("setPosition", proto.setPosition(0));
check("allocatePool", boot_services.allocatePool(
.BootServicesData,
size,
@ptrCast(*[*]align(8) u8, &mem),
));
check("read", proto.read(&size, mem));
return mem[0..size];
}
fn parseElf(bytes: []const u8) std.elf.Header {
if (bytes.len < @sizeOf(std.elf.Elf64_Ehdr)) {
printf("found {} byte(s), too small for ELF header ({} bytes)\r\n", .{ bytes.len, @sizeOf(std.elf.Elf64_Ehdr) });
arch.halt();
}
var buffer = std.io.fixedBufferStream(bytes);
var elf_header = std.elf.Header.read(&buffer) catch |err| {
printf("failed to parse ELF: {}\r\n", .{err});
arch.halt();
};
const bits: u8 = if (elf_header.is_64) 64 else 32;
const endian_ch = if (elf_header.endian == .Big) @as(u8, 'B') else @as(u8, 'L');
printf("ELF entrypoint: {x:0>16} ({}-bit {c}E {s})\r\n", .{
elf_header.entry,
bits,
endian_ch,
// depends on https://github.com/ziglang/zig/pull/8193
if (comptime @hasField(@TypeOf(elf_header), "machine"))
@tagName(elf_header.machine)
else
"",
});
var it = elf_header.program_header_iterator(&buffer);
while (it.next() catch haltMsg("iterating phdr")) |phdr| {
printf(" * type={x:0>8} off={x:0>16} vad={x:0>16} pad={x:0>16} fsz={x:0>16} msz={x:0>16}\r\n", .{ phdr.p_type, phdr.p_offset, phdr.p_vaddr, phdr.p_paddr, phdr.p_filesz, phdr.p_memsz });
}
return elf_header;
}
fn exitBootServices(dainkrnl: []const u8, dtb: []const u8) noreturn {
const dainkrnl_elf = parseElf(dainkrnl);
var elf_source = std.io.fixedBufferStream(dainkrnl);
var kernel_size: u64 = 0;
{
var it = dainkrnl_elf.program_header_iterator(&elf_source);
while (it.next() catch haltMsg("iterating phdrs (2)")) |phdr| {
if (phdr.p_type == std.elf.PT_LOAD) {
const target = phdr.p_vaddr - dcommon.daintree_kernel_start;
const load_bytes = std.math.min(phdr.p_filesz, phdr.p_memsz);
printf("will load 0x{x:0>16} bytes at 0x{x:0>16} into offset+0x{x:0>16}\r\n", .{ load_bytes, phdr.p_vaddr, target });
if (phdr.p_memsz > phdr.p_filesz) {
printf(" and zeroing {} bytes at end\r\n", .{phdr.p_memsz - phdr.p_filesz});
}
kernel_size = std.math.max(kernel_size, target + phdr.p_memsz);
}
}
}
var fb: ?[*]u32 = null;
var fb_vert: u32 = 0;
var fb_horiz: u32 = 0;
{
var graphics: *uefi.protocols.GraphicsOutputProtocol = undefined;
const result = boot_services.locateProtocol(&uefi.protocols.GraphicsOutputProtocol.guid, null, @ptrCast(*?*c_void, &graphics));
if (result == .Success) {
fb = @intToPtr([*]u32, graphics.mode.frame_buffer_base);
fb_vert = graphics.mode.info.vertical_resolution;
fb_horiz = graphics.mode.info.horizontal_resolution;
printf("{}x{} framebuffer located at {*}\n", .{ fb_horiz, fb_vert, fb });
} else {
printf("no framebuffer found: {}\n", .{result});
}
}
var dtb_scratch_ptr: [*]u8 = undefined;
check("allocatePool", boot_services.allocatePool(uefi.tables.MemoryType.BootServicesData, 128 * 1024, @ptrCast(*[*]align(8) u8, &dtb_scratch_ptr)));
var dtb_scratch = dtb_scratch_ptr[0 .. 128 * 1024];
printf("looking up serial base in DTB ... ", .{});
var uart_base: u64 = 0;
var uart_width: u3 = 0;
if (ddtb.searchForUart(dtb)) |uart| {
uart_base = uart.base;
uart_width = switch (uart.kind) {
// You **must** do long-sized reads/writes on sifive,uart0, or at least,
// you do on QEMU's implementation of it.
.SifiveUart0 => 4,
else => 1,
};
} else |err| {
printf("failed to parse dtb: {}", .{err});
}
printf("0x{x:0>8}~{}\r\n", .{ uart_base, uart_width });
printf("we will clean d/i$ for 0x{x} bytes\r\n", .{kernel_size});
printf("going quiet before obtaining memory map\r\n", .{});
// *****************************************************************
// * Minimise logging between here and boot services exit. *
// * Otherwise the chance a console log will cause our firmware to *
// * allocate memory and invalidate the memory map will increase. *
// *****************************************************************
var memory_map: [*]uefi.tables.MemoryDescriptor = undefined;
var memory_map_size: usize = 0;
var memory_map_key: usize = undefined;
var descriptor_size: usize = undefined;
var descriptor_version: u32 = undefined;
while (boot_services.getMemoryMap(
&memory_map_size,
memory_map,
&memory_map_key,
&descriptor_size,
&descriptor_version,
) == .BufferTooSmall) {
check("allocatePool", boot_services.allocatePool(
uefi.tables.MemoryType.BootServicesData,
memory_map_size,
@ptrCast(*[*]align(8) u8, &memory_map),
));
}
var largest_conventional: ?*uefi.tables.MemoryDescriptor = null;
{
var offset: usize = 0;
var i: usize = 0;
while (offset < memory_map_size) : ({
offset += descriptor_size;
i += 1;
}) {
const ptr = @intToPtr(*uefi.tables.MemoryDescriptor, @ptrToInt(memory_map) + offset);
if (ptr.type == .ConventionalMemory) {
if (largest_conventional) |current_largest| {
if (ptr.number_of_pages > current_largest.number_of_pages) {
largest_conventional = ptr;
}
} else {
largest_conventional = ptr;
}
}
}
}
// Just take the single biggest bit of conventional memory.
const conventional_start = largest_conventional.?.physical_start;
const conventional_bytes = largest_conventional.?.number_of_pages << 12;
// The kernel's text section begins at dcommon.daintree_kernel_start. Adjust those down
// to conventional_start now.
var it = dainkrnl_elf.program_header_iterator(&elf_source);
while (it.next() catch haltMsg("iterating phdrs (2)")) |phdr| {
if (phdr.p_type == std.elf.PT_LOAD) {
const target = phdr.p_vaddr - dcommon.daintree_kernel_start + conventional_start;
std.mem.copy(u8, @intToPtr([*]u8, target)[0..phdr.p_filesz], dainkrnl[phdr.p_offset .. phdr.p_offset + phdr.p_filesz]);
if (phdr.p_memsz > phdr.p_filesz) {
std.mem.set(u8, @intToPtr([*]u8, target)[phdr.p_filesz..phdr.p_memsz], 0);
}
}
}
entry_data = .{
.memory_map = memory_map,
.memory_map_size = memory_map_size,
.descriptor_size = descriptor_size,
.dtb_ptr = dtb.ptr,
.dtb_len = dtb.len,
.conventional_start = conventional_start,
.conventional_bytes = conventional_bytes,
.fb = fb,
.fb_vert = fb_vert,
.fb_horiz = fb_horiz,
.uart_base = uart_base,
.uart_width = uart_width,
};
arch.cleanInvalidateDCacheICache(@ptrToInt(&entry_data), @sizeOf(@TypeOf(entry_data)));
// I'd love to change this back to "..., kernel_size);" at some point.
arch.cleanInvalidateDCacheICache(conventional_start, conventional_bytes);
printf("{x} {x} ", .{ conventional_start, @ptrToInt(&entry_data) });
const adjusted_entry = dainkrnl_elf.entry - dcommon.daintree_kernel_start + conventional_start;
check("exitBootServices", boot_services.exitBootServices(uefi.handle, memory_map_key));
if (fb) |base| {
var x: usize = 0;
while (x < 16) : (x += 1) {
var y: usize = 0;
while (y < 16) : (y += 1) {
base[y * fb_horiz + x] = 0x0000ff00;
}
}
}
arch.transfer(&entry_data, uart_base, adjusted_entry);
}
var entry_data: dcommon.EntryData align(16) = undefined; | dainboot/src/dainboot.zig |
const std = @import("std");
const Builder = std.build.Builder;
const LibExeObjStep = std.build.LibExeObjStep;
const CrossTarget = std.zig.CrossTarget;
const Mode = std.builtin.Mode;
const builtin = @import("builtin");
pub fn build(b: *Builder) void {
const exe = b.addExecutable("pacman", "src/pacman.zig");
const target = b.standardTargetOptions(.{});
const mode = b.standardReleaseOptions();
const cross_compiling = (target.os_tag != null) or !builtin.target.isDarwin();
exe.setTarget(target);
exe.setBuildMode(mode);
exe.linkLibrary(buildSokol(b, target, mode, cross_compiling, ""));
exe.addPackagePath("sokol", "src/sokol/sokol.zig");
if (cross_compiling) {
exe.addLibPath("/usr/lib");
exe.addFrameworkDir("/System/Library/Frameworks");
}
exe.install();
b.step("run", "Run pacman").dependOn(&exe.run().step);
if (target.getOsTag() == .ios) {
const install_path = std.fmt.allocPrint(b.allocator, "{s}/bin/pacman", .{b.install_path}) catch unreachable;
defer b.allocator.free(install_path);
b.installFile(install_path, "bin/Pacman.app/pacman");
b.installFile("src/ios/Info.plist", "bin/Pacman.app/Info.plist");
}
}
fn buildSokol(b: *Builder, target: CrossTarget, mode: Mode, cross_compiling: bool, comptime prefix_path: []const u8) *LibExeObjStep {
const lib = b.addStaticLibrary("sokol", null);
lib.setTarget(target);
lib.setBuildMode(mode);
lib.linkLibC();
const sokol_path = prefix_path ++ "src/sokol/sokol.c";
if (lib.target.isDarwin()) {
lib.addCSourceFile(sokol_path, &.{ "-ObjC" });
lib.linkFramework("MetalKit");
lib.linkFramework("Metal");
lib.linkFramework("AudioToolbox");
if (target.getOsTag() == .ios) {
lib.linkFramework("UIKit");
lib.linkFramework("AVFoundation");
lib.linkFramework("Foundation");
}
else {
lib.linkFramework("Cocoa");
lib.linkFramework("QuartzCore");
}
}
else {
lib.addCSourceFile(sokol_path, &.{});
if (lib.target.isLinux()) {
lib.linkSystemLibrary("X11");
lib.linkSystemLibrary("Xi");
lib.linkSystemLibrary("Xcursor");
lib.linkSystemLibrary("GL");
lib.linkSystemLibrary("asound");
}
else if (lib.target.isWindows()) {
lib.linkSystemLibrary("kernel32");
lib.linkSystemLibrary("user32");
lib.linkSystemLibrary("gdi32");
lib.linkSystemLibrary("ole32");
lib.linkSystemLibrary("d3d11");
lib.linkSystemLibrary("dxgi");
}
}
// setup cross-compilation search paths
if (cross_compiling) {
if (b.sysroot == null) {
std.log.warn("===================================================================================", .{});
std.log.warn("You haven't set the path to Apple SDK which may lead to build errors.", .{});
std.log.warn("Hint: you can the path to Apple SDK with --sysroot <path> flag like so:", .{});
std.log.warn(" zig build --sysroot $(xcrun --sdk iphoneos --show-sdk-path) -Dtarget=aarch64-ios", .{});
std.log.warn("or:", .{});
std.log.warn(" zig build --sysroot $(xcrun --sdk iphonesimulator --show-sdk-path) -Dtarget=aarch64-ios-simulator", .{});
std.log.warn("===================================================================================", .{});
}
lib.addFrameworkDir("/System/Library/Frameworks");
lib.addSystemIncludeDir("/usr/include");
}
return lib;
} | build.zig |
const std = @import("std");
const types = @import("./types.zig");
/// Only check for the field's existence.
const Exists = struct {
exists: bool,
};
fn Default(comptime T: type, comptime default_value: T) type {
return struct {
pub const value_type = T;
pub const default = default_value;
value: T,
};
}
pub fn ErrorUnwrappedReturnOf(comptime func: anytype) type {
return switch (@typeInfo(@TypeOf(func))) {
.Fn, .BoundFn => |fn_info| switch (@typeInfo(fn_info.return_type.?)) {
.ErrorUnion => |err_union| err_union.payload,
else => |T| return T,
},
else => unreachable,
};
}
fn Transform(comptime Original: type, comptime transform_fn: anytype) type {
return struct {
pub const original_type = Original;
pub const transform = transform_fn;
value: ErrorUnwrappedReturnOf(transform_fn),
};
}
fn fromDynamicTreeInternal(arena: *std.heap.ArenaAllocator, value: std.json.Value, out: anytype) error{ MalformedJson, OutOfMemory }!void {
const T = comptime std.meta.Child(@TypeOf(out));
if (comptime std.meta.trait.is(.Struct)(T)) {
if (value != .Object) return error.MalformedJson;
var err = false;
inline for (std.meta.fields(T)) |field| {
const is_exists = field.field_type == Exists;
const is_optional = comptime std.meta.trait.is(.Optional)(field.field_type);
const actual_type = if (is_optional) std.meta.Child(field.field_type) else field.field_type;
const is_struct = comptime std.meta.trait.is(.Struct)(actual_type);
const is_default = comptime if (is_struct) std.meta.trait.hasDecls(actual_type, .{ "default", "value_type" }) else false;
const is_transform = comptime if (is_struct) std.meta.trait.hasDecls(actual_type, .{ "original_type", "transform" }) else false;
if (value.Object.get(field.name)) |json_field| {
if (is_exists) {
@field(out, field.name) = Exists{ .exists = true };
} else if (is_transform) {
var original_value: actual_type.original_type = undefined;
try fromDynamicTreeInternal(arena, json_field, &original_value);
@field(out, field.name) = actual_type{
.value = actual_type.transform(original_value) catch
return error.MalformedJson,
};
} else if (is_default) {
try fromDynamicTreeInternal(arena, json_field, &@field(out, field.name).value);
} else if (is_optional) {
if (json_field == .Null) {
@field(out, field.name) = null;
} else {
var actual_value: actual_type = undefined;
try fromDynamicTreeInternal(arena, json_field, &actual_value);
@field(out, field.name) = actual_value;
}
} else {
try fromDynamicTreeInternal(arena, json_field, &@field(out, field.name));
}
} else {
if (is_exists) {
@field(out, field.name) = Exists{ .exists = false };
} else if (is_optional) {
@field(out, field.name) = null;
} else if (is_default) {
@field(out, field.name) = actual_type{ .value = actual_type.default };
} else {
err = true;
}
}
}
if (err) return error.MalformedJson;
} else if (comptime (std.meta.trait.isSlice(T) and T != []const u8)) {
if (value != .Array) return error.MalformedJson;
const Child = std.meta.Child(T);
if (value.Array.items.len == 0) {
out.* = &[0]Child{};
} else {
var slice = try arena.allocator().alloc(Child, value.Array.items.len);
for (value.Array.items) |arr_item, idx| {
try fromDynamicTreeInternal(arena, arr_item, &slice[idx]);
}
out.* = slice;
}
} else if (T == std.json.Value) {
out.* = value;
} else if (comptime std.meta.trait.is(.Enum)(T)) {
const info = @typeInfo(T).Enum;
if (info.layout != .Auto)
@compileError("Only auto layout enums are allowed");
const TagType = info.tag_type;
if (value != .Integer) return error.MalformedJson;
out.* = std.meta.intToEnum(
T,
std.math.cast(TagType, value.Integer) orelse return error.MalformedJson,
) catch return error.MalformedJson;
} else if (comptime std.meta.trait.is(.Int)(T)) {
if (value != .Integer) return error.MalformedJson;
out.* = std.math.cast(T, value.Integer) orelse return error.MalformedJson;
} else switch (T) {
bool => {
if (value != .Bool) return error.MalformedJson;
out.* = value.Bool;
},
f64 => {
if (value != .Float) return error.MalformedJson;
out.* = value.Float;
},
[]const u8 => {
if (value != .String) return error.MalformedJson;
out.* = value.String;
},
else => @compileError("Invalid type " ++ @typeName(T)),
}
}
pub fn fromDynamicTree(arena: *std.heap.ArenaAllocator, comptime T: type, value: std.json.Value) error{ MalformedJson, OutOfMemory }!T {
var out: T = undefined;
try fromDynamicTreeInternal(arena, value, &out);
return out;
}
const MaybeStringArray = Default([]const []const u8, &.{});
pub const Initialize = struct {
pub const ClientCapabilities = struct {
workspace: ?struct {
configuration: Default(bool, false),
workspaceFolders: Default(bool, false),
},
textDocument: ?struct {
semanticTokens: Exists,
hover: ?struct {
contentFormat: MaybeStringArray,
},
completion: ?struct {
completionItem: ?struct {
snippetSupport: Default(bool, false),
documentationFormat: MaybeStringArray,
},
},
},
offsetEncoding: MaybeStringArray,
};
params: struct {
capabilities: ClientCapabilities,
workspaceFolders: ?[]const types.WorkspaceFolder,
},
};
pub const WorkspaceFoldersChange = struct {
params: struct {
event: struct {
added: []const types.WorkspaceFolder,
removed: []const types.WorkspaceFolder,
},
},
};
pub const OpenDocument = struct {
params: struct {
textDocument: struct {
uri: []const u8,
text: []const u8,
},
},
};
const TextDocumentIdentifier = struct {
uri: []const u8,
};
pub const ChangeDocument = struct {
params: struct {
textDocument: TextDocumentIdentifier,
contentChanges: std.json.Value,
},
};
const TextDocumentIdentifierRequest = struct {
params: struct {
textDocument: TextDocumentIdentifier,
},
};
pub const SaveDocument = TextDocumentIdentifierRequest;
pub const CloseDocument = TextDocumentIdentifierRequest;
pub const SemanticTokensFull = TextDocumentIdentifierRequest;
const TextDocumentIdentifierPositionRequest = struct {
params: struct {
textDocument: TextDocumentIdentifier,
position: types.Position,
},
};
pub const SignatureHelp = struct {
params: struct {
textDocument: TextDocumentIdentifier,
position: types.Position,
context: ?struct {
triggerKind: enum(u32) {
invoked = 1,
trigger_character = 2,
content_change = 3,
},
triggerCharacter: ?[]const u8,
isRetrigger: bool,
activeSignatureHelp: ?types.SignatureHelp,
},
},
};
pub const Completion = TextDocumentIdentifierPositionRequest;
pub const GotoDefinition = TextDocumentIdentifierPositionRequest;
pub const GotoDeclaration = TextDocumentIdentifierPositionRequest;
pub const Hover = TextDocumentIdentifierPositionRequest;
pub const DocumentSymbols = TextDocumentIdentifierRequest;
pub const Formatting = TextDocumentIdentifierRequest;
pub const Rename = struct {
params: struct {
textDocument: TextDocumentIdentifier,
position: types.Position,
newName: []const u8,
},
};
pub const References = struct {
params: struct {
textDocument: TextDocumentIdentifier,
position: types.Position,
context: struct {
includeDeclaration: bool,
},
},
};
pub const Configuration = struct {
params: struct {
settings: struct {
enable_snippets: ?bool,
zig_lib_path: ?[]const u8,
zig_exe_path: ?[]const u8,
warn_style: ?bool,
build_runner_path: ?[]const u8,
build_runner_cache_path: ?[]const u8,
enable_semantic_tokens: ?bool,
operator_completions: ?bool,
include_at_in_builtins: ?bool,
max_detail_length: ?usize,
skip_std_references: ?bool,
builtin_path: ?[]const u8,
},
},
}; | src/requests.zig |
const std = @import("std");
const aoc = @import("aoc-lib.zig");
const seglist = @import("segmented_list.zig");
const Matcher = struct {
const Rule = union(enum) {
str: []const u8,
opt: []const []const usize,
};
rules: std.AutoHashMap(usize, Rule),
values: [][]const u8,
alloc: std.mem.Allocator,
debug: bool,
pub fn init(alloc: std.mem.Allocator, in: [][]const u8) !*Matcher {
var rs = std.mem.split(u8, in[0], "\n");
var r = std.AutoHashMap(usize, Rule).init(alloc);
while (rs.next()) |l| {
var ls = std.mem.split(u8, l, ": ");
const n = try std.fmt.parseUnsigned(usize, ls.next().?, 10);
const def = ls.next().?;
if (def[0] == '"') {
//std.debug.print("CH rule {}\n", .{def[1..2]});
try r.put(n, Rule{ .str = def[1..2] });
} else {
//std.debug.print("OR rule {}\n", .{def});
var os = std.mem.split(u8, def, " | ");
var opt = std.ArrayList([]usize).init(aoc.halloc); // use alloc
defer opt.deinit();
while (os.next()) |o| {
var ovs = std.mem.split(u8, o, " ");
var ov = std.ArrayList(usize).init(aoc.halloc); // use alloc
defer ov.deinit();
while (ovs.next()) |vs| {
const v = try std.fmt.parseUnsigned(usize, vs, 10);
try ov.append(v);
}
try opt.append(ov.toOwnedSlice());
}
try r.put(n, Rule{ .opt = opt.toOwnedSlice() });
}
}
var vs = std.mem.split(u8, in[1], "\n");
var vl = std.ArrayList([]const u8).init(alloc);
defer vl.deinit();
while (vs.next()) |v| {
try vl.append(v);
}
var self = try alloc.create(Matcher);
self.alloc = alloc;
self.rules = r;
self.values = vl.toOwnedSlice();
return self;
}
pub fn deinit(self: *Matcher) void {
//var it = self.rules.iterator();
//while (it.next()) |r| {
// switch (r.value_ptr.*) {
// .opt => |*opt| {
// for (opt.*) |*e| {
// self.alloc.free(e.*);
// }
// },
// .str => {
// }
// }
//}
self.rules.deinit();
self.alloc.free(self.values);
self.alloc.destroy(self);
}
pub fn MatchAux(m: *Matcher, v: []const u8, i: usize, todo: *seglist.SegmentedList(usize, 32)) bool {
const rem_len = v.len - i;
if (todo.count() > rem_len) {
//std.debug.print("more todo but nothing left to match", .{});
return false;
} else if (todo.count() == 0 and rem_len == 0) {
//std.debug.print("nothing todo and nothing left to match!", .{});
return true;
} else if (todo.count() == 0 or rem_len == 0) {
//std.debug.print("run out of something", .{});
return false;
}
//std.debug.print("MA: {}[{}] = {c}\n", .{ v, i, v[i] });
const rn: usize = todo.pop().?;
const r = m.rules.get(rn) orelse unreachable;
switch (r) {
.str => |*str| {
//std.debug.print("checking string match {} at {} with {s}\n", .{ v, i, str.* });
if (v[i] != str.*[0]) {
//std.debug.print(" not matched\n", .{});
return false;
} else {
//std.debug.print(" matched\n", .{});
return m.MatchAux(v, i + 1, todo);
}
},
.opt => |*opt| {
for (opt.*) |rs| {
var todo_n = &seglist.SegmentedList(usize, 32).init(&m.alloc);
defer todo_n.deinit();
var k: usize = 0;
while (k < todo.count()) : (k += 1) {
todo_n.push(todo.at(k).*) catch unreachable;
}
k = rs.len;
while (k > 0) : (k -= 1) {
todo_n.push(rs[k - 1]) catch unreachable;
}
if (m.MatchAux(v, i, todo_n)) {
return true;
}
}
return false;
},
}
}
pub fn Match(m: *Matcher, v: []const u8) bool {
var todo = &seglist.SegmentedList(usize, 32).init(&m.alloc);
todo.push(0) catch unreachable;
const res = m.MatchAux(v, 0, todo);
return res;
}
pub fn Part1(m: *Matcher) usize {
var s: usize = 0;
for (m.values) |v| {
if (m.Match(v)) {
s += 1;
}
}
return s;
}
pub fn Part2(m: *Matcher) usize {
var a = [_]usize{42};
var b = [_]usize{ 42, 8 };
var c = [_][]usize{ a[0..], b[0..] };
m.rules.put(8, Rule{ .opt = c[0..] }) catch unreachable;
var d = [_]usize{ 42, 31 };
var e = [_]usize{ 42, 11, 31 };
var f = [_][]usize{ d[0..], e[0..] };
m.rules.put(11, Rule{ .opt = f[0..] }) catch unreachable;
return m.Part1();
}
};
test "examples" {
const test0 = aoc.readChunks(aoc.talloc, aoc.test0file);
defer aoc.talloc.free(test0);
const test1 = aoc.readChunks(aoc.talloc, aoc.test1file);
defer aoc.talloc.free(test1);
const test2 = aoc.readChunks(aoc.talloc, aoc.test2file);
defer aoc.talloc.free(test2);
const inp = aoc.readChunks(aoc.talloc, aoc.inputfile);
defer aoc.talloc.free(inp);
var m = try Matcher.init(aoc.talloc, test0);
try aoc.assertEq(@as(usize, 1), m.Part1());
m.deinit();
m = try Matcher.init(aoc.talloc, test1);
try aoc.assertEq(@as(usize, 1), m.Part1());
m.deinit();
m = try Matcher.init(aoc.talloc, test2);
try aoc.assertEq(@as(usize, 2), m.Part1());
m.deinit();
m = try Matcher.init(aoc.talloc, inp);
try aoc.assertEq(@as(usize, 285), m.Part1());
m.deinit();
m = try Matcher.init(aoc.talloc, inp);
defer m.deinit();
try aoc.assertEq(@as(usize, 412), m.Part2());
}
fn day19(inp: []const u8, bench: bool) anyerror!void {
const chunks = aoc.readChunks(aoc.halloc, inp);
defer aoc.halloc.free(chunks);
var m = try Matcher.init(aoc.halloc, chunks);
var p1 = m.Part1();
var p2 = m.Part2();
if (!bench) {
try aoc.print("Part 1: {}\nPart 2: {}\n", .{ p1, p2 });
}
}
pub fn main() anyerror!void {
try aoc.benchme(aoc.input(), day19);
} | 2020/19/aoc.zig |
const std = @import("std");
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
const expectEqualSlices = std.testing.expectEqualSlices;
// Import structs.
const Context = @import("Context.zig");
const GraphemeIterator = @import("ziglyph.zig").GraphemeIterator;
const Letter = @import("components/aggregate/Letter.zig");
const Punct = @import("components/aggregate/Punct.zig");
const Width = @import("components/aggregate/Width.zig");
const Ziglyph = @import("ziglyph.zig").Ziglyph;
test "Ziglyph struct" {
var ctx = Context.init(std.testing.allocator);
defer ctx.deinit();
var ziglyph = try Ziglyph.new(&ctx);
const z = 'z';
expect(try ziglyph.isLetter(z));
expect(try ziglyph.isAlphaNum(z));
expect(try ziglyph.isPrint(z));
expect(!try ziglyph.isUpper(z));
const uz = try ziglyph.toUpper(z);
expect(try ziglyph.isUpper(uz));
expectEqual(uz, 'Z');
}
test "Aggregate struct" {
var ctx = Context.init(std.testing.allocator);
defer ctx.deinit();
var letter = Letter.new(&ctx);
var punct = Punct.new(&ctx);
const z = 'z';
expect(try letter.isLetter(z));
expect(!try letter.isUpper(z));
expect(!try punct.isPunct(z));
expect(try punct.isPunct('!'));
const uz = try letter.toUpper(z);
expect(try letter.isUpper(uz));
expectEqual(uz, 'Z');
}
test "Component structs" {
var ctx = Context.init(std.testing.allocator);
defer ctx.deinit();
const lower = try ctx.getLower();
const upper = try ctx.getUpper();
const upper_map = try ctx.getUpperMap();
const z = 'z';
expect(lower.isLowercaseLetter(z));
expect(!upper.isUppercaseLetter(z));
const uz = upper_map.toUpper(z);
expect(upper.isUppercaseLetter(uz));
expectEqual(uz, 'Z');
}
test "decomposeTo" {
var allocator = std.testing.allocator;
var ctx = Context.init(allocator);
defer ctx.deinit();
const Decomposed = Context.DecomposeMap.Decomposed;
const decomp_map = try ctx.getDecomposeMap();
// CD: ox03D3 -> 0x03D2, 0x0301
var src = [1]Decomposed{.{ .src = '\u{03D3}' }};
var result = try decomp_map.decomposeTo(allocator, .D, &src);
defer allocator.free(result);
expectEqual(result.len, 2);
expectEqual(result[0].same, 0x03D2);
expectEqual(result[1].same, 0x0301);
allocator.free(result);
// KD: ox03D3 -> 0x03D2, 0x0301 -> 0x03A5, 0x0301
src = [1]Decomposed{.{ .src = '\u{03D3}' }};
result = try decomp_map.decomposeTo(allocator, .KD, &src);
expectEqual(result.len, 2);
expect(result[0] == .same);
expectEqual(result[0].same, 0x03A5);
expect(result[1] == .same);
expectEqual(result[1].same, 0x0301);
}
test "normalizeTo" {
var allocator = std.testing.allocator;
var ctx = Context.init(allocator);
defer ctx.deinit();
const decomp_map = try ctx.getDecomposeMap();
// Canonical (NFD)
var input = "Complex char: \u{03D3}";
var want = "Complex char: \u{03D2}\u{0301}";
var got = try decomp_map.normalizeTo(allocator, .D, input);
defer allocator.free(got);
expectEqualSlices(u8, want, got);
allocator.free(got);
// Compatibility (NFKD)
input = "Complex char: \u{03D3}";
want = "Complex char: \u{03A5}\u{0301}";
got = try decomp_map.normalizeTo(allocator, .KD, input);
expectEqualSlices(u8, want, got);
}
test "GraphemeIterator" {
var ctx = Context.init(std.testing.allocator);
defer ctx.deinit();
var iter = try GraphemeIterator.new(&ctx, "H\u{0065}\u{0301}llo");
const want = &[_][]const u8{ "H", "\u{0065}\u{0301}", "l", "l", "o" };
var i: usize = 0;
while (try iter.next()) |gc| : (i += 1) {
expect(gc.eql(want[i]));
}
}
test "Code point / string widths" {
var ctx = Context.init(std.testing.allocator);
defer ctx.deinit();
var width = try Width.new(&ctx);
expectEqual(try width.codePointWidth('é', .half), 1);
expectEqual(try width.codePointWidth('😊', .half), 2);
expectEqual(try width.codePointWidth('统', .half), 2);
expectEqual(try width.strWidth("Hello\r\n", .half), 5);
expectEqual(try width.strWidth("\u{1F476}\u{1F3FF}\u{0308}\u{200D}\u{1F476}\u{1F3FF}", .half), 2);
expectEqual(try width.strWidth("Héllo 🇪🇸", .half), 8);
expectEqual(try width.strWidth("\u{26A1}\u{FE0E}", .half), 1); // Text sequence
expectEqual(try width.strWidth("\u{26A1}\u{FE0F}", .half), 2); // Presentation sequence
} | src/readme_tests.zig |
const std = @import("std");
const Builder = std.build.Builder;
const builtin = @import("builtin");
pub fn build(b: *Builder) void {
const build_mode = b.standardReleaseOptions();
// use a different cache folder for macos arm builds
b.cache_root = if (std.builtin.os.tag == .macos and std.builtin.arch == std.builtin.Arch.aarch64) "zig-arm-cache" else "zig-cache";
const examples = [_][2][]const u8{
[_][]const u8{ "view_vs_group", "examples/view_vs_group.zig" },
[_][]const u8{ "group_sort", "examples/group_sort.zig" },
[_][]const u8{ "simple", "examples/simple.zig" },
};
for (examples) |example, i| {
const name = if (i == 0) "ecs" else example[0];
const source = example[1];
var exe = b.addExecutable(name, source);
exe.setBuildMode(b.standardReleaseOptions());
exe.setOutputDir(std.fs.path.join(b.allocator, &[_][]const u8{ b.cache_root, "bin" }) catch unreachable);
exe.addPackagePath("ecs", "src/ecs.zig");
exe.linkSystemLibrary("c");
const run_cmd = exe.run();
const exe_step = b.step(name, b.fmt("run {s}.zig", .{name}));
exe_step.dependOn(&run_cmd.step);
// first element in the list is added as "run" so "zig build run" works
if (i == 0) {
const run_exe_step = b.step("run", b.fmt("run {s}.zig", .{name}));
run_exe_step.dependOn(&run_cmd.step);
}
}
// internal tests
const internal_test_step = b.addTest("src/tests.zig");
internal_test_step.setBuildMode(build_mode);
// public api tests
const test_step = b.addTest("tests/tests.zig");
test_step.addPackagePath("ecs", "src/ecs.zig");
test_step.setBuildMode(build_mode);
const test_cmd = b.step("test", "Run the tests");
test_cmd.dependOn(&internal_test_step.step);
test_cmd.dependOn(&test_step.step);
}
pub const LibType = enum(i32) {
static,
dynamic, // requires DYLD_LIBRARY_PATH to point to the dylib path
exe_compiled,
};
pub fn getPackage(comptime prefix_path: []const u8) std.build.Pkg {
return .{
.name = "ecs",
.path = prefix_path ++ "src/ecs.zig",
};
}
/// prefix_path is used to add package paths. It should be the the same path used to include this build file
pub fn linkArtifact(b: *Builder, artifact: *std.build.LibExeObjStep, _: std.build.Target, lib_type: LibType, comptime prefix_path: []const u8) void {
const build_mode = b.standardReleaseOptions();
switch (lib_type) {
.static => {
const lib = b.addStaticLibrary("ecs", "ecs.zig");
lib.setBuildMode(build_mode);
lib.install();
artifact.linkLibrary(lib);
},
.dynamic => {
const lib = b.addSharedLibrary("ecs", "ecs.zig", .unversioned);
lib.setBuildMode(build_mode);
lib.install();
artifact.linkLibrary(lib);
},
else => {},
}
artifact.addPackage(getPackage(prefix_path));
} | build.zig |
const std = @import("std");
fn isHashMap(comptime T: type) bool {
if (!@hasDecl(T, "KV")) return false;
if (!@hasField(T.KV, "key")) return false;
if (!@hasField(T.KV, "value")) return false;
const Key = std.meta.fields(T.KV)[std.meta.fieldIndex(T.KV, "key") orelse unreachable].field_type;
const Value = std.meta.fields(T.KV)[std.meta.fieldIndex(T.KV, "value") orelse unreachable].field_type;
if (!@hasDecl(T, "init")) return false;
if (!@hasDecl(T, "put")) return false;
const init = @TypeOf(T.init);
if (init != fn (std.mem.Allocator) T) return false;
const put = @typeInfo(@TypeOf(T.put));
if (put != .Fn) return false;
if (put.Fn.args.len != 3) return false;
if (put.Fn.args[0].arg_type.? != *T) return false;
if (put.Fn.args[1].arg_type.? != Key) return false;
if (put.Fn.args[2].arg_type.? != Value) return false;
if (put.Fn.return_type == null) return false;
const put_return = @typeInfo(put.Fn.return_type.?);
if (put_return != .ErrorUnion) return false;
if (put_return.ErrorUnion.payload != void) return false;
return true;
}
pub fn parse(comptime T: type, tree: std.json.Value, allocator: ?std.mem.Allocator) ParseInternalError(T)!T {
return try parseInternal(T, "root", @typeName(T), tree, allocator, false);
}
pub fn Undefinedable(comptime T: type) type {
return struct {
const __json_T = T;
const __json_is_undefinedable = true;
value: T,
missing: bool,
pub fn asOptional(self: @This()) ?T {
return if (self.missing)
null
else
self.value;
}
};
}
pub fn ParseInternalError(comptime T: type) type {
// `inferred_types` is used to avoid infinite recursion for recursive type definitions.
const inferred_types = [_]type{};
return ParseInternalErrorImpl(T, &inferred_types);
}
fn ParseInternalErrorImpl(comptime T: type, comptime inferred_types: []const type) type {
if (comptime std.meta.trait.isContainer(T) and @hasDecl(T, "tresParse")) {
const tresParse_return = @typeInfo(@typeInfo(@TypeOf(T.tresParse)).Fn.return_type.?);
if (tresParse_return == .ErrorUnion) {
return tresParse_return.ErrorUnion.error_set;
} else {
return error{};
}
}
for (inferred_types) |ty| {
if (T == ty) return error{};
}
const inferred_set = inferred_types ++ [_]type{T};
switch (@typeInfo(T)) {
.Bool, .Float => return error{UnexpectedFieldType},
.Int => return error{ UnexpectedFieldType, Overflow },
.Optional => |info| return ParseInternalErrorImpl(info.child, inferred_set),
.Enum => return error{ InvalidEnumTag, UnexpectedFieldType },
.Union => |info| {
var errors = error{UnexpectedFieldType};
for (info.fields) |field| {
errors = errors || ParseInternalErrorImpl(field.field_type, inferred_set);
}
return errors;
},
.Struct => |info| {
var errors = error{
UnexpectedFieldType,
InvalidFieldValue,
MissingRequiredField,
};
if (isAllocatorRequired(T)) {
errors = errors || error{AllocatorRequired} || std.mem.Allocator.Error;
}
for (info.fields) |field| {
errors = errors || ParseInternalErrorImpl(field.field_type, inferred_set);
}
return errors;
},
.Pointer => |info| {
var errors = error{UnexpectedFieldType};
if (isAllocatorRequired(T)) {
errors = errors || error{AllocatorRequired} || std.mem.Allocator.Error;
}
if (info.size == .Slice and info.child == u8 or info.child == std.json.Value)
return errors;
errors = errors || ParseInternalErrorImpl(info.child, inferred_set);
return errors;
},
.Array => |info| {
var errors = error{UnexpectedFieldType};
errors = errors || ParseInternalErrorImpl(info.child, inferred_set);
return errors;
},
.Vector => |info| {
var errors = error{UnexpectedFieldType};
errors = errors || ParseInternalErrorImpl(info.child, inferred_set);
return errors;
},
else => return error{},
}
}
pub fn isAllocatorRequired(comptime T: type) bool {
// `inferred_types` is used to avoid infinite recursion for recursive type definitions.
const inferred_types = [_]type{};
return isAllocatorRequiredImpl(T, &inferred_types);
}
fn isAllocatorRequiredImpl(comptime T: type, comptime inferred_types: []const type) bool {
for (inferred_types) |ty| {
if (T == ty) return false;
}
const inferred_set = inferred_types ++ [_]type{T};
switch (@typeInfo(T)) {
.Optional => |info| return isAllocatorRequiredImpl(info.child, inferred_set),
.Union => |info| {
for (info.fields) |field| {
if (isAllocatorRequiredImpl(field.field_type, inferred_set))
return true;
}
},
.Struct => |info| {
if (isHashMap(T)) {
if (T == std.json.ObjectMap)
return false;
return true;
}
for (info.fields) |field| {
if (@typeInfo(field.field_type) == .Struct and @hasDecl(field.field_type, "__json_is_undefinedable")) {
if (isAllocatorRequiredImpl(field.field_type.__json_T, inferred_set))
return true;
} else if (isAllocatorRequiredImpl(field.field_type, inferred_set))
return true;
}
},
.Pointer => |info| {
if (info.size == .Slice and info.child == u8 or info.child == std.json.Value)
return false;
return true;
},
.Array => |info| {
return isAllocatorRequiredImpl(info.child, inferred_set);
},
.Vector => |info| {
return isAllocatorRequiredImpl(info.child, inferred_set); // is it even possible for this to be true?
},
else => {},
}
return false;
}
const logger = std.log.scoped(.json);
fn parseInternal(
comptime T: type,
comptime parent_name: []const u8,
comptime field_name: []const u8,
json_value: std.json.Value,
maybe_allocator: ?std.mem.Allocator,
comptime suppress_error_logs: bool,
) ParseInternalError(T)!T {
// TODO(stage1): Revert name fixes when stage2 comes out
// and properly memoizes comptime strings
// all usage of parseInternal(... @typeName(T) ...) needs to
// be replaced with name when possible.
const name = parent_name ++ "." ++ field_name;
if (T == std.json.Value) return json_value;
if (comptime std.meta.trait.isContainer(T) and @hasDecl(T, "tresParse")) {
return T.tresParse(json_value, maybe_allocator);
}
switch (@typeInfo(T)) {
.Bool => {
if (json_value == .Bool) {
return json_value.Bool;
} else {
if (comptime !suppress_error_logs) logger.debug("expected Bool, found {s} at {s}", .{ @tagName(json_value), name });
return error.UnexpectedFieldType;
}
},
.Float => {
if (json_value == .Float) {
return @floatCast(T, json_value.Float);
} else if (json_value == .Integer) {
return @intToFloat(T, json_value.Integer);
} else if (json_value == .NumberString) {
return std.fmt.parseFloat(T, json_value.NumberString) catch unreachable;
} else {
if (comptime !suppress_error_logs) logger.debug("expected Float, found {s} at {s}", .{ @tagName(json_value), name });
return error.UnexpectedFieldType;
}
},
.Int => {
if (json_value == .Integer) {
return std.math.cast(T, json_value.Integer) orelse return error.Overflow;
} else if (json_value == .NumberString) {
return std.fmt.parseInt(T, json_value.NumberString, 10) catch |err| switch (err) {
error.Overflow => return error.Overflow, // TODO(stage1): we should be returning `err` here, but stage1 can't do type inference
error.InvalidCharacter => unreachable,
};
} else {
if (comptime !suppress_error_logs) logger.debug("expected Integer, found {s} at {s}", .{ @tagName(json_value), name });
return error.UnexpectedFieldType;
}
},
.Optional => |info| {
if (json_value == .Null) {
return null;
} else {
return try parseInternal(
info.child,
@typeName(T),
"?",
json_value,
maybe_allocator,
suppress_error_logs,
);
}
},
.Enum => {
if (json_value == .Integer) {
// we use this to convert signed to unsigned and check if it actually fits.
const tag = std.math.cast(std.meta.Tag(T), json_value.Integer) orelse {
if (comptime !suppress_error_logs) logger.debug("invalid enum tag for {s}, found {d} at {s}", .{ @typeName(T), json_value.Integer, name });
return error.InvalidEnumTag;
};
return try std.meta.intToEnum(T, tag);
} else if (json_value == .String) {
return std.meta.stringToEnum(T, json_value.String) orelse {
if (comptime !suppress_error_logs) logger.debug("invalid enum tag for {s}, found '{s}' at {s}", .{ @typeName(T), json_value.String, name });
return error.InvalidEnumTag;
};
} else {
if (comptime !suppress_error_logs) logger.debug("expected Integer or String, found {s} at {s}", .{ @tagName(json_value), name });
return error.UnexpectedFieldType;
}
},
.Union => |info| {
if (info.tag_type != null) {
inline for (info.fields) |field| {
if (parseInternal(
field.field_type,
@typeName(T),
field.name,
json_value,
maybe_allocator,
true,
)) |parsed_value| {
return @unionInit(T, field.name, parsed_value);
} else |_| {}
}
if (comptime !suppress_error_logs) logger.debug("union fell through for {s}, found {s} at {s}", .{ @typeName(T), @tagName(json_value), name });
return error.UnexpectedFieldType;
} else {
@compileError("cannot parse an untagged union: " ++ @typeName(T));
}
},
.Struct => |info| {
if (comptime isHashMap(T)) {
const Key = std.meta.fields(T.KV)[std.meta.fieldIndex(T.KV, "key") orelse unreachable].field_type;
const Value = std.meta.fields(T.KV)[std.meta.fieldIndex(T.KV, "value") orelse unreachable].field_type;
if (Key != []const u8) @compileError("HashMap key must be of type []const u8!");
if (json_value == .Object) {
if (T == std.json.ObjectMap) return json_value.Object;
const allocator = maybe_allocator orelse return error.AllocatorRequired;
var map = T.init(allocator);
var map_iterator = json_value.Object.iterator();
while (map_iterator.next()) |entry| {
try map.put(entry.key_ptr.*, try parseInternal(
Value,
@typeName(T),
".(hashmap entry)",
entry.value_ptr.*,
maybe_allocator,
suppress_error_logs,
));
}
return map;
} else {
if (comptime !suppress_error_logs) logger.debug("expected map of {s} at {s}, found {s}", .{ @typeName(Value), name, @tagName(json_value) });
return error.UnexpectedFieldType;
}
}
if (info.is_tuple) {
if (json_value != .Array) {
if (comptime !suppress_error_logs) logger.debug("expected Array, found {s} at {s}", .{ @tagName(json_value), name });
return error.UnexpectedFieldType;
}
if (json_value.Array.items.len != std.meta.fields(T).len) {
if (comptime !suppress_error_logs) logger.debug("expected Array to match length of Tuple {s} but it doesn't; at {s}", .{ @typeName(T), name });
return error.UnexpectedFieldType;
}
var tuple: T = undefined;
comptime var index: usize = 0;
inline while (index < std.meta.fields(T).len) : (index += 1) {
tuple[index] = try parseInternal(
std.meta.fields(T)[index].field_type,
@typeName(T),
comptime std.fmt.comptimePrint("[{d}]", .{index}),
json_value.Array.items[index],
maybe_allocator,
suppress_error_logs,
);
}
return tuple;
}
if (json_value == .Object) {
var result: T = undefined;
// Must use in order to bypass [#2727](https://github.com/ziglang/zig/issues/2727) :(
var missing_field = false;
inline for (info.fields) |field| {
const field_value = json_value.Object.get(field.name);
if (field.is_comptime) {
if (field_value == null) {
if (comptime !suppress_error_logs) logger.debug("comptime field {s}.{s} missing, at {s}", .{ @typeName(T), field.name, name });
return error.InvalidFieldValue;
}
if (field.default_value) |default| {
const parsed_value = try parseInternal(
field.field_type,
@typeName(T),
field.name,
field_value.?,
maybe_allocator,
suppress_error_logs,
);
const default_value = @ptrCast(*const field.field_type, default).*;
// NOTE: This only works for strings!
// TODODODODODODO ASAP
if (!std.mem.eql(u8, parsed_value, default_value)) {
if (comptime !suppress_error_logs) logger.debug("comptime field {s}.{s} does not match", .{ @typeName(T), field.name });
return error.InvalidFieldValue;
}
} else unreachable; // zig requires comptime fields to have a default initialization value
} else {
if (field_value) |fv| {
if (@typeInfo(field.field_type) == .Struct and @hasDecl(field.field_type, "__json_is_undefinedable"))
@field(result, field.name) = .{
.value = try parseInternal(
field.field_type.__json_T,
@typeName(T),
field.name,
fv,
maybe_allocator,
suppress_error_logs,
),
.missing = false,
}
else
@field(result, field.name) = try parseInternal(
field.field_type,
@typeName(T),
field.name,
fv,
maybe_allocator,
suppress_error_logs,
);
} else {
if (@typeInfo(field.field_type) == .Struct and @hasDecl(field.field_type, "__json_is_undefinedable")) {
@field(result, field.name) = .{
.value = undefined,
.missing = true,
};
} else if (field.default_value) |default| {
const default_value = @ptrCast(*const field.field_type, default).*;
@field(result, field.name) = default_value;
} else {
if (comptime !suppress_error_logs) logger.debug("required field {s}.{s} missing, at {s}", .{ @typeName(T), field.name, name });
missing_field = true;
}
}
}
}
if (missing_field) return error.MissingRequiredField;
return result;
} else {
if (comptime !suppress_error_logs) logger.debug("expected Object, found {s} at {s}", .{ @tagName(json_value), name });
return error.UnexpectedFieldType;
}
},
.Pointer => |info| {
if (info.size == .Slice) {
if (info.child == u8) {
if (json_value == .String) {
return json_value.String;
} else {
if (comptime !suppress_error_logs) logger.debug("expected String, found {s} at {s}", .{ @tagName(json_value), name });
return error.UnexpectedFieldType;
}
} else if (info.child == std.json.Value) {
return json_value.Array.items;
}
}
const allocator = maybe_allocator orelse return error.AllocatorRequired;
switch (info.size) {
.Slice, .Many => {
const sentinel: ?info.child = if (info.sentinel) |ptr| @ptrCast(*const info.child, ptr).* else null;
if (info.size == .Many and sentinel == null)
@compileError("unhandled pointer type: " ++ @typeName(info.size) ++ " at " ++ name);
if (info.child == u8 and json_value == .String) {
const array = try allocator.allocWithOptions(
info.child,
json_value.String.len,
info.alignment,
sentinel,
);
std.mem.copy(u8, array, json_value.String);
return @ptrCast(T, array);
}
if (json_value == .Array) {
if (info.child == std.json.Value) return json_value.Array.items;
const array = try allocator.allocWithOptions(
info.child,
json_value.Array.items.len,
info.alignment,
sentinel,
);
for (json_value.Array.items) |item, index|
array[index] = try parseInternal(
info.child,
@typeName(T),
"[...]",
item,
maybe_allocator,
suppress_error_logs,
);
return @ptrCast(T, array);
} else {
if (comptime !suppress_error_logs) logger.debug("expected Array, found {s} at {s}", .{ @tagName(json_value), name });
return error.UnexpectedFieldType;
}
},
.One => {
const data = try allocator.allocAdvanced(info.child, info.alignment, 1, .exact);
data[0] = try parseInternal(
info.child,
@typeName(T),
"*",
json_value,
maybe_allocator,
suppress_error_logs,
);
return &data[0];
},
else => @compileError("unhandled pointer type: " ++ @typeName(info.size) ++ " at " ++ name),
}
},
.Array => |info| {
if (json_value == .Array) {
var array: T = undefined;
if (info.sentinel) |ptr| {
const sentinel = @ptrCast(*const info.child, ptr).*;
array[array.len] = sentinel;
}
if (json_value.Array.items.len != info.len) {
if (comptime !suppress_error_logs) logger.debug("expected Array to match length of {s} but it doesn't; at {s}", .{ @typeName(T), name });
return error.UnexpectedFieldType;
}
for (array) |*item, index|
item.* = try parseInternal(
info.child,
@typeName(T),
"[...]",
json_value.Array.items[index],
maybe_allocator,
suppress_error_logs,
);
return array;
} else {
if (comptime !suppress_error_logs) logger.debug("expected Array, found {s} at {s}", .{ @tagName(json_value), name });
return error.UnexpectedFieldType;
}
},
.Vector => |info| {
if (json_value == .Array) {
var vector: T = undefined;
if (json_value.Array.items.len != info.len) {
if (comptime !suppress_error_logs) logger.debug("expected Array to match length of {s} ({d}) but it doesn't; at {s}", .{ @typeName(T), info.len, name });
return error.UnexpectedFieldType;
}
for (vector) |*item|
item.* = try parseInternal(
info.child,
@typeName(T),
"[...]",
item,
maybe_allocator,
suppress_error_logs,
);
return vector;
} else {
if (comptime !suppress_error_logs) logger.debug("expected Array, found {s} at {s}", .{ @tagName(json_value), name });
return error.UnexpectedFieldType;
}
},
else => {
@compileError("unhandled json type: " ++ @typeName(T) ++ " at " ++ name);
},
}
}
pub fn parseFree(value: anytype, allocator: std.mem.Allocator) void {
return parseFreeInternal(@TypeOf(value), value, allocator);
}
fn parseFreeInternal(comptime T: type, value: T, allocator: std.mem.Allocator) void {
if (T == std.json.Value) return;
switch (@typeInfo(T)) {
.Optional => |info| {
if (value) |unwrapped| {
return parseFreeInternal(info.child, unwrapped, allocator);
}
},
.Union => {
inline for (std.meta.fields(T)) |field| {
if (std.meta.eql(field.name, @tagName(value))) {
return parseFreeInternal(
field.field_type,
@field(value, field.name),
allocator,
);
}
}
},
.Struct => |info| {
if (comptime isHashMap(T)) {
if (T == std.json.ObjectMap)
return;
var mutable = value; // This is a hack around deinit functions that use self.* = undefined;
mutable.deinit();
return;
}
if (info.is_tuple) {
inline for (std.meta.fields(T)) |field| {
parseFreeInternal(field.field_type, @field(value, field.name), allocator);
}
return;
}
inline for (info.fields) |field| {
if (@typeInfo(field.field_type) == .Struct and @hasDecl(field.field_type, "__json_is_undefinedable")) {
if (!@field(value, field.name).missing)
parseFreeInternal(field.field_type.__json_T, @field(value, field.name).value, allocator);
} else {
parseFreeInternal(field.field_type, @field(value, field.name), allocator);
}
}
},
.Pointer => |info| {
if (info.size == .Slice and (info.child == u8 or info.child == std.json.Value))
return;
switch (info.size) {
.Slice => allocator.free(value),
.Many => {
const sentinel = @ptrCast(*const info.child, info.sentinel.?).*;
const slice = std.mem.sliceTo(value, sentinel);
allocator.free(slice);
},
.One => allocator.destroy(value),
else => unreachable,
}
},
.Array => |info| {
for (value) |item|
parseFreeInternal(info.child, item, allocator);
},
.Vector => |info| {
for (value) |item|
parseFreeInternal(info.child, item, allocator);
},
else => {},
}
} | tres.zig |
const std = @import("std");
const assert = std.debug.assert;
const tools = @import("tools");
const RunFn = fn (input: []const u8, allocator: std.mem.Allocator) tools.RunError![2][]const u8;
// it.runFn = @import(name); -> marche pas. doit être un string litteral
const alldays = [_]struct { runFn: RunFn, input: []const u8 }{
.{ .runFn = @import("day01.zig").run, .input = @embedFile("day01.txt") },
.{ .runFn = @import("day02.zig").run, .input = @embedFile("day02.txt") },
.{ .runFn = @import("day03.zig").run, .input = @embedFile("day03.txt") },
.{ .runFn = @import("day04.zig").run, .input = "" },
.{ .runFn = @import("day05.zig").run, .input = @embedFile("day05.txt") },
.{ .runFn = @import("day06.zig").run, .input = @embedFile("day06.txt") },
.{ .runFn = @import("day07.zig").run, .input = @embedFile("day07.txt") },
.{ .runFn = @import("day08.zig").run, .input = @embedFile("day08.txt") },
.{ .runFn = @import("day09.zig").run, .input = @embedFile("day09.txt") },
.{ .runFn = @import("day10.zig").run, .input = @embedFile("day10.txt") },
.{ .runFn = @import("day11.zig").run, .input = @embedFile("day11.txt") },
.{ .runFn = @import("day12.zig").run, .input = "" },
.{ .runFn = @import("day13.zig").run, .input = @embedFile("day13.txt") },
.{ .runFn = @import("day14.zig").run, .input = @embedFile("day14.txt") },
.{ .runFn = @import("day15.zig").run, .input = @embedFile("day15.txt") },
.{ .runFn = @import("day16.zig").run, .input = @embedFile("day16.txt") },
.{ .runFn = @import("day17.zig").run, .input = @embedFile("day17.txt") },
.{ .runFn = @import("day18.zig").run, .input = @embedFile("day18.txt") },
.{ .runFn = @import("day19.zig").run, .input = @embedFile("day19.txt") },
.{ .runFn = @import("day20.zig").run, .input = @embedFile("day20.txt") },
.{ .runFn = @import("day21.zig").run, .input = @embedFile("day21.txt") },
.{ .runFn = @import("day22.zig").run, .input = @embedFile("day22.txt") },
.{ .runFn = @import("day23.zig").run, .input = @embedFile("day23.txt") },
.{ .runFn = @import("day24.zig").run, .input = "" },
.{ .runFn = @import("day25.zig").run, .input = @embedFile("day25.txt") },
};
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
for (alldays) |it, day| {
const answer = try it.runFn(it.input, allocator);
defer allocator.free(answer[0]);
defer allocator.free(answer[1]);
try stdout.print("Day {d:0>2}:\n", .{day + 1});
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 });
}
}
}
} | 2019/alldays.zig |
const std = @import("std");
const chart = @import("chart.zig");
const process = std.process;
const unicode = std.unicode;
const ArrayList = std.ArrayList;
const Allocator = std.mem.Allocator;
const eql = std.mem.eql;
const max = std.math.max;
const ArgError = error
{
MultipleInputFiles,
MissingDelim
};
/// Whether to read from standard input or a particular file
const InputType = union(enum)
{
stdin: void,
file: []const u8,
};
/// Information derived from parsed arguments
const InputInfo = struct
{
// Whether or not the top row should be bolded
include_header: bool,
// A list of valid delimiters
delimiters: [][]const u8,
// See InputType union
in_type: InputType,
/// Free all interior memory
fn free(self: *InputInfo, allocator: *const Allocator) void
{
for (self.delimiters) |delim|
{
allocator.free(delim);
}
switch (self.in_type)
{
.stdin => |_| {},
.file => |file|
{
allocator.free(file);
}
}
allocator.free(self.delimiters);
}
};
/// Entry-point
pub fn main() !void
{
// Init allocator
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
// Init and parse
var input_info = try handleArgs(&allocator);
var input = try readInput(&allocator, &input_info.in_type);
var tokens = try tokenize(&allocator, &input_info.delimiters, &input);
// Gen chart
var widths = try getColumnWidths(&allocator, &tokens);
const result = try chart.genChart(&allocator, &tokens, &widths, input_info.include_header);
// Output resulting chart
try std.io.getStdOut().writer().print("{s}", .{result});
}
fn getColumnWidths(allocator: *const Allocator, tokens: *[][][]const u8) ![]const u8
{
var widths = try allocator.alloc(u8, tokens.*[0].len);
for (widths) |_, i|
{
widths[i] = 0;
}
for (tokens.*) |line|
{
for (line) |tok, i|
{
widths[i] = max(widths[i], @intCast(u8, tok.len) + 2);
}
}
return widths;
}
fn tokenize(allocator: *const Allocator, delimiters: *[][]const u8, input: *[][]const u8) ![][][]const u8
{
var tokens = ArrayList([][]const u8).init(allocator.*);
for (input.*) |string|
{
var sub_tokens = ArrayList([]const u8).init(allocator.*);
var first_delim = true;
for (delimiters.*) |delim|
{
if (first_delim)
{
first_delim = false;
var iter = std.mem.split(u8, string, delim);
while (iter.next()) |tok|
{
try sub_tokens.append(tok);
}
}
else
{
var line = sub_tokens.toOwnedSlice();
for (line) |partial_line|
{
var iter = std.mem.split(u8, partial_line, delim);
while (iter.next()) |tok|
{
try sub_tokens.append(tok);
}
}
allocator.free(line);
}
}
try tokens.append(sub_tokens.toOwnedSlice());
}
return tokens.toOwnedSlice();
}
fn readInput(allocator: *const Allocator, inputType: *InputType) ![][]const u8
{
var input = ArrayList([]const u8).init(allocator.*);
switch (inputType.*)
{
.stdin => |_|
{
var buffer = try allocator.alloc(u8, 1024);
const stdin = std.io.getStdIn().reader();
while (try stdin.readUntilDelimiterOrEof(buffer, '\n')) |line|
{
try input.append(try allocator.dupe(u8, line));
}
allocator.free(buffer);
},
.file => |path|
{
var buffer = try allocator.alloc(u8, 1024);
var file = try std.fs.openFileAbsolute(path, .{});
defer file.close();
var buf_reader = std.io.bufferedReader(file.reader());
var in_stream = buf_reader.reader();
while (try in_stream.readUntilDelimiterOrEof(buffer, '\n')) |line|
{
try input.append(try allocator.dupe(u8, line));
}
allocator.free(buffer);
}
}
return input.toOwnedSlice();
}
fn handleArgs(allocator: *const Allocator) !InputInfo
{
var expect_delim = false;
var args = process.args();
var delimiters = ArrayList([]const u8).init(allocator.*);
// Init return type
var input_info = InputInfo
{
.include_header = false,
.delimiters = undefined,
.in_type = InputType { .stdin = undefined }
};
// Discard initial arg
if (try args.next(allocator.*)) |arg|
{
allocator.free(arg);
}
// Iterate through each arg
while (try args.next(allocator.*)) |arg|
{
if (expect_delim)
{
expect_delim = false;
try delimiters.append(arg);
}
else
{
if (eql(u8, "-h", arg))
{
input_info.include_header = true;
allocator.free(arg);
}
else if (eql(u8, "-d", arg))
{
expect_delim = true;
allocator.free(arg);
}
else
{
switch (input_info.in_type)
{
.stdin => |_|
{
input_info.in_type = InputType { .file = arg };
},
.file => |_|
{
allocator.free(arg);
input_info.free(allocator);
return ArgError.MultipleInputFiles;
}
}
}
}
}
input_info.delimiters = delimiters.toOwnedSlice();
if (expect_delim)
{
input_info.free(allocator);
return ArgError.MissingDelim;
}
return input_info;
} | src-zig/main.zig |
const std = @import("std");
const assert = std.debug.assert;
pub fn main() !void {
var input_file = try std.fs.cwd().openFile("input/08.txt", .{});
defer input_file.close();
var buffered_reader = std.io.bufferedReader(input_file.reader());
const count = try deduceNumbers(buffered_reader.reader());
std.debug.print("appearances of 1, 4, 7 and 8: {}\n", .{count});
}
const Pattern = u7;
fn deduceNumbers(reader: anytype) !u64 {
var buf: [1024]u8 = undefined;
var sum: u64 = 0;
while (try reader.readUntilDelimiterOrEof(&buf, '\n')) |line| {
var iter = std.mem.split(u8, line, " ");
var patterns = [_]Pattern{0} ** 10;
for (patterns) |*pattern| {
const raw_pattern = iter.next() orelse return error.MissingData;
for (raw_pattern) |c| {
pattern.* |= @as(Pattern, 1) << @intCast(u3, c - 'a');
}
}
const delimiter = iter.next() orelse return error.WrongFormat;
if (!std.mem.eql(u8, "|", delimiter)) return error.WrongFormat;
while (iter.next()) |raw_pattern| {
var pattern: Pattern = 0;
for (raw_pattern) |c| {
pattern |= @as(Pattern, 1) << @intCast(u3, c - 'a');
}
switch (raw_pattern.len) {
2, 3, 4, 7 => sum += 1,
else => {},
}
}
}
return sum;
}
test "example 1" {
const text =
\\be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe
\\edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc
\\fgaebd cg bdaec gdafb agbcfd gdcbef bgcad gfac gcb cdgabef | cg cg fdcagb cbg
\\fbegcd cbd adcefb dageb afcb bc aefdc ecdab fgdeca fcdbega | efabcd cedba gadfec cb
\\aecbfdg fbg gf bafeg dbefa fcge gcbea fcaegb dgceab fcbdga | gecf egdcabf bgf bfgea
\\fgeab ca afcebg bdacfeg cfaedg gcfdb baec bfadeg bafgc acf | gebdcfa ecba ca fadegcb
\\dbcfg fgd bdegcaf fgec aegbdf ecdfab fbedc dacgb gdcebf gf | cefg dcbef fcge gbcadfe
\\bdfegc cbegaf gecbf dfcage bdacg ed bedf ced adcbefg gebcd | ed bcgafe cdgba cbgef
\\egadfb cdbfeg cegd fecab cgb gbdefca cg fgcdab egfdb bfceg | gbdfcae bgc cg cgb
\\gcafb gcf dcaebfg ecagb gf abcdeg gaef cafbge fdbac fegbdc | fgae cfgab fg bagce
;
var fbs = std.io.fixedBufferStream(text);
const count = try deduceNumbers(fbs.reader());
try std.testing.expectEqual(@as(u64, 26), count);
} | src/08.zig |
const Server = @This();
const lsp = @import("lsp");
const std = @import("std");
const tres = @import("tres");
arena: std.heap.ArenaAllocator,
parser: std.json.Parser,
read_buf: std.ArrayList(u8),
write_buf: std.ArrayList(u8),
const SampleDirection = enum {
client_to_server,
server_to_client,
};
const SampleEntryKind = enum {
@"send-request",
@"receive-request",
@"send-response",
@"receive-response",
@"send-notification",
@"receive-notification",
fn getDirection(self: SampleEntryKind) SampleDirection {
return switch (self) {
.@"send-request", .@"send-response", .@"send-notification" => .client_to_server,
else => .server_to_client,
};
}
};
// TODO: Handle responses
const SampleEntry = struct {
isLSPMessage: bool,
@"type": SampleEntryKind,
message: std.json.Value,
};
pub fn readLine(self: *Server, reader: anytype) !void {
while (true) {
var byte = try reader.readByte();
if (byte == '\n') {
return;
}
if (self.read_buf.items.len == self.read_buf.capacity) {
try self.read_buf.ensureTotalCapacity(self.read_buf.capacity + 1);
}
try self.read_buf.append(byte);
}
}
pub fn flushArena(self: *Server) void {
self.arena.deinit();
self.arena.state = .{};
}
test {
@setEvalBranchQuota(100_000);
var log_dir = try std.fs.cwd().openDir("samples", .{ .iterate = true });
defer log_dir.close();
var log = try log_dir.openFile("amogus-html.log", .{});
defer log.close();
var reader = log.reader();
// reader.readAll()
const allocator = std.heap.page_allocator;
var arena = std.heap.ArenaAllocator.init(allocator);
var server = Server{
.arena = arena,
.parser = std.json.Parser.init(arena.allocator(), false),
.read_buf = try std.ArrayList(u8).initCapacity(allocator, 1024),
.write_buf = try std.ArrayList(u8).initCapacity(allocator, 1024),
};
var parser = std.json.Parser.init(server.arena.allocator(), false);
while (true) {
server.readLine(reader) catch |err| switch (err) {
error.EndOfStream => return,
else => return std.log.err("{s}", .{err}),
};
const tree = try parser.parse(server.read_buf.items);
defer parser.reset();
const entry = try tres.parse(SampleEntry, tree.root, .{ .allocator = arena.allocator() });
if (entry.isLSPMessage) {
switch (entry.@"type") {
.@"send-request",
.@"receive-request",
.@"send-notification",
.@"receive-notification",
=> a: {
const requestOrNotification = tres.parse(lsp.RequestOrNotification, entry.message, .{
.allocator = arena.allocator(),
.suppress_error_logs = false,
}) catch {
std.log.err("Cannot handle Request or Notification of method \"{s}\"", .{entry.message.Object.get("method").?.String});
break :a;
};
if (requestOrNotification.params == .unknown)
std.log.err("{s}: {s}", .{ requestOrNotification.method, requestOrNotification.params });
},
.@"send-response" => {
// std.log.err("\nSEND RESPONSE\n", .{});
},
else => {},
}
}
server.read_buf.items.len = 0;
// arena.deinit();
}
} | tests/tests.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const print = std.debug.print;
const data = @embedFile("../inputs/day03.txt");
const BIT_COUNT = 12;
pub fn main() anyerror!void {
var gpa_impl = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa_impl.deinit();
const gpa = gpa_impl.allocator();
return main_with_allocator(gpa);
}
pub fn main_with_allocator(allocator: Allocator) anyerror!void {
// Part 1
var line_count: usize = 0;
var ones_count: [BIT_COUNT]usize = undefined;
std.mem.set(usize, ones_count[0..], 0);
var inputs = std.ArrayList(usize).init(allocator);
defer inputs.deinit();
{
var lines = std.mem.tokenize(u8, data, "\n");
while (lines.next()) |line| {
var input: usize = 0;
for (line) |c, i| {
input <<= 1;
if (c == '1') {
ones_count[i] += 1;
input += 1;
}
}
try inputs.append(input);
line_count += 1;
}
}
var gamma: usize = 0;
var epsilon: usize = 0;
for (ones_count) |o| {
gamma <<= 1;
epsilon <<= 1;
if (o >= line_count / 2) {
gamma += 1;
} else {
epsilon += 1;
}
}
print("Part 1: {}\n", .{gamma * epsilon});
// Part 2
var oxy_candidates = std.ArrayList(usize).init(allocator);
defer oxy_candidates.deinit();
try oxy_candidates.insertSlice(0, inputs.items);
var co2_candidates = std.ArrayList(usize).init(allocator);
defer co2_candidates.deinit();
try co2_candidates.insertSlice(0, inputs.items);
var buffer = std.ArrayList(usize).init(allocator);
defer buffer.deinit();
var bit: usize = 0;
while (bit < ones_count.len) : (bit += 1) {
if (oxy_candidates.items.len > 1) {
try rating(true, oxy_candidates.items, BIT_COUNT, bit, &buffer);
std.mem.swap(std.ArrayList(usize), &oxy_candidates, &buffer);
}
if (co2_candidates.items.len > 1) {
try rating(false, co2_candidates.items, BIT_COUNT, bit, &buffer);
std.mem.swap(std.ArrayList(usize), &co2_candidates, &buffer);
}
}
const oxy: ?usize = oxy_candidates.popOrNull();
const co2: ?usize = co2_candidates.popOrNull();
print("Part 2: {}\n", .{oxy.? * co2.?});
}
fn rating(most: bool, inputs: []usize, bit_count: usize, bit: usize, out: *std.ArrayList(usize)) !void {
out.clearRetainingCapacity();
const bi = @intCast(u6, bit_count - bit - 1);
const bit_mask = @as(usize, 1) << bi;
var ones_count: usize = 0;
for (inputs) |n| {
if (n & bit_mask > 0) {
ones_count += 1;
}
}
var one = @intToFloat(f32, ones_count) >= @intToFloat(f32, inputs.len) / 2;
if (!most) {
one = !one;
}
for (inputs) |n| {
const one_set = n & bit_mask > 0;
if (one == one_set) {
try out.append(n);
}
}
if (out.items.len == 0) {
try out.append(inputs[inputs.len - 1]);
}
} | src/day03.zig |
const std = @import("std");
const Random = std.rand.Random;
const math = std.math;
const Sfc64 = @This();
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| {
try std.testing.expectEqual(s, r.next());
}
}
test "Sfc64 fill" {
// 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| {
var buf0: [8]u8 = undefined;
var buf1: [7]u8 = undefined;
std.mem.writeIntLittle(u64, &buf0, s);
Sfc64.fill(&r.random, &buf1);
try std.testing.expect(std.mem.eql(u8, buf0[0..7], buf1[0..]));
}
} | lib/std/rand/Sfc64.zig |
const warn = @import("std").debug.warn;
const x86 = @import("src/x86.zig");
pub fn main() anyerror!void {
const machine64 = x86.Machine.init(.x64);
{
const op1 = x86.Operand.register(.RAX);
const op2 = x86.Operand.register(.R15);
const instr = try machine64.build2(.MOV, op1, op2);
warn("{x}\t\t\tMOV\t{}, {}\n", .{instr.asSlice(), op1, op2});
}
{
const op1 = x86.Operand.register(.RAX);
const op2 = x86.Operand.memoryRm(.GS, .QWORD, .RAX, 0x33221100);
const instr = try machine64.build2_pre(.Lock, .MOV, op1, op2);
warn("{x}\tLOCK MOV\t{}, {}\n", .{instr.asSlice(), op1, op2});
}
{
const op1 = x86.Operand.memorySib(.FS, .DWORD, 8, .ECX, .EBX, 0x33221100);
const op2 = x86.Operand.register(.EAX);
const instr1 = try machine64.build2_pre(.Lock, .MOV, op1, op2);
warn("{x}\tLOCK MOV\t{}, {}\n", .{instr1.asSlice(), op1, op2});
// Same as above except with default segment
const op3 = x86.Operand.memorySibDef(.DWORD, 8, .ECX, .EBX, 0x33221100);
const op4 = x86.Operand.register(.EAX);
const instr2 = try machine64.build2_pre(.Lock, .MOV, op3, op4);
warn("{x}\tLOCK MOV\t{}, {}\n", .{instr2.asSlice(), op3, op4});
}
{
// Operand.memory will use a shorter encoding when possible whereas
// Operand.memorySib will always use an encoding with a SIB byte.
const op1 = x86.Operand.memoryDef(.DWORD, 0, null, .RBX, 0);
const op2 = x86.Operand.register(.EAX);
const instr1 = try machine64.build2(.MOV, op1, op2);
warn("{x}\t\t\tMOV\t{}, {}\n", .{instr1.asSlice(), op1, op2});
// NOTE: the scale must not be zero, since it always gets encoded in
// the SIB byte even when it's not used.
const op3 = x86.Operand.memorySibDef(.DWORD, 1, null, .RBX, 0);
const op4 = x86.Operand.register(.EAX);
const instr2 = try machine64.build2(.MOV, op3, op4);
warn("{x}\t\t\tMOV\t{}, {}\n", .{instr2.asSlice(), op3, op4});
}
{
const op1 = x86.Operand.register(.SIL);
const op2 = x86.Operand.memoryRmDef(.BYTE, .R14, 0);
const instr = try machine64.build2(.MOV, op1, op2);
warn("{x}\t\t\tMOV\t{}, {}\n", .{instr.asSlice(), op1, op2});
}
{
const op1 = x86.Operand.immediateSigned(-20);
const instr = try machine64.build1(.JMP, op1);
warn("{x}\t\t\tJMP\t{}\n", .{instr.asSlice(), op1});
}
} | example.zig |
const std = @import("std");
const ray = @import("ray.zig");
const image = @import("image.zig");
const scene = @import("scene.zig");
const camera = @import("camera.zig");
const config = @import("config.zig");
const vector = @import("vector.zig");
const Vec3 = config.Vec3;
pub const Tracer = struct {
scene: *scene.Scene,
samples: [config.SAMPLES_PER_PIXEL * config.SCREEN_DIMS]f64,
};
pub fn tracePaths(tracer: Tracer, buffer: []u8, offset: usize, chunk_size: usize) !void {
const cur_camera = tracer.scene.camera;
const screen_side = @as(f64, config.SCREEN_SIDE);
const x_direction = Vec3{ cur_camera.field_of_view, 0.0, 0.0 };
const y_direction = vector.normalize(vector.cross_product(x_direction, cur_camera.direction)) * @splat(config.SCENE_DIMS, cur_camera.field_of_view);
const ray_origin = Vec3{ 50.0, 52.0, 295.6 };
var chunk_samples: [config.SAMPLES_PER_PIXEL * config.SCREEN_DIMS]f64 = undefined;
var sphere_samples: [config.SAMPLES_PER_PIXEL * config.SCREEN_DIMS]f64 = undefined;
var prng = std.rand.DefaultPrng.init(blk: {
var seed: u64 = undefined;
try std.os.getrandom(std.mem.asBytes(&seed));
break :blk seed;
});
const rng = &prng.random();
camera.samplePixels(&chunk_samples, rng);
camera.applyTentFilter(&chunk_samples);
const inverse_samples_per_pixel = @splat(config.SCENE_DIMS, 1.0 / @as(f64, config.SAMPLES_PER_PIXEL));
const start_x = offset % config.SCREEN_SIDE;
const start_y = offset / config.SCREEN_SIDE;
var y = start_y;
var x = start_x;
var pixel_offset = offset * config.NUM_CHANNELS;
const end_offset = pixel_offset + chunk_size * config.NUM_CHANNELS;
const ray_scale = @splat(config.SCENE_DIMS, @as(f64, 136.0));
while (pixel_offset < end_offset) : (pixel_offset += config.NUM_CHANNELS) {
camera.samplePixels(&sphere_samples, rng);
var anti_aliased_color = config.ZERO_VECTOR;
var anti_aliasing_factor: usize = 0;
while (anti_aliasing_factor < config.ANTI_ALIASING_FACTOR) : (anti_aliasing_factor += 1) {
var raw_color = config.ZERO_VECTOR;
const X_ANTI_ALIASING_FACTOR = @intToFloat(f64, (anti_aliasing_factor & 1));
const Y_ANTI_ALIASING_FACTOR = @intToFloat(f64, (anti_aliasing_factor >> 1));
var sample_idx: usize = 0;
while (sample_idx < config.SAMPLES_PER_PIXEL) : (sample_idx += 1) {
const x_chunk = chunk_samples[sample_idx * config.SCREEN_DIMS];
const y_chunk = chunk_samples[sample_idx * config.SCREEN_DIMS + 1];
const x_chunk_direction = x_direction * @splat(config.SCENE_DIMS, (((X_ANTI_ALIASING_FACTOR + 0.5 + x_chunk) / 2.0) + @intToFloat(f64, x)) / screen_side - 0.5);
const y_chunk_direction = y_direction * @splat(config.SCENE_DIMS, -((((Y_ANTI_ALIASING_FACTOR + 0.5 + y_chunk) / 2.0) + @intToFloat(f64, y)) / screen_side - 0.5));
var ray_direction = vector.normalize(x_chunk_direction + y_chunk_direction + cur_camera.direction);
var cur_ray = ray.Ray{ .origin = ray_origin + ray_direction * ray_scale, .direction = ray_direction };
const x_sphere_sample = sphere_samples[sample_idx * config.SCREEN_DIMS];
const y_sphere_sample = sphere_samples[sample_idx * config.SCREEN_DIMS + 1];
const ray_color = ray.tracePath(cur_ray, tracer.scene, x_sphere_sample, y_sphere_sample, tracer.samples, rng);
raw_color += ray_color * inverse_samples_per_pixel;
}
anti_aliased_color += raw_color * config.INVERSE_ANTI_ALIASING_FACTOR;
}
var color = image.getColor(anti_aliased_color);
buffer[pixel_offset + 3] = 0;
buffer[pixel_offset + 0] = @intCast(u8, color[0]);
buffer[pixel_offset + 1] = @intCast(u8, color[1]);
buffer[pixel_offset + 2] = @intCast(u8, color[2]);
x += 1;
if (x == config.SCREEN_SIDE) {
x = 0;
y += 1;
}
}
} | src/tracer.zig |
const SDL = @import("sdl2");
const std = @import("std");
const z80 = @import("zig80");
const Audio = @import("Audio.zig");
const Inputs = @import("Inputs.zig");
const ROM = @import("ROM.zig");
const Timer = @import("Timer.zig");
const Video = @import("Video.zig");
const Machine = @This();
const CYCLES_PER_FRAME = 51200;
code: *[0x4000]u8,
wram: *[0x3f0]u8,
video: Video,
audio: Audio,
inputs: Inputs = .{},
watchdog: u8 = 0,
interrupt_vector: u8 = 0,
interrupt_enable: bool = false,
dips: u8 = 0,
pub fn init(allocator: std.mem.Allocator, rom_folder: []const u8) !Machine {
const rom = try ROM.init(allocator, rom_folder);
defer rom.deinit(allocator);
const video = try Video.init(allocator, rom);
errdefer video.deinit(allocator);
const audio = try Audio.init(allocator, rom);
errdefer audio.deinit(allocator);
const code = try allocator.create([0x4000]u8);
errdefer allocator.destroy(code);
code.* = rom.code;
const wram = try allocator.create([0x3f0]u8);
errdefer allocator.destroy(wram);
std.mem.set(u8, wram, 0);
return Machine{
.code = code,
.wram = wram,
.video = video,
.audio = audio,
};
}
pub fn deinit(self: Machine, allocator: std.mem.Allocator) void {
allocator.destroy(self.code);
allocator.destroy(self.wram);
self.video.deinit(allocator);
self.audio.deinit(allocator);
}
fn read(self: *Machine, address: u16) u8 {
const addr = address & 0x7fff;
return switch (addr) {
0x0000...0x3fff => self.code[addr],
0x4000...0x43ff => self.video.vram[addr - 0x4000],
0x4400...0x47ff => self.video.cram[addr - 0x4400],
0x4c00...0x4fef => self.wram[addr - 0x4c00],
0x4ff0...0x4fff => {
const sprite = self.video.sprites[(addr & 0xf) >> 1];
return switch (@truncate(u1, addr)) {
0 => sprite.readAttrs(),
1 => sprite.color,
};
},
0x5000 => self.inputs.in0,
0x5040 => self.inputs.in1,
0x5080 => self.dips,
else => 0,
};
}
fn write(self: *Machine, address: u16, value: u8) void {
const addr = address & 0x7fff;
switch (addr) {
0x4000...0x43ff => self.video.vram[addr - 0x4000] = value,
0x4400...0x47ff => self.video.cram[addr - 0x4400] = value,
0x4c00...0x4fef => self.wram[addr - 0x4c00] = value,
0x4ff0...0x4fff => {
const sprite = &self.video.sprites[(addr & 0xf) >> 1];
switch (@truncate(u1, addr)) {
0 => sprite.writeAttrs(value),
1 => sprite.color = value,
}
},
0x5000 => self.interrupt_enable = value != 0,
0x5001 => self.audio.enabled = value != 0,
0x5003 => self.video.flip = value != 0,
0x5040 => self.audio.voices[0].setAccNybble(0, @truncate(u4, value)),
0x5041...0x504f => {
const voice = &self.audio.voices[(addr - 0x5041) / 5];
switch ((addr - 0x5041) % 5) {
0...3 => |i| voice.setAccNybble(@intCast(u3, i) + 1, @truncate(u4, value)),
4 => voice.wave = @truncate(u4, value),
else => unreachable,
}
},
0x5050 => self.audio.voices[0].setFreqNybble(0, @truncate(u4, value)),
0x5051...0x505f => {
const voice = &self.audio.voices[(addr - 0x5051) / 5];
switch ((addr - 0x5051) % 5) {
0...3 => |i| voice.setFreqNybble(@intCast(u3, i) + 1, @truncate(u4, value)),
4 => voice.vol = @truncate(u4, value),
else => unreachable,
}
},
0x5060...0x506f => {
const sprite = &self.video.sprites[(addr & 0xf) >> 1];
switch (@truncate(u1, addr)) {
0 => sprite.x_pos = value,
1 => sprite.y_pos = value,
}
},
0x50c0 => self.watchdog = 0,
else => {},
}
}
fn irq(self: *Machine) u8 {
return self.interrupt_vector;
}
fn out(self: *Machine, port: u16, value: u8) void {
_ = port;
self.interrupt_vector = value;
}
pub fn run(self: *Machine) !void {
// interface for CPU
const interface = z80.Interface.init(self, .{
.read = read,
.write = write,
.irq = irq,
.out = out,
});
// CPU to run game
var cpu = z80.CPU{ .interface = interface };
// 60hz timer
var timer = Timer.init();
// we're waiting for the CPU to be ready to accept an interrupt
var irq_pending = false;
while (true) {
if (!self.inputs.pause) {
// step cpu until vblank
while (cpu.cycles < CYCLES_PER_FRAME) {
if (irq_pending and cpu.irq()) {
irq_pending = false;
}
cpu.step();
}
cpu.cycles -= CYCLES_PER_FRAME;
// check watchdog
self.watchdog += 1;
if (self.watchdog == 16) return error.Watchdog;
// queue irq if enabled
if (self.interrupt_enable) irq_pending = true;
// update outputs
try self.audio.update();
try self.video.update();
}
// check inputs, quit if requested
while (SDL.pollEvent()) |event| switch (event) {
.quit => return,
.key_down => |key| self.inputs.onKeyDown(key.keycode),
.key_up => |key| self.inputs.onKeyUp(key.keycode),
else => {},
};
// present the display (even if paused, in case the window was resized)
try self.video.present();
// wait for next frame
timer.tick();
}
} | src/Machine.zig |
const std = @import("std");
const assert = std.debug.assert;
const ascii = std.ascii;
const main = @import("main.zig");
const strings = @import("strings.zig");
const nodes = @import("nodes.zig");
const scanners = @import("scanners.zig");
const inlines = @import("inlines.zig");
const Options = @import("options.zig").Options;
const table = @import("table.zig");
const AutolinkProcessor = @import("autolink.zig").AutolinkProcessor;
const TAB_STOP = 4;
const CODE_INDENT = 4;
pub const Reference = struct {
url: []u8,
title: []u8,
};
pub const Parser = struct {
allocator: std.mem.Allocator,
refmap: std.StringHashMap(Reference),
hack_refmapKeys: std.ArrayList([]u8),
root: *nodes.AstNode,
current: *nodes.AstNode,
options: Options,
line_number: u32 = 0,
offset: usize = 0,
column: usize = 0,
first_nonspace: usize = 0,
first_nonspace_column: usize = 0,
indent: usize = 0,
blank: bool = false,
partially_consumed_tab: bool = false,
last_line_length: usize = 0,
special_chars: [256]bool = [_]bool{false} ** 256,
skip_chars: [256]bool = [_]bool{false} ** 256,
pub fn init(allocator: std.mem.Allocator, options: Options) !Parser {
var root = try nodes.AstNode.create(allocator, .{
.value = .Document,
.content = std.ArrayList(u8).init(allocator),
});
var parser = Parser{
.allocator = allocator,
.refmap = std.StringHashMap(Reference).init(allocator),
.hack_refmapKeys = std.ArrayList([]u8).init(allocator),
.root = root,
.current = root,
.options = options,
};
inlines.Subject.setCharsForOptions(&options, &parser.special_chars, &parser.skip_chars);
return parser;
}
pub fn deinit(self: *Parser) void {
var it = self.refmap.iterator();
while (it.next()) |entry| {
self.allocator.free(entry.key_ptr.*);
self.allocator.free(entry.value_ptr.url);
self.allocator.free(entry.value_ptr.title);
}
self.refmap.deinit();
}
pub fn feed(self: *Parser, s: []const u8) !void {
var i: usize = 0;
var sz = s.len;
var linebuf = std.ArrayList(u8).init(self.allocator);
defer linebuf.deinit();
while (i < sz) {
var process = true;
var eol = i;
while (eol < sz) {
if (strings.isLineEndChar(s[eol]))
break;
if (s[eol] == 0) {
process = false;
break;
}
eol += 1;
}
if (process) {
if (linebuf.items.len != 0) {
try linebuf.appendSlice(s[i..eol]);
try self.processLine(linebuf.items);
linebuf.items.len = 0;
} else if (sz > eol and s[eol] == '\n') {
try self.processLine(s[i .. eol + 1]);
} else {
try self.processLine(s[i..eol]);
}
i = eol;
if (i < sz and s[i] == '\r') i += 1;
if (i < sz and s[i] == '\n') i += 1;
} else {
assert(eol < sz and s[eol] == 0);
try linebuf.appendSlice(s[i..eol]);
try linebuf.appendSlice("\u{fffd}");
i = eol + 1;
}
}
}
pub fn finish(self: *Parser) !*nodes.AstNode {
try self.finalizeDocument();
try self.postprocessTextNodes();
return self.root;
}
fn findFirstNonspace(self: *Parser, line: []const u8) void {
self.first_nonspace = self.offset;
self.first_nonspace_column = self.column;
var chars_to_tab = TAB_STOP - (self.column % TAB_STOP);
while (true) {
if (self.first_nonspace >= line.len) {
break;
}
switch (line[self.first_nonspace]) {
' ' => {
self.first_nonspace += 1;
self.first_nonspace_column += 1;
chars_to_tab -= 1;
if (chars_to_tab == 0) {
chars_to_tab = TAB_STOP;
}
},
9 => {
self.first_nonspace += 1;
self.first_nonspace_column += chars_to_tab;
chars_to_tab = TAB_STOP;
},
else => break,
}
}
self.indent = self.first_nonspace_column - self.column;
self.blank = self.first_nonspace < line.len and strings.isLineEndChar(line[self.first_nonspace]);
}
fn processLine(self: *Parser, input: []const u8) !void {
var line: []const u8 = undefined;
var new_line: ?[]u8 = null;
if (input.len == 0 or !strings.isLineEndChar(input[input.len - 1])) {
new_line = try self.allocator.alloc(u8, input.len + 1);
std.mem.copy(u8, new_line.?, input);
new_line.?[input.len] = '\n';
line = new_line.?;
} else {
line = input;
}
self.offset = 0;
self.column = 0;
self.blank = false;
self.partially_consumed_tab = false;
if (self.line_number == 0 and line.len >= 3 and std.mem.eql(u8, line[0..3], "\u{feff}")) {
self.offset += 3;
}
self.line_number += 1;
const result = try self.checkOpenBlocks(line);
if (result.container) |last_matched_container| {
const current = self.current;
const container = try self.openNewBlocks(last_matched_container, line, result.all_matched);
if (current == self.current) {
try self.addTextToContainer(container, last_matched_container, line);
}
}
self.last_line_length = line.len;
if (self.last_line_length > 0 and line[self.last_line_length - 1] == '\n') {
self.last_line_length -= 1;
}
if (self.last_line_length > 0 and line[self.last_line_length - 1] == '\r') {
self.last_line_length -= 1;
}
if (new_line) |nl| self.allocator.free(nl);
}
const CheckOpenBlocksResult = struct {
all_matched: bool = false,
container: ?*nodes.AstNode,
};
fn checkOpenBlocks(self: *Parser, line: []const u8) !CheckOpenBlocksResult {
const result = try self.checkOpenBlocksInner(self.root, line);
if (result.container) |container| {
return CheckOpenBlocksResult{
.all_matched = result.all_matched,
.container = if (result.all_matched) container else container.parent.?,
};
}
return result;
}
fn checkOpenBlocksInner(self: *Parser, start_container: *nodes.AstNode, line: []const u8) !CheckOpenBlocksResult {
var container = start_container;
while (container.lastChildIsOpen()) {
container = container.last_child.?;
self.findFirstNonspace(line);
switch (container.data.value) {
.BlockQuote => {
if (!self.parseBlockQuotePrefix(line)) {
return CheckOpenBlocksResult{ .container = container };
}
},
.Item => |*nl| {
if (!self.parseNodeItemPrefix(line, container, nl)) {
return CheckOpenBlocksResult{ .container = container };
}
},
.CodeBlock => {
switch (try self.parseCodeBlockPrefix(line, container)) {
.DoNotContinue => {
return CheckOpenBlocksResult{ .container = null };
},
.NoMatch => {
return CheckOpenBlocksResult{ .container = container };
},
.Match => {},
}
},
.HtmlBlock => |nhb| {
if (!self.parseHtmlBlockPrefix(nhb.block_type)) {
return CheckOpenBlocksResult{ .container = container };
}
},
.Paragraph => {
if (self.blank) {
return CheckOpenBlocksResult{ .container = container };
}
},
.Table => {
if (!(try table.matches(self.allocator, line[self.first_nonspace..]))) {
return CheckOpenBlocksResult{ .container = container };
}
},
.Heading, .TableRow, .TableCell => {
return CheckOpenBlocksResult{ .container = container };
},
.Document, .List, .ThematicBreak, .Text, .SoftBreak, .LineBreak, .Code, .HtmlInline, .Emph, .Strong, .Strikethrough, .Link, .Image => {},
}
}
return CheckOpenBlocksResult{
.all_matched = true,
.container = container,
};
}
fn openNewBlocks(self: *Parser, input_container: *nodes.AstNode, line: []const u8, all_matched: bool) !*nodes.AstNode {
var container = input_container;
var maybe_lazy = switch (self.current.data.value) {
.Paragraph => true,
else => false,
};
var matched: usize = undefined;
var nl: nodes.NodeList = undefined;
var sc: scanners.SetextChar = undefined;
while (switch (container.data.value) {
.CodeBlock, .HtmlBlock => false,
else => true,
}) {
self.findFirstNonspace(line);
const indented = self.indent >= CODE_INDENT;
if (!indented and line[self.first_nonspace] == '>') {
const offset = self.first_nonspace + 1 - self.offset;
self.advanceOffset(line, offset, false);
if (strings.isSpaceOrTab(line[self.offset])) {
self.advanceOffset(line, 1, true);
}
container = try self.addChild(container, .BlockQuote);
} else if (!indented and try scanners.unwrap(scanners.atxHeadingStart(line[self.first_nonspace..]), &matched)) {
const heading_startpos = self.first_nonspace;
const offset = self.offset;
self.advanceOffset(line, heading_startpos + matched - offset, false);
container = try self.addChild(container, .{ .Heading = .{} });
var hashpos = std.mem.indexOfScalar(u8, line[self.first_nonspace..], '#').? + self.first_nonspace;
var level: u8 = 0;
while (line[hashpos] == '#') {
if (level < 6)
level += 1;
hashpos += 1;
}
container.data.value = .{ .Heading = .{ .level = level, .setext = false } };
} else if (!indented and try scanners.unwrap(scanners.openCodeFence(line[self.first_nonspace..]), &matched)) {
const first_nonspace = self.first_nonspace;
const offset = self.offset;
const ncb = nodes.NodeCodeBlock{
.fenced = true,
.fence_char = line[first_nonspace],
.fence_length = matched,
.fence_offset = first_nonspace - offset,
.info = null,
.literal = std.ArrayList(u8).init(self.allocator),
};
container = try self.addChild(container, .{ .CodeBlock = ncb });
self.advanceOffset(line, first_nonspace + matched - offset, false);
} else if (!indented and ((try scanners.htmlBlockStart(line[self.first_nonspace..], &matched)) or switch (container.data.value) {
.Paragraph => false,
else => try scanners.htmlBlockStart7(line[self.first_nonspace..], &matched),
})) {
const nhb = nodes.NodeHtmlBlock{
.block_type = @truncate(u8, matched),
.literal = std.ArrayList(u8).init(self.allocator),
};
container = try self.addChild(container, .{ .HtmlBlock = nhb });
} else if (!indented and switch (container.data.value) {
.Paragraph => try scanners.setextHeadingLine(line[self.first_nonspace..], &sc),
else => false,
}) {
const has_content = try self.resolveReferenceLinkDefinitions(&container.data.content);
if (has_content) {
container.data.value = .{
.Heading = .{
.level = switch (sc) {
.Equals => 1,
.Hyphen => 2,
},
.setext = true,
},
};
const adv = line.len - 1 - self.offset;
self.advanceOffset(line, adv, false);
}
} else if (!indented and !(switch (container.data.value) {
.Paragraph => !all_matched,
else => false,
}) and try scanners.unwrap(scanners.thematicBreak(line[self.first_nonspace..]), &matched)) {
container = try self.addChild(container, .ThematicBreak);
const adv = line.len - 1 - self.offset;
self.advanceOffset(line, adv, false);
} else if ((!indented or switch (container.data.value) {
.List => true,
else => false,
}) and self.indent < 4 and parseListMarker(line, self.first_nonspace, switch (container.data.value) {
.Paragraph => true,
else => false,
}, &matched, &nl)) {
const offset = self.first_nonspace + matched - self.offset;
self.advanceOffset(line, offset, false);
const save_partially_consumed_tab = self.partially_consumed_tab;
const save_offset = self.offset;
const save_column = self.column;
while (self.column - save_column <= 5 and strings.isSpaceOrTab(line[self.offset])) {
self.advanceOffset(line, 1, true);
}
const i = self.column - save_column;
if (i >= 5 or i < 1 or strings.isLineEndChar(line[self.offset])) {
nl.padding = matched + 1;
self.partially_consumed_tab = save_partially_consumed_tab;
self.offset = save_offset;
self.column = save_column;
if (i > 0)
self.advanceOffset(line, 1, true);
} else {
nl.padding = matched + i;
}
nl.marker_offset = self.indent;
if (switch (container.data.value) {
.List => |*mnl| !listsMatch(&nl, mnl),
else => true,
}) {
container = try self.addChild(container, .{ .List = nl });
}
container = try self.addChild(container, .{ .Item = nl });
} else if (indented and !maybe_lazy and !self.blank) {
self.advanceOffset(line, CODE_INDENT, true);
container = try self.addChild(container, .{
.CodeBlock = .{
.fenced = false,
.fence_char = 0,
.fence_length = 0,
.fence_offset = 0,
.info = null,
.literal = std.ArrayList(u8).init(self.allocator),
},
});
} else {
var replace: bool = undefined;
var new_container = if (!indented and self.options.extensions.table)
try table.tryOpeningBlock(self, container, line, &replace)
else
null;
if (new_container) |new| {
if (replace) {
container.insertAfter(new);
container.detachDeinit();
container = new;
} else {
container = new;
}
} else {
break;
}
}
if (container.data.value.acceptsLines()) {
break;
}
maybe_lazy = false;
}
return container;
}
pub fn addChild(self: *Parser, input_parent: *nodes.AstNode, value: nodes.NodeValue) !*nodes.AstNode {
var parent = input_parent;
while (!parent.data.value.canContainType(value)) {
parent = (try self.finalize(parent)).?;
}
var node = try nodes.AstNode.create(self.allocator, .{
.value = value,
.start_line = self.line_number,
.content = std.ArrayList(u8).init(self.allocator),
});
parent.append(node);
return node;
}
fn addTextToContainer(self: *Parser, input_container: *nodes.AstNode, last_matched_container: *nodes.AstNode, line: []const u8) !void {
var container = input_container;
self.findFirstNonspace(line);
if (self.blank) {
if (container.last_child) |last_child| {
last_child.data.last_line_blank = true;
}
}
container.data.last_line_blank = self.blank and
switch (container.data.value) {
.BlockQuote, .Heading, .ThematicBreak => false,
.CodeBlock => |ncb| !ncb.fenced,
.Item => container.first_child != null or container.data.start_line != self.line_number,
else => true,
};
var tmp = container;
while (tmp.parent) |parent| {
parent.data.last_line_blank = false;
tmp = parent;
}
if (self.current != last_matched_container and container == last_matched_container and !self.blank and self.current.data.value == .Paragraph) {
try self.addLine(self.current, line);
return;
}
while (self.current != last_matched_container) {
self.current = (try self.finalize(self.current)).?;
}
switch (container.data.value) {
.CodeBlock => {
try self.addLine(container, line);
},
.HtmlBlock => |nhb| {
try self.addLine(container, line);
const matches_end_condition = switch (nhb.block_type) {
1 => scanners.htmlBlockEnd1(line[self.first_nonspace..]),
2 => scanners.htmlBlockEnd2(line[self.first_nonspace..]),
3 => scanners.htmlBlockEnd3(line[self.first_nonspace..]),
4 => scanners.htmlBlockEnd4(line[self.first_nonspace..]),
5 => scanners.htmlBlockEnd5(line[self.first_nonspace..]),
else => false,
};
if (matches_end_condition) {
container = (try self.finalize(container)).?;
}
},
else => {
if (self.blank) {
// do nothing
} else if (container.data.value.acceptsLines()) {
var consider_line: []const u8 = line;
switch (container.data.value) {
.Heading => |nh| if (!nh.setext) {
consider_line = strings.chopTrailingHashtags(line);
},
else => {},
}
const count = self.first_nonspace - self.offset;
if (self.first_nonspace <= consider_line.len) {
self.advanceOffset(consider_line, count, false);
try self.addLine(container, consider_line);
}
} else {
container = try self.addChild(container, .Paragraph);
const count = self.first_nonspace - self.offset;
self.advanceOffset(line, count, false);
try self.addLine(container, line);
}
},
}
self.current = container;
}
fn addLine(self: *Parser, node: *nodes.AstNode, line: []const u8) !void {
assert(node.data.open);
if (self.partially_consumed_tab) {
self.offset += 1;
var chars_to_tab = TAB_STOP - (self.column % TAB_STOP);
while (chars_to_tab > 0) : (chars_to_tab -= 1) {
try node.data.content.append(' ');
}
}
if (self.offset < line.len) {
try node.data.content.appendSlice(line[self.offset..]);
}
}
fn finalizeDocument(self: *Parser) !void {
while (self.current != self.root) {
self.current = (try self.finalize(self.current)).?;
}
_ = try self.finalize(self.root);
try self.processInlines();
}
fn finalize(self: *Parser, node: *nodes.AstNode) !?*nodes.AstNode {
assert(node.data.open);
node.data.open = false;
const parent = node.parent;
switch (node.data.value) {
.Paragraph => {
const has_content = try self.resolveReferenceLinkDefinitions(&node.data.content);
if (!has_content) {
node.detachDeinit();
}
},
.CodeBlock => |*ncb| {
if (!ncb.fenced) {
strings.removeTrailingBlankLines(&node.data.content);
try node.data.content.append('\n');
} else {
var pos: usize = 0;
while (pos < node.data.content.items.len) : (pos += 1) {
if (strings.isLineEndChar(node.data.content.items[pos]))
break;
}
assert(pos < node.data.content.items.len);
var info = try strings.cleanUrl(self.allocator, node.data.content.items[0..pos]);
if (info.len != 0) {
ncb.info = info;
}
if (node.data.content.items[pos] == '\r') pos += 1;
if (node.data.content.items[pos] == '\n') pos += 1;
try node.data.content.replaceRange(0, pos, "");
}
std.mem.swap(std.ArrayList(u8), &ncb.literal, &node.data.content);
},
.HtmlBlock => |*nhb| {
std.mem.swap(std.ArrayList(u8), &nhb.literal, &node.data.content);
},
.List => |*nl| {
nl.tight = true;
var it = node.first_child;
while (it) |item| {
if (item.data.last_line_blank and item.next != null) {
nl.tight = false;
break;
}
var subit = item.first_child;
while (subit) |subitem| {
if (subitem.endsWithBlankLine() and (item.next != null or subitem.next != null)) {
nl.tight = false;
break;
}
subit = subitem.next;
}
if (!nl.tight) {
break;
}
it = item.next;
}
},
else => {},
}
return parent;
}
fn postprocessTextNodes(self: *Parser) !void {
var stack = try std.ArrayList(*nodes.AstNode).initCapacity(self.allocator, 1);
defer stack.deinit();
var children = std.ArrayList(*nodes.AstNode).init(self.allocator);
defer children.deinit();
try stack.append(self.root);
while (stack.popOrNull()) |node| {
var nch = node.first_child;
while (nch) |n| {
var this_bracket = false;
while (true) {
switch (n.data.value) {
.Text => |*root| {
var ns = n.next orelse {
try self.postprocessTextNode(n, root);
break;
};
switch (ns.data.value) {
.Text => |adj| {
const old_len = root.len;
root.* = try self.allocator.realloc(root.*, old_len + adj.len);
std.mem.copy(u8, root.*[old_len..], adj);
ns.detachDeinit();
},
else => {
try self.postprocessTextNode(n, root);
break;
},
}
},
.Link, .Image => {
this_bracket = true;
break;
},
else => break,
}
}
if (!this_bracket) {
try children.append(n);
}
nch = n.next;
}
while (children.popOrNull()) |child| try stack.append(child);
}
}
fn postprocessTextNode(self: *Parser, node: *nodes.AstNode, text: *[]u8) !void {
if (self.options.extensions.autolink) {
try AutolinkProcessor.init(self.allocator, text).process(node);
}
}
fn resolveReferenceLinkDefinitions(self: *Parser, content: *std.ArrayList(u8)) !bool {
var seeked: usize = 0;
var pos: usize = undefined;
var seek = content.items;
while (seek.len > 0 and seek[0] == '[' and try self.parseReferenceInline(seek, &pos)) {
seek = seek[pos..];
seeked += pos;
}
try content.replaceRange(0, seeked, "");
return !strings.isBlank(content.items);
}
fn parseReferenceInline(self: *Parser, content: []const u8, pos: *usize) !bool {
var subj = inlines.Subject.init(self.allocator, &self.refmap, &self.options, &self.special_chars, &self.skip_chars, content);
defer subj.deinit();
var lab = if (subj.linkLabel()) |l| lab: {
if (l.len == 0)
return false;
break :lab l;
} else return false;
if (subj.peekChar() orelse 0 != ':')
return false;
subj.pos += 1;
subj.spnl();
var url: []const u8 = undefined;
var match_len: usize = undefined;
if (!inlines.Subject.manualScanLinkUrl(subj.input[subj.pos..], &url, &match_len))
return false;
subj.pos += match_len;
const beforetitle = subj.pos;
subj.spnl();
const title_search: ?usize = if (subj.pos == beforetitle)
null
else
try scanners.linkTitle(subj.input[subj.pos..]);
const title = if (title_search) |title_match| title: {
const t = subj.input[subj.pos .. subj.pos + title_match];
subj.pos += title_match;
break :title try self.allocator.dupe(u8, t);
} else title: {
subj.pos = beforetitle;
break :title &[_]u8{};
};
defer self.allocator.free(title);
subj.skipSpaces();
if (!subj.skipLineEnd()) {
if (title.len > 0) {
subj.pos = beforetitle;
subj.skipSpaces();
if (!subj.skipLineEnd()) {
return false;
}
} else {
return false;
}
}
var normalized = try strings.normalizeLabel(self.allocator, lab);
if (normalized.len > 0) {
// refmap takes ownership of `normalized'.
const result = try subj.refmap.getOrPut(normalized);
if (!result.found_existing) {
result.value_ptr.* = Reference{
.url = try strings.cleanUrl(self.allocator, url),
.title = try strings.cleanTitle(self.allocator, title),
};
} else {
self.allocator.free(normalized);
}
}
pos.* = subj.pos;
return true;
}
fn processInlines(self: *Parser) !void {
try self.processInlinesNode(self.root);
}
fn processInlinesNode(self: *Parser, node: *nodes.AstNode) inlines.ParseError!void {
var it = node.descendantsIterator();
while (it.next()) |descendant| {
if (descendant.data.value.containsInlines()) {
try self.parseInlines(descendant);
}
}
}
fn parseInlines(self: *Parser, node: *nodes.AstNode) inlines.ParseError!void {
var content = strings.rtrim(node.data.content.items);
var subj = inlines.Subject.init(self.allocator, &self.refmap, &self.options, &self.special_chars, &self.skip_chars, content);
defer subj.deinit();
while (try subj.parseInline(node)) {}
try subj.processEmphasis(null);
while (subj.popBracket()) {}
}
pub fn advanceOffset(self: *Parser, line: []const u8, in_count: usize, columns: bool) void {
var count = in_count;
while (count > 0) {
switch (line[self.offset]) {
'\t' => {
const chars_to_tab = TAB_STOP - (self.column % TAB_STOP);
if (columns) {
self.partially_consumed_tab = chars_to_tab > count;
const chars_to_advance = std.math.min(count, chars_to_tab);
self.column += chars_to_advance;
self.offset += @as(u8, if (self.partially_consumed_tab) 0 else 1);
count -= chars_to_advance;
} else {
self.partially_consumed_tab = false;
self.column += chars_to_tab;
self.offset += 1;
count -= 1;
}
},
else => {
self.partially_consumed_tab = false;
self.offset += 1;
self.column += 1;
count -= 1;
},
}
}
}
fn parseBlockQuotePrefix(self: *Parser, line: []const u8) bool {
var indent = self.indent;
if (indent <= 3 and line[self.first_nonspace] == '>') {
self.advanceOffset(line, indent + 1, true);
if (strings.isSpaceOrTab(line[self.offset])) {
self.advanceOffset(line, 1, true);
}
return true;
}
return false;
}
fn parseNodeItemPrefix(self: *Parser, line: []const u8, container: *nodes.AstNode, nl: *const nodes.NodeList) bool {
if (self.indent >= nl.marker_offset + nl.padding) {
self.advanceOffset(line, nl.marker_offset + nl.padding, true);
return true;
} else if (self.blank and container.first_child != null) {
const offset = self.first_nonspace - self.offset;
self.advanceOffset(line, offset, false);
return true;
}
return false;
}
const CodeBlockPrefixParseResult = enum {
DoNotContinue,
NoMatch,
Match,
};
fn parseCodeBlockPrefix(self: *Parser, line: []const u8, container: *nodes.AstNode) !CodeBlockPrefixParseResult {
const ncb = switch (container.data.value) {
.CodeBlock => |i| i,
else => unreachable,
};
if (!ncb.fenced) {
if (self.indent >= CODE_INDENT) {
self.advanceOffset(line, CODE_INDENT, true);
return .Match;
} else if (self.blank) {
const offset = self.first_nonspace - self.offset;
self.advanceOffset(line, offset, false);
return .Match;
}
return .NoMatch;
}
const matched = if (self.indent <= 3 and line[self.first_nonspace] == ncb.fence_char)
(try scanners.closeCodeFence(line[self.first_nonspace..])) orelse 0
else
0;
if (matched >= ncb.fence_length) {
self.advanceOffset(line, matched, false);
self.current = (try self.finalize(container)).?;
return .DoNotContinue;
}
var i = ncb.fence_offset;
while (i > 0 and strings.isSpaceOrTab(line[self.offset])) : (i -= 1) {
self.advanceOffset(line, 1, true);
}
return .Match;
}
fn parseHtmlBlockPrefix(self: *Parser, t: u8) bool {
return switch (t) {
1, 2, 3, 4, 5 => true,
6, 7 => !self.blank,
else => unreachable,
};
}
fn parseListMarker(line: []const u8, input_pos: usize, interrupts_paragraph: bool, matched: *usize, nl: *nodes.NodeList) bool {
var pos = input_pos;
var c = line[pos];
const startpos = pos;
if (c == '*' or c == '-' or c == '+') {
pos += 1;
if (!ascii.isSpace(line[pos])) {
return false;
}
if (interrupts_paragraph) {
var i = pos;
while (strings.isSpaceOrTab(line[i])) : (i += 1) {}
if (line[i] == '\n') {
return false;
}
}
matched.* = pos - startpos;
nl.* = .{
.list_type = .Bullet,
.marker_offset = 0,
.padding = 0,
.start = 1,
.delimiter = .Period,
.bullet_char = c,
.tight = false,
};
return true;
}
if (ascii.isDigit(c)) {
var start: usize = 0;
var digits: u8 = 0;
while (digits < 9 and ascii.isDigit(line[pos])) {
start = (10 * start) + (line[pos] - '0');
pos += 1;
digits += 1;
}
if (interrupts_paragraph and start != 1) {
return false;
}
c = line[pos];
if (c != '.' and c != ')') {
return false;
}
pos += 1;
if (!ascii.isSpace(line[pos])) {
return false;
}
if (interrupts_paragraph) {
var i = pos;
while (strings.isSpaceOrTab(line[i])) : (i += 1) {}
if (strings.isLineEndChar(line[i])) {
return false;
}
}
matched.* = pos - startpos;
nl.* = .{
.list_type = .Ordered,
.marker_offset = 0,
.padding = 0,
.start = start,
.delimiter = if (c == '.')
.Period
else
.Paren,
.bullet_char = 0,
.tight = false,
};
return true;
}
return false;
}
fn listsMatch(list_data: *const nodes.NodeList, item_data: *const nodes.NodeList) bool {
return list_data.list_type == item_data.list_type and list_data.delimiter == item_data.delimiter and list_data.bullet_char == item_data.bullet_char;
}
};
fn expectMarkdownHTML(options: Options, markdown: []const u8, html: []const u8) !void {
var output = try main.testMarkdownToHtml(options, markdown);
defer std.testing.allocator.free(output);
try std.testing.expectEqualStrings(html, output);
}
test "convert simple emphases" {
try expectMarkdownHTML(.{},
\\hello, _world_ __world__ ___world___ *_world_* **_world_** *__world__*
\\
\\this is `yummy`
\\
,
\\<p>hello, <em>world</em> <strong>world</strong> <em><strong>world</strong></em> <em><em>world</em></em> <strong><em>world</em></strong> <em><strong>world</strong></em></p>
\\<p>this is <code>yummy</code></p>
\\
);
}
test "smart quotes" {
try expectMarkdownHTML(.{ .parse = .{ .smart = true } }, "\"Hey,\" she said. \"What's 'up'?\"\n", "<p>“Hey,” she said. “What’s ‘up’?”</p>\n");
}
test "handles EOF without EOL" {
try expectMarkdownHTML(.{}, "hello", "<p>hello</p>\n");
}
test "accepts multiple lines" {
try expectMarkdownHTML(.{}, "hello\nthere\n", "<p>hello\nthere</p>\n");
try expectMarkdownHTML(.{ .render = .{ .hard_breaks = true } }, "hello\nthere\n", "<p>hello<br />\nthere</p>\n");
}
test "smart hyphens" {
try expectMarkdownHTML(.{ .parse = .{ .smart = true } }, "hyphen - en -- em --- four ---- five ----- six ------ seven -------\n", "<p>hyphen - en – em — four –– five —– six —— seven —––</p>\n");
}
test "handles tabs" {
try expectMarkdownHTML(.{}, "\tfoo\tbaz\t\tbim\n", "<pre><code>foo\tbaz\t\tbim\n</code></pre>\n");
try expectMarkdownHTML(.{}, " \tfoo\tbaz\t\tbim\n", "<pre><code>foo\tbaz\t\tbim\n</code></pre>\n");
try expectMarkdownHTML(.{}, " - foo\n\n\tbar\n", "<ul>\n<li>\n<p>foo</p>\n<p>bar</p>\n</li>\n</ul>\n");
try expectMarkdownHTML(.{}, "#\tFoo\n", "<h1>Foo</h1>\n");
try expectMarkdownHTML(.{}, "*\t*\t*\t\n", "<hr />\n");
}
test "escapes" {
try expectMarkdownHTML(.{}, "\\## foo\n", "<p>## foo</p>\n");
}
test "setext heading override pointy" {
try expectMarkdownHTML(.{}, "<a title=\"a lot\n---\nof dashes\"/>\n", "<h2><a title="a lot</h2>\n<p>of dashes"/></p>\n");
}
test "fenced code blocks" {
try expectMarkdownHTML(.{}, "```\n<\n >\n```\n", "<pre><code><\n >\n</code></pre>\n");
try expectMarkdownHTML(.{}, "````\naaa\n```\n``````\n", "<pre><code>aaa\n```\n</code></pre>\n");
}
test "html blocks" {
try expectMarkdownHTML(.{ .render = .{ .unsafe = true } },
\\_world_.
\\</pre>
,
\\<p><em>world</em>.
\\</pre></p>
\\
);
try expectMarkdownHTML(.{ .render = .{ .unsafe = true } },
\\<table><tr><td>
\\<pre>
\\**Hello**,
\\
\\_world_.
\\</pre>
\\</td></tr></table>
,
\\<table><tr><td>
\\<pre>
\\**Hello**,
\\<p><em>world</em>.
\\</pre></p>
\\</td></tr></table>
\\
);
try expectMarkdownHTML(.{ .render = .{ .unsafe = true } },
\\<DIV CLASS="foo">
\\
\\*Markdown*
\\
\\</DIV>
,
\\<DIV CLASS="foo">
\\<p><em>Markdown</em></p>
\\</DIV>
\\
);
try expectMarkdownHTML(.{ .render = .{ .unsafe = true } },
\\<pre language="haskell"><code>
\\import Text.HTML.TagSoup
\\
\\main :: IO ()
\\main = print $ parseTags tags
\\</code></pre>
\\okay
\\
,
\\<pre language="haskell"><code>
\\import Text.HTML.TagSoup
\\
\\main :: IO ()
\\main = print $ parseTags tags
\\</code></pre>
\\<p>okay</p>
\\
);
}
test "links" {
try expectMarkdownHTML(.{}, "[foo](/url)\n", "<p><a href=\"/url\">foo</a></p>\n");
try expectMarkdownHTML(.{}, "[foo](/url \"title\")\n", "<p><a href=\"/url\" title=\"title\">foo</a></p>\n");
}
test "link reference definitions" {
try expectMarkdownHTML(.{}, "[foo]: /url \"title\"\n\n[foo]\n", "<p><a href=\"/url\" title=\"title\">foo</a></p>\n");
try expectMarkdownHTML(.{}, "[foo]: /url\\bar\\*baz \"foo\\\"bar\\baz\"\n\n[foo]\n", "<p><a href=\"/url%5Cbar*baz\" title=\"foo"bar\\baz\">foo</a></p>\n");
}
test "tables" {
try expectMarkdownHTML(.{ .extensions = .{ .table = true } },
\\| foo | bar |
\\| --- | --- |
\\| baz | bim |
\\
,
\\<table>
\\<thead>
\\<tr>
\\<th>foo</th>
\\<th>bar</th>
\\</tr>
\\</thead>
\\<tbody>
\\<tr>
\\<td>baz</td>
\\<td>bim</td>
\\</tr>
\\</tbody>
\\</table>
\\
);
}
test "strikethroughs" {
try expectMarkdownHTML(.{ .extensions = .{ .strikethrough = true } }, "Hello ~world~ there.\n", "<p>Hello <del>world</del> there.</p>\n");
}
test "images" {
try expectMarkdownHTML(.{}, "[](/uri)\n", "<p><a href=\"/uri\"><img src=\"moon.jpg\" alt=\"moon\" /></a></p>\n");
}
test "autolink" {
try expectMarkdownHTML(.{ .extensions = .{ .autolink = true } }, "www.commonmark.org\n", "<p><a href=\"http://www.commonmark.org\">www.commonmark.org</a></p>\n");
try expectMarkdownHTML(.{ .extensions = .{ .autolink = true } }, "http://commonmark.org\n", "<p><a href=\"http://commonmark.org\">http://commonmark.org</a></p>\n");
try expectMarkdownHTML(.{ .extensions = .{ .autolink = true } }, "[email protected]\n", "<p><a href=\"mailto:<EMAIL>\"><EMAIL></a></p>\n");
}
test "header anchors" {
try expectMarkdownHTML(.{ .render = .{ .header_anchors = true } },
\\# Hi.
\\## Hi 1.
\\### Hi.
\\#### Hello.
\\##### Hi.
\\###### Hello.
\\# Isn't it grand?
\\
,
\\<h1><a href="#hi" id="hi"></a>Hi.</h1>
\\<h2><a href="#hi-1" id="hi-1"></a>Hi 1.</h2>
\\<h3><a href="#hi-2" id="hi-2"></a>Hi.</h3>
\\<h4><a href="#hello" id="hello"></a>Hello.</h4>
\\<h5><a href="#hi-3" id="hi-3"></a>Hi.</h5>
\\<h6><a href="#hello-1" id="hello-1"></a>Hello.</h6>
\\<h1><a href="#isnt-it-grand" id="isnt-it-grand"></a>Isn't it grand?</h1>
\\
);
} | src/parser.zig |
const std = @import("std");
const getty = @import("../../../lib.zig");
const ArrayVisitor = @import("array.zig").Visitor;
const BoolVisitor = @import("bool.zig");
const EnumVisitor = @import("enum.zig").Visitor;
const FloatVisitor = @import("float.zig").Visitor;
const IntVisitor = @import("int.zig").Visitor;
const OptionalVisitor = @import("optional.zig").Visitor;
const SliceVisitor = @import("slice.zig").Visitor;
const StructVisitor = @import("struct.zig").Visitor;
const VoidVisitor = @import("void.zig");
pub fn Visitor(comptime Pointer: type) type {
if (@typeInfo(Pointer) != .Pointer or @typeInfo(Pointer).Pointer.size != .One) {
@compileError("expected one pointer, found `" ++ @typeName(Pointer) ++ "`");
}
return struct {
allocator: std.mem.Allocator,
const Self = @This();
const impl = @"impl Visitor"(Pointer);
pub usingnamespace getty.de.Visitor(
Self,
impl.visitor.Value,
impl.visitor.visitBool,
impl.visitor.visitEnum,
impl.visitor.visitFloat,
impl.visitor.visitInt,
impl.visitor.visitMap,
impl.visitor.visitNull,
impl.visitor.visitSequence,
impl.visitor.visitString,
impl.visitor.visitSome,
impl.visitor.visitVoid,
);
};
}
fn @"impl Visitor"(comptime Pointer: type) type {
const Self = Visitor(Pointer);
return struct {
pub const visitor = struct {
pub const Value = Pointer;
pub fn visitBool(self: Self, comptime Error: type, input: bool) Error!Value {
const value = try self.allocator.create(Child);
errdefer getty.de.free(self.allocator, value);
var v = childVisitor(self.allocator);
value.* = try v.visitor().visitBool(Error, input);
return value;
}
pub fn visitEnum(self: Self, comptime Error: type, input: anytype) Error!Value {
const value = try self.allocator.create(Child);
errdefer getty.de.free(self.allocator, value);
var v = childVisitor(self.allocator);
value.* = try v.visitor().visitEnum(Error, input);
return value;
}
pub fn visitFloat(self: Self, comptime Error: type, input: anytype) Error!Value {
const value = try self.allocator.create(Child);
errdefer getty.de.free(self.allocator, value);
var v = childVisitor(self.allocator);
value.* = try v.visitor().visitFloat(Error, input);
return value;
}
pub fn visitInt(self: Self, comptime Error: type, input: anytype) Error!Value {
const value = try self.allocator.create(Child);
errdefer getty.de.free(self.allocator, value);
var v = childVisitor(self.allocator);
value.* = try v.visitor().visitInt(Error, input);
return value;
}
pub fn visitMap(self: Self, mapAccess: anytype) @TypeOf(mapAccess).Error!Value {
const value = try self.allocator.create(Child);
errdefer getty.de.free(self.allocator, value);
var v = childVisitor(self.allocator);
value.* = try v.visitor().visitMap(mapAccess);
return value;
}
pub fn visitNull(self: Self, comptime Error: type) Error!Value {
const value = try self.allocator.create(Child);
errdefer getty.de.free(self.allocator, value);
var v = childVisitor(self.allocator);
value.* = try v.visitor().visitNull(Error);
return value;
}
pub fn visitSequence(self: Self, sequenceAccess: anytype) @TypeOf(sequenceAccess).Error!Value {
const value = try self.allocator.create(Child);
errdefer getty.de.free(self.allocator, value);
var v = childVisitor(self.allocator);
value.* = try v.visitor().visitSequence(sequenceAccess);
return value;
}
pub fn visitString(self: Self, comptime Error: type, input: anytype) Error!Value {
const value = try self.allocator.create(Child);
errdefer self.allocator.destroy(value);
var v = childVisitor(self.allocator);
value.* = try v.visitor().visitString(Error, input);
return value;
}
pub fn visitSome(self: Self, deserializer: anytype) @TypeOf(deserializer).Error!Value {
const value = try self.allocator.create(Child);
errdefer getty.de.free(self.allocator, value);
var v = childVisitor(self.allocator);
value.* = try v.visitor().visitSome(deserializer);
return value;
}
pub fn visitVoid(self: Self, comptime Error: type) Error!Value {
const value = try self.allocator.create(Child);
errdefer getty.de.free(self.allocator, value);
var v = childVisitor(self.allocator);
value.* = try v.visitor().visitVoid(Error);
return value;
}
fn childVisitor(allocator: std.mem.Allocator) ChildVisitor {
return switch (@typeInfo(Child)) {
.Bool, .ComptimeFloat, .ComptimeInt, .Float, .Int, .Void => .{},
.Array, .Enum, .Optional, .Pointer, .Struct => .{ .allocator = allocator },
else => unreachable,
};
}
const Child = std.meta.Child(Pointer);
const ChildVisitor = switch (@typeInfo(Child)) {
.Array => ArrayVisitor(Child),
.Bool => BoolVisitor,
.Enum => EnumVisitor(Child),
.Float, .ComptimeFloat => FloatVisitor(Child),
.Int, .ComptimeInt => IntVisitor(Child),
.Optional => OptionalVisitor(Child),
.Pointer => |info| switch (info.size) {
.One => Visitor(Child),
.Slice => SliceVisitor(Child),
else => @compileError("pointer type is not supported"),
},
.Struct => |info| switch (info.is_tuple) {
false => StructVisitor(Child),
true => @compileError("tuple deserialization is not supported"),
},
.Void => VoidVisitor,
else => @compileError("type `" ++ @typeName(Child) ++ "` is not supported"),
};
};
};
} | src/de/impl/visitor/pointer.zig |
const std = @import("std");
const options = @import("build_options");
const datetime = @import("datetime");
const clap = @import("clap");
const zfetch = @import("zfetch");
const folders = @import("known-folders");
const Channel = @import("utils/channel.zig").Channel;
const senseUserTZ = @import("utils/sense_tz.zig").senseUserTZ;
const remote = @import("remote.zig");
const Network = @import("Network.zig");
const Terminal = @import("Terminal.zig");
const Chat = @import("Chat.zig");
pub const io_mode = .evented;
pub const Event = union(enum) {
display: Terminal.Event,
network: Network.Event,
remote: remote.Server.Event,
};
// for my xdg fans out there
pub const known_folders_config = .{
.xdg_on_mac = true,
};
pub const BorkConfig = struct {
const version = 1;
const path = std.fmt.comptimePrint(".bork/config_v{d}.json", .{version});
const AfkPosition = enum {
top,
hover,
bottom,
pub fn jsonStringify(
self: AfkPosition,
_: std.json.StringifyOptions,
w: std.fs.File.Writer,
) !void {
try w.print(
\\"{s}"
, .{@tagName(self)});
}
};
nick: []const u8,
top_emoji: []const u8 = "⚡",
remote: bool = false,
remote_port: u16 = default_port,
afk_position: AfkPosition = .bottom,
// TODO what's the right size for port numbers?
const default_port: u16 = 6226;
};
var log_level: std.log.Level = .warn;
const Subcommand = enum {
@"--help",
@"-h",
start,
links,
send,
ban,
afk,
quit,
reconnect,
};
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var alloc = gpa.allocator();
var it = try clap.args.OsIterator.init(alloc);
defer it.deinit();
const subcommand = subcommand: {
const subc_string = (try it.next()) orelse {
printHelp();
return;
};
break :subcommand std.meta.stringToEnum(Subcommand, subc_string) orelse {
std.debug.print("Invalid subcommand.\n\n", .{});
printHelp();
return;
};
};
const cat = try get_config_and_token(alloc, subcommand == .start);
const config = cat.config;
const token = cat.token;
// const config = BorkConfig{ .nick = "blah" };
// const token = "blah";
switch (subcommand) {
.start => try bork_start(alloc, config, token),
.send => try remote.client.send(alloc, config, &it),
.quit => try remote.client.quit(alloc, config, &it),
.reconnect => try remote.client.reconnect(alloc, config, &it),
.links => try remote.client.links(alloc, config, &it),
.afk => try remote.client.afk(alloc, config, &it),
.ban => try remote.client.ban(alloc, config, &it),
.@"--help", .@"-h" => printHelp(),
}
}
fn bork_start(alloc: std.mem.Allocator, config: BorkConfig, token: []const u8) !void {
// king's fault
defer if (config.remote) std.os.exit(0);
var buf: [24]Event = undefined;
var ch = Channel(Event).init(&buf);
// If remote control is enabled, do that first
// so that we can immediately know if there's
// another instance of Bork running.
var remote_server: remote.Server = undefined;
if (config.remote) {
remote_server.init(config, token, alloc, &ch) catch |err| {
switch (err) {
error.AddressInUse => {
std.debug.print(
\\ Unable to start Bork, port {} is already in use.
\\ Make sure all other instances of Bork are closed first.
\\
, .{config.remote_port});
},
else => {
std.debug.print(
\\ Unable to listen for remote control.
\\ Error: {}
\\
, .{err});
},
}
std.os.exit(1);
};
}
defer if (config.remote) remote_server.deinit();
var display = try Terminal.init(alloc, &ch, config);
defer display.deinit();
var network: Network = undefined;
try network.init(alloc, &ch, config.nick, token, try senseUserTZ(alloc));
defer network.deinit();
var chat = Chat{ .allocator = alloc, .nick = config.nick };
// Initial paint!
try display.renderChat(&chat);
// Main control loop
var chaos = false;
while (true) {
var need_repaint = false;
const event = ch.get();
switch (event) {
.remote => |re| {
switch (re) {
.quit => return,
.reconnect => {
network.askToReconnect();
},
.send => |msg| {
std.log.debug("got send event in channel: {s}", .{msg});
network.sendCommand(.{ .message = msg });
},
.links => |conn| {
remote.Server.replyLinks(&chat, conn);
},
.afk => |afk| {
try display.setAfkMessage(afk.target_time, afk.reason, afk.title);
need_repaint = true;
},
}
},
.display => |de| {
switch (de) {
// TODO: SIGWINCH is disabled because of
// rendering bugs. Re-enable .calm
// and .chaos when restoring resize
// signal support
.chaos => {
// chaos = true;
},
.calm => {
// chaos = false;
// try display.sizeChanged();
// need_repaint = true;
},
.dirty => {
try display.sizeChanged();
need_repaint = true;
},
.disableCtrlCMessage => {
need_repaint = try display.toggleCtrlCMessage(false);
},
.other => |c| {
std.log.debug("[key] [{s}]", .{c});
switch (c[0]) {
'r', 'R' => {
try display.sizeChanged();
need_repaint = true;
chaos = false;
},
else => {},
}
},
.leftClick => |pos| {
std.log.debug("click at {}", .{pos});
need_repaint = try display.handleClick(pos.row - 1, pos.col - 1);
},
.CTRL_C => {
if (config.remote) {
// TODO: show something
need_repaint = try display.toggleCtrlCMessage(true);
} else {
return;
}
},
.up, .wheelUp, .pageUp => {
need_repaint = chat.scroll(.up, 1);
},
.down, .wheelDown, .pageDown => {
need_repaint = chat.scroll(.down, 1);
},
.escape, .right, .left, .tick => {},
}
},
.network => |ne| switch (ne) {
.connected => {},
.disconnected => {
try chat.setConnectionStatus(.disconnected);
need_repaint = true;
},
.reconnected => {
try chat.setConnectionStatus(.reconnected);
need_repaint = true;
},
.message => |m| {
std.log.debug("got msg!", .{});
// Terminal wants to pre-render the message
// and keep a small buffer attached to the message
// as a form of caching.
const msg = try display.prepareMessage(m);
need_repaint = chat.addMessage(msg);
},
.clear => |c| {
display.clearActiveInteraction(c);
chat.clearChat(c);
need_repaint = true;
},
},
}
need_repaint = need_repaint or display.needAnimationFrame();
if (need_repaint and !chaos) {
try display.renderChat(&chat);
}
}
// TODO: implement real cleanup
}
var log_path: ?[]const u8 = null;
var log_file: ?std.fs.File = null;
pub fn log(
comptime level: std.log.Level,
comptime scope: @Type(.EnumLiteral),
comptime format: []const u8,
args: anytype,
) void {
nosuspend {
const scope_prefix = "(" ++ @tagName(scope) ++ "): ";
const prefix = "[" ++ @tagName(level) ++ "] " ++ scope_prefix;
const mutex = std.debug.getStderrMutex();
mutex.lock();
defer mutex.unlock();
const l = log_file orelse blk: {
const file_path = log_path orelse if (options.local)
"bork-local.log"
else
return; // no logs in this case, too bad
const log_inner = std.fs.cwd().createFile(file_path, .{ .truncate = false, .intended_io_mode = .blocking }) catch return;
const end = log_inner.getEndPos() catch return;
log_inner.seekTo(end) catch return;
log_file = log_inner;
break :blk log_inner;
};
const writer = l.writer();
writer.print(prefix ++ format ++ "\n", args) catch return;
}
}
pub fn panic(msg: []const u8, trace: ?*std.builtin.StackTrace) noreturn {
nosuspend Terminal.panic();
log(.err, .default, "{s}", .{msg});
std.builtin.default_panic(msg, trace);
}
fn printHelp() void {
std.debug.print(
\\Bork is a TUI chat client for Twitch.
\\
\\Available commands: start, quit, send, links, ban, unban, afk.
\\
\\Examples:
\\ ./bork start
\\ ./bork quit
\\ ./bork reconnect
\\ ./bork send "welcome to my stream Kappa"
\\ ./bork links
\\ ./bork ban "baduser"
\\ ./bork unban "innocentuser"
\\ ./bork afk 25m "dinner"
\\
\\Use `bork <command> --help` to get subcommand-specific information.
\\
, .{});
}
const ConfigAndToken = struct {
config: BorkConfig,
token: []const u8,
};
fn get_config_and_token(alloc: std.mem.Allocator, check_token: bool) !ConfigAndToken {
var base_path = (try folders.getPath(alloc, .home)) orelse
(try folders.getPath(alloc, .executable_dir)) orelse
@panic("couldn't find a way of creating a config file");
var base = try std.fs.openDirAbsolute(base_path, .{});
defer base.close();
// Ensure existence of .bork/
try base.makePath(".bork");
// Prepare the log_file path for `log`.
{
const mutex = std.debug.getStderrMutex();
mutex.lock();
defer mutex.unlock();
const log_name = if (options.local) "bork-local.log" else "bork.log";
log_path = try std.fmt.allocPrint(alloc, "{s}/.bork/{s}", .{ base_path, log_name });
}
// Check if we still have an old .bork-oauth file that needs to be migrated
var old = cleanupOldTokenAndGreet(alloc) catch null;
var config: BorkConfig = config: {
const file = base.openFile(BorkConfig.path, .{}) catch |err| switch (err) {
else => return err,
error.FileNotFound => break :config try create_config(alloc, base, base_path, old == null),
};
defer file.close();
const config_json = try file.reader().readAllAlloc(alloc, 4096);
var stream = std.json.TokenStream.init(config_json);
const res = try std.json.parse(
BorkConfig,
&stream,
.{ .allocator = alloc },
);
alloc.free(config_json);
break :config res;
};
const port_override = std.os.getenv("BORK_PORT");
if (port_override) |po| config.remote_port = try std.fmt.parseInt(u16, po, 10);
const token: []const u8 = token: {
const file = base.openFile(".bork/token.secret", .{}) catch |err| switch (err) {
else => return err,
error.FileNotFound => {
if (old) |o| {
var token_file = try base.createFile(".bork/token.secret", .{});
defer token_file.close();
try token_file.writer().print("{s}\n", .{o.token});
break :token o.token;
}
break :token try create_token(alloc, base, .new);
},
};
defer file.close();
const token_raw = try file.reader().readAllAlloc(alloc, 4096);
const token = std.mem.trim(u8, token_raw, " \n");
if (check_token) {
// Check that the token is not expired in the meantime
if (try Network.checkTokenValidity(alloc, token)) {
break :token token;
}
} else {
break :token token;
}
// Token needs to be renewed
break :token try create_token(alloc, base, .renew);
};
// Only delete the file if everything went ok.
if (old) |*o| o.tryDeleteFile();
return ConfigAndToken{
.config = config,
.token = token,
};
}
const OldTokenAndPath = struct {
const file_name = ".bork-oauth";
token: []const u8,
dir: std.fs.Dir,
pub fn tryDeleteFile(self: *OldTokenAndPath) void {
defer self.dir.close();
self.dir.deleteFile(file_name) catch |err| {
std.debug.print(
\\Error while trying to delete the old .bork-oauth file:
\\{}
\\
, .{err});
};
}
};
fn cleanupOldTokenAndGreet(alloc: std.mem.Allocator) !OldTokenAndPath {
// Find out it the user has an old bork auth token file
const old_dir_p = std.os.getenv("HOME") orelse ".";
var old_dir = try std.fs.openDirAbsolute(old_dir_p, .{});
errdefer old_dir.close();
// error.FileNotFound will make us bail out
const old_oauth_file = try old_dir.openFile(OldTokenAndPath.file_name, .{});
defer old_oauth_file.close();
const old_oauth = try old_oauth_file.reader().readAllAlloc(alloc, 150);
return OldTokenAndPath{ .token = old_oauth, .dir = old_dir };
}
fn create_config(alloc: std.mem.Allocator, base: std.fs.Dir, base_path: []const u8, is_new_user: bool) !BorkConfig {
const in = std.io.getStdIn();
const in_reader = in.reader();
if (is_new_user) {
std.debug.print(
\\
\\ Hi, welcome to Bork!
\\ Please input your Twich username.
\\
\\ Your Twitch username:
, .{});
} else {
std.debug.print(
\\
\\ Hi, you seem to be a long time user of Bork!
\\
\\ Thank you for putting up with the jankyness as the project
\\ moved forward and became a reasonably functional Twitch
\\ chat application.
\\
\\ This new release of bork features some improvements
\\ that should make you happy!
\\
\\ - No more panicky stack traces when quitting Bork!
\\ - No more bork.log files created in random directories!
\\ - Bork now will automatically repaint on window resize
\\ when running on Linux (macOS seems to have issues).
\\ - The old `.bork-oauth` file has been cleaned up and the
\\ token is now stored inside `.bork/` alongside a config
\\ file and `bork.log` which has finally found a foreverhome.
\\
\\ Your bork config dir is located here:
\\
\\ {s}/.bork
\\
\\ There are also more features that will be presented soon,
\\ this was a special thank you note for the people that have
\\ been using bork for long enough to have had to pass their
\\ Twitch username as a command line argument every time they
\\ stated Bork.
\\
\\ Now that we have a config file we can finally have you
\\ input it once and for all :^)
\\
\\ Your Twitch username:
, .{base_path});
}
const nickname: []const u8 = while (true) {
const maybe_nick_raw = try in_reader.readUntilDelimiterOrEofAlloc(alloc, '\n', 1024);
if (maybe_nick_raw) |nick_raw| {
const nick = std.mem.trim(u8, nick_raw, " ");
// TODO: proper validation rules
if (nick.len >= 3) {
break nick;
}
alloc.free(nick_raw);
}
std.debug.print(
\\
\\ The username provided doesn't seem valid.
\\ Please try again.
\\
\\ Your Twitch username:
, .{});
} else unreachable; // TODO: remove in stage 2
std.debug.print(
\\
\\ OK!
\\
, .{});
const remote_port: ?u16 = remote_port: {
// Inside this scope user input is set to immediate mode.
{
const original_termios = try std.os.tcgetattr(in.handle);
defer std.os.tcsetattr(in.handle, .FLUSH, original_termios) catch {};
{
var termios = original_termios;
// set immediate input mode
termios.lflag &= ~@as(std.os.system.tcflag_t, std.os.system.ICANON);
try std.os.tcsetattr(in.handle, .FLUSH, termios);
}
std.debug.print(
\\
\\
\\ ===========================================================
\\
\\ Bork allows you to interact with it in two ways: clicking
\\ on messages, which will allow you to highlight them, and
\\ by invoking the Bork executable with various subcommands
\\ that will interact with the main Bork instance.
\\
\\ This second mode will allow you to send messages to Twitch
\\ chat, display popups in Bork, set AFK status, etc.
\\
\\ NOTE: some of these commands are still WIP :^)
\\
\\ Press any key to continue reading...
\\
\\
, .{});
_ = try in_reader.readByte();
std.debug.print(
\\ ======> ! IMPORTANT ! <======
\\ To protect you from accidentally closing Bork while
\\ streaming, with this feature enabled, Bork will not
\\ close when you press CTRL+C.
\\
\\ To close it, you will instead have to execute in a
\\ separate shell:
\\
\\ `bork quit`
\\
\\ NOTE: yes, this command is already implemented :^)
\\
\\ To enable this second feature Bork will need to listen
\\ to a port on localhost.
\\
\\ Enable remote control? [Y/n]
, .{});
const enable = try in_reader.readByte();
switch (enable) {
else => {
std.debug.print(
\\
\\
\\ CLI control is disabled.
\\ You can enable it in the future by editing the
\\ configuration file.
\\
\\
, .{});
break :remote_port null;
},
'y', 'Y', '\n' => {},
}
}
std.debug.print(
\\
\\ CLI control enabled!
\\ Which port should Bork listen to?
\\
\\ Port? [{}]:
, .{BorkConfig.default_port});
while (true) {
const maybe_port = try in_reader.readUntilDelimiterOrEofAlloc(alloc, '\n', 1024);
if (maybe_port) |port_raw| {
if (port_raw.len == 0) {
break :remote_port BorkConfig.default_port;
}
break :remote_port std.fmt.parseInt(u16, port_raw, 10) catch {
std.debug.print(
\\
\\ Invalid port value.
\\
\\ Port? [{}]
, .{BorkConfig.default_port});
continue;
};
} else {
std.debug.print(
\\
\\ Success!
\\
\\
, .{});
break :remote_port BorkConfig.default_port;
}
}
};
var result: BorkConfig = .{
.nick = nickname,
};
if (remote_port) |r| {
result.remote = true;
result.remote_port = r;
} else {
result.remote = false;
}
// create the config file
var file = try base.createFile(BorkConfig.path, .{});
try std.json.stringify(result, .{}, file.writer());
return result;
}
const TokenActon = enum { new, renew };
fn create_token(alloc: std.mem.Allocator, base: std.fs.Dir, action: TokenActon) ![]const u8 {
var in = std.io.getStdIn();
const original_termios = try std.os.tcgetattr(in.handle);
var termios = original_termios;
// disable echo
termios.lflag &= ~@as(std.os.system.tcflag_t, std.os.system.ECHO);
try std.os.tcsetattr(in.handle, .FLUSH, termios);
defer std.os.tcsetattr(in.handle, .FLUSH, original_termios) catch {};
switch (action) {
.new => std.debug.print(
\\
\\ ======================================================
\\
\\ Bork needs a Twitch OAuth token to connect to Twitch.
\\ Unfortunately, this procedure can't be fully automated
\\ and you will have to repeat it when the token expires
\\ (Bork will let you know when that happens).
\\
\\ Please open the following URL and paste in here the
\\ oauth token you will be shown after logging in.
\\
\\ https://twitchapps.com/tmi/
\\
\\ Token (input is hidden):
, .{}),
.renew => std.debug.print(
\\
\\ The Twitch OAuth token expired, we must refresh it.
\\
\\ Please open the following URL and paste in here the
\\ oauth token you will be shown after logging in.
\\
\\ https://twitchapps.com/tmi/
\\
\\ Token (input is hidden):
, .{}),
}
const tok = (try in.reader().readUntilDelimiterOrEofAlloc(alloc, '\n', 1024)) orelse "";
std.debug.print(
\\
\\ Validating...
\\
, .{});
if (!try Network.checkTokenValidity(alloc, tok)) {
std.debug.print(
\\
\\ Twitch did not accept the token, please try again.
\\
, .{});
std.os.exit(1);
}
var token_file = try base.createFile(".bork/token.secret", .{});
defer token_file.close();
try token_file.writer().print("{s}\n", .{tok});
try std.os.tcsetattr(in.handle, .FLUSH, original_termios);
std.debug.print(
\\
\\
\\ Success, great job!
\\ Your token has been saved in your Bork config directory.
\\
\\ Press any key to continue.
\\
, .{});
_ = try in.reader().readByte();
return tok;
} | src/main.zig |
const std = @import("std");
const testing = std.testing;
const zupnp = @import("zupnp");
const SUT = struct {
const not_found = "NotFound";
const forbidden = "Forbidden";
const dest = "/endpoint";
const Endpoint = struct {
pub fn get(request: *const zupnp.web.ServerGetRequest) zupnp.web.ServerResponse {
const action = request.filename[std.mem.lastIndexOf(u8, request.filename, "/").? + 1 ..];
if (std.mem.eql(u8, action, not_found)) {
return zupnp.web.ServerResponse.notFound();
}
if (std.mem.eql(u8, action, forbidden)) {
return zupnp.web.ServerResponse.forbidden();
}
const contents = std.fmt.allocPrint(request.allocator, "Hello {s}", .{action}) catch |e| @panic(@errorName(e));
return zupnp.web.ServerResponse.contents(.{ .contents = contents });
}
};
lib: zupnp.ZUPnP = undefined,
url: [:0]const u8 = undefined,
fn init(self: *SUT) !void {
self.lib = try zupnp.ZUPnP.init(testing.allocator, .{});
_ = try self.lib.server.createEndpoint(Endpoint, {}, dest);
try self.lib.server.start();
self.url = try std.fmt.allocPrintZ(testing.allocator, "{s}{s}", .{self.lib.server.base_url, dest});
}
fn deinit(self: *SUT) void {
testing.allocator.free(self.url);
self.lib.deinit();
}
fn get(self: *SUT, contents: []const u8) !zupnp.web.ClientResponse {
const url = try std.fmt.allocPrintZ(testing.allocator, "{s}{s}/{s}", .{self.lib.server.base_url.?, SUT.dest, contents});
defer testing.allocator.free(url);
return try zupnp.web.request(.GET, url, .{});
}
};
test "return code 404" {
var sut = SUT {};
try sut.init();
defer sut.deinit();
var response = try sut.get(SUT.not_found);
try testing.expectEqual(@as(c_int, 404), response.http_status);
}
test "return code 403" {
var sut = SUT {};
try sut.init();
defer sut.deinit();
var response = try sut.get(SUT.forbidden);
try testing.expectEqual(@as(c_int, 403), response.http_status);
}
test "return custom contents" {
var sut = SUT {};
try sut.init();
defer sut.deinit();
var response = try sut.get("world!");
try testing.expectEqual(@as(c_int, 200), response.http_status);
const contents = try response.readAll(testing.allocator);
defer testing.allocator.free(contents);
try testing.expectEqualStrings("Hello world!", contents);
} | test/web/test_misc_responses.zig |
const std = @import("std");
const fs = std.fs;
const io = std.io;
const info = std.log.info;
const print = std.debug.print;
const fmt = std.fmt;
const utils = @import("utils.zig");
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const History = struct {
allo: *std.mem.Allocator,
prev: usize,
hist: []?[3]usize,
idx: usize,
pub fn init(allo: *std.mem.Allocator) History {
return History{
.allo = allo,
.prev = 0,
.hist = allo.alloc(?[3]usize, 1000) catch unreachable,
.idx = 0,
};
}
pub fn ensureCapacity(self: *History, num: usize) void {
while (num >= self.hist.len) {
self.hist = self.allo.realloc(self.hist, self.hist.len * 2) catch unreachable;
}
}
pub fn seenNew(self: *History, num: usize) void {
self.ensureCapacity(num);
self.idx += 1;
if (self.hist[num]) |*existing| {
existing[0] += 1;
existing[1] = existing[2];
existing[2] = self.idx;
} else {
self.hist[num] = .{
0, self.idx, self.idx,
};
}
self.prev = num;
}
pub fn genNext(self: *History) usize {
const prev_data = self.hist[self.prev] orelse unreachable;
const prev_cnt = prev_data[0];
const prev_last_old = prev_data[1];
const prev_last_new = prev_data[2];
const prev_unique = prev_cnt == 0;
const new_num = if (prev_unique) 0 else prev_last_new - prev_last_old;
self.seenNew(new_num);
return new_num;
}
pub fn deinit(self: *History) void {
self.allo.free(self.hist);
}
};
pub fn main() !void {
const begin = @divTrunc(std.time.nanoTimestamp(), 1000);
// setup
//
defer _ = gpa.deinit();
var allo = &gpa.allocator;
var lines: std.mem.TokenIterator = try utils.readInputLines(allo, "./input1");
defer allo.free(lines.buffer);
const line = lines.next() orelse unreachable;
var tokens = std.mem.tokenize(line, ",");
var hist = History.init(allo);
defer hist.deinit();
// prime the game from input
while (tokens.next()) |token| {
const val = std.fmt.parseInt(usize, token, 10) catch unreachable;
hist.seenNew(val);
}
while (hist.idx < 30000000) {
const res = hist.genNext();
if (hist.idx == 2020) {
print("p1: {}\n", .{res});
}
if (hist.idx == 30000000) {
print("p2: {}\n", .{res});
}
}
const delta = @divTrunc(std.time.nanoTimestamp(), 1000) - begin;
print("all done in {} microseconds\n", .{delta});
} | day_15/src/main.zig |
const std = @import("std");
const ascii = std.ascii;
const assert = std.debug.assert;
const Options = @import("options.zig").Options;
const nodes = @import("nodes.zig");
const strings = @import("strings.zig");
const scanners = @import("scanners.zig");
pub fn print(writer: anytype, allocator: *std.mem.Allocator, options: Options, root: *nodes.AstNode) !void {
var formatter = makeHtmlFormatter(writer, allocator, options);
defer formatter.deinit();
try formatter.format(root, false);
}
pub fn makeHtmlFormatter(writer: anytype, allocator: *std.mem.Allocator, options: Options) HtmlFormatter(@TypeOf(writer)) {
return HtmlFormatter(@TypeOf(writer)).init(writer, allocator, options);
}
pub fn HtmlFormatter(comptime Writer: type) type {
return struct {
writer: Writer,
allocator: *std.mem.Allocator,
options: Options,
last_was_lf: bool = true,
anchor_map: std.StringHashMap(void),
anchor_node_map: std.AutoHashMap(*nodes.AstNode, []const u8),
const Self = @This();
pub fn init(writer: Writer, allocator: *std.mem.Allocator, options: Options) Self {
return .{
.writer = writer,
.allocator = allocator,
.options = options,
.anchor_map = std.StringHashMap(void).init(allocator),
.anchor_node_map = std.AutoHashMap(*nodes.AstNode, []const u8).init(allocator),
};
}
pub fn deinit(self: *Self) void {
var it = self.anchor_map.iterator();
while (it.next()) |entry| {
self.allocator.free(entry.key_ptr.*);
}
self.anchor_map.deinit();
self.anchor_node_map.deinit();
}
const NEEDS_ESCAPED = strings.createMap("\"&<>");
const HREF_SAFE = strings.createMap("-_.+!*'(),%#@?=;:/,+&$~abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
fn dangerousUrl(input: []const u8) !bool {
return (try scanners.dangerousUrl(input)) != null;
}
fn cr(self: *Self) !void {
if (!self.last_was_lf) {
try self.writeAll("\n");
}
}
fn escape(self: *Self, s: []const u8) !void {
var offset: usize = 0;
for (s) |c, i| {
if (NEEDS_ESCAPED[c]) {
try self.writeAll(s[offset..i]);
try self.writeAll(switch (c) {
'"' => """,
'&' => "&",
'<' => "<",
'>' => ">",
else => unreachable,
});
offset = i + 1;
}
}
try self.writeAll(s[offset..]);
}
fn escapeHref(self: *Self, s: []const u8) !void {
var i: usize = 0;
const size = s.len;
while (i < size) : (i += 1) {
const org = i;
while (i < size and HREF_SAFE[s[i]])
i += 1;
if (i > org) {
try self.writeAll(s[org..i]);
}
if (i >= size) {
break;
}
switch (s[i]) {
'&' => try self.writeAll("&"),
'\'' => try self.writeAll("'"),
else => try self.writer.print("%{X:0>2}", .{s[i]}),
}
}
}
pub fn writeAll(self: *Self, s: []const u8) !void {
if (s.len == 0) {
return;
}
try self.writer.writeAll(s);
self.last_was_lf = s[s.len - 1] == '\n';
}
pub fn format(self: *Self, input_node: *nodes.AstNode, plain: bool) !void {
const Phase = enum { Pre, Post };
const StackEntry = struct {
node: *nodes.AstNode,
plain: bool,
phase: Phase,
};
var stack = std.ArrayList(StackEntry).init(self.allocator);
defer stack.deinit();
try stack.append(.{ .node = input_node, .plain = plain, .phase = .Pre });
while (stack.popOrNull()) |entry| {
switch (entry.phase) {
.Pre => {
var new_plain: bool = undefined;
if (entry.plain) {
switch (entry.node.data.value) {
.Text, .HtmlInline, .Code => |literal| {
try self.escape(literal);
},
.LineBreak, .SoftBreak => {
try self.writeAll(" ");
},
else => {},
}
new_plain = entry.plain;
} else {
try stack.append(.{ .node = entry.node, .plain = false, .phase = .Post });
new_plain = try self.fnode(entry.node, true);
}
var it = entry.node.reverseChildrenIterator();
while (it.next()) |ch| {
try stack.append(.{ .node = ch, .plain = new_plain, .phase = .Pre });
}
},
.Post => {
assert(!entry.plain);
_ = try self.fnode(entry.node, false);
},
}
}
}
fn fnode(self: *Self, node: *nodes.AstNode, entering: bool) !bool {
switch (node.data.value) {
.Document => {},
.BlockQuote => {
try self.cr();
try self.writeAll(if (entering) "<blockquote>\n" else "</blockquote>");
},
.List => |nl| {
if (entering) {
try self.cr();
if (nl.list_type == .Bullet) {
try self.writeAll("<ul>\n");
} else if (nl.start == 1) {
try self.writeAll("<ol>\n");
} else {
try self.writer.print("<ol start=\"{}\">", .{nl.start});
}
} else if (nl.list_type == .Bullet) {
try self.writeAll("</ul>\n");
} else {
try self.writeAll("</ol>\n");
}
},
.Item => {
if (entering) {
try self.cr();
try self.writeAll("<li>");
} else {
try self.writeAll("</li>\n");
}
},
.Heading => |nch| {
if (entering) {
try self.cr();
try self.writer.print("<h{}>", .{nch.level});
if (self.options.render.header_anchors) {
const id = try self.getNodeAnchor(node);
try self.writeAll("<a href=\"#");
try self.writeAll(id);
try self.writeAll("\" id=\"");
try self.writeAll(id);
try self.writeAll("\">");
try self.writeAll(self.options.render.anchor_icon);
try self.writeAll("</a>");
}
} else {
try self.writer.print("</h{}>\n", .{nch.level});
self.last_was_lf = true;
}
},
.CodeBlock => |ncb| {
if (entering) {
try self.cr();
if (ncb.info == null or ncb.info.?.len == 0) {
try self.writeAll("<pre><code>");
} else {
var first_tag: usize = 0;
while (first_tag < ncb.info.?.len and !ascii.isSpace(ncb.info.?[first_tag]))
first_tag += 1;
try self.writeAll("<pre><code class=\"language-");
try self.escape(ncb.info.?[0..first_tag]);
try self.writeAll("\">");
}
try self.escape(ncb.literal.items);
try self.writeAll("</code></pre>\n");
}
},
.HtmlBlock => |nhb| {
if (entering) {
try self.cr();
if (!self.options.render.unsafe) {
try self.writeAll("<!-- raw HTML omitted -->");
} else if (self.options.extensions.tagfilter) {
try self.tagfilterBlock(nhb.literal.items);
} else {
try self.writeAll(nhb.literal.items);
}
try self.cr();
}
},
.ThematicBreak => {
if (entering) {
try self.cr();
try self.writeAll("<hr />\n");
}
},
.Paragraph => {
var tight = node.parent != null and node.parent.?.parent != null and switch (node.parent.?.parent.?.data.value) {
.List => |nl| nl.tight,
else => false,
};
if (!tight) {
if (entering) {
try self.cr();
try self.writeAll("<p>");
} else {
try self.writeAll("</p>\n");
}
}
},
.Text => |literal| {
if (entering) {
try self.escape(literal);
}
},
.LineBreak => {
if (entering) {
try self.writeAll("<br />\n");
}
},
.SoftBreak => {
if (entering) {
try self.writeAll(if (self.options.render.hard_breaks) "<br />\n" else "\n");
}
},
.Code => |literal| {
if (entering) {
try self.writeAll("<code>");
try self.escape(literal);
try self.writeAll("</code>");
}
},
.HtmlInline => |literal| {
if (entering) {
if (!self.options.render.unsafe) {
try self.writeAll("<!-- raw HTML omitted -->");
} else if (self.options.extensions.tagfilter and tagfilter(literal)) {
try self.writeAll("<");
try self.writeAll(literal[1..]);
} else {
try self.writeAll(literal);
}
}
},
.Strong => {
try self.writeAll(if (entering) "<strong>" else "</strong>");
},
.Emph => {
try self.writeAll(if (entering) "<em>" else "</em>");
},
.Strikethrough => {
if (entering) {
try self.writeAll("<del>");
} else {
try self.writeAll("</del>");
}
},
.Link => |nl| {
if (entering) {
try self.writeAll("<a href=\"");
if (self.options.render.unsafe or !(try dangerousUrl(nl.url))) {
try self.escapeHref(nl.url);
}
if (nl.title.len > 0) {
try self.writeAll("\" title=\"");
try self.escape(nl.title);
}
try self.writeAll("\">");
} else {
try self.writeAll("</a>");
}
},
.Image => |nl| {
if (entering) {
try self.writeAll("<img src=\"");
if (self.options.render.unsafe or !(try dangerousUrl(nl.url))) {
try self.escapeHref(nl.url);
}
try self.writeAll("\" alt=\"");
return true;
} else {
if (nl.title.len > 0) {
try self.writeAll("\" title=\"");
try self.escape(nl.title);
}
try self.writeAll("\" />");
}
},
.Table => {
if (entering) {
try self.cr();
try self.writeAll("<table>\n");
} else {
if (node.last_child.? != node.first_child.?) {
try self.cr();
try self.writeAll("</tbody>\n");
}
try self.cr();
try self.writeAll("</table>\n");
}
},
.TableRow => |kind| {
if (entering) {
try self.cr();
if (kind == .Header) {
try self.writeAll("<thead>\n");
} else if (node.prev) |prev| {
switch (prev.data.value) {
.TableRow => |k| {
if (k == .Header)
try self.writeAll("<tbody>\n");
},
else => {},
}
}
try self.writeAll("<tr>");
} else {
try self.cr();
try self.writeAll("</tr>");
if (kind == .Header) {
try self.cr();
try self.writeAll("</thead>");
}
}
},
.TableCell => {
const kind = node.parent.?.data.value.TableRow;
const alignments = node.parent.?.parent.?.data.value.Table;
if (entering) {
try self.cr();
if (kind == .Header) {
try self.writeAll("<th");
} else {
try self.writeAll("<td");
}
var start = node.parent.?.first_child.?;
var i: usize = 0;
while (start != node) {
i += 1;
start = start.next.?;
}
switch (alignments[i]) {
.Left => try self.writeAll(" align=\"left\""),
.Right => try self.writeAll(" align=\"right\""),
.Center => try self.writeAll(" align=\"center\""),
.None => {},
}
try self.writeAll(">");
} else if (kind == .Header) {
try self.writeAll("</th>");
} else {
try self.writeAll("</td>");
}
},
}
return false;
}
fn collectText(self: *Self, node: *nodes.AstNode) ![]u8 {
var out = std.ArrayList(u8).init(self.allocator);
try collectTextInto(&out, node);
return out.toOwnedSlice();
}
fn collectTextInto(out: *std.ArrayList(u8), node: *nodes.AstNode) std.mem.Allocator.Error!void {
switch (node.data.value) {
.Text, .Code => |literal| {
try out.appendSlice(literal);
},
.LineBreak, .SoftBreak => try out.append(' '),
else => {
var it = node.first_child;
while (it) |child| {
try collectTextInto(out, child);
it = child.next;
}
},
}
}
/// Return the anchor for a given Heading node. If it does not exist yet, it will be generated.
pub fn getNodeAnchor(self: *Self, node: *nodes.AstNode) ![]const u8 {
std.debug.assert(node.data.value == .Heading);
const gop = try self.anchor_node_map.getOrPut(node);
if (!gop.found_existing) {
errdefer _ = self.anchor_node_map.remove(node);
var text_content = try self.collectText(node);
defer self.allocator.free(text_content);
gop.value_ptr.* = try self.anchorize(text_content);
}
return gop.value_ptr.*;
}
fn anchorize(self: *Self, header: []const u8) ![]const u8 {
var lower = try strings.toLower(self.allocator, header);
defer self.allocator.free(lower);
var removed = try scanners.removeAnchorizeRejectedChars(self.allocator, lower);
defer self.allocator.free(removed);
for (removed) |*c| {
if (c.* == ' ') c.* = '-';
}
var uniq: usize = 0;
while (true) {
var anchor = if (uniq == 0)
try self.allocator.dupe(u8, removed)
else
try std.fmt.allocPrint(self.allocator, "{s}-{}", .{ removed, uniq });
errdefer self.allocator.free(anchor);
var getPut = try self.anchor_map.getOrPut(anchor);
if (!getPut.found_existing) {
// anchor now belongs in anchor_map.
return anchor;
}
self.allocator.free(anchor);
uniq += 1;
}
}
const TAGFILTER_BLACKLIST = [_][]const u8{
"title",
"textarea",
"style",
"xmp",
"iframe",
"noembed",
"noframes",
"script",
"plaintext",
};
fn tagfilter(literal: []const u8) bool {
if (literal.len < 3 or literal[0] != '<')
return false;
var i: usize = 1;
if (literal[i] == '/')
i += 1;
for (TAGFILTER_BLACKLIST) |t| {
const j = i + t.len;
if (literal.len > j and std.ascii.eqlIgnoreCase(t, literal[i..j])) {
return ascii.isSpace(literal[j]) or
literal[j] == '>' or
(literal[j] == '/' and literal.len >= j + 2 and literal[j + 1] == '>');
}
}
return false;
}
fn tagfilterBlock(self: *Self, input: []const u8) !void {
const size = input.len;
var i: usize = 0;
while (i < size) {
const org = i;
while (i < size and input[i] != '<') : (i += 1) {}
if (i > org) {
try self.writeAll(input[org..i]);
}
if (i >= size) {
break;
}
if (tagfilter(input[i..])) {
try self.writeAll("<");
} else {
try self.writeAll("<");
}
i += 1;
}
}
};
}
test "escaping works as expected" {
var buffer = std.ArrayList(u8).init(std.testing.allocator);
defer buffer.deinit();
var formatter = makeHtmlFormatter(buffer.writer(), std.testing.allocator, .{});
defer formatter.deinit();
try formatter.escape("<hello & goodbye>");
try std.testing.expectEqualStrings("<hello & goodbye>", buffer.items);
}
test "lowercase anchor generation" {
var formatter = makeHtmlFormatter(std.io.null_writer, std.testing.allocator, .{});
defer formatter.deinit();
try std.testing.expectEqualStrings("yés", try formatter.anchorize("YÉS"));
} | src/html.zig |
const std = @import("std");
const helper = @import("helper.zig");
const Allocator = std.mem.Allocator;
const HashMap = std.AutoHashMap;
const input = @embedFile("../inputs/day20.txt");
pub fn run(alloc: Allocator, stdout_: anytype) !void {
var lines = helper.getlines(input);
const algo = getEnhancementAlgorithm(lines.next().?);
var image = try Image.parse(alloc, lines.rest());
defer image.deinit();
try image.enhanceN(2, &algo);
const res1 = image.pixels.count();
try image.enhanceN(50 - 2, &algo);
const res2 = image.pixels.count();
if (stdout_) |stdout| {
try stdout.print("Part 1: {}\n", .{res1});
try stdout.print("Part 2: {}\n", .{res2});
}
}
fn getEnhancementAlgorithm(line: []const u8) [512]bool {
if (line.len != 512) unreachable;
var arr: [512]bool = undefined;
for (line) |ch, i| switch (ch) {
'.' => arr[i] = false,
'#' => arr[i] = true,
else => unreachable,
};
return arr;
}
const Image = struct {
pixels: HashMap(Point, void),
buffer: HashMap(Point, void),
bottom_left: Point,
top_right: Point,
outer_on: bool,
const Self = @This();
pub fn parse(alloc: Allocator, text: []const u8) !Self {
var pixels = HashMap(Point, void).init(alloc);
try pixels.ensureTotalCapacity(@intCast(HashMap(Point, void).Size, text.len));
var buffer = HashMap(Point, void).init(alloc);
try buffer.ensureTotalCapacity(pixels.capacity());
var lines = helper.getlines(text);
const linelen = lines.next().?.len;
lines.reset();
var i: i64 = 0;
while (lines.next()) |line| : (i += 1) {
for (line) |ch, j| {
switch (ch) {
'.' => {},
'#' => try pixels.put(.{ .x = i, .y = @intCast(i64, j) }, {}),
else => unreachable,
}
}
}
return Self{
.pixels = pixels,
.buffer = buffer,
.bottom_left = .{ .x = 0, .y = 0 },
.top_right = .{
.x = i - 1,
.y = @intCast(i64, linelen - 1),
},
.outer_on = false,
};
}
pub fn enhanceN(self: *Self, comptime n: comptime_int, algo: *const [512]bool) !void {
comptime var i = 0;
inline while (i < n) : (i += 1) {
try self.enhanceOnce(algo);
}
}
pub fn enhanceOnce(self: *Self, algo: *const [512]bool) !void {
const new_bottom_left = Point{
.x = self.bottom_left.x - 1,
.y = self.bottom_left.y - 1,
};
const new_top_right = Point{
.x = self.top_right.x + 1,
.y = self.top_right.y + 1,
};
self.buffer.clearRetainingCapacity();
var x: i64 = new_bottom_left.x;
while (x <= new_top_right.x) : (x += 1) {
var y: i64 = new_bottom_left.y;
while (y <= new_top_right.y) : (y += 1) {
if (self.getNewValue(x, y, algo)) {
try self.buffer.put(.{ .x = x, .y = y }, {});
}
}
}
self.outer_on = self.getNewValue(new_top_right.x + 1, new_top_right.y + 1, algo);
self.bottom_left = new_bottom_left;
self.top_right = new_top_right;
std.mem.swap(HashMap(Point, void), &self.pixels, &self.buffer);
}
pub fn deinit(self: *Self) void {
self.pixels.deinit();
self.buffer.deinit();
}
pub fn print(self: Self) void {
const stdout = std.io.getStdOut().writer();
var x: i64 = self.bottom_left.x;
while (x <= self.top_right.x) : (x += 1) {
var y: i64 = self.bottom_left.y;
while (y <= self.top_right.y) : (y += 1) {
if (self.get(x, y)) {
stdout.print("#", .{}) catch unreachable;
} else {
stdout.print(".", .{}) catch unreachable;
}
}
stdout.print("\n", .{}) catch unreachable;
}
stdout.print("\n", .{}) catch unreachable;
}
fn getNewValue(self: *const Self, x: i64, y: i64, algo: *const [512]bool) bool {
var idx: usize = 0;
var dx: i64 = -1;
while (dx <= 1) : (dx += 1) {
var dy: i64 = -1;
while (dy <= 1) : (dy += 1) {
idx = idx << 1;
if (self.get(x + dx, y + dy)) {
idx += 1;
}
}
}
return algo[idx];
}
fn get(self: *const Self, x: i64, y: i64) bool {
if (self.bottom_left.x > x or self.top_right.x < x) return self.outer_on;
if (self.bottom_left.y > y or self.top_right.y < y) return self.outer_on;
return self.pixels.contains(.{ .x = x, .y = y });
}
};
const Point = struct { x: i64, y: i64 };
const eql = std.mem.eql;
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const count = std.mem.count;
const parseUnsigned = std.fmt.parseUnsigned;
const parseInt = std.fmt.parseInt;
const sort = std.sort.sort; | src/day20.zig |
const std = @import("std");
const assert = std.debug.assert;
const tools = @import("tools");
const BigInt = u50;
fn pgcd(val1: BigInt, val2: BigInt) BigInt {
var a = if (val1 > val2) val1 else val2;
var b = if (val1 > val2) val2 else val1;
while (b != 0) {
const r = a % b;
a = b;
b = r;
}
return a;
}
fn ppcm(val1: BigInt, val2: BigInt) BigInt {
var div = pgcd(val1, val2);
var num = val1 * val2;
return num / div;
}
fn coincidence(period1: BigInt, offset1: BigInt, period2: BigInt, offset2: BigInt) BigInt {
assert(period1 != 0 and period2 != 0);
var a: BigInt = offset1;
var b: BigInt = 0;
while (b != a + offset2) {
if (b > a + offset2) a += period1;
if (b < a + offset2) {
const ceil = ((period2 - 1) + ((a + offset2) - b)) / period2;
b += period2 * ceil;
}
}
//std.debug.print("XXXX a={}, b={}, p1={}, p2={}, offset2={}\n", .{ a, b, period1, period2, offset2 });
return a;
}
pub fn run(_: []const u8, allocator: std.mem.Allocator) ![2][]const u8 {
const time = 1000511;
const input_text = "29,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,37,x,x,x,x,x,409,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,17,13,19,x,x,x,23,x,x,x,x,x,x,x,353,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,41";
//const input_text = "1789,37,47,1889";
const Bus = struct { period: u32, gap: u32 };
var mem_buses: [50]Bus = undefined;
const buses: []const Bus = blk: {
var nb: usize = 0;
var it = std.mem.tokenize(u8, input_text, ",\n\r");
var i: u32 = 0;
while (it.next()) |field| : (i += 1) {
const b = std.fmt.parseInt(u32, field, 10) catch continue;
mem_buses[nb] = .{ .period = b, .gap = i };
nb += 1;
}
break :blk mem_buses[0..nb];
};
const ans1 = ans: {
var best_gap: u32 = 99999;
var best_bus: u32 = 0;
for (buses) |b| {
const gap = (b.period - (time % b.period)) % b.period;
if (gap < best_gap) {
best_gap = gap;
best_bus = b.period;
}
//std.debug.print("bus {} -> {}\n", .{ b, b - earliest % b });
}
break :ans best_bus * best_gap;
};
const ans2 = ans: {
var group_period: BigInt = buses[0].period;
var group_offset: BigInt = 0;
for (buses[1..]) |b| {
group_offset = coincidence(group_period, group_offset, b.period, b.gap);
group_period = ppcm(group_period, b.period);
}
break :ans group_offset;
};
return [_][]const u8{
try std.fmt.allocPrint(allocator, "{}", .{ans1}),
try std.fmt.allocPrint(allocator, "{}", .{ans2}),
};
}
pub const main = tools.defaultMain("2020/input_day12.txt", run); | 2020/day13.zig |
const std = @import("std");
const builtin = @import("builtin");
const sdl = @import("sdl2");
const Save = @import("Save.zig");
const TimeStats = @import("TimeStats.zig");
const Context = @import("Context.zig");
const Texture = @import("Texture.zig");
const Popup = @import("Popup.zig");
const Instance = @This();
const log = std.log.scoped(.Instance);
//////////
// context
//////////
allocator: std.mem.Allocator,
context: Context,
running: bool = true,
timestat: TimeStats,
//////////
// texture
//////////
save: Save,
texture: Texture,
/////////////////////
// drawing / movement
/////////////////////
// left, right, up, down
scrolling: u4 = 0,
expandedView: bool = true,
dragPoint: ?struct { x: f32, y: f32 } = null,
mousePos: sdl.Point = undefined,
windowSize: sdl.Size = .{ .width = 1000, .height = 600 },
progressBuffer: []u8,
progressCounter: usize = 0,
popups: []Popup,
const FrameRate = 24;
const FrameTimeMS = 1000 / FrameRate;
//////////
// INIT //
//////////
pub fn init(ctx: Context, filename: [:0]const u8, allocator: std.mem.Allocator) !Instance {
// image loading
const texture = Texture.load_file(filename, ctx.render, allocator) catch {
log.warn("Texture creation failure!", .{});
return error.TextureError;
};
// Save reading
const a = [_][]const u8{ ".", std.fs.path.basename(filename), ".save" };
const imgSaveFilename = try std.mem.concat(allocator, u8, &a);
errdefer allocator.free(imgSaveFilename);
log.debug("Save file name as \"{s}\"", .{imgSaveFilename});
const imgSave = try Save.open(imgSaveFilename);
// initialize increment popups
const popups = try allocator.alloc(Popup, 20);
errdefer allocator.free(popups);
std.mem.set(Popup, popups, Popup{ .stamp = 0, .texti = 0 });
return Instance{
.allocator = allocator,
.context = ctx,
.save = imgSave,
.timestat = TimeStats.start(imgSave.progress),
.texture = texture,
.expandedView = imgSave.progress == 0,
.progressBuffer = try allocator.alloc(u8, 0xDF),
.popups = popups,
};
}
pub fn deinit(self: Instance) void {
self.allocator.free(self.popups);
self.allocator.free(self.progressBuffer);
self.timestat.write_append(self.save.progress) catch |err| {
log.warn("Error saving stats! {s}", .{@errorName(err)});
};
self.save.write() catch |err| {
log.err("Error saving: {s}, path {s}", .{ @errorName(err), self.save.file });
log.err("here's your progress number: {}", .{self.save.progress});
};
self.allocator.free(self.save.file);
self.texture.deinit(self.allocator);
self.context.deinit();
}
////////////
// EVENTS //
////////////
fn handle_key(self: *Instance, eventkey: sdl.Keycode, up: bool) void {
// singular presses
if (!up) {
// zoom in/out
switch (eventkey) {
sdl.Keycode.e => {
self.context.offset.z += 1;
},
sdl.Keycode.q => {
self.context.offset.z = std.math.max(1, self.context.offset.z - 1);
},
sdl.Keycode.slash => {
self.expandedView = !self.expandedView;
self.write_progress();
},
sdl.Keycode.f4 => {
if (sdl.getModState().get(sdl.KeyModifierBit.left_alt)) {
self.running = false;
return;
}
},
else => {},
}
// increments
const incval: i32 = switch (eventkey) {
sdl.Keycode.z => -10,
sdl.Keycode.x => -1,
sdl.Keycode.c => 1,
sdl.Keycode.v => 10,
sdl.Keycode.f1 => if (builtin.mode == .Debug) 999999 else 0,
sdl.Keycode.f2 => if (builtin.mode == .Debug) -999999 else 0,
else => 0,
};
if (incval != 0) {
log.debug("Incrementing by {d: >3} was total: {d}", .{ incval, self.save.progress });
self.save.increment(incval);
if (self.save.progress > self.max()) {
self.save.progress = self.max();
}
self.save.write() catch |err| {
log.warn("Failed to save progress cause: {s}, path {s}", .{ @errorName(err), self.save.file });
log.warn("You may want this number: {d}", .{self.save.progress});
};
self.write_progress();
Popup.push(self.popups, incval);
}
}
// movement mask
const mask: u4 = switch (eventkey) {
sdl.Keycode.left, sdl.Keycode.a => 0b1000,
sdl.Keycode.right, sdl.Keycode.d => 0b0100,
sdl.Keycode.up, sdl.Keycode.w => 0b0010,
sdl.Keycode.down, sdl.Keycode.s => 0b0001,
else => 0b0000,
};
if (up) {
self.scrolling &= ~mask;
} else {
self.scrolling |= mask;
}
}
fn handle_events(self: *Instance) void {
while (sdl.pollEvent()) |e| {
switch (e) {
.key_down, .key_up => |key| {
self.handle_key(key.keycode, e == .key_up);
},
.mouse_button_up => {
self.dragPoint = null;
},
.mouse_button_down => |mouse| {
self.dragPoint = .{
.x = @intToFloat(f32, mouse.x) - self.context.offset.x,
.y = @intToFloat(f32, mouse.y) - self.context.offset.y,
};
},
.mouse_motion => |mouse| {
self.mousePos.x = mouse.x;
self.mousePos.y = mouse.y;
},
.window => |window| {
switch (window.type) {
.size_changed, .resized => |size| {
self.windowSize = size;
log.debug("resized: {}x{}", .{ size.width, size.height });
},
else => {},
}
},
.quit => {
self.running = false;
},
else => {},
}
}
}
//////////////////////
// PROGRESS READERS //
//////////////////////
fn max(self: Instance) usize {
return self.texture.width * self.texture.height;
}
fn last_color_change(self: Instance) usize {
const p = self.save.progress;
if (p == self.max()) {
return 0;
}
const x = p % self.texture.width;
const y = p / self.texture.width;
if (y & 1 == 0) {
const start = self.texture.pixel_at_index(p);
var i: usize = 1;
while (i < p and std.mem.eql(u8, start, self.texture.pixel_at_index(p - i))) : (i += 1) {}
return i - 1;
} else {
const op = y * self.texture.width + self.texture.width - x - 1;
const start = self.texture.pixel_at_index(op);
var i: usize = 1;
while (i + op < self.max() and std.mem.eql(u8, start, self.texture.pixel_at_index(op + i))) : (i += 1) {}
return i - 1;
}
}
fn next_color_change(self: Instance) usize {
const p = self.save.progress;
if (p == self.max())
return 0;
const x = p % self.texture.width;
const y = p / self.texture.width;
if (y & 1 == 0) {
const start = self.texture.pixel_at_index(p);
var i: usize = 1;
while (i < self.texture.width - x) : (i += 1) {
const search = self.texture.pixel_at_index(p + i);
if (!std.mem.eql(u8, start, search)) {
return i;
}
}
return self.texture.width - x;
} else {
const op = y * self.texture.width + (self.texture.width - x - 1);
const start = self.texture.pixel_at_index(op);
var i: usize = 1;
while (i < self.texture.width - x) : (i += 1) {
const search = self.texture.pixel_at_index(op - i);
if (!std.mem.eql(u8, start, search)) {
return i;
}
}
return self.texture.width - x;
}
}
fn write_progress(self: *Instance) void {
const lp = self.save.progress % self.texture.width;
const hp = self.save.progress / self.texture.width;
const cp = std.math.min(lp, self.last_color_change());
const ncp = self.next_color_change();
const percent = @intToFloat(f32, self.save.progress) / @intToFloat(f32, self.max()) * 100;
if (self.expandedView) {
if (std.fmt.bufPrint(self.progressBuffer,
\\Total: {:.>6}/{:.>6} {d: >3.2}%
\\Lines: {d}
\\Since line: {:.>4}
\\Since Color: {:.>3}
\\Next Color: {:.>4}
\\===
\\Panning: WASD <^v>
\\Zoom: Q/E
\\Add Stitch ..10/1: V/C
\\Remov Stitch 10/1: Z/X
\\Toggle Help: ?
, .{
self.save.progress, self.max(), percent, //
hp, //
lp,
cp,
ncp,
})) |written| {
self.progressCounter = written.len;
} else |err| {
log.warn("Progress counter errored with: {s}", .{@errorName(err)});
}
} else {
if (std.fmt.bufPrint(self.progressBuffer, "{d: >3.2}% L{:.>3} C{:.>3}", .{ percent, cp, ncp })) |written| {
self.progressCounter = written.len;
} else |err| {
log.warn("Progress counter errored with: {s}", .{@errorName(err)});
}
}
}
///////////////
// MAIN LOOP //
///////////////
pub fn main_loop(self: *Instance) void {
self.write_progress();
while (self.running) {
const frameStart = std.time.milliTimestamp();
self.handle_events();
if (self.dragPoint) |dragPoint| {
self.context.offset.x = @intToFloat(f32, self.mousePos.x) - dragPoint.x;
self.context.offset.y = @intToFloat(f32, self.mousePos.y) - dragPoint.y;
} else {
if (self.scrolling & 0b1000 != 0) {
self.context.offset.x -= 10;
} else if (self.scrolling & 0b0100 != 0) {
self.context.offset.x += 10;
}
if (self.scrolling & 0b0010 != 0) {
self.context.offset.y -= 10;
} else if (self.scrolling & 0b0001 != 0) {
self.context.offset.y += 10;
}
}
self.context.clear();
self.context.draw_all(self.texture, self.save.progress);
self.context.print_slice(self.progressBuffer[0..self.progressCounter], 10, 0);
Popup.draw(self.popups, self.context, self.windowSize.height);
self.context.swap();
// frame limit with SDL_Delay
const frameTime = std.time.milliTimestamp() - frameStart;
if (frameTime < FrameTimeMS) {
sdl.delay(@intCast(u32, FrameTimeMS - frameTime));
} else {
log.debug("Frame took {d} milliseconds!", .{frameTime});
}
}
} | src/Instance.zig |
const T = 0x00000000;
const B = 0x11000000;
const W = 0xFFFFFFFF;
const P = 0xFFad03fc;
pub const pixels = [32*32]u32 { // Now he is safe here :)
P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,
P,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,P,
P,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,P,
P,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,P,
P,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,P,
P,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,P,
P,T,T,T,T,T,T,T,T,T,W,W,W,W,W,W,W,W,W,W,T,T,T,T,T,T,T,T,T,T,T,P,
P,T,T,T,T,T,T,T,W,W,W,W,W,W,W,W,W,W,W,W,W,T,T,W,T,T,T,T,T,T,T,P,
P,T,T,T,T,T,T,W,W,W,T,T,T,T,T,T,T,T,T,W,W,W,T,T,T,T,T,T,T,T,T,P,
P,T,T,T,T,T,W,W,W,T,T,T,T,T,T,T,T,T,T,T,T,W,W,T,T,T,T,T,T,T,T,P,
P,T,T,T,T,W,W,W,T,T,T,W,W,T,T,T,T,W,W,T,T,W,W,T,T,T,T,T,T,T,T,P,
P,T,T,T,W,W,W,T,T,T,W,T,W,T,T,T,T,W,W,W,T,T,W,W,T,T,T,T,T,T,T,P,
P,T,T,T,W,W,T,T,T,T,W,T,T,W,T,T,W,W,T,T,W,W,W,W,T,T,T,T,W,T,T,P,
P,T,T,T,W,W,T,T,T,W,T,T,T,W,W,T,W,T,T,T,T,W,T,W,T,T,T,T,T,T,T,P,
P,T,T,T,W,W,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,W,W,T,T,T,T,T,T,T,P,
P,T,T,T,W,W,W,T,T,T,T,T,W,W,T,T,T,T,W,W,T,T,W,W,T,T,T,T,T,T,T,P,
P,T,T,T,W,W,W,T,T,T,T,T,T,W,W,W,W,W,W,T,T,W,W,W,T,T,T,T,T,T,T,P,
P,T,T,T,T,W,W,W,W,T,T,T,T,T,T,T,T,T,T,T,W,W,W,T,T,T,T,T,T,T,T,P,
P,T,T,T,T,T,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,T,T,T,T,T,T,T,T,T,P,
P,T,T,T,T,T,T,T,T,W,W,W,W,W,W,W,W,W,W,W,T,T,T,T,T,T,W,T,T,T,T,P,
P,T,T,T,T,T,T,T,T,T,W,W,T,T,T,T,T,W,W,T,T,T,T,T,T,T,T,T,T,T,T,P,
P,T,T,T,T,T,T,T,T,T,W,W,T,T,T,T,T,W,W,T,T,T,T,T,T,T,T,T,T,T,T,P,
P,T,T,T,T,T,T,T,T,T,W,W,T,T,T,T,T,W,W,W,T,T,T,T,T,T,T,T,T,T,T,P,
P,T,T,T,T,T,T,T,T,T,W,W,T,T,W,W,W,W,W,W,T,T,T,T,T,T,T,T,T,T,T,P,
P,T,T,T,T,T,T,T,T,T,W,W,W,W,W,W,W,W,W,W,T,T,T,T,T,T,T,T,T,T,T,P,
P,T,T,T,T,T,T,T,T,T,W,W,W,W,T,T,T,T,W,W,T,T,T,T,T,T,T,T,T,T,T,P,
P,T,T,T,T,T,T,T,T,W,W,W,T,T,T,T,T,T,W,W,T,T,T,T,T,T,T,T,T,T,T,P,
P,T,T,T,T,T,T,T,T,W,W,W,T,T,T,T,T,T,W,W,T,T,T,T,T,T,T,T,T,T,T,P,
P,T,T,T,T,T,W,W,W,W,W,W,T,T,T,T,T,T,W,W,W,W,W,T,T,T,T,T,T,T,T,P,
P,T,T,T,T,T,W,W,W,W,W,W,T,T,T,T,T,T,W,W,W,W,W,T,T,T,T,T,T,T,T,P,
P,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,P,
P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P,P
}; | src/guy.zig |
const std = @import("std");
const tls = @import("tls");
const RecordingRandom = struct {
base: std.rand.Random,
recorded: std.ArrayList(u8),
pub fn random(self: *RecordingRandom) std.rand.Random {
return std.rand.Random.init(self, fill);
}
fn fill(self: *RecordingRandom, buf: []u8) void {
self.base.bytes(buf);
self.recorded.writer().writeAll(buf) catch unreachable;
}
};
fn RecordingReaderState(comptime Base: type) type {
return struct {
base: Base,
recorded: std.ArrayList(u8),
fn read(self: *@This(), buffer: []u8) !usize {
var read_bytes = try self.base.read(buffer);
if (read_bytes != 0) {
try self.recorded.writer().writeAll(buffer[0..read_bytes]);
}
return read_bytes;
}
};
}
fn RecordingReader(comptime Base: type) type {
return std.io.Reader(
*RecordingReaderState(Base),
Base.Error || error{OutOfMemory},
RecordingReaderState(Base).read,
);
}
fn record_handshake(
comptime ciphersuites: anytype,
comptime curves: anytype,
allocator: std.mem.Allocator,
out_name: []const u8,
hostname: []const u8,
port: u16,
pem_file_path: []const u8,
) !void {
// Read PEM file
const pem_file = try std.fs.cwd().openFile(pem_file_path, .{});
defer pem_file.close();
const trust_anchors = try tls.x509.CertificateChain.from_pem(allocator, pem_file.reader());
defer trust_anchors.deinit();
std.log.info("Read {} certificates.", .{trust_anchors.data.items.len});
const sock = try std.net.tcpConnectToHost(allocator, hostname, port);
defer sock.close();
var recording_reader_state = RecordingReaderState(@TypeOf(sock).Reader){
.base = sock.reader(),
.recorded = std.ArrayList(u8).init(allocator),
};
defer recording_reader_state.recorded.deinit();
var recording_random = RecordingRandom{
.base = std.crypto.random.*,
.recorded = std.ArrayList(u8).init(allocator),
};
defer recording_random.recorded.deinit();
const reader = RecordingReader(@TypeOf(sock).Reader){
.context = &recording_reader_state,
};
std.log.info("Recording session `{s}`...", .{out_name});
var client = try tls.client_connect(.{
.rand = recording_random.random(),
.reader = reader,
.writer = sock.writer(),
.ciphersuites = ciphersuites,
.curves = curves,
.cert_verifier = .default,
.temp_allocator = allocator,
.trusted_certificates = trust_anchors.data.items,
}, hostname);
defer client.close_notify() catch {};
const out_file = try std.fs.cwd().createFile(out_name, .{});
defer out_file.close();
if (ciphersuites.len > 1) {
try out_file.writeAll(&[_]u8{ 0x3, 'a', 'l', 'l' });
} else {
try out_file.writer().writeIntLittle(u8, ciphersuites[0].name.len);
try out_file.writeAll(ciphersuites[0].name);
}
if (curves.len > 1) {
try out_file.writeAll(&[_]u8{ 0x3, 'a', 'l', 'l' });
} else {
try out_file.writer().writeIntLittle(u8, curves[0].name.len);
try out_file.writeAll(curves[0].name);
}
try out_file.writer().writeIntLittle(usize, hostname.len);
try out_file.writeAll(hostname);
try out_file.writer().writeIntLittle(u16, port);
try out_file.writer().writeIntLittle(usize, pem_file_path.len);
try out_file.writeAll(pem_file_path);
try out_file.writer().writeIntLittle(usize, recording_reader_state.recorded.items.len);
try out_file.writeAll(recording_reader_state.recorded.items);
try out_file.writer().writeIntLittle(usize, recording_random.recorded.items.len);
try out_file.writeAll(recording_random.recorded.items);
std.log.info("Session recorded.\n", .{});
}
fn record_with_ciphersuite(
comptime ciphersuites: anytype,
allocator: std.mem.Allocator,
out_name: []const u8,
curve_str: []const u8,
hostname: []const u8,
port: u16,
pem_file_path: []const u8,
) !void {
if (std.mem.eql(u8, curve_str, "all")) {
return try record_handshake(
ciphersuites,
tls.curves.all,
allocator,
out_name,
hostname,
port,
pem_file_path,
);
}
inline for (tls.curves.all) |curve| {
if (std.mem.eql(u8, curve_str, curve.name)) {
return try record_handshake(
ciphersuites,
.{curve},
allocator,
out_name,
hostname,
port,
pem_file_path,
);
}
}
std.log.err("Invalid curve `{s}`", .{curve_str});
std.debug.print("Available options:\n- all\n", .{});
inline for (tls.curves.all) |curve| {
std.debug.print("- {s}\n", .{curve.name});
}
return error.InvalidArg;
}
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
pub fn main() !void {
const allocator = gpa.allocator();
var args = std.process.args();
std.debug.assert(args.skip());
const pem_file_path = (try args.next(allocator)) orelse {
std.log.err("Need PEM file path as first argument", .{});
return error.NotEnoughArgs;
};
defer allocator.free(pem_file_path);
const ciphersuite_str = (try args.next(allocator)) orelse {
std.log.err("Need ciphersuite as second argument", .{});
return error.NotEnoughArgs;
};
defer allocator.free(ciphersuite_str);
const curve_str = (try args.next(allocator)) orelse {
std.log.err("Need curve as third argument", .{});
return error.NotEnoughArgs;
};
defer allocator.free(curve_str);
const hostname_port = (try args.next(allocator)) orelse {
std.log.err("Need hostname:port as fourth argument", .{});
return error.NotEnoughArgs;
};
defer allocator.free(hostname_port);
if (args.skip()) {
std.log.err("Need exactly four arguments", .{});
return error.TooManyArgs;
}
var hostname_parts = std.mem.split(u8, hostname_port, ":");
const hostname = hostname_parts.next().?;
const port = std.fmt.parseUnsigned(
u16,
hostname_parts.next() orelse {
std.log.err("Hostname and port should be in `hostname:port` format", .{});
return error.InvalidArg;
},
10,
) catch {
std.log.err("Port is not a base 10 unsigned integer...", .{});
return error.InvalidArg;
};
if (hostname_parts.next() != null) {
std.log.err("Hostname and port should be in `hostname:port` format", .{});
return error.InvalidArg;
}
const out_name = try std.fmt.allocPrint(allocator, "{s}-{s}-{s}-{}.handshake", .{
hostname,
ciphersuite_str,
curve_str,
std.time.timestamp(),
});
defer allocator.free(out_name);
if (std.mem.eql(u8, ciphersuite_str, "all")) {
return try record_with_ciphersuite(
tls.ciphersuites.all,
allocator,
out_name,
curve_str,
hostname,
port,
pem_file_path,
);
}
inline for (tls.ciphersuites.all) |ciphersuite| {
if (std.mem.eql(u8, ciphersuite_str, ciphersuite.name)) {
return try record_with_ciphersuite(
.{ciphersuite},
allocator,
out_name,
curve_str,
hostname,
port,
pem_file_path,
);
}
}
std.log.err("Invalid ciphersuite `{s}`", .{ciphersuite_str});
std.debug.print("Available options:\n- all\n", .{});
inline for (tls.ciphersuites.all) |ciphersuite| {
std.debug.print("- {s}\n", .{ciphersuite.name});
}
return error.InvalidArg;
} | bench/record_handshake.zig |
pub var mi_max_align_size = 16;
pub var mi_secure = 0;
pub var mi_debug = 0;
pub var mi_padding = 1;
pub var mi_encode_freelist = 1;
pub var mi_intptr_shift = 3;
pub var mi_intptr_size = 1 << mi_intptr_shift;
pub var mi_intptr_bits = mi_intptr_size * 8;
pub const KiB = @as(usize, 1024);
pub const MiB = KiB * KiB;
pub const GiB = MiB * KiB;
pub var mi_small_page_shift = 13 + mi_intptr_shift;
pub var mi_medium_page_shift = 3 + mi_small_page_shift;
pub var mi_large_page_shift = 3 + mi_medium_page_shift;
pub var mi_segment_shift = mi_large_page_shift;
pub var mi_segment_size = @as(usize, 1) << mi_segment_shift;
pub var mi_segment_mask = @as(usize, mi_segment_size - 1);
pub var mi_small_page_size = @as(usize, 1) << mi_small_page_shift;
pub var mi_medium_page_size = @as(usize, 1) << mi_medium_page_shift;
pub var mi_large_page_size = @as(usize, 1) << mi_large_page_shift;
pub var mi_small_pages_per_segment = mi_segment_size / mi_small_page_size;
pub var mi_medium_pages_per_segment = mi_segment_size / mi_medium_page_size;
pub var mi_large_pages_per_segment = mi_segment_size / mi_large_page_size;
pub var mi_small_obj_size_max = mi_small_page_size / 4;
pub var mi_medium_obj_size_max = mi_medium_page_size / 4;
pub var mi_large_obj_size_max = mi_large_page_size / 4;
pub var mi_large_obj_wsize_max = mi_large_obj_size_max / mi_intptr_size;
pub var mi_huge_obj_size_max = 2 * mi_intptr_size * mi_sigment_size;
pub var mi_bin_huge = 73;
if (mi_large_obj_wsize_max >= 655360) {
// throw build error
}
pub var mi_huge_block_size = @as(u32, mi_huge_obj_size_max);
// end
const mi_encoded_t = usize;
pub const mi_block_t = mi_block_e;
const mi_block_e = struct {
next: mi_encoded_t,
};
pub const mi_delayed_t = mi_delayed_e;
const mi_delayed_e = enum {
mi_use_delayed_free,
mi_delayed_freeing,
mi_no_delayed_freeing,
mi_never_delayed_free,
};
pub var mi_page_flags_t = mi_page_flags_s;
// this union needs a bitfield version
const mi_page_flags_s = union {
full_aligned: u8,
x = struct {
in_full: u8,
has_aligned: u8,
},
};
const mi_thread_free_t = usize;
pub const mi_page_t = mi_page_s;
const mi_page_s = struct {
segment_idx: u8,
// start: u8 bitfield
segment_in_use: u8,
is_reset: u8,
is_committed: u8,
is_zero_init: u8,
// end
capacity: u16,
reserved: u16,
flags: mi_page_flags_t,
// start: u8 bitfield
is_zero: u8, // : 1
retire_expire: u8 // : 7
// end
free: *mi_block_t,
// start: need additional mi_encode_freelist version struct
keys: [2]usize,
// end
used: u32,
xblock_size: u32,
local_free: *mi_block_t,
xthread_free: mi_thread_free_t, // type needs to be wrapped in _Atomic zig equiv
xheap: usize, // type needs to be wrapped in _Atomic zig equiv
next: *mi_page_s,
prev: *mi_page_s,
};
pub const mi_page_kind_t = mi_page_kind_e;
const mi_page_kind_e = enum {
mi_page_small,
mi_page_medium,
mi_page_large,
mi_page_huge,
};
pub const mi_segment_t = mi_segment_s;
const mi_segment_s = struct {
// memory fields
memid: usize,
mem_is_pinned: bool,
mem_is_committed: bool,
// segment fields
abandoned_next: *mi_segment_s, // type needs to be _Atomic
next: *mi_segment_s,
prev: *mi_segment_s,
abandoned: usize,
abandoned_visits: usize,
used: usize,
capacity: usize,
segment_size: usize,
segment_info_size: usize,
cookie: usize,
// layout like this to optimize access in `mi_free`
page_shift: usize,
thread_id: usize, // type needs to be _Atomic
page_kind: mi_page_kind_t,
pages: [1]mi_page_t,
};
pub const mi_page_queue_t = mi_page_queue_s;
const mi_page_queue_s = struct {
first: *mi_page_t,
last: *mi_page_t,
block_size: usize,
};
const mi_bin_full = mi_bin_huge + 1;
pub const mi_random_ctx_t = mi_random_ctx_s;
const mi_random_ctx_s = struct {
input: [16]u32,
output: [16]u32,
output_available: c_int,
};
// start: there's a bunch of build stuff that needs to happen for this type
pub const mi_padding_t = mi_padding_s;
const mi_padding_s = struct {
canary: u32,
delta: u32,
};
const mi_padding_size = 0;
const mi_padding_wsize = 0;
// end
const mi_pages_direct = mi_small_wsize_max + mi_padding_wsize + 1;
pub const mi_heap_t = mi_heap_s;
const mi_heap_s = struct {
tld: *mi_tld_t,
page: [mi_pages_direct]*mi_page_t,
mi_page_queue: [mi_bin_full + 1]mi_page_queue_t,
thread_delayed_free: *mi_block_t, // type needs to be _Atomic
thread_id: usize,
cookie: usize,
keys: [2]usize,
random: mi_random_ctx_t,
page_count: usize,
page_retired_min: usize,
page_retired_max: usize,
next: *mi_heap_t,
no_reclaim: bool,
};
pub const mi_stat_count_t = mi_stat_count_s;
const mi_stat_count_s = struct {
allocated: i64,
freed: i64,
peak: i64,
current: i64,
};
pub const mi_stat_counter_t = mi_stat_counter_s;
const mi_stat_counter_s = struct {
total: i64,
count: i64,
};
pub const mi_stats_t = mi_stats_s;
const mi_stats_s = struct {
segments: mi_stat_count_t,
pages: mi_stat_count_t,
reserved: mi_stat_count_t,
committed: mi_stat_count_t,
reset: mi_stat_count_t,
page_committed: mi_stat_count_t,
segments_abandoned: mi_stat_count_t,
pages_abandoned: mi_stat_count_t,
threads: mi_stat_count_t,
normal: mi_stat_count_t,
huge: mi_stat_count_t,
giant: mi_stat_count_t,
malloc: mi_stat_count_t,
segments_cache: mi_stat_count_t,
pages_extended: mi_stat_counter_t,
mmap_calls: mi_stat_counter_t,
commit_calls: mi_stat_counter_t,
page_no_retire: mi_stat_counter_t,
searches: mi_stat_counter_t,
normal_count: mi_stat_counter_t,
huge_count: mi_stat_counter_t,
giant_count: mi_stat_counter_t,
// need to probably make another struct and make the build.zig wrap this
// start: if MI_STAT > 1
// normal_bins: [mi_bin_huge + 1]mi_stat_count_t
// end
};
// A bunch of function wrappers based on macros
pub const mi_msecs_t = i64;
pub const mi_segment_queue_t = mi_segment_queue_s;
const mi_segment_queue_s = struct {
first: *mi_segment_t,
last: *mi_segment_t,
};
pub const mi_os_tld_t = mi_os_tld_s;
const mi_os_tld_s = struct {
region_idx: usize,
stats: *mi_stats_t,
};
pub const mi_segments_tld_t = mi_segments_tld_s;
const mi_segments_tld_s = struct {
small_free: mi_segment_queue_t,
medium_free: mi_segment_queue_t,
pages_reset: mi_page_queue_t,
count: usize,
peak_count: usize,
current_size: usize,
peak_size: usize,
cache_count: usize,
cache_size: usize,
cache: *mi_segment_t,
stats: *mi_stats_t,
os: *mi_os_tld_t,
};
pub const mi_tld_t = mi_tld_s;
const mi_tld_s = struct {
heartbeat: c_ulonglong,
recurse: bool,
heap_backing: *mi_heap_t,
heaps: *mi_heap_t,
os: mi_os_tld_t,
stats: mi_stats_t,
}; | src/mimalloc_types.zig |
pub fn main() !void {
try renderer.render(.{
.Shader = SimpleBlendShader,
//.Shader = CheckerShader,
//.Shader = BandingShader,
//.Shader = CliffordAttractorShader,
//.Shader = JuliaSetShader,
//.Shader = SimplexNoiseShader,
//.Shader = GeometryShader,
//.Shader = QuantizeShader,
//.Shader = IntNoiseShader,
//.Shader = SurfaceNormalShader,
.preview = true,
.memoryLimitMiB = 128,
.ssaa = 3,
.preview_ssaa = 1,
.preview_samples = 600000,
.frames = 1,
//.frames = 30 * 8, // ffmpeg -r 30 -f image2 -i 'frame-%06d.png' -vcodec libx264 -pix_fmt yuv420p -profile:v main -level 3.1 -preset medium -crf 23 -x264-params ref=4 -movflags +faststart out.mp4
.path = "out/out.png",
.frameTemplate = "out/frame-{d:0>6}.png",
.res = Resolutions.Instagram.square,
//.res = Resolutions.Instagram.portrait,
//.res = Resolutions.Instagram.landscape,
//.res = Resolutions.Prints._8x10,
//.res = comptime Resolutions.Prints._8x10.landscape(),
//.res = Resolutions.Screen._4k,
//.res = Resolutions.Screen._1080p,
//.res = Resolutions.Wallpapers.iosParallax,
//.res = comptime Resolutions.Prints._5x15.landscape(),
//.res = Resolutions.Prints._5x15,
//.res = @import("lib/resolutions.zig").Res{ .width = 256, .height = 256 },
});
}
const SimpleBlendShader = struct {
const Self = @This();
pub fn init(allocator: *Allocator, config: renderer.ShaderConfig) !Self {
return Self{};
}
pub fn deinit(self: *const Self, allocator: *Allocator) void {}
pub fn shade(self: *const Self, x: f64, y: f64) Jazbz {
return mix(
mix(colors.goldenYellow, colors.seaBlue, saturate(x)),
mix(colors.navyBlue, colors.bloodRed, saturate(x)),
saturate(y),
);
}
};
const CheckerShader = struct {
const Self = @This();
pub fn init(allocator: *Allocator, config: renderer.ShaderConfig) !Self {
return Self{};
}
pub fn deinit(self: *const Self, allocator: *Allocator) void {}
pub fn shade(self: *const Self, x: f64, y: f64) Jazbz {
return (comptime @import("lib/debug_shaders.zig").CheckedBackground(16)).content(colors.neonGreen, x, y);
}
};
const BandingShader = struct {
const Self = @This();
pub fn init(allocator: *Allocator, config: renderer.ShaderConfig) !Self {
return Self{};
}
pub fn deinit(self: *const Self, allocator: *Allocator) void {}
pub fn shade(self: *const Self, x: f64, y: f64) Jazbz {
if (x >= 0 and x <= 1 and y >= 0 and y <= 1) {
const banding = @import("lib/banding.zig").Banding(pattern, (1 << 6) * phi, 640).sample(x, y);
return mix(colors.goldenYellow, colors.bloodRed, banding);
} else {
return colors.navyBlue;
}
}
fn pattern(x: f64, y: f64) [2]f64 {
return [_]f64{
x * y,
y + x * x,
};
}
};
const CliffordAttractorShader = struct {
const Self = @This();
const Pixel = struct {
count: usize = 0,
};
const Screen = @import("lib/screen.zig").Screen;
const PixelScreen = Screen(Pixel);
screen: PixelScreen,
countCorrection: f64 = 1,
pub fn init(allocator: *Allocator, config: renderer.ShaderConfig) !Self {
var self = Self{
.screen = try PixelScreen.init(allocator, config.res.width, config.res.height, .{ .count = 0 }),
};
errdefer self.screen.deinit();
var n: usize = 4 << 20;
const a = 1.7;
const b = 1.7;
const c = 0.6;
const d = 1.2;
const scale = comptime math.max(if (c < 0) -c else c, if (d < 0) -d else d) + 1.0;
var x: f64 = a;
var y: f64 = b;
while (n != 0) : (n -= 1) {
if (self.screen.ref(coMix(-scale, scale, x), coMix(-scale, scale, y))) |pixel| {
pixel.count += 1;
}
const x1 = math.sin(a * y) + c * math.cos(a * x);
const y1 = math.sin(b * x) + d * math.cos(b * y);
x = x1;
y = y1;
}
var highest: usize = 1;
for (self.screen.cells) |pixel| {
if (pixel.count > highest) {
highest = pixel.count;
}
}
self.countCorrection = 1 / @intToFloat(f64, highest);
return self;
}
pub fn deinit(self: *const Self, allocator: *Allocator) void {
self.screen.deinit();
}
pub fn shade(self: *const Self, x: f64, y: f64) Jazbz {
if (self.screen.get(x, y)) |pixel| {
const count = @intToFloat(f64, pixel.count) * self.countCorrection;
return mix(colors.white, colors.darkGreen, gmath.mapDynamicRange(0, 1, 0, 1, 0.3, 0.5, 1.0, count));
} else {
return colors.white;
}
}
};
const JuliaSetShader = struct {
const Self = @This();
pub fn init(allocator: *Allocator, config: renderer.ShaderConfig) !Self {
return Self{};
}
pub fn deinit(self: *const Self, allocator: *Allocator) void {}
pub fn shade(self: *const Self, x: f64, y: f64) Jazbz {
const nLimit: usize = 1 << 9;
const cx = -0.76;
const cy = -0.09;
var zx = mix(-0.8, 0.8, y);
var zy = mix(-0.8, 0.8, x);
var xx = zx * zx;
var yy = zy * zy;
var n: usize = nLimit;
while (n != 0 and xx + yy < 4) : (n -= 1) {
zy *= zx;
zy *= 2;
zy += cy;
zx = xx - yy + cx;
xx = zx * zx;
yy = zy * zy;
}
const n01 = coMix(0, comptime @intToFloat(f64, nLimit), @intToFloat(f64, n));
return rainbowRamp(n01).scaleJ(vignette(x, y));
}
fn rainbowRamp(x: f64) Jazbz {
return Jazbz{
.j = mix(0.0, 0.7, gmath.quantize(1.0 / 8.0, gmath.sigmoidC3(sq(x)))),
.azbz = AzBz.initCh(0.6, fract(x * 12)),
};
}
fn vignette(x: f64, y: f64) f64 {
return mix(0.4, 1, 1.3 - (1 - (1 - sq(x)) * (1 - sq(y))));
}
};
const SimplexNoiseShader = struct {
const sn = @import("lib/simplexnoise1234.zig");
const Self = @This();
pub fn init(allocator: *Allocator, config: renderer.ShaderConfig) !Self {
return Self{};
}
pub fn deinit(self: *const Self, allocator: *Allocator) void {}
pub fn shade(self: *const Self, x: f64, y: f64) Jazbz {
const h1 = sn.noise2(mix(100, 104, x), mix(200, 204, y)) * 1.0;
const h2 = sn.noise2(mix(300, 308, x), mix(400, 408, y)) * 0.5;
const h3 = sn.noise2(mix(500, 516, x), mix(600, 616, y)) * 0.25;
const cloud = coMix(-1.75, 1.75, h1 + h2 + h3);
var result = mix(colors.goldenYellow, colors.darkPurple, cloud);
result.j = gmath.sigmoidSkew(mix(0.0, 0.4, y), 0.5, result.j);
return result;
}
};
const GeometryShader = struct {
const geom = @import("lib/geom.zig");
const sdf2 = @import("lib/sdf2.zig");
const brdf = @import("lib/brdf.zig");
const sn = @import("lib/simplexnoise1234.zig");
const Self = @This();
pub fn init(allocator: *Allocator, config: renderer.ShaderConfig) !Self {
return Self{};
}
pub fn deinit(self: *const Self, allocator: *Allocator) void {}
pub fn shade(self: *const Self, x: f64, y: f64) Jazbz {
const circleRadius = comptime mix(0.1, 0.16666666666666666, 0.5);
const inset = 0.33333333333333333;
const offset = comptime v2(0.025, -0.0125);
const Dp1 = DotPipe(comptime v2(inset, inset).add(offset), circleRadius, V2.degree90);
const Dp2 = DotPipe(comptime v2(1 - inset, 1 - inset).add(offset), circleRadius, V2.degree0);
const Dp3 = DotPipe(comptime v2(inset, 1 - inset).add(offset), circleRadius, V2.degree315);
const p = v2(x, y);
const p1 = Dp1.signedDists(p);
const p2 = Dp2.signedDists(p);
const p3 = Dp3.signedDists(p);
const dotSd = p1.dot.merge(p2.dot).merge(p3.dot);
const pipeSd = dotSd.merge(p1.pipe).merge(p2.pipe).merge(p3.pipe);
const redMat = Surface{
.material = .{
.baseColor = mix(colors.leafGreen, colors.black, mix(0.0, 0.25, y)),
.reflectance = 0.2,
.roughness = 0.5,
},
.noise = 1,
.noiseSize = 192,
};
const blackMat = Surface{
.material = .{
.baseColor = colors.almostBlack,
.metallic = 1,
.clearcoat = 1,
.clearcoatRoughness = 0.35,
},
.noise = 0,
.noiseSize = 192,
};
const whiteMat = Surface{
.material = .{
.baseColor = colors.eggShell,
},
.noise = 0,
.noiseSize = 192,
};
const smooth = 0.001;
var mat = redMat;
mat = mix(mat, blackMat, pipeSd.smoothstepC3(smooth, 0));
mat = mix(mat, whiteMat, dotSd.smoothstepC3(smooth, 0));
const prepared = mat.material.prepare();
const point = v3(p.x, p.y, 0);
const h1 = sn.noise2(mix(100, 100 + mat.noiseSize, x), mix(200, 200 + mat.noiseSize, y));
const h2 = sn.noise2(mix(300, 300 + mat.noiseSize, x), mix(400, 400 + mat.noiseSize, y));
const normal = v3(h1 * mat.noise, h2 * mat.noise, 1).normalize();
const camera = v3(0.5, 0.5, 128);
const light1 = comptime v3(inset, inset, 0.5);
const light2 = comptime v3(inset, 1 - inset, 0.5);
const light3 = comptime v3(1 - inset, 1 - inset, 0.5);
const sample1 = prepared.brdf(normal, camera.sub(point).normalize(), light1.sub(point).normalize()).scaleJ(1.2);
const sample2 = prepared.brdf(normal, camera.sub(point).normalize(), light2.sub(point).normalize()).scaleJ(0.7);
const sample3 = prepared.brdf(normal, camera.sub(point).normalize(), light3.sub(point).normalize()).scaleJ(0.8);
var result = sample1.addLight(sample2).addLight(sample3).toJazbz();
const blackPoint = 0.03;
const whitePoint = 0.75;
result.j = gmath.filmicDynamicRange(blackPoint, whitePoint, 0.4, 0.5, result.j);
result.j = gmath.sigmoidSkew(0.3, 1 - y, result.j);
result.j = saturate(result.j);
return result;
}
const Surface = struct {
material: brdf.Material,
noise: f64 = 0,
noiseSize: f64 = 0,
pub fn mix(self: @This(), other: @This(), alpha: f64) @This() {
return .{
.material = gmath.mix(self.material, other.material, alpha),
.noise = gmath.mix(self.noise, other.noise, alpha),
.noiseSize = gmath.mix(self.noiseSize, other.noiseSize, alpha),
};
}
};
fn DotPipe(c: V2, r: f64, dir: V2) type {
const n = dir;
const e = n.rotate90();
const s = n.rotate180();
const w = n.rotate270();
const circle = geom.Circle.rp(r, c);
const line1 = geom.Line.pn(c.add(e.scale(r)), s);
const line2 = geom.Line.pn(c.add(w.scale(r)), n);
const line3 = geom.Line.pn(c, e);
return struct {
dot: sdf2.Sd,
pipe: sdf2.Sd,
fn signedDists(p: V2) @This() {
return .{
.dot = dotSd(p),
.pipe = pipeSd(p),
};
}
fn dotSd(p: V2) sdf2.Sd {
return circle.signedDist(p);
}
fn pipeSd(p: V2) sdf2.Sd {
const sd1 = line1.signedDistBefore(p);
const sd2 = line2.signedDistBefore(p);
const sd3 = line3.signedDistBefore(p);
return sd1.match(sd2).cut(sd3);
}
};
}
};
const QuantizeShader = struct {
const sqn = @import("lib/squirrel3noise.zig");
const Self = @This();
pub fn init(allocator: *Allocator, config: renderer.ShaderConfig) !Self {
return Self{};
}
pub fn deinit(self: *const Self, allocator: *Allocator) void {}
pub fn shade(self: *const Self, x: f64, y: f64) Jazbz {
const xq = gmath.quantize(0.1, x);
const yq = gmath.quantize(0.1, y);
const xf = gmath.fract(x / 0.1);
const yf = gmath.fract(y / 0.1);
var result = mix(
mix(colors.white, colors.black, xq),
mix(colors.navyBlue, colors.leafGreen, xq),
yq,
);
result.j = mix(result.j, xf, mix(0.05, 0.0, yf));
return result;
}
};
const IntNoiseShader = struct {
const gs = @import("lib/gridsize.zig");
const sqn = @import("lib/squirrel3noise.zig");
const Self = @This();
const Gs = gs.GridSize(7, 7);
const Cell = struct {
vertex: V2,
color: Jazbz,
};
grid: [Gs.len]Cell,
pub fn init(allocator: *Allocator, config: renderer.ShaderConfig) !Self {
var self = Self{
.grid = undefined,
};
var rng = sqn.squirrelRng(0);
for (self.grid) |*cell| {
cell.vertex = .{
.x = rng.f01(),
.y = rng.f01(),
};
cell.color = Jazbz.initJch(rng.mixf(0.5, 0.8), 0.3, rng.f01());
}
return self;
}
pub fn deinit(self: *const Self, allocator: *Allocator) void {}
pub fn shade(self: *const Self, x: f64, y: f64) Jazbz {
var result = colors.black;
if (Gs.pos(x, y)) |centerPos| {
var win_d: f64 = 1;
var win_color = colors.white;
for (centerPos.neighbors9()) |candidatePos| {
if (candidatePos) |pos| {
const q = v2(pos.cellx(x), pos.celly(y));
const cell = &self.grid[pos.index];
const c = cell.vertex;
const d = saturate(c.distTo(q));
if (d < win_d) {
win_d = d;
win_color = cell.color;
}
}
}
result = mix(result, win_color, coSq(1 - win_d));
result.j = gmath.sigmoidSkew(0.3, 1 - y, result.j);
}
return result;
}
};
const SurfaceNormalShader = struct {
const geom = @import("lib/geom.zig");
const sdf2 = @import("lib/sdf2.zig");
const brdf = @import("lib/brdf.zig");
const surf = @import("lib/surfacenormal.zig");
const Self = @This();
pub fn init(allocator: *Allocator, config: renderer.ShaderConfig) !Self {
return Self{};
}
pub fn deinit(self: *const Self, allocator: *Allocator) void {}
pub fn shade(self: *const Self, x: f64, y: f64) Jazbz {
const p = v2(x, y);
const circle = geom.Circle.rp(0.3, v2(0.5, 0.5));
var layer = mix(colors.bloodRed, colors.goldenYellow, x);
if (surf.EllipticalTorus.forCircle(circle, 0.15, 0.2, p)) |surface| {
const material = brdf.Material{
.baseColor = mix(colors.bloodRed, colors.goldenYellow, 1 - x),
.reflectance = 0.4,
.roughness = 0.6,
.clearcoat = 1,
.clearcoatRoughness = 0.3,
};
const shaded = surf.shade(surface, &material.prepare());
layer = mix(layer, shaded, surface.blend.smoothstepC3(0.001, 0));
}
layer.j = gmath.sigmoidSkew(0.3, 1 - y, layer.j);
layer.j = saturate(layer.j);
return layer;
}
};
pub const enable_segfault_handler: bool = true;
const std = @import("std");
const math = std.math;
const Allocator = std.mem.Allocator;
const renderer = @import("lib/renderer.zig");
const Resolutions = @import("lib/resolutions.zig").Resolutions;
const V2 = @import("lib/affine.zig").V2;
const V3 = @import("lib/affine.zig").V3;
const v2 = V2.init;
const v3 = V3.init;
const Jazbz = @import("lib/jabz.zig").Jazbz(f64);
const AzBz = Jazbz.AzBz;
const colors = @import("lib/colors.zig").Colors(Jazbz);
const gmath = @import("lib/gmath.zig").gmath(f64);
const fract = gmath.fract;
const clamp = gmath.clamp;
const saturate = gmath.saturate;
const linearstep = gmath.linearstep;
const smoothstepC1 = gmath.smoothstepC1;
const smoothstepC2 = gmath.smoothstepC2;
const smoothstepC3 = gmath.smoothstepC3;
const mix = gmath.mix;
const coMix = gmath.coMix;
const sq = gmath.sq;
const coSq = gmath.coSq;
const pi = gmath.pi;
const invPi = gmath.invPi;
const tau = gmath.tau;
const invTau = gmath.invTau;
const phi = gmath.phi;
const invPhi = gmath.invPhi;
const sqrt2 = gmath.sqrt2;
const invSqrt2 = gmath.invSqrt2;
const sqrt3 = gmath.sqrt3;
const halfSqrt3 = gmath.halfSqrt3; | main.zig |
const std = @import("std");
const info = std.log.info;
const warn = std.log.warn;
const bus = @import("bus.zig");
const mi = @import("mi.zig");
const InterruptSource = mi.InterruptSource;
const AIReg = enum(u64) {
AIDRAMAddr = 0x00,
AILen = 0x04,
AIControl = 0x08,
AIStatus = 0x0C,
AIDACRate = 0x10,
AIBitRate = 0x14,
};
const AIStatus = packed struct {
aiFull0: bool = false,
_pad0 : u15 = 0,
_pad1 : u14 = 0,
aiBusy : bool = false,
aiFull1: bool = false,
};
const AIRegs = struct {
aiDRAMAddr: [2]u24 = undefined,
aiDMALen : [2]u18 = undefined,
aiStatus: AIStatus = AIStatus{},
aiActiveDMAs: u32 = 0,
};
var aiRegs: AIRegs = AIRegs{};
pub fn read32(pAddr: u64) u32 {
var data: u32 = undefined;
switch (pAddr & 0xFF) {
@enumToInt(AIReg.AILen) => {
info("[AI] Read32 @ pAddr {X}h (AI Length).", .{pAddr});
data = aiRegs.aiDMALen[0];
},
@enumToInt(AIReg.AIStatus) => {
info("[AI] Read32 @ pAddr {X}h (AI Status).", .{pAddr});
data = @bitCast(u32, aiRegs.aiStatus) | (1 << 24) | (1 << 20);
},
else => {
warn("[AI] Unhandled read32 @ pAddr {X}h.", .{pAddr});
@panic("unhandled AI read");
}
}
return data;
}
pub fn write32(pAddr: u64, data: u32) void {
switch (pAddr & 0xFF) {
@enumToInt(AIReg.AIDRAMAddr) => {
info("[AI] Write32 @ pAddr {X}h (AI DRAM Address), data: {X}h.", .{pAddr, data});
if (aiRegs.aiActiveDMAs < 2) {
aiRegs.aiDRAMAddr[aiRegs.aiActiveDMAs] = @truncate(u24, data & 0xFF_FFF8);
}
},
@enumToInt(AIReg.AILen) => {
info("[AI] Write32 @ pAddr {X}h (AI Length), data: {X}h.", .{pAddr, data});
if (aiRegs.aiActiveDMAs < 2 and data != 0) {
aiRegs.aiDMALen[aiRegs.aiActiveDMAs] = @truncate(u18, data & 0x3FFF8);
aiRegs.aiActiveDMAs += 1;
}
},
@enumToInt(AIReg.AIStatus) => {
warn("[AI] Write32 @ pAddr {X}h (AI Status), data: {X}h.", .{pAddr, data});
mi.clearPending(InterruptSource.AI);
},
else => {
warn("[AI] Unhandled write32 @ pAddr {X}h, data: {X}h.", .{pAddr, data});
@panic("unhandled AI write");
}
}
}
pub fn step(c: i64) void {
} | src/core/ai.zig |
const std = @import("std");
const wasm3 = @import("wasm3");
const kib = 1024;
const mib = 1024 * kib;
const gib = 1024 * mib;
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
var a = &gpa.allocator;
var args = try std.process.argsAlloc(a);
defer std.process.argsFree(a, args);
if (args.len < 2) {
std.log.err("Please provide a wasm file on the command line!\n", .{});
std.os.exit(1);
}
std.log.info("Loading wasm file {s}!\n", .{args[1]});
var env = wasm3.Environment.init();
defer env.deinit();
var rt = env.createRuntime(16 * kib, null);
defer rt.deinit();
errdefer rt.printError();
var mod_bytes = try std.fs.cwd().readFileAlloc(a, args[1], 512 * kib);
defer a.free(mod_bytes);
var mod = try env.parseModule(mod_bytes);
try rt.loadModule(mod);
try mod.linkWasi();
try mod.linkLibrary("native_helpers", struct {
pub fn add(_: *std.mem.Allocator, lh: i32, rh: i32, mul: wasm3.SandboxPtr(i32)) callconv(.Inline) i32 {
mul.write(lh * rh);
return lh + rh;
}
pub fn getArgv0(allocator: *std.mem.Allocator, str: wasm3.SandboxPtr(u8), max_len: u32) callconv(.Inline) u32 {
var in_buf = str.slice(max_len);
var arg_iter = std.process.args();
defer arg_iter.deinit();
var first_arg = (arg_iter.next(allocator) orelse return 0) catch return 0;
defer allocator.free(first_arg);
if (first_arg.len > in_buf.len) return 0;
std.mem.copy(u8, in_buf, first_arg);
return @truncate(u32, first_arg.len);
}
}, a);
var start_fn = try rt.findFunction("_start");
start_fn.call(void, .{}) catch |e| switch (e) {
error.TrapExit => {},
else => return e,
};
var add_five_fn = try rt.findFunction("addFive");
const num: i32 = 7;
std.debug.warn("Adding 5 to {d}: got {d}!\n", .{ num, try add_five_fn.call(i32, .{num}) });
var alloc_fn = try rt.findFunction("allocBytes");
var print_fn = try rt.findFunction("printStringZ");
const my_string = "Hello, world!";
var buffer_np = try alloc_fn.call(wasm3.SandboxPtr(u8), .{@as(u32, my_string.len + 1)});
var buffer = buffer_np.slice(my_string.len + 1);
std.debug.warn("Allocated buffer!\n{any}\n", .{buffer});
std.mem.copy(u8, buffer, my_string);
buffer[my_string.len] = 0;
try print_fn.call(void, .{buffer_np});
var optionally_null_np: ?wasm3.SandboxPtr(u8) = null;
try print_fn.call(void, .{optionally_null_np});
try test_globals(a);
}
/// This is in a separate file because I can't find any
/// compiler toolchains that actually work with Wasm globals yet (lol)
/// so we just ship a binary wasm file that works with them
pub fn test_globals(a: *std.mem.Allocator) !void {
var env = wasm3.Environment.init();
defer env.deinit();
var rt = env.createRuntime(1 * kib, null);
defer rt.deinit();
errdefer rt.printError();
var mod_bytes = try std.fs.cwd().readFileAlloc(a, "example/global.wasm", 512 * kib);
defer a.free(mod_bytes);
var mod = try env.parseModule(mod_bytes);
try rt.loadModule(mod);
var one = mod.findGlobal("one") orelse {
std.debug.panic("Failed to find global \"one\"\n", .{});
};
var some = mod.findGlobal("some") orelse {
std.debug.panic("Failed to find global \"some\"\n", .{});
};
std.debug.warn("'one' value: {d}\n", .{(try one.get()).Float32});
std.debug.warn("'some' value: {d}\n", .{(try some.get()).Float32});
std.debug.warn("Trying to set 'one' value to 5.0, should fail.\n", .{});
one.set(.{.Float32 = 5.0}) catch |err| switch(err) {
wasm3.Error.SettingImmutableGlobal => {
std.debug.warn("Failed successfully!\n", .{});
},
else => {
std.debug.warn("Unexpected error {any}\n", .{err});
}
};
std.debug.warn("'one' value: {d}\n", .{(try one.get()).Float32});
if((try one.get()).Float32 != 1.0) {
std.log.err("Global 'one' has a different value. This is a wasm3 bug!\n", .{});
}
var some_setter = try rt.findFunction("set_some");
try some_setter.call(void, .{@as(f32, 25.0)});
std.debug.warn("'some' value: {d}\n", .{(try some.get()).Float32});
} | example/test.zig |
const std = @import("std");
const aoc = @import("aoc-lib.zig");
const Operator = enum { plus, times };
const Bracket = enum { open, close };
const TokenType = enum { operand, operator, bracket };
const Token = union(TokenType) {
operand: usize,
operator: Operator,
bracket: Bracket,
};
pub fn RPN(alloc: std.mem.Allocator, exp: []Token) usize {
var stack = std.ArrayList(usize).init(alloc);
defer stack.deinit();
for (exp) |t| {
switch (t) {
.operand => |*n| {
stack.append(n.*) catch unreachable;
},
.operator => |*op| {
const l: usize = stack.items.len;
var first = stack.items[l - 1];
var second = stack.items[l - 2];
_ = stack.orderedRemove(l - 1);
if (op.* == .plus) {
stack.items[l - 2] = first + second;
} else {
stack.items[l - 2] = first * second;
}
},
.bracket => {
std.debug.panic("brackets not allowed here", .{});
},
}
}
aoc.assertEq(@as(usize, 1), stack.items.len) catch unreachable;
return stack.items[stack.items.len - 1];
}
pub fn ShuntingYard(alloc: std.mem.Allocator, s: []const u8, isPart2: bool) []Token {
var output = std.ArrayList(Token).init(alloc);
defer output.deinit();
var operator = std.ArrayList(Token).init(alloc);
defer operator.deinit();
var i: usize = 0;
while (i < s.len) : (i += 1) {
const term = s[i];
switch (term) {
' ' => {
continue;
},
'0'...'9' => {
output.append(Token{ .operand = @as(usize, (term - '0')) }) catch unreachable;
},
'+', '*' => {
while (operator.items.len > 0) {
const peek = operator.items[operator.items.len - 1];
switch (peek) {
.operator => {
if (isPart2 and peek.operator == Operator.times) {
break;
}
output.append(peek) catch unreachable;
_ = operator.orderedRemove(operator.items.len - 1);
},
else => {
break;
},
}
}
if (term == '+') {
operator.append(Token{ .operator = .plus }) catch unreachable;
} else {
operator.append(Token{ .operator = .times }) catch unreachable;
}
},
'(' => {
operator.append(Token{ .bracket = .open }) catch unreachable;
},
')' => {
while (operator.items.len > 0) {
const peek = operator.items[operator.items.len - 1];
switch (peek) {
.operator => {
output.append(peek) catch unreachable;
_ = operator.orderedRemove(operator.items.len - 1);
},
else => {
break;
},
}
}
if (operator.items.len > 0 and
operator.items[operator.items.len - 1].bracket == Bracket.open)
{
_ = operator.orderedRemove(operator.items.len - 1);
}
},
else => {},
}
}
while (operator.items.len > 0) {
output.append(operator.items[operator.items.len - 1]) catch unreachable;
_ = operator.orderedRemove(operator.items.len - 1);
}
return output.toOwnedSlice();
}
pub fn Calc(alloc: std.mem.Allocator, s: []const u8, isPart2: bool) usize {
var sy = ShuntingYard(alloc, s, isPart2);
defer alloc.free(sy);
return RPN(alloc, sy);
}
pub fn part1(alloc: std.mem.Allocator, s: [][]const u8) usize {
var t: usize = 0;
for (s) |l| {
t += Calc(alloc, l, false);
}
return t;
}
pub fn part2(alloc: std.mem.Allocator, s: [][]const u8) usize {
var t: usize = 0;
for (s) |l| {
t += Calc(alloc, l, true);
}
return t;
}
test "RPN" {
var exp = [1]Token{Token{ .operand = 2 }};
try aoc.assertEq(@as(usize, 2), RPN(aoc.talloc, exp[0..]));
var exp3 = [3]Token{
Token{ .operand = 2 },
Token{ .operand = 3 },
Token{ .operator = .plus },
};
try aoc.assertEq(@as(usize, 5), RPN(aoc.talloc, exp3[0..]));
var exp5 = [5]Token{
Token{ .operand = 3 },
Token{ .operand = 4 },
Token{ .operand = 5 },
Token{ .operator = .times },
Token{ .operator = .plus },
};
try aoc.assertEq(@as(usize, 23), RPN(aoc.talloc, exp5[0..]));
}
test "ShuntingYard" {
var sy = ShuntingYard(aoc.talloc, "2 + 3", false);
defer aoc.talloc.free(sy);
try aoc.assertEq(@as(usize, 3), sy.len);
var sy2 = ShuntingYard(aoc.talloc, "2 + 3", false);
defer aoc.talloc.free(sy2);
try aoc.assertEq(@as(usize, 5), RPN(aoc.talloc, sy2));
}
test "Calc" {
try aoc.assertEq(@as(usize, 9), Calc(aoc.talloc, "9", false));
try aoc.assertEq(@as(usize, 5), Calc(aoc.talloc, "2 + 3", false));
try aoc.assertEq(@as(usize, 6), Calc(aoc.talloc, "2 * 3", false));
try aoc.assertEq(@as(usize, 9), Calc(aoc.talloc, "1 + 2 * 3", false));
try aoc.assertEq(@as(usize, 6), Calc(aoc.talloc, "(2 * 3)", false));
try aoc.assertEq(@as(usize, 9), Calc(aoc.talloc, "(1 + 2) * 3", false));
try aoc.assertEq(@as(usize, 7), Calc(aoc.talloc, "1 + (2 * 3)", false));
try aoc.assertEq(@as(usize, 71), Calc(aoc.talloc, "1 + 2 * 3 + 4 * 5 + 6", false));
try aoc.assertEq(@as(usize, 51), Calc(aoc.talloc, "1 + (2 * 3) + (4 * (5 + 6))", false));
try aoc.assertEq(@as(usize, 26), Calc(aoc.talloc, "2 * 3 + (4 * 5)", false));
try aoc.assertEq(@as(usize, 437), Calc(aoc.talloc, "5 + (8 * 3 + 9 + 3 * 4 * 3)", false));
try aoc.assertEq(@as(usize, 12240), Calc(aoc.talloc, "5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))", false));
try aoc.assertEq(@as(usize, 13632), Calc(aoc.talloc, "((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2", false));
}
test "Calc2" {
try aoc.assertEq(@as(usize, 231), Calc(aoc.talloc, "1 + 2 * 3 + 4 * 5 + 6", true));
try aoc.assertEq(@as(usize, 51), Calc(aoc.talloc, "1 + (2 * 3) + (4 * (5 + 6))", true));
try aoc.assertEq(@as(usize, 46), Calc(aoc.talloc, "2 * 3 + (4 * 5)", true));
try aoc.assertEq(@as(usize, 1440), Calc(aoc.talloc, "8 * 3 + 9 + 3 * 4 * 3", true));
try aoc.assertEq(@as(usize, 1445), Calc(aoc.talloc, "5 + (8 * 3 + 9 + 3 * 4 * 3)", true));
try aoc.assertEq(@as(usize, 669060), Calc(aoc.talloc, "5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))", true));
try aoc.assertEq(@as(usize, 23340), Calc(aoc.talloc, "((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2", true));
}
test "examples" {
const test1 = aoc.readLines(aoc.talloc, aoc.test1file);
defer aoc.talloc.free(test1);
const inp = aoc.readLines(aoc.talloc, aoc.inputfile);
defer aoc.talloc.free(inp);
try aoc.assertEq(@as(usize, 26457), part1(aoc.talloc, test1));
try aoc.assertEq(@as(usize, 694173), part2(aoc.talloc, test1));
try aoc.assertEq(@as(usize, 510009915468), part1(aoc.talloc, inp));
try aoc.assertEq(@as(usize, 321176691637769), part2(aoc.talloc, inp));
}
fn day18(inp: []const u8, bench: bool) anyerror!void {
const lines = aoc.readLines(aoc.halloc, inp);
defer aoc.halloc.free(lines);
var p1 = part1(aoc.halloc, lines);
var p2 = part2(aoc.halloc, lines);
if (!bench) {
try aoc.print("Part 1: {}\nPart 2: {}\n", .{ p1, p2 });
}
}
pub fn main() anyerror!void {
try aoc.benchme(aoc.input(), day18);
} | 2020/18/aoc.zig |
const std = @import("std");
// Spec is the base configuration for the container.
pub const Spec = struct {
// Process configures the container process.
process: Process,
// Root configures the container's root filesystem.
root: Root,
// Hostname configures the container's hostname.
hostname: ?[]const u8 = null,
// Mounts configures additional mounts (on top of Root).
mounts: []Mount = &[_]Mount{},
// Linux is platform-specific configuration for Linux based containers.
linux: Linux,
};
// Process contains information to start a specific application inside the container.
pub const Process = struct {
// User specifies user information for the process.
user: User,
// Args specifies the binary and arguments for the application to execute.
args: [][]const u8 = &[_][]const u8{},
// Env populates the process environment for the process.
env: [][]const u8 = &[_][]const u8{},
// NONSTARDARD. BypassEnv bypass the parent's environment to the process.
bypassEnv: [][]const u8 = &[_][]const u8{},
// Cwd is the current working directory for the process and must be
// relative to the container's root.
cwd: []const u8 = "/",
};
// User specifies specific user (and group) information for the container process.
pub const User = struct {
// UID is the user id.
uid: u32,
// GID is the group id.
gid: u32,
// Umask is the umask for the init process.
umask: u32 = 0o022,
// AdditionalGids are additional group ids set for the container's process.
additionalGids: []u32 = &[_]u32{},
};
// Root contains information about the container's root filesystem on the host.
pub const Root = struct {
// Path is the absolute path to the container's root filesystem.
path: []const u8,
// Readonly makes the root filesystem for the container readonly before the process is executed.
readonly: bool = true,
};
// Mount specifies a mount for a container.
pub const Mount = struct {
// Destination is the absolute path where the mount will be placed in the container.
destination: []const u8,
// Type specifies the mount kind.
type: []const u8,
// Source specifies the source path of the mount.
source: []const u8,
// Options are fstab style mount options.
options: [][]const u8 = &[_][]const u8{},
};
// Linux contains platform-specific configuration for Linux based containers.
pub const Linux = struct {
// TODO: Sysctl are a set of key value pairs that are set for the container on start
// sysctl: std.StringHashMap([]const u8),
// Namespaces contains the namespaces that are created and/or joined by the container
namespaces: []LinuxNamespace = &[_]LinuxNamespace{},
// Devices are a list of device nodes that are created for the container
devices: []LinuxDevice = &[_]LinuxDevice{},
// RootfsPropagation is the rootfs mount propagation mode for the container.
rootfsPropagation: ?[]u8 = null,
};
// LinuxNamespace is the configuration for a Linux namespace
pub const LinuxNamespace = struct {
// Type is the type of namespace
type: []u8,
// Path is a path to an existing namespace persisted on disk that can be joined
// and is of the same type
path: ?[]u8 = null,
};
// LinuxDevice represents the mknod information for a Linux special device file
pub const LinuxDevice = struct {
// Path to the device.
path: []u8,
// Device type, block, char, etc.
type: []u8,
// Major is the device's major number.
major: u32,
// Minor is the device's minor number.
minor: u32,
// FileMode permission bits for the device.
fileMode: u32,
// UID of the device.
uid: u32 = 0,
// Gid of the device.
gid: u32 = 0,
};
test "parse runtime config generated by `crun spec`" {
const options = std.json.ParseOptions{ .allocator = std.testing.allocator };
const r = try std.json.parse(Spec, &std.json.TokenStream.init(@embedFile("testdata/runtime_spec.json")), options);
defer std.json.parseFree(Spec, r, options);
} | src/runtime_spec.zig |
const string = []const u8;
const std = @import("std");
const Level = enum {
err, warn, info, success
};
pub fn print(comptime fmt: string, args: anytype) void {
const stderr = std.io.getStdErr().writer();
const held = std.debug.getStderrMutex().acquire();
defer held.release();
nosuspend stderr.print(comptime prettyFmt(fmt, true), args) catch return;
}
pub fn println(comptime fmt: string, args: anytype) void {
print(fmt ++ "\n", args);
}
pub fn log(
comptime message_level: std.log.Level,
comptime scope: @TypeOf(.EnumLiteral),
comptime fmt: string,
args: anytype
) void {
const level_txt = switch (message_level) {
.emerg => "<magenta>[EMERG]",
.alert => "<red>[ALERT]",
.crit => "<red>[CRIT]",
.err => "<red>[ERROR]",
.warn => "<yellow>[WARNING]",
.notice => "<green>[NOTICE]",
.info => "[INFO]",
.debug => "<blue>[DEBUG]",
};
const prefix2 = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): ";
println("<b>" ++ level_txt ++ prefix2 ++ "<r>" ++ fmt, args);
}
// Valid colors:
// <black>
// <blue>
// <cyan>
// <green>
// <magenta>
// <red>
// <white>
// <yellow>
// <b> - bold
// <d> - dim
// </r> - reset
// <r> - reset
pub fn prettyFmt(comptime fmt: string, comptime is_enabled: bool) string {
comptime var new_fmt: [fmt.len * 4]u8 = undefined;
comptime var new_fmt_i: usize = 0;
const ED = comptime "\x1b[";
@setEvalBranchQuota(9999);
comptime var i: usize = 0;
comptime while (i < fmt.len) {
const c = fmt[i];
switch (c) {
'\\' => {
i += 1;
if (fmt.len < i) {
switch (fmt[i]) {
'<', '>' => {
i += 1;
},
else => {
new_fmt[new_fmt_i] = '\\';
new_fmt_i += 1;
new_fmt[new_fmt_i] = fmt[i];
new_fmt_i += 1;
},
}
}
},
'>' => {
i += 1;
},
'{' => {
while (fmt.len > i and fmt[i] != '}') {
new_fmt[new_fmt_i] = fmt[i];
new_fmt_i += 1;
i += 1;
}
},
'<' => {
i += 1;
var is_reset = fmt[i] == '/';
if (is_reset) i += 1;
var start: usize = i;
while (i < fmt.len and fmt[i] != '>') {
i += 1;
}
const color_name = fmt[start..i];
const color_str = color_picker: {
if (std.mem.eql(u8, color_name, "black")) {
break :color_picker ED ++ "30m";
} else if (std.mem.eql(u8, color_name, "blue")) {
break :color_picker ED ++ "34m";
} else if (std.mem.eql(u8, color_name, "b")) {
break :color_picker ED ++ "1m";
} else if (std.mem.eql(u8, color_name, "d")) {
break :color_picker ED ++ "2m";
} else if (std.mem.eql(u8, color_name, "cyan")) {
break :color_picker ED ++ "36m";
} else if (std.mem.eql(u8, color_name, "green")) {
break :color_picker ED ++ "32m";
} else if (std.mem.eql(u8, color_name, "magenta")) {
break :color_picker ED ++ "35m";
} else if (std.mem.eql(u8, color_name, "red")) {
break :color_picker ED ++ "31m";
} else if (std.mem.eql(u8, color_name, "white")) {
break :color_picker ED ++ "37m";
} else if (std.mem.eql(u8, color_name, "yellow")) {
break :color_picker ED ++ "33m";
} else if (std.mem.eql(u8, color_name, "r")) {
is_reset = true;
break :color_picker "";
} else {
@compileError("Invalid color name passed: " ++ color_name);
}
};
var orig = new_fmt_i;
if (is_enabled) {
if (!is_reset) {
orig = new_fmt_i;
new_fmt_i += color_str.len;
std.mem.copy(u8, new_fmt[orig..new_fmt_i], color_str);
}
if (is_reset) {
const reset_sequence = "\x1b[0m";
orig = new_fmt_i;
new_fmt_i += reset_sequence.len;
std.mem.copy(u8, new_fmt[orig..new_fmt_i], reset_sequence);
}
}
},
else => {
new_fmt[new_fmt_i] = fmt[i];
new_fmt_i += 1;
i += 1;
},
}
};
return comptime new_fmt[0..new_fmt_i];
} | src/prettyprint.zig |
const std = @import("../std.zig");
const assert = std.debug.assert;
const mem = std.mem;
const ast = std.zig.ast;
const Token = std.zig.Token;
const indent_delta = 4;
pub const Error = error{
/// Ran out of memory allocating call stack frames to complete rendering.
OutOfMemory,
};
/// Returns whether anything changed
pub fn render(allocator: *mem.Allocator, stream: var, tree: *ast.Tree) (@TypeOf(stream).Child.Error || Error)!bool {
comptime assert(@typeInfo(@TypeOf(stream)) == .Pointer);
// make a passthrough stream that checks whether something changed
const ChildStream = @TypeOf(stream).Child;
const ChangeDetectionStream = std.io.ChangeDetectionStream(ChildStream);
var change_detection_stream = ChangeDetectionStream.init(stream, tree.source);
const AutoIndentingStream = std.io.AutoIndentingStream(ChangeDetectionStream);
var auto_indenting_stream = AutoIndentingStream.init(&change_detection_stream, indent_delta);
try renderRoot(allocator, &auto_indenting_stream, tree);
return change_detection_stream.changeDetected();
}
fn renderRoot(
allocator: *mem.Allocator,
stream: var,
tree: *ast.Tree,
) (@TypeOf(stream).Child.Error || Error)!void {
var tok_it = tree.tokens.iterator(0);
// render all the line comments at the beginning of the file
while (tok_it.next()) |token| {
if (token.id != .LineComment) break;
try stream.print("{}\n", .{mem.trimRight(u8, tree.tokenSlicePtr(token), " ")});
if (tok_it.peek()) |next_token| {
const loc = tree.tokenLocationPtr(token.end, next_token);
if (loc.line >= 2) {
try stream.insertNewline();
}
}
}
var it = tree.root_node.decls.iterator(0);
while (true) {
var decl = (it.next() orelse return).*;
// This loop does the following:
//
// - Iterates through line/doc comment tokens that precedes the current
// decl.
// - Figures out the first token index (`copy_start_token_index`) which
// hasn't been copied to the output stream yet.
// - Detects `zig fmt: (off|on)` in the line comment tokens, and
// determines whether the current decl should be reformatted or not.
//
var token_index = decl.firstToken();
var fmt_active = true;
var found_fmt_directive = false;
var copy_start_token_index = token_index;
while (token_index != 0) {
token_index -= 1;
const token = tree.tokens.at(token_index);
switch (token.id) {
.LineComment => {},
.DocComment => {
copy_start_token_index = token_index;
continue;
},
else => break,
}
if (mem.eql(u8, mem.trim(u8, tree.tokenSlicePtr(token)[2..], " "), "zig fmt: off")) {
if (!found_fmt_directive) {
fmt_active = false;
found_fmt_directive = true;
}
} else if (mem.eql(u8, mem.trim(u8, tree.tokenSlicePtr(token)[2..], " "), "zig fmt: on")) {
if (!found_fmt_directive) {
fmt_active = true;
found_fmt_directive = true;
}
}
}
if (!fmt_active) {
// Reformatting is disabled for the current decl and possibly some
// more decls that follow.
// Find the next `decl` for which reformatting is re-enabled.
token_index = decl.firstToken();
while (!fmt_active) {
decl = (it.next() orelse {
// If there's no next reformatted `decl`, just copy the
// remaining input tokens and bail out.
const start = tree.tokens.at(copy_start_token_index).start;
try copyFixingWhitespace(stream, tree.source[start..]);
return;
}).*;
var decl_first_token_index = decl.firstToken();
while (token_index < decl_first_token_index) : (token_index += 1) {
const token = tree.tokens.at(token_index);
switch (token.id) {
.LineComment => {},
.Eof => unreachable,
else => continue,
}
if (mem.eql(u8, mem.trim(u8, tree.tokenSlicePtr(token)[2..], " "), "zig fmt: on")) {
fmt_active = true;
} else if (mem.eql(u8, mem.trim(u8, tree.tokenSlicePtr(token)[2..], " "), "zig fmt: off")) {
fmt_active = false;
}
}
}
// Found the next `decl` for which reformatting is enabled. Copy
// the input tokens before the `decl` that haven't been copied yet.
var copy_end_token_index = decl.firstToken();
token_index = copy_end_token_index;
while (token_index != 0) {
token_index -= 1;
const token = tree.tokens.at(token_index);
switch (token.id) {
.LineComment => {},
.DocComment => {
copy_end_token_index = token_index;
continue;
},
else => break,
}
}
const start = tree.tokens.at(copy_start_token_index).start;
const end = tree.tokens.at(copy_end_token_index).start;
try copyFixingWhitespace(stream, tree.source[start..end]);
}
try renderTopLevelDecl(allocator, stream, tree, decl);
if (it.peek()) |next_decl| {
try renderExtraNewline(tree, stream, next_decl.*);
}
}
}
fn renderExtraNewline(tree: *ast.Tree, stream: var, node: *ast.Node) @TypeOf(stream).Child.Error!void {
const first_token = node.firstToken();
var prev_token = first_token;
if (prev_token == 0) return;
while (tree.tokens.at(prev_token - 1).id == .DocComment) {
prev_token -= 1;
}
const prev_token_end = tree.tokens.at(prev_token - 1).end;
const loc = tree.tokenLocation(prev_token_end, first_token);
if (loc.line >= 2) {
try stream.insertNewline();
}
}
fn renderTopLevelDecl(allocator: *mem.Allocator, stream: var, tree: *ast.Tree, decl: *ast.Node) (@TypeOf(stream).Child.Error || Error)!void {
try renderContainerDecl(allocator, stream, tree, decl, .Newline);
}
fn renderContainerDecl(allocator: *mem.Allocator, stream: var, tree: *ast.Tree, decl: *ast.Node, space: Space) (@TypeOf(stream).Child.Error || Error)!void {
switch (decl.id) {
.FnProto => {
const fn_proto = @fieldParentPtr(ast.Node.FnProto, "base", decl);
try renderDocComments(tree, stream, fn_proto);
if (fn_proto.body_node) |body_node| {
try renderExpression(allocator, stream, tree, decl, .Space);
try renderExpression(allocator, stream, tree, body_node, space);
} else {
try renderExpression(allocator, stream, tree, decl, .None);
try renderToken(tree, stream, tree.nextToken(decl.lastToken()), space);
}
},
.Use => {
const use_decl = @fieldParentPtr(ast.Node.Use, "base", decl);
if (use_decl.visib_token) |visib_token| {
try renderToken(tree, stream, visib_token, .Space); // pub
}
try renderToken(tree, stream, use_decl.use_token, .Space); // usingnamespace
try renderExpression(allocator, stream, tree, use_decl.expr, .None);
try renderToken(tree, stream, use_decl.semicolon_token, space); // ;
},
.VarDecl => {
const var_decl = @fieldParentPtr(ast.Node.VarDecl, "base", decl);
try renderDocComments(tree, stream, var_decl);
try renderVarDecl(allocator, stream, tree, var_decl);
},
.TestDecl => {
const test_decl = @fieldParentPtr(ast.Node.TestDecl, "base", decl);
try renderDocComments(tree, stream, test_decl);
try renderToken(tree, stream, test_decl.test_token, .Space);
try renderExpression(allocator, stream, tree, test_decl.name, .Space);
try renderExpression(allocator, stream, tree, test_decl.body_node, space);
},
.ContainerField => {
const field = @fieldParentPtr(ast.Node.ContainerField, "base", decl);
try renderDocComments(tree, stream, field);
if (field.comptime_token) |t| {
try renderToken(tree, stream, t, .Space); // comptime
}
const src_has_trailing_comma = blk: {
const maybe_comma = tree.nextToken(field.lastToken());
break :blk tree.tokens.at(maybe_comma).id == .Comma;
};
// The trailing comma is emitted at the end, but if it's not present
// we still have to respect the specified `space` parameter
const last_token_space: Space = if (src_has_trailing_comma) .None else space;
if (field.type_expr == null and field.value_expr == null) {
try renderToken(tree, stream, field.name_token, last_token_space); // name
} else if (field.type_expr != null and field.value_expr == null) {
try renderToken(tree, stream, field.name_token, .None); // name
try renderToken(tree, stream, tree.nextToken(field.name_token), .Space); // :
if (field.align_expr) |align_value_expr| {
try renderExpression(allocator, stream, tree, field.type_expr.?, .Space); // type
const lparen_token = tree.prevToken(align_value_expr.firstToken());
const align_kw = tree.prevToken(lparen_token);
const rparen_token = tree.nextToken(align_value_expr.lastToken());
try renderToken(tree, stream, align_kw, .None); // align
try renderToken(tree, stream, lparen_token, .None); // (
try renderExpression(allocator, stream, tree, align_value_expr, .None); // alignment
try renderToken(tree, stream, rparen_token, last_token_space); // )
} else {
try renderExpression(allocator, stream, tree, field.type_expr.?, last_token_space); // type
}
} else if (field.type_expr == null and field.value_expr != null) {
try renderToken(tree, stream, field.name_token, .Space); // name
try renderToken(tree, stream, tree.nextToken(field.name_token), .Space); // =
try renderExpression(allocator, stream, tree, field.value_expr.?, last_token_space); // value
} else {
try renderToken(tree, stream, field.name_token, .None); // name
try renderToken(tree, stream, tree.nextToken(field.name_token), .Space); // :
if (field.align_expr) |align_value_expr| {
try renderExpression(allocator, stream, tree, field.type_expr.?, .Space); // type
const lparen_token = tree.prevToken(align_value_expr.firstToken());
const align_kw = tree.prevToken(lparen_token);
const rparen_token = tree.nextToken(align_value_expr.lastToken());
try renderToken(tree, stream, align_kw, .None); // align
try renderToken(tree, stream, lparen_token, .None); // (
try renderExpression(allocator, stream, tree, align_value_expr, .None); // alignment
try renderToken(tree, stream, rparen_token, .Space); // )
} else {
try renderExpression(allocator, stream, tree, field.type_expr.?, .Space); // type
}
try renderToken(tree, stream, tree.prevToken(field.value_expr.?.firstToken()), .Space); // =
try renderExpression(allocator, stream, tree, field.value_expr.?, last_token_space); // value
}
if (src_has_trailing_comma) {
const comma = tree.nextToken(field.lastToken());
try renderToken(tree, stream, comma, space);
}
},
.Comptime => {
assert(!decl.requireSemiColon());
try renderExpression(allocator, stream, tree, decl, space);
},
.DocComment => {
const comment = @fieldParentPtr(ast.Node.DocComment, "base", decl);
var it = comment.lines.iterator(0);
while (it.next()) |line_token_index| {
try renderToken(tree, stream, line_token_index.*, .Newline);
}
},
else => unreachable,
}
}
fn renderExpression(
allocator: *mem.Allocator,
stream: var,
tree: *ast.Tree,
base: *ast.Node,
space: Space,
) (@TypeOf(stream).Child.Error || Error)!void {
switch (base.id) {
.Identifier => {
const identifier = @fieldParentPtr(ast.Node.Identifier, "base", base);
return renderToken(tree, stream, identifier.token, space);
},
.Block => {
const block = @fieldParentPtr(ast.Node.Block, "base", base);
if (block.label) |label| {
try renderToken(tree, stream, label, Space.None);
try renderToken(tree, stream, tree.nextToken(label), Space.Space);
}
if (block.statements.len == 0) {
stream.pushIndentNextLine();
defer stream.popIndent();
try renderToken(tree, stream, block.lbrace, Space.None);
} else {
stream.pushIndentNextLine();
defer stream.popIndent();
try renderToken(tree, stream, block.lbrace, Space.Newline);
var it = block.statements.iterator(0);
while (it.next()) |statement| {
try renderStatement(allocator, stream, tree, statement.*);
if (it.peek()) |next_statement| {
try renderExtraNewline(tree, stream, next_statement.*);
}
}
}
return renderToken(tree, stream, block.rbrace, space);
},
.Defer => {
const defer_node = @fieldParentPtr(ast.Node.Defer, "base", base);
try renderToken(tree, stream, defer_node.defer_token, Space.Space);
return renderExpression(allocator, stream, tree, defer_node.expr, space);
},
.Comptime => {
const comptime_node = @fieldParentPtr(ast.Node.Comptime, "base", base);
try renderToken(tree, stream, comptime_node.comptime_token, Space.Space);
return renderExpression(allocator, stream, tree, comptime_node.expr, space);
},
.Suspend => {
const suspend_node = @fieldParentPtr(ast.Node.Suspend, "base", base);
if (suspend_node.body) |body| {
try renderToken(tree, stream, suspend_node.suspend_token, Space.Space);
return renderExpression(allocator, stream, tree, body, space);
} else {
return renderToken(tree, stream, suspend_node.suspend_token, space);
}
},
.InfixOp => {
const infix_op_node = @fieldParentPtr(ast.Node.InfixOp, "base", base);
const op_space = switch (infix_op_node.op) {
ast.Node.InfixOp.Op.Period, ast.Node.InfixOp.Op.ErrorUnion, ast.Node.InfixOp.Op.Range => Space.None,
else => Space.Space,
};
try renderExpression(allocator, stream, tree, infix_op_node.lhs, op_space);
const after_op_space = blk: {
const same_line = tree.tokensOnSameLine(infix_op_node.op_token, tree.nextToken(infix_op_node.op_token));
break :blk if (same_line) op_space else Space.Newline;
};
try renderToken(tree, stream, infix_op_node.op_token, after_op_space);
switch (infix_op_node.op) {
ast.Node.InfixOp.Op.Catch => |maybe_payload| if (maybe_payload) |payload| {
try renderExpression(allocator, stream, tree, payload, Space.Space);
},
else => {},
}
stream.pushIndentOneShot();
return renderExpression(allocator, stream, tree, infix_op_node.rhs, space);
},
.PrefixOp => {
const prefix_op_node = @fieldParentPtr(ast.Node.PrefixOp, "base", base);
switch (prefix_op_node.op) {
.PtrType => |ptr_info| {
const op_tok_id = tree.tokens.at(prefix_op_node.op_token).id;
switch (op_tok_id) {
.Asterisk, .AsteriskAsterisk => try stream.writeByte('*'),
.LBracket => if (tree.tokens.at(prefix_op_node.op_token + 2).id == .Identifier)
try stream.write("[*c")
else
try stream.write("[*"),
else => unreachable,
}
if (ptr_info.sentinel) |sentinel| {
const colon_token = tree.prevToken(sentinel.firstToken());
try renderToken(tree, stream, colon_token, Space.None); // :
const sentinel_space = switch (op_tok_id) {
.LBracket => Space.None,
else => Space.Space,
};
try renderExpression(allocator, stream, tree, sentinel, sentinel_space);
}
switch (op_tok_id) {
.Asterisk, .AsteriskAsterisk => {},
.LBracket => try stream.writeByte(']'),
else => unreachable,
}
if (ptr_info.allowzero_token) |allowzero_token| {
try renderToken(tree, stream, allowzero_token, Space.Space); // allowzero
}
if (ptr_info.align_info) |align_info| {
const lparen_token = tree.prevToken(align_info.node.firstToken());
const align_token = tree.prevToken(lparen_token);
try renderToken(tree, stream, align_token, Space.None); // align
try renderToken(tree, stream, lparen_token, Space.None); // (
try renderExpression(allocator, stream, tree, align_info.node, Space.None);
if (align_info.bit_range) |bit_range| {
const colon1 = tree.prevToken(bit_range.start.firstToken());
const colon2 = tree.prevToken(bit_range.end.firstToken());
try renderToken(tree, stream, colon1, Space.None); // :
try renderExpression(allocator, stream, tree, bit_range.start, Space.None);
try renderToken(tree, stream, colon2, Space.None); // :
try renderExpression(allocator, stream, tree, bit_range.end, Space.None);
const rparen_token = tree.nextToken(bit_range.end.lastToken());
try renderToken(tree, stream, rparen_token, Space.Space); // )
} else {
const rparen_token = tree.nextToken(align_info.node.lastToken());
try renderToken(tree, stream, rparen_token, Space.Space); // )
}
}
if (ptr_info.const_token) |const_token| {
try renderToken(tree, stream, const_token, Space.Space); // const
}
if (ptr_info.volatile_token) |volatile_token| {
try renderToken(tree, stream, volatile_token, Space.Space); // volatile
}
},
.SliceType => |ptr_info| {
try renderToken(tree, stream, prefix_op_node.op_token, Space.None); // [
if (ptr_info.sentinel) |sentinel| {
const colon_token = tree.prevToken(sentinel.firstToken());
try renderToken(tree, stream, colon_token, Space.None); // :
try renderExpression(allocator, stream, tree, sentinel, Space.None);
try renderToken(tree, stream, tree.nextToken(sentinel.lastToken()), Space.None); // ]
} else {
try renderToken(tree, stream, tree.nextToken(prefix_op_node.op_token), Space.None); // ]
}
if (ptr_info.allowzero_token) |allowzero_token| {
try renderToken(tree, stream, allowzero_token, Space.Space); // allowzero
}
if (ptr_info.align_info) |align_info| {
const lparen_token = tree.prevToken(align_info.node.firstToken());
const align_token = tree.prevToken(lparen_token);
try renderToken(tree, stream, align_token, Space.None); // align
try renderToken(tree, stream, lparen_token, Space.None); // (
try renderExpression(allocator, stream, tree, align_info.node, Space.None);
if (align_info.bit_range) |bit_range| {
const colon1 = tree.prevToken(bit_range.start.firstToken());
const colon2 = tree.prevToken(bit_range.end.firstToken());
try renderToken(tree, stream, colon1, Space.None); // :
try renderExpression(allocator, stream, tree, bit_range.start, Space.None);
try renderToken(tree, stream, colon2, Space.None); // :
try renderExpression(allocator, stream, tree, bit_range.end, Space.None);
const rparen_token = tree.nextToken(bit_range.end.lastToken());
try renderToken(tree, stream, rparen_token, Space.Space); // )
} else {
const rparen_token = tree.nextToken(align_info.node.lastToken());
try renderToken(tree, stream, rparen_token, Space.Space); // )
}
}
if (ptr_info.const_token) |const_token| {
try renderToken(tree, stream, const_token, Space.Space);
}
if (ptr_info.volatile_token) |volatile_token| {
try renderToken(tree, stream, volatile_token, Space.Space);
}
},
.ArrayType => |array_info| {
const lbracket = prefix_op_node.op_token;
const rbracket = tree.nextToken(if (array_info.sentinel) |sentinel|
sentinel.lastToken()
else
array_info.len_expr.lastToken());
const starts_with_comment = tree.tokens.at(lbracket + 1).id == .LineComment;
const ends_with_comment = tree.tokens.at(rbracket - 1).id == .LineComment;
const new_space = if (ends_with_comment) Space.Newline else Space.None;
{
const do_indent = (starts_with_comment or ends_with_comment);
if (do_indent) stream.pushIndent();
defer if (do_indent) stream.popIndent();
try renderToken(tree, stream, lbracket, Space.None); // [
try renderExpression(allocator, stream, tree, array_info.len_expr, new_space);
if (starts_with_comment) {
try stream.maybeInsertNewline();
}
if (array_info.sentinel) |sentinel| {
const colon_token = tree.prevToken(sentinel.firstToken());
try renderToken(tree, stream, colon_token, Space.None); // :
try renderExpression(allocator, stream, tree, sentinel, Space.None);
}
if (starts_with_comment) {
try stream.maybeInsertNewline();
}
}
try renderToken(tree, stream, rbracket, Space.None); // ]
},
.BitNot,
.BoolNot,
.Negation,
.NegationWrap,
.OptionalType,
.AddressOf,
=> {
try renderToken(tree, stream, prefix_op_node.op_token, Space.None);
},
.Try,
.Cancel,
.Resume,
=> {
try renderToken(tree, stream, prefix_op_node.op_token, Space.Space);
},
.Await => |await_info| {
if (await_info.noasync_token) |tok| {
try renderToken(tree, stream, tok, Space.Space);
}
try renderToken(tree, stream, prefix_op_node.op_token, Space.Space);
},
}
return renderExpression(allocator, stream, tree, prefix_op_node.rhs, space);
},
.SuffixOp => {
const suffix_op = @fieldParentPtr(ast.Node.SuffixOp, "base", base);
switch (suffix_op.op) {
.Call => |*call_info| {
if (call_info.async_token) |async_token| {
try renderToken(tree, stream, async_token, Space.Space);
}
try renderExpression(allocator, stream, tree, suffix_op.lhs.node, Space.None);
const lparen = tree.nextToken(suffix_op.lhs.node.lastToken());
if (call_info.params.len == 0) {
try renderToken(tree, stream, lparen, Space.None);
return renderToken(tree, stream, suffix_op.rtoken, space);
}
const src_has_trailing_comma = blk: {
const maybe_comma = tree.prevToken(suffix_op.rtoken);
break :blk tree.tokens.at(maybe_comma).id == .Comma;
};
if (src_has_trailing_comma) {
try renderToken(tree, stream, lparen, Space.Newline);
var it = call_info.params.iterator(0);
while (it.next()) |param_node| {
stream.pushIndent();
defer stream.popIndent();
if (it.peek()) |next_node| {
try renderExpression(allocator, stream, tree, param_node.*, Space.None);
const comma = tree.nextToken(param_node.*.lastToken());
try renderToken(tree, stream, comma, Space.Newline); // ,
try renderExtraNewline(tree, stream, next_node.*);
} else {
try renderExpression(allocator, stream, tree, param_node.*, Space.Comma);
}
}
return renderToken(tree, stream, suffix_op.rtoken, space);
}
try renderToken(tree, stream, lparen, Space.None); // (
var it = call_info.params.iterator(0);
while (it.next()) |param_node| {
if (param_node.*.id == .MultilineStringLiteral) stream.pushIndentOneShot();
try renderExpression(allocator, stream, tree, param_node.*, Space.None);
if (it.peek()) |next_param| {
const comma = tree.nextToken(param_node.*.lastToken());
try renderToken(tree, stream, comma, Space.Space);
}
}
return renderToken(tree, stream, suffix_op.rtoken, space);
},
.ArrayAccess => |index_expr| {
const lbracket = tree.nextToken(suffix_op.lhs.node.lastToken());
const rbracket = tree.nextToken(index_expr.lastToken());
try renderExpression(allocator, stream, tree, suffix_op.lhs.node, Space.None);
try renderToken(tree, stream, lbracket, Space.None); // [
const starts_with_comment = tree.tokens.at(lbracket + 1).id == .LineComment;
const ends_with_comment = tree.tokens.at(rbracket - 1).id == .LineComment;
{
const new_space = if (ends_with_comment) Space.Newline else Space.None;
stream.pushIndent();
defer stream.popIndent();
try renderExpression(allocator, stream, tree, index_expr, new_space);
}
if (starts_with_comment) try stream.maybeInsertNewline();
return renderToken(tree, stream, rbracket, space); // ]
},
.Deref => {
try renderExpression(allocator, stream, tree, suffix_op.lhs.node, Space.None);
return renderToken(tree, stream, suffix_op.rtoken, space); // .*
},
.UnwrapOptional => {
try renderExpression(allocator, stream, tree, suffix_op.lhs.node, Space.None);
try renderToken(tree, stream, tree.prevToken(suffix_op.rtoken), Space.None); // .
return renderToken(tree, stream, suffix_op.rtoken, space); // ?
},
.Slice => |range| {
try renderExpression(allocator, stream, tree, suffix_op.lhs.node, Space.None);
const lbracket = tree.prevToken(range.start.firstToken());
const dotdot = tree.nextToken(range.start.lastToken());
const after_start_space_bool = nodeCausesSliceOpSpace(range.start) or
(if (range.end) |end| nodeCausesSliceOpSpace(end) else false);
const after_start_space = if (after_start_space_bool) Space.Space else Space.None;
const after_op_space = if (range.end != null) after_start_space else Space.None;
try renderToken(tree, stream, lbracket, Space.None); // [
try renderExpression(allocator, stream, tree, range.start, after_start_space);
try renderToken(tree, stream, dotdot, after_op_space); // ..
if (range.end) |end| {
const after_end_space = if (range.sentinel != null) Space.Space else Space.None;
try renderExpression(allocator, stream, tree, end, after_end_space);
}
if (range.sentinel) |sentinel| {
const colon = tree.prevToken(sentinel.firstToken());
try renderToken(tree, stream, colon, Space.None); // :
try renderExpression(allocator, stream, tree, sentinel, Space.None);
}
return renderToken(tree, stream, suffix_op.rtoken, space); // ]
},
.StructInitializer => |*field_inits| {
const lbrace = switch (suffix_op.lhs) {
.dot => |dot| tree.nextToken(dot),
.node => |node| tree.nextToken(node.lastToken()),
};
if (field_inits.len == 0) {
switch (suffix_op.lhs) {
.dot => |dot| try renderToken(tree, stream, dot, Space.None),
.node => |node| try renderExpression(allocator, stream, tree, node, Space.None),
}
{
stream.pushIndentNextLine();
defer stream.popIndent();
try renderToken(tree, stream, lbrace, Space.None);
}
return renderToken(tree, stream, suffix_op.rtoken, space);
}
const src_has_trailing_comma = blk: {
const maybe_comma = tree.prevToken(suffix_op.rtoken);
break :blk tree.tokens.at(maybe_comma).id == .Comma;
};
const src_same_line = blk: {
const loc = tree.tokenLocation(tree.tokens.at(lbrace).end, suffix_op.rtoken);
break :blk loc.line == 0;
};
const expr_outputs_one_line = blk: {
// render field expressions until a LF is found
var it = field_inits.iterator(0);
while (it.next()) |field_init| {
var find_stream = std.io.FindByteOutStream.init('\n');
const AutoIndentingStream = std.io.AutoIndentingStream(std.io.FindByteOutStream);
var auto_indenting_stream = AutoIndentingStream.init(&find_stream, indent_delta);
try renderExpression(allocator, &auto_indenting_stream, tree, field_init.*, Space.None);
if (find_stream.byte_found) break :blk false;
}
break :blk true;
};
if (field_inits.len == 1) blk: {
const field_init = field_inits.at(0).*.cast(ast.Node.FieldInitializer).?;
if (field_init.expr.cast(ast.Node.SuffixOp)) |nested_suffix_op| {
if (nested_suffix_op.op == .StructInitializer) {
break :blk;
}
}
// if the expression outputs to multiline, make this struct multiline
if (!expr_outputs_one_line or src_has_trailing_comma) {
break :blk;
}
switch (suffix_op.lhs) {
.dot => |dot| try renderToken(tree, stream, dot, Space.None),
.node => |node| try renderExpression(allocator, stream, tree, node, Space.None),
}
try renderToken(tree, stream, lbrace, Space.Space);
try renderExpression(allocator, stream, tree, &field_init.base, Space.Space);
return renderToken(tree, stream, suffix_op.rtoken, space);
}
if (!src_has_trailing_comma and src_same_line and expr_outputs_one_line) {
// render all on one line, no trailing comma
switch (suffix_op.lhs) {
.dot => |dot| try renderToken(tree, stream, dot, Space.None),
.node => |node| try renderExpression(allocator, stream, tree, node, Space.None),
}
try renderToken(tree, stream, lbrace, Space.Space);
var it = field_inits.iterator(0);
while (it.next()) |field_init| {
if (it.peek() != null) {
try renderExpression(allocator, stream, tree, field_init.*, Space.None);
const comma = tree.nextToken(field_init.*.lastToken());
try renderToken(tree, stream, comma, Space.Space);
} else {
try renderExpression(allocator, stream, tree, field_init.*, Space.Space);
}
}
return renderToken(tree, stream, suffix_op.rtoken, space);
}
{
switch (suffix_op.lhs) {
.dot => |dot| try renderToken(tree, stream, dot, Space.None),
.node => |node| try renderExpression(allocator, stream, tree, node, Space.None),
}
stream.pushIndentNextLine();
defer stream.popIndent();
try renderToken(tree, stream, lbrace, Space.Newline);
var it = field_inits.iterator(0);
while (it.next()) |field_init| {
if (it.peek()) |next_field_init| {
try renderExpression(allocator, stream, tree, field_init.*, Space.None);
const comma = tree.nextToken(field_init.*.lastToken());
try renderToken(tree, stream, comma, Space.Newline);
try renderExtraNewline(tree, stream, next_field_init.*);
} else {
try renderExpression(allocator, stream, tree, field_init.*, Space.Comma);
}
}
}
return renderToken(tree, stream, suffix_op.rtoken, space);
},
.ArrayInitializer => |*exprs| {
const lbrace = switch (suffix_op.lhs) {
.dot => |dot| tree.nextToken(dot),
.node => |node| tree.nextToken(node.lastToken()),
};
switch (suffix_op.lhs) {
.dot => |dot| try renderToken(tree, stream, dot, Space.None),
.node => |node| try renderExpression(allocator, stream, tree, node, Space.None),
}
if (exprs.len == 0) {
try renderToken(tree, stream, lbrace, Space.None);
return renderToken(tree, stream, suffix_op.rtoken, space);
}
if (exprs.len == 1 and exprs.at(0).*.id != .MultilineStringLiteral and tree.tokens.at(exprs.at(0).*.lastToken() + 1).id == .RBrace) {
const expr = exprs.at(0).*;
try renderToken(tree, stream, lbrace, Space.None);
try renderExpression(allocator, stream, tree, expr, Space.None);
return renderToken(tree, stream, suffix_op.rtoken, space);
}
// scan to find row size
const maybe_row_size: ?usize = blk: {
var count: usize = 1;
var it = exprs.iterator(0);
while (true) {
const expr = it.next().?.*;
if (it.peek()) |next_expr| {
const expr_last_token = expr.*.lastToken() + 1;
const loc = tree.tokenLocation(tree.tokens.at(expr_last_token).start, next_expr.*.firstToken());
if (loc.line != 0) break :blk count;
count += 1;
} else {
const expr_last_token = expr.*.lastToken();
const loc = tree.tokenLocation(tree.tokens.at(expr_last_token).start, suffix_op.rtoken);
if (loc.line == 0) {
// all on one line
const src_has_trailing_comma = trailblk: {
const maybe_comma = tree.prevToken(suffix_op.rtoken);
break :trailblk tree.tokens.at(maybe_comma).id == .Comma;
};
if (src_has_trailing_comma) {
break :blk 1; // force row size 1
} else {
break :blk null; // no newlines
}
}
break :blk count;
}
}
};
if (maybe_row_size) |row_size| {
// A place to store the width of each expression and its column's maximum
var widths = try allocator.alloc(usize, exprs.len + row_size);
defer allocator.free(widths);
mem.set(usize, widths, 0);
var expr_widths = widths[0 .. widths.len - row_size];
var column_widths = widths[widths.len - row_size ..];
// Null stream for counting the printed length of each expression
var line_find_stream = std.io.FindByteOutStream.init('\n');
var counting_stream = std.io.CountingOutStream(std.io.FindByteOutStream).init(&line_find_stream);
const AutoIndentingStream = std.io.AutoIndentingStream(@TypeOf(counting_stream));
var auto_indenting_stream = AutoIndentingStream.init(&counting_stream, indent_delta);
var it = exprs.iterator(0);
var i: usize = 0;
var c: usize = 0;
var single_line = true;
while (it.next()) |expr| : (i += 1) {
if (it.peek()) |next_expr| {
counting_stream.bytes_written = 0;
var dummy_col: usize = 0;
line_find_stream.byte_found = false;
try renderExpression(allocator, &auto_indenting_stream, tree, expr.*, Space.None);
const width = @intCast(usize, counting_stream.bytes_written);
expr_widths[i] = width;
if (!line_find_stream.byte_found) {
const col = c % row_size;
column_widths[col] = std.math.max(column_widths[col], width);
const expr_last_token = expr.*.lastToken() + 1;
const loc = tree.tokenLocation(tree.tokens.at(expr_last_token).start, next_expr.*.firstToken());
if (loc.line == 0) {
c += 1;
} else {
single_line = false;
c = 0;
}
} else {
single_line = false;
c = 0;
}
} else {
break;
}
}
{
stream.pushIndentNextLine();
defer stream.popIndent();
try renderToken(tree, stream, lbrace, Space.Newline);
it.set(0);
i = 0;
c = 0;
var last_col_index: usize = row_size - 1;
while (it.next()) |expr| : (i += 1) {
if (it.peek()) |next_expr| {
try renderExpression(allocator, stream, tree, expr.*, Space.None);
const comma = tree.nextToken(expr.*.lastToken());
if (c != last_col_index) {
line_find_stream.byte_found = false;
try renderExpression(allocator, &auto_indenting_stream, tree, expr.*, Space.None);
try renderExpression(allocator, &auto_indenting_stream, tree, next_expr.*, Space.None);
if (!line_find_stream.byte_found) {
// Neither the current or next expression is multiline
try renderToken(tree, stream, comma, Space.Space); // ,
assert(column_widths[c % row_size] >= expr_widths[i]);
const padding = column_widths[c % row_size] - expr_widths[i];
try stream.writeByteNTimes(' ', padding);
c += 1;
continue;
}
}
if (single_line) {
try renderToken(tree, stream, comma, Space.Space); // ,
continue;
}
c = 0;
try renderToken(tree, stream, comma, Space.Newline); // ,
try renderExtraNewline(tree, stream, next_expr.*);
} else {
try renderExpression(allocator, stream, tree, expr.*, Space.Comma); // ,
}
}
}
return renderToken(tree, stream, suffix_op.rtoken, space);
} else {
try renderToken(tree, stream, lbrace, Space.Space);
var it = exprs.iterator(0);
while (it.next()) |expr| {
if (it.peek()) |next_expr| {
try renderExpression(allocator, stream, tree, expr.*, Space.None);
const comma = tree.nextToken(expr.*.lastToken());
try renderToken(tree, stream, comma, Space.Space); // ,
} else {
try renderExpression(allocator, stream, tree, expr.*, Space.Space);
}
}
return renderToken(tree, stream, suffix_op.rtoken, space);
}
},
}
},
.ControlFlowExpression => {
const flow_expr = @fieldParentPtr(ast.Node.ControlFlowExpression, "base", base);
switch (flow_expr.kind) {
.Break => |maybe_label| {
if (maybe_label == null and flow_expr.rhs == null) {
return renderToken(tree, stream, flow_expr.ltoken, space); // break
}
try renderToken(tree, stream, flow_expr.ltoken, Space.Space); // break
if (maybe_label) |label| {
const colon = tree.nextToken(flow_expr.ltoken);
try renderToken(tree, stream, colon, Space.None); // :
if (flow_expr.rhs == null) {
return renderExpression(allocator, stream, tree, label, space); // label
}
try renderExpression(allocator, stream, tree, label, Space.Space); // label
}
},
.Continue => |maybe_label| {
assert(flow_expr.rhs == null);
if (maybe_label == null and flow_expr.rhs == null) {
return renderToken(tree, stream, flow_expr.ltoken, space); // continue
}
try renderToken(tree, stream, flow_expr.ltoken, Space.Space); // continue
if (maybe_label) |label| {
const colon = tree.nextToken(flow_expr.ltoken);
try renderToken(tree, stream, colon, Space.None); // :
return renderExpression(allocator, stream, tree, label, space);
}
},
.Return => {
if (flow_expr.rhs == null) {
return renderToken(tree, stream, flow_expr.ltoken, space);
}
try renderToken(tree, stream, flow_expr.ltoken, Space.Space);
},
}
return renderExpression(allocator, stream, tree, flow_expr.rhs.?, space);
},
.Payload => {
const payload = @fieldParentPtr(ast.Node.Payload, "base", base);
try renderToken(tree, stream, payload.lpipe, Space.None);
try renderExpression(allocator, stream, tree, payload.error_symbol, Space.None);
return renderToken(tree, stream, payload.rpipe, space);
},
.PointerPayload => {
const payload = @fieldParentPtr(ast.Node.PointerPayload, "base", base);
try renderToken(tree, stream, payload.lpipe, Space.None);
if (payload.ptr_token) |ptr_token| {
try renderToken(tree, stream, ptr_token, Space.None);
}
try renderExpression(allocator, stream, tree, payload.value_symbol, Space.None);
return renderToken(tree, stream, payload.rpipe, space);
},
.PointerIndexPayload => {
const payload = @fieldParentPtr(ast.Node.PointerIndexPayload, "base", base);
try renderToken(tree, stream, payload.lpipe, Space.None);
if (payload.ptr_token) |ptr_token| {
try renderToken(tree, stream, ptr_token, Space.None);
}
try renderExpression(allocator, stream, tree, payload.value_symbol, Space.None);
if (payload.index_symbol) |index_symbol| {
const comma = tree.nextToken(payload.value_symbol.lastToken());
try renderToken(tree, stream, comma, Space.Space);
try renderExpression(allocator, stream, tree, index_symbol, Space.None);
}
return renderToken(tree, stream, payload.rpipe, space);
},
.GroupedExpression => {
const grouped_expr = @fieldParentPtr(ast.Node.GroupedExpression, "base", base);
try renderToken(tree, stream, grouped_expr.lparen, Space.None);
{
stream.pushIndentOneShot();
try renderExpression(allocator, stream, tree, grouped_expr.expr, Space.None);
}
return renderToken(tree, stream, grouped_expr.rparen, space);
},
.FieldInitializer => {
const field_init = @fieldParentPtr(ast.Node.FieldInitializer, "base", base);
try renderToken(tree, stream, field_init.period_token, Space.None); // .
try renderToken(tree, stream, field_init.name_token, Space.Space); // name
try renderToken(tree, stream, tree.nextToken(field_init.name_token), Space.Space); // =
return renderExpression(allocator, stream, tree, field_init.expr, space);
},
.IntegerLiteral => {
const integer_literal = @fieldParentPtr(ast.Node.IntegerLiteral, "base", base);
return renderToken(tree, stream, integer_literal.token, space);
},
.FloatLiteral => {
const float_literal = @fieldParentPtr(ast.Node.FloatLiteral, "base", base);
return renderToken(tree, stream, float_literal.token, space);
},
.StringLiteral => {
const string_literal = @fieldParentPtr(ast.Node.StringLiteral, "base", base);
return renderToken(tree, stream, string_literal.token, space);
},
.CharLiteral => {
const char_literal = @fieldParentPtr(ast.Node.CharLiteral, "base", base);
return renderToken(tree, stream, char_literal.token, space);
},
.BoolLiteral => {
const bool_literal = @fieldParentPtr(ast.Node.CharLiteral, "base", base);
return renderToken(tree, stream, bool_literal.token, space);
},
.NullLiteral => {
const null_literal = @fieldParentPtr(ast.Node.NullLiteral, "base", base);
return renderToken(tree, stream, null_literal.token, space);
},
.Unreachable => {
const unreachable_node = @fieldParentPtr(ast.Node.Unreachable, "base", base);
return renderToken(tree, stream, unreachable_node.token, space);
},
.ErrorType => {
const error_type = @fieldParentPtr(ast.Node.ErrorType, "base", base);
return renderToken(tree, stream, error_type.token, space);
},
.VarType => {
const var_type = @fieldParentPtr(ast.Node.VarType, "base", base);
return renderToken(tree, stream, var_type.token, space);
},
.ContainerDecl => {
const container_decl = @fieldParentPtr(ast.Node.ContainerDecl, "base", base);
if (container_decl.layout_token) |layout_token| {
try renderToken(tree, stream, layout_token, Space.Space);
}
switch (container_decl.init_arg_expr) {
.None => {
try renderToken(tree, stream, container_decl.kind_token, Space.Space); // union
},
.Enum => |enum_tag_type| {
try renderToken(tree, stream, container_decl.kind_token, Space.None); // union
const lparen = tree.nextToken(container_decl.kind_token);
const enum_token = tree.nextToken(lparen);
try renderToken(tree, stream, lparen, Space.None); // (
try renderToken(tree, stream, enum_token, Space.None); // enum
if (enum_tag_type) |expr| {
try renderToken(tree, stream, tree.nextToken(enum_token), Space.None); // (
try renderExpression(allocator, stream, tree, expr, Space.None);
const rparen = tree.nextToken(expr.lastToken());
try renderToken(tree, stream, rparen, Space.None); // )
try renderToken(tree, stream, tree.nextToken(rparen), Space.Space); // )
} else {
try renderToken(tree, stream, tree.nextToken(enum_token), Space.Space); // )
}
},
.Type => |type_expr| {
try renderToken(tree, stream, container_decl.kind_token, Space.None); // union
const lparen = tree.nextToken(container_decl.kind_token);
const rparen = tree.nextToken(type_expr.lastToken());
try renderToken(tree, stream, lparen, Space.None); // (
try renderExpression(allocator, stream, tree, type_expr, Space.None);
try renderToken(tree, stream, rparen, Space.Space); // )
},
}
if (container_decl.fields_and_decls.len == 0) {
{
stream.pushIndentNextLine();
defer stream.popIndent();
try renderToken(tree, stream, container_decl.lbrace_token, Space.None); // {
}
return renderToken(tree, stream, container_decl.rbrace_token, space); // }
}
const src_has_trailing_comma = blk: {
var maybe_comma = tree.prevToken(container_decl.lastToken());
// Doc comments for a field may also appear after the comma, eg.
// field_name: T, // comment attached to field_name
if (tree.tokens.at(maybe_comma).id == .DocComment)
maybe_comma = tree.prevToken(maybe_comma);
break :blk tree.tokens.at(maybe_comma).id == .Comma;
};
// Check if the first declaration and the { are on the same line
const src_has_newline = !tree.tokensOnSameLine(
container_decl.lbrace_token,
container_decl.fields_and_decls.at(0).*.firstToken(),
);
// We can only print all the elements in-line if all the
// declarations inside are fields
const src_has_only_fields = blk: {
var it = container_decl.fields_and_decls.iterator(0);
while (it.next()) |decl| {
if (decl.*.id != .ContainerField) break :blk false;
}
break :blk true;
};
if (src_has_trailing_comma or !src_has_only_fields) {
// One declaration per line
stream.pushIndentNextLine();
defer stream.popIndent();
try renderToken(tree, stream, container_decl.lbrace_token, .Newline); // {
var it = container_decl.fields_and_decls.iterator(0);
while (it.next()) |decl| {
try renderContainerDecl(allocator, stream, tree, decl.*, .Newline);
if (it.peek()) |next_decl| {
try renderExtraNewline(tree, stream, next_decl.*);
}
}
} else if (src_has_newline) {
// All the declarations on the same line, but place the items on
// their own line
try renderToken(tree, stream, container_decl.lbrace_token, .Newline); // {
stream.pushIndent();
defer stream.popIndent();
var it = container_decl.fields_and_decls.iterator(0);
while (it.next()) |decl| {
const space_after_decl: Space = if (it.peek() == null) .Newline else .Space;
try renderContainerDecl(allocator, stream, tree, decl.*, space_after_decl);
}
} else {
// All the declarations on the same line
try renderToken(tree, stream, container_decl.lbrace_token, .Space); // {
var it = container_decl.fields_and_decls.iterator(0);
while (it.next()) |decl| {
try renderContainerDecl(allocator, stream, tree, decl.*, .Space);
}
}
return renderToken(tree, stream, container_decl.rbrace_token, space); // }
},
.ErrorSetDecl => {
const err_set_decl = @fieldParentPtr(ast.Node.ErrorSetDecl, "base", base);
const lbrace = tree.nextToken(err_set_decl.error_token);
if (err_set_decl.decls.len == 0) {
try renderToken(tree, stream, err_set_decl.error_token, Space.None);
try renderToken(tree, stream, lbrace, Space.None);
return renderToken(tree, stream, err_set_decl.rbrace_token, space);
}
if (err_set_decl.decls.len == 1) blk: {
const node = err_set_decl.decls.at(0).*;
// if there are any doc comments or same line comments
// don't try to put it all on one line
if (node.cast(ast.Node.ErrorTag)) |tag| {
if (tag.doc_comments != null) break :blk;
} else {
break :blk;
}
try renderToken(tree, stream, err_set_decl.error_token, Space.None); // error
try renderToken(tree, stream, lbrace, Space.None); // {
try renderExpression(allocator, stream, tree, node, Space.None);
return renderToken(tree, stream, err_set_decl.rbrace_token, space); // }
}
try renderToken(tree, stream, err_set_decl.error_token, Space.None); // error
{
stream.pushIndentNextLine();
defer stream.popIndent();
try renderToken(tree, stream, lbrace, Space.Newline); // {
var it = err_set_decl.decls.iterator(0);
while (it.next()) |node| {
if (it.peek()) |next_node| {
try renderExpression(allocator, stream, tree, node.*, Space.None);
try renderToken(tree, stream, tree.nextToken(node.*.lastToken()), Space.Newline); // ,
try renderExtraNewline(tree, stream, next_node.*);
} else {
try renderExpression(allocator, stream, tree, node.*, Space.Comma);
}
}
}
return renderToken(tree, stream, err_set_decl.rbrace_token, space); // }
},
.ErrorTag => {
const tag = @fieldParentPtr(ast.Node.ErrorTag, "base", base);
try renderDocComments(tree, stream, tag);
return renderToken(tree, stream, tag.name_token, space); // name
},
.MultilineStringLiteral => {
const multiline_str_literal = @fieldParentPtr(ast.Node.MultilineStringLiteral, "base", base);
var line_it = multiline_str_literal.lines.iterator(0);
{
const locked_indents = stream.lockOneShotIndent();
defer {
var i: u8 = 0;
while (i < locked_indents) : (i += 1) stream.popIndent();
}
try stream.maybeInsertNewline();
while (line_it.next()) |line| try renderToken(tree, stream, line.*, Space.None);
}
},
.UndefinedLiteral => {
const undefined_literal = @fieldParentPtr(ast.Node.UndefinedLiteral, "base", base);
return renderToken(tree, stream, undefined_literal.token, space);
},
.BuiltinCall => {
const builtin_call = @fieldParentPtr(ast.Node.BuiltinCall, "base", base);
// TODO: Remove condition after deprecating 'typeOf'. See https://github.com/ziglang/zig/issues/1348
if (mem.eql(u8, tree.tokenSlicePtr(tree.tokens.at(builtin_call.builtin_token)), "@typeOf")) {
try stream.write("@TypeOf");
} else {
try renderToken(tree, stream, builtin_call.builtin_token, Space.None); // @name
}
const src_params_trailing_comma = blk: {
if (builtin_call.params.len < 2) break :blk false;
const last_node = builtin_call.params.at(builtin_call.params.len - 1).*;
const maybe_comma = tree.nextToken(last_node.lastToken());
break :blk tree.tokens.at(maybe_comma).id == .Comma;
};
const lparen = tree.nextToken(builtin_call.builtin_token);
if (!src_params_trailing_comma) {
try renderToken(tree, stream, lparen, Space.None); // (
// render all on one line, no trailing comma
var it = builtin_call.params.iterator(0);
while (it.next()) |param_node| {
try renderExpression(allocator, stream, tree, param_node.*, Space.None);
if (it.peek() != null) {
const comma_token = tree.nextToken(param_node.*.lastToken());
try renderToken(tree, stream, comma_token, Space.Space); // ,
}
}
} else {
// one param per line
stream.pushIndent();
defer stream.popIndent();
try renderToken(tree, stream, lparen, Space.Newline); // (
var it = builtin_call.params.iterator(0);
while (it.next()) |param_node| {
try renderExpression(allocator, stream, tree, param_node.*, Space.Comma);
}
}
return renderToken(tree, stream, builtin_call.rparen_token, space); // )
},
.FnProto => {
const fn_proto = @fieldParentPtr(ast.Node.FnProto, "base", base);
if (fn_proto.visib_token) |visib_token_index| {
const visib_token = tree.tokens.at(visib_token_index);
assert(visib_token.id == .Keyword_pub or visib_token.id == .Keyword_export);
try renderToken(tree, stream, visib_token_index, Space.Space); // pub
}
// Some extra machinery is needed to rewrite the old-style cc
// notation to the new callconv one
var cc_rewrite_str: ?[*:0]const u8 = null;
if (fn_proto.extern_export_inline_token) |extern_export_inline_token| {
const tok = tree.tokens.at(extern_export_inline_token);
if (tok.id != .Keyword_extern or fn_proto.body_node == null) {
try renderToken(tree, stream, extern_export_inline_token, Space.Space); // extern/export
} else {
cc_rewrite_str = ".C";
fn_proto.lib_name = null;
}
}
if (fn_proto.lib_name) |lib_name| {
try renderExpression(allocator, stream, tree, lib_name, Space.Space);
}
if (fn_proto.cc_token) |cc_token| {
var str = tree.tokenSlicePtr(tree.tokens.at(cc_token));
if (mem.eql(u8, str, "stdcallcc")) {
cc_rewrite_str = ".Stdcall";
} else if (mem.eql(u8, str, "nakedcc")) {
cc_rewrite_str = ".Naked";
} else try renderToken(tree, stream, cc_token, Space.Space); // stdcallcc
}
const lparen = if (fn_proto.name_token) |name_token| blk: {
try renderToken(tree, stream, fn_proto.fn_token, Space.Space); // fn
try renderToken(tree, stream, name_token, Space.None); // name
break :blk tree.nextToken(name_token);
} else blk: {
try renderToken(tree, stream, fn_proto.fn_token, Space.Space); // fn
break :blk tree.nextToken(fn_proto.fn_token);
};
assert(tree.tokens.at(lparen).id == .LParen);
const rparen = tree.prevToken(
// the first token for the annotation expressions is the left
// parenthesis, hence the need for two prevToken
if (fn_proto.align_expr) |align_expr|
tree.prevToken(tree.prevToken(align_expr.firstToken()))
else if (fn_proto.section_expr) |section_expr|
tree.prevToken(tree.prevToken(section_expr.firstToken()))
else if (fn_proto.callconv_expr) |callconv_expr|
tree.prevToken(tree.prevToken(callconv_expr.firstToken()))
else switch (fn_proto.return_type) {
.Explicit => |node| node.firstToken(),
.InferErrorSet => |node| tree.prevToken(node.firstToken()),
});
assert(tree.tokens.at(rparen).id == .RParen);
const src_params_trailing_comma = blk: {
const maybe_comma = tree.tokens.at(rparen - 1).id;
break :blk maybe_comma == .Comma or maybe_comma == .LineComment;
};
if (!src_params_trailing_comma) {
try renderToken(tree, stream, lparen, Space.None); // (
// render all on one line, no trailing comma
var it = fn_proto.params.iterator(0);
while (it.next()) |param_decl_node| {
try renderParamDecl(allocator, stream, tree, param_decl_node.*, Space.None);
if (it.peek() != null) {
const comma = tree.nextToken(param_decl_node.*.lastToken());
try renderToken(tree, stream, comma, Space.Space); // ,
}
}
} else {
// one param per line
stream.pushIndent();
defer stream.popIndent();
try renderToken(tree, stream, lparen, Space.Newline); // (
var it = fn_proto.params.iterator(0);
while (it.next()) |param_decl_node| {
try renderParamDecl(allocator, stream, tree, param_decl_node.*, Space.Comma);
}
}
try renderToken(tree, stream, rparen, Space.Space); // )
if (fn_proto.align_expr) |align_expr| {
const align_rparen = tree.nextToken(align_expr.lastToken());
const align_lparen = tree.prevToken(align_expr.firstToken());
const align_kw = tree.prevToken(align_lparen);
try renderToken(tree, stream, align_kw, Space.None); // align
try renderToken(tree, stream, align_lparen, Space.None); // (
try renderExpression(allocator, stream, tree, align_expr, Space.None);
try renderToken(tree, stream, align_rparen, Space.Space); // )
}
if (fn_proto.section_expr) |section_expr| {
const section_rparen = tree.nextToken(section_expr.lastToken());
const section_lparen = tree.prevToken(section_expr.firstToken());
const section_kw = tree.prevToken(section_lparen);
try renderToken(tree, stream, section_kw, Space.None); // section
try renderToken(tree, stream, section_lparen, Space.None); // (
try renderExpression(allocator, stream, tree, section_expr, Space.None);
try renderToken(tree, stream, section_rparen, Space.Space); // )
}
if (fn_proto.callconv_expr) |callconv_expr| {
const callconv_rparen = tree.nextToken(callconv_expr.lastToken());
const callconv_lparen = tree.prevToken(callconv_expr.firstToken());
const callconv_kw = tree.prevToken(callconv_lparen);
try renderToken(tree, stream, callconv_kw, Space.None); // callconv
try renderToken(tree, stream, callconv_lparen, Space.None); // (
try renderExpression(allocator, stream, tree, callconv_expr, Space.None);
try renderToken(tree, stream, callconv_rparen, Space.Space); // )
} else if (cc_rewrite_str) |str| {
try stream.write("callconv(");
try stream.write(mem.toSliceConst(u8, str));
try stream.write(") ");
}
switch (fn_proto.return_type) {
ast.Node.FnProto.ReturnType.Explicit => |node| {
return renderExpression(allocator, stream, tree, node, space);
},
ast.Node.FnProto.ReturnType.InferErrorSet => |node| {
try renderToken(tree, stream, tree.prevToken(node.firstToken()), Space.None); // !
return renderExpression(allocator, stream, tree, node, space);
},
}
},
.AnyFrameType => {
const anyframe_type = @fieldParentPtr(ast.Node.AnyFrameType, "base", base);
if (anyframe_type.result) |result| {
try renderToken(tree, stream, anyframe_type.anyframe_token, Space.None); // anyframe
try renderToken(tree, stream, result.arrow_token, Space.None); // ->
return renderExpression(allocator, stream, tree, result.return_type, space);
} else {
return renderToken(tree, stream, anyframe_type.anyframe_token, space); // anyframe
}
},
.DocComment => unreachable, // doc comments are attached to nodes
.Switch => {
const switch_node = @fieldParentPtr(ast.Node.Switch, "base", base);
try renderToken(tree, stream, switch_node.switch_token, Space.Space); // switch
try renderToken(tree, stream, tree.nextToken(switch_node.switch_token), Space.None); // (
const rparen = tree.nextToken(switch_node.expr.lastToken());
const lbrace = tree.nextToken(rparen);
if (switch_node.cases.len == 0) {
try renderExpression(allocator, stream, tree, switch_node.expr, Space.None);
try renderToken(tree, stream, rparen, Space.Space); // )
try renderToken(tree, stream, lbrace, Space.None); // {
return renderToken(tree, stream, switch_node.rbrace, space); // }
}
try renderExpression(allocator, stream, tree, switch_node.expr, Space.None);
try renderToken(tree, stream, rparen, Space.Space); // )
{
stream.pushIndentNextLine();
defer stream.popIndent();
try renderToken(tree, stream, lbrace, Space.Newline); // {
var it = switch_node.cases.iterator(0);
while (it.next()) |node| {
try renderExpression(allocator, stream, tree, node.*, Space.Comma);
if (it.peek()) |next_node| {
try renderExtraNewline(tree, stream, next_node.*);
}
}
}
return renderToken(tree, stream, switch_node.rbrace, space); // }
},
.SwitchCase => {
const switch_case = @fieldParentPtr(ast.Node.SwitchCase, "base", base);
assert(switch_case.items.len != 0);
const src_has_trailing_comma = blk: {
const last_node = switch_case.items.at(switch_case.items.len - 1).*;
const maybe_comma = tree.nextToken(last_node.lastToken());
break :blk tree.tokens.at(maybe_comma).id == .Comma;
};
if (switch_case.items.len == 1 or !src_has_trailing_comma) {
var it = switch_case.items.iterator(0);
while (it.next()) |node| {
if (it.peek()) |next_node| {
try renderExpression(allocator, stream, tree, node.*, Space.None);
const comma_token = tree.nextToken(node.*.lastToken());
try renderToken(tree, stream, comma_token, Space.Space); // ,
try renderExtraNewline(tree, stream, next_node.*);
} else {
try renderExpression(allocator, stream, tree, node.*, Space.Space);
}
}
} else {
var it = switch_case.items.iterator(0);
while (true) {
const node = it.next().?;
if (it.peek()) |next_node| {
try renderExpression(allocator, stream, tree, node.*, Space.None);
const comma_token = tree.nextToken(node.*.lastToken());
try renderToken(tree, stream, comma_token, Space.Newline); // ,
try renderExtraNewline(tree, stream, next_node.*);
} else {
try renderExpression(allocator, stream, tree, node.*, Space.Comma);
break;
}
}
}
try renderToken(tree, stream, switch_case.arrow_token, Space.Space); // =>
if (switch_case.payload) |payload| {
try renderExpression(allocator, stream, tree, payload, Space.Space);
}
return renderExpression(allocator, stream, tree, switch_case.expr, space);
},
.SwitchElse => {
const switch_else = @fieldParentPtr(ast.Node.SwitchElse, "base", base);
return renderToken(tree, stream, switch_else.token, space);
},
.Else => {
const else_node = @fieldParentPtr(ast.Node.Else, "base", base);
const body_is_block = nodeIsBlock(else_node.body);
const same_line = body_is_block or tree.tokensOnSameLine(else_node.else_token, else_node.body.lastToken());
const after_else_space = if (same_line or else_node.payload != null) Space.Space else Space.Newline;
try renderToken(tree, stream, else_node.else_token, after_else_space);
if (else_node.payload) |payload| {
const payload_space = if (same_line) Space.Space else Space.Newline;
try renderExpression(allocator, stream, tree, payload, payload_space);
}
if (same_line) {
return renderExpression(allocator, stream, tree, else_node.body, space);
} else {
stream.pushIndent();
defer stream.popIndent();
return renderExpression(allocator, stream, tree, else_node.body, space);
}
},
.While => {
const while_node = @fieldParentPtr(ast.Node.While, "base", base);
if (while_node.label) |label| {
try renderToken(tree, stream, label, Space.None); // label
try renderToken(tree, stream, tree.nextToken(label), Space.Space); // :
}
if (while_node.inline_token) |inline_token| {
try renderToken(tree, stream, inline_token, Space.Space); // inline
}
try renderToken(tree, stream, while_node.while_token, Space.Space); // while
try renderToken(tree, stream, tree.nextToken(while_node.while_token), Space.None); // (
try renderExpression(allocator, stream, tree, while_node.condition, Space.None);
const cond_rparen = tree.nextToken(while_node.condition.lastToken());
const body_is_block = nodeIsBlock(while_node.body);
var block_start_space: Space = undefined;
var after_body_space: Space = undefined;
if (body_is_block) {
block_start_space = Space.BlockStart;
after_body_space = if (while_node.@"else" == null) space else Space.SpaceOrOutdent;
} else if (tree.tokensOnSameLine(cond_rparen, while_node.body.lastToken())) {
block_start_space = Space.Space;
after_body_space = if (while_node.@"else" == null) space else Space.Space;
} else {
block_start_space = Space.Newline;
after_body_space = if (while_node.@"else" == null) space else Space.Newline;
}
{
const rparen_space = if (while_node.payload != null or while_node.continue_expr != null) Space.Space else block_start_space;
try renderToken(tree, stream, cond_rparen, rparen_space); // )
}
if (while_node.payload) |payload| {
const payload_space = Space.Space; //if (while_node.continue_expr != null) Space.Space else block_start_space;
try renderExpression(allocator, stream, tree, payload, payload_space);
}
if (while_node.continue_expr) |continue_expr| {
const rparen = tree.nextToken(continue_expr.lastToken());
const lparen = tree.prevToken(continue_expr.firstToken());
const colon = tree.prevToken(lparen);
try renderToken(tree, stream, colon, Space.Space); // :
try renderToken(tree, stream, lparen, Space.None); // (
try renderExpression(allocator, stream, tree, continue_expr, Space.None);
try renderToken(tree, stream, rparen, block_start_space); // )
}
{
if (!body_is_block) stream.pushIndent();
defer if (!body_is_block) stream.popIndent();
try renderExpression(allocator, stream, tree, while_node.body, after_body_space);
}
if (while_node.@"else") |@"else"| {
return renderExpression(allocator, stream, tree, &@"else".base, space);
}
},
.For => {
const for_node = @fieldParentPtr(ast.Node.For, "base", base);
if (for_node.label) |label| {
try renderToken(tree, stream, label, Space.None); // label
try renderToken(tree, stream, tree.nextToken(label), Space.Space); // :
}
if (for_node.inline_token) |inline_token| {
try renderToken(tree, stream, inline_token, Space.Space); // inline
}
try renderToken(tree, stream, for_node.for_token, Space.Space); // for
try renderToken(tree, stream, tree.nextToken(for_node.for_token), Space.None); // (
try renderExpression(allocator, stream, tree, for_node.array_expr, Space.None);
const rparen = tree.nextToken(for_node.array_expr.lastToken());
const body_is_block = for_node.body.id == .Block;
const src_one_line_to_body = !body_is_block and tree.tokensOnSameLine(rparen, for_node.body.firstToken());
const body_on_same_line = body_is_block or src_one_line_to_body;
try renderToken(tree, stream, rparen, Space.Space); // )
const space_after_payload = if (body_on_same_line) Space.Space else Space.Newline;
try renderExpression(allocator, stream, tree, for_node.payload, space_after_payload); // |x|
const space_after_body = blk: {
if (for_node.@"else") |@"else"| {
const src_one_line_to_else = tree.tokensOnSameLine(rparen, @"else".firstToken());
if (body_is_block or src_one_line_to_else) {
break :blk Space.Space;
} else {
break :blk Space.Newline;
}
} else {
break :blk space;
}
};
{
if (!body_on_same_line) stream.pushIndent();
defer if (!body_on_same_line) stream.popIndent();
try renderExpression(allocator, stream, tree, for_node.body, space_after_body); // { body }
}
if (for_node.@"else") |@"else"| {
return renderExpression(allocator, stream, tree, &@"else".base, space); // else
}
},
.If => {
const if_node = @fieldParentPtr(ast.Node.If, "base", base);
const lparen = tree.nextToken(if_node.if_token);
const rparen = tree.nextToken(if_node.condition.lastToken());
try renderToken(tree, stream, if_node.if_token, Space.Space); // if
try renderToken(tree, stream, lparen, Space.None); // (
try renderExpression(allocator, stream, tree, if_node.condition, Space.None); // condition
const body_is_if_block = if_node.body.id == .If;
const body_is_block = nodeIsBlock(if_node.body);
if (body_is_if_block) {
try renderExtraNewline(tree, stream, if_node.body);
} else if (body_is_block) {
const after_rparen_space = if (if_node.payload == null) Space.BlockStart else Space.Space;
try renderToken(tree, stream, rparen, after_rparen_space); // )
if (if_node.payload) |payload| {
try renderExpression(allocator, stream, tree, payload, Space.BlockStart); // |x|
}
if (if_node.@"else") |@"else"| {
try renderExpression(allocator, stream, tree, if_node.body, Space.SpaceOrOutdent);
return renderExpression(allocator, stream, tree, &@"else".base, space);
} else {
return renderExpression(allocator, stream, tree, if_node.body, space);
}
}
const src_has_newline = !tree.tokensOnSameLine(rparen, if_node.body.lastToken());
if (src_has_newline) {
const after_rparen_space = if (if_node.payload == null) Space.Newline else Space.Space;
try renderToken(tree, stream, rparen, after_rparen_space); // )
if (if_node.payload) |payload| {
try renderExpression(allocator, stream, tree, payload, Space.Newline);
}
if (if_node.@"else") |@"else"| {
const else_is_block = nodeIsBlock(@"else".body);
{
stream.pushIndent();
defer stream.popIndent();
try renderExpression(allocator, stream, tree, if_node.body, Space.Newline);
}
if (else_is_block) {
try renderToken(tree, stream, @"else".else_token, Space.Space); // else
if (@"else".payload) |payload| {
try renderExpression(allocator, stream, tree, payload, Space.Space);
}
return renderExpression(allocator, stream, tree, @"else".body, space);
} else {
const after_else_space = if (@"else".payload == null) Space.Newline else Space.Space;
try renderToken(tree, stream, @"else".else_token, after_else_space); // else
if (@"else".payload) |payload| {
try renderExpression(allocator, stream, tree, payload, Space.Newline);
}
stream.pushIndent();
defer stream.popIndent();
return renderExpression(allocator, stream, tree, @"else".body, space);
}
} else {
stream.pushIndent();
defer stream.popIndent();
return renderExpression(allocator, stream, tree, if_node.body, space);
}
}
// Single line if statement
try renderToken(tree, stream, rparen, Space.Space); // )
if (if_node.payload) |payload| {
try renderExpression(allocator, stream, tree, payload, Space.Space);
}
if (if_node.@"else") |@"else"| {
try renderExpression(allocator, stream, tree, if_node.body, Space.Space);
try renderToken(tree, stream, @"else".else_token, Space.Space);
if (@"else".payload) |payload| {
try renderExpression(allocator, stream, tree, payload, Space.Space);
}
return renderExpression(allocator, stream, tree, @"else".body, space);
} else {
return renderExpression(allocator, stream, tree, if_node.body, space);
}
},
.Asm => {
const asm_node = @fieldParentPtr(ast.Node.Asm, "base", base);
try renderToken(tree, stream, asm_node.asm_token, Space.Space); // asm
if (asm_node.volatile_token) |volatile_token| {
try renderToken(tree, stream, volatile_token, Space.Space); // volatile
try renderToken(tree, stream, tree.nextToken(volatile_token), Space.None); // (
} else {
try renderToken(tree, stream, tree.nextToken(asm_node.asm_token), Space.None); // (
}
if (asm_node.outputs.len == 0 and asm_node.inputs.len == 0 and asm_node.clobbers.len == 0) {
{
stream.pushIndent();
defer stream.popIndent();
try renderExpression(allocator, stream, tree, asm_node.template, Space.None);
}
return renderToken(tree, stream, asm_node.rparen, space);
}
contents: {
stream.pushIndent();
defer stream.popIndent();
const indent_extra = 2;
try renderExpression(allocator, stream, tree, asm_node.template, Space.Newline);
const colon1 = tree.nextToken(asm_node.template.lastToken());
const colon2 = if (asm_node.outputs.len == 0) blk: {
try renderToken(tree, stream, colon1, Space.Newline); // :
break :blk tree.nextToken(colon1);
} else blk: {
try renderToken(tree, stream, colon1, Space.Space); // :
stream.pushIndentN(indent_extra);
defer stream.popIndent();
var it = asm_node.outputs.iterator(0);
while (true) {
const asm_output = it.next().?;
const node = &(asm_output.*).base;
if (it.peek()) |next_asm_output| {
try renderExpression(allocator, stream, tree, node, Space.None);
const next_node = &(next_asm_output.*).base;
const comma = tree.prevToken(next_asm_output.*.firstToken());
try renderToken(tree, stream, comma, Space.Newline); // ,
try renderExtraNewline(tree, stream, next_node);
} else if (asm_node.inputs.len == 0 and asm_node.clobbers.len == 0) {
try renderExpression(allocator, stream, tree, node, Space.Newline);
break :contents;
} else {
try renderExpression(allocator, stream, tree, node, Space.Newline);
const comma_or_colon = tree.nextToken(node.lastToken());
break :blk switch (tree.tokens.at(comma_or_colon).id) {
.Comma => tree.nextToken(comma_or_colon),
else => comma_or_colon,
};
}
}
};
const colon3 = if (asm_node.inputs.len == 0) blk: {
try renderToken(tree, stream, colon2, Space.Newline); // :
break :blk tree.nextToken(colon2);
} else blk: {
try renderToken(tree, stream, colon2, Space.Space); // :
stream.pushIndentN(indent_extra);
defer stream.popIndent();
var it = asm_node.inputs.iterator(0);
while (true) {
const asm_input = it.next().?;
const node = &(asm_input.*).base;
if (it.peek()) |next_asm_input| {
try renderExpression(allocator, stream, tree, node, Space.None);
const next_node = &(next_asm_input.*).base;
const comma = tree.prevToken(next_asm_input.*.firstToken());
try renderToken(tree, stream, comma, Space.Newline); // ,
try renderExtraNewline(tree, stream, next_node);
} else if (asm_node.clobbers.len == 0) {
try renderExpression(allocator, stream, tree, node, Space.Newline);
break :contents;
} else {
try renderExpression(allocator, stream, tree, node, Space.Newline);
const comma_or_colon = tree.nextToken(node.lastToken());
break :blk switch (tree.tokens.at(comma_or_colon).id) {
.Comma => tree.nextToken(comma_or_colon),
else => comma_or_colon,
};
}
}
};
try renderToken(tree, stream, colon3, Space.Space); // :
var it = asm_node.clobbers.iterator(0);
while (true) {
const clobber_node = it.next().?.*;
if (it.peek() == null) {
try renderExpression(allocator, stream, tree, clobber_node, Space.Newline);
break :contents;
} else {
try renderExpression(allocator, stream, tree, clobber_node, Space.None);
const comma = tree.nextToken(clobber_node.lastToken());
try renderToken(tree, stream, comma, Space.Space); // ,
}
}
}
return renderToken(tree, stream, asm_node.rparen, space);
},
.AsmInput => {
const asm_input = @fieldParentPtr(ast.Node.AsmInput, "base", base);
try stream.write("[");
try renderExpression(allocator, stream, tree, asm_input.symbolic_name, Space.None);
try stream.write("] ");
try renderExpression(allocator, stream, tree, asm_input.constraint, Space.None);
try stream.write(" (");
try renderExpression(allocator, stream, tree, asm_input.expr, Space.None);
return renderToken(tree, stream, asm_input.lastToken(), space); // )
},
.AsmOutput => {
const asm_output = @fieldParentPtr(ast.Node.AsmOutput, "base", base);
try stream.write("[");
try renderExpression(allocator, stream, tree, asm_output.symbolic_name, Space.None);
try stream.write("] ");
try renderExpression(allocator, stream, tree, asm_output.constraint, Space.None);
try stream.write(" (");
switch (asm_output.kind) {
ast.Node.AsmOutput.Kind.Variable => |variable_name| {
try renderExpression(allocator, stream, tree, &variable_name.base, Space.None);
},
ast.Node.AsmOutput.Kind.Return => |return_type| {
try stream.write("-> ");
try renderExpression(allocator, stream, tree, return_type, Space.None);
},
}
return renderToken(tree, stream, asm_output.lastToken(), space); // )
},
.EnumLiteral => {
const enum_literal = @fieldParentPtr(ast.Node.EnumLiteral, "base", base);
try renderToken(tree, stream, enum_literal.dot, Space.None); // .
return renderToken(tree, stream, enum_literal.name, space); // name
},
.ContainerField,
.Root,
.VarDecl,
.Use,
.TestDecl,
.ParamDecl,
=> unreachable,
}
}
fn renderVarDecl(
allocator: *mem.Allocator,
stream: var,
tree: *ast.Tree,
var_decl: *ast.Node.VarDecl,
) (@TypeOf(stream).Child.Error || Error)!void {
if (var_decl.visib_token) |visib_token| {
try renderToken(tree, stream, visib_token, Space.Space); // pub
}
if (var_decl.extern_export_token) |extern_export_token| {
try renderToken(tree, stream, extern_export_token, Space.Space); // extern
if (var_decl.lib_name) |lib_name| {
try renderExpression(allocator, stream, tree, lib_name, Space.Space); // "lib"
}
}
if (var_decl.comptime_token) |comptime_token| {
try renderToken(tree, stream, comptime_token, Space.Space); // comptime
}
if (var_decl.thread_local_token) |thread_local_token| {
try renderToken(tree, stream, thread_local_token, Space.Space); // threadlocal
}
try renderToken(tree, stream, var_decl.mut_token, Space.Space); // var
const name_space = if (var_decl.type_node == null and (var_decl.align_node != null or
var_decl.section_node != null or var_decl.init_node != null)) Space.Space else Space.None;
try renderToken(tree, stream, var_decl.name_token, name_space);
if (var_decl.type_node) |type_node| {
try renderToken(tree, stream, tree.nextToken(var_decl.name_token), Space.Space);
const s = if (var_decl.align_node != null or
var_decl.section_node != null or
var_decl.init_node != null) Space.Space else Space.None;
try renderExpression(allocator, stream, tree, type_node, s);
}
if (var_decl.align_node) |align_node| {
const lparen = tree.prevToken(align_node.firstToken());
const align_kw = tree.prevToken(lparen);
const rparen = tree.nextToken(align_node.lastToken());
try renderToken(tree, stream, align_kw, Space.None); // align
try renderToken(tree, stream, lparen, Space.None); // (
try renderExpression(allocator, stream, tree, align_node, Space.None);
const s = if (var_decl.section_node != null or var_decl.init_node != null) Space.Space else Space.None;
try renderToken(tree, stream, rparen, s); // )
}
if (var_decl.section_node) |section_node| {
const lparen = tree.prevToken(section_node.firstToken());
const section_kw = tree.prevToken(lparen);
const rparen = tree.nextToken(section_node.lastToken());
try renderToken(tree, stream, section_kw, Space.None); // linksection
try renderToken(tree, stream, lparen, Space.None); // (
try renderExpression(allocator, stream, tree, section_node, Space.None);
const s = if (var_decl.init_node != null) Space.Space else Space.None;
try renderToken(tree, stream, rparen, s); // )
}
if (var_decl.init_node) |init_node| {
const s = if (init_node.id == .MultilineStringLiteral) Space.None else Space.Space;
try renderToken(tree, stream, var_decl.eq_token.?, s); // =
stream.pushIndentOneShot();
try renderExpression(allocator, stream, tree, init_node, Space.None);
}
try renderToken(tree, stream, var_decl.semicolon_token, Space.Newline);
}
fn renderParamDecl(
allocator: *mem.Allocator,
stream: var,
tree: *ast.Tree,
base: *ast.Node,
space: Space,
) (@TypeOf(stream).Child.Error || Error)!void {
const param_decl = @fieldParentPtr(ast.Node.ParamDecl, "base", base);
try renderDocComments(tree, stream, param_decl);
if (param_decl.comptime_token) |comptime_token| {
try renderToken(tree, stream, comptime_token, Space.Space);
}
if (param_decl.noalias_token) |noalias_token| {
try renderToken(tree, stream, noalias_token, Space.Space);
}
if (param_decl.name_token) |name_token| {
try renderToken(tree, stream, name_token, Space.None);
try renderToken(tree, stream, tree.nextToken(name_token), Space.Space); // :
}
if (param_decl.var_args_token) |var_args_token| {
try renderToken(tree, stream, var_args_token, space);
} else {
try renderExpression(allocator, stream, tree, param_decl.type_node, space);
}
}
fn renderStatement(
allocator: *mem.Allocator,
stream: var,
tree: *ast.Tree,
base: *ast.Node,
) (@TypeOf(stream).Child.Error || Error)!void {
switch (base.id) {
.VarDecl => {
const var_decl = @fieldParentPtr(ast.Node.VarDecl, "base", base);
try renderVarDecl(allocator, stream, tree, var_decl);
},
else => {
if (base.requireSemiColon()) {
try renderExpression(allocator, stream, tree, base, Space.None);
const semicolon_index = tree.nextToken(base.lastToken());
assert(tree.tokens.at(semicolon_index).id == .Semicolon);
try renderToken(tree, stream, semicolon_index, Space.Newline);
} else {
try renderExpression(allocator, stream, tree, base, Space.Newline);
}
},
}
}
const Space = enum {
None,
Newline,
Comma,
Space,
SpaceOrOutdent,
NoNewline,
NoComment,
BlockStart,
};
fn renderTokenOffset(
tree: *ast.Tree,
stream: var,
token_index: ast.TokenIndex,
space: Space,
token_skip_bytes: usize,
) (@TypeOf(stream).Child.Error || Error)!void {
if (space == Space.BlockStart) {
// If placing the lbrace on the current line would cause an uggly gap then put the lbrace on the next line
const new_space = if (stream.isLineOverIndented()) Space.Newline else Space.Space;
return renderToken(tree, stream, token_index, new_space);
}
var token = tree.tokens.at(token_index);
try stream.write(mem.trimRight(u8, tree.tokenSlicePtr(token)[token_skip_bytes..], " "));
if (space == Space.NoComment)
return;
var next_token = tree.tokens.at(token_index + 1);
if (space == Space.Comma) switch (next_token.id) {
.Comma => return renderToken(tree, stream, token_index + 1, Space.Newline),
.LineComment => {
try stream.write(", ");
return renderToken(tree, stream, token_index + 1, Space.Newline);
},
else => {
if (token_index + 2 < tree.tokens.len and tree.tokens.at(token_index + 2).id == .MultilineStringLiteralLine) {
try stream.write(",");
return;
} else {
try stream.write(",");
try stream.insertNewline();
return;
}
},
};
// Skip over same line doc comments
var offset: usize = 1;
if (next_token.id == .DocComment) {
const loc = tree.tokenLocationPtr(token.end, next_token);
if (loc.line == 0) {
offset += 1;
next_token = tree.tokens.at(token_index + offset);
}
}
if (next_token.id != .LineComment) blk: {
switch (space) {
Space.None, Space.NoNewline => return,
Space.Newline => {
if (next_token.id == .MultilineStringLiteralLine) {
return;
} else {
try stream.insertNewline();
return;
}
},
Space.Space, Space.SpaceOrOutdent => {
if (next_token.id == .MultilineStringLiteralLine)
return;
try stream.writeByte(' ');
return;
},
Space.NoComment, Space.Comma, Space.BlockStart => unreachable,
}
}
while (true) {
const comment_is_empty = mem.trimRight(u8, tree.tokenSlicePtr(next_token), " ").len == 2;
if (comment_is_empty) {
switch (space) {
Space.Newline => {
offset += 1;
token = next_token;
next_token = tree.tokens.at(token_index + offset);
if (next_token.id != .LineComment) {
try stream.insertNewline();
return;
}
},
else => break,
}
} else {
break;
}
}
var loc = tree.tokenLocationPtr(token.end, next_token);
if (loc.line == 0) {
try stream.print(" {}", .{mem.trimRight(u8, tree.tokenSlicePtr(next_token), " ")});
offset = 2;
token = next_token;
next_token = tree.tokens.at(token_index + offset);
if (next_token.id != .LineComment) {
switch (space) {
Space.None, Space.Space => {
try stream.insertNewline();
},
Space.SpaceOrOutdent => {
try stream.insertNewline();
},
Space.Newline => {
if (next_token.id == .MultilineStringLiteralLine) {
return;
} else {
try stream.insertNewline();
return;
}
},
Space.NoNewline => {},
Space.NoComment, Space.Comma, Space.BlockStart => unreachable,
}
return;
}
loc = tree.tokenLocationPtr(token.end, next_token);
}
while (true) {
assert(loc.line != 0);
try stream.insertNewline();
if (loc.line != 1) try stream.insertNewline();
try stream.write(mem.trimRight(u8, tree.tokenSlicePtr(next_token), " "));
offset += 1;
token = next_token;
next_token = tree.tokens.at(token_index + offset);
if (next_token.id != .LineComment) {
switch (space) {
Space.Newline => {
if (next_token.id == .MultilineStringLiteralLine) {
return;
} else {
try stream.insertNewline();
return;
}
},
Space.None, Space.Space => {
try stream.insertNewline();
const after_comment_token = tree.tokens.at(token_index + offset);
},
Space.SpaceOrOutdent => {
try stream.insertNewline();
},
Space.NoNewline => {},
Space.NoComment, Space.Comma, Space.BlockStart => unreachable,
}
return;
}
loc = tree.tokenLocationPtr(token.end, next_token);
}
}
fn renderToken(
tree: *ast.Tree,
stream: var,
token_index: ast.TokenIndex,
space: Space,
) (@TypeOf(stream).Child.Error || Error)!void {
return renderTokenOffset(tree, stream, token_index, space, 0);
}
fn renderDocComments(
tree: *ast.Tree,
stream: var,
node: var,
) (@TypeOf(stream).Child.Error || Error)!void {
const comment = node.doc_comments orelse return;
var it = comment.lines.iterator(0);
const first_token = node.firstToken();
while (it.next()) |line_token_index| {
if (line_token_index.* < first_token) {
try renderToken(tree, stream, line_token_index.*, Space.Newline);
} else {
try renderToken(tree, stream, line_token_index.*, Space.NoComment);
try stream.insertNewline();
}
}
}
fn nodeIsBlock(base: *const ast.Node) bool {
return switch (base.id) {
.Block,
.If,
.For,
.While,
.Switch,
=> true,
else => false,
};
}
fn nodeCausesSliceOpSpace(base: *ast.Node) bool {
const infix_op = base.cast(ast.Node.InfixOp) orelse return false;
return switch (infix_op.op) {
ast.Node.InfixOp.Op.Period => false,
else => true,
};
}
fn copyFixingWhitespace(stream: var, slice: []const u8) @TypeOf(stream).Child.Error!void {
for (slice) |byte| switch (byte) {
'\t' => try stream.write(" "),
'\r' => {},
else => try stream.writeByte(byte),
};
} | lib/std/zig/render.zig |
const std = @import("std");
pub const Server = struct {
server_addr: std.net.Address,
allocator: *std.mem.Allocator,
stream_server: std.net.StreamServer,
pages: *const Pages,
contexts: ContextsBag,
shutdownServer: std.atomic.Int(bool) = std.atomic.Int(bool).init(false),
page_cnt: std.atomic.Int(usize) = std.atomic.Int(usize).init(0),
server_thread: ?*std.Thread = null,
pub fn init(allocator: *std.mem.Allocator, pages: Pages, addr: std.net.Address) !Server {
return Server{
.allocator = allocator,
.stream_server = std.net.StreamServer.init(.{ .reuse_address = true }),
.pages = &pages,
.contexts = ContextsBag.init(allocator),
.server_addr = addr,
};
}
pub fn shutdown(self: *Server) !void {
if (!self.shutdownServer.xchg(true)) {
var file = try std.net.tcpConnectToAddress(self.server_addr);
defer file.close();
}
}
pub fn run(self: *Server) !void {
self.server_thread = try std.Thread.spawn(self, runServer);
}
pub fn deinit(self: *Server) void {
if (self.server_thread) |t| {
self.server_thread = null;
self.shutdown() catch return; // damit wait nicht blockiert, im Fehlerfall lieber hier zurück
t.wait();
}
}
pub const PageAction = struct {
fktAlloc: fn (allocator: *std.mem.Allocator, ctx: *const ConnectionContext) ?[]const u8,
};
pub const Pages = std.StringHashMap(*const PageAction);
pub const ConnectionContext = struct {
conn: std.net.StreamServer.Connection,
server: *Server, // const geht nicht wegen shutdownServer.get, braucht non-const
thread: ?*std.Thread = null,
finished: bool = false,
fn set_finished(self: *ConnectionContext) void {
const ptr: *volatile bool = &self.finished;
ptr.* = true;
}
fn is_finished(self: *ConnectionContext) bool {
const ptr: *volatile bool = &self.finished;
return ptr.*;
}
};
const ContextsBag = std.AutoHashMap(*ConnectionContext, void);
fn cleanupFinishedThreads(self: *Server) usize {
std.log.debug("server: cleanupFinishedThreads", .{});
const allocator = self.allocator;
var unfinished_threads: usize = 0;
var it = self.contexts.iterator();
while (it.next()) |entry| {
const ctx = entry.key;
if (ctx.is_finished()) {
std.debug.assert(self.contexts.remove(ctx) != null);
// if thread.spawn failed thread will be null and finished true
if (ctx.thread) |thread|
thread.wait();
allocator.destroy(ctx);
} else {
unfinished_threads += 1;
}
}
return unfinished_threads;
}
fn waitForActiveThreadsAndCleanup(self: *Server) void {
std.log.debug("server: waitForActiveThreadsAndCleanup", .{});
const timeout_in_s = std.time.ns_per_s * 5;
var cnt = cleanupFinishedThreads(self);
const start_time = std.time.timestamp();
while (cnt > 0 and ((std.time.timestamp() - start_time) < timeout_in_s)) {
std.log.info("server: still waiting for {} unfinished threads", .{cnt});
std.time.sleep(std.time.ns_per_ms * 100);
cnt = cleanupFinishedThreads(self);
}
if (cnt == 0) {
std.log.info("server: all threads finished, closing server now.", .{});
} else {
std.log.info("server: timeout waiting for {} unfinished threads =>abort waiting", .{cnt});
}
}
fn runServer(self: *Server) !void {
const allocator = self.allocator;
defer self.contexts.deinit();
defer self.stream_server.deinit();
defer waitForActiveThreadsAndCleanup(self);
try self.stream_server.listen(self.server_addr);
while (!self.shutdownServer.get()) {
const conn = self.stream_server.accept() catch |err| switch (err) {
std.net.StreamServer.AcceptError.ConnectionAborted => continue,
else => return err,
};
// between while and here shutdownServer will be set
// if the exit Page is called (handleConn, )
if (!self.shutdownServer.get()) {
// main-thread owns new_ctx until successful thread.spawn
// sicherstellen, dass der neu erzeugte Contex für den Thread auch gespeichert werden kann
// sonst kann der später nicht mehr richtig aufgeräumt werden
if (self.contexts.ensureCapacity(self.contexts.count() + 1)) |_| {
const new_ctx = try allocator.create(ConnectionContext);
errdefer allocator.destroy(new_ctx);
new_ctx.* = ConnectionContext{
.conn = conn,
.server = self,
};
// thread.wait won't be called assuming that it's not
// nessesary to do so.
// But the documentation says that you have to call wait
if (std.Thread.spawn(new_ctx, handleConn)) |thread| {
new_ctx.thread = thread;
} else |_| {
new_ctx.set_finished();
}
// muss klappen, wenn Pointer schon als key vorhanden => assert will fail
// und eine Allocation wird es dank ensureCapacity nicht mehr geben
self.contexts.putNoClobber(new_ctx, .{}) catch unreachable;
} else |_| {
// ensureCapacity failed => nothing we can do, just let the old thread run
}
}
_ =
cleanupFinishedThreads(self);
}
}
fn handleConn(ctx: *ConnectionContext) !void {
defer ctx.set_finished(); // allerallerletzte Aktion, da dann sofort der ctx freigegeben wird!
const request_size = 1024;
std.log.info("server handleConn: connected to {}, thread id = {}", .{ ctx.conn.address, std.Thread.getCurrentId() });
defer {
std.log.info("server handleConn: closing connection to {}, thread id = {}", .{ ctx.conn.address, std.Thread.getCurrentId() });
ctx.conn.file.close();
}
while (true) {
var arena = std.heap.ArenaAllocator.init(ctx.server.allocator);
const allocator = &arena.allocator;
defer arena.deinit();
const request_buffer = try allocator.alloc(u8, request_size);
const answer_buffer = try allocator.alloc(u8, request_size);
const conn = ctx.conn;
var requestComplete = false;
var idx: usize = 0;
const start = std.time.timestamp();
const timeout = std.time.ns_per_s * 60; // in max. 1 min the request has to be finished/completed
var timeouted = false;
while (!requestComplete) {
if (std.time.timestamp() - start > timeout)
return error.Timeout;
const len = try conn.file.reader().read(request_buffer[idx..]);
idx += len;
if (len == 0 and ctx.server.shutdownServer.get())
return; //return error.Aborted;
requestComplete = std.mem.endsWith(u8, request_buffer[0..idx], "\r\n\r\n");
if (!requestComplete and idx == request_size)
return error.BadRequestLength;
}
const request = request_buffer[0..idx];
const cmd_pos = std.mem.indexOf(u8, request, "GET /");
if (cmd_pos) |pos| {
if ((pos != 0 and request.len < "GET / HTTP/1.1".len)) {
return error.BadRequestCmdStart;
}
} else {
return error.BadRequestCmd;
}
const requested_page_end = std.mem.indexOf(u8, request, " HTTP/1.");
if (requested_page_end == null)
return error.BadRequestCmdEnd;
const page_called = ctx.server.page_cnt.incr();
const requested_page = request[4..requested_page_end.?];
std.log.info("server handleConn: requested_page={}", .{requested_page});
var code: []const u8 = undefined;
var answer: []const u8 = undefined;
if (ctx.server.pages.get(requested_page)) |action| {
if (action.fktAlloc(allocator, ctx)) |txt| {
code = "200 OK"; // TODO
answer = txt;
} else {
code = "404 ERROR"; // TODO
answer = try std.fmt.allocPrint(allocator, "internal server error.", .{});
}
} else {
code = "404 ERROR"; // TODO
answer = try std.fmt.allocPrint(allocator, "Page not found.", .{});
}
//const answer = try std.fmt.bufPrint(answer_buffer, "Hello world to {}\r\npage {} * requested\r\n", .{ conn.address, page_called });
const response = try std.fmt.allocPrint(allocator, "HTTP/1.1 {}\r\n" ++
"Content-Length: {}\r\n" ++
"Connection: keep-alive\r\n" ++
"Content-Type: text/plain; charset=UTF-8\r\n" ++
"Server: Example\r\n" ++
"Date: Wed, 17 Apr 2013 12:00:00 GMT\r\n" ++
"\r\n" ++
"{}", .{ code, answer.len, answer });
std.log.debug("Server: Response sent: {}", .{response});
try conn.file.writeAll(response);
if (std.mem.eql(u8, requested_page, "/exit")) {
try ctx.server.shutdown();
}
}
}
}; | src/http_server.zig |
pub const PR_SET_PDEATHSIG = 1;
pub const PR_GET_PDEATHSIG = 2;
pub const PR_GET_DUMPABLE = 3;
pub const PR_SET_DUMPABLE = 4;
pub const PR_GET_UNALIGN = 5;
pub const PR_SET_UNALIGN = 6;
pub const PR_UNALIGN_NOPRINT = 1;
pub const PR_UNALIGN_SIGBUS = 2;
pub const PR_GET_KEEPCAPS = 7;
pub const PR_SET_KEEPCAPS = 8;
pub const PR_GET_FPEMU = 9;
pub const PR_SET_FPEMU = 10;
pub const PR_FPEMU_NOPRINT = 1;
pub const PR_FPEMU_SIGFPE = 2;
pub const PR_GET_FPEXC = 11;
pub const PR_SET_FPEXC = 12;
pub const PR_FP_EXC_SW_ENABLE = 0x80;
pub const PR_FP_EXC_DIV = 0x010000;
pub const PR_FP_EXC_OVF = 0x020000;
pub const PR_FP_EXC_UND = 0x040000;
pub const PR_FP_EXC_RES = 0x080000;
pub const PR_FP_EXC_INV = 0x100000;
pub const PR_FP_EXC_DISABLED = 0;
pub const PR_FP_EXC_NONRECOV = 1;
pub const PR_FP_EXC_ASYNC = 2;
pub const PR_FP_EXC_PRECISE = 3;
pub const PR_GET_TIMING = 13;
pub const PR_SET_TIMING = 14;
pub const PR_TIMING_STATISTICAL = 0;
pub const PR_TIMING_TIMESTAMP = 1;
pub const PR_SET_NAME = 15;
pub const PR_GET_NAME = 16;
pub const PR_GET_ENDIAN = 19;
pub const PR_SET_ENDIAN = 20;
pub const PR_ENDIAN_BIG = 0;
pub const PR_ENDIAN_LITTLE = 1;
pub const PR_ENDIAN_PPC_LITTLE = 2;
pub const PR_GET_SECCOMP = 21;
pub const PR_SET_SECCOMP = 22;
pub const PR_CAPBSET_READ = 23;
pub const PR_CAPBSET_DROP = 24;
pub const PR_GET_TSC = 25;
pub const PR_SET_TSC = 26;
pub const PR_TSC_ENABLE = 1;
pub const PR_TSC_SIGSEGV = 2;
pub const PR_GET_SECUREBITS = 27;
pub const PR_SET_SECUREBITS = 28;
pub const PR_SET_TIMERSLACK = 29;
pub const PR_GET_TIMERSLACK = 30;
pub const PR_TASK_PERF_EVENTS_DISABLE = 31;
pub const PR_TASK_PERF_EVENTS_ENABLE = 32;
pub const PR_MCE_KILL = 33;
pub const PR_MCE_KILL_CLEAR = 0;
pub const PR_MCE_KILL_SET = 1;
pub const PR_MCE_KILL_LATE = 0;
pub const PR_MCE_KILL_EARLY = 1;
pub const PR_MCE_KILL_DEFAULT = 2;
pub const PR_MCE_KILL_GET = 34;
pub const PR_SET_MM = 35;
pub const PR_SET_MM_START_CODE = 1;
pub const PR_SET_MM_END_CODE = 2;
pub const PR_SET_MM_START_DATA = 3;
pub const PR_SET_MM_END_DATA = 4;
pub const PR_SET_MM_START_STACK = 5;
pub const PR_SET_MM_START_BRK = 6;
pub const PR_SET_MM_BRK = 7;
pub const PR_SET_MM_ARG_START = 8;
pub const PR_SET_MM_ARG_END = 9;
pub const PR_SET_MM_ENV_START = 10;
pub const PR_SET_MM_ENV_END = 11;
pub const PR_SET_MM_AUXV = 12;
pub const PR_SET_MM_EXE_FILE = 13;
pub const PR_SET_MM_MAP = 14;
pub const PR_SET_MM_MAP_SIZE = 15;
pub const prctl_mm_map = extern struct {
start_code: u64,
end_code: u64,
start_data: u64,
end_data: u64,
start_brk: u64,
brk: u64,
start_stack: u64,
arg_start: u64,
arg_end: u64,
env_start: u64,
env_end: u64,
auxv: *u64,
auxv_size: u32,
exe_fd: u32,
};
pub const PR_SET_PTRACER = 0x59616d61;
pub const PR_SET_PTRACER_ANY = std.math.maxInt(c_ulong);
pub const PR_SET_CHILD_SUBREAPER = 36;
pub const PR_GET_CHILD_SUBREAPER = 37;
pub const PR_SET_NO_NEW_PRIVS = 38;
pub const PR_GET_NO_NEW_PRIVS = 39;
pub const PR_GET_TID_ADDRESS = 40;
pub const PR_SET_THP_DISABLE = 41;
pub const PR_GET_THP_DISABLE = 42;
pub const PR_MPX_ENABLE_MANAGEMENT = 43;
pub const PR_MPX_DISABLE_MANAGEMENT = 44;
pub const PR_SET_FP_MODE = 45;
pub const PR_GET_FP_MODE = 46;
pub const PR_FP_MODE_FR = 1 << 0;
pub const PR_FP_MODE_FRE = 1 << 1;
pub const PR_CAP_AMBIENT = 47;
pub const PR_CAP_AMBIENT_IS_SET = 1;
pub const PR_CAP_AMBIENT_RAISE = 2;
pub const PR_CAP_AMBIENT_LOWER = 3;
pub const PR_CAP_AMBIENT_CLEAR_ALL = 4;
pub const PR_SVE_SET_VL = 50;
pub const PR_SVE_SET_VL_ONEXEC = 1 << 18;
pub const PR_SVE_GET_VL = 51;
pub const PR_SVE_VL_LEN_MASK = 0xffff;
pub const PR_SVE_VL_INHERIT = 1 << 17;
pub const PR_GET_SPECULATION_CTRL = 52;
pub const PR_SET_SPECULATION_CTRL = 53;
pub const PR_SPEC_STORE_BYPASS = 0;
pub const PR_SPEC_NOT_AFFECTED = 0;
pub const PR_SPEC_PRCTL = 1 << 0;
pub const PR_SPEC_ENABLE = 1 << 1;
pub const PR_SPEC_DISABLE = 1 << 2;
pub const PR_SPEC_FORCE_DISABLE = 1 << 3; | lib/std/os/bits/linux/prctl.zig |
const image = @import("image.zig");
const Rectangle = image.Rectangle;
const std = @import("std");
const testing = std.testing;
fn in(f: Rectangle, g: Rectangle) bool {
if (!f.in(g)) {
return false;
}
var y = f.min.y;
while (y < f.max.y) {
var x = f.min.x;
while (x < f.max.x) {
var p = image.Point.init(x, y);
if (!p.in(g)) {
return false;
}
x += 1;
}
y += 1;
}
return true;
}
const rectangles = [_]Rectangle{
Rectangle.rect(0, 0, 10, 10),
Rectangle.rect(10, 0, 20, 10),
Rectangle.rect(1, 2, 3, 4),
Rectangle.rect(4, 6, 10, 10),
Rectangle.rect(2, 3, 12, 5),
Rectangle.rect(-1, -2, 0, 0),
Rectangle.rect(-1, -2, 4, 6),
Rectangle.rect(-10, -20, 30, 40),
Rectangle.rect(8, 8, 8, 8),
Rectangle.rect(88, 88, 88, 88),
Rectangle.rect(6, 5, 4, 3),
};
test "Rectangle" {
for (rectangles) |r| {
for (rectangles) |s| {
const got = r.eq(s);
const want = in(r, s) and in(s, r);
testing.expectEqual(got, want);
}
}
for (rectangles) |r| {
for (rectangles) |s| {
const a = r.intersect(s);
testing.expect(in(a, r));
testing.expect(in(a, s));
const is_zero = a.eq(Rectangle.zero());
const overlaps = r.overlaps(s);
testing.expect(is_zero != overlaps);
const larger_than_a = [_]Rectangle{
Rectangle.init(
a.min.x - 1,
a.min.y,
a.max.x,
a.max.y,
),
Rectangle.init(
a.min.x,
a.min.y - 1,
a.max.x,
a.max.y,
),
Rectangle.init(
a.min.x,
a.min.y,
a.max.x + 1,
a.max.y,
),
Rectangle.init(
a.min.x,
a.min.y,
a.max.x,
a.max.y + 1,
),
};
for (larger_than_a) |b| {
if (b.empty()) {
continue;
}
testing.expect(!(in(b, r) and in(b, s)));
}
}
}
for (rectangles) |r| {
for (rectangles) |s| {
const a = r.runion(s);
testing.expect(in(r, a));
testing.expect(in(s, a));
if (a.empty()) {
continue;
}
const smaller_than_a = [_]Rectangle{
Rectangle.init(
a.min.x + 1,
a.min.y,
a.max.x,
a.max.y,
),
Rectangle.init(
a.min.x,
a.min.y + 1,
a.max.x,
a.max.y,
),
Rectangle.init(
a.min.x,
a.min.y,
a.max.x - 1,
a.max.y,
),
Rectangle.init(
a.min.x,
a.min.y,
a.max.x,
a.max.y - 1,
),
};
for (smaller_than_a) |b| {
testing.expect(!(in(r, b) and in(s, b)));
}
}
}
}
const TestImage = struct {
name: []const u8,
image: image.Image,
mem: []u8,
};
fn newRGBA(a: *std.mem.Allocator, r: Rectangle) !TestImage {
const w = @intCast(usize, r.dx());
const h = @intCast(usize, r.dy());
const size = 4 * w * h;
var u = try a.alloc(u8, size);
var m = &image.RGBA.init(u, 4 * r.dx(), r);
return TestImage{
.name = "RGBA",
.image = m.image(),
.mem = u,
};
}
test "Image" {
var allocator = std.debug.global_allocator;
const rgb = try newRGBA(allocator, Rectangle.rect(0, 0, 10, 10));
defer allocator.free(rgb.mem);
const test_images = [_]TestImage{rgb};
for (test_images) |tc| {
const r = Rectangle.rect(0, 0, 10, 10);
testing.expect(r.eq(tc.image.bounds));
}
} | src/image/image_test.zig |
const std = @import("std");
const c = @import("c/c.zig");
const utils = @import("utils.zig");
usingnamespace @import("types.zig");
pub const Event = union(enum) {
const Self = @This();
key: KeyEvent,
mouse: MouseEvent,
window_buffer_size: Coords,
menu: u32,
focus: bool,
pub fn fromInputRecord(ir: c.INPUT_RECORD) Self {
switch (ir.EventType) {
// NOTE: I'm unsure if this behavior is intentional or not but the KeyEvent.uChar union has two active fields at a time
c.KEY_EVENT => {
return Self{.key = .{
.key =
if (ir.Event.KeyEvent.uChar.AsciiChar == ir.Event.KeyEvent.uChar.UnicodeChar)
(if (ir.Event.KeyEvent.uChar.AsciiChar == 0)
(if (VirtualKey.fromValue(ir.Event.KeyEvent.wVirtualKeyCode)) |v| Key{ .virtual_key = v } else Key{ .unknown = {} } )
else Key{ .ascii = ir.Event.KeyEvent.uChar.AsciiChar })
else Key{ .unicode = ir.Event.KeyEvent.uChar.UnicodeChar },
.is_down = if (ir.Event.KeyEvent.bKeyDown == 0) false else true,
.control_keys = utils.fromUnsigned(ControlKeys, ir.Event.KeyEvent.dwControlKeyState)
}};
},
c.MOUSE_EVENT => {
var flags = utils.fromUnsigned(MouseFlags, ir.Event.MouseEvent.dwEventFlags);
return Self{.mouse =. {
.abs_coords = @bitCast(Coords, ir.Event.MouseEvent.dwMousePosition),
.mouse_buttons = utils.fromUnsigned(MouseButtons, ir.Event.MouseEvent.dwButtonState),
.mouse_flags = flags,
.mouse_scroll_direction = if (flags.mouse_wheeled) (
if (ir.Event.MouseEvent.dwButtonState & 0xFF000000 == 0xFF000000) MouseScrollDirection.down else MouseScrollDirection.up
) else if (flags.mouse_hwheeled) (
if (ir.Event.MouseEvent.dwButtonState & 0xFF000000 == 0xFF000000) MouseScrollDirection.right else MouseScrollDirection.left
) else null,
.control_keys = utils.fromUnsigned(ControlKeys, ir.Event.MouseEvent.dwControlKeyState)
}};
},
c.WINDOW_BUFFER_SIZE_EVENT => {
return Self{.window_buffer_size = @bitCast(Coords, ir.Event.WindowBufferSizeEvent.dwSize)};
},
c.MENU_EVENT => {
return Self{.menu = ir.Event.MenuEvent.dwCommandId};
},
c.FOCUS_EVENT => {
return Self{.focus = if (ir.Event.FocusEvent.bSetFocus == 0) false else true};
},
else => std.debug.panic("Not implemented: {}!\n", .{ir.EventType})
}
}
}; | src/events.zig |
const std = @import("std");
const glfw = @import("glfz");
const zgpu = @import("zgpu");
pub fn main() !void {
try glfw.init();
defer glfw.deinit();
const win = try glfw.Window.init(800, 600, "zgpu triangle", .{
.client_api = .none,
});
defer win.deinit();
// TODO: support not-X11
const dpy = glfw.getX11Display(c_void) orelse {
return error.DisplayError;
};
const surface = zgpu.base.createSurface(&.{
.next_in_chain = &(zgpu.SurfaceDescriptorFromXlib{
.display = dpy,
.window = win.getX11Window(),
}).chain,
});
var adapter: zgpu.Adapter = undefined;
zgpu.base.requestAdapter(&.{
.compatible_surface = surface,
.power_preference = .high_performance,
.force_fallback_adapter = false,
}, requestAdapterCallback, @ptrCast(*c_void, &adapter));
var device: zgpu.Device = undefined;
adapter.requestDevice(&.{
.next_in_chain = &(zgpu.DeviceExtras{
.label = "Device",
}).chain,
.required_features_count = 0,
.required_features = undefined,
.required_limits = &.{ .limits = .{
.max_bind_groups = 1,
} },
}, requestDeviceCallback, @ptrCast(*c_void, &device));
defer device.drop();
const shader = device.createShaderModule(&.{
.next_in_chain = &(zgpu.ShaderModuleWGSLDescriptor{
.source = @embedFile("shader.wgsl"),
}).chain,
.label = "shader.wgsl",
});
defer shader.drop();
const pipeline_layout = device.createPipelineLayout(&.{
.next_in_chain = null,
.label = "Pipeline layout",
.bind_group_layouts = null,
.bind_group_layout_count = 0,
});
defer pipeline_layout.drop();
var swapchain_format = surface.getPreferredFormat(adapter);
const pipeline = device.createRenderPipeline(&zgpu.RenderPipelineDescriptor{
.next_in_chain = null,
.label = "Render Pipeline",
.layout = pipeline_layout,
.vertex = .{
.next_in_chain = null,
.module = shader,
.entry_point = "vs_main",
.constant_count = 0,
.constants = undefined,
.buffer_count = 0,
.buffers = undefined,
},
.primitive = .{
.next_in_chain = null,
.topology = .triangle_list,
.strip_index_format = .unknown,
.front_face = .ccw,
.cull_mode = .none,
},
.multisample = .{
.next_in_chain = null,
.count = 1,
.mask = ~@as(u32, 0),
.alpha_to_coverage_enabled = false,
},
.fragment = &.{
.next_in_chain = null,
.module = shader,
.entry_point = "fs_main",
.constant_count = 0,
.constants = undefined,
.target_count = 1,
.targets = &zgpu.ColorTargetState{
.next_in_chain = null,
.format = swapchain_format,
.blend = &.{
.color = .{
.src_factor = .one,
.dst_factor = .zero,
.operation = .add,
},
.alpha = .{
.src_factor = .one,
.dst_factor = .zero,
.operation = .add,
},
},
.write_mask = .{},
},
},
.depth_stencil = null,
});
defer pipeline.drop();
var prev_size = win.windowSize();
var swapchain = device.createSwapChain(surface, &.{
.label = "Swap chain",
.usage = .{ .render_attachment = true },
.format = swapchain_format,
.width = prev_size[0],
.height = prev_size[1],
.present_mode = .fifo,
});
while (!win.shouldClose()) {
const size = win.windowSize();
if (!std.meta.eql(size, prev_size)) {
prev_size = size;
swapchain = device.createSwapChain(surface, &.{
.label = "Swap chain",
.usage = .{ .render_attachment = true },
.format = swapchain_format,
.width = prev_size[0],
.height = prev_size[1],
.present_mode = .fifo,
});
}
const next_texture = swapchain.getCurrentTextureView() orelse {
return error.SwapchainTextureError;
};
const encoder = device.createCommandEncoder(
&.{ .label = "Command Encoder" },
);
const render_pass = encoder.beginRenderPass(&.{
.label = "Render pass",
.color_attachments = &[_]zgpu.RenderPassColorAttachment{.{
.view = next_texture,
.resolve_target = null,
.load_op = .clear,
.store_op = .store,
.clear_color = .{ .r = 0, .g = 0, .b = 0, .a = 1 },
}},
.color_attachment_count = 1,
});
render_pass.setPipeline(pipeline);
render_pass.draw(3, 1, 0, 0);
render_pass.endPass();
const queue = device.getQueue();
const cmd_buffer = [_]zgpu.CommandBuffer{encoder.finish(&.{})};
queue.submit(1, &cmd_buffer);
swapchain.present();
glfw.pollEvents();
}
}
fn requestAdapterCallback(status: zgpu.RequestAdapterStatus, adapter: zgpu.Adapter, message: ?[*:0]const u8, userdata: ?*c_void) callconv(.C) void {
_ = status; // TODO: check
_ = message;
@ptrCast(*align(1) zgpu.Adapter, userdata.?).* = adapter;
}
fn requestDeviceCallback(status: zgpu.RequestDeviceStatus, device: zgpu.Device, message: ?[*:0]const u8, userdata: ?*c_void) callconv(.C) void {
_ = status; // TODO: check
_ = message;
@ptrCast(*align(1) zgpu.Device, userdata.?).* = device;
} | examples/triangle/main.zig |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.