code
stringlengths 38
801k
| repo_path
stringlengths 6
263
|
---|---|
const builtin = @import("builtin");
const std = @import("../../std.zig");
const testing = std.testing;
const math = std.math;
const cmath = math.complex;
const Complex = cmath.Complex;
const ldexp_cexp = @import("ldexp.zig").ldexp_cexp;
/// Returns the hyperbolic sine of z.
pub fn sinh(z: anytype) @TypeOf(z) {
const T = @TypeOf(z.re);
return switch (T) {
f32 => sinh32(z),
f64 => sinh64(z),
else => @compileError("tan not implemented for " ++ @typeName(z)),
};
}
fn sinh32(z: Complex(f32)) Complex(f32) {
const x = z.re;
const y = z.im;
const hx = @bitCast(u32, x);
const ix = hx & 0x7fffffff;
const hy = @bitCast(u32, y);
const iy = hy & 0x7fffffff;
if (ix < 0x7f800000 and iy < 0x7f800000) {
if (iy == 0) {
return Complex(f32).new(math.sinh(x), y);
}
// small x: normal case
if (ix < 0x41100000) {
return Complex(f32).new(math.sinh(x) * math.cos(y), math.cosh(x) * math.sin(y));
}
// |x|>= 9, so cosh(x) ~= exp(|x|)
if (ix < 0x42b17218) {
// x < 88.7: exp(|x|) won't overflow
const h = math.exp(math.fabs(x)) * 0.5;
return Complex(f32).new(math.copysign(f32, h, x) * math.cos(y), h * math.sin(y));
}
// x < 192.7: scale to avoid overflow
else if (ix < 0x4340b1e7) {
const v = Complex(f32).new(math.fabs(x), y);
const r = ldexp_cexp(v, -1);
return Complex(f32).new(r.re * math.copysign(f32, 1, x), r.im);
}
// x >= 192.7: result always overflows
else {
const h = 0x1p127 * x;
return Complex(f32).new(h * math.cos(y), h * h * math.sin(y));
}
}
if (ix == 0 and iy >= 0x7f800000) {
return Complex(f32).new(math.copysign(f32, 0, x * (y - y)), y - y);
}
if (iy == 0 and ix >= 0x7f800000) {
if (hx & 0x7fffff == 0) {
return Complex(f32).new(x, y);
}
return Complex(f32).new(x, math.copysign(f32, 0, y));
}
if (ix < 0x7f800000 and iy >= 0x7f800000) {
return Complex(f32).new(y - y, x * (y - y));
}
if (ix >= 0x7f800000 and (hx & 0x7fffff) == 0) {
if (iy >= 0x7f800000) {
return Complex(f32).new(x * x, x * (y - y));
}
return Complex(f32).new(x * math.cos(y), math.inf_f32 * math.sin(y));
}
return Complex(f32).new((x * x) * (y - y), (x + x) * (y - y));
}
fn sinh64(z: Complex(f64)) Complex(f64) {
const x = z.re;
const y = z.im;
const fx = @bitCast(u64, x);
const hx = @intCast(u32, fx >> 32);
const lx = @truncate(u32, fx);
const ix = hx & 0x7fffffff;
const fy = @bitCast(u64, y);
const hy = @intCast(u32, fy >> 32);
const ly = @truncate(u32, fy);
const iy = hy & 0x7fffffff;
if (ix < 0x7ff00000 and iy < 0x7ff00000) {
if (iy | ly == 0) {
return Complex(f64).new(math.sinh(x), y);
}
// small x: normal case
if (ix < 0x40360000) {
return Complex(f64).new(math.sinh(x) * math.cos(y), math.cosh(x) * math.sin(y));
}
// |x|>= 22, so cosh(x) ~= exp(|x|)
if (ix < 0x40862e42) {
// x < 710: exp(|x|) won't overflow
const h = math.exp(math.fabs(x)) * 0.5;
return Complex(f64).new(math.copysign(f64, h, x) * math.cos(y), h * math.sin(y));
}
// x < 1455: scale to avoid overflow
else if (ix < 0x4096bbaa) {
const v = Complex(f64).new(math.fabs(x), y);
const r = ldexp_cexp(v, -1);
return Complex(f64).new(r.re * math.copysign(f64, 1, x), r.im);
}
// x >= 1455: result always overflows
else {
const h = 0x1p1023 * x;
return Complex(f64).new(h * math.cos(y), h * h * math.sin(y));
}
}
if (ix | lx == 0 and iy >= 0x7ff00000) {
return Complex(f64).new(math.copysign(f64, 0, x * (y - y)), y - y);
}
if (iy | ly == 0 and ix >= 0x7ff00000) {
if ((hx & 0xfffff) | lx == 0) {
return Complex(f64).new(x, y);
}
return Complex(f64).new(x, math.copysign(f64, 0, y));
}
if (ix < 0x7ff00000 and iy >= 0x7ff00000) {
return Complex(f64).new(y - y, x * (y - y));
}
if (ix >= 0x7ff00000 and (hx & 0xfffff) | lx == 0) {
if (iy >= 0x7ff00000) {
return Complex(f64).new(x * x, x * (y - y));
}
return Complex(f64).new(x * math.cos(y), math.inf_f64 * math.sin(y));
}
return Complex(f64).new((x * x) * (y - y), (x + x) * (y - y));
}
const epsilon = 0.0001;
test "complex.csinh32" {
const a = Complex(f32).new(5, 3);
const c = sinh(a);
testing.expect(math.approxEqAbs(f32, c.re, -73.460617, epsilon));
testing.expect(math.approxEqAbs(f32, c.im, 10.472508, epsilon));
}
test "complex.csinh64" {
const a = Complex(f64).new(5, 3);
const c = sinh(a);
testing.expect(math.approxEqAbs(f64, c.re, -73.460617, epsilon));
testing.expect(math.approxEqAbs(f64, c.im, 10.472508, epsilon));
} | lib/std/math/complex/sinh.zig |
const std = @import("../std.zig");
const builtin = @import("builtin");
const assert = std.debug.assert;
const maxInt = std.math.maxInt;
const elf = std.elf;
const vdso = @import("linux/vdso.zig");
const dl = @import("../dynamic_library.zig");
const native_arch = builtin.cpu.arch;
const native_endian = native_arch.endian();
const is_mips = native_arch.isMIPS();
const is_ppc = native_arch.isPPC();
const is_ppc64 = native_arch.isPPC64();
const is_sparc = native_arch.isSPARC();
const iovec = std.os.iovec;
const iovec_const = std.os.iovec_const;
test {
if (builtin.os.tag == .linux) {
_ = @import("linux/test.zig");
}
}
const syscall_bits = switch (native_arch) {
.thumb => @import("linux/thumb.zig"),
else => arch_bits,
};
const arch_bits = switch (native_arch) {
.i386 => @import("linux/i386.zig"),
.x86_64 => @import("linux/x86_64.zig"),
.aarch64 => @import("linux/arm64.zig"),
.arm, .thumb => @import("linux/arm-eabi.zig"),
.riscv64 => @import("linux/riscv64.zig"),
.sparcv9 => @import("linux/sparc64.zig"),
.mips, .mipsel => @import("linux/mips.zig"),
.powerpc => @import("linux/powerpc.zig"),
.powerpc64, .powerpc64le => @import("linux/powerpc64.zig"),
else => struct {},
};
pub const syscall0 = syscall_bits.syscall0;
pub const syscall1 = syscall_bits.syscall1;
pub const syscall2 = syscall_bits.syscall2;
pub const syscall3 = syscall_bits.syscall3;
pub const syscall4 = syscall_bits.syscall4;
pub const syscall5 = syscall_bits.syscall5;
pub const syscall6 = syscall_bits.syscall6;
pub const syscall7 = syscall_bits.syscall7;
pub const restore = syscall_bits.restore;
pub const restore_rt = syscall_bits.restore_rt;
pub const socketcall = syscall_bits.socketcall;
pub const syscall_pipe = syscall_bits.syscall_pipe;
pub const syscall_fork = syscall_bits.syscall_fork;
pub const ARCH = arch_bits.ARCH;
pub const Elf_Symndx = arch_bits.Elf_Symndx;
pub const F = arch_bits.F;
pub const Flock = arch_bits.Flock;
pub const HWCAP = arch_bits.HWCAP;
pub const LOCK = arch_bits.LOCK;
pub const MMAP2_UNIT = arch_bits.MMAP2_UNIT;
pub const REG = arch_bits.REG;
pub const SC = arch_bits.SC;
pub const SYS = arch_bits.SYS;
pub const Stat = arch_bits.Stat;
pub const VDSO = arch_bits.VDSO;
pub const blkcnt_t = arch_bits.blkcnt_t;
pub const blksize_t = arch_bits.blksize_t;
pub const clone = arch_bits.clone;
pub const dev_t = arch_bits.dev_t;
pub const ino_t = arch_bits.ino_t;
pub const mcontext_t = arch_bits.mcontext_t;
pub const mode_t = arch_bits.mode_t;
pub const msghdr = arch_bits.msghdr;
pub const msghdr_const = arch_bits.msghdr_const;
pub const nlink_t = arch_bits.nlink_t;
pub const off_t = arch_bits.off_t;
pub const time_t = arch_bits.time_t;
pub const timeval = arch_bits.timeval;
pub const timezone = arch_bits.timezone;
pub const ucontext_t = arch_bits.ucontext_t;
pub const user_desc = arch_bits.user_desc;
pub const tls = @import("linux/tls.zig");
pub const pie = @import("linux/start_pie.zig");
pub const BPF = @import("linux/bpf.zig");
pub const IOCTL = @import("linux/ioctl.zig");
pub const MAP = struct {
pub usingnamespace arch_bits.MAP;
/// Share changes
pub const SHARED = 0x01;
/// Changes are private
pub const PRIVATE = 0x02;
/// share + validate extension flags
pub const SHARED_VALIDATE = 0x03;
/// Mask for type of mapping
pub const TYPE = 0x0f;
/// Interpret addr exactly
pub const FIXED = 0x10;
/// don't use a file
pub const ANONYMOUS = if (is_mips) 0x800 else 0x20;
// MAP_ 0x0100 - 0x4000 flags are per architecture
/// populate (prefault) pagetables
pub const POPULATE = if (is_mips) 0x10000 else 0x8000;
/// do not block on IO
pub const NONBLOCK = if (is_mips) 0x20000 else 0x10000;
/// give out an address that is best suited for process/thread stacks
pub const STACK = if (is_mips) 0x40000 else 0x20000;
/// create a huge page mapping
pub const HUGETLB = if (is_mips) 0x80000 else 0x40000;
/// perform synchronous page faults for the mapping
pub const SYNC = 0x80000;
/// MAP_FIXED which doesn't unmap underlying mapping
pub const FIXED_NOREPLACE = 0x100000;
/// For anonymous mmap, memory could be uninitialized
pub const UNINITIALIZED = 0x4000000;
};
pub const O = struct {
pub usingnamespace arch_bits.O;
pub const RDONLY = 0o0;
pub const WRONLY = 0o1;
pub const RDWR = 0o2;
};
pub usingnamespace @import("linux/io_uring.zig");
/// Set by startup code, used by `getauxval`.
pub var elf_aux_maybe: ?[*]std.elf.Auxv = null;
/// See `std.elf` for the constants.
pub fn getauxval(index: usize) usize {
const auxv = elf_aux_maybe orelse return 0;
var i: usize = 0;
while (auxv[i].a_type != std.elf.AT_NULL) : (i += 1) {
if (auxv[i].a_type == index)
return auxv[i].a_un.a_val;
}
return 0;
}
// Some architectures (and some syscalls) require 64bit parameters to be passed
// in a even-aligned register pair.
const require_aligned_register_pair =
builtin.cpu.arch.isPPC() or
builtin.cpu.arch.isMIPS() or
builtin.cpu.arch.isARM() or
builtin.cpu.arch.isThumb();
// Split a 64bit value into a {LSB,MSB} pair.
// The LE/BE variants specify the endianness to assume.
fn splitValueLE64(val: i64) [2]u32 {
const u = @bitCast(u64, val);
return [2]u32{
@truncate(u32, u),
@truncate(u32, u >> 32),
};
}
fn splitValueBE64(val: i64) [2]u32 {
const u = @bitCast(u64, val);
return [2]u32{
@truncate(u32, u >> 32),
@truncate(u32, u),
};
}
fn splitValue64(val: i64) [2]u32 {
const u = @bitCast(u64, val);
switch (native_endian) {
.Little => return [2]u32{
@truncate(u32, u),
@truncate(u32, u >> 32),
},
.Big => return [2]u32{
@truncate(u32, u >> 32),
@truncate(u32, u),
},
}
}
/// Get the errno from a syscall return value, or 0 for no error.
pub fn getErrno(r: usize) E {
const signed_r = @bitCast(isize, r);
const int = if (signed_r > -4096 and signed_r < 0) -signed_r else 0;
return @intToEnum(E, int);
}
pub fn dup(old: i32) usize {
return syscall1(.dup, @bitCast(usize, @as(isize, old)));
}
pub fn dup2(old: i32, new: i32) usize {
if (@hasField(SYS, "dup2")) {
return syscall2(.dup2, @bitCast(usize, @as(isize, old)), @bitCast(usize, @as(isize, new)));
} else {
if (old == new) {
if (std.debug.runtime_safety) {
const rc = syscall2(.fcntl, @bitCast(usize, @as(isize, old)), F.GETFD);
if (@bitCast(isize, rc) < 0) return rc;
}
return @intCast(usize, old);
} else {
return syscall3(.dup3, @bitCast(usize, @as(isize, old)), @bitCast(usize, @as(isize, new)), 0);
}
}
}
pub fn dup3(old: i32, new: i32, flags: u32) usize {
return syscall3(.dup3, @bitCast(usize, @as(isize, old)), @bitCast(usize, @as(isize, new)), flags);
}
pub fn chdir(path: [*:0]const u8) usize {
return syscall1(.chdir, @ptrToInt(path));
}
pub fn fchdir(fd: fd_t) usize {
return syscall1(.fchdir, @bitCast(usize, @as(isize, fd)));
}
pub fn chroot(path: [*:0]const u8) usize {
return syscall1(.chroot, @ptrToInt(path));
}
pub fn execve(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8, envp: [*:null]const ?[*:0]const u8) usize {
return syscall3(.execve, @ptrToInt(path), @ptrToInt(argv), @ptrToInt(envp));
}
pub fn fork() usize {
if (comptime native_arch.isSPARC()) {
return syscall_fork();
} else if (@hasField(SYS, "fork")) {
return syscall0(.fork);
} else {
return syscall2(.clone, SIG.CHLD, 0);
}
}
/// This must be inline, and inline call the syscall function, because if the
/// child does a return it will clobber the parent's stack.
/// It is advised to avoid this function and use clone instead, because
/// the compiler is not aware of how vfork affects control flow and you may
/// see different results in optimized builds.
pub inline fn vfork() usize {
return @call(.{ .modifier = .always_inline }, syscall0, .{.vfork});
}
pub fn futimens(fd: i32, times: *const [2]timespec) usize {
return utimensat(fd, null, times, 0);
}
pub fn utimensat(dirfd: i32, path: ?[*:0]const u8, times: *const [2]timespec, flags: u32) usize {
return syscall4(.utimensat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(times), flags);
}
pub fn fallocate(fd: i32, mode: i32, offset: i64, length: i64) usize {
if (usize_bits < 64) {
const offset_halves = splitValue64(offset);
const length_halves = splitValue64(length);
return syscall6(
.fallocate,
@bitCast(usize, @as(isize, fd)),
@bitCast(usize, @as(isize, mode)),
offset_halves[0],
offset_halves[1],
length_halves[0],
length_halves[1],
);
} else {
return syscall4(
.fallocate,
@bitCast(usize, @as(isize, fd)),
@bitCast(usize, @as(isize, mode)),
@bitCast(u64, offset),
@bitCast(u64, length),
);
}
}
pub fn futex_wait(uaddr: *const i32, futex_op: u32, val: i32, timeout: ?*const timespec) usize {
return syscall4(.futex, @ptrToInt(uaddr), futex_op, @bitCast(u32, val), @ptrToInt(timeout));
}
pub fn futex_wake(uaddr: *const i32, futex_op: u32, val: i32) usize {
return syscall3(.futex, @ptrToInt(uaddr), futex_op, @bitCast(u32, val));
}
pub fn getcwd(buf: [*]u8, size: usize) usize {
return syscall2(.getcwd, @ptrToInt(buf), size);
}
pub fn getdents(fd: i32, dirp: [*]u8, len: usize) usize {
return syscall3(
.getdents,
@bitCast(usize, @as(isize, fd)),
@ptrToInt(dirp),
std.math.min(len, maxInt(c_int)),
);
}
pub fn getdents64(fd: i32, dirp: [*]u8, len: usize) usize {
return syscall3(
.getdents64,
@bitCast(usize, @as(isize, fd)),
@ptrToInt(dirp),
std.math.min(len, maxInt(c_int)),
);
}
pub fn inotify_init1(flags: u32) usize {
return syscall1(.inotify_init1, flags);
}
pub fn inotify_add_watch(fd: i32, pathname: [*:0]const u8, mask: u32) usize {
return syscall3(.inotify_add_watch, @bitCast(usize, @as(isize, fd)), @ptrToInt(pathname), mask);
}
pub fn inotify_rm_watch(fd: i32, wd: i32) usize {
return syscall2(.inotify_rm_watch, @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, wd)));
}
pub fn readlink(noalias path: [*:0]const u8, noalias buf_ptr: [*]u8, buf_len: usize) usize {
if (@hasField(SYS, "readlink")) {
return syscall3(.readlink, @ptrToInt(path), @ptrToInt(buf_ptr), buf_len);
} else {
return syscall4(.readlinkat, @bitCast(usize, @as(isize, AT.FDCWD)), @ptrToInt(path), @ptrToInt(buf_ptr), buf_len);
}
}
pub fn readlinkat(dirfd: i32, noalias path: [*:0]const u8, noalias buf_ptr: [*]u8, buf_len: usize) usize {
return syscall4(.readlinkat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(buf_ptr), buf_len);
}
pub fn mkdir(path: [*:0]const u8, mode: u32) usize {
if (@hasField(SYS, "mkdir")) {
return syscall2(.mkdir, @ptrToInt(path), mode);
} else {
return syscall3(.mkdirat, @bitCast(usize, @as(isize, AT.FDCWD)), @ptrToInt(path), mode);
}
}
pub fn mkdirat(dirfd: i32, path: [*:0]const u8, mode: u32) usize {
return syscall3(.mkdirat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), mode);
}
pub fn mknod(path: [*:0]const u8, mode: u32, dev: u32) usize {
if (@hasField(SYS, "mknod")) {
return syscall3(.mknod, @ptrToInt(path), mode, dev);
} else {
return mknodat(AT.FDCWD, path, mode, dev);
}
}
pub fn mknodat(dirfd: i32, path: [*:0]const u8, mode: u32, dev: u32) usize {
return syscall4(.mknodat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), mode, dev);
}
pub fn mount(special: [*:0]const u8, dir: [*:0]const u8, fstype: [*:0]const u8, flags: u32, data: usize) usize {
return syscall5(.mount, @ptrToInt(special), @ptrToInt(dir), @ptrToInt(fstype), flags, data);
}
pub fn umount(special: [*:0]const u8) usize {
return syscall2(.umount2, @ptrToInt(special), 0);
}
pub fn umount2(special: [*:0]const u8, flags: u32) usize {
return syscall2(.umount2, @ptrToInt(special), flags);
}
pub fn mmap(address: ?[*]u8, length: usize, prot: usize, flags: u32, fd: i32, offset: i64) usize {
if (@hasField(SYS, "mmap2")) {
// Make sure the offset is also specified in multiples of page size
if ((offset & (MMAP2_UNIT - 1)) != 0)
return @bitCast(usize, -@as(isize, @enumToInt(E.INVAL)));
return syscall6(
.mmap2,
@ptrToInt(address),
length,
prot,
flags,
@bitCast(usize, @as(isize, fd)),
@truncate(usize, @bitCast(u64, offset) / MMAP2_UNIT),
);
} else {
return syscall6(
.mmap,
@ptrToInt(address),
length,
prot,
flags,
@bitCast(usize, @as(isize, fd)),
@bitCast(u64, offset),
);
}
}
pub fn mprotect(address: [*]const u8, length: usize, protection: usize) usize {
return syscall3(.mprotect, @ptrToInt(address), length, protection);
}
pub const MSF = struct {
pub const ASYNC = 1;
pub const INVALIDATE = 2;
pub const SYNC = 4;
};
pub fn msync(address: [*]const u8, length: usize, flags: i32) usize {
return syscall3(.msync, @ptrToInt(address), length, @bitCast(u32, flags));
}
pub fn munmap(address: [*]const u8, length: usize) usize {
return syscall2(.munmap, @ptrToInt(address), length);
}
pub fn poll(fds: [*]pollfd, n: nfds_t, timeout: i32) usize {
if (@hasField(SYS, "poll")) {
return syscall3(.poll, @ptrToInt(fds), n, @bitCast(u32, timeout));
} else {
return syscall5(
.ppoll,
@ptrToInt(fds),
n,
@ptrToInt(if (timeout >= 0)
×pec{
.tv_sec = @divTrunc(timeout, 1000),
.tv_nsec = @rem(timeout, 1000) * 1000000,
}
else
null),
0,
NSIG / 8,
);
}
}
pub fn ppoll(fds: [*]pollfd, n: nfds_t, timeout: ?*timespec, sigmask: ?*const sigset_t) usize {
return syscall5(.ppoll, @ptrToInt(fds), n, @ptrToInt(timeout), @ptrToInt(sigmask), NSIG / 8);
}
pub fn read(fd: i32, buf: [*]u8, count: usize) usize {
return syscall3(.read, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count);
}
pub fn preadv(fd: i32, iov: [*]const iovec, count: usize, offset: i64) usize {
const offset_u = @bitCast(u64, offset);
return syscall5(
.preadv,
@bitCast(usize, @as(isize, fd)),
@ptrToInt(iov),
count,
// Kernel expects the offset is splitted into largest natural word-size.
// See following link for detail:
// https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=601cc11d054ae4b5e9b5babec3d8e4667a2cb9b5
@truncate(usize, offset_u),
if (usize_bits < 64) @truncate(usize, offset_u >> 32) else 0,
);
}
pub fn preadv2(fd: i32, iov: [*]const iovec, count: usize, offset: i64, flags: kernel_rwf) usize {
const offset_u = @bitCast(u64, offset);
return syscall6(
.preadv2,
@bitCast(usize, @as(isize, fd)),
@ptrToInt(iov),
count,
// See comments in preadv
@truncate(usize, offset_u),
if (usize_bits < 64) @truncate(usize, offset_u >> 32) else 0,
flags,
);
}
pub fn readv(fd: i32, iov: [*]const iovec, count: usize) usize {
return syscall3(.readv, @bitCast(usize, @as(isize, fd)), @ptrToInt(iov), count);
}
pub fn writev(fd: i32, iov: [*]const iovec_const, count: usize) usize {
return syscall3(.writev, @bitCast(usize, @as(isize, fd)), @ptrToInt(iov), count);
}
pub fn pwritev(fd: i32, iov: [*]const iovec_const, count: usize, offset: i64) usize {
const offset_u = @bitCast(u64, offset);
return syscall5(
.pwritev,
@bitCast(usize, @as(isize, fd)),
@ptrToInt(iov),
count,
// See comments in preadv
@truncate(usize, offset_u),
if (usize_bits < 64) @truncate(usize, offset_u >> 32) else 0,
);
}
pub fn pwritev2(fd: i32, iov: [*]const iovec_const, count: usize, offset: i64, flags: kernel_rwf) usize {
const offset_u = @bitCast(u64, offset);
return syscall6(
.pwritev2,
@bitCast(usize, @as(isize, fd)),
@ptrToInt(iov),
count,
// See comments in preadv
@truncate(usize, offset_u),
if (usize_bits < 64) @truncate(usize, offset_u >> 32) else 0,
flags,
);
}
pub fn rmdir(path: [*:0]const u8) usize {
if (@hasField(SYS, "rmdir")) {
return syscall1(.rmdir, @ptrToInt(path));
} else {
return syscall3(.unlinkat, @bitCast(usize, @as(isize, AT.FDCWD)), @ptrToInt(path), AT.REMOVEDIR);
}
}
pub fn symlink(existing: [*:0]const u8, new: [*:0]const u8) usize {
if (@hasField(SYS, "symlink")) {
return syscall2(.symlink, @ptrToInt(existing), @ptrToInt(new));
} else {
return syscall3(.symlinkat, @ptrToInt(existing), @bitCast(usize, @as(isize, AT.FDCWD)), @ptrToInt(new));
}
}
pub fn symlinkat(existing: [*:0]const u8, newfd: i32, newpath: [*:0]const u8) usize {
return syscall3(.symlinkat, @ptrToInt(existing), @bitCast(usize, @as(isize, newfd)), @ptrToInt(newpath));
}
pub fn pread(fd: i32, buf: [*]u8, count: usize, offset: i64) usize {
if (@hasField(SYS, "pread64") and usize_bits < 64) {
const offset_halves = splitValue64(offset);
if (require_aligned_register_pair) {
return syscall6(
.pread64,
@bitCast(usize, @as(isize, fd)),
@ptrToInt(buf),
count,
0,
offset_halves[0],
offset_halves[1],
);
} else {
return syscall5(
.pread64,
@bitCast(usize, @as(isize, fd)),
@ptrToInt(buf),
count,
offset_halves[0],
offset_halves[1],
);
}
} else {
// Some architectures (eg. 64bit SPARC) pread is called pread64.
const syscall_number = if (!@hasField(SYS, "pread") and @hasField(SYS, "pread64"))
.pread64
else
.pread;
return syscall4(
syscall_number,
@bitCast(usize, @as(isize, fd)),
@ptrToInt(buf),
count,
@bitCast(u64, offset),
);
}
}
pub fn access(path: [*:0]const u8, mode: u32) usize {
if (@hasField(SYS, "access")) {
return syscall2(.access, @ptrToInt(path), mode);
} else {
return syscall4(.faccessat, @bitCast(usize, @as(isize, AT.FDCWD)), @ptrToInt(path), mode, 0);
}
}
pub fn faccessat(dirfd: i32, path: [*:0]const u8, mode: u32, flags: u32) usize {
return syscall4(.faccessat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), mode, flags);
}
pub fn pipe(fd: *[2]i32) usize {
if (comptime (native_arch.isMIPS() or native_arch.isSPARC())) {
return syscall_pipe(fd);
} else if (@hasField(SYS, "pipe")) {
return syscall1(.pipe, @ptrToInt(fd));
} else {
return syscall2(.pipe2, @ptrToInt(fd), 0);
}
}
pub fn pipe2(fd: *[2]i32, flags: u32) usize {
return syscall2(.pipe2, @ptrToInt(fd), flags);
}
pub fn write(fd: i32, buf: [*]const u8, count: usize) usize {
return syscall3(.write, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count);
}
pub fn ftruncate(fd: i32, length: i64) usize {
if (@hasField(SYS, "ftruncate64") and usize_bits < 64) {
const length_halves = splitValue64(length);
if (require_aligned_register_pair) {
return syscall4(
.ftruncate64,
@bitCast(usize, @as(isize, fd)),
0,
length_halves[0],
length_halves[1],
);
} else {
return syscall3(
.ftruncate64,
@bitCast(usize, @as(isize, fd)),
length_halves[0],
length_halves[1],
);
}
} else {
return syscall2(
.ftruncate,
@bitCast(usize, @as(isize, fd)),
@bitCast(usize, length),
);
}
}
pub fn pwrite(fd: i32, buf: [*]const u8, count: usize, offset: i64) usize {
if (@hasField(SYS, "pwrite64") and usize_bits < 64) {
const offset_halves = splitValue64(offset);
if (require_aligned_register_pair) {
return syscall6(
.pwrite64,
@bitCast(usize, @as(isize, fd)),
@ptrToInt(buf),
count,
0,
offset_halves[0],
offset_halves[1],
);
} else {
return syscall5(
.pwrite64,
@bitCast(usize, @as(isize, fd)),
@ptrToInt(buf),
count,
offset_halves[0],
offset_halves[1],
);
}
} else {
// Some architectures (eg. 64bit SPARC) pwrite is called pwrite64.
const syscall_number = if (!@hasField(SYS, "pwrite") and @hasField(SYS, "pwrite64"))
.pwrite64
else
.pwrite;
return syscall4(
syscall_number,
@bitCast(usize, @as(isize, fd)),
@ptrToInt(buf),
count,
@bitCast(u64, offset),
);
}
}
pub fn rename(old: [*:0]const u8, new: [*:0]const u8) usize {
if (@hasField(SYS, "rename")) {
return syscall2(.rename, @ptrToInt(old), @ptrToInt(new));
} else if (@hasField(SYS, "renameat")) {
return syscall4(.renameat, @bitCast(usize, @as(isize, AT.FDCWD)), @ptrToInt(old), @bitCast(usize, @as(isize, AT.FDCWD)), @ptrToInt(new));
} else {
return syscall5(.renameat2, @bitCast(usize, @as(isize, AT.FDCWD)), @ptrToInt(old), @bitCast(usize, @as(isize, AT.FDCWD)), @ptrToInt(new), 0);
}
}
pub fn renameat(oldfd: i32, oldpath: [*]const u8, newfd: i32, newpath: [*]const u8) usize {
if (@hasField(SYS, "renameat")) {
return syscall4(
.renameat,
@bitCast(usize, @as(isize, oldfd)),
@ptrToInt(oldpath),
@bitCast(usize, @as(isize, newfd)),
@ptrToInt(newpath),
);
} else {
return syscall5(
.renameat2,
@bitCast(usize, @as(isize, oldfd)),
@ptrToInt(oldpath),
@bitCast(usize, @as(isize, newfd)),
@ptrToInt(newpath),
0,
);
}
}
pub fn renameat2(oldfd: i32, oldpath: [*:0]const u8, newfd: i32, newpath: [*:0]const u8, flags: u32) usize {
return syscall5(
.renameat2,
@bitCast(usize, @as(isize, oldfd)),
@ptrToInt(oldpath),
@bitCast(usize, @as(isize, newfd)),
@ptrToInt(newpath),
flags,
);
}
pub fn open(path: [*:0]const u8, flags: u32, perm: mode_t) usize {
if (@hasField(SYS, "open")) {
return syscall3(.open, @ptrToInt(path), flags, perm);
} else {
return syscall4(
.openat,
@bitCast(usize, @as(isize, AT.FDCWD)),
@ptrToInt(path),
flags,
perm,
);
}
}
pub fn create(path: [*:0]const u8, perm: mode_t) usize {
return syscall2(.creat, @ptrToInt(path), perm);
}
pub fn openat(dirfd: i32, path: [*:0]const u8, flags: u32, mode: mode_t) usize {
// dirfd could be negative, for example AT.FDCWD is -100
return syscall4(.openat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), flags, mode);
}
/// See also `clone` (from the arch-specific include)
pub fn clone5(flags: usize, child_stack_ptr: usize, parent_tid: *i32, child_tid: *i32, newtls: usize) usize {
return syscall5(.clone, flags, child_stack_ptr, @ptrToInt(parent_tid), @ptrToInt(child_tid), newtls);
}
/// See also `clone` (from the arch-specific include)
pub fn clone2(flags: u32, child_stack_ptr: usize) usize {
return syscall2(.clone, flags, child_stack_ptr);
}
pub fn close(fd: i32) usize {
return syscall1(.close, @bitCast(usize, @as(isize, fd)));
}
pub fn fchmod(fd: i32, mode: mode_t) usize {
return syscall2(.fchmod, @bitCast(usize, @as(isize, fd)), mode);
}
pub fn fchown(fd: i32, owner: uid_t, group: gid_t) usize {
if (@hasField(SYS, "fchown32")) {
return syscall3(.fchown32, @bitCast(usize, @as(isize, fd)), owner, group);
} else {
return syscall3(.fchown, @bitCast(usize, @as(isize, fd)), owner, group);
}
}
/// Can only be called on 32 bit systems. For 64 bit see `lseek`.
pub fn llseek(fd: i32, offset: u64, result: ?*u64, whence: usize) usize {
// NOTE: The offset parameter splitting is independent from the target
// endianness.
return syscall5(
._llseek,
@bitCast(usize, @as(isize, fd)),
@truncate(usize, offset >> 32),
@truncate(usize, offset),
@ptrToInt(result),
whence,
);
}
/// Can only be called on 64 bit systems. For 32 bit see `llseek`.
pub fn lseek(fd: i32, offset: i64, whence: usize) usize {
return syscall3(.lseek, @bitCast(usize, @as(isize, fd)), @bitCast(usize, offset), whence);
}
pub fn exit(status: i32) noreturn {
_ = syscall1(.exit, @bitCast(usize, @as(isize, status)));
unreachable;
}
pub fn exit_group(status: i32) noreturn {
_ = syscall1(.exit_group, @bitCast(usize, @as(isize, status)));
unreachable;
}
pub fn getrandom(buf: [*]u8, count: usize, flags: u32) usize {
return syscall3(.getrandom, @ptrToInt(buf), count, flags);
}
pub fn kill(pid: pid_t, sig: i32) usize {
return syscall2(.kill, @bitCast(usize, @as(isize, pid)), @bitCast(usize, @as(isize, sig)));
}
pub fn tkill(tid: pid_t, sig: i32) usize {
return syscall2(.tkill, @bitCast(usize, @as(isize, tid)), @bitCast(usize, @as(isize, sig)));
}
pub fn tgkill(tgid: pid_t, tid: pid_t, sig: i32) usize {
return syscall3(.tgkill, @bitCast(usize, @as(isize, tgid)), @bitCast(usize, @as(isize, tid)), @bitCast(usize, @as(isize, sig)));
}
pub fn link(oldpath: [*:0]const u8, newpath: [*:0]const u8, flags: i32) usize {
if (@hasField(SYS, "link")) {
return syscall3(
.link,
@ptrToInt(oldpath),
@ptrToInt(newpath),
@bitCast(usize, @as(isize, flags)),
);
} else {
return syscall5(
.linkat,
@bitCast(usize, @as(isize, AT.FDCWD)),
@ptrToInt(oldpath),
@bitCast(usize, @as(isize, AT.FDCWD)),
@ptrToInt(newpath),
@bitCast(usize, @as(isize, flags)),
);
}
}
pub fn linkat(oldfd: fd_t, oldpath: [*:0]const u8, newfd: fd_t, newpath: [*:0]const u8, flags: i32) usize {
return syscall5(
.linkat,
@bitCast(usize, @as(isize, oldfd)),
@ptrToInt(oldpath),
@bitCast(usize, @as(isize, newfd)),
@ptrToInt(newpath),
@bitCast(usize, @as(isize, flags)),
);
}
pub fn unlink(path: [*:0]const u8) usize {
if (@hasField(SYS, "unlink")) {
return syscall1(.unlink, @ptrToInt(path));
} else {
return syscall3(.unlinkat, @bitCast(usize, @as(isize, AT.FDCWD)), @ptrToInt(path), 0);
}
}
pub fn unlinkat(dirfd: i32, path: [*:0]const u8, flags: u32) usize {
return syscall3(.unlinkat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), flags);
}
pub fn waitpid(pid: pid_t, status: *u32, flags: u32) usize {
return syscall4(.wait4, @bitCast(usize, @as(isize, pid)), @ptrToInt(status), flags, 0);
}
pub fn waitid(id_type: P, id: i32, infop: *siginfo_t, flags: u32) usize {
return syscall5(.waitid, @enumToInt(id_type), @bitCast(usize, @as(isize, id)), @ptrToInt(infop), flags, 0);
}
pub fn fcntl(fd: fd_t, cmd: i32, arg: usize) usize {
return syscall3(.fcntl, @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, cmd)), arg);
}
pub fn flock(fd: fd_t, operation: i32) usize {
return syscall2(.flock, @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, operation)));
}
var vdso_clock_gettime = @ptrCast(?*const anyopaque, init_vdso_clock_gettime);
// We must follow the C calling convention when we call into the VDSO
const vdso_clock_gettime_ty = fn (i32, *timespec) callconv(.C) usize;
pub fn clock_gettime(clk_id: i32, tp: *timespec) usize {
if (@hasDecl(VDSO, "CGT_SYM")) {
const ptr = @atomicLoad(?*const anyopaque, &vdso_clock_gettime, .Unordered);
if (ptr) |fn_ptr| {
const f = @ptrCast(vdso_clock_gettime_ty, fn_ptr);
const rc = f(clk_id, tp);
switch (rc) {
0, @bitCast(usize, -@as(isize, @enumToInt(E.INVAL))) => return rc,
else => {},
}
}
}
return syscall2(.clock_gettime, @bitCast(usize, @as(isize, clk_id)), @ptrToInt(tp));
}
fn init_vdso_clock_gettime(clk: i32, ts: *timespec) callconv(.C) usize {
const ptr = @intToPtr(?*const anyopaque, vdso.lookup(VDSO.CGT_VER, VDSO.CGT_SYM));
// Note that we may not have a VDSO at all, update the stub address anyway
// so that clock_gettime will fall back on the good old (and slow) syscall
@atomicStore(?*const anyopaque, &vdso_clock_gettime, ptr, .Monotonic);
// Call into the VDSO if available
if (ptr) |fn_ptr| {
const f = @ptrCast(vdso_clock_gettime_ty, fn_ptr);
return f(clk, ts);
}
return @bitCast(usize, -@as(isize, @enumToInt(E.NOSYS)));
}
pub fn clock_getres(clk_id: i32, tp: *timespec) usize {
return syscall2(.clock_getres, @bitCast(usize, @as(isize, clk_id)), @ptrToInt(tp));
}
pub fn clock_settime(clk_id: i32, tp: *const timespec) usize {
return syscall2(.clock_settime, @bitCast(usize, @as(isize, clk_id)), @ptrToInt(tp));
}
pub fn gettimeofday(tv: *timeval, tz: *timezone) usize {
return syscall2(.gettimeofday, @ptrToInt(tv), @ptrToInt(tz));
}
pub fn settimeofday(tv: *const timeval, tz: *const timezone) usize {
return syscall2(.settimeofday, @ptrToInt(tv), @ptrToInt(tz));
}
pub fn nanosleep(req: *const timespec, rem: ?*timespec) usize {
return syscall2(.nanosleep, @ptrToInt(req), @ptrToInt(rem));
}
pub fn setuid(uid: uid_t) usize {
if (@hasField(SYS, "setuid32")) {
return syscall1(.setuid32, uid);
} else {
return syscall1(.setuid, uid);
}
}
pub fn setgid(gid: gid_t) usize {
if (@hasField(SYS, "setgid32")) {
return syscall1(.setgid32, gid);
} else {
return syscall1(.setgid, gid);
}
}
pub fn setreuid(ruid: uid_t, euid: uid_t) usize {
if (@hasField(SYS, "setreuid32")) {
return syscall2(.setreuid32, ruid, euid);
} else {
return syscall2(.setreuid, ruid, euid);
}
}
pub fn setregid(rgid: gid_t, egid: gid_t) usize {
if (@hasField(SYS, "setregid32")) {
return syscall2(.setregid32, rgid, egid);
} else {
return syscall2(.setregid, rgid, egid);
}
}
pub fn getuid() uid_t {
if (@hasField(SYS, "getuid32")) {
return @intCast(uid_t, syscall0(.getuid32));
} else {
return @intCast(uid_t, syscall0(.getuid));
}
}
pub fn getgid() gid_t {
if (@hasField(SYS, "getgid32")) {
return @intCast(gid_t, syscall0(.getgid32));
} else {
return @intCast(gid_t, syscall0(.getgid));
}
}
pub fn geteuid() uid_t {
if (@hasField(SYS, "geteuid32")) {
return @intCast(uid_t, syscall0(.geteuid32));
} else {
return @intCast(uid_t, syscall0(.geteuid));
}
}
pub fn getegid() gid_t {
if (@hasField(SYS, "getegid32")) {
return @intCast(gid_t, syscall0(.getegid32));
} else {
return @intCast(gid_t, syscall0(.getegid));
}
}
pub fn seteuid(euid: uid_t) usize {
// We use setresuid here instead of setreuid to ensure that the saved uid
// is not changed. This is what musl and recent glibc versions do as well.
//
// The setresuid(2) man page says that if -1 is passed the corresponding
// id will not be changed. Since uid_t is unsigned, this wraps around to the
// max value in C.
comptime assert(@typeInfo(uid_t) == .Int and @typeInfo(uid_t).Int.signedness == .unsigned);
return setresuid(std.math.maxInt(uid_t), euid, std.math.maxInt(uid_t));
}
pub fn setegid(egid: gid_t) usize {
// We use setresgid here instead of setregid to ensure that the saved uid
// is not changed. This is what musl and recent glibc versions do as well.
//
// The setresgid(2) man page says that if -1 is passed the corresponding
// id will not be changed. Since gid_t is unsigned, this wraps around to the
// max value in C.
comptime assert(@typeInfo(uid_t) == .Int and @typeInfo(uid_t).Int.signedness == .unsigned);
return setresgid(std.math.maxInt(gid_t), egid, std.math.maxInt(gid_t));
}
pub fn getresuid(ruid: *uid_t, euid: *uid_t, suid: *uid_t) usize {
if (@hasField(SYS, "getresuid32")) {
return syscall3(.getresuid32, @ptrToInt(ruid), @ptrToInt(euid), @ptrToInt(suid));
} else {
return syscall3(.getresuid, @ptrToInt(ruid), @ptrToInt(euid), @ptrToInt(suid));
}
}
pub fn getresgid(rgid: *gid_t, egid: *gid_t, sgid: *gid_t) usize {
if (@hasField(SYS, "getresgid32")) {
return syscall3(.getresgid32, @ptrToInt(rgid), @ptrToInt(egid), @ptrToInt(sgid));
} else {
return syscall3(.getresgid, @ptrToInt(rgid), @ptrToInt(egid), @ptrToInt(sgid));
}
}
pub fn setresuid(ruid: uid_t, euid: uid_t, suid: uid_t) usize {
if (@hasField(SYS, "setresuid32")) {
return syscall3(.setresuid32, ruid, euid, suid);
} else {
return syscall3(.setresuid, ruid, euid, suid);
}
}
pub fn setresgid(rgid: gid_t, egid: gid_t, sgid: gid_t) usize {
if (@hasField(SYS, "setresgid32")) {
return syscall3(.setresgid32, rgid, egid, sgid);
} else {
return syscall3(.setresgid, rgid, egid, sgid);
}
}
pub fn getgroups(size: usize, list: *gid_t) usize {
if (@hasField(SYS, "getgroups32")) {
return syscall2(.getgroups32, size, @ptrToInt(list));
} else {
return syscall2(.getgroups, size, @ptrToInt(list));
}
}
pub fn setgroups(size: usize, list: *const gid_t) usize {
if (@hasField(SYS, "setgroups32")) {
return syscall2(.setgroups32, size, @ptrToInt(list));
} else {
return syscall2(.setgroups, size, @ptrToInt(list));
}
}
pub fn getpid() pid_t {
return @bitCast(pid_t, @truncate(u32, syscall0(.getpid)));
}
pub fn gettid() pid_t {
return @bitCast(pid_t, @truncate(u32, syscall0(.gettid)));
}
pub fn sigprocmask(flags: u32, noalias set: ?*const sigset_t, noalias oldset: ?*sigset_t) usize {
return syscall4(.rt_sigprocmask, flags, @ptrToInt(set), @ptrToInt(oldset), NSIG / 8);
}
pub fn sigaction(sig: u6, noalias act: ?*const Sigaction, noalias oact: ?*Sigaction) usize {
assert(sig >= 1);
assert(sig != SIG.KILL);
assert(sig != SIG.STOP);
var ksa: k_sigaction = undefined;
var oldksa: k_sigaction = undefined;
const mask_size = @sizeOf(@TypeOf(ksa.mask));
if (act) |new| {
const restorer_fn = if ((new.flags & SA.SIGINFO) != 0) restore_rt else restore;
ksa = k_sigaction{
.handler = new.handler.handler,
.flags = new.flags | SA.RESTORER,
.mask = undefined,
.restorer = @ptrCast(fn () callconv(.C) void, restorer_fn),
};
@memcpy(@ptrCast([*]u8, &ksa.mask), @ptrCast([*]const u8, &new.mask), mask_size);
}
const ksa_arg = if (act != null) @ptrToInt(&ksa) else 0;
const oldksa_arg = if (oact != null) @ptrToInt(&oldksa) else 0;
const result = switch (native_arch) {
// The sparc version of rt_sigaction needs the restorer function to be passed as an argument too.
.sparc, .sparcv9 => syscall5(.rt_sigaction, sig, ksa_arg, oldksa_arg, @ptrToInt(ksa.restorer), mask_size),
else => syscall4(.rt_sigaction, sig, ksa_arg, oldksa_arg, mask_size),
};
if (getErrno(result) != .SUCCESS) return result;
if (oact) |old| {
old.handler.handler = oldksa.handler;
old.flags = @truncate(c_uint, oldksa.flags);
@memcpy(@ptrCast([*]u8, &old.mask), @ptrCast([*]const u8, &oldksa.mask), mask_size);
}
return 0;
}
const usize_bits = @typeInfo(usize).Int.bits;
pub fn sigaddset(set: *sigset_t, sig: u6) void {
const s = sig - 1;
// shift in musl: s&8*sizeof *set->__bits-1
const shift = @intCast(u5, s & (usize_bits - 1));
const val = @intCast(u32, 1) << shift;
(set.*)[@intCast(usize, s) / usize_bits] |= val;
}
pub fn sigismember(set: *const sigset_t, sig: u6) bool {
const s = sig - 1;
return ((set.*)[@intCast(usize, s) / usize_bits] & (@intCast(usize, 1) << (s & (usize_bits - 1)))) != 0;
}
pub fn getsockname(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) usize {
if (native_arch == .i386) {
return socketcall(SC.getsockname, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len) });
}
return syscall3(.getsockname, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len));
}
pub fn getpeername(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) usize {
if (native_arch == .i386) {
return socketcall(SC.getpeername, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len) });
}
return syscall3(.getpeername, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len));
}
pub fn socket(domain: u32, socket_type: u32, protocol: u32) usize {
if (native_arch == .i386) {
return socketcall(SC.socket, &[3]usize{ domain, socket_type, protocol });
}
return syscall3(.socket, domain, socket_type, protocol);
}
pub fn setsockopt(fd: i32, level: u32, optname: u32, optval: [*]const u8, optlen: socklen_t) usize {
if (native_arch == .i386) {
return socketcall(SC.setsockopt, &[5]usize{ @bitCast(usize, @as(isize, fd)), level, optname, @ptrToInt(optval), @intCast(usize, optlen) });
}
return syscall5(.setsockopt, @bitCast(usize, @as(isize, fd)), level, optname, @ptrToInt(optval), @intCast(usize, optlen));
}
pub fn getsockopt(fd: i32, level: u32, optname: u32, noalias optval: [*]u8, noalias optlen: *socklen_t) usize {
if (native_arch == .i386) {
return socketcall(SC.getsockopt, &[5]usize{ @bitCast(usize, @as(isize, fd)), level, optname, @ptrToInt(optval), @ptrToInt(optlen) });
}
return syscall5(.getsockopt, @bitCast(usize, @as(isize, fd)), level, optname, @ptrToInt(optval), @ptrToInt(optlen));
}
pub fn sendmsg(fd: i32, msg: *const std.x.os.Socket.Message, flags: c_int) usize {
if (native_arch == .i386) {
return socketcall(SC.sendmsg, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(msg), @bitCast(usize, @as(isize, flags)) });
}
return syscall3(.sendmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(msg), @bitCast(usize, @as(isize, flags)));
}
pub fn sendmmsg(fd: i32, msgvec: [*]mmsghdr_const, vlen: u32, flags: u32) usize {
if (@typeInfo(usize).Int.bits > @typeInfo(@TypeOf(mmsghdr(undefined).msg_len)).Int.bits) {
// workaround kernel brokenness:
// if adding up all iov_len overflows a i32 then split into multiple calls
// see https://www.openwall.com/lists/musl/2014/06/07/5
const kvlen = if (vlen > IOV_MAX) IOV_MAX else vlen; // matches kernel
var next_unsent: usize = 0;
for (msgvec[0..kvlen]) |*msg, i| {
var size: i32 = 0;
const msg_iovlen = @intCast(usize, msg.msg_hdr.msg_iovlen); // kernel side this is treated as unsigned
for (msg.msg_hdr.msg_iov[0..msg_iovlen]) |iov| {
if (iov.iov_len > std.math.maxInt(i32) or @addWithOverflow(i32, size, @intCast(i32, iov.iov_len), &size)) {
// batch-send all messages up to the current message
if (next_unsent < i) {
const batch_size = i - next_unsent;
const r = syscall4(.sendmmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(&msgvec[next_unsent]), batch_size, flags);
if (getErrno(r) != 0) return next_unsent;
if (r < batch_size) return next_unsent + r;
}
// send current message as own packet
const r = sendmsg(fd, &msg.msg_hdr, flags);
if (getErrno(r) != 0) return r;
// Linux limits the total bytes sent by sendmsg to INT_MAX, so this cast is safe.
msg.msg_len = @intCast(u32, r);
next_unsent = i + 1;
break;
}
}
}
if (next_unsent < kvlen or next_unsent == 0) { // want to make sure at least one syscall occurs (e.g. to trigger MSG.EOR)
const batch_size = kvlen - next_unsent;
const r = syscall4(.sendmmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(&msgvec[next_unsent]), batch_size, flags);
if (getErrno(r) != 0) return r;
return next_unsent + r;
}
return kvlen;
}
return syscall4(.sendmmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(msgvec), vlen, flags);
}
pub fn connect(fd: i32, addr: *const anyopaque, len: socklen_t) usize {
if (native_arch == .i386) {
return socketcall(SC.connect, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), len });
}
return syscall3(.connect, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), len);
}
pub fn recvmsg(fd: i32, msg: *std.x.os.Socket.Message, flags: c_int) usize {
if (native_arch == .i386) {
return socketcall(SC.recvmsg, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(msg), @bitCast(usize, @as(isize, flags)) });
}
return syscall3(.recvmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(msg), @bitCast(usize, @as(isize, flags)));
}
pub fn recvfrom(fd: i32, noalias buf: [*]u8, len: usize, flags: u32, noalias addr: ?*sockaddr, noalias alen: ?*socklen_t) usize {
if (native_arch == .i386) {
return socketcall(SC.recvfrom, &[6]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), len, flags, @ptrToInt(addr), @ptrToInt(alen) });
}
return syscall6(.recvfrom, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), len, flags, @ptrToInt(addr), @ptrToInt(alen));
}
pub fn shutdown(fd: i32, how: i32) usize {
if (native_arch == .i386) {
return socketcall(SC.shutdown, &[2]usize{ @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, how)) });
}
return syscall2(.shutdown, @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, how)));
}
pub fn bind(fd: i32, addr: *const sockaddr, len: socklen_t) usize {
if (native_arch == .i386) {
return socketcall(SC.bind, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @intCast(usize, len) });
}
return syscall3(.bind, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @intCast(usize, len));
}
pub fn listen(fd: i32, backlog: u32) usize {
if (native_arch == .i386) {
return socketcall(SC.listen, &[2]usize{ @bitCast(usize, @as(isize, fd)), backlog });
}
return syscall2(.listen, @bitCast(usize, @as(isize, fd)), backlog);
}
pub fn sendto(fd: i32, buf: [*]const u8, len: usize, flags: u32, addr: ?*const sockaddr, alen: socklen_t) usize {
if (native_arch == .i386) {
return socketcall(SC.sendto, &[6]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), len, flags, @ptrToInt(addr), @intCast(usize, alen) });
}
return syscall6(.sendto, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), len, flags, @ptrToInt(addr), @intCast(usize, alen));
}
pub fn sendfile(outfd: i32, infd: i32, offset: ?*i64, count: usize) usize {
if (@hasField(SYS, "sendfile64")) {
return syscall4(
.sendfile64,
@bitCast(usize, @as(isize, outfd)),
@bitCast(usize, @as(isize, infd)),
@ptrToInt(offset),
count,
);
} else {
return syscall4(
.sendfile,
@bitCast(usize, @as(isize, outfd)),
@bitCast(usize, @as(isize, infd)),
@ptrToInt(offset),
count,
);
}
}
pub fn socketpair(domain: i32, socket_type: i32, protocol: i32, fd: *[2]i32) usize {
if (native_arch == .i386) {
return socketcall(SC.socketpair, &[4]usize{ @intCast(usize, domain), @intCast(usize, socket_type), @intCast(usize, protocol), @ptrToInt(fd) });
}
return syscall4(.socketpair, @intCast(usize, domain), @intCast(usize, socket_type), @intCast(usize, protocol), @ptrToInt(fd));
}
pub fn accept(fd: i32, noalias addr: ?*sockaddr, noalias len: ?*socklen_t) usize {
if (native_arch == .i386) {
return socketcall(SC.accept, &[4]usize{ fd, addr, len, 0 });
}
return accept4(fd, addr, len, 0);
}
pub fn accept4(fd: i32, noalias addr: ?*sockaddr, noalias len: ?*socklen_t, flags: u32) usize {
if (native_arch == .i386) {
return socketcall(SC.accept4, &[4]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len), flags });
}
return syscall4(.accept4, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len), flags);
}
pub fn fstat(fd: i32, stat_buf: *Stat) usize {
if (@hasField(SYS, "fstat64")) {
return syscall2(.fstat64, @bitCast(usize, @as(isize, fd)), @ptrToInt(stat_buf));
} else {
return syscall2(.fstat, @bitCast(usize, @as(isize, fd)), @ptrToInt(stat_buf));
}
}
pub fn stat(pathname: [*:0]const u8, statbuf: *Stat) usize {
if (@hasField(SYS, "stat64")) {
return syscall2(.stat64, @ptrToInt(pathname), @ptrToInt(statbuf));
} else {
return syscall2(.stat, @ptrToInt(pathname), @ptrToInt(statbuf));
}
}
pub fn lstat(pathname: [*:0]const u8, statbuf: *Stat) usize {
if (@hasField(SYS, "lstat64")) {
return syscall2(.lstat64, @ptrToInt(pathname), @ptrToInt(statbuf));
} else {
return syscall2(.lstat, @ptrToInt(pathname), @ptrToInt(statbuf));
}
}
pub fn fstatat(dirfd: i32, path: [*:0]const u8, stat_buf: *Stat, flags: u32) usize {
if (@hasField(SYS, "fstatat64")) {
return syscall4(.fstatat64, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(stat_buf), flags);
} else {
return syscall4(.fstatat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(stat_buf), flags);
}
}
pub fn statx(dirfd: i32, path: [*]const u8, flags: u32, mask: u32, statx_buf: *Statx) usize {
if (@hasField(SYS, "statx")) {
return syscall5(
.statx,
@bitCast(usize, @as(isize, dirfd)),
@ptrToInt(path),
flags,
mask,
@ptrToInt(statx_buf),
);
}
return @bitCast(usize, -@as(isize, @enumToInt(E.NOSYS)));
}
pub fn listxattr(path: [*:0]const u8, list: [*]u8, size: usize) usize {
return syscall3(.listxattr, @ptrToInt(path), @ptrToInt(list), size);
}
pub fn llistxattr(path: [*:0]const u8, list: [*]u8, size: usize) usize {
return syscall3(.llistxattr, @ptrToInt(path), @ptrToInt(list), size);
}
pub fn flistxattr(fd: usize, list: [*]u8, size: usize) usize {
return syscall3(.flistxattr, fd, @ptrToInt(list), size);
}
pub fn getxattr(path: [*:0]const u8, name: [*:0]const u8, value: [*]u8, size: usize) usize {
return syscall4(.getxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size);
}
pub fn lgetxattr(path: [*:0]const u8, name: [*:0]const u8, value: [*]u8, size: usize) usize {
return syscall4(.lgetxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size);
}
pub fn fgetxattr(fd: usize, name: [*:0]const u8, value: [*]u8, size: usize) usize {
return syscall4(.lgetxattr, fd, @ptrToInt(name), @ptrToInt(value), size);
}
pub fn setxattr(path: [*:0]const u8, name: [*:0]const u8, value: *const void, size: usize, flags: usize) usize {
return syscall5(.setxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size, flags);
}
pub fn lsetxattr(path: [*:0]const u8, name: [*:0]const u8, value: *const void, size: usize, flags: usize) usize {
return syscall5(.lsetxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size, flags);
}
pub fn fsetxattr(fd: usize, name: [*:0]const u8, value: *const void, size: usize, flags: usize) usize {
return syscall5(.fsetxattr, fd, @ptrToInt(name), @ptrToInt(value), size, flags);
}
pub fn removexattr(path: [*:0]const u8, name: [*:0]const u8) usize {
return syscall2(.removexattr, @ptrToInt(path), @ptrToInt(name));
}
pub fn lremovexattr(path: [*:0]const u8, name: [*:0]const u8) usize {
return syscall2(.lremovexattr, @ptrToInt(path), @ptrToInt(name));
}
pub fn fremovexattr(fd: usize, name: [*:0]const u8) usize {
return syscall2(.fremovexattr, fd, @ptrToInt(name));
}
pub fn sched_yield() usize {
return syscall0(.sched_yield);
}
pub fn sched_getaffinity(pid: pid_t, size: usize, set: *cpu_set_t) usize {
const rc = syscall3(.sched_getaffinity, @bitCast(usize, @as(isize, pid)), size, @ptrToInt(set));
if (@bitCast(isize, rc) < 0) return rc;
if (rc < size) @memset(@ptrCast([*]u8, set) + rc, 0, size - rc);
return 0;
}
pub fn epoll_create() usize {
return epoll_create1(0);
}
pub fn epoll_create1(flags: usize) usize {
return syscall1(.epoll_create1, flags);
}
pub fn epoll_ctl(epoll_fd: i32, op: u32, fd: i32, ev: ?*epoll_event) usize {
return syscall4(.epoll_ctl, @bitCast(usize, @as(isize, epoll_fd)), @intCast(usize, op), @bitCast(usize, @as(isize, fd)), @ptrToInt(ev));
}
pub fn epoll_wait(epoll_fd: i32, events: [*]epoll_event, maxevents: u32, timeout: i32) usize {
return epoll_pwait(epoll_fd, events, maxevents, timeout, null);
}
pub fn epoll_pwait(epoll_fd: i32, events: [*]epoll_event, maxevents: u32, timeout: i32, sigmask: ?*const sigset_t) usize {
return syscall6(
.epoll_pwait,
@bitCast(usize, @as(isize, epoll_fd)),
@ptrToInt(events),
@intCast(usize, maxevents),
@bitCast(usize, @as(isize, timeout)),
@ptrToInt(sigmask),
@sizeOf(sigset_t),
);
}
pub fn eventfd(count: u32, flags: u32) usize {
return syscall2(.eventfd2, count, flags);
}
pub fn timerfd_create(clockid: i32, flags: u32) usize {
return syscall2(.timerfd_create, @bitCast(usize, @as(isize, clockid)), flags);
}
pub const itimerspec = extern struct {
it_interval: timespec,
it_value: timespec,
};
pub fn timerfd_gettime(fd: i32, curr_value: *itimerspec) usize {
return syscall2(.timerfd_gettime, @bitCast(usize, @as(isize, fd)), @ptrToInt(curr_value));
}
pub fn timerfd_settime(fd: i32, flags: u32, new_value: *const itimerspec, old_value: ?*itimerspec) usize {
return syscall4(.timerfd_settime, @bitCast(usize, @as(isize, fd)), flags, @ptrToInt(new_value), @ptrToInt(old_value));
}
pub fn unshare(flags: usize) usize {
return syscall1(.unshare, flags);
}
pub fn capget(hdrp: *cap_user_header_t, datap: *cap_user_data_t) usize {
return syscall2(.capget, @ptrToInt(hdrp), @ptrToInt(datap));
}
pub fn capset(hdrp: *cap_user_header_t, datap: *const cap_user_data_t) usize {
return syscall2(.capset, @ptrToInt(hdrp), @ptrToInt(datap));
}
pub fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) usize {
return syscall2(.sigaltstack, @ptrToInt(ss), @ptrToInt(old_ss));
}
pub fn uname(uts: *utsname) usize {
return syscall1(.uname, @ptrToInt(uts));
}
pub fn io_uring_setup(entries: u32, p: *io_uring_params) usize {
return syscall2(.io_uring_setup, entries, @ptrToInt(p));
}
pub fn io_uring_enter(fd: i32, to_submit: u32, min_complete: u32, flags: u32, sig: ?*sigset_t) usize {
return syscall6(.io_uring_enter, @bitCast(usize, @as(isize, fd)), to_submit, min_complete, flags, @ptrToInt(sig), NSIG / 8);
}
pub fn io_uring_register(fd: i32, opcode: IORING_REGISTER, arg: ?*const anyopaque, nr_args: u32) usize {
return syscall4(.io_uring_register, @bitCast(usize, @as(isize, fd)), @enumToInt(opcode), @ptrToInt(arg), nr_args);
}
pub fn memfd_create(name: [*:0]const u8, flags: u32) usize {
return syscall2(.memfd_create, @ptrToInt(name), flags);
}
pub fn getrusage(who: i32, usage: *rusage) usize {
return syscall2(.getrusage, @bitCast(usize, @as(isize, who)), @ptrToInt(usage));
}
pub fn tcgetattr(fd: fd_t, termios_p: *termios) usize {
return syscall3(.ioctl, @bitCast(usize, @as(isize, fd)), T.CGETS, @ptrToInt(termios_p));
}
pub fn tcsetattr(fd: fd_t, optional_action: TCSA, termios_p: *const termios) usize {
return syscall3(.ioctl, @bitCast(usize, @as(isize, fd)), T.CSETS + @enumToInt(optional_action), @ptrToInt(termios_p));
}
pub fn ioctl(fd: fd_t, request: u32, arg: usize) usize {
return syscall3(.ioctl, @bitCast(usize, @as(isize, fd)), request, arg);
}
pub fn signalfd(fd: fd_t, mask: *const sigset_t, flags: u32) usize {
return syscall4(.signalfd4, @bitCast(usize, @as(isize, fd)), @ptrToInt(mask), NSIG / 8, flags);
}
pub fn copy_file_range(fd_in: fd_t, off_in: ?*i64, fd_out: fd_t, off_out: ?*i64, len: usize, flags: u32) usize {
return syscall6(
.copy_file_range,
@bitCast(usize, @as(isize, fd_in)),
@ptrToInt(off_in),
@bitCast(usize, @as(isize, fd_out)),
@ptrToInt(off_out),
len,
flags,
);
}
pub fn bpf(cmd: BPF.Cmd, attr: *BPF.Attr, size: u32) usize {
return syscall3(.bpf, @enumToInt(cmd), @ptrToInt(attr), size);
}
pub fn sync() void {
_ = syscall0(.sync);
}
pub fn syncfs(fd: fd_t) usize {
return syscall1(.syncfs, @bitCast(usize, @as(isize, fd)));
}
pub fn fsync(fd: fd_t) usize {
return syscall1(.fsync, @bitCast(usize, @as(isize, fd)));
}
pub fn fdatasync(fd: fd_t) usize {
return syscall1(.fdatasync, @bitCast(usize, @as(isize, fd)));
}
pub fn prctl(option: i32, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize {
return syscall5(.prctl, @bitCast(usize, @as(isize, option)), arg2, arg3, arg4, arg5);
}
pub fn getrlimit(resource: rlimit_resource, rlim: *rlimit) usize {
// use prlimit64 to have 64 bit limits on 32 bit platforms
return prlimit(0, resource, null, rlim);
}
pub fn setrlimit(resource: rlimit_resource, rlim: *const rlimit) usize {
// use prlimit64 to have 64 bit limits on 32 bit platforms
return prlimit(0, resource, rlim, null);
}
pub fn prlimit(pid: pid_t, resource: rlimit_resource, new_limit: ?*const rlimit, old_limit: ?*rlimit) usize {
return syscall4(
.prlimit64,
@bitCast(usize, @as(isize, pid)),
@bitCast(usize, @as(isize, @enumToInt(resource))),
@ptrToInt(new_limit),
@ptrToInt(old_limit),
);
}
pub fn madvise(address: [*]u8, len: usize, advice: u32) usize {
return syscall3(.madvise, @ptrToInt(address), len, advice);
}
pub fn pidfd_open(pid: pid_t, flags: u32) usize {
return syscall2(.pidfd_open, @bitCast(usize, @as(isize, pid)), flags);
}
pub fn pidfd_getfd(pidfd: fd_t, targetfd: fd_t, flags: u32) usize {
return syscall3(
.pidfd_getfd,
@bitCast(usize, @as(isize, pidfd)),
@bitCast(usize, @as(isize, targetfd)),
flags,
);
}
pub fn pidfd_send_signal(pidfd: fd_t, sig: i32, info: ?*siginfo_t, flags: u32) usize {
return syscall4(
.pidfd_send_signal,
@bitCast(usize, @as(isize, pidfd)),
@bitCast(usize, @as(isize, sig)),
@ptrToInt(info),
flags,
);
}
pub fn process_vm_readv(pid: pid_t, local: [*]const iovec, local_count: usize, remote: [*]const iovec, remote_count: usize, flags: usize) usize {
return syscall6(
.process_vm_readv,
@bitCast(usize, @as(isize, pid)),
@ptrToInt(local),
local_count,
@ptrToInt(remote),
remote_count,
flags,
);
}
pub fn process_vm_writev(pid: pid_t, local: [*]const iovec, local_count: usize, remote: [*]const iovec, remote_count: usize, flags: usize) usize {
return syscall6(
.process_vm_writev,
@bitCast(usize, @as(isize, pid)),
@ptrToInt(local),
local_count,
@ptrToInt(remote),
remote_count,
flags,
);
}
pub fn fadvise(fd: fd_t, offset: i64, len: i64, advice: usize) usize {
if (comptime builtin.cpu.arch.isMIPS()) {
// MIPS requires a 7 argument syscall
const offset_halves = splitValue64(offset);
const length_halves = splitValue64(len);
return syscall7(
.fadvise64,
@bitCast(usize, @as(isize, fd)),
0,
offset_halves[0],
offset_halves[1],
length_halves[0],
length_halves[1],
advice,
);
} else if (comptime builtin.cpu.arch.isARM()) {
// ARM reorders the arguments
const offset_halves = splitValue64(offset);
const length_halves = splitValue64(len);
return syscall6(
.fadvise64_64,
@bitCast(usize, @as(isize, fd)),
advice,
offset_halves[0],
offset_halves[1],
length_halves[0],
length_halves[1],
);
} else if (@hasField(SYS, "fadvise64_64") and usize_bits != 64) {
// The extra usize check is needed to avoid SPARC64 because it provides both
// fadvise64 and fadvise64_64 but the latter behaves differently than other platforms.
const offset_halves = splitValue64(offset);
const length_halves = splitValue64(len);
return syscall6(
.fadvise64_64,
@bitCast(usize, @as(isize, fd)),
offset_halves[0],
offset_halves[1],
length_halves[0],
length_halves[1],
advice,
);
} else {
return syscall4(
.fadvise64,
@bitCast(usize, @as(isize, fd)),
@bitCast(usize, offset),
@bitCast(usize, len),
advice,
);
}
}
pub fn perf_event_open(
attr: *perf_event_attr,
pid: pid_t,
cpu: i32,
group_fd: fd_t,
flags: usize,
) usize {
return syscall5(
.perf_event_open,
@ptrToInt(attr),
@bitCast(usize, @as(isize, pid)),
@bitCast(usize, @as(isize, cpu)),
@bitCast(usize, @as(isize, group_fd)),
flags,
);
}
pub const E = switch (native_arch) {
.mips, .mipsel => @import("linux/errno/mips.zig").E,
.sparc, .sparcel, .sparcv9 => @import("linux/errno/sparc.zig").E,
else => @import("linux/errno/generic.zig").E,
};
pub const pid_t = i32;
pub const fd_t = i32;
pub const uid_t = u32;
pub const gid_t = u32;
pub const clock_t = isize;
pub const NAME_MAX = 255;
pub const PATH_MAX = 4096;
pub const IOV_MAX = 1024;
/// Largest hardware address length
/// e.g. a mac address is a type of hardware address
pub const MAX_ADDR_LEN = 32;
pub const STDIN_FILENO = 0;
pub const STDOUT_FILENO = 1;
pub const STDERR_FILENO = 2;
pub const AT = struct {
/// Special value used to indicate openat should use the current working directory
pub const FDCWD = -100;
/// Do not follow symbolic links
pub const SYMLINK_NOFOLLOW = 0x100;
/// Remove directory instead of unlinking file
pub const REMOVEDIR = 0x200;
/// Follow symbolic links.
pub const SYMLINK_FOLLOW = 0x400;
/// Suppress terminal automount traversal
pub const NO_AUTOMOUNT = 0x800;
/// Allow empty relative pathname
pub const EMPTY_PATH = 0x1000;
/// Type of synchronisation required from statx()
pub const STATX_SYNC_TYPE = 0x6000;
/// - Do whatever stat() does
pub const STATX_SYNC_AS_STAT = 0x0000;
/// - Force the attributes to be sync'd with the server
pub const STATX_FORCE_SYNC = 0x2000;
/// - Don't sync attributes with the server
pub const STATX_DONT_SYNC = 0x4000;
/// Apply to the entire subtree
pub const RECURSIVE = 0x8000;
};
pub const FALLOC = struct {
/// Default is extend size
pub const FL_KEEP_SIZE = 0x01;
/// De-allocates range
pub const FL_PUNCH_HOLE = 0x02;
/// Reserved codepoint
pub const FL_NO_HIDE_STALE = 0x04;
/// Removes a range of a file without leaving a hole in the file
pub const FL_COLLAPSE_RANGE = 0x08;
/// Converts a range of file to zeros preferably without issuing data IO
pub const FL_ZERO_RANGE = 0x10;
/// Inserts space within the file size without overwriting any existing data
pub const FL_INSERT_RANGE = 0x20;
/// Unshares shared blocks within the file size without overwriting any existing data
pub const FL_UNSHARE_RANGE = 0x40;
};
pub const FUTEX = struct {
pub const WAIT = 0;
pub const WAKE = 1;
pub const FD = 2;
pub const REQUEUE = 3;
pub const CMP_REQUEUE = 4;
pub const WAKE_OP = 5;
pub const LOCK_PI = 6;
pub const UNLOCK_PI = 7;
pub const TRYLOCK_PI = 8;
pub const WAIT_BITSET = 9;
pub const WAKE_BITSET = 10;
pub const WAIT_REQUEUE_PI = 11;
pub const CMP_REQUEUE_PI = 12;
pub const PRIVATE_FLAG = 128;
pub const CLOCK_REALTIME = 256;
};
pub const PROT = struct {
/// page can not be accessed
pub const NONE = 0x0;
/// page can be read
pub const READ = 0x1;
/// page can be written
pub const WRITE = 0x2;
/// page can be executed
pub const EXEC = 0x4;
/// page may be used for atomic ops
pub const SEM = switch (native_arch) {
// TODO: also xtensa
.mips, .mipsel, .mips64, .mips64el => 0x10,
else => 0x8,
};
/// mprotect flag: extend change to start of growsdown vma
pub const GROWSDOWN = 0x01000000;
/// mprotect flag: extend change to end of growsup vma
pub const GROWSUP = 0x02000000;
};
pub const FD_CLOEXEC = 1;
pub const F_OK = 0;
pub const X_OK = 1;
pub const W_OK = 2;
pub const R_OK = 4;
pub const W = struct {
pub const NOHANG = 1;
pub const UNTRACED = 2;
pub const STOPPED = 2;
pub const EXITED = 4;
pub const CONTINUED = 8;
pub const NOWAIT = 0x1000000;
pub fn EXITSTATUS(s: u32) u8 {
return @intCast(u8, (s & 0xff00) >> 8);
}
pub fn TERMSIG(s: u32) u32 {
return s & 0x7f;
}
pub fn STOPSIG(s: u32) u32 {
return EXITSTATUS(s);
}
pub fn IFEXITED(s: u32) bool {
return TERMSIG(s) == 0;
}
pub fn IFSTOPPED(s: u32) bool {
return @truncate(u16, ((s & 0xffff) *% 0x10001) >> 8) > 0x7f00;
}
pub fn IFSIGNALED(s: u32) bool {
return (s & 0xffff) -% 1 < 0xff;
}
};
// waitid id types
pub const P = enum(c_uint) {
ALL = 0,
PID = 1,
PGID = 2,
PIDFD = 3,
_,
};
pub const SA = if (is_mips) struct {
pub const NOCLDSTOP = 1;
pub const NOCLDWAIT = 0x10000;
pub const SIGINFO = 8;
pub const RESTART = 0x10000000;
pub const RESETHAND = 0x80000000;
pub const ONSTACK = 0x08000000;
pub const NODEFER = 0x40000000;
pub const RESTORER = 0x04000000;
} else if (is_sparc) struct {
pub const NOCLDSTOP = 0x8;
pub const NOCLDWAIT = 0x100;
pub const SIGINFO = 0x200;
pub const RESTART = 0x2;
pub const RESETHAND = 0x4;
pub const ONSTACK = 0x1;
pub const NODEFER = 0x20;
pub const RESTORER = 0x04000000;
} else struct {
pub const NOCLDSTOP = 1;
pub const NOCLDWAIT = 2;
pub const SIGINFO = 4;
pub const RESTART = 0x10000000;
pub const RESETHAND = 0x80000000;
pub const ONSTACK = 0x08000000;
pub const NODEFER = 0x40000000;
pub const RESTORER = 0x04000000;
};
pub const SIG = if (is_mips) struct {
pub const BLOCK = 1;
pub const UNBLOCK = 2;
pub const SETMASK = 3;
pub const HUP = 1;
pub const INT = 2;
pub const QUIT = 3;
pub const ILL = 4;
pub const TRAP = 5;
pub const ABRT = 6;
pub const IOT = ABRT;
pub const BUS = 7;
pub const FPE = 8;
pub const KILL = 9;
pub const USR1 = 10;
pub const SEGV = 11;
pub const USR2 = 12;
pub const PIPE = 13;
pub const ALRM = 14;
pub const TERM = 15;
pub const STKFLT = 16;
pub const CHLD = 17;
pub const CONT = 18;
pub const STOP = 19;
pub const TSTP = 20;
pub const TTIN = 21;
pub const TTOU = 22;
pub const URG = 23;
pub const XCPU = 24;
pub const XFSZ = 25;
pub const VTALRM = 26;
pub const PROF = 27;
pub const WINCH = 28;
pub const IO = 29;
pub const POLL = 29;
pub const PWR = 30;
pub const SYS = 31;
pub const UNUSED = SIG.SYS;
pub const ERR = @intToPtr(?Sigaction.sigaction_fn, maxInt(usize));
pub const DFL = @intToPtr(?Sigaction.sigaction_fn, 0);
pub const IGN = @intToPtr(?Sigaction.sigaction_fn, 1);
} else if (is_sparc) struct {
pub const BLOCK = 1;
pub const UNBLOCK = 2;
pub const SETMASK = 4;
pub const HUP = 1;
pub const INT = 2;
pub const QUIT = 3;
pub const ILL = 4;
pub const TRAP = 5;
pub const ABRT = 6;
pub const EMT = 7;
pub const FPE = 8;
pub const KILL = 9;
pub const BUS = 10;
pub const SEGV = 11;
pub const SYS = 12;
pub const PIPE = 13;
pub const ALRM = 14;
pub const TERM = 15;
pub const URG = 16;
pub const STOP = 17;
pub const TSTP = 18;
pub const CONT = 19;
pub const CHLD = 20;
pub const TTIN = 21;
pub const TTOU = 22;
pub const POLL = 23;
pub const XCPU = 24;
pub const XFSZ = 25;
pub const VTALRM = 26;
pub const PROF = 27;
pub const WINCH = 28;
pub const LOST = 29;
pub const USR1 = 30;
pub const USR2 = 31;
pub const IOT = ABRT;
pub const CLD = CHLD;
pub const PWR = LOST;
pub const IO = SIG.POLL;
pub const ERR = @intToPtr(?Sigaction.sigaction_fn, maxInt(usize));
pub const DFL = @intToPtr(?Sigaction.sigaction_fn, 0);
pub const IGN = @intToPtr(?Sigaction.sigaction_fn, 1);
} else struct {
pub const BLOCK = 0;
pub const UNBLOCK = 1;
pub const SETMASK = 2;
pub const HUP = 1;
pub const INT = 2;
pub const QUIT = 3;
pub const ILL = 4;
pub const TRAP = 5;
pub const ABRT = 6;
pub const IOT = ABRT;
pub const BUS = 7;
pub const FPE = 8;
pub const KILL = 9;
pub const USR1 = 10;
pub const SEGV = 11;
pub const USR2 = 12;
pub const PIPE = 13;
pub const ALRM = 14;
pub const TERM = 15;
pub const STKFLT = 16;
pub const CHLD = 17;
pub const CONT = 18;
pub const STOP = 19;
pub const TSTP = 20;
pub const TTIN = 21;
pub const TTOU = 22;
pub const URG = 23;
pub const XCPU = 24;
pub const XFSZ = 25;
pub const VTALRM = 26;
pub const PROF = 27;
pub const WINCH = 28;
pub const IO = 29;
pub const POLL = 29;
pub const PWR = 30;
pub const SYS = 31;
pub const UNUSED = SIG.SYS;
pub const ERR = @intToPtr(?Sigaction.sigaction_fn, maxInt(usize));
pub const DFL = @intToPtr(?Sigaction.sigaction_fn, 0);
pub const IGN = @intToPtr(?Sigaction.sigaction_fn, 1);
};
pub const kernel_rwf = u32;
pub const RWF = struct {
/// high priority request, poll if possible
pub const HIPRI: kernel_rwf = 0x00000001;
/// per-IO O.DSYNC
pub const DSYNC: kernel_rwf = 0x00000002;
/// per-IO O.SYNC
pub const SYNC: kernel_rwf = 0x00000004;
/// per-IO, return -EAGAIN if operation would block
pub const NOWAIT: kernel_rwf = 0x00000008;
/// per-IO O.APPEND
pub const APPEND: kernel_rwf = 0x00000010;
};
pub const SEEK = struct {
pub const SET = 0;
pub const CUR = 1;
pub const END = 2;
};
pub const SHUT = struct {
pub const RD = 0;
pub const WR = 1;
pub const RDWR = 2;
};
pub const SOCK = struct {
pub const STREAM = if (is_mips) 2 else 1;
pub const DGRAM = if (is_mips) 1 else 2;
pub const RAW = 3;
pub const RDM = 4;
pub const SEQPACKET = 5;
pub const DCCP = 6;
pub const PACKET = 10;
pub const CLOEXEC = if (is_sparc) 0o20000000 else 0o2000000;
pub const NONBLOCK = if (is_mips) 0o200 else if (is_sparc) 0o40000 else 0o4000;
};
pub const TCP = struct {
/// Turn off Nagle's algorithm
pub const NODELAY = 1;
/// Limit MSS
pub const MAXSEG = 2;
/// Never send partially complete segments.
pub const CORK = 3;
/// Start keeplives after this period, in seconds
pub const KEEPIDLE = 4;
/// Interval between keepalives
pub const KEEPINTVL = 5;
/// Number of keepalives before death
pub const KEEPCNT = 6;
/// Number of SYN retransmits
pub const SYNCNT = 7;
/// Life time of orphaned FIN-WAIT-2 state
pub const LINGER2 = 8;
/// Wake up listener only when data arrive
pub const DEFER_ACCEPT = 9;
/// Bound advertised window
pub const WINDOW_CLAMP = 10;
/// Information about this connection.
pub const INFO = 11;
/// Block/reenable quick acks
pub const QUICKACK = 12;
/// Congestion control algorithm
pub const CONGESTION = 13;
/// TCP MD5 Signature (RFC2385)
pub const MD5SIG = 14;
/// Use linear timeouts for thin streams
pub const THIN_LINEAR_TIMEOUTS = 16;
/// Fast retrans. after 1 dupack
pub const THIN_DUPACK = 17;
/// How long for loss retry before timeout
pub const USER_TIMEOUT = 18;
/// TCP sock is under repair right now
pub const REPAIR = 19;
pub const REPAIR_QUEUE = 20;
pub const QUEUE_SEQ = 21;
pub const REPAIR_OPTIONS = 22;
/// Enable FastOpen on listeners
pub const FASTOPEN = 23;
pub const TIMESTAMP = 24;
/// limit number of unsent bytes in write queue
pub const NOTSENT_LOWAT = 25;
/// Get Congestion Control (optional) info
pub const CC_INFO = 26;
/// Record SYN headers for new connections
pub const SAVE_SYN = 27;
/// Get SYN headers recorded for connection
pub const SAVED_SYN = 28;
/// Get/set window parameters
pub const REPAIR_WINDOW = 29;
/// Attempt FastOpen with connect
pub const FASTOPEN_CONNECT = 30;
/// Attach a ULP to a TCP connection
pub const ULP = 31;
/// TCP MD5 Signature with extensions
pub const MD5SIG_EXT = 32;
/// Set the key for Fast Open (cookie)
pub const FASTOPEN_KEY = 33;
/// Enable TFO without a TFO cookie
pub const FASTOPEN_NO_COOKIE = 34;
pub const ZEROCOPY_RECEIVE = 35;
/// Notify bytes available to read as a cmsg on read
pub const INQ = 36;
pub const CM_INQ = INQ;
/// delay outgoing packets by XX usec
pub const TX_DELAY = 37;
pub const REPAIR_ON = 1;
pub const REPAIR_OFF = 0;
/// Turn off without window probes
pub const REPAIR_OFF_NO_WP = -1;
};
pub const PF = struct {
pub const UNSPEC = 0;
pub const LOCAL = 1;
pub const UNIX = LOCAL;
pub const FILE = LOCAL;
pub const INET = 2;
pub const AX25 = 3;
pub const IPX = 4;
pub const APPLETALK = 5;
pub const NETROM = 6;
pub const BRIDGE = 7;
pub const ATMPVC = 8;
pub const X25 = 9;
pub const INET6 = 10;
pub const ROSE = 11;
pub const DECnet = 12;
pub const NETBEUI = 13;
pub const SECURITY = 14;
pub const KEY = 15;
pub const NETLINK = 16;
pub const ROUTE = PF.NETLINK;
pub const PACKET = 17;
pub const ASH = 18;
pub const ECONET = 19;
pub const ATMSVC = 20;
pub const RDS = 21;
pub const SNA = 22;
pub const IRDA = 23;
pub const PPPOX = 24;
pub const WANPIPE = 25;
pub const LLC = 26;
pub const IB = 27;
pub const MPLS = 28;
pub const CAN = 29;
pub const TIPC = 30;
pub const BLUETOOTH = 31;
pub const IUCV = 32;
pub const RXRPC = 33;
pub const ISDN = 34;
pub const PHONET = 35;
pub const IEEE802154 = 36;
pub const CAIF = 37;
pub const ALG = 38;
pub const NFC = 39;
pub const VSOCK = 40;
pub const KCM = 41;
pub const QIPCRTR = 42;
pub const SMC = 43;
pub const XDP = 44;
pub const MAX = 45;
};
pub const AF = struct {
pub const UNSPEC = PF.UNSPEC;
pub const LOCAL = PF.LOCAL;
pub const UNIX = AF.LOCAL;
pub const FILE = AF.LOCAL;
pub const INET = PF.INET;
pub const AX25 = PF.AX25;
pub const IPX = PF.IPX;
pub const APPLETALK = PF.APPLETALK;
pub const NETROM = PF.NETROM;
pub const BRIDGE = PF.BRIDGE;
pub const ATMPVC = PF.ATMPVC;
pub const X25 = PF.X25;
pub const INET6 = PF.INET6;
pub const ROSE = PF.ROSE;
pub const DECnet = PF.DECnet;
pub const NETBEUI = PF.NETBEUI;
pub const SECURITY = PF.SECURITY;
pub const KEY = PF.KEY;
pub const NETLINK = PF.NETLINK;
pub const ROUTE = PF.ROUTE;
pub const PACKET = PF.PACKET;
pub const ASH = PF.ASH;
pub const ECONET = PF.ECONET;
pub const ATMSVC = PF.ATMSVC;
pub const RDS = PF.RDS;
pub const SNA = PF.SNA;
pub const IRDA = PF.IRDA;
pub const PPPOX = PF.PPPOX;
pub const WANPIPE = PF.WANPIPE;
pub const LLC = PF.LLC;
pub const IB = PF.IB;
pub const MPLS = PF.MPLS;
pub const CAN = PF.CAN;
pub const TIPC = PF.TIPC;
pub const BLUETOOTH = PF.BLUETOOTH;
pub const IUCV = PF.IUCV;
pub const RXRPC = PF.RXRPC;
pub const ISDN = PF.ISDN;
pub const PHONET = PF.PHONET;
pub const IEEE802154 = PF.IEEE802154;
pub const CAIF = PF.CAIF;
pub const ALG = PF.ALG;
pub const NFC = PF.NFC;
pub const VSOCK = PF.VSOCK;
pub const KCM = PF.KCM;
pub const QIPCRTR = PF.QIPCRTR;
pub const SMC = PF.SMC;
pub const XDP = PF.XDP;
pub const MAX = PF.MAX;
};
pub const SO = struct {
pub usingnamespace if (is_mips) struct {
pub const DEBUG = 1;
pub const REUSEADDR = 0x0004;
pub const KEEPALIVE = 0x0008;
pub const DONTROUTE = 0x0010;
pub const BROADCAST = 0x0020;
pub const LINGER = 0x0080;
pub const OOBINLINE = 0x0100;
pub const REUSEPORT = 0x0200;
pub const SNDBUF = 0x1001;
pub const RCVBUF = 0x1002;
pub const SNDLOWAT = 0x1003;
pub const RCVLOWAT = 0x1004;
pub const RCVTIMEO = 0x1006;
pub const SNDTIMEO = 0x1005;
pub const ERROR = 0x1007;
pub const TYPE = 0x1008;
pub const ACCEPTCONN = 0x1009;
pub const PROTOCOL = 0x1028;
pub const DOMAIN = 0x1029;
pub const NO_CHECK = 11;
pub const PRIORITY = 12;
pub const BSDCOMPAT = 14;
pub const PASSCRED = 17;
pub const PEERCRED = 18;
pub const PEERSEC = 30;
pub const SNDBUFFORCE = 31;
pub const RCVBUFFORCE = 33;
pub const SECURITY_AUTHENTICATION = 22;
pub const SECURITY_ENCRYPTION_TRANSPORT = 23;
pub const SECURITY_ENCRYPTION_NETWORK = 24;
pub const BINDTODEVICE = 25;
pub const ATTACH_FILTER = 26;
pub const DETACH_FILTER = 27;
pub const GET_FILTER = ATTACH_FILTER;
pub const PEERNAME = 28;
pub const TIMESTAMP_OLD = 29;
pub const PASSSEC = 34;
pub const TIMESTAMPNS_OLD = 35;
pub const MARK = 36;
pub const TIMESTAMPING_OLD = 37;
pub const RXQ_OVFL = 40;
pub const WIFI_STATUS = 41;
pub const PEEK_OFF = 42;
pub const NOFCS = 43;
pub const LOCK_FILTER = 44;
pub const SELECT_ERR_QUEUE = 45;
pub const BUSY_POLL = 46;
pub const MAX_PACING_RATE = 47;
pub const BPF_EXTENSIONS = 48;
pub const INCOMING_CPU = 49;
pub const ATTACH_BPF = 50;
pub const DETACH_BPF = DETACH_FILTER;
pub const ATTACH_REUSEPORT_CBPF = 51;
pub const ATTACH_REUSEPORT_EBPF = 52;
pub const CNX_ADVICE = 53;
pub const MEMINFO = 55;
pub const INCOMING_NAPI_ID = 56;
pub const COOKIE = 57;
pub const PEERGROUPS = 59;
pub const ZEROCOPY = 60;
pub const TXTIME = 61;
pub const BINDTOIFINDEX = 62;
pub const TIMESTAMP_NEW = 63;
pub const TIMESTAMPNS_NEW = 64;
pub const TIMESTAMPING_NEW = 65;
pub const RCVTIMEO_NEW = 66;
pub const SNDTIMEO_NEW = 67;
pub const DETACH_REUSEPORT_BPF = 68;
} else if (is_ppc or is_ppc64) struct {
pub const DEBUG = 1;
pub const REUSEADDR = 2;
pub const TYPE = 3;
pub const ERROR = 4;
pub const DONTROUTE = 5;
pub const BROADCAST = 6;
pub const SNDBUF = 7;
pub const RCVBUF = 8;
pub const KEEPALIVE = 9;
pub const OOBINLINE = 10;
pub const NO_CHECK = 11;
pub const PRIORITY = 12;
pub const LINGER = 13;
pub const BSDCOMPAT = 14;
pub const REUSEPORT = 15;
pub const RCVLOWAT = 16;
pub const SNDLOWAT = 17;
pub const RCVTIMEO = 18;
pub const SNDTIMEO = 19;
pub const PASSCRED = 20;
pub const PEERCRED = 21;
pub const ACCEPTCONN = 30;
pub const PEERSEC = 31;
pub const SNDBUFFORCE = 32;
pub const RCVBUFFORCE = 33;
pub const PROTOCOL = 38;
pub const DOMAIN = 39;
pub const SECURITY_AUTHENTICATION = 22;
pub const SECURITY_ENCRYPTION_TRANSPORT = 23;
pub const SECURITY_ENCRYPTION_NETWORK = 24;
pub const BINDTODEVICE = 25;
pub const ATTACH_FILTER = 26;
pub const DETACH_FILTER = 27;
pub const GET_FILTER = ATTACH_FILTER;
pub const PEERNAME = 28;
pub const TIMESTAMP_OLD = 29;
pub const PASSSEC = 34;
pub const TIMESTAMPNS_OLD = 35;
pub const MARK = 36;
pub const TIMESTAMPING_OLD = 37;
pub const RXQ_OVFL = 40;
pub const WIFI_STATUS = 41;
pub const PEEK_OFF = 42;
pub const NOFCS = 43;
pub const LOCK_FILTER = 44;
pub const SELECT_ERR_QUEUE = 45;
pub const BUSY_POLL = 46;
pub const MAX_PACING_RATE = 47;
pub const BPF_EXTENSIONS = 48;
pub const INCOMING_CPU = 49;
pub const ATTACH_BPF = 50;
pub const DETACH_BPF = DETACH_FILTER;
pub const ATTACH_REUSEPORT_CBPF = 51;
pub const ATTACH_REUSEPORT_EBPF = 52;
pub const CNX_ADVICE = 53;
pub const MEMINFO = 55;
pub const INCOMING_NAPI_ID = 56;
pub const COOKIE = 57;
pub const PEERGROUPS = 59;
pub const ZEROCOPY = 60;
pub const TXTIME = 61;
pub const BINDTOIFINDEX = 62;
pub const TIMESTAMP_NEW = 63;
pub const TIMESTAMPNS_NEW = 64;
pub const TIMESTAMPING_NEW = 65;
pub const RCVTIMEO_NEW = 66;
pub const SNDTIMEO_NEW = 67;
pub const DETACH_REUSEPORT_BPF = 68;
} else if (is_sparc) struct {
pub const DEBUG = 1;
pub const REUSEADDR = 4;
pub const TYPE = 4104;
pub const ERROR = 4103;
pub const DONTROUTE = 16;
pub const BROADCAST = 32;
pub const SNDBUF = 4097;
pub const RCVBUF = 4098;
pub const KEEPALIVE = 8;
pub const OOBINLINE = 256;
pub const NO_CHECK = 11;
pub const PRIORITY = 12;
pub const LINGER = 128;
pub const BSDCOMPAT = 1024;
pub const REUSEPORT = 512;
pub const PASSCRED = 2;
pub const PEERCRED = 64;
pub const RCVLOWAT = 2048;
pub const SNDLOWAT = 4096;
pub const RCVTIMEO = 8192;
pub const SNDTIMEO = 16384;
pub const ACCEPTCONN = 32768;
pub const PEERSEC = 30;
pub const SNDBUFFORCE = 4106;
pub const RCVBUFFORCE = 4107;
pub const PROTOCOL = 4136;
pub const DOMAIN = 4137;
pub const SECURITY_AUTHENTICATION = 20481;
pub const SECURITY_ENCRYPTION_TRANSPORT = 20482;
pub const SECURITY_ENCRYPTION_NETWORK = 20484;
pub const BINDTODEVICE = 13;
pub const ATTACH_FILTER = 26;
pub const DETACH_FILTER = 27;
pub const GET_FILTER = 26;
pub const PEERNAME = 28;
pub const TIMESTAMP_OLD = 29;
pub const PASSSEC = 31;
pub const TIMESTAMPNS_OLD = 33;
pub const MARK = 34;
pub const TIMESTAMPING_OLD = 35;
pub const RXQ_OVFL = 36;
pub const WIFI_STATUS = 37;
pub const PEEK_OFF = 38;
pub const NOFCS = 39;
pub const LOCK_FILTER = 40;
pub const SELECT_ERR_QUEUE = 41;
pub const BUSY_POLL = 48;
pub const MAX_PACING_RATE = 49;
pub const BPF_EXTENSIONS = 50;
pub const INCOMING_CPU = 51;
pub const ATTACH_BPF = 52;
pub const DETACH_BPF = 27;
pub const ATTACH_REUSEPORT_CBPF = 53;
pub const ATTACH_REUSEPORT_EBPF = 54;
pub const CNX_ADVICE = 55;
pub const MEMINFO = 57;
pub const INCOMING_NAPI_ID = 58;
pub const COOKIE = 59;
pub const PEERGROUPS = 61;
pub const ZEROCOPY = 62;
pub const TXTIME = 63;
pub const BINDTOIFINDEX = 65;
pub const TIMESTAMP_NEW = 70;
pub const TIMESTAMPNS_NEW = 66;
pub const TIMESTAMPING_NEW = 67;
pub const RCVTIMEO_NEW = 68;
pub const SNDTIMEO_NEW = 69;
pub const DETACH_REUSEPORT_BPF = 71;
} else struct {
pub const DEBUG = 1;
pub const REUSEADDR = 2;
pub const TYPE = 3;
pub const ERROR = 4;
pub const DONTROUTE = 5;
pub const BROADCAST = 6;
pub const SNDBUF = 7;
pub const RCVBUF = 8;
pub const KEEPALIVE = 9;
pub const OOBINLINE = 10;
pub const NO_CHECK = 11;
pub const PRIORITY = 12;
pub const LINGER = 13;
pub const BSDCOMPAT = 14;
pub const REUSEPORT = 15;
pub const PASSCRED = 16;
pub const PEERCRED = 17;
pub const RCVLOWAT = 18;
pub const SNDLOWAT = 19;
pub const RCVTIMEO = 20;
pub const SNDTIMEO = 21;
pub const ACCEPTCONN = 30;
pub const PEERSEC = 31;
pub const SNDBUFFORCE = 32;
pub const RCVBUFFORCE = 33;
pub const PROTOCOL = 38;
pub const DOMAIN = 39;
pub const SECURITY_AUTHENTICATION = 22;
pub const SECURITY_ENCRYPTION_TRANSPORT = 23;
pub const SECURITY_ENCRYPTION_NETWORK = 24;
pub const BINDTODEVICE = 25;
pub const ATTACH_FILTER = 26;
pub const DETACH_FILTER = 27;
pub const GET_FILTER = ATTACH_FILTER;
pub const PEERNAME = 28;
pub const TIMESTAMP_OLD = 29;
pub const PASSSEC = 34;
pub const TIMESTAMPNS_OLD = 35;
pub const MARK = 36;
pub const TIMESTAMPING_OLD = 37;
pub const RXQ_OVFL = 40;
pub const WIFI_STATUS = 41;
pub const PEEK_OFF = 42;
pub const NOFCS = 43;
pub const LOCK_FILTER = 44;
pub const SELECT_ERR_QUEUE = 45;
pub const BUSY_POLL = 46;
pub const MAX_PACING_RATE = 47;
pub const BPF_EXTENSIONS = 48;
pub const INCOMING_CPU = 49;
pub const ATTACH_BPF = 50;
pub const DETACH_BPF = DETACH_FILTER;
pub const ATTACH_REUSEPORT_CBPF = 51;
pub const ATTACH_REUSEPORT_EBPF = 52;
pub const CNX_ADVICE = 53;
pub const MEMINFO = 55;
pub const INCOMING_NAPI_ID = 56;
pub const COOKIE = 57;
pub const PEERGROUPS = 59;
pub const ZEROCOPY = 60;
pub const TXTIME = 61;
pub const BINDTOIFINDEX = 62;
pub const TIMESTAMP_NEW = 63;
pub const TIMESTAMPNS_NEW = 64;
pub const TIMESTAMPING_NEW = 65;
pub const RCVTIMEO_NEW = 66;
pub const SNDTIMEO_NEW = 67;
pub const DETACH_REUSEPORT_BPF = 68;
};
};
pub const SCM = struct {
pub const WIFI_STATUS = SO.WIFI_STATUS;
pub const TIMESTAMPING_OPT_STATS = 54;
pub const TIMESTAMPING_PKTINFO = 58;
pub const TXTIME = SO.TXTIME;
};
pub const SOL = struct {
pub const SOCKET = if (is_mips or is_sparc) 65535 else 1;
pub const IP = 0;
pub const IPV6 = 41;
pub const ICMPV6 = 58;
pub const RAW = 255;
pub const DECNET = 261;
pub const X25 = 262;
pub const PACKET = 263;
pub const ATM = 264;
pub const AAL = 265;
pub const IRDA = 266;
pub const NETBEUI = 267;
pub const LLC = 268;
pub const DCCP = 269;
pub const NETLINK = 270;
pub const TIPC = 271;
pub const RXRPC = 272;
pub const PPPOL2TP = 273;
pub const BLUETOOTH = 274;
pub const PNPIPE = 275;
pub const RDS = 276;
pub const IUCV = 277;
pub const CAIF = 278;
pub const ALG = 279;
pub const NFC = 280;
pub const KCM = 281;
pub const TLS = 282;
pub const XDP = 283;
};
pub const SOMAXCONN = 128;
pub const IP = struct {
pub const TOS = 1;
pub const TTL = 2;
pub const HDRINCL = 3;
pub const OPTIONS = 4;
pub const ROUTER_ALERT = 5;
pub const RECVOPTS = 6;
pub const RETOPTS = 7;
pub const PKTINFO = 8;
pub const PKTOPTIONS = 9;
pub const PMTUDISC = 10;
pub const MTU_DISCOVER = 10;
pub const RECVERR = 11;
pub const RECVTTL = 12;
pub const RECVTOS = 13;
pub const MTU = 14;
pub const FREEBIND = 15;
pub const IPSEC_POLICY = 16;
pub const XFRM_POLICY = 17;
pub const PASSSEC = 18;
pub const TRANSPARENT = 19;
pub const ORIGDSTADDR = 20;
pub const RECVORIGDSTADDR = IP.ORIGDSTADDR;
pub const MINTTL = 21;
pub const NODEFRAG = 22;
pub const CHECKSUM = 23;
pub const BIND_ADDRESS_NO_PORT = 24;
pub const RECVFRAGSIZE = 25;
pub const MULTICAST_IF = 32;
pub const MULTICAST_TTL = 33;
pub const MULTICAST_LOOP = 34;
pub const ADD_MEMBERSHIP = 35;
pub const DROP_MEMBERSHIP = 36;
pub const UNBLOCK_SOURCE = 37;
pub const BLOCK_SOURCE = 38;
pub const ADD_SOURCE_MEMBERSHIP = 39;
pub const DROP_SOURCE_MEMBERSHIP = 40;
pub const MSFILTER = 41;
pub const MULTICAST_ALL = 49;
pub const UNICAST_IF = 50;
pub const RECVRETOPTS = IP.RETOPTS;
pub const PMTUDISC_DONT = 0;
pub const PMTUDISC_WANT = 1;
pub const PMTUDISC_DO = 2;
pub const PMTUDISC_PROBE = 3;
pub const PMTUDISC_INTERFACE = 4;
pub const PMTUDISC_OMIT = 5;
pub const DEFAULT_MULTICAST_TTL = 1;
pub const DEFAULT_MULTICAST_LOOP = 1;
pub const MAX_MEMBERSHIPS = 20;
};
/// IPv6 socket options
pub const IPV6 = struct {
pub const ADDRFORM = 1;
pub const @"2292PKTINFO" = 2;
pub const @"2292HOPOPTS" = 3;
pub const @"2292DSTOPTS" = 4;
pub const @"2292RTHDR" = 5;
pub const @"2292PKTOPTIONS" = 6;
pub const CHECKSUM = 7;
pub const @"2292HOPLIMIT" = 8;
pub const NEXTHOP = 9;
pub const AUTHHDR = 10;
pub const FLOWINFO = 11;
pub const UNICAST_HOPS = 16;
pub const MULTICAST_IF = 17;
pub const MULTICAST_HOPS = 18;
pub const MULTICAST_LOOP = 19;
pub const ADD_MEMBERSHIP = 20;
pub const DROP_MEMBERSHIP = 21;
pub const ROUTER_ALERT = 22;
pub const MTU_DISCOVER = 23;
pub const MTU = 24;
pub const RECVERR = 25;
pub const V6ONLY = 26;
pub const JOIN_ANYCAST = 27;
pub const LEAVE_ANYCAST = 28;
// IPV6.MTU_DISCOVER values
pub const PMTUDISC_DONT = 0;
pub const PMTUDISC_WANT = 1;
pub const PMTUDISC_DO = 2;
pub const PMTUDISC_PROBE = 3;
pub const PMTUDISC_INTERFACE = 4;
pub const PMTUDISC_OMIT = 5;
// Flowlabel
pub const FLOWLABEL_MGR = 32;
pub const FLOWINFO_SEND = 33;
pub const IPSEC_POLICY = 34;
pub const XFRM_POLICY = 35;
pub const HDRINCL = 36;
// Advanced API (RFC3542) (1)
pub const RECVPKTINFO = 49;
pub const PKTINFO = 50;
pub const RECVHOPLIMIT = 51;
pub const HOPLIMIT = 52;
pub const RECVHOPOPTS = 53;
pub const HOPOPTS = 54;
pub const RTHDRDSTOPTS = 55;
pub const RECVRTHDR = 56;
pub const RTHDR = 57;
pub const RECVDSTOPTS = 58;
pub const DSTOPTS = 59;
pub const RECVPATHMTU = 60;
pub const PATHMTU = 61;
pub const DONTFRAG = 62;
// Advanced API (RFC3542) (2)
pub const RECVTCLASS = 66;
pub const TCLASS = 67;
pub const AUTOFLOWLABEL = 70;
// RFC5014: Source address selection
pub const ADDR_PREFERENCES = 72;
pub const PREFER_SRC_TMP = 0x0001;
pub const PREFER_SRC_PUBLIC = 0x0002;
pub const PREFER_SRC_PUBTMP_DEFAULT = 0x0100;
pub const PREFER_SRC_COA = 0x0004;
pub const PREFER_SRC_HOME = 0x0400;
pub const PREFER_SRC_CGA = 0x0008;
pub const PREFER_SRC_NONCGA = 0x0800;
// RFC5082: Generalized Ttl Security Mechanism
pub const MINHOPCOUNT = 73;
pub const ORIGDSTADDR = 74;
pub const RECVORIGDSTADDR = IPV6.ORIGDSTADDR;
pub const TRANSPARENT = 75;
pub const UNICAST_IF = 76;
pub const RECVFRAGSIZE = 77;
pub const FREEBIND = 78;
};
pub const MSG = struct {
pub const OOB = 0x0001;
pub const PEEK = 0x0002;
pub const DONTROUTE = 0x0004;
pub const CTRUNC = 0x0008;
pub const PROXY = 0x0010;
pub const TRUNC = 0x0020;
pub const DONTWAIT = 0x0040;
pub const EOR = 0x0080;
pub const WAITALL = 0x0100;
pub const FIN = 0x0200;
pub const SYN = 0x0400;
pub const CONFIRM = 0x0800;
pub const RST = 0x1000;
pub const ERRQUEUE = 0x2000;
pub const NOSIGNAL = 0x4000;
pub const MORE = 0x8000;
pub const WAITFORONE = 0x10000;
pub const BATCH = 0x40000;
pub const ZEROCOPY = 0x4000000;
pub const FASTOPEN = 0x20000000;
pub const CMSG_CLOEXEC = 0x40000000;
};
pub const DT = struct {
pub const UNKNOWN = 0;
pub const FIFO = 1;
pub const CHR = 2;
pub const DIR = 4;
pub const BLK = 6;
pub const REG = 8;
pub const LNK = 10;
pub const SOCK = 12;
pub const WHT = 14;
};
pub const T = struct {
pub const CGETS = if (is_mips) 0x540D else 0x5401;
pub const CSETS = 0x5402;
pub const CSETSW = 0x5403;
pub const CSETSF = 0x5404;
pub const CGETA = 0x5405;
pub const CSETA = 0x5406;
pub const CSETAW = 0x5407;
pub const CSETAF = 0x5408;
pub const CSBRK = 0x5409;
pub const CXONC = 0x540A;
pub const CFLSH = 0x540B;
pub const IOCEXCL = 0x540C;
pub const IOCNXCL = 0x540D;
pub const IOCSCTTY = 0x540E;
pub const IOCGPGRP = 0x540F;
pub const IOCSPGRP = 0x5410;
pub const IOCOUTQ = if (is_mips) 0x7472 else 0x5411;
pub const IOCSTI = 0x5412;
pub const IOCGWINSZ = if (is_mips or is_ppc64) 0x40087468 else 0x5413;
pub const IOCSWINSZ = if (is_mips or is_ppc64) 0x80087467 else 0x5414;
pub const IOCMGET = 0x5415;
pub const IOCMBIS = 0x5416;
pub const IOCMBIC = 0x5417;
pub const IOCMSET = 0x5418;
pub const IOCGSOFTCAR = 0x5419;
pub const IOCSSOFTCAR = 0x541A;
pub const FIONREAD = if (is_mips) 0x467F else 0x541B;
pub const IOCINQ = FIONREAD;
pub const IOCLINUX = 0x541C;
pub const IOCCONS = 0x541D;
pub const IOCGSERIAL = 0x541E;
pub const IOCSSERIAL = 0x541F;
pub const IOCPKT = 0x5420;
pub const FIONBIO = 0x5421;
pub const IOCNOTTY = 0x5422;
pub const IOCSETD = 0x5423;
pub const IOCGETD = 0x5424;
pub const CSBRKP = 0x5425;
pub const IOCSBRK = 0x5427;
pub const IOCCBRK = 0x5428;
pub const IOCGSID = 0x5429;
pub const IOCGRS485 = 0x542E;
pub const IOCSRS485 = 0x542F;
pub const IOCGPTN = IOCTL.IOR('T', 0x30, c_uint);
pub const IOCSPTLCK = IOCTL.IOW('T', 0x31, c_int);
pub const IOCGDEV = IOCTL.IOR('T', 0x32, c_uint);
pub const CGETX = 0x5432;
pub const CSETX = 0x5433;
pub const CSETXF = 0x5434;
pub const CSETXW = 0x5435;
pub const IOCSIG = IOCTL.IOW('T', 0x36, c_int);
pub const IOCVHANGUP = 0x5437;
pub const IOCGPKT = IOCTL.IOR('T', 0x38, c_int);
pub const IOCGPTLCK = IOCTL.IOR('T', 0x39, c_int);
pub const IOCGEXCL = IOCTL.IOR('T', 0x40, c_int);
};
pub const EPOLL = struct {
pub const CLOEXEC = O.CLOEXEC;
pub const CTL_ADD = 1;
pub const CTL_DEL = 2;
pub const CTL_MOD = 3;
pub const IN = 0x001;
pub const PRI = 0x002;
pub const OUT = 0x004;
pub const RDNORM = 0x040;
pub const RDBAND = 0x080;
pub const WRNORM = if (is_mips) 0x004 else 0x100;
pub const WRBAND = if (is_mips) 0x100 else 0x200;
pub const MSG = 0x400;
pub const ERR = 0x008;
pub const HUP = 0x010;
pub const RDHUP = 0x2000;
pub const EXCLUSIVE = (@as(u32, 1) << 28);
pub const WAKEUP = (@as(u32, 1) << 29);
pub const ONESHOT = (@as(u32, 1) << 30);
pub const ET = (@as(u32, 1) << 31);
};
pub const CLOCK = struct {
pub const REALTIME = 0;
pub const MONOTONIC = 1;
pub const PROCESS_CPUTIME_ID = 2;
pub const THREAD_CPUTIME_ID = 3;
pub const MONOTONIC_RAW = 4;
pub const REALTIME_COARSE = 5;
pub const MONOTONIC_COARSE = 6;
pub const BOOTTIME = 7;
pub const REALTIME_ALARM = 8;
pub const BOOTTIME_ALARM = 9;
pub const SGI_CYCLE = 10;
pub const TAI = 11;
};
pub const CSIGNAL = 0x000000ff;
pub const CLONE = struct {
pub const VM = 0x00000100;
pub const FS = 0x00000200;
pub const FILES = 0x00000400;
pub const SIGHAND = 0x00000800;
pub const PIDFD = 0x00001000;
pub const PTRACE = 0x00002000;
pub const VFORK = 0x00004000;
pub const PARENT = 0x00008000;
pub const THREAD = 0x00010000;
pub const NEWNS = 0x00020000;
pub const SYSVSEM = 0x00040000;
pub const SETTLS = 0x00080000;
pub const PARENT_SETTID = 0x00100000;
pub const CHILD_CLEARTID = 0x00200000;
pub const DETACHED = 0x00400000;
pub const UNTRACED = 0x00800000;
pub const CHILD_SETTID = 0x01000000;
pub const NEWCGROUP = 0x02000000;
pub const NEWUTS = 0x04000000;
pub const NEWIPC = 0x08000000;
pub const NEWUSER = 0x10000000;
pub const NEWPID = 0x20000000;
pub const NEWNET = 0x40000000;
pub const IO = 0x80000000;
// Flags for the clone3() syscall.
/// Clear any signal handler and reset to SIG_DFL.
pub const CLEAR_SIGHAND = 0x100000000;
/// Clone into a specific cgroup given the right permissions.
pub const INTO_CGROUP = 0x200000000;
// cloning flags intersect with CSIGNAL so can be used with unshare and clone3 syscalls only.
/// New time namespace
pub const NEWTIME = 0x00000080;
};
pub const EFD = struct {
pub const SEMAPHORE = 1;
pub const CLOEXEC = O.CLOEXEC;
pub const NONBLOCK = O.NONBLOCK;
};
pub const MS = struct {
pub const RDONLY = 1;
pub const NOSUID = 2;
pub const NODEV = 4;
pub const NOEXEC = 8;
pub const SYNCHRONOUS = 16;
pub const REMOUNT = 32;
pub const MANDLOCK = 64;
pub const DIRSYNC = 128;
pub const NOATIME = 1024;
pub const NODIRATIME = 2048;
pub const BIND = 4096;
pub const MOVE = 8192;
pub const REC = 16384;
pub const SILENT = 32768;
pub const POSIXACL = (1 << 16);
pub const UNBINDABLE = (1 << 17);
pub const PRIVATE = (1 << 18);
pub const SLAVE = (1 << 19);
pub const SHARED = (1 << 20);
pub const RELATIME = (1 << 21);
pub const KERNMOUNT = (1 << 22);
pub const I_VERSION = (1 << 23);
pub const STRICTATIME = (1 << 24);
pub const LAZYTIME = (1 << 25);
pub const NOREMOTELOCK = (1 << 27);
pub const NOSEC = (1 << 28);
pub const BORN = (1 << 29);
pub const ACTIVE = (1 << 30);
pub const NOUSER = (1 << 31);
pub const RMT_MASK = (RDONLY | SYNCHRONOUS | MANDLOCK | I_VERSION | LAZYTIME);
pub const MGC_VAL = 0xc0ed0000;
pub const MGC_MSK = 0xffff0000;
};
pub const MNT = struct {
pub const FORCE = 1;
pub const DETACH = 2;
pub const EXPIRE = 4;
};
pub const UMOUNT_NOFOLLOW = 8;
pub const IN = struct {
pub const CLOEXEC = O.CLOEXEC;
pub const NONBLOCK = O.NONBLOCK;
pub const ACCESS = 0x00000001;
pub const MODIFY = 0x00000002;
pub const ATTRIB = 0x00000004;
pub const CLOSE_WRITE = 0x00000008;
pub const CLOSE_NOWRITE = 0x00000010;
pub const CLOSE = CLOSE_WRITE | CLOSE_NOWRITE;
pub const OPEN = 0x00000020;
pub const MOVED_FROM = 0x00000040;
pub const MOVED_TO = 0x00000080;
pub const MOVE = MOVED_FROM | MOVED_TO;
pub const CREATE = 0x00000100;
pub const DELETE = 0x00000200;
pub const DELETE_SELF = 0x00000400;
pub const MOVE_SELF = 0x00000800;
pub const ALL_EVENTS = 0x00000fff;
pub const UNMOUNT = 0x00002000;
pub const Q_OVERFLOW = 0x00004000;
pub const IGNORED = 0x00008000;
pub const ONLYDIR = 0x01000000;
pub const DONT_FOLLOW = 0x02000000;
pub const EXCL_UNLINK = 0x04000000;
pub const MASK_ADD = 0x20000000;
pub const ISDIR = 0x40000000;
pub const ONESHOT = 0x80000000;
};
pub const S = struct {
pub const IFMT = 0o170000;
pub const IFDIR = 0o040000;
pub const IFCHR = 0o020000;
pub const IFBLK = 0o060000;
pub const IFREG = 0o100000;
pub const IFIFO = 0o010000;
pub const IFLNK = 0o120000;
pub const IFSOCK = 0o140000;
pub const ISUID = 0o4000;
pub const ISGID = 0o2000;
pub const ISVTX = 0o1000;
pub const IRUSR = 0o400;
pub const IWUSR = 0o200;
pub const IXUSR = 0o100;
pub const IRWXU = 0o700;
pub const IRGRP = 0o040;
pub const IWGRP = 0o020;
pub const IXGRP = 0o010;
pub const IRWXG = 0o070;
pub const IROTH = 0o004;
pub const IWOTH = 0o002;
pub const IXOTH = 0o001;
pub const IRWXO = 0o007;
pub fn ISREG(m: u32) bool {
return m & IFMT == IFREG;
}
pub fn ISDIR(m: u32) bool {
return m & IFMT == IFDIR;
}
pub fn ISCHR(m: u32) bool {
return m & IFMT == IFCHR;
}
pub fn ISBLK(m: u32) bool {
return m & IFMT == IFBLK;
}
pub fn ISFIFO(m: u32) bool {
return m & IFMT == IFIFO;
}
pub fn ISLNK(m: u32) bool {
return m & IFMT == IFLNK;
}
pub fn ISSOCK(m: u32) bool {
return m & IFMT == IFSOCK;
}
};
pub const UTIME = struct {
pub const NOW = 0x3fffffff;
pub const OMIT = 0x3ffffffe;
};
pub const TFD = struct {
pub const NONBLOCK = O.NONBLOCK;
pub const CLOEXEC = O.CLOEXEC;
pub const TIMER_ABSTIME = 1;
pub const TIMER_CANCEL_ON_SET = (1 << 1);
};
pub const winsize = extern struct {
ws_row: u16,
ws_col: u16,
ws_xpixel: u16,
ws_ypixel: u16,
};
/// NSIG is the total number of signals defined.
/// As signal numbers are sequential, NSIG is one greater than the largest defined signal number.
pub const NSIG = if (is_mips) 128 else 65;
pub const sigset_t = [1024 / 32]u32;
pub const all_mask: sigset_t = [_]u32{0xffffffff} ** sigset_t.len;
pub const app_mask: sigset_t = [2]u32{ 0xfffffffc, 0x7fffffff } ++ [_]u32{0xffffffff} ** 30;
pub const k_sigaction = switch (native_arch) {
.mips, .mipsel => extern struct {
flags: c_uint,
handler: ?fn (c_int) callconv(.C) void,
mask: [4]c_ulong,
restorer: fn () callconv(.C) void,
},
.mips64, .mips64el => extern struct {
flags: c_uint,
handler: ?fn (c_int) callconv(.C) void,
mask: [2]c_ulong,
restorer: fn () callconv(.C) void,
},
else => extern struct {
handler: ?fn (c_int) callconv(.C) void,
flags: c_ulong,
restorer: fn () callconv(.C) void,
mask: [2]c_uint,
},
};
/// Renamed from `sigaction` to `Sigaction` to avoid conflict with the syscall.
pub const Sigaction = extern struct {
pub const handler_fn = fn (c_int) callconv(.C) void;
pub const sigaction_fn = fn (c_int, *const siginfo_t, ?*const anyopaque) callconv(.C) void;
handler: extern union {
handler: ?handler_fn,
sigaction: ?sigaction_fn,
},
mask: sigset_t,
flags: c_uint,
restorer: ?fn () callconv(.C) void = null,
};
pub const empty_sigset = [_]u32{0} ** @typeInfo(sigset_t).Array.len;
pub const SFD = struct {
pub const CLOEXEC = O.CLOEXEC;
pub const NONBLOCK = O.NONBLOCK;
};
pub const signalfd_siginfo = extern struct {
signo: u32,
errno: i32,
code: i32,
pid: u32,
uid: uid_t,
fd: i32,
tid: u32,
band: u32,
overrun: u32,
trapno: u32,
status: i32,
int: i32,
ptr: u64,
utime: u64,
stime: u64,
addr: u64,
addr_lsb: u16,
__pad2: u16,
syscall: i32,
call_addr: u64,
native_arch: u32,
__pad: [28]u8,
};
pub const in_port_t = u16;
pub const sa_family_t = u16;
pub const socklen_t = u32;
pub const sockaddr = extern struct {
family: sa_family_t,
data: [14]u8,
pub const SS_MAXSIZE = 128;
pub const storage = std.x.os.Socket.Address.Native.Storage;
/// IPv4 socket address
pub const in = extern struct {
family: sa_family_t = AF.INET,
port: in_port_t,
addr: u32,
zero: [8]u8 = [8]u8{ 0, 0, 0, 0, 0, 0, 0, 0 },
};
/// IPv6 socket address
pub const in6 = extern struct {
family: sa_family_t = AF.INET6,
port: in_port_t,
flowinfo: u32,
addr: [16]u8,
scope_id: u32,
};
/// UNIX domain socket address
pub const un = extern struct {
family: sa_family_t = AF.UNIX,
path: [108]u8,
};
/// Netlink socket address
pub const nl = extern struct {
family: sa_family_t = AF.NETLINK,
__pad1: c_ushort = 0,
/// port ID
pid: u32,
/// multicast groups mask
groups: u32,
};
pub const xdp = extern struct {
family: u16 = AF.XDP,
flags: u16,
ifindex: u32,
queue_id: u32,
shared_umem_fd: u32,
};
};
pub const mmsghdr = extern struct {
msg_hdr: msghdr,
msg_len: u32,
};
pub const mmsghdr_const = extern struct {
msg_hdr: msghdr_const,
msg_len: u32,
};
pub const epoll_data = extern union {
ptr: usize,
fd: i32,
@"u32": u32,
@"u64": u64,
};
// On x86_64 the structure is packed so that it matches the definition of its
// 32bit counterpart
pub const epoll_event = switch (native_arch) {
.x86_64 => packed struct {
events: u32,
data: epoll_data,
},
else => extern struct {
events: u32,
data: epoll_data,
},
};
pub const VFS_CAP_REVISION_MASK = 0xFF000000;
pub const VFS_CAP_REVISION_SHIFT = 24;
pub const VFS_CAP_FLAGS_MASK = ~VFS_CAP_REVISION_MASK;
pub const VFS_CAP_FLAGS_EFFECTIVE = 0x000001;
pub const VFS_CAP_REVISION_1 = 0x01000000;
pub const VFS_CAP_U32_1 = 1;
pub const XATTR_CAPS_SZ_1 = @sizeOf(u32) * (1 + 2 * VFS_CAP_U32_1);
pub const VFS_CAP_REVISION_2 = 0x02000000;
pub const VFS_CAP_U32_2 = 2;
pub const XATTR_CAPS_SZ_2 = @sizeOf(u32) * (1 + 2 * VFS_CAP_U32_2);
pub const XATTR_CAPS_SZ = XATTR_CAPS_SZ_2;
pub const VFS_CAP_U32 = VFS_CAP_U32_2;
pub const VFS_CAP_REVISION = VFS_CAP_REVISION_2;
pub const vfs_cap_data = extern struct {
//all of these are mandated as little endian
//when on disk.
const Data = struct {
permitted: u32,
inheritable: u32,
};
magic_etc: u32,
data: [VFS_CAP_U32]Data,
};
pub const CAP = struct {
pub const CHOWN = 0;
pub const DAC_OVERRIDE = 1;
pub const DAC_READ_SEARCH = 2;
pub const FOWNER = 3;
pub const FSETID = 4;
pub const KILL = 5;
pub const SETGID = 6;
pub const SETUID = 7;
pub const SETPCAP = 8;
pub const LINUX_IMMUTABLE = 9;
pub const NET_BIND_SERVICE = 10;
pub const NET_BROADCAST = 11;
pub const NET_ADMIN = 12;
pub const NET_RAW = 13;
pub const IPC_LOCK = 14;
pub const IPC_OWNER = 15;
pub const SYS_MODULE = 16;
pub const SYS_RAWIO = 17;
pub const SYS_CHROOT = 18;
pub const SYS_PTRACE = 19;
pub const SYS_PACCT = 20;
pub const SYS_ADMIN = 21;
pub const SYS_BOOT = 22;
pub const SYS_NICE = 23;
pub const SYS_RESOURCE = 24;
pub const SYS_TIME = 25;
pub const SYS_TTY_CONFIG = 26;
pub const MKNOD = 27;
pub const LEASE = 28;
pub const AUDIT_WRITE = 29;
pub const AUDIT_CONTROL = 30;
pub const SETFCAP = 31;
pub const MAC_OVERRIDE = 32;
pub const MAC_ADMIN = 33;
pub const SYSLOG = 34;
pub const WAKE_ALARM = 35;
pub const BLOCK_SUSPEND = 36;
pub const AUDIT_READ = 37;
pub const LAST_CAP = AUDIT_READ;
pub fn valid(x: u8) bool {
return x >= 0 and x <= LAST_CAP;
}
pub fn TO_MASK(cap: u8) u32 {
return @as(u32, 1) << @intCast(u5, cap & 31);
}
pub fn TO_INDEX(cap: u8) u8 {
return cap >> 5;
}
};
pub const cap_t = extern struct {
hdrp: *cap_user_header_t,
datap: *cap_user_data_t,
};
pub const cap_user_header_t = extern struct {
version: u32,
pid: usize,
};
pub const cap_user_data_t = extern struct {
effective: u32,
permitted: u32,
inheritable: u32,
};
pub const inotify_event = extern struct {
wd: i32,
mask: u32,
cookie: u32,
len: u32,
//name: [?]u8,
};
pub const dirent64 = extern struct {
d_ino: u64,
d_off: u64,
d_reclen: u16,
d_type: u8,
d_name: u8, // field address is the address of first byte of name https://github.com/ziglang/zig/issues/173
pub fn reclen(self: dirent64) u16 {
return self.d_reclen;
}
};
pub const dl_phdr_info = extern struct {
dlpi_addr: usize,
dlpi_name: ?[*:0]const u8,
dlpi_phdr: [*]std.elf.Phdr,
dlpi_phnum: u16,
};
pub const CPU_SETSIZE = 128;
pub const cpu_set_t = [CPU_SETSIZE / @sizeOf(usize)]usize;
pub const cpu_count_t = std.meta.Int(.unsigned, std.math.log2(CPU_SETSIZE * 8));
pub fn CPU_COUNT(set: cpu_set_t) cpu_count_t {
var sum: cpu_count_t = 0;
for (set) |x| {
sum += @popCount(usize, x);
}
return sum;
}
pub const MINSIGSTKSZ = switch (native_arch) {
.i386, .x86_64, .arm, .mipsel => 2048,
.aarch64 => 5120,
else => @compileError("MINSIGSTKSZ not defined for this architecture"),
};
pub const SIGSTKSZ = switch (native_arch) {
.i386, .x86_64, .arm, .mipsel => 8192,
.aarch64 => 16384,
else => @compileError("SIGSTKSZ not defined for this architecture"),
};
pub const SS_ONSTACK = 1;
pub const SS_DISABLE = 2;
pub const SS_AUTODISARM = 1 << 31;
pub const stack_t = if (is_mips)
// IRIX compatible stack_t
extern struct {
sp: [*]u8,
size: usize,
flags: i32,
}
else
extern struct {
sp: [*]u8,
flags: i32,
size: usize,
};
pub const sigval = extern union {
int: i32,
ptr: *anyopaque,
};
const siginfo_fields_union = extern union {
pad: [128 - 2 * @sizeOf(c_int) - @sizeOf(c_long)]u8,
common: extern struct {
first: extern union {
piduid: extern struct {
pid: pid_t,
uid: uid_t,
},
timer: extern struct {
timerid: i32,
overrun: i32,
},
},
second: extern union {
value: sigval,
sigchld: extern struct {
status: i32,
utime: clock_t,
stime: clock_t,
},
},
},
sigfault: extern struct {
addr: *anyopaque,
addr_lsb: i16,
first: extern union {
addr_bnd: extern struct {
lower: *anyopaque,
upper: *anyopaque,
},
pkey: u32,
},
},
sigpoll: extern struct {
band: isize,
fd: i32,
},
sigsys: extern struct {
call_addr: *anyopaque,
syscall: i32,
native_arch: u32,
},
};
pub const siginfo_t = if (is_mips)
extern struct {
signo: i32,
code: i32,
errno: i32,
fields: siginfo_fields_union,
}
else
extern struct {
signo: i32,
errno: i32,
code: i32,
fields: siginfo_fields_union,
};
pub const io_uring_params = extern struct {
sq_entries: u32,
cq_entries: u32,
flags: u32,
sq_thread_cpu: u32,
sq_thread_idle: u32,
features: u32,
wq_fd: u32,
resv: [3]u32,
sq_off: io_sqring_offsets,
cq_off: io_cqring_offsets,
};
// io_uring_params.features flags
pub const IORING_FEAT_SINGLE_MMAP = 1 << 0;
pub const IORING_FEAT_NODROP = 1 << 1;
pub const IORING_FEAT_SUBMIT_STABLE = 1 << 2;
pub const IORING_FEAT_RW_CUR_POS = 1 << 3;
pub const IORING_FEAT_CUR_PERSONALITY = 1 << 4;
pub const IORING_FEAT_FAST_POLL = 1 << 5;
pub const IORING_FEAT_POLL_32BITS = 1 << 6;
// io_uring_params.flags
/// io_context is polled
pub const IORING_SETUP_IOPOLL = 1 << 0;
/// SQ poll thread
pub const IORING_SETUP_SQPOLL = 1 << 1;
/// sq_thread_cpu is valid
pub const IORING_SETUP_SQ_AFF = 1 << 2;
/// app defines CQ size
pub const IORING_SETUP_CQSIZE = 1 << 3;
/// clamp SQ/CQ ring sizes
pub const IORING_SETUP_CLAMP = 1 << 4;
/// attach to existing wq
pub const IORING_SETUP_ATTACH_WQ = 1 << 5;
/// start with ring disabled
pub const IORING_SETUP_R_DISABLED = 1 << 6;
pub const io_sqring_offsets = extern struct {
/// offset of ring head
head: u32,
/// offset of ring tail
tail: u32,
/// ring mask value
ring_mask: u32,
/// entries in ring
ring_entries: u32,
/// ring flags
flags: u32,
/// number of sqes not submitted
dropped: u32,
/// sqe index array
array: u32,
resv1: u32,
resv2: u64,
};
// io_sqring_offsets.flags
/// needs io_uring_enter wakeup
pub const IORING_SQ_NEED_WAKEUP = 1 << 0;
/// kernel has cqes waiting beyond the cq ring
pub const IORING_SQ_CQ_OVERFLOW = 1 << 1;
pub const io_cqring_offsets = extern struct {
head: u32,
tail: u32,
ring_mask: u32,
ring_entries: u32,
overflow: u32,
cqes: u32,
resv: [2]u64,
};
pub const io_uring_sqe = extern struct {
opcode: IORING_OP,
flags: u8,
ioprio: u16,
fd: i32,
off: u64,
addr: u64,
len: u32,
rw_flags: u32,
user_data: u64,
buf_index: u16,
personality: u16,
splice_fd_in: i32,
__pad2: [2]u64,
};
pub const IOSQE_BIT = enum(u8) {
FIXED_FILE,
IO_DRAIN,
IO_LINK,
IO_HARDLINK,
ASYNC,
BUFFER_SELECT,
_,
};
// io_uring_sqe.flags
/// use fixed fileset
pub const IOSQE_FIXED_FILE = 1 << @enumToInt(IOSQE_BIT.FIXED_FILE);
/// issue after inflight IO
pub const IOSQE_IO_DRAIN = 1 << @enumToInt(IOSQE_BIT.IO_DRAIN);
/// links next sqe
pub const IOSQE_IO_LINK = 1 << @enumToInt(IOSQE_BIT.IO_LINK);
/// like LINK, but stronger
pub const IOSQE_IO_HARDLINK = 1 << @enumToInt(IOSQE_BIT.IO_HARDLINK);
/// always go async
pub const IOSQE_ASYNC = 1 << @enumToInt(IOSQE_BIT.ASYNC);
/// select buffer from buf_group
pub const IOSQE_BUFFER_SELECT = 1 << @enumToInt(IOSQE_BIT.BUFFER_SELECT);
pub const IORING_OP = enum(u8) {
NOP,
READV,
WRITEV,
FSYNC,
READ_FIXED,
WRITE_FIXED,
POLL_ADD,
POLL_REMOVE,
SYNC_FILE_RANGE,
SENDMSG,
RECVMSG,
TIMEOUT,
TIMEOUT_REMOVE,
ACCEPT,
ASYNC_CANCEL,
LINK_TIMEOUT,
CONNECT,
FALLOCATE,
OPENAT,
CLOSE,
FILES_UPDATE,
STATX,
READ,
WRITE,
FADVISE,
MADVISE,
SEND,
RECV,
OPENAT2,
EPOLL_CTL,
SPLICE,
PROVIDE_BUFFERS,
REMOVE_BUFFERS,
TEE,
SHUTDOWN,
RENAMEAT,
UNLINKAT,
MKDIRAT,
SYMLINKAT,
LINKAT,
_,
};
// io_uring_sqe.fsync_flags
pub const IORING_FSYNC_DATASYNC = 1 << 0;
// io_uring_sqe.timeout_flags
pub const IORING_TIMEOUT_ABS = 1 << 0;
// IO completion data structure (Completion Queue Entry)
pub const io_uring_cqe = extern struct {
/// io_uring_sqe.data submission passed back
user_data: u64,
/// result code for this event
res: i32,
flags: u32,
pub fn err(self: io_uring_cqe) E {
if (self.res > -4096 and self.res < 0) {
return @intToEnum(E, -self.res);
}
return .SUCCESS;
}
};
// io_uring_cqe.flags
/// If set, the upper 16 bits are the buffer ID
pub const IORING_CQE_F_BUFFER = 1 << 0;
pub const IORING_OFF_SQ_RING = 0;
pub const IORING_OFF_CQ_RING = 0x8000000;
pub const IORING_OFF_SQES = 0x10000000;
// io_uring_enter flags
pub const IORING_ENTER_GETEVENTS = 1 << 0;
pub const IORING_ENTER_SQ_WAKEUP = 1 << 1;
// io_uring_register opcodes and arguments
pub const IORING_REGISTER = enum(u8) {
REGISTER_BUFFERS,
UNREGISTER_BUFFERS,
REGISTER_FILES,
UNREGISTER_FILES,
REGISTER_EVENTFD,
UNREGISTER_EVENTFD,
REGISTER_FILES_UPDATE,
REGISTER_EVENTFD_ASYNC,
REGISTER_PROBE,
REGISTER_PERSONALITY,
UNREGISTER_PERSONALITY,
REGISTER_RESTRICTIONS,
REGISTER_ENABLE_RINGS,
_,
};
pub const io_uring_files_update = extern struct {
offset: u32,
resv: u32,
fds: u64,
};
pub const IO_URING_OP_SUPPORTED = 1 << 0;
pub const io_uring_probe_op = extern struct {
op: IORING_OP,
resv: u8,
/// IO_URING_OP_* flags
flags: u16,
resv2: u32,
};
pub const io_uring_probe = extern struct {
/// last opcode supported
last_op: IORING_OP,
/// Number of io_uring_probe_op following
ops_len: u8,
resv: u16,
resv2: u32[3],
// Followed by up to `ops_len` io_uring_probe_op structures
};
pub const io_uring_restriction = extern struct {
opcode: u16,
arg: extern union {
/// IORING_RESTRICTION_REGISTER_OP
register_op: IORING_REGISTER,
/// IORING_RESTRICTION_SQE_OP
sqe_op: IORING_OP,
/// IORING_RESTRICTION_SQE_FLAGS_*
sqe_flags: u8,
},
resv: u8,
resv2: u32[3],
};
/// io_uring_restriction->opcode values
pub const IORING_RESTRICTION = enum(u8) {
/// Allow an io_uring_register(2) opcode
REGISTER_OP = 0,
/// Allow an sqe opcode
SQE_OP = 1,
/// Allow sqe flags
SQE_FLAGS_ALLOWED = 2,
/// Require sqe flags (these flags must be set on each submission)
SQE_FLAGS_REQUIRED = 3,
_,
};
pub const utsname = extern struct {
sysname: [64:0]u8,
nodename: [64:0]u8,
release: [64:0]u8,
version: [64:0]u8,
machine: [64:0]u8,
domainname: [64:0]u8,
};
pub const HOST_NAME_MAX = 64;
pub const STATX_TYPE = 0x0001;
pub const STATX_MODE = 0x0002;
pub const STATX_NLINK = 0x0004;
pub const STATX_UID = 0x0008;
pub const STATX_GID = 0x0010;
pub const STATX_ATIME = 0x0020;
pub const STATX_MTIME = 0x0040;
pub const STATX_CTIME = 0x0080;
pub const STATX_INO = 0x0100;
pub const STATX_SIZE = 0x0200;
pub const STATX_BLOCKS = 0x0400;
pub const STATX_BASIC_STATS = 0x07ff;
pub const STATX_BTIME = 0x0800;
pub const STATX_ATTR_COMPRESSED = 0x0004;
pub const STATX_ATTR_IMMUTABLE = 0x0010;
pub const STATX_ATTR_APPEND = 0x0020;
pub const STATX_ATTR_NODUMP = 0x0040;
pub const STATX_ATTR_ENCRYPTED = 0x0800;
pub const STATX_ATTR_AUTOMOUNT = 0x1000;
pub const statx_timestamp = extern struct {
tv_sec: i64,
tv_nsec: u32,
__pad1: u32,
};
/// Renamed to `Statx` to not conflict with the `statx` function.
pub const Statx = extern struct {
/// Mask of bits indicating filled fields
mask: u32,
/// Block size for filesystem I/O
blksize: u32,
/// Extra file attribute indicators
attributes: u64,
/// Number of hard links
nlink: u32,
/// User ID of owner
uid: uid_t,
/// Group ID of owner
gid: gid_t,
/// File type and mode
mode: u16,
__pad1: u16,
/// Inode number
ino: u64,
/// Total size in bytes
size: u64,
/// Number of 512B blocks allocated
blocks: u64,
/// Mask to show what's supported in `attributes`.
attributes_mask: u64,
/// Last access file timestamp
atime: statx_timestamp,
/// Creation file timestamp
btime: statx_timestamp,
/// Last status change file timestamp
ctime: statx_timestamp,
/// Last modification file timestamp
mtime: statx_timestamp,
/// Major ID, if this file represents a device.
rdev_major: u32,
/// Minor ID, if this file represents a device.
rdev_minor: u32,
/// Major ID of the device containing the filesystem where this file resides.
dev_major: u32,
/// Minor ID of the device containing the filesystem where this file resides.
dev_minor: u32,
__pad2: [14]u64,
};
pub const addrinfo = extern struct {
flags: i32,
family: i32,
socktype: i32,
protocol: i32,
addrlen: socklen_t,
addr: ?*sockaddr,
canonname: ?[*:0]u8,
next: ?*addrinfo,
};
pub const IPPORT_RESERVED = 1024;
pub const IPPROTO = struct {
pub const IP = 0;
pub const HOPOPTS = 0;
pub const ICMP = 1;
pub const IGMP = 2;
pub const IPIP = 4;
pub const TCP = 6;
pub const EGP = 8;
pub const PUP = 12;
pub const UDP = 17;
pub const IDP = 22;
pub const TP = 29;
pub const DCCP = 33;
pub const IPV6 = 41;
pub const ROUTING = 43;
pub const FRAGMENT = 44;
pub const RSVP = 46;
pub const GRE = 47;
pub const ESP = 50;
pub const AH = 51;
pub const ICMPV6 = 58;
pub const NONE = 59;
pub const DSTOPTS = 60;
pub const MTP = 92;
pub const BEETPH = 94;
pub const ENCAP = 98;
pub const PIM = 103;
pub const COMP = 108;
pub const SCTP = 132;
pub const MH = 135;
pub const UDPLITE = 136;
pub const MPLS = 137;
pub const RAW = 255;
pub const MAX = 256;
};
pub const RR = struct {
pub const A = 1;
pub const CNAME = 5;
pub const AAAA = 28;
};
pub const tcp_repair_opt = extern struct {
opt_code: u32,
opt_val: u32,
};
pub const tcp_repair_window = extern struct {
snd_wl1: u32,
snd_wnd: u32,
max_window: u32,
rcv_wnd: u32,
rcv_wup: u32,
};
pub const TcpRepairOption = enum {
TCP_NO_QUEUE,
TCP_RECV_QUEUE,
TCP_SEND_QUEUE,
TCP_QUEUES_NR,
};
/// why fastopen failed from client perspective
pub const tcp_fastopen_client_fail = enum {
/// catch-all
TFO_STATUS_UNSPEC,
/// if not in TFO_CLIENT_NO_COOKIE mode
TFO_COOKIE_UNAVAILABLE,
/// SYN-ACK did not ack SYN data
TFO_DATA_NOT_ACKED,
/// SYN-ACK did not ack SYN data after timeout
TFO_SYN_RETRANSMITTED,
};
/// for TCP_INFO socket option
pub const TCPI_OPT_TIMESTAMPS = 1;
pub const TCPI_OPT_SACK = 2;
pub const TCPI_OPT_WSCALE = 4;
/// ECN was negociated at TCP session init
pub const TCPI_OPT_ECN = 8;
/// we received at least one packet with ECT
pub const TCPI_OPT_ECN_SEEN = 16;
/// SYN-ACK acked data in SYN sent or rcvd
pub const TCPI_OPT_SYN_DATA = 32;
pub const nfds_t = usize;
pub const pollfd = extern struct {
fd: fd_t,
events: i16,
revents: i16,
};
pub const POLL = struct {
pub const IN = 0x001;
pub const PRI = 0x002;
pub const OUT = 0x004;
pub const ERR = 0x008;
pub const HUP = 0x010;
pub const NVAL = 0x020;
pub const RDNORM = 0x040;
pub const RDBAND = 0x080;
};
pub const MFD_CLOEXEC = 0x0001;
pub const MFD_ALLOW_SEALING = 0x0002;
pub const MFD_HUGETLB = 0x0004;
pub const MFD_ALL_FLAGS = MFD_CLOEXEC | MFD_ALLOW_SEALING | MFD_HUGETLB;
pub const HUGETLB_FLAG_ENCODE_SHIFT = 26;
pub const HUGETLB_FLAG_ENCODE_MASK = 0x3f;
pub const HUGETLB_FLAG_ENCODE_64KB = 16 << HUGETLB_FLAG_ENCODE_SHIFT;
pub const HUGETLB_FLAG_ENCODE_512KB = 19 << HUGETLB_FLAG_ENCODE_SHIFT;
pub const HUGETLB_FLAG_ENCODE_1MB = 20 << HUGETLB_FLAG_ENCODE_SHIFT;
pub const HUGETLB_FLAG_ENCODE_2MB = 21 << HUGETLB_FLAG_ENCODE_SHIFT;
pub const HUGETLB_FLAG_ENCODE_8MB = 23 << HUGETLB_FLAG_ENCODE_SHIFT;
pub const HUGETLB_FLAG_ENCODE_16MB = 24 << HUGETLB_FLAG_ENCODE_SHIFT;
pub const HUGETLB_FLAG_ENCODE_32MB = 25 << HUGETLB_FLAG_ENCODE_SHIFT;
pub const HUGETLB_FLAG_ENCODE_256MB = 28 << HUGETLB_FLAG_ENCODE_SHIFT;
pub const HUGETLB_FLAG_ENCODE_512MB = 29 << HUGETLB_FLAG_ENCODE_SHIFT;
pub const HUGETLB_FLAG_ENCODE_1GB = 30 << HUGETLB_FLAG_ENCODE_SHIFT;
pub const HUGETLB_FLAG_ENCODE_2GB = 31 << HUGETLB_FLAG_ENCODE_SHIFT;
pub const HUGETLB_FLAG_ENCODE_16GB = 34 << HUGETLB_FLAG_ENCODE_SHIFT;
pub const MFD_HUGE_SHIFT = HUGETLB_FLAG_ENCODE_SHIFT;
pub const MFD_HUGE_MASK = HUGETLB_FLAG_ENCODE_MASK;
pub const MFD_HUGE_64KB = HUGETLB_FLAG_ENCODE_64KB;
pub const MFD_HUGE_512KB = HUGETLB_FLAG_ENCODE_512KB;
pub const MFD_HUGE_1MB = HUGETLB_FLAG_ENCODE_1MB;
pub const MFD_HUGE_2MB = HUGETLB_FLAG_ENCODE_2MB;
pub const MFD_HUGE_8MB = HUGETLB_FLAG_ENCODE_8MB;
pub const MFD_HUGE_16MB = HUGETLB_FLAG_ENCODE_16MB;
pub const MFD_HUGE_32MB = HUGETLB_FLAG_ENCODE_32MB;
pub const MFD_HUGE_256MB = HUGETLB_FLAG_ENCODE_256MB;
pub const MFD_HUGE_512MB = HUGETLB_FLAG_ENCODE_512MB;
pub const MFD_HUGE_1GB = HUGETLB_FLAG_ENCODE_1GB;
pub const MFD_HUGE_2GB = HUGETLB_FLAG_ENCODE_2GB;
pub const MFD_HUGE_16GB = HUGETLB_FLAG_ENCODE_16GB;
pub const rusage = extern struct {
utime: timeval,
stime: timeval,
maxrss: isize,
ixrss: isize,
idrss: isize,
isrss: isize,
minflt: isize,
majflt: isize,
nswap: isize,
inblock: isize,
oublock: isize,
msgsnd: isize,
msgrcv: isize,
nsignals: isize,
nvcsw: isize,
nivcsw: isize,
__reserved: [16]isize = [1]isize{0} ** 16,
pub const SELF = 0;
pub const CHILDREN = -1;
pub const THREAD = 1;
};
pub const cc_t = u8;
pub const speed_t = u32;
pub const tcflag_t = u32;
pub const NCCS = 32;
pub const B0 = 0o0000000;
pub const B50 = 0o0000001;
pub const B75 = 0o0000002;
pub const B110 = 0o0000003;
pub const B134 = 0o0000004;
pub const B150 = 0o0000005;
pub const B200 = 0o0000006;
pub const B300 = 0o0000007;
pub const B600 = 0o0000010;
pub const B1200 = 0o0000011;
pub const B1800 = 0o0000012;
pub const B2400 = 0o0000013;
pub const B4800 = 0o0000014;
pub const B9600 = 0o0000015;
pub const B19200 = 0o0000016;
pub const B38400 = 0o0000017;
pub const BOTHER = 0o0010000;
pub const B57600 = 0o0010001;
pub const B115200 = 0o0010002;
pub const B230400 = 0o0010003;
pub const B460800 = 0o0010004;
pub const B500000 = 0o0010005;
pub const B576000 = 0o0010006;
pub const B921600 = 0o0010007;
pub const B1000000 = 0o0010010;
pub const B1152000 = 0o0010011;
pub const B1500000 = 0o0010012;
pub const B2000000 = 0o0010013;
pub const B2500000 = 0o0010014;
pub const B3000000 = 0o0010015;
pub const B3500000 = 0o0010016;
pub const B4000000 = 0o0010017;
pub const V = switch (native_arch) {
.powerpc, .powerpc64, .powerpc64le => struct {
pub const INTR = 0;
pub const QUIT = 1;
pub const ERASE = 2;
pub const KILL = 3;
pub const EOF = 4;
pub const MIN = 5;
pub const EOL = 6;
pub const TIME = 7;
pub const EOL2 = 8;
pub const SWTC = 9;
pub const WERASE = 10;
pub const REPRINT = 11;
pub const SUSP = 12;
pub const START = 13;
pub const STOP = 14;
pub const LNEXT = 15;
pub const DISCARD = 16;
},
.sparc, .sparcv9 => struct {
pub const INTR = 0;
pub const QUIT = 1;
pub const ERASE = 2;
pub const KILL = 3;
pub const EOF = 4;
pub const EOL = 5;
pub const EOL2 = 6;
pub const SWTC = 7;
pub const START = 8;
pub const STOP = 9;
pub const SUSP = 10;
pub const DSUSP = 11;
pub const REPRINT = 12;
pub const DISCARD = 13;
pub const WERASE = 14;
pub const LNEXT = 15;
pub const MIN = EOF;
pub const TIME = EOL;
},
.mips, .mipsel, .mips64, .mips64el => struct {
pub const INTR = 0;
pub const QUIT = 1;
pub const ERASE = 2;
pub const KILL = 3;
pub const MIN = 4;
pub const TIME = 5;
pub const EOL2 = 6;
pub const SWTC = 7;
pub const SWTCH = 7;
pub const START = 8;
pub const STOP = 9;
pub const SUSP = 10;
pub const REPRINT = 12;
pub const DISCARD = 13;
pub const WERASE = 14;
pub const LNEXT = 15;
pub const EOF = 16;
pub const EOL = 17;
},
else => struct {
pub const INTR = 0;
pub const QUIT = 1;
pub const ERASE = 2;
pub const KILL = 3;
pub const EOF = 4;
pub const TIME = 5;
pub const MIN = 6;
pub const SWTC = 7;
pub const START = 8;
pub const STOP = 9;
pub const SUSP = 10;
pub const EOL = 11;
pub const REPRINT = 12;
pub const DISCARD = 13;
pub const WERASE = 14;
pub const LNEXT = 15;
pub const EOL2 = 16;
},
};
pub const IGNBRK: tcflag_t = 1;
pub const BRKINT: tcflag_t = 2;
pub const IGNPAR: tcflag_t = 4;
pub const PARMRK: tcflag_t = 8;
pub const INPCK: tcflag_t = 16;
pub const ISTRIP: tcflag_t = 32;
pub const INLCR: tcflag_t = 64;
pub const IGNCR: tcflag_t = 128;
pub const ICRNL: tcflag_t = 256;
pub const IUCLC: tcflag_t = 512;
pub const IXON: tcflag_t = 1024;
pub const IXANY: tcflag_t = 2048;
pub const IXOFF: tcflag_t = 4096;
pub const IMAXBEL: tcflag_t = 8192;
pub const IUTF8: tcflag_t = 16384;
pub const OPOST: tcflag_t = 1;
pub const OLCUC: tcflag_t = 2;
pub const ONLCR: tcflag_t = 4;
pub const OCRNL: tcflag_t = 8;
pub const ONOCR: tcflag_t = 16;
pub const ONLRET: tcflag_t = 32;
pub const OFILL: tcflag_t = 64;
pub const OFDEL: tcflag_t = 128;
pub const VTDLY: tcflag_t = 16384;
pub const VT0: tcflag_t = 0;
pub const VT1: tcflag_t = 16384;
pub const CSIZE: tcflag_t = 48;
pub const CS5: tcflag_t = 0;
pub const CS6: tcflag_t = 16;
pub const CS7: tcflag_t = 32;
pub const CS8: tcflag_t = 48;
pub const CSTOPB: tcflag_t = 64;
pub const CREAD: tcflag_t = 128;
pub const PARENB: tcflag_t = 256;
pub const PARODD: tcflag_t = 512;
pub const HUPCL: tcflag_t = 1024;
pub const CLOCAL: tcflag_t = 2048;
pub const ISIG: tcflag_t = 1;
pub const ICANON: tcflag_t = 2;
pub const ECHO: tcflag_t = 8;
pub const ECHOE: tcflag_t = 16;
pub const ECHOK: tcflag_t = 32;
pub const ECHONL: tcflag_t = 64;
pub const NOFLSH: tcflag_t = 128;
pub const TOSTOP: tcflag_t = 256;
pub const IEXTEN: tcflag_t = 32768;
pub const TCSA = enum(c_uint) {
NOW,
DRAIN,
FLUSH,
_,
};
pub const termios = extern struct {
iflag: tcflag_t,
oflag: tcflag_t,
cflag: tcflag_t,
lflag: tcflag_t,
line: cc_t,
cc: [NCCS]cc_t,
ispeed: speed_t,
ospeed: speed_t,
};
pub const SIOCGIFINDEX = 0x8933;
pub const IFNAMESIZE = 16;
pub const ifmap = extern struct {
mem_start: u32,
mem_end: u32,
base_addr: u16,
irq: u8,
dma: u8,
port: u8,
};
pub const ifreq = extern struct {
ifrn: extern union {
name: [IFNAMESIZE]u8,
},
ifru: extern union {
addr: sockaddr,
dstaddr: sockaddr,
broadaddr: sockaddr,
netmask: sockaddr,
hwaddr: sockaddr,
flags: i16,
ivalue: i32,
mtu: i32,
map: ifmap,
slave: [IFNAMESIZE - 1:0]u8,
newname: [IFNAMESIZE - 1:0]u8,
data: ?[*]u8,
},
};
// doc comments copied from musl
pub const rlimit_resource = if (native_arch.isMIPS() or native_arch.isSPARC())
arch_bits.rlimit_resource
else
enum(c_int) {
/// Per-process CPU limit, in seconds.
CPU,
/// Largest file that can be created, in bytes.
FSIZE,
/// Maximum size of data segment, in bytes.
DATA,
/// Maximum size of stack segment, in bytes.
STACK,
/// Largest core file that can be created, in bytes.
CORE,
/// Largest resident set size, in bytes.
/// This affects swapping; processes that are exceeding their
/// resident set size will be more likely to have physical memory
/// taken from them.
RSS,
/// Number of processes.
NPROC,
/// Number of open files.
NOFILE,
/// Locked-in-memory address space.
MEMLOCK,
/// Address space limit.
AS,
/// Maximum number of file locks.
LOCKS,
/// Maximum number of pending signals.
SIGPENDING,
/// Maximum bytes in POSIX message queues.
MSGQUEUE,
/// Maximum nice priority allowed to raise to.
/// Nice levels 19 .. -20 correspond to 0 .. 39
/// values of this resource limit.
NICE,
/// Maximum realtime priority allowed for non-priviledged
/// processes.
RTPRIO,
/// Maximum CPU time in µs that a process scheduled under a real-time
/// scheduling policy may consume without making a blocking system
/// call before being forcibly descheduled.
RTTIME,
_,
};
pub const rlim_t = u64;
pub const RLIM = struct {
/// No limit
pub const INFINITY = ~@as(rlim_t, 0);
pub const SAVED_MAX = INFINITY;
pub const SAVED_CUR = INFINITY;
};
pub const rlimit = extern struct {
/// Soft limit
cur: rlim_t,
/// Hard limit
max: rlim_t,
};
pub const MADV = struct {
pub const NORMAL = 0;
pub const RANDOM = 1;
pub const SEQUENTIAL = 2;
pub const WILLNEED = 3;
pub const DONTNEED = 4;
pub const FREE = 8;
pub const REMOVE = 9;
pub const DONTFORK = 10;
pub const DOFORK = 11;
pub const MERGEABLE = 12;
pub const UNMERGEABLE = 13;
pub const HUGEPAGE = 14;
pub const NOHUGEPAGE = 15;
pub const DONTDUMP = 16;
pub const DODUMP = 17;
pub const WIPEONFORK = 18;
pub const KEEPONFORK = 19;
pub const COLD = 20;
pub const PAGEOUT = 21;
pub const HWPOISON = 100;
pub const SOFT_OFFLINE = 101;
};
pub const POSIX_FADV = switch (native_arch) {
.s390x => if (@typeInfo(usize).Int.bits == 64) struct {
pub const NORMAL = 0;
pub const RANDOM = 1;
pub const SEQUENTIAL = 2;
pub const WILLNEED = 3;
pub const DONTNEED = 6;
pub const NOREUSE = 7;
} else struct {
pub const NORMAL = 0;
pub const RANDOM = 1;
pub const SEQUENTIAL = 2;
pub const WILLNEED = 3;
pub const DONTNEED = 4;
pub const NOREUSE = 5;
},
else => struct {
pub const NORMAL = 0;
pub const RANDOM = 1;
pub const SEQUENTIAL = 2;
pub const WILLNEED = 3;
pub const DONTNEED = 4;
pub const NOREUSE = 5;
},
};
/// The timespec struct used by the kernel.
pub const kernel_timespec = if (@sizeOf(usize) >= 8) timespec else extern struct {
tv_sec: i64,
tv_nsec: i64,
};
pub const timespec = extern struct {
tv_sec: isize,
tv_nsec: isize,
};
pub const XDP = struct {
pub const SHARED_UMEM = (1 << 0);
pub const COPY = (1 << 1);
pub const ZEROCOPY = (1 << 2);
pub const UMEM_UNALIGNED_CHUNK_FLAG = (1 << 0);
pub const USE_NEED_WAKEUP = (1 << 3);
pub const MMAP_OFFSETS = 1;
pub const RX_RING = 2;
pub const TX_RING = 3;
pub const UMEM_REG = 4;
pub const UMEM_FILL_RING = 5;
pub const UMEM_COMPLETION_RING = 6;
pub const STATISTICS = 7;
pub const OPTIONS = 8;
pub const OPTIONS_ZEROCOPY = (1 << 0);
pub const PGOFF_RX_RING = 0;
pub const PGOFF_TX_RING = 0x80000000;
pub const UMEM_PGOFF_FILL_RING = 0x100000000;
pub const UMEM_PGOFF_COMPLETION_RING = 0x180000000;
};
pub const xdp_ring_offset = extern struct {
producer: u64,
consumer: u64,
desc: u64,
flags: u64,
};
pub const xdp_mmap_offsets = extern struct {
rx: xdp_ring_offset,
tx: xdp_ring_offset,
fr: xdp_ring_offset,
cr: xdp_ring_offset,
};
pub const xdp_umem_reg = extern struct {
addr: u64,
len: u64,
chunk_size: u32,
headroom: u32,
flags: u32,
};
pub const xdp_statistics = extern struct {
rx_dropped: u64,
rx_invalid_descs: u64,
tx_invalid_descs: u64,
rx_ring_full: u64,
rx_fill_ring_empty_descs: u64,
tx_ring_empty_descs: u64,
};
pub const xdp_options = extern struct {
flags: u32,
};
pub const XSK_UNALIGNED_BUF_OFFSET_SHIFT = 48;
pub const XSK_UNALIGNED_BUF_ADDR_MASK = (1 << XSK_UNALIGNED_BUF_OFFSET_SHIFT) - 1;
pub const xdp_desc = extern struct {
addr: u64,
len: u32,
options: u32,
};
fn issecure_mask(comptime x: comptime_int) comptime_int {
return 1 << x;
}
pub const SECUREBITS_DEFAULT = 0x00000000;
pub const SECURE_NOROOT = 0;
pub const SECURE_NOROOT_LOCKED = 1;
pub const SECBIT_NOROOT = issecure_mask(SECURE_NOROOT);
pub const SECBIT_NOROOT_LOCKED = issecure_mask(SECURE_NOROOT_LOCKED);
pub const SECURE_NO_SETUID_FIXUP = 2;
pub const SECURE_NO_SETUID_FIXUP_LOCKED = 3;
pub const SECBIT_NO_SETUID_FIXUP = issecure_mask(SECURE_NO_SETUID_FIXUP);
pub const SECBIT_NO_SETUID_FIXUP_LOCKED = issecure_mask(SECURE_NO_SETUID_FIXUP_LOCKED);
pub const SECURE_KEEP_CAPS = 4;
pub const SECURE_KEEP_CAPS_LOCKED = 5;
pub const SECBIT_KEEP_CAPS = issecure_mask(SECURE_KEEP_CAPS);
pub const SECBIT_KEEP_CAPS_LOCKED = issecure_mask(SECURE_KEEP_CAPS_LOCKED);
pub const SECURE_NO_CAP_AMBIENT_RAISE = 6;
pub const SECURE_NO_CAP_AMBIENT_RAISE_LOCKED = 7;
pub const SECBIT_NO_CAP_AMBIENT_RAISE = issecure_mask(SECURE_NO_CAP_AMBIENT_RAISE);
pub const SECBIT_NO_CAP_AMBIENT_RAISE_LOCKED = issecure_mask(SECURE_NO_CAP_AMBIENT_RAISE_LOCKED);
pub const SECURE_ALL_BITS = issecure_mask(SECURE_NOROOT) |
issecure_mask(SECURE_NO_SETUID_FIXUP) |
issecure_mask(SECURE_KEEP_CAPS) |
issecure_mask(SECURE_NO_CAP_AMBIENT_RAISE);
pub const SECURE_ALL_LOCKS = SECURE_ALL_BITS << 1;
pub const PR = enum(i32) {
SET_PDEATHSIG = 1,
GET_PDEATHSIG = 2,
GET_DUMPABLE = 3,
SET_DUMPABLE = 4,
GET_UNALIGN = 5,
SET_UNALIGN = 6,
GET_KEEPCAPS = 7,
SET_KEEPCAPS = 8,
GET_FPEMU = 9,
SET_FPEMU = 10,
GET_FPEXC = 11,
SET_FPEXC = 12,
GET_TIMING = 13,
SET_TIMING = 14,
SET_NAME = 15,
GET_NAME = 16,
GET_ENDIAN = 19,
SET_ENDIAN = 20,
GET_SECCOMP = 21,
SET_SECCOMP = 22,
CAPBSET_READ = 23,
CAPBSET_DROP = 24,
GET_TSC = 25,
SET_TSC = 26,
GET_SECUREBITS = 27,
SET_SECUREBITS = 28,
SET_TIMERSLACK = 29,
GET_TIMERSLACK = 30,
TASK_PERF_EVENTS_DISABLE = 31,
TASK_PERF_EVENTS_ENABLE = 32,
MCE_KILL = 33,
MCE_KILL_GET = 34,
SET_MM = 35,
SET_PTRACER = 0x59616d61,
SET_CHILD_SUBREAPER = 36,
GET_CHILD_SUBREAPER = 37,
SET_NO_NEW_PRIVS = 38,
GET_NO_NEW_PRIVS = 39,
GET_TID_ADDRESS = 40,
SET_THP_DISABLE = 41,
GET_THP_DISABLE = 42,
MPX_ENABLE_MANAGEMENT = 43,
MPX_DISABLE_MANAGEMENT = 44,
SET_FP_MODE = 45,
GET_FP_MODE = 46,
CAP_AMBIENT = 47,
SVE_SET_VL = 50,
SVE_GET_VL = 51,
GET_SPECULATION_CTRL = 52,
SET_SPECULATION_CTRL = 53,
_,
pub const UNALIGN_NOPRINT = 1;
pub const UNALIGN_SIGBUS = 2;
pub const FPEMU_NOPRINT = 1;
pub const FPEMU_SIGFPE = 2;
pub const FP_EXC_SW_ENABLE = 0x80;
pub const FP_EXC_DIV = 0x010000;
pub const FP_EXC_OVF = 0x020000;
pub const FP_EXC_UND = 0x040000;
pub const FP_EXC_RES = 0x080000;
pub const FP_EXC_INV = 0x100000;
pub const FP_EXC_DISABLED = 0;
pub const FP_EXC_NONRECOV = 1;
pub const FP_EXC_ASYNC = 2;
pub const FP_EXC_PRECISE = 3;
pub const TIMING_STATISTICAL = 0;
pub const TIMING_TIMESTAMP = 1;
pub const ENDIAN_BIG = 0;
pub const ENDIAN_LITTLE = 1;
pub const ENDIAN_PPC_LITTLE = 2;
pub const TSC_ENABLE = 1;
pub const TSC_SIGSEGV = 2;
pub const MCE_KILL_CLEAR = 0;
pub const MCE_KILL_SET = 1;
pub const MCE_KILL_LATE = 0;
pub const MCE_KILL_EARLY = 1;
pub const MCE_KILL_DEFAULT = 2;
pub const SET_MM_START_CODE = 1;
pub const SET_MM_END_CODE = 2;
pub const SET_MM_START_DATA = 3;
pub const SET_MM_END_DATA = 4;
pub const SET_MM_START_STACK = 5;
pub const SET_MM_START_BRK = 6;
pub const SET_MM_BRK = 7;
pub const SET_MM_ARG_START = 8;
pub const SET_MM_ARG_END = 9;
pub const SET_MM_ENV_START = 10;
pub const SET_MM_ENV_END = 11;
pub const SET_MM_AUXV = 12;
pub const SET_MM_EXE_FILE = 13;
pub const SET_MM_MAP = 14;
pub const SET_MM_MAP_SIZE = 15;
pub const SET_PTRACER_ANY = std.math.maxInt(c_ulong);
pub const FP_MODE_FR = 1 << 0;
pub const FP_MODE_FRE = 1 << 1;
pub const CAP_AMBIENT_IS_SET = 1;
pub const CAP_AMBIENT_RAISE = 2;
pub const CAP_AMBIENT_LOWER = 3;
pub const CAP_AMBIENT_CLEAR_ALL = 4;
pub const SVE_SET_VL_ONEXEC = 1 << 18;
pub const SVE_VL_LEN_MASK = 0xffff;
pub const SVE_VL_INHERIT = 1 << 17;
pub const SPEC_STORE_BYPASS = 0;
pub const SPEC_NOT_AFFECTED = 0;
pub const SPEC_PRCTL = 1 << 0;
pub const SPEC_ENABLE = 1 << 1;
pub const SPEC_DISABLE = 1 << 2;
pub const SPEC_FORCE_DISABLE = 1 << 3;
};
pub const prctl_mm_map = extern struct {
start_code: u64,
end_code: u64,
start_data: u64,
end_data: u64,
start_brk: u64,
brk: u64,
start_stack: u64,
arg_start: u64,
arg_end: u64,
env_start: u64,
env_end: u64,
auxv: *u64,
auxv_size: u32,
exe_fd: u32,
};
pub const NETLINK = struct {
/// Routing/device hook
pub const ROUTE = 0;
/// Unused number
pub const UNUSED = 1;
/// Reserved for user mode socket protocols
pub const USERSOCK = 2;
/// Unused number, formerly ip_queue
pub const FIREWALL = 3;
/// socket monitoring
pub const SOCK_DIAG = 4;
/// netfilter/iptables ULOG
pub const NFLOG = 5;
/// ipsec
pub const XFRM = 6;
/// SELinux event notifications
pub const SELINUX = 7;
/// Open-iSCSI
pub const ISCSI = 8;
/// auditing
pub const AUDIT = 9;
pub const FIB_LOOKUP = 10;
pub const CONNECTOR = 11;
/// netfilter subsystem
pub const NETFILTER = 12;
pub const IP6_FW = 13;
/// DECnet routing messages
pub const DNRTMSG = 14;
/// Kernel messages to userspace
pub const KOBJECT_UEVENT = 15;
pub const GENERIC = 16;
// leave room for NETLINK_DM (DM Events)
/// SCSI Transports
pub const SCSITRANSPORT = 18;
pub const ECRYPTFS = 19;
pub const RDMA = 20;
/// Crypto layer
pub const CRYPTO = 21;
/// SMC monitoring
pub const SMC = 22;
};
// Flags values
/// It is request message.
pub const NLM_F_REQUEST = 0x01;
/// Multipart message, terminated by NLMSG_DONE
pub const NLM_F_MULTI = 0x02;
/// Reply with ack, with zero or error code
pub const NLM_F_ACK = 0x04;
/// Echo this request
pub const NLM_F_ECHO = 0x08;
/// Dump was inconsistent due to sequence change
pub const NLM_F_DUMP_INTR = 0x10;
/// Dump was filtered as requested
pub const NLM_F_DUMP_FILTERED = 0x20;
// Modifiers to GET request
/// specify tree root
pub const NLM_F_ROOT = 0x100;
/// return all matching
pub const NLM_F_MATCH = 0x200;
/// atomic GET
pub const NLM_F_ATOMIC = 0x400;
pub const NLM_F_DUMP = NLM_F_ROOT | NLM_F_MATCH;
// Modifiers to NEW request
/// Override existing
pub const NLM_F_REPLACE = 0x100;
/// Do not touch, if it exists
pub const NLM_F_EXCL = 0x200;
/// Create, if it does not exist
pub const NLM_F_CREATE = 0x400;
/// Add to end of list
pub const NLM_F_APPEND = 0x800;
// Modifiers to DELETE request
/// Do not delete recursively
pub const NLM_F_NONREC = 0x100;
// Flags for ACK message
/// request was capped
pub const NLM_F_CAPPED = 0x100;
/// extended ACK TVLs were included
pub const NLM_F_ACK_TLVS = 0x200;
pub const NetlinkMessageType = enum(u16) {
/// < 0x10: reserved control messages
pub const MIN_TYPE = 0x10;
/// Nothing.
NOOP = 0x1,
/// Error
ERROR = 0x2,
/// End of a dump
DONE = 0x3,
/// Data lost
OVERRUN = 0x4,
// rtlink types
RTM_NEWLINK = 16,
RTM_DELLINK,
RTM_GETLINK,
RTM_SETLINK,
RTM_NEWADDR = 20,
RTM_DELADDR,
RTM_GETADDR,
RTM_NEWROUTE = 24,
RTM_DELROUTE,
RTM_GETROUTE,
RTM_NEWNEIGH = 28,
RTM_DELNEIGH,
RTM_GETNEIGH,
RTM_NEWRULE = 32,
RTM_DELRULE,
RTM_GETRULE,
RTM_NEWQDISC = 36,
RTM_DELQDISC,
RTM_GETQDISC,
RTM_NEWTCLASS = 40,
RTM_DELTCLASS,
RTM_GETTCLASS,
RTM_NEWTFILTER = 44,
RTM_DELTFILTER,
RTM_GETTFILTER,
RTM_NEWACTION = 48,
RTM_DELACTION,
RTM_GETACTION,
RTM_NEWPREFIX = 52,
RTM_GETMULTICAST = 58,
RTM_GETANYCAST = 62,
RTM_NEWNEIGHTBL = 64,
RTM_GETNEIGHTBL = 66,
RTM_SETNEIGHTBL,
RTM_NEWNDUSEROPT = 68,
RTM_NEWADDRLABEL = 72,
RTM_DELADDRLABEL,
RTM_GETADDRLABEL,
RTM_GETDCB = 78,
RTM_SETDCB,
RTM_NEWNETCONF = 80,
RTM_DELNETCONF,
RTM_GETNETCONF = 82,
RTM_NEWMDB = 84,
RTM_DELMDB = 85,
RTM_GETMDB = 86,
RTM_NEWNSID = 88,
RTM_DELNSID = 89,
RTM_GETNSID = 90,
RTM_NEWSTATS = 92,
RTM_GETSTATS = 94,
RTM_NEWCACHEREPORT = 96,
RTM_NEWCHAIN = 100,
RTM_DELCHAIN,
RTM_GETCHAIN,
RTM_NEWNEXTHOP = 104,
RTM_DELNEXTHOP,
RTM_GETNEXTHOP,
_,
};
/// Netlink message header
/// Specified in RFC 3549 Section 2.3.2
pub const nlmsghdr = extern struct {
/// Length of message including header
len: u32,
/// Message content
@"type": NetlinkMessageType,
/// Additional flags
flags: u16,
/// Sequence number
seq: u32,
/// Sending process port ID
pid: u32,
};
pub const ifinfomsg = extern struct {
family: u8,
__pad1: u8 = 0,
/// ARPHRD_*
@"type": c_ushort,
/// Link index
index: c_int,
/// IFF_* flags
flags: c_uint,
/// IFF_* change mask
change: c_uint,
};
pub const rtattr = extern struct {
/// Length of option
len: c_ushort,
/// Type of option
@"type": IFLA,
pub const ALIGNTO = 4;
};
pub const IFLA = enum(c_ushort) {
UNSPEC,
ADDRESS,
BROADCAST,
IFNAME,
MTU,
LINK,
QDISC,
STATS,
COST,
PRIORITY,
MASTER,
/// Wireless Extension event
WIRELESS,
/// Protocol specific information for a link
PROTINFO,
TXQLEN,
MAP,
WEIGHT,
OPERSTATE,
LINKMODE,
LINKINFO,
NET_NS_PID,
IFALIAS,
/// Number of VFs if device is SR-IOV PF
NUM_VF,
VFINFO_LIST,
STATS64,
VF_PORTS,
PORT_SELF,
AF_SPEC,
/// Group the device belongs to
GROUP,
NET_NS_FD,
/// Extended info mask, VFs, etc
EXT_MASK,
/// Promiscuity count: > 0 means acts PROMISC
PROMISCUITY,
NUM_TX_QUEUES,
NUM_RX_QUEUES,
CARRIER,
PHYS_PORT_ID,
CARRIER_CHANGES,
PHYS_SWITCH_ID,
LINK_NETNSID,
PHYS_PORT_NAME,
PROTO_DOWN,
GSO_MAX_SEGS,
GSO_MAX_SIZE,
PAD,
XDP,
EVENT,
NEW_NETNSID,
IF_NETNSID,
CARRIER_UP_COUNT,
CARRIER_DOWN_COUNT,
NEW_IFINDEX,
MIN_MTU,
MAX_MTU,
_,
pub const TARGET_NETNSID: IFLA = .IF_NETNSID;
};
pub const rtnl_link_ifmap = extern struct {
mem_start: u64,
mem_end: u64,
base_addr: u64,
irq: u16,
dma: u8,
port: u8,
};
pub const rtnl_link_stats = extern struct {
/// total packets received
rx_packets: u32,
/// total packets transmitted
tx_packets: u32,
/// total bytes received
rx_bytes: u32,
/// total bytes transmitted
tx_bytes: u32,
/// bad packets received
rx_errors: u32,
/// packet transmit problems
tx_errors: u32,
/// no space in linux buffers
rx_dropped: u32,
/// no space available in linux
tx_dropped: u32,
/// multicast packets received
multicast: u32,
collisions: u32,
// detailed rx_errors
rx_length_errors: u32,
/// receiver ring buff overflow
rx_over_errors: u32,
/// recved pkt with crc error
rx_crc_errors: u32,
/// recv'd frame alignment error
rx_frame_errors: u32,
/// recv'r fifo overrun
rx_fifo_errors: u32,
/// receiver missed packet
rx_missed_errors: u32,
// detailed tx_errors
tx_aborted_errors: u32,
tx_carrier_errors: u32,
tx_fifo_errors: u32,
tx_heartbeat_errors: u32,
tx_window_errors: u32,
// for cslip etc
rx_compressed: u32,
tx_compressed: u32,
/// dropped, no handler found
rx_nohandler: u32,
};
pub const rtnl_link_stats64 = extern struct {
/// total packets received
rx_packets: u64,
/// total packets transmitted
tx_packets: u64,
/// total bytes received
rx_bytes: u64,
/// total bytes transmitted
tx_bytes: u64,
/// bad packets received
rx_errors: u64,
/// packet transmit problems
tx_errors: u64,
/// no space in linux buffers
rx_dropped: u64,
/// no space available in linux
tx_dropped: u64,
/// multicast packets received
multicast: u64,
collisions: u64,
// detailed rx_errors
rx_length_errors: u64,
/// receiver ring buff overflow
rx_over_errors: u64,
/// recved pkt with crc error
rx_crc_errors: u64,
/// recv'd frame alignment error
rx_frame_errors: u64,
/// recv'r fifo overrun
rx_fifo_errors: u64,
/// receiver missed packet
rx_missed_errors: u64,
// detailed tx_errors
tx_aborted_errors: u64,
tx_carrier_errors: u64,
tx_fifo_errors: u64,
tx_heartbeat_errors: u64,
tx_window_errors: u64,
// for cslip etc
rx_compressed: u64,
tx_compressed: u64,
/// dropped, no handler found
rx_nohandler: u64,
};
pub const perf_event_attr = extern struct {
/// Major type: hardware/software/tracepoint/etc.
type: PERF.TYPE = undefined,
/// Size of the attr structure, for fwd/bwd compat.
size: u32 = @sizeOf(perf_event_attr),
/// Type specific configuration information.
config: u64 = 0,
sample_period_or_freq: u64 = 0,
sample_type: u64 = 0,
read_format: u64 = 0,
flags: packed struct {
/// off by default
disabled: bool = false,
/// children inherit it
inherit: bool = false,
/// must always be on PMU
pinned: bool = false,
/// only group on PMU
exclusive: bool = false,
/// don't count user
exclude_user: bool = false,
/// ditto kernel
exclude_kernel: bool = false,
/// ditto hypervisor
exclude_hv: bool = false,
/// don't count when idle
exclude_idle: bool = false,
/// include mmap data
mmap: bool = false,
/// include comm data
comm: bool = false,
/// use freq, not period
freq: bool = false,
/// per task counts
inherit_stat: bool = false,
/// next exec enables
enable_on_exec: bool = false,
/// trace fork/exit
task: bool = false,
/// wakeup_watermark
watermark: bool = false,
/// precise_ip:
///
/// 0 - SAMPLE_IP can have arbitrary skid
/// 1 - SAMPLE_IP must have constant skid
/// 2 - SAMPLE_IP requested to have 0 skid
/// 3 - SAMPLE_IP must have 0 skid
///
/// See also PERF_RECORD_MISC_EXACT_IP
/// skid constraint
precise_ip: u2 = 0,
/// non-exec mmap data
mmap_data: bool = false,
/// sample_type all events
sample_id_all: bool = false,
/// don't count in host
exclude_host: bool = false,
/// don't count in guest
exclude_guest: bool = false,
/// exclude kernel callchains
exclude_callchain_kernel: bool = false,
/// exclude user callchains
exclude_callchain_user: bool = false,
/// include mmap with inode data
mmap2: bool = false,
/// flag comm events that are due to an exec
comm_exec: bool = false,
/// use @clockid for time fields
use_clockid: bool = false,
/// context switch data
context_switch: bool = false,
/// Write ring buffer from end to beginning
write_backward: bool = false,
/// include namespaces data
namespaces: bool = false,
__reserved_1: u35 = 0,
} = .{},
/// wakeup every n events, or
/// bytes before wakeup
wakeup_events_or_watermark: u32 = 0,
bp_type: u32 = 0,
/// This field is also used for:
/// bp_addr
/// kprobe_func for perf_kprobe
/// uprobe_path for perf_uprobe
config1: u64 = 0,
/// This field is also used for:
/// bp_len
/// kprobe_addr when kprobe_func == null
/// probe_offset for perf_[k,u]probe
config2: u64 = 0,
/// enum perf_branch_sample_type
branch_sample_type: u64 = 0,
/// Defines set of user regs to dump on samples.
/// See asm/perf_regs.h for details.
sample_regs_user: u64 = 0,
/// Defines size of the user stack to dump on samples.
sample_stack_user: u32 = 0,
clockid: i32 = 0,
/// Defines set of regs to dump for each sample
/// state captured on:
/// - precise = 0: PMU interrupt
/// - precise > 0: sampled instruction
///
/// See asm/perf_regs.h for details.
sample_regs_intr: u64 = 0,
/// Wakeup watermark for AUX area
aux_watermark: u32 = 0,
sample_max_stack: u16 = 0,
/// Align to u64
__reserved_2: u16 = 0,
};
pub const PERF = struct {
pub const TYPE = enum(u32) {
HARDWARE,
SOFTWARE,
TRACEPOINT,
HW_CACHE,
RAW,
BREAKPOINT,
MAX,
};
pub const COUNT = struct {
pub const HW = enum(u32) {
CPU_CYCLES,
INSTRUCTIONS,
CACHE_REFERENCES,
CACHE_MISSES,
BRANCH_INSTRUCTIONS,
BRANCH_MISSES,
BUS_CYCLES,
STALLED_CYCLES_FRONTEND,
STALLED_CYCLES_BACKEND,
REF_CPU_CYCLES,
MAX,
pub const CACHE = enum(u32) {
L1D,
L1I,
LL,
DTLB,
ITLB,
BPU,
NODE,
MAX,
pub const OP = enum(u32) {
READ,
WRITE,
PREFETCH,
MAX,
};
pub const RESULT = enum(u32) {
ACCESS,
MISS,
MAX,
};
};
};
pub const SW = enum(u32) {
CPU_CLOCK,
TASK_CLOCK,
PAGE_FAULTS,
CONTEXT_SWITCHES,
CPU_MIGRATIONS,
PAGE_FAULTS_MIN,
PAGE_FAULTS_MAJ,
ALIGNMENT_FAULTS,
EMULATION_FAULTS,
DUMMY,
BPF_OUTPUT,
MAX,
};
};
pub const SAMPLE = struct {
pub const IP = 1;
pub const TID = 2;
pub const TIME = 4;
pub const ADDR = 8;
pub const READ = 16;
pub const CALLCHAIN = 32;
pub const ID = 64;
pub const CPU = 128;
pub const PERIOD = 256;
pub const STREAM_ID = 512;
pub const RAW = 1024;
pub const BRANCH_STACK = 2048;
pub const REGS_USER = 4096;
pub const STACK_USER = 8192;
pub const WEIGHT = 16384;
pub const DATA_SRC = 32768;
pub const IDENTIFIER = 65536;
pub const TRANSACTION = 131072;
pub const REGS_INTR = 262144;
pub const PHYS_ADDR = 524288;
pub const MAX = 1048576;
pub const BRANCH = struct {
pub const USER = 1 << 0;
pub const KERNEL = 1 << 1;
pub const HV = 1 << 2;
pub const ANY = 1 << 3;
pub const ANY_CALL = 1 << 4;
pub const ANY_RETURN = 1 << 5;
pub const IND_CALL = 1 << 6;
pub const ABORT_TX = 1 << 7;
pub const IN_TX = 1 << 8;
pub const NO_TX = 1 << 9;
pub const COND = 1 << 10;
pub const CALL_STACK = 1 << 11;
pub const IND_JUMP = 1 << 12;
pub const CALL = 1 << 13;
pub const NO_FLAGS = 1 << 14;
pub const NO_CYCLES = 1 << 15;
pub const TYPE_SAVE = 1 << 16;
pub const MAX = 1 << 17;
};
};
pub const FLAG = struct {
pub const FD_NO_GROUP = 1 << 0;
pub const FD_OUTPUT = 1 << 1;
pub const PID_CGROUP = 1 << 2;
pub const FD_CLOEXEC = 1 << 3;
};
pub const EVENT_IOC = struct {
pub const ENABLE = 9216;
pub const DISABLE = 9217;
pub const REFRESH = 9218;
pub const RESET = 9219;
pub const PERIOD = 1074275332;
pub const SET_OUTPUT = 9221;
pub const SET_FILTER = 1074275334;
pub const SET_BPF = 1074013192;
pub const PAUSE_OUTPUT = 1074013193;
pub const QUERY_BPF = 3221758986;
pub const MODIFY_ATTRIBUTES = 1074275339;
};
pub const IOC_FLAG_GROUP = 1;
}; | lib/std/os/linux.zig |
const Atom = @This();
const std = @import("std");
const elf = std.elf;
const log = std.log.scoped(.elf);
const math = std.math;
const mem = std.mem;
const Allocator = mem.Allocator;
const Elf = @import("../Elf.zig");
/// Each decl always gets a local symbol with the fully qualified name.
/// The vaddr and size are found here directly.
/// The file offset is found by computing the vaddr offset from the section vaddr
/// the symbol references, and adding that to the file offset of the section.
/// If this field is 0, it means the codegen size = 0 and there is no symbol or
/// offset table entry.
local_sym_index: u32,
/// null means global synthetic symbol table.
file: ?u32,
/// List of symbol aliases pointing to the same atom via different entries
aliases: std.ArrayListUnmanaged(u32) = .{},
/// List of symbols contained within this atom
contained: std.ArrayListUnmanaged(SymbolAtOffset) = .{},
/// Code (may be non-relocated) this atom represents
code: std.ArrayListUnmanaged(u8) = .{},
/// Size of this atom
/// TODO is this really needed given that size is a field of a symbol?
size: u32,
/// Alignment of this atom. Unlike in MachO, minimum alignment is 1.
alignment: u32,
/// List of relocations belonging to this atom.
relocs: std.ArrayListUnmanaged(elf.Elf64_Rela) = .{},
/// Points to the previous and next neighbours
next: ?*Atom,
prev: ?*Atom,
pub const SymbolAtOffset = struct {
local_sym_index: u32,
offset: u64,
pub fn format(
self: SymbolAtOffset,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = fmt;
_ = options;
try std.fmt.format(writer, "{{ {d}: .offset = {d} }}", .{ self.local_sym_index, self.offset });
}
};
pub fn createEmpty(allocator: *Allocator) !*Atom {
const self = try allocator.create(Atom);
self.* = .{
.local_sym_index = 0,
.file = undefined,
.size = 0,
.alignment = 0,
.prev = null,
.next = null,
};
return self;
}
pub fn deinit(self: *Atom, allocator: *Allocator) void {
self.relocs.deinit(allocator);
self.code.deinit(allocator);
self.contained.deinit(allocator);
self.aliases.deinit(allocator);
}
pub fn format(self: Atom, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = fmt;
_ = options;
try std.fmt.format(writer, "Atom {{ ", .{});
try std.fmt.format(writer, " .local_sym_index = {d}, ", .{self.local_sym_index});
try std.fmt.format(writer, " .file = {d}, ", .{self.file});
try std.fmt.format(writer, " .aliases = {any}, ", .{self.aliases.items});
try std.fmt.format(writer, " .contained = {any}, ", .{self.contained.items});
try std.fmt.format(writer, " .code = {x}, ", .{std.fmt.fmtSliceHexLower(if (self.code.items.len > 64)
self.code.items[0..64]
else
self.code.items)});
try std.fmt.format(writer, " .size = {d}, ", .{self.size});
try std.fmt.format(writer, " .alignment = {d}, ", .{self.alignment});
try std.fmt.format(writer, " .relocs = {any}, ", .{self.relocs.items});
try std.fmt.format(writer, "}}", .{});
}
fn getSymbol(self: Atom, elf_file: *Elf, index: u32) elf.Elf64_Sym {
if (self.file) |file| {
const object = elf_file.objects.items[file];
return object.symtab.items[index];
} else {
return elf_file.locals.items[index];
}
}
pub fn resolveRelocs(self: *Atom, elf_file: *Elf) !void {
const sym = self.getSymbol(elf_file, self.local_sym_index);
const sym_name = if (self.file) |file|
elf_file.objects.items[file].getString(sym.st_name)
else
elf_file.getString(sym.st_name);
log.debug("resolving relocs in atom '{s}'", .{sym_name});
const is_got_atom = if (elf_file.got_sect_index) |ndx| ndx == sym.st_shndx else false;
for (self.relocs.items) |rel| {
const r_sym = rel.r_sym();
const r_type = rel.r_type();
if (r_type == elf.R_X86_64_64 and is_got_atom) {
// Special handling as we have repurposed r_addend for out GOT atoms.
// Now, r_addend in those cases contains the index to the object file where
// the target symbol is defined.
const target: u64 = blk: {
if (rel.r_addend > -1) {
const object = elf_file.objects.items[@intCast(u64, rel.r_addend)];
const tsym = object.symtab.items[r_sym];
break :blk tsym.st_value;
} else {
const tsym = elf_file.locals.items[r_sym];
break :blk tsym.st_value;
}
};
const tsym_name = if (rel.r_addend > -1) blk: {
const object = elf_file.objects.items[@intCast(u64, rel.r_addend)];
const tsym = object.symtab.items[r_sym];
break :blk object.getString(tsym.st_name);
} else elf_file.getString(elf_file.locals.items[r_sym].st_name);
log.debug("R_X86_64_64: (GOT) {x}: [() => 0x{x}] ({s})", .{ rel.r_offset, target, tsym_name });
mem.writeIntLittle(u64, self.code.items[rel.r_offset..][0..8], target);
continue;
}
const tsym = if (self.file) |file| blk: {
const object = elf_file.objects.items[file];
break :blk object.symtab.items[r_sym];
} else elf_file.locals.items[r_sym];
const tsym_name = if (self.file) |file| blk: {
const object = elf_file.objects.items[file];
break :blk object.getString(tsym.st_name);
} else elf_file.getString(tsym.st_name);
const tsym_st_bind = tsym.st_info >> 4;
const tsym_st_type = tsym.st_info & 0xf;
switch (r_type) {
elf.R_X86_64_NONE => {},
elf.R_X86_64_64 => {
const is_local = tsym_st_type == elf.STT_SECTION or tsym_st_bind == elf.STB_LOCAL;
const target: u64 = blk: {
if (!is_local) {
const global = elf_file.globals.get(tsym_name).?;
if (global.file) |file| {
const actual_object = elf_file.objects.items[file];
const actual_tsym = actual_object.symtab.items[global.sym_index];
break :blk actual_tsym.st_value;
} else {
const actual_tsym = elf_file.locals.items[global.sym_index];
break :blk actual_tsym.st_value;
}
}
break :blk tsym.st_value;
};
log.debug("R_X86_64_64: {x}: [() => 0x{x}] ({s})", .{ rel.r_offset, target, tsym_name });
mem.writeIntLittle(u64, self.code.items[rel.r_offset..][0..8], target);
},
elf.R_X86_64_PC32 => {
const source = @intCast(i64, sym.st_value + rel.r_offset);
const is_local = tsym_st_type == elf.STT_SECTION or tsym_st_bind == elf.STB_LOCAL;
const target: i64 = blk: {
if (!is_local) {
const global = elf_file.globals.get(tsym_name).?;
if (global.file) |file| {
const actual_object = elf_file.objects.items[file];
const actual_tsym = actual_object.symtab.items[global.sym_index];
break :blk @intCast(i64, actual_tsym.st_value);
} else {
const actual_tsym = elf_file.locals.items[global.sym_index];
break :blk @intCast(i64, actual_tsym.st_value);
}
}
break :blk @intCast(i64, tsym.st_value);
};
const displacement = @intCast(i32, target - source + rel.r_addend);
log.debug("R_X86_64_PC32: {x}: [0x{x} => 0x{x}] ({s})", .{
rel.r_offset,
source,
target,
tsym_name,
});
mem.writeIntLittle(i32, self.code.items[rel.r_offset..][0..4], displacement);
},
elf.R_X86_64_PLT32 => {
const source = @intCast(i64, sym.st_value + rel.r_offset);
const is_local = tsym_st_type == elf.STT_SECTION or tsym_st_bind == elf.STB_LOCAL;
const target: i64 = blk: {
if (!is_local) {
const global = elf_file.globals.get(tsym_name).?;
if (global.file) |file| {
const actual_object = elf_file.objects.items[file];
const actual_tsym = actual_object.symtab.items[global.sym_index];
if (actual_tsym.st_info & 0xf == elf.STT_NOTYPE and
actual_tsym.st_shndx == elf.SHN_UNDEF)
{
log.debug("TODO handle R_X86_64_PLT32 to an UND symbol via PLT table", .{});
break :blk source;
}
break :blk @intCast(i64, actual_tsym.st_value);
} else {
const actual_tsym = elf_file.locals.items[global.sym_index];
break :blk @intCast(i64, actual_tsym.st_value);
}
}
break :blk @intCast(i64, tsym.st_value);
};
const displacement = @intCast(i32, target - source + rel.r_addend);
log.debug("R_X86_64_PLT32: {x}: [0x{x} => 0x{x}] ({s})", .{
rel.r_offset,
source,
target,
tsym_name,
});
mem.writeIntLittle(i32, self.code.items[rel.r_offset..][0..4], displacement);
},
elf.R_X86_64_32 => {
const is_local = tsym_st_type == elf.STT_SECTION or tsym_st_bind == elf.STB_LOCAL;
const target: u64 = blk: {
if (!is_local) {
const global = elf_file.globals.get(tsym_name).?;
if (global.file) |file| {
const actual_object = elf_file.objects.items[file];
const actual_tsym = actual_object.symtab.items[global.sym_index];
break :blk actual_tsym.st_value;
} else {
const actual_tsym = elf_file.locals.items[global.sym_index];
break :blk actual_tsym.st_value;
}
}
break :blk tsym.st_value;
};
const scaled = math.cast(u32, @intCast(i64, target) + rel.r_addend) catch |err| switch (err) {
error.Overflow => {
log.err("R_X86_64_32: target value overflows 32bits", .{});
log.err(" target value 0x{x}", .{@intCast(i64, target) + rel.r_addend});
log.err(" target symbol {s}", .{tsym_name});
return error.RelocationOverflow;
},
else => |e| return e,
};
log.debug("R_X86_64_32: {x}: [() => 0x{x}] ({s})", .{ rel.r_offset, scaled, tsym_name });
mem.writeIntLittle(u32, self.code.items[rel.r_offset..][0..4], scaled);
},
elf.R_X86_64_REX_GOTPCRELX => outer: {
const source = @intCast(i64, sym.st_value + rel.r_offset);
const global = elf_file.globals.get(tsym_name).?;
const got_atom = elf_file.got_entries_map.get(global) orelse {
log.debug("TODO R_X86_64_REX_GOTPCRELX unhandled: no GOT entry found", .{});
log.debug("TODO R_X86_64_REX_GOTPCRELX: {x}: [0x{x} => 0x{x}] ({s})", .{
rel.r_offset,
source,
tsym.st_value,
tsym_name,
});
break :outer;
};
const target: i64 = blk: {
if (got_atom.file) |file| {
const actual_object = elf_file.objects.items[file];
const actual_tsym = actual_object.symtab.items[got_atom.local_sym_index];
break :blk @intCast(i64, actual_tsym.st_value);
}
const actual_tsym = elf_file.locals.items[got_atom.local_sym_index];
break :blk @intCast(i64, actual_tsym.st_value);
};
log.debug("R_X86_64_REX_GOTPCRELX: {x}: [0x{x} => 0x{x}] ({s})", .{
rel.r_offset,
source,
target,
tsym_name,
});
const displacement = @intCast(i32, target - source + rel.r_addend);
mem.writeIntLittle(i32, self.code.items[rel.r_offset..][0..4], displacement);
},
else => {
const source = @intCast(i64, sym.st_value + rel.r_offset);
log.debug("TODO {d}: {x}: [0x{x} => 0x{x}] ({s})", .{
r_type,
rel.r_offset,
source,
tsym.st_value,
tsym_name,
});
},
}
}
} | src/Elf/Atom.zig |
const std = @import("std");
const vk = @import("vulkan");
const c = @import("c.zig");
const err = @import("err.zig");
pub usingnamespace @import("types.zig");
//// Misc ////
pub fn init() !void {
// This is a backcompat thing and we're a new library, so disable it unconditionally
glfwInitHint(c.GLFW_JOYSTICK_HAT_BUTTONS, c.GLFW_FALSE);
err.check();
if (glfwInit() == 0) {
return err.require(error{GlfwPlatformError});
}
}
extern fn glfwInitHint(c_int, c_int) void;
extern fn glfwInit() c_int;
pub const deinit = glfwTerminate;
extern fn glfwTerminate() void;
pub fn swapInterval(interval: u31) void {
glfwSwapInterval(interval);
err.check();
}
extern fn glfwSwapInterval(c_int) void;
//// Input ////
pub fn pollEvents() void {
glfwPollEvents();
err.check();
}
pub fn waitEvents() void {
glfwWaitEvents();
err.check();
}
extern fn glfwPollEvents() void;
extern fn glfwWaitEvents() void;
//// Enums ////
pub const ClientApi = enum(c_int) {
opengl = c.GLFW_OPENGL_API,
opengl_es = c.GLFW_OPENGL_ES_API,
none = c.GLFW_NO_API,
};
pub const ContextCreationApi = enum(c_int) {
native = c.GLFW_NATIVE_CONTEXT_API,
egl = c.GLFW_EGL_CONTEXT_API,
osmesa = c.GLFW_OSMESA_CONTEXT_API,
};
pub const OpenglProfile = enum(c_int) {
any = c.GLFW_OPENGL_ANY_PROFILE,
compat = c.GLFW_OPENGL_COMPAT_PROFILE,
core = c.GLFW_OPENGL_CORE_PROFILE,
};
pub const Key = enum(c_int) {
unknown = c.GLFW_KEY_UNKNOWN,
space = c.GLFW_KEY_SPACE,
apostrophe = c.GLFW_KEY_APOSTROPHE,
comma = c.GLFW_KEY_COMMA,
minus = c.GLFW_KEY_MINUS,
period = c.GLFW_KEY_PERIOD,
slash = c.GLFW_KEY_SLASH,
@"0" = c.GLFW_KEY_0,
@"1" = c.GLFW_KEY_1,
@"2" = c.GLFW_KEY_2,
@"3" = c.GLFW_KEY_3,
@"4" = c.GLFW_KEY_4,
@"5" = c.GLFW_KEY_5,
@"6" = c.GLFW_KEY_6,
@"7" = c.GLFW_KEY_7,
@"8" = c.GLFW_KEY_8,
@"9" = c.GLFW_KEY_9,
semicolon = c.GLFW_KEY_SEMICOLON,
equal = c.GLFW_KEY_EQUAL,
a = c.GLFW_KEY_A,
b = c.GLFW_KEY_B,
c = c.GLFW_KEY_C,
d = c.GLFW_KEY_D,
e = c.GLFW_KEY_E,
f = c.GLFW_KEY_F,
g = c.GLFW_KEY_G,
h = c.GLFW_KEY_H,
i = c.GLFW_KEY_I,
j = c.GLFW_KEY_J,
k = c.GLFW_KEY_K,
l = c.GLFW_KEY_L,
m = c.GLFW_KEY_M,
n = c.GLFW_KEY_N,
o = c.GLFW_KEY_O,
p = c.GLFW_KEY_P,
q = c.GLFW_KEY_Q,
r = c.GLFW_KEY_R,
s = c.GLFW_KEY_S,
t = c.GLFW_KEY_T,
u = c.GLFW_KEY_U,
v = c.GLFW_KEY_V,
w = c.GLFW_KEY_W,
x = c.GLFW_KEY_X,
y = c.GLFW_KEY_Y,
z = c.GLFW_KEY_Z,
left_bracket = c.GLFW_KEY_LEFT_BRACKET,
backslash = c.GLFW_KEY_BACKSLASH,
right_bracket = c.GLFW_KEY_RIGHT_BRACKET,
grave_accent = c.GLFW_KEY_GRAVE_ACCENT,
world_1 = c.GLFW_KEY_WORLD_1,
world_2 = c.GLFW_KEY_WORLD_2,
escape = c.GLFW_KEY_ESCAPE,
enter = c.GLFW_KEY_ENTER,
tab = c.GLFW_KEY_TAB,
backspace = c.GLFW_KEY_BACKSPACE,
insert = c.GLFW_KEY_INSERT,
delete = c.GLFW_KEY_DELETE,
right = c.GLFW_KEY_RIGHT,
left = c.GLFW_KEY_LEFT,
down = c.GLFW_KEY_DOWN,
up = c.GLFW_KEY_UP,
page_up = c.GLFW_KEY_PAGE_UP,
page_down = c.GLFW_KEY_PAGE_DOWN,
home = c.GLFW_KEY_HOME,
end = c.GLFW_KEY_END,
caps_lock = c.GLFW_KEY_CAPS_LOCK,
scroll_lock = c.GLFW_KEY_SCROLL_LOCK,
num_lock = c.GLFW_KEY_NUM_LOCK,
print_screen = c.GLFW_KEY_PRINT_SCREEN,
pause = c.GLFW_KEY_PAUSE,
f1 = c.GLFW_KEY_F1,
f2 = c.GLFW_KEY_F2,
f3 = c.GLFW_KEY_F3,
f4 = c.GLFW_KEY_F4,
f5 = c.GLFW_KEY_F5,
f6 = c.GLFW_KEY_F6,
f7 = c.GLFW_KEY_F7,
f8 = c.GLFW_KEY_F8,
f9 = c.GLFW_KEY_F9,
f10 = c.GLFW_KEY_F10,
f11 = c.GLFW_KEY_F11,
f12 = c.GLFW_KEY_F12,
f13 = c.GLFW_KEY_F13,
f14 = c.GLFW_KEY_F14,
f15 = c.GLFW_KEY_F15,
f16 = c.GLFW_KEY_F16,
f17 = c.GLFW_KEY_F17,
f18 = c.GLFW_KEY_F18,
f19 = c.GLFW_KEY_F19,
f20 = c.GLFW_KEY_F20,
f21 = c.GLFW_KEY_F21,
f22 = c.GLFW_KEY_F22,
f23 = c.GLFW_KEY_F23,
f24 = c.GLFW_KEY_F24,
f25 = c.GLFW_KEY_F25,
kp_0 = c.GLFW_KEY_KP_0,
kp_1 = c.GLFW_KEY_KP_1,
kp_2 = c.GLFW_KEY_KP_2,
kp_3 = c.GLFW_KEY_KP_3,
kp_4 = c.GLFW_KEY_KP_4,
kp_5 = c.GLFW_KEY_KP_5,
kp_6 = c.GLFW_KEY_KP_6,
kp_7 = c.GLFW_KEY_KP_7,
kp_8 = c.GLFW_KEY_KP_8,
kp_9 = c.GLFW_KEY_KP_9,
kp_decimal = c.GLFW_KEY_KP_DECIMAL,
kp_divide = c.GLFW_KEY_KP_DIVIDE,
kp_multiply = c.GLFW_KEY_KP_MULTIPLY,
kp_subtract = c.GLFW_KEY_KP_SUBTRACT,
kp_add = c.GLFW_KEY_KP_ADD,
kp_enter = c.GLFW_KEY_KP_ENTER,
kp_equal = c.GLFW_KEY_KP_EQUAL,
left_shift = c.GLFW_KEY_LEFT_SHIFT,
left_control = c.GLFW_KEY_LEFT_CONTROL,
left_alt = c.GLFW_KEY_LEFT_ALT,
left_super = c.GLFW_KEY_LEFT_SUPER,
right_shift = c.GLFW_KEY_RIGHT_SHIFT,
right_control = c.GLFW_KEY_RIGHT_CONTROL,
right_alt = c.GLFW_KEY_RIGHT_ALT,
right_super = c.GLFW_KEY_RIGHT_SUPER,
menu = c.GLFW_KEY_MENU,
};
pub const KeyAction = enum(c_int) {
press = c.GLFW_PRESS,
release = c.GLFW_RELEASE,
repeat = c.GLFW_REPEAT,
};
pub const MouseButton = enum(c_int) {
left = c.GLFW_MOUSE_BUTTON_1,
right = c.GLFW_MOUSE_BUTTON_2,
middle = c.GLFW_MOUSE_BUTTON_3,
mouse4 = c.GLFW_MOUSE_BUTTON_4,
mouse5 = c.GLFW_MOUSE_BUTTON_5,
mouse6 = c.GLFW_MOUSE_BUTTON_6,
mouse7 = c.GLFW_MOUSE_BUTTON_7,
mouse8 = c.GLFW_MOUSE_BUTTON_8,
};
pub const MouseAction = enum(c_int) {
press = c.GLFW_PRESS,
release = c.GLFW_RELEASE,
};
pub const ModKey = enum(c_int) {
shift = c.GLFW_MOD_SHIFT,
ctrl = c.GLFW_MOD_SHIFT,
alt = c.GLFW_MOD_ALT,
super = c.GLFW_MOD_SUPER,
caps_lock = c.GLFW_MOD_CAPS_LOCK,
num_lock = c.GLFW_MOD_NUM_LOCK,
};
pub const Modifiers = extern struct {
val: c_int,
pub fn has(self: Modifiers, m: ModKey) bool {
return self.val & @enumToInt(m) != 0;
}
};
//// Vulkan ////
pub fn vulkanSupported() bool {
return glfwVulkanSupported() != c.GLFW_FALSE;
}
extern fn glfwVulkanSupported() c_int;
/// Vulkan must be supported.
pub fn getRequiredInstanceExtensions() [][*:0]const u8 {
var count: u32 = undefined;
const result = glfwGetRequiredInstanceExtensions(&count) orelse unreachable;
return result[0..count];
}
extern fn glfwGetRequiredInstanceExtensions(*u32) ?[*][*:0]const u8;
pub const getInstanceProcAddress = glfwGetInstanceProcAddress;
extern fn glfwGetInstanceProcAddress(instance: vk.Instance, proc_name: [*:0]const u8) vk.PfnVoidFunction;
/// Vulkan must be supported.
/// The instance must have the required extensions enabled.
pub fn getPhysicalDevicePresentationSupport(instance: vk.Instance, device: vk.PhysicalDevice, queue_family: u32) !bool {
const result = glfwGetPhysicalDevicePresentationSupport(instance, device, queue_family) != 0;
if (!result) try err.get(error{GlfwPlatformError});
return result;
}
extern fn glfwGetPhysicalDevicePresentationSupport(vk.Instance, vk.PhysicalDevice, u32) c_int; | glfz.zig |
const builtin = @import("builtin");
const is_test = builtin.is_test;
const std = @import("std");
const maxInt = std.math.maxInt;
const LDBL_MANT_DIG = 113;
pub extern fn __floattitf(arg: i128) f128 {
@setRuntimeSafety(is_test);
if (arg == 0)
return 0.0;
var ai = arg;
const N: u32 = 128;
const si = ai >> @intCast(u7, (N - 1));
ai = ((ai ^ si) -% si);
var a = @bitCast(u128, ai);
const sd = @bitCast(i32, N - @clz(u128, a)); // number of significant digits
var e: i32 = sd - 1; // exponent
if (sd > LDBL_MANT_DIG) {
// start: 0000000000000000000001xxxxxxxxxxxxxxxxxxxxxxPQxxxxxxxxxxxxxxxxxx
// finish: 000000000000000000000000000000000000001xxxxxxxxxxxxxxxxxxxxxxPQR
// 12345678901234567890123456
// 1 = msb 1 bit
// P = bit LDBL_MANT_DIG-1 bits to the right of 1
// Q = bit LDBL_MANT_DIG bits to the right of 1
// R = "or" of all bits to the right of Q
switch (sd) {
LDBL_MANT_DIG + 1 => {
a <<= 1;
},
LDBL_MANT_DIG + 2 => {},
else => {
const shift1_amt = @intCast(i32, sd - (LDBL_MANT_DIG + 2));
const shift1_amt_u7 = @intCast(u7, shift1_amt);
const shift2_amt = @intCast(i32, N + (LDBL_MANT_DIG + 2)) - sd;
const shift2_amt_u7 = @intCast(u7, shift2_amt);
a = (a >> shift1_amt_u7) | @boolToInt((a & (@intCast(u128, maxInt(u128)) >> shift2_amt_u7)) != 0);
},
}
// finish
a |= @boolToInt((a & 4) != 0); // Or P into R
a += 1; // round - this step may add a significant bit
a >>= 2; // dump Q and R
// a is now rounded to LDBL_MANT_DIG or LDBL_MANT_DIG+1 bits
if ((a & (@as(u128, 1) << LDBL_MANT_DIG)) != 0) {
a >>= 1;
e += 1;
}
// a is now rounded to LDBL_MANT_DIG bits
} else {
a <<= @intCast(u7, LDBL_MANT_DIG - sd);
// a is now rounded to LDBL_MANT_DIG bits
}
const s = @bitCast(u128, arg) >> (128 - 64);
const high: u128 = (@intCast(u64, s) & 0x8000000000000000) | // sign
(@intCast(u64, (e + 16383)) << 48) | // exponent
(@truncate(u64, a >> 64) & 0x0000ffffffffffff); // mantissa-high
const low = @truncate(u64, a); // mantissa-low
return @bitCast(f128, low | (high << 64));
}
test "import floattitf" {
_ = @import("floattitf_test.zig");
} | lib/std/special/compiler_rt/floattitf.zig |
const std = @import("../../../std.zig");
const pid_t = linux.pid_t;
const uid_t = linux.uid_t;
const clock_t = linux.clock_t;
const stack_t = linux.stack_t;
const sigset_t = linux.sigset_t;
const linux = std.os.linux;
const sockaddr = linux.sockaddr;
const socklen_t = linux.socklen_t;
const iovec = linux.iovec;
const iovec_const = linux.iovec_const;
pub const SYS = extern enum(usize) {
restart_syscall = 0,
exit = 1,
fork = 2,
read = 3,
write = 4,
open = 5,
close = 6,
wait4 = 7,
creat = 8,
link = 9,
unlink = 10,
execv = 11,
chdir = 12,
chown = 13,
mknod = 14,
chmod = 15,
lchown = 16,
brk = 17,
perfctr = 18,
lseek = 19,
getpid = 20,
capget = 21,
capset = 22,
setuid = 23,
getuid = 24,
vmsplice = 25,
ptrace = 26,
alarm = 27,
sigaltstack = 28,
pause = 29,
utime = 30,
access = 33,
nice = 34,
sync = 36,
kill = 37,
stat = 38,
sendfile = 39,
lstat = 40,
dup = 41,
pipe = 42,
times = 43,
umount2 = 45,
setgid = 46,
getgid = 47,
signal = 48,
geteuid = 49,
getegid = 50,
acct = 51,
memory_ordering = 52,
ioctl = 54,
reboot = 55,
symlink = 57,
readlink = 58,
execve = 59,
umask = 60,
chroot = 61,
fstat = 62,
fstat64 = 63,
getpagesize = 64,
msync = 65,
vfork = 66,
pread64 = 67,
pwrite64 = 68,
mmap = 71,
munmap = 73,
mprotect = 74,
madvise = 75,
vhangup = 76,
mincore = 78,
getgroups = 79,
setgroups = 80,
getpgrp = 81,
setitimer = 83,
swapon = 85,
getitimer = 86,
sethostname = 88,
dup2 = 90,
fcntl = 92,
select = 93,
fsync = 95,
setpriority = 96,
socket = 97,
connect = 98,
accept = 99,
getpriority = 100,
rt_sigreturn = 101,
rt_sigaction = 102,
rt_sigprocmask = 103,
rt_sigpending = 104,
rt_sigtimedwait = 105,
rt_sigqueueinfo = 106,
rt_sigsuspend = 107,
setresuid = 108,
getresuid = 109,
setresgid = 110,
getresgid = 111,
recvmsg = 113,
sendmsg = 114,
gettimeofday = 116,
getrusage = 117,
getsockopt = 118,
getcwd = 119,
readv = 120,
writev = 121,
settimeofday = 122,
fchown = 123,
fchmod = 124,
recvfrom = 125,
setreuid = 126,
setregid = 127,
rename = 128,
truncate = 129,
ftruncate = 130,
flock = 131,
lstat64 = 132,
sendto = 133,
shutdown = 134,
socketpair = 135,
mkdir = 136,
rmdir = 137,
utimes = 138,
stat64 = 139,
sendfile64 = 140,
getpeername = 141,
futex = 142,
gettid = 143,
getrlimit = 144,
setrlimit = 145,
pivot_root = 146,
prctl = 147,
pciconfig_read = 148,
pciconfig_write = 149,
getsockname = 150,
inotify_init = 151,
inotify_add_watch = 152,
poll = 153,
getdents64 = 154,
inotify_rm_watch = 156,
statfs = 157,
fstatfs = 158,
umount = 159,
sched_set_affinity = 160,
sched_get_affinity = 161,
getdomainname = 162,
setdomainname = 163,
utrap_install = 164,
quotactl = 165,
set_tid_address = 166,
mount = 167,
ustat = 168,
setxattr = 169,
lsetxattr = 170,
fsetxattr = 171,
getxattr = 172,
lgetxattr = 173,
getdents = 174,
setsid = 175,
fchdir = 176,
fgetxattr = 177,
listxattr = 178,
llistxattr = 179,
flistxattr = 180,
removexattr = 181,
lremovexattr = 182,
sigpending = 183,
query_module = 184,
setpgid = 185,
fremovexattr = 186,
tkill = 187,
exit_group = 188,
uname = 189,
init_module = 190,
personality = 191,
remap_file_pages = 192,
epoll_create = 193,
epoll_ctl = 194,
epoll_wait = 195,
ioprio_set = 196,
getppid = 197,
sigaction = 198,
sgetmask = 199,
ssetmask = 200,
sigsuspend = 201,
oldlstat = 202,
uselib = 203,
readdir = 204,
readahead = 205,
socketcall = 206,
syslog = 207,
lookup_dcookie = 208,
fadvise64 = 209,
fadvise64_64 = 210,
tgkill = 211,
waitpid = 212,
swapoff = 213,
sysinfo = 214,
ipc = 215,
sigreturn = 216,
clone = 217,
ioprio_get = 218,
adjtimex = 219,
sigprocmask = 220,
create_module = 221,
delete_module = 222,
get_kernel_syms = 223,
getpgid = 224,
bdflush = 225,
sysfs = 226,
afs_syscall = 227,
setfsuid = 228,
setfsgid = 229,
_newselect = 230,
splice = 232,
stime = 233,
statfs64 = 234,
fstatfs64 = 235,
_llseek = 236,
mlock = 237,
munlock = 238,
mlockall = 239,
munlockall = 240,
sched_setparam = 241,
sched_getparam = 242,
sched_setscheduler = 243,
sched_getscheduler = 244,
sched_yield = 245,
sched_get_priority_max = 246,
sched_get_priority_min = 247,
sched_rr_get_interval = 248,
nanosleep = 249,
mremap = 250,
_sysctl = 251,
getsid = 252,
fdatasync = 253,
nfsservctl = 254,
sync_file_range = 255,
clock_settime = 256,
clock_gettime = 257,
clock_getres = 258,
clock_nanosleep = 259,
sched_getaffinity = 260,
sched_setaffinity = 261,
timer_settime = 262,
timer_gettime = 263,
timer_getoverrun = 264,
timer_delete = 265,
timer_create = 266,
vserver = 267,
io_setup = 268,
io_destroy = 269,
io_submit = 270,
io_cancel = 271,
io_getevents = 272,
mq_open = 273,
mq_unlink = 274,
mq_timedsend = 275,
mq_timedreceive = 276,
mq_notify = 277,
mq_getsetattr = 278,
waitid = 279,
tee = 280,
add_key = 281,
request_key = 282,
keyctl = 283,
openat = 284,
mkdirat = 285,
mknodat = 286,
fchownat = 287,
futimesat = 288,
fstatat64 = 289,
unlinkat = 290,
renameat = 291,
linkat = 292,
symlinkat = 293,
readlinkat = 294,
fchmodat = 295,
faccessat = 296,
pselect6 = 297,
ppoll = 298,
unshare = 299,
set_robust_list = 300,
get_robust_list = 301,
migrate_pages = 302,
mbind = 303,
get_mempolicy = 304,
set_mempolicy = 305,
kexec_load = 306,
move_pages = 307,
getcpu = 308,
epoll_pwait = 309,
utimensat = 310,
signalfd = 311,
timerfd_create = 312,
eventfd = 313,
fallocate = 314,
timerfd_settime = 315,
timerfd_gettime = 316,
signalfd4 = 317,
eventfd2 = 318,
epoll_create1 = 319,
dup3 = 320,
pipe2 = 321,
inotify_init1 = 322,
accept4 = 323,
preadv = 324,
pwritev = 325,
rt_tgsigqueueinfo = 326,
perf_event_open = 327,
recvmmsg = 328,
fanotify_init = 329,
fanotify_mark = 330,
prlimit64 = 331,
name_to_handle_at = 332,
open_by_handle_at = 333,
clock_adjtime = 334,
syncfs = 335,
sendmmsg = 336,
setns = 337,
process_vm_readv = 338,
process_vm_writev = 339,
kern_features = 340,
kcmp = 341,
finit_module = 342,
sched_setattr = 343,
sched_getattr = 344,
renameat2 = 345,
seccomp = 346,
getrandom = 347,
memfd_create = 348,
bpf = 349,
execveat = 350,
membarrier = 351,
userfaultfd = 352,
bind = 353,
listen = 354,
setsockopt = 355,
mlock2 = 356,
copy_file_range = 357,
preadv2 = 358,
pwritev2 = 359,
statx = 360,
io_pgetevents = 361,
pkey_mprotect = 362,
pkey_alloc = 363,
pkey_free = 364,
rseq = 365,
semtimedop = 392,
semget = 393,
semctl = 394,
shmget = 395,
shmctl = 396,
shmat = 397,
shmdt = 398,
msgget = 399,
msgsnd = 400,
msgrcv = 401,
msgctl = 402,
pidfd_send_signal = 424,
io_uring_setup = 425,
io_uring_enter = 426,
io_uring_register = 427,
open_tree = 428,
move_mount = 429,
fsopen = 430,
fsconfig = 431,
fsmount = 432,
fspick = 433,
pidfd_open = 434,
openat2 = 437,
pidfd_getfd = 438,
_,
};
pub const O_CREAT = 0x200;
pub const O_EXCL = 0x800;
pub const O_NOCTTY = 0x8000;
pub const O_TRUNC = 0x400;
pub const O_APPEND = 0x8;
pub const O_NONBLOCK = 0x4000;
pub const O_SYNC = 0x802000;
pub const O_DSYNC = 0x2000;
pub const O_RSYNC = O_SYNC;
pub const O_DIRECTORY = 0x10000;
pub const O_NOFOLLOW = 0x20000;
pub const O_CLOEXEC = 0x400000;
pub const O_ASYNC = 0x40;
pub const O_DIRECT = 0x100000;
pub const O_LARGEFILE = 0;
pub const O_NOATIME = 0x200000;
pub const O_PATH = 0x1000000;
pub const O_TMPFILE = 0x2010000;
pub const O_NDELAY = O_NONBLOCK | 0x4;
pub const F_DUPFD = 0;
pub const F_GETFD = 1;
pub const F_SETFD = 2;
pub const F_GETFL = 3;
pub const F_SETFL = 4;
pub const F_SETOWN = 5;
pub const F_GETOWN = 6;
pub const F_GETLK = 7;
pub const F_SETLK = 8;
pub const F_SETLKW = 9;
pub const F_RDLCK = 1;
pub const F_WRLCK = 2;
pub const F_UNLCK = 3;
pub const F_SETOWN_EX = 15;
pub const F_GETOWN_EX = 16;
pub const F_GETOWNER_UIDS = 17;
pub const LOCK_SH = 1;
pub const LOCK_EX = 2;
pub const LOCK_NB = 4;
pub const LOCK_UN = 8;
/// stack-like segment
pub const MAP_GROWSDOWN = 0x0200;
/// ETXTBSY
pub const MAP_DENYWRITE = 0x0800;
/// mark it as an executable
pub const MAP_EXECUTABLE = 0x1000;
/// pages are locked
pub const MAP_LOCKED = 0x0100;
/// don't check for reservations
pub const MAP_NORESERVE = 0x0040;
pub const VDSO_CGT_SYM = "__vdso_clock_gettime";
pub const VDSO_CGT_VER = "LINUX_2.6";
pub const Flock = extern struct {
l_type: i16,
l_whence: i16,
l_start: off_t,
l_len: off_t,
l_pid: pid_t,
};
pub const msghdr = extern struct {
msg_name: ?*sockaddr,
msg_namelen: socklen_t,
msg_iov: [*]iovec,
msg_iovlen: u64,
msg_control: ?*c_void,
msg_controllen: u64,
msg_flags: i32,
};
pub const msghdr_const = extern struct {
msg_name: ?*const sockaddr,
msg_namelen: socklen_t,
msg_iov: [*]iovec_const,
msg_iovlen: u64,
msg_control: ?*c_void,
msg_controllen: u64,
msg_flags: i32,
};
pub const off_t = i64;
pub const ino_t = u64;
pub const mode_t = u32;
/// atime, mtime, and ctime have functions to return `timespec`,
/// because although this is a POSIX API, the layout and names of
/// the structs are inconsistent across operating systems, and
/// in C, macros are used to hide the differences. Here we use
/// methods to accomplish this.
pub const libc_stat = extern struct {
dev: u64,
ino: ino_t,
mode: u32,
nlink: usize,
uid: u32,
gid: u32,
rdev: u64,
__pad0: u32,
size: off_t,
blksize: isize,
blocks: i64,
atim: timespec,
mtim: timespec,
ctim: timespec,
__unused: [2]isize,
pub fn atime(self: libc_stat) timespec {
return self.atim;
}
pub fn mtime(self: libc_stat) timespec {
return self.mtim;
}
pub fn ctime(self: libc_stat) timespec {
return self.ctim;
}
};
pub const kernel_stat = extern struct {
dev: u32,
ino: ino_t,
mode: mode_t,
nlink: i16,
uid: u32,
gid: u32,
rdev: u32,
size: off_t,
atim: isize,
mtim: isize,
ctim: isize,
blksize: off_t,
blocks: off_t,
__unused4: [2]isize,
// Hack to make the stdlib not complain about atime
// and friends not being a method.
// TODO what should tv_nsec be filled with?
pub fn atime(self: kernel_stat) timespec {
return timespec{.tv_sec=self.atim, .tv_nsec=0};
}
pub fn mtime(self: kernel_stat) timespec {
return timespec{.tv_sec=self.mtim, .tv_nsec=0};
}
pub fn ctime(self: kernel_stat) timespec {
return timespec{.tv_sec=self.ctim, .tv_nsec=0};
}
};
/// Renamed to Stat to not conflict with the stat function.
pub const Stat = if (std.builtin.link_libc) libc_stat else kernel_stat;
pub const timespec = extern struct {
tv_sec: isize,
tv_nsec: isize,
};
pub const timeval = extern struct {
tv_sec: isize,
tv_usec: isize,
};
pub const timezone = extern struct {
tz_minuteswest: i32,
tz_dsttime: i32,
};
// TODO I'm not sure if the code below is correct, need someone with more
// knowledge about sparc64 linux internals to look into.
pub const Elf_Symndx = u32;
pub const fpstate = extern struct {
regs: [32]u64,
fsr: u64,
gsr: u64,
fprs: u64,
};
pub const __fpq = extern struct {
fpq_addr: *u32,
fpq_instr: u32,
};
pub const __fq = extern struct {
FQu: extern union {
whole: f64,
fpq: __fpq,
},
};
pub const fpregset_t = extern struct {
fpu_fr: extern union {
fpu_regs: [32]u32,
fpu_dregs: [32]f64,
fpu_qregs: [16]c_longdouble,
},
fpu_q: *__fq,
fpu_fsr: u64,
fpu_qcnt: u8,
fpu_q_entrysize: u8,
fpu_en: u8,
};
pub const siginfo_fpu_t = extern struct {
float_regs: [64]u32,
fsr: u64,
gsr: u64,
fprs: u64,
};
pub const sigcontext = extern struct {
info: [128]i8,
regs: extern struct {
u_regs: [16]u64,
tstate: u64,
tpc: u64,
tnpc: u64,
y: u64,
fprs: u64,
},
fpu_save: *siginfo_fpu_t,
stack: extern struct {
sp: usize,
flags: i32,
size: u64,
},
mask: u64,
};
pub const greg_t = u64;
pub const gregset_t = [19]greg_t;
pub const fq = extern struct {
addr: *u64,
insn: u32,
};
pub const fpu_t = extern struct {
fregs: extern union {
sregs: [32]u32,
dregs: [32]u64,
qregs: [16]c_longdouble,
},
fsr: u64,
fprs: u64,
gsr: u64,
fq: *fq,
qcnt: u8,
qentsz: u8,
enab: u8,
};
pub const mcontext_t = extern struct {
gregs: gregset_t,
fp: greg_t,
@"i7": greg_t,
fpregs: fpu_t,
};
pub const ucontext_t = extern struct {
link: *ucontext_t,
flags: u64,
sigmask: u64,
mcontext: mcontext_t,
stack: stack_t,
sigmask: sigset_t,
}; | lib/std/os/bits/linux/sparc64.zig |
const std = @import("std");
const warn = @import("nonsecure-common/debug.zig").warn;
const port = @import("ports/" ++ @import("build_options").BOARD ++ "/nonsecure.zig");
// FreeRTOS-related thingy
const os = @cImport({
@cInclude("FreeRTOS.h");
@cInclude("task.h");
@cInclude("timers.h");
});
comptime {
_ = @import("nonsecure-common/oshooks.zig");
}
// The (unprocessed) Non-Secure exception vector table.
export const raw_exception_vectors linksection(".text.raw_isr_vector") = @import("nonsecure-common/excvector.zig").getDefaultFreertos();
// The entry point. The reset handler transfers the control to this function
// after initializing data sections.
export fn main() void {
port.init();
warn("Creating an idle task.\r\n", .{});
_ = os.xTaskCreateRestricted(&idle_task_params, 0);
warn("Creating a timer.\r\n", .{});
const timer = os.xTimerCreate("saluton", 100, os.pdTRUE, null, getTrampoline_timerHandler());
_ = xTimerStart(timer, 0);
warn("Entering the scheduler.\r\n", .{});
os.vTaskStartScheduler();
unreachable;
}
fn xTimerStart(timer: os.TimerHandle_t, ticks: os.TickType_t) os.BaseType_t {
return os.xTimerGenericCommand(timer, os.tmrCOMMAND_START, os.xTaskGetTickCount(), null, ticks);
}
extern fn getTrampoline_timerHandler() extern fn (_arg: ?*os.tmrTimerControl) void;
var i: u32 = 0;
export fn timerHandler(_arg: ?*os.tmrTimerControl) void {
i +%= 1;
warn("The timer has fired for {} time(s)!\r\n", .{i});
}
var idle_task_stack = [1]u32{0} ** 128;
const idle_task_params = os.TaskParameters_t{
.pvTaskCode = idleTaskMain,
.pcName = "saluton",
.usStackDepth = idle_task_stack.len,
.pvParameters = null,
.uxPriority = 0,
.puxStackBuffer = &idle_task_stack,
.xRegions = [1]os.MemoryRegion_t{os.MemoryRegion_t{
.pvBaseAddress = null,
.ulLengthInBytes = 0,
.ulParameters = 0,
}} ** 3,
.pxTaskBuffer = null,
};
fn idleTaskMain(_arg: ?*c_void) callconv(.C) void {
warn("The idle task is running.\r\n", .{});
while (true) {}
}
// Zig panic handler. See `panicking.zig` for details.
const panicking = @import("nonsecure-common/panicking.zig");
pub fn panic(msg: []const u8, error_return_trace: ?*panicking.StackTrace) noreturn {
panicking.panic(msg, error_return_trace);
} | examples/nonsecure-rtosbasic.zig |
const std = @import("std");
const root = @import("main.zig");
const math = std.math;
const assert = std.debug.assert;
const panic = std.debug.panic;
const expectEqual = std.testing.expectEqual;
pub const Vec3 = Vector3(f32);
pub const Vec3_f64 = Vector3(f64);
pub const Vec3_i32 = Vector3(i32);
pub const Vec3_usize = Vector3(usize);
/// A 3 dimensional vector.
pub fn Vector3(comptime T: type) type {
if (@typeInfo(T) != .Float and @typeInfo(T) != .Int) {
@compileError("Vector3 not implemented for " ++ @typeName(T));
}
return extern struct {
x: T,
y: T,
z: T,
const Self = @This();
/// Construct a vector from given 3 components.
pub fn new(x: T, y: T, z: T) Self {
return Self{ .x = x, .y = y, .z = z };
}
/// Return component from given index.
pub fn at(self: *const Self, index: i32) T {
assert(index <= 2);
if (index == 0) {
return self.x;
} else if (index == 1) {
return self.y;
} else {
return self.z;
}
}
/// Set all components to the same given value.
pub fn set(val: T) Self {
return Self.new(val, val, val);
}
/// Shorthand for writing vec3.new(0, 0, 0).
pub fn zero() Self {
return Self.set(0);
}
/// Shorthand for writing vec3.new(1, 1, 1).
pub fn one() Self {
return Self.set(1);
}
/// Shorthand for writing vec3.new(0, 1, 0).
pub fn up() Self {
return Self.new(0, 1, 0);
}
/// Shorthand for writing vec3.new(0, -1, 0).
pub fn down() Self {
return Self.new(0, -1, 0);
}
/// Shorthand for writing vec3.new(1, 0, 0).
pub fn right() Self {
return Self.new(1, 0, 0);
}
/// Shorthand for writing vec3.new(-1, 0, 0).
pub fn left() Self {
return Self.new(-1, 0, 0);
}
/// Shorthand for writing vec3.new(0, 0, -1).
pub fn back() Self {
return Self.new(0, 0, -1);
}
/// Shorthand for writing vec3.new(0, 0, 1).
pub fn forward() Self {
return Self.new(0, 0, 1);
}
/// Negate the given vector.
pub fn negate(self: Self) Self {
return self.scale(-1);
}
/// Cast a type to another type. Only for integers and floats.
/// It's like builtins: @intCast, @floatCast, @intToFloat, @floatToInt
pub fn cast(self: Self, dest: anytype) Vector3(dest) {
const source_info = @typeInfo(T);
const dest_info = @typeInfo(dest);
if (source_info == .Float and dest_info == .Int) {
const x = @floatToInt(dest, self.x);
const y = @floatToInt(dest, self.y);
const z = @floatToInt(dest, self.z);
return Vector3(dest).new(x, y, z);
}
if (source_info == .Int and dest_info == .Float) {
const x = @intToFloat(dest, self.x);
const y = @intToFloat(dest, self.y);
const z = @intToFloat(dest, self.z);
return Vector3(dest).new(x, y, z);
}
return switch (dest_info) {
.Float => {
const x = @floatCast(dest, self.x);
const y = @floatCast(dest, self.y);
const z = @floatCast(dest, self.z);
return Vector3(dest).new(x, y, z);
},
.Int => {
const x = @intCast(dest, self.x);
const y = @intCast(dest, self.y);
const z = @intCast(dest, self.z);
return Vector3(dest).new(x, y, z);
},
else => panic(
"Error, given type should be integers or float.\n",
.{},
),
};
}
/// Construct new vector from slice.
pub fn fromSlice(slice: []const T) Self {
return Self.new(slice[0], slice[1], slice[2]);
}
/// Transform vector to array.
pub fn toArray(self: Self) [3]T {
return .{ self.x, self.y, self.z };
}
/// Return the angle in degrees between two vectors.
pub fn getAngle(lhs: Self, rhs: Self) T {
const dot_product = Self.dot(lhs.norm(), rhs.norm());
return root.toDegrees(math.acos(dot_product));
}
/// Compute the length (magnitude) of given vector |a|.
pub fn length(self: Self) T {
return @sqrt(self.dot(self));
}
/// Compute the distance between two points.
pub fn distance(a: Self, b: Self) T {
return length(b.sub(a));
}
/// Construct new normalized vector from a given vector.
pub fn norm(self: Self) Self {
var l = length(self);
return Self.new(
self.x / l,
self.y / l,
self.z / l,
);
}
pub fn eql(lhs: Self, rhs: Self) bool {
return lhs.x == rhs.x and lhs.y == rhs.y and lhs.z == rhs.z;
}
/// Substraction between two given vector.
pub fn sub(lhs: Self, rhs: Self) Self {
return Self.new(
lhs.x - rhs.x,
lhs.y - rhs.y,
lhs.z - rhs.z,
);
}
/// Addition betwen two given vector.
pub fn add(lhs: Self, rhs: Self) Self {
return Self.new(
lhs.x + rhs.x,
lhs.y + rhs.y,
lhs.z + rhs.z,
);
}
/// Multiply each components by the given scalar.
pub fn scale(v: Self, scalar: T) Self {
return Self.new(
v.x * scalar,
v.y * scalar,
v.z * scalar,
);
}
/// Compute the cross product from two vector.
pub fn cross(lhs: Self, rhs: Self) Self {
return Self.new(
(lhs.y * rhs.z) - (lhs.z * rhs.y),
(lhs.z * rhs.x) - (lhs.x * rhs.z),
(lhs.x * rhs.y) - (lhs.y * rhs.x),
);
}
/// Return the dot product between two given vector.
pub fn dot(lhs: Self, rhs: Self) T {
return (lhs.x * rhs.x) + (lhs.y * rhs.y) + (lhs.z * rhs.z);
}
/// Lerp between two vectors.
pub fn lerp(lhs: Self, rhs: Self, t: T) Self {
const x = root.lerp(T, lhs.x, rhs.x, t);
const y = root.lerp(T, lhs.y, rhs.y, t);
const z = root.lerp(T, lhs.z, rhs.z, t);
return Self.new(x, y, z);
}
/// Construct a new vector from the min components between two vectors.
pub fn min(lhs: Self, rhs: Self) Self {
return Self.new(
@minimum(lhs.x, rhs.x),
@minimum(lhs.y, rhs.y),
@minimum(lhs.z, rhs.z),
);
}
/// Construct a new vector from the max components between two vectors.
pub fn max(lhs: Self, rhs: Self) Self {
return Self.new(
@maximum(lhs.x, rhs.x),
@maximum(lhs.y, rhs.y),
@maximum(lhs.z, rhs.z),
);
}
/// Construct a new vector from absolute components.
pub fn abs(self: Self) Self {
return switch (@typeInfo(T)) {
.Float => Self.new(
math.absFloat(self.x),
math.absFloat(self.y),
math.absFloat(self.z),
),
.Int => Self.new(
math.absInt(self.x),
math.absInt(self.y),
math.absInt(self.z),
),
else => unreachable,
};
}
};
}
test "zalgebra.Vec3.init" {
var a = Vec3.new(1.5, 2.6, 3.7);
try expectEqual(a.x, 1.5);
try expectEqual(a.y, 2.6);
try expectEqual(a.z, 3.7);
}
test "zalgebra.Vec3.set" {
var a = Vec3.new(2.5, 2.5, 2.5);
var b = Vec3.set(2.5);
try expectEqual(Vec3.eql(a, b), true);
}
test "zalgebra.Vec3.negate" {
var a = Vec3.set(10);
var b = Vec3.set(-10);
try expectEqual(Vec3.eql(a.negate(), b), true);
}
test "zalgebra.Vec3.getAngle" {
var a = Vec3.new(1, 0, 0);
var b = Vec3.up();
var c = Vec3.new(-1, 0, 0);
var d = Vec3.new(1, 1, 0);
try expectEqual(Vec3.getAngle(a, b), 90);
try expectEqual(Vec3.getAngle(a, c), 180);
try expectEqual(Vec3.getAngle(a, d), 45);
}
test "zalgebra.Vec3.toArray" {
const a = Vec3.up().toArray();
const b = [_]f32{ 0, 1, 0 };
try expectEqual(std.mem.eql(f32, &a, &b), true);
}
test "zalgebra.Vec3.eql" {
var a = Vec3.new(1, 2, 3);
var b = Vec3.new(1, 2, 3);
var c = Vec3.new(1.5, 2, 3);
try expectEqual(Vec3.eql(a, b), true);
try expectEqual(Vec3.eql(a, c), false);
}
test "zalgebra.Vec3.length" {
var a = Vec3.new(1.5, 2.6, 3.7);
try expectEqual(a.length(), 4.7644519);
}
test "zalgebra.Vec3.distance" {
var a = Vec3.new(0, 0, 0);
var b = Vec3.new(-1, 0, 0);
var c = Vec3.new(0, 5, 0);
try expectEqual(Vec3.distance(a, b), 1);
try expectEqual(Vec3.distance(a, c), 5);
}
test "zalgebra.Vec3.normalize" {
var a = Vec3.new(1.5, 2.6, 3.7);
try expectEqual(
Vec3.eql(a.norm(), Vec3.new(0.314831584, 0.545708060, 0.776584625)),
true,
);
}
test "zalgebra.Vec3.sub" {
var a = Vec3.new(1, 2, 3);
var b = Vec3.new(2, 2, 3);
try expectEqual(Vec3.eql(Vec3.sub(a, b), Vec3.new(-1, 0, 0)), true);
}
test "zalgebra.Vec3.add" {
var a = Vec3.new(1, 2, 3);
var b = Vec3.new(2, 2, 3);
try expectEqual(Vec3.eql(Vec3.add(a, b), Vec3.new(3, 4, 6)), true);
}
test "zalgebra.Vec3.scale" {
var a = Vec3.new(1, 2, 3);
try expectEqual(Vec3.eql(Vec3.scale(a, 5), Vec3.new(5, 10, 15)), true);
}
test "zalgebra.Vec3.cross" {
var a = Vec3.new(1.5, 2.6, 3.7);
var b = Vec3.new(2.5, 3.45, 1.0);
var c = Vec3.new(1.5, 2.6, 3.7);
var result_1 = Vec3.cross(a, c);
var result_2 = Vec3.cross(a, b);
try expectEqual(Vec3.eql(result_1, Vec3.new(0, 0, 0)), true);
try expectEqual(Vec3.eql(
result_2,
Vec3.new(-10.1650009, 7.75, -1.32499980),
), true);
}
test "zalgebra.Vec3.dot" {
var a = Vec3.new(1.5, 2.6, 3.7);
var b = Vec3.new(2.5, 3.45, 1.0);
try expectEqual(Vec3.dot(a, b), 16.42);
}
test "zalgebra.Vec3.lerp" {
var a = Vec3.new(-10.0, 0.0, -10.0);
var b = Vec3.new(10.0, 10.0, 10.0);
try expectEqual(Vec3.eql(
Vec3.lerp(a, b, 0.5),
Vec3.new(0.0, 5.0, 0.0),
), true);
}
test "zalgebra.Vec3.min" {
var a = Vec3.new(10.0, -2.0, 0.0);
var b = Vec3.new(-10.0, 5.0, 0.0);
try expectEqual(Vec3.eql(
Vec3.min(a, b),
Vec3.new(-10.0, -2.0, 0.0),
), true);
}
test "zalgebra.Vec3.max" {
var a = Vec3.new(10.0, -2.0, 0.0);
var b = Vec3.new(-10.0, 5.0, 0.0);
try expectEqual(Vec3.eql(Vec3.max(a, b), Vec3.new(10.0, 5.0, 0.0)), true);
}
test "zalgebra.Vec4.abs" {
{
const vec = Vec3.new(-42, -43, -44);
const expected = Vec3.new(42, 43, 44);
try expectEqual(expected, vec.abs());
}
{
const vec = Vec3.new(42, 43, 44);
const expected = Vec3.new(42, 43, 44);
try expectEqual(expected, vec.abs());
}
}
test "zalgebra.Vec3.at" {
const t = Vec3.new(10.0, -2.0, 0.0);
try expectEqual(t.at(0), 10.0);
try expectEqual(t.at(1), -2.0);
try expectEqual(t.at(2), 0.0);
}
test "zalgebra.Vec3.fromSlice" {
const array = [3]f32{ 2, 1, 4 };
try expectEqual(Vec3.eql(Vec3.fromSlice(&array), Vec3.new(2, 1, 4)), true);
}
test "zalgebra.Vec3.cast" {
const a = Vec3_i32.new(3, 6, 2);
const b = Vec3_usize.new(3, 6, 2);
try expectEqual(Vec3_usize.eql(a.cast(usize), b), true);
const c = Vec3.new(3.5, 6.5, 2.0);
const d = Vec3_f64.new(3.5, 6.5, 2);
try expectEqual(Vec3_f64.eql(c.cast(f64), d), true);
const e = Vec3_i32.new(3, 6, 2);
const f = Vec3.new(3.0, 6.0, 2.0);
try expectEqual(Vec3.eql(e.cast(f32), f), true);
const g = Vec3.new(3.0, 6.0, 2.0);
const h = Vec3_i32.new(3, 6, 2);
try expectEqual(Vec3_i32.eql(g.cast(i32), h), true);
} | src/vec3.zig |
const __fixsfti = @import("fixsfti.zig").__fixsfti;
const std = @import("std");
const math = std.math;
const testing = std.testing;
const warn = std.debug.warn;
fn test__fixsfti(a: f32, expected: i128) void {
const x = __fixsfti(a);
//warn("a={}:{x} x={}:{x} expected={}:{x}:@as(u128, {x})\n", .{a, @bitCast(u32, a), x, x, expected, expected, @bitCast(u128, expected)});
testing.expect(x == expected);
}
test "fixsfti" {
//warn("\n", .{});
test__fixsfti(-math.f32_max, math.minInt(i128));
test__fixsfti(-0x1.FFFFFFFFFFFFFp+1023, math.minInt(i128));
test__fixsfti(-0x1.FFFFFFFFFFFFFp+1023, -0x80000000000000000000000000000000);
test__fixsfti(-0x1.0000000000000p+127, -0x80000000000000000000000000000000);
test__fixsfti(-0x1.FFFFFFFFFFFFFp+126, -0x80000000000000000000000000000000);
test__fixsfti(-0x1.FFFFFFFFFFFFEp+126, -0x80000000000000000000000000000000);
test__fixsfti(-0x1.FFFFFF0000000p+126, -0x80000000000000000000000000000000);
test__fixsfti(-0x1.FFFFFE0000000p+126, -0x7FFFFF80000000000000000000000000);
test__fixsfti(-0x1.FFFFFC0000000p+126, -0x7FFFFF00000000000000000000000000);
test__fixsfti(-0x1.0000000000001p+63, -0x8000000000000000);
test__fixsfti(-0x1.0000000000000p+63, -0x8000000000000000);
test__fixsfti(-0x1.FFFFFFFFFFFFFp+62, -0x8000000000000000);
test__fixsfti(-0x1.FFFFFFFFFFFFEp+62, -0x8000000000000000);
test__fixsfti(-0x1.FFFFFFp+62, -0x8000000000000000);
test__fixsfti(-0x1.FFFFFEp+62, -0x7fffff8000000000);
test__fixsfti(-0x1.FFFFFCp+62, -0x7fffff0000000000);
test__fixsfti(-0x1.000000p+31, -0x80000000);
test__fixsfti(-0x1.FFFFFFp+30, -0x80000000);
test__fixsfti(-0x1.FFFFFEp+30, -0x7FFFFF80);
test__fixsfti(-0x1.FFFFFCp+30, -0x7FFFFF00);
test__fixsfti(-2.01, -2);
test__fixsfti(-2.0, -2);
test__fixsfti(-1.99, -1);
test__fixsfti(-1.0, -1);
test__fixsfti(-0.99, 0);
test__fixsfti(-0.5, 0);
test__fixsfti(-math.f32_min, 0);
test__fixsfti(0.0, 0);
test__fixsfti(math.f32_min, 0);
test__fixsfti(0.5, 0);
test__fixsfti(0.99, 0);
test__fixsfti(1.0, 1);
test__fixsfti(1.5, 1);
test__fixsfti(1.99, 1);
test__fixsfti(2.0, 2);
test__fixsfti(2.01, 2);
test__fixsfti(0x1.FFFFFCp+30, 0x7FFFFF00);
test__fixsfti(0x1.FFFFFEp+30, 0x7FFFFF80);
test__fixsfti(0x1.FFFFFFp+30, 0x80000000);
test__fixsfti(0x1.000000p+31, 0x80000000);
test__fixsfti(0x1.FFFFFCp+62, 0x7FFFFF0000000000);
test__fixsfti(0x1.FFFFFEp+62, 0x7FFFFF8000000000);
test__fixsfti(0x1.FFFFFFp+62, 0x8000000000000000);
test__fixsfti(0x1.FFFFFFFFFFFFEp+62, 0x8000000000000000);
test__fixsfti(0x1.FFFFFFFFFFFFFp+62, 0x8000000000000000);
test__fixsfti(0x1.0000000000000p+63, 0x8000000000000000);
test__fixsfti(0x1.0000000000001p+63, 0x8000000000000000);
test__fixsfti(0x1.FFFFFC0000000p+126, 0x7FFFFF00000000000000000000000000);
test__fixsfti(0x1.FFFFFE0000000p+126, 0x7FFFFF80000000000000000000000000);
test__fixsfti(0x1.FFFFFF0000000p+126, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
test__fixsfti(0x1.FFFFFFFFFFFFEp+126, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
test__fixsfti(0x1.FFFFFFFFFFFFFp+126, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
test__fixsfti(0x1.0000000000000p+127, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
test__fixsfti(0x1.FFFFFFFFFFFFFp+1023, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
test__fixsfti(0x1.FFFFFFFFFFFFFp+1023, math.maxInt(i128));
test__fixsfti(math.f32_max, math.maxInt(i128));
} | lib/std/special/compiler_rt/fixsfti_test.zig |
const std = @import("std");
const testing = std.testing;
const mimalloc_allocator = @import("main.zig").mimalloc_allocator;
test "allocate memory and free" {
const TestStruct = struct {
width: i32,
height: i32,
title: []const u8,
index: usize,
};
const memory: []TestStruct = mimalloc_allocator.alloc(TestStruct, 1)
catch @panic("test failure");
mimalloc_allocator.free(memory);
}
test "allocate memory, use it and free" {
const TestStruct = struct {
width: i32,
height: i32,
title: []const u8,
index: usize,
};
const memory: []TestStruct = mimalloc_allocator.alloc(TestStruct, 1)
catch @panic("test failure");
memory[0] = TestStruct{
.width = 1280,
.height = 720,
.title = "Should work fine!",
.index = 12,
};
try testing.expect(memory[0].width == 1280);
try testing.expect(memory[0].height == 720);
try testing.expect(memory[0].index == 12);
mimalloc_allocator.free(memory);
}
test "allocate memory, use it, reallocate memory, use it and free" {
const TestStruct = struct {
width: i32,
height: i32,
title: []const u8,
index: usize,
};
var memory: []TestStruct = mimalloc_allocator.alloc(TestStruct, 2)
catch @panic("test failure");
memory[0] = TestStruct{
.width = 1280,
.height = 720,
.title = "Should work fine!",
.index = 12,
};
memory[1] = TestStruct{
.width = 1230,
.height = 820,
.title = "Cool game",
.index = 120,
};
try testing.expect(memory[0].width == 1280);
try testing.expect(memory[0].height == 720);
try testing.expect(memory[0].index == 12);
try testing.expect(memory[1].width == 1230);
try testing.expect(memory[1].height == 820);
try testing.expect(memory[1].index == 120);
memory = mimalloc_allocator.realloc(memory, 4)
catch @panic("test failure");
memory[0] = TestStruct{
.width = 6122,
.height = 810,
.title = "Game",
.index = 99,
};
memory[1] = TestStruct{
.width = 728,
.height = 187,
.title = "Race game",
.index = 7,
};
memory[2] = TestStruct{
.width = 12612,
.height = 45,
.title = "Window title",
.index = 31,
};
memory[3] = TestStruct{
.width = 125,
.height = 1,
.title = "Game title",
.index = 21,
};
try testing.expect(memory[0].width == 6122);
try testing.expect(memory[0].height == 810);
try testing.expect(memory[0].index == 99);
try testing.expect(memory[1].width == 728);
try testing.expect(memory[1].height == 187);
try testing.expect(memory[1].index == 7);
try testing.expect(memory[2].width == 12612);
try testing.expect(memory[2].height == 45);
try testing.expect(memory[2].index == 31);
try testing.expect(memory[3].width == 125);
try testing.expect(memory[3].height == 1);
try testing.expect(memory[3].index == 21);
mimalloc_allocator.free(memory);
} | src/tests.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const expect = std.testing.expect;
pub fn DynamicArray(comptime T: type) type {
return struct {
const Self = @This();
count: usize,
capacity: usize,
items: []T,
allocator: *Allocator,
pub fn init(allocator: *Allocator) Self {
return Self{
.count = 0,
.capacity = 0,
.items = &[_]T{},
.allocator = allocator,
};
}
pub fn appendItem(self: *Self, item: T) void {
if (self.capacity < self.count + 1) {
self.capacity = growCapacity(self.capacity);
self.items = self.allocator.realloc(self.items, self.capacity) catch @panic("Error allocating new memory");
}
self.items[self.count] = item;
self.count += 1;
}
pub fn deinit(self: *Self) void {
if (self.capacity == 0) return;
self.allocator.free(self.items);
self.* = Self.init(self.allocator);
}
fn growCapacity(capacity: usize) usize {
return if (capacity < 8) 8 else capacity * 2;
}
};
}
test "create a DynamicArray" {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer {
const leaked = gpa.deinit();
if (leaked) expect(false) catch @panic("The list is leaking");
}
var arr = DynamicArray(u8).init(&gpa.allocator);
defer arr.deinit();
arr.appendItem(5);
try expect(arr.items[0] == 5);
try expect(arr.count == 1);
arr.appendItem(1);
arr.appendItem(2);
arr.appendItem(3);
arr.appendItem(4);
arr.appendItem(5);
arr.appendItem(6);
arr.appendItem(7);
arr.appendItem(8);
arr.appendItem(9);
arr.appendItem(10);
arr.appendItem(11);
arr.appendItem(12);
arr.appendItem(13);
arr.appendItem(14);
try expect(arr.items[10] == 10);
arr.deinit();
try expect(arr.count == 0);
try expect(arr.capacity == 0);
} | src/dynamic_array.zig |
export fn mission3_main() noreturn {
Bss.prepare();
Exceptions.prepare();
Uart.prepare();
Timer0.prepare();
Timer1.prepare();
Timer2.prepare();
LedMatrix.prepare();
ClockManagement.prepareHf();
CycleActivity.prepare();
TerminalActivity.prepare();
I2c0.prepare();
Accel.prepare();
while (true) {
CycleActivity.update();
TerminalActivity.update();
}
}
const Accel = struct {
fn prepare() void {
var data_buf: [0x32]u8 = undefined;
data_buf[orientation_configuration_register] = orientation_configuration_register_mask_enable;
I2c0.writeBlockingPanic(device_address, &data_buf, orientation_configuration_register, orientation_configuration_register);
data_buf[control_register1] = control_register1_mask_active;
I2c0.writeBlockingPanic(device_address, &data_buf, control_register1, control_register1);
}
fn update() void {
var data_buf: [32]u8 = undefined;
I2c0.readBlockingPanic(device_address, &data_buf, orientation_register, orientation_register);
const orientation = data_buf[orientation_register];
if (orientation & orientation_register_mask_changed != 0) {
format("orientation: 0x{x} ", .{orientation});
if (orientation & orientation_register_mask_forward_backward != 0) {
format("forward ", .{});
} else {
format("backward ", .{});
}
if (orientation & orientation_register_mask_z_lock_out != 0) {
log("up/down/left/right is unknown", .{});
} else {
const direction = (orientation & orientation_register_mask_direction) >> @ctz(u5, orientation_register_mask_direction);
switch (direction) {
0 => {
log("up", .{});
},
1 => {
log("down", .{});
},
2 => {
log("right", .{});
},
3 => {
log("left", .{});
},
else => {
unreachable;
},
}
}
}
}
const control_register1 = 0x2a;
const control_register1_mask_active = 0x01;
const device_address = 0x1d;
const orientation_register = 0x10;
const orientation_register_mask_changed = 0x80;
const orientation_register_mask_direction = 0x06;
const orientation_register_mask_forward_backward = 0x01;
const orientation_register_mask_z_lock_out = 0x40;
const orientation_configuration_register = 0x11;
const orientation_configuration_register_mask_enable = 0x40;
};
const CycleActivity = struct {
var cycle_counter: u32 = undefined;
var cycle_time: u32 = undefined;
var last_cycle_start: ?u32 = undefined;
var max_cycle_time: u32 = undefined;
var up_time_seconds: u32 = undefined;
var up_timer: TimeKeeper = undefined;
fn prepare() void {
cycle_counter = 0;
cycle_time = 0;
last_cycle_start = null;
max_cycle_time = 0;
up_time_seconds = 0;
up_timer.prepare(1000 * 1000);
}
fn update() void {
cycle_counter += 1;
const new_cycle_start = Timer0.capture();
if (last_cycle_start) |start| {
cycle_time = new_cycle_start -% start;
max_cycle_time = math.max(cycle_time, max_cycle_time);
}
last_cycle_start = new_cycle_start;
if (up_timer.isFinished()) {
up_timer.reset();
up_time_seconds += 1;
Accel.update();
}
}
};
const TerminalActivity = struct {
var keyboard_column: u32 = undefined;
var prev_now: u32 = undefined;
var temperature: u32 = 0;
fn prepare() void {
keyboard_column = 1;
prev_now = CycleActivity.up_time_seconds;
Temperature.tasks.start = 1;
redraw();
}
fn redraw() void {
Terminal.clearScreen();
Terminal.setScrollingRegion(5, 99);
Terminal.move(5 - 1, 1);
log("keyboard input will be echoed below:", .{});
Terminal.move(99, keyboard_column);
}
fn update() void {
if (Uart.isReadByteReady()) {
const byte = Uart.readByte();
switch (byte) {
3 => {
SystemControlBlock.requestSystemReset();
},
12 => {
redraw();
},
27 => {
Uart.writeByteBlocking('$');
keyboard_column += 1;
},
'\r' => {
Uart.writeText("\n");
keyboard_column = 1;
},
else => {
Uart.writeByteBlocking(byte);
keyboard_column += 1;
},
}
}
Uart.update();
if (Temperature.events.data_ready != 0) {
Temperature.events.data_ready = 0;
temperature = Temperature.registers.temperature;
}
const now = CycleActivity.up_time_seconds;
if (now >= prev_now + 1) {
Terminal.hideCursor();
Terminal.move(1, 1);
Terminal.line("up {:3}s cycle {}us max {}us {}.{}C", .{ CycleActivity.up_time_seconds, CycleActivity.cycle_time, CycleActivity.max_cycle_time, temperature / 4, temperature % 4 * 25 });
Terminal.showCursor();
Terminal.move(99, keyboard_column);
prev_now = now;
}
}
};
comptime {
const mission_id = 3;
asm (typicalVectorTable(mission_id));
}
usingnamespace @import("lib_basics.zig").typical; | mission3_sensors.zig |
const std = @import("std");
const c = @import("c.zig");
const util = @import("util.zig");
// TODO: calculate this whole error and function below at comptime
const CompilationError = error{
// Success = 0
InvalidStage,
CompilationError,
InternalError,
NullResultObject,
InvalidAssembly,
ValidationError,
TransformationError,
ConfigurationError,
UnknownError,
};
fn status_to_err(i: c_int) CompilationError {
switch (i) {
c.shaderc_compilation_status_invalid_stage => return CompilationError.InvalidStage,
c.shaderc_compilation_status_compilation_error => return CompilationError.CompilationError,
c.shaderc_compilation_status_internal_error => return CompilationError.InternalError,
c.shaderc_compilation_status_null_result_object => return CompilationError.NullResultObject,
c.shaderc_compilation_status_invalid_assembly => return CompilationError.InvalidAssembly,
c.shaderc_compilation_status_validation_error => return CompilationError.ValidationError,
c.shaderc_compilation_status_transformation_error => return CompilationError.TransformationError,
c.shaderc_compilation_status_configuration_error => return CompilationError.ConfigurationError,
else => return CompilationError.UnknownError,
}
}
export fn include_cb(user_data: ?*c_void, requested_source: [*c]const u8, include_type: c_int, requesting_source: [*c]const u8, include_depth: usize) *c.shaderc_include_result {
const alloc = @ptrCast(*std.mem.Allocator, @alignCast(8, user_data));
var out = alloc.create(c.shaderc_include_result) catch |err| {
std.debug.panic("Could not allocate shaderc_include_result: {}", .{err});
};
out.* = (c.shaderc_include_result){
.user_data = user_data,
.source_name = "",
.source_name_length = 0,
.content = null,
.content_length = 0,
};
const name = std.mem.spanZ(requested_source);
const file = std.fs.cwd().openFile(name, std.fs.File.OpenFlags{ .read = true }) catch |err| {
const msg = std.fmt.allocPrint(alloc, "{}", .{err}) catch |err2| {
std.debug.panic("Could not allocate error message: {}", .{err2});
};
out.content = msg.ptr;
out.content_length = msg.len;
return out;
};
const size = file.getEndPos() catch |err| {
std.debug.panic("Could not get end position of file: {}", .{err});
};
const buf = alloc.alloc(u8, size) catch |err| {
std.debug.panic("Could not allocate space for data: {}", .{err});
};
_ = file.readAll(buf) catch |err| {
std.debug.panic("Could not read header: {}", .{err});
};
out.source_name = requested_source;
out.source_name_length = name.len;
out.content = buf.ptr;
out.content_length = buf.len;
return out;
}
export fn include_release_cb(user_data: ?*c_void, include_result: ?*c.shaderc_include_result) void {
if (include_result != null) {
const alloc = @ptrCast(*std.mem.Allocator, @alignCast(8, user_data));
const r = @ptrCast(*c.shaderc_include_result, include_result);
if (r.*.content != null) {
alloc.destroy(r.*.content);
}
alloc.destroy(r);
}
}
pub fn build_shader_from_file(alloc: *std.mem.Allocator, comptime name: []const u8) ![]u32 {
const buf = try util.file_contents(alloc, name);
return build_shader(alloc, name, buf);
}
pub fn build_shader(alloc: *std.mem.Allocator, name: []const u8, src: []const u8) ![]u32 {
const compiler = c.shaderc_compiler_initialize();
defer c.shaderc_compiler_release(compiler);
const options = c.shaderc_compile_options_initialize();
defer c.shaderc_compile_options_release(options);
c.shaderc_compile_options_set_include_callbacks(options, include_cb, include_release_cb, alloc);
const result = c.shaderc_compile_into_spv(
compiler,
src.ptr,
src.len,
c.shaderc_shader_kind.shaderc_glsl_infer_from_source,
name.ptr,
"main",
options,
);
defer c.shaderc_result_release(result);
const r = c.shaderc_result_get_compilation_status(result);
if (@enumToInt(r) != c.shaderc_compilation_status_success) {
const err = c.shaderc_result_get_error_message(result);
std.debug.warn("Shader error: {} {s}\n", .{ r, err });
return status_to_err(@enumToInt(r));
}
// Copy the result out of the shader
const len = c.shaderc_result_get_length(result);
std.debug.assert(len % 4 == 0);
const out = alloc.alloc(u32, len / 4) catch unreachable;
@memcpy(@ptrCast([*]u8, out.ptr), c.shaderc_result_get_bytes(result), len);
return out;
}
////////////////////////////////////////////////////////////////////////////////
pub const LineErr = struct {
msg: []const u8,
line: ?u32,
};
pub const Error = struct {
errs: []const LineErr,
code: c.shaderc_compilation_status,
};
pub const Shader = struct {
spirv: []const u32,
has_time: bool,
};
pub const Result = union(enum) {
Shader: Shader,
Error: Error,
pub fn deinit(self: Result, alloc: *std.mem.Allocator) void {
switch (self) {
.Shader => |d| alloc.free(d.spirv),
.Error => |e| {
for (e.errs) |r| {
alloc.free(r.msg);
}
alloc.free(e.errs);
},
}
}
};
pub fn build_preview_shader(
alloc: *std.mem.Allocator,
compiler: c.shaderc_compiler_t,
src: []const u8,
) !Result {
// Load the standard fragment shader prelude from a file
// (or embed in the source if this is a release build)
var arena = std.heap.ArenaAllocator.init(alloc);
var tmp_alloc: *std.mem.Allocator = &arena.allocator;
defer arena.deinit();
const prelude = try util.file_contents(
tmp_alloc,
"shaders/preview.prelude.frag",
);
const full_src = try tmp_alloc.alloc(u8, prelude.len + src.len);
std.mem.copy(u8, full_src, prelude);
std.mem.copy(u8, full_src[prelude.len..], src);
const options = c.shaderc_compile_options_initialize();
c.shaderc_compile_options_set_include_callbacks(
options,
include_cb,
include_release_cb,
alloc,
);
defer c.shaderc_compile_options_release(options);
const result = c.shaderc_compile_into_spv(
compiler,
full_src.ptr,
full_src.len,
c.shaderc_shader_kind.shaderc_glsl_fragment_shader,
"preview",
"main",
options,
);
defer c.shaderc_result_release(result);
const r = c.shaderc_result_get_compilation_status(result);
if (@enumToInt(r) != c.shaderc_compilation_status_success) {
var start: usize = 0;
var prelude_newlines: u32 = 0;
while (std.mem.indexOf(u8, prelude[start..], "\n")) |end| {
prelude_newlines += 1;
start += end + 1;
}
// Copy the error out of the shader
const err_msg = c.shaderc_result_get_error_message(result);
const len = std.mem.len(err_msg);
const out = try tmp_alloc.alloc(u8, len);
@memcpy(out.ptr, err_msg, len);
// Prase out individual lines of the error message, figuring out
// which ones have a line number attached.
start = 0;
var errs = std.ArrayList(LineErr).init(alloc);
while (std.mem.indexOf(u8, out[start..], "\n")) |end| {
const line = out[start..(start + end)];
start += end + 1;
const num_start = std.mem.indexOf(u8, line, ":") orelse std.debug.panic(
"Could not find ':' in error message",
.{},
);
const num_end = num_start + 1 + (std.mem.indexOf(
u8,
line[(num_start + 1)..],
" ",
) orelse std.debug.panic("Could not find ':' in error message", .{}));
if (num_end >= num_start + 2) {
// Error message with line attached
var line_num = try std.fmt.parseInt(u32, line[(num_start + 1)..(num_end - 1)], 10);
line_num = if (line_num < prelude_newlines) 1 else (line_num - prelude_newlines);
const line_msg = try alloc.dupe(u8, line[(num_end + 1)..]);
try errs.append(.{
.msg = line_msg,
.line = line_num,
});
} else {
const line_msg = try alloc.dupe(u8, line[(num_start + 2)..]);
try errs.append(.{
.msg = line_msg,
.line = null,
});
}
}
return Result{ .Error = .{ .errs = errs.toOwnedSlice(), .code = r } };
} else {
// Copy the result out of the shader
const len = c.shaderc_result_get_length(result);
std.debug.assert(len % 4 == 0);
const out = try alloc.alloc(u32, len / 4);
@memcpy(@ptrCast([*]u8, out.ptr), c.shaderc_result_get_bytes(result), len);
// Find the text "iTime" in the script, then walk backwards until you
// see the either the beginning of the line or a comment (//)
//
// This prevents the template from running, though folks could still
// put iTime into a /* ... */ block, which would falsely trigger
// continously-running mode.
var has_time = false;
var start: usize = 0;
while (std.mem.indexOf(u8, src[start..], "iTime")) |next| {
has_time = true;
var i = next;
while (i > 0) : (i -= 1) {
if (src[start + i] == '\n') {
break;
} else if (src[start + i - 1] == '/' and src[start + i] == '/') {
has_time = false;
break;
}
}
if (has_time) {
break;
}
start += next + 1;
}
return Result{
.Shader = .{ .spirv = out, .has_time = has_time },
};
}
} | src/shaderc.zig |
const std = @import("std");
const path = std.fs.path;
const lexer = @import("lexer.zig");
const parser = @import("parser.zig");
const errors = @import("errors.zig");
pub const ProcessDetails = struct { included_files: [][]const u8 };
pub fn process(
alloc: std.mem.Allocator,
tokens: []const lexer.Token,
raw_data: []const u8,
filename: []const u8,
included_files: *std.ArrayList([]const u8),
completed_tokens: *std.ArrayList(parser.Token),
) anyerror![]parser.Token {
const containing_dir_path = path.dirname(filename);
var containing_dir = std.fs.cwd();
if (containing_dir_path) |dir| {
containing_dir = try containing_dir.openDir(dir, .{});
}
var last_token: lexer.Token = undefined;
for (tokens) |t| {
try process_token(
t,
last_token,
raw_data,
alloc,
included_files,
completed_tokens,
containing_dir,
// containing_dir_path,
) catch |err| switch (err) {
error.FileNotFound => errors.executor_panic("Unable to preproc file due to preproc @use statement not finding file. Try checking the spelling. File failed on: ", filename),
else => err,
};
last_token = t;
}
try completed_tokens.appendSlice(try parser.parseTokens(alloc, tokens, raw_data));
try completed_tokens.append(parser.Token{ .start = 0, .id = .Eof, .data = .{ .single_token = 0 } });
return completed_tokens.toOwnedSlice();
}
fn process_token(
token: lexer.Token,
last_token: lexer.Token,
raw_data: []const u8,
alloc: std.mem.Allocator,
included_files: *std.ArrayList([]const u8),
completed_tokens: *std.ArrayList(parser.Token),
src_directory: std.fs.Dir,
// src_directory_path: []const u8,
) anyerror!void {
switch (token.id) {
.Atom => if (last_token.id == .PreProcUse) {
std.debug.print("PREPROC GLOBAL: {s}\n", .{raw_data[token.start..token.end]});
@panic("Unimplemented.");
},
.String => if (last_token.id == .PreProcUse) {
const to_import = raw_data[token.start + 1 .. token.end - 1];
for (included_files.items) |f| {
if (std.mem.eql(u8, f, to_import)) {
return;
}
}
var buffer = try alloc.create([8192]u8);
var source = try src_directory.openFile(to_import, .{}) catch |err| switch (err) {
error.FileNotFound => errors.executor_panic("Unable to find file", to_import),
else => err,
};
defer source.close();
var bytes_read = try source.readAll(buffer);
var complete_src = buffer[0..bytes_read];
var lexed_tokens = try lexer.tokenize(alloc, complete_src);
const file_contains_preproc = contains_preproc(lexed_tokens);
if (file_contains_preproc) {
var last_token_nested: lexer.Token = undefined;
var relative_dir_path = path.dirname(to_import);
var relative_dir = src_directory;
if (relative_dir_path) |relative_dir_path_exist| {
relative_dir = try src_directory.openDir(relative_dir_path_exist, .{});
}
for (lexed_tokens) |t| {
try process_token(
t,
last_token_nested,
complete_src,
alloc,
included_files,
completed_tokens,
relative_dir,
);
last_token_nested = t;
}
}
var parsed_tokens = try parser.parseTokens(alloc, lexed_tokens, complete_src);
try included_files.*.append(to_import);
try completed_tokens.*.appendSlice(parsed_tokens);
},
else => {},
}
}
fn contains_preproc(tokens: []const lexer.Token) bool {
for (tokens) |t| {
if (t.id == .PreProcUse) {
return true;
}
}
return false;
} | src/preproc.zig |
const std = @import("std");
const upaya = @import("upaya");
const ts = @import("../tilescript.zig");
usingnamespace @import("imgui");
var buffer: [5]u8 = undefined;
var inspected_object_index: ?usize = null;
pub fn draw(state: *ts.AppState) void {
if (state.prefs.windows.object_editor) {
igPushStyleVarVec2(ImGuiStyleVar_WindowMinSize, ImVec2{ .x = 200, .y = 100 });
defer igPopStyleVar(1);
_ = igBegin("Object Editor", &state.prefs.windows.object_editor, ImGuiWindowFlags_None);
defer igEnd();
if (igBeginChildEx("##obj-editor-child", igGetItemID(), ImVec2{ .y = -igGetFrameHeightWithSpacing() }, false, ImGuiWindowFlags_None)) {
defer igEndChild();
if (inspected_object_index) |obj_index| {
var obj = &state.map.objects.items[obj_index];
igPushItemWidth(igGetWindowContentRegionWidth());
if (ogInputText("##name", &obj.name, obj.name.len)) {}
igPopItemWidth();
_ = ogDrag(usize, "Tile X", &obj.x, 0.5, 0, state.map.w - 1);
_ = ogDrag(usize, "Tile Y", &obj.y, 0.5, 0, state.map.h - 1);
igSeparator();
// custom properties
var delete_index: usize = std.math.maxInt(usize);
for (obj.props.items) |*prop, i| {
igPushIDPtr(prop);
igPushItemWidth(igGetWindowContentRegionWidth() / 2 - 15);
if (ogInputText("##key", &prop.name, prop.name.len)) {}
igSameLine(0, 5);
switch (prop.value) {
.string => |*str| {
_ = ogInputText("##value", str, str.len);
},
.float => |*flt| {
_ = ogDragSigned(f32, "##flt", flt, 1, std.math.minInt(i32), std.math.maxInt(i32));
},
.int => |*int| {
_ = ogDragSigned(i32, "##int", int, 1, std.math.minInt(i32), std.math.maxInt(i32));
},
.link => |linked_id| {
igPushItemFlag(ImGuiItemFlags_Disabled, true);
igPushStyleVarFloat(ImGuiStyleVar_Alpha, 0.5);
_ = std.fmt.bufPrint(&buffer, "${}", .{linked_id}) catch unreachable;
_ = ogInputText("##value", &buffer, buffer.len);
igPopItemFlag();
igPopStyleVar(1);
},
}
igSameLine(0, 5);
igPopItemWidth();
igSameLine(0, 5);
if (ogButton(icons.trash)) {
delete_index = i;
}
igPopID();
}
if (delete_index < std.math.maxInt(usize)) {
_ = obj.props.orderedRemove(delete_index);
}
}
}
if (inspected_object_index == null) {
igPushItemFlag(ImGuiItemFlags_Disabled, true);
igPushStyleVarFloat(ImGuiStyleVar_Alpha, 0.5);
}
if (igButton("Add Property", ImVec2{})) {
igOpenPopup("##add-property");
}
if (inspected_object_index == null) {
igPopItemFlag();
igPopStyleVar(1);
}
igSetNextWindowPos(igGetIO().MousePos, ImGuiCond_Appearing, .{ .x = 0.5 });
if (igBeginPopup("##add-property", ImGuiWindowFlags_None)) {
addPropertyPopup(state);
igEndPopup();
}
}
}
fn addPropertyPopup(state: *ts.AppState) void {
igText("Property Type");
if (igButton("string", ImVec2{ .x = 100 })) {
state.map.objects.items[inspected_object_index.?].addProp(.{ .string = undefined });
igCloseCurrentPopup();
}
if (igButton("float", ImVec2{ .x = 100 })) {
state.map.objects.items[inspected_object_index.?].addProp(.{ .float = undefined });
igCloseCurrentPopup();
}
if (igButton("int", ImVec2{ .x = 100 })) {
state.map.objects.items[inspected_object_index.?].addProp(.{ .int = undefined });
igCloseCurrentPopup();
}
}
pub fn setSelectedObject(index: ?usize) void {
inspected_object_index = index;
} | tilescript/windows/object_editor.zig |
usingnamespace @import("../engine/engine.zig");
const std = @import("std");
const testing = std.testing;
const mem = std.mem;
pub const AlwaysVoid = struct {
pub fn deinit(self: *const @This(), allocator: *mem.Allocator) void {}
};
/// If the result is not `null`, its `.offset` value will be updated to reflect the current parse
/// position before Always returns it.
pub fn AlwaysContext(comptime Value: type) type {
return ?Result(Value);
}
/// Always yields the input value (once/unambiguously), or no value (if the input value is null).
///
/// The `input` value is taken ownership of by the parser, and deinitialized once the parser is.
pub fn Always(comptime Payload: type, comptime Value: type) type {
return struct {
parser: Parser(Payload, Value) = Parser(Payload, Value).init(parse, nodeName, deinit),
input: AlwaysContext(Value),
const Self = @This();
pub fn init(input: AlwaysContext(Value)) Self {
return Self{ .input = input };
}
pub fn deinit(parser: *Parser(Payload, Value), allocator: *mem.Allocator) void {
const self = @fieldParentPtr(Self, "parser", parser);
if (self.input) |input| input.deinit(allocator);
}
pub fn nodeName(parser: *const Parser(Payload, Value), node_name_cache: *std.AutoHashMap(usize, ParserNodeName)) Error!u64 {
const self = @fieldParentPtr(Self, "parser", parser);
var v = std.hash_map.hashString("Always");
v +%= std.hash_map.getAutoHashFn(?Result(Value), void)({}, self.input);
return v;
}
pub fn parse(parser: *const Parser(Payload, Value), in_ctx: *const Context(Payload, Value)) callconv(.Async) Error!void {
const self = @fieldParentPtr(Self, "parser", parser);
var ctx = in_ctx.with(self.input);
defer ctx.results.close();
if (self.input) |input| {
var tmp = input.toUnowned();
tmp.offset = ctx.offset;
try ctx.results.add(tmp);
}
}
};
}
test "always" {
nosuspend {
const allocator = testing.allocator;
const Payload = void;
const ctx = try Context(Payload, AlwaysVoid).init(allocator, "hello world", {});
defer ctx.deinit();
const noop = Always(Payload, AlwaysVoid).init(null);
try noop.parser.parse(&ctx);
var sub = ctx.subscribe();
try testing.expect(sub.next() == null);
}
} | src/combn/combinator/always.zig |
const std = @import("std");
const Span = @import("basics.zig").Span;
pub const InterpolationFunction = enum {
linear,
smoothstep,
};
pub const CurveNode = struct {
value: f32,
t: f32,
};
// curves are like notes except the value will be interpolated in between them.
// they can't be created in real-time
const CurveSpanNode = struct {
frame: i32, // frames (e.g. 44100 for one second in)
value: f32,
};
const CurveSpanValues = struct {
start_node: CurveSpanNode,
end_node: CurveSpanNode,
};
const CurveSpan = struct {
start: usize,
end: usize,
values: ?CurveSpanValues, // if null, this is a silent gap between curves
};
pub const Curve = struct {
pub const num_outputs = 1;
pub const num_temps = 0;
pub const Params = struct {
sample_rate: f32,
function: InterpolationFunction,
curve: []const CurveNode,
};
// progress through the curve, in seconds
t: f32,
// some state to make it faster to continue painting. note: this relies on
// the curve param not being mutated by the caller
current_song_note: usize,
current_song_note_offset: i32,
next_song_note: usize,
// this is just some memory set aside for temporary use during a paint
// call. it could just as easily be a stack local
curve_nodes: [32]CurveSpanNode,
pub fn init() Curve {
return .{
.current_song_note = 0,
.current_song_note_offset = 0,
.next_song_note = 0,
.t = 0.0,
.curve_nodes = undefined,
};
}
pub fn paint(
self: *Curve,
span: Span,
outputs: [num_outputs][]f32,
temps: [num_temps][]f32,
note_id_changed: bool,
params: Params,
) void {
if (note_id_changed) {
self.current_song_note = 0;
self.current_song_note_offset = 0;
self.next_song_note = 0;
self.t = 0.0;
}
const out = outputs[0][span.start..span.end];
const curve_nodes = self.getCurveSpanNodes(params.sample_rate, out.len, params.curve);
var start: usize = 0;
while (start < out.len) {
const curve_span = getNextCurveSpan(curve_nodes, start, out.len);
const paint_start = @intCast(i32, curve_span.start);
const paint_end = @intCast(i32, curve_span.end);
if (curve_span.values) |values| {
// the full range between nodes
const fstart = values.start_node.frame;
const fend = values.end_node.frame;
// std.debug.assert(fstart < fend);
// std.debug.assert(fstart <= paint_start);
// std.debug.assert(curve_span.start < paint_end);
// std.debug.assert(curve_span.end <= fend);
// 'x' values are 0-1
const start_x = @intToFloat(f32, paint_start - fstart) / @intToFloat(f32, fend - fstart);
const start_value = values.start_node.value;
const value_delta = values.end_node.value - values.start_node.value;
const x_step = 1.0 / @intToFloat(f32, fend - fstart);
var i: usize = curve_span.start;
switch (params.function) {
.linear => {
var y = start_value + start_x * value_delta;
var y_step = x_step * value_delta;
while (i < curve_span.end) : (i += 1) {
out[i] += y;
y += y_step;
}
},
.smoothstep => {
var x = start_x;
while (i < curve_span.end) : (i += 1) {
const v = x * x * (3.0 - 2.0 * x) * value_delta;
out[i] += start_value + v;
x += x_step;
}
},
}
}
start = curve_span.end;
}
}
fn getCurveSpanNodes(
self: *Curve,
sample_rate: f32,
out_len: usize,
curve_nodes: []const CurveNode,
) []CurveSpanNode {
var count: usize = 0;
const buf_time = @intToFloat(f32, out_len) / sample_rate;
const end_t = self.t + buf_time;
// add a note that was begun in a previous frame
if (self.current_song_note < self.next_song_note) {
self.curve_nodes[count] = .{
.frame = self.current_song_note_offset,
.value = curve_nodes[self.current_song_note].value,
};
count += 1;
}
var one_past = false;
for (curve_nodes[self.next_song_note..]) |song_note| {
const note_t = song_note.t;
if (note_t >= end_t) {
// keep one note past the end
if (!one_past) {
one_past = true;
} else {
break;
}
}
const f = (note_t - self.t) / buf_time; // 0 to 1
const rel_frame_index = @floatToInt(i32, f * @intToFloat(f32, out_len));
// if there's already a note at this frame (from the previous note
// carry-over), this should overwrite that one
if (count > 0 and self.curve_nodes[count - 1].frame == rel_frame_index) {
count -= 1;
}
self.curve_nodes[count] = .{
.frame = rel_frame_index,
.value = song_note.value,
};
count += 1;
if (!one_past) {
self.current_song_note = self.next_song_note;
self.current_song_note_offset = 0;
self.next_song_note += 1;
}
}
self.t += buf_time;
self.current_song_note_offset -= @intCast(i32, out_len);
return self.curve_nodes[0..count];
}
};
// note: will possibly emit an end node past the end of the buffer (necessary
// for interpolation)
fn getNextCurveSpan(curve_nodes: []const CurveSpanNode, dest_start_: usize, dest_end_: usize) CurveSpan {
std.debug.assert(dest_start_ < dest_end_);
const dest_start = @intCast(i32, dest_start_);
const dest_end = @intCast(i32, dest_end_);
for (curve_nodes) |curve_node, i| {
const start_pos = curve_node.frame;
if (start_pos >= dest_end) {
// this curve_node (and all after it, since they're in
// chronological order) starts after the end of the buffer
break;
}
// this span ends at the start of the next curve_node (if one exists),
// or the end of the buffer, whichever comes first
const end_pos = if (i < curve_nodes.len - 1)
std.math.min(dest_end, curve_nodes[i + 1].frame)
else
dest_end;
if (end_pos <= dest_start) {
// curve_node is entirely in the past. skip it
continue;
}
const note_start_clipped = if (start_pos > dest_start)
start_pos
else
dest_start;
if (note_start_clipped > dest_start) {
// gap before the note begins
return .{
.start = @intCast(usize, dest_start),
.end = @intCast(usize, note_start_clipped),
.values = null,
};
}
const note_end = end_pos;
const note_end_clipped = if (note_end > dest_end)
dest_end
else
note_end;
return .{
.start = @intCast(usize, note_start_clipped),
.end = @intCast(usize, note_end_clipped),
.values = if (i < curve_nodes.len - 1)
CurveSpanValues{
.start_node = curve_node,
.end_node = curve_nodes[i + 1],
}
else
null,
};
}
std.debug.assert(dest_start < dest_end);
return .{
.start = @intCast(usize, dest_start),
.end = @intCast(usize, dest_end),
.values = null,
};
} | src/zang/mod_curve.zig |
const std = @import("std");
pub fn main() anyerror!void {
std.log.info("All your codebase are belong to us.", .{});
}
const expect = @import("std").testing.expect;
const mem = @import("std").mem;
// Declare an enum.
const Type = enum {
ok,
not_ok,
};
// Declare a specific instance of the enum variant.
const c = Type.ok;
// If you want access to the ordinal value of an enum, you
// can specify the tag type.
const Value = enum(u2) {
zero,
one,
two,
};
// Now you can cast between u2 and Value.
// The ordinal value starts from 0, counting up for each member.
test "enum ordinal value" {
try expect(@enumToInt(Value.zero) == 0);
try expect(@enumToInt(Value.one) == 1);
try expect(@enumToInt(Value.two) == 2);
}
// You can override the ordinal value for an enum.
const Value2 = enum(u32) {
hundred = 100,
thousand = 1000,
million = 1000000,
};
test "set enum ordinal value" {
try expect(@enumToInt(Value2.hundred) == 100);
try expect(@enumToInt(Value2.thousand) == 1000);
try expect(@enumToInt(Value2.million) == 1000000);
}
// Enums can have methods, the same as structs and unions.
// Enum methods are not special, they are only namespaced
// functions that you can call with dot syntax.
const Suit = enum {
clubs,
spades,
diamonds,
hearts,
pub fn isClubs(self: Suit) bool {
return self == Suit.clubs;
}
};
test "enum method" {
const p = Suit.spades;
try expect(!p.isClubs());
}
// An enum variant of different types can be switched upon.
const Foo = enum {
string,
number,
none,
};
test "enum variant switch" {
const p = Foo.number;
const what_is_it = switch (p) {
Foo.string => "this is a string",
Foo.number => "this is a number",
Foo.none => "this is a none",
};
try expect(mem.eql(u8, what_is_it, "this is a number"));
}
// @typeInfo can be used to access the integer tag type of an enum.
const Small = enum {
one,
two,
three,
four,
};
test "std.meta.Tag" {
try expect(@typeInfo(Small).Enum.tag_type == u2);
}
// @typeInfo tells us the field count and the fields names:
test "@typeInfo" {
try expect(@typeInfo(Small).Enum.fields.len == 4);
try expect(mem.eql(u8, @typeInfo(Small).Enum.fields[1].name, "two"));
}
// @tagName gives a []const u8 representation of an enum value:
test "@tagName" {
try expect(mem.eql(u8, @tagName(Small.three), "three"));
} | enums/src/main.zig |
pub const WLDP_LOCKDOWN_UNDEFINED = @as(u32, 0);
pub const WLDP_LOCKDOWN_DEFINED_FLAG = @as(u32, 2147483648);
pub const WLDP_LOCKDOWN_CONFIG_CI_FLAG = @as(u32, 1);
pub const WLDP_LOCKDOWN_CONFIG_CI_AUDIT_FLAG = @as(u32, 2);
pub const WLDP_LOCKDOWN_UMCIENFORCE_FLAG = @as(u32, 4);
pub const WLDP_LOCKDOWN_AUDIT_FLAG = @as(u32, 8);
pub const WLDP_LOCKDOWN_EXCLUSION_FLAG = @as(u32, 16);
pub const WLDP_LOCKDOWN_OFF = @as(u32, 2147483648);
pub const WLDP_HOST_INFORMATION_REVISION = @as(u32, 1);
pub const WLDP_FLAGS_SKIPSIGNATUREVALIDATION = @as(u32, 256);
pub const MAX_TDI_ENTITIES = @as(u32, 4096);
pub const INFO_CLASS_GENERIC = @as(u32, 256);
pub const INFO_CLASS_PROTOCOL = @as(u32, 512);
pub const INFO_CLASS_IMPLEMENTATION = @as(u32, 768);
pub const INFO_TYPE_PROVIDER = @as(u32, 256);
pub const INFO_TYPE_ADDRESS_OBJECT = @as(u32, 512);
pub const INFO_TYPE_CONNECTION = @as(u32, 768);
pub const ENTITY_LIST_ID = @as(u32, 0);
pub const INVALID_ENTITY_INSTANCE = @as(i32, -1);
pub const CONTEXT_SIZE = @as(u32, 16);
pub const ENTITY_TYPE_ID = @as(u32, 1);
pub const CO_TL_NBF = @as(u32, 1024);
pub const CO_TL_SPX = @as(u32, 1026);
pub const CO_TL_TCP = @as(u32, 1028);
pub const CO_TL_SPP = @as(u32, 1030);
pub const CL_TL_NBF = @as(u32, 1025);
pub const CL_TL_UDP = @as(u32, 1027);
pub const ER_ICMP = @as(u32, 896);
pub const CL_NL_IPX = @as(u32, 769);
pub const CL_NL_IP = @as(u32, 771);
pub const AT_ARP = @as(u32, 640);
pub const AT_NULL = @as(u32, 642);
pub const IF_GENERIC = @as(u32, 512);
pub const IF_MIB = @as(u32, 514);
pub const IOCTL_TDI_TL_IO_CONTROL_ENDPOINT = @as(u32, 2162744);
pub const DCI_VERSION = @as(u32, 256);
pub const DCICREATEPRIMARYSURFACE = @as(u32, 1);
pub const DCICREATEOFFSCREENSURFACE = @as(u32, 2);
pub const DCICREATEOVERLAYSURFACE = @as(u32, 3);
pub const DCIENUMSURFACE = @as(u32, 4);
pub const DCIESCAPE = @as(u32, 5);
pub const DCI_OK = @as(u32, 0);
pub const DCI_FAIL_GENERIC = @as(i32, -1);
pub const DCI_FAIL_UNSUPPORTEDVERSION = @as(i32, -2);
pub const DCI_FAIL_INVALIDSURFACE = @as(i32, -3);
pub const DCI_FAIL_UNSUPPORTED = @as(i32, -4);
pub const DCI_ERR_CURRENTLYNOTAVAIL = @as(i32, -5);
pub const DCI_ERR_INVALIDRECT = @as(i32, -6);
pub const DCI_ERR_UNSUPPORTEDFORMAT = @as(i32, -7);
pub const DCI_ERR_UNSUPPORTEDMASK = @as(i32, -8);
pub const DCI_ERR_TOOBIGHEIGHT = @as(i32, -9);
pub const DCI_ERR_TOOBIGWIDTH = @as(i32, -10);
pub const DCI_ERR_TOOBIGSIZE = @as(i32, -11);
pub const DCI_ERR_OUTOFMEMORY = @as(i32, -12);
pub const DCI_ERR_INVALIDPOSITION = @as(i32, -13);
pub const DCI_ERR_INVALIDSTRETCH = @as(i32, -14);
pub const DCI_ERR_INVALIDCLIPLIST = @as(i32, -15);
pub const DCI_ERR_SURFACEISOBSCURED = @as(i32, -16);
pub const DCI_ERR_XALIGN = @as(i32, -17);
pub const DCI_ERR_YALIGN = @as(i32, -18);
pub const DCI_ERR_XYALIGN = @as(i32, -19);
pub const DCI_ERR_WIDTHALIGN = @as(i32, -20);
pub const DCI_ERR_HEIGHTALIGN = @as(i32, -21);
pub const DCI_STATUS_POINTERCHANGED = @as(u32, 1);
pub const DCI_STATUS_STRIDECHANGED = @as(u32, 2);
pub const DCI_STATUS_FORMATCHANGED = @as(u32, 4);
pub const DCI_STATUS_SURFACEINFOCHANGED = @as(u32, 8);
pub const DCI_STATUS_CHROMAKEYCHANGED = @as(u32, 16);
pub const DCI_STATUS_WASSTILLDRAWING = @as(u32, 32);
pub const DCI_SURFACE_TYPE = @as(u32, 15);
pub const DCI_PRIMARY = @as(u32, 0);
pub const DCI_OFFSCREEN = @as(u32, 1);
pub const DCI_OVERLAY = @as(u32, 2);
pub const DCI_VISIBLE = @as(u32, 16);
pub const DCI_CHROMAKEY = @as(u32, 32);
pub const DCI_1632_ACCESS = @as(u32, 64);
pub const DCI_DWORDSIZE = @as(u32, 128);
pub const DCI_DWORDALIGN = @as(u32, 256);
pub const DCI_WRITEONLY = @as(u32, 512);
pub const DCI_ASYNC = @as(u32, 1024);
pub const DCI_CAN_STRETCHX = @as(u32, 4096);
pub const DCI_CAN_STRETCHY = @as(u32, 8192);
pub const DCI_CAN_STRETCHXN = @as(u32, 16384);
pub const DCI_CAN_STRETCHYN = @as(u32, 32768);
pub const DCI_CANOVERLAY = @as(u32, 65536);
pub const FILE_FLAG_OPEN_REQUIRING_OPLOCK = @as(u32, 262144);
pub const PROGRESS_CONTINUE = @as(u32, 0);
pub const PROGRESS_CANCEL = @as(u32, 1);
pub const PROGRESS_STOP = @as(u32, 2);
pub const PROGRESS_QUIET = @as(u32, 3);
pub const COPY_FILE_FAIL_IF_EXISTS = @as(u32, 1);
pub const COPY_FILE_RESTARTABLE = @as(u32, 2);
pub const COPY_FILE_OPEN_SOURCE_FOR_WRITE = @as(u32, 4);
pub const COPY_FILE_ALLOW_DECRYPTED_DESTINATION = @as(u32, 8);
pub const COPY_FILE_COPY_SYMLINK = @as(u32, 2048);
pub const COPY_FILE_NO_BUFFERING = @as(u32, 4096);
pub const COPY_FILE_REQUEST_SECURITY_PRIVILEGES = @as(u32, 8192);
pub const COPY_FILE_RESUME_FROM_PAUSE = @as(u32, 16384);
pub const COPY_FILE_NO_OFFLOAD = @as(u32, 262144);
pub const COPY_FILE_IGNORE_EDP_BLOCK = @as(u32, 4194304);
pub const COPY_FILE_IGNORE_SOURCE_ENCRYPTION = @as(u32, 8388608);
pub const COPY_FILE_DONT_REQUEST_DEST_WRITE_DAC = @as(u32, 33554432);
pub const COPY_FILE_REQUEST_COMPRESSED_TRAFFIC = @as(u32, 268435456);
pub const COPY_FILE_OPEN_AND_COPY_REPARSE_POINT = @as(u32, 2097152);
pub const COPY_FILE_DIRECTORY = @as(u32, 128);
pub const COPY_FILE_SKIP_ALTERNATE_STREAMS = @as(u32, 32768);
pub const COPY_FILE_DISABLE_PRE_ALLOCATION = @as(u32, 67108864);
pub const COPY_FILE_ENABLE_LOW_FREE_SPACE_MODE = @as(u32, 134217728);
pub const FAIL_FAST_GENERATE_EXCEPTION_ADDRESS = @as(u32, 1);
pub const FAIL_FAST_NO_HARD_ERROR_DLG = @as(u32, 2);
pub const DTR_CONTROL_DISABLE = @as(u32, 0);
pub const DTR_CONTROL_ENABLE = @as(u32, 1);
pub const DTR_CONTROL_HANDSHAKE = @as(u32, 2);
pub const RTS_CONTROL_DISABLE = @as(u32, 0);
pub const RTS_CONTROL_ENABLE = @as(u32, 1);
pub const RTS_CONTROL_HANDSHAKE = @as(u32, 2);
pub const RTS_CONTROL_TOGGLE = @as(u32, 3);
pub const GMEM_NOCOMPACT = @as(u32, 16);
pub const GMEM_NODISCARD = @as(u32, 32);
pub const GMEM_MODIFY = @as(u32, 128);
pub const GMEM_DISCARDABLE = @as(u32, 256);
pub const GMEM_NOT_BANKED = @as(u32, 4096);
pub const GMEM_SHARE = @as(u32, 8192);
pub const GMEM_DDESHARE = @as(u32, 8192);
pub const GMEM_NOTIFY = @as(u32, 16384);
pub const GMEM_LOWER = @as(u32, 4096);
pub const GMEM_VALID_FLAGS = @as(u32, 32626);
pub const GMEM_INVALID_HANDLE = @as(u32, 32768);
pub const GMEM_DISCARDED = @as(u32, 16384);
pub const GMEM_LOCKCOUNT = @as(u32, 255);
pub const THREAD_PRIORITY_ERROR_RETURN = @as(u32, 2147483647);
pub const VOLUME_NAME_DOS = @as(u32, 0);
pub const VOLUME_NAME_GUID = @as(u32, 1);
pub const VOLUME_NAME_NT = @as(u32, 2);
pub const VOLUME_NAME_NONE = @as(u32, 4);
pub const DRIVE_UNKNOWN = @as(u32, 0);
pub const DRIVE_NO_ROOT_DIR = @as(u32, 1);
pub const DRIVE_REMOVABLE = @as(u32, 2);
pub const DRIVE_FIXED = @as(u32, 3);
pub const DRIVE_REMOTE = @as(u32, 4);
pub const DRIVE_CDROM = @as(u32, 5);
pub const DRIVE_RAMDISK = @as(u32, 6);
pub const FILE_TYPE_UNKNOWN = @as(u32, 0);
pub const FILE_TYPE_DISK = @as(u32, 1);
pub const FILE_TYPE_CHAR = @as(u32, 2);
pub const FILE_TYPE_PIPE = @as(u32, 3);
pub const FILE_TYPE_REMOTE = @as(u32, 32768);
pub const NOPARITY = @as(u32, 0);
pub const ODDPARITY = @as(u32, 1);
pub const EVENPARITY = @as(u32, 2);
pub const MARKPARITY = @as(u32, 3);
pub const SPACEPARITY = @as(u32, 4);
pub const ONESTOPBIT = @as(u32, 0);
pub const ONE5STOPBITS = @as(u32, 1);
pub const TWOSTOPBITS = @as(u32, 2);
pub const IGNORE = @as(u32, 0);
pub const INFINITE = @as(u32, 4294967295);
pub const CBR_110 = @as(u32, 110);
pub const CBR_300 = @as(u32, 300);
pub const CBR_600 = @as(u32, 600);
pub const CBR_1200 = @as(u32, 1200);
pub const CBR_2400 = @as(u32, 2400);
pub const CBR_4800 = @as(u32, 4800);
pub const CBR_9600 = @as(u32, 9600);
pub const CBR_14400 = @as(u32, 14400);
pub const CBR_19200 = @as(u32, 19200);
pub const CBR_38400 = @as(u32, 38400);
pub const CBR_56000 = @as(u32, 56000);
pub const CBR_57600 = @as(u32, 57600);
pub const CBR_115200 = @as(u32, 115200);
pub const CBR_128000 = @as(u32, 128000);
pub const CBR_256000 = @as(u32, 256000);
pub const CE_TXFULL = @as(u32, 256);
pub const CE_PTO = @as(u32, 512);
pub const CE_IOE = @as(u32, 1024);
pub const CE_DNS = @as(u32, 2048);
pub const CE_OOP = @as(u32, 4096);
pub const CE_MODE = @as(u32, 32768);
pub const IE_BADID = @as(i32, -1);
pub const IE_OPEN = @as(i32, -2);
pub const IE_NOPEN = @as(i32, -3);
pub const IE_MEMORY = @as(i32, -4);
pub const IE_DEFAULT = @as(i32, -5);
pub const IE_HARDWARE = @as(i32, -10);
pub const IE_BYTESIZE = @as(i32, -11);
pub const IE_BAUDRATE = @as(i32, -12);
pub const RESETDEV = @as(u32, 7);
pub const LPTx = @as(u32, 128);
pub const S_QUEUEEMPTY = @as(u32, 0);
pub const S_THRESHOLD = @as(u32, 1);
pub const S_ALLTHRESHOLD = @as(u32, 2);
pub const S_NORMAL = @as(u32, 0);
pub const S_LEGATO = @as(u32, 1);
pub const S_STACCATO = @as(u32, 2);
pub const S_PERIOD512 = @as(u32, 0);
pub const S_PERIOD1024 = @as(u32, 1);
pub const S_PERIOD2048 = @as(u32, 2);
pub const S_PERIODVOICE = @as(u32, 3);
pub const S_WHITE512 = @as(u32, 4);
pub const S_WHITE1024 = @as(u32, 5);
pub const S_WHITE2048 = @as(u32, 6);
pub const S_WHITEVOICE = @as(u32, 7);
pub const S_SERDVNA = @as(i32, -1);
pub const S_SEROFM = @as(i32, -2);
pub const S_SERMACT = @as(i32, -3);
pub const S_SERQFUL = @as(i32, -4);
pub const S_SERBDNT = @as(i32, -5);
pub const S_SERDLN = @as(i32, -6);
pub const S_SERDCC = @as(i32, -7);
pub const S_SERDTP = @as(i32, -8);
pub const S_SERDVL = @as(i32, -9);
pub const S_SERDMD = @as(i32, -10);
pub const S_SERDSH = @as(i32, -11);
pub const S_SERDPT = @as(i32, -12);
pub const S_SERDFQ = @as(i32, -13);
pub const S_SERDDR = @as(i32, -14);
pub const S_SERDSR = @as(i32, -15);
pub const S_SERDST = @as(i32, -16);
pub const FS_CASE_IS_PRESERVED = @as(u32, 2);
pub const FS_CASE_SENSITIVE = @as(u32, 1);
pub const FS_UNICODE_STORED_ON_DISK = @as(u32, 4);
pub const FS_PERSISTENT_ACLS = @as(u32, 8);
pub const FS_VOL_IS_COMPRESSED = @as(u32, 32768);
pub const FS_FILE_COMPRESSION = @as(u32, 16);
pub const FS_FILE_ENCRYPTION = @as(u32, 131072);
pub const OFS_MAXPATHNAME = @as(u32, 128);
pub const MAXINTATOM = @as(u32, 49152);
pub const SCS_32BIT_BINARY = @as(u32, 0);
pub const SCS_DOS_BINARY = @as(u32, 1);
pub const SCS_WOW_BINARY = @as(u32, 2);
pub const SCS_PIF_BINARY = @as(u32, 3);
pub const SCS_POSIX_BINARY = @as(u32, 4);
pub const SCS_OS216_BINARY = @as(u32, 5);
pub const SCS_64BIT_BINARY = @as(u32, 6);
pub const FIBER_FLAG_FLOAT_SWITCH = @as(u32, 1);
pub const UMS_VERSION = @as(u32, 256);
pub const FILE_SKIP_COMPLETION_PORT_ON_SUCCESS = @as(u32, 1);
pub const FILE_SKIP_SET_EVENT_ON_HANDLE = @as(u32, 2);
pub const CRITICAL_SECTION_NO_DEBUG_INFO = @as(u32, 16777216);
pub const HINSTANCE_ERROR = @as(u32, 32);
pub const FORMAT_MESSAGE_MAX_WIDTH_MASK = @as(u32, 255);
pub const FILE_ENCRYPTABLE = @as(u32, 0);
pub const FILE_IS_ENCRYPTED = @as(u32, 1);
pub const FILE_SYSTEM_ATTR = @as(u32, 2);
pub const FILE_ROOT_DIR = @as(u32, 3);
pub const FILE_SYSTEM_DIR = @as(u32, 4);
pub const FILE_UNKNOWN = @as(u32, 5);
pub const FILE_SYSTEM_NOT_SUPPORT = @as(u32, 6);
pub const FILE_USER_DISALLOWED = @as(u32, 7);
pub const FILE_READ_ONLY = @as(u32, 8);
pub const FILE_DIR_DISALLOWED = @as(u32, 9);
pub const EFS_USE_RECOVERY_KEYS = @as(u32, 1);
pub const CREATE_FOR_IMPORT = @as(u32, 1);
pub const CREATE_FOR_DIR = @as(u32, 2);
pub const OVERWRITE_HIDDEN = @as(u32, 4);
pub const EFSRPC_SECURE_ONLY = @as(u32, 8);
pub const EFS_DROP_ALTERNATE_STREAMS = @as(u32, 16);
pub const BACKUP_INVALID = @as(u32, 0);
pub const BACKUP_GHOSTED_FILE_EXTENTS = @as(u32, 11);
pub const STREAM_NORMAL_ATTRIBUTE = @as(u32, 0);
pub const STREAM_MODIFIED_WHEN_READ = @as(u32, 1);
pub const STREAM_CONTAINS_SECURITY = @as(u32, 2);
pub const STREAM_CONTAINS_PROPERTIES = @as(u32, 4);
pub const STREAM_SPARSE_ATTRIBUTE = @as(u32, 8);
pub const STREAM_CONTAINS_GHOSTED_FILE_EXTENTS = @as(u32, 16);
pub const STARTF_HOLOGRAPHIC = @as(u32, 262144);
pub const SHUTDOWN_NORETRY = @as(u32, 1);
pub const PROTECTION_LEVEL_SAME = @as(u32, 4294967295);
pub const PROC_THREAD_ATTRIBUTE_NUMBER = @as(u32, 65535);
pub const PROC_THREAD_ATTRIBUTE_THREAD = @as(u32, 65536);
pub const PROC_THREAD_ATTRIBUTE_INPUT = @as(u32, 131072);
pub const PROC_THREAD_ATTRIBUTE_ADDITIVE = @as(u32, 262144);
pub const PROCESS_CREATION_MITIGATION_POLICY_DEP_ENABLE = @as(u32, 1);
pub const PROCESS_CREATION_MITIGATION_POLICY_DEP_ATL_THUNK_ENABLE = @as(u32, 2);
pub const PROCESS_CREATION_MITIGATION_POLICY_SEHOP_ENABLE = @as(u32, 4);
pub const PROCESS_CREATION_CHILD_PROCESS_RESTRICTED = @as(u32, 1);
pub const PROCESS_CREATION_CHILD_PROCESS_OVERRIDE = @as(u32, 2);
pub const PROCESS_CREATION_CHILD_PROCESS_RESTRICTED_UNLESS_SECURE = @as(u32, 4);
pub const PROCESS_CREATION_ALL_APPLICATION_PACKAGES_OPT_OUT = @as(u32, 1);
pub const PROCESS_CREATION_DESKTOP_APP_BREAKAWAY_ENABLE_PROCESS_TREE = @as(u32, 1);
pub const PROCESS_CREATION_DESKTOP_APP_BREAKAWAY_DISABLE_PROCESS_TREE = @as(u32, 2);
pub const PROCESS_CREATION_DESKTOP_APP_BREAKAWAY_OVERRIDE = @as(u32, 4);
pub const ATOM_FLAG_GLOBAL = @as(u32, 2);
pub const BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE = @as(u32, 1);
pub const BASE_SEARCH_PATH_DISABLE_SAFE_SEARCHMODE = @as(u32, 65536);
pub const BASE_SEARCH_PATH_PERMANENT = @as(u32, 32768);
pub const COPYFILE2_MESSAGE_COPY_OFFLOAD = @as(i32, 1);
pub const COPYFILE2_IO_CYCLE_SIZE_MIN = @as(u32, 4096);
pub const COPYFILE2_IO_CYCLE_SIZE_MAX = @as(u32, 1073741824);
pub const COPYFILE2_IO_RATE_MIN = @as(u32, 512);
pub const EVENTLOG_FULL_INFO = @as(u32, 0);
pub const OPERATION_API_VERSION = @as(u32, 1);
pub const MAX_COMPUTERNAME_LENGTH = @as(u32, 15);
pub const LOGON32_PROVIDER_WINNT35 = @as(u32, 1);
pub const LOGON32_PROVIDER_VIRTUAL = @as(u32, 4);
pub const LOGON_ZERO_PASSWORD_BUFFER = @as(u32, 2147483648);
pub const HW_PROFILE_GUIDLEN = @as(u32, 39);
pub const DOCKINFO_UNDOCKED = @as(u32, 1);
pub const DOCKINFO_DOCKED = @as(u32, 2);
pub const DOCKINFO_USER_SUPPLIED = @as(u32, 4);
pub const TC_NORMAL = @as(u32, 0);
pub const TC_HARDERR = @as(u32, 1);
pub const TC_GP_TRAP = @as(u32, 2);
pub const TC_SIGNAL = @as(u32, 3);
pub const AC_LINE_OFFLINE = @as(u32, 0);
pub const AC_LINE_ONLINE = @as(u32, 1);
pub const AC_LINE_BACKUP_POWER = @as(u32, 2);
pub const AC_LINE_UNKNOWN = @as(u32, 255);
pub const BATTERY_FLAG_HIGH = @as(u32, 1);
pub const BATTERY_FLAG_LOW = @as(u32, 2);
pub const BATTERY_FLAG_CRITICAL = @as(u32, 4);
pub const BATTERY_FLAG_CHARGING = @as(u32, 8);
pub const BATTERY_FLAG_NO_BATTERY = @as(u32, 128);
pub const BATTERY_FLAG_UNKNOWN = @as(u32, 255);
pub const BATTERY_PERCENTAGE_UNKNOWN = @as(u32, 255);
pub const SYSTEM_STATUS_FLAG_POWER_SAVING_ON = @as(u32, 1);
pub const BATTERY_LIFE_UNKNOWN = @as(u32, 4294967295);
pub const ACTCTX_FLAG_PROCESSOR_ARCHITECTURE_VALID = @as(u32, 1);
pub const ACTCTX_FLAG_LANGID_VALID = @as(u32, 2);
pub const ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID = @as(u32, 4);
pub const ACTCTX_FLAG_RESOURCE_NAME_VALID = @as(u32, 8);
pub const ACTCTX_FLAG_SET_PROCESS_DEFAULT = @as(u32, 16);
pub const ACTCTX_FLAG_APPLICATION_NAME_VALID = @as(u32, 32);
pub const ACTCTX_FLAG_SOURCE_IS_ASSEMBLYREF = @as(u32, 64);
pub const ACTCTX_FLAG_HMODULE_VALID = @as(u32, 128);
pub const DEACTIVATE_ACTCTX_FLAG_FORCE_EARLY_DEACTIVATION = @as(u32, 1);
pub const FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX = @as(u32, 1);
pub const FIND_ACTCTX_SECTION_KEY_RETURN_FLAGS = @as(u32, 2);
pub const FIND_ACTCTX_SECTION_KEY_RETURN_ASSEMBLY_METADATA = @as(u32, 4);
pub const ACTIVATION_CONTEXT_BASIC_INFORMATION_DEFINED = @as(u32, 1);
pub const QUERY_ACTCTX_FLAG_USE_ACTIVE_ACTCTX = @as(u32, 4);
pub const QUERY_ACTCTX_FLAG_ACTCTX_IS_HMODULE = @as(u32, 8);
pub const QUERY_ACTCTX_FLAG_ACTCTX_IS_ADDRESS = @as(u32, 16);
pub const QUERY_ACTCTX_FLAG_NO_ADDREF = @as(u32, 2147483648);
pub const RESTART_MAX_CMD_LINE = @as(u32, 1024);
pub const RECOVERY_DEFAULT_PING_INTERVAL = @as(u32, 5000);
pub const FILE_RENAME_FLAG_REPLACE_IF_EXISTS = @as(u32, 1);
pub const FILE_RENAME_FLAG_POSIX_SEMANTICS = @as(u32, 2);
pub const FILE_RENAME_FLAG_SUPPRESS_PIN_STATE_INHERITANCE = @as(u32, 4);
pub const FILE_DISPOSITION_FLAG_DO_NOT_DELETE = @as(u32, 0);
pub const FILE_DISPOSITION_FLAG_DELETE = @as(u32, 1);
pub const FILE_DISPOSITION_FLAG_POSIX_SEMANTICS = @as(u32, 2);
pub const FILE_DISPOSITION_FLAG_FORCE_IMAGE_SECTION_CHECK = @as(u32, 4);
pub const FILE_DISPOSITION_FLAG_ON_CLOSE = @as(u32, 8);
pub const FILE_DISPOSITION_FLAG_IGNORE_READONLY_ATTRIBUTE = @as(u32, 16);
pub const STORAGE_INFO_FLAGS_ALIGNED_DEVICE = @as(u32, 1);
pub const STORAGE_INFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE = @as(u32, 2);
pub const STORAGE_INFO_OFFSET_UNKNOWN = @as(u32, 4294967295);
pub const REMOTE_PROTOCOL_INFO_FLAG_LOOPBACK = @as(u32, 1);
pub const REMOTE_PROTOCOL_INFO_FLAG_OFFLINE = @as(u32, 2);
pub const REMOTE_PROTOCOL_INFO_FLAG_PERSISTENT_HANDLE = @as(u32, 4);
pub const RPI_FLAG_SMB2_SHARECAP_TIMEWARP = @as(u32, 2);
pub const RPI_FLAG_SMB2_SHARECAP_DFS = @as(u32, 8);
pub const RPI_FLAG_SMB2_SHARECAP_CONTINUOUS_AVAILABILITY = @as(u32, 16);
pub const RPI_FLAG_SMB2_SHARECAP_SCALEOUT = @as(u32, 32);
pub const RPI_FLAG_SMB2_SHARECAP_CLUSTER = @as(u32, 64);
pub const RPI_SMB2_FLAG_SERVERCAP_DFS = @as(u32, 1);
pub const RPI_SMB2_FLAG_SERVERCAP_LEASING = @as(u32, 2);
pub const RPI_SMB2_FLAG_SERVERCAP_LARGEMTU = @as(u32, 4);
pub const RPI_SMB2_FLAG_SERVERCAP_MULTICHANNEL = @as(u32, 8);
pub const RPI_SMB2_FLAG_SERVERCAP_PERSISTENT_HANDLES = @as(u32, 16);
pub const RPI_SMB2_FLAG_SERVERCAP_DIRECTORY_LEASING = @as(u32, 32);
pub const MICROSOFT_WINDOWS_WINBASE_H_DEFINE_INTERLOCKED_CPLUSPLUS_OVERLOADS = @as(u32, 0);
pub const MICROSOFT_WINBASE_H_DEFINE_INTERLOCKED_CPLUSPLUS_OVERLOADS = @as(u32, 0);
pub const CODEINTEGRITY_OPTION_ENABLED = @as(u32, 1);
pub const CODEINTEGRITY_OPTION_TESTSIGN = @as(u32, 2);
pub const CODEINTEGRITY_OPTION_UMCI_ENABLED = @as(u32, 4);
pub const CODEINTEGRITY_OPTION_UMCI_AUDITMODE_ENABLED = @as(u32, 8);
pub const CODEINTEGRITY_OPTION_UMCI_EXCLUSIONPATHS_ENABLED = @as(u32, 16);
pub const CODEINTEGRITY_OPTION_TEST_BUILD = @as(u32, 32);
pub const CODEINTEGRITY_OPTION_PREPRODUCTION_BUILD = @as(u32, 64);
pub const CODEINTEGRITY_OPTION_DEBUGMODE_ENABLED = @as(u32, 128);
pub const CODEINTEGRITY_OPTION_FLIGHT_BUILD = @as(u32, 256);
pub const CODEINTEGRITY_OPTION_FLIGHTING_ENABLED = @as(u32, 512);
pub const CODEINTEGRITY_OPTION_HVCI_KMCI_ENABLED = @as(u32, 1024);
pub const CODEINTEGRITY_OPTION_HVCI_KMCI_AUDITMODE_ENABLED = @as(u32, 2048);
pub const CODEINTEGRITY_OPTION_HVCI_KMCI_STRICTMODE_ENABLED = @as(u32, 4096);
pub const CODEINTEGRITY_OPTION_HVCI_IUM_ENABLED = @as(u32, 8192);
pub const FILE_MAXIMUM_DISPOSITION = @as(u32, 5);
pub const FILE_DIRECTORY_FILE = @as(u32, 1);
pub const FILE_WRITE_THROUGH = @as(u32, 2);
pub const FILE_SEQUENTIAL_ONLY = @as(u32, 4);
pub const FILE_NO_INTERMEDIATE_BUFFERING = @as(u32, 8);
pub const FILE_SYNCHRONOUS_IO_ALERT = @as(u32, 16);
pub const FILE_SYNCHRONOUS_IO_NONALERT = @as(u32, 32);
pub const FILE_NON_DIRECTORY_FILE = @as(u32, 64);
pub const FILE_CREATE_TREE_CONNECTION = @as(u32, 128);
pub const FILE_COMPLETE_IF_OPLOCKED = @as(u32, 256);
pub const FILE_NO_EA_KNOWLEDGE = @as(u32, 512);
pub const FILE_OPEN_REMOTE_INSTANCE = @as(u32, 1024);
pub const FILE_RANDOM_ACCESS = @as(u32, 2048);
pub const FILE_DELETE_ON_CLOSE = @as(u32, 4096);
pub const FILE_OPEN_BY_FILE_ID = @as(u32, 8192);
pub const FILE_OPEN_FOR_BACKUP_INTENT = @as(u32, 16384);
pub const FILE_NO_COMPRESSION = @as(u32, 32768);
pub const FILE_OPEN_REQUIRING_OPLOCK = @as(u32, 65536);
pub const FILE_RESERVE_OPFILTER = @as(u32, 1048576);
pub const FILE_OPEN_REPARSE_POINT = @as(u32, 2097152);
pub const FILE_OPEN_NO_RECALL = @as(u32, 4194304);
pub const FILE_OPEN_FOR_FREE_SPACE_QUERY = @as(u32, 8388608);
pub const FILE_VALID_OPTION_FLAGS = @as(u32, 16777215);
pub const FILE_VALID_PIPE_OPTION_FLAGS = @as(u32, 50);
pub const FILE_VALID_MAILSLOT_OPTION_FLAGS = @as(u32, 50);
pub const FILE_VALID_SET_FLAGS = @as(u32, 54);
pub const FILE_SUPERSEDED = @as(u32, 0);
pub const FILE_OPENED = @as(u32, 1);
pub const FILE_CREATED = @as(u32, 2);
pub const FILE_OVERWRITTEN = @as(u32, 3);
pub const FILE_EXISTS = @as(u32, 4);
pub const FILE_DOES_NOT_EXIST = @as(u32, 5);
pub const WINWATCHNOTIFY_START = @as(u32, 0);
pub const WINWATCHNOTIFY_STOP = @as(u32, 1);
pub const WINWATCHNOTIFY_DESTROY = @as(u32, 2);
pub const WINWATCHNOTIFY_CHANGING = @as(u32, 3);
pub const WINWATCHNOTIFY_CHANGED = @as(u32, 4);
pub const RSC_FLAG_INF = @as(u32, 1);
pub const RSC_FLAG_SKIPDISKSPACECHECK = @as(u32, 2);
pub const RSC_FLAG_QUIET = @as(u32, 4);
pub const RSC_FLAG_NGCONV = @as(u32, 8);
pub const RSC_FLAG_UPDHLPDLLS = @as(u32, 16);
pub const RSC_FLAG_DELAYREGISTEROCX = @as(u32, 512);
pub const RSC_FLAG_SETUPAPI = @as(u32, 1024);
pub const ALINF_QUIET = @as(u32, 4);
pub const ALINF_NGCONV = @as(u32, 8);
pub const ALINF_UPDHLPDLLS = @as(u32, 16);
pub const ALINF_BKINSTALL = @as(u32, 32);
pub const ALINF_ROLLBACK = @as(u32, 64);
pub const ALINF_CHECKBKDATA = @as(u32, 128);
pub const ALINF_ROLLBKDOALL = @as(u32, 256);
pub const ALINF_DELAYREGISTEROCX = @as(u32, 512);
pub const AIF_WARNIFSKIP = @as(u32, 1);
pub const AIF_NOSKIP = @as(u32, 2);
pub const AIF_NOVERSIONCHECK = @as(u32, 4);
pub const AIF_FORCE_FILE_IN_USE = @as(u32, 8);
pub const AIF_NOOVERWRITE = @as(u32, 16);
pub const AIF_NO_VERSION_DIALOG = @as(u32, 32);
pub const AIF_REPLACEONLY = @as(u32, 1024);
pub const AIF_NOLANGUAGECHECK = @as(u32, 268435456);
pub const AIF_QUIET = @as(u32, 536870912);
pub const IE4_RESTORE = @as(u32, 1);
pub const IE4_BACKNEW = @as(u32, 2);
pub const IE4_NODELETENEW = @as(u32, 4);
pub const IE4_NOMESSAGES = @as(u32, 8);
pub const IE4_NOPROGRESS = @as(u32, 16);
pub const IE4_NOENUMKEY = @as(u32, 32);
pub const IE4_NO_CRC_MAPPING = @as(u32, 64);
pub const IE4_REGSECTION = @as(u32, 128);
pub const IE4_FRDOALL = @as(u32, 256);
pub const IE4_UPDREFCNT = @as(u32, 512);
pub const IE4_USEREFCNT = @as(u32, 1024);
pub const IE4_EXTRAINCREFCNT = @as(u32, 2048);
pub const IE4_REMOVREGBKDATA = @as(u32, 4096);
pub const ARSR_RESTORE = @as(u32, 1);
pub const ARSR_NOMESSAGES = @as(u32, 8);
pub const ARSR_REGSECTION = @as(u32, 128);
pub const ARSR_REMOVREGBKDATA = @as(u32, 4096);
pub const AFSR_RESTORE = @as(u32, 1);
pub const AFSR_BACKNEW = @as(u32, 2);
pub const AFSR_NODELETENEW = @as(u32, 4);
pub const AFSR_NOMESSAGES = @as(u32, 8);
pub const AFSR_NOPROGRESS = @as(u32, 16);
pub const AFSR_UPDREFCNT = @as(u32, 512);
pub const AFSR_USEREFCNT = @as(u32, 1024);
pub const AFSR_EXTRAINCREFCNT = @as(u32, 2048);
pub const AADBE_ADD_ENTRY = @as(u32, 1);
pub const AADBE_DEL_ENTRY = @as(u32, 2);
pub const ADN_DEL_IF_EMPTY = @as(u32, 1);
pub const ADN_DONT_DEL_SUBDIRS = @as(u32, 2);
pub const ADN_DONT_DEL_DIR = @as(u32, 4);
pub const ADN_DEL_UNC_PATHS = @as(u32, 8);
pub const LIS_QUIET = @as(u32, 1);
pub const LIS_NOGRPCONV = @as(u32, 2);
pub const RUNCMDS_QUIET = @as(u32, 1);
pub const RUNCMDS_NOWAIT = @as(u32, 2);
pub const RUNCMDS_DELAYPOSTCMD = @as(u32, 4);
pub const IME_MAXPROCESS = @as(u32, 32);
pub const CP_HWND = @as(u32, 0);
pub const CP_OPEN = @as(u32, 1);
pub const CP_DIRECT = @as(u32, 2);
pub const CP_LEVEL = @as(u32, 3);
pub const MCW_DEFAULT = @as(u32, 0);
pub const MCW_RECT = @as(u32, 1);
pub const MCW_WINDOW = @as(u32, 2);
pub const MCW_SCREEN = @as(u32, 4);
pub const MCW_VERTICAL = @as(u32, 8);
pub const MCW_HIDDEN = @as(u32, 16);
pub const IME_MODE_ALPHANUMERIC = @as(u32, 1);
pub const IME_MODE_SBCSCHAR = @as(u32, 2);
pub const IME_MODE_KATAKANA = @as(u32, 2);
pub const IME_MODE_HIRAGANA = @as(u32, 4);
pub const IME_MODE_HANJACONVERT = @as(u32, 4);
pub const IME_MODE_DBCSCHAR = @as(u32, 16);
pub const IME_MODE_ROMAN = @as(u32, 32);
pub const IME_MODE_NOROMAN = @as(u32, 64);
pub const IME_MODE_CODEINPUT = @as(u32, 128);
pub const IME_MODE_NOCODEINPUT = @as(u32, 256);
pub const IME_GETIMECAPS = @as(u32, 3);
pub const IME_SETOPEN = @as(u32, 4);
pub const IME_GETOPEN = @as(u32, 5);
pub const IME_GETVERSION = @as(u32, 7);
pub const IME_SETCONVERSIONWINDOW = @as(u32, 8);
pub const IME_MOVEIMEWINDOW = @as(u32, 8);
pub const IME_SETCONVERSIONMODE = @as(u32, 16);
pub const IME_GETCONVERSIONMODE = @as(u32, 17);
pub const IME_SET_MODE = @as(u32, 18);
pub const IME_SENDVKEY = @as(u32, 19);
pub const IME_ENTERWORDREGISTERMODE = @as(u32, 24);
pub const IME_SETCONVERSIONFONTEX = @as(u32, 25);
pub const IME_BANJAtoJUNJA = @as(u32, 19);
pub const IME_JUNJAtoBANJA = @as(u32, 20);
pub const IME_JOHABtoKS = @as(u32, 21);
pub const IME_KStoJOHAB = @as(u32, 22);
pub const IMEA_INIT = @as(u32, 1);
pub const IMEA_NEXT = @as(u32, 2);
pub const IMEA_PREV = @as(u32, 3);
pub const IME_REQUEST_CONVERT = @as(u32, 1);
pub const IME_ENABLE_CONVERT = @as(u32, 2);
pub const INTERIM_WINDOW = @as(u32, 0);
pub const MODE_WINDOW = @as(u32, 1);
pub const HANJA_WINDOW = @as(u32, 2);
pub const IME_RS_ERROR = @as(u32, 1);
pub const IME_RS_NOIME = @as(u32, 2);
pub const IME_RS_TOOLONG = @as(u32, 5);
pub const IME_RS_ILLEGAL = @as(u32, 6);
pub const IME_RS_NOTFOUND = @as(u32, 7);
pub const IME_RS_NOROOM = @as(u32, 10);
pub const IME_RS_DISKERROR = @as(u32, 14);
pub const IME_RS_INVALID = @as(u32, 17);
pub const IME_RS_NEST = @as(u32, 18);
pub const IME_RS_SYSTEMMODAL = @as(u32, 19);
pub const WM_IME_REPORT = @as(u32, 640);
pub const IR_STRINGSTART = @as(u32, 256);
pub const IR_STRINGEND = @as(u32, 257);
pub const IR_OPENCONVERT = @as(u32, 288);
pub const IR_CHANGECONVERT = @as(u32, 289);
pub const IR_CLOSECONVERT = @as(u32, 290);
pub const IR_FULLCONVERT = @as(u32, 291);
pub const IR_IMESELECT = @as(u32, 304);
pub const IR_STRING = @as(u32, 320);
pub const IR_DBCSCHAR = @as(u32, 352);
pub const IR_UNDETERMINE = @as(u32, 368);
pub const IR_STRINGEX = @as(u32, 384);
pub const IR_MODEINFO = @as(u32, 400);
pub const WM_WNT_CONVERTREQUESTEX = @as(u32, 265);
pub const WM_CONVERTREQUEST = @as(u32, 266);
pub const WM_CONVERTRESULT = @as(u32, 267);
pub const WM_INTERIM = @as(u32, 268);
pub const WM_IMEKEYDOWN = @as(u32, 656);
pub const WM_IMEKEYUP = @as(u32, 657);
pub const DELAYLOAD_GPA_FAILURE = @as(u32, 4);
pub const CATID_DeleteBrowsingHistory = Guid.initString("31caf6e4-d6aa-4090-a050-a5ac8972e9ef");
pub const DELETE_BROWSING_HISTORY_HISTORY = @as(u32, 1);
pub const DELETE_BROWSING_HISTORY_COOKIES = @as(u32, 2);
pub const DELETE_BROWSING_HISTORY_TIF = @as(u32, 4);
pub const DELETE_BROWSING_HISTORY_FORMDATA = @as(u32, 8);
pub const DELETE_BROWSING_HISTORY_PASSWORDS = @as(u32, 16);
pub const DELETE_BROWSING_HISTORY_PRESERVEFAVORITES = @as(u32, 32);
pub const DELETE_BROWSING_HISTORY_DOWNLOADHISTORY = @as(u32, 64);
//--------------------------------------------------------------------------------
// Section: Types (133)
//--------------------------------------------------------------------------------
pub const TDIENTITY_ENTITY_TYPE = enum(u32) {
GENERIC_ENTITY = 0,
AT_ENTITY = 640,
CL_NL_ENTITY = 769,
CO_NL_ENTITY = 768,
CL_TL_ENTITY = 1025,
CO_TL_ENTITY = 1024,
ER_ENTITY = 896,
IF_ENTITY = 512,
};
pub const GENERIC_ENTITY = TDIENTITY_ENTITY_TYPE.GENERIC_ENTITY;
pub const AT_ENTITY = TDIENTITY_ENTITY_TYPE.AT_ENTITY;
pub const CL_NL_ENTITY = TDIENTITY_ENTITY_TYPE.CL_NL_ENTITY;
pub const CO_NL_ENTITY = TDIENTITY_ENTITY_TYPE.CO_NL_ENTITY;
pub const CL_TL_ENTITY = TDIENTITY_ENTITY_TYPE.CL_TL_ENTITY;
pub const CO_TL_ENTITY = TDIENTITY_ENTITY_TYPE.CO_TL_ENTITY;
pub const ER_ENTITY = TDIENTITY_ENTITY_TYPE.ER_ENTITY;
pub const IF_ENTITY = TDIENTITY_ENTITY_TYPE.IF_ENTITY;
pub const _D3DHAL_CALLBACKS = extern struct {
placeholder: usize, // TODO: why is this type empty?
};
pub const _D3DHAL_GLOBALDRIVERDATA = extern struct {
placeholder: usize, // TODO: why is this type empty?
};
pub const HWINWATCH = *opaque{};
pub const FEATURE_STATE_CHANGE_SUBSCRIPTION = isize;
pub const FH_SERVICE_PIPE_HANDLE = isize;
pub const IMAGE_THUNK_DATA64 = extern struct {
u1: extern union {
ForwarderString: u64,
Function: u64,
Ordinal: u64,
AddressOfData: u64,
},
};
pub const IMAGE_THUNK_DATA32 = extern struct {
u1: extern union {
ForwarderString: u32,
Function: u32,
Ordinal: u32,
AddressOfData: u32,
},
};
pub const IMAGE_DELAYLOAD_DESCRIPTOR = extern struct {
Attributes: extern union {
AllAttributes: u32,
Anonymous: extern struct {
_bitfield: u32,
},
},
DllNameRVA: u32,
ModuleHandleRVA: u32,
ImportAddressTableRVA: u32,
ImportNameTableRVA: u32,
BoundImportAddressTableRVA: u32,
UnloadInformationTableRVA: u32,
TimeDateStamp: u32,
};
pub const CUSTOM_SYSTEM_EVENT_TRIGGER_CONFIG = extern struct {
Size: u32,
TriggerId: ?[*:0]const u16,
};
pub const PFIBER_CALLOUT_ROUTINE = fn(
lpParameter: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
pub const JIT_DEBUG_INFO = extern struct {
dwSize: u32,
dwProcessorArchitecture: u32,
dwThreadID: u32,
dwReserved0: u32,
lpExceptionAddress: u64,
lpExceptionRecord: u64,
lpContextRecord: u64,
};
pub const PROC_THREAD_ATTRIBUTE_NUM = enum(i32) {
ParentProcess = 0,
HandleList = 2,
GroupAffinity = 3,
PreferredNode = 4,
IdealProcessor = 5,
UmsThread = 6,
MitigationPolicy = 7,
SecurityCapabilities = 9,
ProtectionLevel = 11,
JobList = 13,
ChildProcessPolicy = 14,
AllApplicationPackagesPolicy = 15,
Win32kFilter = 16,
SafeOpenPromptOriginClaim = 17,
DesktopAppPolicy = 18,
PseudoConsole = 22,
MitigationAuditPolicy = 24,
MachineType = 25,
ComponentFilter = 26,
EnableOptionalXStateFeatures = 27,
};
pub const ProcThreadAttributeParentProcess = PROC_THREAD_ATTRIBUTE_NUM.ParentProcess;
pub const ProcThreadAttributeHandleList = PROC_THREAD_ATTRIBUTE_NUM.HandleList;
pub const ProcThreadAttributeGroupAffinity = PROC_THREAD_ATTRIBUTE_NUM.GroupAffinity;
pub const ProcThreadAttributePreferredNode = PROC_THREAD_ATTRIBUTE_NUM.PreferredNode;
pub const ProcThreadAttributeIdealProcessor = PROC_THREAD_ATTRIBUTE_NUM.IdealProcessor;
pub const ProcThreadAttributeUmsThread = PROC_THREAD_ATTRIBUTE_NUM.UmsThread;
pub const ProcThreadAttributeMitigationPolicy = PROC_THREAD_ATTRIBUTE_NUM.MitigationPolicy;
pub const ProcThreadAttributeSecurityCapabilities = PROC_THREAD_ATTRIBUTE_NUM.SecurityCapabilities;
pub const ProcThreadAttributeProtectionLevel = PROC_THREAD_ATTRIBUTE_NUM.ProtectionLevel;
pub const ProcThreadAttributeJobList = PROC_THREAD_ATTRIBUTE_NUM.JobList;
pub const ProcThreadAttributeChildProcessPolicy = PROC_THREAD_ATTRIBUTE_NUM.ChildProcessPolicy;
pub const ProcThreadAttributeAllApplicationPackagesPolicy = PROC_THREAD_ATTRIBUTE_NUM.AllApplicationPackagesPolicy;
pub const ProcThreadAttributeWin32kFilter = PROC_THREAD_ATTRIBUTE_NUM.Win32kFilter;
pub const ProcThreadAttributeSafeOpenPromptOriginClaim = PROC_THREAD_ATTRIBUTE_NUM.SafeOpenPromptOriginClaim;
pub const ProcThreadAttributeDesktopAppPolicy = PROC_THREAD_ATTRIBUTE_NUM.DesktopAppPolicy;
pub const ProcThreadAttributePseudoConsole = PROC_THREAD_ATTRIBUTE_NUM.PseudoConsole;
pub const ProcThreadAttributeMitigationAuditPolicy = PROC_THREAD_ATTRIBUTE_NUM.MitigationAuditPolicy;
pub const ProcThreadAttributeMachineType = PROC_THREAD_ATTRIBUTE_NUM.MachineType;
pub const ProcThreadAttributeComponentFilter = PROC_THREAD_ATTRIBUTE_NUM.ComponentFilter;
pub const ProcThreadAttributeEnableOptionalXStateFeatures = PROC_THREAD_ATTRIBUTE_NUM.EnableOptionalXStateFeatures;
pub const HW_PROFILE_INFOA = extern struct {
dwDockInfo: u32,
szHwProfileGuid: [39]CHAR,
szHwProfileName: [80]CHAR,
};
pub const HW_PROFILE_INFOW = extern struct {
dwDockInfo: u32,
szHwProfileGuid: [39]u16,
szHwProfileName: [80]u16,
};
pub const ACTCTX_SECTION_KEYED_DATA_2600 = extern struct {
cbSize: u32,
ulDataFormatVersion: u32,
lpData: ?*anyopaque,
ulLength: u32,
lpSectionGlobalData: ?*anyopaque,
ulSectionGlobalDataLength: u32,
lpSectionBase: ?*anyopaque,
ulSectionTotalLength: u32,
hActCtx: ?HANDLE,
ulAssemblyRosterIndex: u32,
};
pub const ACTCTX_SECTION_KEYED_DATA_ASSEMBLY_METADATA = extern struct {
lpInformation: ?*anyopaque,
lpSectionBase: ?*anyopaque,
ulSectionLength: u32,
lpSectionGlobalDataBase: ?*anyopaque,
ulSectionGlobalDataLength: u32,
};
pub const ACTIVATION_CONTEXT_BASIC_INFORMATION = extern struct {
hActCtx: ?HANDLE,
dwFlags: u32,
};
pub const PQUERYACTCTXW_FUNC = fn(
dwFlags: u32,
hActCtx: ?HANDLE,
pvSubInstance: ?*anyopaque,
ulInfoClass: u32,
// TODO: what to do with BytesParamIndex 5?
pvBuffer: ?*anyopaque,
cbBuffer: usize,
pcbWrittenOrRequired: ?*usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const APPLICATION_RECOVERY_CALLBACK = fn(
pvParameter: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const FILE_CASE_SENSITIVE_INFO = extern struct {
Flags: u32,
};
pub const FILE_DISPOSITION_INFO_EX = extern struct {
Flags: u32,
};
pub const CLIENT_ID = extern struct {
UniqueProcess: ?HANDLE,
UniqueThread: ?HANDLE,
};
pub const LDR_DATA_TABLE_ENTRY = extern struct {
Reserved1: [2]?*anyopaque,
InMemoryOrderLinks: LIST_ENTRY,
Reserved2: [2]?*anyopaque,
DllBase: ?*anyopaque,
Reserved3: [2]?*anyopaque,
FullDllName: UNICODE_STRING,
Reserved4: [8]u8,
Reserved5: [3]?*anyopaque,
Anonymous: extern union {
CheckSum: u32,
Reserved6: ?*anyopaque,
},
TimeDateStamp: u32,
};
pub const OBJECT_ATTRIBUTES = extern struct {
Length: u32,
RootDirectory: ?HANDLE,
ObjectName: ?*UNICODE_STRING,
Attributes: u32,
SecurityDescriptor: ?*anyopaque,
SecurityQualityOfService: ?*anyopaque,
};
pub const IO_STATUS_BLOCK = extern struct {
Anonymous: extern union {
Status: NTSTATUS,
Pointer: ?*anyopaque,
},
Information: usize,
};
pub const PIO_APC_ROUTINE = fn(
ApcContext: ?*anyopaque,
IoStatusBlock: ?*IO_STATUS_BLOCK,
Reserved: u32,
) callconv(@import("std").os.windows.WINAPI) void;
pub const SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION = extern struct {
IdleTime: LARGE_INTEGER,
KernelTime: LARGE_INTEGER,
UserTime: LARGE_INTEGER,
Reserved1: [2]LARGE_INTEGER,
Reserved2: u32,
};
pub const SYSTEM_PROCESS_INFORMATION = extern struct {
NextEntryOffset: u32,
NumberOfThreads: u32,
Reserved1: [48]u8,
ImageName: UNICODE_STRING,
BasePriority: i32,
UniqueProcessId: ?HANDLE,
Reserved2: ?*anyopaque,
HandleCount: u32,
SessionId: u32,
Reserved3: ?*anyopaque,
PeakVirtualSize: usize,
VirtualSize: usize,
Reserved4: u32,
PeakWorkingSetSize: usize,
WorkingSetSize: usize,
Reserved5: ?*anyopaque,
QuotaPagedPoolUsage: usize,
Reserved6: ?*anyopaque,
QuotaNonPagedPoolUsage: usize,
PagefileUsage: usize,
PeakPagefileUsage: usize,
PrivatePageCount: usize,
Reserved7: [6]LARGE_INTEGER,
};
pub const SYSTEM_THREAD_INFORMATION = extern struct {
Reserved1: [3]LARGE_INTEGER,
Reserved2: u32,
StartAddress: ?*anyopaque,
ClientId: CLIENT_ID,
Priority: i32,
BasePriority: i32,
Reserved3: u32,
ThreadState: u32,
WaitReason: u32,
};
pub const SYSTEM_REGISTRY_QUOTA_INFORMATION = extern struct {
RegistryQuotaAllowed: u32,
RegistryQuotaUsed: u32,
Reserved1: ?*anyopaque,
};
pub const SYSTEM_BASIC_INFORMATION = extern struct {
Reserved1: [24]u8,
Reserved2: [4]?*anyopaque,
NumberOfProcessors: i8,
};
pub const SYSTEM_TIMEOFDAY_INFORMATION = extern struct {
Reserved1: [48]u8,
};
pub const SYSTEM_PERFORMANCE_INFORMATION = extern struct {
Reserved1: [312]u8,
};
pub const SYSTEM_EXCEPTION_INFORMATION = extern struct {
Reserved1: [16]u8,
};
pub const SYSTEM_LOOKASIDE_INFORMATION = extern struct {
Reserved1: [32]u8,
};
pub const SYSTEM_INTERRUPT_INFORMATION = extern struct {
Reserved1: [24]u8,
};
pub const SYSTEM_POLICY_INFORMATION = extern struct {
Reserved1: [2]?*anyopaque,
Reserved2: [3]u32,
};
pub const FILE_INFORMATION_CLASS = enum(i32) {
n = 1,
};
pub const FileDirectoryInformation = FILE_INFORMATION_CLASS.n;
pub const THREAD_NAME_INFORMATION = extern struct {
ThreadName: UNICODE_STRING,
};
pub const SYSTEM_CODEINTEGRITY_INFORMATION = extern struct {
Length: u32,
CodeIntegrityOptions: u32,
};
pub const SYSTEM_INFORMATION_CLASS = enum(i32) {
BasicInformation = 0,
PerformanceInformation = 2,
TimeOfDayInformation = 3,
ProcessInformation = 5,
ProcessorPerformanceInformation = 8,
InterruptInformation = 23,
ExceptionInformation = 33,
RegistryQuotaInformation = 37,
LookasideInformation = 45,
CodeIntegrityInformation = 103,
PolicyInformation = 134,
};
pub const SystemBasicInformation = SYSTEM_INFORMATION_CLASS.BasicInformation;
pub const SystemPerformanceInformation = SYSTEM_INFORMATION_CLASS.PerformanceInformation;
pub const SystemTimeOfDayInformation = SYSTEM_INFORMATION_CLASS.TimeOfDayInformation;
pub const SystemProcessInformation = SYSTEM_INFORMATION_CLASS.ProcessInformation;
pub const SystemProcessorPerformanceInformation = SYSTEM_INFORMATION_CLASS.ProcessorPerformanceInformation;
pub const SystemInterruptInformation = SYSTEM_INFORMATION_CLASS.InterruptInformation;
pub const SystemExceptionInformation = SYSTEM_INFORMATION_CLASS.ExceptionInformation;
pub const SystemRegistryQuotaInformation = SYSTEM_INFORMATION_CLASS.RegistryQuotaInformation;
pub const SystemLookasideInformation = SYSTEM_INFORMATION_CLASS.LookasideInformation;
pub const SystemCodeIntegrityInformation = SYSTEM_INFORMATION_CLASS.CodeIntegrityInformation;
pub const SystemPolicyInformation = SYSTEM_INFORMATION_CLASS.PolicyInformation;
pub const OBJECT_INFORMATION_CLASS = enum(i32) {
BasicInformation = 0,
TypeInformation = 2,
};
pub const ObjectBasicInformation = OBJECT_INFORMATION_CLASS.BasicInformation;
pub const ObjectTypeInformation = OBJECT_INFORMATION_CLASS.TypeInformation;
pub const PUBLIC_OBJECT_BASIC_INFORMATION = extern struct {
Attributes: u32,
GrantedAccess: u32,
HandleCount: u32,
PointerCount: u32,
Reserved: [10]u32,
};
pub const PUBLIC_OBJECT_TYPE_INFORMATION = extern struct {
TypeName: UNICODE_STRING,
Reserved: [22]u32,
};
pub const KEY_VALUE_ENTRY = extern struct {
ValueName: ?*UNICODE_STRING,
DataLength: u32,
DataOffset: u32,
Type: u32,
};
pub const KEY_SET_INFORMATION_CLASS = enum(i32) {
KeyWriteTimeInformation = 0,
KeyWow64FlagsInformation = 1,
KeyControlFlagsInformation = 2,
KeySetVirtualizationInformation = 3,
KeySetDebugInformation = 4,
KeySetHandleTagsInformation = 5,
MaxKeySetInfoClass = 6,
};
pub const KeyWriteTimeInformation = KEY_SET_INFORMATION_CLASS.KeyWriteTimeInformation;
pub const KeyWow64FlagsInformation = KEY_SET_INFORMATION_CLASS.KeyWow64FlagsInformation;
pub const KeyControlFlagsInformation = KEY_SET_INFORMATION_CLASS.KeyControlFlagsInformation;
pub const KeySetVirtualizationInformation = KEY_SET_INFORMATION_CLASS.KeySetVirtualizationInformation;
pub const KeySetDebugInformation = KEY_SET_INFORMATION_CLASS.KeySetDebugInformation;
pub const KeySetHandleTagsInformation = KEY_SET_INFORMATION_CLASS.KeySetHandleTagsInformation;
pub const MaxKeySetInfoClass = KEY_SET_INFORMATION_CLASS.MaxKeySetInfoClass;
pub const WINSTATIONINFOCLASS = enum(i32) {
n = 8,
};
pub const WinStationInformation = WINSTATIONINFOCLASS.n;
pub const WINSTATIONINFORMATIONW = extern struct {
Reserved2: [70]u8,
LogonId: u32,
Reserved3: [1140]u8,
};
pub const PWINSTATIONQUERYINFORMATIONW = fn(
param0: ?HANDLE,
param1: u32,
param2: WINSTATIONINFOCLASS,
param3: ?*anyopaque,
param4: u32,
param5: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOLEAN;
const CLSID_CameraUIControl_Value = @import("../zig.zig").Guid.initString("16d5a2be-b1c5-47b3-8eae-ccbcf452c7e8");
pub const CLSID_CameraUIControl = &CLSID_CameraUIControl_Value;
pub const CameraUIControlMode = enum(i32) {
Browse = 0,
Linear = 1,
};
// NOTE: not creating aliases because this enum is 'Scoped'
pub const CameraUIControlLinearSelectionMode = enum(i32) {
Single = 0,
Multiple = 1,
};
// NOTE: not creating aliases because this enum is 'Scoped'
pub const CameraUIControlCaptureMode = enum(i32) {
PhotoOrVideo = 0,
Photo = 1,
Video = 2,
};
// NOTE: not creating aliases because this enum is 'Scoped'
pub const CameraUIControlPhotoFormat = enum(i32) {
Jpeg = 0,
Png = 1,
JpegXR = 2,
};
// NOTE: not creating aliases because this enum is 'Scoped'
pub const CameraUIControlVideoFormat = enum(i32) {
Mp4 = 0,
Wmv = 1,
};
// NOTE: not creating aliases because this enum is 'Scoped'
pub const CameraUIControlViewType = enum(i32) {
SingleItem = 0,
ItemList = 1,
};
// NOTE: not creating aliases because this enum is 'Scoped'
// TODO: this type is limited to platform 'windows8.0'
const IID_ICameraUIControlEventCallback_Value = @import("../zig.zig").Guid.initString("1bfa0c2c-fbcd-4776-bda4-88bf974e74f4");
pub const IID_ICameraUIControlEventCallback = &IID_ICameraUIControlEventCallback_Value;
pub const ICameraUIControlEventCallback = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
OnStartupComplete: fn(
self: *const ICameraUIControlEventCallback,
) callconv(@import("std").os.windows.WINAPI) void,
OnSuspendComplete: fn(
self: *const ICameraUIControlEventCallback,
) callconv(@import("std").os.windows.WINAPI) void,
OnItemCaptured: fn(
self: *const ICameraUIControlEventCallback,
pszPath: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) void,
OnItemDeleted: fn(
self: *const ICameraUIControlEventCallback,
pszPath: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) void,
OnClosed: fn(
self: *const ICameraUIControlEventCallback,
) 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 ICameraUIControlEventCallback_OnStartupComplete(self: *const T) callconv(.Inline) void {
return @ptrCast(*const ICameraUIControlEventCallback.VTable, self.vtable).OnStartupComplete(@ptrCast(*const ICameraUIControlEventCallback, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ICameraUIControlEventCallback_OnSuspendComplete(self: *const T) callconv(.Inline) void {
return @ptrCast(*const ICameraUIControlEventCallback.VTable, self.vtable).OnSuspendComplete(@ptrCast(*const ICameraUIControlEventCallback, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ICameraUIControlEventCallback_OnItemCaptured(self: *const T, pszPath: ?[*:0]const u16) callconv(.Inline) void {
return @ptrCast(*const ICameraUIControlEventCallback.VTable, self.vtable).OnItemCaptured(@ptrCast(*const ICameraUIControlEventCallback, self), pszPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ICameraUIControlEventCallback_OnItemDeleted(self: *const T, pszPath: ?[*:0]const u16) callconv(.Inline) void {
return @ptrCast(*const ICameraUIControlEventCallback.VTable, self.vtable).OnItemDeleted(@ptrCast(*const ICameraUIControlEventCallback, self), pszPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ICameraUIControlEventCallback_OnClosed(self: *const T) callconv(.Inline) void {
return @ptrCast(*const ICameraUIControlEventCallback.VTable, self.vtable).OnClosed(@ptrCast(*const ICameraUIControlEventCallback, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_ICameraUIControl_Value = @import("../zig.zig").Guid.initString("b8733adf-3d68-4b8f-bb08-e28a0bed0376");
pub const IID_ICameraUIControl = &IID_ICameraUIControl_Value;
pub const ICameraUIControl = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Show: fn(
self: *const ICameraUIControl,
pWindow: ?*IUnknown,
mode: CameraUIControlMode,
selectionMode: CameraUIControlLinearSelectionMode,
captureMode: CameraUIControlCaptureMode,
photoFormat: CameraUIControlPhotoFormat,
videoFormat: CameraUIControlVideoFormat,
bHasCloseButton: BOOL,
pEventCallback: ?*ICameraUIControlEventCallback,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Close: fn(
self: *const ICameraUIControl,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Suspend: fn(
self: *const ICameraUIControl,
pbDeferralRequired: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Resume: fn(
self: *const ICameraUIControl,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCurrentViewType: fn(
self: *const ICameraUIControl,
pViewType: ?*CameraUIControlViewType,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetActiveItem: fn(
self: *const ICameraUIControl,
pbstrActiveItemPath: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSelectedItems: fn(
self: *const ICameraUIControl,
ppSelectedItemPaths: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveCapturedItem: fn(
self: *const ICameraUIControl,
pszPath: ?[*:0]const u16,
) 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 ICameraUIControl_Show(self: *const T, pWindow: ?*IUnknown, mode: CameraUIControlMode, selectionMode: CameraUIControlLinearSelectionMode, captureMode: CameraUIControlCaptureMode, photoFormat: CameraUIControlPhotoFormat, videoFormat: CameraUIControlVideoFormat, bHasCloseButton: BOOL, pEventCallback: ?*ICameraUIControlEventCallback) callconv(.Inline) HRESULT {
return @ptrCast(*const ICameraUIControl.VTable, self.vtable).Show(@ptrCast(*const ICameraUIControl, self), pWindow, mode, selectionMode, captureMode, photoFormat, videoFormat, bHasCloseButton, pEventCallback);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ICameraUIControl_Close(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ICameraUIControl.VTable, self.vtable).Close(@ptrCast(*const ICameraUIControl, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ICameraUIControl_Suspend(self: *const T, pbDeferralRequired: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const ICameraUIControl.VTable, self.vtable).Suspend(@ptrCast(*const ICameraUIControl, self), pbDeferralRequired);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ICameraUIControl_Resume(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ICameraUIControl.VTable, self.vtable).Resume(@ptrCast(*const ICameraUIControl, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ICameraUIControl_GetCurrentViewType(self: *const T, pViewType: ?*CameraUIControlViewType) callconv(.Inline) HRESULT {
return @ptrCast(*const ICameraUIControl.VTable, self.vtable).GetCurrentViewType(@ptrCast(*const ICameraUIControl, self), pViewType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ICameraUIControl_GetActiveItem(self: *const T, pbstrActiveItemPath: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ICameraUIControl.VTable, self.vtable).GetActiveItem(@ptrCast(*const ICameraUIControl, self), pbstrActiveItemPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ICameraUIControl_GetSelectedItems(self: *const T, ppSelectedItemPaths: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const ICameraUIControl.VTable, self.vtable).GetSelectedItems(@ptrCast(*const ICameraUIControl, self), ppSelectedItemPaths);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ICameraUIControl_RemoveCapturedItem(self: *const T, pszPath: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const ICameraUIControl.VTable, self.vtable).RemoveCapturedItem(@ptrCast(*const ICameraUIControl, self), pszPath);
}
};}
pub usingnamespace MethodMixin(@This());
};
const CLSID_EditionUpgradeHelper_Value = @import("../zig.zig").Guid.initString("01776df3-b9af-4e50-9b1c-56e93116d704");
pub const CLSID_EditionUpgradeHelper = &CLSID_EditionUpgradeHelper_Value;
const CLSID_EditionUpgradeBroker_Value = @import("../zig.zig").Guid.initString("c4270827-4f39-45df-9288-12ff6b85a921");
pub const CLSID_EditionUpgradeBroker = &CLSID_EditionUpgradeBroker_Value;
// TODO: this type is limited to platform 'windows10.0.10240'
const IID_IEditionUpgradeHelper_Value = @import("../zig.zig").Guid.initString("d3e9e342-5deb-43b6-849e-6913b85d503a");
pub const IID_IEditionUpgradeHelper = &IID_IEditionUpgradeHelper_Value;
pub const IEditionUpgradeHelper = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
CanUpgrade: fn(
self: *const IEditionUpgradeHelper,
isAllowed: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UpdateOperatingSystem: fn(
self: *const IEditionUpgradeHelper,
contentId: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ShowProductKeyUI: fn(
self: *const IEditionUpgradeHelper,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetOsProductContentId: fn(
self: *const IEditionUpgradeHelper,
contentId: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetGenuineLocalStatus: fn(
self: *const IEditionUpgradeHelper,
isGenuine: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEditionUpgradeHelper_CanUpgrade(self: *const T, isAllowed: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IEditionUpgradeHelper.VTable, self.vtable).CanUpgrade(@ptrCast(*const IEditionUpgradeHelper, self), isAllowed);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEditionUpgradeHelper_UpdateOperatingSystem(self: *const T, contentId: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IEditionUpgradeHelper.VTable, self.vtable).UpdateOperatingSystem(@ptrCast(*const IEditionUpgradeHelper, self), contentId);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEditionUpgradeHelper_ShowProductKeyUI(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IEditionUpgradeHelper.VTable, self.vtable).ShowProductKeyUI(@ptrCast(*const IEditionUpgradeHelper, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEditionUpgradeHelper_GetOsProductContentId(self: *const T, contentId: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IEditionUpgradeHelper.VTable, self.vtable).GetOsProductContentId(@ptrCast(*const IEditionUpgradeHelper, self), contentId);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEditionUpgradeHelper_GetGenuineLocalStatus(self: *const T, isGenuine: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IEditionUpgradeHelper.VTable, self.vtable).GetGenuineLocalStatus(@ptrCast(*const IEditionUpgradeHelper, self), isGenuine);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWindowsLockModeHelper_Value = @import("../zig.zig").Guid.initString("f342d19e-cc22-4648-bb5d-03ccf75b47c5");
pub const IID_IWindowsLockModeHelper = &IID_IWindowsLockModeHelper_Value;
pub const IWindowsLockModeHelper = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetSMode: fn(
self: *const IWindowsLockModeHelper,
isSmode: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWindowsLockModeHelper_GetSMode(self: *const T, isSmode: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IWindowsLockModeHelper.VTable, self.vtable).GetSMode(@ptrCast(*const IWindowsLockModeHelper, self), isSmode);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IEditionUpgradeBroker_Value = @import("../zig.zig").Guid.initString("ff19cbcf-9455-4937-b872-6b7929a460af");
pub const IID_IEditionUpgradeBroker = &IID_IEditionUpgradeBroker_Value;
pub const IEditionUpgradeBroker = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
InitializeParentWindow: fn(
self: *const IEditionUpgradeBroker,
parentHandle: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UpdateOperatingSystem: fn(
self: *const IEditionUpgradeBroker,
parameter: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ShowProductKeyUI: fn(
self: *const IEditionUpgradeBroker,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CanUpgrade: fn(
self: *const IEditionUpgradeBroker,
) 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 IEditionUpgradeBroker_InitializeParentWindow(self: *const T, parentHandle: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IEditionUpgradeBroker.VTable, self.vtable).InitializeParentWindow(@ptrCast(*const IEditionUpgradeBroker, self), parentHandle);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEditionUpgradeBroker_UpdateOperatingSystem(self: *const T, parameter: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IEditionUpgradeBroker.VTable, self.vtable).UpdateOperatingSystem(@ptrCast(*const IEditionUpgradeBroker, self), parameter);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEditionUpgradeBroker_ShowProductKeyUI(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IEditionUpgradeBroker.VTable, self.vtable).ShowProductKeyUI(@ptrCast(*const IEditionUpgradeBroker, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEditionUpgradeBroker_CanUpgrade(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IEditionUpgradeBroker.VTable, self.vtable).CanUpgrade(@ptrCast(*const IEditionUpgradeBroker, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IContainerActivationHelper_Value = @import("../zig.zig").Guid.initString("b524f93f-80d5-4ec7-ae9e-d66e93ade1fa");
pub const IID_IContainerActivationHelper = &IID_IContainerActivationHelper_Value;
pub const IContainerActivationHelper = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
CanActivateClientVM: fn(
self: *const IContainerActivationHelper,
isAllowed: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IContainerActivationHelper_CanActivateClientVM(self: *const T, isAllowed: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IContainerActivationHelper.VTable, self.vtable).CanActivateClientVM(@ptrCast(*const IContainerActivationHelper, self), isAllowed);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IClipServiceNotificationHelper_Value = @import("../zig.zig").Guid.initString("c39948f0-6142-44fd-98ca-e1681a8d68b5");
pub const IID_IClipServiceNotificationHelper = &IID_IClipServiceNotificationHelper_Value;
pub const IClipServiceNotificationHelper = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
ShowToast: fn(
self: *const IClipServiceNotificationHelper,
titleText: ?BSTR,
bodyText: ?BSTR,
packageName: ?BSTR,
appId: ?BSTR,
launchCommand: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IClipServiceNotificationHelper_ShowToast(self: *const T, titleText: ?BSTR, bodyText: ?BSTR, packageName: ?BSTR, appId: ?BSTR, launchCommand: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IClipServiceNotificationHelper.VTable, self.vtable).ShowToast(@ptrCast(*const IClipServiceNotificationHelper, self), titleText, bodyText, packageName, appId, launchCommand);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const FEATURE_CHANGE_TIME = enum(i32) {
READ = 0,
MODULE_RELOAD = 1,
SESSION = 2,
REBOOT = 3,
};
pub const FEATURE_CHANGE_TIME_READ = FEATURE_CHANGE_TIME.READ;
pub const FEATURE_CHANGE_TIME_MODULE_RELOAD = FEATURE_CHANGE_TIME.MODULE_RELOAD;
pub const FEATURE_CHANGE_TIME_SESSION = FEATURE_CHANGE_TIME.SESSION;
pub const FEATURE_CHANGE_TIME_REBOOT = FEATURE_CHANGE_TIME.REBOOT;
pub const FEATURE_ENABLED_STATE = enum(i32) {
DEFAULT = 0,
DISABLED = 1,
ENABLED = 2,
};
pub const FEATURE_ENABLED_STATE_DEFAULT = FEATURE_ENABLED_STATE.DEFAULT;
pub const FEATURE_ENABLED_STATE_DISABLED = FEATURE_ENABLED_STATE.DISABLED;
pub const FEATURE_ENABLED_STATE_ENABLED = FEATURE_ENABLED_STATE.ENABLED;
pub const FEATURE_ERROR = extern struct {
hr: HRESULT,
lineNumber: u16,
file: ?[*:0]const u8,
process: ?[*:0]const u8,
module: ?[*:0]const u8,
callerReturnAddressOffset: u32,
callerModule: ?[*:0]const u8,
message: ?[*:0]const u8,
originLineNumber: u16,
originFile: ?[*:0]const u8,
originModule: ?[*:0]const u8,
originCallerReturnAddressOffset: u32,
originCallerModule: ?[*:0]const u8,
originName: ?[*:0]const u8,
};
pub const PFEATURE_STATE_CHANGE_CALLBACK = fn(
context: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) void;
pub const DCICMD = extern struct {
dwCommand: u32,
dwParam1: u32,
dwParam2: u32,
dwVersion: u32,
dwReserved: u32,
};
pub const DCICREATEINPUT = extern struct {
cmd: DCICMD,
dwCompression: u32,
dwMask: [3]u32,
dwWidth: u32,
dwHeight: u32,
dwDCICaps: u32,
dwBitCount: u32,
lpSurface: ?*anyopaque,
};
pub const DCISURFACEINFO = extern struct {
dwSize: u32,
dwDCICaps: u32,
dwCompression: u32,
dwMask: [3]u32,
dwWidth: u32,
dwHeight: u32,
lStride: i32,
dwBitCount: u32,
dwOffSurface: usize,
wSelSurface: u16,
wReserved: u16,
dwReserved1: u32,
dwReserved2: u32,
dwReserved3: u32,
BeginAccess: isize,
EndAccess: isize,
DestroySurface: isize,
};
pub const ENUM_CALLBACK = fn(
lpSurfaceInfo: ?*DCISURFACEINFO,
lpContext: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) void;
pub const DCIENUMINPUT = extern struct {
cmd: DCICMD,
rSrc: RECT,
rDst: RECT,
EnumCallback: isize,
lpContext: ?*anyopaque,
};
pub const DCIOFFSCREEN = extern struct {
dciInfo: DCISURFACEINFO,
Draw: isize,
SetClipList: isize,
SetDestination: isize,
};
pub const DCIOVERLAY = extern struct {
dciInfo: DCISURFACEINFO,
dwChromakeyValue: u32,
dwChromakeyMask: u32,
};
pub const WINWATCHNOTIFYPROC = fn(
hww: ?HWINWATCH,
hwnd: ?HWND,
code: u32,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) void;
pub const STRENTRYA = extern struct {
pszName: ?PSTR,
pszValue: ?PSTR,
};
pub const STRENTRYW = extern struct {
pszName: ?PWSTR,
pszValue: ?PWSTR,
};
pub const STRTABLEA = extern struct {
cEntries: u32,
pse: ?*STRENTRYA,
};
pub const STRTABLEW = extern struct {
cEntries: u32,
pse: ?*STRENTRYW,
};
pub const REGINSTALLA = fn(
hm: ?HINSTANCE,
pszSection: ?[*:0]const u8,
pstTable: ?*STRTABLEA,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const CABINFOA = extern struct {
pszCab: ?PSTR,
pszInf: ?PSTR,
pszSection: ?PSTR,
szSrcPath: [260]CHAR,
dwFlags: u32,
};
pub const CABINFOW = extern struct {
pszCab: ?PWSTR,
pszInf: ?PWSTR,
pszSection: ?PWSTR,
szSrcPath: [260]u16,
dwFlags: u32,
};
pub const PERUSERSECTIONA = extern struct {
szGUID: [59]CHAR,
szDispName: [128]CHAR,
szLocale: [10]CHAR,
szStub: [1040]CHAR,
szVersion: [32]CHAR,
szCompID: [128]CHAR,
dwIsInstalled: u32,
bRollback: BOOL,
};
pub const PERUSERSECTIONW = extern struct {
szGUID: [59]u16,
szDispName: [128]u16,
szLocale: [10]u16,
szStub: [1040]u16,
szVersion: [32]u16,
szCompID: [128]u16,
dwIsInstalled: u32,
bRollback: BOOL,
};
pub const IMESTRUCT = extern struct {
fnc: u32,
wParam: WPARAM,
wCount: u32,
dchSource: u32,
dchDest: u32,
lParam1: LPARAM,
lParam2: LPARAM,
lParam3: LPARAM,
};
pub const UNDETERMINESTRUCT = extern struct {
dwSize: u32,
uDefIMESize: u32,
uDefIMEPos: u32,
uUndetTextLen: u32,
uUndetTextPos: u32,
uUndetAttrPos: u32,
uCursorPos: u32,
uDeltaStart: u32,
uDetermineTextLen: u32,
uDetermineTextPos: u32,
uDetermineDelimPos: u32,
uYomiTextLen: u32,
uYomiTextPos: u32,
uYomiDelimPos: u32,
};
pub const STRINGEXSTRUCT = extern struct {
dwSize: u32,
uDeterminePos: u32,
uDetermineDelimPos: u32,
uYomiPos: u32,
uYomiDelimPos: u32,
};
pub const DATETIME = extern struct {
year: u16,
month: u16,
day: u16,
hour: u16,
min: u16,
sec: u16,
};
pub const IMEPROA = extern struct {
hWnd: ?HWND,
InstDate: DATETIME,
wVersion: u32,
szDescription: [50]u8,
szName: [80]u8,
szOptions: [30]u8,
};
pub const IMEPROW = extern struct {
hWnd: ?HWND,
InstDate: DATETIME,
wVersion: u32,
szDescription: [50]u16,
szName: [80]u16,
szOptions: [30]u16,
};
pub const JAVA_TRUST = extern struct {
cbSize: u32,
flag: u32,
fAllActiveXPermissions: BOOL,
fAllPermissions: BOOL,
dwEncodingType: u32,
pbJavaPermissions: ?*u8,
cbJavaPermissions: u32,
pbSigner: ?*u8,
cbSigner: u32,
pwszZone: ?[*:0]const u16,
guidZone: Guid,
hVerify: HRESULT,
};
pub const TDIEntityID = extern struct {
tei_entity: TDIENTITY_ENTITY_TYPE,
tei_instance: u32,
};
pub const TDIObjectID = extern struct {
toi_entity: TDIEntityID,
toi_class: u32,
toi_type: u32,
toi_id: u32,
};
pub const tcp_request_query_information_ex_xp = extern struct {
ID: TDIObjectID,
Context: [2]usize,
};
pub const tcp_request_query_information_ex_w2k = extern struct {
ID: TDIObjectID,
Context: [16]u8,
};
pub const tcp_request_set_information_ex = extern struct {
ID: TDIObjectID,
BufferSize: u32,
Buffer: [1]u8,
};
pub const TDI_TL_IO_CONTROL_TYPE = enum(i32) {
EndpointIoControlType = 0,
SetSockOptIoControlType = 1,
GetSockOptIoControlType = 2,
SocketIoControlType = 3,
};
pub const EndpointIoControlType = TDI_TL_IO_CONTROL_TYPE.EndpointIoControlType;
pub const SetSockOptIoControlType = TDI_TL_IO_CONTROL_TYPE.SetSockOptIoControlType;
pub const GetSockOptIoControlType = TDI_TL_IO_CONTROL_TYPE.GetSockOptIoControlType;
pub const SocketIoControlType = TDI_TL_IO_CONTROL_TYPE.SocketIoControlType;
pub const TDI_TL_IO_CONTROL_ENDPOINT = extern struct {
Type: TDI_TL_IO_CONTROL_TYPE,
Level: u32,
Anonymous: extern union {
IoControlCode: u32,
OptionName: u32,
},
InputBuffer: ?*anyopaque,
InputBufferLength: u32,
OutputBuffer: ?*anyopaque,
OutputBufferLength: u32,
};
pub const WLDP_HOST = enum(i32) {
RUNDLL32 = 0,
SVCHOST = 1,
MAX = 2,
};
pub const WLDP_HOST_RUNDLL32 = WLDP_HOST.RUNDLL32;
pub const WLDP_HOST_SVCHOST = WLDP_HOST.SVCHOST;
pub const WLDP_HOST_MAX = WLDP_HOST.MAX;
pub const WLDP_HOST_ID = enum(i32) {
UNKNOWN = 0,
GLOBAL = 1,
VBA = 2,
WSH = 3,
POWERSHELL = 4,
IE = 5,
MSI = 6,
ALL = 7,
MAX = 8,
};
pub const WLDP_HOST_ID_UNKNOWN = WLDP_HOST_ID.UNKNOWN;
pub const WLDP_HOST_ID_GLOBAL = WLDP_HOST_ID.GLOBAL;
pub const WLDP_HOST_ID_VBA = WLDP_HOST_ID.VBA;
pub const WLDP_HOST_ID_WSH = WLDP_HOST_ID.WSH;
pub const WLDP_HOST_ID_POWERSHELL = WLDP_HOST_ID.POWERSHELL;
pub const WLDP_HOST_ID_IE = WLDP_HOST_ID.IE;
pub const WLDP_HOST_ID_MSI = WLDP_HOST_ID.MSI;
pub const WLDP_HOST_ID_ALL = WLDP_HOST_ID.ALL;
pub const WLDP_HOST_ID_MAX = WLDP_HOST_ID.MAX;
pub const DECISION_LOCATION = enum(i32) {
REFRESH_GLOBAL_DATA = 0,
PARAMETER_VALIDATION = 1,
AUDIT = 2,
FAILED_CONVERT_GUID = 3,
ENTERPRISE_DEFINED_CLASS_ID = 4,
GLOBAL_BUILT_IN_LIST = 5,
PROVIDER_BUILT_IN_LIST = 6,
ENFORCE_STATE_LIST = 7,
NOT_FOUND = 8,
UNKNOWN = 9,
};
pub const DECISION_LOCATION_REFRESH_GLOBAL_DATA = DECISION_LOCATION.REFRESH_GLOBAL_DATA;
pub const DECISION_LOCATION_PARAMETER_VALIDATION = DECISION_LOCATION.PARAMETER_VALIDATION;
pub const DECISION_LOCATION_AUDIT = DECISION_LOCATION.AUDIT;
pub const DECISION_LOCATION_FAILED_CONVERT_GUID = DECISION_LOCATION.FAILED_CONVERT_GUID;
pub const DECISION_LOCATION_ENTERPRISE_DEFINED_CLASS_ID = DECISION_LOCATION.ENTERPRISE_DEFINED_CLASS_ID;
pub const DECISION_LOCATION_GLOBAL_BUILT_IN_LIST = DECISION_LOCATION.GLOBAL_BUILT_IN_LIST;
pub const DECISION_LOCATION_PROVIDER_BUILT_IN_LIST = DECISION_LOCATION.PROVIDER_BUILT_IN_LIST;
pub const DECISION_LOCATION_ENFORCE_STATE_LIST = DECISION_LOCATION.ENFORCE_STATE_LIST;
pub const DECISION_LOCATION_NOT_FOUND = DECISION_LOCATION.NOT_FOUND;
pub const DECISION_LOCATION_UNKNOWN = DECISION_LOCATION.UNKNOWN;
pub const WLDP_KEY = enum(i32) {
UNKNOWN = 0,
OVERRIDE = 1,
ALL_KEYS = 2,
};
pub const KEY_UNKNOWN = WLDP_KEY.UNKNOWN;
pub const KEY_OVERRIDE = WLDP_KEY.OVERRIDE;
pub const KEY_ALL_KEYS = WLDP_KEY.ALL_KEYS;
pub const VALUENAME = enum(i32) {
UNKNOWN = 0,
ENTERPRISE_DEFINED_CLASS_ID = 1,
BUILT_IN_LIST = 2,
};
pub const VALUENAME_UNKNOWN = VALUENAME.UNKNOWN;
pub const VALUENAME_ENTERPRISE_DEFINED_CLASS_ID = VALUENAME.ENTERPRISE_DEFINED_CLASS_ID;
pub const VALUENAME_BUILT_IN_LIST = VALUENAME.BUILT_IN_LIST;
pub const WLDP_WINDOWS_LOCKDOWN_MODE = enum(i32) {
UNLOCKED = 0,
TRIAL = 1,
LOCKED = 2,
MAX = 3,
};
pub const WLDP_WINDOWS_LOCKDOWN_MODE_UNLOCKED = WLDP_WINDOWS_LOCKDOWN_MODE.UNLOCKED;
pub const WLDP_WINDOWS_LOCKDOWN_MODE_TRIAL = WLDP_WINDOWS_LOCKDOWN_MODE.TRIAL;
pub const WLDP_WINDOWS_LOCKDOWN_MODE_LOCKED = WLDP_WINDOWS_LOCKDOWN_MODE.LOCKED;
pub const WLDP_WINDOWS_LOCKDOWN_MODE_MAX = WLDP_WINDOWS_LOCKDOWN_MODE.MAX;
pub const WLDP_WINDOWS_LOCKDOWN_RESTRICTION = enum(i32) {
NONE = 0,
NOUNLOCK = 1,
NOUNLOCK_PERMANENT = 2,
MAX = 3,
};
pub const WLDP_WINDOWS_LOCKDOWN_RESTRICTION_NONE = WLDP_WINDOWS_LOCKDOWN_RESTRICTION.NONE;
pub const WLDP_WINDOWS_LOCKDOWN_RESTRICTION_NOUNLOCK = WLDP_WINDOWS_LOCKDOWN_RESTRICTION.NOUNLOCK;
pub const WLDP_WINDOWS_LOCKDOWN_RESTRICTION_NOUNLOCK_PERMANENT = WLDP_WINDOWS_LOCKDOWN_RESTRICTION.NOUNLOCK_PERMANENT;
pub const WLDP_WINDOWS_LOCKDOWN_RESTRICTION_MAX = WLDP_WINDOWS_LOCKDOWN_RESTRICTION.MAX;
pub const WLDP_POLICY_SETTING = enum(i32) {
E = 1000,
};
pub const WLDP_POLICY_SETTING_AV_PERF_MODE = WLDP_POLICY_SETTING.E;
pub const WLDP_HOST_INFORMATION = extern struct {
dwRevision: u32,
dwHostId: WLDP_HOST_ID,
szSource: ?[*:0]const u16,
hSource: ?HANDLE,
};
pub const WLDP_DEVICE_SECURITY_INFORMATION = extern struct {
UnlockIdSize: u32,
UnlockId: ?*u8,
ManufacturerIDLength: u32,
ManufacturerID: ?PWSTR,
};
pub const PWLDP_SETDYNAMICCODETRUST_API = fn(
hFileHandle: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const PWLDP_ISDYNAMICCODEPOLICYENABLED_API = fn(
pbEnabled: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const PWLDP_QUERYDYNAMICODETRUST_API = fn(
fileHandle: ?HANDLE,
// TODO: what to do with BytesParamIndex 2?
baseImage: ?*anyopaque,
imageSize: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const PWLDP_QUERYWINDOWSLOCKDOWNMODE_API = fn(
lockdownMode: ?*WLDP_WINDOWS_LOCKDOWN_MODE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const PWLDP_QUERYDEVICESECURITYINFORMATION_API = fn(
information: ?[*]WLDP_DEVICE_SECURITY_INFORMATION,
informationLength: u32,
returnLength: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const PWLDP_QUERYWINDOWSLOCKDOWNRESTRICTION_API = fn(
LockdownRestriction: ?*WLDP_WINDOWS_LOCKDOWN_RESTRICTION,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const PWLDP_SETWINDOWSLOCKDOWNRESTRICTION_API = fn(
LockdownRestriction: WLDP_WINDOWS_LOCKDOWN_RESTRICTION,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const PWLDP_ISAPPAPPROVEDBYPOLICY_API = fn(
PackageFamilyName: ?[*:0]const u16,
PackageVersion: u64,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const PWLDP_QUERYPOLICYSETTINGENABLED_API = fn(
Setting: WLDP_POLICY_SETTING,
Enabled: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const PWLDP_QUERYPOLICYSETTINGENABLED2_API = fn(
Setting: ?[*:0]const u16,
Enabled: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const PWLDP_ISWCOSPRODUCTIONCONFIGURATION_API = fn(
IsProductionConfiguration: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const PWLDP_RESETWCOSPRODUCTIONCONFIGURATION_API = fn(
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const PWLDP_ISPRODUCTIONCONFIGURATION_API = fn(
IsProductionConfiguration: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const PWLDP_RESETPRODUCTIONCONFIGURATION_API = fn(
) callconv(@import("std").os.windows.WINAPI) HRESULT;
const CLSID_DefaultBrowserSyncSettings_Value = @import("../zig.zig").Guid.initString("3ac83423-3112-4aa6-9b5b-1feb23d0c5f9");
pub const CLSID_DefaultBrowserSyncSettings = &CLSID_DefaultBrowserSyncSettings_Value;
const IID_IDefaultBrowserSyncSettings_Value = @import("../zig.zig").Guid.initString("7a27faad-5ae6-4255-9030-c530936292e3");
pub const IID_IDefaultBrowserSyncSettings = &IID_IDefaultBrowserSyncSettings_Value;
pub const IDefaultBrowserSyncSettings = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
IsEnabled: fn(
self: *const IDefaultBrowserSyncSettings,
) callconv(@import("std").os.windows.WINAPI) BOOL,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDefaultBrowserSyncSettings_IsEnabled(self: *const T) callconv(.Inline) BOOL {
return @ptrCast(*const IDefaultBrowserSyncSettings.VTable, self.vtable).IsEnabled(@ptrCast(*const IDefaultBrowserSyncSettings, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DELAYLOAD_PROC_DESCRIPTOR = extern struct {
ImportDescribedByName: u32,
Description: extern union {
Name: ?[*:0]const u8,
Ordinal: u32,
},
};
pub const PDELAYLOAD_FAILURE_DLL_CALLBACK = fn(
NotificationReason: u32,
DelayloadInfo: ?*DELAYLOAD_INFO,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
const IID_IDeleteBrowsingHistory_Value = @import("../zig.zig").Guid.initString("cf38ed4b-2be7-4461-8b5e-9a466dc82ae3");
pub const IID_IDeleteBrowsingHistory = &IID_IDeleteBrowsingHistory_Value;
pub const IDeleteBrowsingHistory = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
DeleteBrowsingHistory: fn(
self: *const IDeleteBrowsingHistory,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDeleteBrowsingHistory_DeleteBrowsingHistory(self: *const T, dwFlags: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDeleteBrowsingHistory.VTable, self.vtable).DeleteBrowsingHistory(@ptrCast(*const IDeleteBrowsingHistory, self), dwFlags);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const tcp_request_query_information_ex32_xp = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
ID: TDIObjectID,
Context: [4]u32,
},
else => usize, // NOTE: this should be a @compileError but can't because of https://github.com/ziglang/zig/issues/9682
};
pub const DELAYLOAD_INFO = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
Size: u32,
DelayloadDescriptor: ?*IMAGE_DELAYLOAD_DESCRIPTOR,
ThunkAddress: ?*IMAGE_THUNK_DATA64,
TargetDllName: ?[*:0]const u8,
TargetApiDescriptor: DELAYLOAD_PROC_DESCRIPTOR,
TargetModuleBase: ?*anyopaque,
Unused: ?*anyopaque,
LastError: u32,
},
.X86 => extern struct {
Size: u32,
DelayloadDescriptor: ?*IMAGE_DELAYLOAD_DESCRIPTOR,
ThunkAddress: ?*IMAGE_THUNK_DATA32,
TargetDllName: ?[*:0]const u8,
TargetApiDescriptor: DELAYLOAD_PROC_DESCRIPTOR,
TargetModuleBase: ?*anyopaque,
Unused: ?*anyopaque,
LastError: u32,
},
};
//--------------------------------------------------------------------------------
// Section: Functions (227)
//--------------------------------------------------------------------------------
pub extern "ntdll" fn RtlGetReturnAddressHijackTarget(
) callconv(@import("std").os.windows.WINAPI) usize;
pub extern "ntdll" fn RtlRaiseCustomSystemEventTrigger(
TriggerConfig: ?*CUSTOM_SYSTEM_EVENT_TRIGGER_CONFIG,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "api-ms-win-core-apiquery-l2-1-0" fn IsApiSetImplemented(
Contract: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn QueryThreadCycleTime(
ThreadHandle: ?HANDLE,
CycleTime: ?*u64,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn QueryProcessCycleTime(
ProcessHandle: ?HANDLE,
CycleTime: ?*u64,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn QueryIdleProcessorCycleTime(
BufferLength: ?*u32,
// TODO: what to do with BytesParamIndex 0?
ProcessorIdleCycleTime: ?*u64,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn QueryIdleProcessorCycleTimeEx(
Group: u16,
BufferLength: ?*u32,
// TODO: what to do with BytesParamIndex 1?
ProcessorIdleCycleTime: ?*u64,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "api-ms-win-core-realtime-l1-1-1" fn QueryInterruptTimePrecise(
lpInterruptTimePrecise: ?*u64,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "api-ms-win-core-realtime-l1-1-1" fn QueryUnbiasedInterruptTimePrecise(
lpUnbiasedInterruptTimePrecise: ?*u64,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "api-ms-win-core-realtime-l1-1-1" fn QueryInterruptTime(
lpInterruptTime: ?*u64,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn QueryUnbiasedInterruptTime(
UnbiasedTime: ?*u64,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows10.0.15063'
pub extern "api-ms-win-core-realtime-l1-1-2" fn QueryAuxiliaryCounterFrequency(
lpAuxiliaryCounterFrequency: ?*u64,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows10.0.15063'
pub extern "api-ms-win-core-realtime-l1-1-2" fn ConvertAuxiliaryCounterToPerformanceCounter(
ullAuxiliaryCounterValue: u64,
lpPerformanceCounterValue: ?*u64,
lpConversionError: ?*u64,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows10.0.15063'
pub extern "api-ms-win-core-realtime-l1-1-2" fn ConvertPerformanceCounterToAuxiliaryCounter(
ullPerformanceCounterValue: u64,
lpAuxiliaryCounterValue: ?*u64,
lpConversionError: ?*u64,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "KERNEL32" fn GlobalCompact(
dwMinFree: u32,
) callconv(@import("std").os.windows.WINAPI) usize;
pub extern "KERNEL32" fn GlobalFix(
hMem: isize,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "KERNEL32" fn GlobalUnfix(
hMem: isize,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "KERNEL32" fn GlobalWire(
hMem: isize,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
pub extern "KERNEL32" fn GlobalUnWire(
hMem: isize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn LocalShrink(
hMem: isize,
cbNewSize: u32,
) callconv(@import("std").os.windows.WINAPI) usize;
pub extern "KERNEL32" fn LocalCompact(
uMinFree: u32,
) callconv(@import("std").os.windows.WINAPI) usize;
pub extern "KERNEL32" fn SetEnvironmentStringsA(
NewEnvironment: ?[*]u8,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn SetHandleCount(
uNumber: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "KERNEL32" fn RequestDeviceWakeup(
hDevice: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn CancelDeviceWakeupRequest(
hDevice: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn SetMessageWaitingIndicator(
hMsgIndicator: ?HANDLE,
ulMsgCount: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn MulDiv(
nNumber: i32,
nNumerator: i32,
nDenominator: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn GetSystemRegistryQuota(
pdwQuotaAllowed: ?*u32,
pdwQuotaUsed: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn FileTimeToDosDateTime(
lpFileTime: ?*const FILETIME,
lpFatDate: ?*u16,
lpFatTime: ?*u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn DosDateTimeToFileTime(
wFatDate: u16,
wFatTime: u16,
lpFileTime: ?*FILETIME,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn _lopen(
lpPathName: ?[*:0]const u8,
iReadWrite: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub extern "KERNEL32" fn _lcreat(
lpPathName: ?[*:0]const u8,
iAttribute: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub extern "KERNEL32" fn _lread(
hFile: i32,
// TODO: what to do with BytesParamIndex 2?
lpBuffer: ?*anyopaque,
uBytes: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "KERNEL32" fn _lwrite(
hFile: i32,
// TODO: what to do with BytesParamIndex 2?
lpBuffer: ?[*]const u8,
uBytes: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "KERNEL32" fn _hread(
hFile: i32,
// TODO: what to do with BytesParamIndex 2?
lpBuffer: ?*anyopaque,
lBytes: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub extern "KERNEL32" fn _hwrite(
hFile: i32,
// TODO: what to do with BytesParamIndex 2?
lpBuffer: ?[*]const u8,
lBytes: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub extern "KERNEL32" fn _lclose(
hFile: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub extern "KERNEL32" fn _llseek(
hFile: i32,
lOffset: i32,
iOrigin: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn SignalObjectAndWait(
hObjectToSignal: ?HANDLE,
hObjectToWaitOn: ?HANDLE,
dwMilliseconds: u32,
bAlertable: BOOL,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "KERNEL32" fn OpenMutexA(
dwDesiredAccess: u32,
bInheritHandle: BOOL,
lpName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
pub extern "KERNEL32" fn OpenSemaphoreA(
dwDesiredAccess: u32,
bInheritHandle: BOOL,
lpName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
pub extern "KERNEL32" fn CreateWaitableTimerA(
lpTimerAttributes: ?*SECURITY_ATTRIBUTES,
bManualReset: BOOL,
lpTimerName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
pub extern "KERNEL32" fn OpenWaitableTimerA(
dwDesiredAccess: u32,
bInheritHandle: BOOL,
lpTimerName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
pub extern "KERNEL32" fn CreateWaitableTimerExA(
lpTimerAttributes: ?*SECURITY_ATTRIBUTES,
lpTimerName: ?[*:0]const u8,
dwFlags: u32,
dwDesiredAccess: u32,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn GetFirmwareEnvironmentVariableA(
lpName: ?[*:0]const u8,
lpGuid: ?[*:0]const u8,
// TODO: what to do with BytesParamIndex 3?
pBuffer: ?*anyopaque,
nSize: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn GetFirmwareEnvironmentVariableW(
lpName: ?[*:0]const u16,
lpGuid: ?[*:0]const u16,
// TODO: what to do with BytesParamIndex 3?
pBuffer: ?*anyopaque,
nSize: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "KERNEL32" fn GetFirmwareEnvironmentVariableExA(
lpName: ?[*:0]const u8,
lpGuid: ?[*:0]const u8,
// TODO: what to do with BytesParamIndex 3?
pBuffer: ?*anyopaque,
nSize: u32,
pdwAttribubutes: ?*u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "KERNEL32" fn GetFirmwareEnvironmentVariableExW(
lpName: ?[*:0]const u16,
lpGuid: ?[*:0]const u16,
// TODO: what to do with BytesParamIndex 3?
pBuffer: ?*anyopaque,
nSize: u32,
pdwAttribubutes: ?*u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn SetFirmwareEnvironmentVariableA(
lpName: ?[*:0]const u8,
lpGuid: ?[*:0]const u8,
// TODO: what to do with BytesParamIndex 3?
pValue: ?*anyopaque,
nSize: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn SetFirmwareEnvironmentVariableW(
lpName: ?[*:0]const u16,
lpGuid: ?[*:0]const u16,
// TODO: what to do with BytesParamIndex 3?
pValue: ?*anyopaque,
nSize: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.0'
pub extern "KERNEL32" fn SetFirmwareEnvironmentVariableExA(
lpName: ?[*:0]const u8,
lpGuid: ?[*:0]const u8,
// TODO: what to do with BytesParamIndex 3?
pValue: ?*anyopaque,
nSize: u32,
dwAttributes: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.0'
pub extern "KERNEL32" fn SetFirmwareEnvironmentVariableExW(
lpName: ?[*:0]const u16,
lpGuid: ?[*:0]const u16,
// TODO: what to do with BytesParamIndex 3?
pValue: ?*anyopaque,
nSize: u32,
dwAttributes: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.0'
pub extern "KERNEL32" fn IsNativeVhdBoot(
NativeVhdBoot: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn GetProfileIntA(
lpAppName: ?[*:0]const u8,
lpKeyName: ?[*:0]const u8,
nDefault: i32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn GetProfileIntW(
lpAppName: ?[*:0]const u16,
lpKeyName: ?[*:0]const u16,
nDefault: i32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn GetProfileStringA(
lpAppName: ?[*:0]const u8,
lpKeyName: ?[*:0]const u8,
lpDefault: ?[*:0]const u8,
lpReturnedString: ?[*:0]u8,
nSize: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn GetProfileStringW(
lpAppName: ?[*:0]const u16,
lpKeyName: ?[*:0]const u16,
lpDefault: ?[*:0]const u16,
lpReturnedString: ?[*:0]u16,
nSize: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn WriteProfileStringA(
lpAppName: ?[*:0]const u8,
lpKeyName: ?[*:0]const u8,
lpString: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn WriteProfileStringW(
lpAppName: ?[*:0]const u16,
lpKeyName: ?[*:0]const u16,
lpString: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn GetProfileSectionA(
lpAppName: ?[*:0]const u8,
lpReturnedString: ?[*:0]u8,
nSize: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn GetProfileSectionW(
lpAppName: ?[*:0]const u16,
lpReturnedString: ?[*:0]u16,
nSize: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn WriteProfileSectionA(
lpAppName: ?[*:0]const u8,
lpString: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn WriteProfileSectionW(
lpAppName: ?[*:0]const u16,
lpString: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn GetPrivateProfileIntA(
lpAppName: ?[*:0]const u8,
lpKeyName: ?[*:0]const u8,
nDefault: i32,
lpFileName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn GetPrivateProfileIntW(
lpAppName: ?[*:0]const u16,
lpKeyName: ?[*:0]const u16,
nDefault: i32,
lpFileName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn GetPrivateProfileStringA(
lpAppName: ?[*:0]const u8,
lpKeyName: ?[*:0]const u8,
lpDefault: ?[*:0]const u8,
lpReturnedString: ?[*:0]u8,
nSize: u32,
lpFileName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn GetPrivateProfileStringW(
lpAppName: ?[*:0]const u16,
lpKeyName: ?[*:0]const u16,
lpDefault: ?[*:0]const u16,
lpReturnedString: ?[*:0]u16,
nSize: u32,
lpFileName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn WritePrivateProfileStringA(
lpAppName: ?[*:0]const u8,
lpKeyName: ?[*:0]const u8,
lpString: ?[*:0]const u8,
lpFileName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn WritePrivateProfileStringW(
lpAppName: ?[*:0]const u16,
lpKeyName: ?[*:0]const u16,
lpString: ?[*:0]const u16,
lpFileName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn GetPrivateProfileSectionA(
lpAppName: ?[*:0]const u8,
lpReturnedString: ?[*:0]u8,
nSize: u32,
lpFileName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn GetPrivateProfileSectionW(
lpAppName: ?[*:0]const u16,
lpReturnedString: ?[*:0]u16,
nSize: u32,
lpFileName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn WritePrivateProfileSectionA(
lpAppName: ?[*:0]const u8,
lpString: ?[*:0]const u8,
lpFileName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn WritePrivateProfileSectionW(
lpAppName: ?[*:0]const u16,
lpString: ?[*:0]const u16,
lpFileName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn GetPrivateProfileSectionNamesA(
lpszReturnBuffer: ?[*:0]u8,
nSize: u32,
lpFileName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn GetPrivateProfileSectionNamesW(
lpszReturnBuffer: ?[*:0]u16,
nSize: u32,
lpFileName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn GetPrivateProfileStructA(
lpszSection: ?[*:0]const u8,
lpszKey: ?[*:0]const u8,
// TODO: what to do with BytesParamIndex 3?
lpStruct: ?*anyopaque,
uSizeStruct: u32,
szFile: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn GetPrivateProfileStructW(
lpszSection: ?[*:0]const u16,
lpszKey: ?[*:0]const u16,
// TODO: what to do with BytesParamIndex 3?
lpStruct: ?*anyopaque,
uSizeStruct: u32,
szFile: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn WritePrivateProfileStructA(
lpszSection: ?[*:0]const u8,
lpszKey: ?[*:0]const u8,
// TODO: what to do with BytesParamIndex 3?
lpStruct: ?*anyopaque,
uSizeStruct: u32,
szFile: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn WritePrivateProfileStructW(
lpszSection: ?[*:0]const u16,
lpszKey: ?[*:0]const u16,
// TODO: what to do with BytesParamIndex 3?
lpStruct: ?*anyopaque,
uSizeStruct: u32,
szFile: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn IsBadHugeReadPtr(
lp: ?*const anyopaque,
ucb: usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn IsBadHugeWritePtr(
lp: ?*anyopaque,
ucb: usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn GetComputerNameA(
lpBuffer: ?[*:0]u8,
nSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn GetComputerNameW(
lpBuffer: ?[*:0]u16,
nSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn DnsHostnameToComputerNameA(
Hostname: ?[*:0]const u8,
ComputerName: ?[*:0]u8,
nSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn DnsHostnameToComputerNameW(
Hostname: ?[*:0]const u16,
ComputerName: ?[*:0]u16,
nSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ADVAPI32" fn GetUserNameA(
lpBuffer: ?[*:0]u8,
pcbBuffer: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ADVAPI32" fn GetUserNameW(
lpBuffer: ?[*:0]u16,
pcbBuffer: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "ADVAPI32" fn IsTokenUntrusted(
TokenHandle: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn CancelTimerQueueTimer(
TimerQueue: ?HANDLE,
Timer: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ADVAPI32" fn GetCurrentHwProfileA(
lpHwProfileInfo: ?*HW_PROFILE_INFOA,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ADVAPI32" fn GetCurrentHwProfileW(
lpHwProfileInfo: ?*HW_PROFILE_INFOW,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn ReplacePartitionUnit(
TargetPartition: ?PWSTR,
SparePartition: ?PWSTR,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub usingnamespace switch (@import("../zig.zig").arch) {
.X86, .X64 => struct {
pub extern "KERNEL32" fn GetThreadEnabledXStateFeatures(
) callconv(@import("std").os.windows.WINAPI) u64;
}, else => struct { } };
pub usingnamespace switch (@import("../zig.zig").arch) {
.X86, .X64 => struct {
pub extern "KERNEL32" fn EnableProcessOptionalXStateFeatures(
Features: u64,
) callconv(@import("std").os.windows.WINAPI) BOOL;
}, else => struct { } };
pub extern "api-ms-win-core-backgroundtask-l1-1-0" fn RaiseCustomSystemEventTrigger(
CustomSystemEventTriggerConfig: ?*CUSTOM_SYSTEM_EVENT_TRIGGER_CONFIG,
) callconv(@import("std").os.windows.WINAPI) u32;
pub usingnamespace switch (@import("../zig.zig").arch) {
.X64, .Arm64 => struct {
pub extern "KERNEL32" fn uaw_lstrcmpW(
String1: ?*u16,
String2: ?*u16,
) callconv(@import("std").os.windows.WINAPI) i32;
}, else => struct { } };
pub usingnamespace switch (@import("../zig.zig").arch) {
.X64, .Arm64 => struct {
pub extern "KERNEL32" fn uaw_lstrcmpiW(
String1: ?*u16,
String2: ?*u16,
) callconv(@import("std").os.windows.WINAPI) i32;
}, else => struct { } };
pub usingnamespace switch (@import("../zig.zig").arch) {
.X64, .Arm64 => struct {
pub extern "KERNEL32" fn uaw_lstrlenW(
String: ?*u16,
) callconv(@import("std").os.windows.WINAPI) i32;
}, else => struct { } };
pub usingnamespace switch (@import("../zig.zig").arch) {
.X64, .Arm64 => struct {
pub extern "KERNEL32" fn uaw_wcschr(
String: ?*u16,
Character: u16,
) callconv(@import("std").os.windows.WINAPI) ?*u16;
}, else => struct { } };
pub usingnamespace switch (@import("../zig.zig").arch) {
.X64, .Arm64 => struct {
pub extern "KERNEL32" fn uaw_wcscpy(
Destination: ?*u16,
Source: ?*u16,
) callconv(@import("std").os.windows.WINAPI) ?*u16;
}, else => struct { } };
pub usingnamespace switch (@import("../zig.zig").arch) {
.X64, .Arm64 => struct {
pub extern "KERNEL32" fn uaw_wcsicmp(
String1: ?*u16,
String2: ?*u16,
) callconv(@import("std").os.windows.WINAPI) i32;
}, else => struct { } };
pub usingnamespace switch (@import("../zig.zig").arch) {
.X64, .Arm64 => struct {
pub extern "KERNEL32" fn uaw_wcslen(
String: ?*u16,
) callconv(@import("std").os.windows.WINAPI) usize;
}, else => struct { } };
pub usingnamespace switch (@import("../zig.zig").arch) {
.X64, .Arm64 => struct {
pub extern "KERNEL32" fn uaw_wcsrchr(
String: ?*u16,
Character: u16,
) callconv(@import("std").os.windows.WINAPI) ?*u16;
}, else => struct { } };
// TODO: this type is limited to platform 'windows5.0'
pub extern "ntdll" fn NtClose(
Handle: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "ntdll" fn NtOpenFile(
FileHandle: ?*?HANDLE,
DesiredAccess: u32,
ObjectAttributes: ?*OBJECT_ATTRIBUTES,
IoStatusBlock: ?*IO_STATUS_BLOCK,
ShareAccess: u32,
OpenOptions: u32,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "ntdll" fn NtRenameKey(
KeyHandle: ?HANDLE,
NewName: ?*UNICODE_STRING,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "ntdll" fn NtNotifyChangeMultipleKeys(
MasterKeyHandle: ?HANDLE,
Count: u32,
SubordinateObjects: ?[*]OBJECT_ATTRIBUTES,
Event: ?HANDLE,
ApcRoutine: ?PIO_APC_ROUTINE,
ApcContext: ?*anyopaque,
IoStatusBlock: ?*IO_STATUS_BLOCK,
CompletionFilter: u32,
WatchTree: BOOLEAN,
// TODO: what to do with BytesParamIndex 10?
Buffer: ?*anyopaque,
BufferSize: u32,
Asynchronous: BOOLEAN,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "ntdll" fn NtQueryMultipleValueKey(
KeyHandle: ?HANDLE,
ValueEntries: [*]KEY_VALUE_ENTRY,
EntryCount: u32,
// TODO: what to do with BytesParamIndex 4?
ValueBuffer: ?*anyopaque,
BufferLength: ?*u32,
RequiredBufferLength: ?*u32,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "ntdll" fn NtSetInformationKey(
KeyHandle: ?HANDLE,
KeySetInformationClass: KEY_SET_INFORMATION_CLASS,
// TODO: what to do with BytesParamIndex 3?
KeySetInformation: ?*anyopaque,
KeySetInformationLength: u32,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ntdll" fn NtDeviceIoControlFile(
FileHandle: ?HANDLE,
Event: ?HANDLE,
ApcRoutine: ?PIO_APC_ROUTINE,
ApcContext: ?*anyopaque,
IoStatusBlock: ?*IO_STATUS_BLOCK,
IoControlCode: u32,
InputBuffer: ?*anyopaque,
InputBufferLength: u32,
OutputBuffer: ?*anyopaque,
OutputBufferLength: u32,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ntdll" fn NtWaitForSingleObject(
Handle: ?HANDLE,
Alertable: BOOLEAN,
Timeout: ?*LARGE_INTEGER,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "ntdll" fn RtlIsNameLegalDOS8Dot3(
Name: ?*UNICODE_STRING,
OemName: ?*STRING,
NameContainsSpaces: ?*BOOLEAN,
) callconv(@import("std").os.windows.WINAPI) BOOLEAN;
pub extern "ntdll" fn NtQueryObject(
Handle: ?HANDLE,
ObjectInformationClass: OBJECT_INFORMATION_CLASS,
// TODO: what to do with BytesParamIndex 3?
ObjectInformation: ?*anyopaque,
ObjectInformationLength: u32,
ReturnLength: ?*u32,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "ntdll" fn NtQuerySystemInformation(
SystemInformationClass: SYSTEM_INFORMATION_CLASS,
SystemInformation: ?*anyopaque,
SystemInformationLength: u32,
ReturnLength: ?*u32,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "ntdll" fn NtQuerySystemTime(
SystemTime: ?*LARGE_INTEGER,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "ntdll" fn NtQueryTimerResolution(
MaximumTime: ?*u32,
MinimumTime: ?*u32,
CurrentTime: ?*u32,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "ntdll" fn RtlLocalTimeToSystemTime(
LocalTime: ?*LARGE_INTEGER,
SystemTime: ?*LARGE_INTEGER,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "ntdll" fn RtlTimeToSecondsSince1970(
Time: ?*LARGE_INTEGER,
ElapsedSeconds: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOLEAN;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ntdll" fn RtlFreeAnsiString(
AnsiString: ?*STRING,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ntdll" fn RtlFreeUnicodeString(
UnicodeString: ?*UNICODE_STRING,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ntdll" fn RtlFreeOemString(
OemString: ?*STRING,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "ntdll" fn RtlInitString(
DestinationString: ?*STRING,
SourceString: ?*i8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "ntdll" fn RtlInitStringEx(
DestinationString: ?*STRING,
SourceString: ?*i8,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "ntdll" fn RtlInitAnsiString(
DestinationString: ?*STRING,
SourceString: ?*i8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "ntdll" fn RtlInitAnsiStringEx(
DestinationString: ?*STRING,
SourceString: ?*i8,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ntdll" fn RtlInitUnicodeString(
DestinationString: ?*UNICODE_STRING,
SourceString: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ntdll" fn RtlAnsiStringToUnicodeString(
DestinationString: ?*UNICODE_STRING,
SourceString: ?*STRING,
AllocateDestinationString: BOOLEAN,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ntdll" fn RtlUnicodeStringToAnsiString(
DestinationString: ?*STRING,
SourceString: ?*UNICODE_STRING,
AllocateDestinationString: BOOLEAN,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ntdll" fn RtlUnicodeStringToOemString(
DestinationString: ?*STRING,
SourceString: ?*UNICODE_STRING,
AllocateDestinationString: BOOLEAN,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ntdll" fn RtlUnicodeToMultiByteSize(
BytesInMultiByteString: ?*u32,
// TODO: what to do with BytesParamIndex 2?
UnicodeString: ?[*]u16,
BytesInUnicodeString: u32,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ntdll" fn RtlCharToInteger(
String: ?*i8,
Base: u32,
Value: ?*u32,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "ntdll" fn RtlUniform(
Seed: ?*u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "api-ms-win-core-featurestaging-l1-1-0" fn GetFeatureEnabledState(
featureId: u32,
changeTime: FEATURE_CHANGE_TIME,
) callconv(@import("std").os.windows.WINAPI) FEATURE_ENABLED_STATE;
pub extern "api-ms-win-core-featurestaging-l1-1-0" fn RecordFeatureUsage(
featureId: u32,
kind: u32,
addend: u32,
originName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "api-ms-win-core-featurestaging-l1-1-0" fn RecordFeatureError(
featureId: u32,
@"error": ?*const FEATURE_ERROR,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "api-ms-win-core-featurestaging-l1-1-0" fn SubscribeFeatureStateChangeNotification(
subscription: ?*FEATURE_STATE_CHANGE_SUBSCRIPTION,
callback: ?PFEATURE_STATE_CHANGE_CALLBACK,
context: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "api-ms-win-core-featurestaging-l1-1-0" fn UnsubscribeFeatureStateChangeNotification(
subscription: FEATURE_STATE_CHANGE_SUBSCRIPTION,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "api-ms-win-core-featurestaging-l1-1-1" fn GetFeatureVariant(
featureId: u32,
changeTime: FEATURE_CHANGE_TIME,
payloadId: ?*u32,
hasNotification: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "DCIMAN32" fn DCIOpenProvider(
) callconv(@import("std").os.windows.WINAPI) ?HDC;
// TODO: this type is limited to platform 'windows5.0'
pub extern "DCIMAN32" fn DCICloseProvider(
hdc: ?HDC,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "DCIMAN32" fn DCICreatePrimary(
hdc: ?HDC,
lplpSurface: ?*?*DCISURFACEINFO,
) callconv(@import("std").os.windows.WINAPI) i32;
pub extern "DCIMAN32" fn DCICreateOffscreen(
hdc: ?HDC,
dwCompression: u32,
dwRedMask: u32,
dwGreenMask: u32,
dwBlueMask: u32,
dwWidth: u32,
dwHeight: u32,
dwDCICaps: u32,
dwBitCount: u32,
lplpSurface: ?*?*DCIOFFSCREEN,
) callconv(@import("std").os.windows.WINAPI) i32;
pub extern "DCIMAN32" fn DCICreateOverlay(
hdc: ?HDC,
lpOffscreenSurf: ?*anyopaque,
lplpSurface: ?*?*DCIOVERLAY,
) callconv(@import("std").os.windows.WINAPI) i32;
pub extern "DCIMAN32" fn DCIEnum(
hdc: ?HDC,
lprDst: ?*RECT,
lprSrc: ?*RECT,
lpFnCallback: ?*anyopaque,
lpContext: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) i32;
pub extern "DCIMAN32" fn DCISetSrcDestClip(
pdci: ?*DCIOFFSCREEN,
srcrc: ?*RECT,
destrc: ?*RECT,
prd: ?*RGNDATA,
) callconv(@import("std").os.windows.WINAPI) i32;
pub extern "DCIMAN32" fn WinWatchOpen(
hwnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) ?HWINWATCH;
pub extern "DCIMAN32" fn WinWatchClose(
hWW: ?HWINWATCH,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "DCIMAN32" fn WinWatchGetClipList(
hWW: ?HWINWATCH,
prc: ?*RECT,
size: u32,
prd: ?*RGNDATA,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "DCIMAN32" fn WinWatchDidStatusChange(
hWW: ?HWINWATCH,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "DCIMAN32" fn GetWindowRegionData(
hwnd: ?HWND,
size: u32,
prd: ?*RGNDATA,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "DCIMAN32" fn GetDCRegionData(
hdc: ?HDC,
size: u32,
prd: ?*RGNDATA,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "DCIMAN32" fn WinWatchNotify(
hWW: ?HWINWATCH,
NotifyCallback: ?WINWATCHNOTIFYPROC,
NotifyParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "DCIMAN32" fn DCIEndAccess(
pdci: ?*DCISURFACEINFO,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "DCIMAN32" fn DCIBeginAccess(
pdci: ?*DCISURFACEINFO,
x: i32,
y: i32,
dx: i32,
dy: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "DCIMAN32" fn DCIDestroy(
pdci: ?*DCISURFACEINFO,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "DCIMAN32" fn DCIDraw(
pdci: ?*DCIOFFSCREEN,
) callconv(@import("std").os.windows.WINAPI) i32;
pub extern "DCIMAN32" fn DCISetClipList(
pdci: ?*DCIOFFSCREEN,
prd: ?*RGNDATA,
) callconv(@import("std").os.windows.WINAPI) i32;
pub extern "DCIMAN32" fn DCISetDestination(
pdci: ?*DCIOFFSCREEN,
dst: ?*RECT,
src: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) i32;
pub extern "api-ms-win-dx-d3dkmt-l1-1-0" fn GdiEntry13(
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "ADVPACK" fn RunSetupCommandA(
hWnd: ?HWND,
szCmdName: ?[*:0]const u8,
szInfSection: ?[*:0]const u8,
szDir: ?[*:0]const u8,
lpszTitle: ?[*:0]const u8,
phEXE: ?*?HANDLE,
dwFlags: u32,
pvReserved: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn RunSetupCommandW(
hWnd: ?HWND,
szCmdName: ?[*:0]const u16,
szInfSection: ?[*:0]const u16,
szDir: ?[*:0]const u16,
lpszTitle: ?[*:0]const u16,
phEXE: ?*?HANDLE,
dwFlags: u32,
pvReserved: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn NeedRebootInit(
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "ADVPACK" fn NeedReboot(
dwRebootCheck: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "ADVPACK" fn RebootCheckOnInstallA(
hwnd: ?HWND,
pszINF: ?[*:0]const u8,
pszSec: ?[*:0]const u8,
dwReserved: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn RebootCheckOnInstallW(
hwnd: ?HWND,
pszINF: ?[*:0]const u16,
pszSec: ?[*:0]const u16,
dwReserved: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn TranslateInfStringA(
pszInfFilename: ?[*:0]const u8,
pszInstallSection: ?[*:0]const u8,
pszTranslateSection: ?[*:0]const u8,
pszTranslateKey: ?[*:0]const u8,
pszBuffer: ?[*:0]u8,
cchBuffer: u32,
pdwRequiredSize: ?*u32,
pvReserved: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn TranslateInfStringW(
pszInfFilename: ?[*:0]const u16,
pszInstallSection: ?[*:0]const u16,
pszTranslateSection: ?[*:0]const u16,
pszTranslateKey: ?[*:0]const u16,
pszBuffer: ?[*:0]u16,
cchBuffer: u32,
pdwRequiredSize: ?*u32,
pvReserved: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "ADVPACK" fn RegInstallA(
hmod: ?HINSTANCE,
pszSection: ?[*:0]const u8,
pstTable: ?*const STRTABLEA,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "ADVPACK" fn RegInstallW(
hmod: ?HINSTANCE,
pszSection: ?[*:0]const u16,
pstTable: ?*const STRTABLEW,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn LaunchINFSectionExW(
hwnd: ?HWND,
hInstance: ?HINSTANCE,
pszParms: ?PWSTR,
nShow: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn ExecuteCabA(
hwnd: ?HWND,
pCab: ?*CABINFOA,
pReserved: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn ExecuteCabW(
hwnd: ?HWND,
pCab: ?*CABINFOW,
pReserved: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn AdvInstallFileA(
hwnd: ?HWND,
lpszSourceDir: ?[*:0]const u8,
lpszSourceFile: ?[*:0]const u8,
lpszDestDir: ?[*:0]const u8,
lpszDestFile: ?[*:0]const u8,
dwFlags: u32,
dwReserved: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn AdvInstallFileW(
hwnd: ?HWND,
lpszSourceDir: ?[*:0]const u16,
lpszSourceFile: ?[*:0]const u16,
lpszDestDir: ?[*:0]const u16,
lpszDestFile: ?[*:0]const u16,
dwFlags: u32,
dwReserved: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn RegSaveRestoreA(
hWnd: ?HWND,
pszTitleString: ?[*:0]const u8,
hkBckupKey: ?HKEY,
pcszRootKey: ?[*:0]const u8,
pcszSubKey: ?[*:0]const u8,
pcszValueName: ?[*:0]const u8,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn RegSaveRestoreW(
hWnd: ?HWND,
pszTitleString: ?[*:0]const u16,
hkBckupKey: ?HKEY,
pcszRootKey: ?[*:0]const u16,
pcszSubKey: ?[*:0]const u16,
pcszValueName: ?[*:0]const u16,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn RegSaveRestoreOnINFA(
hWnd: ?HWND,
pszTitle: ?[*:0]const u8,
pszINF: ?[*:0]const u8,
pszSection: ?[*:0]const u8,
hHKLMBackKey: ?HKEY,
hHKCUBackKey: ?HKEY,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn RegSaveRestoreOnINFW(
hWnd: ?HWND,
pszTitle: ?[*:0]const u16,
pszINF: ?[*:0]const u16,
pszSection: ?[*:0]const u16,
hHKLMBackKey: ?HKEY,
hHKCUBackKey: ?HKEY,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn RegRestoreAllA(
hWnd: ?HWND,
pszTitleString: ?[*:0]const u8,
hkBckupKey: ?HKEY,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn RegRestoreAllW(
hWnd: ?HWND,
pszTitleString: ?[*:0]const u16,
hkBckupKey: ?HKEY,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn FileSaveRestoreW(
hDlg: ?HWND,
lpFileList: ?PWSTR,
lpDir: ?[*:0]const u16,
lpBaseName: ?[*:0]const u16,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn FileSaveRestoreOnINFA(
hWnd: ?HWND,
pszTitle: ?[*:0]const u8,
pszINF: ?[*:0]const u8,
pszSection: ?[*:0]const u8,
pszBackupDir: ?[*:0]const u8,
pszBaseBackupFile: ?[*:0]const u8,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn FileSaveRestoreOnINFW(
hWnd: ?HWND,
pszTitle: ?[*:0]const u16,
pszINF: ?[*:0]const u16,
pszSection: ?[*:0]const u16,
pszBackupDir: ?[*:0]const u16,
pszBaseBackupFile: ?[*:0]const u16,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn AddDelBackupEntryA(
lpcszFileList: ?[*:0]const u8,
lpcszBackupDir: ?[*:0]const u8,
lpcszBaseName: ?[*:0]const u8,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn AddDelBackupEntryW(
lpcszFileList: ?[*:0]const u16,
lpcszBackupDir: ?[*:0]const u16,
lpcszBaseName: ?[*:0]const u16,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn FileSaveMarkNotExistA(
lpFileList: ?[*:0]const u8,
lpDir: ?[*:0]const u8,
lpBaseName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn FileSaveMarkNotExistW(
lpFileList: ?[*:0]const u16,
lpDir: ?[*:0]const u16,
lpBaseName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn GetVersionFromFileA(
lpszFilename: ?[*:0]const u8,
pdwMSVer: ?*u32,
pdwLSVer: ?*u32,
bVersion: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn GetVersionFromFileW(
lpszFilename: ?[*:0]const u16,
pdwMSVer: ?*u32,
pdwLSVer: ?*u32,
bVersion: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn GetVersionFromFileExA(
lpszFilename: ?[*:0]const u8,
pdwMSVer: ?*u32,
pdwLSVer: ?*u32,
bVersion: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn GetVersionFromFileExW(
lpszFilename: ?[*:0]const u16,
pdwMSVer: ?*u32,
pdwLSVer: ?*u32,
bVersion: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn IsNTAdmin(
dwReserved: u32,
lpdwReserved: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "ADVPACK" fn DelNodeA(
pszFileOrDirName: ?[*:0]const u8,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn DelNodeW(
pszFileOrDirName: ?[*:0]const u16,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn DelNodeRunDLL32W(
hwnd: ?HWND,
hInstance: ?HINSTANCE,
pszParms: ?PWSTR,
nShow: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn OpenINFEngineA(
pszInfFilename: ?[*:0]const u8,
pszInstallSection: ?[*:0]const u8,
dwFlags: u32,
phInf: ?*?*anyopaque,
pvReserved: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn OpenINFEngineW(
pszInfFilename: ?[*:0]const u16,
pszInstallSection: ?[*:0]const u16,
dwFlags: u32,
phInf: ?*?*anyopaque,
pvReserved: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn TranslateInfStringExA(
hInf: ?*anyopaque,
pszInfFilename: ?[*:0]const u8,
pszTranslateSection: ?[*:0]const u8,
pszTranslateKey: ?[*:0]const u8,
pszBuffer: [*:0]u8,
dwBufferSize: u32,
pdwRequiredSize: ?*u32,
pvReserved: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn TranslateInfStringExW(
hInf: ?*anyopaque,
pszInfFilename: ?[*:0]const u16,
pszTranslateSection: ?[*:0]const u16,
pszTranslateKey: ?[*:0]const u16,
pszBuffer: [*:0]u16,
dwBufferSize: u32,
pdwRequiredSize: ?*u32,
pvReserved: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn CloseINFEngine(
hInf: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn ExtractFilesA(
pszCabName: ?[*:0]const u8,
pszExpandDir: ?[*:0]const u8,
dwFlags: u32,
pszFileList: ?[*:0]const u8,
lpReserved: ?*anyopaque,
dwReserved: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn ExtractFilesW(
pszCabName: ?[*:0]const u16,
pszExpandDir: ?[*:0]const u16,
dwFlags: u32,
pszFileList: ?[*:0]const u16,
lpReserved: ?*anyopaque,
dwReserved: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn LaunchINFSectionW(
hwndOwner: ?HWND,
hInstance: ?HINSTANCE,
pszParams: ?PWSTR,
nShow: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub extern "ADVPACK" fn UserInstStubWrapperA(
hwnd: ?HWND,
hInstance: ?HINSTANCE,
pszParms: ?[*:0]const u8,
nShow: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn UserInstStubWrapperW(
hwnd: ?HWND,
hInstance: ?HINSTANCE,
pszParms: ?[*:0]const u16,
nShow: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn UserUnInstStubWrapperA(
hwnd: ?HWND,
hInstance: ?HINSTANCE,
pszParms: ?[*:0]const u8,
nShow: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn UserUnInstStubWrapperW(
hwnd: ?HWND,
hInstance: ?HINSTANCE,
pszParms: ?[*:0]const u16,
nShow: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn SetPerUserSecValuesA(
pPerUser: ?*PERUSERSECTIONA,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "ADVPACK" fn SetPerUserSecValuesW(
pPerUser: ?*PERUSERSECTIONW,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SendIMEMessageExA(
param0: ?HWND,
param1: LPARAM,
) callconv(@import("std").os.windows.WINAPI) LRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SendIMEMessageExW(
param0: ?HWND,
param1: LPARAM,
) callconv(@import("std").os.windows.WINAPI) LRESULT;
pub extern "USER32" fn IMPGetIMEA(
param0: ?HWND,
param1: ?*IMEPROA,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "USER32" fn IMPGetIMEW(
param0: ?HWND,
param1: ?*IMEPROW,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "USER32" fn IMPQueryIMEA(
param0: ?*IMEPROA,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "USER32" fn IMPQueryIMEW(
param0: ?*IMEPROW,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "USER32" fn IMPSetIMEA(
param0: ?HWND,
param1: ?*IMEPROA,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "USER32" fn IMPSetIMEW(
param0: ?HWND,
param1: ?*IMEPROW,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "USER32" fn WINNLSGetIMEHotkey(
param0: ?HWND,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn WINNLSEnableIME(
param0: ?HWND,
param1: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "USER32" fn WINNLSGetEnableStatus(
param0: ?HWND,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "APPHELP" fn ApphelpCheckShellObject(
ObjectCLSID: ?*const Guid,
bShimIfNecessary: BOOL,
pullFlags: ?*u64,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "Wldp" fn WldpGetLockdownPolicy(
hostInformation: ?*WLDP_HOST_INFORMATION,
lockdownState: ?*u32,
lockdownFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "Wldp" fn WldpIsClassInApprovedList(
classID: ?*const Guid,
hostInformation: ?*WLDP_HOST_INFORMATION,
isApproved: ?*BOOL,
optionalFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "Wldp" fn WldpSetDynamicCodeTrust(
fileHandle: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "Wldp" fn WldpIsDynamicCodePolicyEnabled(
isEnabled: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "Wldp" fn WldpQueryDynamicCodeTrust(
fileHandle: ?HANDLE,
// TODO: what to do with BytesParamIndex 2?
baseImage: ?*anyopaque,
imageSize: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "Wldp" fn WldpQueryDeviceSecurityInformation(
information: ?[*]WLDP_DEVICE_SECURITY_INFORMATION,
informationLength: u32,
returnLength: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (52)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../zig.zig").unicode_mode) {
.ansi => struct {
pub const HW_PROFILE_INFO = thismodule.HW_PROFILE_INFOA;
pub const STRENTRY = thismodule.STRENTRYA;
pub const STRTABLE = thismodule.STRTABLEA;
pub const CABINFO = thismodule.CABINFOA;
pub const PERUSERSECTION = thismodule.PERUSERSECTIONA;
pub const IMEPRO = thismodule.IMEPROA;
pub const GetFirmwareEnvironmentVariable = thismodule.GetFirmwareEnvironmentVariableA;
pub const GetFirmwareEnvironmentVariableEx = thismodule.GetFirmwareEnvironmentVariableExA;
pub const SetFirmwareEnvironmentVariable = thismodule.SetFirmwareEnvironmentVariableA;
pub const SetFirmwareEnvironmentVariableEx = thismodule.SetFirmwareEnvironmentVariableExA;
pub const GetProfileInt = thismodule.GetProfileIntA;
pub const GetProfileString = thismodule.GetProfileStringA;
pub const WriteProfileString = thismodule.WriteProfileStringA;
pub const GetProfileSection = thismodule.GetProfileSectionA;
pub const WriteProfileSection = thismodule.WriteProfileSectionA;
pub const GetPrivateProfileInt = thismodule.GetPrivateProfileIntA;
pub const GetPrivateProfileString = thismodule.GetPrivateProfileStringA;
pub const WritePrivateProfileString = thismodule.WritePrivateProfileStringA;
pub const GetPrivateProfileSection = thismodule.GetPrivateProfileSectionA;
pub const WritePrivateProfileSection = thismodule.WritePrivateProfileSectionA;
pub const GetPrivateProfileSectionNames = thismodule.GetPrivateProfileSectionNamesA;
pub const GetPrivateProfileStruct = thismodule.GetPrivateProfileStructA;
pub const WritePrivateProfileStruct = thismodule.WritePrivateProfileStructA;
pub const GetComputerName = thismodule.GetComputerNameA;
pub const DnsHostnameToComputerName = thismodule.DnsHostnameToComputerNameA;
pub const GetUserName = thismodule.GetUserNameA;
pub const GetCurrentHwProfile = thismodule.GetCurrentHwProfileA;
pub const RunSetupCommand = thismodule.RunSetupCommandA;
pub const RebootCheckOnInstall = thismodule.RebootCheckOnInstallA;
pub const TranslateInfString = thismodule.TranslateInfStringA;
pub const RegInstall = thismodule.RegInstallA;
pub const ExecuteCab = thismodule.ExecuteCabA;
pub const AdvInstallFile = thismodule.AdvInstallFileA;
pub const RegSaveRestore = thismodule.RegSaveRestoreA;
pub const RegSaveRestoreOnINF = thismodule.RegSaveRestoreOnINFA;
pub const RegRestoreAll = thismodule.RegRestoreAllA;
pub const FileSaveRestoreOnINF = thismodule.FileSaveRestoreOnINFA;
pub const AddDelBackupEntry = thismodule.AddDelBackupEntryA;
pub const FileSaveMarkNotExist = thismodule.FileSaveMarkNotExistA;
pub const GetVersionFromFile = thismodule.GetVersionFromFileA;
pub const GetVersionFromFileEx = thismodule.GetVersionFromFileExA;
pub const DelNode = thismodule.DelNodeA;
pub const OpenINFEngine = thismodule.OpenINFEngineA;
pub const TranslateInfStringEx = thismodule.TranslateInfStringExA;
pub const ExtractFiles = thismodule.ExtractFilesA;
pub const UserInstStubWrapper = thismodule.UserInstStubWrapperA;
pub const UserUnInstStubWrapper = thismodule.UserUnInstStubWrapperA;
pub const SetPerUserSecValues = thismodule.SetPerUserSecValuesA;
pub const SendIMEMessageEx = thismodule.SendIMEMessageExA;
pub const IMPGetIME = thismodule.IMPGetIMEA;
pub const IMPQueryIME = thismodule.IMPQueryIMEA;
pub const IMPSetIME = thismodule.IMPSetIMEA;
},
.wide => struct {
pub const HW_PROFILE_INFO = thismodule.HW_PROFILE_INFOW;
pub const STRENTRY = thismodule.STRENTRYW;
pub const STRTABLE = thismodule.STRTABLEW;
pub const CABINFO = thismodule.CABINFOW;
pub const PERUSERSECTION = thismodule.PERUSERSECTIONW;
pub const IMEPRO = thismodule.IMEPROW;
pub const GetFirmwareEnvironmentVariable = thismodule.GetFirmwareEnvironmentVariableW;
pub const GetFirmwareEnvironmentVariableEx = thismodule.GetFirmwareEnvironmentVariableExW;
pub const SetFirmwareEnvironmentVariable = thismodule.SetFirmwareEnvironmentVariableW;
pub const SetFirmwareEnvironmentVariableEx = thismodule.SetFirmwareEnvironmentVariableExW;
pub const GetProfileInt = thismodule.GetProfileIntW;
pub const GetProfileString = thismodule.GetProfileStringW;
pub const WriteProfileString = thismodule.WriteProfileStringW;
pub const GetProfileSection = thismodule.GetProfileSectionW;
pub const WriteProfileSection = thismodule.WriteProfileSectionW;
pub const GetPrivateProfileInt = thismodule.GetPrivateProfileIntW;
pub const GetPrivateProfileString = thismodule.GetPrivateProfileStringW;
pub const WritePrivateProfileString = thismodule.WritePrivateProfileStringW;
pub const GetPrivateProfileSection = thismodule.GetPrivateProfileSectionW;
pub const WritePrivateProfileSection = thismodule.WritePrivateProfileSectionW;
pub const GetPrivateProfileSectionNames = thismodule.GetPrivateProfileSectionNamesW;
pub const GetPrivateProfileStruct = thismodule.GetPrivateProfileStructW;
pub const WritePrivateProfileStruct = thismodule.WritePrivateProfileStructW;
pub const GetComputerName = thismodule.GetComputerNameW;
pub const DnsHostnameToComputerName = thismodule.DnsHostnameToComputerNameW;
pub const GetUserName = thismodule.GetUserNameW;
pub const GetCurrentHwProfile = thismodule.GetCurrentHwProfileW;
pub const RunSetupCommand = thismodule.RunSetupCommandW;
pub const RebootCheckOnInstall = thismodule.RebootCheckOnInstallW;
pub const TranslateInfString = thismodule.TranslateInfStringW;
pub const RegInstall = thismodule.RegInstallW;
pub const ExecuteCab = thismodule.ExecuteCabW;
pub const AdvInstallFile = thismodule.AdvInstallFileW;
pub const RegSaveRestore = thismodule.RegSaveRestoreW;
pub const RegSaveRestoreOnINF = thismodule.RegSaveRestoreOnINFW;
pub const RegRestoreAll = thismodule.RegRestoreAllW;
pub const FileSaveRestoreOnINF = thismodule.FileSaveRestoreOnINFW;
pub const AddDelBackupEntry = thismodule.AddDelBackupEntryW;
pub const FileSaveMarkNotExist = thismodule.FileSaveMarkNotExistW;
pub const GetVersionFromFile = thismodule.GetVersionFromFileW;
pub const GetVersionFromFileEx = thismodule.GetVersionFromFileExW;
pub const DelNode = thismodule.DelNodeW;
pub const OpenINFEngine = thismodule.OpenINFEngineW;
pub const TranslateInfStringEx = thismodule.TranslateInfStringExW;
pub const ExtractFiles = thismodule.ExtractFilesW;
pub const UserInstStubWrapper = thismodule.UserInstStubWrapperW;
pub const UserUnInstStubWrapper = thismodule.UserUnInstStubWrapperW;
pub const SetPerUserSecValues = thismodule.SetPerUserSecValuesW;
pub const SendIMEMessageEx = thismodule.SendIMEMessageExW;
pub const IMPGetIME = thismodule.IMPGetIMEW;
pub const IMPQueryIME = thismodule.IMPQueryIMEW;
pub const IMPSetIME = thismodule.IMPSetIMEW;
},
.unspecified => if (@import("builtin").is_test) struct {
pub const HW_PROFILE_INFO = *opaque{};
pub const STRENTRY = *opaque{};
pub const STRTABLE = *opaque{};
pub const CABINFO = *opaque{};
pub const PERUSERSECTION = *opaque{};
pub const IMEPRO = *opaque{};
pub const GetFirmwareEnvironmentVariable = *opaque{};
pub const GetFirmwareEnvironmentVariableEx = *opaque{};
pub const SetFirmwareEnvironmentVariable = *opaque{};
pub const SetFirmwareEnvironmentVariableEx = *opaque{};
pub const GetProfileInt = *opaque{};
pub const GetProfileString = *opaque{};
pub const WriteProfileString = *opaque{};
pub const GetProfileSection = *opaque{};
pub const WriteProfileSection = *opaque{};
pub const GetPrivateProfileInt = *opaque{};
pub const GetPrivateProfileString = *opaque{};
pub const WritePrivateProfileString = *opaque{};
pub const GetPrivateProfileSection = *opaque{};
pub const WritePrivateProfileSection = *opaque{};
pub const GetPrivateProfileSectionNames = *opaque{};
pub const GetPrivateProfileStruct = *opaque{};
pub const WritePrivateProfileStruct = *opaque{};
pub const GetComputerName = *opaque{};
pub const DnsHostnameToComputerName = *opaque{};
pub const GetUserName = *opaque{};
pub const GetCurrentHwProfile = *opaque{};
pub const RunSetupCommand = *opaque{};
pub const RebootCheckOnInstall = *opaque{};
pub const TranslateInfString = *opaque{};
pub const RegInstall = *opaque{};
pub const ExecuteCab = *opaque{};
pub const AdvInstallFile = *opaque{};
pub const RegSaveRestore = *opaque{};
pub const RegSaveRestoreOnINF = *opaque{};
pub const RegRestoreAll = *opaque{};
pub const FileSaveRestoreOnINF = *opaque{};
pub const AddDelBackupEntry = *opaque{};
pub const FileSaveMarkNotExist = *opaque{};
pub const GetVersionFromFile = *opaque{};
pub const GetVersionFromFileEx = *opaque{};
pub const DelNode = *opaque{};
pub const OpenINFEngine = *opaque{};
pub const TranslateInfStringEx = *opaque{};
pub const ExtractFiles = *opaque{};
pub const UserInstStubWrapper = *opaque{};
pub const UserUnInstStubWrapper = *opaque{};
pub const SetPerUserSecValues = *opaque{};
pub const SendIMEMessageEx = *opaque{};
pub const IMPGetIME = *opaque{};
pub const IMPQueryIME = *opaque{};
pub const IMPSetIME = *opaque{};
} else struct {
pub const HW_PROFILE_INFO = @compileError("'HW_PROFILE_INFO' requires that UNICODE be set to true or false in the root module");
pub const STRENTRY = @compileError("'STRENTRY' requires that UNICODE be set to true or false in the root module");
pub const STRTABLE = @compileError("'STRTABLE' requires that UNICODE be set to true or false in the root module");
pub const CABINFO = @compileError("'CABINFO' requires that UNICODE be set to true or false in the root module");
pub const PERUSERSECTION = @compileError("'PERUSERSECTION' requires that UNICODE be set to true or false in the root module");
pub const IMEPRO = @compileError("'IMEPRO' requires that UNICODE be set to true or false in the root module");
pub const GetFirmwareEnvironmentVariable = @compileError("'GetFirmwareEnvironmentVariable' requires that UNICODE be set to true or false in the root module");
pub const GetFirmwareEnvironmentVariableEx = @compileError("'GetFirmwareEnvironmentVariableEx' requires that UNICODE be set to true or false in the root module");
pub const SetFirmwareEnvironmentVariable = @compileError("'SetFirmwareEnvironmentVariable' requires that UNICODE be set to true or false in the root module");
pub const SetFirmwareEnvironmentVariableEx = @compileError("'SetFirmwareEnvironmentVariableEx' requires that UNICODE be set to true or false in the root module");
pub const GetProfileInt = @compileError("'GetProfileInt' requires that UNICODE be set to true or false in the root module");
pub const GetProfileString = @compileError("'GetProfileString' requires that UNICODE be set to true or false in the root module");
pub const WriteProfileString = @compileError("'WriteProfileString' requires that UNICODE be set to true or false in the root module");
pub const GetProfileSection = @compileError("'GetProfileSection' requires that UNICODE be set to true or false in the root module");
pub const WriteProfileSection = @compileError("'WriteProfileSection' requires that UNICODE be set to true or false in the root module");
pub const GetPrivateProfileInt = @compileError("'GetPrivateProfileInt' requires that UNICODE be set to true or false in the root module");
pub const GetPrivateProfileString = @compileError("'GetPrivateProfileString' requires that UNICODE be set to true or false in the root module");
pub const WritePrivateProfileString = @compileError("'WritePrivateProfileString' requires that UNICODE be set to true or false in the root module");
pub const GetPrivateProfileSection = @compileError("'GetPrivateProfileSection' requires that UNICODE be set to true or false in the root module");
pub const WritePrivateProfileSection = @compileError("'WritePrivateProfileSection' requires that UNICODE be set to true or false in the root module");
pub const GetPrivateProfileSectionNames = @compileError("'GetPrivateProfileSectionNames' requires that UNICODE be set to true or false in the root module");
pub const GetPrivateProfileStruct = @compileError("'GetPrivateProfileStruct' requires that UNICODE be set to true or false in the root module");
pub const WritePrivateProfileStruct = @compileError("'WritePrivateProfileStruct' requires that UNICODE be set to true or false in the root module");
pub const GetComputerName = @compileError("'GetComputerName' requires that UNICODE be set to true or false in the root module");
pub const DnsHostnameToComputerName = @compileError("'DnsHostnameToComputerName' requires that UNICODE be set to true or false in the root module");
pub const GetUserName = @compileError("'GetUserName' requires that UNICODE be set to true or false in the root module");
pub const GetCurrentHwProfile = @compileError("'GetCurrentHwProfile' requires that UNICODE be set to true or false in the root module");
pub const RunSetupCommand = @compileError("'RunSetupCommand' requires that UNICODE be set to true or false in the root module");
pub const RebootCheckOnInstall = @compileError("'RebootCheckOnInstall' requires that UNICODE be set to true or false in the root module");
pub const TranslateInfString = @compileError("'TranslateInfString' requires that UNICODE be set to true or false in the root module");
pub const RegInstall = @compileError("'RegInstall' requires that UNICODE be set to true or false in the root module");
pub const ExecuteCab = @compileError("'ExecuteCab' requires that UNICODE be set to true or false in the root module");
pub const AdvInstallFile = @compileError("'AdvInstallFile' requires that UNICODE be set to true or false in the root module");
pub const RegSaveRestore = @compileError("'RegSaveRestore' requires that UNICODE be set to true or false in the root module");
pub const RegSaveRestoreOnINF = @compileError("'RegSaveRestoreOnINF' requires that UNICODE be set to true or false in the root module");
pub const RegRestoreAll = @compileError("'RegRestoreAll' requires that UNICODE be set to true or false in the root module");
pub const FileSaveRestoreOnINF = @compileError("'FileSaveRestoreOnINF' requires that UNICODE be set to true or false in the root module");
pub const AddDelBackupEntry = @compileError("'AddDelBackupEntry' requires that UNICODE be set to true or false in the root module");
pub const FileSaveMarkNotExist = @compileError("'FileSaveMarkNotExist' requires that UNICODE be set to true or false in the root module");
pub const GetVersionFromFile = @compileError("'GetVersionFromFile' requires that UNICODE be set to true or false in the root module");
pub const GetVersionFromFileEx = @compileError("'GetVersionFromFileEx' requires that UNICODE be set to true or false in the root module");
pub const DelNode = @compileError("'DelNode' requires that UNICODE be set to true or false in the root module");
pub const OpenINFEngine = @compileError("'OpenINFEngine' requires that UNICODE be set to true or false in the root module");
pub const TranslateInfStringEx = @compileError("'TranslateInfStringEx' requires that UNICODE be set to true or false in the root module");
pub const ExtractFiles = @compileError("'ExtractFiles' requires that UNICODE be set to true or false in the root module");
pub const UserInstStubWrapper = @compileError("'UserInstStubWrapper' requires that UNICODE be set to true or false in the root module");
pub const UserUnInstStubWrapper = @compileError("'UserUnInstStubWrapper' requires that UNICODE be set to true or false in the root module");
pub const SetPerUserSecValues = @compileError("'SetPerUserSecValues' requires that UNICODE be set to true or false in the root module");
pub const SendIMEMessageEx = @compileError("'SendIMEMessageEx' requires that UNICODE be set to true or false in the root module");
pub const IMPGetIME = @compileError("'IMPGetIME' requires that UNICODE be set to true or false in the root module");
pub const IMPQueryIME = @compileError("'IMPQueryIME' requires that UNICODE be set to true or false in the root module");
pub const IMPSetIME = @compileError("'IMPSetIME' requires that UNICODE be set to true or false in the root module");
},
};
//--------------------------------------------------------------------------------
// Section: Imports (27)
//--------------------------------------------------------------------------------
const Guid = @import("../zig.zig").Guid;
const BOOL = @import("../foundation.zig").BOOL;
const BOOLEAN = @import("../foundation.zig").BOOLEAN;
const BSTR = @import("../foundation.zig").BSTR;
const CHAR = @import("../foundation.zig").CHAR;
const FILETIME = @import("../foundation.zig").FILETIME;
const HANDLE = @import("../foundation.zig").HANDLE;
const HDC = @import("../graphics/gdi.zig").HDC;
const HINSTANCE = @import("../foundation.zig").HINSTANCE;
const HKEY = @import("../system/registry.zig").HKEY;
const HRESULT = @import("../foundation.zig").HRESULT;
const HWND = @import("../foundation.zig").HWND;
const IUnknown = @import("../system/com.zig").IUnknown;
const LARGE_INTEGER = @import("../foundation.zig").LARGE_INTEGER;
const LIST_ENTRY = @import("../system/kernel.zig").LIST_ENTRY;
const LPARAM = @import("../foundation.zig").LPARAM;
const LRESULT = @import("../foundation.zig").LRESULT;
const NTSTATUS = @import("../foundation.zig").NTSTATUS;
const PSTR = @import("../foundation.zig").PSTR;
const PWSTR = @import("../foundation.zig").PWSTR;
const RECT = @import("../foundation.zig").RECT;
const RGNDATA = @import("../graphics/gdi.zig").RGNDATA;
const SAFEARRAY = @import("../system/com.zig").SAFEARRAY;
const SECURITY_ATTRIBUTES = @import("../security.zig").SECURITY_ATTRIBUTES;
const STRING = @import("../system/kernel.zig").STRING;
const UNICODE_STRING = @import("../foundation.zig").UNICODE_STRING;
const WPARAM = @import("../foundation.zig").WPARAM;
test {
// The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476
if (@hasDecl(@This(), "PFIBER_CALLOUT_ROUTINE")) { _ = PFIBER_CALLOUT_ROUTINE; }
if (@hasDecl(@This(), "PQUERYACTCTXW_FUNC")) { _ = PQUERYACTCTXW_FUNC; }
if (@hasDecl(@This(), "APPLICATION_RECOVERY_CALLBACK")) { _ = APPLICATION_RECOVERY_CALLBACK; }
if (@hasDecl(@This(), "PIO_APC_ROUTINE")) { _ = PIO_APC_ROUTINE; }
if (@hasDecl(@This(), "PWINSTATIONQUERYINFORMATIONW")) { _ = PWINSTATIONQUERYINFORMATIONW; }
if (@hasDecl(@This(), "PFEATURE_STATE_CHANGE_CALLBACK")) { _ = PFEATURE_STATE_CHANGE_CALLBACK; }
if (@hasDecl(@This(), "ENUM_CALLBACK")) { _ = ENUM_CALLBACK; }
if (@hasDecl(@This(), "WINWATCHNOTIFYPROC")) { _ = WINWATCHNOTIFYPROC; }
if (@hasDecl(@This(), "REGINSTALLA")) { _ = REGINSTALLA; }
if (@hasDecl(@This(), "PWLDP_SETDYNAMICCODETRUST_API")) { _ = PWLDP_SETDYNAMICCODETRUST_API; }
if (@hasDecl(@This(), "PWLDP_ISDYNAMICCODEPOLICYENABLED_API")) { _ = PWLDP_ISDYNAMICCODEPOLICYENABLED_API; }
if (@hasDecl(@This(), "PWLDP_QUERYDYNAMICODETRUST_API")) { _ = PWLDP_QUERYDYNAMICODETRUST_API; }
if (@hasDecl(@This(), "PWLDP_QUERYWINDOWSLOCKDOWNMODE_API")) { _ = PWLDP_QUERYWINDOWSLOCKDOWNMODE_API; }
if (@hasDecl(@This(), "PWLDP_QUERYDEVICESECURITYINFORMATION_API")) { _ = PWLDP_QUERYDEVICESECURITYINFORMATION_API; }
if (@hasDecl(@This(), "PWLDP_QUERYWINDOWSLOCKDOWNRESTRICTION_API")) { _ = PWLDP_QUERYWINDOWSLOCKDOWNRESTRICTION_API; }
if (@hasDecl(@This(), "PWLDP_SETWINDOWSLOCKDOWNRESTRICTION_API")) { _ = PWLDP_SETWINDOWSLOCKDOWNRESTRICTION_API; }
if (@hasDecl(@This(), "PWLDP_ISAPPAPPROVEDBYPOLICY_API")) { _ = PWLDP_ISAPPAPPROVEDBYPOLICY_API; }
if (@hasDecl(@This(), "PWLDP_QUERYPOLICYSETTINGENABLED_API")) { _ = PWLDP_QUERYPOLICYSETTINGENABLED_API; }
if (@hasDecl(@This(), "PWLDP_QUERYPOLICYSETTINGENABLED2_API")) { _ = PWLDP_QUERYPOLICYSETTINGENABLED2_API; }
if (@hasDecl(@This(), "PWLDP_ISWCOSPRODUCTIONCONFIGURATION_API")) { _ = PWLDP_ISWCOSPRODUCTIONCONFIGURATION_API; }
if (@hasDecl(@This(), "PWLDP_RESETWCOSPRODUCTIONCONFIGURATION_API")) { _ = PWLDP_RESETWCOSPRODUCTIONCONFIGURATION_API; }
if (@hasDecl(@This(), "PWLDP_ISPRODUCTIONCONFIGURATION_API")) { _ = PWLDP_ISPRODUCTIONCONFIGURATION_API; }
if (@hasDecl(@This(), "PWLDP_RESETPRODUCTIONCONFIGURATION_API")) { _ = PWLDP_RESETPRODUCTIONCONFIGURATION_API; }
if (@hasDecl(@This(), "PDELAYLOAD_FAILURE_DLL_CALLBACK")) { _ = PDELAYLOAD_FAILURE_DLL_CALLBACK; }
@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/windows_programming.zig |
pub const InstructionName = enum(u8) {
nop = 0,
scope_push = 1, // deprecated
scope_pop = 2, // deprecated
declare = 3, // deprecated
store_global_name = 4, // deprecated
load_global_name = 5, // deprecated
push_str = 6,
push_num = 7,
array_pack = 8,
call_fn = 9,
call_obj = 10,
pop = 11,
add = 12,
sub = 13,
mul = 14,
div = 15,
mod = 16,
bool_and = 17,
bool_or = 18,
bool_not = 19,
negate = 20,
eq = 21,
neq = 22,
less_eq = 23,
greater_eq = 24,
less = 25,
greater = 26,
jmp = 27,
jnf = 28,
iter_make = 29,
iter_next = 30,
array_store = 31,
array_load = 32,
ret = 33,
store_local = 34,
load_local = 35,
// HERE BE HOLE
retval = 37,
jif = 38,
store_global_idx = 39,
load_global_idx = 40,
push_true = 41,
push_false = 42,
push_void = 43,
};
/// This union contains each possible instruction with its (optional) arguments already encoded.
/// Each instruction type is either `NoArg`, `SingleArg`, `CallArg` or `Deprecated`, defining how
/// each instruction is encoded.
/// This information can be used to encode/decode the instructions based on their meta-information.
pub const Instruction = union(InstructionName) {
pub const Deprecated = struct {};
pub const NoArg = struct {};
fn SingleArg(comptime T: type) type {
return struct { value: T };
}
pub const CallArg = struct {
function: []const u8,
argc: u8,
};
nop: NoArg,
scope_push: Deprecated,
scope_pop: Deprecated,
declare: Deprecated,
store_global_name: Deprecated,
load_global_name: Deprecated,
push_str: SingleArg([]const u8),
push_num: SingleArg(f64),
array_pack: SingleArg(u16),
call_fn: CallArg,
call_obj: CallArg,
pop: NoArg,
add: NoArg,
sub: NoArg,
mul: NoArg,
div: NoArg,
mod: NoArg,
bool_and: NoArg,
bool_or: NoArg,
bool_not: NoArg,
negate: NoArg,
eq: NoArg,
neq: NoArg,
less_eq: NoArg,
greater_eq: NoArg,
less: NoArg,
greater: NoArg,
jmp: SingleArg(u32),
jnf: SingleArg(u32),
iter_make: NoArg,
iter_next: NoArg,
array_store: NoArg,
array_load: NoArg,
ret: NoArg,
store_local: SingleArg(u16),
load_local: SingleArg(u16),
retval: NoArg,
jif: SingleArg(u32),
store_global_idx: SingleArg(u16),
load_global_idx: SingleArg(u16),
push_true: NoArg,
push_false: NoArg,
push_void: NoArg,
}; | src/library/common/ir.zig |
const std = @import("std");
const common = @import("common.zig");
const rom = @import("rom.zig");
pub const encodings = @import("gen4/encodings.zig");
pub const offsets = @import("gen4/offsets.zig");
pub const script = @import("gen4/script.zig");
comptime {
_ = encodings;
}
const debug = std.debug;
const io = std.io;
const math = std.math;
const mem = std.mem;
const nds = rom.nds;
const lu128 = rom.int.lu128;
const lu16 = rom.int.lu16;
const lu32 = rom.int.lu32;
pub const BasePokemon = extern struct {
stats: common.Stats,
types: [2]u8,
catch_rate: u8,
base_exp_yield: u8,
ev_yield: common.EvYield,
items: [2]lu16,
gender_ratio: u8,
egg_cycles: u8,
base_friendship: u8,
growth_rate: common.GrowthRate,
egg_groups: [2]common.EggGroup,
abilities: [2]u8,
flee_rate: u8,
color: common.Color,
unknown: [2]u8,
// Memory layout
// TMS 01-92, HMS 01-08
machine_learnset: lu128,
comptime {
std.debug.assert(@sizeOf(@This()) == 44);
}
};
pub const Evolution = extern struct {
method: common.EvoMethod,
padding: u8,
param: lu16,
target: lu16,
comptime {
std.debug.assert(@sizeOf(@This()) == 6);
}
};
pub const EvolutionTable = extern struct {
items: [7]Evolution,
terminator: lu16,
comptime {
std.debug.assert(@sizeOf(@This()) == 44);
}
};
pub const MoveTutor = extern struct {
move: lu16,
cost: u8,
tutor: u8,
comptime {
std.debug.assert(@sizeOf(@This()) == 8);
}
};
pub const PartyMemberBase = extern struct {
iv: u8 = 0,
gender_ability: GenderAbilityPair = GenderAbilityPair{},
level: lu16 = lu16.init(0),
species: lu16 = lu16.init(0),
comptime {
std.debug.assert(@sizeOf(@This()) == 6);
}
pub const GenderAbilityPair = packed struct {
gender: u4 = 0,
ability: u4 = 0,
};
pub fn toParent(base: *PartyMemberBase, comptime Parent: type) *Parent {
return @fieldParentPtr(Parent, "base", base);
}
};
pub const PartyMemberNone = extern struct {
base: PartyMemberBase = PartyMemberBase{},
comptime {
std.debug.assert(@sizeOf(@This()) == 6);
}
};
pub const PartyMemberItem = extern struct {
base: PartyMemberBase = PartyMemberBase{},
item: lu16 = lu16.init(0),
comptime {
std.debug.assert(@sizeOf(@This()) == 8);
}
};
pub const PartyMemberMoves = extern struct {
base: PartyMemberBase = PartyMemberBase{},
moves: [4]lu16 = [_]lu16{lu16.init(0)} ** 4,
comptime {
std.debug.assert(@sizeOf(@This()) == 14);
}
};
pub const PartyMemberBoth = extern struct {
base: PartyMemberBase = PartyMemberBase{},
item: lu16 = lu16.init(0),
moves: [4]lu16 = [_]lu16{lu16.init(0)} ** 4,
comptime {
std.debug.assert(@sizeOf(@This()) == 16);
}
};
/// In HG/SS/Plat, this struct is always padded with a u16 at the end, no matter the party_type
pub fn HgSsPlatMember(comptime T: type) type {
return extern struct {
member: T,
pad: lu16,
comptime {
std.debug.assert(@sizeOf(@This()) == @sizeOf(T) + 2);
}
};
}
pub const Trainer = extern struct {
party_type: common.PartyType,
class: u8,
battle_type: u8, // TODO: This should probably be an enum
party_size: u8,
items: [4]lu16,
ai: lu32,
battle_type2: u8,
pad: [3]u8,
comptime {
std.debug.assert(@sizeOf(@This()) == 20);
}
pub fn partyMember(trainer: Trainer, version: common.Version, party: []u8, i: usize) ?*PartyMemberBase {
return switch (version) {
.diamond,
.pearl,
=> switch (trainer.party_type) {
.none => partyMemberHelper(party, @sizeOf(PartyMemberNone), i),
.item => partyMemberHelper(party, @sizeOf(PartyMemberItem), i),
.moves => partyMemberHelper(party, @sizeOf(PartyMemberMoves), i),
.both => partyMemberHelper(party, @sizeOf(PartyMemberBoth), i),
},
.platinum,
.heart_gold,
.soul_silver,
=> switch (trainer.party_type) {
.none => partyMemberHelper(party, @sizeOf(HgSsPlatMember(PartyMemberNone)), i),
.item => partyMemberHelper(party, @sizeOf(HgSsPlatMember(PartyMemberItem)), i),
.moves => partyMemberHelper(party, @sizeOf(HgSsPlatMember(PartyMemberMoves)), i),
.both => partyMemberHelper(party, @sizeOf(HgSsPlatMember(PartyMemberBoth)), i),
},
else => unreachable,
};
}
fn partyMemberHelper(party: []u8, member_size: usize, i: usize) ?*PartyMemberBase {
const start = i * member_size;
const end = start + member_size;
if (party.len < end)
return null;
return &mem.bytesAsSlice(PartyMemberBase, party[start..][0..@sizeOf(PartyMemberBase)])[0];
}
};
// TODO: This is the first data structure I had to decode from scratch as I couldn't find a proper
// resource for it... Fill it out!
pub const Move = extern struct {
u8_0: u8,
u8_1: u8,
category: common.MoveCategory,
power: u8,
type: u8,
accuracy: u8,
pp: u8,
u8_7: u8,
u8_8: u8,
u8_9: u8,
u8_10: u8,
u8_11: u8,
u8_12: u8,
u8_13: u8,
u8_14: u8,
u8_15: u8,
comptime {
std.debug.assert(@sizeOf(@This()) == 16);
}
};
pub const LevelUpMove = packed struct {
id: u9,
level: u7,
pub const term = LevelUpMove{
.id = math.maxInt(u9),
.level = math.maxInt(u7),
};
comptime {
std.debug.assert(@sizeOf(@This()) == 2);
}
};
pub const DpptWildPokemons = extern struct {
grass_rate: lu32,
grass: [12]Grass,
swarm_replace: [2]Replacement, // Replaces grass[0, 1]
day_replace: [2]Replacement, // Replaces grass[2, 3]
night_replace: [2]Replacement, // Replaces grass[2, 3]
radar_replace: [4]Replacement, // Replaces grass[4, 5, 10, 11]
unknown_replace: [6]Replacement, // ???
gba_replace: [10]Replacement, // Each even replaces grass[8], each uneven replaces grass[9]
surf: Sea,
sea_unknown: Sea,
old_rod: Sea,
good_rod: Sea,
super_rod: Sea,
comptime {
std.debug.assert(@sizeOf(@This()) == 424);
}
pub const Grass = extern struct {
level: u8,
pad1: [3]u8,
species: lu16,
pad2: [2]u8,
comptime {
std.debug.assert(@sizeOf(@This()) == 8);
}
};
pub const Sea = extern struct {
rate: lu32,
mons: [5]SeaMon,
};
pub const SeaMon = extern struct {
max_level: u8,
min_level: u8,
pad1: [2]u8,
species: lu16,
pad2: [2]u8,
comptime {
std.debug.assert(@sizeOf(@This()) == 8);
}
};
pub const Replacement = extern struct {
species: lu16,
pad: [2]u8,
comptime {
std.debug.assert(@sizeOf(@This()) == 4);
}
};
};
pub const HgssWildPokemons = extern struct {
grass_rate: u8,
sea_rates: [5]u8,
unknown: [2]u8,
grass_levels: [12]u8,
grass_morning: [12]lu16,
grass_day: [12]lu16,
grass_night: [12]lu16,
radio: [4]lu16,
surf: [5]Sea,
sea_unknown: [2]Sea,
old_rod: [5]Sea,
good_rod: [5]Sea,
super_rod: [5]Sea,
swarm: [4]lu16,
comptime {
std.debug.assert(@sizeOf(@This()) == 196);
}
pub const Sea = extern struct {
min_level: u8,
max_level: u8,
species: lu16,
comptime {
std.debug.assert(@sizeOf(@This()) == 4);
}
};
};
pub const Pocket = enum(u4) {
items = 0x00,
tms_hms = 0x01,
berries = 0x02,
key_items = 0x03,
poke_balls = 0x09,
_,
};
// https://github.com/projectpokemon/PPRE/blob/master/pokemon/itemtool/itemdata.py
pub const Item = extern struct {
price: lu16,
battle_effect: u8,
gain: u8,
berry: u8,
fling_effect: u8,
fling_power: u8,
natural_gift_power: u8,
flag: u8,
pocket: packed struct {
pocket: Pocket,
pad: u4,
},
type: u8,
category: u8,
category2: lu16,
index: u8,
statboosts: Boost,
ev_yield: common.EvYield,
hp_restore: u8,
pp_restore: u8,
happy1: u8,
happy2: u8,
happy3: u8,
padding1: u8,
padding2: u8,
padding3: u8,
padding4: u8,
padding5: u8,
padding6: u8,
padding7: u8,
padding8: u8,
pub const Boost = packed struct {
hp: u2,
level: u1,
evolution: u1,
attack: u4,
defense: u4,
sp_attack: u4,
sp_defense: u4,
speed: u4,
accuracy: u4,
crit: u2,
pp: u2,
target: u8,
target2: u8,
};
comptime {
std.debug.assert(@sizeOf(@This()) == 36);
}
};
pub const MapHeader = extern struct {
unknown00: u8,
unknown01: u8,
unknown02: u8,
unknown03: u8,
unknown04: u8,
unknown05: u8,
unknown06: u8,
unknown07: u8,
unknown08: u8,
unknown09: u8,
unknown0a: u8,
unknown0b: u8,
unknown0c: u8,
unknown0d: u8,
unknown0e: u8,
unknown0f: u8,
unknown10: u8,
unknown11: u8,
unknown12: u8,
unknown13: u8,
unknown14: u8,
unknown15: u8,
unknown16: u8,
unknown17: u8,
comptime {
std.debug.assert(@sizeOf(@This()) == 24);
}
};
const StaticPokemon = struct {
species: *lu16,
level: *lu16,
};
const PokeballItem = struct {
item: *lu16,
amount: *lu16,
};
pub const EncryptedStringTable = struct {
data: []u8,
pub fn count(table: EncryptedStringTable) u16 {
return table.header().count.value();
}
pub fn getEncryptedString(table: EncryptedStringTable, i: u32) []lu16 {
const key = @truncate(u16, @as(u32, table.header().key.value()) * 0x2FD);
const encrypted_slice = table.slices()[i];
const slice = decryptSlice(key, i, encrypted_slice);
const res = table.data[slice.start.value()..][0 .. slice.len.value() * @sizeOf(lu16)];
return mem.bytesAsSlice(lu16, res);
}
const Header = packed struct {
count: lu16,
key: lu16,
};
fn header(table: EncryptedStringTable) *Header {
return @ptrCast(*Header, table.data[0..@sizeOf(Header)]);
}
fn slices(table: EncryptedStringTable) []nds.Slice {
const data = table.data[@sizeOf(Header)..][0 .. table.count() * @sizeOf(nds.Slice)];
return mem.bytesAsSlice(nds.Slice, data);
}
fn decryptSlice(key: u16, i: u32, slice: nds.Slice) nds.Slice {
const key2 = (@as(u32, key) * (i + 1)) & 0xFFFF;
const key3 = key2 | (key2 << 16);
return nds.Slice.init(slice.start.value() ^ key3, slice.len.value() ^ key3);
}
fn size(strings: u32, chars: u32) u32 {
return @sizeOf(Header) + // Header
@sizeOf(nds.Slice) * strings + // String offsets
strings * @sizeOf(lu16) + // String terminators
chars * @sizeOf(lu16); // String chars
}
};
fn decryptAndDecode(data: []const lu16, key: u16, out: anytype) !void {
const first = decryptChar(key, @intCast(u32, 0), data[0].value());
const compressed = first == 0xF100;
const start = @boolToInt(compressed);
var bits: u5 = 0;
var container: u32 = 0;
for (data[start..]) |c, i| {
const decoded = decryptChar(key, @intCast(u32, i + start), c.value());
if (compressed) {
container |= @as(u32, decoded) << bits;
bits += 16;
while (bits >= 9) : (bits -= 9) {
const char = @intCast(u16, container & 0x1FF);
if (char == 0x1Ff)
return;
try encodings.decode2(&@bitCast([2]u8, lu16.init(char)), out);
container >>= 9;
}
} else {
if (decoded == 0xffff)
return;
try encodings.decode2(&@bitCast([2]u8, lu16.init(decoded)), out);
}
}
}
fn encrypt(data: []lu16, key: u16) void {
for (data) |*c, i|
c.* = lu16.init(decryptChar(key, @intCast(u32, i), c.value()));
}
fn decryptChar(key: u16, i: u32, char: u16) u16 {
return char ^ @truncate(u16, key + i * 0x493D);
}
fn getKey(i: u32) u16 {
return @truncate(u16, 0x91BD3 * (i + 1));
}
pub const StringTable = struct {
file_this_was_extracted_from: u16,
number_of_strings: u16,
buf: []u8 = &[_]u8{},
pub fn create(
allocator: mem.Allocator,
file_this_was_extracted_from: u16,
number_of_strings: u16,
max_string_len: usize,
) !StringTable {
const buf = try allocator.alloc(u8, number_of_strings * max_string_len);
errdefer allocator.free(buf);
return StringTable{
.file_this_was_extracted_from = file_this_was_extracted_from,
.number_of_strings = number_of_strings,
.buf = buf,
};
}
pub fn destroy(table: StringTable, allocator: mem.Allocator) void {
allocator.free(table.buf);
}
pub fn maxStringLen(table: StringTable) usize {
return table.buf.len / table.number_of_strings;
}
pub fn get(table: StringTable, i: usize) []u8 {
const len = table.maxStringLen();
return table.buf[len * i ..][0..len];
}
pub fn getSpan(table: StringTable, i: usize) []u8 {
const res = table.get(i);
const end = mem.indexOfScalar(u8, res, 0) orelse res.len;
return res[0..end];
}
pub fn encryptedSize(table: StringTable) u32 {
return EncryptedStringTable.size(
@intCast(u32, table.number_of_strings),
@intCast(u32, table.maxStringLen() * table.number_of_strings),
);
}
};
pub const Game = struct {
info: offsets.Info,
allocator: mem.Allocator,
rom: *nds.Rom,
owned: Owned,
ptrs: Pointers,
// These fields are owned by the game and will be applied to
// the rom oppon calling `apply`.
pub const Owned = struct {
old_arm_len: usize,
arm9: []u8,
trainer_parties: [][6]PartyMemberBoth,
text: Text,
pub fn deinit(owned: Owned, allocator: mem.Allocator) void {
allocator.free(owned.arm9);
allocator.free(owned.trainer_parties);
owned.text.deinit(allocator);
}
};
pub const Text = struct {
type_names: StringTable,
pokemon_names: StringTable,
//trainer_names:StringTable,
move_names: StringTable,
ability_names: StringTable,
item_names: StringTable,
item_descriptions: StringTable,
move_descriptions: StringTable,
pub const Array = [std.meta.fields(Text).len]StringTable;
pub fn deinit(text: Text, allocator: mem.Allocator) void {
for (text.asArray()) |table|
table.destroy(allocator);
}
pub fn asArray(text: Text) Array {
var res: Array = undefined;
inline for (std.meta.fields(Text)) |field, i|
res[i] = @field(text, field.name);
return res;
}
};
// The fields below are pointers into the nds rom and will
// be invalidated oppon calling `apply`.
pub const Pointers = struct {
starters: [3]*lu16,
pokemons: []BasePokemon,
moves: []Move,
trainers: []Trainer,
wild_pokemons: union {
dppt: []DpptWildPokemons,
hgss: []HgssWildPokemons,
},
items: []Item,
tms: []lu16,
hms: []lu16,
evolutions: []EvolutionTable,
level_up_moves: nds.fs.Fs,
pokedex: nds.fs.Fs,
pokedex_heights: []lu32,
pokedex_weights: []lu32,
species_to_national_dex: []lu16,
text: nds.fs.Fs,
scripts: nds.fs.Fs,
static_pokemons: []StaticPokemon,
given_pokemons: []StaticPokemon,
pokeball_items: []PokeballItem,
pub fn deinit(ptrs: Pointers, allocator: mem.Allocator) void {
allocator.free(ptrs.static_pokemons);
allocator.free(ptrs.given_pokemons);
allocator.free(ptrs.pokeball_items);
}
};
pub fn identify(reader: anytype) !offsets.Info {
const header = try reader.readStruct(nds.Header);
for (offsets.infos) |info| {
//if (!mem.eql(u8, info.game_title, game_title))
// continue;
if (!mem.eql(u8, &info.gamecode, &header.gamecode))
continue;
return info;
}
return error.UnknownGame;
}
pub fn fromRom(allocator: mem.Allocator, nds_rom: *nds.Rom) !Game {
const info = try identify(io.fixedBufferStream(nds_rom.data.items).reader());
const arm9 = if (info.arm9_is_encoded)
try nds.blz.decode(allocator, nds_rom.arm9())
else
try allocator.dupe(u8, nds_rom.arm9());
errdefer allocator.free(arm9);
const file_system = nds_rom.fileSystem();
const trainers = try (try file_system.openNarc(nds.fs.root, info.trainers)).toSlice(0, Trainer);
const trainer_parties_narc = try file_system.openNarc(nds.fs.root, info.parties);
const trainer_parties = try allocator.alloc([6]PartyMemberBoth, trainer_parties_narc.fat.len);
mem.set([6]PartyMemberBoth, trainer_parties, [_]PartyMemberBoth{.{}} ** 6);
for (trainer_parties) |*party, i| {
const party_data = trainer_parties_narc.fileData(.{ .i = @intCast(u32, i) });
const party_size = if (i < trainers.len) trainers[i].party_size else 0;
var j: usize = 0;
while (j < party_size) : (j += 1) {
const base = trainers[i].partyMember(info.version, party_data, j) orelse break;
party[j].base = base.*;
switch (trainers[i].party_type) {
.none => {},
.item => party[j].item = base.toParent(PartyMemberItem).item,
.moves => party[j].moves = base.toParent(PartyMemberMoves).moves,
.both => {
const member = base.toParent(PartyMemberBoth);
party[j].item = member.item;
party[j].moves = member.moves;
},
}
}
}
const text = try file_system.openNarc(nds.fs.root, info.text);
const type_names = try decryptStringTable(allocator, 16, text, info.type_names);
errdefer type_names.destroy(allocator);
const pokemon_names = try decryptStringTable(allocator, 16, text, info.pokemon_names);
errdefer pokemon_names.destroy(allocator);
const item_names = try decryptStringTable(allocator, 16, text, info.item_names);
errdefer item_names.destroy(allocator);
const ability_names = try decryptStringTable(allocator, 16, text, info.ability_names);
errdefer ability_names.destroy(allocator);
const move_names = try decryptStringTable(allocator, 16, text, info.move_names);
errdefer move_names.destroy(allocator);
//const trainer_names = try decryptStringTable( allocator, 32,text, info.trainer_names);
//errdefer trainer_names.destroy(allocator);
const item_descriptions = try decryptStringTable(allocator, 128, text, info.item_descriptions);
errdefer item_descriptions.destroy(allocator);
const move_descriptions = try decryptStringTable(allocator, 256, text, info.move_descriptions);
errdefer move_descriptions.destroy(allocator);
return fromRomEx(allocator, nds_rom, info, .{
.old_arm_len = nds_rom.arm9().len,
.arm9 = arm9,
.trainer_parties = trainer_parties,
.text = .{
.type_names = type_names,
.item_descriptions = item_descriptions,
.item_names = item_names,
.ability_names = ability_names,
.move_descriptions = move_descriptions,
.move_names = move_names,
//.trainer_names = trainer_names,
.pokemon_names = pokemon_names,
},
});
}
pub fn fromRomEx(
allocator: mem.Allocator,
nds_rom: *nds.Rom,
info: offsets.Info,
owned: Owned,
) !Game {
const file_system = nds_rom.fileSystem();
const arm9_overlay_table = nds_rom.arm9OverlayTable();
const hm_tm_prefix_index = mem.indexOf(u8, owned.arm9, info.hm_tm_prefix) orelse return error.CouldNotFindTmsOrHms;
const hm_tm_index = hm_tm_prefix_index + info.hm_tm_prefix.len;
const hm_tms_len = (offsets.tm_count + offsets.hm_count) * @sizeOf(u16);
const hm_tms = mem.bytesAsSlice(lu16, owned.arm9[hm_tm_index..][0..hm_tms_len]);
const text = try file_system.openNarc(nds.fs.root, info.text);
const scripts = try file_system.openNarc(nds.fs.root, info.scripts);
const pokedex = try file_system.openNarc(nds.fs.root, info.pokedex);
const commands = try findScriptCommands(info.version, scripts, allocator);
errdefer {
allocator.free(commands.static_pokemons);
allocator.free(commands.given_pokemons);
allocator.free(commands.pokeball_items);
}
return Game{
.info = info,
.allocator = allocator,
.rom = nds_rom,
.owned = owned,
.ptrs = .{
.starters = switch (info.starters) {
.arm9 => |offset| blk: {
if (owned.arm9.len < offset + offsets.starters_len)
return error.CouldNotFindStarters;
const starters_section = mem.bytesAsSlice(lu16, owned.arm9[offset..][0..offsets.starters_len]);
break :blk [_]*lu16{
&starters_section[0],
&starters_section[2],
&starters_section[4],
};
},
.overlay9 => |overlay| blk: {
const overlay_entry = arm9_overlay_table[overlay.file];
const fat_entry = file_system.fat[overlay_entry.file_id.value()];
const file_data = file_system.data[fat_entry.start.value()..fat_entry.end.value()];
const starters_section = mem.bytesAsSlice(lu16, file_data[overlay.offset..][0..offsets.starters_len]);
break :blk [_]*lu16{
&starters_section[0],
&starters_section[2],
&starters_section[4],
};
},
},
.pokemons = try (try file_system.openNarc(nds.fs.root, info.pokemons)).toSlice(0, BasePokemon),
.moves = try (try file_system.openNarc(nds.fs.root, info.moves)).toSlice(0, Move),
.trainers = try (try file_system.openNarc(nds.fs.root, info.trainers)).toSlice(0, Trainer),
.items = try (try file_system.openNarc(nds.fs.root, info.itemdata)).toSlice(0, Item),
.evolutions = try (try file_system.openNarc(nds.fs.root, info.evolutions)).toSlice(0, EvolutionTable),
.wild_pokemons = blk: {
const narc = try file_system.openNarc(nds.fs.root, info.wild_pokemons);
switch (info.version) {
.diamond,
.pearl,
.platinum,
=> break :blk .{ .dppt = try narc.toSlice(0, DpptWildPokemons) },
.heart_gold,
.soul_silver,
=> break :blk .{ .hgss = try narc.toSlice(0, HgssWildPokemons) },
else => unreachable,
}
},
.tms = hm_tms[0..92],
.hms = hm_tms[92..],
.level_up_moves = try file_system.openNarc(nds.fs.root, info.level_up_moves),
.pokedex = pokedex,
.pokedex_heights = mem.bytesAsSlice(lu32, pokedex.fileData(.{ .i = info.pokedex_heights })),
.pokedex_weights = mem.bytesAsSlice(lu32, pokedex.fileData(.{ .i = info.pokedex_weights })),
.species_to_national_dex = mem.bytesAsSlice(lu16, pokedex.fileData(.{ .i = info.species_to_national_dex })),
.text = text,
.scripts = scripts,
.static_pokemons = commands.static_pokemons,
.given_pokemons = commands.given_pokemons,
.pokeball_items = commands.pokeball_items,
},
};
}
pub fn apply(game: *Game) !void {
if (game.info.arm9_is_encoded) {
const arm9 = try nds.blz.encode(game.allocator, game.owned.arm9, 0x4000);
defer game.allocator.free(arm9);
// In the secure area, there is an offset that points to the end of the compressed arm9.
// We have to find that offset and replace it with the new size.
const secure_area = arm9[0..0x4000];
var len_bytes: [3]u8 = undefined;
mem.writeIntLittle(u24, &len_bytes, @intCast(u24, game.owned.old_arm_len));
if (mem.indexOf(u8, secure_area, &len_bytes)) |off| {
mem.writeIntLittle(
u24,
secure_area[off..][0..3],
@intCast(u24, arm9.len),
);
}
mem.copy(
u8,
try game.rom.resizeSection(game.rom.arm9(), arm9.len),
arm9,
);
} else {
mem.copy(
u8,
try game.rom.resizeSection(game.rom.arm9(), game.owned.arm9.len),
game.owned.arm9,
);
}
try game.applyTrainerParties();
try game.applyStrings();
game.ptrs.deinit(game.allocator);
game.* = try fromRomEx(
game.allocator,
game.rom,
game.info,
game.owned,
);
}
fn applyTrainerParties(game: Game) !void {
const file_system = game.rom.fileSystem();
const trainer_parties_narc = try file_system.openFileData(nds.fs.root, game.info.parties);
const trainer_parties = game.owned.trainer_parties;
const content_size = @sizeOf([6]HgSsPlatMember(PartyMemberBoth)) *
trainer_parties.len;
const size = nds.fs.narcSize(trainer_parties.len, content_size);
const buf = try game.rom.resizeSection(trainer_parties_narc, size);
const trainers = try (try file_system.openNarc(nds.fs.root, game.info.trainers)).toSlice(0, Trainer);
var builder = nds.fs.SimpleNarcBuilder.init(
buf,
trainer_parties.len,
);
const fat = builder.fat();
const writer = builder.stream.writer();
const files_offset = builder.stream.pos;
for (trainer_parties) |party, i| {
const party_size = if (i < trainers.len) trainers[i].party_size else 0;
const start = builder.stream.pos - files_offset;
defer fat[i] = nds.Range.init(start, builder.stream.pos - files_offset);
for (party[0..party_size]) |member| {
switch (trainers[i].party_type) {
.none => writer.writeAll(&mem.toBytes(PartyMemberNone{
.base = member.base,
})) catch unreachable,
.item => writer.writeAll(&mem.toBytes(PartyMemberItem{
.base = member.base,
.item = member.item,
})) catch unreachable,
.moves => writer.writeAll(&mem.toBytes(PartyMemberMoves{
.base = member.base,
.moves = member.moves,
})) catch unreachable,
.both => writer.writeAll(&mem.toBytes(member)) catch unreachable,
}
// Write padding
switch (game.info.version) {
.diamond, .pearl => {},
.platinum,
.heart_gold,
.soul_silver,
=> writer.writeAll("\x00\x00") catch unreachable,
else => unreachable,
}
}
const len = (builder.stream.pos - files_offset) - start;
writer.writeByteNTimes(
0,
@sizeOf([6]HgSsPlatMember(PartyMemberBoth)) - len,
) catch unreachable;
}
_ = builder.finish();
}
/// Applies all decrypted strings to the game.
fn applyStrings(game: Game) !void {
// First, we construct an array of all tables we have decrypted. We do
// this to avoid code duplication in many cases. This table type erases
// the tables.
const file_system = game.rom.fileSystem();
const old_text_bytes = try file_system.openFileData(nds.fs.root, game.info.text);
const old_text = try nds.fs.Fs.fromNarc(old_text_bytes);
// We then calculate the size of the content for our new narc
var extra_bytes: usize = 0;
for (game.owned.text.asArray()) |table| {
extra_bytes += math.sub(
u32,
table.encryptedSize(),
old_text.fat[table.file_this_was_extracted_from].len(),
) catch 0;
}
const buf = try game.rom.resizeSection(old_text_bytes, old_text_bytes.len + extra_bytes);
const text = try nds.fs.Fs.fromNarc(buf);
// First, resize all tables that need a resize
for (game.owned.text.asArray()) |table| {
const new_file_size = table.encryptedSize();
const file = &text.fat[table.file_this_was_extracted_from];
const file_needs_a_resize = file.len() < new_file_size;
if (file_needs_a_resize) {
const extra = new_file_size - file.len();
mem.copyBackwards(
u8,
text.data[file.end.value() + extra ..],
text.data[file.end.value() .. text.data.len - extra],
);
const old_file_end = file.end.value();
file.* = nds.Range.init(file.start.value(), file.end.value() + extra);
for (text.fat) |*f| {
const start = f.start.value();
const end = f.end.value();
const file_is_before_the_file_we_moved = start < old_file_end;
if (file_is_before_the_file_we_moved)
continue;
f.* = nds.Range.init(start + extra, end + extra);
}
}
const Header = EncryptedStringTable.Header;
const bytes = text.data[file.start.value()..file.end.value()];
debug.assert(bytes.len == new_file_size);
// Non of the writes here can fail as long as we calculated the size
// of the file correctly above
const writer = io.fixedBufferStream(bytes).writer();
const chars_per_entry = table.maxStringLen() + 1; // Always make room for a terminator
const bytes_per_entry = chars_per_entry * 2;
try writer.writeAll(&mem.toBytes(Header{
.count = lu16.init(table.number_of_strings),
.key = lu16.init(0),
}));
const start_of_entry_table = writer.context.pos;
for (@as([*]void, undefined)[0..table.number_of_strings]) |_| {
try writer.writeAll(&mem.toBytes(nds.Slice{
.start = lu32.init(0),
.len = lu32.init(0),
}));
}
const entries = mem.bytesAsSlice(nds.Slice, bytes[start_of_entry_table..writer.context.pos]);
for (entries) |*entry, j| {
const start_of_str = writer.context.pos;
const str = table.getSpan(j);
encodings.encode(str, writer) catch unreachable;
try writer.writeAll("\xff\xff");
const end_of_str = writer.context.pos;
const encoded_str = mem.bytesAsSlice(lu16, bytes[start_of_str..end_of_str]);
encrypt(encoded_str, getKey(@intCast(u32, j)));
const length_of_str = @intCast(u32, (end_of_str - start_of_str) / 2);
entry.start = lu32.init(@intCast(u32, start_of_str));
entry.len = lu32.init(length_of_str);
// Pad the string, so that each entry is always entry_size
// apart. This ensure that patches generated from tm35-apply
// are small.
writer.writeByteNTimes(0, (chars_per_entry - length_of_str) * 2) catch unreachable;
debug.assert(writer.context.pos - start_of_str == bytes_per_entry);
}
// Assert that we got the file size right.
debug.assert(writer.context.pos == bytes.len);
}
}
pub fn deinit(game: Game) void {
game.owned.deinit(game.allocator);
game.ptrs.deinit(game.allocator);
}
const ScriptCommands = struct {
static_pokemons: []StaticPokemon,
given_pokemons: []StaticPokemon,
pokeball_items: []PokeballItem,
};
fn findScriptCommands(version: common.Version, scripts: nds.fs.Fs, allocator: mem.Allocator) !ScriptCommands {
if (version == .heart_gold or version == .soul_silver) {
// We don't support decoding scripts for hg/ss yet.
return ScriptCommands{
.static_pokemons = &[_]StaticPokemon{},
.given_pokemons = &[_]StaticPokemon{},
.pokeball_items = &[_]PokeballItem{},
};
}
var static_pokemons = std.ArrayList(StaticPokemon).init(allocator);
errdefer static_pokemons.deinit();
var given_pokemons = std.ArrayList(StaticPokemon).init(allocator);
errdefer given_pokemons.deinit();
var pokeball_items = std.ArrayList(PokeballItem).init(allocator);
errdefer pokeball_items.deinit();
var script_offsets = std.ArrayList(isize).init(allocator);
defer script_offsets.deinit();
for (scripts.fat) |fat| {
const script_data = scripts.data[fat.start.value()..fat.end.value()];
defer script_offsets.shrinkRetainingCapacity(0);
for (script.getScriptOffsets(script_data)) |relative_offset, i| {
const offset = relative_offset.value() + @intCast(isize, i + 1) * @sizeOf(lu32);
if (@intCast(isize, script_data.len) < offset)
continue;
if (offset < 0)
continue;
try script_offsets.append(offset);
}
// The variable 0x8008 is the variables that stores items given
// from Pokéballs.
var var_8008: ?*lu16 = null;
var offset_i: usize = 0;
while (offset_i < script_offsets.items.len) : (offset_i += 1) {
const offset = script_offsets.items[offset_i];
if (@intCast(isize, script_data.len) < offset)
return error.Error;
if (offset < 0)
return error.Error;
var decoder = script.CommandDecoder{
.bytes = script_data,
.i = @intCast(usize, offset),
};
while (decoder.next() catch continue) |command| {
// If we hit var 0x8008, the var_8008_tmp will be set and
// Var_8008 will become var_8008_tmp. Then the next iteration
// of this loop will set var_8008 to null again. This allows us
// to store this state for only the next iteration of the loop.
var var_8008_tmp: ?*lu16 = null;
defer var_8008 = var_8008_tmp;
switch (command.tag) {
.wild_battle => try static_pokemons.append(.{
.species = &command.data().wild_battle.species,
.level = &command.data().wild_battle.level,
}),
.wild_battle2 => try static_pokemons.append(.{
.species = &command.data().wild_battle2.species,
.level = &command.data().wild_battle2.level,
}),
.wild_battle3 => try static_pokemons.append(.{
.species = &command.data().wild_battle3.species,
.level = &command.data().wild_battle3.level,
}),
.give_pokemon => try given_pokemons.append(.{
.species = &command.data().give_pokemon.species,
.level = &command.data().give_pokemon.level,
}),
// In scripts, field items are two SetVar commands
// followed by a jump to the code that gives this item:
// SetVar 0x8008 // Item given
// SetVar 0x8009 // Amount of items
// Jump ???
.set_var => switch (command.data().set_var.destination.value()) {
0x8008 => var_8008_tmp = &command.data().set_var.value,
0x8009 => if (var_8008) |item| {
const amount = &command.data().set_var.value;
try pokeball_items.append(PokeballItem{
.item = item,
.amount = amount,
});
},
else => {},
},
.jump, .compare_last_result_jump, .call, .compare_last_result_call => {
const off = switch (command.tag) {
.compare_last_result_call => command.data().compare_last_result_call.adr.value(),
.call => command.data().call.adr.value(),
.jump => command.data().jump.adr.value(),
.compare_last_result_jump => command.data().compare_last_result_jump.adr.value(),
else => unreachable,
};
const location = off + @intCast(isize, decoder.i);
if (mem.indexOfScalar(isize, script_offsets.items, location) == null)
try script_offsets.append(location);
},
else => {},
}
}
}
}
return ScriptCommands{
.static_pokemons = static_pokemons.toOwnedSlice(),
.given_pokemons = given_pokemons.toOwnedSlice(),
.pokeball_items = pokeball_items.toOwnedSlice(),
};
}
fn decryptStringTable(
allocator: mem.Allocator,
max_string_len: usize,
text: nds.fs.Fs,
file: u16,
) !StringTable {
const table = EncryptedStringTable{ .data = text.fileData(.{ .i = file }) };
const res = try StringTable.create(
allocator,
file,
table.count(),
max_string_len,
);
errdefer res.destroy(allocator);
mem.set(u8, res.buf, 0);
var i: usize = 0;
while (i < res.number_of_strings) : (i += 1) {
const id = @intCast(u32, i);
const buf = res.get(i);
const writer = io.fixedBufferStream(buf).writer();
const encrypted_string = table.getEncryptedString(id);
try decryptAndDecode(encrypted_string, getKey(id), writer);
}
return res;
}
}; | src/core/gen4.zig |
const common = @import("common.zig");
const mecha = @import("mecha");
const std = @import("std");
const ston = @import("ston");
const util = @import("util");
const fmt = std.fmt;
const math = std.math;
const mem = std.mem;
const meta = std.meta;
const testing = std.testing;
const escape = util.escape;
// The tm35 format in 8 lines of cfg:
// Line <- Suffix* '=' .*
//
// Suffix
// <- '.' IDENTIFIER
// / '[' INTEGER ']'
//
// INTEGER <- [0-9]+
// IDENTIFIER <- [A-Za-z0-9_]+
//
/// A function for efficiently reading the tm35 format from `reader` and write unwanted lines
/// back into `writer`. `consume` will be called once a line has been parsed successfully, which
/// allows the caller to handle the parsed result however they like. If `consume` returns
/// `error.DidNotConsumeData`, then that will indicate to `io`, that the callback could not handle
/// the result and that `io` should handle it instead. Any other error from `consume` will
/// be returned from `io` as well.
pub fn io(
allocator: mem.Allocator,
reader: anytype,
writer: anytype,
ctx: anytype,
consume: anytype,
) !void {
// WARNING: All the optimizations below have been done with the aid of profilers. Do not
// simplify the code unless you have checked that the simplified code is just as fast.
// Here is a simple oneliner you can use on linux to check:
// ```
// zig build build-tm35-noop -Drelease && \\
// perf stat -r 250 dash -c 'zig-out/bin/tm35-noop < src/common/test_file.tm35 > /dev/null'
// ```
// Two arraylists used for buffering input and output. These are used over buffered streams
// for two reasons:
// * For input, this allows us to ensure that there is always at least one entire line in the
// input. This allows ston.Deserializer to work straight on the input data without having
// to read the lines into a buffer first.
// * For output, this allows us to collect all non consumed lines into one buffer and output
// it at the same time we are reading more into into `in`. Because we know that non cosumed
// lines is always a subset of the input we can ensure that `out` has the same capacity as
// `in` and call `appendSliceAssumeCapacity` to avoid allocating in the hot loop.
var in = std.ArrayList(u8).init(allocator);
defer in.deinit();
var out = std.ArrayList(u8).init(allocator);
defer out.deinit();
try in.ensureUnusedCapacity(util.io.bufsize);
try out.ensureUnusedCapacity(util.io.bufsize);
in.items.len = try reader.read(in.unusedCapacitySlice());
var first_none_consumed_line: ?usize = null;
var start_of_line: usize = 0;
var parser = ston.Parser{ .str = in.items };
var des = ston.Deserializer(Game){ .parser = &parser };
while (parser.str.len != 0) : (start_of_line = parser.i) {
while (des.next()) |res| : (start_of_line = parser.i) {
if (consume(ctx, res)) |_| {
if (first_none_consumed_line) |start| {
// Ok, `consume` just consumed a line after we have had at least one line
// that was not consumed. we can now slice from
// `first_none_consumed_line..start_of_line` to get all the lines we need to
// handle and append them all in one go to `out`. This is faster than
// appending none consumed lines one at the time because this feeds more data
// to mem.copy which then causes us to hit a codepath that is really fast
// on a lot of data.
const lines = parser.str[start..start_of_line];
out.appendSliceAssumeCapacity(lines);
first_none_consumed_line = null;
}
} else |err| switch (err) {
// When `consume` returns `DidNotConsumeData` it communicates to us that they
// could not handle the result in any meaningful way, so we are responsible
// for writing the parsed string back out.
error.DidNotConsumeData => if (first_none_consumed_line == null) {
first_none_consumed_line = start_of_line;
},
else => return err,
}
} else |err|
// If we couldn't parse a portion of the buffer, then we skip to the next line
// and try again. The current line will just be written out again.
if (mem.indexOfScalarPos(u8, parser.str, parser.i, '\n')) |index| {
if (first_none_consumed_line == null)
first_none_consumed_line = start_of_line;
const line = parser.str[start_of_line .. index + 1];
parser.i = index + 1;
std.log.debug("{s}: '{s}'", .{ @errorName(err), line[0 .. line.len - 1] });
continue;
}
// Ok, we are done deserializing this batch of input. We need to output all the
// lines that wasn't consumed and write the this to the writer.
if (first_none_consumed_line) |start| {
const lines = parser.str[start..start_of_line];
out.appendSliceAssumeCapacity(lines);
first_none_consumed_line = null;
}
try writer.writeAll(out.items);
out.shrinkRetainingCapacity(0);
// There is probably some leftover which wasn't part of a full line. Copy that to the
// start and make room for more data. Here we need to ensure that `out` at least as much
// capacity as `in`.
mem.copy(u8, in.items, in.items[start_of_line..]);
in.shrinkRetainingCapacity(in.items.len - start_of_line);
try in.ensureUnusedCapacity(util.io.bufsize);
try out.ensureTotalCapacity(in.capacity);
const num = try reader.read(in.unusedCapacitySlice());
in.items.len += num;
if (num == 0 and in.items.len != 0) {
// If get here, then the input did not have a terminating newline. In that case
// the above parsing logic will never succeed. Let's append a newline here so that
// we can handle that egde case.
in.appendAssumeCapacity('\n');
}
parser = ston.Parser{ .str = in.items };
}
}
/// Takes a struct pointer and a union and sets the structs field with
/// the same name as the unions active tag to that tags value.
/// All union field names must exist in the struct, and these union
/// field types must be able to coirse to the struct fields type.
pub fn setField(struct_ptr: anytype, union_val: anytype) void {
const Union = @TypeOf(union_val);
inline for (@typeInfo(Union).Union.fields) |field| {
if (union_val == @field(meta.Tag(Union), field.name)) {
@field(struct_ptr, field.name) = @field(union_val, field.name);
return;
}
}
unreachable;
}
fn getUnionValue(
val: anytype,
) @TypeOf(&@field(val, @typeInfo(@TypeOf(val)).Union.fields[0].name)) {
const T = @TypeOf(val);
inline for (@typeInfo(T).Union.fields) |field| {
if (val == @field(meta.Tag(T), field.name)) {
return &@field(val, field.name);
}
}
unreachable;
}
pub const Color = common.ColorKind;
pub const EggGroup = common.EggGroup;
pub const GrowthRate = common.GrowthRate;
pub const PartyType = common.PartyType;
pub const Version = common.Version;
pub const Game = union(enum) {
version: Version,
game_title: []const u8,
gamecode: []const u8,
instant_text: bool,
starters: ston.Index(u8, u16),
text_delays: ston.Index(u8, u8),
trainers: ston.Index(u16, Trainer),
moves: ston.Index(u16, Move),
pokemons: ston.Index(u16, Pokemon),
abilities: ston.Index(u16, Ability),
types: ston.Index(u8, Type),
tms: ston.Index(u8, u16),
hms: ston.Index(u8, u16),
items: ston.Index(u16, Item),
pokedex: ston.Index(u16, Pokedex),
maps: ston.Index(u16, Map),
wild_pokemons: ston.Index(u16, WildPokemons),
static_pokemons: ston.Index(u16, StaticPokemon),
given_pokemons: ston.Index(u16, GivenPokemon),
pokeball_items: ston.Index(u16, PokeballItem),
hidden_hollows: ston.Index(u16, HiddenHollow),
text: ston.Index(u16, []const u8),
};
pub const Trainer = union(enum) {
class: u8,
encounter_music: u8,
trainer_picture: u8,
name: []const u8,
items: ston.Index(u8, u16),
party_type: PartyType,
party_size: u8,
party: ston.Index(u8, PartyMember),
};
pub const PartyMember = union(enum) {
ability: u4,
level: u8,
species: u16,
item: u16,
moves: ston.Index(u8, u16),
};
pub const Move = union(enum) {
name: []const u8,
description: []const u8,
effect: u8,
power: u8,
type: u8,
accuracy: u8,
pp: u8,
target: u8,
priority: u8,
category: Category,
pub const Category = common.MoveCategory;
};
pub fn Stats(comptime T: type) type {
return union(enum) {
hp: T,
attack: T,
defense: T,
speed: T,
sp_attack: T,
sp_defense: T,
pub fn value(stats: @This()) T {
return getUnionValue(stats).*;
}
};
}
pub const Pokemon = union(enum) {
name: []const u8,
stats: Stats(u8),
ev_yield: Stats(u2),
base_exp_yield: u16,
base_friendship: u8,
catch_rate: u8,
egg_cycles: u8,
gender_ratio: u8,
pokedex_entry: u16,
growth_rate: GrowthRate,
color: Color,
abilities: ston.Index(u8, u8),
egg_groups: ston.Index(u8, EggGroup),
evos: ston.Index(u8, Evolution),
hms: ston.Index(u8, bool),
items: ston.Index(u8, u16),
moves: ston.Index(u8, LevelUpMove),
tms: ston.Index(u8, bool),
types: ston.Index(u8, u8),
};
pub const Evolution = union(enum) {
method: Method,
param: u16,
target: u16,
pub const Method = enum {
attack_eql_defense,
attack_gth_defense,
attack_lth_defense,
beauty,
friend_ship,
friend_ship_during_day,
friend_ship_during_night,
level_up,
level_up_female,
level_up_holding_item_during_daytime,
level_up_holding_item_during_the_night,
level_up_in_special_magnetic_field,
level_up_knowning_move,
level_up_male,
level_up_may_spawn_pokemon,
level_up_near_ice_rock,
level_up_near_moss_rock,
level_up_spawn_if_cond,
level_up_with_other_pokemon_in_party,
personality_value1,
personality_value2,
trade,
trade_holding_item,
trade_with_pokemon,
unknown_0x02,
unknown_0x03,
unused,
use_item,
use_item_on_female,
use_item_on_male,
};
};
pub const LevelUpMove = union(enum) {
id: u16,
level: u16,
};
pub const Ability = union(enum) {
name: []const u8,
};
pub const Type = union(enum) {
name: []const u8,
};
pub const Pocket = enum {
none,
items,
key_items,
poke_balls,
tms_hms,
berries,
};
pub const Item = union(enum) {
name: []const u8,
description: []const u8,
price: u32,
battle_effect: u8,
pocket: Pocket,
};
pub const Pokedex = union(enum) {
height: u32,
weight: u32,
category: []const u8,
};
pub const Map = union(enum) {
music: u16,
cave: u8,
weather: u8,
type: u8,
escape_rope: u8,
battle_scene: u8,
allow_cycling: bool,
allow_escaping: bool,
allow_running: bool,
show_map_name: bool,
};
pub const WildPokemons = union(enum) {
grass_0: WildArea,
grass_1: WildArea,
grass_2: WildArea,
grass_3: WildArea,
grass_4: WildArea,
grass_5: WildArea,
grass_6: WildArea,
dark_grass_0: WildArea,
dark_grass_1: WildArea,
dark_grass_2: WildArea,
dark_grass_3: WildArea,
rustling_grass_0: WildArea,
rustling_grass_1: WildArea,
rustling_grass_2: WildArea,
rustling_grass_3: WildArea,
surf_0: WildArea,
surf_1: WildArea,
surf_2: WildArea,
surf_3: WildArea,
ripple_surf_0: WildArea,
ripple_surf_1: WildArea,
ripple_surf_2: WildArea,
ripple_surf_3: WildArea,
rock_smash: WildArea,
fishing_0: WildArea,
fishing_1: WildArea,
fishing_2: WildArea,
fishing_3: WildArea,
ripple_fishing_0: WildArea,
ripple_fishing_1: WildArea,
ripple_fishing_2: WildArea,
ripple_fishing_3: WildArea,
pub fn init(tag: meta.Tag(WildPokemons), area: WildArea) WildPokemons {
const Tag = meta.Tag(WildPokemons);
inline for (@typeInfo(Tag).Enum.fields) |field| {
if (@field(Tag, field.name) == tag)
return @unionInit(WildPokemons, field.name, area);
}
unreachable;
}
pub fn value(pokemons: @This()) WildArea {
return getUnionValue(pokemons).*;
}
};
pub const WildArea = union(enum) {
encounter_rate: u32,
pokemons: ston.Index(u8, WildPokemon),
};
pub const WildPokemon = union(enum) {
min_level: u8,
max_level: u8,
species: u16,
};
pub const StaticPokemon = union(enum) {
species: u16,
level: u16,
};
pub const GivenPokemon = union(enum) {
species: u16,
level: u16,
};
pub const PokeballItem = union(enum) {
item: u16,
amount: u16,
};
pub const HiddenHollow = union(enum) {
groups: ston.Index(u8, union(enum) {
pokemons: ston.Index(u8, union(enum) {
species: u16,
}),
}),
items: ston.Index(u8, u16),
}; | src/core/format.zig |
usingnamespace @import("aoc-lib.zig");
const rollWays = [_]usize{1,3,6,7,6,3,1};
const Game = struct {
start : [2]usize,
d : usize,
fn fromInput(inp: []const u8, allocator: *Allocator) !*Game {
var g = try allocator.create(Game);
var n : usize = 0;
var p : usize = 0;
for (inp) |ch| {
switch (ch) {
':' => {
n = 0;
},
'0'...'9' => {
n = n*10+@as(usize, ch-'0');
},
'\n' => {
g.start[p] = n;
n = 0;
p += 1;
},
else => {
},
}
}
g.d = 0;
return g;
}
fn roll(self: *Game) usize {
var r = 1 + (self.d % 100);
self.d += 1;
return r;
}
pub fn part1(self: *Game) usize {
var s = [_]usize{0, 0};
var p = [_]usize{ self.start[0]-1, self.start[1]-1 };
while (true) {
var r = self.roll() + self.roll() + self.roll();
p[0] += r;
p[0] %= 10;
s[0] += p[0] + 1;
if (s[0] >= 1000) {
return s[1] * self.d;
}
r = self.roll() + self.roll() + self.roll();
p[1] += r;
p[1] %= 10;
s[1] += p[1] + 1;
if (s[1] >= 1000) {
return s[0] * self.d;
}
}
return 1;
}
pub fn part2(self: *Game) usize {
var games : [21 * 21 * 11 * 11]usize = undefined;
for (games) |*v| {
v.* = 0;
}
var wins : [21 * 21 * 11 * 11]usize = undefined;
for (wins) |*v| {
v.* = 0;
}
var its : i8 = 40;
while (its >= 0) : (its -= 1) {
var ts = @intCast(usize, its);
var is1 : isize = 20;
while (is1 >= 0) : (is1 -= 1) {
var s1 = @intCast(usize, is1);
if (s1 > ts) {
continue;
}
var s2 = ts - s1;
if (s2 > 20) {
continue;
}
var p1 : usize = 1;
while (p1 <= 10) : (p1 += 1) {
var p2 : usize = 1;
while (p2 <= 10) : (p2 += 1) {
var i = (((s1 * 21) + s2) * 11 + p1) * 11 + p2;
var r : usize = 3;
while (r <= 9) : (r += 1) {
var w = rollWays[r - 3];
var np1 = p1 + r;
if (np1 > 10) {
np1 -= 10;
}
var ns1 = s1 + np1;
if (ns1 >= 21) {
games[i] += w;
wins[i] += w;
} else {
var ii = ((((s2 * 21) + ns1) * 11 + p2) * 11) + np1;
games[i] += w * games[ii];
wins[i] += w * (games[ii] - wins[ii]);
}
}
}
}
}
}
var ri = self.start[0]*11 + self.start[1];
var w1 = wins[ri];
var w2 = games[ri]- wins[ri];
if (w1 > w2) {
return w1;
}
return w2;
}
};
test "examples" {
const talloc = @import("std").testing.allocator;
var t = Game.fromInput(test1file, talloc) catch unreachable;
defer talloc.destroy(t);
var ti = Game.fromInput(inputfile, talloc) catch unreachable;
defer talloc.destroy(ti);
try assertEq(@as(usize, 739785), t.part1());
try assertEq(@as(usize, 428736), ti.part1());
try assertEq(@as(usize, 444356092776315), t.part2());
try assertEq(@as(usize, 57328067654557), ti.part2());
}
fn aoc(inp: []const u8, bench: bool) anyerror!void {
var g = try Game.fromInput(inp, alloc);
defer alloc.destroy(g);
var p1 = g.part1();
var p2 = g.part2();
if (!bench) {
try print("Part1: {}\nPart2: {}\n", .{ p1, p2 });
}
}
pub fn main() anyerror!void {
try benchme(input(), aoc);
} | 2021/21/aoc.zig |
const std = @import("std");
const gc = @import("gc.zig");
const InterpreterError = @import("vm.zig").InterpreterError;
const Heap = gc.Heap;
const HeapId = gc.HeapId;
const vm = @import("vm.zig").vm;
const range = @import("utils.zig").range;
var format_level: u8 = 0;
pub const Object = struct {
id: HeapId,
members: std.StringHashMap(Value),
const Self = @This();
pub fn init(id: HeapId, allocator: std.mem.Allocator) Self {
return Self{ .id = id, .members = std.StringHashMap(Value).init(allocator) };
}
pub fn deinit(self: *Self) void {
self.members.deinit();
}
pub fn format(self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = options;
_ = fmt;
format_level += 1;
var it = self.members.iterator();
var first = true;
try std.fmt.format(writer, "{{", .{});
while (true) {
var entry = it.next();
if (entry == null) break;
if (!first) {
try std.fmt.format(writer, ",", .{});
} else {
first = false;
}
try std.fmt.format(writer, "\n", .{});
try printIndent(writer);
try std.fmt.format(writer, "{s}: {}", .{ entry.?.key_ptr.*, entry.?.value_ptr.* });
}
format_level -= 1;
if (self.members.count() != 0) {
try printIndent(writer);
}
try std.fmt.format(writer, "}}", .{});
}
};
fn printIndent(writer: anytype) !void {
var lvl: u8 = 0;
while (lvl < format_level) : (lvl += 1) {
try std.fmt.format(writer, " ", .{});
}
}
// TODO: Add a string pool
pub const String = struct {
id: HeapId,
string: std.ArrayList(u8),
const Self = @This();
pub fn init(id: HeapId, allocator: std.mem.Allocator) Self {
return Self{ .id = id, .string = std.ArrayList(u8).init(allocator) };
}
pub fn deinit(self: *Self) void {
self.string.deinit();
}
pub fn str(self: Self) []u8 {
return self.string.items;
}
pub fn concat(self: *Self, others: anytype) !void {
var total_size: usize = self.string.items.len;
comptime var i: usize = 0;
inline while (i < others.len) : (i += 1) {
total_size += others[i].len;
}
try self.string.ensureTotalCapacity(total_size);
i = 0;
inline while (i < others.len) : (i += 1) {
try self.string.appendSlice(others[i]);
}
}
pub fn concatNTimes(self: *Self, other: []const u8, n: usize) !void {
try self.string.ensureTotalCapacity(self.string.items.len + other.len);
for (range(n)) |_| {
try self.string.appendSlice(other);
}
}
pub fn format(self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = options;
_ = fmt;
return std.fmt.format(writer, "\"{s}\"", .{self.string.items});
}
};
/// Helper function that checks if a constant string
/// has already been inserted in the heap string pool.
/// If yes, just return the pointer, otherwise create it,
/// copy its content and insert it in the pool before
/// return the pointer.
/// ⚠️ This should never be used for string that will be mutated ⚠️
pub fn makeConstantString(str: []const u8) *String {
const existing_value = vm().heap.string_pool.get(str);
if (existing_value != null) {
return existing_value.?;
}
var string = vm().heap.makeString();
string.concat(.{str}) catch unreachable;
vm().heap.string_pool.put(string.str(), string) catch unreachable;
return string;
}
pub const Value = union(enum) {
number: f64,
boolean: bool,
nil: void,
string: *String,
object: *Object,
pub fn fromNumber(n: f64) Value {
return Value{ .number = n };
}
pub fn fromBoolean(b: bool) Value {
return Value{ .boolean = b };
}
pub fn fromNil() Value {
return Value{ .nil = {} };
}
pub fn fromString(string: *String) Value {
return Value{ .string = string };
}
pub fn asNumber(self: Value) InterpreterError!f64 {
switch (self) {
.number => |v| return v,
else => return InterpreterError.CastError,
}
}
pub fn asBoolean(self: Value) InterpreterError!bool {
switch (self) {
.boolean => |v| return v,
else => return InterpreterError.CastError,
}
}
pub fn asNil(self: Value) InterpreterError!void {
switch (self) {
.nil => {},
else => return InterpreterError.CastError,
}
}
pub fn asString(self: Value) InterpreterError!*String {
switch (self) {
.string => |s| return s,
else => return InterpreterError.CastError,
}
}
pub fn asObject(self: Value) InterpreterError!*Object {
switch (self) {
.object => |o| return o,
else => return InterpreterError.CastError,
}
}
pub fn isNumber(self: Value) bool {
switch (self) {
.number => return true,
else => return false,
}
}
pub fn isBoolean(self: Value) bool {
switch (self) {
.boolean => return true,
else => return false,
}
}
pub fn isNil(self: Value) bool {
switch (self) {
.nil => return true,
else => return false,
}
}
pub fn isString(self: Value) bool {
switch (self) {
.string => return true,
else => return false,
}
}
pub fn isObject(self: Value) bool {
switch (self) {
.object => return true,
else => return false,
}
}
pub fn sharesType(lhs: Value, rhs: Value) bool {
return @enumToInt(lhs) == @enumToInt(rhs);
}
pub fn equals(lhs: Value, rhs: Value) InterpreterError!bool {
if (!sharesType(lhs, rhs)) {
return InterpreterError.CannotCompareValuesError;
}
switch (lhs) {
// TODO: Remove nil
.nil => return true,
.boolean => {
const b1 = @field(lhs, "boolean");
const b2 = @field(rhs, "boolean");
return b1 == b2;
},
.number => {
const n1 = @field(lhs, "number");
const n2 = @field(rhs, "number");
return n1 == n2;
},
.string => {
const s1 = @field(lhs, "string");
const s2 = @field(rhs, "string");
return std.mem.eql(u8, s1.str(), s2.str());
},
.object => {
const id1 = @field(lhs, "object");
const id2 = @field(rhs, "object");
// Should we be smarter than a pointer comparison here ?
return id1 == id2;
},
}
unreachable;
}
pub fn greaterThan(lhs: Value, rhs: Value) InterpreterError!bool {
if (!sharesType(lhs, rhs)) {
return InterpreterError.CannotCompareValuesError;
}
switch (lhs) {
// TODO: Remove nil
.number => {
const n1 = @field(lhs, "number");
const n2 = @field(rhs, "number");
return n1 > n2;
},
.string => {
const s1 = @field(lhs, "string");
const s2 = @field(rhs, "string");
const order = std.mem.order(u8, s1.str(), s2.str());
return order == .gt;
},
else => return InterpreterError.NonsensicalComparisonError,
}
unreachable;
}
pub fn greaterThanOrEqual(lhs: Value, rhs: Value) InterpreterError!bool {
if (!sharesType(lhs, rhs)) {
return InterpreterError.CannotCompareValuesError;
}
switch (lhs) {
// TODO: Remove nil
.number => {
const n1 = @field(lhs, "number");
const n2 = @field(rhs, "number");
return n1 >= n2;
},
.string => {
const s1 = @field(lhs, "string");
const s2 = @field(rhs, "string");
const order = std.mem.order(u8, s1.str(), s2.str());
return order == .gt or order == .eq;
},
else => return InterpreterError.NonsensicalComparisonError,
}
unreachable;
}
pub fn lessThan(lhs: Value, rhs: Value) InterpreterError!bool {
if (!sharesType(lhs, rhs)) {
return InterpreterError.CannotCompareValuesError;
}
switch (lhs) {
.number => {
const n1 = @field(lhs, "number");
const n2 = @field(rhs, "number");
return n1 < n2;
},
.string => {
const s1 = @field(lhs, "string");
const s2 = @field(rhs, "string");
const order = std.mem.order(u8, s1.str(), s2.str());
return order == .lt;
},
else => return InterpreterError.NonsensicalComparisonError,
}
unreachable;
}
pub fn lessThanOrEqual(lhs: Value, rhs: Value) InterpreterError!bool {
if (!sharesType(lhs, rhs)) {
return InterpreterError.CannotCompareValuesError;
}
switch (lhs) {
.number => {
const n1 = @field(lhs, "number");
const n2 = @field(rhs, "number");
return n1 <= n2;
},
.string => {
const s1 = @field(lhs, "string");
const s2 = @field(rhs, "string");
const order = std.mem.order(u8, s1.str(), s2.str());
return order == .lt or order == .eq;
},
else => return InterpreterError.NonsensicalComparisonError,
}
unreachable;
}
pub fn format(value: Value, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = options;
_ = fmt;
switch (value) {
.nil => return std.fmt.format(writer, "<nil>", .{}),
.boolean => |b| return std.fmt.format(writer, "{}", .{b}),
.number => |n| return std.fmt.format(writer, "{d}", .{n}),
.string => |s| return std.fmt.format(writer, "{}", .{s.*}),
.object => |o| return std.fmt.format(writer, "{}", .{o.*}),
}
}
}; | src/value.zig |
const std = @import("std");
const print = std.debug.print;
const ParseIntError = std.fmt.ParseIntError;
const util = @import("util.zig");
const data = @embedFile("../data/day01.txt");
const Str = []const u8;
pub const LineIter = struct {
_iter: std.mem.SplitIterator(u8),
const Self = @This();
pub fn init(input: Str) Self {
return .{ ._iter = std.mem.split(u8, input, "\n") };
}
pub fn next(self: *Self) ParseIntError!?u32 {
if (self._iter.next()) |line| {
const trimmed = std.mem.trim(u8, line, " \t\r");
if (trimmed.len == 0) return try self.next();
return try std.fmt.parseUnsigned(u32, trimmed, 10);
} else {
return null;
}
}
};
fn part1(input: Str) !u32 {
var answer: u32 = 0;
var iter = LineIter.init(input);
var prev_num: ?u32 = try iter.next();
while (try iter.next()) |num| {
if (num > prev_num.?) answer += 1;
prev_num = num;
}
return answer;
}
fn part2(input: Str) !u32 {
var answer: u32 = 0;
var iter = LineIter.init(input);
var num1: ?u32 = try iter.next();
var num2: ?u32 = try iter.next();
var num3: ?u32 = try iter.next();
while (try iter.next()) |next_num| {
if (next_num > num1.?) answer += 1;
num1 = num2;
num2 = num3;
num3 = next_num;
}
return answer;
}
pub fn main() !void {
try util.runPart(part1, data);
print("\n", .{});
try util.runPart(part2, data);
}
test "1a" {
try std.testing.expectEqual(@as(u32, 0), try part1(""));
try std.testing.expectEqual(@as(u32, 0), try part1("100"));
try std.testing.expectEqual(@as(u32, 0), try part1("100\n99"));
try std.testing.expectEqual(@as(u32, 0), try part1("100\n100"));
try std.testing.expectEqual(@as(u32, 1), try part1("100\n101"));
try std.testing.expectEqual(@as(u32, 2), try part1("100\n101\n102\n"));
try std.testing.expectEqual(@as(u32, 1), try part1(" 100 \n 101 "));
try std.testing.expectError(error.InvalidCharacter, part1("text"));
{
const input =
\\199
\\200
\\208
\\210
\\200
\\207
\\240
\\269
\\260
\\263
;
try std.testing.expectEqual(@as(u32, 7), try part1(input));
}
{
const input =
\\123
\\124
\\ 125
\\100
\\
\\100
\\20
\\21
\\
;
try std.testing.expectEqual(@as(u32, 3), try part1(input));
}
}
test "1b" {
try std.testing.expectEqual(@as(u32, 0), try part2(""));
try std.testing.expectEqual(@as(u32, 0), try part2("100"));
try std.testing.expectEqual(@as(u32, 0), try part2("100\n101\n102"));
try std.testing.expectEqual(@as(u32, 1), try part2("100\n101\n102\n103"));
try std.testing.expectError(error.InvalidCharacter, part2("text"));
const input =
\\199
\\200
\\208
\\210
\\200
\\207
\\240
\\269
\\260
\\263
;
try std.testing.expectEqual(@as(u32, 5), try part2(input));
} | src/day01.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;
pub fn run(input: []const u8, allocator: std.mem.Allocator) tools.RunError![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 stdout = std.io.getStdOut().writer();
var cpu = Computer{
.name = "Springdroid",
.memory = try allocator.alloc(Computer.Data, 50000),
};
defer allocator.free(cpu.memory);
const part1: Computer.Data = ans1: {
// J = 'd and(!a or !b or !c)'
const ascii_programm =
\\NOT A J
\\NOT J T
\\AND B T
\\AND C T
\\NOT T J
\\AND D J
\\WALK
\\
;
cpu.boot(boot_image);
trace("starting {}\n", .{cpu.name});
_ = async cpu.run();
var i_input: usize = 0;
while (!cpu.is_halted()) {
if (cpu.io_mode == .input) {
cpu.io_port = ascii_programm[i_input];
i_input += 1;
trace("wrting input to {} = {}\n", .{ cpu.name, cpu.io_port });
}
if (cpu.io_mode == .output) {
trace("{} outputs {}\n", .{ cpu.name, cpu.io_port });
if (cpu.io_port < 127) {
// stdout.print("{c}", .{@intCast(u8, cpu.io_port)}) catch unreachable;
} else {
break :ans1 cpu.io_port;
}
}
trace("resuming {}\n", .{cpu.name});
resume cpu.io_runframe;
}
unreachable;
};
const part2: Computer.Data = ans2: {
// J = J and (H OR E) (suffisant)
//const ascii_programm =
// \\NOT A J
// \\NOT J T
// \\AND B T
// \\AND C T
// \\NOT T J
// \\AND D J
// \\NOT J T
// \\OR H T
// \\OR E T
// \\AND T J
// \\RUN
// \\
//;
// J = J and (H OR (E and (I or F)) plus robuste!
const ascii_programm =
\\NOT A J
\\NOT J T
\\AND B T
\\AND C T
\\NOT T J
\\AND D J
\\NOT F T
\\NOT T T
\\OR I T
\\AND E T
\\OR H T
\\AND T J
\\RUN
\\
;
cpu.boot(boot_image);
trace("starting {}\n", .{cpu.name});
_ = async cpu.run();
var i_input: usize = 0;
while (!cpu.is_halted()) {
if (cpu.io_mode == .input) {
cpu.io_port = ascii_programm[i_input];
i_input += 1;
trace("wrting input to {} = {}\n", .{ cpu.name, cpu.io_port });
}
if (cpu.io_mode == .output) {
trace("{} outputs {}\n", .{ cpu.name, cpu.io_port });
if (cpu.io_port < 127) {
//stdout.print("{c}", .{@intCast(u8, cpu.io_port)}) catch unreachable;
} else {
break :ans2 cpu.io_port;
}
}
trace("resuming {}\n", .{cpu.name});
resume cpu.io_runframe;
}
unreachable;
};
return [_][]const u8{
try std.fmt.allocPrint(allocator, "{}", .{part1}),
try std.fmt.allocPrint(allocator, "{}", .{part2}),
};
}
pub const main = tools.defaultMain("2019/day21.txt", run); | 2019/day21.zig |
const std = @import("std");
const assert = std.debug.assert;
const tools = @import("tools");
const Registers = [6]u64;
const Opcode = enum { addi, addr, muli, mulr, bani, banr, bori, borr, setr, seti, gtir, gtri, gtrr, eqir, eqri, eqrr };
fn eval(op: Opcode, par: [3]u32, r: Registers) Registers {
var o = r;
switch (op) {
.addi => o[par[2]] = r[par[0]] + par[1],
.addr => o[par[2]] = r[par[0]] + r[par[1]],
.muli => o[par[2]] = r[par[0]] * par[1],
.mulr => o[par[2]] = r[par[0]] * r[par[1]],
.bani => o[par[2]] = r[par[0]] & par[1],
.banr => o[par[2]] = r[par[0]] & r[par[1]],
.bori => o[par[2]] = r[par[0]] | par[1],
.borr => o[par[2]] = r[par[0]] | r[par[1]],
.setr => o[par[2]] = r[par[0]],
.seti => o[par[2]] = par[0],
.gtir => o[par[2]] = if (par[0] > r[par[1]]) @as(u32, 1) else @as(u32, 0),
.gtri => o[par[2]] = if (r[par[0]] > par[1]) @as(u32, 1) else @as(u32, 0),
.gtrr => o[par[2]] = if (r[par[0]] > r[par[1]]) @as(u32, 1) else @as(u32, 0),
.eqir => o[par[2]] = if (par[0] == r[par[1]]) @as(u32, 1) else @as(u32, 0),
.eqri => o[par[2]] = if (r[par[0]] == par[1]) @as(u32, 1) else @as(u32, 0),
.eqrr => o[par[2]] = if (r[par[0]] == r[par[1]]) @as(u32, 1) else @as(u32, 0),
}
return o;
}
pub fn run(input_text: []const u8, allocator: std.mem.Allocator) ![2][]const u8 {
var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit();
const Insn = struct { op: Opcode, par: [3]u32 };
const param: struct {
ip: u32,
prg: []Insn,
} = param: {
var prg = std.ArrayList(Insn).init(arena.allocator());
var ip: ?u32 = null;
var it = std.mem.tokenize(u8, input_text, "\n\r");
while (it.next()) |line| {
if (tools.match_pattern("{} {} {} {}", line)) |fields| {
const op = try tools.nameToEnum(Opcode, fields[0].lit);
const par = [3]u32{
@intCast(u32, fields[1].imm),
@intCast(u32, fields[2].imm),
@intCast(u32, fields[3].imm),
};
try prg.append(Insn{ .op = op, .par = par });
} else if (tools.match_pattern("#ip {}", line)) |fields| {
assert(ip == null);
ip = @intCast(u32, fields[0].imm);
} else unreachable;
}
break :param .{ .ip = ip.?, .prg = prg.items };
};
const ans1 = ans: {
var reg: Registers = .{ 0, 0, 0, 0, 0, 0 };
var ip: u32 = 0;
while (ip < param.prg.len) {
reg[param.ip] = ip;
if (false and ip <= 2) {
std.debug.print("[{}] {} {},{},{} regs=<{}, {}, {}, {}, ({}), {}>\n", .{
ip,
param.prg[ip].op,
param.prg[ip].par[0],
param.prg[ip].par[1],
param.prg[ip].par[2],
reg[0],
reg[1],
reg[2],
reg[3],
reg[4],
reg[5],
});
}
reg = eval(param.prg[ip].op, param.prg[ip].par, reg);
ip = @intCast(u32, reg[param.ip]);
ip += 1;
}
break :ans reg[0];
};
const ans2 = ans: {
//var reg: Registers = .{ 1, 0, 0, 0, 0, 0 };
//var ip: u32 = 0;
////reg = .{ 1, 10551311, 105510, 0, 2, 10551312 };
////ip = 2;
//while (ip < param.prg.len) {
// reg[param.ip] = ip;
// reg = eval(param.prg[ip].op, param.prg[ip].par, reg);
// ip = @intCast(u32, reg[param.ip]);
// ip += 1;
//}
// le programme calcule (très lentement) la some des facteurs premiers : (cf ci-dessous)
break :ans 1 + 431 + 24481 + 10551311;
};
return [_][]const u8{
try std.fmt.allocPrint(allocator, "{}", .{ans1}),
try std.fmt.allocPrint(allocator, "{}", .{ans2}),
};
}
pub const main = tools.defaultMain("2018/input_day19.txt", run);
// [00] addi 4 16 4 jmp lbl_start
// [01] seti 1 7 2 r2=1
// [02] seti 1 1 5 R5=1
// [03] mulr 2 5 3 R3=R5*R2
// [04] eqrr 3 1 3 if (R3 == R1)
// [05] addr 3 4 4 //
// [06] addi 4 1 4 //
// [07] addr 2 0 0 // R0 += R2
// [08] addi 5 1 5 R5+=1
// [09] gtrr 5 1 3 if (R5<=R1) jmp 03
// [10] addr 4 3 4 //
// [11] seti 2 7 4 //
// [12] addi 2 1 2 R2+=1
// [13] gtrr 2 1 3 if (R2<=R1) JUMP 01
// [14] addr 3 4 4 //
// [15] seti 1 3 4 //
// [16] mulr 4 4 4 EXIT
// [17] addi 1 2 1 lbl_start
// [18] mulr 1 1 1
// [19] mulr 4 1 1
// [20] muli 1 11 1
// [21] addi 3 3 3
// [22] mulr 3 4 3
// [23] addi 3 9 3
// [24] addr 1 3 1
// [25] addr 4 0 4 jmp lbl_part2
// [26] seti 0 1 4 // jmp lbl1
// [27] setr 4 9 3 lbl_part2:
// [28] mulr 3 4 3
// [29] addr 4 3 3
// [30] mulr 4 3 3
// [31] muli 3 14 3
// [32] mulr 3 4 3
// [33] addr 1 3 1 R1= 10551311
// [34] seti 0 6 0 R0=0
// [35] seti 0 7 4 jmp 01 | 2018/day19.zig |
const std = @import("std");
const utils = @import("utils");
const georgios = @import("georgios.zig");
const memory = @import("memory.zig");
pub const FileError = error {
/// The operation is not supported.
Unsupported,
/// An Implementation-Related Error Occured.
Internal,
InvalidFileId,
} || utils.Error || memory.MemoryError;
/// File IO Interface
pub const File = struct {
pub const Writer = std.io.Writer(*File, FileError, write);
pub const Id = u32;
/// Used for seek()
pub const SeekType = enum {
FromStart,
FromHere,
FromEnd,
};
pub const nop = struct {
pub fn read_impl(file: *File, to: []u8) FileError!usize {
_ = file;
_ = to;
return 0;
}
pub fn write_impl(file: *File, from: []const u8) FileError!usize {
_ = file;
return from.len;
}
pub fn seek_impl(file: *File,
offset: isize, seek_type: SeekType) FileError!usize {
_ = file;
_ = offset;
_ = seek_type;
return 0;
}
pub fn close_impl(file: *File) FileError!void {
_ = file;
}
};
pub const unsupported = struct {
pub fn read_impl(file: *File, to: []u8) FileError!usize {
_ = file;
_ = to;
return FileError.Unsupported;
}
pub fn write_impl(file: *File, from: []const u8) FileError!usize {
_ = file;
_ = from;
return FileError.Unsupported;
}
pub fn seek_impl(file: *File,
offset: isize, seek_type: SeekType) FileError!usize {
_ = file;
_ = offset;
_ = seek_type;
return FileError.Unsupported;
}
pub fn close_impl(file: *File) FileError!void {
_ = file;
return FileError.Unsupported;
}
};
pub const system_call = struct {
pub fn read_impl(file: *File, to: []u8) FileError!usize {
return georgios.system_calls.file_read(file.id.?, to);
}
pub fn write_impl(file: *File, from: []const u8) FileError!usize {
return georgios.system_calls.file_write(file.id.?, from);
}
pub fn seek_impl(file: *File,
offset: isize, seek_type: SeekType) FileError!usize {
// TODO: Causes Zig to crash:
// return georgios.system_calls.file_seek(file.id.?, offset, seek_type);
_ = file;
_ = offset;
_ = seek_type;
return FileError.Unsupported;
}
pub fn close_impl(file: *File) FileError!void {
return georgios.system_calls.file_close(file.id.?);
}
};
const default_impl = if (georgios.is_program) system_call else unsupported;
valid: bool = false,
id: ?Id = null,
set_up_writer: bool = false,
_writer: Writer = undefined,
read_impl: fn(*File, []u8) FileError!usize = default_impl.read_impl,
write_impl: fn(*File, []const u8) FileError!usize = default_impl.write_impl,
seek_impl: fn(*File, isize, SeekType) FileError!usize = default_impl.seek_impl,
close_impl: fn(*File) FileError!void = default_impl.close_impl,
/// Set the file to do nothing when used.
pub fn set_nop_impl(self: *File) void {
self.read_impl = nop.read_impl;
self.write_impl = nop.write_impl;
self.seek_impl = nop.seek_impl;
self.close_impl = nop.close_impl;
}
/// Set the file to return FileError.Unsupported when used.
pub fn set_unsupported_impl(self: *File) void {
self.read_impl = unsupported.read_impl;
self.write_impl = unsupported.write_impl;
self.seek_impl = unsupported.seek_impl;
self.close_impl = unsupported.close_impl;
}
/// Tries to read as much as possible into the `to` slice and will return
/// the amount read, which may be less than `to.len`. Can return 0 if the
/// `to` slice is zero or the end of the file has been reached already. It
/// should never return `FileError.OutOfBounds` or
/// `FileError.NotEnoughDestination`, but `read_or_error` will. The exact
/// return values are defined by the file implementation.
pub fn read(file: *File, to: []u8) callconv(.Inline) FileError!usize {
return file.read_impl(file, to);
}
/// Same as `read`, but return `FileError.OutOfBounds` if an empty `to` was
/// passed or `FileError.OutOfBounds` if trying to read from a file that's
/// already reached the end.
pub fn read_or_error(file: *File, to: []u8) callconv(.Inline) FileError!usize {
if (to.len == 0) {
return FileError.NotEnoughDestination;
}
const result = try file.read_impl(file, to);
if (result == 0) {
return FileError.OutOfBounds;
}
return result;
}
/// Tries the write the entire `from` slice and will return the amount
/// written, which may be less than `from.len`. As with `read` this can be
/// 0 if the file has a limit of what can be written and that limit was
/// already reached. Also like `read` this should never return
/// `FileError.OutOfBounds`, but `write_or_error` can. The exact return
/// values are defined by the file implementation.
pub fn write(file: *File, from: []const u8) FileError!usize {
return file.write_impl(file, from);
}
/// Same as `write`, but return `FileError.OutOfBounds` if an empty `from`
/// was passed or `FileError.OutOfBounds` if trying to write to a file
/// that's already reached the end.
pub fn write_or_error(file: *File, from: []const u8) callconv(.Inline) FileError!usize {
const result = file.write_impl(file, from);
if (result == 0 and from.len > 0) {
return FileError.OutOfBounds;
}
return result;
}
/// Shift where the file is operating from. Returns the new location if
/// that's applicable, but if it's not it always returns 0.
pub fn seek(file: *File, offset: isize,
seek_type: File.SeekType) callconv(.Inline) FileError!usize {
return file.seek_impl(file, offset, seek_type);
}
/// Free resources used by the file.
pub fn close(file: *File) callconv(.Inline) FileError!void {
defer file.valid = false;
file.close_impl(file) catch |e| return e;
}
/// A generic seek calculation for File Implementations to call.
/// This assumes the following:
/// - The start of the stream is always 0 and this is something that can
/// be seeked.
/// - The `position` can never over or under flow, or otherwise go past
/// start by being negative.
/// - If `limit` is non-null, then the stream position can't go past it.
/// The result is returned unless it's invalid, then
/// `FileError.OutOfBounds` is returned.
pub fn generic_seek(position: usize, end: usize, limit: ?usize,
offset: isize, seek_type: SeekType) FileError!usize {
const from: usize = switch (seek_type) {
.FromStart => 0,
.FromHere => position,
.FromEnd => end,
};
if (utils.add_isize_to_usize(from, offset)) |result| {
if (result != position and limit != null and result >= limit.?) {
return FileError.OutOfBounds;
}
return result;
}
return FileError.OutOfBounds;
}
pub fn get_writer(self: *File) *Writer {
if (!self.set_up_writer) {
self._writer = Writer{.context = self};
self.set_up_writer = true;
}
return &self._writer;
}
// fn writer_write(self: *File, bytes: []const u8) FileError!void {
// _ = try self.write(bytes);
// }
};
/// Test for normal situation.
fn generic_seek_subtest(seek_type: File.SeekType, expected_from: usize) !void {
try std.testing.expectEqual(expected_from,
try File.generic_seek(1, 4, null, 0, seek_type));
try std.testing.expectEqual(expected_from + 5,
try File.generic_seek(1, 4, null, 5, seek_type));
try std.testing.expectError(FileError.OutOfBounds,
File.generic_seek(1, 4, 4, 5, seek_type));
try std.testing.expectError(FileError.OutOfBounds,
File.generic_seek(1, 4, 4, -5, seek_type));
try std.testing.expectError(FileError.OutOfBounds,
File.generic_seek(1, 4, 4, -5, seek_type));
}
test "File.generic_seek" {
// Some normal situations
try generic_seek_subtest(.FromStart, 0);
try generic_seek_subtest(.FromHere, 1);
try generic_seek_subtest(.FromEnd, 4);
// We should be able to go to max_usize.
const max_usize = utils.max_of_int(usize);
const max_isize = utils.max_of_int(isize);
const max_isize_as_usize = @bitCast(usize, max_isize);
try std.testing.expectEqual(max_usize,
max_isize_as_usize + max_isize_as_usize + 1); // Just a sanity check
try std.testing.expectEqual(max_usize,
try File.generic_seek(max_isize_as_usize + 1, 4, null, max_isize, .FromHere));
// However we shouldn't be able to go to past max_usize.
try std.testing.expectError(FileError.OutOfBounds,
File.generic_seek(max_usize, 4, null, 5, .FromHere));
try std.testing.expectError(FileError.OutOfBounds,
File.generic_seek(max_usize, 4, 4, 5, .FromHere));
}
/// File that reads from and writes to a provided fixed buffer.
pub const BufferFile = struct {
const Self = @This();
file: File = undefined,
buffer: []u8 = undefined,
position: usize = 0,
written_up_until: usize = 0,
pub fn init(self: *Self, buffer: []u8) void {
self.file.read_impl = Self.read;
self.file.write_impl = Self.write;
self.file.seek_impl = Self.seek;
self.file.close_impl = File.nop.close_impl;
self.buffer = buffer;
self.reset();
}
pub fn reset(self: *Self) void {
self.position = 0;
self.written_up_until = 0;
}
pub fn read(file: *File, to: []u8) FileError!usize {
const self = @fieldParentPtr(Self, "file", file);
if (self.written_up_until > self.position) {
const read_size = self.written_up_until - self.position;
_ = utils.memory_copy_truncate(to[0..read_size],
self.buffer[self.position..self.written_up_until]);
self.position = self.written_up_until;
return read_size;
}
return 0;
}
fn fill_unwritten(self: *Self, pos: usize) void {
if (pos > self.written_up_until) {
utils.memory_set(self.buffer[self.written_up_until..pos], 0);
}
}
pub fn write(file: *File, from: []const u8) FileError!usize {
const self = @fieldParentPtr(Self, "file", file);
const write_size = utils.min(usize, from.len, self.buffer.len - self.position);
if (write_size > 0) {
self.fill_unwritten(self.position);
const new_position = self.position + write_size;
_ = utils.memory_copy_truncate(self.buffer[self.position..new_position],
from[0..write_size]);
self.position = new_position;
self.written_up_until = new_position;
}
return write_size;
}
pub fn seek(file: *File,
offset: isize, seek_type: File.SeekType) FileError!usize {
const self = @fieldParentPtr(Self, "file", file);
const new_postion = try File.generic_seek(
self.position, self.written_up_until, self.buffer.len, offset, seek_type);
self.position = new_postion;
return new_postion;
}
pub fn set_contents(
self: *Self, offset: usize, new_contents: []const u8) utils.Error!void {
self.fill_unwritten(offset);
self.written_up_until = offset +
try utils.memory_copy_error(self.buffer[offset..], new_contents);
}
pub fn get_contents(self: *Self) []u8 {
return self.buffer[0..self.written_up_until];
}
pub fn expect(self: *Self, expected_contents: []const u8) !void {
try std.testing.expectEqualSlices(u8, expected_contents, self.get_contents());
}
};
test "BufferFile" {
var file_buffer: [128]u8 = undefined;
var buffer_file = BufferFile{};
buffer_file.init(file_buffer[0..]);
const file = &buffer_file.file;
// Put "adc123" into `file_buffer`, read it into `result_buffer`, then
// compare them.
const string = "abc123";
const len = string.len;
var result_buffer: [128]u8 = undefined;
try buffer_file.set_contents(0, string);
try std.testing.expectEqual(len, try file.read(result_buffer[0..]));
// TODO: Show strings if fail?
try std.testing.expectEqualSlices(u8, string[0..], result_buffer[0..len]);
try buffer_file.expect(string[0..]);
// Seek position 3 and then read three 3 to start of result buffer
try std.testing.expectEqual(@as(usize, 3), try file.seek(3, .FromStart));
try std.testing.expectEqual(@as(usize, 3), try file.read(result_buffer[0..]));
try std.testing.expectEqualSlices(u8, "123123", result_buffer[0..len]);
// Try to read again at the end of the file
try std.testing.expectEqual(@as(usize, 0), try file.read(result_buffer[0..]));
try std.testing.expectEqual(len, buffer_file.position);
// Try Writing Another String Over It
const string2 = "cdef";
try std.testing.expectEqual(@as(usize, 2), try file.seek(2, .FromStart));
try std.testing.expectEqual(@as(usize, string2.len), try file.write(string2));
try std.testing.expectEqual(@as(usize, 0), try file.seek(0, .FromStart));
try std.testing.expectEqual(len, try file.read(result_buffer[0..]));
try std.testing.expectEqualSlices(u8, "abcdef", result_buffer[0..len]);
// Unwritten With Set Contents
{
buffer_file.reset();
const blank = "\x00\x00\x00\x00\x00\x00\x00\x00";
const str = "Georgios";
try buffer_file.set_contents(blank.len, str);
try buffer_file.expect(blank ++ str);
}
// Unwritten With Seek
{
buffer_file.reset();
const str1 = "123";
try std.testing.expectEqual(str1.len, try file.write(str1));
try std.testing.expectEqual(str1.len, buffer_file.written_up_until);
const blank = "\x00\x00\x00\x00\x00\x00\x00\x00";
const expected1 = str1 ++ blank;
try std.testing.expectEqual(expected1.len,
try file.seek(expected1.len, .FromStart));
try std.testing.expectEqual(str1.len, buffer_file.written_up_until);
try buffer_file.expect(str1);
const str2 = "4567";
try std.testing.expectEqual(str2.len, try file.write(str2));
const expected2 = expected1 ++ str2;
try buffer_file.expect(expected2);
}
// Try to Write and Read End Of Buffer
{
buffer_file.reset();
const str = "xyz";
const pos = file_buffer.len - str.len;
try buffer_file.set_contents(pos, str);
try std.testing.expectEqual(pos, try file.seek(-@as(isize, str.len), .FromEnd));
try std.testing.expectEqual(str.len, try file.read(result_buffer[0..]));
try std.testing.expectEqualSlices(u8, str[0..], result_buffer[0..str.len]);
try std.testing.expectEqual(@as(usize, 0), try file.write("ijk"));
try std.testing.expectEqual(@as(usize, 0), try file.read(result_buffer[0..]));
}
} | libs/georgios/io.zig |
const sf = @import("../sfml.zig");
const Time = @This();
// Constructors
/// Converts a time from a csfml object
/// For inner workings
pub fn _fromCSFML(time: sf.c.sfTime) Time {
return Time{ .us = time.microseconds };
}
/// Converts a time to a csfml object
/// For inner workings
pub fn _toCSFML(self: Time) sf.c.sfTime {
return sf.c.sfTime{ .microseconds = self.us };
}
/// Creates a time object from a seconds count
pub fn seconds(s: f32) Time {
return Time{ .us = @floatToInt(i64, s * 1_000) * 1_000 };
}
/// Creates a time object from milliseconds
pub fn milliseconds(ms: i32) Time {
return Time{ .us = @intCast(i64, ms) * 1_000 };
}
/// Creates a time object from microseconds
pub fn microseconds(us: i64) Time {
return Time{ .us = us };
}
// Getters
/// Gets this time measurement as microseconds
pub fn asMicroseconds(self: Time) i64 {
return self.us;
}
/// Gets this time measurement as milliseconds
pub fn asMilliseconds(self: Time) i32 {
return @truncate(i32, @divFloor(self.us, 1_000));
}
/// Gets this time measurement as seconds (as a float)
pub fn asSeconds(self: Time) f32 {
return @intToFloat(f32, self.us) / 1_000_000;
}
// Misc
/// Sleeps the amount of time specified
pub fn sleep(time: Time) void {
sf.c.sfSleep(time._toCSFML());
}
/// A time of zero
pub const Zero = microseconds(0);
us: i64,
pub const TimeSpan = struct {
// Constructors
/// Construcs a time span
pub fn init(begin: Time, length: Time) TimeSpan {
return TimeSpan{
.offset = begin,
.length = length,
};
}
/// Converts a timespan from a csfml object
/// For inner workings
pub fn _fromCSFML(span: sf.c.sfTimeSpan) TimeSpan {
return TimeSpan{
.offset = Time._fromCSFML(span.offset),
.length = Time._fromCSFML(span.length),
};
}
/// Converts a timespan to a csfml object
/// For inner workings
pub fn _toCSFML(self: TimeSpan) sf.c.sfTimeSpan {
return sf.c.sfTimeSpan{
.offset = self.offset._toCSFML(),
.length = self.length._toCSFML(),
};
}
/// The beginning of this span
offset: Time,
/// The length of this time span
length: Time,
};
test "time: conversion" {
const tst = @import("std").testing;
var t = Time.microseconds(5_120_000);
try tst.expectEqual(@as(i32, 5_120), t.asMilliseconds());
try tst.expectApproxEqAbs(@as(f32, 5.12), t.asSeconds(), 0.0001);
t = Time.seconds(12);
try tst.expectApproxEqAbs(@as(f32, 12), t.asSeconds(), 0.0001);
t = Time.microseconds(800);
try tst.expectApproxEqAbs(@as(f32, 0.0008), t.asSeconds(), 0.0001);
} | src/sfml/system/Time.zig |
const std = @import("std");
pub fn build(b: *std.build.Builder) void {
// 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("zigcurl", "src/main.zig");
//exe.addCSourceFile("src/download.c", &[_][]const u8{});
//exe.setTarget(.{.cpu_arch = .aarch64, .os_tag = .linux, .abi = .gnu});
exe.setTarget(target);
exe.setBuildMode(mode);
//exe.setVerboseCC(true);
//exe.setVerboseLink(true);
exe.linkLibC();
if (exe.target.isDarwin()) {
// brew install curl
const libCurlPath = "/opt/homebrew/opt/curl/lib";
exe.addLibPath(libCurlPath);
// workaround for UnhandledSymbolType (is a _curl_jmpenv common symbol)
const dir = std.fs.openDirAbsolute(libCurlPath, .{.access_sub_paths = true}) catch {
std.log.err("could not open {s}", .{libCurlPath});
std.process.exit(1);
};
if (dir.rename("libcurl.a", "libcurl.a.bak")) {
std.log.info("renamed {s}/libcurl.a to libcurl.a.bak", .{libCurlPath});
} else |err| {
std.debug.assert(err == error.FileNotFound);
}
}
exe.linkSystemLibrary("curl"); // add libcurl to the project
// exe.addIncludeDir("/opt/homebrew/opt/curl/include");
// exe.addLibPath("/usr/lib/aarch64-linux-gnu");
// exe.linkSystemLibraryName("curl");
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);
} | build.zig |
const expect = @import("std").testing.expect;
const mem = @import("std").mem;
const Tag = @import("std").meta.Tag;
const Small2 = enum(u2) { One, Two };
const A = enum(u3) { One, Two, Three, Four, One2, Two2, Three2, Four2 };
const B = enum(u3) { One3, Two3, Three3, Four3, One23, Two23, Three23, Four23 };
const C = enum(u2) { One4, Two4, Three4, Four4 };
const BitFieldOfEnums = packed struct {
a: A,
b: B,
c: C,
};
const bit_field_1 = BitFieldOfEnums{
.a = A.Two,
.b = B.Three3,
.c = C.Four4,
};
test "bit field access with enum fields" {
var data = bit_field_1;
try expect(getA(&data) == A.Two);
try expect(getB(&data) == B.Three3);
try expect(getC(&data) == C.Four4);
comptime try expect(@sizeOf(BitFieldOfEnums) == 1);
data.b = B.Four3;
try expect(data.b == B.Four3);
data.a = A.Three;
try expect(data.a == A.Three);
try expect(data.b == B.Four3);
}
fn getA(data: *const BitFieldOfEnums) A {
return data.a;
}
fn getB(data: *const BitFieldOfEnums) B {
return data.b;
}
fn getC(data: *const BitFieldOfEnums) C {
return data.c;
}
const MultipleChoice2 = enum(u32) {
Unspecified1,
A = 20,
Unspecified2,
B = 40,
Unspecified3,
C = 60,
Unspecified4,
D = 1000,
Unspecified5,
};
const EnumWithOneMember = enum { Eof };
fn doALoopThing(id: EnumWithOneMember) void {
while (true) {
if (id == EnumWithOneMember.Eof) {
break;
}
@compileError("above if condition should be comptime");
}
}
test "comparison operator on enum with one member is comptime known" {
doALoopThing(EnumWithOneMember.Eof);
}
const State = enum { Start };
test "switch on enum with one member is comptime known" {
var state = State.Start;
switch (state) {
State.Start => return,
}
@compileError("analysis should not reach here");
}
test "enum literal in array literal" {
const Items = enum { one, two };
const array = [_]Items{ .one, .two };
try expect(array[0] == .one);
try expect(array[1] == .two);
}
test "enum value allocation" {
const LargeEnum = enum(u32) {
A0 = 0x80000000,
A1,
A2,
};
try expect(@enumToInt(LargeEnum.A0) == 0x80000000);
try expect(@enumToInt(LargeEnum.A1) == 0x80000001);
try expect(@enumToInt(LargeEnum.A2) == 0x80000002);
}
test "enum literal casting to tagged union" {
const Arch = union(enum) {
x86_64,
arm: Arm32,
const Arm32 = enum {
v8_5a,
v8_4a,
};
};
var t = true;
var x: Arch = .x86_64;
var y = if (t) x else .x86_64;
switch (y) {
.x86_64 => {},
else => @panic("fail"),
}
}
const Bar = enum { A, B, C, D };
test "enum literal casting to error union with payload enum" {
var bar: error{B}!Bar = undefined;
bar = .B; // should never cast to the error set
try expect((try bar) == Bar.B);
}
test "tagName on enum literals" {
try expect(mem.eql(u8, @tagName(.FooBar), "FooBar"));
comptime try expect(mem.eql(u8, @tagName(.FooBar), "FooBar"));
}
test "method call on an enum" {
const S = struct {
const E = enum {
one,
two,
fn method(self: *E) bool {
return self.* == .two;
}
fn generic_method(self: *E, foo: anytype) bool {
return self.* == .two and foo == bool;
}
};
fn doTheTest() !void {
var e = E.two;
try expect(e.method());
try expect(e.generic_method(bool));
}
};
try S.doTheTest();
comptime try S.doTheTest();
}
test "exporting enum type and value" {
const S = struct {
const E = enum(c_int) { one, two };
comptime {
@export(E, .{ .name = "E" });
}
const e: E = .two;
comptime {
@export(e, .{ .name = "e" });
}
};
try expect(S.e == .two);
} | test/behavior/enum_stage1.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const Metadata = @import("metadata.zig").Metadata;
const id3v1 = @import("id3v1.zig"); // needed for genre ID lookup for gnre atom
// Some atoms can be "full atoms", meaning they have an additional 4 bytes
// for a version and some flags.
pub const FullAtomHeader = struct {
version: u8,
flags: u24,
pub const len = 4;
pub fn read(reader: anytype) !FullAtomHeader {
return FullAtomHeader{
.version = try reader.readByte(),
.flags = try reader.readIntBig(u24),
};
}
};
/// Every atom in a MP4 file has this fixed-size header
pub const AtomHeader = struct {
/// the atom size (including the header)
size: u64,
/// the name or type
name: [4]u8,
/// whether or not this atom has its size speicfied in an extended size field
extended_size: bool,
/// Length of a normal atom header (without an extended size field)
pub const len = 8;
/// Length of an extended size field (if it exists)
pub const extended_size_field_len = 8;
pub fn read(reader: anytype, seekable_stream: anytype) !AtomHeader {
var header: AtomHeader = undefined;
header.extended_size = false;
const size_field = try reader.readIntBig(u32);
try reader.readNoEof(&header.name);
header.size = switch (size_field) {
0 => blk: {
// a size of 0 means the atom extends to end of file
const remaining = (try seekable_stream.getEndPos()) - (try seekable_stream.getPos());
break :blk remaining;
},
1 => blk: {
// a size of 1 means the atom header has an extended size field
header.extended_size = true;
break :blk try reader.readIntBig(u64);
},
else => |size| size,
};
if (header.size < header.headerSize()) {
return error.AtomSizeTooSmall;
}
const remaining = (try seekable_stream.getEndPos()) - (try seekable_stream.getPos());
if (header.sizeExcludingHeader() > remaining) {
return error.EndOfStream;
}
return header;
}
pub fn headerSize(self: AtomHeader) u64 {
const extended_len: u64 = if (self.extended_size) AtomHeader.extended_size_field_len else 0;
return AtomHeader.len + extended_len;
}
pub fn sizeExcludingHeader(self: AtomHeader) u64 {
return self.size - self.headerSize();
}
};
/// Generic data atom
///
/// See the iTunes Metadata Format Specification
pub const DataAtom = struct {
header: AtomHeader,
indicators: Indicators,
pub fn read(reader: anytype, seekable_stream: anytype) !DataAtom {
const header = try AtomHeader.read(reader, seekable_stream);
return readIndicatorsGivenHeader(header, reader);
}
pub fn readIndicatorsGivenHeader(header: AtomHeader, reader: anytype) !DataAtom {
if (!std.mem.eql(u8, "data", &header.name)) {
return error.InvalidDataAtom;
}
if (header.sizeExcludingHeader() < Indicators.len) {
return error.DataAtomSizeTooSmall;
}
return DataAtom{
.header = header,
.indicators = Indicators{
.type_indicator = try reader.readIntBig(u32),
.locale_indicator = try reader.readIntBig(u32),
},
};
}
pub const Indicators = struct {
type_indicator: u32,
locale_indicator: u32,
pub const len = 8;
/// Returns the 'type set' identifier of the "type indicator" field.
fn getTypeSet(self: Indicators) TypeSet {
return @intToEnum(TypeSet, (self.type_indicator & 0x0000FF00) >> 8);
}
pub const TypeSet = enum(u8) {
basic = 0,
// anything besides 0 is unknown
_,
};
/// Returns the basic type of the value, or null if the type set is unknown instead of basic.
///
/// See the iTunes Metadata Format Specification
fn getBasicType(self: Indicators) ?BasicType {
switch (self.getTypeSet()) {
.basic => {
const basic_type = @intCast(u8, self.type_indicator & 0x000000FF);
return @intToEnum(BasicType, basic_type);
},
else => return null,
}
}
/// From the iTunes Metadata Format Specification
pub const BasicType = enum(u8) {
implicit = 0,
utf8 = 1,
utf16_be = 2,
s_jis = 3,
html = 6,
xml = 7,
uuid = 8,
isrc = 9, // as UTF-8
mi3p = 10, // as UTF-8
gif = 12,
jpeg = 13,
png = 14,
url = 15,
duration = 16, // milliseconds as a u32
date_time = 17, // in UTC, seconds since midnight 1 Jan 1904, 32 or 64 bits
genres = 18, // list of genre ids
be_signed_integer = 21, // 1, 2, 3, 4, or 8 bytes
riaa_pa = 24,
upc = 25, // as UTF-8
bmp = 27,
_,
};
};
pub fn dataSize(self: DataAtom) u64 {
return self.header.sizeExcludingHeader() - Indicators.len;
}
pub fn readValueAsBytes(self: DataAtom, allocator: Allocator, reader: anytype) ![]u8 {
const data_size = self.dataSize();
var value = try allocator.alloc(u8, data_size);
errdefer allocator.free(value);
try reader.readNoEof(value);
return value;
}
pub fn skipValue(self: DataAtom, seekable_stream: anytype) !void {
const data_size = self.dataSize();
try seekByExtended(seekable_stream, data_size);
}
};
/// Reads a single metadata item within an `ilst` and adds its value(s) to the metadata if it's valid
pub fn readMetadataItem(allocator: Allocator, reader: anytype, seekable_stream: anytype, metadata: *Metadata, atom_header: AtomHeader, end_of_containing_atom: usize) !void {
// used as the name when the metadata item is of type ----
var full_meaning_name: ?[]u8 = null;
defer if (full_meaning_name != null) allocator.free(full_meaning_name.?);
var maybe_unhandled_header: ?AtomHeader = unhandled_header: {
// ---- is a special metadata item that has a 'mean' and an optional 'name' atom
// that describe the meaning as a string
if (std.mem.eql(u8, "----", &atom_header.name)) {
var meaning_string = meaning_string: {
const mean_header = try AtomHeader.read(reader, seekable_stream);
if (!std.mem.eql(u8, "mean", &mean_header.name)) {
return error.InvalidDataAtom;
}
if (mean_header.sizeExcludingHeader() < FullAtomHeader.len) {
return error.InvalidDataAtom;
}
// mean atoms are FullAtoms, so read the extra bits
_ = try FullAtomHeader.read(reader);
const data_size = mean_header.sizeExcludingHeader() - FullAtomHeader.len;
var meaning_string = try allocator.alloc(u8, data_size);
errdefer allocator.free(meaning_string);
try reader.readNoEof(meaning_string);
break :meaning_string meaning_string;
};
var should_free_meaning_string = true;
defer if (should_free_meaning_string) allocator.free(meaning_string);
var name_string = name_string: {
const name_header = try AtomHeader.read(reader, seekable_stream);
if (!std.mem.eql(u8, "name", &name_header.name)) {
// name is optional, so bail out and try reading the rest as a DataAtom
// we also want to save the meaning string for after the break
full_meaning_name = meaning_string;
// so we also need to stop it from getting freed in the defer
should_free_meaning_string = false;
break :unhandled_header name_header;
}
if (name_header.sizeExcludingHeader() < FullAtomHeader.len) {
return error.InvalidDataAtom;
}
// name atoms are FullAtoms, so read the extra bits
_ = try FullAtomHeader.read(reader);
const data_size = name_header.sizeExcludingHeader() - FullAtomHeader.len;
var name_string = try allocator.alloc(u8, data_size);
errdefer allocator.free(name_string);
try reader.readNoEof(name_string);
break :name_string name_string;
};
defer allocator.free(name_string);
// to get the full meaning string, the name is appended to the meaning with a '.' separator
full_meaning_name = try std.mem.join(allocator, ".", &.{ meaning_string, name_string });
break :unhandled_header null;
} else {
break :unhandled_header null;
}
};
// If this is a ---- item, use the full meaning name, otherwise use the metadata item atom's name
// TODO: Potentially store the two different ways of naming things
// in separate maps, like ID3v2.user_defined
const metadata_item_name: []const u8 = full_meaning_name orelse &atom_header.name;
// There can be more than 1 data atom per metadata item
while ((try seekable_stream.getPos()) < end_of_containing_atom) {
const data_atom = data_atom: {
if (maybe_unhandled_header) |unhandled_header| {
const data_atom = try DataAtom.readIndicatorsGivenHeader(unhandled_header, reader);
maybe_unhandled_header = null;
break :data_atom data_atom;
} else {
break :data_atom try DataAtom.read(reader, seekable_stream);
}
};
const maybe_basic_type = data_atom.indicators.getBasicType();
// We can do some extra verification here to avoid processing
// invalid atoms by checking that the reported size of the data
// fits inside the reported size of its containing atom.
const data_end_pos: usize = (try seekable_stream.getPos()) + data_atom.dataSize();
if (data_end_pos > end_of_containing_atom) {
return error.DataAtomSizeTooLarge;
}
if (maybe_basic_type) |basic_type| {
switch (basic_type) {
.utf8 => {
var value = try data_atom.readValueAsBytes(allocator, reader);
defer allocator.free(value);
try metadata.map.put(metadata_item_name, value);
},
// TODO: Verify that the UTF-16 case works correctly--I didn't have any
// files with UTF-16 data atoms.
.utf16_be => {
// data size must be divisible by 2
if (data_atom.dataSize() % 2 != 0) {
return error.InvalidUTF16Data;
}
var value_bytes = try allocator.alignedAlloc(u8, @alignOf(u16), data_atom.dataSize());
defer allocator.free(value_bytes);
try reader.readNoEof(value_bytes);
var value_utf16 = std.mem.bytesAsSlice(u16, value_bytes);
// swap the bytes to make it little-endian instead of big-endian
for (value_utf16) |c, i| {
value_utf16[i] = @byteSwap(u16, c);
}
// convert to UTF-8
var value_utf8 = std.unicode.utf16leToUtf8Alloc(allocator, value_utf16) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
else => return error.InvalidUTF16Data,
};
defer allocator.free(value_utf8);
try metadata.map.put(metadata_item_name, value_utf8);
},
.be_signed_integer => {
var size = data_atom.dataSize();
if (size == 0 or size > 8) {
return error.InvalidDataAtom;
}
var value_buf: [8]u8 = undefined;
var value_bytes = value_buf[0..size];
try reader.readNoEof(value_bytes);
const value_int: i64 = switch (size) {
1 => std.mem.readIntSliceBig(i8, value_bytes),
2 => std.mem.readIntSliceBig(i16, value_bytes),
3 => std.mem.readIntSliceBig(i24, value_bytes),
4 => std.mem.readIntSliceBig(i32, value_bytes),
8 => std.mem.readIntSliceBig(i64, value_bytes),
else => unreachable,
};
const longest_possible_string = "-9223372036854775808";
var int_string_buf: [longest_possible_string.len]u8 = undefined;
const value_utf8 = std.fmt.bufPrintIntToSlice(&int_string_buf, value_int, 10, .lower, .{});
try metadata.map.put(metadata_item_name, value_utf8);
},
.implicit => {
// these atoms have two 16-bit integer values
if (std.mem.eql(u8, "trkn", &atom_header.name) or std.mem.eql(u8, "disk", &atom_header.name)) {
if (data_atom.dataSize() < 4) {
return error.InvalidDataAtom;
}
const longest_possible_string = "65535/65535";
var utf8_buf: [longest_possible_string.len]u8 = undefined;
var utf8_fbs = std.io.fixedBufferStream(&utf8_buf);
var utf8_writer = utf8_fbs.writer();
// the first 16 bits are unknown
_ = try reader.readIntBig(u16);
// second 16 bits is the 'current' number
const current = try reader.readIntBig(u16);
// after that is the 'total' number (if present)
const maybe_total: ?u16 = total: {
if (data_atom.dataSize() >= 6) {
const val = try reader.readIntBig(u16);
break :total if (val != 0) val else null;
} else {
break :total null;
}
};
// there can be trailing bytes as well that are unknown, so
// just skip to the end
try seekable_stream.seekTo(end_of_containing_atom);
if (maybe_total) |total| {
utf8_writer.print("{}/{}", .{ current, total }) catch unreachable;
} else {
utf8_writer.print("{}", .{current}) catch unreachable;
}
try metadata.map.put(metadata_item_name, utf8_fbs.getWritten());
} else if (std.mem.eql(u8, "gnre", &atom_header.name)) {
if (data_atom.dataSize() != 2) {
return error.InvalidDataAtom;
}
// Note: The first byte having any non-zero value
// will make the genre lookup impossible, since ID3v1
// genres are limited to a u8, so reading it as a u16
// will better exclude invalid gnre atoms.
//
// TODO: This needs verification that this is the correct
// data type / handling of the value (ffmpeg skips
// the first byte, and TagLib reads it as a i16).
const genre_id_plus_one = try reader.readIntBig(u16);
if (genre_id_plus_one > 0 and genre_id_plus_one <= id3v1.id3v1_genre_names.len) {
const genre_id = genre_id_plus_one - 1;
const genre_name = id3v1.id3v1_genre_names[genre_id];
try metadata.map.put(metadata_item_name, genre_name);
}
} else {
// any other implicit type is unknown, though
try data_atom.skipValue(seekable_stream);
}
},
else => {
try data_atom.skipValue(seekable_stream);
},
}
} else {
try data_atom.skipValue(seekable_stream);
}
}
}
/// Reads the metadata from an MP4 file.
///
/// MP4 is defined in ISO/IEC 14496-14 but MP4 files are essentially identical to QuickTime container files.
/// See https://wiki.multimedia.cx/index.php/QuickTime_container for information.
///
/// This function does just enough to extract the metadata relevant to an audio file
pub fn read(allocator: Allocator, reader: anytype, seekable_stream: anytype) !Metadata {
var metadata: Metadata = Metadata.init(allocator);
errdefer metadata.deinit();
// A MP4 file is a tree of atoms. An "atom" is the building block of a MP4 container.
//
// First, we verify that the first atom is an `ftyp` atom in order to check that
// we are actually reading a MP4 file. This is technically optional according to
// https://developer.apple.com/library/archive/documentation/QuickTime/QTFF/QTFFChap1/qtff1.html#//apple_ref/doc/uid/TP40000939-CH203-CJBCBIFF
// but 'strongly recommendeded.'
//
// This verification is done so that we can short-circuit out of non-MP4 files quickly, instead
// of skipping around the file randomly due to happens-to-be-valid-enough data.
var first_atom_header = try AtomHeader.read(reader, seekable_stream);
if (!std.mem.eql(u8, "ftyp", &first_atom_header.name)) {
return error.MissingFileTypeCompatibilityAtom;
}
// We don't actually care too much about the contents of the `ftyp` atom, so just skip them
// TODO: Should we care about the contents?
try seekByExtended(seekable_stream, first_atom_header.sizeExcludingHeader());
// For our purposes of extracting the audio metadata we assume that the MP4 file
// respects the following layout which seem to be standard:
//
// ftyp
// [...] (potentially other top-level atoms)
// moov
// udta
// meta
// ilst
// aART
// \xA9alb
// \xA9ART
// ...
// [...] (potentially other top-level atoms)
//
// The data that interests us are the atoms under the "ilst" atom.
//
// We skip all top-level atoms completely until we find a `moov` atom, and
// then drill down to the metadata we care about, still skipping anything we
// don't care about.
var state: enum {
start,
in_moov,
in_udta,
in_meta,
in_ilst,
} = .start;
// Keep track of the end position of the atom we are currently 'inside'
// so that we can treat that as the end position of any data we try to read,
// since the size of atoms include the size of all of their children, too.
var end_of_current_atom: usize = try seekable_stream.getEndPos();
var end_of_ilst: usize = 0;
while (true) {
var start_pos = try seekable_stream.getPos();
const atom_header = AtomHeader.read(reader, seekable_stream) catch |err| {
// Because of the nature of the mp4 format, we can't really detect when
// all of the atoms are 'done', and instead will always get some type of error
// when reading the next header (EndOfStream or an invalid header).
// So, if we have already read some metadata, then we treat it as a successful read
// and return that metadata.
// However, we also need to reset the cursor position back to where it was
// before this particular attempt at reading a header so that
// the cursor position is not part-way through an invalid header when potentially
// trying to read something else after this function finishes.
try seekable_stream.seekTo(start_pos);
if (metadata.map.entries.items.len > 0) return metadata else return err;
};
end_of_current_atom = start_pos + atom_header.size;
switch (state) {
.start => if (std.mem.eql(u8, "moov", &atom_header.name)) {
state = .in_moov;
continue;
},
.in_moov => if (std.mem.eql(u8, "udta", &atom_header.name)) {
state = .in_udta;
continue;
},
.in_udta => if (std.mem.eql(u8, "meta", &atom_header.name)) {
// The full atom header doesn't interest us but it has to be read.
_ = try FullAtomHeader.read(reader);
metadata.start_offset = start_pos;
metadata.end_offset = end_of_current_atom;
state = .in_meta;
continue;
},
.in_meta => if (std.mem.eql(u8, "ilst", &atom_header.name)) {
// Used when handling the in_ilst state to know if there are more elements in the list.
end_of_ilst = end_of_current_atom;
state = .in_ilst;
continue;
},
.in_ilst => {
readMetadataItem(allocator, reader, seekable_stream, &metadata, atom_header, end_of_current_atom) catch |err| switch (err) {
// Some errors within the ilst can be recovered from by skipping the invalid atom
error.DataAtomSizeTooLarge,
error.DataAtomSizeTooSmall,
error.InvalidDataAtom,
error.AtomSizeTooSmall,
error.InvalidUTF16Data,
=> {
try seekable_stream.seekTo(end_of_current_atom);
},
else => |e| return e,
};
if ((try seekable_stream.getPos()) >= end_of_ilst) {
state = .start;
}
continue;
},
}
// Skip every atom we don't recognize or are not interested in.
try seekByExtended(seekable_stream, atom_header.sizeExcludingHeader());
}
return metadata;
}
/// SeekableStream.seekBy wrapper that allows for u64 sizes
fn seekByExtended(seekable_stream: anytype, amount: u64) !void {
if (std.math.cast(u32, amount)) |seek_amount| {
try seekable_stream.seekBy(seek_amount);
} else |_| {
var remaining = amount;
while (remaining > 0) {
const seek_amt = std.math.min(remaining, std.math.maxInt(u32));
try seekable_stream.seekBy(@intCast(u32, seek_amt));
remaining -= seek_amt;
}
}
}
test "seekByExtended" {
const TestStream = struct {
pos: u64,
const Self = @This();
// dummy partial-implementation of a seekable stream
// that assumes all seekBy calls use positives `amt`s
pub const SeekableStream = struct {
ctx: *Self,
pub fn seekBy(self: @This(), amt: i64) !void {
self.ctx.pos += @intCast(u32, amt);
}
};
};
var test_stream = TestStream{ .pos = 0 };
const test_seekable_stream = TestStream.SeekableStream{ .ctx = &test_stream };
const large_seek_amt: u64 = 1 << 32;
try seekByExtended(test_seekable_stream, large_seek_amt);
try std.testing.expectEqual(large_seek_amt, test_stream.pos);
}
test "atom size too small" {
const res = readData(std.testing.allocator, ftyp_test_data ++ "\x00\x00\x00\x03moov");
try std.testing.expectError(error.AtomSizeTooSmall, res);
}
test "data atom size too small" {
// 0x0A is too small of a size for the data atom, so it should be skipped
const invalid_data = "\x00\x00\x00\x10aART\x00\x00\x00\x0Adata";
const valid_data = "\x00\x00\x00\x18\xA9nam\x00\x00\x00\x10data\x00\x00\x00\x01\x00\x00\x00\x00";
const data = try writeTestData(std.testing.allocator, invalid_data ++ valid_data);
defer std.testing.allocator.free(data);
var metadata = try readData(std.testing.allocator, data);
defer metadata.deinit();
// the invalid atom should be skipped but the valid one should be read
try std.testing.expectEqual(@as(usize, 1), metadata.map.entries.items.len);
}
test "data atom size too large" {
// data atom's reported size is too large to be contained in its containing atom, so it should be skipped
const invalid_data = "\x00\x00\x00\x10aART\x00\x00\x00\x10data";
const valid_data = "\x00\x00\x00\x18\xA9nam\x00\x00\x00\x10data\x00\x00\x00\x01\x00\x00\x00\x00";
const data = try writeTestData(std.testing.allocator, invalid_data ++ valid_data);
defer std.testing.allocator.free(data);
var metadata = try readData(std.testing.allocator, data);
defer metadata.deinit();
// the invalid atom should be skipped but the valid one should be read
try std.testing.expectEqual(@as(usize, 1), metadata.map.entries.items.len);
}
test "atom size too big" {
const res = readData(std.testing.allocator, ftyp_test_data ++ "\x11\x11\x11\x11\x20\x20");
try std.testing.expectError(error.EndOfStream, res);
}
test "data atom bad type" {
// 0xAB is not a valid data atom type, it should be skipped
const invalid_data = "\x00\x00\x00\x18aART\x00\x00\x00\x10data\xAB\x00\x00\x00\x00\x00\x00\x00";
const valid_data = "\x00\x00\x00\x18\xA9nam\x00\x00\x00\x10data\x00\x00\x00\x01\x00\x00\x00\x00";
const data = try writeTestData(std.testing.allocator, invalid_data ++ valid_data);
defer std.testing.allocator.free(data);
var metadata = try readData(std.testing.allocator, data);
defer metadata.deinit();
// the invalid atom should be skipped but the valid one should be read
try std.testing.expectEqual(@as(usize, 1), metadata.map.entries.items.len);
}
test "data atom bad well-known type" {
// 0xFFFFFF is not a valid data atom well-known type, it should be skipped
const invalid_data = "\x00\x00\x00\x18aART\x00\x00\x00\x10data\x00\xFF\xFF\xFF\x00\x00\x00\x00";
const valid_data = "\x00\x00\x00\x18\xA9nam\x00\x00\x00\x10data\x00\x00\x00\x01\x00\x00\x00\x00";
const data = try writeTestData(std.testing.allocator, invalid_data ++ valid_data);
defer std.testing.allocator.free(data);
var metadata = try readData(std.testing.allocator, data);
defer metadata.deinit();
// the invalid atom should be skipped but the valid one should be read
try std.testing.expectEqual(@as(usize, 1), metadata.map.entries.items.len);
}
test "extended size" {
const valid_data_with_extended_size = "\x00\x00\x00\x01\xA9nam\x00\x00\x00\x00\x00\x00\x00\x20\x00\x00\x00\x10data\x00\x00\x00\x01\x00\x00\x00\x00";
const data = try writeTestData(std.testing.allocator, valid_data_with_extended_size);
defer std.testing.allocator.free(data);
var metadata = try readData(std.testing.allocator, data);
defer metadata.deinit();
// the valid atom should be read
try std.testing.expectEqual(@as(usize, 1), metadata.map.entries.items.len);
}
test "extended size smaller than extended header len" {
// extended size is set as 0x09, which is larger than AtomHeader.len but smaller
// than the size of the header with the extended size included, so it
// should be rejected as too small
const data = "\x00\x00\x00\x01ftyp\x00\x00\x00\x00\x00\x00\x00\x09";
const res = readData(std.testing.allocator, data);
try std.testing.expectError(error.AtomSizeTooSmall, res);
}
const ftyp_test_data = "\x00\x00\x00\x08ftyp";
fn writeTestData(allocator: Allocator, metadata_payload: []const u8) ![]u8 {
var data = std.ArrayList(u8).init(allocator);
errdefer data.deinit();
const moov_len = AtomHeader.len;
const udta_len = AtomHeader.len;
const meta_len = AtomHeader.len + FullAtomHeader.len;
const ilst_len = AtomHeader.len;
var writer = data.writer();
try writer.writeAll(ftyp_test_data);
var atom_len: u32 = moov_len + udta_len + meta_len + ilst_len + @intCast(u32, metadata_payload.len);
try writer.writeIntBig(u32, atom_len);
try writer.writeAll("moov");
atom_len -= moov_len;
try writer.writeIntBig(u32, atom_len);
try writer.writeAll("udta");
atom_len -= udta_len;
try writer.writeIntBig(u32, atom_len);
try writer.writeAll("meta");
try writer.writeByte(1);
try writer.writeIntBig(u24, 0);
atom_len -= meta_len;
try writer.writeIntBig(u32, atom_len);
try writer.writeAll("ilst");
try writer.writeAll(metadata_payload);
return data.toOwnedSlice();
}
fn readData(allocator: Allocator, data: []const u8) !Metadata {
var stream_source = std.io.StreamSource{ .const_buffer = std.io.fixedBufferStream(data) };
return try read(allocator, stream_source.reader(), stream_source.seekableStream());
} | src/mp4.zig |
pub fn Register(comptime R: type) type {
return RegisterRW(R, R);
}
pub fn RegisterRW(comptime Read: type, comptime Write: type) type {
return struct {
raw_ptr: *volatile u32,
const Self = @This();
pub fn init(address: usize) Self {
return Self{ .raw_ptr = @intToPtr(*volatile u32, address) };
}
pub fn initRange(address: usize, comptime dim_increment: usize, comptime num_registers: usize) [num_registers]Self {
var registers: [num_registers]Self = undefined;
var i: usize = 0;
while (i < num_registers) : (i += 1) {
registers[i] = Self.init(address + (i * dim_increment));
}
return registers;
}
pub fn read(self: Self) Read {
return @bitCast(Read, self.raw_ptr.*);
}
pub fn write(self: Self, value: Write) void {
self.raw_ptr.* = @bitCast(u32, value);
}
pub fn modify(self: Self, new_value: anytype) void {
if (Read != Write) {
@compileError("Can't modify because read and write types for this register aren't the same.");
}
var old_value = self.read();
const info = @typeInfo(@TypeOf(new_value));
inline for (info.Struct.fields) |field| {
@field(old_value, field.name) = @field(new_value, field.name);
}
self.write(old_value);
}
pub fn read_raw(self: Self) u32 {
return self.raw_ptr.*;
}
pub fn write_raw(self: Self, value: u32) void {
self.raw_ptr.* = value;
}
pub fn default_read_value(self: Self) Read {
return Read{};
}
pub fn default_write_value(self: Self) Write {
return Write{};
}
};
}
pub fn RepeatedFields(comptime num_fields: usize, comptime field_name: []const u8, comptime T: type) type {
var info = @typeInfo(packed struct { f: T });
var fields: [num_fields]std.builtin.TypeInfo.StructField = undefined;
var field_ix: usize = 0;
while (field_ix < num_fields) : (field_ix += 1) {
var field = info.Struct.fields[0];
// awkward workaround for lack of comptime allocator
@setEvalBranchQuota(100000);
var field_ix_buffer: [field_name.len + 16]u8 = undefined;
var stream = std.io.FixedBufferStream([]u8){ .buffer = &field_ix_buffer, .pos = 0 };
std.fmt.format(stream.writer(), "{}{}", .{ field_name, field_ix }) catch unreachable;
field.name = stream.getWritten();
field.default_value = T.default_value;
fields[field_ix] = field;
}
// TODO this might not be safe to set
info.Struct.is_tuple = true;
info.Struct.fields = &fields;
return @Type(info);
} | registers.zig |
usingnamespace @import("bits.zig");
pub const SOCKET = *opaque {};
pub const INVALID_SOCKET = @intToPtr(SOCKET, ~@as(usize, 0));
pub const SOCKET_ERROR = -1;
pub const WSADESCRIPTION_LEN = 256;
pub const WSASYS_STATUS_LEN = 128;
pub const WSADATA = if (@sizeOf(usize) == @sizeOf(u64))
extern struct {
wVersion: WORD,
wHighVersion: WORD,
iMaxSockets: u16,
iMaxUdpDg: u16,
lpVendorInfo: *u8,
szDescription: [WSADESCRIPTION_LEN + 1]u8,
szSystemStatus: [WSASYS_STATUS_LEN + 1]u8,
}
else
extern struct {
wVersion: WORD,
wHighVersion: WORD,
szDescription: [WSADESCRIPTION_LEN + 1]u8,
szSystemStatus: [WSASYS_STATUS_LEN + 1]u8,
iMaxSockets: u16,
iMaxUdpDg: u16,
lpVendorInfo: *u8,
};
pub const MAX_PROTOCOL_CHAIN = 7;
pub const WSAPROTOCOLCHAIN = extern struct {
ChainLen: c_int,
ChainEntries: [MAX_PROTOCOL_CHAIN]DWORD,
};
pub const WSAPROTOCOL_LEN = 255;
pub const WSAPROTOCOL_INFOA = extern struct {
dwServiceFlags1: DWORD,
dwServiceFlags2: DWORD,
dwServiceFlags3: DWORD,
dwServiceFlags4: DWORD,
dwProviderFlags: DWORD,
ProviderId: GUID,
dwCatalogEntryId: DWORD,
ProtocolChain: WSAPROTOCOLCHAIN,
iVersion: c_int,
iAddressFamily: c_int,
iMaxSockAddr: c_int,
iMinSockAddr: c_int,
iSocketType: c_int,
iProtocol: c_int,
iProtocolMaxOffset: c_int,
iNetworkByteOrder: c_int,
iSecurityScheme: c_int,
dwMessageSize: DWORD,
dwProviderReserved: DWORD,
szProtocol: [WSAPROTOCOL_LEN + 1]CHAR,
};
pub const WSAPROTOCOL_INFOW = extern struct {
dwServiceFlags1: DWORD,
dwServiceFlags2: DWORD,
dwServiceFlags3: DWORD,
dwServiceFlags4: DWORD,
dwProviderFlags: DWORD,
ProviderId: GUID,
dwCatalogEntryId: DWORD,
ProtocolChain: WSAPROTOCOLCHAIN,
iVersion: c_int,
iAddressFamily: c_int,
iMaxSockAddr: c_int,
iMinSockAddr: c_int,
iSocketType: c_int,
iProtocol: c_int,
iProtocolMaxOffset: c_int,
iNetworkByteOrder: c_int,
iSecurityScheme: c_int,
dwMessageSize: DWORD,
dwProviderReserved: DWORD,
szProtocol: [WSAPROTOCOL_LEN + 1]WCHAR,
};
pub const GROUP = u32;
pub const SG_UNCONSTRAINED_GROUP = 0x1;
pub const SG_CONSTRAINED_GROUP = 0x2;
pub const WSA_FLAG_OVERLAPPED = 0x01;
pub const WSA_FLAG_MULTIPOINT_C_ROOT = 0x02;
pub const WSA_FLAG_MULTIPOINT_C_LEAF = 0x04;
pub const WSA_FLAG_MULTIPOINT_D_ROOT = 0x08;
pub const WSA_FLAG_MULTIPOINT_D_LEAF = 0x10;
pub const WSA_FLAG_ACCESS_SYSTEM_SECURITY = 0x40;
pub const WSA_FLAG_NO_HANDLE_INHERIT = 0x80;
pub const WSAEVENT = HANDLE;
pub const WSAOVERLAPPED = extern struct {
Internal: DWORD,
InternalHigh: DWORD,
Offset: DWORD,
OffsetHigh: DWORD,
hEvent: ?WSAEVENT,
};
pub const WSAOVERLAPPED_COMPLETION_ROUTINE = fn (dwError: DWORD, cbTransferred: DWORD, lpOverlapped: *WSAOVERLAPPED, dwFlags: DWORD) callconv(.C) void;
pub const ADDRESS_FAMILY = u16;
// Microsoft use the signed c_int for this, but it should never be negative
pub const socklen_t = u32;
pub const AF_UNSPEC = 0;
pub const AF_UNIX = 1;
pub const AF_INET = 2;
pub const AF_IMPLINK = 3;
pub const AF_PUP = 4;
pub const AF_CHAOS = 5;
pub const AF_NS = 6;
pub const AF_IPX = AF_NS;
pub const AF_ISO = 7;
pub const AF_OSI = AF_ISO;
pub const AF_ECMA = 8;
pub const AF_DATAKIT = 9;
pub const AF_CCITT = 10;
pub const AF_SNA = 11;
pub const AF_DECnet = 12;
pub const AF_DLI = 13;
pub const AF_LAT = 14;
pub const AF_HYLINK = 15;
pub const AF_APPLETALK = 16;
pub const AF_NETBIOS = 17;
pub const AF_VOICEVIEW = 18;
pub const AF_FIREFOX = 19;
pub const AF_UNKNOWN1 = 20;
pub const AF_BAN = 21;
pub const AF_ATM = 22;
pub const AF_INET6 = 23;
pub const AF_CLUSTER = 24;
pub const AF_12844 = 25;
pub const AF_IRDA = 26;
pub const AF_NETDES = 28;
pub const AF_TCNPROCESS = 29;
pub const AF_TCNMESSAGE = 30;
pub const AF_ICLFXBM = 31;
pub const AF_BTH = 32;
pub const AF_MAX = 33;
pub const SOCK_STREAM = 1;
pub const SOCK_DGRAM = 2;
pub const SOCK_RAW = 3;
pub const SOCK_RDM = 4;
pub const SOCK_SEQPACKET = 5;
pub const IPPROTO_ICMP = 1;
pub const IPPROTO_IGMP = 2;
pub const BTHPROTO_RFCOMM = 3;
pub const IPPROTO_TCP = 6;
pub const IPPROTO_UDP = 17;
pub const IPPROTO_ICMPV6 = 58;
pub const IPPROTO_RM = 113;
pub const AI_PASSIVE = 0x00001;
pub const AI_CANONNAME = 0x00002;
pub const AI_NUMERICHOST = 0x00004;
pub const AI_NUMERICSERV = 0x00008;
pub const AI_ADDRCONFIG = 0x00400;
pub const AI_V4MAPPED = 0x00800;
pub const AI_NON_AUTHORITATIVE = 0x04000;
pub const AI_SECURE = 0x08000;
pub const AI_RETURN_PREFERRED_NAMES = 0x10000;
pub const AI_DISABLE_IDN_ENCODING = 0x80000;
pub const FIONBIO = -2147195266;
pub const sockaddr = extern struct {
family: ADDRESS_FAMILY,
data: [14]u8,
};
pub const addrinfo = extern struct {
flags: i32,
family: i32,
socktype: i32,
protocol: i32,
addrlen: usize,
canonname: ?[*:0]u8,
addr: ?*sockaddr,
next: ?*addrinfo,
};
/// IPv4 socket address
pub const sockaddr_in = extern struct {
family: ADDRESS_FAMILY = AF_INET,
port: USHORT,
addr: u32,
zero: [8]u8 = [8]u8{ 0, 0, 0, 0, 0, 0, 0, 0 },
};
/// IPv6 socket address
pub const sockaddr_in6 = extern struct {
family: ADDRESS_FAMILY = AF_INET6,
port: USHORT,
flowinfo: u32,
addr: [16]u8,
scope_id: u32,
};
/// UNIX domain socket address
pub const sockaddr_un = extern struct {
family: ADDRESS_FAMILY = AF_UNIX,
path: [108]u8,
};
pub const WSABUF = extern struct {
len: ULONG,
buf: [*]u8,
};
pub const WSAMSG = extern struct {
name: *const sockaddr,
namelen: INT,
lpBuffers: [*]WSABUF,
dwBufferCount: DWORD,
Control: WSABUF,
dwFlags: DWORD,
};
pub const pollfd = extern struct {
fd: SOCKET,
events: SHORT,
revents: SHORT,
};
// Event flag definitions for WSAPoll().
pub const POLLRDNORM = 0x0100;
pub const POLLRDBAND = 0x0200;
pub const POLLIN = (POLLRDNORM | POLLRDBAND);
pub const POLLPRI = 0x0400;
pub const POLLWRNORM = 0x0010;
pub const POLLOUT = (POLLWRNORM);
pub const POLLWRBAND = 0x0020;
pub const POLLERR = 0x0001;
pub const POLLHUP = 0x0002;
pub const POLLNVAL = 0x0004;
// https://docs.microsoft.com/en-au/windows/win32/winsock/windows-sockets-error-codes-2
pub const WinsockError = extern enum(u16) {
/// Specified event object handle is invalid.
/// An application attempts to use an event object, but the specified handle is not valid.
WSA_INVALID_HANDLE = 6,
/// Insufficient memory available.
/// An application used a Windows Sockets function that directly maps to a Windows function.
/// The Windows function is indicating a lack of required memory resources.
WSA_NOT_ENOUGH_MEMORY = 8,
/// One or more parameters are invalid.
/// An application used a Windows Sockets function which directly maps to a Windows function.
/// The Windows function is indicating a problem with one or more parameters.
WSA_INVALID_PARAMETER = 87,
/// Overlapped operation aborted.
/// An overlapped operation was canceled due to the closure of the socket, or the execution of the SIO_FLUSH command in WSAIoctl.
WSA_OPERATION_ABORTED = 995,
/// Overlapped I/O event object not in signaled state.
/// The application has tried to determine the status of an overlapped operation which is not yet completed.
/// Applications that use WSAGetOverlappedResult (with the fWait flag set to FALSE) in a polling mode to determine when an overlapped operation has completed, get this error code until the operation is complete.
WSA_IO_INCOMPLETE = 996,
/// The application has initiated an overlapped operation that cannot be completed immediately.
/// A completion indication will be given later when the operation has been completed.
WSA_IO_PENDING = 997,
/// Interrupted function call.
/// A blocking operation was interrupted by a call to WSACancelBlockingCall.
WSAEINTR = 10004,
/// File handle is not valid.
/// The file handle supplied is not valid.
WSAEBADF = 10009,
/// Permission denied.
/// An attempt was made to access a socket in a way forbidden by its access permissions.
/// An example is using a broadcast address for sendto without broadcast permission being set using setsockopt(SO_BROADCAST).
/// Another possible reason for the WSAEACCES error is that when the bind function is called (on Windows NT 4.0 with SP4 and later), another application, service, or kernel mode driver is bound to the same address with exclusive access.
/// Such exclusive access is a new feature of Windows NT 4.0 with SP4 and later, and is implemented by using the SO_EXCLUSIVEADDRUSE option.
WSAEACCES = 10013,
/// Bad address.
/// The system detected an invalid pointer address in attempting to use a pointer argument of a call.
/// This error occurs if an application passes an invalid pointer value, or if the length of the buffer is too small.
/// For instance, if the length of an argument, which is a sockaddr structure, is smaller than the sizeof(sockaddr).
WSAEFAULT = 10014,
/// Invalid argument.
/// Some invalid argument was supplied (for example, specifying an invalid level to the setsockopt function).
/// In some instances, it also refers to the current state of the socket—for instance, calling accept on a socket that is not listening.
WSAEINVAL = 10022,
/// Too many open files.
/// Too many open sockets. Each implementation may have a maximum number of socket handles available, either globally, per process, or per thread.
WSAEMFILE = 10024,
/// Resource temporarily unavailable.
/// This error is returned from operations on nonblocking sockets that cannot be completed immediately, for example recv when no data is queued to be read from the socket.
/// It is a nonfatal error, and the operation should be retried later.
/// It is normal for WSAEWOULDBLOCK to be reported as the result from calling connect on a nonblocking SOCK_STREAM socket, since some time must elapse for the connection to be established.
WSAEWOULDBLOCK = 10035,
/// Operation now in progress.
/// A blocking operation is currently executing.
/// Windows Sockets only allows a single blocking operation—per- task or thread—to be outstanding, and if any other function call is made (whether or not it references that or any other socket) the function fails with the WSAEINPROGRESS error.
WSAEINPROGRESS = 10036,
/// Operation already in progress.
/// An operation was attempted on a nonblocking socket with an operation already in progress—that is, calling connect a second time on a nonblocking socket that is already connecting, or canceling an asynchronous request (WSAAsyncGetXbyY) that has already been canceled or completed.
WSAEALREADY = 10037,
/// Socket operation on nonsocket.
/// An operation was attempted on something that is not a socket.
/// Either the socket handle parameter did not reference a valid socket, or for select, a member of an fd_set was not valid.
WSAENOTSOCK = 10038,
/// Destination address required.
/// A required address was omitted from an operation on a socket.
/// For example, this error is returned if sendto is called with the remote address of ADDR_ANY.
WSAEDESTADDRREQ = 10039,
/// Message too long.
/// A message sent on a datagram socket was larger than the internal message buffer or some other network limit, or the buffer used to receive a datagram was smaller than the datagram itself.
WSAEMSGSIZE = 10040,
/// Protocol wrong type for socket.
/// A protocol was specified in the socket function call that does not support the semantics of the socket type requested.
/// For example, the ARPA Internet UDP protocol cannot be specified with a socket type of SOCK_STREAM.
WSAEPROTOTYPE = 10041,
/// Bad protocol option.
/// An unknown, invalid or unsupported option or level was specified in a getsockopt or setsockopt call.
WSAENOPROTOOPT = 10042,
/// Protocol not supported.
/// The requested protocol has not been configured into the system, or no implementation for it exists.
/// For example, a socket call requests a SOCK_DGRAM socket, but specifies a stream protocol.
WSAEPROTONOSUPPORT = 10043,
/// Socket type not supported.
/// The support for the specified socket type does not exist in this address family.
/// For example, the optional type SOCK_RAW might be selected in a socket call, and the implementation does not support SOCK_RAW sockets at all.
WSAESOCKTNOSUPPORT = 10044,
/// Operation not supported.
/// The attempted operation is not supported for the type of object referenced.
/// Usually this occurs when a socket descriptor to a socket that cannot support this operation is trying to accept a connection on a datagram socket.
WSAEOPNOTSUPP = 10045,
/// Protocol family not supported.
/// The protocol family has not been configured into the system or no implementation for it exists.
/// This message has a slightly different meaning from WSAEAFNOSUPPORT.
/// However, it is interchangeable in most cases, and all Windows Sockets functions that return one of these messages also specify WSAEAFNOSUPPORT.
WSAEPFNOSUPPORT = 10046,
/// Address family not supported by protocol family.
/// An address incompatible with the requested protocol was used.
/// All sockets are created with an associated address family (that is, AF_INET for Internet Protocols) and a generic protocol type (that is, SOCK_STREAM).
/// This error is returned if an incorrect protocol is explicitly requested in the socket call, or if an address of the wrong family is used for a socket, for example, in sendto.
WSAEAFNOSUPPORT = 10047,
/// Address already in use.
/// Typically, only one usage of each socket address (protocol/IP address/port) is permitted.
/// This error occurs if an application attempts to bind a socket to an IP address/port that has already been used for an existing socket, or a socket that was not closed properly, or one that is still in the process of closing.
/// For server applications that need to bind multiple sockets to the same port number, consider using setsockopt (SO_REUSEADDR).
/// Client applications usually need not call bind at all—connect chooses an unused port automatically.
/// When bind is called with a wildcard address (involving ADDR_ANY), a WSAEADDRINUSE error could be delayed until the specific address is committed.
/// This could happen with a call to another function later, including connect, listen, WSAConnect, or WSAJoinLeaf.
WSAEADDRINUSE = 10048,
/// Cannot assign requested address.
/// The requested address is not valid in its context.
/// This normally results from an attempt to bind to an address that is not valid for the local computer.
/// This can also result from connect, sendto, WSAConnect, WSAJoinLeaf, or WSASendTo when the remote address or port is not valid for a remote computer (for example, address or port 0).
WSAEADDRNOTAVAIL = 10049,
/// Network is down.
/// A socket operation encountered a dead network.
/// This could indicate a serious failure of the network system (that is, the protocol stack that the Windows Sockets DLL runs over), the network interface, or the local network itself.
WSAENETDOWN = 10050,
/// Network is unreachable.
/// A socket operation was attempted to an unreachable network.
/// This usually means the local software knows no route to reach the remote host.
WSAENETUNREACH = 10051,
/// Network dropped connection on reset.
/// The connection has been broken due to keep-alive activity detecting a failure while the operation was in progress.
/// It can also be returned by setsockopt if an attempt is made to set SO_KEEPALIVE on a connection that has already failed.
WSAENETRESET = 10052,
/// Software caused connection abort.
/// An established connection was aborted by the software in your host computer, possibly due to a data transmission time-out or protocol error.
WSAECONNABORTED = 10053,
/// Connection reset by peer.
/// An existing connection was forcibly closed by the remote host.
/// This normally results if the peer application on the remote host is suddenly stopped, the host is rebooted, the host or remote network interface is disabled, or the remote host uses a hard close (see setsockopt for more information on the SO_LINGER option on the remote socket).
/// This error may also result if a connection was broken due to keep-alive activity detecting a failure while one or more operations are in progress.
/// Operations that were in progress fail with WSAENETRESET. Subsequent operations fail with WSAECONNRESET.
WSAECONNRESET = 10054,
/// No buffer space available.
/// An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full.
WSAENOBUFS = 10055,
/// Socket is already connected.
/// A connect request was made on an already-connected socket.
/// Some implementations also return this error if sendto is called on a connected SOCK_DGRAM socket (for SOCK_STREAM sockets, the to parameter in sendto is ignored) although other implementations treat this as a legal occurrence.
WSAEISCONN = 10056,
/// Socket is not connected.
/// A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using sendto) no address was supplied.
/// Any other type of operation might also return this error—for example, setsockopt setting SO_KEEPALIVE if the connection has been reset.
WSAENOTCONN = 10057,
/// Cannot send after socket shutdown.
/// A request to send or receive data was disallowed because the socket had already been shut down in that direction with a previous shutdown call.
/// By calling shutdown a partial close of a socket is requested, which is a signal that sending or receiving, or both have been discontinued.
WSAESHUTDOWN = 10058,
/// Too many references.
/// Too many references to some kernel object.
WSAETOOMANYREFS = 10059,
/// Connection timed out.
/// A connection attempt failed because the connected party did not properly respond after a period of time, or the established connection failed because the connected host has failed to respond.
WSAETIMEDOUT = 10060,
/// Connection refused.
/// No connection could be made because the target computer actively refused it.
/// This usually results from trying to connect to a service that is inactive on the foreign host—that is, one with no server application running.
WSAECONNREFUSED = 10061,
/// Cannot translate name.
/// Cannot translate a name.
WSAELOOP = 10062,
/// Name too long.
/// A name component or a name was too long.
WSAENAMETOOLONG = 10063,
/// Host is down.
/// A socket operation failed because the destination host is down. A socket operation encountered a dead host.
/// Networking activity on the local host has not been initiated.
/// These conditions are more likely to be indicated by the error WSAETIMEDOUT.
WSAEHOSTDOWN = 10064,
/// No route to host.
/// A socket operation was attempted to an unreachable host. See WSAENETUNREACH.
WSAEHOSTUNREACH = 10065,
/// Directory not empty.
/// Cannot remove a directory that is not empty.
WSAENOTEMPTY = 10066,
/// Too many processes.
/// A Windows Sockets implementation may have a limit on the number of applications that can use it simultaneously.
/// WSAStartup may fail with this error if the limit has been reached.
WSAEPROCLIM = 10067,
/// User quota exceeded.
/// Ran out of user quota.
WSAEUSERS = 10068,
/// Disk quota exceeded.
/// Ran out of disk quota.
WSAEDQUOT = 10069,
/// Stale file handle reference.
/// The file handle reference is no longer available.
WSAESTALE = 10070,
/// Item is remote.
/// The item is not available locally.
WSAEREMOTE = 10071,
/// Network subsystem is unavailable.
/// This error is returned by WSAStartup if the Windows Sockets implementation cannot function at this time because the underlying system it uses to provide network services is currently unavailable.
/// Users should check:
/// - That the appropriate Windows Sockets DLL file is in the current path.
/// - That they are not trying to use more than one Windows Sockets implementation simultaneously.
/// - If there is more than one Winsock DLL on your system, be sure the first one in the path is appropriate for the network subsystem currently loaded.
/// - The Windows Sockets implementation documentation to be sure all necessary components are currently installed and configured correctly.
WSASYSNOTREADY = 10091,
/// Winsock.dll version out of range.
/// The current Windows Sockets implementation does not support the Windows Sockets specification version requested by the application.
/// Check that no old Windows Sockets DLL files are being accessed.
WSAVERNOTSUPPORTED = 10092,
/// Successful WSAStartup not yet performed.
/// Either the application has not called WSAStartup or WSAStartup failed.
/// The application may be accessing a socket that the current active task does not own (that is, trying to share a socket between tasks), or WSACleanup has been called too many times.
WSANOTINITIALISED = 10093,
/// Graceful shutdown in progress.
/// Returned by WSARecv and WSARecvFrom to indicate that the remote party has initiated a graceful shutdown sequence.
WSAEDISCON = 10101,
/// No more results.
/// No more results can be returned by the WSALookupServiceNext function.
WSAENOMORE = 10102,
/// Call has been canceled.
/// A call to the WSALookupServiceEnd function was made while this call was still processing. The call has been canceled.
WSAECANCELLED = 10103,
/// Procedure call table is invalid.
/// The service provider procedure call table is invalid.
/// A service provider returned a bogus procedure table to Ws2_32.dll.
/// This is usually caused by one or more of the function pointers being NULL.
WSAEINVALIDPROCTABLE = 10104,
/// Service provider is invalid.
/// The requested service provider is invalid.
/// This error is returned by the WSCGetProviderInfo and WSCGetProviderInfo32 functions if the protocol entry specified could not be found.
/// This error is also returned if the service provider returned a version number other than 2.0.
WSAEINVALIDPROVIDER = 10105,
/// Service provider failed to initialize.
/// The requested service provider could not be loaded or initialized.
/// This error is returned if either a service provider's DLL could not be loaded (LoadLibrary failed) or the provider's WSPStartup or NSPStartup function failed.
WSAEPROVIDERFAILEDINIT = 10106,
/// System call failure.
/// A system call that should never fail has failed.
/// This is a generic error code, returned under various conditions.
/// Returned when a system call that should never fail does fail.
/// For example, if a call to WaitForMultipleEvents fails or one of the registry functions fails trying to manipulate the protocol/namespace catalogs.
/// Returned when a provider does not return SUCCESS and does not provide an extended error code.
/// Can indicate a service provider implementation error.
WSASYSCALLFAILURE = 10107,
/// Service not found.
/// No such service is known. The service cannot be found in the specified name space.
WSASERVICE_NOT_FOUND = 10108,
/// Class type not found.
/// The specified class was not found.
WSATYPE_NOT_FOUND = 10109,
/// No more results.
/// No more results can be returned by the WSALookupServiceNext function.
WSA_E_NO_MORE = 10110,
/// Call was canceled.
/// A call to the WSALookupServiceEnd function was made while this call was still processing. The call has been canceled.
WSA_E_CANCELLED = 10111,
/// Database query was refused.
/// A database query failed because it was actively refused.
WSAEREFUSED = 10112,
/// Host not found.
/// No such host is known. The name is not an official host name or alias, or it cannot be found in the database(s) being queried.
/// This error may also be returned for protocol and service queries, and means that the specified name could not be found in the relevant database.
WSAHOST_NOT_FOUND = 11001,
/// Nonauthoritative host not found.
/// This is usually a temporary error during host name resolution and means that the local server did not receive a response from an authoritative server. A retry at some time later may be successful.
WSATRY_AGAIN = 11002,
/// This is a nonrecoverable error.
/// This indicates that some sort of nonrecoverable error occurred during a database lookup.
/// This may be because the database files (for example, BSD-compatible HOSTS, SERVICES, or PROTOCOLS files) could not be found, or a DNS request was returned by the server with a severe error.
WSANO_RECOVERY = 11003,
/// Valid name, no data record of requested type.
/// The requested name is valid and was found in the database, but it does not have the correct associated data being resolved for.
/// The usual example for this is a host name-to-address translation attempt (using gethostbyname or WSAAsyncGetHostByName) which uses the DNS (Domain Name Server).
/// An MX record is returned but no A record—indicating the host itself exists, but is not directly reachable.
WSANO_DATA = 11004,
/// QoS receivers.
/// At least one QoS reserve has arrived.
WSA_QOS_RECEIVERS = 11005,
/// QoS senders.
/// At least one QoS send path has arrived.
WSA_QOS_SENDERS = 11006,
/// No QoS senders.
/// There are no QoS senders.
WSA_QOS_NO_SENDERS = 11007,
/// QoS no receivers.
/// There are no QoS receivers.
WSA_QOS_NO_RECEIVERS = 11008,
/// QoS request confirmed.
/// The QoS reserve request has been confirmed.
WSA_QOS_REQUEST_CONFIRMED = 11009,
/// QoS admission error.
/// A QoS error occurred due to lack of resources.
WSA_QOS_ADMISSION_FAILURE = 11010,
/// QoS policy failure.
/// The QoS request was rejected because the policy system couldn't allocate the requested resource within the existing policy.
WSA_QOS_POLICY_FAILURE = 11011,
/// QoS bad style.
/// An unknown or conflicting QoS style was encountered.
WSA_QOS_BAD_STYLE = 11012,
/// QoS bad object.
/// A problem was encountered with some part of the filterspec or the provider-specific buffer in general.
WSA_QOS_BAD_OBJECT = 11013,
/// QoS traffic control error.
/// An error with the underlying traffic control (TC) API as the generic QoS request was converted for local enforcement by the TC API.
/// This could be due to an out of memory error or to an internal QoS provider error.
WSA_QOS_TRAFFIC_CTRL_ERROR = 11014,
/// QoS generic error.
/// A general QoS error.
WSA_QOS_GENERIC_ERROR = 11015,
/// QoS service type error.
/// An invalid or unrecognized service type was found in the QoS flowspec.
WSA_QOS_ESERVICETYPE = 11016,
/// QoS flowspec error.
/// An invalid or inconsistent flowspec was found in the QOS structure.
WSA_QOS_EFLOWSPEC = 11017,
/// Invalid QoS provider buffer.
/// An invalid QoS provider-specific buffer.
WSA_QOS_EPROVSPECBUF = 11018,
/// Invalid QoS filter style.
/// An invalid QoS filter style was used.
WSA_QOS_EFILTERSTYLE = 11019,
/// Invalid QoS filter type.
/// An invalid QoS filter type was used.
WSA_QOS_EFILTERTYPE = 11020,
/// Incorrect QoS filter count.
/// An incorrect number of QoS FILTERSPECs were specified in the FLOWDESCRIPTOR.
WSA_QOS_EFILTERCOUNT = 11021,
/// Invalid QoS object length.
/// An object with an invalid ObjectLength field was specified in the QoS provider-specific buffer.
WSA_QOS_EOBJLENGTH = 11022,
/// Incorrect QoS flow count.
/// An incorrect number of flow descriptors was specified in the QoS structure.
WSA_QOS_EFLOWCOUNT = 11023,
/// Unrecognized QoS object.
/// An unrecognized object was found in the QoS provider-specific buffer.
WSA_QOS_EUNKOWNPSOBJ = 11024,
/// Invalid QoS policy object.
/// An invalid policy object was found in the QoS provider-specific buffer.
WSA_QOS_EPOLICYOBJ = 11025,
/// Invalid QoS flow descriptor.
/// An invalid QoS flow descriptor was found in the flow descriptor list.
WSA_QOS_EFLOWDESC = 11026,
/// Invalid QoS provider-specific flowspec.
/// An invalid or inconsistent flowspec was found in the QoS provider-specific buffer.
WSA_QOS_EPSFLOWSPEC = 11027,
/// Invalid QoS provider-specific filterspec.
/// An invalid FILTERSPEC was found in the QoS provider-specific buffer.
WSA_QOS_EPSFILTERSPEC = 11028,
/// Invalid QoS shape discard mode object.
/// An invalid shape discard mode object was found in the QoS provider-specific buffer.
WSA_QOS_ESDMODEOBJ = 11029,
/// Invalid QoS shaping rate object.
/// An invalid shaping rate object was found in the QoS provider-specific buffer.
WSA_QOS_ESHAPERATEOBJ = 11030,
/// Reserved policy QoS element type.
/// A reserved policy element was found in the QoS provider-specific buffer.
WSA_QOS_RESERVED_PETYPE = 11031,
_,
};
/// no parameters
const IOC_VOID = 0x80000000;
/// copy out parameters
const IOC_OUT = 0x40000000;
/// copy in parameters
const IOC_IN = 0x80000000;
/// The IOCTL is a generic Windows Sockets 2 IOCTL code. New IOCTL codes defined for Windows Sockets 2 will have T == 1.
const IOC_WS2 = 0x08000000;
pub const SIO_BASE_HANDLE = IOC_OUT | IOC_WS2 | 34;
pub const SOL_SOCKET = 0xffff;
pub const SO_DEBUG = 0x0001;
pub const SO_ACCEPTCONN = 0x0002;
pub const SO_REUSEADDR = 0x0004;
pub const SO_KEEPALIVE = 0x0008;
pub const SO_DONTROUTE = 0x0010;
pub const SO_BROADCAST = 0x0020;
pub const SO_USELOOPBACK = 0x0040;
pub const SO_LINGER = 0x0080;
pub const SO_OOBINLINE = 0x0100;
pub const SO_DONTLINGER = ~@as(u32, SO_LINGER);
pub const SO_EXCLUSIVEADDRUSE = ~@as(u32, SO_REUSEADDR);
pub const SO_SNDBUF = 0x1001;
pub const SO_RCVBUF = 0x1002;
pub const SO_SNDLOWAT = 0x1003;
pub const SO_RCVLOWAT = 0x1004;
pub const SO_SNDTIMEO = 0x1005;
pub const SO_RCVTIMEO = 0x1006;
pub const SO_ERROR = 0x1007;
pub const SO_TYPE = 0x1008;
pub const SO_GROUP_ID = 0x2001;
pub const SO_GROUP_PRIORITY = 0x2002;
pub const SO_MAX_MSG_SIZE = 0x2003;
pub const SO_PROTOCOL_INFOA = 0x2004;
pub const SO_PROTOCOL_INFOW = 0x2005;
pub const PVD_CONFIG = 0x3001;
pub const SO_CONDITIONAL_ACCEPT = 0x3002;
pub const TCP_NODELAY = 0x0001;
pub extern "ws2_32" fn WSAStartup(
wVersionRequired: WORD,
lpWSAData: *WSADATA,
) callconv(WINAPI) c_int;
pub extern "ws2_32" fn WSACleanup() callconv(WINAPI) c_int;
pub extern "ws2_32" fn WSAGetLastError() callconv(WINAPI) WinsockError;
pub extern "ws2_32" fn WSASocketA(
af: c_int,
type: c_int,
protocol: c_int,
lpProtocolInfo: ?*WSAPROTOCOL_INFOA,
g: GROUP,
dwFlags: DWORD,
) callconv(WINAPI) SOCKET;
pub extern "ws2_32" fn WSASocketW(
af: c_int,
type: c_int,
protocol: c_int,
lpProtocolInfo: ?*WSAPROTOCOL_INFOW,
g: GROUP,
dwFlags: DWORD,
) callconv(WINAPI) SOCKET;
pub extern "ws2_32" fn closesocket(s: SOCKET) callconv(WINAPI) c_int;
pub extern "ws2_32" fn WSAIoctl(
s: SOCKET,
dwIoControlCode: DWORD,
lpvInBuffer: ?*const c_void,
cbInBuffer: DWORD,
lpvOutBuffer: ?LPVOID,
cbOutBuffer: DWORD,
lpcbBytesReturned: LPDWORD,
lpOverlapped: ?*WSAOVERLAPPED,
lpCompletionRoutine: ?WSAOVERLAPPED_COMPLETION_ROUTINE,
) callconv(WINAPI) c_int;
pub extern "ws2_32" fn accept(
s: SOCKET,
addr: ?*sockaddr,
addrlen: ?*c_int,
) callconv(WINAPI) SOCKET;
pub extern "ws2_32" fn bind(
s: SOCKET,
addr: ?*const sockaddr,
addrlen: c_int,
) callconv(WINAPI) c_int;
pub extern "ws2_32" fn connect(
s: SOCKET,
name: *const sockaddr,
namelen: c_int,
) callconv(WINAPI) c_int;
pub extern "ws2_32" fn listen(
s: SOCKET,
backlog: c_int,
) callconv(WINAPI) c_int;
pub extern "ws2_32" fn WSARecv(
s: SOCKET,
lpBuffers: [*]const WSABUF,
dwBufferCount: DWORD,
lpNumberOfBytesRecvd: ?*DWORD,
lpFlags: *DWORD,
lpOverlapped: ?*WSAOVERLAPPED,
lpCompletionRoutine: ?WSAOVERLAPPED_COMPLETION_ROUTINE,
) callconv(WINAPI) c_int;
pub extern "ws2_32" fn WSARecvFrom(
s: SOCKET,
lpBuffers: [*]const WSABUF,
dwBufferCount: DWORD,
lpNumberOfBytesRecvd: ?*DWORD,
lpFlags: *DWORD,
lpFrom: ?*sockaddr,
lpFromlen: ?*socklen_t,
lpOverlapped: ?*WSAOVERLAPPED,
lpCompletionRoutine: ?WSAOVERLAPPED_COMPLETION_ROUTINE,
) callconv(WINAPI) c_int;
pub extern "ws2_32" fn WSASend(
s: SOCKET,
lpBuffers: [*]WSABUF,
dwBufferCount: DWORD,
lpNumberOfBytesSent: ?*DWORD,
dwFlags: DWORD,
lpOverlapped: ?*WSAOVERLAPPED,
lpCompletionRoutine: ?WSAOVERLAPPED_COMPLETION_ROUTINE,
) callconv(WINAPI) c_int;
pub extern "ws2_32" fn WSASendTo(
s: SOCKET,
lpBuffers: [*]WSABUF,
dwBufferCount: DWORD,
lpNumberOfBytesSent: ?*DWORD,
dwFlags: DWORD,
lpTo: ?*const sockaddr,
iTolen: c_int,
lpOverlapped: ?*WSAOVERLAPPED,
lpCompletionRoutine: ?WSAOVERLAPPED_COMPLETION_ROUTINE,
) callconv(WINAPI) c_int;
pub extern "ws2_32" fn WSAPoll(
fdArray: [*]pollfd,
fds: c_ulong,
timeout: c_int,
) callconv(WINAPI) c_int;
pub extern "ws2_32" fn getaddrinfo(
pNodeName: [*:0]const u8,
pServiceName: [*:0]const u8,
pHints: *const addrinfo,
ppResult: **addrinfo,
) callconv(WINAPI) i32;
pub extern "ws2_32" fn freeaddrinfo(
pAddrInfo: *addrinfo,
) callconv(WINAPI) void;
pub extern "ws2_32" fn ioctlsocket(
s: SOCKET,
cmd: c_long,
argp: *c_ulong,
) callconv(WINAPI) c_int;
pub extern "ws2_32" fn getsockname(
s: SOCKET,
name: *sockaddr,
namelen: *c_int,
) callconv(WINAPI) c_int;
pub extern "ws2_32" fn setsockopt(
s: SOCKET,
level: u32,
optname: u32,
optval: ?*const c_void,
optlen: socklen_t,
) callconv(WINAPI) c_int;
pub extern "ws2_32" fn shutdown(
s: SOCKET,
how: c_int,
) callconv(WINAPI) c_int; | lib/std/os/windows/ws2_32.zig |
const std = @import("std");
const mem = std.mem;
const primes = [_]u64{
0xa0761d6478bd642f,
0xe7037ed1a0b428db,
0x8ebc6af09c88c6e3,
0x589965cc75374cc3,
0x1d8e4e27c47d124f,
};
fn read_bytes(comptime bytes: u8, data: []const u8) u64 {
return mem.readVarInt(u64, data[0..bytes], .Little);
}
fn read_8bytes_swapped(data: []const u8) u64 {
return (read_bytes(4, data) << 32 | read_bytes(4, data[4..]));
}
fn mum(a: u64, b: u64) u64 {
var r = std.math.mulWide(u64, a, b);
r = (r >> 64) ^ r;
return @truncate(u64, r);
}
fn mix0(a: u64, b: u64, seed: u64) u64 {
return mum(a ^ seed ^ primes[0], b ^ seed ^ primes[1]);
}
fn mix1(a: u64, b: u64, seed: u64) u64 {
return mum(a ^ seed ^ primes[2], b ^ seed ^ primes[3]);
}
pub const Wyhash = struct {
seed: u64,
msg_len: usize,
pub fn init(seed: u64) Wyhash {
return Wyhash{
.seed = seed,
.msg_len = 0,
};
}
fn round(self: *Wyhash, b: []const u8) void {
std.debug.assert(b.len == 32);
self.seed = mix0(
read_bytes(8, b[0..]),
read_bytes(8, b[8..]),
self.seed,
) ^ mix1(
read_bytes(8, b[16..]),
read_bytes(8, b[24..]),
self.seed,
);
}
fn partial(self: *Wyhash, b: []const u8) void {
const rem_key = b;
const rem_len = b.len;
var seed = self.seed;
seed = switch (@intCast(u5, rem_len)) {
0 => seed,
1 => mix0(read_bytes(1, rem_key), primes[4], seed),
2 => mix0(read_bytes(2, rem_key), primes[4], seed),
3 => mix0((read_bytes(2, rem_key) << 8) | read_bytes(1, rem_key[2..]), primes[4], seed),
4 => mix0(read_bytes(4, rem_key), primes[4], seed),
5 => mix0((read_bytes(4, rem_key) << 8) | read_bytes(1, rem_key[4..]), primes[4], seed),
6 => mix0((read_bytes(4, rem_key) << 16) | read_bytes(2, rem_key[4..]), primes[4], seed),
7 => mix0((read_bytes(4, rem_key) << 24) | (read_bytes(2, rem_key[4..]) << 8) | read_bytes(1, rem_key[6..]), primes[4], seed),
8 => mix0(read_8bytes_swapped(rem_key), primes[4], seed),
9 => mix0(read_8bytes_swapped(rem_key), read_bytes(1, rem_key[8..]), seed),
10 => mix0(read_8bytes_swapped(rem_key), read_bytes(2, rem_key[8..]), seed),
11 => mix0(read_8bytes_swapped(rem_key), (read_bytes(2, rem_key[8..]) << 8) | read_bytes(1, rem_key[10..]), seed),
12 => mix0(read_8bytes_swapped(rem_key), read_bytes(4, rem_key[8..]), seed),
13 => mix0(read_8bytes_swapped(rem_key), (read_bytes(4, rem_key[8..]) << 8) | read_bytes(1, rem_key[12..]), seed),
14 => mix0(read_8bytes_swapped(rem_key), (read_bytes(4, rem_key[8..]) << 16) | read_bytes(2, rem_key[12..]), seed),
15 => mix0(read_8bytes_swapped(rem_key), (read_bytes(4, rem_key[8..]) << 24) | (read_bytes(2, rem_key[12..]) << 8) | read_bytes(1, rem_key[14..]), seed),
16 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed),
17 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_bytes(1, rem_key[16..]), primes[4], seed),
18 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_bytes(2, rem_key[16..]), primes[4], seed),
19 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1((read_bytes(2, rem_key[16..]) << 8) | read_bytes(1, rem_key[18..]), primes[4], seed),
20 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_bytes(4, rem_key[16..]), primes[4], seed),
21 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1((read_bytes(4, rem_key[16..]) << 8) | read_bytes(1, rem_key[20..]), primes[4], seed),
22 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1((read_bytes(4, rem_key[16..]) << 16) | read_bytes(2, rem_key[20..]), primes[4], seed),
23 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1((read_bytes(4, rem_key[16..]) << 24) | (read_bytes(2, rem_key[20..]) << 8) | read_bytes(1, rem_key[22..]), primes[4], seed),
24 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_8bytes_swapped(rem_key[16..]), primes[4], seed),
25 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_8bytes_swapped(rem_key[16..]), read_bytes(1, rem_key[24..]), seed),
26 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_8bytes_swapped(rem_key[16..]), read_bytes(2, rem_key[24..]), seed),
27 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_8bytes_swapped(rem_key[16..]), (read_bytes(2, rem_key[24..]) << 8) | read_bytes(1, rem_key[26..]), seed),
28 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_8bytes_swapped(rem_key[16..]), read_bytes(4, rem_key[24..]), seed),
29 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_8bytes_swapped(rem_key[16..]), (read_bytes(4, rem_key[24..]) << 8) | read_bytes(1, rem_key[28..]), seed),
30 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_8bytes_swapped(rem_key[16..]), (read_bytes(4, rem_key[24..]) << 16) | read_bytes(2, rem_key[28..]), seed),
31 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_8bytes_swapped(rem_key[16..]), (read_bytes(4, rem_key[24..]) << 24) | (read_bytes(2, rem_key[28..]) << 8) | read_bytes(1, rem_key[30..]), seed),
};
self.seed = seed;
}
pub fn update(self: *Wyhash, b: []const u8) void {
var off: usize = 0;
// Full middle blocks.
while (off + 32 <= b.len) : (off += 32) {
@inlineCall(self.round, b[off .. off + 32]);
}
self.partial(b[off..]);
self.msg_len += b.len;
}
pub fn final(self: *Wyhash) u64 {
return mum(self.seed ^ self.msg_len, primes[4]);
}
pub fn hash(seed: u64, input: []const u8) u64 {
var c = Wyhash.init(seed);
@inlineCall(c.update, input);
return @inlineCall(c.final);
}
};
test "test vectors" {
const expectEqual = std.testing.expectEqual;
const hash = Wyhash.hash;
expectEqual(hash(0, ""), 0x0);
expectEqual(hash(1, "a"), 0xbed235177f41d328);
expectEqual(hash(2, "abc"), 0xbe348debe59b27c3);
expectEqual(hash(3, "message digest"), 0x37320f657213a290);
expectEqual(hash(4, "abcdefghijklmnopqrstuvwxyz"), 0xd0b270e1d8a7019c);
expectEqual(hash(5, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"), 0x602a1894d3bbfe7f);
expectEqual(hash(6, "12345678901234567890123456789012345678901234567890123456789012345678901234567890"), 0x829e9c148b75970e);
} | std/hash/wyhash.zig |
const Archive = @This();
const std = @import("std");
const assert = std.debug.assert;
const fs = std.fs;
const log = std.log.scoped(.macho);
const macho = std.macho;
const mem = std.mem;
const fat = @import("fat.zig");
const Allocator = mem.Allocator;
const Object = @import("Object.zig");
file: fs.File,
name: []const u8,
header: ?ar_hdr = null,
// The actual contents we care about linking with will be embedded at
// an offset within a file if we are linking against a fat lib
library_offset: u64 = 0,
/// Parsed table of contents.
/// Each symbol name points to a list of all definition
/// sites within the current static archive.
toc: std.StringArrayHashMapUnmanaged(std.ArrayListUnmanaged(u32)) = .{},
// Archive files start with the ARMAG identifying string. Then follows a
// `struct ar_hdr', and as many bytes of member file data as its `ar_size'
// member indicates, for each member file.
/// String that begins an archive file.
const ARMAG: *const [SARMAG:0]u8 = "!<arch>\n";
/// Size of that string.
const SARMAG: u4 = 8;
/// String in ar_fmag at the end of each header.
const ARFMAG: *const [2:0]u8 = "`\n";
const ar_hdr = extern struct {
/// Member file name, sometimes / terminated.
ar_name: [16]u8,
/// File date, decimal seconds since Epoch.
ar_date: [12]u8,
/// User ID, in ASCII format.
ar_uid: [6]u8,
/// Group ID, in ASCII format.
ar_gid: [6]u8,
/// File mode, in ASCII octal.
ar_mode: [8]u8,
/// File size, in ASCII decimal.
ar_size: [10]u8,
/// Always contains ARFMAG.
ar_fmag: [2]u8,
const NameOrLength = union(enum) {
Name: []const u8,
Length: u32,
};
fn nameOrLength(self: ar_hdr) !NameOrLength {
const value = getValue(&self.ar_name);
const slash_index = mem.indexOf(u8, value, "/") orelse return error.MalformedArchive;
const len = value.len;
if (slash_index == len - 1) {
// Name stored directly
return NameOrLength{ .Name = value };
} else {
// Name follows the header directly and its length is encoded in
// the name field.
const length = try std.fmt.parseInt(u32, value[slash_index + 1 ..], 10);
return NameOrLength{ .Length = length };
}
}
fn date(self: ar_hdr) !u64 {
const value = getValue(&self.ar_date);
return std.fmt.parseInt(u64, value, 10);
}
fn size(self: ar_hdr) !u32 {
const value = getValue(&self.ar_size);
return std.fmt.parseInt(u32, value, 10);
}
fn getValue(raw: []const u8) []const u8 {
return mem.trimRight(u8, raw, &[_]u8{@as(u8, 0x20)});
}
};
pub fn deinit(self: *Archive, allocator: *Allocator) void {
for (self.toc.keys()) |*key| {
allocator.free(key.*);
}
for (self.toc.values()) |*value| {
value.deinit(allocator);
}
self.toc.deinit(allocator);
allocator.free(self.name);
}
pub fn parse(self: *Archive, allocator: *Allocator, target: std.Target) !void {
const reader = self.file.reader();
self.library_offset = try fat.getLibraryOffset(reader, target);
try self.file.seekTo(self.library_offset);
const magic = try reader.readBytesNoEof(SARMAG);
if (!mem.eql(u8, &magic, ARMAG)) {
log.debug("invalid magic: expected '{s}', found '{s}'", .{ ARMAG, magic });
return error.NotArchive;
}
self.header = try reader.readStruct(ar_hdr);
if (!mem.eql(u8, &self.header.?.ar_fmag, ARFMAG)) {
log.debug("invalid header delimiter: expected '{s}', found '{s}'", .{ ARFMAG, self.header.?.ar_fmag });
return error.NotArchive;
}
var embedded_name = try parseName(allocator, self.header.?, reader);
log.debug("parsing archive '{s}' at '{s}'", .{ embedded_name, self.name });
defer allocator.free(embedded_name);
try self.parseTableOfContents(allocator, reader);
try reader.context.seekTo(0);
}
fn parseName(allocator: *Allocator, header: ar_hdr, reader: anytype) ![]u8 {
const name_or_length = try header.nameOrLength();
var name: []u8 = undefined;
switch (name_or_length) {
.Name => |n| {
name = try allocator.dupe(u8, n);
},
.Length => |len| {
var n = try allocator.alloc(u8, len);
defer allocator.free(n);
try reader.readNoEof(n);
const actual_len = mem.indexOfScalar(u8, n, @as(u8, 0)) orelse n.len;
name = try allocator.dupe(u8, n[0..actual_len]);
},
}
return name;
}
fn parseTableOfContents(self: *Archive, allocator: *Allocator, reader: anytype) !void {
const symtab_size = try reader.readIntLittle(u32);
var symtab = try allocator.alloc(u8, symtab_size);
defer allocator.free(symtab);
reader.readNoEof(symtab) catch {
log.err("incomplete symbol table: expected symbol table of length 0x{x}", .{symtab_size});
return error.MalformedArchive;
};
const strtab_size = try reader.readIntLittle(u32);
var strtab = try allocator.alloc(u8, strtab_size);
defer allocator.free(strtab);
reader.readNoEof(strtab) catch {
log.err("incomplete symbol table: expected string table of length 0x{x}", .{strtab_size});
return error.MalformedArchive;
};
var symtab_stream = std.io.fixedBufferStream(symtab);
var symtab_reader = symtab_stream.reader();
while (true) {
const n_strx = symtab_reader.readIntLittle(u32) catch |err| switch (err) {
error.EndOfStream => break,
else => |e| return e,
};
const object_offset = try symtab_reader.readIntLittle(u32);
const sym_name = mem.spanZ(@ptrCast([*:0]const u8, strtab.ptr + n_strx));
const owned_name = try allocator.dupe(u8, sym_name);
const res = try self.toc.getOrPut(allocator, owned_name);
defer if (res.found_existing) allocator.free(owned_name);
if (!res.found_existing) {
res.value_ptr.* = .{};
}
try res.value_ptr.append(allocator, object_offset);
}
}
pub fn parseObject(self: Archive, allocator: *Allocator, target: std.Target, offset: u32) !Object {
const reader = self.file.reader();
try reader.context.seekTo(offset + self.library_offset);
const object_header = try reader.readStruct(ar_hdr);
if (!mem.eql(u8, &object_header.ar_fmag, ARFMAG)) {
log.err("invalid header delimiter: expected '{s}', found '{s}'", .{ ARFMAG, object_header.ar_fmag });
return error.MalformedArchive;
}
const object_name = try parseName(allocator, object_header, reader);
defer allocator.free(object_name);
log.debug("extracting object '{s}' from archive '{s}'", .{ object_name, self.name });
const name = name: {
var buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined;
const path = try std.os.realpath(self.name, &buffer);
break :name try std.fmt.allocPrint(allocator, "{s}({s})", .{ path, object_name });
};
var object = Object{
.file = try fs.cwd().openFile(self.name, .{}),
.name = name,
.file_offset = @intCast(u32, try reader.context.getPos()),
.mtime = try self.header.?.date(),
};
try object.parse(allocator, target);
try reader.context.seekTo(0);
return object;
} | src/MachO/Archive.zig |
const std = @import("std");
const assert = std.debug.assert;
const zephyr = @import("zephyr.zig");
const FlashArea = zephyr.flash.FlashArea;
const image = @import("image.zig");
const Image = image.Image;
pub const TlvTag = enum(u16) {
KeyHash = 0x01,
PubKey = 0x02,
Sha256 = 0x10,
RSA2048_PSS = 0x20,
ECDSA224 = 0x21,
ECDSA256 = 0x22,
RSA3072_PSS = 0x23,
ED25519 = 0x24,
Enc_RSA2048 = 0x30,
Enc_KW = 0x31,
Enc_EC256 = 0x32,
Enc_X25519 = 0x33,
Dependency = 0x40,
Sec_Cnt = 0x50,
Boot_Record = 0x60,
Other = 0xffff,
};
pub fn showTlv(img: *Image) !void {
var it = try TlvIter.init(img);
while (try it.next()) |item| {
zephyr.println("Tlv@{d}: t:{x:0>2}, len:{x:0>2}", .{ item.offset, item.tag, item.len });
}
}
// Walk through the TLV, ensuring that all of the entries are valid.
// TODO: Ensure that the entries that should be protected are.
pub fn validateTlv(img: *Image) !void {
var it = try TlvIter.init(img);
while (try it.next()) |_| {}
}
pub const TlvIter = struct {
const Self = @This();
header: TlvHeader,
base: u32,
img: *Image,
offset: u32,
pub fn init(img: *Image) !TlvIter {
const base = img.header.tlvBase();
const header = try img.readStruct(TlvHeader, base);
switch (header.magic) {
TLV_INFO_MAGIC => {
zephyr.println("Tlv magic: {} bytes", .{header.tlv_tot});
},
TLV_PROT_INFO_MAGIC => {
// Not yet implemented.
unreachable;
},
else => return error.InvalidTlv,
}
return TlvIter{
.header = header,
.base = base,
.img = img,
.offset = @sizeOf(TlvHeader),
};
}
pub fn next(self: *Self) !?TlvItem {
if (self.offset == self.header.tlv_tot) {
return null;
} else {
const old_offset = self.offset;
if (self.offset + @sizeOf(TlvEntry) > self.header.tlv_tot)
return error.CorruptTlv;
const entry = try self.img.readStruct(TlvEntry, self.base + self.offset);
self.offset += @sizeOf(TlvEntry) + entry.len;
if (self.offset > self.header.tlv_tot)
return error.CorruptTlv;
return TlvItem{
.tag = entry.tag,
.len = entry.len,
.offset = old_offset,
};
}
}
pub fn readItem(self: *const Self, comptime T: type, item: *const TlvItem) !T {
return self.img.readStruct(T, self.base + item.offset + @sizeOf(TlvEntry));
}
};
pub const TlvItem = struct {
tag: u16,
len: u16,
offset: u32,
};
const TLV_INFO_MAGIC = 0x6907;
const TLV_PROT_INFO_MAGIC = 0x6908;
const TlvHeader = extern struct {
magic: u16,
tlv_tot: u16,
};
comptime {
assert(@sizeOf(TlvHeader) == 4);
}
// This header can be misaligned. Arm allows these loads, but this
// may be an issue on other targets.
const TlvEntry = extern struct {
tag: u16,
len: u16,
};
comptime {
assert(@sizeOf(TlvEntry) == 4);
} | tlv.zig |
const Allocator = std.mem.Allocator;
const Header = @import("http").Header;
const Headers = @import("http").Headers;
const Method = @import("http").Method;
const std = @import("std");
const Uri = @import("http").Uri;
const Version = @import("http").Version;
const BodyType = enum {
ContentLength,
Empty,
};
const Body = union(BodyType) {
ContentLength: struct {
length: []const u8,
content: []const u8
},
Empty: void,
};
pub const Request = struct {
allocator: *Allocator,
headers: Headers,
ip: ?[]const u8,
method: Method,
path: []const u8,
uri: Uri,
version: Version,
body: Body,
pub fn deinit(self: *Request) void {
if (self.ip != null) {
self.allocator.free(self.ip.?);
}
self.headers.deinit();
switch(self.body) {
.ContentLength => |*body| {
self.allocator.free(body.length);
},
else => {}
}
}
pub fn init(allocator: *Allocator, method: Method, uri: Uri, options: anytype) !Request {
var path = if (uri.path.len != 0) uri.path else "/";
var request = Request {
.allocator = allocator,
.body = Body.Empty,
.headers = Headers.init(allocator),
.ip = null,
.method = method,
.path = path,
.uri = uri,
.version = Version.Http11,
};
switch(request.uri.host) {
.ip => |address|{
request.ip = try std.fmt.allocPrint(allocator, "{}", .{address});
try request.headers.append("Host", request.ip.?);
},
.name => |name| {
try request.headers.append("Host", name);
}
}
if (@hasField(@TypeOf(options), "headers")) {
var user_headers = getUserHeaders(options.headers);
try request.headers._items.appendSlice(user_headers);
}
if (@hasField(@TypeOf(options), "version")) {
request.options = options.version;
}
if (@hasField(@TypeOf(options), "content")) {
var content_length = std.fmt.allocPrint(allocator, "{d}", .{options.content.len}) catch unreachable;
try request.headers.append("Content-Length", content_length);
request.body = Body {
.ContentLength = .{
.length = content_length,
.content = options.content,
}
};
}
return request;
}
fn getUserHeaders(user_headers: anytype) []Header {
const typeof = @TypeOf(user_headers);
const typeinfo = @typeInfo(typeof);
switch(typeinfo) {
.Struct => |obj| {
return Header.as_slice(user_headers);
},
.Pointer => |ptr| {
return user_headers;
},
else => {
@compileError("Invalid headers type: You must provide either a http.Headers or an anonymous struct literal.");
}
}
}
};
const expect = std.testing.expect;
test "Request" {
const uri = try Uri.parse("http://ziglang.org/news/", false);
var request = try Request.init(std.testing.allocator, .Get, uri, .{});
defer request.deinit();
expect(request.method == .Get);
expect(request.version == .Http11);
expect(std.mem.eql(u8, request.headers.items()[0].name.raw(), "Host"));
expect(std.mem.eql(u8, request.headers.items()[0].value, "ziglang.org"));
expect(std.mem.eql(u8, request.path, "/news/"));
expect(request.body == .Empty);
}
test "Request - Path defaults to /" {
const uri = try Uri.parse("http://ziglang.org", false);
var request = try Request.init(std.testing.allocator, .Get, uri, .{});
defer request.deinit();
expect(std.mem.eql(u8, request.path, "/"));
}
test "Request - With user headers" {
const uri = try Uri.parse("http://ziglang.org/news/", false);
var headers = Headers.init(std.testing.allocator);
defer headers.deinit();
try headers.append("Gotta-go", "Fast!");
var request = try Request.init(std.testing.allocator, .Get, uri, .{ .headers = headers.items()});
defer request.deinit();
expect(std.mem.eql(u8, request.headers.items()[0].name.raw(), "Host"));
expect(std.mem.eql(u8, request.headers.items()[0].value, "ziglang.org"));
expect(std.mem.eql(u8, request.headers.items()[1].name.raw(), "Gotta-go"));
expect(std.mem.eql(u8, request.headers.items()[1].value, "Fast!"));
}
test "Request - With compile time user headers" {
const uri = try Uri.parse("http://ziglang.org/news/", false);
var headers = .{
.{"Gotta-go", "Fast!"}
};
var request = try Request.init(std.testing.allocator, .Get, uri, .{ .headers = headers});
defer request.deinit();
expect(std.mem.eql(u8, request.headers.items()[0].name.raw(), "Host"));
expect(std.mem.eql(u8, request.headers.items()[0].value, "ziglang.org"));
expect(std.mem.eql(u8, request.headers.items()[1].name.raw(), "Gotta-go"));
expect(std.mem.eql(u8, request.headers.items()[1].value, "Fast!"));
}
test "Request - With IP address" {
const uri = try Uri.parse("http://127.0.0.1:8080/", false);
var request = try Request.init(std.testing.allocator, .Get, uri, .{});
defer request.deinit();
expect(std.mem.eql(u8, request.ip.?, "127.0.0.1:8080"));
expect(std.mem.eql(u8, request.headers.items()[0].name.raw(), "Host"));
expect(std.mem.eql(u8, request.headers.items()[0].value, "127.0.0.1:8080"));
}
test "Request - With content" {
const uri = try Uri.parse("http://ziglang.org/news/", false);
var request = try Request.init(std.testing.allocator, .Get, uri, .{ .content = "Gotta go fast!"});
defer request.deinit();
expect(request.body == .ContentLength);
expect(std.mem.eql(u8, request.headers.items()[0].name.raw(), "Host"));
expect(std.mem.eql(u8, request.headers.items()[0].value, "ziglang.org"));
expect(std.mem.eql(u8, request.headers.items()[1].name.raw(), "Content-Length"));
expect(std.mem.eql(u8, request.headers.items()[1].value, "14"));
switch (request.body) {
.ContentLength => |body| {
expect(std.mem.eql(u8, body.length, "14"));
expect(std.mem.eql(u8, body.content, "Gotta go fast!"));
},
.Empty => unreachable,
}
} | src/request.zig |
const fmath = @import("index.zig");
pub fn log2(x: var) -> @typeOf(x) {
const T = @typeOf(x);
switch (T) {
f32 => @inlineCall(log2f, x),
f64 => @inlineCall(log2d, x),
else => @compileError("log2 not implemented for " ++ @typeName(T)),
}
}
fn log2f(x_: f32) -> f32 {
const ivln2hi: f32 = 1.4428710938e+00;
const ivln2lo: f32 = -1.7605285393e-04;
const Lg1: f32 = 0xaaaaaa.0p-24;
const Lg2: f32 = 0xccce13.0p-25;
const Lg3: f32 = 0x91e9ee.0p-25;
const Lg4: f32 = 0xf89e26.0p-26;
var x = x_;
var u = @bitCast(u32, x);
var ix = u;
var k: i32 = 0;
// x < 2^(-126)
if (ix < 0x00800000 or ix >> 31 != 0) {
// log(+-0) = -inf
if (ix << 1 == 0) {
return -1 / (x * x);
}
// log(-#) = nan
if (ix >> 31 != 0) {
return (x - x) / 0.0
}
k -= 25;
x *= 0x1.0p25;
ix = @bitCast(u32, x);
} else if (ix >= 0x7F800000) {
return x;
} else if (ix == 0x3F800000) {
return 0;
}
// x into [sqrt(2) / 2, sqrt(2)]
ix += 0x3F800000 - 0x3F3504F3;
k += i32(ix >> 23) - 0x7F;
ix = (ix & 0x007FFFFF) + 0x3F3504F3;
x = @bitCast(f32, ix);
const f = x - 1.0;
const s = f / (2.0 + f);
const z = s * s;
const w = z * z;
const t1 = w * (Lg2 + w * Lg4);
const t2 = z * (Lg1 + w * Lg3);
const R = t2 + t1;
const hfsq = 0.5 * f * f;
var hi = f - hfsq;
u = @bitCast(u32, hi);
u &= 0xFFFFF000;
hi = @bitCast(f32, u);
const lo = f - hi - hfsq + s * (hfsq + R);
(lo + hi) * ivln2lo + lo * ivln2hi + hi * ivln2hi + f32(k)
}
fn log2d(x_: f64) -> f64 {
const ivln2hi: f64 = 1.44269504072144627571e+00;
const ivln2lo: f64 = 1.67517131648865118353e-10;
const Lg1: f64 = 6.666666666666735130e-01;
const Lg2: f64 = 3.999999999940941908e-01;
const Lg3: f64 = 2.857142874366239149e-01;
const Lg4: f64 = 2.222219843214978396e-01;
const Lg5: f64 = 1.818357216161805012e-01;
const Lg6: f64 = 1.531383769920937332e-01;
const Lg7: f64 = 1.479819860511658591e-01;
var x = x_;
var ix = @bitCast(u64, x);
var hx = u32(ix >> 32);
var k: i32 = 0;
if (hx < 0x00100000 or hx >> 31 != 0) {
// log(+-0) = -inf
if (ix << 1 == 0) {
return -1 / (x * x);
}
// log(-#) = nan
if (hx >> 31 != 0) {
return (x - x) / 0.0;
}
// subnormal, scale x
k -= 54;
x *= 0x1.0p54;
hx = u32(@bitCast(u64, x) >> 32);
}
else if (hx >= 0x7FF00000) {
return x;
}
else if (hx == 0x3FF00000 and ix << 32 == 0) {
return 0;
}
// x into [sqrt(2) / 2, sqrt(2)]
hx += 0x3FF00000 - 0x3FE6A09E;
k += i32(hx >> 20) - 0x3FF;
hx = (hx & 0x000FFFFF) + 0x3FE6A09E;
ix = (u64(hx) << 32) | (ix & 0xFFFFFFFF);
x = @bitCast(f64, ix);
const f = x - 1.0;
const hfsq = 0.5 * f * f;
const s = f / (2.0 + f);
const z = s * s;
const w = z * z;
const t1 = w * (Lg2 + w * (Lg4 + w * Lg6));
const t2 = z * (Lg1 + w * (Lg3 + w * (Lg5 + w * Lg7)));
const R = t2 + t1;
// hi + lo = f - hfsq + s * (hfsq + R) ~ log(1 + f)
var hi = f - hfsq;
var hii = @bitCast(u64, hi);
hii &= @maxValue(u64) << 32;
hi = @bitCast(f64, hii);
const lo = f - hi - hfsq + s * (hfsq + R);
var val_hi = hi * ivln2hi;
var val_lo = (lo + hi) * ivln2lo + lo * ivln2hi;
// spadd(val_hi, val_lo, y)
const y = f64(k);
const ww = y + val_hi;
val_lo += (y - ww) + val_hi;
val_hi = ww;
val_lo + val_hi
}
test "log2" {
fmath.assert(log2(f32(0.2)) == log2f(0.2));
fmath.assert(log2(f64(0.2)) == log2d(0.2));
}
test "log2f" {
const epsilon = 0.000001;
fmath.assert(fmath.approxEq(f32, log2f(0.2), -2.321928, epsilon));
fmath.assert(fmath.approxEq(f32, log2f(0.8923), -0.164399, epsilon));
fmath.assert(fmath.approxEq(f32, log2f(1.5), 0.584962, epsilon));
fmath.assert(fmath.approxEq(f32, log2f(37.45), 5.226894, epsilon));
fmath.assert(fmath.approxEq(f32, log2f(123123.234375), 16.909744, epsilon));
}
test "log2d" {
const epsilon = 0.000001;
fmath.assert(fmath.approxEq(f64, log2d(0.2), -2.321928, epsilon));
fmath.assert(fmath.approxEq(f64, log2d(0.8923), -0.164399, epsilon));
fmath.assert(fmath.approxEq(f64, log2d(1.5), 0.584962, epsilon));
fmath.assert(fmath.approxEq(f64, log2d(37.45), 5.226894, epsilon));
fmath.assert(fmath.approxEq(f64, log2d(123123.234375), 16.909744, epsilon));
} | src/log2.zig |
pub const DWRITE_ALPHA_MAX = @as(u32, 255);
pub const FACILITY_DWRITE = @as(u32, 2200);
pub const DWRITE_ERR_BASE = @as(u32, 20480);
pub const DWRITE_E_REMOTEFONT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2003283955));
pub const DWRITE_E_DOWNLOADCANCELLED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2003283954));
pub const DWRITE_E_DOWNLOADFAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2003283953));
pub const DWRITE_E_TOOMANYDOWNLOADS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2003283952));
//--------------------------------------------------------------------------------
// Section: Types (194)
//--------------------------------------------------------------------------------
pub const DWRITE_FONT_AXIS_TAG = enum(u32) {
WEIGHT = 1952999287,
WIDTH = 1752458359,
SLANT = 1953393779,
OPTICAL_SIZE = 2054385775,
ITALIC = 1818326121,
};
pub const DWRITE_FONT_AXIS_TAG_WEIGHT = DWRITE_FONT_AXIS_TAG.WEIGHT;
pub const DWRITE_FONT_AXIS_TAG_WIDTH = DWRITE_FONT_AXIS_TAG.WIDTH;
pub const DWRITE_FONT_AXIS_TAG_SLANT = DWRITE_FONT_AXIS_TAG.SLANT;
pub const DWRITE_FONT_AXIS_TAG_OPTICAL_SIZE = DWRITE_FONT_AXIS_TAG.OPTICAL_SIZE;
pub const DWRITE_FONT_AXIS_TAG_ITALIC = DWRITE_FONT_AXIS_TAG.ITALIC;
pub const DWRITE_COLOR_F = extern struct {
r: f32,
g: f32,
b: f32,
a: f32,
};
pub const DWRITE_MEASURING_MODE = enum(i32) {
NATURAL = 0,
GDI_CLASSIC = 1,
GDI_NATURAL = 2,
};
pub const DWRITE_MEASURING_MODE_NATURAL = DWRITE_MEASURING_MODE.NATURAL;
pub const DWRITE_MEASURING_MODE_GDI_CLASSIC = DWRITE_MEASURING_MODE.GDI_CLASSIC;
pub const DWRITE_MEASURING_MODE_GDI_NATURAL = DWRITE_MEASURING_MODE.GDI_NATURAL;
pub const DWRITE_GLYPH_IMAGE_FORMATS = enum(u32) {
NONE = 0,
TRUETYPE = 1,
CFF = 2,
COLR = 4,
SVG = 8,
PNG = 16,
JPEG = 32,
TIFF = 64,
PREMULTIPLIED_B8G8R8A8 = 128,
_,
pub fn initFlags(o: struct {
NONE: u1 = 0,
TRUETYPE: u1 = 0,
CFF: u1 = 0,
COLR: u1 = 0,
SVG: u1 = 0,
PNG: u1 = 0,
JPEG: u1 = 0,
TIFF: u1 = 0,
PREMULTIPLIED_B8G8R8A8: u1 = 0,
}) DWRITE_GLYPH_IMAGE_FORMATS {
return @intToEnum(DWRITE_GLYPH_IMAGE_FORMATS,
(if (o.NONE == 1) @enumToInt(DWRITE_GLYPH_IMAGE_FORMATS.NONE) else 0)
| (if (o.TRUETYPE == 1) @enumToInt(DWRITE_GLYPH_IMAGE_FORMATS.TRUETYPE) else 0)
| (if (o.CFF == 1) @enumToInt(DWRITE_GLYPH_IMAGE_FORMATS.CFF) else 0)
| (if (o.COLR == 1) @enumToInt(DWRITE_GLYPH_IMAGE_FORMATS.COLR) else 0)
| (if (o.SVG == 1) @enumToInt(DWRITE_GLYPH_IMAGE_FORMATS.SVG) else 0)
| (if (o.PNG == 1) @enumToInt(DWRITE_GLYPH_IMAGE_FORMATS.PNG) else 0)
| (if (o.JPEG == 1) @enumToInt(DWRITE_GLYPH_IMAGE_FORMATS.JPEG) else 0)
| (if (o.TIFF == 1) @enumToInt(DWRITE_GLYPH_IMAGE_FORMATS.TIFF) else 0)
| (if (o.PREMULTIPLIED_B8G8R8A8 == 1) @enumToInt(DWRITE_GLYPH_IMAGE_FORMATS.PREMULTIPLIED_B8G8R8A8) else 0)
);
}
};
pub const DWRITE_GLYPH_IMAGE_FORMATS_NONE = DWRITE_GLYPH_IMAGE_FORMATS.NONE;
pub const DWRITE_GLYPH_IMAGE_FORMATS_TRUETYPE = DWRITE_GLYPH_IMAGE_FORMATS.TRUETYPE;
pub const DWRITE_GLYPH_IMAGE_FORMATS_CFF = DWRITE_GLYPH_IMAGE_FORMATS.CFF;
pub const DWRITE_GLYPH_IMAGE_FORMATS_COLR = DWRITE_GLYPH_IMAGE_FORMATS.COLR;
pub const DWRITE_GLYPH_IMAGE_FORMATS_SVG = DWRITE_GLYPH_IMAGE_FORMATS.SVG;
pub const DWRITE_GLYPH_IMAGE_FORMATS_PNG = DWRITE_GLYPH_IMAGE_FORMATS.PNG;
pub const DWRITE_GLYPH_IMAGE_FORMATS_JPEG = DWRITE_GLYPH_IMAGE_FORMATS.JPEG;
pub const DWRITE_GLYPH_IMAGE_FORMATS_TIFF = DWRITE_GLYPH_IMAGE_FORMATS.TIFF;
pub const DWRITE_GLYPH_IMAGE_FORMATS_PREMULTIPLIED_B8G8R8A8 = DWRITE_GLYPH_IMAGE_FORMATS.PREMULTIPLIED_B8G8R8A8;
pub const DWRITE_FONT_FILE_TYPE = enum(i32) {
UNKNOWN = 0,
CFF = 1,
TRUETYPE = 2,
OPENTYPE_COLLECTION = 3,
TYPE1_PFM = 4,
TYPE1_PFB = 5,
VECTOR = 6,
BITMAP = 7,
// TRUETYPE_COLLECTION = 3, this enum value conflicts with OPENTYPE_COLLECTION
};
pub const DWRITE_FONT_FILE_TYPE_UNKNOWN = DWRITE_FONT_FILE_TYPE.UNKNOWN;
pub const DWRITE_FONT_FILE_TYPE_CFF = DWRITE_FONT_FILE_TYPE.CFF;
pub const DWRITE_FONT_FILE_TYPE_TRUETYPE = DWRITE_FONT_FILE_TYPE.TRUETYPE;
pub const DWRITE_FONT_FILE_TYPE_OPENTYPE_COLLECTION = DWRITE_FONT_FILE_TYPE.OPENTYPE_COLLECTION;
pub const DWRITE_FONT_FILE_TYPE_TYPE1_PFM = DWRITE_FONT_FILE_TYPE.TYPE1_PFM;
pub const DWRITE_FONT_FILE_TYPE_TYPE1_PFB = DWRITE_FONT_FILE_TYPE.TYPE1_PFB;
pub const DWRITE_FONT_FILE_TYPE_VECTOR = DWRITE_FONT_FILE_TYPE.VECTOR;
pub const DWRITE_FONT_FILE_TYPE_BITMAP = DWRITE_FONT_FILE_TYPE.BITMAP;
pub const DWRITE_FONT_FILE_TYPE_TRUETYPE_COLLECTION = DWRITE_FONT_FILE_TYPE.OPENTYPE_COLLECTION;
pub const DWRITE_FONT_FACE_TYPE = enum(i32) {
CFF = 0,
TRUETYPE = 1,
OPENTYPE_COLLECTION = 2,
TYPE1 = 3,
VECTOR = 4,
BITMAP = 5,
UNKNOWN = 6,
RAW_CFF = 7,
// TRUETYPE_COLLECTION = 2, this enum value conflicts with OPENTYPE_COLLECTION
};
pub const DWRITE_FONT_FACE_TYPE_CFF = DWRITE_FONT_FACE_TYPE.CFF;
pub const DWRITE_FONT_FACE_TYPE_TRUETYPE = DWRITE_FONT_FACE_TYPE.TRUETYPE;
pub const DWRITE_FONT_FACE_TYPE_OPENTYPE_COLLECTION = DWRITE_FONT_FACE_TYPE.OPENTYPE_COLLECTION;
pub const DWRITE_FONT_FACE_TYPE_TYPE1 = DWRITE_FONT_FACE_TYPE.TYPE1;
pub const DWRITE_FONT_FACE_TYPE_VECTOR = DWRITE_FONT_FACE_TYPE.VECTOR;
pub const DWRITE_FONT_FACE_TYPE_BITMAP = DWRITE_FONT_FACE_TYPE.BITMAP;
pub const DWRITE_FONT_FACE_TYPE_UNKNOWN = DWRITE_FONT_FACE_TYPE.UNKNOWN;
pub const DWRITE_FONT_FACE_TYPE_RAW_CFF = DWRITE_FONT_FACE_TYPE.RAW_CFF;
pub const DWRITE_FONT_FACE_TYPE_TRUETYPE_COLLECTION = DWRITE_FONT_FACE_TYPE.OPENTYPE_COLLECTION;
pub const DWRITE_FONT_SIMULATIONS = enum(u32) {
NONE = 0,
BOLD = 1,
OBLIQUE = 2,
_,
pub fn initFlags(o: struct {
NONE: u1 = 0,
BOLD: u1 = 0,
OBLIQUE: u1 = 0,
}) DWRITE_FONT_SIMULATIONS {
return @intToEnum(DWRITE_FONT_SIMULATIONS,
(if (o.NONE == 1) @enumToInt(DWRITE_FONT_SIMULATIONS.NONE) else 0)
| (if (o.BOLD == 1) @enumToInt(DWRITE_FONT_SIMULATIONS.BOLD) else 0)
| (if (o.OBLIQUE == 1) @enumToInt(DWRITE_FONT_SIMULATIONS.OBLIQUE) else 0)
);
}
};
pub const DWRITE_FONT_SIMULATIONS_NONE = DWRITE_FONT_SIMULATIONS.NONE;
pub const DWRITE_FONT_SIMULATIONS_BOLD = DWRITE_FONT_SIMULATIONS.BOLD;
pub const DWRITE_FONT_SIMULATIONS_OBLIQUE = DWRITE_FONT_SIMULATIONS.OBLIQUE;
pub const DWRITE_FONT_WEIGHT = enum(i32) {
THIN = 100,
EXTRA_LIGHT = 200,
// ULTRA_LIGHT = 200, this enum value conflicts with EXTRA_LIGHT
LIGHT = 300,
SEMI_LIGHT = 350,
NORMAL = 400,
// REGULAR = 400, this enum value conflicts with NORMAL
MEDIUM = 500,
DEMI_BOLD = 600,
// SEMI_BOLD = 600, this enum value conflicts with DEMI_BOLD
BOLD = 700,
EXTRA_BOLD = 800,
// ULTRA_BOLD = 800, this enum value conflicts with EXTRA_BOLD
BLACK = 900,
// HEAVY = 900, this enum value conflicts with BLACK
EXTRA_BLACK = 950,
// ULTRA_BLACK = 950, this enum value conflicts with EXTRA_BLACK
};
pub const DWRITE_FONT_WEIGHT_THIN = DWRITE_FONT_WEIGHT.THIN;
pub const DWRITE_FONT_WEIGHT_EXTRA_LIGHT = DWRITE_FONT_WEIGHT.EXTRA_LIGHT;
pub const DWRITE_FONT_WEIGHT_ULTRA_LIGHT = DWRITE_FONT_WEIGHT.EXTRA_LIGHT;
pub const DWRITE_FONT_WEIGHT_LIGHT = DWRITE_FONT_WEIGHT.LIGHT;
pub const DWRITE_FONT_WEIGHT_SEMI_LIGHT = DWRITE_FONT_WEIGHT.SEMI_LIGHT;
pub const DWRITE_FONT_WEIGHT_NORMAL = DWRITE_FONT_WEIGHT.NORMAL;
pub const DWRITE_FONT_WEIGHT_REGULAR = DWRITE_FONT_WEIGHT.NORMAL;
pub const DWRITE_FONT_WEIGHT_MEDIUM = DWRITE_FONT_WEIGHT.MEDIUM;
pub const DWRITE_FONT_WEIGHT_DEMI_BOLD = DWRITE_FONT_WEIGHT.DEMI_BOLD;
pub const DWRITE_FONT_WEIGHT_SEMI_BOLD = DWRITE_FONT_WEIGHT.DEMI_BOLD;
pub const DWRITE_FONT_WEIGHT_BOLD = DWRITE_FONT_WEIGHT.BOLD;
pub const DWRITE_FONT_WEIGHT_EXTRA_BOLD = DWRITE_FONT_WEIGHT.EXTRA_BOLD;
pub const DWRITE_FONT_WEIGHT_ULTRA_BOLD = DWRITE_FONT_WEIGHT.EXTRA_BOLD;
pub const DWRITE_FONT_WEIGHT_BLACK = DWRITE_FONT_WEIGHT.BLACK;
pub const DWRITE_FONT_WEIGHT_HEAVY = DWRITE_FONT_WEIGHT.BLACK;
pub const DWRITE_FONT_WEIGHT_EXTRA_BLACK = DWRITE_FONT_WEIGHT.EXTRA_BLACK;
pub const DWRITE_FONT_WEIGHT_ULTRA_BLACK = DWRITE_FONT_WEIGHT.EXTRA_BLACK;
pub const DWRITE_FONT_STRETCH = enum(i32) {
UNDEFINED = 0,
ULTRA_CONDENSED = 1,
EXTRA_CONDENSED = 2,
CONDENSED = 3,
SEMI_CONDENSED = 4,
NORMAL = 5,
// MEDIUM = 5, this enum value conflicts with NORMAL
SEMI_EXPANDED = 6,
EXPANDED = 7,
EXTRA_EXPANDED = 8,
ULTRA_EXPANDED = 9,
};
pub const DWRITE_FONT_STRETCH_UNDEFINED = DWRITE_FONT_STRETCH.UNDEFINED;
pub const DWRITE_FONT_STRETCH_ULTRA_CONDENSED = DWRITE_FONT_STRETCH.ULTRA_CONDENSED;
pub const DWRITE_FONT_STRETCH_EXTRA_CONDENSED = DWRITE_FONT_STRETCH.EXTRA_CONDENSED;
pub const DWRITE_FONT_STRETCH_CONDENSED = DWRITE_FONT_STRETCH.CONDENSED;
pub const DWRITE_FONT_STRETCH_SEMI_CONDENSED = DWRITE_FONT_STRETCH.SEMI_CONDENSED;
pub const DWRITE_FONT_STRETCH_NORMAL = DWRITE_FONT_STRETCH.NORMAL;
pub const DWRITE_FONT_STRETCH_MEDIUM = DWRITE_FONT_STRETCH.NORMAL;
pub const DWRITE_FONT_STRETCH_SEMI_EXPANDED = DWRITE_FONT_STRETCH.SEMI_EXPANDED;
pub const DWRITE_FONT_STRETCH_EXPANDED = DWRITE_FONT_STRETCH.EXPANDED;
pub const DWRITE_FONT_STRETCH_EXTRA_EXPANDED = DWRITE_FONT_STRETCH.EXTRA_EXPANDED;
pub const DWRITE_FONT_STRETCH_ULTRA_EXPANDED = DWRITE_FONT_STRETCH.ULTRA_EXPANDED;
pub const DWRITE_FONT_STYLE = enum(i32) {
NORMAL = 0,
OBLIQUE = 1,
ITALIC = 2,
};
pub const DWRITE_FONT_STYLE_NORMAL = DWRITE_FONT_STYLE.NORMAL;
pub const DWRITE_FONT_STYLE_OBLIQUE = DWRITE_FONT_STYLE.OBLIQUE;
pub const DWRITE_FONT_STYLE_ITALIC = DWRITE_FONT_STYLE.ITALIC;
pub const DWRITE_INFORMATIONAL_STRING_ID = enum(i32) {
NONE = 0,
COPYRIGHT_NOTICE = 1,
VERSION_STRINGS = 2,
TRADEMARK = 3,
MANUFACTURER = 4,
DESIGNER = 5,
DESIGNER_URL = 6,
DESCRIPTION = 7,
FONT_VENDOR_URL = 8,
LICENSE_DESCRIPTION = 9,
LICENSE_INFO_URL = 10,
WIN32_FAMILY_NAMES = 11,
WIN32_SUBFAMILY_NAMES = 12,
TYPOGRAPHIC_FAMILY_NAMES = 13,
TYPOGRAPHIC_SUBFAMILY_NAMES = 14,
SAMPLE_TEXT = 15,
FULL_NAME = 16,
POSTSCRIPT_NAME = 17,
POSTSCRIPT_CID_NAME = 18,
WEIGHT_STRETCH_STYLE_FAMILY_NAME = 19,
DESIGN_SCRIPT_LANGUAGE_TAG = 20,
SUPPORTED_SCRIPT_LANGUAGE_TAG = 21,
// PREFERRED_FAMILY_NAMES = 13, this enum value conflicts with TYPOGRAPHIC_FAMILY_NAMES
// PREFERRED_SUBFAMILY_NAMES = 14, this enum value conflicts with TYPOGRAPHIC_SUBFAMILY_NAMES
// WWS_FAMILY_NAME = 19, this enum value conflicts with WEIGHT_STRETCH_STYLE_FAMILY_NAME
};
pub const DWRITE_INFORMATIONAL_STRING_NONE = DWRITE_INFORMATIONAL_STRING_ID.NONE;
pub const DWRITE_INFORMATIONAL_STRING_COPYRIGHT_NOTICE = DWRITE_INFORMATIONAL_STRING_ID.COPYRIGHT_NOTICE;
pub const DWRITE_INFORMATIONAL_STRING_VERSION_STRINGS = DWRITE_INFORMATIONAL_STRING_ID.VERSION_STRINGS;
pub const DWRITE_INFORMATIONAL_STRING_TRADEMARK = DWRITE_INFORMATIONAL_STRING_ID.TRADEMARK;
pub const DWRITE_INFORMATIONAL_STRING_MANUFACTURER = DWRITE_INFORMATIONAL_STRING_ID.MANUFACTURER;
pub const DWRITE_INFORMATIONAL_STRING_DESIGNER = DWRITE_INFORMATIONAL_STRING_ID.DESIGNER;
pub const DWRITE_INFORMATIONAL_STRING_DESIGNER_URL = DWRITE_INFORMATIONAL_STRING_ID.DESIGNER_URL;
pub const DWRITE_INFORMATIONAL_STRING_DESCRIPTION = DWRITE_INFORMATIONAL_STRING_ID.DESCRIPTION;
pub const DWRITE_INFORMATIONAL_STRING_FONT_VENDOR_URL = DWRITE_INFORMATIONAL_STRING_ID.FONT_VENDOR_URL;
pub const DWRITE_INFORMATIONAL_STRING_LICENSE_DESCRIPTION = DWRITE_INFORMATIONAL_STRING_ID.LICENSE_DESCRIPTION;
pub const DWRITE_INFORMATIONAL_STRING_LICENSE_INFO_URL = DWRITE_INFORMATIONAL_STRING_ID.LICENSE_INFO_URL;
pub const DWRITE_INFORMATIONAL_STRING_WIN32_FAMILY_NAMES = DWRITE_INFORMATIONAL_STRING_ID.WIN32_FAMILY_NAMES;
pub const DWRITE_INFORMATIONAL_STRING_WIN32_SUBFAMILY_NAMES = DWRITE_INFORMATIONAL_STRING_ID.WIN32_SUBFAMILY_NAMES;
pub const DWRITE_INFORMATIONAL_STRING_TYPOGRAPHIC_FAMILY_NAMES = DWRITE_INFORMATIONAL_STRING_ID.TYPOGRAPHIC_FAMILY_NAMES;
pub const DWRITE_INFORMATIONAL_STRING_TYPOGRAPHIC_SUBFAMILY_NAMES = DWRITE_INFORMATIONAL_STRING_ID.TYPOGRAPHIC_SUBFAMILY_NAMES;
pub const DWRITE_INFORMATIONAL_STRING_SAMPLE_TEXT = DWRITE_INFORMATIONAL_STRING_ID.SAMPLE_TEXT;
pub const DWRITE_INFORMATIONAL_STRING_FULL_NAME = DWRITE_INFORMATIONAL_STRING_ID.FULL_NAME;
pub const DWRITE_INFORMATIONAL_STRING_POSTSCRIPT_NAME = DWRITE_INFORMATIONAL_STRING_ID.POSTSCRIPT_NAME;
pub const DWRITE_INFORMATIONAL_STRING_POSTSCRIPT_CID_NAME = DWRITE_INFORMATIONAL_STRING_ID.POSTSCRIPT_CID_NAME;
pub const DWRITE_INFORMATIONAL_STRING_WEIGHT_STRETCH_STYLE_FAMILY_NAME = DWRITE_INFORMATIONAL_STRING_ID.WEIGHT_STRETCH_STYLE_FAMILY_NAME;
pub const DWRITE_INFORMATIONAL_STRING_DESIGN_SCRIPT_LANGUAGE_TAG = DWRITE_INFORMATIONAL_STRING_ID.DESIGN_SCRIPT_LANGUAGE_TAG;
pub const DWRITE_INFORMATIONAL_STRING_SUPPORTED_SCRIPT_LANGUAGE_TAG = DWRITE_INFORMATIONAL_STRING_ID.SUPPORTED_SCRIPT_LANGUAGE_TAG;
pub const DWRITE_INFORMATIONAL_STRING_PREFERRED_FAMILY_NAMES = DWRITE_INFORMATIONAL_STRING_ID.TYPOGRAPHIC_FAMILY_NAMES;
pub const DWRITE_INFORMATIONAL_STRING_PREFERRED_SUBFAMILY_NAMES = DWRITE_INFORMATIONAL_STRING_ID.TYPOGRAPHIC_SUBFAMILY_NAMES;
pub const DWRITE_INFORMATIONAL_STRING_WWS_FAMILY_NAME = DWRITE_INFORMATIONAL_STRING_ID.WEIGHT_STRETCH_STYLE_FAMILY_NAME;
pub const DWRITE_FONT_METRICS = extern struct {
designUnitsPerEm: u16,
ascent: u16,
descent: u16,
lineGap: i16,
capHeight: u16,
xHeight: u16,
underlinePosition: i16,
underlineThickness: u16,
strikethroughPosition: i16,
strikethroughThickness: u16,
};
pub const DWRITE_GLYPH_METRICS = extern struct {
leftSideBearing: i32,
advanceWidth: u32,
rightSideBearing: i32,
topSideBearing: i32,
advanceHeight: u32,
bottomSideBearing: i32,
verticalOriginY: i32,
};
pub const DWRITE_GLYPH_OFFSET = extern struct {
advanceOffset: f32,
ascenderOffset: f32,
};
pub const DWRITE_FACTORY_TYPE = enum(i32) {
SHARED = 0,
ISOLATED = 1,
};
pub const DWRITE_FACTORY_TYPE_SHARED = DWRITE_FACTORY_TYPE.SHARED;
pub const DWRITE_FACTORY_TYPE_ISOLATED = DWRITE_FACTORY_TYPE.ISOLATED;
// TODO: this type is limited to platform 'windows6.1'
const IID_IDWriteFontFileLoader_Value = Guid.initString("727cad4e-d6af-4c9e-8a08-d695b11caa49");
pub const IID_IDWriteFontFileLoader = &IID_IDWriteFontFileLoader_Value;
pub const IDWriteFontFileLoader = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
CreateStreamFromKey: fn(
self: *const IDWriteFontFileLoader,
// TODO: what to do with BytesParamIndex 1?
fontFileReferenceKey: ?*const anyopaque,
fontFileReferenceKeySize: u32,
fontFileStream: ?*?*IDWriteFontFileStream,
) 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 IDWriteFontFileLoader_CreateStreamFromKey(self: *const T, fontFileReferenceKey: ?*const anyopaque, fontFileReferenceKeySize: u32, fontFileStream: ?*?*IDWriteFontFileStream) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFileLoader.VTable, self.vtable).CreateStreamFromKey(@ptrCast(*const IDWriteFontFileLoader, self), fontFileReferenceKey, fontFileReferenceKeySize, fontFileStream);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDWriteLocalFontFileLoader_Value = Guid.initString("b2d9f3ec-c9fe-4a11-a2ec-d86208f7c0a2");
pub const IID_IDWriteLocalFontFileLoader = &IID_IDWriteLocalFontFileLoader_Value;
pub const IDWriteLocalFontFileLoader = extern struct {
pub const VTable = extern struct {
base: IDWriteFontFileLoader.VTable,
GetFilePathLengthFromKey: fn(
self: *const IDWriteLocalFontFileLoader,
// TODO: what to do with BytesParamIndex 1?
fontFileReferenceKey: ?*const anyopaque,
fontFileReferenceKeySize: u32,
filePathLength: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFilePathFromKey: fn(
self: *const IDWriteLocalFontFileLoader,
// TODO: what to do with BytesParamIndex 1?
fontFileReferenceKey: ?*const anyopaque,
fontFileReferenceKeySize: u32,
filePath: [*:0]u16,
filePathSize: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLastWriteTimeFromKey: fn(
self: *const IDWriteLocalFontFileLoader,
// TODO: what to do with BytesParamIndex 1?
fontFileReferenceKey: ?*const anyopaque,
fontFileReferenceKeySize: u32,
lastWriteTime: ?*FILETIME,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFontFileLoader.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteLocalFontFileLoader_GetFilePathLengthFromKey(self: *const T, fontFileReferenceKey: ?*const anyopaque, fontFileReferenceKeySize: u32, filePathLength: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteLocalFontFileLoader.VTable, self.vtable).GetFilePathLengthFromKey(@ptrCast(*const IDWriteLocalFontFileLoader, self), fontFileReferenceKey, fontFileReferenceKeySize, filePathLength);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteLocalFontFileLoader_GetFilePathFromKey(self: *const T, fontFileReferenceKey: ?*const anyopaque, fontFileReferenceKeySize: u32, filePath: [*:0]u16, filePathSize: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteLocalFontFileLoader.VTable, self.vtable).GetFilePathFromKey(@ptrCast(*const IDWriteLocalFontFileLoader, self), fontFileReferenceKey, fontFileReferenceKeySize, filePath, filePathSize);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteLocalFontFileLoader_GetLastWriteTimeFromKey(self: *const T, fontFileReferenceKey: ?*const anyopaque, fontFileReferenceKeySize: u32, lastWriteTime: ?*FILETIME) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteLocalFontFileLoader.VTable, self.vtable).GetLastWriteTimeFromKey(@ptrCast(*const IDWriteLocalFontFileLoader, self), fontFileReferenceKey, fontFileReferenceKeySize, lastWriteTime);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IDWriteFontFileStream_Value = Guid.initString("6d4865fe-0ab8-4d91-8f62-5dd6be34a3e0");
pub const IID_IDWriteFontFileStream = &IID_IDWriteFontFileStream_Value;
pub const IDWriteFontFileStream = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
ReadFileFragment: fn(
self: *const IDWriteFontFileStream,
fragmentStart: ?*const ?*anyopaque,
fileOffset: u64,
fragmentSize: u64,
fragmentContext: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ReleaseFileFragment: fn(
self: *const IDWriteFontFileStream,
fragmentContext: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) void,
GetFileSize: fn(
self: *const IDWriteFontFileStream,
fileSize: ?*u64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLastWriteTime: fn(
self: *const IDWriteFontFileStream,
lastWriteTime: ?*u64,
) 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 IDWriteFontFileStream_ReadFileFragment(self: *const T, fragmentStart: ?*const ?*anyopaque, fileOffset: u64, fragmentSize: u64, fragmentContext: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFileStream.VTable, self.vtable).ReadFileFragment(@ptrCast(*const IDWriteFontFileStream, self), fragmentStart, fileOffset, fragmentSize, fragmentContext);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFileStream_ReleaseFileFragment(self: *const T, fragmentContext: ?*anyopaque) callconv(.Inline) void {
return @ptrCast(*const IDWriteFontFileStream.VTable, self.vtable).ReleaseFileFragment(@ptrCast(*const IDWriteFontFileStream, self), fragmentContext);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFileStream_GetFileSize(self: *const T, fileSize: ?*u64) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFileStream.VTable, self.vtable).GetFileSize(@ptrCast(*const IDWriteFontFileStream, self), fileSize);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFileStream_GetLastWriteTime(self: *const T, lastWriteTime: ?*u64) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFileStream.VTable, self.vtable).GetLastWriteTime(@ptrCast(*const IDWriteFontFileStream, self), lastWriteTime);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IDWriteFontFile_Value = Guid.initString("739d886a-cef5-47dc-8769-1a8b41bebbb0");
pub const IID_IDWriteFontFile = &IID_IDWriteFontFile_Value;
pub const IDWriteFontFile = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetReferenceKey: fn(
self: *const IDWriteFontFile,
fontFileReferenceKey: ?*const ?*anyopaque,
fontFileReferenceKeySize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLoader: fn(
self: *const IDWriteFontFile,
fontFileLoader: ?*?*IDWriteFontFileLoader,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Analyze: fn(
self: *const IDWriteFontFile,
isSupportedFontType: ?*BOOL,
fontFileType: ?*DWRITE_FONT_FILE_TYPE,
fontFaceType: ?*DWRITE_FONT_FACE_TYPE,
numberOfFaces: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFile_GetReferenceKey(self: *const T, fontFileReferenceKey: ?*const ?*anyopaque, fontFileReferenceKeySize: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFile.VTable, self.vtable).GetReferenceKey(@ptrCast(*const IDWriteFontFile, self), fontFileReferenceKey, fontFileReferenceKeySize);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFile_GetLoader(self: *const T, fontFileLoader: ?*?*IDWriteFontFileLoader) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFile.VTable, self.vtable).GetLoader(@ptrCast(*const IDWriteFontFile, self), fontFileLoader);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFile_Analyze(self: *const T, isSupportedFontType: ?*BOOL, fontFileType: ?*DWRITE_FONT_FILE_TYPE, fontFaceType: ?*DWRITE_FONT_FACE_TYPE, numberOfFaces: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFile.VTable, self.vtable).Analyze(@ptrCast(*const IDWriteFontFile, self), isSupportedFontType, fontFileType, fontFaceType, numberOfFaces);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DWRITE_PIXEL_GEOMETRY = enum(i32) {
FLAT = 0,
RGB = 1,
BGR = 2,
};
pub const DWRITE_PIXEL_GEOMETRY_FLAT = DWRITE_PIXEL_GEOMETRY.FLAT;
pub const DWRITE_PIXEL_GEOMETRY_RGB = DWRITE_PIXEL_GEOMETRY.RGB;
pub const DWRITE_PIXEL_GEOMETRY_BGR = DWRITE_PIXEL_GEOMETRY.BGR;
pub const DWRITE_RENDERING_MODE = enum(i32) {
DEFAULT = 0,
ALIASED = 1,
GDI_CLASSIC = 2,
GDI_NATURAL = 3,
NATURAL = 4,
NATURAL_SYMMETRIC = 5,
OUTLINE = 6,
// CLEARTYPE_GDI_CLASSIC = 2, this enum value conflicts with GDI_CLASSIC
// CLEARTYPE_GDI_NATURAL = 3, this enum value conflicts with GDI_NATURAL
// CLEARTYPE_NATURAL = 4, this enum value conflicts with NATURAL
// CLEARTYPE_NATURAL_SYMMETRIC = 5, this enum value conflicts with NATURAL_SYMMETRIC
};
pub const DWRITE_RENDERING_MODE_DEFAULT = DWRITE_RENDERING_MODE.DEFAULT;
pub const DWRITE_RENDERING_MODE_ALIASED = DWRITE_RENDERING_MODE.ALIASED;
pub const DWRITE_RENDERING_MODE_GDI_CLASSIC = DWRITE_RENDERING_MODE.GDI_CLASSIC;
pub const DWRITE_RENDERING_MODE_GDI_NATURAL = DWRITE_RENDERING_MODE.GDI_NATURAL;
pub const DWRITE_RENDERING_MODE_NATURAL = DWRITE_RENDERING_MODE.NATURAL;
pub const DWRITE_RENDERING_MODE_NATURAL_SYMMETRIC = DWRITE_RENDERING_MODE.NATURAL_SYMMETRIC;
pub const DWRITE_RENDERING_MODE_OUTLINE = DWRITE_RENDERING_MODE.OUTLINE;
pub const DWRITE_RENDERING_MODE_CLEARTYPE_GDI_CLASSIC = DWRITE_RENDERING_MODE.GDI_CLASSIC;
pub const DWRITE_RENDERING_MODE_CLEARTYPE_GDI_NATURAL = DWRITE_RENDERING_MODE.GDI_NATURAL;
pub const DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL = DWRITE_RENDERING_MODE.NATURAL;
pub const DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL_SYMMETRIC = DWRITE_RENDERING_MODE.NATURAL_SYMMETRIC;
pub const DWRITE_MATRIX = extern struct {
m11: f32,
m12: f32,
m21: f32,
m22: f32,
dx: f32,
dy: f32,
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IDWriteRenderingParams_Value = Guid.initString("2f0da53a-2add-47cd-82ee-d9ec34688e75");
pub const IID_IDWriteRenderingParams = &IID_IDWriteRenderingParams_Value;
pub const IDWriteRenderingParams = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetGamma: fn(
self: *const IDWriteRenderingParams,
) callconv(@import("std").os.windows.WINAPI) f32,
GetEnhancedContrast: fn(
self: *const IDWriteRenderingParams,
) callconv(@import("std").os.windows.WINAPI) f32,
GetClearTypeLevel: fn(
self: *const IDWriteRenderingParams,
) callconv(@import("std").os.windows.WINAPI) f32,
GetPixelGeometry: fn(
self: *const IDWriteRenderingParams,
) callconv(@import("std").os.windows.WINAPI) DWRITE_PIXEL_GEOMETRY,
GetRenderingMode: fn(
self: *const IDWriteRenderingParams,
) callconv(@import("std").os.windows.WINAPI) DWRITE_RENDERING_MODE,
};
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 IDWriteRenderingParams_GetGamma(self: *const T) callconv(.Inline) f32 {
return @ptrCast(*const IDWriteRenderingParams.VTable, self.vtable).GetGamma(@ptrCast(*const IDWriteRenderingParams, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteRenderingParams_GetEnhancedContrast(self: *const T) callconv(.Inline) f32 {
return @ptrCast(*const IDWriteRenderingParams.VTable, self.vtable).GetEnhancedContrast(@ptrCast(*const IDWriteRenderingParams, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteRenderingParams_GetClearTypeLevel(self: *const T) callconv(.Inline) f32 {
return @ptrCast(*const IDWriteRenderingParams.VTable, self.vtable).GetClearTypeLevel(@ptrCast(*const IDWriteRenderingParams, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteRenderingParams_GetPixelGeometry(self: *const T) callconv(.Inline) DWRITE_PIXEL_GEOMETRY {
return @ptrCast(*const IDWriteRenderingParams.VTable, self.vtable).GetPixelGeometry(@ptrCast(*const IDWriteRenderingParams, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteRenderingParams_GetRenderingMode(self: *const T) callconv(.Inline) DWRITE_RENDERING_MODE {
return @ptrCast(*const IDWriteRenderingParams.VTable, self.vtable).GetRenderingMode(@ptrCast(*const IDWriteRenderingParams, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IDWriteFontFace_Value = Guid.initString("5f49804d-7024-4d43-bfa9-d25984f53849");
pub const IID_IDWriteFontFace = &IID_IDWriteFontFace_Value;
pub const IDWriteFontFace = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetType: fn(
self: *const IDWriteFontFace,
) callconv(@import("std").os.windows.WINAPI) DWRITE_FONT_FACE_TYPE,
GetFiles: fn(
self: *const IDWriteFontFace,
numberOfFiles: ?*u32,
fontFiles: ?[*]?*IDWriteFontFile,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetIndex: fn(
self: *const IDWriteFontFace,
) callconv(@import("std").os.windows.WINAPI) u32,
GetSimulations: fn(
self: *const IDWriteFontFace,
) callconv(@import("std").os.windows.WINAPI) DWRITE_FONT_SIMULATIONS,
IsSymbolFont: fn(
self: *const IDWriteFontFace,
) callconv(@import("std").os.windows.WINAPI) BOOL,
GetMetrics: fn(
self: *const IDWriteFontFace,
fontFaceMetrics: ?*DWRITE_FONT_METRICS,
) callconv(@import("std").os.windows.WINAPI) void,
GetGlyphCount: fn(
self: *const IDWriteFontFace,
) callconv(@import("std").os.windows.WINAPI) u16,
GetDesignGlyphMetrics: fn(
self: *const IDWriteFontFace,
glyphIndices: [*:0]const u16,
glyphCount: u32,
glyphMetrics: [*]DWRITE_GLYPH_METRICS,
isSideways: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetGlyphIndices: fn(
self: *const IDWriteFontFace,
codePoints: [*]const u32,
codePointCount: u32,
glyphIndices: [*:0]u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TryGetFontTable: fn(
self: *const IDWriteFontFace,
openTypeTableTag: u32,
tableData: ?*const ?*anyopaque,
tableSize: ?*u32,
tableContext: ?*?*anyopaque,
exists: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ReleaseFontTable: fn(
self: *const IDWriteFontFace,
tableContext: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) void,
GetGlyphRunOutline: fn(
self: *const IDWriteFontFace,
emSize: f32,
glyphIndices: [*:0]const u16,
glyphAdvances: ?[*]const f32,
glyphOffsets: ?[*]const DWRITE_GLYPH_OFFSET,
glyphCount: u32,
isSideways: BOOL,
isRightToLeft: BOOL,
geometrySink: ?*ID2D1SimplifiedGeometrySink,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetRecommendedRenderingMode: fn(
self: *const IDWriteFontFace,
emSize: f32,
pixelsPerDip: f32,
measuringMode: DWRITE_MEASURING_MODE,
renderingParams: ?*IDWriteRenderingParams,
renderingMode: ?*DWRITE_RENDERING_MODE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetGdiCompatibleMetrics: fn(
self: *const IDWriteFontFace,
emSize: f32,
pixelsPerDip: f32,
transform: ?*const DWRITE_MATRIX,
fontFaceMetrics: ?*DWRITE_FONT_METRICS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetGdiCompatibleGlyphMetrics: fn(
self: *const IDWriteFontFace,
emSize: f32,
pixelsPerDip: f32,
transform: ?*const DWRITE_MATRIX,
useGdiNatural: BOOL,
glyphIndices: [*:0]const u16,
glyphCount: u32,
glyphMetrics: [*]DWRITE_GLYPH_METRICS,
isSideways: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace_GetType(self: *const T) callconv(.Inline) DWRITE_FONT_FACE_TYPE {
return @ptrCast(*const IDWriteFontFace.VTable, self.vtable).GetType(@ptrCast(*const IDWriteFontFace, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace_GetFiles(self: *const T, numberOfFiles: ?*u32, fontFiles: ?[*]?*IDWriteFontFile) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFace.VTable, self.vtable).GetFiles(@ptrCast(*const IDWriteFontFace, self), numberOfFiles, fontFiles);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace_GetIndex(self: *const T) callconv(.Inline) u32 {
return @ptrCast(*const IDWriteFontFace.VTable, self.vtable).GetIndex(@ptrCast(*const IDWriteFontFace, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace_GetSimulations(self: *const T) callconv(.Inline) DWRITE_FONT_SIMULATIONS {
return @ptrCast(*const IDWriteFontFace.VTable, self.vtable).GetSimulations(@ptrCast(*const IDWriteFontFace, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace_IsSymbolFont(self: *const T) callconv(.Inline) BOOL {
return @ptrCast(*const IDWriteFontFace.VTable, self.vtable).IsSymbolFont(@ptrCast(*const IDWriteFontFace, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace_GetMetrics(self: *const T, fontFaceMetrics: ?*DWRITE_FONT_METRICS) callconv(.Inline) void {
return @ptrCast(*const IDWriteFontFace.VTable, self.vtable).GetMetrics(@ptrCast(*const IDWriteFontFace, self), fontFaceMetrics);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace_GetGlyphCount(self: *const T) callconv(.Inline) u16 {
return @ptrCast(*const IDWriteFontFace.VTable, self.vtable).GetGlyphCount(@ptrCast(*const IDWriteFontFace, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace_GetDesignGlyphMetrics(self: *const T, glyphIndices: [*:0]const u16, glyphCount: u32, glyphMetrics: [*]DWRITE_GLYPH_METRICS, isSideways: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFace.VTable, self.vtable).GetDesignGlyphMetrics(@ptrCast(*const IDWriteFontFace, self), glyphIndices, glyphCount, glyphMetrics, isSideways);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace_GetGlyphIndices(self: *const T, codePoints: [*]const u32, codePointCount: u32, glyphIndices: [*:0]u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFace.VTable, self.vtable).GetGlyphIndices(@ptrCast(*const IDWriteFontFace, self), codePoints, codePointCount, glyphIndices);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace_TryGetFontTable(self: *const T, openTypeTableTag: u32, tableData: ?*const ?*anyopaque, tableSize: ?*u32, tableContext: ?*?*anyopaque, exists: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFace.VTable, self.vtable).TryGetFontTable(@ptrCast(*const IDWriteFontFace, self), openTypeTableTag, tableData, tableSize, tableContext, exists);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace_ReleaseFontTable(self: *const T, tableContext: ?*anyopaque) callconv(.Inline) void {
return @ptrCast(*const IDWriteFontFace.VTable, self.vtable).ReleaseFontTable(@ptrCast(*const IDWriteFontFace, self), tableContext);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace_GetGlyphRunOutline(self: *const T, emSize: f32, glyphIndices: [*:0]const u16, glyphAdvances: ?[*]const f32, glyphOffsets: ?[*]const DWRITE_GLYPH_OFFSET, glyphCount: u32, isSideways: BOOL, isRightToLeft: BOOL, geometrySink: ?*ID2D1SimplifiedGeometrySink) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFace.VTable, self.vtable).GetGlyphRunOutline(@ptrCast(*const IDWriteFontFace, self), emSize, glyphIndices, glyphAdvances, glyphOffsets, glyphCount, isSideways, isRightToLeft, geometrySink);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace_GetRecommendedRenderingMode(self: *const T, emSize: f32, pixelsPerDip: f32, measuringMode: DWRITE_MEASURING_MODE, renderingParams: ?*IDWriteRenderingParams, renderingMode: ?*DWRITE_RENDERING_MODE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFace.VTable, self.vtable).GetRecommendedRenderingMode(@ptrCast(*const IDWriteFontFace, self), emSize, pixelsPerDip, measuringMode, renderingParams, renderingMode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace_GetGdiCompatibleMetrics(self: *const T, emSize: f32, pixelsPerDip: f32, transform: ?*const DWRITE_MATRIX, fontFaceMetrics: ?*DWRITE_FONT_METRICS) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFace.VTable, self.vtable).GetGdiCompatibleMetrics(@ptrCast(*const IDWriteFontFace, self), emSize, pixelsPerDip, transform, fontFaceMetrics);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace_GetGdiCompatibleGlyphMetrics(self: *const T, emSize: f32, pixelsPerDip: f32, transform: ?*const DWRITE_MATRIX, useGdiNatural: BOOL, glyphIndices: [*:0]const u16, glyphCount: u32, glyphMetrics: [*]DWRITE_GLYPH_METRICS, isSideways: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFace.VTable, self.vtable).GetGdiCompatibleGlyphMetrics(@ptrCast(*const IDWriteFontFace, self), emSize, pixelsPerDip, transform, useGdiNatural, glyphIndices, glyphCount, glyphMetrics, isSideways);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IDWriteFontCollectionLoader_Value = Guid.initString("cca920e4-52f0-492b-bfa8-29c72ee0a468");
pub const IID_IDWriteFontCollectionLoader = &IID_IDWriteFontCollectionLoader_Value;
pub const IDWriteFontCollectionLoader = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
CreateEnumeratorFromKey: fn(
self: *const IDWriteFontCollectionLoader,
factory: ?*IDWriteFactory,
// TODO: what to do with BytesParamIndex 2?
collectionKey: ?*const anyopaque,
collectionKeySize: u32,
fontFileEnumerator: ?*?*IDWriteFontFileEnumerator,
) 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 IDWriteFontCollectionLoader_CreateEnumeratorFromKey(self: *const T, factory: ?*IDWriteFactory, collectionKey: ?*const anyopaque, collectionKeySize: u32, fontFileEnumerator: ?*?*IDWriteFontFileEnumerator) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontCollectionLoader.VTable, self.vtable).CreateEnumeratorFromKey(@ptrCast(*const IDWriteFontCollectionLoader, self), factory, collectionKey, collectionKeySize, fontFileEnumerator);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IDWriteFontFileEnumerator_Value = Guid.initString("72755049-5ff7-435d-8348-4be97cfa6c7c");
pub const IID_IDWriteFontFileEnumerator = &IID_IDWriteFontFileEnumerator_Value;
pub const IDWriteFontFileEnumerator = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
MoveNext: fn(
self: *const IDWriteFontFileEnumerator,
hasCurrentFile: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCurrentFontFile: fn(
self: *const IDWriteFontFileEnumerator,
fontFile: ?*?*IDWriteFontFile,
) 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 IDWriteFontFileEnumerator_MoveNext(self: *const T, hasCurrentFile: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFileEnumerator.VTable, self.vtable).MoveNext(@ptrCast(*const IDWriteFontFileEnumerator, self), hasCurrentFile);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFileEnumerator_GetCurrentFontFile(self: *const T, fontFile: ?*?*IDWriteFontFile) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFileEnumerator.VTable, self.vtable).GetCurrentFontFile(@ptrCast(*const IDWriteFontFileEnumerator, self), fontFile);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IDWriteLocalizedStrings_Value = Guid.initString("08256209-099a-4b34-b86d-c22b110e7771");
pub const IID_IDWriteLocalizedStrings = &IID_IDWriteLocalizedStrings_Value;
pub const IDWriteLocalizedStrings = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetCount: fn(
self: *const IDWriteLocalizedStrings,
) callconv(@import("std").os.windows.WINAPI) u32,
FindLocaleName: fn(
self: *const IDWriteLocalizedStrings,
localeName: ?[*:0]const u16,
index: ?*u32,
exists: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLocaleNameLength: fn(
self: *const IDWriteLocalizedStrings,
index: u32,
length: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLocaleName: fn(
self: *const IDWriteLocalizedStrings,
index: u32,
localeName: [*:0]u16,
size: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetStringLength: fn(
self: *const IDWriteLocalizedStrings,
index: u32,
length: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetString: fn(
self: *const IDWriteLocalizedStrings,
index: u32,
stringBuffer: [*:0]u16,
size: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteLocalizedStrings_GetCount(self: *const T) callconv(.Inline) u32 {
return @ptrCast(*const IDWriteLocalizedStrings.VTable, self.vtable).GetCount(@ptrCast(*const IDWriteLocalizedStrings, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteLocalizedStrings_FindLocaleName(self: *const T, localeName: ?[*:0]const u16, index: ?*u32, exists: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteLocalizedStrings.VTable, self.vtable).FindLocaleName(@ptrCast(*const IDWriteLocalizedStrings, self), localeName, index, exists);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteLocalizedStrings_GetLocaleNameLength(self: *const T, index: u32, length: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteLocalizedStrings.VTable, self.vtable).GetLocaleNameLength(@ptrCast(*const IDWriteLocalizedStrings, self), index, length);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteLocalizedStrings_GetLocaleName(self: *const T, index: u32, localeName: [*:0]u16, size: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteLocalizedStrings.VTable, self.vtable).GetLocaleName(@ptrCast(*const IDWriteLocalizedStrings, self), index, localeName, size);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteLocalizedStrings_GetStringLength(self: *const T, index: u32, length: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteLocalizedStrings.VTable, self.vtable).GetStringLength(@ptrCast(*const IDWriteLocalizedStrings, self), index, length);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteLocalizedStrings_GetString(self: *const T, index: u32, stringBuffer: [*:0]u16, size: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteLocalizedStrings.VTable, self.vtable).GetString(@ptrCast(*const IDWriteLocalizedStrings, self), index, stringBuffer, size);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IDWriteFontCollection_Value = Guid.initString("a84cee02-3eea-4eee-a827-87c1a02a0fcc");
pub const IID_IDWriteFontCollection = &IID_IDWriteFontCollection_Value;
pub const IDWriteFontCollection = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetFontFamilyCount: fn(
self: *const IDWriteFontCollection,
) callconv(@import("std").os.windows.WINAPI) u32,
GetFontFamily: fn(
self: *const IDWriteFontCollection,
index: u32,
fontFamily: ?*?*IDWriteFontFamily,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FindFamilyName: fn(
self: *const IDWriteFontCollection,
familyName: ?[*:0]const u16,
index: ?*u32,
exists: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontFromFontFace: fn(
self: *const IDWriteFontCollection,
fontFace: ?*IDWriteFontFace,
font: ?*?*IDWriteFont,
) 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 IDWriteFontCollection_GetFontFamilyCount(self: *const T) callconv(.Inline) u32 {
return @ptrCast(*const IDWriteFontCollection.VTable, self.vtable).GetFontFamilyCount(@ptrCast(*const IDWriteFontCollection, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontCollection_GetFontFamily(self: *const T, index: u32, fontFamily: ?*?*IDWriteFontFamily) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontCollection.VTable, self.vtable).GetFontFamily(@ptrCast(*const IDWriteFontCollection, self), index, fontFamily);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontCollection_FindFamilyName(self: *const T, familyName: ?[*:0]const u16, index: ?*u32, exists: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontCollection.VTable, self.vtable).FindFamilyName(@ptrCast(*const IDWriteFontCollection, self), familyName, index, exists);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontCollection_GetFontFromFontFace(self: *const T, fontFace: ?*IDWriteFontFace, font: ?*?*IDWriteFont) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontCollection.VTable, self.vtable).GetFontFromFontFace(@ptrCast(*const IDWriteFontCollection, self), fontFace, font);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IDWriteFontList_Value = Guid.initString("1a0d8438-1d97-4ec1-aef9-a2fb86ed6acb");
pub const IID_IDWriteFontList = &IID_IDWriteFontList_Value;
pub const IDWriteFontList = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetFontCollection: fn(
self: *const IDWriteFontList,
fontCollection: ?*?*IDWriteFontCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontCount: fn(
self: *const IDWriteFontList,
) callconv(@import("std").os.windows.WINAPI) u32,
GetFont: fn(
self: *const IDWriteFontList,
index: u32,
font: ?*?*IDWriteFont,
) 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 IDWriteFontList_GetFontCollection(self: *const T, fontCollection: ?*?*IDWriteFontCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontList.VTable, self.vtable).GetFontCollection(@ptrCast(*const IDWriteFontList, self), fontCollection);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontList_GetFontCount(self: *const T) callconv(.Inline) u32 {
return @ptrCast(*const IDWriteFontList.VTable, self.vtable).GetFontCount(@ptrCast(*const IDWriteFontList, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontList_GetFont(self: *const T, index: u32, font: ?*?*IDWriteFont) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontList.VTable, self.vtable).GetFont(@ptrCast(*const IDWriteFontList, self), index, font);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IDWriteFontFamily_Value = Guid.initString("da20d8ef-812a-4c43-9802-62ec4abd7add");
pub const IID_IDWriteFontFamily = &IID_IDWriteFontFamily_Value;
pub const IDWriteFontFamily = extern struct {
pub const VTable = extern struct {
base: IDWriteFontList.VTable,
GetFamilyNames: fn(
self: *const IDWriteFontFamily,
names: ?*?*IDWriteLocalizedStrings,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFirstMatchingFont: fn(
self: *const IDWriteFontFamily,
weight: DWRITE_FONT_WEIGHT,
stretch: DWRITE_FONT_STRETCH,
style: DWRITE_FONT_STYLE,
matchingFont: ?*?*IDWriteFont,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetMatchingFonts: fn(
self: *const IDWriteFontFamily,
weight: DWRITE_FONT_WEIGHT,
stretch: DWRITE_FONT_STRETCH,
style: DWRITE_FONT_STYLE,
matchingFonts: ?*?*IDWriteFontList,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFontList.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFamily_GetFamilyNames(self: *const T, names: ?*?*IDWriteLocalizedStrings) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFamily.VTable, self.vtable).GetFamilyNames(@ptrCast(*const IDWriteFontFamily, self), names);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFamily_GetFirstMatchingFont(self: *const T, weight: DWRITE_FONT_WEIGHT, stretch: DWRITE_FONT_STRETCH, style: DWRITE_FONT_STYLE, matchingFont: ?*?*IDWriteFont) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFamily.VTable, self.vtable).GetFirstMatchingFont(@ptrCast(*const IDWriteFontFamily, self), weight, stretch, style, matchingFont);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFamily_GetMatchingFonts(self: *const T, weight: DWRITE_FONT_WEIGHT, stretch: DWRITE_FONT_STRETCH, style: DWRITE_FONT_STYLE, matchingFonts: ?*?*IDWriteFontList) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFamily.VTable, self.vtable).GetMatchingFonts(@ptrCast(*const IDWriteFontFamily, self), weight, stretch, style, matchingFonts);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IDWriteFont_Value = Guid.initString("acd16696-8c14-4f5d-877e-fe3fc1d32737");
pub const IID_IDWriteFont = &IID_IDWriteFont_Value;
pub const IDWriteFont = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetFontFamily: fn(
self: *const IDWriteFont,
fontFamily: ?*?*IDWriteFontFamily,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetWeight: fn(
self: *const IDWriteFont,
) callconv(@import("std").os.windows.WINAPI) DWRITE_FONT_WEIGHT,
GetStretch: fn(
self: *const IDWriteFont,
) callconv(@import("std").os.windows.WINAPI) DWRITE_FONT_STRETCH,
GetStyle: fn(
self: *const IDWriteFont,
) callconv(@import("std").os.windows.WINAPI) DWRITE_FONT_STYLE,
IsSymbolFont: fn(
self: *const IDWriteFont,
) callconv(@import("std").os.windows.WINAPI) BOOL,
GetFaceNames: fn(
self: *const IDWriteFont,
names: ?*?*IDWriteLocalizedStrings,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetInformationalStrings: fn(
self: *const IDWriteFont,
informationalStringID: DWRITE_INFORMATIONAL_STRING_ID,
informationalStrings: ?*?*IDWriteLocalizedStrings,
exists: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSimulations: fn(
self: *const IDWriteFont,
) callconv(@import("std").os.windows.WINAPI) DWRITE_FONT_SIMULATIONS,
GetMetrics: fn(
self: *const IDWriteFont,
fontMetrics: ?*DWRITE_FONT_METRICS,
) callconv(@import("std").os.windows.WINAPI) void,
HasCharacter: fn(
self: *const IDWriteFont,
unicodeValue: u32,
exists: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateFontFace: fn(
self: *const IDWriteFont,
fontFace: ?*?*IDWriteFontFace,
) 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 IDWriteFont_GetFontFamily(self: *const T, fontFamily: ?*?*IDWriteFontFamily) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFont.VTable, self.vtable).GetFontFamily(@ptrCast(*const IDWriteFont, self), fontFamily);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFont_GetWeight(self: *const T) callconv(.Inline) DWRITE_FONT_WEIGHT {
return @ptrCast(*const IDWriteFont.VTable, self.vtable).GetWeight(@ptrCast(*const IDWriteFont, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFont_GetStretch(self: *const T) callconv(.Inline) DWRITE_FONT_STRETCH {
return @ptrCast(*const IDWriteFont.VTable, self.vtable).GetStretch(@ptrCast(*const IDWriteFont, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFont_GetStyle(self: *const T) callconv(.Inline) DWRITE_FONT_STYLE {
return @ptrCast(*const IDWriteFont.VTable, self.vtable).GetStyle(@ptrCast(*const IDWriteFont, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFont_IsSymbolFont(self: *const T) callconv(.Inline) BOOL {
return @ptrCast(*const IDWriteFont.VTable, self.vtable).IsSymbolFont(@ptrCast(*const IDWriteFont, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFont_GetFaceNames(self: *const T, names: ?*?*IDWriteLocalizedStrings) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFont.VTable, self.vtable).GetFaceNames(@ptrCast(*const IDWriteFont, self), names);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFont_GetInformationalStrings(self: *const T, informationalStringID: DWRITE_INFORMATIONAL_STRING_ID, informationalStrings: ?*?*IDWriteLocalizedStrings, exists: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFont.VTable, self.vtable).GetInformationalStrings(@ptrCast(*const IDWriteFont, self), informationalStringID, informationalStrings, exists);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFont_GetSimulations(self: *const T) callconv(.Inline) DWRITE_FONT_SIMULATIONS {
return @ptrCast(*const IDWriteFont.VTable, self.vtable).GetSimulations(@ptrCast(*const IDWriteFont, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFont_GetMetrics(self: *const T, fontMetrics: ?*DWRITE_FONT_METRICS) callconv(.Inline) void {
return @ptrCast(*const IDWriteFont.VTable, self.vtable).GetMetrics(@ptrCast(*const IDWriteFont, self), fontMetrics);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFont_HasCharacter(self: *const T, unicodeValue: u32, exists: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFont.VTable, self.vtable).HasCharacter(@ptrCast(*const IDWriteFont, self), unicodeValue, exists);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFont_CreateFontFace(self: *const T, fontFace: ?*?*IDWriteFontFace) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFont.VTable, self.vtable).CreateFontFace(@ptrCast(*const IDWriteFont, self), fontFace);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DWRITE_READING_DIRECTION = enum(i32) {
LEFT_TO_RIGHT = 0,
RIGHT_TO_LEFT = 1,
TOP_TO_BOTTOM = 2,
BOTTOM_TO_TOP = 3,
};
pub const DWRITE_READING_DIRECTION_LEFT_TO_RIGHT = DWRITE_READING_DIRECTION.LEFT_TO_RIGHT;
pub const DWRITE_READING_DIRECTION_RIGHT_TO_LEFT = DWRITE_READING_DIRECTION.RIGHT_TO_LEFT;
pub const DWRITE_READING_DIRECTION_TOP_TO_BOTTOM = DWRITE_READING_DIRECTION.TOP_TO_BOTTOM;
pub const DWRITE_READING_DIRECTION_BOTTOM_TO_TOP = DWRITE_READING_DIRECTION.BOTTOM_TO_TOP;
pub const DWRITE_FLOW_DIRECTION = enum(i32) {
TOP_TO_BOTTOM = 0,
BOTTOM_TO_TOP = 1,
LEFT_TO_RIGHT = 2,
RIGHT_TO_LEFT = 3,
};
pub const DWRITE_FLOW_DIRECTION_TOP_TO_BOTTOM = DWRITE_FLOW_DIRECTION.TOP_TO_BOTTOM;
pub const DWRITE_FLOW_DIRECTION_BOTTOM_TO_TOP = DWRITE_FLOW_DIRECTION.BOTTOM_TO_TOP;
pub const DWRITE_FLOW_DIRECTION_LEFT_TO_RIGHT = DWRITE_FLOW_DIRECTION.LEFT_TO_RIGHT;
pub const DWRITE_FLOW_DIRECTION_RIGHT_TO_LEFT = DWRITE_FLOW_DIRECTION.RIGHT_TO_LEFT;
pub const DWRITE_TEXT_ALIGNMENT = enum(i32) {
LEADING = 0,
TRAILING = 1,
CENTER = 2,
JUSTIFIED = 3,
};
pub const DWRITE_TEXT_ALIGNMENT_LEADING = DWRITE_TEXT_ALIGNMENT.LEADING;
pub const DWRITE_TEXT_ALIGNMENT_TRAILING = DWRITE_TEXT_ALIGNMENT.TRAILING;
pub const DWRITE_TEXT_ALIGNMENT_CENTER = DWRITE_TEXT_ALIGNMENT.CENTER;
pub const DWRITE_TEXT_ALIGNMENT_JUSTIFIED = DWRITE_TEXT_ALIGNMENT.JUSTIFIED;
pub const DWRITE_PARAGRAPH_ALIGNMENT = enum(i32) {
NEAR = 0,
FAR = 1,
CENTER = 2,
};
pub const DWRITE_PARAGRAPH_ALIGNMENT_NEAR = DWRITE_PARAGRAPH_ALIGNMENT.NEAR;
pub const DWRITE_PARAGRAPH_ALIGNMENT_FAR = DWRITE_PARAGRAPH_ALIGNMENT.FAR;
pub const DWRITE_PARAGRAPH_ALIGNMENT_CENTER = DWRITE_PARAGRAPH_ALIGNMENT.CENTER;
pub const DWRITE_WORD_WRAPPING = enum(i32) {
WRAP = 0,
NO_WRAP = 1,
EMERGENCY_BREAK = 2,
WHOLE_WORD = 3,
CHARACTER = 4,
};
pub const DWRITE_WORD_WRAPPING_WRAP = DWRITE_WORD_WRAPPING.WRAP;
pub const DWRITE_WORD_WRAPPING_NO_WRAP = DWRITE_WORD_WRAPPING.NO_WRAP;
pub const DWRITE_WORD_WRAPPING_EMERGENCY_BREAK = DWRITE_WORD_WRAPPING.EMERGENCY_BREAK;
pub const DWRITE_WORD_WRAPPING_WHOLE_WORD = DWRITE_WORD_WRAPPING.WHOLE_WORD;
pub const DWRITE_WORD_WRAPPING_CHARACTER = DWRITE_WORD_WRAPPING.CHARACTER;
pub const DWRITE_LINE_SPACING_METHOD = enum(i32) {
DEFAULT = 0,
UNIFORM = 1,
PROPORTIONAL = 2,
};
pub const DWRITE_LINE_SPACING_METHOD_DEFAULT = DWRITE_LINE_SPACING_METHOD.DEFAULT;
pub const DWRITE_LINE_SPACING_METHOD_UNIFORM = DWRITE_LINE_SPACING_METHOD.UNIFORM;
pub const DWRITE_LINE_SPACING_METHOD_PROPORTIONAL = DWRITE_LINE_SPACING_METHOD.PROPORTIONAL;
pub const DWRITE_TRIMMING_GRANULARITY = enum(i32) {
NONE = 0,
CHARACTER = 1,
WORD = 2,
};
pub const DWRITE_TRIMMING_GRANULARITY_NONE = DWRITE_TRIMMING_GRANULARITY.NONE;
pub const DWRITE_TRIMMING_GRANULARITY_CHARACTER = DWRITE_TRIMMING_GRANULARITY.CHARACTER;
pub const DWRITE_TRIMMING_GRANULARITY_WORD = DWRITE_TRIMMING_GRANULARITY.WORD;
pub const DWRITE_FONT_FEATURE_TAG = enum(u32) {
ALTERNATIVE_FRACTIONS = 1668441697,
PETITE_CAPITALS_FROM_CAPITALS = 1668297315,
SMALL_CAPITALS_FROM_CAPITALS = 1668493923,
CONTEXTUAL_ALTERNATES = 1953259875,
CASE_SENSITIVE_FORMS = 1702060387,
GLYPH_COMPOSITION_DECOMPOSITION = 1886217059,
CONTEXTUAL_LIGATURES = 1734962275,
CAPITAL_SPACING = 1886613603,
CONTEXTUAL_SWASH = 1752658787,
CURSIVE_POSITIONING = 1936880995,
DEFAULT = 1953261156,
DISCRETIONARY_LIGATURES = 1734962276,
EXPERT_FORMS = 1953527909,
FRACTIONS = 1667330662,
FULL_WIDTH = 1684633446,
HALF_FORMS = 1718378856,
HALANT_FORMS = 1852596584,
ALTERNATE_HALF_WIDTH = 1953259880,
HISTORICAL_FORMS = 1953720680,
HORIZONTAL_KANA_ALTERNATES = 1634626408,
HISTORICAL_LIGATURES = 1734962280,
HALF_WIDTH = 1684633448,
HOJO_KANJI_FORMS = 1869246312,
JIS04_FORMS = 875589738,
JIS78_FORMS = 943157354,
JIS83_FORMS = 859336810,
JIS90_FORMS = 809070698,
KERNING = 1852990827,
STANDARD_LIGATURES = 1634167148,
LINING_FIGURES = 1836412524,
LOCALIZED_FORMS = 1818455916,
MARK_POSITIONING = 1802658157,
MATHEMATICAL_GREEK = 1802659693,
MARK_TO_MARK_POSITIONING = 1802333037,
ALTERNATE_ANNOTATION_FORMS = 1953259886,
NLC_KANJI_FORMS = 1801677934,
OLD_STYLE_FIGURES = 1836412527,
ORDINALS = 1852076655,
PROPORTIONAL_ALTERNATE_WIDTH = 1953259888,
PETITE_CAPITALS = 1885430640,
PROPORTIONAL_FIGURES = 1836412528,
PROPORTIONAL_WIDTHS = 1684633456,
QUARTER_WIDTHS = 1684633457,
REQUIRED_LIGATURES = 1734962290,
RUBY_NOTATION_FORMS = 2036495730,
STYLISTIC_ALTERNATES = 1953259891,
SCIENTIFIC_INFERIORS = 1718511987,
SMALL_CAPITALS = 1885564275,
SIMPLIFIED_FORMS = 1819307379,
STYLISTIC_SET_1 = 825258867,
STYLISTIC_SET_2 = 842036083,
STYLISTIC_SET_3 = 858813299,
STYLISTIC_SET_4 = 875590515,
STYLISTIC_SET_5 = 892367731,
STYLISTIC_SET_6 = 909144947,
STYLISTIC_SET_7 = 925922163,
STYLISTIC_SET_8 = 942699379,
STYLISTIC_SET_9 = 959476595,
STYLISTIC_SET_10 = 808547187,
STYLISTIC_SET_11 = 825324403,
STYLISTIC_SET_12 = 842101619,
STYLISTIC_SET_13 = 858878835,
STYLISTIC_SET_14 = 875656051,
STYLISTIC_SET_15 = 892433267,
STYLISTIC_SET_16 = 909210483,
STYLISTIC_SET_17 = 925987699,
STYLISTIC_SET_18 = 942764915,
STYLISTIC_SET_19 = 959542131,
STYLISTIC_SET_20 = 808612723,
SUBSCRIPT = 1935832435,
SUPERSCRIPT = 1936749939,
SWASH = 1752397683,
TITLING = 1819568500,
TRADITIONAL_NAME_FORMS = 1835101812,
TABULAR_FIGURES = 1836412532,
TRADITIONAL_FORMS = 1684107892,
THIRD_WIDTHS = 1684633460,
UNICASE = 1667853941,
VERTICAL_WRITING = 1953654134,
VERTICAL_ALTERNATES_AND_ROTATION = 846492278,
SLASHED_ZERO = 1869768058,
};
pub const DWRITE_FONT_FEATURE_TAG_ALTERNATIVE_FRACTIONS = DWRITE_FONT_FEATURE_TAG.ALTERNATIVE_FRACTIONS;
pub const DWRITE_FONT_FEATURE_TAG_PETITE_CAPITALS_FROM_CAPITALS = DWRITE_FONT_FEATURE_TAG.PETITE_CAPITALS_FROM_CAPITALS;
pub const DWRITE_FONT_FEATURE_TAG_SMALL_CAPITALS_FROM_CAPITALS = DWRITE_FONT_FEATURE_TAG.SMALL_CAPITALS_FROM_CAPITALS;
pub const DWRITE_FONT_FEATURE_TAG_CONTEXTUAL_ALTERNATES = DWRITE_FONT_FEATURE_TAG.CONTEXTUAL_ALTERNATES;
pub const DWRITE_FONT_FEATURE_TAG_CASE_SENSITIVE_FORMS = DWRITE_FONT_FEATURE_TAG.CASE_SENSITIVE_FORMS;
pub const DWRITE_FONT_FEATURE_TAG_GLYPH_COMPOSITION_DECOMPOSITION = DWRITE_FONT_FEATURE_TAG.GLYPH_COMPOSITION_DECOMPOSITION;
pub const DWRITE_FONT_FEATURE_TAG_CONTEXTUAL_LIGATURES = DWRITE_FONT_FEATURE_TAG.CONTEXTUAL_LIGATURES;
pub const DWRITE_FONT_FEATURE_TAG_CAPITAL_SPACING = DWRITE_FONT_FEATURE_TAG.CAPITAL_SPACING;
pub const DWRITE_FONT_FEATURE_TAG_CONTEXTUAL_SWASH = DWRITE_FONT_FEATURE_TAG.CONTEXTUAL_SWASH;
pub const DWRITE_FONT_FEATURE_TAG_CURSIVE_POSITIONING = DWRITE_FONT_FEATURE_TAG.CURSIVE_POSITIONING;
pub const DWRITE_FONT_FEATURE_TAG_DEFAULT = DWRITE_FONT_FEATURE_TAG.DEFAULT;
pub const DWRITE_FONT_FEATURE_TAG_DISCRETIONARY_LIGATURES = DWRITE_FONT_FEATURE_TAG.DISCRETIONARY_LIGATURES;
pub const DWRITE_FONT_FEATURE_TAG_EXPERT_FORMS = DWRITE_FONT_FEATURE_TAG.EXPERT_FORMS;
pub const DWRITE_FONT_FEATURE_TAG_FRACTIONS = DWRITE_FONT_FEATURE_TAG.FRACTIONS;
pub const DWRITE_FONT_FEATURE_TAG_FULL_WIDTH = DWRITE_FONT_FEATURE_TAG.FULL_WIDTH;
pub const DWRITE_FONT_FEATURE_TAG_HALF_FORMS = DWRITE_FONT_FEATURE_TAG.HALF_FORMS;
pub const DWRITE_FONT_FEATURE_TAG_HALANT_FORMS = DWRITE_FONT_FEATURE_TAG.HALANT_FORMS;
pub const DWRITE_FONT_FEATURE_TAG_ALTERNATE_HALF_WIDTH = DWRITE_FONT_FEATURE_TAG.ALTERNATE_HALF_WIDTH;
pub const DWRITE_FONT_FEATURE_TAG_HISTORICAL_FORMS = DWRITE_FONT_FEATURE_TAG.HISTORICAL_FORMS;
pub const DWRITE_FONT_FEATURE_TAG_HORIZONTAL_KANA_ALTERNATES = DWRITE_FONT_FEATURE_TAG.HORIZONTAL_KANA_ALTERNATES;
pub const DWRITE_FONT_FEATURE_TAG_HISTORICAL_LIGATURES = DWRITE_FONT_FEATURE_TAG.HISTORICAL_LIGATURES;
pub const DWRITE_FONT_FEATURE_TAG_HALF_WIDTH = DWRITE_FONT_FEATURE_TAG.HALF_WIDTH;
pub const DWRITE_FONT_FEATURE_TAG_HOJO_KANJI_FORMS = DWRITE_FONT_FEATURE_TAG.HOJO_KANJI_FORMS;
pub const DWRITE_FONT_FEATURE_TAG_JIS04_FORMS = DWRITE_FONT_FEATURE_TAG.JIS04_FORMS;
pub const DWRITE_FONT_FEATURE_TAG_JIS78_FORMS = DWRITE_FONT_FEATURE_TAG.JIS78_FORMS;
pub const DWRITE_FONT_FEATURE_TAG_JIS83_FORMS = DWRITE_FONT_FEATURE_TAG.JIS83_FORMS;
pub const DWRITE_FONT_FEATURE_TAG_JIS90_FORMS = DWRITE_FONT_FEATURE_TAG.JIS90_FORMS;
pub const DWRITE_FONT_FEATURE_TAG_KERNING = DWRITE_FONT_FEATURE_TAG.KERNING;
pub const DWRITE_FONT_FEATURE_TAG_STANDARD_LIGATURES = DWRITE_FONT_FEATURE_TAG.STANDARD_LIGATURES;
pub const DWRITE_FONT_FEATURE_TAG_LINING_FIGURES = DWRITE_FONT_FEATURE_TAG.LINING_FIGURES;
pub const DWRITE_FONT_FEATURE_TAG_LOCALIZED_FORMS = DWRITE_FONT_FEATURE_TAG.LOCALIZED_FORMS;
pub const DWRITE_FONT_FEATURE_TAG_MARK_POSITIONING = DWRITE_FONT_FEATURE_TAG.MARK_POSITIONING;
pub const DWRITE_FONT_FEATURE_TAG_MATHEMATICAL_GREEK = DWRITE_FONT_FEATURE_TAG.MATHEMATICAL_GREEK;
pub const DWRITE_FONT_FEATURE_TAG_MARK_TO_MARK_POSITIONING = DWRITE_FONT_FEATURE_TAG.MARK_TO_MARK_POSITIONING;
pub const DWRITE_FONT_FEATURE_TAG_ALTERNATE_ANNOTATION_FORMS = DWRITE_FONT_FEATURE_TAG.ALTERNATE_ANNOTATION_FORMS;
pub const DWRITE_FONT_FEATURE_TAG_NLC_KANJI_FORMS = DWRITE_FONT_FEATURE_TAG.NLC_KANJI_FORMS;
pub const DWRITE_FONT_FEATURE_TAG_OLD_STYLE_FIGURES = DWRITE_FONT_FEATURE_TAG.OLD_STYLE_FIGURES;
pub const DWRITE_FONT_FEATURE_TAG_ORDINALS = DWRITE_FONT_FEATURE_TAG.ORDINALS;
pub const DWRITE_FONT_FEATURE_TAG_PROPORTIONAL_ALTERNATE_WIDTH = DWRITE_FONT_FEATURE_TAG.PROPORTIONAL_ALTERNATE_WIDTH;
pub const DWRITE_FONT_FEATURE_TAG_PETITE_CAPITALS = DWRITE_FONT_FEATURE_TAG.PETITE_CAPITALS;
pub const DWRITE_FONT_FEATURE_TAG_PROPORTIONAL_FIGURES = DWRITE_FONT_FEATURE_TAG.PROPORTIONAL_FIGURES;
pub const DWRITE_FONT_FEATURE_TAG_PROPORTIONAL_WIDTHS = DWRITE_FONT_FEATURE_TAG.PROPORTIONAL_WIDTHS;
pub const DWRITE_FONT_FEATURE_TAG_QUARTER_WIDTHS = DWRITE_FONT_FEATURE_TAG.QUARTER_WIDTHS;
pub const DWRITE_FONT_FEATURE_TAG_REQUIRED_LIGATURES = DWRITE_FONT_FEATURE_TAG.REQUIRED_LIGATURES;
pub const DWRITE_FONT_FEATURE_TAG_RUBY_NOTATION_FORMS = DWRITE_FONT_FEATURE_TAG.RUBY_NOTATION_FORMS;
pub const DWRITE_FONT_FEATURE_TAG_STYLISTIC_ALTERNATES = DWRITE_FONT_FEATURE_TAG.STYLISTIC_ALTERNATES;
pub const DWRITE_FONT_FEATURE_TAG_SCIENTIFIC_INFERIORS = DWRITE_FONT_FEATURE_TAG.SCIENTIFIC_INFERIORS;
pub const DWRITE_FONT_FEATURE_TAG_SMALL_CAPITALS = DWRITE_FONT_FEATURE_TAG.SMALL_CAPITALS;
pub const DWRITE_FONT_FEATURE_TAG_SIMPLIFIED_FORMS = DWRITE_FONT_FEATURE_TAG.SIMPLIFIED_FORMS;
pub const DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_1 = DWRITE_FONT_FEATURE_TAG.STYLISTIC_SET_1;
pub const DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_2 = DWRITE_FONT_FEATURE_TAG.STYLISTIC_SET_2;
pub const DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_3 = DWRITE_FONT_FEATURE_TAG.STYLISTIC_SET_3;
pub const DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_4 = DWRITE_FONT_FEATURE_TAG.STYLISTIC_SET_4;
pub const DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_5 = DWRITE_FONT_FEATURE_TAG.STYLISTIC_SET_5;
pub const DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_6 = DWRITE_FONT_FEATURE_TAG.STYLISTIC_SET_6;
pub const DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_7 = DWRITE_FONT_FEATURE_TAG.STYLISTIC_SET_7;
pub const DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_8 = DWRITE_FONT_FEATURE_TAG.STYLISTIC_SET_8;
pub const DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_9 = DWRITE_FONT_FEATURE_TAG.STYLISTIC_SET_9;
pub const DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_10 = DWRITE_FONT_FEATURE_TAG.STYLISTIC_SET_10;
pub const DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_11 = DWRITE_FONT_FEATURE_TAG.STYLISTIC_SET_11;
pub const DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_12 = DWRITE_FONT_FEATURE_TAG.STYLISTIC_SET_12;
pub const DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_13 = DWRITE_FONT_FEATURE_TAG.STYLISTIC_SET_13;
pub const DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_14 = DWRITE_FONT_FEATURE_TAG.STYLISTIC_SET_14;
pub const DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_15 = DWRITE_FONT_FEATURE_TAG.STYLISTIC_SET_15;
pub const DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_16 = DWRITE_FONT_FEATURE_TAG.STYLISTIC_SET_16;
pub const DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_17 = DWRITE_FONT_FEATURE_TAG.STYLISTIC_SET_17;
pub const DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_18 = DWRITE_FONT_FEATURE_TAG.STYLISTIC_SET_18;
pub const DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_19 = DWRITE_FONT_FEATURE_TAG.STYLISTIC_SET_19;
pub const DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_20 = DWRITE_FONT_FEATURE_TAG.STYLISTIC_SET_20;
pub const DWRITE_FONT_FEATURE_TAG_SUBSCRIPT = DWRITE_FONT_FEATURE_TAG.SUBSCRIPT;
pub const DWRITE_FONT_FEATURE_TAG_SUPERSCRIPT = DWRITE_FONT_FEATURE_TAG.SUPERSCRIPT;
pub const DWRITE_FONT_FEATURE_TAG_SWASH = DWRITE_FONT_FEATURE_TAG.SWASH;
pub const DWRITE_FONT_FEATURE_TAG_TITLING = DWRITE_FONT_FEATURE_TAG.TITLING;
pub const DWRITE_FONT_FEATURE_TAG_TRADITIONAL_NAME_FORMS = DWRITE_FONT_FEATURE_TAG.TRADITIONAL_NAME_FORMS;
pub const DWRITE_FONT_FEATURE_TAG_TABULAR_FIGURES = DWRITE_FONT_FEATURE_TAG.TABULAR_FIGURES;
pub const DWRITE_FONT_FEATURE_TAG_TRADITIONAL_FORMS = DWRITE_FONT_FEATURE_TAG.TRADITIONAL_FORMS;
pub const DWRITE_FONT_FEATURE_TAG_THIRD_WIDTHS = DWRITE_FONT_FEATURE_TAG.THIRD_WIDTHS;
pub const DWRITE_FONT_FEATURE_TAG_UNICASE = DWRITE_FONT_FEATURE_TAG.UNICASE;
pub const DWRITE_FONT_FEATURE_TAG_VERTICAL_WRITING = DWRITE_FONT_FEATURE_TAG.VERTICAL_WRITING;
pub const DWRITE_FONT_FEATURE_TAG_VERTICAL_ALTERNATES_AND_ROTATION = DWRITE_FONT_FEATURE_TAG.VERTICAL_ALTERNATES_AND_ROTATION;
pub const DWRITE_FONT_FEATURE_TAG_SLASHED_ZERO = DWRITE_FONT_FEATURE_TAG.SLASHED_ZERO;
pub const DWRITE_TEXT_RANGE = extern struct {
startPosition: u32,
length: u32,
};
pub const DWRITE_FONT_FEATURE = extern struct {
nameTag: DWRITE_FONT_FEATURE_TAG,
parameter: u32,
};
pub const DWRITE_TYPOGRAPHIC_FEATURES = extern struct {
features: ?*DWRITE_FONT_FEATURE,
featureCount: u32,
};
pub const DWRITE_TRIMMING = extern struct {
granularity: DWRITE_TRIMMING_GRANULARITY,
delimiter: u32,
delimiterCount: u32,
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IDWriteTextFormat_Value = Guid.initString("9c906818-31d7-4fd3-a151-7c5e225db55a");
pub const IID_IDWriteTextFormat = &IID_IDWriteTextFormat_Value;
pub const IDWriteTextFormat = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetTextAlignment: fn(
self: *const IDWriteTextFormat,
textAlignment: DWRITE_TEXT_ALIGNMENT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetParagraphAlignment: fn(
self: *const IDWriteTextFormat,
paragraphAlignment: DWRITE_PARAGRAPH_ALIGNMENT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetWordWrapping: fn(
self: *const IDWriteTextFormat,
wordWrapping: DWRITE_WORD_WRAPPING,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetReadingDirection: fn(
self: *const IDWriteTextFormat,
readingDirection: DWRITE_READING_DIRECTION,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetFlowDirection: fn(
self: *const IDWriteTextFormat,
flowDirection: DWRITE_FLOW_DIRECTION,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetIncrementalTabStop: fn(
self: *const IDWriteTextFormat,
incrementalTabStop: f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetTrimming: fn(
self: *const IDWriteTextFormat,
trimmingOptions: ?*const DWRITE_TRIMMING,
trimmingSign: ?*IDWriteInlineObject,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetLineSpacing: fn(
self: *const IDWriteTextFormat,
lineSpacingMethod: DWRITE_LINE_SPACING_METHOD,
lineSpacing: f32,
baseline: f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetTextAlignment: fn(
self: *const IDWriteTextFormat,
) callconv(@import("std").os.windows.WINAPI) DWRITE_TEXT_ALIGNMENT,
GetParagraphAlignment: fn(
self: *const IDWriteTextFormat,
) callconv(@import("std").os.windows.WINAPI) DWRITE_PARAGRAPH_ALIGNMENT,
GetWordWrapping: fn(
self: *const IDWriteTextFormat,
) callconv(@import("std").os.windows.WINAPI) DWRITE_WORD_WRAPPING,
GetReadingDirection: fn(
self: *const IDWriteTextFormat,
) callconv(@import("std").os.windows.WINAPI) DWRITE_READING_DIRECTION,
GetFlowDirection: fn(
self: *const IDWriteTextFormat,
) callconv(@import("std").os.windows.WINAPI) DWRITE_FLOW_DIRECTION,
GetIncrementalTabStop: fn(
self: *const IDWriteTextFormat,
) callconv(@import("std").os.windows.WINAPI) f32,
GetTrimming: fn(
self: *const IDWriteTextFormat,
trimmingOptions: ?*DWRITE_TRIMMING,
trimmingSign: ?*?*IDWriteInlineObject,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLineSpacing: fn(
self: *const IDWriteTextFormat,
lineSpacingMethod: ?*DWRITE_LINE_SPACING_METHOD,
lineSpacing: ?*f32,
baseline: ?*f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontCollection: fn(
self: *const IDWriteTextFormat,
fontCollection: ?*?*IDWriteFontCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontFamilyNameLength: fn(
self: *const IDWriteTextFormat,
) callconv(@import("std").os.windows.WINAPI) u32,
GetFontFamilyName: fn(
self: *const IDWriteTextFormat,
fontFamilyName: [*:0]u16,
nameSize: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontWeight: fn(
self: *const IDWriteTextFormat,
) callconv(@import("std").os.windows.WINAPI) DWRITE_FONT_WEIGHT,
GetFontStyle: fn(
self: *const IDWriteTextFormat,
) callconv(@import("std").os.windows.WINAPI) DWRITE_FONT_STYLE,
GetFontStretch: fn(
self: *const IDWriteTextFormat,
) callconv(@import("std").os.windows.WINAPI) DWRITE_FONT_STRETCH,
GetFontSize: fn(
self: *const IDWriteTextFormat,
) callconv(@import("std").os.windows.WINAPI) f32,
GetLocaleNameLength: fn(
self: *const IDWriteTextFormat,
) callconv(@import("std").os.windows.WINAPI) u32,
GetLocaleName: fn(
self: *const IDWriteTextFormat,
localeName: [*:0]u16,
nameSize: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat_SetTextAlignment(self: *const T, textAlignment: DWRITE_TEXT_ALIGNMENT) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextFormat.VTable, self.vtable).SetTextAlignment(@ptrCast(*const IDWriteTextFormat, self), textAlignment);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat_SetParagraphAlignment(self: *const T, paragraphAlignment: DWRITE_PARAGRAPH_ALIGNMENT) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextFormat.VTable, self.vtable).SetParagraphAlignment(@ptrCast(*const IDWriteTextFormat, self), paragraphAlignment);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat_SetWordWrapping(self: *const T, wordWrapping: DWRITE_WORD_WRAPPING) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextFormat.VTable, self.vtable).SetWordWrapping(@ptrCast(*const IDWriteTextFormat, self), wordWrapping);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat_SetReadingDirection(self: *const T, readingDirection: DWRITE_READING_DIRECTION) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextFormat.VTable, self.vtable).SetReadingDirection(@ptrCast(*const IDWriteTextFormat, self), readingDirection);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat_SetFlowDirection(self: *const T, flowDirection: DWRITE_FLOW_DIRECTION) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextFormat.VTable, self.vtable).SetFlowDirection(@ptrCast(*const IDWriteTextFormat, self), flowDirection);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat_SetIncrementalTabStop(self: *const T, incrementalTabStop: f32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextFormat.VTable, self.vtable).SetIncrementalTabStop(@ptrCast(*const IDWriteTextFormat, self), incrementalTabStop);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat_SetTrimming(self: *const T, trimmingOptions: ?*const DWRITE_TRIMMING, trimmingSign: ?*IDWriteInlineObject) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextFormat.VTable, self.vtable).SetTrimming(@ptrCast(*const IDWriteTextFormat, self), trimmingOptions, trimmingSign);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat_SetLineSpacing(self: *const T, lineSpacingMethod: DWRITE_LINE_SPACING_METHOD, lineSpacing: f32, baseline: f32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextFormat.VTable, self.vtable).SetLineSpacing(@ptrCast(*const IDWriteTextFormat, self), lineSpacingMethod, lineSpacing, baseline);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat_GetTextAlignment(self: *const T) callconv(.Inline) DWRITE_TEXT_ALIGNMENT {
return @ptrCast(*const IDWriteTextFormat.VTable, self.vtable).GetTextAlignment(@ptrCast(*const IDWriteTextFormat, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat_GetParagraphAlignment(self: *const T) callconv(.Inline) DWRITE_PARAGRAPH_ALIGNMENT {
return @ptrCast(*const IDWriteTextFormat.VTable, self.vtable).GetParagraphAlignment(@ptrCast(*const IDWriteTextFormat, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat_GetWordWrapping(self: *const T) callconv(.Inline) DWRITE_WORD_WRAPPING {
return @ptrCast(*const IDWriteTextFormat.VTable, self.vtable).GetWordWrapping(@ptrCast(*const IDWriteTextFormat, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat_GetReadingDirection(self: *const T) callconv(.Inline) DWRITE_READING_DIRECTION {
return @ptrCast(*const IDWriteTextFormat.VTable, self.vtable).GetReadingDirection(@ptrCast(*const IDWriteTextFormat, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat_GetFlowDirection(self: *const T) callconv(.Inline) DWRITE_FLOW_DIRECTION {
return @ptrCast(*const IDWriteTextFormat.VTable, self.vtable).GetFlowDirection(@ptrCast(*const IDWriteTextFormat, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat_GetIncrementalTabStop(self: *const T) callconv(.Inline) f32 {
return @ptrCast(*const IDWriteTextFormat.VTable, self.vtable).GetIncrementalTabStop(@ptrCast(*const IDWriteTextFormat, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat_GetTrimming(self: *const T, trimmingOptions: ?*DWRITE_TRIMMING, trimmingSign: ?*?*IDWriteInlineObject) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextFormat.VTable, self.vtable).GetTrimming(@ptrCast(*const IDWriteTextFormat, self), trimmingOptions, trimmingSign);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat_GetLineSpacing(self: *const T, lineSpacingMethod: ?*DWRITE_LINE_SPACING_METHOD, lineSpacing: ?*f32, baseline: ?*f32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextFormat.VTable, self.vtable).GetLineSpacing(@ptrCast(*const IDWriteTextFormat, self), lineSpacingMethod, lineSpacing, baseline);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat_GetFontCollection(self: *const T, fontCollection: ?*?*IDWriteFontCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextFormat.VTable, self.vtable).GetFontCollection(@ptrCast(*const IDWriteTextFormat, self), fontCollection);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat_GetFontFamilyNameLength(self: *const T) callconv(.Inline) u32 {
return @ptrCast(*const IDWriteTextFormat.VTable, self.vtable).GetFontFamilyNameLength(@ptrCast(*const IDWriteTextFormat, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat_GetFontFamilyName(self: *const T, fontFamilyName: [*:0]u16, nameSize: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextFormat.VTable, self.vtable).GetFontFamilyName(@ptrCast(*const IDWriteTextFormat, self), fontFamilyName, nameSize);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat_GetFontWeight(self: *const T) callconv(.Inline) DWRITE_FONT_WEIGHT {
return @ptrCast(*const IDWriteTextFormat.VTable, self.vtable).GetFontWeight(@ptrCast(*const IDWriteTextFormat, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat_GetFontStyle(self: *const T) callconv(.Inline) DWRITE_FONT_STYLE {
return @ptrCast(*const IDWriteTextFormat.VTable, self.vtable).GetFontStyle(@ptrCast(*const IDWriteTextFormat, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat_GetFontStretch(self: *const T) callconv(.Inline) DWRITE_FONT_STRETCH {
return @ptrCast(*const IDWriteTextFormat.VTable, self.vtable).GetFontStretch(@ptrCast(*const IDWriteTextFormat, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat_GetFontSize(self: *const T) callconv(.Inline) f32 {
return @ptrCast(*const IDWriteTextFormat.VTable, self.vtable).GetFontSize(@ptrCast(*const IDWriteTextFormat, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat_GetLocaleNameLength(self: *const T) callconv(.Inline) u32 {
return @ptrCast(*const IDWriteTextFormat.VTable, self.vtable).GetLocaleNameLength(@ptrCast(*const IDWriteTextFormat, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat_GetLocaleName(self: *const T, localeName: [*:0]u16, nameSize: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextFormat.VTable, self.vtable).GetLocaleName(@ptrCast(*const IDWriteTextFormat, self), localeName, nameSize);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IDWriteTypography_Value = Guid.initString("55f1112b-1dc2-4b3c-9541-f46894ed85b6");
pub const IID_IDWriteTypography = &IID_IDWriteTypography_Value;
pub const IDWriteTypography = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
AddFontFeature: fn(
self: *const IDWriteTypography,
fontFeature: DWRITE_FONT_FEATURE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontFeatureCount: fn(
self: *const IDWriteTypography,
) callconv(@import("std").os.windows.WINAPI) u32,
GetFontFeature: fn(
self: *const IDWriteTypography,
fontFeatureIndex: u32,
fontFeature: ?*DWRITE_FONT_FEATURE,
) 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 IDWriteTypography_AddFontFeature(self: *const T, fontFeature: DWRITE_FONT_FEATURE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTypography.VTable, self.vtable).AddFontFeature(@ptrCast(*const IDWriteTypography, self), fontFeature);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTypography_GetFontFeatureCount(self: *const T) callconv(.Inline) u32 {
return @ptrCast(*const IDWriteTypography.VTable, self.vtable).GetFontFeatureCount(@ptrCast(*const IDWriteTypography, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTypography_GetFontFeature(self: *const T, fontFeatureIndex: u32, fontFeature: ?*DWRITE_FONT_FEATURE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTypography.VTable, self.vtable).GetFontFeature(@ptrCast(*const IDWriteTypography, self), fontFeatureIndex, fontFeature);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DWRITE_SCRIPT_SHAPES = enum(u32) {
DEFAULT = 0,
NO_VISUAL = 1,
_,
pub fn initFlags(o: struct {
DEFAULT: u1 = 0,
NO_VISUAL: u1 = 0,
}) DWRITE_SCRIPT_SHAPES {
return @intToEnum(DWRITE_SCRIPT_SHAPES,
(if (o.DEFAULT == 1) @enumToInt(DWRITE_SCRIPT_SHAPES.DEFAULT) else 0)
| (if (o.NO_VISUAL == 1) @enumToInt(DWRITE_SCRIPT_SHAPES.NO_VISUAL) else 0)
);
}
};
pub const DWRITE_SCRIPT_SHAPES_DEFAULT = DWRITE_SCRIPT_SHAPES.DEFAULT;
pub const DWRITE_SCRIPT_SHAPES_NO_VISUAL = DWRITE_SCRIPT_SHAPES.NO_VISUAL;
pub const DWRITE_SCRIPT_ANALYSIS = extern struct {
script: u16,
shapes: DWRITE_SCRIPT_SHAPES,
};
pub const DWRITE_BREAK_CONDITION = enum(i32) {
NEUTRAL = 0,
CAN_BREAK = 1,
MAY_NOT_BREAK = 2,
MUST_BREAK = 3,
};
pub const DWRITE_BREAK_CONDITION_NEUTRAL = DWRITE_BREAK_CONDITION.NEUTRAL;
pub const DWRITE_BREAK_CONDITION_CAN_BREAK = DWRITE_BREAK_CONDITION.CAN_BREAK;
pub const DWRITE_BREAK_CONDITION_MAY_NOT_BREAK = DWRITE_BREAK_CONDITION.MAY_NOT_BREAK;
pub const DWRITE_BREAK_CONDITION_MUST_BREAK = DWRITE_BREAK_CONDITION.MUST_BREAK;
pub const DWRITE_LINE_BREAKPOINT = extern struct {
_bitfield: u8,
};
pub const DWRITE_NUMBER_SUBSTITUTION_METHOD = enum(i32) {
FROM_CULTURE = 0,
CONTEXTUAL = 1,
NONE = 2,
NATIONAL = 3,
TRADITIONAL = 4,
};
pub const DWRITE_NUMBER_SUBSTITUTION_METHOD_FROM_CULTURE = DWRITE_NUMBER_SUBSTITUTION_METHOD.FROM_CULTURE;
pub const DWRITE_NUMBER_SUBSTITUTION_METHOD_CONTEXTUAL = DWRITE_NUMBER_SUBSTITUTION_METHOD.CONTEXTUAL;
pub const DWRITE_NUMBER_SUBSTITUTION_METHOD_NONE = DWRITE_NUMBER_SUBSTITUTION_METHOD.NONE;
pub const DWRITE_NUMBER_SUBSTITUTION_METHOD_NATIONAL = DWRITE_NUMBER_SUBSTITUTION_METHOD.NATIONAL;
pub const DWRITE_NUMBER_SUBSTITUTION_METHOD_TRADITIONAL = DWRITE_NUMBER_SUBSTITUTION_METHOD.TRADITIONAL;
const IID_IDWriteNumberSubstitution_Value = Guid.initString("14885cc9-bab0-4f90-b6ed-5c366a2cd03d");
pub const IID_IDWriteNumberSubstitution = &IID_IDWriteNumberSubstitution_Value;
pub const IDWriteNumberSubstitution = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
};}
pub usingnamespace MethodMixin(@This());
};
pub const DWRITE_SHAPING_TEXT_PROPERTIES = extern struct {
_bitfield: u16,
};
pub const DWRITE_SHAPING_GLYPH_PROPERTIES = extern struct {
_bitfield: u16,
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IDWriteTextAnalysisSource_Value = Guid.initString("688e1a58-5094-47c8-adc8-fbcea60ae92b");
pub const IID_IDWriteTextAnalysisSource = &IID_IDWriteTextAnalysisSource_Value;
pub const IDWriteTextAnalysisSource = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetTextAtPosition: fn(
self: *const IDWriteTextAnalysisSource,
textPosition: u32,
textString: ?*const ?*u16,
textLength: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetTextBeforePosition: fn(
self: *const IDWriteTextAnalysisSource,
textPosition: u32,
textString: ?*const ?*u16,
textLength: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetParagraphReadingDirection: fn(
self: *const IDWriteTextAnalysisSource,
) callconv(@import("std").os.windows.WINAPI) DWRITE_READING_DIRECTION,
GetLocaleName: fn(
self: *const IDWriteTextAnalysisSource,
textPosition: u32,
textLength: ?*u32,
localeName: ?*const ?*u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetNumberSubstitution: fn(
self: *const IDWriteTextAnalysisSource,
textPosition: u32,
textLength: ?*u32,
numberSubstitution: ?*?*IDWriteNumberSubstitution,
) 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 IDWriteTextAnalysisSource_GetTextAtPosition(self: *const T, textPosition: u32, textString: ?*const ?*u16, textLength: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextAnalysisSource.VTable, self.vtable).GetTextAtPosition(@ptrCast(*const IDWriteTextAnalysisSource, self), textPosition, textString, textLength);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextAnalysisSource_GetTextBeforePosition(self: *const T, textPosition: u32, textString: ?*const ?*u16, textLength: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextAnalysisSource.VTable, self.vtable).GetTextBeforePosition(@ptrCast(*const IDWriteTextAnalysisSource, self), textPosition, textString, textLength);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextAnalysisSource_GetParagraphReadingDirection(self: *const T) callconv(.Inline) DWRITE_READING_DIRECTION {
return @ptrCast(*const IDWriteTextAnalysisSource.VTable, self.vtable).GetParagraphReadingDirection(@ptrCast(*const IDWriteTextAnalysisSource, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextAnalysisSource_GetLocaleName(self: *const T, textPosition: u32, textLength: ?*u32, localeName: ?*const ?*u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextAnalysisSource.VTable, self.vtable).GetLocaleName(@ptrCast(*const IDWriteTextAnalysisSource, self), textPosition, textLength, localeName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextAnalysisSource_GetNumberSubstitution(self: *const T, textPosition: u32, textLength: ?*u32, numberSubstitution: ?*?*IDWriteNumberSubstitution) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextAnalysisSource.VTable, self.vtable).GetNumberSubstitution(@ptrCast(*const IDWriteTextAnalysisSource, self), textPosition, textLength, numberSubstitution);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IDWriteTextAnalysisSink_Value = Guid.initString("5810cd44-0ca0-4701-b3fa-bec5182ae4f6");
pub const IID_IDWriteTextAnalysisSink = &IID_IDWriteTextAnalysisSink_Value;
pub const IDWriteTextAnalysisSink = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetScriptAnalysis: fn(
self: *const IDWriteTextAnalysisSink,
textPosition: u32,
textLength: u32,
scriptAnalysis: ?*const DWRITE_SCRIPT_ANALYSIS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetLineBreakpoints: fn(
self: *const IDWriteTextAnalysisSink,
textPosition: u32,
textLength: u32,
lineBreakpoints: [*]const DWRITE_LINE_BREAKPOINT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetBidiLevel: fn(
self: *const IDWriteTextAnalysisSink,
textPosition: u32,
textLength: u32,
explicitLevel: u8,
resolvedLevel: u8,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetNumberSubstitution: fn(
self: *const IDWriteTextAnalysisSink,
textPosition: u32,
textLength: u32,
numberSubstitution: ?*IDWriteNumberSubstitution,
) 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 IDWriteTextAnalysisSink_SetScriptAnalysis(self: *const T, textPosition: u32, textLength: u32, scriptAnalysis: ?*const DWRITE_SCRIPT_ANALYSIS) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextAnalysisSink.VTable, self.vtable).SetScriptAnalysis(@ptrCast(*const IDWriteTextAnalysisSink, self), textPosition, textLength, scriptAnalysis);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextAnalysisSink_SetLineBreakpoints(self: *const T, textPosition: u32, textLength: u32, lineBreakpoints: [*]const DWRITE_LINE_BREAKPOINT) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextAnalysisSink.VTable, self.vtable).SetLineBreakpoints(@ptrCast(*const IDWriteTextAnalysisSink, self), textPosition, textLength, lineBreakpoints);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextAnalysisSink_SetBidiLevel(self: *const T, textPosition: u32, textLength: u32, explicitLevel: u8, resolvedLevel: u8) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextAnalysisSink.VTable, self.vtable).SetBidiLevel(@ptrCast(*const IDWriteTextAnalysisSink, self), textPosition, textLength, explicitLevel, resolvedLevel);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextAnalysisSink_SetNumberSubstitution(self: *const T, textPosition: u32, textLength: u32, numberSubstitution: ?*IDWriteNumberSubstitution) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextAnalysisSink.VTable, self.vtable).SetNumberSubstitution(@ptrCast(*const IDWriteTextAnalysisSink, self), textPosition, textLength, numberSubstitution);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IDWriteTextAnalyzer_Value = Guid.initString("b7e6163e-7f46-43b4-84b3-e4e6249c365d");
pub const IID_IDWriteTextAnalyzer = &IID_IDWriteTextAnalyzer_Value;
pub const IDWriteTextAnalyzer = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
AnalyzeScript: fn(
self: *const IDWriteTextAnalyzer,
analysisSource: ?*IDWriteTextAnalysisSource,
textPosition: u32,
textLength: u32,
analysisSink: ?*IDWriteTextAnalysisSink,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AnalyzeBidi: fn(
self: *const IDWriteTextAnalyzer,
analysisSource: ?*IDWriteTextAnalysisSource,
textPosition: u32,
textLength: u32,
analysisSink: ?*IDWriteTextAnalysisSink,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AnalyzeNumberSubstitution: fn(
self: *const IDWriteTextAnalyzer,
analysisSource: ?*IDWriteTextAnalysisSource,
textPosition: u32,
textLength: u32,
analysisSink: ?*IDWriteTextAnalysisSink,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AnalyzeLineBreakpoints: fn(
self: *const IDWriteTextAnalyzer,
analysisSource: ?*IDWriteTextAnalysisSource,
textPosition: u32,
textLength: u32,
analysisSink: ?*IDWriteTextAnalysisSink,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetGlyphs: fn(
self: *const IDWriteTextAnalyzer,
textString: [*:0]const u16,
textLength: u32,
fontFace: ?*IDWriteFontFace,
isSideways: BOOL,
isRightToLeft: BOOL,
scriptAnalysis: ?*const DWRITE_SCRIPT_ANALYSIS,
localeName: ?[*:0]const u16,
numberSubstitution: ?*IDWriteNumberSubstitution,
features: ?[*]const ?*const DWRITE_TYPOGRAPHIC_FEATURES,
featureRangeLengths: ?[*]const u32,
featureRanges: u32,
maxGlyphCount: u32,
clusterMap: [*:0]u16,
textProps: [*]DWRITE_SHAPING_TEXT_PROPERTIES,
glyphIndices: [*:0]u16,
glyphProps: [*]DWRITE_SHAPING_GLYPH_PROPERTIES,
actualGlyphCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetGlyphPlacements: fn(
self: *const IDWriteTextAnalyzer,
textString: [*:0]const u16,
clusterMap: [*:0]const u16,
textProps: [*]DWRITE_SHAPING_TEXT_PROPERTIES,
textLength: u32,
glyphIndices: [*:0]const u16,
glyphProps: [*]const DWRITE_SHAPING_GLYPH_PROPERTIES,
glyphCount: u32,
fontFace: ?*IDWriteFontFace,
fontEmSize: f32,
isSideways: BOOL,
isRightToLeft: BOOL,
scriptAnalysis: ?*const DWRITE_SCRIPT_ANALYSIS,
localeName: ?[*:0]const u16,
features: ?[*]const ?*const DWRITE_TYPOGRAPHIC_FEATURES,
featureRangeLengths: ?[*]const u32,
featureRanges: u32,
glyphAdvances: [*]f32,
glyphOffsets: [*]DWRITE_GLYPH_OFFSET,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetGdiCompatibleGlyphPlacements: fn(
self: *const IDWriteTextAnalyzer,
textString: [*:0]const u16,
clusterMap: [*:0]const u16,
textProps: [*]DWRITE_SHAPING_TEXT_PROPERTIES,
textLength: u32,
glyphIndices: [*:0]const u16,
glyphProps: [*]const DWRITE_SHAPING_GLYPH_PROPERTIES,
glyphCount: u32,
fontFace: ?*IDWriteFontFace,
fontEmSize: f32,
pixelsPerDip: f32,
transform: ?*const DWRITE_MATRIX,
useGdiNatural: BOOL,
isSideways: BOOL,
isRightToLeft: BOOL,
scriptAnalysis: ?*const DWRITE_SCRIPT_ANALYSIS,
localeName: ?[*:0]const u16,
features: ?[*]const ?*const DWRITE_TYPOGRAPHIC_FEATURES,
featureRangeLengths: ?[*]const u32,
featureRanges: u32,
glyphAdvances: [*]f32,
glyphOffsets: [*]DWRITE_GLYPH_OFFSET,
) 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 IDWriteTextAnalyzer_AnalyzeScript(self: *const T, analysisSource: ?*IDWriteTextAnalysisSource, textPosition: u32, textLength: u32, analysisSink: ?*IDWriteTextAnalysisSink) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextAnalyzer.VTable, self.vtable).AnalyzeScript(@ptrCast(*const IDWriteTextAnalyzer, self), analysisSource, textPosition, textLength, analysisSink);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextAnalyzer_AnalyzeBidi(self: *const T, analysisSource: ?*IDWriteTextAnalysisSource, textPosition: u32, textLength: u32, analysisSink: ?*IDWriteTextAnalysisSink) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextAnalyzer.VTable, self.vtable).AnalyzeBidi(@ptrCast(*const IDWriteTextAnalyzer, self), analysisSource, textPosition, textLength, analysisSink);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextAnalyzer_AnalyzeNumberSubstitution(self: *const T, analysisSource: ?*IDWriteTextAnalysisSource, textPosition: u32, textLength: u32, analysisSink: ?*IDWriteTextAnalysisSink) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextAnalyzer.VTable, self.vtable).AnalyzeNumberSubstitution(@ptrCast(*const IDWriteTextAnalyzer, self), analysisSource, textPosition, textLength, analysisSink);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextAnalyzer_AnalyzeLineBreakpoints(self: *const T, analysisSource: ?*IDWriteTextAnalysisSource, textPosition: u32, textLength: u32, analysisSink: ?*IDWriteTextAnalysisSink) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextAnalyzer.VTable, self.vtable).AnalyzeLineBreakpoints(@ptrCast(*const IDWriteTextAnalyzer, self), analysisSource, textPosition, textLength, analysisSink);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextAnalyzer_GetGlyphs(self: *const T, textString: [*:0]const u16, textLength: u32, fontFace: ?*IDWriteFontFace, isSideways: BOOL, isRightToLeft: BOOL, scriptAnalysis: ?*const DWRITE_SCRIPT_ANALYSIS, localeName: ?[*:0]const u16, numberSubstitution: ?*IDWriteNumberSubstitution, features: ?[*]const ?*const DWRITE_TYPOGRAPHIC_FEATURES, featureRangeLengths: ?[*]const u32, featureRanges: u32, maxGlyphCount: u32, clusterMap: [*:0]u16, textProps: [*]DWRITE_SHAPING_TEXT_PROPERTIES, glyphIndices: [*:0]u16, glyphProps: [*]DWRITE_SHAPING_GLYPH_PROPERTIES, actualGlyphCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextAnalyzer.VTable, self.vtable).GetGlyphs(@ptrCast(*const IDWriteTextAnalyzer, self), textString, textLength, fontFace, isSideways, isRightToLeft, scriptAnalysis, localeName, numberSubstitution, features, featureRangeLengths, featureRanges, maxGlyphCount, clusterMap, textProps, glyphIndices, glyphProps, actualGlyphCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextAnalyzer_GetGlyphPlacements(self: *const T, textString: [*:0]const u16, clusterMap: [*:0]const u16, textProps: [*]DWRITE_SHAPING_TEXT_PROPERTIES, textLength: u32, glyphIndices: [*:0]const u16, glyphProps: [*]const DWRITE_SHAPING_GLYPH_PROPERTIES, glyphCount: u32, fontFace: ?*IDWriteFontFace, fontEmSize: f32, isSideways: BOOL, isRightToLeft: BOOL, scriptAnalysis: ?*const DWRITE_SCRIPT_ANALYSIS, localeName: ?[*:0]const u16, features: ?[*]const ?*const DWRITE_TYPOGRAPHIC_FEATURES, featureRangeLengths: ?[*]const u32, featureRanges: u32, glyphAdvances: [*]f32, glyphOffsets: [*]DWRITE_GLYPH_OFFSET) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextAnalyzer.VTable, self.vtable).GetGlyphPlacements(@ptrCast(*const IDWriteTextAnalyzer, self), textString, clusterMap, textProps, textLength, glyphIndices, glyphProps, glyphCount, fontFace, fontEmSize, isSideways, isRightToLeft, scriptAnalysis, localeName, features, featureRangeLengths, featureRanges, glyphAdvances, glyphOffsets);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextAnalyzer_GetGdiCompatibleGlyphPlacements(self: *const T, textString: [*:0]const u16, clusterMap: [*:0]const u16, textProps: [*]DWRITE_SHAPING_TEXT_PROPERTIES, textLength: u32, glyphIndices: [*:0]const u16, glyphProps: [*]const DWRITE_SHAPING_GLYPH_PROPERTIES, glyphCount: u32, fontFace: ?*IDWriteFontFace, fontEmSize: f32, pixelsPerDip: f32, transform: ?*const DWRITE_MATRIX, useGdiNatural: BOOL, isSideways: BOOL, isRightToLeft: BOOL, scriptAnalysis: ?*const DWRITE_SCRIPT_ANALYSIS, localeName: ?[*:0]const u16, features: ?[*]const ?*const DWRITE_TYPOGRAPHIC_FEATURES, featureRangeLengths: ?[*]const u32, featureRanges: u32, glyphAdvances: [*]f32, glyphOffsets: [*]DWRITE_GLYPH_OFFSET) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextAnalyzer.VTable, self.vtable).GetGdiCompatibleGlyphPlacements(@ptrCast(*const IDWriteTextAnalyzer, self), textString, clusterMap, textProps, textLength, glyphIndices, glyphProps, glyphCount, fontFace, fontEmSize, pixelsPerDip, transform, useGdiNatural, isSideways, isRightToLeft, scriptAnalysis, localeName, features, featureRangeLengths, featureRanges, glyphAdvances, glyphOffsets);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DWRITE_GLYPH_RUN = extern struct {
fontFace: ?*IDWriteFontFace,
fontEmSize: f32,
glyphCount: u32,
glyphIndices: ?*const u16,
glyphAdvances: ?*const f32,
glyphOffsets: ?*const DWRITE_GLYPH_OFFSET,
isSideways: BOOL,
bidiLevel: u32,
};
pub const DWRITE_GLYPH_RUN_DESCRIPTION = extern struct {
localeName: ?[*:0]const u16,
string: ?[*:0]const u16,
stringLength: u32,
clusterMap: ?*const u16,
textPosition: u32,
};
pub const DWRITE_UNDERLINE = extern struct {
width: f32,
thickness: f32,
offset: f32,
runHeight: f32,
readingDirection: DWRITE_READING_DIRECTION,
flowDirection: DWRITE_FLOW_DIRECTION,
localeName: ?[*:0]const u16,
measuringMode: DWRITE_MEASURING_MODE,
};
pub const DWRITE_STRIKETHROUGH = extern struct {
width: f32,
thickness: f32,
offset: f32,
readingDirection: DWRITE_READING_DIRECTION,
flowDirection: DWRITE_FLOW_DIRECTION,
localeName: ?[*:0]const u16,
measuringMode: DWRITE_MEASURING_MODE,
};
pub const DWRITE_LINE_METRICS = extern struct {
length: u32,
trailingWhitespaceLength: u32,
newlineLength: u32,
height: f32,
baseline: f32,
isTrimmed: BOOL,
};
pub const DWRITE_CLUSTER_METRICS = extern struct {
width: f32,
length: u16,
_bitfield: u16,
};
pub const DWRITE_TEXT_METRICS = extern struct {
left: f32,
top: f32,
width: f32,
widthIncludingTrailingWhitespace: f32,
height: f32,
layoutWidth: f32,
layoutHeight: f32,
maxBidiReorderingDepth: u32,
lineCount: u32,
};
pub const DWRITE_INLINE_OBJECT_METRICS = extern struct {
width: f32,
height: f32,
baseline: f32,
supportsSideways: BOOL,
};
pub const DWRITE_OVERHANG_METRICS = extern struct {
left: f32,
top: f32,
right: f32,
bottom: f32,
};
pub const DWRITE_HIT_TEST_METRICS = extern struct {
textPosition: u32,
length: u32,
left: f32,
top: f32,
width: f32,
height: f32,
bidiLevel: u32,
isText: BOOL,
isTrimmed: BOOL,
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IDWriteInlineObject_Value = Guid.initString("8339fde3-106f-47ab-8373-1c6295eb10b3");
pub const IID_IDWriteInlineObject = &IID_IDWriteInlineObject_Value;
pub const IDWriteInlineObject = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Draw: fn(
self: *const IDWriteInlineObject,
clientDrawingContext: ?*anyopaque,
renderer: ?*IDWriteTextRenderer,
originX: f32,
originY: f32,
isSideways: BOOL,
isRightToLeft: BOOL,
clientDrawingEffect: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetMetrics: fn(
self: *const IDWriteInlineObject,
metrics: ?*DWRITE_INLINE_OBJECT_METRICS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetOverhangMetrics: fn(
self: *const IDWriteInlineObject,
overhangs: ?*DWRITE_OVERHANG_METRICS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetBreakConditions: fn(
self: *const IDWriteInlineObject,
breakConditionBefore: ?*DWRITE_BREAK_CONDITION,
breakConditionAfter: ?*DWRITE_BREAK_CONDITION,
) 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 IDWriteInlineObject_Draw(self: *const T, clientDrawingContext: ?*anyopaque, renderer: ?*IDWriteTextRenderer, originX: f32, originY: f32, isSideways: BOOL, isRightToLeft: BOOL, clientDrawingEffect: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteInlineObject.VTable, self.vtable).Draw(@ptrCast(*const IDWriteInlineObject, self), clientDrawingContext, renderer, originX, originY, isSideways, isRightToLeft, clientDrawingEffect);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteInlineObject_GetMetrics(self: *const T, metrics: ?*DWRITE_INLINE_OBJECT_METRICS) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteInlineObject.VTable, self.vtable).GetMetrics(@ptrCast(*const IDWriteInlineObject, self), metrics);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteInlineObject_GetOverhangMetrics(self: *const T, overhangs: ?*DWRITE_OVERHANG_METRICS) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteInlineObject.VTable, self.vtable).GetOverhangMetrics(@ptrCast(*const IDWriteInlineObject, self), overhangs);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteInlineObject_GetBreakConditions(self: *const T, breakConditionBefore: ?*DWRITE_BREAK_CONDITION, breakConditionAfter: ?*DWRITE_BREAK_CONDITION) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteInlineObject.VTable, self.vtable).GetBreakConditions(@ptrCast(*const IDWriteInlineObject, self), breakConditionBefore, breakConditionAfter);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IDWritePixelSnapping_Value = Guid.initString("eaf3a2da-ecf4-4d24-b644-b34f6842024b");
pub const IID_IDWritePixelSnapping = &IID_IDWritePixelSnapping_Value;
pub const IDWritePixelSnapping = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
IsPixelSnappingDisabled: fn(
self: *const IDWritePixelSnapping,
clientDrawingContext: ?*anyopaque,
isDisabled: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCurrentTransform: fn(
self: *const IDWritePixelSnapping,
clientDrawingContext: ?*anyopaque,
transform: ?*DWRITE_MATRIX,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPixelsPerDip: fn(
self: *const IDWritePixelSnapping,
clientDrawingContext: ?*anyopaque,
pixelsPerDip: ?*f32,
) 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 IDWritePixelSnapping_IsPixelSnappingDisabled(self: *const T, clientDrawingContext: ?*anyopaque, isDisabled: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWritePixelSnapping.VTable, self.vtable).IsPixelSnappingDisabled(@ptrCast(*const IDWritePixelSnapping, self), clientDrawingContext, isDisabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWritePixelSnapping_GetCurrentTransform(self: *const T, clientDrawingContext: ?*anyopaque, transform: ?*DWRITE_MATRIX) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWritePixelSnapping.VTable, self.vtable).GetCurrentTransform(@ptrCast(*const IDWritePixelSnapping, self), clientDrawingContext, transform);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWritePixelSnapping_GetPixelsPerDip(self: *const T, clientDrawingContext: ?*anyopaque, pixelsPerDip: ?*f32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWritePixelSnapping.VTable, self.vtable).GetPixelsPerDip(@ptrCast(*const IDWritePixelSnapping, self), clientDrawingContext, pixelsPerDip);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IDWriteTextRenderer_Value = Guid.initString("ef8a8135-5cc6-45fe-8825-c5a0724eb819");
pub const IID_IDWriteTextRenderer = &IID_IDWriteTextRenderer_Value;
pub const IDWriteTextRenderer = extern struct {
pub const VTable = extern struct {
base: IDWritePixelSnapping.VTable,
DrawGlyphRun: fn(
self: *const IDWriteTextRenderer,
clientDrawingContext: ?*anyopaque,
baselineOriginX: f32,
baselineOriginY: f32,
measuringMode: DWRITE_MEASURING_MODE,
glyphRun: ?*const DWRITE_GLYPH_RUN,
glyphRunDescription: ?*const DWRITE_GLYPH_RUN_DESCRIPTION,
clientDrawingEffect: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DrawUnderline: fn(
self: *const IDWriteTextRenderer,
clientDrawingContext: ?*anyopaque,
baselineOriginX: f32,
baselineOriginY: f32,
underline: ?*const DWRITE_UNDERLINE,
clientDrawingEffect: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DrawStrikethrough: fn(
self: *const IDWriteTextRenderer,
clientDrawingContext: ?*anyopaque,
baselineOriginX: f32,
baselineOriginY: f32,
strikethrough: ?*const DWRITE_STRIKETHROUGH,
clientDrawingEffect: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DrawInlineObject: fn(
self: *const IDWriteTextRenderer,
clientDrawingContext: ?*anyopaque,
originX: f32,
originY: f32,
inlineObject: ?*IDWriteInlineObject,
isSideways: BOOL,
isRightToLeft: BOOL,
clientDrawingEffect: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWritePixelSnapping.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextRenderer_DrawGlyphRun(self: *const T, clientDrawingContext: ?*anyopaque, baselineOriginX: f32, baselineOriginY: f32, measuringMode: DWRITE_MEASURING_MODE, glyphRun: ?*const DWRITE_GLYPH_RUN, glyphRunDescription: ?*const DWRITE_GLYPH_RUN_DESCRIPTION, clientDrawingEffect: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextRenderer.VTable, self.vtable).DrawGlyphRun(@ptrCast(*const IDWriteTextRenderer, self), clientDrawingContext, baselineOriginX, baselineOriginY, measuringMode, glyphRun, glyphRunDescription, clientDrawingEffect);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextRenderer_DrawUnderline(self: *const T, clientDrawingContext: ?*anyopaque, baselineOriginX: f32, baselineOriginY: f32, underline: ?*const DWRITE_UNDERLINE, clientDrawingEffect: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextRenderer.VTable, self.vtable).DrawUnderline(@ptrCast(*const IDWriteTextRenderer, self), clientDrawingContext, baselineOriginX, baselineOriginY, underline, clientDrawingEffect);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextRenderer_DrawStrikethrough(self: *const T, clientDrawingContext: ?*anyopaque, baselineOriginX: f32, baselineOriginY: f32, strikethrough: ?*const DWRITE_STRIKETHROUGH, clientDrawingEffect: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextRenderer.VTable, self.vtable).DrawStrikethrough(@ptrCast(*const IDWriteTextRenderer, self), clientDrawingContext, baselineOriginX, baselineOriginY, strikethrough, clientDrawingEffect);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextRenderer_DrawInlineObject(self: *const T, clientDrawingContext: ?*anyopaque, originX: f32, originY: f32, inlineObject: ?*IDWriteInlineObject, isSideways: BOOL, isRightToLeft: BOOL, clientDrawingEffect: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextRenderer.VTable, self.vtable).DrawInlineObject(@ptrCast(*const IDWriteTextRenderer, self), clientDrawingContext, originX, originY, inlineObject, isSideways, isRightToLeft, clientDrawingEffect);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IDWriteTextLayout_Value = Guid.initString("53737037-6d14-410b-9bfe-0b182bb70961");
pub const IID_IDWriteTextLayout = &IID_IDWriteTextLayout_Value;
pub const IDWriteTextLayout = extern struct {
pub const VTable = extern struct {
base: IDWriteTextFormat.VTable,
SetMaxWidth: fn(
self: *const IDWriteTextLayout,
maxWidth: f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetMaxHeight: fn(
self: *const IDWriteTextLayout,
maxHeight: f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetFontCollection: fn(
self: *const IDWriteTextLayout,
fontCollection: ?*IDWriteFontCollection,
textRange: DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetFontFamilyName: fn(
self: *const IDWriteTextLayout,
fontFamilyName: ?[*:0]const u16,
textRange: DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetFontWeight: fn(
self: *const IDWriteTextLayout,
fontWeight: DWRITE_FONT_WEIGHT,
textRange: DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetFontStyle: fn(
self: *const IDWriteTextLayout,
fontStyle: DWRITE_FONT_STYLE,
textRange: DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetFontStretch: fn(
self: *const IDWriteTextLayout,
fontStretch: DWRITE_FONT_STRETCH,
textRange: DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetFontSize: fn(
self: *const IDWriteTextLayout,
fontSize: f32,
textRange: DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetUnderline: fn(
self: *const IDWriteTextLayout,
hasUnderline: BOOL,
textRange: DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetStrikethrough: fn(
self: *const IDWriteTextLayout,
hasStrikethrough: BOOL,
textRange: DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetDrawingEffect: fn(
self: *const IDWriteTextLayout,
drawingEffect: ?*IUnknown,
textRange: DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetInlineObject: fn(
self: *const IDWriteTextLayout,
inlineObject: ?*IDWriteInlineObject,
textRange: DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetTypography: fn(
self: *const IDWriteTextLayout,
typography: ?*IDWriteTypography,
textRange: DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetLocaleName: fn(
self: *const IDWriteTextLayout,
localeName: ?[*:0]const u16,
textRange: DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetMaxWidth: fn(
self: *const IDWriteTextLayout,
) callconv(@import("std").os.windows.WINAPI) f32,
GetMaxHeight: fn(
self: *const IDWriteTextLayout,
) callconv(@import("std").os.windows.WINAPI) f32,
GetFontCollection: fn(
self: *const IDWriteTextLayout,
currentPosition: u32,
fontCollection: ?*?*IDWriteFontCollection,
textRange: ?*DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontFamilyNameLength: fn(
self: *const IDWriteTextLayout,
currentPosition: u32,
nameLength: ?*u32,
textRange: ?*DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontFamilyName: fn(
self: *const IDWriteTextLayout,
currentPosition: u32,
fontFamilyName: [*:0]u16,
nameSize: u32,
textRange: ?*DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontWeight: fn(
self: *const IDWriteTextLayout,
currentPosition: u32,
fontWeight: ?*DWRITE_FONT_WEIGHT,
textRange: ?*DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontStyle: fn(
self: *const IDWriteTextLayout,
currentPosition: u32,
fontStyle: ?*DWRITE_FONT_STYLE,
textRange: ?*DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontStretch: fn(
self: *const IDWriteTextLayout,
currentPosition: u32,
fontStretch: ?*DWRITE_FONT_STRETCH,
textRange: ?*DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontSize: fn(
self: *const IDWriteTextLayout,
currentPosition: u32,
fontSize: ?*f32,
textRange: ?*DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetUnderline: fn(
self: *const IDWriteTextLayout,
currentPosition: u32,
hasUnderline: ?*BOOL,
textRange: ?*DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetStrikethrough: fn(
self: *const IDWriteTextLayout,
currentPosition: u32,
hasStrikethrough: ?*BOOL,
textRange: ?*DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDrawingEffect: fn(
self: *const IDWriteTextLayout,
currentPosition: u32,
drawingEffect: ?*?*IUnknown,
textRange: ?*DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetInlineObject: fn(
self: *const IDWriteTextLayout,
currentPosition: u32,
inlineObject: ?*?*IDWriteInlineObject,
textRange: ?*DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetTypography: fn(
self: *const IDWriteTextLayout,
currentPosition: u32,
typography: ?*?*IDWriteTypography,
textRange: ?*DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLocaleNameLength: fn(
self: *const IDWriteTextLayout,
currentPosition: u32,
nameLength: ?*u32,
textRange: ?*DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLocaleName: fn(
self: *const IDWriteTextLayout,
currentPosition: u32,
localeName: [*:0]u16,
nameSize: u32,
textRange: ?*DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Draw: fn(
self: *const IDWriteTextLayout,
clientDrawingContext: ?*anyopaque,
renderer: ?*IDWriteTextRenderer,
originX: f32,
originY: f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLineMetrics: fn(
self: *const IDWriteTextLayout,
lineMetrics: ?[*]DWRITE_LINE_METRICS,
maxLineCount: u32,
actualLineCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetMetrics: fn(
self: *const IDWriteTextLayout,
textMetrics: ?*DWRITE_TEXT_METRICS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetOverhangMetrics: fn(
self: *const IDWriteTextLayout,
overhangs: ?*DWRITE_OVERHANG_METRICS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetClusterMetrics: fn(
self: *const IDWriteTextLayout,
clusterMetrics: ?[*]DWRITE_CLUSTER_METRICS,
maxClusterCount: u32,
actualClusterCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DetermineMinWidth: fn(
self: *const IDWriteTextLayout,
minWidth: ?*f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
HitTestPoint: fn(
self: *const IDWriteTextLayout,
pointX: f32,
pointY: f32,
isTrailingHit: ?*BOOL,
isInside: ?*BOOL,
hitTestMetrics: ?*DWRITE_HIT_TEST_METRICS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
HitTestTextPosition: fn(
self: *const IDWriteTextLayout,
textPosition: u32,
isTrailingHit: BOOL,
pointX: ?*f32,
pointY: ?*f32,
hitTestMetrics: ?*DWRITE_HIT_TEST_METRICS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
HitTestTextRange: fn(
self: *const IDWriteTextLayout,
textPosition: u32,
textLength: u32,
originX: f32,
originY: f32,
hitTestMetrics: ?[*]DWRITE_HIT_TEST_METRICS,
maxHitTestMetricsCount: u32,
actualHitTestMetricsCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteTextFormat.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_SetMaxWidth(self: *const T, maxWidth: f32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).SetMaxWidth(@ptrCast(*const IDWriteTextLayout, self), maxWidth);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_SetMaxHeight(self: *const T, maxHeight: f32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).SetMaxHeight(@ptrCast(*const IDWriteTextLayout, self), maxHeight);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_SetFontCollection(self: *const T, fontCollection: ?*IDWriteFontCollection, textRange: DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).SetFontCollection(@ptrCast(*const IDWriteTextLayout, self), fontCollection, textRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_SetFontFamilyName(self: *const T, fontFamilyName: ?[*:0]const u16, textRange: DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).SetFontFamilyName(@ptrCast(*const IDWriteTextLayout, self), fontFamilyName, textRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_SetFontWeight(self: *const T, fontWeight: DWRITE_FONT_WEIGHT, textRange: DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).SetFontWeight(@ptrCast(*const IDWriteTextLayout, self), fontWeight, textRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_SetFontStyle(self: *const T, fontStyle: DWRITE_FONT_STYLE, textRange: DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).SetFontStyle(@ptrCast(*const IDWriteTextLayout, self), fontStyle, textRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_SetFontStretch(self: *const T, fontStretch: DWRITE_FONT_STRETCH, textRange: DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).SetFontStretch(@ptrCast(*const IDWriteTextLayout, self), fontStretch, textRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_SetFontSize(self: *const T, fontSize: f32, textRange: DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).SetFontSize(@ptrCast(*const IDWriteTextLayout, self), fontSize, textRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_SetUnderline(self: *const T, hasUnderline: BOOL, textRange: DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).SetUnderline(@ptrCast(*const IDWriteTextLayout, self), hasUnderline, textRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_SetStrikethrough(self: *const T, hasStrikethrough: BOOL, textRange: DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).SetStrikethrough(@ptrCast(*const IDWriteTextLayout, self), hasStrikethrough, textRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_SetDrawingEffect(self: *const T, drawingEffect: ?*IUnknown, textRange: DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).SetDrawingEffect(@ptrCast(*const IDWriteTextLayout, self), drawingEffect, textRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_SetInlineObject(self: *const T, inlineObject: ?*IDWriteInlineObject, textRange: DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).SetInlineObject(@ptrCast(*const IDWriteTextLayout, self), inlineObject, textRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_SetTypography(self: *const T, typography: ?*IDWriteTypography, textRange: DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).SetTypography(@ptrCast(*const IDWriteTextLayout, self), typography, textRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_SetLocaleName(self: *const T, localeName: ?[*:0]const u16, textRange: DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).SetLocaleName(@ptrCast(*const IDWriteTextLayout, self), localeName, textRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_GetMaxWidth(self: *const T) callconv(.Inline) f32 {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).GetMaxWidth(@ptrCast(*const IDWriteTextLayout, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_GetMaxHeight(self: *const T) callconv(.Inline) f32 {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).GetMaxHeight(@ptrCast(*const IDWriteTextLayout, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_GetFontCollection(self: *const T, currentPosition: u32, fontCollection: ?*?*IDWriteFontCollection, textRange: ?*DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).GetFontCollection(@ptrCast(*const IDWriteTextLayout, self), currentPosition, fontCollection, textRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_GetFontFamilyNameLength(self: *const T, currentPosition: u32, nameLength: ?*u32, textRange: ?*DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).GetFontFamilyNameLength(@ptrCast(*const IDWriteTextLayout, self), currentPosition, nameLength, textRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_GetFontFamilyName(self: *const T, currentPosition: u32, fontFamilyName: [*:0]u16, nameSize: u32, textRange: ?*DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).GetFontFamilyName(@ptrCast(*const IDWriteTextLayout, self), currentPosition, fontFamilyName, nameSize, textRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_GetFontWeight(self: *const T, currentPosition: u32, fontWeight: ?*DWRITE_FONT_WEIGHT, textRange: ?*DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).GetFontWeight(@ptrCast(*const IDWriteTextLayout, self), currentPosition, fontWeight, textRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_GetFontStyle(self: *const T, currentPosition: u32, fontStyle: ?*DWRITE_FONT_STYLE, textRange: ?*DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).GetFontStyle(@ptrCast(*const IDWriteTextLayout, self), currentPosition, fontStyle, textRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_GetFontStretch(self: *const T, currentPosition: u32, fontStretch: ?*DWRITE_FONT_STRETCH, textRange: ?*DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).GetFontStretch(@ptrCast(*const IDWriteTextLayout, self), currentPosition, fontStretch, textRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_GetFontSize(self: *const T, currentPosition: u32, fontSize: ?*f32, textRange: ?*DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).GetFontSize(@ptrCast(*const IDWriteTextLayout, self), currentPosition, fontSize, textRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_GetUnderline(self: *const T, currentPosition: u32, hasUnderline: ?*BOOL, textRange: ?*DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).GetUnderline(@ptrCast(*const IDWriteTextLayout, self), currentPosition, hasUnderline, textRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_GetStrikethrough(self: *const T, currentPosition: u32, hasStrikethrough: ?*BOOL, textRange: ?*DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).GetStrikethrough(@ptrCast(*const IDWriteTextLayout, self), currentPosition, hasStrikethrough, textRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_GetDrawingEffect(self: *const T, currentPosition: u32, drawingEffect: ?*?*IUnknown, textRange: ?*DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).GetDrawingEffect(@ptrCast(*const IDWriteTextLayout, self), currentPosition, drawingEffect, textRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_GetInlineObject(self: *const T, currentPosition: u32, inlineObject: ?*?*IDWriteInlineObject, textRange: ?*DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).GetInlineObject(@ptrCast(*const IDWriteTextLayout, self), currentPosition, inlineObject, textRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_GetTypography(self: *const T, currentPosition: u32, typography: ?*?*IDWriteTypography, textRange: ?*DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).GetTypography(@ptrCast(*const IDWriteTextLayout, self), currentPosition, typography, textRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_GetLocaleNameLength(self: *const T, currentPosition: u32, nameLength: ?*u32, textRange: ?*DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).GetLocaleNameLength(@ptrCast(*const IDWriteTextLayout, self), currentPosition, nameLength, textRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_GetLocaleName(self: *const T, currentPosition: u32, localeName: [*:0]u16, nameSize: u32, textRange: ?*DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).GetLocaleName(@ptrCast(*const IDWriteTextLayout, self), currentPosition, localeName, nameSize, textRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_Draw(self: *const T, clientDrawingContext: ?*anyopaque, renderer: ?*IDWriteTextRenderer, originX: f32, originY: f32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).Draw(@ptrCast(*const IDWriteTextLayout, self), clientDrawingContext, renderer, originX, originY);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_GetLineMetrics(self: *const T, lineMetrics: ?[*]DWRITE_LINE_METRICS, maxLineCount: u32, actualLineCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).GetLineMetrics(@ptrCast(*const IDWriteTextLayout, self), lineMetrics, maxLineCount, actualLineCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_GetMetrics(self: *const T, textMetrics: ?*DWRITE_TEXT_METRICS) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).GetMetrics(@ptrCast(*const IDWriteTextLayout, self), textMetrics);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_GetOverhangMetrics(self: *const T, overhangs: ?*DWRITE_OVERHANG_METRICS) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).GetOverhangMetrics(@ptrCast(*const IDWriteTextLayout, self), overhangs);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_GetClusterMetrics(self: *const T, clusterMetrics: ?[*]DWRITE_CLUSTER_METRICS, maxClusterCount: u32, actualClusterCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).GetClusterMetrics(@ptrCast(*const IDWriteTextLayout, self), clusterMetrics, maxClusterCount, actualClusterCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_DetermineMinWidth(self: *const T, minWidth: ?*f32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).DetermineMinWidth(@ptrCast(*const IDWriteTextLayout, self), minWidth);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_HitTestPoint(self: *const T, pointX: f32, pointY: f32, isTrailingHit: ?*BOOL, isInside: ?*BOOL, hitTestMetrics: ?*DWRITE_HIT_TEST_METRICS) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).HitTestPoint(@ptrCast(*const IDWriteTextLayout, self), pointX, pointY, isTrailingHit, isInside, hitTestMetrics);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_HitTestTextPosition(self: *const T, textPosition: u32, isTrailingHit: BOOL, pointX: ?*f32, pointY: ?*f32, hitTestMetrics: ?*DWRITE_HIT_TEST_METRICS) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).HitTestTextPosition(@ptrCast(*const IDWriteTextLayout, self), textPosition, isTrailingHit, pointX, pointY, hitTestMetrics);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout_HitTestTextRange(self: *const T, textPosition: u32, textLength: u32, originX: f32, originY: f32, hitTestMetrics: ?[*]DWRITE_HIT_TEST_METRICS, maxHitTestMetricsCount: u32, actualHitTestMetricsCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout.VTable, self.vtable).HitTestTextRange(@ptrCast(*const IDWriteTextLayout, self), textPosition, textLength, originX, originY, hitTestMetrics, maxHitTestMetricsCount, actualHitTestMetricsCount);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IDWriteBitmapRenderTarget_Value = Guid.initString("5e5a32a3-8dff-4773-9ff6-0696eab77267");
pub const IID_IDWriteBitmapRenderTarget = &IID_IDWriteBitmapRenderTarget_Value;
pub const IDWriteBitmapRenderTarget = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
DrawGlyphRun: fn(
self: *const IDWriteBitmapRenderTarget,
baselineOriginX: f32,
baselineOriginY: f32,
measuringMode: DWRITE_MEASURING_MODE,
glyphRun: ?*const DWRITE_GLYPH_RUN,
renderingParams: ?*IDWriteRenderingParams,
textColor: u32,
blackBoxRect: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetMemoryDC: fn(
self: *const IDWriteBitmapRenderTarget,
) callconv(@import("std").os.windows.WINAPI) ?HDC,
GetPixelsPerDip: fn(
self: *const IDWriteBitmapRenderTarget,
) callconv(@import("std").os.windows.WINAPI) f32,
SetPixelsPerDip: fn(
self: *const IDWriteBitmapRenderTarget,
pixelsPerDip: f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCurrentTransform: fn(
self: *const IDWriteBitmapRenderTarget,
transform: ?*DWRITE_MATRIX,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCurrentTransform: fn(
self: *const IDWriteBitmapRenderTarget,
transform: ?*const DWRITE_MATRIX,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSize: fn(
self: *const IDWriteBitmapRenderTarget,
size: ?*SIZE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Resize: fn(
self: *const IDWriteBitmapRenderTarget,
width: u32,
height: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteBitmapRenderTarget_DrawGlyphRun(self: *const T, baselineOriginX: f32, baselineOriginY: f32, measuringMode: DWRITE_MEASURING_MODE, glyphRun: ?*const DWRITE_GLYPH_RUN, renderingParams: ?*IDWriteRenderingParams, textColor: u32, blackBoxRect: ?*RECT) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteBitmapRenderTarget.VTable, self.vtable).DrawGlyphRun(@ptrCast(*const IDWriteBitmapRenderTarget, self), baselineOriginX, baselineOriginY, measuringMode, glyphRun, renderingParams, textColor, blackBoxRect);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteBitmapRenderTarget_GetMemoryDC(self: *const T) callconv(.Inline) ?HDC {
return @ptrCast(*const IDWriteBitmapRenderTarget.VTable, self.vtable).GetMemoryDC(@ptrCast(*const IDWriteBitmapRenderTarget, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteBitmapRenderTarget_GetPixelsPerDip(self: *const T) callconv(.Inline) f32 {
return @ptrCast(*const IDWriteBitmapRenderTarget.VTable, self.vtable).GetPixelsPerDip(@ptrCast(*const IDWriteBitmapRenderTarget, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteBitmapRenderTarget_SetPixelsPerDip(self: *const T, pixelsPerDip: f32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteBitmapRenderTarget.VTable, self.vtable).SetPixelsPerDip(@ptrCast(*const IDWriteBitmapRenderTarget, self), pixelsPerDip);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteBitmapRenderTarget_GetCurrentTransform(self: *const T, transform: ?*DWRITE_MATRIX) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteBitmapRenderTarget.VTable, self.vtable).GetCurrentTransform(@ptrCast(*const IDWriteBitmapRenderTarget, self), transform);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteBitmapRenderTarget_SetCurrentTransform(self: *const T, transform: ?*const DWRITE_MATRIX) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteBitmapRenderTarget.VTable, self.vtable).SetCurrentTransform(@ptrCast(*const IDWriteBitmapRenderTarget, self), transform);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteBitmapRenderTarget_GetSize(self: *const T, size: ?*SIZE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteBitmapRenderTarget.VTable, self.vtable).GetSize(@ptrCast(*const IDWriteBitmapRenderTarget, self), size);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteBitmapRenderTarget_Resize(self: *const T, width: u32, height: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteBitmapRenderTarget.VTable, self.vtable).Resize(@ptrCast(*const IDWriteBitmapRenderTarget, self), width, height);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IDWriteGdiInterop_Value = Guid.initString("1edd9491-9853-4299-898f-6432983b6f3a");
pub const IID_IDWriteGdiInterop = &IID_IDWriteGdiInterop_Value;
pub const IDWriteGdiInterop = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
CreateFontFromLOGFONT: fn(
self: *const IDWriteGdiInterop,
logFont: ?*const LOGFONTW,
font: ?*?*IDWriteFont,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ConvertFontToLOGFONT: fn(
self: *const IDWriteGdiInterop,
font: ?*IDWriteFont,
logFont: ?*LOGFONTW,
isSystemFont: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ConvertFontFaceToLOGFONT: fn(
self: *const IDWriteGdiInterop,
font: ?*IDWriteFontFace,
logFont: ?*LOGFONTW,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateFontFaceFromHdc: fn(
self: *const IDWriteGdiInterop,
hdc: ?HDC,
fontFace: ?*?*IDWriteFontFace,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateBitmapRenderTarget: fn(
self: *const IDWriteGdiInterop,
hdc: ?HDC,
width: u32,
height: u32,
renderTarget: ?*?*IDWriteBitmapRenderTarget,
) 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 IDWriteGdiInterop_CreateFontFromLOGFONT(self: *const T, logFont: ?*const LOGFONTW, font: ?*?*IDWriteFont) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteGdiInterop.VTable, self.vtable).CreateFontFromLOGFONT(@ptrCast(*const IDWriteGdiInterop, self), logFont, font);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteGdiInterop_ConvertFontToLOGFONT(self: *const T, font: ?*IDWriteFont, logFont: ?*LOGFONTW, isSystemFont: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteGdiInterop.VTable, self.vtable).ConvertFontToLOGFONT(@ptrCast(*const IDWriteGdiInterop, self), font, logFont, isSystemFont);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteGdiInterop_ConvertFontFaceToLOGFONT(self: *const T, font: ?*IDWriteFontFace, logFont: ?*LOGFONTW) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteGdiInterop.VTable, self.vtable).ConvertFontFaceToLOGFONT(@ptrCast(*const IDWriteGdiInterop, self), font, logFont);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteGdiInterop_CreateFontFaceFromHdc(self: *const T, hdc: ?HDC, fontFace: ?*?*IDWriteFontFace) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteGdiInterop.VTable, self.vtable).CreateFontFaceFromHdc(@ptrCast(*const IDWriteGdiInterop, self), hdc, fontFace);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteGdiInterop_CreateBitmapRenderTarget(self: *const T, hdc: ?HDC, width: u32, height: u32, renderTarget: ?*?*IDWriteBitmapRenderTarget) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteGdiInterop.VTable, self.vtable).CreateBitmapRenderTarget(@ptrCast(*const IDWriteGdiInterop, self), hdc, width, height, renderTarget);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DWRITE_TEXTURE_TYPE = enum(i32) {
ALIASED_1x1 = 0,
CLEARTYPE_3x1 = 1,
};
pub const DWRITE_TEXTURE_ALIASED_1x1 = DWRITE_TEXTURE_TYPE.ALIASED_1x1;
pub const DWRITE_TEXTURE_CLEARTYPE_3x1 = DWRITE_TEXTURE_TYPE.CLEARTYPE_3x1;
// TODO: this type is limited to platform 'windows6.1'
const IID_IDWriteGlyphRunAnalysis_Value = Guid.initString("7d97dbf7-e085-42d4-81e3-6a883bded118");
pub const IID_IDWriteGlyphRunAnalysis = &IID_IDWriteGlyphRunAnalysis_Value;
pub const IDWriteGlyphRunAnalysis = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetAlphaTextureBounds: fn(
self: *const IDWriteGlyphRunAnalysis,
textureType: DWRITE_TEXTURE_TYPE,
textureBounds: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateAlphaTexture: fn(
self: *const IDWriteGlyphRunAnalysis,
textureType: DWRITE_TEXTURE_TYPE,
textureBounds: ?*const RECT,
// TODO: what to do with BytesParamIndex 3?
alphaValues: ?*u8,
bufferSize: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetAlphaBlendParams: fn(
self: *const IDWriteGlyphRunAnalysis,
renderingParams: ?*IDWriteRenderingParams,
blendGamma: ?*f32,
blendEnhancedContrast: ?*f32,
blendClearTypeLevel: ?*f32,
) 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 IDWriteGlyphRunAnalysis_GetAlphaTextureBounds(self: *const T, textureType: DWRITE_TEXTURE_TYPE, textureBounds: ?*RECT) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteGlyphRunAnalysis.VTable, self.vtable).GetAlphaTextureBounds(@ptrCast(*const IDWriteGlyphRunAnalysis, self), textureType, textureBounds);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteGlyphRunAnalysis_CreateAlphaTexture(self: *const T, textureType: DWRITE_TEXTURE_TYPE, textureBounds: ?*const RECT, alphaValues: ?*u8, bufferSize: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteGlyphRunAnalysis.VTable, self.vtable).CreateAlphaTexture(@ptrCast(*const IDWriteGlyphRunAnalysis, self), textureType, textureBounds, alphaValues, bufferSize);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteGlyphRunAnalysis_GetAlphaBlendParams(self: *const T, renderingParams: ?*IDWriteRenderingParams, blendGamma: ?*f32, blendEnhancedContrast: ?*f32, blendClearTypeLevel: ?*f32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteGlyphRunAnalysis.VTable, self.vtable).GetAlphaBlendParams(@ptrCast(*const IDWriteGlyphRunAnalysis, self), renderingParams, blendGamma, blendEnhancedContrast, blendClearTypeLevel);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IDWriteFactory_Value = Guid.initString("b859ee5a-d838-4b5b-a2e8-1adc7d93db48");
pub const IID_IDWriteFactory = &IID_IDWriteFactory_Value;
pub const IDWriteFactory = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetSystemFontCollection: fn(
self: *const IDWriteFactory,
fontCollection: ?*?*IDWriteFontCollection,
checkForUpdates: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateCustomFontCollection: fn(
self: *const IDWriteFactory,
collectionLoader: ?*IDWriteFontCollectionLoader,
// TODO: what to do with BytesParamIndex 2?
collectionKey: ?*const anyopaque,
collectionKeySize: u32,
fontCollection: ?*?*IDWriteFontCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RegisterFontCollectionLoader: fn(
self: *const IDWriteFactory,
fontCollectionLoader: ?*IDWriteFontCollectionLoader,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UnregisterFontCollectionLoader: fn(
self: *const IDWriteFactory,
fontCollectionLoader: ?*IDWriteFontCollectionLoader,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateFontFileReference: fn(
self: *const IDWriteFactory,
filePath: ?[*:0]const u16,
lastWriteTime: ?*const FILETIME,
fontFile: ?*?*IDWriteFontFile,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateCustomFontFileReference: fn(
self: *const IDWriteFactory,
// TODO: what to do with BytesParamIndex 1?
fontFileReferenceKey: ?*const anyopaque,
fontFileReferenceKeySize: u32,
fontFileLoader: ?*IDWriteFontFileLoader,
fontFile: ?*?*IDWriteFontFile,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateFontFace: fn(
self: *const IDWriteFactory,
fontFaceType: DWRITE_FONT_FACE_TYPE,
numberOfFiles: u32,
fontFiles: [*]?*IDWriteFontFile,
faceIndex: u32,
fontFaceSimulationFlags: DWRITE_FONT_SIMULATIONS,
fontFace: ?*?*IDWriteFontFace,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateRenderingParams: fn(
self: *const IDWriteFactory,
renderingParams: ?*?*IDWriteRenderingParams,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateMonitorRenderingParams: fn(
self: *const IDWriteFactory,
monitor: ?HMONITOR,
renderingParams: ?*?*IDWriteRenderingParams,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateCustomRenderingParams: fn(
self: *const IDWriteFactory,
gamma: f32,
enhancedContrast: f32,
clearTypeLevel: f32,
pixelGeometry: DWRITE_PIXEL_GEOMETRY,
renderingMode: DWRITE_RENDERING_MODE,
renderingParams: ?*?*IDWriteRenderingParams,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RegisterFontFileLoader: fn(
self: *const IDWriteFactory,
fontFileLoader: ?*IDWriteFontFileLoader,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UnregisterFontFileLoader: fn(
self: *const IDWriteFactory,
fontFileLoader: ?*IDWriteFontFileLoader,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateTextFormat: fn(
self: *const IDWriteFactory,
fontFamilyName: ?[*:0]const u16,
fontCollection: ?*IDWriteFontCollection,
fontWeight: DWRITE_FONT_WEIGHT,
fontStyle: DWRITE_FONT_STYLE,
fontStretch: DWRITE_FONT_STRETCH,
fontSize: f32,
localeName: ?[*:0]const u16,
textFormat: ?*?*IDWriteTextFormat,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateTypography: fn(
self: *const IDWriteFactory,
typography: ?*?*IDWriteTypography,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetGdiInterop: fn(
self: *const IDWriteFactory,
gdiInterop: ?*?*IDWriteGdiInterop,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateTextLayout: fn(
self: *const IDWriteFactory,
string: [*:0]const u16,
stringLength: u32,
textFormat: ?*IDWriteTextFormat,
maxWidth: f32,
maxHeight: f32,
textLayout: ?*?*IDWriteTextLayout,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateGdiCompatibleTextLayout: fn(
self: *const IDWriteFactory,
string: [*:0]const u16,
stringLength: u32,
textFormat: ?*IDWriteTextFormat,
layoutWidth: f32,
layoutHeight: f32,
pixelsPerDip: f32,
transform: ?*const DWRITE_MATRIX,
useGdiNatural: BOOL,
textLayout: ?*?*IDWriteTextLayout,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateEllipsisTrimmingSign: fn(
self: *const IDWriteFactory,
textFormat: ?*IDWriteTextFormat,
trimmingSign: ?*?*IDWriteInlineObject,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateTextAnalyzer: fn(
self: *const IDWriteFactory,
textAnalyzer: ?*?*IDWriteTextAnalyzer,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateNumberSubstitution: fn(
self: *const IDWriteFactory,
substitutionMethod: DWRITE_NUMBER_SUBSTITUTION_METHOD,
localeName: ?[*:0]const u16,
ignoreUserOverride: BOOL,
numberSubstitution: ?*?*IDWriteNumberSubstitution,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateGlyphRunAnalysis: fn(
self: *const IDWriteFactory,
glyphRun: ?*const DWRITE_GLYPH_RUN,
pixelsPerDip: f32,
transform: ?*const DWRITE_MATRIX,
renderingMode: DWRITE_RENDERING_MODE,
measuringMode: DWRITE_MEASURING_MODE,
baselineOriginX: f32,
baselineOriginY: f32,
glyphRunAnalysis: ?*?*IDWriteGlyphRunAnalysis,
) 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 IDWriteFactory_GetSystemFontCollection(self: *const T, fontCollection: ?*?*IDWriteFontCollection, checkForUpdates: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory.VTable, self.vtable).GetSystemFontCollection(@ptrCast(*const IDWriteFactory, self), fontCollection, checkForUpdates);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory_CreateCustomFontCollection(self: *const T, collectionLoader: ?*IDWriteFontCollectionLoader, collectionKey: ?*const anyopaque, collectionKeySize: u32, fontCollection: ?*?*IDWriteFontCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory.VTable, self.vtable).CreateCustomFontCollection(@ptrCast(*const IDWriteFactory, self), collectionLoader, collectionKey, collectionKeySize, fontCollection);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory_RegisterFontCollectionLoader(self: *const T, fontCollectionLoader: ?*IDWriteFontCollectionLoader) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory.VTable, self.vtable).RegisterFontCollectionLoader(@ptrCast(*const IDWriteFactory, self), fontCollectionLoader);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory_UnregisterFontCollectionLoader(self: *const T, fontCollectionLoader: ?*IDWriteFontCollectionLoader) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory.VTable, self.vtable).UnregisterFontCollectionLoader(@ptrCast(*const IDWriteFactory, self), fontCollectionLoader);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory_CreateFontFileReference(self: *const T, filePath: ?[*:0]const u16, lastWriteTime: ?*const FILETIME, fontFile: ?*?*IDWriteFontFile) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory.VTable, self.vtable).CreateFontFileReference(@ptrCast(*const IDWriteFactory, self), filePath, lastWriteTime, fontFile);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory_CreateCustomFontFileReference(self: *const T, fontFileReferenceKey: ?*const anyopaque, fontFileReferenceKeySize: u32, fontFileLoader: ?*IDWriteFontFileLoader, fontFile: ?*?*IDWriteFontFile) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory.VTable, self.vtable).CreateCustomFontFileReference(@ptrCast(*const IDWriteFactory, self), fontFileReferenceKey, fontFileReferenceKeySize, fontFileLoader, fontFile);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory_CreateFontFace(self: *const T, fontFaceType: DWRITE_FONT_FACE_TYPE, numberOfFiles: u32, fontFiles: [*]?*IDWriteFontFile, faceIndex: u32, fontFaceSimulationFlags: DWRITE_FONT_SIMULATIONS, fontFace: ?*?*IDWriteFontFace) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory.VTable, self.vtable).CreateFontFace(@ptrCast(*const IDWriteFactory, self), fontFaceType, numberOfFiles, fontFiles, faceIndex, fontFaceSimulationFlags, fontFace);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory_CreateRenderingParams(self: *const T, renderingParams: ?*?*IDWriteRenderingParams) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory.VTable, self.vtable).CreateRenderingParams(@ptrCast(*const IDWriteFactory, self), renderingParams);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory_CreateMonitorRenderingParams(self: *const T, monitor: ?HMONITOR, renderingParams: ?*?*IDWriteRenderingParams) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory.VTable, self.vtable).CreateMonitorRenderingParams(@ptrCast(*const IDWriteFactory, self), monitor, renderingParams);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory_CreateCustomRenderingParams(self: *const T, gamma: f32, enhancedContrast: f32, clearTypeLevel: f32, pixelGeometry: DWRITE_PIXEL_GEOMETRY, renderingMode: DWRITE_RENDERING_MODE, renderingParams: ?*?*IDWriteRenderingParams) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory.VTable, self.vtable).CreateCustomRenderingParams(@ptrCast(*const IDWriteFactory, self), gamma, enhancedContrast, clearTypeLevel, pixelGeometry, renderingMode, renderingParams);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory_RegisterFontFileLoader(self: *const T, fontFileLoader: ?*IDWriteFontFileLoader) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory.VTable, self.vtable).RegisterFontFileLoader(@ptrCast(*const IDWriteFactory, self), fontFileLoader);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory_UnregisterFontFileLoader(self: *const T, fontFileLoader: ?*IDWriteFontFileLoader) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory.VTable, self.vtable).UnregisterFontFileLoader(@ptrCast(*const IDWriteFactory, self), fontFileLoader);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory_CreateTextFormat(self: *const T, fontFamilyName: ?[*:0]const u16, fontCollection: ?*IDWriteFontCollection, fontWeight: DWRITE_FONT_WEIGHT, fontStyle: DWRITE_FONT_STYLE, fontStretch: DWRITE_FONT_STRETCH, fontSize: f32, localeName: ?[*:0]const u16, textFormat: ?*?*IDWriteTextFormat) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory.VTable, self.vtable).CreateTextFormat(@ptrCast(*const IDWriteFactory, self), fontFamilyName, fontCollection, fontWeight, fontStyle, fontStretch, fontSize, localeName, textFormat);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory_CreateTypography(self: *const T, typography: ?*?*IDWriteTypography) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory.VTable, self.vtable).CreateTypography(@ptrCast(*const IDWriteFactory, self), typography);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory_GetGdiInterop(self: *const T, gdiInterop: ?*?*IDWriteGdiInterop) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory.VTable, self.vtable).GetGdiInterop(@ptrCast(*const IDWriteFactory, self), gdiInterop);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory_CreateTextLayout(self: *const T, string: [*:0]const u16, stringLength: u32, textFormat: ?*IDWriteTextFormat, maxWidth: f32, maxHeight: f32, textLayout: ?*?*IDWriteTextLayout) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory.VTable, self.vtable).CreateTextLayout(@ptrCast(*const IDWriteFactory, self), string, stringLength, textFormat, maxWidth, maxHeight, textLayout);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory_CreateGdiCompatibleTextLayout(self: *const T, string: [*:0]const u16, stringLength: u32, textFormat: ?*IDWriteTextFormat, layoutWidth: f32, layoutHeight: f32, pixelsPerDip: f32, transform: ?*const DWRITE_MATRIX, useGdiNatural: BOOL, textLayout: ?*?*IDWriteTextLayout) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory.VTable, self.vtable).CreateGdiCompatibleTextLayout(@ptrCast(*const IDWriteFactory, self), string, stringLength, textFormat, layoutWidth, layoutHeight, pixelsPerDip, transform, useGdiNatural, textLayout);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory_CreateEllipsisTrimmingSign(self: *const T, textFormat: ?*IDWriteTextFormat, trimmingSign: ?*?*IDWriteInlineObject) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory.VTable, self.vtable).CreateEllipsisTrimmingSign(@ptrCast(*const IDWriteFactory, self), textFormat, trimmingSign);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory_CreateTextAnalyzer(self: *const T, textAnalyzer: ?*?*IDWriteTextAnalyzer) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory.VTable, self.vtable).CreateTextAnalyzer(@ptrCast(*const IDWriteFactory, self), textAnalyzer);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory_CreateNumberSubstitution(self: *const T, substitutionMethod: DWRITE_NUMBER_SUBSTITUTION_METHOD, localeName: ?[*:0]const u16, ignoreUserOverride: BOOL, numberSubstitution: ?*?*IDWriteNumberSubstitution) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory.VTable, self.vtable).CreateNumberSubstitution(@ptrCast(*const IDWriteFactory, self), substitutionMethod, localeName, ignoreUserOverride, numberSubstitution);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory_CreateGlyphRunAnalysis(self: *const T, glyphRun: ?*const DWRITE_GLYPH_RUN, pixelsPerDip: f32, transform: ?*const DWRITE_MATRIX, renderingMode: DWRITE_RENDERING_MODE, measuringMode: DWRITE_MEASURING_MODE, baselineOriginX: f32, baselineOriginY: f32, glyphRunAnalysis: ?*?*IDWriteGlyphRunAnalysis) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory.VTable, self.vtable).CreateGlyphRunAnalysis(@ptrCast(*const IDWriteFactory, self), glyphRun, pixelsPerDip, transform, renderingMode, measuringMode, baselineOriginX, baselineOriginY, glyphRunAnalysis);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DWRITE_PANOSE_FAMILY = enum(i32) {
ANY = 0,
NO_FIT = 1,
TEXT_DISPLAY = 2,
SCRIPT = 3,
DECORATIVE = 4,
SYMBOL = 5,
// PICTORIAL = 5, this enum value conflicts with SYMBOL
};
pub const DWRITE_PANOSE_FAMILY_ANY = DWRITE_PANOSE_FAMILY.ANY;
pub const DWRITE_PANOSE_FAMILY_NO_FIT = DWRITE_PANOSE_FAMILY.NO_FIT;
pub const DWRITE_PANOSE_FAMILY_TEXT_DISPLAY = DWRITE_PANOSE_FAMILY.TEXT_DISPLAY;
pub const DWRITE_PANOSE_FAMILY_SCRIPT = DWRITE_PANOSE_FAMILY.SCRIPT;
pub const DWRITE_PANOSE_FAMILY_DECORATIVE = DWRITE_PANOSE_FAMILY.DECORATIVE;
pub const DWRITE_PANOSE_FAMILY_SYMBOL = DWRITE_PANOSE_FAMILY.SYMBOL;
pub const DWRITE_PANOSE_FAMILY_PICTORIAL = DWRITE_PANOSE_FAMILY.SYMBOL;
pub const DWRITE_PANOSE_SERIF_STYLE = enum(i32) {
ANY = 0,
NO_FIT = 1,
COVE = 2,
OBTUSE_COVE = 3,
SQUARE_COVE = 4,
OBTUSE_SQUARE_COVE = 5,
SQUARE = 6,
THIN = 7,
OVAL = 8,
EXAGGERATED = 9,
TRIANGLE = 10,
NORMAL_SANS = 11,
OBTUSE_SANS = 12,
PERPENDICULAR_SANS = 13,
FLARED = 14,
ROUNDED = 15,
SCRIPT = 16,
// PERP_SANS = 13, this enum value conflicts with PERPENDICULAR_SANS
// BONE = 8, this enum value conflicts with OVAL
};
pub const DWRITE_PANOSE_SERIF_STYLE_ANY = DWRITE_PANOSE_SERIF_STYLE.ANY;
pub const DWRITE_PANOSE_SERIF_STYLE_NO_FIT = DWRITE_PANOSE_SERIF_STYLE.NO_FIT;
pub const DWRITE_PANOSE_SERIF_STYLE_COVE = DWRITE_PANOSE_SERIF_STYLE.COVE;
pub const DWRITE_PANOSE_SERIF_STYLE_OBTUSE_COVE = DWRITE_PANOSE_SERIF_STYLE.OBTUSE_COVE;
pub const DWRITE_PANOSE_SERIF_STYLE_SQUARE_COVE = DWRITE_PANOSE_SERIF_STYLE.SQUARE_COVE;
pub const DWRITE_PANOSE_SERIF_STYLE_OBTUSE_SQUARE_COVE = DWRITE_PANOSE_SERIF_STYLE.OBTUSE_SQUARE_COVE;
pub const DWRITE_PANOSE_SERIF_STYLE_SQUARE = DWRITE_PANOSE_SERIF_STYLE.SQUARE;
pub const DWRITE_PANOSE_SERIF_STYLE_THIN = DWRITE_PANOSE_SERIF_STYLE.THIN;
pub const DWRITE_PANOSE_SERIF_STYLE_OVAL = DWRITE_PANOSE_SERIF_STYLE.OVAL;
pub const DWRITE_PANOSE_SERIF_STYLE_EXAGGERATED = DWRITE_PANOSE_SERIF_STYLE.EXAGGERATED;
pub const DWRITE_PANOSE_SERIF_STYLE_TRIANGLE = DWRITE_PANOSE_SERIF_STYLE.TRIANGLE;
pub const DWRITE_PANOSE_SERIF_STYLE_NORMAL_SANS = DWRITE_PANOSE_SERIF_STYLE.NORMAL_SANS;
pub const DWRITE_PANOSE_SERIF_STYLE_OBTUSE_SANS = DWRITE_PANOSE_SERIF_STYLE.OBTUSE_SANS;
pub const DWRITE_PANOSE_SERIF_STYLE_PERPENDICULAR_SANS = DWRITE_PANOSE_SERIF_STYLE.PERPENDICULAR_SANS;
pub const DWRITE_PANOSE_SERIF_STYLE_FLARED = DWRITE_PANOSE_SERIF_STYLE.FLARED;
pub const DWRITE_PANOSE_SERIF_STYLE_ROUNDED = DWRITE_PANOSE_SERIF_STYLE.ROUNDED;
pub const DWRITE_PANOSE_SERIF_STYLE_SCRIPT = DWRITE_PANOSE_SERIF_STYLE.SCRIPT;
pub const DWRITE_PANOSE_SERIF_STYLE_PERP_SANS = DWRITE_PANOSE_SERIF_STYLE.PERPENDICULAR_SANS;
pub const DWRITE_PANOSE_SERIF_STYLE_BONE = DWRITE_PANOSE_SERIF_STYLE.OVAL;
pub const DWRITE_PANOSE_WEIGHT = enum(i32) {
ANY = 0,
NO_FIT = 1,
VERY_LIGHT = 2,
LIGHT = 3,
THIN = 4,
BOOK = 5,
MEDIUM = 6,
DEMI = 7,
BOLD = 8,
HEAVY = 9,
BLACK = 10,
EXTRA_BLACK = 11,
// NORD = 11, this enum value conflicts with EXTRA_BLACK
};
pub const DWRITE_PANOSE_WEIGHT_ANY = DWRITE_PANOSE_WEIGHT.ANY;
pub const DWRITE_PANOSE_WEIGHT_NO_FIT = DWRITE_PANOSE_WEIGHT.NO_FIT;
pub const DWRITE_PANOSE_WEIGHT_VERY_LIGHT = DWRITE_PANOSE_WEIGHT.VERY_LIGHT;
pub const DWRITE_PANOSE_WEIGHT_LIGHT = DWRITE_PANOSE_WEIGHT.LIGHT;
pub const DWRITE_PANOSE_WEIGHT_THIN = DWRITE_PANOSE_WEIGHT.THIN;
pub const DWRITE_PANOSE_WEIGHT_BOOK = DWRITE_PANOSE_WEIGHT.BOOK;
pub const DWRITE_PANOSE_WEIGHT_MEDIUM = DWRITE_PANOSE_WEIGHT.MEDIUM;
pub const DWRITE_PANOSE_WEIGHT_DEMI = DWRITE_PANOSE_WEIGHT.DEMI;
pub const DWRITE_PANOSE_WEIGHT_BOLD = DWRITE_PANOSE_WEIGHT.BOLD;
pub const DWRITE_PANOSE_WEIGHT_HEAVY = DWRITE_PANOSE_WEIGHT.HEAVY;
pub const DWRITE_PANOSE_WEIGHT_BLACK = DWRITE_PANOSE_WEIGHT.BLACK;
pub const DWRITE_PANOSE_WEIGHT_EXTRA_BLACK = DWRITE_PANOSE_WEIGHT.EXTRA_BLACK;
pub const DWRITE_PANOSE_WEIGHT_NORD = DWRITE_PANOSE_WEIGHT.EXTRA_BLACK;
pub const DWRITE_PANOSE_PROPORTION = enum(i32) {
ANY = 0,
NO_FIT = 1,
OLD_STYLE = 2,
MODERN = 3,
EVEN_WIDTH = 4,
EXPANDED = 5,
CONDENSED = 6,
VERY_EXPANDED = 7,
VERY_CONDENSED = 8,
MONOSPACED = 9,
};
pub const DWRITE_PANOSE_PROPORTION_ANY = DWRITE_PANOSE_PROPORTION.ANY;
pub const DWRITE_PANOSE_PROPORTION_NO_FIT = DWRITE_PANOSE_PROPORTION.NO_FIT;
pub const DWRITE_PANOSE_PROPORTION_OLD_STYLE = DWRITE_PANOSE_PROPORTION.OLD_STYLE;
pub const DWRITE_PANOSE_PROPORTION_MODERN = DWRITE_PANOSE_PROPORTION.MODERN;
pub const DWRITE_PANOSE_PROPORTION_EVEN_WIDTH = DWRITE_PANOSE_PROPORTION.EVEN_WIDTH;
pub const DWRITE_PANOSE_PROPORTION_EXPANDED = DWRITE_PANOSE_PROPORTION.EXPANDED;
pub const DWRITE_PANOSE_PROPORTION_CONDENSED = DWRITE_PANOSE_PROPORTION.CONDENSED;
pub const DWRITE_PANOSE_PROPORTION_VERY_EXPANDED = DWRITE_PANOSE_PROPORTION.VERY_EXPANDED;
pub const DWRITE_PANOSE_PROPORTION_VERY_CONDENSED = DWRITE_PANOSE_PROPORTION.VERY_CONDENSED;
pub const DWRITE_PANOSE_PROPORTION_MONOSPACED = DWRITE_PANOSE_PROPORTION.MONOSPACED;
pub const DWRITE_PANOSE_CONTRAST = enum(i32) {
ANY = 0,
NO_FIT = 1,
NONE = 2,
VERY_LOW = 3,
LOW = 4,
MEDIUM_LOW = 5,
MEDIUM = 6,
MEDIUM_HIGH = 7,
HIGH = 8,
VERY_HIGH = 9,
HORIZONTAL_LOW = 10,
HORIZONTAL_MEDIUM = 11,
HORIZONTAL_HIGH = 12,
BROKEN = 13,
};
pub const DWRITE_PANOSE_CONTRAST_ANY = DWRITE_PANOSE_CONTRAST.ANY;
pub const DWRITE_PANOSE_CONTRAST_NO_FIT = DWRITE_PANOSE_CONTRAST.NO_FIT;
pub const DWRITE_PANOSE_CONTRAST_NONE = DWRITE_PANOSE_CONTRAST.NONE;
pub const DWRITE_PANOSE_CONTRAST_VERY_LOW = DWRITE_PANOSE_CONTRAST.VERY_LOW;
pub const DWRITE_PANOSE_CONTRAST_LOW = DWRITE_PANOSE_CONTRAST.LOW;
pub const DWRITE_PANOSE_CONTRAST_MEDIUM_LOW = DWRITE_PANOSE_CONTRAST.MEDIUM_LOW;
pub const DWRITE_PANOSE_CONTRAST_MEDIUM = DWRITE_PANOSE_CONTRAST.MEDIUM;
pub const DWRITE_PANOSE_CONTRAST_MEDIUM_HIGH = DWRITE_PANOSE_CONTRAST.MEDIUM_HIGH;
pub const DWRITE_PANOSE_CONTRAST_HIGH = DWRITE_PANOSE_CONTRAST.HIGH;
pub const DWRITE_PANOSE_CONTRAST_VERY_HIGH = DWRITE_PANOSE_CONTRAST.VERY_HIGH;
pub const DWRITE_PANOSE_CONTRAST_HORIZONTAL_LOW = DWRITE_PANOSE_CONTRAST.HORIZONTAL_LOW;
pub const DWRITE_PANOSE_CONTRAST_HORIZONTAL_MEDIUM = DWRITE_PANOSE_CONTRAST.HORIZONTAL_MEDIUM;
pub const DWRITE_PANOSE_CONTRAST_HORIZONTAL_HIGH = DWRITE_PANOSE_CONTRAST.HORIZONTAL_HIGH;
pub const DWRITE_PANOSE_CONTRAST_BROKEN = DWRITE_PANOSE_CONTRAST.BROKEN;
pub const DWRITE_PANOSE_STROKE_VARIATION = enum(i32) {
ANY = 0,
NO_FIT = 1,
NO_VARIATION = 2,
GRADUAL_DIAGONAL = 3,
GRADUAL_TRANSITIONAL = 4,
GRADUAL_VERTICAL = 5,
GRADUAL_HORIZONTAL = 6,
RAPID_VERTICAL = 7,
RAPID_HORIZONTAL = 8,
INSTANT_VERTICAL = 9,
INSTANT_HORIZONTAL = 10,
};
pub const DWRITE_PANOSE_STROKE_VARIATION_ANY = DWRITE_PANOSE_STROKE_VARIATION.ANY;
pub const DWRITE_PANOSE_STROKE_VARIATION_NO_FIT = DWRITE_PANOSE_STROKE_VARIATION.NO_FIT;
pub const DWRITE_PANOSE_STROKE_VARIATION_NO_VARIATION = DWRITE_PANOSE_STROKE_VARIATION.NO_VARIATION;
pub const DWRITE_PANOSE_STROKE_VARIATION_GRADUAL_DIAGONAL = DWRITE_PANOSE_STROKE_VARIATION.GRADUAL_DIAGONAL;
pub const DWRITE_PANOSE_STROKE_VARIATION_GRADUAL_TRANSITIONAL = DWRITE_PANOSE_STROKE_VARIATION.GRADUAL_TRANSITIONAL;
pub const DWRITE_PANOSE_STROKE_VARIATION_GRADUAL_VERTICAL = DWRITE_PANOSE_STROKE_VARIATION.GRADUAL_VERTICAL;
pub const DWRITE_PANOSE_STROKE_VARIATION_GRADUAL_HORIZONTAL = DWRITE_PANOSE_STROKE_VARIATION.GRADUAL_HORIZONTAL;
pub const DWRITE_PANOSE_STROKE_VARIATION_RAPID_VERTICAL = DWRITE_PANOSE_STROKE_VARIATION.RAPID_VERTICAL;
pub const DWRITE_PANOSE_STROKE_VARIATION_RAPID_HORIZONTAL = DWRITE_PANOSE_STROKE_VARIATION.RAPID_HORIZONTAL;
pub const DWRITE_PANOSE_STROKE_VARIATION_INSTANT_VERTICAL = DWRITE_PANOSE_STROKE_VARIATION.INSTANT_VERTICAL;
pub const DWRITE_PANOSE_STROKE_VARIATION_INSTANT_HORIZONTAL = DWRITE_PANOSE_STROKE_VARIATION.INSTANT_HORIZONTAL;
pub const DWRITE_PANOSE_ARM_STYLE = enum(i32) {
ANY = 0,
NO_FIT = 1,
STRAIGHT_ARMS_HORIZONTAL = 2,
STRAIGHT_ARMS_WEDGE = 3,
STRAIGHT_ARMS_VERTICAL = 4,
STRAIGHT_ARMS_SINGLE_SERIF = 5,
STRAIGHT_ARMS_DOUBLE_SERIF = 6,
NONSTRAIGHT_ARMS_HORIZONTAL = 7,
NONSTRAIGHT_ARMS_WEDGE = 8,
NONSTRAIGHT_ARMS_VERTICAL = 9,
NONSTRAIGHT_ARMS_SINGLE_SERIF = 10,
NONSTRAIGHT_ARMS_DOUBLE_SERIF = 11,
// STRAIGHT_ARMS_HORZ = 2, this enum value conflicts with STRAIGHT_ARMS_HORIZONTAL
// STRAIGHT_ARMS_VERT = 4, this enum value conflicts with STRAIGHT_ARMS_VERTICAL
// BENT_ARMS_HORZ = 7, this enum value conflicts with NONSTRAIGHT_ARMS_HORIZONTAL
// BENT_ARMS_WEDGE = 8, this enum value conflicts with NONSTRAIGHT_ARMS_WEDGE
// BENT_ARMS_VERT = 9, this enum value conflicts with NONSTRAIGHT_ARMS_VERTICAL
// BENT_ARMS_SINGLE_SERIF = 10, this enum value conflicts with NONSTRAIGHT_ARMS_SINGLE_SERIF
// BENT_ARMS_DOUBLE_SERIF = 11, this enum value conflicts with NONSTRAIGHT_ARMS_DOUBLE_SERIF
};
pub const DWRITE_PANOSE_ARM_STYLE_ANY = DWRITE_PANOSE_ARM_STYLE.ANY;
pub const DWRITE_PANOSE_ARM_STYLE_NO_FIT = DWRITE_PANOSE_ARM_STYLE.NO_FIT;
pub const DWRITE_PANOSE_ARM_STYLE_STRAIGHT_ARMS_HORIZONTAL = DWRITE_PANOSE_ARM_STYLE.STRAIGHT_ARMS_HORIZONTAL;
pub const DWRITE_PANOSE_ARM_STYLE_STRAIGHT_ARMS_WEDGE = DWRITE_PANOSE_ARM_STYLE.STRAIGHT_ARMS_WEDGE;
pub const DWRITE_PANOSE_ARM_STYLE_STRAIGHT_ARMS_VERTICAL = DWRITE_PANOSE_ARM_STYLE.STRAIGHT_ARMS_VERTICAL;
pub const DWRITE_PANOSE_ARM_STYLE_STRAIGHT_ARMS_SINGLE_SERIF = DWRITE_PANOSE_ARM_STYLE.STRAIGHT_ARMS_SINGLE_SERIF;
pub const DWRITE_PANOSE_ARM_STYLE_STRAIGHT_ARMS_DOUBLE_SERIF = DWRITE_PANOSE_ARM_STYLE.STRAIGHT_ARMS_DOUBLE_SERIF;
pub const DWRITE_PANOSE_ARM_STYLE_NONSTRAIGHT_ARMS_HORIZONTAL = DWRITE_PANOSE_ARM_STYLE.NONSTRAIGHT_ARMS_HORIZONTAL;
pub const DWRITE_PANOSE_ARM_STYLE_NONSTRAIGHT_ARMS_WEDGE = DWRITE_PANOSE_ARM_STYLE.NONSTRAIGHT_ARMS_WEDGE;
pub const DWRITE_PANOSE_ARM_STYLE_NONSTRAIGHT_ARMS_VERTICAL = DWRITE_PANOSE_ARM_STYLE.NONSTRAIGHT_ARMS_VERTICAL;
pub const DWRITE_PANOSE_ARM_STYLE_NONSTRAIGHT_ARMS_SINGLE_SERIF = DWRITE_PANOSE_ARM_STYLE.NONSTRAIGHT_ARMS_SINGLE_SERIF;
pub const DWRITE_PANOSE_ARM_STYLE_NONSTRAIGHT_ARMS_DOUBLE_SERIF = DWRITE_PANOSE_ARM_STYLE.NONSTRAIGHT_ARMS_DOUBLE_SERIF;
pub const DWRITE_PANOSE_ARM_STYLE_STRAIGHT_ARMS_HORZ = DWRITE_PANOSE_ARM_STYLE.STRAIGHT_ARMS_HORIZONTAL;
pub const DWRITE_PANOSE_ARM_STYLE_STRAIGHT_ARMS_VERT = DWRITE_PANOSE_ARM_STYLE.STRAIGHT_ARMS_VERTICAL;
pub const DWRITE_PANOSE_ARM_STYLE_BENT_ARMS_HORZ = DWRITE_PANOSE_ARM_STYLE.NONSTRAIGHT_ARMS_HORIZONTAL;
pub const DWRITE_PANOSE_ARM_STYLE_BENT_ARMS_WEDGE = DWRITE_PANOSE_ARM_STYLE.NONSTRAIGHT_ARMS_WEDGE;
pub const DWRITE_PANOSE_ARM_STYLE_BENT_ARMS_VERT = DWRITE_PANOSE_ARM_STYLE.NONSTRAIGHT_ARMS_VERTICAL;
pub const DWRITE_PANOSE_ARM_STYLE_BENT_ARMS_SINGLE_SERIF = DWRITE_PANOSE_ARM_STYLE.NONSTRAIGHT_ARMS_SINGLE_SERIF;
pub const DWRITE_PANOSE_ARM_STYLE_BENT_ARMS_DOUBLE_SERIF = DWRITE_PANOSE_ARM_STYLE.NONSTRAIGHT_ARMS_DOUBLE_SERIF;
pub const DWRITE_PANOSE_LETTERFORM = enum(i32) {
ANY = 0,
NO_FIT = 1,
NORMAL_CONTACT = 2,
NORMAL_WEIGHTED = 3,
NORMAL_BOXED = 4,
NORMAL_FLATTENED = 5,
NORMAL_ROUNDED = 6,
NORMAL_OFF_CENTER = 7,
NORMAL_SQUARE = 8,
OBLIQUE_CONTACT = 9,
OBLIQUE_WEIGHTED = 10,
OBLIQUE_BOXED = 11,
OBLIQUE_FLATTENED = 12,
OBLIQUE_ROUNDED = 13,
OBLIQUE_OFF_CENTER = 14,
OBLIQUE_SQUARE = 15,
};
pub const DWRITE_PANOSE_LETTERFORM_ANY = DWRITE_PANOSE_LETTERFORM.ANY;
pub const DWRITE_PANOSE_LETTERFORM_NO_FIT = DWRITE_PANOSE_LETTERFORM.NO_FIT;
pub const DWRITE_PANOSE_LETTERFORM_NORMAL_CONTACT = DWRITE_PANOSE_LETTERFORM.NORMAL_CONTACT;
pub const DWRITE_PANOSE_LETTERFORM_NORMAL_WEIGHTED = DWRITE_PANOSE_LETTERFORM.NORMAL_WEIGHTED;
pub const DWRITE_PANOSE_LETTERFORM_NORMAL_BOXED = DWRITE_PANOSE_LETTERFORM.NORMAL_BOXED;
pub const DWRITE_PANOSE_LETTERFORM_NORMAL_FLATTENED = DWRITE_PANOSE_LETTERFORM.NORMAL_FLATTENED;
pub const DWRITE_PANOSE_LETTERFORM_NORMAL_ROUNDED = DWRITE_PANOSE_LETTERFORM.NORMAL_ROUNDED;
pub const DWRITE_PANOSE_LETTERFORM_NORMAL_OFF_CENTER = DWRITE_PANOSE_LETTERFORM.NORMAL_OFF_CENTER;
pub const DWRITE_PANOSE_LETTERFORM_NORMAL_SQUARE = DWRITE_PANOSE_LETTERFORM.NORMAL_SQUARE;
pub const DWRITE_PANOSE_LETTERFORM_OBLIQUE_CONTACT = DWRITE_PANOSE_LETTERFORM.OBLIQUE_CONTACT;
pub const DWRITE_PANOSE_LETTERFORM_OBLIQUE_WEIGHTED = DWRITE_PANOSE_LETTERFORM.OBLIQUE_WEIGHTED;
pub const DWRITE_PANOSE_LETTERFORM_OBLIQUE_BOXED = DWRITE_PANOSE_LETTERFORM.OBLIQUE_BOXED;
pub const DWRITE_PANOSE_LETTERFORM_OBLIQUE_FLATTENED = DWRITE_PANOSE_LETTERFORM.OBLIQUE_FLATTENED;
pub const DWRITE_PANOSE_LETTERFORM_OBLIQUE_ROUNDED = DWRITE_PANOSE_LETTERFORM.OBLIQUE_ROUNDED;
pub const DWRITE_PANOSE_LETTERFORM_OBLIQUE_OFF_CENTER = DWRITE_PANOSE_LETTERFORM.OBLIQUE_OFF_CENTER;
pub const DWRITE_PANOSE_LETTERFORM_OBLIQUE_SQUARE = DWRITE_PANOSE_LETTERFORM.OBLIQUE_SQUARE;
pub const DWRITE_PANOSE_MIDLINE = enum(i32) {
ANY = 0,
NO_FIT = 1,
STANDARD_TRIMMED = 2,
STANDARD_POINTED = 3,
STANDARD_SERIFED = 4,
HIGH_TRIMMED = 5,
HIGH_POINTED = 6,
HIGH_SERIFED = 7,
CONSTANT_TRIMMED = 8,
CONSTANT_POINTED = 9,
CONSTANT_SERIFED = 10,
LOW_TRIMMED = 11,
LOW_POINTED = 12,
LOW_SERIFED = 13,
};
pub const DWRITE_PANOSE_MIDLINE_ANY = DWRITE_PANOSE_MIDLINE.ANY;
pub const DWRITE_PANOSE_MIDLINE_NO_FIT = DWRITE_PANOSE_MIDLINE.NO_FIT;
pub const DWRITE_PANOSE_MIDLINE_STANDARD_TRIMMED = DWRITE_PANOSE_MIDLINE.STANDARD_TRIMMED;
pub const DWRITE_PANOSE_MIDLINE_STANDARD_POINTED = DWRITE_PANOSE_MIDLINE.STANDARD_POINTED;
pub const DWRITE_PANOSE_MIDLINE_STANDARD_SERIFED = DWRITE_PANOSE_MIDLINE.STANDARD_SERIFED;
pub const DWRITE_PANOSE_MIDLINE_HIGH_TRIMMED = DWRITE_PANOSE_MIDLINE.HIGH_TRIMMED;
pub const DWRITE_PANOSE_MIDLINE_HIGH_POINTED = DWRITE_PANOSE_MIDLINE.HIGH_POINTED;
pub const DWRITE_PANOSE_MIDLINE_HIGH_SERIFED = DWRITE_PANOSE_MIDLINE.HIGH_SERIFED;
pub const DWRITE_PANOSE_MIDLINE_CONSTANT_TRIMMED = DWRITE_PANOSE_MIDLINE.CONSTANT_TRIMMED;
pub const DWRITE_PANOSE_MIDLINE_CONSTANT_POINTED = DWRITE_PANOSE_MIDLINE.CONSTANT_POINTED;
pub const DWRITE_PANOSE_MIDLINE_CONSTANT_SERIFED = DWRITE_PANOSE_MIDLINE.CONSTANT_SERIFED;
pub const DWRITE_PANOSE_MIDLINE_LOW_TRIMMED = DWRITE_PANOSE_MIDLINE.LOW_TRIMMED;
pub const DWRITE_PANOSE_MIDLINE_LOW_POINTED = DWRITE_PANOSE_MIDLINE.LOW_POINTED;
pub const DWRITE_PANOSE_MIDLINE_LOW_SERIFED = DWRITE_PANOSE_MIDLINE.LOW_SERIFED;
pub const DWRITE_PANOSE_XHEIGHT = enum(i32) {
ANY = 0,
NO_FIT = 1,
CONSTANT_SMALL = 2,
CONSTANT_STANDARD = 3,
CONSTANT_LARGE = 4,
DUCKING_SMALL = 5,
DUCKING_STANDARD = 6,
DUCKING_LARGE = 7,
// CONSTANT_STD = 3, this enum value conflicts with CONSTANT_STANDARD
// DUCKING_STD = 6, this enum value conflicts with DUCKING_STANDARD
};
pub const DWRITE_PANOSE_XHEIGHT_ANY = DWRITE_PANOSE_XHEIGHT.ANY;
pub const DWRITE_PANOSE_XHEIGHT_NO_FIT = DWRITE_PANOSE_XHEIGHT.NO_FIT;
pub const DWRITE_PANOSE_XHEIGHT_CONSTANT_SMALL = DWRITE_PANOSE_XHEIGHT.CONSTANT_SMALL;
pub const DWRITE_PANOSE_XHEIGHT_CONSTANT_STANDARD = DWRITE_PANOSE_XHEIGHT.CONSTANT_STANDARD;
pub const DWRITE_PANOSE_XHEIGHT_CONSTANT_LARGE = DWRITE_PANOSE_XHEIGHT.CONSTANT_LARGE;
pub const DWRITE_PANOSE_XHEIGHT_DUCKING_SMALL = DWRITE_PANOSE_XHEIGHT.DUCKING_SMALL;
pub const DWRITE_PANOSE_XHEIGHT_DUCKING_STANDARD = DWRITE_PANOSE_XHEIGHT.DUCKING_STANDARD;
pub const DWRITE_PANOSE_XHEIGHT_DUCKING_LARGE = DWRITE_PANOSE_XHEIGHT.DUCKING_LARGE;
pub const DWRITE_PANOSE_XHEIGHT_CONSTANT_STD = DWRITE_PANOSE_XHEIGHT.CONSTANT_STANDARD;
pub const DWRITE_PANOSE_XHEIGHT_DUCKING_STD = DWRITE_PANOSE_XHEIGHT.DUCKING_STANDARD;
pub const DWRITE_PANOSE_TOOL_KIND = enum(i32) {
ANY = 0,
NO_FIT = 1,
FLAT_NIB = 2,
PRESSURE_POINT = 3,
ENGRAVED = 4,
BALL = 5,
BRUSH = 6,
ROUGH = 7,
FELT_PEN_BRUSH_TIP = 8,
WILD_BRUSH = 9,
};
pub const DWRITE_PANOSE_TOOL_KIND_ANY = DWRITE_PANOSE_TOOL_KIND.ANY;
pub const DWRITE_PANOSE_TOOL_KIND_NO_FIT = DWRITE_PANOSE_TOOL_KIND.NO_FIT;
pub const DWRITE_PANOSE_TOOL_KIND_FLAT_NIB = DWRITE_PANOSE_TOOL_KIND.FLAT_NIB;
pub const DWRITE_PANOSE_TOOL_KIND_PRESSURE_POINT = DWRITE_PANOSE_TOOL_KIND.PRESSURE_POINT;
pub const DWRITE_PANOSE_TOOL_KIND_ENGRAVED = DWRITE_PANOSE_TOOL_KIND.ENGRAVED;
pub const DWRITE_PANOSE_TOOL_KIND_BALL = DWRITE_PANOSE_TOOL_KIND.BALL;
pub const DWRITE_PANOSE_TOOL_KIND_BRUSH = DWRITE_PANOSE_TOOL_KIND.BRUSH;
pub const DWRITE_PANOSE_TOOL_KIND_ROUGH = DWRITE_PANOSE_TOOL_KIND.ROUGH;
pub const DWRITE_PANOSE_TOOL_KIND_FELT_PEN_BRUSH_TIP = DWRITE_PANOSE_TOOL_KIND.FELT_PEN_BRUSH_TIP;
pub const DWRITE_PANOSE_TOOL_KIND_WILD_BRUSH = DWRITE_PANOSE_TOOL_KIND.WILD_BRUSH;
pub const DWRITE_PANOSE_SPACING = enum(i32) {
ANY = 0,
NO_FIT = 1,
PROPORTIONAL_SPACED = 2,
MONOSPACED = 3,
};
pub const DWRITE_PANOSE_SPACING_ANY = DWRITE_PANOSE_SPACING.ANY;
pub const DWRITE_PANOSE_SPACING_NO_FIT = DWRITE_PANOSE_SPACING.NO_FIT;
pub const DWRITE_PANOSE_SPACING_PROPORTIONAL_SPACED = DWRITE_PANOSE_SPACING.PROPORTIONAL_SPACED;
pub const DWRITE_PANOSE_SPACING_MONOSPACED = DWRITE_PANOSE_SPACING.MONOSPACED;
pub const DWRITE_PANOSE_ASPECT_RATIO = enum(i32) {
ANY = 0,
NO_FIT = 1,
VERY_CONDENSED = 2,
CONDENSED = 3,
NORMAL = 4,
EXPANDED = 5,
VERY_EXPANDED = 6,
};
pub const DWRITE_PANOSE_ASPECT_RATIO_ANY = DWRITE_PANOSE_ASPECT_RATIO.ANY;
pub const DWRITE_PANOSE_ASPECT_RATIO_NO_FIT = DWRITE_PANOSE_ASPECT_RATIO.NO_FIT;
pub const DWRITE_PANOSE_ASPECT_RATIO_VERY_CONDENSED = DWRITE_PANOSE_ASPECT_RATIO.VERY_CONDENSED;
pub const DWRITE_PANOSE_ASPECT_RATIO_CONDENSED = DWRITE_PANOSE_ASPECT_RATIO.CONDENSED;
pub const DWRITE_PANOSE_ASPECT_RATIO_NORMAL = DWRITE_PANOSE_ASPECT_RATIO.NORMAL;
pub const DWRITE_PANOSE_ASPECT_RATIO_EXPANDED = DWRITE_PANOSE_ASPECT_RATIO.EXPANDED;
pub const DWRITE_PANOSE_ASPECT_RATIO_VERY_EXPANDED = DWRITE_PANOSE_ASPECT_RATIO.VERY_EXPANDED;
pub const DWRITE_PANOSE_SCRIPT_TOPOLOGY = enum(i32) {
ANY = 0,
NO_FIT = 1,
ROMAN_DISCONNECTED = 2,
ROMAN_TRAILING = 3,
ROMAN_CONNECTED = 4,
CURSIVE_DISCONNECTED = 5,
CURSIVE_TRAILING = 6,
CURSIVE_CONNECTED = 7,
BLACKLETTER_DISCONNECTED = 8,
BLACKLETTER_TRAILING = 9,
BLACKLETTER_CONNECTED = 10,
};
pub const DWRITE_PANOSE_SCRIPT_TOPOLOGY_ANY = DWRITE_PANOSE_SCRIPT_TOPOLOGY.ANY;
pub const DWRITE_PANOSE_SCRIPT_TOPOLOGY_NO_FIT = DWRITE_PANOSE_SCRIPT_TOPOLOGY.NO_FIT;
pub const DWRITE_PANOSE_SCRIPT_TOPOLOGY_ROMAN_DISCONNECTED = DWRITE_PANOSE_SCRIPT_TOPOLOGY.ROMAN_DISCONNECTED;
pub const DWRITE_PANOSE_SCRIPT_TOPOLOGY_ROMAN_TRAILING = DWRITE_PANOSE_SCRIPT_TOPOLOGY.ROMAN_TRAILING;
pub const DWRITE_PANOSE_SCRIPT_TOPOLOGY_ROMAN_CONNECTED = DWRITE_PANOSE_SCRIPT_TOPOLOGY.ROMAN_CONNECTED;
pub const DWRITE_PANOSE_SCRIPT_TOPOLOGY_CURSIVE_DISCONNECTED = DWRITE_PANOSE_SCRIPT_TOPOLOGY.CURSIVE_DISCONNECTED;
pub const DWRITE_PANOSE_SCRIPT_TOPOLOGY_CURSIVE_TRAILING = DWRITE_PANOSE_SCRIPT_TOPOLOGY.CURSIVE_TRAILING;
pub const DWRITE_PANOSE_SCRIPT_TOPOLOGY_CURSIVE_CONNECTED = DWRITE_PANOSE_SCRIPT_TOPOLOGY.CURSIVE_CONNECTED;
pub const DWRITE_PANOSE_SCRIPT_TOPOLOGY_BLACKLETTER_DISCONNECTED = DWRITE_PANOSE_SCRIPT_TOPOLOGY.BLACKLETTER_DISCONNECTED;
pub const DWRITE_PANOSE_SCRIPT_TOPOLOGY_BLACKLETTER_TRAILING = DWRITE_PANOSE_SCRIPT_TOPOLOGY.BLACKLETTER_TRAILING;
pub const DWRITE_PANOSE_SCRIPT_TOPOLOGY_BLACKLETTER_CONNECTED = DWRITE_PANOSE_SCRIPT_TOPOLOGY.BLACKLETTER_CONNECTED;
pub const DWRITE_PANOSE_SCRIPT_FORM = enum(i32) {
ANY = 0,
NO_FIT = 1,
UPRIGHT_NO_WRAPPING = 2,
UPRIGHT_SOME_WRAPPING = 3,
UPRIGHT_MORE_WRAPPING = 4,
UPRIGHT_EXTREME_WRAPPING = 5,
OBLIQUE_NO_WRAPPING = 6,
OBLIQUE_SOME_WRAPPING = 7,
OBLIQUE_MORE_WRAPPING = 8,
OBLIQUE_EXTREME_WRAPPING = 9,
EXAGGERATED_NO_WRAPPING = 10,
EXAGGERATED_SOME_WRAPPING = 11,
EXAGGERATED_MORE_WRAPPING = 12,
EXAGGERATED_EXTREME_WRAPPING = 13,
};
pub const DWRITE_PANOSE_SCRIPT_FORM_ANY = DWRITE_PANOSE_SCRIPT_FORM.ANY;
pub const DWRITE_PANOSE_SCRIPT_FORM_NO_FIT = DWRITE_PANOSE_SCRIPT_FORM.NO_FIT;
pub const DWRITE_PANOSE_SCRIPT_FORM_UPRIGHT_NO_WRAPPING = DWRITE_PANOSE_SCRIPT_FORM.UPRIGHT_NO_WRAPPING;
pub const DWRITE_PANOSE_SCRIPT_FORM_UPRIGHT_SOME_WRAPPING = DWRITE_PANOSE_SCRIPT_FORM.UPRIGHT_SOME_WRAPPING;
pub const DWRITE_PANOSE_SCRIPT_FORM_UPRIGHT_MORE_WRAPPING = DWRITE_PANOSE_SCRIPT_FORM.UPRIGHT_MORE_WRAPPING;
pub const DWRITE_PANOSE_SCRIPT_FORM_UPRIGHT_EXTREME_WRAPPING = DWRITE_PANOSE_SCRIPT_FORM.UPRIGHT_EXTREME_WRAPPING;
pub const DWRITE_PANOSE_SCRIPT_FORM_OBLIQUE_NO_WRAPPING = DWRITE_PANOSE_SCRIPT_FORM.OBLIQUE_NO_WRAPPING;
pub const DWRITE_PANOSE_SCRIPT_FORM_OBLIQUE_SOME_WRAPPING = DWRITE_PANOSE_SCRIPT_FORM.OBLIQUE_SOME_WRAPPING;
pub const DWRITE_PANOSE_SCRIPT_FORM_OBLIQUE_MORE_WRAPPING = DWRITE_PANOSE_SCRIPT_FORM.OBLIQUE_MORE_WRAPPING;
pub const DWRITE_PANOSE_SCRIPT_FORM_OBLIQUE_EXTREME_WRAPPING = DWRITE_PANOSE_SCRIPT_FORM.OBLIQUE_EXTREME_WRAPPING;
pub const DWRITE_PANOSE_SCRIPT_FORM_EXAGGERATED_NO_WRAPPING = DWRITE_PANOSE_SCRIPT_FORM.EXAGGERATED_NO_WRAPPING;
pub const DWRITE_PANOSE_SCRIPT_FORM_EXAGGERATED_SOME_WRAPPING = DWRITE_PANOSE_SCRIPT_FORM.EXAGGERATED_SOME_WRAPPING;
pub const DWRITE_PANOSE_SCRIPT_FORM_EXAGGERATED_MORE_WRAPPING = DWRITE_PANOSE_SCRIPT_FORM.EXAGGERATED_MORE_WRAPPING;
pub const DWRITE_PANOSE_SCRIPT_FORM_EXAGGERATED_EXTREME_WRAPPING = DWRITE_PANOSE_SCRIPT_FORM.EXAGGERATED_EXTREME_WRAPPING;
pub const DWRITE_PANOSE_FINIALS = enum(i32) {
ANY = 0,
NO_FIT = 1,
NONE_NO_LOOPS = 2,
NONE_CLOSED_LOOPS = 3,
NONE_OPEN_LOOPS = 4,
SHARP_NO_LOOPS = 5,
SHARP_CLOSED_LOOPS = 6,
SHARP_OPEN_LOOPS = 7,
TAPERED_NO_LOOPS = 8,
TAPERED_CLOSED_LOOPS = 9,
TAPERED_OPEN_LOOPS = 10,
ROUND_NO_LOOPS = 11,
ROUND_CLOSED_LOOPS = 12,
ROUND_OPEN_LOOPS = 13,
};
pub const DWRITE_PANOSE_FINIALS_ANY = DWRITE_PANOSE_FINIALS.ANY;
pub const DWRITE_PANOSE_FINIALS_NO_FIT = DWRITE_PANOSE_FINIALS.NO_FIT;
pub const DWRITE_PANOSE_FINIALS_NONE_NO_LOOPS = DWRITE_PANOSE_FINIALS.NONE_NO_LOOPS;
pub const DWRITE_PANOSE_FINIALS_NONE_CLOSED_LOOPS = DWRITE_PANOSE_FINIALS.NONE_CLOSED_LOOPS;
pub const DWRITE_PANOSE_FINIALS_NONE_OPEN_LOOPS = DWRITE_PANOSE_FINIALS.NONE_OPEN_LOOPS;
pub const DWRITE_PANOSE_FINIALS_SHARP_NO_LOOPS = DWRITE_PANOSE_FINIALS.SHARP_NO_LOOPS;
pub const DWRITE_PANOSE_FINIALS_SHARP_CLOSED_LOOPS = DWRITE_PANOSE_FINIALS.SHARP_CLOSED_LOOPS;
pub const DWRITE_PANOSE_FINIALS_SHARP_OPEN_LOOPS = DWRITE_PANOSE_FINIALS.SHARP_OPEN_LOOPS;
pub const DWRITE_PANOSE_FINIALS_TAPERED_NO_LOOPS = DWRITE_PANOSE_FINIALS.TAPERED_NO_LOOPS;
pub const DWRITE_PANOSE_FINIALS_TAPERED_CLOSED_LOOPS = DWRITE_PANOSE_FINIALS.TAPERED_CLOSED_LOOPS;
pub const DWRITE_PANOSE_FINIALS_TAPERED_OPEN_LOOPS = DWRITE_PANOSE_FINIALS.TAPERED_OPEN_LOOPS;
pub const DWRITE_PANOSE_FINIALS_ROUND_NO_LOOPS = DWRITE_PANOSE_FINIALS.ROUND_NO_LOOPS;
pub const DWRITE_PANOSE_FINIALS_ROUND_CLOSED_LOOPS = DWRITE_PANOSE_FINIALS.ROUND_CLOSED_LOOPS;
pub const DWRITE_PANOSE_FINIALS_ROUND_OPEN_LOOPS = DWRITE_PANOSE_FINIALS.ROUND_OPEN_LOOPS;
pub const DWRITE_PANOSE_XASCENT = enum(i32) {
ANY = 0,
NO_FIT = 1,
VERY_LOW = 2,
LOW = 3,
MEDIUM = 4,
HIGH = 5,
VERY_HIGH = 6,
};
pub const DWRITE_PANOSE_XASCENT_ANY = DWRITE_PANOSE_XASCENT.ANY;
pub const DWRITE_PANOSE_XASCENT_NO_FIT = DWRITE_PANOSE_XASCENT.NO_FIT;
pub const DWRITE_PANOSE_XASCENT_VERY_LOW = DWRITE_PANOSE_XASCENT.VERY_LOW;
pub const DWRITE_PANOSE_XASCENT_LOW = DWRITE_PANOSE_XASCENT.LOW;
pub const DWRITE_PANOSE_XASCENT_MEDIUM = DWRITE_PANOSE_XASCENT.MEDIUM;
pub const DWRITE_PANOSE_XASCENT_HIGH = DWRITE_PANOSE_XASCENT.HIGH;
pub const DWRITE_PANOSE_XASCENT_VERY_HIGH = DWRITE_PANOSE_XASCENT.VERY_HIGH;
pub const DWRITE_PANOSE_DECORATIVE_CLASS = enum(i32) {
ANY = 0,
NO_FIT = 1,
DERIVATIVE = 2,
NONSTANDARD_TOPOLOGY = 3,
NONSTANDARD_ELEMENTS = 4,
NONSTANDARD_ASPECT = 5,
INITIALS = 6,
CARTOON = 7,
PICTURE_STEMS = 8,
ORNAMENTED = 9,
TEXT_AND_BACKGROUND = 10,
COLLAGE = 11,
MONTAGE = 12,
};
pub const DWRITE_PANOSE_DECORATIVE_CLASS_ANY = DWRITE_PANOSE_DECORATIVE_CLASS.ANY;
pub const DWRITE_PANOSE_DECORATIVE_CLASS_NO_FIT = DWRITE_PANOSE_DECORATIVE_CLASS.NO_FIT;
pub const DWRITE_PANOSE_DECORATIVE_CLASS_DERIVATIVE = DWRITE_PANOSE_DECORATIVE_CLASS.DERIVATIVE;
pub const DWRITE_PANOSE_DECORATIVE_CLASS_NONSTANDARD_TOPOLOGY = DWRITE_PANOSE_DECORATIVE_CLASS.NONSTANDARD_TOPOLOGY;
pub const DWRITE_PANOSE_DECORATIVE_CLASS_NONSTANDARD_ELEMENTS = DWRITE_PANOSE_DECORATIVE_CLASS.NONSTANDARD_ELEMENTS;
pub const DWRITE_PANOSE_DECORATIVE_CLASS_NONSTANDARD_ASPECT = DWRITE_PANOSE_DECORATIVE_CLASS.NONSTANDARD_ASPECT;
pub const DWRITE_PANOSE_DECORATIVE_CLASS_INITIALS = DWRITE_PANOSE_DECORATIVE_CLASS.INITIALS;
pub const DWRITE_PANOSE_DECORATIVE_CLASS_CARTOON = DWRITE_PANOSE_DECORATIVE_CLASS.CARTOON;
pub const DWRITE_PANOSE_DECORATIVE_CLASS_PICTURE_STEMS = DWRITE_PANOSE_DECORATIVE_CLASS.PICTURE_STEMS;
pub const DWRITE_PANOSE_DECORATIVE_CLASS_ORNAMENTED = DWRITE_PANOSE_DECORATIVE_CLASS.ORNAMENTED;
pub const DWRITE_PANOSE_DECORATIVE_CLASS_TEXT_AND_BACKGROUND = DWRITE_PANOSE_DECORATIVE_CLASS.TEXT_AND_BACKGROUND;
pub const DWRITE_PANOSE_DECORATIVE_CLASS_COLLAGE = DWRITE_PANOSE_DECORATIVE_CLASS.COLLAGE;
pub const DWRITE_PANOSE_DECORATIVE_CLASS_MONTAGE = DWRITE_PANOSE_DECORATIVE_CLASS.MONTAGE;
pub const DWRITE_PANOSE_ASPECT = enum(i32) {
ANY = 0,
NO_FIT = 1,
SUPER_CONDENSED = 2,
VERY_CONDENSED = 3,
CONDENSED = 4,
NORMAL = 5,
EXTENDED = 6,
VERY_EXTENDED = 7,
SUPER_EXTENDED = 8,
MONOSPACED = 9,
};
pub const DWRITE_PANOSE_ASPECT_ANY = DWRITE_PANOSE_ASPECT.ANY;
pub const DWRITE_PANOSE_ASPECT_NO_FIT = DWRITE_PANOSE_ASPECT.NO_FIT;
pub const DWRITE_PANOSE_ASPECT_SUPER_CONDENSED = DWRITE_PANOSE_ASPECT.SUPER_CONDENSED;
pub const DWRITE_PANOSE_ASPECT_VERY_CONDENSED = DWRITE_PANOSE_ASPECT.VERY_CONDENSED;
pub const DWRITE_PANOSE_ASPECT_CONDENSED = DWRITE_PANOSE_ASPECT.CONDENSED;
pub const DWRITE_PANOSE_ASPECT_NORMAL = DWRITE_PANOSE_ASPECT.NORMAL;
pub const DWRITE_PANOSE_ASPECT_EXTENDED = DWRITE_PANOSE_ASPECT.EXTENDED;
pub const DWRITE_PANOSE_ASPECT_VERY_EXTENDED = DWRITE_PANOSE_ASPECT.VERY_EXTENDED;
pub const DWRITE_PANOSE_ASPECT_SUPER_EXTENDED = DWRITE_PANOSE_ASPECT.SUPER_EXTENDED;
pub const DWRITE_PANOSE_ASPECT_MONOSPACED = DWRITE_PANOSE_ASPECT.MONOSPACED;
pub const DWRITE_PANOSE_FILL = enum(i32) {
ANY = 0,
NO_FIT = 1,
STANDARD_SOLID_FILL = 2,
NO_FILL = 3,
PATTERNED_FILL = 4,
COMPLEX_FILL = 5,
SHAPED_FILL = 6,
DRAWN_DISTRESSED = 7,
};
pub const DWRITE_PANOSE_FILL_ANY = DWRITE_PANOSE_FILL.ANY;
pub const DWRITE_PANOSE_FILL_NO_FIT = DWRITE_PANOSE_FILL.NO_FIT;
pub const DWRITE_PANOSE_FILL_STANDARD_SOLID_FILL = DWRITE_PANOSE_FILL.STANDARD_SOLID_FILL;
pub const DWRITE_PANOSE_FILL_NO_FILL = DWRITE_PANOSE_FILL.NO_FILL;
pub const DWRITE_PANOSE_FILL_PATTERNED_FILL = DWRITE_PANOSE_FILL.PATTERNED_FILL;
pub const DWRITE_PANOSE_FILL_COMPLEX_FILL = DWRITE_PANOSE_FILL.COMPLEX_FILL;
pub const DWRITE_PANOSE_FILL_SHAPED_FILL = DWRITE_PANOSE_FILL.SHAPED_FILL;
pub const DWRITE_PANOSE_FILL_DRAWN_DISTRESSED = DWRITE_PANOSE_FILL.DRAWN_DISTRESSED;
pub const DWRITE_PANOSE_LINING = enum(i32) {
ANY = 0,
NO_FIT = 1,
NONE = 2,
INLINE = 3,
OUTLINE = 4,
ENGRAVED = 5,
SHADOW = 6,
RELIEF = 7,
BACKDROP = 8,
};
pub const DWRITE_PANOSE_LINING_ANY = DWRITE_PANOSE_LINING.ANY;
pub const DWRITE_PANOSE_LINING_NO_FIT = DWRITE_PANOSE_LINING.NO_FIT;
pub const DWRITE_PANOSE_LINING_NONE = DWRITE_PANOSE_LINING.NONE;
pub const DWRITE_PANOSE_LINING_INLINE = DWRITE_PANOSE_LINING.INLINE;
pub const DWRITE_PANOSE_LINING_OUTLINE = DWRITE_PANOSE_LINING.OUTLINE;
pub const DWRITE_PANOSE_LINING_ENGRAVED = DWRITE_PANOSE_LINING.ENGRAVED;
pub const DWRITE_PANOSE_LINING_SHADOW = DWRITE_PANOSE_LINING.SHADOW;
pub const DWRITE_PANOSE_LINING_RELIEF = DWRITE_PANOSE_LINING.RELIEF;
pub const DWRITE_PANOSE_LINING_BACKDROP = DWRITE_PANOSE_LINING.BACKDROP;
pub const DWRITE_PANOSE_DECORATIVE_TOPOLOGY = enum(i32) {
ANY = 0,
NO_FIT = 1,
STANDARD = 2,
SQUARE = 3,
MULTIPLE_SEGMENT = 4,
ART_DECO = 5,
UNEVEN_WEIGHTING = 6,
DIVERSE_ARMS = 7,
DIVERSE_FORMS = 8,
LOMBARDIC_FORMS = 9,
UPPER_CASE_IN_LOWER_CASE = 10,
IMPLIED_TOPOLOGY = 11,
HORSESHOE_E_AND_A = 12,
CURSIVE = 13,
BLACKLETTER = 14,
SWASH_VARIANCE = 15,
};
pub const DWRITE_PANOSE_DECORATIVE_TOPOLOGY_ANY = DWRITE_PANOSE_DECORATIVE_TOPOLOGY.ANY;
pub const DWRITE_PANOSE_DECORATIVE_TOPOLOGY_NO_FIT = DWRITE_PANOSE_DECORATIVE_TOPOLOGY.NO_FIT;
pub const DWRITE_PANOSE_DECORATIVE_TOPOLOGY_STANDARD = DWRITE_PANOSE_DECORATIVE_TOPOLOGY.STANDARD;
pub const DWRITE_PANOSE_DECORATIVE_TOPOLOGY_SQUARE = DWRITE_PANOSE_DECORATIVE_TOPOLOGY.SQUARE;
pub const DWRITE_PANOSE_DECORATIVE_TOPOLOGY_MULTIPLE_SEGMENT = DWRITE_PANOSE_DECORATIVE_TOPOLOGY.MULTIPLE_SEGMENT;
pub const DWRITE_PANOSE_DECORATIVE_TOPOLOGY_ART_DECO = DWRITE_PANOSE_DECORATIVE_TOPOLOGY.ART_DECO;
pub const DWRITE_PANOSE_DECORATIVE_TOPOLOGY_UNEVEN_WEIGHTING = DWRITE_PANOSE_DECORATIVE_TOPOLOGY.UNEVEN_WEIGHTING;
pub const DWRITE_PANOSE_DECORATIVE_TOPOLOGY_DIVERSE_ARMS = DWRITE_PANOSE_DECORATIVE_TOPOLOGY.DIVERSE_ARMS;
pub const DWRITE_PANOSE_DECORATIVE_TOPOLOGY_DIVERSE_FORMS = DWRITE_PANOSE_DECORATIVE_TOPOLOGY.DIVERSE_FORMS;
pub const DWRITE_PANOSE_DECORATIVE_TOPOLOGY_LOMBARDIC_FORMS = DWRITE_PANOSE_DECORATIVE_TOPOLOGY.LOMBARDIC_FORMS;
pub const DWRITE_PANOSE_DECORATIVE_TOPOLOGY_UPPER_CASE_IN_LOWER_CASE = DWRITE_PANOSE_DECORATIVE_TOPOLOGY.UPPER_CASE_IN_LOWER_CASE;
pub const DWRITE_PANOSE_DECORATIVE_TOPOLOGY_IMPLIED_TOPOLOGY = DWRITE_PANOSE_DECORATIVE_TOPOLOGY.IMPLIED_TOPOLOGY;
pub const DWRITE_PANOSE_DECORATIVE_TOPOLOGY_HORSESHOE_E_AND_A = DWRITE_PANOSE_DECORATIVE_TOPOLOGY.HORSESHOE_E_AND_A;
pub const DWRITE_PANOSE_DECORATIVE_TOPOLOGY_CURSIVE = DWRITE_PANOSE_DECORATIVE_TOPOLOGY.CURSIVE;
pub const DWRITE_PANOSE_DECORATIVE_TOPOLOGY_BLACKLETTER = DWRITE_PANOSE_DECORATIVE_TOPOLOGY.BLACKLETTER;
pub const DWRITE_PANOSE_DECORATIVE_TOPOLOGY_SWASH_VARIANCE = DWRITE_PANOSE_DECORATIVE_TOPOLOGY.SWASH_VARIANCE;
pub const DWRITE_PANOSE_CHARACTER_RANGES = enum(i32) {
ANY = 0,
NO_FIT = 1,
EXTENDED_COLLECTION = 2,
LITERALS = 3,
NO_LOWER_CASE = 4,
SMALL_CAPS = 5,
};
pub const DWRITE_PANOSE_CHARACTER_RANGES_ANY = DWRITE_PANOSE_CHARACTER_RANGES.ANY;
pub const DWRITE_PANOSE_CHARACTER_RANGES_NO_FIT = DWRITE_PANOSE_CHARACTER_RANGES.NO_FIT;
pub const DWRITE_PANOSE_CHARACTER_RANGES_EXTENDED_COLLECTION = DWRITE_PANOSE_CHARACTER_RANGES.EXTENDED_COLLECTION;
pub const DWRITE_PANOSE_CHARACTER_RANGES_LITERALS = DWRITE_PANOSE_CHARACTER_RANGES.LITERALS;
pub const DWRITE_PANOSE_CHARACTER_RANGES_NO_LOWER_CASE = DWRITE_PANOSE_CHARACTER_RANGES.NO_LOWER_CASE;
pub const DWRITE_PANOSE_CHARACTER_RANGES_SMALL_CAPS = DWRITE_PANOSE_CHARACTER_RANGES.SMALL_CAPS;
pub const DWRITE_PANOSE_SYMBOL_KIND = enum(i32) {
ANY = 0,
NO_FIT = 1,
MONTAGES = 2,
PICTURES = 3,
SHAPES = 4,
SCIENTIFIC = 5,
MUSIC = 6,
EXPERT = 7,
PATTERNS = 8,
BOARDERS = 9,
ICONS = 10,
LOGOS = 11,
INDUSTRY_SPECIFIC = 12,
};
pub const DWRITE_PANOSE_SYMBOL_KIND_ANY = DWRITE_PANOSE_SYMBOL_KIND.ANY;
pub const DWRITE_PANOSE_SYMBOL_KIND_NO_FIT = DWRITE_PANOSE_SYMBOL_KIND.NO_FIT;
pub const DWRITE_PANOSE_SYMBOL_KIND_MONTAGES = DWRITE_PANOSE_SYMBOL_KIND.MONTAGES;
pub const DWRITE_PANOSE_SYMBOL_KIND_PICTURES = DWRITE_PANOSE_SYMBOL_KIND.PICTURES;
pub const DWRITE_PANOSE_SYMBOL_KIND_SHAPES = DWRITE_PANOSE_SYMBOL_KIND.SHAPES;
pub const DWRITE_PANOSE_SYMBOL_KIND_SCIENTIFIC = DWRITE_PANOSE_SYMBOL_KIND.SCIENTIFIC;
pub const DWRITE_PANOSE_SYMBOL_KIND_MUSIC = DWRITE_PANOSE_SYMBOL_KIND.MUSIC;
pub const DWRITE_PANOSE_SYMBOL_KIND_EXPERT = DWRITE_PANOSE_SYMBOL_KIND.EXPERT;
pub const DWRITE_PANOSE_SYMBOL_KIND_PATTERNS = DWRITE_PANOSE_SYMBOL_KIND.PATTERNS;
pub const DWRITE_PANOSE_SYMBOL_KIND_BOARDERS = DWRITE_PANOSE_SYMBOL_KIND.BOARDERS;
pub const DWRITE_PANOSE_SYMBOL_KIND_ICONS = DWRITE_PANOSE_SYMBOL_KIND.ICONS;
pub const DWRITE_PANOSE_SYMBOL_KIND_LOGOS = DWRITE_PANOSE_SYMBOL_KIND.LOGOS;
pub const DWRITE_PANOSE_SYMBOL_KIND_INDUSTRY_SPECIFIC = DWRITE_PANOSE_SYMBOL_KIND.INDUSTRY_SPECIFIC;
pub const DWRITE_PANOSE_SYMBOL_ASPECT_RATIO = enum(i32) {
ANY = 0,
NO_FIT = 1,
NO_WIDTH = 2,
EXCEPTIONALLY_WIDE = 3,
SUPER_WIDE = 4,
VERY_WIDE = 5,
WIDE = 6,
NORMAL = 7,
NARROW = 8,
VERY_NARROW = 9,
};
pub const DWRITE_PANOSE_SYMBOL_ASPECT_RATIO_ANY = DWRITE_PANOSE_SYMBOL_ASPECT_RATIO.ANY;
pub const DWRITE_PANOSE_SYMBOL_ASPECT_RATIO_NO_FIT = DWRITE_PANOSE_SYMBOL_ASPECT_RATIO.NO_FIT;
pub const DWRITE_PANOSE_SYMBOL_ASPECT_RATIO_NO_WIDTH = DWRITE_PANOSE_SYMBOL_ASPECT_RATIO.NO_WIDTH;
pub const DWRITE_PANOSE_SYMBOL_ASPECT_RATIO_EXCEPTIONALLY_WIDE = DWRITE_PANOSE_SYMBOL_ASPECT_RATIO.EXCEPTIONALLY_WIDE;
pub const DWRITE_PANOSE_SYMBOL_ASPECT_RATIO_SUPER_WIDE = DWRITE_PANOSE_SYMBOL_ASPECT_RATIO.SUPER_WIDE;
pub const DWRITE_PANOSE_SYMBOL_ASPECT_RATIO_VERY_WIDE = DWRITE_PANOSE_SYMBOL_ASPECT_RATIO.VERY_WIDE;
pub const DWRITE_PANOSE_SYMBOL_ASPECT_RATIO_WIDE = DWRITE_PANOSE_SYMBOL_ASPECT_RATIO.WIDE;
pub const DWRITE_PANOSE_SYMBOL_ASPECT_RATIO_NORMAL = DWRITE_PANOSE_SYMBOL_ASPECT_RATIO.NORMAL;
pub const DWRITE_PANOSE_SYMBOL_ASPECT_RATIO_NARROW = DWRITE_PANOSE_SYMBOL_ASPECT_RATIO.NARROW;
pub const DWRITE_PANOSE_SYMBOL_ASPECT_RATIO_VERY_NARROW = DWRITE_PANOSE_SYMBOL_ASPECT_RATIO.VERY_NARROW;
pub const DWRITE_OUTLINE_THRESHOLD = enum(i32) {
NTIALIASED = 0,
LIASED = 1,
};
pub const DWRITE_OUTLINE_THRESHOLD_ANTIALIASED = DWRITE_OUTLINE_THRESHOLD.NTIALIASED;
pub const DWRITE_OUTLINE_THRESHOLD_ALIASED = DWRITE_OUTLINE_THRESHOLD.LIASED;
pub const DWRITE_BASELINE = enum(i32) {
DEFAULT = 0,
ROMAN = 1,
CENTRAL = 2,
MATH = 3,
HANGING = 4,
IDEOGRAPHIC_BOTTOM = 5,
IDEOGRAPHIC_TOP = 6,
MINIMUM = 7,
MAXIMUM = 8,
};
pub const DWRITE_BASELINE_DEFAULT = DWRITE_BASELINE.DEFAULT;
pub const DWRITE_BASELINE_ROMAN = DWRITE_BASELINE.ROMAN;
pub const DWRITE_BASELINE_CENTRAL = DWRITE_BASELINE.CENTRAL;
pub const DWRITE_BASELINE_MATH = DWRITE_BASELINE.MATH;
pub const DWRITE_BASELINE_HANGING = DWRITE_BASELINE.HANGING;
pub const DWRITE_BASELINE_IDEOGRAPHIC_BOTTOM = DWRITE_BASELINE.IDEOGRAPHIC_BOTTOM;
pub const DWRITE_BASELINE_IDEOGRAPHIC_TOP = DWRITE_BASELINE.IDEOGRAPHIC_TOP;
pub const DWRITE_BASELINE_MINIMUM = DWRITE_BASELINE.MINIMUM;
pub const DWRITE_BASELINE_MAXIMUM = DWRITE_BASELINE.MAXIMUM;
pub const DWRITE_VERTICAL_GLYPH_ORIENTATION = enum(i32) {
DEFAULT = 0,
STACKED = 1,
};
pub const DWRITE_VERTICAL_GLYPH_ORIENTATION_DEFAULT = DWRITE_VERTICAL_GLYPH_ORIENTATION.DEFAULT;
pub const DWRITE_VERTICAL_GLYPH_ORIENTATION_STACKED = DWRITE_VERTICAL_GLYPH_ORIENTATION.STACKED;
pub const DWRITE_GLYPH_ORIENTATION_ANGLE = enum(i32) {
@"0_DEGREES" = 0,
@"90_DEGREES" = 1,
@"180_DEGREES" = 2,
@"270_DEGREES" = 3,
};
pub const DWRITE_GLYPH_ORIENTATION_ANGLE_0_DEGREES = DWRITE_GLYPH_ORIENTATION_ANGLE.@"0_DEGREES";
pub const DWRITE_GLYPH_ORIENTATION_ANGLE_90_DEGREES = DWRITE_GLYPH_ORIENTATION_ANGLE.@"90_DEGREES";
pub const DWRITE_GLYPH_ORIENTATION_ANGLE_180_DEGREES = DWRITE_GLYPH_ORIENTATION_ANGLE.@"180_DEGREES";
pub const DWRITE_GLYPH_ORIENTATION_ANGLE_270_DEGREES = DWRITE_GLYPH_ORIENTATION_ANGLE.@"270_DEGREES";
pub const DWRITE_FONT_METRICS1 = extern struct {
__AnonymousBase_DWrite_1_L627_C38: DWRITE_FONT_METRICS,
glyphBoxLeft: i16,
glyphBoxTop: i16,
glyphBoxRight: i16,
glyphBoxBottom: i16,
subscriptPositionX: i16,
subscriptPositionY: i16,
subscriptSizeX: i16,
subscriptSizeY: i16,
superscriptPositionX: i16,
superscriptPositionY: i16,
superscriptSizeX: i16,
superscriptSizeY: i16,
hasTypographicMetrics: BOOL,
};
pub const DWRITE_CARET_METRICS = extern struct {
slopeRise: i16,
slopeRun: i16,
offset: i16,
};
pub const DWRITE_PANOSE = extern union {
values: [10]u8,
familyKind: u8,
text: extern struct {
familyKind: u8,
serifStyle: u8,
weight: u8,
proportion: u8,
contrast: u8,
strokeVariation: u8,
armStyle: u8,
letterform: u8,
midline: u8,
xHeight: u8,
},
script: extern struct {
familyKind: u8,
toolKind: u8,
weight: u8,
spacing: u8,
aspectRatio: u8,
contrast: u8,
scriptTopology: u8,
scriptForm: u8,
finials: u8,
xAscent: u8,
},
decorative: extern struct {
familyKind: u8,
decorativeClass: u8,
weight: u8,
aspect: u8,
contrast: u8,
serifVariant: u8,
fill: u8,
lining: u8,
decorativeTopology: u8,
characterRange: u8,
},
symbol: extern struct {
familyKind: u8,
symbolKind: u8,
weight: u8,
spacing: u8,
aspectRatioAndContrast: u8,
aspectRatio94: u8,
aspectRatio119: u8,
aspectRatio157: u8,
aspectRatio163: u8,
aspectRatio211: u8,
},
};
pub const DWRITE_UNICODE_RANGE = extern struct {
first: u32,
last: u32,
};
pub const DWRITE_SCRIPT_PROPERTIES = extern struct {
isoScriptCode: u32,
isoScriptNumber: u32,
clusterLookahead: u32,
justificationCharacter: u32,
_bitfield: u32,
};
pub const DWRITE_JUSTIFICATION_OPPORTUNITY = extern struct {
expansionMinimum: f32,
expansionMaximum: f32,
compressionMaximum: f32,
_bitfield: u32,
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IDWriteFactory1_Value = Guid.initString("30572f99-dac6-41db-a16e-0486307e606a");
pub const IID_IDWriteFactory1 = &IID_IDWriteFactory1_Value;
pub const IDWriteFactory1 = extern struct {
pub const VTable = extern struct {
base: IDWriteFactory.VTable,
GetEudcFontCollection: fn(
self: *const IDWriteFactory1,
fontCollection: ?*?*IDWriteFontCollection,
checkForUpdates: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateCustomRenderingParams: fn(
self: *const IDWriteFactory1,
gamma: f32,
enhancedContrast: f32,
enhancedContrastGrayscale: f32,
clearTypeLevel: f32,
pixelGeometry: DWRITE_PIXEL_GEOMETRY,
renderingMode: DWRITE_RENDERING_MODE,
renderingParams: ?*?*IDWriteRenderingParams1,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFactory.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory1_GetEudcFontCollection(self: *const T, fontCollection: ?*?*IDWriteFontCollection, checkForUpdates: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory1.VTable, self.vtable).GetEudcFontCollection(@ptrCast(*const IDWriteFactory1, self), fontCollection, checkForUpdates);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory1_CreateCustomRenderingParams(self: *const T, gamma: f32, enhancedContrast: f32, enhancedContrastGrayscale: f32, clearTypeLevel: f32, pixelGeometry: DWRITE_PIXEL_GEOMETRY, renderingMode: DWRITE_RENDERING_MODE, renderingParams: ?*?*IDWriteRenderingParams1) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory1.VTable, self.vtable).CreateCustomRenderingParams(@ptrCast(*const IDWriteFactory1, self), gamma, enhancedContrast, enhancedContrastGrayscale, clearTypeLevel, pixelGeometry, renderingMode, renderingParams);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IDWriteFontFace1_Value = Guid.initString("a71efdb4-9fdb-4838-ad90-cfc3be8c3daf");
pub const IID_IDWriteFontFace1 = &IID_IDWriteFontFace1_Value;
pub const IDWriteFontFace1 = extern struct {
pub const VTable = extern struct {
base: IDWriteFontFace.VTable,
GetMetrics: fn(
self: *const IDWriteFontFace1,
fontMetrics: ?*DWRITE_FONT_METRICS1,
) callconv(@import("std").os.windows.WINAPI) void,
GetGdiCompatibleMetrics: fn(
self: *const IDWriteFontFace1,
emSize: f32,
pixelsPerDip: f32,
transform: ?*const DWRITE_MATRIX,
fontMetrics: ?*DWRITE_FONT_METRICS1,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCaretMetrics: fn(
self: *const IDWriteFontFace1,
caretMetrics: ?*DWRITE_CARET_METRICS,
) callconv(@import("std").os.windows.WINAPI) void,
GetUnicodeRanges: fn(
self: *const IDWriteFontFace1,
maxRangeCount: u32,
unicodeRanges: ?[*]DWRITE_UNICODE_RANGE,
actualRangeCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsMonospacedFont: fn(
self: *const IDWriteFontFace1,
) callconv(@import("std").os.windows.WINAPI) BOOL,
GetDesignGlyphAdvances: fn(
self: *const IDWriteFontFace1,
glyphCount: u32,
glyphIndices: [*:0]const u16,
glyphAdvances: [*]i32,
isSideways: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetGdiCompatibleGlyphAdvances: fn(
self: *const IDWriteFontFace1,
emSize: f32,
pixelsPerDip: f32,
transform: ?*const DWRITE_MATRIX,
useGdiNatural: BOOL,
isSideways: BOOL,
glyphCount: u32,
glyphIndices: [*:0]const u16,
glyphAdvances: [*]i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetKerningPairAdjustments: fn(
self: *const IDWriteFontFace1,
glyphCount: u32,
glyphIndices: [*:0]const u16,
glyphAdvanceAdjustments: [*]i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
HasKerningPairs: fn(
self: *const IDWriteFontFace1,
) callconv(@import("std").os.windows.WINAPI) BOOL,
GetRecommendedRenderingMode: fn(
self: *const IDWriteFontFace1,
fontEmSize: f32,
dpiX: f32,
dpiY: f32,
transform: ?*const DWRITE_MATRIX,
isSideways: BOOL,
outlineThreshold: DWRITE_OUTLINE_THRESHOLD,
measuringMode: DWRITE_MEASURING_MODE,
renderingMode: ?*DWRITE_RENDERING_MODE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetVerticalGlyphVariants: fn(
self: *const IDWriteFontFace1,
glyphCount: u32,
nominalGlyphIndices: [*:0]const u16,
verticalGlyphIndices: [*:0]u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
HasVerticalGlyphVariants: fn(
self: *const IDWriteFontFace1,
) callconv(@import("std").os.windows.WINAPI) BOOL,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFontFace.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace1_GetMetrics(self: *const T, fontMetrics: ?*DWRITE_FONT_METRICS1) callconv(.Inline) void {
return @ptrCast(*const IDWriteFontFace1.VTable, self.vtable).GetMetrics(@ptrCast(*const IDWriteFontFace1, self), fontMetrics);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace1_GetGdiCompatibleMetrics(self: *const T, emSize: f32, pixelsPerDip: f32, transform: ?*const DWRITE_MATRIX, fontMetrics: ?*DWRITE_FONT_METRICS1) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFace1.VTable, self.vtable).GetGdiCompatibleMetrics(@ptrCast(*const IDWriteFontFace1, self), emSize, pixelsPerDip, transform, fontMetrics);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace1_GetCaretMetrics(self: *const T, caretMetrics: ?*DWRITE_CARET_METRICS) callconv(.Inline) void {
return @ptrCast(*const IDWriteFontFace1.VTable, self.vtable).GetCaretMetrics(@ptrCast(*const IDWriteFontFace1, self), caretMetrics);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace1_GetUnicodeRanges(self: *const T, maxRangeCount: u32, unicodeRanges: ?[*]DWRITE_UNICODE_RANGE, actualRangeCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFace1.VTable, self.vtable).GetUnicodeRanges(@ptrCast(*const IDWriteFontFace1, self), maxRangeCount, unicodeRanges, actualRangeCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace1_IsMonospacedFont(self: *const T) callconv(.Inline) BOOL {
return @ptrCast(*const IDWriteFontFace1.VTable, self.vtable).IsMonospacedFont(@ptrCast(*const IDWriteFontFace1, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace1_GetDesignGlyphAdvances(self: *const T, glyphCount: u32, glyphIndices: [*:0]const u16, glyphAdvances: [*]i32, isSideways: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFace1.VTable, self.vtable).GetDesignGlyphAdvances(@ptrCast(*const IDWriteFontFace1, self), glyphCount, glyphIndices, glyphAdvances, isSideways);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace1_GetGdiCompatibleGlyphAdvances(self: *const T, emSize: f32, pixelsPerDip: f32, transform: ?*const DWRITE_MATRIX, useGdiNatural: BOOL, isSideways: BOOL, glyphCount: u32, glyphIndices: [*:0]const u16, glyphAdvances: [*]i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFace1.VTable, self.vtable).GetGdiCompatibleGlyphAdvances(@ptrCast(*const IDWriteFontFace1, self), emSize, pixelsPerDip, transform, useGdiNatural, isSideways, glyphCount, glyphIndices, glyphAdvances);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace1_GetKerningPairAdjustments(self: *const T, glyphCount: u32, glyphIndices: [*:0]const u16, glyphAdvanceAdjustments: [*]i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFace1.VTable, self.vtable).GetKerningPairAdjustments(@ptrCast(*const IDWriteFontFace1, self), glyphCount, glyphIndices, glyphAdvanceAdjustments);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace1_HasKerningPairs(self: *const T) callconv(.Inline) BOOL {
return @ptrCast(*const IDWriteFontFace1.VTable, self.vtable).HasKerningPairs(@ptrCast(*const IDWriteFontFace1, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace1_GetRecommendedRenderingMode(self: *const T, fontEmSize: f32, dpiX: f32, dpiY: f32, transform: ?*const DWRITE_MATRIX, isSideways: BOOL, outlineThreshold: DWRITE_OUTLINE_THRESHOLD, measuringMode: DWRITE_MEASURING_MODE, renderingMode: ?*DWRITE_RENDERING_MODE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFace1.VTable, self.vtable).GetRecommendedRenderingMode(@ptrCast(*const IDWriteFontFace1, self), fontEmSize, dpiX, dpiY, transform, isSideways, outlineThreshold, measuringMode, renderingMode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace1_GetVerticalGlyphVariants(self: *const T, glyphCount: u32, nominalGlyphIndices: [*:0]const u16, verticalGlyphIndices: [*:0]u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFace1.VTable, self.vtable).GetVerticalGlyphVariants(@ptrCast(*const IDWriteFontFace1, self), glyphCount, nominalGlyphIndices, verticalGlyphIndices);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace1_HasVerticalGlyphVariants(self: *const T) callconv(.Inline) BOOL {
return @ptrCast(*const IDWriteFontFace1.VTable, self.vtable).HasVerticalGlyphVariants(@ptrCast(*const IDWriteFontFace1, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IDWriteFont1_Value = Guid.initString("acd16696-8c14-4f5d-877e-fe3fc1d32738");
pub const IID_IDWriteFont1 = &IID_IDWriteFont1_Value;
pub const IDWriteFont1 = extern struct {
pub const VTable = extern struct {
base: IDWriteFont.VTable,
GetMetrics: fn(
self: *const IDWriteFont1,
fontMetrics: ?*DWRITE_FONT_METRICS1,
) callconv(@import("std").os.windows.WINAPI) void,
GetPanose: fn(
self: *const IDWriteFont1,
panose: ?*DWRITE_PANOSE,
) callconv(@import("std").os.windows.WINAPI) void,
GetUnicodeRanges: fn(
self: *const IDWriteFont1,
maxRangeCount: u32,
unicodeRanges: ?[*]DWRITE_UNICODE_RANGE,
actualRangeCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsMonospacedFont: fn(
self: *const IDWriteFont1,
) callconv(@import("std").os.windows.WINAPI) BOOL,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFont.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFont1_GetMetrics(self: *const T, fontMetrics: ?*DWRITE_FONT_METRICS1) callconv(.Inline) void {
return @ptrCast(*const IDWriteFont1.VTable, self.vtable).GetMetrics(@ptrCast(*const IDWriteFont1, self), fontMetrics);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFont1_GetPanose(self: *const T, panose: ?*DWRITE_PANOSE) callconv(.Inline) void {
return @ptrCast(*const IDWriteFont1.VTable, self.vtable).GetPanose(@ptrCast(*const IDWriteFont1, self), panose);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFont1_GetUnicodeRanges(self: *const T, maxRangeCount: u32, unicodeRanges: ?[*]DWRITE_UNICODE_RANGE, actualRangeCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFont1.VTable, self.vtable).GetUnicodeRanges(@ptrCast(*const IDWriteFont1, self), maxRangeCount, unicodeRanges, actualRangeCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFont1_IsMonospacedFont(self: *const T) callconv(.Inline) BOOL {
return @ptrCast(*const IDWriteFont1.VTable, self.vtable).IsMonospacedFont(@ptrCast(*const IDWriteFont1, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IDWriteRenderingParams1_Value = Guid.initString("94413cf4-a6fc-4248-8b50-6674348fcad3");
pub const IID_IDWriteRenderingParams1 = &IID_IDWriteRenderingParams1_Value;
pub const IDWriteRenderingParams1 = extern struct {
pub const VTable = extern struct {
base: IDWriteRenderingParams.VTable,
GetGrayscaleEnhancedContrast: fn(
self: *const IDWriteRenderingParams1,
) callconv(@import("std").os.windows.WINAPI) f32,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteRenderingParams.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteRenderingParams1_GetGrayscaleEnhancedContrast(self: *const T) callconv(.Inline) f32 {
return @ptrCast(*const IDWriteRenderingParams1.VTable, self.vtable).GetGrayscaleEnhancedContrast(@ptrCast(*const IDWriteRenderingParams1, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IDWriteTextAnalyzer1_Value = Guid.initString("80dad800-e21f-4e83-96ce-bfcce500db7c");
pub const IID_IDWriteTextAnalyzer1 = &IID_IDWriteTextAnalyzer1_Value;
pub const IDWriteTextAnalyzer1 = extern struct {
pub const VTable = extern struct {
base: IDWriteTextAnalyzer.VTable,
ApplyCharacterSpacing: fn(
self: *const IDWriteTextAnalyzer1,
leadingSpacing: f32,
trailingSpacing: f32,
minimumAdvanceWidth: f32,
textLength: u32,
glyphCount: u32,
clusterMap: [*:0]const u16,
glyphAdvances: [*]const f32,
glyphOffsets: [*]const DWRITE_GLYPH_OFFSET,
glyphProperties: [*]const DWRITE_SHAPING_GLYPH_PROPERTIES,
modifiedGlyphAdvances: [*]f32,
modifiedGlyphOffsets: [*]DWRITE_GLYPH_OFFSET,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetBaseline: fn(
self: *const IDWriteTextAnalyzer1,
fontFace: ?*IDWriteFontFace,
baseline: DWRITE_BASELINE,
isVertical: BOOL,
isSimulationAllowed: BOOL,
scriptAnalysis: DWRITE_SCRIPT_ANALYSIS,
localeName: ?[*:0]const u16,
baselineCoordinate: ?*i32,
exists: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AnalyzeVerticalGlyphOrientation: fn(
self: *const IDWriteTextAnalyzer1,
analysisSource: ?*IDWriteTextAnalysisSource1,
textPosition: u32,
textLength: u32,
analysisSink: ?*IDWriteTextAnalysisSink1,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetGlyphOrientationTransform: fn(
self: *const IDWriteTextAnalyzer1,
glyphOrientationAngle: DWRITE_GLYPH_ORIENTATION_ANGLE,
isSideways: BOOL,
transform: ?*DWRITE_MATRIX,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetScriptProperties: fn(
self: *const IDWriteTextAnalyzer1,
scriptAnalysis: DWRITE_SCRIPT_ANALYSIS,
scriptProperties: ?*DWRITE_SCRIPT_PROPERTIES,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetTextComplexity: fn(
self: *const IDWriteTextAnalyzer1,
textString: [*:0]const u16,
textLength: u32,
fontFace: ?*IDWriteFontFace,
isTextSimple: ?*BOOL,
textLengthRead: ?*u32,
glyphIndices: ?[*:0]u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetJustificationOpportunities: fn(
self: *const IDWriteTextAnalyzer1,
fontFace: ?*IDWriteFontFace,
fontEmSize: f32,
scriptAnalysis: DWRITE_SCRIPT_ANALYSIS,
textLength: u32,
glyphCount: u32,
textString: [*:0]const u16,
clusterMap: [*:0]const u16,
glyphProperties: [*]const DWRITE_SHAPING_GLYPH_PROPERTIES,
justificationOpportunities: [*]DWRITE_JUSTIFICATION_OPPORTUNITY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
JustifyGlyphAdvances: fn(
self: *const IDWriteTextAnalyzer1,
lineWidth: f32,
glyphCount: u32,
justificationOpportunities: [*]const DWRITE_JUSTIFICATION_OPPORTUNITY,
glyphAdvances: [*]const f32,
glyphOffsets: [*]const DWRITE_GLYPH_OFFSET,
justifiedGlyphAdvances: [*]f32,
justifiedGlyphOffsets: ?[*]DWRITE_GLYPH_OFFSET,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetJustifiedGlyphs: fn(
self: *const IDWriteTextAnalyzer1,
fontFace: ?*IDWriteFontFace,
fontEmSize: f32,
scriptAnalysis: DWRITE_SCRIPT_ANALYSIS,
textLength: u32,
glyphCount: u32,
maxGlyphCount: u32,
clusterMap: ?[*:0]const u16,
glyphIndices: [*:0]const u16,
glyphAdvances: [*]const f32,
justifiedGlyphAdvances: [*]const f32,
justifiedGlyphOffsets: [*]const DWRITE_GLYPH_OFFSET,
glyphProperties: [*]const DWRITE_SHAPING_GLYPH_PROPERTIES,
actualGlyphCount: ?*u32,
modifiedClusterMap: ?[*:0]u16,
modifiedGlyphIndices: [*:0]u16,
modifiedGlyphAdvances: [*]f32,
modifiedGlyphOffsets: [*]DWRITE_GLYPH_OFFSET,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteTextAnalyzer.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextAnalyzer1_ApplyCharacterSpacing(self: *const T, leadingSpacing: f32, trailingSpacing: f32, minimumAdvanceWidth: f32, textLength: u32, glyphCount: u32, clusterMap: [*:0]const u16, glyphAdvances: [*]const f32, glyphOffsets: [*]const DWRITE_GLYPH_OFFSET, glyphProperties: [*]const DWRITE_SHAPING_GLYPH_PROPERTIES, modifiedGlyphAdvances: [*]f32, modifiedGlyphOffsets: [*]DWRITE_GLYPH_OFFSET) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextAnalyzer1.VTable, self.vtable).ApplyCharacterSpacing(@ptrCast(*const IDWriteTextAnalyzer1, self), leadingSpacing, trailingSpacing, minimumAdvanceWidth, textLength, glyphCount, clusterMap, glyphAdvances, glyphOffsets, glyphProperties, modifiedGlyphAdvances, modifiedGlyphOffsets);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextAnalyzer1_GetBaseline(self: *const T, fontFace: ?*IDWriteFontFace, baseline: DWRITE_BASELINE, isVertical: BOOL, isSimulationAllowed: BOOL, scriptAnalysis: DWRITE_SCRIPT_ANALYSIS, localeName: ?[*:0]const u16, baselineCoordinate: ?*i32, exists: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextAnalyzer1.VTable, self.vtable).GetBaseline(@ptrCast(*const IDWriteTextAnalyzer1, self), fontFace, baseline, isVertical, isSimulationAllowed, scriptAnalysis, localeName, baselineCoordinate, exists);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextAnalyzer1_AnalyzeVerticalGlyphOrientation(self: *const T, analysisSource: ?*IDWriteTextAnalysisSource1, textPosition: u32, textLength: u32, analysisSink: ?*IDWriteTextAnalysisSink1) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextAnalyzer1.VTable, self.vtable).AnalyzeVerticalGlyphOrientation(@ptrCast(*const IDWriteTextAnalyzer1, self), analysisSource, textPosition, textLength, analysisSink);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextAnalyzer1_GetGlyphOrientationTransform(self: *const T, glyphOrientationAngle: DWRITE_GLYPH_ORIENTATION_ANGLE, isSideways: BOOL, transform: ?*DWRITE_MATRIX) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextAnalyzer1.VTable, self.vtable).GetGlyphOrientationTransform(@ptrCast(*const IDWriteTextAnalyzer1, self), glyphOrientationAngle, isSideways, transform);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextAnalyzer1_GetScriptProperties(self: *const T, scriptAnalysis: DWRITE_SCRIPT_ANALYSIS, scriptProperties: ?*DWRITE_SCRIPT_PROPERTIES) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextAnalyzer1.VTable, self.vtable).GetScriptProperties(@ptrCast(*const IDWriteTextAnalyzer1, self), scriptAnalysis, scriptProperties);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextAnalyzer1_GetTextComplexity(self: *const T, textString: [*:0]const u16, textLength: u32, fontFace: ?*IDWriteFontFace, isTextSimple: ?*BOOL, textLengthRead: ?*u32, glyphIndices: ?[*:0]u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextAnalyzer1.VTable, self.vtable).GetTextComplexity(@ptrCast(*const IDWriteTextAnalyzer1, self), textString, textLength, fontFace, isTextSimple, textLengthRead, glyphIndices);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextAnalyzer1_GetJustificationOpportunities(self: *const T, fontFace: ?*IDWriteFontFace, fontEmSize: f32, scriptAnalysis: DWRITE_SCRIPT_ANALYSIS, textLength: u32, glyphCount: u32, textString: [*:0]const u16, clusterMap: [*:0]const u16, glyphProperties: [*]const DWRITE_SHAPING_GLYPH_PROPERTIES, justificationOpportunities: [*]DWRITE_JUSTIFICATION_OPPORTUNITY) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextAnalyzer1.VTable, self.vtable).GetJustificationOpportunities(@ptrCast(*const IDWriteTextAnalyzer1, self), fontFace, fontEmSize, scriptAnalysis, textLength, glyphCount, textString, clusterMap, glyphProperties, justificationOpportunities);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextAnalyzer1_JustifyGlyphAdvances(self: *const T, lineWidth: f32, glyphCount: u32, justificationOpportunities: [*]const DWRITE_JUSTIFICATION_OPPORTUNITY, glyphAdvances: [*]const f32, glyphOffsets: [*]const DWRITE_GLYPH_OFFSET, justifiedGlyphAdvances: [*]f32, justifiedGlyphOffsets: ?[*]DWRITE_GLYPH_OFFSET) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextAnalyzer1.VTable, self.vtable).JustifyGlyphAdvances(@ptrCast(*const IDWriteTextAnalyzer1, self), lineWidth, glyphCount, justificationOpportunities, glyphAdvances, glyphOffsets, justifiedGlyphAdvances, justifiedGlyphOffsets);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextAnalyzer1_GetJustifiedGlyphs(self: *const T, fontFace: ?*IDWriteFontFace, fontEmSize: f32, scriptAnalysis: DWRITE_SCRIPT_ANALYSIS, textLength: u32, glyphCount: u32, maxGlyphCount: u32, clusterMap: ?[*:0]const u16, glyphIndices: [*:0]const u16, glyphAdvances: [*]const f32, justifiedGlyphAdvances: [*]const f32, justifiedGlyphOffsets: [*]const DWRITE_GLYPH_OFFSET, glyphProperties: [*]const DWRITE_SHAPING_GLYPH_PROPERTIES, actualGlyphCount: ?*u32, modifiedClusterMap: ?[*:0]u16, modifiedGlyphIndices: [*:0]u16, modifiedGlyphAdvances: [*]f32, modifiedGlyphOffsets: [*]DWRITE_GLYPH_OFFSET) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextAnalyzer1.VTable, self.vtable).GetJustifiedGlyphs(@ptrCast(*const IDWriteTextAnalyzer1, self), fontFace, fontEmSize, scriptAnalysis, textLength, glyphCount, maxGlyphCount, clusterMap, glyphIndices, glyphAdvances, justifiedGlyphAdvances, justifiedGlyphOffsets, glyphProperties, actualGlyphCount, modifiedClusterMap, modifiedGlyphIndices, modifiedGlyphAdvances, modifiedGlyphOffsets);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IDWriteTextAnalysisSource1_Value = Guid.initString("639cfad8-0fb4-4b21-a58a-067920120009");
pub const IID_IDWriteTextAnalysisSource1 = &IID_IDWriteTextAnalysisSource1_Value;
pub const IDWriteTextAnalysisSource1 = extern struct {
pub const VTable = extern struct {
base: IDWriteTextAnalysisSource.VTable,
GetVerticalGlyphOrientation: fn(
self: *const IDWriteTextAnalysisSource1,
textPosition: u32,
textLength: ?*u32,
glyphOrientation: ?*DWRITE_VERTICAL_GLYPH_ORIENTATION,
bidiLevel: ?*u8,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteTextAnalysisSource.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextAnalysisSource1_GetVerticalGlyphOrientation(self: *const T, textPosition: u32, textLength: ?*u32, glyphOrientation: ?*DWRITE_VERTICAL_GLYPH_ORIENTATION, bidiLevel: ?*u8) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextAnalysisSource1.VTable, self.vtable).GetVerticalGlyphOrientation(@ptrCast(*const IDWriteTextAnalysisSource1, self), textPosition, textLength, glyphOrientation, bidiLevel);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IDWriteTextAnalysisSink1_Value = Guid.initString("b0d941a0-85e7-4d8b-9fd3-5ced9934482a");
pub const IID_IDWriteTextAnalysisSink1 = &IID_IDWriteTextAnalysisSink1_Value;
pub const IDWriteTextAnalysisSink1 = extern struct {
pub const VTable = extern struct {
base: IDWriteTextAnalysisSink.VTable,
SetGlyphOrientation: fn(
self: *const IDWriteTextAnalysisSink1,
textPosition: u32,
textLength: u32,
glyphOrientationAngle: DWRITE_GLYPH_ORIENTATION_ANGLE,
adjustedBidiLevel: u8,
isSideways: BOOL,
isRightToLeft: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteTextAnalysisSink.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextAnalysisSink1_SetGlyphOrientation(self: *const T, textPosition: u32, textLength: u32, glyphOrientationAngle: DWRITE_GLYPH_ORIENTATION_ANGLE, adjustedBidiLevel: u8, isSideways: BOOL, isRightToLeft: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextAnalysisSink1.VTable, self.vtable).SetGlyphOrientation(@ptrCast(*const IDWriteTextAnalysisSink1, self), textPosition, textLength, glyphOrientationAngle, adjustedBidiLevel, isSideways, isRightToLeft);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IDWriteTextLayout1_Value = Guid.initString("9064d822-80a7-465c-a986-df65f78b8feb");
pub const IID_IDWriteTextLayout1 = &IID_IDWriteTextLayout1_Value;
pub const IDWriteTextLayout1 = extern struct {
pub const VTable = extern struct {
base: IDWriteTextLayout.VTable,
SetPairKerning: fn(
self: *const IDWriteTextLayout1,
isPairKerningEnabled: BOOL,
textRange: DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPairKerning: fn(
self: *const IDWriteTextLayout1,
currentPosition: u32,
isPairKerningEnabled: ?*BOOL,
textRange: ?*DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCharacterSpacing: fn(
self: *const IDWriteTextLayout1,
leadingSpacing: f32,
trailingSpacing: f32,
minimumAdvanceWidth: f32,
textRange: DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCharacterSpacing: fn(
self: *const IDWriteTextLayout1,
currentPosition: u32,
leadingSpacing: ?*f32,
trailingSpacing: ?*f32,
minimumAdvanceWidth: ?*f32,
textRange: ?*DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteTextLayout.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout1_SetPairKerning(self: *const T, isPairKerningEnabled: BOOL, textRange: DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout1.VTable, self.vtable).SetPairKerning(@ptrCast(*const IDWriteTextLayout1, self), isPairKerningEnabled, textRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout1_GetPairKerning(self: *const T, currentPosition: u32, isPairKerningEnabled: ?*BOOL, textRange: ?*DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout1.VTable, self.vtable).GetPairKerning(@ptrCast(*const IDWriteTextLayout1, self), currentPosition, isPairKerningEnabled, textRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout1_SetCharacterSpacing(self: *const T, leadingSpacing: f32, trailingSpacing: f32, minimumAdvanceWidth: f32, textRange: DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout1.VTable, self.vtable).SetCharacterSpacing(@ptrCast(*const IDWriteTextLayout1, self), leadingSpacing, trailingSpacing, minimumAdvanceWidth, textRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout1_GetCharacterSpacing(self: *const T, currentPosition: u32, leadingSpacing: ?*f32, trailingSpacing: ?*f32, minimumAdvanceWidth: ?*f32, textRange: ?*DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout1.VTable, self.vtable).GetCharacterSpacing(@ptrCast(*const IDWriteTextLayout1, self), currentPosition, leadingSpacing, trailingSpacing, minimumAdvanceWidth, textRange);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DWRITE_TEXT_ANTIALIAS_MODE = enum(i32) {
CLEARTYPE = 0,
GRAYSCALE = 1,
};
pub const DWRITE_TEXT_ANTIALIAS_MODE_CLEARTYPE = DWRITE_TEXT_ANTIALIAS_MODE.CLEARTYPE;
pub const DWRITE_TEXT_ANTIALIAS_MODE_GRAYSCALE = DWRITE_TEXT_ANTIALIAS_MODE.GRAYSCALE;
// TODO: this type is limited to platform 'windows8.0'
const IID_IDWriteBitmapRenderTarget1_Value = Guid.initString("791e8298-3ef3-4230-9880-c9bdecc42064");
pub const IID_IDWriteBitmapRenderTarget1 = &IID_IDWriteBitmapRenderTarget1_Value;
pub const IDWriteBitmapRenderTarget1 = extern struct {
pub const VTable = extern struct {
base: IDWriteBitmapRenderTarget.VTable,
GetTextAntialiasMode: fn(
self: *const IDWriteBitmapRenderTarget1,
) callconv(@import("std").os.windows.WINAPI) DWRITE_TEXT_ANTIALIAS_MODE,
SetTextAntialiasMode: fn(
self: *const IDWriteBitmapRenderTarget1,
antialiasMode: DWRITE_TEXT_ANTIALIAS_MODE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteBitmapRenderTarget.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteBitmapRenderTarget1_GetTextAntialiasMode(self: *const T) callconv(.Inline) DWRITE_TEXT_ANTIALIAS_MODE {
return @ptrCast(*const IDWriteBitmapRenderTarget1.VTable, self.vtable).GetTextAntialiasMode(@ptrCast(*const IDWriteBitmapRenderTarget1, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteBitmapRenderTarget1_SetTextAntialiasMode(self: *const T, antialiasMode: DWRITE_TEXT_ANTIALIAS_MODE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteBitmapRenderTarget1.VTable, self.vtable).SetTextAntialiasMode(@ptrCast(*const IDWriteBitmapRenderTarget1, self), antialiasMode);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DWRITE_OPTICAL_ALIGNMENT = enum(i32) {
NE = 0,
_SIDE_BEARINGS = 1,
};
pub const DWRITE_OPTICAL_ALIGNMENT_NONE = DWRITE_OPTICAL_ALIGNMENT.NE;
pub const DWRITE_OPTICAL_ALIGNMENT_NO_SIDE_BEARINGS = DWRITE_OPTICAL_ALIGNMENT._SIDE_BEARINGS;
pub const DWRITE_GRID_FIT_MODE = enum(i32) {
DEFAULT = 0,
DISABLED = 1,
ENABLED = 2,
};
pub const DWRITE_GRID_FIT_MODE_DEFAULT = DWRITE_GRID_FIT_MODE.DEFAULT;
pub const DWRITE_GRID_FIT_MODE_DISABLED = DWRITE_GRID_FIT_MODE.DISABLED;
pub const DWRITE_GRID_FIT_MODE_ENABLED = DWRITE_GRID_FIT_MODE.ENABLED;
pub const DWRITE_TEXT_METRICS1 = extern struct {
Base: DWRITE_TEXT_METRICS,
heightIncludingTrailingWhitespace: f32,
};
// TODO: this type is limited to platform 'windows8.1'
const IID_IDWriteTextRenderer1_Value = Guid.initString("d3e0e934-22a0-427e-aae4-7d9574b59db1");
pub const IID_IDWriteTextRenderer1 = &IID_IDWriteTextRenderer1_Value;
pub const IDWriteTextRenderer1 = extern struct {
pub const VTable = extern struct {
base: IDWriteTextRenderer.VTable,
DrawGlyphRun: fn(
self: *const IDWriteTextRenderer1,
clientDrawingContext: ?*anyopaque,
baselineOriginX: f32,
baselineOriginY: f32,
orientationAngle: DWRITE_GLYPH_ORIENTATION_ANGLE,
measuringMode: DWRITE_MEASURING_MODE,
glyphRun: ?*const DWRITE_GLYPH_RUN,
glyphRunDescription: ?*const DWRITE_GLYPH_RUN_DESCRIPTION,
clientDrawingEffect: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DrawUnderline: fn(
self: *const IDWriteTextRenderer1,
clientDrawingContext: ?*anyopaque,
baselineOriginX: f32,
baselineOriginY: f32,
orientationAngle: DWRITE_GLYPH_ORIENTATION_ANGLE,
underline: ?*const DWRITE_UNDERLINE,
clientDrawingEffect: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DrawStrikethrough: fn(
self: *const IDWriteTextRenderer1,
clientDrawingContext: ?*anyopaque,
baselineOriginX: f32,
baselineOriginY: f32,
orientationAngle: DWRITE_GLYPH_ORIENTATION_ANGLE,
strikethrough: ?*const DWRITE_STRIKETHROUGH,
clientDrawingEffect: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DrawInlineObject: fn(
self: *const IDWriteTextRenderer1,
clientDrawingContext: ?*anyopaque,
originX: f32,
originY: f32,
orientationAngle: DWRITE_GLYPH_ORIENTATION_ANGLE,
inlineObject: ?*IDWriteInlineObject,
isSideways: BOOL,
isRightToLeft: BOOL,
clientDrawingEffect: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteTextRenderer.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextRenderer1_DrawGlyphRun(self: *const T, clientDrawingContext: ?*anyopaque, baselineOriginX: f32, baselineOriginY: f32, orientationAngle: DWRITE_GLYPH_ORIENTATION_ANGLE, measuringMode: DWRITE_MEASURING_MODE, glyphRun: ?*const DWRITE_GLYPH_RUN, glyphRunDescription: ?*const DWRITE_GLYPH_RUN_DESCRIPTION, clientDrawingEffect: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextRenderer1.VTable, self.vtable).DrawGlyphRun(@ptrCast(*const IDWriteTextRenderer1, self), clientDrawingContext, baselineOriginX, baselineOriginY, orientationAngle, measuringMode, glyphRun, glyphRunDescription, clientDrawingEffect);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextRenderer1_DrawUnderline(self: *const T, clientDrawingContext: ?*anyopaque, baselineOriginX: f32, baselineOriginY: f32, orientationAngle: DWRITE_GLYPH_ORIENTATION_ANGLE, underline: ?*const DWRITE_UNDERLINE, clientDrawingEffect: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextRenderer1.VTable, self.vtable).DrawUnderline(@ptrCast(*const IDWriteTextRenderer1, self), clientDrawingContext, baselineOriginX, baselineOriginY, orientationAngle, underline, clientDrawingEffect);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextRenderer1_DrawStrikethrough(self: *const T, clientDrawingContext: ?*anyopaque, baselineOriginX: f32, baselineOriginY: f32, orientationAngle: DWRITE_GLYPH_ORIENTATION_ANGLE, strikethrough: ?*const DWRITE_STRIKETHROUGH, clientDrawingEffect: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextRenderer1.VTable, self.vtable).DrawStrikethrough(@ptrCast(*const IDWriteTextRenderer1, self), clientDrawingContext, baselineOriginX, baselineOriginY, orientationAngle, strikethrough, clientDrawingEffect);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextRenderer1_DrawInlineObject(self: *const T, clientDrawingContext: ?*anyopaque, originX: f32, originY: f32, orientationAngle: DWRITE_GLYPH_ORIENTATION_ANGLE, inlineObject: ?*IDWriteInlineObject, isSideways: BOOL, isRightToLeft: BOOL, clientDrawingEffect: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextRenderer1.VTable, self.vtable).DrawInlineObject(@ptrCast(*const IDWriteTextRenderer1, self), clientDrawingContext, originX, originY, orientationAngle, inlineObject, isSideways, isRightToLeft, clientDrawingEffect);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.1'
const IID_IDWriteTextFormat1_Value = Guid.initString("5f174b49-0d8b-4cfb-8bca-f1cce9d06c67");
pub const IID_IDWriteTextFormat1 = &IID_IDWriteTextFormat1_Value;
pub const IDWriteTextFormat1 = extern struct {
pub const VTable = extern struct {
base: IDWriteTextFormat.VTable,
SetVerticalGlyphOrientation: fn(
self: *const IDWriteTextFormat1,
glyphOrientation: DWRITE_VERTICAL_GLYPH_ORIENTATION,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetVerticalGlyphOrientation: fn(
self: *const IDWriteTextFormat1,
) callconv(@import("std").os.windows.WINAPI) DWRITE_VERTICAL_GLYPH_ORIENTATION,
SetLastLineWrapping: fn(
self: *const IDWriteTextFormat1,
isLastLineWrappingEnabled: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLastLineWrapping: fn(
self: *const IDWriteTextFormat1,
) callconv(@import("std").os.windows.WINAPI) BOOL,
SetOpticalAlignment: fn(
self: *const IDWriteTextFormat1,
opticalAlignment: DWRITE_OPTICAL_ALIGNMENT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetOpticalAlignment: fn(
self: *const IDWriteTextFormat1,
) callconv(@import("std").os.windows.WINAPI) DWRITE_OPTICAL_ALIGNMENT,
SetFontFallback: fn(
self: *const IDWriteTextFormat1,
fontFallback: ?*IDWriteFontFallback,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontFallback: fn(
self: *const IDWriteTextFormat1,
fontFallback: ?*?*IDWriteFontFallback,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteTextFormat.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat1_SetVerticalGlyphOrientation(self: *const T, glyphOrientation: DWRITE_VERTICAL_GLYPH_ORIENTATION) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextFormat1.VTable, self.vtable).SetVerticalGlyphOrientation(@ptrCast(*const IDWriteTextFormat1, self), glyphOrientation);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat1_GetVerticalGlyphOrientation(self: *const T) callconv(.Inline) DWRITE_VERTICAL_GLYPH_ORIENTATION {
return @ptrCast(*const IDWriteTextFormat1.VTable, self.vtable).GetVerticalGlyphOrientation(@ptrCast(*const IDWriteTextFormat1, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat1_SetLastLineWrapping(self: *const T, isLastLineWrappingEnabled: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextFormat1.VTable, self.vtable).SetLastLineWrapping(@ptrCast(*const IDWriteTextFormat1, self), isLastLineWrappingEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat1_GetLastLineWrapping(self: *const T) callconv(.Inline) BOOL {
return @ptrCast(*const IDWriteTextFormat1.VTable, self.vtable).GetLastLineWrapping(@ptrCast(*const IDWriteTextFormat1, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat1_SetOpticalAlignment(self: *const T, opticalAlignment: DWRITE_OPTICAL_ALIGNMENT) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextFormat1.VTable, self.vtable).SetOpticalAlignment(@ptrCast(*const IDWriteTextFormat1, self), opticalAlignment);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat1_GetOpticalAlignment(self: *const T) callconv(.Inline) DWRITE_OPTICAL_ALIGNMENT {
return @ptrCast(*const IDWriteTextFormat1.VTable, self.vtable).GetOpticalAlignment(@ptrCast(*const IDWriteTextFormat1, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat1_SetFontFallback(self: *const T, fontFallback: ?*IDWriteFontFallback) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextFormat1.VTable, self.vtable).SetFontFallback(@ptrCast(*const IDWriteTextFormat1, self), fontFallback);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat1_GetFontFallback(self: *const T, fontFallback: ?*?*IDWriteFontFallback) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextFormat1.VTable, self.vtable).GetFontFallback(@ptrCast(*const IDWriteTextFormat1, self), fontFallback);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.1'
const IID_IDWriteTextLayout2_Value = Guid.initString("1093c18f-8d5e-43f0-b064-0917311b525e");
pub const IID_IDWriteTextLayout2 = &IID_IDWriteTextLayout2_Value;
pub const IDWriteTextLayout2 = extern struct {
pub const VTable = extern struct {
base: IDWriteTextLayout1.VTable,
GetMetrics: fn(
self: *const IDWriteTextLayout2,
textMetrics: ?*DWRITE_TEXT_METRICS1,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetVerticalGlyphOrientation: fn(
self: *const IDWriteTextLayout2,
glyphOrientation: DWRITE_VERTICAL_GLYPH_ORIENTATION,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetVerticalGlyphOrientation: fn(
self: *const IDWriteTextLayout2,
) callconv(@import("std").os.windows.WINAPI) DWRITE_VERTICAL_GLYPH_ORIENTATION,
SetLastLineWrapping: fn(
self: *const IDWriteTextLayout2,
isLastLineWrappingEnabled: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLastLineWrapping: fn(
self: *const IDWriteTextLayout2,
) callconv(@import("std").os.windows.WINAPI) BOOL,
SetOpticalAlignment: fn(
self: *const IDWriteTextLayout2,
opticalAlignment: DWRITE_OPTICAL_ALIGNMENT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetOpticalAlignment: fn(
self: *const IDWriteTextLayout2,
) callconv(@import("std").os.windows.WINAPI) DWRITE_OPTICAL_ALIGNMENT,
SetFontFallback: fn(
self: *const IDWriteTextLayout2,
fontFallback: ?*IDWriteFontFallback,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontFallback: fn(
self: *const IDWriteTextLayout2,
fontFallback: ?*?*IDWriteFontFallback,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteTextLayout1.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout2_GetMetrics(self: *const T, textMetrics: ?*DWRITE_TEXT_METRICS1) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout2.VTable, self.vtable).GetMetrics(@ptrCast(*const IDWriteTextLayout2, self), textMetrics);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout2_SetVerticalGlyphOrientation(self: *const T, glyphOrientation: DWRITE_VERTICAL_GLYPH_ORIENTATION) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout2.VTable, self.vtable).SetVerticalGlyphOrientation(@ptrCast(*const IDWriteTextLayout2, self), glyphOrientation);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout2_GetVerticalGlyphOrientation(self: *const T) callconv(.Inline) DWRITE_VERTICAL_GLYPH_ORIENTATION {
return @ptrCast(*const IDWriteTextLayout2.VTable, self.vtable).GetVerticalGlyphOrientation(@ptrCast(*const IDWriteTextLayout2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout2_SetLastLineWrapping(self: *const T, isLastLineWrappingEnabled: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout2.VTable, self.vtable).SetLastLineWrapping(@ptrCast(*const IDWriteTextLayout2, self), isLastLineWrappingEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout2_GetLastLineWrapping(self: *const T) callconv(.Inline) BOOL {
return @ptrCast(*const IDWriteTextLayout2.VTable, self.vtable).GetLastLineWrapping(@ptrCast(*const IDWriteTextLayout2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout2_SetOpticalAlignment(self: *const T, opticalAlignment: DWRITE_OPTICAL_ALIGNMENT) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout2.VTable, self.vtable).SetOpticalAlignment(@ptrCast(*const IDWriteTextLayout2, self), opticalAlignment);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout2_GetOpticalAlignment(self: *const T) callconv(.Inline) DWRITE_OPTICAL_ALIGNMENT {
return @ptrCast(*const IDWriteTextLayout2.VTable, self.vtable).GetOpticalAlignment(@ptrCast(*const IDWriteTextLayout2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout2_SetFontFallback(self: *const T, fontFallback: ?*IDWriteFontFallback) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout2.VTable, self.vtable).SetFontFallback(@ptrCast(*const IDWriteTextLayout2, self), fontFallback);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout2_GetFontFallback(self: *const T, fontFallback: ?*?*IDWriteFontFallback) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout2.VTable, self.vtable).GetFontFallback(@ptrCast(*const IDWriteTextLayout2, self), fontFallback);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.1'
const IID_IDWriteTextAnalyzer2_Value = Guid.initString("553a9ff3-5693-4df7-b52b-74806f7f2eb9");
pub const IID_IDWriteTextAnalyzer2 = &IID_IDWriteTextAnalyzer2_Value;
pub const IDWriteTextAnalyzer2 = extern struct {
pub const VTable = extern struct {
base: IDWriteTextAnalyzer1.VTable,
GetGlyphOrientationTransform: fn(
self: *const IDWriteTextAnalyzer2,
glyphOrientationAngle: DWRITE_GLYPH_ORIENTATION_ANGLE,
isSideways: BOOL,
originX: f32,
originY: f32,
transform: ?*DWRITE_MATRIX,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetTypographicFeatures: fn(
self: *const IDWriteTextAnalyzer2,
fontFace: ?*IDWriteFontFace,
scriptAnalysis: DWRITE_SCRIPT_ANALYSIS,
localeName: ?[*:0]const u16,
maxTagCount: u32,
actualTagCount: ?*u32,
tags: [*]DWRITE_FONT_FEATURE_TAG,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CheckTypographicFeature: fn(
self: *const IDWriteTextAnalyzer2,
fontFace: ?*IDWriteFontFace,
scriptAnalysis: DWRITE_SCRIPT_ANALYSIS,
localeName: ?[*:0]const u16,
featureTag: DWRITE_FONT_FEATURE_TAG,
glyphCount: u32,
glyphIndices: [*:0]const u16,
featureApplies: [*:0]u8,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteTextAnalyzer1.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextAnalyzer2_GetGlyphOrientationTransform(self: *const T, glyphOrientationAngle: DWRITE_GLYPH_ORIENTATION_ANGLE, isSideways: BOOL, originX: f32, originY: f32, transform: ?*DWRITE_MATRIX) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextAnalyzer2.VTable, self.vtable).GetGlyphOrientationTransform(@ptrCast(*const IDWriteTextAnalyzer2, self), glyphOrientationAngle, isSideways, originX, originY, transform);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextAnalyzer2_GetTypographicFeatures(self: *const T, fontFace: ?*IDWriteFontFace, scriptAnalysis: DWRITE_SCRIPT_ANALYSIS, localeName: ?[*:0]const u16, maxTagCount: u32, actualTagCount: ?*u32, tags: [*]DWRITE_FONT_FEATURE_TAG) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextAnalyzer2.VTable, self.vtable).GetTypographicFeatures(@ptrCast(*const IDWriteTextAnalyzer2, self), fontFace, scriptAnalysis, localeName, maxTagCount, actualTagCount, tags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextAnalyzer2_CheckTypographicFeature(self: *const T, fontFace: ?*IDWriteFontFace, scriptAnalysis: DWRITE_SCRIPT_ANALYSIS, localeName: ?[*:0]const u16, featureTag: DWRITE_FONT_FEATURE_TAG, glyphCount: u32, glyphIndices: [*:0]const u16, featureApplies: [*:0]u8) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextAnalyzer2.VTable, self.vtable).CheckTypographicFeature(@ptrCast(*const IDWriteTextAnalyzer2, self), fontFace, scriptAnalysis, localeName, featureTag, glyphCount, glyphIndices, featureApplies);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.1'
const IID_IDWriteFontFallback_Value = Guid.initString("efa008f9-f7a1-48bf-b05c-f224713cc0ff");
pub const IID_IDWriteFontFallback = &IID_IDWriteFontFallback_Value;
pub const IDWriteFontFallback = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
MapCharacters: fn(
self: *const IDWriteFontFallback,
analysisSource: ?*IDWriteTextAnalysisSource,
textPosition: u32,
textLength: u32,
baseFontCollection: ?*IDWriteFontCollection,
baseFamilyName: ?[*:0]const u16,
baseWeight: DWRITE_FONT_WEIGHT,
baseStyle: DWRITE_FONT_STYLE,
baseStretch: DWRITE_FONT_STRETCH,
mappedLength: ?*u32,
mappedFont: ?*?*IDWriteFont,
scale: ?*f32,
) 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 IDWriteFontFallback_MapCharacters(self: *const T, analysisSource: ?*IDWriteTextAnalysisSource, textPosition: u32, textLength: u32, baseFontCollection: ?*IDWriteFontCollection, baseFamilyName: ?[*:0]const u16, baseWeight: DWRITE_FONT_WEIGHT, baseStyle: DWRITE_FONT_STYLE, baseStretch: DWRITE_FONT_STRETCH, mappedLength: ?*u32, mappedFont: ?*?*IDWriteFont, scale: ?*f32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFallback.VTable, self.vtable).MapCharacters(@ptrCast(*const IDWriteFontFallback, self), analysisSource, textPosition, textLength, baseFontCollection, baseFamilyName, baseWeight, baseStyle, baseStretch, mappedLength, mappedFont, scale);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.1'
const IID_IDWriteFontFallbackBuilder_Value = Guid.initString("fd882d06-8aba-4fb8-b849-8be8b73e14de");
pub const IID_IDWriteFontFallbackBuilder = &IID_IDWriteFontFallbackBuilder_Value;
pub const IDWriteFontFallbackBuilder = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
AddMapping: fn(
self: *const IDWriteFontFallbackBuilder,
ranges: [*]const DWRITE_UNICODE_RANGE,
rangesCount: u32,
targetFamilyNames: [*]const ?*const u16,
targetFamilyNamesCount: u32,
fontCollection: ?*IDWriteFontCollection,
localeName: ?[*:0]const u16,
baseFamilyName: ?[*:0]const u16,
scale: f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddMappings: fn(
self: *const IDWriteFontFallbackBuilder,
fontFallback: ?*IDWriteFontFallback,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateFontFallback: fn(
self: *const IDWriteFontFallbackBuilder,
fontFallback: ?*?*IDWriteFontFallback,
) 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 IDWriteFontFallbackBuilder_AddMapping(self: *const T, ranges: [*]const DWRITE_UNICODE_RANGE, rangesCount: u32, targetFamilyNames: [*]const ?*const u16, targetFamilyNamesCount: u32, fontCollection: ?*IDWriteFontCollection, localeName: ?[*:0]const u16, baseFamilyName: ?[*:0]const u16, scale: f32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFallbackBuilder.VTable, self.vtable).AddMapping(@ptrCast(*const IDWriteFontFallbackBuilder, self), ranges, rangesCount, targetFamilyNames, targetFamilyNamesCount, fontCollection, localeName, baseFamilyName, scale);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFallbackBuilder_AddMappings(self: *const T, fontFallback: ?*IDWriteFontFallback) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFallbackBuilder.VTable, self.vtable).AddMappings(@ptrCast(*const IDWriteFontFallbackBuilder, self), fontFallback);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFallbackBuilder_CreateFontFallback(self: *const T, fontFallback: ?*?*IDWriteFontFallback) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFallbackBuilder.VTable, self.vtable).CreateFontFallback(@ptrCast(*const IDWriteFontFallbackBuilder, self), fontFallback);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.1'
const IID_IDWriteFont2_Value = Guid.initString("29748ed6-8c9c-4a6a-be0b-d912e8538944");
pub const IID_IDWriteFont2 = &IID_IDWriteFont2_Value;
pub const IDWriteFont2 = extern struct {
pub const VTable = extern struct {
base: IDWriteFont1.VTable,
IsColorFont: fn(
self: *const IDWriteFont2,
) callconv(@import("std").os.windows.WINAPI) BOOL,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFont1.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFont2_IsColorFont(self: *const T) callconv(.Inline) BOOL {
return @ptrCast(*const IDWriteFont2.VTable, self.vtable).IsColorFont(@ptrCast(*const IDWriteFont2, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.1'
const IID_IDWriteFontFace2_Value = Guid.initString("d8b768ff-64bc-4e66-982b-ec8e87f693f7");
pub const IID_IDWriteFontFace2 = &IID_IDWriteFontFace2_Value;
pub const IDWriteFontFace2 = extern struct {
pub const VTable = extern struct {
base: IDWriteFontFace1.VTable,
IsColorFont: fn(
self: *const IDWriteFontFace2,
) callconv(@import("std").os.windows.WINAPI) BOOL,
GetColorPaletteCount: fn(
self: *const IDWriteFontFace2,
) callconv(@import("std").os.windows.WINAPI) u32,
GetPaletteEntryCount: fn(
self: *const IDWriteFontFace2,
) callconv(@import("std").os.windows.WINAPI) u32,
GetPaletteEntries: fn(
self: *const IDWriteFontFace2,
colorPaletteIndex: u32,
firstEntryIndex: u32,
entryCount: u32,
paletteEntries: [*]DWRITE_COLOR_F,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetRecommendedRenderingMode: fn(
self: *const IDWriteFontFace2,
fontEmSize: f32,
dpiX: f32,
dpiY: f32,
transform: ?*const DWRITE_MATRIX,
isSideways: BOOL,
outlineThreshold: DWRITE_OUTLINE_THRESHOLD,
measuringMode: DWRITE_MEASURING_MODE,
renderingParams: ?*IDWriteRenderingParams,
renderingMode: ?*DWRITE_RENDERING_MODE,
gridFitMode: ?*DWRITE_GRID_FIT_MODE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFontFace1.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace2_IsColorFont(self: *const T) callconv(.Inline) BOOL {
return @ptrCast(*const IDWriteFontFace2.VTable, self.vtable).IsColorFont(@ptrCast(*const IDWriteFontFace2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace2_GetColorPaletteCount(self: *const T) callconv(.Inline) u32 {
return @ptrCast(*const IDWriteFontFace2.VTable, self.vtable).GetColorPaletteCount(@ptrCast(*const IDWriteFontFace2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace2_GetPaletteEntryCount(self: *const T) callconv(.Inline) u32 {
return @ptrCast(*const IDWriteFontFace2.VTable, self.vtable).GetPaletteEntryCount(@ptrCast(*const IDWriteFontFace2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace2_GetPaletteEntries(self: *const T, colorPaletteIndex: u32, firstEntryIndex: u32, entryCount: u32, paletteEntries: [*]DWRITE_COLOR_F) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFace2.VTable, self.vtable).GetPaletteEntries(@ptrCast(*const IDWriteFontFace2, self), colorPaletteIndex, firstEntryIndex, entryCount, paletteEntries);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace2_GetRecommendedRenderingMode(self: *const T, fontEmSize: f32, dpiX: f32, dpiY: f32, transform: ?*const DWRITE_MATRIX, isSideways: BOOL, outlineThreshold: DWRITE_OUTLINE_THRESHOLD, measuringMode: DWRITE_MEASURING_MODE, renderingParams: ?*IDWriteRenderingParams, renderingMode: ?*DWRITE_RENDERING_MODE, gridFitMode: ?*DWRITE_GRID_FIT_MODE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFace2.VTable, self.vtable).GetRecommendedRenderingMode(@ptrCast(*const IDWriteFontFace2, self), fontEmSize, dpiX, dpiY, transform, isSideways, outlineThreshold, measuringMode, renderingParams, renderingMode, gridFitMode);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DWRITE_COLOR_GLYPH_RUN = extern struct {
glyphRun: DWRITE_GLYPH_RUN,
glyphRunDescription: ?*DWRITE_GLYPH_RUN_DESCRIPTION,
baselineOriginX: f32,
baselineOriginY: f32,
runColor: DWRITE_COLOR_F,
paletteIndex: u16,
};
// TODO: this type is limited to platform 'windows8.1'
const IID_IDWriteColorGlyphRunEnumerator_Value = Guid.initString("d31fbe17-f157-41a2-8d24-cb779e0560e8");
pub const IID_IDWriteColorGlyphRunEnumerator = &IID_IDWriteColorGlyphRunEnumerator_Value;
pub const IDWriteColorGlyphRunEnumerator = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
MoveNext: fn(
self: *const IDWriteColorGlyphRunEnumerator,
hasRun: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCurrentRun: fn(
self: *const IDWriteColorGlyphRunEnumerator,
colorGlyphRun: ?*const ?*DWRITE_COLOR_GLYPH_RUN,
) 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 IDWriteColorGlyphRunEnumerator_MoveNext(self: *const T, hasRun: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteColorGlyphRunEnumerator.VTable, self.vtable).MoveNext(@ptrCast(*const IDWriteColorGlyphRunEnumerator, self), hasRun);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteColorGlyphRunEnumerator_GetCurrentRun(self: *const T, colorGlyphRun: ?*const ?*DWRITE_COLOR_GLYPH_RUN) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteColorGlyphRunEnumerator.VTable, self.vtable).GetCurrentRun(@ptrCast(*const IDWriteColorGlyphRunEnumerator, self), colorGlyphRun);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.1'
const IID_IDWriteRenderingParams2_Value = Guid.initString("f9d711c3-9777-40ae-87e8-3e5af9bf0948");
pub const IID_IDWriteRenderingParams2 = &IID_IDWriteRenderingParams2_Value;
pub const IDWriteRenderingParams2 = extern struct {
pub const VTable = extern struct {
base: IDWriteRenderingParams1.VTable,
GetGridFitMode: fn(
self: *const IDWriteRenderingParams2,
) callconv(@import("std").os.windows.WINAPI) DWRITE_GRID_FIT_MODE,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteRenderingParams1.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteRenderingParams2_GetGridFitMode(self: *const T) callconv(.Inline) DWRITE_GRID_FIT_MODE {
return @ptrCast(*const IDWriteRenderingParams2.VTable, self.vtable).GetGridFitMode(@ptrCast(*const IDWriteRenderingParams2, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.1'
const IID_IDWriteFactory2_Value = Guid.initString("0439fc60-ca44-4994-8dee-3a9af7b732ec");
pub const IID_IDWriteFactory2 = &IID_IDWriteFactory2_Value;
pub const IDWriteFactory2 = extern struct {
pub const VTable = extern struct {
base: IDWriteFactory1.VTable,
GetSystemFontFallback: fn(
self: *const IDWriteFactory2,
fontFallback: ?*?*IDWriteFontFallback,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateFontFallbackBuilder: fn(
self: *const IDWriteFactory2,
fontFallbackBuilder: ?*?*IDWriteFontFallbackBuilder,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TranslateColorGlyphRun: fn(
self: *const IDWriteFactory2,
baselineOriginX: f32,
baselineOriginY: f32,
glyphRun: ?*const DWRITE_GLYPH_RUN,
glyphRunDescription: ?*const DWRITE_GLYPH_RUN_DESCRIPTION,
measuringMode: DWRITE_MEASURING_MODE,
worldToDeviceTransform: ?*const DWRITE_MATRIX,
colorPaletteIndex: u32,
colorLayers: ?*?*IDWriteColorGlyphRunEnumerator,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateCustomRenderingParams: fn(
self: *const IDWriteFactory2,
gamma: f32,
enhancedContrast: f32,
grayscaleEnhancedContrast: f32,
clearTypeLevel: f32,
pixelGeometry: DWRITE_PIXEL_GEOMETRY,
renderingMode: DWRITE_RENDERING_MODE,
gridFitMode: DWRITE_GRID_FIT_MODE,
renderingParams: ?*?*IDWriteRenderingParams2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateGlyphRunAnalysis: fn(
self: *const IDWriteFactory2,
glyphRun: ?*const DWRITE_GLYPH_RUN,
transform: ?*const DWRITE_MATRIX,
renderingMode: DWRITE_RENDERING_MODE,
measuringMode: DWRITE_MEASURING_MODE,
gridFitMode: DWRITE_GRID_FIT_MODE,
antialiasMode: DWRITE_TEXT_ANTIALIAS_MODE,
baselineOriginX: f32,
baselineOriginY: f32,
glyphRunAnalysis: ?*?*IDWriteGlyphRunAnalysis,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFactory1.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory2_GetSystemFontFallback(self: *const T, fontFallback: ?*?*IDWriteFontFallback) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory2.VTable, self.vtable).GetSystemFontFallback(@ptrCast(*const IDWriteFactory2, self), fontFallback);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory2_CreateFontFallbackBuilder(self: *const T, fontFallbackBuilder: ?*?*IDWriteFontFallbackBuilder) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory2.VTable, self.vtable).CreateFontFallbackBuilder(@ptrCast(*const IDWriteFactory2, self), fontFallbackBuilder);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory2_TranslateColorGlyphRun(self: *const T, baselineOriginX: f32, baselineOriginY: f32, glyphRun: ?*const DWRITE_GLYPH_RUN, glyphRunDescription: ?*const DWRITE_GLYPH_RUN_DESCRIPTION, measuringMode: DWRITE_MEASURING_MODE, worldToDeviceTransform: ?*const DWRITE_MATRIX, colorPaletteIndex: u32, colorLayers: ?*?*IDWriteColorGlyphRunEnumerator) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory2.VTable, self.vtable).TranslateColorGlyphRun(@ptrCast(*const IDWriteFactory2, self), baselineOriginX, baselineOriginY, glyphRun, glyphRunDescription, measuringMode, worldToDeviceTransform, colorPaletteIndex, colorLayers);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory2_CreateCustomRenderingParams(self: *const T, gamma: f32, enhancedContrast: f32, grayscaleEnhancedContrast: f32, clearTypeLevel: f32, pixelGeometry: DWRITE_PIXEL_GEOMETRY, renderingMode: DWRITE_RENDERING_MODE, gridFitMode: DWRITE_GRID_FIT_MODE, renderingParams: ?*?*IDWriteRenderingParams2) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory2.VTable, self.vtable).CreateCustomRenderingParams(@ptrCast(*const IDWriteFactory2, self), gamma, enhancedContrast, grayscaleEnhancedContrast, clearTypeLevel, pixelGeometry, renderingMode, gridFitMode, renderingParams);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory2_CreateGlyphRunAnalysis(self: *const T, glyphRun: ?*const DWRITE_GLYPH_RUN, transform: ?*const DWRITE_MATRIX, renderingMode: DWRITE_RENDERING_MODE, measuringMode: DWRITE_MEASURING_MODE, gridFitMode: DWRITE_GRID_FIT_MODE, antialiasMode: DWRITE_TEXT_ANTIALIAS_MODE, baselineOriginX: f32, baselineOriginY: f32, glyphRunAnalysis: ?*?*IDWriteGlyphRunAnalysis) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory2.VTable, self.vtable).CreateGlyphRunAnalysis(@ptrCast(*const IDWriteFactory2, self), glyphRun, transform, renderingMode, measuringMode, gridFitMode, antialiasMode, baselineOriginX, baselineOriginY, glyphRunAnalysis);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DWRITE_FONT_PROPERTY_ID = enum(i32) {
NONE = 0,
WEIGHT_STRETCH_STYLE_FAMILY_NAME = 1,
TYPOGRAPHIC_FAMILY_NAME = 2,
WEIGHT_STRETCH_STYLE_FACE_NAME = 3,
FULL_NAME = 4,
WIN32_FAMILY_NAME = 5,
POSTSCRIPT_NAME = 6,
DESIGN_SCRIPT_LANGUAGE_TAG = 7,
SUPPORTED_SCRIPT_LANGUAGE_TAG = 8,
SEMANTIC_TAG = 9,
WEIGHT = 10,
STRETCH = 11,
STYLE = 12,
TYPOGRAPHIC_FACE_NAME = 13,
// TOTAL = 13, this enum value conflicts with TYPOGRAPHIC_FACE_NAME
TOTAL_RS3 = 14,
// PREFERRED_FAMILY_NAME = 2, this enum value conflicts with TYPOGRAPHIC_FAMILY_NAME
// FAMILY_NAME = 1, this enum value conflicts with WEIGHT_STRETCH_STYLE_FAMILY_NAME
// FACE_NAME = 3, this enum value conflicts with WEIGHT_STRETCH_STYLE_FACE_NAME
};
pub const DWRITE_FONT_PROPERTY_ID_NONE = DWRITE_FONT_PROPERTY_ID.NONE;
pub const DWRITE_FONT_PROPERTY_ID_WEIGHT_STRETCH_STYLE_FAMILY_NAME = DWRITE_FONT_PROPERTY_ID.WEIGHT_STRETCH_STYLE_FAMILY_NAME;
pub const DWRITE_FONT_PROPERTY_ID_TYPOGRAPHIC_FAMILY_NAME = DWRITE_FONT_PROPERTY_ID.TYPOGRAPHIC_FAMILY_NAME;
pub const DWRITE_FONT_PROPERTY_ID_WEIGHT_STRETCH_STYLE_FACE_NAME = DWRITE_FONT_PROPERTY_ID.WEIGHT_STRETCH_STYLE_FACE_NAME;
pub const DWRITE_FONT_PROPERTY_ID_FULL_NAME = DWRITE_FONT_PROPERTY_ID.FULL_NAME;
pub const DWRITE_FONT_PROPERTY_ID_WIN32_FAMILY_NAME = DWRITE_FONT_PROPERTY_ID.WIN32_FAMILY_NAME;
pub const DWRITE_FONT_PROPERTY_ID_POSTSCRIPT_NAME = DWRITE_FONT_PROPERTY_ID.POSTSCRIPT_NAME;
pub const DWRITE_FONT_PROPERTY_ID_DESIGN_SCRIPT_LANGUAGE_TAG = DWRITE_FONT_PROPERTY_ID.DESIGN_SCRIPT_LANGUAGE_TAG;
pub const DWRITE_FONT_PROPERTY_ID_SUPPORTED_SCRIPT_LANGUAGE_TAG = DWRITE_FONT_PROPERTY_ID.SUPPORTED_SCRIPT_LANGUAGE_TAG;
pub const DWRITE_FONT_PROPERTY_ID_SEMANTIC_TAG = DWRITE_FONT_PROPERTY_ID.SEMANTIC_TAG;
pub const DWRITE_FONT_PROPERTY_ID_WEIGHT = DWRITE_FONT_PROPERTY_ID.WEIGHT;
pub const DWRITE_FONT_PROPERTY_ID_STRETCH = DWRITE_FONT_PROPERTY_ID.STRETCH;
pub const DWRITE_FONT_PROPERTY_ID_STYLE = DWRITE_FONT_PROPERTY_ID.STYLE;
pub const DWRITE_FONT_PROPERTY_ID_TYPOGRAPHIC_FACE_NAME = DWRITE_FONT_PROPERTY_ID.TYPOGRAPHIC_FACE_NAME;
pub const DWRITE_FONT_PROPERTY_ID_TOTAL = DWRITE_FONT_PROPERTY_ID.TYPOGRAPHIC_FACE_NAME;
pub const DWRITE_FONT_PROPERTY_ID_TOTAL_RS3 = DWRITE_FONT_PROPERTY_ID.TOTAL_RS3;
pub const DWRITE_FONT_PROPERTY_ID_PREFERRED_FAMILY_NAME = DWRITE_FONT_PROPERTY_ID.TYPOGRAPHIC_FAMILY_NAME;
pub const DWRITE_FONT_PROPERTY_ID_FAMILY_NAME = DWRITE_FONT_PROPERTY_ID.WEIGHT_STRETCH_STYLE_FAMILY_NAME;
pub const DWRITE_FONT_PROPERTY_ID_FACE_NAME = DWRITE_FONT_PROPERTY_ID.WEIGHT_STRETCH_STYLE_FACE_NAME;
pub const DWRITE_FONT_PROPERTY = extern struct {
propertyId: DWRITE_FONT_PROPERTY_ID,
propertyValue: ?[*:0]const u16,
localeName: ?[*:0]const u16,
};
pub const DWRITE_LOCALITY = enum(i32) {
REMOTE = 0,
PARTIAL = 1,
LOCAL = 2,
};
pub const DWRITE_LOCALITY_REMOTE = DWRITE_LOCALITY.REMOTE;
pub const DWRITE_LOCALITY_PARTIAL = DWRITE_LOCALITY.PARTIAL;
pub const DWRITE_LOCALITY_LOCAL = DWRITE_LOCALITY.LOCAL;
pub const DWRITE_RENDERING_MODE1 = enum(i32) {
DEFAULT = 0,
ALIASED = 1,
GDI_CLASSIC = 2,
GDI_NATURAL = 3,
NATURAL = 4,
NATURAL_SYMMETRIC = 5,
OUTLINE = 6,
NATURAL_SYMMETRIC_DOWNSAMPLED = 7,
};
pub const DWRITE_RENDERING_MODE1_DEFAULT = DWRITE_RENDERING_MODE1.DEFAULT;
pub const DWRITE_RENDERING_MODE1_ALIASED = DWRITE_RENDERING_MODE1.ALIASED;
pub const DWRITE_RENDERING_MODE1_GDI_CLASSIC = DWRITE_RENDERING_MODE1.GDI_CLASSIC;
pub const DWRITE_RENDERING_MODE1_GDI_NATURAL = DWRITE_RENDERING_MODE1.GDI_NATURAL;
pub const DWRITE_RENDERING_MODE1_NATURAL = DWRITE_RENDERING_MODE1.NATURAL;
pub const DWRITE_RENDERING_MODE1_NATURAL_SYMMETRIC = DWRITE_RENDERING_MODE1.NATURAL_SYMMETRIC;
pub const DWRITE_RENDERING_MODE1_OUTLINE = DWRITE_RENDERING_MODE1.OUTLINE;
pub const DWRITE_RENDERING_MODE1_NATURAL_SYMMETRIC_DOWNSAMPLED = DWRITE_RENDERING_MODE1.NATURAL_SYMMETRIC_DOWNSAMPLED;
// TODO: this type is limited to platform 'windows10.0.10240'
const IID_IDWriteRenderingParams3_Value = Guid.initString("b7924baa-391b-412a-8c5c-e44cc2d867dc");
pub const IID_IDWriteRenderingParams3 = &IID_IDWriteRenderingParams3_Value;
pub const IDWriteRenderingParams3 = extern struct {
pub const VTable = extern struct {
base: IDWriteRenderingParams2.VTable,
GetRenderingMode1: fn(
self: *const IDWriteRenderingParams3,
) callconv(@import("std").os.windows.WINAPI) DWRITE_RENDERING_MODE1,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteRenderingParams2.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteRenderingParams3_GetRenderingMode1(self: *const T) callconv(.Inline) DWRITE_RENDERING_MODE1 {
return @ptrCast(*const IDWriteRenderingParams3.VTable, self.vtable).GetRenderingMode1(@ptrCast(*const IDWriteRenderingParams3, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.10240'
const IID_IDWriteFactory3_Value = Guid.initString("9a1b41c3-d3bb-466a-87fc-fe67556a3b65");
pub const IID_IDWriteFactory3 = &IID_IDWriteFactory3_Value;
pub const IDWriteFactory3 = extern struct {
pub const VTable = extern struct {
base: IDWriteFactory2.VTable,
CreateGlyphRunAnalysis: fn(
self: *const IDWriteFactory3,
glyphRun: ?*const DWRITE_GLYPH_RUN,
transform: ?*const DWRITE_MATRIX,
renderingMode: DWRITE_RENDERING_MODE1,
measuringMode: DWRITE_MEASURING_MODE,
gridFitMode: DWRITE_GRID_FIT_MODE,
antialiasMode: DWRITE_TEXT_ANTIALIAS_MODE,
baselineOriginX: f32,
baselineOriginY: f32,
glyphRunAnalysis: ?*?*IDWriteGlyphRunAnalysis,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateCustomRenderingParams: fn(
self: *const IDWriteFactory3,
gamma: f32,
enhancedContrast: f32,
grayscaleEnhancedContrast: f32,
clearTypeLevel: f32,
pixelGeometry: DWRITE_PIXEL_GEOMETRY,
renderingMode: DWRITE_RENDERING_MODE1,
gridFitMode: DWRITE_GRID_FIT_MODE,
renderingParams: ?*?*IDWriteRenderingParams3,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateFontFaceReference: fn(
self: *const IDWriteFactory3,
fontFile: ?*IDWriteFontFile,
faceIndex: u32,
fontSimulations: DWRITE_FONT_SIMULATIONS,
fontFaceReference: ?*?*IDWriteFontFaceReference,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateFontFaceReference1: fn(
self: *const IDWriteFactory3,
filePath: ?[*:0]const u16,
lastWriteTime: ?*const FILETIME,
faceIndex: u32,
fontSimulations: DWRITE_FONT_SIMULATIONS,
fontFaceReference: ?*?*IDWriteFontFaceReference,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSystemFontSet: fn(
self: *const IDWriteFactory3,
fontSet: ?*?*IDWriteFontSet,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateFontSetBuilder: fn(
self: *const IDWriteFactory3,
fontSetBuilder: ?*?*IDWriteFontSetBuilder,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateFontCollectionFromFontSet: fn(
self: *const IDWriteFactory3,
fontSet: ?*IDWriteFontSet,
fontCollection: ?*?*IDWriteFontCollection1,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSystemFontCollection: fn(
self: *const IDWriteFactory3,
includeDownloadableFonts: BOOL,
fontCollection: ?*?*IDWriteFontCollection1,
checkForUpdates: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontDownloadQueue: fn(
self: *const IDWriteFactory3,
fontDownloadQueue: ?*?*IDWriteFontDownloadQueue,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFactory2.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory3_CreateGlyphRunAnalysis(self: *const T, glyphRun: ?*const DWRITE_GLYPH_RUN, transform: ?*const DWRITE_MATRIX, renderingMode: DWRITE_RENDERING_MODE1, measuringMode: DWRITE_MEASURING_MODE, gridFitMode: DWRITE_GRID_FIT_MODE, antialiasMode: DWRITE_TEXT_ANTIALIAS_MODE, baselineOriginX: f32, baselineOriginY: f32, glyphRunAnalysis: ?*?*IDWriteGlyphRunAnalysis) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory3.VTable, self.vtable).CreateGlyphRunAnalysis(@ptrCast(*const IDWriteFactory3, self), glyphRun, transform, renderingMode, measuringMode, gridFitMode, antialiasMode, baselineOriginX, baselineOriginY, glyphRunAnalysis);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory3_CreateCustomRenderingParams(self: *const T, gamma: f32, enhancedContrast: f32, grayscaleEnhancedContrast: f32, clearTypeLevel: f32, pixelGeometry: DWRITE_PIXEL_GEOMETRY, renderingMode: DWRITE_RENDERING_MODE1, gridFitMode: DWRITE_GRID_FIT_MODE, renderingParams: ?*?*IDWriteRenderingParams3) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory3.VTable, self.vtable).CreateCustomRenderingParams(@ptrCast(*const IDWriteFactory3, self), gamma, enhancedContrast, grayscaleEnhancedContrast, clearTypeLevel, pixelGeometry, renderingMode, gridFitMode, renderingParams);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory3_CreateFontFaceReference(self: *const T, fontFile: ?*IDWriteFontFile, faceIndex: u32, fontSimulations: DWRITE_FONT_SIMULATIONS, fontFaceReference: ?*?*IDWriteFontFaceReference) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory3.VTable, self.vtable).CreateFontFaceReference(@ptrCast(*const IDWriteFactory3, self), fontFile, faceIndex, fontSimulations, fontFaceReference);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory3_CreateFontFaceReference1(self: *const T, filePath: ?[*:0]const u16, lastWriteTime: ?*const FILETIME, faceIndex: u32, fontSimulations: DWRITE_FONT_SIMULATIONS, fontFaceReference: ?*?*IDWriteFontFaceReference) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory3.VTable, self.vtable).CreateFontFaceReference(@ptrCast(*const IDWriteFactory3, self), filePath, lastWriteTime, faceIndex, fontSimulations, fontFaceReference);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory3_GetSystemFontSet(self: *const T, fontSet: ?*?*IDWriteFontSet) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory3.VTable, self.vtable).GetSystemFontSet(@ptrCast(*const IDWriteFactory3, self), fontSet);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory3_CreateFontSetBuilder(self: *const T, fontSetBuilder: ?*?*IDWriteFontSetBuilder) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory3.VTable, self.vtable).CreateFontSetBuilder(@ptrCast(*const IDWriteFactory3, self), fontSetBuilder);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory3_CreateFontCollectionFromFontSet(self: *const T, fontSet: ?*IDWriteFontSet, fontCollection: ?*?*IDWriteFontCollection1) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory3.VTable, self.vtable).CreateFontCollectionFromFontSet(@ptrCast(*const IDWriteFactory3, self), fontSet, fontCollection);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory3_GetSystemFontCollection(self: *const T, includeDownloadableFonts: BOOL, fontCollection: ?*?*IDWriteFontCollection1, checkForUpdates: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory3.VTable, self.vtable).GetSystemFontCollection(@ptrCast(*const IDWriteFactory3, self), includeDownloadableFonts, fontCollection, checkForUpdates);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory3_GetFontDownloadQueue(self: *const T, fontDownloadQueue: ?*?*IDWriteFontDownloadQueue) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory3.VTable, self.vtable).GetFontDownloadQueue(@ptrCast(*const IDWriteFactory3, self), fontDownloadQueue);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.10240'
const IID_IDWriteFontSet_Value = Guid.initString("53585141-d9f8-4095-8321-d73cf6bd116b");
pub const IID_IDWriteFontSet = &IID_IDWriteFontSet_Value;
pub const IDWriteFontSet = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetFontCount: fn(
self: *const IDWriteFontSet,
) callconv(@import("std").os.windows.WINAPI) u32,
GetFontFaceReference: fn(
self: *const IDWriteFontSet,
listIndex: u32,
fontFaceReference: ?*?*IDWriteFontFaceReference,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FindFontFaceReference: fn(
self: *const IDWriteFontSet,
fontFaceReference: ?*IDWriteFontFaceReference,
listIndex: ?*u32,
exists: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FindFontFace: fn(
self: *const IDWriteFontSet,
fontFace: ?*IDWriteFontFace,
listIndex: ?*u32,
exists: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPropertyValues: fn(
self: *const IDWriteFontSet,
propertyID: DWRITE_FONT_PROPERTY_ID,
values: ?*?*IDWriteStringList,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPropertyValues1: fn(
self: *const IDWriteFontSet,
propertyID: DWRITE_FONT_PROPERTY_ID,
preferredLocaleNames: ?[*:0]const u16,
values: ?*?*IDWriteStringList,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPropertyValues2: fn(
self: *const IDWriteFontSet,
listIndex: u32,
propertyId: DWRITE_FONT_PROPERTY_ID,
exists: ?*BOOL,
values: ?*?*IDWriteLocalizedStrings,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPropertyOccurrenceCount: fn(
self: *const IDWriteFontSet,
property: ?*const DWRITE_FONT_PROPERTY,
propertyOccurrenceCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetMatchingFonts: fn(
self: *const IDWriteFontSet,
familyName: ?[*:0]const u16,
fontWeight: DWRITE_FONT_WEIGHT,
fontStretch: DWRITE_FONT_STRETCH,
fontStyle: DWRITE_FONT_STYLE,
filteredSet: ?*?*IDWriteFontSet,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetMatchingFonts1: fn(
self: *const IDWriteFontSet,
properties: [*]const DWRITE_FONT_PROPERTY,
propertyCount: u32,
filteredSet: ?*?*IDWriteFontSet,
) 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 IDWriteFontSet_GetFontCount(self: *const T) callconv(.Inline) u32 {
return @ptrCast(*const IDWriteFontSet.VTable, self.vtable).GetFontCount(@ptrCast(*const IDWriteFontSet, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSet_GetFontFaceReference(self: *const T, listIndex: u32, fontFaceReference: ?*?*IDWriteFontFaceReference) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontSet.VTable, self.vtable).GetFontFaceReference(@ptrCast(*const IDWriteFontSet, self), listIndex, fontFaceReference);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSet_FindFontFaceReference(self: *const T, fontFaceReference: ?*IDWriteFontFaceReference, listIndex: ?*u32, exists: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontSet.VTable, self.vtable).FindFontFaceReference(@ptrCast(*const IDWriteFontSet, self), fontFaceReference, listIndex, exists);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSet_FindFontFace(self: *const T, fontFace: ?*IDWriteFontFace, listIndex: ?*u32, exists: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontSet.VTable, self.vtable).FindFontFace(@ptrCast(*const IDWriteFontSet, self), fontFace, listIndex, exists);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSet_GetPropertyValues(self: *const T, propertyID: DWRITE_FONT_PROPERTY_ID, values: ?*?*IDWriteStringList) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontSet.VTable, self.vtable).GetPropertyValues(@ptrCast(*const IDWriteFontSet, self), propertyID, values);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSet_GetPropertyValues1(self: *const T, propertyID: DWRITE_FONT_PROPERTY_ID, preferredLocaleNames: ?[*:0]const u16, values: ?*?*IDWriteStringList) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontSet.VTable, self.vtable).GetPropertyValues(@ptrCast(*const IDWriteFontSet, self), propertyID, preferredLocaleNames, values);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSet_GetPropertyValues2(self: *const T, listIndex: u32, propertyId: DWRITE_FONT_PROPERTY_ID, exists: ?*BOOL, values: ?*?*IDWriteLocalizedStrings) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontSet.VTable, self.vtable).GetPropertyValues(@ptrCast(*const IDWriteFontSet, self), listIndex, propertyId, exists, values);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSet_GetPropertyOccurrenceCount(self: *const T, property: ?*const DWRITE_FONT_PROPERTY, propertyOccurrenceCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontSet.VTable, self.vtable).GetPropertyOccurrenceCount(@ptrCast(*const IDWriteFontSet, self), property, propertyOccurrenceCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSet_GetMatchingFonts(self: *const T, familyName: ?[*:0]const u16, fontWeight: DWRITE_FONT_WEIGHT, fontStretch: DWRITE_FONT_STRETCH, fontStyle: DWRITE_FONT_STYLE, filteredSet: ?*?*IDWriteFontSet) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontSet.VTable, self.vtable).GetMatchingFonts(@ptrCast(*const IDWriteFontSet, self), familyName, fontWeight, fontStretch, fontStyle, filteredSet);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSet_GetMatchingFonts1(self: *const T, properties: [*]const DWRITE_FONT_PROPERTY, propertyCount: u32, filteredSet: ?*?*IDWriteFontSet) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontSet.VTable, self.vtable).GetMatchingFonts(@ptrCast(*const IDWriteFontSet, self), properties, propertyCount, filteredSet);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDWriteFontSetBuilder_Value = Guid.initString("2f642afe-9c68-4f40-b8be-457401afcb3d");
pub const IID_IDWriteFontSetBuilder = &IID_IDWriteFontSetBuilder_Value;
pub const IDWriteFontSetBuilder = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
AddFontFaceReference: fn(
self: *const IDWriteFontSetBuilder,
fontFaceReference: ?*IDWriteFontFaceReference,
properties: [*]const DWRITE_FONT_PROPERTY,
propertyCount: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddFontFaceReference1: fn(
self: *const IDWriteFontSetBuilder,
fontFaceReference: ?*IDWriteFontFaceReference,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddFontSet: fn(
self: *const IDWriteFontSetBuilder,
fontSet: ?*IDWriteFontSet,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateFontSet: fn(
self: *const IDWriteFontSetBuilder,
fontSet: ?*?*IDWriteFontSet,
) 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 IDWriteFontSetBuilder_AddFontFaceReference(self: *const T, fontFaceReference: ?*IDWriteFontFaceReference, properties: [*]const DWRITE_FONT_PROPERTY, propertyCount: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontSetBuilder.VTable, self.vtable).AddFontFaceReference(@ptrCast(*const IDWriteFontSetBuilder, self), fontFaceReference, properties, propertyCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSetBuilder_AddFontFaceReference1(self: *const T, fontFaceReference: ?*IDWriteFontFaceReference) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontSetBuilder.VTable, self.vtable).AddFontFaceReference(@ptrCast(*const IDWriteFontSetBuilder, self), fontFaceReference);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSetBuilder_AddFontSet(self: *const T, fontSet: ?*IDWriteFontSet) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontSetBuilder.VTable, self.vtable).AddFontSet(@ptrCast(*const IDWriteFontSetBuilder, self), fontSet);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSetBuilder_CreateFontSet(self: *const T, fontSet: ?*?*IDWriteFontSet) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontSetBuilder.VTable, self.vtable).CreateFontSet(@ptrCast(*const IDWriteFontSetBuilder, self), fontSet);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IDWriteFontCollection1_Value = Guid.initString("53585141-d9f8-4095-8321-d73cf6bd116c");
pub const IID_IDWriteFontCollection1 = &IID_IDWriteFontCollection1_Value;
pub const IDWriteFontCollection1 = extern struct {
pub const VTable = extern struct {
base: IDWriteFontCollection.VTable,
GetFontSet: fn(
self: *const IDWriteFontCollection1,
fontSet: ?*?*IDWriteFontSet,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontFamily: fn(
self: *const IDWriteFontCollection1,
index: u32,
fontFamily: ?*?*IDWriteFontFamily1,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFontCollection.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontCollection1_GetFontSet(self: *const T, fontSet: ?*?*IDWriteFontSet) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontCollection1.VTable, self.vtable).GetFontSet(@ptrCast(*const IDWriteFontCollection1, self), fontSet);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontCollection1_GetFontFamily(self: *const T, index: u32, fontFamily: ?*?*IDWriteFontFamily1) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontCollection1.VTable, self.vtable).GetFontFamily(@ptrCast(*const IDWriteFontCollection1, self), index, fontFamily);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.10240'
const IID_IDWriteFontFamily1_Value = Guid.initString("da20d8ef-812a-4c43-9802-62ec4abd7adf");
pub const IID_IDWriteFontFamily1 = &IID_IDWriteFontFamily1_Value;
pub const IDWriteFontFamily1 = extern struct {
pub const VTable = extern struct {
base: IDWriteFontFamily.VTable,
GetFontLocality: fn(
self: *const IDWriteFontFamily1,
listIndex: u32,
) callconv(@import("std").os.windows.WINAPI) DWRITE_LOCALITY,
GetFont: fn(
self: *const IDWriteFontFamily1,
listIndex: u32,
font: ?*?*IDWriteFont3,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontFaceReference: fn(
self: *const IDWriteFontFamily1,
listIndex: u32,
fontFaceReference: ?*?*IDWriteFontFaceReference,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFontFamily.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFamily1_GetFontLocality(self: *const T, listIndex: u32) callconv(.Inline) DWRITE_LOCALITY {
return @ptrCast(*const IDWriteFontFamily1.VTable, self.vtable).GetFontLocality(@ptrCast(*const IDWriteFontFamily1, self), listIndex);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFamily1_GetFont(self: *const T, listIndex: u32, font: ?*?*IDWriteFont3) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFamily1.VTable, self.vtable).GetFont(@ptrCast(*const IDWriteFontFamily1, self), listIndex, font);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFamily1_GetFontFaceReference(self: *const T, listIndex: u32, fontFaceReference: ?*?*IDWriteFontFaceReference) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFamily1.VTable, self.vtable).GetFontFaceReference(@ptrCast(*const IDWriteFontFamily1, self), listIndex, fontFaceReference);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.10240'
const IID_IDWriteFontList1_Value = Guid.initString("da20d8ef-812a-4c43-9802-62ec4abd7ade");
pub const IID_IDWriteFontList1 = &IID_IDWriteFontList1_Value;
pub const IDWriteFontList1 = extern struct {
pub const VTable = extern struct {
base: IDWriteFontList.VTable,
GetFontLocality: fn(
self: *const IDWriteFontList1,
listIndex: u32,
) callconv(@import("std").os.windows.WINAPI) DWRITE_LOCALITY,
GetFont: fn(
self: *const IDWriteFontList1,
listIndex: u32,
font: ?*?*IDWriteFont3,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontFaceReference: fn(
self: *const IDWriteFontList1,
listIndex: u32,
fontFaceReference: ?*?*IDWriteFontFaceReference,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFontList.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontList1_GetFontLocality(self: *const T, listIndex: u32) callconv(.Inline) DWRITE_LOCALITY {
return @ptrCast(*const IDWriteFontList1.VTable, self.vtable).GetFontLocality(@ptrCast(*const IDWriteFontList1, self), listIndex);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontList1_GetFont(self: *const T, listIndex: u32, font: ?*?*IDWriteFont3) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontList1.VTable, self.vtable).GetFont(@ptrCast(*const IDWriteFontList1, self), listIndex, font);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontList1_GetFontFaceReference(self: *const T, listIndex: u32, fontFaceReference: ?*?*IDWriteFontFaceReference) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontList1.VTable, self.vtable).GetFontFaceReference(@ptrCast(*const IDWriteFontList1, self), listIndex, fontFaceReference);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.10240'
const IID_IDWriteFontFaceReference_Value = Guid.initString("5e7fa7ca-dde3-424c-89f0-9fcd6fed58cd");
pub const IID_IDWriteFontFaceReference = &IID_IDWriteFontFaceReference_Value;
pub const IDWriteFontFaceReference = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
CreateFontFace: fn(
self: *const IDWriteFontFaceReference,
fontFace: ?*?*IDWriteFontFace3,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateFontFaceWithSimulations: fn(
self: *const IDWriteFontFaceReference,
fontFaceSimulationFlags: DWRITE_FONT_SIMULATIONS,
fontFace: ?*?*IDWriteFontFace3,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Equals: fn(
self: *const IDWriteFontFaceReference,
fontFaceReference: ?*IDWriteFontFaceReference,
) callconv(@import("std").os.windows.WINAPI) BOOL,
GetFontFaceIndex: fn(
self: *const IDWriteFontFaceReference,
) callconv(@import("std").os.windows.WINAPI) u32,
GetSimulations: fn(
self: *const IDWriteFontFaceReference,
) callconv(@import("std").os.windows.WINAPI) DWRITE_FONT_SIMULATIONS,
GetFontFile: fn(
self: *const IDWriteFontFaceReference,
fontFile: ?*?*IDWriteFontFile,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLocalFileSize: fn(
self: *const IDWriteFontFaceReference,
) callconv(@import("std").os.windows.WINAPI) u64,
GetFileSize: fn(
self: *const IDWriteFontFaceReference,
) callconv(@import("std").os.windows.WINAPI) u64,
GetFileTime: fn(
self: *const IDWriteFontFaceReference,
lastWriteTime: ?*FILETIME,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLocality: fn(
self: *const IDWriteFontFaceReference,
) callconv(@import("std").os.windows.WINAPI) DWRITE_LOCALITY,
EnqueueFontDownloadRequest: fn(
self: *const IDWriteFontFaceReference,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EnqueueCharacterDownloadRequest: fn(
self: *const IDWriteFontFaceReference,
characters: [*:0]const u16,
characterCount: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EnqueueGlyphDownloadRequest: fn(
self: *const IDWriteFontFaceReference,
glyphIndices: [*:0]const u16,
glyphCount: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EnqueueFileFragmentDownloadRequest: fn(
self: *const IDWriteFontFaceReference,
fileOffset: u64,
fragmentSize: u64,
) 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 IDWriteFontFaceReference_CreateFontFace(self: *const T, fontFace: ?*?*IDWriteFontFace3) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFaceReference.VTable, self.vtable).CreateFontFace(@ptrCast(*const IDWriteFontFaceReference, self), fontFace);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFaceReference_CreateFontFaceWithSimulations(self: *const T, fontFaceSimulationFlags: DWRITE_FONT_SIMULATIONS, fontFace: ?*?*IDWriteFontFace3) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFaceReference.VTable, self.vtable).CreateFontFaceWithSimulations(@ptrCast(*const IDWriteFontFaceReference, self), fontFaceSimulationFlags, fontFace);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFaceReference_Equals(self: *const T, fontFaceReference: ?*IDWriteFontFaceReference) callconv(.Inline) BOOL {
return @ptrCast(*const IDWriteFontFaceReference.VTable, self.vtable).Equals(@ptrCast(*const IDWriteFontFaceReference, self), fontFaceReference);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFaceReference_GetFontFaceIndex(self: *const T) callconv(.Inline) u32 {
return @ptrCast(*const IDWriteFontFaceReference.VTable, self.vtable).GetFontFaceIndex(@ptrCast(*const IDWriteFontFaceReference, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFaceReference_GetSimulations(self: *const T) callconv(.Inline) DWRITE_FONT_SIMULATIONS {
return @ptrCast(*const IDWriteFontFaceReference.VTable, self.vtable).GetSimulations(@ptrCast(*const IDWriteFontFaceReference, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFaceReference_GetFontFile(self: *const T, fontFile: ?*?*IDWriteFontFile) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFaceReference.VTable, self.vtable).GetFontFile(@ptrCast(*const IDWriteFontFaceReference, self), fontFile);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFaceReference_GetLocalFileSize(self: *const T) callconv(.Inline) u64 {
return @ptrCast(*const IDWriteFontFaceReference.VTable, self.vtable).GetLocalFileSize(@ptrCast(*const IDWriteFontFaceReference, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFaceReference_GetFileSize(self: *const T) callconv(.Inline) u64 {
return @ptrCast(*const IDWriteFontFaceReference.VTable, self.vtable).GetFileSize(@ptrCast(*const IDWriteFontFaceReference, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFaceReference_GetFileTime(self: *const T, lastWriteTime: ?*FILETIME) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFaceReference.VTable, self.vtable).GetFileTime(@ptrCast(*const IDWriteFontFaceReference, self), lastWriteTime);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFaceReference_GetLocality(self: *const T) callconv(.Inline) DWRITE_LOCALITY {
return @ptrCast(*const IDWriteFontFaceReference.VTable, self.vtable).GetLocality(@ptrCast(*const IDWriteFontFaceReference, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFaceReference_EnqueueFontDownloadRequest(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFaceReference.VTable, self.vtable).EnqueueFontDownloadRequest(@ptrCast(*const IDWriteFontFaceReference, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFaceReference_EnqueueCharacterDownloadRequest(self: *const T, characters: [*:0]const u16, characterCount: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFaceReference.VTable, self.vtable).EnqueueCharacterDownloadRequest(@ptrCast(*const IDWriteFontFaceReference, self), characters, characterCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFaceReference_EnqueueGlyphDownloadRequest(self: *const T, glyphIndices: [*:0]const u16, glyphCount: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFaceReference.VTable, self.vtable).EnqueueGlyphDownloadRequest(@ptrCast(*const IDWriteFontFaceReference, self), glyphIndices, glyphCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFaceReference_EnqueueFileFragmentDownloadRequest(self: *const T, fileOffset: u64, fragmentSize: u64) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFaceReference.VTable, self.vtable).EnqueueFileFragmentDownloadRequest(@ptrCast(*const IDWriteFontFaceReference, self), fileOffset, fragmentSize);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.10240'
const IID_IDWriteFont3_Value = Guid.initString("29748ed6-8c9c-4a6a-be0b-d912e8538944");
pub const IID_IDWriteFont3 = &IID_IDWriteFont3_Value;
pub const IDWriteFont3 = extern struct {
pub const VTable = extern struct {
base: IDWriteFont2.VTable,
CreateFontFace: fn(
self: *const IDWriteFont3,
fontFace: ?*?*IDWriteFontFace3,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Equals: fn(
self: *const IDWriteFont3,
font: ?*IDWriteFont,
) callconv(@import("std").os.windows.WINAPI) BOOL,
GetFontFaceReference: fn(
self: *const IDWriteFont3,
fontFaceReference: ?*?*IDWriteFontFaceReference,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
HasCharacter: fn(
self: *const IDWriteFont3,
unicodeValue: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL,
GetLocality: fn(
self: *const IDWriteFont3,
) callconv(@import("std").os.windows.WINAPI) DWRITE_LOCALITY,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFont2.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFont3_CreateFontFace(self: *const T, fontFace: ?*?*IDWriteFontFace3) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFont3.VTable, self.vtable).CreateFontFace(@ptrCast(*const IDWriteFont3, self), fontFace);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFont3_Equals(self: *const T, font: ?*IDWriteFont) callconv(.Inline) BOOL {
return @ptrCast(*const IDWriteFont3.VTable, self.vtable).Equals(@ptrCast(*const IDWriteFont3, self), font);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFont3_GetFontFaceReference(self: *const T, fontFaceReference: ?*?*IDWriteFontFaceReference) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFont3.VTable, self.vtable).GetFontFaceReference(@ptrCast(*const IDWriteFont3, self), fontFaceReference);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFont3_HasCharacter(self: *const T, unicodeValue: u32) callconv(.Inline) BOOL {
return @ptrCast(*const IDWriteFont3.VTable, self.vtable).HasCharacter(@ptrCast(*const IDWriteFont3, self), unicodeValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFont3_GetLocality(self: *const T) callconv(.Inline) DWRITE_LOCALITY {
return @ptrCast(*const IDWriteFont3.VTable, self.vtable).GetLocality(@ptrCast(*const IDWriteFont3, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.10240'
const IID_IDWriteFontFace3_Value = Guid.initString("d37d7598-09be-4222-a236-2081341cc1f2");
pub const IID_IDWriteFontFace3 = &IID_IDWriteFontFace3_Value;
pub const IDWriteFontFace3 = extern struct {
pub const VTable = extern struct {
base: IDWriteFontFace2.VTable,
GetFontFaceReference: fn(
self: *const IDWriteFontFace3,
fontFaceReference: ?*?*IDWriteFontFaceReference,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPanose: fn(
self: *const IDWriteFontFace3,
panose: ?*DWRITE_PANOSE,
) callconv(@import("std").os.windows.WINAPI) void,
GetWeight: fn(
self: *const IDWriteFontFace3,
) callconv(@import("std").os.windows.WINAPI) DWRITE_FONT_WEIGHT,
GetStretch: fn(
self: *const IDWriteFontFace3,
) callconv(@import("std").os.windows.WINAPI) DWRITE_FONT_STRETCH,
GetStyle: fn(
self: *const IDWriteFontFace3,
) callconv(@import("std").os.windows.WINAPI) DWRITE_FONT_STYLE,
GetFamilyNames: fn(
self: *const IDWriteFontFace3,
names: ?*?*IDWriteLocalizedStrings,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFaceNames: fn(
self: *const IDWriteFontFace3,
names: ?*?*IDWriteLocalizedStrings,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetInformationalStrings: fn(
self: *const IDWriteFontFace3,
informationalStringID: DWRITE_INFORMATIONAL_STRING_ID,
informationalStrings: ?*?*IDWriteLocalizedStrings,
exists: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
HasCharacter: fn(
self: *const IDWriteFontFace3,
unicodeValue: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL,
GetRecommendedRenderingMode: fn(
self: *const IDWriteFontFace3,
fontEmSize: f32,
dpiX: f32,
dpiY: f32,
transform: ?*const DWRITE_MATRIX,
isSideways: BOOL,
outlineThreshold: DWRITE_OUTLINE_THRESHOLD,
measuringMode: DWRITE_MEASURING_MODE,
renderingParams: ?*IDWriteRenderingParams,
renderingMode: ?*DWRITE_RENDERING_MODE1,
gridFitMode: ?*DWRITE_GRID_FIT_MODE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsCharacterLocal: fn(
self: *const IDWriteFontFace3,
unicodeValue: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL,
IsGlyphLocal: fn(
self: *const IDWriteFontFace3,
glyphId: u16,
) callconv(@import("std").os.windows.WINAPI) BOOL,
AreCharactersLocal: fn(
self: *const IDWriteFontFace3,
characters: [*:0]const u16,
characterCount: u32,
enqueueIfNotLocal: BOOL,
isLocal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AreGlyphsLocal: fn(
self: *const IDWriteFontFace3,
glyphIndices: [*:0]const u16,
glyphCount: u32,
enqueueIfNotLocal: BOOL,
isLocal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFontFace2.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace3_GetFontFaceReference(self: *const T, fontFaceReference: ?*?*IDWriteFontFaceReference) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFace3.VTable, self.vtable).GetFontFaceReference(@ptrCast(*const IDWriteFontFace3, self), fontFaceReference);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace3_GetPanose(self: *const T, panose: ?*DWRITE_PANOSE) callconv(.Inline) void {
return @ptrCast(*const IDWriteFontFace3.VTable, self.vtable).GetPanose(@ptrCast(*const IDWriteFontFace3, self), panose);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace3_GetWeight(self: *const T) callconv(.Inline) DWRITE_FONT_WEIGHT {
return @ptrCast(*const IDWriteFontFace3.VTable, self.vtable).GetWeight(@ptrCast(*const IDWriteFontFace3, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace3_GetStretch(self: *const T) callconv(.Inline) DWRITE_FONT_STRETCH {
return @ptrCast(*const IDWriteFontFace3.VTable, self.vtable).GetStretch(@ptrCast(*const IDWriteFontFace3, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace3_GetStyle(self: *const T) callconv(.Inline) DWRITE_FONT_STYLE {
return @ptrCast(*const IDWriteFontFace3.VTable, self.vtable).GetStyle(@ptrCast(*const IDWriteFontFace3, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace3_GetFamilyNames(self: *const T, names: ?*?*IDWriteLocalizedStrings) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFace3.VTable, self.vtable).GetFamilyNames(@ptrCast(*const IDWriteFontFace3, self), names);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace3_GetFaceNames(self: *const T, names: ?*?*IDWriteLocalizedStrings) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFace3.VTable, self.vtable).GetFaceNames(@ptrCast(*const IDWriteFontFace3, self), names);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace3_GetInformationalStrings(self: *const T, informationalStringID: DWRITE_INFORMATIONAL_STRING_ID, informationalStrings: ?*?*IDWriteLocalizedStrings, exists: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFace3.VTable, self.vtable).GetInformationalStrings(@ptrCast(*const IDWriteFontFace3, self), informationalStringID, informationalStrings, exists);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace3_HasCharacter(self: *const T, unicodeValue: u32) callconv(.Inline) BOOL {
return @ptrCast(*const IDWriteFontFace3.VTable, self.vtable).HasCharacter(@ptrCast(*const IDWriteFontFace3, self), unicodeValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace3_GetRecommendedRenderingMode(self: *const T, fontEmSize: f32, dpiX: f32, dpiY: f32, transform: ?*const DWRITE_MATRIX, isSideways: BOOL, outlineThreshold: DWRITE_OUTLINE_THRESHOLD, measuringMode: DWRITE_MEASURING_MODE, renderingParams: ?*IDWriteRenderingParams, renderingMode: ?*DWRITE_RENDERING_MODE1, gridFitMode: ?*DWRITE_GRID_FIT_MODE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFace3.VTable, self.vtable).GetRecommendedRenderingMode(@ptrCast(*const IDWriteFontFace3, self), fontEmSize, dpiX, dpiY, transform, isSideways, outlineThreshold, measuringMode, renderingParams, renderingMode, gridFitMode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace3_IsCharacterLocal(self: *const T, unicodeValue: u32) callconv(.Inline) BOOL {
return @ptrCast(*const IDWriteFontFace3.VTable, self.vtable).IsCharacterLocal(@ptrCast(*const IDWriteFontFace3, self), unicodeValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace3_IsGlyphLocal(self: *const T, glyphId: u16) callconv(.Inline) BOOL {
return @ptrCast(*const IDWriteFontFace3.VTable, self.vtable).IsGlyphLocal(@ptrCast(*const IDWriteFontFace3, self), glyphId);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace3_AreCharactersLocal(self: *const T, characters: [*:0]const u16, characterCount: u32, enqueueIfNotLocal: BOOL, isLocal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFace3.VTable, self.vtable).AreCharactersLocal(@ptrCast(*const IDWriteFontFace3, self), characters, characterCount, enqueueIfNotLocal, isLocal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace3_AreGlyphsLocal(self: *const T, glyphIndices: [*:0]const u16, glyphCount: u32, enqueueIfNotLocal: BOOL, isLocal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFace3.VTable, self.vtable).AreGlyphsLocal(@ptrCast(*const IDWriteFontFace3, self), glyphIndices, glyphCount, enqueueIfNotLocal, isLocal);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDWriteStringList_Value = Guid.initString("cfee3140-1157-47ca-8b85-31bfcf3f2d0e");
pub const IID_IDWriteStringList = &IID_IDWriteStringList_Value;
pub const IDWriteStringList = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetCount: fn(
self: *const IDWriteStringList,
) callconv(@import("std").os.windows.WINAPI) u32,
GetLocaleNameLength: fn(
self: *const IDWriteStringList,
listIndex: u32,
length: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLocaleName: fn(
self: *const IDWriteStringList,
listIndex: u32,
localeName: [*:0]u16,
size: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetStringLength: fn(
self: *const IDWriteStringList,
listIndex: u32,
length: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetString: fn(
self: *const IDWriteStringList,
listIndex: u32,
stringBuffer: [*:0]u16,
stringBufferSize: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteStringList_GetCount(self: *const T) callconv(.Inline) u32 {
return @ptrCast(*const IDWriteStringList.VTable, self.vtable).GetCount(@ptrCast(*const IDWriteStringList, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteStringList_GetLocaleNameLength(self: *const T, listIndex: u32, length: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteStringList.VTable, self.vtable).GetLocaleNameLength(@ptrCast(*const IDWriteStringList, self), listIndex, length);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteStringList_GetLocaleName(self: *const T, listIndex: u32, localeName: [*:0]u16, size: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteStringList.VTable, self.vtable).GetLocaleName(@ptrCast(*const IDWriteStringList, self), listIndex, localeName, size);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteStringList_GetStringLength(self: *const T, listIndex: u32, length: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteStringList.VTable, self.vtable).GetStringLength(@ptrCast(*const IDWriteStringList, self), listIndex, length);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteStringList_GetString(self: *const T, listIndex: u32, stringBuffer: [*:0]u16, stringBufferSize: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteStringList.VTable, self.vtable).GetString(@ptrCast(*const IDWriteStringList, self), listIndex, stringBuffer, stringBufferSize);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.1'
const IID_IDWriteFontDownloadListener_Value = Guid.initString("b06fe5b9-43ec-4393-881b-dbe4dc72fda7");
pub const IID_IDWriteFontDownloadListener = &IID_IDWriteFontDownloadListener_Value;
pub const IDWriteFontDownloadListener = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
DownloadCompleted: fn(
self: *const IDWriteFontDownloadListener,
downloadQueue: ?*IDWriteFontDownloadQueue,
context: ?*IUnknown,
downloadResult: HRESULT,
) 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 IDWriteFontDownloadListener_DownloadCompleted(self: *const T, downloadQueue: ?*IDWriteFontDownloadQueue, context: ?*IUnknown, downloadResult: HRESULT) callconv(.Inline) void {
return @ptrCast(*const IDWriteFontDownloadListener.VTable, self.vtable).DownloadCompleted(@ptrCast(*const IDWriteFontDownloadListener, self), downloadQueue, context, downloadResult);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.1'
const IID_IDWriteFontDownloadQueue_Value = Guid.initString("b71e6052-5aea-4fa3-832e-f60d431f7e91");
pub const IID_IDWriteFontDownloadQueue = &IID_IDWriteFontDownloadQueue_Value;
pub const IDWriteFontDownloadQueue = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
AddListener: fn(
self: *const IDWriteFontDownloadQueue,
listener: ?*IDWriteFontDownloadListener,
token: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveListener: fn(
self: *const IDWriteFontDownloadQueue,
token: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsEmpty: fn(
self: *const IDWriteFontDownloadQueue,
) callconv(@import("std").os.windows.WINAPI) BOOL,
BeginDownload: fn(
self: *const IDWriteFontDownloadQueue,
context: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CancelDownload: fn(
self: *const IDWriteFontDownloadQueue,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetGenerationCount: fn(
self: *const IDWriteFontDownloadQueue,
) callconv(@import("std").os.windows.WINAPI) u64,
};
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 IDWriteFontDownloadQueue_AddListener(self: *const T, listener: ?*IDWriteFontDownloadListener, token: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontDownloadQueue.VTable, self.vtable).AddListener(@ptrCast(*const IDWriteFontDownloadQueue, self), listener, token);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontDownloadQueue_RemoveListener(self: *const T, token: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontDownloadQueue.VTable, self.vtable).RemoveListener(@ptrCast(*const IDWriteFontDownloadQueue, self), token);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontDownloadQueue_IsEmpty(self: *const T) callconv(.Inline) BOOL {
return @ptrCast(*const IDWriteFontDownloadQueue.VTable, self.vtable).IsEmpty(@ptrCast(*const IDWriteFontDownloadQueue, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontDownloadQueue_BeginDownload(self: *const T, context: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontDownloadQueue.VTable, self.vtable).BeginDownload(@ptrCast(*const IDWriteFontDownloadQueue, self), context);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontDownloadQueue_CancelDownload(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontDownloadQueue.VTable, self.vtable).CancelDownload(@ptrCast(*const IDWriteFontDownloadQueue, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontDownloadQueue_GetGenerationCount(self: *const T) callconv(.Inline) u64 {
return @ptrCast(*const IDWriteFontDownloadQueue.VTable, self.vtable).GetGenerationCount(@ptrCast(*const IDWriteFontDownloadQueue, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDWriteGdiInterop1_Value = Guid.initString("4556be70-3abd-4f70-90be-421780a6f515");
pub const IID_IDWriteGdiInterop1 = &IID_IDWriteGdiInterop1_Value;
pub const IDWriteGdiInterop1 = extern struct {
pub const VTable = extern struct {
base: IDWriteGdiInterop.VTable,
CreateFontFromLOGFONT: fn(
self: *const IDWriteGdiInterop1,
logFont: ?*const LOGFONTW,
fontCollection: ?*IDWriteFontCollection,
font: ?*?*IDWriteFont,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontSignature: fn(
self: *const IDWriteGdiInterop1,
fontFace: ?*IDWriteFontFace,
fontSignature: ?*FONTSIGNATURE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontSignature1: fn(
self: *const IDWriteGdiInterop1,
font: ?*IDWriteFont,
fontSignature: ?*FONTSIGNATURE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetMatchingFontsByLOGFONT: fn(
self: *const IDWriteGdiInterop1,
logFont: ?*const LOGFONTA,
fontSet: ?*IDWriteFontSet,
filteredSet: ?*?*IDWriteFontSet,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteGdiInterop.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteGdiInterop1_CreateFontFromLOGFONT(self: *const T, logFont: ?*const LOGFONTW, fontCollection: ?*IDWriteFontCollection, font: ?*?*IDWriteFont) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteGdiInterop1.VTable, self.vtable).CreateFontFromLOGFONT(@ptrCast(*const IDWriteGdiInterop1, self), logFont, fontCollection, font);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteGdiInterop1_GetFontSignature(self: *const T, fontFace: ?*IDWriteFontFace, fontSignature: ?*FONTSIGNATURE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteGdiInterop1.VTable, self.vtable).GetFontSignature(@ptrCast(*const IDWriteGdiInterop1, self), fontFace, fontSignature);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteGdiInterop1_GetFontSignature1(self: *const T, font: ?*IDWriteFont, fontSignature: ?*FONTSIGNATURE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteGdiInterop1.VTable, self.vtable).GetFontSignature(@ptrCast(*const IDWriteGdiInterop1, self), font, fontSignature);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteGdiInterop1_GetMatchingFontsByLOGFONT(self: *const T, logFont: ?*const LOGFONTA, fontSet: ?*IDWriteFontSet, filteredSet: ?*?*IDWriteFontSet) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteGdiInterop1.VTable, self.vtable).GetMatchingFontsByLOGFONT(@ptrCast(*const IDWriteGdiInterop1, self), logFont, fontSet, filteredSet);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DWRITE_LINE_METRICS1 = extern struct {
Base: DWRITE_LINE_METRICS,
leadingBefore: f32,
leadingAfter: f32,
};
pub const DWRITE_FONT_LINE_GAP_USAGE = enum(i32) {
DEFAULT = 0,
DISABLED = 1,
ENABLED = 2,
};
pub const DWRITE_FONT_LINE_GAP_USAGE_DEFAULT = DWRITE_FONT_LINE_GAP_USAGE.DEFAULT;
pub const DWRITE_FONT_LINE_GAP_USAGE_DISABLED = DWRITE_FONT_LINE_GAP_USAGE.DISABLED;
pub const DWRITE_FONT_LINE_GAP_USAGE_ENABLED = DWRITE_FONT_LINE_GAP_USAGE.ENABLED;
pub const DWRITE_LINE_SPACING = extern struct {
method: DWRITE_LINE_SPACING_METHOD,
height: f32,
baseline: f32,
leadingBefore: f32,
fontLineGapUsage: DWRITE_FONT_LINE_GAP_USAGE,
};
// TODO: this type is limited to platform 'windows8.1'
const IID_IDWriteTextFormat2_Value = Guid.initString("f67e0edd-9e3d-4ecc-8c32-4183253dfe70");
pub const IID_IDWriteTextFormat2 = &IID_IDWriteTextFormat2_Value;
pub const IDWriteTextFormat2 = extern struct {
pub const VTable = extern struct {
base: IDWriteTextFormat1.VTable,
SetLineSpacing: fn(
self: *const IDWriteTextFormat2,
lineSpacingOptions: ?*const DWRITE_LINE_SPACING,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLineSpacing: fn(
self: *const IDWriteTextFormat2,
lineSpacingOptions: ?*DWRITE_LINE_SPACING,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteTextFormat1.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat2_SetLineSpacing(self: *const T, lineSpacingOptions: ?*const DWRITE_LINE_SPACING) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextFormat2.VTable, self.vtable).SetLineSpacing(@ptrCast(*const IDWriteTextFormat2, self), lineSpacingOptions);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat2_GetLineSpacing(self: *const T, lineSpacingOptions: ?*DWRITE_LINE_SPACING) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextFormat2.VTable, self.vtable).GetLineSpacing(@ptrCast(*const IDWriteTextFormat2, self), lineSpacingOptions);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.1'
const IID_IDWriteTextLayout3_Value = Guid.initString("07ddcd52-020e-4de8-ac33-6c953d83f92d");
pub const IID_IDWriteTextLayout3 = &IID_IDWriteTextLayout3_Value;
pub const IDWriteTextLayout3 = extern struct {
pub const VTable = extern struct {
base: IDWriteTextLayout2.VTable,
InvalidateLayout: fn(
self: *const IDWriteTextLayout3,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetLineSpacing: fn(
self: *const IDWriteTextLayout3,
lineSpacingOptions: ?*const DWRITE_LINE_SPACING,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLineSpacing: fn(
self: *const IDWriteTextLayout3,
lineSpacingOptions: ?*DWRITE_LINE_SPACING,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLineMetrics: fn(
self: *const IDWriteTextLayout3,
lineMetrics: ?[*]DWRITE_LINE_METRICS1,
maxLineCount: u32,
actualLineCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteTextLayout2.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout3_InvalidateLayout(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout3.VTable, self.vtable).InvalidateLayout(@ptrCast(*const IDWriteTextLayout3, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout3_SetLineSpacing(self: *const T, lineSpacingOptions: ?*const DWRITE_LINE_SPACING) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout3.VTable, self.vtable).SetLineSpacing(@ptrCast(*const IDWriteTextLayout3, self), lineSpacingOptions);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout3_GetLineSpacing(self: *const T, lineSpacingOptions: ?*DWRITE_LINE_SPACING) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout3.VTable, self.vtable).GetLineSpacing(@ptrCast(*const IDWriteTextLayout3, self), lineSpacingOptions);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout3_GetLineMetrics(self: *const T, lineMetrics: ?[*]DWRITE_LINE_METRICS1, maxLineCount: u32, actualLineCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout3.VTable, self.vtable).GetLineMetrics(@ptrCast(*const IDWriteTextLayout3, self), lineMetrics, maxLineCount, actualLineCount);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DWRITE_COLOR_GLYPH_RUN1 = extern struct {
Base: DWRITE_COLOR_GLYPH_RUN,
glyphImageFormat: DWRITE_GLYPH_IMAGE_FORMATS,
measuringMode: DWRITE_MEASURING_MODE,
};
pub const DWRITE_GLYPH_IMAGE_DATA = extern struct {
imageData: ?*const anyopaque,
imageDataSize: u32,
uniqueDataId: u32,
pixelsPerEm: u32,
pixelSize: D2D_SIZE_U,
horizontalLeftOrigin: POINT,
horizontalRightOrigin: POINT,
verticalTopOrigin: POINT,
verticalBottomOrigin: POINT,
};
const IID_IDWriteColorGlyphRunEnumerator1_Value = Guid.initString("7c5f86da-c7a1-4f05-b8e1-55a179fe5a35");
pub const IID_IDWriteColorGlyphRunEnumerator1 = &IID_IDWriteColorGlyphRunEnumerator1_Value;
pub const IDWriteColorGlyphRunEnumerator1 = extern struct {
pub const VTable = extern struct {
base: IDWriteColorGlyphRunEnumerator.VTable,
GetCurrentRun: fn(
self: *const IDWriteColorGlyphRunEnumerator1,
colorGlyphRun: ?*const ?*DWRITE_COLOR_GLYPH_RUN1,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteColorGlyphRunEnumerator.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteColorGlyphRunEnumerator1_GetCurrentRun(self: *const T, colorGlyphRun: ?*const ?*DWRITE_COLOR_GLYPH_RUN1) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteColorGlyphRunEnumerator1.VTable, self.vtable).GetCurrentRun(@ptrCast(*const IDWriteColorGlyphRunEnumerator1, self), colorGlyphRun);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDWriteFontFace4_Value = Guid.initString("27f2a904-4eb8-441d-9678-0563f53e3e2f");
pub const IID_IDWriteFontFace4 = &IID_IDWriteFontFace4_Value;
pub const IDWriteFontFace4 = extern struct {
pub const VTable = extern struct {
base: IDWriteFontFace3.VTable,
GetGlyphImageFormats: fn(
self: *const IDWriteFontFace4,
glyphId: u16,
pixelsPerEmFirst: u32,
pixelsPerEmLast: u32,
glyphImageFormats: ?*DWRITE_GLYPH_IMAGE_FORMATS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetGlyphImageFormats1: fn(
self: *const IDWriteFontFace4,
) callconv(@import("std").os.windows.WINAPI) DWRITE_GLYPH_IMAGE_FORMATS,
GetGlyphImageData: fn(
self: *const IDWriteFontFace4,
glyphId: u16,
pixelsPerEm: u32,
glyphImageFormat: DWRITE_GLYPH_IMAGE_FORMATS,
glyphData: ?*DWRITE_GLYPH_IMAGE_DATA,
glyphDataContext: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ReleaseGlyphImageData: fn(
self: *const IDWriteFontFace4,
glyphDataContext: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) void,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFontFace3.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace4_GetGlyphImageFormats(self: *const T, glyphId: u16, pixelsPerEmFirst: u32, pixelsPerEmLast: u32, glyphImageFormats: ?*DWRITE_GLYPH_IMAGE_FORMATS) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFace4.VTable, self.vtable).GetGlyphImageFormats(@ptrCast(*const IDWriteFontFace4, self), glyphId, pixelsPerEmFirst, pixelsPerEmLast, glyphImageFormats);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace4_GetGlyphImageFormats1(self: *const T) callconv(.Inline) DWRITE_GLYPH_IMAGE_FORMATS {
return @ptrCast(*const IDWriteFontFace4.VTable, self.vtable).GetGlyphImageFormats(@ptrCast(*const IDWriteFontFace4, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace4_GetGlyphImageData(self: *const T, glyphId: u16, pixelsPerEm: u32, glyphImageFormat: DWRITE_GLYPH_IMAGE_FORMATS, glyphData: ?*DWRITE_GLYPH_IMAGE_DATA, glyphDataContext: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFace4.VTable, self.vtable).GetGlyphImageData(@ptrCast(*const IDWriteFontFace4, self), glyphId, pixelsPerEm, glyphImageFormat, glyphData, glyphDataContext);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace4_ReleaseGlyphImageData(self: *const T, glyphDataContext: ?*anyopaque) callconv(.Inline) void {
return @ptrCast(*const IDWriteFontFace4.VTable, self.vtable).ReleaseGlyphImageData(@ptrCast(*const IDWriteFontFace4, self), glyphDataContext);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDWriteFactory4_Value = Guid.initString("4b0b5bd3-0797-4549-8ac5-fe915cc53856");
pub const IID_IDWriteFactory4 = &IID_IDWriteFactory4_Value;
pub const IDWriteFactory4 = extern struct {
pub const VTable = extern struct {
base: IDWriteFactory3.VTable,
TranslateColorGlyphRun: fn(
self: *const IDWriteFactory4,
baselineOrigin: D2D_POINT_2F,
glyphRun: ?*const DWRITE_GLYPH_RUN,
glyphRunDescription: ?*const DWRITE_GLYPH_RUN_DESCRIPTION,
desiredGlyphImageFormats: DWRITE_GLYPH_IMAGE_FORMATS,
measuringMode: DWRITE_MEASURING_MODE,
worldAndDpiTransform: ?*const DWRITE_MATRIX,
colorPaletteIndex: u32,
colorLayers: ?*?*IDWriteColorGlyphRunEnumerator1,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ComputeGlyphOrigins: fn(
self: *const IDWriteFactory4,
glyphRun: ?*const DWRITE_GLYPH_RUN,
baselineOrigin: D2D_POINT_2F,
glyphOrigins: ?*D2D_POINT_2F,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ComputeGlyphOrigins1: fn(
self: *const IDWriteFactory4,
glyphRun: ?*const DWRITE_GLYPH_RUN,
measuringMode: DWRITE_MEASURING_MODE,
baselineOrigin: D2D_POINT_2F,
worldAndDpiTransform: ?*const DWRITE_MATRIX,
glyphOrigins: ?*D2D_POINT_2F,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFactory3.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory4_TranslateColorGlyphRun(self: *const T, baselineOrigin: D2D_POINT_2F, glyphRun: ?*const DWRITE_GLYPH_RUN, glyphRunDescription: ?*const DWRITE_GLYPH_RUN_DESCRIPTION, desiredGlyphImageFormats: DWRITE_GLYPH_IMAGE_FORMATS, measuringMode: DWRITE_MEASURING_MODE, worldAndDpiTransform: ?*const DWRITE_MATRIX, colorPaletteIndex: u32, colorLayers: ?*?*IDWriteColorGlyphRunEnumerator1) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory4.VTable, self.vtable).TranslateColorGlyphRun(@ptrCast(*const IDWriteFactory4, self), baselineOrigin, glyphRun, glyphRunDescription, desiredGlyphImageFormats, measuringMode, worldAndDpiTransform, colorPaletteIndex, colorLayers);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory4_ComputeGlyphOrigins(self: *const T, glyphRun: ?*const DWRITE_GLYPH_RUN, baselineOrigin: D2D_POINT_2F, glyphOrigins: ?*D2D_POINT_2F) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory4.VTable, self.vtable).ComputeGlyphOrigins(@ptrCast(*const IDWriteFactory4, self), glyphRun, baselineOrigin, glyphOrigins);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory4_ComputeGlyphOrigins1(self: *const T, glyphRun: ?*const DWRITE_GLYPH_RUN, measuringMode: DWRITE_MEASURING_MODE, baselineOrigin: D2D_POINT_2F, worldAndDpiTransform: ?*const DWRITE_MATRIX, glyphOrigins: ?*D2D_POINT_2F) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory4.VTable, self.vtable).ComputeGlyphOrigins(@ptrCast(*const IDWriteFactory4, self), glyphRun, measuringMode, baselineOrigin, worldAndDpiTransform, glyphOrigins);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDWriteFontSetBuilder1_Value = Guid.initString("3ff7715f-3cdc-4dc6-9b72-ec5621dccafd");
pub const IID_IDWriteFontSetBuilder1 = &IID_IDWriteFontSetBuilder1_Value;
pub const IDWriteFontSetBuilder1 = extern struct {
pub const VTable = extern struct {
base: IDWriteFontSetBuilder.VTable,
AddFontFile: fn(
self: *const IDWriteFontSetBuilder1,
fontFile: ?*IDWriteFontFile,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFontSetBuilder.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSetBuilder1_AddFontFile(self: *const T, fontFile: ?*IDWriteFontFile) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontSetBuilder1.VTable, self.vtable).AddFontFile(@ptrCast(*const IDWriteFontSetBuilder1, self), fontFile);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDWriteAsyncResult_Value = Guid.initString("ce25f8fd-863b-4d13-9651-c1f88dc73fe2");
pub const IID_IDWriteAsyncResult = &IID_IDWriteAsyncResult_Value;
pub const IDWriteAsyncResult = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetWaitHandle: fn(
self: *const IDWriteAsyncResult,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE,
GetResult: fn(
self: *const IDWriteAsyncResult,
) 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 IDWriteAsyncResult_GetWaitHandle(self: *const T) callconv(.Inline) ?HANDLE {
return @ptrCast(*const IDWriteAsyncResult.VTable, self.vtable).GetWaitHandle(@ptrCast(*const IDWriteAsyncResult, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteAsyncResult_GetResult(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteAsyncResult.VTable, self.vtable).GetResult(@ptrCast(*const IDWriteAsyncResult, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DWRITE_FILE_FRAGMENT = extern struct {
fileOffset: u64,
fragmentSize: u64,
};
const IID_IDWriteRemoteFontFileStream_Value = Guid.initString("4db3757a-2c72-4ed9-b2b6-1ababe1aff9c");
pub const IID_IDWriteRemoteFontFileStream = &IID_IDWriteRemoteFontFileStream_Value;
pub const IDWriteRemoteFontFileStream = extern struct {
pub const VTable = extern struct {
base: IDWriteFontFileStream.VTable,
GetLocalFileSize: fn(
self: *const IDWriteRemoteFontFileStream,
localFileSize: ?*u64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFileFragmentLocality: fn(
self: *const IDWriteRemoteFontFileStream,
fileOffset: u64,
fragmentSize: u64,
isLocal: ?*BOOL,
partialSize: ?*u64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLocality: fn(
self: *const IDWriteRemoteFontFileStream,
) callconv(@import("std").os.windows.WINAPI) DWRITE_LOCALITY,
BeginDownload: fn(
self: *const IDWriteRemoteFontFileStream,
downloadOperationID: ?*const Guid,
fileFragments: [*]const DWRITE_FILE_FRAGMENT,
fragmentCount: u32,
asyncResult: ?*?*IDWriteAsyncResult,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFontFileStream.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteRemoteFontFileStream_GetLocalFileSize(self: *const T, localFileSize: ?*u64) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteRemoteFontFileStream.VTable, self.vtable).GetLocalFileSize(@ptrCast(*const IDWriteRemoteFontFileStream, self), localFileSize);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteRemoteFontFileStream_GetFileFragmentLocality(self: *const T, fileOffset: u64, fragmentSize: u64, isLocal: ?*BOOL, partialSize: ?*u64) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteRemoteFontFileStream.VTable, self.vtable).GetFileFragmentLocality(@ptrCast(*const IDWriteRemoteFontFileStream, self), fileOffset, fragmentSize, isLocal, partialSize);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteRemoteFontFileStream_GetLocality(self: *const T) callconv(.Inline) DWRITE_LOCALITY {
return @ptrCast(*const IDWriteRemoteFontFileStream.VTable, self.vtable).GetLocality(@ptrCast(*const IDWriteRemoteFontFileStream, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteRemoteFontFileStream_BeginDownload(self: *const T, downloadOperationID: ?*const Guid, fileFragments: [*]const DWRITE_FILE_FRAGMENT, fragmentCount: u32, asyncResult: ?*?*IDWriteAsyncResult) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteRemoteFontFileStream.VTable, self.vtable).BeginDownload(@ptrCast(*const IDWriteRemoteFontFileStream, self), downloadOperationID, fileFragments, fragmentCount, asyncResult);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DWRITE_CONTAINER_TYPE = enum(i32) {
UNKNOWN = 0,
WOFF = 1,
WOFF2 = 2,
};
pub const DWRITE_CONTAINER_TYPE_UNKNOWN = DWRITE_CONTAINER_TYPE.UNKNOWN;
pub const DWRITE_CONTAINER_TYPE_WOFF = DWRITE_CONTAINER_TYPE.WOFF;
pub const DWRITE_CONTAINER_TYPE_WOFF2 = DWRITE_CONTAINER_TYPE.WOFF2;
const IID_IDWriteRemoteFontFileLoader_Value = Guid.initString("68648c83-6ede-46c0-ab46-20083a887fde");
pub const IID_IDWriteRemoteFontFileLoader = &IID_IDWriteRemoteFontFileLoader_Value;
pub const IDWriteRemoteFontFileLoader = extern struct {
pub const VTable = extern struct {
base: IDWriteFontFileLoader.VTable,
CreateRemoteStreamFromKey: fn(
self: *const IDWriteRemoteFontFileLoader,
// TODO: what to do with BytesParamIndex 1?
fontFileReferenceKey: ?*const anyopaque,
fontFileReferenceKeySize: u32,
fontFileStream: ?*?*IDWriteRemoteFontFileStream,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLocalityFromKey: fn(
self: *const IDWriteRemoteFontFileLoader,
// TODO: what to do with BytesParamIndex 1?
fontFileReferenceKey: ?*const anyopaque,
fontFileReferenceKeySize: u32,
locality: ?*DWRITE_LOCALITY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateFontFileReferenceFromUrl: fn(
self: *const IDWriteRemoteFontFileLoader,
factory: ?*IDWriteFactory,
baseUrl: ?[*:0]const u16,
fontFileUrl: ?[*:0]const u16,
fontFile: ?*?*IDWriteFontFile,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFontFileLoader.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteRemoteFontFileLoader_CreateRemoteStreamFromKey(self: *const T, fontFileReferenceKey: ?*const anyopaque, fontFileReferenceKeySize: u32, fontFileStream: ?*?*IDWriteRemoteFontFileStream) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteRemoteFontFileLoader.VTable, self.vtable).CreateRemoteStreamFromKey(@ptrCast(*const IDWriteRemoteFontFileLoader, self), fontFileReferenceKey, fontFileReferenceKeySize, fontFileStream);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteRemoteFontFileLoader_GetLocalityFromKey(self: *const T, fontFileReferenceKey: ?*const anyopaque, fontFileReferenceKeySize: u32, locality: ?*DWRITE_LOCALITY) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteRemoteFontFileLoader.VTable, self.vtable).GetLocalityFromKey(@ptrCast(*const IDWriteRemoteFontFileLoader, self), fontFileReferenceKey, fontFileReferenceKeySize, locality);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteRemoteFontFileLoader_CreateFontFileReferenceFromUrl(self: *const T, factory: ?*IDWriteFactory, baseUrl: ?[*:0]const u16, fontFileUrl: ?[*:0]const u16, fontFile: ?*?*IDWriteFontFile) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteRemoteFontFileLoader.VTable, self.vtable).CreateFontFileReferenceFromUrl(@ptrCast(*const IDWriteRemoteFontFileLoader, self), factory, baseUrl, fontFileUrl, fontFile);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDWriteInMemoryFontFileLoader_Value = Guid.initString("dc102f47-a12d-4b1c-822d-9e117e33043f");
pub const IID_IDWriteInMemoryFontFileLoader = &IID_IDWriteInMemoryFontFileLoader_Value;
pub const IDWriteInMemoryFontFileLoader = extern struct {
pub const VTable = extern struct {
base: IDWriteFontFileLoader.VTable,
CreateInMemoryFontFileReference: fn(
self: *const IDWriteInMemoryFontFileLoader,
factory: ?*IDWriteFactory,
// TODO: what to do with BytesParamIndex 2?
fontData: ?*const anyopaque,
fontDataSize: u32,
ownerObject: ?*IUnknown,
fontFile: ?*?*IDWriteFontFile,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFileCount: fn(
self: *const IDWriteInMemoryFontFileLoader,
) callconv(@import("std").os.windows.WINAPI) u32,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFontFileLoader.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteInMemoryFontFileLoader_CreateInMemoryFontFileReference(self: *const T, factory: ?*IDWriteFactory, fontData: ?*const anyopaque, fontDataSize: u32, ownerObject: ?*IUnknown, fontFile: ?*?*IDWriteFontFile) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteInMemoryFontFileLoader.VTable, self.vtable).CreateInMemoryFontFileReference(@ptrCast(*const IDWriteInMemoryFontFileLoader, self), factory, fontData, fontDataSize, ownerObject, fontFile);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteInMemoryFontFileLoader_GetFileCount(self: *const T) callconv(.Inline) u32 {
return @ptrCast(*const IDWriteInMemoryFontFileLoader.VTable, self.vtable).GetFileCount(@ptrCast(*const IDWriteInMemoryFontFileLoader, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDWriteFactory5_Value = Guid.initString("958db99a-be2a-4f09-af7d-65189803d1d3");
pub const IID_IDWriteFactory5 = &IID_IDWriteFactory5_Value;
pub const IDWriteFactory5 = extern struct {
pub const VTable = extern struct {
base: IDWriteFactory4.VTable,
CreateFontSetBuilder: fn(
self: *const IDWriteFactory5,
fontSetBuilder: ?*?*IDWriteFontSetBuilder1,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateInMemoryFontFileLoader: fn(
self: *const IDWriteFactory5,
newLoader: ?*?*IDWriteInMemoryFontFileLoader,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateHttpFontFileLoader: fn(
self: *const IDWriteFactory5,
referrerUrl: ?[*:0]const u16,
extraHeaders: ?[*:0]const u16,
newLoader: ?*?*IDWriteRemoteFontFileLoader,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AnalyzeContainerType: fn(
self: *const IDWriteFactory5,
// TODO: what to do with BytesParamIndex 1?
fileData: ?*const anyopaque,
fileDataSize: u32,
) callconv(@import("std").os.windows.WINAPI) DWRITE_CONTAINER_TYPE,
UnpackFontFile: fn(
self: *const IDWriteFactory5,
containerType: DWRITE_CONTAINER_TYPE,
// TODO: what to do with BytesParamIndex 2?
fileData: ?*const anyopaque,
fileDataSize: u32,
unpackedFontStream: ?*?*IDWriteFontFileStream,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFactory4.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory5_CreateFontSetBuilder(self: *const T, fontSetBuilder: ?*?*IDWriteFontSetBuilder1) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory5.VTable, self.vtable).CreateFontSetBuilder(@ptrCast(*const IDWriteFactory5, self), fontSetBuilder);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory5_CreateInMemoryFontFileLoader(self: *const T, newLoader: ?*?*IDWriteInMemoryFontFileLoader) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory5.VTable, self.vtable).CreateInMemoryFontFileLoader(@ptrCast(*const IDWriteFactory5, self), newLoader);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory5_CreateHttpFontFileLoader(self: *const T, referrerUrl: ?[*:0]const u16, extraHeaders: ?[*:0]const u16, newLoader: ?*?*IDWriteRemoteFontFileLoader) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory5.VTable, self.vtable).CreateHttpFontFileLoader(@ptrCast(*const IDWriteFactory5, self), referrerUrl, extraHeaders, newLoader);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory5_AnalyzeContainerType(self: *const T, fileData: ?*const anyopaque, fileDataSize: u32) callconv(.Inline) DWRITE_CONTAINER_TYPE {
return @ptrCast(*const IDWriteFactory5.VTable, self.vtable).AnalyzeContainerType(@ptrCast(*const IDWriteFactory5, self), fileData, fileDataSize);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory5_UnpackFontFile(self: *const T, containerType: DWRITE_CONTAINER_TYPE, fileData: ?*const anyopaque, fileDataSize: u32, unpackedFontStream: ?*?*IDWriteFontFileStream) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory5.VTable, self.vtable).UnpackFontFile(@ptrCast(*const IDWriteFactory5, self), containerType, fileData, fileDataSize, unpackedFontStream);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DWRITE_FONT_AXIS_VALUE = extern struct {
axisTag: DWRITE_FONT_AXIS_TAG,
value: f32,
};
pub const DWRITE_FONT_AXIS_RANGE = extern struct {
axisTag: DWRITE_FONT_AXIS_TAG,
minValue: f32,
maxValue: f32,
};
pub const DWRITE_FONT_FAMILY_MODEL = enum(i32) {
TYPOGRAPHIC = 0,
WEIGHT_STRETCH_STYLE = 1,
};
pub const DWRITE_FONT_FAMILY_MODEL_TYPOGRAPHIC = DWRITE_FONT_FAMILY_MODEL.TYPOGRAPHIC;
pub const DWRITE_FONT_FAMILY_MODEL_WEIGHT_STRETCH_STYLE = DWRITE_FONT_FAMILY_MODEL.WEIGHT_STRETCH_STYLE;
pub const DWRITE_AUTOMATIC_FONT_AXES = enum(u32) {
NONE = 0,
OPTICAL_SIZE = 1,
_,
pub fn initFlags(o: struct {
NONE: u1 = 0,
OPTICAL_SIZE: u1 = 0,
}) DWRITE_AUTOMATIC_FONT_AXES {
return @intToEnum(DWRITE_AUTOMATIC_FONT_AXES,
(if (o.NONE == 1) @enumToInt(DWRITE_AUTOMATIC_FONT_AXES.NONE) else 0)
| (if (o.OPTICAL_SIZE == 1) @enumToInt(DWRITE_AUTOMATIC_FONT_AXES.OPTICAL_SIZE) else 0)
);
}
};
pub const DWRITE_AUTOMATIC_FONT_AXES_NONE = DWRITE_AUTOMATIC_FONT_AXES.NONE;
pub const DWRITE_AUTOMATIC_FONT_AXES_OPTICAL_SIZE = DWRITE_AUTOMATIC_FONT_AXES.OPTICAL_SIZE;
pub const DWRITE_FONT_AXIS_ATTRIBUTES = enum(u32) {
NONE = 0,
VARIABLE = 1,
HIDDEN = 2,
_,
pub fn initFlags(o: struct {
NONE: u1 = 0,
VARIABLE: u1 = 0,
HIDDEN: u1 = 0,
}) DWRITE_FONT_AXIS_ATTRIBUTES {
return @intToEnum(DWRITE_FONT_AXIS_ATTRIBUTES,
(if (o.NONE == 1) @enumToInt(DWRITE_FONT_AXIS_ATTRIBUTES.NONE) else 0)
| (if (o.VARIABLE == 1) @enumToInt(DWRITE_FONT_AXIS_ATTRIBUTES.VARIABLE) else 0)
| (if (o.HIDDEN == 1) @enumToInt(DWRITE_FONT_AXIS_ATTRIBUTES.HIDDEN) else 0)
);
}
};
pub const DWRITE_FONT_AXIS_ATTRIBUTES_NONE = DWRITE_FONT_AXIS_ATTRIBUTES.NONE;
pub const DWRITE_FONT_AXIS_ATTRIBUTES_VARIABLE = DWRITE_FONT_AXIS_ATTRIBUTES.VARIABLE;
pub const DWRITE_FONT_AXIS_ATTRIBUTES_HIDDEN = DWRITE_FONT_AXIS_ATTRIBUTES.HIDDEN;
const IID_IDWriteFactory6_Value = Guid.initString("f3744d80-21f7-42eb-b35d-995bc72fc223");
pub const IID_IDWriteFactory6 = &IID_IDWriteFactory6_Value;
pub const IDWriteFactory6 = extern struct {
pub const VTable = extern struct {
base: IDWriteFactory5.VTable,
CreateFontFaceReference: fn(
self: *const IDWriteFactory6,
fontFile: ?*IDWriteFontFile,
faceIndex: u32,
fontSimulations: DWRITE_FONT_SIMULATIONS,
fontAxisValues: [*]const DWRITE_FONT_AXIS_VALUE,
fontAxisValueCount: u32,
fontFaceReference: ?*?*IDWriteFontFaceReference1,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateFontResource: fn(
self: *const IDWriteFactory6,
fontFile: ?*IDWriteFontFile,
faceIndex: u32,
fontResource: ?*?*IDWriteFontResource,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSystemFontSet: fn(
self: *const IDWriteFactory6,
includeDownloadableFonts: BOOL,
fontSet: ?*?*IDWriteFontSet1,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSystemFontCollection: fn(
self: *const IDWriteFactory6,
includeDownloadableFonts: BOOL,
fontFamilyModel: DWRITE_FONT_FAMILY_MODEL,
fontCollection: ?*?*IDWriteFontCollection2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateFontCollectionFromFontSet: fn(
self: *const IDWriteFactory6,
fontSet: ?*IDWriteFontSet,
fontFamilyModel: DWRITE_FONT_FAMILY_MODEL,
fontCollection: ?*?*IDWriteFontCollection2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateFontSetBuilder: fn(
self: *const IDWriteFactory6,
fontSetBuilder: ?*?*IDWriteFontSetBuilder2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateTextFormat: fn(
self: *const IDWriteFactory6,
fontFamilyName: ?[*:0]const u16,
fontCollection: ?*IDWriteFontCollection,
fontAxisValues: [*]const DWRITE_FONT_AXIS_VALUE,
fontAxisValueCount: u32,
fontSize: f32,
localeName: ?[*:0]const u16,
textFormat: ?*?*IDWriteTextFormat3,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFactory5.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory6_CreateFontFaceReference(self: *const T, fontFile: ?*IDWriteFontFile, faceIndex: u32, fontSimulations: DWRITE_FONT_SIMULATIONS, fontAxisValues: [*]const DWRITE_FONT_AXIS_VALUE, fontAxisValueCount: u32, fontFaceReference: ?*?*IDWriteFontFaceReference1) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory6.VTable, self.vtable).CreateFontFaceReference(@ptrCast(*const IDWriteFactory6, self), fontFile, faceIndex, fontSimulations, fontAxisValues, fontAxisValueCount, fontFaceReference);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory6_CreateFontResource(self: *const T, fontFile: ?*IDWriteFontFile, faceIndex: u32, fontResource: ?*?*IDWriteFontResource) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory6.VTable, self.vtable).CreateFontResource(@ptrCast(*const IDWriteFactory6, self), fontFile, faceIndex, fontResource);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory6_GetSystemFontSet(self: *const T, includeDownloadableFonts: BOOL, fontSet: ?*?*IDWriteFontSet1) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory6.VTable, self.vtable).GetSystemFontSet(@ptrCast(*const IDWriteFactory6, self), includeDownloadableFonts, fontSet);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory6_GetSystemFontCollection(self: *const T, includeDownloadableFonts: BOOL, fontFamilyModel: DWRITE_FONT_FAMILY_MODEL, fontCollection: ?*?*IDWriteFontCollection2) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory6.VTable, self.vtable).GetSystemFontCollection(@ptrCast(*const IDWriteFactory6, self), includeDownloadableFonts, fontFamilyModel, fontCollection);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory6_CreateFontCollectionFromFontSet(self: *const T, fontSet: ?*IDWriteFontSet, fontFamilyModel: DWRITE_FONT_FAMILY_MODEL, fontCollection: ?*?*IDWriteFontCollection2) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory6.VTable, self.vtable).CreateFontCollectionFromFontSet(@ptrCast(*const IDWriteFactory6, self), fontSet, fontFamilyModel, fontCollection);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory6_CreateFontSetBuilder(self: *const T, fontSetBuilder: ?*?*IDWriteFontSetBuilder2) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory6.VTable, self.vtable).CreateFontSetBuilder(@ptrCast(*const IDWriteFactory6, self), fontSetBuilder);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory6_CreateTextFormat(self: *const T, fontFamilyName: ?[*:0]const u16, fontCollection: ?*IDWriteFontCollection, fontAxisValues: [*]const DWRITE_FONT_AXIS_VALUE, fontAxisValueCount: u32, fontSize: f32, localeName: ?[*:0]const u16, textFormat: ?*?*IDWriteTextFormat3) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory6.VTable, self.vtable).CreateTextFormat(@ptrCast(*const IDWriteFactory6, self), fontFamilyName, fontCollection, fontAxisValues, fontAxisValueCount, fontSize, localeName, textFormat);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDWriteFontFace5_Value = Guid.initString("98eff3a5-b667-479a-b145-e2fa5b9fdc29");
pub const IID_IDWriteFontFace5 = &IID_IDWriteFontFace5_Value;
pub const IDWriteFontFace5 = extern struct {
pub const VTable = extern struct {
base: IDWriteFontFace4.VTable,
GetFontAxisValueCount: fn(
self: *const IDWriteFontFace5,
) callconv(@import("std").os.windows.WINAPI) u32,
GetFontAxisValues: fn(
self: *const IDWriteFontFace5,
fontAxisValues: [*]DWRITE_FONT_AXIS_VALUE,
fontAxisValueCount: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
HasVariations: fn(
self: *const IDWriteFontFace5,
) callconv(@import("std").os.windows.WINAPI) BOOL,
GetFontResource: fn(
self: *const IDWriteFontFace5,
fontResource: ?*?*IDWriteFontResource,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Equals: fn(
self: *const IDWriteFontFace5,
fontFace: ?*IDWriteFontFace,
) callconv(@import("std").os.windows.WINAPI) BOOL,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFontFace4.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace5_GetFontAxisValueCount(self: *const T) callconv(.Inline) u32 {
return @ptrCast(*const IDWriteFontFace5.VTable, self.vtable).GetFontAxisValueCount(@ptrCast(*const IDWriteFontFace5, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace5_GetFontAxisValues(self: *const T, fontAxisValues: [*]DWRITE_FONT_AXIS_VALUE, fontAxisValueCount: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFace5.VTable, self.vtable).GetFontAxisValues(@ptrCast(*const IDWriteFontFace5, self), fontAxisValues, fontAxisValueCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace5_HasVariations(self: *const T) callconv(.Inline) BOOL {
return @ptrCast(*const IDWriteFontFace5.VTable, self.vtable).HasVariations(@ptrCast(*const IDWriteFontFace5, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace5_GetFontResource(self: *const T, fontResource: ?*?*IDWriteFontResource) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFace5.VTable, self.vtable).GetFontResource(@ptrCast(*const IDWriteFontFace5, self), fontResource);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace5_Equals(self: *const T, fontFace: ?*IDWriteFontFace) callconv(.Inline) BOOL {
return @ptrCast(*const IDWriteFontFace5.VTable, self.vtable).Equals(@ptrCast(*const IDWriteFontFace5, self), fontFace);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDWriteFontResource_Value = Guid.initString("1f803a76-6871-48e8-987f-b975551c50f2");
pub const IID_IDWriteFontResource = &IID_IDWriteFontResource_Value;
pub const IDWriteFontResource = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetFontFile: fn(
self: *const IDWriteFontResource,
fontFile: ?*?*IDWriteFontFile,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontFaceIndex: fn(
self: *const IDWriteFontResource,
) callconv(@import("std").os.windows.WINAPI) u32,
GetFontAxisCount: fn(
self: *const IDWriteFontResource,
) callconv(@import("std").os.windows.WINAPI) u32,
GetDefaultFontAxisValues: fn(
self: *const IDWriteFontResource,
fontAxisValues: [*]DWRITE_FONT_AXIS_VALUE,
fontAxisValueCount: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontAxisRanges: fn(
self: *const IDWriteFontResource,
fontAxisRanges: [*]DWRITE_FONT_AXIS_RANGE,
fontAxisRangeCount: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontAxisAttributes: fn(
self: *const IDWriteFontResource,
axisIndex: u32,
) callconv(@import("std").os.windows.WINAPI) DWRITE_FONT_AXIS_ATTRIBUTES,
GetAxisNames: fn(
self: *const IDWriteFontResource,
axisIndex: u32,
names: ?*?*IDWriteLocalizedStrings,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetAxisValueNameCount: fn(
self: *const IDWriteFontResource,
axisIndex: u32,
) callconv(@import("std").os.windows.WINAPI) u32,
GetAxisValueNames: fn(
self: *const IDWriteFontResource,
axisIndex: u32,
axisValueIndex: u32,
fontAxisRange: ?*DWRITE_FONT_AXIS_RANGE,
names: ?*?*IDWriteLocalizedStrings,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
HasVariations: fn(
self: *const IDWriteFontResource,
) callconv(@import("std").os.windows.WINAPI) BOOL,
CreateFontFace: fn(
self: *const IDWriteFontResource,
fontSimulations: DWRITE_FONT_SIMULATIONS,
fontAxisValues: [*]const DWRITE_FONT_AXIS_VALUE,
fontAxisValueCount: u32,
fontFace: ?*?*IDWriteFontFace5,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateFontFaceReference: fn(
self: *const IDWriteFontResource,
fontSimulations: DWRITE_FONT_SIMULATIONS,
fontAxisValues: [*]const DWRITE_FONT_AXIS_VALUE,
fontAxisValueCount: u32,
fontFaceReference: ?*?*IDWriteFontFaceReference1,
) 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 IDWriteFontResource_GetFontFile(self: *const T, fontFile: ?*?*IDWriteFontFile) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontResource.VTable, self.vtable).GetFontFile(@ptrCast(*const IDWriteFontResource, self), fontFile);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontResource_GetFontFaceIndex(self: *const T) callconv(.Inline) u32 {
return @ptrCast(*const IDWriteFontResource.VTable, self.vtable).GetFontFaceIndex(@ptrCast(*const IDWriteFontResource, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontResource_GetFontAxisCount(self: *const T) callconv(.Inline) u32 {
return @ptrCast(*const IDWriteFontResource.VTable, self.vtable).GetFontAxisCount(@ptrCast(*const IDWriteFontResource, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontResource_GetDefaultFontAxisValues(self: *const T, fontAxisValues: [*]DWRITE_FONT_AXIS_VALUE, fontAxisValueCount: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontResource.VTable, self.vtable).GetDefaultFontAxisValues(@ptrCast(*const IDWriteFontResource, self), fontAxisValues, fontAxisValueCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontResource_GetFontAxisRanges(self: *const T, fontAxisRanges: [*]DWRITE_FONT_AXIS_RANGE, fontAxisRangeCount: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontResource.VTable, self.vtable).GetFontAxisRanges(@ptrCast(*const IDWriteFontResource, self), fontAxisRanges, fontAxisRangeCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontResource_GetFontAxisAttributes(self: *const T, axisIndex: u32) callconv(.Inline) DWRITE_FONT_AXIS_ATTRIBUTES {
return @ptrCast(*const IDWriteFontResource.VTable, self.vtable).GetFontAxisAttributes(@ptrCast(*const IDWriteFontResource, self), axisIndex);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontResource_GetAxisNames(self: *const T, axisIndex: u32, names: ?*?*IDWriteLocalizedStrings) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontResource.VTable, self.vtable).GetAxisNames(@ptrCast(*const IDWriteFontResource, self), axisIndex, names);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontResource_GetAxisValueNameCount(self: *const T, axisIndex: u32) callconv(.Inline) u32 {
return @ptrCast(*const IDWriteFontResource.VTable, self.vtable).GetAxisValueNameCount(@ptrCast(*const IDWriteFontResource, self), axisIndex);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontResource_GetAxisValueNames(self: *const T, axisIndex: u32, axisValueIndex: u32, fontAxisRange: ?*DWRITE_FONT_AXIS_RANGE, names: ?*?*IDWriteLocalizedStrings) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontResource.VTable, self.vtable).GetAxisValueNames(@ptrCast(*const IDWriteFontResource, self), axisIndex, axisValueIndex, fontAxisRange, names);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontResource_HasVariations(self: *const T) callconv(.Inline) BOOL {
return @ptrCast(*const IDWriteFontResource.VTable, self.vtable).HasVariations(@ptrCast(*const IDWriteFontResource, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontResource_CreateFontFace(self: *const T, fontSimulations: DWRITE_FONT_SIMULATIONS, fontAxisValues: [*]const DWRITE_FONT_AXIS_VALUE, fontAxisValueCount: u32, fontFace: ?*?*IDWriteFontFace5) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontResource.VTable, self.vtable).CreateFontFace(@ptrCast(*const IDWriteFontResource, self), fontSimulations, fontAxisValues, fontAxisValueCount, fontFace);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontResource_CreateFontFaceReference(self: *const T, fontSimulations: DWRITE_FONT_SIMULATIONS, fontAxisValues: [*]const DWRITE_FONT_AXIS_VALUE, fontAxisValueCount: u32, fontFaceReference: ?*?*IDWriteFontFaceReference1) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontResource.VTable, self.vtable).CreateFontFaceReference(@ptrCast(*const IDWriteFontResource, self), fontSimulations, fontAxisValues, fontAxisValueCount, fontFaceReference);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDWriteFontFaceReference1_Value = Guid.initString("c081fe77-2fd1-41ac-a5a3-34983c4ba61a");
pub const IID_IDWriteFontFaceReference1 = &IID_IDWriteFontFaceReference1_Value;
pub const IDWriteFontFaceReference1 = extern struct {
pub const VTable = extern struct {
base: IDWriteFontFaceReference.VTable,
CreateFontFace: fn(
self: *const IDWriteFontFaceReference1,
fontFace: ?*?*IDWriteFontFace5,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontAxisValueCount: fn(
self: *const IDWriteFontFaceReference1,
) callconv(@import("std").os.windows.WINAPI) u32,
GetFontAxisValues: fn(
self: *const IDWriteFontFaceReference1,
fontAxisValues: [*]DWRITE_FONT_AXIS_VALUE,
fontAxisValueCount: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFontFaceReference.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFaceReference1_CreateFontFace(self: *const T, fontFace: ?*?*IDWriteFontFace5) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFaceReference1.VTable, self.vtable).CreateFontFace(@ptrCast(*const IDWriteFontFaceReference1, self), fontFace);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFaceReference1_GetFontAxisValueCount(self: *const T) callconv(.Inline) u32 {
return @ptrCast(*const IDWriteFontFaceReference1.VTable, self.vtable).GetFontAxisValueCount(@ptrCast(*const IDWriteFontFaceReference1, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFaceReference1_GetFontAxisValues(self: *const T, fontAxisValues: [*]DWRITE_FONT_AXIS_VALUE, fontAxisValueCount: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFaceReference1.VTable, self.vtable).GetFontAxisValues(@ptrCast(*const IDWriteFontFaceReference1, self), fontAxisValues, fontAxisValueCount);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDWriteFontSetBuilder2_Value = Guid.initString("ee5ba612-b131-463c-8f4f-3189b9401e45");
pub const IID_IDWriteFontSetBuilder2 = &IID_IDWriteFontSetBuilder2_Value;
pub const IDWriteFontSetBuilder2 = extern struct {
pub const VTable = extern struct {
base: IDWriteFontSetBuilder1.VTable,
AddFont: fn(
self: *const IDWriteFontSetBuilder2,
fontFile: ?*IDWriteFontFile,
fontFaceIndex: u32,
fontSimulations: DWRITE_FONT_SIMULATIONS,
fontAxisValues: [*]const DWRITE_FONT_AXIS_VALUE,
fontAxisValueCount: u32,
fontAxisRanges: [*]const DWRITE_FONT_AXIS_RANGE,
fontAxisRangeCount: u32,
properties: [*]const DWRITE_FONT_PROPERTY,
propertyCount: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddFontFile: fn(
self: *const IDWriteFontSetBuilder2,
filePath: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFontSetBuilder1.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSetBuilder2_AddFont(self: *const T, fontFile: ?*IDWriteFontFile, fontFaceIndex: u32, fontSimulations: DWRITE_FONT_SIMULATIONS, fontAxisValues: [*]const DWRITE_FONT_AXIS_VALUE, fontAxisValueCount: u32, fontAxisRanges: [*]const DWRITE_FONT_AXIS_RANGE, fontAxisRangeCount: u32, properties: [*]const DWRITE_FONT_PROPERTY, propertyCount: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontSetBuilder2.VTable, self.vtable).AddFont(@ptrCast(*const IDWriteFontSetBuilder2, self), fontFile, fontFaceIndex, fontSimulations, fontAxisValues, fontAxisValueCount, fontAxisRanges, fontAxisRangeCount, properties, propertyCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSetBuilder2_AddFontFile(self: *const T, filePath: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontSetBuilder2.VTable, self.vtable).AddFontFile(@ptrCast(*const IDWriteFontSetBuilder2, self), filePath);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDWriteFontSet1_Value = Guid.initString("7e9fda85-6c92-4053-bc47-7ae3530db4d3");
pub const IID_IDWriteFontSet1 = &IID_IDWriteFontSet1_Value;
pub const IDWriteFontSet1 = extern struct {
pub const VTable = extern struct {
base: IDWriteFontSet.VTable,
GetMatchingFonts: fn(
self: *const IDWriteFontSet1,
fontProperty: ?*const DWRITE_FONT_PROPERTY,
fontAxisValues: [*]const DWRITE_FONT_AXIS_VALUE,
fontAxisValueCount: u32,
matchingFonts: ?*?*IDWriteFontSet1,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFirstFontResources: fn(
self: *const IDWriteFontSet1,
filteredFontSet: ?*?*IDWriteFontSet1,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFilteredFonts: fn(
self: *const IDWriteFontSet1,
indices: [*]const u32,
indexCount: u32,
filteredFontSet: ?*?*IDWriteFontSet1,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFilteredFonts1: fn(
self: *const IDWriteFontSet1,
fontAxisRanges: [*]const DWRITE_FONT_AXIS_RANGE,
fontAxisRangeCount: u32,
selectAnyRange: BOOL,
filteredFontSet: ?*?*IDWriteFontSet1,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFilteredFonts2: fn(
self: *const IDWriteFontSet1,
properties: ?[*]const DWRITE_FONT_PROPERTY,
propertyCount: u32,
selectAnyProperty: BOOL,
filteredFontSet: ?*?*IDWriteFontSet1,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFilteredFontIndices: fn(
self: *const IDWriteFontSet1,
fontAxisRanges: [*]const DWRITE_FONT_AXIS_RANGE,
fontAxisRangeCount: u32,
selectAnyRange: BOOL,
indices: [*]u32,
maxIndexCount: u32,
actualIndexCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFilteredFontIndices1: fn(
self: *const IDWriteFontSet1,
properties: [*]const DWRITE_FONT_PROPERTY,
propertyCount: u32,
selectAnyProperty: BOOL,
indices: [*]u32,
maxIndexCount: u32,
actualIndexCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontAxisRanges: fn(
self: *const IDWriteFontSet1,
listIndex: u32,
fontAxisRanges: [*]DWRITE_FONT_AXIS_RANGE,
maxFontAxisRangeCount: u32,
actualFontAxisRangeCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontAxisRanges1: fn(
self: *const IDWriteFontSet1,
fontAxisRanges: [*]DWRITE_FONT_AXIS_RANGE,
maxFontAxisRangeCount: u32,
actualFontAxisRangeCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontFaceReference: fn(
self: *const IDWriteFontSet1,
listIndex: u32,
fontFaceReference: ?*?*IDWriteFontFaceReference1,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateFontResource: fn(
self: *const IDWriteFontSet1,
listIndex: u32,
fontResource: ?*?*IDWriteFontResource,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateFontFace: fn(
self: *const IDWriteFontSet1,
listIndex: u32,
fontFace: ?*?*IDWriteFontFace5,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontLocality: fn(
self: *const IDWriteFontSet1,
listIndex: u32,
) callconv(@import("std").os.windows.WINAPI) DWRITE_LOCALITY,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFontSet.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSet1_GetMatchingFonts(self: *const T, fontProperty: ?*const DWRITE_FONT_PROPERTY, fontAxisValues: [*]const DWRITE_FONT_AXIS_VALUE, fontAxisValueCount: u32, matchingFonts: ?*?*IDWriteFontSet1) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontSet1.VTable, self.vtable).GetMatchingFonts(@ptrCast(*const IDWriteFontSet1, self), fontProperty, fontAxisValues, fontAxisValueCount, matchingFonts);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSet1_GetFirstFontResources(self: *const T, filteredFontSet: ?*?*IDWriteFontSet1) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontSet1.VTable, self.vtable).GetFirstFontResources(@ptrCast(*const IDWriteFontSet1, self), filteredFontSet);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSet1_GetFilteredFonts(self: *const T, indices: [*]const u32, indexCount: u32, filteredFontSet: ?*?*IDWriteFontSet1) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontSet1.VTable, self.vtable).GetFilteredFonts(@ptrCast(*const IDWriteFontSet1, self), indices, indexCount, filteredFontSet);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSet1_GetFilteredFonts1(self: *const T, fontAxisRanges: [*]const DWRITE_FONT_AXIS_RANGE, fontAxisRangeCount: u32, selectAnyRange: BOOL, filteredFontSet: ?*?*IDWriteFontSet1) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontSet1.VTable, self.vtable).GetFilteredFonts(@ptrCast(*const IDWriteFontSet1, self), fontAxisRanges, fontAxisRangeCount, selectAnyRange, filteredFontSet);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSet1_GetFilteredFonts2(self: *const T, properties: ?[*]const DWRITE_FONT_PROPERTY, propertyCount: u32, selectAnyProperty: BOOL, filteredFontSet: ?*?*IDWriteFontSet1) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontSet1.VTable, self.vtable).GetFilteredFonts(@ptrCast(*const IDWriteFontSet1, self), properties, propertyCount, selectAnyProperty, filteredFontSet);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSet1_GetFilteredFontIndices(self: *const T, fontAxisRanges: [*]const DWRITE_FONT_AXIS_RANGE, fontAxisRangeCount: u32, selectAnyRange: BOOL, indices: [*]u32, maxIndexCount: u32, actualIndexCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontSet1.VTable, self.vtable).GetFilteredFontIndices(@ptrCast(*const IDWriteFontSet1, self), fontAxisRanges, fontAxisRangeCount, selectAnyRange, indices, maxIndexCount, actualIndexCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSet1_GetFilteredFontIndices1(self: *const T, properties: [*]const DWRITE_FONT_PROPERTY, propertyCount: u32, selectAnyProperty: BOOL, indices: [*]u32, maxIndexCount: u32, actualIndexCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontSet1.VTable, self.vtable).GetFilteredFontIndices(@ptrCast(*const IDWriteFontSet1, self), properties, propertyCount, selectAnyProperty, indices, maxIndexCount, actualIndexCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSet1_GetFontAxisRanges(self: *const T, listIndex: u32, fontAxisRanges: [*]DWRITE_FONT_AXIS_RANGE, maxFontAxisRangeCount: u32, actualFontAxisRangeCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontSet1.VTable, self.vtable).GetFontAxisRanges(@ptrCast(*const IDWriteFontSet1, self), listIndex, fontAxisRanges, maxFontAxisRangeCount, actualFontAxisRangeCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSet1_GetFontAxisRanges1(self: *const T, fontAxisRanges: [*]DWRITE_FONT_AXIS_RANGE, maxFontAxisRangeCount: u32, actualFontAxisRangeCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontSet1.VTable, self.vtable).GetFontAxisRanges(@ptrCast(*const IDWriteFontSet1, self), fontAxisRanges, maxFontAxisRangeCount, actualFontAxisRangeCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSet1_GetFontFaceReference(self: *const T, listIndex: u32, fontFaceReference: ?*?*IDWriteFontFaceReference1) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontSet1.VTable, self.vtable).GetFontFaceReference(@ptrCast(*const IDWriteFontSet1, self), listIndex, fontFaceReference);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSet1_CreateFontResource(self: *const T, listIndex: u32, fontResource: ?*?*IDWriteFontResource) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontSet1.VTable, self.vtable).CreateFontResource(@ptrCast(*const IDWriteFontSet1, self), listIndex, fontResource);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSet1_CreateFontFace(self: *const T, listIndex: u32, fontFace: ?*?*IDWriteFontFace5) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontSet1.VTable, self.vtable).CreateFontFace(@ptrCast(*const IDWriteFontSet1, self), listIndex, fontFace);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSet1_GetFontLocality(self: *const T, listIndex: u32) callconv(.Inline) DWRITE_LOCALITY {
return @ptrCast(*const IDWriteFontSet1.VTable, self.vtable).GetFontLocality(@ptrCast(*const IDWriteFontSet1, self), listIndex);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDWriteFontList2_Value = Guid.initString("c0763a34-77af-445a-b735-08c37b0a5bf5");
pub const IID_IDWriteFontList2 = &IID_IDWriteFontList2_Value;
pub const IDWriteFontList2 = extern struct {
pub const VTable = extern struct {
base: IDWriteFontList1.VTable,
GetFontSet: fn(
self: *const IDWriteFontList2,
fontSet: ?*?*IDWriteFontSet1,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFontList1.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontList2_GetFontSet(self: *const T, fontSet: ?*?*IDWriteFontSet1) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontList2.VTable, self.vtable).GetFontSet(@ptrCast(*const IDWriteFontList2, self), fontSet);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDWriteFontFamily2_Value = Guid.initString("3ed49e77-a398-4261-b9cf-c126c2131ef3");
pub const IID_IDWriteFontFamily2 = &IID_IDWriteFontFamily2_Value;
pub const IDWriteFontFamily2 = extern struct {
pub const VTable = extern struct {
base: IDWriteFontFamily1.VTable,
GetMatchingFonts: fn(
self: *const IDWriteFontFamily2,
fontAxisValues: [*]const DWRITE_FONT_AXIS_VALUE,
fontAxisValueCount: u32,
matchingFonts: ?*?*IDWriteFontList2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontSet: fn(
self: *const IDWriteFontFamily2,
fontSet: ?*?*IDWriteFontSet1,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFontFamily1.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFamily2_GetMatchingFonts(self: *const T, fontAxisValues: [*]const DWRITE_FONT_AXIS_VALUE, fontAxisValueCount: u32, matchingFonts: ?*?*IDWriteFontList2) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFamily2.VTable, self.vtable).GetMatchingFonts(@ptrCast(*const IDWriteFontFamily2, self), fontAxisValues, fontAxisValueCount, matchingFonts);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFamily2_GetFontSet(self: *const T, fontSet: ?*?*IDWriteFontSet1) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFamily2.VTable, self.vtable).GetFontSet(@ptrCast(*const IDWriteFontFamily2, self), fontSet);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDWriteFontCollection2_Value = Guid.initString("514039c6-4617-4064-bf8b-92ea83e506e0");
pub const IID_IDWriteFontCollection2 = &IID_IDWriteFontCollection2_Value;
pub const IDWriteFontCollection2 = extern struct {
pub const VTable = extern struct {
base: IDWriteFontCollection1.VTable,
GetFontFamily: fn(
self: *const IDWriteFontCollection2,
index: u32,
fontFamily: ?*?*IDWriteFontFamily2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetMatchingFonts: fn(
self: *const IDWriteFontCollection2,
familyName: ?[*:0]const u16,
fontAxisValues: [*]const DWRITE_FONT_AXIS_VALUE,
fontAxisValueCount: u32,
fontList: ?*?*IDWriteFontList2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontFamilyModel: fn(
self: *const IDWriteFontCollection2,
) callconv(@import("std").os.windows.WINAPI) DWRITE_FONT_FAMILY_MODEL,
GetFontSet: fn(
self: *const IDWriteFontCollection2,
fontSet: ?*?*IDWriteFontSet1,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFontCollection1.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontCollection2_GetFontFamily(self: *const T, index: u32, fontFamily: ?*?*IDWriteFontFamily2) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontCollection2.VTable, self.vtable).GetFontFamily(@ptrCast(*const IDWriteFontCollection2, self), index, fontFamily);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontCollection2_GetMatchingFonts(self: *const T, familyName: ?[*:0]const u16, fontAxisValues: [*]const DWRITE_FONT_AXIS_VALUE, fontAxisValueCount: u32, fontList: ?*?*IDWriteFontList2) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontCollection2.VTable, self.vtable).GetMatchingFonts(@ptrCast(*const IDWriteFontCollection2, self), familyName, fontAxisValues, fontAxisValueCount, fontList);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontCollection2_GetFontFamilyModel(self: *const T) callconv(.Inline) DWRITE_FONT_FAMILY_MODEL {
return @ptrCast(*const IDWriteFontCollection2.VTable, self.vtable).GetFontFamilyModel(@ptrCast(*const IDWriteFontCollection2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontCollection2_GetFontSet(self: *const T, fontSet: ?*?*IDWriteFontSet1) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontCollection2.VTable, self.vtable).GetFontSet(@ptrCast(*const IDWriteFontCollection2, self), fontSet);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDWriteTextLayout4_Value = Guid.initString("05a9bf42-223f-4441-b5fb-8263685f55e9");
pub const IID_IDWriteTextLayout4 = &IID_IDWriteTextLayout4_Value;
pub const IDWriteTextLayout4 = extern struct {
pub const VTable = extern struct {
base: IDWriteTextLayout3.VTable,
SetFontAxisValues: fn(
self: *const IDWriteTextLayout4,
fontAxisValues: [*]const DWRITE_FONT_AXIS_VALUE,
fontAxisValueCount: u32,
textRange: DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontAxisValueCount: fn(
self: *const IDWriteTextLayout4,
currentPosition: u32,
) callconv(@import("std").os.windows.WINAPI) u32,
GetFontAxisValues: fn(
self: *const IDWriteTextLayout4,
currentPosition: u32,
fontAxisValues: [*]DWRITE_FONT_AXIS_VALUE,
fontAxisValueCount: u32,
textRange: ?*DWRITE_TEXT_RANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetAutomaticFontAxes: fn(
self: *const IDWriteTextLayout4,
) callconv(@import("std").os.windows.WINAPI) DWRITE_AUTOMATIC_FONT_AXES,
SetAutomaticFontAxes: fn(
self: *const IDWriteTextLayout4,
automaticFontAxes: DWRITE_AUTOMATIC_FONT_AXES,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteTextLayout3.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout4_SetFontAxisValues(self: *const T, fontAxisValues: [*]const DWRITE_FONT_AXIS_VALUE, fontAxisValueCount: u32, textRange: DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout4.VTable, self.vtable).SetFontAxisValues(@ptrCast(*const IDWriteTextLayout4, self), fontAxisValues, fontAxisValueCount, textRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout4_GetFontAxisValueCount(self: *const T, currentPosition: u32) callconv(.Inline) u32 {
return @ptrCast(*const IDWriteTextLayout4.VTable, self.vtable).GetFontAxisValueCount(@ptrCast(*const IDWriteTextLayout4, self), currentPosition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout4_GetFontAxisValues(self: *const T, currentPosition: u32, fontAxisValues: [*]DWRITE_FONT_AXIS_VALUE, fontAxisValueCount: u32, textRange: ?*DWRITE_TEXT_RANGE) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout4.VTable, self.vtable).GetFontAxisValues(@ptrCast(*const IDWriteTextLayout4, self), currentPosition, fontAxisValues, fontAxisValueCount, textRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout4_GetAutomaticFontAxes(self: *const T) callconv(.Inline) DWRITE_AUTOMATIC_FONT_AXES {
return @ptrCast(*const IDWriteTextLayout4.VTable, self.vtable).GetAutomaticFontAxes(@ptrCast(*const IDWriteTextLayout4, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextLayout4_SetAutomaticFontAxes(self: *const T, automaticFontAxes: DWRITE_AUTOMATIC_FONT_AXES) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextLayout4.VTable, self.vtable).SetAutomaticFontAxes(@ptrCast(*const IDWriteTextLayout4, self), automaticFontAxes);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDWriteTextFormat3_Value = Guid.initString("6d3b5641-e550-430d-a85b-b7bf48a93427");
pub const IID_IDWriteTextFormat3 = &IID_IDWriteTextFormat3_Value;
pub const IDWriteTextFormat3 = extern struct {
pub const VTable = extern struct {
base: IDWriteTextFormat2.VTable,
SetFontAxisValues: fn(
self: *const IDWriteTextFormat3,
fontAxisValues: [*]const DWRITE_FONT_AXIS_VALUE,
fontAxisValueCount: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontAxisValueCount: fn(
self: *const IDWriteTextFormat3,
) callconv(@import("std").os.windows.WINAPI) u32,
GetFontAxisValues: fn(
self: *const IDWriteTextFormat3,
fontAxisValues: [*]DWRITE_FONT_AXIS_VALUE,
fontAxisValueCount: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetAutomaticFontAxes: fn(
self: *const IDWriteTextFormat3,
) callconv(@import("std").os.windows.WINAPI) DWRITE_AUTOMATIC_FONT_AXES,
SetAutomaticFontAxes: fn(
self: *const IDWriteTextFormat3,
automaticFontAxes: DWRITE_AUTOMATIC_FONT_AXES,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteTextFormat2.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat3_SetFontAxisValues(self: *const T, fontAxisValues: [*]const DWRITE_FONT_AXIS_VALUE, fontAxisValueCount: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextFormat3.VTable, self.vtable).SetFontAxisValues(@ptrCast(*const IDWriteTextFormat3, self), fontAxisValues, fontAxisValueCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat3_GetFontAxisValueCount(self: *const T) callconv(.Inline) u32 {
return @ptrCast(*const IDWriteTextFormat3.VTable, self.vtable).GetFontAxisValueCount(@ptrCast(*const IDWriteTextFormat3, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat3_GetFontAxisValues(self: *const T, fontAxisValues: [*]DWRITE_FONT_AXIS_VALUE, fontAxisValueCount: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextFormat3.VTable, self.vtable).GetFontAxisValues(@ptrCast(*const IDWriteTextFormat3, self), fontAxisValues, fontAxisValueCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat3_GetAutomaticFontAxes(self: *const T) callconv(.Inline) DWRITE_AUTOMATIC_FONT_AXES {
return @ptrCast(*const IDWriteTextFormat3.VTable, self.vtable).GetAutomaticFontAxes(@ptrCast(*const IDWriteTextFormat3, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteTextFormat3_SetAutomaticFontAxes(self: *const T, automaticFontAxes: DWRITE_AUTOMATIC_FONT_AXES) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteTextFormat3.VTable, self.vtable).SetAutomaticFontAxes(@ptrCast(*const IDWriteTextFormat3, self), automaticFontAxes);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDWriteFontFallback1_Value = Guid.initString("2397599d-dd0d-4681-bd6a-f4f31eaade77");
pub const IID_IDWriteFontFallback1 = &IID_IDWriteFontFallback1_Value;
pub const IDWriteFontFallback1 = extern struct {
pub const VTable = extern struct {
base: IDWriteFontFallback.VTable,
MapCharacters: fn(
self: *const IDWriteFontFallback1,
analysisSource: ?*IDWriteTextAnalysisSource,
textPosition: u32,
textLength: u32,
baseFontCollection: ?*IDWriteFontCollection,
baseFamilyName: ?[*:0]const u16,
fontAxisValues: [*]const DWRITE_FONT_AXIS_VALUE,
fontAxisValueCount: u32,
mappedLength: ?*u32,
scale: ?*f32,
mappedFontFace: ?*?*IDWriteFontFace5,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFontFallback.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFallback1_MapCharacters(self: *const T, analysisSource: ?*IDWriteTextAnalysisSource, textPosition: u32, textLength: u32, baseFontCollection: ?*IDWriteFontCollection, baseFamilyName: ?[*:0]const u16, fontAxisValues: [*]const DWRITE_FONT_AXIS_VALUE, fontAxisValueCount: u32, mappedLength: ?*u32, scale: ?*f32, mappedFontFace: ?*?*IDWriteFontFace5) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFallback1.VTable, self.vtable).MapCharacters(@ptrCast(*const IDWriteFontFallback1, self), analysisSource, textPosition, textLength, baseFontCollection, baseFamilyName, fontAxisValues, fontAxisValueCount, mappedLength, scale, mappedFontFace);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDWriteFontSet2_Value = Guid.initString("dc7ead19-e54c-43af-b2da-4e2b79ba3f7f");
pub const IID_IDWriteFontSet2 = &IID_IDWriteFontSet2_Value;
pub const IDWriteFontSet2 = extern struct {
pub const VTable = extern struct {
base: IDWriteFontSet1.VTable,
GetExpirationEvent: fn(
self: *const IDWriteFontSet2,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFontSet1.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSet2_GetExpirationEvent(self: *const T) callconv(.Inline) ?HANDLE {
return @ptrCast(*const IDWriteFontSet2.VTable, self.vtable).GetExpirationEvent(@ptrCast(*const IDWriteFontSet2, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDWriteFontCollection3_Value = Guid.initString("a4d055a6-f9e3-4e25-93b7-9e309f3af8e9");
pub const IID_IDWriteFontCollection3 = &IID_IDWriteFontCollection3_Value;
pub const IDWriteFontCollection3 = extern struct {
pub const VTable = extern struct {
base: IDWriteFontCollection2.VTable,
GetExpirationEvent: fn(
self: *const IDWriteFontCollection3,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFontCollection2.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontCollection3_GetExpirationEvent(self: *const T) callconv(.Inline) ?HANDLE {
return @ptrCast(*const IDWriteFontCollection3.VTable, self.vtable).GetExpirationEvent(@ptrCast(*const IDWriteFontCollection3, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDWriteFactory7_Value = Guid.initString("35d0e0b3-9076-4d2e-a016-a91b568a06b4");
pub const IID_IDWriteFactory7 = &IID_IDWriteFactory7_Value;
pub const IDWriteFactory7 = extern struct {
pub const VTable = extern struct {
base: IDWriteFactory6.VTable,
GetSystemFontSet: fn(
self: *const IDWriteFactory7,
includeDownloadableFonts: BOOL,
fontSet: ?*?*IDWriteFontSet2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSystemFontCollection: fn(
self: *const IDWriteFactory7,
includeDownloadableFonts: BOOL,
fontFamilyModel: DWRITE_FONT_FAMILY_MODEL,
fontCollection: ?*?*IDWriteFontCollection3,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFactory6.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory7_GetSystemFontSet(self: *const T, includeDownloadableFonts: BOOL, fontSet: ?*?*IDWriteFontSet2) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory7.VTable, self.vtable).GetSystemFontSet(@ptrCast(*const IDWriteFactory7, self), includeDownloadableFonts, fontSet);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFactory7_GetSystemFontCollection(self: *const T, includeDownloadableFonts: BOOL, fontFamilyModel: DWRITE_FONT_FAMILY_MODEL, fontCollection: ?*?*IDWriteFontCollection3) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFactory7.VTable, self.vtable).GetSystemFontCollection(@ptrCast(*const IDWriteFactory7, self), includeDownloadableFonts, fontFamilyModel, fontCollection);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DWRITE_FONT_SOURCE_TYPE = enum(i32) {
UNKNOWN = 0,
PER_MACHINE = 1,
PER_USER = 2,
APPX_PACKAGE = 3,
REMOTE_FONT_PROVIDER = 4,
};
pub const DWRITE_FONT_SOURCE_TYPE_UNKNOWN = DWRITE_FONT_SOURCE_TYPE.UNKNOWN;
pub const DWRITE_FONT_SOURCE_TYPE_PER_MACHINE = DWRITE_FONT_SOURCE_TYPE.PER_MACHINE;
pub const DWRITE_FONT_SOURCE_TYPE_PER_USER = DWRITE_FONT_SOURCE_TYPE.PER_USER;
pub const DWRITE_FONT_SOURCE_TYPE_APPX_PACKAGE = DWRITE_FONT_SOURCE_TYPE.APPX_PACKAGE;
pub const DWRITE_FONT_SOURCE_TYPE_REMOTE_FONT_PROVIDER = DWRITE_FONT_SOURCE_TYPE.REMOTE_FONT_PROVIDER;
const IID_IDWriteFontSet3_Value = Guid.initString("7c073ef2-a7f4-4045-8c32-8ab8ae640f90");
pub const IID_IDWriteFontSet3 = &IID_IDWriteFontSet3_Value;
pub const IDWriteFontSet3 = extern struct {
pub const VTable = extern struct {
base: IDWriteFontSet2.VTable,
GetFontSourceType: fn(
self: *const IDWriteFontSet3,
fontIndex: u32,
) callconv(@import("std").os.windows.WINAPI) DWRITE_FONT_SOURCE_TYPE,
GetFontSourceNameLength: fn(
self: *const IDWriteFontSet3,
listIndex: u32,
) callconv(@import("std").os.windows.WINAPI) u32,
GetFontSourceName: fn(
self: *const IDWriteFontSet3,
listIndex: u32,
stringBuffer: [*:0]u16,
stringBufferSize: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFontSet2.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSet3_GetFontSourceType(self: *const T, fontIndex: u32) callconv(.Inline) DWRITE_FONT_SOURCE_TYPE {
return @ptrCast(*const IDWriteFontSet3.VTable, self.vtable).GetFontSourceType(@ptrCast(*const IDWriteFontSet3, self), fontIndex);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSet3_GetFontSourceNameLength(self: *const T, listIndex: u32) callconv(.Inline) u32 {
return @ptrCast(*const IDWriteFontSet3.VTable, self.vtable).GetFontSourceNameLength(@ptrCast(*const IDWriteFontSet3, self), listIndex);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontSet3_GetFontSourceName(self: *const T, listIndex: u32, stringBuffer: [*:0]u16, stringBufferSize: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontSet3.VTable, self.vtable).GetFontSourceName(@ptrCast(*const IDWriteFontSet3, self), listIndex, stringBuffer, stringBufferSize);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDWriteFontFace6_Value = Guid.initString("c4b1fe1b-6e84-47d5-b54c-a597981b06ad");
pub const IID_IDWriteFontFace6 = &IID_IDWriteFontFace6_Value;
pub const IDWriteFontFace6 = extern struct {
pub const VTable = extern struct {
base: IDWriteFontFace5.VTable,
GetFamilyNames: fn(
self: *const IDWriteFontFace6,
fontFamilyModel: DWRITE_FONT_FAMILY_MODEL,
names: ?*?*IDWriteLocalizedStrings,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFaceNames: fn(
self: *const IDWriteFontFace6,
fontFamilyModel: DWRITE_FONT_FAMILY_MODEL,
names: ?*?*IDWriteLocalizedStrings,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDWriteFontFace5.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace6_GetFamilyNames(self: *const T, fontFamilyModel: DWRITE_FONT_FAMILY_MODEL, names: ?*?*IDWriteLocalizedStrings) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFace6.VTable, self.vtable).GetFamilyNames(@ptrCast(*const IDWriteFontFace6, self), fontFamilyModel, names);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDWriteFontFace6_GetFaceNames(self: *const T, fontFamilyModel: DWRITE_FONT_FAMILY_MODEL, names: ?*?*IDWriteLocalizedStrings) callconv(.Inline) HRESULT {
return @ptrCast(*const IDWriteFontFace6.VTable, self.vtable).GetFaceNames(@ptrCast(*const IDWriteFontFace6, self), fontFamilyModel, names);
}
};}
pub usingnamespace MethodMixin(@This());
};
//--------------------------------------------------------------------------------
// Section: Functions (1)
//--------------------------------------------------------------------------------
// TODO: this type is limited to platform 'windows6.1'
pub extern "DWrite" fn DWriteCreateFactory(
factoryType: DWRITE_FACTORY_TYPE,
iid: ?*const Guid,
factory: ?*?*IUnknown,
) 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 (18)
//--------------------------------------------------------------------------------
const Guid = @import("../zig.zig").Guid;
const BOOL = @import("../foundation.zig").BOOL;
const D2D_POINT_2F = @import("../graphics/direct2d/common.zig").D2D_POINT_2F;
const D2D_SIZE_U = @import("../graphics/direct2d/common.zig").D2D_SIZE_U;
const FILETIME = @import("../foundation.zig").FILETIME;
const FONTSIGNATURE = @import("../globalization.zig").FONTSIGNATURE;
const HANDLE = @import("../foundation.zig").HANDLE;
const HDC = @import("../graphics/gdi.zig").HDC;
const HMONITOR = @import("../graphics/gdi.zig").HMONITOR;
const HRESULT = @import("../foundation.zig").HRESULT;
const ID2D1SimplifiedGeometrySink = @import("../graphics/direct2d/common.zig").ID2D1SimplifiedGeometrySink;
const IUnknown = @import("../system/com.zig").IUnknown;
const LOGFONTA = @import("../graphics/gdi.zig").LOGFONTA;
const LOGFONTW = @import("../graphics/gdi.zig").LOGFONTW;
const POINT = @import("../foundation.zig").POINT;
const PWSTR = @import("../foundation.zig").PWSTR;
const RECT = @import("../foundation.zig").RECT;
const SIZE = @import("../foundation.zig").SIZE;
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/graphics/direct_write.zig |
pub const PERCEIVEDFLAG_UNDEFINED = @as(u32, 0);
pub const PERCEIVEDFLAG_SOFTCODED = @as(u32, 1);
pub const PERCEIVEDFLAG_HARDCODED = @as(u32, 2);
pub const PERCEIVEDFLAG_NATIVESUPPORT = @as(u32, 4);
pub const PERCEIVEDFLAG_GDIPLUS = @as(u32, 16);
pub const PERCEIVEDFLAG_WMSDK = @as(u32, 32);
pub const PERCEIVEDFLAG_ZIPFOLDER = @as(u32, 64);
//--------------------------------------------------------------------------------
// Section: Types (11)
//--------------------------------------------------------------------------------
pub const SHITEMID = packed struct {
cb: u16,
abID: [1]u8,
};
pub const ITEMIDLIST = extern struct {
mkid: SHITEMID,
};
pub const STRRET_TYPE = enum(i32) {
WSTR = 0,
OFFSET = 1,
CSTR = 2,
};
pub const STRRET_WSTR = STRRET_TYPE.WSTR;
pub const STRRET_OFFSET = STRRET_TYPE.OFFSET;
pub const STRRET_CSTR = STRRET_TYPE.CSTR;
pub const STRRET = extern struct {
uType: u32,
Anonymous: extern union {
pOleStr: ?PWSTR,
uOffset: u32,
cStr: [260]u8,
},
};
pub const SHELLDETAILS = packed struct {
fmt: i32,
cxChar: i32,
str: STRRET,
};
pub const PERCEIVED = enum(i32) {
FIRST = -3,
// CUSTOM = -3, this enum value conflicts with FIRST
UNSPECIFIED = -2,
FOLDER = -1,
UNKNOWN = 0,
TEXT = 1,
IMAGE = 2,
AUDIO = 3,
VIDEO = 4,
COMPRESSED = 5,
DOCUMENT = 6,
SYSTEM = 7,
APPLICATION = 8,
GAMEMEDIA = 9,
CONTACTS = 10,
// LAST = 10, this enum value conflicts with CONTACTS
};
pub const PERCEIVED_TYPE_FIRST = PERCEIVED.FIRST;
pub const PERCEIVED_TYPE_CUSTOM = PERCEIVED.FIRST;
pub const PERCEIVED_TYPE_UNSPECIFIED = PERCEIVED.UNSPECIFIED;
pub const PERCEIVED_TYPE_FOLDER = PERCEIVED.FOLDER;
pub const PERCEIVED_TYPE_UNKNOWN = PERCEIVED.UNKNOWN;
pub const PERCEIVED_TYPE_TEXT = PERCEIVED.TEXT;
pub const PERCEIVED_TYPE_IMAGE = PERCEIVED.IMAGE;
pub const PERCEIVED_TYPE_AUDIO = PERCEIVED.AUDIO;
pub const PERCEIVED_TYPE_VIDEO = PERCEIVED.VIDEO;
pub const PERCEIVED_TYPE_COMPRESSED = PERCEIVED.COMPRESSED;
pub const PERCEIVED_TYPE_DOCUMENT = PERCEIVED.DOCUMENT;
pub const PERCEIVED_TYPE_SYSTEM = PERCEIVED.SYSTEM;
pub const PERCEIVED_TYPE_APPLICATION = PERCEIVED.APPLICATION;
pub const PERCEIVED_TYPE_GAMEMEDIA = PERCEIVED.GAMEMEDIA;
pub const PERCEIVED_TYPE_CONTACTS = PERCEIVED.CONTACTS;
pub const PERCEIVED_TYPE_LAST = PERCEIVED.CONTACTS;
pub const COMDLG_FILTERSPEC = extern struct {
pszName: ?[*:0]const u16,
pszSpec: ?[*:0]const u16,
};
pub const SHCOLSTATE = enum(i32) {
DEFAULT = 0,
TYPE_STR = 1,
TYPE_INT = 2,
TYPE_DATE = 3,
TYPEMASK = 15,
ONBYDEFAULT = 16,
SLOW = 32,
EXTENDED = 64,
SECONDARYUI = 128,
HIDDEN = 256,
PREFER_VARCMP = 512,
PREFER_FMTCMP = 1024,
NOSORTBYFOLDERNESS = 2048,
VIEWONLY = 65536,
BATCHREAD = 131072,
NO_GROUPBY = 262144,
FIXED_WIDTH = 4096,
NODPISCALE = 8192,
FIXED_RATIO = 16384,
DISPLAYMASK = 61440,
};
pub const SHCOLSTATE_DEFAULT = SHCOLSTATE.DEFAULT;
pub const SHCOLSTATE_TYPE_STR = SHCOLSTATE.TYPE_STR;
pub const SHCOLSTATE_TYPE_INT = SHCOLSTATE.TYPE_INT;
pub const SHCOLSTATE_TYPE_DATE = SHCOLSTATE.TYPE_DATE;
pub const SHCOLSTATE_TYPEMASK = SHCOLSTATE.TYPEMASK;
pub const SHCOLSTATE_ONBYDEFAULT = SHCOLSTATE.ONBYDEFAULT;
pub const SHCOLSTATE_SLOW = SHCOLSTATE.SLOW;
pub const SHCOLSTATE_EXTENDED = SHCOLSTATE.EXTENDED;
pub const SHCOLSTATE_SECONDARYUI = SHCOLSTATE.SECONDARYUI;
pub const SHCOLSTATE_HIDDEN = SHCOLSTATE.HIDDEN;
pub const SHCOLSTATE_PREFER_VARCMP = SHCOLSTATE.PREFER_VARCMP;
pub const SHCOLSTATE_PREFER_FMTCMP = SHCOLSTATE.PREFER_FMTCMP;
pub const SHCOLSTATE_NOSORTBYFOLDERNESS = SHCOLSTATE.NOSORTBYFOLDERNESS;
pub const SHCOLSTATE_VIEWONLY = SHCOLSTATE.VIEWONLY;
pub const SHCOLSTATE_BATCHREAD = SHCOLSTATE.BATCHREAD;
pub const SHCOLSTATE_NO_GROUPBY = SHCOLSTATE.NO_GROUPBY;
pub const SHCOLSTATE_FIXED_WIDTH = SHCOLSTATE.FIXED_WIDTH;
pub const SHCOLSTATE_NODPISCALE = SHCOLSTATE.NODPISCALE;
pub const SHCOLSTATE_FIXED_RATIO = SHCOLSTATE.FIXED_RATIO;
pub const SHCOLSTATE_DISPLAYMASK = SHCOLSTATE.DISPLAYMASK;
pub const DEVICE_SCALE_FACTOR = enum(i32) {
DEVICE_SCALE_FACTOR_INVALID = 0,
SCALE_100_PERCENT = 100,
SCALE_120_PERCENT = 120,
SCALE_125_PERCENT = 125,
SCALE_140_PERCENT = 140,
SCALE_150_PERCENT = 150,
SCALE_160_PERCENT = 160,
SCALE_175_PERCENT = 175,
SCALE_180_PERCENT = 180,
SCALE_200_PERCENT = 200,
SCALE_225_PERCENT = 225,
SCALE_250_PERCENT = 250,
SCALE_300_PERCENT = 300,
SCALE_350_PERCENT = 350,
SCALE_400_PERCENT = 400,
SCALE_450_PERCENT = 450,
SCALE_500_PERCENT = 500,
};
pub const DEVICE_SCALE_FACTOR_INVALID = DEVICE_SCALE_FACTOR.DEVICE_SCALE_FACTOR_INVALID;
pub const SCALE_100_PERCENT = DEVICE_SCALE_FACTOR.SCALE_100_PERCENT;
pub const SCALE_120_PERCENT = DEVICE_SCALE_FACTOR.SCALE_120_PERCENT;
pub const SCALE_125_PERCENT = DEVICE_SCALE_FACTOR.SCALE_125_PERCENT;
pub const SCALE_140_PERCENT = DEVICE_SCALE_FACTOR.SCALE_140_PERCENT;
pub const SCALE_150_PERCENT = DEVICE_SCALE_FACTOR.SCALE_150_PERCENT;
pub const SCALE_160_PERCENT = DEVICE_SCALE_FACTOR.SCALE_160_PERCENT;
pub const SCALE_175_PERCENT = DEVICE_SCALE_FACTOR.SCALE_175_PERCENT;
pub const SCALE_180_PERCENT = DEVICE_SCALE_FACTOR.SCALE_180_PERCENT;
pub const SCALE_200_PERCENT = DEVICE_SCALE_FACTOR.SCALE_200_PERCENT;
pub const SCALE_225_PERCENT = DEVICE_SCALE_FACTOR.SCALE_225_PERCENT;
pub const SCALE_250_PERCENT = DEVICE_SCALE_FACTOR.SCALE_250_PERCENT;
pub const SCALE_300_PERCENT = DEVICE_SCALE_FACTOR.SCALE_300_PERCENT;
pub const SCALE_350_PERCENT = DEVICE_SCALE_FACTOR.SCALE_350_PERCENT;
pub const SCALE_400_PERCENT = DEVICE_SCALE_FACTOR.SCALE_400_PERCENT;
pub const SCALE_450_PERCENT = DEVICE_SCALE_FACTOR.SCALE_450_PERCENT;
pub const SCALE_500_PERCENT = DEVICE_SCALE_FACTOR.SCALE_500_PERCENT;
// TODO: this type is limited to platform 'windows6.1'
const IID_IObjectArray_Value = Guid.initString("92ca9dcd-5622-4bba-a805-5e9f541bd8c9");
pub const IID_IObjectArray = &IID_IObjectArray_Value;
pub const IObjectArray = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetCount: fn(
self: *const IObjectArray,
pcObjects: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetAt: fn(
self: *const IObjectArray,
uiIndex: u32,
riid: ?*const Guid,
ppv: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IObjectArray_GetCount(self: *const T, pcObjects: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IObjectArray.VTable, self.vtable).GetCount(@ptrCast(*const IObjectArray, self), pcObjects);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IObjectArray_GetAt(self: *const T, uiIndex: u32, riid: ?*const Guid, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IObjectArray.VTable, self.vtable).GetAt(@ptrCast(*const IObjectArray, self), uiIndex, riid, ppv);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IObjectCollection_Value = Guid.initString("5632b1a4-e38a-400a-928a-d4cd63230295");
pub const IID_IObjectCollection = &IID_IObjectCollection_Value;
pub const IObjectCollection = extern struct {
pub const VTable = extern struct {
base: IObjectArray.VTable,
AddObject: fn(
self: *const IObjectCollection,
punk: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddFromArray: fn(
self: *const IObjectCollection,
poaSource: ?*IObjectArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveObjectAt: fn(
self: *const IObjectCollection,
uiIndex: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clear: fn(
self: *const IObjectCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IObjectArray.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IObjectCollection_AddObject(self: *const T, punk: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IObjectCollection.VTable, self.vtable).AddObject(@ptrCast(*const IObjectCollection, self), punk);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IObjectCollection_AddFromArray(self: *const T, poaSource: ?*IObjectArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IObjectCollection.VTable, self.vtable).AddFromArray(@ptrCast(*const IObjectCollection, self), poaSource);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IObjectCollection_RemoveObjectAt(self: *const T, uiIndex: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IObjectCollection.VTable, self.vtable).RemoveObjectAt(@ptrCast(*const IObjectCollection, self), uiIndex);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IObjectCollection_Clear(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IObjectCollection.VTable, self.vtable).Clear(@ptrCast(*const IObjectCollection, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
//--------------------------------------------------------------------------------
// Section: Functions (0)
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (0)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../../zig.zig").unicode_mode) {
.ansi => struct {
},
.wide => struct {
},
.unspecified => if (@import("builtin").is_test) struct {
} else struct {
},
};
//--------------------------------------------------------------------------------
// Section: Imports (4)
//--------------------------------------------------------------------------------
const Guid = @import("../../zig.zig").Guid;
const HRESULT = @import("../../foundation.zig").HRESULT;
const IUnknown = @import("../../system/com.zig").IUnknown;
const PWSTR = @import("../../foundation.zig").PWSTR;
test {
@setEvalBranchQuota(
@import("std").meta.declarations(@This()).len * 3
);
// reference all the pub declarations
if (!@import("builtin").is_test) return;
inline for (@import("std").meta.declarations(@This())) |decl| {
if (decl.is_pub) {
_ = decl;
}
}
} | win32/ui/shell/common.zig |
pub const MBEDTLS_ERR_PK_ALLOC_FAILED = -0x3F80;
pub const MBEDTLS_ERR_PK_BAD_INPUT_DATA = -0x3E80;
pub const MBEDTLS_ERR_PK_FILE_IO_ERROR = -0x3E00;
pub const MBEDTLS_ERR_ERROR_GENERIC_ERROR = -0x0001;
pub const MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED = -0x006E;
pub const MBEDTLS_ERR_AES_BAD_INPUT_DATA = -0x0021;
pub const MBEDTLS_ERR_AES_INVALID_KEY_LENGTH = -0x0020;
pub const MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH = -0x0022;
pub const MBEDTLS_ERR_NET_UNKNOWN_HOST = -0x0052;
pub const MBEDTLS_ERR_NET_SOCKET_FAILED = -0x0042;
pub const MBEDTLS_ERR_NET_CONNECT_FAILED = -0x0044;
pub const MBEDTLS_ERR_NET_INVALID_CONTEXT = -0x0045;
pub const MBEDTLS_ERR_NET_CONN_RESET = -0x0050;
pub const MBEDTLS_ERR_NET_SEND_FAILED = -0x004E;
pub const MBEDTLS_ERR_MPI_BAD_INPUT_DATA = -0x0004;
pub const MBEDTLS_SSL_VERIFY_NONE = 0;
pub const MBEDTLS_SSL_VERIFY_OPTIONAL = 1;
pub const MBEDTLS_SSL_VERIFY_REQUIRED = 2;
pub const MBEDTLS_SSL_PRESET_DEFAULT = 0;
pub const MBEDTLS_SSL_PRESET_SUITEB = 2;
pub const MBEDTLS_ERR_SSL_BAD_INPUT_DATA = -0x7100;
pub const MBEDTLS_ERR_SSL_ALLOC_FAILED = -0x7F00;
pub const MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE = -0x7080;
pub const MBEDTLS_ERR_SSL_WANT_WRITE = -0x6880;
pub const MBEDTLS_ERR_SSL_WANT_READ = -0x6900;
pub const MBEDTLS_ERR_SSL_INTERNAL_ERROR = -0x6C00;
pub const MBEDTLS_ERR_SSL_HW_ACCEL_FAILED = -0x7F80;
pub const MBEDTLS_ERR_SSL_COMPRESSION_FAILED = -0x6F00;
pub const MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL = -0x6A00;
pub const MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY = -0x7880;
pub const MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA = -0x6100;
pub const MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED = -0x6400;
pub const MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE = -0x6080;
pub const MBEDTLS_ERR_CIPHER_INVALID_CONTEXT = -0x6380;
pub const MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED = -0x6280; | src/bits.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 parseInt = std.fmt.parseInt;
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const util = @import("util.zig");
const gpa = util.gpa;
const data = @embedFile("../data/day02.txt");
pub fn main() !void {
var instructions = std.ArrayList(Instruction).init(gpa);
defer instructions.deinit();
// Parse input into instruction list
var lineIterator = std.mem.tokenize(u8, data, "\n");
while (lineIterator.next()) |line| {
if (line.len == 0) continue;
var parts = std.mem.split(u8, line, " ");
const command = parts.next().?;
const distance = try parseInt(u32, parts.next().?, 10);
const instruction = Instruction{ .direction = switch (command[0]) {
'f' => .Forward,
'u' => .Up,
'd' => .Down,
else => unreachable,
}, .distance = distance };
try instructions.append(instruction);
}
// Act on instructions
var submarine = Submarine.init();
for (instructions.items) |inst| {
switch (inst.direction) {
.Forward => submarine.MoveForward(inst.distance),
.Up => submarine.MoveUp(inst.distance),
.Down => submarine.MoveDown(inst.distance),
}
}
// Part1
const resultPart1 = submarine.aim * submarine.distance;
std.debug.assert(resultPart1 == 2187380);
std.debug.print("Submarine value1 {}\n", .{resultPart1});
// Part 2
const resultPart2 = submarine.depth * submarine.distance;
std.debug.assert(result == 2086357770);
std.debug.print("Submarine value2 {}\n", .{resultPart2});
}
const Direction = enum { Forward, Down, Up };
const Instruction = struct { direction: Direction, distance: usize };
const Submarine = struct {
const Self = @This();
distance: usize = 0,
depth: usize = 0,
aim: usize = 0,
pub fn init() Submarine {
return Submarine{
.distance = 0,
.depth = 0,
.aim = 0,
};
}
pub fn MoveForward(this: *Self, distance: usize) void {
this.distance += distance;
this.depth += this.aim * distance;
}
pub fn MoveUp(this: *Self, distance: usize) void {
this.aim -= distance;
}
pub fn MoveDown(this: *Self, distance: usize) void {
this.aim += distance;
}
}; | src/day02.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/13.txt", .{});
defer input_file.close();
var buffered_reader = std.io.bufferedReader(input_file.reader());
const count = try fold(allocator, buffered_reader.reader());
std.debug.print("number of dots after one fold: {}\n", .{count});
}
const Point = packed struct { x: u32, y: u32 };
fn fold(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 parse_mode: enum { dots, fold_instructions } = .dots;
var dots = std.ArrayList(u64).init(allocator);
while (try reader.readUntilDelimiterOrEof(&buf, '\n')) |line| {
switch (parse_mode) {
.dots => {
if (line.len == 0) {
parse_mode = .fold_instructions;
} else {
var iter = std.mem.split(u8, line, ",");
const x = try std.fmt.parseInt(u32, iter.next() orelse return error.WrongFormat, 10);
const y = try std.fmt.parseInt(u32, iter.next() orelse return error.WrongFormat, 10);
if (iter.next() != null) return error.WrongFormat;
try dots.append(@bitCast(u64, Point{ .x = x, .y = y }));
}
},
.fold_instructions => {
var iter = std.mem.split(u8, line, "=");
const axis_x_y = iter.next() orelse return error.WrongFormat;
const axis_pos = try std.fmt.parseInt(u32, iter.next() orelse return error.WrongFormat, 10);
if (iter.next() != null) return error.WrongFormat;
if (std.mem.eql(u8, "fold along x", axis_x_y)) {
var i: usize = 0;
while (i < dots.items.len) : (i += 1) {
const p = @bitCast(Point, dots.items[i]);
if (p.x > axis_pos) {
const new_x = p.x - (2 * (p.x - axis_pos));
const new_p = Point{ .x = new_x, .y = p.y };
const already_exists_before = i > 0 and std.mem.indexOfScalar(u64, dots.items[0 .. i - 1], @bitCast(u64, new_p)) != null;
const already_exists_after = std.mem.indexOfScalarPos(u64, dots.items, i + 1, @bitCast(u64, new_p)) != null;
const already_exists = already_exists_before or already_exists_after;
if (already_exists) {
_ = dots.swapRemove(i);
i -= 1;
} else {
dots.items[i] = @bitCast(u64, new_p);
}
}
}
} else if (std.mem.eql(u8, "fold along y", axis_x_y)) {
var i: usize = 0;
while (i < dots.items.len) : (i += 1) {
const p = @bitCast(Point, dots.items[i]);
if (p.y > axis_pos) {
const new_y = p.y - (2 * (p.y - axis_pos));
const new_p = Point{ .x = p.x, .y = new_y };
const already_exists_before = i > 0 and std.mem.indexOfScalar(u64, dots.items[0 .. i - 1], @bitCast(u64, new_p)) != null;
const already_exists_after = std.mem.indexOfScalarPos(u64, dots.items, i + 1, @bitCast(u64, new_p)) != null;
const already_exists = already_exists_before or already_exists_after;
if (already_exists) {
_ = dots.swapRemove(i);
i -= 1;
} else {
dots.items[i] = @bitCast(u64, new_p);
}
}
}
} else unreachable;
return dots.items.len;
},
}
}
return error.NoFoldInstruction;
}
test "example 1" {
const text =
\\6,10
\\0,14
\\9,10
\\0,3
\\10,4
\\4,11
\\6,0
\\6,12
\\4,1
\\0,13
\\10,12
\\3,4
\\3,0
\\8,4
\\1,10
\\2,14
\\8,10
\\9,0
\\
\\fold along y=7
\\fold along x=5
;
var fbs = std.io.fixedBufferStream(text);
const count = try fold(std.testing.allocator, fbs.reader());
try std.testing.expectEqual(@as(u64, 17), count);
} | src/13.zig |
const std = @import("std");
const Target = std.Target;
const llvm = @import("llvm.zig");
pub fn getDarwinArchString(self: Target) [:0]const u8 {
const arch = self.getArch();
switch (arch) {
.aarch64 => return "arm64",
.thumb,
.arm,
=> return "arm",
.powerpc => return "ppc",
.powerpc64 => return "ppc64",
.powerpc64le => return "ppc64le",
// @tagName should be able to return sentinel terminated slice
else => @panic("TODO https://github.com/ziglang/zig/issues/3779"), //return @tagName(arch),
}
}
pub fn llvmTargetFromTriple(triple: std.Buffer) !*llvm.Target {
var result: *llvm.Target = undefined;
var err_msg: [*:0]u8 = undefined;
if (llvm.GetTargetFromTriple(triple.toSlice(), &result, &err_msg) != 0) {
std.debug.warn("triple: {s} error: {s}\n", .{ triple.toSlice(), err_msg });
return error.UnsupportedTarget;
}
return result;
}
pub fn initializeAllTargets() void {
llvm.InitializeAllTargets();
llvm.InitializeAllTargetInfos();
llvm.InitializeAllTargetMCs();
llvm.InitializeAllAsmPrinters();
llvm.InitializeAllAsmParsers();
}
pub fn getTriple(allocator: *std.mem.Allocator, self: std.Target) !std.Buffer {
var result = try std.Buffer.initSize(allocator, 0);
errdefer result.deinit();
// LLVM WebAssembly output support requires the target to be activated at
// build type with -DCMAKE_LLVM_EXPIERMENTAL_TARGETS_TO_BUILD=WebAssembly.
//
// LLVM determines the output format based on the abi suffix,
// defaulting to an object based on the architecture. The default format in
// LLVM 6 sets the wasm arch output incorrectly to ELF. We need to
// explicitly set this ourself in order for it to work.
//
// This is fixed in LLVM 7 and you will be able to get wasm output by
// using the target triple `wasm32-unknown-unknown-unknown`.
const env_name = if (self.isWasm()) "wasm" else @tagName(self.getAbi());
var out = &std.io.BufferOutStream.init(&result).stream;
try out.print("{}-unknown-{}-{}", .{ @tagName(self.getArch()), @tagName(self.getOs()), env_name });
return result;
} | src-self-hosted/util.zig |
const sqrt = @import("std").math.sqrt;
pub fn Vector(comptime T: type) type {
return struct {
const Self = @This();
x: T,
y: T,
z: T,
pub fn new(x: T, y: T, z: T) Self {
return Self{ .x = x, .y = y, .z = z };
}
pub fn up() Self {
return Self{ .x = 0.0, .y = 1.0, .z = 0.0 };
}
pub fn zero() Self {
return Self{ .x = 0.0, .y = 0.0, .z = 0.0 };
}
pub fn white() Self {
return Self{ .x = 255.0, .y = 255.0, .z = 255.0 };
}
pub fn dot_product(self: Self, v: Self) T {
return (self.x * v.x) + (self.y * v.y) + (self.z * v.z);
}
pub fn cross_product(self: Self, v: Self) Self {
return Self {
.x = (self.y * v.z) - (self.z * v.y),
.y = (self.z * v.x) - (self.x * v.z),
.z = (self.x * v.y) - (self.y * v.x),
};
}
pub fn scale(self: Self, factor: T) Self {
return Self {
.x = self.x * factor,
.y = self.y * factor,
.z = self.z * factor,
};
}
pub fn unit(self: Self) Self {
return self.scale(1.0 / self.length());
}
pub fn add(self: Self, v: Self) Self {
return Self {
.x = self.x + v.x,
.y = self.y + v.y,
.z = self.z + v.z,
};
}
pub fn add3(self: Self, v: Self, w: Self) Self {
return Self {
.x = self.x + v.x + w.x,
.y = self.y + v.y + w.y,
.z = self.z + v.z + w.z,
};
}
pub fn subtract(self: Self, v: Self) Self {
return Self {
.x = self.x - v.x,
.y = self.y - v.y,
.z = self.z - v.z,
};
}
pub fn negate(self: Self) Self {
return Self {
.x = -self.x,
.y = -self.y,
.z = -self.z,
};
}
pub fn length(self: Self) T {
return sqrt(self.dot_product(self));
}
pub fn reflect_through(self: Self, normal: Self) Self {
const a = self.dot_product(normal);
const d = normal.scale(a);
const e = d.scale(2.0);
return self.subtract(e);
}
};
} | zigray/vector.zig |
const std = @import("std");
const palette = @import("palette.zig");
const Palette = palette.Palette;
const Color = palette.Color;
const mem = std.mem;
usingnamespace @import("mecha");
fn testParser(comptime parser: anytype, comptime examples: anytype) !void {
var fail = std.testing.FailingAllocator.init(std.testing.allocator, 0);
inline for (examples) |ex| {
try expectResult(ParserResult(@TypeOf(parser)), .{ .value = ex[1], .rest = ex[2] }, parser(&fail.allocator, ex[0]));
}
}
fn toByte(v: u8) u8 {
return v * 0x10 + v;
}
fn toByte2(v: [2]u8) u8 {
return v[0] * 0x10 + v[1];
}
const hex = convert(u8, toInt(u8, 16), asStr(ascii.digit(16)));
const hex1 = map(u8, toByte, hex);
const hex2 = map(u8, toByte2, manyN(hex, 2, .{}));
const rgb1 = map(Color, toStruct(Color), manyN(hex1, 3, .{}));
const rgb2 = map(Color, toStruct(Color), manyN(hex2, 3, .{}));
pub const raw_color = combine(.{
ascii.char('#'),
oneOf(.{
rgb2,
rgb1,
}),
});
const ws = discard(many(oneOf(.{
utf8.char(' '),
utf8.char('\n'),
utf8.char('\r'),
utf8.char('\t'),
}), .{ .collect = false }));
pub const color = combine(.{
oneOf(.{ utf8.char('"'), utf8.char('\'') }),
raw_color,
oneOf(.{ utf8.char('"'), utf8.char('\'') }),
ws,
});
test "pal.parser.color" {
const c = Color{ .r = 0xaa, .g = 0xbb, .b = 0xcc };
try testParser(color, .{
.{ "'#aabbcc'", c, "" },
.{ "\"#abc\"", c, "" },
});
}
const identifier = many(oneOf(.{
discard(utf8.range('a', 'z')),
discard(utf8.range('A', 'Z')),
utf8.char('-'),
}), .{ .collect = false });
pub const section = combine(.{
ascii.char('['),
identifier,
ascii.char(']'),
ws,
});
test "pal.parser.section" {
try testParser(section, .{
.{ "[default]", "default", "" },
.{ "[some-section-name] \n", "some-section-name", "" },
});
}
pub const key = combine(.{
identifier,
ws,
utf8.char('='),
ws,
});
test "pal.parser.key" {
try testParser(key, .{
.{ "key = value", "key", "value" },
.{ "key \t\n\r = value", "key", "value" },
});
}
pub fn arrayN(
comptime n: usize,
comptime parser: anytype,
comptime delim: anytype,
) Parser([n]ParserResult(@TypeOf(parser))) {
return struct {
const Array = [n]ParserResult(@TypeOf(parser));
const Res = Result(Array);
const List = combine(.{
ascii.char('['),
ws,
parser,
manyN(combine(.{
combine(.{ delim, ws }),
parser,
}), n - 1, .{}),
opt(combine(.{ delim, ws })),
ascii.char(']'),
});
fn func(allocator: *mem.Allocator, str: []const u8) Error!Res {
if (List(allocator, str)) |r| {
var res: Array = undefined;
for (res[1..]) |*arr, i| {
arr.* = r.value[1][i];
}
res[0] = r.value[0];
return Res{ .value = res, .rest = r.rest };
} else |err| {
return err;
}
}
}.func;
}
test "pal.parser.arrayN" {
const array = comptime arrayN(3, color, ascii.char(','));
const c = Color{ .r = 0xaa, .g = 0xbb, .b = 0xcc };
try testParser(array, .{
.{ "['#aabbcc' , \t'#aabbcc','#aabbcc'\r]A", [3]Color{ c, c, c }, "A" },
.{
\\[
\\ '#aabbcc',
\\ '#aabbcc',
\\ '#aabbcc'
\\]
,
[3]Color{ c, c, c },
"",
},
});
}
pub fn comment(allocator: *mem.Allocator, s: []const u8) Error!Result(void) {
_ = allocator;
if (!mem.startsWith(u8, s, "#")) {
return Error.ParserFailed;
} else {
if (mem.indexOf(u8, s, "\n")) |idx| {
return Result(void){ .value = {}, .rest = s[idx..] };
} else {
return Result(void){ .value = {}, .rest = "" };
}
}
}
test "pal.parser.comment" {
try testParser(comment, .{
.{ "# hello this is a comment", {}, "" },
.{ "# hello this is a comment\n", {}, "\n" },
});
}
pub const Value = union(enum) {
Single: Color,
Array: [16]Color,
};
pub fn value(allocator: *mem.Allocator, str: []const u8) Error!Result(Value) {
const R = Result(Value);
const A = comptime arrayN(16, color, ascii.char(','));
if (color(allocator, str)) |r| {
return R{ .value = Value{ .Single = r.value }, .rest = r.rest };
} else |_| {
if (A(allocator, str)) |r| {
return R{ .value = Value{ .Array = r.value }, .rest = r.rest };
} else |err2| return err2;
}
}
test "pal.parser.value" {
try testParser(value, .{
.{ "'#073642'", Value{ .Single = Color{ .r = 0x07, .g = 0x36, .b = 0x42 } }, "" },
.{ "'#fdf6e3'", Value{ .Single = Color{ .r = 0xfd, .g = 0xf6, .b = 0xe3 } }, "" },
.{ "'#dc322f'", Value{ .Single = Color{ .r = 0xdc, .g = 0x32, .b = 0x2f } }, "" },
});
}
pub fn parsePalette(allocator: *mem.Allocator, str: []const u8) Error!Result(Palette) {
const Pair = struct {
k: []const u8,
v: Value,
fn getSingle(self: @This()) Error!Color {
switch (self.v) {
.Single => |c| return c,
else => return Error.ParserFailed,
}
}
fn getArray(self: @This()) Error![16]Color {
switch (self.v) {
.Array => |c| return c,
else => return Error.ParserFailed,
}
}
};
const Prototype = struct {
name: []const u8,
pairs: [4]Pair,
};
const pairP = comptime map(Pair, toStruct(Pair), combine(.{ key, value }));
const protoP = comptime map(Prototype, toStruct(Prototype), combine(.{
discard(ws),
section,
manyN(pairP, 4, .{}),
discard(ws),
}));
if (protoP(allocator, str)) |proto| {
var result: Palette = undefined;
result.name = proto.value.name;
for (proto.value.pairs) |p| {
if (mem.eql(u8, p.k, "background")) {
result.background = try p.getSingle();
} else if (mem.eql(u8, p.k, "foreground")) {
result.foreground = try p.getSingle();
} else if (mem.eql(u8, p.k, "cursor")) {
result.cursor = try p.getSingle();
} else if (mem.eql(u8, p.k, "colors")) {
result.colors = try p.getArray();
}
}
return Result(Palette){ .value = result, .rest = proto.rest };
} else |err| return err;
}
fn genSolarized() !Palette {
@setEvalBranchQuota(10000);
var fail = std.testing.FailingAllocator.init(undefined, 0);
return Palette{
.name = "default",
.background = (try raw_color(&fail.allocator, "#073642")).value,
.foreground = (try raw_color(&fail.allocator, "#fdf6e3")).value,
.cursor = (try raw_color(&fail.allocator, "#dc322f")).value,
.colors = [16]Color{
(try raw_color(&fail.allocator, "#073642")).value,
(try raw_color(&fail.allocator, "#dc322f")).value,
(try raw_color(&fail.allocator, "#859900")).value,
(try raw_color(&fail.allocator, "#b58900")).value,
(try raw_color(&fail.allocator, "#268bd2")).value,
(try raw_color(&fail.allocator, "#d33682")).value,
(try raw_color(&fail.allocator, "#2aa198")).value,
(try raw_color(&fail.allocator, "#eee8d5")).value,
(try raw_color(&fail.allocator, "#6c7c80")).value,
(try raw_color(&fail.allocator, "#dc322f")).value,
(try raw_color(&fail.allocator, "#859900")).value,
(try raw_color(&fail.allocator, "#b58900")).value,
(try raw_color(&fail.allocator, "#268bd2")).value,
(try raw_color(&fail.allocator, "#d33682")).value,
(try raw_color(&fail.allocator, "#2aa198")).value,
(try raw_color(&fail.allocator, "#eee8d5")).value,
},
};
}
const solarized = genSolarized() catch unreachable;
const solarized_palette_src =
\\
\\[default]
\\background='#073642'
\\foreground='#fdf6e3'
\\cursor='#dc322f'
\\colors = [
\\'#073642',
\\'#dc322f',
\\'#859900',
\\'#b58900',
\\'#268bd2',
\\'#d33682',
\\'#2aa198',
\\'#eee8d5',
\\'#6c7c80',
\\'#dc322f',
\\'#859900',
\\'#b58900',
\\'#268bd2',
\\'#d33682',
\\'#2aa198',
\\'#eee8d5',
\\]
\\
;
test "pal.parser.parsePalette" {
const result = try parsePalette(undefined, solarized_palette_src);
// expectEquals only check for pointer equality
// so we have to do this manually
try std.testing.expectEqualSlices(u8, solarized.name, result.value.name);
try std.testing.expectEqual(solarized.background, result.value.background);
try std.testing.expectEqual(solarized.foreground, result.value.foreground);
try std.testing.expectEqual(solarized.cursor, result.value.cursor);
try std.testing.expectEqual(solarized.colors, result.value.colors);
}
pub fn consume(
comptime parser: anytype,
allocator: *mem.Allocator,
slice: []ParserResult(@TypeOf(parser)),
str: []const u8,
) Error!Result([]ParserResult(@TypeOf(parser))) {
const Slice = []ParserResult(@TypeOf(parser));
var idx: usize = 0;
var rem = str;
while (parser(allocator, rem)) |r| : ({
idx += 1;
rem = r.rest;
}) {
if (idx >= slice.len) {
break;
} else {
slice[idx] = r.value;
if (r.rest.len == 0) break;
}
} else |err| return err;
return Result(Slice){ .value = slice[0..idx], .rest = rem };
}
test "pal.parser.consume" {
var fail = std.testing.FailingAllocator.init(std.testing.allocator, 0);
const p = comptime ascii.range('a', 'z');
var arr: [3]u8 = undefined;
const res = try consume(p, &fail.allocator, &arr, "aaaa");
try std.testing.expectEqualSlices(u8, "aaa", arr[0..]);
try std.testing.expectEqualSlices(u8, arr[0..], res.value);
try std.testing.expectEqualSlices(u8, "a", res.rest);
}
test "pal.parser.parsePalette+consume" {
const N = 2;
var fail = std.testing.FailingAllocator.init(std.testing.allocator, 0);
var palettes: [N]Palette = undefined;
const result = try consume(parsePalette, &fail.allocator, &palettes, solarized_palette_src ** N);
for (result.value) |r| {
try std.testing.expectEqualSlices(u8, solarized.name, r.name);
try std.testing.expectEqual(solarized.background, r.background);
try std.testing.expectEqual(solarized.foreground, r.foreground);
try std.testing.expectEqual(solarized.cursor, r.cursor);
try std.testing.expectEqual(solarized.colors, r.colors);
}
} | pal/pal/parser.zig |
const builtin = @import("builtin");
const std = @import("std");
//===========================================================================//
/// A simple spin-lock.
pub const SpinLock = struct {
// TODO: Instead of just storing 1 for held, we should store the thread ID
// of the holding thread. Then we could detect cases like a thread trying
// to acquire a lock it already holds, or a thread releasing a lock held by
// another thread, or a thread calling assertHeld on a lock held by a
// different thread.
locked: u32, // 0 if unheld, 1 if held
/// Creates a new lock, initially unheld.
pub fn init() SpinLock {
return SpinLock{.locked = 0};
}
/// Acquires the lock, blocking if necessary.
pub fn acquire(self: *this) void {
// TODO: The AtomicOrder params here (and elsewhere) could probably be
// relaxed a bit.
while (@cmpxchgWeak(u32, &self.locked, 0, 1,
builtin.AtomicOrder.SeqCst,
builtin.AtomicOrder.SeqCst) != null) {}
}
/// Releases the lock. Panics if the lock is not currently held.
pub fn release(self: *this) void {
if (@cmpxchgStrong(u32, &self.locked, 1, 0,
builtin.AtomicOrder.SeqCst,
builtin.AtomicOrder.SeqCst) != null) {
@panic("releasing unheld SpinLock");
}
}
/// Asserts that the lock is currently held.
pub fn assertHeld(self: *this) void {
std.debug.assert(@cmpxchgStrong(u32, &self.locked, 1, 1,
builtin.AtomicOrder.SeqCst,
builtin.AtomicOrder.SeqCst) == null);
}
};
//===========================================================================//
test "spinlock lock/unlock" {
var mutex = SpinLock.init();
mutex.acquire();
mutex.assertHeld();
mutex.release();
}
//===========================================================================// | src/ziegfried/spinlock.zig |
const tIndex = enum(u3) {
Alpha,
Hex,
Space,
Digit,
Lower,
Upper,
// Ctrl, < 0x20 || == DEL
// Print, = Graph || == ' '. NOT '\t' et cetera
Punct,
Graph,
//ASCII, | ~0b01111111
//isBlank, == ' ' || == '\x09'
};
const combinedTable = init: {
comptime var table: [256]u8 = undefined;
const std = @import("std");
const mem = std.mem;
const alpha = [_]u1{
// 0, 1, 2, 3, 4, 5, 6, 7 ,8, 9,10,11,12,13,14,15
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,
};
const lower = [_]u1{
// 0, 1, 2, 3, 4, 5, 6, 7 ,8, 9,10,11,12,13,14,15
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,
};
const upper = [_]u1{
// 0, 1, 2, 3, 4, 5, 6, 7 ,8, 9,10,11,12,13,14,15
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
const digit = [_]u1{
// 0, 1, 2, 3, 4, 5, 6, 7 ,8, 9,10,11,12,13,14,15
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
const hex = [_]u1{
// 0, 1, 2, 3, 4, 5, 6, 7 ,8, 9,10,11,12,13,14,15
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
const space = [_]u1{
// 0, 1, 2, 3, 4, 5, 6, 7 ,8, 9,10,11,12,13,14,15
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
const punct = [_]u1{
// 0, 1, 2, 3, 4, 5, 6, 7 ,8, 9,10,11,12,13,14,15
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
};
const graph = [_]u1{
// 0, 1, 2, 3, 4, 5, 6, 7 ,8, 9,10,11,12,13,14,15
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,
};
comptime var i = 0;
inline while (i < 128) : (i += 1) {
table[i] =
u8(alpha[i]) << @enumToInt(tIndex.Alpha) |
u8(hex[i]) << @enumToInt(tIndex.Hex) |
u8(space[i]) << @enumToInt(tIndex.Space) |
u8(digit[i]) << @enumToInt(tIndex.Digit) |
u8(lower[i]) << @enumToInt(tIndex.Lower) |
u8(upper[i]) << @enumToInt(tIndex.Upper) |
u8(punct[i]) << @enumToInt(tIndex.Punct) |
u8(graph[i]) << @enumToInt(tIndex.Graph);
}
mem.set(u8, table[128..256], 0);
break :init table;
};
fn inTable(c: u8, t: tIndex) bool {
return (combinedTable[c] & (u8(1) << @enumToInt(t))) != 0;
}
pub fn isAlNum(c: u8) bool {
return (combinedTable[c] & ((u8(1) << @enumToInt(tIndex.Alpha)) |
u8(1) << @enumToInt(tIndex.Digit))) != 0;
}
pub fn isAlpha(c: u8) bool {
return inTable(c, tIndex.Alpha);
}
pub fn isCntrl(c: u8) bool {
return c < 0x20 or c == 127; //DEL
}
pub fn isDigit(c: u8) bool {
return inTable(c, tIndex.Digit);
}
pub fn isGraph(c: u8) bool {
return inTable(c, tIndex.Graph);
}
pub fn isLower(c: u8) bool {
return inTable(c, tIndex.Lower);
}
pub fn isPrint(c: u8) bool {
return inTable(c, tIndex.Graph) or c == ' ';
}
pub fn isPunct(c: u8) bool {
return inTable(c, tIndex.Punct);
}
pub fn isSpace(c: u8) bool {
return inTable(c, tIndex.Space);
}
pub fn isUpper(c: u8) bool {
return inTable(c, tIndex.Upper);
}
pub fn isXDigit(c: u8) bool {
return inTable(c, tIndex.Hex);
}
pub fn isASCII(c: u8) bool {
return c < 128;
}
pub fn isBlank(c: u8) bool {
return (c == ' ') or (c == '\x09');
}
pub fn toUpper(c: u8) u8 {
if (isLower(c)) {
return c & 0b11011111;
} else {
return c;
}
}
pub fn toLower(c: u8) u8 {
if (isUpper(c)) {
return c | 0b00100000;
} else {
return c;
}
}
test "ascii character classes" {
const std = @import("std");
const testing = std.testing;
testing.expect('C' == toUpper('c'));
testing.expect(':' == toUpper(':'));
testing.expect('\xab' == toUpper('\xab'));
testing.expect('c' == toLower('C'));
testing.expect(isAlpha('c'));
testing.expect(!isAlpha('5'));
testing.expect(isSpace(' '));
} | std/ascii.zig |
const std = @import("std");
pub fn build(b: *std.build.Builder) !void {
// Working Windows target provided for convenience
const target = if (b.option(bool, "windows", "Cross-compile to Windows") orelse false)
std.zig.CrossTarget{ .cpu_arch = .x86_64, .os_tag = .windows, .abi = .gnu }
else b.standardTargetOptions(.{});
const mode = b.standardReleaseOptions();
// Example runner
const exe = b.addExecutable("examples", "main.zig");
const skipAssetMake = b.option(bool, "skip-asset-make", "Don't build assets") orelse false;
if (!skipAssetMake) {
const makeAssets = b.addSystemCommand(&.{ "make" });
exe.step.dependOn(&makeAssets.step);
}
exe.setTarget(target);
exe.setBuildMode(mode);
// TODO: Move elsewhere
// vvvvvvv
exe.addPackagePath("sdlb", "../src/sdlb.zig");
exe.linkLibC();
if (target.os_tag != null and target.os_tag.? == .windows) {
if (target.abi.? != .gnu or target.cpu_arch.? != .x86_64) {
std.log.err("windows target only supports x86 gnu", .{});
return error.invalid_target;
}
// Windows libs required for SDL2
exe.linkSystemLibrary("gdi32");
exe.linkSystemLibrary("winmm");
exe.linkSystemLibrary("imm32");
exe.linkSystemLibrary("ole32");
exe.linkSystemLibrary("oleaut32");
exe.linkSystemLibrary("version");
exe.linkSystemLibrary("setupapi");
// Static MinGW libs
exe.addIncludeDir("../mingw64/include");
exe.addIncludeDir("../mingw64/include/SDL2");
exe.addIncludeDir("../mingw64/include/opus");
exe.addObjectFile("../mingw64/lib/libSDL2.a");
exe.addObjectFile("../mingw64/lib/libzstd.a");
exe.addObjectFile("../mingw64/lib/libogg.a");
exe.addObjectFile("../mingw64/lib/libopus.a");
exe.addObjectFile("../mingw64/lib/libopusfile.a");
} else {
exe.addIncludeDir("SDL2");
exe.linkSystemLibrary("SDL2");
exe.linkSystemLibrary("zstd");
exe.linkSystemLibrary("opusfile");
}
// ^^^^^^^
exe.install();
const runCmd = exe.run();
runCmd.step.dependOn(&exe.install_step.?.step);
if (b.args) |args| {
runCmd.addArgs(args);
}
const runStep = b.step("run", "Run the example runner");
runStep.dependOn(&runCmd.step);
} | examples/build.zig |
const std = @import("std");
const c = @import("internal/c.zig");
const internal = @import("internal/internal.zig");
const log = std.log.scoped(.git);
const git = @import("git.zig");
pub const Note = opaque {
pub fn deinit(self: *Note) void {
log.debug("Note.deinit called", .{});
c.git_note_free(@ptrCast(*c.git_note, self));
log.debug("note freed successfully", .{});
}
/// Get the note author
pub fn author(self: *const Note) *const git.Signature {
log.debug("Note.author called", .{});
return @ptrCast(
*const git.Signature,
c.git_note_author(@ptrCast(*const c.git_note, self)),
);
}
/// Get the note committer
pub fn committer(self: *const Note) *const git.Signature {
log.debug("Note.committer called", .{});
return @ptrCast(
*const git.Signature,
c.git_note_committer(@ptrCast(*const c.git_note, self)),
);
}
/// Get the note message
pub fn message(self: *const Note) [:0]const u8 {
log.debug("Note.message called", .{});
const ret = c.git_note_message(@ptrCast(*const c.git_note, self));
return std.mem.sliceTo(ret, 0);
}
/// Get the note id
pub fn id(self: *const Note) *const git.Oid {
log.debug("Note.id called", .{});
return @ptrCast(
*const git.Oid,
c.git_note_id(@ptrCast(*const c.git_note, self)),
);
}
comptime {
std.testing.refAllDecls(@This());
}
};
pub const NoteIterator = opaque {
/// Return the current item and advance the iterator internally to the next value
pub fn next(self: *NoteIterator) !?NextItem {
log.debug("NoteIterator.next called", .{});
var ret: NextItem = undefined;
internal.wrapCall("git_note_next", .{
@ptrCast(*c.git_oid, &ret.note_id),
@ptrCast(*c.git_oid, &ret.annotated_id),
@ptrCast(*c.git_note_iterator, self),
}) catch |err| switch (err) {
git.GitError.IterOver => {
log.debug("end of iteration reached", .{});
return null;
},
else => return err,
};
return ret;
}
pub fn deinit(self: *NoteIterator) void {
log.debug("NoteIterator.deinit called", .{});
c.git_note_iterator_free(@ptrCast(*c.git_note_iterator, self));
log.debug("note iterator freed successfully", .{});
}
pub const NextItem = struct {
note_id: git.Oid,
annotated_id: git.Oid,
};
comptime {
std.testing.refAllDecls(@This());
}
};
comptime {
std.testing.refAllDecls(@This());
} | src/notes.zig |
const var extern packed export pub noalias inline comptime nakedcc stdcallcc volatile align linksection threadlocal
const as = 2;
union
struct
enum
error
asd {
.asd = asd,
}
fn dump(
value: var.asda.ad.asd,
// NYI some arg
asdasd: Baddad
) void {
}
"for"
break return continue asm defer errdefer unreachable
if else switch and or try catch orelse
async await suspend resume cancel noasync
while for
null undefined
fn usingnamespace test
bool f16 f32 f64 f128 void noreturn type anyerror anytype
promise anyframe
i2 u2 i3 u3 i4 u4 i5 u5 i6 u6 i7 u7 i8 u8 i16 u16 u29 i29 i32 u32 i64 u64 i128 u128 isize usize
.i368 .i686 .i23
c_short c_ushort c_int c_uint c_long c_ulong c_longlong c_ulonglong c_longdouble c_void
true false
a + b
a += b
a +% b
a +%= b
a - b
a -= b
a -% b
a -%= b
-a
-%a
a * b
a *= b
a *% b
a *%= b
a / b
a /= b
a % b
a %= b
a << b
a <<= b
a >> b
a >>= b
a & b
a &= b
a | b
a |= b
a ^ b
a ^= b
~a
a orelse b
a.?
a catch b
a catch |err| b
a and b
a or b
!a
a == b
a == null
a != b
a > b
a >= b
a < b
a <= b
a ++ b
a ** b
a.*
&a
a || b
123
123.123
123.123e123
123.123E123
1e3
0x123
0x123.123
0x123.123p123
0o123
0b1
1_234_567;
0xff00_00ff;
0b10000000_10101010;
0b1000_0000_1010_1010;
0x123_190.109_038_018p102;
3.14159_26535_89793;
123.i812
a.i111
slice[0..2]
/// TODO blah blah
// TODO blah blah
"adsfjioasdjfoiad"
c"adsfjioasdjfoiad"
'\a'
const \\ adsjfaf23n9
const v = fn(aas, 2342, 23) as;
fn foo(a:as) s {
}
fn foo() A![]Foo {
}
extern fn bar() as as void;
extern fn foobar() void;
errdefer |err| std.debug.assert(err == error.Overflow);
c\\ adsjfafsdjkl \x11 \u1245 \U123456
extern fn bar() void;
c\\ adsjfafsdjkl \ \\ \ \xdeadbeef
extern fn foobar() void;
\\ adsjfafsdjkl
pub fn barfoo();
fn
\\ adsjfafsdjkl
}
"hello \x1 \n \t \\ \r 1m ' \\ \a \" \u{11}"
extern fn foobarfoo() void;
"\"hello\""
'a'
'ab'
'\''
'\a\naa'
'\a'
'\aaasas'
'\n'
'💩';
fn(i13i,Foo) Bar;
foo = bar;
@"overloaded" = 89;
@cImport
@cInclude
@import
@exampleBuiltin
*const asasd
*const [N:0]u8
?[]T and *[N]T
.{
.x = 13,
.y = 67,
}
var i: Number = .{.int = 42};
pub extern "hellas" export fn @"eeeasla"(as: FN) userdata;
pub extern "hellas" export fn hello(as: as) AA!OO {
anyframe->U
}
pub extern "ole32" stdcallcc fn CoTaskMemFree(pv: *const LPVOID, asda: asdsad, sacz: @"zxc", asd: asd) oop!asd;
pub stdcallcc fn CoUninitialize() A![];
ident
pub const Foo = extern struct {
fn_call()
};
asda: extern struct {
};
const Err = error {
};
{
: Bar,
}
(asdasd)
const Bar = struct {
field: Foo = 234"asas",
comptime field: Bad = Fasd {},
field: var
};
const Boof = union(enum) {
};
const Bad = enum(u8) {
Dummy,
_
};
var as: Bad = Bad(u8) {
pub stdcallcc fn CoUninitialize() void;
};
blk: {
break :blk void;
var f = Bar {
.val = 9
}
}
extern fn f2(s: *const *volatile u8) Error!GenericType(s) {
}
var asd: *const asd!asdads = 0;
var ba = 0;
blk: while () : (sas) {
error.asdasd;
}
const asas: u8asd;
addsaad
const alignment = blk: {
const a = comptime meta.alignment(P);
const b: a = fn() A!A;
a = 23;
if (a > 0) break :blk a;
break :blk 1;
};
std.debug.warn(run_qemu.getEnvMap() .get("PATH"));
///Given a pointer to a single item, returns a slice of the underlying bytes, preserving constness.
pub fn asBytes(ptr: var) asdsa!AsBytesReturnType(@typeOf(ptr)) {
const P = @typeOf(ptr);
return @ptrCast(AsBytesReturnType(P), ptr);
}
pub const LARGE_INTEGER = extern struct {
_u2: extern struct {
LowPart: fn(a, b, c)d,
HighPart: LONG,
},
QuadPart: LONGLONG,
};
pub const GUID = extern struct {
Data1: c_ulong,
Data2: c_ushort,
Data3: c_ushort,
Data4: [8]u8,
};
pub async fn function() Error!ReturnType {
}
pub async fn function(arg: Int, arg: I) !ReturnType {
} | Syntaxes/samples.zig |
const zm = @import("zetamath");
usingnamespace @import("zetarender");
const std = @import("std");
const UBO = extern struct {
model: zm.Mat44f,
view: zm.Mat44f,
proj: zm.Mat44f,
};
const Vertex = extern struct {
const Self = @This();
pos: zm.Vec2f,
color: zm.Vec3f,
pub fn new(pos: zm.Vec2f, color: zm.Vec3f) Self {
return Self{
.pos = pos,
.color = color,
};
}
};
const SimpleRenderPass = program.renderpass.Object(.{
.attachments = &[_]program.renderpass.Attachment{.{
.format = null,
.samples = .{ .@"1_bit" = true },
.load_op = .clear,
.store_op = .store,
.stencil_load_op = .dont_care,
.stencil_store_op = .dont_care,
.initial_layout = .@"undefined",
.final_layout = .present_src_khr,
}},
.subpasses = &[_]program.renderpass.SubPass{.{
.bind_point = .graphics,
.color_attachments = &[_]program.renderpass.SubPass.Dependency{.{
.index = 0,
.layout = .color_attachment_optimal,
}},
// .resolve_attachments = &[_]program.renderpass.SubPass.Dependency{},
}},
});
const vert_shader = @alignCast(@alignOf(u32), @embedFile("shaders/vert.spv"));
const frag_shader = @alignCast(@alignOf(u32), @embedFile("shaders/frag.spv"));
const SimplePipelineState = program.pipeline.State{
.kind = .graphics,
.render_pass = SimpleRenderPass,
.layout = .{
.set_layouts = &[_]program.descriptor.SetLayout{
.{
.bindings = &[_]program.descriptor.Binding{.{
.kind = .uniform_buffer,
.count = 1,
.stages = .{ .vertex_bit = true },
}},
},
},
},
.shader_stages = &[_]program.pipeline.ShaderStage{
.{
.stage = .{ .vertex_bit = true },
.shader = .{ .bytes = vert_shader },
.entrypoint = "main",
},
.{
.stage = .{ .fragment_bit = true },
.shader = .{ .bytes = frag_shader },
.entrypoint = "main",
},
},
.vertex_input_state = .{
.input_rate = .vertex,
.bindings = &[_]type{Vertex},
},
.input_assembly_state = .{
.topology = .triangle_list,
.primitive_restart = false,
},
.rasterizer_state = .{
.cull_mode = .{},
.front_face = .clockwise,
.polygon_mode = .fill,
},
.multisample_state = null,
.depth_stencil_state = null,
.color_blend_state = .{
.attachments = &[_]program.pipeline.ColorBlendState.Attachment{
.{
.enable_blending = false,
.color_blend_src = .zero,
.color_blend_dst = .zero,
.color_blend_op = .add,
.alpha_blend_src = .zero,
.alpha_blend_dst = .zero,
.alpha_blend_op = .add,
.color_write_mask = .{ .r_bit = true, .g_bit = true, .b_bit = true, .a_bit = true },
},
},
},
};
const SimplePipeline = program.pipeline.Object(SimplePipelineState);
pub const SimpleCommand = struct {
const Self = @This();
base: program.command.IObject = .{
.executeFn = execute,
},
vertex_buffer: *backend.buffer.Buffer,
index_buffer: *backend.buffer.Buffer,
pub fn build(render: *Render, vertex_buffer: *backend.buffer.Buffer, index_buffer: *backend.buffer.Buffer) !Self {
try vertex_buffer.init(render.backend.context.allocator, &render.backend.vallocator, &render.backend.context);
try index_buffer.init(render.backend.context.allocator, &render.backend.vallocator, &render.backend.context);
return Self{
.vertex_buffer = vertex_buffer,
.index_buffer = index_buffer,
};
}
pub fn deinit(self: Self) void {
self.vertex_buffer.deinit();
self.index_buffer.deinit();
}
pub fn execute(base: *const program.command.IObject, context: *const backend.Context, cb: backend.vk.CommandBuffer, fb: backend.Framebuffer) !void {
const self = @fieldParentPtr(Self, "base", base);
try self.vertex_buffer.push();
try self.index_buffer.push();
const offset = [_]backend.vk.DeviceSize{0};
context.vkd.cmdBindVertexBuffers(cb, 0, 1, @ptrCast([*]const backend.vk.Buffer, &self.vertex_buffer.buffer()), &offset);
context.vkd.cmdBindIndexBuffer(cb, self.index_buffer.buffer(), 0, .uint16);
context.vkd.cmdDrawIndexed(cb, self.index_buffer.len(), 1, 0, 0, 0);
}
};
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer std.debug.assert(!gpa.deinit());
var allocator = &gpa.allocator;
var testWindow = windowing.Window.new("Vulkan Test", .{ .width = 1280, .height = 720 });
try testWindow.init();
defer testWindow.deinit();
var render = Render.new(allocator, &testWindow);
try render.init();
defer render.deinit();
var clear_color = backend.vk.ClearValue{ .color = .{ .float_32 = [4]f32{ 1.0, 0.0, 0.0, 1.0 } } };
const simple_render_pass = try SimpleRenderPass.build(&render, &clear_color);
defer simple_render_pass.deinit();
const simple_pipeline = try SimplePipeline.build(&render, &simple_render_pass);
defer simple_pipeline.deinit();
var vertex1 = Vertex.new(zm.Vec2f.new(-0.5, -0.5), zm.Vec3f.new(1.0, 0.0, 0.0));
var vertex2 = Vertex.new(zm.Vec2f.new(0.5, -0.5), zm.Vec3f.new(0.0, 1.0, 0.0));
var vertex3 = Vertex.new(zm.Vec2f.new(0.5, 0.5), zm.Vec3f.new(0.0, 0.0, 1.0));
var vertex4 = Vertex.new(zm.Vec2f.new(-0.5, 0.5), zm.Vec3f.new(0.0, 0.0, 0.0));
var vertex_buffer = backend.buffer.DirectBuffer(Vertex, .Vertex).new(&[_]Vertex{ vertex1, vertex2, vertex3, vertex4 });
var indices = [_]u16{ 0, 1, 2, 2, 3, 0 };
var index_buffer = backend.buffer.DirectBuffer(u16, .Index).new(&indices);
const simple_command = try SimpleCommand.build(&render, &vertex_buffer.buf, &index_buffer.buf);
defer simple_command.deinit();
const simple_program = render.buildProgram(&[_]program.Step{
.{ .RenderPass = &simple_render_pass.base },
.{ .Pipeline = &simple_pipeline.base },
.{ .Command = &simple_command.base },
});
var counter: f32 = 0;
while (testWindow.isRunning()) {
counter += 0.001;
testWindow.update();
clear_color.color.float_32[0] = @sin(counter);
clear_color.color.float_32[1] = @sin(-counter);
clear_color.color.float_32[2] = @cos(counter);
vertex1.color.x = @cos(-counter);
vertex2.color.y = @cos(-counter);
vertex3.color.z = @cos(-counter);
vertex4.color.x = @cos(-counter);
vertex1.pos.x = @cos(counter);
vertex1.pos.y = @cos(counter);
vertex2.pos.x = @cos(-counter);
vertex2.pos.y = @sin(-counter);
try vertex_buffer.update(&[_]Vertex{ vertex1, vertex2, vertex3, vertex4 });
try render.present(&simple_program);
// try render.backend.vallocator.gc();
}
render.stop();
} | examples/simple-render/main.zig |
pub const D3DCOMPILER_DLL = "d3dcompiler_47.dll";
pub const D3DCOMPILE_OPTIMIZATION_LEVEL2 = @as(u32, 49152);
pub const D3D_COMPILE_STANDARD_FILE_INCLUDE = @as(u32, 1);
pub const D3D_COMPILER_VERSION = @as(u32, 47);
pub const D3DCOMPILE_DEBUG = @as(u32, 1);
pub const D3DCOMPILE_SKIP_VALIDATION = @as(u32, 2);
pub const D3DCOMPILE_SKIP_OPTIMIZATION = @as(u32, 4);
pub const D3DCOMPILE_PACK_MATRIX_ROW_MAJOR = @as(u32, 8);
pub const D3DCOMPILE_PACK_MATRIX_COLUMN_MAJOR = @as(u32, 16);
pub const D3DCOMPILE_PARTIAL_PRECISION = @as(u32, 32);
pub const D3DCOMPILE_FORCE_VS_SOFTWARE_NO_OPT = @as(u32, 64);
pub const D3DCOMPILE_FORCE_PS_SOFTWARE_NO_OPT = @as(u32, 128);
pub const D3DCOMPILE_NO_PRESHADER = @as(u32, 256);
pub const D3DCOMPILE_AVOID_FLOW_CONTROL = @as(u32, 512);
pub const D3DCOMPILE_PREFER_FLOW_CONTROL = @as(u32, 1024);
pub const D3DCOMPILE_ENABLE_STRICTNESS = @as(u32, 2048);
pub const D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY = @as(u32, 4096);
pub const D3DCOMPILE_IEEE_STRICTNESS = @as(u32, 8192);
pub const D3DCOMPILE_OPTIMIZATION_LEVEL0 = @as(u32, 16384);
pub const D3DCOMPILE_OPTIMIZATION_LEVEL1 = @as(u32, 0);
pub const D3DCOMPILE_OPTIMIZATION_LEVEL3 = @as(u32, 32768);
pub const D3DCOMPILE_RESERVED16 = @as(u32, 65536);
pub const D3DCOMPILE_RESERVED17 = @as(u32, 131072);
pub const D3DCOMPILE_WARNINGS_ARE_ERRORS = @as(u32, 262144);
pub const D3DCOMPILE_RESOURCES_MAY_ALIAS = @as(u32, 524288);
pub const D3DCOMPILE_ENABLE_UNBOUNDED_DESCRIPTOR_TABLES = @as(u32, 1048576);
pub const D3DCOMPILE_ALL_RESOURCES_BOUND = @as(u32, 2097152);
pub const D3DCOMPILE_DEBUG_NAME_FOR_SOURCE = @as(u32, 4194304);
pub const D3DCOMPILE_DEBUG_NAME_FOR_BINARY = @as(u32, 8388608);
pub const D3DCOMPILE_EFFECT_CHILD_EFFECT = @as(u32, 1);
pub const D3DCOMPILE_EFFECT_ALLOW_SLOW_OPS = @as(u32, 2);
pub const D3DCOMPILE_FLAGS2_FORCE_ROOT_SIGNATURE_LATEST = @as(u32, 0);
pub const D3DCOMPILE_FLAGS2_FORCE_ROOT_SIGNATURE_1_0 = @as(u32, 16);
pub const D3DCOMPILE_FLAGS2_FORCE_ROOT_SIGNATURE_1_1 = @as(u32, 32);
pub const D3DCOMPILE_SECDATA_MERGE_UAV_SLOTS = @as(u32, 1);
pub const D3DCOMPILE_SECDATA_PRESERVE_TEMPLATE_SLOTS = @as(u32, 2);
pub const D3DCOMPILE_SECDATA_REQUIRE_TEMPLATE_MATCH = @as(u32, 4);
pub const D3D_DISASM_ENABLE_COLOR_CODE = @as(u32, 1);
pub const D3D_DISASM_ENABLE_DEFAULT_VALUE_PRINTS = @as(u32, 2);
pub const D3D_DISASM_ENABLE_INSTRUCTION_NUMBERING = @as(u32, 4);
pub const D3D_DISASM_ENABLE_INSTRUCTION_CYCLE = @as(u32, 8);
pub const D3D_DISASM_DISABLE_DEBUG_INFO = @as(u32, 16);
pub const D3D_DISASM_ENABLE_INSTRUCTION_OFFSET = @as(u32, 32);
pub const D3D_DISASM_INSTRUCTION_ONLY = @as(u32, 64);
pub const D3D_DISASM_PRINT_HEX_LITERALS = @as(u32, 128);
pub const D3D_GET_INST_OFFSETS_INCLUDE_NON_EXECUTABLE = @as(u32, 1);
pub const D3D_COMPRESS_SHADER_KEEP_ALL_PARTS = @as(u32, 1);
pub const DxcValidatorFlags_Default = @as(u32, 0);
pub const DxcValidatorFlags_InPlaceEdit = @as(u32, 1);
pub const DxcValidatorFlags_RootSignatureOnly = @as(u32, 2);
pub const DxcValidatorFlags_ModuleOnly = @as(u32, 4);
pub const DxcValidatorFlags_ValidMask = @as(u32, 7);
pub const DxcVersionInfoFlags_None = @as(u32, 0);
pub const DxcVersionInfoFlags_Debug = @as(u32, 1);
pub const DxcVersionInfoFlags_Internal = @as(u32, 2);
pub const CLSID_DxcCompiler = Guid.initString("73e22d93-e6ce-47f3-b5bf-f0664f39c1b0");
pub const CLSID_DxcLinker = Guid.initString("ef6a8087-b0ea-4d56-9e45-d07e1a8b7806");
pub const CLSID_DxcDiaDataSource = Guid.initString("cd1f6b73-2ab0-484d-8edc-ebe7a43ca09f");
pub const CLSID_DxcLibrary = Guid.initString("6245d6af-66e0-48fd-80b4-4d271796748c");
pub const CLSID_DxcValidator = Guid.initString("8ca3e215-f728-4cf3-8cdd-88af917587a1");
pub const CLSID_DxcAssembler = Guid.initString("d728db68-f903-4f80-94cd-dccf76ec7151");
pub const CLSID_DxcContainerReflection = Guid.initString("b9f54489-55b8-400c-ba3a-1675e4728b91");
pub const CLSID_DxcOptimizer = Guid.initString("ae2cd79f-cc22-453f-9b6b-b124e7a5204c");
pub const CLSID_DxcContainerBuilder = Guid.initString("94134294-411f-4574-b4d0-8741e25240d2");
//--------------------------------------------------------------------------------
// Section: Types (26)
//--------------------------------------------------------------------------------
pub const DXC_CP = enum(u32) {
ACP = 0,
UTF16 = 1200,
UTF8 = 65001,
};
pub const DXC_CP_ACP = DXC_CP.ACP;
pub const DXC_CP_UTF16 = DXC_CP.UTF16;
pub const DXC_CP_UTF8 = DXC_CP.UTF8;
pub const pD3DCompile = fn(
pSrcData: ?*const c_void,
SrcDataSize: usize,
pFileName: ?[*:0]const u8,
pDefines: ?*const D3D_SHADER_MACRO,
pInclude: ?*ID3DInclude,
pEntrypoint: ?[*:0]const u8,
pTarget: ?[*:0]const u8,
Flags1: u32,
Flags2: u32,
ppCode: ?*?*ID3DBlob,
ppErrorMsgs: ?*?*ID3DBlob,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const pD3DPreprocess = fn(
pSrcData: ?*const c_void,
SrcDataSize: usize,
pFileName: ?[*:0]const u8,
pDefines: ?*const D3D_SHADER_MACRO,
pInclude: ?*ID3DInclude,
ppCodeText: ?*?*ID3DBlob,
ppErrorMsgs: ?*?*ID3DBlob,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const pD3DDisassemble = fn(
// TODO: what to do with BytesParamIndex 1?
pSrcData: ?*const c_void,
SrcDataSize: usize,
Flags: u32,
szComments: ?[*:0]const u8,
ppDisassembly: ?*?*ID3DBlob,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const D3DCOMPILER_STRIP_FLAGS = enum(i32) {
REFLECTION_DATA = 1,
DEBUG_INFO = 2,
TEST_BLOBS = 4,
PRIVATE_DATA = 8,
ROOT_SIGNATURE = 16,
FORCE_DWORD = 2147483647,
};
pub const D3DCOMPILER_STRIP_REFLECTION_DATA = D3DCOMPILER_STRIP_FLAGS.REFLECTION_DATA;
pub const D3DCOMPILER_STRIP_DEBUG_INFO = D3DCOMPILER_STRIP_FLAGS.DEBUG_INFO;
pub const D3DCOMPILER_STRIP_TEST_BLOBS = D3DCOMPILER_STRIP_FLAGS.TEST_BLOBS;
pub const D3DCOMPILER_STRIP_PRIVATE_DATA = D3DCOMPILER_STRIP_FLAGS.PRIVATE_DATA;
pub const D3DCOMPILER_STRIP_ROOT_SIGNATURE = D3DCOMPILER_STRIP_FLAGS.ROOT_SIGNATURE;
pub const D3DCOMPILER_STRIP_FORCE_DWORD = D3DCOMPILER_STRIP_FLAGS.FORCE_DWORD;
pub const D3D_BLOB_PART = enum(i32) {
INPUT_SIGNATURE_BLOB = 0,
OUTPUT_SIGNATURE_BLOB = 1,
INPUT_AND_OUTPUT_SIGNATURE_BLOB = 2,
PATCH_CONSTANT_SIGNATURE_BLOB = 3,
ALL_SIGNATURE_BLOB = 4,
DEBUG_INFO = 5,
LEGACY_SHADER = 6,
XNA_PREPASS_SHADER = 7,
XNA_SHADER = 8,
PDB = 9,
PRIVATE_DATA = 10,
ROOT_SIGNATURE = 11,
DEBUG_NAME = 12,
TEST_ALTERNATE_SHADER = 32768,
TEST_COMPILE_DETAILS = 32769,
TEST_COMPILE_PERF = 32770,
TEST_COMPILE_REPORT = 32771,
};
pub const D3D_BLOB_INPUT_SIGNATURE_BLOB = D3D_BLOB_PART.INPUT_SIGNATURE_BLOB;
pub const D3D_BLOB_OUTPUT_SIGNATURE_BLOB = D3D_BLOB_PART.OUTPUT_SIGNATURE_BLOB;
pub const D3D_BLOB_INPUT_AND_OUTPUT_SIGNATURE_BLOB = D3D_BLOB_PART.INPUT_AND_OUTPUT_SIGNATURE_BLOB;
pub const D3D_BLOB_PATCH_CONSTANT_SIGNATURE_BLOB = D3D_BLOB_PART.PATCH_CONSTANT_SIGNATURE_BLOB;
pub const D3D_BLOB_ALL_SIGNATURE_BLOB = D3D_BLOB_PART.ALL_SIGNATURE_BLOB;
pub const D3D_BLOB_DEBUG_INFO = D3D_BLOB_PART.DEBUG_INFO;
pub const D3D_BLOB_LEGACY_SHADER = D3D_BLOB_PART.LEGACY_SHADER;
pub const D3D_BLOB_XNA_PREPASS_SHADER = D3D_BLOB_PART.XNA_PREPASS_SHADER;
pub const D3D_BLOB_XNA_SHADER = D3D_BLOB_PART.XNA_SHADER;
pub const D3D_BLOB_PDB = D3D_BLOB_PART.PDB;
pub const D3D_BLOB_PRIVATE_DATA = D3D_BLOB_PART.PRIVATE_DATA;
pub const D3D_BLOB_ROOT_SIGNATURE = D3D_BLOB_PART.ROOT_SIGNATURE;
pub const D3D_BLOB_DEBUG_NAME = D3D_BLOB_PART.DEBUG_NAME;
pub const D3D_BLOB_TEST_ALTERNATE_SHADER = D3D_BLOB_PART.TEST_ALTERNATE_SHADER;
pub const D3D_BLOB_TEST_COMPILE_DETAILS = D3D_BLOB_PART.TEST_COMPILE_DETAILS;
pub const D3D_BLOB_TEST_COMPILE_PERF = D3D_BLOB_PART.TEST_COMPILE_PERF;
pub const D3D_BLOB_TEST_COMPILE_REPORT = D3D_BLOB_PART.TEST_COMPILE_REPORT;
pub const D3D_SHADER_DATA = extern struct {
pBytecode: ?*const c_void,
BytecodeLength: usize,
};
pub const DxcCreateInstanceProc = fn(
rclsid: ?*const Guid,
riid: ?*const Guid,
ppv: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const DxcCreateInstance2Proc = fn(
pMalloc: ?*IMalloc,
rclsid: ?*const Guid,
riid: ?*const Guid,
ppv: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
const IID_IDxcBlob_Value = @import("../zig.zig").Guid.initString("8ba5fb08-5195-40e2-ac58-0d989c3a0102");
pub const IID_IDxcBlob = &IID_IDxcBlob_Value;
pub const IDxcBlob = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetBufferPointer: fn(
self: *const IDxcBlob,
) callconv(@import("std").os.windows.WINAPI) ?*c_void,
GetBufferSize: fn(
self: *const IDxcBlob,
) callconv(@import("std").os.windows.WINAPI) usize,
};
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 IDxcBlob_GetBufferPointer(self: *const T) callconv(.Inline) ?*c_void {
return @ptrCast(*const IDxcBlob.VTable, self.vtable).GetBufferPointer(@ptrCast(*const IDxcBlob, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcBlob_GetBufferSize(self: *const T) callconv(.Inline) usize {
return @ptrCast(*const IDxcBlob.VTable, self.vtable).GetBufferSize(@ptrCast(*const IDxcBlob, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDxcBlobEncoding_Value = @import("../zig.zig").Guid.initString("7241d424-2646-4191-97c0-98e96e42fc68");
pub const IID_IDxcBlobEncoding = &IID_IDxcBlobEncoding_Value;
pub const IDxcBlobEncoding = extern struct {
pub const VTable = extern struct {
base: IDxcBlob.VTable,
GetEncoding: fn(
self: *const IDxcBlobEncoding,
pKnown: ?*BOOL,
pCodePage: ?*DXC_CP,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDxcBlob.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcBlobEncoding_GetEncoding(self: *const T, pKnown: ?*BOOL, pCodePage: ?*DXC_CP) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcBlobEncoding.VTable, self.vtable).GetEncoding(@ptrCast(*const IDxcBlobEncoding, self), pKnown, pCodePage);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDxcLibrary_Value = @import("../zig.zig").Guid.initString("e5204dc7-d18c-4c3c-bdfb-851673980fe7");
pub const IID_IDxcLibrary = &IID_IDxcLibrary_Value;
pub const IDxcLibrary = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetMalloc: fn(
self: *const IDxcLibrary,
pMalloc: ?*IMalloc,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateBlobFromBlob: fn(
self: *const IDxcLibrary,
pBlob: ?*IDxcBlob,
offset: u32,
length: u32,
ppResult: ?*?*IDxcBlob,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateBlobFromFile: fn(
self: *const IDxcLibrary,
pFileName: ?[*:0]const u16,
codePage: ?*DXC_CP,
pBlobEncoding: ?*?*IDxcBlobEncoding,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateBlobWithEncodingFromPinned: fn(
self: *const IDxcLibrary,
// TODO: what to do with BytesParamIndex 1?
pText: ?*const c_void,
size: u32,
codePage: DXC_CP,
pBlobEncoding: ?*?*IDxcBlobEncoding,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateBlobWithEncodingOnHeapCopy: fn(
self: *const IDxcLibrary,
// TODO: what to do with BytesParamIndex 1?
pText: ?*const c_void,
size: u32,
codePage: DXC_CP,
pBlobEncoding: ?*?*IDxcBlobEncoding,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateBlobWithEncodingOnMalloc: fn(
self: *const IDxcLibrary,
// TODO: what to do with BytesParamIndex 2?
pText: ?*const c_void,
pIMalloc: ?*IMalloc,
size: u32,
codePage: DXC_CP,
pBlobEncoding: ?*?*IDxcBlobEncoding,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateIncludeHandler: fn(
self: *const IDxcLibrary,
ppResult: ?*?*IDxcIncludeHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateStreamFromBlobReadOnly: fn(
self: *const IDxcLibrary,
pBlob: ?*IDxcBlob,
ppStream: ?*?*IStream,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetBlobAsUtf8: fn(
self: *const IDxcLibrary,
pBlob: ?*IDxcBlob,
pBlobEncoding: ?*?*IDxcBlobEncoding,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetBlobAsUtf16: fn(
self: *const IDxcLibrary,
pBlob: ?*IDxcBlob,
pBlobEncoding: ?*?*IDxcBlobEncoding,
) 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 IDxcLibrary_SetMalloc(self: *const T, pMalloc: ?*IMalloc) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcLibrary.VTable, self.vtable).SetMalloc(@ptrCast(*const IDxcLibrary, self), pMalloc);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcLibrary_CreateBlobFromBlob(self: *const T, pBlob: ?*IDxcBlob, offset: u32, length: u32, ppResult: ?*?*IDxcBlob) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcLibrary.VTable, self.vtable).CreateBlobFromBlob(@ptrCast(*const IDxcLibrary, self), pBlob, offset, length, ppResult);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcLibrary_CreateBlobFromFile(self: *const T, pFileName: ?[*:0]const u16, codePage: ?*DXC_CP, pBlobEncoding: ?*?*IDxcBlobEncoding) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcLibrary.VTable, self.vtable).CreateBlobFromFile(@ptrCast(*const IDxcLibrary, self), pFileName, codePage, pBlobEncoding);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcLibrary_CreateBlobWithEncodingFromPinned(self: *const T, pText: ?*const c_void, size: u32, codePage: DXC_CP, pBlobEncoding: ?*?*IDxcBlobEncoding) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcLibrary.VTable, self.vtable).CreateBlobWithEncodingFromPinned(@ptrCast(*const IDxcLibrary, self), pText, size, codePage, pBlobEncoding);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcLibrary_CreateBlobWithEncodingOnHeapCopy(self: *const T, pText: ?*const c_void, size: u32, codePage: DXC_CP, pBlobEncoding: ?*?*IDxcBlobEncoding) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcLibrary.VTable, self.vtable).CreateBlobWithEncodingOnHeapCopy(@ptrCast(*const IDxcLibrary, self), pText, size, codePage, pBlobEncoding);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcLibrary_CreateBlobWithEncodingOnMalloc(self: *const T, pText: ?*const c_void, pIMalloc: ?*IMalloc, size: u32, codePage: DXC_CP, pBlobEncoding: ?*?*IDxcBlobEncoding) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcLibrary.VTable, self.vtable).CreateBlobWithEncodingOnMalloc(@ptrCast(*const IDxcLibrary, self), pText, pIMalloc, size, codePage, pBlobEncoding);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcLibrary_CreateIncludeHandler(self: *const T, ppResult: ?*?*IDxcIncludeHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcLibrary.VTable, self.vtable).CreateIncludeHandler(@ptrCast(*const IDxcLibrary, self), ppResult);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcLibrary_CreateStreamFromBlobReadOnly(self: *const T, pBlob: ?*IDxcBlob, ppStream: ?*?*IStream) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcLibrary.VTable, self.vtable).CreateStreamFromBlobReadOnly(@ptrCast(*const IDxcLibrary, self), pBlob, ppStream);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcLibrary_GetBlobAsUtf8(self: *const T, pBlob: ?*IDxcBlob, pBlobEncoding: ?*?*IDxcBlobEncoding) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcLibrary.VTable, self.vtable).GetBlobAsUtf8(@ptrCast(*const IDxcLibrary, self), pBlob, pBlobEncoding);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcLibrary_GetBlobAsUtf16(self: *const T, pBlob: ?*IDxcBlob, pBlobEncoding: ?*?*IDxcBlobEncoding) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcLibrary.VTable, self.vtable).GetBlobAsUtf16(@ptrCast(*const IDxcLibrary, self), pBlob, pBlobEncoding);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDxcOperationResult_Value = @import("../zig.zig").Guid.initString("cedb484a-d4e9-445a-b991-ca21ca157dc2");
pub const IID_IDxcOperationResult = &IID_IDxcOperationResult_Value;
pub const IDxcOperationResult = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetStatus: fn(
self: *const IDxcOperationResult,
pStatus: ?*HRESULT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetResult: fn(
self: *const IDxcOperationResult,
pResult: ?*?*IDxcBlob,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetErrorBuffer: fn(
self: *const IDxcOperationResult,
pErrors: ?*?*IDxcBlobEncoding,
) 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 IDxcOperationResult_GetStatus(self: *const T, pStatus: ?*HRESULT) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcOperationResult.VTable, self.vtable).GetStatus(@ptrCast(*const IDxcOperationResult, self), pStatus);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcOperationResult_GetResult(self: *const T, pResult: ?*?*IDxcBlob) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcOperationResult.VTable, self.vtable).GetResult(@ptrCast(*const IDxcOperationResult, self), pResult);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcOperationResult_GetErrorBuffer(self: *const T, pErrors: ?*?*IDxcBlobEncoding) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcOperationResult.VTable, self.vtable).GetErrorBuffer(@ptrCast(*const IDxcOperationResult, self), pErrors);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDxcIncludeHandler_Value = @import("../zig.zig").Guid.initString("7f61fc7d-950d-467f-b3e3-3c02fb49187c");
pub const IID_IDxcIncludeHandler = &IID_IDxcIncludeHandler_Value;
pub const IDxcIncludeHandler = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
LoadSource: fn(
self: *const IDxcIncludeHandler,
pFilename: ?[*:0]const u16,
ppIncludeSource: ?*?*IDxcBlob,
) 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 IDxcIncludeHandler_LoadSource(self: *const T, pFilename: ?[*:0]const u16, ppIncludeSource: ?*?*IDxcBlob) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcIncludeHandler.VTable, self.vtable).LoadSource(@ptrCast(*const IDxcIncludeHandler, self), pFilename, ppIncludeSource);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DxcDefine = extern struct {
Name: ?[*:0]const u16,
Value: ?[*:0]const u16,
};
const IID_IDxcCompiler_Value = @import("../zig.zig").Guid.initString("8c210bf3-011f-4422-8d70-6f9acb8db617");
pub const IID_IDxcCompiler = &IID_IDxcCompiler_Value;
pub const IDxcCompiler = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Compile: fn(
self: *const IDxcCompiler,
pSource: ?*IDxcBlob,
pSourceName: ?[*:0]const u16,
pEntryPoint: ?[*:0]const u16,
pTargetProfile: ?[*:0]const u16,
pArguments: [*]?PWSTR,
argCount: u32,
pDefines: [*]const DxcDefine,
defineCount: u32,
pIncludeHandler: ?*IDxcIncludeHandler,
ppResult: ?*?*IDxcOperationResult,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Preprocess: fn(
self: *const IDxcCompiler,
pSource: ?*IDxcBlob,
pSourceName: ?[*:0]const u16,
pArguments: [*]?PWSTR,
argCount: u32,
pDefines: [*]const DxcDefine,
defineCount: u32,
pIncludeHandler: ?*IDxcIncludeHandler,
ppResult: ?*?*IDxcOperationResult,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Disassemble: fn(
self: *const IDxcCompiler,
pSource: ?*IDxcBlob,
ppDisassembly: ?*?*IDxcBlobEncoding,
) 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 IDxcCompiler_Compile(self: *const T, pSource: ?*IDxcBlob, pSourceName: ?[*:0]const u16, pEntryPoint: ?[*:0]const u16, pTargetProfile: ?[*:0]const u16, pArguments: [*]?PWSTR, argCount: u32, pDefines: [*]const DxcDefine, defineCount: u32, pIncludeHandler: ?*IDxcIncludeHandler, ppResult: ?*?*IDxcOperationResult) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcCompiler.VTable, self.vtable).Compile(@ptrCast(*const IDxcCompiler, self), pSource, pSourceName, pEntryPoint, pTargetProfile, pArguments, argCount, pDefines, defineCount, pIncludeHandler, ppResult);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcCompiler_Preprocess(self: *const T, pSource: ?*IDxcBlob, pSourceName: ?[*:0]const u16, pArguments: [*]?PWSTR, argCount: u32, pDefines: [*]const DxcDefine, defineCount: u32, pIncludeHandler: ?*IDxcIncludeHandler, ppResult: ?*?*IDxcOperationResult) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcCompiler.VTable, self.vtable).Preprocess(@ptrCast(*const IDxcCompiler, self), pSource, pSourceName, pArguments, argCount, pDefines, defineCount, pIncludeHandler, ppResult);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcCompiler_Disassemble(self: *const T, pSource: ?*IDxcBlob, ppDisassembly: ?*?*IDxcBlobEncoding) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcCompiler.VTable, self.vtable).Disassemble(@ptrCast(*const IDxcCompiler, self), pSource, ppDisassembly);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDxcCompiler2_Value = @import("../zig.zig").Guid.initString("a005a9d9-b8bb-4594-b5c9-0e633bec4d37");
pub const IID_IDxcCompiler2 = &IID_IDxcCompiler2_Value;
pub const IDxcCompiler2 = extern struct {
pub const VTable = extern struct {
base: IDxcCompiler.VTable,
CompileWithDebug: fn(
self: *const IDxcCompiler2,
pSource: ?*IDxcBlob,
pSourceName: ?[*:0]const u16,
pEntryPoint: ?[*:0]const u16,
pTargetProfile: ?[*:0]const u16,
pArguments: [*]?PWSTR,
argCount: u32,
pDefines: [*]const DxcDefine,
defineCount: u32,
pIncludeHandler: ?*IDxcIncludeHandler,
ppResult: ?*?*IDxcOperationResult,
ppDebugBlobName: ?*?PWSTR,
ppDebugBlob: ?*?*IDxcBlob,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDxcCompiler.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcCompiler2_CompileWithDebug(self: *const T, pSource: ?*IDxcBlob, pSourceName: ?[*:0]const u16, pEntryPoint: ?[*:0]const u16, pTargetProfile: ?[*:0]const u16, pArguments: [*]?PWSTR, argCount: u32, pDefines: [*]const DxcDefine, defineCount: u32, pIncludeHandler: ?*IDxcIncludeHandler, ppResult: ?*?*IDxcOperationResult, ppDebugBlobName: ?*?PWSTR, ppDebugBlob: ?*?*IDxcBlob) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcCompiler2.VTable, self.vtable).CompileWithDebug(@ptrCast(*const IDxcCompiler2, self), pSource, pSourceName, pEntryPoint, pTargetProfile, pArguments, argCount, pDefines, defineCount, pIncludeHandler, ppResult, ppDebugBlobName, ppDebugBlob);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDxcLinker_Value = @import("../zig.zig").Guid.initString("f1b5be2a-62dd-4327-a1c2-42ac1e1e78e6");
pub const IID_IDxcLinker = &IID_IDxcLinker_Value;
pub const IDxcLinker = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
RegisterLibrary: fn(
self: *const IDxcLinker,
pLibName: ?[*:0]const u16,
pLib: ?*IDxcBlob,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Link: fn(
self: *const IDxcLinker,
pEntryName: ?[*:0]const u16,
pTargetProfile: ?[*:0]const u16,
pLibNames: [*]const ?[*:0]const u16,
libCount: u32,
pArguments: [*]const ?[*:0]const u16,
argCount: u32,
ppResult: ?*?*IDxcOperationResult,
) 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 IDxcLinker_RegisterLibrary(self: *const T, pLibName: ?[*:0]const u16, pLib: ?*IDxcBlob) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcLinker.VTable, self.vtable).RegisterLibrary(@ptrCast(*const IDxcLinker, self), pLibName, pLib);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcLinker_Link(self: *const T, pEntryName: ?[*:0]const u16, pTargetProfile: ?[*:0]const u16, pLibNames: [*]const ?[*:0]const u16, libCount: u32, pArguments: [*]const ?[*:0]const u16, argCount: u32, ppResult: ?*?*IDxcOperationResult) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcLinker.VTable, self.vtable).Link(@ptrCast(*const IDxcLinker, self), pEntryName, pTargetProfile, pLibNames, libCount, pArguments, argCount, ppResult);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDxcValidator_Value = @import("../zig.zig").Guid.initString("a6e82bd2-1fd7-4826-9811-2857e797f49a");
pub const IID_IDxcValidator = &IID_IDxcValidator_Value;
pub const IDxcValidator = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Validate: fn(
self: *const IDxcValidator,
pShader: ?*IDxcBlob,
Flags: u32,
ppResult: ?*?*IDxcOperationResult,
) 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 IDxcValidator_Validate(self: *const T, pShader: ?*IDxcBlob, Flags: u32, ppResult: ?*?*IDxcOperationResult) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcValidator.VTable, self.vtable).Validate(@ptrCast(*const IDxcValidator, self), pShader, Flags, ppResult);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDxcContainerBuilder_Value = @import("../zig.zig").Guid.initString("334b1f50-2292-4b35-99a1-25588d8c17fe");
pub const IID_IDxcContainerBuilder = &IID_IDxcContainerBuilder_Value;
pub const IDxcContainerBuilder = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Load: fn(
self: *const IDxcContainerBuilder,
pDxilContainerHeader: ?*IDxcBlob,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddPart: fn(
self: *const IDxcContainerBuilder,
fourCC: u32,
pSource: ?*IDxcBlob,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemovePart: fn(
self: *const IDxcContainerBuilder,
fourCC: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SerializeContainer: fn(
self: *const IDxcContainerBuilder,
ppResult: ?*?*IDxcOperationResult,
) 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 IDxcContainerBuilder_Load(self: *const T, pDxilContainerHeader: ?*IDxcBlob) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcContainerBuilder.VTable, self.vtable).Load(@ptrCast(*const IDxcContainerBuilder, self), pDxilContainerHeader);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcContainerBuilder_AddPart(self: *const T, fourCC: u32, pSource: ?*IDxcBlob) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcContainerBuilder.VTable, self.vtable).AddPart(@ptrCast(*const IDxcContainerBuilder, self), fourCC, pSource);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcContainerBuilder_RemovePart(self: *const T, fourCC: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcContainerBuilder.VTable, self.vtable).RemovePart(@ptrCast(*const IDxcContainerBuilder, self), fourCC);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcContainerBuilder_SerializeContainer(self: *const T, ppResult: ?*?*IDxcOperationResult) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcContainerBuilder.VTable, self.vtable).SerializeContainer(@ptrCast(*const IDxcContainerBuilder, self), ppResult);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDxcAssembler_Value = @import("../zig.zig").Guid.initString("091f7a26-1c1f-4948-904b-e6e3a8a771d5");
pub const IID_IDxcAssembler = &IID_IDxcAssembler_Value;
pub const IDxcAssembler = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
AssembleToContainer: fn(
self: *const IDxcAssembler,
pShader: ?*IDxcBlob,
ppResult: ?*?*IDxcOperationResult,
) 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 IDxcAssembler_AssembleToContainer(self: *const T, pShader: ?*IDxcBlob, ppResult: ?*?*IDxcOperationResult) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcAssembler.VTable, self.vtable).AssembleToContainer(@ptrCast(*const IDxcAssembler, self), pShader, ppResult);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDxcContainerReflection_Value = @import("../zig.zig").Guid.initString("d2c21b26-8350-4bdc-976a-331ce6f4c54c");
pub const IID_IDxcContainerReflection = &IID_IDxcContainerReflection_Value;
pub const IDxcContainerReflection = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Load: fn(
self: *const IDxcContainerReflection,
pContainer: ?*IDxcBlob,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPartCount: fn(
self: *const IDxcContainerReflection,
pResult: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPartKind: fn(
self: *const IDxcContainerReflection,
idx: u32,
pResult: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPartContent: fn(
self: *const IDxcContainerReflection,
idx: u32,
ppResult: ?*?*IDxcBlob,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FindFirstPartKind: fn(
self: *const IDxcContainerReflection,
kind: u32,
pResult: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPartReflection: fn(
self: *const IDxcContainerReflection,
idx: u32,
iid: ?*const Guid,
ppvObject: ?*?*c_void,
) 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 IDxcContainerReflection_Load(self: *const T, pContainer: ?*IDxcBlob) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcContainerReflection.VTable, self.vtable).Load(@ptrCast(*const IDxcContainerReflection, self), pContainer);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcContainerReflection_GetPartCount(self: *const T, pResult: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcContainerReflection.VTable, self.vtable).GetPartCount(@ptrCast(*const IDxcContainerReflection, self), pResult);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcContainerReflection_GetPartKind(self: *const T, idx: u32, pResult: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcContainerReflection.VTable, self.vtable).GetPartKind(@ptrCast(*const IDxcContainerReflection, self), idx, pResult);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcContainerReflection_GetPartContent(self: *const T, idx: u32, ppResult: ?*?*IDxcBlob) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcContainerReflection.VTable, self.vtable).GetPartContent(@ptrCast(*const IDxcContainerReflection, self), idx, ppResult);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcContainerReflection_FindFirstPartKind(self: *const T, kind: u32, pResult: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcContainerReflection.VTable, self.vtable).FindFirstPartKind(@ptrCast(*const IDxcContainerReflection, self), kind, pResult);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcContainerReflection_GetPartReflection(self: *const T, idx: u32, iid: ?*const Guid, ppvObject: ?*?*c_void) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcContainerReflection.VTable, self.vtable).GetPartReflection(@ptrCast(*const IDxcContainerReflection, self), idx, iid, ppvObject);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDxcOptimizerPass_Value = @import("../zig.zig").Guid.initString("ae2cd79f-cc22-453f-9b6b-b124e7a5204c");
pub const IID_IDxcOptimizerPass = &IID_IDxcOptimizerPass_Value;
pub const IDxcOptimizerPass = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetOptionName: fn(
self: *const IDxcOptimizerPass,
ppResult: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDescription: fn(
self: *const IDxcOptimizerPass,
ppResult: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetOptionArgCount: fn(
self: *const IDxcOptimizerPass,
pCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetOptionArgName: fn(
self: *const IDxcOptimizerPass,
argIndex: u32,
ppResult: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetOptionArgDescription: fn(
self: *const IDxcOptimizerPass,
argIndex: u32,
ppResult: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcOptimizerPass_GetOptionName(self: *const T, ppResult: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcOptimizerPass.VTable, self.vtable).GetOptionName(@ptrCast(*const IDxcOptimizerPass, self), ppResult);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcOptimizerPass_GetDescription(self: *const T, ppResult: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcOptimizerPass.VTable, self.vtable).GetDescription(@ptrCast(*const IDxcOptimizerPass, self), ppResult);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcOptimizerPass_GetOptionArgCount(self: *const T, pCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcOptimizerPass.VTable, self.vtable).GetOptionArgCount(@ptrCast(*const IDxcOptimizerPass, self), pCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcOptimizerPass_GetOptionArgName(self: *const T, argIndex: u32, ppResult: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcOptimizerPass.VTable, self.vtable).GetOptionArgName(@ptrCast(*const IDxcOptimizerPass, self), argIndex, ppResult);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcOptimizerPass_GetOptionArgDescription(self: *const T, argIndex: u32, ppResult: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcOptimizerPass.VTable, self.vtable).GetOptionArgDescription(@ptrCast(*const IDxcOptimizerPass, self), argIndex, ppResult);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDxcOptimizer_Value = @import("../zig.zig").Guid.initString("25740e2e-9cba-401b-9119-4fb42f39f270");
pub const IID_IDxcOptimizer = &IID_IDxcOptimizer_Value;
pub const IDxcOptimizer = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetAvailablePassCount: fn(
self: *const IDxcOptimizer,
pCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetAvailablePass: fn(
self: *const IDxcOptimizer,
index: u32,
ppResult: ?*?*IDxcOptimizerPass,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RunOptimizer: fn(
self: *const IDxcOptimizer,
pBlob: ?*IDxcBlob,
ppOptions: [*]?PWSTR,
optionCount: u32,
pOutputModule: ?*?*IDxcBlob,
ppOutputText: ?*?*IDxcBlobEncoding,
) 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 IDxcOptimizer_GetAvailablePassCount(self: *const T, pCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcOptimizer.VTable, self.vtable).GetAvailablePassCount(@ptrCast(*const IDxcOptimizer, self), pCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcOptimizer_GetAvailablePass(self: *const T, index: u32, ppResult: ?*?*IDxcOptimizerPass) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcOptimizer.VTable, self.vtable).GetAvailablePass(@ptrCast(*const IDxcOptimizer, self), index, ppResult);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcOptimizer_RunOptimizer(self: *const T, pBlob: ?*IDxcBlob, ppOptions: [*]?PWSTR, optionCount: u32, pOutputModule: ?*?*IDxcBlob, ppOutputText: ?*?*IDxcBlobEncoding) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcOptimizer.VTable, self.vtable).RunOptimizer(@ptrCast(*const IDxcOptimizer, self), pBlob, ppOptions, optionCount, pOutputModule, ppOutputText);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDxcVersionInfo_Value = @import("../zig.zig").Guid.initString("b04f5b50-2059-4f12-a8ff-a1e0cde1cc7e");
pub const IID_IDxcVersionInfo = &IID_IDxcVersionInfo_Value;
pub const IDxcVersionInfo = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetVersion: fn(
self: *const IDxcVersionInfo,
pMajor: ?*u32,
pMinor: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFlags: fn(
self: *const IDxcVersionInfo,
pFlags: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcVersionInfo_GetVersion(self: *const T, pMajor: ?*u32, pMinor: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcVersionInfo.VTable, self.vtable).GetVersion(@ptrCast(*const IDxcVersionInfo, self), pMajor, pMinor);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcVersionInfo_GetFlags(self: *const T, pFlags: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcVersionInfo.VTable, self.vtable).GetFlags(@ptrCast(*const IDxcVersionInfo, self), pFlags);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDxcVersionInfo2_Value = @import("../zig.zig").Guid.initString("fb6904c4-42f0-4b62-9c46-983af7da7c83");
pub const IID_IDxcVersionInfo2 = &IID_IDxcVersionInfo2_Value;
pub const IDxcVersionInfo2 = extern struct {
pub const VTable = extern struct {
base: IDxcVersionInfo.VTable,
GetCommitInfo: fn(
self: *const IDxcVersionInfo2,
pCommitCount: ?*u32,
pCommitHash: ?*?*i8,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDxcVersionInfo.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDxcVersionInfo2_GetCommitInfo(self: *const T, pCommitCount: ?*u32, pCommitHash: ?*?*i8) callconv(.Inline) HRESULT {
return @ptrCast(*const IDxcVersionInfo2.VTable, self.vtable).GetCommitInfo(@ptrCast(*const IDxcVersionInfo2, self), pCommitCount, pCommitHash);
}
};}
pub usingnamespace MethodMixin(@This());
};
//--------------------------------------------------------------------------------
// Section: Functions (27)
//--------------------------------------------------------------------------------
pub extern "D3DCOMPILER_47" fn D3DReadFileToBlob(
pFileName: ?[*:0]const u16,
ppContents: ?*?*ID3DBlob,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "D3DCOMPILER_47" fn D3DWriteBlobToFile(
pBlob: ?*ID3DBlob,
pFileName: ?[*:0]const u16,
bOverwrite: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "D3DCOMPILER_47" fn D3DCompile(
// TODO: what to do with BytesParamIndex 1?
pSrcData: ?*const c_void,
SrcDataSize: usize,
pSourceName: ?[*:0]const u8,
pDefines: ?*const D3D_SHADER_MACRO,
pInclude: ?*ID3DInclude,
pEntrypoint: ?[*:0]const u8,
pTarget: ?[*:0]const u8,
Flags1: u32,
Flags2: u32,
ppCode: ?*?*ID3DBlob,
ppErrorMsgs: ?*?*ID3DBlob,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "D3DCOMPILER_47" fn D3DCompile2(
// TODO: what to do with BytesParamIndex 1?
pSrcData: ?*const c_void,
SrcDataSize: usize,
pSourceName: ?[*:0]const u8,
pDefines: ?*const D3D_SHADER_MACRO,
pInclude: ?*ID3DInclude,
pEntrypoint: ?[*:0]const u8,
pTarget: ?[*:0]const u8,
Flags1: u32,
Flags2: u32,
SecondaryDataFlags: u32,
// TODO: what to do with BytesParamIndex 11?
pSecondaryData: ?*const c_void,
SecondaryDataSize: usize,
ppCode: ?*?*ID3DBlob,
ppErrorMsgs: ?*?*ID3DBlob,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "D3DCOMPILER_47" fn D3DCompileFromFile(
pFileName: ?[*:0]const u16,
pDefines: ?*const D3D_SHADER_MACRO,
pInclude: ?*ID3DInclude,
pEntrypoint: ?[*:0]const u8,
pTarget: ?[*:0]const u8,
Flags1: u32,
Flags2: u32,
ppCode: ?*?*ID3DBlob,
ppErrorMsgs: ?*?*ID3DBlob,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "D3DCOMPILER_47" fn D3DPreprocess(
// TODO: what to do with BytesParamIndex 1?
pSrcData: ?*const c_void,
SrcDataSize: usize,
pSourceName: ?[*:0]const u8,
pDefines: ?*const D3D_SHADER_MACRO,
pInclude: ?*ID3DInclude,
ppCodeText: ?*?*ID3DBlob,
ppErrorMsgs: ?*?*ID3DBlob,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "D3DCOMPILER_47" fn D3DGetDebugInfo(
// TODO: what to do with BytesParamIndex 1?
pSrcData: ?*const c_void,
SrcDataSize: usize,
ppDebugInfo: ?*?*ID3DBlob,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "D3DCOMPILER_47" fn D3DReflect(
// TODO: what to do with BytesParamIndex 1?
pSrcData: ?*const c_void,
SrcDataSize: usize,
pInterface: ?*const Guid,
ppReflector: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "D3DCOMPILER_47" fn D3DReflectLibrary(
// TODO: what to do with BytesParamIndex 1?
pSrcData: ?*const c_void,
SrcDataSize: usize,
riid: ?*const Guid,
ppReflector: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "D3DCOMPILER_47" fn D3DDisassemble(
// TODO: what to do with BytesParamIndex 1?
pSrcData: ?*const c_void,
SrcDataSize: usize,
Flags: u32,
szComments: ?[*:0]const u8,
ppDisassembly: ?*?*ID3DBlob,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "D3DCOMPILER_47" fn D3DDisassembleRegion(
// TODO: what to do with BytesParamIndex 1?
pSrcData: ?*const c_void,
SrcDataSize: usize,
Flags: u32,
szComments: ?[*:0]const u8,
StartByteOffset: usize,
NumInsts: usize,
pFinishByteOffset: ?*usize,
ppDisassembly: ?*?*ID3DBlob,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "D3DCOMPILER_47" fn D3DCreateLinker(
ppLinker: ?*?*ID3D11Linker,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "D3DCOMPILER_47" fn D3DLoadModule(
pSrcData: ?*const c_void,
cbSrcDataSize: usize,
ppModule: ?*?*ID3D11Module,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "D3DCOMPILER_47" fn D3DCreateFunctionLinkingGraph(
uFlags: u32,
ppFunctionLinkingGraph: ?*?*ID3D11FunctionLinkingGraph,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "D3DCOMPILER_47" fn D3DGetTraceInstructionOffsets(
// TODO: what to do with BytesParamIndex 1?
pSrcData: ?*const c_void,
SrcDataSize: usize,
Flags: u32,
StartInstIndex: usize,
NumInsts: usize,
pOffsets: ?[*]usize,
pTotalInsts: ?*usize,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "D3DCOMPILER_47" fn D3DGetInputSignatureBlob(
// TODO: what to do with BytesParamIndex 1?
pSrcData: ?*const c_void,
SrcDataSize: usize,
ppSignatureBlob: ?*?*ID3DBlob,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "D3DCOMPILER_47" fn D3DGetOutputSignatureBlob(
// TODO: what to do with BytesParamIndex 1?
pSrcData: ?*const c_void,
SrcDataSize: usize,
ppSignatureBlob: ?*?*ID3DBlob,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "D3DCOMPILER_47" fn D3DGetInputAndOutputSignatureBlob(
// TODO: what to do with BytesParamIndex 1?
pSrcData: ?*const c_void,
SrcDataSize: usize,
ppSignatureBlob: ?*?*ID3DBlob,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "D3DCOMPILER_47" fn D3DStripShader(
// TODO: what to do with BytesParamIndex 1?
pShaderBytecode: ?*const c_void,
BytecodeLength: usize,
uStripFlags: u32,
ppStrippedBlob: ?*?*ID3DBlob,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "D3DCOMPILER_47" fn D3DGetBlobPart(
// TODO: what to do with BytesParamIndex 1?
pSrcData: ?*const c_void,
SrcDataSize: usize,
Part: D3D_BLOB_PART,
Flags: u32,
ppPart: ?*?*ID3DBlob,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "D3DCOMPILER_47" fn D3DSetBlobPart(
// TODO: what to do with BytesParamIndex 1?
pSrcData: ?*const c_void,
SrcDataSize: usize,
Part: D3D_BLOB_PART,
Flags: u32,
// TODO: what to do with BytesParamIndex 5?
pPart: ?*const c_void,
PartSize: usize,
ppNewShader: ?*?*ID3DBlob,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "D3DCOMPILER_47" fn D3DCreateBlob(
Size: usize,
ppBlob: ?*?*ID3DBlob,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "D3DCOMPILER_47" fn D3DCompressShaders(
uNumShaders: u32,
pShaderData: [*]D3D_SHADER_DATA,
uFlags: u32,
ppCompressedData: ?*?*ID3DBlob,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "D3DCOMPILER_47" fn D3DDecompressShaders(
// TODO: what to do with BytesParamIndex 1?
pSrcData: ?*const c_void,
SrcDataSize: usize,
uNumShaders: u32,
uStartIndex: u32,
pIndices: ?[*]u32,
uFlags: u32,
ppShaders: [*]?*ID3DBlob,
pTotalShaders: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "D3DCOMPILER_47" fn D3DDisassemble10Effect(
pEffect: ?*ID3D10Effect,
Flags: u32,
ppDisassembly: ?*?*ID3DBlob,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "dxcompiler" fn DxcCreateInstance(
rclsid: ?*const Guid,
riid: ?*const Guid,
ppv: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "dxcompiler" fn DxcCreateInstance2(
pMalloc: ?*IMalloc,
rclsid: ?*const Guid,
riid: ?*const Guid,
ppv: ?*?*c_void,
) 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 (15)
//--------------------------------------------------------------------------------
const Guid = @import("../zig.zig").Guid;
const BOOL = @import("../foundation.zig").BOOL;
const D3D_SHADER_MACRO = @import("../graphics/direct3d11.zig").D3D_SHADER_MACRO;
const HRESULT = @import("../foundation.zig").HRESULT;
const ID3D10Effect = @import("../graphics/direct3d10.zig").ID3D10Effect;
const ID3D11FunctionLinkingGraph = @import("../graphics/direct3d11.zig").ID3D11FunctionLinkingGraph;
const ID3D11Linker = @import("../graphics/direct3d11.zig").ID3D11Linker;
const ID3D11Module = @import("../graphics/direct3d11.zig").ID3D11Module;
const ID3DBlob = @import("../graphics/direct3d11.zig").ID3DBlob;
const ID3DInclude = @import("../graphics/direct3d11.zig").ID3DInclude;
const IMalloc = @import("../system/com.zig").IMalloc;
const IStream = @import("../storage/structured_storage.zig").IStream;
const IUnknown = @import("../system/com.zig").IUnknown;
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(), "pD3DCompile")) { _ = pD3DCompile; }
if (@hasDecl(@This(), "pD3DPreprocess")) { _ = pD3DPreprocess; }
if (@hasDecl(@This(), "pD3DDisassemble")) { _ = pD3DDisassemble; }
if (@hasDecl(@This(), "DxcCreateInstanceProc")) { _ = DxcCreateInstanceProc; }
if (@hasDecl(@This(), "DxcCreateInstance2Proc")) { _ = DxcCreateInstance2Proc; }
@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;
}
}
} | deps/zigwin32/win32/graphics/hlsl.zig |
const kernel = @import("../kernel.zig");
const TODO = kernel.TODO;
const log = kernel.log.scoped(.x86_64);
pub const page_size = kernel.arch.check_page_size(0x1000);
pub const Stivale2 = @import("x86_64/limine/stivale2/stivale2.zig");
pub const Spinlock = @import("x86_64/spinlock.zig");
pub const PIC = @import("x86_64/pic.zig");
pub const GDT = @import("x86_64/gdt.zig");
pub const TSS = @import("x86_64/tss.zig");
pub const interrupts = @import("x86_64/interrupts.zig");
pub const Paging = @import("x86_64/paging.zig");
pub const ACPI = @import("x86_64/acpi.zig");
/// This is just the arch-specific part of the address space
pub const AddressSpace = Paging.AddressSpace;
const Virtual = kernel.Virtual;
const Thread = kernel.scheduler.Thread;
pub export fn start(stivale2_struct_address: u64) noreturn {
log.debug("Hello kernel!", .{});
log.debug("Stivale2 address: 0x{x}", .{stivale2_struct_address});
kernel.address_space = kernel.Virtual.AddressSpace.from_current() orelse unreachable;
enable_cpu_features();
const stivale2_struct_physical_address = kernel.Physical.Address.new(stivale2_struct_address);
kernel.higher_half_direct_map = Stivale2.process_higher_half_direct_map(stivale2_struct_physical_address.access_identity(*Stivale2.Struct)) catch unreachable;
rsdp = Stivale2.process_rsdp(stivale2_struct_physical_address.access_identity(*Stivale2.Struct)) catch unreachable;
kernel.Physical.Memory.map = Stivale2.process_memory_map(stivale2_struct_physical_address.access_identity(*Stivale2.Struct)) catch unreachable;
Paging.init(Stivale2.get_pmrs(stivale2_struct_physical_address.access_identity(*Stivale2.Struct)));
const region_type = kernel.Physical.Memory.map.find_address(stivale2_struct_physical_address);
log.debug("Region type: {}", .{region_type});
Stivale2.process_bootloader_information(stivale2_struct_physical_address.access_higher_half(*Stivale2.Struct)) catch unreachable;
preinit_scheduler();
init_scheduler();
asm volatile ("int $0x40");
//kernel.scheduler.yield(undefined);
log.debug("Everything OK", .{});
log.debug("CR8: 0x{x}", .{cr8.read()});
//next_timer(1);
while (true) {
kernel.spinloop_hint();
}
}
fn init_scheduler() void {
defer init_timer();
kernel.scheduler.init();
}
var timestamp_ticks_per_ms: u64 = 0;
fn init_timer() void {
disable_interrupts();
const bsp = &kernel.cpus[0];
const timer_calibration_start = read_timestamp();
bsp.lapic.write(.TIMER_INITCNT, kernel.maxInt(u32));
var times_i: u64 = 0;
const times = 8;
while (times_i < times) : (times_i += 1) {
out8(IOPort.PIT_command, 0x30);
out8(IOPort.PIT_data, 0xa9);
out8(IOPort.PIT_data, 0x04);
while (true) {
out8(IOPort.PIT_command, 0xe2);
if (in8(IOPort.PIT_data) & (1 << 7) != 0) break;
}
}
bsp.lapic.ticks_per_ms = kernel.maxInt(u32) - bsp.lapic.read(.TIMER_CURRENT_COUNT) >> 4;
const timer_calibration_end = read_timestamp();
timestamp_ticks_per_ms = (timer_calibration_end - timer_calibration_start) >> 3;
enable_interrupts();
}
pub inline fn read_timestamp() u64 {
var my_rdx: u64 = undefined;
var my_rax: u64 = undefined;
asm volatile (
\\rdtsc
: [rax] "={rax}" (my_rax),
[rdx] "={rdx}" (my_rdx),
);
return my_rdx << 32 | my_rax;
}
pub inline fn set_current_cpu(cpu: *kernel.arch.CPU) void {
log.debug("Setting current CPU: 0x{x}", .{@ptrToInt(cpu)});
IA32_KERNEL_GS_BASE.write(@ptrToInt(cpu));
}
pub inline fn get_current_cpu() ?*CPU {
return @intToPtr(?*kernel.arch.CPU, IA32_KERNEL_GS_BASE.read());
//return asm volatile (
//\\mov %%gs:[0], %[result]
//: [result] "=r" (-> ?*kernel.arch.CPU),
//);
}
pub inline fn read_gs() ?*kernel.arch.CPU {
return asm volatile (
\\mov %%gs:[0], %[result]
: [result] "=r" (-> ?*kernel.arch.CPU),
);
}
pub const sched_call_vector: u8 = 0x31;
pub const ring_vector: u8 = 0x32;
var last_vector: u8 = ring_vector;
pub const syscall_vector: u8 = 0x80;
pub const lapic_timer_interrupt: u8 = 0xef;
pub const invlpg_vector: u8 = 0xFE;
pub const spurious_vector: u8 = 0xFF;
pub fn enable_apic() void {
const spurious_value = @as(u32, 0x100) | spurious_vector;
const cpu = get_current_cpu() orelse @panic("cannot get cpu");
log.debug("Local storage: 0x{x}", .{@ptrToInt(cpu)});
// TODO: x2APIC
const ia32_apic = IA32_APIC_BASE.read();
const apic_physical_address = get_apic_base(ia32_apic);
log.debug("APIC physical address: 0{x}", .{apic_physical_address});
cpu.lapic = LAPIC.new(kernel.Physical.Address.new(apic_physical_address));
cpu.lapic.write(.SPURIOUS, spurious_value);
const lapic_id = cpu.lapic.read(.LAPIC_ID);
kernel.assert(@src(), lapic_id == cpu.lapic_id);
log.debug("APIC enabled", .{});
}
pub export fn foo(myrsp: u64) callconv(.C) void {
const cpu = @intToPtr(?*CPU, IA32_GS_BASE.read()).?;
log.debug("GS: {}", .{read_gs()});
asm volatile ("swapgs");
log.debug("GS: {}", .{read_gs()});
log.debug("CPU: 0x{x}. INTSTACK: 0x{x}. SCHDSTACK: 0x{x}", .{ @ptrToInt(cpu), cpu.int_stack, cpu.scheduler_stack });
log.debug("RSP: 0x{x}", .{myrsp});
}
pub export fn syscall_handler() callconv(.Naked) void {
asm volatile (
\\mov %%gs, %%rdi
\\swapgs
\\call foo
\\cli
\\loop:
\\hlt
\\jmp loop
);
}
pub fn enable_syscall() void {
IA32_LSTAR.write(@ptrToInt(syscall_handler));
// TODO: figure out what this does
IA32_FMASK.write(@truncate(u22, ~@as(u64, 1 << 1)));
// TODO: figure out what this does
IA32_STAR.write(@offsetOf(GDT.Table, "code_64") << 32);
// TODO: figure out what this does
var efer = IA32_EFER.read();
efer.or_flag(.SCE);
IA32_EFER.write(efer);
log.debug("Enabled syscalls", .{});
}
pub fn preinit_scheduler() void {
const bsp = &kernel.cpus[0];
set_current_cpu(bsp);
IA32_GS_BASE.write(0);
bsp.gdt.initial_setup();
interrupts.init();
enable_apic();
enable_syscall();
bsp.shared_tss = TSS.Struct{};
bsp.shared_tss.set_interrupt_stack(bsp.int_stack);
bsp.shared_tss.set_scheduler_stack(bsp.scheduler_stack);
bsp.gdt.update_tss(&bsp.shared_tss);
log.debug("Scheduler pre-initialization finished!", .{});
}
//pub fn init_all_cores() void {
//// TODO: initialize each CPU but the BSP
////for (
//const all_stacks_size = kernel.arch.bootstrap_stack_size * kernel.cpus.len;
//const stack_allocation = kernel.Physical.Memory.allocate_pages(kernel.bytes_to_pages(all_stacks_size)) orelse @panic("unable to allocate stacks");
//const stack_allocation_virtual_address_value = stack_allocation.identity_virtual_address().value;
//for (kernel.cpus) |*cpu, i| {
//const stack = stack_allocation_virtual_address_value + (kernel.arch.bootstrap_stack_size * i);
//const stack_top = stack + kernel.arch.bootstrap_stack_size - 0x10;
//}
//}
pub var rsdp: kernel.Physical.Address = undefined;
pub const IOPort = struct {
pub const DMA1 = 0x0000;
pub const PIC1 = 0x0020;
pub const Cyrix_MSR = 0x0022;
pub const PIT_data = 0x0040;
pub const PIT_command = 0x0043;
pub const PS2 = 0x0060;
pub const CMOS_RTC = 0x0070;
pub const DMA_page_registers = 0x0080;
pub const A20 = 0x0092;
pub const PIC2 = 0x00a0;
pub const DMA2 = 0x00c0;
pub const E9_hack = 0x00e9;
pub const ATA2 = 0x0170;
pub const ATA1 = 0x01f0;
pub const parallel_port = 0x0278;
pub const serial2 = 0x02f8;
pub const IBM_VGA = 0x03b0;
pub const floppy = 0x03f0;
pub const serial1 = 0x03f8;
};
const Serial = struct {
const io_ports = [8]u16{
0x3F8,
0x2F8,
0x3E8,
0x2E8,
0x5F8,
0x4F8,
0x5E8,
0x4E8,
};
var initialization_state = [1]bool{false} ** 8;
const InitError = error{
already_initialized,
not_present,
};
fn Port(comptime port_number: u8) type {
comptime kernel.assert_unsafe(@src(), port_number > 0 and port_number <= 8);
const port_index = port_number - 1;
return struct {
const io_port = io_ports[port_index];
fn init() Serial.InitError!void {
if (initialization_state[port_index]) return Serial.InitError.already_initialized;
out8(io_port + 7, 0);
if (in8(io_port + 7) != 0) return Serial.InitError.not_present;
out8(io_port + 7, 0xff);
if (in8(io_port + 7) != 0xff) return Serial.InitError.not_present;
TODO();
}
};
}
};
pub inline fn out8(comptime port: u16, value: u8) void {
asm volatile ("outb %[value], %[port]"
:
: [value] "{al}" (value),
[port] "N{dx}" (port),
);
}
pub inline fn in8(comptime port: u16) u8 {
return asm volatile ("inb %[port], %[result]"
: [result] "={al}" (-> u8),
: [port] "N{dx}" (port),
);
}
pub inline fn writer_function(str: []const u8) usize {
for (str) |c| {
out8(IOPort.E9_hack, c);
}
return str.len;
}
pub const rax = SimpleR64("rax");
pub const rbx = SimpleR64("rbx");
pub const rcx = SimpleR64("rcx");
pub const rdx = SimpleR64("rdx");
pub const rbp = SimpleR64("rbp");
pub const rsp = SimpleR64("rsp");
pub const rsi = SimpleR64("rsi");
pub const rdi = SimpleR64("rdi");
pub const r8 = SimpleR64("r8");
pub const r9 = SimpleR64("r9");
pub const r10 = SimpleR64("r10");
pub const r11 = SimpleR64("r11");
pub const r12 = SimpleR64("r12");
pub const r13 = SimpleR64("r13");
pub const r14 = SimpleR64("r14");
pub const r15 = SimpleR64("r15");
pub fn SimpleR64(comptime name: []const u8) type {
return struct {
pub inline fn read() u64 {
return asm volatile ("mov %%" ++ name ++ ", %[result]"
: [result] "={rax}" (-> u64),
);
}
pub inline fn write(value: u64) void {
asm volatile ("mov %[in], %%" ++ name
:
: [in] "r" (value),
);
}
};
}
pub fn ComplexR64(comptime name: []const u8, comptime _BitEnum: type) type {
return struct {
const BitEnum = _BitEnum;
pub inline fn read_raw() u64 {
return asm volatile ("mov %%" ++ name ++ ", %[result]"
: [result] "={rax}" (-> u64),
);
}
pub inline fn write_raw(value: u64) void {
asm volatile ("mov %[in], %%" ++ name
:
: [in] "r" (value),
);
}
pub inline fn read() Value {
return Value{
.value = read_raw(),
};
}
pub inline fn write(value: Value) void {
write_raw(value.value);
}
pub inline fn get_bit(comptime bit: BitEnum) bool {
return read().get_bit(bit);
}
pub inline fn set_bit(comptime bit: BitEnum) void {
var value = read();
value.set_bit(bit);
write(value);
}
pub inline fn clear_bit(comptime bit: BitEnum) void {
var value = read();
value.clear_bit(bit);
write(value);
}
pub const Value = struct {
value: u64,
pub inline fn get_bit(value: Value, comptime bit: BitEnum) bool {
return value.value & (1 << @enumToInt(bit)) != 0;
}
pub inline fn set_bit(value: *Value, comptime bit: BitEnum) void {
value.value |= 1 << @enumToInt(bit);
}
pub inline fn clear_bit(value: *Value, comptime bit: BitEnum) void {
const mask = ~(1 << @enumToInt(bit));
value.value &= mask;
}
};
};
}
// From Intel manual, volume 3, chapter 2.5: Control Registers
/// Contains system control flags that control operating mode and states of the processor.
const cr0 = ComplexR64("cr0", enum(u6) {
/// Protection Enable (bit 0 of CR0) — Enables protected mode when set; enables real-address mode when
/// clear. This flag does not enable paging directly. It only enables segment-level protection. To enable paging,
/// both the PE and PG flags must be set.
/// See also: Section 9.9, “Mode Switching.”
PE = 0,
/// Monitor Coprocessor (bit 1 of CR0) — Controls the interaction of the WAIT (or FWAIT) instruction with
/// the TS flag (bit 3 of CR0). If the MP flag is set, a WAIT instruction generates a device-not-available exception
/// (#NM) if the TS flag is also set. If the MP flag is clear, the WAIT instruction ignores the setting of the TS flag.
/// Table 9-3 shows the recommended setting of this flag, depending on the IA-32 processor and x87 FPU or
/// math coprocessor present in the system. Table 2-2 shows the interaction of the MP, EM, and TS flags.
MP = 1,
/// Emulation (bit 2 of CR0) — Indicates that the processor does not have an internal or external x87 FPU when set;
/// indicates an x87 FPU is present when clear. This flag also affects the execution of
/// MMX/SSE/SSE2/SSE3/SSSE3/SSE4 instructions.
/// When the EM flag is set, execution of an x87 FPU instruction generates a device-not-available exception
/// (#NM). This flag must be set when the processor does not have an internal x87 FPU or is not connected to
/// an external math coprocessor. Setting this flag forces all floating-point instructions to be handled by soft-
/// ware emulation. Table 9-3 shows the recommended setting of this flag, depending on the IA-32 processor
/// and x87 FPU or math coprocessor present in the system. Table 2-2 shows the interaction of the EM, MP, and
/// TS flags.
/// Also, when the EM flag is set, execution of an MMX instruction causes an invalid-opcode exception (#UD)
/// to be generated (see Table 12-1). Thus, if an IA-32 or Intel 64 processor incorporates MMX technology, the
/// EM flag must be set to 0 to enable execution of MMX instructions.
/// Similarly for SSE/SSE2/SSE3/SSSE3/SSE4 extensions, when the EM flag is set, execution of most
/// SSE/SSE2/SSE3/SSSE3/SSE4 instructions causes an invalid opcode exception (#UD) to be generated (see
/// Table 13-1). If an IA-32 or Intel 64 processor incorporates the SSE/SSE2/SSE3/SSSE3/SSE4 extensions,
/// the EM flag must be set to 0 to enable execution of these extensions. SSE/SSE2/SSE3/SSSE3/SSE4
/// instructions not affected by the EM flag include: PAUSE, PREFETCHh, SFENCE, LFENCE, MFENCE, MOVNTI,
/// CLFLUSH, CRC32, and POPCNT.
EM = 2,
/// Task Switched (bit 3 of CR0) — Allows the saving of the x87 FPU/MMX/SSE/SSE2/SSE3/SSSE3/SSE4
/// context on a task switch to be delayed until an x87 FPU/MMX/SSE/SSE2/SSE3/SSSE3/SSE4 instruction is
/// actually executed by the new task. The processor sets this flag on every task switch and tests it when
/// executing x87 FPU/MMX/SSE/SSE2/SSE3/SSSE3/SSE4 instructions.
/// * If the TS flag is set and the EM flag (bit 2 of CR0) is clear, a device-not-available exception (#NM) is
/// raised prior to the execution of any x87 FPU/MMX/SSE/SSE2/SSE3/SSSE3/SSE4 instruction; with the
/// exception of PAUSE, PREFETCHh, SFENCE, LFENCE, MFENCE, MOVNTI, CLFLUSH, CRC32, and POPCNT.
/// See the paragraph below for the special case of the WAIT/FWAIT instructions.
/// * If the TS flag is set and the MP flag (bit 1 of CR0) and EM flag are clear, an #NM exception is not raised
/// prior to the execution of an x87 FPU WAIT/FWAIT instruction.
/// * If the EM flag is set, the setting of the TS flag has no effect on the execution of x87
/// FPU/MMX/SSE/SSE2/SSE3/SSSE3/SSE4 instructions.
/// Table 2-2 shows the actions taken when the processor encounters an x87 FPU instruction based on the
/// settings of the TS, EM, and MP flags. Table 12-1 and 13-1 show the actions taken when the processor
/// encounters an MMX/SSE/SSE2/SSE3/SSSE3/SSE4 instruction.
/// The processor does not automatically save the context of the x87 FPU, XMM, and MXCSR registers on a
/// task switch. Instead, it sets the TS flag, which causes the processor to raise an #NM exception whenever it
/// encounters an x87 FPU/MMX/SSE/SSE2/SSE3/SSSE3/SSE4 instruction in the instruction stream for the
/// new task (with the exception of the instructions listed above).
/// The fault handler for the #NM exception can then be used to clear the TS flag (with the CLTS instruction)
/// and save the context of the x87 FPU, XMM, and MXCSR registers. If the task never encounters an x87
/// FPU/MMX/SSE/SSE2/SSE3/SSSE3/SSE4 instruction, the x87 FPU/MMX/SSE/SSE2/SSE3/SSSE3/SSE4
/// context is never saved.
TS = 3,
/// Extension Type (bit 4 of CR0) — Reserved in the Pentium 4, Intel Xeon, P6 family, and Pentium proces-
/// sors. In the Pentium 4, Intel Xeon, and P6 family processors, this flag is hardcoded to 1. In the Intel386
/// and Intel486 processors, this flag indicates support of Intel 387 DX math coprocessor instructions when
/// set.
ET = 4,
/// Numeric Error (bit 5 of CR0) — Enables the native (internal) mechanism for reporting x87 FPU errors
/// when set; enables the PC-style x87 FPU error reporting mechanism when clear. When the NE flag is clear
/// and the IGNNE# input is asserted, x87 FPU errors are ignored. When the NE flag is clear and the IGNNE#
/// input is deasserted, an unmasked x87 FPU error causes the processor to assert the FERR# pin to generate
/// an external interrupt and to stop instruction execution immediately before executing the next waiting
/// floating-point instruction or WAIT/FWAIT instruction.
/// The FERR# pin is intended to drive an input to an external interrupt controller (the FERR# pin emulates the
/// ERROR# pin of the Intel 287 and Intel 387 DX math coprocessors). The NE flag, IGNNE# pin, and FERR#
/// pin are used with external logic to implement PC-style error reporting. Using FERR# and IGNNE# to handle
/// floating-point exceptions is deprecated by modern operating systems; this non-native approach also limits
/// newer processors to operate with one logical processor active.
/// See also: Section 8.7, “Handling x87 FPU Exceptions in Software” in Chapter 8, “Programming with the x87
/// FPU,” and Appendix A, “EFLAGS Cross-Reference,” in the Intel® 64 and IA-32 Architectures Software
/// Developer’s Manual, Volume 1.
NE = 5,
/// Write Protect (bit 16 of CR0) — When set, inhibits supervisor-level procedures from writing into read-
/// only pages; when clear, allows supervisor-level procedures to write into read-only pages (regardless of the
/// U/S bit setting; see Section 4.1.3 and Section 4.6). This flag facilitates implementation of the copy-on-
/// write method of creating a new process (forking) used by operating systems such as UNIX. This flag must
/// be set before software can set CR4.CET, and it cannot be cleared as long as CR4.CET = 1 (see below).
WP = 16,
/// Alignment Mask (bit 18 of CR0) — Enables automatic alignment checking when set; disables alignment
/// checking when clear. Alignment checking is performed only when the AM flag is set, the AC flag in the
/// EFLAGS register is set, CPL is 3, and the processor is operating in either protected or virtual-8086 mode
AM = 18,
/// Not Write-through (bit 29 of CR0) — When the NW and CD flags are clear, write-back (for Pentium 4,
/// Intel Xeon, P6 family, and Pentium processors) or write-through (for Intel486 processors) is enabled for
/// writes that hit the cache and invalidation cycles are enabled. See Table 11-5 for detailed information about
/// the effect of the NW flag on caching for other settings of the CD and NW flags.
NW = 29,
/// Cache Disable (bit 30 of CR0) — When the CD and NW flags are clear, caching of memory locations for
/// the whole of physical memory in the processor’s internal (and external) caches is enabled. When the CD
/// flag is set, caching is restricted as described in Table 11-5. To prevent the processor from accessing and
/// updating its caches, the CD flag must be set and the caches must be invalidated so that no cache hits can
/// occur.
/// See also: Section 11.5.3, “Preventing Caching,” and Section 11.5, “Cache Control.”
CD = 30,
/// Paging (bit 31 of CR0) — Enables paging when set; disables paging when clear. When paging is
/// disabled, all linear addresses are treated as physical addresses. The PG flag has no effect if the PE flag (bit
/// 0 of register CR0) is not also set; setting the PG flag when the PE flag is clear causes a general-protection
/// exception (#GP). See also: Chapter 4, “Paging.”
/// On Intel 64 processors, enabling and disabling IA-32e mode operation also requires modifying CR0.PG.
PG = 31,
});
// RESERVED: const CR1 = R64("cr1");
/// Contains the page-fault linear address (the linear address that caused a page fault).
pub const cr2 = SimpleR64("cr2");
/// Contains the physical address of the base of the paging-structure hierarchy and two flags (PCD and
/// PWT). Only the most-significant bits (less the lower 12 bits) of the base address are specified; the lower 12 bits
/// of the address are assumed to be 0. The first paging structure must thus be aligned to a page (4-KByte)
/// boundary. The PCD and PWT flags control caching of that paging structure in the processor’s internal data
/// caches (they do not control TLB caching of page-directory information).
/// When using the physical address extension, the CR3 register contains the base address of the page-directory-
/// pointer table. With 4-level paging and 5-level paging, the CR3 register contains the base address of the PML4
/// table and PML5 table, respectively. If PCIDs are enabled, CR3 has a format different from that illustrated in
/// Figure 2-7. See Section 4.5, “4-Level Paging and 5-Level Paging.”
/// See also: Chapter 4, “Paging.”
pub const cr3 = ComplexR64("cr3", enum(u6) {
/// Page-level Write-Through (bit 3 of CR3) — Controls the memory type used to access the first paging
/// structure of the current paging-structure hierarchy. See Section 4.9, “Paging and Memory Typing”. This bit
/// is not used if paging is disabled, with PAE paging, or with 4-level paging or 5-level paging if CR4.PCIDE=1.
PWT = 3,
/// Page-level Cache Disable (bit 4 of CR3) — Controls the memory type used to access the first paging
/// structure of the current paging-structure hierarchy. See Section 4.9, “Paging and Memory Typing”. This bit
/// is not used if paging is disabled, with PAE paging, or with 4-level paging1 or 5-level paging if CR4.PCIDE=1.
PCD = 4,
PCID_top_bit = 11,
});
/// Contains a group of flags that enable several architectural extensions, and indicate operating system or
/// executive support for specific processor capabilities. Bits CR4[63:32] can only be used for IA-32e mode only
/// features that are enabled after entering 64-bit mode. Bits CR4[63:32] do not have any effect outside of IA-32e
/// mode.
const cr4 = ComplexR64("cr4", enum(u6) {
/// Virtual-8086 Mode Extensions (bit 0 of CR4) — Enables interrupt- and exception-handling extensions
/// in virtual-8086 mode when set; disables the extensions when clear. Use of the virtual mode extensions can
/// improve the performance of virtual-8086 applications by eliminating the overhead of calling the virtual-
/// 8086 monitor to handle interrupts and exceptions that occur while executing an 8086 program and,
/// instead, redirecting the interrupts and exceptions back to the 8086 program’s handlers. It also provides
/// hardware support for a virtual interrupt flag (VIF) to improve reliability of running 8086 programs in multi-
/// tasking and multiple-processor environments.
/// See also: Section 20.3, “Interrupt and Exception Handling in Virtual-8086 Mode.”
VME = 0,
/// Protected-Mode Virtual Interrupts (bit 1 of CR4) — Enables hardware support for a virtual interrupt
/// flag (VIF) in protected mode when set; disables the VIF flag in protected mode when clear.
/// See also: Section 20.4, “Protected-Mode Virtual Interrupts.”
PVI = 1,
/// Time Stamp Disable (bit 2 of CR4) — Restricts the execution of the RDTSC instruction to procedures
/// running at privilege level 0 when set; allows RDTSC instruction to be executed at any privilege level when
/// clear. This bit also applies to the RDTSCP instruction if supported (if CPUID.80000001H:EDX[27] = 1).
TSD = 2,
/// Debugging Extensions (bit 3 of CR4) — References to debug registers DR4 and DR5 cause an unde-
/// fined opcode (#UD) exception to be generated when set; when clear, processor aliases references to regis-
/// ters DR4 and DR5 for compatibility with software written to run on earlier IA-32 processors.
/// See also: Section 17.2.2, “Debug Registers DR4 and DR5.”
DE = 3,
/// Page Size Extensions (bit 4 of CR4) — Enables 4-MByte pages with 32-bit paging when set; restricts
/// 32-bit paging to pages of 4 KBytes when clear.
/// See also: Section 4.3, “32-Bit Paging.”
PSE = 4,
/// Physical Address Extension (bit 5 of CR4) — When set, enables paging to produce physical addresses
/// with more than 32 bits. When clear, restricts physical addresses to 32 bits. PAE must be set before entering
/// IA-32e mode.
/// See also: Chapter 4, “Paging.”
PAE = 5,
/// Machine-Check Enable (bit 6 of CR4) — Enables the machine-check exception when set; disables the
/// machine-check exception when clear.
/// See also: Chapter 15, “Machine-Check Architecture.”
MCE = 6,
/// Page Global Enable (bit 7 of CR4) — (Introduced in the P6 family processors.) Enables the global page
/// feature when set; disables the global page feature when clear. The global page feature allows frequently
/// used or shared pages to be marked as global to all users (done with the global flag, bit 8, in a page-direc-
/// tory-pointer-table entry, a page-directory entry, or a page-table entry). Global pages are not flushed from
/// the translation-lookaside buffer (TLB) on a task switch or a write to register CR3.
/// When enabling the global page feature, paging must be enabled (by setting the PG flag in control register
/// CR0) before the PGE flag is set. Reversing this sequence may affect program correctness, and processor
/// performance will be impacted.
/// See also: Section 4.10, “Caching Translation Information.”
PGE = 7,
/// Performance-Monitoring Counter Enable (bit 8 of CR4) — Enables execution of the RDPMC instruc-
/// tion for programs or procedures running at any protection level when set; RDPMC instruction can be
/// executed only at protection level 0 when clear.
PME = 8,
/// Operating System Support for FXSAVE and FXRSTOR instructions (bit 9 of CR4) — When set, this
/// flag: (1) indicates to software that the operating system supports the use of the FXSAVE and FXRSTOR
/// instructions, (2) enables the FXSAVE and FXRSTOR instructions to save and restore the contents of the
/// XMM and MXCSR registers along with the contents of the x87 FPU and MMX registers, and (3) enables the
/// processor to execute SSE/SSE2/SSE3/SSSE3/SSE4 instructions, with the exception of the PAUSE,
/// PREFETCHh, SFENCE, LFENCE, MFENCE, MOVNTI, CLFLUSH, CRC32, and POPCNT.
/// If this flag is clear, the FXSAVE and FXRSTOR instructions will save and restore the contents of the x87 FPU
/// and MMX registers, but they may not save and restore the contents of the XMM and MXCSR registers. Also,
/// the processor will generate an invalid opcode exception (#UD) if it attempts to execute any
/// SSE/SSE2/SSE3 instruction, with the exception of PAUSE, PREFETCHh, SFENCE, LFENCE, MFENCE,
/// MOVNTI, CLFLUSH, CRC32, and POPCNT. The operating system or executive must explicitly set this flag.
/// NOTE
/// CPUID feature flag FXSR indicates availability of the FXSAVE/FXRSTOR instructions. The OSFXSR
/// bit provides operating system software with a means of enabling FXSAVE/FXRSTOR to save/restore
/// the contents of the X87 FPU, XMM and MXCSR registers. Consequently OSFXSR bit indicates that
/// the operating system provides context switch support for SSE/SSE2/SSE3/SSSE3/SSE4.
OSFXSR = 9,
/// Operating System Support for Unmasked SIMD Floating-Point Exceptions (bit 10 of CR4) —
/// When set, indicates that the operating system supports the handling of unmasked SIMD floating-point
/// exceptions through an exception handler that is invoked when a SIMD floating-point exception (#XM) is
/// generated. SIMD floating-point exceptions are only generated by SSE/SSE2/SSE3/SSE4.1 SIMD floating-
/// point instructions.
/// The operating system or executive must explicitly set this flag. If this flag is not set, the processor will
/// generate an invalid opcode exception (#UD) whenever it detects an unmasked SIMD floating-point excep-
/// tion.
OSXMMEXCPT = 10,
/// User-Mode Instruction Prevention (bit 11 of CR4) — When set, the following instructions cannot be
/// executed if CPL > 0: SGDT, SIDT, SLDT, SMSW, and STR. An attempt at such execution causes a general-
/// protection exception (#GP).
UMIP = 11,
/// 57-bit linear addresses (bit 12 of CR4) — When set in IA-32e mode, the processor uses 5-level paging
/// to translate 57-bit linear addresses. When clear in IA-32e mode, the processor uses 4-level paging to
/// translate 48-bit linear addresses. This bit cannot be modified in IA-32e mode.
LA57 = 12,
/// VMX-Enable Bit (bit 13 of CR4) — Enables VMX operation when set. See Chapter 23, “Introduction to
/// Virtual Machine Extensions.”
VMXE = 13,
/// SMX-Enable Bit (bit 14 of CR4) — Enables SMX operation when set. See Chapter 6, “Safer Mode Exten-
/// sions Reference” of Intel® 64 and IA-32 Architectures Software Developer’s Manual, Volume 2D.
SMXE = 14,
/// FSGSBASE-Enable Bit (bit 16 of CR4) — Enables the instructions RDFSBASE, RDGSBASE, WRFSBASE,
/// and WRGSBASE.
FSGSBASE = 16,
/// PCID-Enable Bit (bit 17 of CR4) — Enables process-context identifiers (PCIDs) when set. See Section
/// 4.10.1, “Process-Context Identifiers (PCIDs)”. Applies only in IA-32e mode (if IA32_EFER.LMA = 1).
PCIDE = 17,
/// XSAVE and Processor Extended States-Enable Bit (bit 18 of CR4) — When set, this flag: (1) indi-
/// cates (via CPUID.01H:ECX.OSXSAVE[bit 27]) that the operating system supports the use of the XGETBV,
/// XSAVE and XRSTOR instructions by general software; (2) enables the XSAVE and XRSTOR instructions to
/// save and restore the x87 FPU state (including MMX registers), the SSE state (XMM registers and MXCSR),
/// along with other processor extended states enabled in XCR0; (3) enables the processor to execute XGETBV
/// and XSETBV instructions in order to read and write XCR0. See Section 2.6 and Chapter 13, “System
/// Programming for Instruction Set Extensions and Processor Extended States”.
OSXSAVE = 18,
/// Key-Locker-Enable Bit (bit 19 of CR4) — When set, the LOADIWKEY instruction is enabled; in addition,
/// if support for the AES Key Locker instructions has been activated by system firmware,
/// CPUID.19H:EBX.AESKLE[bit 0] is enumerated as 1 and the AES Key Locker instructions are enabled.1
/// When clear, CPUID.19H:EBX.AESKLE[bit 0] is enumerated as 0 and execution of any Key Locker instruction
/// causes an invalid-opcode exception (#UD).
KL = 19,
/// SMEP-Enable Bit (bit 20 of CR4) — Enables supervisor-mode execution prevention (SMEP) when set.
/// See Section 4.6, “Access Rights”.
SMEP = 20,
/// SMAP-Enable Bit (bit 21 of CR4) — Enables supervisor-mode access prevention (SMAP) when set. See
/// Section 4.6, “Access Rights.”
SMAP = 21,
/// Enable protection keys for user-mode pages (bit 22 of CR4) — 4-level paging and 5-level paging
/// associate each user-mode linear address with a protection key. When set, this flag indicates (via
/// CPUID.(EAX=07H,ECX=0H):ECX.OSPKE [bit 4]) that the operating system supports use of the PKRU
/// register to specify, for each protection key, whether user-mode linear addresses with that protection key
/// can be read or written. This bit also enables access to the PKRU register using the RDPKRU and WRPKRU
/// instructions.
PKE = 22,
/// Control-flow Enforcement Technology (bit 23 of CR4) — Enables control-flow enforcement tech-
/// nology when set. See Chapter 18, “Control-flow Enforcement Technology (CET)” of the IA-32 Intel® Archi-
/// tecture Software Developer’s Manual, Volume 1. This flag can be set only if CR0.WP is set, and it must be
/// clear before CR0.WP can be cleared (see below).
CET = 23,
/// Enable protection keys for supervisor-mode pages (bit 24 of CR4) — 4-level paging and 5-level
/// paging associate each supervisor-mode linear address with a protection key. When set, this flag allows use
/// of the IA32_PKRS MSR to specify, for each protection key, whether supervisor-mode linear addresses with
/// that protection key can be read or written.
PKS = 24,
});
/// Provides read and write access to the Task Priority Register (TPR). It specifies the priority threshold
/// value that operating systems use to control the priority class of external interrupts allowed to interrupt the
/// processor. This register is available only in 64-bit mode. However, interrupt filtering continues to apply in
/// compatibility mode.
const cr8 = SimpleR64("cr8");
fn get_task_priority_level() u4 {
return @truncate(u4, cr8.read());
}
fn enable_cpu_features() void {
kernel.Physical.Address.max_bit = CPUID.get_max_physical_address_bit();
kernel.Physical.Address.max = @as(u64, 1) << kernel.Physical.Address.max_bit;
// Initialize FPU
var cr0_value = cr0.read();
cr0_value.set_bit(.MP);
cr0_value.set_bit(.NE);
cr0.write(cr0_value);
var cr4_value = cr4.read();
cr4_value.set_bit(.OSFXSR);
cr4_value.set_bit(.OSXMMEXCPT);
cr4.write(cr4_value);
log.debug("@TODO: MXCSR. See Intel manual", .{});
// @TODO: is this correct?
const cw: u16 = 0x037a;
asm volatile (
\\fninit
\\fldcw (%[cw])
:
: [cw] "r" (&cw),
);
log.debug("Making sure the cache is initialized properly", .{});
kernel.assert(@src(), !cr0.get_bit(.CD));
kernel.assert(@src(), !cr0.get_bit(.NW));
}
pub fn SimpleMSR(comptime msr: u32) type {
return struct {
pub inline fn read() u64 {
var low: u32 = undefined;
var high: u32 = undefined;
asm volatile ("rdmsr"
: [_] "={eax}" (low),
[_] "={edx}" (high),
: [_] "{ecx}" (msr),
);
return (@as(u64, high) << 32) | low;
}
pub inline fn write(value: u64) void {
const low = @truncate(u32, value);
const high = @truncate(u32, value >> 32);
asm volatile ("wrmsr"
:
: [_] "{eax}" (low),
[_] "{edx}" (high),
[_] "{ecx}" (msr),
);
}
};
}
pub fn ComplexMSR(comptime msr: u32, comptime _BitEnum: type) type {
return struct {
pub const BitEnum = _BitEnum;
pub const Flags = kernel.Bitflag(false, BitEnum);
pub inline fn read() Flags {
var low: u32 = undefined;
var high: u32 = undefined;
asm volatile ("rdmsr"
: [_] "={eax}" (low),
[_] "={edx}" (high),
: [_] "{ecx}" (msr),
);
return Flags.from_bits((@as(u64, high) << 32) | low);
}
pub inline fn write(flags: Flags) void {
const value = flags.bits;
const low = @truncate(u32, value);
const high = @truncate(u32, value >> 32);
asm volatile ("wrmsr"
:
: [_] "{eax}" (low),
[_] "{edx}" (high),
[_] "{ecx}" (msr),
);
}
};
}
//pub const PAT = SimpleMSR(0x277);
pub const IA32_STAR = SimpleMSR(0xC0000081);
pub const IA32_LSTAR = SimpleMSR(0xC0000082);
pub const IA32_FMASK = SimpleMSR(0xC0000084);
pub const IA32_FS_BASE = SimpleMSR(0xC0000100);
pub const IA32_GS_BASE = SimpleMSR(0xC0000101);
pub const IA32_KERNEL_GS_BASE = SimpleMSR(0xC0000102);
pub const IA32_EFER = ComplexMSR(0xC0000080, enum(u64) {
/// Syscall Enable - syscall, sysret
SCE = 0,
/// Long Mode Enable
LME = 8,
/// Long Mode Active
LMA = 10,
/// Enables page access restriction by preventing instruction fetches from PAE pages with the XD bit set
NXE = 11,
SVME = 12,
LMSLE = 13,
FFXSR = 14,
TCE = 15,
});
pub const IA32_APIC_BASE = ComplexMSR(0x0000001B, enum(u64) {
bsp = 8,
global_enable = 11,
});
fn get_apic_base(ia32_apic_base: IA32_APIC_BASE.Flags) u32 {
return @truncate(u32, ia32_apic_base.bits & 0xfffff000);
}
pub const RFLAGS = struct {
pub const Flags = kernel.Bitflag(false, enum(u64) {
CF = 0,
PF = 2,
AF = 4,
ZF = 6,
SF = 7,
TF = 8,
IF = 9,
DF = 10,
OF = 11,
IOPL0 = 12,
IOPL1 = 13,
NT = 14,
RF = 16,
VM = 17,
AC = 18,
VIF = 19,
VIP = 20,
ID = 21,
});
pub inline fn read() Flags {
return Flags{
.bits = asm volatile (
\\pushfq
\\pop %[flags]
: [flags] "=r" (-> u64),
),
};
}
};
pub const CPUID = struct {
eax: u32,
ebx: u32,
edx: u32,
ecx: u32,
/// Returns the maximum number bits a physical address is allowed to have in this CPU
pub inline fn get_max_physical_address_bit() u6 {
return @truncate(u6, cpuid(0x80000008).eax);
}
};
pub inline fn cpuid(leaf: u32) CPUID {
var eax: u32 = undefined;
var ebx: u32 = undefined;
var edx: u32 = undefined;
var ecx: u32 = undefined;
asm volatile (
\\cpuid
: [eax] "={eax}" (eax),
[ebx] "={ebx}" (ebx),
[edx] "={edx}" (edx),
[ecx] "={ecx}" (ecx),
: [leaf] "{eax}" (leaf),
);
return CPUID{
.eax = eax,
.ebx = ebx,
.edx = edx,
.ecx = ecx,
};
}
pub fn get_memory_map() kernel.Memory.Map {
const memory_map_struct = Stivale2.find(Stivale2.Struct.MemoryMap) orelse @panic("Stivale had no RSDP struct");
return Stivale2.process_memory_map(memory_map_struct);
}
pub const valid_page_sizes = [3]u64{ 0x1000, 0x1000 * 512, 0x1000 * 512 * 512 };
fn is_canonical_address(address: u64) bool {
const sign_bit = address & (1 << 63) != 0;
const significant_bit_count = page_table_level_count_to_bit_map(page_table_level_count);
var i: u8 = 63;
while (i >= significant_bit_count) : (i -= 1) {
const bit = address & (1 << i) != 0;
if (bit != sign_bit) return false;
}
return true;
}
pub const page_table_level_count = 4;
fn page_table_level_count_to_bit_map(level: u8) u8 {
return switch (level) {
4 => 48,
5 => 57,
else => @panic("invalid page table level count\n"),
};
}
const use_cr8 = true;
pub inline fn enable_interrupts() void {
if (use_cr8) {
cr8.write(0);
asm volatile ("sti");
} else {
asm volatile ("sti");
}
//log.debug("IF=1", .{});
}
pub inline fn disable_interrupts() void {
if (use_cr8) {
cr8.write(0xe);
asm volatile ("sti");
} else {
asm volatile ("cli");
}
//log.debug("IF=0", .{});
}
pub inline fn are_interrupts_enabled() bool {
if (use_cr8) {
const if_set = RFLAGS.read().contains(.IF);
const cr8_value = cr8.read();
return if_set and cr8_value == 0;
} else {
const if_set = RFLAGS.read().contains(.IF);
return if_set;
}
}
pub const LAPIC = struct {
ticks_per_ms: u32 = 0,
address: kernel.Virtual.Address,
const timer_interrupt = 0x40;
const Register = enum(u32) {
LAPIC_ID = 0x20,
EOI = 0xB0,
SPURIOUS = 0xF0,
ERROR_STATUS_REGISTER = 0x280,
ICR_LOW = 0x300,
ICR_HIGH = 0x310,
LVT_TIMER = 0x320,
TIMER_DIV = 0x3E0,
TIMER_INITCNT = 0x380,
TIMER_CURRENT_COUNT = 0x390,
};
pub inline fn new(lapic_physical_address: kernel.Physical.Address) LAPIC {
//Paging.should_log = true;
const lapic_virtual_address = lapic_physical_address.to_higher_half_virtual_address();
log.debug("Virtual address: 0x{x}", .{lapic_virtual_address.value});
kernel.address_space.map(lapic_physical_address, lapic_virtual_address, kernel.Virtual.AddressSpace.Flags.from_flags(&.{ .cache_disable, .read_write }));
const lapic = LAPIC{
.address = lapic_virtual_address,
};
log.debug("LAPIC initialized: 0x{x}", .{lapic_virtual_address.value});
return lapic;
}
pub inline fn read(lapic: LAPIC, comptime register: LAPIC.Register) u32 {
const register_index = @enumToInt(register) / @sizeOf(u32);
const result = lapic.address.access([*]volatile u32)[register_index];
return result;
}
pub inline fn write(lapic: LAPIC, comptime register: Register, value: u32) void {
const register_index = @enumToInt(register) / @sizeOf(u32);
lapic.address.access([*]volatile u32)[register_index] = value;
}
pub inline fn next_timer(lapic: LAPIC, ms: u32) void {
kernel.assert(@src(), lapic.ticks_per_ms != 0);
lapic.write(.LVT_TIMER, timer_interrupt | (1 << 17));
lapic.write(.TIMER_INITCNT, lapic.ticks_per_ms * ms);
}
pub inline fn end_of_interrupt(lapic: LAPIC) void {
lapic.write(.EOI, 0);
log.debug("LAPIC error status register: 0x{x}", .{lapic.read(.ERROR_STATUS_REGISTER)});
}
};
pub inline fn next_timer(ms: u32) void {
const current_cpu = get_current_cpu().?;
current_cpu.lapic.next_timer(ms);
}
const stack_size = 0x10000;
const guard_stack_size = 0x1000;
pub const CPU = struct {
gdt: GDT.Table,
shared_tss: TSS.Struct,
int_stack: u64,
scheduler_stack: u64,
lapic: LAPIC,
lapic_id: u32,
spinlock_count: u64,
current_thread: ?*kernel.scheduler.Thread,
is_bootstrap: bool,
pub fn bootstrap_stacks(cpu: *CPU) void {
cpu.int_stack = bootstrap_stack(stack_size);
cpu.scheduler_stack = bootstrap_stack(stack_size);
}
fn bootstrap_stack(size: u64) u64 {
const total_size = size + guard_stack_size;
const physical_address = kernel.Physical.Memory.allocate_pages(kernel.bytes_to_pages(total_size, true)) orelse @panic("stack allocation");
const virtual_address = physical_address.access_higher_half();
kernel.address_space.map(physical_address, virtual_address);
return virtual_address.value + total_size;
}
};
export fn thread_terminate(thread: *Thread) void {
thread.terminate();
}
fn thread_terminate_stack() callconv(.Naked) void {
asm volatile (
\\sub $0x8, %%rsp
\\jmp thread_terminate
);
unreachable;
}
pub const Context = struct {
cr8: u64,
es: u64,
ds: u64,
r15: u64,
r14: u64,
r13: u64,
r12: u64,
r11: u64,
r10: u64,
r9: u64,
r8: u64,
rbp: u64,
rsi: u64,
rdi: u64,
rdx: u64,
rcx: u64,
rbx: u64,
rax: u64,
interrupt_number: u64,
error_code: u64,
rip: u64,
cs: u64,
rflags: u64,
rsp: u64,
ss: u64,
pub fn new(thread: *kernel.scheduler.Thread, entry_point: kernel.scheduler.Thread.EntryPoint) *Context {
const kernel_stack = thread.kernel_stack_base.value + thread.kernel_stack_size - 8;
log.debug("thread user stack base: 0x{x}", .{thread.user_stack_base.value});
const user_stack_base = if (thread.user_stack_base.value == 0) thread.kernel_stack_base.value else thread.user_stack_base.value;
const user_stack = thread.user_stack_reserve - 8 + user_stack_base;
log.debug("User stack: 0x{x}", .{user_stack});
const context = @intToPtr(*Context, kernel_stack - @sizeOf(Context));
thread.kernel_stack = Virtual.Address.new(kernel_stack);
log.debug("Kernel stack deref", .{});
thread.kernel_stack.access(*u64).* = @ptrToInt(thread_terminate_stack);
log.debug("Privilege level", .{});
// TODO: FPU
switch (thread.privilege_level) {
.kernel => {
context.cs = @offsetOf(GDT.Table, "code_64");
context.ss = @offsetOf(GDT.Table, "data_64");
},
.user => {
context.cs = @offsetOf(GDT.Table, "user_code_64") | 0b11;
context.ss = @offsetOf(GDT.Table, "user_data_64") | 0b11;
log.debug("CS: 0x{x}. SS: 0x{x}", .{ context.cs, context.ss });
},
}
context.rflags = RFLAGS.Flags.from_flag(.IF).bits;
context.rip = entry_point.start_address;
context.rsp = user_stack;
// TODO: remove when doing userspace
log.debug("RSP: 0x{x}", .{context.rsp});
kernel.assert(@src(), context.rsp < thread.kernel_stack_base.value + thread.kernel_stack_size);
context.rdi = entry_point.argument;
return context;
}
pub fn debug(context: *Context) void {
log.debug("Context address: 0x{x}", .{@ptrToInt(context)});
inline for (kernel.fields(Context)) |field| {
log.debug("{s}: 0x{x}", .{ field.name, @field(context, field.name) });
}
}
pub fn check(context: *Context, src: kernel.SourceLocation) void {
var failed = false;
failed = failed or context.cs > 0x100;
failed = failed or context.ss > 0x100;
// TODO: more checking
if (failed) {
context.debug();
kernel.panic("check failed: {s}:{}:{} {s}()", .{ src.file, src.line, src.column, src.fn_name });
}
}
};
//pub extern fn switch_context(new_context: *Context, new_address_space: *AddressSpace, kernel_stack: u64, new_thread: *Thread, old_address_space: *Virtual.AddressSpace) callconv(.C) void;
export fn switch_context() callconv(.Naked) void {
asm volatile (
\\cli
\\
\\mov (%%rsi), %%rsi
\\mov %%cr3, %%rax
\\cmp %%rsi, %%rax
\\je .cont
\\mov %%rsi, %%cr3
\\.cont:
\\mov %%rdi, %%rsp
\\mov %%rcx, %%rsi
\\mov %%r8, %%rdx
);
asm volatile (
\\call post_context_switch
);
interrupts.epilogue();
unreachable;
}
export fn post_context_switch(context: *Context, new_thread: *kernel.scheduler.Thread, old_address_space: *kernel.Virtual.AddressSpace) callconv(.C) void {
log.debug("Context switching", .{});
if (kernel.scheduler.lock.were_interrupts_enabled) {
@panic("interrupts were enabled");
}
kernel.scheduler.lock.release();
//kernel.assert(@src(), context == new_thread.context);
//kernel.assert(@src(), context.rsp < new_thread.kernel_stack_base.value + new_thread.kernel_stack_size);
context.check(@src());
const current_cpu = get_current_cpu().?;
current_cpu.current_thread = new_thread;
// TODO: checks
//const new_thread = current_thread.time_slices == 1;
// TODO: close reference or dettach address space
_ = old_address_space;
new_thread.last_known_execution_address = context.rip;
current_cpu.lapic.end_of_interrupt();
if (are_interrupts_enabled()) @panic("interrupts enabled");
if (current_cpu.spinlock_count > 0) @panic("spinlocks active");
// TODO: profiling
} | src/kernel/arch/x86_64.zig |
/// Esc represents the Ansi Escape code.
pub const Esc: []const u8 = "\x1b";
/// EscapePrefix represents the common "Esc[" escaping prefix pattern.
pub const EscapePrefix: []const u8 = Esc ++ "[";
/// Reset represents the reset code. All text attributes will be turned off.
pub const Reset: []const u8 = "0";
/// cursor is a namespace struct that groups all cursor ansi escape codes
pub const cursor = struct {
// TODO Investigate the difference between 'H' and 'f' suffixes.
/// Moves the cursor to the specified position (coordinates).
/// If you do not specify a position, the cursor moves to the home position at the upper-left corner of the screen (line 0, column 0). This escape sequence works the same way as the following Cursor Position escape sequence.
pub const PositionSuffix1: []const u8 = "H";
pub const PositionSuffix2: []const u8 = "f";
/// Moves the cursor up by the specified number of lines without changing columns.
/// If the cursor is already on the top line, ANSI.SYS ignores this sequence.
pub const UpSuffix: []const u8 = "A";
/// Moves the cursor down by the specified number of lines without changing columns.
/// If the cursor is already on the bottom line, ANSI.SYS ignores this sequence.
pub const DownSuffix: []const u8 = "B";
/// Moves the cursor forward by the specified number of columns without changing lines.
/// If the cursor is already in the rightmost column, ANSI.SYS ignores this sequence.
pub const ForwardSuffix: []const u8 = "C";
/// Moves the cursor back by the specified number of columns without changing lines.
/// If the cursor is already in the leftmost column, ANSI.SYS ignores this sequence.
pub const BackwardSuffix: []const u8 = "D";
/// Saves the current cursor position.
/// You can move the cursor to the saved cursor position by using the Restore Cursor Position sequence.
pub const SavePositionSuffix: []const u8 = "s";
/// Returns the cursor to the position stored by the Save Cursor Position sequence.
pub const RestorePositionSuffix: []const u8 = "u";
/// Clears the screen and moves the cursor to the home position (line 0, column 0).
pub const EraseDisplaySuffix: []const u8 = "2J";
/// Clears all characters from the cursor position to the end of the line (including the character at the cursor position).
pub const EraseLineSuffix: []const u8 = "K";
};
pub const graphics = struct {
/// GraphicsSuffix represents the suffix used for graphics escaping.
///
/// Calls the graphics functions specified by the following values.
/// These specified functions remain active until the next occurrence of this escape sequence.
/// Graphics mode changes the colors and attributes of text (such as bold and underline) displayed on the screen.
pub const SetModeSuffix: []const u8 = "m";
pub const attr = struct {
// TODO namespace conflicts
pub const AttrReset: []const u8 = "0";
pub const Bold: []const u8 = "1";
pub const Dim: []const u8 = "2";
pub const Italic: []const u8 = "3";
pub const Underline: []const u8 = "4";
// TODO 5? 6?
pub const Inverse: []const u8 = "7";
pub const Hidden: []const u8 = "8";
pub const Strikethrough: []const u8 = "9";
};
};
/// color namespace groups all color codes.
pub const color = struct {
/// fg namespace groups all foreground color codes.
pub const fg = struct {
pub const Black: []const u8 = "30";
pub const Red: []const u8 = "31";
pub const Green: []const u8 = "32";
pub const Yellow: []const u8 = "33";
pub const Blue: []const u8 = "34";
pub const Magenta: []const u8 = "35";
pub const Cyan: []const u8 = "36";
pub const White: []const u8 = "37";
// Next arguments are `5;<n>` for Hicolors (0-255) or `2;<r>;<g>;<b> for Custom RGB`
// example: "\x1b[38;5;80m"
pub const FgHiColor: []const u8 = "38";
pub const FgReset: []const u8 = "39";
pub const FgHiColorPreffix: []const u8 = FgHiColor ++ ";5";
pub const FgHiColorRGBPreffix: []const u8 = FgHiColor ++ ";2";
};
/// bg namespace groups all background color codes.
pub const bg = struct {
pub const Black: []const u8 = "40";
pub const Red: []const u8 = "41";
pub const Green: []const u8 = "42";
pub const Yellow: []const u8 = "43";
pub const Blue: []const u8 = "44";
pub const Magenta: []const u8 = "45";
pub const Cyan: []const u8 = "46";
pub const White: []const u8 = "47";
// Next arguments are `5;<n>` for Hicolors (0-255) or `2;<r>;<g>;<b> for Custom RGB`
// example: "\x1b[38;5;80m"
pub const BgHiColor: []const u8 = "48";
pub const BgReset: []const u8 = "49";
pub const BgHiColorPreffix: []const u8 = BgHiColor ++ ";5";
pub const BgHiColorRGBPreffix: []const u8 = BgHiColor ++ ";2";
};
};
pub inline fn resetEscapeSequence() []const u8 {
return EscapePrefix ++ Reset ++ graphics.SetModeSuffix;
}
pub inline fn resetForegroundEscapeSequence() []const u8 {
return EscapePrefix ++ color.fg.FgReset ++ graphics.SetModeSuffix;
}
pub inline fn resetBackgroundEscapeSequence() []const u8 {
return EscapePrefix ++ color.bg.BgReset ++ graphics.SetModeSuffix;
} | src/codes.zig |
const std = @import("std");
const mem = std.mem;
const Ambiguous = @This();
allocator: *mem.Allocator,
array: []bool,
lo: u21 = 161,
hi: u21 = 1114109,
pub fn init(allocator: *mem.Allocator) !Ambiguous {
var instance = Ambiguous{
.allocator = allocator,
.array = try allocator.alloc(bool, 1113949),
};
mem.set(bool, instance.array, false);
var index: u21 = 0;
instance.array[0] = true;
instance.array[3] = true;
instance.array[6] = true;
instance.array[7] = true;
instance.array[9] = true;
instance.array[12] = true;
instance.array[13] = true;
instance.array[15] = true;
instance.array[16] = true;
index = 17;
while (index <= 18) : (index += 1) {
instance.array[index] = true;
}
instance.array[19] = true;
index = 21;
while (index <= 22) : (index += 1) {
instance.array[index] = true;
}
instance.array[23] = true;
instance.array[24] = true;
instance.array[25] = true;
index = 27;
while (index <= 29) : (index += 1) {
instance.array[index] = true;
}
instance.array[30] = true;
instance.array[37] = true;
instance.array[47] = true;
instance.array[54] = true;
instance.array[55] = true;
index = 61;
while (index <= 64) : (index += 1) {
instance.array[index] = true;
}
instance.array[69] = true;
index = 71;
while (index <= 73) : (index += 1) {
instance.array[index] = true;
}
index = 75;
while (index <= 76) : (index += 1) {
instance.array[index] = true;
}
instance.array[79] = true;
index = 81;
while (index <= 82) : (index += 1) {
instance.array[index] = true;
}
instance.array[86] = true;
index = 87;
while (index <= 89) : (index += 1) {
instance.array[index] = true;
}
instance.array[91] = true;
instance.array[93] = true;
instance.array[96] = true;
instance.array[112] = true;
instance.array[114] = true;
instance.array[122] = true;
index = 133;
while (index <= 134) : (index += 1) {
instance.array[index] = true;
}
instance.array[138] = true;
index = 144;
while (index <= 146) : (index += 1) {
instance.array[index] = true;
}
instance.array[151] = true;
index = 158;
while (index <= 161) : (index += 1) {
instance.array[index] = true;
}
instance.array[163] = true;
index = 167;
while (index <= 170) : (index += 1) {
instance.array[index] = true;
}
instance.array[172] = true;
index = 177;
while (index <= 178) : (index += 1) {
instance.array[index] = true;
}
index = 197;
while (index <= 198) : (index += 1) {
instance.array[index] = true;
}
instance.array[202] = true;
instance.array[301] = true;
instance.array[303] = true;
instance.array[305] = true;
instance.array[307] = true;
instance.array[309] = true;
instance.array[311] = true;
instance.array[313] = true;
instance.array[315] = true;
instance.array[432] = true;
instance.array[448] = true;
instance.array[547] = true;
instance.array[550] = true;
index = 552;
while (index <= 554) : (index += 1) {
instance.array[index] = true;
}
instance.array[556] = true;
instance.array[559] = true;
index = 567;
while (index <= 570) : (index += 1) {
instance.array[index] = true;
}
instance.array[572] = true;
instance.array[574] = true;
index = 607;
while (index <= 718) : (index += 1) {
instance.array[index] = true;
}
index = 752;
while (index <= 768) : (index += 1) {
instance.array[index] = true;
}
index = 770;
while (index <= 776) : (index += 1) {
instance.array[index] = true;
}
index = 784;
while (index <= 800) : (index += 1) {
instance.array[index] = true;
}
index = 802;
while (index <= 808) : (index += 1) {
instance.array[index] = true;
}
instance.array[864] = true;
index = 879;
while (index <= 942) : (index += 1) {
instance.array[index] = true;
}
instance.array[944] = true;
instance.array[8047] = true;
index = 8050;
while (index <= 8052) : (index += 1) {
instance.array[index] = true;
}
instance.array[8053] = true;
instance.array[8055] = true;
instance.array[8056] = true;
instance.array[8059] = true;
instance.array[8060] = true;
index = 8063;
while (index <= 8065) : (index += 1) {
instance.array[index] = true;
}
index = 8067;
while (index <= 8070) : (index += 1) {
instance.array[index] = true;
}
instance.array[8079] = true;
index = 8081;
while (index <= 8082) : (index += 1) {
instance.array[index] = true;
}
instance.array[8084] = true;
instance.array[8090] = true;
instance.array[8093] = true;
instance.array[8147] = true;
instance.array[8158] = true;
index = 8160;
while (index <= 8163) : (index += 1) {
instance.array[index] = true;
}
instance.array[8203] = true;
instance.array[8290] = true;
instance.array[8292] = true;
instance.array[8296] = true;
instance.array[8306] = true;
instance.array[8309] = true;
index = 8320;
while (index <= 8321) : (index += 1) {
instance.array[index] = true;
}
instance.array[8325] = true;
instance.array[8330] = true;
index = 8370;
while (index <= 8371) : (index += 1) {
instance.array[index] = true;
}
index = 8378;
while (index <= 8381) : (index += 1) {
instance.array[index] = true;
}
index = 8383;
while (index <= 8394) : (index += 1) {
instance.array[index] = true;
}
index = 8399;
while (index <= 8408) : (index += 1) {
instance.array[index] = true;
}
instance.array[8424] = true;
index = 8431;
while (index <= 8435) : (index += 1) {
instance.array[index] = true;
}
index = 8436;
while (index <= 8440) : (index += 1) {
instance.array[index] = true;
}
index = 8471;
while (index <= 8472) : (index += 1) {
instance.array[index] = true;
}
instance.array[8497] = true;
instance.array[8499] = true;
instance.array[8518] = true;
instance.array[8543] = true;
index = 8545;
while (index <= 8546) : (index += 1) {
instance.array[index] = true;
}
index = 8550;
while (index <= 8551) : (index += 1) {
instance.array[index] = true;
}
instance.array[8554] = true;
instance.array[8558] = true;
instance.array[8560] = true;
instance.array[8564] = true;
instance.array[8569] = true;
index = 8572;
while (index <= 8575) : (index += 1) {
instance.array[index] = true;
}
instance.array[8578] = true;
instance.array[8580] = true;
index = 8582;
while (index <= 8587) : (index += 1) {
instance.array[index] = true;
}
instance.array[8589] = true;
index = 8595;
while (index <= 8598) : (index += 1) {
instance.array[index] = true;
}
index = 8603;
while (index <= 8604) : (index += 1) {
instance.array[index] = true;
}
instance.array[8615] = true;
instance.array[8619] = true;
instance.array[8625] = true;
index = 8639;
while (index <= 8640) : (index += 1) {
instance.array[index] = true;
}
index = 8643;
while (index <= 8646) : (index += 1) {
instance.array[index] = true;
}
index = 8649;
while (index <= 8650) : (index += 1) {
instance.array[index] = true;
}
index = 8653;
while (index <= 8654) : (index += 1) {
instance.array[index] = true;
}
index = 8673;
while (index <= 8674) : (index += 1) {
instance.array[index] = true;
}
index = 8677;
while (index <= 8678) : (index += 1) {
instance.array[index] = true;
}
instance.array[8692] = true;
instance.array[8696] = true;
instance.array[8708] = true;
instance.array[8734] = true;
instance.array[8817] = true;
index = 9151;
while (index <= 9210) : (index += 1) {
instance.array[index] = true;
}
index = 9211;
while (index <= 9288) : (index += 1) {
instance.array[index] = true;
}
index = 9290;
while (index <= 9310) : (index += 1) {
instance.array[index] = true;
}
index = 9311;
while (index <= 9386) : (index += 1) {
instance.array[index] = true;
}
index = 9391;
while (index <= 9426) : (index += 1) {
instance.array[index] = true;
}
index = 9439;
while (index <= 9454) : (index += 1) {
instance.array[index] = true;
}
index = 9457;
while (index <= 9460) : (index += 1) {
instance.array[index] = true;
}
index = 9471;
while (index <= 9472) : (index += 1) {
instance.array[index] = true;
}
index = 9474;
while (index <= 9480) : (index += 1) {
instance.array[index] = true;
}
index = 9489;
while (index <= 9490) : (index += 1) {
instance.array[index] = true;
}
instance.array[9493] = true;
instance.array[9494] = true;
index = 9499;
while (index <= 9500) : (index += 1) {
instance.array[index] = true;
}
instance.array[9503] = true;
instance.array[9504] = true;
index = 9509;
while (index <= 9511) : (index += 1) {
instance.array[index] = true;
}
instance.array[9514] = true;
index = 9517;
while (index <= 9520) : (index += 1) {
instance.array[index] = true;
}
index = 9537;
while (index <= 9540) : (index += 1) {
instance.array[index] = true;
}
instance.array[9550] = true;
index = 9572;
while (index <= 9573) : (index += 1) {
instance.array[index] = true;
}
instance.array[9576] = true;
index = 9581;
while (index <= 9582) : (index += 1) {
instance.array[index] = true;
}
instance.array[9595] = true;
instance.array[9597] = true;
instance.array[9631] = true;
instance.array[9633] = true;
index = 9663;
while (index <= 9664) : (index += 1) {
instance.array[index] = true;
}
index = 9666;
while (index <= 9668) : (index += 1) {
instance.array[index] = true;
}
index = 9670;
while (index <= 9673) : (index += 1) {
instance.array[index] = true;
}
index = 9675;
while (index <= 9676) : (index += 1) {
instance.array[index] = true;
}
instance.array[9678] = true;
index = 9725;
while (index <= 9726) : (index += 1) {
instance.array[index] = true;
}
instance.array[9758] = true;
index = 9765;
while (index <= 9772) : (index += 1) {
instance.array[index] = true;
}
index = 9774;
while (index <= 9778) : (index += 1) {
instance.array[index] = true;
}
index = 9780;
while (index <= 9792) : (index += 1) {
instance.array[index] = true;
}
instance.array[9794] = true;
index = 9799;
while (index <= 9800) : (index += 1) {
instance.array[index] = true;
}
index = 9802;
while (index <= 9808) : (index += 1) {
instance.array[index] = true;
}
instance.array[9811] = true;
index = 9813;
while (index <= 9816) : (index += 1) {
instance.array[index] = true;
}
index = 9818;
while (index <= 9819) : (index += 1) {
instance.array[index] = true;
}
index = 9821;
while (index <= 9822) : (index += 1) {
instance.array[index] = true;
}
instance.array[9884] = true;
index = 9941;
while (index <= 9950) : (index += 1) {
instance.array[index] = true;
}
index = 10933;
while (index <= 10936) : (index += 1) {
instance.array[index] = true;
}
index = 12711;
while (index <= 12718) : (index += 1) {
instance.array[index] = true;
}
index = 57183;
while (index <= 63582) : (index += 1) {
instance.array[index] = true;
}
index = 64863;
while (index <= 64878) : (index += 1) {
instance.array[index] = true;
}
instance.array[65372] = true;
index = 127071;
while (index <= 127081) : (index += 1) {
instance.array[index] = true;
}
index = 127087;
while (index <= 127116) : (index += 1) {
instance.array[index] = true;
}
index = 127119;
while (index <= 127176) : (index += 1) {
instance.array[index] = true;
}
index = 127183;
while (index <= 127212) : (index += 1) {
instance.array[index] = true;
}
index = 127214;
while (index <= 127215) : (index += 1) {
instance.array[index] = true;
}
index = 127226;
while (index <= 127243) : (index += 1) {
instance.array[index] = true;
}
index = 917599;
while (index <= 917838) : (index += 1) {
instance.array[index] = true;
}
index = 982879;
while (index <= 1048412) : (index += 1) {
instance.array[index] = true;
}
index = 1048415;
while (index <= 1113948) : (index += 1) {
instance.array[index] = true;
}
// Placeholder: 0. Struct name, 1. Code point kind
return instance;
}
pub fn deinit(self: *Ambiguous) void {
self.allocator.free(self.array);
}
// isAmbiguous checks if cp is of the kind Ambiguous.
pub fn isAmbiguous(self: Ambiguous, 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/DerivedEastAsianWidth/Ambiguous.zig |
const std = @import("std");
const c = @cImport({
@cInclude("stdio.h");
@cInclude("stdlib.h");
@cInclude("string.h");
@cInclude("time.h");
@cInclude("lauxlib.h");
@cInclude("lua.h");
@cInclude("lualib.h");
@cInclude("libavcodec/avcodec.h");
@cInclude("libavformat/avformat.h");
@cInclude("libavformat/avio.h");
@cInclude("libswscale/swscale.h");
});
const av_error_codes = [_]c_int{
c.AVERROR_BSF_NOT_FOUND,
c.AVERROR_BUG,
c.AVERROR_BUFFER_TOO_SMALL,
c.AVERROR_DECODER_NOT_FOUND,
c.AVERROR_DEMUXER_NOT_FOUND,
c.AVERROR_ENCODER_NOT_FOUND,
c.AVERROR_EOF,
c.AVERROR_EXIT,
c.AVERROR_EXTERNAL,
c.AVERROR_FILTER_NOT_FOUND,
c.AVERROR_INVALIDDATA,
c.AVERROR_MUXER_NOT_FOUND,
c.AVERROR_OPTION_NOT_FOUND,
c.AVERROR_PATCHWELCOME,
c.AVERROR_PROTOCOL_NOT_FOUND,
c.AVERROR_STREAM_NOT_FOUND,
c.AVERROR_BUG2,
c.AVERROR_UNKNOWN,
c.AVERROR_EXPERIMENTAL,
c.AVERROR_INPUT_CHANGED,
c.AVERROR_OUTPUT_CHANGED,
c.AVERROR_HTTP_BAD_REQUEST,
c.AVERROR_HTTP_UNAUTHORIZED,
c.AVERROR_HTTP_FORBIDDEN,
c.AVERROR_HTTP_NOT_FOUND,
c.AVERROR_HTTP_OTHER_4XX,
c.AVERROR_HTTP_SERVER_ERROR,
};
const av_errors = [_][]const u8{
"AVERROR_BSF_NOT_FOUND",
"AVERROR_BUG",
"AVERROR_BUFFER_TOO_SMALL",
"AVERROR_DECODER_NOT_FOUND",
"AVERROR_DEMUXER_NOT_FOUND",
"AVERROR_ENCODER_NOT_FOUND",
"AVERROR_EOF",
"AVERROR_EXIT",
"AVERROR_EXTERNAL",
"AVERROR_FILTER_NOT_FOUND",
"AVERROR_INVALIDDATA",
"AVERROR_MUXER_NOT_FOUND",
"AVERROR_OPTION_NOT_FOUND",
"AVERROR_PATCHWELCOME",
"AVERROR_PROTOCOL_NOT_FOUND",
"AVERROR_STREAM_NOT_FOUND",
"AVERROR_BUG2",
"AVERROR_UNKNOWN",
"AVERROR_EXPERIMENTAL",
"AVERROR_INPUT_CHANGED",
"AVERROR_OUTPUT_CHANGED",
"AVERROR_HTTP_BAD_REQUEST",
"AVERROR_HTTP_UNAUTHORIZED",
"AVERROR_HTTP_FORBIDDEN",
"AVERROR_HTTP_NOT_FOUND",
"AVERROR_HTTP_OTHER_4XX",
"AVERROR_HTTP_SERVER_ERROR",
};
fn libav_strerror(error_code: c_int) ?[]const u8 {
var idx: usize = 0;
while (idx < av_error_codes.len) : (idx += 1) {
if (av_error_codes[idx] == error_code) return av_errors[idx];
}
return null;
}
pub const funny_stream_loop_t = extern struct {
packet: c.AVPacket,
oc: *c.AVFormatContext,
stream: ?*c.AVStream = null,
codec: *c.AVCodec,
size: c_int,
picture_buf: [*]u8,
pic: *c.AVFrame,
size2: c_int,
picture_buf2: [*]u8,
pic_rgb: *c.AVFrame,
};
pub const funny_stream_t = extern struct {
img_convert_ctx: *c.SwsContext,
context: *c.AVFormatContext,
ccontext: *c.AVCodecContext,
video_stream_index: usize,
loop_ctx: funny_stream_loop_t,
stop: bool = false,
};
// global funny_open mutex
var open_mutex = std.Thread.Mutex{};
const logger = std.log.scoped(.lovr_rtsp);
fn possible_av_error(L: *c.lua_State, ret: c_int) !void {
if (ret < 0) {
const maybe_av_error_name = libav_strerror(ret);
if (maybe_av_error_name) |error_name| {
std.log.err("av error: {s}", .{error_name});
}
c.lua_pushstring(L, "libav issue");
_ = c.lua_error(L);
return error.AvError;
}
}
export fn funny_open(arg_L: ?*c.lua_State) callconv(.C) c_int {
var L = arg_L.?;
var rtsp_url_len: usize = undefined;
var rtsp_url = c.luaL_checklstring(L, @as(c_int, 1), &rtsp_url_len);
return funny_open_wrapped(L, rtsp_url[0..rtsp_url_len :0]) catch |err| {
logger.err("error happened shit {s}", .{@errorName(err)});
if (@errorReturnTrace()) |trace| {
std.debug.dumpStackTrace(trace.*);
}
c.lua_pushstring(L, "error in native rtsp library");
_ = c.lua_error(L);
return 1;
};
}
fn funny_open_wrapped(L: *c.lua_State, rtsp_url: [:0]const u8) !c_int {
open_mutex.lock();
defer open_mutex.unlock();
var context_cptr = c.avformat_alloc_context().?;
var context = @ptrCast(*c.AVFormatContext, context_cptr);
const codec = c.avcodec_find_decoder(@bitCast(c_uint, c.AV_CODEC_ID_H264)) orelse {
c.lua_pushstring(L, "could not find h264 decoder");
return c.lua_error(L);
};
var codec_context_cptr = c.avcodec_alloc_context3(codec).?;
var codec_context = @ptrCast(*c.AVCodecContext, codec_context_cptr);
var opts: ?*c.AVDictionary = null;
try possible_av_error(L, c.av_dict_set(&opts, "reorder_queue_size", "100000", 0));
if (c.avformat_open_input(&context_cptr, rtsp_url.ptr, null, &opts) != @as(c_int, 0)) {
c.lua_pushstring(L, "c.avformat_open_input error");
_ = c.lua_error(L);
return error.AvError;
}
// set it again just in case avformat_open_input changed the pointer value!!!
context = @ptrCast(*c.AVFormatContext, context_cptr);
if (c.avformat_find_stream_info(context, null) < 0) {
c.lua_pushstring(L, "c.avformat_find_stream_info error");
_ = c.lua_error(L);
return error.AvError;
}
var maybe_video_stream_index: ?usize = null;
{
var i: usize = 0;
while (i < context.nb_streams) : (i += 1) {
if (context.streams[i].*.codec.*.codec_type == c.AVMEDIA_TYPE_VIDEO) {
maybe_video_stream_index = i;
}
}
}
var video_stream_index: usize = maybe_video_stream_index.?;
var packet: c.AVPacket = undefined;
c.av_init_packet(&packet);
var inner_loop_context = c.avformat_alloc_context();
try possible_av_error(L, c.av_read_play(context));
try possible_av_error(L, c.avcodec_get_context_defaults3(codec_context_cptr, codec));
codec_context = @ptrCast(*c.AVCodecContext, codec_context_cptr);
const stream_codec_context = context.streams[@intCast(usize, video_stream_index)].*.codec.?;
//const actual_stream_codec = stream_codec_context.*.codec.?;
try possible_av_error(L, c.avcodec_copy_context(codec_context_cptr, stream_codec_context));
codec_context = @ptrCast(*c.AVCodecContext, codec_context_cptr);
try possible_av_error(L, c.avcodec_open2(
codec_context,
codec,
null,
));
var img_convert_ctx = c.sws_getContext(
codec_context.width,
codec_context.height,
codec_context.pix_fmt,
codec_context.width,
codec_context.height,
c.AV_PIX_FMT_RGB24,
@as(c_int, 4),
null,
null,
null,
) orelse {
c.lua_pushstring(L, "failed to load sws context");
return c.lua_error(L);
};
// pic1 contains incoming yuv data, pic2 contains rgb24 data
const pic1_size = c.avpicture_get_size(
c.AV_PIX_FMT_YUV420P,
codec_context.width,
codec_context.height,
);
const pic1_buf = @ptrCast(
[*c]u8,
@alignCast(std.meta.alignment(u8), c.av_malloc(@bitCast(usize, @as(c_long, pic1_size)))),
);
const pic1 = c.av_frame_alloc();
try possible_av_error(L, c.avpicture_fill(
@ptrCast(*c.AVPicture, pic1),
pic1_buf,
c.AV_PIX_FMT_YUV420P,
codec_context.width,
codec_context.height,
));
const pic2_size = c.avpicture_get_size(
c.AV_PIX_FMT_RGB24,
codec_context.width,
codec_context.height,
);
const pic2_buf = @ptrCast(
[*c]u8,
@alignCast(std.meta.alignment(u8), c.av_malloc(@bitCast(usize, @as(c_long, pic2_size)))),
);
const pic2 = c.av_frame_alloc();
try possible_av_error(L, c.avpicture_fill(
@ptrCast(*c.AVPicture, pic2),
pic2_buf,
c.AV_PIX_FMT_RGB24,
codec_context.width,
codec_context.height,
));
var funny_stream_1: *funny_stream_t = @ptrCast(
*funny_stream_t,
@alignCast(std.meta.alignment(funny_stream_t), c.lua_newuserdata(L, @sizeOf(funny_stream_t)).?),
);
c.lua_getfield(L, -@as(c_int, 10000), "funny_stream");
_ = c.lua_setmetatable(L, -@as(c_int, 2));
funny_stream_1.* = funny_stream_t{
.img_convert_ctx = img_convert_ctx,
.context = context,
.ccontext = codec_context,
.video_stream_index = video_stream_index,
.loop_ctx = funny_stream_loop_t{
.packet = packet,
.oc = inner_loop_context,
.codec = codec,
.size = pic1_size,
.picture_buf = pic1_buf,
.pic = pic1,
.size2 = pic2_size,
.picture_buf2 = pic2_buf,
.pic_rgb = pic2,
},
};
_ = c.printf("init done!\n");
return 1;
}
fn rtsp_fetch_frame(L: *c.lua_State, funny_stream_1: *funny_stream_t, blob_ptr: [*]u8) !f64 {
var timer = try std.time.Timer.start();
std.log.info("fetching a frame", .{});
if (c.av_read_frame(funny_stream_1.*.context, &funny_stream_1.*.loop_ctx.packet) < @as(c_int, 0)) {
c.lua_pushstring(L, "c.av_read_frame return less than 0");
_ = c.lua_error(L);
}
if (funny_stream_1.*.loop_ctx.packet.stream_index == funny_stream_1.*.video_stream_index) {
if (funny_stream_1.*.loop_ctx.stream == null) {
std.log.info("creating stream", .{});
const codec_context = funny_stream_1.context.streams[funny_stream_1.video_stream_index].*.codec.?;
const actual_codec = codec_context.*.codec;
funny_stream_1.*.loop_ctx.stream = c.avformat_new_stream(funny_stream_1.*.loop_ctx.oc, actual_codec);
if (c.avcodec_copy_context(funny_stream_1.*.loop_ctx.stream.?.codec, codec_context) < 0) {
c.lua_pushstring(L, "failed to initialize av stream");
_ = c.lua_error(L);
}
funny_stream_1.*.loop_ctx.stream.?.sample_aspect_ratio =
codec_context.?.*.sample_aspect_ratio;
}
var check: c_int = 0;
funny_stream_1.*.loop_ctx.packet.stream_index = funny_stream_1.*.loop_ctx.stream.?.id;
_ = c.avcodec_decode_video2(funny_stream_1.*.ccontext, funny_stream_1.*.loop_ctx.pic, &check, &funny_stream_1.*.loop_ctx.packet);
if (check != @as(c_int, 0)) {
_ = c.sws_scale(
funny_stream_1.*.img_convert_ctx,
@ptrCast([*c][*c]u8, @alignCast(std.meta.alignment([*c][*c]u8), &funny_stream_1.*.loop_ctx.pic.*.data)),
@ptrCast([*c]c_int, @alignCast(std.meta.alignment(c_int), &funny_stream_1.*.loop_ctx.pic.*.linesize)),
@as(c_int, 0),
funny_stream_1.*.ccontext.*.height,
@ptrCast([*c][*c]u8, @alignCast(std.meta.alignment([*c][*c]u8), &funny_stream_1.*.loop_ctx.pic_rgb.*.data)),
@ptrCast([*c]c_int, @alignCast(std.meta.alignment(c_int), &funny_stream_1.*.loop_ctx.pic_rgb.*.linesize)),
);
const picbuf_size = @bitCast(c_ulong, @as(c_long, funny_stream_1.*.loop_ctx.size2));
std.mem.copy(u8, blob_ptr[0..picbuf_size], funny_stream_1.*.loop_ctx.picture_buf2[0..picbuf_size]);
}
}
//c.av_free_packet(&funny_stream_1.*.loop_ctx.packet);
c.av_init_packet(&funny_stream_1.*.loop_ctx.packet);
const elapsed: f64 = @intToFloat(f64, timer.read()) / @intToFloat(f64, std.time.ns_per_s);
return elapsed;
}
export fn rtsp_stop_wrapper(arg_L: ?*c.lua_State) callconv(.C) c_int {
var L = arg_L.?;
if (c.lua_gettop(L) != @as(c_int, 2)) {
return c.luaL_error(L, "expecting exactly 2 arguments");
}
const rtsp_stream_voidptr = c.luaL_checkudata(L, @as(c_int, 1), "funny_stream");
var rtsp_stream: *funny_stream_t = @ptrCast(
*funny_stream_t,
@alignCast(std.meta.alignment(funny_stream_t), rtsp_stream_voidptr.?),
);
rtsp_stream.stop = true;
return 0;
}
export fn rtsp_frame_loop_wrapper(arg_L: ?*c.lua_State) callconv(.C) c_int {
var L = arg_L.?;
return rtsp_frame_loop(L) catch |err| {
logger.err("error happened shit {s}", .{@errorName(err)});
if (@errorReturnTrace()) |trace| {
std.debug.dumpStackTrace(trace.*);
}
c.lua_pushstring(L, "error in native rtsp library");
_ = c.lua_error(L);
return 1;
};
}
const FPS_TARGET: f64 = 45;
const FPS_BUDGET: f64 = (1.0 / FPS_TARGET);
fn rtsp_frame_loop(L: *c.lua_State) !c_int {
if (c.lua_gettop(L) != @as(c_int, 2)) {
return c.luaL_error(L, "expecting exactly 2 arguments");
}
const rtsp_stream_voidptr = c.luaL_checkudata(L, @as(c_int, 1), "funny_stream");
var rtsp_stream: *funny_stream_t = @ptrCast(
*funny_stream_t,
@alignCast(std.meta.alignment(funny_stream_t), rtsp_stream_voidptr.?),
);
var blob_ptr: ?[*]u8 = @ptrCast(?[*]u8, c.lua_touserdata(L, @as(c_int, 2)));
while (true) {
if (rtsp_stream.stop) {
std.log.info("stream loop stopping", .{});
break;
}
const time_receiving_frame: f64 = try rtsp_fetch_frame(L, rtsp_stream, blob_ptr.?);
const remaining_time = FPS_BUDGET - time_receiving_frame;
//std.log.info("timings {d:.6} {d:.6} {d:.6}", .{ FPS_BUDGET, time_receiving_frame, remaining_time });
if (remaining_time > 0) {
// good case: we decoded fast
// we can sleep the rest of the ms knowing we're on 60fps target
//std.time.sleep(@floatToInt(u64, remaining_time * std.time.ns_per_s));
}
}
return 0;
}
const funny_lib = [_]c.luaL_Reg{
c.luaL_Reg{ .name = "open", .func = funny_open },
c.luaL_Reg{ .name = "frameLoop", .func = rtsp_frame_loop_wrapper },
c.luaL_Reg{ .name = "stop", .func = rtsp_stop_wrapper },
c.luaL_Reg{ .name = null, .func = null },
};
export fn luaopen_rtsp(L: ?*c.lua_State) c_int {
open_mutex.lock();
defer open_mutex.unlock();
_ = c.avformat_network_init();
_ = c.luaL_newmetatable(L, "funny_stream");
c.luaL_register(L, "rtsp", &funny_lib);
return 1;
} | src/main.zig |
const std = @import("std");
const Timezone = @import("datetime.zig").Timezone;
const create = Timezone.create;
// Timezones
pub const Africa = struct {
pub const Abidjan = create("Africa/Abidjan", 0);
pub const Accra = create("Africa/Accra", 0);
pub const Addis_Ababa = create("Africa/Addis_Ababa", 180);
pub const Algiers = create("Africa/Algiers", 60);
pub const Asmara = create("Africa/Asmara", 180);
pub const Bamako = create("Africa/Bamako", 0);
pub const Bangui = create("Africa/Bangui", 60);
pub const Banjul = create("Africa/Banjul", 0);
pub const Bissau = create("Africa/Bissau", 0);
pub const Blantyre = create("Africa/Blantyre", 120);
pub const Brazzaville = create("Africa/Brazzaville", 60);
pub const Bujumbura = create("Africa/Bujumbura", 120);
pub const Cairo = create("Africa/Cairo", 120);
pub const Casablanca = create("Africa/Casablanca", 60);
pub const Ceuta = create("Africa/Ceuta", 60);
pub const Conakry = create("Africa/Conakry", 0);
pub const Dakar = create("Africa/Dakar", 0);
pub const Dar_es_Salaam = create("Africa/Dar_es_Salaam", 180);
pub const Djibouti = create("Africa/Djibouti", 180);
pub const Douala = create("Africa/Douala", 60);
pub const El_Aaiun = create("Africa/El_Aaiun", 0);
pub const Freetown = create("Africa/Freetown", 0);
pub const Gaborone = create("Africa/Gaborone", 120);
pub const Harare = create("Africa/Harare", 120);
pub const Johannesburg = create("Africa/Johannesburg", 120);
pub const Juba = create("Africa/Juba", 180);
pub const Kampala = create("Africa/Kampala", 180);
pub const Khartoum = create("Africa/Khartoum", 120);
pub const Kigali = create("Africa/Kigali", 120);
pub const Kinshasa = create("Africa/Kinshasa", 60);
pub const Lagos = create("Africa/Lagos", 60);
pub const Libreville = create("Africa/Libreville", 60);
pub const Lome = create("Africa/Lome", 0);
pub const Luanda = create("Africa/Luanda", 60);
pub const Lubumbashi = create("Africa/Lubumbashi", 120);
pub const Lusaka = create("Africa/Lusaka", 120);
pub const Malabo = create("Africa/Malabo", 60);
pub const Maputo = create("Africa/Maputo", 120);
pub const Maseru = create("Africa/Maseru", 120);
pub const Mbabane = create("Africa/Mbabane", 120);
pub const Mogadishu = create("Africa/Mogadishu", 180);
pub const Monrovia = create("Africa/Monrovia", 0);
pub const Nairobi = create("Africa/Nairobi", 180);
pub const Ndjamena = create("Africa/Ndjamena", 60);
pub const Niamey = create("Africa/Niamey", 60);
pub const Nouakchott = create("Africa/Nouakchott", 0);
pub const Ouagadougou = create("Africa/Ouagadougou", 0);
pub const Porto_Novo = create("Africa/Porto-Novo", 60);
pub const Sao_Tome = create("Africa/Sao_Tome", 0);
pub const Timbuktu = create("Africa/Timbuktu", 0);
pub const Tripoli = create("Africa/Tripoli", 120);
pub const Tunis = create("Africa/Tunis", 60);
pub const Windhoek = create("Africa/Windhoek", 120);
};
pub const America = struct {
pub const Adak = create("America/Adak", -600);
pub const Anchorage = create("America/Anchorage", -540);
pub const Anguilla = create("America/Anguilla", -240);
pub const Antigua = create("America/Antigua", -240);
pub const Araguaina = create("America/Araguaina", -180);
pub const Argentina = struct {
pub const Buenos_Aires = create("America/Argentina/Buenos_Aires", -180);
pub const Catamarca = create("America/Argentina/Catamarca", -180);
pub const ComodRivadavia = create("America/Argentina/ComodRivadavia", -180);
pub const Cordoba = create("America/Argentina/Cordoba", -180);
pub const Jujuy = create("America/Argentina/Jujuy", -180);
pub const La_Rioja = create("America/Argentina/La_Rioja", -180);
pub const Mendoza = create("America/Argentina/Mendoza", -180);
pub const Rio_Gallegos = create("America/Argentina/Rio_Gallegos", -180);
pub const Salta = create("America/Argentina/Salta", -180);
pub const San_Juan = create("America/Argentina/San_Juan", -180);
pub const San_Luis = create("America/Argentina/San_Luis", -180);
pub const Tucuman = create("America/Argentina/Tucuman", -180);
pub const Ushuaia = create("America/Argentina/Ushuaia", -180);
};
pub const Aruba = create("America/Aruba", -240);
pub const Asuncion = create("America/Asuncion", -240);
pub const Atikokan = create("America/Atikokan", -300);
pub const Atka = create("America/Atka", -600);
pub const Bahia = create("America/Bahia", -180);
pub const Bahia_Banderas = create("America/Bahia_Banderas", -360);
pub const Barbados = create("America/Barbados", -240);
pub const Belem = create("America/Belem", -180);
pub const Belize = create("America/Belize", -360);
pub const Blanc_Sablon = create("America/Blanc-Sablon", -240);
pub const Boa_Vista = create("America/Boa_Vista", -240);
pub const Bogota = create("America/Bogota", -300);
pub const Boise = create("America/Boise", -420);
pub const Buenos_Aires = create("America/Buenos_Aires", -180);
pub const Cambridge_Bay = create("America/Cambridge_Bay", -420);
pub const Campo_Grande = create("America/Campo_Grande", -240);
pub const Cancun = create("America/Cancun", -300);
pub const Caracas = create("America/Caracas", -240);
pub const Catamarca = create("America/Catamarca", -180);
pub const Cayenne = create("America/Cayenne", -180);
pub const Cayman = create("America/Cayman", -300);
pub const Chicago = create("America/Chicago", -360);
pub const Chihuahua = create("America/Chihuahua", -420);
pub const Coral_Harbour = create("America/Coral_Harbour", -300);
pub const Cordoba = create("America/Cordoba", -180);
pub const Costa_Rica = create("America/Costa_Rica", -360);
pub const Creston = create("America/Creston", -420);
pub const Cuiaba = create("America/Cuiaba", -240);
pub const Curacao = create("America/Curacao", -240);
pub const Danmarkshavn = create("America/Danmarkshavn", 0);
pub const Dawson = create("America/Dawson", -480);
pub const Dawson_Creek = create("America/Dawson_Creek", -420);
pub const Denver = create("America/Denver", -420);
pub const Detroit = create("America/Detroit", -300);
pub const Dominica = create("America/Dominica", -240);
pub const Edmonton = create("America/Edmonton", -420);
pub const Eirunepe = create("America/Eirunepe", -300);
pub const El_Salvador = create("America/El_Salvador", -360);
pub const Ensenada = create("America/Ensenada", -480);
pub const Fort_Nelson = create("America/Fort_Nelson", -420);
pub const Fort_Wayne = create("America/Fort_Wayne", -300);
pub const Fortaleza = create("America/Fortaleza", -180);
pub const Glace_Bay = create("America/Glace_Bay", -240);
pub const Godthab = create("America/Godthab", -180);
pub const Goose_Bay = create("America/Goose_Bay", -240);
pub const Grand_Turk = create("America/Grand_Turk", -300);
pub const Grenada = create("America/Grenada", -240);
pub const Guadeloupe = create("America/Guadeloupe", -240);
pub const Guatemala = create("America/Guatemala", -360);
pub const Guayaquil = create("America/Guayaquil", -300);
pub const Guyana = create("America/Guyana", -240);
pub const Halifax = create("America/Halifax", -240);
pub const Havana = create("America/Havana", -300);
pub const Hermosillo = create("America/Hermosillo", -420);
pub const Indiana = struct {
// FIXME: Name conflict
pub const Indianapolis_ = create("America/Indiana/Indianapolis", -300);
pub const Knox = create("America/Indiana/Knox", -360);
pub const Marengo = create("America/Indiana/Marengo", -300);
pub const Petersburg = create("America/Indiana/Petersburg", -300);
pub const Tell_City = create("America/Indiana/Tell_City", -360);
pub const Vevay = create("America/Indiana/Vevay", -300);
pub const Vincennes = create("America/Indiana/Vincennes", -300);
pub const Winamac = create("America/Indiana/Winamac", -300);
};
pub const Indianapolis = create("America/Indianapolis", -300);
pub const Inuvik = create("America/Inuvik", -420);
pub const Iqaluit = create("America/Iqaluit", -300);
pub const Jamaica = create("America/Jamaica", -300);
pub const Jujuy = create("America/Jujuy", -180);
pub const Juneau = create("America/Juneau", -540);
pub const Kentucky = struct {
// FIXME: Name conflict
pub const Louisville_ = create("America/Kentucky/Louisville", -300);
pub const Monticello = create("America/Kentucky/Monticello", -300);
};
pub const Knox_IN = create("America/Knox_IN", -360);
pub const Kralendijk = create("America/Kralendijk", -240);
pub const La_Paz = create("America/La_Paz", -240);
pub const Lima = create("America/Lima", -300);
pub const Los_Angeles = create("America/Los_Angeles", -480);
pub const Louisville = create("America/Louisville", -300);
pub const Lower_Princes = create("America/Lower_Princes", -240);
pub const Maceio = create("America/Maceio", -180);
pub const Managua = create("America/Managua", -360);
pub const Manaus = create("America/Manaus", -240);
pub const Marigot = create("America/Marigot", -240);
pub const Martinique = create("America/Martinique", -240);
pub const Matamoros = create("America/Matamoros", -360);
pub const Mazatlan = create("America/Mazatlan", -420);
pub const Mendoza = create("America/Mendoza", -180);
pub const Menominee = create("America/Menominee", -360);
pub const Merida = create("America/Merida", -360);
pub const Metlakatla = create("America/Metlakatla", -540);
pub const Mexico_City = create("America/Mexico_City", -360);
pub const Miquelon = create("America/Miquelon", -180);
pub const Moncton = create("America/Moncton", -240);
pub const Monterrey = create("America/Monterrey", -360);
pub const Montevideo = create("America/Montevideo", -180);
pub const Montreal = create("America/Montreal", -300);
pub const Montserrat = create("America/Montserrat", -240);
pub const Nassau = create("America/Nassau", -300);
pub const New_York = create("America/New_York", -300);
pub const Nipigon = create("America/Nipigon", -300);
pub const Nome = create("America/Nome", -540);
pub const Noronha = create("America/Noronha", -120);
pub const North_Dakota = struct {
pub const Beulah = create("America/North_Dakota/Beulah", -360);
pub const Center = create("America/North_Dakota/Center", -360);
pub const New_Salem = create("America/North_Dakota/New_Salem", -360);
};
pub const Ojinaga = create("America/Ojinaga", -420);
pub const Panama = create("America/Panama", -300);
pub const Pangnirtung = create("America/Pangnirtung", -300);
pub const Paramaribo = create("America/Paramaribo", -180);
pub const Phoenix = create("America/Phoenix", -420);
pub const Port_of_Spain = create("America/Port_of_Spain", -240);
pub const Port_au_Prince = create("America/Port-au-Prince", -300);
pub const Porto_Acre = create("America/Porto_Acre", -300);
pub const Porto_Velho = create("America/Porto_Velho", -240);
pub const Puerto_Rico = create("America/Puerto_Rico", -240);
pub const Punta_Arenas = create("America/Punta_Arenas", -180);
pub const Rainy_River = create("America/Rainy_River", -360);
pub const Rankin_Inlet = create("America/Rankin_Inlet", -360);
pub const Recife = create("America/Recife", -180);
pub const Regina = create("America/Regina", -360);
pub const Resolute = create("America/Resolute", -360);
pub const Rio_Branco = create("America/Rio_Branco", -300);
pub const Rosario = create("America/Rosario", -180);
pub const Santa_Isabel = create("America/Santa_Isabel", -480);
pub const Santarem = create("America/Santarem", -180);
pub const Santiago = create("America/Santiago", -240);
pub const Santo_Domingo = create("America/Santo_Domingo", -240);
pub const Sao_Paulo = create("America/Sao_Paulo", -180);
pub const Scoresbysund = create("America/Scoresbysund", -60);
pub const Shiprock = create("America/Shiprock", -420);
pub const Sitka = create("America/Sitka", -540);
pub const St_Barthelemy = create("America/St_Barthelemy", -240);
pub const St_Johns = create("America/St_Johns", -210);
pub const St_Kitts = create("America/St_Kitts", -240);
pub const St_Lucia = create("America/St_Lucia", -240);
pub const St_Thomas = create("America/St_Thomas", -240);
pub const St_Vincent = create("America/St_Vincent", -240);
pub const Swift_Current = create("America/Swift_Current", -360);
pub const Tegucigalpa = create("America/Tegucigalpa", -360);
pub const Thule = create("America/Thule", -240);
pub const Thunder_Bay = create("America/Thunder_Bay", -300);
pub const Tijuana = create("America/Tijuana", -480);
pub const Toronto = create("America/Toronto", -300);
pub const Tortola = create("America/Tortola", -240);
pub const Vancouver = create("America/Vancouver", -480);
pub const Virgin = create("America/Virgin", -240);
pub const Whitehorse = create("America/Whitehorse", -480);
pub const Winnipeg = create("America/Winnipeg", -360);
pub const Yakutat = create("America/Yakutat", -540);
pub const Yellowknife = create("America/Yellowknife", -420);
};
pub const Antarctica = struct {
pub const Casey = create("Antarctica/Casey", 660);
pub const Davis = create("Antarctica/Davis", 420);
pub const DumontDUrville = create("Antarctica/DumontDUrville", 600);
pub const Macquarie = create("Antarctica/Macquarie", 660);
pub const Mawson = create("Antarctica/Mawson", 300);
pub const McMurdo = create("Antarctica/McMurdo", 720);
pub const Palmer = create("Antarctica/Palmer", -180);
pub const Rothera = create("Antarctica/Rothera", -180);
pub const South_Pole = create("Antarctica/South_Pole", 720);
pub const Syowa = create("Antarctica/Syowa", 180);
pub const Troll = create("Antarctica/Troll", 0);
pub const Vostok = create("Antarctica/Vostok", 360);
};
pub const Arctic = struct {
pub const Longyearbyen = create("Arctic/Longyearbyen", 60);
};
pub const Asia = struct {
pub const Aden = create("Asia/Aden", 180);
pub const Almaty = create("Asia/Almaty", 360);
pub const Amman = create("Asia/Amman", 120);
pub const Anadyr = create("Asia/Anadyr", 720);
pub const Aqtau = create("Asia/Aqtau", 300);
pub const Aqtobe = create("Asia/Aqtobe", 300);
pub const Ashgabat = create("Asia/Ashgabat", 300);
pub const Ashkhabad = create("Asia/Ashkhabad", 300);
pub const Atyrau = create("Asia/Atyrau", 300);
pub const Baghdad = create("Asia/Baghdad", 180);
pub const Bahrain = create("Asia/Bahrain", 180);
pub const Baku = create("Asia/Baku", 240);
pub const Bangkok = create("Asia/Bangkok", 420);
pub const Barnaul = create("Asia/Barnaul", 420);
pub const Beirut = create("Asia/Beirut", 120);
pub const Bishkek = create("Asia/Bishkek", 360);
pub const Brunei = create("Asia/Brunei", 480);
pub const Calcutta = create("Asia/Calcutta", 330);
pub const Chita = create("Asia/Chita", 540);
pub const Choibalsan = create("Asia/Choibalsan", 480);
pub const Chongqing = create("Asia/Chongqing", 480);
pub const Chungking = create("Asia/Chungking", 480);
pub const Colombo = create("Asia/Colombo", 330);
pub const Dacca = create("Asia/Dacca", 360);
pub const Damascus = create("Asia/Damascus", 120);
pub const Dhaka = create("Asia/Dhaka", 360);
pub const Dili = create("Asia/Dili", 540);
pub const Dubai = create("Asia/Dubai", 240);
pub const Dushanbe = create("Asia/Dushanbe", 300);
pub const Famagusta = create("Asia/Famagusta", 120);
pub const Gaza = create("Asia/Gaza", 120);
pub const Harbin = create("Asia/Harbin", 480);
pub const Hebron = create("Asia/Hebron", 120);
pub const Ho_Chi_Minh = create("Asia/Ho_Chi_Minh", 420);
pub const Hong_Kong = create("Asia/Hong_Kong", 480);
pub const Hovd = create("Asia/Hovd", 420);
pub const Irkutsk = create("Asia/Irkutsk", 480);
pub const Istanbul = create("Asia/Istanbul", 180);
pub const Jakarta = create("Asia/Jakarta", 420);
pub const Jayapura = create("Asia/Jayapura", 540);
pub const Jerusalem = create("Asia/Jerusalem", 120);
pub const Kabul = create("Asia/Kabul", 270);
pub const Kamchatka = create("Asia/Kamchatka", 720);
pub const Karachi = create("Asia/Karachi", 300);
pub const Kashgar = create("Asia/Kashgar", 360);
pub const Kathmandu = create("Asia/Kathmandu", 345);
pub const Katmandu = create("Asia/Katmandu", 345);
pub const Khandyga = create("Asia/Khandyga", 540);
pub const Kolkata = create("Asia/Kolkata", 330);
pub const Krasnoyarsk = create("Asia/Krasnoyarsk", 420);
pub const Kuala_Lumpur = create("Asia/Kuala_Lumpur", 480);
pub const Kuching = create("Asia/Kuching", 480);
pub const Kuwait = create("Asia/Kuwait", 180);
pub const Macao = create("Asia/Macao", 480);
pub const Macau = create("Asia/Macau", 480);
pub const Magadan = create("Asia/Magadan", 660);
pub const Makassar = create("Asia/Makassar", 480);
pub const Manila = create("Asia/Manila", 480);
pub const Muscat = create("Asia/Muscat", 240);
pub const Nicosia = create("Asia/Nicosia", 120);
pub const Novokuznetsk = create("Asia/Novokuznetsk", 420);
pub const Novosibirsk = create("Asia/Novosibirsk", 420);
pub const Omsk = create("Asia/Omsk", 360);
pub const Oral = create("Asia/Oral", 300);
pub const Phnom_Penh = create("Asia/Phnom_Penh", 420);
pub const Pontianak = create("Asia/Pontianak", 420);
pub const Pyongyang = create("Asia/Pyongyang", 540);
pub const Qatar = create("Asia/Qatar", 180);
pub const Qyzylorda = create("Asia/Qyzylorda", 300);
pub const Rangoon = create("Asia/Rangoon", 390);
pub const Riyadh = create("Asia/Riyadh", 180);
pub const Saigon = create("Asia/Saigon", 420);
pub const Sakhalin = create("Asia/Sakhalin", 660);
pub const Samarkand = create("Asia/Samarkand", 300);
pub const Seoul = create("Asia/Seoul", 540);
pub const Shanghai = create("Asia/Shanghai", 480);
pub const Singapore = create("Asia/Singapore", 480);
pub const Srednekolymsk = create("Asia/Srednekolymsk", 660);
pub const Taipei = create("Asia/Taipei", 480);
pub const Tashkent = create("Asia/Tashkent", 300);
pub const Tbilisi = create("Asia/Tbilisi", 240);
pub const Tehran = create("Asia/Tehran", 210);
pub const Tel_Aviv = create("Asia/Tel_Aviv", 120);
pub const Thimbu = create("Asia/Thimbu", 360);
pub const Thimphu = create("Asia/Thimphu", 360);
pub const Tokyo = create("Asia/Tokyo", 540);
pub const Tomsk = create("Asia/Tomsk", 420);
pub const Ujung_Pandang = create("Asia/Ujung_Pandang", 480);
pub const Ulaanbaatar = create("Asia/Ulaanbaatar", 480);
pub const Ulan_Bator = create("Asia/Ulan_Bator", 480);
pub const Urumqi = create("Asia/Urumqi", 360);
pub const Ust_Nera = create("Asia/Ust-Nera", 600);
pub const Vientiane = create("Asia/Vientiane", 420);
pub const Vladivostok = create("Asia/Vladivostok", 600);
pub const Yakutsk = create("Asia/Yakutsk", 540);
pub const Yangon = create("Asia/Yangon", 390);
pub const Yekaterinburg = create("Asia/Yekaterinburg", 300);
pub const Yerevan = create("Asia/Yerevan", 240);
};
pub const Atlantic = struct {
pub const Azores = create("Atlantic/Azores", -60);
pub const Bermuda = create("Atlantic/Bermuda", -240);
pub const Canary = create("Atlantic/Canary", 0);
pub const Cape_Verde = create("Atlantic/Cape_Verde", -60);
pub const Faeroe = create("Atlantic/Faeroe", 0);
pub const Faroe = create("Atlantic/Faroe", 0);
pub const Jan_Mayen = create("Atlantic/Jan_Mayen", 60);
pub const Madeira = create("Atlantic/Madeira", 0);
pub const Reykjavik = create("Atlantic/Reykjavik", 0);
pub const South_Georgia = create("Atlantic/South_Georgia", -120);
pub const St_Helena = create("Atlantic/St_Helena", 0);
pub const Stanley = create("Atlantic/Stanley", -180);
};
pub const Australia = struct {
pub const ACT = create("Australia/ACT", 600);
pub const Adelaide = create("Australia/Adelaide", 570);
pub const Brisbane = create("Australia/Brisbane", 600);
pub const Broken_Hill = create("Australia/Broken_Hill", 570);
pub const Canberra = create("Australia/Canberra", 600);
pub const Currie = create("Australia/Currie", 600);
pub const Darwin = create("Australia/Darwin", 570);
pub const Eucla = create("Australia/Eucla", 525);
pub const Hobart = create("Australia/Hobart", 600);
pub const LHI = create("Australia/LHI", 630);
pub const Lindeman = create("Australia/Lindeman", 600);
pub const Lord_Howe = create("Australia/Lord_Howe", 630);
pub const Melbourne = create("Australia/Melbourne", 600);
pub const North = create("Australia/North", 570);
pub const NSW = create("Australia/NSW", 600);
pub const Perth = create("Australia/Perth", 480);
pub const Queensland = create("Australia/Queensland", 600);
pub const South = create("Australia/South", 570);
pub const Sydney = create("Australia/Sydney", 600);
pub const Tasmania = create("Australia/Tasmania", 600);
pub const Victoria = create("Australia/Victoria", 600);
pub const West = create("Australia/West", 480);
pub const Yancowinna = create("Australia/Yancowinna", 570);
};
pub const Brazil = struct {
pub const Acre = create("Brazil/Acre", -300);
pub const DeNoronha = create("Brazil/DeNoronha", -120);
pub const East = create("Brazil/East", -180);
pub const West = create("Brazil/West", -240);
};
pub const Canada = struct {
pub const Atlantic = create("Canada/Atlantic", -240);
pub const Central = create("Canada/Central", -360);
pub const Eastern = create("Canada/Eastern", -300);
pub const Mountain = create("Canada/Mountain", -420);
pub const Newfoundland = create("Canada/Newfoundland", -210);
pub const Pacific = create("Canada/Pacific", -480);
pub const Saskatchewan = create("Canada/Saskatchewan", -360);
pub const Yukon = create("Canada/Yukon", -480);
};
pub const CET = create("CET", 60);
pub const Chile = struct {
pub const Continental = create("Chile/Continental", -240);
pub const EasterIsland = create("Chile/EasterIsland", -360);
};
pub const CST6CDT = create("CST6CDT", -360);
pub const Cuba = create("Cuba", -300);
pub const EET = create("EET", 120);
pub const Egypt = create("Egypt", 120);
pub const Eire = create("Eire", 0);
pub const EST = create("EST", -300);
pub const EST5EDT = create("EST5EDT", -300);
pub const Etc = struct {
// NOTE: The signs are intentionally inverted. See the Etc area description.
pub const GMT = create("Etc/GMT", 0);
pub const GMTp0 = create("Etc/GMT+0", 0);
pub const GMTp1 = create("Etc/GMT+1", -60);
pub const GMTp10 = create("Etc/GMT+10", -600);
pub const GMTp11 = create("Etc/GMT+11", -660);
pub const GMTp12 = create("Etc/GMT+12", -720);
pub const GMTp2 = create("Etc/GMT+2", -120);
pub const GMTp3 = create("Etc/GMT+3", -180);
pub const GMTp4 = create("Etc/GMT+4", -240);
pub const GMTp5 = create("Etc/GMT+5", -300);
pub const GMTp6 = create("Etc/GMT+6", -360);
pub const GMTp7 = create("Etc/GMT+7", -420);
pub const GMTp8 = create("Etc/GMT+8", -480);
pub const GMTp9 = create("Etc/GMT+9", -540);
pub const GMT0 = create("Etc/GMT0", 0);
pub const GMTm0 = create("Etc/GMT-0", 0);
pub const GMTm1 = create("Etc/GMT-1", 60);
pub const GMTm10 = create("Etc/GMT-10", 600);
pub const GMTm11 = create("Etc/GMT-11", 660);
pub const GMTm12 = create("Etc/GMT-12", 720);
pub const GMTm13 = create("Etc/GMT-13", 780);
pub const GMTm14 = create("Etc/GMT-14", 840);
pub const GMTm2 = create("Etc/GMT-2", 120);
pub const GMTm3 = create("Etc/GMT-3", 180);
pub const GMTm4 = create("Etc/GMT-4", 240);
pub const GMTm5 = create("Etc/GMT-5", 300);
pub const GMTm6 = create("Etc/GMT-6", 360);
pub const GMTm7 = create("Etc/GMT-7", 420);
pub const GMTm8 = create("Etc/GMT-8", 480);
pub const GMTm9 = create("Etc/GMT-9", 540);
pub const Greenwich = create("Etc/Greenwich", 0);
pub const UCT = create("Etc/UCT", 0);
pub const Universal = create("Etc/Universal", 0);
pub const UTC = create("Etc/UTC", 0);
pub const Zulu = create("Etc/Zulu", 0);
};
pub const Europe = struct {
pub const Amsterdam = create("Europe/Amsterdam", 60);
pub const Andorra = create("Europe/Andorra", 60);
pub const Astrakhan = create("Europe/Astrakhan", 240);
pub const Athens = create("Europe/Athens", 120);
pub const Belfast = create("Europe/Belfast", 0);
pub const Belgrade = create("Europe/Belgrade", 60);
pub const Berlin = create("Europe/Berlin", 60);
pub const Bratislava = create("Europe/Bratislava", 60);
pub const Brussels = create("Europe/Brussels", 60);
pub const Bucharest = create("Europe/Bucharest", 120);
pub const Budapest = create("Europe/Budapest", 60);
pub const Busingen = create("Europe/Busingen", 60);
pub const Chisinau = create("Europe/Chisinau", 120);
pub const Copenhagen = create("Europe/Copenhagen", 60);
pub const Dublin = create("Europe/Dublin", 0);
pub const Gibraltar = create("Europe/Gibraltar", 60);
pub const Guernsey = create("Europe/Guernsey", 0);
pub const Helsinki = create("Europe/Helsinki", 120);
pub const Isle_of_Man = create("Europe/Isle_of_Man", 0);
pub const Istanbul = create("Europe/Istanbul", 180);
pub const Jersey = create("Europe/Jersey", 0);
pub const Kaliningrad = create("Europe/Kaliningrad", 120);
pub const Kiev = create("Europe/Kiev", 120);
pub const Kirov = create("Europe/Kirov", 180);
pub const Lisbon = create("Europe/Lisbon", 0);
pub const Ljubljana = create("Europe/Ljubljana", 60);
pub const London = create("Europe/London", 0);
pub const Luxembourg = create("Europe/Luxembourg", 60);
pub const Madrid = create("Europe/Madrid", 60);
pub const Malta = create("Europe/Malta", 60);
pub const Mariehamn = create("Europe/Mariehamn", 120);
pub const Minsk = create("Europe/Minsk", 180);
pub const Monaco = create("Europe/Monaco", 60);
pub const Moscow = create("Europe/Moscow", 180);
pub const Oslo = create("Europe/Oslo", 60);
pub const Paris = create("Europe/Paris", 60);
pub const Podgorica = create("Europe/Podgorica", 60);
pub const Prague = create("Europe/Prague", 60);
pub const Riga = create("Europe/Riga", 120);
pub const Rome = create("Europe/Rome", 60);
pub const Samara = create("Europe/Samara", 240);
pub const San_Marino = create("Europe/San_Marino", 60);
pub const Sarajevo = create("Europe/Sarajevo", 60);
pub const Saratov = create("Europe/Saratov", 240);
pub const Simferopol = create("Europe/Simferopol", 180);
pub const Skopje = create("Europe/Skopje", 60);
pub const Sofia = create("Europe/Sofia", 120);
pub const Stockholm = create("Europe/Stockholm", 60);
pub const Tallinn = create("Europe/Tallinn", 120);
pub const Tirane = create("Europe/Tirane", 60);
pub const Tiraspol = create("Europe/Tiraspol", 120);
pub const Ulyanovsk = create("Europe/Ulyanovsk", 240);
pub const Uzhgorod = create("Europe/Uzhgorod", 120);
pub const Vaduz = create("Europe/Vaduz", 60);
pub const Vatican = create("Europe/Vatican", 60);
pub const Vienna = create("Europe/Vienna", 60);
pub const Vilnius = create("Europe/Vilnius", 120);
pub const Volgograd = create("Europe/Volgograd", 240);
pub const Warsaw = create("Europe/Warsaw", 60);
pub const Zagreb = create("Europe/Zagreb", 60);
pub const Zaporozhye = create("Europe/Zaporozhye", 120);
pub const Zurich = create("Europe/Zurich", 60);
};
pub const GB = create("GB", 0);
pub const GB_Eire = create("GB-Eire", 0);
pub const GMT = create("GMT", 0);
pub const GMTp0 = create("GMT+0", 0);
pub const GMT0 = create("GMT0", 0);
pub const GMTm0 = create("GMT-0", 0);
pub const Greenwich = create("Greenwich", 0);
pub const Hongkong = create("Hongkong", 480);
pub const HST = create("HST", -600);
pub const Iceland = create("Iceland", 0);
pub const Indian = struct {
pub const Antananarivo = create("Indian/Antananarivo", 180);
pub const Chagos = create("Indian/Chagos", 360);
pub const Christmas = create("Indian/Christmas", 420);
pub const Cocos = create("Indian/Cocos", 390);
pub const Comoro = create("Indian/Comoro", 180);
pub const Kerguelen = create("Indian/Kerguelen", 300);
pub const Mahe = create("Indian/Mahe", 240);
pub const Maldives = create("Indian/Maldives", 300);
pub const Mauritius = create("Indian/Mauritius", 240);
pub const Mayotte = create("Indian/Mayotte", 180);
pub const Reunion = create("Indian/Reunion", 240);
};
pub const Iran = create("Iran", 210);
pub const Israel = create("Israel", 120);
pub const Jamaica = create("Jamaica", -300);
pub const Japan = create("Japan", 540);
pub const Kwajalein = create("Kwajalein", 720);
pub const Libya = create("Libya", 120);
pub const MET = create("MET", 60);
pub const Mexico = struct {
pub const BajaNorte = create("Mexico/BajaNorte", -480);
pub const BajaSur = create("Mexico/BajaSur", -420);
pub const General = create("Mexico/General", -360);
};
pub const MST = create("MST", -420);
pub const MST7MDT = create("MST7MDT", -420);
pub const Navajo = create("Navajo", -420);
pub const NZ = create("NZ", 720);
pub const NZ_CHAT = create("NZ-CHAT", 765);
pub const Pacific = struct {
pub const Apia = create("Pacific/Apia", 780);
pub const Auckland = create("Pacific/Auckland", 720);
pub const Bougainville = create("Pacific/Bougainville", 660);
pub const Chatham = create("Pacific/Chatham", 765);
pub const Chuuk = create("Pacific/Chuuk", 600);
pub const Easter = create("Pacific/Easter", -360);
pub const Efate = create("Pacific/Efate", 660);
pub const Enderbury = create("Pacific/Enderbury", 780);
pub const Fakaofo = create("Pacific/Fakaofo", 780);
pub const Fiji = create("Pacific/Fiji", 720);
pub const Funafuti = create("Pacific/Funafuti", 720);
pub const Galapagos = create("Pacific/Galapagos", -360);
pub const Gambier = create("Pacific/Gambier", -540);
pub const Guadalcanal = create("Pacific/Guadalcanal", 660);
pub const Guam = create("Pacific/Guam", 600);
pub const Honolulu = create("Pacific/Honolulu", -600);
pub const Johnston = create("Pacific/Johnston", -600);
pub const Kiritimati = create("Pacific/Kiritimati", 840);
pub const Kosrae = create("Pacific/Kosrae", 660);
pub const Kwajalein = create("Pacific/Kwajalein", 720);
pub const Majuro = create("Pacific/Majuro", 720);
pub const Marquesas = create("Pacific/Marquesas", -570);
pub const Midway = create("Pacific/Midway", -660);
pub const Nauru = create("Pacific/Nauru", 720);
pub const Niue = create("Pacific/Niue", -660);
pub const Norfolk = create("Pacific/Norfolk", 660);
pub const Noumea = create("Pacific/Noumea", 660);
pub const Pago_Pago = create("Pacific/Pago_Pago", -660);
pub const Palau = create("Pacific/Palau", 540);
pub const Pitcairn = create("Pacific/Pitcairn", -480);
pub const Pohnpei = create("Pacific/Pohnpei", 660);
pub const Ponape = create("Pacific/Ponape", 660);
pub const Port_Moresby = create("Pacific/Port_Moresby", 600);
pub const Rarotonga = create("Pacific/Rarotonga", -600);
pub const Saipan = create("Pacific/Saipan", 600);
pub const Samoa = create("Pacific/Samoa", -660);
pub const Tahiti = create("Pacific/Tahiti", -600);
pub const Tarawa = create("Pacific/Tarawa", 720);
pub const Tongatapu = create("Pacific/Tongatapu", 780);
pub const Truk = create("Pacific/Truk", 600);
pub const Wake = create("Pacific/Wake", 720);
pub const Wallis = create("Pacific/Wallis", 720);
pub const Yap = create("Pacific/Yap", 600);
};
pub const Poland = create("Poland", 60);
pub const Portugal = create("Portugal", 0);
pub const PRC = create("PRC", 480);
pub const PST8PDT = create("PST8PDT", -480);
pub const ROC = create("ROC", 480);
pub const ROK = create("ROK", 540);
pub const Singapore = create("Singapore", 480);
pub const Turkey = create("Turkey", 180);
pub const UCT = create("UCT", 0);
pub const Universal = create("Universal", 0);
pub const US = struct {
pub const Alaska = create("US/Alaska", -540);
pub const Aleutian = create("US/Aleutian", -600);
pub const Arizona = create("US/Arizona", -420);
pub const Central = create("US/Central", -360);
pub const Eastern = create("US/Eastern", -300);
pub const East_Indiana = create("US/East-Indiana", -300);
pub const Hawaii = create("US/Hawaii", -600);
pub const Indiana_Starke = create("US/Indiana-Starke", -360);
pub const Michigan = create("US/Michigan", -300);
pub const Mountain = create("US/Mountain", -420);
pub const Pacific = create("US/Pacific", -480);
pub const Pacific_New = create("US/Pacific-New", -480);
pub const Samoa = create("US/Samoa", -660);
};
pub const UTC = create("UTC", 0);
pub const WET = create("WET", 0);
pub const W_SU = create("W-SU", 180);
pub const Zulu = create("Zulu", 0);
// TODO: Allow lookup by name
//pub fn getAll() []*const Timezone {
// for (comptime std.meta.fields(@This())) |field {
//
// }
//}
//pub fn get(name: []const u8) ?*const Timezone {
// return ALL_TIMEZONES.getValue(name);
//}
test "timezone-get" {
const testing = std.testing;
//testing.expect(get("America/New_York").? == America.New_York);
testing.expect(America.New_York.offset == -300);
} | src/time/timezones.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const GPA = std.heap.GeneralPurposeAllocator;
const Error = std.mem.Allocator.Error;
// set io_mode
pub const io_mode = .evented;
/// Buff struct
/// size the size of the buffer
/// addr the address of the undelying memory block
/// offset the first unused place in the buffer 0xffff means the buff is full
/// allocator the address of the us allocator
const Buff = struct {
size: u32,
addr: []u8,
offset: u32,
allocator: *Allocator,
};
/// init a buffer of the deisred size
fn init(size: u32, a: *Allocator) Error!*Buff {
var ptr = try a.alloc(u8, size);
return &Buff{
.size = size,
.addr = ptr,
.offset = 0,
.allocator = a,
};
}
/// close the given buffer and free it's memory
fn close(b: *Buff) void {
b.allocator.free(b.addr);
}
/// write c into our buffer
fn write(b: *Buff, c: u8) !void {
// todo add fail if more than size
b.addr[b.offset] = c;
b.*.offset += 1;
}
/// read c into our buffer
fn read(b: *Buff) !u8 {
b.offset -= 1;
// todo add fail if 0
const c: u8 = b.addr[b.offset];
return c;
}
pub fn main() !void {
var gpa = GPA(.{}){};
var alloc = &gpa.allocator;
var buff = try init(3, alloc);
defer close(buff);
std.debug.print("writing 'a' to buff\n", .{});
try write(buff, 'a');
std.debug.print("reading one char from buff\n", .{});
const c = read(buff);
std.debug.print("char is : {c}\n", .{c});
std.debug.print("writing 'a' then 'b' to buff\n", .{});
// get frames without blocking
var w1 = async write(buff, 'a');
var w2 = async write(buff, 'b');
// wait for frames
try await w1;
try await w2;
std.debug.print("reading two char from buff\n", .{});
// get frames
var r1 = async read(buff);
var r2 = async read(buff);
// read async
const d = try await r1;
const e = try await r2;
std.debug.print("chars are : {c} {c}\n", .{d, e});
} | async_buff.zig |
const std = @import("std");
const assert = std.debug.assert;
const tools = @import("tools");
pub fn run(input_text: []const u8, allocator: std.mem.Allocator) ![2][]const u8 {
const ans1 = ans: {
var mem = try allocator.alloc(u36, 100000);
defer allocator.free(mem);
std.mem.set(u36, mem, 0);
var mask_or: u36 = 0;
var mask_and: u36 = 0xFFFFFFFFF;
var it = std.mem.tokenize(u8, input_text, "\n\r");
while (it.next()) |line| {
if (tools.match_pattern("mask = {}", line)) |fields| {
const pattern = fields[0].lit;
mask_or = 0;
mask_and = 0xFFFFFFFFF;
for (pattern) |bit, i| {
const mask = @as(u36, 1) << @intCast(u6, 35 - i);
switch (bit) {
'X' => {},
'1' => mask_or |= mask,
'0' => mask_and &= ~mask,
else => unreachable,
}
}
} else if (tools.match_pattern("mem[{}] = {}", line)) |fields| {
const adr = @intCast(usize, fields[0].imm);
const val = @intCast(u36, fields[1].imm);
mem[adr] = (val | mask_or) & mask_and;
} else {
unreachable;
}
}
var sum: u64 = 0;
for (mem) |v| {
sum += v;
}
break :ans sum;
};
const ans2 = ans: {
var mem = std.AutoArrayHashMap(u36, u36).init(allocator);
defer mem.deinit();
var mask_or: u36 = 0;
var mask_and: u36 = 0xFFFFFFFFF;
var mask_muts: [36]u36 = undefined;
var mask_nb_mut: u6 = 0;
var it = std.mem.tokenize(u8, input_text, "\n\r");
while (it.next()) |line| {
if (tools.match_pattern("mask = {}", line)) |fields| {
const pattern = fields[0].lit;
mask_or = 0;
mask_and = 0xFFFFFFFFF;
mask_nb_mut = 0;
for (pattern) |bit, i| {
const mask = @as(u36, 1) << @intCast(u6, 35 - i);
switch (bit) {
'X' => {
mask_and &= ~mask;
mask_muts[mask_nb_mut] = mask;
mask_nb_mut += 1;
},
'1' => mask_or |= mask,
'0' => {},
else => unreachable,
}
}
} else if (tools.match_pattern("mem[{}] = {}", line)) |fields| {
const adr = @intCast(u36, fields[0].imm);
const val = @intCast(u36, fields[1].imm);
const base = (adr | mask_or) & mask_and;
var i: u36 = 0;
while (i < (@as(u36, 1) << (mask_nb_mut + 1))) : (i += 1) {
var a: u36 = base;
for (mask_muts[0..mask_nb_mut]) |mask, j| {
const use = ((i & (@as(u32, 1) << @intCast(u5, j))) != 0);
if (use) a |= mask;
}
try mem.put(a, val);
}
} else {
unreachable;
}
}
{
var sum: u64 = 0;
var it2 = mem.iterator();
while (it2.next()) |v| {
sum += v.value_ptr.*;
}
break :ans sum;
}
};
return [_][]const u8{
try std.fmt.allocPrint(allocator, "{}", .{ans1}),
try std.fmt.allocPrint(allocator, "{}", .{ans2}),
};
}
pub const main = tools.defaultMain("2020/input_day14.txt", run); | 2020/day14.zig |
const std = @import("std");
const testing = std.testing;
const seperatorBonus = 5;
const adjacentCaseEqualBonus: i32 = 3;
const unmatchedLetterPenalty = -1;
const adjecencyBonus = 5;
const adjecencyIncrease = 1.2;
const caseEqualBonus: i32 = 7;
const firstLetterBonus = 12;
const leadingLetterPenalty = -3;
const maxLeadingLetterPolicy = -9;
pub fn match(pattern: []const u8, input: []const u8) bool {
if (pattern.len > input.len) return false;
var currentIndex: usize = 0;
for (pattern) |each| {
if (indexOf(input, currentIndex, each)) |pIndex| {
currentIndex = pIndex + 1;
} else return false;
}
return true;
}
pub fn scoredMatch(pattern: []const u8, input: []const u8) ?i32 {
if (pattern.len > input.len) return null;
if (pattern.len == 0) return 0;
var ramp: f32 = 1;
var rampSum: f32 = 0.0;
var score: i32 = 0;
var inputIndex: usize = 0;
for (pattern) |patternChar, patternIndex| {
if (indexOf(input, inputIndex, patternChar)) |position| {
score += if (patternChar == input[position]) caseEqualBonus else 0;
if (patternIndex == 0) {
score += firstMatchScore(position);
} else {
var prev = input[position - 1];
if (isSeparator(prev)) {
score += seperatorBonus;
}
if (inputIndex + 1 == position) {
ramp += (ramp * adjecencyIncrease);
rampSum += ramp - 1;
score += adjecencyBonus;
score += if (pattern[patternIndex - 1] == prev) adjacentCaseEqualBonus else 0;
} else {
ramp = 1;
}
}
inputIndex = position + 1;
} else return null;
}
score += ((@intCast(i32, (input.len - pattern.len)) * unmatchedLetterPenalty));
return score;
}
fn indexOf(haystack: []const u8, start_index: usize, needle: u8) ?usize {
const ascii = std.ascii;
const lowercaseNeedle = ascii.toLower(needle);
var i: usize = start_index;
const end = haystack.len - 1;
while (i <= end) : (i += 1) {
if (ascii.toLower(haystack[i]) == lowercaseNeedle) return i;
}
return null;
}
fn firstMatchScore(position: usize) i32 {
if (position == 0) return firstLetterBonus;
return std.math.max(@intCast(i32, position) * leadingLetterPenalty, maxLeadingLetterPolicy);
}
inline fn isSeparator(char: u8) bool {
return char == '_' or char == ':';
}
test "test fuzzy match" {
try testing.expect(match("a", "bba"));
try testing.expect(!match("a", "bb"));
try testing.expect(!match("b", "aa"));
try testing.expect(match("b", "aab"));
try testing.expect(match("b", "aa:__x_b"));
try testing.expect(match("b", "aa:__x_b"));
try testing.expect(!match("aba", "aa:__x_b"));
try testing.expect(match("aba", "aa:__x_ba"));
}
test "scoredMatch" {
try testing.expectEqual(scoredMatch("a", "b"), null);
try testing.expectEqual(scoredMatch("a", ""), null);
try testing.expectEqual(scoredMatch("", "b"), 0);
try testing.expectEqual(scoredMatch("a", "a").?, firstLetterBonus + caseEqualBonus);
try testing.expectEqual(scoredMatch("a", "a").?, firstLetterBonus + caseEqualBonus);
try testing.expectEqual(scoredMatch("a", "A").?, firstLetterBonus);
try testing.expectEqual(scoredMatch("a", "ab").?, firstLetterBonus + caseEqualBonus + unmatchedLetterPenalty);
try testing.expectEqual(scoredMatch("a", "1a").?, leadingLetterPenalty + unmatchedLetterPenalty + caseEqualBonus);
try testing.expectEqual(scoredMatch("a", "12345a").?, maxLeadingLetterPolicy + (5 * unmatchedLetterPenalty) + caseEqualBonus);
} | src/main.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 png = zigimg.png;
const std = @import("std");
const testing = std.testing;
const zigimg = @import("zigimg");
usingnamespace @import("../helpers.zig");
test "Should error on non PNG images" {
const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/bmp/simple_v4.bmp");
defer file.close();
var stream_source = std.io.StreamSource{ .file = file };
var pngFile = png.PNG.init(zigimg_test_allocator);
defer pngFile.deinit();
var pixelsOpt: ?color.ColorStorage = null;
const invalidFile = pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt);
defer {
if (pixelsOpt) |pixels| {
pixels.deinit(zigimg_test_allocator);
}
}
expectError(invalidFile, errors.ImageError.InvalidMagicHeader);
}
test "Read PNG header properly" {
const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/basn0g01.png");
defer file.close();
var stream_source = std.io.StreamSource{ .file = file };
var pngFile = png.PNG.init(zigimg_test_allocator);
defer pngFile.deinit();
var pixelsOpt: ?color.ColorStorage = null;
try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt);
defer {
if (pixelsOpt) |pixels| {
pixels.deinit(zigimg_test_allocator);
}
}
expectEq(pngFile.header.width, 32);
expectEq(pngFile.header.height, 32);
expectEq(pngFile.header.bit_depth, 1);
testing.expect(pngFile.header.color_type == .Grayscale);
expectEq(pngFile.header.compression_method, 0);
expectEq(pngFile.header.filter_method, 0);
testing.expect(pngFile.header.interlace_method == .Standard);
testing.expect(pngFile.pixel_format == .Grayscale1);
testing.expect(pixelsOpt != null);
if (pixelsOpt) |pixels| {
testing.expect(pixels == .Grayscale1);
}
}
test "Read gAMA chunk properly" {
const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/basn0g01.png");
defer file.close();
var stream_source = std.io.StreamSource{ .file = file };
var pngFile = png.PNG.init(zigimg_test_allocator);
defer pngFile.deinit();
var pixelsOpt: ?color.ColorStorage = null;
try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt);
defer {
if (pixelsOpt) |pixels| {
pixels.deinit(zigimg_test_allocator);
}
}
const gammaChunkOpt = pngFile.findFirstChunk("gAMA");
testing.expect(gammaChunkOpt != null);
if (gammaChunkOpt) |gammaChunk| {
expectEq(gammaChunk.gAMA.toGammaExponent(), 1.0);
}
}
test "Png Suite" {
_ = @import("png_basn_test.zig");
_ = @import("png_basi_test.zig");
_ = @import("png_odd_sizes_test.zig");
}
test "Misc tests" {
_ = @import("png_misc_test.zig");
} | tests/formats/png_test.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const testing = std.testing;
const input_file = "input08.txt";
const Op = enum(u8) {
/// No Operation
nop,
/// Add signed 16-bit immediate to accumulator
acc16,
/// Jump by signed 16-bit immediate
jmp16,
_,
pub fn len(self: Op) usize {
return switch (self) {
.nop => 1,
.acc16, .jmp16 => 3,
else => unreachable,
};
}
};
const CompileOptions = struct {
ignore_jump_out_of_bounds: bool = false,
};
fn compile(allocator: *Allocator, reader: anytype, comptime opt: CompileOptions) ![]u8 {
var result = std.ArrayList(u8).init(allocator);
errdefer result.deinit();
var instruction_addr = std.AutoHashMap(usize, usize).init(allocator);
defer instruction_addr.deinit();
// First pass: assembly
var instruction_counter: usize = 0;
var buf: [1024]u8 = undefined;
while (try reader.readUntilDelimiterOrEof(&buf, '\n')) |line| {
var iter = std.mem.tokenize(line, " ");
const op = iter.next() orelse return error.InvalidSyntax;
try instruction_addr.put(instruction_counter, result.items.len);
if (std.mem.eql(u8, "nop", op)) {
try result.append(@enumToInt(Op.nop));
} else if (std.mem.eql(u8, "acc", op)) {
const arg = iter.next() orelse return error.ExpectedParameter;
const imm = std.fmt.parseInt(i16, arg, 10) catch return error.InvalidIntegerLiteral;
try result.append(@enumToInt(Op.acc16));
std.mem.writeIntLittle(i16, try result.addManyAsArray(2), imm);
} else if (std.mem.eql(u8, "jmp", op)) {
const arg = iter.next() orelse return error.ExpectedParameter;
const imm = std.fmt.parseInt(i16, arg, 10) catch return error.InvalidIntegerLiteral;
try result.append(@enumToInt(Op.jmp16));
std.mem.writeIntLittle(i16, try result.addManyAsArray(2), imm);
} else return error.InvalidOp;
instruction_counter += 1;
}
// Second pass: adjust jumps
var i: usize = 0;
instruction_counter = 0;
while (i < result.items.len) {
const op = @intToEnum(Op, result.items[i]);
switch (op) {
.jmp16 => {
const offset = std.mem.readIntLittle(i16, result.items[i + 1 ..][0..2]);
const location = @intCast(usize, @intCast(i16, instruction_counter) + offset);
const code_location = instruction_addr.get(location) orelse if (opt.ignore_jump_out_of_bounds) 0 else return error.JumpOutOfBounds;
const code_offset = @intCast(i16, code_location) - @intCast(i16, i);
std.mem.writeIntLittle(i16, result.items[i + 1 ..][0..2], code_offset);
},
else => {},
}
i += op.len();
instruction_counter += 1;
}
return result.toOwnedSlice();
}
test "bytecode compiler" {
const allocator = std.testing.allocator;
const assembly =
\\nop +0
\\acc +1
\\jmp +1
\\nop
\\
;
var fbs = std.io.fixedBufferStream(assembly);
const reader = fbs.reader();
const bytecode = try compile(allocator, reader, .{});
defer allocator.free(bytecode);
try testing.expectEqualSlices(u8, &[_]u8{
0, // nop
1, 1, 0, // acc +1
2, 3, 0, // jmp +1
0, // nop
}, bytecode);
}
test "bytecode compiler bounds check" {
const allocator = std.testing.allocator;
const assembly =
\\nop +0
\\acc +1
\\jmp +12
\\nop
\\
;
var fbs = std.io.fixedBufferStream(assembly);
const reader = fbs.reader();
try testing.expectError(error.JumpOutOfBounds, compile(allocator, reader, .{}));
}
const Vm = struct {
pc: usize = 0,
accumulator: i32 = 0,
bytecode: []const u8,
};
fn runUntilInfiniteLoop(allocator: *Allocator, vm: *Vm) !void {
var visited_bytecode_addrs = std.AutoHashMap(usize, void).init(allocator);
defer visited_bytecode_addrs.deinit();
while (true) {
if (visited_bytecode_addrs.get(vm.pc) != null) break;
try visited_bytecode_addrs.put(vm.pc, {});
const op = @intToEnum(Op, vm.bytecode[vm.pc]);
switch (op) {
.nop => {},
.acc16 => {
const imm = std.mem.readIntLittle(i16, vm.bytecode[vm.pc + 1 ..][0..2]);
vm.accumulator += imm;
},
.jmp16 => {
const imm = std.mem.readIntLittle(i16, vm.bytecode[vm.pc + 1 ..][0..2]);
vm.pc = @intCast(usize, @intCast(isize, vm.pc) + imm);
},
else => unreachable,
}
switch (op) {
.jmp16 => {},
else => vm.pc += op.len(),
}
}
}
test "infinite loop detector" {
const allocator = std.testing.allocator;
const assembly =
\\nop +0
\\acc +1
\\jmp +4
\\acc +3
\\jmp -3
\\acc -99
\\acc +1
\\jmp -4
\\acc +6
;
var fbs = std.io.fixedBufferStream(assembly);
const reader = fbs.reader();
const bytecode = try compile(allocator, reader, .{});
defer allocator.free(bytecode);
var vm = Vm{ .bytecode = bytecode };
try runUntilInfiniteLoop(allocator, &vm);
try testing.expectEqual(@as(i32, 5), vm.accumulator);
}
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();
const bytecode = try compile(allocator, reader, .{ .ignore_jump_out_of_bounds = true });
defer allocator.free(bytecode);
var vm = Vm{ .bytecode = bytecode };
try runUntilInfiniteLoop(allocator, &vm);
std.debug.print("accumulator value before infinite loop: {}\n", .{vm.accumulator});
} | src/08.zig |
const std = @import("std");
const bigint = std.math.big.int;
const math = std.math;
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var global_allocator = &gpa.allocator;
const Pair = struct {
p: bigint.Managed,
q: bigint.Managed,
pub fn deinit(self: *Pair) void {
defer self.p.deinit();
defer self.q.deinit();
}
};
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
const n = try get_n();
var k = binary_search(n);
var pair = try sum_terms(0, k - 1);
defer pair.deinit();
var p = pair.p.toConst();
var q = pair.q.toConst();
var answer = try bigint.Managed.init(global_allocator);
defer answer.deinit();
try bigint.Managed.add(&answer, p, q);
var a = try bigint.Managed.init(global_allocator);
defer a.deinit();
var ten = try bigint.Managed.initSet(global_allocator, 10);
defer ten.deinit();
try bigint.Managed.pow(&a, ten.toConst(), @bitCast(u32, n - 1));
var tmp = try bigint.Managed.init(global_allocator);
defer tmp.deinit();
try bigint.Managed.mul(&tmp, answer.toConst(), a.toConst());
try bigint.Managed.divFloor(&answer, &a, tmp.toConst(), q);
var str = try answer.toString(global_allocator, 10, std.fmt.Case.lower);
var i: usize = 0;
var n_usize = @as(usize, @bitCast(u32, n));
while (i < n_usize) {
var sb = [10:0]u8{ ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' };
var j: usize = i;
while (j < n_usize and j < i + 10) {
sb[j - i] = str[j];
j += 1;
}
if (i + 10 <= n_usize) {
try stdout.print("{s}\t:{d}\n", .{ sb, i + 10 });
} else {
try stdout.print("{s}\t:{d}\n", .{ sb, n });
}
i += 10;
}
}
fn sum_terms(a: i32, b: i32) anyerror!Pair {
if (b == a + 1) {
var p = try bigint.Managed.initSet(global_allocator, 1);
var q = try bigint.Managed.initSet(global_allocator, b);
return Pair{
.p = p,
.q = q,
};
}
var mid: i32 = @divFloor((a + b), 2);
var pair_left: Pair = try sum_terms(a, mid);
defer pair_left.deinit();
var pair_right: Pair = try sum_terms(mid, b);
defer pair_right.deinit();
var left = try bigint.Managed.init(global_allocator);
try bigint.Managed.mul(&left, pair_left.p.toConst(), pair_right.q.toConst());
try bigint.Managed.add(&left, left.toConst(), pair_right.p.toConst());
var right = try bigint.Managed.init(global_allocator);
try bigint.Managed.mul(&right, pair_left.q.toConst(), pair_right.q.toConst());
return Pair{
.p = left,
.q = right,
};
}
fn binary_search(n: i32) i32 {
var a: i32 = 0;
var b: i32 = 1;
while (!test_k(n, b)) {
a = b;
b *= 2;
}
while (b - a > 1) {
var m: i32 = @divFloor(a + b, 2);
if (test_k(n, m)) {
b = m;
} else {
a = m;
}
}
return b;
}
fn test_k(n: i32, k: i32) bool {
if (k < 0) {
return false;
}
var float_k = @intToFloat(f64, k);
var float_n = @intToFloat(f64, n);
var ln_k_factorial = float_k * (math.ln(float_k) - 1.0) + 0.5 * math.ln(math.tau);
var log_10_k_factorial = ln_k_factorial / math.ln10;
return log_10_k_factorial >= float_n + 50.0;
}
fn get_n() !i32 {
const args = try std.process.argsAlloc(global_allocator);
defer std.process.argsFree(global_allocator, args);
if (args.len > 1) {
return try std.fmt.parseInt(i32, args[1], 10);
} else {
return 27;
}
} | bench/algorithm/edigits/1.zig |
const watchdog = @import("watchdog.zig");
const cpu = @import("mk20dx256.zig");
const interrupt = @import("interrupt.zig");
const config = @import("config.zig");
const systick = @import("systick.zig");
extern fn _eram() void;
extern var _etext: usize;
extern var _sdata: usize;
extern var _edata: usize;
extern var _sbss: u8;
extern var _ebss: u8;
export const interrupt_vectors linksection(".vectors") = [_]fn () callconv(.C) void{
_eram,
_start,
interrupt.isr_non_maskable,
interrupt.isr_hard_fault,
interrupt.isr_memmanage_fault,
interrupt.isr_bus_fault,
interrupt.isr_usage_fault,
interrupt.isr_ignore, // Reserved 7
interrupt.isr_ignore, // Reserved 8
interrupt.isr_ignore, // Reserved 9
interrupt.isr_ignore, // Reserved 10
interrupt.isr_svcall,
interrupt.isr_debug_monitor,
interrupt.isr_ignore, // Reserved 13
interrupt.isr_pendablesrvreq,
interrupt.isr_systick,
interrupt.isr_dma_ch0_complete,
interrupt.isr_dma_ch1_complete,
interrupt.isr_dma_ch2_complete,
interrupt.isr_dma_ch3_complete,
interrupt.isr_dma_ch4_complete,
interrupt.isr_dma_ch5_complete,
interrupt.isr_dma_ch6_complete,
interrupt.isr_dma_ch7_complete,
interrupt.isr_dma_ch8_complete,
interrupt.isr_dma_ch9_complete,
interrupt.isr_dma_ch10_complete,
interrupt.isr_dma_ch11_complete,
interrupt.isr_dma_ch12_complete,
interrupt.isr_dma_ch13_complete,
interrupt.isr_dma_ch14_complete,
interrupt.isr_dma_ch15_complete,
interrupt.isr_dma_error,
interrupt.isr_ignore, // Unused ? INT_MCM ?
interrupt.isr_flash_cmd_complete,
interrupt.isr_flash_read_collision,
interrupt.isr_low_voltage_warning,
interrupt.isr_low_voltage_wakeup,
interrupt.isr_wdog_or_emw,
interrupt.isr_ignore, // Reserved 39
interrupt.isr_i2c0,
interrupt.isr_i2c1,
interrupt.isr_spi0,
interrupt.isr_spi1,
interrupt.isr_ignore, // Teensy does not have SPI2
interrupt.isr_can0_or_msg_buf,
interrupt.isr_can0_bus_off,
interrupt.isr_can0_error,
interrupt.isr_can0_transmit_warn,
interrupt.isr_can0_receive_warn,
interrupt.isr_can0_wakeup,
interrupt.isr_i2s0_transmit,
interrupt.isr_i2s0_receive,
interrupt.isr_ignore, // Teensy does not have CAN1
interrupt.isr_ignore, // Teensy does not have CAN1
interrupt.isr_ignore, // Teensy does not have CAN1
interrupt.isr_ignore, // Teensy does not have CAN1
interrupt.isr_ignore, // Teensy does not have CAN1
interrupt.isr_ignore, // Teensy does not have CAN1
interrupt.isr_ignore, // Reserved 59
interrupt.isr_uart0_lon,
interrupt.isr_uart0_status,
interrupt.isr_uart0_error,
interrupt.isr_uart1_status,
interrupt.isr_uart1_error,
interrupt.isr_uart2_status,
interrupt.isr_uart2_error,
interrupt.isr_ignore, // Teensy does not have UART3
interrupt.isr_ignore, // Teensy does not have UART3
interrupt.isr_ignore, // Teensy does not have UART4
interrupt.isr_ignore, // Teensy does not have UART4
interrupt.isr_ignore, // Teensy does not have UART5
interrupt.isr_ignore, // Teensy does not have UART5
interrupt.isr_adc0,
interrupt.isr_adc1,
interrupt.isr_cmp0,
interrupt.isr_cmp1,
interrupt.isr_cmp2,
interrupt.isr_ftm0,
interrupt.isr_ftm1,
interrupt.isr_ftm2,
interrupt.isr_cmt,
interrupt.isr_rtc_alarm,
interrupt.isr_rtc_seconds,
interrupt.isr_pit_ch0,
interrupt.isr_pit_ch1,
interrupt.isr_pit_ch2,
interrupt.isr_pit_ch3,
interrupt.isr_pdb,
interrupt.isr_usb_otg,
interrupt.isr_usb_charger,
interrupt.isr_ignore, // Reserved 91
interrupt.isr_ignore, // Reserved 92
interrupt.isr_ignore, // Reserved 93
interrupt.isr_ignore, // Reserved 94
interrupt.isr_ignore, // Nothing according to manual, I2S0 according to headers
interrupt.isr_ignore, // Nothing according to manual, SDHC according to headers
interrupt.isr_dac0,
interrupt.isr_ignore, // Teensy does not have DAC1
interrupt.isr_tsi,
interrupt.isr_mcg,
interrupt.isr_lpt,
interrupt.isr_ignore, // Reserved 102
interrupt.isr_port_a,
interrupt.isr_port_b,
interrupt.isr_port_c,
interrupt.isr_port_d,
interrupt.isr_port_e,
interrupt.isr_ignore, // Reserved 108
interrupt.isr_ignore, // Reserved 109
interrupt.isr_software,
interrupt.isr_ignore, // Reserved 111
};
// The flash configuration appears at 0x400 and is loaded on boot.
// The first 8 bytes are the backdoor comparison key.
// The next 4 bytes are the FPROT registers.
//
// Then, there's one byte each:
// FSEC, FOPT, FEPROT, FDPROT
//
// For most of these fields, 0xFF are the permissive defaults. For
// FSEC, we'll set SEC to 10 to put the MCU in unsecure mode for
// unlimited flash access -> 0xFE.
//
export const flashconfigbytes: [16]u8 linksection(".flashconfig") = [_]u8{
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF,
};
pub fn setup() void {
// The CPU has a watchdog feature which is on by default,
// so we have to configure it to not have nasty reset-surprises
// later on.
watchdog.disable();
// There is a write-once-after-reset register that allows to
// set which power states are available. Let's set it here.
if (cpu.RegolatorStatusAndControl.* & cpu.PMC_REGSC_ACKISO_MASK != 0) {
cpu.RegolatorStatusAndControl.* |= cpu.PMC_REGSC_ACKISO_MASK;
}
// For the sake of simplicity, enable all GPIO port clocks
cpu.System.ClockGating5.* |= (cpu.SIM_SCGC5_PORTA_MASK | cpu.SIM_SCGC5_PORTB_MASK | cpu.SIM_SCGC5_PORTC_MASK | cpu.SIM_SCGC5_PORTD_MASK | cpu.SIM_SCGC5_PORTE_MASK);
// ----------------------------------------------------------------------------------
// Setup clocks
// ----------------------------------------------------------------------------------
// See section 5 in the Freescale K20 manual for how clock distribution works
// The limits are outlined in section 5.5:
// Core and System clocks: max 72 MHz
// Bus/peripherial clock: max 50 MHz (integer divide of core)
// Flash clock: max 25 MHz
//
// Set MCG to very high frequency crystal and request oscillator. We have
// to do this first so that the divisor will be correct (512 and not 16)
cpu.ClockGenerator.control2 = cpu.mcg_c2_range0(2) | cpu.MCG_C2_EREFS0_MASK;
// Select the external reference clock for MCGOUTCLK
// The divider for the FLL has to be chosen that we get something in 31.25 to 39.0625 kHz
// 16MHz / 512 = 31.25 kHz -> set FRDIV to 4
cpu.ClockGenerator.control1 = cpu.mcg_c1_clks(2) | cpu.mcg_c1_frdiv(4);
// Wait for OSC to become ready
while ((cpu.ClockGenerator.status & cpu.MCG_S_OSCINIT0_MASK) == 0) {}
// Wait for the FLL to synchronize to external reference
while ((cpu.ClockGenerator.status & cpu.MCG_S_IREFST_MASK) != 0) {}
// Wait for the clock mode to synchronize to external
while ((cpu.ClockGenerator.status & cpu.MCG_S_CLKST_MASK) != cpu.mcg_s_clkst(2)) {}
switch (config.frequency) {
config.CpuFrequency.F72MHz => {
cpu.ClockGenerator.control5 = cpu.mcg_c5_prdiv0(5); // 16 MHz / 6 = 2.66 MHz (this needs to be 2-4MHz)
cpu.ClockGenerator.control6 = cpu.MCG_C6_PLLS_MASK | cpu.mcg_c6_vdiv0(3); // Enable PLL*27 = 71.82 MHz
},
}
// Now that we setup and enabled the PLL, wait for it to become active
while ((cpu.ClockGenerator.status & cpu.MCG_S_PLLST_MASK) == 1) {}
// and locked
while ((cpu.ClockGenerator.status & cpu.MCG_S_LOCK0_MASK) == 1) {}
// -- For the modes <= 16 MHz, we have the MCG clock on 16 MHz, without FLL/PLL
// Also, USB is not possible
switch (config.frequency) {
config.CpuFrequency.F72MHz => {
// 72 MHz core, 36 MHz bus, 24 MHz flash
cpu.System.ClockDevider1.* = cpu.sim_clkdiv1_outdiv1(0) | cpu.sim_clkdiv1_outdiv2(1) | cpu.sim_clkdiv1_outdiv4(2);
cpu.System.ClockDevider2.* = cpu.sim_clkdiv2_usbdiv(2) | cpu.SIM_CLKDIV2_USBFRAC_MASK; // 72 * 2/3 = 48
},
}
var bss = @ptrCast([*]u8, &_sbss);
@memset(bss, 0, @ptrToInt(&_ebss) - @ptrToInt(&_sbss));
systick.init();
interrupt.enable();
}
extern fn zrtMain() noreturn;
export fn _start() linksection(".startup") noreturn {
zrtMain();
} | src/teensy3_2/init.zig |
const std = @import("std");
const args_parser = @import("args");
const img = @import("img");
const qoi = @import("qoi");
const Cli = struct {
help: bool = false,
};
pub fn main() !u8 {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var cli = args_parser.parseForCurrentProcess(Cli, allocator, .print) catch return 1;
defer cli.deinit();
if (cli.positionals.len != 2) {
return 1;
}
const in_path = cli.positionals[0];
const out_path = cli.positionals[1];
const in_ext = std.fs.path.extension(in_path);
const out_ext = std.fs.path.extension(out_path);
var image = if (std.mem.eql(u8, in_ext, ".qoi")) blk: {
var file = try std.fs.cwd().openFile(in_path, .{});
defer file.close();
var buffered_stream = std.io.bufferedReader(file.reader());
break :blk try qoi.decodeStream(allocator, buffered_stream.reader());
} else blk: {
var file = try img.Image.fromFilePath(allocator, in_path);
defer file.deinit();
var image = qoi.Image{
.width = try std.math.cast(u32, file.width),
.height = try std.math.cast(u32, file.height),
.colorspace = .sRGB,
.pixels = try allocator.alloc(qoi.Color, file.width * file.height),
};
errdefer image.deinit(allocator);
var iter = file.iterator();
var index: usize = 0;
while (iter.next()) |color| : (index += 1) {
const src_pix = color.toIntegerColor8();
image.pixels[index] = .{
.r = src_pix.R,
.g = src_pix.G,
.b = src_pix.B,
.a = src_pix.A,
};
}
break :blk image;
};
defer image.deinit(allocator);
var file = try std.fs.cwd().createFile(out_path, .{});
defer file.close();
if (std.mem.eql(u8, out_ext, ".qoi")) {
const buffer = try qoi.encodeBuffer(allocator, image.asConst());
defer allocator.free(buffer);
try file.writeAll(buffer);
} else if (std.mem.eql(u8, out_ext, ".ppm")) { // portable pixmap
// https://en.wikipedia.org/wiki/Netpbm#PPM_example
try file.writer().print("P6 {} {} 255\n", .{ image.width, image.height });
for (image.pixels) |pix| {
try file.writeAll(&[_]u8{
pix.r, pix.g, pix.b,
});
}
} else if (std.mem.eql(u8, out_ext, ".pam")) { // portable anymap
// https://en.wikipedia.org/wiki/Netpbm#PAM_graphics_format
try file.writer().print(
\\P7
\\WIDTH {}
\\HEIGHT {}
\\DEPTH 4
\\MAXVAL 255
\\TUPLTYPE RGB_ALPHA
\\ENDHDR
\\
, .{ image.width, image.height });
try file.writeAll(std.mem.sliceAsBytes(image.pixels));
} else { // fallback impl
var zigimg = img.Image{
.allocator = undefined,
.width = image.width,
.height = image.height,
.pixels = img.color.ColorStorage{
.Rgba32 = @ptrCast([*]img.color.Rgba32, image.pixels.ptr)[0..image.pixels.len],
},
};
const fmt = if (std.ascii.eqlIgnoreCase(out_ext, ".bmp"))
img.ImageFormat.Bmp
else if (std.ascii.eqlIgnoreCase(out_ext, ".pbm"))
img.ImageFormat.Pbm
else if (std.ascii.eqlIgnoreCase(out_ext, ".pcx"))
img.ImageFormat.Pcx
else if (std.ascii.eqlIgnoreCase(out_ext, ".pgm"))
img.ImageFormat.Pgm
else if (std.ascii.eqlIgnoreCase(out_ext, ".png"))
img.ImageFormat.Png
else if (std.ascii.eqlIgnoreCase(out_ext, ".ppm"))
img.ImageFormat.Ppm
else if (std.ascii.eqlIgnoreCase(out_ext, ".raw"))
img.ImageFormat.Raw
else if (std.ascii.eqlIgnoreCase(out_ext, ".tga"))
img.ImageFormat.Tga
else
return error.UnknownFormat;
try zigimg.writeToFile(&file, fmt, img.AllFormats.ImageEncoderOptions.None);
}
return 0;
} | src/convert.zig |
const c = @cImport({
@cInclude("cfl_group.h");
});
const widget = @import("widget.zig");
pub const GroupPtr = ?*c.Fl_Group;
pub const Group = struct {
inner: ?*c.Fl_Group,
pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) Group {
const ptr = c.Fl_Group_new(x, y, w, h, title);
if (ptr == null) unreachable;
return Group{
.inner = ptr,
};
}
pub fn current() Group {
return Group{
.inner = c.Fl_Group_current(),
};
}
pub fn raw(self: *Group) ?*c.Fl_Group {
return self.inner;
}
pub fn fromRaw(ptr: ?*c.Fl_Group) Group {
return Group{
.inner = ptr,
};
}
pub fn fromWidgetPtr(w: widget.WidgetPtr) Group {
return Group{
.inner = @ptrCast(?*c.Fl_Group, w),
};
}
pub fn fromVoidPtr(ptr: ?*c_void) Group {
return Group{
.inner = @ptrCast(?*c.Fl_Group, ptr),
};
}
pub fn toVoidPtr(self: *Group) ?*c_void {
return @ptrCast(?*c_void, self.inner);
}
pub fn asWidget(self: *const Group) widget.Widget {
return widget.Widget{
.inner = @ptrCast(widget.WidgetPtr, self.inner),
};
}
pub fn handle(self: *Group, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void {
c.Fl_Group_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data);
}
pub fn draw(self: *Group, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void {
c.Fl_Group_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data);
}
pub fn begin(self: *Group) void {
c.Fl_Group_begin(self.inner);
}
pub fn end(self: *Group) void {
c.Fl_Group_end(self.inner);
}
pub fn find(self: *const Group, w: *widget.Widget) u32 {
return c.Fl_Group_find(self.inner, w.*.raw());
}
pub fn add(self: *Group, w: *widget.Widget) void {
return c.Fl_Group_add(self.inner, w.*.raw());
}
pub fn insert(self: *Group, w: *widget.Widget, index: u32) void {
return c.Fl_Group_insert(self.inner, w.*.raw(), index);
}
pub fn remove(self: *Group, w: *widget.Widget) void {
return c.Fl_Group_remove(self.inner, w.*.raw());
}
pub fn resizable(self: *const Group, w: *widget.Widget) void {
return c.Fl_Group_resizable(self.inner, w.*.raw());
}
pub fn clear(self: *Group) void {
c.Fl_Group_clear(self.inner);
}
pub fn children(self: *const Group) u32 {
c.Fl_Group_children(self.inner);
}
pub fn child(self: *const Group, idx: u32) !widget.Widget {
const ptr = c.Fl_Group_child(self.inner, idx);
if (ptr == 0) unreachable;
return widget.Widget{
.inner = ptr,
};
}
};
pub const PackType = enum(i32) {
Vertical = 0,
Horizontal = 1,
};
pub const Pack = struct {
inner: ?*c.Fl_Pack,
pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) Pack {
const ptr = c.Fl_Pack_new(x, y, w, h, title);
if (ptr == null) unreachable;
return Pack{
.inner = ptr,
};
}
pub fn raw(self: *Pack) ?*c.Fl_Pack {
return self.inner;
}
pub fn fromRaw(ptr: ?*c.Fl_Pack) Pack {
return Pack{
.inner = ptr,
};
}
pub fn fromWidgetPtr(w: widget.WidgetPtr) Pack {
return Pack{
.inner = @ptrCast(?*c.Fl_Pack, w),
};
}
pub fn fromVoidPtr(ptr: ?*c_void) Pack {
return Pack{
.inner = @ptrCast(?*c.Fl_Pack, ptr),
};
}
pub fn toVoidPtr(self: *Pack) ?*c_void {
return @ptrCast(?*c_void, self.inner);
}
pub fn asWidget(self: *const Pack) widget.Widget {
return widget.Widget{
.inner = @ptrCast(widget.WidgetPtr, self.inner),
};
}
pub fn asGroup(self: *const Pack) Group {
return Group{
.inner = @ptrCast(?*c.Fl_Group, self.inner),
};
}
pub fn handle(self: *Pack, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void {
c.Fl_Pack_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data);
}
pub fn draw(self: *Pack, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void {
c.Fl_Pack_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data);
}
/// Get the spacing of the pack
pub fn spacing(self: *const Pack) i32 {
return c.Fl_Pack_spacing(self.inner);
}
/// Set the spacing of the pack
pub fn setSpacing(self: *Pack, s: i32) void {
c.Fl_Pack_set_spacing(self.inner, s);
}
};
pub const Tabs = struct {
inner: ?*c.Fl_Tabs,
pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) Tabs {
const ptr = c.Fl_Tabs_new(x, y, w, h, title);
if (ptr == null) unreachable;
return Tabs{
.inner = ptr,
};
}
pub fn raw(self: *Tabs) ?*c.Fl_Tabs {
return self.inner;
}
pub fn fromRaw(ptr: ?*c.Fl_Tabs) Tabs {
return Tabs{
.inner = ptr,
};
}
pub fn fromWidgetPtr(w: widget.WidgetPtr) Tabs {
return Tabs{
.inner = @ptrCast(?*c.Fl_Tabs, w),
};
}
pub fn fromVoidPtr(ptr: ?*c_void) Tabs {
return Tabs{
.inner = @ptrCast(?*c.Fl_Tabs, ptr),
};
}
pub fn toVoidPtr(self: *Tabs) ?*c_void {
return @ptrCast(?*c_void, self.inner);
}
pub fn asWidget(self: *const Tabs) widget.Widget {
return widget.Widget{
.inner = @ptrCast(widget.WidgetPtr, self.inner),
};
}
pub fn asGroup(self: *const Tabs) Group {
return Group{
.inner = @ptrCast(?*c.Fl_Group, self.inner),
};
}
pub fn handle(self: *Tabs, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void {
c.Fl_Tabs_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data);
}
pub fn draw(self: *Tabs, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void {
c.Fl_Tabs_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data);
}
/// Gets the currently visible group
pub fn value(self: *Tabs) Group {
return Group{ .inner = c.Fl_Tabs_value(self.inner) };
}
/// Sets the currently visible group
pub fn set_value(self: *Tabs, w: *const Group) void {
_ = c.Fl_Tabs_set_value(self.inner, w);
}
/// Sets the tab label alignment
pub fn set_tab_align(self: *Tabs, a: i32) void {
c.Fl_Tabs_set_tab_align(self.inner, a);
}
/// Gets the tab label alignment.
pub fn tab_align(self: *const Tabs) i32 {
return c.Fl_Tabs_tab_align(self.inner);
}
};
pub const ScrollType = enum(i32) {
/// Never show bars
None = 0,
/// Show vertical bar
Horizontal = 1,
/// Show vertical bar
Vertical = 2,
/// Show both horizontal and vertical bars
Both = 3,
/// Always show bars
AlwaysOn = 4,
/// Show horizontal bar always
HorizontalAlways = 5,
/// Show vertical bar always
VerticalAlways = 6,
/// Always show both horizontal and vertical bars
BothAlways = 7,
};
pub const Scroll = struct {
inner: ?*c.Fl_Scroll,
pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) Scroll {
const ptr = c.Fl_Scroll_new(x, y, w, h, title);
if (ptr == null) unreachable;
return Scroll{
.inner = ptr,
};
}
pub fn raw(self: *Scroll) ?*c.Fl_Scroll {
return self.inner;
}
pub fn fromRaw(ptr: ?*c.Fl_Scroll) Scroll {
return Scroll{
.inner = ptr,
};
}
pub fn fromWidgetPtr(w: widget.WidgetPtr) Scroll {
return Scroll{
.inner = @ptrCast(?*c.Fl_Scroll, w),
};
}
pub fn fromVoidPtr(ptr: ?*c_void) Scroll {
return Scroll{
.inner = @ptrCast(?*c.Fl_Scroll, ptr),
};
}
pub fn toVoidPtr(self: *Scroll) ?*c_void {
return @ptrCast(?*c_void, self.inner);
}
pub fn asWidget(self: *const Scroll) widget.Widget {
return widget.Widget{
.inner = @ptrCast(widget.WidgetPtr, self.inner),
};
}
pub fn asGroup(self: *const Scroll) Group {
return Group{
.inner = @ptrCast(?*c.Fl_Group, self.inner),
};
}
pub fn handle(self: *Scroll, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void {
c.Fl_Scroll_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data);
}
pub fn draw(self: *Scroll, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void {
c.Fl_Scroll_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data);
}
};
test "" {
@import("std").testing.refAllDecls(@This());
} | src/group.zig |
const std = @import("std");
const mem = std.mem;
const unicode = std.unicode;
const CaseFoldMap = @This();
allocator: *std.mem.Allocator,
map: std.AutoHashMap(u21, []const u21),
pub fn init(allocator: *std.mem.Allocator) !CaseFoldMap {
var instance = CaseFoldMap{
.allocator = allocator,
.map = std.AutoHashMap(u21, []const u21).init(allocator),
};
try instance.map.put(0x0041, &[_]u21{
0x0061,
});
try instance.map.put(0x0042, &[_]u21{
0x0062,
});
try instance.map.put(0x0043, &[_]u21{
0x0063,
});
try instance.map.put(0x0044, &[_]u21{
0x0064,
});
try instance.map.put(0x0045, &[_]u21{
0x0065,
});
try instance.map.put(0x0046, &[_]u21{
0x0066,
});
try instance.map.put(0x0047, &[_]u21{
0x0067,
});
try instance.map.put(0x0048, &[_]u21{
0x0068,
});
try instance.map.put(0x0049, &[_]u21{
0x0069,
});
try instance.map.put(0x004A, &[_]u21{
0x006A,
});
try instance.map.put(0x004B, &[_]u21{
0x006B,
});
try instance.map.put(0x004C, &[_]u21{
0x006C,
});
try instance.map.put(0x004D, &[_]u21{
0x006D,
});
try instance.map.put(0x004E, &[_]u21{
0x006E,
});
try instance.map.put(0x004F, &[_]u21{
0x006F,
});
try instance.map.put(0x0050, &[_]u21{
0x0070,
});
try instance.map.put(0x0051, &[_]u21{
0x0071,
});
try instance.map.put(0x0052, &[_]u21{
0x0072,
});
try instance.map.put(0x0053, &[_]u21{
0x0073,
});
try instance.map.put(0x0054, &[_]u21{
0x0074,
});
try instance.map.put(0x0055, &[_]u21{
0x0075,
});
try instance.map.put(0x0056, &[_]u21{
0x0076,
});
try instance.map.put(0x0057, &[_]u21{
0x0077,
});
try instance.map.put(0x0058, &[_]u21{
0x0078,
});
try instance.map.put(0x0059, &[_]u21{
0x0079,
});
try instance.map.put(0x005A, &[_]u21{
0x007A,
});
try instance.map.put(0x00B5, &[_]u21{
0x03BC,
});
try instance.map.put(0x00C0, &[_]u21{
0x00E0,
});
try instance.map.put(0x00C1, &[_]u21{
0x00E1,
});
try instance.map.put(0x00C2, &[_]u21{
0x00E2,
});
try instance.map.put(0x00C3, &[_]u21{
0x00E3,
});
try instance.map.put(0x00C4, &[_]u21{
0x00E4,
});
try instance.map.put(0x00C5, &[_]u21{
0x00E5,
});
try instance.map.put(0x00C6, &[_]u21{
0x00E6,
});
try instance.map.put(0x00C7, &[_]u21{
0x00E7,
});
try instance.map.put(0x00C8, &[_]u21{
0x00E8,
});
try instance.map.put(0x00C9, &[_]u21{
0x00E9,
});
try instance.map.put(0x00CA, &[_]u21{
0x00EA,
});
try instance.map.put(0x00CB, &[_]u21{
0x00EB,
});
try instance.map.put(0x00CC, &[_]u21{
0x00EC,
});
try instance.map.put(0x00CD, &[_]u21{
0x00ED,
});
try instance.map.put(0x00CE, &[_]u21{
0x00EE,
});
try instance.map.put(0x00CF, &[_]u21{
0x00EF,
});
try instance.map.put(0x00D0, &[_]u21{
0x00F0,
});
try instance.map.put(0x00D1, &[_]u21{
0x00F1,
});
try instance.map.put(0x00D2, &[_]u21{
0x00F2,
});
try instance.map.put(0x00D3, &[_]u21{
0x00F3,
});
try instance.map.put(0x00D4, &[_]u21{
0x00F4,
});
try instance.map.put(0x00D5, &[_]u21{
0x00F5,
});
try instance.map.put(0x00D6, &[_]u21{
0x00F6,
});
try instance.map.put(0x00D8, &[_]u21{
0x00F8,
});
try instance.map.put(0x00D9, &[_]u21{
0x00F9,
});
try instance.map.put(0x00DA, &[_]u21{
0x00FA,
});
try instance.map.put(0x00DB, &[_]u21{
0x00FB,
});
try instance.map.put(0x00DC, &[_]u21{
0x00FC,
});
try instance.map.put(0x00DD, &[_]u21{
0x00FD,
});
try instance.map.put(0x00DE, &[_]u21{
0x00FE,
});
try instance.map.put(0x00DF, &[_]u21{
0x0073,
0x0073,
});
try instance.map.put(0x0100, &[_]u21{
0x0101,
});
try instance.map.put(0x0102, &[_]u21{
0x0103,
});
try instance.map.put(0x0104, &[_]u21{
0x0105,
});
try instance.map.put(0x0106, &[_]u21{
0x0107,
});
try instance.map.put(0x0108, &[_]u21{
0x0109,
});
try instance.map.put(0x010A, &[_]u21{
0x010B,
});
try instance.map.put(0x010C, &[_]u21{
0x010D,
});
try instance.map.put(0x010E, &[_]u21{
0x010F,
});
try instance.map.put(0x0110, &[_]u21{
0x0111,
});
try instance.map.put(0x0112, &[_]u21{
0x0113,
});
try instance.map.put(0x0114, &[_]u21{
0x0115,
});
try instance.map.put(0x0116, &[_]u21{
0x0117,
});
try instance.map.put(0x0118, &[_]u21{
0x0119,
});
try instance.map.put(0x011A, &[_]u21{
0x011B,
});
try instance.map.put(0x011C, &[_]u21{
0x011D,
});
try instance.map.put(0x011E, &[_]u21{
0x011F,
});
try instance.map.put(0x0120, &[_]u21{
0x0121,
});
try instance.map.put(0x0122, &[_]u21{
0x0123,
});
try instance.map.put(0x0124, &[_]u21{
0x0125,
});
try instance.map.put(0x0126, &[_]u21{
0x0127,
});
try instance.map.put(0x0128, &[_]u21{
0x0129,
});
try instance.map.put(0x012A, &[_]u21{
0x012B,
});
try instance.map.put(0x012C, &[_]u21{
0x012D,
});
try instance.map.put(0x012E, &[_]u21{
0x012F,
});
try instance.map.put(0x0130, &[_]u21{
0x0069,
0x0307,
});
try instance.map.put(0x0132, &[_]u21{
0x0133,
});
try instance.map.put(0x0134, &[_]u21{
0x0135,
});
try instance.map.put(0x0136, &[_]u21{
0x0137,
});
try instance.map.put(0x0139, &[_]u21{
0x013A,
});
try instance.map.put(0x013B, &[_]u21{
0x013C,
});
try instance.map.put(0x013D, &[_]u21{
0x013E,
});
try instance.map.put(0x013F, &[_]u21{
0x0140,
});
try instance.map.put(0x0141, &[_]u21{
0x0142,
});
try instance.map.put(0x0143, &[_]u21{
0x0144,
});
try instance.map.put(0x0145, &[_]u21{
0x0146,
});
try instance.map.put(0x0147, &[_]u21{
0x0148,
});
try instance.map.put(0x0149, &[_]u21{
0x02BC,
0x006E,
});
try instance.map.put(0x014A, &[_]u21{
0x014B,
});
try instance.map.put(0x014C, &[_]u21{
0x014D,
});
try instance.map.put(0x014E, &[_]u21{
0x014F,
});
try instance.map.put(0x0150, &[_]u21{
0x0151,
});
try instance.map.put(0x0152, &[_]u21{
0x0153,
});
try instance.map.put(0x0154, &[_]u21{
0x0155,
});
try instance.map.put(0x0156, &[_]u21{
0x0157,
});
try instance.map.put(0x0158, &[_]u21{
0x0159,
});
try instance.map.put(0x015A, &[_]u21{
0x015B,
});
try instance.map.put(0x015C, &[_]u21{
0x015D,
});
try instance.map.put(0x015E, &[_]u21{
0x015F,
});
try instance.map.put(0x0160, &[_]u21{
0x0161,
});
try instance.map.put(0x0162, &[_]u21{
0x0163,
});
try instance.map.put(0x0164, &[_]u21{
0x0165,
});
try instance.map.put(0x0166, &[_]u21{
0x0167,
});
try instance.map.put(0x0168, &[_]u21{
0x0169,
});
try instance.map.put(0x016A, &[_]u21{
0x016B,
});
try instance.map.put(0x016C, &[_]u21{
0x016D,
});
try instance.map.put(0x016E, &[_]u21{
0x016F,
});
try instance.map.put(0x0170, &[_]u21{
0x0171,
});
try instance.map.put(0x0172, &[_]u21{
0x0173,
});
try instance.map.put(0x0174, &[_]u21{
0x0175,
});
try instance.map.put(0x0176, &[_]u21{
0x0177,
});
try instance.map.put(0x0178, &[_]u21{
0x00FF,
});
try instance.map.put(0x0179, &[_]u21{
0x017A,
});
try instance.map.put(0x017B, &[_]u21{
0x017C,
});
try instance.map.put(0x017D, &[_]u21{
0x017E,
});
try instance.map.put(0x017F, &[_]u21{
0x0073,
});
try instance.map.put(0x0181, &[_]u21{
0x0253,
});
try instance.map.put(0x0182, &[_]u21{
0x0183,
});
try instance.map.put(0x0184, &[_]u21{
0x0185,
});
try instance.map.put(0x0186, &[_]u21{
0x0254,
});
try instance.map.put(0x0187, &[_]u21{
0x0188,
});
try instance.map.put(0x0189, &[_]u21{
0x0256,
});
try instance.map.put(0x018A, &[_]u21{
0x0257,
});
try instance.map.put(0x018B, &[_]u21{
0x018C,
});
try instance.map.put(0x018E, &[_]u21{
0x01DD,
});
try instance.map.put(0x018F, &[_]u21{
0x0259,
});
try instance.map.put(0x0190, &[_]u21{
0x025B,
});
try instance.map.put(0x0191, &[_]u21{
0x0192,
});
try instance.map.put(0x0193, &[_]u21{
0x0260,
});
try instance.map.put(0x0194, &[_]u21{
0x0263,
});
try instance.map.put(0x0196, &[_]u21{
0x0269,
});
try instance.map.put(0x0197, &[_]u21{
0x0268,
});
try instance.map.put(0x0198, &[_]u21{
0x0199,
});
try instance.map.put(0x019C, &[_]u21{
0x026F,
});
try instance.map.put(0x019D, &[_]u21{
0x0272,
});
try instance.map.put(0x019F, &[_]u21{
0x0275,
});
try instance.map.put(0x01A0, &[_]u21{
0x01A1,
});
try instance.map.put(0x01A2, &[_]u21{
0x01A3,
});
try instance.map.put(0x01A4, &[_]u21{
0x01A5,
});
try instance.map.put(0x01A6, &[_]u21{
0x0280,
});
try instance.map.put(0x01A7, &[_]u21{
0x01A8,
});
try instance.map.put(0x01A9, &[_]u21{
0x0283,
});
try instance.map.put(0x01AC, &[_]u21{
0x01AD,
});
try instance.map.put(0x01AE, &[_]u21{
0x0288,
});
try instance.map.put(0x01AF, &[_]u21{
0x01B0,
});
try instance.map.put(0x01B1, &[_]u21{
0x028A,
});
try instance.map.put(0x01B2, &[_]u21{
0x028B,
});
try instance.map.put(0x01B3, &[_]u21{
0x01B4,
});
try instance.map.put(0x01B5, &[_]u21{
0x01B6,
});
try instance.map.put(0x01B7, &[_]u21{
0x0292,
});
try instance.map.put(0x01B8, &[_]u21{
0x01B9,
});
try instance.map.put(0x01BC, &[_]u21{
0x01BD,
});
try instance.map.put(0x01C4, &[_]u21{
0x01C6,
});
try instance.map.put(0x01C5, &[_]u21{
0x01C6,
});
try instance.map.put(0x01C7, &[_]u21{
0x01C9,
});
try instance.map.put(0x01C8, &[_]u21{
0x01C9,
});
try instance.map.put(0x01CA, &[_]u21{
0x01CC,
});
try instance.map.put(0x01CB, &[_]u21{
0x01CC,
});
try instance.map.put(0x01CD, &[_]u21{
0x01CE,
});
try instance.map.put(0x01CF, &[_]u21{
0x01D0,
});
try instance.map.put(0x01D1, &[_]u21{
0x01D2,
});
try instance.map.put(0x01D3, &[_]u21{
0x01D4,
});
try instance.map.put(0x01D5, &[_]u21{
0x01D6,
});
try instance.map.put(0x01D7, &[_]u21{
0x01D8,
});
try instance.map.put(0x01D9, &[_]u21{
0x01DA,
});
try instance.map.put(0x01DB, &[_]u21{
0x01DC,
});
try instance.map.put(0x01DE, &[_]u21{
0x01DF,
});
try instance.map.put(0x01E0, &[_]u21{
0x01E1,
});
try instance.map.put(0x01E2, &[_]u21{
0x01E3,
});
try instance.map.put(0x01E4, &[_]u21{
0x01E5,
});
try instance.map.put(0x01E6, &[_]u21{
0x01E7,
});
try instance.map.put(0x01E8, &[_]u21{
0x01E9,
});
try instance.map.put(0x01EA, &[_]u21{
0x01EB,
});
try instance.map.put(0x01EC, &[_]u21{
0x01ED,
});
try instance.map.put(0x01EE, &[_]u21{
0x01EF,
});
try instance.map.put(0x01F0, &[_]u21{
0x006A,
0x030C,
});
try instance.map.put(0x01F1, &[_]u21{
0x01F3,
});
try instance.map.put(0x01F2, &[_]u21{
0x01F3,
});
try instance.map.put(0x01F4, &[_]u21{
0x01F5,
});
try instance.map.put(0x01F6, &[_]u21{
0x0195,
});
try instance.map.put(0x01F7, &[_]u21{
0x01BF,
});
try instance.map.put(0x01F8, &[_]u21{
0x01F9,
});
try instance.map.put(0x01FA, &[_]u21{
0x01FB,
});
try instance.map.put(0x01FC, &[_]u21{
0x01FD,
});
try instance.map.put(0x01FE, &[_]u21{
0x01FF,
});
try instance.map.put(0x0200, &[_]u21{
0x0201,
});
try instance.map.put(0x0202, &[_]u21{
0x0203,
});
try instance.map.put(0x0204, &[_]u21{
0x0205,
});
try instance.map.put(0x0206, &[_]u21{
0x0207,
});
try instance.map.put(0x0208, &[_]u21{
0x0209,
});
try instance.map.put(0x020A, &[_]u21{
0x020B,
});
try instance.map.put(0x020C, &[_]u21{
0x020D,
});
try instance.map.put(0x020E, &[_]u21{
0x020F,
});
try instance.map.put(0x0210, &[_]u21{
0x0211,
});
try instance.map.put(0x0212, &[_]u21{
0x0213,
});
try instance.map.put(0x0214, &[_]u21{
0x0215,
});
try instance.map.put(0x0216, &[_]u21{
0x0217,
});
try instance.map.put(0x0218, &[_]u21{
0x0219,
});
try instance.map.put(0x021A, &[_]u21{
0x021B,
});
try instance.map.put(0x021C, &[_]u21{
0x021D,
});
try instance.map.put(0x021E, &[_]u21{
0x021F,
});
try instance.map.put(0x0220, &[_]u21{
0x019E,
});
try instance.map.put(0x0222, &[_]u21{
0x0223,
});
try instance.map.put(0x0224, &[_]u21{
0x0225,
});
try instance.map.put(0x0226, &[_]u21{
0x0227,
});
try instance.map.put(0x0228, &[_]u21{
0x0229,
});
try instance.map.put(0x022A, &[_]u21{
0x022B,
});
try instance.map.put(0x022C, &[_]u21{
0x022D,
});
try instance.map.put(0x022E, &[_]u21{
0x022F,
});
try instance.map.put(0x0230, &[_]u21{
0x0231,
});
try instance.map.put(0x0232, &[_]u21{
0x0233,
});
try instance.map.put(0x023A, &[_]u21{
0x2C65,
});
try instance.map.put(0x023B, &[_]u21{
0x023C,
});
try instance.map.put(0x023D, &[_]u21{
0x019A,
});
try instance.map.put(0x023E, &[_]u21{
0x2C66,
});
try instance.map.put(0x0241, &[_]u21{
0x0242,
});
try instance.map.put(0x0243, &[_]u21{
0x0180,
});
try instance.map.put(0x0244, &[_]u21{
0x0289,
});
try instance.map.put(0x0245, &[_]u21{
0x028C,
});
try instance.map.put(0x0246, &[_]u21{
0x0247,
});
try instance.map.put(0x0248, &[_]u21{
0x0249,
});
try instance.map.put(0x024A, &[_]u21{
0x024B,
});
try instance.map.put(0x024C, &[_]u21{
0x024D,
});
try instance.map.put(0x024E, &[_]u21{
0x024F,
});
try instance.map.put(0x0345, &[_]u21{
0x03B9,
});
try instance.map.put(0x0370, &[_]u21{
0x0371,
});
try instance.map.put(0x0372, &[_]u21{
0x0373,
});
try instance.map.put(0x0376, &[_]u21{
0x0377,
});
try instance.map.put(0x037F, &[_]u21{
0x03F3,
});
try instance.map.put(0x0386, &[_]u21{
0x03AC,
});
try instance.map.put(0x0388, &[_]u21{
0x03AD,
});
try instance.map.put(0x0389, &[_]u21{
0x03AE,
});
try instance.map.put(0x038A, &[_]u21{
0x03AF,
});
try instance.map.put(0x038C, &[_]u21{
0x03CC,
});
try instance.map.put(0x038E, &[_]u21{
0x03CD,
});
try instance.map.put(0x038F, &[_]u21{
0x03CE,
});
try instance.map.put(0x0390, &[_]u21{
0x03B9,
0x0308,
0x0301,
});
try instance.map.put(0x0391, &[_]u21{
0x03B1,
});
try instance.map.put(0x0392, &[_]u21{
0x03B2,
});
try instance.map.put(0x0393, &[_]u21{
0x03B3,
});
try instance.map.put(0x0394, &[_]u21{
0x03B4,
});
try instance.map.put(0x0395, &[_]u21{
0x03B5,
});
try instance.map.put(0x0396, &[_]u21{
0x03B6,
});
try instance.map.put(0x0397, &[_]u21{
0x03B7,
});
try instance.map.put(0x0398, &[_]u21{
0x03B8,
});
try instance.map.put(0x0399, &[_]u21{
0x03B9,
});
try instance.map.put(0x039A, &[_]u21{
0x03BA,
});
try instance.map.put(0x039B, &[_]u21{
0x03BB,
});
try instance.map.put(0x039C, &[_]u21{
0x03BC,
});
try instance.map.put(0x039D, &[_]u21{
0x03BD,
});
try instance.map.put(0x039E, &[_]u21{
0x03BE,
});
try instance.map.put(0x039F, &[_]u21{
0x03BF,
});
try instance.map.put(0x03A0, &[_]u21{
0x03C0,
});
try instance.map.put(0x03A1, &[_]u21{
0x03C1,
});
try instance.map.put(0x03A3, &[_]u21{
0x03C3,
});
try instance.map.put(0x03A4, &[_]u21{
0x03C4,
});
try instance.map.put(0x03A5, &[_]u21{
0x03C5,
});
try instance.map.put(0x03A6, &[_]u21{
0x03C6,
});
try instance.map.put(0x03A7, &[_]u21{
0x03C7,
});
try instance.map.put(0x03A8, &[_]u21{
0x03C8,
});
try instance.map.put(0x03A9, &[_]u21{
0x03C9,
});
try instance.map.put(0x03AA, &[_]u21{
0x03CA,
});
try instance.map.put(0x03AB, &[_]u21{
0x03CB,
});
try instance.map.put(0x03B0, &[_]u21{
0x03C5,
0x0308,
0x0301,
});
try instance.map.put(0x03C2, &[_]u21{
0x03C3,
});
try instance.map.put(0x03CF, &[_]u21{
0x03D7,
});
try instance.map.put(0x03D0, &[_]u21{
0x03B2,
});
try instance.map.put(0x03D1, &[_]u21{
0x03B8,
});
try instance.map.put(0x03D5, &[_]u21{
0x03C6,
});
try instance.map.put(0x03D6, &[_]u21{
0x03C0,
});
try instance.map.put(0x03D8, &[_]u21{
0x03D9,
});
try instance.map.put(0x03DA, &[_]u21{
0x03DB,
});
try instance.map.put(0x03DC, &[_]u21{
0x03DD,
});
try instance.map.put(0x03DE, &[_]u21{
0x03DF,
});
try instance.map.put(0x03E0, &[_]u21{
0x03E1,
});
try instance.map.put(0x03E2, &[_]u21{
0x03E3,
});
try instance.map.put(0x03E4, &[_]u21{
0x03E5,
});
try instance.map.put(0x03E6, &[_]u21{
0x03E7,
});
try instance.map.put(0x03E8, &[_]u21{
0x03E9,
});
try instance.map.put(0x03EA, &[_]u21{
0x03EB,
});
try instance.map.put(0x03EC, &[_]u21{
0x03ED,
});
try instance.map.put(0x03EE, &[_]u21{
0x03EF,
});
try instance.map.put(0x03F0, &[_]u21{
0x03BA,
});
try instance.map.put(0x03F1, &[_]u21{
0x03C1,
});
try instance.map.put(0x03F4, &[_]u21{
0x03B8,
});
try instance.map.put(0x03F5, &[_]u21{
0x03B5,
});
try instance.map.put(0x03F7, &[_]u21{
0x03F8,
});
try instance.map.put(0x03F9, &[_]u21{
0x03F2,
});
try instance.map.put(0x03FA, &[_]u21{
0x03FB,
});
try instance.map.put(0x03FD, &[_]u21{
0x037B,
});
try instance.map.put(0x03FE, &[_]u21{
0x037C,
});
try instance.map.put(0x03FF, &[_]u21{
0x037D,
});
try instance.map.put(0x0400, &[_]u21{
0x0450,
});
try instance.map.put(0x0401, &[_]u21{
0x0451,
});
try instance.map.put(0x0402, &[_]u21{
0x0452,
});
try instance.map.put(0x0403, &[_]u21{
0x0453,
});
try instance.map.put(0x0404, &[_]u21{
0x0454,
});
try instance.map.put(0x0405, &[_]u21{
0x0455,
});
try instance.map.put(0x0406, &[_]u21{
0x0456,
});
try instance.map.put(0x0407, &[_]u21{
0x0457,
});
try instance.map.put(0x0408, &[_]u21{
0x0458,
});
try instance.map.put(0x0409, &[_]u21{
0x0459,
});
try instance.map.put(0x040A, &[_]u21{
0x045A,
});
try instance.map.put(0x040B, &[_]u21{
0x045B,
});
try instance.map.put(0x040C, &[_]u21{
0x045C,
});
try instance.map.put(0x040D, &[_]u21{
0x045D,
});
try instance.map.put(0x040E, &[_]u21{
0x045E,
});
try instance.map.put(0x040F, &[_]u21{
0x045F,
});
try instance.map.put(0x0410, &[_]u21{
0x0430,
});
try instance.map.put(0x0411, &[_]u21{
0x0431,
});
try instance.map.put(0x0412, &[_]u21{
0x0432,
});
try instance.map.put(0x0413, &[_]u21{
0x0433,
});
try instance.map.put(0x0414, &[_]u21{
0x0434,
});
try instance.map.put(0x0415, &[_]u21{
0x0435,
});
try instance.map.put(0x0416, &[_]u21{
0x0436,
});
try instance.map.put(0x0417, &[_]u21{
0x0437,
});
try instance.map.put(0x0418, &[_]u21{
0x0438,
});
try instance.map.put(0x0419, &[_]u21{
0x0439,
});
try instance.map.put(0x041A, &[_]u21{
0x043A,
});
try instance.map.put(0x041B, &[_]u21{
0x043B,
});
try instance.map.put(0x041C, &[_]u21{
0x043C,
});
try instance.map.put(0x041D, &[_]u21{
0x043D,
});
try instance.map.put(0x041E, &[_]u21{
0x043E,
});
try instance.map.put(0x041F, &[_]u21{
0x043F,
});
try instance.map.put(0x0420, &[_]u21{
0x0440,
});
try instance.map.put(0x0421, &[_]u21{
0x0441,
});
try instance.map.put(0x0422, &[_]u21{
0x0442,
});
try instance.map.put(0x0423, &[_]u21{
0x0443,
});
try instance.map.put(0x0424, &[_]u21{
0x0444,
});
try instance.map.put(0x0425, &[_]u21{
0x0445,
});
try instance.map.put(0x0426, &[_]u21{
0x0446,
});
try instance.map.put(0x0427, &[_]u21{
0x0447,
});
try instance.map.put(0x0428, &[_]u21{
0x0448,
});
try instance.map.put(0x0429, &[_]u21{
0x0449,
});
try instance.map.put(0x042A, &[_]u21{
0x044A,
});
try instance.map.put(0x042B, &[_]u21{
0x044B,
});
try instance.map.put(0x042C, &[_]u21{
0x044C,
});
try instance.map.put(0x042D, &[_]u21{
0x044D,
});
try instance.map.put(0x042E, &[_]u21{
0x044E,
});
try instance.map.put(0x042F, &[_]u21{
0x044F,
});
try instance.map.put(0x0460, &[_]u21{
0x0461,
});
try instance.map.put(0x0462, &[_]u21{
0x0463,
});
try instance.map.put(0x0464, &[_]u21{
0x0465,
});
try instance.map.put(0x0466, &[_]u21{
0x0467,
});
try instance.map.put(0x0468, &[_]u21{
0x0469,
});
try instance.map.put(0x046A, &[_]u21{
0x046B,
});
try instance.map.put(0x046C, &[_]u21{
0x046D,
});
try instance.map.put(0x046E, &[_]u21{
0x046F,
});
try instance.map.put(0x0470, &[_]u21{
0x0471,
});
try instance.map.put(0x0472, &[_]u21{
0x0473,
});
try instance.map.put(0x0474, &[_]u21{
0x0475,
});
try instance.map.put(0x0476, &[_]u21{
0x0477,
});
try instance.map.put(0x0478, &[_]u21{
0x0479,
});
try instance.map.put(0x047A, &[_]u21{
0x047B,
});
try instance.map.put(0x047C, &[_]u21{
0x047D,
});
try instance.map.put(0x047E, &[_]u21{
0x047F,
});
try instance.map.put(0x0480, &[_]u21{
0x0481,
});
try instance.map.put(0x048A, &[_]u21{
0x048B,
});
try instance.map.put(0x048C, &[_]u21{
0x048D,
});
try instance.map.put(0x048E, &[_]u21{
0x048F,
});
try instance.map.put(0x0490, &[_]u21{
0x0491,
});
try instance.map.put(0x0492, &[_]u21{
0x0493,
});
try instance.map.put(0x0494, &[_]u21{
0x0495,
});
try instance.map.put(0x0496, &[_]u21{
0x0497,
});
try instance.map.put(0x0498, &[_]u21{
0x0499,
});
try instance.map.put(0x049A, &[_]u21{
0x049B,
});
try instance.map.put(0x049C, &[_]u21{
0x049D,
});
try instance.map.put(0x049E, &[_]u21{
0x049F,
});
try instance.map.put(0x04A0, &[_]u21{
0x04A1,
});
try instance.map.put(0x04A2, &[_]u21{
0x04A3,
});
try instance.map.put(0x04A4, &[_]u21{
0x04A5,
});
try instance.map.put(0x04A6, &[_]u21{
0x04A7,
});
try instance.map.put(0x04A8, &[_]u21{
0x04A9,
});
try instance.map.put(0x04AA, &[_]u21{
0x04AB,
});
try instance.map.put(0x04AC, &[_]u21{
0x04AD,
});
try instance.map.put(0x04AE, &[_]u21{
0x04AF,
});
try instance.map.put(0x04B0, &[_]u21{
0x04B1,
});
try instance.map.put(0x04B2, &[_]u21{
0x04B3,
});
try instance.map.put(0x04B4, &[_]u21{
0x04B5,
});
try instance.map.put(0x04B6, &[_]u21{
0x04B7,
});
try instance.map.put(0x04B8, &[_]u21{
0x04B9,
});
try instance.map.put(0x04BA, &[_]u21{
0x04BB,
});
try instance.map.put(0x04BC, &[_]u21{
0x04BD,
});
try instance.map.put(0x04BE, &[_]u21{
0x04BF,
});
try instance.map.put(0x04C0, &[_]u21{
0x04CF,
});
try instance.map.put(0x04C1, &[_]u21{
0x04C2,
});
try instance.map.put(0x04C3, &[_]u21{
0x04C4,
});
try instance.map.put(0x04C5, &[_]u21{
0x04C6,
});
try instance.map.put(0x04C7, &[_]u21{
0x04C8,
});
try instance.map.put(0x04C9, &[_]u21{
0x04CA,
});
try instance.map.put(0x04CB, &[_]u21{
0x04CC,
});
try instance.map.put(0x04CD, &[_]u21{
0x04CE,
});
try instance.map.put(0x04D0, &[_]u21{
0x04D1,
});
try instance.map.put(0x04D2, &[_]u21{
0x04D3,
});
try instance.map.put(0x04D4, &[_]u21{
0x04D5,
});
try instance.map.put(0x04D6, &[_]u21{
0x04D7,
});
try instance.map.put(0x04D8, &[_]u21{
0x04D9,
});
try instance.map.put(0x04DA, &[_]u21{
0x04DB,
});
try instance.map.put(0x04DC, &[_]u21{
0x04DD,
});
try instance.map.put(0x04DE, &[_]u21{
0x04DF,
});
try instance.map.put(0x04E0, &[_]u21{
0x04E1,
});
try instance.map.put(0x04E2, &[_]u21{
0x04E3,
});
try instance.map.put(0x04E4, &[_]u21{
0x04E5,
});
try instance.map.put(0x04E6, &[_]u21{
0x04E7,
});
try instance.map.put(0x04E8, &[_]u21{
0x04E9,
});
try instance.map.put(0x04EA, &[_]u21{
0x04EB,
});
try instance.map.put(0x04EC, &[_]u21{
0x04ED,
});
try instance.map.put(0x04EE, &[_]u21{
0x04EF,
});
try instance.map.put(0x04F0, &[_]u21{
0x04F1,
});
try instance.map.put(0x04F2, &[_]u21{
0x04F3,
});
try instance.map.put(0x04F4, &[_]u21{
0x04F5,
});
try instance.map.put(0x04F6, &[_]u21{
0x04F7,
});
try instance.map.put(0x04F8, &[_]u21{
0x04F9,
});
try instance.map.put(0x04FA, &[_]u21{
0x04FB,
});
try instance.map.put(0x04FC, &[_]u21{
0x04FD,
});
try instance.map.put(0x04FE, &[_]u21{
0x04FF,
});
try instance.map.put(0x0500, &[_]u21{
0x0501,
});
try instance.map.put(0x0502, &[_]u21{
0x0503,
});
try instance.map.put(0x0504, &[_]u21{
0x0505,
});
try instance.map.put(0x0506, &[_]u21{
0x0507,
});
try instance.map.put(0x0508, &[_]u21{
0x0509,
});
try instance.map.put(0x050A, &[_]u21{
0x050B,
});
try instance.map.put(0x050C, &[_]u21{
0x050D,
});
try instance.map.put(0x050E, &[_]u21{
0x050F,
});
try instance.map.put(0x0510, &[_]u21{
0x0511,
});
try instance.map.put(0x0512, &[_]u21{
0x0513,
});
try instance.map.put(0x0514, &[_]u21{
0x0515,
});
try instance.map.put(0x0516, &[_]u21{
0x0517,
});
try instance.map.put(0x0518, &[_]u21{
0x0519,
});
try instance.map.put(0x051A, &[_]u21{
0x051B,
});
try instance.map.put(0x051C, &[_]u21{
0x051D,
});
try instance.map.put(0x051E, &[_]u21{
0x051F,
});
try instance.map.put(0x0520, &[_]u21{
0x0521,
});
try instance.map.put(0x0522, &[_]u21{
0x0523,
});
try instance.map.put(0x0524, &[_]u21{
0x0525,
});
try instance.map.put(0x0526, &[_]u21{
0x0527,
});
try instance.map.put(0x0528, &[_]u21{
0x0529,
});
try instance.map.put(0x052A, &[_]u21{
0x052B,
});
try instance.map.put(0x052C, &[_]u21{
0x052D,
});
try instance.map.put(0x052E, &[_]u21{
0x052F,
});
try instance.map.put(0x0531, &[_]u21{
0x0561,
});
try instance.map.put(0x0532, &[_]u21{
0x0562,
});
try instance.map.put(0x0533, &[_]u21{
0x0563,
});
try instance.map.put(0x0534, &[_]u21{
0x0564,
});
try instance.map.put(0x0535, &[_]u21{
0x0565,
});
try instance.map.put(0x0536, &[_]u21{
0x0566,
});
try instance.map.put(0x0537, &[_]u21{
0x0567,
});
try instance.map.put(0x0538, &[_]u21{
0x0568,
});
try instance.map.put(0x0539, &[_]u21{
0x0569,
});
try instance.map.put(0x053A, &[_]u21{
0x056A,
});
try instance.map.put(0x053B, &[_]u21{
0x056B,
});
try instance.map.put(0x053C, &[_]u21{
0x056C,
});
try instance.map.put(0x053D, &[_]u21{
0x056D,
});
try instance.map.put(0x053E, &[_]u21{
0x056E,
});
try instance.map.put(0x053F, &[_]u21{
0x056F,
});
try instance.map.put(0x0540, &[_]u21{
0x0570,
});
try instance.map.put(0x0541, &[_]u21{
0x0571,
});
try instance.map.put(0x0542, &[_]u21{
0x0572,
});
try instance.map.put(0x0543, &[_]u21{
0x0573,
});
try instance.map.put(0x0544, &[_]u21{
0x0574,
});
try instance.map.put(0x0545, &[_]u21{
0x0575,
});
try instance.map.put(0x0546, &[_]u21{
0x0576,
});
try instance.map.put(0x0547, &[_]u21{
0x0577,
});
try instance.map.put(0x0548, &[_]u21{
0x0578,
});
try instance.map.put(0x0549, &[_]u21{
0x0579,
});
try instance.map.put(0x054A, &[_]u21{
0x057A,
});
try instance.map.put(0x054B, &[_]u21{
0x057B,
});
try instance.map.put(0x054C, &[_]u21{
0x057C,
});
try instance.map.put(0x054D, &[_]u21{
0x057D,
});
try instance.map.put(0x054E, &[_]u21{
0x057E,
});
try instance.map.put(0x054F, &[_]u21{
0x057F,
});
try instance.map.put(0x0550, &[_]u21{
0x0580,
});
try instance.map.put(0x0551, &[_]u21{
0x0581,
});
try instance.map.put(0x0552, &[_]u21{
0x0582,
});
try instance.map.put(0x0553, &[_]u21{
0x0583,
});
try instance.map.put(0x0554, &[_]u21{
0x0584,
});
try instance.map.put(0x0555, &[_]u21{
0x0585,
});
try instance.map.put(0x0556, &[_]u21{
0x0586,
});
try instance.map.put(0x0587, &[_]u21{
0x0565,
0x0582,
});
try instance.map.put(0x10A0, &[_]u21{
0x2D00,
});
try instance.map.put(0x10A1, &[_]u21{
0x2D01,
});
try instance.map.put(0x10A2, &[_]u21{
0x2D02,
});
try instance.map.put(0x10A3, &[_]u21{
0x2D03,
});
try instance.map.put(0x10A4, &[_]u21{
0x2D04,
});
try instance.map.put(0x10A5, &[_]u21{
0x2D05,
});
try instance.map.put(0x10A6, &[_]u21{
0x2D06,
});
try instance.map.put(0x10A7, &[_]u21{
0x2D07,
});
try instance.map.put(0x10A8, &[_]u21{
0x2D08,
});
try instance.map.put(0x10A9, &[_]u21{
0x2D09,
});
try instance.map.put(0x10AA, &[_]u21{
0x2D0A,
});
try instance.map.put(0x10AB, &[_]u21{
0x2D0B,
});
try instance.map.put(0x10AC, &[_]u21{
0x2D0C,
});
try instance.map.put(0x10AD, &[_]u21{
0x2D0D,
});
try instance.map.put(0x10AE, &[_]u21{
0x2D0E,
});
try instance.map.put(0x10AF, &[_]u21{
0x2D0F,
});
try instance.map.put(0x10B0, &[_]u21{
0x2D10,
});
try instance.map.put(0x10B1, &[_]u21{
0x2D11,
});
try instance.map.put(0x10B2, &[_]u21{
0x2D12,
});
try instance.map.put(0x10B3, &[_]u21{
0x2D13,
});
try instance.map.put(0x10B4, &[_]u21{
0x2D14,
});
try instance.map.put(0x10B5, &[_]u21{
0x2D15,
});
try instance.map.put(0x10B6, &[_]u21{
0x2D16,
});
try instance.map.put(0x10B7, &[_]u21{
0x2D17,
});
try instance.map.put(0x10B8, &[_]u21{
0x2D18,
});
try instance.map.put(0x10B9, &[_]u21{
0x2D19,
});
try instance.map.put(0x10BA, &[_]u21{
0x2D1A,
});
try instance.map.put(0x10BB, &[_]u21{
0x2D1B,
});
try instance.map.put(0x10BC, &[_]u21{
0x2D1C,
});
try instance.map.put(0x10BD, &[_]u21{
0x2D1D,
});
try instance.map.put(0x10BE, &[_]u21{
0x2D1E,
});
try instance.map.put(0x10BF, &[_]u21{
0x2D1F,
});
try instance.map.put(0x10C0, &[_]u21{
0x2D20,
});
try instance.map.put(0x10C1, &[_]u21{
0x2D21,
});
try instance.map.put(0x10C2, &[_]u21{
0x2D22,
});
try instance.map.put(0x10C3, &[_]u21{
0x2D23,
});
try instance.map.put(0x10C4, &[_]u21{
0x2D24,
});
try instance.map.put(0x10C5, &[_]u21{
0x2D25,
});
try instance.map.put(0x10C7, &[_]u21{
0x2D27,
});
try instance.map.put(0x10CD, &[_]u21{
0x2D2D,
});
try instance.map.put(0x13F8, &[_]u21{
0x13F0,
});
try instance.map.put(0x13F9, &[_]u21{
0x13F1,
});
try instance.map.put(0x13FA, &[_]u21{
0x13F2,
});
try instance.map.put(0x13FB, &[_]u21{
0x13F3,
});
try instance.map.put(0x13FC, &[_]u21{
0x13F4,
});
try instance.map.put(0x13FD, &[_]u21{
0x13F5,
});
try instance.map.put(0x1C80, &[_]u21{
0x0432,
});
try instance.map.put(0x1C81, &[_]u21{
0x0434,
});
try instance.map.put(0x1C82, &[_]u21{
0x043E,
});
try instance.map.put(0x1C83, &[_]u21{
0x0441,
});
try instance.map.put(0x1C84, &[_]u21{
0x0442,
});
try instance.map.put(0x1C85, &[_]u21{
0x0442,
});
try instance.map.put(0x1C86, &[_]u21{
0x044A,
});
try instance.map.put(0x1C87, &[_]u21{
0x0463,
});
try instance.map.put(0x1C88, &[_]u21{
0xA64B,
});
try instance.map.put(0x1C90, &[_]u21{
0x10D0,
});
try instance.map.put(0x1C91, &[_]u21{
0x10D1,
});
try instance.map.put(0x1C92, &[_]u21{
0x10D2,
});
try instance.map.put(0x1C93, &[_]u21{
0x10D3,
});
try instance.map.put(0x1C94, &[_]u21{
0x10D4,
});
try instance.map.put(0x1C95, &[_]u21{
0x10D5,
});
try instance.map.put(0x1C96, &[_]u21{
0x10D6,
});
try instance.map.put(0x1C97, &[_]u21{
0x10D7,
});
try instance.map.put(0x1C98, &[_]u21{
0x10D8,
});
try instance.map.put(0x1C99, &[_]u21{
0x10D9,
});
try instance.map.put(0x1C9A, &[_]u21{
0x10DA,
});
try instance.map.put(0x1C9B, &[_]u21{
0x10DB,
});
try instance.map.put(0x1C9C, &[_]u21{
0x10DC,
});
try instance.map.put(0x1C9D, &[_]u21{
0x10DD,
});
try instance.map.put(0x1C9E, &[_]u21{
0x10DE,
});
try instance.map.put(0x1C9F, &[_]u21{
0x10DF,
});
try instance.map.put(0x1CA0, &[_]u21{
0x10E0,
});
try instance.map.put(0x1CA1, &[_]u21{
0x10E1,
});
try instance.map.put(0x1CA2, &[_]u21{
0x10E2,
});
try instance.map.put(0x1CA3, &[_]u21{
0x10E3,
});
try instance.map.put(0x1CA4, &[_]u21{
0x10E4,
});
try instance.map.put(0x1CA5, &[_]u21{
0x10E5,
});
try instance.map.put(0x1CA6, &[_]u21{
0x10E6,
});
try instance.map.put(0x1CA7, &[_]u21{
0x10E7,
});
try instance.map.put(0x1CA8, &[_]u21{
0x10E8,
});
try instance.map.put(0x1CA9, &[_]u21{
0x10E9,
});
try instance.map.put(0x1CAA, &[_]u21{
0x10EA,
});
try instance.map.put(0x1CAB, &[_]u21{
0x10EB,
});
try instance.map.put(0x1CAC, &[_]u21{
0x10EC,
});
try instance.map.put(0x1CAD, &[_]u21{
0x10ED,
});
try instance.map.put(0x1CAE, &[_]u21{
0x10EE,
});
try instance.map.put(0x1CAF, &[_]u21{
0x10EF,
});
try instance.map.put(0x1CB0, &[_]u21{
0x10F0,
});
try instance.map.put(0x1CB1, &[_]u21{
0x10F1,
});
try instance.map.put(0x1CB2, &[_]u21{
0x10F2,
});
try instance.map.put(0x1CB3, &[_]u21{
0x10F3,
});
try instance.map.put(0x1CB4, &[_]u21{
0x10F4,
});
try instance.map.put(0x1CB5, &[_]u21{
0x10F5,
});
try instance.map.put(0x1CB6, &[_]u21{
0x10F6,
});
try instance.map.put(0x1CB7, &[_]u21{
0x10F7,
});
try instance.map.put(0x1CB8, &[_]u21{
0x10F8,
});
try instance.map.put(0x1CB9, &[_]u21{
0x10F9,
});
try instance.map.put(0x1CBA, &[_]u21{
0x10FA,
});
try instance.map.put(0x1CBD, &[_]u21{
0x10FD,
});
try instance.map.put(0x1CBE, &[_]u21{
0x10FE,
});
try instance.map.put(0x1CBF, &[_]u21{
0x10FF,
});
try instance.map.put(0x1E00, &[_]u21{
0x1E01,
});
try instance.map.put(0x1E02, &[_]u21{
0x1E03,
});
try instance.map.put(0x1E04, &[_]u21{
0x1E05,
});
try instance.map.put(0x1E06, &[_]u21{
0x1E07,
});
try instance.map.put(0x1E08, &[_]u21{
0x1E09,
});
try instance.map.put(0x1E0A, &[_]u21{
0x1E0B,
});
try instance.map.put(0x1E0C, &[_]u21{
0x1E0D,
});
try instance.map.put(0x1E0E, &[_]u21{
0x1E0F,
});
try instance.map.put(0x1E10, &[_]u21{
0x1E11,
});
try instance.map.put(0x1E12, &[_]u21{
0x1E13,
});
try instance.map.put(0x1E14, &[_]u21{
0x1E15,
});
try instance.map.put(0x1E16, &[_]u21{
0x1E17,
});
try instance.map.put(0x1E18, &[_]u21{
0x1E19,
});
try instance.map.put(0x1E1A, &[_]u21{
0x1E1B,
});
try instance.map.put(0x1E1C, &[_]u21{
0x1E1D,
});
try instance.map.put(0x1E1E, &[_]u21{
0x1E1F,
});
try instance.map.put(0x1E20, &[_]u21{
0x1E21,
});
try instance.map.put(0x1E22, &[_]u21{
0x1E23,
});
try instance.map.put(0x1E24, &[_]u21{
0x1E25,
});
try instance.map.put(0x1E26, &[_]u21{
0x1E27,
});
try instance.map.put(0x1E28, &[_]u21{
0x1E29,
});
try instance.map.put(0x1E2A, &[_]u21{
0x1E2B,
});
try instance.map.put(0x1E2C, &[_]u21{
0x1E2D,
});
try instance.map.put(0x1E2E, &[_]u21{
0x1E2F,
});
try instance.map.put(0x1E30, &[_]u21{
0x1E31,
});
try instance.map.put(0x1E32, &[_]u21{
0x1E33,
});
try instance.map.put(0x1E34, &[_]u21{
0x1E35,
});
try instance.map.put(0x1E36, &[_]u21{
0x1E37,
});
try instance.map.put(0x1E38, &[_]u21{
0x1E39,
});
try instance.map.put(0x1E3A, &[_]u21{
0x1E3B,
});
try instance.map.put(0x1E3C, &[_]u21{
0x1E3D,
});
try instance.map.put(0x1E3E, &[_]u21{
0x1E3F,
});
try instance.map.put(0x1E40, &[_]u21{
0x1E41,
});
try instance.map.put(0x1E42, &[_]u21{
0x1E43,
});
try instance.map.put(0x1E44, &[_]u21{
0x1E45,
});
try instance.map.put(0x1E46, &[_]u21{
0x1E47,
});
try instance.map.put(0x1E48, &[_]u21{
0x1E49,
});
try instance.map.put(0x1E4A, &[_]u21{
0x1E4B,
});
try instance.map.put(0x1E4C, &[_]u21{
0x1E4D,
});
try instance.map.put(0x1E4E, &[_]u21{
0x1E4F,
});
try instance.map.put(0x1E50, &[_]u21{
0x1E51,
});
try instance.map.put(0x1E52, &[_]u21{
0x1E53,
});
try instance.map.put(0x1E54, &[_]u21{
0x1E55,
});
try instance.map.put(0x1E56, &[_]u21{
0x1E57,
});
try instance.map.put(0x1E58, &[_]u21{
0x1E59,
});
try instance.map.put(0x1E5A, &[_]u21{
0x1E5B,
});
try instance.map.put(0x1E5C, &[_]u21{
0x1E5D,
});
try instance.map.put(0x1E5E, &[_]u21{
0x1E5F,
});
try instance.map.put(0x1E60, &[_]u21{
0x1E61,
});
try instance.map.put(0x1E62, &[_]u21{
0x1E63,
});
try instance.map.put(0x1E64, &[_]u21{
0x1E65,
});
try instance.map.put(0x1E66, &[_]u21{
0x1E67,
});
try instance.map.put(0x1E68, &[_]u21{
0x1E69,
});
try instance.map.put(0x1E6A, &[_]u21{
0x1E6B,
});
try instance.map.put(0x1E6C, &[_]u21{
0x1E6D,
});
try instance.map.put(0x1E6E, &[_]u21{
0x1E6F,
});
try instance.map.put(0x1E70, &[_]u21{
0x1E71,
});
try instance.map.put(0x1E72, &[_]u21{
0x1E73,
});
try instance.map.put(0x1E74, &[_]u21{
0x1E75,
});
try instance.map.put(0x1E76, &[_]u21{
0x1E77,
});
try instance.map.put(0x1E78, &[_]u21{
0x1E79,
});
try instance.map.put(0x1E7A, &[_]u21{
0x1E7B,
});
try instance.map.put(0x1E7C, &[_]u21{
0x1E7D,
});
try instance.map.put(0x1E7E, &[_]u21{
0x1E7F,
});
try instance.map.put(0x1E80, &[_]u21{
0x1E81,
});
try instance.map.put(0x1E82, &[_]u21{
0x1E83,
});
try instance.map.put(0x1E84, &[_]u21{
0x1E85,
});
try instance.map.put(0x1E86, &[_]u21{
0x1E87,
});
try instance.map.put(0x1E88, &[_]u21{
0x1E89,
});
try instance.map.put(0x1E8A, &[_]u21{
0x1E8B,
});
try instance.map.put(0x1E8C, &[_]u21{
0x1E8D,
});
try instance.map.put(0x1E8E, &[_]u21{
0x1E8F,
});
try instance.map.put(0x1E90, &[_]u21{
0x1E91,
});
try instance.map.put(0x1E92, &[_]u21{
0x1E93,
});
try instance.map.put(0x1E94, &[_]u21{
0x1E95,
});
try instance.map.put(0x1E96, &[_]u21{
0x0068,
0x0331,
});
try instance.map.put(0x1E97, &[_]u21{
0x0074,
0x0308,
});
try instance.map.put(0x1E98, &[_]u21{
0x0077,
0x030A,
});
try instance.map.put(0x1E99, &[_]u21{
0x0079,
0x030A,
});
try instance.map.put(0x1E9A, &[_]u21{
0x0061,
0x02BE,
});
try instance.map.put(0x1E9B, &[_]u21{
0x1E61,
});
try instance.map.put(0x1E9E, &[_]u21{
0x0073,
0x0073,
});
try instance.map.put(0x1EA0, &[_]u21{
0x1EA1,
});
try instance.map.put(0x1EA2, &[_]u21{
0x1EA3,
});
try instance.map.put(0x1EA4, &[_]u21{
0x1EA5,
});
try instance.map.put(0x1EA6, &[_]u21{
0x1EA7,
});
try instance.map.put(0x1EA8, &[_]u21{
0x1EA9,
});
try instance.map.put(0x1EAA, &[_]u21{
0x1EAB,
});
try instance.map.put(0x1EAC, &[_]u21{
0x1EAD,
});
try instance.map.put(0x1EAE, &[_]u21{
0x1EAF,
});
try instance.map.put(0x1EB0, &[_]u21{
0x1EB1,
});
try instance.map.put(0x1EB2, &[_]u21{
0x1EB3,
});
try instance.map.put(0x1EB4, &[_]u21{
0x1EB5,
});
try instance.map.put(0x1EB6, &[_]u21{
0x1EB7,
});
try instance.map.put(0x1EB8, &[_]u21{
0x1EB9,
});
try instance.map.put(0x1EBA, &[_]u21{
0x1EBB,
});
try instance.map.put(0x1EBC, &[_]u21{
0x1EBD,
});
try instance.map.put(0x1EBE, &[_]u21{
0x1EBF,
});
try instance.map.put(0x1EC0, &[_]u21{
0x1EC1,
});
try instance.map.put(0x1EC2, &[_]u21{
0x1EC3,
});
try instance.map.put(0x1EC4, &[_]u21{
0x1EC5,
});
try instance.map.put(0x1EC6, &[_]u21{
0x1EC7,
});
try instance.map.put(0x1EC8, &[_]u21{
0x1EC9,
});
try instance.map.put(0x1ECA, &[_]u21{
0x1ECB,
});
try instance.map.put(0x1ECC, &[_]u21{
0x1ECD,
});
try instance.map.put(0x1ECE, &[_]u21{
0x1ECF,
});
try instance.map.put(0x1ED0, &[_]u21{
0x1ED1,
});
try instance.map.put(0x1ED2, &[_]u21{
0x1ED3,
});
try instance.map.put(0x1ED4, &[_]u21{
0x1ED5,
});
try instance.map.put(0x1ED6, &[_]u21{
0x1ED7,
});
try instance.map.put(0x1ED8, &[_]u21{
0x1ED9,
});
try instance.map.put(0x1EDA, &[_]u21{
0x1EDB,
});
try instance.map.put(0x1EDC, &[_]u21{
0x1EDD,
});
try instance.map.put(0x1EDE, &[_]u21{
0x1EDF,
});
try instance.map.put(0x1EE0, &[_]u21{
0x1EE1,
});
try instance.map.put(0x1EE2, &[_]u21{
0x1EE3,
});
try instance.map.put(0x1EE4, &[_]u21{
0x1EE5,
});
try instance.map.put(0x1EE6, &[_]u21{
0x1EE7,
});
try instance.map.put(0x1EE8, &[_]u21{
0x1EE9,
});
try instance.map.put(0x1EEA, &[_]u21{
0x1EEB,
});
try instance.map.put(0x1EEC, &[_]u21{
0x1EED,
});
try instance.map.put(0x1EEE, &[_]u21{
0x1EEF,
});
try instance.map.put(0x1EF0, &[_]u21{
0x1EF1,
});
try instance.map.put(0x1EF2, &[_]u21{
0x1EF3,
});
try instance.map.put(0x1EF4, &[_]u21{
0x1EF5,
});
try instance.map.put(0x1EF6, &[_]u21{
0x1EF7,
});
try instance.map.put(0x1EF8, &[_]u21{
0x1EF9,
});
try instance.map.put(0x1EFA, &[_]u21{
0x1EFB,
});
try instance.map.put(0x1EFC, &[_]u21{
0x1EFD,
});
try instance.map.put(0x1EFE, &[_]u21{
0x1EFF,
});
try instance.map.put(0x1F08, &[_]u21{
0x1F00,
});
try instance.map.put(0x1F09, &[_]u21{
0x1F01,
});
try instance.map.put(0x1F0A, &[_]u21{
0x1F02,
});
try instance.map.put(0x1F0B, &[_]u21{
0x1F03,
});
try instance.map.put(0x1F0C, &[_]u21{
0x1F04,
});
try instance.map.put(0x1F0D, &[_]u21{
0x1F05,
});
try instance.map.put(0x1F0E, &[_]u21{
0x1F06,
});
try instance.map.put(0x1F0F, &[_]u21{
0x1F07,
});
try instance.map.put(0x1F18, &[_]u21{
0x1F10,
});
try instance.map.put(0x1F19, &[_]u21{
0x1F11,
});
try instance.map.put(0x1F1A, &[_]u21{
0x1F12,
});
try instance.map.put(0x1F1B, &[_]u21{
0x1F13,
});
try instance.map.put(0x1F1C, &[_]u21{
0x1F14,
});
try instance.map.put(0x1F1D, &[_]u21{
0x1F15,
});
try instance.map.put(0x1F28, &[_]u21{
0x1F20,
});
try instance.map.put(0x1F29, &[_]u21{
0x1F21,
});
try instance.map.put(0x1F2A, &[_]u21{
0x1F22,
});
try instance.map.put(0x1F2B, &[_]u21{
0x1F23,
});
try instance.map.put(0x1F2C, &[_]u21{
0x1F24,
});
try instance.map.put(0x1F2D, &[_]u21{
0x1F25,
});
try instance.map.put(0x1F2E, &[_]u21{
0x1F26,
});
try instance.map.put(0x1F2F, &[_]u21{
0x1F27,
});
try instance.map.put(0x1F38, &[_]u21{
0x1F30,
});
try instance.map.put(0x1F39, &[_]u21{
0x1F31,
});
try instance.map.put(0x1F3A, &[_]u21{
0x1F32,
});
try instance.map.put(0x1F3B, &[_]u21{
0x1F33,
});
try instance.map.put(0x1F3C, &[_]u21{
0x1F34,
});
try instance.map.put(0x1F3D, &[_]u21{
0x1F35,
});
try instance.map.put(0x1F3E, &[_]u21{
0x1F36,
});
try instance.map.put(0x1F3F, &[_]u21{
0x1F37,
});
try instance.map.put(0x1F48, &[_]u21{
0x1F40,
});
try instance.map.put(0x1F49, &[_]u21{
0x1F41,
});
try instance.map.put(0x1F4A, &[_]u21{
0x1F42,
});
try instance.map.put(0x1F4B, &[_]u21{
0x1F43,
});
try instance.map.put(0x1F4C, &[_]u21{
0x1F44,
});
try instance.map.put(0x1F4D, &[_]u21{
0x1F45,
});
try instance.map.put(0x1F50, &[_]u21{
0x03C5,
0x0313,
});
try instance.map.put(0x1F52, &[_]u21{
0x03C5,
0x0313,
0x0300,
});
try instance.map.put(0x1F54, &[_]u21{
0x03C5,
0x0313,
0x0301,
});
try instance.map.put(0x1F56, &[_]u21{
0x03C5,
0x0313,
0x0342,
});
try instance.map.put(0x1F59, &[_]u21{
0x1F51,
});
try instance.map.put(0x1F5B, &[_]u21{
0x1F53,
});
try instance.map.put(0x1F5D, &[_]u21{
0x1F55,
});
try instance.map.put(0x1F5F, &[_]u21{
0x1F57,
});
try instance.map.put(0x1F68, &[_]u21{
0x1F60,
});
try instance.map.put(0x1F69, &[_]u21{
0x1F61,
});
try instance.map.put(0x1F6A, &[_]u21{
0x1F62,
});
try instance.map.put(0x1F6B, &[_]u21{
0x1F63,
});
try instance.map.put(0x1F6C, &[_]u21{
0x1F64,
});
try instance.map.put(0x1F6D, &[_]u21{
0x1F65,
});
try instance.map.put(0x1F6E, &[_]u21{
0x1F66,
});
try instance.map.put(0x1F6F, &[_]u21{
0x1F67,
});
try instance.map.put(0x1F80, &[_]u21{
0x1F00,
0x03B9,
});
try instance.map.put(0x1F81, &[_]u21{
0x1F01,
0x03B9,
});
try instance.map.put(0x1F82, &[_]u21{
0x1F02,
0x03B9,
});
try instance.map.put(0x1F83, &[_]u21{
0x1F03,
0x03B9,
});
try instance.map.put(0x1F84, &[_]u21{
0x1F04,
0x03B9,
});
try instance.map.put(0x1F85, &[_]u21{
0x1F05,
0x03B9,
});
try instance.map.put(0x1F86, &[_]u21{
0x1F06,
0x03B9,
});
try instance.map.put(0x1F87, &[_]u21{
0x1F07,
0x03B9,
});
try instance.map.put(0x1F88, &[_]u21{
0x1F00,
0x03B9,
});
try instance.map.put(0x1F89, &[_]u21{
0x1F01,
0x03B9,
});
try instance.map.put(0x1F8A, &[_]u21{
0x1F02,
0x03B9,
});
try instance.map.put(0x1F8B, &[_]u21{
0x1F03,
0x03B9,
});
try instance.map.put(0x1F8C, &[_]u21{
0x1F04,
0x03B9,
});
try instance.map.put(0x1F8D, &[_]u21{
0x1F05,
0x03B9,
});
try instance.map.put(0x1F8E, &[_]u21{
0x1F06,
0x03B9,
});
try instance.map.put(0x1F8F, &[_]u21{
0x1F07,
0x03B9,
});
try instance.map.put(0x1F90, &[_]u21{
0x1F20,
0x03B9,
});
try instance.map.put(0x1F91, &[_]u21{
0x1F21,
0x03B9,
});
try instance.map.put(0x1F92, &[_]u21{
0x1F22,
0x03B9,
});
try instance.map.put(0x1F93, &[_]u21{
0x1F23,
0x03B9,
});
try instance.map.put(0x1F94, &[_]u21{
0x1F24,
0x03B9,
});
try instance.map.put(0x1F95, &[_]u21{
0x1F25,
0x03B9,
});
try instance.map.put(0x1F96, &[_]u21{
0x1F26,
0x03B9,
});
try instance.map.put(0x1F97, &[_]u21{
0x1F27,
0x03B9,
});
try instance.map.put(0x1F98, &[_]u21{
0x1F20,
0x03B9,
});
try instance.map.put(0x1F99, &[_]u21{
0x1F21,
0x03B9,
});
try instance.map.put(0x1F9A, &[_]u21{
0x1F22,
0x03B9,
});
try instance.map.put(0x1F9B, &[_]u21{
0x1F23,
0x03B9,
});
try instance.map.put(0x1F9C, &[_]u21{
0x1F24,
0x03B9,
});
try instance.map.put(0x1F9D, &[_]u21{
0x1F25,
0x03B9,
});
try instance.map.put(0x1F9E, &[_]u21{
0x1F26,
0x03B9,
});
try instance.map.put(0x1F9F, &[_]u21{
0x1F27,
0x03B9,
});
try instance.map.put(0x1FA0, &[_]u21{
0x1F60,
0x03B9,
});
try instance.map.put(0x1FA1, &[_]u21{
0x1F61,
0x03B9,
});
try instance.map.put(0x1FA2, &[_]u21{
0x1F62,
0x03B9,
});
try instance.map.put(0x1FA3, &[_]u21{
0x1F63,
0x03B9,
});
try instance.map.put(0x1FA4, &[_]u21{
0x1F64,
0x03B9,
});
try instance.map.put(0x1FA5, &[_]u21{
0x1F65,
0x03B9,
});
try instance.map.put(0x1FA6, &[_]u21{
0x1F66,
0x03B9,
});
try instance.map.put(0x1FA7, &[_]u21{
0x1F67,
0x03B9,
});
try instance.map.put(0x1FA8, &[_]u21{
0x1F60,
0x03B9,
});
try instance.map.put(0x1FA9, &[_]u21{
0x1F61,
0x03B9,
});
try instance.map.put(0x1FAA, &[_]u21{
0x1F62,
0x03B9,
});
try instance.map.put(0x1FAB, &[_]u21{
0x1F63,
0x03B9,
});
try instance.map.put(0x1FAC, &[_]u21{
0x1F64,
0x03B9,
});
try instance.map.put(0x1FAD, &[_]u21{
0x1F65,
0x03B9,
});
try instance.map.put(0x1FAE, &[_]u21{
0x1F66,
0x03B9,
});
try instance.map.put(0x1FAF, &[_]u21{
0x1F67,
0x03B9,
});
try instance.map.put(0x1FB2, &[_]u21{
0x1F70,
0x03B9,
});
try instance.map.put(0x1FB3, &[_]u21{
0x03B1,
0x03B9,
});
try instance.map.put(0x1FB4, &[_]u21{
0x03AC,
0x03B9,
});
try instance.map.put(0x1FB6, &[_]u21{
0x03B1,
0x0342,
});
try instance.map.put(0x1FB7, &[_]u21{
0x03B1,
0x0342,
0x03B9,
});
try instance.map.put(0x1FB8, &[_]u21{
0x1FB0,
});
try instance.map.put(0x1FB9, &[_]u21{
0x1FB1,
});
try instance.map.put(0x1FBA, &[_]u21{
0x1F70,
});
try instance.map.put(0x1FBB, &[_]u21{
0x1F71,
});
try instance.map.put(0x1FBC, &[_]u21{
0x03B1,
0x03B9,
});
try instance.map.put(0x1FBE, &[_]u21{
0x03B9,
});
try instance.map.put(0x1FC2, &[_]u21{
0x1F74,
0x03B9,
});
try instance.map.put(0x1FC3, &[_]u21{
0x03B7,
0x03B9,
});
try instance.map.put(0x1FC4, &[_]u21{
0x03AE,
0x03B9,
});
try instance.map.put(0x1FC6, &[_]u21{
0x03B7,
0x0342,
});
try instance.map.put(0x1FC7, &[_]u21{
0x03B7,
0x0342,
0x03B9,
});
try instance.map.put(0x1FC8, &[_]u21{
0x1F72,
});
try instance.map.put(0x1FC9, &[_]u21{
0x1F73,
});
try instance.map.put(0x1FCA, &[_]u21{
0x1F74,
});
try instance.map.put(0x1FCB, &[_]u21{
0x1F75,
});
try instance.map.put(0x1FCC, &[_]u21{
0x03B7,
0x03B9,
});
try instance.map.put(0x1FD2, &[_]u21{
0x03B9,
0x0308,
0x0300,
});
try instance.map.put(0x1FD3, &[_]u21{
0x03B9,
0x0308,
0x0301,
});
try instance.map.put(0x1FD6, &[_]u21{
0x03B9,
0x0342,
});
try instance.map.put(0x1FD7, &[_]u21{
0x03B9,
0x0308,
0x0342,
});
try instance.map.put(0x1FD8, &[_]u21{
0x1FD0,
});
try instance.map.put(0x1FD9, &[_]u21{
0x1FD1,
});
try instance.map.put(0x1FDA, &[_]u21{
0x1F76,
});
try instance.map.put(0x1FDB, &[_]u21{
0x1F77,
});
try instance.map.put(0x1FE2, &[_]u21{
0x03C5,
0x0308,
0x0300,
});
try instance.map.put(0x1FE3, &[_]u21{
0x03C5,
0x0308,
0x0301,
});
try instance.map.put(0x1FE4, &[_]u21{
0x03C1,
0x0313,
});
try instance.map.put(0x1FE6, &[_]u21{
0x03C5,
0x0342,
});
try instance.map.put(0x1FE7, &[_]u21{
0x03C5,
0x0308,
0x0342,
});
try instance.map.put(0x1FE8, &[_]u21{
0x1FE0,
});
try instance.map.put(0x1FE9, &[_]u21{
0x1FE1,
});
try instance.map.put(0x1FEA, &[_]u21{
0x1F7A,
});
try instance.map.put(0x1FEB, &[_]u21{
0x1F7B,
});
try instance.map.put(0x1FEC, &[_]u21{
0x1FE5,
});
try instance.map.put(0x1FF2, &[_]u21{
0x1F7C,
0x03B9,
});
try instance.map.put(0x1FF3, &[_]u21{
0x03C9,
0x03B9,
});
try instance.map.put(0x1FF4, &[_]u21{
0x03CE,
0x03B9,
});
try instance.map.put(0x1FF6, &[_]u21{
0x03C9,
0x0342,
});
try instance.map.put(0x1FF7, &[_]u21{
0x03C9,
0x0342,
0x03B9,
});
try instance.map.put(0x1FF8, &[_]u21{
0x1F78,
});
try instance.map.put(0x1FF9, &[_]u21{
0x1F79,
});
try instance.map.put(0x1FFA, &[_]u21{
0x1F7C,
});
try instance.map.put(0x1FFB, &[_]u21{
0x1F7D,
});
try instance.map.put(0x1FFC, &[_]u21{
0x03C9,
0x03B9,
});
try instance.map.put(0x2126, &[_]u21{
0x03C9,
});
try instance.map.put(0x212A, &[_]u21{
0x006B,
});
try instance.map.put(0x212B, &[_]u21{
0x00E5,
});
try instance.map.put(0x2132, &[_]u21{
0x214E,
});
try instance.map.put(0x2160, &[_]u21{
0x2170,
});
try instance.map.put(0x2161, &[_]u21{
0x2171,
});
try instance.map.put(0x2162, &[_]u21{
0x2172,
});
try instance.map.put(0x2163, &[_]u21{
0x2173,
});
try instance.map.put(0x2164, &[_]u21{
0x2174,
});
try instance.map.put(0x2165, &[_]u21{
0x2175,
});
try instance.map.put(0x2166, &[_]u21{
0x2176,
});
try instance.map.put(0x2167, &[_]u21{
0x2177,
});
try instance.map.put(0x2168, &[_]u21{
0x2178,
});
try instance.map.put(0x2169, &[_]u21{
0x2179,
});
try instance.map.put(0x216A, &[_]u21{
0x217A,
});
try instance.map.put(0x216B, &[_]u21{
0x217B,
});
try instance.map.put(0x216C, &[_]u21{
0x217C,
});
try instance.map.put(0x216D, &[_]u21{
0x217D,
});
try instance.map.put(0x216E, &[_]u21{
0x217E,
});
try instance.map.put(0x216F, &[_]u21{
0x217F,
});
try instance.map.put(0x2183, &[_]u21{
0x2184,
});
try instance.map.put(0x24B6, &[_]u21{
0x24D0,
});
try instance.map.put(0x24B7, &[_]u21{
0x24D1,
});
try instance.map.put(0x24B8, &[_]u21{
0x24D2,
});
try instance.map.put(0x24B9, &[_]u21{
0x24D3,
});
try instance.map.put(0x24BA, &[_]u21{
0x24D4,
});
try instance.map.put(0x24BB, &[_]u21{
0x24D5,
});
try instance.map.put(0x24BC, &[_]u21{
0x24D6,
});
try instance.map.put(0x24BD, &[_]u21{
0x24D7,
});
try instance.map.put(0x24BE, &[_]u21{
0x24D8,
});
try instance.map.put(0x24BF, &[_]u21{
0x24D9,
});
try instance.map.put(0x24C0, &[_]u21{
0x24DA,
});
try instance.map.put(0x24C1, &[_]u21{
0x24DB,
});
try instance.map.put(0x24C2, &[_]u21{
0x24DC,
});
try instance.map.put(0x24C3, &[_]u21{
0x24DD,
});
try instance.map.put(0x24C4, &[_]u21{
0x24DE,
});
try instance.map.put(0x24C5, &[_]u21{
0x24DF,
});
try instance.map.put(0x24C6, &[_]u21{
0x24E0,
});
try instance.map.put(0x24C7, &[_]u21{
0x24E1,
});
try instance.map.put(0x24C8, &[_]u21{
0x24E2,
});
try instance.map.put(0x24C9, &[_]u21{
0x24E3,
});
try instance.map.put(0x24CA, &[_]u21{
0x24E4,
});
try instance.map.put(0x24CB, &[_]u21{
0x24E5,
});
try instance.map.put(0x24CC, &[_]u21{
0x24E6,
});
try instance.map.put(0x24CD, &[_]u21{
0x24E7,
});
try instance.map.put(0x24CE, &[_]u21{
0x24E8,
});
try instance.map.put(0x24CF, &[_]u21{
0x24E9,
});
try instance.map.put(0x2C00, &[_]u21{
0x2C30,
});
try instance.map.put(0x2C01, &[_]u21{
0x2C31,
});
try instance.map.put(0x2C02, &[_]u21{
0x2C32,
});
try instance.map.put(0x2C03, &[_]u21{
0x2C33,
});
try instance.map.put(0x2C04, &[_]u21{
0x2C34,
});
try instance.map.put(0x2C05, &[_]u21{
0x2C35,
});
try instance.map.put(0x2C06, &[_]u21{
0x2C36,
});
try instance.map.put(0x2C07, &[_]u21{
0x2C37,
});
try instance.map.put(0x2C08, &[_]u21{
0x2C38,
});
try instance.map.put(0x2C09, &[_]u21{
0x2C39,
});
try instance.map.put(0x2C0A, &[_]u21{
0x2C3A,
});
try instance.map.put(0x2C0B, &[_]u21{
0x2C3B,
});
try instance.map.put(0x2C0C, &[_]u21{
0x2C3C,
});
try instance.map.put(0x2C0D, &[_]u21{
0x2C3D,
});
try instance.map.put(0x2C0E, &[_]u21{
0x2C3E,
});
try instance.map.put(0x2C0F, &[_]u21{
0x2C3F,
});
try instance.map.put(0x2C10, &[_]u21{
0x2C40,
});
try instance.map.put(0x2C11, &[_]u21{
0x2C41,
});
try instance.map.put(0x2C12, &[_]u21{
0x2C42,
});
try instance.map.put(0x2C13, &[_]u21{
0x2C43,
});
try instance.map.put(0x2C14, &[_]u21{
0x2C44,
});
try instance.map.put(0x2C15, &[_]u21{
0x2C45,
});
try instance.map.put(0x2C16, &[_]u21{
0x2C46,
});
try instance.map.put(0x2C17, &[_]u21{
0x2C47,
});
try instance.map.put(0x2C18, &[_]u21{
0x2C48,
});
try instance.map.put(0x2C19, &[_]u21{
0x2C49,
});
try instance.map.put(0x2C1A, &[_]u21{
0x2C4A,
});
try instance.map.put(0x2C1B, &[_]u21{
0x2C4B,
});
try instance.map.put(0x2C1C, &[_]u21{
0x2C4C,
});
try instance.map.put(0x2C1D, &[_]u21{
0x2C4D,
});
try instance.map.put(0x2C1E, &[_]u21{
0x2C4E,
});
try instance.map.put(0x2C1F, &[_]u21{
0x2C4F,
});
try instance.map.put(0x2C20, &[_]u21{
0x2C50,
});
try instance.map.put(0x2C21, &[_]u21{
0x2C51,
});
try instance.map.put(0x2C22, &[_]u21{
0x2C52,
});
try instance.map.put(0x2C23, &[_]u21{
0x2C53,
});
try instance.map.put(0x2C24, &[_]u21{
0x2C54,
});
try instance.map.put(0x2C25, &[_]u21{
0x2C55,
});
try instance.map.put(0x2C26, &[_]u21{
0x2C56,
});
try instance.map.put(0x2C27, &[_]u21{
0x2C57,
});
try instance.map.put(0x2C28, &[_]u21{
0x2C58,
});
try instance.map.put(0x2C29, &[_]u21{
0x2C59,
});
try instance.map.put(0x2C2A, &[_]u21{
0x2C5A,
});
try instance.map.put(0x2C2B, &[_]u21{
0x2C5B,
});
try instance.map.put(0x2C2C, &[_]u21{
0x2C5C,
});
try instance.map.put(0x2C2D, &[_]u21{
0x2C5D,
});
try instance.map.put(0x2C2E, &[_]u21{
0x2C5E,
});
try instance.map.put(0x2C60, &[_]u21{
0x2C61,
});
try instance.map.put(0x2C62, &[_]u21{
0x026B,
});
try instance.map.put(0x2C63, &[_]u21{
0x1D7D,
});
try instance.map.put(0x2C64, &[_]u21{
0x027D,
});
try instance.map.put(0x2C67, &[_]u21{
0x2C68,
});
try instance.map.put(0x2C69, &[_]u21{
0x2C6A,
});
try instance.map.put(0x2C6B, &[_]u21{
0x2C6C,
});
try instance.map.put(0x2C6D, &[_]u21{
0x0251,
});
try instance.map.put(0x2C6E, &[_]u21{
0x0271,
});
try instance.map.put(0x2C6F, &[_]u21{
0x0250,
});
try instance.map.put(0x2C70, &[_]u21{
0x0252,
});
try instance.map.put(0x2C72, &[_]u21{
0x2C73,
});
try instance.map.put(0x2C75, &[_]u21{
0x2C76,
});
try instance.map.put(0x2C7E, &[_]u21{
0x023F,
});
try instance.map.put(0x2C7F, &[_]u21{
0x0240,
});
try instance.map.put(0x2C80, &[_]u21{
0x2C81,
});
try instance.map.put(0x2C82, &[_]u21{
0x2C83,
});
try instance.map.put(0x2C84, &[_]u21{
0x2C85,
});
try instance.map.put(0x2C86, &[_]u21{
0x2C87,
});
try instance.map.put(0x2C88, &[_]u21{
0x2C89,
});
try instance.map.put(0x2C8A, &[_]u21{
0x2C8B,
});
try instance.map.put(0x2C8C, &[_]u21{
0x2C8D,
});
try instance.map.put(0x2C8E, &[_]u21{
0x2C8F,
});
try instance.map.put(0x2C90, &[_]u21{
0x2C91,
});
try instance.map.put(0x2C92, &[_]u21{
0x2C93,
});
try instance.map.put(0x2C94, &[_]u21{
0x2C95,
});
try instance.map.put(0x2C96, &[_]u21{
0x2C97,
});
try instance.map.put(0x2C98, &[_]u21{
0x2C99,
});
try instance.map.put(0x2C9A, &[_]u21{
0x2C9B,
});
try instance.map.put(0x2C9C, &[_]u21{
0x2C9D,
});
try instance.map.put(0x2C9E, &[_]u21{
0x2C9F,
});
try instance.map.put(0x2CA0, &[_]u21{
0x2CA1,
});
try instance.map.put(0x2CA2, &[_]u21{
0x2CA3,
});
try instance.map.put(0x2CA4, &[_]u21{
0x2CA5,
});
try instance.map.put(0x2CA6, &[_]u21{
0x2CA7,
});
try instance.map.put(0x2CA8, &[_]u21{
0x2CA9,
});
try instance.map.put(0x2CAA, &[_]u21{
0x2CAB,
});
try instance.map.put(0x2CAC, &[_]u21{
0x2CAD,
});
try instance.map.put(0x2CAE, &[_]u21{
0x2CAF,
});
try instance.map.put(0x2CB0, &[_]u21{
0x2CB1,
});
try instance.map.put(0x2CB2, &[_]u21{
0x2CB3,
});
try instance.map.put(0x2CB4, &[_]u21{
0x2CB5,
});
try instance.map.put(0x2CB6, &[_]u21{
0x2CB7,
});
try instance.map.put(0x2CB8, &[_]u21{
0x2CB9,
});
try instance.map.put(0x2CBA, &[_]u21{
0x2CBB,
});
try instance.map.put(0x2CBC, &[_]u21{
0x2CBD,
});
try instance.map.put(0x2CBE, &[_]u21{
0x2CBF,
});
try instance.map.put(0x2CC0, &[_]u21{
0x2CC1,
});
try instance.map.put(0x2CC2, &[_]u21{
0x2CC3,
});
try instance.map.put(0x2CC4, &[_]u21{
0x2CC5,
});
try instance.map.put(0x2CC6, &[_]u21{
0x2CC7,
});
try instance.map.put(0x2CC8, &[_]u21{
0x2CC9,
});
try instance.map.put(0x2CCA, &[_]u21{
0x2CCB,
});
try instance.map.put(0x2CCC, &[_]u21{
0x2CCD,
});
try instance.map.put(0x2CCE, &[_]u21{
0x2CCF,
});
try instance.map.put(0x2CD0, &[_]u21{
0x2CD1,
});
try instance.map.put(0x2CD2, &[_]u21{
0x2CD3,
});
try instance.map.put(0x2CD4, &[_]u21{
0x2CD5,
});
try instance.map.put(0x2CD6, &[_]u21{
0x2CD7,
});
try instance.map.put(0x2CD8, &[_]u21{
0x2CD9,
});
try instance.map.put(0x2CDA, &[_]u21{
0x2CDB,
});
try instance.map.put(0x2CDC, &[_]u21{
0x2CDD,
});
try instance.map.put(0x2CDE, &[_]u21{
0x2CDF,
});
try instance.map.put(0x2CE0, &[_]u21{
0x2CE1,
});
try instance.map.put(0x2CE2, &[_]u21{
0x2CE3,
});
try instance.map.put(0x2CEB, &[_]u21{
0x2CEC,
});
try instance.map.put(0x2CED, &[_]u21{
0x2CEE,
});
try instance.map.put(0x2CF2, &[_]u21{
0x2CF3,
});
try instance.map.put(0xA640, &[_]u21{
0xA641,
});
try instance.map.put(0xA642, &[_]u21{
0xA643,
});
try instance.map.put(0xA644, &[_]u21{
0xA645,
});
try instance.map.put(0xA646, &[_]u21{
0xA647,
});
try instance.map.put(0xA648, &[_]u21{
0xA649,
});
try instance.map.put(0xA64A, &[_]u21{
0xA64B,
});
try instance.map.put(0xA64C, &[_]u21{
0xA64D,
});
try instance.map.put(0xA64E, &[_]u21{
0xA64F,
});
try instance.map.put(0xA650, &[_]u21{
0xA651,
});
try instance.map.put(0xA652, &[_]u21{
0xA653,
});
try instance.map.put(0xA654, &[_]u21{
0xA655,
});
try instance.map.put(0xA656, &[_]u21{
0xA657,
});
try instance.map.put(0xA658, &[_]u21{
0xA659,
});
try instance.map.put(0xA65A, &[_]u21{
0xA65B,
});
try instance.map.put(0xA65C, &[_]u21{
0xA65D,
});
try instance.map.put(0xA65E, &[_]u21{
0xA65F,
});
try instance.map.put(0xA660, &[_]u21{
0xA661,
});
try instance.map.put(0xA662, &[_]u21{
0xA663,
});
try instance.map.put(0xA664, &[_]u21{
0xA665,
});
try instance.map.put(0xA666, &[_]u21{
0xA667,
});
try instance.map.put(0xA668, &[_]u21{
0xA669,
});
try instance.map.put(0xA66A, &[_]u21{
0xA66B,
});
try instance.map.put(0xA66C, &[_]u21{
0xA66D,
});
try instance.map.put(0xA680, &[_]u21{
0xA681,
});
try instance.map.put(0xA682, &[_]u21{
0xA683,
});
try instance.map.put(0xA684, &[_]u21{
0xA685,
});
try instance.map.put(0xA686, &[_]u21{
0xA687,
});
try instance.map.put(0xA688, &[_]u21{
0xA689,
});
try instance.map.put(0xA68A, &[_]u21{
0xA68B,
});
try instance.map.put(0xA68C, &[_]u21{
0xA68D,
});
try instance.map.put(0xA68E, &[_]u21{
0xA68F,
});
try instance.map.put(0xA690, &[_]u21{
0xA691,
});
try instance.map.put(0xA692, &[_]u21{
0xA693,
});
try instance.map.put(0xA694, &[_]u21{
0xA695,
});
try instance.map.put(0xA696, &[_]u21{
0xA697,
});
try instance.map.put(0xA698, &[_]u21{
0xA699,
});
try instance.map.put(0xA69A, &[_]u21{
0xA69B,
});
try instance.map.put(0xA722, &[_]u21{
0xA723,
});
try instance.map.put(0xA724, &[_]u21{
0xA725,
});
try instance.map.put(0xA726, &[_]u21{
0xA727,
});
try instance.map.put(0xA728, &[_]u21{
0xA729,
});
try instance.map.put(0xA72A, &[_]u21{
0xA72B,
});
try instance.map.put(0xA72C, &[_]u21{
0xA72D,
});
try instance.map.put(0xA72E, &[_]u21{
0xA72F,
});
try instance.map.put(0xA732, &[_]u21{
0xA733,
});
try instance.map.put(0xA734, &[_]u21{
0xA735,
});
try instance.map.put(0xA736, &[_]u21{
0xA737,
});
try instance.map.put(0xA738, &[_]u21{
0xA739,
});
try instance.map.put(0xA73A, &[_]u21{
0xA73B,
});
try instance.map.put(0xA73C, &[_]u21{
0xA73D,
});
try instance.map.put(0xA73E, &[_]u21{
0xA73F,
});
try instance.map.put(0xA740, &[_]u21{
0xA741,
});
try instance.map.put(0xA742, &[_]u21{
0xA743,
});
try instance.map.put(0xA744, &[_]u21{
0xA745,
});
try instance.map.put(0xA746, &[_]u21{
0xA747,
});
try instance.map.put(0xA748, &[_]u21{
0xA749,
});
try instance.map.put(0xA74A, &[_]u21{
0xA74B,
});
try instance.map.put(0xA74C, &[_]u21{
0xA74D,
});
try instance.map.put(0xA74E, &[_]u21{
0xA74F,
});
try instance.map.put(0xA750, &[_]u21{
0xA751,
});
try instance.map.put(0xA752, &[_]u21{
0xA753,
});
try instance.map.put(0xA754, &[_]u21{
0xA755,
});
try instance.map.put(0xA756, &[_]u21{
0xA757,
});
try instance.map.put(0xA758, &[_]u21{
0xA759,
});
try instance.map.put(0xA75A, &[_]u21{
0xA75B,
});
try instance.map.put(0xA75C, &[_]u21{
0xA75D,
});
try instance.map.put(0xA75E, &[_]u21{
0xA75F,
});
try instance.map.put(0xA760, &[_]u21{
0xA761,
});
try instance.map.put(0xA762, &[_]u21{
0xA763,
});
try instance.map.put(0xA764, &[_]u21{
0xA765,
});
try instance.map.put(0xA766, &[_]u21{
0xA767,
});
try instance.map.put(0xA768, &[_]u21{
0xA769,
});
try instance.map.put(0xA76A, &[_]u21{
0xA76B,
});
try instance.map.put(0xA76C, &[_]u21{
0xA76D,
});
try instance.map.put(0xA76E, &[_]u21{
0xA76F,
});
try instance.map.put(0xA779, &[_]u21{
0xA77A,
});
try instance.map.put(0xA77B, &[_]u21{
0xA77C,
});
try instance.map.put(0xA77D, &[_]u21{
0x1D79,
});
try instance.map.put(0xA77E, &[_]u21{
0xA77F,
});
try instance.map.put(0xA780, &[_]u21{
0xA781,
});
try instance.map.put(0xA782, &[_]u21{
0xA783,
});
try instance.map.put(0xA784, &[_]u21{
0xA785,
});
try instance.map.put(0xA786, &[_]u21{
0xA787,
});
try instance.map.put(0xA78B, &[_]u21{
0xA78C,
});
try instance.map.put(0xA78D, &[_]u21{
0x0265,
});
try instance.map.put(0xA790, &[_]u21{
0xA791,
});
try instance.map.put(0xA792, &[_]u21{
0xA793,
});
try instance.map.put(0xA796, &[_]u21{
0xA797,
});
try instance.map.put(0xA798, &[_]u21{
0xA799,
});
try instance.map.put(0xA79A, &[_]u21{
0xA79B,
});
try instance.map.put(0xA79C, &[_]u21{
0xA79D,
});
try instance.map.put(0xA79E, &[_]u21{
0xA79F,
});
try instance.map.put(0xA7A0, &[_]u21{
0xA7A1,
});
try instance.map.put(0xA7A2, &[_]u21{
0xA7A3,
});
try instance.map.put(0xA7A4, &[_]u21{
0xA7A5,
});
try instance.map.put(0xA7A6, &[_]u21{
0xA7A7,
});
try instance.map.put(0xA7A8, &[_]u21{
0xA7A9,
});
try instance.map.put(0xA7AA, &[_]u21{
0x0266,
});
try instance.map.put(0xA7AB, &[_]u21{
0x025C,
});
try instance.map.put(0xA7AC, &[_]u21{
0x0261,
});
try instance.map.put(0xA7AD, &[_]u21{
0x026C,
});
try instance.map.put(0xA7AE, &[_]u21{
0x026A,
});
try instance.map.put(0xA7B0, &[_]u21{
0x029E,
});
try instance.map.put(0xA7B1, &[_]u21{
0x0287,
});
try instance.map.put(0xA7B2, &[_]u21{
0x029D,
});
try instance.map.put(0xA7B3, &[_]u21{
0xAB53,
});
try instance.map.put(0xA7B4, &[_]u21{
0xA7B5,
});
try instance.map.put(0xA7B6, &[_]u21{
0xA7B7,
});
try instance.map.put(0xA7B8, &[_]u21{
0xA7B9,
});
try instance.map.put(0xA7BA, &[_]u21{
0xA7BB,
});
try instance.map.put(0xA7BC, &[_]u21{
0xA7BD,
});
try instance.map.put(0xA7BE, &[_]u21{
0xA7BF,
});
try instance.map.put(0xA7C2, &[_]u21{
0xA7C3,
});
try instance.map.put(0xA7C4, &[_]u21{
0xA794,
});
try instance.map.put(0xA7C5, &[_]u21{
0x0282,
});
try instance.map.put(0xA7C6, &[_]u21{
0x1D8E,
});
try instance.map.put(0xA7C7, &[_]u21{
0xA7C8,
});
try instance.map.put(0xA7C9, &[_]u21{
0xA7CA,
});
try instance.map.put(0xA7F5, &[_]u21{
0xA7F6,
});
try instance.map.put(0xAB70, &[_]u21{
0x13A0,
});
try instance.map.put(0xAB71, &[_]u21{
0x13A1,
});
try instance.map.put(0xAB72, &[_]u21{
0x13A2,
});
try instance.map.put(0xAB73, &[_]u21{
0x13A3,
});
try instance.map.put(0xAB74, &[_]u21{
0x13A4,
});
try instance.map.put(0xAB75, &[_]u21{
0x13A5,
});
try instance.map.put(0xAB76, &[_]u21{
0x13A6,
});
try instance.map.put(0xAB77, &[_]u21{
0x13A7,
});
try instance.map.put(0xAB78, &[_]u21{
0x13A8,
});
try instance.map.put(0xAB79, &[_]u21{
0x13A9,
});
try instance.map.put(0xAB7A, &[_]u21{
0x13AA,
});
try instance.map.put(0xAB7B, &[_]u21{
0x13AB,
});
try instance.map.put(0xAB7C, &[_]u21{
0x13AC,
});
try instance.map.put(0xAB7D, &[_]u21{
0x13AD,
});
try instance.map.put(0xAB7E, &[_]u21{
0x13AE,
});
try instance.map.put(0xAB7F, &[_]u21{
0x13AF,
});
try instance.map.put(0xAB80, &[_]u21{
0x13B0,
});
try instance.map.put(0xAB81, &[_]u21{
0x13B1,
});
try instance.map.put(0xAB82, &[_]u21{
0x13B2,
});
try instance.map.put(0xAB83, &[_]u21{
0x13B3,
});
try instance.map.put(0xAB84, &[_]u21{
0x13B4,
});
try instance.map.put(0xAB85, &[_]u21{
0x13B5,
});
try instance.map.put(0xAB86, &[_]u21{
0x13B6,
});
try instance.map.put(0xAB87, &[_]u21{
0x13B7,
});
try instance.map.put(0xAB88, &[_]u21{
0x13B8,
});
try instance.map.put(0xAB89, &[_]u21{
0x13B9,
});
try instance.map.put(0xAB8A, &[_]u21{
0x13BA,
});
try instance.map.put(0xAB8B, &[_]u21{
0x13BB,
});
try instance.map.put(0xAB8C, &[_]u21{
0x13BC,
});
try instance.map.put(0xAB8D, &[_]u21{
0x13BD,
});
try instance.map.put(0xAB8E, &[_]u21{
0x13BE,
});
try instance.map.put(0xAB8F, &[_]u21{
0x13BF,
});
try instance.map.put(0xAB90, &[_]u21{
0x13C0,
});
try instance.map.put(0xAB91, &[_]u21{
0x13C1,
});
try instance.map.put(0xAB92, &[_]u21{
0x13C2,
});
try instance.map.put(0xAB93, &[_]u21{
0x13C3,
});
try instance.map.put(0xAB94, &[_]u21{
0x13C4,
});
try instance.map.put(0xAB95, &[_]u21{
0x13C5,
});
try instance.map.put(0xAB96, &[_]u21{
0x13C6,
});
try instance.map.put(0xAB97, &[_]u21{
0x13C7,
});
try instance.map.put(0xAB98, &[_]u21{
0x13C8,
});
try instance.map.put(0xAB99, &[_]u21{
0x13C9,
});
try instance.map.put(0xAB9A, &[_]u21{
0x13CA,
});
try instance.map.put(0xAB9B, &[_]u21{
0x13CB,
});
try instance.map.put(0xAB9C, &[_]u21{
0x13CC,
});
try instance.map.put(0xAB9D, &[_]u21{
0x13CD,
});
try instance.map.put(0xAB9E, &[_]u21{
0x13CE,
});
try instance.map.put(0xAB9F, &[_]u21{
0x13CF,
});
try instance.map.put(0xABA0, &[_]u21{
0x13D0,
});
try instance.map.put(0xABA1, &[_]u21{
0x13D1,
});
try instance.map.put(0xABA2, &[_]u21{
0x13D2,
});
try instance.map.put(0xABA3, &[_]u21{
0x13D3,
});
try instance.map.put(0xABA4, &[_]u21{
0x13D4,
});
try instance.map.put(0xABA5, &[_]u21{
0x13D5,
});
try instance.map.put(0xABA6, &[_]u21{
0x13D6,
});
try instance.map.put(0xABA7, &[_]u21{
0x13D7,
});
try instance.map.put(0xABA8, &[_]u21{
0x13D8,
});
try instance.map.put(0xABA9, &[_]u21{
0x13D9,
});
try instance.map.put(0xABAA, &[_]u21{
0x13DA,
});
try instance.map.put(0xABAB, &[_]u21{
0x13DB,
});
try instance.map.put(0xABAC, &[_]u21{
0x13DC,
});
try instance.map.put(0xABAD, &[_]u21{
0x13DD,
});
try instance.map.put(0xABAE, &[_]u21{
0x13DE,
});
try instance.map.put(0xABAF, &[_]u21{
0x13DF,
});
try instance.map.put(0xABB0, &[_]u21{
0x13E0,
});
try instance.map.put(0xABB1, &[_]u21{
0x13E1,
});
try instance.map.put(0xABB2, &[_]u21{
0x13E2,
});
try instance.map.put(0xABB3, &[_]u21{
0x13E3,
});
try instance.map.put(0xABB4, &[_]u21{
0x13E4,
});
try instance.map.put(0xABB5, &[_]u21{
0x13E5,
});
try instance.map.put(0xABB6, &[_]u21{
0x13E6,
});
try instance.map.put(0xABB7, &[_]u21{
0x13E7,
});
try instance.map.put(0xABB8, &[_]u21{
0x13E8,
});
try instance.map.put(0xABB9, &[_]u21{
0x13E9,
});
try instance.map.put(0xABBA, &[_]u21{
0x13EA,
});
try instance.map.put(0xABBB, &[_]u21{
0x13EB,
});
try instance.map.put(0xABBC, &[_]u21{
0x13EC,
});
try instance.map.put(0xABBD, &[_]u21{
0x13ED,
});
try instance.map.put(0xABBE, &[_]u21{
0x13EE,
});
try instance.map.put(0xABBF, &[_]u21{
0x13EF,
});
try instance.map.put(0xFB00, &[_]u21{
0x0066,
0x0066,
});
try instance.map.put(0xFB01, &[_]u21{
0x0066,
0x0069,
});
try instance.map.put(0xFB02, &[_]u21{
0x0066,
0x006C,
});
try instance.map.put(0xFB03, &[_]u21{
0x0066,
0x0066,
0x0069,
});
try instance.map.put(0xFB04, &[_]u21{
0x0066,
0x0066,
0x006C,
});
try instance.map.put(0xFB05, &[_]u21{
0x0073,
0x0074,
});
try instance.map.put(0xFB06, &[_]u21{
0x0073,
0x0074,
});
try instance.map.put(0xFB13, &[_]u21{
0x0574,
0x0576,
});
try instance.map.put(0xFB14, &[_]u21{
0x0574,
0x0565,
});
try instance.map.put(0xFB15, &[_]u21{
0x0574,
0x056B,
});
try instance.map.put(0xFB16, &[_]u21{
0x057E,
0x0576,
});
try instance.map.put(0xFB17, &[_]u21{
0x0574,
0x056D,
});
try instance.map.put(0xFF21, &[_]u21{
0xFF41,
});
try instance.map.put(0xFF22, &[_]u21{
0xFF42,
});
try instance.map.put(0xFF23, &[_]u21{
0xFF43,
});
try instance.map.put(0xFF24, &[_]u21{
0xFF44,
});
try instance.map.put(0xFF25, &[_]u21{
0xFF45,
});
try instance.map.put(0xFF26, &[_]u21{
0xFF46,
});
try instance.map.put(0xFF27, &[_]u21{
0xFF47,
});
try instance.map.put(0xFF28, &[_]u21{
0xFF48,
});
try instance.map.put(0xFF29, &[_]u21{
0xFF49,
});
try instance.map.put(0xFF2A, &[_]u21{
0xFF4A,
});
try instance.map.put(0xFF2B, &[_]u21{
0xFF4B,
});
try instance.map.put(0xFF2C, &[_]u21{
0xFF4C,
});
try instance.map.put(0xFF2D, &[_]u21{
0xFF4D,
});
try instance.map.put(0xFF2E, &[_]u21{
0xFF4E,
});
try instance.map.put(0xFF2F, &[_]u21{
0xFF4F,
});
try instance.map.put(0xFF30, &[_]u21{
0xFF50,
});
try instance.map.put(0xFF31, &[_]u21{
0xFF51,
});
try instance.map.put(0xFF32, &[_]u21{
0xFF52,
});
try instance.map.put(0xFF33, &[_]u21{
0xFF53,
});
try instance.map.put(0xFF34, &[_]u21{
0xFF54,
});
try instance.map.put(0xFF35, &[_]u21{
0xFF55,
});
try instance.map.put(0xFF36, &[_]u21{
0xFF56,
});
try instance.map.put(0xFF37, &[_]u21{
0xFF57,
});
try instance.map.put(0xFF38, &[_]u21{
0xFF58,
});
try instance.map.put(0xFF39, &[_]u21{
0xFF59,
});
try instance.map.put(0xFF3A, &[_]u21{
0xFF5A,
});
try instance.map.put(0x10400, &[_]u21{
0x10428,
});
try instance.map.put(0x10401, &[_]u21{
0x10429,
});
try instance.map.put(0x10402, &[_]u21{
0x1042A,
});
try instance.map.put(0x10403, &[_]u21{
0x1042B,
});
try instance.map.put(0x10404, &[_]u21{
0x1042C,
});
try instance.map.put(0x10405, &[_]u21{
0x1042D,
});
try instance.map.put(0x10406, &[_]u21{
0x1042E,
});
try instance.map.put(0x10407, &[_]u21{
0x1042F,
});
try instance.map.put(0x10408, &[_]u21{
0x10430,
});
try instance.map.put(0x10409, &[_]u21{
0x10431,
});
try instance.map.put(0x1040A, &[_]u21{
0x10432,
});
try instance.map.put(0x1040B, &[_]u21{
0x10433,
});
try instance.map.put(0x1040C, &[_]u21{
0x10434,
});
try instance.map.put(0x1040D, &[_]u21{
0x10435,
});
try instance.map.put(0x1040E, &[_]u21{
0x10436,
});
try instance.map.put(0x1040F, &[_]u21{
0x10437,
});
try instance.map.put(0x10410, &[_]u21{
0x10438,
});
try instance.map.put(0x10411, &[_]u21{
0x10439,
});
try instance.map.put(0x10412, &[_]u21{
0x1043A,
});
try instance.map.put(0x10413, &[_]u21{
0x1043B,
});
try instance.map.put(0x10414, &[_]u21{
0x1043C,
});
try instance.map.put(0x10415, &[_]u21{
0x1043D,
});
try instance.map.put(0x10416, &[_]u21{
0x1043E,
});
try instance.map.put(0x10417, &[_]u21{
0x1043F,
});
try instance.map.put(0x10418, &[_]u21{
0x10440,
});
try instance.map.put(0x10419, &[_]u21{
0x10441,
});
try instance.map.put(0x1041A, &[_]u21{
0x10442,
});
try instance.map.put(0x1041B, &[_]u21{
0x10443,
});
try instance.map.put(0x1041C, &[_]u21{
0x10444,
});
try instance.map.put(0x1041D, &[_]u21{
0x10445,
});
try instance.map.put(0x1041E, &[_]u21{
0x10446,
});
try instance.map.put(0x1041F, &[_]u21{
0x10447,
});
try instance.map.put(0x10420, &[_]u21{
0x10448,
});
try instance.map.put(0x10421, &[_]u21{
0x10449,
});
try instance.map.put(0x10422, &[_]u21{
0x1044A,
});
try instance.map.put(0x10423, &[_]u21{
0x1044B,
});
try instance.map.put(0x10424, &[_]u21{
0x1044C,
});
try instance.map.put(0x10425, &[_]u21{
0x1044D,
});
try instance.map.put(0x10426, &[_]u21{
0x1044E,
});
try instance.map.put(0x10427, &[_]u21{
0x1044F,
});
try instance.map.put(0x104B0, &[_]u21{
0x104D8,
});
try instance.map.put(0x104B1, &[_]u21{
0x104D9,
});
try instance.map.put(0x104B2, &[_]u21{
0x104DA,
});
try instance.map.put(0x104B3, &[_]u21{
0x104DB,
});
try instance.map.put(0x104B4, &[_]u21{
0x104DC,
});
try instance.map.put(0x104B5, &[_]u21{
0x104DD,
});
try instance.map.put(0x104B6, &[_]u21{
0x104DE,
});
try instance.map.put(0x104B7, &[_]u21{
0x104DF,
});
try instance.map.put(0x104B8, &[_]u21{
0x104E0,
});
try instance.map.put(0x104B9, &[_]u21{
0x104E1,
});
try instance.map.put(0x104BA, &[_]u21{
0x104E2,
});
try instance.map.put(0x104BB, &[_]u21{
0x104E3,
});
try instance.map.put(0x104BC, &[_]u21{
0x104E4,
});
try instance.map.put(0x104BD, &[_]u21{
0x104E5,
});
try instance.map.put(0x104BE, &[_]u21{
0x104E6,
});
try instance.map.put(0x104BF, &[_]u21{
0x104E7,
});
try instance.map.put(0x104C0, &[_]u21{
0x104E8,
});
try instance.map.put(0x104C1, &[_]u21{
0x104E9,
});
try instance.map.put(0x104C2, &[_]u21{
0x104EA,
});
try instance.map.put(0x104C3, &[_]u21{
0x104EB,
});
try instance.map.put(0x104C4, &[_]u21{
0x104EC,
});
try instance.map.put(0x104C5, &[_]u21{
0x104ED,
});
try instance.map.put(0x104C6, &[_]u21{
0x104EE,
});
try instance.map.put(0x104C7, &[_]u21{
0x104EF,
});
try instance.map.put(0x104C8, &[_]u21{
0x104F0,
});
try instance.map.put(0x104C9, &[_]u21{
0x104F1,
});
try instance.map.put(0x104CA, &[_]u21{
0x104F2,
});
try instance.map.put(0x104CB, &[_]u21{
0x104F3,
});
try instance.map.put(0x104CC, &[_]u21{
0x104F4,
});
try instance.map.put(0x104CD, &[_]u21{
0x104F5,
});
try instance.map.put(0x104CE, &[_]u21{
0x104F6,
});
try instance.map.put(0x104CF, &[_]u21{
0x104F7,
});
try instance.map.put(0x104D0, &[_]u21{
0x104F8,
});
try instance.map.put(0x104D1, &[_]u21{
0x104F9,
});
try instance.map.put(0x104D2, &[_]u21{
0x104FA,
});
try instance.map.put(0x104D3, &[_]u21{
0x104FB,
});
try instance.map.put(0x10C80, &[_]u21{
0x10CC0,
});
try instance.map.put(0x10C81, &[_]u21{
0x10CC1,
});
try instance.map.put(0x10C82, &[_]u21{
0x10CC2,
});
try instance.map.put(0x10C83, &[_]u21{
0x10CC3,
});
try instance.map.put(0x10C84, &[_]u21{
0x10CC4,
});
try instance.map.put(0x10C85, &[_]u21{
0x10CC5,
});
try instance.map.put(0x10C86, &[_]u21{
0x10CC6,
});
try instance.map.put(0x10C87, &[_]u21{
0x10CC7,
});
try instance.map.put(0x10C88, &[_]u21{
0x10CC8,
});
try instance.map.put(0x10C89, &[_]u21{
0x10CC9,
});
try instance.map.put(0x10C8A, &[_]u21{
0x10CCA,
});
try instance.map.put(0x10C8B, &[_]u21{
0x10CCB,
});
try instance.map.put(0x10C8C, &[_]u21{
0x10CCC,
});
try instance.map.put(0x10C8D, &[_]u21{
0x10CCD,
});
try instance.map.put(0x10C8E, &[_]u21{
0x10CCE,
});
try instance.map.put(0x10C8F, &[_]u21{
0x10CCF,
});
try instance.map.put(0x10C90, &[_]u21{
0x10CD0,
});
try instance.map.put(0x10C91, &[_]u21{
0x10CD1,
});
try instance.map.put(0x10C92, &[_]u21{
0x10CD2,
});
try instance.map.put(0x10C93, &[_]u21{
0x10CD3,
});
try instance.map.put(0x10C94, &[_]u21{
0x10CD4,
});
try instance.map.put(0x10C95, &[_]u21{
0x10CD5,
});
try instance.map.put(0x10C96, &[_]u21{
0x10CD6,
});
try instance.map.put(0x10C97, &[_]u21{
0x10CD7,
});
try instance.map.put(0x10C98, &[_]u21{
0x10CD8,
});
try instance.map.put(0x10C99, &[_]u21{
0x10CD9,
});
try instance.map.put(0x10C9A, &[_]u21{
0x10CDA,
});
try instance.map.put(0x10C9B, &[_]u21{
0x10CDB,
});
try instance.map.put(0x10C9C, &[_]u21{
0x10CDC,
});
try instance.map.put(0x10C9D, &[_]u21{
0x10CDD,
});
try instance.map.put(0x10C9E, &[_]u21{
0x10CDE,
});
try instance.map.put(0x10C9F, &[_]u21{
0x10CDF,
});
try instance.map.put(0x10CA0, &[_]u21{
0x10CE0,
});
try instance.map.put(0x10CA1, &[_]u21{
0x10CE1,
});
try instance.map.put(0x10CA2, &[_]u21{
0x10CE2,
});
try instance.map.put(0x10CA3, &[_]u21{
0x10CE3,
});
try instance.map.put(0x10CA4, &[_]u21{
0x10CE4,
});
try instance.map.put(0x10CA5, &[_]u21{
0x10CE5,
});
try instance.map.put(0x10CA6, &[_]u21{
0x10CE6,
});
try instance.map.put(0x10CA7, &[_]u21{
0x10CE7,
});
try instance.map.put(0x10CA8, &[_]u21{
0x10CE8,
});
try instance.map.put(0x10CA9, &[_]u21{
0x10CE9,
});
try instance.map.put(0x10CAA, &[_]u21{
0x10CEA,
});
try instance.map.put(0x10CAB, &[_]u21{
0x10CEB,
});
try instance.map.put(0x10CAC, &[_]u21{
0x10CEC,
});
try instance.map.put(0x10CAD, &[_]u21{
0x10CED,
});
try instance.map.put(0x10CAE, &[_]u21{
0x10CEE,
});
try instance.map.put(0x10CAF, &[_]u21{
0x10CEF,
});
try instance.map.put(0x10CB0, &[_]u21{
0x10CF0,
});
try instance.map.put(0x10CB1, &[_]u21{
0x10CF1,
});
try instance.map.put(0x10CB2, &[_]u21{
0x10CF2,
});
try instance.map.put(0x118A0, &[_]u21{
0x118C0,
});
try instance.map.put(0x118A1, &[_]u21{
0x118C1,
});
try instance.map.put(0x118A2, &[_]u21{
0x118C2,
});
try instance.map.put(0x118A3, &[_]u21{
0x118C3,
});
try instance.map.put(0x118A4, &[_]u21{
0x118C4,
});
try instance.map.put(0x118A5, &[_]u21{
0x118C5,
});
try instance.map.put(0x118A6, &[_]u21{
0x118C6,
});
try instance.map.put(0x118A7, &[_]u21{
0x118C7,
});
try instance.map.put(0x118A8, &[_]u21{
0x118C8,
});
try instance.map.put(0x118A9, &[_]u21{
0x118C9,
});
try instance.map.put(0x118AA, &[_]u21{
0x118CA,
});
try instance.map.put(0x118AB, &[_]u21{
0x118CB,
});
try instance.map.put(0x118AC, &[_]u21{
0x118CC,
});
try instance.map.put(0x118AD, &[_]u21{
0x118CD,
});
try instance.map.put(0x118AE, &[_]u21{
0x118CE,
});
try instance.map.put(0x118AF, &[_]u21{
0x118CF,
});
try instance.map.put(0x118B0, &[_]u21{
0x118D0,
});
try instance.map.put(0x118B1, &[_]u21{
0x118D1,
});
try instance.map.put(0x118B2, &[_]u21{
0x118D2,
});
try instance.map.put(0x118B3, &[_]u21{
0x118D3,
});
try instance.map.put(0x118B4, &[_]u21{
0x118D4,
});
try instance.map.put(0x118B5, &[_]u21{
0x118D5,
});
try instance.map.put(0x118B6, &[_]u21{
0x118D6,
});
try instance.map.put(0x118B7, &[_]u21{
0x118D7,
});
try instance.map.put(0x118B8, &[_]u21{
0x118D8,
});
try instance.map.put(0x118B9, &[_]u21{
0x118D9,
});
try instance.map.put(0x118BA, &[_]u21{
0x118DA,
});
try instance.map.put(0x118BB, &[_]u21{
0x118DB,
});
try instance.map.put(0x118BC, &[_]u21{
0x118DC,
});
try instance.map.put(0x118BD, &[_]u21{
0x118DD,
});
try instance.map.put(0x118BE, &[_]u21{
0x118DE,
});
try instance.map.put(0x118BF, &[_]u21{
0x118DF,
});
try instance.map.put(0x16E40, &[_]u21{
0x16E60,
});
try instance.map.put(0x16E41, &[_]u21{
0x16E61,
});
try instance.map.put(0x16E42, &[_]u21{
0x16E62,
});
try instance.map.put(0x16E43, &[_]u21{
0x16E63,
});
try instance.map.put(0x16E44, &[_]u21{
0x16E64,
});
try instance.map.put(0x16E45, &[_]u21{
0x16E65,
});
try instance.map.put(0x16E46, &[_]u21{
0x16E66,
});
try instance.map.put(0x16E47, &[_]u21{
0x16E67,
});
try instance.map.put(0x16E48, &[_]u21{
0x16E68,
});
try instance.map.put(0x16E49, &[_]u21{
0x16E69,
});
try instance.map.put(0x16E4A, &[_]u21{
0x16E6A,
});
try instance.map.put(0x16E4B, &[_]u21{
0x16E6B,
});
try instance.map.put(0x16E4C, &[_]u21{
0x16E6C,
});
try instance.map.put(0x16E4D, &[_]u21{
0x16E6D,
});
try instance.map.put(0x16E4E, &[_]u21{
0x16E6E,
});
try instance.map.put(0x16E4F, &[_]u21{
0x16E6F,
});
try instance.map.put(0x16E50, &[_]u21{
0x16E70,
});
try instance.map.put(0x16E51, &[_]u21{
0x16E71,
});
try instance.map.put(0x16E52, &[_]u21{
0x16E72,
});
try instance.map.put(0x16E53, &[_]u21{
0x16E73,
});
try instance.map.put(0x16E54, &[_]u21{
0x16E74,
});
try instance.map.put(0x16E55, &[_]u21{
0x16E75,
});
try instance.map.put(0x16E56, &[_]u21{
0x16E76,
});
try instance.map.put(0x16E57, &[_]u21{
0x16E77,
});
try instance.map.put(0x16E58, &[_]u21{
0x16E78,
});
try instance.map.put(0x16E59, &[_]u21{
0x16E79,
});
try instance.map.put(0x16E5A, &[_]u21{
0x16E7A,
});
try instance.map.put(0x16E5B, &[_]u21{
0x16E7B,
});
try instance.map.put(0x16E5C, &[_]u21{
0x16E7C,
});
try instance.map.put(0x16E5D, &[_]u21{
0x16E7D,
});
try instance.map.put(0x16E5E, &[_]u21{
0x16E7E,
});
try instance.map.put(0x16E5F, &[_]u21{
0x16E7F,
});
try instance.map.put(0x1E900, &[_]u21{
0x1E922,
});
try instance.map.put(0x1E901, &[_]u21{
0x1E923,
});
try instance.map.put(0x1E902, &[_]u21{
0x1E924,
});
try instance.map.put(0x1E903, &[_]u21{
0x1E925,
});
try instance.map.put(0x1E904, &[_]u21{
0x1E926,
});
try instance.map.put(0x1E905, &[_]u21{
0x1E927,
});
try instance.map.put(0x1E906, &[_]u21{
0x1E928,
});
try instance.map.put(0x1E907, &[_]u21{
0x1E929,
});
try instance.map.put(0x1E908, &[_]u21{
0x1E92A,
});
try instance.map.put(0x1E909, &[_]u21{
0x1E92B,
});
try instance.map.put(0x1E90A, &[_]u21{
0x1E92C,
});
try instance.map.put(0x1E90B, &[_]u21{
0x1E92D,
});
try instance.map.put(0x1E90C, &[_]u21{
0x1E92E,
});
try instance.map.put(0x1E90D, &[_]u21{
0x1E92F,
});
try instance.map.put(0x1E90E, &[_]u21{
0x1E930,
});
try instance.map.put(0x1E90F, &[_]u21{
0x1E931,
});
try instance.map.put(0x1E910, &[_]u21{
0x1E932,
});
try instance.map.put(0x1E911, &[_]u21{
0x1E933,
});
try instance.map.put(0x1E912, &[_]u21{
0x1E934,
});
try instance.map.put(0x1E913, &[_]u21{
0x1E935,
});
try instance.map.put(0x1E914, &[_]u21{
0x1E936,
});
try instance.map.put(0x1E915, &[_]u21{
0x1E937,
});
try instance.map.put(0x1E916, &[_]u21{
0x1E938,
});
try instance.map.put(0x1E917, &[_]u21{
0x1E939,
});
try instance.map.put(0x1E918, &[_]u21{
0x1E93A,
});
try instance.map.put(0x1E919, &[_]u21{
0x1E93B,
});
try instance.map.put(0x1E91A, &[_]u21{
0x1E93C,
});
try instance.map.put(0x1E91B, &[_]u21{
0x1E93D,
});
try instance.map.put(0x1E91C, &[_]u21{
0x1E93E,
});
try instance.map.put(0x1E91D, &[_]u21{
0x1E93F,
});
try instance.map.put(0x1E91E, &[_]u21{
0x1E940,
});
try instance.map.put(0x1E91F, &[_]u21{
0x1E941,
});
try instance.map.put(0x1E920, &[_]u21{
0x1E942,
});
try instance.map.put(0x1E921, &[_]u21{
0x1E943,
});
return instance;
}
const Self = @This();
pub fn deinit(self: *Self) void {
self.map.deinit();
}
/// CaseFold can be a simple, one code point value or a sequence of code points in the full case fold scenario.
pub const CaseFold = union(enum) {
simple: u21,
full: []const u21,
};
/// toCaseFold will convert a code point into its case folded equivalent. Note that this can result
/// in a mapping to more than one code point, known as the full case fold.
pub fn toCaseFold(self: Self, cp: u21) CaseFold {
if (self.map.get(cp)) |seq| {
if (seq.len == 1) {
return .{ .simple = seq[0] };
} else {
return .{ .full = seq };
}
} else {
return .{ .simple = cp };
}
}
/// caseFoldStr will caseFold the code points in str, producing a slice of u8 with the new bytes.
/// Caller must free returned bytes.
pub fn caseFoldStr(self: *Self, allocator: *mem.Allocator, str: []const u8) ![]u8 {
var result = std.ArrayList(u8).init(allocator);
defer result.deinit();
var code_points = std.ArrayList(u21).init(self.allocator);
defer code_points.deinit();
// Gather decomposed code points.
var iter = (try unicode.Utf8View.init(str)).iterator();
while (iter.nextCodepoint()) |cp| {
const cf = self.toCaseFold(cp);
switch (cf) {
.simple => |scp| try code_points.append(scp),
.full => |seq| try code_points.appendSlice(seq),
}
}
// Encode as UTF-8 code units.
var buf: [4]u8 = undefined;
for (code_points.items) |dcp| {
const len = try unicode.utf8Encode(dcp, &buf);
try result.appendSlice(buf[0..len]);
}
return result.toOwnedSlice();
} | src/components/autogen/CaseFolding/CaseFoldMap.zig |
const std = @import("std");
const fs = std.fs;
const io = std.io;
const math = std.math;
const mem = std.mem;
const net = std.net;
const os = std.os;
const rand = std.rand;
const time = std.time;
const assert = std.debug.assert;
const expect = std.testing.expect;
const avl = @import("avl.zig");
const config = @import("config.zig");
const timestamp_str_width = "[18446744073709551.615]".len;
/// Convert a specified timestamp to a human-readable format.
fn formatTimeStamp(output: *[timestamp_str_width]u8, milliseconds: u64) void {
var rem = milliseconds;
var i = timestamp_str_width;
while (i > 0) : (i -= 1) {
if (i == timestamp_str_width) {
output[i - 1] = ']';
} else if (i == timestamp_str_width - 4) {
output[i - 1] = '.';
} else if (i == 1) {
output[i - 1] = '[';
} else if (rem == 0) {
if (i > timestamp_str_width - 6) {
output[i - 1] = '0';
} else {
output[i - 1] = ' ';
}
} else {
output[i - 1] = '0' + @intCast(u8, rem % 10);
rem /= 10;
}
}
}
test "format timestamp" {
var buffer: [timestamp_str_width]u8 = undefined;
formatTimeStamp(&buffer, 0);
expect(mem.eql(u8, buffer[0..], "[ 0.000]"));
formatTimeStamp(&buffer, 1);
expect(mem.eql(u8, buffer[0..], "[ 0.001]"));
formatTimeStamp(&buffer, 100);
expect(mem.eql(u8, buffer[0..], "[ 0.100]"));
formatTimeStamp(&buffer, 1000);
expect(mem.eql(u8, buffer[0..], "[ 1.000]"));
formatTimeStamp(&buffer, 10000);
expect(mem.eql(u8, buffer[0..], "[ 10.000]"));
formatTimeStamp(&buffer, 1234567890);
expect(mem.eql(u8, buffer[0..], "[ 1234567.890]"));
formatTimeStamp(&buffer, 18446744073709551615);
expect(mem.eql(u8, buffer[0..], "[18446744073709551.615]"));
}
/// Format and print an info message on the standard output.
fn info(comptime fmt: []const u8, args: anytype) void {
var timestamp: [timestamp_str_width]u8 = undefined;
formatTimeStamp(×tamp, @intCast(u64, time.milliTimestamp()));
const writer = io.getStdOut().writer();
writer.print("{} " ++ fmt, .{timestamp} ++ args) catch return;
}
/// Format and print a warning message on the standard error output.
fn warn(comptime fmt: []const u8, args: anytype) void {
var timestamp: [timestamp_str_width]u8 = undefined;
formatTimeStamp(×tamp, @intCast(u64, time.milliTimestamp()));
const writer = io.getStdErr().writer();
writer.print("\x1b[31m{} " ++ fmt ++ "\x1b[0m", .{timestamp} ++ args) catch return;
}
/// Thin wrapper for a character slice to output non-printable characters as escaped values with
/// std.fmt.
const EscapeFormatter = struct {
/// Managed slice.
_slice: []const u8,
/// Construct an EscapeFormatter.
fn init(slice: []const u8) EscapeFormatter {
return EscapeFormatter{ ._slice = slice };
}
/// Return the managed slice.
fn getSlice(self: *const EscapeFormatter) []const u8 {
return self._slice;
}
/// Format and output the slice.
pub fn format(
self: EscapeFormatter,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
out_stream: anytype,
) !void {
if (fmt.len > 0) {
@compileError("Unknown format character: '" ++ fmt ++ "'");
}
for (self._slice) |char| {
if (char == '\\') {
try out_stream.writeAll("\\\\");
} else if (char == '\'') {
try out_stream.writeAll("\\'");
} else if (char >= ' ' and char <= '~') {
try out_stream.writeAll(&[_]u8{char});
} else {
try out_stream.writeAll("\\x");
try out_stream.writeAll(&[_]u8{'0' + (char / 10)});
try out_stream.writeAll(&[_]u8{'0' + (char % 10)});
}
}
}
};
/// Alias for EscapeFormatter.init().
fn E(slice: []const u8) EscapeFormatter {
return EscapeFormatter.init(slice);
}
/// Conditional variant of EscapeFormatter.
const ConditionalEscapeFormatter = struct {
/// Wrapped EscapeFormatter.
_escape: EscapeFormatter,
/// Pointer to an outside flag that controls whether the slice should be escaped during the
/// format() call or not.
_cond: *bool,
/// Construct a ConditionalEscapeFormatter.
fn init(slice: []const u8, cond: *bool) ConditionalEscapeFormatter {
return ConditionalEscapeFormatter{
._escape = EscapeFormatter.init(slice),
._cond = cond,
};
}
/// Format and output the slice.
pub fn format(
self: ConditionalEscapeFormatter,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
out_stream: anytype,
) !void {
if (fmt.len > 0) {
@compileError("Unknown format character: '" ++ fmt ++ "'");
}
if (self._cond.*) {
try self._escape.format(fmt, options, out_stream);
} else {
try out_stream.writeAll(self._escape.getSlice());
}
}
};
/// Alias for ConditionalEscapeFormatter.init().
fn CE(slice: []const u8, cond: *bool) ConditionalEscapeFormatter {
return ConditionalEscapeFormatter.init(slice, cond);
}
/// Lexical analyzer for IRC messages and list parameters.
const Lexer = struct {
/// Input string.
_string: []const u8,
/// Current position in the input string.
_pos: usize,
/// Construct a Lexer.
fn init(string: []const u8) Lexer {
return Lexer{
._string = string,
._pos = 0,
};
}
/// Return the current position in the input string.
fn getCurPos(self: *const Lexer) usize {
return self._pos;
}
/// Return the current character.
fn getCurChar(self: *const Lexer) u8 {
if (self._pos < self._string.len) {
return self._string[self._pos];
}
return 0;
}
/// Skip to a next character in the string.
fn nextChar(self: *Lexer) void {
if (self._pos < self._string.len) {
self._pos += 1;
}
}
/// Read all space characters at the current position if a separator is valid at this point.
fn _processSpace(self: *Lexer) void {
if (self._pos == 0) {
return;
}
while (self.getCurChar() == ' ') {
self.nextChar();
}
}
/// Read one word starting at exactly the current position.
fn _readWordNow(self: *Lexer) ?[]const u8 {
const begin = self._pos;
var end = begin;
while (self.getCurChar() != '\x00' and self.getCurChar() != ' ') : (end += 1) {
self.nextChar();
}
return if (begin != end) self._string[begin..end] else null;
}
/// Read a next word from the string.
fn readWord(self: *Lexer) ?[]const u8 {
self._processSpace();
return self._readWordNow();
}
/// Read a next parameter from the string.
fn readParam(self: *Lexer) ?[]const u8 {
self._processSpace();
if (self.getCurChar() == ':') {
const begin = self._pos + 1;
const end = self._string.len;
self._pos = end;
// The last parameter after ':' is always valid and can be empty.
return self._string[begin..end];
}
return self._readWordNow();
}
/// Read a next list item from the string. Individual items are separated by commas, the string
/// should not contain any spaces. This function is used to parse list items from parameters.
fn readListItem(self: *Lexer) ?[]const u8 {
if (self._pos != 0 and self.getCurChar() == ',') {
self.nextChar();
}
const begin = self._pos;
var end = begin;
while (self.getCurChar() != '\x00' and self.getCurChar() != ',') : (end += 1) {
self.nextChar();
}
return if (begin != end) self._string[begin..end] else null;
}
/// Query whether all characters were read.
fn isAtEnd(self: *const Lexer) bool {
return self._pos == self._string.len;
}
/// Read a remainder of the string.
fn readRest(self: *Lexer) ?[]const u8 {
const begin = self._pos;
const end = self._string.len;
self._pos = end;
return if (begin != end) self._string[begin..end] else null;
}
};
/// User on the server. This is the base type for a remote Client or an artificial LocalBot.
const User = struct {
const Type = enum {
Client,
LocalBot,
};
/// User type.
_type: Type,
/// Parent server.
_server: *Server,
/// Unique nick name (owned).
_nickname: ?[]u8,
/// Username (owned).
_username: ?[]u8,
/// Realname (owned).
_realname: ?[]u8,
/// Joined channels.
_channels: ChannelSet,
/// Construct a new User.
fn init(type_: Type, server: *Server) User {
const allocator = server.getAllocator();
return User{
._type = type_,
._server = server,
._nickname = null,
._username = null,
._realname = null,
._channels = ChannelSet.init(allocator),
};
}
/// Quit the server and destroy the user.
fn deinit(self: *User) void {
// Quit all channels.
self._quit("Client quit");
assert(self._channels.count() == 0);
self._channels.deinit();
const allocator = self._server.getAllocator();
if (self._nickname) |nickname| {
allocator.free(nickname);
}
if (self._username) |username| {
allocator.free(username);
}
if (self._realname) |realname| {
allocator.free(realname);
}
}
/// Quit the server. The operation leaves all joined channels and informs their members about
/// the quit.
fn _quit(self: *User, quit_message: []const u8) void {
// Send a QUIT message to users in all joined channels.
if (self._channels.count() == 0) {
return;
}
var ec: bool = undefined;
const users = self._server.getUsers();
var user_iter = users.iterator();
while (user_iter.next()) |user_node| {
const user = user_node.value();
// Skip if this is the current user.
if (user == self) {
continue;
}
// Check if the user is in any joined channel.
var found = false;
var channel_iter = self._channels.iterator();
while (channel_iter.next()) |channel_node| {
const channel = channel_node.key();
const members = channel.getMembers();
const member_iter = members.find(user);
if (member_iter.valid()) {
found = true;
break;
}
}
if (!found) {
continue;
}
// Inform the user about the quit.
user.sendMessage(&ec, "{} QUIT :{}", .{ CE(self._nickname.?, &ec), quit_message });
}
// Quit all joined channels.
var channel_iter = self._channels.iterator();
while (channel_iter.next()) |channel_node| {
const channel = channel_node.key();
channel.quit(self);
}
self._channels.clear();
}
/// Obtain the current nickname or "*" if the name has not been set yet.
fn getNickName(self: *const User) []const u8 {
return if (self._nickname) |nickname| nickname else "*";
}
/// Return whether the user has its nickname set.
fn hasNickName(self: *const User) bool {
return self._nickname != null;
}
/// Set a new nickname. Note that it is a caller's responsibility to make sure that this name
/// does not duplicate a nickname of another user on the server.
fn _nick(self: *User, nickname: []const u8) !void {
const allocator = self._server.getAllocator();
// Make a copy of the nickname string.
const nickname_copy = allocator.alloc(u8, nickname.len) catch |err| {
self._warn(
"Failed to allocate a nickname storage with size of '{}' bytes: {}.\n",
.{ nickname.len, @errorName(err) },
);
return err;
};
errdefer allocator.free(nickname_copy);
mem.copy(u8, nickname_copy, nickname);
// Tell the server about the new nickname.
// TODO Fix passing of the self._nickname parameter which is a workaround for a bug in the
// Zig compiler.
try self._server.recordNickNameChange(
self,
if (self._nickname) |old_nickname| old_nickname else null,
nickname_copy,
);
// Set the new nickname.
if (self._nickname) |old_nickname| {
allocator.free(old_nickname);
}
self._nickname = nickname_copy;
}
/// Obtain the current username or "*" if the name has not been set yet.
fn getUserName(self: *const User) []const u8 {
return if (self._username) |username| username else "*";
}
/// Obtain the current realname or "*" if the name has not been set yet.
fn getRealName(self: *const User) []const u8 {
return if (self._realname) |realname| realname else "*";
}
/// Set a new username and realname.
fn _user(self: *User, username: []const u8, realname: []const u8) !void {
const allocator = self._server.getAllocator();
// Make a copy of the username string.
const username_copy = allocator.alloc(u8, username.len) catch |err| {
self._warn(
"Failed to allocate a username storage with size of '{}' bytes: {}.\n",
.{ username.len, @errorName(err) },
);
return err;
};
errdefer allocator.free(username_copy);
mem.copy(u8, username_copy, username);
// Make a copy of the realname string.
const realname_copy = allocator.alloc(u8, realname.len) catch |err| {
self._warn(
"Failed to allocate a realname storage with size of '{}' bytes: {}.\n",
.{ realname.len, @errorName(err) },
);
return err;
};
errdefer allocator.free(realname_copy);
mem.copy(u8, realname_copy, realname);
// Set the new username and realname.
if (self._username) |old_username| {
allocator.free(old_username);
}
self._username = username_copy;
if (self._realname) |old_realname| {
allocator.free(old_realname);
}
self._realname = realname_copy;
}
/// Format and print an info message on the standard output.
fn _info(self: *const User, comptime fmt: []const u8, args: anytype) void {
switch (self._type) {
.Client => {
return Client.fromConstUser(self)._info(fmt, args);
},
.LocalBot => {
return LocalBot.fromConstUser(self)._info(fmt, args);
},
}
}
/// Format and print a warning message on the standard error output.
fn _warn(self: *const User, comptime fmt: []const u8, args: anytype) void {
switch (self._type) {
.Client => {
return Client.fromConstUser(self)._warn(fmt, args);
},
.LocalBot => {
return LocalBot.fromConstUser(self)._warn(fmt, args);
},
}
}
/// Join a specified channel. Note that it is a caller's responsibility to make sure that the
/// user is not already in the channel.
fn _joinChannel(self: *User, channel: *Channel) !void {
const channel_iter = self._channels.insert(channel, {}) catch |err| {
self._warn(
"Failed to insert channel '{}' in the channel set: {}.\n",
.{ E(channel.getName()), @errorName(err) },
);
return err;
};
errdefer self._channels.remove(channel_iter);
try channel.join(self);
}
/// Leave a specified channel.
fn _partChannel(self: *User, channel: *Channel, part_message: []const u8) void {
const channel_iter = self._channels.find(channel);
assert(channel_iter.valid());
channel.part(self, part_message);
self._channels.remove(channel_iter);
}
/// Send a private message to the user.
fn sendPrivMsg(self: *User, from: []const u8, to: []const u8, text: []const u8) void {
switch (self._type) {
.Client => {
return Client.fromUser(self)._sendPrivMsg(from, to, text);
},
.LocalBot => {
// Ignore because local bots do not care about received private messages.
},
}
}
/// Send an IRC protocol message to the user.
fn sendMessage(
self: *User,
escape_cond: ?*bool,
comptime fmt: []const u8,
args: anytype,
) void {
switch (self._type) {
.Client => {
Client.fromUser(self)._sendMessage(escape_cond, fmt, args);
},
.LocalBot => {
// Ignore because local bots do not send messages anywhere.
},
}
}
};
const UserSet = avl.Map(*User, void, avl.getLessThanFn(*User));
const UserNameSet = avl.Map([]const u8, *User, avl.getLessThanFn([]const u8));
/// Remote client.
const Client = struct {
const InputState = enum {
Normal,
Normal_CR,
};
const AcceptParamError = error{MissingParameter};
const CheckRegisteredError = error{NotRegistered};
const InputError = error{
MalformedMessage,
EndOfFile,
Quit,
};
/// User definition.
_user: User,
/// Client's socket.
_fd: i32,
/// Client's network address.
_addr: net.Address,
/// Writer to the client's socket.
_file_writer: fs.File.Writer,
/// Reader from the client's socket.
_file_reader: fs.File.Reader,
/// Input buffer for IRC messages.
_input_buffer: [512]u8,
/// Number of bytes currently stored in _input_buffer that compose an incomplete message.
_input_received: usize,
/// Current input state at the _input_received position.
_input_state: InputState,
/// Create a new Client instance. Ownership of a specified client descriptor is transferred to
/// the created instance. If constructing the client fails, the file descriptor gets closed by
/// the function.
fn create(fd: i32, addr: net.Address, server: *Server) !*Client {
errdefer os.close(fd);
info("{}: Creating the client.\n", .{addr});
const allocator = server.getAllocator();
const client = allocator.create(Client) catch |err| {
warn("{}: Failed to allocate a client instance: {}.\n", .{ addr, @errorName(err) });
return err;
};
const file = fs.File{ .handle = fd };
client.* = Client{
._user = User.init(.Client, server),
._fd = fd,
._addr = addr,
._file_writer = file.writer(),
._file_reader = file.reader(),
._input_buffer = undefined,
._input_received = 0,
._input_state = .Normal,
};
return client;
}
/// Close the remote client connection and destroy the client.
fn destroy(self: *Client) void {
self._info("Destroying the client.\n", .{});
os.close(self._fd);
const allocator = self._user._server.getAllocator();
self._user.deinit();
allocator.destroy(self);
}
/// Get a Client base pointer given a pointer to its embedded User member.
fn fromUser(user: *User) *Client {
assert(user._type == .Client);
return @fieldParentPtr(Client, "_user", user);
}
/// Get a const Client base pointer given a const pointer to its embedded User member.
fn fromConstUser(user: *const User) *const Client {
assert(user._type == .Client);
return @fieldParentPtr(Client, "_user", user);
}
/// Get a pointer to the embedded User member.
fn toUser(self: *Client) *User {
return &self._user;
}
/// Get the client's file descriptor.
fn getFileDescriptor(self: *const Client) i32 {
return self._fd;
}
/// Format and print an info message on the standard output.
fn _info(self: *const Client, comptime fmt: []const u8, args: anytype) void {
info("{}: " ++ fmt, .{self._addr} ++ args);
}
/// Format and print a warning message on the standard error output.
fn _warn(self: *const Client, comptime fmt: []const u8, args: anytype) void {
warn("{}: " ++ fmt, .{self._addr} ++ args);
}
/// Read one parameter from a specified message (lexer). Upon successful completion, a slice
/// with the parameter is returned. Otherwise, error AcceptParamError.MissingParameter is
/// returned. If the parameter is additionally marked as mandatory then an error reply is sent
/// to the user.
fn _acceptParam(
self: *Client,
lexer: *Lexer,
command: []const u8,
requirement: enum { Mandatory, Optional, Silent },
) AcceptParamError![]const u8 {
const maybe_param = lexer.readParam();
if (maybe_param) |param| {
return param;
}
if (requirement == .Mandatory) {
// Send ERR_NEEDMOREPARAMS.
var ec: bool = undefined;
self._sendMessage(
&ec,
":{} 461 {} {} :Not enough parameters",
.{
self._user._server.getHostName(),
CE(self._user.getNickName(), &ec),
CE(command, &ec),
},
);
}
return AcceptParamError.MissingParameter;
}
/// Read an optional parameter from a specified message (lexer). If it is missing then a given
/// default value is returned instead.
fn _acceptParamOrDefault(
self: *Client,
lexer: *Lexer,
command: []const u8,
default: []const u8,
) []const u8 {
return self._acceptParam(lexer, command, .Optional) catch |err| {
switch (err) {
AcceptParamError.MissingParameter => {
return default;
},
}
};
}
/// Check that the end of a specified message (lexer) has been reached. A warning is reported if
/// that is not the case.
fn _acceptEndOfMessage(self: *Client, lexer: *Lexer, command: []const u8) void {
if (lexer.isAtEnd())
return;
const pos = lexer.getCurPos() + 1;
const rest = lexer.readRest() orelse unreachable;
self._warn(
"Expected the end of the '{}' message at position '{}' but found '{}'.\n",
.{ command, pos, E(rest) },
);
}
/// Process the NICK command.
/// RFC 1459: Parameters: <nickname> [ <hopcount> ]
/// RFC 2812: Parameters: <nickname>
/// IRCZT: Parameters: <nickname>
fn _processCommand_NICK(self: *Client, lexer: *Lexer) !void {
const hostname = self._user._server.getHostName();
const nickname = self._user.getNickName();
var ec: bool = undefined;
const new_nickname = self._acceptParam(lexer, "NICK", .Silent) catch |err| {
switch (err) {
AcceptParamError.MissingParameter => {
// Send ERR_NONICKNAMEGIVEN.
self._sendMessage(
&ec,
":{} 431 {} :No nickname given",
.{ CE(hostname, &ec), CE(nickname, &ec) },
);
return;
},
}
};
self._acceptEndOfMessage(lexer, "NICK");
// Validate the nickname.
for (new_nickname) |char, i| {
// <letter>
if ((char >= 'a' and char <= 'z') or (char >= 'A' and char <= 'Z')) {
continue;
}
if (i != 0) {
// <number>
if (char >= '0' and char <= '9') {
continue;
}
// <special>
if (char == '-' or char == '[' or char == ']' or char == '\\' or char == '`' or
char == '^' or char == '{' or char == '}')
{
continue;
}
}
// Send ERR_ERRONEUSNICKNAME.
self._sendMessage(
&ec,
":{} 432 {} {} :Erroneus nickname",
.{ hostname, CE(nickname, &ec), CE(new_nickname, &ec) },
);
return;
}
// Check that the nickname is not already in use.
if (self._user._server.lookupUser(new_nickname) != null) {
// Send ERR_NICKNAMEINUSE.
self._sendMessage(
&ec,
":{} 433 {} {} :Nickname is already in use",
.{ CE(hostname, &ec), CE(nickname, &ec), CE(new_nickname, &ec) },
);
return;
}
const is_first_nickname = self._user._nickname == null;
self._user._nick(new_nickname) catch |err| {
self._sendMessage(
null,
"ERROR :NICK command failed on the server: {}",
.{@errorName(err)},
);
return err;
};
assert((self._user._username != null) == (self._user._realname != null));
if (is_first_nickname and self._user._username != null) {
// Complete the join if the initial NICK and USER pair was received.
self._completeRegistration();
}
}
/// Process the USER command.
/// RFC 1459: Parameters: <username> <hostname> <servername> <realname>
/// RFC 2812: Parameters: <user> <mode> <unused> <realname>
/// IRCZT: Parameters: <username> <unused> <unused> <realname>
fn _processCommand_USER(self: *Client, lexer: *Lexer) !void {
assert((self._user._username != null) == (self._user._realname != null));
if (self._user._username != null) {
// Send ERR_ALREADYREGISTRED.
var ec: bool = undefined;
self._sendMessage(
&ec,
":{} 462 {} :You may not reregister",
.{ self._user._server.getHostName(), CE(self._user.getNickName(), &ec) },
);
return;
}
const username = self._acceptParam(lexer, "USER", .Mandatory) catch return;
const hostname = self._acceptParam(lexer, "USER", .Mandatory) catch return;
const servername = self._acceptParam(lexer, "USER", .Mandatory) catch return;
const realname = self._acceptParam(lexer, "USER", .Mandatory) catch return;
self._acceptEndOfMessage(lexer, "USER");
self._user._user(username, realname) catch |err| {
self._sendMessage(
null,
"ERROR :USER command failed on the server: {}",
.{@errorName(err)},
);
return err;
};
if (self._user._nickname != null) {
// Complete the join if the initial NICK and USER pair was received.
self._completeRegistration();
}
}
/// Complete join of the client after the initial USER and NICK pair is received.
fn _completeRegistration(self: *Client) void {
assert(self._user._nickname != null);
assert(self._user._username != null);
assert(self._user._realname != null);
const hostname = self._user._server.getHostName();
const nickname = self._user.getNickName();
var ec: bool = undefined;
// Send RPL_LUSERCLIENT.
const users = self._user._server.getUsers();
self._sendMessage(
&ec,
":{} 251 {} :There are {} users and 0 invisible on 1 servers",
.{ CE(hostname, &ec), CE(nickname, &ec), users.count() },
);
// Send motd.
self._sendMessage(
&ec,
":{} 375 {} :- {} Message of the Day -",
.{ CE(hostname, &ec), CE(nickname, &ec), CE(hostname, &ec) },
);
self._sendMessage(
&ec,
":{} 372 {} :- Welcome to the {} IRC network!",
.{ CE(hostname, &ec), CE(nickname, &ec), CE(hostname, &ec) },
);
self._sendMessage(
&ec,
":{} 376 {} :End of /MOTD command.",
.{ CE(hostname, &ec), CE(nickname, &ec) },
);
// Welcome the user also via a private message.
self._sendMessage(
&ec,
":irczt-connect PRIVMSG {} :Welcome to {}",
.{ CE(nickname, &ec), CE(hostname, &ec) },
);
}
/// Check that the user has completed the initial registration and is fully joined. If that is
/// not the case then reply ERR_NOTREGISTERED is sent to the client and
/// error CheckRegisteredError.NotRegistered is returned.
fn _checkRegistered(self: *Client) !void {
assert((self._user._username != null) == (self._user._realname != null));
if (self._user._nickname != null and self._user._username != null) {
return;
}
self._sendMessage(
null,
":{} 451 * :You have not registered",
.{self._user._server.getHostName()},
);
return Client.CheckRegisteredError.NotRegistered;
}
/// Process the QUIT command.
/// RFC 1459: Parameters: [<Quit message>]
/// RFC 2812: Parameters: [ <Quit Message> ]
/// IRCZT: Parameters: [ <Quit Message> ]
fn _processCommand_QUIT(self: *Client, lexer: *Lexer) !void {
const quit_message = self._acceptParamOrDefault(lexer, "QUIT", "Client quit");
self._acceptEndOfMessage(lexer, "QUIT");
var ec: bool = undefined;
self._sendMessage(&ec, "ERROR :{}", .{CE(quit_message, &ec)});
self._user._quit(quit_message);
return Client.InputError.Quit;
}
/// Process the LIST command.
/// RFC 1459: Parameters: [<channel>{,<channel>} [<server>]]
/// RFC 2812: Parameters: [ <channel> *( "," <channel> ) [ <target> ] ]
/// IRCZT: Parameters: [ <channel> *( "," <channel> ) ]
fn _processCommand_LIST(self: *Client, lexer: *Lexer) !void {
self._checkRegistered() catch return;
const maybe_channel_list = self._acceptParam(lexer, "LIST", .Optional) catch null;
self._acceptEndOfMessage(lexer, "LIST");
const hostname = self._user._server.getHostName();
const nickname = self._user.getNickName();
var ec: bool = undefined;
// Send RPL_LISTSTART.
self._sendMessage(
&ec,
":{} 321 {} Channel :Users Name",
.{ CE(hostname, &ec), CE(nickname, &ec) },
);
if (maybe_channel_list) |channel_list| {
// Send RPL_LIST for each matched channel.
var sub_lexer = Lexer.init(channel_list);
while (sub_lexer.readListItem()) |channel_name| {
const channel = self._user._server.lookupChannel(channel_name) orelse continue;
self._sendMessage(
&ec,
":{} 322 {} {} {} :{}",
.{
CE(hostname, &ec),
CE(nickname, &ec),
CE(channel.getName(), &ec),
channel.getMembers().count(),
CE(channel.getTopic(), &ec),
},
);
}
} else {
// Send RPL_LIST for each channel on the server.
const channels = self._user._server.getChannels();
var channel_iter = channels.iterator();
while (channel_iter.next()) |channel_node| {
const channel = channel_node.value();
self._sendMessage(
&ec,
":{} 322 {} {} {} :{}",
.{
CE(hostname, &ec),
CE(nickname, &ec),
CE(channel.getName(), &ec),
channel.getMembers().count(),
CE(channel.getTopic(), &ec),
},
);
}
}
// Send RPL_LISTEND.
self._sendMessage(
&ec,
":{} 323 {} :End of /LIST",
.{ CE(hostname, &ec), CE(nickname, &ec) },
);
}
/// Process the JOIN command.
/// RFC 1459: Parameters: <channel>{,<channel>} [<key>{,<key>}]
/// RFC 2812: Parameters: ( <channel> *( "," <channel> ) [ <key> *( "," <key> ) ] ) / "0"
/// IRCZT: Parameters: <channel> *( "," <channel> )
fn _processCommand_JOIN(self: *Client, lexer: *Lexer) !void {
self._checkRegistered() catch return;
const channel_list = self._acceptParam(lexer, "JOIN", .Mandatory) catch return;
self._acceptEndOfMessage(lexer, "JOIN");
const hostname = self._user._server.getHostName();
const nickname = self._user.getNickName();
var ec: bool = undefined;
var sub_lexer = Lexer.init(channel_list);
while (sub_lexer.readListItem()) |channel_name| {
const channel = self._user._server.lookupChannel(channel_name) orelse {
// Send ERR_NOSUCHCHANNEL.
self._sendMessage(
&ec,
":{} 403 {} {} :No such channel",
.{ CE(hostname, &ec), CE(nickname, &ec), CE(channel_name, &ec) },
);
continue;
};
// If the user is already in the channel then skip it as there is nothing left to do.
const members = channel.getMembers();
const member_iter = members.find(&self._user);
if (member_iter.valid()) {
continue;
}
self._user._joinChannel(channel) catch |err| {
self._sendMessage(
null,
"ERROR :JOIN command failed on the server: {}",
.{@errorName(err)},
);
return err;
};
}
}
/// Process the PART command.
/// RFC 1459: Parameters: <channel>{,<channel>}
/// RFC 2812: Parameters: <channel> *( "," <channel> ) [ <Part Message> ]
/// IRCZT: Parameters: <channel> *( "," <channel> ) [ <Part Message> ]
fn _processCommand_PART(self: *Client, lexer: *Lexer) !void {
self._checkRegistered() catch return;
const channel_list = self._acceptParam(lexer, "PART", .Mandatory) catch return;
const part_message = self._acceptParamOrDefault(lexer, "PART", self._user.getNickName());
self._acceptEndOfMessage(lexer, "PART");
const hostname = self._user._server.getHostName();
const nickname = self._user.getNickName();
var ec: bool = undefined;
var sub_lexer = Lexer.init(channel_list);
while (sub_lexer.readListItem()) |channel_name| {
const channel = self._user._server.lookupChannel(channel_name) orelse {
// Send ERR_NOSUCHCHANNEL.
self._sendMessage(
&ec,
":{} 403 {} {} :No such channel",
.{ CE(hostname, &ec), CE(nickname, &ec), CE(channel_name, &ec) },
);
continue;
};
const channel_iter = self._user._channels.find(channel);
if (!channel_iter.valid()) {
// Send ERR_NOTONCHANNEL.
self._sendMessage(
&ec,
":{} 442 {} {} :You're not on that channel",
.{ CE(hostname, &ec), CE(nickname, &ec), CE(channel_name, &ec) },
);
continue;
}
self._user._partChannel(channel, part_message);
}
}
/// Process the WHO command.
/// RFC 1459: Parameters: [<name> [<o>]]
/// RFC 2812: Parameters: [ <mask> [ "o" ] ]
/// IRCZT: Parameters: <channel>
fn _processCommand_WHO(self: *Client, lexer: *Lexer) !void {
self._checkRegistered() catch return;
const name = self._acceptParam(lexer, "WHO", .Mandatory) catch return;
self._acceptEndOfMessage(lexer, "WHO");
const hostname = self._user._server.getHostName();
const nickname = self._user.getNickName();
var ec: bool = undefined;
const maybe_channel = self._user._server.lookupChannel(name);
if (maybe_channel) |channel| {
// Send RPL_WHOREPLY.
const members = channel.getMembers();
var member_iter = members.iterator();
while (member_iter.next()) |member_node| {
const member = member_node.key();
self._sendMessage(
&ec,
":{} 352 {} {} {} hidden {} {} H :0 {}",
.{
CE(hostname, &ec),
CE(nickname, &ec),
CE(name, &ec),
CE(member.getUserName(), &ec),
CE(hostname, &ec),
CE(member.getNickName(), &ec),
CE(member.getRealName(), &ec),
},
);
}
}
// Send RPL_ENDOFWHO.
self._sendMessage(
&ec,
":{} 315 {} {} :End of /WHO list",
.{ CE(hostname, &ec), CE(nickname, &ec), CE(name, &ec) },
);
}
/// Process the TOPIC command.
/// RFC 1459: Parameters: <channel> [<topic>]
/// RFC 2812: Parameters: <channel> [ <topic> ]
/// IRCZT: Parameters: <channel> [ <topic> ]
fn _processCommand_TOPIC(self: *Client, lexer: *Lexer) !void {
self._checkRegistered() catch return;
const channel_name = self._acceptParam(lexer, "TOPIC", .Mandatory) catch return;
const maybe_topic = self._acceptParam(lexer, "TOPIC", .Optional) catch null;
self._acceptEndOfMessage(lexer, "TOPIC");
const hostname = self._user._server.getHostName();
const nickname = self._user.getNickName();
var ec: bool = undefined;
const channel = self._user._server.lookupChannel(channel_name) orelse {
// Send ERR_NOSUCHCHANNEL.
self._sendMessage(
&ec,
":{} 403 {} {} :No such channel",
.{ CE(hostname, &ec), CE(nickname, &ec), CE(channel_name, &ec) },
);
return;
};
channel.topicate(&self._user, maybe_topic) catch |err| {
self._sendMessage(
null,
"ERROR :TOPIC command failed on the server: {}",
.{@errorName(err)},
);
return err;
};
}
/// Process the PRIVMSG command.
/// RFC 1459: Parameters: <receiver>{,<receiver>} <text to be sent>
/// RFC 2812: Parameters: <msgtarget> <text to be sent>
/// IRCZT: Parameters: <msgtarget> <text to be sent>
fn _processCommand_PRIVMSG(self: *Client, lexer: *Lexer) !void {
self._checkRegistered() catch return;
const msgtarget = self._acceptParam(lexer, "PRIVMSG", .Mandatory) catch return;
const text = self._acceptParam(lexer, "PRIVMSG", .Mandatory) catch return;
self._acceptEndOfMessage(lexer, "PRIVMSG");
const hostname = self._user._server.getHostName();
const nickname = self._user.getNickName();
var ec: bool = undefined;
var sub_lexer = Lexer.init(msgtarget);
while (sub_lexer.readListItem()) |msgto| {
// Try matching msgto with a channel name.
const maybe_channel = self._user._server.lookupChannel(msgto);
if (maybe_channel) |channel| {
channel.sendPrivMsg(&self._user, text);
continue;
}
// Try matching msgto with a user nick.
const maybe_user = self._user._server.lookupUser(msgto);
if (maybe_user) |user| {
user.sendPrivMsg(nickname, msgto, text);
continue;
}
// Send ERR_NOSUCHNICK.
self._sendMessage(
&ec,
":{} 401 {} {} :No such nick/channel",
.{ CE(hostname, &ec), CE(nickname, &ec), CE(msgto, &ec) },
);
}
}
/// Process a single message from the client.
fn _processMessage(self: *Client, message: []const u8) !void {
var lexer = Lexer.init(message);
const hostname = self._user._server.getHostName();
const nickname = self._user.getNickName();
var ec: bool = undefined;
// Parse any prefix. If it is present then check it matches the current nickname as that is
// the only allowed prefix for clients.
if (lexer.getCurChar() == ':') {
const prefix = lexer.readWord() orelse unreachable;
if (!mem.eql(u8, prefix[1..], nickname)) {
self._sendMessage(null, "ERROR :Message prefix does not match the nickname", .{});
return Client.InputError.MalformedMessage;
}
}
// Parse the command name.
const command = lexer.readWord() orelse {
self._sendMessage(null, "ERROR :No command specified in the message", .{});
return Client.InputError.MalformedMessage;
};
// Process the command.
if (mem.eql(u8, command, "NICK")) {
try self._processCommand_NICK(&lexer);
} else if (mem.eql(u8, command, "USER")) {
try self._processCommand_USER(&lexer);
} else if (mem.eql(u8, command, "QUIT")) {
try self._processCommand_QUIT(&lexer);
} else if (mem.eql(u8, command, "LIST")) {
try self._processCommand_LIST(&lexer);
} else if (mem.eql(u8, command, "JOIN")) {
try self._processCommand_JOIN(&lexer);
} else if (mem.eql(u8, command, "PART")) {
try self._processCommand_PART(&lexer);
} else if (mem.eql(u8, command, "WHO")) {
try self._processCommand_WHO(&lexer);
} else if (mem.eql(u8, command, "TOPIC")) {
try self._processCommand_TOPIC(&lexer);
} else if (mem.eql(u8, command, "PRIVMSG")) {
try self._processCommand_PRIVMSG(&lexer);
} else {
// Send ERR_UNKNOWNCOMMAND.
self._sendMessage(
&ec,
":{} 421 {} {} :Unknown command",
.{ self._user._server.getHostName(), CE(nickname, &ec), CE(command, &ec) },
);
}
}
/// Read new input available on the client's socket and process it. When an error is returned,
/// no further calls to processInput() are allowed and the client should be destroyed.
fn processInput(self: *Client) !void {
assert(self._input_received < self._input_buffer.len);
var pos = self._input_received;
const read = self._file_reader.read(self._input_buffer[pos..]) catch |err| {
self._warn(
"Failed to read input from the client's socket (fd '{}'): {}.\n",
.{ self._file_reader.context.handle, @errorName(err) },
);
return err;
};
if (read == 0) {
// End of file reached.
self._info("Client disconnected.\n", .{});
return Client.InputError.EndOfFile;
}
self._input_received += read;
var message_begin: usize = 0;
while (pos < self._input_received) : (pos += 1) {
const char = self._input_buffer[pos];
switch (self._input_state) {
.Normal => {
if (char == '\r') {
self._input_state = .Normal_CR;
}
},
.Normal_CR => {
if (char == '\n') {
const message = self._input_buffer[message_begin .. pos - 1];
self._info("< {}\n", .{E(message)});
try self._processMessage(message);
self._input_state = .Normal;
message_begin = pos + 1;
} else {
self._info("< {}\n", .{E(self._input_buffer[message_begin .. pos + 1])});
self._sendMessage(
null,
"ERROR :Message is not terminated by the \\r\\n pair",
.{},
);
return Client.InputError.MalformedMessage;
}
},
}
}
if (message_begin >= self._input_received) {
assert(message_begin == self._input_received);
self._input_received = 0;
} else if (message_begin == 0 and self._input_received == self._input_buffer.len) {
self._info("< {}\n", .{E(self._input_buffer[0..])});
self._sendMessage(null, "ERROR :Message is too long", .{});
return Client.InputError.MalformedMessage;
} else {
mem.copy(
u8,
self._input_buffer[0..],
self._input_buffer[message_begin..self._input_received],
);
self._input_received -= message_begin;
}
}
/// Send a private message to the client.
fn _sendPrivMsg(self: *Client, from: []const u8, to: []const u8, text: []const u8) void {
var ec: bool = undefined;
self._sendMessage(
&ec,
":{} PRIVMSG {} :{}",
.{ CE(from, &ec), CE(to, &ec), CE(text, &ec) },
);
}
/// Send an IRC protocol message to the client.
fn _sendMessage(
self: *Client,
maybe_escape_cond: ?*bool,
comptime fmt: []const u8,
args: anytype,
) void {
if (maybe_escape_cond) |escape_cond| {
escape_cond.* = true;
}
self._info("> " ++ fmt ++ "\n", args);
if (maybe_escape_cond) |escape_cond| {
escape_cond.* = false;
}
self._file_writer.print(fmt ++ "\r\n", args) catch |err| {
self._warn(
"Failed to write the message into the client's socket (fd '{}'): {}.\n",
.{ self._file_writer.context.handle, @errorName(err) },
);
};
}
};
const ClientSet = avl.Map(*Client, void, avl.getLessThanFn(*Client));
/// Local bot which simulates a user.
const LocalBot = struct {
/// User definition.
_user: User,
/// Number of channels that the bot should try to be in.
_channels_target: u8,
/// Probability that the bot leaves a channel at each tick.
_channels_leave_rate: f32,
/// Number of sent messages per each tick in every joined channel.
_message_rate: f32,
/// Average message length.
_message_length: u8,
/// Create a new LocalBot instance.
fn create(
nickname: []const u8,
channels_target: u8,
channels_leave_rate: f32,
message_rate: f32,
message_length: u8,
server: *Server,
) !*LocalBot {
info("{}: Creating the local bot.\n", .{E(nickname)});
const allocator = server.getAllocator();
const local_bot = allocator.create(LocalBot) catch |err| {
warn(
"{}: Failed to allocate a local bot instance: {}.\n",
.{ E(nickname), @errorName(err) },
);
return err;
};
local_bot.* = LocalBot{
._user = User.init(.LocalBot, server),
._channels_target = channels_target,
._channels_leave_rate = channels_leave_rate,
._message_rate = message_rate,
._message_length = message_length,
};
return local_bot;
}
/// Destroy the local bot.
fn destroy(self: *LocalBot) void {
self._info("Destroying the local bot.\n", .{});
const allocator = self._user._server.getAllocator();
self._user.deinit();
allocator.destroy(self);
}
/// Get a LocalBot base pointer given a pointer to its embedded User member.
fn fromUser(user: *User) *LocalBot {
assert(user._type == .LocalBot);
return @fieldParentPtr(LocalBot, "_user", user);
}
/// Get a const LocalBot base pointer given a const pointer to its embedded User member.
fn fromConstUser(user: *const User) *const LocalBot {
assert(user._type == .LocalBot);
return @fieldParentPtr(LocalBot, "_user", user);
}
/// Format and print an info message on the standard output.
fn _info(self: *const LocalBot, comptime fmt: []const u8, args: anytype) void {
const nickname = E(self._user.getNickName());
info("{}: " ++ fmt, .{nickname} ++ args);
}
/// Format and print a warning message on the standard error output.
fn _warn(self: *const LocalBot, comptime fmt: []const u8, args: anytype) void {
const nickname = E(self._user.getNickName());
warn("{}: " ++ fmt, .{nickname} ++ args);
}
/// Simulate the NICK registration command.
fn register_NICK(self: *LocalBot, nickname: []const u8) !void {
return self._user._nick(nickname);
}
/// Simulate the USER registration command.
fn register_USER(self: *LocalBot, username: []const u8, realname: []const u8) !void {
return self._user._user(username, realname);
}
/// Join the bot's desired number of channels.
fn _tick_joinChannels(self: *LocalBot) void {
const joined = self._user._channels.count();
if (self._channels_target <= joined) {
return;
}
var needed = self._channels_target - joined;
const server_channels = self._user._server.getChannels();
var left = server_channels.count() - joined;
const rng = self._user._server.getRNG();
var server_channel_iter = server_channels.iterator();
while (server_channel_iter.next()) |server_channel_node| {
const server_channel = server_channel_node.value();
// Skip this channel if the bot is already in it.
const user_channel_iter = self._user._channels.find(server_channel);
if (user_channel_iter.valid()) {
continue;
}
const join_probability: f32 = @intToFloat(f32, needed) / @intToFloat(f32, left);
if (rng.float(f32) < join_probability) {
self._user._joinChannel(server_channel) catch {};
needed -= 1;
if (needed == 0) {
break;
}
}
left -= 1;
}
}
/// Process joined channels and leave them randomly at a specific rate.
fn _tick_partChannels(self: *LocalBot) void {
const rng = self._user._server.getRNG();
var channel_iter = self._user._channels.iterator();
while (channel_iter.valid()) {
const channel = channel_iter.key();
_ = channel_iter.next();
if (rng.float(f32) < self._channels_leave_rate) {
self._user._partChannel(channel, self._user.getNickName());
}
}
}
/// Send random messages to joined channels at a specific rate.
fn _tick_sendMessages(self: *LocalBot) void {
const rng = self._user._server.getRNG();
const word_bank = self._user._server.getWordBank();
var channel_iter = self._user._channels.iterator();
while (channel_iter.next()) |channel_node| {
const channel = channel_node.key();
if (rng.float(f32) >= self._message_rate) {
continue;
}
// Generate a random message.
var needed = rng.intRangeAtMost(u8, 1, 2 * self._message_length - 1);
var message_buffer: [1024]u8 = undefined;
var at: usize = 0;
while (needed > 0) : (needed -= 1) {
const word_index = rng.uintLessThan(usize, word_bank.len);
const word = word_bank[word_index];
if (message_buffer.len - at < 1 + word.len) {
break;
}
if (at != 0) {
message_buffer[at] = ' ';
at += 1;
}
mem.copy(u8, message_buffer[at..], word);
at += word.len;
}
// Send the message to the channel.
channel.sendPrivMsg(&self._user, message_buffer[0..at]);
}
}
/// Run the bot's intelligence.
fn tick(self: *LocalBot) void {
self._tick_joinChannels();
self._tick_partChannels();
self._tick_sendMessages();
}
};
const LocalBotSet = avl.Map(*LocalBot, void, avl.getLessThanFn(*LocalBot));
const Channel = struct {
/// Parent server.
_server: *Server,
/// Channel name (owned).
_name: []const u8,
/// Channel topic (owned).
_topic: ?[]const u8,
/// Users in the channel.
_members: UserSet,
/// Create a new Channel instance.
fn create(name: []const u8, server: *Server) !*Channel {
info("{}: Creating the channel.\n", .{E(name)});
const allocator = server.getAllocator();
// Make a copy of the name string.
const name_copy = allocator.alloc(u8, name.len) catch |err| {
warn(
"{}: Failed to allocate a channel name storage with size of '{}' bytes: {}.\n",
.{ E(name), name.len, @errorName(err) },
);
return err;
};
errdefer allocator.free(name_copy);
mem.copy(u8, name_copy, name);
// Allocate a channel instance.
const channel = allocator.create(Channel) catch |err| {
warn(
"{}: Failed to allocate a channel instance: {}.\n",
.{ E(name), @errorName(err) },
);
return err;
};
channel.* = Channel{
._server = server,
._name = name_copy,
._topic = null,
._members = UserSet.init(allocator),
};
return channel;
}
/// Destroy the channel. All members need to leave prior to calling this function.
fn destroy(self: *Channel) void {
self._info("Destroying the channel.\n", .{});
const allocator = self._server.getAllocator();
allocator.free(self._name);
if (self._topic) |topic| {
allocator.free(topic);
}
// Channels can be destroyed only after all users leave.
assert(self._members.count() == 0);
self._members.deinit();
allocator.destroy(self);
}
/// Obtain the channel name.
fn getName(self: *const Channel) []const u8 {
return self._name;
}
/// Obtain a topic set in the channel.
fn getTopic(self: *const Channel) []const u8 {
return if (self._topic) |topic| topic else "";
}
/// Obtain a set of users currently present in the channel.
fn getMembers(self: *const Channel) *const UserSet {
return &self._members;
}
/// Format and print an info message on the standard output.
fn _info(self: *const Channel, comptime fmt: []const u8, args: anytype) void {
const name = E(self._name);
info("{}: " ++ fmt, .{name} ++ args);
}
/// Format and print a warning message on the standard error output.
fn _warn(self: *const Channel, comptime fmt: []const u8, args: anytype) void {
const name = E(self._name);
warn("{}: " ++ fmt, .{name} ++ args);
}
/// Send information about the current topic to a specified user.
fn _sendTopic(self: *const Channel, user: *User) void {
const nickname = user.getNickName();
const hostname = self._server.getHostName();
var ec: bool = undefined;
if (self._topic) |topic| {
// Send RPL_TOPIC.
user.sendMessage(
&ec,
":{} 332 {} {} :{}",
.{
CE(hostname, &ec),
CE(nickname, &ec),
CE(self._name, &ec),
CE(topic, &ec),
},
);
} else {
// Send RPL_NOTOPIC.
user.sendMessage(
&ec,
":{} 331 {} {} :No topic is set",
.{ CE(hostname, &ec), CE(nickname, &ec), CE(self._name, &ec) },
);
}
}
/// Process join from a user. Note that it is a caller's responsibility to make sure that the
/// user is not already in the channel.
fn join(self: *Channel, user: *User) !void {
const user_iter = self._members.insert(user, {}) catch |err| {
self._warn(
"Failed to insert user '{}' in the channel user set: {}.\n",
.{ E(user.getNickName()), @errorName(err) },
);
return err;
};
errdefer self._members.remove(user_iter);
const nickname = user.getNickName();
const hostname = self._server.getHostName();
var ec: bool = undefined;
self._info(
"User '{}' joined the channel (now at '{}' users).\n",
.{ E(nickname), self._members.count() },
);
// Inform all members about the join.
var member_iter = self._members.iterator();
while (member_iter.next()) |member_node| {
const member = member_node.key();
member.sendMessage(
&ec,
":{} JOIN {}",
.{ CE(nickname, &ec), CE(self._name, &ec) },
);
}
// Send information about the channel topic.
self._sendTopic(user);
// Send RPL_NAMREPLY.
member_iter = self._members.iterator();
while (member_iter.next()) |member_node| {
const member = member_node.key();
const member_nickname = member.getNickName();
user.sendMessage(
&ec,
":{} 353 {} = {} :{}",
.{
CE(hostname, &ec),
CE(nickname, &ec),
CE(self._name, &ec),
CE(member_nickname, &ec),
},
);
}
// Send RPL_ENDOFNAMES.
user.sendMessage(
&ec,
":{} 366 {} {} :End of /NAMES list",
.{ CE(hostname, &ec), CE(nickname, &ec), CE(self._name, &ec) },
);
}
/// Process leave from a user.
fn part(self: *Channel, user: *User, part_message: []const u8) void {
const nickname = user.getNickName();
var ec: bool = undefined;
// Inform all members about the leave.
var member_iter = self._members.iterator();
while (member_iter.next()) |member_node| {
const member = member_node.key();
member.sendMessage(
&ec,
":{} PART {} :{}",
.{ CE(nickname, &ec), CE(self._name, &ec), CE(part_message, &ec) },
);
}
const user_iter = self._members.find(user);
assert(user_iter.valid());
self._members.remove(user_iter);
self._info(
"User '{}' parted the channel (now at '{}' users).\n",
.{ E(nickname), self._members.count() },
);
}
/// Process quit from a user.
fn quit(self: *Channel, user: *User) void {
// Note that members are not informed about the user leaving. It is a responsibility of the
// caller to send this information to all relevant users.
const user_iter = self._members.find(user);
assert(user_iter.valid());
self._members.remove(user_iter);
self._info(
"User '{}' quit the channel (now at '{}' users).\n",
.{ E(user.getNickName()), self._members.count() },
);
}
/// Set/query the channel topic.
fn topicate(self: *Channel, user: *User, maybe_topic: ?[]const u8) !void {
if (maybe_topic) |topic| {
// The user sets a new topic.
const allocator = self._server.getAllocator();
var maybe_new_topic: ?[]const u8 = undefined;
if (topic.len != 0) {
// Make a copy of the topic string.
const topic_copy = allocator.alloc(u8, topic.len) catch |err| {
self._warn(
"Failed to allocate a topic storage with size of '{}' bytes: {}.\n",
.{ topic.len, @errorName(err) },
);
return err;
};
errdefer allocator.free(topic_copy);
mem.copy(u8, topic_copy, topic);
maybe_new_topic = topic_copy;
} else {
maybe_new_topic = null;
}
if (self._topic) |old_topic| {
allocator.free(old_topic);
}
self._topic = maybe_new_topic;
// Inform all members about the new topic.
var member_iter = self._members.iterator();
while (member_iter.next()) |member_node| {
const member = member_node.key();
self._sendTopic(member);
}
return;
}
// The user queries the current topic.
self._sendTopic(user);
}
/// Send a message to all users in the channel.
fn sendPrivMsg(self: *Channel, user: *const User, text: []const u8) void {
const from_name = user.getNickName();
var member_iter = self._members.iterator();
while (member_iter.next()) |member_node| {
const member = member_node.key();
member.sendPrivMsg(from_name, self._name, text);
}
}
};
const ChannelSet = avl.Map(*Channel, void, avl.getLessThanFn(*Channel));
const ChannelNameSet = avl.Map([]const u8, *Channel, avl.getLessThanFn([]const u8));
const Server = struct {
/// Memory allocator, used by the server and related channel+user objects.
_allocator: *mem.Allocator,
/// Random number generator.
_rng: *rand.Random,
/// Word bank for use by local bots.
_word_bank: []const []const u8,
/// Socket address.
_sockaddr: net.Address,
/// Host name (owned).
_host: []const u8,
/// Port number (owned).
_port: []const u8,
/// All remote clients (owned).
_clients: ClientSet,
/// All local bots (owned).
_local_bots: LocalBotSet,
/// Users with a valid name (owned). This is a subset of _clients and _local_bots. Keys
/// (nicknames) are owned by respective User instances.
_users: UserNameSet,
/// All channels (owned). Keys (names) are owned by respective Channel instances.
_channels: ChannelNameSet,
/// Create a new Server instance.
fn create(
address: []const u8,
word_bank: []const []const u8,
allocator: *mem.Allocator,
rng: *rand.Random,
) !*Server {
// Parse the address.
var host_end: usize = address.len;
var port_start: usize = address.len;
for (address) |char, i| {
if (char == ':') {
host_end = i;
port_start = i + 1;
break;
}
}
const host = address[0..host_end];
const port = address[port_start..address.len];
const parsed_port = std.fmt.parseUnsigned(u16, port, 10) catch |err| {
warn("Failed to parse port number '{}': {}.\n", .{ port, @errorName(err) });
return err;
};
const parsed_address = net.Address.parseIp4(host, parsed_port) catch |err| {
warn("Failed to parse IP address '{}:{}': {}.\n", .{ host, port, @errorName(err) });
return err;
};
// Make a copy of the host and port strings.
const host_copy = allocator.alloc(u8, host.len) catch |err| {
warn(
"Failed to allocate a hostname storage with size of '{}' bytes: {}.\n",
.{ host.len, @errorName(err) },
);
return err;
};
errdefer allocator.free(host_copy);
mem.copy(u8, host_copy, host);
const port_copy = allocator.alloc(u8, port.len) catch |err| {
warn(
"Failed to allocate a port storage with size of '{}' bytes: {}.\n",
.{ port.len, @errorName(err) },
);
return err;
};
errdefer allocator.free(port_copy);
mem.copy(u8, port_copy, port);
// Allocate the server struct.
const server = allocator.create(Server) catch |err| {
warn("Failed to allocate a server instance: {}.\n", .{@errorName(err)});
return err;
};
server.* = Server{
._allocator = allocator,
._rng = rng,
._word_bank = word_bank,
._sockaddr = parsed_address,
._host = host_copy,
._port = port_copy,
._clients = ClientSet.init(allocator),
._local_bots = LocalBotSet.init(allocator),
._users = UserNameSet.init(allocator),
._channels = ChannelNameSet.init(allocator),
};
return server;
}
/// Destroy the server, including all associated users and channels.
fn destroy(self: *Server) void {
// Destroy all clients.
var client_iter = self._clients.iterator();
while (client_iter.next()) |client_node| {
const client = client_node.key();
client.destroy();
}
self._clients.deinit();
// Destroy all local bots.
var local_bot_iter = self._local_bots.iterator();
while (local_bot_iter.next()) |local_bot_node| {
const local_bot = local_bot_node.key();
local_bot.destroy();
}
self._local_bots.deinit();
self._users.deinit();
// Destroy all channels.
var channel_iter = self._channels.iterator();
while (channel_iter.next()) |channel_node| {
const channel = channel_node.value();
channel.destroy();
}
self._channels.deinit();
self._allocator.free(self._host);
self._allocator.free(self._port);
self._allocator.destroy(self);
}
/// Obtain the memory allocator.
fn getAllocator(self: *Server) *mem.Allocator {
return self._allocator;
}
/// Obtain the random number generator.
fn getRNG(self: *Server) *rand.Random {
return self._rng;
}
/// Obtain the word bank.
fn getWordBank(self: *const Server) []const []const u8 {
return self._word_bank;
}
/// Obtain the server's hostname.
fn getHostName(self: *const Server) []const u8 {
return self._host;
}
/// Obtain registered users on the server.
fn getUsers(self: *Server) *const UserNameSet {
return &self._users;
}
/// Obtain channels on the server.
fn getChannels(self: *Server) *const ChannelNameSet {
return &self._channels;
}
/// Run the server.
fn run(self: *Server) !void {
// Create the server socket.
const listenfd = os.socket(
os.AF_INET,
os.SOCK_STREAM | os.SOCK_CLOEXEC,
os.IPPROTO_TCP,
) catch |err| {
warn("Failed to create a server socket: {}.\n", .{@errorName(err)});
return err;
};
defer os.close(listenfd);
os.bind(listenfd, &self._sockaddr.any, self._sockaddr.getOsSockLen()) catch |err| {
warn(
"Failed to bind to address '{}:{}': {}.\n",
.{ self._host, self._port, @errorName(err) },
);
return err;
};
os.listen(listenfd, os.SOMAXCONN) catch |err| {
warn(
"Failed to listen on '{}:{}': {}.\n",
.{ self._host, self._port, @errorName(err) },
);
return err;
};
// Create an epoll instance.
const epfd = os.epoll_create1(os.EPOLL_CLOEXEC) catch |err| {
warn("Failed to create an epoll instance: {}.\n", .{@errorName(err)});
return err;
};
defer os.close(epfd);
// Register the server socket with the epoll instance.
var listenfd_event = os.epoll_event{
.events = os.EPOLLIN,
.data = os.epoll_data{ .ptr = 0 },
};
os.epoll_ctl(epfd, os.EPOLL_CTL_ADD, listenfd, &listenfd_event) catch |err| {
warn(
"Failed to add the server socket (fd '{}') to the epoll instance: {}.\n",
.{ listenfd, @errorName(err) },
);
return err;
};
// Register the standard input with the epoll instance.
var stdinfd_event = os.epoll_event{
.events = os.EPOLLIN,
.data = os.epoll_data{ .ptr = 1 },
};
os.epoll_ctl(epfd, os.EPOLL_CTL_ADD, os.STDIN_FILENO, &stdinfd_event) catch |err| {
warn(
"Failed to add the standard input (fd '{}') to the epoll instance: {}.\n",
.{ os.STDIN_FILENO, @errorName(err) },
);
return err;
};
// Listen for events.
info("Listening on '{}:{}'.\n", .{ self._host, self._port });
var next_bot_tick = time.milliTimestamp();
while (true) {
var timeout = next_bot_tick - time.milliTimestamp();
// Run the local bot ticks if it is time.
if (timeout <= 0) {
var local_bot_iter = self._local_bots.iterator();
while (local_bot_iter.next()) |local_bot_node| {
const local_bot = local_bot_node.key();
local_bot.tick();
}
timeout = 1000;
next_bot_tick = time.milliTimestamp() + timeout;
}
// Wait for a next event.
var events: [1]os.epoll_event = undefined;
assert(timeout <= 1000);
const ep = os.epoll_wait(epfd, events[0..], @intCast(i32, timeout));
if (ep == 0) {
continue;
}
// Handle the event.
switch (events[0].data.ptr) {
0 => self._acceptClient(epfd, listenfd),
1 => {
// Exit on any input on stdin.
info("Exit request from the standard input.\n", .{});
break;
},
else => self._processInput(epfd, @intToPtr(*Client, events[0].data.ptr)),
}
}
}
/// Accept a new client connection.
fn _acceptClient(self: *Server, epfd: i32, listenfd: i32) void {
var client_sockaddr: os.sockaddr align(4) = undefined;
var client_socklen: os.socklen_t = @sizeOf(@TypeOf(client_sockaddr));
const clientfd = os.accept(
listenfd,
&client_sockaddr,
&client_socklen,
os.SOCK_CLOEXEC,
) catch |err| {
warn("Failed to accept a new client connection: {}.\n", .{@errorName(err)});
return;
};
const client_addr = net.Address.initPosix(&client_sockaddr);
// Create a new client. This transfers ownership of the clientfd to the Client
// instance.
const client = Client.create(clientfd, client_addr, self) catch return;
errdefer client.destroy();
const client_iter = self._clients.insert(client, {}) catch |err| {
warn(
"Failed to insert client '{}' in the main client set: {}.\n",
.{ client_addr, @errorName(err) },
);
return;
};
errdefer self._clients.remove(client_iter);
// Listen for the client.
var clientfd_event = os.epoll_event{
.events = os.EPOLLIN,
.data = os.epoll_data{ .ptr = @ptrToInt(client) },
};
os.epoll_ctl(epfd, os.EPOLL_CTL_ADD, clientfd, &clientfd_event) catch |err| {
warn(
"Failed to add socket (fd '{}') of client '{}' to the epoll instance: {}.\n",
.{ clientfd, client_addr, @errorName(err) },
);
return;
};
}
/// Process input from a client.
fn _processInput(self: *Server, epfd: i32, client: *Client) void {
client.processInput() catch {
// The client quit or a critical error occurred. Destroy the client now.
const clientfd = client.getFileDescriptor();
os.epoll_ctl(epfd, os.EPOLL_CTL_DEL, clientfd, undefined) catch unreachable;
const user = client.toUser();
if (user.hasNickName()) {
const user_iter = self._users.find(user.getNickName());
assert(user_iter.valid());
self._users.remove(user_iter);
}
const client_iter = self._clients.find(client);
assert(client_iter.valid());
self._clients.remove(client_iter);
client.destroy();
};
}
/// Process a nickname change. Note that it is a caller's responsibility to make sure that this
/// name does not duplicate a nickname of another user on the server.
fn recordNickNameChange(
self: *Server,
user: *User,
maybe_old_nickname: ?[]const u8,
new_nickname: []const u8,
) !void {
_ = self._users.insert(new_nickname, user) catch |err| {
warn(
"Failed to insert user '{}' in the named user set: {}.\n",
.{ E(new_nickname), @errorName(err) },
);
return err;
};
if (maybe_old_nickname) |old_nickname| {
const user_iter = self._users.find(old_nickname);
assert(user_iter.valid());
self._users.remove(user_iter);
}
}
/// Find a user that has a specified nickname.
fn lookupUser(self: *Server, name: []const u8) ?*User {
const user_iter = self._users.find(name);
return if (user_iter.valid()) user_iter.value() else null;
}
/// Create a new channel with a specified name.
fn createChannel(self: *Server, name: []const u8) !void {
const channel = try Channel.create(name, self);
errdefer channel.destroy();
const channel_iter = self._channels.insert(channel.getName(), channel) catch |err| {
warn(
"Failed to insert channel '{}' in the main channel set: {}.\n",
.{ E(name), @errorName(err) },
);
return err;
};
}
/// Find a channel that has a specified name.
fn lookupChannel(self: *Server, name: []const u8) ?*Channel {
const channel_iter = self._channels.find(name);
return if (channel_iter.valid()) channel_iter.value() else null;
}
/// Create a new local bot with a specified name.
fn createLocalBot(
self: *Server,
nickname: []const u8,
channels_target: u8,
channels_leave_rate: f32,
message_rate: f32,
message_length: u8,
) !void {
const local_bot = try LocalBot.create(
nickname,
channels_target,
channels_leave_rate,
message_rate,
message_length,
self,
);
errdefer local_bot.destroy();
const local_bot_iter = self._local_bots.insert(local_bot, {}) catch |err| {
warn(
"Failed to insert local bot '{}' in the main local bot set: {}.\n",
.{ E(nickname), @errorName(err) },
);
return err;
};
errdefer self._local_bots.remove(local_bot_iter);
// Perform the registration process.
try local_bot.register_NICK(nickname);
try local_bot.register_USER(nickname, nickname);
// Run the initial tick.
local_bot.tick();
}
};
/// Select a random number from a specified range.
fn selectFromConfigRange(rng: *rand.Random, comptime T: type, range: *const config.Range(T)) T {
switch (T) {
u8 => {
return rng.intRangeAtMost(u8, range.min, range.max);
},
f32 => {
return range.min + (range.max - range.min) * rng.float(f32);
},
else => @compileError("Unhandled select type"),
}
}
pub fn main() u8 {
// Ignore SIGPIPE.
const sa = os.Sigaction{
.sigaction = os.linux.SIG_IGN,
.mask = os.empty_sigset,
.flags = 0,
};
os.sigaction(os.SIGPIPE, &sa, null);
// Get an allocator.
var gp_allocator = std.heap.GeneralPurposeAllocator(.{}){};
defer if (gp_allocator.deinit()) {
warn("Memory leaks detected on exit.\n", .{});
};
// Initialize a random number generator.
var rand_buffer: [8]u8 = undefined;
std.crypto.randomBytes(rand_buffer[0..]) catch |err| {
warn(
"Failed to obtain random bytes to initialize a random number generator: {}.\n",
.{@errorName(err)},
);
return 1;
};
const seed = mem.readIntLittle(u64, rand_buffer[0..8]);
var prng = rand.DefaultPrng.init(seed);
// Create the server.
const server = Server.create(
config.address,
&config.word_bank,
&gp_allocator.allocator,
&prng.random,
) catch return 1;
defer server.destroy();
// Create pre-defined channels.
for (config.channels) |channel| {
server.createChannel(channel) catch return 1;
}
// Create artificial users.
const rng = &prng.random;
for (config.local_bots) |local_bot| {
server.createLocalBot(
local_bot,
selectFromConfigRange(rng, u8, &config.bot_channels_target),
selectFromConfigRange(rng, f32, &config.bot_channels_leave_rate),
selectFromConfigRange(rng, f32, &config.bot_message_rate),
selectFromConfigRange(rng, u8, &config.bot_message_length),
) catch return 1;
}
// Run the server.
server.run() catch return 1;
return 0;
} | src/main.zig |
const builtin = @import("builtin");
const build_options = @import("build_options");
const std = @import("std");
const json = std.json;
const log = std.log;
const fs = std.fs;
const Sha1 = std.crypto.hash.Sha1;
const Base64 = std.base64.url_safe_no_pad.Encoder;
// Foilz Archive Util
const foilz = @import("archiver.zig");
// Maint utils
const logger = @import("logger.zig");
const maint = @import("maintenance.zig");
const shutil = @import("shutil.zig");
const win_asni = @cImport(@cInclude("win_ansi_fix.h"));
// Install dir suffix
const install_suffix = ".tinfoil";
const plugin = @import("burrito_plugin");
const metadata = @import("metadata.zig");
const MetaStruct = metadata.MetaStruct;
// Payload
pub const FOILZ_PAYLOAD = @embedFile("../payload.foilz.gz");
pub const RELEASE_METADATA_JSON = @embedFile("../_metadata.json");
// Memory allocator
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
var allocator = &arena.allocator;
pub fn main() anyerror!void {
log.debug("Size of embedded payload is: {}", .{FOILZ_PAYLOAD.len});
// If this is not a production build, we always want a clean install
const wants_clean_install = !build_options.IS_PROD;
const meta = metadata.parse(allocator, RELEASE_METADATA_JSON).?;
const install_dir = (try get_install_dir(&meta))[0..];
const metadata_path = try fs.path.join(allocator, &[_][]const u8{ install_dir, "_metadata.json" });
log.debug("Install Directory: {s}", .{install_dir});
log.debug("Metadata path: {s}", .{metadata_path});
// Ensure the destination directory is created
try std.fs.cwd().makePath(install_dir);
// If the metadata file exists, don't install again
var needs_install: bool = false;
std.fs.accessAbsolute(metadata_path, .{}) catch |err| {
if (err == error.FileNotFound) {
needs_install = true;
} else {
log.crit("We failed to open the destination directory with an unexpected error: {s}", .{err});
return;
}
};
// Get argvs
const args = try std.process.argsAlloc(allocator);
const args_trimmed = args[1..];
defer std.process.argsFree(allocator, args);
const args_string = try std.mem.join(allocator, " ", args_trimmed);
log.debug("Passing args string: {s}", .{args_string});
// Execute plugin code
plugin.burrito_plugin_entry(install_dir, RELEASE_METADATA_JSON);
// If we need an install, install the payload onto the target machine
if (needs_install or wants_clean_install) {
try do_payload_install(install_dir, metadata_path);
} else {
log.debug("Skipping archive unpacking, this machine already has the app installed!", .{});
}
// Check for maintenance commands
if (args_trimmed.len > 0 and std.mem.eql(u8, args_trimmed[0], "maintenance")) {
try logger.info("Entering burrito maintenance mode...", .{});
try logger.info("Build metadata: {s}", .{RELEASE_METADATA_JSON});
try maint.do_maint(args_trimmed[1..], install_dir);
return;
}
// Clean up older versions
const base_install_path = try get_base_install_dir();
try maint.do_clean_old_versions(base_install_path, install_dir);
// Get Env
var env_map = try std.process.getEnvMap(allocator);
// Add _IS_TTY env variable
if (shutil.is_tty()) {
try env_map.put("_IS_TTY", "1");
} else {
try env_map.put("_IS_TTY", "0");
}
// Get name of the exe (useful to pass into argv for the child erlang process)
const exe_path = try fs.selfExePathAlloc(allocator);
const exe_name = fs.path.basename(exe_path);
// Compute the full base bin path
const base_bin_path = try fs.path.join(allocator, &[_][]const u8{ install_dir, "bin", build_options.RELEASE_NAME });
log.debug("Base Executable Path: {s}", .{base_bin_path});
// Windows does not have a REAL execve, so instead the wrapper will hang around while the Erlang process runs
// We'll use a ChildProcess with stdin and out being inherited
if (builtin.os.tag == .windows) {
// Fix up Windows 10+ consoles having ANSI escape support, but only if we set some flags
win_asni.enable_virtual_term();
const bat_path = try std.mem.concat(allocator, u8, &[_][]const u8{ base_bin_path, ".bat" });
const win_args = &[_][]const u8{ bat_path, "start", exe_name };
const final_args = try std.mem.concat(allocator, []const u8, &.{ win_args, args_trimmed });
const win_child_proc = try std.ChildProcess.init(final_args, allocator);
win_child_proc.env_map = &env_map;
win_child_proc.stdout_behavior = .Inherit;
win_child_proc.stdin_behavior = .Inherit;
log.debug("CLI List: {s}", .{final_args});
_ = try win_child_proc.spawnAndWait();
} else {
const cli = &[_][]const u8{ base_bin_path, "start", exe_name, args_string };
log.debug("CLI List: {s}", .{cli});
return std.process.execve(allocator, cli, &env_map);
}
}
fn do_payload_install(install_dir: []const u8, metadata_path: []const u8) !void {
// Unpack the files
try foilz.unpack_files(FOILZ_PAYLOAD, install_dir);
// Write metadata file
const file = try fs.createFileAbsolute(metadata_path, .{ .truncate = true });
try file.writeAll(RELEASE_METADATA_JSON);
}
fn get_base_install_dir() ![]u8 {
return try fs.getAppDataDir(allocator, install_suffix);
}
fn get_install_dir(meta: *const MetaStruct) ![]u8 {
// Combine the hash of the payload and a base dir to get a safe install directory
const base_install_path = try get_base_install_dir();
// Parse the ERTS version and app version from the metadata JSON string
const dir_name = try std.fmt.allocPrint(allocator, "{s}_erts-{s}_{s}", .{ build_options.RELEASE_NAME, meta.erts_version, meta.app_version });
// Ensure that base directory is created
std.os.mkdir(base_install_path, 0o755) catch {};
// Construct the full app install path
const name = try fs.path.join(allocator, &[_][]const u8{ install_suffix, dir_name });
return fs.getAppDataDir(allocator, name);
} | src/wrapper.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const print = std.debug.print;
const input = @embedFile("../input/day19.txt");
var rules: [133][]const u8 = undefined;
const Key = struct {
start: usize,
len: usize,
rule: usize,
};
var cache: std.AutoHashMap(Key, bool) = undefined;
fn matchSeq(message: []const u8, start: usize, rule_seq: []const u8) bool {
if (message.len == 0 and rule_seq.len == 0) return true;
if (message.len == 0 or rule_seq.len == 0) return false;
var t = std.mem.tokenize(rule_seq, " ");
const rule_no = std.fmt.parseUnsigned(usize, t.next().?, 10) catch unreachable;
const rule_rest = t.rest();
var i: usize = 1;
while (i <= message.len) : (i += 1) {
const b = match(message[0..i], start, rule_no);
if (b and matchSeq(message[i..], start + i, rule_rest)) {
return true;
}
}
return false;
}
fn match(message: []const u8, start: usize, rule_no: usize) bool {
if (cache.get(Key{.start = start, .len = message.len, .rule = rule_no})) |ret|
return ret;
var ret = false;
const rule = rules[rule_no];
if (rule[0] == '"') {
ret = message[0] == rule[1] and message.len == 1;
} else {
var options = std.mem.split(rule, " | ");
while (options.next()) |rule_seq| {
if (matchSeq(message, start, rule_seq)) {
ret = true;
break;
}
}
}
cache.put(Key{.start = start, .len = message.len, .rule = rule_no}, ret) catch unreachable;
return ret;
}
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var allocator = &gpa.allocator;
cache = std.AutoHashMap(Key, bool).init(allocator);
defer cache.deinit();
var s = std.mem.split(input, "\n\n");
var rules_block = s.next().?;
var message_block = s.next().?;
var lines = std.mem.tokenize(rules_block, "\n");
while (lines.next()) |line| {
const colon_pos = std.mem.indexOfScalar(u8, line, ':').?;
const rule_no = try std.fmt.parseUnsigned(usize, line[0..colon_pos], 10);
rules[rule_no] = line[colon_pos+2..];
}
var part: usize = 1;
while (part <= 2) : (part += 1) {
if (part == 2) {
rules[8] = "42 | 42 8";
rules[11] = "42 31 | 42 11 31";
}
var matches: usize = 0;
var messages = std.mem.tokenize(message_block, "\n");
while (messages.next()) |message| {
cache.clearRetainingCapacity();
if (match(message, 0, 0)) matches += 1;
}
print("part{}: {}\n", .{part, matches});
}
} | src/day19.zig |
const Self = @This();
const std = @import("std");
const zt = @import("zt");
const ig = @import("imgui");
const sling = @import("sling.zig");
/// Do not manipulate this directly, instead used the setX methods provided.
position: sling.math.Vec2 = .{},
/// Do not manipulate this directly, instead used the setX methods provided.
rotation: f32 = 0,
/// Do not manipulate this directly, instead used the setX methods provided.
zoom: f32 = 1.0,
/// Do not manipulate this directly, instead used the setX methods provided.
origin: sling.math.Vec2 = .{ .x = 0.5, .y = 0.5 },
/// Do not manipulate this directly, instead used the setX methods provided.
viewMatrix: sling.math.Mat4 = sling.math.Mat4.identity,
/// Do not manipulate this directly, instead used the setX methods provided.
inverseViewMatrix: sling.math.Mat4 = sling.math.Mat4.identity,
/// Do not manipulate this directly, instead used the setX methods provided.
projectionMatrix: sling.math.Mat4 = sling.math.Mat4.identity,
/// If you want this to be re-evaluated you can set this to true, and
/// viewMatrix, inverseViewMatrix, and projectionMatrix will all
/// be recalculated.
dirty: bool = true,
/// Unused for now, but eventually will be used to render your game into
/// a separate rendertarget, or into an imgui window.
sizeOverride: ?sling.math.Vec2 = null,
/// Do not manipulate this directly, is for internal state. Prefer to use `ig.igGetIO().*.DisplaySize`
currentSize: sling.math.Vec2 = .{},
pub fn init() Self {
var value: Self = .{};
value.position.x = -100;
value.recalc();
return value;
}
inline fn getSize(self: Self) sling.math.Vec2 {
if (self.sizeOverride) |override| {
return override;
}
var io = ig.igGetIO();
return io.*.DisplaySize;
}
pub inline fn recalc(self: *Self) void {
var targetSize = self.getSize();
// Projection recalc
if (self.currentSize.x != targetSize.x or self.currentSize.y != targetSize.y) {
self.projectionMatrix = sling.math.Mat4.createOrthogonal(0, targetSize.x, targetSize.y, 0, -128, 128);
self.currentSize = targetSize;
self.dirty = true;
}
if (self.dirty) {
self.viewMatrix = sling.math.Mat4.batchMul(&.{
sling.math.Mat4.createTranslationXYZ(-self.position.x, -self.position.y, 0), // translate
sling.math.Mat4.createZRotation(self.rotation), // Rotation
sling.math.Mat4.createScale(self.zoom, self.zoom, 1.0), // Scale
sling.math.Mat4.createTranslationXYZ(self.currentSize.x * self.origin.x, self.currentSize.y * self.origin.y, 0), // center
});
if (self.viewMatrix.invert()) |inverted| {
self.inverseViewMatrix = inverted;
} else {
std.log.err("Camera failed to inverse view matrix:\n{any}", .{self.viewMatrix});
}
self.dirty = false;
}
}
pub fn setPosition(self: *Self, target: sling.math.Vec2) void {
if (target.x == self.position.x and target.y == self.position.y) {
return;
}
self.dirty = true;
self.position = target;
}
pub fn setZoom(self: *Self, target: f32) void {
if (target == self.zoom) {
return;
}
self.dirty = true;
self.zoom = target;
}
pub fn setRotation(self: *Self, target: sling.math.Vec2) void {
if (target.x == self.position.x and target.y == self.position.y) {
return;
}
self.dirty = true;
self.position = target;
}
/// Translates a world coordinate into the corresponding point in screenspace.
/// Useful to align user interface items over top of a world item.
pub fn worldToScreen(self: *Self, point: zt.math.Vec2) zt.math.Vec2 {
return point.transform4(self.viewMatrix);
}
/// Translates a screen coordinate into the corresponding point in worldspace.
/// Useful for casting the mouse/interface position into world coords.
pub fn screenToWorld(self: *Self, point: zt.math.Vec2) zt.math.Vec2 {
return point.transform4(self.inverseViewMatrix);
} | src/camera.zig |
const std = @import("std");
pub fn build(b: *std.build.Builder) void {
// 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("main", "main.zig");
const exe_opt = b.addOptions();
exe.addOptions("build_options", exe_opt);
// To be updated - options will not work as expected
exe_opt.addOption(bool, "debugCmd", false);
exe_opt.addOption(bool, "debugDisp", false);
exe_opt.addOption(bool, "debugLoop", false);
exe_opt.addOption(bool, "debugStart", false);
exe_opt.addOption(bool, "debugStages", false);
const pipes_pkg: std.build.Pkg = .{
.name = "pipes",
.path = .{ .path = "./pipes.zig" },
.dependencies = &.{exe_opt.getPackage("build_options")},
};
const filters_pkg: std.build.Pkg = .{
.name = "filters",
.path = .{ .path = "./filters.zig" },
.dependencies = &.{exe_opt.getPackage("build_options")},
//.dependencies = &.{exe_opt.getPackage("build_options"), pipes_pkg},
};
exe.addPackage(pipes_pkg);
exe.addPackage(filters_pkg);
exe.setTarget(target); // best for this cpu
//exe.setTarget(.{ // generic x86_64 - about 8% slower on my box
// .cpu_arch = .x86_64,
// .os_tag = .linux,
// .abi = .gnu,
// .cpu_model = .baseline, // .baseline encompasses more old cpus
//});
exe.setBuildMode(mode);
//exe.pie = true;
//exe.setBuildMode(std.builtin.Mode.ReleaseFast); // to hard code ReleaseFast/ReleaseSafe etc
exe.setOutputDir(".");
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);
} | build.zig |
const std = @import("std");
const hyperia = @import("hyperia.zig");
const mem = std.mem;
const mpmc = hyperia.mpmc;
const testing = std.testing;
pub fn ObjectPool(comptime T: type, comptime capacity: comptime_int) type {
return struct {
const Self = @This();
queue: mpmc.Queue(*T, capacity) align(mpmc.cache_line_length),
head: [*]T align(mpmc.cache_line_length),
pub fn init(allocator: *mem.Allocator) !Self {
var queue = try mpmc.Queue(*T, capacity).init(allocator);
errdefer queue.deinit(allocator);
const items = try allocator.create([capacity]T);
errdefer allocator.destroy(items);
for (items) |*item| if (!queue.tryPush(item)) unreachable;
return Self{ .queue = queue, .head = items };
}
pub fn deinit(self: *Self, allocator: *mem.Allocator) void {
allocator.destroy(@ptrCast(*const [capacity]T, self.head));
self.queue.deinit(allocator);
}
pub fn acquire(self: *Self, allocator: *mem.Allocator) !*T {
if (self.queue.tryPop()) |item| {
return item;
}
return try allocator.create(T);
}
pub fn release(self: *Self, allocator: *mem.Allocator, item: *T) void {
if (@ptrToInt(item) >= @ptrToInt(self.head) and @ptrToInt(item) <= @ptrToInt(self.head + capacity - 1)) {
while (true) {
if (self.queue.tryPush(item)) {
break;
}
}
return;
}
allocator.destroy(item);
}
};
}
test {
testing.refAllDecls(ObjectPool(u8, 16));
}
test "object_pool: test invariants" {
const allocator = testing.allocator;
var pool = try ObjectPool(u8, 2).init(allocator);
defer pool.deinit(allocator);
const a = try pool.acquire(allocator);
const b = try pool.acquire(allocator);
const c = try pool.acquire(allocator);
pool.release(allocator, c);
pool.release(allocator, b);
pool.release(allocator, a);
} | object_pool.zig |
const arduino = @import("arduino");
const std = @import("std");
const dht = arduino.lib.dht;
// Necessary, and has the side effect of pulling in the needed _start method
pub const panic = arduino.start.panicLogUart;
// until the compilert works, code from __udivmodhi4:
fn udivmod(_num: u16, _den: u16) struct { div: u16, rem: u16 } {
var num = _num;
var den = _den;
var bit: u16 = 1;
var res: u16 = 0;
while (den < num and (bit != 0) and (den & (@as(u16, 1) << 15)) == 0) {
den <<= 1;
bit <<= 1;
}
while (bit != 0) {
if (num >= den) {
num -= den;
res |= bit;
}
bit >>= 1;
den >>= 1;
}
return .{ .div = res, .rem = num };
}
fn printNumToBuf(num_x10: i16, buf: *[16]u8) []u8 {
var v: u16 = if (num_x10 > 0) @intCast(u16, num_x10) else @intCast(u16, -num_x10);
var idx: u8 = 0;
while (v > 0) {
const next = udivmod(v, 10);
v = next.div;
buf[(buf.len - 1) - idx] = '0' + @intCast(u8, next.rem);
if (idx == 0) {
buf[(buf.len - 2)] = '.';
idx = 2;
} else {
idx += 1;
}
}
if (num_x10 < 0) {
buf[(buf.len - 1) - idx] = '-';
idx += 1;
}
return buf[buf.len - idx ..];
}
pub fn main() void {
arduino.uart.init(arduino.cpu.CPU_FREQ, 115200);
const sensor1 = dht.DHT22(8);
const sensor2 = dht.DHT22(7);
const sensor_names = [_][]const u8{ "sensor #1", "sensor #2" };
while (true) {
const measures = [_]dht.Readout{
sensor1.read(),
sensor2.read(),
};
for (measures) |measure, idx| {
switch (measure.err) {
.OK => {},
.BAD_CHECKSUM => @panic("BAD_CHECKSUM"),
.NO_CONNECTION => @panic("NO_CONNECTION"),
.NO_ACK => @panic("NO_ACK"),
.INTERRUPTED => @panic("INTERRUPTED"),
}
arduino.uart.write(sensor_names[idx]);
arduino.uart.write(": ");
var work_buffer: [16]u8 = undefined;
//const msg = std.fmt.bufPrint(&work_buffer, "t={}\n", .{measure.temperature_x10}) catch unreachable; -- fails because of (at least) error unions
arduino.uart.write(printNumToBuf(measure.humidity_x10, &work_buffer));
arduino.uart.write("%, ");
arduino.uart.write(printNumToBuf(measure.temperature_x10, &work_buffer));
arduino.uart.write("°C\n");
}
arduino.cpu.delayMilliseconds(2000); // "the interval of whole process must beyond 2 seconds."
}
} | examples/dht22_to_uart.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const meta = std.meta;
const trait = std.meta.trait;
const assert = std.debug.assert;
const testing = std.testing;
const mustache = @import("../mustache.zig");
const RenderOptions = mustache.options.RenderOptions;
const Delimiters = mustache.Delimiters;
const Element = mustache.Element;
const rendering = @import("rendering.zig");
const lambda = @import("lambda.zig");
const LambdaContext = lambda.LambdaContext;
const invoker = @import("invoker.zig");
const Fields = invoker.Fields;
const FlattenedType = invoker.FlattenedType;
const map = @import("partials_map.zig");
pub fn PathResolution(comptime Payload: type) type {
return union(enum) {
/// The path could no be found on the current context
/// This result indicates that the path should be resolved against the parent context
/// For example:
/// context = .{ name = "Phill" };
/// path = "address"
NotFoundInContext,
/// Parts of the path could not be found on the current context.
/// This result indicates that the path is broken and should NOT be resolved against the parent context
/// For example:
/// context = .{ .address = .{ street = "Wall St, 50", } };
/// path = "address.country"
ChainBroken,
/// The path could be resolved against the current context, but the iterator was fully consumed
/// This result indicates that the path is valid, but not to be rendered and should NOT be resolved against the parent context
/// For example:
/// context = .{ .visible = false };
/// path = "visible"
IteratorConsumed,
/// The lambda could be resolved against the current context,
/// The payload is the result returned by "action_fn"
Lambda: Payload,
/// The field could be resolved against the current context
/// The payload is the result returned by "action_fn"
Field: Payload,
};
}
pub const Escape = enum {
Escaped,
Unescaped,
};
pub fn getContext(comptime Writer: type, data: anytype, comptime PartialsMap: type, comptime options: RenderOptions) Context: {
const Data = @TypeOf(data);
const by_value = Fields.byValue(Data);
if (!by_value and !trait.isSingleItemPtr(Data)) @compileError("Expected a pointer to " ++ @typeName(Data));
const RenderEngine = rendering.RenderEngine(Writer, PartialsMap, options);
break :Context RenderEngine.Context;
} {
const Impl = ContextImpl(Writer, @TypeOf(data), PartialsMap, options);
return Impl.context(data);
}
pub fn Context(comptime Writer: type, comptime PartialsMap: type, comptime options: RenderOptions) type {
const RenderEngine = rendering.RenderEngine(Writer, PartialsMap, options);
const DataRender = RenderEngine.DataRender;
return struct {
const Self = @This();
pub const ContextStack = struct {
parent: ?*const @This(),
ctx: Self,
};
const VTable = struct {
get: fn (*const anyopaque, Element.Path, ?usize) PathResolution(Self),
capacityHint: fn (*const anyopaque, *DataRender, Element.Path) PathResolution(usize),
interpolate: fn (*const anyopaque, *DataRender, Element.Path, Escape) (Allocator.Error || Writer.Error)!PathResolution(void),
expandLambda: fn (*const anyopaque, *DataRender, Element.Path, []const u8, Escape, Delimiters) (Allocator.Error || Writer.Error)!PathResolution(void),
};
pub const Iterator = struct {
data: union(enum) {
Empty,
Lambda: Self,
Sequence: struct {
context: *const Self,
path: Element.Path,
state: union(enum) {
Fetching: struct {
item: Self,
index: usize,
},
Finished,
},
fn fetch(self: *@This(), index: usize) ?Self {
const result = self.context.vtable.get(
&self.context.ctx,
self.path,
index,
);
return switch (result) {
.Field => |item| item,
.IteratorConsumed => null,
else => {
assert(false);
unreachable;
},
};
}
},
},
fn initEmpty() Iterator {
return .{
.data = .Empty,
};
}
fn initLambda(lambda_ctx: Self) Iterator {
return .{
.data = .{
.Lambda = lambda_ctx,
},
};
}
fn initSequence(parent_ctx: *const Self, path: Element.Path, item: Self) Iterator {
return .{
.data = .{
.Sequence = .{
.context = parent_ctx,
.path = path,
.state = .{
.Fetching = .{
.item = item,
.index = 0,
},
},
},
},
};
}
pub fn lambda(self: Iterator) ?Self {
return switch (self.data) {
.Lambda => |item| item,
else => null,
};
}
pub inline fn truthy(self: Iterator) bool {
switch (self.data) {
.Empty => return false,
.Lambda => return true,
.Sequence => |sequence| switch (sequence.state) {
.Fetching => return true,
.Finished => return false,
},
}
}
pub fn next(self: *Iterator) ?Self {
switch (self.data) {
.Lambda, .Empty => return null,
.Sequence => |*sequence| switch (sequence.state) {
.Fetching => |current| {
const next_index = current.index + 1;
if (sequence.fetch(next_index)) |item| {
sequence.state = .{
.Fetching = .{
.item = item,
.index = next_index,
},
};
} else {
sequence.state = .Finished;
}
return current.item;
},
.Finished => return null,
},
}
}
};
ctx: FlattenedType = undefined,
vtable: *const VTable,
pub inline fn get(self: Self, path: Element.Path) PathResolution(Self) {
return self.vtable.get(&self.ctx, path, null);
}
pub inline fn capacityHint(
self: Self,
data_render: *DataRender,
path: Element.Path,
) PathResolution(usize) {
return self.vtable.capacityHint(&self.ctx, data_render, path);
}
pub fn iterator(self: *const Self, path: Element.Path) PathResolution(Iterator) {
const result = self.vtable.get(&self.ctx, path, 0);
return switch (result) {
.Field => |item| .{
.Field = Iterator.initSequence(self, path, item),
},
.IteratorConsumed => .{
.Field = Iterator.initEmpty(),
},
.Lambda => |item| .{
.Field = Iterator.initLambda(item),
},
.ChainBroken => .ChainBroken,
.NotFoundInContext => .NotFoundInContext,
};
}
pub inline fn interpolate(
self: Self,
data_render: *DataRender,
path: Element.Path,
escape: Escape,
) (Allocator.Error || Writer.Error)!PathResolution(void) {
return try self.vtable.interpolate(&self.ctx, data_render, path, escape);
}
pub inline fn expandLambda(
self: Self,
data_render: *DataRender,
path: Element.Path,
inner_text: []const u8,
escape: Escape,
delimiters: Delimiters,
) (Allocator.Error || Writer.Error)!PathResolution(void) {
return try self.vtable.expandLambda(&self.ctx, data_render, path, inner_text, escape, delimiters);
}
};
}
fn ContextImpl(comptime Writer: type, comptime Data: type, comptime PartialsMap: type, comptime options: RenderOptions) type {
const RenderEngine = rendering.RenderEngine(Writer, PartialsMap, options);
const ContextInterface = RenderEngine.Context;
const DataRender = RenderEngine.DataRender;
const Invoker = RenderEngine.Invoker;
return struct {
const vtable = ContextInterface.VTable{
.get = get,
.capacityHint = capacityHint,
.interpolate = interpolate,
.expandLambda = expandLambda,
};
const is_zero_size = @sizeOf(Data) == 0;
const Self = @This();
pub fn context(data: Data) ContextInterface {
var interface = ContextInterface{
.vtable = &vtable,
};
if (!is_zero_size) {
if (comptime @sizeOf(Data) > @sizeOf(FlattenedType)) @compileError(std.fmt.comptimePrint("Type {s} size {} exceeds the maxinum by-val size of {}", .{ @typeName(Data), @sizeOf(Data), @sizeOf(FlattenedType) }));
var ptr = @ptrCast(*Data, @alignCast(@alignOf(Data), &interface.ctx));
ptr.* = data;
}
return interface;
}
fn get(ctx: *const anyopaque, path: Element.Path, index: ?usize) PathResolution(ContextInterface) {
return Invoker.get(
getData(ctx),
path,
index,
);
}
fn capacityHint(
ctx: *const anyopaque,
data_render: *DataRender,
path: Element.Path,
) PathResolution(usize) {
return Invoker.capacityHint(
data_render,
getData(ctx),
path,
);
}
fn interpolate(
ctx: *const anyopaque,
data_render: *DataRender,
path: Element.Path,
escape: Escape,
) (Allocator.Error || Writer.Error)!PathResolution(void) {
return try Invoker.interpolate(
data_render,
getData(ctx),
path,
escape,
);
}
fn expandLambda(
ctx: *const anyopaque,
data_render: *DataRender,
path: Element.Path,
inner_text: []const u8,
escape: Escape,
delimiters: Delimiters,
) (Allocator.Error || Writer.Error)!PathResolution(void) {
return try Invoker.expandLambda(
data_render,
getData(ctx),
inner_text,
escape,
delimiters,
path,
);
}
inline fn getData(ctx: *const anyopaque) Data {
return if (is_zero_size) undefined else (@ptrCast(*const Data, @alignCast(@alignOf(Data), ctx))).*;
}
};
}
test {
_ = invoker;
_ = lambda;
_ = struct_tests;
}
const struct_tests = struct {
// Test model
const Item = struct {
name: []const u8,
value: f32,
};
const Person = struct {
// Fields
id: u32,
name: []const u8,
address: struct {
street: []const u8,
region: enum { EU, US, RoW },
zip: u64,
contacts: struct {
phone: []const u8,
email: []const u8,
},
coordinates: struct {
lon: f64,
lat: f64,
},
},
items: []const Item,
salary: f32,
indication: ?*Person,
active: bool,
additional_information: ?[]const u8,
counter: usize = 0,
buffer: [32]u8 = undefined,
// Lambdas
pub fn staticLambda(ctx: LambdaContext) !void {
try ctx.write("1");
}
pub fn selfLambda(self: Person, ctx: LambdaContext) !void {
try ctx.writeFormat("{}", .{self.name.len});
}
pub fn selfConstPtrLambda(self: *const Person, ctx: LambdaContext) !void {
try ctx.writeFormat("{}", .{self.name.len});
}
pub fn selfMutPtrLambda(self: *Person, ctx: LambdaContext) !void {
self.counter += 1;
try ctx.writeFormat("{}", .{self.counter});
}
pub fn willFailStaticLambda(ctx: LambdaContext) error{Expected}!void {
_ = ctx;
return error.Expected;
}
pub fn willFailSelfLambda(self: Person, ctx: LambdaContext) error{Expected}!void {
_ = self;
ctx.write("unfinished") catch unreachable;
return error.Expected;
}
pub fn anythingElse(int: i32) u32 {
_ = int;
return 42;
}
};
fn getPerson() Person {
var person_1 = testing.allocator.create(Person) catch unreachable;
person_1.* = Person{
.id = 1,
.name = "<NAME>",
.address = .{
.street = "far away street",
.region = .EU,
.zip = 99450,
.contacts = .{
.phone = "555-9090",
.email = "<EMAIL>",
},
.coordinates = .{
.lon = 41.40338,
.lat = 2.17403,
},
},
.items = &[_]Item{
.{ .name = "just one item", .value = 0.01 },
},
.salary = 75.00,
.indication = null,
.active = false,
.additional_information = null,
};
var person_2 = Person{
.id = 2,
.name = "<NAME>",
.address = .{
.street = "nearby",
.region = .RoW,
.zip = 333900,
.contacts = .{
.phone = "555-9191",
.email = "<EMAIL>",
},
.coordinates = .{
.lon = 38.71471,
.lat = -9.13872,
},
},
.items = &[_]Item{
.{ .name = "item 1", .value = 100 },
.{ .name = "item 2", .value = 200 },
},
.salary = 140.00,
.indication = person_1,
.active = true,
.additional_information = "someone was here",
};
return person_2;
}
const dummy_options = RenderOptions{ .Text = .{} };
const DummyPartialsMap = map.PartialsMap(void, dummy_options);
const DummyParser = @import("../parsing/parser.zig").Parser(.{ .source = .{ .String = .{ .copy_strings = false } }, .output = .Render, .load_mode = .runtime_loaded });
const dummy_map = DummyPartialsMap.init({});
fn expectPath(allocator: Allocator, path: []const u8) !Element.Path {
var parser = try DummyParser.init(allocator, "", .{});
defer parser.deinit();
return try parser.parsePath(path);
}
fn interpolate(writer: anytype, data: anytype, path: []const u8) anyerror!void {
const Data = @TypeOf(data);
const by_value = comptime Fields.byValue(Data);
const Writer = @TypeOf(writer);
var ctx = getContext(Writer, if (by_value) data else @as(*const Data, &data), DummyPartialsMap, dummy_options);
try interpolateCtx(writer, ctx, path, .Unescaped);
}
fn interpolateCtx(writer: anytype, ctx: Context(@TypeOf(writer), DummyPartialsMap, dummy_options), identifier: []const u8, escape: Escape) anyerror!void {
const RenderEngine = rendering.RenderEngine(@TypeOf(writer), DummyPartialsMap, dummy_options);
var stack = RenderEngine.ContextStack{
.parent = null,
.ctx = ctx,
};
var data_render = RenderEngine.DataRender{
.stack = &stack,
.out_writer = .{ .Writer = writer },
.partials_map = undefined,
.indentation_queue = undefined,
.template_options = {},
};
var path = try expectPath(testing.allocator, identifier);
defer Element.destroyPath(testing.allocator, false, path);
switch (try ctx.interpolate(&data_render, path, escape)) {
.Lambda => {
_ = try ctx.expandLambda(&data_render, path, "", escape, .{});
},
else => {},
}
}
test "Write Int" {
const allocator = testing.allocator;
var list = std.ArrayList(u8).init(allocator);
defer list.deinit();
var person = getPerson();
defer if (person.indication) |indication| allocator.destroy(indication);
var writer = list.writer();
// Direct access
try interpolate(writer, person, "id");
try testing.expectEqualStrings("2", list.items);
list.clearAndFree();
// Ref access
try interpolate(writer, &person, "id");
try testing.expectEqualStrings("2", list.items);
list.clearAndFree();
// Nested access
try interpolate(writer, person, "address.zip");
try testing.expectEqualStrings("333900", list.items);
list.clearAndFree();
// Nested pointer access
try interpolate(writer, person, "indication.address.zip");
try testing.expectEqualStrings("99450", list.items);
list.clearAndFree();
// Nested Ref access
try interpolate(writer, &person, "address.zip");
try testing.expectEqualStrings("333900", list.items);
list.clearAndFree();
// Nested Ref pointer access
try interpolate(writer, &person, "indication.address.zip");
try testing.expectEqualStrings("99450", list.items);
}
test "Write Float" {
const allocator = testing.allocator;
var list = std.ArrayList(u8).init(allocator);
defer list.deinit();
var person = getPerson();
defer if (person.indication) |indication| allocator.destroy(indication);
var writer = list.writer();
// Direct access
try interpolate(writer, person, "salary");
try testing.expectEqualStrings("140", list.items);
list.clearAndFree();
// Ref access
try interpolate(writer, &person, "salary");
try testing.expectEqualStrings("140", list.items);
list.clearAndFree();
// Nested access
try interpolate(writer, person, "address.coordinates.lon");
try testing.expectEqualStrings("38.71471", list.items);
list.clearAndFree();
// Negative values
try interpolate(writer, person, "address.coordinates.lat");
try testing.expectEqualStrings("-9.13872", list.items);
list.clearAndFree();
// Nested pointer access
try interpolate(writer, person, "indication.address.coordinates.lon");
try testing.expectEqualStrings("41.40338", list.items);
list.clearAndFree();
// Nested Ref access
try interpolate(writer, &person, "address.coordinates.lon");
try testing.expectEqualStrings("38.71471", list.items);
list.clearAndFree();
// Negative Ref values
try interpolate(writer, &person, "address.coordinates.lat");
try testing.expectEqualStrings("-9.13872", list.items);
list.clearAndFree();
// Nested Ref pointer access
try interpolate(writer, &person, "indication.address.coordinates.lon");
try testing.expectEqualStrings("41.40338", list.items);
}
test "Write String" {
const allocator = testing.allocator;
var list = std.ArrayList(u8).init(allocator);
defer list.deinit();
var person = getPerson();
defer if (person.indication) |indication| allocator.destroy(indication);
var writer = list.writer();
// Direct access
try interpolate(writer, person, "name");
try testing.expectEqualStrings("Someone Jr", list.items);
list.clearAndFree();
// Ref access
try interpolate(writer, &person, "name");
try testing.expectEqualStrings("Someone Jr", list.items);
list.clearAndFree();
// Direct Len access
try interpolate(writer, person, "name.len");
try testing.expectEqualStrings("10", list.items);
list.clearAndFree();
// Direct Ref Len access
try interpolate(writer, &person, "name.len");
try testing.expectEqualStrings("10", list.items);
list.clearAndFree();
// Nested access
try interpolate(writer, person, "address.street");
try testing.expectEqualStrings("nearby", list.items);
list.clearAndFree();
// Nested pointer access
try interpolate(writer, person, "indication.address.street");
try testing.expectEqualStrings("far away street", list.items);
list.clearAndFree();
// Nested Ref access
try interpolate(writer, &person, "address.street");
try testing.expectEqualStrings("nearby", list.items);
list.clearAndFree();
// Nested pointer access
try interpolate(writer, &person, "indication.address.street");
try testing.expectEqualStrings("far away street", list.items);
}
test "Write Enum" {
const allocator = testing.allocator;
var list = std.ArrayList(u8).init(allocator);
defer list.deinit();
var person = getPerson();
defer if (person.indication) |indication| allocator.destroy(indication);
var writer = list.writer();
// Direct access
try interpolate(writer, person, "address.region");
try testing.expectEqualStrings("RoW", list.items);
list.clearAndFree();
// Ref access
try interpolate(writer, &person, "address.region");
try testing.expectEqualStrings("RoW", list.items);
list.clearAndFree();
// Nested pointer access
try interpolate(writer, person, "indication.address.region");
try testing.expectEqualStrings("EU", list.items);
list.clearAndFree();
// Nested Ref pointer access
try interpolate(writer, &person, "indication.address.region");
try testing.expectEqualStrings("EU", list.items);
}
test "Write Bool" {
const allocator = testing.allocator;
var list = std.ArrayList(u8).init(allocator);
defer list.deinit();
var person = getPerson();
defer if (person.indication) |indication| allocator.destroy(indication);
var writer = list.writer();
// Direct access
try interpolate(writer, person, "active");
try testing.expectEqualStrings("true", list.items);
list.clearAndFree();
// Ref access
try interpolate(writer, &person, "active");
try testing.expectEqualStrings("true", list.items);
list.clearAndFree();
// Nested pointer access
try interpolate(writer, person, "indication.active");
try testing.expectEqualStrings("false", list.items);
list.clearAndFree();
// Nested Ref pointer access
try interpolate(writer, &person, "indication.active");
try testing.expectEqualStrings("false", list.items);
}
test "Write Nullable" {
const allocator = testing.allocator;
var list = std.ArrayList(u8).init(allocator);
defer list.deinit();
var person = getPerson();
defer if (person.indication) |indication| allocator.destroy(indication);
var writer = list.writer();
// Direct access
try interpolate(writer, person, "additional_information");
try testing.expectEqualStrings("someone was here", list.items);
list.clearAndFree();
// Ref access
try interpolate(writer, &person, "additional_information");
try testing.expectEqualStrings("someone was here", list.items);
list.clearAndFree();
// Null Accress
try interpolate(writer, person.indication, "additional_information");
try testing.expectEqualStrings("", list.items);
list.clearAndFree();
// Null Ref Accress
try interpolate(writer, person.indication, "additional_information");
try testing.expectEqualStrings("", list.items);
list.clearAndFree();
// Nested pointer access
try interpolate(writer, person, "indication.additional_information");
try testing.expectEqualStrings("", list.items);
list.clearAndFree();
// Nested Ref pointer access
try interpolate(writer, &person, "indication.additional_information");
try testing.expectEqualStrings("", list.items);
}
test "Write Not found" {
const allocator = testing.allocator;
var list = std.ArrayList(u8).init(allocator);
defer list.deinit();
var person = getPerson();
defer if (person.indication) |indication| allocator.destroy(indication);
var writer = list.writer();
// Direct access
try interpolate(writer, person, "wrong_name");
try testing.expectEqualStrings("", list.items);
// Nested access
try interpolate(writer, person, "name.wrong_name");
try testing.expectEqualStrings("", list.items);
// Direct Ref access
try interpolate(writer, &person, "wrong_name");
try testing.expectEqualStrings("", list.items);
// Nested Ref access
try interpolate(writer, &person, "name.wrong_name");
try testing.expectEqualStrings("", list.items);
}
test "Lambda - staticLambda" {
const allocator = testing.allocator;
var list = std.ArrayList(u8).init(allocator);
defer list.deinit();
var person = getPerson();
defer if (person.indication) |indication| allocator.destroy(indication);
var writer = list.writer();
// Direct access
try interpolate(writer, person, "staticLambda");
try testing.expectEqualStrings("1", list.items);
list.clearAndFree();
// Ref access
try interpolate(writer, &person, "staticLambda");
try testing.expectEqualStrings("1", list.items);
list.clearAndFree();
// Nested pointer access
try interpolate(writer, person, "indication.staticLambda");
try testing.expectEqualStrings("1", list.items);
list.clearAndFree();
// Nested Ref access
try interpolate(writer, &person, "staticLambda");
try testing.expectEqualStrings("1", list.items);
list.clearAndFree();
// Nested Ref pointer access
try interpolate(writer, &person, "indication.staticLambda");
try testing.expectEqualStrings("1", list.items);
list.clearAndFree();
}
test "Lambda - selfLambda" {
const allocator = testing.allocator;
var list = std.ArrayList(u8).init(allocator);
defer list.deinit();
var person = getPerson();
defer if (person.indication) |indication| allocator.destroy(indication);
var writer = list.writer();
// Direct access
try interpolate(writer, person, "selfLambda");
try testing.expectEqualStrings("10", list.items);
list.clearAndFree();
// Ref access
try interpolate(writer, &person, "selfLambda");
try testing.expectEqualStrings("10", list.items);
list.clearAndFree();
// Nested pointer access
try interpolate(writer, person, "indication.selfLambda");
try testing.expectEqualStrings("8", list.items);
list.clearAndFree();
// Nested Ref access
try interpolate(writer, &person, "selfLambda");
try testing.expectEqualStrings("10", list.items);
list.clearAndFree();
// Nested Ref pointer access
try interpolate(writer, &person, "indication.selfLambda");
try testing.expectEqualStrings("8", list.items);
list.clearAndFree();
}
test "Lambda - selfConstPtrLambda" {
const allocator = testing.allocator;
var list = std.ArrayList(u8).init(allocator);
defer list.deinit();
var person = getPerson();
defer if (person.indication) |indication| allocator.destroy(indication);
const person_const_ptr: *const Person = &person;
const person_ptr: *Person = &person;
var writer = list.writer();
// Direct access
try interpolate(writer, person, "selfConstPtrLambda");
try testing.expectEqualStrings("10", list.items);
list.clearAndFree();
// Const Ref access
try interpolate(writer, person_const_ptr, "selfConstPtrLambda");
try testing.expectEqualStrings("10", list.items);
list.clearAndFree();
// Mut Ref access
try interpolate(writer, person_ptr, "selfConstPtrLambda");
try testing.expectEqualStrings("10", list.items);
list.clearAndFree();
// Nested pointer access
try interpolate(writer, person, "indication.selfConstPtrLambda");
try testing.expectEqualStrings("8", list.items);
list.clearAndFree();
// Nested const Ref access
try interpolate(writer, person_const_ptr, "indication.selfConstPtrLambda");
try testing.expectEqualStrings("8", list.items);
list.clearAndFree();
// Nested Ref access
try interpolate(writer, person_ptr, "indication.selfConstPtrLambda");
try testing.expectEqualStrings("8", list.items);
list.clearAndFree();
}
test "Lambda - Write selfMutPtrLambda" {
const allocator = testing.allocator;
var list = std.ArrayList(u8).init(allocator);
defer list.deinit();
var writer = list.writer();
{
var person = getPerson();
defer if (person.indication) |indication| allocator.destroy(indication);
// Cannot be called from a context by value
try interpolate(writer, person, "selfMutPtrLambda");
try testing.expectEqualStrings("", list.items);
list.clearAndFree();
// Mutable pointer
try interpolate(writer, person, "indication.selfMutPtrLambda");
try testing.expectEqualStrings("1", list.items);
try testing.expect(person.indication.?.counter == 1);
list.clearAndFree();
try interpolate(writer, person, "indication.selfMutPtrLambda");
try testing.expectEqualStrings("2", list.items); // Called again, it's mutable
try testing.expect(person.indication.?.counter == 2);
list.clearAndFree();
}
{
var person = getPerson();
defer if (person.indication) |indication| allocator.destroy(indication);
// Cannot be called from a context const
const const_person_ptr: *const Person = &person;
try interpolate(writer, const_person_ptr, "selfMutPtrLambda");
try testing.expectEqualStrings("", list.items);
list.clearAndFree();
}
{
var person = getPerson();
defer if (person.indication) |indication| allocator.destroy(indication);
// Ref access
try interpolate(writer, &person, "selfMutPtrLambda");
try testing.expectEqualStrings("1", list.items);
try testing.expect(person.counter == 1);
list.clearAndFree();
try interpolate(writer, &person, "selfMutPtrLambda");
try testing.expectEqualStrings("2", list.items); //Called again, it's mutable
try testing.expect(person.counter == 2);
list.clearAndFree();
// Nested pointer access
try interpolate(writer, &person, "indication.selfMutPtrLambda");
try testing.expectEqualStrings("1", list.items);
try testing.expect(person.indication.?.counter == 1);
list.clearAndFree();
try interpolate(writer, &person, "indication.selfMutPtrLambda");
try testing.expectEqualStrings("2", list.items); // Called again, it's mutable
try testing.expect(person.indication.?.counter == 2);
list.clearAndFree();
}
}
test "Lambda - error handling" {
const allocator = testing.allocator;
var list = std.ArrayList(u8).init(allocator);
defer list.deinit();
var person = getPerson();
defer if (person.indication) |indication| allocator.destroy(indication);
var writer = list.writer();
try interpolate(writer, person, "willFailStaticLambda");
try testing.expectEqualStrings("", list.items);
list.clearAndFree();
try interpolate(writer, person, "willFailSelfLambda");
try testing.expectEqualStrings("unfinished", list.items);
list.clearAndFree();
}
test "Lambda - Write invalid functions" {
const allocator = testing.allocator;
var list = std.ArrayList(u8).init(allocator);
defer list.deinit();
var person = getPerson();
defer if (person.indication) |indication| allocator.destroy(indication);
var writer = list.writer();
// Unexpected arguments
try interpolate(writer, person, "anythingElse");
try testing.expectEqualStrings("", list.items);
list.clearAndFree();
}
test "Navigation" {
const allocator = testing.allocator;
var list = std.ArrayList(u8).init(allocator);
defer list.deinit();
var person = getPerson();
defer if (person.indication) |indication| allocator.destroy(indication);
var writer = list.writer();
// Person
var person_ctx = getContext(@TypeOf(writer), &person, DummyPartialsMap, dummy_options);
{
list.clearAndFree();
try interpolateCtx(writer, person_ctx, "address.street", .Unescaped);
try testing.expectEqualStrings("nearby", list.items);
}
// Address
var address_ctx = address_ctx: {
const path = try expectPath(allocator, "address");
defer Element.destroyPath(allocator, false, path);
switch (person_ctx.get(path)) {
.Field => |found| break :address_ctx found,
else => {
try testing.expect(false);
unreachable;
},
}
};
{
list.clearAndFree();
try interpolateCtx(writer, address_ctx, "street", .Unescaped);
try testing.expectEqualStrings("nearby", list.items);
}
// Street
var street_ctx = street_ctx: {
const path = try expectPath(allocator, "street");
defer Element.destroyPath(allocator, false, path);
switch (address_ctx.get(path)) {
.Field => |found| break :street_ctx found,
else => {
try testing.expect(false);
unreachable;
},
}
};
{
list.clearAndFree();
try interpolateCtx(writer, street_ctx, "", .Unescaped);
try testing.expectEqualStrings("nearby", list.items);
}
{
list.clearAndFree();
try interpolateCtx(writer, street_ctx, ".", .Unescaped);
try testing.expectEqualStrings("nearby", list.items);
}
}
test "Navigation Pointers" {
const allocator = testing.allocator;
var list = std.ArrayList(u8).init(allocator);
defer list.deinit();
var person = getPerson();
defer if (person.indication) |indication| allocator.destroy(indication);
var writer = list.writer();
// Person
var person_ctx = getContext(@TypeOf(writer), &person, DummyPartialsMap, dummy_options);
{
list.clearAndFree();
try interpolateCtx(writer, person_ctx, "indication.address.street", .Unescaped);
try testing.expectEqualStrings("far away street", list.items);
}
// Indication
var indication_ctx = indication_ctx: {
const path = try expectPath(allocator, "indication");
defer Element.destroyPath(allocator, false, path);
switch (person_ctx.get(path)) {
.Field => |found| break :indication_ctx found,
else => {
try testing.expect(false);
unreachable;
},
}
};
{
list.clearAndFree();
try interpolateCtx(writer, indication_ctx, "address.street", .Unescaped);
try testing.expectEqualStrings("far away street", list.items);
}
// Address
var address_ctx = address_ctx: {
const path = try expectPath(allocator, "address");
defer Element.destroyPath(allocator, false, path);
switch (indication_ctx.get(path)) {
.Field => |found| break :address_ctx found,
else => {
try testing.expect(false);
unreachable;
},
}
};
{
list.clearAndFree();
try interpolateCtx(writer, address_ctx, "street", .Unescaped);
try testing.expectEqualStrings("far away street", list.items);
}
// Street
var street_ctx = street_ctx: {
const path = try expectPath(allocator, "street");
defer Element.destroyPath(allocator, false, path);
switch (address_ctx.get(path)) {
.Field => |found| break :street_ctx found,
else => {
try testing.expect(false);
unreachable;
},
}
};
{
list.clearAndFree();
try interpolateCtx(writer, street_ctx, "", .Unescaped);
try testing.expectEqualStrings("far away street", list.items);
}
{
list.clearAndFree();
try interpolateCtx(writer, street_ctx, ".", .Unescaped);
try testing.expectEqualStrings("far away street", list.items);
}
}
test "Navigation NotFound" {
const allocator = testing.allocator;
// Person
var person = getPerson();
defer if (person.indication) |indication| allocator.destroy(indication);
const Writer = @TypeOf(std.io.null_writer);
var person_ctx = getContext(Writer, &person, DummyPartialsMap, dummy_options);
const address_ctx = address_ctx: {
const path = try expectPath(allocator, "address");
defer Element.destroyPath(allocator, false, path);
// Person.address
switch (person_ctx.get(path)) {
.Field => |found| break :address_ctx found,
else => {
try testing.expect(false);
unreachable;
},
}
};
{
const path = try expectPath(allocator, "wrong_address");
defer Element.destroyPath(allocator, false, path);
var wrong_address = person_ctx.get(path);
try testing.expect(wrong_address == .NotFoundInContext);
}
const street_ctx = street_ctx: {
const path = try expectPath(allocator, "street");
defer Element.destroyPath(allocator, false, path);
// Person.address.street
switch (address_ctx.get(path)) {
.Field => |found| break :street_ctx found,
else => {
try testing.expect(false);
unreachable;
},
}
};
{
const path = try expectPath(allocator, "wrong_street");
defer Element.destroyPath(allocator, false, path);
var wrong_street = address_ctx.get(path);
try testing.expect(wrong_street == .NotFoundInContext);
}
{
const path = try expectPath(allocator, "len");
defer Element.destroyPath(allocator, false, path);
// Person.address.street.len
var street_len_ctx = switch (street_ctx.get(path)) {
.Field => |found| found,
else => {
try testing.expect(false);
unreachable;
},
};
_ = street_len_ctx;
}
{
const path = try expectPath(allocator, "wrong_len");
defer Element.destroyPath(allocator, false, path);
var wrong_len = street_ctx.get(path);
try testing.expect(wrong_len == .NotFoundInContext);
}
}
test "Iterator over slice" {
const allocator = testing.allocator;
var list = std.ArrayList(u8).init(allocator);
defer list.deinit();
var person = getPerson();
defer if (person.indication) |indication| allocator.destroy(indication);
var writer = list.writer();
// Person
var ctx = getContext(@TypeOf(writer), &person, DummyPartialsMap, dummy_options);
const path = try expectPath(allocator, "items");
defer Element.destroyPath(allocator, false, path);
var iterator = switch (ctx.iterator(path)) {
.Field => |found| found,
else => {
try testing.expect(false);
unreachable;
},
};
var item_1 = iterator.next() orelse {
try testing.expect(false);
unreachable;
};
list.clearAndFree();
try interpolateCtx(writer, item_1, "name", .Unescaped);
try testing.expectEqualStrings("item 1", list.items);
var item_2 = iterator.next() orelse {
try testing.expect(false);
unreachable;
};
list.clearAndFree();
try interpolateCtx(writer, item_2, "name", .Unescaped);
try testing.expectEqualStrings("item 2", list.items);
var no_more = iterator.next();
try testing.expect(no_more == null);
}
test "Iterator over bool" {
const allocator = testing.allocator;
// Person
var person = getPerson();
defer if (person.indication) |indication| allocator.destroy(indication);
const Writer = @TypeOf(std.io.null_writer);
var ctx = getContext(Writer, &person, DummyPartialsMap, dummy_options);
{
// iterator over true
const path = try expectPath(allocator, "active");
defer Element.destroyPath(allocator, false, path);
var iterator = switch (ctx.iterator(path)) {
.Field => |found| found,
else => {
try testing.expect(false);
unreachable;
},
};
var item_1 = iterator.next();
try testing.expect(item_1 != null);
var no_more = iterator.next();
try testing.expect(no_more == null);
}
{
// iterator over false
const path = try expectPath(allocator, "indication.active");
defer Element.destroyPath(allocator, false, path);
var iterator = switch (ctx.iterator(path)) {
.Field => |found| found,
else => {
try testing.expect(false);
unreachable;
},
};
var no_more = iterator.next();
try testing.expect(no_more == null);
}
}
test "Iterator over null" {
const allocator = testing.allocator;
// Person
var person = getPerson();
defer if (person.indication) |indication| allocator.destroy(indication);
const Writer = @TypeOf(std.io.null_writer);
var ctx = getContext(Writer, &person, DummyPartialsMap, dummy_options);
{
// iterator over true
const path = try expectPath(allocator, "additional_information");
defer Element.destroyPath(allocator, false, path);
var iterator = switch (ctx.iterator(path)) {
.Field => |found| found,
else => {
try testing.expect(false);
unreachable;
},
};
var item_1 = iterator.next();
try testing.expect(item_1 != null);
var no_more = iterator.next();
try testing.expect(no_more == null);
}
{
// iterator over false
const path = try expectPath(allocator, "indication.additional_information");
defer Element.destroyPath(allocator, false, path);
var iterator = switch (ctx.iterator(path)) {
.Field => |found| found,
else => {
try testing.expect(false);
unreachable;
},
};
var no_more = iterator.next();
try testing.expect(no_more == null);
}
}
}; | src/rendering/context.zig |
const std = @import("std");
const Value = @import("value.zig").Value;
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const Target = std.Target;
const Module = @import("Module.zig");
/// This is the raw data, with no bookkeeping, no memory awareness, no de-duplication.
/// It's important for this type to be small.
/// Types are not de-duplicated, which helps with multi-threading since it obviates the requirement
/// of obtaining a lock on a global type table, as well as making the
/// garbage collection bookkeeping simpler.
/// This union takes advantage of the fact that the first page of memory
/// is unmapped, giving us 4096 possible enum tags that have no payload.
pub const Type = extern union {
/// If the tag value is less than Tag.no_payload_count, then no pointer
/// dereference is needed.
tag_if_small_enough: usize,
ptr_otherwise: *Payload,
pub fn zigTypeTag(self: Type) std.builtin.TypeId {
switch (self.tag()) {
.u8,
.i8,
.u16,
.i16,
.u32,
.i32,
.u64,
.i64,
.usize,
.isize,
.c_short,
.c_ushort,
.c_int,
.c_uint,
.c_long,
.c_ulong,
.c_longlong,
.c_ulonglong,
.c_longdouble,
.int_signed,
.int_unsigned,
=> return .Int,
.f16,
.f32,
.f64,
.f128,
=> return .Float,
.c_void => return .Opaque,
.bool => return .Bool,
.void => return .Void,
.type => return .Type,
.error_set, .error_set_single, .anyerror => return .ErrorSet,
.comptime_int => return .ComptimeInt,
.comptime_float => return .ComptimeFloat,
.noreturn => return .NoReturn,
.@"null" => return .Null,
.@"undefined" => return .Undefined,
.fn_noreturn_no_args => return .Fn,
.fn_void_no_args => return .Fn,
.fn_naked_noreturn_no_args => return .Fn,
.fn_ccc_void_no_args => return .Fn,
.function => return .Fn,
.array, .array_u8_sentinel_0, .array_u8, .array_sentinel => return .Array,
.single_const_pointer_to_comptime_int,
.const_slice_u8,
.single_const_pointer,
.single_mut_pointer,
.many_const_pointer,
.many_mut_pointer,
.c_const_pointer,
.c_mut_pointer,
.const_slice,
.mut_slice,
.pointer,
=> return .Pointer,
.optional,
.optional_single_const_pointer,
.optional_single_mut_pointer,
=> return .Optional,
.enum_literal => return .EnumLiteral,
.anyerror_void_error_union, .error_union => return .ErrorUnion,
.anyframe_T, .@"anyframe" => return .AnyFrame,
.empty_struct => return .Struct,
}
}
pub fn initTag(comptime small_tag: Tag) Type {
comptime assert(@enumToInt(small_tag) < Tag.no_payload_count);
return .{ .tag_if_small_enough = @enumToInt(small_tag) };
}
pub fn initPayload(payload: *Payload) Type {
assert(@enumToInt(payload.tag) >= Tag.no_payload_count);
return .{ .ptr_otherwise = payload };
}
pub fn tag(self: Type) Tag {
if (self.tag_if_small_enough < Tag.no_payload_count) {
return @intToEnum(Tag, @intCast(@TagType(Tag), self.tag_if_small_enough));
} else {
return self.ptr_otherwise.tag;
}
}
pub fn cast(self: Type, comptime T: type) ?*T {
if (self.tag_if_small_enough < Tag.no_payload_count)
return null;
const expected_tag = std.meta.fieldInfo(T, "base").default_value.?.tag;
if (self.ptr_otherwise.tag != expected_tag)
return null;
return @fieldParentPtr(T, "base", self.ptr_otherwise);
}
pub fn castPointer(self: Type) ?*Payload.PointerSimple {
return switch (self.tag()) {
.single_const_pointer,
.single_mut_pointer,
.many_const_pointer,
.many_mut_pointer,
.c_const_pointer,
.c_mut_pointer,
.const_slice,
.mut_slice,
.optional_single_const_pointer,
.optional_single_mut_pointer,
=> @fieldParentPtr(Payload.PointerSimple, "base", self.ptr_otherwise),
else => null,
};
}
pub fn eql(a: Type, b: Type) bool {
// As a shortcut, if the small tags / addresses match, we're done.
if (a.tag_if_small_enough == b.tag_if_small_enough)
return true;
const zig_tag_a = a.zigTypeTag();
const zig_tag_b = b.zigTypeTag();
if (zig_tag_a != zig_tag_b)
return false;
switch (zig_tag_a) {
.EnumLiteral => return true,
.Type => return true,
.Void => return true,
.Bool => return true,
.NoReturn => return true,
.ComptimeFloat => return true,
.ComptimeInt => return true,
.Undefined => return true,
.Null => return true,
.AnyFrame => {
return a.elemType().eql(b.elemType());
},
.Pointer => {
// Hot path for common case:
if (a.castPointer()) |a_payload| {
if (b.castPointer()) |b_payload| {
return a.tag() == b.tag() and eql(a_payload.pointee_type, b_payload.pointee_type);
}
}
const is_slice_a = isSlice(a);
const is_slice_b = isSlice(b);
if (is_slice_a != is_slice_b)
return false;
@panic("TODO implement more pointer Type equality comparison");
},
.Int => {
// Detect that e.g. u64 != usize, even if the bits match on a particular target.
const a_is_named_int = a.isNamedInt();
const b_is_named_int = b.isNamedInt();
if (a_is_named_int != b_is_named_int)
return false;
if (a_is_named_int)
return a.tag() == b.tag();
// Remaining cases are arbitrary sized integers.
// The target will not be branched upon, because we handled target-dependent cases above.
const info_a = a.intInfo(@as(Target, undefined));
const info_b = b.intInfo(@as(Target, undefined));
return info_a.signedness == info_b.signedness and info_a.bits == info_b.bits;
},
.Array => {
if (a.arrayLen() != b.arrayLen())
return false;
if (!a.elemType().eql(b.elemType()))
return false;
const sentinel_a = a.sentinel();
const sentinel_b = b.sentinel();
if (sentinel_a) |sa| {
if (sentinel_b) |sb| {
return sa.eql(sb);
} else {
return false;
}
} else {
return sentinel_b == null;
}
},
.Fn => {
if (!a.fnReturnType().eql(b.fnReturnType()))
return false;
if (a.fnCallingConvention() != b.fnCallingConvention())
return false;
const a_param_len = a.fnParamLen();
const b_param_len = b.fnParamLen();
if (a_param_len != b_param_len)
return false;
var i: usize = 0;
while (i < a_param_len) : (i += 1) {
if (!a.fnParamType(i).eql(b.fnParamType(i)))
return false;
}
return true;
},
.Optional => {
var buf_a: Payload.PointerSimple = undefined;
var buf_b: Payload.PointerSimple = undefined;
return a.optionalChild(&buf_a).eql(b.optionalChild(&buf_b));
},
.Float,
.Struct,
.ErrorUnion,
.ErrorSet,
.Enum,
.Union,
.BoundFn,
.Opaque,
.Frame,
.Vector,
=> std.debug.panic("TODO implement Type equality comparison of {} and {}", .{ a, b }),
}
}
pub fn hash(self: Type) u64 {
var hasher = std.hash.Wyhash.init(0);
const zig_type_tag = self.zigTypeTag();
std.hash.autoHash(&hasher, zig_type_tag);
switch (zig_type_tag) {
.Type,
.Void,
.Bool,
.NoReturn,
.ComptimeFloat,
.ComptimeInt,
.Undefined,
.Null,
=> {}, // The zig type tag is all that is needed to distinguish.
.Pointer => {
// TODO implement more pointer type hashing
},
.Int => {
// Detect that e.g. u64 != usize, even if the bits match on a particular target.
if (self.isNamedInt()) {
std.hash.autoHash(&hasher, self.tag());
} else {
// Remaining cases are arbitrary sized integers.
// The target will not be branched upon, because we handled target-dependent cases above.
const info = self.intInfo(@as(Target, undefined));
std.hash.autoHash(&hasher, info.signedness);
std.hash.autoHash(&hasher, info.bits);
}
},
.Array => {
std.hash.autoHash(&hasher, self.arrayLen());
std.hash.autoHash(&hasher, self.elemType().hash());
// TODO hash array sentinel
},
.Fn => {
std.hash.autoHash(&hasher, self.fnReturnType().hash());
std.hash.autoHash(&hasher, self.fnCallingConvention());
const params_len = self.fnParamLen();
std.hash.autoHash(&hasher, params_len);
var i: usize = 0;
while (i < params_len) : (i += 1) {
std.hash.autoHash(&hasher, self.fnParamType(i).hash());
}
},
.Optional => {
var buf: Payload.PointerSimple = undefined;
std.hash.autoHash(&hasher, self.optionalChild(&buf).hash());
},
.Float,
.Struct,
.ErrorUnion,
.ErrorSet,
.Enum,
.Union,
.BoundFn,
.Opaque,
.Frame,
.AnyFrame,
.Vector,
.EnumLiteral,
=> {
// TODO implement more type hashing
},
}
return hasher.final();
}
pub fn copy(self: Type, allocator: *Allocator) error{OutOfMemory}!Type {
if (self.tag_if_small_enough < Tag.no_payload_count) {
return Type{ .tag_if_small_enough = self.tag_if_small_enough };
} else switch (self.ptr_otherwise.tag) {
.u8,
.i8,
.u16,
.i16,
.u32,
.i32,
.u64,
.i64,
.usize,
.isize,
.c_short,
.c_ushort,
.c_int,
.c_uint,
.c_long,
.c_ulong,
.c_longlong,
.c_ulonglong,
.c_longdouble,
.c_void,
.f16,
.f32,
.f64,
.f128,
.bool,
.void,
.type,
.anyerror,
.comptime_int,
.comptime_float,
.noreturn,
.@"null",
.@"undefined",
.fn_noreturn_no_args,
.fn_void_no_args,
.fn_naked_noreturn_no_args,
.fn_ccc_void_no_args,
.single_const_pointer_to_comptime_int,
.const_slice_u8,
.enum_literal,
.anyerror_void_error_union,
.@"anyframe",
=> unreachable,
.array_u8_sentinel_0 => return self.copyPayloadShallow(allocator, Payload.Array_u8_Sentinel0),
.array_u8 => return self.copyPayloadShallow(allocator, Payload.Array_u8),
.array => {
const payload = @fieldParentPtr(Payload.Array, "base", self.ptr_otherwise);
const new_payload = try allocator.create(Payload.Array);
new_payload.* = .{
.base = payload.base,
.len = payload.len,
.elem_type = try payload.elem_type.copy(allocator),
};
return Type{ .ptr_otherwise = &new_payload.base };
},
.array_sentinel => {
const payload = @fieldParentPtr(Payload.ArraySentinel, "base", self.ptr_otherwise);
const new_payload = try allocator.create(Payload.ArraySentinel);
new_payload.* = .{
.base = payload.base,
.len = payload.len,
.sentinel = try payload.sentinel.copy(allocator),
.elem_type = try payload.elem_type.copy(allocator),
};
return Type{ .ptr_otherwise = &new_payload.base };
},
.int_signed => return self.copyPayloadShallow(allocator, Payload.IntSigned),
.int_unsigned => return self.copyPayloadShallow(allocator, Payload.IntUnsigned),
.function => {
const payload = @fieldParentPtr(Payload.Function, "base", self.ptr_otherwise);
const new_payload = try allocator.create(Payload.Function);
const param_types = try allocator.alloc(Type, payload.param_types.len);
for (payload.param_types) |param_type, i| {
param_types[i] = try param_type.copy(allocator);
}
new_payload.* = .{
.base = payload.base,
.return_type = try payload.return_type.copy(allocator),
.param_types = param_types,
.cc = payload.cc,
};
return Type{ .ptr_otherwise = &new_payload.base };
},
.optional => return self.copyPayloadSingleField(allocator, Payload.Optional, "child_type"),
.single_const_pointer,
.single_mut_pointer,
.many_const_pointer,
.many_mut_pointer,
.c_const_pointer,
.c_mut_pointer,
.const_slice,
.mut_slice,
.optional_single_mut_pointer,
.optional_single_const_pointer,
=> return self.copyPayloadSingleField(allocator, Payload.PointerSimple, "pointee_type"),
.anyframe_T => return self.copyPayloadSingleField(allocator, Payload.AnyFrame, "return_type"),
.pointer => {
const payload = @fieldParentPtr(Payload.Pointer, "base", self.ptr_otherwise);
const new_payload = try allocator.create(Payload.Pointer);
new_payload.* = .{
.base = payload.base,
.pointee_type = try payload.pointee_type.copy(allocator),
.sentinel = if (payload.sentinel) |some| try some.copy(allocator) else null,
.@"align" = payload.@"align",
.bit_offset = payload.bit_offset,
.host_size = payload.host_size,
.@"allowzero" = payload.@"allowzero",
.mutable = payload.mutable,
.@"volatile" = payload.@"volatile",
.size = payload.size,
};
return Type{ .ptr_otherwise = &new_payload.base };
},
.error_union => {
const payload = @fieldParentPtr(Payload.ErrorUnion, "base", self.ptr_otherwise);
const new_payload = try allocator.create(Payload.ErrorUnion);
new_payload.* = .{
.base = payload.base,
.error_set = try payload.error_set.copy(allocator),
.payload = try payload.payload.copy(allocator),
};
return Type{ .ptr_otherwise = &new_payload.base };
},
.error_set => return self.copyPayloadShallow(allocator, Payload.ErrorSet),
.error_set_single => return self.copyPayloadShallow(allocator, Payload.ErrorSetSingle),
.empty_struct => return self.copyPayloadShallow(allocator, Payload.EmptyStruct),
}
}
fn copyPayloadShallow(self: Type, allocator: *Allocator, comptime T: type) error{OutOfMemory}!Type {
const payload = @fieldParentPtr(T, "base", self.ptr_otherwise);
const new_payload = try allocator.create(T);
new_payload.* = payload.*;
return Type{ .ptr_otherwise = &new_payload.base };
}
fn copyPayloadSingleField(self: Type, allocator: *Allocator, comptime T: type, comptime field_name: []const u8) error{OutOfMemory}!Type {
const payload = @fieldParentPtr(T, "base", self.ptr_otherwise);
const new_payload = try allocator.create(T);
new_payload.base = payload.base;
@field(new_payload, field_name) = try @field(payload, field_name).copy(allocator);
return Type{ .ptr_otherwise = &new_payload.base };
}
pub fn format(
self: Type,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
out_stream: anytype,
) @TypeOf(out_stream).Error!void {
comptime assert(fmt.len == 0);
var ty = self;
while (true) {
const t = ty.tag();
switch (t) {
.u8,
.i8,
.u16,
.i16,
.u32,
.i32,
.u64,
.i64,
.usize,
.isize,
.c_short,
.c_ushort,
.c_int,
.c_uint,
.c_long,
.c_ulong,
.c_longlong,
.c_ulonglong,
.c_longdouble,
.c_void,
.f16,
.f32,
.f64,
.f128,
.bool,
.void,
.type,
.anyerror,
.comptime_int,
.comptime_float,
.noreturn,
=> return out_stream.writeAll(@tagName(t)),
.enum_literal => return out_stream.writeAll("@Type(.EnumLiteral)"),
.@"null" => return out_stream.writeAll("@Type(.Null)"),
.@"undefined" => return out_stream.writeAll("@Type(.Undefined)"),
// TODO this should print the structs name
.empty_struct => return out_stream.writeAll("struct {}"),
.@"anyframe" => return out_stream.writeAll("anyframe"),
.anyerror_void_error_union => return out_stream.writeAll("anyerror!void"),
.const_slice_u8 => return out_stream.writeAll("[]const u8"),
.fn_noreturn_no_args => return out_stream.writeAll("fn() noreturn"),
.fn_void_no_args => return out_stream.writeAll("fn() void"),
.fn_naked_noreturn_no_args => return out_stream.writeAll("fn() callconv(.Naked) noreturn"),
.fn_ccc_void_no_args => return out_stream.writeAll("fn() callconv(.C) void"),
.single_const_pointer_to_comptime_int => return out_stream.writeAll("*const comptime_int"),
.function => {
const payload = @fieldParentPtr(Payload.Function, "base", ty.ptr_otherwise);
try out_stream.writeAll("fn(");
for (payload.param_types) |param_type, i| {
if (i != 0) try out_stream.writeAll(", ");
try param_type.format("", .{}, out_stream);
}
try out_stream.writeAll(") ");
ty = payload.return_type;
continue;
},
.anyframe_T => {
const payload = @fieldParentPtr(Payload.AnyFrame, "base", ty.ptr_otherwise);
try out_stream.print("anyframe->", .{});
ty = payload.return_type;
continue;
},
.array_u8 => {
const payload = @fieldParentPtr(Payload.Array_u8, "base", ty.ptr_otherwise);
return out_stream.print("[{}]u8", .{payload.len});
},
.array_u8_sentinel_0 => {
const payload = @fieldParentPtr(Payload.Array_u8_Sentinel0, "base", ty.ptr_otherwise);
return out_stream.print("[{}:0]u8", .{payload.len});
},
.array => {
const payload = @fieldParentPtr(Payload.Array, "base", ty.ptr_otherwise);
try out_stream.print("[{}]", .{payload.len});
ty = payload.elem_type;
continue;
},
.array_sentinel => {
const payload = @fieldParentPtr(Payload.ArraySentinel, "base", ty.ptr_otherwise);
try out_stream.print("[{}:{}]", .{ payload.len, payload.sentinel });
ty = payload.elem_type;
continue;
},
.single_const_pointer => {
const payload = @fieldParentPtr(Payload.PointerSimple, "base", ty.ptr_otherwise);
try out_stream.writeAll("*const ");
ty = payload.pointee_type;
continue;
},
.single_mut_pointer => {
const payload = @fieldParentPtr(Payload.PointerSimple, "base", ty.ptr_otherwise);
try out_stream.writeAll("*");
ty = payload.pointee_type;
continue;
},
.many_const_pointer => {
const payload = @fieldParentPtr(Payload.PointerSimple, "base", ty.ptr_otherwise);
try out_stream.writeAll("[*]const ");
ty = payload.pointee_type;
continue;
},
.many_mut_pointer => {
const payload = @fieldParentPtr(Payload.PointerSimple, "base", ty.ptr_otherwise);
try out_stream.writeAll("[*]");
ty = payload.pointee_type;
continue;
},
.c_const_pointer => {
const payload = @fieldParentPtr(Payload.PointerSimple, "base", ty.ptr_otherwise);
try out_stream.writeAll("[*c]const ");
ty = payload.pointee_type;
continue;
},
.c_mut_pointer => {
const payload = @fieldParentPtr(Payload.PointerSimple, "base", ty.ptr_otherwise);
try out_stream.writeAll("[*c]");
ty = payload.pointee_type;
continue;
},
.const_slice => {
const payload = @fieldParentPtr(Payload.PointerSimple, "base", ty.ptr_otherwise);
try out_stream.writeAll("[]const ");
ty = payload.pointee_type;
continue;
},
.mut_slice => {
const payload = @fieldParentPtr(Payload.PointerSimple, "base", ty.ptr_otherwise);
try out_stream.writeAll("[]");
ty = payload.pointee_type;
continue;
},
.int_signed => {
const payload = @fieldParentPtr(Payload.IntSigned, "base", ty.ptr_otherwise);
return out_stream.print("i{}", .{payload.bits});
},
.int_unsigned => {
const payload = @fieldParentPtr(Payload.IntUnsigned, "base", ty.ptr_otherwise);
return out_stream.print("u{}", .{payload.bits});
},
.optional => {
const payload = @fieldParentPtr(Payload.Optional, "base", ty.ptr_otherwise);
try out_stream.writeByte('?');
ty = payload.child_type;
continue;
},
.optional_single_const_pointer => {
const payload = @fieldParentPtr(Payload.PointerSimple, "base", ty.ptr_otherwise);
try out_stream.writeAll("?*const ");
ty = payload.pointee_type;
continue;
},
.optional_single_mut_pointer => {
const payload = @fieldParentPtr(Payload.PointerSimple, "base", ty.ptr_otherwise);
try out_stream.writeAll("?*");
ty = payload.pointee_type;
continue;
},
.pointer => {
const payload = @fieldParentPtr(Payload.Pointer, "base", ty.ptr_otherwise);
if (payload.sentinel) |some| switch (payload.size) {
.One, .C => unreachable,
.Many => try out_stream.print("[*:{}]", .{some}),
.Slice => try out_stream.print("[:{}]", .{some}),
} else switch (payload.size) {
.One => try out_stream.writeAll("*"),
.Many => try out_stream.writeAll("[*]"),
.C => try out_stream.writeAll("[*c]"),
.Slice => try out_stream.writeAll("[]"),
}
if (payload.@"align" != 0) {
try out_stream.print("align({}", .{payload.@"align"});
if (payload.bit_offset != 0) {
try out_stream.print(":{}:{}", .{ payload.bit_offset, payload.host_size });
}
try out_stream.writeAll(") ");
}
if (!payload.mutable) try out_stream.writeAll("const ");
if (payload.@"volatile") try out_stream.writeAll("volatile ");
if (payload.@"allowzero") try out_stream.writeAll("allowzero ");
ty = payload.pointee_type;
continue;
},
.error_union => {
const payload = @fieldParentPtr(Payload.ErrorUnion, "base", ty.ptr_otherwise);
try payload.error_set.format("", .{}, out_stream);
try out_stream.writeAll("!");
ty = payload.payload;
continue;
},
.error_set => {
const payload = @fieldParentPtr(Payload.ErrorSet, "base", ty.ptr_otherwise);
return out_stream.writeAll(std.mem.spanZ(payload.decl.name));
},
.error_set_single => {
const payload = @fieldParentPtr(Payload.ErrorSetSingle, "base", ty.ptr_otherwise);
return out_stream.print("error{{{}}}", .{payload.name});
},
}
unreachable;
}
}
pub fn toValue(self: Type, allocator: *Allocator) Allocator.Error!Value {
switch (self.tag()) {
.u8 => return Value.initTag(.u8_type),
.i8 => return Value.initTag(.i8_type),
.u16 => return Value.initTag(.u16_type),
.i16 => return Value.initTag(.i16_type),
.u32 => return Value.initTag(.u32_type),
.i32 => return Value.initTag(.i32_type),
.u64 => return Value.initTag(.u64_type),
.i64 => return Value.initTag(.i64_type),
.usize => return Value.initTag(.usize_type),
.isize => return Value.initTag(.isize_type),
.c_short => return Value.initTag(.c_short_type),
.c_ushort => return Value.initTag(.c_ushort_type),
.c_int => return Value.initTag(.c_int_type),
.c_uint => return Value.initTag(.c_uint_type),
.c_long => return Value.initTag(.c_long_type),
.c_ulong => return Value.initTag(.c_ulong_type),
.c_longlong => return Value.initTag(.c_longlong_type),
.c_ulonglong => return Value.initTag(.c_ulonglong_type),
.c_longdouble => return Value.initTag(.c_longdouble_type),
.c_void => return Value.initTag(.c_void_type),
.f16 => return Value.initTag(.f16_type),
.f32 => return Value.initTag(.f32_type),
.f64 => return Value.initTag(.f64_type),
.f128 => return Value.initTag(.f128_type),
.bool => return Value.initTag(.bool_type),
.void => return Value.initTag(.void_type),
.type => return Value.initTag(.type_type),
.anyerror => return Value.initTag(.anyerror_type),
.comptime_int => return Value.initTag(.comptime_int_type),
.comptime_float => return Value.initTag(.comptime_float_type),
.noreturn => return Value.initTag(.noreturn_type),
.@"null" => return Value.initTag(.null_type),
.@"undefined" => return Value.initTag(.undefined_type),
.fn_noreturn_no_args => return Value.initTag(.fn_noreturn_no_args_type),
.fn_void_no_args => return Value.initTag(.fn_void_no_args_type),
.fn_naked_noreturn_no_args => return Value.initTag(.fn_naked_noreturn_no_args_type),
.fn_ccc_void_no_args => return Value.initTag(.fn_ccc_void_no_args_type),
.single_const_pointer_to_comptime_int => return Value.initTag(.single_const_pointer_to_comptime_int_type),
.const_slice_u8 => return Value.initTag(.const_slice_u8_type),
.enum_literal => return Value.initTag(.enum_literal_type),
else => {
const ty_payload = try allocator.create(Value.Payload.Ty);
ty_payload.* = .{ .ty = self };
return Value.initPayload(&ty_payload.base);
},
}
}
pub fn hasCodeGenBits(self: Type) bool {
return switch (self.tag()) {
.u8,
.i8,
.u16,
.i16,
.u32,
.i32,
.u64,
.i64,
.usize,
.isize,
.c_short,
.c_ushort,
.c_int,
.c_uint,
.c_long,
.c_ulong,
.c_longlong,
.c_ulonglong,
.c_longdouble,
.f16,
.f32,
.f64,
.f128,
.bool,
.anyerror,
.fn_noreturn_no_args,
.fn_void_no_args,
.fn_naked_noreturn_no_args,
.fn_ccc_void_no_args,
.function,
.single_const_pointer_to_comptime_int,
.const_slice_u8,
.array_u8_sentinel_0,
.optional,
.optional_single_mut_pointer,
.optional_single_const_pointer,
.@"anyframe",
.anyframe_T,
.anyerror_void_error_union,
.error_set,
.error_set_single,
=> true,
// TODO lazy types
.array => self.elemType().hasCodeGenBits() and self.arrayLen() != 0,
.array_u8 => self.arrayLen() != 0,
.array_sentinel, .single_const_pointer, .single_mut_pointer, .many_const_pointer, .many_mut_pointer, .c_const_pointer, .c_mut_pointer, .const_slice, .mut_slice, .pointer => self.elemType().hasCodeGenBits(),
.int_signed => self.cast(Payload.IntSigned).?.bits != 0,
.int_unsigned => self.cast(Payload.IntUnsigned).?.bits != 0,
.error_union => {
const payload = self.cast(Payload.ErrorUnion).?;
return payload.error_set.hasCodeGenBits() or payload.payload.hasCodeGenBits();
},
.c_void,
.void,
.type,
.comptime_int,
.comptime_float,
.noreturn,
.@"null",
.@"undefined",
.enum_literal,
.empty_struct,
=> false,
};
}
pub fn isNoReturn(self: Type) bool {
return self.zigTypeTag() == .NoReturn;
}
/// Asserts that hasCodeGenBits() is true.
pub fn abiAlignment(self: Type, target: Target) u32 {
return switch (self.tag()) {
.u8,
.i8,
.bool,
.array_u8_sentinel_0,
.array_u8,
=> return 1,
.fn_noreturn_no_args, // represents machine code; not a pointer
.fn_void_no_args, // represents machine code; not a pointer
.fn_naked_noreturn_no_args, // represents machine code; not a pointer
.fn_ccc_void_no_args, // represents machine code; not a pointer
.function, // represents machine code; not a pointer
=> return switch (target.cpu.arch) {
.arm, .armeb => 4,
.aarch64, .aarch64_32, .aarch64_be => 4,
.riscv64 => 2,
else => 1,
},
.i16, .u16 => return 2,
.i32, .u32 => return 4,
.i64, .u64 => return 8,
.isize,
.usize,
.single_const_pointer_to_comptime_int,
.const_slice_u8,
.single_const_pointer,
.single_mut_pointer,
.many_const_pointer,
.many_mut_pointer,
.c_const_pointer,
.c_mut_pointer,
.const_slice,
.mut_slice,
.optional_single_const_pointer,
.optional_single_mut_pointer,
.@"anyframe",
.anyframe_T,
=> return @divExact(target.cpu.arch.ptrBitWidth(), 8),
.pointer => {
const payload = @fieldParentPtr(Payload.Pointer, "base", self.ptr_otherwise);
if (payload.@"align" != 0) return payload.@"align";
return @divExact(target.cpu.arch.ptrBitWidth(), 8);
},
.c_short => return @divExact(CType.short.sizeInBits(target), 8),
.c_ushort => return @divExact(CType.ushort.sizeInBits(target), 8),
.c_int => return @divExact(CType.int.sizeInBits(target), 8),
.c_uint => return @divExact(CType.uint.sizeInBits(target), 8),
.c_long => return @divExact(CType.long.sizeInBits(target), 8),
.c_ulong => return @divExact(CType.ulong.sizeInBits(target), 8),
.c_longlong => return @divExact(CType.longlong.sizeInBits(target), 8),
.c_ulonglong => return @divExact(CType.ulonglong.sizeInBits(target), 8),
.f16 => return 2,
.f32 => return 4,
.f64 => return 8,
.f128 => return 16,
.c_longdouble => return 16,
.error_set,
.error_set_single,
.anyerror_void_error_union,
.anyerror,
=> return 2, // TODO revisit this when we have the concept of the error tag type
.array, .array_sentinel => return self.elemType().abiAlignment(target),
.int_signed, .int_unsigned => {
const bits: u16 = if (self.cast(Payload.IntSigned)) |pl|
pl.bits
else if (self.cast(Payload.IntUnsigned)) |pl|
pl.bits
else
unreachable;
return std.math.ceilPowerOfTwoPromote(u16, (bits + 7) / 8);
},
.optional => {
var buf: Payload.PointerSimple = undefined;
const child_type = self.optionalChild(&buf);
if (!child_type.hasCodeGenBits()) return 1;
if (child_type.zigTypeTag() == .Pointer and !child_type.isCPtr())
return @divExact(target.cpu.arch.ptrBitWidth(), 8);
return child_type.abiAlignment(target);
},
.error_union => {
const payload = self.cast(Payload.ErrorUnion).?;
if (!payload.error_set.hasCodeGenBits()) {
return payload.payload.abiAlignment(target);
} else if (!payload.payload.hasCodeGenBits()) {
return payload.error_set.abiAlignment(target);
}
@panic("TODO abiAlignment error union");
},
.c_void,
.void,
.type,
.comptime_int,
.comptime_float,
.noreturn,
.@"null",
.@"undefined",
.enum_literal,
.empty_struct,
=> unreachable,
};
}
/// Asserts the type has the ABI size already resolved.
pub fn abiSize(self: Type, target: Target) u64 {
return switch (self.tag()) {
.fn_noreturn_no_args => unreachable, // represents machine code; not a pointer
.fn_void_no_args => unreachable, // represents machine code; not a pointer
.fn_naked_noreturn_no_args => unreachable, // represents machine code; not a pointer
.fn_ccc_void_no_args => unreachable, // represents machine code; not a pointer
.function => unreachable, // represents machine code; not a pointer
.c_void => unreachable,
.void => unreachable,
.type => unreachable,
.comptime_int => unreachable,
.comptime_float => unreachable,
.noreturn => unreachable,
.@"null" => unreachable,
.@"undefined" => unreachable,
.enum_literal => unreachable,
.single_const_pointer_to_comptime_int => unreachable,
.empty_struct => unreachable,
.u8,
.i8,
.bool,
=> return 1,
.array_u8 => @fieldParentPtr(Payload.Array_u8_Sentinel0, "base", self.ptr_otherwise).len,
.array_u8_sentinel_0 => @fieldParentPtr(Payload.Array_u8_Sentinel0, "base", self.ptr_otherwise).len + 1,
.array => {
const payload = @fieldParentPtr(Payload.Array, "base", self.ptr_otherwise);
const elem_size = std.math.max(payload.elem_type.abiAlignment(target), payload.elem_type.abiSize(target));
return payload.len * elem_size;
},
.array_sentinel => {
const payload = @fieldParentPtr(Payload.ArraySentinel, "base", self.ptr_otherwise);
const elem_size = std.math.max(payload.elem_type.abiAlignment(target), payload.elem_type.abiSize(target));
return (payload.len + 1) * elem_size;
},
.i16, .u16 => return 2,
.i32, .u32 => return 4,
.i64, .u64 => return 8,
.@"anyframe", .anyframe_T, .isize, .usize => return @divExact(target.cpu.arch.ptrBitWidth(), 8),
.const_slice,
.mut_slice,
=> {
if (self.elemType().hasCodeGenBits()) return @divExact(target.cpu.arch.ptrBitWidth(), 8) * 2;
return @divExact(target.cpu.arch.ptrBitWidth(), 8);
},
.const_slice_u8 => return @divExact(target.cpu.arch.ptrBitWidth(), 8) * 2,
.optional_single_const_pointer,
.optional_single_mut_pointer,
=> {
if (self.elemType().hasCodeGenBits()) return 1;
return @divExact(target.cpu.arch.ptrBitWidth(), 8);
},
.single_const_pointer,
.single_mut_pointer,
.many_const_pointer,
.many_mut_pointer,
.c_const_pointer,
.c_mut_pointer,
.pointer,
=> {
if (self.elemType().hasCodeGenBits()) return 0;
return @divExact(target.cpu.arch.ptrBitWidth(), 8);
},
.c_short => return @divExact(CType.short.sizeInBits(target), 8),
.c_ushort => return @divExact(CType.ushort.sizeInBits(target), 8),
.c_int => return @divExact(CType.int.sizeInBits(target), 8),
.c_uint => return @divExact(CType.uint.sizeInBits(target), 8),
.c_long => return @divExact(CType.long.sizeInBits(target), 8),
.c_ulong => return @divExact(CType.ulong.sizeInBits(target), 8),
.c_longlong => return @divExact(CType.longlong.sizeInBits(target), 8),
.c_ulonglong => return @divExact(CType.ulonglong.sizeInBits(target), 8),
.f16 => return 2,
.f32 => return 4,
.f64 => return 8,
.f128 => return 16,
.c_longdouble => return 16,
.error_set,
.error_set_single,
.anyerror_void_error_union,
.anyerror,
=> return 2, // TODO revisit this when we have the concept of the error tag type
.int_signed, .int_unsigned => {
const bits: u16 = if (self.cast(Payload.IntSigned)) |pl|
pl.bits
else if (self.cast(Payload.IntUnsigned)) |pl|
pl.bits
else
unreachable;
return std.math.ceilPowerOfTwoPromote(u16, (bits + 7) / 8);
},
.optional => {
var buf: Payload.PointerSimple = undefined;
const child_type = self.optionalChild(&buf);
if (!child_type.hasCodeGenBits()) return 1;
if (child_type.zigTypeTag() == .Pointer and !child_type.isCPtr())
return @divExact(target.cpu.arch.ptrBitWidth(), 8);
// Optional types are represented as a struct with the child type as the first
// field and a boolean as the second. Since the child type's abi alignment is
// guaranteed to be >= that of bool's (1 byte) the added size is exactly equal
// to the child type's ABI alignment.
return child_type.abiAlignment(target) + child_type.abiSize(target);
},
.error_union => {
const payload = self.cast(Payload.ErrorUnion).?;
if (!payload.error_set.hasCodeGenBits() and !payload.payload.hasCodeGenBits()) {
return 0;
} else if (!payload.error_set.hasCodeGenBits()) {
return payload.payload.abiSize(target);
} else if (!payload.payload.hasCodeGenBits()) {
return payload.error_set.abiSize(target);
}
@panic("TODO abiSize error union");
},
};
}
pub fn isSinglePointer(self: Type) bool {
return switch (self.tag()) {
.u8,
.i8,
.u16,
.i16,
.u32,
.i32,
.u64,
.i64,
.usize,
.isize,
.c_short,
.c_ushort,
.c_int,
.c_uint,
.c_long,
.c_ulong,
.c_longlong,
.c_ulonglong,
.c_longdouble,
.f16,
.f32,
.f64,
.f128,
.c_void,
.bool,
.void,
.type,
.anyerror,
.comptime_int,
.comptime_float,
.noreturn,
.@"null",
.@"undefined",
.array,
.array_sentinel,
.array_u8,
.array_u8_sentinel_0,
.const_slice_u8,
.fn_noreturn_no_args,
.fn_void_no_args,
.fn_naked_noreturn_no_args,
.fn_ccc_void_no_args,
.function,
.int_unsigned,
.int_signed,
.optional,
.optional_single_mut_pointer,
.optional_single_const_pointer,
.enum_literal,
.many_const_pointer,
.many_mut_pointer,
.c_const_pointer,
.c_mut_pointer,
.const_slice,
.mut_slice,
.error_union,
.@"anyframe",
.anyframe_T,
.anyerror_void_error_union,
.error_set,
.error_set_single,
.empty_struct,
=> false,
.single_const_pointer,
.single_mut_pointer,
.single_const_pointer_to_comptime_int,
=> true,
.pointer => self.cast(Payload.Pointer).?.size == .One,
};
}
pub fn isSlice(self: Type) bool {
return switch (self.tag()) {
.u8,
.i8,
.u16,
.i16,
.u32,
.i32,
.u64,
.i64,
.usize,
.isize,
.c_short,
.c_ushort,
.c_int,
.c_uint,
.c_long,
.c_ulong,
.c_longlong,
.c_ulonglong,
.c_longdouble,
.f16,
.f32,
.f64,
.f128,
.c_void,
.bool,
.void,
.type,
.anyerror,
.comptime_int,
.comptime_float,
.noreturn,
.@"null",
.@"undefined",
.array,
.array_sentinel,
.array_u8,
.array_u8_sentinel_0,
.single_const_pointer,
.single_mut_pointer,
.many_const_pointer,
.many_mut_pointer,
.c_const_pointer,
.c_mut_pointer,
.single_const_pointer_to_comptime_int,
.fn_noreturn_no_args,
.fn_void_no_args,
.fn_naked_noreturn_no_args,
.fn_ccc_void_no_args,
.function,
.int_unsigned,
.int_signed,
.optional,
.optional_single_mut_pointer,
.optional_single_const_pointer,
.enum_literal,
.error_union,
.@"anyframe",
.anyframe_T,
.anyerror_void_error_union,
.error_set,
.error_set_single,
.empty_struct,
=> false,
.const_slice,
.mut_slice,
.const_slice_u8,
=> true,
.pointer => self.cast(Payload.Pointer).?.size == .Slice,
};
}
pub fn isConstPtr(self: Type) bool {
return switch (self.tag()) {
.u8,
.i8,
.u16,
.i16,
.u32,
.i32,
.u64,
.i64,
.usize,
.isize,
.c_short,
.c_ushort,
.c_int,
.c_uint,
.c_long,
.c_ulong,
.c_longlong,
.c_ulonglong,
.c_longdouble,
.f16,
.f32,
.f64,
.f128,
.c_void,
.bool,
.void,
.type,
.anyerror,
.comptime_int,
.comptime_float,
.noreturn,
.@"null",
.@"undefined",
.array,
.array_sentinel,
.array_u8,
.array_u8_sentinel_0,
.fn_noreturn_no_args,
.fn_void_no_args,
.fn_naked_noreturn_no_args,
.fn_ccc_void_no_args,
.function,
.int_unsigned,
.int_signed,
.single_mut_pointer,
.many_mut_pointer,
.c_mut_pointer,
.optional,
.optional_single_mut_pointer,
.optional_single_const_pointer,
.enum_literal,
.mut_slice,
.error_union,
.@"anyframe",
.anyframe_T,
.anyerror_void_error_union,
.error_set,
.error_set_single,
.empty_struct,
=> false,
.single_const_pointer,
.many_const_pointer,
.c_const_pointer,
.single_const_pointer_to_comptime_int,
.const_slice_u8,
.const_slice,
=> true,
.pointer => !self.cast(Payload.Pointer).?.mutable,
};
}
pub fn isVolatilePtr(self: Type) bool {
return switch (self.tag()) {
.u8,
.i8,
.u16,
.i16,
.u32,
.i32,
.u64,
.i64,
.usize,
.isize,
.c_short,
.c_ushort,
.c_int,
.c_uint,
.c_long,
.c_ulong,
.c_longlong,
.c_ulonglong,
.c_longdouble,
.f16,
.f32,
.f64,
.f128,
.c_void,
.bool,
.void,
.type,
.anyerror,
.comptime_int,
.comptime_float,
.noreturn,
.@"null",
.@"undefined",
.array,
.array_sentinel,
.array_u8,
.array_u8_sentinel_0,
.fn_noreturn_no_args,
.fn_void_no_args,
.fn_naked_noreturn_no_args,
.fn_ccc_void_no_args,
.function,
.int_unsigned,
.int_signed,
.single_mut_pointer,
.single_const_pointer,
.many_const_pointer,
.many_mut_pointer,
.c_const_pointer,
.c_mut_pointer,
.const_slice,
.mut_slice,
.single_const_pointer_to_comptime_int,
.const_slice_u8,
.optional,
.optional_single_mut_pointer,
.optional_single_const_pointer,
.enum_literal,
.error_union,
.@"anyframe",
.anyframe_T,
.anyerror_void_error_union,
.error_set,
.error_set_single,
.empty_struct,
=> false,
.pointer => {
const payload = @fieldParentPtr(Payload.Pointer, "base", self.ptr_otherwise);
return payload.@"volatile";
},
};
}
pub fn isAllowzeroPtr(self: Type) bool {
return switch (self.tag()) {
.u8,
.i8,
.u16,
.i16,
.u32,
.i32,
.u64,
.i64,
.usize,
.isize,
.c_short,
.c_ushort,
.c_int,
.c_uint,
.c_long,
.c_ulong,
.c_longlong,
.c_ulonglong,
.c_longdouble,
.f16,
.f32,
.f64,
.f128,
.c_void,
.bool,
.void,
.type,
.anyerror,
.comptime_int,
.comptime_float,
.noreturn,
.@"null",
.@"undefined",
.array,
.array_sentinel,
.array_u8,
.array_u8_sentinel_0,
.fn_noreturn_no_args,
.fn_void_no_args,
.fn_naked_noreturn_no_args,
.fn_ccc_void_no_args,
.function,
.int_unsigned,
.int_signed,
.single_mut_pointer,
.single_const_pointer,
.many_const_pointer,
.many_mut_pointer,
.c_const_pointer,
.c_mut_pointer,
.const_slice,
.mut_slice,
.single_const_pointer_to_comptime_int,
.const_slice_u8,
.optional,
.optional_single_mut_pointer,
.optional_single_const_pointer,
.enum_literal,
.error_union,
.@"anyframe",
.anyframe_T,
.anyerror_void_error_union,
.error_set,
.error_set_single,
.empty_struct,
=> false,
.pointer => {
const payload = @fieldParentPtr(Payload.Pointer, "base", self.ptr_otherwise);
return payload.@"allowzero";
},
};
}
/// Asserts that the type is an optional
pub fn isPtrLikeOptional(self: Type) bool {
switch (self.tag()) {
.optional_single_const_pointer, .optional_single_mut_pointer => return true,
.optional => {
var buf: Payload.PointerSimple = undefined;
const child_type = self.optionalChild(&buf);
// optionals of zero sized pointers behave like bools
if (!child_type.hasCodeGenBits()) return false;
return child_type.zigTypeTag() == .Pointer and !child_type.isCPtr();
},
else => unreachable,
}
}
/// Returns if type can be used for a runtime variable
pub fn isValidVarType(self: Type, is_extern: bool) bool {
var ty = self;
while (true) switch (ty.zigTypeTag()) {
.Bool,
.Int,
.Float,
.ErrorSet,
.Enum,
.Frame,
.AnyFrame,
.Vector,
=> return true,
.Opaque => return is_extern,
.BoundFn,
.ComptimeFloat,
.ComptimeInt,
.EnumLiteral,
.NoReturn,
.Type,
.Void,
.Undefined,
.Null,
=> return false,
.Optional => {
var buf: Payload.PointerSimple = undefined;
return ty.optionalChild(&buf).isValidVarType(is_extern);
},
.Pointer, .Array => ty = ty.elemType(),
.ErrorUnion => @panic("TODO fn isValidVarType"),
.Fn => @panic("TODO fn isValidVarType"),
.Struct => @panic("TODO struct isValidVarType"),
.Union => @panic("TODO union isValidVarType"),
};
}
/// Asserts the type is a pointer or array type.
pub fn elemType(self: Type) Type {
return switch (self.tag()) {
.u8,
.i8,
.u16,
.i16,
.u32,
.i32,
.u64,
.i64,
.usize,
.isize,
.c_short,
.c_ushort,
.c_int,
.c_uint,
.c_long,
.c_ulong,
.c_longlong,
.c_ulonglong,
.c_longdouble,
.f16,
.f32,
.f64,
.f128,
.c_void,
.bool,
.void,
.type,
.anyerror,
.comptime_int,
.comptime_float,
.noreturn,
.@"null",
.@"undefined",
.fn_noreturn_no_args,
.fn_void_no_args,
.fn_naked_noreturn_no_args,
.fn_ccc_void_no_args,
.function,
.int_unsigned,
.int_signed,
.optional,
.optional_single_const_pointer,
.optional_single_mut_pointer,
.enum_literal,
.error_union,
.@"anyframe",
.anyframe_T,
.anyerror_void_error_union,
.error_set,
.error_set_single,
.empty_struct,
=> unreachable,
.array => self.cast(Payload.Array).?.elem_type,
.array_sentinel => self.cast(Payload.ArraySentinel).?.elem_type,
.single_const_pointer,
.single_mut_pointer,
.many_const_pointer,
.many_mut_pointer,
.c_const_pointer,
.c_mut_pointer,
.const_slice,
.mut_slice,
=> self.castPointer().?.pointee_type,
.array_u8, .array_u8_sentinel_0, .const_slice_u8 => Type.initTag(.u8),
.single_const_pointer_to_comptime_int => Type.initTag(.comptime_int),
.pointer => self.cast(Payload.Pointer).?.pointee_type,
};
}
/// Asserts that the type is an optional.
pub fn optionalChild(self: Type, buf: *Payload.PointerSimple) Type {
return switch (self.tag()) {
.optional => self.cast(Payload.Optional).?.child_type,
.optional_single_mut_pointer => {
buf.* = .{
.base = .{ .tag = .single_mut_pointer },
.pointee_type = self.castPointer().?.pointee_type,
};
return Type.initPayload(&buf.base);
},
.optional_single_const_pointer => {
buf.* = .{
.base = .{ .tag = .single_const_pointer },
.pointee_type = self.castPointer().?.pointee_type,
};
return Type.initPayload(&buf.base);
},
else => unreachable,
};
}
/// Asserts that the type is an optional.
/// Same as `optionalChild` but allocates the buffer if needed.
pub fn optionalChildAlloc(self: Type, allocator: *Allocator) !Type {
return switch (self.tag()) {
.optional => self.cast(Payload.Optional).?.child_type,
.optional_single_mut_pointer, .optional_single_const_pointer => {
const payload = try allocator.create(Payload.PointerSimple);
payload.* = .{
.base = .{
.tag = if (self.tag() == .optional_single_const_pointer)
.single_const_pointer
else
.single_mut_pointer,
},
.pointee_type = self.castPointer().?.pointee_type,
};
return Type.initPayload(&payload.base);
},
else => unreachable,
};
}
/// Asserts the type is an array or vector.
pub fn arrayLen(self: Type) u64 {
return switch (self.tag()) {
.u8,
.i8,
.u16,
.i16,
.u32,
.i32,
.u64,
.i64,
.usize,
.isize,
.c_short,
.c_ushort,
.c_int,
.c_uint,
.c_long,
.c_ulong,
.c_longlong,
.c_ulonglong,
.c_longdouble,
.f16,
.f32,
.f64,
.f128,
.c_void,
.bool,
.void,
.type,
.anyerror,
.comptime_int,
.comptime_float,
.noreturn,
.@"null",
.@"undefined",
.fn_noreturn_no_args,
.fn_void_no_args,
.fn_naked_noreturn_no_args,
.fn_ccc_void_no_args,
.function,
.pointer,
.single_const_pointer,
.single_mut_pointer,
.many_const_pointer,
.many_mut_pointer,
.c_const_pointer,
.c_mut_pointer,
.const_slice,
.mut_slice,
.single_const_pointer_to_comptime_int,
.const_slice_u8,
.int_unsigned,
.int_signed,
.optional,
.optional_single_mut_pointer,
.optional_single_const_pointer,
.enum_literal,
.error_union,
.@"anyframe",
.anyframe_T,
.anyerror_void_error_union,
.error_set,
.error_set_single,
.empty_struct,
=> unreachable,
.array => self.cast(Payload.Array).?.len,
.array_sentinel => self.cast(Payload.ArraySentinel).?.len,
.array_u8 => self.cast(Payload.Array_u8).?.len,
.array_u8_sentinel_0 => self.cast(Payload.Array_u8_Sentinel0).?.len,
};
}
/// Asserts the type is an array, pointer or vector.
pub fn sentinel(self: Type) ?Value {
return switch (self.tag()) {
.u8,
.i8,
.u16,
.i16,
.u32,
.i32,
.u64,
.i64,
.usize,
.isize,
.c_short,
.c_ushort,
.c_int,
.c_uint,
.c_long,
.c_ulong,
.c_longlong,
.c_ulonglong,
.c_longdouble,
.f16,
.f32,
.f64,
.f128,
.c_void,
.bool,
.void,
.type,
.anyerror,
.comptime_int,
.comptime_float,
.noreturn,
.@"null",
.@"undefined",
.fn_noreturn_no_args,
.fn_void_no_args,
.fn_naked_noreturn_no_args,
.fn_ccc_void_no_args,
.function,
.const_slice,
.mut_slice,
.const_slice_u8,
.int_unsigned,
.int_signed,
.optional,
.optional_single_mut_pointer,
.optional_single_const_pointer,
.enum_literal,
.error_union,
.@"anyframe",
.anyframe_T,
.anyerror_void_error_union,
.error_set,
.error_set_single,
.empty_struct,
=> unreachable,
.single_const_pointer,
.single_mut_pointer,
.many_const_pointer,
.many_mut_pointer,
.c_const_pointer,
.c_mut_pointer,
.single_const_pointer_to_comptime_int,
.array,
.array_u8,
=> return null,
.pointer => return self.cast(Payload.Pointer).?.sentinel,
.array_sentinel => return self.cast(Payload.ArraySentinel).?.sentinel,
.array_u8_sentinel_0 => return Value.initTag(.zero),
};
}
/// Returns true if and only if the type is a fixed-width integer.
pub fn isInt(self: Type) bool {
return self.isSignedInt() or self.isUnsignedInt();
}
/// Returns true if and only if the type is a fixed-width, signed integer.
pub fn isSignedInt(self: Type) bool {
return switch (self.tag()) {
.f16,
.f32,
.f64,
.f128,
.c_longdouble,
.c_void,
.bool,
.void,
.type,
.anyerror,
.comptime_int,
.comptime_float,
.noreturn,
.@"null",
.@"undefined",
.fn_noreturn_no_args,
.fn_void_no_args,
.fn_naked_noreturn_no_args,
.fn_ccc_void_no_args,
.function,
.array,
.array_sentinel,
.array_u8,
.array_u8_sentinel_0,
.pointer,
.single_const_pointer,
.single_mut_pointer,
.many_const_pointer,
.many_mut_pointer,
.c_const_pointer,
.c_mut_pointer,
.const_slice,
.mut_slice,
.single_const_pointer_to_comptime_int,
.const_slice_u8,
.int_unsigned,
.u8,
.usize,
.c_ushort,
.c_uint,
.c_ulong,
.c_ulonglong,
.u16,
.u32,
.u64,
.optional,
.optional_single_mut_pointer,
.optional_single_const_pointer,
.enum_literal,
.error_union,
.@"anyframe",
.anyframe_T,
.anyerror_void_error_union,
.error_set,
.error_set_single,
.empty_struct,
=> false,
.int_signed,
.i8,
.isize,
.c_short,
.c_int,
.c_long,
.c_longlong,
.i16,
.i32,
.i64,
=> true,
};
}
/// Returns true if and only if the type is a fixed-width, unsigned integer.
pub fn isUnsignedInt(self: Type) bool {
return switch (self.tag()) {
.f16,
.f32,
.f64,
.f128,
.c_longdouble,
.c_void,
.bool,
.void,
.type,
.anyerror,
.comptime_int,
.comptime_float,
.noreturn,
.@"null",
.@"undefined",
.fn_noreturn_no_args,
.fn_void_no_args,
.fn_naked_noreturn_no_args,
.fn_ccc_void_no_args,
.function,
.array,
.array_sentinel,
.array_u8,
.array_u8_sentinel_0,
.pointer,
.single_const_pointer,
.single_mut_pointer,
.many_const_pointer,
.many_mut_pointer,
.c_const_pointer,
.c_mut_pointer,
.const_slice,
.mut_slice,
.single_const_pointer_to_comptime_int,
.const_slice_u8,
.int_signed,
.i8,
.isize,
.c_short,
.c_int,
.c_long,
.c_longlong,
.i16,
.i32,
.i64,
.optional,
.optional_single_mut_pointer,
.optional_single_const_pointer,
.enum_literal,
.error_union,
.@"anyframe",
.anyframe_T,
.anyerror_void_error_union,
.error_set,
.error_set_single,
.empty_struct,
=> false,
.int_unsigned,
.u8,
.usize,
.c_ushort,
.c_uint,
.c_ulong,
.c_ulonglong,
.u16,
.u32,
.u64,
=> true,
};
}
/// Asserts the type is an integer.
pub fn intInfo(self: Type, target: Target) struct { signedness: std.builtin.Signedness, bits: u16 } {
return switch (self.tag()) {
.f16,
.f32,
.f64,
.f128,
.c_longdouble,
.c_void,
.bool,
.void,
.type,
.anyerror,
.comptime_int,
.comptime_float,
.noreturn,
.@"null",
.@"undefined",
.fn_noreturn_no_args,
.fn_void_no_args,
.fn_naked_noreturn_no_args,
.fn_ccc_void_no_args,
.function,
.array,
.array_sentinel,
.array_u8,
.array_u8_sentinel_0,
.pointer,
.single_const_pointer,
.single_mut_pointer,
.many_const_pointer,
.many_mut_pointer,
.c_const_pointer,
.c_mut_pointer,
.const_slice,
.mut_slice,
.single_const_pointer_to_comptime_int,
.const_slice_u8,
.optional,
.optional_single_mut_pointer,
.optional_single_const_pointer,
.enum_literal,
.error_union,
.@"anyframe",
.anyframe_T,
.anyerror_void_error_union,
.error_set,
.error_set_single,
.empty_struct,
=> unreachable,
.int_unsigned => .{ .signedness = .unsigned, .bits = self.cast(Payload.IntUnsigned).?.bits },
.int_signed => .{ .signedness = .signed, .bits = self.cast(Payload.IntSigned).?.bits },
.u8 => .{ .signedness = .unsigned, .bits = 8 },
.i8 => .{ .signedness = .signed, .bits = 8 },
.u16 => .{ .signedness = .unsigned, .bits = 16 },
.i16 => .{ .signedness = .signed, .bits = 16 },
.u32 => .{ .signedness = .unsigned, .bits = 32 },
.i32 => .{ .signedness = .signed, .bits = 32 },
.u64 => .{ .signedness = .unsigned, .bits = 64 },
.i64 => .{ .signedness = .signed, .bits = 64 },
.usize => .{ .signedness = .unsigned, .bits = target.cpu.arch.ptrBitWidth() },
.isize => .{ .signedness = .signed, .bits = target.cpu.arch.ptrBitWidth() },
.c_short => .{ .signedness = .signed, .bits = CType.short.sizeInBits(target) },
.c_ushort => .{ .signedness = .unsigned, .bits = CType.ushort.sizeInBits(target) },
.c_int => .{ .signedness = .signed, .bits = CType.int.sizeInBits(target) },
.c_uint => .{ .signedness = .unsigned, .bits = CType.uint.sizeInBits(target) },
.c_long => .{ .signedness = .signed, .bits = CType.long.sizeInBits(target) },
.c_ulong => .{ .signedness = .unsigned, .bits = CType.ulong.sizeInBits(target) },
.c_longlong => .{ .signedness = .signed, .bits = CType.longlong.sizeInBits(target) },
.c_ulonglong => .{ .signedness = .unsigned, .bits = CType.ulonglong.sizeInBits(target) },
};
}
pub fn isNamedInt(self: Type) bool {
return switch (self.tag()) {
.f16,
.f32,
.f64,
.f128,
.c_longdouble,
.c_void,
.bool,
.void,
.type,
.anyerror,
.comptime_int,
.comptime_float,
.noreturn,
.@"null",
.@"undefined",
.fn_noreturn_no_args,
.fn_void_no_args,
.fn_naked_noreturn_no_args,
.fn_ccc_void_no_args,
.function,
.array,
.array_sentinel,
.array_u8,
.array_u8_sentinel_0,
.pointer,
.single_const_pointer,
.single_mut_pointer,
.many_const_pointer,
.many_mut_pointer,
.c_const_pointer,
.c_mut_pointer,
.const_slice,
.mut_slice,
.single_const_pointer_to_comptime_int,
.const_slice_u8,
.int_unsigned,
.int_signed,
.u8,
.i8,
.u16,
.i16,
.u32,
.i32,
.u64,
.i64,
.optional,
.optional_single_mut_pointer,
.optional_single_const_pointer,
.enum_literal,
.error_union,
.@"anyframe",
.anyframe_T,
.anyerror_void_error_union,
.error_set,
.error_set_single,
.empty_struct,
=> false,
.usize,
.isize,
.c_short,
.c_ushort,
.c_int,
.c_uint,
.c_long,
.c_ulong,
.c_longlong,
.c_ulonglong,
=> true,
};
}
pub fn isFloat(self: Type) bool {
return switch (self.tag()) {
.f16,
.f32,
.f64,
.f128,
.c_longdouble,
=> true,
else => false,
};
}
/// Asserts the type is a fixed-size float.
pub fn floatBits(self: Type, target: Target) u16 {
return switch (self.tag()) {
.f16 => 16,
.f32 => 32,
.f64 => 64,
.f128 => 128,
.c_longdouble => CType.longdouble.sizeInBits(target),
else => unreachable,
};
}
/// Asserts the type is a function.
pub fn fnParamLen(self: Type) usize {
return switch (self.tag()) {
.fn_noreturn_no_args => 0,
.fn_void_no_args => 0,
.fn_naked_noreturn_no_args => 0,
.fn_ccc_void_no_args => 0,
.function => @fieldParentPtr(Payload.Function, "base", self.ptr_otherwise).param_types.len,
.f16,
.f32,
.f64,
.f128,
.c_longdouble,
.c_void,
.bool,
.void,
.type,
.anyerror,
.comptime_int,
.comptime_float,
.noreturn,
.@"null",
.@"undefined",
.array,
.array_sentinel,
.array_u8,
.array_u8_sentinel_0,
.pointer,
.single_const_pointer,
.single_mut_pointer,
.many_const_pointer,
.many_mut_pointer,
.c_const_pointer,
.c_mut_pointer,
.const_slice,
.mut_slice,
.single_const_pointer_to_comptime_int,
.const_slice_u8,
.u8,
.i8,
.u16,
.i16,
.u32,
.i32,
.u64,
.i64,
.usize,
.isize,
.c_short,
.c_ushort,
.c_int,
.c_uint,
.c_long,
.c_ulong,
.c_longlong,
.c_ulonglong,
.int_unsigned,
.int_signed,
.optional,
.optional_single_mut_pointer,
.optional_single_const_pointer,
.enum_literal,
.error_union,
.@"anyframe",
.anyframe_T,
.anyerror_void_error_union,
.error_set,
.error_set_single,
.empty_struct,
=> unreachable,
};
}
/// Asserts the type is a function. The length of the slice must be at least the length
/// given by `fnParamLen`.
pub fn fnParamTypes(self: Type, types: []Type) void {
switch (self.tag()) {
.fn_noreturn_no_args => return,
.fn_void_no_args => return,
.fn_naked_noreturn_no_args => return,
.fn_ccc_void_no_args => return,
.function => {
const payload = @fieldParentPtr(Payload.Function, "base", self.ptr_otherwise);
std.mem.copy(Type, types, payload.param_types);
},
.f16,
.f32,
.f64,
.f128,
.c_longdouble,
.c_void,
.bool,
.void,
.type,
.anyerror,
.comptime_int,
.comptime_float,
.noreturn,
.@"null",
.@"undefined",
.array,
.array_sentinel,
.array_u8,
.array_u8_sentinel_0,
.pointer,
.single_const_pointer,
.single_mut_pointer,
.many_const_pointer,
.many_mut_pointer,
.c_const_pointer,
.c_mut_pointer,
.const_slice,
.mut_slice,
.single_const_pointer_to_comptime_int,
.const_slice_u8,
.u8,
.i8,
.u16,
.i16,
.u32,
.i32,
.u64,
.i64,
.usize,
.isize,
.c_short,
.c_ushort,
.c_int,
.c_uint,
.c_long,
.c_ulong,
.c_longlong,
.c_ulonglong,
.int_unsigned,
.int_signed,
.optional,
.optional_single_mut_pointer,
.optional_single_const_pointer,
.enum_literal,
.error_union,
.@"anyframe",
.anyframe_T,
.anyerror_void_error_union,
.error_set,
.error_set_single,
.empty_struct,
=> unreachable,
}
}
/// Asserts the type is a function.
pub fn fnParamType(self: Type, index: usize) Type {
switch (self.tag()) {
.function => {
const payload = @fieldParentPtr(Payload.Function, "base", self.ptr_otherwise);
return payload.param_types[index];
},
.fn_noreturn_no_args,
.fn_void_no_args,
.fn_naked_noreturn_no_args,
.fn_ccc_void_no_args,
.f16,
.f32,
.f64,
.f128,
.c_longdouble,
.c_void,
.bool,
.void,
.type,
.anyerror,
.comptime_int,
.comptime_float,
.noreturn,
.@"null",
.@"undefined",
.array,
.array_sentinel,
.array_u8,
.array_u8_sentinel_0,
.pointer,
.single_const_pointer,
.single_mut_pointer,
.many_const_pointer,
.many_mut_pointer,
.c_const_pointer,
.c_mut_pointer,
.const_slice,
.mut_slice,
.single_const_pointer_to_comptime_int,
.const_slice_u8,
.u8,
.i8,
.u16,
.i16,
.u32,
.i32,
.u64,
.i64,
.usize,
.isize,
.c_short,
.c_ushort,
.c_int,
.c_uint,
.c_long,
.c_ulong,
.c_longlong,
.c_ulonglong,
.int_unsigned,
.int_signed,
.optional,
.optional_single_mut_pointer,
.optional_single_const_pointer,
.enum_literal,
.error_union,
.@"anyframe",
.anyframe_T,
.anyerror_void_error_union,
.error_set,
.error_set_single,
.empty_struct,
=> unreachable,
}
}
/// Asserts the type is a function.
pub fn fnReturnType(self: Type) Type {
return switch (self.tag()) {
.fn_noreturn_no_args => Type.initTag(.noreturn),
.fn_naked_noreturn_no_args => Type.initTag(.noreturn),
.fn_void_no_args,
.fn_ccc_void_no_args,
=> Type.initTag(.void),
.function => @fieldParentPtr(Payload.Function, "base", self.ptr_otherwise).return_type,
.f16,
.f32,
.f64,
.f128,
.c_longdouble,
.c_void,
.bool,
.void,
.type,
.anyerror,
.comptime_int,
.comptime_float,
.noreturn,
.@"null",
.@"undefined",
.array,
.array_sentinel,
.array_u8,
.array_u8_sentinel_0,
.pointer,
.single_const_pointer,
.single_mut_pointer,
.many_const_pointer,
.many_mut_pointer,
.c_const_pointer,
.c_mut_pointer,
.const_slice,
.mut_slice,
.single_const_pointer_to_comptime_int,
.const_slice_u8,
.u8,
.i8,
.u16,
.i16,
.u32,
.i32,
.u64,
.i64,
.usize,
.isize,
.c_short,
.c_ushort,
.c_int,
.c_uint,
.c_long,
.c_ulong,
.c_longlong,
.c_ulonglong,
.int_unsigned,
.int_signed,
.optional,
.optional_single_mut_pointer,
.optional_single_const_pointer,
.enum_literal,
.error_union,
.@"anyframe",
.anyframe_T,
.anyerror_void_error_union,
.error_set,
.error_set_single,
.empty_struct,
=> unreachable,
};
}
/// Asserts the type is a function.
pub fn fnCallingConvention(self: Type) std.builtin.CallingConvention {
return switch (self.tag()) {
.fn_noreturn_no_args => .Unspecified,
.fn_void_no_args => .Unspecified,
.fn_naked_noreturn_no_args => .Naked,
.fn_ccc_void_no_args => .C,
.function => @fieldParentPtr(Payload.Function, "base", self.ptr_otherwise).cc,
.f16,
.f32,
.f64,
.f128,
.c_longdouble,
.c_void,
.bool,
.void,
.type,
.anyerror,
.comptime_int,
.comptime_float,
.noreturn,
.@"null",
.@"undefined",
.array,
.array_sentinel,
.array_u8,
.array_u8_sentinel_0,
.pointer,
.single_const_pointer,
.single_mut_pointer,
.many_const_pointer,
.many_mut_pointer,
.c_const_pointer,
.c_mut_pointer,
.const_slice,
.mut_slice,
.single_const_pointer_to_comptime_int,
.const_slice_u8,
.u8,
.i8,
.u16,
.i16,
.u32,
.i32,
.u64,
.i64,
.usize,
.isize,
.c_short,
.c_ushort,
.c_int,
.c_uint,
.c_long,
.c_ulong,
.c_longlong,
.c_ulonglong,
.int_unsigned,
.int_signed,
.optional,
.optional_single_mut_pointer,
.optional_single_const_pointer,
.enum_literal,
.error_union,
.@"anyframe",
.anyframe_T,
.anyerror_void_error_union,
.error_set,
.error_set_single,
.empty_struct,
=> unreachable,
};
}
/// Asserts the type is a function.
pub fn fnIsVarArgs(self: Type) bool {
return switch (self.tag()) {
.fn_noreturn_no_args => false,
.fn_void_no_args => false,
.fn_naked_noreturn_no_args => false,
.fn_ccc_void_no_args => false,
.function => false,
.f16,
.f32,
.f64,
.f128,
.c_longdouble,
.c_void,
.bool,
.void,
.type,
.anyerror,
.comptime_int,
.comptime_float,
.noreturn,
.@"null",
.@"undefined",
.array,
.array_sentinel,
.array_u8,
.array_u8_sentinel_0,
.pointer,
.single_const_pointer,
.single_mut_pointer,
.many_const_pointer,
.many_mut_pointer,
.c_const_pointer,
.c_mut_pointer,
.const_slice,
.mut_slice,
.single_const_pointer_to_comptime_int,
.const_slice_u8,
.u8,
.i8,
.u16,
.i16,
.u32,
.i32,
.u64,
.i64,
.usize,
.isize,
.c_short,
.c_ushort,
.c_int,
.c_uint,
.c_long,
.c_ulong,
.c_longlong,
.c_ulonglong,
.int_unsigned,
.int_signed,
.optional,
.optional_single_mut_pointer,
.optional_single_const_pointer,
.enum_literal,
.error_union,
.@"anyframe",
.anyframe_T,
.anyerror_void_error_union,
.error_set,
.error_set_single,
.empty_struct,
=> unreachable,
};
}
pub fn isNumeric(self: Type) bool {
return switch (self.tag()) {
.f16,
.f32,
.f64,
.f128,
.c_longdouble,
.comptime_int,
.comptime_float,
.u8,
.i8,
.u16,
.i16,
.u32,
.i32,
.u64,
.i64,
.usize,
.isize,
.c_short,
.c_ushort,
.c_int,
.c_uint,
.c_long,
.c_ulong,
.c_longlong,
.c_ulonglong,
.int_unsigned,
.int_signed,
=> true,
.c_void,
.bool,
.void,
.type,
.anyerror,
.noreturn,
.@"null",
.@"undefined",
.fn_noreturn_no_args,
.fn_void_no_args,
.fn_naked_noreturn_no_args,
.fn_ccc_void_no_args,
.function,
.array,
.array_sentinel,
.array_u8,
.array_u8_sentinel_0,
.pointer,
.single_const_pointer,
.single_mut_pointer,
.many_const_pointer,
.many_mut_pointer,
.c_const_pointer,
.c_mut_pointer,
.const_slice,
.mut_slice,
.single_const_pointer_to_comptime_int,
.const_slice_u8,
.optional,
.optional_single_mut_pointer,
.optional_single_const_pointer,
.enum_literal,
.error_union,
.@"anyframe",
.anyframe_T,
.anyerror_void_error_union,
.error_set,
.error_set_single,
.empty_struct,
=> false,
};
}
pub fn onePossibleValue(self: Type) ?Value {
var ty = self;
while (true) switch (ty.tag()) {
.f16,
.f32,
.f64,
.f128,
.c_longdouble,
.comptime_int,
.comptime_float,
.u8,
.i8,
.u16,
.i16,
.u32,
.i32,
.u64,
.i64,
.usize,
.isize,
.c_short,
.c_ushort,
.c_int,
.c_uint,
.c_long,
.c_ulong,
.c_longlong,
.c_ulonglong,
.bool,
.type,
.anyerror,
.fn_noreturn_no_args,
.fn_void_no_args,
.fn_naked_noreturn_no_args,
.fn_ccc_void_no_args,
.function,
.single_const_pointer_to_comptime_int,
.array_sentinel,
.array_u8_sentinel_0,
.const_slice_u8,
.const_slice,
.mut_slice,
.c_void,
.optional,
.optional_single_mut_pointer,
.optional_single_const_pointer,
.enum_literal,
.anyerror_void_error_union,
.anyframe_T,
.@"anyframe",
.error_union,
.error_set,
.error_set_single,
=> return null,
.empty_struct => return Value.initTag(.empty_struct_value),
.void => return Value.initTag(.void_value),
.noreturn => return Value.initTag(.unreachable_value),
.@"null" => return Value.initTag(.null_value),
.@"undefined" => return Value.initTag(.undef),
.int_unsigned => {
if (ty.cast(Payload.IntUnsigned).?.bits == 0) {
return Value.initTag(.zero);
} else {
return null;
}
},
.int_signed => {
if (ty.cast(Payload.IntSigned).?.bits == 0) {
return Value.initTag(.zero);
} else {
return null;
}
},
.array, .array_u8 => {
if (ty.arrayLen() == 0)
return Value.initTag(.empty_array);
ty = ty.elemType();
continue;
},
.many_const_pointer,
.many_mut_pointer,
.c_const_pointer,
.c_mut_pointer,
.single_const_pointer,
.single_mut_pointer,
=> {
const ptr = ty.castPointer().?;
ty = ptr.pointee_type;
continue;
},
.pointer => {
ty = ty.cast(Payload.Pointer).?.pointee_type;
continue;
},
};
}
pub fn isCPtr(self: Type) bool {
return switch (self.tag()) {
.f16,
.f32,
.f64,
.f128,
.c_longdouble,
.comptime_int,
.comptime_float,
.u8,
.i8,
.u16,
.i16,
.u32,
.i32,
.u64,
.i64,
.usize,
.isize,
.c_short,
.c_ushort,
.c_int,
.c_uint,
.c_long,
.c_ulong,
.c_longlong,
.c_ulonglong,
.bool,
.type,
.anyerror,
.fn_noreturn_no_args,
.fn_void_no_args,
.fn_naked_noreturn_no_args,
.fn_ccc_void_no_args,
.function,
.single_const_pointer_to_comptime_int,
.const_slice_u8,
.c_void,
.void,
.noreturn,
.@"null",
.@"undefined",
.int_unsigned,
.int_signed,
.array,
.array_sentinel,
.array_u8,
.array_u8_sentinel_0,
.single_const_pointer,
.single_mut_pointer,
.many_const_pointer,
.many_mut_pointer,
.const_slice,
.mut_slice,
.optional,
.optional_single_mut_pointer,
.optional_single_const_pointer,
.enum_literal,
.error_union,
.@"anyframe",
.anyframe_T,
.anyerror_void_error_union,
.error_set,
.error_set_single,
.empty_struct,
=> return false,
.c_const_pointer,
.c_mut_pointer,
=> return true,
.pointer => self.cast(Payload.Pointer).?.size == .C,
};
}
pub fn isIndexable(self: Type) bool {
const zig_tag = self.zigTypeTag();
// TODO tuples are indexable
return zig_tag == .Array or zig_tag == .Vector or self.isSlice() or
(self.isSinglePointer() and self.elemType().zigTypeTag() == .Array);
}
/// Asserts that the type is a container. (note: ErrorSet is not a container).
pub fn getContainerScope(self: Type) *Module.Scope.Container {
return switch (self.tag()) {
.f16,
.f32,
.f64,
.f128,
.c_longdouble,
.comptime_int,
.comptime_float,
.u8,
.i8,
.u16,
.i16,
.u32,
.i32,
.u64,
.i64,
.usize,
.isize,
.c_short,
.c_ushort,
.c_int,
.c_uint,
.c_long,
.c_ulong,
.c_longlong,
.c_ulonglong,
.bool,
.type,
.anyerror,
.fn_noreturn_no_args,
.fn_void_no_args,
.fn_naked_noreturn_no_args,
.fn_ccc_void_no_args,
.function,
.single_const_pointer_to_comptime_int,
.const_slice_u8,
.c_void,
.void,
.noreturn,
.@"null",
.@"undefined",
.int_unsigned,
.int_signed,
.array,
.array_sentinel,
.array_u8,
.array_u8_sentinel_0,
.single_const_pointer,
.single_mut_pointer,
.many_const_pointer,
.many_mut_pointer,
.const_slice,
.mut_slice,
.optional,
.optional_single_mut_pointer,
.optional_single_const_pointer,
.enum_literal,
.error_union,
.@"anyframe",
.anyframe_T,
.anyerror_void_error_union,
.error_set,
.error_set_single,
.c_const_pointer,
.c_mut_pointer,
.pointer,
=> unreachable,
.empty_struct => self.cast(Type.Payload.EmptyStruct).?.scope,
};
}
/// Asserts that self.zigTypeTag() == .Int.
pub fn minInt(self: Type, arena: *std.heap.ArenaAllocator, target: Target) !Value {
assert(self.zigTypeTag() == .Int);
const info = self.intInfo(target);
if (info.signedness == .unsigned) {
return Value.initTag(.zero);
}
if ((info.bits - 1) <= std.math.maxInt(u6)) {
const payload = try arena.allocator.create(Value.Payload.Int_i64);
payload.* = .{
.int = -(@as(i64, 1) << @truncate(u6, info.bits - 1)),
};
return Value.initPayload(&payload.base);
}
var res = try std.math.big.int.Managed.initSet(&arena.allocator, 1);
try res.shiftLeft(res, info.bits - 1);
res.negate();
const res_const = res.toConst();
if (res_const.positive) {
const val_payload = try arena.allocator.create(Value.Payload.IntBigPositive);
val_payload.* = .{ .limbs = res_const.limbs };
return Value.initPayload(&val_payload.base);
} else {
const val_payload = try arena.allocator.create(Value.Payload.IntBigNegative);
val_payload.* = .{ .limbs = res_const.limbs };
return Value.initPayload(&val_payload.base);
}
}
/// Asserts that self.zigTypeTag() == .Int.
pub fn maxInt(self: Type, arena: *std.heap.ArenaAllocator, target: Target) !Value {
assert(self.zigTypeTag() == .Int);
const info = self.intInfo(target);
if (info.signedness == .signed and (info.bits - 1) <= std.math.maxInt(u6)) {
const payload = try arena.allocator.create(Value.Payload.Int_i64);
payload.* = .{
.int = (@as(i64, 1) << @truncate(u6, info.bits - 1)) - 1,
};
return Value.initPayload(&payload.base);
} else if (info.signedness == .signed and info.bits <= std.math.maxInt(u6)) {
const payload = try arena.allocator.create(Value.Payload.Int_u64);
payload.* = .{
.int = (@as(u64, 1) << @truncate(u6, info.bits)) - 1,
};
return Value.initPayload(&payload.base);
}
var res = try std.math.big.int.Managed.initSet(&arena.allocator, 1);
try res.shiftLeft(res, info.bits - @boolToInt(info.signedness == .signed));
const one = std.math.big.int.Const{
.limbs = &[_]std.math.big.Limb{1},
.positive = true,
};
res.sub(res.toConst(), one) catch unreachable;
const res_const = res.toConst();
if (res_const.positive) {
const val_payload = try arena.allocator.create(Value.Payload.IntBigPositive);
val_payload.* = .{ .limbs = res_const.limbs };
return Value.initPayload(&val_payload.base);
} else {
const val_payload = try arena.allocator.create(Value.Payload.IntBigNegative);
val_payload.* = .{ .limbs = res_const.limbs };
return Value.initPayload(&val_payload.base);
}
}
/// This enum does not directly correspond to `std.builtin.TypeId` because
/// it has extra enum tags in it, as a way of using less memory. For example,
/// even though Zig recognizes `*align(10) i32` and `*i32` both as Pointer types
/// but with different alignment values, in this data structure they are represented
/// with different enum tags, because the the former requires more payload data than the latter.
/// See `zigTypeTag` for the function that corresponds to `std.builtin.TypeId`.
pub const Tag = enum {
// The first section of this enum are tags that require no payload.
u8,
i8,
u16,
i16,
u32,
i32,
u64,
i64,
usize,
isize,
c_short,
c_ushort,
c_int,
c_uint,
c_long,
c_ulong,
c_longlong,
c_ulonglong,
c_longdouble,
f16,
f32,
f64,
f128,
c_void,
bool,
void,
type,
anyerror,
comptime_int,
comptime_float,
noreturn,
enum_literal,
@"null",
@"undefined",
fn_noreturn_no_args,
fn_void_no_args,
fn_naked_noreturn_no_args,
fn_ccc_void_no_args,
single_const_pointer_to_comptime_int,
anyerror_void_error_union,
@"anyframe",
const_slice_u8, // See last_no_payload_tag below.
// After this, the tag requires a payload.
array_u8,
array_u8_sentinel_0,
array,
array_sentinel,
pointer,
single_const_pointer,
single_mut_pointer,
many_const_pointer,
many_mut_pointer,
c_const_pointer,
c_mut_pointer,
const_slice,
mut_slice,
int_signed,
int_unsigned,
function,
optional,
optional_single_mut_pointer,
optional_single_const_pointer,
error_union,
anyframe_T,
error_set,
error_set_single,
empty_struct,
pub const last_no_payload_tag = Tag.const_slice_u8;
pub const no_payload_count = @enumToInt(last_no_payload_tag) + 1;
};
pub const Payload = struct {
tag: Tag,
pub const Array_u8_Sentinel0 = struct {
base: Payload = Payload{ .tag = .array_u8_sentinel_0 },
len: u64,
};
pub const Array_u8 = struct {
base: Payload = Payload{ .tag = .array_u8 },
len: u64,
};
pub const Array = struct {
base: Payload = Payload{ .tag = .array },
len: u64,
elem_type: Type,
};
pub const ArraySentinel = struct {
base: Payload = Payload{ .tag = .array_sentinel },
len: u64,
sentinel: Value,
elem_type: Type,
};
pub const PointerSimple = struct {
base: Payload,
pointee_type: Type,
};
pub const IntSigned = struct {
base: Payload = Payload{ .tag = .int_signed },
bits: u16,
};
pub const IntUnsigned = struct {
base: Payload = Payload{ .tag = .int_unsigned },
bits: u16,
};
pub const Function = struct {
base: Payload = Payload{ .tag = .function },
param_types: []Type,
return_type: Type,
cc: std.builtin.CallingConvention,
};
pub const Optional = struct {
base: Payload = Payload{ .tag = .optional },
child_type: Type,
};
pub const Pointer = struct {
base: Payload = .{ .tag = .pointer },
pointee_type: Type,
sentinel: ?Value,
/// If zero use pointee_type.AbiAlign()
@"align": u32,
bit_offset: u16,
host_size: u16,
@"allowzero": bool,
mutable: bool,
@"volatile": bool,
size: std.builtin.TypeInfo.Pointer.Size,
};
pub const ErrorUnion = struct {
base: Payload = .{ .tag = .error_union },
error_set: Type,
payload: Type,
};
pub const AnyFrame = struct {
base: Payload = .{ .tag = .anyframe_T },
return_type: Type,
};
pub const ErrorSet = struct {
base: Payload = .{ .tag = .error_set },
decl: *Module.Decl,
};
pub const ErrorSetSingle = struct {
base: Payload = .{ .tag = .error_set_single },
/// memory is owned by `Module`
name: []const u8,
};
/// Mostly used for namespace like structs with zero fields.
/// Most commonly used for files.
pub const EmptyStruct = struct {
base: Payload = .{ .tag = .empty_struct },
scope: *Module.Scope.Container,
};
};
};
pub const CType = enum {
short,
ushort,
int,
uint,
long,
ulong,
longlong,
ulonglong,
longdouble,
pub fn sizeInBits(self: CType, target: Target) u16 {
const arch = target.cpu.arch;
switch (target.os.tag) {
.freestanding, .other => switch (target.cpu.arch) {
.msp430 => switch (self) {
.short,
.ushort,
.int,
.uint,
=> return 16,
.long,
.ulong,
=> return 32,
.longlong,
.ulonglong,
=> return 64,
.longdouble => @panic("TODO figure out what kind of float `long double` is on this target"),
},
else => switch (self) {
.short,
.ushort,
=> return 16,
.int,
.uint,
=> return 32,
.long,
.ulong,
=> return target.cpu.arch.ptrBitWidth(),
.longlong,
.ulonglong,
=> return 64,
.longdouble => @panic("TODO figure out what kind of float `long double` is on this target"),
},
},
.linux,
.macos,
.freebsd,
.netbsd,
.dragonfly,
.openbsd,
.wasi,
.emscripten,
=> switch (self) {
.short,
.ushort,
=> return 16,
.int,
.uint,
=> return 32,
.long,
.ulong,
=> return target.cpu.arch.ptrBitWidth(),
.longlong,
.ulonglong,
=> return 64,
.longdouble => @panic("TODO figure out what kind of float `long double` is on this target"),
},
.windows, .uefi => switch (self) {
.short,
.ushort,
=> return 16,
.int,
.uint,
.long,
.ulong,
=> return 32,
.longlong,
.ulonglong,
=> return 64,
.longdouble => @panic("TODO figure out what kind of float `long double` is on this target"),
},
.ios => switch (self) {
.short,
.ushort,
=> return 16,
.int,
.uint,
=> return 32,
.long,
.ulong,
.longlong,
.ulonglong,
=> return 64,
.longdouble => @panic("TODO figure out what kind of float `long double` is on this target"),
},
.ananas,
.cloudabi,
.fuchsia,
.kfreebsd,
.lv2,
.solaris,
.haiku,
.minix,
.rtems,
.nacl,
.cnk,
.aix,
.cuda,
.nvcl,
.amdhsa,
.ps4,
.elfiamcu,
.tvos,
.watchos,
.mesa3d,
.contiki,
.amdpal,
.hermit,
.hurd,
=> @panic("TODO specify the C integer and float type sizes for this OS"),
}
}
}; | src/type.zig |
const std = @import("std.zig");
const mem = std.mem;
const builtin = std.builtin;
const Version = std.builtin.Version;
/// TODO Nearly all the functions in this namespace would be
/// better off if https://github.com/ziglang/zig/issues/425
/// was solved.
pub const Target = struct {
cpu: Cpu,
os: Os,
abi: Abi,
pub const Os = struct {
tag: Tag,
version_range: VersionRange,
pub const Tag = enum {
freestanding,
ananas,
cloudabi,
dragonfly,
freebsd,
fuchsia,
ios,
kfreebsd,
linux,
lv2,
macos,
netbsd,
openbsd,
solaris,
windows,
zos,
haiku,
minix,
rtems,
nacl,
aix,
cuda,
nvcl,
amdhsa,
ps4,
elfiamcu,
tvos,
watchos,
mesa3d,
contiki,
amdpal,
hermit,
hurd,
wasi,
emscripten,
uefi,
opencl,
glsl450,
vulkan,
other,
pub fn isDarwin(tag: Tag) bool {
return switch (tag) {
.ios, .macos, .watchos, .tvos => true,
else => false,
};
}
pub fn dynamicLibSuffix(tag: Tag) [:0]const u8 {
if (tag.isDarwin()) {
return ".dylib";
}
switch (tag) {
.windows => return ".dll",
else => return ".so",
}
}
pub fn defaultVersionRange(tag: Tag) Os {
return .{
.tag = tag,
.version_range = VersionRange.default(tag),
};
}
};
/// Based on NTDDI version constants from
/// https://docs.microsoft.com/en-us/cpp/porting/modifying-winver-and-win32-winnt
pub const WindowsVersion = enum(u32) {
nt4 = 0x04000000,
win2k = 0x05000000,
xp = 0x05010000,
ws2003 = 0x05020000,
vista = 0x06000000,
win7 = 0x06010000,
win8 = 0x06020000,
win8_1 = 0x06030000,
win10 = 0x0A000000, //aka win10_th1
win10_th2 = 0x0A000001,
win10_rs1 = 0x0A000002,
win10_rs2 = 0x0A000003,
win10_rs3 = 0x0A000004,
win10_rs4 = 0x0A000005,
win10_rs5 = 0x0A000006,
win10_19h1 = 0x0A000007,
win10_vb = 0x0A000008, //aka win10_19h2
win10_mn = 0x0A000009, //aka win10_20h1
win10_fe = 0x0A00000A, //aka win10_20h2
_,
/// Latest Windows version that the Zig Standard Library is aware of
pub const latest = WindowsVersion.win10_fe;
/// Compared against build numbers reported by the runtime to distinguish win10 versions,
/// where 0x0A000000 + index corresponds to the WindowsVersion u32 value.
pub const known_win10_build_numbers = [_]u32{
10240, //win10 aka win10_th1
10586, //win10_th2
14393, //win10_rs1
15063, //win10_rs2
16299, //win10_rs3
17134, //win10_rs4
17763, //win10_rs5
18362, //win10_19h1
18363, //win10_vb aka win10_19h2
19041, //win10_mn aka win10_20h1
19042, //win10_fe aka win10_20h2
};
/// Returns whether the first version `self` is newer (greater) than or equal to the second version `ver`.
pub fn isAtLeast(self: WindowsVersion, ver: WindowsVersion) bool {
return @enumToInt(self) >= @enumToInt(ver);
}
pub const Range = struct {
min: WindowsVersion,
max: WindowsVersion,
pub fn includesVersion(self: Range, ver: WindowsVersion) bool {
return @enumToInt(ver) >= @enumToInt(self.min) and @enumToInt(ver) <= @enumToInt(self.max);
}
/// Checks if system is guaranteed to be at least `version` or older than `version`.
/// Returns `null` if a runtime check is required.
pub fn isAtLeast(self: Range, ver: WindowsVersion) ?bool {
if (@enumToInt(self.min) >= @enumToInt(ver)) return true;
if (@enumToInt(self.max) < @enumToInt(ver)) return false;
return null;
}
};
/// This function is defined to serialize a Zig source code representation of this
/// type, that, when parsed, will deserialize into the same data.
pub fn format(
self: WindowsVersion,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
out_stream: anytype,
) !void {
if (fmt.len > 0 and fmt[0] == 's') {
if (@enumToInt(self) >= @enumToInt(WindowsVersion.nt4) and @enumToInt(self) <= @enumToInt(WindowsVersion.latest)) {
try std.fmt.format(out_stream, ".{s}", .{@tagName(self)});
} else {
// TODO this code path breaks zig triples, but it is used in `builtin`
try std.fmt.format(out_stream, "@intToEnum(Target.Os.WindowsVersion, 0x{X:0>8})", .{@enumToInt(self)});
}
} else {
if (@enumToInt(self) >= @enumToInt(WindowsVersion.nt4) and @enumToInt(self) <= @enumToInt(WindowsVersion.latest)) {
try std.fmt.format(out_stream, "WindowsVersion.{s}", .{@tagName(self)});
} else {
try std.fmt.format(out_stream, "WindowsVersion(0x{X:0>8})", .{@enumToInt(self)});
}
}
}
};
pub const LinuxVersionRange = struct {
range: Version.Range,
glibc: Version,
pub fn includesVersion(self: LinuxVersionRange, ver: Version) bool {
return self.range.includesVersion(ver);
}
/// Checks if system is guaranteed to be at least `version` or older than `version`.
/// Returns `null` if a runtime check is required.
pub fn isAtLeast(self: LinuxVersionRange, ver: Version) ?bool {
return self.range.isAtLeast(ver);
}
};
/// The version ranges here represent the minimum OS version to be supported
/// and the maximum OS version to be supported. The default values represent
/// the range that the Zig Standard Library bases its abstractions on.
///
/// The minimum version of the range is the main setting to tweak for a target.
/// Usually, the maximum target OS version will remain the default, which is
/// the latest released version of the OS.
///
/// To test at compile time if the target is guaranteed to support a given OS feature,
/// one should check that the minimum version of the range is greater than or equal to
/// the version the feature was introduced in.
///
/// To test at compile time if the target certainly will not support a given OS feature,
/// one should check that the maximum version of the range is less than the version the
/// feature was introduced in.
///
/// If neither of these cases apply, a runtime check should be used to determine if the
/// target supports a given OS feature.
///
/// Binaries built with a given maximum version will continue to function on newer
/// operating system versions. However, such a binary may not take full advantage of the
/// newer operating system APIs.
///
/// See `Os.isAtLeast`.
pub const VersionRange = union {
none: void,
semver: Version.Range,
linux: LinuxVersionRange,
windows: WindowsVersion.Range,
/// The default `VersionRange` represents the range that the Zig Standard Library
/// bases its abstractions on.
pub fn default(tag: Tag) VersionRange {
switch (tag) {
.freestanding,
.ananas,
.cloudabi,
.fuchsia,
.kfreebsd,
.lv2,
.solaris,
.zos,
.haiku,
.minix,
.rtems,
.nacl,
.aix,
.cuda,
.nvcl,
.amdhsa,
.ps4,
.elfiamcu,
.mesa3d,
.contiki,
.amdpal,
.hermit,
.hurd,
.wasi,
.emscripten,
.uefi,
.opencl, // TODO: OpenCL versions
.glsl450, // TODO: GLSL versions
.vulkan,
.other,
=> return .{ .none = {} },
.freebsd => return .{
.semver = Version.Range{
.min = .{ .major = 12, .minor = 0 },
.max = .{ .major = 13, .minor = 0 },
},
},
.macos => return .{
.semver = .{
.min = .{ .major = 10, .minor = 13 },
.max = .{ .major = 11, .minor = 2 },
},
},
.ios => return .{
.semver = .{
.min = .{ .major = 12, .minor = 0 },
.max = .{ .major = 13, .minor = 4, .patch = 0 },
},
},
.watchos => return .{
.semver = .{
.min = .{ .major = 6, .minor = 0 },
.max = .{ .major = 6, .minor = 2, .patch = 0 },
},
},
.tvos => return .{
.semver = .{
.min = .{ .major = 13, .minor = 0 },
.max = .{ .major = 13, .minor = 4, .patch = 0 },
},
},
.netbsd => return .{
.semver = .{
.min = .{ .major = 8, .minor = 0 },
.max = .{ .major = 9, .minor = 1 },
},
},
.openbsd => return .{
.semver = .{
.min = .{ .major = 6, .minor = 8 },
.max = .{ .major = 6, .minor = 9 },
},
},
.dragonfly => return .{
.semver = .{
.min = .{ .major = 5, .minor = 8 },
.max = .{ .major = 6, .minor = 0 },
},
},
.linux => return .{
.linux = .{
.range = .{
.min = .{ .major = 3, .minor = 16 },
.max = .{ .major = 5, .minor = 5, .patch = 5 },
},
.glibc = .{ .major = 2, .minor = 17 },
},
},
.windows => return .{
.windows = .{
.min = .win8_1,
.max = WindowsVersion.latest,
},
},
}
}
};
pub const TaggedVersionRange = union(enum) {
none: void,
semver: Version.Range,
linux: LinuxVersionRange,
windows: WindowsVersion.Range,
};
/// Provides a tagged union. `Target` does not store the tag because it is
/// redundant with the OS tag; this function abstracts that part away.
pub fn getVersionRange(self: Os) TaggedVersionRange {
switch (self.tag) {
.linux => return TaggedVersionRange{ .linux = self.version_range.linux },
.windows => return TaggedVersionRange{ .windows = self.version_range.windows },
.freebsd,
.macos,
.ios,
.tvos,
.watchos,
.netbsd,
.openbsd,
.dragonfly,
=> return TaggedVersionRange{ .semver = self.version_range.semver },
else => return .none,
}
}
/// Checks if system is guaranteed to be at least `version` or older than `version`.
/// Returns `null` if a runtime check is required.
pub fn isAtLeast(self: Os, comptime tag: Tag, version: anytype) ?bool {
if (self.tag != tag) return false;
return switch (tag) {
.linux => self.version_range.linux.isAtLeast(version),
.windows => self.version_range.windows.isAtLeast(version),
else => self.version_range.semver.isAtLeast(version),
};
}
/// On Darwin, we always link libSystem which contains libc.
/// Similarly on FreeBSD and NetBSD we always link system libc
/// since this is the stable syscall interface.
pub fn requiresLibC(os: Os) bool {
return switch (os.tag) {
.freebsd,
.netbsd,
.macos,
.ios,
.tvos,
.watchos,
.dragonfly,
.openbsd,
.haiku,
=> true,
.linux,
.windows,
.freestanding,
.ananas,
.cloudabi,
.fuchsia,
.kfreebsd,
.lv2,
.solaris,
.zos,
.minix,
.rtems,
.nacl,
.aix,
.cuda,
.nvcl,
.amdhsa,
.ps4,
.elfiamcu,
.mesa3d,
.contiki,
.amdpal,
.hermit,
.hurd,
.wasi,
.emscripten,
.uefi,
.opencl,
.glsl450,
.vulkan,
.other,
=> false,
};
}
};
pub const aarch64 = @import("target/aarch64.zig");
pub const amdgpu = @import("target/amdgpu.zig");
pub const arm = @import("target/arm.zig");
pub const avr = @import("target/avr.zig");
pub const bpf = @import("target/bpf.zig");
pub const hexagon = @import("target/hexagon.zig");
pub const mips = @import("target/mips.zig");
pub const msp430 = @import("target/msp430.zig");
pub const nvptx = @import("target/nvptx.zig");
pub const powerpc = @import("target/powerpc.zig");
pub const riscv = @import("target/riscv.zig");
pub const sparc = @import("target/sparc.zig");
pub const spirv = @import("target/spirv.zig");
pub const systemz = @import("target/systemz.zig");
pub const ve = @import("target/ve.zig");
pub const wasm = @import("target/wasm.zig");
pub const x86 = @import("target/x86.zig");
pub const Abi = enum {
none,
gnu,
gnuabin32,
gnuabi64,
gnueabi,
gnueabihf,
gnux32,
gnuilp32,
code16,
eabi,
eabihf,
android,
musl,
musleabi,
musleabihf,
msvc,
itanium,
cygnus,
coreclr,
simulator,
macabi,
pub fn default(arch: Cpu.Arch, target_os: Os) Abi {
if (arch.isWasm()) {
return .musl;
}
switch (target_os.tag) {
.freestanding,
.ananas,
.cloudabi,
.dragonfly,
.lv2,
.solaris,
.zos,
.minix,
.rtems,
.nacl,
.aix,
.cuda,
.nvcl,
.amdhsa,
.ps4,
.elfiamcu,
.mesa3d,
.contiki,
.amdpal,
.hermit,
.other,
=> return .eabi,
.openbsd,
.macos,
.freebsd,
.ios,
.tvos,
.watchos,
.fuchsia,
.kfreebsd,
.netbsd,
.hurd,
.haiku,
.windows,
=> return .gnu,
.uefi => return .msvc,
.linux,
.wasi,
.emscripten,
=> return .musl,
.opencl, // TODO: SPIR-V ABIs with Linkage capability
.glsl450,
.vulkan,
=> return .none,
}
}
pub fn isGnu(abi: Abi) bool {
return switch (abi) {
.gnu, .gnuabin32, .gnuabi64, .gnueabi, .gnueabihf, .gnux32 => true,
else => false,
};
}
pub fn isMusl(abi: Abi) bool {
return switch (abi) {
.musl, .musleabi, .musleabihf => true,
else => false,
};
}
pub fn floatAbi(abi: Abi) FloatAbi {
return switch (abi) {
.gnueabihf,
.eabihf,
.musleabihf,
=> .hard,
else => .soft,
};
}
};
pub const ObjectFormat = enum {
coff,
pe,
elf,
macho,
wasm,
c,
spirv,
hex,
raw,
};
pub const SubSystem = enum {
Console,
Windows,
Posix,
Native,
EfiApplication,
EfiBootServiceDriver,
EfiRom,
EfiRuntimeDriver,
};
pub const Cpu = struct {
/// Architecture
arch: Arch,
/// The CPU model to target. It has a set of features
/// which are overridden with the `features` field.
model: *const Model,
/// An explicit list of the entire CPU feature set. It may differ from the specific CPU model's features.
features: Feature.Set,
pub const Feature = struct {
/// The bit index into `Set`. Has a default value of `undefined` because the canonical
/// structures are populated via comptime logic.
index: Set.Index = undefined,
/// Has a default value of `undefined` because the canonical
/// structures are populated via comptime logic.
name: []const u8 = undefined,
/// If this corresponds to an LLVM-recognized feature, this will be populated;
/// otherwise null.
llvm_name: ?[:0]const u8,
/// Human-friendly UTF-8 text.
description: []const u8,
/// Sparse `Set` of features this depends on.
dependencies: Set,
/// A bit set of all the features.
pub const Set = struct {
ints: [usize_count]usize,
pub const needed_bit_count = 288;
pub const byte_count = (needed_bit_count + 7) / 8;
pub const usize_count = (byte_count + (@sizeOf(usize) - 1)) / @sizeOf(usize);
pub const Index = std.math.Log2Int(std.meta.Int(.unsigned, usize_count * @bitSizeOf(usize)));
pub const ShiftInt = std.math.Log2Int(usize);
pub const empty = Set{ .ints = [1]usize{0} ** usize_count };
pub fn empty_workaround() Set {
return Set{ .ints = [1]usize{0} ** usize_count };
}
pub fn isEmpty(set: Set) bool {
return for (set.ints) |x| {
if (x != 0) break false;
} else true;
}
pub fn isEnabled(set: Set, arch_feature_index: Index) bool {
const usize_index = arch_feature_index / @bitSizeOf(usize);
const bit_index = @intCast(ShiftInt, arch_feature_index % @bitSizeOf(usize));
return (set.ints[usize_index] & (@as(usize, 1) << bit_index)) != 0;
}
/// Adds the specified feature but not its dependencies.
pub fn addFeature(set: *Set, arch_feature_index: Index) void {
const usize_index = arch_feature_index / @bitSizeOf(usize);
const bit_index = @intCast(ShiftInt, arch_feature_index % @bitSizeOf(usize));
set.ints[usize_index] |= @as(usize, 1) << bit_index;
}
/// Adds the specified feature set but not its dependencies.
pub fn addFeatureSet(set: *Set, other_set: Set) void {
set.ints = @as(std.meta.Vector(usize_count, usize), set.ints) |
@as(std.meta.Vector(usize_count, usize), other_set.ints);
}
/// Removes the specified feature but not its dependents.
pub fn removeFeature(set: *Set, arch_feature_index: Index) void {
const usize_index = arch_feature_index / @bitSizeOf(usize);
const bit_index = @intCast(ShiftInt, arch_feature_index % @bitSizeOf(usize));
set.ints[usize_index] &= ~(@as(usize, 1) << bit_index);
}
/// Removes the specified feature but not its dependents.
pub fn removeFeatureSet(set: *Set, other_set: Set) void {
set.ints = @as(std.meta.Vector(usize_count, usize), set.ints) &
~@as(std.meta.Vector(usize_count, usize), other_set.ints);
}
pub fn populateDependencies(set: *Set, all_features_list: []const Cpu.Feature) void {
@setEvalBranchQuota(1000000);
var old = set.ints;
while (true) {
for (all_features_list) |feature, index_usize| {
const index = @intCast(Index, index_usize);
if (set.isEnabled(index)) {
set.addFeatureSet(feature.dependencies);
}
}
const nothing_changed = mem.eql(usize, &old, &set.ints);
if (nothing_changed) return;
old = set.ints;
}
}
pub fn asBytes(set: *const Set) *const [byte_count]u8 {
return @ptrCast(*const [byte_count]u8, &set.ints);
}
pub fn eql(set: Set, other: Set) bool {
return mem.eql(usize, &set.ints, &other.ints);
}
};
pub fn feature_set_fns(comptime F: type) type {
return struct {
/// Populates only the feature bits specified.
pub fn featureSet(features: []const F) Set {
var x = Set.empty_workaround(); // TODO remove empty_workaround
for (features) |feature| {
x.addFeature(@enumToInt(feature));
}
return x;
}
/// Returns true if the specified feature is enabled.
pub fn featureSetHas(set: Set, feature: F) bool {
return set.isEnabled(@enumToInt(feature));
}
/// Returns true if any specified feature is enabled.
pub fn featureSetHasAny(set: Set, features: anytype) bool {
comptime std.debug.assert(std.meta.trait.isIndexable(@TypeOf(features)));
inline for (features) |feature| {
if (set.isEnabled(@enumToInt(@as(F, feature)))) return true;
}
return false;
}
/// Returns true if every specified feature is enabled.
pub fn featureSetHasAll(set: Set, features: anytype) bool {
comptime std.debug.assert(std.meta.trait.isIndexable(@TypeOf(features)));
inline for (features) |feature| {
if (!set.isEnabled(@enumToInt(@as(F, feature)))) return false;
}
return true;
}
};
}
};
pub const Arch = enum {
arm,
armeb,
aarch64,
aarch64_be,
aarch64_32,
arc,
avr,
bpfel,
bpfeb,
csky,
hexagon,
mips,
mipsel,
mips64,
mips64el,
msp430,
powerpc,
powerpcle,
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,
kalimba,
shave,
lanai,
wasm32,
wasm64,
renderscript32,
renderscript64,
ve,
// Stage1 currently assumes that architectures above this comment
// map one-to-one with the ZigLLVM_ArchType enum.
spu_2,
spirv32,
spirv64,
pub fn isX86(arch: Arch) bool {
return switch (arch) {
.i386, .x86_64 => true,
else => false,
};
}
pub fn isARM(arch: Arch) bool {
return switch (arch) {
.arm, .armeb => true,
else => false,
};
}
pub fn isThumb(arch: Arch) bool {
return switch (arch) {
.thumb, .thumbeb => true,
else => false,
};
}
pub fn isWasm(arch: Arch) bool {
return switch (arch) {
.wasm32, .wasm64 => true,
else => false,
};
}
pub fn isRISCV(arch: Arch) bool {
return switch (arch) {
.riscv32, .riscv64 => true,
else => false,
};
}
pub fn isMIPS(arch: Arch) bool {
return switch (arch) {
.mips, .mipsel, .mips64, .mips64el => true,
else => false,
};
}
pub fn isPPC(arch: Arch) bool {
return switch (arch) {
.powerpc, .powerpcle => true,
else => false,
};
}
pub fn isPPC64(arch: Arch) bool {
return switch (arch) {
.powerpc64, .powerpc64le => true,
else => false,
};
}
pub fn isSPARC(arch: Arch) bool {
return switch (arch) {
.sparc, .sparcel, .sparcv9 => true,
else => false,
};
}
pub fn isSPIRV(arch: Arch) bool {
return switch (arch) {
.spirv32, .spirv64 => true,
else => false,
};
}
pub fn parseCpuModel(arch: Arch, cpu_name: []const u8) !*const Cpu.Model {
for (arch.allCpuModels()) |cpu| {
if (mem.eql(u8, cpu_name, cpu.name)) {
return cpu;
}
}
return error.UnknownCpuModel;
}
pub fn toElfMachine(arch: Arch) std.elf.EM {
return switch (arch) {
.avr => ._AVR,
.msp430 => ._MSP430,
.arc => ._ARC,
.arm => ._ARM,
.armeb => ._ARM,
.hexagon => ._HEXAGON,
.le32 => ._NONE,
.mips => ._MIPS,
.mipsel => ._MIPS_RS3_LE,
.powerpc, .powerpcle => ._PPC,
.r600 => ._NONE,
.riscv32 => ._RISCV,
.sparc => ._SPARC,
.sparcel => ._SPARC,
.tce => ._NONE,
.tcele => ._NONE,
.thumb => ._ARM,
.thumbeb => ._ARM,
.i386 => ._386,
.xcore => ._XCORE,
.nvptx => ._NONE,
.amdil => ._NONE,
.hsail => ._NONE,
.spir => ._NONE,
.kalimba => ._CSR_KALIMBA,
.shave => ._NONE,
.lanai => ._LANAI,
.wasm32 => ._NONE,
.renderscript32 => ._NONE,
.aarch64_32 => ._AARCH64,
.aarch64 => ._AARCH64,
.aarch64_be => ._AARCH64,
.mips64 => ._MIPS,
.mips64el => ._MIPS_RS3_LE,
.powerpc64 => ._PPC64,
.powerpc64le => ._PPC64,
.riscv64 => ._RISCV,
.x86_64 => ._X86_64,
.nvptx64 => ._NONE,
.le64 => ._NONE,
.amdil64 => ._NONE,
.hsail64 => ._NONE,
.spir64 => ._NONE,
.wasm64 => ._NONE,
.renderscript64 => ._NONE,
.amdgcn => ._NONE,
.bpfel => ._BPF,
.bpfeb => ._BPF,
.csky => ._NONE,
.sparcv9 => ._SPARCV9,
.s390x => ._S390,
.ve => ._NONE,
.spu_2 => ._SPU_2,
.spirv32 => ._NONE,
.spirv64 => ._NONE,
};
}
pub fn toCoffMachine(arch: Arch) std.coff.MachineType {
return switch (arch) {
.avr => .Unknown,
.msp430 => .Unknown,
.arc => .Unknown,
.arm => .ARM,
.armeb => .Unknown,
.hexagon => .Unknown,
.le32 => .Unknown,
.mips => .Unknown,
.mipsel => .Unknown,
.powerpc, .powerpcle => .POWERPC,
.r600 => .Unknown,
.riscv32 => .RISCV32,
.sparc => .Unknown,
.sparcel => .Unknown,
.tce => .Unknown,
.tcele => .Unknown,
.thumb => .Thumb,
.thumbeb => .Thumb,
.i386 => .I386,
.xcore => .Unknown,
.nvptx => .Unknown,
.amdil => .Unknown,
.hsail => .Unknown,
.spir => .Unknown,
.kalimba => .Unknown,
.shave => .Unknown,
.lanai => .Unknown,
.wasm32 => .Unknown,
.renderscript32 => .Unknown,
.aarch64_32 => .ARM64,
.aarch64 => .ARM64,
.aarch64_be => .Unknown,
.mips64 => .Unknown,
.mips64el => .Unknown,
.powerpc64 => .Unknown,
.powerpc64le => .Unknown,
.riscv64 => .RISCV64,
.x86_64 => .X64,
.nvptx64 => .Unknown,
.le64 => .Unknown,
.amdil64 => .Unknown,
.hsail64 => .Unknown,
.spir64 => .Unknown,
.wasm64 => .Unknown,
.renderscript64 => .Unknown,
.amdgcn => .Unknown,
.bpfel => .Unknown,
.bpfeb => .Unknown,
.csky => .Unknown,
.sparcv9 => .Unknown,
.s390x => .Unknown,
.ve => .Unknown,
.spu_2 => .Unknown,
.spirv32 => .Unknown,
.spirv64 => .Unknown,
};
}
pub fn endian(arch: Arch) builtin.Endian {
return switch (arch) {
.avr,
.arm,
.aarch64_32,
.aarch64,
.amdgcn,
.amdil,
.amdil64,
.bpfel,
.csky,
.hexagon,
.hsail,
.hsail64,
.kalimba,
.le32,
.le64,
.mipsel,
.mips64el,
.msp430,
.nvptx,
.nvptx64,
.sparcel,
.tcele,
.powerpcle,
.powerpc64le,
.r600,
.riscv32,
.riscv64,
.i386,
.x86_64,
.wasm32,
.wasm64,
.xcore,
.thumb,
.spir,
.spir64,
.renderscript32,
.renderscript64,
.shave,
.ve,
.spu_2,
// GPU bitness is opaque. For now, assume little endian.
.spirv32,
.spirv64,
=> .Little,
.arc,
.armeb,
.aarch64_be,
.bpfeb,
.mips,
.mips64,
.powerpc,
.powerpc64,
.thumbeb,
.sparc,
.sparcv9,
.tce,
.lanai,
.s390x,
=> .Big,
};
}
pub fn ptrBitWidth(arch: Arch) u16 {
switch (arch) {
.avr,
.msp430,
.spu_2,
=> return 16,
.arc,
.arm,
.armeb,
.csky,
.hexagon,
.le32,
.mips,
.mipsel,
.powerpc,
.powerpcle,
.r600,
.riscv32,
.sparc,
.sparcel,
.tce,
.tcele,
.thumb,
.thumbeb,
.i386,
.xcore,
.nvptx,
.amdil,
.hsail,
.spir,
.kalimba,
.shave,
.lanai,
.wasm32,
.renderscript32,
.aarch64_32,
.spirv32,
=> return 32,
.aarch64,
.aarch64_be,
.mips64,
.mips64el,
.powerpc64,
.powerpc64le,
.riscv64,
.x86_64,
.nvptx64,
.le64,
.amdil64,
.hsail64,
.spir64,
.wasm64,
.renderscript64,
.amdgcn,
.bpfel,
.bpfeb,
.sparcv9,
.s390x,
.ve,
.spirv64,
=> return 64,
}
}
/// Returns a name that matches the lib/std/target/* source file name.
pub fn genericName(arch: Arch) []const u8 {
return switch (arch) {
.arm, .armeb, .thumb, .thumbeb => "arm",
.aarch64, .aarch64_be, .aarch64_32 => "aarch64",
.bpfel, .bpfeb => "bpf",
.mips, .mipsel, .mips64, .mips64el => "mips",
.powerpc, .powerpcle, .powerpc64, .powerpc64le => "powerpc",
.amdgcn => "amdgpu",
.riscv32, .riscv64 => "riscv",
.sparc, .sparcv9, .sparcel => "sparc",
.s390x => "systemz",
.i386, .x86_64 => "x86",
.nvptx, .nvptx64 => "nvptx",
.wasm32, .wasm64 => "wasm",
.spirv32, .spirv64 => "spir-v",
else => @tagName(arch),
};
}
/// All CPU features Zig is aware of, sorted lexicographically by name.
pub fn allFeaturesList(arch: Arch) []const Cpu.Feature {
return switch (arch) {
.arm, .armeb, .thumb, .thumbeb => &arm.all_features,
.aarch64, .aarch64_be, .aarch64_32 => &aarch64.all_features,
.avr => &avr.all_features,
.bpfel, .bpfeb => &bpf.all_features,
.hexagon => &hexagon.all_features,
.mips, .mipsel, .mips64, .mips64el => &mips.all_features,
.msp430 => &msp430.all_features,
.powerpc, .powerpcle, .powerpc64, .powerpc64le => &powerpc.all_features,
.amdgcn => &amdgpu.all_features,
.riscv32, .riscv64 => &riscv.all_features,
.sparc, .sparcv9, .sparcel => &sparc.all_features,
.spirv32, .spirv64 => &spirv.all_features,
.s390x => &systemz.all_features,
.i386, .x86_64 => &x86.all_features,
.nvptx, .nvptx64 => &nvptx.all_features,
.ve => &ve.all_features,
.wasm32, .wasm64 => &wasm.all_features,
else => &[0]Cpu.Feature{},
};
}
/// All processors Zig is aware of, sorted lexicographically by name.
pub fn allCpuModels(arch: Arch) []const *const Cpu.Model {
return switch (arch) {
.arm, .armeb, .thumb, .thumbeb => comptime allCpusFromDecls(arm.cpu),
.aarch64, .aarch64_be, .aarch64_32 => comptime allCpusFromDecls(aarch64.cpu),
.avr => comptime allCpusFromDecls(avr.cpu),
.bpfel, .bpfeb => comptime allCpusFromDecls(bpf.cpu),
.hexagon => comptime allCpusFromDecls(hexagon.cpu),
.mips, .mipsel, .mips64, .mips64el => comptime allCpusFromDecls(mips.cpu),
.msp430 => comptime allCpusFromDecls(msp430.cpu),
.powerpc, .powerpcle, .powerpc64, .powerpc64le => comptime allCpusFromDecls(powerpc.cpu),
.amdgcn => comptime allCpusFromDecls(amdgpu.cpu),
.riscv32, .riscv64 => comptime allCpusFromDecls(riscv.cpu),
.sparc, .sparcv9, .sparcel => comptime allCpusFromDecls(sparc.cpu),
.s390x => comptime allCpusFromDecls(systemz.cpu),
.i386, .x86_64 => comptime allCpusFromDecls(x86.cpu),
.nvptx, .nvptx64 => comptime allCpusFromDecls(nvptx.cpu),
.ve => comptime allCpusFromDecls(ve.cpu),
.wasm32, .wasm64 => comptime allCpusFromDecls(wasm.cpu),
else => &[0]*const Model{},
};
}
fn allCpusFromDecls(comptime cpus: type) []const *const Cpu.Model {
const decls = std.meta.declarations(cpus);
var array: [decls.len]*const Cpu.Model = undefined;
for (decls) |decl, i| {
array[i] = &@field(cpus, decl.name);
}
return &array;
}
};
pub const Model = struct {
name: []const u8,
llvm_name: ?[:0]const u8,
features: Feature.Set,
pub fn toCpu(model: *const Model, arch: Arch) Cpu {
var features = model.features;
features.populateDependencies(arch.allFeaturesList());
return .{
.arch = arch,
.model = model,
.features = features,
};
}
pub fn generic(arch: Arch) *const Model {
const S = struct {
const generic_model = Model{
.name = "generic",
.llvm_name = null,
.features = Cpu.Feature.Set.empty,
};
};
return switch (arch) {
.arm, .armeb, .thumb, .thumbeb => &arm.cpu.generic,
.aarch64, .aarch64_be, .aarch64_32 => &aarch64.cpu.generic,
.avr => &avr.cpu.avr2,
.bpfel, .bpfeb => &bpf.cpu.generic,
.hexagon => &hexagon.cpu.generic,
.mips, .mipsel => &mips.cpu.mips32,
.mips64, .mips64el => &mips.cpu.mips64,
.msp430 => &msp430.cpu.generic,
.powerpc => &powerpc.cpu.ppc,
.powerpcle => &powerpc.cpu.ppc,
.powerpc64 => &powerpc.cpu.ppc64,
.powerpc64le => &powerpc.cpu.ppc64le,
.amdgcn => &amdgpu.cpu.generic,
.riscv32 => &riscv.cpu.generic_rv32,
.riscv64 => &riscv.cpu.generic_rv64,
.sparc, .sparcel => &sparc.cpu.generic,
.sparcv9 => &sparc.cpu.v9,
.s390x => &systemz.cpu.generic,
.i386 => &x86.cpu._i386,
.x86_64 => &x86.cpu.x86_64,
.nvptx, .nvptx64 => &nvptx.cpu.sm_20,
.ve => &ve.cpu.generic,
.wasm32, .wasm64 => &wasm.cpu.generic,
else => &S.generic_model,
};
}
pub fn baseline(arch: Arch) *const Model {
return switch (arch) {
.arm, .armeb, .thumb, .thumbeb => &arm.cpu.baseline,
.riscv32 => &riscv.cpu.baseline_rv32,
.riscv64 => &riscv.cpu.baseline_rv64,
.i386 => &x86.cpu.pentium4,
.nvptx, .nvptx64 => &nvptx.cpu.sm_20,
.sparc, .sparcel => &sparc.cpu.v8,
else => generic(arch),
};
}
};
/// The "default" set of CPU features for cross-compiling. A conservative set
/// of features that is expected to be supported on most available hardware.
pub fn baseline(arch: Arch) Cpu {
return Model.baseline(arch).toCpu(arch);
}
};
pub const current = builtin.target;
pub const stack_align = 16;
pub fn zigTriple(self: Target, allocator: *mem.Allocator) ![]u8 {
return std.zig.CrossTarget.fromTarget(self).zigTriple(allocator);
}
pub fn linuxTripleSimple(allocator: *mem.Allocator, cpu_arch: Cpu.Arch, os_tag: Os.Tag, abi: Abi) ![]u8 {
return std.fmt.allocPrint(allocator, "{s}-{s}-{s}", .{ @tagName(cpu_arch), @tagName(os_tag), @tagName(abi) });
}
pub fn linuxTriple(self: Target, allocator: *mem.Allocator) ![]u8 {
return linuxTripleSimple(allocator, self.cpu.arch, self.os.tag, self.abi);
}
pub fn oFileExt_os_abi(os_tag: Os.Tag, abi: Abi) [:0]const u8 {
if (abi == .msvc) {
return ".obj";
}
switch (os_tag) {
.windows, .uefi => return ".obj",
else => return ".o",
}
}
pub fn oFileExt(self: Target) [:0]const u8 {
return oFileExt_os_abi(self.os.tag, self.abi);
}
pub fn exeFileExtSimple(cpu_arch: Cpu.Arch, os_tag: Os.Tag) [:0]const u8 {
switch (os_tag) {
.windows => return ".exe",
.uefi => return ".efi",
else => if (cpu_arch.isWasm()) {
return ".wasm";
} else {
return "";
},
}
}
pub fn exeFileExt(self: Target) [:0]const u8 {
return exeFileExtSimple(self.cpu.arch, self.os.tag);
}
pub fn staticLibSuffix_os_abi(os_tag: Os.Tag, abi: Abi) [:0]const u8 {
if (abi == .msvc) {
return ".lib";
}
switch (os_tag) {
.windows, .uefi => return ".lib",
else => return ".a",
}
}
pub fn staticLibSuffix(self: Target) [:0]const u8 {
return staticLibSuffix_os_abi(self.os.tag, self.abi);
}
pub fn dynamicLibSuffix(self: Target) [:0]const u8 {
return self.os.tag.dynamicLibSuffix();
}
pub fn libPrefix_os_abi(os_tag: Os.Tag, abi: Abi) [:0]const u8 {
if (abi == .msvc) {
return "";
}
switch (os_tag) {
.windows, .uefi => return "",
else => return "lib",
}
}
pub fn libPrefix(self: Target) [:0]const u8 {
return libPrefix_os_abi(self.os.tag, self.abi);
}
pub fn getObjectFormatSimple(os_tag: Os.Tag, cpu_arch: Cpu.Arch) ObjectFormat {
if (os_tag == .windows or os_tag == .uefi) {
return .coff;
} else if (os_tag.isDarwin()) {
return .macho;
}
if (cpu_arch.isWasm()) {
return .wasm;
}
if (cpu_arch.isSPIRV()) {
return .spirv;
}
return .elf;
}
pub fn getObjectFormat(self: Target) ObjectFormat {
return getObjectFormatSimple(self.os.tag, self.cpu.arch);
}
pub fn isMinGW(self: Target) bool {
return self.os.tag == .windows and self.isGnu();
}
pub fn isGnu(self: Target) bool {
return self.abi.isGnu();
}
pub fn isMusl(self: Target) bool {
return self.abi.isMusl();
}
pub fn isAndroid(self: Target) bool {
return switch (self.abi) {
.android => true,
else => false,
};
}
pub fn isWasm(self: Target) bool {
return self.cpu.arch.isWasm();
}
pub fn isDarwin(self: Target) bool {
return self.os.tag.isDarwin();
}
pub fn isGnuLibC_os_tag_abi(os_tag: Os.Tag, abi: Abi) bool {
return os_tag == .linux and abi.isGnu();
}
pub fn isGnuLibC(self: Target) bool {
return isGnuLibC_os_tag_abi(self.os.tag, self.abi);
}
pub fn supportsNewStackCall(self: Target) bool {
return !self.cpu.arch.isWasm();
}
pub const FloatAbi = enum {
hard,
soft,
soft_fp,
};
pub fn getFloatAbi(self: Target) FloatAbi {
return self.abi.floatAbi();
}
pub fn hasDynamicLinker(self: Target) bool {
if (self.cpu.arch.isWasm()) {
return false;
}
switch (self.os.tag) {
.freestanding,
.ios,
.tvos,
.watchos,
.macos,
.uefi,
.windows,
.emscripten,
.opencl,
.glsl450,
.vulkan,
.other,
=> return false,
else => return true,
}
}
pub const DynamicLinker = struct {
/// Contains the memory used to store the dynamic linker path. This field should
/// not be used directly. See `get` and `set`. This field exists so that this API requires no allocator.
buffer: [255]u8 = undefined,
/// Used to construct the dynamic linker path. This field should not be used
/// directly. See `get` and `set`.
max_byte: ?u8 = null,
/// Asserts that the length is less than or equal to 255 bytes.
pub fn init(dl_or_null: ?[]const u8) DynamicLinker {
var result: DynamicLinker = undefined;
result.set(dl_or_null);
return result;
}
/// The returned memory has the same lifetime as the `DynamicLinker`.
pub fn get(self: *const DynamicLinker) ?[]const u8 {
const m: usize = self.max_byte orelse return null;
return self.buffer[0 .. m + 1];
}
/// Asserts that the length is less than or equal to 255 bytes.
pub fn set(self: *DynamicLinker, dl_or_null: ?[]const u8) void {
if (dl_or_null) |dl| {
mem.copy(u8, &self.buffer, dl);
self.max_byte = @intCast(u8, dl.len - 1);
} else {
self.max_byte = null;
}
}
};
pub fn standardDynamicLinkerPath(self: Target) DynamicLinker {
var result: DynamicLinker = .{};
const S = struct {
fn print(r: *DynamicLinker, comptime fmt: []const u8, args: anytype) DynamicLinker {
r.max_byte = @intCast(u8, (std.fmt.bufPrint(&r.buffer, fmt, args) catch unreachable).len - 1);
return r.*;
}
fn copy(r: *DynamicLinker, s: []const u8) DynamicLinker {
mem.copy(u8, &r.buffer, s);
r.max_byte = @intCast(u8, s.len - 1);
return r.*;
}
};
const print = S.print;
const copy = S.copy;
if (self.abi == .android) {
const suffix = if (self.cpu.arch.ptrBitWidth() == 64) "64" else "";
return print(&result, "/system/bin/linker{s}", .{suffix});
}
if (self.abi.isMusl()) {
const is_arm = switch (self.cpu.arch) {
.arm, .armeb, .thumb, .thumbeb => true,
else => false,
};
const arch_part = switch (self.cpu.arch) {
.arm, .thumb => "arm",
.armeb, .thumbeb => "armeb",
else => |arch| @tagName(arch),
};
const arch_suffix = if (is_arm and self.abi.floatAbi() == .hard) "hf" else "";
return print(&result, "/lib/ld-musl-{s}{s}.so.1", .{ arch_part, arch_suffix });
}
switch (self.os.tag) {
.freebsd => return copy(&result, "/libexec/ld-elf.so.1"),
.netbsd => return copy(&result, "/libexec/ld.elf_so"),
.openbsd => return copy(&result, "/usr/libexec/ld.so"),
.dragonfly => return copy(&result, "/libexec/ld-elf.so.2"),
.linux => switch (self.cpu.arch) {
.i386,
.sparc,
.sparcel,
=> return copy(&result, "/lib/ld-linux.so.2"),
.aarch64 => return copy(&result, "/lib/ld-linux-aarch64.so.1"),
.aarch64_be => return copy(&result, "/lib/ld-linux-aarch64_be.so.1"),
.aarch64_32 => return copy(&result, "/lib/ld-linux-aarch64_32.so.1"),
.arm,
.armeb,
.thumb,
.thumbeb,
=> return copy(&result, switch (self.abi.floatAbi()) {
.hard => "/lib/ld-linux-armhf.so.3",
else => "/lib/ld-linux.so.3",
}),
.mips,
.mipsel,
.mips64,
.mips64el,
=> {
const lib_suffix = switch (self.abi) {
.gnuabin32, .gnux32 => "32",
.gnuabi64 => "64",
else => "",
};
const is_nan_2008 = mips.featureSetHas(self.cpu.features, .nan2008);
const loader = if (is_nan_2008) "ld-linux-mipsn8.so.1" else "ld.so.1";
return print(&result, "/lib{s}/{s}", .{ lib_suffix, loader });
},
.powerpc, .powerpcle => return copy(&result, "/lib/ld.so.1"),
.powerpc64, .powerpc64le => return copy(&result, "/lib64/ld64.so.2"),
.s390x => return copy(&result, "/lib64/ld64.so.1"),
.sparcv9 => return copy(&result, "/lib64/ld-linux.so.2"),
.x86_64 => return copy(&result, switch (self.abi) {
.gnux32 => "/libx32/ld-linux-x32.so.2",
else => "/lib64/ld-linux-x86-64.so.2",
}),
.riscv32 => return copy(&result, "/lib/ld-linux-riscv32-ilp32.so.1"),
.riscv64 => return copy(&result, "/lib/ld-linux-riscv64-lp64.so.1"),
// Architectures in this list have been verified as not having a standard
// dynamic linker path.
.wasm32,
.wasm64,
.bpfel,
.bpfeb,
.nvptx,
.nvptx64,
.spu_2,
.avr,
.spirv32,
.spirv64,
=> return result,
// TODO go over each item in this list and either move it to the above list, or
// implement the standard dynamic linker path code for it.
.arc,
.csky,
.hexagon,
.msp430,
.r600,
.amdgcn,
.tce,
.tcele,
.xcore,
.le32,
.le64,
.amdil,
.amdil64,
.hsail,
.hsail64,
.spir,
.spir64,
.kalimba,
.shave,
.lanai,
.renderscript32,
.renderscript64,
.ve,
=> return result,
},
.ios,
.tvos,
.watchos,
.macos,
=> return copy(&result, "/usr/lib/dyld"),
// Operating systems in this list have been verified as not having a standard
// dynamic linker path.
.freestanding,
.uefi,
.windows,
.emscripten,
.wasi,
.opencl,
.glsl450,
.vulkan,
.other,
=> return result,
// TODO revisit when multi-arch for Haiku is available
.haiku => return copy(&result, "/system/runtime_loader"),
// TODO go over each item in this list and either move it to the above list, or
// implement the standard dynamic linker path code for it.
.ananas,
.cloudabi,
.fuchsia,
.kfreebsd,
.lv2,
.solaris,
.zos,
.minix,
.rtems,
.nacl,
.aix,
.cuda,
.nvcl,
.amdhsa,
.ps4,
.elfiamcu,
.mesa3d,
.contiki,
.amdpal,
.hermit,
.hurd,
=> return result,
}
}
/// Return whether or not the given host target is capable of executing natively executables
/// of the other target.
pub fn canExecBinariesOf(host_target: Target, binary_target: Target) bool {
if (host_target.os.tag != binary_target.os.tag)
return false;
if (host_target.cpu.arch == binary_target.cpu.arch)
return true;
if (host_target.cpu.arch == .x86_64 and binary_target.cpu.arch == .i386)
return true;
if (host_target.cpu.arch == .aarch64 and binary_target.cpu.arch == .arm)
return true;
if (host_target.cpu.arch == .aarch64_be and binary_target.cpu.arch == .armeb)
return true;
return false;
}
};
test {
std.testing.refAllDecls(Target.Cpu.Arch);
} | lib/std/target.zig |
const std = @import("std");
const Compilation = @import("compilation.zig").Compilation;
const llvm = @import("llvm.zig");
const c = @import("c.zig");
const ir = @import("ir.zig");
const Value = @import("value.zig").Value;
const Type = @import("type.zig").Type;
const Scope = @import("scope.zig").Scope;
const util = @import("util.zig");
const event = std.event;
const assert = std.debug.assert;
const DW = std.dwarf;
const maxInt = std.math.maxInt;
pub async fn renderToLlvm(comp: *Compilation, fn_val: *Value.Fn, code: *ir.Code) Compilation.BuildError!void {
fn_val.base.ref();
defer fn_val.base.deref(comp);
defer code.destroy(comp.gpa());
var output_path = try comp.createRandomOutputPath(comp.target.oFileExt());
errdefer output_path.deinit();
const llvm_handle = try comp.zig_compiler.getAnyLlvmContext();
defer llvm_handle.release(comp.zig_compiler);
const context = llvm_handle.node.data;
const module = llvm.ModuleCreateWithNameInContext(comp.name.span(), context) orelse return error.OutOfMemory;
defer llvm.DisposeModule(module);
llvm.SetTarget(module, comp.llvm_triple.span());
llvm.SetDataLayout(module, comp.target_layout_str);
if (comp.target.getObjectFormat() == .coff) {
llvm.AddModuleCodeViewFlag(module);
} else {
llvm.AddModuleDebugInfoFlag(module);
}
const builder = llvm.CreateBuilderInContext(context) orelse return error.OutOfMemory;
defer llvm.DisposeBuilder(builder);
const dibuilder = llvm.CreateDIBuilder(module, true) orelse return error.OutOfMemory;
defer llvm.DisposeDIBuilder(dibuilder);
// Don't use ZIG_VERSION_STRING here. LLVM misparses it when it includes
// the git revision.
const producer = try std.fmt.allocPrintZ(&code.arena.allocator, "zig {}.{}.{}", .{
@as(u32, c.ZIG_VERSION_MAJOR),
@as(u32, c.ZIG_VERSION_MINOR),
@as(u32, c.ZIG_VERSION_PATCH),
});
const flags = "";
const runtime_version = 0;
const compile_unit_file = llvm.CreateFile(
dibuilder,
comp.name.span(),
comp.root_package.root_src_dir.span(),
) orelse return error.OutOfMemory;
const is_optimized = comp.build_mode != .Debug;
const compile_unit = llvm.CreateCompileUnit(
dibuilder,
DW.LANG_C99,
compile_unit_file,
producer,
is_optimized,
flags,
runtime_version,
"",
0,
!comp.strip,
) orelse return error.OutOfMemory;
var ofile = ObjectFile{
.comp = comp,
.module = module,
.builder = builder,
.dibuilder = dibuilder,
.context = context,
.lock = event.Lock.init(),
.arena = &code.arena.allocator,
};
try renderToLlvmModule(&ofile, fn_val, code);
// TODO module level assembly
//if (buf_len(&g->global_asm) != 0) {
// LLVMSetModuleInlineAsm(g->module, buf_ptr(&g->global_asm));
//}
llvm.DIBuilderFinalize(dibuilder);
if (comp.verbose_llvm_ir) {
std.debug.warn("raw module:\n", .{});
llvm.DumpModule(ofile.module);
}
// verify the llvm module when safety is on
if (std.debug.runtime_safety) {
var error_ptr: ?[*:0]u8 = null;
_ = llvm.VerifyModule(ofile.module, llvm.AbortProcessAction, &error_ptr);
}
const is_small = comp.build_mode == .ReleaseSmall;
const is_debug = comp.build_mode == .Debug;
var err_msg: [*:0]u8 = undefined;
// TODO integrate this with evented I/O
if (llvm.TargetMachineEmitToFile(
comp.target_machine,
module,
output_path.span(),
llvm.EmitBinary,
&err_msg,
is_debug,
is_small,
)) {
if (std.debug.runtime_safety) {
std.debug.panic("unable to write object file {}: {s}\n", .{ output_path.span(), err_msg });
}
return error.WritingObjectFileFailed;
}
//validate_inline_fns(g); TODO
fn_val.containing_object = output_path;
if (comp.verbose_llvm_ir) {
std.debug.warn("optimized module:\n", .{});
llvm.DumpModule(ofile.module);
}
if (comp.verbose_link) {
std.debug.warn("created {}\n", .{output_path.span()});
}
}
pub const ObjectFile = struct {
comp: *Compilation,
module: *llvm.Module,
builder: *llvm.Builder,
dibuilder: *llvm.DIBuilder,
context: *llvm.Context,
lock: event.Lock,
arena: *std.mem.Allocator,
fn gpa(self: *ObjectFile) *std.mem.Allocator {
return self.comp.gpa();
}
};
pub fn renderToLlvmModule(ofile: *ObjectFile, fn_val: *Value.Fn, code: *ir.Code) !void {
// TODO audit more of codegen.cpp:fn_llvm_value and port more logic
const llvm_fn_type = try fn_val.base.typ.getLlvmType(ofile.arena, ofile.context);
const llvm_fn = llvm.AddFunction(
ofile.module,
fn_val.symbol_name.span(),
llvm_fn_type,
) orelse return error.OutOfMemory;
const want_fn_safety = fn_val.block_scope.?.safety.get(ofile.comp);
if (want_fn_safety and ofile.comp.haveLibC()) {
try addLLVMFnAttr(ofile, llvm_fn, "sspstrong");
try addLLVMFnAttrStr(ofile, llvm_fn, "stack-protector-buffer-size", "4");
}
// TODO
//if (fn_val.align_stack) |align_stack| {
// try addLLVMFnAttrInt(ofile, llvm_fn, "alignstack", align_stack);
//}
const fn_type = fn_val.base.typ.cast(Type.Fn).?;
const fn_type_normal = &fn_type.key.data.Normal;
try addLLVMFnAttr(ofile, llvm_fn, "nounwind");
//add_uwtable_attr(g, fn_table_entry->llvm_value);
try addLLVMFnAttr(ofile, llvm_fn, "nobuiltin");
//if (g->build_mode == BuildModeDebug && fn_table_entry->fn_inline != FnInlineAlways) {
// ZigLLVMAddFunctionAttr(fn_table_entry->llvm_value, "no-frame-pointer-elim", "true");
// ZigLLVMAddFunctionAttr(fn_table_entry->llvm_value, "no-frame-pointer-elim-non-leaf", nullptr);
//}
//if (fn_table_entry->section_name) {
// LLVMSetSection(fn_table_entry->llvm_value, buf_ptr(fn_table_entry->section_name));
//}
//if (fn_table_entry->align_bytes > 0) {
// LLVMSetAlignment(fn_table_entry->llvm_value, (unsigned)fn_table_entry->align_bytes);
//} else {
// // We'd like to set the best alignment for the function here, but on Darwin LLVM gives
// // "Cannot getTypeInfo() on a type that is unsized!" assertion failure when calling
// // any of the functions for getting alignment. Not specifying the alignment should
// // use the ABI alignment, which is fine.
//}
//if (!type_has_bits(return_type)) {
// // nothing to do
//} else if (type_is_codegen_pointer(return_type)) {
// addLLVMAttr(fn_table_entry->llvm_value, 0, "nonnull");
//} else if (handle_is_ptr(return_type) &&
// calling_convention_does_first_arg_return(fn_type->data.fn.fn_type_id.cc))
//{
// addLLVMArgAttr(fn_table_entry->llvm_value, 0, "sret");
// addLLVMArgAttr(fn_table_entry->llvm_value, 0, "nonnull");
//}
// TODO set parameter attributes
// TODO
//uint32_t err_ret_trace_arg_index = get_err_ret_trace_arg_index(g, fn_table_entry);
//if (err_ret_trace_arg_index != UINT32_MAX) {
// addLLVMArgAttr(fn_table_entry->llvm_value, (unsigned)err_ret_trace_arg_index, "nonnull");
//}
const cur_ret_ptr = if (fn_type_normal.return_type.handleIsPtr()) llvm.GetParam(llvm_fn, 0) else null;
// build all basic blocks
for (code.basic_block_list.span()) |bb| {
bb.llvm_block = llvm.AppendBasicBlockInContext(
ofile.context,
llvm_fn,
bb.name_hint,
) orelse return error.OutOfMemory;
}
const entry_bb = code.basic_block_list.at(0);
llvm.PositionBuilderAtEnd(ofile.builder, entry_bb.llvm_block);
llvm.ClearCurrentDebugLocation(ofile.builder);
// TODO set up error return tracing
// TODO allocate temporary stack values
const var_list = fn_type.non_key.Normal.variable_list.span();
// create debug variable declarations for variables and allocate all local variables
for (var_list) |var_scope, i| {
const var_type = switch (var_scope.data) {
.Const => unreachable,
.Param => |param| param.typ,
};
// if (!type_has_bits(var->value->type)) {
// continue;
// }
// if (ir_get_var_is_comptime(var))
// continue;
// if (type_requires_comptime(var->value->type))
// continue;
// if (var->src_arg_index == SIZE_MAX) {
// var->value_ref = build_alloca(g, var->value->type, buf_ptr(&var->name), var->align_bytes);
// var->di_loc_var = ZigLLVMCreateAutoVariable(g->dbuilder, get_di_scope(g, var->parent_scope),
// buf_ptr(&var->name), import->di_file, (unsigned)(var->decl_node->line + 1),
// var->value->type->di_type, !g->strip_debug_symbols, 0);
// } else {
// it's a parameter
// assert(var->gen_arg_index != SIZE_MAX);
// TypeTableEntry *gen_type;
// FnGenParamInfo *gen_info = &fn_table_entry->type_entry->data.fn.gen_param_info[var->src_arg_index];
if (var_type.handleIsPtr()) {
// if (gen_info->is_byval) {
// gen_type = var->value->type;
// } else {
// gen_type = gen_info->type;
// }
var_scope.data.Param.llvm_value = llvm.GetParam(llvm_fn, @intCast(c_uint, i));
} else {
// gen_type = var->value->type;
var_scope.data.Param.llvm_value = try renderAlloca(ofile, var_type, var_scope.name, .Abi);
}
// if (var->decl_node) {
// var->di_loc_var = ZigLLVMCreateParameterVariable(g->dbuilder, get_di_scope(g, var->parent_scope),
// buf_ptr(&var->name), import->di_file,
// (unsigned)(var->decl_node->line + 1),
// gen_type->di_type, !g->strip_debug_symbols, 0, (unsigned)(var->gen_arg_index + 1));
// }
// }
}
// TODO finishing error return trace setup. we have to do this after all the allocas.
// create debug variable declarations for parameters
// rely on the first variables in the variable_list being parameters.
//size_t next_var_i = 0;
for (fn_type.key.data.Normal.params) |param, i| {
//FnGenParamInfo *info = &fn_table_entry->type_entry->data.fn.gen_param_info[param_i];
//if (info->gen_index == SIZE_MAX)
// continue;
const scope_var = var_list[i];
//assert(variable->src_arg_index != SIZE_MAX);
//next_var_i += 1;
//assert(variable);
//assert(variable->value_ref);
if (!param.typ.handleIsPtr()) {
//clear_debug_source_node(g);
const llvm_param = llvm.GetParam(llvm_fn, @intCast(c_uint, i));
_ = try renderStoreUntyped(
ofile,
llvm_param,
scope_var.data.Param.llvm_value,
.Abi,
.Non,
);
}
//if (variable->decl_node) {
// gen_var_debug_decl(g, variable);
//}
}
for (code.basic_block_list.span()) |current_block| {
llvm.PositionBuilderAtEnd(ofile.builder, current_block.llvm_block);
for (current_block.instruction_list.span()) |instruction| {
if (instruction.ref_count == 0 and !instruction.hasSideEffects()) continue;
instruction.llvm_value = try instruction.render(ofile, fn_val);
}
current_block.llvm_exit_block = llvm.GetInsertBlock(ofile.builder);
}
}
fn addLLVMAttr(
ofile: *ObjectFile,
val: *llvm.Value,
attr_index: llvm.AttributeIndex,
attr_name: []const u8,
) !void {
const kind_id = llvm.GetEnumAttributeKindForName(attr_name.ptr, attr_name.len);
assert(kind_id != 0);
const llvm_attr = llvm.CreateEnumAttribute(ofile.context, kind_id, 0) orelse return error.OutOfMemory;
llvm.AddAttributeAtIndex(val, attr_index, llvm_attr);
}
fn addLLVMAttrStr(
ofile: *ObjectFile,
val: *llvm.Value,
attr_index: llvm.AttributeIndex,
attr_name: []const u8,
attr_val: []const u8,
) !void {
const llvm_attr = llvm.CreateStringAttribute(
ofile.context,
attr_name.ptr,
@intCast(c_uint, attr_name.len),
attr_val.ptr,
@intCast(c_uint, attr_val.len),
) orelse return error.OutOfMemory;
llvm.AddAttributeAtIndex(val, attr_index, llvm_attr);
}
fn addLLVMAttrInt(
val: *llvm.Value,
attr_index: llvm.AttributeIndex,
attr_name: []const u8,
attr_val: u64,
) !void {
const kind_id = llvm.GetEnumAttributeKindForName(attr_name.ptr, attr_name.len);
assert(kind_id != 0);
const llvm_attr = llvm.CreateEnumAttribute(ofile.context, kind_id, attr_val) orelse return error.OutOfMemory;
llvm.AddAttributeAtIndex(val, attr_index, llvm_attr);
}
fn addLLVMFnAttr(ofile: *ObjectFile, fn_val: *llvm.Value, attr_name: []const u8) !void {
return addLLVMAttr(ofile, fn_val, maxInt(llvm.AttributeIndex), attr_name);
}
fn addLLVMFnAttrStr(ofile: *ObjectFile, fn_val: *llvm.Value, attr_name: []const u8, attr_val: []const u8) !void {
return addLLVMAttrStr(ofile, fn_val, maxInt(llvm.AttributeIndex), attr_name, attr_val);
}
fn addLLVMFnAttrInt(ofile: *ObjectFile, fn_val: *llvm.Value, attr_name: []const u8, attr_val: u64) !void {
return addLLVMAttrInt(ofile, fn_val, maxInt(llvm.AttributeIndex), attr_name, attr_val);
}
fn renderLoadUntyped(
ofile: *ObjectFile,
ptr: *llvm.Value,
alignment: Type.Pointer.Align,
vol: Type.Pointer.Vol,
name: [*:0]const u8,
) !*llvm.Value {
const result = llvm.BuildLoad(ofile.builder, ptr, name) orelse return error.OutOfMemory;
switch (vol) {
.Non => {},
.Volatile => llvm.SetVolatile(result, 1),
}
llvm.SetAlignment(result, resolveAlign(ofile, alignment, llvm.GetElementType(llvm.TypeOf(ptr))));
return result;
}
fn renderLoad(ofile: *ObjectFile, ptr: *llvm.Value, ptr_type: *Type.Pointer, name: [*:0]const u8) !*llvm.Value {
return renderLoadUntyped(ofile, ptr, ptr_type.key.alignment, ptr_type.key.vol, name);
}
pub fn getHandleValue(ofile: *ObjectFile, ptr: *llvm.Value, ptr_type: *Type.Pointer) !?*llvm.Value {
const child_type = ptr_type.key.child_type;
if (!child_type.hasBits()) {
return null;
}
if (child_type.handleIsPtr()) {
return ptr;
}
return try renderLoad(ofile, ptr, ptr_type, "");
}
pub fn renderStoreUntyped(
ofile: *ObjectFile,
value: *llvm.Value,
ptr: *llvm.Value,
alignment: Type.Pointer.Align,
vol: Type.Pointer.Vol,
) !*llvm.Value {
const result = llvm.BuildStore(ofile.builder, value, ptr) orelse return error.OutOfMemory;
switch (vol) {
.Non => {},
.Volatile => llvm.SetVolatile(result, 1),
}
llvm.SetAlignment(result, resolveAlign(ofile, alignment, llvm.TypeOf(value)));
return result;
}
pub fn renderStore(
ofile: *ObjectFile,
value: *llvm.Value,
ptr: *llvm.Value,
ptr_type: *Type.Pointer,
) !*llvm.Value {
return renderStoreUntyped(ofile, value, ptr, ptr_type.key.alignment, ptr_type.key.vol);
}
pub fn renderAlloca(
ofile: *ObjectFile,
var_type: *Type,
name: []const u8,
alignment: Type.Pointer.Align,
) !*llvm.Value {
const llvm_var_type = try var_type.getLlvmType(ofile.arena, ofile.context);
const name_with_null = try std.cstr.addNullByte(ofile.arena, name);
const result = llvm.BuildAlloca(ofile.builder, llvm_var_type, @ptrCast([*:0]const u8, name_with_null.ptr)) orelse return error.OutOfMemory;
llvm.SetAlignment(result, resolveAlign(ofile, alignment, llvm_var_type));
return result;
}
pub fn resolveAlign(ofile: *ObjectFile, alignment: Type.Pointer.Align, llvm_type: *llvm.Type) u32 {
return switch (alignment) {
.Abi => return llvm.ABIAlignmentOfType(ofile.comp.target_data_ref, llvm_type),
.Override => |a| a,
};
} | src-self-hosted/codegen.zig |
const uefi = @import("std").os.uefi;
const Guid = uefi.Guid;
const Time = uefi.Time;
const Status = uefi.Status;
pub const FileProtocol = extern struct {
revision: u64,
_open: extern fn (*const FileProtocol, **const FileProtocol, [*:0]const u16, u64, u64) Status,
_close: extern fn (*const FileProtocol) Status,
_delete: extern fn (*const FileProtocol) Status,
_read: extern fn (*const FileProtocol, *usize, [*]u8) Status,
_write: extern fn (*const FileProtocol, *usize, [*]const u8) Status,
_get_info: extern fn (*const FileProtocol, *Guid, *usize, *c_void) Status,
_set_info: extern fn (*const FileProtocol, *Guid, usize, *const c_void) Status,
_flush: extern fn (*const FileProtocol) Status,
pub fn open(self: *const FileProtocol, new_handle: **const FileProtocol, file_name: [*:0]const u16, open_mode: u64, attributes: u64) Status {
return self._open(self, new_handle, file_name, open_mode, attributes);
}
pub fn close(self: *const FileProtocol) Status {
return self._close(self);
}
pub fn delete(self: *const FileProtocol) Status {
return self._delete(self);
}
pub fn read(self: *const FileProtocol, buffer_size: *usize, buffer: [*]u8) Status {
return self._read(self, buffer_size, buffer);
}
pub fn write(self: *const FileProtocol, buffer_size: *usize, buffer: [*]const u8) Status {
return self._write(self, buffer_size, buffer);
}
pub fn get_info(self: *const FileProtocol, information_type: *Guid, buffer_size: *usize, buffer: *c_void) Status {
return self._get_info(self, information_type, buffer_size, buffer);
}
pub fn set_info(self: *const FileProtocol, information_type: *Guid, buffer_size: usize, buffer: *const c_void) Status {
return self._set_info(self, information_type, buffer_size, buffer);
}
pub fn flush(self: *const FileProtocol) Status {
return self._flush(self);
}
pub const guid align(8) = Guid{
.time_low = 0x09576e92,
.time_mid = 0x6d3f,
.time_high_and_version = 0x11d2,
.clock_seq_high_and_reserved = 0x8e,
.clock_seq_low = 0x39,
.node = [_]u8{ 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b },
};
pub const efi_file_mode_read: u64 = 0x0000000000000001;
pub const efi_file_mode_write: u64 = 0x0000000000000002;
pub const efi_file_mode_create: u64 = 0x8000000000000000;
pub const efi_file_read_only: u64 = 0x0000000000000001;
pub const efi_file_hidden: u64 = 0x0000000000000002;
pub const efi_file_system: u64 = 0x0000000000000004;
pub const efi_file_reserved: u64 = 0x0000000000000008;
pub const efi_file_directory: u64 = 0x0000000000000010;
pub const efi_file_archive: u64 = 0x0000000000000020;
pub const efi_file_valid_attr: u64 = 0x0000000000000037;
};
pub const FileInfo = extern struct {
size: u64,
file_size: u64,
physical_size: u64,
create_time: Time,
last_access_time: Time,
modification_time: Time,
attribute: u64,
pub fn getFileName(self: *const FileInfo) [*:0]const u16 {
return @ptrCast([*:0]const u16, @ptrCast([*]const u8, self) + @sizeOf(FileInfo));
}
pub const efi_file_read_only: u64 = 0x0000000000000001;
pub const efi_file_hidden: u64 = 0x0000000000000002;
pub const efi_file_system: u64 = 0x0000000000000004;
pub const efi_file_reserved: u64 = 0x0000000000000008;
pub const efi_file_directory: u64 = 0x0000000000000010;
pub const efi_file_archive: u64 = 0x0000000000000020;
pub const efi_file_valid_attr: u64 = 0x0000000000000037;
}; | lib/std/os/uefi/protocols/file_protocol.zig |
const std = @import("std");
const mem = std.mem;
const math = std.math;
const assert = std.debug.assert;
const Allocator = mem.Allocator;
const term = @import("prim.zig");
// promote some primitive ops
pub const size = term.size;
pub const ignoreSignalInput = term.ignoreSignalInput;
pub const handleSignalInput = term.handleSignalInput;
pub const cursorShow = term.cursorShow;
pub const cursorHide = term.cursorHide;
pub const nextEvent = term.nextEvent;
pub const setTimeout = term.setTimeout;
pub const clear = term.clear;
pub const Event = term.Event;
pub const ErrorSet = struct {
pub const Term = term.ErrorSet;
pub const Write = Term.Write || std.os.WriteError;
pub const Utf8Encode = error{
Utf8CannotEncodeSurrogateHalf,
CodepointTooLarge,
};
};
usingnamespace @import("util.zig");
/// must be called before any buffers are `push`ed to the terminal.
pub fn init(allocator: *Allocator) ErrorSet.Term.Setup!void {
front = try Buffer.init(allocator, 24, 80);
errdefer front.deinit();
try term.setup(allocator);
}
/// should be called prior to program exit
pub fn deinit() void {
front.deinit();
term.teardown();
}
/// compare state of input buffer to a buffer tracking display state
/// and send changes to the terminal.
pub fn push(buffer: Buffer) (Allocator.Error || ErrorSet.Utf8Encode || ErrorSet.Write)!void {
// resizing the front buffer naively can lead to artifacting
// if we do not clear the terminal here.
if ((buffer.width != front.width) or (buffer.height != front.height)) {
try term.clear();
front.clear();
}
try front.resize(buffer.height, buffer.width);
var row: usize = 0;
//try term.beginSync();
while (row < buffer.height) : (row += 1) {
var col: usize = 0;
var last_touched: usize = buffer.width; // out of bounds, can't match col
while (col < buffer.width) : (col += 1) {
// go to the next character if these are the same.
if (Cell.eql(
front.cell(row, col),
buffer.cell(row, col),
)) continue;
// only send cursor movement sequence if the last modified
// cell was not the immediately previous cell in this row
if (last_touched != col)
try term.cursorTo(row, col);
last_touched = col + 1;
const cell = buffer.cell(row, col);
front.cellRef(row, col).* = cell;
var codepoint: [4]u8 = undefined;
const len = try std.unicode.utf8Encode(cell.char, &codepoint);
try term.sendSGR(cell.attribs);
try term.send(codepoint[0..len]);
}
}
//try term.endSync();
try term.flush();
}
/// structure that represents a single textual character on screen
pub const Cell = struct {
char: u21 = ' ',
attribs: term.SGR = term.SGR{},
fn eql(self: Cell, other: Cell) bool {
return self.char == other.char and self.attribs.eql(other.attribs);
}
};
/// structure on which terminal drawing and printing operations are performed.
pub const Buffer = struct {
data: []Cell,
height: usize,
width: usize,
allocator: *Allocator,
pub const Writer = std.io.Writer(
*WriteCursor,
WriteCursor.Error,
WriteCursor.writeFn,
);
/// State tracking for an `io.Writer` into a `Buffer`. Buffers do not hold onto
/// any information about cursor position, so a sequential operations like writing to
/// it is not well defined without a helper like this.
pub const WriteCursor = struct {
row_num: usize,
col_num: usize,
/// wrap determines how to continue writing when the the text meets
/// the last column in a row. In truncate mode, the text until the next newline
/// is dropped. In wrap mode, input is moved to the first column of the next row.
wrap: bool = false,
attribs: term.SGR = term.SGR{},
buffer: *Buffer,
const Error = error{ InvalidUtf8, InvalidCharacter };
fn writeFn(self: *WriteCursor, bytes: []const u8) Error!usize {
if (self.row_num >= self.buffer.height) return 0;
var cp_iter = (try std.unicode.Utf8View.init(bytes)).iterator();
var bytes_written: usize = 0;
while (cp_iter.nextCodepoint()) |cp| {
if (self.col_num >= self.buffer.width and self.wrap) {
self.col_num = 0;
self.row_num += 1;
}
if (self.row_num >= self.buffer.height) return bytes_written;
switch (cp) {
//TODO: handle other line endings and return an error when
// encountering unpritable or width-breaking codepoints.
'\n' => {
self.col_num = 0;
self.row_num += 1;
},
else => {
if (self.col_num < self.buffer.width)
self.buffer.cellRef(self.row_num, self.col_num).* = .{
.char = cp,
.attribs = self.attribs,
};
self.col_num += 1;
},
}
bytes_written = cp_iter.i;
}
return bytes_written;
}
pub fn writer(self: *WriteCursor) Writer {
return .{ .context = self };
}
};
/// constructs a `WriteCursor` for the buffer at a given offset.
pub fn cursorAt(self: *Buffer, row_num: usize, col_num: usize) WriteCursor {
return .{
.row_num = row_num,
.col_num = col_num,
.buffer = self,
};
}
/// constructs a `WriteCursor` for the buffer at a given offset. data written
/// through a wrapped cursor wraps around to the next line when it reaches the right
/// edge of the row.
pub fn wrappedCursorAt(self: *Buffer, row_num: usize, col_num: usize) WriteCursor {
var cursor = self.cursorAt(row_num, col_num);
cursor.wrap = true;
return cursor;
}
pub fn clear(self: *Buffer) void {
mem.set(Cell, self.data, .{});
}
pub fn init(allocator: *Allocator, height: usize, width: usize) Allocator.Error!Buffer {
var self = Buffer{
.data = try allocator.alloc(Cell, width * height),
.width = width,
.height = height,
.allocator = allocator,
};
self.clear();
return self;
}
pub fn deinit(self: *Buffer) void {
self.allocator.free(self.data);
}
/// return a slice representing a row at a given context. Generic over the constness
/// of self; if the buffer is const, the slice elements are const.
pub fn row(self: anytype, row_num: usize) RowType: {
switch (@typeInfo(@TypeOf(self))) {
.Pointer => |p| {
if (p.child != Buffer) @compileError("expected Buffer");
if (p.is_const)
break :RowType []const Cell
else
break :RowType []Cell;
},
else => {
if (@TypeOf(self) != Buffer) @compileError("expected Buffer");
break :RowType []const Cell;
},
}
} {
assert(row_num < self.height);
const row_idx = row_num * self.width;
return self.data[row_idx .. row_idx + self.width];
}
/// return a reference to the cell at the given row and column number. generic over
/// the constness of self; if self is const, the cell pointed to is also const.
pub fn cellRef(self: anytype, row_num: usize, col_num: usize) RefType: {
switch (@typeInfo(@TypeOf(self))) {
.Pointer => |p| {
if (p.child != Buffer) @compileError("expected Buffer");
if (p.is_const)
break :RefType *const Cell
else
break :RefType *Cell;
},
else => {
if (@TypeOf(self) != Buffer) @compileError("expected Buffer");
break :RefType *const Cell;
},
}
} {
assert(col_num < self.width);
return &self.row(row_num)[col_num];
}
/// return a copy of the cell at a given offset
pub fn cell(self: Buffer, row_num: usize, col_num: usize) Cell {
assert(col_num < self.width);
return self.row(row_num)[col_num];
}
/// fill a buffer with the given cell
pub fn fill(self: *Buffer, a_cell: Cell) void {
mem.set(Cell, self.data, a_cell);
}
/// grows or shrinks a cell buffer ensuring alignment by line and column
/// data is lost in shrunk dimensions, and new space is initialized
/// as the default cell in grown dimensions.
pub fn resize(self: *Buffer, height: usize, width: usize) Allocator.Error!void {
if (self.height == height and self.width == width) return;
//TODO: figure out more ways to minimize unnecessary reallocation and
//redrawing here. for instance:
// `if self.width < width and self.height < self.height` no redraw or
// realloc required
// more difficult:
// `if self.width * self.height >= width * height` requires redraw
// but could possibly use some sort of scratch buffer thing.
const old = self.*;
self.* = .{
.allocator = old.allocator,
.width = width,
.height = height,
.data = try old.allocator.alloc(Cell, width * height),
};
if (width > old.width or
height > old.height) self.clear();
const min_height = math.min(old.height, height);
const min_width = math.min(old.width, width);
var n: usize = 0;
while (n < min_height) : (n += 1) {
mem.copy(Cell, self.row(n), old.row(n)[0..min_width]);
}
self.allocator.free(old.data);
}
// draw the contents of 'other' on top of the contents of self at the provided
// offset. anything out of bounds of the destination is ignored. row_num and col_num
// are still 1-indexed; this means 0 is out of bounds by 1, and -1 is out of bounds
// by 2. This may change.
pub fn blit(self: *Buffer, other: Buffer, row_num: isize, col_num: isize) void {
var self_row_idx = row_num;
var other_row_idx: usize = 0;
while (self_row_idx < self.height and other_row_idx < other.height) : ({
self_row_idx += 1;
other_row_idx += 1;
}) {
if (self_row_idx < 0) continue;
var self_col_idx = col_num;
var other_col_idx: usize = 0;
while (self_col_idx < self.width and other_col_idx < other.width) : ({
self_col_idx += 1;
other_col_idx += 1;
}) {
if (self_col_idx < 0) continue;
self.cellRef(
@intCast(usize, self_row_idx),
@intCast(usize, self_col_idx),
).* = other.cell(other_row_idx, other_col_idx);
}
}
}
// draw the contents of 'other' on top of the contents of self at the provided
// offset. anything out of bounds of the destination is ignored. row_num and col_num
// are still 1-indexed; this means 0 is out of bounds by 1, and -1 is out of bounds
// by 2. This may change.
pub fn blitFrom(self: *Buffer, other: Buffer, row_num: isize, col_num: isize, other_row_num: usize, other_col_num: usize) void {
var self_row_idx = row_num;
var other_row_idx: usize = other_row_num;
while (self_row_idx < self.height and other_row_idx < other.height) : ({
self_row_idx += 1;
other_row_idx += 1;
}) {
if (self_row_idx < 0) continue;
var self_col_idx = col_num;
var other_col_idx: usize = other_col_num;
while (self_col_idx < self.width and other_col_idx < other.width) : ({
self_col_idx += 1;
other_col_idx += 1;
}) {
if (self_col_idx < 0) continue;
self.cellRef(
@intCast(usize, self_row_idx),
@intCast(usize, self_col_idx),
).* = other.cell(other_row_idx, other_col_idx);
}
}
}
// std.fmt compatibility for debugging
pub fn format(
self: Buffer,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) @TypeOf(writer).Error!void {
var row_num: usize = 0;
try writer.print("\n\x1B[4m|", .{});
while (row_num < self.height) : (row_num += 1) {
for (self.row(row_num)) |this_cell| {
var utf8Seq: [4]u8 = undefined;
const len = std.unicode.utf8Encode(this_cell.char, &utf8Seq) catch unreachable;
try writer.print("{}|", .{utf8Seq[0..len]});
}
if (row_num != self.height - 1)
try writer.print("\n|", .{});
}
try writer.print("\x1B[0m\n", .{});
}
};
const Size = struct {
height: usize,
width: usize,
};
/// represents the last drawn state of the terminal
var front: Buffer = undefined;
// tests ///////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
test "Buffer.resize()" {
var buffer = try Buffer.init(std.testing.allocator, 10, 10);
defer buffer.deinit();
// newly initialized buffer should have all cells set to default value
for (buffer.data) |cell| {
std.testing.expectEqual(Cell{}, cell);
}
for (buffer.row(4)[0..3]) |*cell| {
cell.char = '.';
}
try buffer.resize(5, 12);
// make sure data is preserved between resizes
for (buffer.row(4)[0..3]) |cell| {
std.testing.expectEqual(@as(u21, '.'), cell.char);
}
// ensure nothing weird was written to expanded rows
for (buffer.row(2)[3..]) |cell| {
std.testing.expectEqual(Cell{}, cell);
}
}
// most useful tests of this are function tests
// see `examples/`
test "buffer.cellRef()" {
var buffer = try Buffer.init(std.testing.allocator, 1, 1);
defer buffer.deinit();
const ref = buffer.cellRef(0, 0);
ref.* = Cell{ .char = '.' };
std.testing.expectEqual(@as(u21, '.'), buffer.cell(0, 0).char);
}
test "buffer.cursorAt()" {
var buffer = try Buffer.init(std.testing.allocator, 10, 10);
defer buffer.deinit();
var cursor = buffer.cursorAt(9, 5);
const n = try cursor.writer().write("hello!!!!!\n!!!!");
std.debug.print("{}", .{buffer});
std.testing.expectEqual(@as(usize, 11), n);
}
test "Buffer.blit()" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
var alloc = &arena.allocator;
var buffer1 = try Buffer.init(alloc, 10, 10);
var buffer2 = try Buffer.init(alloc, 5, 5);
buffer2.fill(.{ .char = '#' });
std.debug.print("{}", .{buffer2});
std.debug.print("blit(-2,6)", .{});
buffer1.blit(buffer2, -2, 6);
std.debug.print("{}", .{buffer1});
}
test "wrappedWrite" {
var buffer = try Buffer.init(std.testing.allocator, 5, 5);
defer buffer.deinit();
var cursor = buffer.wrappedCursorAt(4, 0);
const n = try cursor.writer().write("hello!!!!!");
std.debug.print("{}", .{buffer});
std.testing.expectEqual(@as(usize, 5), n);
}
test "static anal" {
std.meta.refAllDecls(@This());
std.meta.refAllDecls(Cell);
std.meta.refAllDecls(Buffer);
std.meta.refAllDecls(Buffer.WriteCursor);
} | src/box.zig |
const std = @import("std");
const Trigger = @import("trigger.zig").Trigger;
const Impulse = @import("notes.zig").Impulse;
const Notes = @import("notes.zig").Notes;
const Span = @import("basics.zig").Span;
const span = Span.init(0, 1024);
const ExpectedResult = struct {
start: usize,
end: usize,
params: f32,
note_id_changed: bool,
};
fn testAll(
trigger: *Trigger(f32),
iap: Notes(f32).ImpulsesAndParamses,
expected: []const ExpectedResult,
) void {
var ctr = trigger.counter(span, iap);
for (expected) |e| {
const r = trigger.next(&ctr).?;
std.testing.expectEqual(e.start, r.span.start);
std.testing.expectEqual(e.end, r.span.end);
std.testing.expectEqual(e.params, r.params);
std.testing.expectEqual(e.note_id_changed, r.note_id_changed);
}
std.testing.expectEqual(
@as(?Trigger(f32).NewPaintReturnValue, null),
trigger.next(&ctr),
);
}
test "Trigger: no notes" {
var trigger = Trigger(f32).init();
testAll(&trigger, .{
.impulses = &[_]Impulse {},
.paramses = &[_]f32 {},
}, &[_]ExpectedResult {});
}
test "Trigger: first note at frame=0" {
var trigger = Trigger(f32).init();
testAll(&trigger, .{
.impulses = &[_]Impulse {
.{ .frame = 0, .note_id = 1, .event_id = 1 },
},
.paramses = &[_]f32 {
440.0,
},
}, &[_]ExpectedResult {
.{ .start = 0, .end = 1024, .params = 440.0, .note_id_changed = true },
});
}
test "Trigger: first note after frame=0" {
var trigger = Trigger(f32).init();
testAll(&trigger, .{
.impulses = &[_]Impulse {
.{ .frame = 500, .note_id = 1, .event_id = 1 },
},
.paramses = &[_]f32 {
440.0,
},
}, &[_]ExpectedResult {
.{ .start = 500, .end = 1024, .params = 440.0, .note_id_changed = true },
});
}
test "Trigger: carryover" {
var trigger = Trigger(f32).init();
testAll(&trigger, .{
.impulses = &[_]Impulse {
.{ .frame = 0, .note_id = 1, .event_id = 1 },
.{ .frame = 200, .note_id = 2, .event_id = 2 },
},
.paramses = &[_]f32 {
440.0,
220.0,
},
}, &[_]ExpectedResult {
.{ .start = 0, .end = 200, .params = 440.0, .note_id_changed = true },
.{ .start = 200, .end = 1024, .params = 220.0, .note_id_changed = true },
});
testAll(&trigger, .{
.impulses = &[_]Impulse {
.{ .frame = 500, .note_id = 3, .event_id = 1 },
.{ .frame = 600, .note_id = 3, .event_id = 2 }, // same
},
.paramses = &[_]f32 {
330.0,
660.0,
},
}, &[_]ExpectedResult {
.{ .start = 0, .end = 500, .params = 220.0, .note_id_changed = false },
.{ .start = 500, .end = 600, .params = 330.0, .note_id_changed = true },
.{ .start = 600, .end = 1024, .params = 660.0, .note_id_changed = false },
});
testAll(&trigger, .{
.impulses = &[_]Impulse {},
.paramses = &[_]f32 {},
}, &[_]ExpectedResult {
.{ .start = 0, .end = 1024, .params = 660.0, .note_id_changed = false },
});
}
test "Trigger: two notes starting at the same time" {
var trigger = Trigger(f32).init();
testAll(&trigger, .{
.impulses = &[_]Impulse {
.{ .frame = 200, .note_id = 1, .event_id = 1 },
.{ .frame = 200, .note_id = 2, .event_id = 2 },
},
.paramses = &[_]f32 {
440.0,
220.0,
},
}, &[_]ExpectedResult {
.{ .start = 200, .end = 1024, .params = 220.0, .note_id_changed = true },
});
} | src/zang/trigger_test.zig |
const std = @import("std");
const ELF = @import("../elf.zig");
const phdr = @import("../data-structures/phdr.zig");
const shdr = @import("../data-structures/shdr.zig");
const ehdr10 = @import("../data-structures/ehdr.zig");
const shdrErrors = error{
no_string_table,
E_Shoff_shnum_shentsize_is_zero,
};
fn shdr_get_name_init(
elf: ELF.ELF,
alloc: std.mem.Allocator,
) ![]const u8 {
if (!elf.is32) {
var shdr1: std.elf.Elf64_Shdr = undefined;
const buf = std.mem.asBytes(&shdr1);
_ = try elf.file.preadAll(buf, elf.ehdr.shoff + @sizeOf(std.elf.Elf64_Shdr) * elf.ehdr.shstrndx);
const buffer = try alloc.alloc(u8, shdr1.sh_size);
_ = try elf.file.preadAll(buffer, shdr1.sh_offset);
return buffer;
} else {
var shdr1: std.elf.Elf32_Shdr = undefined;
const buf = std.mem.asBytes(&shdr1);
_ = try elf.file.preadAll(buf, elf.ehdr.shoff + @sizeOf(std.elf.Elf32_Shdr) * elf.ehdr.shstrndx);
const buffer = try alloc.alloc(u8, shdr1.sh_size);
_ = try elf.file.preadAll(buffer, shdr1.sh_offset);
return buffer;
}
}
fn shdr_get_name(list: []const u8, offset: u64) []const u8 {
if (offset < list.len) {
const slice = list[offset..];
const len = std.mem.indexOf(u8, slice, "\x00") orelse 0;
return slice[0..len];
} else {
return "";
}
}
pub fn shdrParse64(
elf: ELF.ELF,
alloc: std.mem.Allocator,
) !std.ArrayList(shdr.Shdr) {
var list = std.ArrayList(shdr.Shdr).init(alloc);
const stream = elf.file.reader();
var section_strtab = try shdr_get_name_init(elf, alloc);
// defer alloc.free(section_strtab);
//try std.io.getStdOut().writer().print("{x}\n", .{std.fmt.fmtSliceHexLower(section_strtab[0..])});
var i: usize = 0;
var shdr1: std.elf.Elf64_Shdr = undefined;
while (i < elf.ehdr.shnum) : (i = i + 1) {
const offset = elf.ehdr.shoff + (@sizeOf(@TypeOf(shdr1)) * i);
try elf.file.seekableStream().seekTo(offset);
try stream.readNoEof(std.mem.asBytes(&shdr1));
var shdr2: shdr.Shdr = undefined;
shdr2.name = shdr_get_name(section_strtab, shdr1.sh_name);
shdr2.shtype = @intToEnum(shdr.sh_type, shdr1.sh_type);
shdr2.offset = shdr1.sh_offset;
shdr2.entsize = shdr1.sh_entsize;
shdr2.addralign = shdr1.sh_addralign;
shdr2.info = shdr1.sh_info;
shdr2.link = shdr1.sh_link;
shdr2.size = shdr1.sh_size;
shdr2.addr = shdr1.sh_addr;
shdr2.flags = @bitCast(shdr.sh_flags, @as(u64, shdr1.sh_flags));
//var data = try alloc.alloc(u8, shdr.sh_size); //[shdr.sh_size]u8 = undefined;
//try parse_source.seekableStream().seekTo(shdr.sh_offset);
//_ = try parse_source.reader().read(data[0..]);
try list.append(shdr2);
}
return list;
}
pub fn shdrParse32(
elf: ELF.ELF,
alloc: std.mem.Allocator,
) !std.ArrayList(shdr.Shdr) {
var list = std.ArrayList(shdr.Shdr).init(alloc);
const stream = elf.file.reader();
var section_strtab = try shdr_get_name_init(elf, alloc);
// defer alloc.free(section_strtab);
//try std.io.getStdOut().writer().print("{x}\n", .{std.fmt.fmtSliceHexLower(section_strtab[0..])});
var i: usize = 0;
var shdr1: std.elf.Elf32_Shdr = undefined;
while (i < elf.ehdr.shnum) : (i = i + 1) {
const offset = elf.ehdr.shoff + (@sizeOf(@TypeOf(shdr1)) * i);
try elf.file.seekableStream().seekTo(offset);
try stream.readNoEof(std.mem.asBytes(&shdr1));
var shdr2: shdr.Shdr = undefined;
shdr2.name = shdr_get_name(section_strtab, shdr1.sh_name);
shdr2.shtype = @intToEnum(shdr.sh_type, shdr1.sh_type);
shdr2.offset = shdr1.sh_offset;
shdr2.entsize = shdr1.sh_entsize;
shdr2.addralign = shdr1.sh_addralign;
shdr2.info = shdr1.sh_info;
shdr2.link = shdr1.sh_link;
shdr2.size = shdr1.sh_size;
shdr2.addr = shdr1.sh_addr;
shdr2.flags = @bitCast(shdr.sh_flags, @intCast(u64, shdr1.sh_flags));
//var data = try alloc.alloc(u8, shdr.sh_size); //[shdr.sh_size]u8 = undefined;
//try parse_source.seekableStream().seekTo(shdr.sh_offset);
//_ = try parse_source.reader().read(data[0..]);
try list.append(shdr2);
}
return list;
}
pub fn shdrParse(elf: ELF.ELF, alloc: std.mem.Allocator) !std.ArrayList(shdr.Shdr) {
if (elf.is32) {
return @call(.{ .modifier = .always_inline }, shdrParse32, .{ elf, alloc });
} else {
return @call(.{ .modifier = .always_inline }, shdrParse64, .{ elf, alloc });
}
}
// autoupdate string table at the end, use this last
fn updateStrtab(a: ELF.ELF, alloc: std.mem.Allocator) !?[]u8 {
if (a.ehdr.shstrndx == 0) {
return null;
}
var b = a.shdrs.items[a.ehdr.shstrndx];
// try parse_source.preadAll(buf, b.offset);
var c = std.ArrayList(u8).init(alloc);
try c.append('\x00');
for (a.shdrs.items) |s| {
try c.appendSlice(s.name);
try c.append('\x00');
}
try a.file.seekableStream().seekTo(b.offset);
try a.file.writer().writeAll(c.items);
return c.items;
}
// its not packed but i named it like this for some reason sorry
fn shdrToPacked32(a: ELF.ELF, alloc: std.mem.Allocator) ![]std.elf.Elf32_Shdr {
var ar = std.ArrayList(std.elf.Elf32_Shdr).init(alloc);
defer ar.deinit();
const section_names = try updateStrtab(a, alloc);
var b: std.elf.Elf32_Shdr = undefined;
for (a.shdrs.items) |s| {
b.sh_type = @enumToInt(s.shtype);
b.sh_info = @intCast(std.elf.Elf32_Word, s.info);
b.sh_link = @intCast(std.elf.Elf32_Word, s.link);
if (section_names != null) {
b.sh_name = @truncate(u32, std.mem.indexOf(u8, section_names.?, s.name) orelse 0);
}
b.sh_size = @intCast(std.elf.Elf32_Word, s.size);
b.sh_addr = @intCast(std.elf.Elf32_Addr, s.addr);
b.sh_flags = @truncate(std.elf.Elf32_Word, @bitCast(u64, s.flags));
b.sh_offset = @intCast(std.elf.Elf32_Off, s.offset);
b.sh_entsize = @intCast(std.elf.Elf32_Word, s.entsize);
b.sh_addralign = @intCast(std.elf.Elf32_Word, s.addralign);
try ar.append(b);
}
return alloc.dupe(std.elf.Elf32_Shdr, ar.items);
}
fn shdrToPacked64(a: ELF.ELF, alloc: std.mem.Allocator) ![]std.elf.Elf64_Shdr {
var ar = std.ArrayList(std.elf.Elf64_Shdr).init(alloc);
defer ar.deinit();
const section_names = try updateStrtab(a, alloc);
var b: std.elf.Elf64_Shdr = undefined;
for (a.shdrs.items) |s| {
b.sh_type = @enumToInt(s.shtype);
b.sh_info = @intCast(std.elf.Elf64_Word, s.info);
b.sh_link = @intCast(std.elf.Elf64_Word, s.link);
if (section_names != null) {
b.sh_name = @truncate(std.elf.Elf64_Word, std.mem.indexOf(u8, section_names.?, s.name) orelse 0);
}
b.sh_size = @intCast(std.elf.Elf64_Xword, s.size);
b.sh_addr = @intCast(std.elf.Elf64_Addr, s.addr);
b.sh_flags = @bitCast(std.elf.Elf64_Xword, s.flags);
b.sh_offset = @intCast(std.elf.Elf64_Off, s.offset);
b.sh_entsize = @intCast(std.elf.Elf64_Xword, s.entsize);
b.sh_addralign = @intCast(std.elf.Elf64_Xword, s.addralign);
try ar.append(b);
}
return alloc.dupe(std.elf.Elf64_Shdr, ar.items);
}
pub fn writeShdrList(
a: ELF.ELF,
alloc: std.mem.Allocator,
) !void {
if (a.ehdr.shoff == 0 or a.ehdr.shnum == 0 or a.ehdr.shentsize == 0) {
return shdrErrors.E_Shoff_shnum_shentsize_is_zero;
}
var sec_names = try updateStrtab(a, alloc);
if (sec_names != null) {
var writeoffset = a.shdrs.items[a.ehdr.shstrndx].offset;
try a.file.pwriteAll(sec_names.?, writeoffset);
std.mem.copy(u8, a.data[writeoffset..], sec_names.?);
}
if (a.is32) {
var shdr2 = try shdrToPacked32(a, alloc);
try a.file.pwriteAll(std.mem.sliceAsBytes(shdr2), a.ehdr.shoff);
} else {
var shdr2 = try shdrToPacked64(a, alloc);
try a.file.pwriteAll(std.mem.sliceAsBytes(shdr2), a.ehdr.shoff);
}
} | src/functions/shdr.zig |
const std = @import("std");
const assert = std.debug.assert;
pub const Accum = struct {
count: usize,
values: std.AutoHashMap(usize, isize),
pub fn init() Accum {
const allocator = std.heap.direct_allocator;
return Accum{
.count = 0,
.values = std.AutoHashMap(usize, isize).init(allocator),
};
}
pub fn deinit(self: *Accum) void {
self.values.deinit();
}
pub fn reset(self: *Accum) void {
self.count = 0;
self.values.clear();
}
pub fn append(self: *Accum, value: isize) void {
_ = self.values.put(self.count, value) catch unreachable;
self.count += 1;
}
pub fn compute_sum(self: *Accum) isize {
var total: isize = 0;
var j: usize = 0;
while (j < self.count) : (j += 1) {
const value = self.values.get(j).?.value;
total += value;
}
return total;
}
pub fn find_first_repetition(self: *Accum) isize {
const allocator = std.heap.direct_allocator;
var seen = std.AutoHashMap(isize, void).init(allocator);
defer seen.deinit();
var total: isize = 0;
main: while (true) {
var j: usize = 0;
while (j < self.count) : (j += 1) {
if (seen.contains(total)) {
break :main;
}
_ = seen.put(total, {}) catch unreachable;
const value = self.values.get(j).?.value;
total += value;
}
}
return total;
}
pub fn parse(self: *Accum, str: []const u8) void {
const value = std.fmt.parseInt(isize, std.mem.trim(u8, str, " \t"), 10) catch 0;
self.append(value);
}
};
test "compute sum" {
const Data = struct {
values: []const u8,
expected: isize,
};
const data = [_]Data{
Data{ .values = "+1, -2, +3, +1", .expected = 3 },
Data{ .values = "+1, +1, +1", .expected = 3 },
Data{ .values = "+1, +1, -2", .expected = 0 },
Data{ .values = "-1, -2, -3", .expected = -6 },
};
var accum = Accum.init();
defer accum.deinit();
for (data) |d| {
accum.reset();
var it = std.mem.separate(d.values, ",");
while (it.next()) |item| {
accum.parse(item);
}
assert(accum.compute_sum() == d.expected);
}
}
test "find first repetition" {
const Data = struct {
values: []const u8,
expected: isize,
};
const data = [_]Data{
Data{ .values = "+1, -2, +3, +1", .expected = 2 },
Data{ .values = "+1, -1", .expected = 0 },
Data{ .values = "+3, +3, +4, -2, -4", .expected = 10 },
Data{ .values = "-6, +3, +8, +5, -6", .expected = 5 },
Data{ .values = "+7, +7, -2, -7, -4", .expected = 14 },
};
var accum = Accum.init();
defer accum.deinit();
for (data) |d| {
accum.reset();
var it = std.mem.separate(d.values, ",");
while (it.next()) |item| {
accum.parse(item);
}
// std.debug.warn("[{}]\n", d.values);
assert(accum.find_first_repetition() == d.expected);
}
} | 2018/p01/accum.zig |
const std = @import("std");
const epoch = std.time.epoch;
const testing = std.testing;
const DateError = error{
InvalidDate,
};
const Date = struct {
year: u16,
month: u8,
day: u8,
};
const MeacalDate = struct {
year: u8,
month: u8,
day: u8,
};
pub fn convertDateStringToDate(date_string: []const u8) !Date {
var it = std.mem.tokenize(u8, date_string, "-");
const year = try std.fmt.parseInt(u16, it.next().?, 10);
const month = try std.fmt.parseInt(u8, it.next().?, 10);
const day = try std.fmt.parseInt(u8, it.next().?, 10);
if (month < 1 or month > 12) {
return DateError.InvalidDate;
}
const leap_kind: epoch.YearLeapKind = if (epoch.isLeapYear(year)) .leap else .not_leap;
const days_in_month = epoch.getDaysInMonth(
leap_kind,
try std.meta.intToEnum(epoch.Month, month),
);
if (day < 1 or day > days_in_month) {
return DateError.InvalidDate;
}
return Date{
.year = year,
.month = month,
.day = day,
};
}
pub fn convertDateStringToMeacal(date_string: []const u8, base_year: u16) !MeacalDate {
const target_date = try convertDateStringToDate(date_string);
var month: usize = 1;
var days: usize = 0;
while (month < target_date.month) : (month += 1) {
days += epoch.getDaysInMonth(
epoch.YearLeapKind.not_leap,
try std.meta.intToEnum(epoch.Month, month),
);
}
days += target_date.day - 1;
var p1: u8 = @intCast(u8, target_date.year - base_year);
var p2: u8 = @intCast(u8, 65 + @divFloor(days, 14));
// End of year fix.
if (p2 == '[') {
p2 = '+';
}
var p3 = @intCast(u8, @mod(days, 14));
// Leap day fix.
if (target_date.month == 2 and target_date.day == 29) {
p2 = '+';
p3 = 1;
}
return MeacalDate{
.year = p1,
.month = p2,
.day = p3,
};
}
test "Not leap year" {
var md = try convertDateStringToMeacal("1968-07-10", 1968);
try testing.expect(std.meta.eql(md, MeacalDate{ .year = 0, .month = 'N', .day = 8 }));
md = try convertDateStringToMeacal("2021-01-01", 2021);
try testing.expect(std.meta.eql(md, MeacalDate{ .year = 0, .month = 'A', .day = 0 }));
md = try convertDateStringToMeacal("2021-07-10", 2021);
try testing.expect(std.meta.eql(md, MeacalDate{ .year = 0, .month = 'N', .day = 8 }));
md = try convertDateStringToMeacal("2020-02-28", 2020);
try testing.expect(std.meta.eql(md, MeacalDate{ .year = 0, .month = 'E', .day = 2 }));
md = try convertDateStringToMeacal("2020-02-29", 2020);
try testing.expect(std.meta.eql(md, MeacalDate{ .year = 0, .month = '+', .day = 1 }));
if (convertDateStringToMeacal("2021-02-29", 2021)) {} else |err| {
try testing.expect(err == DateError.InvalidDate);
}
} | zig/src/date.zig |
//--------------------------------------------------------------------------------
// Section: Types (10)
//--------------------------------------------------------------------------------
// TODO: this type is limited to platform 'windows10.0.10240'
const IID_IRandomAccessStreamFileAccessMode_Value = @import("../../zig.zig").Guid.initString("332e5848-2e15-458e-85c4-c911c0c3d6f4");
pub const IID_IRandomAccessStreamFileAccessMode = &IID_IRandomAccessStreamFileAccessMode_Value;
pub const IRandomAccessStreamFileAccessMode = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetMode: fn(
self: *const IRandomAccessStreamFileAccessMode,
fileAccessMode: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRandomAccessStreamFileAccessMode_GetMode(self: *const T, fileAccessMode: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRandomAccessStreamFileAccessMode.VTable, self.vtable).GetMode(@ptrCast(*const IRandomAccessStreamFileAccessMode, self), fileAccessMode);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.10240'
const IID_IUnbufferedFileHandleOplockCallback_Value = @import("../../zig.zig").Guid.initString("d1019a0e-6243-4329-8497-2e75894d7710");
pub const IID_IUnbufferedFileHandleOplockCallback = &IID_IUnbufferedFileHandleOplockCallback_Value;
pub const IUnbufferedFileHandleOplockCallback = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
OnBrokenCallback: fn(
self: *const IUnbufferedFileHandleOplockCallback,
) 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 IUnbufferedFileHandleOplockCallback_OnBrokenCallback(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUnbufferedFileHandleOplockCallback.VTable, self.vtable).OnBrokenCallback(@ptrCast(*const IUnbufferedFileHandleOplockCallback, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.10240'
const IID_IUnbufferedFileHandleProvider_Value = @import("../../zig.zig").Guid.initString("a65c9109-42ab-4b94-a7b1-dd2e4e68515e");
pub const IID_IUnbufferedFileHandleProvider = &IID_IUnbufferedFileHandleProvider_Value;
pub const IUnbufferedFileHandleProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
OpenUnbufferedFileHandle: fn(
self: *const IUnbufferedFileHandleProvider,
oplockBreakCallback: ?*IUnbufferedFileHandleOplockCallback,
fileHandle: ?*usize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CloseUnbufferedFileHandle: fn(
self: *const IUnbufferedFileHandleProvider,
) 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 IUnbufferedFileHandleProvider_OpenUnbufferedFileHandle(self: *const T, oplockBreakCallback: ?*IUnbufferedFileHandleOplockCallback, fileHandle: ?*usize) callconv(.Inline) HRESULT {
return @ptrCast(*const IUnbufferedFileHandleProvider.VTable, self.vtable).OpenUnbufferedFileHandle(@ptrCast(*const IUnbufferedFileHandleProvider, self), oplockBreakCallback, fileHandle);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUnbufferedFileHandleProvider_CloseUnbufferedFileHandle(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUnbufferedFileHandleProvider.VTable, self.vtable).CloseUnbufferedFileHandle(@ptrCast(*const IUnbufferedFileHandleProvider, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const HANDLE_OPTIONS = enum(u32) {
NONE = 0,
OPEN_REQUIRING_OPLOCK = 262144,
DELETE_ON_CLOSE = 67108864,
SEQUENTIAL_SCAN = 134217728,
RANDOM_ACCESS = 268435456,
NO_BUFFERING = 536870912,
OVERLAPPED = 1073741824,
WRITE_THROUGH = 2147483648,
_,
pub fn initFlags(o: struct {
NONE: u1 = 0,
OPEN_REQUIRING_OPLOCK: u1 = 0,
DELETE_ON_CLOSE: u1 = 0,
SEQUENTIAL_SCAN: u1 = 0,
RANDOM_ACCESS: u1 = 0,
NO_BUFFERING: u1 = 0,
OVERLAPPED: u1 = 0,
WRITE_THROUGH: u1 = 0,
}) HANDLE_OPTIONS {
return @intToEnum(HANDLE_OPTIONS,
(if (o.NONE == 1) @enumToInt(HANDLE_OPTIONS.NONE) else 0)
| (if (o.OPEN_REQUIRING_OPLOCK == 1) @enumToInt(HANDLE_OPTIONS.OPEN_REQUIRING_OPLOCK) else 0)
| (if (o.DELETE_ON_CLOSE == 1) @enumToInt(HANDLE_OPTIONS.DELETE_ON_CLOSE) else 0)
| (if (o.SEQUENTIAL_SCAN == 1) @enumToInt(HANDLE_OPTIONS.SEQUENTIAL_SCAN) else 0)
| (if (o.RANDOM_ACCESS == 1) @enumToInt(HANDLE_OPTIONS.RANDOM_ACCESS) else 0)
| (if (o.NO_BUFFERING == 1) @enumToInt(HANDLE_OPTIONS.NO_BUFFERING) else 0)
| (if (o.OVERLAPPED == 1) @enumToInt(HANDLE_OPTIONS.OVERLAPPED) else 0)
| (if (o.WRITE_THROUGH == 1) @enumToInt(HANDLE_OPTIONS.WRITE_THROUGH) else 0)
);
}
};
pub const HO_NONE = HANDLE_OPTIONS.NONE;
pub const HO_OPEN_REQUIRING_OPLOCK = HANDLE_OPTIONS.OPEN_REQUIRING_OPLOCK;
pub const HO_DELETE_ON_CLOSE = HANDLE_OPTIONS.DELETE_ON_CLOSE;
pub const HO_SEQUENTIAL_SCAN = HANDLE_OPTIONS.SEQUENTIAL_SCAN;
pub const HO_RANDOM_ACCESS = HANDLE_OPTIONS.RANDOM_ACCESS;
pub const HO_NO_BUFFERING = HANDLE_OPTIONS.NO_BUFFERING;
pub const HO_OVERLAPPED = HANDLE_OPTIONS.OVERLAPPED;
pub const HO_WRITE_THROUGH = HANDLE_OPTIONS.WRITE_THROUGH;
pub const HANDLE_ACCESS_OPTIONS = enum(u32) {
NONE = 0,
READ_ATTRIBUTES = 128,
READ = 1179785,
WRITE = 1179926,
DELETE = 65536,
_,
pub fn initFlags(o: struct {
NONE: u1 = 0,
READ_ATTRIBUTES: u1 = 0,
READ: u1 = 0,
WRITE: u1 = 0,
DELETE: u1 = 0,
}) HANDLE_ACCESS_OPTIONS {
return @intToEnum(HANDLE_ACCESS_OPTIONS,
(if (o.NONE == 1) @enumToInt(HANDLE_ACCESS_OPTIONS.NONE) else 0)
| (if (o.READ_ATTRIBUTES == 1) @enumToInt(HANDLE_ACCESS_OPTIONS.READ_ATTRIBUTES) else 0)
| (if (o.READ == 1) @enumToInt(HANDLE_ACCESS_OPTIONS.READ) else 0)
| (if (o.WRITE == 1) @enumToInt(HANDLE_ACCESS_OPTIONS.WRITE) else 0)
| (if (o.DELETE == 1) @enumToInt(HANDLE_ACCESS_OPTIONS.DELETE) else 0)
);
}
};
pub const HAO_NONE = HANDLE_ACCESS_OPTIONS.NONE;
pub const HAO_READ_ATTRIBUTES = HANDLE_ACCESS_OPTIONS.READ_ATTRIBUTES;
pub const HAO_READ = HANDLE_ACCESS_OPTIONS.READ;
pub const HAO_WRITE = HANDLE_ACCESS_OPTIONS.WRITE;
pub const HAO_DELETE = HANDLE_ACCESS_OPTIONS.DELETE;
pub const HANDLE_SHARING_OPTIONS = enum(u32) {
NONE = 0,
READ = 1,
WRITE = 2,
DELETE = 4,
_,
pub fn initFlags(o: struct {
NONE: u1 = 0,
READ: u1 = 0,
WRITE: u1 = 0,
DELETE: u1 = 0,
}) HANDLE_SHARING_OPTIONS {
return @intToEnum(HANDLE_SHARING_OPTIONS,
(if (o.NONE == 1) @enumToInt(HANDLE_SHARING_OPTIONS.NONE) else 0)
| (if (o.READ == 1) @enumToInt(HANDLE_SHARING_OPTIONS.READ) else 0)
| (if (o.WRITE == 1) @enumToInt(HANDLE_SHARING_OPTIONS.WRITE) else 0)
| (if (o.DELETE == 1) @enumToInt(HANDLE_SHARING_OPTIONS.DELETE) else 0)
);
}
};
pub const HSO_SHARE_NONE = HANDLE_SHARING_OPTIONS.NONE;
pub const HSO_SHARE_READ = HANDLE_SHARING_OPTIONS.READ;
pub const HSO_SHARE_WRITE = HANDLE_SHARING_OPTIONS.WRITE;
pub const HSO_SHARE_DELETE = HANDLE_SHARING_OPTIONS.DELETE;
pub const HANDLE_CREATION_OPTIONS = enum(i32) {
CREATE_NEW = 1,
CREATE_ALWAYS = 2,
OPEN_EXISTING = 3,
OPEN_ALWAYS = 4,
TRUNCATE_EXISTING = 5,
};
pub const HCO_CREATE_NEW = HANDLE_CREATION_OPTIONS.CREATE_NEW;
pub const HCO_CREATE_ALWAYS = HANDLE_CREATION_OPTIONS.CREATE_ALWAYS;
pub const HCO_OPEN_EXISTING = HANDLE_CREATION_OPTIONS.OPEN_EXISTING;
pub const HCO_OPEN_ALWAYS = HANDLE_CREATION_OPTIONS.OPEN_ALWAYS;
pub const HCO_TRUNCATE_EXISTING = HANDLE_CREATION_OPTIONS.TRUNCATE_EXISTING;
// TODO: this type is limited to platform 'windows10.0.10240'
const IID_IOplockBreakingHandler_Value = @import("../../zig.zig").Guid.initString("826abe3d-3acd-47d3-84f2-88aaedcf6304");
pub const IID_IOplockBreakingHandler = &IID_IOplockBreakingHandler_Value;
pub const IOplockBreakingHandler = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
OplockBreaking: fn(
self: *const IOplockBreakingHandler,
) 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 IOplockBreakingHandler_OplockBreaking(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IOplockBreakingHandler.VTable, self.vtable).OplockBreaking(@ptrCast(*const IOplockBreakingHandler, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.10240'
const IID_IStorageItemHandleAccess_Value = @import("../../zig.zig").Guid.initString("5ca296b2-2c25-4d22-b785-b885c8201e6a");
pub const IID_IStorageItemHandleAccess = &IID_IStorageItemHandleAccess_Value;
pub const IStorageItemHandleAccess = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Create: fn(
self: *const IStorageItemHandleAccess,
accessOptions: HANDLE_ACCESS_OPTIONS,
sharingOptions: HANDLE_SHARING_OPTIONS,
options: HANDLE_OPTIONS,
oplockBreakingHandler: ?*IOplockBreakingHandler,
interopHandle: ?*?HANDLE,
) 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 IStorageItemHandleAccess_Create(self: *const T, accessOptions: HANDLE_ACCESS_OPTIONS, sharingOptions: HANDLE_SHARING_OPTIONS, options: HANDLE_OPTIONS, oplockBreakingHandler: ?*IOplockBreakingHandler, interopHandle: ?*?HANDLE) callconv(.Inline) HRESULT {
return @ptrCast(*const IStorageItemHandleAccess.VTable, self.vtable).Create(@ptrCast(*const IStorageItemHandleAccess, self), accessOptions, sharingOptions, options, oplockBreakingHandler, interopHandle);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.10240'
const IID_IStorageFolderHandleAccess_Value = @import("../../zig.zig").Guid.initString("df19938f-5462-48a0-be65-d2a3271a08d6");
pub const IID_IStorageFolderHandleAccess = &IID_IStorageFolderHandleAccess_Value;
pub const IStorageFolderHandleAccess = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Create: fn(
self: *const IStorageFolderHandleAccess,
fileName: ?[*:0]const u16,
creationOptions: HANDLE_CREATION_OPTIONS,
accessOptions: HANDLE_ACCESS_OPTIONS,
sharingOptions: HANDLE_SHARING_OPTIONS,
options: HANDLE_OPTIONS,
oplockBreakingHandler: ?*IOplockBreakingHandler,
interopHandle: ?*?HANDLE,
) 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 IStorageFolderHandleAccess_Create(self: *const T, fileName: ?[*:0]const u16, creationOptions: HANDLE_CREATION_OPTIONS, accessOptions: HANDLE_ACCESS_OPTIONS, sharingOptions: HANDLE_SHARING_OPTIONS, options: HANDLE_OPTIONS, oplockBreakingHandler: ?*IOplockBreakingHandler, interopHandle: ?*?HANDLE) callconv(.Inline) HRESULT {
return @ptrCast(*const IStorageFolderHandleAccess.VTable, self.vtable).Create(@ptrCast(*const IStorageFolderHandleAccess, self), fileName, creationOptions, accessOptions, sharingOptions, options, oplockBreakingHandler, interopHandle);
}
};}
pub usingnamespace MethodMixin(@This());
};
//--------------------------------------------------------------------------------
// Section: Functions (0)
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (0)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../../zig.zig").unicode_mode) {
.ansi => struct {
},
.wide => struct {
},
.unspecified => if (@import("builtin").is_test) struct {
} else struct {
},
};
//--------------------------------------------------------------------------------
// Section: Imports (4)
//--------------------------------------------------------------------------------
const HANDLE = @import("../../foundation.zig").HANDLE;
const HRESULT = @import("../../foundation.zig").HRESULT;
const IUnknown = @import("../../system/com.zig").IUnknown;
const PWSTR = @import("../../foundation.zig").PWSTR;
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/win_rt/storage.zig |
const std = @import("std");
const mecha = @import("mecha/mecha.zig");
const reflect = @import("reflect.zig");
const fmt = std.fmt;
const fs = std.fs;
const heap = std.heap;
const io = std.io;
const math = std.math;
const mem = std.mem;
const net = std.net;
const os = std.os;
const testing = std.testing;
usingnamespace @import("auto/xproto.zig");
pub const bigreq = @import("auto/bigreq.zig");
pub const composite = @import("auto/composite.zig");
pub const damage = @import("auto/damage.zig");
pub const dpms = @import("auto/dpms.zig");
pub const dri2 = @import("auto/dri2.zig");
pub const dri3 = @import("auto/dri3.zig");
pub const ge = @import("auto/ge.zig");
pub const glx = @import("auto/glx.zig");
pub const present = @import("auto/present.zig");
pub const randr = @import("auto/randr.zig");
pub const record = @import("auto/record.zig");
pub const render = @import("auto/render.zig");
pub const res = @import("auto/res.zig");
pub const screensaver = @import("auto/screensaver.zig");
pub const shape = @import("auto/shape.zig");
pub const shm = @import("auto/shm.zig");
pub const sync = @import("auto/sync.zig");
pub const xc_misc = @import("auto/xc_misc.zig");
pub const xevie = @import("auto/xevie.zig");
pub const xf86dri = @import("auto/xf86dri.zig");
pub const xf86vidmode = @import("auto/xf86vidmode.zig");
pub const xfixes = @import("auto/xfixes.zig");
pub const xinerama = @import("auto/xinerama.zig");
pub const input = @import("auto/xinput.zig");
pub const xkb = @import("auto/xkb.zig");
pub const xprint = @import("auto/xprint.zig");
pub const selinux = @import("auto/xselinux.zig");
pub const xtest = @import("auto/xtest.zig");
pub const xv = @import("auto/xv.zig");
pub const xvmc = @import("auto/xvmc.zig");
pub const Extension = struct {
name: []const u8,
global_id: u32,
};
const Connection = struct {
allocator: *mem.Allocator,
handle: fs.File,
setup: Setup,
pub fn close(conn: Connection) void {
conn.handle.close();
reflect.free(conn.setup, conn.allocator);
}
};
pub fn connect(allocator: *mem.Allocator) !Connection {
const display_str = os.getenv("DISPLAY") orelse return error.DisplayNotFound;
const display = try Display.parse(display_str);
const handle = try display.connect();
errdefer handle.close();
var hostname_buf: [os.HOST_NAME_MAX]u8 = undefined;
const hostname = try os.gethostname(&hostname_buf);
const xautority = try openXAuthority();
defer xautority.close();
var auth_buf: [Auth.max_size]u8 = undefined;
var fba = heap.FixedBufferAllocator.init(&auth_buf);
const auth = while (Auth.read(xautority.reader(), &fba.allocator) catch |err| switch (err) {
error.EndOfStream => null,
else => |e| return e,
}) |auth| : (fba.reset()) {
if (mem.eql(u8, auth.address, hostname))
break auth;
} else return error.AuthNotFound;
return setup(allocator, handle, auth);
}
fn setup(allocator: *mem.Allocator, handle: fs.File, auth: Auth) !Connection {
try reflect.encode(handle.writer(), SetupRequest{
.byte_order = if (@import("std").builtin.endian == .Big) 0x42 else 0x6c,
.pad0 = 0,
.protocol_major_version = 11,
.protocol_minor_version = 0,
.pad1 = [2]u8{ 0, 0 },
.authorization_protocol_name_len = @intCast(u16, auth.name.len),
.authorization_protocol_data_len = @intCast(u16, auth.data.len),
.authorization_protocol_name = auth.name,
.authorization_protocol_data = auth.data,
});
const result = try reflect.decode(handle.reader(), allocator, Setup);
errdefer reflect.free(result, allocator);
switch (result.status) {
0 => return error.SetupFailed,
2 => unreachable, // TODO: authenticate
1 => {},
else => return error.InvalidStatus,
}
return Connection{
.allocator = allocator,
.handle = handle,
.setup = result,
};
}
pub const Display = struct {
protocol: []const u8,
host: []const u8,
display: u16,
screen: u16,
pub fn parse(str: []const u8) !Display {
const result = parseDisplay(str) orelse return error.InvalidDisplay;
return Display{
.protocol = result.value[0] orelse "",
.host = result.value[1],
.display = result.value[2],
.screen = result.value[3] orelse 0,
};
}
pub fn connect(display: Display) !fs.File {
if (display.host.len != 0) {
const port = 6000 + display.display;
const address = try net.Address.parseIp(display.host, port);
return net.tcpConnectToAddress(address);
} else {
var buf: [fs.MAX_PATH_BYTES]u8 = undefined;
const path = fmt.bufPrint(&buf, "/tmp/.X11-unix/X{}", .{display.display}) catch unreachable;
return try net.connectUnixSocket(path);
}
}
usingnamespace mecha;
const parseDisplay = combine(.{
opt(protocol),
host,
displayId,
opt(combine(.{ ascii.char('.'), screenId })),
eos,
});
const protocol = combine(.{
many(ascii.not(ascii.char('/'))),
ascii.char('/'),
});
const host = combine(.{
many(ascii.not(ascii.char(':'))),
ascii.char(':'),
});
const displayId = int(u16, 10);
const screenId = int(u16, 10);
};
pub const Auth = struct {
family: u16,
address: []u8,
number: []u8,
name: []u8,
data: []u8,
/// Maximum size an Auth can ever occupy when encoded. This is
/// useful for when you wonna avoid the heap by allocating all
/// the data with a heap.FixedBufferAllocator.
pub const max_size = math.maxInt(u16) * 4 + @sizeOf(u16);
pub fn read(stream: anytype, allocator: *mem.Allocator) !Auth {
const Read = struct {
fn string(s: anytype, a: *mem.Allocator) ![]u8 {
const len = try s.readIntBig(u16);
const result = try a.alloc(u8, len);
errdefer a.free(result);
try s.readNoEof(result);
return result;
}
};
const family = try stream.readIntBig(u16);
const address = try Read.string(stream, allocator);
errdefer allocator.free(address);
const number = try Read.string(stream, allocator);
errdefer allocator.free(number);
const name = try Read.string(stream, allocator);
errdefer allocator.free(name);
const data = try Read.string(stream, allocator);
errdefer allocator.free(data);
return Auth{
.family = family,
.address = address,
.number = number,
.name = name,
.data = data,
};
}
pub fn deinit(auth: Auth, allocator: *Allocator) void {
allocator.free(auth.address);
allocator.free(auth.number);
allocator.free(auth.name);
allocator.free(auth.data);
}
};
pub fn openXAuthority() !fs.File {
if (os.getenv("XAUTHORITY")) |path|
return fs.openFileAbsolute(path, .{});
const home = os.getenv("HOME") orelse return error.HomeDirectoryNotFound;
var home_dir = try fs.cwd().openDir(home, .{});
defer home_dir.close();
return home_dir.openFile(".Xauthority", .{});
}
test "" {
@import("std").testing.refAllDecls(@This());
}
test "connect" {
const conn = try connect(testing.allocator);
defer conn.close();
for (conn.setup.@"roots") |root|
std.debug.warn("{}\n", .{root});
} | src/xcb.zig |
const std = @import("std");
const flags = @import("flags");
const path = std.fs.path;
const fmt = @import("../fmt.zig");
const exports = @import("pkg/exports");
const Export = exports.Export;
const Pkg = Export.Pkg;
const File = std.fs.File;
const Command = flags.Command;
const Flag = flags.Flag;
const Context = flags.Context;
pub const command = Command{
.name = "exports",
.flags = null,
.action = exprtsCmd,
.sub_commands = null,
};
fn exprtsCmd(ctx: *const Context) anyerror!void {
if (ctx.firstArg()) |arg| {
const root = try path.resolve(ctx.allocator, [_][]const u8{arg});
return generate(ctx, root);
}
return generate(ctx, try std.process.getCwdAlloc(ctx.allocator));
}
const build_file = "build.zig";
const src_dir = "src";
const exports_file = "EXPORTS.zig";
fn generate(ctx: *const Context, root: []const u8) anyerror!void {
const stdout = ctx.stdout.?;
const full_build_file = try path.join(
ctx.allocator,
[_][]const u8{ root, build_file },
);
if (!exports.fileExists(full_build_file)) {
try stdout.print("=> can't fing build file at {}\n", full_build_file);
return;
}
try stdout.print("=> found build file at {}\n", full_build_file);
const full_src_dir = try path.join(
ctx.allocator,
[_][]const u8{ root, src_dir },
);
if (!exports.fileExists(full_src_dir)) {
try stdout.print("=> can't fing sources directory at {}\n", full_src_dir);
return;
}
try stdout.print("=> found sources directory at {}\n", full_src_dir);
var e = &exports.Export.init(ctx.allocator, root);
try e.dir(full_src_dir);
const full_exports_file = try path.join(
ctx.allocator,
[_][]const u8{ root, exports_file },
);
var buf = &try std.Buffer.init(ctx.allocator, "");
defer buf.deinit();
var file = try File.openWrite(full_exports_file);
defer file.close();
try render(e, &std.io.BufferOutStream.init(buf).stream);
try fmt.format(
ctx.allocator,
buf.toSlice(),
&file.outStream().stream,
);
try stdout.print("OK generated {}\n", full_exports_file);
}
const header =
\\ // DO NOT EDIT!
\\ // autogenerated by hoodie pkg exports
\\const LibExeObjStep = @import("std").build.LibExeObjStep;
\\pub const Pkg = struct {
\\ name: []const u8,
\\ path: []const u8,
\\};
;
const footer =
\\pub fn setupPakcages(steps: []*LibExeObjStep) void {
\\ for (steps) |step| {
\\ for (packages) |pkg| {
\\ step.addPackagePath(pkg.name, pkg.path);
\\ }
\\ }
\\}
;
fn render(e: *Export, out: var) anyerror!void {
std.sort.sort(*Pkg, e.list.toSlice(), sortPkg);
try out.print("{}\n", header);
try out.print("{}",
\\ pub const packages=[_]Pkg{
);
try e.dumpStream(out);
try out.print("{}",
\\ };
);
try out.print("{}\n", footer);
}
fn sortPkg(lhs: *Pkg, rhs: *Pkg) bool {
return std.mem.compare(u8, lhs.name, rhs.name) == .LessThan;
} | src/cmd/pkg/exports.zig |
const std = @import("std");
const gl = @import("zgl");
const glfw = @import("zglfw");
const renz = @import("renz");
pub fn main() !void {
try glfw.init();
defer glfw.terminate();
glfw.windowHint(.ClientAPI, @enumToInt(glfw.APIAttribute.OpenGLAPI));
glfw.windowHint(.ContextVersionMajor, 4);
glfw.windowHint(.ContextVersionMinor, 5);
glfw.windowHint(.OpenGLProfile, @enumToInt(glfw.GLProfileAttribute.OpenglCoreProfile));
glfw.windowHint(.OpenGLForwardCompat, 1);
glfw.windowHint(.OpenGLDebugContext, 1);
var win = try glfw.createWindow(800, 600, "Hello Triangle!", null, null);
defer glfw.destroyWindow(win);
glfw.makeContextCurrent(win);
gl.debugMessageCallback({}, debugCallback);
glfw.makeContextCurrent(null);
_ = glfw.setFramebufferSizeCallback(win, framebufferSizeCallback);
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = &gpa.allocator;
const file = try renz.File.initGltf(allocator, @embedFile("assets/tri.gltf"), null);
var ren = renz.Renderer(?*glfw.Window, glfw.makeContextCurrent).init(allocator, win, file) catch |err| {
file.deinit();
return err;
};
defer ren.deinit();
while (!glfw.windowShouldClose(win)) {
ren.draw();
glfw.swapBuffers(win);
glfw.pollEvents();
}
}
fn framebufferSizeCallback(win: *glfw.Window, width: c_int, height: c_int) callconv(.C) void {
glfw.makeContextCurrent(win);
gl.viewport(0, 0, @intCast(usize, width), @intCast(usize, height));
}
fn debugCallback(source: gl.DebugSource, type_: gl.DebugMessageType, id: usize, severity: gl.DebugSeverity, message: []const u8) void {
const log = std.log.scoped(.gl);
const fmt = "[{s}] {s}: {s}";
const args = .{
@tagName(source),
@tagName(type_),
message,
};
switch (severity) {
.high => log.crit(fmt, args),
.medium => log.warn(fmt, args),
.low => log.notice(fmt, args),
.notification => log.debug(fmt, args),
}
} | example/hello.zig |
const std = @import("std");
const root = @import("main.zig");
const tls = root.tls;
const Self = @This();
tls_configuration: root.TlsConfiguration,
tls_context: *tls.tls,
tcp_stream: std.net.Stream,
address: ?std.net.Address = null,
const WrapError = error{ OutOfMemory, BadTlsConfiguration, TlsConnectSocket, TlsAcceptSocket };
pub fn wrapClientStream(tls_configuration: root.TlsConfiguration, tcp_stream: std.net.Stream, server_name: []const u8) WrapError!Self {
var maybe_tls_context = tls.tls_client();
if (maybe_tls_context == null) return error.OutOfMemory;
var tls_context = maybe_tls_context.?;
if (tls.tls_configure(tls_context, tls_configuration.config) == -1)
return error.BadTlsConfiguration;
if (tls.tls_connect_socket(tls_context, tcp_stream.handle, server_name.ptr) == -1)
return error.TlsConnectSocket;
return Self{
.tls_configuration = tls_configuration,
.tls_context = tls_context,
.tcp_stream = tcp_stream,
};
}
pub fn wrapServerStream(tls_configuration: root.TlsConfiguration, tls_context: *tls.tls, connection: std.net.StreamServer.Connection) WrapError!Self {
return Self{
.tls_configuration = tls_configuration,
.tls_context = tls_context,
.tcp_stream = connection.stream,
.address = connection.address,
};
}
pub fn deinit(self: *Self) void {
root.closeTlsContext(self.tls_context) catch |e| {
root.out.err("Failed to call tls_close on client: {} ({s})", .{ e, tls.tls_error(self.tls_context) });
};
tls.tls_free(self.tls_context);
self.tcp_stream.close();
self.* = undefined;
}
pub const ReadError = error{ReadFailure};
pub const Reader = std.io.Reader(*Self, ReadError, Self.read);
pub fn read(self: *Self, buffer: []u8) ReadError!usize {
const bytes_read = tls.tls_read(self.tls_context, buffer.ptr, buffer.len);
if (bytes_read == -1) {
root.out.warn("err={s}", .{tls.tls_error(self.tls_context)});
return error.ReadFailure;
}
return @intCast(usize, bytes_read);
}
pub fn reader(self: *Self) Reader {
return Reader{ .context = self };
}
pub const WriteError = error{WriteFailure};
pub const Writer = std.io.Writer(*Self, WriteError, Self.write);
pub fn write(self: *Self, buffer: []const u8) WriteError!usize {
const bytes_written = tls.tls_write(self.tls_context, buffer.ptr, buffer.len);
if (bytes_written == -1)
return error.WriteFailure;
return @intCast(usize, bytes_written);
}
pub fn writer(self: *Self) Writer {
return Writer{ .context = self };
} | src/SslStream.zig |
const std = @import("std");
const testing = std.testing;
const allocator = std.heap.page_allocator;
const memory_size = 30_000;
const max_file_size = 1024 * 1024 * 1024;
pub fn main() anyerror!void {
const args = try std.process.argsAlloc(allocator);
defer std.process.argsFree(allocator, args);
const stderr = std.io.getStdErr().writer();
if (args.len != 2 and !(args.len == 3 and std.mem.eql(u8, args[1], "-e"))) {
try stderr.print("usage: brainfuck [-e expression] [file path]\n", .{});
std.os.exit(1);
}
if (args.len == 3) {
const program = args[2];
interpret(program) catch std.os.exit(1);
} else if (args.len == 2) {
const file_path = args[1];
const program = std.fs.cwd().readFileAlloc(allocator, file_path, max_file_size) catch {
try stderr.print("File not found: {s}\n", .{ file_path });
std.os.exit(1);
};
defer allocator.free(program);
interpret(program) catch std.os.exit(1);
}
}
pub fn interpret(program: []const u8) anyerror!void {
const stdin = std.io.getStdIn().reader();
const stdout = std.io.getStdOut().writer();
const stderr = std.io.getStdErr().writer();
var memory = [_]i32{0} ** memory_size;
var index: u32 = 0;
var program_counter: u32 = 0;
while (program_counter < program.len) {
var character = program[program_counter];
switch(character) {
'>' => {
if (index == memory_size - 1) {
try stderr.print("Error: index out of upper bounds at char {d}\n", .{ program_counter });
return error.IndexOutOfBounds;
}
index += 1;
},
'<' => {
if (index == 0) {
try stderr.print("Error: index out of lower bounds at char {d}\n", .{ program_counter });
return error.IndexOutOfBounds;
}
index -=1 ;
},
'+' => {
memory[index] +%= 1;
},
'-' => {
memory[index] -%= 1;
},
'.' => {
const out_byte = @truncate(u8, @bitCast(u32, memory[index]));
try stdout.writeByte(out_byte);
},
',' => {
memory[index] = stdin.readByte() catch 0;
},
'[' => {
if (memory[index] == 0) {
const start = program_counter;
var depth: u32 = 1;
while (program_counter < program.len - 1) {
program_counter += 1;
const seek_char = program[program_counter];
if (seek_char == ']') {
depth -= 1;
}
if (depth == 0) {
break;
}
if (seek_char == '[') {
depth += 1;
}
}
if (program_counter == program.len - 1 and depth != 0) {
try stderr.print("Error: missing closing braket to opening bracket at char {d}\n", .{ start });
return error.MissingClosingBracket;
}
}
},
']' => {
if (memory[index] != 0) {
const start = program_counter;
var depth: u32 = 1;
while (program_counter > 0) {
program_counter -= 1;
const seek_char = program[program_counter];
if (seek_char == '[') {
depth -= 1;
}
if (depth == 0) {
break;
}
if (seek_char == ']') {
depth += 1;
}
}
if (program_counter == 0 and depth != 0) {
try stderr.print("Error: missing opening bracket to closing bracket at char {d}\n", .{ start });
return error.MissingOpeningBracket;
}
}
},
else => { }
}
program_counter += 1;
}
}
test "get cell bit width brainfuck" {
const program =
\\ // This generates 65536 to check for larger than 16bit cells
\\ [-]>[-]++[<++++++++>-]<[>++++++++<-]>[<++++++++>-]<[>++++++++<-]>[<+++++
\\ +++>-]<[[-]
\\ [-]>[-]+++++[<++++++++++>-]<+.-.
\\ [-]]
\\ // This section is cell doubling for 16bit cells
\\ >[-]>[-]<<[-]++++++++[>++++++++<-]>[<++++>-]<[->+>+<<]>[<++++++++>-]<[>+
\\ +++++++<-]>[<++++>-]>[<+>[-]]<<[>[-]<[-]]>[-<+>]<[[-]
\\ [-]>[-]+++++++[<+++++++>-]<.+++++.
\\ [-]]
\\ // This section is cell quadrupling for 8bit cells
\\ [-]>[-]++++++++[<++++++++>-]<[>++++<-]+>[<->[-]]<[[-]
\\ [-]>[-]+++++++[<++++++++>-]<.
\\ [-]]
\\ [-]>[-]++++[-<++++++++>]<.[->+++<]>++.+++++++.+++++++++++.[----<+>]<+++.
\\ +[->+++<]>.++.+++++++..+++++++.[-]++++++++++.[-]<
;
std.debug.print("\n", .{});
try interpret(program);
}
test "write in cell outside of array bottom" {
const program = "<<<+";
const output = interpret(program);
try testing.expectError(error.IndexOutOfBounds, output);
}
test "write in cell outside of array top" {
const program = ">" ** memory_size;
const output = interpret(program);
try testing.expectError(error.IndexOutOfBounds, output);
}
test "write number over 255 to stdout" {
const program = "+" ** 300 ++ ".";
try interpret(program);
std.debug.print("\n", .{});
}
test "write negative number to stdout" {
const program = "-" ** 200 ++ ".";
try interpret(program);
std.debug.print("\n", .{});
}
test "loop without end" {
const program = "[><";
const output = interpret(program);
try testing.expectError(error.MissingClosingBracket, output);
}
test "loop without beginning" {
const program = "+><]";
const output = interpret(program);
try testing.expectError(error.MissingOpeningBracket, output);
} | src/main.zig |
const std = @import("std");
const c = @import("c.zig");
const shaderc = @import("shaderc.zig");
pub const Blit = struct {
const Self = @This();
device: c.WGPUDeviceId,
bind_group_layout: c.WGPUBindGroupLayoutId,
tex_sampler: c.WGPUSamplerId,
bind_group: ?c.WGPUBindGroupId,
render_pipeline: c.WGPURenderPipelineId,
pub fn init(alloc: *std.mem.Allocator, device: c.WGPUDeviceId) !Blit {
var arena = std.heap.ArenaAllocator.init(alloc);
const tmp_alloc: *std.mem.Allocator = &arena.allocator;
defer arena.deinit();
////////////////////////////////////////////////////////////////////////////
// Build the shaders using shaderc
const vert_spv = shaderc.build_shader_from_file(tmp_alloc, "shaders/blit.vert") catch |err| {
std.debug.panic("Could not open file", .{});
};
const vert_shader = c.wgpu_device_create_shader_module(
device,
(c.WGPUShaderSource){
.bytes = vert_spv.ptr,
.length = vert_spv.len,
},
);
defer c.wgpu_shader_module_destroy(vert_shader);
const frag_spv = shaderc.build_shader_from_file(tmp_alloc, "shaders/blit.frag") catch |err| {
std.debug.panic("Could not open file", .{});
};
const frag_shader = c.wgpu_device_create_shader_module(
device,
(c.WGPUShaderSource){
.bytes = frag_spv.ptr,
.length = frag_spv.len,
},
);
defer c.wgpu_shader_module_destroy(frag_shader);
///////////////////////////////////////////////////////////////////////
// Texture sampler (the texture comes from the Preview struct)
const tex_sampler = c.wgpu_device_create_sampler(device, &(c.WGPUSamplerDescriptor){
.next_in_chain = null,
.label = "font_atlas_sampler",
.address_mode_u = c.WGPUAddressMode._ClampToEdge,
.address_mode_v = c.WGPUAddressMode._ClampToEdge,
.address_mode_w = c.WGPUAddressMode._ClampToEdge,
.mag_filter = c.WGPUFilterMode._Linear,
.min_filter = c.WGPUFilterMode._Nearest,
.mipmap_filter = c.WGPUFilterMode._Nearest,
.lod_min_clamp = 0.0,
.lod_max_clamp = std.math.f32_max,
.compare = c.WGPUCompareFunction._Undefined,
});
////////////////////////////////////////////////////////////////////////////
// Bind groups (?!)
const bind_group_layout_entries = [_]c.WGPUBindGroupLayoutEntry{
(c.WGPUBindGroupLayoutEntry){
.binding = 0,
.visibility = c.WGPUShaderStage_FRAGMENT,
.ty = c.WGPUBindingType_SampledTexture,
.multisampled = false,
.view_dimension = c.WGPUTextureViewDimension._D2,
.texture_component_type = c.WGPUTextureComponentType._Uint,
.storage_texture_format = c.WGPUTextureFormat._Bgra8Unorm,
.count = undefined,
.has_dynamic_offset = undefined,
.min_buffer_binding_size = undefined,
},
(c.WGPUBindGroupLayoutEntry){
.binding = 1,
.visibility = c.WGPUShaderStage_FRAGMENT,
.ty = c.WGPUBindingType_Sampler,
.multisampled = undefined,
.view_dimension = undefined,
.texture_component_type = undefined,
.storage_texture_format = undefined,
.count = undefined,
.has_dynamic_offset = undefined,
.min_buffer_binding_size = undefined,
},
};
const bind_group_layout = c.wgpu_device_create_bind_group_layout(
device,
&(c.WGPUBindGroupLayoutDescriptor){
.label = "bind group layout",
.entries = &bind_group_layout_entries,
.entries_length = bind_group_layout_entries.len,
},
);
const bind_group_layouts = [_]c.WGPUBindGroupId{bind_group_layout};
////////////////////////////////////////////////////////////////////////////
// Render pipelines
const pipeline_layout = c.wgpu_device_create_pipeline_layout(
device,
&(c.WGPUPipelineLayoutDescriptor){
.bind_group_layouts = &bind_group_layouts,
.bind_group_layouts_length = bind_group_layouts.len,
},
);
defer c.wgpu_pipeline_layout_destroy(pipeline_layout);
const render_pipeline = c.wgpu_device_create_render_pipeline(
device,
&(c.WGPURenderPipelineDescriptor){
.layout = pipeline_layout,
.vertex_stage = (c.WGPUProgrammableStageDescriptor){
.module = vert_shader,
.entry_point = "main",
},
.fragment_stage = &(c.WGPUProgrammableStageDescriptor){
.module = frag_shader,
.entry_point = "main",
},
.rasterization_state = &(c.WGPURasterizationStateDescriptor){
.front_face = c.WGPUFrontFace._Ccw,
.cull_mode = c.WGPUCullMode._None,
.depth_bias = 0,
.depth_bias_slope_scale = 0.0,
.depth_bias_clamp = 0.0,
},
.primitive_topology = c.WGPUPrimitiveTopology._TriangleList,
.color_states = &(c.WGPUColorStateDescriptor){
.format = c.WGPUTextureFormat._Bgra8Unorm,
.alpha_blend = (c.WGPUBlendDescriptor){
.src_factor = c.WGPUBlendFactor._One,
.dst_factor = c.WGPUBlendFactor._Zero,
.operation = c.WGPUBlendOperation._Add,
},
.color_blend = (c.WGPUBlendDescriptor){
.src_factor = c.WGPUBlendFactor._One,
.dst_factor = c.WGPUBlendFactor._Zero,
.operation = c.WGPUBlendOperation._Add,
},
.write_mask = c.WGPUColorWrite_ALL,
},
.color_states_length = 1,
.depth_stencil_state = null,
.vertex_state = (c.WGPUVertexStateDescriptor){
.index_format = c.WGPUIndexFormat._Uint16,
.vertex_buffers = null,
.vertex_buffers_length = 0,
},
.sample_count = 1,
.sample_mask = 0,
.alpha_to_coverage_enabled = false,
},
);
return Self{
.device = device,
.tex_sampler = tex_sampler,
.render_pipeline = render_pipeline,
.bind_group_layout = bind_group_layout,
.bind_group = null, // Not assigned until bind_to_tex is called
};
}
pub fn bind_to_tex(self: *Self, tex_view: c.WGPUTextureViewId) void {
if (self.bind_group) |b| {
c.wgpu_bind_group_destroy(b);
}
const bind_group_entries = [_]c.WGPUBindGroupEntry{
(c.WGPUBindGroupEntry){
.binding = 0,
.texture_view = tex_view,
.sampler = 0, // None
.buffer = 0, // None
.offset = undefined,
.size = undefined,
},
(c.WGPUBindGroupEntry){
.binding = 1,
.sampler = self.tex_sampler,
.texture_view = 0, // None
.buffer = 0, // None
.offset = undefined,
.size = undefined,
},
};
self.bind_group = c.wgpu_device_create_bind_group(
self.device,
&(c.WGPUBindGroupDescriptor){
.label = "bind group",
.layout = self.bind_group_layout,
.entries = &bind_group_entries,
.entries_length = bind_group_entries.len,
},
);
}
pub fn deinit(self: *Self) void {
c.wgpu_sampler_destroy(self.tex_sampler);
c.wgpu_bind_group_layout_destroy(self.bind_group_layout);
if (self.bind_group) |b| {
c.wgpu_bind_group_destroy(b);
}
}
pub fn redraw(
self: *Self,
next_texture: c.WGPUSwapChainOutput,
cmd_encoder: c.WGPUCommandEncoderId,
) void {
const color_attachments = [_]c.WGPURenderPassColorAttachmentDescriptor{
(c.WGPURenderPassColorAttachmentDescriptor){
.attachment = next_texture.view_id,
.resolve_target = 0,
.channel = (c.WGPUPassChannel_Color){
.load_op = c.WGPULoadOp._Load,
.store_op = c.WGPUStoreOp._Store,
.clear_value = (c.WGPUColor){
.r = 0.0,
.g = 0.0,
.b = 0.0,
.a = 1.0,
},
.read_only = false,
},
},
};
const rpass = c.wgpu_command_encoder_begin_render_pass(
cmd_encoder,
&(c.WGPURenderPassDescriptor){
.color_attachments = &color_attachments,
.color_attachments_length = color_attachments.len,
.depth_stencil_attachment = null,
},
);
c.wgpu_render_pass_set_pipeline(rpass, self.render_pipeline);
const b = self.bind_group orelse std.debug.panic(
"Tried to blit preview before texture was bound",
.{},
);
c.wgpu_render_pass_set_bind_group(rpass, 0, b, null, 0);
c.wgpu_render_pass_draw(rpass, 6, 1, 0, 0);
c.wgpu_render_pass_end_pass(rpass);
}
}; | src/blit.zig |
const std = @import("std");
const bcm2835 = @import("../bcm2835.zig");
const gpio = @import("../gpio.zig");
const mocks = @import("mocks.zig");
const peripherals = @import("../peripherals.zig");
test "SetLevel - High" {
std.testing.log_level = .debug;
var allocator = std.testing.allocator;
var gpiomem = try mocks.MockGpioMemoryMapper.init(&allocator, bcm2835.BoardInfo.gpio_registers);
defer gpiomem.deinit();
try gpio.init(&gpiomem.memory_mapper);
defer gpio.deinit();
// we can set the level to high without having to worry about setting the pin to the right mode
// because we are just interested in the correct value being written into the right register
// but before we do, verify that the gpset registers indeed hold only null values
try std.testing.expectEqual(gpiomem.registerValue(7), 0); //gpset0
try std.testing.expectEqual(gpiomem.registerValue(8), 0); //gpset1
try gpio.setLevel(0, .High);
try std.testing.expectEqual(gpiomem.registerValue(7), 0b1);
try gpio.setLevel(1, .High);
try std.testing.expectEqual(gpiomem.registerValue(7), 0b11);
try gpio.setLevel(10, .High);
try std.testing.expectEqual(gpiomem.registerValue(7), 0b10000000011);
try gpio.setLevel(42, .High);
try std.testing.expectEqual(gpiomem.registerValue(7), 0b10000000011);
try std.testing.expectEqual(gpiomem.registerValue(8), 0b10000000000);
}
test "SetLevel - Low" {
std.testing.log_level = .debug;
var allocator = std.testing.allocator;
var gpiomem = try mocks.MockGpioMemoryMapper.init(&allocator, bcm2835.BoardInfo.gpio_registers);
defer gpiomem.deinit();
try gpio.init(&gpiomem.memory_mapper);
defer gpio.deinit();
try std.testing.expectEqual(gpiomem.registerValue(10), 0); //gpclr0
try std.testing.expectEqual(gpiomem.registerValue(11), 0); //gpclr1
try gpio.setLevel(0, .Low);
try std.testing.expectEqual(gpiomem.registerValue(10), 0b1);
try gpio.setLevel(1, .Low);
try std.testing.expectEqual(gpiomem.registerValue(10), 0b11);
try gpio.setLevel(10, .Low);
try std.testing.expectEqual(gpiomem.registerValue(10), 0b10000000011);
try gpio.setLevel(42, .Low);
try std.testing.expectEqual(gpiomem.registerValue(10), 0b10000000011);
try std.testing.expectEqual(gpiomem.registerValue(11), 0b10000000000);
}
test "GetLevel" {
std.testing.log_level = .debug;
var allocator = std.testing.allocator;
var gpiomem = try mocks.MockGpioMemoryMapper.init(&allocator, bcm2835.BoardInfo.gpio_registers);
defer gpiomem.deinit();
try gpio.init(&gpiomem.memory_mapper);
defer gpio.deinit();
const gplev0 = 0b1001001; //pins high: (0,3,6)
const gplev1 = 0b0110110; //pins high: 32 + (1,2,4,5)
try gpiomem.setRegisterValue(13, gplev0); //gplev0
try gpiomem.setRegisterValue(14, gplev1); //gplev1
try std.testing.expectEqual(gpio.getLevel(0), .High);
try std.testing.expectEqual(gpio.getLevel(1), .Low);
try std.testing.expectEqual(gpio.getLevel(2), .Low);
try std.testing.expectEqual(gpio.getLevel(3), .High);
try std.testing.expectEqual(gpio.getLevel(4), .Low);
try std.testing.expectEqual(gpio.getLevel(5), .Low);
try std.testing.expectEqual(gpio.getLevel(6), .High);
try std.testing.expectEqual(gpio.getLevel(32 + 0), .Low);
try std.testing.expectEqual(gpio.getLevel(32 + 1), .High);
try std.testing.expectEqual(gpio.getLevel(32 + 2), .High);
try std.testing.expectEqual(gpio.getLevel(32 + 3), .Low);
try std.testing.expectEqual(gpio.getLevel(32 + 4), .High);
try std.testing.expectEqual(gpio.getLevel(32 + 5), .High);
try std.testing.expectEqual(gpio.getLevel(32 + 6), .Low);
}
test "SetMode" {
std.testing.log_level = .debug;
var allocator = std.testing.allocator;
var gpiomem = try mocks.MockGpioMemoryMapper.init(&allocator, bcm2835.BoardInfo.gpio_registers);
defer gpiomem.deinit();
try gpio.init(&gpiomem.memory_mapper);
defer gpio.deinit();
try std.testing.expectEqual(gpiomem.registerValue(0), 0); //gpfsel0
try std.testing.expectEqual(gpiomem.registerValue(1), 0); //gpfsel1
try std.testing.expectEqual(gpiomem.registerValue(5), 0); //gpfsel5
try gpio.setMode(0, .Input);
try std.testing.expectEqual(gpiomem.registerValue(0), 0b0);
try gpio.setMode(1, .Output);
try std.testing.expectEqual(gpiomem.registerValue(0), 0b001000);
try gpio.setMode(11, .Alternate1);
try std.testing.expectEqual(gpiomem.registerValue(1), 0b101000);
try gpio.setMode(50, .Alternate1);
try std.testing.expectEqual(gpiomem.registerValue(5), 0b101);
}
test "GetMode" {
std.testing.log_level = .debug;
var allocator = std.testing.allocator;
var gpiomem = try mocks.MockGpioMemoryMapper.init(&allocator, bcm2835.BoardInfo.gpio_registers);
defer gpiomem.deinit();
try gpio.init(&gpiomem.memory_mapper);
defer gpio.deinit();
try gpiomem.setRegisterValue(0, 0b00010000000000000000000000000101); //gpfsel 0
try gpiomem.setRegisterValue(1, 0b00000111000000000000000000011000); //gpfsel 1
try std.testing.expectEqual(gpio.Mode.Alternate1, try gpio.getMode(0));
try std.testing.expectEqual(gpio.Mode.Input, try gpio.getMode(1));
try std.testing.expectEqual(gpio.Mode.Alternate5, try gpio.getMode(9));
try std.testing.expectEqual(gpio.Mode.Input, try gpio.getMode(10));
try std.testing.expectEqual(gpio.Mode.Alternate4, try gpio.getMode(11));
try std.testing.expectEqual(gpio.Mode.Input, try gpio.getMode(12));
try std.testing.expectEqual(gpio.Mode.Input, try gpio.getMode(17));
try std.testing.expectEqual(gpio.Mode.Alternate3, try gpio.getMode(18));
}
test "setPull" {
std.testing.log_level = .debug;
var allocator = std.testing.allocator;
var gpiomem = try mocks.MockGpioMemoryMapper.init(&allocator, bcm2835.BoardInfo.gpio_registers);
defer gpiomem.deinit();
try gpio.init(&gpiomem.memory_mapper);
defer gpio.deinit();
// unfortunately we can just smoke test this one here, because the register values
// will be set and unset in this function.
try gpio.setPull(2, .PullDown);
} | src/integration-tests/bcm2835.zig |
const Allocator = std.mem.Allocator;
const Headers = @import("http").Headers;
const parseHeaders = @import("headers.zig").parse;
const ParsingError = @import("errors.zig").ParsingError;
const StatusCode = @import("http").StatusCode;
const std = @import("std");
const Version = @import("http").Version;
pub const Response = struct {
allocator: *Allocator,
headers: Headers,
statusCode: StatusCode,
version: Version,
raw_bytes: []const u8,
pub fn deinit(self: Response) void {
var headers = self.headers;
headers.deinit();
self.allocator.free(self.raw_bytes);
}
pub fn parse(allocator: *Allocator, buffer: []const u8) !Response {
const line_end = std.mem.indexOf(u8, buffer, "\r\n") orelse return error.Invalid;
const status_line = buffer[0..line_end];
if (status_line.len < 12) {
return error.Invalid;
}
const http_version = Version.from_bytes(status_line[0..8]) orelse return error.Invalid;
switch (http_version) {
.Http11 => {},
else => return error.Invalid,
}
if (status_line[8] != ' ') {
return error.Invalid;
}
const raw_code = std.fmt.parseInt(u16, status_line[9..12], 10) catch return error.Invalid;
const status_code = StatusCode.from_u16(raw_code) catch return error.Invalid;
if (status_line.len > 12 and status_line[12] != ' ' and status_line[12] != '\r') {
return error.Invalid;
}
var _headers = try parseHeaders(allocator, buffer[status_line.len + 2 ..], 128);
return Response{
.allocator = allocator,
.headers = _headers,
.version = http_version,
.statusCode = status_code,
.raw_bytes = buffer,
};
}
};
const expect = std.testing.expect;
const expectError = std.testing.expectError;
const dupe = std.testing.allocator.dupe;
test "Parse - Success" {
const buffer = try dupe(u8, "HTTP/1.1 200 OK\r\nServer: Apache\r\nContent-Length: 0\r\n\r\n");
var response = try Response.parse(std.testing.allocator, buffer);
defer response.deinit();
try expect(response.statusCode == .Ok);
try expect(response.version == .Http11);
try expect(response.headers.len() == 2);
}
test "Parse - Missing reason phrase" {
const buffer = try dupe(u8, "HTTP/1.1 200\r\n\r\n\r\n");
var response = try Response.parse(std.testing.allocator, buffer);
defer response.deinit();
try expect(response.statusCode == .Ok);
try expect(response.version == .Http11);
}
test "Parse - TooManyHeaders" {
const buffer = "HTTP/1.1 200\r\n" ++ "Cookie: aaa\r\n" ** 129 ++ "\r\n";
var failure = Response.parse(std.testing.allocator, buffer);
try expectError(error.TooManyHeaders, failure);
}
test "Issue #28: Parse - Status code below 100 is invalid" {
const content = "HTTP/1.1 99\r\n\r\n\r\n";
var failure = Response.parse(std.testing.allocator, content);
try expectError(error.Invalid, failure);
}
test "Issue #28: Parse - Status code above 599 is invalid" {
const content = "HTTP/1.1 600\r\n\r\n\r\n";
var failure = Response.parse(std.testing.allocator, content);
try expectError(error.Invalid, failure);
}
test "Parse - Response is invalid if the HTTP version is not HTTP/1.X" {
const content = "HTTP/2.0 200 OK\r\n\r\n\r\n";
const failure = Response.parse(std.testing.allocator, content);
try expectError(error.Invalid, failure);
}
test "Parse - Response is invalid if the status line is less than 12 characters" {
const content = "HTTP/1.1 99\r\n\r\n\r\n";
const failure = Response.parse(std.testing.allocator, content);
try expectError(error.Invalid, failure);
}
test "Parse - When the http version and the status code are not separated by a whitespace - Returns Invalid" {
const content = "HTTP/1.1200 OK\r\n\r\n\r\n";
const failure = Response.parse(std.testing.allocator, content);
try expectError(error.Invalid, failure);
}
test "Parse - When the status code is not an integer - Returns Invalid" {
const content = "HTTP/1.1 2xx OK\r\n\r\n\r\n";
const failure = Response.parse(std.testing.allocator, content);
try expectError(error.Invalid, failure);
}
test "Issue #29: Parse - When the status code is more than 3 digits - Returns Invalid" {
const content = "HTTP/1.1 1871 OK\r\n\r\n\r\n";
const failure = Response.parse(std.testing.allocator, content);
try expectError(error.Invalid, failure);
} | src/events/response.zig |
const std = @import("std");
const pike = @import("pike.zig");
const windows = @import("os/windows.zig");
const ws2_32 = @import("os/windows/ws2_32.zig");
const io = std.io;
const os = std.os;
const net = std.net;
const mem = std.mem;
const meta = std.meta;
var OVERLAPPED = windows.OVERLAPPED{ .Internal = 0, .InternalHigh = 0, .Offset = 0, .OffsetHigh = 0, .hEvent = null };
var OVERLAPPED_PARAM = &OVERLAPPED;
pub const SocketOptionType = enum(u32) {
debug = os.SO_DEBUG,
listen = os.SO_ACCEPTCONN,
reuse_address = os.SO_REUSEADDR,
keep_alive = os.SO_KEEPALIVE,
dont_route = os.SO_DONTROUTE,
broadcast = os.SO_BROADCAST,
linger = os.SO_LINGER,
oob_inline = os.SO_OOBINLINE,
send_buffer_max_size = os.SO_SNDBUF,
recv_buffer_max_size = os.SO_RCVBUF,
send_buffer_min_size = os.SO_SNDLOWAT,
recv_buffer_min_size = os.SO_RCVLOWAT,
send_timeout = os.SO_SNDTIMEO,
recv_timeout = os.SO_RCVTIMEO,
socket_error = os.SO_ERROR,
socket_type = os.SO_TYPE,
protocol_info_a = ws2_32.SO_PROTOCOL_INFOA,
protocol_info_w = ws2_32.SO_PROTOCOL_INFOW,
update_connect_context = ws2_32.SO_UPDATE_CONNECT_CONTEXT,
update_accept_context = ws2_32.SO_UPDATE_ACCEPT_CONTEXT,
};
pub const SocketOption = union(SocketOptionType) {
debug: bool,
listen: bool,
reuse_address: bool,
keep_alive: bool,
dont_route: bool,
broadcast: bool,
linger: ws2_32.LINGER,
oob_inline: bool,
send_buffer_max_size: u32,
recv_buffer_max_size: u32,
send_buffer_min_size: u32,
recv_buffer_min_size: u32,
send_timeout: u32, // Timeout specified in milliseconds.
recv_timeout: u32, // Timeout specified in milliseconds.
socket_error: void,
socket_type: u32,
protocol_info_a: ws2_32.WSAPROTOCOL_INFOA,
protocol_info_w: ws2_32.WSAPROTOCOL_INFOW,
update_connect_context: ?ws2_32.SOCKET,
update_accept_context: ?ws2_32.SOCKET,
};
pub const Connection = struct {
socket: Socket,
address: net.Address,
};
pub const Socket = struct {
pub const Reader = io.Reader(*Self, anyerror, read);
pub const Writer = io.Writer(*Self, anyerror, write);
const Self = @This();
handle: pike.Handle,
pub fn init(domain: i32, socket_type: i32, protocol: i32, flags: windows.DWORD) !Self {
return Self{
.handle = .{
.inner = try windows.WSASocketW(
domain,
socket_type,
protocol,
null,
0,
flags | ws2_32.WSA_FLAG_OVERLAPPED | ws2_32.WSA_FLAG_NO_HANDLE_INHERIT,
),
},
};
}
pub fn deinit(self: *const Self) void {
self.shutdown(ws2_32.SD_BOTH) catch {};
windows.closesocket(@ptrCast(ws2_32.SOCKET, self.handle.inner)) catch {};
}
pub fn registerTo(self: *const Self, notifier: *const pike.Notifier) !void {
try notifier.register(&self.handle, .{ .read = true, .write = true });
}
fn ErrorUnionOf(comptime func: anytype) std.builtin.TypeInfo.ErrorUnion {
return @typeInfo(@typeInfo(@TypeOf(func)).Fn.return_type.?).ErrorUnion;
}
fn call(_: *Self, comptime function: anytype, raw_args: anytype, comptime _: pike.CallOptions) callconv(.Async) (ErrorUnionOf(function).error_set || error{OperationCancelled})!pike.Overlapped {
var overlapped = pike.Overlapped.init(pike.Task.init(@frame()));
var args = raw_args;
comptime var i = 0;
inline while (i < args.len) : (i += 1) {
if (comptime @TypeOf(args[i]) == *windows.OVERLAPPED) {
args[i] = &overlapped.inner;
}
}
var err: ?ErrorUnionOf(function).error_set = null;
suspend {
var would_block = false;
if (@call(.{ .modifier = .always_inline }, function, args)) |_| {} else |call_err| switch (call_err) {
error.WouldBlock => would_block = true,
else => err = call_err,
}
if (!would_block) pike.dispatch(&overlapped.task, .{ .use_lifo = true });
}
if (err) |call_err| return call_err;
return overlapped;
}
pub fn shutdown(self: *const Self, how: c_int) !void {
try windows.shutdown(@ptrCast(ws2_32.SOCKET, self.handle.inner), how);
}
pub fn get(self: *const Self, comptime opt: SocketOptionType) !meta.TagPayload(SocketOption, opt) {
if (opt == .socket_error) {
const errno = try windows.getsockopt(u32, @ptrCast(ws2_32.SOCKET, self.handle.inner), os.SOL.SOCKET, @enumToInt(opt));
if (errno != 0) {
return switch (@intToEnum(ws2_32.WinsockError, @truncate(u16, errno))) {
.WSAEACCES => error.PermissionDenied,
.WSAEADDRINUSE => error.AddressInUse,
.WSAEADDRNOTAVAIL => error.AddressNotAvailable,
.WSAEAFNOSUPPORT => error.AddressFamilyNotSupported,
.WSAEALREADY => error.AlreadyConnecting,
.WSAEBADF => error.BadFileDescriptor,
.WSAECONNREFUSED => error.ConnectionRefused,
.WSAEFAULT => error.InvalidParameter,
.WSAEISCONN => error.AlreadyConnected,
.WSAENETUNREACH => error.NetworkUnreachable,
.WSAENOTSOCK => error.NotASocket,
.WSAEPROTOTYPE => error.UnsupportedProtocol,
.WSAETIMEDOUT => error.ConnectionTimedOut,
.WSAESHUTDOWN => error.AlreadyShutdown,
else => |err| windows.unexpectedWSAError(err),
};
}
} else {
return windows.getsockopt(
meta.TagPayload(SocketOption, opt),
@ptrCast(ws2_32.SOCKET, self.handle.inner),
os.SOL.SOCKET,
@enumToInt(opt),
);
}
}
pub fn set(self: *const Self, comptime opt: SocketOptionType, val: meta.TagPayload(SocketOption, opt)) !void {
try windows.setsockopt(
@ptrCast(ws2_32.SOCKET, self.handle.inner),
os.SOL.SOCKET,
@enumToInt(opt),
blk: {
if (comptime @typeInfo(@TypeOf(val)) == .Optional) {
break :blk if (val) |v| @as([]const u8, std.mem.asBytes(&v)[0..@sizeOf(@TypeOf(val))]) else null;
} else {
break :blk @as([]const u8, std.mem.asBytes(&val)[0..@sizeOf(@TypeOf(val))]);
}
},
);
}
pub fn getBindAddress(self: *const Self) !net.Address {
var addr: os.sockaddr = undefined;
var addr_len: os.socklen_t = @sizeOf(@TypeOf(addr));
try os.getsockname(@ptrCast(ws2_32.SOCKET, self.handle.inner), &addr, &addr_len);
return net.Address.initPosix(@alignCast(4, &addr));
}
pub fn bind(self: *const Self, address: net.Address) !void {
try windows.bind_(@ptrCast(ws2_32.SOCKET, self.handle.inner), &address.any, address.getOsSockLen());
}
pub fn listen(self: *const Self, backlog: usize) !void {
try windows.listen_(@ptrCast(ws2_32.SOCKET, self.handle.inner), backlog);
}
pub fn accept(self: *Self) callconv(.Async) !Connection {
const info = try self.get(.protocol_info_w);
var incoming = try Self.init(
info.iAddressFamily,
info.iSocketType,
info.iProtocol,
0,
);
errdefer incoming.deinit();
var buf: [2 * @sizeOf(ws2_32.sockaddr_storage) + 32]u8 = undefined;
var num_bytes: windows.DWORD = undefined;
_ = try self.call(windows.AcceptEx, .{
@ptrCast(ws2_32.SOCKET, self.handle.inner),
@ptrCast(ws2_32.SOCKET, incoming.handle.inner),
&buf,
@sizeOf(ws2_32.sockaddr_storage),
@sizeOf(ws2_32.sockaddr_storage),
&num_bytes,
OVERLAPPED_PARAM,
}, .{});
var local_addr: *ws2_32.sockaddr = undefined;
var remote_addr: *ws2_32.sockaddr = undefined;
windows.GetAcceptExSockaddrs(
@ptrCast(ws2_32.SOCKET, self.handle.inner),
&buf,
@as(c_int, @sizeOf(ws2_32.sockaddr_storage)),
@as(c_int, @sizeOf(ws2_32.sockaddr_storage)),
&local_addr,
&remote_addr,
) catch |err| switch (err) {
error.FileDescriptorNotASocket => return error.SocketNotListening,
else => return err,
};
try incoming.set(.update_accept_context, @ptrCast(ws2_32.SOCKET, self.handle.inner));
return Connection{
.socket = incoming,
.address = net.Address.initPosix(@alignCast(4, remote_addr)),
};
}
pub fn connect(self: *Self, address: net.Address) callconv(.Async) !void {
try self.bind(net.Address.initIp4(.{ 0, 0, 0, 0 }, 0));
_ = try self.call(windows.ConnectEx, .{
@ptrCast(ws2_32.SOCKET, self.handle.inner),
&address.any,
address.getOsSockLen(),
OVERLAPPED_PARAM,
}, .{});
try self.get(.socket_error);
try self.set(.update_connect_context, null);
}
pub inline fn reader(self: *Self) Reader {
return Reader{ .context = self };
}
pub inline fn writer(self: *Self) Writer {
return Writer{ .context = self };
}
pub fn read(self: *Self, buf: []u8) !usize {
const overlapped = self.call(windows.ReadFile_, .{
self.handle.inner, buf, OVERLAPPED_PARAM,
}, .{}) catch |err| switch (err) {
error.EndOfFile => return 0,
else => return err,
};
return overlapped.inner.InternalHigh;
}
pub fn recv(self: *Self, buf: []u8, flags: u32) callconv(.Async) !usize {
const overlapped = self.call(windows.WSARecv, .{
@ptrCast(ws2_32.SOCKET, self.handle.inner), buf, flags, OVERLAPPED_PARAM,
}, .{}) catch |err| switch (err) {
error.ConnectionAborted,
error.ConnectionResetByPeer,
error.ConnectionClosedByPeer,
error.NetworkSubsystemFailed,
error.NetworkReset,
=> return 0,
else => return err,
};
return overlapped.inner.InternalHigh;
}
pub fn recvFrom(self: *Self, buf: []u8, flags: u32, address: ?*net.Address) callconv(.Async) !usize {
var src_addr: ws2_32.sockaddr = undefined;
var src_addr_len: ws2_32.socklen_t = undefined;
const overlapped = self.call(windows.WSARecvFrom, .{
@ptrCast(ws2_32.SOCKET, self.handle.inner),
buf,
flags,
@as(?*ws2_32.sockaddr, if (address != null) &src_addr else null),
@as(?*ws2_32.socklen_t, if (address != null) &src_addr_len else null),
OVERLAPPED_PARAM,
}, .{}) catch |err| switch (err) {
error.ConnectionAborted,
error.ConnectionResetByPeer,
error.ConnectionClosedByPeer,
error.NetworkSubsystemFailed,
error.NetworkReset,
=> return 0,
else => return err,
};
if (address) |a| {
a.* = net.Address{ .any = src_addr };
}
return overlapped.inner.InternalHigh;
}
pub fn write(self: *Self, buf: []const u8) !usize {
const overlapped = self.call(windows.WriteFile_, .{
self.handle.inner, buf, OVERLAPPED_PARAM,
}, .{}) catch |err| switch (err) {
error.EndOfFile => return 0,
else => return err,
};
return overlapped.inner.InternalHigh;
}
pub fn send(self: *Self, buf: []const u8, flags: u32) callconv(.Async) !usize {
const overlapped = self.call(windows.WSASend, .{
@ptrCast(ws2_32.SOCKET, self.handle.inner), buf, flags, OVERLAPPED_PARAM,
}, .{}) catch |err| switch (err) {
error.ConnectionAborted,
error.ConnectionResetByPeer,
error.NetworkSubsystemFailed,
error.NetworkReset,
=> return 0,
else => return err,
};
return overlapped.inner.InternalHigh;
}
pub fn sendTo(self: *Self, buf: []const u8, flags: u32, address: ?net.Address) callconv(.Async) !usize {
const overlapped = self.call(windows.WSASendTo, .{
@ptrCast(ws2_32.SOCKET, self.handle.inner),
buf,
flags,
@as(?*const ws2_32.sockaddr, if (address) |a| &a.any else null),
if (address) |a| a.getOsSockLen() else 0,
OVERLAPPED_PARAM,
}, .{}) catch |err| switch (err) {
error.ConnectionAborted,
error.ConnectionResetByPeer,
error.ConnectionClosedByPeer,
error.NetworkSubsystemFailed,
error.NetworkReset,
=> return 0,
else => return err,
};
return overlapped.inner.InternalHigh;
}
}; | socket_windows.zig |
usingnamespace @import("root").preamble;
const kb = lib.input.keyboard;
pub const KeyboardLayout = enum {
en_US_QWERTY,
sv_SE_QWERTY,
};
// Keys that are common between keyboard layouts
fn keyLookupDefault(key: kb.keys.Location) error{UnknownKey}!kb.keys.Input {
return switch (key) {
.escape => .escape,
.left_shift => .left_shift,
.right_shift => .right_shift,
.left_ctrl => .left_ctrl,
.right_ctrl => .right_ctrl,
.left_super => .left_super,
.right_super => .right_super,
.left_alt => .left_alt,
.right_alt => .right_alt,
.spacebar => .spacebar,
.option_key => .option_key,
.print_screen => .print_screen,
.pause_break => .pause_break,
.scroll_lock => .scroll_lock,
.insert => .insert,
.home => .home,
.page_up => .page_up,
.delete => .delete,
.end => .end,
.page_down => .page_down,
.arrow_up => .arrow_up,
.arrow_left => .arrow_left,
.arrow_down => .arrow_down,
.arrow_right => .arrow_right,
.backspace => .backspace,
.media_stop => .media_stop,
.media_rewind => .media_rewind,
.media_pause_play => .media_pause_play,
.media_forward => .media_forward,
.media_mute => .media_mute,
.media_volume_up => .media_volume_up,
.media_volume_down => .media_volume_down,
.tab => .tab,
.capslock => .capslock,
.enter => .enter,
.numlock => .numlock,
.numpad_div => .numpad_div,
.numpad_mul => .numpad_mul,
.numpad7 => .numpad7,
.numpad8 => .numpad8,
.numpad9 => .numpad9,
.numpad_sub => .numpad_sub,
.numpad4 => .numpad4,
.numpad5 => .numpad5,
.numpad6 => .numpad6,
.numpad_add => .numpad_add,
.numpad1 => .numpad1,
.numpad2 => .numpad2,
.numpad3 => .numpad3,
.numpad0 => .numpad0,
.numpad_point => .numpad_point,
.numpad_enter => .numpad_enter,
.f1 => .f1,
.f2 => .f2,
.f3 => .f3,
.f4 => .f4,
.f5 => .f5,
.f6 => .f6,
.f7 => .f7,
.f8 => .f8,
.f9 => .f9,
.f10 => .f10,
.f11 => .f11,
.f12 => .f12,
.f13 => .f13,
.f14 => .f14,
.f15 => .f15,
.f16 => .f16,
.f17 => .f17,
.f18 => .f18,
.f19 => .f19,
.f20 => .f20,
.f21 => .f21,
.f22 => .f22,
.f23 => .f23,
.f24 => .f24,
else => error.UnknownKey,
};
}
fn queryQwertyFamily(key: kb.keys.Location) error{UnknownKey}!kb.keys.Input {
return switch (key) {
.line1_1 => .q,
.line1_2 => .w,
.line1_3 => .e,
.line1_4 => .r,
.line1_5 => .t,
.line1_6 => .y,
.line1_7 => .u,
.line1_8 => .i,
.line1_9 => .o,
.line1_10 => .p,
.line2_1 => .a,
.line2_2 => .s,
.line2_3 => .d,
.line2_4 => .f,
.line2_5 => .g,
.line2_6 => .h,
.line2_7 => .j,
.line2_8 => .k,
.line2_9 => .l,
.line3_1 => .z,
.line3_2 => .x,
.line3_3 => .c,
.line3_4 => .v,
.line3_5 => .b,
.line3_6 => .n,
.line3_7 => .m,
else => keyLookupDefault(key),
};
}
fn sv_SE_QWERTY(state: *const kb.state.KeyboardState, key: kb.keys.Location) !kb.keys.Input {
const shift = state.isShiftPressed();
const alt = state.isAltPressed();
switch (key) {
.left_of1 => {
if (alt) return kb.keys.Input.paragraph_sign;
return kb.keys.Input.section_sign;
},
.number_key1 => {
if (shift) return kb.keys.Input.exclamation_mark;
return kb.keys.Input.@"1";
},
.number_key2 => {
if (alt) return kb.keys.Input.at;
if (shift) return kb.keys.Input.quotation_mark;
return kb.keys.Input.@"2";
},
.number_key3 => {
if (alt) return kb.keys.Input.pound_sign;
if (shift) return kb.keys.Input.hash;
return kb.keys.Input.@"3";
},
.number_key4 => {
if (alt) return kb.keys.Input.dollar_sign;
if (shift) return kb.keys.Input.currency_sign;
return kb.keys.Input.@"4";
},
.number_key5 => {
if (alt) return kb.keys.Input.euro_sign;
if (shift) return kb.keys.Input.percent;
return kb.keys.Input.@"5";
},
.number_key6 => {
if (alt) return kb.keys.Input.yen_sign;
if (shift) return kb.keys.Input.ampersand;
return kb.keys.Input.@"6";
},
.number_key7 => {
if (alt) return kb.keys.Input.open_curly_brace;
if (shift) return kb.keys.Input.forward_slash;
return kb.keys.Input.@"7";
},
.number_key8 => {
if (alt) return kb.keys.Input.open_sq_bracket;
if (shift) return kb.keys.Input.open_paren;
return kb.keys.Input.@"8";
},
.number_key9 => {
if (alt) return kb.keys.Input.close_sq_bracket;
if (shift) return kb.keys.Input.close_paren;
return kb.keys.Input.@"9";
},
.number_key0 => {
if (alt) return kb.keys.Input.close_curly_brace;
if (shift) return kb.keys.Input.equals;
return kb.keys.Input.@"0";
},
.right_of0 => {
if (alt) return kb.keys.Input.back_slash;
if (shift) return kb.keys.Input.question_mark;
return kb.keys.Input.plus;
},
.left_of_backspace => {
if (alt) return kb.keys.Input.plusminus;
if (shift) return kb.keys.Input.back_tick;
return kb.keys.Input.acute;
},
.line1_11 => {
if (alt) return kb.keys.Input.umlaut;
return kb.keys.Input.a_with_ring;
},
.line1_12 => {
if (alt) return kb.keys.Input.tilde;
if (shift) return kb.keys.Input.caret;
return kb.keys.Input.umlaut;
},
.line2_10 => {
if (alt) return kb.keys.Input.slashedO;
return kb.keys.Input.o_with_umlaut;
},
.line2_11 => {
if (alt) return kb.keys.Input.ash;
return kb.keys.Input.a_with_umlaut;
},
.line2_12 => {
if (alt) return kb.keys.Input.back_tick;
if (shift) return kb.keys.Input.asterisk;
return kb.keys.Input.apostrophe;
},
.right_of_left_shift => {
if (alt) return kb.keys.Input.vertical_bar;
if (shift) return kb.keys.Input.greater_than;
return kb.keys.Input.less_than;
},
.line3_8 => {
if (shift) return kb.keys.Input.semicolon;
return kb.keys.Input.comma;
},
.line3_9 => {
if (shift) return kb.keys.Input.colon;
return kb.keys.Input.period;
},
.line3_10 => {
if (shift) return kb.keys.Input.underscore;
return kb.keys.Input.minus;
},
else => return queryQwertyFamily(key),
}
}
fn en_US_QWERTY(state: *const kb.state.KeyboardState, key: kb.keys.Location) !kb.keys.Input {
const shift = state.isShiftPressed();
switch (key) {
.left_of1 => {
if (shift) return kb.keys.Input.tilde;
return kb.keys.Input.back_tick;
},
.number_key1 => {
if (shift) return kb.keys.Input.exclamation_mark;
return kb.keys.Input.@"1";
},
.number_key2 => {
if (shift) return kb.keys.Input.at;
return kb.keys.Input.@"2";
},
.number_key3 => {
if (shift) return kb.keys.Input.hash;
return kb.keys.Input.@"3";
},
.number_key4 => {
if (shift) return kb.keys.Input.dollar_sign;
return kb.keys.Input.@"4";
},
.number_key5 => {
if (shift) return kb.keys.Input.percent;
return kb.keys.Input.@"5";
},
.number_key6 => {
if (shift) return kb.keys.Input.caret;
return kb.keys.Input.@"6";
},
.number_key7 => {
if (shift) return kb.keys.Input.ampersand;
return kb.keys.Input.@"7";
},
.number_key8 => {
if (shift) return kb.keys.Input.asterisk;
return kb.keys.Input.@"8";
},
.number_key9 => {
if (shift) return kb.keys.Input.open_paren;
return kb.keys.Input.@"9";
},
.number_key0 => {
if (shift) return kb.keys.Input.close_paren;
return kb.keys.Input.@"0";
},
.right_of0 => {
if (shift) return kb.keys.Input.underscore;
return kb.keys.Input.minus;
},
.left_of_backspace => {
if (shift) return kb.keys.Input.plus;
return kb.keys.Input.equals;
},
.line1_11 => {
if (shift) return kb.keys.Input.open_curly_brace;
return kb.keys.Input.open_sq_bracket;
},
.line1_12 => {
if (shift) return kb.keys.Input.close_curly_brace;
return kb.keys.Input.close_sq_bracket;
},
.line1_13 => {
if (shift) return kb.keys.Input.vertical_bar;
return kb.keys.Input.back_slash;
},
.line2_10 => {
if (shift) return kb.keys.Input.colon;
return kb.keys.Input.semicolon;
},
.line2_11 => {
if (shift) return kb.keys.Input.apostrophe;
return kb.keys.Input.quotation_mark;
},
.line3_8 => {
if (shift) return kb.keys.Input.less_than;
return kb.keys.Input.comma;
},
.line3_9 => {
if (shift) return kb.keys.Input.greater_than;
return kb.keys.Input.period;
},
.line3_10 => {
if (shift) return kb.keys.Input.question_mark;
return kb.keys.Input.forward_slash;
},
else => return queryQwertyFamily(key),
}
}
pub fn getInput(
state: *const kb.state.KeyboardState,
key: kb.keys.Location,
layout: KeyboardLayout,
) !kb.keys.Input {
return switch (layout) {
.en_US_QWERTY => return en_US_QWERTY(state, key),
.sv_SE_QWERTY => return sv_SE_QWERTY(state, key),
};
} | lib/input/keyboard/layouts.zig |
const std = @import("std");
const Channel = @import("../utils/channel.zig").Channel;
const url = @import("../utils/url.zig");
const GlobalEventUnion = @import("../main.zig").Event;
const Chat = @import("../Chat.zig");
const BorkConfig = @import("../main.zig").BorkConfig;
const Network = @import("../Network.zig");
const parseTime = @import("./utils.zig").parseTime;
pub const Event = union(enum) {
quit,
reconnect,
links: std.net.StreamServer.Connection,
send: []const u8,
afk: struct {
title: []const u8,
target_time: i64,
reason: []const u8,
},
};
address: std.net.Address,
listener: std.net.StreamServer,
config: BorkConfig,
token: []const u8,
alloc: std.mem.Allocator,
ch: *Channel(GlobalEventUnion),
pub fn init(
self: *@This(),
config: BorkConfig,
token: []const u8,
alloc: std.mem.Allocator,
ch: *Channel(GlobalEventUnion),
) !void {
self.config = config;
self.token = token;
self.alloc = alloc;
self.ch = ch;
self.address = try std.net.Address.parseIp("127.0.0.1", config.remote_port);
self.listener = std.net.StreamServer.init(.{
.reuse_address = true,
});
errdefer self.listener.deinit();
// Start listening in a detached coroutine
// TODO: since it's only one, this should just be
// a normal async call, stage2-san save me pepeHands
try self.listener.listen(self.address);
try std.event.Loop.instance.?.runDetached(alloc, listen, .{self});
}
// TODO: concurrency
pub fn deinit(self: *@This()) void {
std.log.debug("deiniting Remote Server", .{});
std.os.shutdown(self.listener.sockfd.?, .both) catch |err| {
std.log.debug("remote shutdown encountered an error: {}", .{err});
};
self.listener.deinit();
std.log.debug("deinit done", .{});
}
fn listen(self: *@This()) void {
while (true) {
const conn = self.listener.accept() catch |err| {
std.log.debug("remote encountered an error: {}", .{err});
continue;
};
// Handle the connection in a detached coroutine
std.event.Loop.instance.?.runDetached(self.alloc, handle, .{ self, conn }) catch |err| {
std.log.debug("remote could not handle a connection: {}", .{err});
};
}
}
fn handle(self: *@This(), conn: std.net.StreamServer.Connection) void {
self.erroring_handle(conn) catch {};
}
fn erroring_handle(self: *@This(), conn: std.net.StreamServer.Connection) !void {
var buf: [100]u8 = undefined;
const cmd = conn.stream.reader().readUntilDelimiter(&buf, '\n') catch |err| {
std.log.debug("remote could read: {}", .{err});
return;
};
defer std.log.debug("remote cmd: {s}", .{cmd});
if (std.mem.eql(u8, cmd, "SEND")) {
const msg = conn.stream.reader().readUntilDelimiterAlloc(self.alloc, '\n', 4096) catch |err| {
std.log.debug("remote could read: {}", .{err});
return;
};
defer self.alloc.free(msg);
std.log.debug("remote msg: {s}", .{msg});
// Since sending the message from the main connection
// makes it so that twitch doesn't echo it back, we're
// opening a one-off connection to send the message.
// This way we don't have to implement locally emote
// parsing.
var twitch_conn = Network.connect(self.alloc, self.config.nick, self.token) catch return;
defer twitch_conn.close();
twitch_conn.writer().print("PRIVMSG #{s} :{s}\n", .{ self.config.nick, msg }) catch return;
}
if (std.mem.eql(u8, cmd, "QUIT")) {
self.ch.put(GlobalEventUnion{ .remote = .quit });
}
if (std.mem.eql(u8, cmd, "RECONNECT")) {
self.ch.put(GlobalEventUnion{ .remote = .reconnect });
}
if (std.mem.eql(u8, cmd, "LINKS")) {
self.ch.put(GlobalEventUnion{ .remote = .{ .links = conn } });
}
if (std.mem.eql(u8, cmd, "BAN")) {
const user = conn.stream.reader().readUntilDelimiterAlloc(self.alloc, '\n', 4096) catch |err| {
std.log.debug("remote could read: {}", .{err});
return;
};
defer self.alloc.free(user);
std.log.debug("remote msg: {s}", .{user});
// Since sending the message from the main connection
// makes it so that twitch doesn't echo it back, we're
// opening a one-off connection to send the message.
// This way we don't have to implement locally emote
// parsing.
var twitch_conn = Network.connect(self.alloc, self.config.nick, self.token) catch return;
defer twitch_conn.close();
twitch_conn.writer().print("PRIVMSG #{s} :/ban {s}\n", .{ self.config.nick, user }) catch return;
}
if (std.mem.eql(u8, cmd, "UNBAN")) {
const user = conn.stream.reader().readUntilDelimiterAlloc(self.alloc, '\n', 4096) catch |err| {
std.log.debug("remote could read: {}", .{err});
return;
};
defer self.alloc.free(user);
std.log.debug("remote msg: {s}", .{user});
// Since sending the message from the main connection
// makes it so that twitch doesn't echo it back, we're
// opening a one-off connection to send the message.
// This way we don't have to implement locally emote
// parsing.
var twitch_conn = Network.connect(self.alloc, self.config.nick, self.token) catch return;
defer twitch_conn.close();
twitch_conn.writer().print("PRIVMSG #{s} :/ban {s}\n", .{ self.config.nick, user }) catch return;
}
if (std.mem.eql(u8, cmd, "AFK")) {
const reader = conn.stream.reader();
const time_string = reader.readUntilDelimiterAlloc(self.alloc, '\n', 4096) catch |err| {
std.log.debug("remote could read: {}", .{err});
return;
};
defer self.alloc.free(time_string);
const parsed_time = parseTime(time_string) catch {
std.log.debug("remote failed to parse time", .{});
return;
};
std.log.debug("parsed_time in seconds: {d}", .{parsed_time});
const target_time = std.time.timestamp() + parsed_time;
const reason = reader.readUntilDelimiterAlloc(self.alloc, '\n', 4096) catch |err| {
std.log.debug("remote could read: {}", .{err});
return;
};
errdefer self.alloc.free(reason);
for (reason) |c| switch (c) {
else => {},
'\n', '\r', '\t' => return error.BadReason,
};
const title = reader.readUntilDelimiterAlloc(self.alloc, '\n', 4096) catch |err| {
std.log.debug("remote could read: {}", .{err});
return;
};
errdefer self.alloc.free(title);
for (title) |c| switch (c) {
else => {},
'\n', '\r', '\t' => return error.BadReason,
};
self.ch.put(GlobalEventUnion{
.remote = .{
.afk = .{
.target_time = target_time,
.reason = reason,
.title = title,
},
},
});
}
}
// NOTE: this function should only be called by
// the thread that's also running the main control
// loop
pub fn replyLinks(chat: *Chat, conn: std.net.StreamServer.Connection) void {
var maybe_current = chat.last_link_message;
while (maybe_current) |c| : (maybe_current = c.prev_links) {
const text = switch (c.kind) {
.chat => |comment| comment.text,
else => continue,
};
var it = std.mem.tokenize(u8, text, " ");
while (it.next()) |word| {
if (url.sense(word)) {
const indent = " >>";
conn.stream.writer().print("{s} [{s}]\n{s} {s}\n\n", .{
c.time,
c.login_name,
indent,
url.clean(word),
}) catch return;
}
}
}
conn.stream.close();
} | src/remote/Server.zig |
const std = @import("std");
const Token = struct {
kind: enum {
nil,
comment,
section,
identifier,
value,
},
value: ?[]const u8,
};
const TokenizerState = enum(u3) {
nil,
comment,
section,
identifier,
value,
string,
};
const booleanMap = std.ComptimeStringMap(bool, .{
.{ "1", true },
.{ "enabled", true },
.{ "Enabled", true },
.{ "on", true },
.{ "On", true },
.{ "true", true },
.{ "t", true },
.{ "True", true },
.{ "T", true },
.{ "yes", true },
.{ "y", true },
.{ "Yes", true },
.{ "Y", true },
.{ "0", false },
.{ "disabled", false },
.{ "Disabled", false },
.{ "off", false },
.{ "Off", false },
.{ "false", false },
.{ "f", false },
.{ "False", false },
.{ "F", false },
.{ "no", false },
.{ "n", false },
.{ "No", false },
.{ "N", false },
});
pub fn parse(comptime T: type, data: []const u8) !T {
var seek: usize = 0;
var state = TokenizerState.nil;
var val = std.mem.zeroes(T);
var csec: []const u8 = undefined;
var cid: []const u8 = undefined;
while (consume(data[0..], &seek, &state)) |token| {
switch (token.kind) {
.nil, .comment => {},
.section => csec = token.value.?,
.identifier => {
cid = token.value.?;
const tk = consume(data[0..], &seek, &state).?;
if (tk.kind != .value)
return error.IniSyntaxError;
const info1 = @typeInfo(T);
if (info1 != .Struct)
@compileError("Invalid Archetype");
inline for (info1.Struct.fields) |f| {
if (std.mem.eql(u8, f.name, csec)) {
const info2 = @typeInfo(@TypeOf(@field(val, f.name)));
if (info2 != .Struct)
@compileError("Naked field in archetype");
inline for (info2.Struct.fields) |ff| {
if (std.mem.eql(u8, ff.name, cid)) {
const TT = ff.field_type;
@field(@field(val, f.name), ff.name) = coerce(TT, tk.value.?) catch unreachable; // error.IniInvalidCoerce;
}
}
}
}
},
else => return error.IniSyntaxError,
}
}
return val;
}
fn coerce(comptime T: type, v: []const u8) !T {
return switch (@typeInfo(T)) {
.Bool => booleanMap.get(v).?,
.Float, .ComptimeFloat => try std.fmt.parseFloat(T, v),
.Int, .ComptimeInt => try std.fmt.parseInt(T, v, 10),
else => @as(T, v),
};
}
const IniMap = std.StringHashMap([]const u8);
pub const IniResult = struct {
map: IniMap,
allocator: *std.mem.Allocator,
pub fn deinit(self: *IniResult) void {
defer self.map.deinit();
var iter = self.map.iterator();
while (iter.next()) |i|
self.allocator.free(i.key_ptr.*);
}
};
pub fn parseIntoMap(data: []const u8, allocator: *std.mem.Allocator) !IniResult {
var seek: usize = 0;
var state = TokenizerState.nil;
var csec: []const u8 = undefined;
var cid: []const u8 = undefined;
var map = IniMap.init(allocator);
while (consume(data[0..], &seek, &state)) |token| {
switch (token.kind) {
.nil, .comment => {},
.section => csec = token.value.?,
.identifier => {
cid = token.value.?;
var tk = consume(data[0..], &seek, &state).?;
if (tk.kind != .value)
return error.IniSyntaxError;
var coc = try std.fmt.allocPrint(allocator, "{s}.{s}", .{ csec, cid });
try map.putNoClobber(coc, tk.value.?);
},
else => return error.IniSyntaxError,
}
}
return IniResult{ .map = map, .allocator = allocator };
}
fn consume(data: []const u8, seek: *usize, state: *TokenizerState) ?Token {
if (seek.* >= data.len) return null;
var token: Token = std.mem.zeroes(Token);
var start = seek.*;
var end = start;
var char: u8 = 0;
@setEvalBranchQuota(100000);
while (char != '\n') {
char = data[seek.*];
seek.* += 1;
switch (state.*) {
.nil => {
switch (char) {
';', '#' => {
state.* = .comment;
start = seek.*;
if (std.ascii.isSpace(data[start])) start += 1;
end = start;
},
'[' => {
state.* = .section;
start = seek.*;
end = start;
},
'=' => {
state.* = .value;
start = seek.*;
if (std.ascii.isSpace(data[start])) start += 1;
end = start;
},
else => {
if (!std.ascii.isSpace(char)) {
state.* = .identifier;
start = start;
end = start;
} else {
start += 1;
end += 1;
}
},
}
},
.identifier => {
end += 1;
if (!(std.ascii.isAlNum(char) or char == '_')) {
state.* = .nil;
return Token{
.kind = .identifier,
.value = data[start..end],
};
}
},
.comment => {
end += 1;
switch (char) {
'\n' => {
state.* = .nil;
return Token{
.kind = .comment,
.value = data[start .. end - 2],
};
},
else => {},
}
},
.section => {
end += 1;
switch (char) {
']' => {
state.* = .nil;
return Token{
.kind = .section,
.value = data[start .. end - 1],
};
},
else => {},
}
},
.value => {
switch (char) {
';', '#' => {
state.* = .comment;
return Token{
.kind = .value,
.value = data[start .. end - 2],
};
},
else => {
end += 1;
switch (char) {
'\n' => {
state.* = .nil;
return Token{
.kind = .value,
.value = data[start .. end - 2],
};
},
else => {},
}
},
}
},
else => {},
}
}
return token;
}
test "parse into map" {
var file = try std.fs.cwd().openFile("src/test.ini", .{ .read = true, .write = false });
defer file.close();
var data = try std.testing.allocator.alloc(u8, try file.getEndPos());
defer std.testing.allocator.free(data);
_ = try file.read(data);
var ini = try parseIntoMap(data, std.testing.allocator);
defer ini.deinit();
try std.testing.expectEqualStrings("<NAME>", ini.map.get("owner.name").?);
try std.testing.expectEqualStrings("Acme Widgets Inc.", ini.map.get("owner.organization").?);
try std.testing.expectEqualStrings("192.0.2.62", ini.map.get("database.server").?);
try std.testing.expectEqualStrings("143", ini.map.get("database.port").?);
try std.testing.expectEqualStrings("payroll.dat", ini.map.get("database.file").?);
try std.testing.expectEqualStrings("yes", ini.map.get("database.use").?);
try std.testing.expectEqualStrings("bar", ini.map.get("withtabs.foo").?);
}
test "parse into struct" {
var file = try std.fs.cwd().openFile("src/test.ini", .{ .read = true, .write = false });
defer file.close();
var data = try std.testing.allocator.alloc(u8, try file.getEndPos());
defer std.testing.allocator.free(data);
_ = try file.read(data);
const Config = struct {
owner: struct {
name: []const u8,
organization: []const u8,
},
database: struct {
server: []const u8,
port: usize,
file: []const u8,
use: bool,
},
};
var config = try parse(Config, data);
try std.testing.expectEqualStrings("<NAME>", config.owner.name);
try std.testing.expectEqualStrings("Acme Widgets Inc.", config.owner.organization);
try std.testing.expectEqualStrings("192.0.2.62", config.database.server);
try std.testing.expectEqual(@as(usize, 143), config.database.port);
try std.testing.expectEqualStrings("payroll.dat", config.database.file);
try std.testing.expectEqual(true, config.database.use);
}
test "parse in comptime into struct" {
const config = comptime block: {
const data = @embedFile("test.ini");
const Config = struct {
owner: struct {
name: []const u8,
organization: []const u8,
},
database: struct {
server: []const u8,
port: usize,
file: []const u8,
use: bool,
},
};
var config = try parse(Config, data);
break :block config;
};
try std.testing.expectEqualStrings("<NAME>", config.owner.name);
try std.testing.expectEqualStrings("Acme Widgets Inc.", config.owner.organization);
try std.testing.expectEqualStrings("192.0.2.62", config.database.server);
try std.testing.expectEqual(@as(usize, 143), config.database.port);
try std.testing.expectEqualStrings("payroll.dat", config.database.file);
try std.testing.expectEqual(true, config.database.use);
} | src/ini.zig |
const std = @import("../std.zig");
const builtin = std.builtin;
const mem = std.mem;
pub fn Writer(
comptime Context: type,
comptime WriteError: type,
comptime writeFn: fn (context: Context, bytes: []const u8) WriteError!usize,
) type {
return struct {
context: Context,
const Self = @This();
pub const Error = WriteError;
pub fn write(self: Self, bytes: []const u8) Error!usize {
return writeFn(self.context, bytes);
}
pub fn writeAll(self: Self, bytes: []const u8) Error!void {
var index: usize = 0;
while (index != bytes.len) {
index += try self.write(bytes[index..]);
}
}
pub fn print(self: Self, comptime format: []const u8, args: var) Error!void {
return std.fmt.format(self, format, args);
}
pub fn writeByte(self: Self, byte: u8) Error!void {
const array = [1]u8{byte};
return self.writeAll(&array);
}
pub fn writeByteNTimes(self: Self, byte: u8, n: usize) Error!void {
var bytes: [256]u8 = undefined;
mem.set(u8, bytes[0..], byte);
var remaining: usize = n;
while (remaining > 0) {
const to_write = std.math.min(remaining, bytes.len);
try self.writeAll(bytes[0..to_write]);
remaining -= to_write;
}
}
/// Write a native-endian integer.
/// TODO audit non-power-of-two int sizes
pub fn writeIntNative(self: Self, comptime T: type, value: T) Error!void {
var bytes: [(T.bit_count + 7) / 8]u8 = undefined;
mem.writeIntNative(T, &bytes, value);
return self.writeAll(&bytes);
}
/// Write a foreign-endian integer.
/// TODO audit non-power-of-two int sizes
pub fn writeIntForeign(self: Self, comptime T: type, value: T) Error!void {
var bytes: [(T.bit_count + 7) / 8]u8 = undefined;
mem.writeIntForeign(T, &bytes, value);
return self.writeAll(&bytes);
}
/// TODO audit non-power-of-two int sizes
pub fn writeIntLittle(self: Self, comptime T: type, value: T) Error!void {
var bytes: [(T.bit_count + 7) / 8]u8 = undefined;
mem.writeIntLittle(T, &bytes, value);
return self.writeAll(&bytes);
}
/// TODO audit non-power-of-two int sizes
pub fn writeIntBig(self: Self, comptime T: type, value: T) Error!void {
var bytes: [(T.bit_count + 7) / 8]u8 = undefined;
mem.writeIntBig(T, &bytes, value);
return self.writeAll(&bytes);
}
/// TODO audit non-power-of-two int sizes
pub fn writeInt(self: Self, comptime T: type, value: T, endian: builtin.Endian) Error!void {
var bytes: [(T.bit_count + 7) / 8]u8 = undefined;
mem.writeInt(T, &bytes, value, endian);
return self.writeAll(&bytes);
}
};
} | lib/std/io/writer.zig |
Subsets and Splits