code
stringlengths 38
801k
| repo_path
stringlengths 6
263
|
|---|---|
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const fs = std.fs;
const math = std.math;
const draw = @import("pixel_draw.zig");
usingnamespace draw.vector_math;
const Texture = draw.Texture;
const voxel = @import("voxel.zig");
// ========== Global Variables =============
var main_allocator: *Allocator = undefined;
var font: draw.BitmapFont = undefined;
var potato: Texture = undefined;
var cube_mesh: draw.Mesh = undefined;
var test_chunk: voxel.Chunk = undefined;
// =========================================
pub fn main() anyerror!void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
//defer _ = gpa.deinit(); // NOTE(Samuel): Dont want leak test
main_allocator = &gpa.allocator;
try draw.init(&gpa.allocator, 1280, 720, start, update);
end();
}
fn start() void {
voxel.initBlockList(main_allocator) catch @panic("Unable to init block list");
test_chunk = voxel.Chunk.init();
font = .{
.texture = draw.textureFromTgaData(main_allocator, @embedFile("../assets/font.tga")) catch unreachable,
.font_size_x = 12,
.font_size_y = 16,
.character_spacing = 11,
};
potato = draw.textureFromTgaData(main_allocator, @embedFile("../assets/potato.tga")) catch unreachable;
cube_mesh = draw.cubeMesh(main_allocator);
cube_mesh.texture = potato;
}
fn end() void {
// NOTE(Samuel): Let the OS handle this
//main_allocator.free(font.texture.raw);
//main_allocator.free(potato.raw);
//main_allocator.free(cube_mesh.v);
//main_allocator.free(cube_mesh.i);
}
var cam: draw.Camera3D = .{ .pos = .{ .z = 20.0 }, .far = 100000 };
var mov_speed: f32 = 2.0;
fn update(delta: f32) void {
if (draw.keyPressed(.up)) cam.rotation.x += delta * 2;
if (draw.keyPressed(.down)) cam.rotation.x -= delta * 2;
if (draw.keyPressed(.right)) cam.rotation.y += delta * 2;
if (draw.keyPressed(.left)) cam.rotation.y -= delta * 2;
if (draw.keyPressed(._1)) cam.pos.y += delta * mov_speed;
if (draw.keyPressed(._2)) cam.pos.y -= delta * mov_speed;
if (draw.keyDown(._0)) mov_speed += 2.0;
if (draw.keyDown(._9)) mov_speed -= 2.0;
var camera_forward = eulerAnglesToDirVector(cam.rotation);
camera_forward.y = 0;
var camera_right = eulerAnglesToDirVector(Vec3.c(cam.rotation.x, cam.rotation.y - 3.1415926535 * 0.5, cam.rotation.z));
camera_right.y = 0;
const input_z = draw.keyStrengh(.s) - draw.keyStrengh(.w);
const input_x = draw.keyStrengh(.d) - draw.keyStrengh(.a);
camera_forward = Vec3_mul_F(camera_forward, input_z);
camera_right = Vec3_mul_F(camera_right, input_x);
var camera_delta_p = Vec3_add(camera_forward, camera_right);
camera_delta_p = Vec3_normalize(camera_delta_p);
camera_delta_p = Vec3_mul_F(camera_delta_p, delta * mov_speed);
cam.pos = Vec3_add(camera_delta_p, cam.pos);
draw.gb.fillScreenWithRGBColor(50, 50, 200);
{
for (test_chunk.block_data) |*it, i| {
if (it.* != 0) {
var x: u32 = 0;
var y: u32 = 0;
var z: u32 = 0;
voxel.Chunk.posFromI(i, &x, &y, &z);
const transform = Transform{
.position = .{
.x = @intToFloat(f32, x),
.y = @intToFloat(f32, y),
.z = @intToFloat(f32, z),
},
};
draw.gb.drawMesh(cube_mesh, .Texture, cam, transform);
}
}
}
draw.gb.drawBitmapFontFmt("{d:0.4}/{d:0.4}/{d}", .{ 1 / delta, delta, mov_speed }, 20, 20, 1, 1, font);
draw.gb.drawBitmapFont(draw.char_input_buffer[0..draw.char_input_len], 20, 40, 1, 1, font);
}
|
src/main.zig
|
const c = @import("c.zig");
const std = @import("std");
const zigimg = @import("zigimg");
const Allocator = std.mem.Allocator;
pub fn sdlTextureFromImage(renderer: * c.SDL_Renderer, image : zigimg.image.Image) ! *c.SDL_Texture {
const pxinfo = try PixelInfo.from(image);
// if I don't do the trick with breaking inside the switch,
// then it says, the return value of the switch is ignored,
// which seems strange to me...
// TODO: ask about this on the discord...
const data : *c_void = blk: {if (image.pixels) |storage| {
switch(storage) {
.Argb32 => |argb32| break :blk @ptrCast(*c_void,argb32.ptr),
.Rgb24 => |rgb24| break :blk @ptrCast(*c_void,rgb24.ptr),
else => return error.InvalidColorStorage,
}
} else {
return error.EmptyColorStorage;
}};
const surface = c.SDL_CreateRGBSurfaceFrom(
data,
@intCast(c_int,image.width),
@intCast(c_int,image.height),
pxinfo.bits,
pxinfo.pitch,
pxinfo.pixelmask.red,
pxinfo.pixelmask.green,
pxinfo.pixelmask.blue,
pxinfo.pixelmask.alpha);
if(surface == null) {
return error.CreateRgbSurface;
}
defer c.SDL_FreeSurface(surface);
var texture = c.SDL_CreateTextureFromSurface(renderer,surface);
if (texture) |non_null_texture| {
return non_null_texture;
} else {
return error.CreateTexture;
}
}
/// a helper structure that contains some info about the pixel layout
const PixelInfo = struct {
/// bits per pixel
bits : c_int,
/// the pitch (see SDL docs, this is the width of the image times the size per pixel in byte)
pitch : c_int,
/// the pixelmask for the (A)RGB storage
pixelmask : PixelMask,
const Self = @This();
pub fn from(image : zigimg.image.Image) !Self {
const Sizes = struct {bits : c_int, pitch : c_int};
const sizes : Sizes = switch( image.pixels orelse return error.EmptyColorStorage) {
.Argb32 => Sizes{.bits = 32, .pitch= 4*@intCast(c_int,image.width)},
.Rgb24 => Sizes{.bits = 24, .pitch = 3*@intCast(c_int,image.width)},
else => return error.InvalidColorStorage,
};
return Self {
.bits = @intCast(c_int,sizes.bits),
.pitch = @intCast(c_int,sizes.pitch),
.pixelmask = try PixelMask.fromColorStorage(image.pixels orelse return error.EmptyColorStorage)
};
}
};
// helper structure for getting the pixelmasks out of an image
const PixelMask = struct {
red : u32,
green : u32,
blue : u32,
alpha : u32,
const Self = @This();
/// construct a pixelmask given the colorstorage.
/// *Attention*: right now only works for 24bit RGB and 32bit ARGB storage.
pub fn fromColorStorage(storage : zigimg.color.ColorStorage) !Self {
switch(storage) {
.Argb32 => return Self {
.red = 0x00ff0000,
.green = 0x0000ff00,
.blue = 0x000000ff,
.alpha = 0xff000000,
},
.Rgb24 => return Self {
.red = 0xff0000,
.green = 0x00ff00,
.blue = 0x0000ff,
.alpha = 0,
},
else => return error.InvalidColorStorage,
}
}
};
/// try to read all files in a directory as images and return the list of images
/// if one file cannot be read by zigimg, the function returns an error
pub fn openImagesFromDirectoryRelPath(allocator : *std.mem.Allocator, dir_path : [] const u8) ! []zigimg.image.Image {
var array_list = std.ArrayList(zigimg.image.Image).init(allocator);
defer array_list.deinit();
const dir = try std.fs.cwd().openDir(dir_path, .{.iterate = true});
var iter = dir.iterate();
while (try iter.next()) |entry| {
if (entry.kind == .File) {
var file = try dir.openFile(entry.name,.{});
try array_list.append(try zigimg.image.Image.fromFile(allocator,&file));
}
}
return array_list.toOwnedSlice();
}
/// transform a slice of images into textures
pub fn sdlTexturesFromImagesAlloc(allocator : * std.mem.Allocator, renderer : * c.SDL_Renderer, images : []zigimg.Image) ! []*c.SDL_Texture{
var array_list = try std.ArrayList(*c.SDL_Texture).initCapacity(allocator,images.len);
for (images) |image| {
try array_list.append(try sdlTextureFromImage(renderer,image));
}
return array_list.toOwnedSlice();
}
|
src/utils.zig
|
pub const Os = enum {
freestanding,
ananas,
cloudabi,
darwin,
dragonfly,
freebsd,
fuchsia,
ios,
kfreebsd,
linux,
lv2,
macosx,
netbsd,
openbsd,
solaris,
windows,
haiku,
minix,
rtems,
nacl,
cnk,
bitrig,
aix,
cuda,
nvcl,
amdhsa,
ps4,
elfiamcu,
tvos,
watchos,
mesa3d,
contiki,
};
pub const Arch = enum {
armv8_2a,
armv8_1a,
armv8,
armv8r,
armv8m_baseline,
armv8m_mainline,
armv7,
armv7em,
armv7m,
armv7s,
armv7k,
armv7ve,
armv6,
armv6m,
armv6k,
armv6t2,
armv5,
armv5te,
armv4t,
armeb,
aarch64,
aarch64_be,
avr,
bpfel,
bpfeb,
hexagon,
mips,
mipsel,
mips64,
mips64el,
msp430,
nios2,
powerpc,
powerpc64,
powerpc64le,
r600,
amdgcn,
riscv32,
riscv64,
sparc,
sparcv9,
sparcel,
s390x,
tce,
tcele,
thumb,
thumbeb,
i386,
x86_64,
xcore,
nvptx,
nvptx64,
le32,
le64,
amdil,
amdil64,
hsail,
hsail64,
spir,
spir64,
kalimbav3,
kalimbav4,
kalimbav5,
shave,
lanai,
wasm32,
wasm64,
renderscript32,
renderscript64,
};
pub const Environ = enum {
unknown,
gnu,
gnuabi64,
gnueabi,
gnueabihf,
gnux32,
code16,
eabi,
eabihf,
android,
musl,
musleabi,
musleabihf,
msvc,
itanium,
cygnus,
amdopencl,
coreclr,
opencl,
};
pub const ObjectFormat = enum {
unknown,
coff,
elf,
macho,
wasm,
};
pub const GlobalLinkage = enum {
Internal,
Strong,
Weak,
LinkOnce,
};
pub const AtomicOrder = enum {
Unordered,
Monotonic,
Acquire,
Release,
AcqRel,
SeqCst,
};
pub const Mode = enum {
Debug,
ReleaseSafe,
ReleaseFast,
};
pub const TypeId = enum {
Type,
Void,
Bool,
NoReturn,
Int,
Float,
Pointer,
Array,
Struct,
FloatLiteral,
IntLiteral,
UndefinedLiteral,
NullLiteral,
Nullable,
ErrorUnion,
Error,
Enum,
EnumTag,
Union,
Fn,
Namespace,
Block,
BoundFn,
ArgTuple,
Opaque,
};
pub const FloatMode = enum {
Optimized,
Strict,
};
pub const is_big_endian = false;
pub const is_test = false;
pub const os = Os.linux;
pub const arch = Arch.x86_64;
pub const environ = Environ.gnu;
pub const object_format = ObjectFormat.elf;
pub const mode = Mode.Debug;
pub const link_libc = false;
pub const __zig_test_fn_slice = {}; // overwritten later
|
parser/zig-cache/builtin.zig
|
const Module = @This();
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const ZigDecl = @import("../../Module.zig").Decl;
const spec = @import("spec.zig");
const Word = spec.Word;
const IdRef = spec.IdRef;
const IdResult = spec.IdResult;
const IdResultType = spec.IdResultType;
const Section = @import("Section.zig");
const Type = @import("type.zig").Type;
const TypeCache = std.ArrayHashMapUnmanaged(Type, IdResultType, Type.ShallowHashContext32, true);
/// A general-purpose allocator which may be used to allocate resources for this module
gpa: Allocator,
/// An arena allocator used to store things that have the same lifetime as this module.
arena: Allocator,
/// Module layout, according to SPIR-V Spec section 2.4, "Logical Layout of a Module".
sections: struct {
/// Capability instructions
capabilities: Section = .{},
/// OpExtension instructions
extensions: Section = .{},
// OpExtInstImport instructions - skip for now.
// memory model defined by target, not required here.
/// OpEntryPoint instructions.
entry_points: Section = .{},
// OpExecutionMode and OpExecutionModeId instructions - skip for now.
/// OpString, OpSourcExtension, OpSource, OpSourceContinued.
debug_strings: Section = .{},
// OpName, OpMemberName - skip for now.
// OpModuleProcessed - skip for now.
/// Annotation instructions (OpDecorate etc).
annotations: Section = .{},
/// Type declarations, constants, global variables
/// Below this section, OpLine and OpNoLine is allowed.
types_globals_constants: Section = .{},
// Functions without a body - skip for now.
/// Regular function definitions.
functions: Section = .{},
} = .{},
/// SPIR-V instructions return result-ids. This variable holds the module-wide counter for these.
next_result_id: Word,
/// Cache for results of OpString instructions for module file names fed to OpSource.
/// Since OpString is pretty much only used for those, we don't need to keep track of all strings,
/// just the ones for OpLine. Note that OpLine needs the result of OpString, and not that of OpSource.
source_file_names: std.StringHashMapUnmanaged(IdRef) = .{},
/// SPIR-V type cache. Note that according to SPIR-V spec section 2.8, Types and Variables, non-pointer
/// non-aggrerate types (which includes matrices and vectors) must have a _unique_ representation in
/// the final binary.
/// Note: Uses ArrayHashMap which is insertion ordered, so that we may refer to other types by index (Type.Ref).
type_cache: TypeCache = .{},
pub fn init(gpa: Allocator, arena: Allocator) Module {
return .{
.gpa = gpa,
.arena = arena,
.next_result_id = 1, // 0 is an invalid SPIR-V result id, so start counting at 1.
};
}
pub fn deinit(self: *Module) void {
self.sections.capabilities.deinit(self.gpa);
self.sections.extensions.deinit(self.gpa);
self.sections.entry_points.deinit(self.gpa);
self.sections.debug_strings.deinit(self.gpa);
self.sections.annotations.deinit(self.gpa);
self.sections.types_globals_constants.deinit(self.gpa);
self.sections.functions.deinit(self.gpa);
self.source_file_names.deinit(self.gpa);
self.type_cache.deinit(self.gpa);
self.* = undefined;
}
pub fn allocId(self: *Module) spec.IdResult {
defer self.next_result_id += 1;
return .{ .id = self.next_result_id };
}
pub fn idBound(self: Module) Word {
return self.next_result_id;
}
/// Emit this module as a spir-v binary.
pub fn flush(self: Module, file: std.fs.File) !void {
// See SPIR-V Spec section 2.3, "Physical Layout of a SPIR-V Module and Instruction"
const header = [_]Word{
spec.magic_number,
(spec.version.major << 16) | (spec.version.minor << 8),
0, // TODO: Register Zig compiler magic number.
self.idBound(),
0, // Schema (currently reserved for future use)
};
// Note: needs to be kept in order according to section 2.3!
const buffers = &[_][]const Word{
&header,
self.sections.capabilities.toWords(),
self.sections.extensions.toWords(),
self.sections.entry_points.toWords(),
self.sections.debug_strings.toWords(),
self.sections.annotations.toWords(),
self.sections.types_globals_constants.toWords(),
self.sections.functions.toWords(),
};
var iovc_buffers: [buffers.len]std.os.iovec_const = undefined;
var file_size: u64 = 0;
for (iovc_buffers) |*iovc, i| {
// Note, since spir-v supports both little and big endian we can ignore byte order here and
// just treat the words as a sequence of bytes.
const bytes = std.mem.sliceAsBytes(buffers[i]);
iovc.* = .{ .iov_base = bytes.ptr, .iov_len = bytes.len };
file_size += bytes.len;
}
try file.seekTo(0);
try file.setEndPos(file_size);
try file.pwritevAll(&iovc_buffers, 0);
}
/// Fetch the result-id of an OpString instruction that encodes the path of the source
/// file of the decl. This function may also emit an OpSource with source-level information regarding
/// the decl.
pub fn resolveSourceFileName(self: *Module, decl: *ZigDecl) !IdRef {
const path = decl.getFileScope().sub_file_path;
const result = try self.source_file_names.getOrPut(self.gpa, path);
if (!result.found_existing) {
const file_result_id = self.allocId();
result.value_ptr.* = file_result_id.toRef();
try self.sections.debug_strings.emit(self.gpa, .OpString, .{
.id_result = file_result_id,
.string = path,
});
try self.sections.debug_strings.emit(self.gpa, .OpSource, .{
.source_language = .Unknown, // TODO: Register Zig source language.
.version = 0, // TODO: Zig version as u32?
.file = file_result_id.toRef(),
.source = null, // TODO: Store actual source also?
});
}
return result.value_ptr.*;
}
/// Fetch a result-id for a spir-v type. This function deduplicates the type as appropriate,
/// and returns a cached version if that exists.
/// Note: This function does not attempt to perform any validation on the type.
/// The type is emitted in a shallow fashion; any child types should already
/// be emitted at this point.
pub fn resolveType(self: *Module, ty: Type) !Type.Ref {
const result = try self.type_cache.getOrPut(self.gpa, ty);
if (!result.found_existing) {
result.value_ptr.* = try self.emitType(ty);
}
return result.index;
}
pub fn resolveTypeId(self: *Module, ty: Type) !IdRef {
return self.typeResultId(try self.resolveType(ty));
}
/// Get the result-id of a particular type, by reference. Asserts type_ref is valid.
pub fn typeResultId(self: Module, type_ref: Type.Ref) IdResultType {
return self.type_cache.values()[type_ref];
}
/// Get the result-id of a particular type as IdRef, by Type.Ref. Asserts type_ref is valid.
pub fn typeRefId(self: Module, type_ref: Type.Ref) IdRef {
return self.type_cache.values()[type_ref].toRef();
}
/// Unconditionally emit a spir-v type into the appropriate section.
/// Note: If this function is called with a type that is already generated, it may yield an invalid module
/// as non-pointer non-aggregrate types must me unique!
/// Note: This function does not attempt to perform any validation on the type.
/// The type is emitted in a shallow fashion; any child types should already
/// be emitted at this point.
pub fn emitType(self: *Module, ty: Type) !IdResultType {
const result_id = self.allocId();
const ref_id = result_id.toRef();
const types = &self.sections.types_globals_constants;
const annotations = &self.sections.annotations;
const result_id_operand = .{ .id_result = result_id };
switch (ty.tag()) {
.void => try types.emit(self.gpa, .OpTypeVoid, result_id_operand),
.bool => try types.emit(self.gpa, .OpTypeBool, result_id_operand),
.int => try types.emit(self.gpa, .OpTypeInt, .{
.id_result = result_id,
.width = ty.payload(.int).width,
.signedness = switch (ty.payload(.int).signedness) {
.unsigned => @as(spec.LiteralInteger, 0),
.signed => 1,
},
}),
.float => try types.emit(self.gpa, .OpTypeFloat, .{
.id_result = result_id,
.width = ty.payload(.float).width,
}),
.vector => try types.emit(self.gpa, .OpTypeVector, .{
.id_result = result_id,
.component_type = self.typeResultId(ty.childType()).toRef(),
.component_count = ty.payload(.vector).component_count,
}),
.matrix => try types.emit(self.gpa, .OpTypeMatrix, .{
.id_result = result_id,
.column_type = self.typeResultId(ty.childType()).toRef(),
.column_count = ty.payload(.matrix).column_count,
}),
.image => {
const info = ty.payload(.image);
try types.emit(self.gpa, .OpTypeImage, .{
.id_result = result_id,
.sampled_type = self.typeResultId(ty.childType()).toRef(),
.dim = info.dim,
.depth = @enumToInt(info.depth),
.arrayed = @boolToInt(info.arrayed),
.ms = @boolToInt(info.multisampled),
.sampled = @enumToInt(info.sampled),
.image_format = info.format,
.access_qualifier = info.access_qualifier,
});
},
.sampler => try types.emit(self.gpa, .OpTypeSampler, result_id_operand),
.sampled_image => try types.emit(self.gpa, .OpTypeSampledImage, .{
.id_result = result_id,
.image_type = self.typeResultId(ty.childType()).toRef(),
}),
.array => {
const info = ty.payload(.array);
assert(info.length != 0);
try types.emit(self.gpa, .OpTypeArray, .{
.id_result = result_id,
.element_type = self.typeResultId(ty.childType()).toRef(),
.length = .{ .id = 0 }, // TODO: info.length must be emitted as constant!
});
if (info.array_stride != 0) {
try annotations.decorate(self.gpa, ref_id, .{ .ArrayStride = .{ .array_stride = info.array_stride } });
}
},
.runtime_array => {
const info = ty.payload(.runtime_array);
try types.emit(self.gpa, .OpTypeRuntimeArray, .{
.id_result = result_id,
.element_type = self.typeResultId(ty.childType()).toRef(),
});
if (info.array_stride != 0) {
try annotations.decorate(self.gpa, ref_id, .{ .ArrayStride = .{ .array_stride = info.array_stride } });
}
},
.@"struct" => {
const info = ty.payload(.@"struct");
try types.emitRaw(self.gpa, .OpTypeStruct, 1 + info.members.len);
types.writeOperand(IdResult, result_id);
for (info.members) |member| {
types.writeOperand(IdRef, self.typeResultId(member.ty).toRef());
}
try self.decorateStruct(ref_id, info);
},
.@"opaque" => try types.emit(self.gpa, .OpTypeOpaque, .{
.id_result = result_id,
.literal_string = ty.payload(.@"opaque").name,
}),
.pointer => {
const info = ty.payload(.pointer);
try types.emit(self.gpa, .OpTypePointer, .{
.id_result = result_id,
.storage_class = info.storage_class,
.type = self.typeResultId(ty.childType()).toRef(),
});
if (info.array_stride != 0) {
try annotations.decorate(self.gpa, ref_id, .{ .ArrayStride = .{ .array_stride = info.array_stride } });
}
if (info.alignment) |alignment| {
try annotations.decorate(self.gpa, ref_id, .{ .Alignment = .{ .alignment = alignment } });
}
if (info.max_byte_offset) |max_byte_offset| {
try annotations.decorate(self.gpa, ref_id, .{ .MaxByteOffset = .{ .max_byte_offset = max_byte_offset } });
}
},
.function => {
const info = ty.payload(.function);
try types.emitRaw(self.gpa, .OpTypeFunction, 2 + info.parameters.len);
types.writeOperand(IdResult, result_id);
types.writeOperand(IdRef, self.typeResultId(info.return_type).toRef());
for (info.parameters) |parameter_type| {
types.writeOperand(IdRef, self.typeResultId(parameter_type).toRef());
}
},
.event => try types.emit(self.gpa, .OpTypeEvent, result_id_operand),
.device_event => try types.emit(self.gpa, .OpTypeDeviceEvent, result_id_operand),
.reserve_id => try types.emit(self.gpa, .OpTypeReserveId, result_id_operand),
.queue => try types.emit(self.gpa, .OpTypeQueue, result_id_operand),
.pipe => try types.emit(self.gpa, .OpTypePipe, .{
.id_result = result_id,
.qualifier = ty.payload(.pipe).qualifier,
}),
.pipe_storage => try types.emit(self.gpa, .OpTypePipeStorage, result_id_operand),
.named_barrier => try types.emit(self.gpa, .OpTypeNamedBarrier, result_id_operand),
}
return result_id.toResultType();
}
fn decorateStruct(self: *Module, target: IdRef, info: *const Type.Payload.Struct) !void {
const annotations = &self.sections.annotations;
// Decorations for the struct type itself.
if (info.decorations.block)
try annotations.decorate(self.gpa, target, .Block);
if (info.decorations.buffer_block)
try annotations.decorate(self.gpa, target, .BufferBlock);
if (info.decorations.glsl_shared)
try annotations.decorate(self.gpa, target, .GLSLShared);
if (info.decorations.glsl_packed)
try annotations.decorate(self.gpa, target, .GLSLPacked);
if (info.decorations.c_packed)
try annotations.decorate(self.gpa, target, .CPacked);
// Decorations for the struct members.
const extra = info.member_decoration_extra;
var extra_i: u32 = 0;
for (info.members) |member, i| {
const d = member.decorations;
const index = @intCast(Word, i);
switch (d.matrix_layout) {
.row_major => try annotations.decorateMember(self.gpa, target, index, .RowMajor),
.col_major => try annotations.decorateMember(self.gpa, target, index, .ColMajor),
.none => {},
}
if (d.matrix_layout != .none) {
try annotations.decorateMember(self.gpa, target, index, .{
.MatrixStride = .{ .matrix_stride = extra[extra_i] },
});
extra_i += 1;
}
if (d.no_perspective)
try annotations.decorateMember(self.gpa, target, index, .NoPerspective);
if (d.flat)
try annotations.decorateMember(self.gpa, target, index, .Flat);
if (d.patch)
try annotations.decorateMember(self.gpa, target, index, .Patch);
if (d.centroid)
try annotations.decorateMember(self.gpa, target, index, .Centroid);
if (d.sample)
try annotations.decorateMember(self.gpa, target, index, .Sample);
if (d.invariant)
try annotations.decorateMember(self.gpa, target, index, .Invariant);
if (d.@"volatile")
try annotations.decorateMember(self.gpa, target, index, .Volatile);
if (d.coherent)
try annotations.decorateMember(self.gpa, target, index, .Coherent);
if (d.non_writable)
try annotations.decorateMember(self.gpa, target, index, .NonWritable);
if (d.non_readable)
try annotations.decorateMember(self.gpa, target, index, .NonReadable);
if (d.builtin) {
try annotations.decorateMember(self.gpa, target, index, .{
.BuiltIn = .{ .built_in = @intToEnum(spec.BuiltIn, extra[extra_i]) },
});
extra_i += 1;
}
if (d.stream) {
try annotations.decorateMember(self.gpa, target, index, .{
.Stream = .{ .stream_number = extra[extra_i] },
});
extra_i += 1;
}
if (d.location) {
try annotations.decorateMember(self.gpa, target, index, .{
.Location = .{ .location = extra[extra_i] },
});
extra_i += 1;
}
if (d.component) {
try annotations.decorateMember(self.gpa, target, index, .{
.Component = .{ .component = extra[extra_i] },
});
extra_i += 1;
}
if (d.xfb_buffer) {
try annotations.decorateMember(self.gpa, target, index, .{
.XfbBuffer = .{ .xfb_buffer_number = extra[extra_i] },
});
extra_i += 1;
}
if (d.xfb_stride) {
try annotations.decorateMember(self.gpa, target, index, .{
.XfbStride = .{ .xfb_stride = extra[extra_i] },
});
extra_i += 1;
}
if (d.user_semantic) {
const len = extra[extra_i];
extra_i += 1;
const semantic = @ptrCast([*]const u8, &extra[extra_i])[0..len];
try annotations.decorateMember(self.gpa, target, index, .{
.UserSemantic = .{ .semantic = semantic },
});
extra_i += std.math.divCeil(u32, extra_i, @sizeOf(u32)) catch unreachable;
}
}
}
|
src/codegen/spirv/Module.zig
|
const windows = @import("std").os.windows;
pub const WAVE_FORMAT_PCM = 0x01;
pub const WHDR_INQUEUE = 0x10;
pub const WAVE_MAPPER = 0xffffffff;
pub const CALLBACK_NULL = 0x0;
pub const UINT_PTR = usize;
pub const MMError = error {
Error,
BadDeviceID,
Allocated,
InvalidHandle,
NoDriver,
NoMem,
BadFormat,
StillPlaying,
Unprepared,
Sync,
};
pub const MMRESULT = extern enum(u32) {
MMSYSERR_NOERROR = 0,
MMSYSERR_ERROR = 1,
MMSYSERR_BADDEVICEID = 2,
MMSYSERR_ALLOCATED = 4,
MMSYSERR_INVALIDHANDLE = 5,
MMSYSERR_NODRIVER = 6,
MMSYSERR_NOMEM = 7,
WAVERR_BADFORMAT = 32,
WAVERR_STILLPLAYING = 33,
WAVERR_UNPREPARED = 34,
WAVERR_SYNC = 35,
pub fn toError(self: MMRESULT) MMError!void {
return switch (self) {
MMRESULT.MMSYSERR_NOERROR => {},
MMRESULT.MMSYSERR_ERROR => MMError.Error,
MMRESULT.MMSYSERR_BADDEVICEID => MMError.BadDeviceID,
MMRESULT.MMSYSERR_ALLOCATED => MMError.Allocated,
MMRESULT.MMSYSERR_INVALIDHANDLE => MMError.InvalidHandle,
MMRESULT.MMSYSERR_NODRIVER => MMError.NoDriver,
MMRESULT.MMSYSERR_NOMEM => MMError.NoMem,
MMRESULT.WAVERR_BADFORMAT => MMError.BadFormat,
MMRESULT.WAVERR_STILLPLAYING => MMError.StillPlaying,
MMRESULT.WAVERR_UNPREPARED => MMError.Unprepared,
MMRESULT.WAVERR_SYNC => MMError.Sync,
};
}
};
pub const WaveHdr = extern struct {
lpData: windows.LPSTR,
dwBufferLength: windows.DWORD,
dwBytesRecorded: windows.DWORD,
dwUser: windows.DWORD_PTR,
dwFlags: windows.DWORD,
dwLoops: windows.DWORD,
lpNext: ?*WaveHdr,
reserved: windows.DWORD_PTR,
};
pub const WaveFormatEx = extern struct {
wFormatTag: windows.WORD,
nChannels: windows.WORD,
nSamplesPerSec: windows.DWORD,
nAvgBytesPerSec: windows.DWORD,
nBlockAlign: windows.WORD,
wBitsPerSample: windows.WORD,
cbSize: windows.WORD,
};
pub extern "winmm" stdcallcc fn waveOutOpen(phwo: *windows.HANDLE, uDeviceID: UINT_PTR,
pwfx: *const WaveFormatEx, dwCallback: windows.DWORD_PTR,
dwCallbackInstance: windows.DWORD_PTR, fdwOpen: windows.DWORD) MMRESULT;
pub extern "winmm" stdcallcc fn waveOutClose(hwo: windows.HANDLE) MMRESULT;
pub extern "winmm" stdcallcc fn waveOutPrepareHeader(hwo: windows.HANDLE, pwh: *WaveHdr, cbwh: windows.UINT) MMRESULT;
pub extern "winmm" stdcallcc fn waveOutUnprepareHeader(hwo: windows.HANDLE, pwh: *WaveHdr, cbwh: windows.UINT) MMRESULT;
pub extern "winmm" stdcallcc fn waveOutWrite(hwo: windows.HANDLE, pwh: *WaveHdr, cbwh: windows.UINT) MMRESULT;
|
src/windows/winnm.zig
|
const std = @import("std");
const testing = std.testing;
/// All subfunctions have to be run as `comptime` or in `comptime` blocks.
pub fn ComptimeArrayList(comptime T: type) type {
return struct {
const Self = @This();
items: []T,
pub fn init() Self {
comptime var initial = [_]T{};
return Self{
.items = &initial
};
}
pub fn append(self: *Self, comptime item: T) void {
var new_items: [self.items.len + 1]T = undefined;
std.mem.copy(T, &new_items, self.items);
new_items[self.items.len] = item;
self.items = &new_items;
}
pub fn appendSlice(self: *Self, comptime items: []T) void {
var new_items: [self.items.len + items.len]T = undefined;
std.mem.copy(T, &new_items, self.items);
var i: usize = 0;
while (i < items.len) : (i += 1)
new_items[self.items.len + i] = items[i];
self.items = &new_items;
}
pub fn deinit(self: *Self) void {
var new_items: [0]T = undefined;
self.items = &new_items;
}
pub fn toOwnedSlice(self: *Self) []T {
defer self.deinit();
return self.items;
}
pub fn orderedRemove(self: *Self, comptime index: usize) void {
var new_items: [self.items.len - 1]T = undefined;
var i: usize = 0;
while (i < self.items.len) : (i += 1) {
if (i == index) {
continue;
} else if (i > index) {
new_items[i - 1] = self.items[i];
} else {
new_items[i] = self.items[i];
}
}
self.items = &new_items;
}
/// Adjusts the list's length to `new_len`.
/// On "upsizing", elements that were previously "downsized" and left
/// out of the resize will become undefined
pub fn resize(self: *Self, comptime new_len: usize) void {
if (new_len > self.items.len) {
var new_items: [new_len]T = undefined;
std.mem.copy(u8, &new_items, self.items);
self.items = &new_items;
} else {
self.items.len = new_len;
}
}
/// Shrinks the list's length to `new_len`.
/// This will make elements "left out" of the resize "disappear".
pub fn shrink(self: *Self, comptime new_len: usize) void {
std.debug.assert(new_len <= self.items.len);
var new_items: [new_len]T = undefined;
var i: usize = 0;
while (i < new_len) : (i += 1) {
new_items[i] = self.items[i];
}
self.items = &new_items;
}
/// Caller must free memory.
pub fn toRuntime(self: *Self, allocator: *std.mem.Allocator) !std.ArrayList(T) {
var arr = std.ArrayList(T).init(allocator);
try arr.appendSlice(self.items);
return arr;
}
};
}
test "ComptimeArrayList.append / ComptimeArrayList.appendSlice" {
comptime {
var list = ComptimeArrayList(u8).init();
list.append('a');
list.append('b');
var arr = [_]u8{'c', 'd'};
list.appendSlice(&arr);
var expected = [_]u8{'a', 'b', 'c', 'd'};
var expected_empty = [_]u8{};
std.testing.expectEqualSlices(u8, &expected, list.items);
std.testing.expectEqualSlices(u8, &expected, list.toOwnedSlice());
std.testing.expectEqual(list.items.len, 0);
std.testing.expectEqualSlices(u8, &expected_empty, list.items);
}
}
test "ComptimeArrayList.remove" {
comptime {
var list = ComptimeArrayList(u8).init();
list.append('a');
list.append('b');
list.append('c');
list.append('d');
list.append('e');
list.orderedRemove(1);
list.orderedRemove(3);
list.orderedRemove(1);
var expected = [_]u8{'a', 'd'};
std.testing.expectEqualSlices(u8, &expected, list.toOwnedSlice());
}
}
test "ComptimeArrayList.resize" {
comptime {
var list = ComptimeArrayList(u8).init();
list.append('a');
list.append('b');
list.append('c');
list.append('d');
list.resize(2);
std.testing.expectEqual(2, list.items.len);
}
}
test "ComptimeArrayList.shrink" {
comptime {
var list = ComptimeArrayList(u8).init();
list.append('a');
list.append('b');
list.append('c');
list.append('d');
list.shrink(2);
std.testing.expectEqual(2, list.items.len);
}
}
test "ComptimeArrayList.toRuntime" {
comptime var list = ComptimeArrayList(u8).init();
comptime {
list.append('a');
list.append('b');
list.append('c');
list.append('d');
}
var array_list = try list.toRuntime(std.testing.allocator);
defer array_list.deinit();
var expected = [_]u8{'a', 'b', 'c', 'd'};
std.testing.expectEqualSlices(u8, &expected, array_list.items);
}
|
src/comptime_array_list.zig
|
const is_linux = comptime std.Target.current.os.tag == .linux;
pub const io_mode = .evented;
var server: network.Socket = undefined;
pub fn main() !void {
print("http server...\n", .{});
// var aa = std.heap.ArenaAllocator.init(std.heap.page_allocator);
// defer aa.deinit();
// var allocator = &aa.allocator;
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var allocator = &gpa.allocator;
defer if (gpa.deinit()) std.os.exit(1);
if (is_linux) {
const actionSigint = std.os.Sigaction{
.sigaction = handleSigintLinux,
.mask = std.os.empty_sigset,
.flags = 0,
};
std.os.sigaction(std.os.SIGINT, &actionSigint, null);
}
const args = try std.process.argsAlloc(allocator);
defer std.process.argsFree(allocator, args);
var port: u16 = 8080;
var lastFlag: []const u8 = undefined;
for (args) |arg, index| {
if (startsWith(u8, arg, "-")) {
lastFlag = arg;
} else if (eql(u8, lastFlag, "--port")) {
port = try std.fmt.parseUnsigned(u16, arg, 10);
}
}
print(" port={}\n", .{port});
try network.init();
defer network.deinit();
server = try network.Socket.create(.ipv4, .tcp);
defer server.close();
try server.bind(.{
.address = .{ .ipv4 = network.Address.IPv4.any },
.port = port,
});
try server.listen();
print("listening on {}\n", .{try server.getLocalEndPoint()});
while (true) {
print("waiting for connection...\n", .{});
const socket = try server.accept();
const client = try allocator.create(Client);
client.* = Client{
.allocator = allocator,
.socket = socket,
.handle_frame = async client.handle(),
};
}
}
fn handleSigintLinux(sig: i32, info: *const std.os.siginfo_t, ctx_ptr: ?*const c_void) callconv(.C) void {
print("\nhandleSigintLinux!\n", .{});
server.close();
std.os.exit(0);
}
const Client = struct {
allocator: *Allocator,
socket: network.Socket,
handle_frame: @Frame(Client.handle),
fn handle(self: *Client) !void {
var list = std.ArrayList(u8).init(self.allocator);
defer list.deinit();
while (true) {
const bufferSize: u32 = 1024;
var buffer: [bufferSize]u8 = undefined;
// this is a blocking read...
// when count is less than buffer size (or 0) read is complete.
// FIXME: receive will never return 0 after a bufferSize read!!!
// FIXME: use curl http://127.0.0.1:8080 to get size of request and change bufferSize
const count = try self.socket.receive(&buffer);
// print("received: count={}\n", .{count});
try list.appendSlice(buffer[0..count]);
if (count < bufferSize) break;
}
const request = list.items[0..];
// print("request.len={}\n", .{request.len});
// print("request is {}\n", .{@typeName(@TypeOf(request))});
print("received...\n{}", .{request});
var buffer2: [256]u8 = undefined;
const path = try parsePath(&buffer2, request);
print("\npath={}\n", .{path});
var content: []const u8 = undefined;
var response: []const u8 = undefined;
if (eql(u8, path, "/favicon.ico")) {
content = try getFavicon(self.allocator);
response = try makeResponse(self.allocator, "200 OK", "image/png", content);
} else if (eql(u8, path, "/")) {
content = try get302Html(self.allocator);
response = try makeResponse(self.allocator, "302 FOUND", "text/html", content);
} else if (eql(u8, path, "/index.html")) {
content = try getIndexHtml(self.allocator);
response = try makeResponse(self.allocator, "200 OK", "text/html", content);
} else if (eql(u8, path, "/index.css")) {
content = try getIndexCss(self.allocator);
response = try makeResponse(self.allocator, "200 OK", "text/css", content);
} else {
content = try get404Html(self.allocator);
response = try makeResponse(self.allocator, "404 NOT FOUND", "text/html", content);
}
defer self.allocator.free(content);
defer self.allocator.free(response);
// print("\nsending...\n{}", .{response});
_ = try self.socket.send(response);
self.socket.close();
}
};
fn parsePath(buffer: []u8, request: []u8) ![]u8 {
const idx1 = std.mem.indexOfScalar(u8, request, ' ') orelse return error.Failure;
const idx2 = std.mem.indexOfScalarPos(u8, request, idx1 + 1, ' ') orelse return error.Failure;
// print("parsePath: idx1={}, idx2={}\n", .{ idx1, idx2 });
// std.mem.secureZero(u8, buffer);
std.mem.copy(u8, buffer, request[(idx1 + 1)..idx2]);
const path = buffer[0..(idx2 - (idx1 + 1))];
// print("parsePath: path={}\n", .{path});
return path;
}
fn makeResponse(allocator: *Allocator, code: []const u8, mimeType: []const u8, content: []const u8) ![]const u8 {
const aprint = std.fmt.allocPrint;
var ts = try timestamp.Timestamp.now();
const header1 = try aprint(allocator, "HTTP/1.1 {}", .{code});
defer allocator.free(header1);
// const header2 = try aprint(allocator, "Date: {}", .{std.time.milliTimestamp()});
var header2buf: [32]u8 = undefined;
const header2 = try aprint(allocator, "Date: {}", .{ts.asctime(header2buf[0..])});
defer allocator.free(header2);
const header3 = try aprint(allocator, "Content-Type: {}", .{mimeType});
defer allocator.free(header3);
const header4 = try aprint(allocator, "Content-Length: {}", .{content.len});
defer allocator.free(header4);
if (startsWith(u8, code, "302 ")) {
const header5 = try aprint(allocator, "Location: /index.html", .{});
defer allocator.free(header5);
const lines = &[_][]const u8{
header1,
"Server: zig/" ++ compiler.version(),
header2,
header3,
header4,
header5,
"Connection: close",
"",
content,
};
return try std.mem.join(allocator, "\r\n", lines);
} else {
const lines = &[_][]const u8{
header1,
"Server: zig/" ++ compiler.version(),
header2,
header3,
header4,
"Connection: close",
"",
content,
};
return try std.mem.join(allocator, "\r\n", lines);
}
}
fn get302Html(allocator: *Allocator) ![]const u8 {
const template =
\\<html>
\\<head>
\\ <title>302 Found</title>
\\</head>
\\<body bgcolor="white">
\\ <center><h1>302 Found</h1></center>
\\ <hr>
\\ <center>Zig/{}</center>
\\ <center><a href="/index.html">index.html</a></center>
\\</body>
\\</html>
; // end string
const html = std.fmt.allocPrint(allocator, template, .{compiler.version()});
return html;
}
fn get404Html(allocator: *Allocator) ![]const u8 {
const template =
\\<html>
\\<head>
\\ <title>404 Not Found</title>
\\</head>
\\<body bgcolor="white">
\\ <center><h1>404 Not Found</h1></center>
\\ <hr>
\\ <center>Zig/{}</center>
\\</body>
\\</html>
; // end string
const html = std.fmt.allocPrint(allocator, template, .{compiler.version()});
return html;
}
fn getFavicon(allocator: *Allocator) ![]const u8 {
const bytes = @embedFile("./web/dragon.png");
// @compileLog(bytes);
const content = try allocator.alloc(u8, bytes.len);
std.mem.copy(u8, content, bytes);
return content;
}
fn getIndexHtml(allocator: *Allocator) ![]const u8 {
const bytes = @embedFile("./web/index.html");
// @compileLog(bytes);
const content = try allocator.alloc(u8, bytes.len);
std.mem.copy(u8, content, bytes);
return content;
}
fn getIndexCss(allocator: *Allocator) ![]const u8 {
const bytes = @embedFile("./web/index.css");
// @compileLog(bytes);
const content = try allocator.alloc(u8, bytes.len);
std.mem.copy(u8, content, bytes);
return content;
}
// imports
const std = @import("std");
const print = std.debug.print;
const Allocator = std.mem.Allocator;
const eql = std.mem.eql;
const startsWith = std.mem.startsWith;
const network = @import("20200909_zig-network.zig");
const compiler = @import("version.zig");
const timestamp = @import("timestamp.zig");
|
98_http_server/example.zig
|
const std = @import("std");
pub const Quality = enum {
fast,
beautiful,
};
const Point = struct {
x: i32,
y: i32,
};
const Rectangle = struct {
/// inclusive left bound
left: i32,
/// inclusive upper bound
top: i32,
/// exlusive right bound
right: i32,
/// exlusive lower bound
bottom: i32,
};
pub fn Texture(comptime Pixel: type) type {
return struct {
const Self = @This();
allocator: *std.mem.Allocator,
pixels: []Pixel,
width: usize,
height: usize,
pub fn init(allocator: *std.mem.Allocator, width: usize, height: usize) !Self {
return Self{
.allocator = allocator,
.width = width,
.height = height,
.pixels = try allocator.alloc(Pixel, width * height),
};
}
pub fn deinit(self: Self) void {
self.allocator.free(self.pixels);
}
pub fn sample(tex: Self, u: f32, v: f32) Pixel {
const x = @rem(@floatToInt(usize, @floor(@intToFloat(f32, tex.width) * u)), tex.width);
const y = @rem(@floatToInt(usize, @floor(@intToFloat(f32, tex.height) * v)), tex.height);
return tex.pixels[x + tex.width * y];
}
pub fn getPixel(tex: Self, x: usize, y: usize) Pixel {
return tex.pixels[x + tex.width * y];
}
pub fn setPixel(tex: *Self, x: usize, y: usize, color: Pixel) void {
tex.pixels[x + tex.width * y] = color;
}
pub fn getPixelPtr(tex: *Self, x: usize, y: usize) *Pixel {
return &tex.pixels[x + tex.width * y];
}
pub fn fill(tex: *Self, color: Pixel) void {
for (tex.pixels) |*pix| {
pix.* = color;
}
}
};
}
pub fn Vertex(comptime PixelType: type) type {
return struct {
x: i32,
y: i32,
z: f32 = 0,
u: f32 = 0,
v: f32 = 0,
color: PixelType = 0,
};
}
pub fn Face(comptime PixelType: type) type {
return struct {
const Self = @This();
texture: *Texture(PixelType),
vertices: [3]Vertex(PixelType),
pub fn toPolygon(face: Self) [3]Point {
return [3]Point{
.{ .x = face.vertices[0].x, .y = face.vertices[0].y },
.{ .x = face.vertices[1].x, .y = face.vertices[1].y },
.{ .x = face.vertices[2].x, .y = face.vertices[2].y },
};
}
};
}
fn clamp(v: f32, min: f32, max: f32) f32 {
return std.math.min(max, std.math.max(min, v));
}
pub fn Context(comptime PixelType: type, quality: Quality, comptime numThreads: ?comptime_int) type {
return struct {
const Self = @This();
const DepthType = u32;
const ColorTexture = Texture(PixelType);
const DepthTexture = Texture(DepthType);
const RenderJob = struct {
context: *Self,
face: Face(PixelType),
};
colorTarget: ?*ColorTexture,
depthTarget: ?*DepthTexture,
renderSystem: RenderSystem,
targetWidth: usize,
targetHeight: usize,
pub fn init(context: *Self) !void {
context.* = .{
.colorTarget = null,
.depthTarget = null,
.renderSystem = undefined,
.targetWidth = 0,
.targetHeight = 0,
};
try RenderSystem.init(&context.renderSystem);
}
pub fn deinit(self: Self) void {
self.renderSystem.deinit();
}
pub fn setRenderTarget(self: *Self, colorTarget: ?*ColorTexture, depthTarget: ?*DepthTexture) error{SizeMismatch}!void {
if (colorTarget != null and depthTarget == null) {
if (colorTarget.?.width != depthTarget.?.width)
return error.SizeMismatch;
if (colorTarget.?.height != depthTarget.?.height)
return error.SizeMismatch;
}
if (colorTarget) |ct| {
self.targetWidth = ct.width;
self.targetHeight = ct.height;
}
if (depthTarget) |dt| {
self.targetWidth = dt.width;
self.targetHeight = dt.height;
}
self.colorTarget = colorTarget;
self.depthTarget = depthTarget;
}
pub fn beginFrame(self: *Self) void {
self.renderSystem.beginFrame();
}
pub fn renderPolygonTextured(self: *Self, face: Face(PixelType)) !void {
try self.renderSystem.renderPolygonTextured(.{
.context = self,
.face = face,
});
}
pub fn endFrame(self: *Self) void {
self.renderSystem.endFrame();
}
const RenderSystem = if (numThreads) |unwrapped_core_count|
struct {
const RS = @This();
const Queue = std.atomic.Queue(RenderJob);
const RenderWorker = struct {
queue: *Queue,
thread: *std.Thread,
shutdown: bool,
processedPolyCount: *usize,
};
plenty_of_memory: []u8,
queue: Queue = undefined,
processedPolyCount: usize,
expectedPolyCount: usize,
workers: [unwrapped_core_count]RenderWorker = undefined,
fixed_buffer_allocator: std.heap.ThreadSafeFixedBufferAllocator = undefined,
fn init(rs: *RS) !void {
rs.* = .{
.queue = Queue.init(),
.fixed_buffer_allocator = undefined,
.plenty_of_memory = undefined,
.processedPolyCount = 0,
.expectedPolyCount = 0,
};
rs.plenty_of_memory = try std.heap.page_allocator.alloc(u8, 8 * 1024 * 1024); // 16 MB polygon space
errdefer std.heap.page_allocator.free(rs.plenty_of_memory);
rs.fixed_buffer_allocator = std.heap.ThreadSafeFixedBufferAllocator.init(rs.plenty_of_memory);
for (rs.workers) |*loop_worker| {
loop_worker.* = RenderWorker{
.queue = &rs.queue,
.thread = undefined,
.shutdown = false,
.processedPolyCount = &rs.processedPolyCount,
};
loop_worker.thread = try std.Thread.spawn(loop_worker, struct {
fn doWork(worker: *RenderWorker) void {
while (!worker.shutdown) {
while (worker.queue.get()) |job| {
paintTriangle(.{
.left = 0,
.top = 0,
.right = @intCast(i32, job.data.context.targetWidth),
.bottom = @intCast(i32, job.data.context.targetHeight),
}, job.data.face.toPolygon(), job.data, paintTextured);
_ = @atomicRmw(usize, worker.processedPolyCount, .Add, 1, .SeqCst);
}
std.time.sleep(1);
}
}
}.doWork);
}
}
fn beginFrame(renderSystem: *RS) void {
@atomicStore(usize, &renderSystem.processedPolyCount, 0, .Release);
renderSystem.expectedPolyCount = 0;
@atomicStore(usize, &renderSystem.fixed_buffer_allocator.end_index, 0, .Release);
}
fn renderPolygonTextured(renderSystem: *RS, job: RenderJob) !void {
const node = try renderSystem.fixed_buffer_allocator.allocator.create(Queue.Node);
node.* = Queue.Node{
.prev = undefined,
.next = undefined,
.data = job,
};
renderSystem.queue.put(node);
renderSystem.expectedPolyCount += 1;
}
fn endFrame(renderSystem: RS) void {
while (@atomicLoad(usize, &renderSystem.processedPolyCount, .Acquire) != renderSystem.expectedPolyCount) {
std.time.sleep(1);
}
}
fn deinit(renderSystem: RS) void {
std.heap.page_allocator.free(renderSystem.plenty_of_memory);
}
}
else
struct {
const RS = @This();
fn init(rs: *RS) error{Dummy}!void {}
fn beginFrame(renderSystem: RS) void {}
fn renderPolygonTextured(renderSystem: RS, job: RenderJob) error{OutOfMemory}!void {
paintTriangle(.{
.left = 0,
.top = 0,
.right = @intCast(i32, job.context.targetWidth),
.bottom = @intCast(i32, job.context.targetHeight),
}, job.face.toPolygon(), job, paintTextured);
}
fn endFrame(renderSystem: RS) void {}
fn deinit(renderSystem: RS) void {}
};
pub fn paintTextured(x: i32, y: i32, job: RenderJob) void {
const p1 = &job.face.vertices[0];
const p2 = &job.face.vertices[1];
const p3 = &job.face.vertices[2];
// std.debug.warn("{} {}\n", .{ (p2.y - p3.y), (p1.x - p3.x) });
const divisor = (p2.y - p3.y) * (p1.x - p3.x) + (p3.x - p2.x) * (p1.y - p3.y);
if (divisor == 0)
return;
var v1 = clamp(@intToFloat(f32, (p2.y - p3.y) * (x - p3.x) + (p3.x - p2.x) * (y - p3.y)) / @intToFloat(f32, divisor), 0.0, 1.0);
var v2 = clamp(@intToFloat(f32, (p3.y - p1.y) * (x - p3.x) + (p1.x - p3.x) * (y - p3.y)) / @intToFloat(f32, divisor), 0.0, 1.0);
var v3 = clamp(1.0 - v2 - v1, 0.0, 1.0);
if (quality != .fast) {
var sum = v1 + v2 + v3;
v1 /= sum;
v2 /= sum;
v3 /= sum;
}
const z = p1.z * v1 + p2.z * v2 + p3.z * v3;
if (z < 0.0 or z > 1.0)
return;
var depth: *DepthType = undefined;
var int_z: DepthType = undefined;
if (job.context.depthTarget) |depthTarget| {
int_z = @floatToInt(DepthType, @floor(@floatToInt(f32, std.math.maxInt(DepthType) - 1) * @as(f64, z)));
depth = depthTarget.getPixelPtr(@intCast(usize, x), @intCast(usize, y));
if (@atomicLoad(DepthType, depth, .Acquire) < int_z)
return;
}
var u: f32 = undefined;
var v: f32 = undefined;
if (quality == .beautiful) {
u = z * ((p1.u / z) * v1 + (p2.u / z) * v2 + (p3.u / z) * v3);
v = z * ((p1.v / z) * v1 + (p2.v / z) * v2 + (p3.v / z) * v3);
} else {
u = p1.u * v1 + p2.u * v2 + p3.u * v3;
v = p1.v * v1 + p2.v * v2 + p3.v * v3;
}
const pixCol = job.face.texture.sample(u, v);
if (pixCol == 0x00)
return;
if (job.context.depthTarget) |depthTarget| {
_ = @atomicRmw(DepthType, depth, .Min, int_z, .SeqCst); // we don't care for the previous value
if (@atomicLoad(DepthType, depth, .Acquire) != int_z)
return;
}
// if (depth.* < int_z)
// return;
// depth.* = int_z;
if (job.context.colorTarget) |colorTarget| {
colorTarget.setPixel(@intCast(usize, x), @intCast(usize, y), pixCol);
}
}
};
}
fn paintTriangle(bounds: Rectangle, points: [3]Point, context: var, painter: fn (x: i32, y: i32, ctx: @TypeOf(context)) void) void {
var localPoints = points;
std.sort.sort(
Point,
&localPoints,
struct {
fn lessThan(lhs: Point, rhs: Point) bool {
return lhs.y < rhs.y;
}
}.lessThan,
);
// Implements two special versions
// of painting an up-facing or down-facing triangle with one perfectly horizontal side.
const Helper = struct {
const Mode = enum {
growing,
shrinking,
};
fn paintHalfTriangle(comptime mode: Mode, x_left: i32, x_right: i32, x_low: i32, y0: i32, y1: i32, bounds0: Rectangle, context0: var, painter0: fn (x: i32, y: i32, ctx: @TypeOf(context0)) void) void {
// early-discard when triangle is fully out of bounds
if (y0 >= bounds0.bottom or y1 < bounds0.top)
return;
if (std.math.max(x_left, std.math.max(x_right, x_low)) < bounds0.left)
return;
if (std.math.min(x_left, std.math.min(x_right, x_low)) >= bounds0.right)
return;
const totalY = y1 - y0;
std.debug.assert(totalY > 0);
var xa = if (mode == .shrinking) std.math.min(x_left, x_right) else x_low;
var xb = if (mode == .shrinking) std.math.max(x_left, x_right) else x_low;
const dx_a = if (mode == .shrinking) x_low - xa else std.math.min(x_left, x_right) - x_low;
const dx_b = if (mode == .shrinking) x_low - xb else std.math.max(x_left, x_right) - x_low;
const sx_a = if (dx_a < 0) @as(i32, -1) else 1;
const sx_b = if (dx_b < 0) @as(i32, -1) else 1;
const de_a = std.math.fabs(@intToFloat(f32, dx_a) / @intToFloat(f32, totalY));
const de_b = std.math.fabs(@intToFloat(f32, dx_b) / @intToFloat(f32, totalY));
var e_a: f32 = 0;
var e_b: f32 = 0;
var sy = y0;
while (sy <= std.math.min(bounds0.bottom - 1, y1)) : (sy += 1) {
if (sy >= 0) {
var x_s = std.math.max(xa, bounds0.left);
const x_e = std.math.min(xb, bounds0.right - 1);
while (x_s <= x_e) : (x_s += 1) {
painter0(x_s, sy, context0);
}
}
e_a += de_a;
e_b += de_b;
if (e_a >= 0.5) {
const d = @floor(e_a);
xa += @floatToInt(i32, d) * sx_a;
e_a -= d;
}
if (e_b >= 0.5) {
const d = @floor(e_b);
xb += @floatToInt(i32, d) * sx_b;
e_b -= d;
}
}
}
fn paintUpperTriangle(x00: i32, x01: i32, x1: i32, y0: i32, y1: i32, bounds0: Rectangle, ctx: var, painter0: fn (x: i32, y: i32, _ctx: @TypeOf(ctx)) void) void {
paintHalfTriangle(.shrinking, x00, x01, x1, y0, y1, bounds0, ctx, painter0);
}
fn paintLowerTriangle(x0: i32, x10: i32, x11: i32, y0: i32, y1: i32, bounds0: Rectangle, ctx: var, painter0: fn (x: i32, y: i32, _ctx: @TypeOf(ctx)) void) void {
paintHalfTriangle(.growing, x10, x11, x0, y0, y1, bounds0, ctx, painter0);
}
};
if (localPoints[0].y == localPoints[1].y and localPoints[0].y == localPoints[2].y) {
// this is actually a flat line, nothing to draw here
return;
}
if (localPoints[0].y == localPoints[1].y) {
// triangle shape:
// o---o
// \ /
// o
Helper.paintUpperTriangle(
localPoints[0].x,
localPoints[1].x,
localPoints[2].x,
localPoints[0].y,
localPoints[2].y,
bounds,
context,
painter,
);
} else if (localPoints[1].y == localPoints[2].y) {
// triangle shape:
// o
// / \
// o---o
Helper.paintLowerTriangle(
localPoints[0].x,
localPoints[1].x,
localPoints[2].x,
localPoints[0].y,
localPoints[1].y,
bounds,
context,
painter,
);
} else {
// non-straightline triangle
// o
// / \
// o---\
// \ |
// \ \
// \|
// o
const y0 = localPoints[0].y;
const y1 = localPoints[1].y;
const y2 = localPoints[2].y;
const deltaY01 = y1 - y0;
const deltaY12 = y2 - y1;
const deltaY02 = y2 - y0;
std.debug.assert(deltaY01 > 0);
std.debug.assert(deltaY12 > 0);
// std.debug.warn("{d} * ({d} - {d}) / {d}\n", .{ deltaY01, localPoints[2].x, localPoints[0].x, deltaY02 });
const pHelp: Point = .{
.x = localPoints[0].x + @divFloor(deltaY01 * (localPoints[2].x - localPoints[0].x), deltaY02),
.y = y1,
};
Helper.paintLowerTriangle(
localPoints[0].x,
localPoints[1].x,
pHelp.x,
localPoints[0].y,
localPoints[1].y,
bounds,
context,
painter,
);
Helper.paintUpperTriangle(
localPoints[1].x,
pHelp.x,
localPoints[2].x,
localPoints[1].y,
localPoints[2].y,
bounds,
context,
painter,
);
}
}
// legacy code:
fn paintPixel(x: i32, y: i32, color: u8) void {
if (x >= 0 and y >= 0 and x < screen.width and y < screen.height) {
paintPixelUnsafe(x, y, color);
}
}
fn paintPixelUnsafe(x: i32, y: i32, color: u8) void {
screen.pixels[@intCast(usize, y)][@intCast(usize, x)] = color;
}
fn paintLine(x0: i32, y0: i32, x1: i32, y1: i32, color: u8) void {
var dx = std.math.absInt(x1 - x0) catch unreachable;
var sx = if (x0 < x1) @as(i32, 1) else -1;
var dy = -(std.math.absInt(y1 - y0) catch unreachable);
var sy = if (y0 < y1) @as(i32, 1) else -1;
var err = dx + dy; // error value e_xy
var x = x0;
var y = y0;
while (true) {
paintPixel(x, y, color);
if (x == x1 and y == y1)
break;
const e2 = 2 * err;
if (e2 > dy) { // e_xy+e_x > 0
err += dy;
x += sx;
}
if (e2 < dx) { // e_xy+e_y < 0
err += dx;
y += sy;
}
}
}
|
src/rasterizer.zig
|
const std = @import("std");
const builtin = @import("builtin");
const Atomic = @import("atomic.zig").Atomic;
const SegmentedList = std.SegmentedList;
const Allocator = std.mem.Allocator;
pub fn Deque(comptime T: type, comptime P: usize) type {
return struct {
const Self = @This();
const List = SegmentedList(T, P);
allocator: *Allocator,
list: Atomic(*List),
bottom: Atomic(isize),
top: Atomic(isize),
pub fn new(allocator: *Allocator) !Self {
var list = try allocator.create(List);
list.* = List.init(allocator);
return Self{
.list = Atomic(*List).init(list),
.bottom = Atomic(isize).init(0),
.top = Atomic(isize).init(0),
.allocator = allocator,
};
}
pub fn deinit(self: *Self) void {
self.list.load(.Monotonic).deinit();
}
pub fn worker(self: *Self) Worker(T, P) {
return Worker(T, P){
.deque = self,
};
}
pub fn stealer(self: *Self) Stealer(T, P) {
return Stealer(T, P){
.deque = self,
};
}
fn push(self: *Self, item: T) !void {
const bottom = self.bottom.load(.Monotonic);
var list = self.list.load(.Monotonic);
try list.push(item);
@fence(.Release);
self.bottom.store(bottom +% 1, .Monotonic);
}
fn pop(self: *Self) ?T {
var bottom = self.bottom.load(.Monotonic);
var top = self.top.load(.Monotonic);
if (bottom -% top <= 0) {
return null;
}
bottom -%= 1;
self.bottom.store(bottom, .Monotonic);
@fence(.SeqCst);
top = self.top.load(.Monotonic);
const size = bottom -% top;
if (size < 0) {
self.bottom.store(bottom +% 1, .Monotonic);
return null;
}
const list = self.list.load(.Monotonic);
var data = list.at(bottom);
if (size != 0) {
return data.*;
}
if (self.top.cmpSwap(top, top +% 1, .SeqCst) == top) {
self.bottom.store(top +% 1, .Monotonic);
return data.*;
} else {
self.bottom.store(top +% 1, .Monotonic);
return null;
}
}
pub fn steal(self: *Self) ?T {
while (true) {
const top = self.top.load(.Acquire);
@fence(.SeqCst);
const bottom = self.bottom.load(.Acquire);
const size = bottom -% top;
if (size <= 0) return null;
const list = self.list.load(.Acquire);
const data = list.at(@intCast(usize, top));
if (self.top.cmpSwap(top, top +% 1, .SeqCst) == top) {
return data.*;
} else {
continue;
}
}
}
};
}
pub fn Worker(comptime T: type, comptime P: usize) type {
return struct {
const Self = @This();
deque: *Deque(T, P),
pub fn push(self: *const Self, item: T) !void {
try self.deque.push(item);
}
pub fn pop(self: *const Self, item: T) ?T {
return self.deque.pop();
}
};
}
pub fn Stealer(comptime T: type, comptime P: usize) type {
return struct {
const Self = @This();
deque: *Deque(T, P),
pub fn steal(self: *const Self) ?T {
return self.deque.steal();
}
};
}
|
src/deque.zig
|
const std = @import("std");
const testing = std.testing;
pub const ParseError = error{
Overflow,
EndOfStream,
OutOfMemory,
};
pub const Uint64Coder = struct {
pub const primitive = u64;
pub fn encodeSize(data: u64) usize {
const bits = u64.bit_count - @clz(u64, data);
return std.math.max(divCeil(u64, bits, 7), 1);
}
pub fn encode(buffer: []u8, data: u64) []u8 {
if (data == 0) {
buffer[0] = 0;
return buffer[0..1];
}
var i = usize(0);
var value = data;
while (value > 0) : (i += 1) {
buffer[i] = u8(0x80) + @truncate(u7, value);
value >>= 7;
}
buffer[i - 1] &= 0x7F;
return buffer[0..i];
}
pub fn decode(bytes: []const u8, len: *usize) ParseError!u64 {
var value = u64(0);
for (bytes) |byte, i| {
if (i >= 10) {
return error.Overflow;
}
value += @intCast(u64, 0x7F & byte) << (7 * @intCast(u6, i));
if (byte & 0x80 == 0) {
len.* = i + 1;
return value;
}
}
// TODO: stream in bytes
return error.EndOfStream;
}
};
test "Uint64Coder" {
var len: usize = 0;
var uint = try Uint64Coder.decode([_]u8{1}, &len);
testing.expectEqual(u64(1), uint);
uint = try Uint64Coder.decode([_]u8{ 0b10101100, 0b00000010 }, &len);
testing.expectEqual(u64(300), uint);
uint = try Uint64Coder.decode([_]u8{ 0b10010110, 0b00000001 }, &len);
testing.expectEqual(u64(150), uint);
}
pub const Int64Coder = struct {
pub const primitive = i64;
pub fn encodeSize(data: i64) usize {
return Uint64Coder.encodeSize(@bitCast(u64, data));
}
pub fn encode(buffer: []u8, data: i64) []u8 {
return Uint64Coder.encode(buffer, @bitCast(u64, data));
}
pub fn decode(bytes: []const u8, len: *usize) ParseError!i64 {
return @bitCast(i64, try Uint64Coder.decode(bytes, len));
}
};
test "Int64Coder" {
var buf1: [1000]u8 = undefined;
var buf2: [1000]u8 = undefined;
testing.expectEqualSlices(
u8,
Uint64Coder.encode(buf1[0..], std.math.maxInt(u64)),
Int64Coder.encode(buf2[0..], -1),
);
}
pub const Sint64Coder = struct {
pub const primitive = i64;
pub fn encodeSize(data: i64) usize {
return Uint64Coder.encodeSize(@bitCast(u64, (data << 1) ^ (data >> 63)));
}
pub fn encode(buffer: []u8, data: i64) []u8 {
return Uint64Coder.encode(buffer, @bitCast(u64, (data << 1) ^ (data >> 63)));
}
pub fn decode(bytes: []const u8, len: *usize) ParseError!i64 {
const source = try Uint64Coder.decode(bytes, len);
const raw = @bitCast(i64, source >> 1);
return if (@mod(source, 2) == 0) raw else -(raw + 1);
}
};
test "Sint64Coder" {
var buf1: [1000]u8 = undefined;
var buf2: [1000]u8 = undefined;
testing.expectEqualSlices(
u8,
Uint64Coder.encode(buf1[0..], 1),
Sint64Coder.encode(buf2[0..], -1),
);
testing.expectEqualSlices(
u8,
Uint64Coder.encode(buf1[0..], 4294967294),
Sint64Coder.encode(buf2[0..], 2147483647),
);
testing.expectEqualSlices(
u8,
Uint64Coder.encode(buf1[0..], 4294967295),
Sint64Coder.encode(buf2[0..], -2147483648),
);
}
pub const Fixed64Coder = struct {
pub const primitive = u64;
pub fn encodeSize(data: u64) usize {
return 8;
}
pub fn encode(buffer: []u8, data: u64) []u8 {
var result = buffer[0..encodeSize(data)];
std.mem.writeIntSliceLittle(u64, result, data);
return result;
}
pub fn decode(bytes: []const u8, len: *usize) ParseError!u64 {
len.* = 8;
return std.mem.readIntSliceLittle(u64, bytes);
}
};
pub const Fixed32Coder = struct {
pub const primitive = u32;
pub fn encodeSize(data: u32) usize {
return 4;
}
pub fn encode(buffer: []u8, data: u32) []u8 {
var result = buffer[0..encodeSize(data)];
std.mem.writeIntSliceLittle(u32, result, data);
return result;
}
pub fn decode(bytes: []const u8, len: *usize) ParseError!u32 {
len.* = 4;
return std.mem.readIntSliceLittle(u32, bytes);
}
};
pub const BytesCoder = struct {
pub fn encodeSize(data: []const u8) usize {
const header_size = Uint64Coder.encodeSize(data.len);
return header_size + data.len;
}
pub fn encode(buffer: []u8, data: []const u8) []u8 {
const header = Uint64Coder.encode(buffer, data.len);
// TODO: use a generator instead of buffer overflow
std.mem.copy(u8, buffer[header.len..], data);
return buffer[0 .. header.len + data.len];
}
pub fn decode(buffer: []const u8, len: *usize, allocator: *std.mem.Allocator) ![]u8 {
var header_len: usize = undefined;
const header = try Uint64Coder.decode(buffer, &header_len);
var data = try allocator.alloc(u8, header);
errdefer allocator.free(data);
std.mem.copy(u8, data, buffer[header_len .. header_len + data.len]);
len.* = header_len + data.len;
return data;
}
};
test "BytesCoder" {
var buffer: [1000]u8 = undefined;
testing.expectEqualSlices(
u8,
[_]u8{ 0x07, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67 },
BytesCoder.encode(buffer[0..], "testing"),
);
}
fn divCeil(comptime T: type, numerator: T, denominator: T) T {
return (numerator + denominator - 1) / denominator;
}
|
src/coder.zig
|
const zfltk = @import("zfltk");
const app = zfltk.app;
const widget = zfltk.widget;
const window = zfltk.window;
const menu = zfltk.menu;
const enums = zfltk.enums;
const text = zfltk.text;
const dialog = zfltk.dialog;
// To avoid exiting when hitting escape.
// Also logic can be added to prompt the user to save their work
pub fn winCb(w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void {
_ = data;
if (app.event() == enums.Event.Close) {
widget.Widget.fromWidgetPtr(w).hide();
}
}
pub fn newCb(w: menu.WidgetPtr, data: ?*c_void) callconv(.C) void {
_ = w;
var buf = text.TextBuffer.fromVoidPtr(data);
buf.setText("");
}
pub fn openCb(w: menu.WidgetPtr, data: ?*c_void) callconv(.C) void {
_ = w;
var dlg = dialog.NativeFileDialog.new(.BrowseFile);
dlg.setFilter("*.{txt,zig}");
dlg.show();
var fname = dlg.filename();
if (fname != null) {
var buf = text.TextBuffer.fromVoidPtr(data);
_ = buf.loadFile(fname) catch unreachable;
}
}
pub fn saveCb(w: menu.WidgetPtr, data: ?*c_void) callconv(.C) void {
_ = w;
var dlg = dialog.NativeFileDialog.new(.BrowseSaveFile);
dlg.setFilter("*.{txt,zig}");
dlg.show();
var fname = dlg.filename();
if (fname != null) {
var buf = text.TextBuffer.fromVoidPtr(data);
_ = buf.saveFile(fname) catch unreachable;
}
}
pub fn quitCb(w: menu.WidgetPtr, data: ?*c_void) callconv(.C) void {
_ = w;
var win = widget.Widget.fromVoidPtr(data);
win.hide();
}
pub fn cutCb(w: menu.WidgetPtr, data: ?*c_void) callconv(.C) void {
_ = w;
const editor = text.TextEditor.fromVoidPtr(data);
editor.cut();
}
pub fn copyCb(w: menu.WidgetPtr, data: ?*c_void) callconv(.C) void {
_ = w;
const editor = text.TextEditor.fromVoidPtr(data);
editor.copy();
}
pub fn pasteCb(w: menu.WidgetPtr, data: ?*c_void) callconv(.C) void {
_ = w;
const editor = text.TextEditor.fromVoidPtr(data);
editor.paste();
}
pub fn helpCb(w: menu.WidgetPtr, data: ?*c_void) callconv(.C) void {
_ = w;
_ = data;
dialog.message(300, 200, "This editor was built using fltk and zig!");
}
pub fn main() !void {
try app.init();
app.setScheme(.Gtk);
app.background(211, 211, 211);
var win = window.Window.new(100, 100, 800, 600, "Editor");
win.freePosition();
var mymenu = menu.MenuBar.new(0, 0, 800, 35, "");
var buf = text.TextBuffer.new();
defer buf.delete();
var editor = text.TextEditor.new(2, 37, 800 - 2, 600 - 37, "");
editor.asTextDisplay().setBuffer(&buf);
editor.asTextDisplay().setLinenumberWidth(24);
win.asGroup().end();
win.asWidget().show();
win.asWidget().setCallback(winCb, null);
mymenu.asMenu().add(
"&File/New...\t",
enums.Shortcut.Ctrl | 'n',
.Normal,
newCb,
buf.toVoidPtr(),
);
mymenu.asMenu().add(
"&File/Open...\t",
enums.Shortcut.Ctrl | 'o',
.Normal,
openCb,
buf.toVoidPtr(),
);
mymenu.asMenu().add(
"&File/Save...\t",
enums.Shortcut.Ctrl | 's',
.MenuDivider,
saveCb,
buf.toVoidPtr(),
);
mymenu.asMenu().add(
"&File/Quit...\t",
enums.Shortcut.Ctrl | 'q',
.Normal,
quitCb,
win.toVoidPtr(),
);
mymenu.asMenu().add(
"&Edit/Cut...\t",
enums.Shortcut.Ctrl | 'x',
.Normal,
cutCb,
editor.toVoidPtr(),
);
mymenu.asMenu().add(
"&Edit/Copy...\t",
enums.Shortcut.Ctrl | 'c',
.Normal,
copyCb,
editor.toVoidPtr(),
);
mymenu.asMenu().add(
"&Edit/Paste...\t",
enums.Shortcut.Ctrl | 'v',
.Normal,
pasteCb,
editor.toVoidPtr(),
);
mymenu.asMenu().add(
"&Help/About...\t",
enums.Shortcut.Ctrl | 'q',
.Normal,
helpCb,
null,
);
var item = mymenu.asMenu().findItem("&File/Quit...\t");
item.setLabelColor(enums.Color.Red);
try app.run();
}
|
examples/editor.zig
|
const std = @import("../std.zig");
const assert = std.debug.assert;
const builtin = @import("builtin");
const macho = std.macho;
usingnamespace @import("../os/bits.zig");
extern "c" fn __error() *c_int;
pub extern "c" fn NSVersionOfRunTimeLibrary(library_name: [*:0]const u8) u32;
pub extern "c" fn _NSGetExecutablePath(buf: [*:0]u8, bufsize: *u32) c_int;
pub extern "c" fn _dyld_image_count() u32;
pub extern "c" fn _dyld_get_image_header(image_index: u32) ?*mach_header;
pub extern "c" fn _dyld_get_image_vmaddr_slide(image_index: u32) usize;
pub extern "c" fn _dyld_get_image_name(image_index: u32) [*:0]const u8;
pub const COPYFILE_ACL = 1 << 0;
pub const COPYFILE_STAT = 1 << 1;
pub const COPYFILE_XATTR = 1 << 2;
pub const COPYFILE_DATA = 1 << 3;
pub const copyfile_state_t = *opaque {};
pub extern "c" fn fcopyfile(from: fd_t, to: fd_t, state: ?copyfile_state_t, flags: u32) c_int;
pub extern "c" fn @"realpath$DARWIN_EXTSN"(noalias file_name: [*:0]const u8, noalias resolved_name: [*]u8) ?[*:0]u8;
pub extern "c" fn __getdirentries64(fd: c_int, buf_ptr: [*]u8, buf_len: usize, basep: *i64) isize;
extern "c" fn fstat(fd: fd_t, buf: *libc_stat) c_int;
/// On x86_64 Darwin, fstat has to be manully linked with $INODE64 suffix to force 64bit version.
/// Note that this is fixed on aarch64 and no longer necessary.
extern "c" fn @"fstat$INODE64"(fd: fd_t, buf: *libc_stat) c_int;
pub const _fstat = if (builtin.arch == .aarch64) fstat else @"fstat$INODE64";
extern "c" fn fstatat(dirfd: fd_t, path: [*:0]const u8, stat_buf: *libc_stat, flags: u32) c_int;
/// On x86_64 Darwin, fstatat has to be manully linked with $INODE64 suffix to force 64bit version.
/// Note that this is fixed on aarch64 and no longer necessary.
extern "c" fn @"fstatat$INODE64"(dirfd: fd_t, path_name: [*:0]const u8, buf: *libc_stat, flags: u32) c_int;
pub const _fstatat = if (builtin.arch == .aarch64) fstatat else @"fstatat$INODE64";
pub extern "c" fn mach_absolute_time() u64;
pub extern "c" fn mach_timebase_info(tinfo: ?*mach_timebase_info_data) void;
pub extern "c" fn malloc_size(?*const c_void) usize;
pub extern "c" fn posix_memalign(memptr: *?*c_void, alignment: usize, size: usize) c_int;
pub extern "c" fn kevent64(
kq: c_int,
changelist: [*]const kevent64_s,
nchanges: c_int,
eventlist: [*]kevent64_s,
nevents: c_int,
flags: c_uint,
timeout: ?*const timespec,
) c_int;
const mach_hdr = if (@sizeOf(usize) == 8) mach_header_64 else mach_header;
/// The value of the link editor defined symbol _MH_EXECUTE_SYM is the address
/// of the mach header in a Mach-O executable file type. It does not appear in
/// any file type other than a MH_EXECUTE file type. The type of the symbol is
/// absolute as the header is not part of any section.
/// This symbol is populated when linking the system's libc, which is guaranteed
/// on this operating system. However when building object files or libraries,
/// the system libc won't be linked until the final executable. So we
/// export a weak symbol here, to be overridden by the real one.
var dummy_execute_header: mach_hdr = undefined;
pub extern var _mh_execute_header: mach_hdr;
comptime {
if (std.Target.current.isDarwin()) {
@export(dummy_execute_header, .{ .name = "_mh_execute_header", .linkage = .Weak });
}
}
pub const mach_header_64 = macho.mach_header_64;
pub const mach_header = macho.mach_header;
pub const _errno = __error;
pub extern "c" fn @"close$NOCANCEL"(fd: fd_t) c_int;
pub extern "c" fn mach_host_self() mach_port_t;
pub extern "c" fn clock_get_time(clock_serv: clock_serv_t, cur_time: *mach_timespec_t) kern_return_t;
pub extern "c" fn host_get_clock_service(host: host_t, clock_id: clock_id_t, clock_serv: ?[*]clock_serv_t) kern_return_t;
pub extern "c" fn mach_port_deallocate(task: ipc_space_t, name: mach_port_name_t) kern_return_t;
pub const sf_hdtr = extern struct {
headers: [*]const iovec_const,
hdr_cnt: c_int,
trailers: [*]const iovec_const,
trl_cnt: c_int,
};
pub extern "c" fn sendfile(
in_fd: fd_t,
out_fd: fd_t,
offset: off_t,
len: *off_t,
sf_hdtr: ?*sf_hdtr,
flags: u32,
) c_int;
pub fn sigaddset(set: *sigset_t, signo: u5) void {
set.* |= @as(u32, 1) << (signo - 1);
}
pub extern "c" fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) c_int;
/// get address to use bind()
pub const AI_PASSIVE = 0x00000001;
/// fill ai_canonname
pub const AI_CANONNAME = 0x00000002;
/// prevent host name resolution
pub const AI_NUMERICHOST = 0x00000004;
/// prevent service name resolution
pub const AI_NUMERICSERV = 0x00001000;
pub const EAI = extern enum(c_int) {
/// address family for hostname not supported
ADDRFAMILY = 1,
/// temporary failure in name resolution
AGAIN = 2,
/// invalid value for ai_flags
BADFLAGS = 3,
/// non-recoverable failure in name resolution
FAIL = 4,
/// ai_family not supported
FAMILY = 5,
/// memory allocation failure
MEMORY = 6,
/// no address associated with hostname
NODATA = 7,
/// hostname nor servname provided, or not known
NONAME = 8,
/// servname not supported for ai_socktype
SERVICE = 9,
/// ai_socktype not supported
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 pthread_mutex_t = extern struct {
__sig: c_long = 0x32AAABA7,
__opaque: [__PTHREAD_MUTEX_SIZE__]u8 = [_]u8{0} ** __PTHREAD_MUTEX_SIZE__,
};
pub const pthread_cond_t = extern struct {
__sig: c_long = 0x3CB0B1BB,
__opaque: [__PTHREAD_COND_SIZE__]u8 = [_]u8{0} ** __PTHREAD_COND_SIZE__,
};
const __PTHREAD_MUTEX_SIZE__ = if (@sizeOf(usize) == 8) 56 else 40;
const __PTHREAD_COND_SIZE__ = if (@sizeOf(usize) == 8) 40 else 24;
pub const pthread_attr_t = extern struct {
__sig: c_long,
__opaque: [56]u8,
};
pub extern "c" fn arc4random_buf(buf: [*]u8, len: usize) void;
|
lib/std/c/darwin.zig
|
const std = @import("std");
const fs = std.fs;
const fmt = std.fmt;
const assert = std.debug.assert;
// Example abilist path:
// ./sysdeps/unix/sysv/linux/aarch64/libc.abilist
const AbiList = struct {
targets: []const ZigTarget,
path: []const u8,
};
const ZigTarget = struct {
arch: std.Target.Cpu.Arch,
abi: std.Target.Abi,
};
const lib_names = [_][]const u8{
"c",
"dl",
"m",
"pthread",
"rt",
"ld",
"util",
};
// fpu/nofpu are hardcoded elsewhere, based on .gnueabi/.gnueabihf with an exception for .arm
// n64/n32 are hardcoded elsewhere, based on .gnuabi64/.gnuabin32
const abi_lists = [_]AbiList{
AbiList{
.targets = &[_]ZigTarget{
ZigTarget{ .arch = .aarch64, .abi = .gnu },
ZigTarget{ .arch = .aarch64_be, .abi = .gnu },
},
.path = "aarch64",
},
AbiList{
.targets = &[_]ZigTarget{ZigTarget{ .arch = .s390x, .abi = .gnu }},
.path = "s390/s390-64",
},
AbiList{
.targets = &[_]ZigTarget{
ZigTarget{ .arch = .arm, .abi = .gnueabi },
ZigTarget{ .arch = .armeb, .abi = .gnueabi },
ZigTarget{ .arch = .arm, .abi = .gnueabihf },
ZigTarget{ .arch = .armeb, .abi = .gnueabihf },
},
.path = "arm",
},
AbiList{
.targets = &[_]ZigTarget{
ZigTarget{ .arch = .sparc, .abi = .gnu },
ZigTarget{ .arch = .sparcel, .abi = .gnu },
},
.path = "sparc/sparc32",
},
AbiList{
.targets = &[_]ZigTarget{ZigTarget{ .arch = .sparcv9, .abi = .gnu }},
.path = "sparc/sparc64",
},
AbiList{
.targets = &[_]ZigTarget{
ZigTarget{ .arch = .mips64el, .abi = .gnuabi64 },
ZigTarget{ .arch = .mips64, .abi = .gnuabi64 },
},
.path = "mips/mips64",
},
AbiList{
.targets = &[_]ZigTarget{
ZigTarget{ .arch = .mips64el, .abi = .gnuabin32 },
ZigTarget{ .arch = .mips64, .abi = .gnuabin32 },
},
.path = "mips/mips64",
},
AbiList{
.targets = &[_]ZigTarget{
ZigTarget{ .arch = .mipsel, .abi = .gnueabihf },
ZigTarget{ .arch = .mips, .abi = .gnueabihf },
},
.path = "mips/mips32",
},
AbiList{
.targets = &[_]ZigTarget{
ZigTarget{ .arch = .mipsel, .abi = .gnueabi },
ZigTarget{ .arch = .mips, .abi = .gnueabi },
},
.path = "mips/mips32",
},
AbiList{
.targets = &[_]ZigTarget{ZigTarget{ .arch = .x86_64, .abi = .gnu }},
.path = "x86_64/64",
},
AbiList{
.targets = &[_]ZigTarget{ZigTarget{ .arch = .x86_64, .abi = .gnux32 }},
.path = "x86_64/x32",
},
AbiList{
.targets = &[_]ZigTarget{ZigTarget{ .arch = .i386, .abi = .gnu }},
.path = "i386",
},
AbiList{
.targets = &[_]ZigTarget{ZigTarget{ .arch = .powerpc64le, .abi = .gnu }},
.path = "powerpc/powerpc64/le",
},
AbiList{
.targets = &[_]ZigTarget{ZigTarget{ .arch = .powerpc64, .abi = .gnu }},
.path = "powerpc/powerpc64/be",
},
AbiList{
.targets = &[_]ZigTarget{
ZigTarget{ .arch = .powerpc, .abi = .gnueabi },
ZigTarget{ .arch = .powerpc, .abi = .gnueabihf },
},
.path = "powerpc/powerpc32",
},
};
const FunctionSet = struct {
list: std.ArrayList(VersionedFn),
fn_vers_list: FnVersionList,
};
const FnVersionList = std.StringHashMap(std.ArrayList(usize));
const VersionedFn = struct {
ver: []const u8, // example: "GLIBC_2.15"
name: []const u8, // example: "puts"
};
const Function = struct {
name: []const u8, // example: "puts"
lib: []const u8, // example: "c"
index: usize,
};
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = &arena.allocator;
const args = try std.process.argsAlloc(allocator);
const in_glibc_dir = args[1]; // path to the unzipped tarball of glibc, e.g. ~/downloads/glibc-2.25
const zig_src_dir = args[2]; // path to the source checkout of zig, lib dir, e.g. ~/zig-src/lib
const prefix = try fs.path.join(allocator, &[_][]const u8{ in_glibc_dir, "sysdeps", "unix", "sysv", "linux" });
const glibc_out_dir = try fs.path.join(allocator, &[_][]const u8{ zig_src_dir, "libc", "glibc" });
var global_fn_set = std.StringHashMap(Function).init(allocator);
var global_ver_set = std.StringHashMap(usize).init(allocator);
var target_functions = std.AutoHashMap(usize, FunctionSet).init(allocator);
for (abi_lists) |*abi_list| {
const target_funcs_gop = try target_functions.getOrPut(@ptrToInt(abi_list));
if (!target_funcs_gop.found_existing) {
target_funcs_gop.entry.value = FunctionSet{
.list = std.ArrayList(VersionedFn).init(allocator),
.fn_vers_list = FnVersionList.init(allocator),
};
}
const fn_set = &target_funcs_gop.entry.value.list;
for (lib_names) |lib_name, lib_name_index| {
const lib_prefix = if (std.mem.eql(u8, lib_name, "ld")) "" else "lib";
const basename = try fmt.allocPrint(allocator, "{}{}.abilist", .{ lib_prefix, lib_name });
const abi_list_filename = blk: {
const is_c = std.mem.eql(u8, lib_name, "c");
const is_m = std.mem.eql(u8, lib_name, "m");
const is_ld = std.mem.eql(u8, lib_name, "ld");
if (abi_list.targets[0].abi == .gnuabi64 and (is_c or is_ld)) {
break :blk try fs.path.join(allocator, &[_][]const u8{ prefix, abi_list.path, "n64", basename });
} else if (abi_list.targets[0].abi == .gnuabin32 and (is_c or is_ld)) {
break :blk try fs.path.join(allocator, &[_][]const u8{ prefix, abi_list.path, "n32", basename });
} else if (abi_list.targets[0].arch != .arm and
abi_list.targets[0].abi == .gnueabihf and
(is_c or (is_m and abi_list.targets[0].arch == .powerpc)))
{
break :blk try fs.path.join(allocator, &[_][]const u8{ prefix, abi_list.path, "fpu", basename });
} else if (abi_list.targets[0].arch != .arm and
abi_list.targets[0].abi == .gnueabi and
(is_c or (is_m and abi_list.targets[0].arch == .powerpc)))
{
break :blk try fs.path.join(allocator, &[_][]const u8{ prefix, abi_list.path, "nofpu", basename });
} else if (abi_list.targets[0].arch == .arm) {
break :blk try fs.path.join(allocator, &[_][]const u8{ prefix, abi_list.path, "le", basename });
} else if (abi_list.targets[0].arch == .armeb) {
break :blk try fs.path.join(allocator, &[_][]const u8{ prefix, abi_list.path, "be", basename });
}
break :blk try fs.path.join(allocator, &[_][]const u8{ prefix, abi_list.path, basename });
};
const max_bytes = 10 * 1024 * 1024;
const contents = std.fs.cwd().readFileAlloc(allocator, abi_list_filename, max_bytes) catch |err| {
std.debug.warn("unable to open {}: {}\n", .{ abi_list_filename, err });
std.process.exit(1);
};
var lines_it = std.mem.tokenize(contents, "\n");
while (lines_it.next()) |line| {
var tok_it = std.mem.tokenize(line, " ");
const ver = tok_it.next().?;
const name = tok_it.next().?;
const category = tok_it.next().?;
if (!std.mem.eql(u8, category, "F") and
!std.mem.eql(u8, category, "D"))
{
continue;
}
if (std.mem.startsWith(u8, ver, "GCC_")) continue;
_ = try global_ver_set.put(ver, undefined);
const gop = try global_fn_set.getOrPut(name);
if (gop.found_existing) {
if (!std.mem.eql(u8, gop.entry.value.lib, "c")) {
gop.entry.value.lib = lib_name;
}
} else {
gop.entry.value = Function{
.name = name,
.lib = lib_name,
.index = undefined,
};
}
try fn_set.append(VersionedFn{
.ver = ver,
.name = name,
});
}
}
}
const global_fn_list = blk: {
var list = std.ArrayList([]const u8).init(allocator);
var it = global_fn_set.iterator();
while (it.next()) |entry| try list.append(entry.key);
std.sort.sort([]const u8, list.items, {}, strCmpLessThan);
break :blk list.items;
};
const global_ver_list = blk: {
var list = std.ArrayList([]const u8).init(allocator);
var it = global_ver_set.iterator();
while (it.next()) |entry| try list.append(entry.key);
std.sort.sort([]const u8, list.items, {}, versionLessThan);
break :blk list.items;
};
{
const vers_txt_path = try fs.path.join(allocator, &[_][]const u8{ glibc_out_dir, "vers.txt" });
const vers_txt_file = try fs.cwd().createFile(vers_txt_path, .{});
defer vers_txt_file.close();
var buffered = std.io.bufferedOutStream(vers_txt_file.writer());
const vers_txt = buffered.writer();
for (global_ver_list) |name, i| {
_ = global_ver_set.put(name, i) catch unreachable;
try vers_txt.print("{}\n", .{name});
}
try buffered.flush();
}
{
const fns_txt_path = try fs.path.join(allocator, &[_][]const u8{ glibc_out_dir, "fns.txt" });
const fns_txt_file = try fs.cwd().createFile(fns_txt_path, .{});
defer fns_txt_file.close();
var buffered = std.io.bufferedOutStream(fns_txt_file.writer());
const fns_txt = buffered.writer();
for (global_fn_list) |name, i| {
const entry = global_fn_set.getEntry(name).?;
entry.value.index = i;
try fns_txt.print("{} {}\n", .{ name, entry.value.lib });
}
try buffered.flush();
}
// Now the mapping of version and function to integer index is complete.
// Here we create a mapping of function name to list of versions.
for (abi_lists) |*abi_list, abi_index| {
const entry = target_functions.getEntry(@ptrToInt(abi_list)).?;
const fn_vers_list = &entry.value.fn_vers_list;
for (entry.value.list.items) |*ver_fn| {
const gop = try fn_vers_list.getOrPut(ver_fn.name);
if (!gop.found_existing) {
gop.entry.value = std.ArrayList(usize).init(allocator);
}
const ver_index = global_ver_set.getEntry(ver_fn.ver).?.value;
if (std.mem.indexOfScalar(usize, gop.entry.value.items, ver_index) == null) {
try gop.entry.value.append(ver_index);
}
}
}
{
const abilist_txt_path = try fs.path.join(allocator, &[_][]const u8{ glibc_out_dir, "abi.txt" });
const abilist_txt_file = try fs.cwd().createFile(abilist_txt_path, .{});
defer abilist_txt_file.close();
var buffered = std.io.bufferedOutStream(abilist_txt_file.writer());
const abilist_txt = buffered.writer();
// first iterate over the abi lists
for (abi_lists) |*abi_list, abi_index| {
const fn_vers_list = &target_functions.getEntry(@ptrToInt(abi_list)).?.value.fn_vers_list;
for (abi_list.targets) |target, it_i| {
if (it_i != 0) try abilist_txt.writeByte(' ');
try abilist_txt.print("{}-linux-{}", .{ @tagName(target.arch), @tagName(target.abi) });
}
try abilist_txt.writeByte('\n');
// next, each line implicitly corresponds to a function
for (global_fn_list) |name| {
const entry = fn_vers_list.getEntry(name) orelse {
try abilist_txt.writeByte('\n');
continue;
};
for (entry.value.items) |ver_index, it_i| {
if (it_i != 0) try abilist_txt.writeByte(' ');
try abilist_txt.print("{d}", .{ver_index});
}
try abilist_txt.writeByte('\n');
}
}
try buffered.flush();
}
}
pub fn strCmpLessThan(context: void, a: []const u8, b: []const u8) bool {
return std.mem.order(u8, a, b) == .lt;
}
pub fn versionLessThan(context: void, a: []const u8, b: []const u8) bool {
const sep_chars = "GLIBC_.";
var a_tokens = std.mem.tokenize(a, sep_chars);
var b_tokens = std.mem.tokenize(b, sep_chars);
while (true) {
const a_next = a_tokens.next();
const b_next = b_tokens.next();
if (a_next == null and b_next == null) {
return false; // equal means not less than
} else if (a_next == null) {
return true;
} else if (b_next == null) {
return false;
}
const a_int = fmt.parseInt(u64, a_next.?, 10) catch unreachable;
const b_int = fmt.parseInt(u64, b_next.?, 10) catch unreachable;
if (a_int < b_int) {
return true;
} else if (a_int > b_int) {
return false;
}
}
}
|
tools/update_glibc.zig
|
files: []const []const u8,
verbose: VerboseTargets,
const std = @import("std");
const Allocator = std.mem.Allocator;
const clap = @import("clap");
const term = @import("term.zig");
pub const version: std.SemanticVersion = .{ .major = 0, .minor = 1, .patch = 0 };
pub const VerboseTargets = packed struct {
tokens: bool,
cst: bool,
pub const Tag = enum {
tokens,
cst,
pub const map = std.ComptimeStringMap(Tag, .{
.{ "tokens", .tokens },
.{ "cst", .cst },
});
};
};
const Self = @This();
pub fn get(allocator: Allocator) !Self {
const params = comptime [_]clap.Param(clap.Help){
clap.parseParam("-h, --help Display this help and exit.") catch unreachable,
clap.parseParam("-V Print version.") catch unreachable,
clap.parseParam("-v <STR>... Items to print in verbose") catch unreachable,
// clap.parseParam("-n, --number <NUM> An option parameter, which takes a value.") catch unreachable,
clap.parseParam("<FILES>...") catch unreachable,
};
var diag = clap.Diagnostic{};
var args = clap.parse(clap.Help, ¶ms, .{ .diagnostic = &diag }) catch |err| {
diag.report(term.stderr.writer(), err) catch {};
std.os.exit(2);
};
defer args.deinit();
if (args.flag("--help")) {
term.eprint("vexc ", .{});
try clap.usage(term.stderr.writer(), ¶ms);
term.eprint("\n\nOptions:\n", .{});
try clap.help(term.stderr.writer(), ¶ms);
std.os.exit(0);
} else if (args.flag("-V")) {
term.eprintln("{}", .{version});
std.os.exit(0);
}
var verbose_targets = VerboseTargets{ .tokens = false, .cst = false };
for (args.options("-v")) |s| {
if (VerboseTargets.Tag.map.get(s)) |tag| {
switch (tag) {
.tokens => verbose_targets.tokens = true,
.cst => verbose_targets.cst = true,
}
} else {
term.eprintln("Error: '{s}' is not a valid verbose target, ignoring.", .{s});
}
}
const positionals = args.positionals();
if (positionals.len == 0) {
term.eprintln("Error: Expected at least one <FILE> argument.", .{});
std.os.exit(2);
}
const files = try allocator.dupe([]const u8, args.positionals());
return Self{
.files = files,
.verbose = verbose_targets,
};
}
pub fn deinit(self: Self, allocator: Allocator) void {
allocator.free(self.files);
}
|
fexc/src/Options.zig
|
const std = @import("std");
const gpa = std.heap.c_allocator;
const fs = std.fs;
const known_folders = @import("known-folders");
const u = @import("./../util/index.zig");
const common = @import("./../common.zig");
//
//
pub fn execute(args: [][]u8) !void {
//
const dir = try fs.path.join(gpa, &.{".zigmod", "deps"});
const top_module = try common.collect_deps(dir, "zig.mod", .{
.log = true,
.update = true,
});
//
const f = try fs.cwd().createFile("deps.zig", .{});
defer f.close();
const w = f.writer();
try w.writeAll("const std = @import(\"std\");\n");
try w.writeAll("const build = std.build;\n");
try w.writeAll("\n");
try w.print("pub const cache = \"{}\";\n", .{std.zig.fmtEscapes(dir)});
try w.writeAll("\n");
try w.print("{s}\n", .{
\\pub fn addAllTo(exe: *build.LibExeObjStep) void {
\\ @setEvalBranchQuota(1_000_000);
\\ for (packages) |pkg| {
\\ exe.addPackage(pkg);
\\ }
\\ if (c_include_dirs.len > 0 or c_source_files.len > 0) {
\\ exe.linkLibC();
\\ }
\\ for (c_include_dirs) |dir| {
\\ exe.addIncludeDir(dir);
\\ }
\\ inline for (c_source_files) |fpath| {
\\ exe.addCSourceFile(fpath[1], @field(c_source_flags, fpath[0]));
\\ }
\\ for (system_libs) |lib| {
\\ exe.linkSystemLibrary(lib);
\\ }
\\}
\\
\\fn get_flags(comptime index: usize) []const u8 {
\\ return @field(c_source_flags, _paths[index]);
\\}
\\
});
const list = &std.ArrayList(u.Module).init(gpa);
try common.collect_pkgs(top_module, list);
try w.writeAll("pub const _ids = .{\n");
try print_ids(w, list.items);
try w.writeAll("};\n\n");
try w.print("pub const _paths = {s}\n", .{".{"});
try print_paths(w, list.items);
try w.writeAll("};\n\n");
try w.writeAll("pub const package_data = struct {\n");
const duped = &std.ArrayList(u.Module).init(gpa);
for (list.items) |mod| {
if (mod.main.len > 0 and mod.clean_path.len > 0) {
try duped.append(mod);
}
}
try print_pkg_data_to(w, duped, &std.ArrayList(u.Module).init(gpa));
try w.writeAll("};\n\n");
try w.writeAll("pub const packages = ");
try print_deps(w, dir, top_module, 0, true);
try w.writeAll(";\n\n");
try w.writeAll("pub const pkgs = ");
try print_deps(w, dir, top_module, 0, false);
try w.writeAll(";\n\n");
try w.writeAll("pub const c_include_dirs = &[_][]const u8{\n");
try print_incl_dirs_to(w, list.items);
try w.writeAll("};\n\n");
try w.writeAll("pub const c_source_flags = struct {\n");
try print_csrc_flags_to(w, list.items);
try w.writeAll("};\n\n");
try w.writeAll("pub const c_source_files = &[_][2][]const u8{\n");
try print_csrc_dirs_to(w, list.items);
try w.writeAll("};\n\n");
try w.writeAll("pub const system_libs = &[_][]const u8{\n");
try print_sys_libs_to(w, list.items, &std.ArrayList([]const u8).init(gpa));
try w.writeAll("};\n\n");
}
fn print_ids(w: fs.File.Writer, list: []u.Module) !void {
for (list) |mod| {
if (mod.is_sys_lib) {
continue;
}
try w.print(" \"{s}\",\n", .{mod.id});
}
}
fn print_paths(w: fs.File.Writer, list: []u.Module) !void {
for (list) |mod| {
if (mod.is_sys_lib) {
continue;
}
if (mod.clean_path.len == 0) {
try w.print(" \"\",\n", .{});
} else {
const s = std.fs.path.sep_str;
try w.print(" \"{}{}{}\",\n", .{std.zig.fmtEscapes(s), std.zig.fmtEscapes(mod.clean_path), std.zig.fmtEscapes(s)});
}
}
}
fn print_deps(w: fs.File.Writer, dir: []const u8, m: u.Module, tabs: i32, array: bool) anyerror!void {
if (m.has_no_zig_deps() and tabs > 0) {
try w.print("null", .{});
return;
}
if (array) {
try u.print_all(w, .{"&[_]build.Pkg{"}, true);
} else {
try u.print_all(w, .{"struct {"}, true);
}
const t = " ";
const r = try u.repeat(t, tabs);
for (m.deps) |d, i| {
if (d.main.len == 0) {
continue;
}
if (!array) {
try w.print(" pub const {s} = packages[{}];\n", .{std.mem.replaceOwned(u8, gpa, d.name, "-", "_"), i});
}
else {
try w.print(" package_data._{s},\n", .{d.id});
}
}
try w.print("{s}", .{try u.concat(&.{r,"}"})});
}
fn print_incl_dirs_to(w: fs.File.Writer, list: []u.Module) !void {
for (list) |mod, i| {
if (mod.is_sys_lib) {
continue;
}
for (mod.c_include_dirs) |it| {
if (i > 0) {
try w.print(" cache ++ _paths[{}] ++ \"{}\",\n", .{i, std.zig.fmtEscapes(it)});
} else {
try w.print(" \"{}\",\n", .{std.zig.fmtEscapes(it)});
}
}
}
}
fn print_csrc_dirs_to(w: fs.File.Writer, list: []u.Module) !void {
for (list) |mod, i| {
if (mod.is_sys_lib) {
continue;
}
for (mod.c_source_files) |it| {
if (i > 0) {
try w.print(" {s}_ids[{}], cache ++ _paths[{}] ++ \"{s}\"{s},\n", .{"[_][]const u8{", i, i, it, "}"});
} else {
try w.print(" {s}_ids[{}], \".{}/{s}\"{s},\n", .{"[_][]const u8{", i, std.zig.fmtEscapes(mod.clean_path), it, "}"});
}
}
}
}
fn print_csrc_flags_to(w: fs.File.Writer, list: []u.Module) !void {
for (list) |mod, i| {
if (mod.is_sys_lib) {
continue;
}
if (mod.c_source_flags.len == 0 and mod.c_source_files.len == 0) {
continue;
}
try w.print(" pub const @\"{s}\" = {s}", .{mod.id, "&.{"});
for (mod.c_source_flags) |it| {
try w.print("\"{}\",", .{std.zig.fmtEscapes(it)});
}
try w.print("{s};\n", .{"}"});
}
}
fn print_sys_libs_to(w: fs.File.Writer, list: []u.Module, list2: *std.ArrayList([]const u8)) !void {
for (list) |mod| {
if (!mod.is_sys_lib) {
continue;
}
try w.print(" \"{s}\",\n", .{mod.name});
}
}
fn print_pkg_data_to(w: fs.File.Writer, list: *std.ArrayList(u.Module), list2: *std.ArrayList(u.Module)) anyerror!void {
var i: usize = 0;
while (i < list.items.len) : (i += 1) {
const mod = list.items[i];
if (contains_all(mod.deps, list2)) {
try w.print(" pub const _{s} = build.Pkg{{ .name = \"{s}\", .path = cache ++ \"/{}/{s}\", .dependencies = &[_]build.Pkg{{", .{mod.id, mod.name, std.zig.fmtEscapes(mod.clean_path), mod.main});
for (mod.deps) |d| {
if (d.main.len > 0) {
try w.print(" _{s},", .{d.id});
}
}
try w.print(" }} }};\n", .{});
try list2.append(mod);
_ = list.orderedRemove(i);
break;
}
}
if (list.items.len > 0) {
try print_pkg_data_to(w, list, list2);
}
}
/// returns if all of the zig modules in needles are in haystack
fn contains_all(needles: []u.Module, haystack: *std.ArrayList(u.Module)) bool {
for (needles) |item| {
if (item.main.len > 0 and !u.list_contains_gen(u.Module, haystack, item)) {
return false;
}
}
return true;
}
|
src/cmd/fetch.zig
|
const std = @import("std");
const clap = @import("clap");
const container = @import("container.zig");
const stdout = std.io.getStdOut().writer();
const stderr = std.io.getStdErr().writer();
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
const params = comptime [_]clap.Param(clap.Help){
clap.parseParam("-h, --help Display this help and exit") catch unreachable,
clap.parseParam("<COMMAND>...") catch unreachable,
};
var iter = try clap.args.OsIterator.init(allocator);
defer iter.deinit();
var diag = clap.Diagnostic{};
var args = clap.parseEx(clap.Help, ¶ms, &iter, .{
.allocator = allocator,
.diagnostic = &diag,
}) catch |err| {
diag.report(stderr, err) catch {};
return err;
};
defer args.deinit();
if (args.flag("--help"))
return clap.help(stdout, ¶ms);
var tmpdir = try TmpDir("container.").create();
defer tmpdir.cleanup();
const in = std.io.fixedBufferStream("this is a test\n").reader();
const streams = container.ioStreams(in, stdout, stderr);
const c = container.Container(@TypeOf(streams)){
.allocator = allocator,
.argv = args.positionals(),
.argp = &.{},
.bind_mounts = &.{
.{
.target = "nix/store",
.source = "/nix/store",
},
.{
.target = "bin",
.source = "/bin",
},
.{
.target = "usr",
.source = "/usr",
},
},
.dir = tmpdir.dir,
.cwd = "/",
.timeout = 2,
.streams = streams,
};
const res = try c.run();
try stdout.print("{s}\n", .{res});
}
fn TmpDir(comptime prefix: []const u8) type {
return struct {
dir: std.fs.Dir,
parent_dir: std.fs.Dir,
sub_path: [sub_path_len]u8,
const Self = @This();
const random_bytes_count = 12;
const sub_path_len = prefix.len + std.fs.base64_encoder.calcSize(random_bytes_count);
pub fn create() !Self {
var random_bytes: [random_bytes_count]u8 = undefined;
std.crypto.random.bytes(&random_bytes);
var sub_path: [sub_path_len]u8 = undefined;
std.mem.copy(u8, &sub_path, prefix);
_ = std.fs.base64_encoder.encode(sub_path[prefix.len..sub_path.len], &random_bytes);
const tmp = try std.fs.openDirAbsolute("/tmp", .{});
try tmp.makeDir(&sub_path);
const dir = try tmp.openDir(&sub_path, .{});
return Self{
.dir = dir,
.parent_dir = tmp,
.sub_path = sub_path,
};
}
pub fn cleanup(self: *Self) void {
self.dir.close();
self.parent_dir.deleteTree(&self.sub_path) catch {};
self.parent_dir.close();
self.* = undefined;
}
};
}
test {
std.testing.refAllDecls(@This());
}
|
src/main.zig
|
const std = @import("std");
const zlm = @import("zlm");
const block_length = @import("../render/texture_atlas.zig").block_length;
const gl = @import("gl.zig");
const TextureAtlas = @import("texture_atlas.zig").TextureAtlas;
const TextureSpec = @import("../track/piece_renderer.zig").TextureSpec;
const Vertex = @import("vertex.zig").Vertex;
const VertexList = @import("vertex.zig").VertexList;
fn createProgram(allocator: *std.mem.Allocator) !gl.Program {
const vertex_shader = try gl.Shader.init(.vertex);
defer vertex_shader.deinit();
vertex_shader.source(@embedFile("glsl/vertex_shader.glsl"));
try vertex_shader.compile(allocator);
const fragment_shader = try gl.Shader.init(.fragment);
defer fragment_shader.deinit();
fragment_shader.source(@embedFile("glsl/fragment_shader.glsl"));
try fragment_shader.compile(allocator);
const program = try gl.Program.init();
errdefer program.deinit();
program.attach(vertex_shader);
program.attach(fragment_shader);
try program.link(allocator);
return program;
}
pub const Renderer = struct {
// GL shader program
program: gl.Program,
// triangle vertex objects
tris: VertexList,
// line vertex objects
lines: VertexList,
// camera position
camera_pos: zlm.Vec3,
// camera rotation
camera_rot: zlm.Vec2,
// palette we've selected
palette: *[256]zlm.Vec3,
// pointer to texture atlas
texture_atlas: *TextureAtlas,
pub fn init(allocator: *std.mem.Allocator) !Renderer {
const program = try createProgram(allocator);
errdefer program.deinit();
const texture_atlas = try TextureAtlas.init(allocator);
errdefer texture_atlas.deinit(allocator);
const palette = try allocator.create([256]zlm.Vec3);
errdefer allocator.destroy(palette);
const tris = VertexList.init();
errdefer tris.deinit(allocator);
const lines = VertexList.init();
errdefer lines.deinit(allocator);
// for depth buffer
gl.enable(.depth_test);
// for backface culling
gl.enable(.cull_face);
return Renderer{
.program = program,
.tris = tris,
.lines = lines,
.camera_pos = zlm.Vec3.zero,
.camera_rot = zlm.Vec2.zero,
.palette = palette,
.texture_atlas = texture_atlas,
};
}
pub fn deinit(self: *Renderer, allocator: *std.mem.Allocator) void {
self.tris.deinit(allocator);
self.lines.deinit(allocator);
self.texture_atlas.deinit(allocator);
self.program.deinit();
allocator.destroy(self.palette);
}
pub fn updateProjection(self: Renderer, ratio: f32) !void {
self.program.use();
const projection = zlm.Mat4.createPerspective(45 * (std.math.pi / 180.0), ratio, 0.1, 1000);
gl.Program.uniform(try self.program.getUniformLocation("projection"), projection);
}
pub fn draw(self: Renderer) !void {
gl.clear(&.{ .color, .depth });
gl.clearColor(0.5, 0.5, 0.5, 1.0);
self.program.use();
// set view matrix
gl.Program.uniform(try self.program.getUniformLocation("view"), self.getViewMatrix());
// set palette and texture
gl.Program.uniform(try self.program.getUniformLocation("palette"), @as([]const zlm.Vec3, self.palette));
gl.Program.uniform(try self.program.getUniformLocation("tex"), @as(i32, 0));
// calculate forward vector for lighting
gl.Program.uniform(try self.program.getUniformLocation("cameraForward"), self.getCameraForward());
self.tris.renderAll(.triangles);
self.lines.renderAll(.lines);
}
fn getViewMatrix(self: Renderer) zlm.Mat4 {
return zlm.Mat4.createTranslation(self.camera_pos.scale(-1))
.mul(zlm.Mat4.createAngleAxis(zlm.Vec3.unitY, -self.camera_rot.y))
.mul(zlm.Mat4.createAngleAxis(zlm.Vec3.unitX, -self.camera_rot.x));
}
fn getCameraForward(self: Renderer) zlm.Vec3 {
return zlm.Vec3.unitZ.transformPosition(zlm.Mat4.createAngleAxis(zlm.Vec3.unitX, self.camera_rot.x)
.mul(zlm.Mat4.createAngleAxis(zlm.Vec3.unitY, self.camera_rot.y)));
}
pub fn newWriter(self: *Renderer, allocator: *std.mem.Allocator) RendererPieceWriter {
return .{
.allocator = allocator,
.points = .{},
.renderer = self,
};
}
};
pub const RendererPieceWriter = struct {
allocator: *std.mem.Allocator,
points: std.ArrayListUnmanaged(zlm.Vec3),
renderer: *Renderer,
pub fn deinit(self: *RendererPieceWriter) void {
self.points.deinit(self.allocator);
}
pub fn getVertices(self: *RendererPieceWriter, comptime n: comptime_int, points: [n]u8) ![n]zlm.Vec3 {
var result: [n]zlm.Vec3 = undefined;
for (result) |*p, i| {
const j = points[i];
if (j >= self.points.items.len) {
return error.VertexOutOfRange;
}
p.* = self.points.items[j];
}
return result;
}
pub fn addPoint(self: *RendererPieceWriter, point: zlm.Vec3) !void {
try self.points.append(self.allocator, point);
}
pub fn drawLine(self: *RendererPieceWriter, points: [2]u8, normal: zlm.Vec3, colors: [10]u8) !void {
const vertices = try self.getVertices(2, points);
try self.renderer.lines.data.appendSlice(self.allocator, &.{
Vertex.init(vertices[0], normal, colors),
Vertex.init(vertices[1], normal, colors),
});
}
pub fn drawTri(self: *RendererPieceWriter, points: [3]u8, normal: zlm.Vec3, colors: [10]u8) !void {
const vertices = try self.getVertices(3, points);
try self.renderer.tris.data.appendSlice(self.allocator, &.{
Vertex.init(vertices[0], normal, colors),
Vertex.init(vertices[1], normal, colors),
Vertex.init(vertices[2], normal, colors),
});
}
pub fn drawTexturedTri(self: *RendererPieceWriter, points: [3]u8, normal: zlm.Vec3, spec: TextureSpec, uvs: [3]u2) !void {
const vertices = try self.getVertices(3, points);
// TODO clean
const top_left = try self.renderer.texture_atlas.get(self.allocator, spec);
const w = @intToFloat(f32, @as(u4, 1) << spec.width) / block_length;
const h = @intToFloat(f32, @as(u4, 1) << spec.height) / block_length;
const uv_coords = if (spec.reversed) [_]zlm.Vec2{
top_left.add(zlm.vec2(w, 0)),
top_left,
top_left.add(zlm.vec2(0, h)),
top_left.add(zlm.vec2(w, h)),
} else [_]zlm.Vec2{
top_left,
top_left.add(zlm.vec2(w, 0)),
top_left.add(zlm.vec2(w, h)),
top_left.add(zlm.vec2(0, h)),
};
try self.renderer.tris.data.appendSlice(self.allocator, &.{
Vertex.initUV(vertices[0], normal, spec.start, uv_coords[uvs[0]]),
Vertex.initUV(vertices[1], normal, spec.start, uv_coords[uvs[1]]),
Vertex.initUV(vertices[2], normal, spec.start, uv_coords[uvs[2]]),
});
}
pub fn endShape(self: *RendererPieceWriter) void {
self.points.clearAndFree(self.allocator);
}
};
|
src/render/renderer.zig
|
const ImageReader = zigimg.ImageReader;
const ImageSeekStream = zigimg.ImageSeekStream;
const PixelFormat = zigimg.PixelFormat;
const assert = std.debug.assert;
const color = zigimg.color;
const errors = zigimg.errors;
const pcx = zigimg.pcx;
const std = @import("std");
const testing = std.testing;
const zigimg = @import("zigimg");
usingnamespace @import("../helpers.zig");
test "PCX bpp1 (linear)" {
const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/pcx/test-bpp1.pcx");
defer file.close();
var stream_source = std.io.StreamSource{ .file = file };
var pcxFile = pcx.PCX{};
var pixelsOpt: ?color.ColorStorage = null;
try pcxFile.read(zigimg_test_allocator, stream_source.reader(), stream_source.seekableStream(), &pixelsOpt);
defer {
if (pixelsOpt) |pixels| {
pixels.deinit(zigimg_test_allocator);
}
}
expectEq(pcxFile.width, 27);
expectEq(pcxFile.height, 27);
expectEq(pcxFile.pixel_format, PixelFormat.Bpp1);
testing.expect(pixelsOpt != null);
if (pixelsOpt) |pixels| {
testing.expect(pixels == .Bpp1);
expectEq(pixels.Bpp1.indices[0], 0);
expectEq(pixels.Bpp1.indices[15], 1);
expectEq(pixels.Bpp1.indices[18], 1);
expectEq(pixels.Bpp1.indices[19], 1);
expectEq(pixels.Bpp1.indices[20], 1);
expectEq(pixels.Bpp1.indices[22 * 27 + 11], 1);
const palette0 = pixels.Bpp1.palette[0].toIntegerColor8();
expectEq(palette0.R, 102);
expectEq(palette0.G, 90);
expectEq(palette0.B, 155);
const palette1 = pixels.Bpp1.palette[1].toIntegerColor8();
expectEq(palette1.R, 115);
expectEq(palette1.G, 137);
expectEq(palette1.B, 106);
}
}
test "PCX bpp4 (linear)" {
const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/pcx/test-bpp4.pcx");
defer file.close();
var stream_source = std.io.StreamSource{ .file = file };
var pcxFile = pcx.PCX{};
var pixelsOpt: ?color.ColorStorage = null;
try pcxFile.read(zigimg_test_allocator, stream_source.reader(), stream_source.seekableStream(), &pixelsOpt);
defer {
if (pixelsOpt) |pixels| {
pixels.deinit(zigimg_test_allocator);
}
}
expectEq(pcxFile.width, 27);
expectEq(pcxFile.height, 27);
expectEq(pcxFile.pixel_format, PixelFormat.Bpp4);
testing.expect(pixelsOpt != null);
if (pixelsOpt) |pixels| {
testing.expect(pixels == .Bpp4);
expectEq(pixels.Bpp4.indices[0], 1);
expectEq(pixels.Bpp4.indices[1], 9);
expectEq(pixels.Bpp4.indices[2], 0);
expectEq(pixels.Bpp4.indices[3], 0);
expectEq(pixels.Bpp4.indices[4], 4);
expectEq(pixels.Bpp4.indices[14 * 27 + 9], 6);
expectEq(pixels.Bpp4.indices[25 * 27 + 25], 7);
const palette0 = pixels.Bpp4.palette[0].toIntegerColor8();
expectEq(palette0.R, 0x5e);
expectEq(palette0.G, 0x37);
expectEq(palette0.B, 0x97);
const palette15 = pixels.Bpp4.palette[15].toIntegerColor8();
expectEq(palette15.R, 0x60);
expectEq(palette15.G, 0xb5);
expectEq(palette15.B, 0x68);
}
}
test "PCX bpp8 (linear)" {
const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/pcx/test-bpp8.pcx");
defer file.close();
var stream_source = std.io.StreamSource{ .file = file };
var pcxFile = pcx.PCX{};
var pixelsOpt: ?color.ColorStorage = null;
try pcxFile.read(zigimg_test_allocator, stream_source.reader(), stream_source.seekableStream(), &pixelsOpt);
defer {
if (pixelsOpt) |pixels| {
pixels.deinit(zigimg_test_allocator);
}
}
expectEq(pcxFile.width, 27);
expectEq(pcxFile.height, 27);
expectEq(pcxFile.pixel_format, PixelFormat.Bpp8);
testing.expect(pixelsOpt != null);
if (pixelsOpt) |pixels| {
testing.expect(pixels == .Bpp8);
expectEq(pixels.Bpp8.indices[0], 37);
expectEq(pixels.Bpp8.indices[3 * 27 + 15], 60);
expectEq(pixels.Bpp8.indices[26 * 27 + 26], 254);
const palette0 = pixels.Bpp8.palette[0].toIntegerColor8();
expectEq(palette0.R, 0x46);
expectEq(palette0.G, 0x1c);
expectEq(palette0.B, 0x71);
const palette15 = pixels.Bpp8.palette[15].toIntegerColor8();
expectEq(palette15.R, 0x41);
expectEq(palette15.G, 0x49);
expectEq(palette15.B, 0x30);
const palette219 = pixels.Bpp8.palette[219].toIntegerColor8();
expectEq(palette219.R, 0x61);
expectEq(palette219.G, 0x8e);
expectEq(palette219.B, 0xc3);
}
}
test "PCX bpp24 (planar)" {
const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/pcx/test-bpp24.pcx");
defer file.close();
var stream_source = std.io.StreamSource{ .file = file };
var pcxFile = pcx.PCX{};
var pixelsOpt: ?color.ColorStorage = null;
try pcxFile.read(zigimg_test_allocator, stream_source.reader(), stream_source.seekableStream(), &pixelsOpt);
defer {
if (pixelsOpt) |pixels| {
pixels.deinit(zigimg_test_allocator);
}
}
expectEq(pcxFile.header.planes, 3);
expectEq(pcxFile.header.bpp, 8);
expectEq(pcxFile.width, 27);
expectEq(pcxFile.height, 27);
expectEq(pcxFile.pixel_format, PixelFormat.Rgb24);
testing.expect(pixelsOpt != null);
if (pixelsOpt) |pixels| {
testing.expect(pixels == .Rgb24);
expectEq(pixels.Rgb24[0].R, 0x34);
expectEq(pixels.Rgb24[0].G, 0x53);
expectEq(pixels.Rgb24[0].B, 0x9f);
expectEq(pixels.Rgb24[1].R, 0x32);
expectEq(pixels.Rgb24[1].G, 0x5b);
expectEq(pixels.Rgb24[1].B, 0x96);
expectEq(pixels.Rgb24[26].R, 0xa8);
expectEq(pixels.Rgb24[26].G, 0x5a);
expectEq(pixels.Rgb24[26].B, 0x78);
expectEq(pixels.Rgb24[27].R, 0x2e);
expectEq(pixels.Rgb24[27].G, 0x54);
expectEq(pixels.Rgb24[27].B, 0x99);
expectEq(pixels.Rgb24[26 * 27 + 26].R, 0x88);
expectEq(pixels.Rgb24[26 * 27 + 26].G, 0xb7);
expectEq(pixels.Rgb24[26 * 27 + 26].B, 0x55);
}
}
|
tests/formats/pcx_test.zig
|
pub fn Set(comptime T: type) type {
return struct {
const Self = @This();
const Storage = @IntType(false, @memberCount(T));
data: Storage,
pub fn empty() Self {
return Self {
.data = Storage(0),
};
}
pub fn universal() Self {
return Self {
.data = ~Storage(0),
};
}
pub fn incl(self: *Self, x: T) void {
// @ptrCast([*]u1, &self.data)[@enumToInt(x)] = 1;
self.data |= Storage(1) << @enumToInt(x);
}
pub fn excl(self: *Self, x: T) void {
// @ptrCast([*]u1, &self.data)[@enumToInt(x)] = 0;
self.data &= ~(Storage(1) << @enumToInt(x));
}
pub fn card(self: Self) usize {
return @intCast(usize, @popCount(self.data));
}
pub fn inSet(self: Self, x: T) bool {
// return @ptrCast([*]const u1, &self.data)[@enumToInt(x)] == 1;
return ((self.data >> @enumToInt(x)) & Storage(1)) == Storage(1);
}
pub fn setEqual(self: Self, x: Self) bool {
return self.data == x.data;
}
pub fn setSubset(self: Self, x: Self, proper: bool) bool {
if (proper and self.setEqual(x)) {
return false;
} else {
return (self.data & x.data) == self.data;
}
}
pub fn setUnion(self: Self, x: Self) Self {
return Self {
.data = self.data | x.data,
};
}
pub fn setDifference(self: Self, x: Self) Self {
return Self {
.data = (self.data ^ x.data) & self.data,
};
}
pub fn setSymDifference(self: Self, x: Self) Self {
return Self {
.data = (self.data ^ x.data),
};
}
pub fn setIntersect(self: Self, x: Self) Self {
return Self {
.data = self.data & x.data,
};
}
pub fn setComplement(self: Self) Self {
return Self {
.data = ~self.data,
};
}
};
}
test "Set" {
const std = @import("std");
const debug = std.debug;
const assert = debug.assert;
const Edges = enum {
Top,
Right,
Bottom,
Left,
};
var set1 = Set(Edges).empty();
set1.incl(Edges.Top);
set1.incl(Edges.Right);
assert(set1.card() == 2);
var set2 = Set(Edges).empty();
set2.incl(Edges.Bottom);
set2.incl(Edges.Left);
assert(set2.card() == 2);
var set3 = set1.setUnion(set2);
assert(set3.card() == 4);
assert(set3.setIntersect(set2).card() == 2);
assert(set3.setDifference(set1).card() == 2);
assert(set3.inSet(Edges.Top));
}
test "Set (comptime)" {
const std = @import("std");
const debug = std.debug;
const assert = debug.assert;
const Edges = enum {
Top,
Right,
Bottom,
Left,
};
comptime {
var set1 = Set(Edges).empty();
set1.incl(Edges.Top);
set1.incl(Edges.Right);
assert(set1.card() == 2);
var set2 = Set(Edges).empty();
set2.incl(Edges.Bottom);
set2.incl(Edges.Left);
assert(set2.card() == 2);
var set3 = set1.setUnion(set2);
assert(set3.card() == 4);
assert(set3.setIntersect(set2).card() == 2);
assert(set3.setDifference(set1).card() == 2);
assert(set3.inSet(Edges.Top));
}
}
|
src/index.zig
|
const std = @import("std");
const debug = std.debug;
const mem = std.mem;
const testing = std.testing;
// TODO: If we get functions with capture one day, then "comptime nextFn fn (&Context) ?Result" wont work, because then those
// can't be used. We could store the function in the iterator. The iterator will then just grow a little in size every
// time you construct iterators from other iterators.
/// A generic iterator which uses ::nextFn to iterate over a ::TContext.
pub fn Iterator(comptime TContext: type, comptime TResult: type, comptime nextFn: fn (*TContext) ?TResult) type {
return struct {
const Result = TResult;
const Context = TContext;
const Self = @This();
context: Context,
pub fn init(context: Context) Self {
return Self{ .context = context };
}
pub fn next(it: *Self) ?Result {
return nextFn(&it.context);
}
/// NOTE: append we can do with no allocations, because we can make a new iterator type
/// and store the last element in its context.
pub fn append(it: Self, item: Result) void {
comptime @panic("TODO: Implement append!");
}
pub fn concat(it: Self, other: var) ConcatIterator(@TypeOf(other)) {
const OtherIterator = @TypeOf(other);
return ConcatIterator(OtherIterator).init(IteratorPair(OtherIterator){ .it1 = it, .it2 = other });
}
pub fn intersect(it: Self, other: var) void {
comptime @panic("TODO: Implement except!");
}
/// NOTE: prepend we can do with no allocations, because we can make a new iterator type
/// and store the last element in its context.
pub fn prepend(it: Self, item: Result) void {
comptime @panic("TODO: Implement append!");
}
pub fn select(it: Self, comptime SelectResult: type, comptime selector: fn (Result) SelectResult) SelectIterator(SelectResult, selector) {
return SelectIterator(SelectResult, selector).init(it.context);
}
pub fn skip(it: Self, count: u64) Self {
var res = it;
var i = @as(u64, 0);
while (i < count) : (i += 1) {
_ = res.next() orelse return res;
}
return res;
}
pub fn take(it: Self, count: u64) TakeIterator() {
return TakeIterator().init(TakeContext{ .it = it, .count = count });
}
pub fn where(it: Self, comptime predicate: fn (Result) bool) WhereIterator(predicate) {
return WhereIterator(predicate).init(it.context);
}
pub fn zip(it: Self, other: var) ZipIterator(@TypeOf(other)) {
const OtherIterator = @TypeOf(other);
return ZipIterator(OtherIterator).init(IteratorPair(OtherIterator){ .it1 = it, .it2 = other });
}
fn IteratorPair(comptime OtherIterator: type) type {
return struct {
it1: Self,
it2: OtherIterator,
};
}
fn ConcatIterator(comptime OtherIterator: type) type {
const OtherResult = @TypeOf(OtherIterator.next).ReturnType.Child;
return Iterator(IteratorPair(OtherIterator), Result, struct {
fn whereNext(context: *IteratorPair(OtherIterator)) ?Result {
return context.it1.next() orelse {
return context.it2.next();
};
}
}.whereNext);
}
fn SelectIterator(comptime SelectResult: type, comptime selector: fn (Result) SelectResult) type {
return Iterator(Context, SelectResult, struct {
fn selectNext(context: *Context) ?SelectResult {
const item = nextFn(context) orelse return null;
return selector(item);
}
}.selectNext);
}
const TakeContext = struct {
it: Self,
count: u64,
};
fn TakeIterator() type {
return Iterator(TakeContext, Result, struct {
fn takeNext(context: *TakeContext) ?Result {
if (context.count == 0) return null;
context.count -= 1;
return context.it.next();
}
}.takeNext);
}
fn WhereIterator(comptime predicate: fn (Result) bool) type {
return Iterator(Context, Result, struct {
fn whereNext(context: *Context) ?Result {
while (nextFn(context)) |item| {
if (predicate(item)) return item;
}
return null;
}
}.whereNext);
}
fn ZipIterator(comptime OtherIterator: type) type {
const OtherResult = @TypeOf(OtherIterator.next).ReturnType.Child;
const ZipPair = struct {
first: Result,
second: OtherResult,
};
return Iterator(IteratorPair(OtherIterator), ZipPair, struct {
fn whereNext(context: *IteratorPair(OtherIterator)) ?ZipPair {
const first = context.it1.next() orelse return null;
const second = context.it2.next() orelse return null;
return ZipPair{ .first = first, .second = second };
}
}.whereNext);
}
};
}
pub fn SliceIterator(comptime T: type) type {
const NextFn = struct {
fn next(context: *[]const T) ?T {
if (context.len != 0) {
defer context.* = (context.*)[1..];
return (context.*)[0];
}
return null;
}
};
return Iterator([]const T, T, NextFn.next);
}
pub fn SliceMutableIterator(comptime T: type) type {
const NextFn = struct {
fn next(context: *[]T) ?*T {
if (context.len != 0) {
defer context.* = (context.*)[1..];
return &(context.*)[0];
}
return null;
}
};
return Iterator([]T, *T, NextFn.next);
}
fn RangeIterator(comptime T: type) type {
const RangeContext = struct {
current: T,
count: T,
step: T,
};
const NextFn = struct {
fn next(context: *RangeContext) ?T {
if (context.count == 0) return null;
defer context.count -= 1;
defer context.current += context.step;
return context.current;
}
};
return Iterator(RangeContext, T, NextFn.next);
}
pub fn range(comptime T: type, start: T, count: T, step: T) RangeIterator(T) {
const Context = RangeIterator(T).Context;
return RangeIterator(T).init(Context{ .current = start, .count = count, .step = step });
}
fn RepeatIterator(comptime T: type) type {
const NextFn = struct {
fn next(context: *T) ?T {
return context.*;
}
};
return Iterator(T, T, NextFn.next);
}
pub fn repeat(comptime T: type, v: T) RepeatIterator(T) {
return RepeatIterator(T).init(v);
}
fn EmptyIterator(comptime T: type) type {
const NextFn = struct {
fn next(context: *u8) ?T {
return null;
}
};
// TODO: The context can't be "void" because of https://github.com/zig-lang/zig/issues/838
return Iterator(u8, T, NextFn.next);
}
pub fn empty(comptime T: type) EmptyIterator(T) {
return EmptyIterator(T).init(0);
}
pub fn aggregate(it: var, func: fn (@TypeOf(it).Result, @TypeOf(it).Result) @TypeOf(it).Result) ?@TypeOf(it).Result {
return aggregateAcc(it, it.next() orelse return null, @TypeOf(it.*).Result, func);
}
pub fn aggregateAcc(it: var, acc: var, func: fn (@TypeOf(acc), @TypeOf(it).Result) @TypeOf(acc)) ?@TypeOf(acc) {
var _it = it;
var result = acc;
while (_it.next()) |item| {
result = func(result, item);
}
return result;
}
pub fn all(it: var, predicate: fn (@TypeOf(it).Result) bool) bool {
var _it = it;
while (_it.next()) |item| {
if (!predicate(item)) return false;
}
return true;
}
pub fn any(it: var, predicate: fn (@TypeOf(it).Result) bool) bool {
var _it = it;
while (_it.next()) |item| {
if (predicate(item)) return true;
}
return false;
}
pub fn countIf(it: var, predicate: fn (@TypeOf(it).Result) bool) u64 {
var _it = it;
var res = @as(u64, 0);
while (_it.next()) |item| {
if (predicate(item)) res += 1;
}
return res;
}
test "iterators.SliceIterator" {
const data = "abacad";
var it = SliceIterator(u8).init(data);
var i = @as(usize, 0);
while (it.next()) |item| : (i += 1) {
testing.expectEqual(data[i], item);
}
testing.expectEqual(data.len, i);
}
test "iterators.SliceMutableIterator" {
var data = "abacac".*;
const res = "bcbdbd";
var it = SliceMutableIterator(u8).init(data[0..]);
while (it.next()) |item| {
item.* += 1;
}
testing.expectEqualSlices(u8, &data, res);
}
test "iterators.range" {
const res = "abcd";
var it = range(u8, 'a', 4, 1);
var i = @as(usize, 0);
while (it.next()) |item| : (i += 1) {
testing.expectEqual(res[i], item);
}
testing.expectEqual(res.len, i);
}
test "iterators.repeat" {
var it = repeat(u64, 3);
var i = @as(usize, 0);
while (it.next()) |item| : (i += 1) {
testing.expectEqual(@as(u64, 3), item);
if (i == 10) break;
}
}
test "iterators.empty" {
var it = empty(u8);
var i = @as(usize, 0);
while (it.next()) |item| : (i += 1) {
testing.expect(false);
}
testing.expectEqual(@as(usize, 0), i);
}
test "iterators.aggregateAcc" {
const data = "abacad";
const countA = struct {
fn f(acc: u64, char: u8) u64 {
return acc + @boolToInt(char == 'a');
}
}.f;
testing.expectEqual(@as(u64, 3), aggregateAcc(SliceIterator(u8).init(data), @as(u64, 0), countA).?);
}
test "iterators.all" {
const data1 = "aaaa";
const data2 = "abaa";
const isA = struct {
fn f(char: u8) bool {
return char == 'a';
}
}.f;
testing.expect(all(SliceIterator(u8).init(data1), isA));
testing.expect(!all(SliceIterator(u8).init(data2), isA));
}
test "iterators.any" {
const data1 = "bbbb";
const data2 = "bbab";
const isA = struct {
fn f(char: u8) bool {
return char == 'a';
}
}.f;
testing.expect(!any(SliceIterator(u8).init(data1), isA));
testing.expect(any(SliceIterator(u8).init(data2), isA));
}
test "iterators.countIf" {
const data = "abab";
const isA = struct {
fn f(char: u8) bool {
return char == 'a';
}
}.f;
testing.expectEqual(@as(usize, 2), countIf(SliceIterator(u8).init(data), isA));
}
test "iterators.SliceIterator" {
const data = "abc";
var it = SliceIterator(u8).init(data);
var i: usize = 0;
while (it.next()) |item| : (i += 1) {
testing.expectEqual(data[i], item);
}
testing.expectEqual(data.len, i);
}
test "iterators.append: TODO" {}
test "iterators.concat" {
const data1 = "abc";
const data2 = "defg";
const it1 = SliceIterator(u8).init(data1);
const it2 = SliceIterator(u8).init(data2);
var concatted = it1.concat(it2);
var i: usize = 0;
while (concatted.next()) |item| : (i += 1) {
if (i < data1.len)
testing.expectEqual(data1[i], item)
else
testing.expectEqual(data2[i - data1.len], item);
}
testing.expectEqual(data1.len + data2.len, i);
}
test "iterators.except: TODO" {}
test "iterators.intersect: TODO" {}
test "iterators.prepend: TODO" {}
test "iterators.select" {
const data = [_]f64{ 1.5, 2.5, 3.5 };
const toI64 = struct {
fn f(i: f64) i64 {
return @floatToInt(i64, i);
}
}.f;
var it = SliceIterator(f64).init(&data).select(i64, toI64);
var i: usize = 0;
while (it.next()) |item| : (i += 1) {
testing.expectEqual(@floatToInt(i64, data[i]), item);
}
testing.expectEqual(data.len, i);
}
test "iterators.skip" {
const data = "abcd";
const res = "cd";
var it = SliceIterator(u8).init(data).skip(2);
var i: usize = 0;
while (it.next()) |item| : (i += 1) {
testing.expectEqual(res[i], item);
}
testing.expectEqual(res.len, i);
}
test "iterators.skipWhile: TODO" {}
test "iterators.take" {
const data = "abcd";
const res = "ab";
var it = SliceIterator(u8).init(data).take(2);
var i: usize = 0;
while (it.next()) |item| : (i += 1) {
testing.expectEqual(res[i], item);
}
testing.expectEqual(res.len, i);
}
test "iterators.takeWhile: TODO" {}
test "iterators.where" {
const data = "abc";
const res = "ac";
const isB = struct {
fn f(i: u8) bool {
return i != 'b';
}
}.f;
var it = SliceIterator(u8).init(data).where(isB);
var i: usize = 0;
while (it.next()) |item| : (i += 1) {
testing.expectEqual(res[i], item);
}
testing.expectEqual(res.len, i);
}
test "iterators.zip" {
const data1 = "abc";
const data2 = "defg";
const it1 = SliceIterator(u8).init(data1);
const it2 = SliceIterator(u8).init(data2);
var zipped = it1.zip(it2);
var i: usize = 0;
while (zipped.next()) |item| : (i += 1) {
testing.expectEqual(data1[i], item.first);
testing.expectEqual(data2[i], item.second);
}
testing.expectEqual(data1.len, i);
}
|
fun/iterators.zig
|
const std = @import("std");
const builtin = std.builtin;
const debug = std.debug;
const heap = std.heap;
const mem = std.mem;
const process = std.process;
/// An example of what methods should be implemented on an arg iterator.
pub const ExampleArgIterator = struct {
const Error = error{};
pub fn next(iter: *ExampleArgIterator) Error!?[]const u8 {
return "2";
}
};
/// An argument iterator which iterates over a slice of arguments.
/// This implementation does not allocate.
pub const SliceIterator = struct {
const Error = error{};
args: []const []const u8,
index: usize = 0,
pub fn next(iter: *SliceIterator) Error!?[]const u8 {
if (iter.args.len <= iter.index)
return null;
defer iter.index += 1;
return iter.args[iter.index];
}
};
test "clap.args.SliceIterator" {
const args = &[_][]const u8{ "A", "BB", "CCC" };
var iter = SliceIterator{ .args = args };
for (args) |a| {
const b = try iter.next();
debug.assert(mem.eql(u8, a, b.?));
}
}
/// An argument iterator which wraps the ArgIterator in ::std.
/// On windows, this iterator allocates.
pub const OsIterator = struct {
const Error = process.ArgIterator.NextError;
arena: heap.ArenaAllocator,
args: process.ArgIterator,
/// The executable path (this is the first argument passed to the program)
/// TODO: Is it the right choice for this to be null? Maybe `init` should
/// return an error when we have no exe.
exe_arg: ?[]const u8,
pub fn init(allocator: *mem.Allocator) Error!OsIterator {
var res = OsIterator{
.arena = heap.ArenaAllocator.init(allocator),
.args = process.args(),
.exe_arg = undefined,
};
res.exe_arg = try res.next();
return res;
}
pub fn deinit(iter: *OsIterator) void {
iter.arena.deinit();
}
pub fn next(iter: *OsIterator) Error!?[]const u8 {
if (builtin.os.tag == .windows) {
return try iter.args.next(&iter.arena.allocator) orelse return null;
} else {
return iter.args.nextPosix();
}
}
};
|
clap/args.zig
|
const std = @import("std");
const builtin = @import("std").builtin;
const kprint = @import("kprint.zig");
const kernel_elf = @import("kernel_elf.zig");
var kernel_panic_allocator_bytes: [5 * 1024 * 1024]u8 = undefined;
var kernel_panic_allocator_state = std.heap.FixedBufferAllocator.init(kernel_panic_allocator_bytes[0..]);
const kernel_panic_allocator = kernel_panic_allocator_state.allocator();
fn dumpStackTrace(dwarf_info: *std.dwarf.DwarfInfo, stack_trace: *builtin.StackTrace) !void {
try std.dwarf.openDwarfDebugInfo(dwarf_info, kernel_panic_allocator);
var frame_index: usize = 0;
var frames_left: usize = std.math.min(stack_trace.index, stack_trace.instruction_addresses.len);
while (frames_left != 0) : ({
frames_left -= 1;
frame_index = (frame_index + 1) % stack_trace.instruction_addresses.len;
}) {
const return_address = stack_trace.instruction_addresses[frame_index];
var compile_unit = dwarf_info.findCompileUnit(return_address) catch {
kprint.write("{: >3} ? ?:? ??? Line info not available ???\r", .{frames_left});
continue;
};
if (dwarf_info.getLineNumberInfo(compile_unit.*, return_address)) |line_info| {
kprint.write("{: >3} {x:0>16} {s}:{}:{}\r", .{
frames_left,
return_address,
line_info.file_name,
line_info.line,
line_info.column,
});
} else |_| {
kprint.write("{: >3} {x:0>16} ?:? ??? Line info not available ???\r", .{ frames_left, return_address });
}
}
}
fn extractDwarfInfo(kernel: *kernel_elf.KernelElf) !std.dwarf.DwarfInfo {
var section_headers_arr: [64]std.elf.Elf64_Shdr = undefined;
var section_headers = section_headers_arr[0..kernel.header.shnum];
// Build array of section headers
var idx: u32 = 0;
var section_headers_iter = kernel.header.section_header_iterator(&kernel.stream);
while (try section_headers_iter.next()) |section| {
section_headers[idx] = section;
idx += 1;
}
const sh_string_table = section_headers[kernel.header.shstrndx];
var str_table_slice = kernel.data[sh_string_table.sh_offset..(sh_string_table.sh_offset + sh_string_table.sh_size)];
var debug_info: []const u8 = undefined;
var debug_str: []const u8 = undefined;
var debug_line: []const u8 = undefined;
var debug_ranges: []const u8 = undefined;
var debug_abbrev: []const u8 = undefined;
for (section_headers) |section| {
var sh_name_str = std.mem.span(@ptrCast([*:0]u8, &str_table_slice[section.sh_name]));
if (std.mem.eql(u8, sh_name_str, ".debug_info")) {
debug_info = kernel.data[section.sh_offset..(section.sh_offset + section.sh_size)];
}
if (std.mem.eql(u8, sh_name_str, ".debug_str")) {
debug_str = kernel.data[section.sh_offset..(section.sh_offset + section.sh_size)];
}
if (std.mem.eql(u8, sh_name_str, ".debug_line")) {
debug_line = kernel.data[section.sh_offset..(section.sh_offset + section.sh_size)];
}
if (std.mem.eql(u8, sh_name_str, ".debug_ranges")) {
debug_ranges = kernel.data[section.sh_offset..(section.sh_offset + section.sh_size)];
}
if (std.mem.eql(u8, sh_name_str, ".debug_abbrev")) {
debug_abbrev = kernel.data[section.sh_offset..(section.sh_offset + section.sh_size)];
}
}
//FIXME How to check we have found everything we need?
return std.dwarf.DwarfInfo{
.endian = std.builtin.Endian.Little,
.debug_info = debug_info,
.debug_abbrev = debug_abbrev,
.debug_str = debug_str,
.debug_line = debug_line,
.debug_ranges = debug_ranges,
.debug_line_str = null,
};
}
var already_panicking: bool = false;
extern fn exit() noreturn;
pub fn handlePanic(msg: []const u8, error_return_trace: ?*builtin.StackTrace) noreturn {
_ = error_return_trace;
if (already_panicking) {
kprint.write("Double panic\r", .{});
while (true) {}
}
already_panicking = true;
printGuru(msg);
var debug_info = extractDwarfInfo(kernel_elf.get()) catch unreachable;
if (error_return_trace) |stack_trace| {
kprint.write("Dumping stack trace\r", .{});
dumpStackTrace(&debug_info, stack_trace) catch unreachable;
} else {
kprint.write("No stack trace available\r", .{});
}
exit();
}
pub fn printGuru(msg: []const u8) void {
kprint.write("+=================+\r", .{});
kprint.write("| GURU MEDITATION |\r", .{});
kprint.write("+=================+\r", .{});
kprint.write("\r", .{});
kprint.write("Message: {s}\r", .{msg});
kprint.write("\r", .{});
}
pub fn printAddress(address:u64) !void {
var debug_info = try extractDwarfInfo(kernel_elf.get());
try std.dwarf.openDwarfDebugInfo(&debug_info, kernel_panic_allocator);
var compile_unit = debug_info.findCompileUnit(address) catch {
kprint.write("0x{x:0>16} ??? ?:? Line info not available ???\r", .{ address });
return;
};
if (debug_info.getLineNumberInfo(compile_unit.*, address)) |line_info| {
kprint.write("0x{x:0>16} {s}:{}:{}\r", .{
address,
line_info.file_name,
line_info.line,
line_info.column,
});
} else |_| {
kprint.write("0x{x:0>16} ?:? ??? Line info not available ???\r", .{ address });
}
}
|
kernel/src/panic.zig
|
const std = @import("std");
const zdf = @import("./src/zdf/src/main.zig");
const templatesPath = "./gitignore/templates";
const filenameWithoutExtension = zdf.utils.filenameWithoutExtension;
fn countFiles(path: []const u8) !usize {
var dir = try std.fs.cwd().openDir(path, .{ .iterate = true });
defer dir.close();
var walker = try dir.walk(std.heap.page_allocator);
defer walker.deinit();
var n: usize = 0;
while (try walker.next()) |entry| {
if (std.mem.eql(u8, std.fs.path.extension(entry.path), ".gitignore")) {
n += 1;
}
}
return n;
}
pub fn build(b: *std.build.Builder) !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = &arena.allocator;
// Standard target options allows the person running `zig build` to choose
// what target to build for. Here we do not override the defaults, which
// means any target is allowed, and the default is native. Other options
// for restricting supported target set are available.
const target = b.standardTargetOptions(.{});
// Standard release options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall.
const mode = b.standardReleaseOptions();
const exe = b.addExecutable("gi", "src/main.zig");
// b.addUserInputOption
exe.addPackagePath("zdf", "./src/zdf/src/main.zig");
exe.setTarget(target);
exe.setBuildMode(mode);
exe.install();
const run_cmd = exe.run();
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
var numFiles = try countFiles(templatesPath);
var dir = try std.fs.cwd().openDir(templatesPath, .{ .iterate = true });
var walker = try dir.walk(allocator);
defer walker.deinit();
// var opts = b.addOptions();
// opts.addOption()
// _ = numFiles;
var files: [][]const u8 = try allocator.alloc([]const u8, numFiles);
var contents: [][]const u8 = try allocator.alloc([]const u8, numFiles);
defer allocator.free(files);
defer allocator.free(contents);
var i: usize = 0;
while (try walker.next()) |entry| {
if (std.mem.eql(u8, std.fs.path.extension(entry.path), ".gitignore")) {
files[i] = try std.mem.dupe(allocator, u8, filenameWithoutExtension(entry.path));
var f = try dir.openFile(entry.basename, .{});
defer f.close();
var content = try f.readToEndAlloc(allocator, 1024 * 1024 * 1024);
contents[i] = content;
i += 1;
}
}
var opts = b.addOptions();
opts.addOption([]const []const u8, "filenames", files);
opts.addOption([]const []const u8, "contents", contents);
exe.addOptions("data", opts);
}
|
build.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const List = std.ArrayList;
const Map = std.AutoHashMap;
const StrMap = std.StringHashMap;
const BitSet = std.DynamicBitSet;
const Str = []const u8;
const int = i64;
const util = @import("util.zig");
const gpa = util.gpa;
const State = struct {
halls: [7]Crab = [_]Crab{ .none } ** 7,
slots: [4][4]Crab,
pub fn isSolved(self: State) bool {
for (self.halls) |c| if (c != .none) return false;
for (self.slots) |slot, i| {
for (slot) |c| if (c.target() != i) return false;
}
return true;
}
pub fn isHallClear(self: @This(), slot: usize, hallpos: usize) bool {
const right = 2 + slot;
if (right < hallpos) {
var start = right;
while (start < hallpos) : (start += 1) {
if (self.halls[start] != .none) return false;
}
}
const left = 1+slot;
if (hallpos < left) {
var start = hallpos + 1;
while (start <= left) : (start += 1) {
if (self.halls[start] != .none) return false;
}
}
return true;
}
pub fn printout(self: @This()) void {
print("{c}{c}.{c}.{c}.{c}.{c}{c}\n {c} {c} {c} {c}\n {c} {c} {c} {c}\n",
.{
self.halls[0].char(), self.halls[1].char(), self.halls[2].char(), self.halls[3].char(),
self.halls[4].char(), self.halls[5].char(), self.halls[6].char(),
self.slots[0][3].char(), self.slots[1][3].char(), self.slots[2][3].char(), self.slots[3][3].char(),
self.slots[0][2].char(), self.slots[1][2].char(), self.slots[2][2].char(), self.slots[3][2].char(),
self.slots[0][1].char(), self.slots[1][1].char(), self.slots[2][1].char(), self.slots[3][1].char(),
self.slots[0][0].char(), self.slots[1][0].char(), self.slots[2][0].char(), self.slots[3][0].char(),
},
);
}
};
const hallway_costs = [4][7]u32{
.{ 3, 2, 2, 4, 6, 8, 9 },
.{ 5, 4, 2, 2, 4, 6, 7 },
.{ 7, 6, 4, 2, 2, 4, 5 },
.{ 9, 8, 6, 4, 2, 2, 3 },
};
const Crab = enum {
none, a, b, c, d,
pub fn cost(self: @This()) u32 {
return ([_]u32{ 0, 1, 10, 100, 1000 })[@enumToInt(self)];
}
pub fn target(self: @This()) usize {
return @enumToInt(self) - 1;
}
pub fn char(self: @This()) u8 {
return ".ABCD"[@enumToInt(self)];
}
};
const QueueEnt = struct {
state: State,
cost: u32,
pub fn order(_: void, a: @This(), b: @This()) std.math.Order {
return std.math.order(a.cost, b.cost);
}
};
const Queue = std.PriorityDequeue(QueueEnt, void, QueueEnt.order);
pub fn main() !void {
var timer = try std.time.Timer.start();
//#############
//#...........#
//###B#B#C#D###
// #D#A#A#C#
// #########
const part1 = try findBestSolution(.{ .slots = .{
.{ .a, .a, .d, .b },
.{ .b, .b, .a, .b },
.{ .c, .c, .a, .c },
.{ .d, .d, .c, .d },
}});
const p1_time = timer.lap();
const part2 = try findBestSolution(.{ .slots = .{
.{ .d, .d, .d, .b },
.{ .a, .b, .c, .b },
.{ .a, .a, .b, .c },
.{ .c, .c, .a, .d },
}});
const p2_time = timer.lap();
print("part1={}, part2={}\n", .{part1, part2});
print("Times: part1={}, part2={}, total={}\n", .{p1_time, p2_time, p1_time + p2_time});
}
fn findBestSolution(initial_state: State) !u32 {
var costs = Map(State, u32).init(gpa);
defer costs.deinit();
var q = Queue.init(gpa, {});
defer q.deinit();
try q.add(QueueEnt{ .state = initial_state, .cost = 0 });
try costs.put(initial_state, 0);
return while (q.removeMinOrNull()) |it| {
const state = it.state;
if (state.isSolved()) return it.cost;
const actual_cost = costs.get(state).?;
if (it.cost > actual_cost) continue;
//print("\n\n{}:\n", .{it.cost});
//it.state.printout();
for (state.halls) |crab, pos| {
if (crab != .none) {
const target = crab.target();
if (state.isHallClear(target, pos)) {
for (state.slots[target]) |c, i| {
if (c != crab) {
if (c == .none) {
var pred = it;
pred.state.slots[target][i] = crab;
pred.state.halls[pos] = .none;
//pred.state.printout();
const distance = hallway_costs[target][pos] + @intCast(u32, state.slots[target].len - 1 - i);
pred.cost += distance * crab.cost();
const gop = try costs.getOrPut(pred.state);
if (!gop.found_existing or gop.value_ptr.* > pred.cost) {
gop.value_ptr.* = pred.cost;
try q.add(pred);
}
}
break;
}
}
}
}
}
for (state.slots) |slot, idx| {
for (slot) |c| {
if (c != .none and c.target() != idx) break;
} else continue;
var self_cost: u32 = 0;
var self_idx: usize = slot.len;
while (self_idx > 0) : (self_cost += 1) {
self_idx -= 1;
const self = slot[self_idx];
if (self != .none) {
for (state.halls) |c, hi| {
if (c == .none) {
if (state.isHallClear(idx, hi)) {
const distance = hallway_costs[idx][hi] + self_cost;
var pred = it;
pred.state.halls[hi] = slot[self_idx];
pred.state.slots[idx][self_idx] = .none;
//pred.state.printout();
pred.cost += distance * slot[self_idx].cost();
const gop = try costs.getOrPut(pred.state);
if (!gop.found_existing or gop.value_ptr.* > pred.cost) {
gop.value_ptr.* = pred.cost;
try q.add(pred);
} else {
//print("pred state has worse cost\n", .{});
}
} else {
//print("hall not clear from slot {} to {}\n", .{idx, hi});
}
}
}
break;
}
}
}
} else return error.NoSolutionExists;
}
// Useful stdlib functions
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const indexOf = std.mem.indexOfScalar;
const indexOfAny = std.mem.indexOfAny;
const indexOfStr = std.mem.indexOfPosLinear;
const lastIndexOf = std.mem.lastIndexOfScalar;
const lastIndexOfAny = std.mem.lastIndexOfAny;
const lastIndexOfStr = std.mem.lastIndexOfLinear;
const trim = std.mem.trim;
const sliceMin = std.mem.min;
const sliceMax = std.mem.max;
const eql = std.mem.eql;
const parseEnum = std.meta.stringToEnum;
const parseInt = std.fmt.parseInt;
const parseFloat = std.fmt.parseFloat;
const min = std.math.min;
const min3 = std.math.min3;
const max = std.math.max;
const max3 = std.math.max3;
const print = std.debug.print;
const assert = std.debug.assert;
const sort = std.sort.sort;
const asc = std.sort.asc;
const desc = std.sort.desc;
|
src/day23.zig
|
const std = @import("std");
const assert = std.debug.assert;
const util = @import("util.zig");
const testing = std.testing;
pub usingnamespace(@import("types.zig"));
pub const avx = @import("avx.zig");
pub const database = @import("database.zig");
pub const operand = @import("operand.zig");
pub const register = @import("register.zig");
pub const instruction = @import("instruction.zig");
pub const mnemonic = @import("mnemonic.zig");
pub const Immediate = operand.Immediate;
pub const Instruction = instruction.Instruction;
pub const Mnemonic = mnemonic.Mnemonic;
pub const Operand = operand.Operand;
pub const Register = register.Register;
pub const CpuFeature = database.CpuFeature;
const Address = operand.Address;
const Signature = database.Signature;
const InstructionItem = database.InstructionItem;
const warn = if (util.debug) std.debug.warn else util.warnDummy;
pub const Machine = struct {
mode: Mode86,
/// TODO: Used for instructions were the mod field of modrm is ignored by CPU
/// Eg: MOV Control/Debug registers
mod_fill: u2 = 0b11,
/// Used for instructions where reg field of modrm is ignored by CPU, (eg: SETcc)
reg_bits_fill: u3 = 0b000,
// TODO: might not need these
base_fill: u3 = 0b000,
index_fill: u3 = 0b000,
/// For avx when W value is ignoreg (.WIG)
w_fill: u1 = 0b0,
/// For vex/evex for opcodes that ignore L field (LIG)
l_fill: u2 = 0b0,
// prefix_order: ? = null;
cpu_feature_mask: CpuFeature.MaskType = CpuFeature.all_features_mask,
pub fn init(mode: Mode86) Machine {
return Machine {
.mode = mode,
};
}
pub fn init_with_features(mode: Mode86, features: []const CpuFeature) Machine {
return Machine {
.mode = mode,
.cpu_feature_mask = CpuFeature.arrayToMask(features),
};
}
pub fn addressSize(self: Machine) BitSize {
return switch (self.mode) {
.x86_16 => .Bit16,
.x86_32 => .Bit32,
.x64 => .Bit64,
};
}
/// If the operand is a .Reg, convert it to the equivalent .Rm
pub fn coerceRm(self: Machine, op: Operand) Operand {
switch (op) {
.Reg => |reg| return Operand.registerRm(reg),
.RegSae => |reg_sae| return Operand.registerRm(reg_sae.reg),
.Rm => return op,
.RmPred => |rm_pred| return Operand { .Rm = rm_pred.rm },
else => unreachable,
}
}
pub fn encodeRMI(
self: Machine,
instr_item: *const InstructionItem,
enc_ctrl: ?*const EncodingControl,
op_reg: ?*const Operand,
op_rm: ?*const Operand,
imm: ?Immediate,
overides: Overides
) AsmError!Instruction {
const opcode = instr_item.opcode.Op;
var res = Instruction{};
var rex_w: u1 = 0;
const reg = if (op_reg) |r| x: {
break :x r.Reg;
} else if (opcode.reg_bits) |reg_bits| x: {
const fake_reg = @intToEnum(Register, reg_bits + @enumToInt(Register.AX));
break :x fake_reg;
} else x: {
const fake_reg = @intToEnum(Register, self.reg_bits_fill + @enumToInt(Register.AX));
break :x fake_reg;
};
const has_rm = (op_rm != null);
var modrm: operand.ModRmResult = undefined;
if (has_rm) {
const rm = self.coerceRm(op_rm.?.*).Rm;
modrm = try rm.encodeReg(self.mode, reg, overides);
}
res.addCompoundOpcode(opcode);
if (has_rm) {
try res.addPrefixes(instr_item, enc_ctrl, modrm.prefixes, modrm, opcode);
} else {
var prefixes = Prefixes {};
try prefixes.addOverides(self.mode, &rex_w, .None, overides);
try res.addPrefixes(instr_item, enc_ctrl, prefixes, null, opcode);
}
try res.addRexRm(self.mode, rex_w, modrm);
res.addOpcode(opcode);
if (has_rm) {
res.modrm(modrm);
}
if (opcode.hasPostfix()) {
res.addImm8(opcode.getPostfix());
} else if (imm) |im| {
res.addImm(im);
}
return res;
}
/// Encode an instruction where the register number used is added to the opcode.
/// The second operand is an immediate.
///
/// Example opcodes:
///
/// B0+ rb ib MOV r8, imm8 ( 0xB0 + 8 bit register number (8 opcodes))
/// B8+ rw iw MOV r16, imm16 ( 0xB8 + 16/32/64 bit register number (8 opcodes))
///
pub fn encodeOI(
self: Machine,
instr_item: *const InstructionItem,
enc_ctrl: ?*const EncodingControl,
op_reg: ?*const Operand,
imm: ?Immediate,
overides: Overides
) AsmError!Instruction {
const opcode = instr_item.opcode.Op;
var res = Instruction{};
var prefixes = Prefixes {};
var rex_w: u1 = 0;
const reg = switch (op_reg.?.*) {
.Reg => |reg| reg,
else => unreachable,
};
// compute prefixes
try prefixes.addOverides(self.mode, &rex_w, .None, overides);
try res.addPrefixes(instr_item, enc_ctrl, prefixes, null, opcode);
try res.addRex(self.mode, null, reg, overides);
res.addOpcodeRegNum(opcode, reg);
if (imm) |im| {
res.addImm(im);
}
return res;
}
pub fn encodeRMII(
self: Machine,
instr_item: *const InstructionItem,
enc_ctrl: ?*const EncodingControl,
op_reg: ?*const Operand,
op_rm: ?*const Operand,
imm1: Immediate,
imm2: Immediate,
overides: Overides
) AsmError!Instruction {
var res = try self.encodeRMI(instr_item, enc_ctrl, op_reg, op_rm, imm1, overides);
res.addImm(imm2);
return res;
}
pub fn encodeAddress(
self: Machine,
instr_item: *const InstructionItem,
enc_ctrl: ?*const EncodingControl,
op_addr: ?*const Operand,
overides: Overides
) AsmError!Instruction {
const opcode = instr_item.opcode.Op;
var res = Instruction{};
var prefixes = Prefixes {};
var rex_w: u1 = 0;
const addr = op_addr.?.Addr;
// compute prefixes
try prefixes.addOverides(self.mode, &rex_w, .None, overides);
res.addCompoundOpcode(opcode);
try res.addPrefixes(instr_item, enc_ctrl, prefixes, null, opcode);
res.addOpcode(opcode);
res.addAddress(addr);
return res;
}
fn getSpecialAddrSize(op: *const Operand, name: register.RegisterName, seg: *Segment) BitSize {
switch (op.*) {
.Rm => {},
else => return .None,
}
switch (op.Rm) {
// [base_reg16 + index_reg16 + disp0/8/16]
.Mem16 => |mem| {
seg.* = mem.segment;
if (
mem.index == null
or mem.index.?.name() != name
or mem.disp.size != .None
) {
return .None;
} else {
return mem.index.?.bitSize();
}
},
// [reg + disp0/8/32]
.Mem => |mem| {
seg.* = mem.segment;
if (
mem.reg.name() != name
or mem.disp.size != .None
) {
return .None;
} else {
return mem.reg.bitSize();
}
},
else => return .None,
}
}
pub fn encodeMSpecial(
self: Machine,
instr_item: *const InstructionItem,
enc_ctrl: ?*const EncodingControl,
op_1: ?*const Operand,
op_2: ?*const Operand,
overides: Overides,
) AsmError!Instruction {
const mnem = instr_item.mnemonic;
const opcode = instr_item.opcode.Op;
var res = Instruction{};
var addressing_size: BitSize = .None;
var def_seg: Segment = .DefaultSeg;
var overide_seg: Segment = .DefaultSeg;
var di_seg: Segment = .DefaultSeg;
var si_seg: Segment = .DefaultSeg;
const di_op_size = if (op_1) |op_| op_.operandSize() else .None;
const si_op_size = if (op_2) |op_| op_.operandSize() else .None;
const di_addr_size = if (op_1) |op_| getSpecialAddrSize(op_, .DI, &di_seg) else .None;
const si_addr_size = if (op_2) |op_| getSpecialAddrSize(op_, .SI, &si_seg) else .None;
switch (mnem) {
// ES:[DI], __
//
// INS BYTE ES:[(E/R)DI], DX
// INS WORD ES:[(E/R)DI], DX
// INS DWORD ES:[(E/R)DI], DX
//
// STOS BYTE ES:[(E/R)DI], AL
// STOS WORD ES:[(E/R)DI], AX
// STOS DWORD ES:[(E/R)DI], EAX
// STOS QWORD ES:[(E/R)DI], RAX
//
// SCAS BYTE ES:[(E/R)DI], AL
// SCAS WORD ES:[(E/R)DI], AX
// SCAS DWORD ES:[(E/R)DI], EAX
// SCAS QWORD ES:[(E/R)DI], RAX
.SCAS, .STOS, .INS => {
if (
di_addr_size == .None
or (mnem == .INS and si_op_size != .Bit16)
or (mnem != .INS and di_op_size != si_op_size)
) {
return AsmError.InvalidOperand;
}
addressing_size = di_addr_size;
overide_seg = di_seg;
def_seg = .ES;
},
// __, DS:[SI]
//
// OUTS DX, BYTE DS:[(E/R)SI]
// OUTS DX, WORD DS:[(E/R)SI]
// OUTS DX, DWORD DS:[(E/R)SI]
//
// LODS AL, BYTE DS:[(E/R)SI]
// LODS AX, WORD DS:[(E/R)SI]
// LODS EAX, DWORD DS:[(E/R)SI]
// LODS RAX, QWORD DS:[(E/R)SI]
.LODS, .OUTS => {
if (
si_addr_size == .None
or (mnem == .OUTS and di_op_size != .Bit16)
or (mnem != .OUTS and di_op_size != si_op_size)
) {
return AsmError.InvalidOperand;
}
addressing_size = si_addr_size;
overide_seg = si_seg;
def_seg = .DS;
},
// ES:[DI], DS:[SI]
//
// MOVS BYTE ES:[(E/R)DI], BYTE DS:[(E/R)SI]
// MOVS WORD ES:[(E/R)DI], WORD DS:[(E/R)SI]
// MOVS DWORD ES:[(E/R)DI], DWORD DS:[(E/R)SI]
// MOVS QWORD ES:[(E/R)DI], QWORD DS:[(E/R)SI]
//
// CMPS BYTE ES:[(R/E)DI], BYTE DS:[(R/E)SI]
// CMPS WORD ES:[(R/E)DI], WORD DS:[(R/E)SI]
// CMPS DWORD ES:[(R/E)DI], DWORD DS:[(R/E)SI]
// CMPS QWORD ES:[(R/E)DI], QWORD DS:[(R/E)SI]
.CMPS, .MOVS => {
if (
di_addr_size == .None
or si_addr_size == .None
or di_addr_size != si_addr_size
or di_op_size != si_op_size
or !(di_seg == .ES or di_seg == .DefaultSeg)
) {
return AsmError.InvalidOperand;
}
addressing_size = di_addr_size;
overide_seg = si_seg;
def_seg = .DS;
},
// XLAT AL, BYTE DS:[(E/R)BX + AL]
.XLAT => {
const rm = if (op_2) |op_2_| op_2_.Rm else op_1.?.Rm;
def_seg = .DS;
switch (rm) {
.Sib => |sib| {
overide_seg = sib.segment;
if (sib.base == null or sib.index == null) {
return AsmError.InvalidOperand;
} else if (sib.base.?.name() == .BX and sib.index.? == .AL) {
addressing_size = sib.base.?.bitSize();
} else if (sib.base.? == .AL and sib.index.?.name() == .BX) {
addressing_size = sib.index.?.bitSize();
} else {
return AsmError.InvalidOperand;
}
// x86_64 doesn't use a default segment for these instructions
if (self.mode == .x64 and addressing_size == .Bit64) {
def_seg = .DefaultSeg;
}
},
else => return AsmError.InvalidOperand,
}
},
else => unreachable,
}
// compute the prefixes
var prefixes = Prefixes {};
var rex_w: u1 = 0;
if (overide_seg != def_seg) {
prefixes.addSegmentOveride(overide_seg);
}
try prefixes.addOverides(self.mode, &rex_w, addressing_size, overides);
try res.addPrefixes(instr_item, enc_ctrl, prefixes, null, opcode);
try res.rexRaw(self.mode, util.rexValue(rex_w, 0, 0, 0));
res.addOpcode(opcode);
return res;
}
pub fn encodeMOffset(
self: Machine,
instr_item: *const InstructionItem,
enc_ctrl: ?*const EncodingControl,
op_reg: ?*const Operand,
op_moff: ?*const Operand,
overides: Overides
) AsmError!Instruction {
const opcode = instr_item.opcode.Op;
var res = Instruction{};
const reg = op_reg.?.Reg;
const moff = op_moff.?.Addr.MOffset;
// MOffset can only use AL, AX, EAX, RAX
if (reg.number() != Register.AX.number()) {
return AsmError.InvalidOperand;
}
if (moff.disp.bitSize() != self.addressSize()) {
return AsmError.InvalidOperand;
}
var prefixes = Prefixes {};
var rex_w: u1 = 0;
// compute prefixes
{
if (moff.segment != .DefaultSeg) {
prefixes.addSegmentOveride(moff.segment);
}
const addressing_size = moff.disp.bitSize();
try prefixes.addOverides(self.mode, &rex_w, addressing_size, overides);
}
res.addCompoundOpcode(opcode);
try res.addPrefixes(instr_item, enc_ctrl, prefixes, null, opcode);
try res.rexRaw(self.mode, util.rexValue(rex_w, 0, 0, 0));
res.addOpcode(opcode);
switch (moff.disp) {
.Disp16 => |disp| res.addImm16(disp),
.Disp32 => |disp| res.addImm32(disp),
.Disp64 => |disp| res.addImm64(disp),
}
return res;
}
pub fn encodeAvx(
self: Machine,
instr_item: *const InstructionItem,
enc_ctrl: ?*const EncodingControl,
vec1_r: ?*const Operand,
vec2_v: ?*const Operand,
rm_op: ?*const Operand,
vec4_is: ?*const Operand,
imm_op: ?*const Operand,
/// 8 bit displacement multiplier
disp_n: u8,
) AsmError!Instruction {
const avx_opcode = instr_item.opcode.Avx;
var res = Instruction{};
var modrm: operand.ModRmResult = undefined;
var has_modrm: bool = undefined;
if (vec1_r == null and rm_op == null) {
has_modrm = false;
} else if (vec1_r) |v| {
var rm = self.coerceRm(rm_op.?.*).Rm;
rm.scaleAvx512Displacement(disp_n);
const reg = switch (v.*) {
.Reg => v.Reg,
.RegPred => v.RegPred.reg,
.RegSae => v.RegSae.reg,
else => unreachable,
};
modrm = try rm.encodeReg(self.mode, reg, .ZO);
has_modrm = true;
} else {
var rm = self.coerceRm(rm_op.?.*).Rm;
rm.scaleAvx512Displacement(disp_n);
const fake_reg = Register.create(.Bit32, avx_opcode.reg_bits.?);
modrm = try rm.encodeReg(self.mode, fake_reg, .ZO);
has_modrm = true;
}
if (has_modrm) {
try res.addPrefixes(instr_item, enc_ctrl, modrm.prefixes, null, Opcode{});
} else {
try res.addPrefixes(instr_item, enc_ctrl, Prefixes{}, null, Opcode{});
}
const modrm_ptr: ?*const operand.ModRmResult = if (has_modrm) &modrm else null;
const avx_res = try avx_opcode.encode(self, vec1_r, vec2_v, rm_op, modrm_ptr);
try res.addAvx(self.mode, avx_res);
res.addOpcodeByte(avx_opcode.opcode);
if (has_modrm) {
res.modrm(modrm);
}
if (vec4_is) |vec| {
// currently EVEX support for 4 operands is not officialy documented
assert(avx_opcode.encoding != .EVEX);
// imm8[7:4] <- vec_number
var imm8: u8 = 0x00;
const vec_num = vec.Reg.number();
imm8 |= vec_num << 4;
// imm8[3:0] <- immediate payload if present
if (imm_op) |imm| {
const imm_val = imm.Imm.as8();
if (imm_val > 0x0F) {
return AsmError.InvalidImmediate;
}
imm8 |= imm_val << 0;
}
res.addImm8(imm8);
} else if (imm_op) |imm| {
res.addImm(imm.Imm);
}
return res;
}
pub fn build0_ctrl(
self: Machine,
ctrl: EncodingControl,
mnem: Mnemonic
) AsmError!Instruction {
return self.build(&ctrl, mnem, null, null, null, null, null);
}
pub fn build1_ctrl(
self: Machine,
ctrl: EncodingControl,
mnem: Mnemonic,
ops1: Operand
) AsmError!Instruction {
return self.build(&ctrl, mnem, &ops1, null, null, null, null);
}
pub fn build2_ctrl(
self: Machine,
ctrl: EncodingControl,
mnem: Mnemonic,
ops1: Operand,
ops2: Operand
) AsmError!Instruction {
return self.build(&ctrl, mnem, &ops1, &ops2, null, null, null);
}
pub fn build3_ctrl(
self: Machine,
ctrl: EncodingControl,
mnem: Mnemonic,
ops1: Operand,
ops2: Operand,
ops3: Operand
) AsmError!Instruction {
return self.build(&ctrl, mnem, &ops1, &ops2, &ops3, null, null);
}
pub fn build4_ctrl(
self: Machine,
ctrl: EncodingControl,
mnem: Mnemonic,
ops1: Operand,
ops2: Operand,
ops3: Operand,
ops4: Operand
) AsmError!Instruction {
return self.build(&ctrl, mnem, &ops1, &ops2, &ops3, &ops4, null);
}
pub fn build5_ctrl(
self: Machine,
ctrl: EncodingControl,
mnem: Mnemonic,
ops1: Operand,
ops2: Operand,
ops3: Operand,
ops4: Operand,
ops5: Operand,
) AsmError!Instruction {
return self.build(&ctrl, mnem, &ops1, &ops2, &ops3, &ops4, &ops5);
}
pub fn build0_pre(
self: Machine,
prefix: Prefix,
mnem: Mnemonic
) AsmError!Instruction {
const ctrl = EncodingControl.prefix(prefix);
return self.build(&ctrl, mnem, null, null, null, null, null);
}
pub fn build1_pre(
self: Machine,
prefix: Prefix,
mnem: Mnemonic,
ops1: Operand
) AsmError!Instruction {
const ctrl = EncodingControl.prefix(prefix);
return self.build(&ctrl, mnem, &ops1, null, null, null, null);
}
pub fn build2_pre(
self: Machine,
prefix: Prefix,
mnem: Mnemonic,
ops1: Operand,
ops2: Operand
) AsmError!Instruction {
const ctrl = EncodingControl.prefix(prefix);
return self.build(&ctrl, mnem, &ops1, &ops2, null, null, null);
}
pub fn build3_pre(
self: Machine,
prefix: Prefix,
mnem: Mnemonic,
ops1: Operand,
ops2: Operand,
ops3: Operand
) AsmError!Instruction {
const ctrl = EncodingControl.prefix(prefix);
return self.build(&ctrl, mnem, &ops1, &ops2, &ops3, null, null);
}
pub fn build4_pre(
self: Machine,
prefix: Prefix,
mnem: Mnemonic,
ops1: Operand,
ops2: Operand,
ops3: Operand,
ops4: Operand
) AsmError!Instruction {
const ctrl = EncodingControl.prefix(prefix);
return self.build(&ctrl, mnem, &ops1, &ops2, &ops3, &ops4, null);
}
pub fn build5_pre(
self: Machine,
prefix: Prefix,
mnem: Mnemonic,
ops1: Operand,
ops2: Operand,
ops3: Operand,
ops4: Operand,
ops5: Operand,
) AsmError!Instruction {
const ctrl = EncodingControl.prefix(prefix);
return self.build(&ctrl, mnem, &ops1, &ops2, &ops3, &ops4, &ops5);
}
pub fn build0(
self: Machine,
mnem: Mnemonic
) AsmError!Instruction {
return self.build(null, mnem, null, null, null, null, null);
}
pub fn build1(
self: Machine,
mnem: Mnemonic,
ops1: Operand
) AsmError!Instruction {
return self.build(null, mnem, &ops1, null, null, null, null);
}
pub fn build2(
self: Machine,
mnem: Mnemonic,
ops1: Operand,
ops2: Operand
) AsmError!Instruction {
return self.build(null, mnem, &ops1, &ops2, null, null, null);
}
pub fn build3(
self: Machine,
mnem: Mnemonic,
ops1: Operand,
ops2: Operand,
ops3: Operand
) AsmError!Instruction {
return self.build(null, mnem, &ops1, &ops2, &ops3, null, null);
}
pub fn build4(
self: Machine,
mnem: Mnemonic,
ops1: Operand,
ops2: Operand,
ops3: Operand,
ops4: Operand
) AsmError!Instruction {
return self.build(null, mnem, &ops1, &ops2, &ops3, &ops4, null);
}
pub fn build5(
self: Machine,
mnem: Mnemonic,
ops1: Operand,
ops2: Operand,
ops3: Operand,
ops4: Operand,
ops5: Operand,
) AsmError!Instruction {
return self.build(null, mnem, &ops1, &ops2, &ops3, &ops4, &ops5);
}
pub fn build(
self: Machine,
ctrl: ?*const EncodingControl,
mnem: Mnemonic,
ops1: ?*const Operand,
ops2: ?*const Operand,
ops3: ?*const Operand,
ops4: ?*const Operand,
ops5: ?*const Operand,
) AsmError!Instruction {
const sig = database.Signature.fromOperands(ops1, ops2, ops3, ops4, ops5);
// sig.debugPrint();
var i = database.lookupMnemonic(mnem);
while (database.getDatabaseItem(i).mnemonic == mnem) : (i += 1) {
const item = database.getDatabaseItem(i);
// all the opcodes with the same mnemonic are stored adjacent to
// each other. So when we reach the end of this section no point
// looking anymore.
if (item.mnemonic != mnem) {
break;
}
if (Signature.matchTemplate(item.signature, sig)) {
// item.signature.debugPrint();
if (item.hasEdgeCase() and item.matchesEdgeCase(self, ops1, ops2, ops3, ops4, ops5)) {
continue;
}
if (!item.isMachineMatch(self)) {
continue;
}
return item.encode(self, ctrl, ops1, ops2, ops3, ops4, ops5);
}
}
return AsmError.InvalidOperand;
}
};
|
src/x86/machine.zig
|
const std = @import("std");
const TCCErrorFunc = fn (user: ?*c_void, message: [*:0]const u8) callconv(.C) void;
const TCCErrorCode = extern enum {
success = 0,
failed = -1,
};
pub const OutputType = extern enum {
memory = 1,
exe = 2,
dll = 3,
obj = 4,
preprocessor = 5,
};
const TCCRelocateType = extern enum(usize) {
get_size = 0, auto = 1, _
};
extern "C" fn tcc_new() callconv(.C) ?*TinyCC;
extern "C" fn tcc_delete(state: *TinyCC) callconv(.C) void;
extern "C" fn tcc_set_lib_path(state: *TinyCC, path: [*:0]const u8) callconv(.C) void;
extern "C" fn tcc_set_error_func(state: *TinyCC, user: ?*c_void, func: TCCErrorFunc) callconv(.C) void;
extern "C" fn tcc_get_error_func(state: *TinyCC) callconv(.C) ?TCCErrorFunc;
extern "C" fn tcc_get_error_opaque(state: *TinyCC) callconv(.C) ?*c_void;
extern "C" fn tcc_set_options(state: *TinyCC, cmd: [*:0]const u8) callconv(.C) void;
extern "C" fn tcc_add_include_path(state: *TinyCC, path: [*:0]const u8) callconv(.C) TCCErrorCode;
extern "C" fn tcc_add_sysinclude_path(state: *TinyCC, path: [*:0]const u8) callconv(.C) TCCErrorCode;
extern "C" fn tcc_define_symbol(state: *TinyCC, sym: [*:0]const u8, value: ?[*:0]const u8) callconv(.C) void;
extern "C" fn tcc_undefine_symbol(state: *TinyCC, sym: [*:0]const u8) callconv(.C) void;
extern "C" fn tcc_add_file(state: *TinyCC, path: [*:0]const u8) callconv(.C) TCCErrorCode;
extern "C" fn tcc_compile_string(state: *TinyCC, buffer: [*:0]const u8) callconv(.C) TCCErrorCode;
extern "C" fn tcc_set_output_type(state: *TinyCC, output: OutputType) callconv(.C) TCCErrorCode;
extern "C" fn tcc_add_library_path(state: *TinyCC, path: [*:0]const u8) callconv(.C) TCCErrorCode;
extern "C" fn tcc_add_library(state: *TinyCC, name: [*:0]const u8) callconv(.C) TCCErrorCode;
extern "C" fn tcc_add_symbol(state: *TinyCC, name: [*:0]const u8, val: ?*const c_void) callconv(.C) TCCErrorCode;
extern "C" fn tcc_output_file(state: *TinyCC, name: [*:0]const u8) callconv(.C) TCCErrorCode;
extern "C" fn tcc_run(state: *TinyCC, argc: c_int, argv: [*]const [*:0]const u8) callconv(.C) c_int;
extern "C" fn tcc_relocate(state: *TinyCC, ptr: TCCRelocateType) callconv(.C) c_int;
extern "C" fn tcc_get_symbol(state: *TinyCC, name: [*:0]const u8) callconv(.C) ?*c_void;
extern "C" fn tcc_list_symbol(state: *TinyCC, ctx: ?*c_void, func: fn (ctx: ?*c_void, name: [*:0]const u8, val: *c_void) callconv(.C) void) void;
pub const SourceFile = union(enum) {
path: [*:0]const u8,
content: [*:0]const u8,
};
pub const Config = union(enum) {
tccdir: [*:0]const u8,
opt: [*:0]const u8,
library_dir: [*:0]const u8,
library: [*:0]const u8,
include: [*:0]const u8,
system_include: [*:0]const u8,
input: SourceFile,
output: OutputType,
define: struct {
name: [*:0]const u8,
value: ?[*:0]const u8 = null,
},
undefine: [*:0]const u8,
bind: struct {
name: [*:0]const u8,
value: ?*const c_void,
},
};
pub const RelocateAction = union(enum) {
auto,
size,
addr: []u8,
};
pub const TinyCC = opaque {
fn reportError(user: ?*c_void, message: [*:0]const u8) callconv(.C) void {
std.log.scoped(.tcc).err("{s}", .{message});
}
pub fn init() !*@This() {
const ret = tcc_new() orelse return error.FailedToCreateState;
tcc_set_error_func(ret, null, reportError);
return ret;
}
pub fn deinit(self: *@This()) void {
tcc_delete(self);
}
fn throw(code: TCCErrorCode, err: anyerror) !void {
if (code == .failed) return err;
}
pub fn apply(self: *@This(), cfg: Config) !void {
return switch (cfg) {
.tccdir => |dir| tcc_set_lib_path(self, dir),
.opt => |cmd| tcc_set_options(self, cmd),
.library_dir => |dir| throw(tcc_add_library_path(self, dir), error.FailedToAddLibraryPath),
.library => |lib| throw(tcc_add_library(self, lib), error.FailedToAddLibrary),
.include => |dir| throw(tcc_add_include_path(self, dir), error.FailedToAddInclude),
.system_include => |dir| throw(tcc_add_sysinclude_path(self, dir), error.FailedToAddSysInclude),
.input => |source| throw(switch (source) {
.content => |text| tcc_compile_string(self, text),
.path => |path| tcc_add_file(self, path),
}, error.CompileError),
.output => |output| throw(tcc_set_output_type(self, output), error.InvalidOutputType),
.define => |def| tcc_define_symbol(self, def.name, if (def.value) |value| value else null),
.undefine => |undef| tcc_undefine_symbol(self, undef),
.bind => |str| throw(tcc_add_symbol(self, str.name, str.value), error.FailedToBindSymbol),
};
}
pub fn setup(self: *@This()) !void {
var buf = [1]u8{0} ** 2048;
var incbuf = [1]u8{0} ** 2048;
const base = try std.fs.selfExeDirPath(&buf);
const len = base.len;
buf[len] = 0;
try self.apply(.{ .tccdir = buf[0..len :0].ptr });
std.mem.copy(u8, buf[len .. len + "/include".len], "/include");
buf[len + "/include".len] = 0;
try self.apply(.{ .system_include = buf[0 .. len + "/include".len :0].ptr });
try self.apply(.{
.define = .{
.name = "__ALIGN__",
.value = comptime std.fmt.comptimePrint("__attribute__((aligned({})))", .{@sizeOf(usize)}),
},
});
try self.apply(.{ .define = .{ .name = "__TJS__" } });
}
pub fn run(self: *@This(), args: []const [*:0]const u8) c_int {
return tcc_run(self, @intCast(c_int, args.len), args.ptr);
}
pub fn relocate(self: *@This()) !void {
if (tcc_relocate(self, .auto) == -1) return error.FailedToRelocate;
}
pub fn get(self: *@This(), sym: [*:0]const u8) ?*c_void {
return tcc_get_symbol(self, sym);
}
pub fn writeFile(self: *@This(), path: [*:0]const u8) !void {
return throw(tcc_output_file(self, path), error.FailedToWrite);
}
};
|
src/tcc.zig
|
const config = @import("config.zig");
const c = @import("c.zig");
const X = @import("x.zig");
const std = @import("std");
const wm = @import("wm.zig");
const colors = @import("colors.zig");
const commands = @import("commands.zig");
const xdraw = @import("xdraw.zig");
const layouter = @import("layouter.zig");
const warn = std.debug.warn;
const panic = std.debug.panic;
const Allocator = std.mem.Allocator;
pub var xlib = X.Xlib{};
var msgQueue = std.atomic.Queue(i32).init();
var timestring: [16]u8 = undefined;
// TODO: maybe dynamic arrays
pub var manager: wm.WindowManager = wm.WindowManager{};
var bars: [wm.maxWindows]c.Window = undefined;
var barDraws: [wm.maxWindows]xdraw.Draw = undefined;
var colours: colors.Colors = undefined;
pub var layouts: [wm.maxWindows]layouter.Layout = undefined;
var logfile: std.fs.File = undefined;
fn getBar(index: usize) c.Window {
return bars[index];
}
pub fn onConfigureRequest(e: *c.XEvent) void {
var event = e.xconfigurerequest;
var screen = manager.getActiveScreen();
var workspace = screen.getActiveWorkspace();
var changes: c.XWindowChanges = undefined;
if (!workspace.hasWindow(event.window)) {
changes.x = event.x;
changes.y = event.y;
changes.width = event.width;
changes.height = event.height;
changes.border_width = event.border_width;
changes.sibling = event.above;
changes.stack_mode = event.detail;
_ = c.XConfigureWindow(xlib.display, event.window, @intCast(c_uint, event.value_mask), &changes);
_ = c.XSync(xlib.display, 0);
}
}
pub fn onDestroyNotify(e: *c.XEvent) void {
var event = e.xdestroywindow;
var screen = manager.getActiveScreen();
var workspace = screen.getActiveWorkspace();
workspace.removeWindow(event.window);
}
pub fn windowFocus(window: u64) void {
var screen = manager.getActiveScreen();
var workspace = screen.getActiveWorkspace();
var index = workspace.getWindowIndex(window);
if (index >= 0) {
debug("WINDOW FOCUS {}: {}\n", .{ @as(usize, manager.activeScreenIndex), @as(i32, index)});
var oldFocus = workspace.getFocusedWindow();
workspace.focusedWindow = @intCast(u32, index);
var newFocus = workspace.getFocusedWindow();
xlib.focusWindow(newFocus);
xlib.windowSetBorder(oldFocus, getColor(config.COLOR.BLACK), config.borderWidth);
xlib.windowSetBorder(newFocus, getColor(config.COLOR.FOREGROUND_FOCUS_FG), config.borderWidth);
drawBar();
}
}
fn onEnterNotify(e: *c.XEvent) void {
var event = e.xcrossing;
debug("on enter notify {}\n", .{@as(u64, event.window)});
var buffer: [256]u8 = undefined;
if (event.window != xlib.root) {
var screenIndex = manager.getScreenIndexOfWindow(event.window);
manager.activeScreenIndex = @intCast(u32, screenIndex);
debug("onEnterNotify window focus\n", .{});
if (!config.focusOnClick) {
windowFocus(event.window);
}
drawBar();
}
}
fn debug(comptime msg: []const u8, args: var) void {
//var buf: [256]u8 = undefined;
//var str = std.fmt.bufPrint(&buf, msg, args) catch unreachable;
//var res = logfile.write(str) catch unreachable;
std.debug.warn(msg, args);
}
fn onUnmapNotify(e: *c.XEvent) void {
var event = e.xunmap;
debug("onUnmapNotify {}\n", .{@as(u64, event.window)});
var screen = manager.getActiveScreen();
var workspace = screen.getActiveWorkspace();
var newFocusIndex = workspace.getWindowIndex(event.window) - 1;
if (newFocusIndex < 0) {
newFocusIndex = 0;
}
workspace.removeWindow(event.window);
layouts[manager.activeScreenIndex].stack(workspace, &xlib);
workspace.focusedWindow = @intCast(u32, newFocusIndex);
if (workspace.amountOfWindows > 0) {
debug("onUnmapNotify window focus {} {}\n", .{@as(u64, event.window), @as(u64, workspace.getFocusedWindow())});
//windowFocus(workspace.getFocusedWindow());
}
//xlib.ungrabButton(event.window);
}
fn getColor(color: config.COLOR) u64 {
return colours.getColorPixel(@enumToInt(color));
}
pub fn onMapRequest(e: *c.XEvent) void {
var event = e.xmap;
var screen = manager.getActiveScreen();
var workspace = screen.getActiveWorkspace();
debug("onMapRequest {}\n", .{@as(u64, event.window)});
debug("override_redirect is {}\n", .{@as(i32, event.override_redirect)});
xlib.grabButton(event.window);
var fixed = xlib.isFixed(event.window);
// NOTE: popups or application like steam will request a fixed size and will not be
// manged by window manager
if (fixed) {
_ = c.XMapWindow(xlib.display, event.window);
} else if (workspace.addWindow(event.window)) {
layouts[manager.activeScreenIndex].stack(workspace, &xlib);
_ = c.XSelectInput(xlib.display, event.window, c.EnterWindowMask | c.FocusChangeMask | c.PointerMotionMask);
_ = c.XMapWindow(xlib.display, event.window);
windowFocus(event.window);
}
_ = c.XSync(xlib.display, 0);
}
pub fn sendConfigureEvent(window: c.Window) void {
var event: c.XConfigureEvent = undefined;
event.type = c.ConfigureNotify;
event.display = display;
event.window = window;
event.x = 10;
event.y = 10;
event.width = 100;
event.height = 100;
event.border_width = 2;
event.override_redirect = 0;
var res = c.XSendEvent(display, window, 0, c.SubstructureNotifyMask, @ptrCast(*c.XEvent, &event));
}
pub fn half(value: u32) i32 {
return @intCast(i32, @divFloor(value, 2));
}
pub fn drawBar() void {
for (manager.screens[0..manager.amountScreens]) |*screen, screenIndex| {
var bar = getBar(screenIndex);
var bardraw = &barDraws[screenIndex];
var w = xlib.getWindowWidth(bar);
var barheight = xlib.getWindowHeight(bar);
var barwidth = xlib.getWindowWidth(bar);
var backgroundColor = config.COLOR.BACKGROUND;
bardraw.setForeground(getColor(backgroundColor));
bardraw.fillRect(0, 0, w, barheight);
if (screenIndex == manager.activeScreenIndex) {
bardraw.setForeground(getColor(config.COLOR.FOREGROUND_FOCUS_FG));
var focusbarWidth: u32 = 200;
var focusbarHeight: u32 = 4;
bardraw.fillRect(half(barwidth) - half(focusbarWidth), @intCast(i32, barheight - focusbarHeight), focusbarWidth, focusbarHeight);
}
// TODO: get height of font
var buttonSize: u32 = barheight - 2;
for (screen.workspaces) |workspace, i| {
var focus = i == screen.activeWorkspace;
var mul = @intCast(u32, i);
var color = config.COLOR.FOREGROUND_NOFOCUS;
if (focus) {
color = config.COLOR.FOREGROUND_FOCUS_BG;
}
var x = @intCast(i32, buttonSize * mul) + 1;
bardraw.setForeground(getColor(color));
bardraw.fillRect(x, 1, buttonSize - 2, buttonSize - 2);
if (focus) {
color = config.COLOR.FOREGROUND_FOCUS_FG;
bardraw.setForeground(getColor(color));
bardraw.fillRect(x, @intCast(i32, barheight) - 4, buttonSize - 2, buttonSize - 2);
}
}
var workspace = screen.getActiveWorkspace();
bardraw.render();
if (workspace.amountOfWindows > 0) {
// TODO: usize
var window = workspace.getFocusedWindow();
var prop: c.XTextProperty = undefined;
if (xlib.getWindowName(window, &prop)) {
var name: [256]u8 = undefined;
@memcpy(&name, prop.value, prop.nitems);
defer xlib.freeWindowName(&prop);
var width: u32 = 0;
var height: u32 = 0;
bardraw.getTextDimensions(xlib.font, name[0..prop.nitems], &width, &height);
var x = half(w) - half(width);
var y: i32 = 0;
// TODO: bardraw.render overwrites drawtext
bardraw.drawText(xlib.font, colours.getColor(@enumToInt(config.COLOR.FOREGROUND_FOCUS_FG)),
x, y, name[0..prop.nitems]);
}
}
var textWidth: u32 = 0;
var textHeith: u32 = 0;
bardraw.getTextDimensions(xlib.font, ×tring, &textWidth, &textHeith);
bardraw.drawText(xlib.font, colours.getColor(@enumToInt(config.COLOR.FOREGROUND_FOCUS_FG)),
@intCast(i32, barwidth - textWidth - 10), 5, timestring[0..timestring.len]);
}
}
fn onExpose(e: *c.XEvent) void {
drawBar();
}
fn onNoExpose(e: *c.XEvent) void {
//drawBar();
}
fn onMotionNotify(e: *c.XEvent) void {
var event = e.xmotion;
var workspace = manager.getActiveScreen().getActiveWorkspace();
// TODO: issue when to many motion events?? it laggs
//debug("Motion Event {}\n", .{ @as(u64, event.window)});
if (!workspace.hasWindow(event.window)) {
xlib.move(event.window, 200, 200);
}
for (manager.screens[0..manager.amountScreens]) |screen, screenIndex| {
if (event.x_root > screen.info.x and event.x_root < screen.info.x + @intCast(i32, screen.info.width)
and event.y_root > screen.info.y and event.y_root < screen.info.y + @intCast(i32, screen.info.height)) {
if (manager.activeScreenIndex != screenIndex) {
debug("Motion ScreenSelect {}\n", .{ @as(usize, manager.activeScreenIndex)});
manager.activeScreenIndex = screenIndex;
drawBar();
}
}
}
}
fn onKeyPress(e: *c.XEvent) void {
var event = e.xkey;
var keysym = c.XKeycodeToKeysym(xlib.display, @intCast(u8, event.keycode), 0);
var screen = manager.getActiveScreen();
var workspace = screen.getActiveWorkspace();
for (config.keys) |key| {
if (event.state == key.modifier and keysym == key.code) {
key.action(event.window, key.arg);
break;
}
}
}
fn onButtonPress(e: *c.XEvent) void {
var event = e.xbutton;
debug("window click {}\n", .{event.window});
for (config.buttons) |button| {
if (event.state == button.modifier and event.button == button.code) {
button.action(event.window, button.arg);
break;
}
}
_ = c.XAllowEvents(xlib.display, c.ReplayPointer, c.CurrentTime);
windowFocus(event.window);
}
fn notify(msg: []const u8, window: u64) void {
var buffer: [256]u8 = undefined;
var str = std.fmt.bufPrint(&buffer, "{} {}", msg, window) catch unreachable;
commands.notify(config.Arg{.String=str});
}
pub fn notifyf(comptime msg: []const u8, args: var) void {
//var buffer: [256]u8 = undefined;
//var str = std.fmt.bufPrint(&buffer, msg, args) catch unreachable;
//commands.notify(config.Arg{.String=str});
}
fn onFocusIn(e: *c.XEvent) void {
var event = e.xfocus;
}
fn xineramaGetScreenInfo() void {
var isActive = c.XineramaIsActive(xlib.display);
std.debug.assert(isActive == 1);
// Parse screen info
var screenInfo: [*]c.XineramaScreenInfo = undefined;
var numScreens: c_int = 0;
screenInfo = c.XineramaQueryScreens(xlib.display, &numScreens);
{
var i: u32 = 0;
while (i < @intCast(u32, numScreens)) : (i += 1) {
manager.screens[i].info.x = @intCast(i32, screenInfo[i].x_org);
manager.screens[i].info.y = @intCast(i32, screenInfo[i].y_org);
manager.screens[i].info.width = @intCast(u32, screenInfo[i].width);
manager.screens[i].info.height = @intCast(u32, screenInfo[i].height);
manager.amountScreens = i + 1;
}
}
}
const ThreadCtx = struct {
display: *c.Display,
window: u64,
};
fn updateStatusbar(ctx: *ThreadCtx) u8 {
var counter: u32 = 0;
while (manager.running) {
//c.XLockDisplay(ctx.display);
var seconds = std.time.milliTimestamp() / 1000;
comptime const secondsPerDay = 24 * 60 * 60;
var days = seconds / secondsPerDay;
var years = days / 365;
var d = Date{};
d.localtime();
var str = std.fmt.bufPrint(×tring, "{d:0<4}-{d:0<2}-{d:0<2} {d:0<2}:{d:0<2}",
.{d.year, d.month, d.day, d.hour, d.minute}) catch unreachable;
//var event: c.XClientMessageEvent = undefined;
//event.type = c.ClientMessage;
//event.serial = 0;
//event.send_event = 1;
//event.message_type = c.XInternAtom(ctx.display, &"_APP_EVT", 0);
//event.format = 32;
//event.window = ctx.window;
//event.data.l[0] = @intCast(i64, c.XInternAtom(ctx.display, &"DUDE", 0));
//event.data.l[1] = c.CurrentTime;
////event.send_event = 1;
//_ = c.XSendEvent(ctx.display, ctx.window, 0, c.NoEventMask, @ptrCast(*c.XEvent, &event));
////_ = c.XSync(ctx.display, 0);
//std.debug.warn("SEND EVENT\n");
//c.XUnlockDisplay(ctx.display);
var node = std.atomic.Queue(i32).Node{
.data = 0,
.next = undefined,
.prev = undefined,
};
msgQueue.put(&node);
std.time.sleep(1000000000);
counter += 1;
}
return 0;
}
const Date = struct {
year: u32 = 0,
month: u32 = 0,
day: u32 = 0,
hour: u32 = 0,
minute: u32 = 0,
second: u32 = 0,
fn localtime(self: *Date) void {
var raw: c.time_t = undefined;
_ = c.time(&raw);
var info: *c.tm = c.localtime(&raw);
self.year = @intCast(u32, info.tm_year + 1900);
self.month = @intCast(u32, info.tm_mon + 1);
self.day = @intCast(u32, info.tm_mday);
self.hour = @intCast(u32, info.tm_hour);
self.minute = @intCast(u32, info.tm_min);
self.second = @intCast(u32, info.tm_sec);
}
};
pub fn main() !void {
logfile = std.fs.cwd().createFile("log.txt", .{}) catch unreachable;
xlib.init(config.fontname);
_ = c.XInitThreads();
defer xlib.delete();
for (config.keys) |key| {
xlib.grabKey(key.modifier, key.code);
}
xineramaGetScreenInfo();
colours.init(xlib.display, xlib.screen);
for (config.colors) |color, i| {
colours.addColor(xlib.display, i, color[0], color[1], color[2]);
}
for (manager.screens[0..manager.amountScreens]) |*screen, screenIndex| {
var barheight: u32 = 32;
var barwidth: u32 = screen.info.width;
var bardraw = &barDraws[screenIndex];
var x = screen.info.x;
var y = @intCast(i32, screen.info.height - barheight - 1);
bars[screenIndex] = xlib.createWindow(x, y + 1, barwidth, barheight);
bardraw.init(xlib.display, bars[screenIndex], xlib.screen, barwidth, barheight);
layouts[screenIndex].x = screen.info.x;
layouts[screenIndex].y = screen.info.y;
layouts[screenIndex].width = screen.info.width;
layouts[screenIndex].height= screen.info.height - barheight;
}
var cmd: [*:0]const u8 = "cd ~/.config/.uwm; ./autostart.sh &";
_ = c.system(cmd);
manager.running = true;
var ctx = ThreadCtx{.display=xlib.display, .window=xlib.root};
var statusbarThread = try std.Thread.spawn(&ctx, updateStatusbar);
while (manager.running) {
var item = msgQueue.get();
while (item != null) {
drawBar();
item = msgQueue.get();
}
if (c.XPending(xlib.display) > 0) {
var e: c.XEvent = undefined;
_ = c.XNextEvent(xlib.display, &e);
switch (e.type) {
c.Expose => onExpose(&e),
c.KeyPress => onKeyPress(&e),
c.ConfigureRequest => onConfigureRequest(&e),
c.MapRequest => onMapRequest(&e),
c.UnmapNotify => onUnmapNotify(&e),
c.DestroyNotify => onDestroyNotify(&e),
c.EnterNotify => onEnterNotify(&e),
c.FocusIn => onFocusIn(&e),
c.NoExpose => onNoExpose(&e),
c.MotionNotify => onMotionNotify(&e),
c.ButtonPress => onButtonPress(&e),
else => continue,
//else => warn("not handled {}\n", e.type),
}
}
//// TODO: sleep correct way?
std.time.sleep(1600000);
}
for (barDraws) |*bardraw| {
bardraw.free();
}
}
|
src/main.zig
|
const std = @import("std");
const debug = std.debug;
const io = std.io;
pub fn print(value: anytype) void {
debug.getStderrMutex().lock();
defer debug.getStderrMutex().unlock();
const stderr = io.getStdErr().writer();
nosuspend {
stderr.writeAll("\x1b[41m") catch return;
switch (@typeInfo(@TypeOf(value))) {
.Struct => |info| {
if (info.is_tuple) {
inline for (info.fields) |f, i| {
inspect(@field(value, f.name));
if (i < info.fields.len - 1) stderr.writeAll(" ") catch return;
}
} else {
inspect(value);
}
},
else => inspect(value),
}
stderr.writeAll("\x1b[K\x1b[0m\n") catch return;
}
}
fn inspect(value: anytype) void {
const stderr = io.getStdErr().writer();
nosuspend {
const err = "Unable to format type '" ++ @typeName(@TypeOf(value)) ++ "'";
switch (@typeInfo(@TypeOf(value))) {
.Array => |info| {
if (info.child == u8) return stderr.print("{s}", .{value}) catch return;
@compileError(err);
},
.Pointer => |ptr_info| switch (ptr_info.size) {
.One => switch (@typeInfo(ptr_info.child)) {
.Array => |info| {
if (info.child == u8) return stderr.print("{s}", .{value}) catch return;
@compileError(err);
},
.Enum, .Union, .Struct => return inspect(value.*),
else => @compileError(err),
},
.Many, .C => {
if (ptr_info.sentinel) |_| return inspect(std.mem.span(value));
if (ptr_info.child == u8) {
return stderr.print("{s}", .{std.mem.span(value)}) catch return;
}
@compileError(err);
},
.Slice => {
if (ptr_info.child == u8) return stderr.print("{s}", .{value}) catch return;
@compileError(err);
},
},
else => stderr.print("{}", .{value}) catch return,
}
}
}
|
src/lib/common/debug.zig
|
const std = @import("std");
const interop = @import("../interop.zig");
const iup = @import("../iup.zig");
const Impl = @import("../impl.zig").Impl;
const CallbackHandler = @import("../callback_handler.zig").CallbackHandler;
const debug = std.debug;
const trait = std.meta.trait;
const Element = iup.Element;
const Handle = iup.Handle;
const Error = iup.Error;
const ChildrenIterator = iup.ChildrenIterator;
const Size = iup.Size;
const Margin = iup.Margin;
///
/// Creates a void container that can interactively show or hide its child.
/// It does not have a native representation, but it contains also several
/// elements to implement the bar handler.
pub const Expander = opaque {
pub const CLASS_NAME = "expander";
pub const NATIVE_TYPE = iup.NativeType.Void;
const Self = @This();
///
/// ACTION ACTION Action generated when the element is activated.
/// Affects each element differently.
/// Callback int function(Ihandle *ih); [in C] ih:action() -> (ret: number) [in
/// Lua] ih: identifier of the element that activated the event.
/// In some elements, this callback may receive more parameters, apart from ih.
/// Please refer to each element's documentation.
/// Affects IupButton, IupItem, IupList, IupText, IupCanvas, IupMultiline,
/// IupToggle
pub const OnActionFn = fn (self: *Self) anyerror!void;
///
/// EXTRABUTTON_CB: Action generated when any mouse button is pressed or released.
/// (since 3.11) int function(Ihandle* ih, int button, int pressed); [in C]
/// ih:extrabutton_cb(button, pressed: number) -> (ret: number) [in Lua] ih:
/// identifies the element that activated the event.
/// button: identifies the extra button.
/// can be 1, 2 or 3.
/// (this is not the same as BUTTON_CB)pressed: indicates the state of the
/// button: 0 - mouse button was released; 1 - mouse button was pressed.
pub const OnExtraButtonFn = fn (self: *Self, arg0: i32, arg1: i32) anyerror!void;
///
/// OPENCLOSE_CB: Action generated before the expander state is interactively changed.
/// (Since 3.11) int function(Ihandle* ih, int state); [in
/// C]ih:openclose_cb(state: number) -> (ret: number) [in Lua]
pub const OnOpenCloseFn = fn (self: *Self, arg0: i32) anyerror!void;
///
/// MAP_CB MAP_CB Called right after an element is mapped and its attributes
/// updated in IupMap.
/// When the element is a dialog, it is called after the layout is updated.
/// For all other elements is called before the layout is updated, so the
/// element current size will still be 0x0 during MAP_CB (since 3.14).
/// Callback int function(Ihandle *ih); [in C] ih:map_cb() -> (ret: number) [in
/// Lua] ih: identifier of the element that activated the event.
/// Affects All that have a native representation.
pub const OnMapFn = fn (self: *Self) anyerror!void;
///
/// DESTROY_CB DESTROY_CB Called right before an element is destroyed.
/// Callback int function(Ihandle *ih); [in C] ih:destroy_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Notes If the dialog is visible then it is hidden before it is destroyed.
/// The callback will be called right after it is hidden.
/// The callback will be called before all other destroy procedures.
/// For instance, if the element has children then it is called before the
/// children are destroyed.
/// For language binding implementations use the callback name "LDESTROY_CB" to
/// release memory allocated by the binding for the element.
/// Also the callback will be called before the language callback.
/// Affects All.
pub const OnDestroyFn = fn (self: *Self) anyerror!void;
///
/// UNMAP_CB UNMAP_CB Called right before an element is unmapped.
/// Callback int function(Ihandle *ih); [in C] ih:unmap_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Affects All that have a native representation.
pub const OnUnmapFn = fn (self: *Self) anyerror!void;
pub const OnLDestroyFn = fn (self: *Self) anyerror!void;
pub const OnPostMessageFn = fn (self: *Self, arg0: [:0]const u8, arg1: i32, arg2: f64, arg3: *iup.Unknow) anyerror!void;
///
/// EXPAND (non inheritable): the default value is "YES".
pub const Expand = enum {
Yes,
Horizontal,
Vertical,
HorizontalFree,
VerticalFree,
No,
};
pub const Floating = enum {
Yes,
Ignore,
No,
};
///
/// STATE (non inheritable): Show or hide the container elements.
/// Possible values: "OPEN" (expanded) or "CLOSE" (collapsed).
/// Default: OPEN.
/// Setting this attribute will automatically change the layout of the entire
/// dialog so the child can be recomposed.
pub const State = enum {
Open,
Closed,
};
///
/// ANIMATION (non inheritable): enable animation during open/close.
/// Works only for BARPOSITION=TOP and does not works for AUTOSHOW.
/// Also the child must be a native container like IupTabs, IupFrame,
/// IupBackgroundBox, or IupScrollBox, or it will not work accordantly.
/// Values can be SLIDE (child controls slide down), CURTAIN (child controls
/// appears as if a curtain is being pulled) or NO.
/// Default: NO.
/// ((since 3.14)
pub const Animation = enum {
Slide,
Curtain,
No,
};
pub const Initializer = struct {
last_error: ?anyerror = null,
ref: *Self,
///
/// Returns a pointer to IUP element or an error.
/// Only top-level or detached elements needs to be unwraped,
pub fn unwrap(self: Initializer) !*Self {
if (self.last_error) |e| {
return e;
} else {
return self.ref;
}
}
///
/// Captures a reference into a external variable
/// Allows to capture some references even using full declarative API
pub fn capture(self: *Initializer, ref: **Self) Initializer {
ref.* = self.ref;
return self.*;
}
pub fn setStrAttribute(self: *Initializer, attributeName: [:0]const u8, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
Self.setStrAttribute(self.ref, attributeName, arg);
return self.*;
}
pub fn setIntAttribute(self: *Initializer, attributeName: [:0]const u8, arg: i32) Initializer {
if (self.last_error) |_| return self.*;
Self.setIntAttribute(self.ref, attributeName, arg);
return self.*;
}
pub fn setBoolAttribute(self: *Initializer, attributeName: [:0]const u8, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
Self.setBoolAttribute(self.ref, attributeName, arg);
return self.*;
}
pub fn setPtrAttribute(self: *Initializer, comptime T: type, attributeName: [:0]const u8, value: ?*T) Initializer {
if (self.last_error) |_| return self.*;
Self.setPtrAttribute(self.ref, T, attributeName, value);
return self.*;
}
pub fn setHandle(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setHandle(self.ref, arg);
return self.*;
}
pub fn setChildren(self: *Initializer, tuple: anytype) Initializer {
if (self.last_error) |_| return self.*;
Self.appendChildren(self.ref, tuple) catch |err| {
self.last_error = err;
};
return self.*;
}
pub fn setHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "HANDLENAME", .{}, arg);
return self.*;
}
pub fn setFrameTime(self: *Initializer, arg: i32) Initializer {
if (self.last_error) |_| return self.*;
interop.setIntAttribute(self.ref, "FRAMETIME", .{}, arg);
return self.*;
}
pub fn setImageOpenHighlight(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "IMAGEOPENHIGHLIGHT", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setImageOpenHighlightHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "IMAGEOPENHIGHLIGHT", .{}, arg);
return self.*;
}
pub fn setImageExtraPress1(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "IMAGEEXTRAPRESS1", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setImageExtraPress1HandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "IMAGEEXTRAPRESS1", .{}, arg);
return self.*;
}
pub fn setImageExtraPress2(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "IMAGEEXTRAPRESS2", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setImageExtraPress2HandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "IMAGEEXTRAPRESS2", .{}, arg);
return self.*;
}
pub fn setImageExtraPress3(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "IMAGEEXTRAPRESS3", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setImageExtraPress3HandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "IMAGEEXTRAPRESS3", .{}, arg);
return self.*;
}
///
/// BACKCOLOR (non inheritable): background color of the bar handler.
/// If not defined it will use the background color of the native parent.
/// (since 3.9)
pub fn setBackColor(self: *Initializer, rgb: iup.Rgb) Initializer {
if (self.last_error) |_| return self.*;
interop.setRgb(self.ref, "BACKCOLOR", .{}, rgb);
return self.*;
}
pub fn setMaxSize(self: *Initializer, width: ?i32, height: ?i32) Initializer {
if (self.last_error) |_| return self.*;
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self.ref, "MAXSIZE", .{}, value);
return self.*;
}
///
/// TITLEIMAGE (non inheritable): title image, shown in the bar handler near
/// the expand/collapse button.
/// When set it will reset TITLE (image and text title are mutually exclusive).
/// Shown only when BARPOSITION=TOP.
/// (since 3.14)
pub fn setTitleImage(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "TITLEIMAGE", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setTitleImageHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "TITLEIMAGE", .{}, arg);
return self.*;
}
pub fn setPosition(self: *Initializer, x: i32, y: i32) Initializer {
if (self.last_error) |_| return self.*;
var buffer: [128]u8 = undefined;
var value = iup.XYPos.intIntToString(&buffer, x, y, ',');
interop.setStrAttribute(self.ref, "POSITION", .{}, value);
return self.*;
}
pub fn setImageExtra1(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "IMAGEEXTRA1", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setImageExtra1HandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "IMAGEEXTRA1", .{}, arg);
return self.*;
}
pub fn setImageExtra2(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "IMAGEEXTRA2", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setImageExtra2HandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "IMAGEEXTRA2", .{}, arg);
return self.*;
}
pub fn setImageExtra3(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "IMAGEEXTRA3", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setImageExtra3HandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "IMAGEEXTRA3", .{}, arg);
return self.*;
}
pub fn setCanFocus(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "CANFOCUS", .{}, arg);
return self.*;
}
pub fn setVisible(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "VISIBLE", .{}, arg);
return self.*;
}
///
/// IMAGE (non inheritable): image name to replace the arrow image by a custom
/// image when STATE=CLOSE.
/// Works only when BARPOSITION=TOP.
/// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name.
/// See also IupImage.
/// (since 3.11)
pub fn setImage(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "IMAGE", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setImageHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "IMAGE", .{}, arg);
return self.*;
}
///
/// HIGHCOLOR (non inheritable): title text color when highlighted.
/// Works only when TITLEEXPAND=Yes.
/// Defaults to the FORECOLOR if not defined.
/// (since 3.14)
pub fn setHighColor(self: *Initializer, rgb: iup.Rgb) Initializer {
if (self.last_error) |_| return self.*;
interop.setRgb(self.ref, "HIGHCOLOR", .{}, rgb);
return self.*;
}
pub fn setTheme(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "THEME", .{}, arg);
return self.*;
}
///
/// EXPAND (non inheritable): the default value is "YES".
pub fn setExpand(self: *Initializer, arg: ?Expand) Initializer {
if (self.last_error) |_| return self.*;
if (arg) |value| switch (value) {
.Yes => interop.setStrAttribute(self.ref, "EXPAND", .{}, "YES"),
.Horizontal => interop.setStrAttribute(self.ref, "EXPAND", .{}, "HORIZONTAL"),
.Vertical => interop.setStrAttribute(self.ref, "EXPAND", .{}, "VERTICAL"),
.HorizontalFree => interop.setStrAttribute(self.ref, "EXPAND", .{}, "HORIZONTALFREE"),
.VerticalFree => interop.setStrAttribute(self.ref, "EXPAND", .{}, "VERTICALFREE"),
.No => interop.setStrAttribute(self.ref, "EXPAND", .{}, "NO"),
} else {
interop.clearAttribute(self.ref, "EXPAND", .{});
}
return self.*;
}
pub fn setSize(self: *Initializer, width: ?i32, height: ?i32) Initializer {
if (self.last_error) |_| return self.*;
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self.ref, "SIZE", .{}, value);
return self.*;
}
pub fn setFontSize(self: *Initializer, arg: i32) Initializer {
if (self.last_error) |_| return self.*;
interop.setIntAttribute(self.ref, "FONTSIZE", .{}, arg);
return self.*;
}
pub fn setUserSize(self: *Initializer, width: ?i32, height: ?i32) Initializer {
if (self.last_error) |_| return self.*;
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self.ref, "USERSIZE", .{}, value);
return self.*;
}
pub fn setTitleImageOpenHighlight(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "TITLEIMAGEOPENHIGHLIGHT", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setTitleImageOpenHighlightHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "TITLEIMAGEOPENHIGHLIGHT", .{}, arg);
return self.*;
}
///
/// TITLE (non inheritable): title text, shown in the bar handler near the
/// expand/collapse button.
/// When set it will reset TITLEIMAGE.
/// Shown only when BARPOSITION=TOP.
/// When the TITLE is defined and BARPOSITION=TOP then the expand/collapse
/// button is left aligned.
/// In all other situations the expand/collapse button is centered.
pub fn setTitle(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "TITLE", .{}, arg);
return self.*;
}
pub fn setPropagateFocus(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "PROPAGATEFOCUS", .{}, arg);
return self.*;
}
pub fn setFloating(self: *Initializer, arg: ?Floating) Initializer {
if (self.last_error) |_| return self.*;
if (arg) |value| switch (value) {
.Yes => interop.setStrAttribute(self.ref, "FLOATING", .{}, "YES"),
.Ignore => interop.setStrAttribute(self.ref, "FLOATING", .{}, "IGNORE"),
.No => interop.setStrAttribute(self.ref, "FLOATING", .{}, "NO"),
} else {
interop.clearAttribute(self.ref, "FLOATING", .{});
}
return self.*;
}
pub fn setNormalizerGroup(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "NORMALIZERGROUP", .{}, arg);
return self.*;
}
pub fn setRasterSize(self: *Initializer, width: ?i32, height: ?i32) Initializer {
if (self.last_error) |_| return self.*;
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self.ref, "RASTERSIZE", .{}, value);
return self.*;
}
pub fn setImageExtraHighlight1(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "IMAGEEXTRAHIGHLIGHT1", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setImageExtraHighlight1HandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "IMAGEEXTRAHIGHLIGHT1", .{}, arg);
return self.*;
}
pub fn setImageExtraHighlight2(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "IMAGEEXTRAHIGHLIGHT2", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setImageExtraHighlight2HandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "IMAGEEXTRAHIGHLIGHT2", .{}, arg);
return self.*;
}
pub fn setImageExtraHighlight3(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "IMAGEEXTRAHIGHLIGHT3", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setImageExtraHighlight3HandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "IMAGEEXTRAHIGHLIGHT3", .{}, arg);
return self.*;
}
///
/// BARSIZE (non inheritable): controls the size of the bar handler.
/// Default: the height or width that fits all its internal elements according
/// to BARPOSITION.
pub fn setBarSize(self: *Initializer, arg: i32) Initializer {
if (self.last_error) |_| return self.*;
interop.setIntAttribute(self.ref, "BARSIZE", .{}, arg);
return self.*;
}
///
/// FRAMECOLOR (non inheritable): frame line color.
/// Default: the global attribute DLGFGCOLOR.
/// (since 3.23)
pub fn setFrameColor(self: *Initializer, rgb: iup.Rgb) Initializer {
if (self.last_error) |_| return self.*;
interop.setRgb(self.ref, "FRAMECOLOR", .{}, rgb);
return self.*;
}
pub fn setFontFace(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "FONTFACE", .{}, arg);
return self.*;
}
///
/// TITLEIMAGEOPEN: image name used when STATE=OPEN.
/// TITLEIMAGEHIGHLIGHT: image name used when mouse is over the title image and
/// STATE=CLOSE.TITLEIMAGEOPENHIGHLIGHT: image name used when mouse is over the
/// title image and STATE=OPEN.
pub fn setTitleImageOpen(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "TITLEIMAGEOPEN", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setTitleImageOpenHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "TITLEIMAGEOPEN", .{}, arg);
return self.*;
}
pub fn setName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "NAME", .{}, arg);
return self.*;
}
///
/// STATE (non inheritable): Show or hide the container elements.
/// Possible values: "OPEN" (expanded) or "CLOSE" (collapsed).
/// Default: OPEN.
/// Setting this attribute will automatically change the layout of the entire
/// dialog so the child can be recomposed.
pub fn setState(self: *Initializer, arg: ?State) Initializer {
if (self.last_error) |_| return self.*;
if (arg) |value| switch (value) {
.Open => interop.setStrAttribute(self.ref, "STATE", .{}, "OPEN"),
.Closed => interop.setStrAttribute(self.ref, "STATE", .{}, "CLOSED"),
} else {
interop.clearAttribute(self.ref, "STATE", .{});
}
return self.*;
}
pub fn setActive(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "ACTIVE", .{}, arg);
return self.*;
}
pub fn setImageHighlight(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "IMAGEHIGHLIGHT", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setImageHighlightHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "IMAGEHIGHLIGHT", .{}, arg);
return self.*;
}
pub fn setExpandWeight(self: *Initializer, arg: f64) Initializer {
if (self.last_error) |_| return self.*;
interop.setDoubleAttribute(self.ref, "EXPANDWEIGHT", .{}, arg);
return self.*;
}
pub fn setMinSize(self: *Initializer, width: ?i32, height: ?i32) Initializer {
if (self.last_error) |_| return self.*;
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self.ref, "MINSIZE", .{}, value);
return self.*;
}
pub fn setTitleImageHighlight(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "TITLEIMAGEHIGHLIGHT", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setTitleImageHighlightHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "TITLEIMAGEHIGHLIGHT", .{}, arg);
return self.*;
}
pub fn setNTheme(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "NTHEME", .{}, arg);
return self.*;
}
///
/// EXTRABUTTONS (non inheritable) (creation only): sets the number of extra
/// image buttons at right when BARPOSITION=TOP.
/// The maximum number of buttons is 3.
/// See the EXTRABUTTON_CB callback.
/// Default: 0.
/// (since 3.11)
pub fn setExtraButtons(self: *Initializer, arg: i32) Initializer {
if (self.last_error) |_| return self.*;
interop.setIntAttribute(self.ref, "EXTRABUTTONS", .{}, arg);
return self.*;
}
///
/// ANIMATION (non inheritable): enable animation during open/close.
/// Works only for BARPOSITION=TOP and does not works for AUTOSHOW.
/// Also the child must be a native container like IupTabs, IupFrame,
/// IupBackgroundBox, or IupScrollBox, or it will not work accordantly.
/// Values can be SLIDE (child controls slide down), CURTAIN (child controls
/// appears as if a curtain is being pulled) or NO.
/// Default: NO.
/// ((since 3.14)
pub fn setAnimation(self: *Initializer, arg: ?Animation) Initializer {
if (self.last_error) |_| return self.*;
if (arg) |value| switch (value) {
.Slide => interop.setStrAttribute(self.ref, "ANIMATION", .{}, "SLIDE"),
.Curtain => interop.setStrAttribute(self.ref, "ANIMATION", .{}, "CURTAIN"),
.No => interop.setStrAttribute(self.ref, "ANIMATION", .{}, "NO"),
} else {
interop.clearAttribute(self.ref, "ANIMATION", .{});
}
return self.*;
}
///
/// FORECOLOR (non inheritable): title text color.
/// Default: the global attribute DLGFGCOLOR.
/// (since 3.9)
pub fn setForeColor(self: *Initializer, rgb: iup.Rgb) Initializer {
if (self.last_error) |_| return self.*;
interop.setRgb(self.ref, "FORECOLOR", .{}, rgb);
return self.*;
}
pub fn setFontStyle(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "FONTSTYLE", .{}, arg);
return self.*;
}
///
/// IMAGEOPEN: image name used when STATE=OPEN.
/// IMAGEHIGHLIGHT: image name used when mouse is over the bar handler and
/// STATE=CLOSE.IMAGEOPENHIGHLIGHT: image name used when mouse is over the bar
/// handler and STATE=OPEN.
pub fn setImageOpen(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "IMAGEOPEN", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setImageOpenHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "IMAGEOPEN", .{}, arg);
return self.*;
}
///
/// FRAMEWIDTH (non inheritable): frame line width.
/// Default: 1.
/// (since 3.23)
pub fn setFrameWidth(self: *Initializer, arg: i32) Initializer {
if (self.last_error) |_| return self.*;
interop.setIntAttribute(self.ref, "FRAMEWIDTH", .{}, arg);
return self.*;
}
///
/// FRAME (non inheritable): enables the frame line around the bar area.
/// Default: No.
/// (since 3.23)
pub fn setFrame(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "FRAME", .{}, arg);
return self.*;
}
///
/// FONT, SIZE, RASTERSIZE, CLIENTSIZE, CLIENTOFFSET, POSITION, MINSIZE,
/// MAXSIZE, THEME: also accepted.
pub fn setFont(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "FONT", .{}, arg);
return self.*;
}
///
/// TABIMAGEn (non inheritable): image name to be used in the respective tab.
/// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name.
/// n starts at 0.
/// See also IupImage.
/// In Motif, the image is shown only if TABTITLEn is NULL.
/// In Windows and Motif set the BGCOLOR attribute before setting the image.
/// When set after map will update the TABIMAGE attribute on the respective
/// child (since 3.10).
/// (since 3.0).
/// TABIMAGE (non inheritable) (at children only): Same as TABIMAGEn but set in
/// each child.
/// Works only if set before the child is added to the tabs.
pub fn setTabImage(self: *Initializer, index: i32, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "TABIMAGE", .{index}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setTabImageHandleName(self: *Initializer, index: i32, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "TABIMAGE", .{index}, arg);
return self.*;
}
///
/// TABTITLEn (non inheritable): Contains the text to be shown in the
/// respective tab title.
/// n starts at 0.
/// If this value is NULL, it will remain empty.
/// The "&" character can be used to define a mnemonic, the next character will
/// be used as key.
/// Use "&&" to show the "&" character instead on defining a mnemonic.
/// The button can be activated from any control in the dialog using the
/// "Alt+key" combination.
/// (mnemonic support since 3.3).
/// When set after map will update the TABTITLE attribute on the respective
/// child (since 3.10).
/// (since 3.0).
/// TABTITLE (non inheritable) (at children only): Same as TABTITLEn but set in
/// each child.
/// Works only if set before the child is added to the tabs.
pub fn setTabTitle(self: *Initializer, index: i32, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "TABTITLE", .{index}, arg);
return self.*;
}
///
/// ACTION ACTION Action generated when the element is activated.
/// Affects each element differently.
/// Callback int function(Ihandle *ih); [in C] ih:action() -> (ret: number) [in
/// Lua] ih: identifier of the element that activated the event.
/// In some elements, this callback may receive more parameters, apart from ih.
/// Please refer to each element's documentation.
/// Affects IupButton, IupItem, IupList, IupText, IupCanvas, IupMultiline,
/// IupToggle
pub fn setActionCallback(self: *Initializer, callback: ?OnActionFn) Initializer {
const Handler = CallbackHandler(Self, OnActionFn, "ACTION");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// EXTRABUTTON_CB: Action generated when any mouse button is pressed or released.
/// (since 3.11) int function(Ihandle* ih, int button, int pressed); [in C]
/// ih:extrabutton_cb(button, pressed: number) -> (ret: number) [in Lua] ih:
/// identifies the element that activated the event.
/// button: identifies the extra button.
/// can be 1, 2 or 3.
/// (this is not the same as BUTTON_CB)pressed: indicates the state of the
/// button: 0 - mouse button was released; 1 - mouse button was pressed.
pub fn setExtraButtonCallback(self: *Initializer, callback: ?OnExtraButtonFn) Initializer {
const Handler = CallbackHandler(Self, OnExtraButtonFn, "EXTRABUTTON_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// OPENCLOSE_CB: Action generated before the expander state is interactively changed.
/// (Since 3.11) int function(Ihandle* ih, int state); [in
/// C]ih:openclose_cb(state: number) -> (ret: number) [in Lua]
pub fn setOpenCloseCallback(self: *Initializer, callback: ?OnOpenCloseFn) Initializer {
const Handler = CallbackHandler(Self, OnOpenCloseFn, "OPENCLOSE_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// MAP_CB MAP_CB Called right after an element is mapped and its attributes
/// updated in IupMap.
/// When the element is a dialog, it is called after the layout is updated.
/// For all other elements is called before the layout is updated, so the
/// element current size will still be 0x0 during MAP_CB (since 3.14).
/// Callback int function(Ihandle *ih); [in C] ih:map_cb() -> (ret: number) [in
/// Lua] ih: identifier of the element that activated the event.
/// Affects All that have a native representation.
pub fn setMapCallback(self: *Initializer, callback: ?OnMapFn) Initializer {
const Handler = CallbackHandler(Self, OnMapFn, "MAP_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// DESTROY_CB DESTROY_CB Called right before an element is destroyed.
/// Callback int function(Ihandle *ih); [in C] ih:destroy_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Notes If the dialog is visible then it is hidden before it is destroyed.
/// The callback will be called right after it is hidden.
/// The callback will be called before all other destroy procedures.
/// For instance, if the element has children then it is called before the
/// children are destroyed.
/// For language binding implementations use the callback name "LDESTROY_CB" to
/// release memory allocated by the binding for the element.
/// Also the callback will be called before the language callback.
/// Affects All.
pub fn setDestroyCallback(self: *Initializer, callback: ?OnDestroyFn) Initializer {
const Handler = CallbackHandler(Self, OnDestroyFn, "DESTROY_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// UNMAP_CB UNMAP_CB Called right before an element is unmapped.
/// Callback int function(Ihandle *ih); [in C] ih:unmap_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Affects All that have a native representation.
pub fn setUnmapCallback(self: *Initializer, callback: ?OnUnmapFn) Initializer {
const Handler = CallbackHandler(Self, OnUnmapFn, "UNMAP_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setLDestroyCallback(self: *Initializer, callback: ?OnLDestroyFn) Initializer {
const Handler = CallbackHandler(Self, OnLDestroyFn, "LDESTROY_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setPostMessageCallback(self: *Initializer, callback: ?OnPostMessageFn) Initializer {
const Handler = CallbackHandler(Self, OnPostMessageFn, "POSTMESSAGE_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
};
pub fn setStrAttribute(self: *Self, attribute: [:0]const u8, arg: [:0]const u8) void {
interop.setStrAttribute(self, attribute, .{}, arg);
}
pub fn getStrAttribute(self: *Self, attribute: [:0]const u8) [:0]const u8 {
return interop.getStrAttribute(self, attribute, .{});
}
pub fn setIntAttribute(self: *Self, attribute: [:0]const u8, arg: i32) void {
interop.setIntAttribute(self, attribute, .{}, arg);
}
pub fn getIntAttribute(self: *Self, attribute: [:0]const u8) i32 {
return interop.getIntAttribute(self, attribute, .{});
}
pub fn setBoolAttribute(self: *Self, attribute: [:0]const u8, arg: bool) void {
interop.setBoolAttribute(self, attribute, .{}, arg);
}
pub fn getBoolAttribute(self: *Self, attribute: [:0]const u8) bool {
return interop.getBoolAttribute(self, attribute, .{});
}
pub fn getPtrAttribute(self: *Self, comptime T: type, attribute: [:0]const u8) ?*T {
return interop.getPtrAttribute(T, self, attribute, .{});
}
pub fn setPtrAttribute(self: *Self, comptime T: type, attribute: [:0]const u8, value: ?*T) void {
interop.setPtrAttribute(T, self, attribute, .{}, value);
}
pub fn setHandle(self: *Self, arg: [:0]const u8) void {
interop.setHandle(self, arg);
}
pub fn fromHandleName(handle_name: [:0]const u8) ?*Self {
return interop.fromHandleName(Self, handle_name);
}
///
/// Creates an interface element given its class name and parameters.
/// After creation the element still needs to be attached to a container and mapped to the native system so it can be visible.
pub fn init() Initializer {
var handle = interop.create(Self);
if (handle) |valid| {
return .{
.ref = @ptrCast(*Self, valid),
};
} else {
return .{ .ref = undefined, .last_error = Error.NotInitialized };
}
}
///
/// Destroys an interface element and all its children.
/// Only dialogs, timers, popup menus and images should be normally destroyed, but detached elements can also be destroyed.
pub fn deinit(self: *Self) void {
interop.destroy(self);
}
///
/// Creates (maps) the native interface objects corresponding to the given IUP interface elements.
/// It will also called recursively to create the native element of all the children in the element's tree.
/// The element must be already attached to a mapped container, except the dialog. A child can only be mapped if its parent is already mapped.
/// This function is automatically called before the dialog is shown in IupShow, IupShowXY or IupPopup.
/// If the element is a dialog then the abstract layout will be updated even if the dialog is already mapped. If the dialog is visible the elements will be immediately repositioned. Calling IupMap for an already mapped dialog is the same as only calling IupRefresh for the dialog.
/// Calling IupMap for an already mapped element that is not a dialog does nothing.
/// If you add new elements to an already mapped dialog you must call IupMap for that elements. And then call IupRefresh to update the dialog layout.
/// If the WID attribute of an element is NULL, it means the element was not already mapped. Some containers do not have a native element associated, like VBOX and HBOX. In this case their WID is a fake value (void*)(-1).
/// It is useful for the application to call IupMap when the value of the WID attribute must be known, i.e. the native element must exist, before a dialog is made visible.
/// The MAP_CB callback is called at the end of the IupMap function, after all processing, so it can also be used to create other things that depend on the WID attribute. But notice that for non dialog elements it will be called before the dialog layout has been updated, so the element current size will still be 0x0 (since 3.14).
pub fn map(self: *Self) !void {
try interop.map(self);
}
///
/// Adds a tuple of children
pub fn appendChildren(self: *Self, tuple: anytype) !void {
try Impl(Self).appendChildren(self, tuple);
}
///
/// Appends a child on this container
/// child must be an Element or
pub fn appendChild(self: *Self, child: anytype) !void {
try Impl(Self).appendChild(self, child);
}
///
/// Returns a iterator for children elements.
pub fn children(self: *Self) ChildrenIterator {
return ChildrenIterator.init(self);
}
///
///
pub fn getDialog(self: *Self) ?*iup.Dialog {
return interop.getDialog(self);
}
///
/// Returns the the child element that has the NAME attribute equals to the given value on the same dialog hierarchy.
/// Works also for children of a menu that is associated with a dialog.
pub fn getDialogChild(self: *Self, byName: [:0]const u8) ?Element {
return interop.getDialogChild(self, byName);
}
///
/// Updates the size and layout of all controls in the same dialog.
/// To be used after changing size attributes, or attributes that affect the size of the control. Can be used for any element inside a dialog, but the layout of the dialog and all controls will be updated. It can change the layout of all the controls inside the dialog because of the dynamic layout positioning.
pub fn refresh(self: *Self) void {
Impl(Self).refresh(self);
}
pub fn getHandleName(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "HANDLENAME", .{});
}
pub fn setHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "HANDLENAME", .{}, arg);
}
pub fn getFrameTime(self: *Self) i32 {
return interop.getIntAttribute(self, "FRAMETIME", .{});
}
pub fn setFrameTime(self: *Self, arg: i32) void {
interop.setIntAttribute(self, "FRAMETIME", .{}, arg);
}
pub fn getImageOpenHighlight(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "IMAGEOPENHIGHLIGHT", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
pub fn setImageOpenHighlight(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "IMAGEOPENHIGHLIGHT", .{}, arg);
}
pub fn setImageOpenHighlightHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "IMAGEOPENHIGHLIGHT", .{}, arg);
}
pub fn getImageExtraPress1(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "IMAGEEXTRAPRESS1", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
pub fn setImageExtraPress1(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "IMAGEEXTRAPRESS1", .{}, arg);
}
pub fn setImageExtraPress1HandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "IMAGEEXTRAPRESS1", .{}, arg);
}
pub fn getImageExtraPress2(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "IMAGEEXTRAPRESS2", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
pub fn setImageExtraPress2(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "IMAGEEXTRAPRESS2", .{}, arg);
}
pub fn setImageExtraPress2HandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "IMAGEEXTRAPRESS2", .{}, arg);
}
pub fn getImageExtraPress3(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "IMAGEEXTRAPRESS3", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
pub fn setImageExtraPress3(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "IMAGEEXTRAPRESS3", .{}, arg);
}
pub fn setImageExtraPress3HandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "IMAGEEXTRAPRESS3", .{}, arg);
}
///
/// BACKCOLOR (non inheritable): background color of the bar handler.
/// If not defined it will use the background color of the native parent.
/// (since 3.9)
pub fn getBackColor(self: *Self) ?iup.Rgb {
return interop.getRgb(self, "BACKCOLOR", .{});
}
///
/// BACKCOLOR (non inheritable): background color of the bar handler.
/// If not defined it will use the background color of the native parent.
/// (since 3.9)
pub fn setBackColor(self: *Self, rgb: iup.Rgb) void {
interop.setRgb(self, "BACKCOLOR", .{}, rgb);
}
pub fn getMaxSize(self: *Self) Size {
var str = interop.getStrAttribute(self, "MAXSIZE", .{});
return Size.parse(str);
}
pub fn setMaxSize(self: *Self, width: ?i32, height: ?i32) void {
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self, "MAXSIZE", .{}, value);
}
///
/// TITLEIMAGE (non inheritable): title image, shown in the bar handler near
/// the expand/collapse button.
/// When set it will reset TITLE (image and text title are mutually exclusive).
/// Shown only when BARPOSITION=TOP.
/// (since 3.14)
pub fn getTitleImage(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "TITLEIMAGE", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
///
/// TITLEIMAGE (non inheritable): title image, shown in the bar handler near
/// the expand/collapse button.
/// When set it will reset TITLE (image and text title are mutually exclusive).
/// Shown only when BARPOSITION=TOP.
/// (since 3.14)
pub fn setTitleImage(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "TITLEIMAGE", .{}, arg);
}
pub fn setTitleImageHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "TITLEIMAGE", .{}, arg);
}
pub fn getPosition(self: *Self) iup.XYPos {
var str = interop.getStrAttribute(self, "POSITION", .{});
return iup.XYPos.parse(str, ',');
}
pub fn setPosition(self: *Self, x: i32, y: i32) void {
var buffer: [128]u8 = undefined;
var value = iup.XYPos.intIntToString(&buffer, x, y, ',');
interop.setStrAttribute(self, "POSITION", .{}, value);
}
pub fn getImageExtra1(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "IMAGEEXTRA1", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
pub fn setImageExtra1(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "IMAGEEXTRA1", .{}, arg);
}
pub fn setImageExtra1HandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "IMAGEEXTRA1", .{}, arg);
}
pub fn getImageExtra2(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "IMAGEEXTRA2", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
pub fn setImageExtra2(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "IMAGEEXTRA2", .{}, arg);
}
pub fn setImageExtra2HandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "IMAGEEXTRA2", .{}, arg);
}
pub fn getImageExtra3(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "IMAGEEXTRA3", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
pub fn setImageExtra3(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "IMAGEEXTRA3", .{}, arg);
}
pub fn setImageExtra3HandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "IMAGEEXTRA3", .{}, arg);
}
pub fn getCanFocus(self: *Self) bool {
return interop.getBoolAttribute(self, "CANFOCUS", .{});
}
pub fn setCanFocus(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "CANFOCUS", .{}, arg);
}
pub fn getVisible(self: *Self) bool {
return interop.getBoolAttribute(self, "VISIBLE", .{});
}
pub fn setVisible(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "VISIBLE", .{}, arg);
}
///
/// IMAGE (non inheritable): image name to replace the arrow image by a custom
/// image when STATE=CLOSE.
/// Works only when BARPOSITION=TOP.
/// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name.
/// See also IupImage.
/// (since 3.11)
pub fn getImage(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "IMAGE", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
///
/// IMAGE (non inheritable): image name to replace the arrow image by a custom
/// image when STATE=CLOSE.
/// Works only when BARPOSITION=TOP.
/// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name.
/// See also IupImage.
/// (since 3.11)
pub fn setImage(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "IMAGE", .{}, arg);
}
pub fn setImageHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "IMAGE", .{}, arg);
}
///
/// HIGHCOLOR (non inheritable): title text color when highlighted.
/// Works only when TITLEEXPAND=Yes.
/// Defaults to the FORECOLOR if not defined.
/// (since 3.14)
pub fn getHighColor(self: *Self) ?iup.Rgb {
return interop.getRgb(self, "HIGHCOLOR", .{});
}
///
/// HIGHCOLOR (non inheritable): title text color when highlighted.
/// Works only when TITLEEXPAND=Yes.
/// Defaults to the FORECOLOR if not defined.
/// (since 3.14)
pub fn setHighColor(self: *Self, rgb: iup.Rgb) void {
interop.setRgb(self, "HIGHCOLOR", .{}, rgb);
}
pub fn getTheme(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "THEME", .{});
}
pub fn setTheme(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "THEME", .{}, arg);
}
///
/// EXPAND (non inheritable): the default value is "YES".
pub fn getExpand(self: *Self) ?Expand {
var ret = interop.getStrAttribute(self, "EXPAND", .{});
if (std.ascii.eqlIgnoreCase("YES", ret)) return .Yes;
if (std.ascii.eqlIgnoreCase("HORIZONTAL", ret)) return .Horizontal;
if (std.ascii.eqlIgnoreCase("VERTICAL", ret)) return .Vertical;
if (std.ascii.eqlIgnoreCase("HORIZONTALFREE", ret)) return .HorizontalFree;
if (std.ascii.eqlIgnoreCase("VERTICALFREE", ret)) return .VerticalFree;
if (std.ascii.eqlIgnoreCase("NO", ret)) return .No;
return null;
}
///
/// EXPAND (non inheritable): the default value is "YES".
pub fn setExpand(self: *Self, arg: ?Expand) void {
if (arg) |value| switch (value) {
.Yes => interop.setStrAttribute(self, "EXPAND", .{}, "YES"),
.Horizontal => interop.setStrAttribute(self, "EXPAND", .{}, "HORIZONTAL"),
.Vertical => interop.setStrAttribute(self, "EXPAND", .{}, "VERTICAL"),
.HorizontalFree => interop.setStrAttribute(self, "EXPAND", .{}, "HORIZONTALFREE"),
.VerticalFree => interop.setStrAttribute(self, "EXPAND", .{}, "VERTICALFREE"),
.No => interop.setStrAttribute(self, "EXPAND", .{}, "NO"),
} else {
interop.clearAttribute(self, "EXPAND", .{});
}
}
pub fn getSize(self: *Self) Size {
var str = interop.getStrAttribute(self, "SIZE", .{});
return Size.parse(str);
}
pub fn setSize(self: *Self, width: ?i32, height: ?i32) void {
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self, "SIZE", .{}, value);
}
///
/// WID (read-only): returns -1 if mapped.
pub fn getWId(self: *Self) i32 {
return interop.getIntAttribute(self, "WID", .{});
}
pub fn getFontSize(self: *Self) i32 {
return interop.getIntAttribute(self, "FONTSIZE", .{});
}
pub fn setFontSize(self: *Self, arg: i32) void {
interop.setIntAttribute(self, "FONTSIZE", .{}, arg);
}
pub fn getNaturalSize(self: *Self) Size {
var str = interop.getStrAttribute(self, "NATURALSIZE", .{});
return Size.parse(str);
}
pub fn getUserSize(self: *Self) Size {
var str = interop.getStrAttribute(self, "USERSIZE", .{});
return Size.parse(str);
}
pub fn setUserSize(self: *Self, width: ?i32, height: ?i32) void {
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self, "USERSIZE", .{}, value);
}
pub fn getTitleImageOpenHighlight(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "TITLEIMAGEOPENHIGHLIGHT", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
pub fn setTitleImageOpenHighlight(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "TITLEIMAGEOPENHIGHLIGHT", .{}, arg);
}
pub fn setTitleImageOpenHighlightHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "TITLEIMAGEOPENHIGHLIGHT", .{}, arg);
}
///
/// TITLE (non inheritable): title text, shown in the bar handler near the
/// expand/collapse button.
/// When set it will reset TITLEIMAGE.
/// Shown only when BARPOSITION=TOP.
/// When the TITLE is defined and BARPOSITION=TOP then the expand/collapse
/// button is left aligned.
/// In all other situations the expand/collapse button is centered.
pub fn getTitle(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "TITLE", .{});
}
///
/// TITLE (non inheritable): title text, shown in the bar handler near the
/// expand/collapse button.
/// When set it will reset TITLEIMAGE.
/// Shown only when BARPOSITION=TOP.
/// When the TITLE is defined and BARPOSITION=TOP then the expand/collapse
/// button is left aligned.
/// In all other situations the expand/collapse button is centered.
pub fn setTitle(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "TITLE", .{}, arg);
}
pub fn getPropagateFocus(self: *Self) bool {
return interop.getBoolAttribute(self, "PROPAGATEFOCUS", .{});
}
pub fn setPropagateFocus(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "PROPAGATEFOCUS", .{}, arg);
}
pub fn getFloating(self: *Self) ?Floating {
var ret = interop.getStrAttribute(self, "FLOATING", .{});
if (std.ascii.eqlIgnoreCase("YES", ret)) return .Yes;
if (std.ascii.eqlIgnoreCase("IGNORE", ret)) return .Ignore;
if (std.ascii.eqlIgnoreCase("NO", ret)) return .No;
return null;
}
pub fn setFloating(self: *Self, arg: ?Floating) void {
if (arg) |value| switch (value) {
.Yes => interop.setStrAttribute(self, "FLOATING", .{}, "YES"),
.Ignore => interop.setStrAttribute(self, "FLOATING", .{}, "IGNORE"),
.No => interop.setStrAttribute(self, "FLOATING", .{}, "NO"),
} else {
interop.clearAttribute(self, "FLOATING", .{});
}
}
pub fn getNormalizerGroup(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "NORMALIZERGROUP", .{});
}
pub fn setNormalizerGroup(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "NORMALIZERGROUP", .{}, arg);
}
pub fn getRasterSize(self: *Self) Size {
var str = interop.getStrAttribute(self, "RASTERSIZE", .{});
return Size.parse(str);
}
pub fn setRasterSize(self: *Self, width: ?i32, height: ?i32) void {
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self, "RASTERSIZE", .{}, value);
}
pub fn getImageExtraHighlight1(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "IMAGEEXTRAHIGHLIGHT1", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
pub fn setImageExtraHighlight1(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "IMAGEEXTRAHIGHLIGHT1", .{}, arg);
}
pub fn setImageExtraHighlight1HandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "IMAGEEXTRAHIGHLIGHT1", .{}, arg);
}
pub fn getImageExtraHighlight2(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "IMAGEEXTRAHIGHLIGHT2", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
pub fn setImageExtraHighlight2(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "IMAGEEXTRAHIGHLIGHT2", .{}, arg);
}
pub fn setImageExtraHighlight2HandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "IMAGEEXTRAHIGHLIGHT2", .{}, arg);
}
pub fn getImageExtraHighlight3(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "IMAGEEXTRAHIGHLIGHT3", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
pub fn setImageExtraHighlight3(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "IMAGEEXTRAHIGHLIGHT3", .{}, arg);
}
pub fn setImageExtraHighlight3HandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "IMAGEEXTRAHIGHLIGHT3", .{}, arg);
}
///
/// BARSIZE (non inheritable): controls the size of the bar handler.
/// Default: the height or width that fits all its internal elements according
/// to BARPOSITION.
pub fn getBarSize(self: *Self) i32 {
return interop.getIntAttribute(self, "BARSIZE", .{});
}
///
/// BARSIZE (non inheritable): controls the size of the bar handler.
/// Default: the height or width that fits all its internal elements according
/// to BARPOSITION.
pub fn setBarSize(self: *Self, arg: i32) void {
interop.setIntAttribute(self, "BARSIZE", .{}, arg);
}
///
/// FRAMECOLOR (non inheritable): frame line color.
/// Default: the global attribute DLGFGCOLOR.
/// (since 3.23)
pub fn getFrameColor(self: *Self) ?iup.Rgb {
return interop.getRgb(self, "FRAMECOLOR", .{});
}
///
/// FRAMECOLOR (non inheritable): frame line color.
/// Default: the global attribute DLGFGCOLOR.
/// (since 3.23)
pub fn setFrameColor(self: *Self, rgb: iup.Rgb) void {
interop.setRgb(self, "FRAMECOLOR", .{}, rgb);
}
pub fn getFontFace(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "FONTFACE", .{});
}
pub fn setFontFace(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "FONTFACE", .{}, arg);
}
///
/// TITLEIMAGEOPEN: image name used when STATE=OPEN.
/// TITLEIMAGEHIGHLIGHT: image name used when mouse is over the title image and
/// STATE=CLOSE.TITLEIMAGEOPENHIGHLIGHT: image name used when mouse is over the
/// title image and STATE=OPEN.
pub fn getTitleImageOpen(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "TITLEIMAGEOPEN", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
///
/// TITLEIMAGEOPEN: image name used when STATE=OPEN.
/// TITLEIMAGEHIGHLIGHT: image name used when mouse is over the title image and
/// STATE=CLOSE.TITLEIMAGEOPENHIGHLIGHT: image name used when mouse is over the
/// title image and STATE=OPEN.
pub fn setTitleImageOpen(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "TITLEIMAGEOPEN", .{}, arg);
}
pub fn setTitleImageOpenHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "TITLEIMAGEOPEN", .{}, arg);
}
pub fn getName(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "NAME", .{});
}
pub fn setName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "NAME", .{}, arg);
}
///
/// STATE (non inheritable): Show or hide the container elements.
/// Possible values: "OPEN" (expanded) or "CLOSE" (collapsed).
/// Default: OPEN.
/// Setting this attribute will automatically change the layout of the entire
/// dialog so the child can be recomposed.
pub fn getState(self: *Self) ?State {
var ret = interop.getStrAttribute(self, "STATE", .{});
if (std.ascii.eqlIgnoreCase("OPEN", ret)) return .Open;
if (std.ascii.eqlIgnoreCase("CLOSED", ret)) return .Closed;
return null;
}
///
/// STATE (non inheritable): Show or hide the container elements.
/// Possible values: "OPEN" (expanded) or "CLOSE" (collapsed).
/// Default: OPEN.
/// Setting this attribute will automatically change the layout of the entire
/// dialog so the child can be recomposed.
pub fn setState(self: *Self, arg: ?State) void {
if (arg) |value| switch (value) {
.Open => interop.setStrAttribute(self, "STATE", .{}, "OPEN"),
.Closed => interop.setStrAttribute(self, "STATE", .{}, "CLOSED"),
} else {
interop.clearAttribute(self, "STATE", .{});
}
}
pub fn getActive(self: *Self) bool {
return interop.getBoolAttribute(self, "ACTIVE", .{});
}
pub fn setActive(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "ACTIVE", .{}, arg);
}
pub fn getImageHighlight(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "IMAGEHIGHLIGHT", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
pub fn setImageHighlight(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "IMAGEHIGHLIGHT", .{}, arg);
}
pub fn setImageHighlightHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "IMAGEHIGHLIGHT", .{}, arg);
}
pub fn getExpandWeight(self: *Self) f64 {
return interop.getDoubleAttribute(self, "EXPANDWEIGHT", .{});
}
pub fn setExpandWeight(self: *Self, arg: f64) void {
interop.setDoubleAttribute(self, "EXPANDWEIGHT", .{}, arg);
}
pub fn getMinSize(self: *Self) Size {
var str = interop.getStrAttribute(self, "MINSIZE", .{});
return Size.parse(str);
}
pub fn setMinSize(self: *Self, width: ?i32, height: ?i32) void {
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self, "MINSIZE", .{}, value);
}
pub fn getTitleImageHighlight(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "TITLEIMAGEHIGHLIGHT", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
pub fn setTitleImageHighlight(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "TITLEIMAGEHIGHLIGHT", .{}, arg);
}
pub fn setTitleImageHighlightHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "TITLEIMAGEHIGHLIGHT", .{}, arg);
}
pub fn getNTheme(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "NTHEME", .{});
}
pub fn setNTheme(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "NTHEME", .{}, arg);
}
///
/// ANIMATION (non inheritable): enable animation during open/close.
/// Works only for BARPOSITION=TOP and does not works for AUTOSHOW.
/// Also the child must be a native container like IupTabs, IupFrame,
/// IupBackgroundBox, or IupScrollBox, or it will not work accordantly.
/// Values can be SLIDE (child controls slide down), CURTAIN (child controls
/// appears as if a curtain is being pulled) or NO.
/// Default: NO.
/// ((since 3.14)
pub fn getAnimation(self: *Self) ?Animation {
var ret = interop.getStrAttribute(self, "ANIMATION", .{});
if (std.ascii.eqlIgnoreCase("SLIDE", ret)) return .Slide;
if (std.ascii.eqlIgnoreCase("CURTAIN", ret)) return .Curtain;
if (std.ascii.eqlIgnoreCase("NO", ret)) return .No;
return null;
}
///
/// ANIMATION (non inheritable): enable animation during open/close.
/// Works only for BARPOSITION=TOP and does not works for AUTOSHOW.
/// Also the child must be a native container like IupTabs, IupFrame,
/// IupBackgroundBox, or IupScrollBox, or it will not work accordantly.
/// Values can be SLIDE (child controls slide down), CURTAIN (child controls
/// appears as if a curtain is being pulled) or NO.
/// Default: NO.
/// ((since 3.14)
pub fn setAnimation(self: *Self, arg: ?Animation) void {
if (arg) |value| switch (value) {
.Slide => interop.setStrAttribute(self, "ANIMATION", .{}, "SLIDE"),
.Curtain => interop.setStrAttribute(self, "ANIMATION", .{}, "CURTAIN"),
.No => interop.setStrAttribute(self, "ANIMATION", .{}, "NO"),
} else {
interop.clearAttribute(self, "ANIMATION", .{});
}
}
pub fn getCharSize(self: *Self) Size {
var str = interop.getStrAttribute(self, "CHARSIZE", .{});
return Size.parse(str);
}
pub fn getClientSize(self: *Self) Size {
var str = interop.getStrAttribute(self, "CLIENTSIZE", .{});
return Size.parse(str);
}
pub fn getClientOffset(self: *Self) Size {
var str = interop.getStrAttribute(self, "CLIENTOFFSET", .{});
return Size.parse(str);
}
///
/// FORECOLOR (non inheritable): title text color.
/// Default: the global attribute DLGFGCOLOR.
/// (since 3.9)
pub fn getForeColor(self: *Self) ?iup.Rgb {
return interop.getRgb(self, "FORECOLOR", .{});
}
///
/// FORECOLOR (non inheritable): title text color.
/// Default: the global attribute DLGFGCOLOR.
/// (since 3.9)
pub fn setForeColor(self: *Self, rgb: iup.Rgb) void {
interop.setRgb(self, "FORECOLOR", .{}, rgb);
}
pub fn getFontStyle(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "FONTSTYLE", .{});
}
pub fn setFontStyle(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "FONTSTYLE", .{}, arg);
}
///
/// IMAGEOPEN: image name used when STATE=OPEN.
/// IMAGEHIGHLIGHT: image name used when mouse is over the bar handler and
/// STATE=CLOSE.IMAGEOPENHIGHLIGHT: image name used when mouse is over the bar
/// handler and STATE=OPEN.
pub fn getImageOpen(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "IMAGEOPEN", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
///
/// IMAGEOPEN: image name used when STATE=OPEN.
/// IMAGEHIGHLIGHT: image name used when mouse is over the bar handler and
/// STATE=CLOSE.IMAGEOPENHIGHLIGHT: image name used when mouse is over the bar
/// handler and STATE=OPEN.
pub fn setImageOpen(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "IMAGEOPEN", .{}, arg);
}
pub fn setImageOpenHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "IMAGEOPEN", .{}, arg);
}
///
/// FRAMEWIDTH (non inheritable): frame line width.
/// Default: 1.
/// (since 3.23)
pub fn getFrameWidth(self: *Self) i32 {
return interop.getIntAttribute(self, "FRAMEWIDTH", .{});
}
///
/// FRAMEWIDTH (non inheritable): frame line width.
/// Default: 1.
/// (since 3.23)
pub fn setFrameWidth(self: *Self, arg: i32) void {
interop.setIntAttribute(self, "FRAMEWIDTH", .{}, arg);
}
///
/// FRAME (non inheritable): enables the frame line around the bar area.
/// Default: No.
/// (since 3.23)
pub fn getFrame(self: *Self) bool {
return interop.getBoolAttribute(self, "FRAME", .{});
}
///
/// FRAME (non inheritable): enables the frame line around the bar area.
/// Default: No.
/// (since 3.23)
pub fn setFrame(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "FRAME", .{}, arg);
}
///
/// FONT, SIZE, RASTERSIZE, CLIENTSIZE, CLIENTOFFSET, POSITION, MINSIZE,
/// MAXSIZE, THEME: also accepted.
pub fn getFont(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "FONT", .{});
}
///
/// FONT, SIZE, RASTERSIZE, CLIENTSIZE, CLIENTOFFSET, POSITION, MINSIZE,
/// MAXSIZE, THEME: also accepted.
pub fn setFont(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "FONT", .{}, arg);
}
///
/// TABIMAGEn (non inheritable): image name to be used in the respective tab.
/// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name.
/// n starts at 0.
/// See also IupImage.
/// In Motif, the image is shown only if TABTITLEn is NULL.
/// In Windows and Motif set the BGCOLOR attribute before setting the image.
/// When set after map will update the TABIMAGE attribute on the respective
/// child (since 3.10).
/// (since 3.0).
/// TABIMAGE (non inheritable) (at children only): Same as TABIMAGEn but set in
/// each child.
/// Works only if set before the child is added to the tabs.
pub fn getTabImage(self: *Self, index: i32) ?iup.Element {
if (interop.getHandleAttribute(self, "TABIMAGE", .{index})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
///
/// TABIMAGEn (non inheritable): image name to be used in the respective tab.
/// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name.
/// n starts at 0.
/// See also IupImage.
/// In Motif, the image is shown only if TABTITLEn is NULL.
/// In Windows and Motif set the BGCOLOR attribute before setting the image.
/// When set after map will update the TABIMAGE attribute on the respective
/// child (since 3.10).
/// (since 3.0).
/// TABIMAGE (non inheritable) (at children only): Same as TABIMAGEn but set in
/// each child.
/// Works only if set before the child is added to the tabs.
pub fn setTabImage(self: *Self, index: i32, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "TABIMAGE", .{index}, arg);
}
pub fn setTabImageHandleName(self: *Self, index: i32, arg: [:0]const u8) void {
interop.setStrAttribute(self, "TABIMAGE", .{index}, arg);
}
///
/// TABTITLEn (non inheritable): Contains the text to be shown in the
/// respective tab title.
/// n starts at 0.
/// If this value is NULL, it will remain empty.
/// The "&" character can be used to define a mnemonic, the next character will
/// be used as key.
/// Use "&&" to show the "&" character instead on defining a mnemonic.
/// The button can be activated from any control in the dialog using the
/// "Alt+key" combination.
/// (mnemonic support since 3.3).
/// When set after map will update the TABTITLE attribute on the respective
/// child (since 3.10).
/// (since 3.0).
/// TABTITLE (non inheritable) (at children only): Same as TABTITLEn but set in
/// each child.
/// Works only if set before the child is added to the tabs.
pub fn getTabTitle(self: *Self, index: i32) [:0]const u8 {
return interop.getStrAttribute(self, "TABTITLE", .{index});
}
///
/// TABTITLEn (non inheritable): Contains the text to be shown in the
/// respective tab title.
/// n starts at 0.
/// If this value is NULL, it will remain empty.
/// The "&" character can be used to define a mnemonic, the next character will
/// be used as key.
/// Use "&&" to show the "&" character instead on defining a mnemonic.
/// The button can be activated from any control in the dialog using the
/// "Alt+key" combination.
/// (mnemonic support since 3.3).
/// When set after map will update the TABTITLE attribute on the respective
/// child (since 3.10).
/// (since 3.0).
/// TABTITLE (non inheritable) (at children only): Same as TABTITLEn but set in
/// each child.
/// Works only if set before the child is added to the tabs.
pub fn setTabTitle(self: *Self, index: i32, arg: [:0]const u8) void {
interop.setStrAttribute(self, "TABTITLE", .{index}, arg);
}
///
/// ACTION ACTION Action generated when the element is activated.
/// Affects each element differently.
/// Callback int function(Ihandle *ih); [in C] ih:action() -> (ret: number) [in
/// Lua] ih: identifier of the element that activated the event.
/// In some elements, this callback may receive more parameters, apart from ih.
/// Please refer to each element's documentation.
/// Affects IupButton, IupItem, IupList, IupText, IupCanvas, IupMultiline,
/// IupToggle
pub fn setActionCallback(self: *Self, callback: ?OnActionFn) void {
const Handler = CallbackHandler(Self, OnActionFn, "ACTION");
Handler.setCallback(self, callback);
}
///
/// EXTRABUTTON_CB: Action generated when any mouse button is pressed or released.
/// (since 3.11) int function(Ihandle* ih, int button, int pressed); [in C]
/// ih:extrabutton_cb(button, pressed: number) -> (ret: number) [in Lua] ih:
/// identifies the element that activated the event.
/// button: identifies the extra button.
/// can be 1, 2 or 3.
/// (this is not the same as BUTTON_CB)pressed: indicates the state of the
/// button: 0 - mouse button was released; 1 - mouse button was pressed.
pub fn setExtraButtonCallback(self: *Self, callback: ?OnExtraButtonFn) void {
const Handler = CallbackHandler(Self, OnExtraButtonFn, "EXTRABUTTON_CB");
Handler.setCallback(self, callback);
}
///
/// OPENCLOSE_CB: Action generated before the expander state is interactively changed.
/// (Since 3.11) int function(Ihandle* ih, int state); [in
/// C]ih:openclose_cb(state: number) -> (ret: number) [in Lua]
pub fn setOpenCloseCallback(self: *Self, callback: ?OnOpenCloseFn) void {
const Handler = CallbackHandler(Self, OnOpenCloseFn, "OPENCLOSE_CB");
Handler.setCallback(self, callback);
}
///
/// MAP_CB MAP_CB Called right after an element is mapped and its attributes
/// updated in IupMap.
/// When the element is a dialog, it is called after the layout is updated.
/// For all other elements is called before the layout is updated, so the
/// element current size will still be 0x0 during MAP_CB (since 3.14).
/// Callback int function(Ihandle *ih); [in C] ih:map_cb() -> (ret: number) [in
/// Lua] ih: identifier of the element that activated the event.
/// Affects All that have a native representation.
pub fn setMapCallback(self: *Self, callback: ?OnMapFn) void {
const Handler = CallbackHandler(Self, OnMapFn, "MAP_CB");
Handler.setCallback(self, callback);
}
///
/// DESTROY_CB DESTROY_CB Called right before an element is destroyed.
/// Callback int function(Ihandle *ih); [in C] ih:destroy_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Notes If the dialog is visible then it is hidden before it is destroyed.
/// The callback will be called right after it is hidden.
/// The callback will be called before all other destroy procedures.
/// For instance, if the element has children then it is called before the
/// children are destroyed.
/// For language binding implementations use the callback name "LDESTROY_CB" to
/// release memory allocated by the binding for the element.
/// Also the callback will be called before the language callback.
/// Affects All.
pub fn setDestroyCallback(self: *Self, callback: ?OnDestroyFn) void {
const Handler = CallbackHandler(Self, OnDestroyFn, "DESTROY_CB");
Handler.setCallback(self, callback);
}
///
/// UNMAP_CB UNMAP_CB Called right before an element is unmapped.
/// Callback int function(Ihandle *ih); [in C] ih:unmap_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Affects All that have a native representation.
pub fn setUnmapCallback(self: *Self, callback: ?OnUnmapFn) void {
const Handler = CallbackHandler(Self, OnUnmapFn, "UNMAP_CB");
Handler.setCallback(self, callback);
}
pub fn setLDestroyCallback(self: *Self, callback: ?OnLDestroyFn) void {
const Handler = CallbackHandler(Self, OnLDestroyFn, "LDESTROY_CB");
Handler.setCallback(self, callback);
}
pub fn setPostMessageCallback(self: *Self, callback: ?OnPostMessageFn) void {
const Handler = CallbackHandler(Self, OnPostMessageFn, "POSTMESSAGE_CB");
Handler.setCallback(self, callback);
}
};
test "Expander HandleName" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setHandleName("Hello").unwrap());
defer item.deinit();
var ret = item.getHandleName();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "Expander FrameTime" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setFrameTime(42).unwrap());
defer item.deinit();
var ret = item.getFrameTime();
try std.testing.expect(ret == 42);
}
test "Expander BackColor" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setBackColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap());
defer item.deinit();
var ret = item.getBackColor();
try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11);
}
test "Expander MaxSize" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setMaxSize(9, 10).unwrap());
defer item.deinit();
var ret = item.getMaxSize();
try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10);
}
test "Expander Position" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setPosition(9, 10).unwrap());
defer item.deinit();
var ret = item.getPosition();
try std.testing.expect(ret.x == 9 and ret.y == 10);
}
test "Expander CanFocus" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setCanFocus(true).unwrap());
defer item.deinit();
var ret = item.getCanFocus();
try std.testing.expect(ret == true);
}
test "Expander Visible" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setVisible(true).unwrap());
defer item.deinit();
var ret = item.getVisible();
try std.testing.expect(ret == true);
}
test "Expander HighColor" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setHighColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap());
defer item.deinit();
var ret = item.getHighColor();
try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11);
}
test "Expander Theme" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setTheme("Hello").unwrap());
defer item.deinit();
var ret = item.getTheme();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "Expander Expand" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setExpand(.Yes).unwrap());
defer item.deinit();
var ret = item.getExpand();
try std.testing.expect(ret != null and ret.? == .Yes);
}
test "Expander Size" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setSize(9, 10).unwrap());
defer item.deinit();
var ret = item.getSize();
try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10);
}
test "Expander FontSize" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setFontSize(42).unwrap());
defer item.deinit();
var ret = item.getFontSize();
try std.testing.expect(ret == 42);
}
test "Expander UserSize" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setUserSize(9, 10).unwrap());
defer item.deinit();
var ret = item.getUserSize();
try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10);
}
test "Expander Title" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setTitle("Hello").unwrap());
defer item.deinit();
var ret = item.getTitle();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "Expander PropagateFocus" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setPropagateFocus(true).unwrap());
defer item.deinit();
var ret = item.getPropagateFocus();
try std.testing.expect(ret == true);
}
test "Expander Floating" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setFloating(.Yes).unwrap());
defer item.deinit();
var ret = item.getFloating();
try std.testing.expect(ret != null and ret.? == .Yes);
}
test "Expander NormalizerGroup" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setNormalizerGroup("Hello").unwrap());
defer item.deinit();
var ret = item.getNormalizerGroup();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "Expander RasterSize" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setRasterSize(9, 10).unwrap());
defer item.deinit();
var ret = item.getRasterSize();
try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10);
}
test "Expander BarSize" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setBarSize(42).unwrap());
defer item.deinit();
var ret = item.getBarSize();
try std.testing.expect(ret == 42);
}
test "Expander FrameColor" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setFrameColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap());
defer item.deinit();
var ret = item.getFrameColor();
try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11);
}
test "Expander FontFace" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setFontFace("Hello").unwrap());
defer item.deinit();
var ret = item.getFontFace();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "Expander Name" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setName("Hello").unwrap());
defer item.deinit();
var ret = item.getName();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "Expander State" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setState(.Open).unwrap());
defer item.deinit();
var ret = item.getState();
try std.testing.expect(ret != null and ret.? == .Open);
}
test "Expander Active" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setActive(true).unwrap());
defer item.deinit();
var ret = item.getActive();
try std.testing.expect(ret == true);
}
test "Expander ExpandWeight" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setExpandWeight(3.14).unwrap());
defer item.deinit();
var ret = item.getExpandWeight();
try std.testing.expect(ret == @as(f64, 3.14));
}
test "Expander MinSize" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setMinSize(9, 10).unwrap());
defer item.deinit();
var ret = item.getMinSize();
try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10);
}
test "Expander NTheme" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setNTheme("Hello").unwrap());
defer item.deinit();
var ret = item.getNTheme();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "Expander Animation" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setAnimation(.Slide).unwrap());
defer item.deinit();
var ret = item.getAnimation();
try std.testing.expect(ret != null and ret.? == .Slide);
}
test "Expander ForeColor" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setForeColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap());
defer item.deinit();
var ret = item.getForeColor();
try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11);
}
test "Expander FontStyle" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setFontStyle("Hello").unwrap());
defer item.deinit();
var ret = item.getFontStyle();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "Expander FrameWidth" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setFrameWidth(42).unwrap());
defer item.deinit();
var ret = item.getFrameWidth();
try std.testing.expect(ret == 42);
}
test "Expander Frame" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setFrame(true).unwrap());
defer item.deinit();
var ret = item.getFrame();
try std.testing.expect(ret == true);
}
test "Expander Font" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Expander.init().setFont("Hello").unwrap());
defer item.deinit();
var ret = item.getFont();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
|
src/elements/expander.zig
|
const std = @import("std");
const Lua = @import("lua.zig").Lua;
const assert = std.debug.assert;
test "set/get scalar" {
var lua = try Lua.init(std.testing.allocator);
defer lua.destroy();
const int16In: i16 = 1;
const int32In: i32 = 2;
const int64In: i64 = 3;
const f16In: f16 = 3.1415;
const f32In: f32 = 3.1415;
const f64In: f64 = 3.1415;
const bIn: bool = true;
lua.set("int16", int16In);
lua.set("int32", int32In);
lua.set("int64", int64In);
lua.set("float16", f16In);
lua.set("float32", f32In);
lua.set("float64", f64In);
lua.set("bool", bIn);
var int16Out = try lua.get(i16, "int16");
var int32Out = try lua.get(i32, "int32");
var int64Out = try lua.get(i64, "int64");
var f16Out = try lua.get(f16, "float16");
var f32Out = try lua.get(f32, "float32");
var f64Out = try lua.get(f64, "float64");
var bOut = try lua.get(bool, "bool");
try std.testing.expectEqual(int16In, int16Out);
try std.testing.expectEqual(int32In, int32Out);
try std.testing.expectEqual(int64In, int64Out);
try std.testing.expectEqual(f16In, f16Out);
try std.testing.expectEqual(f32In, f32Out);
try std.testing.expectEqual(f64In, f64Out);
try std.testing.expectEqual(bIn, bOut);
}
test "set/get string" {
var lua = try Lua.init(std.testing.allocator);
defer lua.destroy();
var strMany: [*]const u8 = "macilaci";
var strSlice: []const u8 = "macilaic";
var strOne = "macilaci";
var strC: [*c]const u8 = "macilaci";
const cstrMany: [*]const u8 = "macilaci";
const cstrSlice: []const u8 = "macilaic";
const cstrOne = "macilaci";
const cstrC: [*c]const u8 = "macilaci";
lua.set("stringMany", strMany);
lua.set("stringSlice", strSlice);
lua.set("stringOne", strOne);
lua.set("stringC", strC);
lua.set("cstringMany", cstrMany);
lua.set("cstringSlice", cstrSlice);
lua.set("cstringOne", cstrOne);
lua.set("cstringC", cstrC);
const retStrMany = try lua.get([]const u8, "stringMany");
const retCStrMany = try lua.get([]const u8, "cstringMany");
const retStrSlice = try lua.get([]const u8, "stringSlice");
const retCStrSlice = try lua.get([]const u8, "cstringSlice");
const retStrOne = try lua.get([]const u8, "stringOne");
const retCStrOne = try lua.get([]const u8, "cstringOne");
const retStrC = try lua.get([]const u8, "stringC");
const retCStrC = try lua.get([]const u8, "cstringC");
try std.testing.expect(std.mem.eql(u8, strMany[0..retStrMany.len], retStrMany));
try std.testing.expect(std.mem.eql(u8, strSlice[0..retStrSlice.len], retStrSlice));
try std.testing.expect(std.mem.eql(u8, strOne[0..retStrOne.len], retStrOne));
try std.testing.expect(std.mem.eql(u8, strC[0..retStrC.len], retStrC));
try std.testing.expect(std.mem.eql(u8, cstrMany[0..retStrMany.len], retCStrMany));
try std.testing.expect(std.mem.eql(u8, cstrSlice[0..retStrSlice.len], retCStrSlice));
try std.testing.expect(std.mem.eql(u8, cstrOne[0..retStrOne.len], retCStrOne));
try std.testing.expect(std.mem.eql(u8, cstrC[0..retStrC.len], retCStrC));
}
test "set/get slice of primitive type (scalar, unmutable string)" {
var lua = try Lua.init(std.testing.allocator);
defer lua.destroy();
const boolSlice = [_]bool{ true, false, true };
const intSlice = [_]i32{ 4, 5, 3, 4, 0 };
const strSlice = [_][]const u8{ "Macilaci", "Gyumifagyi", "Angolhazi" };
lua.set("boolSlice", boolSlice);
lua.set("intSlice", intSlice);
lua.set("strSlice", strSlice);
const retBoolSlice = try lua.getResource([]i32, "boolSlice");
defer lua.release(retBoolSlice);
const retIntSlice = try lua.getResource([]i32, "intSlice");
defer lua.release(retIntSlice);
const retStrSlice = try lua.getResource([][]const u8, "strSlice");
defer lua.release(retStrSlice);
for (retIntSlice) |v, i| {
try std.testing.expectEqual(v, intSlice[i]);
}
for (retStrSlice) |v, i| {
try std.testing.expect(std.mem.eql(u8, v, strSlice[i]));
}
}
test "simple Zig => Lua function call" {
var lua = try Lua.init(std.testing.allocator);
defer lua.destroy();
lua.openLibs();
const lua_command =
\\function test_1() end
\\function test_2(a) end
\\function test_3(a) return a; end
\\function test_4(a,b) return a+b; end
;
lua.run(lua_command);
var fun1 = try lua.getResource(Lua.Function(fn () void), "test_1");
defer lua.release(fun1);
var fun2 = try lua.getResource(Lua.Function(fn (a: i32) void), "test_2");
defer lua.release(fun2);
var fun3_1 = try lua.getResource(Lua.Function(fn (a: i32) i32), "test_3");
defer lua.release(fun3_1);
var fun3_2 = try lua.getResource(Lua.Function(fn (a: []const u8) []const u8), "test_3");
defer lua.release(fun3_2);
var fun4 = try lua.getResource(Lua.Function(fn (a: i32, b: i32) i32), "test_4");
defer lua.release(fun4);
try fun1.call(.{});
try fun2.call(.{42});
const res3_1 = try fun3_1.call(.{42});
try std.testing.expectEqual(res3_1, 42);
const res3_2 = try fun3_2.call(.{"Bela"});
try std.testing.expect(std.mem.eql(u8, res3_2, "Bela"));
const res4 = try fun4.call(.{ 42, 24 });
try std.testing.expectEqual(res4, 66);
}
var testResult0: bool = false;
fn testFun0() void {
testResult0 = true;
}
var testResult1: i32 = 0;
fn testFun1(a: i32, b: i32) void {
testResult1 = a - b;
}
var testResult2: i32 = 0;
fn testFun2(a: []const u8) void {
for (a) |ch| {
testResult2 += ch - '0';
}
}
var testResult3: i32 = 0;
fn testFun3(a: []const u8, b: i32) void {
for (a) |ch| {
testResult3 += ch - '0';
}
testResult3 -= b;
}
test "simple Lua => Zig function call" {
var lua = try Lua.init(std.testing.allocator);
defer lua.destroy();
lua.openLibs();
lua.set("testFun0", testFun0);
lua.set("testFun1", testFun1);
lua.set("testFun2", testFun2);
lua.set("testFun3", testFun3);
lua.run("testFun0()");
try std.testing.expect(testResult0 == true);
lua.run("testFun1(42,10)");
try std.testing.expect(testResult1 == 32);
lua.run("testFun2('0123456789')");
try std.testing.expect(testResult2 == 45);
lua.run("testFun3('0123456789', -10)");
try std.testing.expect(testResult3 == 55);
testResult0 = false;
testResult1 = 0;
testResult2 = 0;
testResult3 = 0;
lua.run("testFun3('0123456789', -10)");
try std.testing.expect(testResult3 == 55);
lua.run("testFun2('0123456789')");
try std.testing.expect(testResult2 == 45);
lua.run("testFun1(42,10)");
try std.testing.expect(testResult1 == 32);
lua.run("testFun0()");
try std.testing.expect(testResult0 == true);
}
fn testFun4(a: []const u8) []const u8 {
return a;
}
fn testFun5(a: i32, b: i32) i32 {
return a - b;
}
test "simple Zig => Lua => Zig function call" {
var lua = try Lua.init(std.testing.allocator);
defer lua.destroy();
lua.openLibs();
lua.set("testFun4", testFun4);
lua.set("testFun5", testFun5);
lua.run("function luaTestFun4(a) return testFun4(a); end");
lua.run("function luaTestFun5(a,b) return testFun5(a,b); end");
var fun4 = try lua.getResource(Lua.Function(fn (a: []const u8) []const u8), "luaTestFun4");
defer lua.release(fun4);
var fun5 = try lua.getResource(Lua.Function(fn (a: i32, b: i32) i32), "luaTestFun5");
defer lua.release(fun5);
var res4 = try fun4.call(.{"macika"});
var res5 = try fun5.call(.{ 42, 1 });
try std.testing.expect(std.mem.eql(u8, res4, "macika"));
try std.testing.expect(res5 == 41);
}
fn testLuaInnerFun(fun: Lua.Function(fn (a: i32) i32)) i32 {
var res = fun.call(.{42}) catch unreachable;
return res;
}
test "Lua function injection into Zig function" {
var lua = try Lua.init(std.testing.allocator);
defer lua.destroy();
lua.openLibs();
// Binding on Zig side
lua.run("function getInt(a) return a+1; end");
var luafun = try lua.getResource(Lua.Function(fn (a: i32) i32), "getInt");
defer lua.release(luafun);
var result = testLuaInnerFun(luafun);
std.log.info("Zig Result: {}", .{result});
// Binding on Lua side
lua.set("zigFunction", testLuaInnerFun);
const lua_command =
\\function getInt(a) return a+1; end
\\zigFunction(getInt);
;
lua.run(lua_command);
}
fn zigInnerFun(a: i32) i32 {
return 2 * a;
}
test "Zig function injection into Lua function" {
var lua = try Lua.init(std.testing.allocator);
defer lua.destroy();
lua.openLibs();
// Binding
lua.set("zigFunction", zigInnerFun);
const lua_command =
\\function test(a) res = a(2); return res; end
\\test(zigFunction);
;
lua.run(lua_command);
}
fn testSliceInput(a: []i32) i32 {
var sum: i32 = 0;
for (a) |v| {
sum += v;
}
return sum;
}
test "Slice input to Zig function" {
var lua = try Lua.init(std.testing.allocator);
defer lua.destroy();
lua.openLibs();
// Binding
lua.set("sumFunction", testSliceInput);
const lua_command =
\\res = sumFunction({1,2,3});
;
lua.run(lua_command);
}
test "Lua.Table allocless set/get tests" {
var lua = try Lua.init(std.testing.allocator);
defer lua.destroy();
lua.openLibs();
// Create table
var originalTbl = try lua.createTable();
defer originalTbl.destroy();
lua.set("tbl", originalTbl);
originalTbl.set("owner", true);
var tbl = try lua.getResource(Lua.Table, "tbl");
defer lua.release(tbl);
const owner = try tbl.get(bool, "owner");
try std.testing.expect(owner);
// Numeric
const int16In: i16 = 1;
const int32In: i32 = 2;
const int64In: i64 = 3;
const f16In: f16 = 3.1415;
const f32In: f32 = 3.1415;
const f64In: f64 = 3.1415;
const bIn: bool = true;
tbl.set("int16", int16In);
tbl.set("int32", int32In);
tbl.set("int64", int64In);
tbl.set("float16", f16In);
tbl.set("float32", f32In);
tbl.set("float64", f64In);
tbl.set("bool", bIn);
var int16Out = try tbl.get(i16, "int16");
var int32Out = try tbl.get(i32, "int32");
var int64Out = try tbl.get(i64, "int64");
var f16Out = try tbl.get(f16, "float16");
var f32Out = try tbl.get(f32, "float32");
var f64Out = try tbl.get(f64, "float64");
var bOut = try tbl.get(bool, "bool");
try std.testing.expectEqual(int16In, int16Out);
try std.testing.expectEqual(int32In, int32Out);
try std.testing.expectEqual(int64In, int64Out);
try std.testing.expectEqual(f16In, f16Out);
try std.testing.expectEqual(f32In, f32Out);
try std.testing.expectEqual(f64In, f64Out);
try std.testing.expectEqual(bIn, bOut);
// String
const str: []const u8 = "Hello World";
tbl.set("str", str);
const retStr = try tbl.get([]const u8, "str");
try std.testing.expect(std.mem.eql(u8, str, retStr));
}
fn tblFun(a: i32) i32 {
return 3 * a;
}
test "Lua.Table inner table tests" {
var lua = try Lua.init(std.testing.allocator);
defer lua.destroy();
lua.openLibs();
// Create table
var tbl = try lua.createTable();
defer lua.release(tbl);
lua.set("tbl", tbl);
var inTbl0 = try lua.createTable();
defer lua.release(inTbl0);
var inTbl1 = try lua.createTable();
defer lua.release(inTbl1);
inTbl1.set("str", "string");
inTbl1.set("int32", 68);
inTbl1.set("fn", tblFun);
inTbl0.set(1, "string");
inTbl0.set(2, 3.1415);
inTbl0.set(3, 42);
inTbl0.set("table", inTbl1);
tbl.set("innerTable", inTbl0);
var retTbl = try lua.getResource(Lua.Table, "tbl");
defer lua.release(retTbl);
var retInnerTable = try retTbl.getResource(Lua.Table, "innerTable");
defer lua.release(retInnerTable);
var str = try retInnerTable.get([]const u8, 1);
var float = try retInnerTable.get(f32, 2);
var int = try retInnerTable.get(i32, 3);
try std.testing.expect(std.mem.eql(u8, str, "string"));
try std.testing.expect(float == 3.1415);
try std.testing.expect(int == 42);
var retInner2Table = try retInnerTable.getResource(Lua.Table, "table");
defer lua.release(retInner2Table);
str = try retInner2Table.get([]const u8, "str");
int = try retInner2Table.get(i32, "int32");
var func = try retInner2Table.getResource(Lua.Function(fn (a: i32) i32), "fn");
defer lua.release(func);
var funcRes = try func.call(.{42});
try std.testing.expect(std.mem.eql(u8, str, "string"));
try std.testing.expect(int == 68);
try std.testing.expect(funcRes == 3 * 42);
}
var luaTableArgSum: i32 = 0;
fn testLuaTableArg(t: Lua.Table) i32 {
var a = t.get(i32, "a") catch -1;
var b = t.get(i32, "b") catch -1;
luaTableArgSum = a + b;
return luaTableArgSum;
}
test "Function with Lua.Table argument" {
var lua = try Lua.init(std.testing.allocator);
defer lua.destroy();
lua.openLibs();
// Zig side
var tbl = try lua.createTable();
defer lua.release(tbl);
tbl.set("a", 42);
tbl.set("b", 128);
var zigRes = testLuaTableArg(tbl);
try std.testing.expect(zigRes == 42 + 128);
// Lua side
lua.set("sumFn", testLuaTableArg);
lua.run("function test() return sumFn({a=1, b=2}); end");
var luaFun = try lua.getResource(Lua.Function(fn () i32), "test");
defer lua.release(luaFun);
var luaRes = try luaFun.call(.{});
try std.testing.expect(luaRes == 1 + 2);
}
fn testLuaTableArgOut(t: Lua.Table) Lua.Table {
t.set(1, 42);
t.set(2, 128);
return t;
}
test "Function with Lua.Table result" {
var lua = try Lua.init(std.testing.allocator);
defer lua.destroy();
lua.openLibs();
lua.injectPrettyPrint();
// Zig side
var tbl = try lua.createTable();
defer lua.release(tbl);
var zigRes = testLuaTableArgOut(tbl);
var zigA = try zigRes.get(i32, 1);
var zigB = try zigRes.get(i32, 2);
try std.testing.expect((zigA + zigB) == 42 + 128);
// Lua side
lua.set("tblFn", testLuaTableArgOut);
//lua.run("function test() tbl = tblFn({}); return tbl[1] + tbl[2]; end");
lua.run("function test() tbl = tblFn({}); return tbl[1] + tbl[2]; end");
var luaFun = try lua.getResource(Lua.Function(fn () i32), "test");
defer lua.release(luaFun);
var luaRes = try luaFun.call(.{});
try std.testing.expect(luaRes == 42 + 128);
}
const TestCustomType = struct {
a: i32,
b: f32,
c: []const u8,
d: bool,
pub fn init(_a: i32, _b: f32, _c: []const u8, _d: bool) TestCustomType {
return TestCustomType{
.a = _a,
.b = _b,
.c = _c,
.d = _d,
};
}
pub fn destroy(_: *TestCustomType) void {}
pub fn getA(self: *TestCustomType) i32 {
return self.a;
}
pub fn getB(self: *TestCustomType) f32 {
return self.b;
}
pub fn getC(self: *TestCustomType) []const u8 {
return self.c;
}
pub fn getD(self: *TestCustomType) bool {
return self.d;
}
pub fn reset(self: *TestCustomType) void {
self.a = 0;
self.b = 0;
self.c = "";
self.d = false;
}
pub fn store(self: *TestCustomType, _a: i32, _b: f32, _c: []const u8, _d: bool) void {
self.a = _a;
self.b = _b;
self.c = _c;
self.d = _d;
}
};
test "Custom types I: allocless in/out member functions arguments" {
var lua = try Lua.init(std.testing.allocator);
defer lua.destroy();
lua.openLibs();
try lua.newUserType(TestCustomType);
const cmd =
\\o = TestCustomType.new(42, 42.0, "life", true)
\\function getA() return o:getA(); end
\\function getB() return o:getB(); end
\\function getC() return o:getC(); end
\\function getD() return o:getD(); end
\\function reset() o:reset() end
\\function store(a,b,c,d) o:store(a,b,c,d) end
;
lua.run(cmd);
var getA = try lua.getResource(Lua.Function(fn () i32), "getA");
defer lua.release(getA);
var getB = try lua.getResource(Lua.Function(fn () f32), "getB");
defer lua.release(getB);
var getC = try lua.getResource(Lua.Function(fn () []const u8), "getC");
defer lua.release(getC);
var getD = try lua.getResource(Lua.Function(fn () bool), "getD");
defer lua.release(getD);
var reset = try lua.getResource(Lua.Function(fn () void), "reset");
defer lua.release(reset);
var store = try lua.getResource(Lua.Function(fn (_a: i32, _b: f32, _c: []const u8, _d: bool) void), "store");
defer lua.release(store);
var resA0 = try getA.call(.{});
try std.testing.expect(resA0 == 42);
var resB0 = try getB.call(.{});
try std.testing.expect(resB0 == 42.0);
var resC0 = try getC.call(.{});
try std.testing.expect(std.mem.eql(u8, resC0, "life"));
var resD0 = try getD.call(.{});
try std.testing.expect(resD0 == true);
try store.call(.{ 1, 1.0, "death", false });
var resA1 = try getA.call(.{});
try std.testing.expect(resA1 == 1);
var resB1 = try getB.call(.{});
try std.testing.expect(resB1 == 1.0);
var resC1 = try getC.call(.{});
try std.testing.expect(std.mem.eql(u8, resC1, "death"));
var resD1 = try getD.call(.{});
try std.testing.expect(resD1 == false);
try reset.call(.{});
var resA2 = try getA.call(.{});
try std.testing.expect(resA2 == 0);
var resB2 = try getB.call(.{});
try std.testing.expect(resB2 == 0.0);
var resC2 = try getC.call(.{});
try std.testing.expect(std.mem.eql(u8, resC2, ""));
var resD2 = try getD.call(.{});
try std.testing.expect(resD2 == false);
}
test "Custom types II: set as global, get without ownership" {
var lua = try Lua.init(std.testing.allocator);
defer lua.destroy();
lua.openLibs();
_ = try lua.newUserType(TestCustomType);
// Creation from Zig
var ojjectum = try lua.createUserType(TestCustomType, .{42, 42.0, "life", true});
defer lua.release(ojjectum);
lua.set("zig", ojjectum);
var ptrZig = try lua.get(*TestCustomType, "zig");
try std.testing.expect(ptrZig.a == 42);
try std.testing.expect(ptrZig.b == 42.0);
try std.testing.expect(std.mem.eql(u8, ptrZig.c, "life"));
try std.testing.expect(ptrZig.d == true);
ptrZig.reset();
try std.testing.expect(ptrZig.a == 0);
try std.testing.expect(ptrZig.b == 0.0);
try std.testing.expect(std.mem.eql(u8, ptrZig.c, ""));
try std.testing.expect(ptrZig.d == false);
// Creation From Lua
lua.run("o = TestCustomType.new(42, 42.0, 'life', true)");
var ptr = try lua.get(*TestCustomType, "o");
try std.testing.expect(ptr.a == 42);
try std.testing.expect(ptr.b == 42.0);
try std.testing.expect(std.mem.eql(u8, ptr.c, "life"));
try std.testing.expect(ptr.d == true);
lua.run("o:reset()");
try std.testing.expect(ptr.a == 0);
try std.testing.expect(ptr.b == 0.0);
try std.testing.expect(std.mem.eql(u8, ptr.c, ""));
try std.testing.expect(ptr.d == false);
}
fn testCustomTypeSwap(ptr0: *TestCustomType, ptr1: *TestCustomType) void {
var tmp: TestCustomType = undefined;
tmp = ptr0.*;
ptr0.* = ptr1.*;
ptr1.* = tmp;
}
test "Custom types III: Zig function with custom user type arguments" {
var lua = try Lua.init(std.testing.allocator);
defer lua.destroy();
lua.openLibs();
_ = try lua.newUserType(TestCustomType);
lua.set("swap", testCustomTypeSwap);
const cmd =
\\o0 = TestCustomType.new(42, 42.0, 'life', true)
\\o1 = TestCustomType.new(0, 1.0, 'test', false)
\\swap(o0, o1)
;
lua.run(cmd);
var ptr0 = try lua.get(*TestCustomType, "o0");
var ptr1 = try lua.get(*TestCustomType, "o1");
try std.testing.expect(ptr0.a == 0);
try std.testing.expect(ptr0.b == 1.0);
try std.testing.expect(std.mem.eql(u8, ptr0.c, "test"));
try std.testing.expect(ptr0.d == false);
try std.testing.expect(ptr1.a == 42);
try std.testing.expect(ptr1.b == 42.0);
try std.testing.expect(std.mem.eql(u8, ptr1.c, "life"));
try std.testing.expect(ptr1.d == true);
}
|
src/tests.zig
|
pub usingnamespace @import("common.zig");
const p = @import("common.zig");
pub const vec2 = @import("vec2.zig");
pub const vec3 = @import("vec3.zig");
pub const mat4x4 = @import("mat4x4.zig");
pub const Mat4x4f = mat4x4.Generic(f32);
pub const Vec2f = vec2.Generic(f32);
pub const Vec3f = vec3.Generic(f32);
/// Helper type for using MVP's
pub const ModelMatrix = struct {
model: Mat4x4f = Mat4x4f.identity(),
trans: Mat4x4f = Mat4x4f.identity(),
rot: Mat4x4f = Mat4x4f.identity(),
sc: Mat4x4f = Mat4x4f.identity(),
/// Apply the changes were made
pub fn update(self: *ModelMatrix) void {
self.model = Mat4x4f.mul(self.sc, Mat4x4f.mul(self.trans, self.rot));
}
/// Translate the matrix
pub fn translate(self: *ModelMatrix, x: f32, y: f32, z: f32) void {
self.trans = Mat4x4f.translate(x, y, z);
self.update();
}
/// Rotate the matrix
pub fn rotate(self: *ModelMatrix, x: f32, y: f32, z: f32, angle: f32) void {
self.rot = Mat4x4f.rotate(x, y, z, angle);
self.update();
}
/// Scale the matrix
pub fn scale(self: *ModelMatrix, x: f32, y: f32, z: f32) void {
self.sc = Mat4x4f.scale(x, y, z);
self.update();
}
};
pub const Rectangle = struct {
position: Vec2f = .{ .x = 0, .y = 0 },
size: Vec2f = .{ .x = 0, .y = 0 },
/// Get the originated position of the rectangle
pub fn getOriginated(self: Rectangle) Vec2f {
return .{
.x = self.position.x + (self.size.x * 0.5),
.y = self.position.y + (self.size.y * 0.5),
};
}
/// Get origin of the rectangle
pub fn getOrigin(self: Rectangle) Vec2f {
return .{
.x = self.size.x * 0.5,
.y = self.size.y * 0.5,
};
}
/// AABB collision detection
/// between to rectangles
pub fn aabb(self: Rectangle, other: Rectangle) bool {
return p.aabb(self.position.x, self.position.y, self.size.x, self.size.y, other.position.x, other.position.y, other.size.x, other.size.y);
}
/// AABB collision detection
/// between to rectangles
pub fn aabbMeeting(self: Rectangle, other: Rectangle, meeting: Vec2f) bool {
return p.aabbMeeting(meeting.x, meeting.y, self.position.x, self.position.y, self.size.x, self.size.y, other.position.x, other.position.y, other.size.x, other.size.y);
}
};
/// Transform 2D
pub const Transform2D = struct {
position: Vec2f = undefined,
size: Vec2f = undefined,
origin: Vec2f = undefined,
/// in degrees
rotation: f32 = undefined,
/// Get the originated position
pub fn getOriginated(self: Transform2D) Vec2f {
return Vec2f{
.x = self.position.x - self.origin.x,
.y = self.position.y - self.origin.y,
};
}
pub fn getRectangle(self: Transform2D) Rectangle {
return Rectangle{ .position = self.getOriginated(), .size = self.size };
}
pub fn getRectangleNoOrigin(self: Transform2D) Rectangle {
return Rectangle{ .position = self.position, .size = self.size };
}
/// AABB collision detection
/// between to transform(rotation does not count)
pub fn aabb(self: Transform2D, other: Transform2D) bool {
return self.getRectangle().aabb(other.getRectangle());
}
/// AABB collision detection
/// between to transform(rotation does not count)
/// origin does not count
pub fn aabbNoOrigin(self: Transform2D, other: Transform2D) bool {
return Rectangle.aabb(self.getRectangleNoOrigin(), other.getRectangleNoOrigin());
}
/// AABB collision detection
/// between to transform(rotation does not count)
pub fn aabbMeeting(self: Transform2D, other: Transform2D, meeting: Vec2f) bool {
return self.getRectangle().aabbMeeting(other.getRectangle(), meeting);
}
/// AABB collision detection
/// between to transform(rotation does not count)
/// origin does not count
pub fn aabbMeetingNoOrigin(self: Transform2D, other: Transform2D, meeting: Vec2f) bool {
return Rectangle.aabbMeeting(self.getRectangleNoOrigin(), other.getRectangleNoOrigin(), meeting);
}
};
/// 2D Camera
pub const Camera2D = struct {
position: Vec2f = Vec2f{ .x = 0, .y = 0 },
offset: Vec2f = Vec2f{ .x = 0, .y = 0 },
zoom: Vec2f = Vec2f{ .x = 1, .y = 1 },
/// In radians
rotation: f32 = 0,
ortho: Mat4x4f = comptime Mat4x4f.identity(),
view: Mat4x4f = comptime Mat4x4f.identity(),
/// Returns the camera matrix
pub fn matrix(self: Camera2D) Mat4x4f {
const origin = Mat4x4f.translate(self.position.x, self.position.y, 0);
const rot = Mat4x4f.rotate(0, 0, 1, self.rotation);
const scale = Mat4x4f.scale(self.zoom.x, self.zoom.y, 0);
const offset = Mat4x4f.translate(self.offset.x, self.offset.y, 0);
return Mat4x4f.mul(Mat4x4f.mul(origin, Mat4x4f.mul(scale, rot)), offset);
}
/// Attaches the camera
pub fn attach(self: *Camera2D) void {
self.view = Mat4x4f.mul(self.matrix(), self.ortho);
}
/// Detaches the camera
pub fn detach(self: *Camera2D) void {
self.view = Mat4x4f.identity();
}
/// Returns the screen space position for a 2d camera world space position
pub fn worldToScreen(self: Camera2D, position: Vec2f) Vec2f {
const m = self.matrix();
const v = Vec3f.transform(Vec3f{ .x = position.x, .y = position.y, .z = 0.0 }, m);
return .{ .x = v.x, .y = v.y };
}
/// Returns the world space position for a 2d camera screen space position
pub fn screenToWorld(self: Camera2D, position: Vec2f) Vec2f {
const m = Mat4x4f.invert(self.matrix());
const v = Vec3f.transform(Vec3f{ .x = position.x, .y = position.y, .z = 0.0 }, m);
return .{ .x = v.x, .y = v.y };
}
};
|
src/core/math/math.zig
|
// Implemented features:
// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices.
// Missing features:
// [ ] Renderer: User texture binding. Changes of ImTextureID aren't supported by this binding! See https://github.com/ocornut/imgui/pull/914
// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp.
// https://github.com/ocornut/imgui
// The aim of imgui_impl_vulkan.h/.cpp is to be usable in your engine without any modification.
// IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/
// Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app.
// - Common XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h.
// You will use those if you want to use this rendering back-end in your engine/app.
// - Helper XXX functions and structures are only used by this example (main.cpp) and by
// the back-end itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code.
// Read comments in imgui_impl_vulkan.h.
// CHANGELOG
// (minor and older changes stripped away, please see git history for details)
// 2019-08-01: Vulkan: Added support for specifying multisample count. Set InitInfo::MSAASamples to one of the vk.SampleCountFlags values to use, default is non-multisampled as before.
// 2019-05-29: Vulkan: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
// 2019-04-30: Vulkan: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
// 2019-04-04: *BREAKING CHANGE*: Vulkan: Added ImageCount/MinImageCount fields in InitInfo, required for initialization (was previously a hard #define IMGUI_VK_QUEUED_FRAMES 2). Added SetMinImageCount().
// 2019-04-04: Vulkan: Added vk.Instance argument to CreateWindow() optional helper.
// 2019-04-04: Vulkan: Avoid passing negative coordinates to vk.CmdSetScissor, which debug validation layers do not like.
// 2019-04-01: Vulkan: Support for 32-bit index buffer (#define ImDrawIdx unsigned int).
// 2019-02-16: Vulkan: Viewport and clipping rectangles correctly using draw_data.FramebufferScale to allow retina display.
// 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
// 2018-08-25: Vulkan: Fixed mishandled vk.SurfaceCapabilitiesKHR::maxImageCount=0 case.
// 2018-06-22: Inverted the parameters to RenderDrawData() to be consistent with other bindings.
// 2018-06-08: Misc: Extracted imgui_impl_vulkan.cpp/.h away from the old combined GLFW+Vulkan example.
// 2018-06-08: Vulkan: Use draw_data.DisplayPos and draw_data.DisplaySize to setup projection matrix and clipping rectangle.
// 2018-03-03: Vulkan: Various refactor, created a couple of XXX helper that the example can use and that viewport support will use.
// 2018-03-01: Vulkan: Renamed Init_Info to InitInfo and fields to match more closely Vulkan terminology.
// 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback, Render() calls RenderDrawData() itself.
// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
// 2017-05-15: Vulkan: Fix scissor offset being negative. Fix new Vulkan validation warnings. Set required depth member for buffer image copy.
// 2016-11-13: Vulkan: Fix validation layer warnings and errors and redeclare gl_PerVertex.
// 2016-10-18: Vulkan: Add location decorators & change to use structs as in/out in glsl, update embedded spv (produced with glslangValidator -x). Null the released resources.
// 2016-08-27: Vulkan: Fix Vulkan example for use when a depth buffer is active.
const imgui = @import("imgui");
const std = @import("std");
const vk = @import("include/vk.zig");
pub const InitInfo = struct {
Instance: vk.Instance,
PhysicalDevice: vk.PhysicalDevice,
Device: vk.Device,
QueueFamily: u32,
Queue: vk.Queue,
PipelineCache: vk.PipelineCache,
DescriptorPool: vk.DescriptorPool,
MinImageCount: u32, // >= 2
ImageCount: u32, // >= MinImageCount
MSAASamples: vk.SampleCountFlags, // >= VK_SAMPLE_COUNT_1_BIT
VkAllocator: ?*const vk.AllocationCallbacks,
Allocator: *std.mem.Allocator,
};
const Frame = struct {
CommandPool: vk.CommandPool = undefined,
CommandBuffer: vk.CommandBuffer = undefined,
Fence: vk.Fence = undefined,
Backbuffer: vk.Image,
BackbufferView: vk.ImageView = undefined,
Framebuffer: vk.Framebuffer = undefined,
};
const FrameSemaphores = struct {
ImageAcquiredSemaphore: vk.Semaphore = undefined,
RenderCompleteSemaphore: vk.Semaphore = undefined,
};
// Helper structure to hold the data needed by one rendering context into one OS window
// (Used by example's main.cpp. Used by multi-viewport features. Probably NOT used by your own engine/app.)
pub const Window = struct {
Allocator: *std.mem.Allocator = undefined,
Width: u32 = 0,
Height: u32 = 0,
Swapchain: vk.SwapchainKHR = .Null,
Surface: vk.SurfaceKHR = undefined,
SurfaceFormat: vk.SurfaceFormatKHR = undefined,
PresentMode: vk.PresentModeKHR = undefined,
RenderPass: vk.RenderPass = .Null,
FrameIndex: u32 = 0, // Current frame being rendered to (0 <= FrameIndex < FrameInFlightCount)
ImageCount: u32 = 0, // Number of simultaneous in-flight frames (returned by vk.GetSwapchainImagesKHR, usually derived from min_image_count)
SemaphoreIndex: u32 = 0, // Current set of swapchain wait semaphores we're using (needs to be distinct from per frame data)
Frames: []Frame = undefined,
FrameSemaphores: []FrameSemaphores = undefined,
};
// Reusable buffers used for rendering 1 current in-flight frame, for RenderDrawData()
// [Please zero-clear before use!]
const FrameRenderBuffers = struct {
VertexBufferMemory: vk.DeviceMemory = .Null,
IndexBufferMemory: vk.DeviceMemory = .Null,
VertexBufferSize: vk.DeviceSize = 0,
IndexBufferSize: vk.DeviceSize = 0,
VertexBuffer: vk.Buffer = .Null,
IndexBuffer: vk.Buffer = .Null,
};
// Each viewport will hold 1 WindowRenderBuffers
const WindowRenderBuffers = struct {
Index: u32 = 0,
FrameRenderBuffers: []FrameRenderBuffers = &[_]FrameRenderBuffers{},
};
// Vulkan data
var g_VulkanInitInfo: InitInfo = undefined;
var g_RenderPass: vk.RenderPass = .Null;
var g_BufferMemoryAlignment: vk.DeviceSize = 256;
var g_PipelineCreateFlags = vk.PipelineCreateFlags{};
var g_DescriptorSetLayout: vk.DescriptorSetLayout = .Null;
var g_PipelineLayout: vk.PipelineLayout = .Null;
var g_DescriptorSet: vk.DescriptorSet = .Null;
var g_Pipeline: vk.Pipeline = .Null;
//font data
var g_FontSampler: vk.Sampler = .Null;
var g_FontMemory: vk.DeviceMemory = .Null;
var g_FontImage: vk.Image = .Null;
var g_FontView: vk.ImageView = .Null;
var g_UploadBufferMemory: vk.DeviceMemory = .Null;
var g_UploadBuffer: vk.Buffer = .Null;
// Render buffers
var g_MainWindowRenderBuffers = WindowRenderBuffers{};
//-----------------------------------------------------------------------------
// SHADERS
//-----------------------------------------------------------------------------
// glsl_shader.vert, compiled with:
// # glslangValidator -V -x -o glsl_shader.vert.u32 glsl_shader.vert
///*
//#version 450 core
//layout(location = 0) in vec2 aPos;
//layout(location = 1) in vec2 aUV;
//layout(location = 2) in vec4 aColor;
//layout(push_constant) uniform uPushConstant { vec2 uScale; vec2 uTranslate; } pc;
//
//out gl_PerVertex { vec4 gl_Position; };
//layout(location = 0) out struct { vec4 Color; vec2 UV; } Out;
//
//void main()
//{
// Out.Color = aColor;
// Out.UV = aUV;
// gl_Position = vec4(aPos * pc.uScale + pc.uTranslate, 0, 1);
//}
//*/
const __glsl_shader_vert_spv = [_]u32{
0x07230203, 0x00010000, 0x00080001, 0x0000002e, 0x00000000, 0x00020011, 0x00000001, 0x0006000b,
0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001,
0x000a000f, 0x00000000, 0x00000004, 0x6e69616d, 0x00000000, 0x0000000b, 0x0000000f, 0x00000015,
0x0000001b, 0x0000001c, 0x00030003, 0x00000002, 0x000001c2, 0x00040005, 0x00000004, 0x6e69616d,
0x00000000, 0x00030005, 0x00000009, 0x00000000, 0x00050006, 0x00000009, 0x00000000, 0x6f6c6f43,
0x00000072, 0x00040006, 0x00000009, 0x00000001, 0x00005655, 0x00030005, 0x0000000b, 0x0074754f,
0x00040005, 0x0000000f, 0x6c6f4361, 0x0000726f, 0x00030005, 0x00000015, 0x00565561, 0x00060005,
0x00000019, 0x505f6c67, 0x65567265, 0x78657472, 0x00000000, 0x00060006, 0x00000019, 0x00000000,
0x505f6c67, 0x7469736f, 0x006e6f69, 0x00030005, 0x0000001b, 0x00000000, 0x00040005, 0x0000001c,
0x736f5061, 0x00000000, 0x00060005, 0x0000001e, 0x73755075, 0x6e6f4368, 0x6e617473, 0x00000074,
0x00050006, 0x0000001e, 0x00000000, 0x61635375, 0x0000656c, 0x00060006, 0x0000001e, 0x00000001,
0x61725475, 0x616c736e, 0x00006574, 0x00030005, 0x00000020, 0x00006370, 0x00040047, 0x0000000b,
0x0000001e, 0x00000000, 0x00040047, 0x0000000f, 0x0000001e, 0x00000002, 0x00040047, 0x00000015,
0x0000001e, 0x00000001, 0x00050048, 0x00000019, 0x00000000, 0x0000000b, 0x00000000, 0x00030047,
0x00000019, 0x00000002, 0x00040047, 0x0000001c, 0x0000001e, 0x00000000, 0x00050048, 0x0000001e,
0x00000000, 0x00000023, 0x00000000, 0x00050048, 0x0000001e, 0x00000001, 0x00000023, 0x00000008,
0x00030047, 0x0000001e, 0x00000002, 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002,
0x00030016, 0x00000006, 0x00000020, 0x00040017, 0x00000007, 0x00000006, 0x00000004, 0x00040017,
0x00000008, 0x00000006, 0x00000002, 0x0004001e, 0x00000009, 0x00000007, 0x00000008, 0x00040020,
0x0000000a, 0x00000003, 0x00000009, 0x0004003b, 0x0000000a, 0x0000000b, 0x00000003, 0x00040015,
0x0000000c, 0x00000020, 0x00000001, 0x0004002b, 0x0000000c, 0x0000000d, 0x00000000, 0x00040020,
0x0000000e, 0x00000001, 0x00000007, 0x0004003b, 0x0000000e, 0x0000000f, 0x00000001, 0x00040020,
0x00000011, 0x00000003, 0x00000007, 0x0004002b, 0x0000000c, 0x00000013, 0x00000001, 0x00040020,
0x00000014, 0x00000001, 0x00000008, 0x0004003b, 0x00000014, 0x00000015, 0x00000001, 0x00040020,
0x00000017, 0x00000003, 0x00000008, 0x0003001e, 0x00000019, 0x00000007, 0x00040020, 0x0000001a,
0x00000003, 0x00000019, 0x0004003b, 0x0000001a, 0x0000001b, 0x00000003, 0x0004003b, 0x00000014,
0x0000001c, 0x00000001, 0x0004001e, 0x0000001e, 0x00000008, 0x00000008, 0x00040020, 0x0000001f,
0x00000009, 0x0000001e, 0x0004003b, 0x0000001f, 0x00000020, 0x00000009, 0x00040020, 0x00000021,
0x00000009, 0x00000008, 0x0004002b, 0x00000006, 0x00000028, 0x00000000, 0x0004002b, 0x00000006,
0x00000029, 0x3f800000, 0x00050036, 0x00000002, 0x00000004, 0x00000000, 0x00000003, 0x000200f8,
0x00000005, 0x0004003d, 0x00000007, 0x00000010, 0x0000000f, 0x00050041, 0x00000011, 0x00000012,
0x0000000b, 0x0000000d, 0x0003003e, 0x00000012, 0x00000010, 0x0004003d, 0x00000008, 0x00000016,
0x00000015, 0x00050041, 0x00000017, 0x00000018, 0x0000000b, 0x00000013, 0x0003003e, 0x00000018,
0x00000016, 0x0004003d, 0x00000008, 0x0000001d, 0x0000001c, 0x00050041, 0x00000021, 0x00000022,
0x00000020, 0x0000000d, 0x0004003d, 0x00000008, 0x00000023, 0x00000022, 0x00050085, 0x00000008,
0x00000024, 0x0000001d, 0x00000023, 0x00050041, 0x00000021, 0x00000025, 0x00000020, 0x00000013,
0x0004003d, 0x00000008, 0x00000026, 0x00000025, 0x00050081, 0x00000008, 0x00000027, 0x00000024,
0x00000026, 0x00050051, 0x00000006, 0x0000002a, 0x00000027, 0x00000000, 0x00050051, 0x00000006,
0x0000002b, 0x00000027, 0x00000001, 0x00070050, 0x00000007, 0x0000002c, 0x0000002a, 0x0000002b,
0x00000028, 0x00000029, 0x00050041, 0x00000011, 0x0000002d, 0x0000001b, 0x0000000d, 0x0003003e,
0x0000002d, 0x0000002c, 0x000100fd, 0x00010038,
};
// glsl_shader.frag, compiled with:
// # glslangValidator -V -x -o glsl_shader.frag.u32 glsl_shader.frag
///*
//#version 450 core
//layout(location = 0) out vec4 fColor;
//layout(set=0, binding=0) uniform sampler2D sTexture;
//layout(location = 0) in struct { vec4 Color; vec2 UV; } In;
//void main()
//{
// fColor = In.Color * texture(sTexture, In.UV.st);
//}
//*/
const __glsl_shader_frag_spv = [_]u32{
0x07230203, 0x00010000, 0x00080001, 0x0000001e, 0x00000000, 0x00020011, 0x00000001, 0x0006000b,
0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001,
0x0007000f, 0x00000004, 0x00000004, 0x6e69616d, 0x00000000, 0x00000009, 0x0000000d, 0x00030010,
0x00000004, 0x00000007, 0x00030003, 0x00000002, 0x000001c2, 0x00040005, 0x00000004, 0x6e69616d,
0x00000000, 0x00040005, 0x00000009, 0x6c6f4366, 0x0000726f, 0x00030005, 0x0000000b, 0x00000000,
0x00050006, 0x0000000b, 0x00000000, 0x6f6c6f43, 0x00000072, 0x00040006, 0x0000000b, 0x00000001,
0x00005655, 0x00030005, 0x0000000d, 0x00006e49, 0x00050005, 0x00000016, 0x78655473, 0x65727574,
0x00000000, 0x00040047, 0x00000009, 0x0000001e, 0x00000000, 0x00040047, 0x0000000d, 0x0000001e,
0x00000000, 0x00040047, 0x00000016, 0x00000022, 0x00000000, 0x00040047, 0x00000016, 0x00000021,
0x00000000, 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002, 0x00030016, 0x00000006,
0x00000020, 0x00040017, 0x00000007, 0x00000006, 0x00000004, 0x00040020, 0x00000008, 0x00000003,
0x00000007, 0x0004003b, 0x00000008, 0x00000009, 0x00000003, 0x00040017, 0x0000000a, 0x00000006,
0x00000002, 0x0004001e, 0x0000000b, 0x00000007, 0x0000000a, 0x00040020, 0x0000000c, 0x00000001,
0x0000000b, 0x0004003b, 0x0000000c, 0x0000000d, 0x00000001, 0x00040015, 0x0000000e, 0x00000020,
0x00000001, 0x0004002b, 0x0000000e, 0x0000000f, 0x00000000, 0x00040020, 0x00000010, 0x00000001,
0x00000007, 0x00090019, 0x00000013, 0x00000006, 0x00000001, 0x00000000, 0x00000000, 0x00000000,
0x00000001, 0x00000000, 0x0003001b, 0x00000014, 0x00000013, 0x00040020, 0x00000015, 0x00000000,
0x00000014, 0x0004003b, 0x00000015, 0x00000016, 0x00000000, 0x0004002b, 0x0000000e, 0x00000018,
0x00000001, 0x00040020, 0x00000019, 0x00000001, 0x0000000a, 0x00050036, 0x00000002, 0x00000004,
0x00000000, 0x00000003, 0x000200f8, 0x00000005, 0x00050041, 0x00000010, 0x00000011, 0x0000000d,
0x0000000f, 0x0004003d, 0x00000007, 0x00000012, 0x00000011, 0x0004003d, 0x00000014, 0x00000017,
0x00000016, 0x00050041, 0x00000019, 0x0000001a, 0x0000000d, 0x00000018, 0x0004003d, 0x0000000a,
0x0000001b, 0x0000001a, 0x00050057, 0x00000007, 0x0000001c, 0x00000017, 0x0000001b, 0x00050085,
0x00000007, 0x0000001d, 0x00000012, 0x0000001c, 0x0003003e, 0x00000009, 0x0000001d, 0x000100fd,
0x00010038,
};
//-----------------------------------------------------------------------------
// FUNCTIONS
//-----------------------------------------------------------------------------
fn MemoryType(properties: vk.MemoryPropertyFlags, type_bits: u32) ?u32 {
var v = &g_VulkanInitInfo;
var prop = vk.GetPhysicalDeviceMemoryProperties(v.PhysicalDevice);
for (prop.memoryTypes[0..prop.memoryTypeCount]) |memType, i|
if (memType.propertyFlags.hasAllSet(properties) and type_bits & (@as(u32, 1) << @intCast(u5, i)) != 0)
return @intCast(u32, i);
return null; // Unable to find memoryType
}
fn CreateOrResizeBuffer(buffer: *vk.Buffer, buffer_memory: *vk.DeviceMemory, p_buffer_size: *vk.DeviceSize, new_size: usize, usage: vk.BufferUsageFlags) !void {
var v = &g_VulkanInitInfo;
if (buffer.* != .Null)
vk.DestroyBuffer(v.Device, buffer.*, v.VkAllocator);
if (buffer_memory.* != .Null)
vk.FreeMemory(v.Device, buffer_memory.*, v.VkAllocator);
var vertex_buffer_size_aligned = ((new_size - 1) / g_BufferMemoryAlignment + 1) * g_BufferMemoryAlignment;
const buffer_info = vk.BufferCreateInfo{
.size = vertex_buffer_size_aligned,
.usage = usage,
.sharingMode = .EXCLUSIVE,
};
buffer.* = try vk.CreateBuffer(v.Device, buffer_info, v.VkAllocator);
var req = vk.GetBufferMemoryRequirements(v.Device, buffer.*);
g_BufferMemoryAlignment = if (g_BufferMemoryAlignment > req.alignment) g_BufferMemoryAlignment else req.alignment;
var alloc_info = vk.MemoryAllocateInfo{
.allocationSize = req.size,
.memoryTypeIndex = MemoryType(.{ .hostVisible = true }, req.memoryTypeBits).?,
};
buffer_memory.* = try vk.AllocateMemory(v.Device, alloc_info, v.VkAllocator);
try vk.BindBufferMemory(v.Device, buffer.*, buffer_memory.*, 0);
p_buffer_size.* = new_size;
}
fn SetupRenderState(draw_data: *imgui.DrawData, command_buffer: vk.CommandBuffer, rb: *FrameRenderBuffers, fb_width: u32, fb_height: u32) void {
// Bind pipeline and descriptor sets:
{
vk.CmdBindPipeline(command_buffer, .GRAPHICS, g_Pipeline);
var desc_set = [_]vk.DescriptorSet{g_DescriptorSet};
vk.CmdBindDescriptorSets(command_buffer, .GRAPHICS, g_PipelineLayout, 0, &desc_set, &[_]u32{});
}
// Bind Vertex And Index Buffer:
{
var vertex_buffers = [_]vk.Buffer{rb.VertexBuffer};
var vertex_offset = [_]vk.DeviceSize{0};
vk.CmdBindVertexBuffers(command_buffer, 0, &vertex_buffers, &vertex_offset);
vk.CmdBindIndexBuffer(command_buffer, rb.IndexBuffer, 0, if (@sizeOf(imgui.DrawIdx) == 2) .UINT16 else .UINT32);
}
// Setup viewport:
{
const viewport = vk.Viewport{
.x = 0,
.y = 0,
.width = @intToFloat(f32, fb_width),
.height = @intToFloat(f32, fb_height),
.minDepth = 0.0,
.maxDepth = 1.0,
};
vk.CmdSetViewport(command_buffer, 0, arrayPtr(&viewport));
}
// Setup scale and translation:
// Our visible imgui space lies from draw_data.DisplayPps (top left) to draw_data.DisplayPos+data_data.DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps.
{
var scale = [2]f32{
2.0 / draw_data.DisplaySize.x,
2.0 / draw_data.DisplaySize.y,
};
var translate = [2]f32{
-1.0 - draw_data.DisplayPos.x * scale[0],
-1.0 - draw_data.DisplayPos.y * scale[1],
};
vk.CmdPushConstants(command_buffer, g_PipelineLayout, .{ .vertex = true }, @sizeOf(f32) * 0, std.mem.asBytes(&scale));
vk.CmdPushConstants(command_buffer, g_PipelineLayout, .{ .vertex = true }, @sizeOf(f32) * 2, std.mem.asBytes(&translate));
}
}
// Render function
// (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
pub fn RenderDrawData(draw_data: *imgui.DrawData, command_buffer: vk.CommandBuffer) !void {
// Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
var fb_width = @floatToInt(u32, draw_data.DisplaySize.x * draw_data.FramebufferScale.x);
var fb_height = @floatToInt(u32, draw_data.DisplaySize.y * draw_data.FramebufferScale.y);
if (fb_width <= 0 or fb_height <= 0 or draw_data.TotalVtxCount == 0)
return;
var v = &g_VulkanInitInfo;
// Allocate array to store enough vertex/index buffers
var wrb = &g_MainWindowRenderBuffers;
if (wrb.FrameRenderBuffers.len == 0) {
wrb.Index = 0;
wrb.FrameRenderBuffers = try v.Allocator.alloc(FrameRenderBuffers, v.ImageCount);
for (wrb.FrameRenderBuffers) |*elem| {
elem.* = FrameRenderBuffers{};
}
}
std.debug.assert(wrb.FrameRenderBuffers.len == v.ImageCount);
wrb.Index = (wrb.Index + 1) % @intCast(u32, wrb.FrameRenderBuffers.len);
const rb = &wrb.FrameRenderBuffers[wrb.Index];
// Create or resize the vertex/index buffers
var vertex_size = @intCast(usize, draw_data.TotalVtxCount) * @sizeOf(imgui.DrawVert);
var index_size = @intCast(usize, draw_data.TotalIdxCount) * @sizeOf(imgui.DrawIdx);
if (rb.VertexBuffer == .Null or rb.VertexBufferSize < vertex_size)
try CreateOrResizeBuffer(&rb.VertexBuffer, &rb.VertexBufferMemory, &rb.VertexBufferSize, vertex_size, .{ .vertexBuffer = true });
if (rb.IndexBuffer == .Null or rb.IndexBufferSize < index_size)
try CreateOrResizeBuffer(&rb.IndexBuffer, &rb.IndexBufferMemory, &rb.IndexBufferSize, index_size, .{ .indexBuffer = true });
// Upload vertex/index data into a single contiguous GPU buffer
{
var vtx_dst: [*]imgui.DrawVert = undefined;
var idx_dst: [*]imgui.DrawIdx = undefined;
try vk.MapMemory(v.Device, rb.VertexBufferMemory, 0, vertex_size, .{}, @ptrCast(**c_void, &vtx_dst));
try vk.MapMemory(v.Device, rb.IndexBufferMemory, 0, index_size, .{}, @ptrCast(**c_void, &idx_dst));
var n: i32 = 0;
while (n < draw_data.CmdListsCount) : (n += 1) {
const cmd_list = draw_data.CmdLists.?[@intCast(u32, n)];
std.mem.copy(imgui.DrawVert, vtx_dst[0..@intCast(u32, cmd_list.VtxBuffer.len)], cmd_list.VtxBuffer.items[0..@intCast(u32, cmd_list.VtxBuffer.len)]);
std.mem.copy(imgui.DrawIdx, idx_dst[0..@intCast(u32, cmd_list.IdxBuffer.len)], cmd_list.IdxBuffer.items[0..@intCast(u32, cmd_list.IdxBuffer.len)]);
vtx_dst += @intCast(u32, cmd_list.VtxBuffer.len);
idx_dst += @intCast(u32, cmd_list.IdxBuffer.len);
}
var ranges = [2]vk.MappedMemoryRange{
vk.MappedMemoryRange{
.memory = rb.VertexBufferMemory,
.size = vk.WHOLE_SIZE,
.offset = 0,
},
vk.MappedMemoryRange{
.memory = rb.IndexBufferMemory,
.size = vk.WHOLE_SIZE,
.offset = 0,
},
};
try vk.FlushMappedMemoryRanges(v.Device, &ranges);
vk.UnmapMemory(v.Device, rb.VertexBufferMemory);
vk.UnmapMemory(v.Device, rb.IndexBufferMemory);
}
// Setup desired Vulkan state
SetupRenderState(draw_data, command_buffer, rb, fb_width, fb_height);
// Will project scissor/clipping rectangles into framebuffer space
var clip_off = draw_data.DisplayPos; // (0,0) unless using multi-viewports
var clip_scale = draw_data.FramebufferScale; // (1,1) unless using retina display which are often (2,2)
// Render command lists
// (Because we merged all buffers into a single one, we maintain our own offset into them)
var global_vtx_offset = @as(u32, 0);
var global_idx_offset = @as(u32, 0);
var n: usize = 0;
while (n < @intCast(usize, draw_data.CmdListsCount)) : (n += 1) {
const cmd_list = draw_data.CmdLists.?[n];
var cmd_i: usize = 0;
while (cmd_i < @intCast(usize, cmd_list.CmdBuffer.len)) : (cmd_i += 1) {
const pcmd = &cmd_list.CmdBuffer.items[cmd_i];
if (pcmd.UserCallback) |fnPtr| {
// User callback, registered via imgui.DrawList::AddCallback()
// (imgui.DrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
if (fnPtr == imgui.DrawCallback_ResetRenderState) {
SetupRenderState(draw_data, command_buffer, rb, fb_width, fb_height);
} else {
fnPtr(cmd_list, pcmd);
}
} else {
// Project scissor/clipping rectangles into framebuffer space
var clip_rect = imgui.Vec4{
.x = (pcmd.ClipRect.x - clip_off.x) * clip_scale.x,
.y = (pcmd.ClipRect.y - clip_off.y) * clip_scale.y,
.z = (pcmd.ClipRect.z - clip_off.x) * clip_scale.x,
.w = (pcmd.ClipRect.w - clip_off.y) * clip_scale.y,
};
if (clip_rect.x < @intToFloat(f32, fb_width) and clip_rect.y < @intToFloat(f32, fb_height) and clip_rect.z >= 0.0 and clip_rect.w >= 0.0) {
// Negative offsets are illegal for vk.CmdSetScissor
if (clip_rect.x < 0.0)
clip_rect.x = 0.0;
if (clip_rect.y < 0.0)
clip_rect.y = 0.0;
// Apply scissor/clipping rectangle
var scissor = vk.Rect2D{
.offset = vk.Offset2D{
.x = @floatToInt(i32, clip_rect.x),
.y = @floatToInt(i32, clip_rect.y),
},
.extent = vk.Extent2D{
.width = @floatToInt(u32, clip_rect.z - clip_rect.x),
.height = @floatToInt(u32, clip_rect.w - clip_rect.y),
},
};
vk.CmdSetScissor(command_buffer, 0, arrayPtr(&scissor));
// Draw
const idxStart = @intCast(u32, pcmd.IdxOffset + global_idx_offset);
const vtxStart = @intCast(i32, pcmd.VtxOffset + global_vtx_offset);
vk.CmdDrawIndexed(command_buffer, pcmd.ElemCount, 1, idxStart, vtxStart, 0);
}
}
}
global_idx_offset += @intCast(u32, cmd_list.IdxBuffer.len);
global_vtx_offset += @intCast(u32, cmd_list.VtxBuffer.len);
}
}
pub fn CreateFontsTexture(command_buffer: vk.CommandBuffer) !void {
var v = &g_VulkanInitInfo;
var io = imgui.GetIO();
var pixels: ?[*]u8 = undefined;
var width: i32 = 0;
var height: i32 = 0;
io.Fonts.?.GetTexDataAsRGBA32(&pixels, &width, &height);
var upload_size = @intCast(usize, width * height * 4);
// Create the Image:
{
var info = vk.ImageCreateInfo{
.imageType = .T_2D,
.format = .R8G8B8A8_UNORM,
.extent = vk.Extent3D{
.width = @intCast(u32, width),
.height = @intCast(u32, height),
.depth = 1,
},
.mipLevels = 1,
.arrayLayers = 1,
.samples = .{ .t1 = true },
.tiling = .OPTIMAL,
.usage = .{ .sampled = true, .transferDst = true },
.sharingMode = .EXCLUSIVE,
.initialLayout = .UNDEFINED,
};
g_FontImage = try vk.CreateImage(v.Device, info, v.VkAllocator);
var req = vk.GetImageMemoryRequirements(v.Device, g_FontImage);
var alloc_info = vk.MemoryAllocateInfo{
.allocationSize = req.size,
.memoryTypeIndex = MemoryType(.{ .deviceLocal = true }, req.memoryTypeBits).?,
};
g_FontMemory = try vk.AllocateMemory(v.Device, alloc_info, v.VkAllocator);
try vk.BindImageMemory(v.Device, g_FontImage, g_FontMemory, 0);
}
// Create the Image View:
{
var info = vk.ImageViewCreateInfo{
.image = g_FontImage,
.viewType = .T_2D,
.format = .R8G8B8A8_UNORM,
.subresourceRange = vk.ImageSubresourceRange{
.aspectMask = .{ .color = true },
.levelCount = 1,
.layerCount = 1,
.baseMipLevel = 0,
.baseArrayLayer = 0,
},
.components = vk.ComponentMapping{
.r = .R,
.g = .G,
.b = .B,
.a = .A,
},
};
g_FontView = try vk.CreateImageView(v.Device, info, v.VkAllocator);
}
// Update the Descriptor Set:
{
var desc_image = [_]vk.DescriptorImageInfo{vk.DescriptorImageInfo{
.sampler = g_FontSampler,
.imageView = g_FontView,
.imageLayout = .SHADER_READ_ONLY_OPTIMAL,
}};
var write_desc = [_]vk.WriteDescriptorSet{vk.WriteDescriptorSet{
.dstSet = g_DescriptorSet,
.descriptorCount = 1,
.descriptorType = .COMBINED_IMAGE_SAMPLER,
.pImageInfo = &desc_image,
.dstBinding = 0,
.dstArrayElement = 0,
.pBufferInfo = undefined,
.pTexelBufferView = undefined,
}};
vk.UpdateDescriptorSets(v.Device, &write_desc, &[_]vk.CopyDescriptorSet{});
}
// Create the Upload Buffer:
{
var buffer_info = vk.BufferCreateInfo{
.size = upload_size,
.usage = .{ .transferSrc = true },
.sharingMode = .EXCLUSIVE,
};
g_UploadBuffer = try vk.CreateBuffer(v.Device, buffer_info, v.VkAllocator);
var req = vk.GetBufferMemoryRequirements(v.Device, g_UploadBuffer);
if (req.alignment > g_BufferMemoryAlignment) {
g_BufferMemoryAlignment = req.alignment;
}
var alloc_info = vk.MemoryAllocateInfo{
.allocationSize = req.size,
.memoryTypeIndex = MemoryType(.{ .hostVisible = true }, req.memoryTypeBits).?,
};
g_UploadBufferMemory = try vk.AllocateMemory(v.Device, alloc_info, v.VkAllocator);
try vk.BindBufferMemory(v.Device, g_UploadBuffer, g_UploadBufferMemory, 0);
}
// Upload to Buffer:
{
var map: [*]u8 = undefined;
try vk.MapMemory(v.Device, g_UploadBufferMemory, 0, upload_size, .{}, @ptrCast(**c_void, &map));
std.mem.copy(u8, map[0..upload_size], pixels.?[0..upload_size]);
var range = [_]vk.MappedMemoryRange{vk.MappedMemoryRange{
.memory = g_UploadBufferMemory,
.size = upload_size,
.offset = 0,
}};
try vk.FlushMappedMemoryRanges(v.Device, &range);
vk.UnmapMemory(v.Device, g_UploadBufferMemory);
}
// Copy to Image:
{
var copy_barrier = [1]vk.ImageMemoryBarrier{vk.ImageMemoryBarrier{
.srcAccessMask = .{},
.dstAccessMask = .{ .transferWrite = true },
.oldLayout = .UNDEFINED,
.newLayout = .TRANSFER_DST_OPTIMAL,
.srcQueueFamilyIndex = vk.QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = vk.QUEUE_FAMILY_IGNORED,
.image = g_FontImage,
.subresourceRange = vk.ImageSubresourceRange{
.aspectMask = .{ .color = true },
.levelCount = 1,
.layerCount = 1,
.baseMipLevel = 0,
.baseArrayLayer = 0,
},
}};
vk.CmdPipelineBarrier(command_buffer, .{ .host = true }, .{ .transfer = true }, .{}, &[_]vk.MemoryBarrier{}, &[_]vk.BufferMemoryBarrier{}, ©_barrier);
var region = [_]vk.BufferImageCopy{vk.BufferImageCopy{
.imageSubresource = vk.ImageSubresourceLayers{
.aspectMask = .{ .color = true },
.mipLevel = 0,
.baseArrayLayer = 0,
.layerCount = 1,
},
.bufferOffset = 0,
.bufferRowLength = 0,
.bufferImageHeight = 0,
.imageOffset = vk.Offset3D{ .x = 0, .y = 0, .z = 0 },
.imageExtent = vk.Extent3D{ .width = @intCast(u32, width), .height = @intCast(u32, height), .depth = 1 },
}};
vk.CmdCopyBufferToImage(command_buffer, g_UploadBuffer, g_FontImage, .TRANSFER_DST_OPTIMAL, ®ion);
var use_barrier = [_]vk.ImageMemoryBarrier{vk.ImageMemoryBarrier{
.srcAccessMask = .{ .transferWrite = true },
.dstAccessMask = .{ .shaderRead = true },
.oldLayout = .TRANSFER_DST_OPTIMAL,
.newLayout = .SHADER_READ_ONLY_OPTIMAL,
.srcQueueFamilyIndex = vk.QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = vk.QUEUE_FAMILY_IGNORED,
.image = g_FontImage,
.subresourceRange = vk.ImageSubresourceRange{
.aspectMask = .{ .color = true },
.levelCount = 1,
.layerCount = 1,
.baseMipLevel = 0,
.baseArrayLayer = 0,
},
}};
vk.CmdPipelineBarrier(command_buffer, .{ .transfer = true }, .{ .fragmentShader = true }, .{}, &[_]vk.MemoryBarrier{}, &[_]vk.BufferMemoryBarrier{}, &use_barrier);
}
// Store our identifier
io.Fonts.?.TexID = @intToPtr(imgui.TextureID, @enumToInt(g_FontImage));
}
fn CreateDeviceObjects() !void {
const v = &g_VulkanInitInfo;
var vert_module: vk.ShaderModule = undefined;
var frag_module: vk.ShaderModule = undefined;
// Create The Shader Modules:
{
const vert_info = vk.ShaderModuleCreateInfo{
.codeSize = @sizeOf(@TypeOf(__glsl_shader_vert_spv)),
.pCode = &__glsl_shader_vert_spv,
};
vert_module = try vk.CreateShaderModule(v.Device, vert_info, v.VkAllocator);
const frag_info = vk.ShaderModuleCreateInfo{
.codeSize = @sizeOf(@TypeOf(__glsl_shader_frag_spv)),
.pCode = &__glsl_shader_frag_spv,
};
frag_module = try vk.CreateShaderModule(v.Device, frag_info, v.VkAllocator);
}
if (g_FontSampler == .Null) {
const info = vk.SamplerCreateInfo{
.magFilter = .LINEAR,
.minFilter = .LINEAR,
.mipmapMode = .LINEAR,
.addressModeU = .REPEAT,
.addressModeV = .REPEAT,
.addressModeW = .REPEAT,
.minLod = -1000,
.maxLod = 1000,
.maxAnisotropy = 1.0,
.mipLodBias = 0,
.anisotropyEnable = vk.FALSE,
.compareEnable = vk.FALSE,
.compareOp = .NEVER,
.borderColor = .FLOAT_TRANSPARENT_BLACK,
.unnormalizedCoordinates = vk.FALSE,
};
g_FontSampler = try vk.CreateSampler(v.Device, info, v.VkAllocator);
}
if (g_DescriptorSetLayout == .Null) {
const sampler = [_]vk.Sampler{g_FontSampler};
const binding = [_]vk.DescriptorSetLayoutBinding{vk.DescriptorSetLayoutBinding{
.binding = 0,
.descriptorType = .COMBINED_IMAGE_SAMPLER,
.descriptorCount = 1,
.stageFlags = .{ .fragment = true },
.pImmutableSamplers = &sampler,
}};
const info = vk.DescriptorSetLayoutCreateInfo{
.bindingCount = 1,
.pBindings = &binding,
};
g_DescriptorSetLayout = try vk.CreateDescriptorSetLayout(v.Device, info, v.VkAllocator);
}
// Create Descriptor Set:
{
const alloc_info = vk.DescriptorSetAllocateInfo{
.descriptorPool = v.DescriptorPool,
.descriptorSetCount = 1,
.pSetLayouts = arrayPtr(&g_DescriptorSetLayout),
};
var out_descriptorSet: vk.DescriptorSet = undefined;
try vk.AllocateDescriptorSets(v.Device, alloc_info, arrayPtr(&out_descriptorSet));
g_DescriptorSet = out_descriptorSet;
}
if (g_PipelineLayout == .Null) {
// Constants: we are using 'vec2 offset' and 'vec2 scale' instead of a full 3d projection matrix
const push_constants = [_]vk.PushConstantRange{vk.PushConstantRange{
.stageFlags = .{ .vertex = true },
.offset = 0 * @sizeOf(f32),
.size = 4 * @sizeOf(f32),
}};
const set_layout = [_]vk.DescriptorSetLayout{g_DescriptorSetLayout};
const layout_info = vk.PipelineLayoutCreateInfo{
.setLayoutCount = 1,
.pSetLayouts = &set_layout,
.pushConstantRangeCount = 1,
.pPushConstantRanges = &push_constants,
};
g_PipelineLayout = try vk.CreatePipelineLayout(v.Device, layout_info, v.VkAllocator);
}
const stage = [_]vk.PipelineShaderStageCreateInfo{
vk.PipelineShaderStageCreateInfo{
.stage = .{ .vertex = true },
.module = vert_module,
.pName = "main",
},
vk.PipelineShaderStageCreateInfo{
.stage = .{ .fragment = true },
.module = frag_module,
.pName = "main",
},
};
const binding_desc = [_]vk.VertexInputBindingDescription{vk.VertexInputBindingDescription{
.binding = 0,
.stride = @sizeOf(imgui.DrawVert),
.inputRate = .VERTEX,
}};
const attribute_desc = [_]vk.VertexInputAttributeDescription{
vk.VertexInputAttributeDescription{
.location = 0,
.binding = binding_desc[0].binding,
.format = .R32G32_SFLOAT,
.offset = @byteOffsetOf(imgui.DrawVert, "pos"),
},
vk.VertexInputAttributeDescription{
.location = 1,
.binding = binding_desc[0].binding,
.format = .R32G32_SFLOAT,
.offset = @byteOffsetOf(imgui.DrawVert, "uv"),
},
vk.VertexInputAttributeDescription{
.location = 2,
.binding = binding_desc[0].binding,
.format = .R8G8B8A8_UNORM,
.offset = @byteOffsetOf(imgui.DrawVert, "col"),
},
};
const vertex_info = vk.PipelineVertexInputStateCreateInfo{
.vertexBindingDescriptionCount = binding_desc.len,
.pVertexBindingDescriptions = &binding_desc,
.vertexAttributeDescriptionCount = attribute_desc.len,
.pVertexAttributeDescriptions = &attribute_desc,
};
const ia_info = vk.PipelineInputAssemblyStateCreateInfo{
.topology = .TRIANGLE_LIST,
.primitiveRestartEnable = vk.FALSE,
};
const viewport_info = vk.PipelineViewportStateCreateInfo{
.viewportCount = 1,
.scissorCount = 1,
};
const raster_info = vk.PipelineRasterizationStateCreateInfo{
.polygonMode = .FILL,
.cullMode = vk.CullModeFlags.none,
.frontFace = .COUNTER_CLOCKWISE,
.lineWidth = 1.0,
.depthClampEnable = vk.FALSE,
.rasterizerDiscardEnable = vk.FALSE,
.depthBiasEnable = vk.FALSE,
.depthBiasConstantFactor = 0,
.depthBiasClamp = 0,
.depthBiasSlopeFactor = 0,
};
const ms_info = vk.PipelineMultisampleStateCreateInfo{
.rasterizationSamples = if (!v.MSAASamples.isEmpty()) v.MSAASamples else .{ .t1 = true },
.sampleShadingEnable = vk.FALSE,
.minSampleShading = 0,
.alphaToCoverageEnable = vk.FALSE,
.alphaToOneEnable = vk.FALSE,
};
const color_attachment = [_]vk.PipelineColorBlendAttachmentState{vk.PipelineColorBlendAttachmentState{
.blendEnable = vk.TRUE,
.srcColorBlendFactor = .SRC_ALPHA,
.dstColorBlendFactor = .ONE_MINUS_SRC_ALPHA,
.colorBlendOp = .ADD,
.srcAlphaBlendFactor = .ONE_MINUS_SRC_ALPHA,
.dstAlphaBlendFactor = .ZERO,
.alphaBlendOp = .ADD,
.colorWriteMask = .{ .r = true, .g = true, .b = true, .a = true },
}};
const depth_info = vk.PipelineDepthStencilStateCreateInfo{
.depthTestEnable = vk.FALSE,
.depthWriteEnable = vk.FALSE,
.depthCompareOp = .NEVER,
.depthBoundsTestEnable = vk.FALSE,
.stencilTestEnable = vk.FALSE,
.front = undefined,
.back = undefined,
.minDepthBounds = 0,
.maxDepthBounds = 0,
};
const blend_info = vk.PipelineColorBlendStateCreateInfo{
.attachmentCount = color_attachment.len,
.pAttachments = &color_attachment,
.logicOpEnable = vk.FALSE,
.logicOp = .CLEAR,
.blendConstants = [_]f32{ 0, 0, 0, 0 },
};
const dynamic_states = [_]vk.DynamicState{ .VIEWPORT, .SCISSOR };
const dynamic_state = vk.PipelineDynamicStateCreateInfo{
.dynamicStateCount = dynamic_states.len,
.pDynamicStates = &dynamic_states,
};
const info = vk.GraphicsPipelineCreateInfo{
.flags = g_PipelineCreateFlags,
.stageCount = stage.len,
.pStages = &stage,
.pVertexInputState = &vertex_info,
.pInputAssemblyState = &ia_info,
.pViewportState = &viewport_info,
.pRasterizationState = &raster_info,
.pMultisampleState = &ms_info,
.pDepthStencilState = &depth_info,
.pColorBlendState = &blend_info,
.pDynamicState = &dynamic_state,
.layout = g_PipelineLayout,
.renderPass = g_RenderPass,
.subpass = 0,
.basePipelineIndex = 0,
};
var out_pipeline: vk.Pipeline = undefined;
try vk.CreateGraphicsPipelines(v.Device, v.PipelineCache, arrayPtr(&info), v.VkAllocator, arrayPtr(&out_pipeline));
g_Pipeline = out_pipeline;
vk.DestroyShaderModule(v.Device, vert_module, v.VkAllocator);
vk.DestroyShaderModule(v.Device, frag_module, v.VkAllocator);
}
pub fn DestroyFontUploadObjects() void {
const v = &g_VulkanInitInfo;
if (g_UploadBuffer != .Null) {
vk.DestroyBuffer(v.Device, g_UploadBuffer, v.VkAllocator);
g_UploadBuffer = .Null;
}
if (g_UploadBufferMemory != .Null) {
vk.FreeMemory(v.Device, g_UploadBufferMemory, v.VkAllocator);
g_UploadBufferMemory = .Null;
}
}
fn DestroyDeviceObjects() void {
const v = &g_VulkanInitInfo;
DestroyWindowRenderBuffers(v.Device, &g_MainWindowRenderBuffers, v.VkAllocator, v.Allocator);
DestroyFontUploadObjects();
if (g_FontView != .Null) {
vk.DestroyImageView(v.Device, g_FontView, v.VkAllocator);
g_FontView = .Null;
}
if (g_FontImage != .Null) {
vk.DestroyImage(v.Device, g_FontImage, v.VkAllocator);
g_FontImage = .Null;
}
if (g_FontMemory != .Null) {
vk.FreeMemory(v.Device, g_FontMemory, v.VkAllocator);
g_FontMemory = .Null;
}
if (g_FontSampler != .Null) {
vk.DestroySampler(v.Device, g_FontSampler, v.VkAllocator);
g_FontSampler = .Null;
}
if (g_DescriptorSetLayout != .Null) {
vk.DestroyDescriptorSetLayout(v.Device, g_DescriptorSetLayout, v.VkAllocator);
g_DescriptorSetLayout = .Null;
}
if (g_PipelineLayout != .Null) {
vk.DestroyPipelineLayout(v.Device, g_PipelineLayout, v.VkAllocator);
g_PipelineLayout = .Null;
}
if (g_Pipeline != .Null) {
vk.DestroyPipeline(v.Device, g_Pipeline, v.VkAllocator);
g_Pipeline = .Null;
}
}
pub fn Init(info: *InitInfo, render_pass: vk.RenderPass) !void {
// Setup back-end capabilities flags
const io = imgui.GetIO();
io.BackendRendererName = "imgui_impl_vulkan";
io.BackendFlags.RendererHasVtxOffset = true; // We can honor the imgui.DrawCmd::VtxOffset field, allowing for large meshes.
if (info.MinImageCount < 2) return error.FailedStuff;
std.debug.assert(info.MinImageCount >= 2);
std.debug.assert(info.ImageCount >= info.MinImageCount);
g_VulkanInitInfo = info.*;
g_RenderPass = render_pass;
try CreateDeviceObjects();
}
pub fn Shutdown() void {
DestroyDeviceObjects();
}
pub fn NewFrame() void {}
pub fn SetMinImageCount(min_image_count: u32) !void {
std.debug.assert(min_image_count >= 2);
if (g_VulkanInitInfo.MinImageCount == min_image_count)
return;
const v = &g_VulkanInitInfo;
try vk.DeviceWaitIdle(v.Device);
DestroyWindowRenderBuffers(v.Device, &g_MainWindowRenderBuffers, v.VkAllocator, v.Allocator);
g_VulkanInitInfo.MinImageCount = min_image_count;
}
//-------------------------------------------------------------------------
// Internal / Miscellaneous Vulkan Helpers
// (Used by example's main.cpp. Used by multi-viewport features. PROBABLY NOT used by your own app.)
//-------------------------------------------------------------------------
// You probably do NOT need to use or care about those functions.
// Those functions only exist because:
// 1) they facilitate the readability and maintenance of the multiple main.cpp examples files.
// 2) the upcoming multi-viewport feature will need them internally.
// Generally we avoid exposing any kind of superfluous high-level helpers in the bindings,
// but it is too much code to duplicate everywhere so we exceptionally expose them.
//
// Your engine/app will likely _already_ have code to setup all that stuff (swap chain, render pass, frame buffers, etc.).
// You may read this code to learn about Vulkan, but it is recommended you use you own custom tailored code to do equivalent work.
// (The XXX functions do not interact with any of the state used by the regular XXX functions)
//-------------------------------------------------------------------------
pub fn SelectSurfaceFormat(physical_device: vk.PhysicalDevice, surface: vk.SurfaceKHR, request_formats: []const vk.Format, request_color_space: vk.ColorSpaceKHR, allocator: *std.mem.Allocator) !vk.SurfaceFormatKHR {
// Per Spec Format and View Format are expected to be the same unless VK_IMAGE_CREATE_MUTABLE_BIT was set at image creation
// Assuming that the default behavior is without setting this bit, there is no need for separate Swapchain image and image view format
// Additionally several new color spaces were introduced with Vulkan Spec v1.0.40,
// hence we must make sure that a format with the mostly available color space, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR, is found and used.
const count = try vk.GetPhysicalDeviceSurfaceFormatsCountKHR(physical_device, surface);
const formats = try allocator.alloc(vk.SurfaceFormatKHR, count);
defer allocator.free(formats);
_ = try vk.GetPhysicalDeviceSurfaceFormatsKHR(physical_device, surface, formats);
// First check if only one format, VK_FORMAT_UNDEFINED, is available, which would imply that any format is available
if (formats.len == 1) {
if (formats[0].format == .UNDEFINED) {
return vk.SurfaceFormatKHR{
.format = request_formats[0],
.colorSpace = request_color_space,
};
} else {
// No point in searching another format
return formats[0];
}
} else {
// Request several formats, the first found will be used
for (request_formats) |request|
for (formats) |avail|
if (avail.format == request and avail.colorSpace == request_color_space)
return avail;
// If none of the requested image formats could be found, use the first available
return formats[0];
}
}
pub fn SelectPresentMode(physical_device: vk.PhysicalDevice, surface: vk.SurfaceKHR, request_modes: []const vk.PresentModeKHR, allocator: *std.mem.Allocator) !vk.PresentModeKHR {
// Request a certain mode and confirm that it is available. If not use VK_PRESENT_MODE_FIFO_KHR which is mandatory
const count = try vk.GetPhysicalDeviceSurfacePresentModesCountKHR(physical_device, surface);
const modes = try allocator.alloc(vk.PresentModeKHR, count);
defer allocator.free(modes);
_ = try vk.GetPhysicalDeviceSurfacePresentModesKHR(physical_device, surface, modes);
//for (modes) |mode, i|
// std.debug.warn("[vulkan] avail_modes[{}] = {}\n", i, mode);
for (request_modes) |request|
for (modes) |avail|
if (request == avail)
return avail;
return .FIFO; // Always available
}
fn CreateWindowCommandBuffers(physical_device: vk.PhysicalDevice, device: vk.Device, wd: *Window, queue_family: u32, allocator: ?*const vk.AllocationCallbacks) !void {
// Create Command Buffers
var i = @as(u32, 0);
while (i < wd.ImageCount) : (i += 1) {
const fd = &wd.Frames[i];
const fsd = &wd.FrameSemaphores[i];
{
const info = vk.CommandPoolCreateInfo{
.flags = .{ .resetCommandBuffer = true },
.queueFamilyIndex = queue_family,
};
fd.CommandPool = try vk.CreateCommandPool(device, info, allocator);
}
{
const info = vk.CommandBufferAllocateInfo{
.commandPool = fd.CommandPool,
.level = .PRIMARY,
.commandBufferCount = 1,
};
try vk.AllocateCommandBuffers(device, info, arrayPtr(&fd.CommandBuffer));
}
{
const info = vk.FenceCreateInfo{
.flags = .{ .signaled = true },
};
fd.Fence = try vk.CreateFence(device, info, allocator);
}
{
const info = vk.SemaphoreCreateInfo{};
fsd.ImageAcquiredSemaphore = try vk.CreateSemaphore(device, info, allocator);
fsd.RenderCompleteSemaphore = try vk.CreateSemaphore(device, info, allocator);
}
}
}
fn GetMinImageCountFromPresentMode(present_mode: vk.PresentModeKHR) u32 {
if (present_mode == .MAILBOX)
return 3;
if (present_mode == .FIFO or present_mode == .FIFO_RELAXED)
return 2;
if (present_mode == .IMMEDIATE)
return 1;
unreachable;
}
// Also destroy old swap chain and in-flight frames data, if any.
fn CreateWindowSwapChain(physical_device: vk.PhysicalDevice, device: vk.Device, wd: *Window, allocator: ?*const vk.AllocationCallbacks, w: u32, h: u32, min_image_count_in: u32) !void {
const old_swapchain = wd.Swapchain;
try vk.DeviceWaitIdle(device);
// We don't use DestroyWindow() because we want to preserve the old swapchain to create the new one.
// Destroy old Framebuffer
if (wd.ImageCount > 0) {
var i = @as(u32, 0);
while (i < wd.ImageCount) : (i += 1) {
DestroyFrame(device, &wd.Frames[i], allocator);
DestroyFrameSemaphores(device, &wd.FrameSemaphores[i], allocator);
}
wd.Allocator.free(wd.Frames);
wd.Allocator.free(wd.FrameSemaphores);
wd.Frames = &[_]Frame{};
wd.FrameSemaphores = &[_]FrameSemaphores{};
wd.ImageCount = 0;
}
if (wd.RenderPass == .Null) {
vk.DestroyRenderPass(device, wd.RenderPass, allocator);
}
// If min image count was not specified, request different count of images dependent on selected present mode
var min_image_count = min_image_count_in;
if (min_image_count == 0)
min_image_count = GetMinImageCountFromPresentMode(wd.PresentMode);
// Create Swapchain
{
var info = vk.SwapchainCreateInfoKHR{
.surface = wd.Surface,
.minImageCount = min_image_count,
.imageFormat = wd.SurfaceFormat.format,
.imageColorSpace = wd.SurfaceFormat.colorSpace,
.imageArrayLayers = 1,
.imageUsage = .{ .colorAttachment = true },
.imageExtent = undefined, // we will fill this in later
.imageSharingMode = .EXCLUSIVE, // Assume that graphics family == present family
.preTransform = .{ .identity = true },
.compositeAlpha = .{ .opaque = true },
.presentMode = wd.PresentMode,
.clipped = vk.TRUE,
.oldSwapchain = old_swapchain,
};
const cap = try vk.GetPhysicalDeviceSurfaceCapabilitiesKHR(physical_device, wd.Surface);
if (info.minImageCount < cap.minImageCount) {
info.minImageCount = cap.minImageCount;
} else if (cap.maxImageCount != 0 and info.minImageCount > cap.maxImageCount) {
info.minImageCount = cap.maxImageCount;
}
if (cap.currentExtent.width == 0xffffffff) {
wd.Width = w;
wd.Height = h;
info.imageExtent = vk.Extent2D{ .width = w, .height = h };
} else {
wd.Width = cap.currentExtent.width;
wd.Height = cap.currentExtent.height;
info.imageExtent = cap.currentExtent;
}
wd.Swapchain = try vk.CreateSwapchainKHR(device, info, allocator);
wd.ImageCount = try vk.GetSwapchainImagesCountKHR(device, wd.Swapchain);
var backbuffers: [16]vk.Image = undefined;
const imagesResult = try vk.GetSwapchainImagesKHR(device, wd.Swapchain, &backbuffers);
std.debug.assert(imagesResult.result == .SUCCESS);
wd.ImageCount = @intCast(u32, imagesResult.swapchainImages.len);
std.debug.assert(wd.Frames.len == 0);
wd.Frames = try wd.Allocator.alloc(Frame, wd.ImageCount);
wd.FrameSemaphores = try wd.Allocator.alloc(FrameSemaphores, wd.ImageCount);
for (wd.Frames) |*frame, i| frame.* = Frame{ .Backbuffer = imagesResult.swapchainImages[i] };
for (wd.FrameSemaphores) |*fs| fs.* = FrameSemaphores{};
}
if (old_swapchain != .Null)
vk.DestroySwapchainKHR(device, old_swapchain, allocator);
// Create the Render Pass
{
const attachment = vk.AttachmentDescription{
.format = wd.SurfaceFormat.format,
.samples = .{ .t1 = true },
.loadOp = .CLEAR,
.storeOp = .STORE,
.stencilLoadOp = .DONT_CARE,
.stencilStoreOp = .DONT_CARE,
.initialLayout = .UNDEFINED,
.finalLayout = .PRESENT_SRC_KHR,
};
const color_attachment = vk.AttachmentReference{
.attachment = 0,
.layout = .COLOR_ATTACHMENT_OPTIMAL,
};
const subpass = vk.SubpassDescription{
.pipelineBindPoint = .GRAPHICS,
.colorAttachmentCount = 1,
.pColorAttachments = arrayPtr(&color_attachment),
};
const dependency = vk.SubpassDependency{
.srcSubpass = vk.SUBPASS_EXTERNAL,
.dstSubpass = 0,
.srcStageMask = .{ .colorAttachmentOutput = true },
.dstStageMask = .{ .colorAttachmentOutput = true },
.srcAccessMask = .{},
.dstAccessMask = .{ .colorAttachmentWrite = true },
};
const info = vk.RenderPassCreateInfo{
.attachmentCount = 1,
.pAttachments = arrayPtr(&attachment),
.subpassCount = 1,
.pSubpasses = arrayPtr(&subpass),
.dependencyCount = 1,
.pDependencies = arrayPtr(&dependency),
};
wd.RenderPass = try vk.CreateRenderPass(device, info, allocator);
}
// Create The Image Views
{
var info = vk.ImageViewCreateInfo{
.image = undefined, // we will set this later
.viewType = .T_2D,
.format = wd.SurfaceFormat.format,
.components = vk.ComponentMapping{
.r = .IDENTITY,
.g = .IDENTITY,
.b = .IDENTITY,
.a = .IDENTITY,
},
.subresourceRange = vk.ImageSubresourceRange{
.aspectMask = .{ .color = true },
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
};
for (wd.Frames) |*fd| {
info.image = fd.Backbuffer;
fd.BackbufferView = try vk.CreateImageView(device, info, allocator);
}
}
// Create Framebuffer
{
var attachment = [_]vk.ImageView{undefined}; // we will set this later
const info = vk.FramebufferCreateInfo{
.renderPass = wd.RenderPass,
.attachmentCount = attachment.len,
.pAttachments = &attachment,
.width = wd.Width,
.height = wd.Height,
.layers = 1,
};
for (wd.Frames) |*fd| {
attachment[0] = fd.BackbufferView;
fd.Framebuffer = try vk.CreateFramebuffer(device, info, allocator);
}
}
}
pub fn CreateWindow(instance: vk.Instance, physical_device: vk.PhysicalDevice, device: vk.Device, wd: *Window, queue_family: u32, allocator: ?*const vk.AllocationCallbacks, width: u32, height: u32, min_image_count: u32) !void {
try CreateWindowSwapChain(physical_device, device, wd, allocator, width, height, min_image_count);
try CreateWindowCommandBuffers(physical_device, device, wd, queue_family, allocator);
}
pub fn DestroyWindow(instance: vk.Instance, device: vk.Device, wd: *Window, allocator: ?*const vk.AllocationCallbacks) !void {
try vk.DeviceWaitIdle(device); // FIXME: We could wait on the Queue if we had the queue in wd. (otherwise VulkanH functions can't use globals)
//vk.QueueWaitIdle(g_Queue);
for (wd.Frames) |_, i| {
DestroyFrame(device, &wd.Frames[i], allocator);
DestroyFrameSemaphores(device, &wd.FrameSemaphores[i], allocator);
}
wd.Allocator.free(wd.Frames);
wd.Allocator.free(wd.FrameSemaphores);
wd.Frames = &[_]Frame{};
wd.FrameSemaphores = &[_]FrameSemaphores{};
vk.DestroyRenderPass(device, wd.RenderPass, allocator);
vk.DestroySwapchainKHR(device, wd.Swapchain, allocator);
vk.DestroySurfaceKHR(instance, wd.Surface, allocator);
wd.* = Window{};
}
fn DestroyFrame(device: vk.Device, fd: *Frame, allocator: ?*const vk.AllocationCallbacks) void {
vk.DestroyFence(device, fd.Fence, allocator);
vk.FreeCommandBuffers(device, fd.CommandPool, arrayPtr(&fd.CommandBuffer));
vk.DestroyCommandPool(device, fd.CommandPool, allocator);
fd.Fence = undefined;
fd.CommandBuffer = undefined;
fd.CommandPool = undefined;
vk.DestroyImageView(device, fd.BackbufferView, allocator);
vk.DestroyFramebuffer(device, fd.Framebuffer, allocator);
}
fn DestroyFrameSemaphores(device: vk.Device, fsd: *FrameSemaphores, allocator: ?*const vk.AllocationCallbacks) void {
vk.DestroySemaphore(device, fsd.ImageAcquiredSemaphore, allocator);
vk.DestroySemaphore(device, fsd.RenderCompleteSemaphore, allocator);
fsd.ImageAcquiredSemaphore = undefined;
fsd.RenderCompleteSemaphore = undefined;
}
fn DestroyFrameRenderBuffers(device: vk.Device, buffers: *FrameRenderBuffers, allocator: ?*const vk.AllocationCallbacks) void {
if (buffers.VertexBuffer != .Null) {
vk.DestroyBuffer(device, buffers.VertexBuffer, allocator);
buffers.VertexBuffer = undefined;
}
if (buffers.VertexBufferMemory != .Null) {
vk.FreeMemory(device, buffers.VertexBufferMemory, allocator);
buffers.VertexBufferMemory = undefined;
}
if (buffers.IndexBuffer != .Null) {
vk.DestroyBuffer(device, buffers.IndexBuffer, allocator);
buffers.IndexBuffer = undefined;
}
if (buffers.IndexBufferMemory != .Null) {
vk.FreeMemory(device, buffers.IndexBufferMemory, allocator);
buffers.IndexBufferMemory = undefined;
}
buffers.VertexBufferSize = 0;
buffers.IndexBufferSize = 0;
}
fn DestroyWindowRenderBuffers(device: vk.Device, buffers: *WindowRenderBuffers, vkAllocator: ?*const vk.AllocationCallbacks, allocator: *std.mem.Allocator) void {
for (buffers.FrameRenderBuffers) |*frb|
DestroyFrameRenderBuffers(device, frb, vkAllocator);
allocator.free(buffers.FrameRenderBuffers);
buffers.FrameRenderBuffers = &[_]FrameRenderBuffers{};
buffers.Index = 0;
}
// converts *T to *[1]T
fn arrayPtrType(comptime ptrType: type) type {
const info = @typeInfo(ptrType);
if (info.Pointer.is_const) {
return *const [1]ptrType.Child;
} else {
return *[1]ptrType.Child;
}
}
fn arrayPtr(ptr: var) arrayPtrType(@TypeOf(ptr)) {
return @ptrCast(arrayPtrType(@TypeOf(ptr)), ptr);
}
|
examples/imgui_impl_vulkan.zig
|
const std = @import("std");
const mem = std.mem;
const SentenceTerminal = @This();
allocator: *mem.Allocator,
array: []bool,
lo: u21 = 33,
hi: u21 = 121480,
pub fn init(allocator: *mem.Allocator) !SentenceTerminal {
var instance = SentenceTerminal{
.allocator = allocator,
.array = try allocator.alloc(bool, 121448),
};
mem.set(bool, instance.array, false);
var index: u21 = 0;
instance.array[0] = true;
instance.array[13] = true;
instance.array[30] = true;
instance.array[1384] = true;
index = 1533;
while (index <= 1534) : (index += 1) {
instance.array[index] = true;
}
instance.array[1715] = true;
index = 1759;
while (index <= 1761) : (index += 1) {
instance.array[index] = true;
}
instance.array[2008] = true;
instance.array[2070] = true;
instance.array[2072] = true;
index = 2076;
while (index <= 2077) : (index += 1) {
instance.array[index] = true;
}
index = 2371;
while (index <= 2372) : (index += 1) {
instance.array[index] = true;
}
index = 4137;
while (index <= 4138) : (index += 1) {
instance.array[index] = true;
}
instance.array[4929] = true;
index = 4934;
while (index <= 4935) : (index += 1) {
instance.array[index] = true;
}
instance.array[5709] = true;
index = 5908;
while (index <= 5909) : (index += 1) {
instance.array[index] = true;
}
instance.array[6114] = true;
instance.array[6120] = true;
index = 6435;
while (index <= 6436) : (index += 1) {
instance.array[index] = true;
}
index = 6791;
while (index <= 6794) : (index += 1) {
instance.array[index] = true;
}
index = 6969;
while (index <= 6970) : (index += 1) {
instance.array[index] = true;
}
index = 6973;
while (index <= 6974) : (index += 1) {
instance.array[index] = true;
}
index = 7194;
while (index <= 7195) : (index += 1) {
instance.array[index] = true;
}
index = 7261;
while (index <= 7262) : (index += 1) {
instance.array[index] = true;
}
index = 8219;
while (index <= 8220) : (index += 1) {
instance.array[index] = true;
}
index = 8230;
while (index <= 8232) : (index += 1) {
instance.array[index] = true;
}
instance.array[11789] = true;
instance.array[11803] = true;
instance.array[12257] = true;
instance.array[42206] = true;
index = 42477;
while (index <= 42478) : (index += 1) {
instance.array[index] = true;
}
instance.array[42706] = true;
instance.array[42710] = true;
index = 43093;
while (index <= 43094) : (index += 1) {
instance.array[index] = true;
}
index = 43181;
while (index <= 43182) : (index += 1) {
instance.array[index] = true;
}
instance.array[43278] = true;
index = 43431;
while (index <= 43432) : (index += 1) {
instance.array[index] = true;
}
index = 43580;
while (index <= 43582) : (index += 1) {
instance.array[index] = true;
}
index = 43727;
while (index <= 43728) : (index += 1) {
instance.array[index] = true;
}
instance.array[43978] = true;
instance.array[65073] = true;
index = 65077;
while (index <= 65078) : (index += 1) {
instance.array[index] = true;
}
instance.array[65248] = true;
instance.array[65261] = true;
instance.array[65278] = true;
instance.array[65344] = true;
index = 68149;
while (index <= 68150) : (index += 1) {
instance.array[index] = true;
}
index = 69428;
while (index <= 69432) : (index += 1) {
instance.array[index] = true;
}
index = 69670;
while (index <= 69671) : (index += 1) {
instance.array[index] = true;
}
index = 69789;
while (index <= 69792) : (index += 1) {
instance.array[index] = true;
}
index = 69920;
while (index <= 69922) : (index += 1) {
instance.array[index] = true;
}
index = 70052;
while (index <= 70053) : (index += 1) {
instance.array[index] = true;
}
instance.array[70060] = true;
index = 70077;
while (index <= 70078) : (index += 1) {
instance.array[index] = true;
}
index = 70167;
while (index <= 70168) : (index += 1) {
instance.array[index] = true;
}
index = 70170;
while (index <= 70171) : (index += 1) {
instance.array[index] = true;
}
instance.array[70280] = true;
index = 70698;
while (index <= 70699) : (index += 1) {
instance.array[index] = true;
}
index = 71073;
while (index <= 71074) : (index += 1) {
instance.array[index] = true;
}
index = 71080;
while (index <= 71094) : (index += 1) {
instance.array[index] = true;
}
index = 71200;
while (index <= 71201) : (index += 1) {
instance.array[index] = true;
}
index = 71451;
while (index <= 71453) : (index += 1) {
instance.array[index] = true;
}
instance.array[71971] = true;
instance.array[71973] = true;
index = 72225;
while (index <= 72226) : (index += 1) {
instance.array[index] = true;
}
index = 72314;
while (index <= 72315) : (index += 1) {
instance.array[index] = true;
}
index = 72736;
while (index <= 72737) : (index += 1) {
instance.array[index] = true;
}
index = 73430;
while (index <= 73431) : (index += 1) {
instance.array[index] = true;
}
index = 92749;
while (index <= 92750) : (index += 1) {
instance.array[index] = true;
}
instance.array[92884] = true;
index = 92950;
while (index <= 92951) : (index += 1) {
instance.array[index] = true;
}
instance.array[92963] = true;
instance.array[93815] = true;
instance.array[113790] = true;
instance.array[121447] = true;
// Placeholder: 0. Struct name, 1. Code point kind
return instance;
}
pub fn deinit(self: *SentenceTerminal) void {
self.allocator.free(self.array);
}
// isSentenceTerminal checks if cp is of the kind Sentence_Terminal.
pub fn isSentenceTerminal(self: SentenceTerminal, 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/SentenceTerminal.zig
|
const std = @import("std");
const string = []const u8;
const u = @import("index.zig");
//
//
pub const b = 1;
pub const kb = b * 1024;
pub const mb = kb * 1024;
pub const gb = mb * 1024;
pub fn print(comptime fmt: string, args: anytype) void {
std.debug.print(fmt ++ "\n", args);
}
const ansi_red = "\x1B[31m";
const ansi_reset = "\x1B[39m";
pub fn assert(ok: bool, comptime fmt: string, args: anytype) void {
if (!ok) {
print(ansi_red ++ fmt ++ ansi_reset, args);
std.os.exit(1);
}
}
pub fn fail(comptime fmt: string, args: anytype) noreturn {
assert(false, fmt, args);
unreachable;
}
pub fn try_index(comptime T: type, array: []T, n: usize, def: T) T {
if (array.len <= n) {
return def;
}
return array[n];
}
pub fn split(alloc: std.mem.Allocator, in: string, delim: string) ![]string {
var list = std.ArrayList(string).init(alloc);
defer list.deinit();
var iter = std.mem.split(u8, in, delim);
while (iter.next()) |str| {
try list.append(str);
}
return list.toOwnedSlice();
}
pub fn trim_prefix(in: string, prefix: string) string {
if (std.mem.startsWith(u8, in, prefix)) {
return in[prefix.len..];
}
return in;
}
pub fn does_file_exist(dir: ?std.fs.Dir, fpath: string) !bool {
const file = (dir orelse std.fs.cwd()).openFile(fpath, .{}) catch |e| switch (e) {
error.FileNotFound => return false,
error.IsDir => return true,
else => return e,
};
defer file.close();
return true;
}
pub fn does_folder_exist(fpath: string) !bool {
const file = std.fs.cwd().openFile(fpath, .{}) catch |e| switch (e) {
error.FileNotFound => return false,
error.IsDir => return true,
else => return e,
};
defer file.close();
const s = try file.stat();
if (s.kind != .Directory) {
return false;
}
return true;
}
pub fn _join(comptime delim: string, comptime xs: []const string) string {
var buf: string = "";
for (xs) |x, i| {
buf = buf ++ x;
if (i < xs.len - 1) buf = buf ++ delim;
}
return buf;
}
pub fn trim_suffix(in: string, suffix: string) string {
if (std.mem.endsWith(u8, in, suffix)) {
return in[0 .. in.len - suffix.len];
}
return in;
}
pub fn list_contains(haystack: []const string, needle: string) bool {
for (haystack) |item| {
if (std.mem.eql(u8, item, needle)) {
return true;
}
}
return false;
}
pub fn list_contains_gen(comptime T: type, haystack: []const T, needle: T) bool {
for (haystack) |item| {
if (item.eql(needle)) {
return true;
}
}
return false;
}
pub fn file_list(alloc: std.mem.Allocator, dpath: string) ![]const string {
var list = std.ArrayList(string).init(alloc);
defer list.deinit();
const dir = try std.fs.cwd().openDir(dpath, .{ .iterate = true });
var walk = try dir.walk(alloc);
defer walk.deinit();
while (true) {
if (try walk.next()) |entry| {
if (entry.kind != .File) {
continue;
}
try list.append(try alloc.dupe(u8, entry.path));
} else {
break;
}
}
return list.toOwnedSlice();
}
pub fn run_cmd_raw(alloc: std.mem.Allocator, dir: ?string, args: []const string) !std.ChildProcess.ExecResult {
return std.ChildProcess.exec(.{ .allocator = alloc, .cwd = dir, .argv = args, .max_output_bytes = std.math.maxInt(usize) }) catch |e| switch (e) {
error.FileNotFound => {
u.fail("\"{s}\" command not found", .{args[0]});
},
else => return e,
};
}
pub fn run_cmd(alloc: std.mem.Allocator, dir: ?string, args: []const string) !u32 {
const result = try run_cmd_raw(alloc, dir, args);
alloc.free(result.stdout);
alloc.free(result.stderr);
return result.term.Exited;
}
pub fn list_remove(alloc: std.mem.Allocator, input: []string, search: string) ![]string {
var list = std.ArrayList(string).init(alloc);
defer list.deinit();
for (input) |item| {
if (!std.mem.eql(u8, item, search)) {
try list.append(item);
}
}
return list.toOwnedSlice();
}
pub fn last(in: []string) !string {
if (in.len == 0) {
return error.EmptyArray;
}
return in[in.len - 1];
}
const alphabet = "0123456789abcdefghijklmnopqrstuvwxyz";
pub fn random_string(alloc: std.mem.Allocator, len: usize) !string {
const now = @intCast(u64, std.time.nanoTimestamp());
var rand = std.rand.DefaultPrng.init(now);
const r = &rand.random();
var buf = try alloc.alloc(u8, len);
var i: usize = 0;
while (i < len) : (i += 1) {
buf[i] = alphabet[r.int(usize) % alphabet.len];
}
return buf;
}
pub fn parse_split(comptime T: type, comptime delim: string) type {
return struct {
const Self = @This();
id: T,
string: string,
pub fn do(input: string) !Self {
var iter = std.mem.split(u8, input, delim);
const start = iter.next() orelse return error.IterEmpty;
const id = std.meta.stringToEnum(T, start) orelse return error.NoMemberFound;
return Self{
.id = id,
.string = iter.rest(),
};
}
};
}
pub const HashFn = enum {
blake3,
sha256,
sha512,
};
pub fn validate_hash(alloc: std.mem.Allocator, input: string, file_path: string) !bool {
const hash = parse_split(HashFn, "-").do(input) catch return false;
const file = try std.fs.cwd().openFile(file_path, .{});
defer file.close();
const data = try file.reader().readAllAlloc(alloc, gb);
const expected = hash.string;
const actual = switch (hash.id) {
.blake3 => try do_hash(alloc, std.crypto.hash.Blake3, data),
.sha256 => try do_hash(alloc, std.crypto.hash.sha2.Sha256, data),
.sha512 => try do_hash(alloc, std.crypto.hash.sha2.Sha512, data),
};
const result = std.mem.startsWith(u8, actual, expected);
if (!result) {
std.log.info("expected: {s}, actual: {s}", .{ expected, actual });
}
return result;
}
pub fn do_hash(alloc: std.mem.Allocator, comptime algo: type, data: string) !string {
const h = &algo.init(.{});
var out: [algo.digest_length]u8 = undefined;
h.update(data);
h.final(&out);
const hex = try std.fmt.allocPrint(alloc, "{x}", .{std.fmt.fmtSliceHexLower(out[0..])});
return hex;
}
/// Returns the result of running `git rev-parse HEAD`
pub fn git_rev_HEAD(alloc: std.mem.Allocator, dir: std.fs.Dir) !string {
const max = std.math.maxInt(usize);
const dirg = try dir.openDir(".git", .{});
const h = std.mem.trim(u8, try dirg.readFileAlloc(alloc, "HEAD", max), "\n");
const r = std.mem.trim(u8, try dirg.readFileAlloc(alloc, h[5..], max), "\n");
return r;
}
pub fn slice(comptime T: type, input: []const T, from: usize, to: usize) []const T {
const f = std.math.max(from, 0);
const t = std.math.min(to, input.len);
return input[f..t];
}
pub fn detect_pkgname(alloc: std.mem.Allocator, override: string, dir: string) !string {
if (override.len > 0) {
return override;
}
const dirO = if (dir.len == 0) std.fs.cwd() else try std.fs.cwd().openDir(dir, .{});
if (!(try does_file_exist(dirO, "build.zig"))) {
return error.NoBuildZig;
}
const dpath = try std.fs.realpathAlloc(alloc, try std.fs.path.join(alloc, &.{ dir, "build.zig" }));
const splitP = try split(alloc, dpath, std.fs.path.sep_str);
var name = splitP[splitP.len - 2];
name = trim_prefix(name, "zig-");
assert(name.len > 0, "package name must not be an empty string", .{});
return name;
}
pub fn detct_mainfile(alloc: std.mem.Allocator, override: string, dir: ?std.fs.Dir, name: string) !string {
if (override.len > 0) {
if (try does_file_exist(dir, override)) {
if (std.mem.endsWith(u8, override, ".zig")) {
return override;
}
}
}
const namedotzig = try std.mem.concat(alloc, u8, &.{ name, ".zig" });
if (try does_file_exist(dir, namedotzig)) {
return namedotzig;
}
if (try does_file_exist(dir, try std.fs.path.join(alloc, &.{ "src", "lib.zig" }))) {
return "src/lib.zig";
}
if (try does_file_exist(dir, try std.fs.path.join(alloc, &.{ "src", "main.zig" }))) {
return "src/main.zig";
}
return error.CantFindMain;
}
pub fn indexOfN(haystack: string, needle: u8, n: usize) ?usize {
var i: usize = 0;
var c: usize = 0;
while (c < n) {
i = indexOfAfter(haystack, needle, i) orelse return null;
c += 1;
}
return i;
}
pub fn indexOfAfter(haystack: string, needle: u8, after: usize) ?usize {
for (haystack) |c, i| {
if (i <= after) continue;
if (c == needle) return i;
}
return null;
}
|
src/util/funcs.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const List = std.ArrayList;
const Map = std.AutoHashMap;
const StrMap = std.StringHashMap;
const BitSet = std.DynamicBitSet;
const Str = []const u8;
const util = @import("util.zig");
const gpa = util.gpa;
const data = @embedFile("../data/day05.txt");
// const data = @embedFile("../data/day05-tst.txt");
pub fn main() !void {
var it = tokenize(u8, data, "\r\n");
var list = List(Point).init(gpa);
var gw: i32 = 0;
var gh: i32 = 0;
while (it.next()) |line| {
var l = tokenize(u8, line, " ,->");
var p0: Point = undefined;
var p1: Point = undefined;
p0[0] = try parseInt(i32, l.next().?, 10);
p0[1] = try parseInt(i32, l.next().?, 10);
p1[0] = try parseInt(i32, l.next().?, 10);
p1[1] = try parseInt(i32, l.next().?, 10);
try list.append(p0);
try list.append(p1);
gw = max(gw, max(p0[0], p1[0]));
gh = max(gh, max(p0[1], p1[1]));
}
gw += 1;
gh += 1;
var grid = try List(u32).initCapacity(gpa, @intCast(usize, gw * gh));
grid.appendNTimesAssumeCapacity(0, @intCast(usize, gw * gh));
var item_cpt: usize = list.items.len;
var i: usize = 0;
while (i < item_cpt) : (i += 2) {
var p0 = list.items[i + 0];
var p1 = list.items[i + 1];
// Comment this block out for part1
// if (p0[0] != p1[0] and p0[1] != p1[1]) {
// continue;
// }
var dx = p1[0] - p0[0];
var dy = p1[1] - p0[1];
dx = if (dx < 0) -1 else dx;
dx = if (dx > 0) 1 else dx;
dy = if (dy < 0) -1 else dy;
dy = if (dy > 0) 1 else dy;
var p = p0;
while (true) : ({
p[0] += dx;
p[1] += dy;
}) {
const coord = @intCast(usize, p[0] + p[1] * gw);
grid.items[coord] += 1;
if (p[0] == p1[0] and p[1] == p1[1]) {
break;
}
}
}
var count: usize = 0;
for (grid.items) |n| {
if (n > 1) {
count += 1;
}
}
print("{}\n", .{count});
}
const Point = [2]i32;
// Useful stdlib functions
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const indexOf = std.mem.indexOfScalar;
const indexOfAny = std.mem.indexOfAny;
const indexOfStr = std.mem.indexOfPosLinear;
const lastIndexOf = std.mem.lastIndexOfScalar;
const lastIndexOfAny = std.mem.lastIndexOfAny;
const lastIndexOfStr = std.mem.lastIndexOfLinear;
const trim = std.mem.trim;
const sliceMin = std.mem.min;
const sliceMax = std.mem.max;
const parseInt = std.fmt.parseInt;
const parseFloat = std.fmt.parseFloat;
const min = std.math.min;
const min3 = std.math.min3;
const max = std.math.max;
const max3 = std.math.max3;
const print = std.debug.print;
const assert = std.debug.assert;
const sort = std.sort.sort;
const asc = std.sort.asc;
const desc = std.sort.desc;
|
src/day05.zig
|
//--------------------------------------------------------------------------------
// Section: Types (1)
//--------------------------------------------------------------------------------
const IID_IChannelCredentials_Value = Guid.initString("181b448c-c17c-4b17-ac6d-06699b93198f");
pub const IID_IChannelCredentials = &IID_IChannelCredentials_Value;
pub const IChannelCredentials = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
SetWindowsCredential: fn(
self: *const IChannelCredentials,
domain: ?BSTR,
username: ?BSTR,
password: ?<PASSWORD>,
impersonationLevel: i32,
allowNtlm: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetUserNameCredential: fn(
self: *const IChannelCredentials,
username: ?BSTR,
password: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetClientCertificateFromStore: fn(
self: *const IChannelCredentials,
storeLocation: ?BSTR,
storeName: ?BSTR,
findYype: ?BSTR,
findValue: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetClientCertificateFromStoreByName: fn(
self: *const IChannelCredentials,
subjectName: ?BSTR,
storeLocation: ?BSTR,
storeName: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetClientCertificateFromFile: fn(
self: *const IChannelCredentials,
filename: ?BSTR,
password: ?BSTR,
keystorageFlags: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetDefaultServiceCertificateFromStore: fn(
self: *const IChannelCredentials,
storeLocation: ?BSTR,
storeName: ?BSTR,
findType: ?BSTR,
findValue: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetDefaultServiceCertificateFromStoreByName: fn(
self: *const IChannelCredentials,
subjectName: ?BSTR,
storeLocation: ?BSTR,
storeName: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetDefaultServiceCertificateFromFile: fn(
self: *const IChannelCredentials,
filename: ?BSTR,
password: ?BSTR,
keystorageFlags: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetServiceCertificateAuthentication: fn(
self: *const IChannelCredentials,
storeLocation: ?BSTR,
revocationMode: ?BSTR,
certificateValidationMode: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetIssuedToken: fn(
self: *const IChannelCredentials,
localIssuerAddres: ?BSTR,
localIssuerBindingType: ?BSTR,
localIssuerBinding: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IChannelCredentials_SetWindowsCredential(self: *const T, domain: ?BSTR, username: ?BSTR, password: ?BSTR, impersonationLevel: i32, allowNtlm: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IChannelCredentials.VTable, self.vtable).SetWindowsCredential(@ptrCast(*const IChannelCredentials, self), domain, username, password, impersonationLevel, allowNtlm);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IChannelCredentials_SetUserNameCredential(self: *const T, username: ?BSTR, password: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IChannelCredentials.VTable, self.vtable).SetUserNameCredential(@ptrCast(*const IChannelCredentials, self), username, password);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IChannelCredentials_SetClientCertificateFromStore(self: *const T, storeLocation: ?BSTR, storeName: ?BSTR, findYype: ?BSTR, findValue: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IChannelCredentials.VTable, self.vtable).SetClientCertificateFromStore(@ptrCast(*const IChannelCredentials, self), storeLocation, storeName, findYype, findValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IChannelCredentials_SetClientCertificateFromStoreByName(self: *const T, subjectName: ?BSTR, storeLocation: ?BSTR, storeName: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IChannelCredentials.VTable, self.vtable).SetClientCertificateFromStoreByName(@ptrCast(*const IChannelCredentials, self), subjectName, storeLocation, storeName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IChannelCredentials_SetClientCertificateFromFile(self: *const T, filename: ?BSTR, password: ?BSTR, keystorageFlags: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IChannelCredentials.VTable, self.vtable).SetClientCertificateFromFile(@ptrCast(*const IChannelCredentials, self), filename, password, keystorageFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IChannelCredentials_SetDefaultServiceCertificateFromStore(self: *const T, storeLocation: ?BSTR, storeName: ?BSTR, findType: ?BSTR, findValue: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IChannelCredentials.VTable, self.vtable).SetDefaultServiceCertificateFromStore(@ptrCast(*const IChannelCredentials, self), storeLocation, storeName, findType, findValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IChannelCredentials_SetDefaultServiceCertificateFromStoreByName(self: *const T, subjectName: ?BSTR, storeLocation: ?BSTR, storeName: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IChannelCredentials.VTable, self.vtable).SetDefaultServiceCertificateFromStoreByName(@ptrCast(*const IChannelCredentials, self), subjectName, storeLocation, storeName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IChannelCredentials_SetDefaultServiceCertificateFromFile(self: *const T, filename: ?BSTR, password: ?BSTR, keystorageFlags: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IChannelCredentials.VTable, self.vtable).SetDefaultServiceCertificateFromFile(@ptrCast(*const IChannelCredentials, self), filename, password, keystorageFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IChannelCredentials_SetServiceCertificateAuthentication(self: *const T, storeLocation: ?BSTR, revocationMode: ?BSTR, certificateValidationMode: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IChannelCredentials.VTable, self.vtable).SetServiceCertificateAuthentication(@ptrCast(*const IChannelCredentials, self), storeLocation, revocationMode, certificateValidationMode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IChannelCredentials_SetIssuedToken(self: *const T, localIssuerAddres: ?BSTR, localIssuerBindingType: ?BSTR, localIssuerBinding: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IChannelCredentials.VTable, self.vtable).SetIssuedToken(@ptrCast(*const IChannelCredentials, self), localIssuerAddres, localIssuerBindingType, localIssuerBinding);
}
};}
pub usingnamespace MethodMixin(@This());
};
//--------------------------------------------------------------------------------
// Section: Functions (0)
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (0)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../../zig.zig").unicode_mode) {
.ansi => struct {
},
.wide => struct {
},
.unspecified => if (@import("builtin").is_test) struct {
} else struct {
},
};
//--------------------------------------------------------------------------------
// Section: Imports (6)
//--------------------------------------------------------------------------------
const Guid = @import("../../zig.zig").Guid;
const BOOL = @import("../../foundation.zig").BOOL;
const BSTR = @import("../../foundation.zig").BSTR;
const HRESULT = @import("../../foundation.zig").HRESULT;
const IDispatch = @import("../../system/com.zig").IDispatch;
const VARIANT = @import("../../system/com.zig").VARIANT;
test {
@setEvalBranchQuota(
@import("std").meta.declarations(@This()).len * 3
);
// reference all the pub declarations
if (!@import("builtin").is_test) return;
inline for (@import("std").meta.declarations(@This())) |decl| {
if (decl.is_pub) {
_ = decl;
}
}
}
|
win32/system/com/channel_credentials.zig
|
pub const FILE_DEVICE_SMARTCARD = @as(u32, 49);
pub const GUID_DEVINTERFACE_SMARTCARD_READER = Guid.initString("50dd5230-ba8a-11d1-bf5d-0000f805f530");
pub const SCARD_ATR_LENGTH = @as(u32, 33);
pub const SCARD_PROTOCOL_UNDEFINED = @as(u32, 0);
pub const SCARD_PROTOCOL_T0 = @as(u32, 1);
pub const SCARD_PROTOCOL_T1 = @as(u32, 2);
pub const SCARD_PROTOCOL_RAW = @as(u32, 65536);
pub const SCARD_PROTOCOL_DEFAULT = @as(u32, 2147483648);
pub const SCARD_PROTOCOL_OPTIMAL = @as(u32, 0);
pub const SCARD_POWER_DOWN = @as(u32, 0);
pub const SCARD_COLD_RESET = @as(u32, 1);
pub const SCARD_WARM_RESET = @as(u32, 2);
pub const MAXIMUM_ATTR_STRING_LENGTH = @as(u32, 32);
pub const MAXIMUM_SMARTCARD_READERS = @as(u32, 10);
pub const SCARD_CLASS_VENDOR_INFO = @as(u32, 1);
pub const SCARD_CLASS_COMMUNICATIONS = @as(u32, 2);
pub const SCARD_CLASS_PROTOCOL = @as(u32, 3);
pub const SCARD_CLASS_POWER_MGMT = @as(u32, 4);
pub const SCARD_CLASS_SECURITY = @as(u32, 5);
pub const SCARD_CLASS_MECHANICAL = @as(u32, 6);
pub const SCARD_CLASS_VENDOR_DEFINED = @as(u32, 7);
pub const SCARD_CLASS_IFD_PROTOCOL = @as(u32, 8);
pub const SCARD_CLASS_ICC_STATE = @as(u32, 9);
pub const SCARD_CLASS_PERF = @as(u32, 32766);
pub const SCARD_CLASS_SYSTEM = @as(u32, 32767);
pub const SCARD_T0_HEADER_LENGTH = @as(u32, 7);
pub const SCARD_T0_CMD_LENGTH = @as(u32, 5);
pub const SCARD_T1_PROLOGUE_LENGTH = @as(u32, 3);
pub const SCARD_T1_EPILOGUE_LENGTH = @as(u32, 2);
pub const SCARD_T1_EPILOGUE_LENGTH_LRC = @as(u32, 1);
pub const SCARD_T1_MAX_IFS = @as(u32, 254);
pub const SCARD_UNKNOWN = @as(u32, 0);
pub const SCARD_ABSENT = @as(u32, 1);
pub const SCARD_PRESENT = @as(u32, 2);
pub const SCARD_SWALLOWED = @as(u32, 3);
pub const SCARD_POWERED = @as(u32, 4);
pub const SCARD_NEGOTIABLE = @as(u32, 5);
pub const SCARD_SPECIFIC = @as(u32, 6);
pub const SCARD_READER_SWALLOWS = @as(u32, 1);
pub const SCARD_READER_EJECTS = @as(u32, 2);
pub const SCARD_READER_CONFISCATES = @as(u32, 4);
pub const SCARD_READER_CONTACTLESS = @as(u32, 8);
pub const SCARD_READER_TYPE_SERIAL = @as(u32, 1);
pub const SCARD_READER_TYPE_PARALELL = @as(u32, 2);
pub const SCARD_READER_TYPE_KEYBOARD = @as(u32, 4);
pub const SCARD_READER_TYPE_SCSI = @as(u32, 8);
pub const SCARD_READER_TYPE_IDE = @as(u32, 16);
pub const SCARD_READER_TYPE_USB = @as(u32, 32);
pub const SCARD_READER_TYPE_PCMCIA = @as(u32, 64);
pub const SCARD_READER_TYPE_TPM = @as(u32, 128);
pub const SCARD_READER_TYPE_NFC = @as(u32, 256);
pub const SCARD_READER_TYPE_UICC = @as(u32, 512);
pub const SCARD_READER_TYPE_NGC = @as(u32, 1024);
pub const SCARD_READER_TYPE_EMBEDDEDSE = @as(u32, 2048);
pub const SCARD_READER_TYPE_VENDOR = @as(u32, 240);
pub const STATUS_LOGON_FAILURE = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073741715));
pub const STATUS_WRONG_PASSWORD = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073741718));
pub const STATUS_PASSWORD_EXPIRED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073741711));
pub const STATUS_PASSWORD_MUST_CHANGE = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073741276));
pub const STATUS_ACCESS_DENIED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073741790));
pub const STATUS_DOWNGRADE_DETECTED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073740920));
pub const STATUS_AUTHENTICATION_FIREWALL_FAILED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073740781));
pub const STATUS_ACCOUNT_DISABLED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073741710));
pub const STATUS_ACCOUNT_RESTRICTION = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073741714));
pub const STATUS_ACCOUNT_LOCKED_OUT = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073741260));
pub const STATUS_ACCOUNT_EXPIRED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073741421));
pub const STATUS_LOGON_TYPE_NOT_GRANTED = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073741477));
pub const STATUS_NO_SUCH_LOGON_SESSION = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073741729));
pub const STATUS_NO_SUCH_USER = @import("../zig.zig").typedConst(NTSTATUS, @as(i32, -1073741724));
pub const CRED_MAX_STRING_LENGTH = @as(u32, 256);
pub const CRED_MAX_GENERIC_TARGET_NAME_LENGTH = @as(u32, 32767);
pub const CRED_MAX_TARGETNAME_NAMESPACE_LENGTH = @as(u32, 256);
pub const CRED_MAX_TARGETNAME_ATTRIBUTE_LENGTH = @as(u32, 256);
pub const CRED_MAX_VALUE_SIZE = @as(u32, 256);
pub const CRED_MAX_ATTRIBUTES = @as(u32, 64);
pub const CRED_LOGON_TYPES_MASK = @as(u32, 61440);
pub const CRED_TI_SERVER_FORMAT_UNKNOWN = @as(u32, 1);
pub const CRED_TI_DOMAIN_FORMAT_UNKNOWN = @as(u32, 2);
pub const CRED_TI_ONLY_PASSWORD_REQUIRED = @as(u32, 4);
pub const CRED_TI_USERNAME_TARGET = @as(u32, 8);
pub const CRED_TI_CREATE_EXPLICIT_CRED = @as(u32, 16);
pub const CRED_TI_WORKGROUP_MEMBER = @as(u32, 32);
pub const CRED_TI_DNSTREE_IS_DFS_SERVER = @as(u32, 64);
pub const CRED_TI_VALID_FLAGS = @as(u32, 61567);
pub const CERT_HASH_LENGTH = @as(u32, 20);
pub const CREDUI_MAX_MESSAGE_LENGTH = @as(u32, 1024);
pub const CREDUI_MAX_CAPTION_LENGTH = @as(u32, 128);
pub const CREDUI_MAX_GENERIC_TARGET_LENGTH = @as(u32, 32767);
pub const CREDUIWIN_IGNORE_CLOUDAUTHORITY_NAME = @as(u32, 262144);
pub const CREDUIWIN_DOWNLEVEL_HELLO_AS_SMART_CARD = @as(u32, 2147483648);
pub const CRED_PRESERVE_CREDENTIAL_BLOB = @as(u32, 1);
pub const CRED_CACHE_TARGET_INFORMATION = @as(u32, 1);
pub const CRED_ALLOW_NAME_RESOLUTION = @as(u32, 1);
pub const CRED_PROTECT_AS_SELF = @as(u32, 1);
pub const CRED_PROTECT_TO_SYSTEM = @as(u32, 2);
pub const CRED_UNPROTECT_AS_SELF = @as(u32, 1);
pub const CRED_UNPROTECT_ALLOW_TO_SYSTEM = @as(u32, 2);
pub const SCARD_SCOPE_TERMINAL = @as(u32, 1);
pub const SCARD_PROVIDER_PRIMARY = @as(u32, 1);
pub const SCARD_PROVIDER_CSP = @as(u32, 2);
pub const SCARD_PROVIDER_KSP = @as(u32, 3);
pub const SCARD_STATE_UNPOWERED = @as(u32, 1024);
pub const SCARD_SHARE_EXCLUSIVE = @as(u32, 1);
pub const SCARD_SHARE_SHARED = @as(u32, 2);
pub const SCARD_SHARE_DIRECT = @as(u32, 3);
pub const SCARD_LEAVE_CARD = @as(u32, 0);
pub const SCARD_RESET_CARD = @as(u32, 1);
pub const SCARD_UNPOWER_CARD = @as(u32, 2);
pub const SCARD_EJECT_CARD = @as(u32, 3);
pub const SC_DLG_MINIMAL_UI = @as(u32, 1);
pub const SC_DLG_NO_UI = @as(u32, 2);
pub const SC_DLG_FORCE_UI = @as(u32, 4);
pub const SCERR_NOCARDNAME = @as(u32, 16384);
pub const SCERR_NOGUIDS = @as(u32, 32768);
pub const SCARD_AUDIT_CHV_FAILURE = @as(u32, 0);
pub const SCARD_AUDIT_CHV_SUCCESS = @as(u32, 1);
pub const CREDSSP_SERVER_AUTH_NEGOTIATE = @as(u32, 1);
pub const CREDSSP_SERVER_AUTH_CERTIFICATE = @as(u32, 2);
pub const CREDSSP_SERVER_AUTH_LOOPBACK = @as(u32, 4);
pub const SECPKG_ALT_ATTR = @as(u32, 2147483648);
pub const SECPKG_ATTR_C_FULL_IDENT_TOKEN = @as(u32, 2147483781);
pub const CREDSSP_CRED_EX_VERSION = @as(u32, 0);
pub const CREDSSP_FLAG_REDIRECT = @as(u32, 1);
//--------------------------------------------------------------------------------
// Section: Types (50)
//--------------------------------------------------------------------------------
pub const CRED_FLAGS = enum(u32) {
PASSWORD_FOR_CERT = 1,
PROMPT_NOW = 2,
USERNAME_TARGET = 4,
OWF_CRED_BLOB = 8,
REQUIRE_CONFIRMATION = 16,
WILDCARD_MATCH = 32,
VSM_PROTECTED = 64,
NGC_CERT = 128,
VALID_FLAGS = 61695,
VALID_INPUT_FLAGS = 61599,
_,
pub fn initFlags(o: struct {
PASSWORD_FOR_CERT: u1 = 0,
PROMPT_NOW: u1 = 0,
USERNAME_TARGET: u1 = 0,
OWF_CRED_BLOB: u1 = 0,
REQUIRE_CONFIRMATION: u1 = 0,
WILDCARD_MATCH: u1 = 0,
VSM_PROTECTED: u1 = 0,
NGC_CERT: u1 = 0,
VALID_FLAGS: u1 = 0,
VALID_INPUT_FLAGS: u1 = 0,
}) CRED_FLAGS {
return @intToEnum(CRED_FLAGS,
(if (o.PASSWORD_FOR_CERT == 1) @enumToInt(CRED_FLAGS.PASSWORD_FOR_CERT) else 0)
| (if (o.PROMPT_NOW == 1) @enumToInt(CRED_FLAGS.PROMPT_NOW) else 0)
| (if (o.USERNAME_TARGET == 1) @enumToInt(CRED_FLAGS.USERNAME_TARGET) else 0)
| (if (o.OWF_CRED_BLOB == 1) @enumToInt(CRED_FLAGS.OWF_CRED_BLOB) else 0)
| (if (o.REQUIRE_CONFIRMATION == 1) @enumToInt(CRED_FLAGS.REQUIRE_CONFIRMATION) else 0)
| (if (o.WILDCARD_MATCH == 1) @enumToInt(CRED_FLAGS.WILDCARD_MATCH) else 0)
| (if (o.VSM_PROTECTED == 1) @enumToInt(CRED_FLAGS.VSM_PROTECTED) else 0)
| (if (o.NGC_CERT == 1) @enumToInt(CRED_FLAGS.NGC_CERT) else 0)
| (if (o.VALID_FLAGS == 1) @enumToInt(CRED_FLAGS.VALID_FLAGS) else 0)
| (if (o.VALID_INPUT_FLAGS == 1) @enumToInt(CRED_FLAGS.VALID_INPUT_FLAGS) else 0)
);
}
};
pub const CRED_FLAGS_PASSWORD_FOR_CERT = CRED_FLAGS.PASSWORD_FOR_CERT;
pub const CRED_FLAGS_PROMPT_NOW = CRED_FLAGS.PROMPT_NOW;
pub const CRED_FLAGS_USERNAME_TARGET = CRED_FLAGS.USERNAME_TARGET;
pub const CRED_FLAGS_OWF_CRED_BLOB = CRED_FLAGS.OWF_CRED_BLOB;
pub const CRED_FLAGS_REQUIRE_CONFIRMATION = CRED_FLAGS.REQUIRE_CONFIRMATION;
pub const CRED_FLAGS_WILDCARD_MATCH = CRED_FLAGS.WILDCARD_MATCH;
pub const CRED_FLAGS_VSM_PROTECTED = CRED_FLAGS.VSM_PROTECTED;
pub const CRED_FLAGS_NGC_CERT = CRED_FLAGS.NGC_CERT;
pub const CRED_FLAGS_VALID_FLAGS = CRED_FLAGS.VALID_FLAGS;
pub const CRED_FLAGS_VALID_INPUT_FLAGS = CRED_FLAGS.VALID_INPUT_FLAGS;
pub const CRED_TYPE = enum(u32) {
GENERIC = 1,
DOMAIN_PASSWORD = 2,
DOMAIN_CERTIFICATE = 3,
DOMAIN_VISIBLE_PASSWORD = 4,
GENERIC_CERTIFICATE = 5,
DOMAIN_EXTENDED = 6,
MAXIMUM = 7,
MAXIMUM_EX = 1007,
};
pub const CRED_TYPE_GENERIC = CRED_TYPE.GENERIC;
pub const CRED_TYPE_DOMAIN_PASSWORD = CRED_TYPE.DOMAIN_PASSWORD;
pub const CRED_TYPE_DOMAIN_CERTIFICATE = CRED_TYPE.DOMAIN_CERTIFICATE;
pub const CRED_TYPE_DOMAIN_VISIBLE_PASSWORD = CRED_TYPE.DOMAIN_VISIBLE_PASSWORD;
pub const CRED_TYPE_GENERIC_CERTIFICATE = CRED_TYPE.GENERIC_CERTIFICATE;
pub const CRED_TYPE_DOMAIN_EXTENDED = CRED_TYPE.DOMAIN_EXTENDED;
pub const CRED_TYPE_MAXIMUM = CRED_TYPE.MAXIMUM;
pub const CRED_TYPE_MAXIMUM_EX = CRED_TYPE.MAXIMUM_EX;
pub const CRED_PERSIST = enum(u32) {
NONE = 0,
SESSION = 1,
LOCAL_MACHINE = 2,
ENTERPRISE = 3,
};
pub const CRED_PERSIST_NONE = CRED_PERSIST.NONE;
pub const CRED_PERSIST_SESSION = CRED_PERSIST.SESSION;
pub const CRED_PERSIST_LOCAL_MACHINE = CRED_PERSIST.LOCAL_MACHINE;
pub const CRED_PERSIST_ENTERPRISE = CRED_PERSIST.ENTERPRISE;
pub const CREDUI_FLAGS = enum(u32) {
ALWAYS_SHOW_UI = 128,
COMPLETE_USERNAME = 2048,
DO_NOT_PERSIST = 2,
EXCLUDE_CERTIFICATES = 8,
EXPECT_CONFIRMATION = 131072,
GENERIC_CREDENTIALS = 262144,
INCORRECT_PASSWORD = 1,
KEEP_USERNAME = 1048576,
PASSWORD_ONLY_OK = 512,
PERSIST = 4096,
REQUEST_ADMINISTRATOR = 4,
REQUIRE_CERTIFICATE = 16,
REQUIRE_SMARTCARD = 256,
SERVER_CREDENTIAL = 16384,
SHOW_SAVE_CHECK_BOX = 64,
USERNAME_TARGET_CREDENTIALS = 524288,
VALIDATE_USERNAME = 1024,
_,
pub fn initFlags(o: struct {
ALWAYS_SHOW_UI: u1 = 0,
COMPLETE_USERNAME: u1 = 0,
DO_NOT_PERSIST: u1 = 0,
EXCLUDE_CERTIFICATES: u1 = 0,
EXPECT_CONFIRMATION: u1 = 0,
GENERIC_CREDENTIALS: u1 = 0,
INCORRECT_PASSWORD: u1 = 0,
KEEP_USERNAME: u1 = 0,
PASSWORD_ONLY_OK: u1 = 0,
PERSIST: u1 = 0,
REQUEST_ADMINISTRATOR: u1 = 0,
REQUIRE_CERTIFICATE: u1 = 0,
REQUIRE_SMARTCARD: u1 = 0,
SERVER_CREDENTIAL: u1 = 0,
SHOW_SAVE_CHECK_BOX: u1 = 0,
USERNAME_TARGET_CREDENTIALS: u1 = 0,
VALIDATE_USERNAME: u1 = 0,
}) CREDUI_FLAGS {
return @intToEnum(CREDUI_FLAGS,
(if (o.ALWAYS_SHOW_UI == 1) @enumToInt(CREDUI_FLAGS.ALWAYS_SHOW_UI) else 0)
| (if (o.COMPLETE_USERNAME == 1) @enumToInt(CREDUI_FLAGS.COMPLETE_USERNAME) else 0)
| (if (o.DO_NOT_PERSIST == 1) @enumToInt(CREDUI_FLAGS.DO_NOT_PERSIST) else 0)
| (if (o.EXCLUDE_CERTIFICATES == 1) @enumToInt(CREDUI_FLAGS.EXCLUDE_CERTIFICATES) else 0)
| (if (o.EXPECT_CONFIRMATION == 1) @enumToInt(CREDUI_FLAGS.EXPECT_CONFIRMATION) else 0)
| (if (o.GENERIC_CREDENTIALS == 1) @enumToInt(CREDUI_FLAGS.GENERIC_CREDENTIALS) else 0)
| (if (o.INCORRECT_PASSWORD == 1) @enumToInt(CREDUI_FLAGS.INCORRECT_PASSWORD) else 0)
| (if (o.KEEP_USERNAME == 1) @enumToInt(CREDUI_FLAGS.KEEP_USERNAME) else 0)
| (if (o.PASSWORD_ONLY_OK == 1) @enumToInt(CREDUI_FLAGS.PASSWORD_ONLY_OK) else 0)
| (if (o.PERSIST == 1) @enumToInt(CREDUI_FLAGS.PERSIST) else 0)
| (if (o.REQUEST_ADMINISTRATOR == 1) @enumToInt(CREDUI_FLAGS.REQUEST_ADMINISTRATOR) else 0)
| (if (o.REQUIRE_CERTIFICATE == 1) @enumToInt(CREDUI_FLAGS.REQUIRE_CERTIFICATE) else 0)
| (if (o.REQUIRE_SMARTCARD == 1) @enumToInt(CREDUI_FLAGS.REQUIRE_SMARTCARD) else 0)
| (if (o.SERVER_CREDENTIAL == 1) @enumToInt(CREDUI_FLAGS.SERVER_CREDENTIAL) else 0)
| (if (o.SHOW_SAVE_CHECK_BOX == 1) @enumToInt(CREDUI_FLAGS.SHOW_SAVE_CHECK_BOX) else 0)
| (if (o.USERNAME_TARGET_CREDENTIALS == 1) @enumToInt(CREDUI_FLAGS.USERNAME_TARGET_CREDENTIALS) else 0)
| (if (o.VALIDATE_USERNAME == 1) @enumToInt(CREDUI_FLAGS.VALIDATE_USERNAME) else 0)
);
}
};
pub const CREDUI_FLAGS_ALWAYS_SHOW_UI = CREDUI_FLAGS.ALWAYS_SHOW_UI;
pub const CREDUI_FLAGS_COMPLETE_USERNAME = CREDUI_FLAGS.COMPLETE_USERNAME;
pub const CREDUI_FLAGS_DO_NOT_PERSIST = CREDUI_FLAGS.DO_NOT_PERSIST;
pub const CREDUI_FLAGS_EXCLUDE_CERTIFICATES = CREDUI_FLAGS.EXCLUDE_CERTIFICATES;
pub const CREDUI_FLAGS_EXPECT_CONFIRMATION = CREDUI_FLAGS.EXPECT_CONFIRMATION;
pub const CREDUI_FLAGS_GENERIC_CREDENTIALS = CREDUI_FLAGS.GENERIC_CREDENTIALS;
pub const CREDUI_FLAGS_INCORRECT_PASSWORD = CREDUI_FLAGS.INCORRECT_PASSWORD;
pub const CREDUI_FLAGS_KEEP_USERNAME = CREDUI_FLAGS.KEEP_USERNAME;
pub const CREDUI_FLAGS_PASSWORD_ONLY_OK = CREDUI_FLAGS.PASSWORD_ONLY_OK;
pub const CREDUI_FLAGS_PERSIST = CREDUI_FLAGS.PERSIST;
pub const CREDUI_FLAGS_REQUEST_ADMINISTRATOR = CREDUI_FLAGS.REQUEST_ADMINISTRATOR;
pub const CREDUI_FLAGS_REQUIRE_CERTIFICATE = CREDUI_FLAGS.REQUIRE_CERTIFICATE;
pub const CREDUI_FLAGS_REQUIRE_SMARTCARD = CREDUI_FLAGS.REQUIRE_SMARTCARD;
pub const CREDUI_FLAGS_SERVER_CREDENTIAL = CREDUI_FLAGS.SERVER_CREDENTIAL;
pub const CREDUI_FLAGS_SHOW_SAVE_CHECK_BOX = CREDUI_FLAGS.SHOW_SAVE_CHECK_BOX;
pub const CREDUI_FLAGS_USERNAME_TARGET_CREDENTIALS = CREDUI_FLAGS.USERNAME_TARGET_CREDENTIALS;
pub const CREDUI_FLAGS_VALIDATE_USERNAME = CREDUI_FLAGS.VALIDATE_USERNAME;
pub const SCARD_SCOPE = enum(u32) {
USER = 0,
SYSTEM = 2,
};
pub const SCARD_SCOPE_USER = SCARD_SCOPE.USER;
pub const SCARD_SCOPE_SYSTEM = SCARD_SCOPE.SYSTEM;
pub const CRED_ENUMERATE_FLAGS = enum(u32) {
S = 1,
_,
pub fn initFlags(o: struct {
S: u1 = 0,
}) CRED_ENUMERATE_FLAGS {
return @intToEnum(CRED_ENUMERATE_FLAGS,
(if (o.S == 1) @enumToInt(CRED_ENUMERATE_FLAGS.S) else 0)
);
}
};
pub const CRED_ENUMERATE_ALL_CREDENTIALS = CRED_ENUMERATE_FLAGS.S;
pub const CREDUIWIN_FLAGS = enum(u32) {
GENERIC = 1,
CHECKBOX = 2,
AUTHPACKAGE_ONLY = 16,
IN_CRED_ONLY = 32,
ENUMERATE_ADMINS = 256,
ENUMERATE_CURRENT_USER = 512,
SECURE_PROMPT = 4096,
PREPROMPTING = 8192,
PACK_32_WOW = 268435456,
_,
pub fn initFlags(o: struct {
GENERIC: u1 = 0,
CHECKBOX: u1 = 0,
AUTHPACKAGE_ONLY: u1 = 0,
IN_CRED_ONLY: u1 = 0,
ENUMERATE_ADMINS: u1 = 0,
ENUMERATE_CURRENT_USER: u1 = 0,
SECURE_PROMPT: u1 = 0,
PREPROMPTING: u1 = 0,
PACK_32_WOW: u1 = 0,
}) CREDUIWIN_FLAGS {
return @intToEnum(CREDUIWIN_FLAGS,
(if (o.GENERIC == 1) @enumToInt(CREDUIWIN_FLAGS.GENERIC) else 0)
| (if (o.CHECKBOX == 1) @enumToInt(CREDUIWIN_FLAGS.CHECKBOX) else 0)
| (if (o.AUTHPACKAGE_ONLY == 1) @enumToInt(CREDUIWIN_FLAGS.AUTHPACKAGE_ONLY) else 0)
| (if (o.IN_CRED_ONLY == 1) @enumToInt(CREDUIWIN_FLAGS.IN_CRED_ONLY) else 0)
| (if (o.ENUMERATE_ADMINS == 1) @enumToInt(CREDUIWIN_FLAGS.ENUMERATE_ADMINS) else 0)
| (if (o.ENUMERATE_CURRENT_USER == 1) @enumToInt(CREDUIWIN_FLAGS.ENUMERATE_CURRENT_USER) else 0)
| (if (o.SECURE_PROMPT == 1) @enumToInt(CREDUIWIN_FLAGS.SECURE_PROMPT) else 0)
| (if (o.PREPROMPTING == 1) @enumToInt(CREDUIWIN_FLAGS.PREPROMPTING) else 0)
| (if (o.PACK_32_WOW == 1) @enumToInt(CREDUIWIN_FLAGS.PACK_32_WOW) else 0)
);
}
};
pub const CREDUIWIN_GENERIC = CREDUIWIN_FLAGS.GENERIC;
pub const CREDUIWIN_CHECKBOX = CREDUIWIN_FLAGS.CHECKBOX;
pub const CREDUIWIN_AUTHPACKAGE_ONLY = CREDUIWIN_FLAGS.AUTHPACKAGE_ONLY;
pub const CREDUIWIN_IN_CRED_ONLY = CREDUIWIN_FLAGS.IN_CRED_ONLY;
pub const CREDUIWIN_ENUMERATE_ADMINS = CREDUIWIN_FLAGS.ENUMERATE_ADMINS;
pub const CREDUIWIN_ENUMERATE_CURRENT_USER = CREDUIWIN_FLAGS.ENUMERATE_CURRENT_USER;
pub const CREDUIWIN_SECURE_PROMPT = CREDUIWIN_FLAGS.SECURE_PROMPT;
pub const CREDUIWIN_PREPROMPTING = CREDUIWIN_FLAGS.PREPROMPTING;
pub const CREDUIWIN_PACK_32_WOW = CREDUIWIN_FLAGS.PACK_32_WOW;
pub const SCARD_STATE = enum(u32) {
UNAWARE = 0,
IGNORE = 1,
UNAVAILABLE = 8,
EMPTY = 16,
PRESENT = 32,
ATRMATCH = 64,
EXCLUSIVE = 128,
INUSE = 256,
MUTE = 512,
CHANGED = 2,
UNKNOWN = 4,
};
pub const SCARD_STATE_UNAWARE = SCARD_STATE.UNAWARE;
pub const SCARD_STATE_IGNORE = SCARD_STATE.IGNORE;
pub const SCARD_STATE_UNAVAILABLE = SCARD_STATE.UNAVAILABLE;
pub const SCARD_STATE_EMPTY = SCARD_STATE.EMPTY;
pub const SCARD_STATE_PRESENT = SCARD_STATE.PRESENT;
pub const SCARD_STATE_ATRMATCH = SCARD_STATE.ATRMATCH;
pub const SCARD_STATE_EXCLUSIVE = SCARD_STATE.EXCLUSIVE;
pub const SCARD_STATE_INUSE = SCARD_STATE.INUSE;
pub const SCARD_STATE_MUTE = SCARD_STATE.MUTE;
pub const SCARD_STATE_CHANGED = SCARD_STATE.CHANGED;
pub const SCARD_STATE_UNKNOWN = SCARD_STATE.UNKNOWN;
pub const CRED_PACK_FLAGS = enum(u32) {
PROTECTED_CREDENTIALS = 1,
WOW_BUFFER = 2,
GENERIC_CREDENTIALS = 4,
ID_PROVIDER_CREDENTIALS = 8,
_,
pub fn initFlags(o: struct {
PROTECTED_CREDENTIALS: u1 = 0,
WOW_BUFFER: u1 = 0,
GENERIC_CREDENTIALS: u1 = 0,
ID_PROVIDER_CREDENTIALS: u1 = 0,
}) CRED_PACK_FLAGS {
return @intToEnum(CRED_PACK_FLAGS,
(if (o.PROTECTED_CREDENTIALS == 1) @enumToInt(CRED_PACK_FLAGS.PROTECTED_CREDENTIALS) else 0)
| (if (o.WOW_BUFFER == 1) @enumToInt(CRED_PACK_FLAGS.WOW_BUFFER) else 0)
| (if (o.GENERIC_CREDENTIALS == 1) @enumToInt(CRED_PACK_FLAGS.GENERIC_CREDENTIALS) else 0)
| (if (o.ID_PROVIDER_CREDENTIALS == 1) @enumToInt(CRED_PACK_FLAGS.ID_PROVIDER_CREDENTIALS) else 0)
);
}
};
pub const CRED_PACK_PROTECTED_CREDENTIALS = CRED_PACK_FLAGS.PROTECTED_CREDENTIALS;
pub const CRED_PACK_WOW_BUFFER = CRED_PACK_FLAGS.WOW_BUFFER;
pub const CRED_PACK_GENERIC_CREDENTIALS = CRED_PACK_FLAGS.GENERIC_CREDENTIALS;
pub const CRED_PACK_ID_PROVIDER_CREDENTIALS = CRED_PACK_FLAGS.ID_PROVIDER_CREDENTIALS;
pub const KeyCredentialManagerOperationErrorStates = enum(u32) {
None = 0,
DeviceJoinFailure = 1,
TokenFailure = 2,
CertificateFailure = 4,
RemoteSessionFailure = 8,
PolicyFailure = 16,
HardwareFailure = 32,
PinExistsFailure = 64,
_,
pub fn initFlags(o: struct {
None: u1 = 0,
DeviceJoinFailure: u1 = 0,
TokenFailure: u1 = 0,
CertificateFailure: u1 = 0,
RemoteSessionFailure: u1 = 0,
PolicyFailure: u1 = 0,
HardwareFailure: u1 = 0,
PinExistsFailure: u1 = 0,
}) KeyCredentialManagerOperationErrorStates {
return @intToEnum(KeyCredentialManagerOperationErrorStates,
(if (o.None == 1) @enumToInt(KeyCredentialManagerOperationErrorStates.None) else 0)
| (if (o.DeviceJoinFailure == 1) @enumToInt(KeyCredentialManagerOperationErrorStates.DeviceJoinFailure) else 0)
| (if (o.TokenFailure == 1) @enumToInt(KeyCredentialManagerOperationErrorStates.TokenFailure) else 0)
| (if (o.CertificateFailure == 1) @enumToInt(KeyCredentialManagerOperationErrorStates.CertificateFailure) else 0)
| (if (o.RemoteSessionFailure == 1) @enumToInt(KeyCredentialManagerOperationErrorStates.RemoteSessionFailure) else 0)
| (if (o.PolicyFailure == 1) @enumToInt(KeyCredentialManagerOperationErrorStates.PolicyFailure) else 0)
| (if (o.HardwareFailure == 1) @enumToInt(KeyCredentialManagerOperationErrorStates.HardwareFailure) else 0)
| (if (o.PinExistsFailure == 1) @enumToInt(KeyCredentialManagerOperationErrorStates.PinExistsFailure) else 0)
);
}
};
pub const KeyCredentialManagerOperationErrorStateNone = KeyCredentialManagerOperationErrorStates.None;
pub const KeyCredentialManagerOperationErrorStateDeviceJoinFailure = KeyCredentialManagerOperationErrorStates.DeviceJoinFailure;
pub const KeyCredentialManagerOperationErrorStateTokenFailure = KeyCredentialManagerOperationErrorStates.TokenFailure;
pub const KeyCredentialManagerOperationErrorStateCertificateFailure = KeyCredentialManagerOperationErrorStates.CertificateFailure;
pub const KeyCredentialManagerOperationErrorStateRemoteSessionFailure = KeyCredentialManagerOperationErrorStates.RemoteSessionFailure;
pub const KeyCredentialManagerOperationErrorStatePolicyFailure = KeyCredentialManagerOperationErrorStates.PolicyFailure;
pub const KeyCredentialManagerOperationErrorStateHardwareFailure = KeyCredentialManagerOperationErrorStates.HardwareFailure;
pub const KeyCredentialManagerOperationErrorStatePinExistsFailure = KeyCredentialManagerOperationErrorStates.PinExistsFailure;
pub const KeyCredentialManagerOperationType = enum(i32) {
rovisioning = 0,
inChange = 1,
inReset = 2,
};
pub const KeyCredentialManagerProvisioning = KeyCredentialManagerOperationType.rovisioning;
pub const KeyCredentialManagerPinChange = KeyCredentialManagerOperationType.inChange;
pub const KeyCredentialManagerPinReset = KeyCredentialManagerOperationType.inReset;
pub const KeyCredentialManagerInfo = extern struct {
containerId: Guid,
};
pub const SecHandle = extern struct {
dwLower: usize,
dwUpper: usize,
};
pub const CREDENTIAL_ATTRIBUTEA = extern struct {
Keyword: ?PSTR,
Flags: u32,
ValueSize: u32,
Value: ?*u8,
};
pub const CREDENTIAL_ATTRIBUTEW = extern struct {
Keyword: ?PWSTR,
Flags: u32,
ValueSize: u32,
Value: ?*u8,
};
pub const CREDENTIALA = extern struct {
Flags: CRED_FLAGS,
Type: CRED_TYPE,
TargetName: ?PSTR,
Comment: ?PSTR,
LastWritten: FILETIME,
CredentialBlobSize: u32,
CredentialBlob: ?*u8,
Persist: CRED_PERSIST,
AttributeCount: u32,
Attributes: ?*CREDENTIAL_ATTRIBUTEA,
TargetAlias: ?PSTR,
UserName: ?PSTR,
};
pub const CREDENTIALW = extern struct {
Flags: CRED_FLAGS,
Type: CRED_TYPE,
TargetName: ?PWSTR,
Comment: ?PWSTR,
LastWritten: FILETIME,
CredentialBlobSize: u32,
CredentialBlob: ?*u8,
Persist: CRED_PERSIST,
AttributeCount: u32,
Attributes: ?*CREDENTIAL_ATTRIBUTEW,
TargetAlias: ?PWSTR,
UserName: ?PWSTR,
};
pub const CREDENTIAL_TARGET_INFORMATIONA = extern struct {
TargetName: ?PSTR,
NetbiosServerName: ?PSTR,
DnsServerName: ?PSTR,
NetbiosDomainName: ?PSTR,
DnsDomainName: ?PSTR,
DnsTreeName: ?PSTR,
PackageName: ?PSTR,
Flags: u32,
CredTypeCount: u32,
CredTypes: ?*u32,
};
pub const CREDENTIAL_TARGET_INFORMATIONW = extern struct {
TargetName: ?PWSTR,
NetbiosServerName: ?PWSTR,
DnsServerName: ?PWSTR,
NetbiosDomainName: ?PWSTR,
DnsDomainName: ?PWSTR,
DnsTreeName: ?PWSTR,
PackageName: ?PWSTR,
Flags: u32,
CredTypeCount: u32,
CredTypes: ?*u32,
};
pub const CERT_CREDENTIAL_INFO = extern struct {
cbSize: u32,
rgbHashOfCert: [20]u8,
};
pub const USERNAME_TARGET_CREDENTIAL_INFO = extern struct {
UserName: ?PWSTR,
};
pub const BINARY_BLOB_CREDENTIAL_INFO = extern struct {
cbBlob: u32,
pbBlob: ?*u8,
};
pub const CRED_MARSHAL_TYPE = enum(i32) {
CertCredential = 1,
UsernameTargetCredential = 2,
BinaryBlobCredential = 3,
UsernameForPackedCredentials = 4,
BinaryBlobForSystem = 5,
};
pub const CertCredential = CRED_MARSHAL_TYPE.CertCredential;
pub const UsernameTargetCredential = CRED_MARSHAL_TYPE.UsernameTargetCredential;
pub const BinaryBlobCredential = CRED_MARSHAL_TYPE.BinaryBlobCredential;
pub const UsernameForPackedCredentials = CRED_MARSHAL_TYPE.UsernameForPackedCredentials;
pub const BinaryBlobForSystem = CRED_MARSHAL_TYPE.BinaryBlobForSystem;
pub const CRED_PROTECTION_TYPE = enum(i32) {
Unprotected = 0,
UserProtection = 1,
TrustedProtection = 2,
ForSystemProtection = 3,
};
pub const CredUnprotected = CRED_PROTECTION_TYPE.Unprotected;
pub const CredUserProtection = CRED_PROTECTION_TYPE.UserProtection;
pub const CredTrustedProtection = CRED_PROTECTION_TYPE.TrustedProtection;
pub const CredForSystemProtection = CRED_PROTECTION_TYPE.ForSystemProtection;
pub const CREDUI_INFOA = extern struct {
cbSize: u32,
hwndParent: ?HWND,
pszMessageText: ?[*:0]const u8,
pszCaptionText: ?[*:0]const u8,
hbmBanner: ?HBITMAP,
};
pub const CREDUI_INFOW = extern struct {
cbSize: u32,
hwndParent: ?HWND,
pszMessageText: ?[*:0]const u16,
pszCaptionText: ?[*:0]const u16,
hbmBanner: ?HBITMAP,
};
pub const SCARD_IO_REQUEST = extern struct {
dwProtocol: u32,
cbPciLength: u32,
};
pub const SCARD_T0_COMMAND = extern struct {
bCla: u8,
bIns: u8,
bP1: u8,
bP2: u8,
bP3: u8,
};
pub const SCARD_T0_REQUEST = extern struct {
ioRequest: SCARD_IO_REQUEST,
bSw1: u8,
bSw2: u8,
Anonymous: extern union {
CmdBytes: SCARD_T0_COMMAND,
rgbHeader: [5]u8,
},
};
pub const SCARD_T1_REQUEST = extern struct {
ioRequest: SCARD_IO_REQUEST,
};
pub const SCARD_READERSTATEA = extern struct {
szReader: ?[*:0]const u8,
pvUserData: ?*anyopaque,
dwCurrentState: SCARD_STATE,
dwEventState: SCARD_STATE,
cbAtr: u32,
rgbAtr: [36]u8,
};
pub const SCARD_READERSTATEW = extern struct {
szReader: ?[*:0]const u16,
pvUserData: ?*anyopaque,
dwCurrentState: SCARD_STATE,
dwEventState: SCARD_STATE,
cbAtr: u32,
rgbAtr: [36]u8,
};
pub const SCARD_ATRMASK = extern struct {
cbAtr: u32,
rgbAtr: [36]u8,
rgbMask: [36]u8,
};
pub const LPOCNCONNPROCA = fn(
param0: usize,
param1: ?PSTR,
param2: ?PSTR,
param3: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) usize;
pub const LPOCNCONNPROCW = fn(
param0: usize,
param1: ?PWSTR,
param2: ?PWSTR,
param3: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) usize;
pub const LPOCNCHKPROC = fn(
param0: usize,
param1: usize,
param2: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const LPOCNDSCPROC = fn(
param0: usize,
param1: usize,
param2: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) void;
pub const OPENCARD_SEARCH_CRITERIAA = extern struct {
dwStructSize: u32,
lpstrGroupNames: ?PSTR,
nMaxGroupNames: u32,
rgguidInterfaces: ?*const Guid,
cguidInterfaces: u32,
lpstrCardNames: ?PSTR,
nMaxCardNames: u32,
lpfnCheck: ?LPOCNCHKPROC,
lpfnConnect: ?LPOCNCONNPROCA,
lpfnDisconnect: ?LPOCNDSCPROC,
pvUserData: ?*anyopaque,
dwShareMode: u32,
dwPreferredProtocols: u32,
};
pub const OPENCARD_SEARCH_CRITERIAW = extern struct {
dwStructSize: u32,
lpstrGroupNames: ?PWSTR,
nMaxGroupNames: u32,
rgguidInterfaces: ?*const Guid,
cguidInterfaces: u32,
lpstrCardNames: ?PWSTR,
nMaxCardNames: u32,
lpfnCheck: ?LPOCNCHKPROC,
lpfnConnect: ?LPOCNCONNPROCW,
lpfnDisconnect: ?LPOCNDSCPROC,
pvUserData: ?*anyopaque,
dwShareMode: u32,
dwPreferredProtocols: u32,
};
pub const OPENCARDNAME_EXA = extern struct {
dwStructSize: u32,
hSCardContext: usize,
hwndOwner: ?HWND,
dwFlags: u32,
lpstrTitle: ?[*:0]const u8,
lpstrSearchDesc: ?[*:0]const u8,
hIcon: ?HICON,
pOpenCardSearchCriteria: ?*OPENCARD_SEARCH_CRITERIAA,
lpfnConnect: ?LPOCNCONNPROCA,
pvUserData: ?*anyopaque,
dwShareMode: u32,
dwPreferredProtocols: u32,
lpstrRdr: ?PSTR,
nMaxRdr: u32,
lpstrCard: ?PSTR,
nMaxCard: u32,
dwActiveProtocol: u32,
hCardHandle: usize,
};
pub const OPENCARDNAME_EXW = extern struct {
dwStructSize: u32,
hSCardContext: usize,
hwndOwner: ?HWND,
dwFlags: u32,
lpstrTitle: ?[*:0]const u16,
lpstrSearchDesc: ?[*:0]const u16,
hIcon: ?HICON,
pOpenCardSearchCriteria: ?*OPENCARD_SEARCH_CRITERIAW,
lpfnConnect: ?LPOCNCONNPROCW,
pvUserData: ?*anyopaque,
dwShareMode: u32,
dwPreferredProtocols: u32,
lpstrRdr: ?PWSTR,
nMaxRdr: u32,
lpstrCard: ?PWSTR,
nMaxCard: u32,
dwActiveProtocol: u32,
hCardHandle: usize,
};
pub const READER_SEL_REQUEST_MATCH_TYPE = enum(i32) {
READER_AND_CONTAINER = 1,
SERIAL_NUMBER = 2,
ALL_CARDS = 3,
};
pub const RSR_MATCH_TYPE_READER_AND_CONTAINER = READER_SEL_REQUEST_MATCH_TYPE.READER_AND_CONTAINER;
pub const RSR_MATCH_TYPE_SERIAL_NUMBER = READER_SEL_REQUEST_MATCH_TYPE.SERIAL_NUMBER;
pub const RSR_MATCH_TYPE_ALL_CARDS = READER_SEL_REQUEST_MATCH_TYPE.ALL_CARDS;
pub const READER_SEL_REQUEST = extern struct {
dwShareMode: u32,
dwPreferredProtocols: u32,
MatchType: READER_SEL_REQUEST_MATCH_TYPE,
Anonymous: extern union {
ReaderAndContainerParameter: extern struct {
cbReaderNameOffset: u32,
cchReaderNameLength: u32,
cbContainerNameOffset: u32,
cchContainerNameLength: u32,
dwDesiredCardModuleVersion: u32,
dwCspFlags: u32,
},
SerialNumberParameter: extern struct {
cbSerialNumberOffset: u32,
cbSerialNumberLength: u32,
dwDesiredCardModuleVersion: u32,
},
},
};
pub const READER_SEL_RESPONSE = extern struct {
cbReaderNameOffset: u32,
cchReaderNameLength: u32,
cbCardNameOffset: u32,
cchCardNameLength: u32,
};
pub const OPENCARDNAMEA = extern struct {
dwStructSize: u32,
hwndOwner: ?HWND,
hSCardContext: usize,
lpstrGroupNames: ?PSTR,
nMaxGroupNames: u32,
lpstrCardNames: ?PSTR,
nMaxCardNames: u32,
rgguidInterfaces: ?*const Guid,
cguidInterfaces: u32,
lpstrRdr: ?PSTR,
nMaxRdr: u32,
lpstrCard: ?PSTR,
nMaxCard: u32,
lpstrTitle: ?[*:0]const u8,
dwFlags: u32,
pvUserData: ?*anyopaque,
dwShareMode: u32,
dwPreferredProtocols: u32,
dwActiveProtocol: u32,
lpfnConnect: ?LPOCNCONNPROCA,
lpfnCheck: ?LPOCNCHKPROC,
lpfnDisconnect: ?LPOCNDSCPROC,
hCardHandle: usize,
};
pub const OPENCARDNAMEW = extern struct {
dwStructSize: u32,
hwndOwner: ?HWND,
hSCardContext: usize,
lpstrGroupNames: ?PWSTR,
nMaxGroupNames: u32,
lpstrCardNames: ?PWSTR,
nMaxCardNames: u32,
rgguidInterfaces: ?*const Guid,
cguidInterfaces: u32,
lpstrRdr: ?PWSTR,
nMaxRdr: u32,
lpstrCard: ?PWSTR,
nMaxCard: u32,
lpstrTitle: ?[*:0]const u16,
dwFlags: u32,
pvUserData: ?*anyopaque,
dwShareMode: u32,
dwPreferredProtocols: u32,
dwActiveProtocol: u32,
lpfnConnect: ?LPOCNCONNPROCW,
lpfnCheck: ?LPOCNCHKPROC,
lpfnDisconnect: ?LPOCNDSCPROC,
hCardHandle: usize,
};
pub const SecPkgContext_ClientCreds = extern struct {
AuthBufferLen: u32,
AuthBuffer: ?*u8,
};
pub const CREDSPP_SUBMIT_TYPE = enum(i32) {
PasswordCreds = 2,
SchannelCreds = 4,
CertificateCreds = 13,
SubmitBufferBoth = 50,
SubmitBufferBothOld = 51,
CredEx = 100,
};
pub const CredsspPasswordCreds = CREDSPP_SUBMIT_TYPE.PasswordCreds;
pub const CredsspSchannelCreds = CREDSPP_SUBMIT_TYPE.SchannelCreds;
pub const CredsspCertificateCreds = CREDSPP_SUBMIT_TYPE.CertificateCreds;
pub const CredsspSubmitBufferBoth = CREDSPP_SUBMIT_TYPE.SubmitBufferBoth;
pub const CredsspSubmitBufferBothOld = CREDSPP_SUBMIT_TYPE.SubmitBufferBothOld;
pub const CredsspCredEx = CREDSPP_SUBMIT_TYPE.CredEx;
pub const CREDSSP_CRED = extern struct {
Type: CREDSPP_SUBMIT_TYPE,
pSchannelCred: ?*anyopaque,
pSpnegoCred: ?*anyopaque,
};
pub const CREDSSP_CRED_EX = extern struct {
Type: CREDSPP_SUBMIT_TYPE,
Version: u32,
Flags: u32,
Reserved: u32,
Cred: CREDSSP_CRED,
};
//--------------------------------------------------------------------------------
// Section: Functions (127)
//--------------------------------------------------------------------------------
pub extern "KeyCredMgr" fn KeyCredentialManagerGetOperationErrorStates(
keyCredentialManagerOperationType: KeyCredentialManagerOperationType,
isReady: ?*BOOL,
keyCredentialManagerOperationErrorStates: ?*KeyCredentialManagerOperationErrorStates,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "KeyCredMgr" fn KeyCredentialManagerShowUIOperation(
hWndOwner: ?HWND,
keyCredentialManagerOperationType: KeyCredentialManagerOperationType,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "KeyCredMgr" fn KeyCredentialManagerGetInformation(
keyCredentialManagerInfo: ?*?*KeyCredentialManagerInfo,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "KeyCredMgr" fn KeyCredentialManagerFreeInformation(
keyCredentialManagerInfo: ?*KeyCredentialManagerInfo,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn CredWriteW(
Credential: ?*CREDENTIALW,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn CredWriteA(
Credential: ?*CREDENTIALA,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn CredReadW(
TargetName: ?[*:0]const u16,
Type: u32,
Flags: u32,
Credential: ?*?*CREDENTIALW,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn CredReadA(
TargetName: ?[*:0]const u8,
Type: u32,
Flags: u32,
Credential: ?*?*CREDENTIALA,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn CredEnumerateW(
Filter: ?[*:0]const u16,
Flags: CRED_ENUMERATE_FLAGS,
Count: ?*u32,
Credential: ?*?*?*CREDENTIALW,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn CredEnumerateA(
Filter: ?[*:0]const u8,
Flags: CRED_ENUMERATE_FLAGS,
Count: ?*u32,
Credential: ?*?*?*CREDENTIALA,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn CredWriteDomainCredentialsW(
TargetInfo: ?*CREDENTIAL_TARGET_INFORMATIONW,
Credential: ?*CREDENTIALW,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn CredWriteDomainCredentialsA(
TargetInfo: ?*CREDENTIAL_TARGET_INFORMATIONA,
Credential: ?*CREDENTIALA,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn CredReadDomainCredentialsW(
TargetInfo: ?*CREDENTIAL_TARGET_INFORMATIONW,
Flags: u32,
Count: ?*u32,
Credential: ?*?*?*CREDENTIALW,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn CredReadDomainCredentialsA(
TargetInfo: ?*CREDENTIAL_TARGET_INFORMATIONA,
Flags: u32,
Count: ?*u32,
Credential: ?*?*?*CREDENTIALA,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn CredDeleteW(
TargetName: ?[*:0]const u16,
Type: u32,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn CredDeleteA(
TargetName: ?[*:0]const u8,
Type: u32,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn CredRenameW(
OldTargetName: ?[*:0]const u16,
NewTargetName: ?[*:0]const u16,
Type: u32,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn CredRenameA(
OldTargetName: ?[*:0]const u8,
NewTargetName: ?[*:0]const u8,
Type: u32,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn CredGetTargetInfoW(
TargetName: ?[*:0]const u16,
Flags: u32,
TargetInfo: ?*?*CREDENTIAL_TARGET_INFORMATIONW,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn CredGetTargetInfoA(
TargetName: ?[*:0]const u8,
Flags: u32,
TargetInfo: ?*?*CREDENTIAL_TARGET_INFORMATIONA,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn CredMarshalCredentialW(
CredType: CRED_MARSHAL_TYPE,
Credential: ?*anyopaque,
MarshaledCredential: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn CredMarshalCredentialA(
CredType: CRED_MARSHAL_TYPE,
Credential: ?*anyopaque,
MarshaledCredential: ?*?PSTR,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn CredUnmarshalCredentialW(
MarshaledCredential: ?[*:0]const u16,
CredType: ?*CRED_MARSHAL_TYPE,
Credential: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn CredUnmarshalCredentialA(
MarshaledCredential: ?[*:0]const u8,
CredType: ?*CRED_MARSHAL_TYPE,
Credential: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn CredIsMarshaledCredentialW(
MarshaledCredential: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn CredIsMarshaledCredentialA(
MarshaledCredential: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "credui" fn CredUnPackAuthenticationBufferW(
dwFlags: CRED_PACK_FLAGS,
// TODO: what to do with BytesParamIndex 2?
pAuthBuffer: ?*anyopaque,
cbAuthBuffer: u32,
pszUserName: ?[*:0]u16,
pcchMaxUserName: ?*u32,
pszDomainName: ?[*:0]u16,
pcchMaxDomainName: ?*u32,
pszPassword: ?[*:0]u16,
pcchMaxPassword: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "credui" fn CredUnPackAuthenticationBufferA(
dwFlags: CRED_PACK_FLAGS,
// TODO: what to do with BytesParamIndex 2?
pAuthBuffer: ?*anyopaque,
cbAuthBuffer: u32,
pszUserName: ?[*:0]u8,
pcchlMaxUserName: ?*u32,
pszDomainName: ?[*:0]u8,
pcchMaxDomainName: ?*u32,
pszPassword: ?[*:0]u8,
pcchMaxPassword: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "credui" fn CredPackAuthenticationBufferW(
dwFlags: CRED_PACK_FLAGS,
pszUserName: ?PWSTR,
pszPassword: ?PWSTR,
// TODO: what to do with BytesParamIndex 4?
pPackedCredentials: ?*u8,
pcbPackedCredentials: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "credui" fn CredPackAuthenticationBufferA(
dwFlags: CRED_PACK_FLAGS,
pszUserName: ?PSTR,
pszPassword: ?PSTR,
// TODO: what to do with BytesParamIndex 4?
pPackedCredentials: ?*u8,
pcbPackedCredentials: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "ADVAPI32" fn CredProtectW(
fAsSelf: BOOL,
pszCredentials: [*:0]u16,
cchCredentials: u32,
pszProtectedCredentials: [*:0]u16,
pcchMaxChars: ?*u32,
ProtectionType: ?*CRED_PROTECTION_TYPE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "ADVAPI32" fn CredProtectA(
fAsSelf: BOOL,
pszCredentials: [*:0]u8,
cchCredentials: u32,
pszProtectedCredentials: [*:0]u8,
pcchMaxChars: ?*u32,
ProtectionType: ?*CRED_PROTECTION_TYPE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "ADVAPI32" fn CredUnprotectW(
fAsSelf: BOOL,
pszProtectedCredentials: [*:0]u16,
cchProtectedCredentials: u32,
pszCredentials: ?[*:0]u16,
pcchMaxChars: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "ADVAPI32" fn CredUnprotectA(
fAsSelf: BOOL,
pszProtectedCredentials: [*:0]u8,
cchProtectedCredentials: u32,
pszCredentials: ?[*:0]u8,
pcchMaxChars: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "ADVAPI32" fn CredIsProtectedW(
pszProtectedCredentials: ?PWSTR,
pProtectionType: ?*CRED_PROTECTION_TYPE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "ADVAPI32" fn CredIsProtectedA(
pszProtectedCredentials: ?PSTR,
pProtectionType: ?*CRED_PROTECTION_TYPE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "ADVAPI32" fn CredFindBestCredentialW(
TargetName: ?[*:0]const u16,
Type: u32,
Flags: u32,
Credential: ?*?*CREDENTIALW,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "ADVAPI32" fn CredFindBestCredentialA(
TargetName: ?[*:0]const u8,
Type: u32,
Flags: u32,
Credential: ?*?*CREDENTIALA,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn CredGetSessionTypes(
MaximumPersistCount: u32,
MaximumPersist: [*]u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn CredFree(
Buffer: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "credui" fn CredUIPromptForCredentialsW(
pUiInfo: ?*CREDUI_INFOW,
pszTargetName: ?[*:0]const u16,
pContext: ?*SecHandle,
dwAuthError: u32,
pszUserName: [*:0]u16,
ulUserNameBufferSize: u32,
pszPassword: [*:0]u16,
ulPasswordBufferSize: u32,
save: ?*BOOL,
dwFlags: CREDUI_FLAGS,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "credui" fn CredUIPromptForCredentialsA(
pUiInfo: ?*CREDUI_INFOA,
pszTargetName: ?[*:0]const u8,
pContext: ?*SecHandle,
dwAuthError: u32,
pszUserName: [*:0]u8,
ulUserNameBufferSize: u32,
pszPassword: [*:0]u8,
ulPasswordBufferSize: u32,
save: ?*BOOL,
dwFlags: CREDUI_FLAGS,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "credui" fn CredUIPromptForWindowsCredentialsW(
pUiInfo: ?*CREDUI_INFOW,
dwAuthError: u32,
pulAuthPackage: ?*u32,
// TODO: what to do with BytesParamIndex 4?
pvInAuthBuffer: ?*const anyopaque,
ulInAuthBufferSize: u32,
// TODO: what to do with BytesParamIndex 6?
ppvOutAuthBuffer: ?*?*anyopaque,
pulOutAuthBufferSize: ?*u32,
pfSave: ?*BOOL,
dwFlags: CREDUIWIN_FLAGS,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "credui" fn CredUIPromptForWindowsCredentialsA(
pUiInfo: ?*CREDUI_INFOA,
dwAuthError: u32,
pulAuthPackage: ?*u32,
// TODO: what to do with BytesParamIndex 4?
pvInAuthBuffer: ?*const anyopaque,
ulInAuthBufferSize: u32,
// TODO: what to do with BytesParamIndex 6?
ppvOutAuthBuffer: ?*?*anyopaque,
pulOutAuthBufferSize: ?*u32,
pfSave: ?*BOOL,
dwFlags: CREDUIWIN_FLAGS,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "credui" fn CredUIParseUserNameW(
UserName: ?[*:0]const u16,
user: [*:0]u16,
userBufferSize: u32,
domain: [*:0]u16,
domainBufferSize: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "credui" fn CredUIParseUserNameA(
userName: ?[*:0]const u8,
user: [*:0]u8,
userBufferSize: u32,
domain: [*:0]u8,
domainBufferSize: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "credui" fn CredUICmdLinePromptForCredentialsW(
pszTargetName: ?[*:0]const u16,
pContext: ?*SecHandle,
dwAuthError: u32,
UserName: [*:0]u16,
ulUserBufferSize: u32,
pszPassword: [*:0]u16,
ulPasswordBufferSize: u32,
pfSave: ?*BOOL,
dwFlags: CREDUI_FLAGS,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "credui" fn CredUICmdLinePromptForCredentialsA(
pszTargetName: ?[*:0]const u8,
pContext: ?*SecHandle,
dwAuthError: u32,
UserName: [*:0]u8,
ulUserBufferSize: u32,
pszPassword: [*:0]u8,
ulPasswordBufferSize: u32,
pfSave: ?*BOOL,
dwFlags: CREDUI_FLAGS,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "credui" fn CredUIConfirmCredentialsW(
pszTargetName: ?[*:0]const u16,
bConfirm: BOOL,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "credui" fn CredUIConfirmCredentialsA(
pszTargetName: ?[*:0]const u8,
bConfirm: BOOL,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "credui" fn CredUIStoreSSOCredW(
pszRealm: ?[*:0]const u16,
pszUsername: ?[*:0]const u16,
pszPassword: ?[*:0]const u16,
bPersist: BOOL,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "credui" fn CredUIReadSSOCredW(
pszRealm: ?[*:0]const u16,
ppszUsername: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardEstablishContext(
dwScope: SCARD_SCOPE,
pvReserved1: ?*const anyopaque,
pvReserved2: ?*const anyopaque,
phContext: ?*usize,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardReleaseContext(
hContext: usize,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardIsValidContext(
hContext: usize,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardListReaderGroupsA(
hContext: usize,
mszGroups: ?[*:0]u8,
pcchGroups: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardListReaderGroupsW(
hContext: usize,
mszGroups: ?[*:0]u16,
pcchGroups: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardListReadersA(
hContext: usize,
mszGroups: ?[*:0]const u8,
mszReaders: ?PSTR,
pcchReaders: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardListReadersW(
hContext: usize,
mszGroups: ?[*:0]const u16,
mszReaders: ?PWSTR,
pcchReaders: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardListCardsA(
hContext: usize,
pbAtr: ?*u8,
rgquidInterfaces: ?[*]const Guid,
cguidInterfaceCount: u32,
mszCards: ?PSTR,
pcchCards: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardListCardsW(
hContext: usize,
pbAtr: ?*u8,
rgquidInterfaces: ?[*]const Guid,
cguidInterfaceCount: u32,
mszCards: ?PWSTR,
pcchCards: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardListInterfacesA(
hContext: usize,
szCard: ?[*:0]const u8,
pguidInterfaces: ?*Guid,
pcguidInterfaces: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardListInterfacesW(
hContext: usize,
szCard: ?[*:0]const u16,
pguidInterfaces: ?*Guid,
pcguidInterfaces: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardGetProviderIdA(
hContext: usize,
szCard: ?[*:0]const u8,
pguidProviderId: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardGetProviderIdW(
hContext: usize,
szCard: ?[*:0]const u16,
pguidProviderId: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardGetCardTypeProviderNameA(
hContext: usize,
szCardName: ?[*:0]const u8,
dwProviderId: u32,
szProvider: [*:0]u8,
pcchProvider: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardGetCardTypeProviderNameW(
hContext: usize,
szCardName: ?[*:0]const u16,
dwProviderId: u32,
szProvider: [*:0]u16,
pcchProvider: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardIntroduceReaderGroupA(
hContext: usize,
szGroupName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardIntroduceReaderGroupW(
hContext: usize,
szGroupName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardForgetReaderGroupA(
hContext: usize,
szGroupName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardForgetReaderGroupW(
hContext: usize,
szGroupName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardIntroduceReaderA(
hContext: usize,
szReaderName: ?[*:0]const u8,
szDeviceName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardIntroduceReaderW(
hContext: usize,
szReaderName: ?[*:0]const u16,
szDeviceName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardForgetReaderA(
hContext: usize,
szReaderName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardForgetReaderW(
hContext: usize,
szReaderName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardAddReaderToGroupA(
hContext: usize,
szReaderName: ?[*:0]const u8,
szGroupName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardAddReaderToGroupW(
hContext: usize,
szReaderName: ?[*:0]const u16,
szGroupName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardRemoveReaderFromGroupA(
hContext: usize,
szReaderName: ?[*:0]const u8,
szGroupName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardRemoveReaderFromGroupW(
hContext: usize,
szReaderName: ?[*:0]const u16,
szGroupName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardIntroduceCardTypeA(
hContext: usize,
szCardName: ?[*:0]const u8,
pguidPrimaryProvider: ?*const Guid,
rgguidInterfaces: ?*const Guid,
dwInterfaceCount: u32,
pbAtr: ?*u8,
pbAtrMask: ?*u8,
cbAtrLen: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardIntroduceCardTypeW(
hContext: usize,
szCardName: ?[*:0]const u16,
pguidPrimaryProvider: ?*const Guid,
rgguidInterfaces: ?*const Guid,
dwInterfaceCount: u32,
pbAtr: ?*u8,
pbAtrMask: ?*u8,
cbAtrLen: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardSetCardTypeProviderNameA(
hContext: usize,
szCardName: ?[*:0]const u8,
dwProviderId: u32,
szProvider: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardSetCardTypeProviderNameW(
hContext: usize,
szCardName: ?[*:0]const u16,
dwProviderId: u32,
szProvider: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardForgetCardTypeA(
hContext: usize,
szCardName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardForgetCardTypeW(
hContext: usize,
szCardName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardFreeMemory(
hContext: usize,
pvMem: ?*const anyopaque,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardAccessStartedEvent(
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardReleaseStartedEvent(
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardLocateCardsA(
hContext: usize,
mszCards: ?[*:0]const u8,
rgReaderStates: ?*SCARD_READERSTATEA,
cReaders: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardLocateCardsW(
hContext: usize,
mszCards: ?[*:0]const u16,
rgReaderStates: ?*SCARD_READERSTATEW,
cReaders: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardLocateCardsByATRA(
hContext: usize,
rgAtrMasks: ?*SCARD_ATRMASK,
cAtrs: u32,
rgReaderStates: ?*SCARD_READERSTATEA,
cReaders: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardLocateCardsByATRW(
hContext: usize,
rgAtrMasks: ?*SCARD_ATRMASK,
cAtrs: u32,
rgReaderStates: ?*SCARD_READERSTATEW,
cReaders: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardGetStatusChangeA(
hContext: usize,
dwTimeout: u32,
rgReaderStates: ?*SCARD_READERSTATEA,
cReaders: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardGetStatusChangeW(
hContext: usize,
dwTimeout: u32,
rgReaderStates: ?*SCARD_READERSTATEW,
cReaders: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardCancel(
hContext: usize,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardConnectA(
hContext: usize,
szReader: ?[*:0]const u8,
dwShareMode: u32,
dwPreferredProtocols: u32,
phCard: ?*usize,
pdwActiveProtocol: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardConnectW(
hContext: usize,
szReader: ?[*:0]const u16,
dwShareMode: u32,
dwPreferredProtocols: u32,
phCard: ?*usize,
pdwActiveProtocol: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardReconnect(
hCard: usize,
dwShareMode: u32,
dwPreferredProtocols: u32,
dwInitialization: u32,
pdwActiveProtocol: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardDisconnect(
hCard: usize,
dwDisposition: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardBeginTransaction(
hCard: usize,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardEndTransaction(
hCard: usize,
dwDisposition: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub extern "WinSCard" fn SCardState(
hCard: usize,
pdwState: ?*u32,
pdwProtocol: ?*u32,
// TODO: what to do with BytesParamIndex 4?
pbAtr: ?*u8,
pcbAtrLen: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardStatusA(
hCard: usize,
mszReaderNames: ?PSTR,
pcchReaderLen: ?*u32,
pdwState: ?*u32,
pdwProtocol: ?*u32,
pbAtr: ?*u8,
pcbAtrLen: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardStatusW(
hCard: usize,
mszReaderNames: ?PWSTR,
pcchReaderLen: ?*u32,
pdwState: ?*u32,
pdwProtocol: ?*u32,
pbAtr: ?*u8,
pcbAtrLen: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardTransmit(
hCard: usize,
pioSendPci: ?*SCARD_IO_REQUEST,
// TODO: what to do with BytesParamIndex 3?
pbSendBuffer: ?*u8,
cbSendLength: u32,
pioRecvPci: ?*SCARD_IO_REQUEST,
// TODO: what to do with BytesParamIndex 6?
pbRecvBuffer: ?*u8,
pcbRecvLength: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "WinSCard" fn SCardGetTransmitCount(
hCard: usize,
pcTransmitCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardControl(
hCard: usize,
dwControlCode: u32,
// TODO: what to do with BytesParamIndex 3?
lpInBuffer: ?*const anyopaque,
cbInBufferSize: u32,
// TODO: what to do with BytesParamIndex 5?
lpOutBuffer: ?*anyopaque,
cbOutBufferSize: u32,
lpBytesReturned: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardGetAttrib(
hCard: usize,
dwAttrId: u32,
// TODO: what to do with BytesParamIndex 3?
pbAttr: ?*u8,
pcbAttrLen: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "WinSCard" fn SCardSetAttrib(
hCard: usize,
dwAttrId: u32,
// TODO: what to do with BytesParamIndex 3?
pbAttr: ?*u8,
cbAttrLen: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "SCARDDLG" fn SCardUIDlgSelectCardA(
param0: ?*OPENCARDNAME_EXA,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "SCARDDLG" fn SCardUIDlgSelectCardW(
param0: ?*OPENCARDNAME_EXW,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "SCARDDLG" fn GetOpenCardNameA(
param0: ?*OPENCARDNAMEA,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "SCARDDLG" fn GetOpenCardNameW(
param0: ?*OPENCARDNAMEW,
) callconv(@import("std").os.windows.WINAPI) i32;
pub extern "SCARDDLG" fn SCardDlgExtendedError(
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "WinSCard" fn SCardReadCacheA(
hContext: usize,
CardIdentifier: ?*Guid,
FreshnessCounter: u32,
LookupName: ?PSTR,
// TODO: what to do with BytesParamIndex 5?
Data: ?*u8,
DataLen: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "WinSCard" fn SCardReadCacheW(
hContext: usize,
CardIdentifier: ?*Guid,
FreshnessCounter: u32,
LookupName: ?PWSTR,
// TODO: what to do with BytesParamIndex 5?
Data: ?*u8,
DataLen: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "WinSCard" fn SCardWriteCacheA(
hContext: usize,
CardIdentifier: ?*Guid,
FreshnessCounter: u32,
LookupName: ?PSTR,
// TODO: what to do with BytesParamIndex 5?
Data: ?*u8,
DataLen: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "WinSCard" fn SCardWriteCacheW(
hContext: usize,
CardIdentifier: ?*Guid,
FreshnessCounter: u32,
LookupName: ?PWSTR,
// TODO: what to do with BytesParamIndex 5?
Data: ?*u8,
DataLen: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "WinSCard" fn SCardGetReaderIconA(
hContext: usize,
szReaderName: ?[*:0]const u8,
// TODO: what to do with BytesParamIndex 3?
pbIcon: ?*u8,
pcbIcon: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "WinSCard" fn SCardGetReaderIconW(
hContext: usize,
szReaderName: ?[*:0]const u16,
// TODO: what to do with BytesParamIndex 3?
pbIcon: ?*u8,
pcbIcon: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "WinSCard" fn SCardGetDeviceTypeIdA(
hContext: usize,
szReaderName: ?[*:0]const u8,
pdwDeviceTypeId: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "WinSCard" fn SCardGetDeviceTypeIdW(
hContext: usize,
szReaderName: ?[*:0]const u16,
pdwDeviceTypeId: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "WinSCard" fn SCardGetReaderDeviceInstanceIdA(
hContext: usize,
szReaderName: ?[*:0]const u8,
szDeviceInstanceId: ?PSTR,
pcchDeviceInstanceId: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "WinSCard" fn SCardGetReaderDeviceInstanceIdW(
hContext: usize,
szReaderName: ?[*:0]const u16,
szDeviceInstanceId: ?PWSTR,
pcchDeviceInstanceId: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "WinSCard" fn SCardListReadersWithDeviceInstanceIdA(
hContext: usize,
szDeviceInstanceId: ?[*:0]const u8,
mszReaders: ?PSTR,
pcchReaders: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "WinSCard" fn SCardListReadersWithDeviceInstanceIdW(
hContext: usize,
szDeviceInstanceId: ?[*:0]const u16,
mszReaders: ?PWSTR,
pcchReaders: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "WinSCard" fn SCardAudit(
hContext: usize,
dwEvent: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (59)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../zig.zig").unicode_mode) {
.ansi => struct {
pub const CREDENTIAL_ATTRIBUTE = thismodule.CREDENTIAL_ATTRIBUTEA;
pub const CREDENTIAL = thismodule.CREDENTIALA;
pub const CREDENTIAL_TARGET_INFORMATION = thismodule.CREDENTIAL_TARGET_INFORMATIONA;
pub const CREDUI_INFO = thismodule.CREDUI_INFOA;
pub const SCARD_READERSTATE = thismodule.SCARD_READERSTATEA;
pub const LPOCNCONNPROC = thismodule.LPOCNCONNPROCA;
pub const OPENCARD_SEARCH_CRITERIA = thismodule.OPENCARD_SEARCH_CRITERIAA;
pub const OPENCARDNAME_EX = thismodule.OPENCARDNAME_EXA;
pub const OPENCARDNAME = thismodule.OPENCARDNAMEA;
pub const CredWrite = thismodule.CredWriteA;
pub const CredRead = thismodule.CredReadA;
pub const CredEnumerate = thismodule.CredEnumerateA;
pub const CredWriteDomainCredentials = thismodule.CredWriteDomainCredentialsA;
pub const CredReadDomainCredentials = thismodule.CredReadDomainCredentialsA;
pub const CredDelete = thismodule.CredDeleteA;
pub const CredRename = thismodule.CredRenameA;
pub const CredGetTargetInfo = thismodule.CredGetTargetInfoA;
pub const CredMarshalCredential = thismodule.CredMarshalCredentialA;
pub const CredUnmarshalCredential = thismodule.CredUnmarshalCredentialA;
pub const CredIsMarshaledCredential = thismodule.CredIsMarshaledCredentialA;
pub const CredUnPackAuthenticationBuffer = thismodule.CredUnPackAuthenticationBufferA;
pub const CredPackAuthenticationBuffer = thismodule.CredPackAuthenticationBufferA;
pub const CredProtect = thismodule.CredProtectA;
pub const CredUnprotect = thismodule.CredUnprotectA;
pub const CredIsProtected = thismodule.CredIsProtectedA;
pub const CredFindBestCredential = thismodule.CredFindBestCredentialA;
pub const CredUIPromptForCredentials = thismodule.CredUIPromptForCredentialsA;
pub const CredUIPromptForWindowsCredentials = thismodule.CredUIPromptForWindowsCredentialsA;
pub const CredUIParseUserName = thismodule.CredUIParseUserNameA;
pub const CredUICmdLinePromptForCredentials = thismodule.CredUICmdLinePromptForCredentialsA;
pub const CredUIConfirmCredentials = thismodule.CredUIConfirmCredentialsA;
pub const SCardListReaderGroups = thismodule.SCardListReaderGroupsA;
pub const SCardListReaders = thismodule.SCardListReadersA;
pub const SCardListCards = thismodule.SCardListCardsA;
pub const SCardListInterfaces = thismodule.SCardListInterfacesA;
pub const SCardGetProviderId = thismodule.SCardGetProviderIdA;
pub const SCardGetCardTypeProviderName = thismodule.SCardGetCardTypeProviderNameA;
pub const SCardIntroduceReaderGroup = thismodule.SCardIntroduceReaderGroupA;
pub const SCardForgetReaderGroup = thismodule.SCardForgetReaderGroupA;
pub const SCardIntroduceReader = thismodule.SCardIntroduceReaderA;
pub const SCardForgetReader = thismodule.SCardForgetReaderA;
pub const SCardAddReaderToGroup = thismodule.SCardAddReaderToGroupA;
pub const SCardRemoveReaderFromGroup = thismodule.SCardRemoveReaderFromGroupA;
pub const SCardIntroduceCardType = thismodule.SCardIntroduceCardTypeA;
pub const SCardSetCardTypeProviderName = thismodule.SCardSetCardTypeProviderNameA;
pub const SCardForgetCardType = thismodule.SCardForgetCardTypeA;
pub const SCardLocateCards = thismodule.SCardLocateCardsA;
pub const SCardLocateCardsByATR = thismodule.SCardLocateCardsByATRA;
pub const SCardGetStatusChange = thismodule.SCardGetStatusChangeA;
pub const SCardConnect = thismodule.SCardConnectA;
pub const SCardStatus = thismodule.SCardStatusA;
pub const SCardUIDlgSelectCard = thismodule.SCardUIDlgSelectCardA;
pub const GetOpenCardName = thismodule.GetOpenCardNameA;
pub const SCardReadCache = thismodule.SCardReadCacheA;
pub const SCardWriteCache = thismodule.SCardWriteCacheA;
pub const SCardGetReaderIcon = thismodule.SCardGetReaderIconA;
pub const SCardGetDeviceTypeId = thismodule.SCardGetDeviceTypeIdA;
pub const SCardGetReaderDeviceInstanceId = thismodule.SCardGetReaderDeviceInstanceIdA;
pub const SCardListReadersWithDeviceInstanceId = thismodule.SCardListReadersWithDeviceInstanceIdA;
},
.wide => struct {
pub const CREDENTIAL_ATTRIBUTE = thismodule.CREDENTIAL_ATTRIBUTEW;
pub const CREDENTIAL = thismodule.CREDENTIALW;
pub const CREDENTIAL_TARGET_INFORMATION = thismodule.CREDENTIAL_TARGET_INFORMATIONW;
pub const CREDUI_INFO = thismodule.CREDUI_INFOW;
pub const SCARD_READERSTATE = thismodule.SCARD_READERSTATEW;
pub const LPOCNCONNPROC = thismodule.LPOCNCONNPROCW;
pub const OPENCARD_SEARCH_CRITERIA = thismodule.OPENCARD_SEARCH_CRITERIAW;
pub const OPENCARDNAME_EX = thismodule.OPENCARDNAME_EXW;
pub const OPENCARDNAME = thismodule.OPENCARDNAMEW;
pub const CredWrite = thismodule.CredWriteW;
pub const CredRead = thismodule.CredReadW;
pub const CredEnumerate = thismodule.CredEnumerateW;
pub const CredWriteDomainCredentials = thismodule.CredWriteDomainCredentialsW;
pub const CredReadDomainCredentials = thismodule.CredReadDomainCredentialsW;
pub const CredDelete = thismodule.CredDeleteW;
pub const CredRename = thismodule.CredRenameW;
pub const CredGetTargetInfo = thismodule.CredGetTargetInfoW;
pub const CredMarshalCredential = thismodule.CredMarshalCredentialW;
pub const CredUnmarshalCredential = thismodule.CredUnmarshalCredentialW;
pub const CredIsMarshaledCredential = thismodule.CredIsMarshaledCredentialW;
pub const CredUnPackAuthenticationBuffer = thismodule.CredUnPackAuthenticationBufferW;
pub const CredPackAuthenticationBuffer = thismodule.CredPackAuthenticationBufferW;
pub const CredProtect = thismodule.CredProtectW;
pub const CredUnprotect = thismodule.CredUnprotectW;
pub const CredIsProtected = thismodule.CredIsProtectedW;
pub const CredFindBestCredential = thismodule.CredFindBestCredentialW;
pub const CredUIPromptForCredentials = thismodule.CredUIPromptForCredentialsW;
pub const CredUIPromptForWindowsCredentials = thismodule.CredUIPromptForWindowsCredentialsW;
pub const CredUIParseUserName = thismodule.CredUIParseUserNameW;
pub const CredUICmdLinePromptForCredentials = thismodule.CredUICmdLinePromptForCredentialsW;
pub const CredUIConfirmCredentials = thismodule.CredUIConfirmCredentialsW;
pub const SCardListReaderGroups = thismodule.SCardListReaderGroupsW;
pub const SCardListReaders = thismodule.SCardListReadersW;
pub const SCardListCards = thismodule.SCardListCardsW;
pub const SCardListInterfaces = thismodule.SCardListInterfacesW;
pub const SCardGetProviderId = thismodule.SCardGetProviderIdW;
pub const SCardGetCardTypeProviderName = thismodule.SCardGetCardTypeProviderNameW;
pub const SCardIntroduceReaderGroup = thismodule.SCardIntroduceReaderGroupW;
pub const SCardForgetReaderGroup = thismodule.SCardForgetReaderGroupW;
pub const SCardIntroduceReader = thismodule.SCardIntroduceReaderW;
pub const SCardForgetReader = thismodule.SCardForgetReaderW;
pub const SCardAddReaderToGroup = thismodule.SCardAddReaderToGroupW;
pub const SCardRemoveReaderFromGroup = thismodule.SCardRemoveReaderFromGroupW;
pub const SCardIntroduceCardType = thismodule.SCardIntroduceCardTypeW;
pub const SCardSetCardTypeProviderName = thismodule.SCardSetCardTypeProviderNameW;
pub const SCardForgetCardType = thismodule.SCardForgetCardTypeW;
pub const SCardLocateCards = thismodule.SCardLocateCardsW;
pub const SCardLocateCardsByATR = thismodule.SCardLocateCardsByATRW;
pub const SCardGetStatusChange = thismodule.SCardGetStatusChangeW;
pub const SCardConnect = thismodule.SCardConnectW;
pub const SCardStatus = thismodule.SCardStatusW;
pub const SCardUIDlgSelectCard = thismodule.SCardUIDlgSelectCardW;
pub const GetOpenCardName = thismodule.GetOpenCardNameW;
pub const SCardReadCache = thismodule.SCardReadCacheW;
pub const SCardWriteCache = thismodule.SCardWriteCacheW;
pub const SCardGetReaderIcon = thismodule.SCardGetReaderIconW;
pub const SCardGetDeviceTypeId = thismodule.SCardGetDeviceTypeIdW;
pub const SCardGetReaderDeviceInstanceId = thismodule.SCardGetReaderDeviceInstanceIdW;
pub const SCardListReadersWithDeviceInstanceId = thismodule.SCardListReadersWithDeviceInstanceIdW;
},
.unspecified => if (@import("builtin").is_test) struct {
pub const CREDENTIAL_ATTRIBUTE = *opaque{};
pub const CREDENTIAL = *opaque{};
pub const CREDENTIAL_TARGET_INFORMATION = *opaque{};
pub const CREDUI_INFO = *opaque{};
pub const SCARD_READERSTATE = *opaque{};
pub const LPOCNCONNPROC = *opaque{};
pub const OPENCARD_SEARCH_CRITERIA = *opaque{};
pub const OPENCARDNAME_EX = *opaque{};
pub const OPENCARDNAME = *opaque{};
pub const CredWrite = *opaque{};
pub const CredRead = *opaque{};
pub const CredEnumerate = *opaque{};
pub const CredWriteDomainCredentials = *opaque{};
pub const CredReadDomainCredentials = *opaque{};
pub const CredDelete = *opaque{};
pub const CredRename = *opaque{};
pub const CredGetTargetInfo = *opaque{};
pub const CredMarshalCredential = *opaque{};
pub const CredUnmarshalCredential = *opaque{};
pub const CredIsMarshaledCredential = *opaque{};
pub const CredUnPackAuthenticationBuffer = *opaque{};
pub const CredPackAuthenticationBuffer = *opaque{};
pub const CredProtect = *opaque{};
pub const CredUnprotect = *opaque{};
pub const CredIsProtected = *opaque{};
pub const CredFindBestCredential = *opaque{};
pub const CredUIPromptForCredentials = *opaque{};
pub const CredUIPromptForWindowsCredentials = *opaque{};
pub const CredUIParseUserName = *opaque{};
pub const CredUICmdLinePromptForCredentials = *opaque{};
pub const CredUIConfirmCredentials = *opaque{};
pub const SCardListReaderGroups = *opaque{};
pub const SCardListReaders = *opaque{};
pub const SCardListCards = *opaque{};
pub const SCardListInterfaces = *opaque{};
pub const SCardGetProviderId = *opaque{};
pub const SCardGetCardTypeProviderName = *opaque{};
pub const SCardIntroduceReaderGroup = *opaque{};
pub const SCardForgetReaderGroup = *opaque{};
pub const SCardIntroduceReader = *opaque{};
pub const SCardForgetReader = *opaque{};
pub const SCardAddReaderToGroup = *opaque{};
pub const SCardRemoveReaderFromGroup = *opaque{};
pub const SCardIntroduceCardType = *opaque{};
pub const SCardSetCardTypeProviderName = *opaque{};
pub const SCardForgetCardType = *opaque{};
pub const SCardLocateCards = *opaque{};
pub const SCardLocateCardsByATR = *opaque{};
pub const SCardGetStatusChange = *opaque{};
pub const SCardConnect = *opaque{};
pub const SCardStatus = *opaque{};
pub const SCardUIDlgSelectCard = *opaque{};
pub const GetOpenCardName = *opaque{};
pub const SCardReadCache = *opaque{};
pub const SCardWriteCache = *opaque{};
pub const SCardGetReaderIcon = *opaque{};
pub const SCardGetDeviceTypeId = *opaque{};
pub const SCardGetReaderDeviceInstanceId = *opaque{};
pub const SCardListReadersWithDeviceInstanceId = *opaque{};
} else struct {
pub const CREDENTIAL_ATTRIBUTE = @compileError("'CREDENTIAL_ATTRIBUTE' requires that UNICODE be set to true or false in the root module");
pub const CREDENTIAL = @compileError("'CREDENTIAL' requires that UNICODE be set to true or false in the root module");
pub const CREDENTIAL_TARGET_INFORMATION = @compileError("'CREDENTIAL_TARGET_INFORMATION' requires that UNICODE be set to true or false in the root module");
pub const CREDUI_INFO = @compileError("'CREDUI_INFO' requires that UNICODE be set to true or false in the root module");
pub const SCARD_READERSTATE = @compileError("'SCARD_READERSTATE' requires that UNICODE be set to true or false in the root module");
pub const LPOCNCONNPROC = @compileError("'LPOCNCONNPROC' requires that UNICODE be set to true or false in the root module");
pub const OPENCARD_SEARCH_CRITERIA = @compileError("'OPENCARD_SEARCH_CRITERIA' requires that UNICODE be set to true or false in the root module");
pub const OPENCARDNAME_EX = @compileError("'OPENCARDNAME_EX' requires that UNICODE be set to true or false in the root module");
pub const OPENCARDNAME = @compileError("'OPENCARDNAME' requires that UNICODE be set to true or false in the root module");
pub const CredWrite = @compileError("'CredWrite' requires that UNICODE be set to true or false in the root module");
pub const CredRead = @compileError("'CredRead' requires that UNICODE be set to true or false in the root module");
pub const CredEnumerate = @compileError("'CredEnumerate' requires that UNICODE be set to true or false in the root module");
pub const CredWriteDomainCredentials = @compileError("'CredWriteDomainCredentials' requires that UNICODE be set to true or false in the root module");
pub const CredReadDomainCredentials = @compileError("'CredReadDomainCredentials' requires that UNICODE be set to true or false in the root module");
pub const CredDelete = @compileError("'CredDelete' requires that UNICODE be set to true or false in the root module");
pub const CredRename = @compileError("'CredRename' requires that UNICODE be set to true or false in the root module");
pub const CredGetTargetInfo = @compileError("'CredGetTargetInfo' requires that UNICODE be set to true or false in the root module");
pub const CredMarshalCredential = @compileError("'CredMarshalCredential' requires that UNICODE be set to true or false in the root module");
pub const CredUnmarshalCredential = @compileError("'CredUnmarshalCredential' requires that UNICODE be set to true or false in the root module");
pub const CredIsMarshaledCredential = @compileError("'CredIsMarshaledCredential' requires that UNICODE be set to true or false in the root module");
pub const CredUnPackAuthenticationBuffer = @compileError("'CredUnPackAuthenticationBuffer' requires that UNICODE be set to true or false in the root module");
pub const CredPackAuthenticationBuffer = @compileError("'CredPackAuthenticationBuffer' requires that UNICODE be set to true or false in the root module");
pub const CredProtect = @compileError("'CredProtect' requires that UNICODE be set to true or false in the root module");
pub const CredUnprotect = @compileError("'CredUnprotect' requires that UNICODE be set to true or false in the root module");
pub const CredIsProtected = @compileError("'CredIsProtected' requires that UNICODE be set to true or false in the root module");
pub const CredFindBestCredential = @compileError("'CredFindBestCredential' requires that UNICODE be set to true or false in the root module");
pub const CredUIPromptForCredentials = @compileError("'CredUIPromptForCredentials' requires that UNICODE be set to true or false in the root module");
pub const CredUIPromptForWindowsCredentials = @compileError("'CredUIPromptForWindowsCredentials' requires that UNICODE be set to true or false in the root module");
pub const CredUIParseUserName = @compileError("'CredUIParseUserName' requires that UNICODE be set to true or false in the root module");
pub const CredUICmdLinePromptForCredentials = @compileError("'CredUICmdLinePromptForCredentials' requires that UNICODE be set to true or false in the root module");
pub const CredUIConfirmCredentials = @compileError("'CredUIConfirmCredentials' requires that UNICODE be set to true or false in the root module");
pub const SCardListReaderGroups = @compileError("'SCardListReaderGroups' requires that UNICODE be set to true or false in the root module");
pub const SCardListReaders = @compileError("'SCardListReaders' requires that UNICODE be set to true or false in the root module");
pub const SCardListCards = @compileError("'SCardListCards' requires that UNICODE be set to true or false in the root module");
pub const SCardListInterfaces = @compileError("'SCardListInterfaces' requires that UNICODE be set to true or false in the root module");
pub const SCardGetProviderId = @compileError("'SCardGetProviderId' requires that UNICODE be set to true or false in the root module");
pub const SCardGetCardTypeProviderName = @compileError("'SCardGetCardTypeProviderName' requires that UNICODE be set to true or false in the root module");
pub const SCardIntroduceReaderGroup = @compileError("'SCardIntroduceReaderGroup' requires that UNICODE be set to true or false in the root module");
pub const SCardForgetReaderGroup = @compileError("'SCardForgetReaderGroup' requires that UNICODE be set to true or false in the root module");
pub const SCardIntroduceReader = @compileError("'SCardIntroduceReader' requires that UNICODE be set to true or false in the root module");
pub const SCardForgetReader = @compileError("'SCardForgetReader' requires that UNICODE be set to true or false in the root module");
pub const SCardAddReaderToGroup = @compileError("'SCardAddReaderToGroup' requires that UNICODE be set to true or false in the root module");
pub const SCardRemoveReaderFromGroup = @compileError("'SCardRemoveReaderFromGroup' requires that UNICODE be set to true or false in the root module");
pub const SCardIntroduceCardType = @compileError("'SCardIntroduceCardType' requires that UNICODE be set to true or false in the root module");
pub const SCardSetCardTypeProviderName = @compileError("'SCardSetCardTypeProviderName' requires that UNICODE be set to true or false in the root module");
pub const SCardForgetCardType = @compileError("'SCardForgetCardType' requires that UNICODE be set to true or false in the root module");
pub const SCardLocateCards = @compileError("'SCardLocateCards' requires that UNICODE be set to true or false in the root module");
pub const SCardLocateCardsByATR = @compileError("'SCardLocateCardsByATR' requires that UNICODE be set to true or false in the root module");
pub const SCardGetStatusChange = @compileError("'SCardGetStatusChange' requires that UNICODE be set to true or false in the root module");
pub const SCardConnect = @compileError("'SCardConnect' requires that UNICODE be set to true or false in the root module");
pub const SCardStatus = @compileError("'SCardStatus' requires that UNICODE be set to true or false in the root module");
pub const SCardUIDlgSelectCard = @compileError("'SCardUIDlgSelectCard' requires that UNICODE be set to true or false in the root module");
pub const GetOpenCardName = @compileError("'GetOpenCardName' requires that UNICODE be set to true or false in the root module");
pub const SCardReadCache = @compileError("'SCardReadCache' requires that UNICODE be set to true or false in the root module");
pub const SCardWriteCache = @compileError("'SCardWriteCache' requires that UNICODE be set to true or false in the root module");
pub const SCardGetReaderIcon = @compileError("'SCardGetReaderIcon' requires that UNICODE be set to true or false in the root module");
pub const SCardGetDeviceTypeId = @compileError("'SCardGetDeviceTypeId' requires that UNICODE be set to true or false in the root module");
pub const SCardGetReaderDeviceInstanceId = @compileError("'SCardGetReaderDeviceInstanceId' requires that UNICODE be set to true or false in the root module");
pub const SCardListReadersWithDeviceInstanceId = @compileError("'SCardListReadersWithDeviceInstanceId' requires that UNICODE be set to true or false in the root module");
},
};
//--------------------------------------------------------------------------------
// Section: Imports (11)
//--------------------------------------------------------------------------------
const Guid = @import("../zig.zig").Guid;
const BOOL = @import("../foundation.zig").BOOL;
const FILETIME = @import("../foundation.zig").FILETIME;
const HANDLE = @import("../foundation.zig").HANDLE;
const HBITMAP = @import("../graphics/gdi.zig").HBITMAP;
const HICON = @import("../ui/windows_and_messaging.zig").HICON;
const HRESULT = @import("../foundation.zig").HRESULT;
const HWND = @import("../foundation.zig").HWND;
const NTSTATUS = @import("../foundation.zig").NTSTATUS;
const PSTR = @import("../foundation.zig").PSTR;
const PWSTR = @import("../foundation.zig").PWSTR;
test {
// The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476
if (@hasDecl(@This(), "LPOCNCONNPROCA")) { _ = LPOCNCONNPROCA; }
if (@hasDecl(@This(), "LPOCNCONNPROCW")) { _ = LPOCNCONNPROCW; }
if (@hasDecl(@This(), "LPOCNCHKPROC")) { _ = LPOCNCHKPROC; }
if (@hasDecl(@This(), "LPOCNDSCPROC")) { _ = LPOCNDSCPROC; }
@setEvalBranchQuota(
@import("std").meta.declarations(@This()).len * 3
);
// reference all the pub declarations
if (!@import("builtin").is_test) return;
inline for (@import("std").meta.declarations(@This())) |decl| {
if (decl.is_pub) {
_ = decl;
}
}
}
|
win32/security/credentials.zig
|
const std = @import("std");
pub const SRANDMEMBER = struct {
key: []const u8,
count: Count,
pub const Count = union(enum) {
One,
Count: usize,
pub const RedisArguments = struct {
pub fn count(self: Count) usize {
return switch (self) {
.One => 0,
.Count => 1,
};
}
pub fn serialize(self: Count, comptime rootSerializer: type, msg: anytype) !void {
switch (self) {
.One => {},
.Count => |c| {
try rootSerializer.serializeArgument(msg, usize, c);
},
}
}
};
};
/// Instantiates a new SPOP command.
pub fn init(key: []const u8, count: Count) SRANDMEMBER {
// TODO: support std.hashmap used as a set!
return .{ .key = key, .count = count };
}
/// Validates if the command is syntactically correct.
pub fn validate(self: SRANDMEMBER) !void {}
pub const RedisCommand = struct {
pub fn serialize(self: SRANDMEMBER, comptime rootSerializer: type, msg: anytype) !void {
return rootSerializer.serializeCommand(msg, .{
"SRANDMEMBER",
self.key,
self.count,
});
}
};
};
test "basic usage" {
const cmd = SRANDMEMBER.init("myset", .One);
try cmd.validate();
const cmd1 = SRANDMEMBER.init("myset", SRANDMEMBER.Count{ .Count = 5 });
try cmd1.validate();
}
test "serializer" {
const serializer = @import("../../serializer.zig").CommandSerializer;
var correctBuf: [1000]u8 = undefined;
var correctMsg = std.io.fixedBufferStream(correctBuf[0..]);
var testBuf: [1000]u8 = undefined;
var testMsg = std.io.fixedBufferStream(testBuf[0..]);
{
{
correctMsg.reset();
testMsg.reset();
try serializer.serializeCommand(
testMsg.outStream(),
SRANDMEMBER.init("s", .One),
);
try serializer.serializeCommand(
correctMsg.outStream(),
.{ "SRANDMEMBER", "s" },
);
// std.debug.warn("{}\n\n\n{}\n", .{ correctMsg.getWritten(), testMsg.getWritten() });
std.testing.expectEqualSlices(u8, correctMsg.getWritten(), testMsg.getWritten());
}
{
correctMsg.reset();
testMsg.reset();
try serializer.serializeCommand(
testMsg.outStream(),
SRANDMEMBER.init("s", SRANDMEMBER.Count{ .Count = 5 }),
);
try serializer.serializeCommand(
correctMsg.outStream(),
.{ "SRANDMEMBER", "s", 5 },
);
// std.debug.warn("{}\n\n\n{}\n", .{ correctMsg.getWritten(), testMsg.getWritten() });
std.testing.expectEqualSlices(u8, correctMsg.getWritten(), testMsg.getWritten());
}
}
}
|
src/commands/sets/srandmember.zig
|
const std = @import("std");
const DebugAllocator = @This();
fn toMB(value: var) f64 {
return switch (@TypeOf(value)) {
f64 => value / (1024 * 1024),
else => @intToFloat(f64, value) / (1024 * 1024),
};
}
const Stats = struct {
mean: f64 = 0,
mean_of_squares: f64 = 0,
total: usize = 0,
count: usize = 0,
fn addSample(self: *Stats, value: usize) void {
const count_f64 = @intToFloat(f64, self.count);
self.mean = (self.mean * count_f64 + @intToFloat(f64, value)) / (count_f64 + 1);
self.mean_of_squares = (self.mean_of_squares * count_f64 + @intToFloat(f64, value * value)) / (count_f64 + 1);
self.total += value;
self.count += 1;
}
fn stdDev(self: Stats) f64 {
return std.math.sqrt(self.mean_of_squares - self.mean * self.mean);
}
};
pub const AllocationInfo = struct {
allocation_stats: Stats = Stats{},
deallocation_count: usize = 0,
deallocation_total: usize = 0,
reallocation_stats: Stats = Stats{},
shrink_stats: Stats = Stats{},
pub fn format(
self: AllocationInfo,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
out_stream: var,
) !void {
@setEvalBranchQuota(2000);
// TODO: Make these behave like {Bi}, which doesnt work on floating point numbers.
return std.fmt.format(
out_stream,
\\------------------------------------------ Allocation info ------------------------------------------
\\{} total allocations (total: {d:.2} MB, mean: {d:.2} MB, std. dev: {d:.2} MB), {} deallocations
\\{} current allocations ({d:.2} MB)
\\{} reallocations (total: {d:.2} MB, mean: {d:.2} MB, std. dev: {d:.2} MB)
\\{} shrinks (total: {d:.2} MB, mean: {d:.2} MB, std. dev: {d:.2} MB)
\\-----------------------------------------------------------------------------------------------------
,
.{
self.allocation_stats.count,
toMB(self.allocation_stats.total),
toMB(self.allocation_stats.mean),
toMB(self.allocation_stats.stdDev()),
self.deallocation_count,
self.allocation_stats.count - self.deallocation_count,
toMB(self.allocation_stats.total + self.reallocation_stats.total - self.deallocation_total - self.shrink_stats.total),
self.reallocation_stats.count,
toMB(self.reallocation_stats.total),
toMB(self.reallocation_stats.mean),
toMB(self.reallocation_stats.stdDev()),
self.shrink_stats.count,
toMB(self.shrink_stats.total),
toMB(self.shrink_stats.mean),
toMB(self.shrink_stats.stdDev()),
},
);
}
};
base_allocator: *std.mem.Allocator,
info: AllocationInfo,
// Interface implementation
allocator: std.mem.Allocator,
pub fn init(base_allocator: *std.mem.Allocator) DebugAllocator {
return .{
.base_allocator = base_allocator,
.info = .{},
.allocator = .{
.reallocFn = realloc,
.shrinkFn = shrink,
},
};
}
fn realloc(allocator: *std.mem.Allocator, old_mem: []u8, old_align: u29, new_size: usize, new_align: u29) ![]u8 {
const self = @fieldParentPtr(DebugAllocator, "allocator", allocator);
var data = try self.base_allocator.reallocFn(self.base_allocator, old_mem, old_align, new_size, new_align);
if (old_mem.len == 0) {
self.info.allocation_stats.addSample(new_size);
} else if (new_size > old_mem.len) {
self.info.reallocation_stats.addSample(new_size - old_mem.len);
} else if (new_size < old_mem.len) {
self.info.shrink_stats.addSample(old_mem.len - new_size);
}
return data;
}
fn shrink(allocator: *std.mem.Allocator, old_mem: []u8, old_align: u29, new_size: usize, new_align: u29) []u8 {
const self = @fieldParentPtr(DebugAllocator, "allocator", allocator);
if (new_size == 0) {
if (self.info.allocation_stats.count == self.info.deallocation_count) {
@panic("error - too many calls to free, most likely double free");
}
self.info.deallocation_total += old_mem.len;
self.info.deallocation_count += 1;
} else if (new_size < old_mem.len) {
self.info.shrink_stats.addSample(old_mem.len - new_size);
} else if (new_size > old_mem.len) {
@panic("error - trying to shrink to a bigger size");
}
return self.base_allocator.shrinkFn(self.base_allocator, old_mem, old_align, new_size, new_align);
}
|
src/debug_allocator.zig
|
const std = @import("std");
const warn = std.debug.warn;
const CanonicalHuffmanTree = @import("./huffman.zig").CanonicalHuffmanTree;
pub fn BlockTree(comptime InputBitStream: type) type {
return struct {
const Self = @This();
lit_tree: CanonicalHuffmanTree(u4, u9, 31 + 257),
dist_tree: CanonicalHuffmanTree(u4, u5, 31 + 1),
pub fn makeStatic() Self {
// FIXME: zig fmt seems to ignore these comments --GM
// zig fmt: off
const lit_table = (([_]u4{8} ** (144 - 0)) ++ ([_]u4{9} ** (256 - 144)) ++ ([_]u4{7} ** (280 - 256)) ++ ([_]u4{8} ** (288 - 280)));
// zig fmt: on
const lit_tree = CanonicalHuffmanTree(u4, u9, 31 + 257).fromLengths(&lit_table);
const dist_table = [_]u4{5} ** 32;
const dist_tree = CanonicalHuffmanTree(u4, u5, 31 + 1).fromLengths(&dist_table);
return Self{
.lit_tree = lit_tree,
.dist_tree = dist_tree,
};
}
pub fn fromBitStream(stream: *InputBitStream) !Self {
const raw_hlit: u5 = try stream.readBitsNoEof(u5, 5);
const raw_hdist: u5 = try stream.readBitsNoEof(u5, 5);
const raw_hclen: u4 = try stream.readBitsNoEof(u4, 4);
// Convert to their real values
const real_hclen: u5 = @intCast(u5, raw_hclen) + 4;
const real_hdist: u6 = @intCast(u6, raw_hdist) + 1;
const real_hlit: u9 = @intCast(u9, raw_hlit) + 257;
//warn("HLIT = {} -> {}\n", raw_hlit, real_hlit);
//warn("HDIST = {} -> {}\n", raw_hdist, real_hdist);
//warn("HCLEN = {} -> {}\n", raw_hclen, real_hclen);
var clen_table: [15 + 4]u3 = [_]u3{0} ** (15 + 4);
const clen_remap: [15 + 4]u5 = [_]u5{
16, 17, 18, 0, 8,
7, 9, 6, 10, 5,
11, 4, 12, 3, 13,
2, 14, 1, 15,
};
// Parse the code length table
{
var i: u5 = 0;
while (i < real_hclen) : (i += 1) {
const k: u5 = clen_remap[i];
const v: u3 = try stream.readBitsNoEof(u3, 3);
clen_table[k] = v;
//warn("clen {} = {}\n", k, v);
}
}
// Build a canonical huffman tree
var clen_tree = CanonicalHuffmanTree(u3, u5, 15 + 4).fromLengths(&clen_table);
// Read literal tree
var lit_table: [31 + 257]u4 = [_]u4{0} ** (31 + 257);
{
var i: u9 = 0;
var prev: u4 = undefined;
while (i < real_hlit) {
const v: u5 = try clen_tree.readFrom(stream);
//warn("hlit {} = {}\n", i, v);
switch (v) {
// Copy previous 3+u2 times
16 => {
// Can't copy a previous value if it's not there
if (i < 1) {
return error.Failed;
}
const times: usize = 3 + try stream.readBitsNoEof(u2, 2);
var j: usize = 0;
while (j < times) : (j += 1) {
lit_table[i] = prev;
i += 1;
}
},
// Repeat 0 for 3+u3 times
17 => {
const times: usize = 3 + try stream.readBitsNoEof(u3, 3);
var j: usize = 0;
while (j < times) : (j += 1) {
lit_table[i] = 0;
i += 1;
}
},
// Repeat 0 for 11+u7 times
18 => {
const times: usize = 11 + try stream.readBitsNoEof(u7, 7);
var j: usize = 0;
while (j < times) : (j += 1) {
lit_table[i] = 0;
i += 1;
}
},
else => {
prev = @intCast(u4, v);
lit_table[i] = prev;
i += 1;
},
}
}
}
// Build another canonical huffman tree
const lit_tree = CanonicalHuffmanTree(u4, u9, 31 + 257).fromLengths(&lit_table);
// TODO: NOT COPY-PASTE THE ABOVE
// Read distance tree
var dist_table: [31 + 1]u4 = [_]u4{0} ** (31 + 1);
{
var i: u6 = 0;
var prev: u4 = undefined;
while (i < real_hdist) {
const v: u5 = try clen_tree.readFrom(stream);
//warn("hdist {} = {}\n", i, v);
switch (v) {
// Copy previous 3+u2 times
16 => {
// Can't copy a previous value if it's not there
if (i < 1) {
return error.Failed;
}
const times: usize = 3 + try stream.readBitsNoEof(u2, 2);
var j: usize = 0;
while (j < times) : (j += 1) {
dist_table[i] = prev;
i += 1;
}
},
// Repeat 0 for 3+u3 times
17 => {
const times: usize = 3 + try stream.readBitsNoEof(u3, 3);
var j: usize = 0;
while (j < times) : (j += 1) {
dist_table[i] = 0;
i += 1;
}
},
// Repeat 0 for 11+u7 times
18 => {
const times: usize = 11 + try stream.readBitsNoEof(u7, 7);
var j: usize = 0;
while (j < times) : (j += 1) {
dist_table[i] = 0;
i += 1;
}
},
else => {
prev = @intCast(u4, v);
dist_table[i] = prev;
i += 1;
},
}
}
}
// Build another canonical huffman tree
const dist_tree = CanonicalHuffmanTree(u4, u5, 31 + 1).fromLengths(&dist_table);
return Self{
.lit_tree = lit_tree,
.dist_tree = dist_tree,
};
}
pub fn readLitFrom(self: *Self, stream: *InputBitStream) !u9 {
return try self.lit_tree.readFrom(stream);
}
pub fn readDistFrom(self: *Self, stream: *InputBitStream) !u5 {
return try self.dist_tree.readFrom(stream);
}
};
}
|
src/block_tree.zig
|
const std = @import("std");
const os = @import("root").os;
var debug_allocator_bytes: [1024 * 1024]u8 = undefined;
var debug_allocator_state = std.heap.FixedBufferAllocator.init(debug_allocator_bytes[0..]);
pub const debug_allocator = &debug_allocator_state.allocator;
extern var __debug_info_start: u8;
extern var __debug_info_end: u8;
extern var __debug_abbrev_start: u8;
extern var __debug_abbrev_end: u8;
extern var __debug_str_start: u8;
extern var __debug_str_end: u8;
extern var __debug_line_start: u8;
extern var __debug_line_end: u8;
extern var __debug_ranges_start: u8;
extern var __debug_ranges_end: u8;
var debug_info = std.dwarf.DwarfInfo{
.endian = std.builtin.endian,
.debug_info = undefined,
.debug_abbrev = undefined,
.debug_str = undefined,
.debug_line = undefined,
.debug_ranges = undefined,
};
var inited_debug_info = false;
fn init_debug_info() void {
if (!inited_debug_info) {
//debug_info.debug_info = slice_section(&__debug_info_start, &__debug_info_end);
//debug_info.debug_abbrev = slice_section(&__debug_abbrev_start, &__debug_abbrev_end);
//debug_info.debug_str = slice_section(&__debug_str_start, &__debug_str_end);
//debug_info.debug_line = slice_section(&__debug_line_start, &__debug_line_end);
//debug_info.debug_ranges = slice_section(&__debug_ranges_start, &__debug_ranges_end);
os.log("Opening debug info\n", .{});
std.dwarf.openDwarfDebugInfo(&debug_info, debug_allocator) catch |err| {
os.log("Unable to open debug info: {s}\n", .{@errorName(err)});
return;
};
os.log("Opened debug info\n", .{});
inited_debug_info = true;
}
}
pub fn dump_frame(bp: usize, ip: usize) void {
os.log("Dumping ip=0x{x}, bp=0x{x}\n", .{ ip, bp });
init_debug_info();
print_addr(ip);
//var it = std.debug.StackIterator.init(null, bp);
//while (it.next()) |addr| {
// print_addr(ip);
//}
}
pub fn dump_stack_trace(trace: *std.builtin.StackTrace) void {
init_debug_info();
for (trace.instruction_addresses[trace.index..]) |addr| {
print_addr(addr);
}
}
fn slice_section(start: *u8, end: *u8) []const u8 {
const s = @ptrToInt(start);
const e = @ptrToInt(end);
return @intToPtr([*]const u8, s)[0 .. e - s];
}
fn print_addr(ip: usize) void {
var compile_unit = debug_info.findCompileUnit(ip) catch |err| {
os.log("Couldn't find the compile unit at {x}: {s}\n", .{ ip, @errorName(err) });
return;
};
var line_info = debug_info.getLineNumberInfo(compile_unit.*, ip) catch |err| {
os.log("Couldn't find the line info at {x}: {s}\n", .{ ip, @errorName(err) });
return;
};
print_info(line_info, ip, debug_info.getSymbolName(ip));
}
fn print_info(line_info: std.debug.LineInfo, ip: usize, symbol_name: ?[]const u8) void {}
|
src/lib/debug.zig
|
const std = @import("std");
const lib = @import("lib.zig");
const mem = std.mem;
const fmt = std.fmt;
const meta = std.meta;
const testing = std.testing;
const Allocator = std.mem.Allocator;
const Reactor = std.x.os.Reactor;
const Session = lib.Session;
const XAuth = lib.XAuth;
const request = lib.request;
const Client = struct {
stream: std.net.Stream,
session: Session,
pub fn init(gpa: *Allocator) !Client {
var it = try lib.XAuth.init(gpa);
defer it.deinit(gpa);
// TODO: fix
const auth = (try it.next()) orelse return error.NotAuthFound;
var buffer: [4096]u8 = undefined;
const req = try auth.request(&buffer);
const Header = extern struct {
status: Status,
unused: u8,
major: u16,
minor: u16,
length: u16,
pub const Status = enum(u8) {
setup_faied,
ok,
authenticate,
_,
};
};
const stream = try std.net.connectUnixSocket("/tmp/.X11-unix/X0");
const writer = stream.writer();
const reader = stream.reader();
try writer.writeAll(req);
const header = try reader.readStruct(Header);
const bytes = try gpa.allocAdvanced(u8, 4, header.length * 4, .exact);
try reader.readNoEof(bytes);
return Client{
.stream = stream,
.session = Session{ .bytes = bytes },
};
}
pub fn deinit(self: *Client, gpa: *Allocator) void {
self.stream.close();
self.session.deinit(gpa);
}
pub fn App(comptime T: type) type {
return struct {
client: *Client,
application: T,
const Self = @This();
pub fn call(self: *Self, event: Reactor.Event) !void {
_ = event; // TODO: handle failure
const reader = self.client.stream.reader();
const bytes = try reader.readBytesNoEof(32);
switch (bytes[0]) {
0 => try self.dispatchErrorHandler(bytes),
1 => @panic("oh yes"), // reponse
2...34 => try self.dispatchEventHandler(bytes),
else => unreachable,
}
}
fn dispatchErrorHandler(self: *Self, event: [32]u8) !void {
_ = self;
std.log.err("{}", .{@bitCast(request.Error, event)});
return error.Error;
}
fn dispatchEventHandler(self: *Self, event: [32]u8) !void {
_ = self;
const C = T;
switch (@intToEnum(request.Event, event[0])) {
.key_press => if (@hasDecl(C, "keyPressCallback"))
try self.application.keyPressCallback(),
.key_release => if (@hasDecl(C, "keyReleaseCallback"))
try self.application.keyReleaseCallback(),
.button_press => if (@hasDecl(C, "buttonPressCallback"))
try self.application.buttonPressCallback(),
.button_release => if (@hasDecl(C, "buttonReleaseCallback"))
try self.application.button_releaseCallback(),
.motion_notify => if (@hasDecl(C, "motionNotifyCallback"))
try self.application.motion_notifyCallback(),
.enter_notify => if (@hasDecl(C, "enterNotifyCallback"))
try self.application.enter_notifyCallback(),
.leave_notify => if (@hasDecl(C, "leaveNotifyCallback"))
try self.application.leave_notifyCallback(),
.focus_in => if (@hasDecl(C, "focusInCallback"))
try self.application.focus_inCallback(),
.focus_out => if (@hasDecl(C, "focusOutCallback"))
try self.application.focus_outCallback(),
.keymap_notify => if (@hasDecl(C, "keymapNotifyCallback"))
try self.application.keymap_notifyCallback(),
.expose => if (@hasDecl(C, "expose"))
try self.application.exposeCallback(),
.graphics_exposure => if (@hasDecl(C, "graphicsExposureCallback"))
try self.application.graphics_exposureCallback(),
.no_exposure => if (@hasDecl(C, "noExposureCallback"))
try self.application.no_exposureCallback(),
.visibility_notify => if (@hasDecl(C, "visibilityNotifyCallback"))
try self.application.visibility_notifyCallback(),
.create_notify => if (@hasDecl(C, "createNotifyCallback"))
try self.application.create_notifyCallback(),
.destroy_notify => if (@hasDecl(C, "destroyNotifyCallback"))
try self.application.destroy_notifyCallback(),
.unmap_notify => if (@hasDecl(C, "unmapNotifyCallback"))
try self.application.unmap_notifyCallback(),
.map_notify => if (@hasDecl(C, "mapNotifyCallback"))
try self.application.map_notifyCallback(),
.map_request => if (@hasDecl(C, "mapRequestCallback"))
try self.application.map_requestCallback(),
.reparent_notify => if (@hasDecl(C, "reparentNotifyCallback"))
try self.application.reparent_notifyCallback(),
.configure_notify => if (@hasDecl(C, "configureNotifyCallback"))
try self.application.configure_notifyCallback(),
.configure_request => if (@hasDecl(C, "configureRequestCallback"))
try self.application.configure_requestCallback(),
.gravity_notify => if (@hasDecl(C, "gravityNotifyCallback"))
try self.application.gravity_notifyCallback(),
.resize_request => if (@hasDecl(C, "resizeRequestCallback"))
try self.application.resize_requestCallback(),
.circulate_notify => if (@hasDecl(C, "circulateNotifyCallback"))
try self.application.circulate_notifyCallback(),
.circulate_request => if (@hasDecl(C, "circulateRequestCallback"))
try self.application.circulate_requestCallback(),
.property_notify => if (@hasDecl(C, "propertyNotifyCallback"))
try self.application.property_notifyCallback(),
.selection_clear => if (@hasDecl(C, "selectionClearCallback"))
try self.application.selection_clearCallback(),
.selection_request => if (@hasDecl(C, "selectionRequestCallback"))
try self.application.selection_requestCallback(),
.selection_notify => if (@hasDecl(C, "selectionNotifyCallback"))
try self.application.selection_notifyCallback(),
.colormap_notify => if (@hasDecl(C, "colormapNotifyCallback"))
try self.application.colormap_notifyCallback(),
.client_message => if (@hasDecl(C, "clientMessageCallback"))
try self.application.client_messageCallback(),
.mapping_notify => if (@hasDecl(C, "mappingNotifyCallback"))
try self.application.mapping_notifyCallback(),
}
}
};
}
pub fn app(self: *Client, application: anytype) App(@TypeOf(application)) {
return .{
.client = self,
.application = application,
};
}
};
const Async = struct {
queue: Queue,
const Queue = std.TailQueue(Entry);
const Entry = struct {
frame: anyframe,
sequence: u16,
opcode: request.Opcode,
result: usize,
};
// resume a suspended function
fn resumeCallback(self: *Async, sequence: u16) ?*Entry {
var node = self.queue.first;
while (node != null) {
const curr = node.?;
if (curr.data.sequence == sequence) {
if (curr.prev) |prev| prev.next = curr.next;
if (curr.next) |next| next.prev = curr.prev;
return node.data;
}
node = node.next();
}
return null;
}
// forwarded callbacks
pub fn keyPressCallback(_: *Async) !void {}
pub fn keyReleaseCallback(_: *Async) !void {}
// handled callbacks
pub fn mapNotifyCallback(_: *Async) !void {}
pub fn createNotifyCallback(_: *Async) !void {
const entry = self.resumeCallback(sequence) orelse return error.NoCallbackFound;
const loc = @intToPtr(*void, entry.result);
loc.* = .{}; // write some data
resume entry.frame;
}
pub fn destroyNotifyCallback(_: *Async) !void {}
};
test {
const gpa = testing.allocator;
var client = try Client.init(gpa);
defer client.deinit(gpa);
var thing: Thing = .{};
var app = client.app(thing);
const setup = client.session.setup();
const screen = client.session.screens().next().?;
const writer = client.stream.writer();
var e: request.ChangeWindowAttributes = .{
.window = screen.root,
.length = 4,
.value_mask = .{ .event_mask = true },
};
const w: request.CreateWindowRequest = .{
.window = @intToEnum(lib.types.Window, setup.resource_id_base),
.parent = screen.root,
.depth = screen.root_depth,
.x = 0,
.y = 0,
.width = 100,
.height = 100,
.class = 0,
.visual = screen.root_visual,
.value_mask = .{},
};
std.log.info("{}", .{w});
const m: request.MapWindowRequest = .{
.window = @intToEnum(lib.types.Window, setup.resource_id_base),
};
std.log.info("{}", .{m});
var reactor = try Reactor.init(.{ .close_on_exec = true });
try reactor.update(client.stream.handle, @intCast(usize, client.stream.handle), .{
.readable = true,
});
//try writer.writeAll(mem.asBytes(&e));
//try writer.writeIntLittle(u32, @bitCast(u32, request.EventMask{
//.structure_notify = true,
//.substructure_notify = true,
//.property_change = true,
//}));
_ = e;
try reactor.poll(2, &app, 100); // root
try writer.writeAll(mem.asBytes(&w));
try reactor.poll(2, &app, 100); // window
try writer.writeAll(mem.asBytes(&m));
try reactor.poll(2, &app, 100); // map
}
const Thing = struct {};
|
src/main.zig
|
const std = @import("std");
pub fn main() anyerror!void {
//std.debug.warn("All your base are belong to us.\n");
// If this program is run without stdin or stdout attached, exit with an error.
const stdin_file = std.io.getStdIn();
const out = std.io.getStdOut().outStream();
var buffer: [1000]u8 = undefined;
var read_bytes = try stdin_file.read(buffer[0..]);
var accumulator: u128 = 0;
while (read_bytes > 0) : (read_bytes = try stdin_file.read(buffer[0..])) {
for (buffer[0..(read_bytes - 1)]) |c| {
switch (c) {
'h', 'H' => {
try out.writeAll("Hello, world!\n");
},
'q', 'Q' => {
try out.writeAll(buffer[0..(read_bytes - 1)]);
try out.writeAll("\n");
},
'9' => {
var bottles: u8 = 99;
var text_buffer: [16]u8 = "99 bottles".* ++ [_]u8{0} ** 6;
var text = text_buffer[0..10];
while (bottles > 0) {
// If this program encounters pipe failure when printing to stdout,
// exit with an error.
try out.print("{} of beer on the wall, ", .{text});
try out.print("{} of beer.\n", .{text});
try out.writeAll("Take one down and pass it around, ");
bottles -= 1;
_ = switch (bottles) {
0 => try std.fmt.bufPrint(text_buffer[0..], "{} bottles", .{"no more"}),
1 => try std.fmt.bufPrint(text_buffer[0..], "{} bottle", .{bottles}),
else => try std.fmt.bufPrint(text_buffer[0..], "{} bottles", .{bottles}),
};
try out.print("{} of beer on the wall.\n\n", .{text});
}
try out.print("{} bottles of beer on the wall, ", .{"No more"});
try out.print("{} bottles of beer.\n", .{"no more"});
try out.writeAll("Go to the store and buy some more, ");
try out.print("{} bottles of beer on the wall.\n\n", .{99});
},
'+' => {
accumulator += 1;
},
else => {},
}
}
}
}
|
003-hq9+/src/main.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const print = std.debug.print;
const data = @embedFile("data/day11.txt");
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const ally = &arena.allocator;
var width = std.mem.indexOf(u8, data, "\n").?;
var pitch = width + 1;
var height = data.len / width;
// allocate our buffers. Data for (x, y) is at index
// pitch + 1 + y*pitch + x. There is an extra line before
// and after the buffer, which allows us to safely read
// "out of bounds" of the problem.
const a = try ally.alloc(u8, data.len + 2*pitch + 2);
const b = try ally.alloc(u8, data.len + 2*pitch + 2);
std.mem.set(u8, a, '.');
std.mem.set(u8, b, '.');
a[width+1] = '\n';
b[width+1] = '\n';
const ipitch = @intCast(isize, pitch);
// 8 directions
const directions = [_]isize{
-ipitch-1, -ipitch, -ipitch+1,
-1, 1,
ipitch-1, ipitch, ipitch+1,
};
std.mem.copy(u8, a[pitch + 1..], data);
const count1 = simulateToCompletion(check, 4, &directions, a, b);
std.mem.copy(u8, a[pitch + 1..], data);
const count2 = simulateToCompletion(scan, 5, &directions, a, b);
print("part1: {}, part2: {}\n", .{count1, count2});
}
fn simulateToCompletion(
comptime checkFunc: fn([]const u8, usize, isize)bool,
comptime tolerance: comptime_int,
directions: []const isize,
a: []u8,
b: []u8,
) usize {
var prev = a;
var next = b;
var running = true;
while (running) {
running = false;
// the buffers retain their newlines, so we can just print them directly.
// print("iter\n{}\n\n\n", .{prev});
for (prev) |c, i| {
if (c == 'L' or c == '#') {
var occ: u32 = 0;
for (directions) |d| {
occ += @boolToInt(checkFunc(prev, i, d));
}
next[i] = if (c == 'L' and occ == 0) '#' else if (c == '#' and occ >= tolerance) 'L' else c;
running = running or next[i] != c;
} else {
next[i] = c;
}
}
var tmp = prev;
prev = next;
next = tmp;
}
var count: usize = 0;
for (prev) |c| {
if (c == '#') count += 1;
}
return count;
}
fn check(d: []const u8, pos: usize, dir: isize) bool {
const idx = @intCast(isize, pos) + dir;
return d[@intCast(usize, idx)] == '#';
}
fn scan(d: []const u8, pos: usize, dir: isize) bool {
var curr = @intCast(isize, pos) + dir;
while (curr >= 0 and curr < @intCast(isize, d.len)) {
const ucurr = @intCast(usize, curr);
if (d[ucurr] == '\n') return false; // detect wraparound
if (d[ucurr] == '#') return true;
if (d[ucurr] == 'L') return false;
curr += dir;
}
return false;
}
|
src/day11.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const Metadata = @import("metadata.zig").Metadata;
const latin1ToUtf8 = @import("latin1.zig").latin1ToUtf8;
pub const id3v1_identifier = "TAG";
pub const tag_size = 128;
/// Assumes the stream cursor is at the end of the ID3v1 tag
pub fn read(allocator: Allocator, reader: anytype, seekable_stream: anytype) !Metadata {
var metadata: Metadata = Metadata.init(allocator);
errdefer metadata.deinit();
var metadata_map = &metadata.map;
var end_pos = try seekable_stream.getPos();
if (end_pos < tag_size) {
return error.EndOfStream;
}
const start_offset = end_pos - tag_size;
metadata.start_offset = start_offset;
metadata.end_offset = end_pos;
try seekable_stream.seekTo(start_offset);
const data = try reader.readBytesNoEof(tag_size);
if (!std.mem.eql(u8, data[0..3], id3v1_identifier)) {
return error.InvalidIdentifier;
}
const song_name = std.mem.trimRight(u8, std.mem.sliceTo(data[3..33], '\x00'), " ");
const artist = std.mem.trimRight(u8, std.mem.sliceTo(data[33..63], '\x00'), " ");
const album_name = std.mem.trimRight(u8, std.mem.sliceTo(data[63..93], '\x00'), " ");
const year = std.mem.trimRight(u8, std.mem.sliceTo(data[93..97], '\x00'), " ");
const comment = std.mem.trimRight(u8, std.mem.sliceTo(data[97..127], '\x00'), " ");
const could_be_v1_1 = data[125] == '\x00';
const track_num = data[126];
const genre = data[127];
// 60 is twice as large as the largest id3v1 field
var utf8_buf: [60]u8 = undefined;
if (song_name.len > 0) {
var utf8_song_name = latin1ToUtf8(song_name, &utf8_buf);
try metadata_map.put("title", utf8_song_name);
}
if (artist.len > 0) {
var utf8_artist = latin1ToUtf8(artist, &utf8_buf);
try metadata_map.put("artist", utf8_artist);
}
if (album_name.len > 0) {
var utf8_album_name = latin1ToUtf8(album_name, &utf8_buf);
try metadata_map.put("album", utf8_album_name);
}
if (year.len > 0) {
var utf8_year = latin1ToUtf8(year, &utf8_buf);
try metadata_map.put("date", utf8_year);
}
if (comment.len > 0) {
var utf8_comment = latin1ToUtf8(comment, &utf8_buf);
try metadata_map.put("comment", utf8_comment);
}
if (could_be_v1_1 and track_num > 0) {
var buf: [3]u8 = undefined;
const track_num_string = try std.fmt.bufPrint(buf[0..], "{}", .{track_num});
try metadata_map.put("track", track_num_string);
}
if (genre < id3v1_genre_names.len) {
try metadata_map.put("genre", id3v1_genre_names[genre]);
}
return metadata;
}
pub const id3v1_genre_names = [_][]const u8{
"Blues",
"Classic Rock",
"Country",
"Dance",
"Disco",
"Funk",
"Grunge",
"Hip-Hop",
"Jazz",
"Metal",
"New Age",
"Oldies",
"Other",
"Pop",
"R&B",
"Rap",
"Reggae",
"Rock",
"Techno",
"Industrial",
"Alternative",
"Ska",
"Death Metal",
"Pranks",
"Soundtrack",
"Euro-Techno",
"Ambient",
"Trip-Hop",
"Vocal",
"Jazz+Funk",
"Fusion",
"Trance",
"Classical",
"Instrumental",
"Acid",
"House",
"Game",
"Sound Clip",
"Gospel",
"Noise",
"AlternRock",
"Bass",
"Soul",
"Punk",
"Space",
"Meditative",
"Instrumental Pop",
"Instrumental Rock",
"Ethnic",
"Gothic",
"Darkwave",
"Techno-Industrial",
"Electronic",
"Pop-Folk",
"Eurodance",
"Dream",
"Southern Rock",
"Comedy",
"Cult",
"Gangsta",
"Top 40",
"Christian Rap",
"Pop/Funk",
"Jungle",
"Native American",
"Cabaret",
"New Wave",
"Psychedelic",
"Rave",
"Showtunes",
"Trailer",
"Lo-Fi",
"Tribal",
"Acid Punk",
"Acid Jazz",
"Polka",
"Retro",
"Musical",
"Rock & Roll",
"Hard Rock",
"Folk",
"Folk-Rock",
"National Folk",
"Swing",
"Fast Fusion",
"Bebop",
"Latin",
"Revival",
"Celtic",
"Bluegrass",
"Avantgarde",
"Gothic Rock",
"Progressive Rock",
"Psychedelic Rock",
"Symphonic Rock",
"Slow Rock",
"Big Band",
"Chorus",
"Easy Listening",
"Acoustic",
"Humour",
"Speech",
"Chanson",
"Opera",
"Chamber Music",
"Sonata",
"Symphony",
"Booty Bass",
"Primus",
"Porn Groove",
"Satire",
"Slow Jam",
"Club",
"Tango",
"Samba",
"Folklore",
"Ballad",
"Power Ballad",
"Rhythmic Soul",
"Freestyle",
"Duet",
"Punk Rock",
"Drum Solo",
"A Cappella",
"Euro-House",
"Dance Hall",
"Goa",
"Drum & Bass",
"Club-House",
"Hardcore Techno",
"Terror",
"Indie",
"BritPop",
"Negerpunk",
"Polsk Punk",
"Beat",
"Christian Gangsta Rap",
"Heavy Metal",
"Black Metal",
"Crossover",
"Contemporary Christian",
"Christian Rock",
"Merengue",
"Salsa",
"Thrash Metal",
"Anime",
"Jpop",
"Synthpop",
"Abstract",
"Art Rock",
"Baroque",
"Bhangra",
"Big Beat",
"Breakbeat",
"Chillout",
"Downtempo",
"Dub",
"EBM",
"Eclectic",
"Electro",
"Electroclash",
"Emo",
"Experimental",
"Garage",
"Global",
"IDM",
"Illbient",
"Industro-Goth",
"Jam Band",
"Krautrock",
"Leftfield",
"Lounge",
"Math Rock",
"New Romantic",
"Nu-Breakz",
"Post-Punk",
"Post-Rock",
"Psytrance",
"Shoegaze",
"Space Rock",
"Trop Rock",
"World Music",
"Neoclassical",
"Audiobook",
"Audio Theatre",
"Neue Deutsche Welle",
"Podcast",
"Indie Rock",
"G-Funk",
"Dubstep",
"Garage Rock",
"Psybient",
};
|
src/id3v1.zig
|
usingnamespace @import("bits.zig");
const std = @import("std");
const builtin = @import("builtin");
const assert = std.debug.assert;
const windows = @import("../windows.zig").windows;
const unexpectedError = std.os.windows.unexpectedError;
const GetLastError = windows.kernel32.GetLastError;
const SetLastError = windows.kernel32.SetLastError;
fn selectSymbol(comptime function_static: anytype, function_dynamic: @TypeOf(function_static), comptime os: std.Target.Os.WindowsVersion) @TypeOf(function_static) {
comptime {
const sym_ok = builtin.Target.current.os.isAtLeast(.windows, os);
if (sym_ok == true) return function_static;
if (sym_ok == null) return function_dynamic;
if (sym_ok == false) @compileError("Target OS range does not support function, at least " ++ @tagName(os) ++ " is required");
}
}
// === Messages ===
pub const WNDPROC = fn (hwnd: HWND, uMsg: UINT, wParam: WPARAM, lParam: LPARAM) callconv(WINAPI) LRESULT;
pub const MSG = extern struct {
hWnd: ?HWND,
message: UINT,
wParam: WPARAM,
lParam: LPARAM,
time: DWORD,
pt: POINT,
lPrivate: DWORD,
};
pub const CREATESTRUCTW = extern struct {
lpCreateParams: LPVOID,
hInstance: HINSTANCE,
hMenu: ?HMENU,
hwndParent: ?HWND,
cy: c_int,
cx: c_int,
y: c_int,
x: c_int,
style: LONG,
lpszName: LPCWSTR,
lpszClass: LPCWSTR,
dwExStyle: DWORD,
};
pub const WM = extern enum(u32) {
pub const WININICHANGE = @This().SETTINGCHANGE;
NULL = 0x0000,
CREATE = 0x0001,
DESTROY = 0x0002,
MOVE = 0x0003,
SIZE = 0x0005,
ACTIVATE = 0x0006,
SETFOCUS = 0x0007,
KILLFOCUS = 0x0008,
ENABLE = 0x000A,
SETREDRAW = 0x000B,
SETTEXT = 0x000C,
GETTEXT = 0x000D,
GETTEXTLENGTH = 0x000E,
PAINT = 0x000F,
CLOSE = 0x0010,
QUERYENDSESSION = 0x0011,
QUERYOPEN = 0x0013,
ENDSESSION = 0x0016,
QUIT = 0x0012,
ERASEBKGND = 0x0014,
SYSCOLORCHANGE = 0x0015,
SHOWWINDOW = 0x0018,
SETTINGCHANGE = 0x001A,
DEVMODECHANGE = 0x001B,
ACTIVATEAPP = 0x001C,
FONTCHANGE = 0x001D,
TIMECHANGE = 0x001E,
CANCELMODE = 0x001F,
SETCURSOR = 0x0020,
MOUSEACTIVATE = 0x0021,
CHILDACTIVATE = 0x0022,
QUEUESYNC = 0x0023,
GETMINMAXINFO = 0x0024,
PAINTICON = 0x0026,
ICONERASEBKGND = 0x0027,
NEXTDLGCTL = 0x0028,
SPOOLERSTATUS = 0x002A,
DRAWITEM = 0x002B,
MEASUREITEM = 0x002C,
DELETEITEM = 0x002D,
VKEYTOITEM = 0x002E,
CHARTOITEM = 0x002F,
SETFONT = 0x0030,
GETFONT = 0x0031,
SETHOTKEY = 0x0032,
GETHOTKEY = 0x0033,
QUERYDRAGICON = 0x0037,
COMPAREITEM = 0x0039,
GETOBJECT = 0x003D,
COMPACTING = 0x0041,
COMMNOTIFY = 0x0044,
WINDOWPOSCHANGING = 0x0046,
WINDOWPOSCHANGED = 0x0047,
POWER = 0x0048,
COPYDATA = 0x004A,
CANCELJOURNAL = 0x004B,
NOTIFY = 0x004E,
INPUTLANGCHANGEREQUEST = 0x0050,
INPUTLANGCHANGE = 0x0051,
TCARD = 0x0052,
HELP = 0x0053,
USERCHANGED = 0x0054,
NOTIFYFORMAT = 0x0055,
CONTEXTMENU = 0x007B,
STYLECHANGING = 0x007C,
STYLECHANGED = 0x007D,
DISPLAYCHANGE = 0x007E,
GETICON = 0x007F,
SETICON = 0x0080,
NCCREATE = 0x0081,
NCDESTROY = 0x0082,
NCCALCSIZE = 0x0083,
NCHITTEST = 0x0084,
NCPAINT = 0x0085,
NCACTIVATE = 0x0086,
GETDLGCODE = 0x0087,
SYNCPAINT = 0x0088,
NCMOUSEMOVE = 0x00A0,
NCLBUTTONDOWN = 0x00A1,
NCLBUTTONUP = 0x00A2,
NCLBUTTONDBLCLK = 0x00A3,
NCRBUTTONDOWN = 0x00A4,
NCRBUTTONUP = 0x00A5,
NCRBUTTONDBLCLK = 0x00A6,
NCMBUTTONDOWN = 0x00A7,
NCMBUTTONUP = 0x00A8,
NCMBUTTONDBLCLK = 0x00A9,
NCXBUTTONDOWN = 0x00AB,
NCXBUTTONUP = 0x00AC,
NCXBUTTONDBLCLK = 0x00AD,
INPUT_DEVICE_CHANGE = 0x00fe,
INPUT = 0x00FF,
KEYFIRST = 0x0100,
KEYDOWN = 0x0100,
KEYUP = 0x0101,
CHAR = 0x0102,
DEADCHAR = 0x0103,
SYSKEYDOWN = 0x0104,
SYSKEYUP = 0x0105,
SYSCHAR = 0x0106,
SYSDEADCHAR = 0x0107,
// Depends on windows version!
// UNICHAR = 0x0109,
// KEYLAST = 0x0109,
// KEYLAST = 0x0108,
IME_STARTCOMPOSITION = 0x010D,
IME_ENDCOMPOSITION = 0x010E,
IME_COMPOSITION = 0x010F,
IME_KEYLAST = 0x010F,
INITDIALOG = 0x0110,
COMMAND = 0x0111,
SYSCOMMAND = 0x0112,
TIMER = 0x0113,
HSCROLL = 0x0114,
VSCROLL = 0x0115,
INITMENU = 0x0116,
INITMENUPOPUP = 0x0117,
MENUSELECT = 0x011F,
GESTURE = 0x0119,
GESTURENOTIFY = 0x011A,
MENUCHAR = 0x0120,
ENTERIDLE = 0x0121,
MENURBUTTONUP = 0x0122,
MENUDRAG = 0x0123,
MENUGETOBJECT = 0x0124,
UNINITMENUPOPUP = 0x0125,
MENUCOMMAND = 0x0126,
CHANGEUISTATE = 0x0127,
UPDATEUISTATE = 0x0128,
QUERYUISTATE = 0x0129,
CTLCOLORMSGBOX = 0x0132,
CTLCOLOREDIT = 0x0133,
CTLCOLORLISTBOX = 0x0134,
CTLCOLORBTN = 0x0135,
CTLCOLORDLG = 0x0136,
CTLCOLORSCROLLBAR = 0x0137,
CTLCOLORSTATIC = 0x0138,
MOUSEFIRST = 0x0200,
MOUSEMOVE = 0x0200,
LBUTTONDOWN = 0x0201,
LBUTTONUP = 0x0202,
LBUTTONDBLCLK = 0x0203,
RBUTTONDOWN = 0x0204,
RBUTTONUP = 0x0205,
RBUTTONDBLCLK = 0x0206,
MBUTTONDOWN = 0x0207,
MBUTTONUP = 0x0208,
MBUTTONDBLCLK = 0x0209,
MOUSEWHEEL = 0x020A,
XBUTTONDOWN = 0x020B,
XBUTTONUP = 0x020C,
XBUTTONDBLCLK = 0x020D,
MOUSEHWHEEL = 0x020e,
// MOUSELAST = 0x020e,
// MOUSELAST = 0x020d,
// MOUSELAST = 0x020a,
// MOUSELAST = 0x0209,
PARENTNOTIFY = 0x0210,
ENTERMENULOOP = 0x0211,
EXITMENULOOP = 0x0212,
NEXTMENU = 0x0213,
SIZING = 0x0214,
CAPTURECHANGED = 0x0215,
MOVING = 0x0216,
POWERBROADCAST = 0x0218,
DEVICECHANGE = 0x0219,
MDICREATE = 0x0220,
MDIDESTROY = 0x0221,
MDIACTIVATE = 0x0222,
MDIRESTORE = 0x0223,
MDINEXT = 0x0224,
MDIMAXIMIZE = 0x0225,
MDITILE = 0x0226,
MDICASCADE = 0x0227,
MDIICONARRANGE = 0x0228,
MDIGETACTIVE = 0x0229,
MDISETMENU = 0x0230,
ENTERSIZEMOVE = 0x0231,
EXITSIZEMOVE = 0x0232,
DROPFILES = 0x0233,
MDIREFRESHMENU = 0x0234,
POINTERDEVICECHANGE = 0x238,
POINTERDEVICEINRANGE = 0x239,
POINTERDEVICEOUTOFRANGE = 0x23a,
TOUCH = 0x0240,
NCPOINTERUPDATE = 0x0241,
NCPOINTERDOWN = 0x0242,
NCPOINTERUP = 0x0243,
POINTERUPDATE = 0x0245,
POINTERDOWN = 0x0246,
POINTERUP = 0x0247,
POINTERENTER = 0x0249,
POINTERLEAVE = 0x024a,
POINTERACTIVATE = 0x024b,
POINTERCAPTURECHANGED = 0x024c,
TOUCHHITTESTING = 0x024d,
POINTERWHEEL = 0x024e,
POINTERHWHEEL = 0x024f,
POINTERROUTEDTO = 0x0251,
POINTERROUTEDAWAY = 0x0252,
POINTERROUTEDRELEASED = 0x0253,
IME_SETCONTEXT = 0x0281,
IME_NOTIFY = 0x0282,
IME_CONTROL = 0x0283,
IME_COMPOSITIONFULL = 0x0284,
IME_SELECT = 0x0285,
IME_CHAR = 0x0286,
IME_REQUEST = 0x0288,
IME_KEYDOWN = 0x0290,
IME_KEYUP = 0x0291,
MOUSEHOVER = 0x02A1,
MOUSELEAVE = 0x02A3,
NCMOUSEHOVER = 0x02A0,
NCMOUSELEAVE = 0x02A2,
WTSSESSION_CHANGE = 0x02B1,
TABLET_FIRST = 0x02c0,
TABLET_LAST = 0x02df,
DPICHANGED = 0x02e0,
DPICHANGED_BEFOREPARENT = 0x02e2,
DPICHANGED_AFTERPARENT = 0x02e3,
GETDPISCALEDSIZE = 0x02e4,
CUT = 0x0300,
COPY = 0x0301,
PASTE = 0x0302,
CLEAR = 0x0303,
UNDO = 0x0304,
RENDERFORMAT = 0x0305,
RENDERALLFORMATS = 0x0306,
DESTROYCLIPBOARD = 0x0307,
DRAWCLIPBOARD = 0x0308,
PAINTCLIPBOARD = 0x0309,
VSCROLLCLIPBOARD = 0x030A,
SIZECLIPBOARD = 0x030B,
ASKCBFORMATNAME = 0x030C,
CHANGECBCHAIN = 0x030D,
HSCROLLCLIPBOARD = 0x030E,
QUERYNEWPALETTE = 0x030F,
PALETTEISCHANGING = 0x0310,
PALETTECHANGED = 0x0311,
HOTKEY = 0x0312,
PRINT = 0x0317,
PRINTCLIENT = 0x0318,
APPCOMMAND = 0x0319,
THEMECHANGED = 0x031A,
CLIPBOARDUPDATE = 0x031d,
DWMCOMPOSITIONCHANGED = 0x031e,
DWMNCRENDERINGCHANGED = 0x031f,
DWMCOLORIZATIONCOLORCHANGED = 0x0320,
DWMWINDOWMAXIMIZEDCHANGE = 0x0321,
DWMSENDICONICTHUMBNAIL = 0x0323,
DWMSENDICONICLIVEPREVIEWBITMAP = 0x0326,
GETTITLEBARINFOEX = 0x033f,
HANDHELDFIRST = 0x0358,
HANDHELDLAST = 0x035F,
AFXFIRST = 0x0360,
AFXLAST = 0x037F,
PENWINFIRST = 0x0380,
PENWINLAST = 0x038F,
APP = 0x8000,
USER = 0x0400,
_,
};
pub extern "user32" fn GetMessageA(lpMsg: *MSG, hWnd: ?HWND, wMsgFilterMin: UINT, wMsgFilterMax: UINT) callconv(WINAPI) BOOL;
pub fn getMessageA(lpMsg: *MSG, hWnd: ?HWND, wMsgFilterMin: u32, wMsgFilterMax: u32) !void {
const r = GetMessageA(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax);
if (r == 0) return error.Quit;
if (r != -1) return;
switch (GetLastError()) {
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return unexpectedError(err),
}
}
pub extern "user32" fn GetMessageW(lpMsg: *MSG, hWnd: ?HWND, wMsgFilterMin: UINT, wMsgFilterMax: UINT) callconv(WINAPI) BOOL;
pub var pfnGetMessageW: @TypeOf(GetMessageW) = undefined;
pub fn getMessageW(lpMsg: *MSG, hWnd: ?HWND, wMsgFilterMin: u32, wMsgFilterMax: u32) !void {
const function = selectSymbol(GetMessageW, pfnGetMessageW, .win2k);
const r = function(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax);
if (r == 0) return error.Quit;
if (r != -1) return;
switch (GetLastError()) {
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return unexpectedError(err),
}
}
pub const PM_NOREMOVE = 0x0000;
pub const PM_REMOVE = 0x0001;
pub const PM_NOYIELD = 0x0002;
pub extern "user32" fn PeekMessageA(lpMsg: *MSG, hWnd: ?HWND, wMsgFilterMin: UINT, wMsgFilterMax: UINT, wRemoveMsg: UINT) callconv(WINAPI) BOOL;
pub fn peekMessageA(lpMsg: *MSG, hWnd: ?HWND, wMsgFilterMin: u32, wMsgFilterMax: u32, wRemoveMsg: u32) !bool {
const r = PeekMessageA(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax, wRemoveMsg);
if (r == 0) return false;
if (r != -1) return true;
switch (GetLastError()) {
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return unexpectedError(err),
}
}
pub extern "user32" fn PeekMessageW(lpMsg: *MSG, hWnd: ?HWND, wMsgFilterMin: UINT, wMsgFilterMax: UINT, wRemoveMsg: UINT) callconv(WINAPI) BOOL;
pub var pfnPeekMessageW: @TypeOf(PeekMessageW) = undefined;
pub fn peekMessageW(lpMsg: *MSG, hWnd: ?HWND, wMsgFilterMin: u32, wMsgFilterMax: u32, wRemoveMsg: u32) !bool {
const function = selectSymbol(PeekMessageW, pfnPeekMessageW, .win2k);
const r = function(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax, wRemoveMsg);
if (r == 0) return false;
if (r != -1) return true;
switch (GetLastError()) {
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return unexpectedError(err),
}
}
pub extern "user32" fn TranslateMessage(lpMsg: *const MSG) callconv(WINAPI) BOOL;
pub fn translateMessage(lpMsg: *const MSG) bool {
return if (TranslateMessage(lpMsg) == 0) false else true;
}
pub extern "user32" fn DispatchMessageA(lpMsg: *const MSG) callconv(WINAPI) LRESULT;
pub fn dispatchMessageA(lpMsg: *const MSG) LRESULT {
return DispatchMessageA(lpMsg);
}
pub extern "user32" fn DispatchMessageW(lpMsg: *const MSG) callconv(WINAPI) LRESULT;
pub var pfnDispatchMessageW: @TypeOf(DispatchMessageW) = undefined;
pub fn dispatchMessageW(lpMsg: *const MSG) LRESULT {
const function = selectSymbol(DispatchMessageW, pfnDispatchMessageW, .win2k);
return function(lpMsg);
}
pub extern "user32" fn PostQuitMessage(nExitCode: i32) callconv(WINAPI) void;
pub fn postQuitMessage(nExitCode: i32) void {
PostQuitMessage(nExitCode);
}
pub extern "user32" fn DefWindowProcA(hWnd: HWND, Msg: UINT, wParam: WPARAM, lParam: LPARAM) callconv(WINAPI) LRESULT;
pub fn defWindowProcA(hWnd: HWND, Msg: UINT, wParam: WPARAM, lParam: LPARAM) LRESULT {
return DefWindowProcA(hWnd, Msg, wParam, lParam);
}
pub extern "user32" fn DefWindowProcW(hWnd: HWND, Msg: UINT, wParam: WPARAM, lParam: LPARAM) callconv(WINAPI) LRESULT;
pub var pfnDefWindowProcW: @TypeOf(DefWindowProcW) = undefined;
pub fn defWindowProcW(hWnd: HWND, Msg: UINT, wParam: WPARAM, lParam: LPARAM) LRESULT {
const function = selectSymbol(DefWindowProcW, pfnDefWindowProcW, .win2k);
return function(hWnd, Msg, wParam, lParam);
}
// === Windows ===
pub const CS_VREDRAW = 0x0001;
pub const CS_HREDRAW = 0x0002;
pub const CS_DBLCLKS = 0x0008;
pub const CS_OWNDC = 0x0020;
pub const CS_CLASSDC = 0x0040;
pub const CS_PARENTDC = 0x0080;
pub const CS_NOCLOSE = 0x0200;
pub const CS_SAVEBITS = 0x0800;
pub const CS_BYTEALIGNCLIENT = 0x1000;
pub const CS_BYTEALIGNWINDOW = 0x2000;
pub const CS_GLOBALCLASS = 0x4000;
pub const WNDCLASSEXA = extern struct {
cbSize: UINT = @sizeOf(WNDCLASSEXA),
style: UINT,
lpfnWndProc: WNDPROC,
cbClsExtra: i32 = 0,
cbWndExtra: i32 = 0,
hInstance: HINSTANCE,
hIcon: ?HICON,
hCursor: ?HCURSOR,
hbrBackground: ?HBRUSH,
lpszMenuName: ?[*:0]const u8,
lpszClassName: [*:0]const u8,
hIconSm: ?HICON,
};
pub const WNDCLASSEXW = extern struct {
cbSize: UINT = @sizeOf(WNDCLASSEXW),
style: UINT,
lpfnWndProc: WNDPROC,
cbClsExtra: i32 = 0,
cbWndExtra: i32 = 0,
hInstance: HINSTANCE,
hIcon: ?HICON,
hCursor: ?HCURSOR,
hbrBackground: ?HBRUSH,
lpszMenuName: ?[*:0]const u16,
lpszClassName: [*:0]const u16,
hIconSm: ?HICON,
};
pub extern "user32" fn RegisterClassExA(*const WNDCLASSEXA) callconv(WINAPI) ATOM;
pub fn registerClassExA(window_class: *const WNDCLASSEXA) !ATOM {
const atom = RegisterClassExA(window_class);
if (atom != 0) return atom;
switch (GetLastError()) {
.CLASS_ALREADY_EXISTS => return error.AlreadyExists,
.INVALID_PARAMETER => unreachable,
else => |err| return unexpectedError(err),
}
}
pub extern "user32" fn RegisterClassExW(*const WNDCLASSEXW) callconv(WINAPI) ATOM;
pub var pfnRegisterClassExW: @TypeOf(RegisterClassExW) = undefined;
pub fn registerClassExW(window_class: *const WNDCLASSEXW) !ATOM {
const function = selectSymbol(RegisterClassExW, pfnRegisterClassExW, .win2k);
const atom = function(window_class);
if (atom != 0) return atom;
switch (GetLastError()) {
.CLASS_ALREADY_EXISTS => return error.AlreadyExists,
.CALL_NOT_IMPLEMENTED => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return unexpectedError(err),
}
}
pub extern "user32" fn UnregisterClassA(lpClassName: [*:0]const u8, hInstance: HINSTANCE) callconv(WINAPI) BOOL;
pub fn unregisterClassA(lpClassName: [*:0]const u8, hInstance: HINSTANCE) !void {
if (UnregisterClassA(lpClassName, hInstance) == 0) {
switch (GetLastError()) {
.CLASS_DOES_NOT_EXIST => return error.ClassDoesNotExist,
else => |err| return unexpectedError(err),
}
}
}
pub extern "user32" fn UnregisterClassW(lpClassName: [*:0]const u16, hInstance: HINSTANCE) callconv(WINAPI) BOOL;
pub var pfnUnregisterClassW: @TypeOf(UnregisterClassW) = undefined;
pub fn unregisterClassW(lpClassName: [*:0]const u16, hInstance: HINSTANCE) !void {
const function = selectSymbol(UnregisterClassW, pfnUnregisterClassW, .win2k);
if (function(lpClassName, hInstance) == 0) {
switch (GetLastError()) {
.CLASS_DOES_NOT_EXIST => return error.ClassDoesNotExist,
else => |err| return unexpectedError(err),
}
}
}
pub const WS_OVERLAPPED = 0x00000000;
pub const WS_POPUP = 0x80000000;
pub const WS_CHILD = 0x40000000;
pub const WS_MINIMIZE = 0x20000000;
pub const WS_VISIBLE = 0x10000000;
pub const WS_DISABLED = 0x08000000;
pub const WS_CLIPSIBLINGS = 0x04000000;
pub const WS_CLIPCHILDREN = 0x02000000;
pub const WS_MAXIMIZE = 0x01000000;
pub const WS_CAPTION = WS_BORDER | WS_DLGFRAME;
pub const WS_BORDER = 0x00800000;
pub const WS_DLGFRAME = 0x00400000;
pub const WS_VSCROLL = 0x00200000;
pub const WS_HSCROLL = 0x00100000;
pub const WS_SYSMENU = 0x00080000;
pub const WS_THICKFRAME = 0x00040000;
pub const WS_GROUP = 0x00020000;
pub const WS_TABSTOP = 0x00010000;
pub const WS_MINIMIZEBOX = 0x00020000;
pub const WS_MAXIMIZEBOX = 0x00010000;
pub const WS_TILED = WS_OVERLAPPED;
pub const WS_ICONIC = WS_MINIMIZE;
pub const WS_SIZEBOX = WS_THICKFRAME;
pub const WS_TILEDWINDOW = WS_OVERLAPPEDWINDOW;
pub const WS_OVERLAPPEDWINDOW = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX;
pub const WS_POPUPWINDOW = WS_POPUP | WS_BORDER | WS_SYSMENU;
pub const WS_CHILDWINDOW = WS_CHILD;
pub const WS_EX_DLGMODALFRAME = 0x00000001;
pub const WS_EX_NOPARENTNOTIFY = 0x00000004;
pub const WS_EX_TOPMOST = 0x00000008;
pub const WS_EX_ACCEPTFILES = 0x00000010;
pub const WS_EX_TRANSPARENT = 0x00000020;
pub const WS_EX_MDICHILD = 0x00000040;
pub const WS_EX_TOOLWINDOW = 0x00000080;
pub const WS_EX_WINDOWEDGE = 0x00000100;
pub const WS_EX_CLIENTEDGE = 0x00000200;
pub const WS_EX_CONTEXTHELP = 0x00000400;
pub const WS_EX_RIGHT = 0x00001000;
pub const WS_EX_LEFT = 0x00000000;
pub const WS_EX_RTLREADING = 0x00002000;
pub const WS_EX_LTRREADING = 0x00000000;
pub const WS_EX_LEFTSCROLLBAR = 0x00004000;
pub const WS_EX_RIGHTSCROLLBAR = 0x00000000;
pub const WS_EX_CONTROLPARENT = 0x00010000;
pub const WS_EX_STATICEDGE = 0x00020000;
pub const WS_EX_APPWINDOW = 0x00040000;
pub const WS_EX_LAYERED = 0x00080000;
pub const WS_EX_OVERLAPPEDWINDOW = WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE;
pub const WS_EX_PALETTEWINDOW = WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST;
pub const CW_USEDEFAULT = @bitCast(i32, @as(u32, 0x80000000));
pub extern "user32" fn CreateWindowExA(dwExStyle: DWORD, lpClassName: [*:0]const u8, lpWindowName: [*:0]const u8, dwStyle: DWORD, X: i32, Y: i32, nWidth: i32, nHeight: i32, hWindParent: ?HWND, hMenu: ?HMENU, hInstance: HINSTANCE, lpParam: ?LPVOID) callconv(WINAPI) ?HWND;
pub fn createWindowExA(dwExStyle: u32, lpClassName: [*:0]const u8, lpWindowName: [*:0]const u8, dwStyle: u32, X: i32, Y: i32, nWidth: i32, nHeight: i32, hWindParent: ?HWND, hMenu: ?HMENU, hInstance: HINSTANCE, lpParam: ?*c_void) !HWND {
const window = CreateWindowExA(dwExStyle, lpClassName, lpWindowName, dwStyle, X, Y, nWidth, nHeight, hWindParent, hMenu, hInstance, lpParam);
if (window) |win| return win;
switch (GetLastError()) {
.CLASS_DOES_NOT_EXIST => return error.ClassDoesNotExist,
.INVALID_PARAMETER => unreachable,
else => |err| return unexpectedError(err),
}
}
pub extern "user32" fn CreateWindowExW(dwExStyle: DWORD, lpClassName: [*:0]const u16, lpWindowName: [*:0]const u16, dwStyle: DWORD, X: i32, Y: i32, nWidth: i32, nHeight: i32, hWindParent: ?HWND, hMenu: ?HMENU, hInstance: HINSTANCE, lpParam: ?LPVOID) callconv(WINAPI) ?HWND;
pub var pfnCreateWindowExW: @TypeOf(RegisterClassExW) = undefined;
pub fn createWindowExW(dwExStyle: u32, lpClassName: [*:0]const u16, lpWindowName: [*:0]const u16, dwStyle: u32, X: i32, Y: i32, nWidth: i32, nHeight: i32, hWindParent: ?HWND, hMenu: ?HMENU, hInstance: HINSTANCE, lpParam: ?*c_void) !HWND {
const function = selectSymbol(CreateWindowExW, pfnCreateWindowExW, .win2k);
const window = function(dwExStyle, lpClassName, lpWindowName, dwStyle, X, Y, nWidth, nHeight, hWindParent, hMenu, hInstance, lpParam);
if (window) |win| return win;
switch (GetLastError()) {
.CLASS_DOES_NOT_EXIST => return error.ClassDoesNotExist,
.INVALID_PARAMETER => unreachable,
else => |err| return unexpectedError(err),
}
}
pub extern "user32" fn DestroyWindow(hWnd: HWND) callconv(WINAPI) BOOL;
pub fn destroyWindow(hWnd: HWND) !void {
if (DestroyWindow(hWnd) == 0) {
switch (GetLastError()) {
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return unexpectedError(err),
}
}
}
pub const SW_HIDE = 0;
pub const SW_SHOWNORMAL = 1;
pub const SW_NORMAL = 1;
pub const SW_SHOWMINIMIZED = 2;
pub const SW_SHOWMAXIMIZED = 3;
pub const SW_MAXIMIZE = 3;
pub const SW_SHOWNOACTIVATE = 4;
pub const SW_SHOW = 5;
pub const SW_MINIMIZE = 6;
pub const SW_SHOWMINNOACTIVE = 7;
pub const SW_SHOWNA = 8;
pub const SW_RESTORE = 9;
pub const SW_SHOWDEFAULT = 10;
pub const SW_FORCEMINIMIZE = 11;
pub const SW_MAX = 11;
pub extern "user32" fn ShowWindow(hWnd: HWND, nCmdShow: i32) callconv(WINAPI) BOOL;
pub fn showWindow(hWnd: HWND, nCmdShow: i32) bool {
return (ShowWindow(hWnd, nCmdShow) == TRUE);
}
pub extern "user32" fn UpdateWindow(hWnd: HWND) callconv(WINAPI) BOOL;
pub fn updateWindow(hWnd: HWND) !void {
if (ShowWindow(hWnd, nCmdShow) == 0) {
switch (GetLastError()) {
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return unexpectedError(err),
}
}
}
pub extern "user32" fn AdjustWindowRectEx(lpRect: *RECT, dwStyle: DWORD, bMenu: BOOL, dwExStyle: DWORD) callconv(WINAPI) BOOL;
pub fn adjustWindowRectEx(lpRect: *RECT, dwStyle: u32, bMenu: bool, dwExStyle: u32) !void {
assert(dwStyle & WS_OVERLAPPED == 0);
if (AdjustWindowRectEx(lpRect, dwStyle, bMenu, dwExStyle) == 0) {
switch (GetLastError()) {
.INVALID_PARAMETER => unreachable,
else => |err| return unexpectedError(err),
}
}
}
pub const GWL_WNDPROC = -4;
pub const GWL_HINSTANCE = -6;
pub const GWL_HWNDPARENT = -8;
pub const GWL_STYLE = -16;
pub const GWL_EXSTYLE = -20;
pub const GWL_USERDATA = -21;
pub const GWL_ID = -12;
pub extern "user32" fn GetWindowLongA(hWnd: HWND, nIndex: i32) callconv(WINAPI) LONG;
pub fn getWindowLongA(hWnd: HWND, nIndex: i32) !i32 {
const value = GetWindowLongA(hWnd, nIndex);
if (value != 0) return value;
switch (GetLastError()) {
.SUCCESS => return 0,
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return unexpectedError(err),
}
}
pub extern "user32" fn GetWindowLongW(hWnd: HWND, nIndex: i32) callconv(WINAPI) LONG;
pub var pfnGetWindowLongW: @TypeOf(GetWindowLongW) = undefined;
pub fn getWindowLongW(hWnd: HWND, nIndex: i32) !i32 {
const function = selectSymbol(GetWindowLongW, pfnGetWindowLongW, .win2k);
const value = function(hWnd, nIndex);
if (value != 0) return value;
switch (GetLastError()) {
.SUCCESS => return 0,
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return unexpectedError(err),
}
}
pub extern "user32" fn GetWindowLongPtrA(hWnd: HWND, nIndex: i32) callconv(WINAPI) LONG_PTR;
pub fn getWindowLongPtrA(hWnd: HWND, nIndex: i32) !isize {
// "When compiling for 32-bit Windows, GetWindowLongPtr is defined as a call to the GetWindowLong function."
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getwindowlongptrw
if (@sizeOf(LONG_PTR) == 4) return getWindowLongA(hWnd, nIndex);
const value = GetWindowLongPtrA(hWnd, nIndex);
if (value != 0) return value;
switch (GetLastError()) {
.SUCCESS => return 0,
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return unexpectedError(err),
}
}
pub extern "user32" fn GetWindowLongPtrW(hWnd: HWND, nIndex: i32) callconv(WINAPI) LONG_PTR;
pub var pfnGetWindowLongPtrW: @TypeOf(GetWindowLongPtrW) = undefined;
pub fn getWindowLongPtrW(hWnd: HWND, nIndex: i32) !isize {
if (@sizeOf(LONG_PTR) == 4) return getWindowLongW(hWnd, nIndex);
const function = selectSymbol(GetWindowLongPtrW, pfnGetWindowLongPtrW, .win2k);
const value = function(hWnd, nIndex);
if (value != 0) return value;
switch (GetLastError()) {
.SUCCESS => return 0,
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return unexpectedError(err),
}
}
pub extern "user32" fn SetWindowLongA(hWnd: HWND, nIndex: i32, dwNewLong: LONG) callconv(WINAPI) LONG;
pub fn setWindowLongA(hWnd: HWND, nIndex: i32, dwNewLong: i32) !i32 {
// [...] you should clear the last error information by calling SetLastError with 0 before calling SetWindowLong.
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwindowlonga
SetLastError(.SUCCESS);
const value = SetWindowLongA(hWnd, nIndex, dwNewLong);
if (value != 0) return value;
switch (GetLastError()) {
.SUCCESS => return 0,
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return unexpectedError(err),
}
}
pub extern "user32" fn SetWindowLongW(hWnd: HWND, nIndex: i32, dwNewLong: LONG) callconv(WINAPI) LONG;
pub var pfnSetWindowLongW: @TypeOf(SetWindowLongW) = undefined;
pub fn setWindowLongW(hWnd: HWND, nIndex: i32, dwNewLong: i32) !i32 {
const function = selectSymbol(SetWindowLongW, pfnSetWindowLongW, .win2k);
SetLastError(.SUCCESS);
const value = function(hWnd, nIndex, dwNewLong);
if (value != 0) return value;
switch (GetLastError()) {
.SUCCESS => return 0,
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return unexpectedError(err),
}
}
pub extern "user32" fn SetWindowLongPtrA(hWnd: HWND, nIndex: i32, dwNewLong: LONG_PTR) callconv(WINAPI) LONG_PTR;
pub fn setWindowLongPtrA(hWnd: HWND, nIndex: i32, dwNewLong: isize) !isize {
// "When compiling for 32-bit Windows, GetWindowLongPtr is defined as a call to the GetWindowLong function."
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getwindowlongptrw
if (@sizeOf(LONG_PTR) == 4) return setWindowLongA(hWnd, nIndex, dwNewLong);
SetLastError(.SUCCESS);
const value = SetWindowLongPtrA(hWnd, nIndex, dwNewLong);
if (value != 0) return value;
switch (GetLastError()) {
.SUCCESS => return 0,
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return unexpectedError(err),
}
}
pub extern "user32" fn SetWindowLongPtrW(hWnd: HWND, nIndex: i32, dwNewLong: LONG_PTR) callconv(WINAPI) LONG_PTR;
pub var pfnSetWindowLongPtrW: @TypeOf(SetWindowLongPtrW) = undefined;
pub fn setWindowLongPtrW(hWnd: HWND, nIndex: i32, dwNewLong: isize) !isize {
if (@sizeOf(LONG_PTR) == 4) return setWindowLongW(hWnd, nIndex, dwNewLong);
const function = selectSymbol(SetWindowLongPtrW, pfnSetWindowLongPtrW, .win2k);
SetLastError(.SUCCESS);
const value = function(hWnd, nIndex, dwNewLong);
if (value != 0) return value;
switch (GetLastError()) {
.SUCCESS => return 0,
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return unexpectedError(err),
}
}
pub extern "user32" fn GetDC(hWnd: ?HWND) callconv(WINAPI) ?HDC;
pub fn getDC(hWnd: ?HWND) !HDC {
const hdc = GetDC(hWnd);
if (hdc) |h| return h;
switch (GetLastError()) {
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return std.os.windows.unexpectedError(err),
}
}
pub extern "user32" fn ReleaseDC(hWnd: ?HWND, hDC: HDC) callconv(WINAPI) i32;
pub fn releaseDC(hWnd: ?HWND, hDC: HDC) bool {
return if (ReleaseDC(hWnd, hDC) == 1) true else false;
}
// === Modal dialogue boxes ===
pub const MB_OK = 0x00000000;
pub const MB_OKCANCEL = 0x00000001;
pub const MB_ABORTRETRYIGNORE = 0x00000002;
pub const MB_YESNOCANCEL = 0x00000003;
pub const MB_YESNO = 0x00000004;
pub const MB_RETRYCANCEL = 0x00000005;
pub const MB_CANCELTRYCONTINUE = 0x00000006;
pub const MB_ICONHAND = 0x00000010;
pub const MB_ICONQUESTION = 0x00000020;
pub const MB_ICONEXCLAMATION = 0x00000030;
pub const MB_ICONASTERISK = 0x00000040;
pub const MB_USERICON = 0x00000080;
pub const MB_ICONWARNING = MB_ICONEXCLAMATION;
pub const MB_ICONERROR = MB_ICONHAND;
pub const MB_ICONINFORMATION = MB_ICONASTERISK;
pub const MB_ICONSTOP = MB_ICONHAND;
pub const MB_DEFBUTTON1 = 0x00000000;
pub const MB_DEFBUTTON2 = 0x00000100;
pub const MB_DEFBUTTON3 = 0x00000200;
pub const MB_DEFBUTTON4 = 0x00000300;
pub const MB_APPLMODAL = 0x00000000;
pub const MB_SYSTEMMODAL = 0x00001000;
pub const MB_TASKMODAL = 0x00002000;
pub const MB_HELP = 0x00004000;
pub const MB_NOFOCUS = 0x00008000;
pub const MB_SETFOREGROUND = 0x00010000;
pub const MB_DEFAULT_DESKTOP_ONLY = 0x00020000;
pub const MB_TOPMOST = 0x00040000;
pub const MB_RIGHT = 0x00080000;
pub const MB_RTLREADING = 0x00100000;
pub const MB_TYPEMASK = 0x0000000F;
pub const MB_ICONMASK = 0x000000F0;
pub const MB_DEFMASK = 0x00000F00;
pub const MB_MODEMASK = 0x00003000;
pub const MB_MISCMASK = 0x0000C000;
pub const MK_CONTROL = 0x0008;
pub const MK_LBUTTON = 0x0001;
pub const MK_MBUTTON = 0x0010;
pub const MK_RBUTTON = 0x0002;
pub const MK_SHIFT = 0x0004;
pub const MK_XBUTTON1 = 0x0020;
pub const MK_XBUTTON2 = 0x0040;
pub const IDOK = 1;
pub const IDCANCEL = 2;
pub const IDABORT = 3;
pub const IDRETRY = 4;
pub const IDIGNORE = 5;
pub const IDYES = 6;
pub const IDNO = 7;
pub const IDCLOSE = 8;
pub const IDHELP = 9;
pub const IDTRYAGAIN = 10;
pub const IDCONTINUE = 11;
pub extern "user32" fn MessageBoxA(hWnd: ?HWND, lpText: [*:0]const u8, lpCaption: [*:0]const u8, uType: UINT) callconv(WINAPI) i32;
pub fn messageBoxA(hWnd: ?HWND, lpText: [*:0]const u8, lpCaption: [*:0]const u8, uType: u32) !i32 {
const value = MessageBoxA(hWnd, lpText, lpCaption, uType);
if (value != 0) return value;
switch (GetLastError()) {
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return unexpectedError(err),
}
}
pub extern "user32" fn MessageBoxW(hWnd: ?HWND, lpText: [*:0]const u16, lpCaption: ?[*:0]const u16, uType: UINT) callconv(WINAPI) i32;
pub var pfnMessageBoxW: @TypeOf(MessageBoxW) = undefined;
pub fn messageBoxW(hWnd: ?HWND, lpText: [*:0]const u16, lpCaption: [*:0]const u16, uType: u32) !i32 {
const function = selectSymbol(pfnMessageBoxW, MessageBoxW, .win2k);
const value = function(hWnd, lpText, lpCaption, uType);
if (value != 0) return value;
switch (GetLastError()) {
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return unexpectedError(err),
}
}
pub const PAINTSTRUCT = extern struct {
hdc: ?HDC,
fErase: BOOL,
rcPaint: RECT,
fRestore: BOOL,
fIncUpdate: BOOL,
rgbReserved: [32]BYTE,
};
pub extern "user32" fn BeginPaint(
hWnd: HWND,
lpPaint: *PAINTSTRUCT,
) callconv(WINAPI) ?HDC;
pub extern "user32" fn EndPaint(
hWnd: HWND,
lpPaint: *const PAINTSTRUCT,
) callconv(WINAPI) BOOL;
pub extern "user32" fn InvalidateRect(
hWnd: HWND, // handle to window
lpRect: ?*const RECT, // rectangle coordinates
bErase: BOOL, // erase state
) callconv(WINAPI) BOOL;
pub extern "user32" fn GetClientRect(hWnd: ?HWND, lpRect: *RECT) callconv(WINAPI) BOOL;
pub fn getClientRect(hWnd: ?HWND, lpRect: *RECT) !BOOL {
const value = GetClientRect(hWnd, lpRect);
if (value != 0) return value;
switch (GetLastError()) {
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return unexpectedError(err),
}
}
|
didot-zwl/zwl/src/windows/user32.zig
|
const std = @import("std");
const zort = @import("main.zig");
pub fn tailSort(
comptime T: type,
allocator: std.mem.Allocator,
arr: []T,
cmp: zort.CompareFn(T),
) !void {
if (arr.len < 2) return;
try tailMerge(T, allocator, arr, cmp, 1);
}
/// Bottom up merge sort. It copies the right block to swap, next merges
/// starting at the tail ends of the two sorted blocks.
/// Can be used stand alone. Uses at most nmemb / 2 swap memory.
pub fn tailMerge(
comptime T: type,
allocator: std.mem.Allocator,
arr: []T,
cmp: zort.CompareFn(T),
b: u2,
) !void {
var c: isize = undefined;
var c_max: isize = undefined;
var d: isize = undefined;
var d_max: isize = undefined;
var e: isize = undefined;
var block: isize = b;
var swap = try allocator.alloc(T, arr.len / 2);
defer allocator.free(swap);
while (block < arr.len) {
var offset: isize = 0;
while (offset + block < arr.len) : (offset += block * 2) {
e = offset + block - 1;
if (!cmp(arr[@intCast(usize, e) + 1], arr[@intCast(usize, e)])) continue;
if (offset + block * 2 < arr.len) {
c_max = 0 + block;
d_max = offset + block * 2;
} else {
c_max = 0 + @intCast(isize, arr.len) - (offset + block);
d_max = 0 + @intCast(isize, arr.len);
}
d = d_max - 1;
while (!cmp(arr[@intCast(usize, d)], arr[@intCast(usize, e)])) {
d_max -= 1;
d -= 1;
c_max -= 1;
}
c = 0;
d = offset + block;
while (c < c_max) {
swap[@intCast(usize, c)] = arr[@intCast(usize, d)];
c += 1;
d += 1;
}
c -= 1;
d = offset + block - 1;
e = d_max - 1;
if (!cmp(arr[@intCast(usize, offset + block)], arr[@intCast(usize, offset)])) {
arr[@intCast(usize, e)] = arr[@intCast(usize, d)];
e -= 1;
d -= 1;
while (c >= 0) {
while (cmp(swap[@intCast(usize, c)], arr[@intCast(usize, d)])) {
arr[@intCast(usize, e)] = arr[@intCast(usize, d)];
e -= 1;
d -= 1;
}
arr[@intCast(usize, e)] = swap[@intCast(usize, c)];
e -= 1;
c -= 1;
}
} else {
arr[@intCast(usize, e)] = arr[@intCast(usize, d)];
e -= 1;
d -= 1;
while (d >= offset) {
while (!cmp(swap[@intCast(usize, c)], arr[@intCast(usize, d)])) {
arr[@intCast(usize, e)] = swap[@intCast(usize, c)];
e -= 1;
c -= 1;
}
arr[@intCast(usize, e)] = arr[@intCast(usize, d)];
e -= 1;
d -= 1;
}
while (c >= 0) {
arr[@intCast(usize, e)] = swap[@intCast(usize, c)];
e -= 1;
c -= 1;
}
}
}
block *= 2;
}
}
|
src/tail.zig
|
const std = @import("std");
const warn = std.debug.print;
const Allocator = std.mem.Allocator;
const c = @cImport({
@cInclude("unistd.h");
@cInclude("errno.h");
@cInclude("sys/epoll.h");
});
pub const SocketType = c_int;
pub const Client = packed struct {
readEvent: *c.epoll_event,
readSocket: SocketType,
writeSocket: SocketType,
};
var epoll_instance: c_int = undefined;
pub fn init() !void {
epoll_instance = c.epoll_create(256);
if (epoll_instance == -1) {
return error.BadValue;
}
}
pub fn newClient(allocator: *Allocator) *Client {
const client = allocator.create(Client) catch unreachable;
const fds = allocator.alloc(SocketType, 2) catch unreachable;
_ = c.pipe(fds.ptr);
client.readSocket = fds[0];
client.writeSocket = fds[1];
allocator.free(fds);
client.readEvent = allocator.create(c.epoll_event) catch unreachable;
return client;
}
//pub fn listen(socket: u8, url: []u8) void {
// _ = socket;
// warn("epoll_listen\n", .{});
//}
pub fn register(client: *Client, callback: fn (?*anyopaque) callconv(.C) void) void { _ = callback; _ = client;}
pub fn dial(client: *Client, url: []u8) void {
_ = url;
//.events = u32(c_int(c.EPOLL_EVENTS.EPOLLIN))|u32(c_int(c.EPOLL_EVENTS.EPOLLET)),
// IN=1, OUT=4, ET=-1
client.readEvent.events = 0x001;
client.readEvent.data.ptr = client;
_ = c.epoll_ctl(epoll_instance, c.EPOLL_CTL_ADD, client.readSocket, client.readEvent);
}
pub fn wait() *Client {
const max_fds = 1;
var events_waiting: [max_fds]c.epoll_event = undefined; //[]c.epoll_event{.data = 1};
var nfds: c_int = -1;
while (nfds < 0) {
nfds = c.epoll_wait(epoll_instance, @ptrCast([*c]c.epoll_event, &events_waiting), max_fds, -1);
if (nfds < 0) {
const errnoPtr: [*c]c_int = c.__errno_location();
const errno = errnoPtr.*;
warn("epoll_wait ignoring errno {}\n", .{errno});
}
}
var clientdata = @alignCast(@alignOf(Client), events_waiting[0].data.ptr);
var client = @ptrCast(*Client, clientdata);
return client;
}
pub fn read(client: *Client, buf: []u8) []u8 {
const pkt_fixed_portion = 1;
warn("c.read readSocket {*}\n", .{client});
var readCountOrErr = c.read(client.readSocket, buf.ptr, pkt_fixed_portion);
if (readCountOrErr >= pkt_fixed_portion) {
const msglen: usize = buf[0];
var msgrecv = @intCast(usize, readCountOrErr - pkt_fixed_portion);
if (msgrecv < msglen) {
var msgleft = msglen - msgrecv;
var r2ce = c.read(client.readSocket, buf.ptr, msgleft);
if (r2ce >= 0) {
msgrecv += @intCast(usize, r2ce);
} else {
warn("read2 ERR\n", .{});
}
}
if (msgrecv == msglen) {
return buf[0..msgrecv];
} else {
return buf[0..0];
}
} else {
warn("epoll client read starved. tried {} got {} bytes\n", .{ pkt_fixed_portion, readCountOrErr });
return buf[0..0];
}
}
pub fn send(client: *Client, buf: []const u8) void {
var len8: u8 = @intCast(u8, buf.len);
var writecount = c.write(client.writeSocket, &len8, 1); // send the size
writecount = writecount + c.write(client.writeSocket, buf.ptr, buf.len);
}
|
src/ipc/epoll.zig
|
pub fn noise(x: f64, y: f64, z: f64) f64 {
const cube_x = @floatToInt(u32, x) & 255;
const cube_y = @floatToInt(u32, y) & 255;
const cube_z = @floatToInt(u32, z) & 255;
const local_x = x - @intToFloat(f64, cube_x);
const local_y = y - @intToFloat(f64, cube_y);
const local_z = z - @intToFloat(f64, cube_z);
const u = fade(local_x);
const v = fade(local_y);
const w = fade(local_z);
const a = p[cube_x] + cube_y;
const aa = p[a] + cube_z;
const ab = p[a + 1] + cube_z;
const b = p[cube_x + 1] + cube_y;
const ba = p[b] + cube_z;
const bb = p[b + 1] + cube_z;
return lerp(
w,
lerp(
v,
lerp(
u,
grad(p[aa], local_x, local_y, local_z),
grad(p[ba], local_x - 1, local_y, local_z),
),
lerp(
u,
grad(p[ab], local_x, local_y - 1, local_z),
grad(p[bb], local_x - 1, local_y - 1, local_z),
),
),
lerp(
v,
lerp(
u,
grad(p[aa + 1], local_x, local_y, local_z - 1),
grad(p[ba + 1], local_x - 1, local_y, local_z - 1),
),
lerp(
u,
grad(p[ab + 1], local_x, local_y - 1, local_z - 1),
grad(p[bb + 1], local_x - 1, local_y - 1, local_z - 1),
),
),
);
}
fn fade(t: f64) f64 {
return t * t * t * (t * (t * 6 - 15) + 10);
}
fn lerp(t: f64, a: f64, b: f64) f64 {
return a + t * (b - a);
}
fn grad(hash: u32, x: f64, y: f64, z: f64) f64 {
const h = hash & 15;
const u = if (h < 8) x else y;
const v = if (h < 4) y else if (h == 12 or h == 14) x else z;
return (if ((h & 1) == 0) u else -u) + (if ((h & 2) == 0) v else -v);
}
pub const p: [512]u8 = .{
151, 160, 137, 91, 90, 15,
131, 13, 201, 95, 96, 53,
194, 233, 7, 225, 140, 36,
103, 30, 69, 142, 8, 99,
37, 240, 21, 10, 23, 190,
6, 148, 247, 120, 234, 75,
0, 26, 197, 62, 94, 252,
219, 203, 117, 35, 11, 32,
57, 177, 33, 88, 237, 149,
56, 87, 174, 20, 125, 136,
171, 168, 68, 175, 74, 165,
71, 134, 139, 48, 27, 166,
77, 146, 158, 231, 83, 111,
229, 122, 60, 211, 133, 230,
220, 105, 92, 41, 55, 46,
245, 40, 244, 102, 143, 54,
65, 25, 63, 161, 1, 216,
80, 73, 209, 76, 132, 187,
208, 89, 18, 169, 200, 196,
135, 130, 116, 188, 159, 86,
164, 100, 109, 198, 173, 186,
3, 64, 52, 217, 226, 250,
124, 123, 5, 202, 38, 147,
118, 126, 255, 82, 85, 212,
207, 206, 59, 227, 47, 16,
58, 17, 182, 189, 28, 42,
223, 183, 170, 213, 119, 248,
152, 2, 44, 154, 163, 70,
221, 153, 101, 155, 167, 43,
172, 9, 129, 22, 39, 253,
19, 98, 108, 110, 79, 113,
224, 232, 178, 185, 112, 104,
218, 246, 97, 228, 251, 34,
242, 193, 238, 210, 144, 12,
191, 179, 162, 241, 81, 51,
145, 235, 249, 14, 239, 107,
49, 192, 214, 31, 181, 199,
106, 157, 184, 84, 204, 176,
115, 121, 50, 45, 127, 4,
150, 254, 138, 236, 205, 93,
222, 114, 67, 29, 24, 72,
243, 141, 128, 195, 78, 66,
215, 61, 156, 180,
// repeated
151, 160,
137, 91, 90, 15, 131, 13,
201, 95, 96, 53, 194, 233,
7, 225, 140, 36, 103, 30,
69, 142, 8, 99, 37, 240,
21, 10, 23, 190, 6, 148,
247, 120, 234, 75, 0, 26,
197, 62, 94, 252, 219, 203,
117, 35, 11, 32, 57, 177,
33, 88, 237, 149, 56, 87,
174, 20, 125, 136, 171, 168,
68, 175, 74, 165, 71, 134,
139, 48, 27, 166, 77, 146,
158, 231, 83, 111, 229, 122,
60, 211, 133, 230, 220, 105,
92, 41, 55, 46, 245, 40,
244, 102, 143, 54, 65, 25,
63, 161, 1, 216, 80, 73,
209, 76, 132, 187, 208, 89,
18, 169, 200, 196, 135, 130,
116, 188, 159, 86, 164, 100,
109, 198, 173, 186, 3, 64,
52, 217, 226, 250, 124, 123,
5, 202, 38, 147, 118, 126,
255, 82, 85, 212, 207, 206,
59, 227, 47, 16, 58, 17,
182, 189, 28, 42, 223, 183,
170, 213, 119, 248, 152, 2,
44, 154, 163, 70, 221, 153,
101, 155, 167, 43, 172, 9,
129, 22, 39, 253, 19, 98,
108, 110, 79, 113, 224, 232,
178, 185, 112, 104, 218, 246,
97, 228, 251, 34, 242, 193,
238, 210, 144, 12, 191, 179,
162, 241, 81, 51, 145, 235,
249, 14, 239, 107, 49, 192,
214, 31, 181, 199, 106, 157,
184, 84, 204, 176, 115, 121,
50, 45, 127, 4, 150, 254,
138, 236, 205, 93, 222, 114,
67, 29, 24, 72, 243, 141,
128, 195, 78, 66, 215, 61,
156, 180,
};
const testing = @import("std").testing;
test {
try testing.expectApproxEqAbs(
@as(f64, 0.13691995878400012),
noise(3.14, 42.0, 7.0),
0.00000000000000001,
);
}
|
modules/algo/src/perlin.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const testing = std.testing;
usingnamespace @import("sparse_set.zig");
const Entity = u32;
const DenseT = u8;
const Vec3 = struct {
x: f32 = 0,
y: f32 = 0,
z: f32 = 0,
};
const DefaultTestSparseSet = SparseSet(.{
.SparseT = Entity,
.DenseT = DenseT,
.allow_resize = .NoResize,
.value_layout = .ExternalStructOfArraysSupport,
});
const ResizableDefaultTestSparseSet = SparseSet(.{
.SparseT = Entity,
.DenseT = DenseT,
.allow_resize = .ResizeAllowed,
.value_layout = .ExternalStructOfArraysSupport,
});
const DefaultTestAOSSimpleSparseSet = SparseSet(.{
.SparseT = Entity,
.DenseT = DenseT,
.ValueT = i32,
.allow_resize = .NoResize,
.value_layout = .InternalArrayOfStructs,
});
const DefaultTestAOSSystemSparseSet = SparseSet(.{
.SparseT = Entity,
.DenseT = DenseT,
.ValueT = Vec3,
.allow_resize = .NoResize,
.value_layout = .InternalArrayOfStructs,
});
const DefaultTestAOSVec3ResizableSparseSet = SparseSet(.{
.SparseT = Entity,
.DenseT = DenseT,
.ValueT = Vec3,
.allow_resize = .ResizeAllowed,
.value_layout = .InternalArrayOfStructs,
.value_init = .ZeroInitialized,
});
test "init safe" {
var ss = DefaultTestSparseSet.init(std.testing.allocator, 128, 8) catch unreachable;
testing.expectEqual(@intCast(DenseT, 0), ss.len());
for (ss.sparse_to_dense) |dense_undefined, sparse| {
var usparse = @intCast(Entity, sparse);
testing.expect(!(ss.hasSparse(usparse)));
}
testing.expectEqual(@intCast(DenseT, 0), ss.len());
ss.deinit();
}
test "add / remove safe 1" {
var ss = DefaultTestSparseSet.init(std.testing.allocator, 128, 8) catch unreachable;
defer ss.deinit();
for (ss.dense_to_sparse) |sparse_undefined, sparse| {
var usparse = @intCast(Entity, sparse) + 10;
var dense_new = ss.add(usparse);
testing.expectEqual(@intCast(DenseT, sparse), dense_new);
testing.expect(ss.hasSparse(usparse));
testing.expectEqual(dense_new, ss.getBySparse(usparse));
testing.expectEqual(usparse, ss.getByDense(dense_new));
}
testing.expectError(error.OutOfBounds, ss.addOrError(1));
testing.expectEqual(@intCast(DenseT, 0), ss.remainingCapacity());
ss.clear();
testing.expect(!(ss.hasSparse(1)));
}
test "add / remove safe 2" {
var ss = DefaultTestSparseSet.init(std.testing.allocator, 128, 8) catch unreachable;
defer ss.deinit();
testing.expect(!(ss.hasSparse(1)));
testing.expectEqual(@intCast(DenseT, 0), ss.add(1));
testing.expect(ss.hasSparse(1));
testing.expectError(error.AlreadyRegistered, ss.addOrError(1));
ss.remove(1);
testing.expect(!(ss.hasSparse(1)));
}
test "add / remove safe 3" {
var ss = DefaultTestSparseSet.init(std.testing.allocator, 128, 8) catch unreachable;
defer ss.deinit();
for (ss.dense_to_sparse) |sparse_undefined, sparse| {
var usparse = @intCast(Entity, sparse) + 10;
_ = ss.add(usparse);
}
testing.expectEqual(@intCast(DenseT, 0), ss.remainingCapacity());
testing.expect(!(ss.hasSparse(5)));
testing.expect(ss.hasSparse(15));
ss.remove(15);
testing.expect(!(ss.hasSparse(15)));
testing.expectEqual(@intCast(DenseT, 1), ss.remainingCapacity());
_ = ss.add(15);
testing.expect(ss.hasSparse(15));
testing.expectEqual(@intCast(DenseT, 0), ss.remainingCapacity());
}
test "AOS" {
var ss = DefaultTestAOSSimpleSparseSet.init(std.testing.allocator, 128, 8) catch unreachable;
defer ss.deinit();
for (ss.dense_to_sparse) |sparse_undefined, sparse| {
var usparse = @intCast(Entity, sparse) + 10;
var value = -@intCast(i32, sparse);
var dense_new = ss.addValue(usparse, value);
testing.expectEqual(@intCast(DenseT, sparse), dense_new);
testing.expect(ss.hasSparse(usparse));
testing.expectEqual(dense_new, ss.getBySparse(usparse));
testing.expectEqual(usparse, ss.getByDense(dense_new));
testing.expectEqual(value, (ss.getValueByDense(dense_new)).*);
testing.expectEqual(value, ss.getValueBySparse(usparse).*);
}
testing.expectEqual(@intCast(DenseT, 0), ss.remainingCapacity());
ss.clear();
testing.expect(!ss.hasSparse(1));
}
test "AOS system" {
var sys = MyPositionSystemAOS.init();
defer sys.deinit();
var ent1: Entity = 10;
var ent2: Entity = 20;
var v1 = Vec3{ .x = 10, .y = 0, .z = 0 };
var v2 = Vec3{ .x = 20, .y = 0, .z = 0 };
sys.addComp(ent1, v1);
sys.addComp(ent2, v2);
testing.expectEqual(v1, sys.getComp(ent1));
testing.expectEqual(v2, sys.getComp(ent2));
testing.expectEqual(v1, sys.component_set.values[0]);
testing.expectEqual(v2, sys.component_set.values[1]);
testing.expectEqual(@as(DenseT, 0), sys.component_set.getBySparse(ent1));
testing.expectEqual(@as(DenseT, 1), sys.component_set.getBySparse(ent2));
sys.removeComp(ent1);
testing.expectEqual(v2, sys.getComp(ent2));
testing.expectEqual(v2, sys.component_set.values[0]);
testing.expectEqual(@as(DenseT, 0), sys.component_set.getBySparse(ent2));
sys.updateComps();
testing.expectEqual(Vec3{ .x = 23, .y = 0, .z = 0 }, sys.getComp(ent2));
}
test "SOA system" {
var sys = MyPositionSystemSOA.init();
defer sys.deinit();
var ent1: Entity = 10;
var ent2: Entity = 20;
var v1 = Vec3{ .x = 10, .y = 0, .z = 0 };
var v2 = Vec3{ .x = 20, .y = 0, .z = 0 };
sys.addComp(ent1, v1);
sys.addComp(ent2, v2);
testing.expectEqual(v1, sys.getComp(ent1));
testing.expectEqual(v2, sys.getComp(ent2));
testing.expectEqual(@as(DenseT, 0), sys.component_set.getBySparse(ent1));
testing.expectEqual(@as(DenseT, 1), sys.component_set.getBySparse(ent2));
sys.removeComp(ent1);
testing.expectEqual(v2, sys.getComp(ent2));
testing.expectEqual(@as(DenseT, 0), sys.component_set.getBySparse(ent2));
sys.updateComps();
testing.expectEqual(Vec3{ .x = 23, .y = 0, .z = 0 }, sys.getComp(ent2));
}
test "SOA resize true" {
var ss = ResizableDefaultTestSparseSet.init(std.testing.allocator, 128, 8) catch unreachable;
defer ss.deinit();
testing.expectError(error.OutOfBounds, ss.hasSparseOrError(500));
for (ss.dense_to_sparse) |sparse_undefined, sparse| {
var usparse = @intCast(Entity, sparse) + 10;
var dense_new = ss.add(usparse);
testing.expect(ss.hasSparse(usparse));
}
testing.expect(!ss.hasSparse(18));
testing.expectEqual(@intCast(DenseT, 8), ss.add(18));
testing.expect(ss.hasSparse(18));
testing.expect(!ss.hasSparse(19));
testing.expectEqual(@intCast(u32, 16), @intCast(u32, ss.dense_to_sparse.len));
testing.expectEqual(@intCast(DenseT, 7), ss.remainingCapacity());
testing.expectEqual(@intCast(Entity, 10), ss.dense_to_sparse[0]);
testing.expectEqual(@intCast(Entity, 11), ss.dense_to_sparse[1]);
testing.expectEqual(@intCast(Entity, 12), ss.dense_to_sparse[2]);
testing.expectEqual(@intCast(Entity, 13), ss.dense_to_sparse[3]);
testing.expectEqual(@intCast(Entity, 16), ss.dense_to_sparse[6]);
testing.expectEqual(@intCast(Entity, 17), ss.dense_to_sparse[7]);
testing.expectEqual(@intCast(Entity, 18), ss.dense_to_sparse[8]);
ss.clear();
testing.expect(!(ss.hasSparse(1)));
}
test "AOS resize true" {
var ss = DefaultTestAOSVec3ResizableSparseSet.init(std.testing.allocator, 128, 8) catch unreachable;
defer ss.deinit();
testing.expectError(error.OutOfBounds, ss.hasSparseOrError(500));
for (ss.dense_to_sparse) |sparse_undefined, sparse| {
var usparse = @intCast(Entity, sparse) + 10;
var value = Vec3{ .x = @intToFloat(f32, sparse), .y = 0, .z = 0 };
var dense_new = ss.addValue(usparse, value);
testing.expect(ss.hasSparse(usparse));
testing.expectEqual(value, ss.getValueBySparse(usparse).*);
}
testing.expect(!ss.hasSparse(18));
testing.expectEqual(@intCast(DenseT, 8), ss.addValue(18, Vec3{ .x = 8, .y = 0, .z = 0 }));
testing.expect(ss.hasSparse(18));
testing.expect(!ss.hasSparse(19));
testing.expectEqual(@intCast(DenseT, 7), ss.remainingCapacity());
testing.expectEqual(Vec3{ .x = 0, .y = 0, .z = 0 }, ss.getValueBySparse(10).*);
testing.expectEqual(Vec3{ .x = 1, .y = 0, .z = 0 }, ss.getValueBySparse(11).*);
testing.expectEqual(Vec3{ .x = 2, .y = 0, .z = 0 }, ss.getValueBySparse(12).*);
testing.expectEqual(Vec3{ .x = 3, .y = 0, .z = 0 }, ss.getValueBySparse(13).*);
testing.expectEqual(Vec3{ .x = 4, .y = 0, .z = 0 }, ss.getValueBySparse(14).*);
testing.expectEqual(Vec3{ .x = 5, .y = 0, .z = 0 }, ss.getValueBySparse(15).*);
testing.expectEqual(Vec3{ .x = 6, .y = 0, .z = 0 }, ss.getValueBySparse(16).*);
testing.expectEqual(Vec3{ .x = 7, .y = 0, .z = 0 }, ss.getValueBySparse(17).*);
testing.expectEqual(Vec3{ .x = 8, .y = 0, .z = 0 }, ss.getValueBySparse(18).*);
ss.clear();
testing.expect(!(ss.hasSparse(1)));
}
const MyPositionSystemAOS = struct {
component_set: DefaultTestAOSSystemSparseSet = undefined,
const Self = @This();
pub fn init() MyPositionSystemAOS {
return Self{
.component_set = DefaultTestAOSSystemSparseSet.init(std.testing.allocator, 128, 8) catch unreachable,
};
}
pub fn deinit(self: *MyPositionSystemAOS) void {
self.component_set.deinit();
}
pub fn addComp(self: *Self, ent: Entity, pos: Vec3) void {
_ = self.component_set.addValue(ent, pos);
}
pub fn removeComp(self: *Self, ent: Entity) void {
self.component_set.remove(ent);
}
pub fn getComp(self: *Self, ent: Entity) Vec3 {
return self.component_set.getValueBySparse(ent).*;
}
pub fn updateComps(self: Self) void {
for (self.component_set.toValueSlice()) |*value, dense| {
value.x += 3;
}
}
};
const MyPositionSystemSOA = struct {
component_set: DefaultTestSparseSet = undefined,
xs: [256]f32 = [_]f32{0} ** 256,
ys: [256]f32 = [_]f32{0} ** 256,
zs: [256]f32 = [_]f32{0} ** 256,
const Self = @This();
pub fn init() MyPositionSystemSOA {
return Self{
.component_set = DefaultTestSparseSet.init(std.testing.allocator, 128, 8) catch unreachable,
};
}
pub fn deinit(self: *MyPositionSystemSOA) void {
self.component_set.deinit();
}
pub fn addComp(self: *Self, ent: Entity, pos: Vec3) void {
var dense = self.component_set.add(ent);
self.xs[dense] = pos.x;
self.ys[dense] = pos.y;
self.zs[dense] = pos.z;
}
pub fn removeComp(self: *Self, ent: Entity) void {
var dense_old: DenseT = undefined;
var dense_new: DenseT = undefined;
self.component_set.removeWithInfo(ent, &dense_old, &dense_new);
self.xs[dense_new] = self.xs[dense_old];
self.ys[dense_new] = self.ys[dense_old];
self.zs[dense_new] = self.zs[dense_old];
}
pub fn getComp(self: *Self, ent: Entity) Vec3 {
var dense = self.component_set.getBySparse(ent);
return Vec3{ .x = self.xs[dense], .y = self.ys[dense], .z = self.zs[dense] };
}
pub fn updateComps(self: *Self) void {
for (self.component_set.toSparseSlice()) |ent, dense| {
self.xs[dense] += 3;
}
}
};
|
src/test.zig
|
const std = @import("std");
const aoc = @import("aoc-lib.zig");
const Mess = struct {
const Field = struct {
min1: i64,
max1: i64,
min2: i64,
max2: i64,
pub fn inRange(self: *Field, v: i64) bool {
return (v >= self.min1 and v <= self.max1) or
(v >= self.min2 and v <= self.max2);
}
};
const Ticket = []const i64;
fields: std.StringHashMap(*Field),
our: Ticket,
tickets: std.ArrayList(Ticket),
err: i64,
onlyDepart: bool,
alloc: std.mem.Allocator,
debug: bool,
fn bit(v: i64) i64 {
var b: i64 = 1;
var bc: usize = 0;
while (bc < v) : (bc += 1) {
b <<= 1;
}
return b;
}
fn find1bit(v: i64) i64 {
var count: i64 = 0;
var n: i64 = 1;
while ((v & n) == 0) : (n <<= 1) {
count += 1;
}
return count;
}
pub fn count1s(v: i64) i64 {
var count: i64 = 0;
var n: i64 = 1 << 32;
while (n > 0) : (n >>= 1) {
if ((n & v) != 0) {
count += 1;
}
}
return count;
}
pub fn fromInput(alloc: std.mem.Allocator, inp: [][]const u8) !*Mess {
var m = try alloc.create(Mess);
m.fields = std.StringHashMap(*Field).init(alloc);
m.err = 0;
m.onlyDepart = true;
m.debug = false;
var lit = std.mem.split(u8, inp[0], "\n");
while (lit.next()) |line| {
var f = try alloc.create(Field);
var sit = std.mem.split(u8, line, ": ");
const name = sit.next().?;
var sit2 = std.mem.split(u8, sit.next().?, " or ");
var range1it = std.mem.split(u8, sit2.next().?, "-");
f.min1 = try std.fmt.parseInt(i64, range1it.next().?, 10);
f.max1 = try std.fmt.parseInt(i64, range1it.next().?, 10);
var range2it = std.mem.split(u8, sit2.next().?, "-");
f.min2 = try std.fmt.parseInt(i64, range2it.next().?, 10);
f.max2 = try std.fmt.parseInt(i64, range2it.next().?, 10);
try m.fields.put(name, f);
}
var our: Ticket = try aoc.Ints(alloc, i64, inp[1]);
lit = std.mem.split(u8, inp[2], "\n");
_ = lit.next().?;
var tickets = std.ArrayList(Ticket).init(alloc);
while (lit.next()) |line| {
var ticket = try aoc.Ints(alloc, i64, line);
var validTicket = true;
for (ticket) |v| {
var validField = false;
var fit = m.fields.iterator();
while (fit.next()) |entry| {
if (entry.value_ptr.*.inRange(v)) {
validField = true;
break;
}
}
if (!validField) {
validTicket = false;
m.err += v;
}
}
if (validTicket) {
try tickets.append(ticket);
} else {
alloc.free(ticket);
}
}
m.tickets = tickets;
m.our = our;
m.alloc = alloc;
return m;
}
pub fn deinit(self: *Mess) void {
self.alloc.free(self.our);
for (self.tickets.items) |t| {
self.alloc.free(t);
}
self.tickets.deinit();
var it = self.fields.iterator();
while (it.next()) |f| {
self.alloc.destroy(f.value_ptr.*);
}
self.fields.deinit();
self.alloc.destroy(self);
}
pub fn Solve(self: *Mess) !i64 {
var possible = std.StringHashMap(i64).init(self.alloc);
defer possible.deinit();
var cfit = self.fields.iterator();
while (cfit.next()) |entry| {
try possible.put(entry.key_ptr.*, 0);
}
const target = self.tickets.items.len;
var col: usize = 0;
while (col < self.our.len) {
var fit = self.fields.iterator();
while (fit.next()) |entry| {
var valid: usize = 0;
const name = entry.key_ptr.*;
const field = entry.value_ptr.*;
for (self.tickets.items) |ticket| {
if (field.inRange(ticket[col])) {
valid += 1;
}
}
if (valid == target) {
if (self.debug) {
std.debug.print("found {s} at {} ({})\n", .{ name, col, col });
}
var bm = possible.get(name).?;
bm |= bit(@intCast(i64, col));
try possible.put(name, bm);
}
}
col += 1;
}
var p: i64 = 1;
while (true) {
var progress = false;
var possIt = possible.iterator();
while (possIt.next()) |possRec| {
var name = possRec.key_ptr.*;
var cols = possRec.value_ptr.*;
if (cols != 0 and count1s(cols) == 1) {
progress = true;
var c: i64 = find1bit(cols);
var ourVal = self.our[std.math.absCast(c)];
if (self.debug) {
std.debug.print("definite {s} is {} ({})\n", .{ name, c, ourVal });
}
if (name[0] == 'd' and name[1] == 'e' or !self.onlyDepart) {
p *= ourVal;
}
_ = possible.remove(name);
var possIt2 = possible.iterator();
while (possIt2.next()) |possRec2| {
possRec2.value_ptr.* &= (bit(c) ^ 0xffffffff);
try possible.put(possRec2.key_ptr.*, possRec2.value_ptr.*);
}
if (possible.count() == 0) {
return p;
}
}
}
if (!progress) {
std.debug.print("no progress made\n", .{});
std.os.exit(0);
}
}
}
};
test "count1s" {
try aoc.assertEq(@as(i64, 1), Mess.count1s(@as(i64, 1)));
try aoc.assertEq(@as(i64, 2), Mess.count1s(@as(i64, 3)));
try aoc.assertEq(@as(i64, 2), Mess.count1s(@as(i64, 6)));
}
test "examples" {
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 t1m = Mess.fromInput(aoc.talloc, test1) catch unreachable;
defer t1m.deinit();
try aoc.assertEq(@as(i64, 71), t1m.err);
var inpm = Mess.fromInput(aoc.talloc, inp) catch unreachable;
defer inpm.deinit();
try aoc.assertEq(@as(i64, 21980), inpm.err);
var t2m = Mess.fromInput(aoc.talloc, test2) catch unreachable;
defer t2m.deinit();
t2m.onlyDepart = false;
const t2a = t2m.Solve() catch unreachable;
try aoc.assertEq(@as(i64, 1716), t2a);
const impa = inpm.Solve() catch unreachable;
try aoc.assertEq(@as(i64, 1439429522627), impa);
}
fn day16(_: []const u8, bench: bool) anyerror!void {
var args = std.process.args();
_ = args.next(aoc.halloc).? catch true;
var chunks: [][]const u8 = undefined;
var onlyDepart = true;
if (args.next(aoc.halloc)) |_| {
chunks = aoc.readChunks(aoc.halloc, aoc.test2file);
onlyDepart = false;
} else {
chunks = aoc.readChunks(aoc.halloc, aoc.inputfile);
}
defer aoc.halloc.free(chunks);
var m = try Mess.fromInput(aoc.halloc, chunks);
defer m.deinit();
m.onlyDepart = onlyDepart;
var p1 = m.err;
var p2 = m.Solve();
if (!bench) {
try aoc.print("Part 1: {}\nPart 2: {}\n", .{ p1, p2 });
}
}
pub fn main() anyerror!void {
try aoc.benchme(aoc.input(), day16);
}
|
2020/16/aoc.zig
|
const std = @import("std");
usingnamespace @import("parse_helpers.zig");
usingnamespace @import("../winmd.zig");
const win32: []const u8 = @embedFile("../default/Windows.Win32.winmd");
const winRT: []const u8 = @embedFile("../default/Windows.WinRT.winmd");
const Allocator = std.mem.Allocator;
/// TypeRow contains the necessary info to dig into a type's particular row
/// TypeReader's primary function is to provide these rows from winmd files
const TypeRow = struct {
type_def: TypeDef,
method_def: ?MethodDef = null,
field: ?Field = null,
};
/// Provided a list of winmd file bytes, the TypeReader will parse these files and attempt to provide a StringHashMap of namespaces and types
/// If a set of file bytes are not provided, TypeReader will attempt to parse the default winmd files ["Windows.Win32.winmd", "Windows.WinRT.winmd"]
/// The default files are embedded as part of this lib
pub const TypeReader = struct {
const Self = @This();
allocator: *std.mem.Allocator,
files: std.ArrayList(DatabaseFile),
types: std.StringArrayHashMap(std.StringArrayHashMap(TypeRow)),
/// The defacto initialization method of TypeReader.
pub fn init(allocator: *Allocator, winmd_files_bytes: ?[][]const u8) !*Self {
const reader = try allocator.create(Self);
reader.* = Self{
.allocator = allocator,
.files = std.ArrayList(DatabaseFile).init(allocator),
.types = std.StringArrayHashMap(std.StringArrayHashMap(TypeRow)).init(allocator),
};
errdefer allocator.destroy(reader);
if (winmd_files_bytes == null) {
try reader.files.append(try DatabaseFile.fromBytes(win32));
try reader.files.append(try DatabaseFile.fromBytes(winRT));
} else {
for (winmd_files_bytes.?) |file_bytes| {
try reader.files.append(try DatabaseFile.fromBytes(file_bytes));
}
}
try reader.parseDatabases();
return reader;
}
pub fn deinit(self: *Self) void {
var namespaces = self.types.iterator();
while (namespaces.next()) |namespace| {
namespace.value.deinit();
}
self.types.deinit();
self.files.deinit();
self.allocator.destroy(self);
}
fn parseDatabases(self: *Self) !void {
for (self.files.items) |database, index| {
const row_count = database.tables[@enumToInt(TableIndex.TypeDef)].row_count;
var row: u32 = 0;
while (row < row_count) : (row += 1) {
const def = Row{
.index = row,
.table_index = TableIndex.TypeDef,
.file_index = @intCast(u16, index),
};
const type_def = TypeDef{
.row = def,
.reader = self,
};
var namespace_hash = try self.types.getOrPutValue(type_def.namespace(), std.StringArrayHashMap(TypeRow).init(self.allocator));
_ = try namespace_hash.value.getOrPutValue(type_def.name(), TypeRow{ .type_def = type_def });
const flags = type_def.flags();
if (flags.interface() or flags.windowsRuntime()) {
continue;
}
const extends_index = self.parseU32(&def, 3);
if (extends_index == 0) continue;
const extends = Row{
.index = (extends_index >> 2) - 1,
.table_index = TableIndex.TypeRef,
.file_index = @intCast(u16, index),
};
if (!std.mem.eql(u8, self.parseStr(&extends, 2), "System") or !std.mem.eql(u8, self.parseStr(&extends, 1), "Object")) {
continue;
}
// begin gathering field info
var field_iter = self.getRowIterator(&def, TableIndex.Field, 4);
while (field_iter.next()) |field_row| {
const field = Field{
.row = field_row,
.reader = self,
};
var field_name_hash = try namespace_hash.value.getOrPutValue(field.name(), TypeRow{ .type_def = type_def });
field_name_hash.value.field = field;
}
//begin gathering method info
var method_iter = self.getRowIterator(&def, TableIndex.MethodDef, 5);
while (method_iter.next()) |method_row| {
const method_def = MethodDef{
.row = method_row,
.reader = self,
};
var method_name_hash = try namespace_hash.value.getOrPutValue(method_def.name(), TypeRow{ .type_def = type_def });
method_name_hash.value.method_def = method_def;
}
}
}
}
/// Read a [`u32`] value from a specific row and column
pub fn parseU32(self: *const TypeReader, row: *const Row, column: u32) u32 {
var file_obj = self.files.items[row.file_index];
var table = file_obj.tables[@enumToInt(row.table_index)];
var offset = table.data + row.index * table.row_size + table.columns[column].offset;
return switch (table.columns[column].size) {
1 => @intCast(u32, copyAs(u8, file_obj.bytes, offset)),
2 => @intCast(u32, copyAs(u16, file_obj.bytes, offset)),
4 => @intCast(u32, copyAs(u32, file_obj.bytes, offset)),
else => {
// Saw this in the windows-rs code. Seems weird
return @truncate(u32, copyAs(u64, file_obj.bytes, offset));
},
};
}
/// Read a []const u8 value from a specific row and column
pub fn parseStr(self: *const TypeReader, row: *const Row, column: u32) []const u8 {
var file_obj = self.files.items[row.file_index];
var offset = file_obj.strings + self.parseU32(row, column);
return viewAsStr(file_obj.bytes, offset);
}
/// Returns the start of a RowIterator for a given starting row and column
pub fn getRowIterator(self: *const TypeReader, row: *const Row, table: TableIndex, column: u32) RowIterator {
var file_obj = self.files.items[row.file_index];
var first = self.parseU32(row, column) - 1;
var last: u32 = 0;
if (row.index + 1 < file_obj.tables[@enumToInt(row.table_index)].row_count) {
var nrow = row.next();
last = self.parseU32(&nrow, column) - 1;
} else {
last = file_obj.tables[@enumToInt(table)].row_count;
}
return RowIterator{
.file_index = row.file_index,
.table = table,
.first = first,
.last = last,
};
}
/// Tries to find a TypeDef within the known set of databases
/// null is returned if it can't be found
pub fn findTypeDef(self: *const TypeReader, namespace: []const u8, name: []const u8) ?TypeDef {
var namespace_entry = self.types.getEntry(namespace);
if (namespace_entry == null) return null;
var name_entry = namespace_entry.?.value.getEntry(name);
if (name_entry == null) return null;
return name_entry.?.value.type_def;
}
};
|
src/winmd/type_reader.zig
|
const Allocator = std.mem.Allocator;
const std = @import("std");
const BufMap = std.BufMap;
const Entry = std.StringHashMap([]const u8).Entry;
const printError = @import("print_error.zig").printError;
pub const Config = struct {
allocator: Allocator,
appname: []const u8,
config_file: []const u8,
map: BufMap,
pub fn init(self: *Config, allocator: Allocator, appname: []const u8, config_file: []const u8) void {
self.allocator = allocator;
self.appname = appname;
self.config_file = config_file;
self.map = BufMap.init(allocator);
}
pub fn deinit(self: *Config) void {
self.map.deinit();
}
pub fn load(self: *Config) !void {
const config_path: []const u8 = try self.getValidConfigFilePath();
defer self.allocator.free(config_path);
const file: std.fs.File = try std.fs.createFileAbsolute(config_path, .{ .read = true, .truncate = false });
defer file.close();
try self.parse(file);
}
pub fn flush(self: *Config) !void {
const config_path: []const u8 = try self.getValidConfigFilePath();
defer self.allocator.free(config_path);
const file: std.fs.File = try std.fs.createFileAbsolute(config_path, .{ .read = false, .truncate = true });
defer file.close();
try self.write(file);
}
pub fn getValidConfigPath(self: *Config, filename: []const u8) ![]const u8 {
const dir_path: []const u8 = try std.fs.getAppDataDir(self.allocator, self.appname);
defer self.allocator.free(dir_path);
std.fs.makeDirAbsolute(dir_path) catch |err| switch (err) {
error.PathAlreadyExists => {},
else => return err,
};
const config_path: []const u8 = std.fs.path.join(self.allocator, &[_][]const u8{ dir_path, filename }) catch unreachable;
return config_path;
}
fn getValidConfigFilePath(self: *Config) ![]const u8 {
return self.getValidConfigPath(self.config_file);
}
fn parse(self: *Config, config_file: std.fs.File) !void {
const reader: std.fs.File.Reader = config_file.reader();
var buffer: [1024]u8 = undefined;
var groupBuffer: [512]u8 = undefined;
var groupLen: usize = 0;
while (try reader.readUntilDelimiterOrEof(&buffer, '\n')) |line| {
if (line[0] == '[') {
std.mem.copy(u8, &groupBuffer, line[1..(line.len - 1)]);
groupLen = line.len - 1;
groupBuffer[groupLen - 1] = '_';
continue;
}
var it: std.mem.SplitIterator(u8) = std.mem.split(u8, line, "=");
const name: []const u8 = it.next() orelse continue;
const value: []const u8 = it.rest();
std.mem.copy(u8, groupBuffer[groupLen..], name);
try self.map.put(groupBuffer[0..(groupLen + name.len)], value);
}
}
fn compareEntries(context: void, left: Entry, right: Entry) bool {
_ = context;
return std.mem.lessThan(u8, left.key_ptr.*, right.key_ptr.*);
}
fn write(self: *Config, config_file: std.fs.File) !void {
const writer: std.fs.File.Writer = config_file.writer();
var buffer: []Entry = try self.allocator.alloc(Entry, self.map.count());
defer self.allocator.free(buffer);
var ind: usize = 0;
var it = self.map.iterator();
while (it.next()) |entry| {
buffer[ind] = entry;
ind += 1;
}
std.sort.sort(Entry, buffer, {}, compareEntries);
var current_group: []const u8 = undefined;
var current_group_len: usize = 0;
for (buffer) |entry| {
const group_end: usize = std.mem.indexOf(u8, entry.key_ptr.*, "_") orelse 0;
if ((group_end != current_group_len) or !std.mem.eql(u8, current_group, entry.key_ptr.*[0..group_end])) {
current_group_len = group_end;
current_group = entry.key_ptr.*[0..group_end];
try writer.print("[{s}]\n", .{current_group});
}
try writer.print("{s}={s}\n", .{
entry.key_ptr.*[(group_end + 1)..],
entry.value_ptr.*,
});
}
}
pub fn getBool(self: *Config, key: []const u8, default: bool) bool {
const val: ?[]const u8 = self.map.get(key);
if (val) |v| {
return v.len > 0 and v[0] == '1';
} else {
return default;
}
}
pub fn putBool(self: *Config, key: []const u8, val: bool) void {
self.map.put(key, if (val) "1" else "0") catch {
printError("Config", "Error during putting bool value");
};
}
};
test "write and load config" {
// Write
{
var write_config: Config = undefined;
write_config.init(std.testing.allocator, "nyancore", "test.conf");
defer write_config.deinit();
try write_config.map.put("test0_key0", "key 0 value");
try write_config.map.put("test1_key1", "key 1 value");
try write_config.flush();
}
// Read
{
var read_config: Config = undefined;
read_config.init(std.testing.allocator, "nyancore", "test.conf");
defer read_config.deinit();
try read_config.load();
std.testing.expect(std.mem.eql(u8, read_config.map.get("test0_key0") orelse "", "key 0 value"));
std.testing.expect(std.mem.eql(u8, read_config.map.get("test1_key1") orelse "", "key 1 value"));
}
}
|
src/application/config.zig
|
const std = @import("std");
const fs = std.fs;
const print = std.debug.print;
const Allocator = std.heap.c_allocator;
const sdl = @cImport({
@cInclude("SDL2/SDL.h");
});
const time = @cImport({
@cInclude("sys/time.h");
});
const c = @cImport({
@cInclude("png.h");
@cInclude("setjmp.h");
});
fn sdl_check_error(code: c_int) void {
if (code != 0) {
print("SDL Error: {}\n", .{sdl.SDL_GetError()});
}
}
const WIDTH: usize = 10;
const HEIGHT: usize = 7;
const TILE_SIZE: u16 = 64;
fn texture_from_file(renderer: ?*sdl.SDL_Renderer, file_name: [*:0]const u8) !*sdl.SDL_Texture {
const fp = c.fopen(file_name, "rb") orelse std.os.abort();
var header = [_]u8{0} ** 8;
var header_slice: []u8 = header[0..];
_ = c.fread(header_slice.ptr, 1, 8, fp);
if (c.png_sig_cmp(header_slice.ptr, 0, 8) != 0) {
std.os.abort();
}
const png_ptr: c.png_structp = c.png_create_read_struct(c.PNG_LIBPNG_VER_STRING, null, null, null) orelse std.os.abort();
const info_ptr: c.png_infop = c.png_create_info_struct(png_ptr) orelse std.os.abort();
const jmp_buf: []c.__jmp_buf_tag = c.png_jmpbuf(png_ptr)[0..];
if (c.setjmp(jmp_buf.ptr) != 0) {
std.os.abort();
}
c.png_init_io(png_ptr, fp);
c.png_set_sig_bytes(png_ptr, 8);
c.png_read_info(png_ptr, info_ptr);
const width = c.png_get_image_width(png_ptr, info_ptr);
const height = c.png_get_image_height(png_ptr, info_ptr);
const color_type = c.png_get_color_type(png_ptr, info_ptr);
const bit_depth = c.png_get_bit_depth(png_ptr, info_ptr);
const number_of_passes = c.png_set_interlace_handling(png_ptr);
c.png_read_update_info(png_ptr, info_ptr);
var row_pointers = try Allocator.alloc(c.png_bytep, height);
for (row_pointers) |*row| {
row.* = (try Allocator.alloc(c.png_byte, c.png_get_rowbytes(png_ptr, info_ptr))).ptr;
}
c.png_read_image(png_ptr, row_pointers.ptr);
var pixels = [_]c.png_byte{0} ** (512 * 512 * 4);
for (pixels) |*byte, i| {
byte.* = row_pointers[i / (512 * 4)][i % 512];
}
var pixels_slice: []u8 = pixels[0..];
const surface = sdl.SDL_CreateRGBSurfaceFrom(
pixels_slice.ptr,
@intCast(c_int, width),
@intCast(c_int, height),
4 * bit_depth,
@intCast(c_int, 4 * width),
0x000000FF,
0x0000FF00,
0x00FF0000,
0xFF000000,
) orelse std.os.abort();
const texture = sdl.SDL_CreateTextureFromSurface(renderer, surface) orelse std.os.abort();
return texture;
}
fn render_grid(renderer: ?*sdl.SDL_Renderer, tiles: [HEIGHT][WIDTH]u64) void {
for (tiles) |col, j| {
for (col) |_, i| {
const rect = sdl.SDL_Rect{
.x = @intCast(c_int, TILE_SIZE * i),
.y = @intCast(c_int, TILE_SIZE * j),
.w = TILE_SIZE,
.h = TILE_SIZE,
};
sdl_check_error(sdl.SDL_SetRenderDrawColor(renderer, @intCast(u8, 255 * i / WIDTH), @intCast(u8, 255 * j / HEIGHT), 0, 255));
sdl_check_error(sdl.SDL_RenderFillRect(renderer, &rect));
}
}
}
fn render_texture(renderer: ?*sdl.SDL_Renderer, texture: *sdl.SDL_Texture) void {
const src = sdl.SDL_Rect{
.x = 0,
.y = 0,
.w = 32 * 3,
.h = 32 * 3,
};
const dest = sdl.SDL_Rect{
.x = 0,
.y = 0,
.w = TILE_SIZE * 3,
.h = TILE_SIZE * 3,
};
sdl_check_error(sdl.SDL_RenderCopy(renderer, texture, &src, &dest));
}
fn render_player(renderer: ?*sdl.SDL_Renderer, x: isize, y: isize, colour: bool) void {
const rect = sdl.SDL_Rect{
.x = @intCast(c_int, x),
.y = @intCast(c_int, y),
.w = TILE_SIZE,
.h = TILE_SIZE,
};
if (colour) {
sdl_check_error(sdl.SDL_SetRenderDrawColor(renderer, 0, 0, 255, 255));
} else {
sdl_check_error(sdl.SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255));
}
sdl_check_error(sdl.SDL_RenderFillRect(renderer, &rect));
}
pub fn main() !void {
sdl_check_error(sdl.SDL_Init(sdl.SDL_INIT_VIDEO | sdl.SDL_INIT_EVENTS));
const window: ?*sdl.SDL_Window = sdl.SDL_CreateWindow("zig_sdl2", sdl.SDL_WINDOWPOS_UNDEFINED, sdl.SDL_WINDOWPOS_UNDEFINED, 640, 448, sdl.SDL_WINDOW_SHOWN);
const renderer: ?*sdl.SDL_Renderer = sdl.SDL_CreateRenderer(window, -1, sdl.SDL_RENDERER_ACCELERATED | sdl.SDL_RENDERER_PRESENTVSYNC);
const tiles = [HEIGHT][WIDTH]u64{
[_]u64{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
[_]u64{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
[_]u64{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
[_]u64{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
[_]u64{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
[_]u64{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
[_]u64{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
};
const texture = try texture_from_file(renderer, "tileset.png");
var quit = false;
var start: time.timeval = undefined;
var end: time.timeval = undefined;
var x: isize = 0;
var y: isize = 0;
var colour: bool = false;
var acc: u64 = 0;
while (!quit) {
_ = time.gettimeofday(&start, null);
var event: sdl.SDL_Event = undefined;
while (sdl.SDL_PollEvent(&event) != 0) {
if (event.type == sdl.SDL_QUIT) {
quit = true;
}
}
const keyboard_state: [*c]const u8 = sdl.SDL_GetKeyboardState(null);
if (keyboard_state[sdl.SDL_SCANCODE_W] != 0) {
y -= 2;
}
if (keyboard_state[sdl.SDL_SCANCODE_S] != 0) {
y += 2;
}
if (keyboard_state[sdl.SDL_SCANCODE_A] != 0) {
x -= 2;
}
if (keyboard_state[sdl.SDL_SCANCODE_D] != 0) {
x += 2;
}
sdl_check_error(sdl.SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255));
sdl_check_error(sdl.SDL_RenderClear(renderer));
render_grid(renderer, tiles);
render_texture(renderer, texture);
render_player(renderer, x, y, colour);
sdl.SDL_RenderPresent(renderer);
_ = time.gettimeofday(&end, null);
var delta = (end.tv_sec - start.tv_sec) * 1000000 + end.tv_usec - start.tv_usec;
acc += @intCast(u64, delta);
if (acc > 2_000_000) {
colour = !colour;
acc -= 2_000_000;
}
}
sdl.SDL_Quit();
}
|
src/main.zig
|
const std = @import("std");
const assert = std.debug.assert;
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var input_file = try std.fs.cwd().openFile("input/09.txt", .{});
defer input_file.close();
var buffered_reader = std.io.bufferedReader(input_file.reader());
const risk_level = try calculateRiskLevel(allocator, buffered_reader.reader());
std.debug.print("product of three largest basins: {}\n", .{risk_level});
}
fn calculateRiskLevel(gpa: std.mem.Allocator, reader: anytype) !u64 {
var arena = std.heap.ArenaAllocator.init(gpa);
defer arena.deinit();
const allocator = arena.allocator();
var buf: [4096]u8 = undefined;
var height_map_array_list = std.ArrayList(u8).init(allocator);
var width: u64 = 0;
while (try reader.readUntilDelimiterOrEof(&buf, '\n')) |line| {
assert(line.len > 0); // empty line
if (width > 0) assert(width == line.len); // different line lengths
width = line.len;
try height_map_array_list.appendSlice(line);
}
const height_map = height_map_array_list.items;
// Find all low points
var low_point_basins = std.AutoHashMap(usize, std.ArrayList(usize)).init(allocator);
for (height_map) |x, i| {
const lower_than_north = i < width or x < height_map[i - width];
const lower_than_south = i >= height_map.len - width or x < height_map[i + width];
const lower_than_west = i % width < 1 or x < height_map[i - 1];
const lower_than_east = i % width >= width - 1 or x < height_map[i + 1];
if (lower_than_north and lower_than_south and lower_than_west and lower_than_east) {
try low_point_basins.put(i, std.ArrayList(usize).init(allocator));
try low_point_basins.getPtr(i).?.append(i);
}
}
// Find all basin mappings
for (height_map) |x, i| {
if (x == '9') continue;
if (low_point_basins.contains(i)) continue;
var pos = i;
while (!low_point_basins.contains(pos)) {
const pos_north: ?usize = if (pos < width) null else pos - width;
const pos_south: ?usize = if (pos >= height_map.len - width) null else pos + width;
const pos_west: ?usize = if (pos % width < 1) null else pos - 1;
const pos_east: ?usize = if (pos % width >= width - 1) null else pos + 1;
const possible_positions = [_]?usize{ pos_north, pos_south, pos_west, pos_east };
var min: ?usize = null;
for (possible_positions) |maybe_possible_pos| {
if (maybe_possible_pos) |possible_pos| {
if (min) |current_min| {
if (height_map[possible_pos] < height_map[current_min]) {
min = possible_pos;
}
} else {
min = possible_pos;
}
}
}
pos = min.?; // no minimum found?
}
try low_point_basins.getPtr(pos).?.append(i);
}
var basin_sizes = try allocator.alloc(usize, low_point_basins.count());
var iter = low_point_basins.iterator();
var i: usize = 0;
while (iter.next()) |entry| {
basin_sizes[i] = entry.value_ptr.items.len;
i += 1;
}
std.sort.sort(usize, basin_sizes, {}, comptime std.sort.desc(usize));
return basin_sizes[0] * basin_sizes[1] * basin_sizes[2];
}
test "example 1" {
const text =
\\2199943210
\\3987894921
\\9856789892
\\8767896789
\\9899965678
;
var fbs = std.io.fixedBufferStream(text);
const risk_level = try calculateRiskLevel(std.testing.allocator, fbs.reader());
try std.testing.expectEqual(@as(u64, 1134), risk_level);
}
|
src/09_2.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const testing = std.testing;
const input_file = "input07.txt";
const Child = struct {
color: []const u8,
amount: u32,
};
const Rules = std.StringHashMap([]const Child);
fn parseRules(allocator: *Allocator, reader: anytype) !Rules {
var result = Rules.init(allocator);
var buf: [4 * 1024]u8 = undefined;
while (try reader.readUntilDelimiterOrEof(&buf, '\n')) |line| {
const line_without_dot = line[0 .. line.len - 1];
var iter = std.mem.split(line_without_dot, " contain ");
const head = iter.next() orelse return error.FormatError;
const tail = iter.next() orelse return error.FormatError;
// parent
const parent = try allocator.dupe(u8, head[0 .. head.len - 5]);
// children
var children = std.ArrayList(Child).init(allocator);
if (!std.mem.eql(u8, tail, "no other bags")) {
var tail_iter = std.mem.split(tail, ", ");
while (tail_iter.next()) |item| {
const trailing_bytes_to_remove: usize = if (std.mem.endsWith(u8, item, " bags")) 5 else if (std.mem.endsWith(u8, item, " bag")) 4 else return error.UnexpectedEnd;
const first_space = std.mem.indexOfScalar(u8, item, ' ').?;
const color = item[first_space + 1 .. item.len - trailing_bytes_to_remove];
const amount = try std.fmt.parseInt(u32, item[0..first_space], 10);
try children.append(Child{
.color = try allocator.dupe(u8, color),
.amount = amount,
});
}
}
try result.put(parent, children.toOwnedSlice());
}
return result;
}
fn freeRules(allocator: *Allocator, rules: *Rules) void {
var iter = rules.iterator();
while (iter.next()) |kv| {
allocator.free(kv.key);
for (kv.value) |x| allocator.free(x.color);
allocator.free(kv.value);
}
rules.deinit();
}
test "parse rules" {
const allocator = std.testing.allocator;
const rules =
\\light red bags contain 1 bright white bag, 2 muted yellow bags.
\\dark orange bags contain 3 bright white bags, 4 muted yellow bags.
\\bright white bags contain 1 shiny gold bag.
\\muted yellow bags contain 2 shiny gold bags, 9 faded blue bags.
\\shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags.
\\dark olive bags contain 3 faded blue bags, 4 dotted black bags.
\\vibrant plum bags contain 5 faded blue bags, 6 dotted black bags.
\\faded blue bags contain no other bags.
\\dotted black bags contain no other bags.
\\
;
var fbs = std.io.fixedBufferStream(rules);
const reader = fbs.reader();
var parsed = try parseRules(allocator, reader);
defer freeRules(allocator, &parsed);
try testing.expectEqualSlices(u8, (parsed.get("light red").?)[0].color, "bright white");
try testing.expectEqual(@as(u32, 1), (parsed.get("light red").?)[0].amount);
try testing.expectEqualSlices(u8, (parsed.get("light red").?)[1].color, "muted yellow");
try testing.expectEqual(@as(u32, 2), (parsed.get("light red").?)[1].amount);
try testing.expectEqualSlices(u8, (parsed.get("bright white").?)[0].color, "shiny gold");
try testing.expectEqual(@as(usize, 0), (parsed.get("faded blue").?).len);
}
fn countInnerBags(rules: Rules, target_color: []const u8) u32 {
var sum: u32 = 0;
const children = rules.get(target_color).?;
for (children) |child| {
sum += child.amount * (1 + countInnerBags(rules, child.color));
}
return sum;
}
test "count inner bags" {
const allocator = std.testing.allocator;
const rules =
\\shiny gold bags contain 2 dark red bags.
\\dark red bags contain 2 dark orange bags.
\\dark orange bags contain 2 dark yellow bags.
\\dark yellow bags contain 2 dark green bags.
\\dark green bags contain 2 dark blue bags.
\\dark blue bags contain 2 dark violet bags.
\\dark violet bags contain no other bags.
\\
;
var fbs = std.io.fixedBufferStream(rules);
const reader = fbs.reader();
var parsed = try parseRules(allocator, reader);
defer freeRules(allocator, &parsed);
try testing.expectEqual(@as(u32, 126), countInnerBags(parsed, "shiny gold"));
}
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = &gpa.allocator;
var file = try std.fs.cwd().openFile(input_file, .{});
defer file.close();
const reader = file.reader();
var parsed = try parseRules(allocator, reader);
defer freeRules(allocator, &parsed);
std.debug.warn("inner bags: {}\n", .{countInnerBags(parsed, "shiny gold")});
}
|
src/07_2.zig
|
const std = @import("std");
const assert = std.debug.assert;
const warn = std.debug.warn;
const zero_struct = @import("util.zig").zero_struct;
pub const sokol = @cImport({
@cDefine("CIMGUI_DEFINE_ENUMS_AND_STRUCTS", "");
@cInclude("sokol/sokol_app.h");
@cInclude("sokol/sokol_gfx.h");
@cInclude("sokol/sokol_time.h");
@cInclude("cimgui/cimgui.h");
@cInclude("sokol/util/sokol_imgui.h");
});
const SokolState = struct {
pass_action: sokol.sg_pass_action = undefined,
};
pub const AppInitFunc = fn (user_data: *c_void) void;
pub const AppUpdateFunc = fn (dt: f64, total_time: f64, user_data: *c_void) bool;
pub const AppState = struct {
init_func: AppInitFunc,
cleanup_func: AppInitFunc,
update_func: AppUpdateFunc,
user_data: *c_void,
};
var sokol_state: SokolState = undefined;
var last_time: u64 = 0;
pub export fn init(user_data: ?*c_void) void {
var desc = zero_struct(sokol.sg_desc);
sokol.sg_setup(&desc);
sokol.stm_setup();
var imgui_desc = zero_struct(sokol.simgui_desc_t);
sokol.simgui_setup(&imgui_desc);
sokol_state.pass_action.colors[0].action = sokol.SG_ACTION_CLEAR;
sokol_state.pass_action.colors[0].val = [_]f32{ 0.1, 0.3, 0.1, 1.0 };
var state = @ptrCast([*]AppState, @alignCast(@alignOf([*]AppState), user_data));
state.*.init_func(state.*.user_data);
}
pub export fn deinit(user_data: ?*c_void) void {
sokol.simgui_shutdown();
sokol.sg_shutdown();
}
pub export fn update(user_data: ?*c_void) void {
var state = @ptrCast([*]AppState, @alignCast(@alignOf([*]AppState), user_data));
const width = sokol.sapp_width();
const height = sokol.sapp_height();
const dt = sokol.stm_sec(sokol.stm_laptime(&last_time));
var quit = state.*.update_func(dt, 0, state.*.user_data);
sokol.simgui_new_frame(width, height, dt);
sokol.igText(c"Zag!");
sokol.sg_begin_default_pass(&sokol_state.pass_action, width, height);
sokol.simgui_render();
sokol.sg_end_pass();
sokol.sg_commit();
if (quit) {
sokol.sapp_quit();
}
}
pub export fn event(ev: [*c]const sokol.sapp_event) void {
_ = sokol.simgui_handle_event(ev);
}
|
code/main/main_sokol.zig
|
const std = @import("std");
const mem = std.mem;
const testing = std.testing;
const EditorMode = @import("state.zig").EditorMode;
const zzz = @import("zzz");
const kisa = @import("kisa");
// TODO: display errors from config parsing.
pub const allowed_keypress_commands = [_]kisa.CommandKind{
.nop,
.insert_character,
.cursor_move_down,
.cursor_move_left,
.cursor_move_right,
.cursor_move_up,
.quit,
.save,
.delete_line,
.delete_word,
};
/// Must call first `init`, then `setup` for initialization.
/// Call `addConfigFile` to continuously add more and more config files in order of
/// precedence from lowest to highest. After that corresponding fields such as `keymap`
/// will be populated.
pub const Config = struct {
arena: std.heap.ArenaAllocator,
ally: *mem.Allocator,
sources: std.ArrayList([]const u8),
tree: Tree,
keymap: Keymap,
const max_files = 32;
const max_nodes = 2048;
pub const Tree = zzz.ZTree(max_files, max_nodes);
pub const Keymap = std.AutoHashMap(EditorMode, Bindings);
pub const KeysToActions = std.HashMap(
kisa.Key,
Actions,
kisa.Key.HashMapContext,
std.hash_map.default_max_load_percentage,
);
pub const Bindings = struct {
default: Actions,
keys: KeysToActions,
};
pub const Actions = std.ArrayList(kisa.CommandKind);
const Self = @This();
pub fn init(ally: *mem.Allocator) Self {
return Self{
.arena = std.heap.ArenaAllocator.init(ally),
.ally = undefined,
.sources = undefined,
.tree = undefined,
.keymap = undefined,
};
}
pub fn setup(self: *Self) !void {
self.ally = &self.arena.allocator;
self.sources = std.ArrayList([]const u8).init(self.ally);
self.tree = Tree{};
self.keymap = Keymap.init(self.ally);
inline for (std.meta.fields(EditorMode)) |enum_field| {
try self.keymap.put(@intToEnum(EditorMode, enum_field.value), Bindings{
.default = Actions.init(self.ally),
.keys = KeysToActions.init(self.ally),
});
}
}
pub fn deinit(self: *Self) void {
self.arena.deinit();
}
/// Add a config file.
pub fn addConfigFile(self: *Self, absolute_path: []const u8) !void {
var file = try std.fs.openFileAbsolute(absolute_path, .{});
defer file.close();
const text = try file.readToEndAlloc(self.ally, std.math.maxInt(usize));
try self.addConfig(text, false);
}
// TODO: add several config files loading.
/// Add config to current tree of configs. Several configs can be added consecutively,
/// order matters, configs must be added from lowest to highest precedence. When `default`
/// is `true`, it means that this is the very first initialization of a config and all the
/// values must be present, it is an error if any value is missing.
pub fn addConfig(self: *Self, content: []const u8, default: bool) !void {
const root = try self.tree.appendText(content);
if (root.findNth(0, .{ .String = "keymap" })) |keymap| {
var mode_it = keymap.nextChild(null);
while (mode_it) |mode| : (mode_it = keymap.nextChild(mode_it)) {
const mode_name = switch (mode.value) {
.String => |val| val,
else => return error.IncorrectModeName,
};
if (std.meta.stringToEnum(EditorMode, mode_name)) |editor_mode| {
var bindings = self.keymap.getPtr(editor_mode).?;
var bindings_it = mode.nextChild(null);
while (bindings_it) |binding| : (bindings_it = mode.nextChild(bindings_it)) {
var key_binding = blk: {
if (mem.eql(u8, "default", binding.value.String)) {
break :blk &bindings.default;
} else {
const key = try parseKeyDefinition(binding.value.String);
try bindings.keys.put(key, Actions.init(self.ally));
break :blk bindings.keys.getPtr(key).?;
}
};
var actions_it = binding.nextChild(null);
while (actions_it) |action| : (actions_it = binding.nextChild(actions_it)) {
action_loop: {
switch (action.value) {
.String => |val| {
const command_kind = std.meta.stringToEnum(
kisa.CommandKind,
val,
) orelse {
std.debug.print("Unknown key action: {s}\n", .{val});
return error.UnknownKeyAction;
};
for (allowed_keypress_commands) |allowed_command_kind| {
if (command_kind == allowed_command_kind) {
try key_binding.append(command_kind);
break :action_loop;
}
}
std.debug.print("{s}\n", .{command_kind});
return error.UnallowedKeyAction;
},
else => unreachable,
}
}
}
}
if (default and bindings.default.items.len == 0) return error.MissingDefault;
} else {
return error.UnknownMode;
}
}
}
}
pub fn resolveKey(self: Self, key: kisa.Key) kisa.Command {
const actions = self.keymap.get(.normal).?.keys.get(key) orelse self.keymap.get(.normal).?.default;
// TODO: different actions and proper casting with this type system.
switch (actions.items[0]) {
.cursor_move_down => {
return @unionInit(kisa.Command, "cursor_move_down", {});
},
else => @panic("Not implemented"),
}
}
fn parseKeyDefinition(string: []const u8) !kisa.Key {
if (string.len == 1) {
return kisa.Key.ascii(string[0]);
} else if (special_keycode_map.get(string)) |keycode| {
return kisa.Key{ .code = keycode };
} else {
var key = kisa.Key{ .code = undefined };
var it = mem.split(string, "-");
while (it.next()) |part| {
if (part.len == 1) {
key.code = kisa.Key.ascii(part[0]).code;
return key;
} else if (special_keycode_map.get(part)) |keycode| {
key.code = keycode;
return key;
} else if (mem.eql(u8, "ctrl", part)) {
key.addCtrl();
} else if (mem.eql(u8, "shift", part)) {
key.addShift();
} else if (mem.eql(u8, "alt", part)) {
key.addAlt();
} else if (mem.eql(u8, "super", part)) {
key.addSuper();
} else {
return error.UnknownKeyDefinition;
}
}
return error.UnknownKeyDefinition;
}
}
const special_keycode_map = std.ComptimeStringMap(kisa.keys.KeyCode, .{
.{ "arrow_up", .{ .keysym = .arrow_up } },
.{ "arrow_down", .{ .keysym = .arrow_down } },
.{ "arrow_left", .{ .keysym = .arrow_left } },
.{ "arrow_right", .{ .keysym = .arrow_right } },
.{ "mouse_button_left", .{ .mouse_button = .left } },
.{ "mouse_button_middle", .{ .mouse_button = .middle } },
.{ "mouse_button_right", .{ .mouse_button = .right } },
.{ "mouse_scroll_up", .{ .mouse_button = .scroll_up } },
.{ "mouse_scroll_down", .{ .mouse_button = .scroll_down } },
.{ "f1", .{ .function = 1 } },
.{ "f2", .{ .function = 2 } },
.{ "f3", .{ .function = 3 } },
.{ "f4", .{ .function = 4 } },
.{ "f5", .{ .function = 5 } },
.{ "f6", .{ .function = 6 } },
.{ "f7", .{ .function = 7 } },
.{ "f8", .{ .function = 8 } },
.{ "f9", .{ .function = 9 } },
.{ "f10", .{ .function = 10 } },
.{ "f11", .{ .function = 11 } },
.{ "f12", .{ .function = 12 } },
});
pub fn format(
value: Self,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = options;
if (fmt.len == 0 or fmt.len == 1 and fmt[0] == 's') {
const start_fmt =
\\Config:
\\ keymap:
\\
;
const mode_fmt =
\\ {s}:
\\
;
const keybinding_single_fmt =
\\ {s}: {s}
\\
;
const keybinding_key_fmt =
\\ {s}:
\\
;
const keybinding_value_fmt =
\\ {s}
\\
;
try std.fmt.format(writer, start_fmt, .{});
var keymap_it = value.keymap.iterator();
while (keymap_it.next()) |keymap_entry| {
const mode = keymap_entry.key_ptr.*;
const bindings = keymap_entry.value_ptr.*;
try std.fmt.format(writer, mode_fmt, .{std.meta.tagName(mode)});
try std.fmt.format(writer, keybinding_single_fmt, .{ "default", bindings.default.items[0] });
var bindings_it = bindings.keys.iterator();
while (bindings_it.next()) |binding_entry| {
const key = binding_entry.key_ptr.*;
const actions = binding_entry.value_ptr.*;
if (actions.items.len == 1) {
try std.fmt.format(writer, keybinding_single_fmt, .{ key, actions.items[0] });
} else {
try std.fmt.format(writer, keybinding_key_fmt, .{key});
for (actions.items) |action| {
try std.fmt.format(writer, keybinding_value_fmt, .{action});
}
}
}
}
} else {
@compileError("Unknown format character for Config: '" ++ fmt ++ "'");
}
}
};
test "config: add default config" {
var ally = testing.allocator;
const config_content =
\\keymap:
\\ normal:
\\ h: cursor_move_left
\\ j: cursor_move_down
\\ k: cursor_move_up
\\ l: cursor_move_right
\\ n:
\\ cursor_move_down
\\ cursor_move_right
\\ default: nop
\\ insert:
\\ default: insert_character
\\ ctrl-alt-c: quit
\\ ctrl-s: save
\\ shift-d: delete_word
\\ arrow_up: cursor_move_up
\\ super-arrow_up: delete_line
;
var config = Config.init(ally);
defer config.deinit();
try config.setup();
try config.addConfig(config_content, true);
const normal = config.keymap.get(.normal).?;
const nkeys = normal.keys;
const insert = config.keymap.get(.insert).?;
const ikeys = insert.keys;
const key_arrow_up = kisa.Key{ .code = .{ .keysym = .arrow_up } };
const key_super_arrow_up = blk: {
var key = kisa.Key{ .code = .{ .keysym = .arrow_up } };
key.addSuper();
break :blk key;
};
var ctrl_alt_c = kisa.Key.ascii('c');
ctrl_alt_c.addCtrl();
ctrl_alt_c.addAlt();
try testing.expectEqual(@as(usize, 2), config.keymap.count());
try testing.expectEqual(@as(usize, 5), nkeys.count());
try testing.expectEqual(@as(usize, 5), ikeys.count());
try testing.expectEqual(@as(usize, 1), normal.default.items.len);
try testing.expectEqual(kisa.CommandKind.nop, normal.default.items[0]);
try testing.expectEqual(@as(usize, 1), nkeys.get(kisa.Key.ascii('h')).?.items.len);
try testing.expectEqual(kisa.CommandKind.cursor_move_left, nkeys.get(kisa.Key.ascii('h')).?.items[0]);
try testing.expectEqual(@as(usize, 1), nkeys.get(kisa.Key.ascii('j')).?.items.len);
try testing.expectEqual(kisa.CommandKind.cursor_move_down, nkeys.get(kisa.Key.ascii('j')).?.items[0]);
try testing.expectEqual(@as(usize, 1), nkeys.get(kisa.Key.ascii('k')).?.items.len);
try testing.expectEqual(kisa.CommandKind.cursor_move_up, nkeys.get(kisa.Key.ascii('k')).?.items[0]);
try testing.expectEqual(@as(usize, 1), nkeys.get(kisa.Key.ascii('l')).?.items.len);
try testing.expectEqual(kisa.CommandKind.cursor_move_right, nkeys.get(kisa.Key.ascii('l')).?.items[0]);
try testing.expectEqual(@as(usize, 2), nkeys.get(kisa.Key.ascii('n')).?.items.len);
try testing.expectEqual(kisa.CommandKind.cursor_move_down, nkeys.get(kisa.Key.ascii('n')).?.items[0]);
try testing.expectEqual(kisa.CommandKind.cursor_move_right, nkeys.get(kisa.Key.ascii('n')).?.items[1]);
try testing.expectEqual(@as(usize, 1), insert.default.items.len);
try testing.expectEqual(kisa.CommandKind.insert_character, insert.default.items[0]);
try testing.expectEqual(@as(usize, 1), ikeys.get(kisa.Key.ctrl('s')).?.items.len);
try testing.expectEqual(kisa.CommandKind.save, ikeys.get(kisa.Key.ctrl('s')).?.items[0]);
try testing.expectEqual(@as(usize, 1), ikeys.get(kisa.Key.shift('d')).?.items.len);
try testing.expectEqual(kisa.CommandKind.delete_word, ikeys.get(kisa.Key.shift('d')).?.items[0]);
try testing.expectEqual(@as(usize, 1), ikeys.get(key_arrow_up).?.items.len);
try testing.expectEqual(kisa.CommandKind.cursor_move_up, ikeys.get(key_arrow_up).?.items[0]);
try testing.expectEqual(@as(usize, 1), ikeys.get(key_super_arrow_up).?.items.len);
try testing.expectEqual(kisa.CommandKind.delete_line, ikeys.get(key_super_arrow_up).?.items[0]);
try testing.expectEqual(@as(usize, 1), ikeys.get(ctrl_alt_c).?.items.len);
try testing.expectEqual(kisa.CommandKind.quit, ikeys.get(ctrl_alt_c).?.items[0]);
}
|
src/config.zig
|
const std = @import("std");
pub fn build(b: *std.build.Builder) void {
const target = b.standardTargetOptions(.{});
const mode = b.standardReleaseOptions();
const exe = b.addExecutable("kisa", "src/main.zig");
exe.addPackagePath("zzz", "libs/zzz/src/main.zig");
exe.addPackagePath("known-folders", "libs/known-folders/known-folders.zig");
exe.addPackagePath("ziglyph", "libs/ziglyph/src/ziglyph.zig");
exe.addPackagePath("zigstr", "libs/zigstr/src/Zigstr.zig");
exe.addPackagePath("kisa", "src/kisa.zig");
exe.setTarget(target);
exe.setBuildMode(mode);
exe.install();
const run_cmd = exe.run();
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
const test_all = b.step("test", "Run tests");
const test_main = b.step("test-main", "Run tests in main");
const test_main_nofork = b.step("test-main-nofork", "Run tests in main without forking");
const test_state = b.step("test-state", "Run tests in state");
const test_config = b.step("test-config", "Run tests in config");
const test_jsonrpc = b.step("test-jsonrpc", "Run tests in jsonrpc");
const test_transport = b.step("test-transport", "Run tests in transport");
const test_rpc = b.step("test-rpc", "Run tests in rpc");
const test_keys = b.step("test-keys", "Run tests in keys");
{
var test_cases = b.addTest("src/main.zig");
test_cases.setFilter("main:");
test_cases.addPackagePath("zzz", "libs/zzz/src/main.zig");
test_cases.addPackagePath("known-folders", "libs/known-folders/known-folders.zig");
test_cases.addPackagePath("ziglyph", "libs/ziglyph/src/ziglyph.zig");
test_cases.addPackagePath("zigstr", "libs/zigstr/src/Zigstr.zig");
test_cases.addPackagePath("kisa", "src/kisa.zig");
test_cases.setTarget(target);
test_cases.setBuildMode(mode);
test_all.dependOn(&test_cases.step);
test_main.dependOn(&test_cases.step);
test_main_nofork.dependOn(&test_cases.step);
}
{
// Forked tests must be run 1 at a time, otherwise they interfere with other tests.
var test_cases = b.addTest("src/main.zig");
test_cases.setFilter("fork/socket:");
test_cases.addPackagePath("zzz", "libs/zzz/src/main.zig");
test_cases.addPackagePath("known-folders", "libs/known-folders/known-folders.zig");
test_cases.addPackagePath("ziglyph", "libs/ziglyph/src/ziglyph.zig");
test_cases.addPackagePath("zigstr", "libs/zigstr/src/Zigstr.zig");
test_cases.addPackagePath("kisa", "src/kisa.zig");
test_cases.setTarget(target);
test_cases.setBuildMode(mode);
test_all.dependOn(&test_cases.step);
test_main.dependOn(&test_cases.step);
}
{
const test_cases = b.addTest("src/state.zig");
test_cases.setFilter("state:");
test_cases.addPackagePath("zzz", "libs/zzz/src/main.zig");
test_cases.addPackagePath("known-folders", "libs/known-folders/known-folders.zig");
test_cases.addPackagePath("ziglyph", "libs/ziglyph/src/ziglyph.zig");
test_cases.addPackagePath("zigstr", "libs/zigstr/src/Zigstr.zig");
test_cases.addPackagePath("kisa", "src/kisa.zig");
test_cases.setTarget(target);
test_cases.setBuildMode(mode);
test_all.dependOn(&test_cases.step);
test_state.dependOn(&test_cases.step);
}
{
const test_cases = b.addTest("src/config.zig");
test_cases.setFilter("config:");
test_cases.addPackagePath("zzz", "libs/zzz/src/main.zig");
test_cases.addPackagePath("known-folders", "libs/known-folders/known-folders.zig");
test_cases.addPackagePath("kisa", "src/kisa.zig");
test_cases.setTarget(target);
test_cases.setBuildMode(mode);
test_all.dependOn(&test_cases.step);
test_config.dependOn(&test_cases.step);
}
{
const test_cases = b.addTest("src/jsonrpc.zig");
test_cases.setFilter("jsonrpc:");
test_cases.setTarget(target);
test_cases.setBuildMode(mode);
test_all.dependOn(&test_cases.step);
test_jsonrpc.dependOn(&test_cases.step);
}
{
const test_cases = b.addTest("src/transport.zig");
test_cases.setFilter("transport/fork1:");
test_cases.addPackagePath("known-folders", "libs/known-folders/known-folders.zig");
test_cases.setTarget(target);
test_cases.setBuildMode(mode);
test_all.dependOn(&test_cases.step);
test_transport.dependOn(&test_cases.step);
}
{
const test_cases = b.addTest("src/transport.zig");
test_cases.setFilter("transport/fork2:");
test_cases.addPackagePath("known-folders", "libs/known-folders/known-folders.zig");
test_cases.setTarget(target);
test_cases.setBuildMode(mode);
test_all.dependOn(&test_cases.step);
test_transport.dependOn(&test_cases.step);
}
{
const test_cases = b.addTest("src/rpc.zig");
test_cases.setFilter("myrpc:");
test_cases.setTarget(target);
test_cases.setBuildMode(mode);
test_all.dependOn(&test_cases.step);
test_rpc.dependOn(&test_cases.step);
}
{
const test_cases = b.addTest("src/keys.zig");
test_cases.setFilter("keys:");
test_cases.setTarget(target);
test_cases.setBuildMode(mode);
test_all.dependOn(&test_cases.step);
test_keys.dependOn(&test_cases.step);
}
}
|
build.zig
|
const std = @import("../index.zig");
const builtin = @import("builtin");
const Os = builtin.Os;
const debug = std.debug;
const assert = debug.assert;
const mem = std.mem;
const fmt = std.fmt;
const Allocator = mem.Allocator;
const os = std.os;
const math = std.math;
const posix = os.posix;
const windows = os.windows;
const cstr = std.cstr;
const windows_util = @import("windows/util.zig");
pub const sep_windows = '\\';
pub const sep_posix = '/';
pub const sep = if (is_windows) sep_windows else sep_posix;
pub const sep_str = [1]u8{sep};
pub const delimiter_windows = ';';
pub const delimiter_posix = ':';
pub const delimiter = if (is_windows) delimiter_windows else delimiter_posix;
const is_windows = builtin.os == builtin.Os.windows;
pub fn isSep(byte: u8) bool {
if (is_windows) {
return byte == '/' or byte == '\\';
} else {
return byte == '/';
}
}
/// Naively combines a series of paths with the native path seperator.
/// Allocates memory for the result, which must be freed by the caller.
pub fn join(allocator: *Allocator, paths: ...) ![]u8 {
if (is_windows) {
return joinWindows(allocator, paths);
} else {
return joinPosix(allocator, paths);
}
}
pub fn joinWindows(allocator: *Allocator, paths: ...) ![]u8 {
return mem.join(allocator, sep_windows, paths);
}
pub fn joinPosix(allocator: *Allocator, paths: ...) ![]u8 {
return mem.join(allocator, sep_posix, paths);
}
test "os.path.join" {
assert(mem.eql(u8, try joinWindows(debug.global_allocator, "c:\\a\\b", "c"), "c:\\a\\b\\c"));
assert(mem.eql(u8, try joinWindows(debug.global_allocator, "c:\\a\\b\\", "c"), "c:\\a\\b\\c"));
assert(mem.eql(u8, try joinWindows(debug.global_allocator, "c:\\", "a", "b\\", "c"), "c:\\a\\b\\c"));
assert(mem.eql(u8, try joinWindows(debug.global_allocator, "c:\\a\\", "b\\", "c"), "c:\\a\\b\\c"));
assert(mem.eql(u8, try joinWindows(debug.global_allocator, "c:\\home\\andy\\dev\\zig\\build\\lib\\zig\\std", "io.zig"), "c:\\home\\andy\\dev\\zig\\build\\lib\\zig\\std\\io.zig"));
assert(mem.eql(u8, try joinPosix(debug.global_allocator, "/a/b", "c"), "/a/b/c"));
assert(mem.eql(u8, try joinPosix(debug.global_allocator, "/a/b/", "c"), "/a/b/c"));
assert(mem.eql(u8, try joinPosix(debug.global_allocator, "/", "a", "b/", "c"), "/a/b/c"));
assert(mem.eql(u8, try joinPosix(debug.global_allocator, "/a/", "b/", "c"), "/a/b/c"));
assert(mem.eql(u8, try joinPosix(debug.global_allocator, "/home/andy/dev/zig/build/lib/zig/std", "io.zig"), "/home/andy/dev/zig/build/lib/zig/std/io.zig"));
}
pub fn isAbsolute(path: []const u8) bool {
if (is_windows) {
return isAbsoluteWindows(path);
} else {
return isAbsolutePosix(path);
}
}
pub fn isAbsoluteWindows(path: []const u8) bool {
if (path[0] == '/')
return true;
if (path[0] == '\\') {
return true;
}
if (path.len < 3) {
return false;
}
if (path[1] == ':') {
if (path[2] == '/')
return true;
if (path[2] == '\\')
return true;
}
return false;
}
pub fn isAbsolutePosix(path: []const u8) bool {
return path[0] == sep_posix;
}
test "os.path.isAbsoluteWindows" {
testIsAbsoluteWindows("/", true);
testIsAbsoluteWindows("//", true);
testIsAbsoluteWindows("//server", true);
testIsAbsoluteWindows("//server/file", true);
testIsAbsoluteWindows("\\\\server\\file", true);
testIsAbsoluteWindows("\\\\server", true);
testIsAbsoluteWindows("\\\\", true);
testIsAbsoluteWindows("c", false);
testIsAbsoluteWindows("c:", false);
testIsAbsoluteWindows("c:\\", true);
testIsAbsoluteWindows("c:/", true);
testIsAbsoluteWindows("c://", true);
testIsAbsoluteWindows("C:/Users/", true);
testIsAbsoluteWindows("C:\\Users\\", true);
testIsAbsoluteWindows("C:cwd/another", false);
testIsAbsoluteWindows("C:cwd\\another", false);
testIsAbsoluteWindows("directory/directory", false);
testIsAbsoluteWindows("directory\\directory", false);
testIsAbsoluteWindows("/usr/local", true);
}
test "os.path.isAbsolutePosix" {
testIsAbsolutePosix("/home/foo", true);
testIsAbsolutePosix("/home/foo/..", true);
testIsAbsolutePosix("bar/", false);
testIsAbsolutePosix("./baz", false);
}
fn testIsAbsoluteWindows(path: []const u8, expected_result: bool) void {
assert(isAbsoluteWindows(path) == expected_result);
}
fn testIsAbsolutePosix(path: []const u8, expected_result: bool) void {
assert(isAbsolutePosix(path) == expected_result);
}
pub const WindowsPath = struct {
is_abs: bool,
kind: Kind,
disk_designator: []const u8,
pub const Kind = enum {
None,
Drive,
NetworkShare,
};
};
pub fn windowsParsePath(path: []const u8) WindowsPath {
if (path.len >= 2 and path[1] == ':') {
return WindowsPath{
.is_abs = isAbsoluteWindows(path),
.kind = WindowsPath.Kind.Drive,
.disk_designator = path[0..2],
};
}
if (path.len >= 1 and (path[0] == '/' or path[0] == '\\') and
(path.len == 1 or (path[1] != '/' and path[1] != '\\')))
{
return WindowsPath{
.is_abs = true,
.kind = WindowsPath.Kind.None,
.disk_designator = path[0..0],
};
}
const relative_path = WindowsPath{
.kind = WindowsPath.Kind.None,
.disk_designator = []u8{},
.is_abs = false,
};
if (path.len < "//a/b".len) {
return relative_path;
}
// TODO when I combined these together with `inline for` the compiler crashed
{
const this_sep = '/';
const two_sep = []u8{ this_sep, this_sep };
if (mem.startsWith(u8, path, two_sep)) {
if (path[2] == this_sep) {
return relative_path;
}
var it = mem.split(path, []u8{this_sep});
_ = (it.next() orelse return relative_path);
_ = (it.next() orelse return relative_path);
return WindowsPath{
.is_abs = isAbsoluteWindows(path),
.kind = WindowsPath.Kind.NetworkShare,
.disk_designator = path[0..it.index],
};
}
}
{
const this_sep = '\\';
const two_sep = []u8{ this_sep, this_sep };
if (mem.startsWith(u8, path, two_sep)) {
if (path[2] == this_sep) {
return relative_path;
}
var it = mem.split(path, []u8{this_sep});
_ = (it.next() orelse return relative_path);
_ = (it.next() orelse return relative_path);
return WindowsPath{
.is_abs = isAbsoluteWindows(path),
.kind = WindowsPath.Kind.NetworkShare,
.disk_designator = path[0..it.index],
};
}
}
return relative_path;
}
test "os.path.windowsParsePath" {
{
const parsed = windowsParsePath("//a/b");
assert(parsed.is_abs);
assert(parsed.kind == WindowsPath.Kind.NetworkShare);
assert(mem.eql(u8, parsed.disk_designator, "//a/b"));
}
{
const parsed = windowsParsePath("\\\\a\\b");
assert(parsed.is_abs);
assert(parsed.kind == WindowsPath.Kind.NetworkShare);
assert(mem.eql(u8, parsed.disk_designator, "\\\\a\\b"));
}
{
const parsed = windowsParsePath("\\\\a\\");
assert(!parsed.is_abs);
assert(parsed.kind == WindowsPath.Kind.None);
assert(mem.eql(u8, parsed.disk_designator, ""));
}
{
const parsed = windowsParsePath("/usr/local");
assert(parsed.is_abs);
assert(parsed.kind == WindowsPath.Kind.None);
assert(mem.eql(u8, parsed.disk_designator, ""));
}
{
const parsed = windowsParsePath("c:../");
assert(!parsed.is_abs);
assert(parsed.kind == WindowsPath.Kind.Drive);
assert(mem.eql(u8, parsed.disk_designator, "c:"));
}
}
pub fn diskDesignator(path: []const u8) []const u8 {
if (is_windows) {
return diskDesignatorWindows(path);
} else {
return "";
}
}
pub fn diskDesignatorWindows(path: []const u8) []const u8 {
return windowsParsePath(path).disk_designator;
}
fn networkShareServersEql(ns1: []const u8, ns2: []const u8) bool {
const sep1 = ns1[0];
const sep2 = ns2[0];
var it1 = mem.split(ns1, []u8{sep1});
var it2 = mem.split(ns2, []u8{sep2});
// TODO ASCII is wrong, we actually need full unicode support to compare paths.
return asciiEqlIgnoreCase(it1.next().?, it2.next().?);
}
fn compareDiskDesignators(kind: WindowsPath.Kind, p1: []const u8, p2: []const u8) bool {
switch (kind) {
WindowsPath.Kind.None => {
assert(p1.len == 0);
assert(p2.len == 0);
return true;
},
WindowsPath.Kind.Drive => {
return asciiUpper(p1[0]) == asciiUpper(p2[0]);
},
WindowsPath.Kind.NetworkShare => {
const sep1 = p1[0];
const sep2 = p2[0];
var it1 = mem.split(p1, []u8{sep1});
var it2 = mem.split(p2, []u8{sep2});
// TODO ASCII is wrong, we actually need full unicode support to compare paths.
return asciiEqlIgnoreCase(it1.next().?, it2.next().?) and asciiEqlIgnoreCase(it1.next().?, it2.next().?);
},
}
}
fn asciiUpper(byte: u8) u8 {
return switch (byte) {
'a'...'z' => 'A' + (byte - 'a'),
else => byte,
};
}
fn asciiEqlIgnoreCase(s1: []const u8, s2: []const u8) bool {
if (s1.len != s2.len)
return false;
var i: usize = 0;
while (i < s1.len) : (i += 1) {
if (asciiUpper(s1[i]) != asciiUpper(s2[i]))
return false;
}
return true;
}
/// Converts the command line arguments into a slice and calls `resolveSlice`.
pub fn resolve(allocator: *Allocator, args: ...) ![]u8 {
var paths: [args.len][]const u8 = undefined;
comptime var arg_i = 0;
inline while (arg_i < args.len) : (arg_i += 1) {
paths[arg_i] = args[arg_i];
}
return resolveSlice(allocator, paths);
}
/// On Windows, this calls `resolveWindows` and on POSIX it calls `resolvePosix`.
pub fn resolveSlice(allocator: *Allocator, paths: []const []const u8) ![]u8 {
if (is_windows) {
return resolveWindows(allocator, paths);
} else {
return resolvePosix(allocator, paths);
}
}
/// This function is like a series of `cd` statements executed one after another.
/// It resolves "." and "..".
/// The result does not have a trailing path separator.
/// If all paths are relative it uses the current working directory as a starting point.
/// Each drive has its own current working directory.
/// Path separators are canonicalized to '\\' and drives are canonicalized to capital letters.
pub fn resolveWindows(allocator: *Allocator, paths: []const []const u8) ![]u8 {
if (paths.len == 0) {
assert(is_windows); // resolveWindows called on non windows can't use getCwd
return os.getCwdAlloc(allocator);
}
// determine which disk designator we will result with, if any
var result_drive_buf = "_:";
var result_disk_designator: []const u8 = "";
var have_drive_kind = WindowsPath.Kind.None;
var have_abs_path = false;
var first_index: usize = 0;
var max_size: usize = 0;
for (paths) |p, i| {
const parsed = windowsParsePath(p);
if (parsed.is_abs) {
have_abs_path = true;
first_index = i;
max_size = result_disk_designator.len;
}
switch (parsed.kind) {
WindowsPath.Kind.Drive => {
result_drive_buf[0] = asciiUpper(parsed.disk_designator[0]);
result_disk_designator = result_drive_buf[0..];
have_drive_kind = WindowsPath.Kind.Drive;
},
WindowsPath.Kind.NetworkShare => {
result_disk_designator = parsed.disk_designator;
have_drive_kind = WindowsPath.Kind.NetworkShare;
},
WindowsPath.Kind.None => {},
}
max_size += p.len + 1;
}
// if we will result with a disk designator, loop again to determine
// which is the last time the disk designator is absolutely specified, if any
// and count up the max bytes for paths related to this disk designator
if (have_drive_kind != WindowsPath.Kind.None) {
have_abs_path = false;
first_index = 0;
max_size = result_disk_designator.len;
var correct_disk_designator = false;
for (paths) |p, i| {
const parsed = windowsParsePath(p);
if (parsed.kind != WindowsPath.Kind.None) {
if (parsed.kind == have_drive_kind) {
correct_disk_designator = compareDiskDesignators(have_drive_kind, result_disk_designator, parsed.disk_designator);
} else {
continue;
}
}
if (!correct_disk_designator) {
continue;
}
if (parsed.is_abs) {
first_index = i;
max_size = result_disk_designator.len;
have_abs_path = true;
}
max_size += p.len + 1;
}
}
// Allocate result and fill in the disk designator, calling getCwd if we have to.
var result: []u8 = undefined;
var result_index: usize = 0;
if (have_abs_path) {
switch (have_drive_kind) {
WindowsPath.Kind.Drive => {
result = try allocator.alloc(u8, max_size);
mem.copy(u8, result, result_disk_designator);
result_index += result_disk_designator.len;
},
WindowsPath.Kind.NetworkShare => {
result = try allocator.alloc(u8, max_size);
var it = mem.split(paths[first_index], "/\\");
const server_name = it.next().?;
const other_name = it.next().?;
result[result_index] = '\\';
result_index += 1;
result[result_index] = '\\';
result_index += 1;
mem.copy(u8, result[result_index..], server_name);
result_index += server_name.len;
result[result_index] = '\\';
result_index += 1;
mem.copy(u8, result[result_index..], other_name);
result_index += other_name.len;
result_disk_designator = result[0..result_index];
},
WindowsPath.Kind.None => {
assert(is_windows); // resolveWindows called on non windows can't use getCwd
const cwd = try os.getCwdAlloc(allocator);
defer allocator.free(cwd);
const parsed_cwd = windowsParsePath(cwd);
result = try allocator.alloc(u8, max_size + parsed_cwd.disk_designator.len + 1);
mem.copy(u8, result, parsed_cwd.disk_designator);
result_index += parsed_cwd.disk_designator.len;
result_disk_designator = result[0..parsed_cwd.disk_designator.len];
if (parsed_cwd.kind == WindowsPath.Kind.Drive) {
result[0] = asciiUpper(result[0]);
}
have_drive_kind = parsed_cwd.kind;
},
}
} else {
assert(is_windows); // resolveWindows called on non windows can't use getCwd
// TODO call get cwd for the result_disk_designator instead of the global one
const cwd = try os.getCwdAlloc(allocator);
defer allocator.free(cwd);
result = try allocator.alloc(u8, max_size + cwd.len + 1);
mem.copy(u8, result, cwd);
result_index += cwd.len;
const parsed_cwd = windowsParsePath(result[0..result_index]);
result_disk_designator = parsed_cwd.disk_designator;
if (parsed_cwd.kind == WindowsPath.Kind.Drive) {
result[0] = asciiUpper(result[0]);
}
have_drive_kind = parsed_cwd.kind;
}
errdefer allocator.free(result);
// Now we know the disk designator to use, if any, and what kind it is. And our result
// is big enough to append all the paths to.
var correct_disk_designator = true;
for (paths[first_index..]) |p, i| {
const parsed = windowsParsePath(p);
if (parsed.kind != WindowsPath.Kind.None) {
if (parsed.kind == have_drive_kind) {
correct_disk_designator = compareDiskDesignators(have_drive_kind, result_disk_designator, parsed.disk_designator);
} else {
continue;
}
}
if (!correct_disk_designator) {
continue;
}
var it = mem.split(p[parsed.disk_designator.len..], "/\\");
while (it.next()) |component| {
if (mem.eql(u8, component, ".")) {
continue;
} else if (mem.eql(u8, component, "..")) {
while (true) {
if (result_index == 0 or result_index == result_disk_designator.len)
break;
result_index -= 1;
if (result[result_index] == '\\' or result[result_index] == '/')
break;
}
} else {
result[result_index] = sep_windows;
result_index += 1;
mem.copy(u8, result[result_index..], component);
result_index += component.len;
}
}
}
if (result_index == result_disk_designator.len) {
result[result_index] = '\\';
result_index += 1;
}
return allocator.shrink(u8, result, result_index);
}
/// This function is like a series of `cd` statements executed one after another.
/// It resolves "." and "..".
/// The result does not have a trailing path separator.
/// If all paths are relative it uses the current working directory as a starting point.
pub fn resolvePosix(allocator: *Allocator, paths: []const []const u8) ![]u8 {
if (paths.len == 0) {
assert(!is_windows); // resolvePosix called on windows can't use getCwd
return os.getCwdAlloc(allocator);
}
var first_index: usize = 0;
var have_abs = false;
var max_size: usize = 0;
for (paths) |p, i| {
if (isAbsolutePosix(p)) {
first_index = i;
have_abs = true;
max_size = 0;
}
max_size += p.len + 1;
}
var result: []u8 = undefined;
var result_index: usize = 0;
if (have_abs) {
result = try allocator.alloc(u8, max_size);
} else {
assert(!is_windows); // resolvePosix called on windows can't use getCwd
const cwd = try os.getCwdAlloc(allocator);
defer allocator.free(cwd);
result = try allocator.alloc(u8, max_size + cwd.len + 1);
mem.copy(u8, result, cwd);
result_index += cwd.len;
}
errdefer allocator.free(result);
for (paths[first_index..]) |p, i| {
var it = mem.split(p, "/");
while (it.next()) |component| {
if (mem.eql(u8, component, ".")) {
continue;
} else if (mem.eql(u8, component, "..")) {
while (true) {
if (result_index == 0)
break;
result_index -= 1;
if (result[result_index] == '/')
break;
}
} else {
result[result_index] = '/';
result_index += 1;
mem.copy(u8, result[result_index..], component);
result_index += component.len;
}
}
}
if (result_index == 0) {
result[0] = '/';
result_index += 1;
}
return allocator.shrink(u8, result, result_index);
}
test "os.path.resolve" {
const cwd = try os.getCwdAlloc(debug.global_allocator);
if (is_windows) {
if (windowsParsePath(cwd).kind == WindowsPath.Kind.Drive) {
cwd[0] = asciiUpper(cwd[0]);
}
assert(mem.eql(u8, testResolveWindows([][]const u8{"."}), cwd));
} else {
assert(mem.eql(u8, testResolvePosix([][]const u8{ "a/b/c/", "../../.." }), cwd));
assert(mem.eql(u8, testResolvePosix([][]const u8{"."}), cwd));
}
}
test "os.path.resolveWindows" {
if (is_windows) {
const cwd = try os.getCwdAlloc(debug.global_allocator);
const parsed_cwd = windowsParsePath(cwd);
{
const result = testResolveWindows([][]const u8{ "/usr/local", "lib\\zig\\std\\array_list.zig" });
const expected = try join(debug.global_allocator, parsed_cwd.disk_designator, "usr\\local\\lib\\zig\\std\\array_list.zig");
if (parsed_cwd.kind == WindowsPath.Kind.Drive) {
expected[0] = asciiUpper(parsed_cwd.disk_designator[0]);
}
assert(mem.eql(u8, result, expected));
}
{
const result = testResolveWindows([][]const u8{ "usr/local", "lib\\zig" });
const expected = try join(debug.global_allocator, cwd, "usr\\local\\lib\\zig");
if (parsed_cwd.kind == WindowsPath.Kind.Drive) {
expected[0] = asciiUpper(parsed_cwd.disk_designator[0]);
}
assert(mem.eql(u8, result, expected));
}
}
assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:\\a\\b\\c", "/hi", "ok" }), "C:\\hi\\ok"));
assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/blah\\blah", "d:/games", "c:../a" }), "C:\\blah\\a"));
assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/blah\\blah", "d:/games", "C:../a" }), "C:\\blah\\a"));
assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/ignore", "d:\\a/b\\c/d", "\\e.exe" }), "D:\\e.exe"));
assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/ignore", "c:/some/file" }), "C:\\some\\file"));
assert(mem.eql(u8, testResolveWindows([][]const u8{ "d:/ignore", "d:some/dir//" }), "D:\\ignore\\some\\dir"));
assert(mem.eql(u8, testResolveWindows([][]const u8{ "//server/share", "..", "relative\\" }), "\\\\server\\share\\relative"));
assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/", "//" }), "C:\\"));
assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/", "//dir" }), "C:\\dir"));
assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/", "//server/share" }), "\\\\server\\share\\"));
assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/", "//server//share" }), "\\\\server\\share\\"));
assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/", "///some//dir" }), "C:\\some\\dir"));
assert(mem.eql(u8, testResolveWindows([][]const u8{ "C:\\foo\\tmp.3\\", "..\\tmp.3\\cycles\\root.js" }), "C:\\foo\\tmp.3\\cycles\\root.js"));
}
test "os.path.resolvePosix" {
assert(mem.eql(u8, testResolvePosix([][]const u8{ "/a/b", "c" }), "/a/b/c"));
assert(mem.eql(u8, testResolvePosix([][]const u8{ "/a/b", "c", "//d", "e///" }), "/d/e"));
assert(mem.eql(u8, testResolvePosix([][]const u8{ "/a/b/c", "..", "../" }), "/a"));
assert(mem.eql(u8, testResolvePosix([][]const u8{ "/", "..", ".." }), "/"));
assert(mem.eql(u8, testResolvePosix([][]const u8{"/a/b/c/"}), "/a/b/c"));
assert(mem.eql(u8, testResolvePosix([][]const u8{ "/var/lib", "../", "file/" }), "/var/file"));
assert(mem.eql(u8, testResolvePosix([][]const u8{ "/var/lib", "/../", "file/" }), "/file"));
assert(mem.eql(u8, testResolvePosix([][]const u8{ "/some/dir", ".", "/absolute/" }), "/absolute"));
assert(mem.eql(u8, testResolvePosix([][]const u8{ "/foo/tmp.3/", "../tmp.3/cycles/root.js" }), "/foo/tmp.3/cycles/root.js"));
}
fn testResolveWindows(paths: []const []const u8) []u8 {
return resolveWindows(debug.global_allocator, paths) catch unreachable;
}
fn testResolvePosix(paths: []const []const u8) []u8 {
return resolvePosix(debug.global_allocator, paths) catch unreachable;
}
/// If the path is a file in the current directory (no directory component)
/// then returns null
pub fn dirname(path: []const u8) ?[]const u8 {
if (is_windows) {
return dirnameWindows(path);
} else {
return dirnamePosix(path);
}
}
pub fn dirnameWindows(path: []const u8) ?[]const u8 {
if (path.len == 0)
return null;
const root_slice = diskDesignatorWindows(path);
if (path.len == root_slice.len)
return path;
const have_root_slash = path.len > root_slice.len and (path[root_slice.len] == '/' or path[root_slice.len] == '\\');
var end_index: usize = path.len - 1;
while ((path[end_index] == '/' or path[end_index] == '\\') and end_index > root_slice.len) {
if (end_index == 0)
return null;
end_index -= 1;
}
while (path[end_index] != '/' and path[end_index] != '\\' and end_index > root_slice.len) {
if (end_index == 0)
return null;
end_index -= 1;
}
if (have_root_slash and end_index == root_slice.len) {
end_index += 1;
}
if (end_index == 0)
return null;
return path[0..end_index];
}
pub fn dirnamePosix(path: []const u8) ?[]const u8 {
if (path.len == 0)
return null;
var end_index: usize = path.len - 1;
while (path[end_index] == '/') {
if (end_index == 0)
return path[0..1];
end_index -= 1;
}
while (path[end_index] != '/') {
if (end_index == 0)
return null;
end_index -= 1;
}
if (end_index == 0 and path[end_index] == '/')
return path[0..1];
if (end_index == 0)
return null;
return path[0..end_index];
}
test "os.path.dirnamePosix" {
testDirnamePosix("/a/b/c", "/a/b");
testDirnamePosix("/a/b/c///", "/a/b");
testDirnamePosix("/a", "/");
testDirnamePosix("/", "/");
testDirnamePosix("////", "/");
testDirnamePosix("", null);
testDirnamePosix("a", null);
testDirnamePosix("a/", null);
testDirnamePosix("a//", null);
}
test "os.path.dirnameWindows" {
testDirnameWindows("c:\\", "c:\\");
testDirnameWindows("c:\\foo", "c:\\");
testDirnameWindows("c:\\foo\\", "c:\\");
testDirnameWindows("c:\\foo\\bar", "c:\\foo");
testDirnameWindows("c:\\foo\\bar\\", "c:\\foo");
testDirnameWindows("c:\\foo\\bar\\baz", "c:\\foo\\bar");
testDirnameWindows("\\", "\\");
testDirnameWindows("\\foo", "\\");
testDirnameWindows("\\foo\\", "\\");
testDirnameWindows("\\foo\\bar", "\\foo");
testDirnameWindows("\\foo\\bar\\", "\\foo");
testDirnameWindows("\\foo\\bar\\baz", "\\foo\\bar");
testDirnameWindows("c:", "c:");
testDirnameWindows("c:foo", "c:");
testDirnameWindows("c:foo\\", "c:");
testDirnameWindows("c:foo\\bar", "c:foo");
testDirnameWindows("c:foo\\bar\\", "c:foo");
testDirnameWindows("c:foo\\bar\\baz", "c:foo\\bar");
testDirnameWindows("file:stream", null);
testDirnameWindows("dir\\file:stream", "dir");
testDirnameWindows("\\\\unc\\share", "\\\\unc\\share");
testDirnameWindows("\\\\unc\\share\\foo", "\\\\unc\\share\\");
testDirnameWindows("\\\\unc\\share\\foo\\", "\\\\unc\\share\\");
testDirnameWindows("\\\\unc\\share\\foo\\bar", "\\\\unc\\share\\foo");
testDirnameWindows("\\\\unc\\share\\foo\\bar\\", "\\\\unc\\share\\foo");
testDirnameWindows("\\\\unc\\share\\foo\\bar\\baz", "\\\\unc\\share\\foo\\bar");
testDirnameWindows("/a/b/", "/a");
testDirnameWindows("/a/b", "/a");
testDirnameWindows("/a", "/");
testDirnameWindows("", null);
testDirnameWindows("/", "/");
testDirnameWindows("////", "/");
testDirnameWindows("foo", null);
}
fn testDirnamePosix(input: []const u8, expected_output: ?[]const u8) void {
if (dirnamePosix(input)) |output| {
assert(mem.eql(u8, output, expected_output.?));
} else {
assert(expected_output == null);
}
}
fn testDirnameWindows(input: []const u8, expected_output: ?[]const u8) void {
if (dirnameWindows(input)) |output| {
assert(mem.eql(u8, output, expected_output.?));
} else {
assert(expected_output == null);
}
}
pub fn basename(path: []const u8) []const u8 {
if (is_windows) {
return basenameWindows(path);
} else {
return basenamePosix(path);
}
}
pub fn basenamePosix(path: []const u8) []const u8 {
if (path.len == 0)
return []u8{};
var end_index: usize = path.len - 1;
while (path[end_index] == '/') {
if (end_index == 0)
return []u8{};
end_index -= 1;
}
var start_index: usize = end_index;
end_index += 1;
while (path[start_index] != '/') {
if (start_index == 0)
return path[0..end_index];
start_index -= 1;
}
return path[start_index + 1 .. end_index];
}
pub fn basenameWindows(path: []const u8) []const u8 {
if (path.len == 0)
return []u8{};
var end_index: usize = path.len - 1;
while (true) {
const byte = path[end_index];
if (byte == '/' or byte == '\\') {
if (end_index == 0)
return []u8{};
end_index -= 1;
continue;
}
if (byte == ':' and end_index == 1) {
return []u8{};
}
break;
}
var start_index: usize = end_index;
end_index += 1;
while (path[start_index] != '/' and path[start_index] != '\\' and
!(path[start_index] == ':' and start_index == 1))
{
if (start_index == 0)
return path[0..end_index];
start_index -= 1;
}
return path[start_index + 1 .. end_index];
}
test "os.path.basename" {
testBasename("", "");
testBasename("/", "");
testBasename("/dir/basename.ext", "basename.ext");
testBasename("/basename.ext", "basename.ext");
testBasename("basename.ext", "basename.ext");
testBasename("basename.ext/", "basename.ext");
testBasename("basename.ext//", "basename.ext");
testBasename("/aaa/bbb", "bbb");
testBasename("/aaa/", "aaa");
testBasename("/aaa/b", "b");
testBasename("/a/b", "b");
testBasename("//a", "a");
testBasenamePosix("\\dir\\basename.ext", "\\dir\\basename.ext");
testBasenamePosix("\\basename.ext", "\\basename.ext");
testBasenamePosix("basename.ext", "basename.ext");
testBasenamePosix("basename.ext\\", "basename.ext\\");
testBasenamePosix("basename.ext\\\\", "basename.ext\\\\");
testBasenamePosix("foo", "foo");
testBasenameWindows("\\dir\\basename.ext", "basename.ext");
testBasenameWindows("\\basename.ext", "basename.ext");
testBasenameWindows("basename.ext", "basename.ext");
testBasenameWindows("basename.ext\\", "basename.ext");
testBasenameWindows("basename.ext\\\\", "basename.ext");
testBasenameWindows("foo", "foo");
testBasenameWindows("C:", "");
testBasenameWindows("C:.", ".");
testBasenameWindows("C:\\", "");
testBasenameWindows("C:\\dir\\base.ext", "base.ext");
testBasenameWindows("C:\\basename.ext", "basename.ext");
testBasenameWindows("C:basename.ext", "basename.ext");
testBasenameWindows("C:basename.ext\\", "basename.ext");
testBasenameWindows("C:basename.ext\\\\", "basename.ext");
testBasenameWindows("C:foo", "foo");
testBasenameWindows("file:stream", "file:stream");
}
fn testBasename(input: []const u8, expected_output: []const u8) void {
assert(mem.eql(u8, basename(input), expected_output));
}
fn testBasenamePosix(input: []const u8, expected_output: []const u8) void {
assert(mem.eql(u8, basenamePosix(input), expected_output));
}
fn testBasenameWindows(input: []const u8, expected_output: []const u8) void {
assert(mem.eql(u8, basenameWindows(input), expected_output));
}
/// Returns the relative path from `from` to `to`. If `from` and `to` each
/// resolve to the same path (after calling `resolve` on each), a zero-length
/// string is returned.
/// On Windows this canonicalizes the drive to a capital letter and paths to `\\`.
pub fn relative(allocator: *Allocator, from: []const u8, to: []const u8) ![]u8 {
if (is_windows) {
return relativeWindows(allocator, from, to);
} else {
return relativePosix(allocator, from, to);
}
}
pub fn relativeWindows(allocator: *Allocator, from: []const u8, to: []const u8) ![]u8 {
const resolved_from = try resolveWindows(allocator, [][]const u8{from});
defer allocator.free(resolved_from);
var clean_up_resolved_to = true;
const resolved_to = try resolveWindows(allocator, [][]const u8{to});
defer if (clean_up_resolved_to) allocator.free(resolved_to);
const parsed_from = windowsParsePath(resolved_from);
const parsed_to = windowsParsePath(resolved_to);
const result_is_to = x: {
if (parsed_from.kind != parsed_to.kind) {
break :x true;
} else switch (parsed_from.kind) {
WindowsPath.Kind.NetworkShare => {
break :x !networkShareServersEql(parsed_to.disk_designator, parsed_from.disk_designator);
},
WindowsPath.Kind.Drive => {
break :x asciiUpper(parsed_from.disk_designator[0]) != asciiUpper(parsed_to.disk_designator[0]);
},
else => unreachable,
}
};
if (result_is_to) {
clean_up_resolved_to = false;
return resolved_to;
}
var from_it = mem.split(resolved_from, "/\\");
var to_it = mem.split(resolved_to, "/\\");
while (true) {
const from_component = from_it.next() orelse return mem.dupe(allocator, u8, to_it.rest());
const to_rest = to_it.rest();
if (to_it.next()) |to_component| {
// TODO ASCII is wrong, we actually need full unicode support to compare paths.
if (asciiEqlIgnoreCase(from_component, to_component))
continue;
}
var up_count: usize = 1;
while (from_it.next()) |_| {
up_count += 1;
}
const up_index_end = up_count * "..\\".len;
const result = try allocator.alloc(u8, up_index_end + to_rest.len);
errdefer allocator.free(result);
var result_index: usize = 0;
while (result_index < up_index_end) {
result[result_index] = '.';
result_index += 1;
result[result_index] = '.';
result_index += 1;
result[result_index] = '\\';
result_index += 1;
}
// shave off the trailing slash
result_index -= 1;
var rest_it = mem.split(to_rest, "/\\");
while (rest_it.next()) |to_component| {
result[result_index] = '\\';
result_index += 1;
mem.copy(u8, result[result_index..], to_component);
result_index += to_component.len;
}
return result[0..result_index];
}
return []u8{};
}
pub fn relativePosix(allocator: *Allocator, from: []const u8, to: []const u8) ![]u8 {
const resolved_from = try resolvePosix(allocator, [][]const u8{from});
defer allocator.free(resolved_from);
const resolved_to = try resolvePosix(allocator, [][]const u8{to});
defer allocator.free(resolved_to);
var from_it = mem.split(resolved_from, "/");
var to_it = mem.split(resolved_to, "/");
while (true) {
const from_component = from_it.next() orelse return mem.dupe(allocator, u8, to_it.rest());
const to_rest = to_it.rest();
if (to_it.next()) |to_component| {
if (mem.eql(u8, from_component, to_component))
continue;
}
var up_count: usize = 1;
while (from_it.next()) |_| {
up_count += 1;
}
const up_index_end = up_count * "../".len;
const result = try allocator.alloc(u8, up_index_end + to_rest.len);
errdefer allocator.free(result);
var result_index: usize = 0;
while (result_index < up_index_end) {
result[result_index] = '.';
result_index += 1;
result[result_index] = '.';
result_index += 1;
result[result_index] = '/';
result_index += 1;
}
if (to_rest.len == 0) {
// shave off the trailing slash
return result[0 .. result_index - 1];
}
mem.copy(u8, result[result_index..], to_rest);
return result;
}
return []u8{};
}
test "os.path.relative" {
testRelativeWindows("c:/blah\\blah", "d:/games", "D:\\games");
testRelativeWindows("c:/aaaa/bbbb", "c:/aaaa", "..");
testRelativeWindows("c:/aaaa/bbbb", "c:/cccc", "..\\..\\cccc");
testRelativeWindows("c:/aaaa/bbbb", "c:/aaaa/bbbb", "");
testRelativeWindows("c:/aaaa/bbbb", "c:/aaaa/cccc", "..\\cccc");
testRelativeWindows("c:/aaaa/", "c:/aaaa/cccc", "cccc");
testRelativeWindows("c:/", "c:\\aaaa\\bbbb", "aaaa\\bbbb");
testRelativeWindows("c:/aaaa/bbbb", "d:\\", "D:\\");
testRelativeWindows("c:/AaAa/bbbb", "c:/aaaa/bbbb", "");
testRelativeWindows("c:/aaaaa/", "c:/aaaa/cccc", "..\\aaaa\\cccc");
testRelativeWindows("C:\\foo\\bar\\baz\\quux", "C:\\", "..\\..\\..\\..");
testRelativeWindows("C:\\foo\\test", "C:\\foo\\test\\bar\\package.json", "bar\\package.json");
testRelativeWindows("C:\\foo\\bar\\baz-quux", "C:\\foo\\bar\\baz", "..\\baz");
testRelativeWindows("C:\\foo\\bar\\baz", "C:\\foo\\bar\\baz-quux", "..\\baz-quux");
testRelativeWindows("\\\\foo\\bar", "\\\\foo\\bar\\baz", "baz");
testRelativeWindows("\\\\foo\\bar\\baz", "\\\\foo\\bar", "..");
testRelativeWindows("\\\\foo\\bar\\baz-quux", "\\\\foo\\bar\\baz", "..\\baz");
testRelativeWindows("\\\\foo\\bar\\baz", "\\\\foo\\bar\\baz-quux", "..\\baz-quux");
testRelativeWindows("C:\\baz-quux", "C:\\baz", "..\\baz");
testRelativeWindows("C:\\baz", "C:\\baz-quux", "..\\baz-quux");
testRelativeWindows("\\\\foo\\baz-quux", "\\\\foo\\baz", "..\\baz");
testRelativeWindows("\\\\foo\\baz", "\\\\foo\\baz-quux", "..\\baz-quux");
testRelativeWindows("C:\\baz", "\\\\foo\\bar\\baz", "\\\\foo\\bar\\baz");
testRelativeWindows("\\\\foo\\bar\\baz", "C:\\baz", "C:\\baz");
testRelativePosix("/var/lib", "/var", "..");
testRelativePosix("/var/lib", "/bin", "../../bin");
testRelativePosix("/var/lib", "/var/lib", "");
testRelativePosix("/var/lib", "/var/apache", "../apache");
testRelativePosix("/var/", "/var/lib", "lib");
testRelativePosix("/", "/var/lib", "var/lib");
testRelativePosix("/foo/test", "/foo/test/bar/package.json", "bar/package.json");
testRelativePosix("/Users/a/web/b/test/mails", "/Users/a/web/b", "../..");
testRelativePosix("/foo/bar/baz-quux", "/foo/bar/baz", "../baz");
testRelativePosix("/foo/bar/baz", "/foo/bar/baz-quux", "../baz-quux");
testRelativePosix("/baz-quux", "/baz", "../baz");
testRelativePosix("/baz", "/baz-quux", "../baz-quux");
}
fn testRelativePosix(from: []const u8, to: []const u8, expected_output: []const u8) void {
const result = relativePosix(debug.global_allocator, from, to) catch unreachable;
assert(mem.eql(u8, result, expected_output));
}
fn testRelativeWindows(from: []const u8, to: []const u8, expected_output: []const u8) void {
const result = relativeWindows(debug.global_allocator, from, to) catch unreachable;
assert(mem.eql(u8, result, expected_output));
}
pub const RealError = error{
FileNotFound,
AccessDenied,
NameTooLong,
NotSupported,
NotDir,
SymLinkLoop,
InputOutput,
FileTooBig,
IsDir,
ProcessFdQuotaExceeded,
SystemFdQuotaExceeded,
NoDevice,
SystemResources,
NoSpaceLeft,
FileSystem,
BadPathName,
/// On Windows, file paths must be valid Unicode.
InvalidUtf8,
/// TODO remove this possibility
PathAlreadyExists,
/// TODO remove this possibility
Unexpected,
};
/// Call from Windows-specific code if you already have a UTF-16LE encoded, null terminated string.
/// Otherwise use `real` or `realC`.
pub fn realW(out_buffer: *[os.MAX_PATH_BYTES]u8, pathname: [*]const u16) RealError![]u8 {
const h_file = windows.CreateFileW(
pathname,
windows.GENERIC_READ,
windows.FILE_SHARE_READ,
null,
windows.OPEN_EXISTING,
windows.FILE_ATTRIBUTE_NORMAL,
null,
);
if (h_file == windows.INVALID_HANDLE_VALUE) {
const err = windows.GetLastError();
switch (err) {
windows.ERROR.FILE_NOT_FOUND => return error.FileNotFound,
windows.ERROR.ACCESS_DENIED => return error.AccessDenied,
windows.ERROR.FILENAME_EXCED_RANGE => return error.NameTooLong,
else => return os.unexpectedErrorWindows(err),
}
}
defer os.close(h_file);
var utf16le_buf: [windows_util.PATH_MAX_WIDE]u16 = undefined;
const casted_len = @intCast(windows.DWORD, utf16le_buf.len); // TODO shouldn't need this cast
const result = windows.GetFinalPathNameByHandleW(h_file, &utf16le_buf, casted_len, windows.VOLUME_NAME_DOS);
assert(result <= utf16le_buf.len);
if (result == 0) {
const err = windows.GetLastError();
switch (err) {
windows.ERROR.FILE_NOT_FOUND => return error.FileNotFound,
windows.ERROR.PATH_NOT_FOUND => return error.FileNotFound,
windows.ERROR.NOT_ENOUGH_MEMORY => return error.SystemResources,
windows.ERROR.FILENAME_EXCED_RANGE => return error.NameTooLong,
windows.ERROR.INVALID_PARAMETER => unreachable,
else => return os.unexpectedErrorWindows(err),
}
}
const utf16le_slice = utf16le_buf[0..result];
// windows returns \\?\ prepended to the path
// we strip it because nobody wants \\?\ prepended to their path
const prefix = []u16{ '\\', '\\', '?', '\\' };
const start_index = if (mem.startsWith(u16, utf16le_slice, prefix)) prefix.len else 0;
// Trust that Windows gives us valid UTF-16LE.
const end_index = std.unicode.utf16leToUtf8(out_buffer, utf16le_slice[start_index..]) catch unreachable;
return out_buffer[0..end_index];
}
/// See `real`
/// Use this when you have a null terminated pointer path.
pub fn realC(out_buffer: *[os.MAX_PATH_BYTES]u8, pathname: [*]const u8) RealError![]u8 {
switch (builtin.os) {
Os.windows => {
const pathname_w = try windows_util.cStrToPrefixedFileW(pathname);
return realW(out_buffer, pathname_w);
},
Os.macosx, Os.ios => {
// TODO instead of calling the libc function here, port the implementation to Zig
const err = posix.getErrno(posix.realpath(pathname, out_buffer));
switch (err) {
0 => return mem.toSlice(u8, out_buffer),
posix.EINVAL => unreachable,
posix.EBADF => unreachable,
posix.EFAULT => unreachable,
posix.EACCES => return error.AccessDenied,
posix.ENOENT => return error.FileNotFound,
posix.ENOTSUP => return error.NotSupported,
posix.ENOTDIR => return error.NotDir,
posix.ENAMETOOLONG => return error.NameTooLong,
posix.ELOOP => return error.SymLinkLoop,
posix.EIO => return error.InputOutput,
else => return os.unexpectedErrorPosix(err),
}
},
Os.linux => {
const fd = try os.posixOpenC(pathname, posix.O_PATH | posix.O_NONBLOCK | posix.O_CLOEXEC, 0);
defer os.close(fd);
var buf: ["/proc/self/fd/-2147483648\x00".len]u8 = undefined;
const proc_path = fmt.bufPrint(buf[0..], "/proc/self/fd/{}\x00", fd) catch unreachable;
return os.readLinkC(out_buffer, proc_path.ptr);
},
Os.freebsd => { // XXX requires fdescfs
const fd = try os.posixOpenC(pathname, posix.O_PATH | posix.O_NONBLOCK | posix.O_CLOEXEC, 0);
defer os.close(fd);
var buf: ["/dev/fd/-2147483648\x00".len]u8 = undefined;
const proc_path = fmt.bufPrint(buf[0..], "/dev/fd/{}\x00", fd) catch unreachable;
return os.readLinkC(out_buffer, proc_path.ptr);
},
else => @compileError("TODO implement os.path.real for " ++ @tagName(builtin.os)),
}
}
/// Return the canonicalized absolute pathname.
/// Expands all symbolic links and resolves references to `.`, `..`, and
/// extra `/` characters in ::pathname.
/// The return value is a slice of out_buffer, and not necessarily from the beginning.
pub fn real(out_buffer: *[os.MAX_PATH_BYTES]u8, pathname: []const u8) RealError![]u8 {
switch (builtin.os) {
Os.windows => {
const pathname_w = try windows_util.sliceToPrefixedFileW(pathname);
return realW(out_buffer, &pathname_w);
},
Os.macosx, Os.ios, Os.linux, Os.freebsd => {
const pathname_c = try os.toPosixPath(pathname);
return realC(out_buffer, &pathname_c);
},
else => @compileError("Unsupported OS"),
}
}
/// `real`, except caller must free the returned memory.
pub fn realAlloc(allocator: *Allocator, pathname: []const u8) ![]u8 {
var buf: [os.MAX_PATH_BYTES]u8 = undefined;
return mem.dupe(allocator, u8, try real(&buf, pathname));
}
test "os.path.real" {
// at least call it so it gets compiled
var buf: [os.MAX_PATH_BYTES]u8 = undefined;
std.debug.assertError(real(&buf, "definitely_bogus_does_not_exist1234"), error.FileNotFound);
}
|
std/os/path.zig
|
const std = @import("std");
const builtin = @import("builtin");
pub extern fn __divsf3(a: f32, b: f32) f32 {
@setRuntimeSafety(builtin.is_test);
const Z = @IntType(false, f32.bit_count);
const typeWidth = f32.bit_count;
const significandBits = std.math.floatMantissaBits(f32);
const exponentBits = std.math.floatExponentBits(f32);
const signBit = (@as(Z, 1) << (significandBits + exponentBits));
const maxExponent = ((1 << exponentBits) - 1);
const exponentBias = (maxExponent >> 1);
const implicitBit = (@as(Z, 1) << significandBits);
const quietBit = implicitBit >> 1;
const significandMask = implicitBit - 1;
const absMask = signBit - 1;
const exponentMask = absMask ^ significandMask;
const qnanRep = exponentMask | quietBit;
const infRep = @bitCast(Z, std.math.inf(f32));
const aExponent = @truncate(u32, (@bitCast(Z, a) >> significandBits) & maxExponent);
const bExponent = @truncate(u32, (@bitCast(Z, b) >> significandBits) & maxExponent);
const quotientSign: Z = (@bitCast(Z, a) ^ @bitCast(Z, b)) & signBit;
var aSignificand: Z = @bitCast(Z, a) & significandMask;
var bSignificand: Z = @bitCast(Z, b) & significandMask;
var scale: i32 = 0;
// Detect if a or b is zero, denormal, infinity, or NaN.
if (aExponent -% 1 >= maxExponent -% 1 or bExponent -% 1 >= maxExponent -% 1) {
const aAbs: Z = @bitCast(Z, a) & absMask;
const bAbs: Z = @bitCast(Z, b) & absMask;
// NaN / anything = qNaN
if (aAbs > infRep) return @bitCast(f32, @bitCast(Z, a) | quietBit);
// anything / NaN = qNaN
if (bAbs > infRep) return @bitCast(f32, @bitCast(Z, b) | quietBit);
if (aAbs == infRep) {
// infinity / infinity = NaN
if (bAbs == infRep) {
return @bitCast(f32, qnanRep);
}
// infinity / anything else = +/- infinity
else {
return @bitCast(f32, aAbs | quotientSign);
}
}
// anything else / infinity = +/- 0
if (bAbs == infRep) return @bitCast(f32, quotientSign);
if (aAbs == 0) {
// zero / zero = NaN
if (bAbs == 0) {
return @bitCast(f32, qnanRep);
}
// zero / anything else = +/- zero
else {
return @bitCast(f32, quotientSign);
}
}
// anything else / zero = +/- infinity
if (bAbs == 0) return @bitCast(f32, infRep | quotientSign);
// one or both of a or b is denormal, the other (if applicable) is a
// normal number. Renormalize one or both of a and b, and set scale to
// include the necessary exponent adjustment.
if (aAbs < implicitBit) scale +%= normalize(f32, &aSignificand);
if (bAbs < implicitBit) scale -%= normalize(f32, &bSignificand);
}
// Or in the implicit significand bit. (If we fell through from the
// denormal path it was already set by normalize( ), but setting it twice
// won't hurt anything.)
aSignificand |= implicitBit;
bSignificand |= implicitBit;
var quotientExponent: i32 = @bitCast(i32, aExponent -% bExponent) +% scale;
// Align the significand of b as a Q31 fixed-point number in the range
// [1, 2.0) and get a Q32 approximate reciprocal using a small minimax
// polynomial approximation: reciprocal = 3/4 + 1/sqrt(2) - b/2. This
// is accurate to about 3.5 binary digits.
const q31b = bSignificand << 8;
var reciprocal = @as(u32, 0x7504f333) -% q31b;
// Now refine the reciprocal estimate using a Newton-Raphson iteration:
//
// x1 = x0 * (2 - x0 * b)
//
// This doubles the number of correct binary digits in the approximation
// with each iteration, so after three iterations, we have about 28 binary
// digits of accuracy.
var correction: u32 = undefined;
correction = @truncate(u32, ~(@as(u64, reciprocal) *% q31b >> 32) +% 1);
reciprocal = @truncate(u32, @as(u64, reciprocal) *% correction >> 31);
correction = @truncate(u32, ~(@as(u64, reciprocal) *% q31b >> 32) +% 1);
reciprocal = @truncate(u32, @as(u64, reciprocal) *% correction >> 31);
correction = @truncate(u32, ~(@as(u64, reciprocal) *% q31b >> 32) +% 1);
reciprocal = @truncate(u32, @as(u64, reciprocal) *% correction >> 31);
// Exhaustive testing shows that the error in reciprocal after three steps
// is in the interval [-0x1.f58108p-31, 0x1.d0e48cp-29], in line with our
// expectations. We bump the reciprocal by a tiny value to force the error
// to be strictly positive (in the range [0x1.4fdfp-37,0x1.287246p-29], to
// be specific). This also causes 1/1 to give a sensible approximation
// instead of zero (due to overflow).
reciprocal -%= 2;
// The numerical reciprocal is accurate to within 2^-28, lies in the
// interval [0x1.000000eep-1, 0x1.fffffffcp-1], and is strictly smaller
// than the true reciprocal of b. Multiplying a by this reciprocal thus
// gives a numerical q = a/b in Q24 with the following properties:
//
// 1. q < a/b
// 2. q is in the interval [0x1.000000eep-1, 0x1.fffffffcp0)
// 3. the error in q is at most 2^-24 + 2^-27 -- the 2^24 term comes
// from the fact that we truncate the product, and the 2^27 term
// is the error in the reciprocal of b scaled by the maximum
// possible value of a. As a consequence of this error bound,
// either q or nextafter(q) is the correctly rounded
var quotient: Z = @truncate(u32, @as(u64, reciprocal) *% (aSignificand << 1) >> 32);
// Two cases: quotient is in [0.5, 1.0) or quotient is in [1.0, 2.0).
// In either case, we are going to compute a residual of the form
//
// r = a - q*b
//
// We know from the construction of q that r satisfies:
//
// 0 <= r < ulp(q)*b
//
// if r is greater than 1/2 ulp(q)*b, then q rounds up. Otherwise, we
// already have the correct result. The exact halfway case cannot occur.
// We also take this time to right shift quotient if it falls in the [1,2)
// range and adjust the exponent accordingly.
var residual: Z = undefined;
if (quotient < (implicitBit << 1)) {
residual = (aSignificand << 24) -% quotient *% bSignificand;
quotientExponent -%= 1;
} else {
quotient >>= 1;
residual = (aSignificand << 23) -% quotient *% bSignificand;
}
const writtenExponent = quotientExponent +% exponentBias;
if (writtenExponent >= maxExponent) {
// If we have overflowed the exponent, return infinity.
return @bitCast(f32, infRep | quotientSign);
} else if (writtenExponent < 1) {
if (writtenExponent == 0) {
// Check whether the rounded result is normal.
const round = @boolToInt((residual << 1) > bSignificand);
// Clear the implicit bit.
var absResult = quotient & significandMask;
// Round.
absResult += round;
if ((absResult & ~significandMask) > 0) {
// The rounded result is normal; return it.
return @bitCast(f32, absResult | quotientSign);
}
}
// Flush denormals to zero. In the future, it would be nice to add
// code to round them correctly.
return @bitCast(f32, quotientSign);
} else {
const round = @boolToInt((residual << 1) > bSignificand);
// Clear the implicit bit
var absResult = quotient & significandMask;
// Insert the exponent
absResult |= @bitCast(Z, writtenExponent) << significandBits;
// Round
absResult +%= round;
// Insert the sign and return
return @bitCast(f32, absResult | quotientSign);
}
}
fn normalize(comptime T: type, significand: *@IntType(false, T.bit_count)) i32 {
@setRuntimeSafety(builtin.is_test);
const Z = @IntType(false, T.bit_count);
const significandBits = std.math.floatMantissaBits(T);
const implicitBit = @as(Z, 1) << significandBits;
const shift = @clz(Z, significand.*) - @clz(Z, implicitBit);
significand.* <<= @intCast(std.math.Log2Int(Z), shift);
return 1 - shift;
}
test "import divsf3" {
_ = @import("divsf3_test.zig");
}
|
lib/std/special/compiler_rt/divsf3.zig
|
const std = @import("std");
const allocators = @import("allocators.zig");
const fs = @import("fs.zig");
const lua = @import("lua.zig");
const c = lua.c;
const L = ?*c.lua_State;
pub export fn registerFsLib(l: L) c_int {
c.luaL_requiref(l, "fs", openFs, 1);
return 0;
}
fn openFs(l: L) callconv(.C) c_int {
var funcs = [_]c.luaL_Reg{
.{ .name = "absolute_path", .func = fsAbsolutePath },
.{ .name = "canonical_path", .func = fsCanonicalPath },
.{ .name = "compose_path", .func = fsComposePath },
.{ .name = "compose_path_slash", .func = fsComposePathSlash },
.{ .name = "parent_path", .func = fsParentPath },
.{ .name = "ancestor_relative_path", .func = fsAncestorRelativePath },
.{ .name = "resolve_path", .func = fsResolvePath },
.{ .name = "path_stem", .func = fsPathStem },
.{ .name = "path_filename", .func = fsPathFilename },
.{ .name = "path_extension", .func = fsPathExtension },
.{ .name = "replace_extension", .func = fsReplaceExtension },
.{ .name = "cwd", .func = fsCwd },
.{ .name = "set_cwd", .func = fsSetCwd },
.{ .name = "stat", .func = fsStat },
.{ .name = "get_file_contents", .func = fsGetFileContents },
.{ .name = "put_file_contents", .func = fsPutFileContents },
.{ .name = "move", .func = fsMove },
.{ .name = "copy", .func = fsCopy },
.{ .name = "delete", .func = fsDelete },
.{ .name = "ensure_dir_exists", .func = fsEnsureDirExists },
.{ .name = null, .func = null },
};
c.lua_createtable(l, 0, funcs.len - 1);
c.luaL_setfuncs(l, &funcs, 0);
return 1;
}
fn fsAbsolutePath(l: L) callconv(.C) c_int {
var temp = lua.getTempAlloc(l);
defer temp.reset(65536) catch {};
var alloc = temp.allocator();
var path: []const u8 = undefined;
path.ptr = c.luaL_checklstring(l, 1, &path.len);
var result = fs.toAbsolute(alloc, path) catch |err| {
_ = c.luaL_error(l, fs.errorName(err));
unreachable;
};
_ = c.lua_pushlstring(l, result.ptr, result.len);
return 1;
}
fn fsCanonicalPath(l: L) callconv(.C) c_int {
var temp = lua.getTempAlloc(l);
defer temp.reset(65536) catch {};
var alloc = temp.allocator();
var path: []const u8 = undefined;
path.ptr = c.luaL_checklstring(l, 1, &path.len);
var result = std.fs.cwd().realpathAlloc(alloc, path) catch |err| {
_ = c.luaL_error(l, fs.errorName(err));
unreachable;
};
_ = c.lua_pushlstring(l, result.ptr, result.len);
return 1;
}
fn fsComposePath(l: L) callconv(.C) c_int {
var temp = lua.getTempAlloc(l);
defer temp.reset(65536) catch {};
var alloc = temp.allocator();
const count = c.lua_gettop(l);
std.debug.assert(count >= 0);
var paths = alloc.alloc([]const u8, @intCast(usize, count)) catch |err| {
_ = c.luaL_error(l, fs.errorName(err));
unreachable;
};
var i: c_int = 1;
while (i <= count) : (i += 1) {
const p = @intCast(usize, i - 1);
paths[p].ptr = c.luaL_checklstring(l, i, &paths[p].len);
}
const result = fs.composePath(alloc, paths, 0) catch |err| {
_ = c.luaL_error(l, fs.errorName(err));
unreachable;
};
_ = c.lua_pushlstring(l, result.ptr, result.len);
return 1;
}
fn fsComposePathSlash(l: L) callconv(.C) c_int {
var temp = lua.getTempAlloc(l);
defer temp.reset(65536) catch {};
var alloc = temp.allocator();
const count = c.lua_gettop(l);
std.debug.assert(count >= 0);
var paths = alloc.alloc([]const u8, @intCast(usize, count)) catch |err| {
_ = c.luaL_error(l, fs.errorName(err));
unreachable;
};
var i: c_int = 1;
while (i <= count) : (i += 1) {
const p = @intCast(usize, i - 1);
paths[p].ptr = c.luaL_checklstring(l, i, &paths[p].len);
}
const result = fs.composePath(alloc, paths, '/') catch |err| {
_ = c.luaL_error(l, fs.errorName(err));
unreachable;
};
_ = c.lua_pushlstring(l, result.ptr, result.len);
return 1;
}
fn fsParentPath(l: L) callconv(.C) c_int {
var path: []const u8 = undefined;
path.ptr = c.luaL_checklstring(l, 1, &path.len);
const result = std.fs.path.dirname(path) orelse "";
_ = c.lua_pushlstring(l, result.ptr, result.len);
return 1;
}
fn fsAncestorRelativePath(l: L) callconv(.C) c_int {
var child: []const u8 = undefined;
var ancestor: []const u8 = undefined;
child.ptr = c.luaL_checklstring(l, 1, &child.len);
ancestor.ptr = c.luaL_checklstring(l, 2, &ancestor.len);
var result = fs.pathRelativeToAncestor(child, ancestor);
_ = c.lua_pushlstring(l, result.ptr, result.len);
return 1;
}
// function resolve_path (path, search_paths, include_cwd)
fn fsResolvePath(l: L) callconv(.C) c_int {
if (c.lua_isnoneornil(l, 1)) {
return 0;
}
var path: []const u8 = undefined;
path.ptr = c.luaL_checklstring(l, 1, &path.len);
if (!c.lua_isnoneornil(l, 2)) blk: {
if (c.lua_type(l, 2) == c.LUA_TTABLE) {
c.lua_pushnil(l);
while (c.lua_next(l, 2) != 0) {
c.lua_pushcfunction(l, fsResolvePath);
c.lua_pushvalue(l, 1);
c.lua_pushvalue(l, -3);
c.lua_callk(l, 2, 1, 0, null); // resolve_path(input_path, search_paths[k])
if (!c.lua_isnoneornil(l, -1)) {
return 1;
}
c.lua_pop(l, 2); // value, and returned nil
}
} else {
var temp = lua.getTempAlloc(l);
defer temp.reset(65536) catch {};
var alloc = temp.allocator();
var search_path: []const u8 = undefined;
search_path.ptr = c.luaL_checklstring(l, 2, &search_path.len);
const parts = [_][]const u8{ search_path, path };
var combined = fs.composePath(alloc, &parts, 0) catch |err| {
_ = c.luaL_error(l, fs.errorName(err));
unreachable;
};
std.fs.cwd().access(combined, .{}) catch |err| switch (err) {
error.FileNotFound, error.BadPathName, error.InvalidUtf8, error.NameTooLong => {
break :blk;
},
else => {
_ = c.luaL_error(l, fs.errorName(err));
unreachable;
},
};
_ = c.lua_pushlstring(l, combined.ptr, combined.len);
return 1;
}
}
if (c.lua_toboolean(l, 3) != 0) {
c.lua_pushcfunction(l, fsResolvePath);
c.lua_pushvalue(l, 1);
{
var temp = lua.getTempAlloc(l);
defer temp.reset(65536) catch {};
var alloc = temp.allocator();
const cwd = std.process.getCwdAlloc(alloc) catch |err| {
_ = c.luaL_error(l, fs.errorName(err));
unreachable;
};
_ = c.lua_pushlstring(l, cwd.ptr, cwd.len);
}
c.lua_callk(l, 2, 1, 0, null); // resolve_path(input_path, cwd)
if (!c.lua_isnoneornil(l, -1)) {
return 1;
}
}
return 0;
}
fn fsPathStem(l: L) callconv(.C) c_int {
var path: []const u8 = undefined;
path.ptr = c.luaL_checklstring(l, 1, &path.len);
var filename = std.fs.path.basename(path);
const index = std.mem.lastIndexOfScalar(u8, filename, '.') orelse 0;
if (index > 0) filename = filename[0..index];
_ = c.lua_pushlstring(l, filename.ptr, filename.len);
return 1;
}
fn fsPathFilename(l: L) callconv(.C) c_int {
var path: []const u8 = undefined;
path.ptr = c.luaL_checklstring(l, 1, &path.len);
const result = std.fs.path.basename(path);
_ = c.lua_pushlstring(l, result.ptr, result.len);
return 1;
}
fn fsPathExtension(l: L) callconv(.C) c_int {
var path: []const u8 = undefined;
path.ptr = c.luaL_checklstring(l, 1, &path.len);
const result = std.fs.path.extension(path);
_ = c.lua_pushlstring(l, result.ptr, result.len);
return 1;
}
fn fsReplaceExtension(l: L) callconv(.C) c_int {
var temp = lua.getTempAlloc(l);
defer temp.reset(65536) catch {};
var alloc = temp.allocator();
var path: []const u8 = undefined;
path.ptr = c.luaL_checklstring(l, 1, &path.len);
var new_ext: []const u8 = undefined;
new_ext.ptr = c.luaL_checklstring(l, 2, &new_ext.len);
var result = fs.replaceExtension(alloc, path, new_ext) catch |err| {
_ = c.luaL_error(l, fs.errorName(err));
unreachable;
};
_ = c.lua_pushlstring(l, result.ptr, result.len);
return 1;
}
fn fsCwd(l: L) callconv(.C) c_int {
var temp = lua.getTempAlloc(l);
defer temp.reset(65536) catch {};
var alloc = temp.allocator();
const result = std.process.getCwdAlloc(alloc) catch |err| {
_ = c.luaL_error(l, fs.errorName(err));
unreachable;
};
_ = c.lua_pushlstring(l, result.ptr, result.len);
return 1;
}
fn fsSetCwd(l: L) callconv(.C) c_int {
var path: []const u8 = undefined;
path.ptr = c.luaL_checklstring(l, 1, &path.len);
std.os.chdir(path) catch |err| {
_ = c.luaL_error(l, fs.errorName(err));
unreachable;
};
return 0;
}
fn fsStat(l: L) callconv(.C) c_int {
var path: []const u8 = undefined;
path.ptr = c.luaL_checklstring(l, 1, &path.len);
var exists = true;
var stat = std.fs.File.Stat {
.inode = 0,
.size = 0,
.mode = 0,
.kind = std.fs.File.Kind.Unknown,
.atime = 0,
.mtime = 0,
.ctime = 0,
};
if (std.fs.cwd().statFile(path)) |s| {
stat = s;
} else |statFileErr| switch (statFileErr) {
error.IsDir => {
var dir = std.fs.cwd().openDir(path, .{}) catch |err| {
_ = c.luaL_error(l, fs.errorName(err));
unreachable;
};
stat = dir.stat() catch |err| {
_ = c.luaL_error(l, fs.errorName(err));
unreachable;
};
},
error.FileNotFound, error.BadPathName, error.InvalidUtf8, error.NameTooLong => {
exists = false;
},
else => {
_ = c.luaL_error(l, fs.errorName(statFileErr));
unreachable;
},
}
c.lua_settop(l, 0);
c.lua_createtable(l, 0, 5);
_ = c.lua_pushstring(l, "size");
if (stat.size > std.math.maxInt(c.lua_Integer)) {
c.lua_pushinteger(l, std.math.maxInt(c.lua_Integer));
} else {
c.lua_pushinteger(l, @intCast(c.lua_Integer, stat.size));
}
c.lua_rawset(l, 1);
_ = c.lua_pushstring(l, "kind");
var kind = switch (stat.kind) {
.BlockDevice => "blockdevice",
.CharacterDevice => "chardevice",
.Directory => "dir",
.NamedPipe => "pipe",
.SymLink => "symlink",
.File => "file",
.UnixDomainSocket => "socket",
.Whiteout => "whiteout",
.Door => "door",
.EventPort => "eventport",
.Unknown => "unknown",
};
if (!exists) kind = "";
_ = c.lua_pushlstring(l, kind.ptr, kind.len);
c.lua_rawset(l, 1);
_ = c.lua_pushstring(l, "mode");
c.lua_pushinteger(l, @intCast(c.lua_Integer, stat.mode));
c.lua_rawset(l, 1);
_ = c.lua_pushstring(l, "atime");
c.lua_pushinteger(l, @intCast(c.lua_Integer, @divFloor(stat.atime, 1000000)));
c.lua_rawset(l, 1);
_ = c.lua_pushstring(l, "mtime");
c.lua_pushinteger(l, @intCast(c.lua_Integer, @divFloor(stat.mtime, 1000000)));
c.lua_rawset(l, 1);
_ = c.lua_pushstring(l, "ctime");
c.lua_pushinteger(l, @intCast(c.lua_Integer, @divFloor(stat.ctime, 1000000)));
c.lua_rawset(l, 1);
return 1;
}
fn fsGetFileContents(l: L) callconv(.C) c_int {
var temp = lua.getTempAlloc(l);
defer temp.reset(65536) catch {};
var alloc = temp.allocator();
var path: []const u8 = undefined;
path.ptr = c.luaL_checklstring(l, 1, &path.len);
const max_size_c = c.lua_tointegerx(l, 2, null);
const max_size: usize = if (max_size_c <= 0) 5_000_000_000 else @intCast(usize, max_size_c);
var result = std.fs.cwd().readFileAlloc(alloc, path, max_size) catch |err| switch (err) {
error.FileNotFound, error.BadPathName, error.InvalidUtf8, error.NameTooLong => {
return 0;
},
else => {
_ = c.luaL_error(l, fs.errorName(err));
unreachable;
},
};
_ = c.lua_pushlstring(l, result.ptr, result.len);
return 1;
}
fn fsPutFileContents(l: L) callconv(.C) c_int {
var path: []const u8 = undefined;
path.ptr = c.luaL_checklstring(l, 1, &path.len);
var contents: []const u8 = undefined;
contents.ptr = c.luaL_tolstring(l, 2, &contents.len);
var af = std.fs.cwd().atomicFile(path, .{}) catch |err| {
_ = c.luaL_error(l, fs.errorName(err));
unreachable;
};
// We can't defer af.deinit(); because luaL_error longjmps away.
af.file.writeAll(contents) catch |err| {
af.deinit();
_ = c.luaL_error(l, fs.errorName(err));
unreachable;
};
af.finish() catch |err| {
af.deinit();
_ = c.luaL_error(l, fs.errorName(err));
unreachable;
};
af.deinit();
return 0;
}
fn fsMove(l: L) callconv(.C) c_int {
var src_path: []const u8 = undefined;
src_path.ptr = c.luaL_checklstring(l, 1, &src_path.len);
var dest_path: []const u8 = undefined;
dest_path.ptr = c.luaL_checklstring(l, 2, &dest_path.len);
var force = c.lua_gettop(l) >= 3 and c.lua_toboolean(l, 3) != 0;
if (!force) {
var exists = true;
std.fs.cwd().access(dest_path, .{}) catch |err| switch (err) {
error.FileNotFound => exists = false,
else => {
_ = c.luaL_error(l, fs.errorName(err));
unreachable;
}
};
if (exists) {
_ = c.luaL_error(l, fs.errorName(error.PathAlreadyExists));
unreachable;
}
}
std.fs.cwd().rename(src_path, dest_path) catch |err| {
_ = c.luaL_error(l, fs.errorName(err));
unreachable;
};
return 0;
}
fn fsCopy(l: L) callconv(.C) c_int {
var src_path: []const u8 = undefined;
src_path.ptr = c.luaL_checklstring(l, 1, &src_path.len);
var dest_path: []const u8 = undefined;
dest_path.ptr = c.luaL_checklstring(l, 2, &dest_path.len);
var force = c.lua_gettop(l) >= 3 and c.lua_toboolean(l, 3) != 0;
if (!force) {
var exists = true;
std.fs.cwd().access(dest_path, .{}) catch |err| switch (err) {
error.FileNotFound => exists = false,
else => {
_ = c.luaL_error(l, fs.errorName(err));
unreachable;
}
};
if (exists) {
_ = c.luaL_error(l, fs.errorName(error.PathAlreadyExists));
unreachable;
}
}
var cwd = std.fs.cwd();
fs.copyTree(cwd, src_path, cwd, dest_path, .{}) catch |err| {
_ = c.luaL_error(l, fs.errorName(err));
unreachable;
};
return 0;
}
fn fsDelete(l: L) callconv(.C) c_int {
var path: []const u8 = undefined;
path.ptr = c.luaL_checklstring(l, 1, &path.len);
var recursive = c.lua_gettop(l) >= 2 and c.lua_toboolean(l, 2) != 0;
std.fs.cwd().deleteFile(path) catch |deleteFileErr| switch (deleteFileErr) {
error.IsDir => {
if (recursive) {
std.fs.cwd().deleteTree(path) catch |err| {
_ = c.luaL_error(l, fs.errorName(err));
unreachable;
};
} else {
std.fs.cwd().deleteDir(path) catch |err| {
_ = c.luaL_error(l, fs.errorName(err));
unreachable;
};
}
},
else => {
_ = c.luaL_error(l, fs.errorName(deleteFileErr));
unreachable;
}
};
return 0;
}
fn fsEnsureDirExists(l: L) callconv(.C) c_int {
var path: []const u8 = undefined;
path.ptr = c.luaL_checklstring(l, 1, &path.len);
std.fs.cwd().makePath(path) catch |err| {
_ = c.luaL_error(l, fs.errorName(err));
unreachable;
};
return 0;
}
|
limp/lua-fs.zig
|
const std = @import("std");
const expect = std.testing.expect;
const mem = std.mem;
const maxInt = std.math.maxInt;
test "int to ptr cast" {
const x = @as(usize, 13);
const y = @intToPtr(*u8, x);
const z = @ptrToInt(y);
try expect(z == 13);
}
test "integer literal to pointer cast" {
const vga_mem = @intToPtr(*u16, 0xB8000);
try expect(@ptrToInt(vga_mem) == 0xB8000);
}
test "peer type resolution: ?T and T" {
try expect(peerTypeTAndOptionalT(true, false).? == 0);
try expect(peerTypeTAndOptionalT(false, false).? == 3);
comptime {
try expect(peerTypeTAndOptionalT(true, false).? == 0);
try expect(peerTypeTAndOptionalT(false, false).? == 3);
}
}
fn peerTypeTAndOptionalT(c: bool, b: bool) ?usize {
if (c) {
return if (b) null else @as(usize, 0);
}
return @as(usize, 3);
}
test "resolve undefined with integer" {
try testResolveUndefWithInt(true, 1234);
comptime try testResolveUndefWithInt(true, 1234);
}
fn testResolveUndefWithInt(b: bool, x: i32) !void {
const value = if (b) x else undefined;
if (b) {
try expect(value == x);
}
}
test "@intCast i32 to u7" {
var x: u128 = maxInt(u128);
var y: i32 = 120;
var z = x >> @intCast(u7, y);
try expect(z == 0xff);
}
test "@intCast to comptime_int" {
try expect(@intCast(comptime_int, 0) == 0);
}
test "implicit cast comptime numbers to any type when the value fits" {
const a: u64 = 255;
var b: u8 = a;
try expect(b == 255);
}
test "implicit cast comptime_int to comptime_float" {
comptime try expect(@as(comptime_float, 10) == @as(f32, 10));
try expect(2 == 2.0);
}
test "comptime_int @intToFloat" {
{
const result = @intToFloat(f16, 1234);
try expect(@TypeOf(result) == f16);
try expect(result == 1234.0);
}
{
const result = @intToFloat(f32, 1234);
try expect(@TypeOf(result) == f32);
try expect(result == 1234.0);
}
{
const result = @intToFloat(f64, 1234);
try expect(@TypeOf(result) == f64);
try expect(result == 1234.0);
}
{
const result = @intToFloat(f128, 1234);
try expect(@TypeOf(result) == f128);
try expect(result == 1234.0);
}
// big comptime_int (> 64 bits) to f128 conversion
{
const result = @intToFloat(f128, 0x1_0000_0000_0000_0000);
try expect(@TypeOf(result) == f128);
try expect(result == 0x1_0000_0000_0000_0000.0);
}
}
test "@floatToInt" {
try testFloatToInts();
comptime try testFloatToInts();
}
fn testFloatToInts() !void {
const x = @as(i32, 1e4);
try expect(x == 10000);
const y = @floatToInt(i32, @as(f32, 1e4));
try expect(y == 10000);
try expectFloatToInt(f32, 255.1, u8, 255);
try expectFloatToInt(f32, 127.2, i8, 127);
try expectFloatToInt(f32, -128.2, i8, -128);
}
fn expectFloatToInt(comptime F: type, f: F, comptime I: type, i: I) !void {
try expect(@floatToInt(I, f) == i);
}
test "implicitly cast indirect pointer to maybe-indirect pointer" {
const S = struct {
const Self = @This();
x: u8,
fn constConst(p: *const *const Self) u8 {
return p.*.x;
}
fn maybeConstConst(p: ?*const *const Self) u8 {
return p.?.*.x;
}
fn constConstConst(p: *const *const *const Self) u8 {
return p.*.*.x;
}
fn maybeConstConstConst(p: ?*const *const *const Self) u8 {
return p.?.*.*.x;
}
};
const s = S{ .x = 42 };
const p = &s;
const q = &p;
const r = &q;
try expect(42 == S.constConst(q));
try expect(42 == S.maybeConstConst(q));
try expect(42 == S.constConstConst(r));
try expect(42 == S.maybeConstConstConst(r));
}
test "@intCast comptime_int" {
const result = @intCast(i32, 1234);
try expect(@TypeOf(result) == i32);
try expect(result == 1234);
}
test "@floatCast comptime_int and comptime_float" {
{
const result = @floatCast(f16, 1234);
try expect(@TypeOf(result) == f16);
try expect(result == 1234.0);
}
{
const result = @floatCast(f16, 1234.0);
try expect(@TypeOf(result) == f16);
try expect(result == 1234.0);
}
{
const result = @floatCast(f32, 1234);
try expect(@TypeOf(result) == f32);
try expect(result == 1234.0);
}
{
const result = @floatCast(f32, 1234.0);
try expect(@TypeOf(result) == f32);
try expect(result == 1234.0);
}
}
test "coerce undefined to optional" {
try expect(MakeType(void).getNull() == null);
try expect(MakeType(void).getNonNull() != null);
}
fn MakeType(comptime T: type) type {
return struct {
fn getNull() ?T {
return null;
}
fn getNonNull() ?T {
return @as(T, undefined);
}
};
}
test "implicit cast from *[N]T to [*c]T" {
var x: [4]u16 = [4]u16{ 0, 1, 2, 3 };
var y: [*c]u16 = &x;
try expect(std.mem.eql(u16, x[0..4], y[0..4]));
x[0] = 8;
y[3] = 6;
try expect(std.mem.eql(u16, x[0..4], y[0..4]));
}
test "*usize to *void" {
var i = @as(usize, 0);
var v = @ptrCast(*void, &i);
v.* = {};
}
test "@intToEnum passed a comptime_int to an enum with one item" {
const E = enum { A };
const x = @intToEnum(E, 0);
try expect(x == E.A);
}
test "@intCast to u0 and use the result" {
const S = struct {
fn doTheTest(zero: u1, one: u1, bigzero: i32) !void {
try expect((one << @intCast(u0, bigzero)) == 1);
try expect((zero << @intCast(u0, bigzero)) == 0);
}
};
try S.doTheTest(0, 1, 0);
comptime try S.doTheTest(0, 1, 0);
}
test "peer result null and comptime_int" {
const S = struct {
fn blah(n: i32) ?i32 {
if (n == 0) {
return null;
} else if (n < 0) {
return -1;
} else {
return 1;
}
}
};
try expect(S.blah(0) == null);
comptime try expect(S.blah(0) == null);
try expect(S.blah(10).? == 1);
comptime try expect(S.blah(10).? == 1);
try expect(S.blah(-10).? == -1);
comptime try expect(S.blah(-10).? == -1);
}
test "*const ?[*]const T to [*c]const [*c]const T" {
var array = [_]u8{ 'o', 'k' };
const opt_array_ptr: ?[*]const u8 = &array;
const a: *const ?[*]const u8 = &opt_array_ptr;
const b: [*c]const [*c]const u8 = a;
try expect(b.*[0] == 'o');
try expect(b[0][1] == 'k');
}
test "array coersion to undefined at runtime" {
@setRuntimeSafety(true);
// TODO implement @setRuntimeSafety in stage2
if (@import("builtin").zig_is_stage2 and
@import("builtin").mode != .Debug and
@import("builtin").mode != .ReleaseSafe)
{
return error.SkipZigTest;
}
var array = [4]u8{ 3, 4, 5, 6 };
var undefined_val = [4]u8{ 0xAA, 0xAA, 0xAA, 0xAA };
try expect(std.mem.eql(u8, &array, &array));
array = undefined;
try expect(std.mem.eql(u8, &array, &undefined_val));
}
|
test/behavior/cast.zig
|
const std = @import("std");
const mem = std.mem;
const testing = std.testing;
const pdump = @import("../pdump.zig").pdump;
// TODO: These shouldn't be hard coded.
pub const page_size = 512;
pub const max_pages = 1024;
// A simulated flash device. We only simulate parts of flash that
// have consisten sized sectors. The simulated flash is significantly
// more restrictive than regular flash, including the following:
// - write alignment is strictly enforced
// - cannot read across sector boundaries
// - interrupted operations fail on read
// - interrupted operations return worst-case status on "check" (in
// other words, the interrupted operation looks like it completed,
// but will fail the test later.
pub const SimFlash = struct {
const Self = @This();
allocator: mem.Allocator,
areas: []FlashArea,
counter: *Counter,
/// Construct a new flash simulator. There will be two areas
/// created, the first will be one sector larger than the other.
/// TODO: Add support for 4 regions with upgrades.
pub fn init(allocator: mem.Allocator, sector_size: usize, sectors: usize) !SimFlash {
var counter = try allocator.create(Counter);
counter.* = Counter.init(null);
errdefer allocator.destroy(counter);
var base: usize = 128 * 1024;
var primary = try FlashArea.init(allocator, counter, .{
.base = base,
.sectors = sectors + 1,
.sector_size = sector_size,
});
errdefer primary.deinit();
base += (sectors + 1) * sector_size;
var secondary = try FlashArea.init(allocator, counter, .{
.base = base,
.sectors = sectors,
.sector_size = sector_size,
});
errdefer secondary.deinit();
var areas = try allocator.alloc(FlashArea, 2);
areas[0] = primary;
areas[1] = secondary;
return Self{
.allocator = allocator,
.areas = areas,
.counter = counter,
};
}
pub fn deinit(self: *Self) void {
for (self.areas) |*area| {
area.deinit();
}
self.allocator.free(self.areas);
self.allocator.destroy(self.counter);
}
/// Open the given numbered area.
pub fn open(self: *const Self, id: u8) !*FlashArea {
if (id < self.areas.len) {
return &self.areas[id];
} else {
return error.InvalidArea;
}
}
/// Install test images in the two slots. There are no headers
/// (yet), just semi-random data.
pub fn installImages(self: *Self, sizes: [2]usize) !void {
// Always off target, large stack buffer is fine.
var buf: [page_size]u8 = undefined;
for (sizes) |size, id| {
var area = try self.open(@intCast(u8, id));
area.reset();
var pos: usize = 0;
while (pos < size) {
const count = std.math.min(size - pos, page_size);
// Generate some random data.
std.mem.set(u8, buf[0..], 0xFF);
fillBuf(buf[0..count], id * max_pages + pos, id, pos / page_size);
// std.log.warn("Write slot {}, page {} (size {})", .{ id, pos / page_size, count });
// try pdump(buf[0..count]);
try area.erase(pos, page_size);
try area.write(pos, buf[0..]);
pos += count;
}
}
}
// Verify the images in the slots (assuming they are reversed).
pub fn verifyImages(self: *Self, sizes: [2]usize) !void {
var buf: [page_size]u8 = undefined;
var buf_exp: [page_size]u8 = undefined;
// Verify that the swap happened.
for (sizes) |size, id| {
// Reads come from "other", but expected data as if from
// the current one.
var area = try self.open(@intCast(u8, 1 - id));
var pos: usize = 0;
while (pos < size) {
var count = size - pos;
if (count > page_size)
count = page_size;
std.mem.set(u8, buf_exp[0..], 0xFF);
fillBuf(buf_exp[0..count], id * max_pages + pos, id, pos / page_size);
try area.read(pos, buf[0..]);
const exp = buf_exp[0..count];
const got = buf[0..count];
// Print the "other" slot we are verifying.
// std.log.info("verify: slot {}, page {} ({} bytes)", .{ 1 - id, pos / page_size, count });
if (!mem.eql(u8, exp, got)) {
std.log.info("Expecting:", .{});
try pdump(exp);
std.log.info("Got:", .{});
try pdump(got);
}
try std.testing.expectEqualSlices(u8, exp, got);
pos += count;
}
}
}
};
pub const FlashArea = struct {
const Self = @This();
allocator: mem.Allocator,
// These fields are shared with the real implementation.
off: usize,
size: usize,
sectors: usize,
sector_size: usize,
log2_ssize: std.math.Log2Int(usize),
// The data contents of the flash.
data: []u8,
state: []State,
// The parent sim.
counter: *Counter,
pub const AreaInit = struct {
base: usize,
sectors: usize,
sector_size: usize,
};
pub fn init(allocator: mem.Allocator, counter: *Counter, info: AreaInit) !FlashArea {
std.debug.assert(std.math.isPowerOfTwo(info.sector_size));
const log2 = std.math.log2_int(usize, info.sector_size);
var state = try allocator.alloc(State, info.sectors);
mem.set(State, state, .Unsafe);
return FlashArea{
.off = info.base,
.sectors = info.sectors,
.sector_size = info.sector_size,
.data = try allocator.alloc(u8, info.sectors * info.sector_size),
.state = state,
.allocator = allocator,
.log2_ssize = log2,
.size = info.sectors * info.sector_size,
.counter = counter,
};
}
/// Reset the simulated flash to an uninitialized state.
pub fn reset(self: *Self) void {
mem.set(State, self.state, .Unsafe);
mem.set(u8, self.data, 0xAA);
self.counter.reset();
}
pub fn deinit(self: *Self) void {
self.allocator.free(self.data);
self.allocator.free(self.state);
}
// Read a section of data from this area. These are restricted
// to be within a single sector.
pub fn read(self: *Self, offset: usize, buf: []u8) !void {
// Ensure we are in bounds.
if (offset + buf.len > self.data.len) {
return error.FlashBound;
}
const page = offset >> self.log2_ssize;
// Ensure we remain entirely within a sector.
if (page != ((offset + buf.len - 1) >> self.log2_ssize)) {
return error.BeyondSector;
}
switch (self.state[page]) {
.Unsafe => return error.ReadUnsafe,
.Unwritten => return error.ReadUnwritten,
.Erased => return error.ReadErased,
.Written => {},
}
std.mem.copy(u8, buf, self.data[offset .. offset + buf.len]);
}
// Erase a sector. The passed data must correspond exactly with
// one or more sectors.
pub fn erase(self: *Self, off: usize, len: usize) !void {
// TODO: We're relying on the Zig bounds check here. This
// is insecure with "ReleaseFast".
if (off + len > self.data.len) {
return error.FlashBound;
}
var page = off >> self.log2_ssize;
if ((page << self.log2_ssize) != off) {
return error.EraseMisaligned;
}
var count = len >> self.log2_ssize;
if ((count << self.log2_ssize) != len) {
return error.EraseMisaligned;
}
while (count > 0) {
self.state[page] = .Unsafe;
mem.set(u8, self.data[page << self.log2_ssize .. (page + 1) << self.log2_ssize], 0xFF);
try self.counter.act();
self.state[page] = .Erased;
page += 1;
count -= 1;
}
}
// Write data to a page. Writes must always be an entire page,
// and exactly one page.
pub fn write(self: *Self, off: usize, buf: []const u8) !void {
// TODO: Relying on bounds check.
if (off + buf.len > self.data.len) {
return error.FlashBound;
}
const page = off >> self.log2_ssize;
if ((page << self.log2_ssize) != off) {
return error.WriteMisaligned;
}
if (buf.len != self.sector_size) {
return error.WriteMisaligned;
}
switch (self.state[page]) {
.Unsafe => return error.WriteUnsafe,
.Unwritten => return error.WriteUnwritten,
.Erased => {},
.Written => return error.WriteWritten,
}
self.state[page] = .Unwritten;
mem.copy(u8, self.data[off .. off + self.sector_size], buf);
try self.counter.act();
self.state[page] = .Written;
}
// Try to determine the state of flash. This tries to make it
// look like partially completed operations have finished, since
// real flash can behave like that.
pub fn getState(self: *Self, off: usize) !State {
if (off > self.data.len) {
return error.FlashBound;
}
const page = off >> self.log2_ssize;
if ((page << self.log2_ssize) != off) {
return error.GetStateMisaligned;
}
switch (self.state[page]) {
.Unsafe, .Erased => return .Erased,
.Written, .Unwritten => return .Written,
}
}
// Save the contents of flash (useful for debugging).
pub fn save(self: *const Self, path: []const u8) !void {
var fd = try std.fs.cwd().createFile(path, .{});
defer fd.close();
try fd.writeAll(self.data);
}
};
pub const State = enum {
// Flash is in an unknown state. Reads and writes will fail,
// status check will return erased.
Unsafe,
// Partially written data. Reads and writes will fail, status
// check will return written data.
Unwritten,
// A completed erase. Writes are allowed, read will return fail
// (simulating ECC devices). Status check will return written.
Erased,
// A completed write. Reads will succeed, Writes will fail.
// Status check returns written.
Written,
};
// A counter to disrupt flash operations. The is loaned to each flash
// device so that the counts are shared across multiple
// partitions/devices.
pub const Counter = struct {
const Self = @This();
// Number of operations, and the limit.
current: usize,
limit: ?usize,
pub fn init(limit: ?usize) Counter {
return .{
.current = 0,
.limit = limit,
};
}
// Reset the current count.
pub fn reset(self: *Self) void {
self.current = 0;
self.limit = null;
}
// Perform an action. Bumps the counter, if possible. If
// expired, returns error.Expired.
pub fn act(self: *Self) !void {
if (self.limit) |limit| {
if (self.current < limit) {
self.current += 1;
} else {
return error.Expired;
}
} else {
self.current += 1;
}
}
// Set a limit. May return error.Expired if the current value
// would exceed the limit. Limit of 'null' means to have no
// limit.
pub fn setLimit(self: *Self, limit: ?usize) !void {
self.limit = limit;
if (self.limit) |lim| {
if (self.current >= lim)
return error.Expired;
}
}
};
test "Flash operations" {
// Predictable prng for testing.
const page_count = 256;
var sim = try SimFlash.init(testing.allocator, page_size, page_count);
defer sim.deinit();
var buf = try testing.allocator.alloc(u8, page_size);
defer testing.allocator.free(buf);
var buf2 = try testing.allocator.alloc(u8, page_size);
defer testing.allocator.free(buf2);
var area = try sim.open(0);
// The initial data should appear erased, but then fail to read or
// write.
try testing.expectEqual(State.Erased, try area.getState(0));
try testing.expectError(error.ReadUnsafe, area.read(0, buf));
try testing.expectError(error.WriteUnsafe, area.write(0, buf));
// Write data into flash.
var page: usize = 0;
while (page < page_count) : (page += 1) {
const offset = page * page_size;
try area.erase(offset, page_size);
fillBuf(buf, page, 0, page);
try area.write(offset, buf);
}
// Make sure it can all read back.
page = 0;
while (page < page_count) : (page += 1) {
fillBuf(buf, page, 0, page);
std.mem.set(u8, buf2, 0xAA);
try area.read(page * page_size, buf2);
try testing.expectEqualSlices(u8, buf, buf2);
}
}
// Fill a buffer with random bytes, using the given seed.
// Conditionall, the random can be reserved for just a small part, and
// the entire buffer can be made readable text.
fn fillBuf(buf: []u8, seed: u64, slot: usize, page: usize) void {
var rng = std.rand.DefaultPrng.init(seed);
if (false) {
_ = slot;
_ = page;
rng.fill(buf);
} else {
var rawseed: [4]u8 = undefined;
rng.fill(&rawseed);
mem.set(u8, buf, ' ');
_ = std.fmt.bufPrint(buf, "{s} Debug page -----\nSlot: {}\nPage: {}\n", .{
std.fmt.fmtSliceHexLower(&rawseed),
slot,
page,
}) catch {};
}
}
|
src/flash/sim.zig
|
const print = @import("std").debug.print;
pub fn main() void {
// The approximate weight of the Space Shuttle upon liftoff
// (including boosters and fuel tank) was 2,200 tons.
//
// We'll convert this weight from tons to kilograms at a
// conversion of 907.18kg to the ton.
var shuttle_weight: f32 = 907.18 * 2.2e+3;
// By default, float values are formatted in scientific
// notation. Try experimenting with '{d}' and '{d:.3}' to see
// how decimal formatting works.
print("Shuttle liftoff weight: {d:.0}kg\n", .{shuttle_weight});
}
// Floating further:
//
// As an example, Zig's f16 is a IEEE 754 "half-precision" binary
// floating-point format ("binary16"), which is stored in memory
// like so:
//
// 0 1 0 0 0 0 1 0 0 1 0 0 1 0 0 0
// | |-------| |-----------------|
// | exponent significand
// |
// sign
//
// This example is the decimal number 3.140625, which happens to
// be the closest representation of Pi we can make with an f16
// due to the way IEEE-754 floating points store digits:
//
// * Sign bit 0 makes the number positive.
// * Exponent bits 10000 are a scale of 16.
// * Significand bits 1001001000 are the decimal value 584.
//
// IEEE-754 saves space by modifying these values: the value
// 01111 is always subtracted from the exponent bits (in our
// case, 10000 - 01111 = 1, so our exponent is 2^1) and our
// significand digits become the decimal value _after_ an
// implicit 1 (so 1.1001001000 or 1.5703125 in decimal)! This
// gives us:
//
// 2^1 * 1.5703125 = 3.140625
//
// Feel free to forget these implementation details immediately.
// The important thing to know is that floating point numbers are
// great at storing big and small values (f64 lets you work with
// numbers on the scale of the number of atoms in the universe),
// but digits may be rounded, leading to results which are less
// precise than integers.
//
// Fun fact: sometimes you'll see the significand labeled as a
// "mantissa" but <NAME> says not to do that.
//
// C compatibility fact: There is also a Zig floating point type
// specifically for working with C ABIs called c_longdouble.
|
exercises/060_floats.zig
|
const sf = struct {
pub usingnamespace @import("../sfml.zig");
pub usingnamespace sf.system;
pub usingnamespace sf.graphics;
};
const std = @import("std");
const assert = std.debug.assert;
const Image = @This();
// Constructor/destructor
/// Creates a new image
pub fn create(size: sf.Vector2u, color: sf.Color) !Image {
var img = sf.c.sfImage_createFromColor(size.x, size.y, color._toCSFML());
if (img == null)
return sf.Error.nullptrUnknownReason;
return Image{ ._ptr = img.? };
}
/// Creates an image from a pixel array
pub fn createFromPixels(size: sf.Vector2u, pixels: []const sf.Color) !Image {
// Check if there is enough data
if (pixels.len < size.x * size.y)
return sf.Error.notEnoughData;
var img = sf.c.sfImage_createFromPixels(size.x, size.y, @ptrCast([*]const u8, pixels.ptr));
if (img == null)
return sf.Error.nullptrUnknownReason;
return Image{ ._ptr = img.? };
}
/// Loads an image from a file
pub fn createFromFile(path: [:0]const u8) !Image {
var img = sf.c.sfImage_createFromFile(path);
if (img == null)
return sf.Error.resourceLoadingError;
return Image{ ._ptr = img.? };
}
/// Destroys an image
pub fn destroy(self: *Image) void {
sf.c.sfImage_destroy(self._ptr);
}
// Save an image to a file
pub fn saveToFile(self: Image, path: [:0]const u8) !void {
if (sf.c.sfImage_saveToFile(self._ptr, path) != 1)
return sf.Error.savingInFileFailed;
}
// Getters/setters
/// Gets a pixel from this image (bounds are only checked in an assertion)
pub fn getPixel(self: Image, pixel_pos: sf.Vector2u) sf.Color {
const size = self.getSize();
assert(pixel_pos.x < size.x and pixel_pos.y < size.y);
return sf.Color._fromCSFML(sf.c.sfImage_getPixel(self._ptr, pixel_pos.x, pixel_pos.y));
}
/// Sets a pixel on this image (bounds are only checked in an assertion)
pub fn setPixel(self: *Image, pixel_pos: sf.Vector2u, color: sf.Color) void {
const size = self.getSize();
assert(pixel_pos.x < size.x and pixel_pos.y < size.y);
sf.c.sfImage_setPixel(self._ptr, pixel_pos.x, pixel_pos.y, color._toCSFML());
}
/// Gets the size of this image
pub fn getSize(self: Image) sf.Vector2u {
const size = sf.c.sfImage_getSize(self._ptr);
return sf.Vector2u{ .x = size.x, .y = size.y };
}
/// Changes the pixels of the image matching color to be transparent
pub fn createMaskFromColor(self: *Image, color: sf.Color, alpha: u8) void {
sf.c.sfImage_createMaskFromColor(self._ptr, color._toCSFML(), alpha);
}
/// Flip an image horizontally (left <-> right)
pub fn flipHorizontally(self: *Image) void {
sf.c.sfImage_flipHorizontally(self._ptr);
}
/// Flip an image vertically (top <-> bottom)
pub fn flipVertically(self: *Image) void {
sf.c.sfImage_flipVertically(self._ptr);
}
/// Get a read-only pointer to the array of pixels of the image
pub fn getPixelsSlice(self: Image) []const sf.Color {
const ptr = sf.c.sfImage_getPixelsPtr(self._ptr);
const size = self.getSize();
const len = size.x * size.y;
var ret: []const sf.Color = undefined;
ret.len = len;
ret.ptr = @ptrCast([*]const sf.Color, @alignCast(4, ptr));
return ret;
}
/// Pointer to the csfml texture
_ptr: *sf.c.sfImage,
test "image: sane getters and setters" {
const tst = std.testing;
const allocator = std.heap.page_allocator;
var pixel_data = try allocator.alloc(sf.Color, 30);
defer allocator.free(pixel_data);
for (pixel_data) |*c, i| {
c.* = sf.Color.fromHSVA(@intToFloat(f32, i) / 30 * 360, 100, 100, 1);
}
var img = try Image.createFromPixels(.{ .x = 5, .y = 6 }, pixel_data);
defer img.destroy();
try tst.expectEqual(sf.Vector2u{ .x = 5, .y = 6 }, img.getSize());
img.setPixel(.{ .x = 1, .y = 2 }, sf.Color.Cyan);
try tst.expectEqual(sf.Color.Cyan, img.getPixel(.{ .x = 1, .y = 2 }));
var tex = try sf.Texture.createFromImage(img, null);
defer tex.destroy();
img.setPixel(.{ .x = 1, .y = 2 }, sf.Color.Red);
var slice = img.getPixelsSlice();
try tst.expectEqual(sf.Color.Red, slice[0]);
}
|
src/sfml/graphics/Image.zig
|
const Request = @This();
const root = @import("root");
const std = @import("std");
const url = @import("url.zig");
const Url = url.Url;
const Allocator = std.mem.Allocator;
const mem = std.mem;
const Stream = std.net.Stream;
const max_buffer_size = blk: {
const given = if (@hasDecl(root, "buffer_size")) root.buffer_size else 1024 * 64; // 64kB
break :blk std.math.min(given, 1024 * 1024 * 16); // max stack size
};
/// Internal allocator, fed by an arena allocator. Any memory allocated using this
/// allocator will be freed upon the end of a request. It's therefore illegal behaviour
/// to read from/write to anything allocated with this after a request and must be duplicated first,
/// or allocated using a different strategy.
arena: *Allocator,
/// Context provides all information from the actual request that was made by the client.
context: Context,
/// Alias to Stream.ReadError
/// Possible errors that can occur when reading from the connection stream.
pub const ReadError = Stream.ReadError;
/// HTTP methods as specified in RFC 7231
pub const Method = enum {
get,
head,
post,
put,
delete,
connect,
options,
trace,
patch,
any,
fn fromString(string: []const u8) Method {
return switch (string[0]) {
'G' => .get,
'H' => .head,
'P' => @as(Method, switch (string[1]) {
'O' => .post,
'U' => .put,
else => .patch,
}),
'D' => .delete,
'C' => .connect,
'O' => .options,
'T' => .trace,
else => .any,
};
}
};
/// HTTP Protocol version
pub const Protocol = enum {
http_0_9,
http_1_0,
http_1_1,
http_2_0,
/// Checks the given string and gives its protocol version
/// Defaults to HTTP/1.1
fn fromString(protocol: []const u8) Protocol {
const eql = std.mem.eql;
if (eql(u8, protocol, "HTTP/1.1")) return .http_1_1;
if (eql(u8, protocol, "HTTP/2.0")) return .http_2_0;
if (eql(u8, protocol, "HTTP/1.0")) return .http_1_0;
if (eql(u8, protocol, "HTTP/0.9")) return .http_0_9;
return .http_1_1; // default
}
};
/// Represents an HTTP Header
pub const Header = struct {
key: []const u8,
value: []const u8,
};
/// Alias to StringHashMapUnmanaged([]const u8)
pub const Headers = std.StringHashMapUnmanaged([]const u8);
/// Buffered reader for reading the connection stream
pub const Reader = std.io.BufferedReader(4096, Stream.Reader).Reader;
/// `Context` contains the result from the parser.
/// `Request` uses this information to handle correctness when parsing
/// a body or the headers.
pub const Context = struct {
/// GET, POST, PUT, DELETE or PATCH
method: Method,
/// Url object, get be used to retrieve path or query parameters
url: Url,
/// HTTP Request headers data.
raw_header_data: []const u8,
/// Protocol used by the requester, http1.1, http2.0, etc.
protocol: Protocol,
/// Hostname the request was sent to. Includes its port. Required for HTTP/1.1
/// Cannot be null for user when `protocol` is `http1_1`.
host: ?[]const u8,
/// Body of the request. Its livetime equals that of the request itself,
/// meaning that any access to its data beyond that is illegal and must be duplicated
/// to extend its lifetime.
raw_body: []const u8,
/// State of the connection. `keep_alive` is the default for HTTP/1.1 and `close` for earlier versions.
/// For HTTP/2.2 browsers such as Chrome and Firefox ignore this.
connection_type: enum {
keep_alive,
close,
},
/// When form data is supplied, this represents how the data is encoded.
form_type: FormType = .none,
/// Represents the encoding of form data.
const FormType = union(enum) {
/// No form data was supplied
none,
/// Uses application/x-www-form-urlencoded
url_encoded,
/// Uses multipart/form-data
/// Value contains the boundary value. Used to find each chunk
multipart: []const u8,
};
};
/// Iterator to iterate through headers
const Iterator = struct {
slice: []const u8,
index: usize,
/// Searches for the next header.
/// Parsing cannot be failed as that would have been caught by `parse()`
pub fn next(self: *Iterator) ?Header {
if (self.index >= self.slice.len) return null;
var state: enum { key, value } = .key;
var header: Header = undefined;
var start = self.index;
while (self.index < self.slice.len) : (self.index += 1) {
const c = self.slice[self.index];
if (state == .key and c == ':') {
header.key = self.slice[start..self.index];
start = self.index + 2;
state = .value;
}
if (state == .value and c == '\r') {
header.value = self.slice[start..self.index];
self.index += 2;
return header;
}
}
return null;
}
};
/// Creates an iterator to retrieve all headers
/// As the data is known, this does not require any allocations
/// If all headers needs to be known at once, use `headers()`.
pub fn iterator(self: Request) Iterator {
return Iterator{
.slice = self.context.raw_header_data[0..],
.index = 0,
};
}
/// Creates an unmanaged Hashmap from the request headers, memory is owned by caller
/// Every header key and value will be allocated for the map and must therefore be freed
/// manually as well.
pub fn headers(self: Request, gpa: *Allocator) !Headers {
var map = Headers{};
var it = self.iterator();
while (it.next()) |header| {
try map.put(gpa, try gpa.dupe(u8, header.key), try gpa.dupe(u8, header.value));
}
return map;
}
/// Returns the content of the body
/// Its livetime equals that of the request itself,
/// meaning that any access to its data beyond that is illegal and must be duplicated
/// to extend its lifetime.
///
/// In case of a form, this contains the raw body.
/// Use formIterator() or formValue() to access form fields/values.
pub fn body(self: Request) []const u8 {
return self.context.raw_body;
}
/// Returns the path of the request
/// To retrieve the raw path, access `context.url.raw_path`
pub fn path(self: Request) []const u8 {
return self.context.url.path;
}
/// Returns the method of the request as `Method`
pub fn method(self: Request) Method {
return self.context.method;
}
/// Returns the host. This cannot be null when the request
/// is HTTP 1.1 or higher.
pub fn host(self: Request) ?[]const u8 {
return self.context.host;
}
/// Returns a `FormIterator` which can be used
/// to iterate over form fields.
pub fn formIterator(self: Request) FormIterator {
return .{
.form_data = self.context.raw_body,
.index = 0,
.form_type = self.context.form_type,
};
}
/// Searches for a given `key` in the form and returns its value.
/// Returns `null` when key is not found.
///
/// NOTE: As the key and value may be url-encoded, this function requires
/// allocations to decode them. Only the result must be freed manually,
/// as this function will handle free'ing any memory that isn't returned to the user.
///
/// NOTE2: If retrieving multiple fields, use `formIterator()` or `form()`
/// as each call to `formValue` will iterate over all fields.
pub fn formValue(self: Request, gpa: *Allocator, key: []const u8) !?[]const u8 {
var it = self.formIterator();
return while (try it.next(gpa)) |field| {
defer gpa.free(field.key);
if (std.mem.eql(u8, key, field.key)) break field.value;
gpa.free(field.value); // only free value if it doesn't match the wanted key.
} else null;
}
/// Constructs a map of key-value pairs for each form field.
/// User is responsible for managing its memory.
pub fn form(self: Request, gpa: *Allocator) !url.KeyValueMap {
var map = url.KeyValueMap{ .map = .{} };
errdefer map.deinit(gpa);
var it = self.formIterator();
while (try it.next(gpa)) |field| {
errdefer field.deinit(gpa);
try map.map.put(gpa, field.key, field.value);
}
return map;
}
/// Iterator to find all form fields.
const FormIterator = struct {
form_data: []const u8,
index: usize,
form_type: Context.FormType,
/// Represents a key-value pair in a form body
const Field = struct {
/// Input field
key: []const u8,
/// Value of the field. Allocated and should be freed manually.
value: []const u8,
/// Frees the memory allocated for the `Field`
pub fn deinit(self: Field, gpa: *Allocator) void {
gpa.free(self.key);
gpa.free(self.value);
}
};
/// Finds the next form field. Will return `null` when it reached
/// the end of the form.
pub fn next(self: *FormIterator, gpa: *Allocator) !?Field {
if (self.index >= self.form_data.len) return null;
switch (self.form_type) {
.none => return null,
.multipart => |boundary_name| {
const data = self.form_data[self.index..];
var batch_name: [72]u8 = undefined;
std.mem.copy(u8, &batch_name, "--");
std.mem.copy(u8, batch_name[2..], boundary_name);
var batch_it = std.mem.split(u8, data, batch_name[0 .. boundary_name.len + 2]);
var batch = batch_it.next() orelse return error.InvalidBody;
batch = batch_it.next() orelse return error.InvalidBody; // Actually get the batch as first one has len 0
self.index += batch.len;
if (std.mem.startsWith(u8, batch, "--")) return null; // end of body
var field: Field = undefined;
var cur_index = boundary_name.len + 3; // '--' & '\n'
// get input name
const name_start = std.mem.indexOfPos(u8, batch, cur_index, "name=") orelse return error.InvalidBody;
var field_start = name_start + "name=".len;
if (batch[field_start] == '"') field_start += 1;
var field_end = field_start;
for (batch[field_end..]) |c, i| {
if (c == '"' or c == '\n') {
field_end += i;
break;
}
}
cur_index = field_end;
if (batch[cur_index] == '"') cur_index += 2 else cur_index += 1; // '"' & '\n'
field.key = try gpa.dupe(u8, batch[field_start..field_end]);
errdefer gpa.free(field.key);
var value_list = std.ArrayList(u8).init(gpa);
try value_list.ensureTotalCapacity(batch.len - cur_index);
defer value_list.deinit();
for (batch[cur_index..]) |char| if (char != '\r' and char != '\n') value_list.appendAssumeCapacity(char);
field.value = value_list.toOwnedSlice();
return field;
},
.url_encoded => {
var key = self.form_data[self.index..];
if (std.mem.indexOfScalar(u8, key, '&')) |index| {
key = key[0..index];
self.index += key.len + 1;
} else self.index += key.len;
var value: []const u8 = undefined;
if (std.mem.indexOfScalar(u8, key, '=')) |index| {
value = key[index + 1 ..];
key = key[0..index];
} else return error.InvalidBody;
const unencoded_key = try url.decode(gpa, key);
errdefer gpa.free(unencoded_key);
return Field{
.key = unencoded_key,
.value = try url.decode(gpa, value),
};
},
}
}
};
/// Errors which can occur during the parsing of
/// a HTTP request.
pub const ParseError = error{
OutOfMemory,
/// Method is missing or invalid
InvalidMethod,
/// URL is missing in status line or invalid
InvalidUrl,
/// Protocol in status line is missing or invalid
InvalidProtocol,
/// Headers are missing
MissingHeaders,
/// Invalid header was found
IncorrectHeader,
/// Buffer overflow when parsing an integer
Overflow,
/// Invalid character when parsing an integer
InvalidCharacter,
/// When the connection has been closed or no more data is available
EndOfStream,
/// Provided request's size is bigger than max size (2^32).
StreamTooLong,
/// Request headers are too large and do not find in `buffer_size`
HeadersTooLarge,
/// Line ending of the requests are corrupted/invalid. According to the http
/// spec, each line must end with \r\n
InvalidLineEnding,
/// When body is incomplete
InvalidBody,
/// When the client uses HTTP version 1.1 and misses the 'host' header, this error will
/// be returned.
MissingHost,
};
/// Parse accepts a `Reader`. It will read all data it contains
/// and tries to parse it into a `Request`. Can return `ParseError` if data is corrupt.
/// The Allocator is made available to users that require an allocation for during a single request,
/// as an arena is passed in by the `Server`. The provided buffer is used to parse the actual content,
/// meaning the entire request -> response can be done with no allocations.
pub fn parse(gpa: *Allocator, reader: anytype, buffer: []u8) (ParseError || Stream.ReadError)!Request {
return Request{
.arena = gpa,
.context = try parseContext(
gpa,
reader,
buffer,
),
};
}
fn parseContext(gpa: *Allocator, reader: anytype, buffer: []u8) (ParseError || @TypeOf(reader).Error)!Context {
var ctx: Context = .{
.method = .get,
.url = Url{
.path = "/",
.raw_path = "/",
.raw_query = "",
},
.raw_header_data = undefined,
.protocol = .http_1_1,
.host = null,
.raw_body = "",
.connection_type = .keep_alive,
};
var parser = Parser(@TypeOf(reader)).init(gpa, buffer, reader);
while (try parser.nextEvent()) |event| {
switch (event) {
.status => |status| {
ctx.protocol = Request.Protocol.fromString(status.protocol);
ctx.url = Url.init(status.path);
ctx.method = Request.Method.fromString(status.method);
},
.header => |header| {
if (ctx.protocol == .http_1_1 and
ctx.connection_type == .keep_alive and
std.ascii.eqlIgnoreCase(header.key, "connection"))
{
if (std.ascii.eqlIgnoreCase(header.value, "close")) ctx.connection_type = .close;
}
if (ctx.host == null and std.ascii.eqlIgnoreCase(header.key, "host"))
ctx.host = header.value;
if (ctx.form_type == .none and
std.ascii.eqlIgnoreCase(header.key, "content-type"))
{
if (std.ascii.indexOfIgnoreCase(header.value, "multipart/form-data")) |_| {
const semicolon = "multipart/form-data".len;
if (header.value[semicolon] != ';') return error.InvalidBody;
if (std.mem.indexOfScalarPos(u8, header.value, semicolon, '=')) |eql_char| {
var end = parser.index - 3; // remove \r\n
if (buffer[end] != '"') end += 1;
var start: usize = parser.index - 2 - header.value.len + eql_char + 1;
if (buffer[start] == '"') start += 1; // strip "
if (end - start > 70) return error.IncorrectHeader; // Boundary may be at max 70 characters
ctx.form_type = .{ .multipart = buffer[start..end] };
} else return error.InvalidBody;
} else if (std.ascii.eqlIgnoreCase(header.value, "application/x-www-form-urlencoded")) {
ctx.form_type = .url_encoded;
}
}
},
.end_of_header => ctx.raw_header_data = buffer[parser.header_start..parser.header_end],
.body => |content| ctx.raw_body = content,
}
}
if (ctx.host == null and ctx.protocol == .http_1_1) return error.MissingHost;
return ctx;
}
fn Parser(ReaderType: anytype) type {
return struct {
const Self = @This();
gpa: *Allocator,
buffer: []u8,
index: usize,
state: std.meta.Tag(Event),
reader: ReaderType,
done: bool,
content_length: usize,
header_start: usize,
header_end: usize,
chunked: bool,
const Event = union(enum) {
status: struct {
method: []const u8,
path: []const u8,
protocol: []const u8,
},
header: struct {
key: []const u8,
value: []const u8,
},
body: []const u8,
// reached end of header
end_of_header: void,
};
const Error = ParseError || ReaderType.Error;
fn init(gpa: *Allocator, buffer: []u8, reader: ReaderType) Self {
return .{
.gpa = gpa,
.buffer = buffer,
.reader = reader,
.state = .status,
.index = 0,
.done = false,
.content_length = 0,
.header_start = 0,
.header_end = 0,
.chunked = false,
};
}
fn nextEvent(self: *Self) Error!?Event {
if (self.done) return null;
return switch (self.state) {
.status => self.parseStatus(),
.header => self.parseHeader(),
.body => self.parseBody(),
.end_of_header => unreachable,
};
}
fn parseStatus(self: *Self) Error!?Event {
self.state = .header;
const line = (try self.reader.readUntilDelimiterOrEof(self.buffer, '\n')) orelse return ParseError.EndOfStream;
self.index += line.len + 1;
self.header_start = self.index;
var it = mem.tokenize(u8, try assertLE(line), " ");
const parsed_method = it.next() orelse return ParseError.InvalidMethod;
const parsed_path = it.next() orelse return ParseError.InvalidUrl;
const protocol = it.next() orelse return ParseError.InvalidProtocol;
return Event{
.status = .{
.method = parsed_method,
.path = parsed_path,
.protocol = protocol,
},
};
}
fn parseHeader(self: *Self) Error!?Event {
const line = (try self.reader.readUntilDelimiterOrEof(self.buffer[self.index..], '\n')) orelse return ParseError.EndOfStream;
self.index += line.len + 1;
if (line.len == 1 and line[0] == '\r') {
self.header_end = self.index;
if (self.content_length == 0 and !self.chunked) {
self.done = true;
}
self.state = .body;
return Event.end_of_header;
}
var it = mem.split(u8, try assertLE(line), ": ");
const key = it.next() orelse return ParseError.MissingHeaders;
const value = it.next() orelse return ParseError.IncorrectHeader;
// if content length hasn't been set yet,
// check if it exists and set it by parsing the int value
if (self.content_length == 0 and
std.ascii.eqlIgnoreCase("content-length", key))
{
self.content_length = try std.fmt.parseInt(usize, value, 10);
}
// check if chunked body
if (std.ascii.eqlIgnoreCase("transfer-encoding", key)) {
// transfer-encoding can contain a list of encodings.
// Therefore, iterate over them and check for 'chunked'.
var split = std.mem.split(u8, value, ", ");
while (split.next()) |maybe_chunk| {
if (std.ascii.eqlIgnoreCase("chunked", maybe_chunk)) {
self.chunked = true;
}
}
}
return Event{
.header = .{
.key = key,
.value = value,
},
};
}
fn parseBody(self: *Self) Error!?Event {
defer self.done = true;
if (self.content_length != 0) {
const raw_body = try self.gpa.alloc(u8, self.content_length);
try self.reader.readNoEof(raw_body);
return Event{ .body = raw_body };
}
std.debug.assert(self.chunked);
var body_list = std.ArrayList(u8).init(self.gpa);
defer body_list.deinit();
var read_len: usize = 0;
while (true) {
var len_buf: [1024]u8 = undefined; //Used to read the length of a chunk
const lf_line = (try self.reader.readUntilDelimiterOrEof(&len_buf, '\n')) orelse
return error.InvalidBody;
const line = try assertLE(lf_line);
const index = std.mem.indexOfScalar(u8, line, ';') orelse
line.len;
const chunk_len = try std.fmt.parseInt(usize, line[0..index], 10);
try body_list.resize(read_len + chunk_len);
try self.reader.readNoEof(body_list.items[read_len..]);
read_len += chunk_len;
// validate clrf
var crlf: [2]u8 = undefined;
try self.reader.readNoEof(&crlf);
if (!std.mem.eql(u8, "\r\n", &crlf)) return error.InvalidBody;
if (chunk_len == 0) {
break;
}
}
return Event{ .body = body_list.toOwnedSlice() };
}
fn assertLE(line: []const u8) ParseError![]const u8 {
if (line.len == 0) return ParseError.InvalidLineEnding;
const idx = line.len - 1;
if (line[idx] != '\r') return ParseError.InvalidLineEnding;
return line[0..idx];
}
};
}
test "Basic request parse" {
const contents =
"GET /test?test HTTP/1.1\r\n" ++
"Host: localhost:8080\r\n" ++
"User-Agent: insomnia/7.1.1\r\n" ++
"Accept: */*\r\n" ++
"Content-Length: 9\r\n" ++
"\r\n" ++
"some body";
var buf: [4096]u8 = undefined;
const stream = std.io.fixedBufferStream(contents).reader();
var request = try parse(std.testing.allocator, stream, &buf);
defer std.testing.allocator.free(request.context.raw_body);
try std.testing.expectEqualStrings("/test", request.path());
try std.testing.expectEqual(Request.Protocol.http_1_1, request.context.protocol);
try std.testing.expectEqual(Request.Method.get, request.context.method);
try std.testing.expectEqualStrings("some body", request.body());
var _headers = try request.headers(std.testing.allocator);
defer {
var it = _headers.iterator();
while (it.next()) |header| {
std.testing.allocator.free(header.key_ptr.*);
std.testing.allocator.free(header.value_ptr.*);
}
_headers.deinit(std.testing.allocator);
}
try std.testing.expect(_headers.contains("Host"));
try std.testing.expect(_headers.contains("Accept"));
}
test "Request iterator" {
const _headers =
"User-Agent: ApplePieClient/1\r\n" ++
"Accept: application/json\r\n" ++
"content-Length: 0\r\n";
var it = Request.Iterator{
.slice = _headers,
.index = 0,
};
const header1 = it.next().?;
const header2 = it.next().?;
const header3 = it.next().?;
const header4 = it.next();
try std.testing.expectEqualStrings("User-Agent", header1.key);
try std.testing.expectEqualStrings("ApplePieClient/1", header1.value);
try std.testing.expectEqualStrings("Accept", header2.key);
try std.testing.expectEqualStrings("content-Length", header3.key);
try std.testing.expectEqual(@as(?Request.Header, null), header4);
}
test "Chunked encoding" {
const content =
"GET /test?test HTTP/1.1\r\n" ++
"Host: localhost:8080\r\n" ++
"User-Agent: insomnia/7.1.1\r\n" ++
"Accept: */*\r\n" ++
"Transfer-Encoding: chunked\r\n" ++
"\r\n" ++
"7\r\n" ++
"Mozilla\r\n" ++
"9\r\n" ++
"Developer\r\n" ++
"7\r\n" ++
"Network\r\n" ++
"0\r\n" ++
"\r\n";
var buf: [2048]u8 = undefined;
var fb = std.io.fixedBufferStream(content).reader();
var request = try parse(std.testing.allocator, fb, &buf);
defer std.testing.allocator.free(request.body());
try std.testing.expectEqualStrings("MozillaDeveloperNetwork", request.body());
}
test "Form body (url-encoded)" {
const content =
"POST / HTTP/1.1\r\n" ++
"Host: localhost:8080\r\n" ++
"Accept: */*\r\n" ++
"Content-Length: 27\r\n" ++
"Content-Type: application/x-www-form-urlencoded\r\n" ++
"\r\n" ++
"Field1=value1&Field2=value2";
var buf: [2048]u8 = undefined;
var fb = std.io.fixedBufferStream(content).reader();
var request = try parse(std.testing.allocator, fb, &buf);
defer std.testing.allocator.free(request.body());
try std.testing.expectEqualStrings("Field1=value1&Field2=value2", request.body());
const expected: []const []const u8 = &.{
"Field1", "value1", "Field2", "value2",
};
var it = request.formIterator();
var index: usize = 0;
while (try it.next(std.testing.allocator)) |field| {
defer field.deinit(std.testing.allocator);
defer index += 2;
try std.testing.expectEqualStrings(expected[index], field.key);
try std.testing.expectEqualStrings(expected[index + 1], field.value);
}
try std.testing.expectEqual(expected.len, index);
const check_value = try request.formValue(std.testing.allocator, "Field2");
defer if (check_value) |val| std.testing.allocator.free(val);
try std.testing.expectEqualStrings("value2", check_value.?);
var as_map = try request.form(std.testing.allocator);
defer as_map.deinit(std.testing.allocator);
try std.testing.expectEqualStrings("value1", as_map.get("Field1").?);
}
test "Form body (multipart)" {
const content =
"POST / HTTP/1.1\r\n" ++
"Host: localhost:8080\r\n" ++
"Accept: */*\r\n" ++
"Content-Length: 140\r\n" ++
"Content-Type: multipart/form-data; boundary=\"boundary\"\r\n" ++
"\r\n" ++
"--boundary\n" ++
"Content-Disposition: form-data; name=\"Field1\"\n" ++
"value1\n" ++
"--boundary\n" ++
"Content-Disposition: form-data; name=\"Field2\"\n" ++
"value2\n" ++
"--boundary--";
var buf: [2048]u8 = undefined;
var fb = std.io.fixedBufferStream(content).reader();
var request = try parse(std.testing.allocator, fb, &buf);
defer std.testing.allocator.free(request.body());
try std.testing.expectEqualStrings("--boundary\n" ++
"Content-Disposition: form-data; name=\"Field1\"\n" ++
"value1\n" ++
"--boundary\n" ++
"Content-Disposition: form-data; name=\"Field2\"\n" ++
"value2\n" ++
"--boundary--", request.body());
const expected: []const []const u8 = &.{
"Field1", "value1", "Field2", "value2",
};
var it = request.formIterator();
var index: usize = 0;
while (try it.next(std.testing.allocator)) |field| {
defer field.deinit(std.testing.allocator);
defer index += 2;
try std.testing.expectEqualStrings(expected[index], field.key);
try std.testing.expectEqualStrings(expected[index + 1], field.value);
}
try std.testing.expectEqual(expected.len, index);
const check_value = try request.formValue(std.testing.allocator, "Field2");
defer if (check_value) |val| std.testing.allocator.free(val);
try std.testing.expectEqualStrings("value2", check_value.?);
var as_map = try request.form(std.testing.allocator);
defer as_map.deinit(std.testing.allocator);
try std.testing.expectEqualStrings("value1", as_map.get("Field1").?);
}
|
src/Request.zig
|
const std = @import("std");
const mem = std.mem;
const process = std.process;
const fs = std.fs;
const path = fs.path;
pub fn main() anyerror!void {
var context = std.StringHashMap([]u8).init(std.heap.c_allocator);
var arg_it = process.args();
_ = arg_it.skip();
const name = try (arg_it.next(std.heap.c_allocator) orelse {
std.debug.warn("First argument should be the name\n", .{});
return error.InvalidArgs;
});
const package = try (arg_it.next(std.heap.c_allocator) orelse {
std.debug.warn("Second argument should be the package\n", .{});
return error.InvalidArgs;
});
const java_version = try (arg_it.next(std.heap.c_allocator) orelse {
std.debug.warn("Third argument should be the java version\n", .{});
return error.InvalidArgs;
});
var joined = try path.join(std.heap.c_allocator, &[_][]const u8{
name,
"src",
"main",
"java",
try replaceAscii(package, '.', path.sep),
try toLowerCaseAscii(name),
});
std.debug.warn("{}\n", .{joined});
_ = try context.put("name", name);
_ = try context.put("lowerName", try toLowerCaseAscii(name));
_ = try context.put("package", package);
_ = try context.put("java_version", java_version);
var pomTemplate = try loadTemplate("../pom.xml.template");
var javaTemplate = try loadTemplate("../Main.java.template");
var current = fs.cwd();
try current.makePath(joined);
var javaFile = try (try current.openDir(joined, .{})).createFile("Main.java", .{});
var pomFile = try (try current.openDir(name, .{})).createFile("pom.xml", .{});
try javaFile.writeAll(try writeTemplate(javaTemplate, context));
try pomFile.writeAll(try writeTemplate(pomTemplate, context));
}
pub fn toLowerCaseAscii(string: []u8) ![]u8 {
var buffer = std.ArrayList(u8).init(std.heap.c_allocator);
for (string) |c| {
if (c >= 65 and c <= 90) {
try buffer.append(c + 32);
} else {
try buffer.append(c);
}
}
return buffer.span();
}
pub fn replaceAscii(string: []u8, from: u8, to: u8) ![]u8 {
var buffer = std.ArrayList(u8).init(std.heap.c_allocator);
for (string) |c| {
if (c == from) {
try buffer.append(to);
} else {
try buffer.append(c);
}
}
return buffer.span();
}
pub fn writeTemplate(templateParts: []TemplatePart, context: std.StringHashMap([]u8)) ![]u8 {
var buffer = std.ArrayList(u8).init(std.heap.c_allocator);
for (templateParts) |part| {
switch (part) {
TemplatePartTag.Text => |value| {
for (value) |char| {
try buffer.append(char);
}
},
TemplatePartTag.TemplateName => |value| {
if (context.get(value)) |templateValue| {
for (templateValue.value) |char| {
try buffer.append(char);
}
}
},
}
}
return buffer.span();
}
const TemplatePartTag = enum {
Text,
TemplateName,
};
const TemplatePart = union(TemplatePartTag) {
Text: []u8,
TemplateName: []u8,
};
pub fn loadTemplate(comptime file_name: []const u8) ![]TemplatePart {
var result = std.ArrayList(TemplatePart).init(std.heap.c_allocator);
const content = @embedFile(file_name);
var buffer = std.ArrayList(u8).init(std.heap.c_allocator);
var in_template = false;
var last_char: ?u8 = null;
var just_entered = false;
var just_left = false;
for (content) |value| {
if (last_char) |lc| {
if (value == '{' and lc == '{') {
in_template = true;
just_entered = true;
try result.append(TemplatePart{ .Text = buffer.span() });
buffer = std.ArrayList(u8).init(std.heap.c_allocator);
} else if (value == '}' and lc == '}') {
in_template = false;
just_left = true;
try result.append(TemplatePart{ .TemplateName = buffer.span() });
buffer = std.ArrayList(u8).init(std.heap.c_allocator);
} else {
if (in_template) {
if (!just_entered) {
try buffer.append(lc);
} else {
just_entered = false;
}
} else {
if (!just_left) {
try buffer.append(lc);
} else {
just_left = false;
}
}
}
}
last_char = value;
}
if (last_char) |lc| {
try buffer.append(lc);
}
try result.append(TemplatePart{ .Text = buffer.span() });
return result.span();
}
|
src/main.zig
|
const std = @import("std");
const assert = std.debug.assert;
const tools = @import("tools");
const Vec2 = tools.Vec2;
const Map = tools.Map(u8, 1000, 2000, false);
pub fn run(input_text: []const u8, allocator: std.mem.Allocator) ![2][]const u8 {
var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit();
var map = Map{ .default_tile = '.' };
map.fill('.', null);
{
var it = std.mem.tokenize(u8, input_text, "\n\r");
while (it.next()) |line| {
if (tools.match_pattern("x={}, y={}..{}", line)) |fields| {
const x = @intCast(i32, fields[0].imm);
const ymin = @intCast(i32, fields[1].imm);
const ymax = @intCast(i32, fields[2].imm);
var p = Vec2{ .x = x, .y = ymin };
while (p.y <= ymax) : (p.y += 1) {
map.set(p, '#');
}
} else if (tools.match_pattern("y={}, x={}..{}", line)) |fields| {
const y = @intCast(i32, fields[0].imm);
const xmin = @intCast(i32, fields[1].imm);
const xmax = @intCast(i32, fields[2].imm);
var p = Vec2{ .x = xmin, .y = y };
while (p.x <= xmax) : (p.x += 1) {
map.set(p, '#');
}
}
}
map.bbox.min.x -= 1;
map.bbox.max.x += 1;
}
const ans1 = ans: {
const bbox = map.bbox;
const source = Vec2{ .x = 500, .y = 0 };
map.set(source, 'v');
var dirty_bbox: tools.BBox = bbox;
dirty_bbox.min = Vec2.min(source, dirty_bbox.min);
dirty_bbox.max = Vec2.max(source, dirty_bbox.max);
while (true) {
var it = map.iter(dirty_bbox);
dirty_bbox = tools.BBox.empty;
while (it.nextEx()) |sq| {
var t = sq.t.*;
const up = if (sq.up) |x| x else '.';
const right = if (sq.right) |x| x else '.';
const left = if (sq.left) |x| x else '.';
const down_right = if (sq.down_right) |x| x else '.';
const down = if (sq.down) |x| x else '.';
const down_left = if (sq.down_left) |x| x else '.';
const ground_left = (down == '#' or down == '~') and (down_left == '#' or down_left == '~');
const ground_right = (down == '#' or down == '~') and (down_right == '#' or down_right == '~');
switch (t) {
'#' => continue,
'~' => continue,
'.' => {
if (up == 'v') t = 'v';
if (right == 'v' and ground_right) t = 'v';
if (left == 'v' and ground_left) t = 'v';
if (right == 'v' and down_right == '#') t = 'v';
if (left == 'v' and down_left == '#') t = 'v';
if (right == '<' and (down_right == '#' or down_right == '~')) t = 'v';
if (left == '>' and (down_left == '#' or down_left == '~')) t = 'v';
},
'v' => {
if (right == 'v' and left == '#') t = '>';
if (left == 'v' and right == '#') t = '<';
if (right == '#' and left == '#' and ground_left and ground_right) t = '~';
if (left == '>') t = '>';
if (right == '<') t = '<';
},
'>' => {
if (right == '<') t = '~';
if (right == '#') t = '~';
if (right == '~') t = '~';
},
'<' => {
if (left == '>') t = '~';
if (left == '#') t = '~';
if (left == '~') t = '~';
},
else => unreachable,
}
if (sq.t.* != t) {
sq.t.* = t;
dirty_bbox.min = Vec2.min(sq.p, dirty_bbox.min);
dirty_bbox.max = Vec2.max(sq.p, dirty_bbox.max);
}
}
if (Vec2.eq(dirty_bbox.min, tools.BBox.empty.min)) {
var water_bbox = tools.BBox.empty;
var water: u32 = 0;
var it2 = map.iter(bbox);
while (it2.nextEx()) |sq| {
switch (sq.t.*) {
'~', '>', '<', 'v' => {
water_bbox.min = Vec2.min(sq.p, water_bbox.min);
water_bbox.max = Vec2.max(sq.p, water_bbox.max);
water += 1;
},
else => {},
}
}
if (false) {
var buf: [2000 * 1000]u8 = undefined;
std.debug.print("{}\n", .{map.printToBuf(null, water_bbox, null, &buf)});
}
break :ans water;
}
dirty_bbox.min.x -= 1;
dirty_bbox.max.x += 1;
dirty_bbox.min.y -= 1;
dirty_bbox.max.y += 1;
if (false) {
const water = blk: {
var w: u32 = 0;
var it2 = map.iter(bbox);
while (it2.next()) |sq| {
switch (sq) {
'~', '>', '<', 'v' => w += 1,
else => {},
}
}
break :blk w;
};
var buf: [300 * 300]u8 = undefined;
std.debug.print("{}\n", .{map.printToBuf(null, dirty_bbox, null, &buf)});
std.debug.print("water = {}\n", .{water});
}
}
unreachable;
};
const ans2 = ans: {
const water = blk: {
var w: u32 = 0;
var it2 = map.iter(null);
while (it2.next()) |sq| {
switch (sq) {
'~' => w += 1,
else => {},
}
}
break :blk w;
};
break :ans water;
};
return [_][]const u8{
try std.fmt.allocPrint(allocator, "{}", .{ans1}),
try std.fmt.allocPrint(allocator, "{}", .{ans2}),
};
}
pub const main = tools.defaultMain("2018/input_day17.txt", run);
|
2018/day17.zig
|
// DO NOT MODIFY. This is not actually a source file; it is a textual representation of generated code.
// Use only for debugging purposes.
// Auto-generated constructor
// Access: public
Method <init> : V
(
// (no arguments)
) {
ALOAD 0
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/runtime/Application#<init>
RETURN
}
// Access: static
Field STARTUP_CONTEXT : Lio/quarkus/runtime/StartupContext;
// Access: protected final
Method doStart : V
(
arg 1 = [Ljava/lang/String;
) {
** label1
LDC (String) "io.netty.allocator.maxOrder"
LDC (String) "1"
// Method descriptor: (Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
INVOKESTATIC java/lang/System#setProperty
POP
LDC (String) "java.util.logging.manager"
LDC (String) "org.jboss.logmanager.LogManager"
// Method descriptor: (Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
INVOKESTATIC java/lang/System#setProperty
POP
// Method descriptor: ()V
INVOKESTATIC io/quarkus/runtime/SubstrateRuntimePropertiesRecorder#doRuntime
// Method descriptor: ()V
INVOKESTATIC io/quarkus/runtime/Timing#mainStarted
// Field descriptor: Lio/quarkus/runtime/StartupContext;
GETSTATIC io/quarkus/runner/ApplicationImpl1#STARTUP_CONTEXT
ASTORE 2
** label2
// Method descriptor: ()V
INVOKESTATIC io/quarkus/runtime/generated/RunTimeConfig#getRunTimeConfiguration
NEW io/quarkus/deployment/steps/LoggingResourceProcessor$setupLoggingRuntimeInit5
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/deployment/steps/LoggingResourceProcessor$setupLoggingRuntimeInit5#<init>
CHECKCAST io/quarkus/runtime/StartupTask
ALOAD 2
// Method descriptor: (Lio/quarkus/runtime/StartupContext;)V
INVOKEINTERFACE io/quarkus/runtime/StartupTask#deploy
NEW io/quarkus/deployment/steps/VertxCoreProcessor$buildWeb8
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/deployment/steps/VertxCoreProcessor$buildWeb8#<init>
CHECKCAST io/quarkus/runtime/StartupTask
ALOAD 2
// Method descriptor: (Lio/quarkus/runtime/StartupContext;)V
INVOKEINTERFACE io/quarkus/runtime/StartupTask#deploy
NEW io/quarkus/deployment/steps/VertxHttpProcessor$cors6
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/deployment/steps/VertxHttpProcessor$cors6#<init>
CHECKCAST io/quarkus/runtime/StartupTask
ALOAD 2
// Method descriptor: (Lio/quarkus/runtime/StartupContext;)V
INVOKEINTERFACE io/quarkus/runtime/StartupTask#deploy
NEW io/quarkus/deployment/steps/VertxCoreProcessor$eventLoopCount4
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/deployment/steps/VertxCoreProcessor$eventLoopCount4#<init>
CHECKCAST io/quarkus/runtime/StartupTask
ALOAD 2
// Method descriptor: (Lio/quarkus/runtime/StartupContext;)V
INVOKEINTERFACE io/quarkus/runtime/StartupTask#deploy
NEW io/quarkus/deployment/steps/NettyProcessor$eagerlyInitClass1
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/deployment/steps/NettyProcessor$eagerlyInitClass1#<init>
CHECKCAST io/quarkus/runtime/StartupTask
ALOAD 2
// Method descriptor: (Lio/quarkus/runtime/StartupContext;)V
INVOKEINTERFACE io/quarkus/runtime/StartupTask#deploy
NEW io/quarkus/deployment/steps/ThreadPoolSetup$createExecutor7
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/deployment/steps/ThreadPoolSetup$createExecutor7#<init>
CHECKCAST io/quarkus/runtime/StartupTask
ALOAD 2
// Method descriptor: (Lio/quarkus/runtime/StartupContext;)V
INVOKEINTERFACE io/quarkus/runtime/StartupTask#deploy
NEW io/quarkus/deployment/steps/VertxHttpProcessor$initializeRouter12
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/deployment/steps/VertxHttpProcessor$initializeRouter12#<init>
CHECKCAST io/quarkus/runtime/StartupTask
ALOAD 2
// Method descriptor: (Lio/quarkus/runtime/StartupContext;)V
INVOKEINTERFACE io/quarkus/runtime/StartupTask#deploy
NEW io/quarkus/deployment/steps/ConfigBuildStep$validateConfigProperties22
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/deployment/steps/ConfigBuildStep$validateConfigProperties22#<init>
CHECKCAST io/quarkus/runtime/StartupTask
ALOAD 2
// Method descriptor: (Lio/quarkus/runtime/StartupContext;)V
INVOKEINTERFACE io/quarkus/runtime/StartupTask#deploy
NEW io/quarkus/deployment/steps/VertxCoreProcessor$build21
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/deployment/steps/VertxCoreProcessor$build21#<init>
CHECKCAST io/quarkus/runtime/StartupTask
ALOAD 2
// Method descriptor: (Lio/quarkus/runtime/StartupContext;)V
INVOKEINTERFACE io/quarkus/runtime/StartupTask#deploy
NEW io/quarkus/deployment/steps/UndertowBuildStep$boot25
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/deployment/steps/UndertowBuildStep$boot25#<init>
CHECKCAST io/quarkus/runtime/StartupTask
ALOAD 2
// Method descriptor: (Lio/quarkus/runtime/StartupContext;)V
INVOKEINTERFACE io/quarkus/runtime/StartupTask#deploy
NEW io/quarkus/deployment/steps/VertxHttpProcessor$finalizeRouter26
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/deployment/steps/VertxHttpProcessor$finalizeRouter26#<init>
CHECKCAST io/quarkus/runtime/StartupTask
ALOAD 2
// Method descriptor: (Lio/quarkus/runtime/StartupContext;)V
INVOKEINTERFACE io/quarkus/runtime/StartupTask#deploy
NEW io/quarkus/deployment/steps/LifecycleEventsBuildStep$startupEvent27
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/deployment/steps/LifecycleEventsBuildStep$startupEvent27#<init>
CHECKCAST io/quarkus/runtime/StartupTask
ALOAD 2
// Method descriptor: (Lio/quarkus/runtime/StartupContext;)V
INVOKEINTERFACE io/quarkus/runtime/StartupTask#deploy
LDC (String) "0.23.2"
LDC (String) "cdi, rest-client, resteasy, resteasy-jsonb"
LDC (String) "prod"
LDC (Boolean) false
// Method descriptor: (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)V
INVOKESTATIC io/quarkus/runtime/Timing#printStartupTime
** label3
GOTO label4
** label5
ASTORE 3
ALOAD 3
// Method descriptor: ()V
INVOKEVIRTUAL java/lang/Throwable#printStackTrace
ALOAD 2
// Method descriptor: ()V
INVOKEVIRTUAL io/quarkus/runtime/StartupContext#close
NEW java/lang/RuntimeException
DUP
LDC (String) "Failed to start quarkus"
ALOAD 3
// Method descriptor: (Ljava/lang/String;Ljava/lang/Throwable;)V
INVOKESPECIAL java/lang/RuntimeException#<init>
CHECKCAST java/lang/Throwable
ATHROW
** label6
GOTO label4
// Try from label2 to label3
// Catch java/lang/Throwable by going to label5
** label4
RETURN
** label7
}
// Access: protected final
Method doStop : V
(
// (no arguments)
) {
** label1
// Field descriptor: Lio/quarkus/runtime/StartupContext;
GETSTATIC io/quarkus/runner/ApplicationImpl1#STARTUP_CONTEXT
// Method descriptor: ()V
INVOKEVIRTUAL io/quarkus/runtime/StartupContext#close
RETURN
** label2
}
// Access: public static
Method <clinit> : V
(
// (no arguments)
) {
** label1
LDC (String) "io.netty.allocator.maxOrder"
LDC (String) "1"
// Method descriptor: (Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
INVOKESTATIC java/lang/System#setProperty
POP
LDC (String) "java.util.logging.manager"
LDC (String) "org.jboss.logmanager.LogManager"
// Method descriptor: (Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
INVOKESTATIC java/lang/System#setProperty
POP
// Method descriptor: ()V
INVOKESTATIC io/quarkus/runtime/Timing#staticInitStarted
NEW io/quarkus/runtime/StartupContext
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/runtime/StartupContext#<init>
ASTORE 0
ALOAD 0
// Field descriptor: Lio/quarkus/runtime/StartupContext;
PUTSTATIC io/quarkus/runner/ApplicationImpl1#STARTUP_CONTEXT
** label2
NEW io/quarkus/deployment/steps/LoggingResourceProcessor$setupLoggingStaticInit3
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/deployment/steps/LoggingResourceProcessor$setupLoggingStaticInit3#<init>
CHECKCAST io/quarkus/runtime/StartupTask
ALOAD 0
// Method descriptor: (Lio/quarkus/runtime/StartupContext;)V
INVOKEINTERFACE io/quarkus/runtime/StartupTask#deploy
NEW io/quarkus/deployment/steps/RestClientProcessor$setup10
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/deployment/steps/RestClientProcessor$setup10#<init>
CHECKCAST io/quarkus/runtime/StartupTask
ALOAD 0
// Method descriptor: (Lio/quarkus/runtime/StartupContext;)V
INVOKEINTERFACE io/quarkus/runtime/StartupTask#deploy
NEW io/quarkus/deployment/steps/VertxCoreProcessor$ioThreadDetector9
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/deployment/steps/VertxCoreProcessor$ioThreadDetector9#<init>
CHECKCAST io/quarkus/runtime/StartupTask
ALOAD 0
// Method descriptor: (Lio/quarkus/runtime/StartupContext;)V
INVOKEINTERFACE io/quarkus/runtime/StartupTask#deploy
NEW io/quarkus/deployment/steps/NettyProcessor$createExecutors2
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/deployment/steps/NettyProcessor$createExecutors2#<init>
CHECKCAST io/quarkus/runtime/StartupTask
ALOAD 0
// Method descriptor: (Lio/quarkus/runtime/StartupContext;)V
INVOKEINTERFACE io/quarkus/runtime/StartupTask#deploy
NEW io/quarkus/deployment/steps/BlockingOperationControlBuildStep$blockingOP11
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/deployment/steps/BlockingOperationControlBuildStep$blockingOP11#<init>
CHECKCAST io/quarkus/runtime/StartupTask
ALOAD 0
// Method descriptor: (Lio/quarkus/runtime/StartupContext;)V
INVOKEINTERFACE io/quarkus/runtime/StartupTask#deploy
NEW io/quarkus/deployment/steps/SubstrateConfigBuildStep$build15
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/deployment/steps/SubstrateConfigBuildStep$build15#<init>
CHECKCAST io/quarkus/runtime/StartupTask
ALOAD 0
// Method descriptor: (Lio/quarkus/runtime/StartupContext;)V
INVOKEINTERFACE io/quarkus/runtime/StartupTask#deploy
NEW io/quarkus/deployment/steps/SubstrateSystemPropertiesBuildStep$writeNativeProps16
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/deployment/steps/SubstrateSystemPropertiesBuildStep$writeNativeProps16#<init>
CHECKCAST io/quarkus/runtime/StartupTask
ALOAD 0
// Method descriptor: (Lio/quarkus/runtime/StartupContext;)V
INVOKEINTERFACE io/quarkus/runtime/StartupTask#deploy
NEW io/quarkus/deployment/steps/UndertowBuildStep$servletContextBean13
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/deployment/steps/UndertowBuildStep$servletContextBean13#<init>
CHECKCAST io/quarkus/runtime/StartupTask
ALOAD 0
// Method descriptor: (Lio/quarkus/runtime/StartupContext;)V
INVOKEINTERFACE io/quarkus/runtime/StartupTask#deploy
NEW io/quarkus/deployment/steps/RuntimeBeanProcessor$build17
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/deployment/steps/RuntimeBeanProcessor$build17#<init>
CHECKCAST io/quarkus/runtime/StartupTask
ALOAD 0
// Method descriptor: (Lio/quarkus/runtime/StartupContext;)V
INVOKEINTERFACE io/quarkus/runtime/StartupTask#deploy
NEW io/quarkus/deployment/steps/RestClientProcessor$registerProviders18
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/deployment/steps/RestClientProcessor$registerProviders18#<init>
CHECKCAST io/quarkus/runtime/StartupTask
ALOAD 0
// Method descriptor: (Lio/quarkus/runtime/StartupContext;)V
INVOKEINTERFACE io/quarkus/runtime/StartupTask#deploy
NEW io/quarkus/deployment/steps/ArcProcessor$generateResources19
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/deployment/steps/ArcProcessor$generateResources19#<init>
CHECKCAST io/quarkus/runtime/StartupTask
ALOAD 0
// Method descriptor: (Lio/quarkus/runtime/StartupContext;)V
INVOKEINTERFACE io/quarkus/runtime/StartupTask#deploy
NEW io/quarkus/deployment/steps/ResteasyServerCommonProcessor$setupInjection23
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/deployment/steps/ResteasyServerCommonProcessor$setupInjection23#<init>
CHECKCAST io/quarkus/runtime/StartupTask
ALOAD 0
// Method descriptor: (Lio/quarkus/runtime/StartupContext;)V
INVOKEINTERFACE io/quarkus/runtime/StartupTask#deploy
NEW io/quarkus/deployment/steps/UndertowArcIntegrationBuildStep$integrateRequestContext20
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/deployment/steps/UndertowArcIntegrationBuildStep$integrateRequestContext20#<init>
CHECKCAST io/quarkus/runtime/StartupTask
ALOAD 0
// Method descriptor: (Lio/quarkus/runtime/StartupContext;)V
INVOKEINTERFACE io/quarkus/runtime/StartupTask#deploy
NEW io/quarkus/deployment/steps/UndertowBuildStep$build24
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/deployment/steps/UndertowBuildStep$build24#<init>
CHECKCAST io/quarkus/runtime/StartupTask
ALOAD 0
// Method descriptor: (Lio/quarkus/runtime/StartupContext;)V
INVOKEINTERFACE io/quarkus/runtime/StartupTask#deploy
RETURN
** label3
GOTO label4
** label5
ASTORE 1
ALOAD 0
// Method descriptor: ()V
INVOKEVIRTUAL io/quarkus/runtime/StartupContext#close
NEW java/lang/RuntimeException
DUP
LDC (String) "Failed to start quarkus"
ALOAD 1
// Method descriptor: (Ljava/lang/String;Ljava/lang/Throwable;)V
INVOKESPECIAL java/lang/RuntimeException#<init>
CHECKCAST java/lang/Throwable
ATHROW
** label6
GOTO label4
// Try from label2 to label3
// Catch java/lang/Throwable by going to label5
** label4
** label7
}
|
localproxyservice/target/generated-sources/gizmo/io/quarkus/runner/ApplicationImpl1.zig
|
pub const FXEQ_MIN_FRAMERATE = @as(u32, 22000);
pub const FXEQ_MAX_FRAMERATE = @as(u32, 48000);
pub const FXEQ_MIN_FREQUENCY_CENTER = @as(f32, 20);
pub const FXEQ_MAX_FREQUENCY_CENTER = @as(f32, 20000);
pub const FXEQ_DEFAULT_FREQUENCY_CENTER_0 = @as(f32, 100);
pub const FXEQ_DEFAULT_FREQUENCY_CENTER_1 = @as(f32, 800);
pub const FXEQ_DEFAULT_FREQUENCY_CENTER_2 = @as(f32, 2000);
pub const FXEQ_DEFAULT_FREQUENCY_CENTER_3 = @as(f32, 10000);
pub const FXEQ_MIN_GAIN = @as(f32, 1.26e-01);
pub const FXEQ_MAX_GAIN = @as(f32, 7.94e+00);
pub const FXEQ_DEFAULT_GAIN = @as(f32, 1);
pub const FXEQ_MIN_BANDWIDTH = @as(f32, 1.0e-01);
pub const FXEQ_MAX_BANDWIDTH = @as(f32, 2);
pub const FXEQ_DEFAULT_BANDWIDTH = @as(f32, 1);
pub const FXMASTERINGLIMITER_MIN_RELEASE = @as(u32, 1);
pub const FXMASTERINGLIMITER_MAX_RELEASE = @as(u32, 20);
pub const FXMASTERINGLIMITER_DEFAULT_RELEASE = @as(u32, 6);
pub const FXMASTERINGLIMITER_MIN_LOUDNESS = @as(u32, 1);
pub const FXMASTERINGLIMITER_MAX_LOUDNESS = @as(u32, 1800);
pub const FXMASTERINGLIMITER_DEFAULT_LOUDNESS = @as(u32, 1000);
pub const FXREVERB_MIN_DIFFUSION = @as(f32, 0);
pub const FXREVERB_MAX_DIFFUSION = @as(f32, 1);
pub const FXREVERB_DEFAULT_DIFFUSION = @as(f32, 9.0e-01);
pub const FXREVERB_MIN_ROOMSIZE = @as(f32, 1.0e-04);
pub const FXREVERB_MAX_ROOMSIZE = @as(f32, 1);
pub const FXREVERB_DEFAULT_ROOMSIZE = @as(f32, 6.0e-01);
pub const FXLOUDNESS_DEFAULT_MOMENTARY_MS = @as(u32, 400);
pub const FXLOUDNESS_DEFAULT_SHORTTERM_MS = @as(u32, 3000);
pub const FXECHO_MIN_WETDRYMIX = @as(f32, 0);
pub const FXECHO_MAX_WETDRYMIX = @as(f32, 1);
pub const FXECHO_DEFAULT_WETDRYMIX = @as(f32, 5.0e-01);
pub const FXECHO_MIN_FEEDBACK = @as(f32, 0);
pub const FXECHO_MAX_FEEDBACK = @as(f32, 1);
pub const FXECHO_DEFAULT_FEEDBACK = @as(f32, 5.0e-01);
pub const FXECHO_MIN_DELAY = @as(f32, 1);
pub const FXECHO_MAX_DELAY = @as(f32, 2000);
pub const FXECHO_DEFAULT_DELAY = @as(f32, 500);
pub const XAUDIO2_MAX_BUFFER_BYTES = @as(u32, 2147483648);
pub const XAUDIO2_MAX_QUEUED_BUFFERS = @as(u32, 64);
pub const XAUDIO2_MAX_BUFFERS_SYSTEM = @as(u32, 2);
pub const XAUDIO2_MAX_AUDIO_CHANNELS = @as(u32, 64);
pub const XAUDIO2_MIN_SAMPLE_RATE = @as(u32, 1000);
pub const XAUDIO2_MAX_SAMPLE_RATE = @as(u32, 200000);
pub const XAUDIO2_MAX_VOLUME_LEVEL = @as(f32, 16777216);
pub const XAUDIO2_MAX_FREQ_RATIO = @as(f32, 1024);
pub const XAUDIO2_DEFAULT_FREQ_RATIO = @as(f32, 2);
pub const XAUDIO2_MAX_FILTER_ONEOVERQ = @as(f32, 1.5e+00);
pub const XAUDIO2_MAX_FILTER_FREQUENCY = @as(f32, 1);
pub const XAUDIO2_MAX_LOOP_COUNT = @as(u32, 254);
pub const XAUDIO2_MAX_INSTANCES = @as(u32, 8);
pub const XAUDIO2_MAX_RATIO_TIMES_RATE_XMA_MONO = @as(u32, 600000);
pub const XAUDIO2_MAX_RATIO_TIMES_RATE_XMA_MULTICHANNEL = @as(u32, 300000);
pub const XAUDIO2_COMMIT_NOW = @as(u32, 0);
pub const XAUDIO2_COMMIT_ALL = @as(u32, 0);
pub const XAUDIO2_NO_LOOP_REGION = @as(u32, 0);
pub const XAUDIO2_LOOP_INFINITE = @as(u32, 255);
pub const XAUDIO2_DEFAULT_CHANNELS = @as(u32, 0);
pub const XAUDIO2_DEFAULT_SAMPLERATE = @as(u32, 0);
pub const XAUDIO2_DEBUG_ENGINE = @as(u32, 1);
pub const XAUDIO2_VOICE_NOPITCH = @as(u32, 2);
pub const XAUDIO2_VOICE_NOSRC = @as(u32, 4);
pub const XAUDIO2_VOICE_USEFILTER = @as(u32, 8);
pub const XAUDIO2_PLAY_TAILS = @as(u32, 32);
pub const XAUDIO2_END_OF_STREAM = @as(u32, 64);
pub const XAUDIO2_SEND_USEFILTER = @as(u32, 128);
pub const XAUDIO2_VOICE_NOSAMPLESPLAYED = @as(u32, 256);
pub const XAUDIO2_STOP_ENGINE_WHEN_IDLE = @as(u32, 8192);
pub const XAUDIO2_1024_QUANTUM = @as(u32, 32768);
pub const XAUDIO2_NO_VIRTUAL_AUDIO_CLIENT = @as(u32, 65536);
pub const XAUDIO2_DEFAULT_FILTER_FREQUENCY = @as(f32, 1);
pub const XAUDIO2_DEFAULT_FILTER_ONEOVERQ = @as(f32, 1);
pub const XAUDIO2_QUANTUM_NUMERATOR = @as(u32, 1);
pub const XAUDIO2_QUANTUM_DENOMINATOR = @as(u32, 100);
pub const FACILITY_XAUDIO2 = @as(u32, 2198);
pub const XAUDIO2_E_INVALID_CALL = @import("../../zig.zig").typedConst(HRESULT, @as(i32, -2003435519));
pub const XAUDIO2_E_XMA_DECODER_ERROR = @import("../../zig.zig").typedConst(HRESULT, @as(i32, -2003435518));
pub const XAUDIO2_E_XAPO_CREATION_FAILED = @import("../../zig.zig").typedConst(HRESULT, @as(i32, -2003435517));
pub const XAUDIO2_E_DEVICE_INVALIDATED = @import("../../zig.zig").typedConst(HRESULT, @as(i32, -2003435516));
pub const Processor1 = @as(u32, 1);
pub const Processor2 = @as(u32, 2);
pub const Processor3 = @as(u32, 4);
pub const Processor4 = @as(u32, 8);
pub const Processor5 = @as(u32, 16);
pub const Processor6 = @as(u32, 32);
pub const Processor7 = @as(u32, 64);
pub const Processor8 = @as(u32, 128);
pub const Processor9 = @as(u32, 256);
pub const Processor10 = @as(u32, 512);
pub const Processor11 = @as(u32, 1024);
pub const Processor12 = @as(u32, 2048);
pub const Processor13 = @as(u32, 4096);
pub const Processor14 = @as(u32, 8192);
pub const Processor15 = @as(u32, 16384);
pub const Processor16 = @as(u32, 32768);
pub const Processor17 = @as(u32, 65536);
pub const Processor18 = @as(u32, 131072);
pub const Processor19 = @as(u32, 262144);
pub const Processor20 = @as(u32, 524288);
pub const Processor21 = @as(u32, 1048576);
pub const Processor22 = @as(u32, 2097152);
pub const Processor23 = @as(u32, 4194304);
pub const Processor24 = @as(u32, 8388608);
pub const Processor25 = @as(u32, 16777216);
pub const Processor26 = @as(u32, 33554432);
pub const Processor27 = @as(u32, 67108864);
pub const Processor28 = @as(u32, 134217728);
pub const Processor29 = @as(u32, 268435456);
pub const Processor30 = @as(u32, 536870912);
pub const Processor31 = @as(u32, 1073741824);
pub const Processor32 = @as(u32, 2147483648);
pub const XAUDIO2_ANY_PROCESSOR = @as(u32, 4294967295);
pub const XAUDIO2_USE_DEFAULT_PROCESSOR = @as(u32, 0);
pub const XAUDIO2_DEFAULT_PROCESSOR = @as(u32, 1);
pub const XAUDIO2_LOG_ERRORS = @as(u32, 1);
pub const XAUDIO2_LOG_WARNINGS = @as(u32, 2);
pub const XAUDIO2_LOG_INFO = @as(u32, 4);
pub const XAUDIO2_LOG_DETAIL = @as(u32, 8);
pub const XAUDIO2_LOG_API_CALLS = @as(u32, 16);
pub const XAUDIO2_LOG_FUNC_CALLS = @as(u32, 32);
pub const XAUDIO2_LOG_TIMING = @as(u32, 64);
pub const XAUDIO2_LOG_LOCKS = @as(u32, 128);
pub const XAUDIO2_LOG_MEMORY = @as(u32, 256);
pub const XAUDIO2_LOG_STREAMING = @as(u32, 4096);
pub const XAUDIO2FX_REVERB_MIN_FRAMERATE = @as(u32, 20000);
pub const XAUDIO2FX_REVERB_MAX_FRAMERATE = @as(u32, 48000);
pub const XAUDIO2FX_REVERB_MIN_WET_DRY_MIX = @as(f32, 0);
pub const XAUDIO2FX_REVERB_MIN_REFLECTIONS_DELAY = @as(u32, 0);
pub const XAUDIO2FX_REVERB_MIN_REVERB_DELAY = @as(u32, 0);
pub const XAUDIO2FX_REVERB_MIN_REAR_DELAY = @as(u32, 0);
pub const XAUDIO2FX_REVERB_MIN_7POINT1_SIDE_DELAY = @as(u32, 0);
pub const XAUDIO2FX_REVERB_MIN_7POINT1_REAR_DELAY = @as(u32, 0);
pub const XAUDIO2FX_REVERB_MIN_POSITION = @as(u32, 0);
pub const XAUDIO2FX_REVERB_MIN_DIFFUSION = @as(u32, 0);
pub const XAUDIO2FX_REVERB_MIN_LOW_EQ_GAIN = @as(u32, 0);
pub const XAUDIO2FX_REVERB_MIN_LOW_EQ_CUTOFF = @as(u32, 0);
pub const XAUDIO2FX_REVERB_MIN_HIGH_EQ_GAIN = @as(u32, 0);
pub const XAUDIO2FX_REVERB_MIN_HIGH_EQ_CUTOFF = @as(u32, 0);
pub const XAUDIO2FX_REVERB_MIN_ROOM_FILTER_FREQ = @as(f32, 20);
pub const XAUDIO2FX_REVERB_MIN_ROOM_FILTER_MAIN = @as(f32, -100);
pub const XAUDIO2FX_REVERB_MIN_ROOM_FILTER_HF = @as(f32, -100);
pub const XAUDIO2FX_REVERB_MIN_REFLECTIONS_GAIN = @as(f32, -100);
pub const XAUDIO2FX_REVERB_MIN_REVERB_GAIN = @as(f32, -100);
pub const XAUDIO2FX_REVERB_MIN_DECAY_TIME = @as(f32, 1.0e-01);
pub const XAUDIO2FX_REVERB_MIN_DENSITY = @as(f32, 0);
pub const XAUDIO2FX_REVERB_MIN_ROOM_SIZE = @as(f32, 0);
pub const XAUDIO2FX_REVERB_MAX_WET_DRY_MIX = @as(f32, 100);
pub const XAUDIO2FX_REVERB_MAX_REFLECTIONS_DELAY = @as(u32, 300);
pub const XAUDIO2FX_REVERB_MAX_REVERB_DELAY = @as(u32, 85);
pub const XAUDIO2FX_REVERB_MAX_REAR_DELAY = @as(u32, 5);
pub const XAUDIO2FX_REVERB_MAX_7POINT1_SIDE_DELAY = @as(u32, 5);
pub const XAUDIO2FX_REVERB_MAX_7POINT1_REAR_DELAY = @as(u32, 20);
pub const XAUDIO2FX_REVERB_MAX_POSITION = @as(u32, 30);
pub const XAUDIO2FX_REVERB_MAX_DIFFUSION = @as(u32, 15);
pub const XAUDIO2FX_REVERB_MAX_LOW_EQ_GAIN = @as(u32, 12);
pub const XAUDIO2FX_REVERB_MAX_LOW_EQ_CUTOFF = @as(u32, 9);
pub const XAUDIO2FX_REVERB_MAX_HIGH_EQ_GAIN = @as(u32, 8);
pub const XAUDIO2FX_REVERB_MAX_HIGH_EQ_CUTOFF = @as(u32, 14);
pub const XAUDIO2FX_REVERB_MAX_ROOM_FILTER_FREQ = @as(f32, 20000);
pub const XAUDIO2FX_REVERB_MAX_ROOM_FILTER_MAIN = @as(f32, 0);
pub const XAUDIO2FX_REVERB_MAX_ROOM_FILTER_HF = @as(f32, 0);
pub const XAUDIO2FX_REVERB_MAX_REFLECTIONS_GAIN = @as(f32, 20);
pub const XAUDIO2FX_REVERB_MAX_REVERB_GAIN = @as(f32, 20);
pub const XAUDIO2FX_REVERB_MAX_DENSITY = @as(f32, 100);
pub const XAUDIO2FX_REVERB_MAX_ROOM_SIZE = @as(f32, 100);
pub const XAUDIO2FX_REVERB_DEFAULT_WET_DRY_MIX = @as(f32, 100);
pub const XAUDIO2FX_REVERB_DEFAULT_REFLECTIONS_DELAY = @as(u32, 5);
pub const XAUDIO2FX_REVERB_DEFAULT_REVERB_DELAY = @as(u32, 5);
pub const XAUDIO2FX_REVERB_DEFAULT_REAR_DELAY = @as(u32, 5);
pub const XAUDIO2FX_REVERB_DEFAULT_7POINT1_SIDE_DELAY = @as(u32, 5);
pub const XAUDIO2FX_REVERB_DEFAULT_7POINT1_REAR_DELAY = @as(u32, 20);
pub const XAUDIO2FX_REVERB_DEFAULT_POSITION = @as(u32, 6);
pub const XAUDIO2FX_REVERB_DEFAULT_POSITION_MATRIX = @as(u32, 27);
pub const XAUDIO2FX_REVERB_DEFAULT_EARLY_DIFFUSION = @as(u32, 8);
pub const XAUDIO2FX_REVERB_DEFAULT_LATE_DIFFUSION = @as(u32, 8);
pub const XAUDIO2FX_REVERB_DEFAULT_LOW_EQ_GAIN = @as(u32, 8);
pub const XAUDIO2FX_REVERB_DEFAULT_LOW_EQ_CUTOFF = @as(u32, 4);
pub const XAUDIO2FX_REVERB_DEFAULT_HIGH_EQ_GAIN = @as(u32, 8);
pub const XAUDIO2FX_REVERB_DEFAULT_HIGH_EQ_CUTOFF = @as(u32, 4);
pub const XAUDIO2FX_REVERB_DEFAULT_ROOM_FILTER_FREQ = @as(f32, 5000);
pub const XAUDIO2FX_REVERB_DEFAULT_ROOM_FILTER_MAIN = @as(f32, 0);
pub const XAUDIO2FX_REVERB_DEFAULT_ROOM_FILTER_HF = @as(f32, 0);
pub const XAUDIO2FX_REVERB_DEFAULT_REFLECTIONS_GAIN = @as(f32, 0);
pub const XAUDIO2FX_REVERB_DEFAULT_REVERB_GAIN = @as(f32, 0);
pub const XAUDIO2FX_REVERB_DEFAULT_DECAY_TIME = @as(f32, 1);
pub const XAUDIO2FX_REVERB_DEFAULT_DENSITY = @as(f32, 100);
pub const XAUDIO2FX_REVERB_DEFAULT_ROOM_SIZE = @as(f32, 100);
pub const XAUDIO2FX_REVERB_DEFAULT_DISABLE_LATE_FIELD = @as(u32, 0);
pub const HRTF_MAX_GAIN_LIMIT = @as(f32, 12);
pub const HRTF_MIN_GAIN_LIMIT = @as(f32, -96);
pub const HRTF_MIN_UNITY_GAIN_DISTANCE = @as(f32, 5.0e-02);
pub const HRTF_DEFAULT_UNITY_GAIN_DISTANCE = @as(f32, 1);
pub const FACILITY_XAPO = @as(u32, 2199);
pub const XAPO_E_FORMAT_UNSUPPORTED = @import("../../zig.zig").typedConst(HRESULT, @as(i32, -2003369983));
pub const XAPO_MIN_CHANNELS = @as(u32, 1);
pub const XAPO_MAX_CHANNELS = @as(u32, 64);
pub const XAPO_MIN_FRAMERATE = @as(u32, 1000);
pub const XAPO_MAX_FRAMERATE = @as(u32, 200000);
pub const XAPO_REGISTRATION_STRING_LENGTH = @as(u32, 256);
pub const XAPO_FLAG_CHANNELS_MUST_MATCH = @as(u32, 1);
pub const XAPO_FLAG_FRAMERATE_MUST_MATCH = @as(u32, 2);
pub const XAPO_FLAG_BITSPERSAMPLE_MUST_MATCH = @as(u32, 4);
pub const XAPO_FLAG_BUFFERCOUNT_MUST_MATCH = @as(u32, 8);
pub const XAPO_FLAG_INPLACE_REQUIRED = @as(u32, 32);
pub const XAPO_FLAG_INPLACE_SUPPORTED = @as(u32, 16);
pub const SPEAKER_MONO = @as(u32, 4);
pub const X3DAUDIO_HANDLE_BYTESIZE = @as(u32, 20);
pub const X3DAUDIO_PI = @as(f32, 3.1415927e+00);
pub const X3DAUDIO_2PI = @as(f32, 6.2831855e+00);
pub const X3DAUDIO_SPEED_OF_SOUND = @as(f32, 3.435e+02);
pub const X3DAUDIO_CALCULATE_MATRIX = @as(u32, 1);
pub const X3DAUDIO_CALCULATE_DELAY = @as(u32, 2);
pub const X3DAUDIO_CALCULATE_LPF_DIRECT = @as(u32, 4);
pub const X3DAUDIO_CALCULATE_LPF_REVERB = @as(u32, 8);
pub const X3DAUDIO_CALCULATE_REVERB = @as(u32, 16);
pub const X3DAUDIO_CALCULATE_DOPPLER = @as(u32, 32);
pub const X3DAUDIO_CALCULATE_EMITTER_ANGLE = @as(u32, 64);
pub const X3DAUDIO_CALCULATE_ZEROCENTER = @as(u32, 65536);
pub const X3DAUDIO_CALCULATE_REDIRECT_TO_LFE = @as(u32, 131072);
//--------------------------------------------------------------------------------
// Section: Types (51)
//--------------------------------------------------------------------------------
pub const XAPO_REGISTRATION_PROPERTIES = packed struct {
clsid: Guid,
FriendlyName: [256]u16,
CopyrightInfo: [256]u16,
MajorVersion: u32,
MinorVersion: u32,
Flags: u32,
MinInputBufferCount: u32,
MaxInputBufferCount: u32,
MinOutputBufferCount: u32,
MaxOutputBufferCount: u32,
};
pub const XAPO_LOCKFORPROCESS_PARAMETERS = packed struct {
pFormat: ?*const WAVEFORMATEX,
MaxFrameCount: u32,
};
pub const XAPO_BUFFER_FLAGS = enum(i32) {
SILENT = 0,
VALID = 1,
};
pub const XAPO_BUFFER_SILENT = XAPO_BUFFER_FLAGS.SILENT;
pub const XAPO_BUFFER_VALID = XAPO_BUFFER_FLAGS.VALID;
pub const XAPO_PROCESS_BUFFER_PARAMETERS = packed struct {
pBuffer: ?*anyopaque,
BufferFlags: XAPO_BUFFER_FLAGS,
ValidFrameCount: u32,
};
const IID_IXAPO_Value = @import("../../zig.zig").Guid.initString("a410b984-9839-4819-a0be-2856ae6b3adb");
pub const IID_IXAPO = &IID_IXAPO_Value;
pub const IXAPO = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetRegistrationProperties: fn(
self: *const IXAPO,
ppRegistrationProperties: ?*?*XAPO_REGISTRATION_PROPERTIES,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsInputFormatSupported: fn(
self: *const IXAPO,
pOutputFormat: ?*const WAVEFORMATEX,
pRequestedInputFormat: ?*const WAVEFORMATEX,
ppSupportedInputFormat: ?*?*WAVEFORMATEX,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsOutputFormatSupported: fn(
self: *const IXAPO,
pInputFormat: ?*const WAVEFORMATEX,
pRequestedOutputFormat: ?*const WAVEFORMATEX,
ppSupportedOutputFormat: ?*?*WAVEFORMATEX,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Initialize: fn(
self: *const IXAPO,
// TODO: what to do with BytesParamIndex 1?
pData: ?*const anyopaque,
DataByteSize: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reset: fn(
self: *const IXAPO,
) callconv(@import("std").os.windows.WINAPI) void,
LockForProcess: fn(
self: *const IXAPO,
InputLockedParameterCount: u32,
pInputLockedParameters: ?[*]const XAPO_LOCKFORPROCESS_PARAMETERS,
OutputLockedParameterCount: u32,
pOutputLockedParameters: ?[*]const XAPO_LOCKFORPROCESS_PARAMETERS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UnlockForProcess: fn(
self: *const IXAPO,
) callconv(@import("std").os.windows.WINAPI) void,
Process: fn(
self: *const IXAPO,
InputProcessParameterCount: u32,
pInputProcessParameters: ?[*]const XAPO_PROCESS_BUFFER_PARAMETERS,
OutputProcessParameterCount: u32,
pOutputProcessParameters: ?[*]XAPO_PROCESS_BUFFER_PARAMETERS,
IsEnabled: BOOL,
) callconv(@import("std").os.windows.WINAPI) void,
CalcInputFrames: fn(
self: *const IXAPO,
OutputFrameCount: u32,
) callconv(@import("std").os.windows.WINAPI) u32,
CalcOutputFrames: fn(
self: *const IXAPO,
InputFrameCount: u32,
) callconv(@import("std").os.windows.WINAPI) u32,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAPO_GetRegistrationProperties(self: *const T, ppRegistrationProperties: ?*?*XAPO_REGISTRATION_PROPERTIES) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAPO.VTable, self.vtable).GetRegistrationProperties(@ptrCast(*const IXAPO, self), ppRegistrationProperties);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAPO_IsInputFormatSupported(self: *const T, pOutputFormat: ?*const WAVEFORMATEX, pRequestedInputFormat: ?*const WAVEFORMATEX, ppSupportedInputFormat: ?*?*WAVEFORMATEX) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAPO.VTable, self.vtable).IsInputFormatSupported(@ptrCast(*const IXAPO, self), pOutputFormat, pRequestedInputFormat, ppSupportedInputFormat);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAPO_IsOutputFormatSupported(self: *const T, pInputFormat: ?*const WAVEFORMATEX, pRequestedOutputFormat: ?*const WAVEFORMATEX, ppSupportedOutputFormat: ?*?*WAVEFORMATEX) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAPO.VTable, self.vtable).IsOutputFormatSupported(@ptrCast(*const IXAPO, self), pInputFormat, pRequestedOutputFormat, ppSupportedOutputFormat);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAPO_Initialize(self: *const T, pData: ?*const anyopaque, DataByteSize: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAPO.VTable, self.vtable).Initialize(@ptrCast(*const IXAPO, self), pData, DataByteSize);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAPO_Reset(self: *const T) callconv(.Inline) void {
return @ptrCast(*const IXAPO.VTable, self.vtable).Reset(@ptrCast(*const IXAPO, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAPO_LockForProcess(self: *const T, InputLockedParameterCount: u32, pInputLockedParameters: ?[*]const XAPO_LOCKFORPROCESS_PARAMETERS, OutputLockedParameterCount: u32, pOutputLockedParameters: ?[*]const XAPO_LOCKFORPROCESS_PARAMETERS) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAPO.VTable, self.vtable).LockForProcess(@ptrCast(*const IXAPO, self), InputLockedParameterCount, pInputLockedParameters, OutputLockedParameterCount, pOutputLockedParameters);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAPO_UnlockForProcess(self: *const T) callconv(.Inline) void {
return @ptrCast(*const IXAPO.VTable, self.vtable).UnlockForProcess(@ptrCast(*const IXAPO, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAPO_Process(self: *const T, InputProcessParameterCount: u32, pInputProcessParameters: ?[*]const XAPO_PROCESS_BUFFER_PARAMETERS, OutputProcessParameterCount: u32, pOutputProcessParameters: ?[*]XAPO_PROCESS_BUFFER_PARAMETERS, IsEnabled: BOOL) callconv(.Inline) void {
return @ptrCast(*const IXAPO.VTable, self.vtable).Process(@ptrCast(*const IXAPO, self), InputProcessParameterCount, pInputProcessParameters, OutputProcessParameterCount, pOutputProcessParameters, IsEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAPO_CalcInputFrames(self: *const T, OutputFrameCount: u32) callconv(.Inline) u32 {
return @ptrCast(*const IXAPO.VTable, self.vtable).CalcInputFrames(@ptrCast(*const IXAPO, self), OutputFrameCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAPO_CalcOutputFrames(self: *const T, InputFrameCount: u32) callconv(.Inline) u32 {
return @ptrCast(*const IXAPO.VTable, self.vtable).CalcOutputFrames(@ptrCast(*const IXAPO, self), InputFrameCount);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXAPOParameters_Value = @import("../../zig.zig").Guid.initString("26d95c66-80f2-499a-ad54-5ae7f01c6d98");
pub const IID_IXAPOParameters = &IID_IXAPOParameters_Value;
pub const IXAPOParameters = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetParameters: fn(
self: *const IXAPOParameters,
// TODO: what to do with BytesParamIndex 1?
pParameters: ?*const anyopaque,
ParameterByteSize: u32,
) callconv(@import("std").os.windows.WINAPI) void,
GetParameters: fn(
self: *const IXAPOParameters,
// TODO: what to do with BytesParamIndex 1?
pParameters: ?*anyopaque,
ParameterByteSize: u32,
) callconv(@import("std").os.windows.WINAPI) void,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAPOParameters_SetParameters(self: *const T, pParameters: ?*const anyopaque, ParameterByteSize: u32) callconv(.Inline) void {
return @ptrCast(*const IXAPOParameters.VTable, self.vtable).SetParameters(@ptrCast(*const IXAPOParameters, self), pParameters, ParameterByteSize);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAPOParameters_GetParameters(self: *const T, pParameters: ?*anyopaque, ParameterByteSize: u32) callconv(.Inline) void {
return @ptrCast(*const IXAPOParameters.VTable, self.vtable).GetParameters(@ptrCast(*const IXAPOParameters, self), pParameters, ParameterByteSize);
}
};}
pub usingnamespace MethodMixin(@This());
};
const CLSID_FXEQ_Value = @import("../../zig.zig").Guid.initString("f5e01117-d6c4-485a-a3f5-695196f3dbfa");
pub const CLSID_FXEQ = &CLSID_FXEQ_Value;
const CLSID_FXMasteringLimiter_Value = @import("../../zig.zig").Guid.initString("c4137916-2be1-46fd-8599-441536f49856");
pub const CLSID_FXMasteringLimiter = &CLSID_FXMasteringLimiter_Value;
const CLSID_FXReverb_Value = @import("../../zig.zig").Guid.initString("7d9aca56-cb68-4807-b632-b137352e8596");
pub const CLSID_FXReverb = &CLSID_FXReverb_Value;
const CLSID_FXEcho_Value = @import("../../zig.zig").Guid.initString("5039d740-f736-449a-84d3-a56202557b87");
pub const CLSID_FXEcho = &CLSID_FXEcho_Value;
pub const FXEQ_PARAMETERS = packed struct {
FrequencyCenter0: f32,
Gain0: f32,
Bandwidth0: f32,
FrequencyCenter1: f32,
Gain1: f32,
Bandwidth1: f32,
FrequencyCenter2: f32,
Gain2: f32,
Bandwidth2: f32,
FrequencyCenter3: f32,
Gain3: f32,
Bandwidth3: f32,
};
pub const FXMASTERINGLIMITER_PARAMETERS = packed struct {
Release: u32,
Loudness: u32,
};
pub const FXREVERB_PARAMETERS = packed struct {
Diffusion: f32,
RoomSize: f32,
};
pub const FXECHO_INITDATA = packed struct {
MaxDelay: f32,
};
pub const FXECHO_PARAMETERS = packed struct {
WetDryMix: f32,
Feedback: f32,
Delay: f32,
};
pub const XAUDIO2_VOICE_DETAILS = packed struct {
CreationFlags: u32,
ActiveFlags: u32,
InputChannels: u32,
InputSampleRate: u32,
};
pub const XAUDIO2_SEND_DESCRIPTOR = packed struct {
Flags: u32,
pOutputVoice: ?*IXAudio2Voice,
};
pub const XAUDIO2_VOICE_SENDS = packed struct {
SendCount: u32,
pSends: ?*XAUDIO2_SEND_DESCRIPTOR,
};
pub const XAUDIO2_EFFECT_DESCRIPTOR = packed struct {
pEffect: ?*IUnknown,
InitialState: BOOL,
OutputChannels: u32,
};
pub const XAUDIO2_EFFECT_CHAIN = packed struct {
EffectCount: u32,
pEffectDescriptors: ?*XAUDIO2_EFFECT_DESCRIPTOR,
};
pub const XAUDIO2_FILTER_TYPE = enum(i32) {
LowPassFilter = 0,
BandPassFilter = 1,
HighPassFilter = 2,
NotchFilter = 3,
LowPassOnePoleFilter = 4,
HighPassOnePoleFilter = 5,
};
pub const LowPassFilter = XAUDIO2_FILTER_TYPE.LowPassFilter;
pub const BandPassFilter = XAUDIO2_FILTER_TYPE.BandPassFilter;
pub const HighPassFilter = XAUDIO2_FILTER_TYPE.HighPassFilter;
pub const NotchFilter = XAUDIO2_FILTER_TYPE.NotchFilter;
pub const LowPassOnePoleFilter = XAUDIO2_FILTER_TYPE.LowPassOnePoleFilter;
pub const HighPassOnePoleFilter = XAUDIO2_FILTER_TYPE.HighPassOnePoleFilter;
pub const XAUDIO2_FILTER_PARAMETERS = packed struct {
Type: XAUDIO2_FILTER_TYPE,
Frequency: f32,
OneOverQ: f32,
};
pub const XAUDIO2_BUFFER = packed struct {
Flags: u32,
AudioBytes: u32,
pAudioData: ?*const u8,
PlayBegin: u32,
PlayLength: u32,
LoopBegin: u32,
LoopLength: u32,
LoopCount: u32,
pContext: ?*anyopaque,
};
pub const XAUDIO2_BUFFER_WMA = packed struct {
pDecodedPacketCumulativeBytes: ?*const u32,
PacketCount: u32,
};
pub const XAUDIO2_VOICE_STATE = packed struct {
pCurrentBufferContext: ?*anyopaque,
BuffersQueued: u32,
SamplesPlayed: u64,
};
pub const XAUDIO2_PERFORMANCE_DATA = packed struct {
AudioCyclesSinceLastQuery: u64,
TotalCyclesSinceLastQuery: u64,
MinimumCyclesPerQuantum: u32,
MaximumCyclesPerQuantum: u32,
MemoryUsageInBytes: u32,
CurrentLatencyInSamples: u32,
GlitchesSinceEngineStarted: u32,
ActiveSourceVoiceCount: u32,
TotalSourceVoiceCount: u32,
ActiveSubmixVoiceCount: u32,
ActiveResamplerCount: u32,
ActiveMatrixMixCount: u32,
ActiveXmaSourceVoices: u32,
ActiveXmaStreams: u32,
};
pub const XAUDIO2_DEBUG_CONFIGURATION = packed struct {
TraceMask: u32,
BreakMask: u32,
LogThreadID: BOOL,
LogFileline: BOOL,
LogFunctionName: BOOL,
LogTiming: BOOL,
};
const IID_IXAudio2_Value = @import("../../zig.zig").Guid.initString("2b02e3cf-2e0b-4ec3-be45-1b2a3fe7210d");
pub const IID_IXAudio2 = &IID_IXAudio2_Value;
pub const IXAudio2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
RegisterForCallbacks: fn(
self: *const IXAudio2,
pCallback: ?*IXAudio2EngineCallback,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UnregisterForCallbacks: fn(
self: *const IXAudio2,
pCallback: ?*IXAudio2EngineCallback,
) callconv(@import("std").os.windows.WINAPI) void,
CreateSourceVoice: fn(
self: *const IXAudio2,
ppSourceVoice: ?*?*IXAudio2SourceVoice,
pSourceFormat: ?*const WAVEFORMATEX,
Flags: u32,
MaxFrequencyRatio: f32,
pCallback: ?*IXAudio2VoiceCallback,
pSendList: ?*const XAUDIO2_VOICE_SENDS,
pEffectChain: ?*const XAUDIO2_EFFECT_CHAIN,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateSubmixVoice: fn(
self: *const IXAudio2,
ppSubmixVoice: ?*?*IXAudio2SubmixVoice,
InputChannels: u32,
InputSampleRate: u32,
Flags: u32,
ProcessingStage: u32,
pSendList: ?*const XAUDIO2_VOICE_SENDS,
pEffectChain: ?*const XAUDIO2_EFFECT_CHAIN,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateMasteringVoice: fn(
self: *const IXAudio2,
ppMasteringVoice: ?*?*IXAudio2MasteringVoice,
InputChannels: u32,
InputSampleRate: u32,
Flags: u32,
szDeviceId: ?[*:0]const u16,
pEffectChain: ?*const XAUDIO2_EFFECT_CHAIN,
StreamCategory: AUDIO_STREAM_CATEGORY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
StartEngine: fn(
self: *const IXAudio2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
StopEngine: fn(
self: *const IXAudio2,
) callconv(@import("std").os.windows.WINAPI) void,
CommitChanges: fn(
self: *const IXAudio2,
OperationSet: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPerformanceData: fn(
self: *const IXAudio2,
pPerfData: ?*XAUDIO2_PERFORMANCE_DATA,
) callconv(@import("std").os.windows.WINAPI) void,
SetDebugConfiguration: fn(
self: *const IXAudio2,
pDebugConfiguration: ?*const XAUDIO2_DEBUG_CONFIGURATION,
pReserved: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) void,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2_RegisterForCallbacks(self: *const T, pCallback: ?*IXAudio2EngineCallback) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAudio2.VTable, self.vtable).RegisterForCallbacks(@ptrCast(*const IXAudio2, self), pCallback);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2_UnregisterForCallbacks(self: *const T, pCallback: ?*IXAudio2EngineCallback) callconv(.Inline) void {
return @ptrCast(*const IXAudio2.VTable, self.vtable).UnregisterForCallbacks(@ptrCast(*const IXAudio2, self), pCallback);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2_CreateSourceVoice(self: *const T, ppSourceVoice: ?*?*IXAudio2SourceVoice, pSourceFormat: ?*const WAVEFORMATEX, Flags: u32, MaxFrequencyRatio: f32, pCallback: ?*IXAudio2VoiceCallback, pSendList: ?*const XAUDIO2_VOICE_SENDS, pEffectChain: ?*const XAUDIO2_EFFECT_CHAIN) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAudio2.VTable, self.vtable).CreateSourceVoice(@ptrCast(*const IXAudio2, self), ppSourceVoice, pSourceFormat, Flags, MaxFrequencyRatio, pCallback, pSendList, pEffectChain);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2_CreateSubmixVoice(self: *const T, ppSubmixVoice: ?*?*IXAudio2SubmixVoice, InputChannels: u32, InputSampleRate: u32, Flags: u32, ProcessingStage: u32, pSendList: ?*const XAUDIO2_VOICE_SENDS, pEffectChain: ?*const XAUDIO2_EFFECT_CHAIN) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAudio2.VTable, self.vtable).CreateSubmixVoice(@ptrCast(*const IXAudio2, self), ppSubmixVoice, InputChannels, InputSampleRate, Flags, ProcessingStage, pSendList, pEffectChain);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2_CreateMasteringVoice(self: *const T, ppMasteringVoice: ?*?*IXAudio2MasteringVoice, InputChannels: u32, InputSampleRate: u32, Flags: u32, szDeviceId: ?[*:0]const u16, pEffectChain: ?*const XAUDIO2_EFFECT_CHAIN, StreamCategory: AUDIO_STREAM_CATEGORY) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAudio2.VTable, self.vtable).CreateMasteringVoice(@ptrCast(*const IXAudio2, self), ppMasteringVoice, InputChannels, InputSampleRate, Flags, szDeviceId, pEffectChain, StreamCategory);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2_StartEngine(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAudio2.VTable, self.vtable).StartEngine(@ptrCast(*const IXAudio2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2_StopEngine(self: *const T) callconv(.Inline) void {
return @ptrCast(*const IXAudio2.VTable, self.vtable).StopEngine(@ptrCast(*const IXAudio2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2_CommitChanges(self: *const T, OperationSet: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAudio2.VTable, self.vtable).CommitChanges(@ptrCast(*const IXAudio2, self), OperationSet);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2_GetPerformanceData(self: *const T, pPerfData: ?*XAUDIO2_PERFORMANCE_DATA) callconv(.Inline) void {
return @ptrCast(*const IXAudio2.VTable, self.vtable).GetPerformanceData(@ptrCast(*const IXAudio2, self), pPerfData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2_SetDebugConfiguration(self: *const T, pDebugConfiguration: ?*const XAUDIO2_DEBUG_CONFIGURATION, pReserved: ?*anyopaque) callconv(.Inline) void {
return @ptrCast(*const IXAudio2.VTable, self.vtable).SetDebugConfiguration(@ptrCast(*const IXAudio2, self), pDebugConfiguration, pReserved);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXAudio2Extension_Value = @import("../../zig.zig").Guid.initString("84ac29bb-d619-44d2-b197-e4acf7df3ed6");
pub const IID_IXAudio2Extension = &IID_IXAudio2Extension_Value;
pub const IXAudio2Extension = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetProcessingQuantum: fn(
self: *const IXAudio2Extension,
quantumNumerator: ?*u32,
quantumDenominator: ?*u32,
) callconv(@import("std").os.windows.WINAPI) void,
GetProcessor: fn(
self: *const IXAudio2Extension,
processor: ?*u32,
) callconv(@import("std").os.windows.WINAPI) void,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2Extension_GetProcessingQuantum(self: *const T, quantumNumerator: ?*u32, quantumDenominator: ?*u32) callconv(.Inline) void {
return @ptrCast(*const IXAudio2Extension.VTable, self.vtable).GetProcessingQuantum(@ptrCast(*const IXAudio2Extension, self), quantumNumerator, quantumDenominator);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2Extension_GetProcessor(self: *const T, processor: ?*u32) callconv(.Inline) void {
return @ptrCast(*const IXAudio2Extension.VTable, self.vtable).GetProcessor(@ptrCast(*const IXAudio2Extension, self), processor);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const IXAudio2Voice = extern struct {
pub const VTable = extern struct {
GetVoiceDetails: fn(
self: *const IXAudio2Voice,
pVoiceDetails: ?*XAUDIO2_VOICE_DETAILS,
) callconv(@import("std").os.windows.WINAPI) void,
SetOutputVoices: fn(
self: *const IXAudio2Voice,
pSendList: ?*const XAUDIO2_VOICE_SENDS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetEffectChain: fn(
self: *const IXAudio2Voice,
pEffectChain: ?*const XAUDIO2_EFFECT_CHAIN,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EnableEffect: fn(
self: *const IXAudio2Voice,
EffectIndex: u32,
OperationSet: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DisableEffect: fn(
self: *const IXAudio2Voice,
EffectIndex: u32,
OperationSet: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetEffectState: fn(
self: *const IXAudio2Voice,
EffectIndex: u32,
pEnabled: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) void,
SetEffectParameters: fn(
self: *const IXAudio2Voice,
EffectIndex: u32,
// TODO: what to do with BytesParamIndex 2?
pParameters: ?*const anyopaque,
ParametersByteSize: u32,
OperationSet: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetEffectParameters: fn(
self: *const IXAudio2Voice,
EffectIndex: u32,
// TODO: what to do with BytesParamIndex 2?
pParameters: ?*anyopaque,
ParametersByteSize: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetFilterParameters: fn(
self: *const IXAudio2Voice,
pParameters: ?*const XAUDIO2_FILTER_PARAMETERS,
OperationSet: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFilterParameters: fn(
self: *const IXAudio2Voice,
pParameters: ?*XAUDIO2_FILTER_PARAMETERS,
) callconv(@import("std").os.windows.WINAPI) void,
SetOutputFilterParameters: fn(
self: *const IXAudio2Voice,
pDestinationVoice: ?*IXAudio2Voice,
pParameters: ?*const XAUDIO2_FILTER_PARAMETERS,
OperationSet: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetOutputFilterParameters: fn(
self: *const IXAudio2Voice,
pDestinationVoice: ?*IXAudio2Voice,
pParameters: ?*XAUDIO2_FILTER_PARAMETERS,
) callconv(@import("std").os.windows.WINAPI) void,
SetVolume: fn(
self: *const IXAudio2Voice,
Volume: f32,
OperationSet: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetVolume: fn(
self: *const IXAudio2Voice,
pVolume: ?*f32,
) callconv(@import("std").os.windows.WINAPI) void,
SetChannelVolumes: fn(
self: *const IXAudio2Voice,
Channels: u32,
pVolumes: [*]const f32,
OperationSet: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetChannelVolumes: fn(
self: *const IXAudio2Voice,
Channels: u32,
pVolumes: [*]f32,
) callconv(@import("std").os.windows.WINAPI) void,
SetOutputMatrix: fn(
self: *const IXAudio2Voice,
pDestinationVoice: ?*IXAudio2Voice,
SourceChannels: u32,
DestinationChannels: u32,
pLevelMatrix: ?*const f32,
OperationSet: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetOutputMatrix: fn(
self: *const IXAudio2Voice,
pDestinationVoice: ?*IXAudio2Voice,
SourceChannels: u32,
DestinationChannels: u32,
pLevelMatrix: ?*f32,
) callconv(@import("std").os.windows.WINAPI) void,
DestroyVoice: fn(
self: *const IXAudio2Voice,
) callconv(@import("std").os.windows.WINAPI) void,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2Voice_GetVoiceDetails(self: *const T, pVoiceDetails: ?*XAUDIO2_VOICE_DETAILS) callconv(.Inline) void {
return @ptrCast(*const IXAudio2Voice.VTable, self.vtable).GetVoiceDetails(@ptrCast(*const IXAudio2Voice, self), pVoiceDetails);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2Voice_SetOutputVoices(self: *const T, pSendList: ?*const XAUDIO2_VOICE_SENDS) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAudio2Voice.VTable, self.vtable).SetOutputVoices(@ptrCast(*const IXAudio2Voice, self), pSendList);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2Voice_SetEffectChain(self: *const T, pEffectChain: ?*const XAUDIO2_EFFECT_CHAIN) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAudio2Voice.VTable, self.vtable).SetEffectChain(@ptrCast(*const IXAudio2Voice, self), pEffectChain);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2Voice_EnableEffect(self: *const T, EffectIndex: u32, OperationSet: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAudio2Voice.VTable, self.vtable).EnableEffect(@ptrCast(*const IXAudio2Voice, self), EffectIndex, OperationSet);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2Voice_DisableEffect(self: *const T, EffectIndex: u32, OperationSet: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAudio2Voice.VTable, self.vtable).DisableEffect(@ptrCast(*const IXAudio2Voice, self), EffectIndex, OperationSet);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2Voice_GetEffectState(self: *const T, EffectIndex: u32, pEnabled: ?*BOOL) callconv(.Inline) void {
return @ptrCast(*const IXAudio2Voice.VTable, self.vtable).GetEffectState(@ptrCast(*const IXAudio2Voice, self), EffectIndex, pEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2Voice_SetEffectParameters(self: *const T, EffectIndex: u32, pParameters: ?*const anyopaque, ParametersByteSize: u32, OperationSet: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAudio2Voice.VTable, self.vtable).SetEffectParameters(@ptrCast(*const IXAudio2Voice, self), EffectIndex, pParameters, ParametersByteSize, OperationSet);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2Voice_GetEffectParameters(self: *const T, EffectIndex: u32, pParameters: ?*anyopaque, ParametersByteSize: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAudio2Voice.VTable, self.vtable).GetEffectParameters(@ptrCast(*const IXAudio2Voice, self), EffectIndex, pParameters, ParametersByteSize);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2Voice_SetFilterParameters(self: *const T, pParameters: ?*const XAUDIO2_FILTER_PARAMETERS, OperationSet: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAudio2Voice.VTable, self.vtable).SetFilterParameters(@ptrCast(*const IXAudio2Voice, self), pParameters, OperationSet);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2Voice_GetFilterParameters(self: *const T, pParameters: ?*XAUDIO2_FILTER_PARAMETERS) callconv(.Inline) void {
return @ptrCast(*const IXAudio2Voice.VTable, self.vtable).GetFilterParameters(@ptrCast(*const IXAudio2Voice, self), pParameters);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2Voice_SetOutputFilterParameters(self: *const T, pDestinationVoice: ?*IXAudio2Voice, pParameters: ?*const XAUDIO2_FILTER_PARAMETERS, OperationSet: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAudio2Voice.VTable, self.vtable).SetOutputFilterParameters(@ptrCast(*const IXAudio2Voice, self), pDestinationVoice, pParameters, OperationSet);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2Voice_GetOutputFilterParameters(self: *const T, pDestinationVoice: ?*IXAudio2Voice, pParameters: ?*XAUDIO2_FILTER_PARAMETERS) callconv(.Inline) void {
return @ptrCast(*const IXAudio2Voice.VTable, self.vtable).GetOutputFilterParameters(@ptrCast(*const IXAudio2Voice, self), pDestinationVoice, pParameters);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2Voice_SetVolume(self: *const T, Volume: f32, OperationSet: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAudio2Voice.VTable, self.vtable).SetVolume(@ptrCast(*const IXAudio2Voice, self), Volume, OperationSet);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2Voice_GetVolume(self: *const T, pVolume: ?*f32) callconv(.Inline) void {
return @ptrCast(*const IXAudio2Voice.VTable, self.vtable).GetVolume(@ptrCast(*const IXAudio2Voice, self), pVolume);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2Voice_SetChannelVolumes(self: *const T, Channels: u32, pVolumes: [*]const f32, OperationSet: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAudio2Voice.VTable, self.vtable).SetChannelVolumes(@ptrCast(*const IXAudio2Voice, self), Channels, pVolumes, OperationSet);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2Voice_GetChannelVolumes(self: *const T, Channels: u32, pVolumes: [*]f32) callconv(.Inline) void {
return @ptrCast(*const IXAudio2Voice.VTable, self.vtable).GetChannelVolumes(@ptrCast(*const IXAudio2Voice, self), Channels, pVolumes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2Voice_SetOutputMatrix(self: *const T, pDestinationVoice: ?*IXAudio2Voice, SourceChannels: u32, DestinationChannels: u32, pLevelMatrix: ?*const f32, OperationSet: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAudio2Voice.VTable, self.vtable).SetOutputMatrix(@ptrCast(*const IXAudio2Voice, self), pDestinationVoice, SourceChannels, DestinationChannels, pLevelMatrix, OperationSet);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2Voice_GetOutputMatrix(self: *const T, pDestinationVoice: ?*IXAudio2Voice, SourceChannels: u32, DestinationChannels: u32, pLevelMatrix: ?*f32) callconv(.Inline) void {
return @ptrCast(*const IXAudio2Voice.VTable, self.vtable).GetOutputMatrix(@ptrCast(*const IXAudio2Voice, self), pDestinationVoice, SourceChannels, DestinationChannels, pLevelMatrix);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2Voice_DestroyVoice(self: *const T) callconv(.Inline) void {
return @ptrCast(*const IXAudio2Voice.VTable, self.vtable).DestroyVoice(@ptrCast(*const IXAudio2Voice, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const IXAudio2SourceVoice = extern struct {
pub const VTable = extern struct {
base: IXAudio2Voice.VTable,
Start: fn(
self: *const IXAudio2SourceVoice,
Flags: u32,
OperationSet: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Stop: fn(
self: *const IXAudio2SourceVoice,
Flags: u32,
OperationSet: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SubmitSourceBuffer: fn(
self: *const IXAudio2SourceVoice,
pBuffer: ?*const XAUDIO2_BUFFER,
pBufferWMA: ?*const XAUDIO2_BUFFER_WMA,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FlushSourceBuffers: fn(
self: *const IXAudio2SourceVoice,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Discontinuity: fn(
self: *const IXAudio2SourceVoice,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ExitLoop: fn(
self: *const IXAudio2SourceVoice,
OperationSet: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetState: fn(
self: *const IXAudio2SourceVoice,
pVoiceState: ?*XAUDIO2_VOICE_STATE,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) void,
SetFrequencyRatio: fn(
self: *const IXAudio2SourceVoice,
Ratio: f32,
OperationSet: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFrequencyRatio: fn(
self: *const IXAudio2SourceVoice,
pRatio: ?*f32,
) callconv(@import("std").os.windows.WINAPI) void,
SetSourceSampleRate: fn(
self: *const IXAudio2SourceVoice,
NewSourceSampleRate: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IXAudio2Voice.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2SourceVoice_Start(self: *const T, Flags: u32, OperationSet: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAudio2SourceVoice.VTable, self.vtable).Start(@ptrCast(*const IXAudio2SourceVoice, self), Flags, OperationSet);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2SourceVoice_Stop(self: *const T, Flags: u32, OperationSet: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAudio2SourceVoice.VTable, self.vtable).Stop(@ptrCast(*const IXAudio2SourceVoice, self), Flags, OperationSet);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2SourceVoice_SubmitSourceBuffer(self: *const T, pBuffer: ?*const XAUDIO2_BUFFER, pBufferWMA: ?*const XAUDIO2_BUFFER_WMA) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAudio2SourceVoice.VTable, self.vtable).SubmitSourceBuffer(@ptrCast(*const IXAudio2SourceVoice, self), pBuffer, pBufferWMA);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2SourceVoice_FlushSourceBuffers(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAudio2SourceVoice.VTable, self.vtable).FlushSourceBuffers(@ptrCast(*const IXAudio2SourceVoice, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2SourceVoice_Discontinuity(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAudio2SourceVoice.VTable, self.vtable).Discontinuity(@ptrCast(*const IXAudio2SourceVoice, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2SourceVoice_ExitLoop(self: *const T, OperationSet: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAudio2SourceVoice.VTable, self.vtable).ExitLoop(@ptrCast(*const IXAudio2SourceVoice, self), OperationSet);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2SourceVoice_GetState(self: *const T, pVoiceState: ?*XAUDIO2_VOICE_STATE, Flags: u32) callconv(.Inline) void {
return @ptrCast(*const IXAudio2SourceVoice.VTable, self.vtable).GetState(@ptrCast(*const IXAudio2SourceVoice, self), pVoiceState, Flags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2SourceVoice_SetFrequencyRatio(self: *const T, Ratio: f32, OperationSet: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAudio2SourceVoice.VTable, self.vtable).SetFrequencyRatio(@ptrCast(*const IXAudio2SourceVoice, self), Ratio, OperationSet);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2SourceVoice_GetFrequencyRatio(self: *const T, pRatio: ?*f32) callconv(.Inline) void {
return @ptrCast(*const IXAudio2SourceVoice.VTable, self.vtable).GetFrequencyRatio(@ptrCast(*const IXAudio2SourceVoice, self), pRatio);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2SourceVoice_SetSourceSampleRate(self: *const T, NewSourceSampleRate: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAudio2SourceVoice.VTable, self.vtable).SetSourceSampleRate(@ptrCast(*const IXAudio2SourceVoice, self), NewSourceSampleRate);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const IXAudio2SubmixVoice = extern struct {
pub const VTable = extern struct {
base: IXAudio2Voice.VTable,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IXAudio2Voice.MethodMixin(T);
};}
pub usingnamespace MethodMixin(@This());
};
pub const IXAudio2MasteringVoice = extern struct {
pub const VTable = extern struct {
base: IXAudio2Voice.VTable,
GetChannelMask: fn(
self: *const IXAudio2MasteringVoice,
pChannelmask: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IXAudio2Voice.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2MasteringVoice_GetChannelMask(self: *const T, pChannelmask: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAudio2MasteringVoice.VTable, self.vtable).GetChannelMask(@ptrCast(*const IXAudio2MasteringVoice, self), pChannelmask);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const IXAudio2EngineCallback = extern struct {
pub const VTable = extern struct {
OnProcessingPassStart: fn(
self: *const IXAudio2EngineCallback,
) callconv(@import("std").os.windows.WINAPI) void,
OnProcessingPassEnd: fn(
self: *const IXAudio2EngineCallback,
) callconv(@import("std").os.windows.WINAPI) void,
OnCriticalError: fn(
self: *const IXAudio2EngineCallback,
Error: HRESULT,
) callconv(@import("std").os.windows.WINAPI) void,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2EngineCallback_OnProcessingPassStart(self: *const T) callconv(.Inline) void {
return @ptrCast(*const IXAudio2EngineCallback.VTable, self.vtable).OnProcessingPassStart(@ptrCast(*const IXAudio2EngineCallback, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2EngineCallback_OnProcessingPassEnd(self: *const T) callconv(.Inline) void {
return @ptrCast(*const IXAudio2EngineCallback.VTable, self.vtable).OnProcessingPassEnd(@ptrCast(*const IXAudio2EngineCallback, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2EngineCallback_OnCriticalError(self: *const T, Error: HRESULT) callconv(.Inline) void {
return @ptrCast(*const IXAudio2EngineCallback.VTable, self.vtable).OnCriticalError(@ptrCast(*const IXAudio2EngineCallback, self), Error);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const IXAudio2VoiceCallback = extern struct {
pub const VTable = extern struct {
OnVoiceProcessingPassStart: fn(
self: *const IXAudio2VoiceCallback,
BytesRequired: u32,
) callconv(@import("std").os.windows.WINAPI) void,
OnVoiceProcessingPassEnd: fn(
self: *const IXAudio2VoiceCallback,
) callconv(@import("std").os.windows.WINAPI) void,
OnStreamEnd: fn(
self: *const IXAudio2VoiceCallback,
) callconv(@import("std").os.windows.WINAPI) void,
OnBufferStart: fn(
self: *const IXAudio2VoiceCallback,
pBufferContext: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) void,
OnBufferEnd: fn(
self: *const IXAudio2VoiceCallback,
pBufferContext: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) void,
OnLoopEnd: fn(
self: *const IXAudio2VoiceCallback,
pBufferContext: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) void,
OnVoiceError: fn(
self: *const IXAudio2VoiceCallback,
pBufferContext: ?*anyopaque,
Error: HRESULT,
) callconv(@import("std").os.windows.WINAPI) void,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2VoiceCallback_OnVoiceProcessingPassStart(self: *const T, BytesRequired: u32) callconv(.Inline) void {
return @ptrCast(*const IXAudio2VoiceCallback.VTable, self.vtable).OnVoiceProcessingPassStart(@ptrCast(*const IXAudio2VoiceCallback, self), BytesRequired);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2VoiceCallback_OnVoiceProcessingPassEnd(self: *const T) callconv(.Inline) void {
return @ptrCast(*const IXAudio2VoiceCallback.VTable, self.vtable).OnVoiceProcessingPassEnd(@ptrCast(*const IXAudio2VoiceCallback, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2VoiceCallback_OnStreamEnd(self: *const T) callconv(.Inline) void {
return @ptrCast(*const IXAudio2VoiceCallback.VTable, self.vtable).OnStreamEnd(@ptrCast(*const IXAudio2VoiceCallback, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2VoiceCallback_OnBufferStart(self: *const T, pBufferContext: ?*anyopaque) callconv(.Inline) void {
return @ptrCast(*const IXAudio2VoiceCallback.VTable, self.vtable).OnBufferStart(@ptrCast(*const IXAudio2VoiceCallback, self), pBufferContext);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2VoiceCallback_OnBufferEnd(self: *const T, pBufferContext: ?*anyopaque) callconv(.Inline) void {
return @ptrCast(*const IXAudio2VoiceCallback.VTable, self.vtable).OnBufferEnd(@ptrCast(*const IXAudio2VoiceCallback, self), pBufferContext);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2VoiceCallback_OnLoopEnd(self: *const T, pBufferContext: ?*anyopaque) callconv(.Inline) void {
return @ptrCast(*const IXAudio2VoiceCallback.VTable, self.vtable).OnLoopEnd(@ptrCast(*const IXAudio2VoiceCallback, self), pBufferContext);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAudio2VoiceCallback_OnVoiceError(self: *const T, pBufferContext: ?*anyopaque, Error: HRESULT) callconv(.Inline) void {
return @ptrCast(*const IXAudio2VoiceCallback.VTable, self.vtable).OnVoiceError(@ptrCast(*const IXAudio2VoiceCallback, self), pBufferContext, Error);
}
};}
pub usingnamespace MethodMixin(@This());
};
const CLSID_AudioVolumeMeter_Value = @import("../../zig.zig").Guid.initString("4fc3b166-972a-40cf-bc37-7db03db2fba3");
pub const CLSID_AudioVolumeMeter = &CLSID_AudioVolumeMeter_Value;
const CLSID_AudioReverb_Value = @import("../../zig.zig").Guid.initString("c2633b16-471b-4498-b8c5-4f0959e2ec09");
pub const CLSID_AudioReverb = &CLSID_AudioReverb_Value;
pub const XAUDIO2FX_VOLUMEMETER_LEVELS = packed struct {
pPeakLevels: ?*f32,
pRMSLevels: ?*f32,
ChannelCount: u32,
};
pub const XAUDIO2FX_REVERB_PARAMETERS = packed struct {
WetDryMix: f32,
ReflectionsDelay: u32,
ReverbDelay: u8,
RearDelay: u8,
SideDelay: u8,
PositionLeft: u8,
PositionRight: u8,
PositionMatrixLeft: u8,
PositionMatrixRight: u8,
EarlyDiffusion: u8,
LateDiffusion: u8,
LowEQGain: u8,
LowEQCutoff: u8,
HighEQGain: u8,
HighEQCutoff: u8,
RoomFilterFreq: f32,
RoomFilterMain: f32,
RoomFilterHF: f32,
ReflectionsGain: f32,
ReverbGain: f32,
DecayTime: f32,
Density: f32,
RoomSize: f32,
DisableLateField: BOOL,
};
pub const XAUDIO2FX_REVERB_I3DL2_PARAMETERS = packed struct {
WetDryMix: f32,
Room: i32,
RoomHF: i32,
RoomRolloffFactor: f32,
DecayTime: f32,
DecayHFRatio: f32,
Reflections: i32,
ReflectionsDelay: f32,
Reverb: i32,
ReverbDelay: f32,
Diffusion: f32,
Density: f32,
HFReference: f32,
};
pub const HrtfPosition = extern struct {
x: f32,
y: f32,
z: f32,
};
pub const HrtfOrientation = extern struct {
element: [9]f32,
};
pub const HrtfDirectivityType = enum(i32) {
OmniDirectional = 0,
Cardioid = 1,
Cone = 2,
};
pub const OmniDirectional = HrtfDirectivityType.OmniDirectional;
pub const Cardioid = HrtfDirectivityType.Cardioid;
pub const Cone = HrtfDirectivityType.Cone;
pub const HrtfEnvironment = enum(i32) {
Small = 0,
Medium = 1,
Large = 2,
Outdoors = 3,
};
pub const Small = HrtfEnvironment.Small;
pub const Medium = HrtfEnvironment.Medium;
pub const Large = HrtfEnvironment.Large;
pub const Outdoors = HrtfEnvironment.Outdoors;
pub const HrtfDirectivity = extern struct {
type: HrtfDirectivityType,
scaling: f32,
};
pub const HrtfDirectivityCardioid = extern struct {
directivity: HrtfDirectivity,
order: f32,
};
pub const HrtfDirectivityCone = extern struct {
directivity: HrtfDirectivity,
innerAngle: f32,
outerAngle: f32,
};
pub const HrtfDistanceDecayType = enum(i32) {
NaturalDecay = 0,
CustomDecay = 1,
};
pub const NaturalDecay = HrtfDistanceDecayType.NaturalDecay;
pub const CustomDecay = HrtfDistanceDecayType.CustomDecay;
pub const HrtfDistanceDecay = extern struct {
type: HrtfDistanceDecayType,
maxGain: f32,
minGain: f32,
unityGainDistance: f32,
cutoffDistance: f32,
};
pub const HrtfApoInit = extern struct {
distanceDecay: ?*HrtfDistanceDecay,
directivity: ?*HrtfDirectivity,
};
// TODO: this type is limited to platform 'windows10.0.10240'
const IID_IXAPOHrtfParameters_Value = @import("../../zig.zig").Guid.initString("15b3cd66-e9de-4464-b6e6-2bc3cf63d455");
pub const IID_IXAPOHrtfParameters = &IID_IXAPOHrtfParameters_Value;
pub const IXAPOHrtfParameters = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetSourcePosition: fn(
self: *const IXAPOHrtfParameters,
position: ?*const HrtfPosition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetSourceOrientation: fn(
self: *const IXAPOHrtfParameters,
orientation: ?*const HrtfOrientation,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetSourceGain: fn(
self: *const IXAPOHrtfParameters,
gain: f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetEnvironment: fn(
self: *const IXAPOHrtfParameters,
environment: HrtfEnvironment,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAPOHrtfParameters_SetSourcePosition(self: *const T, position: ?*const HrtfPosition) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAPOHrtfParameters.VTable, self.vtable).SetSourcePosition(@ptrCast(*const IXAPOHrtfParameters, self), position);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAPOHrtfParameters_SetSourceOrientation(self: *const T, orientation: ?*const HrtfOrientation) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAPOHrtfParameters.VTable, self.vtable).SetSourceOrientation(@ptrCast(*const IXAPOHrtfParameters, self), orientation);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAPOHrtfParameters_SetSourceGain(self: *const T, gain: f32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAPOHrtfParameters.VTable, self.vtable).SetSourceGain(@ptrCast(*const IXAPOHrtfParameters, self), gain);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAPOHrtfParameters_SetEnvironment(self: *const T, environment: HrtfEnvironment) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAPOHrtfParameters.VTable, self.vtable).SetEnvironment(@ptrCast(*const IXAPOHrtfParameters, self), environment);
}
};}
pub usingnamespace MethodMixin(@This());
};
//--------------------------------------------------------------------------------
// Section: Functions (5)
//--------------------------------------------------------------------------------
pub extern "XAudio2_8" fn CreateFX(
clsid: ?*const Guid,
pEffect: ?*?*IUnknown,
// TODO: what to do with BytesParamIndex 3?
pInitDat: ?*const anyopaque,
InitDataByteSize: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "XAudio2_8" fn XAudio2CreateWithVersionInfo(
ppXAudio2: ?*?*IXAudio2,
Flags: u32,
XAudio2Processor: u32,
ntddiVersion: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "XAudio2_8" fn CreateAudioVolumeMeter(
ppApo: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "XAudio2_8" fn CreateAudioReverb(
ppApo: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "HrtfApo" fn CreateHrtfApo(
init: ?*const HrtfApoInit,
xApo: ?*?*IXAPO,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (0)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../../zig.zig").unicode_mode) {
.ansi => struct {
},
.wide => struct {
},
.unspecified => if (@import("builtin").is_test) struct {
} else struct {
},
};
//--------------------------------------------------------------------------------
// Section: Imports (7)
//--------------------------------------------------------------------------------
const Guid = @import("../../zig.zig").Guid;
const AUDIO_STREAM_CATEGORY = @import("../../media/audio.zig").AUDIO_STREAM_CATEGORY;
const BOOL = @import("../../foundation.zig").BOOL;
const HRESULT = @import("../../foundation.zig").HRESULT;
const IUnknown = @import("../../system/com.zig").IUnknown;
const PWSTR = @import("../../foundation.zig").PWSTR;
const WAVEFORMATEX = @import("../../media/audio.zig").WAVEFORMATEX;
test {
@setEvalBranchQuota(
@import("std").meta.declarations(@This()).len * 3
);
// reference all the pub declarations
if (!@import("builtin").is_test) return;
inline for (@import("std").meta.declarations(@This())) |decl| {
if (decl.is_pub) {
_ = decl;
}
}
}
|
win32/media/audio/xaudio2.zig
|
const std = @import("std");
const daemon = @import("daemon.zig");
const ServiceLogger = @import("service_logger.zig").ServiceLogger;
const DaemonState = daemon.DaemonState;
const ServiceDecl = daemon.ServiceDecl;
const Service = daemon.Service;
const ServiceStateType = daemon.ServiceStateType;
const RcClient = daemon.RcClient;
pub const KillServiceContext = struct {
state: *DaemonState,
service: *const Service,
client: *RcClient,
};
pub const KillError = error{ PermissionDenied, UnknownPID } || std.os.UnexpectedError;
// TODO maybe pr this back to zig
pub fn kill(pid: std.os.pid_t, sig: u8) KillError!void {
switch (std.os.errno(std.os.system.kill(pid, sig))) {
0 => return,
std.os.EINVAL => unreachable, // invalid signal
std.os.EPERM => return error.PermissionDenied,
std.os.ESRCH => return error.UnknownPID,
else => |err| return std.os.unexpectedErrno(err),
}
}
pub fn killService(ctx: KillServiceContext) !void {
defer ctx.client.decRef();
var state = ctx.state;
var allocator = ctx.state.allocator;
const service = ctx.service;
const pid = service.state.Running.pid;
const logger_thread = service.state.Running.logger_thread;
// before sending our signals to the process, we need to kill the
// logger thread. it will panic if it tries to read from
// stdout/stderr when they're killed.
ServiceLogger.stopLogger(logger_thread) catch |err| {
try ctx.client.ptr.?.print("err failed to stop logger thread: {}\n", .{err});
return;
};
// First, we make the daemon send a SIGTERM to the child process.
// Then we wait 1 second, and try to send a SIGKILL. If the process is
// already dead, the UnknownPID error will be silently ignored.
kill(pid, std.os.SIGTERM) catch |err| {
if (err == error.UnknownPID) {
try ctx.client.ptr.?.print("err pid not found for SIGTERM!", .{});
return;
}
return err;
};
std.time.sleep(1 * std.time.ns_per_s);
// UnknownPID errors here must be silenced.
kill(pid, std.os.SIGKILL) catch |err| {
if (err != error.UnknownPID) {
return err;
}
};
// Wait 250 milliseconds to give the system time to catch up on that
// SIGKILL and we have updated state.
std.time.sleep(250 * std.time.ns_per_ms);
ctx.state.logger.info("sent wanted signals to pid {}", .{pid});
try state.writeServices(ctx.client.ptr.?.stream());
}
pub const WatchServiceContext = struct {
state: *DaemonState,
service: *Service,
client: *RcClient,
};
/// Caller owns the returned memory.
fn deserializeString(allocator: *std.mem.Allocator, deserializer: anytype) ![]const u8 {
const length = try deserializer.deserialize(u16);
var msg = try allocator.alloc(u8, length);
var i: usize = 0;
while (i < length) : (i += 1) {
msg[i] = try deserializer.deserialize(u8);
}
return msg;
}
pub fn watchService(ctx: WatchServiceContext) !void {
defer ctx.client.decRef();
var state = ctx.state;
var service = ctx.service;
const pipes = try std.os.pipe();
const read_fd = pipes[0];
const write_fd = pipes[1];
// give write_fd to service logger thread
try service.addLoggerClient(write_fd);
defer {
service.removeLoggerClient(write_fd);
// this thread owns the lifetime of both fds, so it must
// close both (after removing the references to them in the service)
std.os.close(read_fd);
std.os.close(write_fd);
}
// read from read_fd in a loop
var read_file = std.fs.File{ .handle = read_fd };
var deserializer = daemon.MsgDeserializer.init(read_file.reader());
while (true) {
const opcode = try deserializer.deserialize(u8);
if (opcode == 1) {
const err_msg = try deserializeString(ctx.state.allocator, &deserializer);
defer ctx.state.allocator.free(err_msg);
std.debug.warn("Failed to link client to daemon: '{}'", .{err_msg});
ctx.client.ptr.?.print("err {}!", .{err_msg}) catch |err| {
if (err == error.Closed) {
// if client is closed, don't care
return;
} else return err;
};
}
if (opcode == 2 or opcode == 3) {
const data_msg = try deserializeString(ctx.state.allocator, &deserializer);
defer ctx.state.allocator.free(data_msg);
const std_name = if (opcode == 2) "stdout" else "stderr";
ctx.client.ptr.?.print("data;{};{};{}!", .{ ctx.service.name, std_name, data_msg }) catch |err| {
if (err == error.Closed) {
// if client is closed, don't care
return;
} else return err;
};
}
}
}
|
src/thread_commands.zig
|
const std = @import("std");
const testing = std.testing;
const lex = @import("lex.zig");
const assert_one_match = true;
const LexResult = struct {
kind: lex.TokenKind,
end: [*]const u8,
};
fn scan(text: [*]const u8, limit: [*]const u8) !LexResult {
std.debug.assert(@ptrToInt(text) < @ptrToInt(limit));
var kind = lex.token0;
const end = lex.lex(text, limit, &kind);
if (end == text)
return error.UnknownToken;
return LexResult { .kind = kind, .end = end };
}
//pub const ScanSkipResult = struct {
// start: [*]const u8,
// scan_result: LexResult,
//};
//pub fn scanSkipInlineWhitespace(text: [*]const u8, limit: [*]const u8) !ScanSkipResult {
// const result1 = try scan(text, limit);
// std.debug.assert(@ptrToInt(result1.end) > @ptrToInt(text));
// if (result1.kind != .inline_whitespace)
// return .{ .start = text, .scan_result = result1 };
// // BUG POTENTIAL!!! Make sure that when I scan src after an UnknownToken error
// // that I skip inline whitespace first
// const result2 = try scan(result1.end, limit);
// std.debug.assert(@ptrToInt(result2.end) > @ptrToInt(result1.end));
// // should be impossible to get 2 inline_whitespace tokens in a row
// if (result2.kind != .inline_whitespace) unreachable;
// return ScanSkipResult { .start = result1.end, .scan_result = result2 };
//}
//
const BinaryOpKind = enum {
//assign,
pipe,
@"or",
@"and",
eq,
gt,
lt,
};
const binary_builtin_id_map = std.ComptimeStringMap(BinaryOpKind, .{
.{ "pipe", .pipe },
.{ "or", .@"or" },
.{ "and", .@"and" },
.{ "eq", .eq },
.{ "gt", .gt },
.{ "lt", .lt },
});
const NodeKind = enum {
//arg_sep,
string,
binary_op,
id,
inline_cmd_start,
inline_cmd_end,
// concat, (equivalent to NodeMultiple from python prototype)
};
// TODO: I could probably make this struct much smaller
pub const Node = struct {
pos: [*]const u8,
//end: [*]const u8,
join_prev: bool, // if true, join this node with the previous node
data: union(enum) {
//arg_sep: void,
arg: [*]const u8,
assign: void,
user_id: void,
builtin_id: [*]const u8,
binary_op: BinaryOpKind,
double_quoted_string: [*]const u8,
single_quoted_string: void,
escape_sequence: void,
},
pub fn getKind(self: Node) NodeKind {
return switch (self.data) {
.arg, .double_quoted_string, .single_quoted_string, .escape_sequence => .string,
.assign, .binary_op => .binary_op,
.user_id, .builtin_id => .id,
};
}
pub fn getIdSlice(self: Node) []const u8 {
const data: struct {delim:u8, end: [*]const u8} = switch (self.data) {
.builtin_id => |d| .{ .delim = '@', .end = d },
.binary_op => |_| .{ .delim = '@', .end = @panic("not impl") },
.user_id => |_| .{ .delim = '$', .end = @panic("not impl") },
else => unreachable,
};
const id_limit = data.end - @as(u1, if ((data.end-1)[0] == data.delim) 1 else 0);
return self.pos[1 .. @ptrToInt(id_limit) - @ptrToInt(self.pos)];
}
pub fn getStringData(self: Node) []const u8 {
switch (self.data) {
.double_quoted_string => {
return self.pos[1 .. @ptrToInt(self.end) - @ptrToInt(self.pos) - 1];
},
else => unreachable,
}
}
};
// Command Memory Layout
//
// every node has a Xbit (16?) offset into the command string that points
// to the START of the first token of the node. This is important because
// each node will have access to both it's start and the start of the next token.
// NOTE: this could be usize to support any size of platform?
//
// string (tokens: arg, double_quoted_string, single_quoted_string, escape_sequence)
// id (tokens: builtin_id, user_id)
// binary_op (tokens: assign, builtin_id)
// inline_cmd_start (token: open_paren)
// inline_cmd_end (token: close_paren)
// arg_separator (token: inline_whitespace)
//
//
//const NodeKind = enum {
// string, id, binary_op, inline_cmd_start, inline_cmd_end, arg_separator,
//};
//const CmdOffset = u16;
//const Node = struct {
// //token_start: CmdOffset,
// pos: [*]const u8,
// kind: NodeKind,
// // TODO: remove this method
// pub fn getKind(self: Node) NodeKind { return self.kind; }
//};
pub const NodeBuilder = @import("block_list.zig").BlockList(Node, .{});
fn parseOneNode(src: [*]const u8, token: LexResult, allstringliterals: bool) Node {
_ = allstringliterals;
switch (token.kind) {
.inline_whitespace, .comment, .newline, .close_paren => unreachable,
.builtin_id => {
var node = Node { .pos = src, //.end = token.end,
.data = .{ .builtin_id = token.end } };
const id = node.getIdSlice();
if (binary_builtin_id_map.get(id)) |binary_op_kind| {
node.data = .{ .binary_op = binary_op_kind };
}
return node;
},
.user_id => return Node { .pos = src, //.end = token.end,
.data = .user_id },
.arg => return Node { .pos = src, //.end = token.end,
.data = .{ .arg = token.end } },
.assign_op => return Node { .pos = src, //.end = token.end,
.data = .assign },
.double_quoted_string => return Node { .pos = src, //.end = token.end,
.data = .{ .double_quoted_string = token.end } },
.open_paren => @panic("parseOneNode open_paren not impl"),
.single_quoted_string => @panic("parseOneNode single_quoted_string not impl"),
.escape_sequence => return Node { .pos = src, //.end = token.end,
.data = .escape_sequence },
}
}
test "parseOneNode" {
// {
// const src: []const u8 = "@a";
// const result = parseOneNode(src.ptr, .{.kind = .builtin_id, .end = src.ptr + src.len}, true);
// //try testing.expectEqual(src[1..], result.getIdSlice());
// try testing.expectEqual(NodeKind.id, result.getKind());
// }
// {
// const src: []const u8 = "@a@";
// const result = try parseOneNode(src.ptr, .{.kind = .builtin_id, .end = src.ptr + src.len}, true);
// try testing.expectEqual(@as([]const u8, src[1..2]), result.getIdSlice());
// }
// {
// const src: []const u8 = "@pipe";
// const result = try parseOneNode(src.ptr, .{.kind = .builtin_id, .end = src.ptr + src.len}, true);
// try testing.expectEqual(BinaryOpKind.pipe, result.data.binary_op);
// }
// {
// const src: []const u8 = "$a";
// const result = try parseOneNode(src.ptr, .{.kind = .user_id, .end = src.ptr + src.len}, true);
// try testing.expectEqual(src[1..], result.getIdSlice());
// }
// {
// const src: []const u8 = "$a$";
// const result = try parseOneNode(src.ptr, .{.kind = .user_id, .end = src.ptr + src.len}, true);
// try testing.expectEqual(@as([]const u8, src[1..2]), result.getIdSlice());
// }
// {
// const src: []const u8 = "a";
// _ = try parseOneNode(src.ptr, .{.kind = .arg, .end = src.ptr + src.len}, true);
// }
// {
// const src: []const u8 = "=";
// _ = try parseOneNode(src.ptr, .{.kind = .assign_op, .end = src.ptr + src.len}, true);
// }
// {
// const src: []const u8 = "\"a\"";
// const result = try parseOneNode(src.ptr, .{.kind = .double_quoted_string, .end = src.ptr + src.len}, true);
// try testing.expect(std.mem.eql(u8, "a", result.getStringData()));
// }
// {
// const src: []const u8 = "@@";
// _ = try parseOneNode(src.ptr, .{.kind = .escape_sequence, .end = src.ptr + src.len}, true);
// }
}
const ParseNodeResult = struct {
node: Node,
token: ?LexResult,
};
fn parseNode(
node_builder: *NodeBuilder,
src: [*]const u8,
limit: [*]const u8,
token: LexResult,
allstringliterals: bool,
) !ParseNodeResult {
std.debug.assert(@ptrToInt(token.end) > @ptrToInt(src));
switch (token.kind) {
.inline_whitespace, .comment, .newline, .close_paren => unreachable,
else => {},
}
var next = src;
var next_token = token;
while (true) {
_ = node_builder; // TODO: remove this!!!
{
//std.debug.print("calling parseOneNode with '{s}'...\n", .{
// next[0 .. @ptrToInt(next_token.end) - @ptrToInt(next)]});
const next_node = try parseOneNode(next, next_token, allstringliterals);
//std.debug.print("b: {}\n", .{next_node});
std.debug.assert(@ptrToInt(next_node.end) > @ptrToInt(next_node.pos));
if (opt_node) |_| {
@panic("not impl");
} else {
opt_node = next_node;
}
std.debug.assert(opt_node.?.end == next_node.end);
}
if (opt_node.?.end == limit)
return ParseNodeResult { .node = opt_node.?, .token = null };
const scan_result = try scan(opt_node.?.end, limit);
if (scan_result.end == opt_node.?.end) {
// TODO: then we reached an unrecognized token!!
@panic("here");
}
// std.debug.print("got {}-char token: '{s}'\n", .{@ptrToInt(scan_result.end) - @ptrToInt(next), next[0..@ptrToInt(scan_result.end) - @ptrToInt(next)]});
if (assert_one_match)
lex.assertNoMatchAfter(opt_node.?.end, limit, scan_result.kind);
switch (scan_result.kind) {
.inline_whitespace, .comment, .newline, .close_paren =>
return ParseNodeResult { .node = opt_node.?, .token = scan_result },
else => {},
}
next_token = scan_result;
next = scan_result.end;
}
}
test "parseNode" {
var node_builder = NodeBuilder { .allocator = std.testing.allocator };
node_builder.deinit();
{
// const src: []const u8 = "a";
// _ = try parseNode(&node_builder, src.ptr, src.ptr + src.len, .{ .kind = .arg, .end = src.ptr + src.len}, true);
}
}
const ParseCommandResult = union(enum) {
success: [*]const u8,
unknown_token: [*]const u8,
err: error {OutOfMemory},
};
pub fn parseCommand(node_builder: *NodeBuilder, src: [*]const u8, limit: [*]const u8, allstringliterals: bool) ParseCommandResult {
_ = allstringliterals;
std.debug.assert(@ptrToInt(src) <= @ptrToInt(limit));
var next_node_is_joined = false;
var next = src;
while (true) : (next_node_is_joined = true) {
if (next != limit) {
const after_whitespace = lex.lexInlineWhitespace(next, limit);
if (after_whitespace != next) {
next_node_is_joined = false;
next = after_whitespace;
}
}
if (next == limit)
return .{ .success = limit };
const token = scan(next, limit) catch |e| switch (e) {
error.UnknownToken => return .{ .unknown_token = next },
};
if (@ptrToInt(token.end) <= @ptrToInt(next)) unreachable;
if (assert_one_match)
lex.assertNoMatchAfter(next, limit, token.kind);
const token_start = next;
next = token.end;
switch (token.kind) {
.inline_whitespace => unreachable, // should be handled by lexInlineWhitespace above
.comment, .newline => return .{ .success = token.end },
.close_paren => return .{ .success = token_start },
.assign_op => {
node_builder.append(.{ .pos = token_start, .join_prev = next_node_is_joined,
.data = .assign, }) catch |e| switch (e) {
error.OutOfMemory => return .{ .err = e },
};
},
.builtin_id => {
node_builder.append(.{ .pos = token_start, .join_prev = next_node_is_joined,
.data = .{ .builtin_id = token.end }, }) catch |e| switch (e) {
error.OutOfMemory => return .{ .err = e },
};
},
.user_id => @panic("here"),
.arg => {
node_builder.append(.{ .pos = token_start, .join_prev = next_node_is_joined,
.data = .{ .arg = token.end }, }) catch |e| switch (e) {
error.OutOfMemory => return .{ .err = e },
};
},
.double_quoted_string => {
node_builder.append(.{ .pos = token_start, .join_prev = next_node_is_joined,
.data = .{ .double_quoted_string = token.end }, }) catch |e| switch (e) {
error.OutOfMemory => return .{ .err = e },
};
},
.single_quoted_string => @panic("here"),
.escape_sequence => {
node_builder.append(.{ .pos = token_start, .join_prev = next_node_is_joined,
.data = .escape_sequence, }) catch |e| switch (e) {
error.OutOfMemory => return .{ .err = e },
};
},
.open_paren => {
@panic("not impl");
},
}
}
}
fn testParseCommand(src: []const u8) !void {
var node_builder = NodeBuilder { .allocator = std.testing.allocator };
node_builder.deinit();
switch(parseCommand(&node_builder, src.ptr, src.ptr + src.len, true)) {
.success => {
// TODO: verify entire command was parsed
},
.unknown_token => return error.UnknownToken,
.err => |e| return e,
}
}
test "parseCommand" {
try testParseCommand(" ");
try testParseCommand("\t \t");
//try testParseCommand("a");
}
|
src/parse.zig
|
const std = @import("std");
const sdk = @import("sdk");
const tier0 = @import("tier0.zig");
const interface = @import("interface.zig");
const mods = @import("mods.zig");
const log = @import("log.zig");
const surface = @import("surface.zig");
const font_manager = @import("font_manager.zig");
const thud = @import("thud.zig");
comptime {
_ = @import("api.zig");
}
var gpa: std.heap.GeneralPurposeAllocator(.{}) = undefined;
fn init() !void {
gpa = .{};
errdefer std.debug.assert(!gpa.deinit());
const version = @import("version.zig").getVersion();
if (version == null) return error.UnknownEngineBuild;
// TODO: load offsets etc
try tier0.init();
try interface.init(gpa.allocator());
errdefer interface.deinit();
surface.init(gpa.allocator());
font_manager.init(gpa.allocator());
errdefer font_manager.deinit();
try mods.init(gpa.allocator());
errdefer mods.deinit();
try thud.init(gpa.allocator());
errdefer thud.deinit();
font_manager.listFonts();
}
fn deinit() void {
thud.deinit();
mods.deinit();
font_manager.deinit();
interface.deinit();
std.debug.assert(!gpa.deinit());
}
// Plugin callbacks below
const Method = switch (@import("builtin").os.tag) {
.windows => std.builtin.CallingConvention.Thiscall,
else => std.builtin.CallingConvention.C,
};
// For some reason the game calls 'unload' if 'load' fails. We really don't
// want this, so we just ignore calls to 'unload' unless we're fully loaded
var loaded = false;
fn load(_: *sdk.IServerPluginCallbacks, interfaceFactory: sdk.CreateInterfaceFn, gameServerFactory: sdk.CreateInterfaceFn) callconv(Method) bool {
_ = interfaceFactory;
_ = gameServerFactory;
init() catch |err| {
if (tier0.ready) log.err("Error initializing Wormhole: {s}\n", .{@errorName(err)});
return false;
};
return true;
}
fn unload(_: *sdk.IServerPluginCallbacks) callconv(Method) void {
if (!loaded) return;
deinit();
}
fn pause(_: *sdk.IServerPluginCallbacks) callconv(Method) void {}
fn unpause(_: *sdk.IServerPluginCallbacks) callconv(Method) void {}
fn getPluginDescription(_: *sdk.IServerPluginCallbacks) callconv(Method) [*:0]const u8 {
return "Wormhole: a mod loader for Portal 2";
}
fn levelInit(_: *sdk.IServerPluginCallbacks, map_name: [*:0]const u8) callconv(Method) void {
_ = map_name;
}
fn serverActivate(_: *sdk.IServerPluginCallbacks, edict_list: [*]sdk.Edict, edict_count: c_int, client_max: c_int) callconv(Method) void {
_ = edict_list;
_ = edict_count;
_ = client_max;
}
fn gameFrame(_: *sdk.IServerPluginCallbacks, simulating: bool) callconv(Method) void {
_ = simulating;
}
fn levelShutdown(_: *sdk.IServerPluginCallbacks) callconv(Method) void {}
fn clientActive(_: *sdk.IServerPluginCallbacks, entity: *sdk.Edict) callconv(Method) void {
_ = entity;
}
fn clientFullyConnect(_: *sdk.IServerPluginCallbacks, entity: *sdk.Edict) callconv(Method) void {
_ = entity;
}
fn clientDisconnect(_: *sdk.IServerPluginCallbacks, entity: *sdk.Edict) callconv(Method) void {
_ = entity;
}
fn clientPutInServer(_: *sdk.IServerPluginCallbacks, entity: *sdk.Edict, player_name: [*:0]const u8) callconv(Method) void {
_ = entity;
_ = player_name;
}
fn setCommandClient(_: *sdk.IServerPluginCallbacks, index: c_int) callconv(Method) void {
_ = index;
}
fn clientSettingsChanged(_: *sdk.IServerPluginCallbacks, entity: *sdk.Edict) callconv(Method) void {
_ = entity;
}
fn clientConnect(_: *sdk.IServerPluginCallbacks, allow: *bool, entity: *sdk.Edict, name: [*:0]const u8, addr: [*:0]const u8, reject: [*:0]u8, max_reject_len: c_int) callconv(Method) c_int {
_ = allow;
_ = entity;
_ = name;
_ = addr;
_ = reject;
_ = max_reject_len;
return 0;
}
fn clientCommand(_: *sdk.IServerPluginCallbacks, entity: *sdk.Edict, args: *const sdk.CCommand) callconv(Method) c_int {
_ = entity;
_ = args;
return 0;
}
fn networkIdValidated(_: *sdk.IServerPluginCallbacks, user_name: [*:0]const u8, network_id: [*:0]const u8) callconv(Method) c_int {
_ = user_name;
_ = network_id;
return 0;
}
fn onQueryCvarValueFinished(_: *sdk.IServerPluginCallbacks, cookie: sdk.QueryCvarCookie, player: *sdk.Edict, status: sdk.QueryCvarValueStatus, name: [*:0]const u8, val: [*:0]const u8) callconv(Method) void {
_ = cookie;
_ = player;
_ = status;
_ = name;
_ = val;
}
fn onEdictAllocated(_: *sdk.IServerPluginCallbacks, edict: *sdk.Edict) callconv(Method) void {
_ = edict;
}
fn onEdictFreed(_: *sdk.IServerPluginCallbacks, edict: *const sdk.Edict) callconv(Method) void {
_ = edict;
}
// Automatically generates the IServerPluginCallbacks vtable from the
// functions defined in this file
var callbacks = sdk.IServerPluginCallbacks{
.vtable = &blk: {
var vt: sdk.IServerPluginCallbacks.Vtable = undefined;
for (std.meta.fieldNames(@TypeOf(vt))) |name| {
@field(vt, name) = @field(@This(), name);
}
break :blk vt;
},
};
// The function we expose to the game!
export fn CreateInterface(name: [*:0]u8, ret: ?*c_int) ?*anyopaque {
if (!std.mem.eql(u8, std.mem.span(name), "ISERVERPLUGINCALLBACKS003")) {
if (ret) |r| r.* = 0;
return @ptrCast(*anyopaque, &callbacks);
}
if (ret) |r| r.* = 1;
return null;
}
|
src/main.zig
|
const SFR = @import("sfr.zig").SFR;
const DDRB = SFR(0x24, u8, packed struct {
DDB0: u1 = 0,
DDB1: u1 = 0,
DDB2: u1 = 0,
DDB3: u1 = 0,
DDB4: u1 = 0,
DDB5: u1 = 0,
DDB6: u1 = 0,
DDB7: u1 = 0,
});
const PORTB = SFR(0x25, u8, packed struct {
PORTB0: u1 = 0,
PORTB1: u1 = 0,
PORTB2: u1 = 0,
PORTB3: u1 = 0,
PORTB4: u1 = 0,
PORTB5: u1 = 0,
PORTB6: u1 = 0,
PORTB7: u1 = 0,
});
const DDRC = SFR(0x27, u8, packed struct {
DDC0: u1 = 0,
DDC1: u1 = 0,
DDC2: u1 = 0,
DDC3: u1 = 0,
DDC4: u1 = 0,
DDC5: u1 = 0,
DDC6: u1 = 0,
DDC7: u1 = 0,
});
const PORTC = SFR(0x28, u8, packed struct {
PORTC0: u1 = 0,
PORTC1: u1 = 0,
PORTC2: u1 = 0,
PORTC3: u1 = 0,
PORTC4: u1 = 0,
PORTC5: u1 = 0,
PORTC6: u1 = 0,
PORTC7: u1 = 0,
});
const DDRD = SFR(0x2A, u8, packed struct {
DDD0: u1 = 0,
DDD1: u1 = 0,
DDD2: u1 = 0,
DDD3: u1 = 0,
DDD4: u1 = 0,
DDD5: u1 = 0,
DDD6: u1 = 0,
DDD7: u1 = 0,
});
const PORTD = SFR(0x2B, u8, packed struct {
PORTD0: u1 = 0,
PORTD1: u1 = 0,
PORTD2: u1 = 0,
PORTD3: u1 = 0,
PORTD4: u1 = 0,
PORTD5: u1 = 0,
PORTD6: u1 = 0,
PORTD7: u1 = 0,
});
pub fn init(comptime pin: u8, comptime ddrx: enum(u8) { b = 0, c, d }, comptime mode: enum(u1) { input = 0, output }) void {
const pins = switch (ddrx) {
.b => DDRB,
.c => DDRC,
.d => DDRD,
};
pins.write_int(@as(u8, @enumToInt(mode)) << pin);
}
pub fn set(comptime portx: enum(u3) { b = 0, c, d }, comptime pin: u8, mode: enum(u1) { low, high }) void {
const pins = switch (portx) {
.b => PORTB,
.c => PORTC,
.d => PORTD,
};
pins.write_int(mode << pin);
}
pub fn toggle(comptime pin: u8, comptime portx: enum(u3) { b = 0, c, d }) void {
const port = switch (portx) {
.b => PORTB,
.c => PORTC,
.d => PORTD,
};
var val = port.read_int();
val ^= 1 << pin;
port.write_int(val);
}
|
src/std/io.zig
|
const std = @import("std");
const x509 = @import("iguanaTLS").x509;
const tls = @import("iguanaTLS");
const TypeOfRequest = enum { GET, POST, PUT, DELETE };
pub fn makeGetRequestAlloc(allocator: std.mem.Allocator, host: []const u8, path: []const u8) ![]const u8 {
return makeRequestAlloc(allocator, host, path, "", "", .GET);
}
pub fn makePostRequestAlloc(allocator: std.mem.Allocator, host: []const u8, path: []const u8, body: []const u8, headers: []const u8) ![]const u8 {
return makeRequestAlloc(allocator, host, path, body, headers, .POST);
}
fn makeRequestAlloc(allocator: std.mem.Allocator,
host: []const u8,
path: []const u8,
body: []const u8,
headers: []const u8,
typeOfRequest: TypeOfRequest) ![]const u8 {
const sock = try std.net.tcpConnectToHost(allocator, host, 443);
defer sock.close();
var client = try tls.client_connect(.{
.reader = sock.reader(),
.writer = sock.writer(),
.cert_verifier = .none,
.temp_allocator = allocator,
.ciphersuites = tls.ciphersuites.all,
.protocols = &[_][]const u8{"http/1.1"},
}, host);
defer client.close_notify() catch {};
try std.testing.expectEqualStrings("http/1.1", client.protocol);
const typeOfRequestStr: []const u8 = switch (typeOfRequest) {
.GET => "GET",
.POST => "POST",
.PUT => "PUT",
.DELETE => "DELETE"
};
var content_length_request: []const u8 = "";
if (body.len > 0) {
content_length_request = try std.fmt.allocPrint(allocator, "Content-Length: {d}\r\n", .{body.len});
}
defer allocator.free(content_length_request);
try client.writer().print("{s} {s} HTTP/1.1\r\nHost: {s}\r\nAccept: */*\r\n{s}\r\n{s}\r\n{s}",
.{typeOfRequestStr, path, host, headers, content_length_request, body});
{
const header = try client.reader().readUntilDelimiterAlloc(allocator, '\n', std.math.maxInt(usize));
try std.testing.expectEqualStrings("HTTP/1.1 200 OK", std.mem.trim(u8, header, &std.ascii.spaces));
allocator.free(header);
}
// Skip the rest of the headers except for Content-Length
var content_length: ?usize = null;
hdr_loop: while (true) {
const header = try client.reader().readUntilDelimiterAlloc(allocator, '\n', std.math.maxInt(usize));
defer allocator.free(header);
const hdr_contents = std.mem.trim(u8, header, &std.ascii.spaces);
if (hdr_contents.len == 0) {
break :hdr_loop;
}
if (std.mem.startsWith(u8, hdr_contents, "Content-Length: ")) {
content_length = try std.fmt.parseUnsigned(usize, hdr_contents[16..], 10);
}
}
try std.testing.expect(content_length != null);
const html_contents = try allocator.alloc(u8, content_length.?);
try client.reader().readNoEof(html_contents);
std.log.info("{s}", .{html_contents});
return html_contents;
}
test "Get Request with a parameter" {
var allocator = std.testing.allocator;
const response = try makeGetRequestAlloc(allocator, "httpbin.org", "/get?name=telezig");
var parser = std.json.Parser.init(allocator, false);
defer parser.deinit();
var tree = try parser.parse(response);
defer tree.deinit();
const args = tree.root.Object.get("args").?;
const name_parameter = args.Object.get("name").?.String;
defer allocator.free(name_parameter);
try std.testing.expectEqualStrings("telezig", name_parameter);
const headers = tree.root.Object.get("headers").?;
const accept_header = headers.Object.get("Accept").?.String;
try std.testing.expectEqualStrings("*/*", accept_header);
const host_header = headers.Object.get("Host").?.String;
try std.testing.expectEqualStrings("httpbin.org", host_header);
const url = tree.root.Object.get("url").?.String;
try std.testing.expectEqualStrings("https://httpbin.org/get?name=telezig", url);
}
test "Post Request with a body" {
var allocator = std.testing.allocator;
const response = try makePostRequestAlloc(allocator, "httpbin.org", "/post", "{\"Post_Key\": \"Post_Value\"}", "Content-Type: application/json");
var parser = std.json.Parser.init(allocator, false);
defer parser.deinit();
var tree = try parser.parse(response);
defer tree.deinit();
const args = tree.root.Object.get("args").?;
try std.testing.expectEqual(@as(usize, 0), args.Object.count());
const headers = tree.root.Object.get("headers").?;
const accept_header = headers.Object.get("Accept").?.String;
try std.testing.expectEqualStrings("*/*", accept_header);
const host_header = headers.Object.get("Host").?.String;
try std.testing.expectEqualStrings("httpbin.org", host_header);
const content_length = headers.Object.get("Content-Length").?.String;
try std.testing.expectEqualStrings("26", content_length);
const content_type = headers.Object.get("Content-Type").?.String;
try std.testing.expectEqualStrings("application/json", content_type);
const url = tree.root.Object.get("url").?.String;
try std.testing.expectEqualStrings("https://httpbin.org/post", url);
const data = tree.root.Object.get("data").?.String;
try std.testing.expectEqualStrings("{\"Post_Key\": \"Post_Value\"}", data);
const post_value = tree.root.Object.get("json").?.Object.get("Post_Key").?.String;
defer allocator.free(post_value);
try std.testing.expectEqualStrings("Post_Value", post_value);
}
|
src/request.zig
|
const std = @import("std");
pub const TokenType = enum {
// Single-character tokens.
LeftParen,
RightParen,
LeftBrace,
RightBrace,
Comma,
Dot,
Minus,
Plus,
Semicolon,
Slash,
Star,
// One or two character tokens.
Bang,
BangEqual,
Equal,
EqualEqual,
Greater,
GreaterEqual,
Less,
LessEqual,
// Literals.
Identifier,
String,
Number,
// Keywords.
And,
Class,
Else,
False,
For,
Fun,
If,
Nil,
Or,
Print,
Return,
Super,
This,
True,
Var,
While,
Error,
Eof,
};
pub const Token = struct {
tokenType: TokenType,
lexeme: []const u8,
line: usize,
};
fn isDigit(char: u8) bool {
return '0' <= char and char <= '9';
}
fn isAlpha(char: u8) bool {
return (('a' <= char and char <= 'z') or
('A' <= char and char <= 'Z') or
char == '_');
}
pub const Scanner = struct {
start: []const u8,
current: usize,
line: usize,
pub fn init(source: []const u8) Scanner {
return Scanner{
.start = source,
.current = 0,
.line = 1,
};
}
pub fn scanToken(self: *Scanner) Token {
self.skipWhitespace();
self.start = self.start[self.current..];
self.current = 0;
if (self.isAtEnd()) return self.makeToken(.Eof);
const c = self.peek();
self.advance();
return switch (c) {
'(' => self.makeToken(.LeftParen),
')' => self.makeToken(.RightParen),
'{' => self.makeToken(.LeftBrace),
'}' => self.makeToken(.RightBrace),
';' => self.makeToken(.Semicolon),
',' => self.makeToken(.Comma),
'.' => self.makeToken(.Dot),
'-' => self.makeToken(.Minus),
'+' => self.makeToken(.Plus),
'/' => self.makeToken(.Slash),
'*' => self.makeToken(.Star),
'!' => self.makeToken(if (self.match('=')) TokenType.BangEqual else TokenType.Bang),
'=' => self.makeToken(if (self.match('=')) TokenType.EqualEqual else TokenType.Equal),
'<' => self.makeToken(if (self.match('=')) TokenType.LessEqual else TokenType.Less),
'>' => self.makeToken(if (self.match('=')) TokenType.GreaterEqual else TokenType.Greater),
'"' => self.scanString(),
else => {
if (isDigit(c)) return self.scanNumber();
if (isAlpha(c)) return self.scanIdentifier();
if (c == 0) return self.makeToken(.Eof);
return self.makeError("Unexpected character.");
},
};
}
fn advance(self: *Scanner) void {
self.current += 1;
}
fn peek(self: *Scanner) u8 {
if (self.isAtEnd()) return 0;
return self.start[self.current];
}
fn peekNext(self: *Scanner) u8 {
if (self.current + 1 >= self.start.len) return 0;
return self.start[self.current + 1];
}
fn match(self: *Scanner, char: u8) bool {
if (self.isAtEnd()) return false;
if (self.peek() != char) return false;
self.current += 1;
return true;
}
fn isAtEnd(self: *Scanner) bool {
return self.current >= self.start.len;
}
fn makeToken(self: *Scanner, tokenType: TokenType) Token {
return Token{
.tokenType = tokenType,
.lexeme = self.start[0..self.current],
.line = self.line,
};
}
fn makeError(self: *Scanner, message: []const u8) Token {
return Token{
.tokenType = .Error,
.lexeme = message,
.line = self.line,
};
}
fn scanString(self: *Scanner) Token {
while (self.peek() != '"' and !self.isAtEnd()) {
if (self.peek() == '\n') self.line += 1;
self.advance();
}
if (self.isAtEnd()) return self.makeError("Unterminated string.");
// The closing quote
self.advance();
return self.makeToken(.String);
}
fn scanNumber(self: *Scanner) Token {
while (isDigit(self.peek())) self.advance();
// Look for a fractional part.
if (self.peek() == '.' and isDigit(self.peekNext())) {
// Consume the "."
self.advance();
while (isDigit(self.peek())) self.advance();
}
return self.makeToken(.Number);
}
fn scanIdentifier(self: *Scanner) Token {
while (isAlpha(self.peek()) or isDigit(self.peek())) self.advance();
return self.makeToken(self.identifierType());
}
fn identifierType(self: *Scanner) TokenType {
return switch (self.start[0]) {
'a' => self.checkKeyword(1, "nd", .And),
'c' => self.checkKeyword(1, "lass", .Class),
'e' => self.checkKeyword(1, "lse", .Else),
'i' => self.checkKeyword(1, "f", .If),
'n' => self.checkKeyword(1, "il", .Nil),
'o' => self.checkKeyword(1, "r", .Or),
'p' => self.checkKeyword(1, "rint", .Print),
'r' => self.checkKeyword(1, "eturn", .Return),
's' => self.checkKeyword(1, "uper", .Super),
'v' => self.checkKeyword(1, "ar", .Var),
'w' => self.checkKeyword(1, "hile", .While),
'f' => {
return switch (self.start[1]) {
'a' => self.checkKeyword(2, "lse", .False),
'o' => self.checkKeyword(2, "r", .For),
'u' => self.checkKeyword(2, "n", .Fun),
else => .Identifier,
};
},
't' => {
return switch (self.start[1]) {
'h' => self.checkKeyword(2, "is", .This),
'r' => self.checkKeyword(2, "ue", .True),
else => .Identifier,
};
},
else => .Identifier,
};
}
fn checkKeyword(self: *Scanner, offset: usize, str: []const u8, tokenType: TokenType) TokenType {
if (self.current != str.len + offset) return .Identifier;
const sourceSlice = self.start[offset..self.current];
std.debug.assert(sourceSlice.len == str.len);
return if (std.mem.eql(u8, sourceSlice, str)) tokenType else .Identifier;
}
fn skipWhitespace(self: *Scanner) void {
while (true) {
switch (self.peek()) {
' ', '\r', '\t' => self.advance(),
'\n' => {
self.line += 1;
self.advance();
},
'/' => {
if (self.peekNext() == '/') {
// A comment goes until the end of the line
while (self.peek() != '\n' and !self.isAtEnd()) {
self.advance();
}
} else {
return;
}
},
else => return,
}
}
}
};
|
src/scanner.zig
|
const std = @import("std");
const math = std.math;
const mem = std.mem;
const assert = std.debug.assert;
const config = @import("../config.zig");
const vsr = @import("../vsr.zig");
const MessagePool = @import("../message_pool.zig").MessagePool;
const Message = MessagePool.Message;
const MessageBus = @import("message_bus.zig").MessageBus;
const Process = @import("message_bus.zig").Process;
const PacketSimulator = @import("packet_simulator.zig").PacketSimulator;
const PacketSimulatorOptions = @import("packet_simulator.zig").PacketSimulatorOptions;
const PacketSimulatorPath = @import("packet_simulator.zig").Path;
const log = std.log.scoped(.network);
pub const NetworkOptions = struct {
packet_simulator_options: PacketSimulatorOptions,
};
pub const Network = struct {
pub const Packet = struct {
network: *Network,
message: *Message,
pub fn deinit(packet: *const Packet, path: PacketSimulatorPath) void {
const source_bus = &packet.network.busses.items[path.source];
source_bus.unref(packet.message);
}
};
pub const Path = struct {
source: Process,
target: Process,
};
allocator: *std.mem.Allocator,
options: NetworkOptions,
packet_simulator: PacketSimulator(Packet),
busses: std.ArrayListUnmanaged(MessageBus),
processes: std.ArrayListUnmanaged(u128),
pub fn init(
allocator: *std.mem.Allocator,
replica_count: u8,
client_count: u8,
options: NetworkOptions,
) !Network {
const process_count = client_count + replica_count;
assert(process_count <= std.math.maxInt(u8));
var busses = try std.ArrayListUnmanaged(MessageBus).initCapacity(allocator, process_count);
errdefer busses.deinit(allocator);
var processes = try std.ArrayListUnmanaged(u128).initCapacity(allocator, process_count);
errdefer processes.deinit(allocator);
const packet_simulator = try PacketSimulator(Packet).init(
allocator,
options.packet_simulator_options,
);
errdefer packet_simulator.deinit(allocator);
return Network{
.allocator = allocator,
.options = options,
.packet_simulator = packet_simulator,
.busses = busses,
.processes = processes,
};
}
pub fn deinit(network: *Network) void {
// TODO: deinit the busses themselves when they gain a deinit()
network.busses.deinit(network.allocator);
network.processes.deinit(network.allocator);
}
/// Returns the address (index into Network.busses)
pub fn init_message_bus(network: *Network, cluster: u32, process: Process) !*MessageBus {
const raw_process = switch (process) {
.replica => |replica| replica,
.client => |client| blk: {
assert(client >= config.replicas_max);
break :blk client;
},
};
for (network.processes.items) |p| assert(p != raw_process);
const bus = try MessageBus.init(network.allocator, cluster, process, network);
network.processes.appendAssumeCapacity(raw_process);
network.busses.appendAssumeCapacity(bus);
return &network.busses.items[network.busses.items.len - 1];
}
pub fn send_message(network: *Network, message: *Message, path: Path) void {
// TODO: we want to unref this message at some point between send()
// and recv() for better realism.
log.debug("send_message: {} > {}: {}", .{
path.source,
path.target,
message.header.command,
});
network.packet_simulator.submit_packet(
.{
.message = message.ref(),
.network = network,
},
deliver_message,
.{
.source = network.process_to_address(path.source),
.target = network.process_to_address(path.target),
},
);
}
fn process_to_address(network: *Network, process: Process) u8 {
for (network.processes.items) |p, i| {
if (std.meta.eql(raw_process_to_process(p), process)) return @intCast(u8, i);
}
unreachable;
}
pub fn get_message_bus(network: *Network, process: Process) *MessageBus {
return &network.busses.items[network.process_to_address(process)];
}
fn deliver_message(packet: Packet, path: PacketSimulatorPath) void {
const network = packet.network;
const source_bus = &network.busses.items[path.source];
const target_bus = &network.busses.items[path.target];
const message = target_bus.get_message() orelse {
log.debug("deliver_message: target message bus has no free messages, dropping", .{});
return;
};
defer target_bus.unref(message);
std.mem.copy(u8, message.buffer, packet.message.buffer);
const process_path = .{
.source = raw_process_to_process(network.processes.items[path.source]),
.target = raw_process_to_process(network.processes.items[path.target]),
};
log.debug("deliver_message: {} > {}: {}", .{
process_path.source,
process_path.target,
packet.message.header.command,
});
if (message.header.command == .request or message.header.command == .prepare) {
const sector_ceil = vsr.sector_ceil(message.header.size);
if (message.header.size != sector_ceil) {
assert(message.header.size < sector_ceil);
assert(message.buffer.len == config.message_size_max + config.sector_size);
mem.set(u8, message.buffer[message.header.size..sector_ceil], 0);
}
}
target_bus.on_message_callback.?(target_bus.on_message_context, message);
}
fn raw_process_to_process(raw: u128) Process {
switch (raw) {
0...(config.replicas_max - 1) => return .{ .replica = @intCast(u8, raw) },
else => {
assert(raw >= config.replicas_max);
return .{ .client = raw };
},
}
}
};
|
src/test/network.zig
|
const std = @import("std");
const zua = @import("zua");
const lex = zua.lex;
const parseString = zua.parse_literal.parseString;
// Tests for comparing parsed strings between Zua and Lua.
// Expects @import("build_options").fuzzed_strings_inputs_dir to be a path to
// a directory containing a corpus of inputs to test and
// @import("build_options").fuzzed_strings_outputs_dir to be a path to a
// directory containing the corresponding expected string after
// parsing.
//
// A usable inputs/outputs pair can be obtained from
// https://github.com/squeek502/fuzzing-lua
const verboseTestPrinting = false;
const build_options = @import("build_options");
const inputs_dir_path = build_options.fuzzed_strings_inputs_dir;
const outputs_dir_path = build_options.fuzzed_strings_outputs_dir;
test "string input/output pairs" {
var allocator = std.testing.allocator;
var inputs_dir = try std.fs.cwd().openDir(inputs_dir_path, .{ .iterate = true });
defer inputs_dir.close();
var outputs_dir = try std.fs.cwd().openDir(outputs_dir_path, .{});
defer outputs_dir.close();
var n: usize = 0;
var inputs_iterator = inputs_dir.iterate();
while (try inputs_iterator.next()) |entry| {
if (entry.kind != .File) continue;
if (verboseTestPrinting) {
std.debug.print("\n{s}\n", .{entry.name});
}
const contents = try inputs_dir.readFileAlloc(allocator, entry.name, std.math.maxInt(usize));
defer allocator.free(contents);
const expectedContents = try outputs_dir.readFileAlloc(allocator, entry.name, std.math.maxInt(usize));
defer allocator.free(expectedContents);
var lexer = lex.Lexer.init(contents, "fuzz");
while (true) {
const token = lexer.next() catch {
break;
};
if (token.id == lex.Token.Id.eof) break;
if (token.id != lex.Token.Id.string) continue;
const string_source = contents[token.start..token.end];
var buf = try allocator.alloc(u8, string_source.len);
defer allocator.free(buf);
const parsed = parseString(string_source, buf);
if (verboseTestPrinting) {
std.debug.print("got\n{x}\n", .{parsed});
std.debug.print("expected\n{x}\n", .{expectedContents});
}
try std.testing.expectEqualSlices(u8, expectedContents, parsed);
}
n += 1;
}
std.debug.print("\n{} input/output pairs checked...\n", .{n});
}
|
test/fuzzed_strings.zig
|
const std = @import("std");
const testing = std.testing;
const math = @import("std").math;
const Vec2 = @import("vec2.zig").Vec2;
const f_eq = @import("utils.zig").f_eq;
/// A Mat2 identity matrix
pub const mat2_identity = Mat2{
.data = .{
.{ 1.0, 0.0 },
.{ 0.0, 1.0 },
},
};
/// Creates a new Mat2 with the given values
pub fn mat2_values(m00: f32, m01: f32, m10: f32, m11: f32) Mat2 {
return Mat2{
.data = .{
.{ m00, m01 },
.{ m10, m11 },
},
};
}
pub const Mat2 = packed struct {
data: [2][2]f32,
pub fn identity() Mat2 {
return mat2_identity;
}
pub fn create(m00: f32, m01: f32, m10: f32, m11: f32) Mat2 {
return Mat2{
.data = .{
.{ m00, m01 },
.{ m10, m11 },
},
};
}
pub fn transpose(m: Mat2) Mat2 {
return Mat2{
.data = .{
.{ m.data[0][0], m.data[1][0] },
.{ m.data[0][1], m.data[1][1] },
},
};
}
/// Inverts the matrix
pub fn invert(m: Mat2) ?Mat2 {
var det = m.data[0][0] * m.data[1][1] - m.data[1][0] * m.data[0][1];
if (det == 0)
return null;
det = 1.0 / det;
return Mat2{
.data = .{
.{ m.data[1][1] * det, -m.data[0][1] * det },
.{ -m.data[1][0] * det, m.data[0][0] * det },
},
};
}
/// Calculates the adjugate
pub fn adjoint(m: Mat2) Mat2 {
return Mat2{
.data = .{
.{ m.data[1][1], -m.data[0][1] },
.{ -m.data[1][0], m.data[0][0] },
},
};
}
///Calculates the determinant
pub fn determinant(m: Mat2) f32 {
return m.data[0][0] * m.data[1][1] - m.data[1][0] * m.data[0][1];
}
///Multiplies two Mat2
pub fn multiply(m: Mat2, other: Mat2) Mat2 {
return Mat2{
.data = .{
.{ m.data[0][0] * other.data[0][0] + m.data[1][0] * other.data[0][1], m.data[0][1] * other.data[0][0] + m.data[1][1] * other.data[0][1] },
.{ m.data[0][0] * other.data[1][0] + m.data[1][0] * other.data[1][1], m.data[0][1] * other.data[1][0] + m.data[1][1] * other.data[1][1] },
},
};
}
pub const mul = multiply;
/// Rotates the matrix by a given angle
pub fn rotate(m: Mat2, rad: f32) Mat2 {
const s = @sin(rad);
const c = @cos(rad);
return Mat2{
.data = .{
.{ m.data[0][0] * c + m.data[1][0] * s, m.data[0][1] * c + m.data[1][1] * s },
.{ m.data[0][0] * -s + m.data[1][0] * c, m.data[0][1] * -s + m.data[1][1] * c },
},
};
}
///Scales the matrix by the dimentions in the given vec2
pub fn scale(m: Mat2, v: Vec2) Mat2 {
return Mat2{
.data = .{
.{ m.data[0][0] * v.x, m.data[0][1] * v.x },
.{ m.data[1][0] * v.y, m.data[1][1] * v.y },
},
};
}
pub fn add(m: Mat2, other: Mat2) Mat2 {
return Mat2{
.data = .{
.{ m.data[0][0] + other.data[0][0], m.data[0][1] + other.data[0][1] },
.{ m.data[1][0] + other.data[1][0], m.data[1][1] + other.data[1][1] },
},
};
}
pub fn substract(m: Mat2, other: Mat2) Mat2 {
return Mat2{
.data = .{
.{ m.data[0][0] - other.data[0][0], m.data[0][1] - other.data[0][1] },
.{ m.data[1][0] - other.data[1][0], m.data[1][1] - other.data[1][1] },
},
};
}
pub const sub = substract;
///Multiply each element by a scalar
pub fn multiplyScalar(m: Mat2, s: f32) Mat2 {
return Mat2{
.data = .{
.{ m.data[0][0] * s, m.data[0][1] * s },
.{ m.data[1][0] * s, m.data[1][1] * s },
},
};
}
///Creates a matrix from a given angle
pub fn from_rotation(rad: f32) Mat2 {
const s = @sin(rad);
const c = @cos(rad);
return Mat2{
.data = .{
.{ c, s },
.{ -s, c },
},
};
}
///Creates a matrix from a vector scaling
pub fn from_scaling(v: Vec2) Mat2 {
return Mat2{
.data = .{
.{ v.x, 0.0 },
.{ 0.0, v.y },
},
};
}
pub fn equals(a: Mat2, b: Mat2) bool {
return f_eq(a.data[0][0], b.data[0][0]) //
and f_eq(a.data[0][1], b.data[0][1]) //
and f_eq(a.data[1][0], b.data[1][0]) //
and f_eq(a.data[1][1], b.data[1][1]);
}
pub fn format(
value: @This(),
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = options;
_ = fmt;
return std.fmt.format(
writer,
"Mat2({d:.3}, {d:.3}, {d:.3}, {d:.3})",
.{ value.data[0][0], value.data[0][1], value.data[1][0], value.data[1][1] },
);
}
test "identity" {
const out = Mat2.identity();
const expected = Mat2{
.data = .{
.{ 1.0, 0.0 },
.{ 0.0, 1.0 },
},
};
try testing.expect(Mat2.equals(out, expected));
}
test "transpose" {
const matA = Mat2.create(1.0, 2.0, 3.0, 4.0);
const out = matA.transpose();
const expected = Mat2.create(1.0, 3.0, 2.0, 4.0);
try testing.expect(Mat2.equals(out, expected));
}
test "invert" {
const matA = Mat2.create(1.0, 2.0, 3.0, 4.0);
const out = matA.invert() orelse @panic("could not invert mat2");
const expected = Mat2.create(-2, 1.0, 1.5, -0.5);
try testing.expect(Mat2.equals(out, expected));
}
test "adjoint" {
const matA = Mat2.create(1.0, 2.0, 3.0, 4.0);
const out = matA.adjoint();
const expected = Mat2.create(4, -2, -3, 1);
try testing.expect(Mat2.equals(out, expected));
}
test "determinant" {
const matA = Mat2.create(1.0, 2.0, 3.0, 4.0);
const out = matA.determinant();
try testing.expectEqual(out, -2);
}
test "multiply" {
const matA = Mat2.create(1.0, 2.0, 3.0, 4.0);
const matB = Mat2.create(5.0, 6.0, 7.0, 8.0);
const out = matA.mul(matB);
const expected = Mat2.create(23.0, 34.0, 31.0, 46.0);
try testing.expect(Mat2.equals(out, expected));
}
test "rotate" {
const matA = Mat2.create(1.0, 2.0, 3.0, 4.0);
const out = matA.rotate(math.pi * 0.5);
const expected = Mat2.create(3, 4.0, -1.0, -2.0);
try testing.expect(Mat2.equals(out, expected));
}
test "scale" {
const matA = Mat2.create(1.0, 2.0, 3.0, 4.0);
const out = matA.scale(Vec2.create(2, 3));
const expected = Mat2.create(2.0, 4.0, 9.0, 12.0);
try testing.expect(Mat2.equals(out, expected));
}
test "add" {
const matA = Mat2.create(1.0, 2.0, 3.0, 4.0);
const matB = Mat2.create(5.0, 6.0, 7.0, 8.0);
const out = matA.add(matB);
const expected = Mat2.create(6.0, 8.0, 10.0, 12.0);
try testing.expect(Mat2.equals(out, expected));
}
test "substract" {
const matA = Mat2.create(1.0, 2.0, 3.0, 4.0);
const matB = Mat2.create(5.0, 6.0, 7.0, 8.0);
const out = matA.sub(matB);
const expected = Mat2.create(-4, -4, -4, -4);
try testing.expect(Mat2.equals(out, expected));
}
test "equals" {
const out = mat2_identity;
const expected = Mat2.create(1.0, 0.0, 0.0, 1.0);
try testing.expect(Mat2.equals(out, expected));
const notExpected = Mat2.create(5.0, 6.0, 7.0, 8.0);
try testing.expect(!Mat2.equals(out, notExpected));
}
};
|
src/mat2.zig
|
const std = @import("std");
const ArrayList = std.ArrayList;
const LinkedList = std.SinglyLinkedList;
const HashMap = std.StringHashMap;
const Allocator = std.mem.Allocator;
const ImmutableAssignments = false;
const MaxDepth = 300;
// === Assignment Parameters ===
// In order to be as flexible as possible and allow for userland access
// to lambdas and error streams, the assignment directly contains the
// assignment name and the Resolved Action type.
const Assignment = struct {
name: []const u8,
value: ResolvedAction,
};
// === Closures ===
// Since there are extremely powerful structures that can contain their
// own scope, values and operations, this system is built around implementing
// functions as closures directly, allowing for significant flexibilty and
// the possibility of user generated functions and partial application.
// NOTICE: Current limitation of zig prevents structs from self referencing like
// is required to allow a lambda type signature that includes a lambda type signature
const Signature = struct {
name: []const u8,
argT: ArgumentTypes,
};
const ClosureT = struct {
argumentList: ArrayList(Signature),
returnType: ArgumentTypes,
};
const Closure = struct {
typeSignature: ClosureT,
procedures: ArrayList(Action),
};
// === Function Call Parameters ===
// Defines every valid type that can be received by a function, including
// scalar values, void, lambdas and error lists.
const ArgumentTypes = union(enum) {
void: struct {},
integer: i32,
unsigned: u32,
float: f32,
boolean: bool,
character: u8,
string: []const u8,
lambda: *const ClosureT,
errlst: usize,
};
const CallParameters = struct {
target: []const u8,
arguments: ArrayList([]const u8),
returnType: ArgumentTypes,
};
const Action = union(enum) {
call: CallParameters,
let: Assignment,
};
const ResolvedAction = union(enum) {
integer: i32,
unsigned: u32,
float: f32,
boolean: bool,
character: u8,
string: []const u8,
call: CallParameters,
lambda: Closure,
errlst: ArrayList(ErrorEntry),
void: struct {},
};
// === Type Resolution ===
// As this system uses encapsulated data, there must be a solution for
// extracting the type information from a particular value, especially
// for lambdas with their embedded type signatures
pub fn getType(ra: ResolvedAction) ArgumentTypes {
return switch (ra) {
.integer => ArgumentTypes{ .integer = -1 },
.unsigned => ArgumentTypes{ .unsigned = 0 },
.float => ArgumentTypes{ .float = 1.0 },
.boolean => ArgumentTypes{ .boolean = true },
.character => ArgumentTypes{ .character = 'A' },
.string => ArgumentTypes{ .string = "" },
.call => |c| c.returnType,
.lambda => |l| ArgumentTypes{ .lambda = &l.typeSignature },
.errlst => |e| ArgumentTypes{ .errlst = e.items.len },
.void => ArgumentTypes{ .void = .{} },
};
}
pub fn isAcceptedType(t1: ArgumentTypes, t2: ArgumentTypes) bool {
return switch (t2) {
.void => switch (t1) {
.void => true,
else => false,
},
.lambda => |l2| switch (t1) {
.lambda => |l1| (l1 == l2),
else => false,
},
.errlst => switch (t1) {
.errlst => true,
else => false,
},
.integer => switch (t1) {
.integer => true,
else => false,
},
.unsigned => switch (t1) {
.unsigned => true,
else => false,
},
.float => switch (t1) {
.float => true,
else => false,
},
.boolean => switch (t1) {
.boolean => true,
else => false,
},
.character => switch (t1) {
.character => true,
else => false,
},
.string => switch (t1) {
.string => true,
else => false,
},
};
}
// === Error Handling and Generation ===
// A simple set of handlers for generating error messages
// consistantly whilst improving general code hygiene
const ErrorEntry = struct {
target: []const u8,
msg: []const u8,
};
fn makeError(target: []const u8, msg: []const u8, alloc: *Allocator) ResolvedAction {
var errLst = ArrayList(ErrorEntry).initCapacity(alloc, 1) catch {
return ResolvedAction{ .void = .{} };
};
var errEntry = ErrorEntry{
.target = target,
.msg = msg,
};
errLst.appendAssumeCapacity(errEntry);
return ResolvedAction{ .errlst = errLst };
}
fn appendError(ra: *ResolvedAction, target: []const u8, msg: []const u8, alloc: *Allocator) ResolvedAction {
switch (ra.*) {
.errlst => {
var errEntry = ErrorEntry{ .target = target, .msg = msg };
var originalLength = ra.errlst.capacity;
var newErrorList = ArrayList(ErrorEntry).initCapacity(alloc, ra.errlst.capacity + 1) catch
return makeError(target, "Not enough memory to reallocate error list", alloc);
newErrorList.appendSliceAssumeCapacity(ra.errlst.toOwnedSlice());
newErrorList.appendAssumeCapacity(errEntry);
ra.errlst.deinit();
return ResolvedAction{ .errlst = newErrorList };
},
else => return makeError(target, msg, alloc),
}
}
// === Assignment Call Execution ===
// As an assignment can be any of the following: Scalar Value, Lambda, Error List
// the call to retrieve those values has to be flexible enough to accomodate that
fn call(c: CallParameters, scopes: *ArrayList(*HashMap(Assignment)), alloc: *Allocator) ResolvedAction {
// Search for function in available scopes
var function = retrieveAssignment(c.target, scopes);
if (function == null)
return makeError(c.target, "Assignment value is not defined in accessible scopes", alloc);
// Check if value is scalar or error and return if so
switch (function.?.value) {
.lambda => |l| {
if (isAcceptedType(l.typeSignature.returnType, c.returnType)) {
var res = apply(l, c.arguments, scopes, alloc);
var resT = getType(res);
if (isAcceptedType(resT, l.typeSignature.returnType)) {
return res;
} else {
return appendError(&res, c.target, "Lambda failed to match promised return type", alloc);
}
} else {
return makeError(c.target, "Lambda return type is not accepted by call return type", alloc);
}
},
.call => |c1| return call(c1, scopes, alloc),
else => return function.?.value,
}
}
// === Argument Type Checkng and Assignment ===
// While it's not ideal to combine Assignment with Type Checking, it reduces the number of
// times the argument has to be iterated over, helping with performance in larger programs
fn typeCheckAndScope(args: *ArrayList(ResolvedAction), typeSig: ClosureT, scope: *HashMap(Assignment)) ?ErrorEntry {
for (args.items) |arg, index| {
var tmp = typeSig.argumentList.items[index];
if (isAcceptedType(getType(arg), tmp.argT)) {
return ErrorEntry{ .target = tmp.name, .msg = "Argument does not match expected type" };
} else {
if (ImmutableAssignments and newScope.contains(tmp.name)) {
return ErrorEntry{ .target = tmp.name, .msg = "Assignment already exists in this scope" };
} else {
scope.*.put(tmp.name, Assignment{
.name = tmp.name,
.value = arg,
}) catch
return ErrorEntry{ .target = tmp.name, .msg = "Failed to add value to scope" };
}
}
}
return null;
}
// === Lambda Function Application ===
// By treating every function call as a lambda, it greatly simplifies the interface
// and allows for first class function definition without requiring an assignment,
// this is particularly essential for partial application and monad implementation
fn apply(lambda: Closure, argList: ArrayList([]const u8), scopes: *ArrayList(*HashMap(Assignment)), alloc: *Allocator) ResolvedAction {
if (argList.capacity != lambda.typeSignature.argumentList.capacity)
return makeError("Apply", "Function expects a different number of arguments", alloc);
// Try and find arguments in list and place in newly allocated memory
// or fail and deallocate with defer
var arguments = ArrayList(Assignment).initCapacity(alloc, argList.capacity) catch
return makeError("Apply", "Argument List Allocation Failed", alloc);
defer arguments.deinit();
for (argList.items) |arg| {
if (retrieveAssignment(arg, scopes)) |ass| {
arguments.append(ass) catch
return makeError(arg, "Failed to append acquired argument to ArrayList", alloc);
} else {
return makeError(arg, "Argument not found in accessible scope", alloc);
}
}
// Resolve arguments to scalar or lambda values to newly allocated memory,
// or fail and deallocate with defer
var resolvedArgs = ArrayList(ResolvedAction).initCapacity(alloc, arguments.capacity) catch
return makeError("Apply", "Resolved Argument List Allocation Failed", alloc);
defer resolvedArgs.deinit();
for (arguments.items) |arg| {
resolvedArgs.append(resolve(arg.value, scopes, alloc)) catch
return makeError(arg.name, "Failed to append resolved value to ArrayList", alloc);
}
// Type check resolved values against closure type signature and assign to scope
// or fail and deallocate with defer
var newScope = HashMap(Assignment).init(alloc);
defer newScope.deinit();
if (typeCheckAndScope(&resolvedArgs, lambda.typeSignature, &newScope)) |err| {
return makeError(err.target, err.msg, alloc);
}
// Begin closure execution with new scope
return execute(lambda, &newScope, scopes, alloc);
}
// It's worth noting that due to how ArrayList works, the Array is actually
// ordered in oldest to newest, so the scope searches have to be done in reverse
fn retrieveAssignment(key: []const u8, scopes: *ArrayList(*HashMap(Assignment))) ?Assignment {
var assignment: ?Assignment = null;
var iterator = scopes.capacity;
var scopePointers = scopes.items;
while (iterator >= 0) : (iterator -= 1) {
if (scopePointers[iterator].*.get(key)) |func| {
assignment = func;
break;
}
}
return assignment;
}
// === Closure Execution ===
// As a closure can contain multiple state manipulating procedures, the
// execution function has to be able to maintain that state of the current
// scope as well as be able to pull from higher scopes for function calls.
// It also has to be able to always return a value, and since any function
// could set the return value it has to be given a known name, this means
// generating an assigment and always checking its value when the user returns.
fn execute(lambda: Closure, current: *HashMap(Assignment), scopes: *ArrayList(*HashMap(Assignment)), alloc: *Allocator) ResolvedAction {
scopes.ensureCapacity(scopes.capacity + 1) catch
return makeError("Lambda", "Not Enough Memory to extend scopes", alloc);
scopes.appendAssumeCapacity(current);
defer _ = scopes.pop();
for (lambda.procedures.items) |proc| {
_ = switch (proc) {
.let => |l| if (ImmutableAssignments and current.contains(l.name)) {
return makeError(l.name, "Assignment already exists in this scope", alloc);
} else {
current.put(l.name, Assignment{ .name = l.name, .value = resolve(l.value, scopes, alloc) }) catch {
return makeError(l.name, "Failed to assign to current scope", alloc);
};
},
.call => |c| _ = call(c, scopes, alloc),
};
if (current.get("lambda_return_value")) |ret| {
if (isAcceptedType(getType(ret.value), lambda.typeSignature.returnType)) {
return ret.value;
} else {
return makeError(ret.name, "Value does not match expected return type", alloc);
}
}
}
current.deinit();
return ResolvedAction{ .void = .{} };
}
fn resolve(ra: ResolvedAction, scopes: *ArrayList(*HashMap(Assignment)), alloc: *Allocator) ResolvedAction {
var res = ra;
var depth: usize = 0;
while (true) {
res = switch (res) {
// This does have the possibility of an infinitely recursive
// execution flow, but passing the current function name
// and/or all parent names would break lambda usage and
// allowing this is required to allow for name aliasing
.call => |c| if (depth < MaxDepth) call(c, scopes, alloc) else makeError("Resolution", "Program Reached Max Call Depth", alloc),
else => break,
};
}
return res;
}
// === Debug Functions ===
// As most debugging is rather challenging to do at compile time
// these functions are specifically intended to stringify values
// for console level debugging output.
fn concatStrings(arr: ArrayList([]const u8), alloc: *Allocator) Allocator.Error![]const u8 {
var length: usize = 0;
for (arr.items) |str| {
length += str.len;
}
var buffer = try alloc.alloc(u8, length);
length = 0;
for (arr.items) |str| {
std.mem.copy(u8, buffer[length..], str);
length += str.len;
}
return buffer;
}
fn lambdaTypeString(cT: *const ClosureT, alloc: *Allocator) Allocator.Error![]const u8 {
var argStrings = ArrayList([]const u8).init(alloc);
defer argStrings.deinit();
try argStrings.append("Lambda: (");
for (cT.argumentList.items) |sig| {
var tyStr = try typeString(sig.argT, alloc);
try argStrings.append(tyStr);
try argStrings.append(" -> ");
}
var retStr = try typeString(cT.returnType, alloc);
try argStrings.append(retStr);
try argStrings.append(")");
var str = concatStrings(argStrings, alloc);
alloc.free(retStr);
return str;
}
fn printErrorList(errlst: ArrayList(ErrorEntry)) !void {
const stdout = std.io.getStdOut().writer();
try stdout.print("Error List:\n", .{});
for (errlst.items) |errorEntry| {
try stdout.print("[Target: {}] Message: {}.\n", .{ errorEntry.target, errorEntry.msg });
}
}
// This has to copy any compile time known strings into a buffer to
// ensure a consistant interface, otherwise the caller would have
// to check the type of t to see if it was a lambda, which would
// be the only option that does allocate memory.
fn mkBuffer(str: []const u8, alloc: *Allocator) Allocator.Error![]const u8 {
var buffer = try alloc.alloc(u8, str.len);
std.mem.copy(u8, buffer[0..], str);
return buffer;
}
fn typeString(t: ArgumentTypes, alloc: *Allocator) Allocator.Error![]const u8 {
return switch (t) {
.lambda => |l| lambdaTypeString(l, alloc),
.errlst => mkBuffer("Error List", alloc),
.void => mkBuffer("Void", alloc),
.integer => mkBuffer("Integer", alloc),
.unsigned => mkBuffer("Unsigned", alloc),
.float => mkBuffer("Float", alloc),
.boolean => mkBuffer("Boolean", alloc),
.character => mkBuffer("Character", alloc),
.string => mkBuffer("String", alloc),
};
}
// === Unit Testing ===
// As with any program, proper functionally must be ensured and
// zig's inbuilt unit testing facility makes this easy as can
// be seen below.
test "Type checking tests" {
var alloc = std.testing.allocator;
var a = ResolvedAction{ .void = .{} };
var b = ResolvedAction{ .integer = 5 };
var c = ResolvedAction{
.call = CallParameters{
.target = "test",
.arguments = ArrayList([]const u8).init(alloc),
.returnType = ArgumentTypes{ .void = .{} },
},
};
var d = ResolvedAction{
.lambda = Closure{
.typeSignature = ClosureT{
.argumentList = ArrayList(Signature).init(alloc),
.returnType = ArgumentTypes{ .void = .{} },
},
.procedures = ArrayList(Action).init(alloc),
},
};
const stdout = std.io.getStdOut().writer();
var aTS = try typeString(getType(a), alloc);
try stdout.print("\nThe value of 'a' is of type: [{}]\n", .{aTS});
std.testing.expect(isAcceptedType(getType(a), ArgumentTypes{ .void = .{} }));
alloc.free(aTS);
var bTS = try typeString(getType(b), alloc);
try stdout.print("The value of 'b' is of type: [{}]\n", .{bTS});
std.testing.expect(isAcceptedType(getType(b), ArgumentTypes{ .integer = -1 }));
alloc.free(bTS);
var cTS = try typeString(getType(c), alloc);
try stdout.print("The value of 'c' is of type: [{}]\n", .{cTS});
std.testing.expect(isAcceptedType(getType(c), ArgumentTypes{ .void = .{} }));
alloc.free(cTS);
var dTS = try typeString(getType(d), alloc);
try stdout.print("The value of 'd' is of type: [{}]\n", .{dTS});
std.testing.expect(isAcceptedType(getType(d), getType(d)));
alloc.free(dTS);
}
test "Simple Error" {
var alloc = std.testing.allocator;
var err = try ArrayList(ErrorEntry).initCapacity(alloc, 2);
try err.append(ErrorEntry{
.target = "Test 1",
.msg = "Testing a single error",
});
try printErrorList(err);
err.appendAssumeCapacity(ErrorEntry{
.target = "Test 2",
.msg = "Testing consequetive errors",
});
try printErrorList(err);
err.deinit();
var err3 = makeError("Test 3", "Testing makeError function", alloc);
try printErrorList(err3.errlst);
//var err4 = appendError(&err3, "Test 4", "Testing appendError function", alloc);
err3.errlst.deinit();
//err4.errlst.deinit();
}
test "Simple Execution" {
var alloc = std.testing.allocator;
var actions = [_]Action{
Action{
.let = Assignment{
.name = "lambda_return_value",
.value = ResolvedAction{ .integer = 5 },
},
},
};
var typeSig = ClosureT{
.argumentList = ArrayList(Signature).init(alloc),
.returnType = ArgumentTypes{ .integer = 0 },
};
var lambda = Closure{
.typeSignature = typeSig,
.procedures = ArrayList(Action).fromOwnedSlice(alloc, actions[0..]),
};
var currentScope = HashMap(Assignment).init(alloc);
defer currentScope.deinit();
var scopes = ArrayList(*HashMap(Assignment)).init(alloc);
var result = execute(lambda, ¤tScope, &scopes, alloc);
scopes.deinit();
var resT = getType(result);
const stdout = std.io.getStdOut().writer();
var tStr = try typeString(resT, alloc);
defer alloc.free(tStr);
try stdout.print("The returned value is of type: [{}]\n", .{tStr});
if (isAcceptedType(resT, ArgumentTypes{ .errlst = 0 })) {
try printErrorList(result.errlst);
} else {
std.testing.expect(isAcceptedType(resT, ArgumentTypes{ .integer = -1 }));
}
}
|
base.zig
|
const std = @import("std");
const gl = @import("../deps/zgl/zgl.zig");
const gltf = @import("gltf.zig");
const util = @import("util.zig");
const zm = @import("zm.zig");
pub fn Renderer(comptime Context: type, comptime activate: fn (Context) void) type {
return struct {
allocator: *std.mem.Allocator,
context: Context,
file: gltf.File,
prog: gl.Program,
vao: gl.VertexArray,
buffers: []gl.Buffer,
// Uniforms
u: struct {
transform: ?u32,
},
const Self = @This();
pub fn init(allocator: *std.mem.Allocator, context: Context, file: gltf.File) !Self {
var self: Self = undefined;
self.allocator = allocator;
self.context = context;
self.file = file;
activate(self.context);
self.prog = try util.loadProgram("opaque");
errdefer self.prog.delete();
self.vao = gl.createVertexArray();
errdefer self.vao.delete();
if (self.file.scene == null) {
if (self.file.scenes.len != 1) {
return error.NoDefaultScene;
} else {
self.file.scene = &self.file.scenes[0];
}
}
self.buffers = try self.allocator.alloc(gl.Buffer, self.file.buffers.len);
errdefer self.allocator.free(self.buffers);
gl.createBuffers(self.buffers);
errdefer gl.deleteBuffers(self.buffers);
for (self.file.buffers) |buffer, i| {
self.buffers[i].storage(u8, buffer.len, buffer.ptr, .{});
}
for (self.file.buffer_views) |view, i| {
if (view.target != .array_buffer) continue;
self.vao.vertexBuffer(
@intCast(u32, i),
self.buffers[view.buffer],
view.byte_offset,
view.byte_stride,
);
}
inline for (comptime std.meta.fieldNames(@TypeOf(self.u))) |name| {
@field(self.u, name) = self.prog.uniformLocation("u_" ++ name);
}
return self;
}
pub fn deinit(self: *Self) void {
gl.deleteBuffers(self.buffers);
self.allocator.free(self.buffers);
self.vao.delete();
self.prog.delete();
self.file.deinit();
}
pub fn draw(self: *Self) void {
activate(self.context);
gl.clearColor(0, 0, 0, 0);
gl.clear(.{ .color = true, .depth = true });
self.vao.bind();
defer gl.bindVertexArray(.invalid);
self.prog.use();
defer gl.useProgram(.invalid);
for (self.file.scene.?.nodes) |node| {
self.drawNode(node.*, zm.id(4));
}
}
fn drawNode(self: *Self, node: gltf.Node, transform: zm.Mat(4, 4)) void {
const matrix = zm.mat(4, 4, node.matrix).mul(transform);
if (node.mesh) |mesh| {
self.prog.uniformMatrix4(self.u.transform, true, &.{matrix.colMajor()});
for (mesh.primitives) |prim| {
self.drawPrimitive(prim);
}
}
for (node.children) |child| {
self.drawNode(child.*, matrix);
}
}
fn drawPrimitive(self: *Self, prim: gltf.Mesh.Primitive) void {
self.bindAttributes(prim.attributes);
defer self.unbindAttributes(prim.attributes);
if (prim.indices) |index_accessor| {
const accessor = self.file.accessors[index_accessor];
// TODO: don't spam these log messages every frame
// Maybe also add info on which node or mesh the primitive is attached to
if (accessor.components != 1) {
std.log.warn("Skipping element buffer of non-scalar type", .{});
return;
}
const elem_type = std.meta.intToEnum(gl.ElementType, @enumToInt(accessor.component_type)) catch {
std.log.warn("Skipping element buffer of invalid element type", .{});
return;
};
const view = self.file.buffer_views[accessor.buffer_view];
if (view.byte_stride != util.glSizeOf(@intToEnum(gl.Type, @enumToInt(elem_type)))) {
std.log.warn("Skipping element buffer of incorrect stride", .{});
return;
}
gl.bindBuffer(self.buffers[view.buffer], .element_array_buffer);
gl.drawElements(prim.mode, accessor.count, elem_type, accessor.byte_offset + view.byte_offset);
} else {
const count: u32 = inline for (attr_map) |m| {
if (@field(prim.attributes, m.name)) |attr| {
break self.file.accessors[attr].count;
}
} else {
std.log.warn("Skipping primitive with no attributes", .{});
return;
};
gl.drawArrays(prim.mode, 0, count);
}
}
fn bindAttributes(self: *Self, attrs: gltf.Mesh.Attributes) void {
inline for (attr_map) |m| {
if (@field(attrs, m.name)) |attr| {
const accessor = self.file.accessors[attr];
self.vao.enableVertexAttribute(m.loc);
self.vao.attribBinding(m.loc, accessor.buffer_view);
self.vao.attribFormat(m.loc, accessor.components, accessor.component_type, accessor.normalized, accessor.byte_offset);
}
}
}
fn unbindAttributes(self: *Self, attrs: gltf.Mesh.Attributes) void {
inline for (attr_map) |m| {
if (@field(attrs, m.name)) |_| {
self.vao.disableVertexAttribute(m.loc);
}
}
}
const attr_map = [_]struct {
name: []const u8,
loc: u32,
}{
.{ .name = "position", .loc = 0 },
.{ .name = "normal", .loc = 1 },
.{ .name = "color_0", .loc = 2 },
};
};
}
|
src/render.zig
|
const build_options = @import("build_options");
const std = @import("std");
const mem = std.mem;
const os = std.os;
const wlr = @import("wlroots");
const wl = @import("wayland").server.wl;
const pixman = @import("pixman");
const server = &@import("main.zig").server;
const util = @import("util.zig");
const Box = @import("Box.zig");
const LayerSurface = @import("LayerSurface.zig");
const Output = @import("Output.zig");
const Server = @import("Server.zig");
const View = @import("View.zig");
const ViewStack = @import("view_stack.zig").ViewStack;
const log = std.log.scoped(.render);
const SurfaceRenderData = struct {
output: *const Output,
/// In output layout coordinates relative to the output
output_x: i32,
output_y: i32,
when: *os.timespec,
};
/// The rendering order in this function must be kept in sync with Cursor.surfaceAt()
pub fn renderOutput(output: *Output) void {
const renderer = output.wlr_output.backend.getRenderer().?;
var now: os.timespec = undefined;
os.clock_gettime(os.CLOCK_MONOTONIC, &now) catch @panic("CLOCK_MONOTONIC not supported");
var needs_frame: bool = undefined;
var damage_region: pixman.Region32 = undefined;
damage_region.init();
defer damage_region.deinit();
output.damage.attachRender(&needs_frame, &damage_region) catch {
log.err("failed to attach renderer", .{});
return;
};
if (!needs_frame) {
output.wlr_output.rollback();
return;
}
renderer.begin(@intCast(u32, output.wlr_output.width), @intCast(u32, output.wlr_output.height));
// Find the first visible fullscreen view in the stack if there is one
var it = ViewStack(View).iter(output.views.first, .forward, output.current.tags, renderFilter);
const fullscreen_view = while (it.next()) |view| {
if (view.current.fullscreen) break view;
} else null;
// If we have a fullscreen view to render, render it.
if (fullscreen_view) |view| {
// Always clear with solid black for fullscreen
renderer.clear(&[_]f32{ 0, 0, 0, 1 });
renderView(output, view, &now);
if (build_options.xwayland) renderXwaylandUnmanaged(output, &now);
} else {
// No fullscreen view, so render normal layers/views
renderer.clear(&server.config.background_color);
renderLayer(output, output.getLayer(.background).*, &now, .toplevels);
renderLayer(output, output.getLayer(.bottom).*, &now, .toplevels);
// The first view in the list is "on top" so always iterate in reverse.
// non-focused, non-floating views
it = ViewStack(View).iter(output.views.last, .reverse, output.current.tags, renderFilter);
while (it.next()) |view| {
if (view.current.focus != 0 or view.current.float) continue;
if (view.draw_borders) renderBorders(output, view, &now);
renderView(output, view, &now);
}
// focused, non-floating views
it = ViewStack(View).iter(output.views.last, .reverse, output.current.tags, renderFilter);
while (it.next()) |view| {
if (view.current.focus == 0 or view.current.float) continue;
if (view.draw_borders) renderBorders(output, view, &now);
renderView(output, view, &now);
}
// non-focused, floating views
it = ViewStack(View).iter(output.views.last, .reverse, output.current.tags, renderFilter);
while (it.next()) |view| {
if (view.current.focus != 0 or !view.current.float) continue;
if (view.draw_borders) renderBorders(output, view, &now);
renderView(output, view, &now);
}
// focused, floating views
it = ViewStack(View).iter(output.views.last, .reverse, output.current.tags, renderFilter);
while (it.next()) |view| {
if (view.current.focus == 0 or !view.current.float) continue;
if (view.draw_borders) renderBorders(output, view, &now);
renderView(output, view, &now);
}
if (build_options.xwayland) renderXwaylandUnmanaged(output, &now);
renderLayer(output, output.getLayer(.top).*, &now, .toplevels);
renderLayer(output, output.getLayer(.background).*, &now, .popups);
renderLayer(output, output.getLayer(.bottom).*, &now, .popups);
renderLayer(output, output.getLayer(.top).*, &now, .popups);
}
// The overlay layer is rendered in both fullscreen and normal cases
renderLayer(output, output.getLayer(.overlay).*, &now, .toplevels);
renderLayer(output, output.getLayer(.overlay).*, &now, .popups);
renderDragIcons(output, &now);
// Hardware cursors are rendered by the GPU on a separate plane, and can be
// moved around without re-rendering what's beneath them - which is more
// efficient. However, not all hardware supports hardware cursors. For this
// reason, wlroots provides a software fallback, which we ask it to render
// here. wlr_cursor handles configuring hardware vs software cursors for you,
// and this function is a no-op when hardware cursors are in use.
output.wlr_output.renderSoftwareCursors(null);
// Conclude rendering and swap the buffers, showing the final frame
// on-screen.
renderer.end();
// TODO: handle failure
output.wlr_output.commit() catch
log.err("output commit failed for {s}", .{mem.sliceTo(&output.wlr_output.name, 0)});
}
fn renderFilter(view: *View, filter_tags: u32) bool {
// This check prevents a race condition when a frame is requested
// between mapping of a view and the first configure being handled.
if (view.current.box.width == 0 or view.current.box.height == 0)
return false;
return view.current.tags & filter_tags != 0;
}
/// Render all surfaces on the passed layer
fn renderLayer(
output: *const Output,
layer: std.TailQueue(LayerSurface),
now: *os.timespec,
role: enum { toplevels, popups },
) void {
var it = layer.first;
while (it) |node| : (it = node.next) {
const layer_surface = &node.data;
var rdata = SurfaceRenderData{
.output = output,
.output_x = layer_surface.box.x,
.output_y = layer_surface.box.y,
.when = now,
};
switch (role) {
.toplevels => layer_surface.wlr_layer_surface.surface.forEachSurface(
*SurfaceRenderData,
renderSurfaceIterator,
&rdata,
),
.popups => layer_surface.wlr_layer_surface.forEachPopupSurface(
*SurfaceRenderData,
renderSurfaceIterator,
&rdata,
),
}
}
}
/// Render all surfaces in the view's surface tree, including subsurfaces and popups
fn renderView(output: *const Output, view: *View, now: *os.timespec) void {
// If we have saved buffers, we are in the middle of a transaction
// and need to render those buffers until the transaction is complete.
if (view.saved_buffers.items.len != 0) {
for (view.saved_buffers.items) |saved_buffer| {
const texture = saved_buffer.client_buffer.texture orelse continue;
renderTexture(
output,
texture,
.{
.x = saved_buffer.surface_box.x + view.current.box.x - view.saved_surface_box.x,
.y = saved_buffer.surface_box.y + view.current.box.y - view.saved_surface_box.y,
.width = @intCast(c_int, saved_buffer.surface_box.width),
.height = @intCast(c_int, saved_buffer.surface_box.height),
},
&saved_buffer.source_box,
saved_buffer.transform,
);
}
} else {
// Since there are no stashed buffers, we are not in the middle of
// a transaction and may simply render the most recent buffers provided
// by the client.
var rdata = SurfaceRenderData{
.output = output,
.output_x = view.current.box.x - view.surface_box.x,
.output_y = view.current.box.y - view.surface_box.y,
.when = now,
};
view.forEachSurface(*SurfaceRenderData, renderSurfaceIterator, &rdata);
}
}
fn renderDragIcons(output: *const Output, now: *os.timespec) void {
const output_box = server.root.output_layout.getBox(output.wlr_output).?;
var it = server.root.drag_icons.first;
while (it) |node| : (it = node.next) {
const drag_icon = &node.data;
var rdata = SurfaceRenderData{
.output = output,
.output_x = @floatToInt(i32, drag_icon.seat.cursor.wlr_cursor.x) +
drag_icon.wlr_drag_icon.surface.sx - output_box.x,
.output_y = @floatToInt(i32, drag_icon.seat.cursor.wlr_cursor.y) +
drag_icon.wlr_drag_icon.surface.sy - output_box.y,
.when = now,
};
drag_icon.wlr_drag_icon.surface.forEachSurface(*SurfaceRenderData, renderSurfaceIterator, &rdata);
}
}
/// Render all xwayland unmanaged windows that appear on the output
fn renderXwaylandUnmanaged(output: *const Output, now: *os.timespec) void {
const output_box = server.root.output_layout.getBox(output.wlr_output).?;
var it = server.root.xwayland_unmanaged_views.last;
while (it) |node| : (it = node.prev) {
const xwayland_surface = node.data.xwayland_surface;
var rdata = SurfaceRenderData{
.output = output,
.output_x = xwayland_surface.x - output_box.x,
.output_y = xwayland_surface.y - output_box.y,
.when = now,
};
xwayland_surface.surface.?.forEachSurface(*SurfaceRenderData, renderSurfaceIterator, &rdata);
}
}
/// This function is passed to wlroots to render each surface during iteration
fn renderSurfaceIterator(
surface: *wlr.Surface,
surface_x: c_int,
surface_y: c_int,
rdata: *SurfaceRenderData,
) callconv(.C) void {
const texture = surface.getTexture() orelse return;
var source_box: wlr.FBox = undefined;
surface.getBufferSourceBox(&source_box);
renderTexture(
rdata.output,
texture,
.{
.x = rdata.output_x + surface_x,
.y = rdata.output_y + surface_y,
.width = surface.current.width,
.height = surface.current.height,
},
&source_box,
surface.current.transform,
);
surface.sendFrameDone(rdata.when);
}
/// Render the given texture at the given box, taking the scale and transform
/// of the output into account.
fn renderTexture(
output: *const Output,
texture: *wlr.Texture,
dest_box: wlr.Box,
source_box: *const wlr.FBox,
transform: wl.Output.Transform,
) void {
var box = dest_box;
// Scale the box to the output's current scaling factor
scaleBox(&box, output.wlr_output.scale);
// wlr_matrix_project_box is a helper which takes a box with a desired
// x, y coordinates, width and height, and an output geometry, then
// prepares an orthographic projection and multiplies the necessary
// transforms to produce a model-view-projection matrix.
var matrix: [9]f32 = undefined;
const inverted = wlr.Output.transformInvert(transform);
wlr.matrix.projectBox(&matrix, &box, inverted, 0.0, &output.wlr_output.transform_matrix);
// This takes our matrix, the texture, and an alpha, and performs the actual
// rendering on the GPU.
const renderer = output.wlr_output.backend.getRenderer().?;
renderer.renderSubtextureWithMatrix(texture, source_box, &matrix, 1.0) catch return;
}
fn renderBorders(output: *const Output, view: *View, now: *os.timespec) void {
const config = &server.config;
const color = blk: {
if (view.current.urgent) break :blk &config.border_color_urgent;
if (view.current.focus != 0) break :blk &config.border_color_focused;
break :blk &config.border_color_unfocused;
};
const border_width = config.border_width;
const actual_box = if (view.saved_buffers.items.len != 0) view.saved_surface_box else view.surface_box;
var border: Box = undefined;
// left and right, covering the corners as well
border.y = view.current.box.y - @intCast(i32, border_width);
border.width = border_width;
border.height = actual_box.height + border_width * 2;
// left
border.x = view.current.box.x - @intCast(i32, border_width);
renderRect(output, border, color);
// right
border.x = view.current.box.x + @intCast(i32, actual_box.width);
renderRect(output, border, color);
// top and bottom
border.x = view.current.box.x;
border.width = actual_box.width;
border.height = border_width;
// top
border.y = view.current.box.y - @intCast(i32, border_width);
renderRect(output, border, color);
// bottom border
border.y = view.current.box.y + @intCast(i32, actual_box.height);
renderRect(output, border, color);
}
fn renderRect(output: *const Output, box: Box, color: *const [4]f32) void {
var wlr_box = box.toWlrBox();
scaleBox(&wlr_box, output.wlr_output.scale);
output.wlr_output.backend.getRenderer().?.renderRect(
&wlr_box,
color,
&output.wlr_output.transform_matrix,
);
}
/// Scale a wlr_box, taking the possibility of fractional scaling into account.
fn scaleBox(box: *wlr.Box, scale: f64) void {
box.x = @floatToInt(c_int, @round(@intToFloat(f64, box.x) * scale));
box.y = @floatToInt(c_int, @round(@intToFloat(f64, box.y) * scale));
box.width = scaleLength(box.width, box.x, scale);
box.height = scaleLength(box.height, box.x, scale);
}
/// Scales a width/height.
///
/// This might seem overly complex, but it needs to work for fractional scaling.
fn scaleLength(length: c_int, offset: c_int, scale: f64) c_int {
return @floatToInt(c_int, @round(@intToFloat(f64, offset + length) * scale) -
@round(@intToFloat(f64, offset) * scale));
}
|
source/river-0.1.0/river/render.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const print = std.debug.print;
const mem = std.mem;
const data = @embedFile("data/day09.txt");
const EntriesList = std.ArrayList(u64);
const Record = struct {
x: usize = 0,
};
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const ally = &arena.allocator;
var lines = std.mem.tokenize(data, "\r\n");
var entries = EntriesList.init(ally);
try entries.ensureCapacity(400);
var result: usize = 0;
while (lines.next()) |line| {
if (line.len == 0) continue;
try entries.append(try std.fmt.parseInt(u64, line, 10));
}
const items = entries.items;
var part1_result: usize = 0;
part1:
for (items[25..]) |id, i| {
const list = items[i..i+25];
var found = false;
for (list[0..list.len-1]) |a, j| {
for (list[j+1..]) |b| {
if (a + b == id) {
found = true;
continue :part1;
}
}
}
if (!found) {
part1_result = id;
break :part1;
}
} else unreachable;
var part2_result: usize = 0;
part2:
for (items) |id, i| {
var total: u64 = 0;
for (items[i..]) |b, l| {
if (b == part1_result) break;
total += b;
if (total > part1_result) break;
if (total == part1_result) {
var min = ~@as(usize, 0);
var max = @as(usize, 0);
for (entries.items[i..i+l+1]) |k| {
if (k < min) min = k;
if (k > max) max = k;
}
part2_result = min + max;
break :part2;
}
}
} else unreachable;
print("part1: {}, part2: {}\n", .{part1_result, part2_result});
}
pub fn originalPart1() void {
for (items) |id, i| {
if (i >= 25) {
const list = items[i-25..i];
var found = false;
for (list[0..list.len-1]) |a, j| {
for (list[j+1..]) |b| {
if (a + b == id) {
found = true;
}
}
}
if (!found) {
print("Result: {}\n", .{id});
}
}
}
}
pub fn originalPart2() void {
const target = 10884537;
for (items) |id, i| {
var total: u64 = 0;
for (items[i..]) |b, l| {
total += b;
if (total == 10884537) {
var min = ~@as(usize, 0);
var max = @as(usize, 0);
// note: off by one bug on this line
// luckily it didn't affect my answer
for (entries.items[i..i+l]) |k| {
if (k < min) min = k;
if (k > max) max = k;
}
print("Result: {}\n", .{min + max});
}
}
}
}
|
src/day09.zig
|
const std = @import("std");
pub const PatternFinder = struct {
gen: GradientGenerator,
// Layers along Y, rows along Z, columns along X
pattern: []const []const []const ?Block,
pub fn search(
self: PatternFinder,
a: Point,
b: Point,
context: anytype,
comptime resultFn: fn (@TypeOf(context), Point) void,
comptime progressFn: ?fn (@TypeOf(context), count: u64, total: u64) void,
) void {
const total: u64 = a.areaTo(b);
var count: u64 = 0;
var it = a.iterTo(b);
while (it.next()) |p| {
if (progressFn) |f| {
count += 1;
f(context, count, total);
}
if (self.check(p)) {
resultFn(context, p);
}
}
}
pub fn check(self: PatternFinder, p: Point) bool {
// TODO: evict the pharoahs from this evil pyramid of doom
for (self.pattern) |layer, py| {
for (layer) |row, pz| {
for (row) |block_opt, px| {
if (block_opt) |block| {
const block_at = self.gen.at(
p.x + @intCast(i32, px),
p.y + @intCast(i32, py),
p.z + @intCast(i32, pz),
);
if (block != block_at) {
return false;
}
}
}
}
}
return true;
}
};
pub const Point = packed struct {
x: i32,
y: i32,
z: i32,
pub fn fromV(vec: std.meta.Vector(3, i32)) Point {
return @bitCast(Point, vec);
}
pub fn v(self: Point) std.meta.Vector(3, i32) {
return @bitCast([3]i32, self);
}
pub fn areaTo(a: Point, b: Point) u64 {
return @reduce(.Mul, @intCast(std.meta.Vector(3, u64), b.v() - a.v()));
}
pub fn iterTo(a: Point, b: Point) Iterator {
return .{ .pos = a, .start = a, .end = b };
}
pub const Iterator = struct {
pos: Point,
start: Point,
end: Point,
pub fn next(self: *Iterator) ?Point {
if (self.pos.y >= self.end.y - 1) {
self.pos.y = self.start.y;
if (self.pos.x >= self.end.x - 1) {
self.pos.x = self.start.x;
if (self.pos.z >= self.end.z - 1) {
return null;
} else {
self.pos.z += 1;
}
} else {
self.pos.x += 1;
}
} else {
self.pos.y += 1;
}
return self.pos;
}
};
};
pub const GradientGenerator = struct {
rand: PosRandom,
lower: Block,
upper: Block,
lower_y: i32,
upper_y: i32,
pub fn at(self: GradientGenerator, x: i32, y: i32, z: i32) Block {
if (y <= self.lower_y) {
return self.lower;
}
if (y >= self.upper_y) {
return self.upper;
}
const fac = 1 - normalize(
@intToFloat(f64, y),
@intToFloat(f64, self.lower_y),
@intToFloat(f64, self.upper_y),
);
if (self.rand.at(x, y, z).nextf() < fac) {
return self.lower;
} else {
return self.upper;
}
}
fn normalize(x: f64, zero: f64, one: f64) f64 {
return (x - zero) / (one - zero);
}
pub fn overworldFloor(seed: i64) GradientGenerator {
var random = Random.initHash(seed, "minecraft:bedrock_floor", .xoroshiro);
return GradientGenerator{
.rand = PosRandom.init(&random),
.lower = .bedrock,
.upper = .other,
.lower_y = -64,
.upper_y = -59,
};
}
pub fn netherFloor(seed: i64) GradientGenerator {
var random = Random.initHash(seed, "minecraft:bedrock_floor", .legacy);
return GradientGenerator{
.rand = PosRandom.init(&random),
.lower = .bedrock,
.upper = .other,
.lower_y = 0,
.upper_y = 5,
};
}
pub fn netherCeiling(seed: i64) GradientGenerator {
var random = Random.initHash(seed, "minecraft:bedrock_roof", .legacy);
return GradientGenerator{
.rand = PosRandom.init(&random),
.lower = .other,
.upper = .bedrock,
.lower_y = 122,
.upper_y = 127,
};
}
};
pub const Block = enum {
bedrock,
other,
};
pub const Random = union(Random.Algorithm) {
legacy: u64,
xoroshiro: [2]u64,
pub const Algorithm = enum { legacy, xoroshiro };
const lmagic = 0x5DEECE66D;
const lmask = ((1 << 48) - 1);
pub fn init(seed: i64, algo: Algorithm) Random {
return switch (algo) {
.legacy => .{ .legacy = (@bitCast(u64, seed) ^ lmagic) & lmask },
.xoroshiro => xoroshiroInit(seed128(seed)),
};
}
const xmagic0: u64 = 0x6a09e667f3bcc909;
const xmagic1: u64 = 0x9e3779b97f4a7c15;
fn xoroshiroInit(seed: [2]u64) Random {
if (seed[0] == 0 and seed[1] == 0) {
return .{ .xoroshiro = .{ xmagic1, xmagic0 } };
}
return .{ .xoroshiro = seed };
}
fn seed128(seed: i64) [2]u64 {
var lo = @bitCast(u64, seed) ^ xmagic0;
var hi = lo +% xmagic1;
return .{ mix(lo), mix(hi) };
}
fn mix(v: u64) u64 {
var x = v;
x = (x ^ (x >> 30)) *% 0xbf58476d1ce4e5b9;
x = (x ^ (x >> 27)) *% 0x94d049bb133111eb;
return x ^ (x >> 31);
}
pub fn initHash(seed: i64, str: []const u8, algo: Algorithm) Random {
var seeder = init(seed, algo);
switch (algo) {
.legacy => return init(
seeder.next64() ^ javaStringHash(str),
.legacy,
),
.xoroshiro => {
var hash: [16]u8 = undefined;
std.crypto.hash.Md5.hash(str, &hash, .{});
const hseed = .{
std.mem.readIntBig(u64, hash[0..8]),
std.mem.readIntBig(u64, hash[8..]),
};
return xoroshiroInit(.{
hseed[0] ^ @bitCast(u64, seeder.next64()),
hseed[1] ^ @bitCast(u64, seeder.next64()),
});
},
}
}
pub fn next(self: *Random, bits: u6) i32 {
std.debug.assert(bits <= 32);
switch (self.*) {
.legacy => |*seed| {
seed.* = (seed.* *% lmagic +% 0xb) & lmask;
return @truncate(i32, @bitCast(i64, seed.*) >> (48 - bits));
},
.xoroshiro => {
const shift = @intCast(u6, @as(u7, 64) - bits);
const rbits = @bitCast(u64, self.next64());
return @intCast(i32, rbits >> shift);
},
}
}
pub fn next64(self: *Random) i64 {
switch (self.*) {
.legacy => {
const top: i64 = self.next(32);
const bottom: i64 = self.next(32);
const result = (top << 32) + bottom;
return result;
},
.xoroshiro => |*s| {
const v = std.math.rotl(u64, s[0] +% s[1], 17) +% s[0];
s[1] ^= s[0];
s[0] = std.math.rotl(u64, s[0], 49) ^ s[1] ^ (s[1] << 21);
s[1] = std.math.rotl(u64, s[1], 28);
return @bitCast(i64, v);
},
}
}
pub fn nextf(self: *Random) f32 {
return @intToFloat(f32, self.next(24)) * 5.9604645e-8;
}
};
pub const PosRandom = union(Random.Algorithm) {
legacy: i64,
xoroshiro: [2]u64,
pub fn init(world: *Random) PosRandom {
return switch (world.*) {
.legacy => .{ .legacy = world.next64() },
.xoroshiro => .{
.xoroshiro = .{
@bitCast(u64, world.next64()),
@bitCast(u64, world.next64()),
},
},
};
}
pub fn at(self: PosRandom, x: i32, y: i32, z: i32) Random {
var seed = @as(i64, x *% 3129871) ^ (@as(i64, z) *% 116129781) ^ y;
seed = seed *% seed *% 42317861 +% seed *% 0xb;
seed >>= 16;
return switch (self) {
.legacy => |rseed| Random.init(seed ^ rseed, .legacy),
.xoroshiro => |rseed| Random.xoroshiroInit(.{
@bitCast(u64, seed) ^ rseed[0], rseed[1],
}),
};
}
};
// Unicode strings not supported because I'm lazy and Java is horrible
pub fn javaStringHash(str: []const u8) u32 {
var hash: u32 = 0;
for (str) |ch| {
std.debug.assert(ch < 0x80);
hash = 31 *% hash +% ch;
}
return hash;
}
|
src/bedrock.zig
|
const std = @import("std");
const zap = @import("zap");
const hyperia = @import("hyperia.zig");
const os = std.os;
const mem = std.mem;
const math = std.math;
const time = std.time;
const testing = std.testing;
const assert = std.debug.assert;
const Reactor = hyperia.Reactor;
const Timer = @This();
pub const Handle = struct {
pub const Error = error{Cancelled} || mem.Allocator.Error;
parent: *Timer,
expires_at: u64,
result: ?Error = null,
runnable: zap.Pool.Runnable = .{ .runFn = resumeWaiter },
frame: anyframe = undefined,
fn resumeWaiter(runnable: *zap.Pool.Runnable) void {
const self = @fieldParentPtr(Timer.Handle, "runnable", runnable);
resume self.frame;
}
pub fn cancel(self: *Timer.Handle) void {
const i = mem.indexOfScalar(*Timer.Handle, self.parent.pending.items[0..self.parent.pending.len], self) orelse return;
assert(self.parent.pending.removeIndex(i) == self);
self.result = error.Cancelled;
hyperia.pool.schedule(.{}, &self.runnable);
}
pub fn wait(self: *Timer.Handle) callconv(.Async) !void {
if (self.result) |err| {
self.result = null;
return err;
}
suspend {
self.frame = @frame();
if (self.parent.pending.add(self)) {
self.parent.event.post();
} else |err| {
self.result = err;
hyperia.pool.schedule(.{}, &self.runnable);
}
}
if (self.result) |err| {
self.result = null;
return err;
}
}
};
event: *Reactor.AutoResetEvent,
pending: std.PriorityQueue(*Handle),
pub fn init(allocator: *mem.Allocator, event: *Reactor.AutoResetEvent) Timer {
return Timer{
.event = event,
.pending = std.PriorityQueue(*Handle).init(allocator, struct {
fn compare(a: *Handle, b: *Handle) math.Order {
return math.order(a.expires_at, b.expires_at);
}
}.compare),
};
}
pub fn deinit(self: *Timer, allocator: *mem.Allocator) void {
var batch: zap.Pool.Batch = .{};
defer hyperia.pool.schedule(.{}, batch);
while (self.pending.removeOrNull()) |handle| {
handle.result = error.Cancelled;
batch.push(&handle.runnable);
}
self.pending.deinit();
}
pub fn after(self: *Timer, duration_ms: u64) Handle {
return Handle{ .parent = self, .expires_at = @intCast(u64, time.milliTimestamp()) + duration_ms };
}
pub fn at(self: *Timer, timestamp_ms: u64) Handle {
return Handle{ .parent = self, .expires_at = timestamp_ms };
}
pub fn delay(self: *Timer) ?u64 {
const head = self.pending.peek() orelse return null;
return math.sub(u64, head.expires_at, @intCast(u64, time.milliTimestamp())) catch 0;
}
pub fn update(self: *Timer, closure: anytype) void {
const current_time = @intCast(u64, time.milliTimestamp());
while (true) {
const head = self.pending.peek() orelse break;
if (head.expires_at > current_time) break;
assert(self.pending.remove() == head);
closure.call(head);
}
}
test {
testing.refAllDecls(@This());
}
test "timer2: register timer" {
hyperia.init();
defer hyperia.deinit();
const allocator = testing.allocator;
const reactor = try Reactor.init(os.EPOLL_CLOEXEC);
defer reactor.deinit();
var reactor_event = try Reactor.AutoResetEvent.init(os.EFD_CLOEXEC, reactor);
defer reactor_event.deinit();
try reactor.add(reactor_event.fd, &reactor_event.handle, .{});
var timer = Timer.init(allocator, &reactor_event);
defer timer.deinit(allocator);
var handle = timer.after(100); // 100 milliseconds
var handle_frame = async handle.wait();
while (timer.delay()) |delay_duration| {
try reactor.poll(1, struct {
pub fn call(event: Reactor.Event) void {
var batch: zap.Pool.Batch = .{};
defer while (batch.pop()) |runnable| runnable.run();
const event_handle = @intToPtr(*Reactor.Handle, event.data);
event_handle.call(&batch, event);
}
}, delay_duration);
timer.update(struct {
pub fn call(timer_handle: *Timer.Handle) void {
timer_handle.runnable.run();
}
});
}
try nosuspend await handle_frame;
}
|
Timer2.zig
|
const std = @import("std");
const lib = @import("lib.zig");
const testing = std.testing;
const assert = std.debug.assert;
const Parser = lib.Parser;
const Instruction = lib.Instruction;
const ArrayList = std.ArrayListUnmanaged;
const Allocator = std.mem.Allocator;
const StringMap = std.StringArrayHashMapUnmanaged;
const Tokenizer = lib.Tokenizer;
const Linker = @This();
objects: Object.List = .{},
generation: u16 = 1,
procedures: ProcedureMap = .{},
files: FileMap = .{},
const ProcedureMap = StringMap(Procedure);
const FileMap = StringMap(Procedure);
const Procedure = struct {
entry: u32,
module: u16,
location: Tokenizer.Location,
};
const log = std.log.scoped(.linker);
pub fn deinit(l: *Linker, gpa: Allocator) void {
for (l.objects.items) |*obj| obj.deinit(gpa);
l.objects.deinit(gpa);
l.procedures.deinit(gpa);
l.files.deinit(gpa);
l.generation = undefined;
}
pub const Object = struct {
name: []const u8,
text: []const u8,
program: Instruction.List = .{},
symbols: SymbolMap = .{},
adjacent: AdjacentMap = .{},
files: Object.FileMap = .{},
pub const List = ArrayList(Object);
pub const SymbolMap = StringMap(SymbolList);
pub const FileMap = StringMap(File);
pub const SymbolList = ArrayList(u32);
pub const AdjacentMap = StringMap(Adjacent);
pub const File = struct {
entry: u32,
location: Tokenizer.Location,
};
pub const Adjacent = struct {
entry: u32,
exit: u32,
location: Tokenizer.Location,
};
pub fn deinit(self: *Object, gpa: Allocator) void {
self.program.deinit(gpa);
for (self.symbols.values()) |*entry| entry.deinit(gpa);
self.symbols.deinit(gpa);
self.adjacent.deinit(gpa);
self.files.deinit(gpa);
}
};
fn mergeAdjacent(l: *Linker) void {
for (l.objects.items) |*obj, module| {
log.debug("processing module {d}", .{module + 1});
const values = obj.adjacent.values();
for (obj.adjacent.keys()) |key, i| {
const opcodes = obj.program.items(.opcode);
const data = obj.program.items(.data);
const exit = values[i].exit;
log.debug("opcode {}", .{opcodes[exit]});
switch (opcodes[exit]) {
.ret, .jmp => {
if (opcodes[exit] == .jmp and data[exit].jmp.generation == l.generation) continue;
var last_adj = values[i];
var last_obj = obj;
for (l.objects.items[module + 1 ..]) |*next, offset| {
if (next.adjacent.get(key)) |current| {
const op = last_obj.program.items(.opcode)[last_adj.exit];
assert(op == .jmp or op == .ret);
const destination = @intCast(u16, module + offset) + 2;
log.debug("updating jump location to address 0x{x:0>8} in module {d}", .{
current.entry,
destination,
});
last_obj.program.items(.opcode)[last_adj.exit] = .jmp;
last_obj.program.items(.data)[last_adj.exit] = .{ .jmp = .{
.generation = l.generation,
.address = current.entry,
.module = destination,
} };
last_adj = current;
last_obj = next;
}
}
},
else => unreachable,
}
}
}
}
test "merge" {
var obj_a = try Parser.parse(testing.allocator, "",
\\
\\
\\ lang: zig esc: none tag: #a
\\ ---------------------------
\\
\\ abc
\\
\\end
\\
\\ lang: zig esc: none tag: #b
\\ ---------------------------
\\
\\ abc
\\
\\end
);
var obj_b = try Parser.parse(testing.allocator, "",
\\
\\
\\ lang: zig esc: none tag: #a
\\ ---------------------------
\\
\\ abc
\\
\\end
);
var obj_c = try Parser.parse(testing.allocator, "",
\\
\\
\\ lang: zig esc: none tag: #b
\\ ---------------------------
\\
\\ abc
\\
\\end
);
var l: Linker = .{};
defer l.deinit(testing.allocator);
try l.objects.appendSlice(testing.allocator, &.{
obj_a,
obj_b,
obj_c,
});
l.mergeAdjacent();
try testing.expectEqualSlices(Instruction.Opcode, &.{ .write, .jmp, .write, .jmp }, obj_a.program.items(.opcode));
try testing.expectEqual(
Instruction.Data.Jmp{
.module = 2,
.address = 0,
.generation = 1,
},
obj_a.program.items(.data)[1].jmp,
);
try testing.expectEqual(
Instruction.Data.Jmp{
.module = 3,
.address = 0,
.generation = 1,
},
obj_a.program.items(.data)[3].jmp,
);
}
fn buildProcedureTable(l: *Linker, gpa: Allocator) !void {
log.debug("building procedure table", .{});
for (l.objects.items) |obj, module| {
log.debug("processing module {d} with {d} procedures", .{ module + 1, obj.adjacent.keys().len });
for (obj.adjacent.keys()) |key, i| {
const entry = try l.procedures.getOrPut(gpa, key);
if (!entry.found_existing) {
const adjacent = obj.adjacent.values()[i];
log.debug("registering new procedure '{s}' address {x:0>8} module {d}", .{
key,
adjacent.entry,
module + 1,
});
entry.value_ptr.* = .{
.module = @intCast(u16, module) + 1,
.entry = @intCast(u32, adjacent.entry),
.location = adjacent.location,
};
}
}
}
log.debug("registered {d} procedures", .{l.procedures.count()});
}
fn updateProcedureCalls(l: *Linker) void {
log.debug("updating procedure calls", .{});
for (l.procedures.keys()) |key, i| {
const proc = l.procedures.values()[i];
for (l.objects.items) |*obj| if (obj.symbols.get(key)) |sym| {
log.debug("updating locations {any}", .{sym.items});
for (sym.items) |location| {
assert(obj.program.items(.opcode)[location] == .call);
const call = &obj.program.items(.data)[location].call;
call.address = proc.entry;
call.module = proc.module;
}
};
}
}
fn buildFileTable(l: *Linker, gpa: Allocator) !void {
for (l.objects.items) |obj, module| {
for (obj.files.keys()) |key, i| {
const file = try l.files.getOrPut(gpa, key);
const record = obj.files.values()[i];
if (file.found_existing) return error.@"Multiple files with the same name";
file.value_ptr.module = @intCast(u16, module) + 1;
file.value_ptr.entry = record.entry;
file.value_ptr.location = record.location;
}
}
}
pub fn link(l: *Linker, gpa: Allocator) !void {
l.procedures.clearRetainingCapacity();
l.files.clearRetainingCapacity();
try l.buildProcedureTable(gpa);
try l.buildFileTable(gpa);
l.mergeAdjacent();
l.updateProcedureCalls();
var failure = false;
for (l.objects.items) |obj| {
for (obj.symbols.keys()) |key| {
if (!l.procedures.contains(key)) {
failure = true;
log.err("unknown symbol '{s}'", .{key});
}
}
}
if (failure) return error.@"Unknown symbol";
}
test "call" {
var obj = try Parser.parse(testing.allocator, "",
\\
\\
\\ lang: zig esc: none tag: #a
\\ ---------------------------
\\
\\ abc
\\
\\end
\\
\\ lang: zig esc: [[]] tag: #b
\\ ---------------------------
\\
\\ [[a]]
\\
\\end
);
var l: Linker = .{};
defer l.deinit(testing.allocator);
try l.objects.append(testing.allocator, obj);
try l.link(testing.allocator);
try testing.expectEqualSlices(
Instruction.Opcode,
&.{ .write, .ret, .call, .ret },
obj.program.items(.opcode),
);
try testing.expectEqual(
Instruction.Data.Call{
.address = 0,
.module = 1,
.indent = 0,
},
obj.program.items(.data)[2].call,
);
}
|
lib/Linker.zig
|
const std = @import("std");
const proto = @import("protocol.zig");
const Connector = @import("connector.zig").Connector;
const Connection = @import("connection.zig").Connection;
const Queue = @import("queue.zig").Queue;
const Basic = @import("basic.zig").Basic;
const Table = @import("table.zig").Table;
pub const Channel = struct {
connector: Connector,
channel_id: u16,
const Self = @This();
pub fn init(id: u16, connection: *Connection) Channel {
var ch = Channel{
.connector = connection.connector,
.channel_id = id,
};
ch.connector.channel = id;
return ch;
}
pub fn queueDeclare(self: *Self, name: []const u8, options: Queue.Options, args: ?*Table) !Queue {
var declare = try proto.Queue.declareSync(
&self.connector,
name,
options.passive,
options.durable,
options.exclusive,
options.auto_delete,
options.no_wait,
args,
);
return Queue.init(self);
}
pub fn basicPublish(self: *Self, exchange_name: []const u8, routing_key: []const u8, body: []const u8, options: Basic.Publish.Options) !void {
try proto.Basic.publishAsync(
&self.connector,
exchange_name,
routing_key,
options.mandatory,
options.immediate,
);
try self.connector.sendHeader(body.len, proto.Basic.BASIC_CLASS);
try self.connector.sendBody(body);
}
pub fn basicConsume(self: *Self, name: []const u8, options: Basic.Consume.Options, args: ?*Table) !Basic.Consumer {
var consume = try proto.Basic.consumeSync(
&self.connector,
name,
"",
options.no_local,
options.no_ack,
options.exclusive,
options.no_wait,
args,
);
return Basic.Consumer{
.connector = self.connector,
};
}
};
|
src/channel.zig
|
const std = @import("std");
const Symbol = @import("Symbol.zig");
const Object = @import("Object.zig");
const types = @import("types.zig");
const Wasm = @import("Wasm.zig");
const Allocator = std.mem.Allocator;
const log = std.log.scoped(.zwld);
/// Accepts a slice with mutable elements and sets the field `field_name`'s value
/// to the index within the list, based on the given `offset`.
fn setIndex(comptime field_name: []const u8, slice: anytype, offset: u32) void {
for (slice) |item, index| {
@field(item, field_name) = @intCast(u32, index + offset);
}
}
/// Output function section, holding a list of all
/// function with indexes to their type
pub const Functions = struct {
/// Holds the list of function type indexes.
/// The list is built from merging all defined functions into this single list.
/// Once appended, it becomes immutable and should not be mutated outside this list.
items: std.ArrayListUnmanaged(std.wasm.Func) = .{},
/// Adds a new function to the section while also setting the function index
/// of the `Func` itself.
pub fn append(self: *Functions, gpa: Allocator, offset: u32, func: std.wasm.Func) !u32 {
const index = offset + self.count();
try self.items.append(gpa, func);
return index;
}
/// Returns the count of entires within the function section
pub fn count(self: *Functions) u32 {
return @intCast(u32, self.items.items.len);
}
pub fn deinit(self: *Functions, gpa: Allocator) void {
self.items.deinit(gpa);
self.* = undefined;
}
};
/// Output import section, containing all the various import types
pub const Imports = struct {
/// Table where the key is represented by an import.
/// Each entry represents and imported function where the value contains the index of the function
/// as well as the index of the type.
imported_functions: std.ArrayHashMapUnmanaged(
ImportKey,
struct { index: u32, type: u32 },
ImportKey.Ctx,
true,
) = .{},
/// Table where the key is represented by an import.
/// Each entry represents an imported global from the host environment and maps to the index
/// within this map.
imported_globals: std.ArrayHashMapUnmanaged(
ImportKey,
struct { index: u32, global: std.wasm.GlobalType },
ImportKey.Ctx,
true,
) = .{},
/// Table where the key is represented by an import.
/// Each entry represents an imported table from the host environment and maps to the index
/// within this map.
imported_tables: std.ArrayHashMapUnmanaged(
ImportKey,
struct { index: u32, table: std.wasm.Table },
ImportKey.Ctx,
true,
) = .{},
/// A list of symbols representing objects that have been imported.
imported_symbols: std.ArrayListUnmanaged(Wasm.SymbolWithLoc) = .{},
const ImportKey = struct {
module_name: []const u8,
name: []const u8,
const Ctx = struct {
pub fn hash(ctx: Ctx, key: ImportKey) u32 {
_ = ctx;
const hashFunc = std.hash.autoHash;
var hasher = std.hash.Wyhash.init(0);
hashFunc(&hasher, key.module_name.len);
hashFunc(&hasher, key.module_name.ptr);
hashFunc(&hasher, key.name.len);
hashFunc(&hasher, key.name.ptr);
return @truncate(u32, hasher.final());
}
pub fn eql(ctx: Ctx, lhs: ImportKey, rhs: ImportKey, index: usize) bool {
_ = ctx;
_ = index;
return std.mem.eql(u8, lhs.name, rhs.name) and
std.mem.eql(u8, lhs.module_name, rhs.module_name);
}
};
};
const max_load = std.hash_map.default_max_load_percentage;
/// Appends an import symbol into the list of imports. Based on the type, also appends it
/// to their respective import list (such as imported_functions)
///
/// NOTE: The given symbol must reside within the given `Object`.
pub fn appendSymbol(
self: *Imports,
gpa: Allocator,
wasm: *const Wasm,
sym_with_loc: Wasm.SymbolWithLoc,
) !void {
const object: *Object = &wasm.objects.items[sym_with_loc.file.?];
const symbol = &object.symtable[sym_with_loc.sym_index];
const import = object.findImport(symbol.externalType(), symbol.index);
const module_name = import.module_name;
const import_name = symbol.name;
switch (symbol.tag) {
.function => {
const ret = try self.imported_functions.getOrPut(gpa, .{
.module_name = module_name,
.name = import_name,
});
if (!ret.found_existing) {
try self.imported_symbols.append(gpa, sym_with_loc);
ret.value_ptr.* = .{
.index = self.functionCount() - 1,
.type = import.kind.function,
};
}
symbol.index = ret.value_ptr.*.index;
log.debug("Imported function '{s}' at index ({d})", .{ import_name, symbol.index });
},
.global => {
const ret = try self.imported_globals.getOrPut(gpa, .{
.module_name = module_name,
.name = import_name,
});
if (!ret.found_existing) {
try self.imported_symbols.append(gpa, sym_with_loc);
ret.value_ptr.* = .{
.index = self.globalCount() - 1,
.global = import.kind.global,
};
}
symbol.index = ret.value_ptr.*.index;
log.debug("Imported global '{s}' at index ({d})", .{ import_name, symbol.index });
},
.table => {
const ret = try self.imported_tables.getOrPut(gpa, .{
.module_name = module_name,
.name = import_name,
});
if (!ret.found_existing) {
try self.imported_symbols.append(gpa, sym_with_loc);
ret.value_ptr.* = .{
.index = self.tableCount() - 1,
.table = import.kind.table,
};
}
symbol.index = ret.value_ptr.*.index;
log.debug("Imported table '{s}' at index ({d})", .{ import_name, symbol.index });
},
else => unreachable, // programmer error: Given symbol cannot be imported
}
}
/// Returns the count of functions that have been imported (so far)
pub fn functionCount(self: Imports) u32 {
return @intCast(u32, self.imported_functions.count());
}
/// Returns the count of tables that have been imported (so far)
pub fn tableCount(self: Imports) u32 {
return @intCast(u32, self.imported_tables.count());
}
/// Returns the count of globals that have been imported (so far)
pub fn globalCount(self: Imports) u32 {
return @intCast(u32, self.imported_globals.count());
}
pub fn deinit(self: *Imports, gpa: Allocator) void {
self.imported_functions.deinit(gpa);
self.imported_globals.deinit(gpa);
self.imported_tables.deinit(gpa);
self.imported_symbols.deinit(gpa);
self.* = undefined;
}
/// Returns a slice to pointers to symbols that have been imported
pub fn symbols(self: Imports) []const Wasm.SymbolWithLoc {
return self.imported_symbols.items;
}
/// Returns the count of symbols which have been imported
pub fn symbolCount(self: Imports) u32 {
return @intCast(u32, self.imported_symbols.items.len);
}
};
/// Represents the output global section, containing a list of globals
pub const Globals = struct {
/// A list of `wasm.Global`s
/// Once appended to this list, they should no longer be mutated
items: std.ArrayListUnmanaged(std.wasm.Global) = .{},
/// List of internal GOT symbols
got_symbols: std.ArrayListUnmanaged(*Symbol) = .{},
/// Appends a new global and sets the `global_idx` on the global based on the
/// current count of globals and the given `offset`.
pub fn append(self: *Globals, gpa: Allocator, offset: u32, global: std.wasm.Global) !u32 {
const index = offset + @intCast(u32, self.items.items.len);
try self.items.append(gpa, global);
return index;
}
/// Appends a new entry to the internal GOT
pub fn addGOTEntry(self: *Globals, gpa: Allocator, symbol: *Symbol, wasm_bin: *Wasm) !void {
if (symbol.kind == .function) {
try wasm_bin.tables.createIndirectFunctionTable(gpa, wasm_bin);
// try wasm_bin.elements.appendSymbol(gpa, symbol);
@panic("TODO: Implement GOT entries");
}
try self.got_symbols.append(gpa, symbol);
}
/// Returns the total amount of globals of the global section
pub fn count(self: Globals) u32 {
return @intCast(u32, self.items.items.len);
}
/// Creates a new linker-defined global with the given mutability and value type.
/// Also appends the new global to the output global section and returns a pointer
/// to the newly created global.
///
/// This will automatically set `init` to `null` and can manually be updated at a later point using
/// the returned pointer.
pub fn create(self: *Globals, gpa: Allocator, mutability: enum { mutable, immutable }, valtype: types.ValueType) !*types.Global {
const index = self.count();
try self.items.append(gpa, .{
.valtype = valtype,
.mutable = mutability == .mutable,
.init = null,
.global_idx = index,
});
return &self.items.items[index];
}
/// Assigns indexes to all functions based on the given `offset`
/// Meaning that for element 0, with offset 2, will have its first element's index
/// set to 2, rather than 0.
pub fn setIndexes(self: *Globals, offset: u32) void {
setIndex("global_idx", self.items.items, offset);
}
pub fn deinit(self: *Globals, gpa: Allocator) void {
self.items.deinit(gpa);
self.got_symbols.deinit(gpa);
self.* = undefined;
}
};
/// Represents the type section, containing a list of
/// wasm signature types.
pub const Types = struct {
/// A list of `wasm.FuncType`, when appending to
/// this list, duplicates will be removed.
///
/// TODO: Would a hashmap be more efficient?
items: std.ArrayListUnmanaged(std.wasm.Type) = .{},
/// Checks if a given type is already present within the list of types.
/// If not, the given type will be appended to the list.
/// In all cases, this will return the index within the list of types.
pub fn append(self: *Types, gpa: Allocator, func_type: std.wasm.Type) !u32 {
return self.find(func_type) orelse {
const index = self.count();
try self.items.append(gpa, func_type);
return index;
};
}
/// Returns a pointer to the function type at given `index`
/// Asserts the index is within bounds.
pub fn get(self: Types, index: u32) *std.wasm.Type {
return &self.items.items[index];
}
/// Checks if any type (read: function signature) already exists within
/// the type section. When it does exist, it will return its index
/// otherwise, returns `null`.
pub fn find(self: Types, func_type: std.wasm.Type) ?u32 {
return for (self.items.items) |ty, index| {
if (std.mem.eql(std.wasm.Valtype, ty.params, func_type.params) and
std.mem.eql(std.wasm.Valtype, ty.returns, func_type.returns))
{
return @intCast(u32, index);
}
} else null;
}
/// Returns the amount of entries in the type section
pub fn count(self: Types) u32 {
return @intCast(u32, self.items.items.len);
}
pub fn deinit(self: *Types, gpa: Allocator) void {
self.items.deinit(gpa);
self.* = undefined;
}
};
/// Represents the table section, containing a list
/// of tables, as well as the definition of linker-defined
/// tables such as the indirect function table
pub const Tables = struct {
/// The list of tables that have been merged from all
/// object files. This does not include any linker-defined
/// tables. Once inserted in this list, the object becomes immutable.
items: std.ArrayListUnmanaged(std.wasm.Table) = .{},
/// Appends a new table to the list of tables and sets its index to
/// the position within the list of tables.
pub fn append(self: *Tables, gpa: Allocator, offset: u32, table: std.wasm.Table) !u32 {
const index = offset + self.count();
try self.items.append(gpa, table);
return index;
}
/// Returns the amount of entries in the table section
pub fn count(self: Tables) u32 {
return @intCast(u32, self.items.items.len);
}
/// Sets the table indexes of all table elements relative to their position within
/// the list, starting from `offset` rather than '0'.
pub fn setIndexes(self: *Tables, offset: u32) void {
setIndex("table_idx", self.items.items, offset);
}
/// Creates a synthetic symbol for the indirect function table and appends it into the
/// table list.
pub fn createIndirectFunctionTable(self: *Tables, gpa: Allocator, wasm_bin: *Wasm) !void {
// Only create it if it doesn't exist yet
if (Symbol.linker_defined.indirect_function_table != null) {
log.debug("Indirect function table already exists, skipping creation...", .{});
return;
}
const index = self.count();
try self.items.append(gpa, .{
.limits = .{ .min = 0, .max = null },
.reftype = .funcref,
.table_idx = index,
});
var symbol: Symbol = .{
.flags = 0, // created defined symbol
.name = Symbol.linker_defined.names.indirect_function_table, // __indirect_function_table
.kind = .{ .table = .{ .index = index, .table = &self.items.items[index] } },
};
try wasm_bin.synthetic_symbols.append(gpa, symbol);
Symbol.linker_defined.indirect_function_table = &wasm_bin.synthetic_symbols.items[wasm_bin.synthetic_symbols.items.len - 1];
log.debug("Created indirect function table at index {d}", .{index});
}
pub fn deinit(self: *Tables, gpa: Allocator) void {
self.items.deinit(gpa);
self.* = undefined;
}
};
/// Represents the exports section, built from explicit exports
/// from all object files, as well as global defined symbols that are
/// non-hidden.
pub const Exports = struct {
/// List of exports, containing both merged exports
/// as linker-defined exports such as __stack_pointer.
items: std.ArrayListUnmanaged(std.wasm.Export) = .{},
/// Contains a list of pointers to symbols
/// TODO: Do we really need this list?
symbols: std.ArrayListUnmanaged(*Symbol) = .{},
/// Appends a given `wasm.Export` to the list of output exports.
pub fn append(self: *Exports, gpa: Allocator, exp: std.wasm.Export) !void {
try self.items.append(gpa, exp);
}
pub fn appendSymbol(self: *Exports, gpa: Allocator, symbol: *Symbol) !void {
try self.symbols.append(gpa, symbol);
}
/// Returns the amount of entries in the export section
pub fn count(self: Exports) u32 {
return @intCast(u32, self.items.items.len);
}
pub fn deinit(self: *Exports, gpa: Allocator) void {
self.items.deinit(gpa);
self.symbols.deinit(gpa);
self.* = undefined;
}
};
pub const Elements = struct {
/// A list of symbols for indirect function calls where the key
/// represents the symbol location, and the value represents the table index.
indirect_functions: std.AutoArrayHashMapUnmanaged(Wasm.SymbolWithLoc, u32) = .{},
/// Appends a function symbol to the list of indirect function calls.
/// The table index will be set on the symbol, based on the length
///
/// Asserts symbol represents a function.
pub fn appendSymbol(self: *Elements, gpa: Allocator, symbol_loc: Wasm.SymbolWithLoc) !void {
const gop = try self.indirect_functions.getOrPut(gpa, symbol_loc);
if (gop.found_existing) return;
// start at index 1 so the index '0' is an invalid function pointer
gop.value_ptr.* = self.functionCount() + 1;
}
pub fn functionCount(self: Elements) u32 {
return @intCast(u32, self.indirect_functions.count());
}
pub fn deinit(self: *Elements, gpa: Allocator) void {
self.indirect_functions.deinit(gpa);
self.* = undefined;
}
};
|
src/sections.zig
|
const std = @import("std");
const assert = std.debug.assert;
const config = @import("../config.zig");
const MessagePool = @import("../message_pool.zig").MessagePool;
const Message = MessagePool.Message;
const Header = @import("../vsr.zig").Header;
const Network = @import("network.zig").Network;
const log = std.log.scoped(.message_bus);
pub const Process = union(enum) {
replica: u8,
client: u128,
};
pub const MessageBus = struct {
network: *Network,
pool: MessagePool,
cluster: u32,
process: Process,
/// The callback to be called when a message is received. Use set_on_message() to set
/// with type safety for the context pointer.
on_message_callback: ?fn (context: ?*c_void, message: *Message) void = null,
on_message_context: ?*c_void = null,
pub fn init(
allocator: *std.mem.Allocator,
cluster: u32,
process: Process,
network: *Network,
) !MessageBus {
return MessageBus{
.pool = try MessagePool.init(allocator),
.network = network,
.cluster = cluster,
.process = process,
};
}
/// TODO
pub fn deinit(bus: *MessageBus) void {}
pub fn set_on_message(
bus: *MessageBus,
comptime Context: type,
context: Context,
comptime on_message: fn (context: Context, message: *Message) void,
) void {
bus.on_message_callback = struct {
fn wrapper(_context: ?*c_void, message: *Message) void {
on_message(@intToPtr(Context, @ptrToInt(_context)), message);
}
}.wrapper;
bus.on_message_context = context;
}
pub fn tick(self: *MessageBus) void {}
pub fn get_message(bus: *MessageBus) ?*Message {
return bus.pool.get_message();
}
pub fn unref(bus: *MessageBus, message: *Message) void {
bus.pool.unref(message);
}
pub fn send_message_to_replica(bus: *MessageBus, replica: u8, message: *Message) void {
// Messages sent by a process to itself should never be passed to the message bus
if (bus.process == .replica) assert(replica != bus.process.replica);
bus.network.send_message(message, .{
.source = bus.process,
.target = .{ .replica = replica },
});
}
/// Try to send the message to the client with the given id.
/// If the client is not currently connected, the message is silently dropped.
pub fn send_message_to_client(bus: *MessageBus, client_id: u128, message: *Message) void {
assert(bus.process == .replica);
bus.network.send_message(message, .{
.source = bus.process,
.target = .{ .client = client_id },
});
}
};
|
src/test/message_bus.zig
|
const std = @import("std");
const zang = @import("zang");
const common = @import("common.zig");
const c = @import("common/c.zig");
pub const AUDIO_FORMAT: zang.AudioFormat = .signed16_lsb;
pub const AUDIO_SAMPLE_RATE = 48000;
pub const AUDIO_BUFFER_SIZE = 1024;
pub const DESCRIPTION =
\\example_laser
\\
\\Trigger a "laser" sound effect by pressing the
\\spacebar. Some parameters of the sound are randomly
\\perturbed.
\\
\\Press "a", "s", or "d" for some alternate sound
\\effects based on the same module.
;
const carrier_curve = [_]zang.CurveNode{
.{ .t = 0.0, .value = 1000.0 },
.{ .t = 0.1, .value = 200.0 },
.{ .t = 0.2, .value = 100.0 },
};
const modulator_curve = [_]zang.CurveNode{
.{ .t = 0.0, .value = 1000.0 },
.{ .t = 0.1, .value = 200.0 },
.{ .t = 0.2, .value = 100.0 },
};
const volume_curve = [_]zang.CurveNode{
.{ .t = 0.0, .value = 0.0 },
.{ .t = 0.004, .value = 1.0 },
.{ .t = 0.2, .value = 0.0 },
};
const LaserPlayer = struct {
pub const num_outputs = 1;
pub const num_temps = 3;
pub const Params = struct {
sample_rate: f32,
freq_mul: f32,
carrier_mul: f32,
modulator_mul: f32,
modulator_rad: f32,
};
carrier_curve: zang.Curve,
carrier: zang.SineOsc,
modulator_curve: zang.Curve,
modulator: zang.SineOsc,
volume_curve: zang.Curve,
fn init() LaserPlayer {
return .{
.carrier_curve = zang.Curve.init(),
.carrier = zang.SineOsc.init(),
.modulator_curve = zang.Curve.init(),
.modulator = zang.SineOsc.init(),
.volume_curve = zang.Curve.init(),
};
}
fn paint(
self: *LaserPlayer,
span: zang.Span,
outputs: [num_outputs][]f32,
temps: [num_temps][]f32,
note_id_changed: bool,
params: Params,
) void {
const out = outputs[0];
zang.zero(span, temps[0]);
self.modulator_curve.paint(span, .{temps[0]}, .{}, note_id_changed, .{
.sample_rate = params.sample_rate,
.function = .smoothstep,
.curve = &modulator_curve,
});
zang.multiplyWithScalar(span, temps[0], params.freq_mul * params.modulator_mul);
zang.zero(span, temps[1]);
self.modulator.paint(span, .{temps[1]}, .{}, note_id_changed, .{
.sample_rate = params.sample_rate,
.freq = zang.buffer(temps[0]),
.phase = zang.constant(0.0),
});
zang.multiplyWithScalar(span, temps[1], params.modulator_rad);
zang.zero(span, temps[0]);
self.carrier_curve.paint(span, .{temps[0]}, .{}, note_id_changed, .{
.sample_rate = params.sample_rate,
.function = .smoothstep,
.curve = &carrier_curve,
});
zang.multiplyWithScalar(span, temps[0], params.freq_mul * params.carrier_mul);
zang.zero(span, temps[2]);
self.carrier.paint(span, .{temps[2]}, .{}, note_id_changed, .{
.sample_rate = params.sample_rate,
.freq = zang.buffer(temps[0]),
.phase = zang.buffer(temps[1]),
});
zang.zero(span, temps[0]);
self.volume_curve.paint(span, .{temps[0]}, .{}, note_id_changed, .{
.sample_rate = params.sample_rate,
.function = .smoothstep,
.curve = &volume_curve,
});
zang.multiply(span, out, temps[0], temps[2]);
}
};
pub const MainModule = struct {
pub const num_outputs = 1;
pub const num_temps = 3;
pub const output_audio = common.AudioOut{ .mono = 0 };
pub const output_visualize = 0;
iq: zang.Notes(LaserPlayer.Params).ImpulseQueue,
idgen: zang.IdGenerator,
player: LaserPlayer,
trigger: zang.Trigger(LaserPlayer.Params),
r: std.rand.Xoroshiro128,
pub fn init() MainModule {
return .{
.iq = zang.Notes(LaserPlayer.Params).ImpulseQueue.init(),
.idgen = zang.IdGenerator.init(),
.player = LaserPlayer.init(),
.trigger = zang.Trigger(LaserPlayer.Params).init(),
.r = std.rand.DefaultPrng.init(0),
};
}
pub fn paint(
self: *MainModule,
span: zang.Span,
outputs: [num_outputs][]f32,
temps: [num_temps][]f32,
) void {
var ctr = self.trigger.counter(span, self.iq.consume());
while (self.trigger.next(&ctr)) |result| {
self.player.paint(
result.span,
outputs,
temps,
result.note_id_changed,
result.params,
);
}
}
pub fn keyEvent(self: *MainModule, key: i32, down: bool, impulse_frame: usize) bool {
if (down) {
const variance = 0.3;
const freq_mul = 1.0 + self.r.random.float(f32) * variance -
0.5 * variance;
switch (key) {
c.SDLK_SPACE => {
// player laser
const carrier_mul_variance = 0.0;
const modulator_mul_variance = 0.1;
const modulator_rad_variance = 0.25;
self.iq.push(impulse_frame, self.idgen.nextId(), .{
.sample_rate = AUDIO_SAMPLE_RATE,
.freq_mul = freq_mul,
.carrier_mul = 2.0 +
self.r.random.float(f32) * carrier_mul_variance -
0.5 * carrier_mul_variance,
.modulator_mul = 0.5 +
self.r.random.float(f32) * modulator_mul_variance -
0.5 * modulator_mul_variance,
.modulator_rad = 0.5 +
self.r.random.float(f32) * modulator_rad_variance -
0.5 * modulator_rad_variance,
});
},
c.SDLK_a => {
// enemy laser
self.iq.push(impulse_frame, self.idgen.nextId(), .{
.sample_rate = AUDIO_SAMPLE_RATE,
.freq_mul = freq_mul,
.carrier_mul = 4.0,
.modulator_mul = 0.125,
.modulator_rad = 1.0,
});
},
c.SDLK_s => {
// pain sound?
self.iq.push(impulse_frame, self.idgen.nextId(), .{
.sample_rate = AUDIO_SAMPLE_RATE,
.freq_mul = freq_mul,
.carrier_mul = 0.5,
.modulator_mul = 0.125,
.modulator_rad = 1.0,
});
},
c.SDLK_d => {
// some web effect?
self.iq.push(impulse_frame, self.idgen.nextId(), .{
.sample_rate = AUDIO_SAMPLE_RATE,
.freq_mul = freq_mul,
.carrier_mul = 1.0,
.modulator_mul = 9.0,
.modulator_rad = 1.0,
});
},
else => return false,
}
return true;
}
return false;
}
};
|
examples/example_laser.zig
|
const std = @import("std");
const ArenaAllocator = std.heap.ArenaAllocator;
const mem = std.mem;
const fmt = std.fmt;
const ascii = std.ascii;
const Uri = @import("zuri").Uri;
const gzip = std.compress.gzip;
const log = std.log;
const dateStrToTimeStamp = @import("parse.zig").Rss.pubDateToTimestamp;
const zfetch = @import("zfetch");
const expect = std.testing.expect;
const print = std.debug.print;
const Datetime = @import("datetime").datetime.Datetime;
pub const FeedResponse = union(enum) {
ok: Ok,
not_modified: void,
fail: []const u8,
};
const InternalResponse = union(enum) {
ok: Ok,
not_modified: void,
permanent_redirect: PermanentRedirect,
temporary_redirect: TemporaryRedirect,
fail: []const u8,
};
const PermanentRedirect = struct {
location: []const u8,
msg: []const u8,
};
const TemporaryRedirect = struct {
location: []const u8,
msg: []const u8,
// Need to pass cache related fields to next request
last_modified: ?[]const u8 = null, // Doesn't own memory
etag: ?[]const u8 = null, // Doesn't own memory
};
pub const RespHeaders = struct {
cache_control_max_age: ?u32 = null,
expires_utc: ?i64 = null,
etag: ?[]const u8 = null,
last_modified_utc: ?i64 = null,
};
pub const Ok = struct {
location: []const u8,
body: []const u8,
content_type: ContentType = .unknown,
headers: RespHeaders = .{},
};
pub const ContentEncoding = enum {
none,
gzip,
};
pub const ContentType = enum {
// zig fmt: off
xml, // text/xml
xml_atom, // application/atom+xml
xml_rss, // application/rss+xml
json, // application/json
json_feed, // application/feed+json
html, // text/html
unknown,
};
// zig fmt: on
const max_redirects = 3;
pub fn resolveRequest(
arena: *ArenaAllocator,
url: []const u8,
last_modified_utc: ?i64,
etag: ?[]const u8,
) !FeedResponse {
var date_buf: [29]u8 = undefined;
const last_modified: ?[]const u8 = if (last_modified_utc) |modified|
Datetime.formatHttpFromTimestamp(&date_buf, modified) catch null
else
null;
var resp = try makeRequest(arena, url, last_modified, etag);
var redirect_count: u16 = 0;
while (redirect_count < max_redirects) : (redirect_count += 1) {
switch (resp) {
.ok, .fail, .not_modified => break,
.permanent_redirect => |perm| {
log.debug("Permanent redirect to {s}", .{perm.location});
resp = try makeRequest(arena, perm.location, null, null);
},
.temporary_redirect => |temp| {
log.info("Temporary redirect to {s}", .{temp.location});
resp = try makeRequest(arena, temp.location, last_modified, etag);
},
}
} else {
const nr_str = comptime fmt.comptimePrint("{d}", .{max_redirects});
return FeedResponse{ .fail = "Too many redirects. Max number of redirects allowed is " ++ nr_str };
}
std.debug.assert(resp == .ok or resp == .fail or resp == .not_modified);
return @ptrCast(*FeedResponse, &resp).*;
}
fn isPermanentRedirect(code: u16) bool {
for ([_]u16{ 301, 307, 308 }) |value| {
if (code == value) return true;
}
return false;
}
pub fn makeRequest(
arena: *ArenaAllocator,
url: []const u8,
last_modified: ?[]const u8,
etag: ?[]const u8,
) !InternalResponse {
var allocator = arena.allocator();
try zfetch.init();
defer zfetch.deinit(); // Does something on Windows systems. Doesn't allocate anything anyway
var headers = zfetch.Headers.init(allocator);
// defer headers.deinit(); // AreanAllocator will clean up all allocations
const uri = try makeUri(url);
try headers.appendValue("Host", uri.host.name);
try headers.appendValue("Connection", "close");
try headers.appendValue("Accept-Encoding", "gzip");
try headers.appendValue("Accept", "application/atom+xml, application/rss+xml, application/feed+json, text/xml, application/xml, application/json, text/html");
if (etag) |value| try headers.appendValue("If-None-Match", value);
// Ignored if there is 'If-None-Match'
if (last_modified) |value| try headers.appendValue("If-Modified-Since", value);
var req = try zfetch.Request.init(allocator, url, null);
// Closing file socket + freeing allocations
// defer req.deinit();
// Only close the file, let AreanAllocator take care of freeing allocations
defer req.socket.close();
try req.do(.GET, headers, null);
if (req.status.code == 200) {
var result: Ok = undefined;
result.location = url;
var content_encoding = ContentEncoding.none;
var content_length: usize = 128;
for (req.headers.list.items) |header| {
// print("{s}: {s}\n", .{ header.name, header.value });
if (ascii.eqlIgnoreCase("content-length", header.name)) {
content_length = try fmt.parseInt(u32, header.value, 10);
} else if (ascii.eqlIgnoreCase("content-type", header.name)) {
const len = mem.indexOfScalar(u8, header.value, ';') orelse header.value.len;
const value = header.value[0..len];
if (ascii.eqlIgnoreCase("text/html", value)) {
result.content_type = .html;
} else if (ascii.eqlIgnoreCase("application/rss+xml", value) or ascii.eqlIgnoreCase("application/x-rss+xml", value)) {
// NOTE: Just in case check for deprecated mime type 'application/x-rss+xml'
result.content_type = .xml_rss;
} else if (ascii.eqlIgnoreCase("application/atom+xml", value)) {
result.content_type = .xml_atom;
} else if (ascii.eqlIgnoreCase("application/xml", value) or
ascii.eqlIgnoreCase("text/xml", value))
{
result.content_type = .xml;
} else if (ascii.eqlIgnoreCase("application/feed+json", value)) {
result.content_type = .json_feed;
} else if (ascii.eqlIgnoreCase("application/json", value)) {
result.content_type = .json;
}
} else if (ascii.eqlIgnoreCase("content-encoding", header.name)) {
var it = mem.split(u8, header.value, ",");
while (it.next()) |val_raw| {
const val = mem.trimLeft(u8, val_raw, " \r\n\t");
if (ascii.startsWithIgnoreCase(val, "gzip")) {
content_encoding = .gzip;
break;
}
}
} else if (ascii.eqlIgnoreCase("etag", header.name)) {
result.headers.etag = header.value;
} else if (ascii.eqlIgnoreCase("last-modified", header.name)) {
result.headers.last_modified_utc = dateStrToTimeStamp(header.value) catch continue;
} else if (ascii.eqlIgnoreCase("expires", header.name)) {
result.headers.expires_utc = dateStrToTimeStamp(header.value) catch continue;
} else if (ascii.eqlIgnoreCase("cache-control", header.name)) {
var it = mem.split(u8, header.value, ",");
while (it.next()) |v_raw| {
const v = mem.trimLeft(u8, v_raw, " \r\n\t");
if (ascii.startsWithIgnoreCase(v, "max-age") or ascii.startsWithIgnoreCase(v, "s-maxage")) {
const eq_index = mem.indexOfScalar(u8, v, '=') orelse continue;
result.headers.cache_control_max_age = try fmt.parseInt(u32, v[eq_index + 1 ..], 10);
break;
}
}
}
}
const req_reader = req.reader();
switch (content_encoding) {
.none => {
result.body = try req_reader.readAllAlloc(allocator, std.math.maxInt(usize));
},
.gzip => {
var stream = try std.compress.gzip.gzipStream(allocator, req_reader);
// defer stream.deinit(); // let ArenaAllocator free all the allocations
result.body = try stream.reader().readAllAlloc(allocator, std.math.maxInt(usize));
},
}
return InternalResponse{ .ok = result };
} else if (isPermanentRedirect(req.status.code)) {
var permanent_redirect = PermanentRedirect{
.location = undefined,
.msg = try fmt.allocPrint(allocator, "{d} {s}", .{ req.status.code, req.status.reason }),
};
for (req.headers.list.items) |header| {
if (ascii.eqlIgnoreCase("location", header.name)) {
permanent_redirect.location = header.value;
break;
}
}
return InternalResponse{ .permanent_redirect = permanent_redirect };
} else if (req.status.code == 302) {
var temporary_redirect = TemporaryRedirect{
.location = undefined,
.last_modified = last_modified,
.etag = etag,
.msg = try fmt.allocPrint(allocator, "{d} {s}", .{ req.status.code, req.status.reason }),
};
for (req.headers.list.items) |header| {
if (ascii.eqlIgnoreCase("location", header.name)) {
temporary_redirect.location = header.value;
break;
}
}
return InternalResponse{ .temporary_redirect = temporary_redirect };
} else if (req.status.code == 304) {
return InternalResponse{ .not_modified = {} };
}
const msg = try fmt.allocPrint(allocator, "{d} {s}", .{ req.status.code, req.status.reason });
return InternalResponse{ .fail = msg };
}
pub fn makeUri(location: []const u8) !Uri {
var result = try Uri.parse(location, true);
if (result.scheme.len == 0) result.scheme = "http";
if (result.path.len == 0) result.path = "/";
return result;
}
test "makeUri" {
const url = try makeUri("google.com");
try std.testing.expectEqualSlices(u8, "http", url.scheme);
try std.testing.expectEqualSlices(u8, "/", url.path);
}
test "http" {
const testing = std.testing;
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
// const url = makeUri("https://google.com") catch unreachable;
// const url = makeUri("https://news.xbox.com/en-us/feed/") catch unreachable;
// const r = try resolveRequest(&arena, "https://feeds.feedburner.com/eclipse/fnews", null, null); // gzip
// const r = try resolveRequest(&arena, "https://www.aruba.it/CMSPages/GetResource.ashx?scriptfile=%2fCMSScripts%2fCustom%2faruba.js", null, null);
// const r = try resolveRequest(&arena, "https://google.com/", null, null);
const r = try resolveRequest(&arena, "http://lobste.rs/", null, null);
// print("{?}\n", .{r});
if (r == .fail) print("{s}\n", .{r.fail});
}
|
src/http.zig
|
const std = @import("std");
const input = @embedFile("data/input06");
usingnamespace @import("util.zig");
pub fn main() !void {
print("[Part1] Count: {}", .{countAnyone(input)});
print("[Part2] Count: {}", .{countEveryone(input)});
}
fn countAnyone(inputStr: []const u8) usize {
var count: usize = 0;
var reader = std.mem.split(inputStr, "\n\n");
while (reader.next()) |group| {
var answered = std.mem.zeroes([26]bool);
for (group) |c| {
if (c >= 'a' and c <= 'z' and !answered[c - 'a']) {
answered[c - 'a'] = true;
count += 1;
}
}
}
return count;
}
fn countEveryone(inputStr: []const u8) usize {
var count: usize = 0;
var reader = std.mem.split(inputStr, "\n\n");
while (reader.next()) |group| {
var everyoneAnswered = [_]bool{true} ** 26;
var answered = [_]bool{false} ** 26;
for (group) |c| {
switch (c) {
'a'...'z' => answered[c - 'a'] = true,
'\n' => {
andEach(&everyoneAnswered, &answered);
answered = [_]bool{false} ** 26;
},
else => {},
}
}
if (group[group.len - 1] != '\n') {
andEach(&everyoneAnswered, &answered);
}
for (everyoneAnswered) |v| {
count += @boolToInt(v);
}
}
return count;
}
const expectEqual = std.testing.expectEqual;
test "countAnyone" {
expectEqual(@as(usize, 11), countAnyone(
\\abc
\\
\\a
\\b
\\c
\\
\\ab
\\ac
\\
\\a
\\a
\\a
\\a
\\
\\b
));
}
test "countEveryone" {
expectEqual(@as(usize, 6), countEveryone(
\\abc
\\
\\a
\\b
\\c
\\
\\ab
\\ac
\\
\\a
\\a
\\a
\\a
\\
\\b
));
}
|
src/day06.zig
|
// https://tools.ietf.org/html/rfc7914
// https://github.com/golang/crypto/blob/master/scrypt/scrypt.go
const std = @import("std");
const crypto = std.crypto;
const fmt = std.fmt;
const math = std.math;
const mem = std.mem;
const phc_format = @import("phc_encoding.zig");
const crypt_format = @import("crypt_encoding_scrypt.zig");
const pwhash = @import("pwhash.zig");
const HmacSha256 = crypto.auth.hmac.sha2.HmacSha256;
pub const KdfError = pwhash.KdfError;
pub const Error = KdfError || phc_format.Error || crypt_format.Error || error{AllocatorRequired};
const max_size = math.maxInt(usize);
const max_int = max_size >> 1;
const default_salt_len = 32;
const default_hash_len = 32;
const max_salt_len = 64;
const max_hash_len = 64;
fn blockCopy(dst: []align(16) u32, src: []align(16) const u32, n: usize) void {
mem.copy(u32, dst, src[0 .. n * 16]);
}
fn blockXor(dst: []align(16) u32, src: []align(16) const u32, n: usize) void {
for (src[0 .. n * 16]) |v, i| {
dst[i] ^= v;
}
}
const QuarterRound = struct { a: usize, b: usize, c: usize, d: u6 };
fn Rp(a: usize, b: usize, c: usize, d: u6) QuarterRound {
return QuarterRound{ .a = a, .b = b, .c = c, .d = d };
}
fn salsa8core(b: *align(16) [16]u32) void {
const arx_steps = comptime [_]QuarterRound{
Rp(4, 0, 12, 7), Rp(8, 4, 0, 9), Rp(12, 8, 4, 13), Rp(0, 12, 8, 18),
Rp(9, 5, 1, 7), Rp(13, 9, 5, 9), Rp(1, 13, 9, 13), Rp(5, 1, 13, 18),
Rp(14, 10, 6, 7), Rp(2, 14, 10, 9), Rp(6, 2, 14, 13), Rp(10, 6, 2, 18),
Rp(3, 15, 11, 7), Rp(7, 3, 15, 9), Rp(11, 7, 3, 13), Rp(15, 11, 7, 18),
Rp(1, 0, 3, 7), Rp(2, 1, 0, 9), Rp(3, 2, 1, 13), Rp(0, 3, 2, 18),
Rp(6, 5, 4, 7), Rp(7, 6, 5, 9), Rp(4, 7, 6, 13), Rp(5, 4, 7, 18),
Rp(11, 10, 9, 7), Rp(8, 11, 10, 9), Rp(9, 8, 11, 13), Rp(10, 9, 8, 18),
Rp(12, 15, 14, 7), Rp(13, 12, 15, 9), Rp(14, 13, 12, 13), Rp(15, 14, 13, 18),
};
var x = b.*;
var j: usize = 0;
while (j < 8) : (j += 2) {
inline for (arx_steps) |r| {
x[r.a] ^= math.rotl(u32, x[r.b] +% x[r.c], r.d);
}
}
j = 0;
while (j < 16) : (j += 1) {
b[j] +%= x[j];
}
}
fn salsaXor(tmp: *align(16) [16]u32, in: []align(16) const u32, out: []align(16) u32) void {
blockXor(tmp, in, 1);
salsa8core(tmp);
blockCopy(out, tmp, 1);
}
fn blockMix(tmp: *align(16) [16]u32, in: []align(16) const u32, out: []align(16) u32, r: u30) void {
blockCopy(tmp, in[(2 * r - 1) * 16 ..], 1);
var i: usize = 0;
while (i < 2 * r) : (i += 2) {
salsaXor(tmp, in[i * 16 ..], out[i * 8 ..]);
salsaXor(tmp, in[i * 16 + 16 ..], out[i * 8 + r * 16 ..]);
}
}
fn integerify(b: []align(16) const u32, r: u30) u64 {
const j = (2 * r - 1) * 16;
return @as(u64, b[j]) | @as(u64, b[j + 1]) << 32;
}
fn smix(b: []align(16) u8, r: u30, n: usize, v: []align(16) u32, xy: []align(16) u32) void {
var x = xy[0 .. 32 * r];
var y = xy[32 * r ..];
for (x) |*v1, j| {
v1.* = mem.readIntSliceLittle(u32, b[4 * j ..]);
}
var tmp: [16]u32 align(16) = undefined;
var i: usize = 0;
while (i < n) : (i += 2) {
blockCopy(v[i * (32 * r) ..], x, 2 * r);
blockMix(&tmp, x, y, r);
blockCopy(v[(i + 1) * (32 * r) ..], y, 2 * r);
blockMix(&tmp, y, x, r);
}
i = 0;
while (i < n) : (i += 2) {
// 32bit downcast
var j = @intCast(usize, integerify(x, r) & (n - 1));
blockXor(x, v[j * (32 * r) ..], 2 * r);
blockMix(&tmp, x, y, r);
// 32bit downcast
j = @intCast(usize, integerify(y, r) & (n - 1));
blockXor(y, v[j * (32 * r) ..], 2 * r);
blockMix(&tmp, y, x, r);
}
for (x) |v1, j| {
mem.writeIntLittle(u32, b[4 * j ..][0..4], v1);
}
}
pub const Params = struct {
const Self = @This();
ln: u6,
r: u30,
p: u30,
/// Baseline parameters for interactive logins
pub const interactive = Self.fromLimits(524288, 16777216);
/// Baseline parameters for offline usage
pub const sensitive = Self.fromLimits(33554432, 1073741824);
/// Create parameters from ops and mem limits
pub fn fromLimits(ops_limit: u64, mem_limit: usize) Self {
const ops = math.max(32768, ops_limit);
const r: u30 = 8;
if (ops < mem_limit / 32) {
const max_n = ops / (r * 4);
return Self{ .r = r, .p = 1, .ln = @intCast(u6, math.log2(max_n)) };
} else {
const max_n = mem_limit / (@intCast(usize, r) * 128);
const ln = @intCast(u6, math.log2(max_n));
const max_rp = math.min(0x3fffffff, (ops / 4) / (@as(u64, 1) << ln));
return Self{ .r = r, .p = @intCast(u30, max_rp / @as(u64, r)), .ln = ln };
}
}
};
/// Apply scrypt to generate a key from a password.
///
/// scrypt is defined in RFC 7914.
///
/// allocator: *mem.Allocator.
///
/// derived_key: Slice of appropriate size for generated key. Generally 16 or 32 bytes in length.
/// May be uninitialized. All bytes will be overwritten.
/// Maximum size is `derived_key.len / 32 == 0xffff_ffff`.
///
/// password: Arbitrary sequence of bytes of any length.
///
/// salt: Arbitrary sequence of bytes of any length.
///
/// params: Params.
pub fn kdf(
allocator: *mem.Allocator,
derived_key: []u8,
password: []const u8,
salt: []const u8,
params: Params,
) KdfError!void {
if (derived_key.len == 0 or derived_key.len / 32 > 0xffff_ffff) {
return KdfError.OutputTooLong;
}
if (params.ln == 0 or params.r == 0 or params.p == 0) {
return KdfError.WeakParameters;
}
const n64 = @as(u64, 1) << params.ln;
if (n64 > max_size) {
return KdfError.WeakParameters;
}
const n = @intCast(usize, n64);
if (@as(u64, params.r) * @as(u64, params.p) >= 1 << 30 or
params.r > max_int / 128 / @as(u64, params.p) or
params.r > max_int / 256 or
n > max_int / 128 / @as(u64, params.r))
{
return KdfError.WeakParameters;
}
var xy = try allocator.alignedAlloc(u32, 16, 64 * params.r);
defer allocator.free(xy);
var v = try allocator.alignedAlloc(u32, 16, 32 * n * params.r);
defer allocator.free(v);
var dk = try allocator.alignedAlloc(u8, 16, params.p * 128 * params.r);
defer allocator.free(dk);
try crypto.pwhash.pbkdf2(dk, password, salt, 1, HmacSha256);
var i: u32 = 0;
while (i < params.p) : (i += 1) {
smix(dk[i * 128 * params.r ..], params.r, n, v, xy);
}
try crypto.pwhash.pbkdf2(derived_key, password, dk, 1, HmacSha256);
}
/// Hash and verify passwords using the PHC format.
const PhcFormatHasher = struct {
const BinValue = phc_format.BinValue;
const HashResult = struct {
alg_id: []const u8,
ln: u6,
r: u30,
p: u30,
salt: BinValue(max_salt_len),
hash: BinValue(max_hash_len),
};
/// Return a non-deterministic hash of the password encoded as a PHC-format string
pub fn create(
allocator: *mem.Allocator,
password: []const u8,
params: Params,
buf: []u8,
) (phc_format.Error || KdfError)![]const u8 {
var salt: [default_salt_len]u8 = undefined;
crypto.random.bytes(&salt);
var hash: [default_hash_len]u8 = undefined;
try kdf(allocator, &hash, password, &salt, params);
return phc_format.serialize(HashResult{
.alg_id = "scrypt",
.ln = params.ln,
.r = params.r,
.p = params.p,
.salt = try BinValue(max_salt_len).fromSlice(&salt),
.hash = try BinValue(max_hash_len).fromSlice(&hash),
}, buf);
}
/// Verify a password against a PHC-format encoded string
pub fn verify(
allocator: *mem.Allocator,
str: []const u8,
password: []const u8,
) (phc_format.Error || KdfError)!void {
const hash_result = try phc_format.deserialize(HashResult, str);
if (!mem.eql(u8, hash_result.alg_id, "scrypt")) return KdfError.PasswordVerificationFailed;
const params = Params{ .ln = hash_result.ln, .r = hash_result.r, .p = hash_result.p };
const expected_hash = hash_result.hash.unwrap();
var hash_buf: [max_hash_len]u8 = undefined;
if (expected_hash.len > hash_buf.len) return KdfError.InvalidEncoding;
var hash = hash_buf[0..expected_hash.len];
try kdf(allocator, hash, password, hash_result.salt.unwrap(), params);
if (!mem.eql(u8, hash, expected_hash)) return KdfError.PasswordVerificationFailed;
}
};
/// Hash and verify passwords using the modular crypt format.
const CryptFormatHasher = struct {
const BinValue = crypt_format.BinValue;
const HashResult = crypt_format.HashResult(max_hash_len);
/// Length of a string returned by the create() function
pub const pwhash_str_length: usize = 101;
/// Return a non-deterministic hash of the password encoded into the modular crypt format
pub fn create(
allocator: *mem.Allocator,
password: []const u8,
params: Params,
buf: []u8,
) (crypt_format.Error || KdfError)![]const u8 {
var salt_bin: [default_salt_len]u8 = undefined;
crypto.random.bytes(&salt_bin);
const salt = crypt_format.saltFromBin(salt_bin.len, salt_bin);
var hash: [default_hash_len]u8 = undefined;
try kdf(allocator, &hash, password, &salt, params);
return crypt_format.serialize(HashResult{
.ln = params.ln,
.r = params.r,
.p = params.p,
.salt = &salt,
.hash = try BinValue(max_hash_len).fromSlice(&hash),
}, buf);
}
/// Verify a password against a string in modular crypt format
pub fn verify(
allocator: *mem.Allocator,
str: []const u8,
password: []const u8,
) (crypt_format.Error || KdfError)!void {
const hash_result = try crypt_format.deserialize(HashResult, str);
const params = Params{ .ln = hash_result.ln, .r = hash_result.r, .p = hash_result.p };
const expected_hash = hash_result.hash.unwrap();
var hash_buf: [max_hash_len]u8 = undefined;
if (expected_hash.len > hash_buf.len) return KdfError.InvalidEncoding;
var hash = hash_buf[0..expected_hash.len];
try kdf(allocator, hash, password, hash_result.salt, params);
if (!mem.eql(u8, hash, expected_hash)) return KdfError.PasswordVerificationFailed;
}
};
/// Options for hashing a password.
pub const HashOptions = struct {
allocator: ?*mem.Allocator,
kdf_params: Params,
encoding: pwhash.Encoding,
};
/// Compute a hash of a password using the scrypt key derivation function.
/// The function returns a string that includes all the parameters required for verification.
pub fn strHash(
password: []const u8,
options: HashOptions,
out: []u8,
) Error![]const u8 {
const allocator = options.allocator orelse return Error.AllocatorRequired;
switch (options.encoding) {
.phc => return PhcFormatHasher.create(allocator, password, options.kdf_params, out),
.crypt => return CryptFormatHasher.create(allocator, password, options.kdf_params, out),
}
}
/// Options for hash verification.
pub const VerifyOptions = struct {
allocator: ?*mem.Allocator,
};
/// Verify that a previously computed hash is valid for a given password.
pub fn strVerify(
str: []const u8,
password: []const u8,
options: VerifyOptions,
) Error!void {
const allocator = options.allocator orelse return Error.AllocatorRequired;
if (mem.startsWith(u8, str, crypt_format.prefix)) {
return CryptFormatHasher.verify(allocator, str, password);
} else {
return PhcFormatHasher.verify(allocator, str, password);
}
}
test "kdf" {
const password = "<PASSWORD>";
const salt = "<PASSWORD>";
var dk: [32]u8 = undefined;
try kdf(std.testing.allocator, &dk, password, salt, .{ .ln = 15, .r = 8, .p = 1 });
const hex = "1e0f97c3f6609024022fbe698da29c2fe53ef1087a8e396dc6d5d2a041e886de";
var bytes: [hex.len / 2]u8 = undefined;
_ = try fmt.hexToBytes(&bytes, hex);
try std.testing.expectEqualSlices(u8, &bytes, &dk);
}
test "kdf rfc 1" {
const password = "";
const salt = "";
var dk: [64]u8 = undefined;
try kdf(std.testing.allocator, &dk, password, salt, .{ .ln = 4, .r = 1, .p = 1 });
const hex = "77d6576238657b203b19ca42c18a0497f16b4844e3074ae8dfdffa3fede21442fcd0069ded0948f8326a753a0fc81f17e8d3e0fb2e0d3628cf35e20c38d18906";
var bytes: [hex.len / 2]u8 = undefined;
_ = try fmt.hexToBytes(&bytes, hex);
try std.testing.expectEqualSlices(u8, &bytes, &dk);
}
test "kdf rfc 2" {
const password = "password";
const salt = "<PASSWORD>";
var dk: [64]u8 = undefined;
try kdf(std.testing.allocator, &dk, password, salt, .{ .ln = 10, .r = 8, .p = 16 });
const hex = "fdbabe1c9d3472007856e7190d01e9fe7c6ad7cbc8237830e77376634b3731622eaf30d92e22a3886ff109279d9830dac727afb94a83ee6d8360cbdfa2cc0640";
var bytes: [hex.len / 2]u8 = undefined;
_ = try fmt.hexToBytes(&bytes, hex);
try std.testing.expectEqualSlices(u8, &bytes, &dk);
}
test "kdf rfc 3" {
const password = "<PASSWORD>";
const salt = "S<PASSWORD>";
var dk: [64]u8 = undefined;
try kdf(std.testing.allocator, &dk, password, salt, .{ .ln = 14, .r = 8, .p = 1 });
const hex = "7023bdcb3afd7348461c06cd81fd38ebfda8fbba904f8e3ea9b543f6545da1f2d5432955613f0fcf62d49705242a9af9e61e85dc0d651e40dfcf017b45575887";
var bytes: [hex.len / 2]u8 = undefined;
_ = try fmt.hexToBytes(&bytes, hex);
try std.testing.expectEqualSlices(u8, &bytes, &dk);
}
test "kdf rfc 4" {
// skip slow test
if (true) {
return error.SkipZigTest;
}
const password = "<PASSWORD>";
const salt = "S<PASSWORD>Chloride";
var dk: [64]u8 = undefined;
try kdf(std.testing.allocator, &dk, password, salt, .{ .ln = 20, .r = 8, .p = 1 });
const hex = "2101cb9b6a511aaeaddbbe09cf70f881ec568d574a2ffd4dabe5ee9820adaa478e56fd8f4ba5d09ffa1c6d927c40f4c337304049e8a952fbcbf45c6fa77a41a4";
var bytes: [hex.len / 2]u8 = undefined;
_ = try fmt.hexToBytes(&bytes, hex);
try std.testing.expectEqualSlices(u8, &bytes, &dk);
}
test "password hashing (crypt format)" {
const str = "$7$A6....1....TrXs5Zk6s8sWHpQgWDIXTR8kUU3s6Jc3s.DtdS8M2i4$a4ik5hGDN7foMuHOW.cp.CtX01UyCeO0.JAG.AHPpx5";
const password = "<PASSWORD>(`";
try CryptFormatHasher.verify(std.testing.allocator, str, password);
const params = Params.interactive;
var buf: [CryptFormatHasher.pwhash_str_length]u8 = undefined;
const str2 = try CryptFormatHasher.create(std.testing.allocator, password, params, &buf);
try CryptFormatHasher.verify(std.testing.allocator, str2, password);
}
test "strHash and strVerify" {
const alloc = std.testing.allocator;
const password = "<PASSWORD>";
const verify_options = VerifyOptions{ .allocator = alloc };
var buf: [128]u8 = undefined;
const s = try strHash(
password,
HashOptions{ .allocator = alloc, .kdf_params = Params.interactive, .encoding = .crypt },
&buf,
);
try strVerify(s, password, verify_options);
const s1 = try strHash(
password,
HashOptions{ .allocator = alloc, .kdf_params = Params.interactive, .encoding = .phc },
&buf,
);
try strVerify(s1, password, verify_options);
}
test "unix-scrypt" {
const alloc = std.testing.allocator;
// https://gitlab.com/jas/scrypt-unix-crypt/blob/master/unix-scrypt.txt
{
const str = "$7$C6..../....SodiumChloride$kBGj9fHznVYFQMEn/qDCfrDevf9YDtcDdKvEqHJLV8D";
const password = "<PASSWORD>";
try strVerify(str, password, .{ .allocator = alloc });
}
// one of the libsodium test vectors
{
const str = "$7$B6....1....75gBMAGwfFWZqBdyF3WdTQnWdUsuTiWjG1fF9c1jiSD$tc8RoB3.Em3/zNgMLWo2u00oGIoTyJv4fl3Fl8Tix72";
const password = "^T5H$JY<PASSWORD>:<PASSWORD>?vg!:jGi]Ax?..l7[p0v:1j<PASSWORD>a9;]bUN;?bWyCbtqg nrDFal+Jxl3,2`#^tFSu%v_+7iYse8-cCkNf!tD=KrW)";
try strVerify(str, password, .{ .allocator = alloc });
}
}
|
src/scrypt.zig
|
const std = @import("std");
const builtin = @import("builtin");
const assert = std.debug.assert;
const meta = std.meta;
const c = @cImport({
@cInclude("stdio.h");
@cInclude("string.h");
@cInclude("unistd.h");
@cInclude("time.h");
@cInclude("errno.h");
@cInclude("stdintfix.h"); // NB: Required as zig is unable to process some macros
@cInclude("SDL2/SDL.h");
@cInclude("SDL2/SDL_syswm.h");
@cInclude("GL/gl.h");
@cInclude("GL/glx.h");
@cInclude("GL/glext.h");
@cInclude("bgfx/c99/bgfx.h");
});
fn sdlSetWindow(window: *c.SDL_Window) !void {
var wmi: c.SDL_SysWMinfo = undefined;
wmi.version.major = c.SDL_MAJOR_VERSION;
wmi.version.minor = c.SDL_MINOR_VERSION;
wmi.version.patch = c.SDL_PATCHLEVEL;
if (c.SDL_GetWindowWMInfo(window, &wmi) == c.SDL_FALSE) {
return error.SDL_FAILED_INIT;
}
var pd = std.mem.zeroes(c.bgfx_platform_data_t);
if (builtin.os.tag == .linux) {
pd.ndt = wmi.info.x11.display;
pd.nwh = @intToPtr(*anyopaque, wmi.info.x11.window);
}
if (builtin.os.tag == .freebsd) {
pd.ndt = wmi.info.x11.display;
pd.nwh = @intToPtr(*anyopaque, wmi.info.x11.window);
}
if (builtin.os.tag == .macos) {
pd.ndt = null;
pd.nwh = wmi.info.cocoa.window;
}
if (builtin.os.tag == .windows) {
pd.ndt = null;
pd.nwh = wmi.info.win.window;
}
//if (builtin.os.tag == .steamlink) {
// pd.ndt = wmi.info.vivante.display;
// pd.nwh = wmi.info.vivante.window;
//}
pd.context = null;
pd.backBuffer = null;
pd.backBufferDS = null;
c.bgfx_set_platform_data(&pd);
}
pub fn main() !void {
_ = c.SDL_Init(0);
defer c.SDL_Quit();
const window = c.SDL_CreateWindow("bgfx", c.SDL_WINDOWPOS_UNDEFINED, c.SDL_WINDOWPOS_UNDEFINED, 800, 600, c.SDL_WINDOW_SHOWN | c.SDL_WINDOW_RESIZABLE).?;
defer c.SDL_DestroyWindow(window);
try sdlSetWindow(window);
var in = std.mem.zeroes(c.bgfx_init_t);
in.type = c.BGFX_RENDERER_TYPE_COUNT; // Automatically choose a renderer.
in.resolution.width = 800;
in.resolution.height = 600;
in.resolution.reset = c.BGFX_RESET_VSYNC;
var success = c.bgfx_init(&in);
defer c.bgfx_shutdown();
assert(success);
c.bgfx_set_debug(c.BGFX_DEBUG_TEXT);
c.bgfx_set_view_clear(0, c.BGFX_CLEAR_COLOR | c.BGFX_CLEAR_DEPTH, 0x443355FF, 1.0, 0);
c.bgfx_set_view_rect(0, 0, 0, 800, 600);
var frame_number: u64 = 0;
gameloop: while (true) {
var event: c.SDL_Event = undefined;
var should_exit = false;
while (c.SDL_PollEvent(&event) == 1) {
switch (event.type) {
c.SDL_QUIT => should_exit = true,
c.SDL_WINDOWEVENT => {
const wev = &event.window;
switch (wev.event) {
c.SDL_WINDOWEVENT_RESIZED, c.SDL_WINDOWEVENT_SIZE_CHANGED => {},
c.SDL_WINDOWEVENT_CLOSE => should_exit = true,
else => {},
}
},
else => {},
}
}
if (should_exit) break :gameloop;
c.bgfx_set_view_rect(0, 0, 0, 800, 600);
c.bgfx_touch(0);
c.bgfx_dbg_text_clear(0, false);
c.bgfx_dbg_text_printf(0, 1, 0x4f, "Frame#:%d", frame_number);
frame_number = c.bgfx_frame(false);
}
}
|
src/main.zig
|
const std = @import("std");
const tools = @import("tools");
const with_trace = false;
const with_dissassemble = false;
const assert = std.debug.assert;
fn trace(comptime fmt: []const u8, args: anytype) void {
if (with_trace) std.debug.print(fmt, args);
}
const Computer = tools.IntCode_Computer;
const Vec2 = tools.Vec2;
const MapTile = u3;
fn tile_to_char(m: MapTile) u8 {
const tile_colors = [_]u8{ ' ', '#', '-', '=', 'o' };
return tile_colors[m];
}
pub fn run(input: []const u8, allocator: std.mem.Allocator) ![2][]const u8 {
const int_count = blk: {
var int_count: usize = 0;
var it = std.mem.split(u8, input, ",");
while (it.next()) |_| int_count += 1;
break :blk int_count;
};
const boot_image = try allocator.alloc(Computer.Data, int_count);
defer allocator.free(boot_image);
{
var it = std.mem.split(u8, input, ",");
var i: usize = 0;
while (it.next()) |n_text| : (i += 1) {
const trimmed = std.mem.trim(u8, n_text, " \n\r\t");
boot_image[i] = try std.fmt.parseInt(Computer.Data, trimmed, 10);
}
}
if (with_dissassemble)
Computer.disassemble(boot_image);
const Arcade = struct {
const screen_size = 40;
screen: tools.Map(u3, screen_size, screen_size, false),
score_display: Computer.Data,
joystick: Computer.Data,
cpu: Computer,
cpu_out: SerialOut,
ball: ?Vec2,
pad: ?Vec2,
const SerialOut = struct {
pos: Vec2,
val: Computer.Data,
cycle: u32,
};
};
var arcade = Arcade{
.screen = .{ .default_tile = 0 },
.score_display = 0,
.joystick = 0,
.cpu = Computer{
.name = "ArcadeCpu",
.memory = try allocator.alloc(Computer.Data, 10000),
},
.cpu_out = Arcade.SerialOut{ .pos = undefined, .val = undefined, .cycle = 0 },
.ball = null,
.pad = null,
};
defer allocator.free(arcade.cpu.memory);
// part 1:
const nb_blocks = part1: {
//arcade.screen.fill(0, null);
const c = &arcade.cpu;
const cpu_out = &arcade.cpu_out;
c.boot(boot_image);
_ = async c.run();
while (!c.is_halted()) {
assert(c.io_mode == .output);
switch (cpu_out.cycle) {
0 => cpu_out.pos.x = @intCast(i32, c.io_port),
1 => cpu_out.pos.y = @intCast(i32, c.io_port),
2 => cpu_out.val = c.io_port,
else => unreachable,
}
cpu_out.cycle += 1;
if (cpu_out.cycle >= 3) {
cpu_out.cycle = 0;
assert(cpu_out.pos.x >= 0 and cpu_out.pos.y >= 0);
arcade.screen.set(cpu_out.pos, @intCast(MapTile, cpu_out.val));
}
resume c.io_runframe;
}
var blocks: usize = 0;
for (arcade.screen.map) |m| {
if (m == 2)
blocks += 1;
}
break :part1 blocks;
};
// part 2
{
arcade.cpu.boot(boot_image);
arcade.cpu.memory[0] = 2; // mode 'gratuit''
trace("starting {}\n", .{arcade.cpu.name});
_ = async arcade.cpu.run();
const c = &arcade.cpu;
const cpu_out = &arcade.cpu_out;
while (!c.is_halted()) {
if (arcade.ball) |ball| {
if (arcade.pad) |pad| {
if (pad.x > ball.x) {
arcade.joystick = -1;
} else if (pad.x < ball.x) {
arcade.joystick = 1;
} else {
arcade.joystick = 0;
}
}
}
if (c.io_mode == .input) {
c.io_port = arcade.joystick;
trace("wrting input to {} = {}\n", .{ c.name, c.io_port });
} else if (c.io_mode == .output) {
trace("{} outputs {}\n", .{ c.name, c.io_port });
switch (cpu_out.cycle) {
0 => cpu_out.pos.x = @intCast(i32, c.io_port),
1 => cpu_out.pos.y = @intCast(i32, c.io_port),
2 => cpu_out.val = c.io_port,
else => unreachable,
}
cpu_out.cycle += 1;
if (cpu_out.cycle >= 3) {
cpu_out.cycle = 0;
if (cpu_out.pos.x < 0 or cpu_out.pos.y < 0) {
arcade.score_display = cpu_out.val;
} else {
arcade.screen.set(cpu_out.pos, @intCast(MapTile, cpu_out.val));
if (cpu_out.val == 3) arcade.pad = cpu_out.pos;
if (cpu_out.val == 4) arcade.ball = cpu_out.pos;
}
}
}
trace("resuming {}\n", .{c.name});
resume c.io_runframe;
}
var storage: [10000]u8 = undefined;
trace("{}, \n score = {}\n", .{ arcade.screen.printToBuf(null, null, tile_to_char, &storage), arcade.score_display });
}
return [_][]const u8{
try std.fmt.allocPrint(allocator, "{}", .{nb_blocks}),
try std.fmt.allocPrint(allocator, "{}", .{arcade.score_display}),
};
}
pub const main = tools.defaultMain("2019/day13.txt", run);
|
2019/day13.zig
|
pub const Opcode = enum(u8) {
NOP = 0x00,
LD_B_n = 0x06,
LD_C_n = 0x0E,
LD_D_n = 0x16,
LD_E_n = 0x1E,
LD_H_n = 0x26,
LD_L_n = 0x2E,
LD_A_A = 0x7F,
LD_A_B = 0x78,
LD_A_C = 0x79,
LD_A_D = 0x7A,
LD_A_E = 0x7B,
LD_A_H = 0x7C,
LD_A_L = 0x7D,
LD_A_HL = 0x7E,
LD_B_B = 0x40,
LD_B_C = 0x41,
LD_B_D = 0x42,
LD_B_E = 0x43,
LD_B_H = 0x44,
LD_B_L = 0x45,
LD_B_HL = 0x46,
LD_C_B = 0x48,
LD_C_C = 0x49,
LD_C_D = 0x4A,
LD_C_E = 0x4B,
LD_C_H = 0x4C,
LD_C_L = 0x4D,
LD_C_HL = 0x4E,
LD_D_B = 0x50,
LD_D_C = 0x51,
LD_D_D = 0x52,
LD_D_E = 0x53,
LD_D_H = 0x54,
LD_D_L = 0x55,
LD_D_HL = 0x56,
LD_E_B = 0x58,
LD_E_C = 0x59,
LD_E_D = 0x5A,
LD_E_E = 0x5B,
LD_E_H = 0x5C,
LD_E_L = 0x5D,
LD_E_HL = 0x5E,
LD_H_B = 0x60,
LD_H_C = 0x61,
LD_H_D = 0x62,
LD_H_E = 0x63,
LD_H_H = 0x64,
LD_H_L = 0x65,
LD_H_HL = 0x66,
LD_L_B = 0x68,
LD_L_C = 0x69,
LD_L_D = 0x6A,
LD_L_E = 0x6B,
LD_L_H = 0x6C,
LD_L_L = 0x6D,
LD_L_HL = 0x6E,
LD_HL_B = 0x70,
LD_HL_C = 0x71,
LD_HL_D = 0x72,
LD_HL_E = 0x73,
LD_HL_H = 0x74,
LD_HL_L = 0x75,
LD_HL_n = 0x36,
LD_A_BC = 0x0A,
LD_A_DE = 0x1A,
LD_A_nn = 0xFA,
LD_A_n = 0x3E,
LD_B_A = 0x47,
LD_C_A = 0x4F,
LD_D_A = 0x57,
LD_E_A = 0x5F,
LD_H_A = 0x67,
LD_L_A = 0x6F,
LD_BC_A = 0x02,
LD_DE_A = 0x12,
LD_HL_A = 0x77,
LD_nn_A = 0xEA,
LD_A_mem_C = 0xF2,
LD_mem_C_A = 0xE2,
LDD_A_HL = 0x3A,
LDD_HL_A = 0x32,
LDI_A_HL = 0x2A,
LDI_HL_A = 0x22,
LDH_n_A = 0xE0,
LDH_A_n = 0xF0,
LD_BC_nn = 0x01,
LD_DE_nn = 0x11,
LD_HL_nn = 0x21,
LD_SP_nn = 0x31,
LD_SP_HL = 0xF9,
LDHL_SP_n = 0xF8,
LD_nn_SP = 0x08,
PUSH_AF = 0xF5,
PUSH_BC = 0xC5,
PUSH_DE = 0xD5,
PUSH_HL = 0xE5,
POP_AF = 0xF1,
POP_BC = 0xC1,
POP_DE = 0xD1,
POP_HL = 0xE1,
ADD_A_A = 0x87,
ADD_A_B = 0x80,
ADD_A_C = 0x81,
ADD_A_D = 0x82,
ADD_A_E = 0x83,
ADD_A_H = 0x84,
ADD_A_L = 0x85,
ADD_A_HL = 0x86,
ADD_A_n = 0xCE,
ADC_A_A = 0x8F,
ADC_A_B = 0x88,
ADC_A_C = 0x89,
ADC_A_D = 0x8A,
ADC_A_E = 0x8B,
ADC_A_H = 0x8C,
ADC_A_L = 0x8D,
ADC_A_HL = 0x8E,
ADC_A_n = 0xC6,
SUB_A_A = 0x97,
SUB_A_B = 0x90,
SUB_A_C = 0x91,
SUB_A_D = 0x92,
SUB_A_E = 0x93,
SUB_A_H = 0x94,
SUB_A_L = 0x95,
SUB_A_HL = 0x96,
SUB_A_n = 0xDE,
SBC_A_A = 0x9F,
SBC_A_B = 0x98,
SBC_A_C = 0x99,
SBC_A_D = 0x9A,
SBC_A_E = 0x9B,
SBC_A_H = 0x9C,
SBC_A_L = 0x9D,
SBC_A_HL = 0x9E,
SBC_A_n = 0xD6,
AND_A_A = 0xA7,
AND_A_B = 0xA0,
AND_A_C = 0xA1,
AND_A_D = 0xA2,
AND_A_E = 0xA3,
AND_A_H = 0xA4,
AND_A_L = 0xA5,
AND_A_HL = 0xA6,
AND_A_n = 0xE6,
OR_A_A = 0xB7,
OR_A_B = 0xB0,
OR_A_C = 0xB1,
OR_A_D = 0xB2,
OR_A_E = 0xB3,
OR_A_H = 0xB4,
OR_A_L = 0xB5,
OR_A_HL = 0xB6,
OR_A_n = 0xF6,
XOR_A_A = 0xAF,
XOR_A_B = 0xA8,
XOR_A_C = 0xA9,
XOR_A_D = 0xAA,
XOR_A_E = 0xAB,
XOR_A_H = 0xAC,
XOR_A_L = 0xAD,
XOR_A_HL = 0xAE,
XOR_A_n = 0xEE,
CP_A_A = 0xBF,
CP_A_B = 0xB8,
CP_A_C = 0xB9,
CP_A_D = 0xBA,
CP_A_E = 0xBB,
CP_A_H = 0xBC,
CP_A_L = 0xBD,
CP_A_HL = 0xBE,
CP_A_n = 0xFE,
INC_A = 0x3C,
INC_B = 0x04,
INC_C = 0x0C,
INC_D = 0x14,
INC_E = 0x1C,
INC_H = 0x24,
INC_L = 0x2C,
INC_mem_HL = 0x34,
DEC_A = 0x3D,
DEC_B = 0x05,
DEC_C = 0x0D,
DEC_D = 0x15,
DEC_E = 0x1D,
DEC_H = 0x25,
DEC_L = 0x2D,
DEC_mem_HL = 0x35,
ADD_HL_BC = 0x09,
ADD_HL_DE = 0x19,
ADD_HL_HL = 0x29,
ADD_HL_SP = 0x39,
ADD_SP_n = 0xE8,
INC_BC = 0x03,
INC_DE = 0x13,
INC_HL = 0x23,
INC_SP = 0x33,
DEC_BC = 0x0B,
DEC_DE = 0x1B,
DEC_HL = 0x2B,
DEC_SP = 0x3B,
MISC = 0xCB,
DAA = 0x27,
CPL = 0x2F,
CCF = 0x3F,
SCF = 0x37,
HALT = 0x76,
STOP_FIRST_BYTE = 0x10,
DI = 0xF3,
EI = 0xFB,
RLCA = 0x07,
RLA = 0x17,
RRCA = 0x0F,
RRA = 0x1F,
JP_nn = 0xC3,
JP_NZ_nn = 0xC2,
JP_Z_nn = 0xCA,
JP_NC_nn = 0xD2,
JP_C_nn = 0xDA,
JP_HL = 0xE9,
JR_n = 0x18,
JR_NZ_n = 0x20,
JR_Z_n = 0x28,
JR_NC_n = 0x30,
JR_C_n = 0x38,
CALL_nn = 0xCD,
CALL_NZ_nn = 0xC4,
CALL_Z_nn = 0xCC,
CALL_NC_nn = 0xD4,
CALL_C_nn = 0xDC,
RST_00 = 0xC7,
RST_08 = 0xCF,
RST_10 = 0xD7,
RST_18 = 0xDF,
RST_20 = 0xE7,
RST_28 = 0xEF,
RST_30 = 0xF7,
RST_38 = 0xFF,
RET = 0xC9,
RET_NZ = 0xC0,
RET_Z = 0xC8,
RET_NC = 0xD0,
RET_C = 0xD8,
RETI = 0xD9,
};
pub const MiscOpcode = enum(u8) {
SWAP_A = 0x37,
SWAP_B = 0x30,
SWAP_C = 0x31,
SWAP_D = 0x32,
SWAP_E = 0x33,
SWAP_H = 0x34,
SWAP_L = 0x35,
SWAP_HL = 0x36,
RLC_A = 0x07,
RLC_B = 0x00,
RLC_C = 0x01,
RLC_D = 0x02,
RLC_E = 0x03,
RLC_H = 0x04,
RLC_L = 0x05,
RLC_HL = 0x06,
RL_A = 0x17,
RL_B = 0x10,
RL_C = 0x11,
RL_D = 0x12,
RL_E = 0x13,
RL_H = 0x14,
RL_L = 0x15,
RL_HL = 0x16,
RRC_A = 0x0F,
RRC_B = 0x08,
RRC_C = 0x09,
RRC_D = 0x0A,
RRC_E = 0x0B,
RRC_H = 0x0C,
RRC_L = 0x0D,
RRC_HL = 0x0E,
RR_A = 0x1F,
RR_B = 0x18,
RR_C = 0x19,
RR_D = 0x1A,
RR_E = 0x1B,
RR_H = 0x1C,
RR_L = 0x1D,
RR_HL = 0x1E,
SLA_A = 0x27,
SLA_B = 0x20,
SLA_C = 0x21,
SLA_D = 0x22,
SLA_E = 0x23,
SLA_H = 0x24,
SLA_L = 0x25,
SLA_HL = 0x26,
SRA_A = 0x2F,
SRA_B = 0x28,
SRA_C = 0x29,
SRA_D = 0x2A,
SRA_E = 0x2B,
SRA_H = 0x2C,
SRA_L = 0x2D,
SRA_HL = 0x2E,
SRL_A = 0x3F,
SRL_B = 0x38,
SRL_C = 0x39,
SRL_D = 0x3A,
SRL_E = 0x3B,
SRL_H = 0x3C,
SRL_L = 0x3D,
SRL_HL = 0x3E,
BIT_A = 0x47,
BIT_B = 0x40,
BIT_C = 0x41,
BIT_D = 0x42,
BIT_E = 0x43,
BIT_H = 0x44,
BIT_L = 0x45,
BIT_HL = 0x46,
SET_A = 0xC7,
SET_B = 0xC0,
SET_C = 0xC1,
SET_D = 0xC2,
SET_E = 0xC3,
SET_H = 0xC4,
SET_L = 0xC5,
SET_HL = 0xC6,
RES_A = 0x87,
RES_B = 0x80,
RES_C = 0x81,
RES_D = 0x82,
RES_E = 0x83,
RES_H = 0x84,
RES_L = 0x85,
RES_HL = 0x86,
};
|
src/opcode.zig
|
const std = @import("std");
const mem = std.mem;
const meta = std.meta;
const net = std.net;
usingnamespace @import("../frame.zig");
usingnamespace @import("../primitive_types.zig");
usingnamespace @import("../query_parameters.zig");
const testing = @import("../testing.zig");
/// EXECUTE is sent to execute a prepared query.
///
/// Described in the protocol spec at §4.1.6
pub const ExecuteFrame = struct {
const Self = @This();
query_id: []const u8,
result_metadata_id: ?[]const u8,
query_parameters: QueryParameters,
pub fn write(self: Self, protocol_version: ProtocolVersion, pw: *PrimitiveWriter) !void {
_ = try pw.writeShortBytes(self.query_id);
if (protocol_version.is(5)) {
if (self.result_metadata_id) |id| {
_ = try pw.writeShortBytes(id);
}
}
_ = try self.query_parameters.write(protocol_version, pw);
}
pub fn read(allocator: *mem.Allocator, protocol_version: ProtocolVersion, pr: *PrimitiveReader) !Self {
var frame = Self{
.query_id = undefined,
.result_metadata_id = null,
.query_parameters = undefined,
};
frame.query_id = (try pr.readShortBytes(allocator)) orelse &[_]u8{};
if (protocol_version.is(5)) {
frame.result_metadata_id = try pr.readShortBytes(allocator);
}
frame.query_parameters = try QueryParameters.read(allocator, protocol_version, pr);
return frame;
}
};
test "execute frame" {
var arena = testing.arenaAllocator();
defer arena.deinit();
// read
const exp = "\x04\x00\x01\x00\x0a\x00\x00\x00\x37\x00\x10\x97\x97\x95\x6d\xfe\xb2\x4c\x99\x86\x8e\xd3\x84\xff\x6f\xd9\x4c\x00\x04\x27\x00\x01\x00\x00\x00\x10\xeb\x11\xc9\x1e\xd8\xcc\x48\x4d\xaf\x55\xe9\x9f\x5c\xd9\xec\x4a\x00\x00\x13\x88\x00\x05\xa2\x41\x4c\x1b\x06\x4c";
const raw_frame = try testing.readRawFrame(&arena.allocator, exp);
checkHeader(Opcode.Execute, exp.len, raw_frame.header);
var pr = PrimitiveReader.init();
pr.reset(raw_frame.body);
const frame = try ExecuteFrame.read(&arena.allocator, raw_frame.header.version, &pr);
const exp_query_id = "\x97\x97\x95\x6d\xfe\xb2\x4c\x99\x86\x8e\xd3\x84\xff\x6f\xd9\x4c";
testing.expectEqualSlices(u8, exp_query_id, frame.query_id);
testing.expectEqual(Consistency.Quorum, frame.query_parameters.consistency_level);
const values = frame.query_parameters.values.?.Normal;
testing.expectEqual(@as(usize, 1), values.len);
testing.expectEqualSlices(u8, "\xeb\x11\xc9\x1e\xd8\xcc\x48\x4d\xaf\x55\xe9\x9f\x5c\xd9\xec\x4a", values[0].Set);
testing.expectEqual(@as(u32, 5000), frame.query_parameters.page_size.?);
testing.expect(frame.query_parameters.paging_state == null);
testing.expect(frame.query_parameters.serial_consistency_level == null);
testing.expectEqual(@as(u64, 1585776216966732), frame.query_parameters.timestamp.?);
testing.expect(frame.query_parameters.keyspace == null);
testing.expect(frame.query_parameters.now_in_seconds == null);
// write
testing.expectSameRawFrame(frame, raw_frame.header, exp);
}
|
src/frames/execute.zig
|
const std = @import("std");
const builtin = @import("builtin");
const CallingConvention = @import("std").builtin.CallingConvention;
pub const is_nvptx = builtin.cpu.arch == .nvptx64;
pub const Kernel = if (is_nvptx) CallingConvention.PtxKernel else CallingConvention.Unspecified;
pub fn threadIdX() usize {
if (!is_nvptx) return 0;
var tid = asm volatile ("mov.u32 \t$0, %tid.x;"
: [ret] "=r" (-> u32),
);
return @as(usize, tid);
}
pub fn blockDimX() usize {
if (!is_nvptx) return 0;
var ntid = asm volatile ("mov.u32 \t$0, %ntid.x;"
: [ret] "=r" (-> u32),
);
return @as(usize, ntid);
}
pub fn blockIdX() usize {
if (!is_nvptx) return 0;
var ctaid = asm volatile ("mov.u32 \t$0, %ctaid.x;"
: [ret] "=r" (-> u32),
);
return @as(usize, ctaid);
}
pub fn gridDimX() usize {
if (!is_nvptx) return 0;
var nctaid = asm volatile ("mov.u32 \t$0, %nctaid.x;"
: [ret] "=r" (-> u32),
);
return @as(usize, nctaid);
}
pub fn getIdX() usize {
return threadIdX() + blockDimX() * blockIdX();
}
pub fn threadIdY() usize {
if (!is_nvptx) return 0;
var tid = asm volatile ("mov.u32 \t$0, %tid.y;"
: [ret] "=r" (-> u32),
);
return @as(usize, tid);
}
pub fn blockDimY() usize {
if (!is_nvptx) return 0;
var ntid = asm volatile ("mov.u32 \t$0, %ntid.y;"
: [ret] "=r" (-> u32),
);
return @as(usize, ntid);
}
pub fn blockIdY() usize {
if (!is_nvptx) return 0;
var ctaid = asm volatile ("mov.u32 \t$0, %ctaid.y;"
: [ret] "=r" (-> u32),
);
return @as(usize, ctaid);
}
pub fn syncThreads() void {
if (!is_nvptx) return;
asm volatile ("bar.sync \t0;");
}
pub fn atomicAdd(x: *u32, a: u32) void {
_ = @atomicRmw(u32, x, .Add, a, .SeqCst);
}
pub fn lastTid(n: usize) usize {
var block_dim = blockDimX();
return if (blockIdX() == gridDimX() - 1) (n - 1) % block_dim else block_dim - 1;
}
pub const Operator = enum { add, mul, min, max };
/// Exclusive scan using Blelloch algorithm
/// Returns the total value which won't be part of the array
// TODO: use generics once it works in Stage2
pub fn exclusiveScan(
comptime op: Operator,
data: anytype,
tid: usize,
last_tid: usize,
) u32 {
var step: u32 = 1;
while (step <= last_tid) : (step *= 2) {
if (tid >= step and (last_tid - tid) % (step * 2) == 0) {
var right = data[tid];
var left = data[tid - step];
data[tid] = switch (op) {
.add => right + left,
.mul => right * left,
.min => if (left < right) left else right,
.max => if (left > right) left else right,
};
}
syncThreads();
}
var total: u32 = 0;
if (tid == last_tid) {
total = data[tid];
data[tid] = 0;
}
syncThreads();
step /= 2;
while (step > 0) : (step /= 2) {
if (tid >= step and (last_tid - tid) % (step * 2) == 0) {
var right = data[tid];
var left = data[tid - step];
data[tid] = switch (op) {
.add => right + left,
.mul => right * left,
.min => if (left < right) left else right,
.max => if (left > right) left else right,
};
data[tid - step] = right;
}
syncThreads();
}
return total;
}
|
CS344/src/kernel_utils.zig
|
const std = @import("std");
const pike = @import("pike.zig");
const posix = @import("os/posix.zig");
const os = std.os;
const net = std.net;
const mem = std.mem;
const time = std.time;
pub inline fn init() !void {}
pub inline fn deinit() void {}
pub const Handle = struct {
inner: os.fd_t,
wake_fn: fn (self: *Handle, batch: *pike.Batch, opts: pike.WakeOptions) void,
pub inline fn wake(self: *Handle, batch: *pike.Batch, opts: pike.WakeOptions) void {
self.wake_fn(self, batch, opts);
}
};
pub const Notifier = struct {
const Self = @This();
handle: os.fd_t,
pub fn init() !Self {
const handle = try os.kqueue();
errdefer os.close(handle);
return Self{ .handle = handle };
}
pub fn deinit(self: *const Self) void {
os.close(self.handle);
}
pub fn register(self: *const Self, handle: *const Handle, comptime opts: pike.PollOptions) !void {
if (handle.inner == -1) return;
var changelist = [_]os.Kevent{
.{
.ident = undefined,
.filter = undefined,
.flags = os.EV_ADD | os.EV_CLEAR,
.fflags = 0,
.data = 0,
.udata = undefined,
},
} ** 2;
comptime var changelist_len = 0;
comptime {
if (opts.read) {
changelist[changelist_len].filter = os.EVFILT_READ;
changelist_len += 1;
}
if (opts.write) {
changelist[changelist_len].filter = os.EVFILT_WRITE;
changelist_len += 1;
}
}
for (changelist[0..changelist_len]) |*event| {
event.ident = @intCast(usize, handle.inner);
event.udata = @ptrToInt(handle);
}
_ = try os.kevent(self.handle, changelist[0..changelist_len], &[0]os.Kevent{}, null);
}
pub fn poll(self: *const Self, timeout: i32) !void {
var events: [128]os.Kevent = undefined;
var batch: pike.Batch = .{};
defer pike.dispatch(batch, .{});
const timeout_spec = os.timespec{
.tv_sec = @divTrunc(timeout, time.ms_per_s),
.tv_nsec = @rem(timeout, time.ms_per_s) * time.ns_per_ms,
};
const num_events = try os.kevent(self.handle, &[0]os.Kevent{}, events[0..], &timeout_spec);
for (events[0..num_events]) |e| {
const handle = @intToPtr(*Handle, e.udata);
const notify = e.filter == os.EVFILT_USER;
const shutdown = e.flags & (os.EV_ERROR | os.EV_EOF) != 0;
const read_ready = e.filter == os.EVFILT_READ;
const write_ready = e.filter == os.EVFILT_WRITE;
handle.wake(&batch, .{
.notify = notify,
.shutdown = shutdown,
.read_ready = read_ready,
.write_ready = write_ready,
});
}
}
};
|
notifier_kqueue.zig
|