code
stringlengths 38
801k
| repo_path
stringlengths 6
263
|
---|---|
const std = @import("std");
const print = std.debug.print;
const net = std.net;
const os = std.os;
const heap = std.heap;
pub fn main() !void {
print("Configuring local address...\n", .{});
const localhost = try net.Address.parseIp4("127.0.0.1", 8080);
print("Creating socket...\n", .{});
const sock_listen = try os.socket(os.AF_INET, os.SOCK_STREAM, os.IPPROTO_TCP);
print("Binding socket to local address...\n", .{});
var sock_len = localhost.getOsSockLen();
try os.bind(sock_listen, &localhost.any, sock_len);
print("Listening...\n", .{});
try os.listen(sock_listen, 10);
var gpa = heap.GeneralPurposeAllocator(.{}){};
defer {
_ = gpa.deinit();
}
var pfds = try gpa.allocator.alloc(os.pollfd, 200);
defer gpa.allocator.free(pfds);
pfds[0].fd = sock_listen;
pfds[0].events = os.POLLIN;
var nfds: u8 = 1;
const timeout = 3 * 60 * 1000;
print("Waiting for connections...\n", .{});
while (true) {
_ = os.poll(pfds, timeout) catch 0;
var current_size = nfds;
var i: u8 = 0;
while (i < current_size) : (i += 1) {
if (pfds[i].revents == 0) continue;
if ((pfds[i].revents & os.POLLIN) == os.POLLIN) {
if (pfds[i].fd == sock_listen) {
// new incoming connection
var accepted_addr: net.Address = undefined;
var addr_len: os.socklen_t = @sizeOf(net.Address);
var sock_client = try os.accept(sock_listen, &accepted_addr.any, &addr_len, os.SOCK_CLOEXEC);
pfds[nfds].fd = sock_client;
pfds[nfds].events = os.POLLIN;
nfds += 1;
print("New connection from {}\n", .{accepted_addr});
} else {
var read: [4096]u8 = undefined;
const bytes_received = try os.recv(pfds[i].fd, read[0..], 0);
if (bytes_received < 1) {
os.close(pfds[i].fd);
pfds[i].fd = -1;
continue;
}
var j: u8 = 0;
while (j < nfds) : (j += 1) {
if (j != i and j != 0) {
_ = try os.send(pfds[j].fd, read[0..bytes_received], 0);
}
}
}
}
}
}
print("Closing sockets...\n", .{});
var i: u8 = 0;
while (i < nfds) : (i += 1) {
if (pfds[i].fd >= 0)
os.close(pfds[i].fd);
}
print("Finished.\n", .{});
return 0;
} | chap03/tcp_serve_chat.zig |
const std = @import("std");
const builtin = @import("builtin");
const TestContext = @import("../src/test.zig").TestContext;
pub fn addCases(ctx: *TestContext) !void {
{
const case = ctx.obj("wrong same named struct", .{});
case.backend = .stage1;
case.addSourceFile("a.zig",
\\pub const Foo = struct {
\\ x: i32,
\\};
);
case.addSourceFile("b.zig",
\\pub const Foo = struct {
\\ z: f64,
\\};
);
case.addError(
\\const a = @import("a.zig");
\\const b = @import("b.zig");
\\
\\export fn entry() void {
\\ var a1: a.Foo = undefined;
\\ bar(&a1);
\\}
\\
\\fn bar(x: *b.Foo) void {_ = x;}
, &[_][]const u8{
"tmp.zig:6:10: error: expected type '*b.Foo', found '*a.Foo'",
"tmp.zig:6:10: note: pointer type child 'a.Foo' cannot cast into pointer type child 'b.Foo'",
"a.zig:1:17: note: a.Foo declared here",
"b.zig:1:17: note: b.Foo declared here",
});
}
{
const case = ctx.obj("multiple files with private function error", .{});
case.backend = .stage1;
case.addSourceFile("foo.zig",
\\fn privateFunction() void { }
);
case.addError(
\\const foo = @import("foo.zig",);
\\
\\export fn callPrivFunction() void {
\\ foo.privateFunction();
\\}
, &[_][]const u8{
"tmp.zig:4:8: error: 'privateFunction' is private",
"foo.zig:1:1: note: declared here",
});
}
{
const case = ctx.obj("multiple files with private member instance function (canonical invocation) error", .{});
case.backend = .stage1;
case.addSourceFile("foo.zig",
\\pub const Foo = struct {
\\ fn privateFunction(self: *Foo) void { _ = self; }
\\};
);
case.addError(
\\const Foo = @import("foo.zig",).Foo;
\\
\\export fn callPrivFunction() void {
\\ var foo = Foo{};
\\ Foo.privateFunction(foo);
\\}
, &[_][]const u8{
"tmp.zig:5:8: error: 'privateFunction' is private",
"foo.zig:2:5: note: declared here",
});
}
{
const case = ctx.obj("multiple files with private member instance function error", .{});
case.backend = .stage1;
case.addSourceFile("foo.zig",
\\pub const Foo = struct {
\\ fn privateFunction(self: *Foo) void { _ = self; }
\\};
);
case.addError(
\\const Foo = @import("foo.zig",).Foo;
\\
\\export fn callPrivFunction() void {
\\ var foo = Foo{};
\\ foo.privateFunction();
\\}
, &[_][]const u8{
"tmp.zig:5:8: error: 'privateFunction' is private",
"foo.zig:2:5: note: declared here",
});
}
{
const case = ctx.obj("export collision", .{});
case.backend = .stage1;
case.addSourceFile("foo.zig",
\\export fn bar() void {}
\\pub const baz = 1234;
);
case.addError(
\\const foo = @import("foo.zig",);
\\
\\export fn bar() usize {
\\ return foo.baz;
\\}
, &[_][]const u8{
"foo.zig:1:1: error: exported symbol collision: 'bar'",
"tmp.zig:3:1: note: other symbol here",
});
}
ctx.objErrStage1("non-printable invalid character", "\xff\xfe" ++
"fn foo() bool {\r\n" ++
" return true;\r\n" ++
"}\r\n", &[_][]const u8{
"tmp.zig:1:1: error: expected test, comptime, var decl, or container field, found 'invalid bytes'",
"tmp.zig:1:1: note: invalid byte: '\\xff'",
});
ctx.objErrStage1("non-printable invalid character with escape alternative", "fn foo() bool {\n" ++
"\treturn true;\n" ++
"}\n", &[_][]const u8{
"tmp.zig:2:1: error: invalid character: '\\t'",
});
// TODO test this in stage2, but we won't even try in stage1
//ctx.objErrStage1("inline fn calls itself indirectly",
// \\export fn foo() void {
// \\ bar();
// \\}
// \\fn bar() callconv(.Inline) void {
// \\ baz();
// \\ quux();
// \\}
// \\fn baz() callconv(.Inline) void {
// \\ bar();
// \\ quux();
// \\}
// \\extern fn quux() void;
//, &[_][]const u8{
// "tmp.zig:4:1: error: unable to inline function",
//});
//ctx.objErrStage1("save reference to inline function",
// \\export fn foo() void {
// \\ quux(@ptrToInt(bar));
// \\}
// \\fn bar() callconv(.Inline) void { }
// \\extern fn quux(usize) void;
//, &[_][]const u8{
// "tmp.zig:4:1: error: unable to inline function",
//});
} | test/compile_errors.zig |
const builtin = @import("builtin");
const std = @import("std");
const assert = std.debug.assert;
const Atomic = std.atomic.Atomic;
const ThreadPool = @This();
stack_size: u32,
max_threads: u16,
queue: Node.Queue = .{},
join_event: Event = .{},
idle_event: Event = .{},
sync: Atomic(u32) = Atomic(u32).init(0),
threads: Atomic(?*Thread) = Atomic(?*Thread).init(null),
const Sync = packed struct {
idle: u10 = 0,
spawned: u10 = 0,
stealing: u10 = 0,
padding: u1 = 0,
shutdown: bool = false,
};
pub const Config = struct {
max_threads: u16,
stack_size: u32 = (std.Thread.SpawnConfig{}).stack_size,
};
pub fn init(config: Config) ThreadPool {
return .{
.max_threads = std.math.max(1, config.max_threads),
.stack_size = std.math.max(std.mem.page_size, config.stack_size),
};
}
pub fn deinit(self: *ThreadPool) void {
self.join();
self.* = undefined;
}
/// A Task represents the unit of Work / Job / Execution that the ThreadPool schedules.
/// The user provides a `callback` which is invoked when the *Task can run on a thread.
pub const Task = struct {
node: Node = .{},
callback: fn (*Task) void,
};
/// An unordered collection of Tasks which can be submitted for scheduling as a group.
pub const Batch = struct {
len: usize = 0,
head: ?*Task = null,
tail: ?*Task = null,
/// Create a batch from a single task.
pub fn from(task: *Task) Batch {
return Batch{
.len = 1,
.head = task,
.tail = task,
};
}
/// Another batch into this one, taking ownership of its tasks.
pub fn push(self: *Batch, batch: Batch) void {
if (batch.len == 0) return;
if (self.len == 0) {
self.* = batch;
} else {
self.tail.?.node.next = if (batch.head) |h| &h.node else null;
self.tail = batch.tail;
self.len += batch.len;
}
}
};
/// Schedule a batch of tasks to be executed by some thread on the thread pool.
pub noinline fn schedule(self: *ThreadPool, batch: Batch) void {
// Sanity check
if (batch.len == 0) {
return;
}
// Extract out the Node's from the Tasks
var list = Node.List{
.head = &batch.head.?.node,
.tail = &batch.tail.?.node,
};
// Push the task Nodes to the most approriate queue
if (Thread.current) |thread| {
thread.buffer.push(&list) catch thread.queue.push(list);
} else {
self.queue.push(list);
}
const sync = @bitCast(Sync, self.sync.load(.Monotonic));
if (sync.shutdown) return;
if (sync.stealing > 0) return;
if (sync.idle == 0 and sync.spawned == self.max_threads) return;
return self.notify();
}
noinline fn notify(self: *ThreadPool) void {
var sync = @bitCast(Sync, self.sync.load(.Monotonic));
while (true) {
if (sync.shutdown) return;
if (sync.stealing != 0) return;
var new_sync = sync;
new_sync.stealing = 1;
if (sync.idle > 0) {
// the thread will decrement idle on its own
} else if (sync.spawned < self.max_threads) {
new_sync.spawned += 1;
} else {
return;
}
sync = @bitCast(Sync, self.sync.tryCompareAndSwap(
@bitCast(u32, sync),
@bitCast(u32, new_sync),
.SeqCst,
.Monotonic,
) orelse {
if (sync.idle > 0)
return self.idle_event.notify();
assert(sync.spawned < self.max_threads);
const spawn_config = std.Thread.SpawnConfig{ .stack_size = self.stack_size };
const thread = std.Thread.spawn(spawn_config, Thread.run, .{self}) catch @panic("failed to spawn a thread");
thread.detach();
return;
});
}
}
/// Marks the thread pool as shutdown
pub noinline fn shutdown(self: *ThreadPool) void {
var sync = @bitCast(Sync, self.sync.load(.Monotonic));
while (!sync.shutdown) {
var new_sync = sync;
new_sync.shutdown = true;
sync = @bitCast(Sync, self.sync.tryCompareAndSwap(
@bitCast(u32, sync),
@bitCast(u32, new_sync),
.SeqCst,
.Monotonic,
) orelse {
self.idle_event.shutdown();
return;
});
}
}
noinline fn register(self: *ThreadPool, thread: *Thread) void {
var threads = self.threads.load(.Monotonic);
while (true) {
thread.next = threads;
threads = self.threads.tryCompareAndSwap(
threads,
thread,
.Release,
.Monotonic,
) orelse break;
}
}
noinline fn unregister(self: *ThreadPool, thread: *Thread) void {
const one_spawned = @bitCast(u32, Sync{ .spawned = 1 });
const sync = @bitCast(Sync, self.sync.fetchSub(one_spawned, .SeqCst));
assert(sync.spawned > 0);
if (sync.spawned == 1) {
self.join_event.notify();
}
thread.join_event.wait();
if (thread.next) |next| {
next.join_event.notify();
}
}
noinline fn join(self: *ThreadPool) void {
self.join_event.wait();
if (self.threads.load(.Acquire)) |thread| {
thread.join_event.notify();
}
}
const Thread = struct {
pool: *ThreadPool,
next: ?*Thread = null,
stealing: bool = true,
target: ?*Thread = null,
join_event: Event = .{},
buffer: Node.Buffer = .{},
queue: Node.Queue = .{},
threadlocal var current: ?*Thread = null;
fn run(thread_pool: *ThreadPool) void {
var self = Thread{ .pool = thread_pool };
current = &self;
self.pool.register(&self);
defer self.pool.unregister(&self);
while (true) {
const node = self.poll() catch break;
const task = @fieldParentPtr(Task, "node", node);
(task.callback)(task);
}
}
fn poll(self: *Thread) error{Shutdown}!*Node {
defer if (self.stealing) {
const one_stealing = @bitCast(u32, Sync{ .stealing = 1 });
const sync = @bitCast(Sync, self.pool.sync.fetchSub(one_stealing, .SeqCst));
// assert(sync.stealing > 0);
if (sync.stealing == 0) {
std.debug.print("{} resetspinning(): {}\n", .{std.Thread.getCurrentId(), sync});
unreachable;
}
self.stealing = false;
self.pool.notify();
};
if (self.buffer.pop()) |node|
return node;
while (true) {
if (self.buffer.consume(&self.queue)) |result|
return result.node;
if (self.buffer.consume(&self.pool.queue)) |result|
return result.node;
if (!self.stealing) blk: {
var sync = @bitCast(Sync, self.pool.sync.load(.Monotonic));
if ((@as(u32, sync.stealing) * 2) >= (sync.spawned - sync.idle))
break :blk;
const one_stealing = @bitCast(u32, Sync{ .stealing = 1 });
sync = @bitCast(Sync, self.pool.sync.fetchAdd(one_stealing, .SeqCst));
assert(sync.stealing < sync.spawned);
self.stealing = true;
}
if (self.stealing) {
var attempts: u8 = 4;
while (attempts > 0) : (attempts -= 1) {
var num_threads: u16 = @bitCast(Sync, self.pool.sync.load(.Monotonic)).spawned;
while (num_threads > 0) : (num_threads -= 1) {
const thread = self.target orelse self.pool.threads.load(.Acquire) orelse unreachable;
self.target = thread.next;
if (self.buffer.consume(&thread.queue)) |result|
return result.node;
if (self.buffer.steal(&thread.buffer)) |result|
return result.node;
}
}
}
if (self.buffer.consume(&self.pool.queue)) |result|
return result.node;
var update = @bitCast(u32, Sync{ .idle = 1 });
if (self.stealing) {
update -%= @bitCast(u32, Sync{ .stealing = 1 });
}
var sync = @bitCast(Sync, self.pool.sync.fetchAdd(update, .SeqCst));
//std.debug.print("\nwait {}({}):{}\n\t\t{}\n", .{std.Thread.getCurrentId(), self.stealing, sync, @bitCast(Sync, @bitCast(u32, sync) +% update)});
assert(sync.idle < sync.spawned);
if (self.stealing) assert(sync.stealing <= sync.spawned);
self.stealing = false;
update = @bitCast(u32, Sync{ .idle = 1 });
if (self.canSteal()) {
update -%= @bitCast(u32, Sync{ .stealing = 1 });
self.stealing = true;
} else {
self.pool.idle_event.wait();
}
sync = @bitCast(Sync, self.pool.sync.fetchSub(update, .SeqCst));
//std.debug.print("\nwake {}({}):{}\n\t\t{}\n", .{std.Thread.getCurrentId(), self.stealing, sync, @bitCast(Sync, @bitCast(u32, sync) -% update)});
assert(sync.idle <= sync.spawned);
if (self.stealing) assert(sync.stealing < sync.spawned);
self.stealing = !sync.shutdown;
if (!self.stealing) return error.Shutdown;
continue;
}
}
fn canSteal(self: *const Thread) bool {
if (self.queue.canSteal())
return true;
if (self.pool.queue.canSteal())
return true;
var num_threads: u16 = @bitCast(Sync, self.pool.sync.load(.Monotonic)).spawned;
var threads: ?*Thread = null;
while (num_threads > 0) : (num_threads -= 1) {
const thread = threads orelse self.pool.threads.load(.Acquire) orelse unreachable;
threads = thread.next;
if (thread.queue.canSteal())
return true;
if (thread.buffer.canSteal())
return true;
}
return false;
}
};
/// Linked list intrusive memory node and lock-free data structures to operate with it
const Node = struct {
next: ?*Node = null,
/// A linked list of Nodes
const List = struct {
head: *Node,
tail: *Node,
};
/// An unbounded multi-producer-(non blocking)-multi-consumer queue of Node pointers.
const Queue = struct {
stack: Atomic(usize) = Atomic(usize).init(0),
cache: ?*Node = null,
const HAS_CACHE: usize = 0b01;
const IS_CONSUMING: usize = 0b10;
const PTR_MASK: usize = ~(HAS_CACHE | IS_CONSUMING);
comptime {
assert(@alignOf(Node) >= ((IS_CONSUMING | HAS_CACHE) + 1));
}
noinline fn push(noalias self: *Queue, list: List) void {
var stack = self.stack.load(.Monotonic);
while (true) {
// Attach the list to the stack (pt. 1)
list.tail.next = @intToPtr(?*Node, stack & PTR_MASK);
// Update the stack with the list (pt. 2).
// Don't change the HAS_CACHE and IS_CONSUMING bits of the consumer.
var new_stack = @ptrToInt(list.head);
assert(new_stack & ~PTR_MASK == 0);
new_stack |= (stack & ~PTR_MASK);
// Push to the stack with a release barrier for the consumer to see the proper list links.
stack = self.stack.tryCompareAndSwap(
stack,
new_stack,
.Release,
.Monotonic,
) orelse break;
}
}
fn canSteal(self: *const Queue) bool {
const stack = self.stack.load(.Monotonic);
if (stack & IS_CONSUMING != 0) return false;
if (stack & (HAS_CACHE | PTR_MASK) == 0) return false;
return true;
}
fn tryAcquireConsumer(self: *Queue) error{Empty, Contended}!?*Node {
var stack = self.stack.load(.Monotonic);
while (true) {
if (stack & IS_CONSUMING != 0)
return error.Contended; // The queue already has a consumer.
if (stack & (HAS_CACHE | PTR_MASK) == 0)
return error.Empty; // The queue is empty when there's nothing cached and nothing in the stack.
// When we acquire the consumer, also consume the pushed stack if the cache is empty.
var new_stack = stack | HAS_CACHE | IS_CONSUMING;
if (stack & HAS_CACHE == 0) {
assert(stack & PTR_MASK != 0);
new_stack &= ~PTR_MASK;
}
// Acquire barrier on getting the consumer to see cache/Node updates done by previous consumers
// and to ensure our cache/Node updates in pop() happen after that of previous consumers.
stack = self.stack.tryCompareAndSwap(
stack,
new_stack,
.Acquire,
.Monotonic,
) orelse return self.cache orelse @intToPtr(*Node, stack & PTR_MASK);
}
}
fn releaseConsumer(noalias self: *Queue, noalias consumer: ?*Node) void {
// Stop consuming and remove the HAS_CACHE bit as well if the consumer's cache is empty.
// When HAS_CACHE bit is zeroed, the next consumer will acquire the pushed stack nodes.
var remove = IS_CONSUMING;
if (consumer == null)
remove |= HAS_CACHE;
// Release the consumer with a release barrier to ensure cache/node accesses
// happen before the consumer was released and before the next consumer starts using the cache.
self.cache = consumer;
const stack = self.stack.fetchSub(remove, .Release);
assert(stack & remove != 0);
}
fn pop(noalias self: *Queue, noalias consumer_ref: *?*Node) ?*Node {
// Check the consumer cache (fast path)
if (consumer_ref.*) |node| {
consumer_ref.* = node.next;
return node;
}
// Load the stack to see if there was anything pushed that we could grab.
var stack = self.stack.load(.Monotonic);
assert(stack & IS_CONSUMING != 0);
if (stack & PTR_MASK == 0) {
return null;
}
// Nodes have been pushed to the stack, grab then with an Acquire barrier to see the Node links.
stack = self.stack.swap(HAS_CACHE | IS_CONSUMING, .Acquire);
assert(stack & IS_CONSUMING != 0);
assert(stack & PTR_MASK != 0);
const node = @intToPtr(*Node, stack & PTR_MASK);
consumer_ref.* = node.next;
return node;
}
};
/// A bounded single-producer, multi-consumer ring buffer for node pointers.
const Buffer = struct {
head: Atomic(Index) = Atomic(Index).init(0),
tail: Atomic(Index) = Atomic(Index).init(0),
array: [capacity]Atomic(*Node) = undefined,
const Index = u32;
const capacity = 256; // Appears to be a pretty good trade-off in space vs contended throughput
comptime {
assert(std.math.maxInt(Index) >= capacity);
assert(std.math.isPowerOfTwo(capacity));
}
noinline fn push(noalias self: *Buffer, noalias list: *List) error{Overflow}!void {
var head = self.head.load(.Monotonic);
var tail = self.tail.loadUnchecked(); // we're the only thread that can change this
while (true) {
var size = tail -% head;
assert(size <= capacity);
// Push nodes from the list to the buffer if it's not empty..
if (size < capacity) {
var nodes: ?*Node = list.head;
while (size < capacity) : (size += 1) {
const node = nodes orelse break;
nodes = node.next;
// Array written atomically with weakest ordering since it could be getting atomically read by steal().
self.array[tail % capacity].store(node, .Unordered);
tail +%= 1;
}
// Release barrier synchronizes with Acquire loads for steal()ers to see the array writes.
self.tail.store(tail, .Release);
// Update the list with the nodes we pushed to the buffer and try again if there's more.
list.head = nodes orelse return;
std.atomic.spinLoopHint();
head = self.head.load(.Monotonic);
continue;
}
// Try to steal/overflow half of the tasks in the buffer to make room for future push()es.
// Migrating half amortizes the cost of stealing while requiring future pops to still use the buffer.
// Acquire barrier to ensure the linked list creation after the steal only happens after we succesfully steal.
var migrate = size / 2;
head = self.head.tryCompareAndSwap(
head,
head +% migrate,
.Acquire,
.Monotonic,
) orelse {
// Link the migrated Nodes together
const first = self.array[head % capacity].loadUnchecked();
while (migrate > 0) : (migrate -= 1) {
const prev = self.array[head % capacity].loadUnchecked();
head +%= 1;
prev.next = self.array[head % capacity].loadUnchecked();
}
// Append the list that was supposed to be pushed to the end of the migrated Nodes
const last = self.array[(head -% 1) % capacity].loadUnchecked();
last.next = list.head;
list.tail.next = null;
// Return the migrated nodes + the original list as overflowed
list.head = first;
return error.Overflow;
};
}
}
fn pop(self: *Buffer) ?*Node {
var head = self.head.load(.Monotonic);
var tail = self.tail.loadUnchecked(); // we're the only thread that can change this
while (true) {
// Quick sanity check and return null when not empty
var size = tail -% head;
assert(size <= capacity);
if (size == 0) {
return null;
}
// On x86, a fetchAdd ("lock xadd") can be faster than a tryCompareAndSwap ("lock cmpxchg").
// If the increment makes the head go past the tail, it means the queue was emptied before we incremented so revert.
// Acquire barrier to ensure that any writes we do to the popped Node only happen after the head increment.
if (comptime builtin.target.cpu.arch.isX86()) {
head = self.head.fetchAdd(1, .Acquire);
if (head == tail) {
self.head.store(head, .Monotonic);
return null;
}
size = tail -% head;
assert(size <= capacity);
return self.array[head % capacity].loadUnchecked();
}
// Dequeue with an acquire barrier to ensure any writes done to the Node
// only happen after we succesfully claim it from the array.
head = self.head.tryCompareAndSwap(
head,
head +% 1,
.Acquire,
.Monotonic,
) orelse return self.array[head % capacity].loadUnchecked();
}
}
const Stole = struct {
node: *Node,
pushed: bool,
};
fn canSteal(self: *const Buffer) bool {
while (true) : (std.atomic.spinLoopHint()) {
const head = self.head.load(.Acquire);
const tail = self.tail.load(.Acquire);
// On x86, the target buffer thread uses fetchAdd to increment the head which can go over if it's zero.
// Account for that here by understanding that it's empty here.
if (comptime builtin.target.cpu.arch.isX86()) {
if (head == tail +% 1) {
return false;
}
}
const size = tail -% head;
if (size > capacity) {
continue;
}
assert(size <= capacity);
return size != 0;
}
}
fn consume(noalias self: *Buffer, noalias queue: *Queue) ?Stole {
var consumer = queue.tryAcquireConsumer() catch return null;
defer queue.releaseConsumer(consumer);
const head = self.head.load(.Monotonic);
const tail = self.tail.loadUnchecked(); // we're the only thread that can change this
const size = tail -% head;
assert(size <= capacity);
assert(size == 0); // we should only be consuming if our array is empty
// Pop nodes from the queue and push them to our array.
// Atomic stores to the array as steal() threads may be atomically reading from it.
var pushed: Index = 0;
while (pushed < capacity) : (pushed += 1) {
const node = queue.pop(&consumer) orelse break;
self.array[(tail +% pushed) % capacity].store(node, .Unordered);
}
// We will be returning one node that we stole from the queue.
// Get an extra, and if that's not possible, take one from our array.
const node = queue.pop(&consumer) orelse blk: {
if (pushed == 0) return null;
pushed -= 1;
break :blk self.array[(tail +% pushed) % capacity].loadUnchecked();
};
// Update the array tail with the nodes we pushed to it.
// Release barrier to synchronize with Acquire barrier in steal()'s to see the written array Nodes.
if (pushed > 0) self.tail.store(tail +% pushed, .Release);
return Stole{
.node = node,
.pushed = pushed > 0,
};
}
fn steal(noalias self: *Buffer, noalias buffer: *Buffer) ?Stole {
const head = self.head.load(.Monotonic);
const tail = self.tail.loadUnchecked(); // we're the only thread that can change this
const size = tail -% head;
assert(size <= capacity);
assert(size == 0); // we should only be stealing if our array is empty
while (true) : (std.atomic.spinLoopHint()) {
const buffer_head = buffer.head.load(.Acquire);
const buffer_tail = buffer.tail.load(.Acquire);
// On x86, the target buffer thread uses fetchAdd to increment the head which can go over if it's zero.
// Account for that here by understanding that it's empty here.
if (comptime builtin.target.cpu.arch.isX86()) {
if (buffer_head == buffer_tail +% 1) {
return null;
}
}
// Overly large size indicates the the tail was updated a lot after the head was loaded.
// Reload both and try again.
const buffer_size = buffer_tail -% buffer_head;
if (buffer_size > capacity) {
continue;
}
// Try to steal half (divCeil) to amortize the cost of stealing from other threads.
const steal_size = buffer_size - (buffer_size / 2);
if (steal_size == 0) {
return null;
}
// Copy the nodes we will steal from the target's array to our own.
// Atomically load from the target buffer array as it may be pushing and atomically storing to it.
// Atomic store to our array as other steal() threads may be atomically loading from it as above.
var i: Index = 0;
while (i < steal_size) : (i += 1) {
const node = buffer.array[(buffer_head +% i) % capacity].load(.Unordered);
self.array[(tail +% i) % capacity].store(node, .Unordered);
}
// Try to commit the steal from the target buffer using:
// - an Acquire barrier to ensure that we only interact with the stolen Nodes after the steal was committed.
// - a Release barrier to ensure that the Nodes are copied above prior to the committing of the steal
// because if they're copied after the steal, the could be getting rewritten by the target's push().
_ = buffer.head.compareAndSwap(
buffer_head,
buffer_head +% steal_size,
.AcqRel,
.Monotonic,
) orelse {
// Pop one from the nodes we stole as we'll be returning it
const pushed = steal_size - 1;
const node = self.array[(tail +% pushed) % capacity].loadUnchecked();
// Update the array tail with the nodes we pushed to it.
// Release barrier to synchronize with Acquire barrier in steal()'s to see the written array Nodes.
if (pushed > 0) self.tail.store(tail +% pushed, .Release);
return Stole{
.node = node,
.pushed = pushed > 0,
};
};
}
}
};
};
/// An event which stores 1 semaphore token and is multi-threaded safe.
/// The event can be shutdown(), waking up all wait()ing threads and
/// making subsequent wait()'s return immediately.
const Event = struct {
state: Atomic(u32) = Atomic(u32).init(EMPTY),
const EMPTY = 0;
const WAITING = 1;
const NOTIFIED = 2;
const SHUTDOWN = 3;
/// Wait for and consume a notification
/// or wait for the event to be shutdown entirely
noinline fn wait(self: *Event) void {
var acquire_with: u32 = EMPTY;
var state = self.state.load(.Monotonic);
while (true) {
// If we're shutdown then exit early.
// Acquire barrier to ensure operations before the shutdown() are seen after the wait().
// Shutdown is rare so it's better to have an Acquire barrier here instead of on CAS failure + load which are common.
if (state == SHUTDOWN) {
std.atomic.fence(.Acquire);
return;
}
// Consume a notification when it pops up.
// Acquire barrier to ensure operations before the notify() appear after the wait().
if (state == NOTIFIED) {
state = self.state.tryCompareAndSwap(
state,
acquire_with,
.Acquire,
.Monotonic,
) orelse return;
continue;
}
// There is no notification to consume, we should wait on the event by ensuring its WAITING.
if (state != WAITING) blk: {
state = self.state.tryCompareAndSwap(
state,
WAITING,
.Monotonic,
.Monotonic,
) orelse break :blk;
continue;
}
// Wait on the event until a notify() or shutdown().
// If we wake up to a notification, we must acquire it with WAITING instead of EMPTY
// since there may be other threads sleeping on the Futex who haven't been woken up yet.
//
// Acquiring to WAITING will make the next notify() or shutdown() wake a sleeping futex thread
// who will either exit on SHUTDOWN or acquire with WAITING again, ensuring all threads are awoken.
// This unfortunately results in the last notify() or shutdown() doing an extra futex wake but that's fine.
std.Thread.Futex.wait(&self.state, WAITING, null) catch unreachable;
state = self.state.load(.Monotonic);
acquire_with = WAITING;
}
}
/// Post a notification to the event if it doesn't have one already
/// then wake up a waiting thread if there is one as well.
fn notify(self: *Event) void {
return self.wake(NOTIFIED, 1);
}
/// Marks the event as shutdown, making all future wait()'s return immediately.
/// Then wakes up any threads currently waiting on the Event.
fn shutdown(self: *Event) void {
return self.wake(SHUTDOWN, std.math.maxInt(u32));
}
noinline fn wake(self: *Event, release_with: u32, wake_threads: u32) void {
// Update the Event to notifty it with the new `release_with` state (either NOTIFIED or SHUTDOWN).
// Release barrier to ensure any operations before this are this to happen before the wait() in the other threads.
const state = self.state.swap(release_with, .Release);
// Only wake threads sleeping in futex if the state is WAITING.
// Avoids unnecessary wake ups.
if (state == WAITING) {
std.Thread.Futex.wake(&self.state, wake_threads);
}
}
}; | src/thread_pool_go_based.zig |
const assert = @import("std").debug.assert;
const RenderTarget = @import("renderer.zig").RenderTarget;
pub const PSFontHeader = packed struct {
magic: u32,
version: u32,
headerSize: u32,
flag: u32,
glyphCount: u32,
bytesPerGlyph: u32,
height: u32,
width: u32,
};
pub const Color = u32;
pub const PSFont = struct {
header: PSFontHeader,
glyphs: []const u8,
pub fn Init(binary: []const u8) PSFont {
var fontHeader = @ptrCast(*const PSFontHeader, binary);
var x = binary[fontHeader.headerSize .. fontHeader.headerSize + fontHeader.glyphCount * fontHeader.bytesPerGlyph];
return PSFont{ .header = fontHeader.*, .glyphs = x };
}
pub fn GetGlyph(self: PSFont, character: u8) []const u8 {
//TODO: Where comes the offset from?
const offset = (character + 2) * self.header.bytesPerGlyph;
return self.glyphs[offset .. offset + self.header.bytesPerGlyph];
}
pub fn Render(self: *const PSFont, target: *RenderTarget, character: u8, color: Color) void {
const glyph = self.GetGlyph(character);
var pixelOffset: u32 = 0;
var mask = @intCast(u8, 1) << @intCast(u3, self.header.width - 1);
while (pixelOffset < self.header.bytesPerGlyph * 8) : (pixelOffset += 1) {
var glyphByte = glyph[pixelOffset / 8];
if (pixelOffset % 8 == 0) {
mask = @intCast(u8, 1) << @intCast(u3, self.header.width - 1);
} else {
mask >>= 1;
}
var maskResult = glyphByte & mask;
//_ = stdout.print("PixelOffset: {}, GlyphByte: {}, MaskResult: {}, Mask: {}\n", .{pixelOffset, glyphByte, maskResult, mask}) catch unreachable;
if (glyphByte & mask > @intCast(u8, 0)) {
target.setPixelAtOffset(pixelOffset, color);
}
}
}
};
pub const DefaultFont = PSFont.Init(DefaultFontFile);
pub const DefaultFontFile = @embedFile("../res/font.psf");
const expect = @import("std").testing.expect;
const stdout = @import("std").io.getStdOut().writer();
test "font loading" {
expect(DefaultFont.header.magic == 0x864ab572);
}
const Renderer = @import("renderer.zig").Renderer;
const Framebuffer = @import("framebuffer.zig");
const Position = @import("framebuffer.zig").Position;
test "font rendering" {
Framebuffer.TestFrameBuffer.reset();
var r = Renderer{ .framebuffer = Framebuffer.TestFrameBuffer };
var target = r.getTarget(Position{ .x = 0, .y = 0 }, 8, 16);
DefaultFont.Render(&target, 'A', 0xFFFFFFFF);
var x: u32 = 0;
var y: u32 = 0;
while (x < 8) : (x += 1) {
while (y < 3) : (y += 1) {
expect(Framebuffer.TestFrameBuffer.getPixel(0, 0) == 0x00000000);
}
}
x = 0;
y = 13;
while (x < 8) : (x += 1) {
while (y < 16) : (y += 1) {
expect(Framebuffer.TestFrameBuffer.getPixel(0, 0) == 0x00000000);
}
}
// expect(Framebuffer.TestFrameBuffer.getPixel(0, 3) == 0x00000000);
// expect(Framebuffer.TestFrameBuffer.getPixel(1, 3) == 0x00000000);
// expect(Framebuffer.TestFrameBuffer.getPixel(2, 3) == 0x00000000);
// expect(Framebuffer.TestFrameBuffer.getPixel(3, 3) == 0xFFFFFFFF);
// expect(Framebuffer.TestFrameBuffer.getPixel(4, 3) == 0x00000000);
// expect(Framebuffer.TestFrameBuffer.getPixel(5, 3) == 0x00000000);
// expect(Framebuffer.TestFrameBuffer.getPixel(6, 3) == 0x00000000);
// expect(Framebuffer.TestFrameBuffer.getPixel(7, 3) == 0x00000000);
} | kernel/psfont.zig |
const xcb = @import("../xcb.zig");
pub const id = xcb.Extension{ .name = "XVideo-MotionCompensation", .global_id = 0 };
pub const CONTEXT = u32;
pub const SURFACE = u32;
pub const SUBPICTURE = u32;
/// @brief SurfaceInfo
pub const SurfaceInfo = struct {
@"id": xcb.xvmc.SURFACE,
@"chroma_format": u16,
@"pad0": u16,
@"max_width": u16,
@"max_height": u16,
@"subpicture_max_width": u16,
@"subpicture_max_height": u16,
@"mc_type": u32,
@"flags": u32,
};
/// @brief QueryVersioncookie
pub const QueryVersioncookie = struct {
sequence: c_uint,
};
/// @brief QueryVersionRequest
pub const QueryVersionRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 0,
@"length": u16,
};
/// @brief QueryVersionReply
pub const QueryVersionReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"major": u32,
@"minor": u32,
};
/// @brief ListSurfaceTypescookie
pub const ListSurfaceTypescookie = struct {
sequence: c_uint,
};
/// @brief ListSurfaceTypesRequest
pub const ListSurfaceTypesRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 1,
@"length": u16,
@"port_id": xcb.xv.PORT,
};
/// @brief ListSurfaceTypesReply
pub const ListSurfaceTypesReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"num": u32,
@"pad1": [20]u8,
@"surfaces": []xcb.xvmc.SurfaceInfo,
};
/// @brief CreateContextcookie
pub const CreateContextcookie = struct {
sequence: c_uint,
};
/// @brief CreateContextRequest
pub const CreateContextRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 2,
@"length": u16,
@"context_id": xcb.xvmc.CONTEXT,
@"port_id": xcb.xv.PORT,
@"surface_id": xcb.xvmc.SURFACE,
@"width": u16,
@"height": u16,
@"flags": u32,
};
/// @brief CreateContextReply
pub const CreateContextReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"width_actual": u16,
@"height_actual": u16,
@"flags_return": u32,
@"pad1": [20]u8,
@"priv_data": []u32,
};
/// @brief DestroyContextRequest
pub const DestroyContextRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 3,
@"length": u16,
@"context_id": xcb.xvmc.CONTEXT,
};
/// @brief CreateSurfacecookie
pub const CreateSurfacecookie = struct {
sequence: c_uint,
};
/// @brief CreateSurfaceRequest
pub const CreateSurfaceRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 4,
@"length": u16,
@"surface_id": xcb.xvmc.SURFACE,
@"context_id": xcb.xvmc.CONTEXT,
};
/// @brief CreateSurfaceReply
pub const CreateSurfaceReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"pad1": [24]u8,
@"priv_data": []u32,
};
/// @brief DestroySurfaceRequest
pub const DestroySurfaceRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 5,
@"length": u16,
@"surface_id": xcb.xvmc.SURFACE,
};
/// @brief CreateSubpicturecookie
pub const CreateSubpicturecookie = struct {
sequence: c_uint,
};
/// @brief CreateSubpictureRequest
pub const CreateSubpictureRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 6,
@"length": u16,
@"subpicture_id": xcb.xvmc.SUBPICTURE,
@"context": xcb.xvmc.CONTEXT,
@"xvimage_id": u32,
@"width": u16,
@"height": u16,
};
/// @brief CreateSubpictureReply
pub const CreateSubpictureReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"width_actual": u16,
@"height_actual": u16,
@"num_palette_entries": u16,
@"entry_bytes": u16,
@"component_order": [4]u8,
@"pad1": [12]u8,
@"priv_data": []u32,
};
/// @brief DestroySubpictureRequest
pub const DestroySubpictureRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 7,
@"length": u16,
@"subpicture_id": xcb.xvmc.SUBPICTURE,
};
/// @brief ListSubpictureTypescookie
pub const ListSubpictureTypescookie = struct {
sequence: c_uint,
};
/// @brief ListSubpictureTypesRequest
pub const ListSubpictureTypesRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 8,
@"length": u16,
@"port_id": xcb.xv.PORT,
@"surface_id": xcb.xvmc.SURFACE,
};
/// @brief ListSubpictureTypesReply
pub const ListSubpictureTypesReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"num": u32,
@"pad1": [20]u8,
@"types": []xcb.xv.ImageFormatInfo,
};
test "" {
@import("std").testing.refAllDecls(@This());
} | src/auto/xvmc.zig |
const xcb = @import("../xcb.zig");
pub const id = xcb.Extension{ .name = "SELinux", .global_id = 0 };
/// @brief QueryVersioncookie
pub const QueryVersioncookie = struct {
sequence: c_uint,
};
/// @brief QueryVersionRequest
pub const QueryVersionRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 0,
@"length": u16,
@"client_major": u8,
@"client_minor": u8,
};
/// @brief QueryVersionReply
pub const QueryVersionReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"server_major": u16,
@"server_minor": u16,
};
/// @brief SetDeviceCreateContextRequest
pub const SetDeviceCreateContextRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 1,
@"length": u16,
@"context_len": u32,
@"context": []const u8,
};
/// @brief GetDeviceCreateContextcookie
pub const GetDeviceCreateContextcookie = struct {
sequence: c_uint,
};
/// @brief GetDeviceCreateContextRequest
pub const GetDeviceCreateContextRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 2,
@"length": u16,
};
/// @brief GetDeviceCreateContextReply
pub const GetDeviceCreateContextReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"context_len": u32,
@"pad1": [20]u8,
@"context": []u8,
};
/// @brief SetDeviceContextRequest
pub const SetDeviceContextRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 3,
@"length": u16,
@"device": u32,
@"context_len": u32,
@"context": []const u8,
};
/// @brief GetDeviceContextcookie
pub const GetDeviceContextcookie = struct {
sequence: c_uint,
};
/// @brief GetDeviceContextRequest
pub const GetDeviceContextRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 4,
@"length": u16,
@"device": u32,
};
/// @brief GetDeviceContextReply
pub const GetDeviceContextReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"context_len": u32,
@"pad1": [20]u8,
@"context": []u8,
};
/// @brief SetWindowCreateContextRequest
pub const SetWindowCreateContextRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 5,
@"length": u16,
@"context_len": u32,
@"context": []const u8,
};
/// @brief GetWindowCreateContextcookie
pub const GetWindowCreateContextcookie = struct {
sequence: c_uint,
};
/// @brief GetWindowCreateContextRequest
pub const GetWindowCreateContextRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 6,
@"length": u16,
};
/// @brief GetWindowCreateContextReply
pub const GetWindowCreateContextReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"context_len": u32,
@"pad1": [20]u8,
@"context": []u8,
};
/// @brief GetWindowContextcookie
pub const GetWindowContextcookie = struct {
sequence: c_uint,
};
/// @brief GetWindowContextRequest
pub const GetWindowContextRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 7,
@"length": u16,
@"window": xcb.WINDOW,
};
/// @brief GetWindowContextReply
pub const GetWindowContextReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"context_len": u32,
@"pad1": [20]u8,
@"context": []u8,
};
/// @brief ListItem
pub const ListItem = struct {
@"name": xcb.ATOM,
@"object_context_len": u32,
@"data_context_len": u32,
@"object_context": []u8,
@"data_context": []u8,
};
/// @brief SetPropertyCreateContextRequest
pub const SetPropertyCreateContextRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 8,
@"length": u16,
@"context_len": u32,
@"context": []const u8,
};
/// @brief GetPropertyCreateContextcookie
pub const GetPropertyCreateContextcookie = struct {
sequence: c_uint,
};
/// @brief GetPropertyCreateContextRequest
pub const GetPropertyCreateContextRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 9,
@"length": u16,
};
/// @brief GetPropertyCreateContextReply
pub const GetPropertyCreateContextReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"context_len": u32,
@"pad1": [20]u8,
@"context": []u8,
};
/// @brief SetPropertyUseContextRequest
pub const SetPropertyUseContextRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 10,
@"length": u16,
@"context_len": u32,
@"context": []const u8,
};
/// @brief GetPropertyUseContextcookie
pub const GetPropertyUseContextcookie = struct {
sequence: c_uint,
};
/// @brief GetPropertyUseContextRequest
pub const GetPropertyUseContextRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 11,
@"length": u16,
};
/// @brief GetPropertyUseContextReply
pub const GetPropertyUseContextReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"context_len": u32,
@"pad1": [20]u8,
@"context": []u8,
};
/// @brief GetPropertyContextcookie
pub const GetPropertyContextcookie = struct {
sequence: c_uint,
};
/// @brief GetPropertyContextRequest
pub const GetPropertyContextRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 12,
@"length": u16,
@"window": xcb.WINDOW,
@"property": xcb.ATOM,
};
/// @brief GetPropertyContextReply
pub const GetPropertyContextReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"context_len": u32,
@"pad1": [20]u8,
@"context": []u8,
};
/// @brief GetPropertyDataContextcookie
pub const GetPropertyDataContextcookie = struct {
sequence: c_uint,
};
/// @brief GetPropertyDataContextRequest
pub const GetPropertyDataContextRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 13,
@"length": u16,
@"window": xcb.WINDOW,
@"property": xcb.ATOM,
};
/// @brief GetPropertyDataContextReply
pub const GetPropertyDataContextReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"context_len": u32,
@"pad1": [20]u8,
@"context": []u8,
};
/// @brief ListPropertiescookie
pub const ListPropertiescookie = struct {
sequence: c_uint,
};
/// @brief ListPropertiesRequest
pub const ListPropertiesRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 14,
@"length": u16,
@"window": xcb.WINDOW,
};
/// @brief ListPropertiesReply
pub const ListPropertiesReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"properties_len": u32,
@"pad1": [20]u8,
@"properties": []xcb.selinux.ListItem,
};
/// @brief SetSelectionCreateContextRequest
pub const SetSelectionCreateContextRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 15,
@"length": u16,
@"context_len": u32,
@"context": []const u8,
};
/// @brief GetSelectionCreateContextcookie
pub const GetSelectionCreateContextcookie = struct {
sequence: c_uint,
};
/// @brief GetSelectionCreateContextRequest
pub const GetSelectionCreateContextRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 16,
@"length": u16,
};
/// @brief GetSelectionCreateContextReply
pub const GetSelectionCreateContextReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"context_len": u32,
@"pad1": [20]u8,
@"context": []u8,
};
/// @brief SetSelectionUseContextRequest
pub const SetSelectionUseContextRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 17,
@"length": u16,
@"context_len": u32,
@"context": []const u8,
};
/// @brief GetSelectionUseContextcookie
pub const GetSelectionUseContextcookie = struct {
sequence: c_uint,
};
/// @brief GetSelectionUseContextRequest
pub const GetSelectionUseContextRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 18,
@"length": u16,
};
/// @brief GetSelectionUseContextReply
pub const GetSelectionUseContextReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"context_len": u32,
@"pad1": [20]u8,
@"context": []u8,
};
/// @brief GetSelectionContextcookie
pub const GetSelectionContextcookie = struct {
sequence: c_uint,
};
/// @brief GetSelectionContextRequest
pub const GetSelectionContextRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 19,
@"length": u16,
@"selection": xcb.ATOM,
};
/// @brief GetSelectionContextReply
pub const GetSelectionContextReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"context_len": u32,
@"pad1": [20]u8,
@"context": []u8,
};
/// @brief GetSelectionDataContextcookie
pub const GetSelectionDataContextcookie = struct {
sequence: c_uint,
};
/// @brief GetSelectionDataContextRequest
pub const GetSelectionDataContextRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 20,
@"length": u16,
@"selection": xcb.ATOM,
};
/// @brief GetSelectionDataContextReply
pub const GetSelectionDataContextReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"context_len": u32,
@"pad1": [20]u8,
@"context": []u8,
};
/// @brief ListSelectionscookie
pub const ListSelectionscookie = struct {
sequence: c_uint,
};
/// @brief ListSelectionsRequest
pub const ListSelectionsRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 21,
@"length": u16,
};
/// @brief ListSelectionsReply
pub const ListSelectionsReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"selections_len": u32,
@"pad1": [20]u8,
@"selections": []xcb.selinux.ListItem,
};
/// @brief GetClientContextcookie
pub const GetClientContextcookie = struct {
sequence: c_uint,
};
/// @brief GetClientContextRequest
pub const GetClientContextRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 22,
@"length": u16,
@"resource": u32,
};
/// @brief GetClientContextReply
pub const GetClientContextReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"context_len": u32,
@"pad1": [20]u8,
@"context": []u8,
};
test "" {
@import("std").testing.refAllDecls(@This());
} | src/auto/xselinux.zig |
const std = @import("std");
const elf = std.elf;
const builtin = @import("builtin");
const assert = std.debug.assert;
const R_AMD64_RELATIVE = 8;
const R_386_RELATIVE = 8;
const R_ARM_RELATIVE = 23;
const R_AARCH64_RELATIVE = 1027;
const R_RISCV_RELATIVE = 3;
const ARCH_RELATIVE_RELOC = switch (builtin.arch) {
.i386 => R_386_RELATIVE,
.x86_64 => R_AMD64_RELATIVE,
.arm => R_ARM_RELATIVE,
.aarch64 => R_AARCH64_RELATIVE,
.riscv64 => R_RISCV_RELATIVE,
else => @compileError("unsupported architecture"),
};
// Just a convoluted (but necessary) way to obtain the address of the _DYNAMIC[]
// vector as PC-relative so that we can use it before any relocation is applied
fn getDynamicSymbol() [*]elf.Dyn {
const addr = switch (builtin.arch) {
.i386 => asm volatile (
\\ .weak _DYNAMIC
\\ .hidden _DYNAMIC
\\ call 1f
\\ 1: pop %[ret]
\\ lea _DYNAMIC-1b(%[ret]), %[ret]
: [ret] "=r" (-> usize)
),
.x86_64 => asm volatile (
\\ .weak _DYNAMIC
\\ .hidden _DYNAMIC
\\ lea _DYNAMIC(%%rip), %[ret]
: [ret] "=r" (-> usize)
),
// Work around the limited offset range of `ldr`
.arm => asm volatile (
\\ .weak _DYNAMIC
\\ .hidden _DYNAMIC
\\ ldr %[ret], 1f
\\ add %[ret], pc
\\ b 2f
\\ 1: .word _DYNAMIC-1b
\\ 2:
: [ret] "=r" (-> usize)
),
// A simple `adr` is not enough as it has a limited offset range
.aarch64 => asm volatile (
\\ .weak _DYNAMIC
\\ .hidden _DYNAMIC
\\ adrp %[ret], _DYNAMIC
\\ add %[ret], %[ret], #:lo12:_DYNAMIC
: [ret] "=r" (-> usize)
),
.riscv64 => asm volatile (
\\ .weak _DYNAMIC
\\ .hidden _DYNAMIC
\\ lla %[ret], _DYNAMIC
: [ret] "=r" (-> usize)
),
else => @compileError("???"),
};
return @intToPtr([*]elf.Dyn, addr);
}
pub fn apply_relocations() void {
@setRuntimeSafety(false);
const dynv = getDynamicSymbol();
const auxv = std.os.linux.elf_aux_maybe.?;
var at_phent: usize = undefined;
var at_phnum: usize = undefined;
var at_phdr: usize = undefined;
var at_hwcap: usize = undefined;
{
var i: usize = 0;
while (auxv[i].a_type != std.elf.AT_NULL) : (i += 1) {
switch (auxv[i].a_type) {
elf.AT_PHENT => at_phent = auxv[i].a_un.a_val,
elf.AT_PHNUM => at_phnum = auxv[i].a_un.a_val,
elf.AT_PHDR => at_phdr = auxv[i].a_un.a_val,
else => continue,
}
}
}
// Sanity check
assert(at_phent == @sizeOf(elf.Phdr));
// Search the TLS section
const phdrs = (@intToPtr([*]elf.Phdr, at_phdr))[0..at_phnum];
const base_addr = blk: {
for (phdrs) |*phdr| {
if (phdr.p_type == elf.PT_DYNAMIC) {
break :blk @ptrToInt(&dynv[0]) - phdr.p_vaddr;
}
}
unreachable;
};
var rel_addr: usize = 0;
var rela_addr: usize = 0;
var rel_size: usize = 0;
var rela_size: usize = 0;
{
var i: usize = 0;
while (dynv[i].d_tag != elf.DT_NULL) : (i += 1) {
switch (dynv[i].d_tag) {
elf.DT_REL => rel_addr = base_addr + dynv[i].d_val,
elf.DT_RELA => rela_addr = base_addr + dynv[i].d_val,
elf.DT_RELSZ => rel_size = dynv[i].d_val,
elf.DT_RELASZ => rela_size = dynv[i].d_val,
else => {},
}
}
}
// Perform the relocations
if (rel_addr != 0) {
const rel = std.mem.bytesAsSlice(elf.Rel, @intToPtr([*]u8, rel_addr)[0..rel_size]);
for (rel) |r| {
if (r.r_type() != ARCH_RELATIVE_RELOC) continue;
@intToPtr(*usize, base_addr + r.r_offset).* += base_addr;
}
}
if (rela_addr != 0) {
const rela = std.mem.bytesAsSlice(elf.Rela, @intToPtr([*]u8, rela_addr)[0..rela_size]);
for (rela) |r| {
if (r.r_type() != ARCH_RELATIVE_RELOC) continue;
@intToPtr(*usize, base_addr + r.r_offset).* += base_addr + @bitCast(usize, r.r_addend);
}
}
} | lib/std/os/linux/start_pie.zig |
const std = @import("std");
const Sdk = @This();
fn sdkRoot() []const u8 {
return std.fs.path.dirname(@src().file) orelse ".";
}
fn assimpRoot() []const u8 {
return sdkRoot() ++ "/vendor/assimp";
}
builder: *std.build.Builder,
pub fn init(b: *std.build.Builder) *Sdk {
const sdk = b.allocator.create(Sdk) catch @panic("out of memory");
sdk.* = Sdk{
.builder = b,
};
return sdk;
}
const UpperCaseFormatter = std.fmt.Formatter(struct {
pub fn format(
string: []const u8,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) @TypeOf(writer).Error!void {
_ = fmt;
_ = options;
var tmp: [256]u8 = undefined;
var i: usize = 0;
while (i < string.len) : (i += tmp.len) {
try writer.writeAll(std.ascii.upperString(&tmp, string[i..std.math.min(string.len, i + tmp.len)]));
}
}
}.format);
fn fmtUpperCase(string: []const u8) UpperCaseFormatter {
return UpperCaseFormatter{ .data = string };
}
const define_name_patches = struct {
pub const Blender = "BLEND";
pub const Unreal = "3D";
};
/// Creates a new LibExeObjStep that will build Assimp. `linkage`
pub fn createLibrary(sdk: *Sdk, linkage: std.build.LibExeObjStep.Linkage, formats: FormatSet) *std.build.LibExeObjStep {
const lib = switch (linkage) {
.static => sdk.builder.addStaticLibrary("assimp", null),
.dynamic => sdk.builder.addSharedLibrary("assimp", null, .unversioned),
};
lib.linkLibC();
lib.linkLibCpp();
for (sdk.getIncludePaths()) |path| {
lib.addIncludeDir(path);
}
lib.addIncludeDir(assimpRoot());
lib.addIncludeDir(assimpRoot() ++ "/contrib");
lib.addIncludeDir(assimpRoot() ++ "/code");
lib.addIncludeDir(assimpRoot() ++ "/contrib/pugixml/src/");
lib.addIncludeDir(assimpRoot() ++ "/contrib/rapidjson/include");
lib.addIncludeDir(assimpRoot() ++ "/contrib/unzip");
lib.addIncludeDir(assimpRoot() ++ "/contrib/zlib");
lib.addIncludeDir(assimpRoot() ++ "/contrib/openddlparser/include");
addSources(lib, &sources.common);
inline for (std.meta.fields(Format)) |fld| {
if (@field(formats, fld.name)) {
addSources(lib, &@field(sources, fld.name));
} else {
var name = fld.name;
if (@hasDecl(define_name_patches, fld.name))
name = @field(define_name_patches, fld.name);
const define_importer = sdk.builder.fmt("ASSIMP_BUILD_NO_{}_IMPORTER", .{fmtUpperCase(name)});
const define_exporter = sdk.builder.fmt("ASSIMP_BUILD_NO_{}_EXPORTER", .{fmtUpperCase(name)});
lib.defineCMacro(define_importer, null);
lib.defineCMacro(define_exporter, null);
}
}
inline for (std.meta.declarations(sources.libraries)) |ext_lib| {
addSources(lib, &@field(sources.libraries, ext_lib.name));
}
return lib;
}
fn addSources(lib: *std.build.LibExeObjStep, file_list: []const []const u8) void {
const flags = [_][]const u8{};
const cflags = flags ++ [_][]const u8{
"-std=c11",
};
const cxxflags = flags ++ [_][]const u8{
"-std=c++11",
};
for (file_list) |src| {
const ext = std.fs.path.extension(src);
if (std.mem.eql(u8, ext, ".c")) {
lib.addCSourceFile(src, &cflags);
} else {
lib.addCSourceFile(src, &cxxflags);
}
}
}
/// Returns the include path for the Assimp library.
pub fn getIncludePaths(sdk: *Sdk) []const []const u8 {
_ = sdk;
const T = struct {
const paths = [_][]const u8{
sdkRoot() ++ "/include",
sdkRoot() ++ "/vendor/assimp/include",
};
};
return &T.paths;
}
/// Adds Assimp to the given `target`, using both `build_mode` and `target` from it.
/// Will link dynamically or statically depending on linkage.
pub fn addTo(sdk: *Sdk, target: *std.build.LibExeObjStep, linkage: std.build.LibExeObjStep.Linkage, formats: FormatSet) void {
const lib = sdk.createLibrary(linkage, formats);
lib.setTarget(target.target);
lib.setBuildMode(target.build_mode);
target.linkLibrary(lib);
for (sdk.getIncludePaths()) |path| {
target.addIncludeDir(path);
}
}
pub const Format = enum {
@"3DS",
@"3MF",
@"AC",
@"AMF",
@"ASE",
@"Assbin",
@"Assjson",
@"Assxml",
@"B3D",
@"Blender",
@"BVH",
@"C4D",
@"COB",
@"Collada",
@"CSM",
@"DXF",
@"FBX",
@"glTF",
@"glTF2",
@"HMP",
@"IFC",
@"Irr",
@"LWO",
@"LWS",
@"M3D",
@"MD2",
@"MD3",
@"MD5",
@"MDC",
@"MDL",
@"MMD",
@"MS3D",
@"NDO",
@"NFF",
@"Obj",
@"OFF",
@"Ogre",
@"OpenGEX",
@"Ply",
@"Q3BSP",
@"Q3D",
@"Raw",
@"SIB",
@"SMD",
@"Step",
@"STEPParser",
@"STL",
@"Terragen",
@"Unreal",
@"X",
@"X3D",
@"XGL",
};
pub const FormatSet = struct {
pub const empty = std.mem.zeroes(FormatSet);
pub const all = blk: {
var set = empty;
inline for (std.meta.fields(FormatSet)) |fld| {
@field(set, fld.name) = true;
}
break :blk set;
};
pub const default = all
// problems with rapidjson
.remove(.glTF)
.remove(.glTF2)
// complex build
.remove(.X3D)
// propietary code:
.remove(.C4D);
pub fn add(set: FormatSet, format: Format) FormatSet {
var copy = set;
inline for (std.meta.fields(FormatSet)) |fld| {
if (std.mem.eql(u8, fld.name, @tagName(format))) {
@field(copy, fld.name) = true;
}
}
return copy;
}
pub fn remove(set: FormatSet, format: Format) FormatSet {
var copy = set;
inline for (std.meta.fields(FormatSet)) |fld| {
if (std.mem.eql(u8, fld.name, @tagName(format))) {
@field(copy, fld.name) = false;
}
}
return copy;
}
@"3DS": bool,
@"3MF": bool,
@"AC": bool,
@"AMF": bool,
@"ASE": bool,
@"Assbin": bool,
@"Assjson": bool,
@"Assxml": bool,
@"B3D": bool,
@"Blender": bool,
@"BVH": bool,
@"C4D": bool,
@"COB": bool,
@"Collada": bool,
@"CSM": bool,
@"DXF": bool,
@"FBX": bool,
@"glTF": bool,
@"glTF2": bool,
@"HMP": bool,
@"IFC": bool,
@"Irr": bool,
@"LWO": bool,
@"LWS": bool,
@"M3D": bool,
@"MD2": bool,
@"MD3": bool,
@"MD5": bool,
@"MDC": bool,
@"MDL": bool,
@"MMD": bool,
@"MS3D": bool,
@"NDO": bool,
@"NFF": bool,
@"Obj": bool,
@"OFF": bool,
@"Ogre": bool,
@"OpenGEX": bool,
@"Ply": bool,
@"Q3BSP": bool,
@"Q3D": bool,
@"Raw": bool,
@"SIB": bool,
@"SMD": bool,
@"Step": bool,
@"STEPParser": bool,
@"STL": bool,
@"Terragen": bool,
@"Unreal": bool,
@"X": bool,
@"X3D": bool,
@"XGL": bool,
};
const sources = struct {
const src_root = assimpRoot() ++ "/code";
const common = [_][]const u8{
src_root ++ "/CApi/AssimpCExport.cpp",
src_root ++ "/CApi/CInterfaceIOWrapper.cpp",
src_root ++ "/Common/AssertHandler.cpp",
src_root ++ "/Common/Assimp.cpp",
src_root ++ "/Common/BaseImporter.cpp",
src_root ++ "/Common/BaseProcess.cpp",
src_root ++ "/Common/Bitmap.cpp",
src_root ++ "/Common/CreateAnimMesh.cpp",
src_root ++ "/Common/DefaultIOStream.cpp",
src_root ++ "/Common/DefaultIOSystem.cpp",
src_root ++ "/Common/DefaultLogger.cpp",
src_root ++ "/Common/Exceptional.cpp",
src_root ++ "/Common/Exporter.cpp",
src_root ++ "/Common/Importer.cpp",
src_root ++ "/Common/ImporterRegistry.cpp",
src_root ++ "/Common/material.cpp",
src_root ++ "/Common/PostStepRegistry.cpp",
src_root ++ "/Common/RemoveComments.cpp",
src_root ++ "/Common/scene.cpp",
src_root ++ "/Common/SceneCombiner.cpp",
src_root ++ "/Common/ScenePreprocessor.cpp",
src_root ++ "/Common/SGSpatialSort.cpp",
src_root ++ "/Common/simd.cpp",
src_root ++ "/Common/SkeletonMeshBuilder.cpp",
src_root ++ "/Common/SpatialSort.cpp",
src_root ++ "/Common/StandardShapes.cpp",
src_root ++ "/Common/Subdivision.cpp",
src_root ++ "/Common/TargetAnimation.cpp",
src_root ++ "/Common/Version.cpp",
src_root ++ "/Common/VertexTriangleAdjacency.cpp",
src_root ++ "/Common/ZipArchiveIOSystem.cpp",
src_root ++ "/Material/MaterialSystem.cpp",
src_root ++ "/Pbrt/PbrtExporter.cpp",
src_root ++ "/PostProcessing/ArmaturePopulate.cpp",
src_root ++ "/PostProcessing/CalcTangentsProcess.cpp",
src_root ++ "/PostProcessing/ComputeUVMappingProcess.cpp",
src_root ++ "/PostProcessing/ConvertToLHProcess.cpp",
src_root ++ "/PostProcessing/DeboneProcess.cpp",
src_root ++ "/PostProcessing/DropFaceNormalsProcess.cpp",
src_root ++ "/PostProcessing/EmbedTexturesProcess.cpp",
src_root ++ "/PostProcessing/FindDegenerates.cpp",
src_root ++ "/PostProcessing/FindInstancesProcess.cpp",
src_root ++ "/PostProcessing/FindInvalidDataProcess.cpp",
src_root ++ "/PostProcessing/FixNormalsStep.cpp",
src_root ++ "/PostProcessing/GenBoundingBoxesProcess.cpp",
src_root ++ "/PostProcessing/GenFaceNormalsProcess.cpp",
src_root ++ "/PostProcessing/GenVertexNormalsProcess.cpp",
src_root ++ "/PostProcessing/ImproveCacheLocality.cpp",
src_root ++ "/PostProcessing/JoinVerticesProcess.cpp",
src_root ++ "/PostProcessing/LimitBoneWeightsProcess.cpp",
src_root ++ "/PostProcessing/MakeVerboseFormat.cpp",
src_root ++ "/PostProcessing/OptimizeGraph.cpp",
src_root ++ "/PostProcessing/OptimizeMeshes.cpp",
src_root ++ "/PostProcessing/PretransformVertices.cpp",
src_root ++ "/PostProcessing/ProcessHelper.cpp",
src_root ++ "/PostProcessing/RemoveRedundantMaterials.cpp",
src_root ++ "/PostProcessing/RemoveVCProcess.cpp",
src_root ++ "/PostProcessing/ScaleProcess.cpp",
src_root ++ "/PostProcessing/SortByPTypeProcess.cpp",
src_root ++ "/PostProcessing/SplitByBoneCountProcess.cpp",
src_root ++ "/PostProcessing/SplitLargeMeshes.cpp",
src_root ++ "/PostProcessing/TextureTransform.cpp",
src_root ++ "/PostProcessing/TriangulateProcess.cpp",
src_root ++ "/PostProcessing/ValidateDataStructure.cpp",
};
const libraries = struct {
const unzip = [_][]const u8{
assimpRoot() ++ "/contrib/unzip/unzip.c",
assimpRoot() ++ "/contrib/unzip/ioapi.c",
assimpRoot() ++ "/contrib/unzip/crypt.c",
};
const zip = [_][]const u8{
assimpRoot() ++ "/contrib/zip/src/zip.c",
};
const zlib = [_][]const u8{
assimpRoot() ++ "/contrib/zlib/inflate.c",
assimpRoot() ++ "/contrib/zlib/infback.c",
assimpRoot() ++ "/contrib/zlib/gzclose.c",
assimpRoot() ++ "/contrib/zlib/gzread.c",
assimpRoot() ++ "/contrib/zlib/inftrees.c",
assimpRoot() ++ "/contrib/zlib/gzwrite.c",
assimpRoot() ++ "/contrib/zlib/compress.c",
assimpRoot() ++ "/contrib/zlib/inffast.c",
assimpRoot() ++ "/contrib/zlib/uncompr.c",
assimpRoot() ++ "/contrib/zlib/gzlib.c",
// assimpRoot() ++ "/contrib/zlib/contrib/testzlib/testzlib.c",
// assimpRoot() ++ "/contrib/zlib/contrib/inflate86/inffas86.c",
// assimpRoot() ++ "/contrib/zlib/contrib/masmx64/inffas8664.c",
// assimpRoot() ++ "/contrib/zlib/contrib/infback9/infback9.c",
// assimpRoot() ++ "/contrib/zlib/contrib/infback9/inftree9.c",
// assimpRoot() ++ "/contrib/zlib/contrib/minizip/miniunz.c",
// assimpRoot() ++ "/contrib/zlib/contrib/minizip/minizip.c",
// assimpRoot() ++ "/contrib/zlib/contrib/minizip/unzip.c",
// assimpRoot() ++ "/contrib/zlib/contrib/minizip/ioapi.c",
// assimpRoot() ++ "/contrib/zlib/contrib/minizip/mztools.c",
// assimpRoot() ++ "/contrib/zlib/contrib/minizip/zip.c",
// assimpRoot() ++ "/contrib/zlib/contrib/minizip/iowin32.c",
// assimpRoot() ++ "/contrib/zlib/contrib/puff/pufftest.c",
// assimpRoot() ++ "/contrib/zlib/contrib/puff/puff.c",
// assimpRoot() ++ "/contrib/zlib/contrib/blast/blast.c",
// assimpRoot() ++ "/contrib/zlib/contrib/untgz/untgz.c",
assimpRoot() ++ "/contrib/zlib/trees.c",
assimpRoot() ++ "/contrib/zlib/zutil.c",
assimpRoot() ++ "/contrib/zlib/deflate.c",
assimpRoot() ++ "/contrib/zlib/crc32.c",
assimpRoot() ++ "/contrib/zlib/adler32.c",
};
const poly2tri = [_][]const u8{
assimpRoot() ++ "/contrib/poly2tri/poly2tri/common/shapes.cc",
assimpRoot() ++ "/contrib/poly2tri/poly2tri/sweep/sweep_context.cc",
assimpRoot() ++ "/contrib/poly2tri/poly2tri/sweep/advancing_front.cc",
assimpRoot() ++ "/contrib/poly2tri/poly2tri/sweep/cdt.cc",
assimpRoot() ++ "/contrib/poly2tri/poly2tri/sweep/sweep.cc",
};
const clipper = [_][]const u8{
assimpRoot() ++ "/contrib/clipper/clipper.cpp",
};
const openddlparser = [_][]const u8{
assimpRoot() ++ "/contrib/openddlparser/code/OpenDDLParser.cpp",
assimpRoot() ++ "/contrib/openddlparser/code/OpenDDLExport.cpp",
assimpRoot() ++ "/contrib/openddlparser/code/DDLNode.cpp",
assimpRoot() ++ "/contrib/openddlparser/code/OpenDDLCommon.cpp",
assimpRoot() ++ "/contrib/openddlparser/code/Value.cpp",
assimpRoot() ++ "/contrib/openddlparser/code/OpenDDLStream.cpp",
};
};
const @"3DS" = [_][]const u8{
src_root ++ "/AssetLib/3DS/3DSConverter.cpp",
src_root ++ "/AssetLib/3DS/3DSExporter.cpp",
src_root ++ "/AssetLib/3DS/3DSLoader.cpp",
};
const @"3MF" = [_][]const u8{
src_root ++ "/AssetLib/3MF/D3MFExporter.cpp",
src_root ++ "/AssetLib/3MF/D3MFImporter.cpp",
src_root ++ "/AssetLib/3MF/D3MFOpcPackage.cpp",
src_root ++ "/AssetLib/3MF/XmlSerializer.cpp",
};
const @"AC" = [_][]const u8{
src_root ++ "/AssetLib/AC/ACLoader.cpp",
};
const @"AMF" = [_][]const u8{
src_root ++ "/AssetLib/AMF/AMFImporter_Geometry.cpp",
src_root ++ "/AssetLib/AMF/AMFImporter_Material.cpp",
src_root ++ "/AssetLib/AMF/AMFImporter_Postprocess.cpp",
src_root ++ "/AssetLib/AMF/AMFImporter.cpp",
};
const @"ASE" = [_][]const u8{
src_root ++ "/AssetLib/ASE/ASELoader.cpp",
src_root ++ "/AssetLib/ASE/ASEParser.cpp",
};
const @"Assbin" = [_][]const u8{
src_root ++ "/AssetLib/Assbin/AssbinExporter.cpp",
src_root ++ "/AssetLib/Assbin/AssbinFileWriter.cpp",
src_root ++ "/AssetLib/Assbin/AssbinLoader.cpp",
};
const @"Assjson" = [_][]const u8{
src_root ++ "/AssetLib/Assjson/cencode.c",
src_root ++ "/AssetLib/Assjson/json_exporter.cpp",
src_root ++ "/AssetLib/Assjson/mesh_splitter.cpp",
};
const @"Assxml" = [_][]const u8{
src_root ++ "/AssetLib/Assxml/AssxmlExporter.cpp",
src_root ++ "/AssetLib/Assxml/AssxmlFileWriter.cpp",
};
const @"B3D" = [_][]const u8{
src_root ++ "/AssetLib/B3D/B3DImporter.cpp",
};
const @"Blender" = [_][]const u8{
src_root ++ "/AssetLib/Blender/BlenderBMesh.cpp",
src_root ++ "/AssetLib/Blender/BlenderCustomData.cpp",
src_root ++ "/AssetLib/Blender/BlenderDNA.cpp",
src_root ++ "/AssetLib/Blender/BlenderLoader.cpp",
src_root ++ "/AssetLib/Blender/BlenderModifier.cpp",
src_root ++ "/AssetLib/Blender/BlenderScene.cpp",
src_root ++ "/AssetLib/Blender/BlenderTessellator.cpp",
};
const @"BVH" = [_][]const u8{
src_root ++ "/AssetLib/BVH/BVHLoader.cpp",
};
const @"C4D" = [_][]const u8{
src_root ++ "/AssetLib/C4D/C4DImporter.cpp",
};
const @"COB" = [_][]const u8{
src_root ++ "/AssetLib/COB/COBLoader.cpp",
};
const @"Collada" = [_][]const u8{
src_root ++ "/AssetLib/Collada/ColladaExporter.cpp",
src_root ++ "/AssetLib/Collada/ColladaHelper.cpp",
src_root ++ "/AssetLib/Collada/ColladaLoader.cpp",
src_root ++ "/AssetLib/Collada/ColladaParser.cpp",
};
const @"CSM" = [_][]const u8{
src_root ++ "/AssetLib/CSM/CSMLoader.cpp",
};
const @"DXF" = [_][]const u8{
src_root ++ "/AssetLib/DXF/DXFLoader.cpp",
};
const @"FBX" = [_][]const u8{
src_root ++ "/AssetLib/FBX/FBXAnimation.cpp",
src_root ++ "/AssetLib/FBX/FBXBinaryTokenizer.cpp",
src_root ++ "/AssetLib/FBX/FBXConverter.cpp",
src_root ++ "/AssetLib/FBX/FBXDeformer.cpp",
src_root ++ "/AssetLib/FBX/FBXDocument.cpp",
src_root ++ "/AssetLib/FBX/FBXDocumentUtil.cpp",
src_root ++ "/AssetLib/FBX/FBXExporter.cpp",
src_root ++ "/AssetLib/FBX/FBXExportNode.cpp",
src_root ++ "/AssetLib/FBX/FBXExportProperty.cpp",
src_root ++ "/AssetLib/FBX/FBXImporter.cpp",
src_root ++ "/AssetLib/FBX/FBXMaterial.cpp",
src_root ++ "/AssetLib/FBX/FBXMeshGeometry.cpp",
src_root ++ "/AssetLib/FBX/FBXModel.cpp",
src_root ++ "/AssetLib/FBX/FBXNodeAttribute.cpp",
src_root ++ "/AssetLib/FBX/FBXParser.cpp",
src_root ++ "/AssetLib/FBX/FBXProperties.cpp",
src_root ++ "/AssetLib/FBX/FBXTokenizer.cpp",
src_root ++ "/AssetLib/FBX/FBXUtil.cpp",
};
const @"glTF" = [_][]const u8{
src_root ++ "/AssetLib/glTF/glTFCommon.cpp",
src_root ++ "/AssetLib/glTF/glTFExporter.cpp",
src_root ++ "/AssetLib/glTF/glTFImporter.cpp",
};
const @"glTF2" = [_][]const u8{
src_root ++ "/AssetLib/glTF2/glTF2Exporter.cpp",
src_root ++ "/AssetLib/glTF2/glTF2Importer.cpp",
};
const @"HMP" = [_][]const u8{
src_root ++ "/AssetLib/HMP/HMPLoader.cpp",
};
const @"IFC" = [_][]const u8{
src_root ++ "/AssetLib/IFC/IFCBoolean.cpp",
src_root ++ "/AssetLib/IFC/IFCCurve.cpp",
src_root ++ "/AssetLib/IFC/IFCGeometry.cpp",
src_root ++ "/AssetLib/IFC/IFCLoader.cpp",
src_root ++ "/AssetLib/IFC/IFCMaterial.cpp",
src_root ++ "/AssetLib/IFC/IFCOpenings.cpp",
src_root ++ "/AssetLib/IFC/IFCProfile.cpp",
// src_root ++ "/AssetLib/IFC/IFCReaderGen_4.cpp", // not used?
src_root ++ "/AssetLib/IFC/IFCReaderGen1_2x3.cpp",
src_root ++ "/AssetLib/IFC/IFCReaderGen2_2x3.cpp",
src_root ++ "/AssetLib/IFC/IFCUtil.cpp",
};
const @"Irr" = [_][]const u8{
src_root ++ "/AssetLib/Irr/IRRLoader.cpp",
src_root ++ "/AssetLib/Irr/IRRMeshLoader.cpp",
src_root ++ "/AssetLib/Irr/IRRShared.cpp",
};
const @"LWO" = [_][]const u8{
src_root ++ "/AssetLib/LWO/LWOAnimation.cpp",
src_root ++ "/AssetLib/LWO/LWOBLoader.cpp",
src_root ++ "/AssetLib/LWO/LWOLoader.cpp",
src_root ++ "/AssetLib/LWO/LWOMaterial.cpp",
src_root ++ "/AssetLib/LWS/LWSLoader.cpp",
};
const @"LWS" = [_][]const u8{
src_root ++ "/AssetLib/M3D/M3DExporter.cpp",
src_root ++ "/AssetLib/M3D/M3DImporter.cpp",
src_root ++ "/AssetLib/M3D/M3DWrapper.cpp",
};
const @"M3D" = [_][]const u8{};
const @"MD2" = [_][]const u8{
src_root ++ "/AssetLib/MD2/MD2Loader.cpp",
};
const @"MD3" = [_][]const u8{
src_root ++ "/AssetLib/MD3/MD3Loader.cpp",
};
const @"MD5" = [_][]const u8{
src_root ++ "/AssetLib/MD5/MD5Loader.cpp",
src_root ++ "/AssetLib/MD5/MD5Parser.cpp",
};
const @"MDC" = [_][]const u8{
src_root ++ "/AssetLib/MDC/MDCLoader.cpp",
};
const @"MDL" = [_][]const u8{
src_root ++ "/AssetLib/MDL/HalfLife/HL1MDLLoader.cpp",
src_root ++ "/AssetLib/MDL/HalfLife/UniqueNameGenerator.cpp",
src_root ++ "/AssetLib/MDL/MDLLoader.cpp",
src_root ++ "/AssetLib/MDL/MDLMaterialLoader.cpp",
};
const @"MMD" = [_][]const u8{
src_root ++ "/AssetLib/MMD/MMDImporter.cpp",
src_root ++ "/AssetLib/MMD/MMDPmxParser.cpp",
};
const @"MS3D" = [_][]const u8{
src_root ++ "/AssetLib/MS3D/MS3DLoader.cpp",
};
const @"NDO" = [_][]const u8{
src_root ++ "/AssetLib/NDO/NDOLoader.cpp",
};
const @"NFF" = [_][]const u8{
src_root ++ "/AssetLib/NFF/NFFLoader.cpp",
};
const @"Obj" = [_][]const u8{
src_root ++ "/AssetLib/Obj/ObjExporter.cpp",
src_root ++ "/AssetLib/Obj/ObjFileImporter.cpp",
src_root ++ "/AssetLib/Obj/ObjFileMtlImporter.cpp",
src_root ++ "/AssetLib/Obj/ObjFileParser.cpp",
};
const @"OFF" = [_][]const u8{
src_root ++ "/AssetLib/OFF/OFFLoader.cpp",
};
const @"Ogre" = [_][]const u8{
src_root ++ "/AssetLib/Ogre/OgreBinarySerializer.cpp",
src_root ++ "/AssetLib/Ogre/OgreImporter.cpp",
src_root ++ "/AssetLib/Ogre/OgreMaterial.cpp",
src_root ++ "/AssetLib/Ogre/OgreStructs.cpp",
src_root ++ "/AssetLib/Ogre/OgreXmlSerializer.cpp",
};
const @"OpenGEX" = [_][]const u8{
src_root ++ "/AssetLib/OpenGEX/OpenGEXExporter.cpp",
src_root ++ "/AssetLib/OpenGEX/OpenGEXImporter.cpp",
};
const @"Ply" = [_][]const u8{
src_root ++ "/AssetLib/Ply/PlyExporter.cpp",
src_root ++ "/AssetLib/Ply/PlyLoader.cpp",
src_root ++ "/AssetLib/Ply/PlyParser.cpp",
};
const @"Q3BSP" = [_][]const u8{
src_root ++ "/AssetLib/Q3BSP/Q3BSPFileImporter.cpp",
src_root ++ "/AssetLib/Q3BSP/Q3BSPFileParser.cpp",
};
const @"Q3D" = [_][]const u8{
src_root ++ "/AssetLib/Q3D/Q3DLoader.cpp",
};
const @"Raw" = [_][]const u8{
src_root ++ "/AssetLib/Raw/RawLoader.cpp",
};
const @"SIB" = [_][]const u8{
src_root ++ "/AssetLib/SIB/SIBImporter.cpp",
};
const @"SMD" = [_][]const u8{
src_root ++ "/AssetLib/SMD/SMDLoader.cpp",
};
const @"Step" = [_][]const u8{
src_root ++ "/AssetLib/Step/StepExporter.cpp",
};
const @"STEPParser" = [_][]const u8{
src_root ++ "/AssetLib/STEPParser/STEPFileEncoding.cpp",
src_root ++ "/AssetLib/STEPParser/STEPFileReader.cpp",
};
const @"STL" = [_][]const u8{
src_root ++ "/AssetLib/STL/STLExporter.cpp",
src_root ++ "/AssetLib/STL/STLLoader.cpp",
};
const @"Terragen" = [_][]const u8{
src_root ++ "/AssetLib/Terragen/TerragenLoader.cpp",
};
const @"Unreal" = [_][]const u8{
src_root ++ "/AssetLib/Unreal/UnrealLoader.cpp",
};
const @"X" = [_][]const u8{
src_root ++ "/AssetLib/X/XFileExporter.cpp",
src_root ++ "/AssetLib/X/XFileImporter.cpp",
src_root ++ "/AssetLib/X/XFileParser.cpp",
};
const @"X3D" = [_][]const u8{
src_root ++ "/AssetLib/X3D/X3DExporter.cpp",
src_root ++ "/AssetLib/X3D/X3DImporter.cpp",
};
const @"XGL" = [_][]const u8{
src_root ++ "/AssetLib/XGL/XGLLoader.cpp",
};
}; | Sdk.zig |
const std = @import("std");
const fmt = std.fmt;
const server = &@import("../main.zig").server;
const Error = @import("../command.zig").Error;
const Seat = @import("../Seat.zig");
const Config = @import("../Config.zig");
pub fn borderWidth(
allocator: *std.mem.Allocator,
seat: *Seat,
args: []const [:0]const u8,
out: *?[]const u8,
) Error!void {
if (args.len < 2) return Error.NotEnoughArguments;
if (args.len > 2) return Error.TooManyArguments;
server.config.border_width = try fmt.parseInt(u32, args[1], 10);
server.root.arrangeAll();
server.root.startTransaction();
}
pub fn backgroundColor(
allocator: *std.mem.Allocator,
seat: *Seat,
args: []const [:0]const u8,
out: *?[]const u8,
) Error!void {
if (args.len < 2) return Error.NotEnoughArguments;
if (args.len > 2) return Error.TooManyArguments;
server.config.background_color = try parseRgba(args[1]);
var it = server.root.outputs.first;
while (it) |node| : (it = node.next) node.data.damage.addWhole();
}
pub fn borderColorFocused(
allocator: *std.mem.Allocator,
seat: *Seat,
args: []const [:0]const u8,
out: *?[]const u8,
) Error!void {
if (args.len < 2) return Error.NotEnoughArguments;
if (args.len > 2) return Error.TooManyArguments;
server.config.border_color_focused = try parseRgba(args[1]);
var it = server.root.outputs.first;
while (it) |node| : (it = node.next) node.data.damage.addWhole();
}
pub fn borderColorUnfocused(
allocator: *std.mem.Allocator,
seat: *Seat,
args: []const [:0]const u8,
out: *?[]const u8,
) Error!void {
if (args.len < 2) return Error.NotEnoughArguments;
if (args.len > 2) return Error.TooManyArguments;
server.config.border_color_unfocused = try parseRgba(args[1]);
var it = server.root.outputs.first;
while (it) |node| : (it = node.next) node.data.damage.addWhole();
}
pub fn borderColorUrgent(
allocator: *std.mem.Allocator,
seat: *Seat,
args: []const [:0]const u8,
out: *?[]const u8,
) Error!void {
if (args.len < 2) return Error.NotEnoughArguments;
if (args.len > 2) return Error.TooManyArguments;
server.config.border_color_urgent = try parseRgba(args[1]);
var it = server.root.outputs.first;
while (it) |node| : (it = node.next) node.data.damage.addWhole();
}
pub fn setCursorWarp(
allocator: *std.mem.Allocator,
seat: *Seat,
args: []const [:0]const u8,
out: *?[]const u8,
) Error!void {
if (args.len < 2) return Error.NotEnoughArguments;
if (args.len > 2) return Error.TooManyArguments;
server.config.warp_cursor = std.meta.stringToEnum(Config.WarpCursorMode, args[1]) orelse
return Error.UnknownOption;
}
/// Parse a color in the format 0xRRGGBB or 0xRRGGBBAA
fn parseRgba(string: []const u8) ![4]f32 {
if (string.len != 8 and string.len != 10) return error.InvalidRgba;
if (string[0] != '0' or string[1] != 'x') return error.InvalidRgba;
const r = try fmt.parseInt(u8, string[2..4], 16);
const g = try fmt.parseInt(u8, string[4..6], 16);
const b = try fmt.parseInt(u8, string[6..8], 16);
const a = if (string.len == 10) try fmt.parseInt(u8, string[8..10], 16) else 255;
return [4]f32{
@intToFloat(f32, r) / 255.0,
@intToFloat(f32, g) / 255.0,
@intToFloat(f32, b) / 255.0,
@intToFloat(f32, a) / 255.0,
};
} | source/river-0.1.0/river/command/config.zig |
const std = @import("std");
const warn = std.debug.warn;
const win = std.os.windows;
usingnamespace @import("externs.zig");
pub const LoadedLibrary = struct {
const Error = error{ UnresolvedImport, OutOfMemory };
const Options = struct { rand: ?*std.rand.Random = null };
image: []align(0x1000) u8,
///allocates space for image with VirtualAlloc
///fills image with random bytes, if options.rand is provided
///copies in sections
///resolves imports (non-recursively!)
///performs relocations
///sets page protection flags
pub fn init(dll: []const u8, options: Options) Error!LoadedLibrary {
// Getting the PE headers
//
//
const dos_header = LoadedLibrary.getDosHeader(dll);
std.log.scoped(.LoadedLibrary).debug("dos_header: {}", .{dos_header.*});
const coff_header = LoadedLibrary.getCoffHeader(dll, dos_header.*);
std.log.scoped(.LoadedLibrary).debug("coff_header: {}", .{coff_header.*});
const optional_header = LoadedLibrary.getOptionalHeader(dll, dos_header.*);
std.log.scoped(.LoadedLibrary).debug("optional_header: {}", .{optional_header.*});
const section_headers = LoadedLibrary.getSectionHeaders(dll, dos_header.*, coff_header.*);
for (section_headers) |header, i| std.log.scoped(.LoadedLibrary).debug("header {}: {}", .{ i, header });
// Allocating space for the image, copying in image in sections
//
//
const image = try std.heap.page_allocator.alignedAlloc(u8, 0x1000, optional_header.size_of_image);
if (options.rand) |rand| rand.bytes(image); //used to make the image look a little different every time if the caller wants that
for (section_headers) |section| std.mem.copy(
u8,
image[section.virtual_address..],
(dll.ptr + section.pointer_to_raw_data)[0..std.mem.min(u32, &[_]u32{
section.size_of_raw_data,
section.virtual_size,
})],
);
// Fix import table
//
//
const import_directories = @ptrCast(
[*]align(1) const Import_Directory_Table,
image.ptr + optional_header.import_table_entry.rva,
)[0 .. optional_header.import_table_entry.size / @sizeOf(Import_Directory_Table)];
for (import_directories) |imp| {
if (imp.import_lookup_table_rva == 0 or imp.import_address_table_rva == 0 or imp.name_rva == 0) continue;
const imp_dll_name = @ptrCast([*:0]const u8, image.ptr + imp.name_rva);
std.log.scoped(.LoadedLibrary).debug("import: {}", .{imp_dll_name});
const imp_dll_location = GetModuleHandleA(imp_dll_name) orelse return error.UnresolvedImport; //recursive loading is not supported!
const table = @ptrCast([*:0]usize, @alignCast(8, image.ptr + imp.import_lookup_table_rva));
var i: usize = 0;
while (table[i] != 0) : (i += 1) {
const function_name = @ptrCast([*:0]const u8, image.ptr + table[i] + @sizeOf(u16));
std.log.scoped(.LoadedLibrary).debug("func: {s}", .{function_name});
const function = @ptrToInt(win.kernel32.GetProcAddress(imp_dll_location, function_name));
table[i] = function;
@ptrCast([*]usize, @alignCast(@alignOf(usize), image.ptr + imp.import_address_table_rva))[i] = function;
std.log.scoped(.LoadedLibrary).debug("&table[i]: 0x{*}, table[i]: 0x{x}", .{ &table[i], table[i] });
}
}
// Perform relocations
// TODO: support different types of patches, all are currently handled the same
//
const reloc_tbl = optional_header.base_relocation_table_entry;
var block = @ptrCast(
*align(1) const RelocationBlock,
image.ptr + reloc_tbl.rva,
);
var patches = @ptrCast(
[*]align(1) const RelocationPatch,
@ptrCast([*]const u8, block) + @sizeOf(RelocationBlock),
)[0 .. (block.size - 8) / 2];
while (true) {
std.log.scoped(.LoadedLibrary).debug("block: {}", .{block.*});
for (patches) |p| {
std.log.scoped(.LoadedLibrary).debug("patch: {}", .{p});
if (p.offset == 0) continue;
@ptrCast(*align(1) [*]u8, image.ptr + block.rva + p.offset).* = image.ptr + block.rva;
}
block = @ptrCast(
*align(1) const RelocationBlock,
image.ptr + reloc_tbl.rva + @sizeOf(RelocationBlock) + @sizeOf(RelocationPatch) * patches.len,
);
patches = @ptrCast(
[*]align(1) const RelocationPatch,
@ptrCast([*]const u8, block) + @sizeOf(RelocationBlock),
)[0 .. (block.size - 8) / 2];
if (@ptrToInt(&patches[patches.len - 1]) + @sizeOf(RelocationPatch) >= @ptrToInt(image.ptr) + reloc_tbl.rva + reloc_tbl.size) break;
}
// Give pages the correct protections
//
//
for (section_headers) |section| {
const flags = @bitCast(SectionFlags, section.characteristics);
const page_protection: u32 = blk: { //TODO more coverage of flags
if (flags.mem_read and flags.mem_write and flags.mem_execute) break :blk win.PAGE_EXECUTE_READWRITE;
if (flags.mem_read and flags.mem_execute) break :blk win.PAGE_EXECUTE_READ;
if (flags.mem_read and flags.mem_write) break :blk win.PAGE_READWRITE;
if (flags.mem_read) break :blk win.PAGE_READONLY;
unreachable; // this section's flags aren't handled properly yet :(. TODO: handle all cases
};
var junk: u32 = undefined; //page's previous protection is always RW; we don't need to know this
if (VirtualProtect(image.ptr + section.virtual_address, section.virtual_size, page_protection, &junk) == 0) @panic("protection change failed");
}
return LoadedLibrary{ .image = image };
}
///deallocates space for image with VirtualFree
pub fn deinit(self: *LoadedLibrary) void {
win.VirtualFree(self.image.ptr, 0, win.MEM_RELEASE);
self.* = undefined;
}
fn findExport(self: LoadedLibrary, comptime T: type, dll: []const u8, name: []const u8) ?T {
const exp_dir_table = @ptrCast(
*align(1) EXPORT_DIRECTORY_TABLE,
self.image.ptr + LoadedLibrary.getOptionalHeader(dll, LoadedLibrary.getDosHeader(dll).*).export_table_entry.rva,
);
std.log.scoped(.LoadedLibrary_findExport).debug("exp_dir_table: {}\n", .{exp_dir_table.*});
const exp_names = @ptrCast(
[*]align(1) const u32,
self.image.ptr + exp_dir_table.namePointerRva,
)[0..exp_dir_table.numberOfNamePointers];
const exp_addresses = @ptrCast(
[*]align(1) const u32,
self.image.ptr + exp_dir_table.exportAddressTableRva,
)[1..exp_dir_table.addressTableEntries];
var found_func: ?T = null;
for (exp_names) |n, i| {
const export_name = std.mem.spanZ(@ptrCast([*:0]const u8, self.image.ptr + n));
std.log.scoped(.LoadedLibrary_findExport).debug("export_name: {}", .{export_name});
if (std.mem.eql(u8, export_name, name)) {
found_func = @ptrCast(T, self.image.ptr + exp_addresses[i]);
}
}
return found_func;
}
// TODO: add findExports(...), for efficiency
fn getDosHeader(dll: []const u8) *const IMAGE_DOS_HEADER {
return @ptrCast(*const IMAGE_DOS_HEADER, @alignCast(@alignOf(IMAGE_DOS_HEADER), dll.ptr));
}
fn getCoffHeader(dll: []const u8, dos_header: IMAGE_DOS_HEADER) *const IMAGE_FILE_HEADER {
return @ptrCast(
*const IMAGE_FILE_HEADER,
@alignCast(@alignOf(IMAGE_FILE_HEADER), dll.ptr + @intCast(u32, dos_header.lfanew)),
);
}
fn getOptionalHeader(dll: []const u8, dos_header: IMAGE_DOS_HEADER) *const IMAGE_OPTIONAL_HEADER {
return @ptrCast(
*const IMAGE_OPTIONAL_HEADER,
@alignCast(@alignOf(IMAGE_OPTIONAL_HEADER), dll.ptr + @intCast(u32, dos_header.lfanew) + @sizeOf(IMAGE_FILE_HEADER)),
);
}
fn getSectionHeaders(dll: []const u8, dos_header: IMAGE_DOS_HEADER, coff_header: IMAGE_FILE_HEADER) []const IMAGE_SECTION_HEADER {
return @ptrCast(
[*]const IMAGE_SECTION_HEADER,
@alignCast(@alignOf(IMAGE_SECTION_HEADER), dll.ptr + @intCast(u32, dos_header.lfanew) + @sizeOf(IMAGE_FILE_HEADER) + @sizeOf(IMAGE_OPTIONAL_HEADER)),
)[0..coff_header.number_of_sections];
}
};
pub fn main() !void {
const file = try std.fs.cwd().openFile("ghi.dll", .{});
defer file.close();
const dll = try std.heap.page_allocator.alloc(u8, (try file.stat()).size);
defer std.heap.page_allocator.free(dll);
_ = try file.readAll(dll);
var seed: u64 = undefined;
try std.os.getrandom(std.mem.asBytes(&seed));
var prng = std.rand.DefaultPrng.init(seed);
var library = try LoadedLibrary.init(dll, .{ .rand = &prng.random });
defer library.deinit();
(library.findExport(
fn (c_int) callconv(.C) void,
dll,
"writeInt",
) orelse @panic("writeInt function not found!"))(1002);
} | main.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 Attribute = struct {
z_attr: ?[*:0]const u8,
/// Check if an attribute is set on. In core git parlance, this the value for "Set" attributes.
///
/// For example, if the attribute file contains:
/// *.c foo
///
/// Then for file `xyz.c` looking up attribute "foo" gives a value for which this is true.
pub fn isTrue(self: Attribute) bool {
return self.getValue() == .@"true";
}
/// Checks if an attribute is set off. In core git parlance, this is the value for attributes that are "Unset" (not to be
/// confused with values that a "Unspecified").
///
/// For example, if the attribute file contains:
/// *.h -foo
///
/// Then for file `zyx.h` looking up attribute "foo" gives a value for which this is true.
pub fn isFalse(self: Attribute) bool {
return self.getValue() == .@"false";
}
/// Checks if an attribute is unspecified. This may be due to the attribute not being mentioned at all or because the
/// attribute was explicitly set unspecified via the `!` operator.
///
/// For example, if the attribute file contains:
/// *.c foo
/// *.h -foo
/// onefile.c !foo
///
/// Then for `onefile.c` looking up attribute "foo" yields a value with of true. Also, looking up "foo" on file `onefile.rb`
/// or looking up "bar" on any file will all give a value of true.
pub fn isUnspecified(self: Attribute) bool {
return self.getValue() == .unspecified;
}
/// Checks if an attribute is set to a value (as opposed to @"true", @"false" or unspecified). This would be the case if for a file
/// with something like:
/// *.txt eol=lf
///
/// Given this, looking up "eol" for `onefile.txt` will give back the string "lf" and will return true.
pub fn hasValue(self: Attribute) bool {
return self.getValue() == .string;
}
pub fn getValue(self: Attribute) AttributeValue {
return @intToEnum(AttributeValue, c.git_attr_value(self.z_attr));
}
pub const AttributeValue = enum(c_uint) {
/// The attribute has been left unspecified
unspecified = 0,
/// The attribute has been set
@"true",
/// The attribute has been unset
@"false",
/// This attribute has a value
string,
};
comptime {
std.testing.refAllDecls(@This());
}
};
pub const AttributeOptions = struct {
flags: git.AttributeFlags,
commit_id: *git.Oid,
comptime {
std.testing.refAllDecls(@This());
}
};
pub const AttributeFlags = struct {
location: Location = .file_then_index,
/// Controls extended attribute behavior
extended: Extended = .{},
pub const Location = enum(u32) {
file_then_index = 0,
index_then_file = 1,
index_only = 2,
};
pub const Extended = packed struct {
z_padding1: u2 = 0,
/// Normally, attribute checks include looking in the /etc (or system equivalent) directory for a `gitattributes`
/// file. Passing this flag will cause attribute checks to ignore that file. Setting the `no_system` flag will cause
/// attribute checks to ignore that file.
no_system: bool = false,
/// Passing the `include_head` flag will use attributes from a `.gitattributes` file in the repository
/// at the HEAD revision.
include_head: bool = false,
/// Passing the `include_commit` flag will use attributes from a `.gitattributes` file in a specific
/// commit.
include_commit: if (HAS_INCLUDE_COMMIT) bool else void = if (HAS_INCLUDE_COMMIT) false else {},
z_padding2: if (HAS_INCLUDE_COMMIT) u27 else u28 = 0,
const HAS_INCLUDE_COMMIT = @hasDecl(c, "GIT_ATTR_CHECK_INCLUDE_COMMIT");
pub fn format(
value: Extended,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = fmt;
return internal.formatWithoutFields(
value,
options,
writer,
&.{ "z_padding1", "z_padding2" },
);
}
test {
try std.testing.expectEqual(@sizeOf(u32), @sizeOf(Extended));
try std.testing.expectEqual(@bitSizeOf(u32), @bitSizeOf(Extended));
}
comptime {
std.testing.refAllDecls(@This());
}
};
comptime {
std.testing.refAllDecls(@This());
}
};
comptime {
std.testing.refAllDecls(@This());
} | src/attribute.zig |
const std = @import("std");
const json = std.json;
const testing = std.testing;
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const Dir = std.fs.Dir;
const print = std.debug.print;
const nestedtext = @import("nestedtext");
const logger = std.log.scoped(.testsuite);
const testcases_path = "tests/official_tests/test_cases/";
const max_file_size: usize = 1024 * 1024;
const skipped_testcases = [_][]const u8{
"dict_21", // Unrepresentable
"dict_22", // Unrepresentable
// TODO: Testcase for different line endings in same file (error lineno)
// TODO: Testcase for multiline key without following value (error lineno)
// TODO: Testcase for bad object keys ('-', '>', ':', '[', '{')
};
const fail_fast = true;
const ParseErrorInfo = struct {
lineno: usize,
colno: ?usize,
message: []const u8,
};
// Modified std.testing functions
// -----------------------------------------------------------------------------
/// Slightly modified from std.testing to return error instead of panic.
fn expectEqualStrings(expected: []const u8, actual: []const u8) !void {
if (std.mem.indexOfDiff(u8, actual, expected)) |diff_index| {
print("\n====== expected this output: =========\n", .{});
printWithVisibleNewlines(expected);
print("\n======== instead found this: =========\n", .{});
printWithVisibleNewlines(actual);
print("\n======================================\n", .{});
var diff_line_number: usize = 1;
for (expected[0..diff_index]) |value| {
if (value == '\n') diff_line_number += 1;
}
print("First difference occurs on line {}:\n", .{diff_line_number});
print("expected:\n", .{});
printIndicatorLine(expected, diff_index);
print("found:\n", .{});
printIndicatorLine(actual, diff_index);
return error.TestingAssert;
}
}
fn printIndicatorLine(source: []const u8, indicator_index: usize) void {
const line_begin_index = if (std.mem.lastIndexOfScalar(u8, source[0..indicator_index], '\n')) |line_begin|
line_begin + 1
else
0;
const line_end_index = if (std.mem.indexOfScalar(u8, source[indicator_index..], '\n')) |line_end|
(indicator_index + line_end)
else
source.len;
printLine(source[line_begin_index..line_end_index]);
{
var i: usize = line_begin_index;
while (i < indicator_index) : (i += 1)
print(" ", .{});
}
print("^\n", .{});
}
fn printWithVisibleNewlines(source: []const u8) void {
var i: usize = 0;
while (std.mem.indexOf(u8, source[i..], "\n")) |nl| : (i += nl + 1) {
printLine(source[i .. i + nl]);
}
print("{s}<ETX>\n", .{source[i..]}); // End of Text (ETX)
}
fn printLine(line: []const u8) void {
if (line.len != 0) switch (line[line.len - 1]) {
' ', '\t' => print("{s}<CR>\n", .{line}), // Carriage return
else => {},
};
print("{s}\n", .{line});
}
// Helpers
// -----------------------------------------------------------------------------
/// Returned memory is owned by the caller.
fn canonicaliseJson(allocator: Allocator, json_input: []const u8) ![]const u8 {
var json_tree = try json.Parser.init(allocator, false).parse(json_input);
defer json_tree.deinit();
var buffer = std.ArrayList(u8).init(allocator);
errdefer buffer.deinit();
try json_tree.root.jsonStringify(.{}, buffer.writer());
return buffer.items;
}
fn readFileIfExists(dir: Dir, allocator: Allocator, file_path: []const u8) !?[]const u8 {
return dir.readFileAlloc(allocator, file_path, max_file_size) catch |e| switch (e) {
error.FileNotFound => null,
else => return e,
};
}
fn skipTestcase(name: []const u8) bool {
for (skipped_testcases) |skip| {
if (std.mem.eql(u8, name, skip)) return true;
}
return false;
}
// Testing mechanism
// -----------------------------------------------------------------------------
fn testParseSuccess(input_nt: []const u8, expected_json: []const u8) !void {
logger.debug("Checking for parsing success", .{});
var p = nestedtext.Parser.init(testing.allocator, .{});
var diags: nestedtext.Parser.Diags = undefined;
p.diags = &diags;
var nt_tree = p.parse(input_nt) catch |e| {
logger.err(
"{s} (line {d})",
.{ diags.ParseError.message, diags.ParseError.lineno },
);
return e;
};
defer nt_tree.deinit();
var json_tree = try nt_tree.toJson(testing.allocator);
defer json_tree.deinit();
var buffer = std.ArrayList(u8).init(testing.allocator);
defer buffer.deinit();
try json_tree.root.jsonStringify(.{}, buffer.writer());
try expectEqualStrings(expected_json, buffer.items);
}
fn testParseError(input_nt: []const u8, expected_error: ParseErrorInfo) !void {
logger.debug("Checking for parsing error", .{});
var p = nestedtext.Parser.init(testing.allocator, .{});
var diags: nestedtext.Parser.Diags = undefined;
p.diags = &diags;
// TODO: Use std.meta.isError() (Zig 0.8).
if (p.parse(input_nt)) |tree| {
tree.deinit();
return error.UnexpectedParseSuccess;
} else |_| {}
logger.debug("Got parse error: {s}", .{diags.ParseError.message});
const expected = expected_error.lineno;
const actual = diags.ParseError.lineno;
if (expected != actual) {
print("expected {}, found {}", .{ expected, actual });
return error.TestingAssert;
}
// TODO: Check message.
}
fn testDumpSuccess(input_json: []const u8, expected_nt: []const u8) !void {
logger.debug("Checking for dumping success", .{});
var json_parser = json.Parser.init(testing.allocator, false);
defer json_parser.deinit();
var json_tree = try json_parser.parse(input_json);
defer json_tree.deinit();
var nt_tree = try nestedtext.fromJson(testing.allocator, json_tree.root);
defer nt_tree.deinit();
var buffer = std.ArrayList(u8).init(testing.allocator);
defer buffer.deinit();
try nt_tree.stringify(.{ .indent = 4 }, buffer.writer());
try expectEqualStrings(expected_nt, buffer.items);
}
fn testSingle(allocator: Allocator, dir: std.fs.Dir) !void {
var tested_something = false;
if (try readFileIfExists(dir, allocator, "load_in.nt")) |input| {
if (try readFileIfExists(dir, allocator, "load_out.json")) |load_out| {
const expected = try canonicaliseJson(allocator, load_out);
try testParseSuccess(input, expected);
} else if (try readFileIfExists(dir, allocator, "load_err.json")) |load_err| {
const json_parse_opts = json.ParseOptions{ .allocator = allocator };
var stream = json.TokenStream.init(load_err);
const err_json = try json.parse(ParseErrorInfo, &stream, json_parse_opts);
defer json.parseFree(ParseErrorInfo, err_json, json_parse_opts);
try testParseError(input, err_json);
} else {
logger.err("Expected one of 'load_out.json' or 'load_err.json'", .{});
return error.InvalidTestcase;
}
tested_something = true;
}
if (try readFileIfExists(dir, allocator, "dump_in.json")) |input| {
if (try readFileIfExists(dir, allocator, "dump_out.nt")) |dump_out| {
const expected = std.mem.trimRight(u8, dump_out, "\r\n");
try testDumpSuccess(input, expected);
} else if (try readFileIfExists(dir, allocator, "dump_err.json")) |load_err| {
// TODO: Should be impossible?
_ = load_err;
logger.warn("Checking dump errors not yet implemented", .{});
} else {
logger.err("Expected one of 'dump_out.nt' or 'dump_err.json'", .{});
return error.InvalidTestcase;
}
tested_something = true;
}
if (!tested_something) {
logger.warn("Nothing found to test", .{});
}
}
fn testAll(base_dir: std.fs.Dir) !void {
var passed: usize = 0;
var skipped: usize = 0;
var failed: usize = 0;
var failures = ArrayList([]const u8).init(testing.allocator);
defer failures.deinit();
print("\n", .{});
var iter = base_dir.iterate();
while (try iter.next()) |*entry| {
std.debug.assert(entry.kind == .Directory);
if (skipTestcase(entry.name)) {
print("--- Skipping testcase: {s} ---\n\n", .{entry.name});
skipped += 1;
continue;
}
var dir = try base_dir.openDir(entry.name, .{});
defer dir.close();
print("--- Running testcase: {s} ---\n", .{entry.name});
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
testSingle(arena.allocator(), dir) catch |e| {
print("--- Testcase failed: {} ---\n\n", .{e});
failed += 1;
try failures.append(entry.name);
if (fail_fast) return e else continue;
};
print("--- Testcase passed ---\n\n", .{});
passed += 1;
}
print("{d} testcases passed\n", .{passed});
print("{d} testcases skipped\n", .{skipped});
print("{d} testcases failed\n", .{failed});
if (failed > 0) {
print("\nFailed testcases:\n", .{});
for (failures.items) |name|
print(" {s}\n", .{name});
print("\n", .{});
return error.TestFailure;
}
}
test "All testcases" {
std.testing.log_level = .debug;
print("\n", .{});
var testcases_dir = try std.fs.cwd().openDir(testcases_path, .{ .iterate = true });
defer testcases_dir.close();
try testAll(testcases_dir);
} | tests/testsuite.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const webgpu = @import("../../webgpu.zig");
const dummy = @import("./dummy.zig");
pub const Instance = struct {
const vtable = webgpu.Instance.VTable{
.destroy_fn = destroy,
.create_surface_fn = createSurface,
.request_adapter_fn = requestAdapter,
};
super: webgpu.Instance,
allocator: Allocator,
low_power_adapter: ?*Adapter,
high_performance_adapter: ?*Adapter,
pub fn create(descriptor: webgpu.InstanceDescriptor) webgpu.Instance.CreateError!*Instance {
var instance = try descriptor.allocator.create(Instance);
errdefer descriptor.allocator.destroy(instance);
instance.super.__vtable = &vtable;
instance.allocator = descriptor.allocator;
instance.low_power_adapter = null;
instance.high_performance_adapter = null;
return instance;
}
fn destroy(super: *webgpu.Instance) void {
var instance = @fieldParentPtr(Instance, "super", super);
if (instance.low_power_adapter) |adapter| {
adapter.destroy();
}
if (instance.high_performance_adapter) |adapter| {
adapter.destroy();
}
instance.allocator.destroy(instance);
}
fn createSurface(super: *webgpu.Instance, descriptor: webgpu.SurfaceDescriptor) webgpu.Instance.CreateSurfaceError!*webgpu.Surface {
var instance = @fieldParentPtr(Instance, "super", super);
var surface = try Surface.create(instance, descriptor);
return &surface.super;
}
fn requestAdapter(super: *webgpu.Instance, options: webgpu.RequestAdapterOptions) webgpu.Instance.RequestAdapterError!*webgpu.Adapter {
var instance = @fieldParentPtr(Instance, "super", super);
var adapter = switch (options.power_preference) {
.low_power => &instance.low_power_adapter,
.high_performance => &instance.high_performance_adapter,
};
if (adapter.*) |cached| {
return &cached.super;
}
adapter.* = try Adapter.create(instance, options);
errdefer adapter.*.?.destroy();
return &adapter.*.?.super;
}
};
pub const Adapter = struct {
const vtable = webgpu.Adapter.VTable{
.request_device_fn = requestDevice,
};
super: webgpu.Adapter,
pub fn create(instance: *Instance, options: webgpu.RequestAdapterOptions) webgpu.Instance.RequestAdapterError!*Adapter {
_ = options;
var adapter = try instance.allocator.create(Adapter);
errdefer instance.allocator.destroy(adapter);
adapter.super = .{
.__vtable = &vtable,
.instance = &instance.super,
.features = .{},
.limits = .{},
.adapter_type = .unknown,
.backend_type = .unknown,
.device_id = 0,
.vendor_id = 0,
.name = "Dummy",
};
return adapter;
}
pub fn destroy(adapter: *Adapter) void {
var instance = @fieldParentPtr(Instance, "super", adapter.super.instance);
instance.allocator.destroy(adapter);
}
fn requestDevice(super: *webgpu.Adapter, descriptor: webgpu.DeviceDescriptor) webgpu.Adapter.RequestDeviceError!*webgpu.Device {
var adapter = @fieldParentPtr(Adapter, "super", super);
var device = try dummy.Device.create(adapter, descriptor);
return &device.super;
}
};
pub const Surface = struct {
const vtable = webgpu.Surface.VTable{
.destroy_fn = destroy,
.get_preferred_format_fn = getPreferredFormat,
};
super: webgpu.Surface,
pub fn create(instance: *Instance, descriptor: webgpu.SurfaceDescriptor) webgpu.Instance.CreateSurfaceError!*Surface {
_ = descriptor;
var surface = try instance.allocator.create(Surface);
errdefer instance.allocator.destroy(surface);
surface.super = .{
.__vtable = &vtable,
.instance = &instance.super,
};
return surface;
}
fn destroy(super: *webgpu.Surface) void {
var surface = @fieldParentPtr(Surface, "super", super);
var instance = @fieldParentPtr(Instance, "super", surface.super.instance);
instance.allocator.destroy(surface);
}
fn getPreferredFormat(super: *webgpu.Surface) webgpu.TextureFormat {
_ = super;
return .bgra8_unorm;
}
}; | src/backends/dummy/instance.zig |
const std = @import("std");
pub fn Point(comptime T: type) type {
return struct {
x: T,
y: T,
const Self = @This();
pub fn make(x: T, y: T) Self {
return .{ .x = x, .y = y };
}
pub fn translate(self: *Self, point: Self) void {
self.x += point.x;
self.y += point.y;
}
pub fn translated(self: Self, point: Self) Self {
return .{ .x = self.x + point.x, .y = self.y + point.y };
}
const add = translate;
const added = translated;
pub fn subtract(self: *Self, point: Self) void {
self.x -= point.x;
self.y -= point.y;
}
pub fn subtracted(self: Self, point: Self) Self {
return .{ .x = self.x - point.x, .y = self.y - point.y };
}
pub fn scaled(self: Self, s: T) Self {
return .{ .x = self.x * s, .y = self.y * s };
}
pub fn dot(self: Self, point: Self) T {
return self.x * point.x + self.y * point.y;
}
pub fn lengthSquared(self: Self) T {
return self.dot(self);
}
pub fn length(self: Self) T {
return std.math.sqrt(self.lengthSquared());
}
pub fn angle(self: Self) T {
return std.math.atan2(T, self.y, self.x);
}
pub fn eql(self: Self, point: Self) bool {
return self.x == point.x and self.y == point.y;
}
pub fn lerp(a: Self, b: Self, t: T) Self {
return .{ .x = mix(a.x, b.x, t), .y = mix(a.y, b.y, t) };
}
fn mix(a: T, b: T, t: T) T {
return (1 - t) * a + t * b;
}
pub fn min(a: Self, b: Self) Self {
return .{ .x = std.math.min(a.x, b.x), .y = std.math.min(a.y, b.y) };
}
pub fn max(a: Self, b: Self) Self {
return .{ .x = std.math.max(a.x, b.x), .y = std.math.max(a.y, b.y) };
}
};
}
pub fn Rect(comptime T: type) type {
return struct {
x: T,
y: T,
w: T,
h: T,
const Self = @This();
pub fn make(x: T, y: T, w: T, h: T) Self {
return .{ .x = x, .y = y, .w = w, .h = h };
}
pub fn fromPoints(p0: Point(T), p1: Point(T)) Self {
return .{
.x = std.math.min(p0.x, p1.x),
.y = std.math.min(p0.y, p1.y),
.w = if (p1.x > p0.x) p1.x - p0.x else p0.x - p1.x,
.h = if (p1.y > p0.y) p1.y - p0.y else p0.y - p1.y,
};
}
pub fn getPosition(self: Self) Point(T) {
return .{ .x = self.x, .y = self.y };
}
pub fn getSize(self: Self) Point(T) {
return .{ .x = self.w, .y = self.h };
}
pub fn translated(self: Self, point: Point(T)) Self {
return .{ .x = self.x + point.x, .y = self.y + point.y, .w = self.w, .h = self.h };
}
pub fn scaled(self: Self, s: T) Rect(T) {
return .{ .x = self.x * s, .y = self.y * s, .w = self.w * s, .h = self.h * s };
}
pub fn contains(self: Self, point: Point(T)) bool {
return point.x >= self.x and point.x < self.x + self.w and point.y >= self.y and point.y < self.y + self.h;
}
pub fn overlaps(self: Self, other: Rect(T)) bool {
return self.x < other.x + other.w and self.x + self.w > other.x and self.y < other.y + other.h and self.y + self.h > other.y;
}
pub fn intersection(self: Self, other: Rect(T)) Rect(T) {
return .{
.x = std.math.max(self.x, other.x),
.y = std.math.max(self.y, other.y),
.w = std.math.min(self.x + self.w, other.x + other.w) - std.math.max(self.x, other.x),
.h = std.math.min(self.y + self.h, other.y + other.h) - std.math.max(self.y, other.y),
};
}
};
} | src/gui/geometry.zig |
pub const WHV_PROCESSOR_FEATURES_BANKS_COUNT = @as(u32, 2);
pub const WHV_HYPERCALL_CONTEXT_MAX_XMM_REGISTERS = @as(u32, 6);
//--------------------------------------------------------------------------------
// Section: Types (84)
//--------------------------------------------------------------------------------
// TODO: this type has a FreeFunc 'WHvDeletePartition', what can Zig do with this information?
pub const WHV_PARTITION_HANDLE = isize;
pub const WHV_CAPABILITY_CODE = enum(i32) {
HypervisorPresent = 0,
Features = 1,
ExtendedVmExits = 2,
ExceptionExitBitmap = 3,
X64MsrExitBitmap = 4,
ProcessorVendor = 4096,
ProcessorFeatures = 4097,
ProcessorClFlushSize = 4098,
ProcessorXsaveFeatures = 4099,
ProcessorClockFrequency = 4100,
InterruptClockFrequency = 4101,
ProcessorFeaturesBanks = 4102,
};
pub const WHvCapabilityCodeHypervisorPresent = WHV_CAPABILITY_CODE.HypervisorPresent;
pub const WHvCapabilityCodeFeatures = WHV_CAPABILITY_CODE.Features;
pub const WHvCapabilityCodeExtendedVmExits = WHV_CAPABILITY_CODE.ExtendedVmExits;
pub const WHvCapabilityCodeExceptionExitBitmap = WHV_CAPABILITY_CODE.ExceptionExitBitmap;
pub const WHvCapabilityCodeX64MsrExitBitmap = WHV_CAPABILITY_CODE.X64MsrExitBitmap;
pub const WHvCapabilityCodeProcessorVendor = WHV_CAPABILITY_CODE.ProcessorVendor;
pub const WHvCapabilityCodeProcessorFeatures = WHV_CAPABILITY_CODE.ProcessorFeatures;
pub const WHvCapabilityCodeProcessorClFlushSize = WHV_CAPABILITY_CODE.ProcessorClFlushSize;
pub const WHvCapabilityCodeProcessorXsaveFeatures = WHV_CAPABILITY_CODE.ProcessorXsaveFeatures;
pub const WHvCapabilityCodeProcessorClockFrequency = WHV_CAPABILITY_CODE.ProcessorClockFrequency;
pub const WHvCapabilityCodeInterruptClockFrequency = WHV_CAPABILITY_CODE.InterruptClockFrequency;
pub const WHvCapabilityCodeProcessorFeaturesBanks = WHV_CAPABILITY_CODE.ProcessorFeaturesBanks;
pub const WHV_CAPABILITY_FEATURES = extern union {
Anonymous: extern struct {
_bitfield: u64,
},
AsUINT64: u64,
};
pub const WHV_EXTENDED_VM_EXITS = extern union {
Anonymous: extern struct {
_bitfield: u64,
},
AsUINT64: u64,
};
pub const WHV_PROCESSOR_VENDOR = enum(i32) {
Amd = 0,
Intel = 1,
Hygon = 2,
};
pub const WHvProcessorVendorAmd = WHV_PROCESSOR_VENDOR.Amd;
pub const WHvProcessorVendorIntel = WHV_PROCESSOR_VENDOR.Intel;
pub const WHvProcessorVendorHygon = WHV_PROCESSOR_VENDOR.Hygon;
pub const WHV_PROCESSOR_FEATURES = extern union {
Anonymous: extern struct {
_bitfield: u64,
},
AsUINT64: u64,
};
pub const WHV_PROCESSOR_FEATURES1 = extern union {
Anonymous: extern struct {
_bitfield: u64,
},
AsUINT64: u64,
};
pub const WHV_PROCESSOR_FEATURES_BANKS = extern struct {
BanksCount: u32,
Reserved0: u32,
Anonymous: extern union {
Anonymous: extern struct {
Bank0: WHV_PROCESSOR_FEATURES,
Bank1: WHV_PROCESSOR_FEATURES1,
},
AsUINT64: [2]u64,
},
};
pub const WHV_PROCESSOR_XSAVE_FEATURES = extern union {
Anonymous: extern struct {
_bitfield: u64,
},
AsUINT64: u64,
};
pub const WHV_X64_MSR_EXIT_BITMAP = extern union {
AsUINT64: u64,
Anonymous: extern struct {
_bitfield: u64,
},
};
pub const WHV_CAPABILITY = extern union {
HypervisorPresent: BOOL,
Features: WHV_CAPABILITY_FEATURES,
ExtendedVmExits: WHV_EXTENDED_VM_EXITS,
ProcessorVendor: WHV_PROCESSOR_VENDOR,
ProcessorFeatures: WHV_PROCESSOR_FEATURES,
ProcessorXsaveFeatures: WHV_PROCESSOR_XSAVE_FEATURES,
ProcessorClFlushSize: u8,
ExceptionExitBitmap: u64,
X64MsrExitBitmap: WHV_X64_MSR_EXIT_BITMAP,
ProcessorClockFrequency: u64,
InterruptClockFrequency: u64,
ProcessorFeaturesBanks: WHV_PROCESSOR_FEATURES_BANKS,
};
pub const WHV_PARTITION_PROPERTY_CODE = enum(i32) {
ExtendedVmExits = 1,
ExceptionExitBitmap = 2,
SeparateSecurityDomain = 3,
NestedVirtualization = 4,
X64MsrExitBitmap = 5,
ProcessorFeatures = 4097,
ProcessorClFlushSize = 4098,
CpuidExitList = 4099,
CpuidResultList = 4100,
LocalApicEmulationMode = 4101,
ProcessorXsaveFeatures = 4102,
ProcessorClockFrequency = 4103,
InterruptClockFrequency = 4104,
ApicRemoteReadSupport = 4105,
ProcessorFeaturesBanks = 4106,
ReferenceTime = 4107,
ProcessorCount = 8191,
};
pub const WHvPartitionPropertyCodeExtendedVmExits = WHV_PARTITION_PROPERTY_CODE.ExtendedVmExits;
pub const WHvPartitionPropertyCodeExceptionExitBitmap = WHV_PARTITION_PROPERTY_CODE.ExceptionExitBitmap;
pub const WHvPartitionPropertyCodeSeparateSecurityDomain = WHV_PARTITION_PROPERTY_CODE.SeparateSecurityDomain;
pub const WHvPartitionPropertyCodeNestedVirtualization = WHV_PARTITION_PROPERTY_CODE.NestedVirtualization;
pub const WHvPartitionPropertyCodeX64MsrExitBitmap = WHV_PARTITION_PROPERTY_CODE.X64MsrExitBitmap;
pub const WHvPartitionPropertyCodeProcessorFeatures = WHV_PARTITION_PROPERTY_CODE.ProcessorFeatures;
pub const WHvPartitionPropertyCodeProcessorClFlushSize = WHV_PARTITION_PROPERTY_CODE.ProcessorClFlushSize;
pub const WHvPartitionPropertyCodeCpuidExitList = WHV_PARTITION_PROPERTY_CODE.CpuidExitList;
pub const WHvPartitionPropertyCodeCpuidResultList = WHV_PARTITION_PROPERTY_CODE.CpuidResultList;
pub const WHvPartitionPropertyCodeLocalApicEmulationMode = WHV_PARTITION_PROPERTY_CODE.LocalApicEmulationMode;
pub const WHvPartitionPropertyCodeProcessorXsaveFeatures = WHV_PARTITION_PROPERTY_CODE.ProcessorXsaveFeatures;
pub const WHvPartitionPropertyCodeProcessorClockFrequency = WHV_PARTITION_PROPERTY_CODE.ProcessorClockFrequency;
pub const WHvPartitionPropertyCodeInterruptClockFrequency = WHV_PARTITION_PROPERTY_CODE.InterruptClockFrequency;
pub const WHvPartitionPropertyCodeApicRemoteReadSupport = WHV_PARTITION_PROPERTY_CODE.ApicRemoteReadSupport;
pub const WHvPartitionPropertyCodeProcessorFeaturesBanks = WHV_PARTITION_PROPERTY_CODE.ProcessorFeaturesBanks;
pub const WHvPartitionPropertyCodeReferenceTime = WHV_PARTITION_PROPERTY_CODE.ReferenceTime;
pub const WHvPartitionPropertyCodeProcessorCount = WHV_PARTITION_PROPERTY_CODE.ProcessorCount;
pub const WHV_X64_CPUID_RESULT = extern struct {
Function: u32,
Reserved: [3]u32,
Eax: u32,
Ebx: u32,
Ecx: u32,
Edx: u32,
};
pub const WHV_EXCEPTION_TYPE = enum(i32) {
DivideErrorFault = 0,
DebugTrapOrFault = 1,
BreakpointTrap = 3,
OverflowTrap = 4,
BoundRangeFault = 5,
InvalidOpcodeFault = 6,
DeviceNotAvailableFault = 7,
DoubleFaultAbort = 8,
InvalidTaskStateSegmentFault = 10,
SegmentNotPresentFault = 11,
StackFault = 12,
GeneralProtectionFault = 13,
PageFault = 14,
FloatingPointErrorFault = 16,
AlignmentCheckFault = 17,
MachineCheckAbort = 18,
SimdFloatingPointFault = 19,
};
pub const WHvX64ExceptionTypeDivideErrorFault = WHV_EXCEPTION_TYPE.DivideErrorFault;
pub const WHvX64ExceptionTypeDebugTrapOrFault = WHV_EXCEPTION_TYPE.DebugTrapOrFault;
pub const WHvX64ExceptionTypeBreakpointTrap = WHV_EXCEPTION_TYPE.BreakpointTrap;
pub const WHvX64ExceptionTypeOverflowTrap = WHV_EXCEPTION_TYPE.OverflowTrap;
pub const WHvX64ExceptionTypeBoundRangeFault = WHV_EXCEPTION_TYPE.BoundRangeFault;
pub const WHvX64ExceptionTypeInvalidOpcodeFault = WHV_EXCEPTION_TYPE.InvalidOpcodeFault;
pub const WHvX64ExceptionTypeDeviceNotAvailableFault = WHV_EXCEPTION_TYPE.DeviceNotAvailableFault;
pub const WHvX64ExceptionTypeDoubleFaultAbort = WHV_EXCEPTION_TYPE.DoubleFaultAbort;
pub const WHvX64ExceptionTypeInvalidTaskStateSegmentFault = WHV_EXCEPTION_TYPE.InvalidTaskStateSegmentFault;
pub const WHvX64ExceptionTypeSegmentNotPresentFault = WHV_EXCEPTION_TYPE.SegmentNotPresentFault;
pub const WHvX64ExceptionTypeStackFault = WHV_EXCEPTION_TYPE.StackFault;
pub const WHvX64ExceptionTypeGeneralProtectionFault = WHV_EXCEPTION_TYPE.GeneralProtectionFault;
pub const WHvX64ExceptionTypePageFault = WHV_EXCEPTION_TYPE.PageFault;
pub const WHvX64ExceptionTypeFloatingPointErrorFault = WHV_EXCEPTION_TYPE.FloatingPointErrorFault;
pub const WHvX64ExceptionTypeAlignmentCheckFault = WHV_EXCEPTION_TYPE.AlignmentCheckFault;
pub const WHvX64ExceptionTypeMachineCheckAbort = WHV_EXCEPTION_TYPE.MachineCheckAbort;
pub const WHvX64ExceptionTypeSimdFloatingPointFault = WHV_EXCEPTION_TYPE.SimdFloatingPointFault;
pub const WHV_X64_LOCAL_APIC_EMULATION_MODE = enum(i32) {
None = 0,
XApic = 1,
X2Apic = 2,
};
pub const WHvX64LocalApicEmulationModeNone = WHV_X64_LOCAL_APIC_EMULATION_MODE.None;
pub const WHvX64LocalApicEmulationModeXApic = WHV_X64_LOCAL_APIC_EMULATION_MODE.XApic;
pub const WHvX64LocalApicEmulationModeX2Apic = WHV_X64_LOCAL_APIC_EMULATION_MODE.X2Apic;
pub const WHV_PARTITION_PROPERTY = extern union {
ExtendedVmExits: WHV_EXTENDED_VM_EXITS,
ProcessorFeatures: WHV_PROCESSOR_FEATURES,
ProcessorXsaveFeatures: WHV_PROCESSOR_XSAVE_FEATURES,
ProcessorClFlushSize: u8,
ProcessorCount: u32,
CpuidExitList: [1]u32,
CpuidResultList: [1]WHV_X64_CPUID_RESULT,
ExceptionExitBitmap: u64,
LocalApicEmulationMode: WHV_X64_LOCAL_APIC_EMULATION_MODE,
SeparateSecurityDomain: BOOL,
NestedVirtualization: BOOL,
X64MsrExitBitmap: WHV_X64_MSR_EXIT_BITMAP,
ProcessorClockFrequency: u64,
InterruptClockFrequency: u64,
ApicRemoteRead: BOOL,
ProcessorFeaturesBanks: WHV_PROCESSOR_FEATURES_BANKS,
ReferenceTime: u64,
};
pub const WHV_MAP_GPA_RANGE_FLAGS = enum(u32) {
None = 0,
Read = 1,
Write = 2,
Execute = 4,
TrackDirtyPages = 8,
_,
pub fn initFlags(o: struct {
None: u1 = 0,
Read: u1 = 0,
Write: u1 = 0,
Execute: u1 = 0,
TrackDirtyPages: u1 = 0,
}) WHV_MAP_GPA_RANGE_FLAGS {
return @intToEnum(WHV_MAP_GPA_RANGE_FLAGS,
(if (o.None == 1) @enumToInt(WHV_MAP_GPA_RANGE_FLAGS.None) else 0)
| (if (o.Read == 1) @enumToInt(WHV_MAP_GPA_RANGE_FLAGS.Read) else 0)
| (if (o.Write == 1) @enumToInt(WHV_MAP_GPA_RANGE_FLAGS.Write) else 0)
| (if (o.Execute == 1) @enumToInt(WHV_MAP_GPA_RANGE_FLAGS.Execute) else 0)
| (if (o.TrackDirtyPages == 1) @enumToInt(WHV_MAP_GPA_RANGE_FLAGS.TrackDirtyPages) else 0)
);
}
};
pub const WHvMapGpaRangeFlagNone = WHV_MAP_GPA_RANGE_FLAGS.None;
pub const WHvMapGpaRangeFlagRead = WHV_MAP_GPA_RANGE_FLAGS.Read;
pub const WHvMapGpaRangeFlagWrite = WHV_MAP_GPA_RANGE_FLAGS.Write;
pub const WHvMapGpaRangeFlagExecute = WHV_MAP_GPA_RANGE_FLAGS.Execute;
pub const WHvMapGpaRangeFlagTrackDirtyPages = WHV_MAP_GPA_RANGE_FLAGS.TrackDirtyPages;
pub const WHV_TRANSLATE_GVA_FLAGS = enum(u32) {
None = 0,
ValidateRead = 1,
ValidateWrite = 2,
ValidateExecute = 4,
PrivilegeExempt = 8,
SetPageTableBits = 16,
_,
pub fn initFlags(o: struct {
None: u1 = 0,
ValidateRead: u1 = 0,
ValidateWrite: u1 = 0,
ValidateExecute: u1 = 0,
PrivilegeExempt: u1 = 0,
SetPageTableBits: u1 = 0,
}) WHV_TRANSLATE_GVA_FLAGS {
return @intToEnum(WHV_TRANSLATE_GVA_FLAGS,
(if (o.None == 1) @enumToInt(WHV_TRANSLATE_GVA_FLAGS.None) else 0)
| (if (o.ValidateRead == 1) @enumToInt(WHV_TRANSLATE_GVA_FLAGS.ValidateRead) else 0)
| (if (o.ValidateWrite == 1) @enumToInt(WHV_TRANSLATE_GVA_FLAGS.ValidateWrite) else 0)
| (if (o.ValidateExecute == 1) @enumToInt(WHV_TRANSLATE_GVA_FLAGS.ValidateExecute) else 0)
| (if (o.PrivilegeExempt == 1) @enumToInt(WHV_TRANSLATE_GVA_FLAGS.PrivilegeExempt) else 0)
| (if (o.SetPageTableBits == 1) @enumToInt(WHV_TRANSLATE_GVA_FLAGS.SetPageTableBits) else 0)
);
}
};
pub const WHvTranslateGvaFlagNone = WHV_TRANSLATE_GVA_FLAGS.None;
pub const WHvTranslateGvaFlagValidateRead = WHV_TRANSLATE_GVA_FLAGS.ValidateRead;
pub const WHvTranslateGvaFlagValidateWrite = WHV_TRANSLATE_GVA_FLAGS.ValidateWrite;
pub const WHvTranslateGvaFlagValidateExecute = WHV_TRANSLATE_GVA_FLAGS.ValidateExecute;
pub const WHvTranslateGvaFlagPrivilegeExempt = WHV_TRANSLATE_GVA_FLAGS.PrivilegeExempt;
pub const WHvTranslateGvaFlagSetPageTableBits = WHV_TRANSLATE_GVA_FLAGS.SetPageTableBits;
pub const WHV_TRANSLATE_GVA_RESULT_CODE = enum(i32) {
Success = 0,
PageNotPresent = 1,
PrivilegeViolation = 2,
InvalidPageTableFlags = 3,
GpaUnmapped = 4,
GpaNoReadAccess = 5,
GpaNoWriteAccess = 6,
GpaIllegalOverlayAccess = 7,
Intercept = 8,
};
pub const WHvTranslateGvaResultSuccess = WHV_TRANSLATE_GVA_RESULT_CODE.Success;
pub const WHvTranslateGvaResultPageNotPresent = WHV_TRANSLATE_GVA_RESULT_CODE.PageNotPresent;
pub const WHvTranslateGvaResultPrivilegeViolation = WHV_TRANSLATE_GVA_RESULT_CODE.PrivilegeViolation;
pub const WHvTranslateGvaResultInvalidPageTableFlags = WHV_TRANSLATE_GVA_RESULT_CODE.InvalidPageTableFlags;
pub const WHvTranslateGvaResultGpaUnmapped = WHV_TRANSLATE_GVA_RESULT_CODE.GpaUnmapped;
pub const WHvTranslateGvaResultGpaNoReadAccess = WHV_TRANSLATE_GVA_RESULT_CODE.GpaNoReadAccess;
pub const WHvTranslateGvaResultGpaNoWriteAccess = WHV_TRANSLATE_GVA_RESULT_CODE.GpaNoWriteAccess;
pub const WHvTranslateGvaResultGpaIllegalOverlayAccess = WHV_TRANSLATE_GVA_RESULT_CODE.GpaIllegalOverlayAccess;
pub const WHvTranslateGvaResultIntercept = WHV_TRANSLATE_GVA_RESULT_CODE.Intercept;
pub const WHV_TRANSLATE_GVA_RESULT = extern struct {
ResultCode: WHV_TRANSLATE_GVA_RESULT_CODE,
Reserved: u32,
};
pub const WHV_REGISTER_NAME = enum(i32) {
X64RegisterRax = 0,
X64RegisterRcx = 1,
X64RegisterRdx = 2,
X64RegisterRbx = 3,
X64RegisterRsp = 4,
X64RegisterRbp = 5,
X64RegisterRsi = 6,
X64RegisterRdi = 7,
X64RegisterR8 = 8,
X64RegisterR9 = 9,
X64RegisterR10 = 10,
X64RegisterR11 = 11,
X64RegisterR12 = 12,
X64RegisterR13 = 13,
X64RegisterR14 = 14,
X64RegisterR15 = 15,
X64RegisterRip = 16,
X64RegisterRflags = 17,
X64RegisterEs = 18,
X64RegisterCs = 19,
X64RegisterSs = 20,
X64RegisterDs = 21,
X64RegisterFs = 22,
X64RegisterGs = 23,
X64RegisterLdtr = 24,
X64RegisterTr = 25,
X64RegisterIdtr = 26,
X64RegisterGdtr = 27,
X64RegisterCr0 = 28,
X64RegisterCr2 = 29,
X64RegisterCr3 = 30,
X64RegisterCr4 = 31,
X64RegisterCr8 = 32,
X64RegisterDr0 = 33,
X64RegisterDr1 = 34,
X64RegisterDr2 = 35,
X64RegisterDr3 = 36,
X64RegisterDr6 = 37,
X64RegisterDr7 = 38,
X64RegisterXCr0 = 39,
X64RegisterXmm0 = 4096,
X64RegisterXmm1 = 4097,
X64RegisterXmm2 = 4098,
X64RegisterXmm3 = 4099,
X64RegisterXmm4 = 4100,
X64RegisterXmm5 = 4101,
X64RegisterXmm6 = 4102,
X64RegisterXmm7 = 4103,
X64RegisterXmm8 = 4104,
X64RegisterXmm9 = 4105,
X64RegisterXmm10 = 4106,
X64RegisterXmm11 = 4107,
X64RegisterXmm12 = 4108,
X64RegisterXmm13 = 4109,
X64RegisterXmm14 = 4110,
X64RegisterXmm15 = 4111,
X64RegisterFpMmx0 = 4112,
X64RegisterFpMmx1 = 4113,
X64RegisterFpMmx2 = 4114,
X64RegisterFpMmx3 = 4115,
X64RegisterFpMmx4 = 4116,
X64RegisterFpMmx5 = 4117,
X64RegisterFpMmx6 = 4118,
X64RegisterFpMmx7 = 4119,
X64RegisterFpControlStatus = 4120,
X64RegisterXmmControlStatus = 4121,
X64RegisterTsc = 8192,
X64RegisterEfer = 8193,
X64RegisterKernelGsBase = 8194,
X64RegisterApicBase = 8195,
X64RegisterPat = 8196,
X64RegisterSysenterCs = 8197,
X64RegisterSysenterEip = 8198,
X64RegisterSysenterEsp = 8199,
X64RegisterStar = 8200,
X64RegisterLstar = 8201,
X64RegisterCstar = 8202,
X64RegisterSfmask = 8203,
X64RegisterInitialApicId = 8204,
X64RegisterMsrMtrrCap = 8205,
X64RegisterMsrMtrrDefType = 8206,
X64RegisterMsrMtrrPhysBase0 = 8208,
X64RegisterMsrMtrrPhysBase1 = 8209,
X64RegisterMsrMtrrPhysBase2 = 8210,
X64RegisterMsrMtrrPhysBase3 = 8211,
X64RegisterMsrMtrrPhysBase4 = 8212,
X64RegisterMsrMtrrPhysBase5 = 8213,
X64RegisterMsrMtrrPhysBase6 = 8214,
X64RegisterMsrMtrrPhysBase7 = 8215,
X64RegisterMsrMtrrPhysBase8 = 8216,
X64RegisterMsrMtrrPhysBase9 = 8217,
X64RegisterMsrMtrrPhysBaseA = 8218,
X64RegisterMsrMtrrPhysBaseB = 8219,
X64RegisterMsrMtrrPhysBaseC = 8220,
X64RegisterMsrMtrrPhysBaseD = 8221,
X64RegisterMsrMtrrPhysBaseE = 8222,
X64RegisterMsrMtrrPhysBaseF = 8223,
X64RegisterMsrMtrrPhysMask0 = 8256,
X64RegisterMsrMtrrPhysMask1 = 8257,
X64RegisterMsrMtrrPhysMask2 = 8258,
X64RegisterMsrMtrrPhysMask3 = 8259,
X64RegisterMsrMtrrPhysMask4 = 8260,
X64RegisterMsrMtrrPhysMask5 = 8261,
X64RegisterMsrMtrrPhysMask6 = 8262,
X64RegisterMsrMtrrPhysMask7 = 8263,
X64RegisterMsrMtrrPhysMask8 = 8264,
X64RegisterMsrMtrrPhysMask9 = 8265,
X64RegisterMsrMtrrPhysMaskA = 8266,
X64RegisterMsrMtrrPhysMaskB = 8267,
X64RegisterMsrMtrrPhysMaskC = 8268,
X64RegisterMsrMtrrPhysMaskD = 8269,
X64RegisterMsrMtrrPhysMaskE = 8270,
X64RegisterMsrMtrrPhysMaskF = 8271,
X64RegisterMsrMtrrFix64k00000 = 8304,
X64RegisterMsrMtrrFix16k80000 = 8305,
X64RegisterMsrMtrrFix16kA0000 = 8306,
X64RegisterMsrMtrrFix4kC0000 = 8307,
X64RegisterMsrMtrrFix4kC8000 = 8308,
X64RegisterMsrMtrrFix4kD0000 = 8309,
X64RegisterMsrMtrrFix4kD8000 = 8310,
X64RegisterMsrMtrrFix4kE0000 = 8311,
X64RegisterMsrMtrrFix4kE8000 = 8312,
X64RegisterMsrMtrrFix4kF0000 = 8313,
X64RegisterMsrMtrrFix4kF8000 = 8314,
X64RegisterTscAux = 8315,
X64RegisterSpecCtrl = 8324,
X64RegisterPredCmd = 8325,
X64RegisterTscVirtualOffset = 8327,
X64RegisterApicId = 12290,
X64RegisterApicVersion = 12291,
RegisterPendingInterruption = -2147483648,
RegisterInterruptState = -2147483647,
RegisterPendingEvent = -2147483646,
X64RegisterDeliverabilityNotifications = -2147483644,
RegisterInternalActivityState = -2147483643,
X64RegisterPendingDebugException = -2147483642,
};
pub const WHvX64RegisterRax = WHV_REGISTER_NAME.X64RegisterRax;
pub const WHvX64RegisterRcx = WHV_REGISTER_NAME.X64RegisterRcx;
pub const WHvX64RegisterRdx = WHV_REGISTER_NAME.X64RegisterRdx;
pub const WHvX64RegisterRbx = WHV_REGISTER_NAME.X64RegisterRbx;
pub const WHvX64RegisterRsp = WHV_REGISTER_NAME.X64RegisterRsp;
pub const WHvX64RegisterRbp = WHV_REGISTER_NAME.X64RegisterRbp;
pub const WHvX64RegisterRsi = WHV_REGISTER_NAME.X64RegisterRsi;
pub const WHvX64RegisterRdi = WHV_REGISTER_NAME.X64RegisterRdi;
pub const WHvX64RegisterR8 = WHV_REGISTER_NAME.X64RegisterR8;
pub const WHvX64RegisterR9 = WHV_REGISTER_NAME.X64RegisterR9;
pub const WHvX64RegisterR10 = WHV_REGISTER_NAME.X64RegisterR10;
pub const WHvX64RegisterR11 = WHV_REGISTER_NAME.X64RegisterR11;
pub const WHvX64RegisterR12 = WHV_REGISTER_NAME.X64RegisterR12;
pub const WHvX64RegisterR13 = WHV_REGISTER_NAME.X64RegisterR13;
pub const WHvX64RegisterR14 = WHV_REGISTER_NAME.X64RegisterR14;
pub const WHvX64RegisterR15 = WHV_REGISTER_NAME.X64RegisterR15;
pub const WHvX64RegisterRip = WHV_REGISTER_NAME.X64RegisterRip;
pub const WHvX64RegisterRflags = WHV_REGISTER_NAME.X64RegisterRflags;
pub const WHvX64RegisterEs = WHV_REGISTER_NAME.X64RegisterEs;
pub const WHvX64RegisterCs = WHV_REGISTER_NAME.X64RegisterCs;
pub const WHvX64RegisterSs = WHV_REGISTER_NAME.X64RegisterSs;
pub const WHvX64RegisterDs = WHV_REGISTER_NAME.X64RegisterDs;
pub const WHvX64RegisterFs = WHV_REGISTER_NAME.X64RegisterFs;
pub const WHvX64RegisterGs = WHV_REGISTER_NAME.X64RegisterGs;
pub const WHvX64RegisterLdtr = WHV_REGISTER_NAME.X64RegisterLdtr;
pub const WHvX64RegisterTr = WHV_REGISTER_NAME.X64RegisterTr;
pub const WHvX64RegisterIdtr = WHV_REGISTER_NAME.X64RegisterIdtr;
pub const WHvX64RegisterGdtr = WHV_REGISTER_NAME.X64RegisterGdtr;
pub const WHvX64RegisterCr0 = WHV_REGISTER_NAME.X64RegisterCr0;
pub const WHvX64RegisterCr2 = WHV_REGISTER_NAME.X64RegisterCr2;
pub const WHvX64RegisterCr3 = WHV_REGISTER_NAME.X64RegisterCr3;
pub const WHvX64RegisterCr4 = WHV_REGISTER_NAME.X64RegisterCr4;
pub const WHvX64RegisterCr8 = WHV_REGISTER_NAME.X64RegisterCr8;
pub const WHvX64RegisterDr0 = WHV_REGISTER_NAME.X64RegisterDr0;
pub const WHvX64RegisterDr1 = WHV_REGISTER_NAME.X64RegisterDr1;
pub const WHvX64RegisterDr2 = WHV_REGISTER_NAME.X64RegisterDr2;
pub const WHvX64RegisterDr3 = WHV_REGISTER_NAME.X64RegisterDr3;
pub const WHvX64RegisterDr6 = WHV_REGISTER_NAME.X64RegisterDr6;
pub const WHvX64RegisterDr7 = WHV_REGISTER_NAME.X64RegisterDr7;
pub const WHvX64RegisterXCr0 = WHV_REGISTER_NAME.X64RegisterXCr0;
pub const WHvX64RegisterXmm0 = WHV_REGISTER_NAME.X64RegisterXmm0;
pub const WHvX64RegisterXmm1 = WHV_REGISTER_NAME.X64RegisterXmm1;
pub const WHvX64RegisterXmm2 = WHV_REGISTER_NAME.X64RegisterXmm2;
pub const WHvX64RegisterXmm3 = WHV_REGISTER_NAME.X64RegisterXmm3;
pub const WHvX64RegisterXmm4 = WHV_REGISTER_NAME.X64RegisterXmm4;
pub const WHvX64RegisterXmm5 = WHV_REGISTER_NAME.X64RegisterXmm5;
pub const WHvX64RegisterXmm6 = WHV_REGISTER_NAME.X64RegisterXmm6;
pub const WHvX64RegisterXmm7 = WHV_REGISTER_NAME.X64RegisterXmm7;
pub const WHvX64RegisterXmm8 = WHV_REGISTER_NAME.X64RegisterXmm8;
pub const WHvX64RegisterXmm9 = WHV_REGISTER_NAME.X64RegisterXmm9;
pub const WHvX64RegisterXmm10 = WHV_REGISTER_NAME.X64RegisterXmm10;
pub const WHvX64RegisterXmm11 = WHV_REGISTER_NAME.X64RegisterXmm11;
pub const WHvX64RegisterXmm12 = WHV_REGISTER_NAME.X64RegisterXmm12;
pub const WHvX64RegisterXmm13 = WHV_REGISTER_NAME.X64RegisterXmm13;
pub const WHvX64RegisterXmm14 = WHV_REGISTER_NAME.X64RegisterXmm14;
pub const WHvX64RegisterXmm15 = WHV_REGISTER_NAME.X64RegisterXmm15;
pub const WHvX64RegisterFpMmx0 = WHV_REGISTER_NAME.X64RegisterFpMmx0;
pub const WHvX64RegisterFpMmx1 = WHV_REGISTER_NAME.X64RegisterFpMmx1;
pub const WHvX64RegisterFpMmx2 = WHV_REGISTER_NAME.X64RegisterFpMmx2;
pub const WHvX64RegisterFpMmx3 = WHV_REGISTER_NAME.X64RegisterFpMmx3;
pub const WHvX64RegisterFpMmx4 = WHV_REGISTER_NAME.X64RegisterFpMmx4;
pub const WHvX64RegisterFpMmx5 = WHV_REGISTER_NAME.X64RegisterFpMmx5;
pub const WHvX64RegisterFpMmx6 = WHV_REGISTER_NAME.X64RegisterFpMmx6;
pub const WHvX64RegisterFpMmx7 = WHV_REGISTER_NAME.X64RegisterFpMmx7;
pub const WHvX64RegisterFpControlStatus = WHV_REGISTER_NAME.X64RegisterFpControlStatus;
pub const WHvX64RegisterXmmControlStatus = WHV_REGISTER_NAME.X64RegisterXmmControlStatus;
pub const WHvX64RegisterTsc = WHV_REGISTER_NAME.X64RegisterTsc;
pub const WHvX64RegisterEfer = WHV_REGISTER_NAME.X64RegisterEfer;
pub const WHvX64RegisterKernelGsBase = WHV_REGISTER_NAME.X64RegisterKernelGsBase;
pub const WHvX64RegisterApicBase = WHV_REGISTER_NAME.X64RegisterApicBase;
pub const WHvX64RegisterPat = WHV_REGISTER_NAME.X64RegisterPat;
pub const WHvX64RegisterSysenterCs = WHV_REGISTER_NAME.X64RegisterSysenterCs;
pub const WHvX64RegisterSysenterEip = WHV_REGISTER_NAME.X64RegisterSysenterEip;
pub const WHvX64RegisterSysenterEsp = WHV_REGISTER_NAME.X64RegisterSysenterEsp;
pub const WHvX64RegisterStar = WHV_REGISTER_NAME.X64RegisterStar;
pub const WHvX64RegisterLstar = WHV_REGISTER_NAME.X64RegisterLstar;
pub const WHvX64RegisterCstar = WHV_REGISTER_NAME.X64RegisterCstar;
pub const WHvX64RegisterSfmask = WHV_REGISTER_NAME.X64RegisterSfmask;
pub const WHvX64RegisterInitialApicId = WHV_REGISTER_NAME.X64RegisterInitialApicId;
pub const WHvX64RegisterMsrMtrrCap = WHV_REGISTER_NAME.X64RegisterMsrMtrrCap;
pub const WHvX64RegisterMsrMtrrDefType = WHV_REGISTER_NAME.X64RegisterMsrMtrrDefType;
pub const WHvX64RegisterMsrMtrrPhysBase0 = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysBase0;
pub const WHvX64RegisterMsrMtrrPhysBase1 = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysBase1;
pub const WHvX64RegisterMsrMtrrPhysBase2 = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysBase2;
pub const WHvX64RegisterMsrMtrrPhysBase3 = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysBase3;
pub const WHvX64RegisterMsrMtrrPhysBase4 = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysBase4;
pub const WHvX64RegisterMsrMtrrPhysBase5 = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysBase5;
pub const WHvX64RegisterMsrMtrrPhysBase6 = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysBase6;
pub const WHvX64RegisterMsrMtrrPhysBase7 = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysBase7;
pub const WHvX64RegisterMsrMtrrPhysBase8 = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysBase8;
pub const WHvX64RegisterMsrMtrrPhysBase9 = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysBase9;
pub const WHvX64RegisterMsrMtrrPhysBaseA = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysBaseA;
pub const WHvX64RegisterMsrMtrrPhysBaseB = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysBaseB;
pub const WHvX64RegisterMsrMtrrPhysBaseC = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysBaseC;
pub const WHvX64RegisterMsrMtrrPhysBaseD = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysBaseD;
pub const WHvX64RegisterMsrMtrrPhysBaseE = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysBaseE;
pub const WHvX64RegisterMsrMtrrPhysBaseF = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysBaseF;
pub const WHvX64RegisterMsrMtrrPhysMask0 = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysMask0;
pub const WHvX64RegisterMsrMtrrPhysMask1 = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysMask1;
pub const WHvX64RegisterMsrMtrrPhysMask2 = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysMask2;
pub const WHvX64RegisterMsrMtrrPhysMask3 = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysMask3;
pub const WHvX64RegisterMsrMtrrPhysMask4 = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysMask4;
pub const WHvX64RegisterMsrMtrrPhysMask5 = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysMask5;
pub const WHvX64RegisterMsrMtrrPhysMask6 = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysMask6;
pub const WHvX64RegisterMsrMtrrPhysMask7 = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysMask7;
pub const WHvX64RegisterMsrMtrrPhysMask8 = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysMask8;
pub const WHvX64RegisterMsrMtrrPhysMask9 = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysMask9;
pub const WHvX64RegisterMsrMtrrPhysMaskA = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysMaskA;
pub const WHvX64RegisterMsrMtrrPhysMaskB = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysMaskB;
pub const WHvX64RegisterMsrMtrrPhysMaskC = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysMaskC;
pub const WHvX64RegisterMsrMtrrPhysMaskD = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysMaskD;
pub const WHvX64RegisterMsrMtrrPhysMaskE = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysMaskE;
pub const WHvX64RegisterMsrMtrrPhysMaskF = WHV_REGISTER_NAME.X64RegisterMsrMtrrPhysMaskF;
pub const WHvX64RegisterMsrMtrrFix64k00000 = WHV_REGISTER_NAME.X64RegisterMsrMtrrFix64k00000;
pub const WHvX64RegisterMsrMtrrFix16k80000 = WHV_REGISTER_NAME.X64RegisterMsrMtrrFix16k80000;
pub const WHvX64RegisterMsrMtrrFix16kA0000 = WHV_REGISTER_NAME.X64RegisterMsrMtrrFix16kA0000;
pub const WHvX64RegisterMsrMtrrFix4kC0000 = WHV_REGISTER_NAME.X64RegisterMsrMtrrFix4kC0000;
pub const WHvX64RegisterMsrMtrrFix4kC8000 = WHV_REGISTER_NAME.X64RegisterMsrMtrrFix4kC8000;
pub const WHvX64RegisterMsrMtrrFix4kD0000 = WHV_REGISTER_NAME.X64RegisterMsrMtrrFix4kD0000;
pub const WHvX64RegisterMsrMtrrFix4kD8000 = WHV_REGISTER_NAME.X64RegisterMsrMtrrFix4kD8000;
pub const WHvX64RegisterMsrMtrrFix4kE0000 = WHV_REGISTER_NAME.X64RegisterMsrMtrrFix4kE0000;
pub const WHvX64RegisterMsrMtrrFix4kE8000 = WHV_REGISTER_NAME.X64RegisterMsrMtrrFix4kE8000;
pub const WHvX64RegisterMsrMtrrFix4kF0000 = WHV_REGISTER_NAME.X64RegisterMsrMtrrFix4kF0000;
pub const WHvX64RegisterMsrMtrrFix4kF8000 = WHV_REGISTER_NAME.X64RegisterMsrMtrrFix4kF8000;
pub const WHvX64RegisterTscAux = WHV_REGISTER_NAME.X64RegisterTscAux;
pub const WHvX64RegisterSpecCtrl = WHV_REGISTER_NAME.X64RegisterSpecCtrl;
pub const WHvX64RegisterPredCmd = WHV_REGISTER_NAME.X64RegisterPredCmd;
pub const WHvX64RegisterTscVirtualOffset = WHV_REGISTER_NAME.X64RegisterTscVirtualOffset;
pub const WHvX64RegisterApicId = WHV_REGISTER_NAME.X64RegisterApicId;
pub const WHvX64RegisterApicVersion = WHV_REGISTER_NAME.X64RegisterApicVersion;
pub const WHvRegisterPendingInterruption = WHV_REGISTER_NAME.RegisterPendingInterruption;
pub const WHvRegisterInterruptState = WHV_REGISTER_NAME.RegisterInterruptState;
pub const WHvRegisterPendingEvent = WHV_REGISTER_NAME.RegisterPendingEvent;
pub const WHvX64RegisterDeliverabilityNotifications = WHV_REGISTER_NAME.X64RegisterDeliverabilityNotifications;
pub const WHvRegisterInternalActivityState = WHV_REGISTER_NAME.RegisterInternalActivityState;
pub const WHvX64RegisterPendingDebugException = WHV_REGISTER_NAME.X64RegisterPendingDebugException;
pub const WHV_UINT128 = extern union {
Anonymous: extern struct {
Low64: u64,
High64: u64,
},
Dword: [4]u32,
};
pub const WHV_X64_FP_REGISTER = extern union {
Anonymous: extern struct {
Mantissa: u64,
_bitfield: u64,
},
AsUINT128: WHV_UINT128,
};
pub const WHV_X64_FP_CONTROL_STATUS_REGISTER = extern union {
Anonymous: extern struct {
FpControl: u16,
FpStatus: u16,
FpTag: u8,
Reserved: u8,
LastFpOp: u16,
Anonymous: extern union {
LastFpRip: u64,
Anonymous: extern struct {
LastFpEip: u32,
LastFpCs: u16,
Reserved2: u16,
},
},
},
AsUINT128: WHV_UINT128,
};
pub const WHV_X64_XMM_CONTROL_STATUS_REGISTER = extern union {
Anonymous: extern struct {
Anonymous: extern union {
LastFpRdp: u64,
Anonymous: extern struct {
LastFpDp: u32,
LastFpDs: u16,
Reserved: u16,
},
},
XmmStatusControl: u32,
XmmStatusControlMask: u32,
},
AsUINT128: WHV_UINT128,
};
pub const WHV_X64_SEGMENT_REGISTER = extern struct {
Base: u64,
Limit: u32,
Selector: u16,
Anonymous: extern union {
Anonymous: extern struct {
_bitfield: u16,
},
Attributes: u16,
},
};
pub const WHV_X64_TABLE_REGISTER = extern struct {
Pad: [3]u16,
Limit: u16,
Base: u64,
};
pub const WHV_X64_INTERRUPT_STATE_REGISTER = extern union {
Anonymous: extern struct {
_bitfield: u64,
},
AsUINT64: u64,
};
pub const WHV_X64_PENDING_INTERRUPTION_REGISTER = extern union {
Anonymous: extern struct {
_bitfield: u32,
ErrorCode: u32,
},
AsUINT64: u64,
};
pub const WHV_X64_DELIVERABILITY_NOTIFICATIONS_REGISTER = extern union {
Anonymous: extern struct {
_bitfield: u64,
},
AsUINT64: u64,
};
pub const WHV_X64_PENDING_EVENT_TYPE = enum(i32) {
ception = 0,
tInt = 5,
};
pub const WHvX64PendingEventException = WHV_X64_PENDING_EVENT_TYPE.ception;
pub const WHvX64PendingEventExtInt = WHV_X64_PENDING_EVENT_TYPE.tInt;
pub const WHV_X64_PENDING_EXCEPTION_EVENT = extern union {
Anonymous: extern struct {
_bitfield: u32,
ErrorCode: u32,
ExceptionParameter: u64,
},
AsUINT128: WHV_UINT128,
};
pub const WHV_X64_PENDING_EXT_INT_EVENT = extern union {
Anonymous: extern struct {
_bitfield: u64,
Reserved2: u64,
},
AsUINT128: WHV_UINT128,
};
pub const WHV_INTERNAL_ACTIVITY_REGISTER = extern union {
Anonymous: extern struct {
_bitfield: u64,
},
AsUINT64: u64,
};
pub const WHV_X64_PENDING_DEBUG_EXCEPTION = extern union {
AsUINT64: u64,
Anonymous: extern struct {
_bitfield: u64,
},
};
pub const WHV_REGISTER_VALUE = extern union {
Reg128: WHV_UINT128,
Reg64: u64,
Reg32: u32,
Reg16: u16,
Reg8: u8,
Fp: WHV_X64_FP_REGISTER,
FpControlStatus: WHV_X64_FP_CONTROL_STATUS_REGISTER,
XmmControlStatus: WHV_X64_XMM_CONTROL_STATUS_REGISTER,
Segment: WHV_X64_SEGMENT_REGISTER,
Table: WHV_X64_TABLE_REGISTER,
InterruptState: WHV_X64_INTERRUPT_STATE_REGISTER,
PendingInterruption: WHV_X64_PENDING_INTERRUPTION_REGISTER,
DeliverabilityNotifications: WHV_X64_DELIVERABILITY_NOTIFICATIONS_REGISTER,
ExceptionEvent: WHV_X64_PENDING_EXCEPTION_EVENT,
ExtIntEvent: WHV_X64_PENDING_EXT_INT_EVENT,
InternalActivity: WHV_INTERNAL_ACTIVITY_REGISTER,
PendingDebugException: WHV_X64_PENDING_DEBUG_EXCEPTION,
};
pub const WHV_RUN_VP_EXIT_REASON = enum(i32) {
None = 0,
MemoryAccess = 1,
X64IoPortAccess = 2,
UnrecoverableException = 4,
InvalidVpRegisterValue = 5,
UnsupportedFeature = 6,
X64InterruptWindow = 7,
X64Halt = 8,
X64ApicEoi = 9,
X64MsrAccess = 4096,
X64Cpuid = 4097,
Exception = 4098,
X64Rdtsc = 4099,
X64ApicSmiTrap = 4100,
Hypercall = 4101,
X64ApicInitSipiTrap = 4102,
Canceled = 8193,
};
pub const WHvRunVpExitReasonNone = WHV_RUN_VP_EXIT_REASON.None;
pub const WHvRunVpExitReasonMemoryAccess = WHV_RUN_VP_EXIT_REASON.MemoryAccess;
pub const WHvRunVpExitReasonX64IoPortAccess = WHV_RUN_VP_EXIT_REASON.X64IoPortAccess;
pub const WHvRunVpExitReasonUnrecoverableException = WHV_RUN_VP_EXIT_REASON.UnrecoverableException;
pub const WHvRunVpExitReasonInvalidVpRegisterValue = WHV_RUN_VP_EXIT_REASON.InvalidVpRegisterValue;
pub const WHvRunVpExitReasonUnsupportedFeature = WHV_RUN_VP_EXIT_REASON.UnsupportedFeature;
pub const WHvRunVpExitReasonX64InterruptWindow = WHV_RUN_VP_EXIT_REASON.X64InterruptWindow;
pub const WHvRunVpExitReasonX64Halt = WHV_RUN_VP_EXIT_REASON.X64Halt;
pub const WHvRunVpExitReasonX64ApicEoi = WHV_RUN_VP_EXIT_REASON.X64ApicEoi;
pub const WHvRunVpExitReasonX64MsrAccess = WHV_RUN_VP_EXIT_REASON.X64MsrAccess;
pub const WHvRunVpExitReasonX64Cpuid = WHV_RUN_VP_EXIT_REASON.X64Cpuid;
pub const WHvRunVpExitReasonException = WHV_RUN_VP_EXIT_REASON.Exception;
pub const WHvRunVpExitReasonX64Rdtsc = WHV_RUN_VP_EXIT_REASON.X64Rdtsc;
pub const WHvRunVpExitReasonX64ApicSmiTrap = WHV_RUN_VP_EXIT_REASON.X64ApicSmiTrap;
pub const WHvRunVpExitReasonHypercall = WHV_RUN_VP_EXIT_REASON.Hypercall;
pub const WHvRunVpExitReasonX64ApicInitSipiTrap = WHV_RUN_VP_EXIT_REASON.X64ApicInitSipiTrap;
pub const WHvRunVpExitReasonCanceled = WHV_RUN_VP_EXIT_REASON.Canceled;
pub const WHV_X64_VP_EXECUTION_STATE = extern union {
Anonymous: extern struct {
_bitfield: u16,
},
AsUINT16: u16,
};
pub const WHV_VP_EXIT_CONTEXT = extern struct {
ExecutionState: WHV_X64_VP_EXECUTION_STATE,
_bitfield: u8,
Reserved: u8,
Reserved2: u32,
Cs: WHV_X64_SEGMENT_REGISTER,
Rip: u64,
Rflags: u64,
};
pub const WHV_MEMORY_ACCESS_TYPE = enum(i32) {
Read = 0,
Write = 1,
Execute = 2,
};
pub const WHvMemoryAccessRead = WHV_MEMORY_ACCESS_TYPE.Read;
pub const WHvMemoryAccessWrite = WHV_MEMORY_ACCESS_TYPE.Write;
pub const WHvMemoryAccessExecute = WHV_MEMORY_ACCESS_TYPE.Execute;
pub const WHV_MEMORY_ACCESS_INFO = extern union {
Anonymous: extern struct {
_bitfield: u32,
},
AsUINT32: u32,
};
pub const WHV_MEMORY_ACCESS_CONTEXT = extern struct {
InstructionByteCount: u8,
Reserved: [3]u8,
InstructionBytes: [16]u8,
AccessInfo: WHV_MEMORY_ACCESS_INFO,
Gpa: u64,
Gva: u64,
};
pub const WHV_X64_IO_PORT_ACCESS_INFO = extern union {
Anonymous: extern struct {
_bitfield: u32,
},
AsUINT32: u32,
};
pub const WHV_X64_IO_PORT_ACCESS_CONTEXT = extern struct {
InstructionByteCount: u8,
Reserved: [3]u8,
InstructionBytes: [16]u8,
AccessInfo: WHV_X64_IO_PORT_ACCESS_INFO,
PortNumber: u16,
Reserved2: [3]u16,
Rax: u64,
Rcx: u64,
Rsi: u64,
Rdi: u64,
Ds: WHV_X64_SEGMENT_REGISTER,
Es: WHV_X64_SEGMENT_REGISTER,
};
pub const WHV_X64_MSR_ACCESS_INFO = extern union {
Anonymous: extern struct {
_bitfield: u32,
},
AsUINT32: u32,
};
pub const WHV_X64_MSR_ACCESS_CONTEXT = extern struct {
AccessInfo: WHV_X64_MSR_ACCESS_INFO,
MsrNumber: u32,
Rax: u64,
Rdx: u64,
};
pub const WHV_X64_CPUID_ACCESS_CONTEXT = extern struct {
Rax: u64,
Rcx: u64,
Rdx: u64,
Rbx: u64,
DefaultResultRax: u64,
DefaultResultRcx: u64,
DefaultResultRdx: u64,
DefaultResultRbx: u64,
};
pub const WHV_VP_EXCEPTION_INFO = extern union {
Anonymous: extern struct {
_bitfield: u32,
},
AsUINT32: u32,
};
pub const WHV_VP_EXCEPTION_CONTEXT = extern struct {
InstructionByteCount: u8,
Reserved: [3]u8,
InstructionBytes: [16]u8,
ExceptionInfo: WHV_VP_EXCEPTION_INFO,
ExceptionType: u8,
Reserved2: [3]u8,
ErrorCode: u32,
ExceptionParameter: u64,
};
pub const WHV_X64_UNSUPPORTED_FEATURE_CODE = enum(i32) {
Intercept = 1,
TaskSwitchTss = 2,
};
pub const WHvUnsupportedFeatureIntercept = WHV_X64_UNSUPPORTED_FEATURE_CODE.Intercept;
pub const WHvUnsupportedFeatureTaskSwitchTss = WHV_X64_UNSUPPORTED_FEATURE_CODE.TaskSwitchTss;
pub const WHV_X64_UNSUPPORTED_FEATURE_CONTEXT = extern struct {
FeatureCode: WHV_X64_UNSUPPORTED_FEATURE_CODE,
Reserved: u32,
FeatureParameter: u64,
};
pub const WHV_RUN_VP_CANCEL_REASON = enum(i32) {
r = 0,
};
pub const WHvRunVpCancelReasonUser = WHV_RUN_VP_CANCEL_REASON.r;
pub const WHV_RUN_VP_CANCELED_CONTEXT = extern struct {
CancelReason: WHV_RUN_VP_CANCEL_REASON,
};
pub const WHV_X64_PENDING_INTERRUPTION_TYPE = enum(i32) {
Interrupt = 0,
Nmi = 2,
Exception = 3,
};
pub const WHvX64PendingInterrupt = WHV_X64_PENDING_INTERRUPTION_TYPE.Interrupt;
pub const WHvX64PendingNmi = WHV_X64_PENDING_INTERRUPTION_TYPE.Nmi;
pub const WHvX64PendingException = WHV_X64_PENDING_INTERRUPTION_TYPE.Exception;
pub const WHV_X64_INTERRUPTION_DELIVERABLE_CONTEXT = extern struct {
DeliverableType: WHV_X64_PENDING_INTERRUPTION_TYPE,
};
pub const WHV_X64_APIC_EOI_CONTEXT = extern struct {
InterruptVector: u32,
};
pub const WHV_X64_RDTSC_INFO = extern union {
Anonymous: extern struct {
_bitfield: u64,
},
AsUINT64: u64,
};
pub const WHV_X64_RDTSC_CONTEXT = extern struct {
TscAux: u64,
VirtualOffset: u64,
Tsc: u64,
ReferenceTime: u64,
RdtscInfo: WHV_X64_RDTSC_INFO,
};
pub const WHV_X64_APIC_SMI_CONTEXT = extern struct {
ApicIcr: u64,
};
pub const WHV_HYPERCALL_CONTEXT = extern struct {
Rax: u64,
Rbx: u64,
Rcx: u64,
Rdx: u64,
R8: u64,
Rsi: u64,
Rdi: u64,
Reserved0: u64,
XmmRegisters: [6]WHV_UINT128,
Reserved1: [2]u64,
};
pub const WHV_X64_APIC_INIT_SIPI_CONTEXT = extern struct {
ApicIcr: u64,
};
pub const WHV_RUN_VP_EXIT_CONTEXT = extern struct {
ExitReason: WHV_RUN_VP_EXIT_REASON,
Reserved: u32,
VpContext: WHV_VP_EXIT_CONTEXT,
Anonymous: extern union {
MemoryAccess: WHV_MEMORY_ACCESS_CONTEXT,
IoPortAccess: WHV_X64_IO_PORT_ACCESS_CONTEXT,
MsrAccess: WHV_X64_MSR_ACCESS_CONTEXT,
CpuidAccess: WHV_X64_CPUID_ACCESS_CONTEXT,
VpException: WHV_VP_EXCEPTION_CONTEXT,
InterruptWindow: WHV_X64_INTERRUPTION_DELIVERABLE_CONTEXT,
UnsupportedFeature: WHV_X64_UNSUPPORTED_FEATURE_CONTEXT,
CancelReason: WHV_RUN_VP_CANCELED_CONTEXT,
ApicEoi: WHV_X64_APIC_EOI_CONTEXT,
ReadTsc: WHV_X64_RDTSC_CONTEXT,
ApicSmi: WHV_X64_APIC_SMI_CONTEXT,
Hypercall: WHV_HYPERCALL_CONTEXT,
ApicInitSipi: WHV_X64_APIC_INIT_SIPI_CONTEXT,
},
};
pub const WHV_INTERRUPT_TYPE = enum(i32) {
Fixed = 0,
LowestPriority = 1,
Nmi = 4,
Init = 5,
Sipi = 6,
LocalInt1 = 9,
};
pub const WHvX64InterruptTypeFixed = WHV_INTERRUPT_TYPE.Fixed;
pub const WHvX64InterruptTypeLowestPriority = WHV_INTERRUPT_TYPE.LowestPriority;
pub const WHvX64InterruptTypeNmi = WHV_INTERRUPT_TYPE.Nmi;
pub const WHvX64InterruptTypeInit = WHV_INTERRUPT_TYPE.Init;
pub const WHvX64InterruptTypeSipi = WHV_INTERRUPT_TYPE.Sipi;
pub const WHvX64InterruptTypeLocalInt1 = WHV_INTERRUPT_TYPE.LocalInt1;
pub const WHV_INTERRUPT_DESTINATION_MODE = enum(i32) {
Physical = 0,
Logical = 1,
};
pub const WHvX64InterruptDestinationModePhysical = WHV_INTERRUPT_DESTINATION_MODE.Physical;
pub const WHvX64InterruptDestinationModeLogical = WHV_INTERRUPT_DESTINATION_MODE.Logical;
pub const WHV_INTERRUPT_TRIGGER_MODE = enum(i32) {
Edge = 0,
Level = 1,
};
pub const WHvX64InterruptTriggerModeEdge = WHV_INTERRUPT_TRIGGER_MODE.Edge;
pub const WHvX64InterruptTriggerModeLevel = WHV_INTERRUPT_TRIGGER_MODE.Level;
pub const WHV_INTERRUPT_CONTROL = extern struct {
_bitfield: u64,
Destination: u32,
Vector: u32,
};
pub const WHV_DOORBELL_MATCH_DATA = extern struct {
GuestAddress: u64,
Value: u64,
Length: u32,
_bitfield: u32,
};
pub const WHV_PARTITION_COUNTER_SET = enum(i32) {
y = 0,
};
pub const WHvPartitionCounterSetMemory = WHV_PARTITION_COUNTER_SET.y;
pub const WHV_PARTITION_MEMORY_COUNTERS = extern struct {
Mapped4KPageCount: u64,
Mapped2MPageCount: u64,
Mapped1GPageCount: u64,
};
pub const WHV_PROCESSOR_COUNTER_SET = enum(i32) {
Runtime = 0,
Intercepts = 1,
Events = 2,
Apic = 3,
};
pub const WHvProcessorCounterSetRuntime = WHV_PROCESSOR_COUNTER_SET.Runtime;
pub const WHvProcessorCounterSetIntercepts = WHV_PROCESSOR_COUNTER_SET.Intercepts;
pub const WHvProcessorCounterSetEvents = WHV_PROCESSOR_COUNTER_SET.Events;
pub const WHvProcessorCounterSetApic = WHV_PROCESSOR_COUNTER_SET.Apic;
pub const WHV_PROCESSOR_RUNTIME_COUNTERS = extern struct {
TotalRuntime100ns: u64,
HypervisorRuntime100ns: u64,
};
pub const WHV_PROCESSOR_INTERCEPT_COUNTER = extern struct {
Count: u64,
Time100ns: u64,
};
pub const WHV_PROCESSOR_INTERCEPT_COUNTERS = extern struct {
PageInvalidations: WHV_PROCESSOR_INTERCEPT_COUNTER,
ControlRegisterAccesses: WHV_PROCESSOR_INTERCEPT_COUNTER,
IoInstructions: WHV_PROCESSOR_INTERCEPT_COUNTER,
HaltInstructions: WHV_PROCESSOR_INTERCEPT_COUNTER,
CpuidInstructions: WHV_PROCESSOR_INTERCEPT_COUNTER,
MsrAccesses: WHV_PROCESSOR_INTERCEPT_COUNTER,
OtherIntercepts: WHV_PROCESSOR_INTERCEPT_COUNTER,
PendingInterrupts: WHV_PROCESSOR_INTERCEPT_COUNTER,
EmulatedInstructions: WHV_PROCESSOR_INTERCEPT_COUNTER,
DebugRegisterAccesses: WHV_PROCESSOR_INTERCEPT_COUNTER,
PageFaultIntercepts: WHV_PROCESSOR_INTERCEPT_COUNTER,
};
pub const WHV_PROCESSOR_EVENT_COUNTERS = extern struct {
PageFaultCount: u64,
ExceptionCount: u64,
InterruptCount: u64,
};
pub const WHV_PROCESSOR_APIC_COUNTERS = extern struct {
MmioAccessCount: u64,
EoiAccessCount: u64,
TprAccessCount: u64,
SentIpiCount: u64,
SelfIpiCount: u64,
};
pub const WHV_EMULATOR_STATUS = extern union {
Anonymous: extern struct {
_bitfield: u32,
},
AsUINT32: u32,
};
pub const WHV_EMULATOR_MEMORY_ACCESS_INFO = extern struct {
GpaAddress: u64,
Direction: u8,
AccessSize: u8,
Data: [8]u8,
};
pub const WHV_EMULATOR_IO_ACCESS_INFO = extern struct {
Direction: u8,
Port: u16,
AccessSize: u16,
Data: u32,
};
pub const WHV_EMULATOR_IO_PORT_CALLBACK = fn(
Context: ?*c_void,
IoAccess: ?*WHV_EMULATOR_IO_ACCESS_INFO,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const WHV_EMULATOR_MEMORY_CALLBACK = fn(
Context: ?*c_void,
MemoryAccess: ?*WHV_EMULATOR_MEMORY_ACCESS_INFO,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const WHV_EMULATOR_GET_VIRTUAL_PROCESSOR_REGISTERS_CALLBACK = fn(
Context: ?*c_void,
RegisterNames: [*]const WHV_REGISTER_NAME,
RegisterCount: u32,
RegisterValues: [*]WHV_REGISTER_VALUE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const WHV_EMULATOR_SET_VIRTUAL_PROCESSOR_REGISTERS_CALLBACK = fn(
Context: ?*c_void,
RegisterNames: [*]const WHV_REGISTER_NAME,
RegisterCount: u32,
RegisterValues: [*]const WHV_REGISTER_VALUE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const WHV_EMULATOR_TRANSLATE_GVA_PAGE_CALLBACK = fn(
Context: ?*c_void,
Gva: u64,
TranslateFlags: WHV_TRANSLATE_GVA_FLAGS,
TranslationResult: ?*WHV_TRANSLATE_GVA_RESULT_CODE,
Gpa: ?*u64,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const WHV_EMULATOR_CALLBACKS = extern struct {
Size: u32,
Reserved: u32,
WHvEmulatorIoPortCallback: ?WHV_EMULATOR_IO_PORT_CALLBACK,
WHvEmulatorMemoryCallback: ?WHV_EMULATOR_MEMORY_CALLBACK,
WHvEmulatorGetVirtualProcessorRegisters: ?WHV_EMULATOR_GET_VIRTUAL_PROCESSOR_REGISTERS_CALLBACK,
WHvEmulatorSetVirtualProcessorRegisters: ?WHV_EMULATOR_SET_VIRTUAL_PROCESSOR_REGISTERS_CALLBACK,
WHvEmulatorTranslateGvaPage: ?WHV_EMULATOR_TRANSLATE_GVA_PAGE_CALLBACK,
};
//--------------------------------------------------------------------------------
// Section: Functions (33)
//--------------------------------------------------------------------------------
pub extern "WinHvPlatform" fn WHvGetCapability(
CapabilityCode: WHV_CAPABILITY_CODE,
// TODO: what to do with BytesParamIndex 2?
CapabilityBuffer: ?*c_void,
CapabilityBufferSizeInBytes: u32,
WrittenSizeInBytes: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvPlatform" fn WHvCreatePartition(
Partition: ?*WHV_PARTITION_HANDLE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvPlatform" fn WHvSetupPartition(
Partition: WHV_PARTITION_HANDLE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvPlatform" fn WHvDeletePartition(
Partition: WHV_PARTITION_HANDLE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvPlatform" fn WHvGetPartitionProperty(
Partition: WHV_PARTITION_HANDLE,
PropertyCode: WHV_PARTITION_PROPERTY_CODE,
// TODO: what to do with BytesParamIndex 3?
PropertyBuffer: ?*c_void,
PropertyBufferSizeInBytes: u32,
WrittenSizeInBytes: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvPlatform" fn WHvSetPartitionProperty(
Partition: WHV_PARTITION_HANDLE,
PropertyCode: WHV_PARTITION_PROPERTY_CODE,
// TODO: what to do with BytesParamIndex 3?
PropertyBuffer: ?*const c_void,
PropertyBufferSizeInBytes: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvPlatform" fn WHvSuspendPartitionTime(
Partition: WHV_PARTITION_HANDLE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvPlatform" fn WHvResumePartitionTime(
Partition: WHV_PARTITION_HANDLE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvPlatform" fn WHvMapGpaRange(
Partition: WHV_PARTITION_HANDLE,
SourceAddress: ?*c_void,
GuestAddress: u64,
SizeInBytes: u64,
Flags: WHV_MAP_GPA_RANGE_FLAGS,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvPlatform" fn WHvUnmapGpaRange(
Partition: WHV_PARTITION_HANDLE,
GuestAddress: u64,
SizeInBytes: u64,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvPlatform" fn WHvTranslateGva(
Partition: WHV_PARTITION_HANDLE,
VpIndex: u32,
Gva: u64,
TranslateFlags: WHV_TRANSLATE_GVA_FLAGS,
TranslationResult: ?*WHV_TRANSLATE_GVA_RESULT,
Gpa: ?*u64,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvPlatform" fn WHvCreateVirtualProcessor(
Partition: WHV_PARTITION_HANDLE,
VpIndex: u32,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvPlatform" fn WHvDeleteVirtualProcessor(
Partition: WHV_PARTITION_HANDLE,
VpIndex: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvPlatform" fn WHvRunVirtualProcessor(
Partition: WHV_PARTITION_HANDLE,
VpIndex: u32,
// TODO: what to do with BytesParamIndex 3?
ExitContext: ?*c_void,
ExitContextSizeInBytes: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvPlatform" fn WHvCancelRunVirtualProcessor(
Partition: WHV_PARTITION_HANDLE,
VpIndex: u32,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvPlatform" fn WHvGetVirtualProcessorRegisters(
Partition: WHV_PARTITION_HANDLE,
VpIndex: u32,
RegisterNames: [*]const WHV_REGISTER_NAME,
RegisterCount: u32,
RegisterValues: [*]WHV_REGISTER_VALUE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvPlatform" fn WHvSetVirtualProcessorRegisters(
Partition: WHV_PARTITION_HANDLE,
VpIndex: u32,
RegisterNames: [*]const WHV_REGISTER_NAME,
RegisterCount: u32,
RegisterValues: [*]const WHV_REGISTER_VALUE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvPlatform" fn WHvGetVirtualProcessorInterruptControllerState(
Partition: WHV_PARTITION_HANDLE,
VpIndex: u32,
// TODO: what to do with BytesParamIndex 3?
State: ?*c_void,
StateSize: u32,
WrittenSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvPlatform" fn WHvSetVirtualProcessorInterruptControllerState(
Partition: WHV_PARTITION_HANDLE,
VpIndex: u32,
// TODO: what to do with BytesParamIndex 3?
State: ?*const c_void,
StateSize: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvPlatform" fn WHvRequestInterrupt(
Partition: WHV_PARTITION_HANDLE,
Interrupt: ?*const WHV_INTERRUPT_CONTROL,
InterruptControlSize: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvPlatform" fn WHvGetVirtualProcessorXsaveState(
Partition: WHV_PARTITION_HANDLE,
VpIndex: u32,
// TODO: what to do with BytesParamIndex 3?
Buffer: ?*c_void,
BufferSizeInBytes: u32,
BytesWritten: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvPlatform" fn WHvSetVirtualProcessorXsaveState(
Partition: WHV_PARTITION_HANDLE,
VpIndex: u32,
// TODO: what to do with BytesParamIndex 3?
Buffer: ?*const c_void,
BufferSizeInBytes: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvPlatform" fn WHvQueryGpaRangeDirtyBitmap(
Partition: WHV_PARTITION_HANDLE,
GuestAddress: u64,
RangeSizeInBytes: u64,
// TODO: what to do with BytesParamIndex 4?
Bitmap: ?*u64,
BitmapSizeInBytes: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvPlatform" fn WHvGetPartitionCounters(
Partition: WHV_PARTITION_HANDLE,
CounterSet: WHV_PARTITION_COUNTER_SET,
// TODO: what to do with BytesParamIndex 3?
Buffer: ?*c_void,
BufferSizeInBytes: u32,
BytesWritten: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvPlatform" fn WHvGetVirtualProcessorCounters(
Partition: WHV_PARTITION_HANDLE,
VpIndex: u32,
CounterSet: WHV_PROCESSOR_COUNTER_SET,
// TODO: what to do with BytesParamIndex 4?
Buffer: ?*c_void,
BufferSizeInBytes: u32,
BytesWritten: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvPlatform" fn WHvGetVirtualProcessorInterruptControllerState2(
Partition: WHV_PARTITION_HANDLE,
VpIndex: u32,
// TODO: what to do with BytesParamIndex 3?
State: ?*c_void,
StateSize: u32,
WrittenSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvPlatform" fn WHvSetVirtualProcessorInterruptControllerState2(
Partition: WHV_PARTITION_HANDLE,
VpIndex: u32,
// TODO: what to do with BytesParamIndex 3?
State: ?*const c_void,
StateSize: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvPlatform" fn WHvRegisterPartitionDoorbellEvent(
Partition: WHV_PARTITION_HANDLE,
MatchData: ?*const WHV_DOORBELL_MATCH_DATA,
EventHandle: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvPlatform" fn WHvUnregisterPartitionDoorbellEvent(
Partition: WHV_PARTITION_HANDLE,
MatchData: ?*const WHV_DOORBELL_MATCH_DATA,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvEmulation" fn WHvEmulatorCreateEmulator(
Callbacks: ?*const WHV_EMULATOR_CALLBACKS,
Emulator: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvEmulation" fn WHvEmulatorDestroyEmulator(
Emulator: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvEmulation" fn WHvEmulatorTryIoEmulation(
Emulator: ?*c_void,
Context: ?*c_void,
VpContext: ?*const WHV_VP_EXIT_CONTEXT,
IoInstructionContext: ?*const WHV_X64_IO_PORT_ACCESS_CONTEXT,
EmulatorReturnStatus: ?*WHV_EMULATOR_STATUS,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "WinHvEmulation" fn WHvEmulatorTryMmioEmulation(
Emulator: ?*c_void,
Context: ?*c_void,
VpContext: ?*const WHV_VP_EXIT_CONTEXT,
MmioInstructionContext: ?*const WHV_MEMORY_ACCESS_CONTEXT,
EmulatorReturnStatus: ?*WHV_EMULATOR_STATUS,
) 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 (3)
//--------------------------------------------------------------------------------
const BOOL = @import("../foundation.zig").BOOL;
const HANDLE = @import("../foundation.zig").HANDLE;
const HRESULT = @import("../foundation.zig").HRESULT;
test {
// The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476
if (@hasDecl(@This(), "WHV_EMULATOR_IO_PORT_CALLBACK")) { _ = WHV_EMULATOR_IO_PORT_CALLBACK; }
if (@hasDecl(@This(), "WHV_EMULATOR_MEMORY_CALLBACK")) { _ = WHV_EMULATOR_MEMORY_CALLBACK; }
if (@hasDecl(@This(), "WHV_EMULATOR_GET_VIRTUAL_PROCESSOR_REGISTERS_CALLBACK")) { _ = WHV_EMULATOR_GET_VIRTUAL_PROCESSOR_REGISTERS_CALLBACK; }
if (@hasDecl(@This(), "WHV_EMULATOR_SET_VIRTUAL_PROCESSOR_REGISTERS_CALLBACK")) { _ = WHV_EMULATOR_SET_VIRTUAL_PROCESSOR_REGISTERS_CALLBACK; }
if (@hasDecl(@This(), "WHV_EMULATOR_TRANSLATE_GVA_PAGE_CALLBACK")) { _ = WHV_EMULATOR_TRANSLATE_GVA_PAGE_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;
}
}
} | deps/zigwin32/win32/system/hypervisor.zig |
const c = @import("c.zig");
const nk = @import("../nuklear.zig");
const std = @import("std");
const testing = std.testing;
pub fn items(
ctx: *nk.Context,
size: nk.Vec2,
item_height: usize,
selected: usize,
strings: []const nk.Slice,
) usize {
return @intCast(usize, c.nk_combo(
ctx,
nk.discardConst(strings.ptr),
@intCast(c_int, strings.len),
@intCast(c_int, selected),
@intCast(c_int, item_height),
size,
));
}
pub fn separator(
ctx: *nk.Context,
size: nk.Vec2,
item_height: usize,
selected: usize,
count: usize,
seb: u8,
items_separated_by_separator: []const u8,
) usize {
return @intCast(usize, c.nk_combo_separator(
ctx,
nk.slice(items_separated_by_separator),
@intCast(c_int, seb),
@intCast(c_int, selected),
@intCast(c_int, count),
@intCast(c_int, item_height),
size,
));
}
pub fn string(
ctx: *nk.Context,
size: nk.Vec2,
item_height: usize,
selected: usize,
count: usize,
items_separated_by_zeros: []const u8,
) usize {
return @intCast(usize, c.nk_combo_string(
ctx,
nk.slice(items_separated_by_zeros),
@intCast(c_int, selected),
@intCast(c_int, count),
@intCast(c_int, item_height),
size,
));
}
pub fn callback(
ctx: *nk.Context,
size: nk.Vec2,
item_height: usize,
selected: usize,
count: usize,
userdata: anytype,
getter: fn (@TypeOf(userdata), usize) []const u8,
) usize {
const T = @TypeOf(userdata);
const Wrapped = struct {
userdata: T,
getter: fn (T, usize) []const u8,
fn valueGetter(user: ?*c_void, index: c_int, out: [*c]nk.Slice) callconv(.C) void {
const casted = @ptrCast(*const @This(), @alignCast(@alignOf(@This()), user));
out.* = nk.slice(casted.getter(casted.userdata, @intCast(usize, index)));
}
};
var wrapped = Wrapped{ .userdata = userdata, .getter = getter };
return @intCast(usize, c.nk_combo_callback(
ctx,
Wrapped.valueGetter,
@ptrCast(*c_void, &wrapped),
@intCast(c_int, selected),
@intCast(c_int, count),
@intCast(c_int, item_height),
size,
));
}
pub fn beginLabel(ctx: *nk.Context, size: nk.Vec2, selected: []const u8) bool {
return c.nk_combo_begin_label(ctx, nk.slice(selected), size) != 0;
}
pub fn beginColor(ctx: *nk.Context, size: nk.Vec2, q: nk.Color) bool {
return c.nk_combo_begin_color(ctx, q, size) != 0;
}
pub fn beginSymbol(ctx: *nk.Context, size: nk.Vec2, symbol: nk.SymbolType) bool {
return c.nk_combo_begin_symbol(ctx, symbol.toNuklear(), size) != 0;
}
pub fn beginSymbolLabel(
ctx: *nk.Context,
size: nk.Vec2,
selected: []const u8,
symbol: nk.SymbolType,
) bool {
return c.nk_combo_begin_symbol_label(ctx, nk.slice(selected), symbol.toNuklear(), size) != 0;
}
pub fn beginImage(ctx: *nk.Context, size: nk.Vec2, img: nk.Image) bool {
return c.nk_combo_begin_image(ctx, img, size) != 0;
}
pub fn beginImageLabel(ctx: *nk.Context, size: nk.Vec2, selected: []const u8, a: nk.Image) bool {
return c.nk_combo_begin_image_label(ctx, nk.slice(selected), a, size) != 0;
}
pub fn itemLabel(ctx: *nk.Context, a: []const u8, alignment: nk.Flags) bool {
return c.nk_combo_item_label(ctx, nk.slice(a), alignment) != 0;
}
pub fn itemImageLabel(ctx: *nk.Context, y: nk.Image, a: []const u8, alignment: nk.Flags) bool {
return c.nk_combo_item_image_label(ctx, y, nk.slice(a), alignment) != 0;
}
pub fn itemSymbolLabel(
ctx: *nk.Context,
symbol: nk.SymbolType,
a: []const u8,
alignment: nk.Flags,
) bool {
return c.nk_combo_item_symbol_label(ctx, symbol.toNuklear(), nk.slice(a), alignment) != 0;
}
pub fn close(ctx: *nk.Context) void {
return c.nk_combo_close(ctx);
}
pub fn end(ctx: *nk.Context) void {
return c.nk_combo_end(ctx);
}
test {
testing.refAllDecls(@This());
}
test "combo" {
var ctx = &try nk.testing.init();
defer nk.free(ctx);
if (nk.window.begin(ctx, &nk.id(opaque {}), nk.rect(10, 10, 10, 10), .{})) |_| {
nk.layout.rowDynamic(ctx, 0.0, 1);
_ = nk.combo.callback(ctx, nk.vec2(10, 10), 0, 0, 2, {}, struct {
fn func(_: void, i: usize) []const u8 {
return switch (i) {
0 => "1",
1 => "2",
else => unreachable,
};
}
}.func);
}
nk.window.end(ctx);
} | src/combo.zig |
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const mem = std.mem;
const net = std.net;
const parseUnsigned = std.fmt.parseUnsigned;
const std = @import("std");
const ValueMap = std.StringHashMap([]const u8);
pub const Host = union(enum) {
ip: net.Address,
name: []const u8,
pub fn equals(first: Host, second: Host) bool {
return switch (first) {
Host.ip => |firstIp| {
return switch (second) {
Host.ip => |secondIp| net.Address.eql(firstIp, secondIp),
Host.name => false,
};
},
Host.name => |firstName| {
return switch (second) {
Host.ip => false,
Host.name => |secondName| mem.eql(u8, firstName, secondName),
};
},
};
}
};
/// possible errors for mapQuery
pub const MapError = error{
NoQuery,
OutOfMemory,
};
/// possible errors for decode and encode
pub const EncodeError = error{
InvalidCharacter,
OutOfMemory,
};
/// possible errors for parse
pub const Error = error{
/// input is not a valid uri due to a invalid character
/// mostly a result of invalid ipv6
InvalidCharacter,
/// given input was empty
EmptyUri,
};
pub const Uri = struct {
scheme: []const u8,
username: []const u8,
password: []const u8,
host: Host,
port: ?u16,
path: []const u8,
query: []const u8,
fragment: []const u8,
len: usize,
/// map query string into a hashmap of key value pairs with no value being an empty string
pub fn mapQuery(allocator: Allocator, query: []const u8) MapError!ValueMap {
if (query.len == 0) {
return error.NoQuery;
}
var map = ValueMap.init(allocator);
errdefer map.deinit();
var start: u32 = 0;
var mid: u32 = 0;
for (query) |c, i| {
if (c == ';' or c == '&') {
if (mid != 0) {
_ = try map.put(query[start..mid], query[mid + 1 .. i]);
} else {
_ = try map.put(query[start..i], "");
}
start = @truncate(u32, i + 1);
mid = 0;
} else if (c == '=') {
mid = @truncate(u32, i);
}
}
if (mid != 0) {
_ = try map.put(query[start..mid], query[mid + 1 ..]);
} else {
_ = try map.put(query[start..], "");
}
return map;
}
/// decode path if it is percent encoded
pub fn decode(allocator: Allocator, path: []const u8) EncodeError!?[]u8 {
var ret: ?[]u8 = null;
var ret_index: usize = 0;
var i: usize = 0;
while (i < path.len) : (i += 1) {
if (path[i] == '%') {
if (!isPchar(path[i..])) {
return error.InvalidCharacter;
}
if (ret == null) {
ret = try allocator.alloc(u8, path.len);
mem.copy(u8, ret.?, path[0..i]);
ret_index = i;
}
// charToDigit can't fail because the chars are validated earlier
var new = (std.fmt.charToDigit(path[i + 1], 16) catch unreachable) << 4;
new |= std.fmt.charToDigit(path[i + 2], 16) catch unreachable;
ret.?[ret_index] = new;
ret_index += 1;
i += 2;
} else if (path[i] != '/' and !isPchar(path[i..])) {
return error.InvalidCharacter;
} else if (ret != null) {
ret.?[ret_index] = path[i];
ret_index += 1;
}
}
if (ret != null) {
return allocator.realloc(ret.?, ret_index) catch ret.?[0..ret_index];
}
return ret;
}
/// percent encode if path contains characters not allowed in paths
pub fn encode(allocator: Allocator, path: []const u8) EncodeError!?[]u8 {
var ret: ?[]u8 = null;
var ret_index: usize = 0;
for (path) |c, i| {
if (c != '/' and !isPchar(path[i..])) {
if (ret == null) {
ret = try allocator.alloc(u8, path.len * 3);
mem.copy(u8, ret.?, path[0..i]);
ret_index = i;
}
const hex_digits = "0123456789ABCDEF";
ret.?[ret_index] = '%';
ret.?[ret_index + 1] = hex_digits[(c & 0xF0) >> 4];
ret.?[ret_index + 2] = hex_digits[c & 0x0F];
ret_index += 3;
} else if (ret != null) {
ret.?[ret_index] = c;
ret_index += 1;
}
}
if (ret != null) {
return allocator.realloc(ret.?, ret_index) catch ret.?[0..ret_index];
}
return ret;
}
/// resolves `path`, leaves trailing '/'
/// assumes `path` to be valid
pub fn resolvePath(allocator: Allocator, path: []const u8) error{OutOfMemory}![]u8 {
assert(path.len > 0);
var list = std.ArrayList([]const u8).init(allocator);
errdefer list.deinit();
var it = mem.tokenize(u8, path, "/");
while (it.next()) |p| {
if (mem.eql(u8, p, ".")) {
continue;
} else if (mem.eql(u8, p, "..")) {
_ = list.popOrNull();
} else {
try list.append(p);
}
}
var buf = try allocator.alloc(u8, path.len);
errdefer allocator.free(buf);
var len: usize = 0;
var segments = list.toOwnedSlice();
defer allocator.free(segments);
for (segments) |s| {
buf[len] = '/';
len += 1;
mem.copy(u8, buf[len..], s);
len += s.len;
}
if (path[path.len - 1] == '/') {
buf[len] = '/';
len += 1;
}
return allocator.realloc(buf, len) catch buf[0..len];
}
/// parse URI from input
/// empty input is an error
/// if assume_auth is true then `example.com` will result in `example.com` being the host instead of path
pub fn parse(input: []const u8, assume_auth: bool) Error!Uri {
if (input.len == 0) {
return error.EmptyUri;
}
var uri = Uri{
.scheme = "",
.username = "",
.password = "",
.host = .{ .name = "" },
.port = null,
.path = "",
.query = "",
.fragment = "",
.len = 0,
};
switch (input[0]) {
'a'...'z', 'A'...'Z' => {
uri.parseMaybeScheme(input);
},
else => {},
}
if (input.len > uri.len + 2 and input[uri.len] == '/' and input[uri.len + 1] == '/') {
uri.len += 2; // for the '//'
try uri.parseAuth(input[uri.len..]);
} else if (assume_auth) {
try uri.parseAuth(input[uri.len..]);
}
// make host ip4 address if possible
if (uri.host == .name and uri.host.name.len > 0) blk: {
var a = net.Address.parseIp4(uri.host.name, 0) catch break :blk;
uri.host = .{ .ip = a }; // workaround for https://github.com/ziglang/zig/issues/3234
}
if (uri.host == .ip and uri.port != null) {
uri.host.ip.setPort(uri.port.?);
}
uri.parsePath(input[uri.len..]);
if (input.len > uri.len + 1 and input[uri.len] == '?') {
uri.parseQuery(input[uri.len + 1 ..]);
}
if (input.len > uri.len + 1 and input[uri.len] == '#') {
uri.parseFragment(input[uri.len + 1 ..]);
}
return uri;
}
fn parseMaybeScheme(u: *Uri, input: []const u8) void {
for (input) |c, i| {
switch (c) {
'a'...'z', 'A'...'Z', '0'...'9', '+', '-', '.' => {
// allowed characters
},
':' => {
u.scheme = input[0..i];
u.len += u.scheme.len + 1; // +1 for the ':'
return;
},
else => {
// not a valid scheme
return;
},
}
}
return;
}
fn parseAuth(u: *Uri, input: []const u8) Error!void {
for (input) |c, i| {
switch (c) {
'@' => {
u.username = input[0..i];
u.len += i + 1; // +1 for the '@'
return u.parseHost(input[i + 1 ..]);
},
'[' => {
if (i != 0)
return error.InvalidCharacter;
return u.parseIP(input);
},
':' => {
u.host.name = input[0..i];
u.len += i + 1; // +1 for the '@'
return u.parseAuthColon(input[i + 1 ..]);
},
'/', '?', '#' => {
u.host.name = input[0..i];
u.len += i;
return;
},
else => if (!isPchar(input)) {
u.host.name = input[0..i];
u.len += input.len;
return;
},
}
}
u.host.name = input;
u.len += input.len;
}
fn parseAuthColon(u: *Uri, input: []const u8) Error!void {
for (input) |c, i| {
if (c == '@') {
u.username = u.host.name;
u.password = input[0..i];
u.len += i + 1; //1 for the '@'
return u.parseHost(input[i + 1 ..]);
} else if (c == '/' or c == '?' or c == '#' or !isPchar(input)) {
u.port = parseUnsigned(u16, input[0..i], 10) catch return error.InvalidCharacter;
u.len += i;
return;
}
}
u.port = parseUnsigned(u16, input, 10) catch return error.InvalidCharacter;
u.len += input.len;
}
fn parseHost(u: *Uri, input: []const u8) Error!void {
for (input) |c, i| {
switch (c) {
':' => {
u.host.name = input[0..i];
u.len += i + 1; // +1 for the ':'
return u.parsePort(input[i..]);
},
'[' => {
if (i != 0)
return error.InvalidCharacter;
return u.parseIP(input);
},
else => if (c == '/' or c == '?' or c == '#' or !isPchar(input)) {
u.host.name = input[0..i];
u.len += i;
return;
},
}
}
u.host.name = input[0..];
u.len += input.len;
}
fn parseIP(u: *Uri, input: []const u8) Error!void {
const end = mem.indexOfScalar(u8, input, ']') orelse return error.InvalidCharacter;
var addr = net.Address.parseIp6(input[1..end], 0) catch return error.InvalidCharacter;
u.host = .{ .ip = addr };
u.len += end + 1;
if (input.len > end + 2 and input[end + 1] == ':') {
u.len += 1;
try u.parsePort(input[end + 2 ..]);
}
}
fn parsePort(u: *Uri, input: []const u8) Error!void {
for (input) |c, i| {
switch (c) {
'0'...'9' => {
// digits
},
else => {
if (i == 0) return error.InvalidCharacter;
u.port = parseUnsigned(u16, input[0..i], 10) catch return error.InvalidCharacter;
u.len += i;
return;
},
}
}
if (input.len == 0) return error.InvalidCharacter;
u.port = parseUnsigned(u16, input[0..], 10) catch return error.InvalidCharacter;
u.len += input.len;
}
fn parsePath(u: *Uri, input: []const u8) void {
for (input) |c, i| {
if (c != '/' and (c == '?' or c == '#' or !isPchar(input[i..]))) {
u.path = input[0..i];
u.len += u.path.len;
return;
}
}
u.path = input[0..];
u.len += u.path.len;
}
fn parseQuery(u: *Uri, input: []const u8) void {
u.len += 1; // +1 for the '?'
for (input) |c, i| {
if (c == '#' or (c != '/' and c != '?' and !isPchar(input[i..]))) {
u.query = input[0..i];
u.len += u.query.len;
return;
}
}
u.query = input;
u.len += input.len;
}
fn parseFragment(u: *Uri, input: []const u8) void {
u.len += 1; // +1 for the '#'
for (input) |c, i| {
if (c != '/' and c != '?' and !isPchar(input[i..])) {
u.fragment = input[0..i];
u.len += u.fragment.len;
return;
}
}
u.fragment = input;
u.len += u.fragment.len;
}
/// returns true if str starts with a valid path character or a percent encoded octet
pub fn isPchar(str: []const u8) bool {
assert(str.len > 0);
return switch (str[0]) {
'a'...'z', 'A'...'Z', '0'...'9', '-', '.', '_', '~', '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '@' => true,
'%' => str.len > 3 and isHex(str[1]) and isHex(str[2]),
else => false,
};
}
/// returns true if c is a hexadecimal digit
pub fn isHex(c: u8) bool {
return switch (c) {
'0'...'9', 'a'...'f', 'A'...'F' => true,
else => false,
};
}
pub fn equals(first: Uri, second: Uri) bool {
var hasSamePort = false;
if (first.port) |firstPort| {
if (second.port) |secondPort| {
hasSamePort = firstPort == secondPort;
}
} else {
if (second.port == null) {
hasSamePort = true;
}
}
return (first.len == second.len and std.mem.eql(u8, first.scheme, second.scheme) and Host.equals(first.host, second.host) and hasSamePort and std.mem.eql(u8, first.path, second.path) and std.mem.eql(u8, first.query, second.query) and std.mem.eql(u8, first.fragment, second.fragment) and std.mem.eql(u8, first.username, second.username) and std.mem.eql(u8, first.password, second.password));
}
};
const expect = std.testing.expect;
const expectEqualStrings = std.testing.expectEqualStrings;
test "Parse a basic url" {
const uri = try Uri.parse("https://ziglang.org:80/documentation/master/?test#toc-Introduction", false);
try expectEqualStrings(uri.scheme, "https");
try expectEqualStrings(uri.username, "");
try expectEqualStrings(uri.password, "");
try expectEqualStrings(uri.host.name, "ziglang.org");
try expect(uri.port.? == 80);
try expectEqualStrings(uri.path, "/documentation/master/");
try expectEqualStrings(uri.query, "test");
try expectEqualStrings(uri.fragment, "toc-Introduction");
try expect(uri.len == 66);
}
test "Parse an IP address" {
const uri = try Uri.parse("telnet://192.0.2.16:80/", false);
try expectEqualStrings(uri.scheme, "telnet");
try expectEqualStrings(uri.username, "");
try expectEqualStrings(uri.password, "");
var buf = [_]u8{0} ** 100;
var ip = std.fmt.bufPrint(buf[0..], "{}", .{uri.host.ip}) catch unreachable;
try expectEqualStrings(ip, "192.0.2.16:80");
try expect(uri.port.? == 80);
try expectEqualStrings(uri.path, "/");
try expectEqualStrings(uri.query, "");
try expectEqualStrings(uri.fragment, "");
try expect(uri.len == 23);
}
test "Parse a single char" {
const uri = try Uri.parse("a", false);
try expectEqualStrings(uri.scheme, "");
try expectEqualStrings(uri.username, "");
try expectEqualStrings(uri.password, "");
try expectEqualStrings(uri.host.name, "");
try expect(uri.port == null);
try expectEqualStrings(uri.path, "a");
try expectEqualStrings(uri.query, "");
try expectEqualStrings(uri.fragment, "");
try expect(uri.len == 1);
}
test "Parse an IPv6 address" {
const uri = try Uri.parse("ldap://[2001:db8::7]/c=GB?objectClass?one", false);
try expectEqualStrings(uri.scheme, "ldap");
try expectEqualStrings(uri.username, "");
try expectEqualStrings(uri.password, "");
var buf = [_]u8{0} ** 100;
var ip = std.fmt.bufPrint(buf[0..], "{}", .{uri.host.ip}) catch unreachable;
try expectEqualStrings(ip, "[2001:fc00:e968:6179::de52:7100]:0");
try expect(uri.port == null);
try expectEqualStrings(uri.path, "/c=GB");
try expectEqualStrings(uri.query, "objectClass?one");
try expectEqualStrings(uri.fragment, "");
try expect(uri.len == 41);
}
test "Parse a mailto" {
const uri = try Uri.parse("mailto:<EMAIL>", false);
try expectEqualStrings(uri.scheme, "mailto");
try expectEqualStrings(uri.username, "");
try expectEqualStrings(uri.password, "");
try expectEqualStrings(uri.host.name, "");
try expect(uri.port == null);
try expectEqualStrings(uri.path, "<EMAIL>");
try expectEqualStrings(uri.query, "");
try expectEqualStrings(uri.fragment, "");
try expect(uri.len == 27);
}
test "Parse a tel" {
const uri = try Uri.parse("tel:+1-816-555-1212", false);
try expectEqualStrings(uri.scheme, "tel");
try expectEqualStrings(uri.username, "");
try expectEqualStrings(uri.password, "");
try expectEqualStrings(uri.host.name, "");
try expect(uri.port == null);
try expectEqualStrings(uri.path, "+1-816-555-1212");
try expectEqualStrings(uri.query, "");
try expectEqualStrings(uri.fragment, "");
try expect(uri.len == 19);
}
test "Parse a urn" {
const uri = try Uri.parse("urn:oasis:names:specification:docbook:dtd:xml:4.1.2", false);
try expectEqualStrings(uri.scheme, "urn");
try expectEqualStrings(uri.username, "");
try expectEqualStrings(uri.password, "");
try expectEqualStrings(uri.host.name, "");
try expect(uri.port == null);
try expectEqualStrings(uri.path, "oasis:names:specification:docbook:dtd:xml:4.1.2");
try expectEqualStrings(uri.query, "");
try expectEqualStrings(uri.fragment, "");
try expect(uri.len == 51);
}
test "Parse authentication information" {
const uri = try Uri.parse("ftp://username:[email protected]/", false);
try expectEqualStrings(uri.scheme, "ftp");
try expectEqualStrings(uri.username, "username");
try expectEqualStrings(uri.password, "password");
try expectEqualStrings(uri.host.name, "host.com");
try expect(uri.port == null);
try expectEqualStrings(uri.path, "/");
try expectEqualStrings(uri.query, "");
try expectEqualStrings(uri.fragment, "");
try expect(uri.len == 33);
}
test "Map query parameters" {
const uri = try Uri.parse("https://ziglang.org:80/documentation/master/?test;1=true&false#toc-Introduction", false);
try expectEqualStrings(uri.scheme, "https");
try expectEqualStrings(uri.username, "");
try expectEqualStrings(uri.password, "");
try expectEqualStrings(uri.host.name, "ziglang.org");
try expect(uri.port.? == 80);
try expectEqualStrings(uri.path, "/documentation/master/");
try expectEqualStrings(uri.query, "test;1=true&false");
try expectEqualStrings(uri.fragment, "toc-Introduction");
var map = try Uri.mapQuery(std.testing.allocator, uri.query);
defer map.deinit();
try expectEqualStrings(map.get("test").?, "");
try expectEqualStrings(map.get("1").?, "true");
try expectEqualStrings(map.get("false").?, "");
}
test "Parse ends at the first whitespace" {
const uri = try Uri.parse("https://ziglang.org/documentation/master/ something else", false);
try expectEqualStrings(uri.scheme, "https");
try expectEqualStrings(uri.username, "");
try expectEqualStrings(uri.password, "");
try expectEqualStrings(uri.host.name, "ziglang.org");
try expectEqualStrings(uri.path, "/documentation/master/");
try expect(uri.len == 41);
}
test "assume auth" {
// TODO: Read the damn spec: I don't understand what is happening here.
const uri = try Uri.parse("ziglang.org", true);
try expectEqualStrings(uri.host.name, "ziglang.org");
try expect(uri.len == 11);
}
test "Encode" {
const path = (try Uri.encode(std.testing.allocator, "/안녕하세요.html")).?;
defer std.testing.allocator.free(path);
try expectEqualStrings(path, "/%EC%95%88%EB%85%95%ED%95%98%EC%84%B8%EC%9A%94.html");
}
test "Decode" {
const path = (try Uri.decode(std.testing.allocator, "/%EC%95%88%EB%85%95%ED%95%98%EC%84%B8%EC%9A%94.html")).?;
defer std.testing.allocator.free(path);
try expectEqualStrings(path, "/안녕하세요.html");
}
test "Resolve paths" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
const alloc = arena.allocator();
var a = try Uri.resolvePath(alloc, "/a/b/..");
try expectEqualStrings(a, "/a");
a = try Uri.resolvePath(alloc, "/a/b/../");
try expectEqualStrings(a, "/a/");
a = try Uri.resolvePath(alloc, "/a/b/c/../d/../");
try expectEqualStrings(a, "/a/b/");
a = try Uri.resolvePath(alloc, "/a/b/c/../d/..");
try expectEqualStrings(a, "/a/b");
a = try Uri.resolvePath(alloc, "/a/b/c/../d/.././");
try expectEqualStrings(a, "/a/b/");
a = try Uri.resolvePath(alloc, "/a/b/c/../d/../.");
try expectEqualStrings(a, "/a/b");
a = try Uri.resolvePath(alloc, "/a/../../");
try expectEqualStrings(a, "/");
arena.deinit();
} | src/uri/uri.zig |
pub const Error = enum(c_int) {
NoSuchObject = 701,
InvalidCurrentTagValue = 702,
InvalidNewTagValue = 703,
RequiredTag = 704,
ReadOnlyTag = 705,
ParameterMismatch = 706,
UnsupportedOrInvalidSearchCriteria = 708,
UnsupportedOrInvalidSortCriteria = 709,
NoSuchContainer = 710,
RestrictedObject = 711,
BadMetadata = 712,
RestrictedParentObject = 713,
NoSuchSourceResource = 714,
SourceResourceAccessDenied = 715,
TransferBusy = 716,
NoSuchFileTransfer = 717,
NoSuchDestinationResource = 718,
DestinationResourceAccessDenied = 719,
CannotProcessRequest = 720,
pub fn toErrorCode(self: Error) c_int {
return @enumToInt(self);
}
};
pub const ContentDirectoryState = struct {
SystemUpdateID: [:0]const u8,
};
pub const GetSearchCapabilitiesOutput = struct {
pub const action_name = "GetSearchCapabilities";
SearchCaps: [:0]const u8,
};
pub const GetSortCapabilitiesOutput = struct {
pub const action_name = "GetSortCapabilities";
SortCaps: [:0]const u8,
};
pub const GetSystemUpdateIdOutput = struct {
pub const action_name = "GetSystemUpdateID";
Id: [:0]const u8,
};
// TODO ideally all of []const u8 should be [:0]const u8
pub const BrowseInput = struct {
@"u:Browse": struct {
ObjectID: []const u8,
BrowseFlag: []const u8,
Filter: []const u8,
StartingIndex: u32,
RequestedCount: u32,
SortCriteria: []const u8,
}
};
// TODO some of the fields are not stringy, however the ActionResult function does not accept non-string fields.
// Revert to string when that gets implemented.
pub const BrowseOutput = struct {
pub const action_name = "Browse";
Result: [:0]const u8,
NumberReturned: [:0]const u8, // u32
TotalMatches: [:0]const u8, // u32
UpdateID: [:0]const u8, // u32
};
// http://www.upnp.org/schemas/av/didl-lite-v2.xsd
pub const DIDLLite = struct {
@"DIDL-Lite": struct {
__attributes__: struct {
@"xmlns:dc": []const u8 = "http://purl.org/dc/elements/1.1/",
@"xmlns:upnp": []const u8 = "urn:schemas-upnp-org:metadata-1-0/upnp/",
xmlns: []const u8 = "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/",
} = .{},
container: ?[]const Container = null,
item: ?[]const Item = null,
}
};
// TODO some of these attributes are []const u8, even though they should be numeric.
// Currently our XML implementation doesn't support numeric attributes.
// Change back to numeric when implementation is made.
pub const Container = struct {
__attributes__: struct {
id: []const u8,
parentID: []const u8 = "0",
restricted: []const u8 = "0", // bool TODO bool needs to be converted to 0 or 1
searchable: ?[]const u8 = null, // bool TODO bool needs to be converted to 0 or 1
childCount: ?[]const u8 = null, // usize
},
@"dc:title": []const u8,
@"upnp:class": []const u8,
res: ?[]const Res = null,
item: ?[]const Item = null,
// container: []Container, // TODO XML parser doesn't support cyclic fields
};
pub const Item = struct {
__attributes__: struct {
id: []const u8,
parentID: []const u8 = "0",
restricted: []const u8 = "0", // bool TODO bool needs to be converted to 0 or 1
refID: ?[]const u8 = null,
},
@"dc:title": []const u8,
@"upnp:class": []const u8,
res: ?[]const Res = null,
};
pub const Res = struct {
__attributes__: struct {
protocolInfo: []const u8,
importUri: ?[]const u8 = null,
size: ?[]const u8 = null, // ?usize
duration: ?[]const u8 = null,
bitrate: ?[]const u8 = null, // ?usize
sampleFrequency: ?[]const u8 = null, // ?usize
bitsPerSample: ?[]const u8 = null, // ?u8
nrAudioChannels: ?[]const u8 = null, // ?u8
resolution: ?[]const u8 = null,
colorDepth: ?[]const u8 = null, // ?u8
protection: ?[]const u8 = null,
},
__item__: []const u8,
}; | src/upnp/definition/content_directory.zig |
const std = @import("std");
pub const Value = union(enum) {
Object: []Member,
Array: []Value,
String: []const u8,
Int: i64,
Float: f64,
Bool: bool,
Null: void,
fn get_obj(self: Value, key: []const u8) ?Value {
if (self == .Object) {
for (self.Object) |member| {
if (std.mem.eql(u8, member.key, key)) {
return member.value;
}
}
}
return null;
}
pub fn get(self: Value, query: anytype) ?Value {
const TO = @TypeOf(query);
if (comptime std.meta.trait.isZigString(TO)) {
return self.get_obj(@as([]const u8, query));
}
const TI = @typeInfo(TO);
if (TI == .Int or TI == .ComptimeInt) {
if (self == .Array) {
return self.Array[i];
}
}
return self.fetch_inner(query, 0);
}
fn fetch_inner(self: Value, query: anytype, comptime n: usize) ?Value {
if (query.len == n) {
return self;
}
const i = query[n];
const TO = @TypeOf(i);
const TI = @typeInfo(TO);
if (comptime std.meta.trait.isZigString(TO)) {
if (self.get_obj(i)) |v| {
return v.fetch_inner(query, n + 1);
}
}
if (TI == .Int or TI == .ComptimeInt) {
if (self == .Array) {
return self.Array[i].fetch_inner(query, n + 1);
}
}
return null;
}
pub fn format(self: Value, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) @TypeOf(writer).Error!void {
_ = fmt;
_ = options;
switch (self) {
.Object => {
try writer.writeAll("{");
for (self.Object) |member, i| {
if (i > 0) {
try writer.writeAll(", ");
}
try writer.print("{}", .{member});
}
try writer.writeAll("}");
},
.Array => {
try writer.writeAll("[");
for (self.Array) |val, i| {
if (i > 0) {
try writer.writeAll(", ");
}
try writer.print("{}", .{val});
}
try writer.writeAll("]");
},
.String => {
try writer.print("\"{s}\"", .{self.String});
},
.Int => {
try writer.print("{d}", .{self.Int});
},
.Float => {
try writer.print("{}", .{self.Float});
},
.Bool => {
try writer.print("{}", .{self.Bool});
},
.Null => {
try writer.writeAll("null");
},
}
}
};
pub const Member = struct {
key: []const u8,
value: Value,
pub fn format(self: Member, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) @TypeOf(writer).Error!void {
_ = fmt;
_ = options;
try writer.print("\"{s}\": {}", .{ self.key, self.value });
}
};
const Parser = struct {
alloc: *std.mem.Allocator,
p: std.json.StreamingParser,
input: []const u8,
index: usize,
tok2: ?std.json.Token,
pub fn next(self: *Parser) !?std.json.Token {
if (self.tok2) |t2| {
defer self.tok2 = null;
return t2;
}
while (self.index < self.input.len) {
var tok: ?std.json.Token = null;
var tok2: ?std.json.Token = null;
const b = self.input[self.index];
try self.p.feed(b, &tok, &tok2);
self.index += 1;
if (tok) |_| {} else {
continue;
}
if (tok2) |t2| {
self.tok2 = t2;
}
return tok;
}
return null;
}
pub const Error =
std.fs.File.OpenError ||
std.json.StreamingParser.Error ||
std.mem.Allocator.Error ||
error{ Overflow } ||
error{InvalidCharacter} ||
error{ JsonExpectedObjKey, JsonExpectedValueStartGotEnd };
};
pub fn parse(alloc: *std.mem.Allocator, input: []const u8) Parser.Error!Value {
const p = &Parser{
.alloc = alloc,
.p = std.json.StreamingParser.init(),
.input = input,
.index = 0,
.tok2 = null,
};
return try parse_value(p, null);
}
fn parse_value(p: *Parser, start: ?std.json.Token) Parser.Error!Value {
const tok = start orelse try p.next();
return switch (tok.?) {
.ObjectBegin => Value{ .Object = try parse_object(p) },
.ObjectEnd => error.JsonExpectedValueStartGotEnd,
.ArrayBegin => Value{ .Array = try parse_array(p) },
.ArrayEnd => error.JsonExpectedValueStartGotEnd,
.String => |t| Value{ .String = t.slice(p.input, p.index - 1) },
.Number => |t| if (t.is_integer) Value{ .Int = try std.fmt.parseInt(i64, t.slice(p.input, p.index - 1), 10) }
else Value{ .Float = try std.fmt.parseFloat(f64, t.slice(p.input, p.index - 1)) },
.True => Value{ .Bool = true },
.False => Value{ .Bool = false },
.Null => Value{ .Null = {} },
};
}
fn parse_object(p: *Parser) Parser.Error![]Member {
const array = &std.ArrayList(Member).init(p.alloc);
defer array.deinit();
while (true) {
const tok = try p.next();
if (tok.? == .ObjectEnd) {
return array.toOwnedSlice();
}
if (tok.? != .String) {
return error.JsonExpectedObjKey;
}
try array.append(Member{
.key = tok.?.String.slice(p.input, p.index - 1),
.value = try parse_value(p, null),
});
}
}
fn parse_array(p: *Parser) Parser.Error![]Value {
const array = &std.ArrayList(Value).init(p.alloc);
defer array.deinit();
while (true) {
const tok = try p.next();
if (tok.? == .ArrayEnd) {
return array.toOwnedSlice();
}
try array.append(try parse_value(p, tok.?));
}
} | src/lib.zig |
const std = @import("std");
const c = @cImport({
@cInclude("Windows.h");
});
const Image = @import("Image.zig");
pub fn hasImage() bool {
const png_format = c.RegisterClipboardFormatA("PNG");
if (png_format != 0 and c.IsClipboardFormatAvailable(png_format) != 0) return true;
if (c.IsClipboardFormatAvailable(c.CF_DIBV5) != 0) return true;
return false;
}
pub fn getImage(allocator: *std.mem.Allocator) !?Image {
const png_format = c.RegisterClipboardFormatA("PNG");
if (png_format != 0 and c.IsClipboardFormatAvailable(png_format) != 0) {
if (c.OpenClipboard(null) == 0) return error.OpenClipboardFailed;
defer _ = c.CloseClipboard();
if (c.GetClipboardData(png_format)) |png_handle| {
const size = c.GlobalSize(png_handle);
if (c.GlobalLock(png_handle)) |local_mem| {
defer _ = c.GlobalUnlock(png_handle);
const data = @ptrCast([*]const u8, local_mem);
return try Image.initFromMemory(allocator, data[0..size]);
}
}
}
if (c.IsClipboardFormatAvailable(c.CF_DIBV5) != 0) {
if (c.OpenClipboard(null) == 0) return error.OpenClipboardFailed;
defer _ = c.CloseClipboard();
if (c.GetClipboardData(c.CF_DIBV5)) |handle| {
const ptr = @alignCast(@alignOf(*c.BITMAPV5HEADER), handle);
const header = @ptrCast(*c.BITMAPV5HEADER, ptr);
const bit_count = header.bV5BitCount;
var r_mask: u32 = 0xff_00_00;
var r_shift: u8 = 16;
var g_mask: u32 = 0x00_ff_00;
var g_shift: u8 = 8;
var b_mask: u32 = 0x00_00_ff;
var b_shift: u8 = 0;
var a_mask: u32 = 0xff_00_00_00;
var a_shift: u8 = 24;
if (header.bV5Compression == 3) { // BI_BITFIELDS (translate-c fail)
r_mask = header.bV5RedMask;
_ = r_shift; // TODO: calc shift
g_mask = header.bV5GreenMask;
_ = g_shift; // TODO: calc shift
b_mask = header.bV5BlueMask;
_ = b_shift; // TODO: calc shift
a_mask = header.bV5AlphaMask;
_ = a_shift; // TODO: calc shift
@panic("TODO");
}
const src = @ptrCast([*]u8, ptr)[header.bV5Size .. header.bV5Size + header.bV5SizeImage];
var image: Image = undefined;
image.width = @intCast(u32, header.bV5Width);
image.height = @intCast(u32, header.bV5Height);
image.pixels = try allocator.alloc(u8, 4 * image.width * image.height);
if (bit_count == 24) {
const bytes_per_row = 3 * image.width;
const pitch = 4 * ((bytes_per_row + 3) / 4);
var y: u32 = 0;
while (y < image.height) : (y += 1) {
const y_flip = image.height - 1 - y;
var x: u32 = 0;
while (x < image.width) : (x += 1) {
const r = src[(y * pitch + 3 * x) + 2];
const g = src[(y * pitch + 3 * x) + 1];
const b = src[(y * pitch + 3 * x) + 0];
image.pixels[4 * (y_flip * image.width + x) + 0] = r;
image.pixels[4 * (y_flip * image.width + x) + 1] = g;
image.pixels[4 * (y_flip * image.width + x) + 2] = b;
image.pixels[4 * (y_flip * image.width + x) + 3] = 0xff;
}
}
return image;
} else {
@panic("TODO");
}
}
// if (c.IsClipboardFormatAvailable(c.CF_DIB) != 0) {
// const handle = c.GetClipboardData(c.CF_DIB);
// if (handle != null) {
// const header = @ptrCast(*c.BITMAPINFO, @alignCast(@alignOf(*c.BITMAPINFO), handle));
// image.width = @intCast(u32, header.bmiHeader.biWidth);
// image.height = @intCast(u32, header.bmiHeader.biWidth);
// @panic("TODO");
// }
// }
}
return null;
}
pub fn setImage(allocator: *std.mem.Allocator, image: Image) !void {
const png_format = c.RegisterClipboardFormatA("PNG");
if (png_format == 0) return error.FormatPngUnsupported;
if (c.OpenClipboard(null) == 0) return error.OpenClipboardFailed;
defer _ = c.CloseClipboard();
if (c.EmptyClipboard() == 0) return error.EmptyClipboardFailed;
var png_data = try image.writeToMemory(allocator);
defer allocator.free(png_data);
// copy to global memory
const global_handle = c.GlobalAlloc(c.GMEM_MOVEABLE, png_data.len);
if (global_handle == null) return error.GlobalAllocFail;
defer _ = c.GlobalFree(global_handle);
if (c.GlobalLock(global_handle)) |local_mem| {
defer _ = c.GlobalUnlock(global_handle);
const data = @ptrCast([*]u8, local_mem);
std.mem.copy(u8, data[0..png_data.len], png_data);
_ = c.SetClipboardData(png_format, global_handle);
}
} | src/ClipboardWin32.zig |
const std = @import("std");
const tools = @import("tools");
const with_trace = true;
const assert = std.debug.assert;
fn trace(comptime fmt: []const u8, args: anytype) void {
if (with_trace) std.debug.print(fmt, args);
}
fn abs(a: i32) i32 {
return if (a > 0) a else -a;
}
fn min(a: i32, b: i32) i32 {
return if (a > b) b else a;
}
fn max(a: i32, b: i32) i32 {
return if (a > b) a else b;
}
pub fn main() anyerror!void {
const stdout = std.io.getStdOut().writer();
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
const limit = 1 * 1024 * 1024 * 1024;
const text = try std.fs.cwd().readFileAlloc(allocator, "day11.txt", limit);
defer allocator.free(text);
const Dir = enum {
n,
nw,
sw,
s,
se,
ne,
};
const dirnames = [_]struct {
d: Dir,
str: []const u8,
}{
.{ .d = .n, .str = "n" },
.{ .d = .nw, .str = "nw" },
.{ .d = .sw, .str = "sw" },
.{ .d = .s, .str = "s" },
.{ .d = .se, .str = "se" },
.{ .d = .ne, .str = "ne" },
};
var x: i32 = 0;
var y: i32 = 0;
var z: i32 = 0;
var maxd: i32 = 0;
var it = std.mem.tokenize(u8, text, ",\n");
while (it.next()) |dir| {
const d = for (dirnames) |dn| {
if (std.mem.eql(u8, dir, dn.str))
break dn.d;
} else unreachable;
switch (d) {
.n => {
x += 0;
y += 1;
z -= 1;
},
.nw => {
x -= 1;
y += 1;
z -= 0;
},
.sw => {
x -= 1;
y += 0;
z += 1;
},
.s => {
x += 0;
y -= 1;
z += 1;
},
.se => {
x += 1;
y -= 1;
z -= 0;
},
.ne => {
x += 1;
y += 0;
z -= 1;
},
}
assert(x + y + z == 0);
const dist = max(abs(x), max(abs(y), abs(z)));
if (dist > maxd) maxd = dist;
}
try stdout.print("dist={}+{}+{} = {}\n, maxd={}\n", .{
x, y, z,
max(abs(x), max(abs(y), abs(z))), maxd,
});
} | 2017/day11.zig |
const std = @import("std");
// dross-zig
const Dross = @import("../dross_zig.zig");
usingnamespace Dross;
// -----------------------------------------------------------------------------
// -----------------------------------------
// - Player -
// -----------------------------------------
///
pub const Player = struct {
//sprite: ?*Sprite = undefined,
animator: ?*Animator2d = undefined,
color: Color = undefined,
scale: Vector2 = undefined,
position: Vector3 = undefined,
flip_h: bool = false,
const Self = @This();
/// Allocates and builds a player
/// Comments: The caller will be the owner of the memory
pub fn new(allocator: *std.mem.Allocator) !*Self {
var new_player = try allocator.create(Player);
new_player.position = Vector3.new(0.0, 1.0, 0.0);
new_player.scale = Vector2.new(1.0, 1.0);
new_player.color = Color.white();
new_player.flip_h = false;
new_player.animator = try Animator2d.new(allocator);
const texture_op = try ResourceHandler.loadTexture("player_ani", "assets/sprites/s_player_sheet.png");
const texture_atlas = texture_op orelse return TextureErrors.FailedToLoad;
var idle_animation: *Animation2d = undefined;
var move_animation: *Animation2d = undefined;
var jump_animation: *Animation2d = undefined;
var climb_animation: *Animation2d = undefined;
idle_animation = try Animation2d.new(allocator, "idle");
move_animation = try Animation2d.new(allocator, "move");
jump_animation = try Animation2d.new(allocator, "jump");
climb_animation = try Animation2d.new(allocator, "climb");
const idle_duration_array = [_]f32{0.25} ** 2;
const move_duration_array = [_]f32{0.25} ** 4;
const jump_duration_array = [_]f32{0.25} ** 1;
const climb_duration_array = [_]f32{0.25} ** 4;
const idle_rso_array = [_]Vector2{Vector2.new(1.0, 1.0)} ** 2;
const move_rso_array = [_]Vector2{Vector2.new(1.0, 1.0)} ** 4;
const jump_rso_array = [_]Vector2{Vector2.new(1.0, 1.0)} ** 1;
const climb_rso_array = [_]Vector2{Vector2.new(1.0, 1.0)} ** 4;
idle_animation.setLoop(true);
move_animation.setLoop(true);
jump_animation.setLoop(false);
climb_animation.setLoop(true);
try idle_animation.createFromTexture(
texture_atlas,
Vector2.new(0.0, 4.0), // Starting coordinates
Vector2.new(16.0, 16.0), // Sprite Size
2, // Number of frames/cells/regions
idle_rso_array[0..],
idle_duration_array[0..], // Frame durations
);
try move_animation.createFromTexture(
texture_atlas,
Vector2.new(0.0, 2.0), // Starting coordinates
Vector2.new(16.0, 16.0), // Sprite Size
4, // Number of frames/cells/regions
move_rso_array[0..],
move_duration_array[0..], // Frame durations
);
try jump_animation.createFromTexture(
texture_atlas,
Vector2.new(0.0, 3.0), // Starting coordinates
Vector2.new(16.0, 16.0), // Sprite Size
1, // Number of frames/cells/regions
jump_rso_array[0..],
jump_duration_array[0..], // Frame durations
);
try climb_animation.createFromTexture(
texture_atlas,
Vector2.new(0.0, 0.0), // Starting coordinates
Vector2.new(16.0, 16.0), // Sprite Size
4, // Number of frames/cells/regions
climb_rso_array[0..],
climb_duration_array[0..], // Frame durations
);
try new_player.animator.?.addAnimation(idle_animation);
try new_player.animator.?.addAnimation(move_animation);
try new_player.animator.?.addAnimation(jump_animation);
try new_player.animator.?.addAnimation(climb_animation);
new_player.animator.?.play("idle", false);
return new_player;
}
/// Frees any allocated memory
pub fn free(allocator: *std.mem.Allocator, self: *Self) void {
Animator2d.free(allocator, self.animator.?);
allocator.destroy(self);
}
/// Update logic
pub fn update(self: *Self, delta: f32) void {
const speed: f32 = 8.0 * delta;
const movement_smoothing = 0.6;
const input_horizontal = Input.keyPressedValue(DrossKey.KeyD) - Input.keyPressedValue(DrossKey.KeyA);
const input_vertical = Input.keyPressedValue(DrossKey.KeyW) - Input.keyPressedValue(DrossKey.KeyS);
const up = Input.keyReleased(DrossKey.KeyUp);
const down = Input.keyReleased(DrossKey.KeyDown);
const target_position = self.position.add( //
Vector3.new( //
input_horizontal * speed, //
0.0, //
0.0, //
));
self.position = self.position.lerp(target_position, movement_smoothing);
if (input_horizontal > 0.0 and self.flip_h) {
// Negative scale
self.flip_h = false;
} else if (input_horizontal < 0.0 and !self.flip_h) {
self.flip_h = true;
// Positive scale
}
if (input_horizontal != 0.0) {
self.animator.?.play("move", false);
} else {
self.animator.?.play("idle", false);
}
self.animator.?.update(delta);
}
/// Rendering event
pub fn render(self: *Self) void {
//Renderer.drawSprite(self.sprite.?, self.position);
//if (!self.animator.?.playing()) return;
const animation = self.animator.?.animation() orelse return;
const frame = animation.textureRegion() orelse return;
Renderer.drawTexturedQuad(frame, self.position, self.scale, self.color, self.flip_h);
}
}; | src/sandbox/player.zig |
const c = @import("../../c_global.zig").c_imp;
const std = @import("std");
const za = @import("zalgebra");
// dross-zig
const VertexArrayGl = @import("vertex_array_opengl.zig").VertexArrayGl;
const vbgl = @import("vertex_buffer_opengl.zig");
const VertexBufferGl = vbgl.VertexBufferGl;
const BufferUsageGl = vbgl.BufferUsageGl;
const IndexBufferGl = @import("index_buffer_opengl.zig").IndexBufferGl;
const shad = @import("shader_opengl.zig");
const ShaderGl = shad.ShaderGl;
const ShaderTypeGl = shad.ShaderTypeGl;
const ShaderProgramGl = @import("shader_program_opengl.zig").ShaderProgramGl;
const Vertex = @import("../vertex.zig").Vertex;
// ----
const Color = @import("../../core/color.zig").Color;
const texture = @import("../texture.zig");
const TextureGl = @import("texture_opengl.zig").TextureGl;
const TextureId = texture.TextureId;
const TextureRegion = @import("../texture_region.zig").TextureRegion;
const Sprite = @import("../sprite.zig").Sprite;
const gly = @import("../font/glyph.zig");
const Glyph = gly.Glyph;
const font = @import("../font/font.zig");
const Font = font.Font;
const PackingMode = @import("../renderer.zig").PackingMode;
const ByteAlignment = @import("../renderer.zig").ByteAlignment;
const Camera = @import("../cameras/camera_2d.zig");
const Math = @import("../../math/math.zig").Math;
const Matrix4 = @import("../../core/matrix4.zig").Matrix4;
const Vector4 = @import("../../core/vector4.zig").Vector4;
const Vector3 = @import("../../core/vector3.zig").Vector3;
const Vector2 = @import("../../core/vector2.zig").Vector2;
const fs = @import("../../utils/file_loader.zig");
const rh = @import("../../core/resource_handler.zig");
const app = @import("../../core/application.zig");
const Application = @import("../../core/application.zig").Application;
const framebuffa = @import("../framebuffer.zig");
const Framebuffer = framebuffa.Framebuffer;
const FrameStatistics = @import("../../utils/profiling/frame_statistics.zig").FrameStatistics;
// ----------------------------------------------------------------------------------------
// Testing vertices and indices
// zig fmt: off
const square_vertices: [20]f32 = [20]f32{
// Positions / Texture coords
// 1.0, 1.0, 0.0, 1.0, 1.0, // Top Right
// 1.0, 0.0, 0.0, 1.0, 0.0,// Bottom Right
// 0.0, 0.0, 0.0, 0.0, 0.0,// Bottom Left
// 0.0, 1.0, 0.0, 0.0, 1.0,// Top Left
0.0, 0.0, 0.0, 0.0, 0.0, // Bottom Left
1.0, 0.0, 0.0, 1.0, 0.0,// Bottom Right
1.0, 1.0, 0.0, 1.0, 1.0,// Top Right
0.0, 1.0, 0.0, 0.0, 1.0,// Top Left
};
//[0 3]
//[2 1]
const square_indices: [6]c_uint = [6]c_uint{
// 0, 1, 3,
// 1, 2, 3,
0, 1, 2,
2, 3, 0
};
const screenbuffer_indices: [6]c_uint = [6]c_uint{
0, 1, 2,
0, 2, 3,
};
// zig fmt: off
//const screenbuffer_vertices: [24]f32 = [24]f32{
// // Positions / Texture coords
// -1.0, 1.0, 0.0, 1.0, // Bottom Left
// -1.0, -1.0, 0.0, 0.0,// Bottom Right
// 1.0, -1.0, 1.0, 0.0,// Top Right
//
// -1.0, 1.0, 0.0, 1.0,// Top Left
// 1.0, -1.0, 1.0, 0.0,// Top Left
// 1.0, 1.0, 1.0, 1.0,// Top Left
//};
// zig fmt: off
const QUAD_TEXTURE_UV: [4]Vector2 = [4]Vector2 {
Vector2.new(0.0, 0.0), // BL
Vector2.new(1.0, 0.0), // BR
Vector2.new(1.0, 1.0), // TR
Vector2.new(0.0, 1.0), // TL
};
// zig fmt: off
const QUAD_VERTEX_POSITIONS: [4]Vector3 = [4]Vector3 {
Vector3.new(0.0, 0.0, 0.0), // BL
Vector3.new(1.0, 0.0, 0.0), // BR
Vector3.new(1.0, 1.0, 0.0), // TR
Vector3.new(0.0, 1.0, 0.0), // TL
};
// -----------------------------------------
// - OpenGL Reference Material -
// -----------------------------------------
// OpenGL Types: https://www.khronos.org/opengl/wiki/OpenGL_Type
// Beginners: https://learnopengl.com/Introduction
// -----------------------------------------
// - GLSL Default Shaders -
// -----------------------------------------
const default_shader_vs: [:0]const u8 = "assets/shaders/default_shader.vs";
const default_shader_fs: [:0]const u8 = "assets/shaders/default_shader.fs";
const screenbuffer_shader_vs: [:0]const u8 = "assets/shaders/screenbuffer_shader.vs";
const screenbuffer_shader_fs: [:0]const u8 = "assets/shaders/screenbuffer_shader.fs";
const font_shader_vs: [:0]const u8 = "assets/shaders/font_shader.vs";
const font_shader_fs: [:0]const u8 = "assets/shaders/font_shader.fs";
const gui_shader_vs: [:0]const u8 = "assets/shaders/gui_shader.vs";
const gui_shader_fs: [:0]const u8 = "assets/shaders/gui_shader.fs";
// -----------------------------------------
// - OpenGL Errors -
// -----------------------------------------
/// Error set for OpenGL related errors
pub const OpenGlError = error{
/// Glad failed to initialize
GladFailure,
/// Failure during shader compilation
ShaderCompilationFailure,
/// Failure during shader program linking
ShaderLinkingFailure,
};
// -----------------------------------------
// - GlPackingMode -
// -----------------------------------------
/// Describes what Packing Mode will be affected
/// by the following operations.
pub const GlPackingMode = enum(c_uint) {
/// Affects the packing of pixel data
Pack = c.GL_PACK_ALIGNMENT,
/// Affects the unpacking of pixel data
Unpack = c.GL_UNPACK_ALIGNMENT,
};
// -----------------------------------------
// - Renderer Maximums -
// -----------------------------------------
/// Maximum amount of quads per draw call
const MAX_QUADS = 10000;
/// Maximum amount of vertices used per draw call
const MAX_VERTICES = MAX_QUADS * 4;
/// Maximum amount of indices used per draw call
const MAX_INDICES = MAX_QUADS * 6;
/// Maximum amount of texture that can be bound per
/// draw call
const MAX_TEXTURE_SLOTS = 32;
// -----------------------------------------
// - RendererGl -
// -----------------------------------------
/// Backend Implmentation for OpenGL
/// Comments: This is for INTERNAL use only.
pub const RendererGl = struct {
/// Default shader program for drawing the scene
shader_program: ?*ShaderProgramGl = undefined,
/// Shader program for drawing the swapchain to the display
screenbuffer_program: ?*ShaderProgramGl = undefined,
/// Font Rendering program for drawing text
font_renderer_program: ?*ShaderProgramGl = undefined,
/// GUI program for drawing on the GUI layer for non-font rendering draws
gui_renderer_program: ?*ShaderProgramGl = undefined,
current_program: *ShaderProgramGl = undefined,
current_vertex_array: *VertexArrayGl = undefined,
current_vertex_buffer: *VertexBufferGl = undefined,
vertex_array: ?*VertexArrayGl = undefined,
vertex_buffer: ?*VertexBufferGl = undefined,
index_buffer: ?*IndexBufferGl = undefined,
screenbuffer_vertex_array: ?*VertexArrayGl = undefined,
screenbuffer_vertex_buffer: ?*VertexBufferGl = undefined,
screenbuffer_index_buffer: ?*IndexBufferGl = undefined,
font_renderer_vertex_array: ?*VertexArrayGl = undefined,
font_renderer_vertex_buffer: ?*VertexBufferGl = undefined,
font_renderer_index_buffer: ?*IndexBufferGl = undefined,
gui_renderer_vertex_array: ?*VertexArrayGl = undefined,
gui_renderer_vertex_buffer: ?*VertexBufferGl = undefined,
gui_renderer_index_buffer: ?*IndexBufferGl = undefined,
clear_color: Color = undefined,
default_draw_color: Color = undefined,
default_texture: ?*texture.Texture = undefined,
screenbuffer: ?*Framebuffer = undefined,
projection_view: ?Matrix4 = undefined,
//quad_vertices: std.ArrayList(Vertex) = undefined,
quad_vertex_base: []Vertex = undefined,
quad_vertex_ptr: [*]Vertex = undefined,
index_count: u32 = 0,
vertex_count: u32 = 0,
//texture_slots: std.ArrayHashMap(c_uint, void) = undefined,
texture_slots: []c_uint = undefined,
texture_slot_index: u32 = 1,
screenbuffer_vertices: std.ArrayList(Vertex) = undefined,
const Self = @This();
/// Builds the necessary components for the OpenGL renderer
/// Comments: INTERNAL use only. The OpenGlBackend will be the owner of the allocated memory.
pub fn new(allocator: *std.mem.Allocator) !*Self {
if (c.gladLoadGLLoader(@ptrCast(c.GLADloadproc, c.glfwGetProcAddress)) == 0) return OpenGlError.GladFailure;
var self = try allocator.create(RendererGl);
// Set up the default quad vertices
//self.quad_vertices = std.ArrayList(Vertex).init(allocator);
// TODO(devon): Change to ensureTotalCapacity when Zig is upgraded to master.
//try self.quad_vertices.ensureCapacity(MAX_VERTICES * @sizeOf(Vertex));
self.quad_vertex_base = try allocator.alloc(Vertex, MAX_VERTICES);
self.quad_vertex_ptr = self.quad_vertex_base.ptr;
self.index_count = 0;
//self.texture_slots = std.ArrayHashMap(c_uint, void).init(allocator);
//self.texture_slots.ensureCapacity(MAX_TEXTURE_SLOTS);
self.texture_slots = try allocator.alloc(c_uint, MAX_TEXTURE_SLOTS);
self.texture_slot_index = 1;
// -------------------
// Set up the screenbuffer vertices
self.screenbuffer_vertices = std.ArrayList(Vertex).init(allocator);
// Top Left
try self.screenbuffer_vertices.append(Vertex{
.x = 1.0, .y = 1.0, .z = 0.0,
.r = 1.0, .g = 1.0, .b = 1.0, .a = 1.0,
.u = 1.0, .v = 1.0,
.index = 0.0,
});
// Bottom Left
try self.screenbuffer_vertices.append(Vertex{
.x = -1.0, .y = 1.0, .z = 0.0,
.r = 1.0, .g = 1.0, .b = 1.0, .a = 1.0,
.u = 0.0, .v = 1.0,
.index = 0.0,
});
// Bottom Right
try self.screenbuffer_vertices.append(Vertex{
.x = -1.0, .y = -1.0, .z = 0.0,
.r = 1.0, .g = 1.0, .b = 1.0, .a = 1.0,
.u = 0.0, .v = 0.0,
.index = 0.0,
});
// Top Right
try self.screenbuffer_vertices.append(Vertex{
.x = 1.0, .y = -1.0, .z = 0.0,
.r = 1.0, .g = 1.0, .b = 1.0, .a = 1.0,
.u = 1.0, .v = 0.0,
.index = 0.0,
});
// -------------------
// Sets the pixel storage mode that affefcts the operation
// of subsequent glReadPixel as well as unpacking texture patterns.
//c.glPixelStorei(c.GL_UNPACK_ALIGNMENT, 1);
self.setByteAlignment(PackingMode.Unpack, ByteAlignment.One);
// Enable depth testing
c.glEnable(c.GL_DEPTH_TEST);
c.glEnable(c.GL_BLEND);
c.glBlendFunc(c.GL_SRC_ALPHA, c.GL_ONE_MINUS_SRC_ALPHA);
// Vertex Shaders
// -------------------------------------------
// Allocate and compile the vertex shader
var vertex_shader: *ShaderGl = try ShaderGl.new(allocator, ShaderTypeGl.Vertex);
try vertex_shader.source(default_shader_vs);
try vertex_shader.compile();
// Allocate and compile the vertex shader for the screenbuffer
var screenbuffer_vertex_shader: *ShaderGl = try ShaderGl.new(allocator, ShaderTypeGl.Vertex);
try screenbuffer_vertex_shader.source(screenbuffer_shader_vs);
try screenbuffer_vertex_shader.compile();
// Allocate and compile the vertex shader for the font rendering
var font_renderer_vertex_shader: *ShaderGl = try ShaderGl.new(allocator, ShaderTypeGl.Vertex);
try font_renderer_vertex_shader.source(font_shader_vs);
try font_renderer_vertex_shader.compile();
// Allocate and compile the vertex shader for the font rendering
var gui_renderer_vertex_shader: *ShaderGl = try ShaderGl.new(allocator, ShaderTypeGl.Vertex);
try gui_renderer_vertex_shader.source(gui_shader_vs);
try gui_renderer_vertex_shader.compile();
// Fragment Shaders
// -------------------------------------------
// Allocate and compile the fragment shader
var fragment_shader: *ShaderGl = try ShaderGl.new(allocator, ShaderTypeGl.Fragment);
try fragment_shader.source(default_shader_fs);
try fragment_shader.compile();
// Allocate and compile the vertex shader for the screenbuffer
var screenbuffer_fragment_shader: *ShaderGl = try ShaderGl.new(allocator, ShaderTypeGl.Fragment);
try screenbuffer_fragment_shader.source(screenbuffer_shader_fs);
try screenbuffer_fragment_shader.compile();
// Allocate and compile the fragment shader for the font rendering
var font_renderer_fragment_shader: *ShaderGl = try ShaderGl.new(allocator, ShaderTypeGl.Fragment);
try font_renderer_fragment_shader.source(font_shader_fs);
try font_renderer_fragment_shader.compile();
// Allocate and compile the fragment shader for the font rendering
var gui_renderer_fragment_shader: *ShaderGl = try ShaderGl.new(allocator, ShaderTypeGl.Fragment);
try gui_renderer_fragment_shader.source(gui_shader_fs);
try gui_renderer_fragment_shader.compile();
// Default shader program setup
// ---------------------------------------------------
// Allocate memory for the shader program
self.shader_program = try ShaderProgramGl.new(allocator);
// Attach the shaders to the shader program
self.shader_program.?.attach(vertex_shader);
self.shader_program.?.attach(fragment_shader);
// Link the shader program
try self.shader_program.?.link();
// Free the memory as they are no longer needed
ShaderGl.free(allocator, vertex_shader);
ShaderGl.free(allocator, fragment_shader);
// Screenbuffer shader program setup
// ----------------------------------------------------
// Allocate memory for the shader program
self.screenbuffer_program = try ShaderProgramGl.new(allocator);
// Attach the shaders to the shader program
self.screenbuffer_program.?.attach(screenbuffer_vertex_shader);
self.screenbuffer_program.?.attach(screenbuffer_fragment_shader);
// Link the shader program
try self.screenbuffer_program.?.link();
// Free the memory as they are no longer needed
ShaderGl.free(allocator, screenbuffer_vertex_shader);
ShaderGl.free(allocator, screenbuffer_fragment_shader);
// Font Renderer shader program setup
// ----------------------------------------------------
// Allocate memory for the shader program
self.font_renderer_program = try ShaderProgramGl.new(allocator);
// Attach the shaders to the shader program
self.font_renderer_program.?.attach(font_renderer_vertex_shader);
self.font_renderer_program.?.attach(font_renderer_fragment_shader);
// Link the shader program
try self.font_renderer_program.?.link();
// Free the memory as they are no longer needed
ShaderGl.free(allocator, font_renderer_vertex_shader);
ShaderGl.free(allocator, font_renderer_fragment_shader);
// GUI Renderer shader program setup
// ----------------------------------------------------
// Allocate memory for the shader program
self.gui_renderer_program = try ShaderProgramGl.new(allocator);
// Attach the shaders to the shader program
self.gui_renderer_program.?.attach(gui_renderer_vertex_shader);
self.gui_renderer_program.?.attach(gui_renderer_fragment_shader);
// Link the shader program
try self.gui_renderer_program.?.link();
// Free the memory as they are no longer needed
ShaderGl.free(allocator, gui_renderer_vertex_shader);
ShaderGl.free(allocator, gui_renderer_fragment_shader);
// Create VAO, VBO, and IB
// -----------------------------------------------------
self.vertex_array = try VertexArrayGl.new(allocator);
self.vertex_buffer = try VertexBufferGl.new(allocator);
self.index_buffer = try IndexBufferGl.new(allocator);
// --
self.screenbuffer_vertex_array = try VertexArrayGl.new(allocator);
self.screenbuffer_vertex_buffer = try VertexBufferGl.new(allocator);
self.screenbuffer_index_buffer = try IndexBufferGl.new(allocator);
// --
self.font_renderer_vertex_array = try VertexArrayGl.new(allocator);
self.font_renderer_vertex_buffer = try VertexBufferGl.new(allocator);
self.font_renderer_index_buffer = try IndexBufferGl.new(allocator);
// --
self.gui_renderer_vertex_array = try VertexArrayGl.new(allocator);
self.gui_renderer_vertex_buffer = try VertexBufferGl.new(allocator);
self.gui_renderer_index_buffer = try IndexBufferGl.new(allocator);
// Default VAO/VBO/IB
// -----------------------------------------------------------
// Bind VAO
// NOTE(devon): Order matters! Bind VAO first, and unbind last!
self.vertex_array.?.bind();
// Bind VBO
self.vertex_buffer.?.bind();
//var vertices_slice = square_vertices[0..];
//var vertices_slice = self.quad_vertices.items[0..];
//var vertices_slice = self.quad_vertex_base[0..];
//self.vertex_buffer.?.data(vertices_slice, BufferUsageGl.StaticDraw);
//self.vertex_buffer.?.dataV(vertices_slice, BufferUsageGl.DynamicDraw);
self.vertex_buffer.?.dataV(self.quad_vertex_base, BufferUsageGl.DynamicDraw);
// Fill the indices
// This will be deleted once we get out of scope.
var quad_indices_ar: [MAX_INDICES]c_uint = undefined;
var indicies_index: usize = 0;
var index_offset: c_uint = 0;
while(indicies_index < MAX_INDICES) : (indicies_index += 6) {
quad_indices_ar[indicies_index + 0] = index_offset + 0;
quad_indices_ar[indicies_index + 1] = index_offset + 1;
quad_indices_ar[indicies_index + 2] = index_offset + 2;
quad_indices_ar[indicies_index + 3] = index_offset + 2;
quad_indices_ar[indicies_index + 4] = index_offset + 3;
quad_indices_ar[indicies_index + 5] = index_offset + 0;
index_offset += 4;
}
// Bind IB
self.index_buffer.?.bind();
var indicies_slice = quad_indices_ar[0..];
self.index_buffer.?.data(indicies_slice, BufferUsageGl.StaticDraw);
//const size_of_vatb = 5;
const size_f32 = @sizeOf(f32);
const stride = @intCast(c_longlong, @sizeOf(Vertex));
//const stride = @intCast(c_longlong, @sizeOf(f32) * size_of_vatb);
const offset_position: u32 = 0;
const offset_color: u32 = 3 * size_f32;
const offset_tex: u32 = 7 * size_f32; // position offset(0) + the length of the color bytes
const offset_index: u32 = 9 * size_f32;
//const offset_tex: u32 = 3 * @sizeOf(f32); // position offset(0) + the length of the color bytes
const index_zero: c_int = 0;
const index_one: c_int = 1;
const index_two: c_int = 2;
const index_three: c_int = 3;
const size_position: c_uint = 3;
const size_color: c_uint = 4;
const size_tex_coords: c_uint = 2;
const size_index: c_uint = 1;
// Tells OpenGL how to interpret the vertex data(per vertex attribute)
// Uses the data to the currently bound VBO
// Position Attribute
c.glVertexAttribPointer(
index_zero, // Which vertex attribute we want to configure
size_position, // Size of vertex attribute (vec3 in this case)
c.GL_FLOAT, // Type of data
c.GL_FALSE, // Should the data be normalized?
stride, // Stride
@intToPtr(?*c_void, offset_position), // Offset
);
// Vertex Attributes are disabled by default, we need to enable them.
c.glEnableVertexAttribArray(index_zero);
// Color Attribute
c.glVertexAttribPointer(
index_one, // Which vertex attribute we want to configure
size_color, // Size of vertex attribute (vec2 in this case)
c.GL_FLOAT, // Type of data
c.GL_FALSE, // Should the data be normalized?
stride, // Stride
@intToPtr(?*c_void, offset_color), // Offset
);
// Enable Texture Coordinate Attribute
c.glEnableVertexAttribArray(index_one);
// Texture Coordinates Attribute
c.glVertexAttribPointer(
index_two, // Which vertex attribute we want to configure
size_tex_coords, // Size of vertex attribute (vec2 in this case)
c.GL_FLOAT, // Type of data
c.GL_FALSE, // Should the data be normalized?
stride, // Stride
@intToPtr(?*c_void, offset_tex), // Offset
);
// Enable Texture Coordinate Attribute
c.glEnableVertexAttribArray(index_two);
// Texture Index Attribute
c.glVertexAttribPointer(
index_three, // Which vertex attribute we want to configure
size_index, // Size of vertex attribute (vec2 in this case)
c.GL_FLOAT, // Type of data
c.GL_FALSE, // Should the data be normalized?
stride, // Stride
@intToPtr(?*c_void, offset_index), // Offset
);
// Enable Texture Coordinate Attribute
c.glEnableVertexAttribArray(index_three);
// Unbind the VBO
c.glBindBuffer(c.GL_ARRAY_BUFFER, index_zero);
// NOTE(devon): Do NOT unbind the EBO while a VAO is active as the bound
// bound element buffer object IS stored in the VAO; keep the EBO bound.
// Unbind the EBO
// Setup screenbuffer VAO/VBO
// ---------------------------------------------------
self.screenbuffer_vertex_array.?.bind();
self.screenbuffer_vertex_buffer.?.bind();
var screenbuffer_vertices_slice = self.screenbuffer_vertices.items[0..];
//var screenbuffer_vertices_slice = screenbuffer_vertices[0..];
self.screenbuffer_vertex_buffer.?.dataV(screenbuffer_vertices_slice, BufferUsageGl.StaticDraw);
//self.screenbuffer_vertex_buffer.?.data(screenbuffer_vertices_slice, BufferUsageGl.StaticDraw);
// Bind IB
self.screenbuffer_index_buffer.?.bind();
var buffer_slice = screenbuffer_indices[0..];
self.screenbuffer_index_buffer.?.data(buffer_slice, BufferUsageGl.StaticDraw);
//const screenbuffer_stride = @intCast(c_longlong, @sizeOf(f32) * 4);
//const screenbuffer_offset_tex: u32 = 2 * @sizeOf(f32); // position offset(0) + the length of the color bytes
const screenbuffer_stride = @intCast(c_longlong, @sizeOf(Vertex));
const screenbuffer_offset_color: u32 = 3 * size_f32;
const screenbuffer_offset_tex: u32 = 7 * size_f32; // position offset(0) + the length of the color bytes
const screenbuffer_offset_index: u32 = 9 * size_f32;
c.glEnableVertexAttribArray(index_zero);
c.glVertexAttribPointer(
index_zero,
size_position,
c.GL_FLOAT,
c.GL_FALSE,
screenbuffer_stride,
@intToPtr(?*c_void, offset_position), // Offset
);
c.glEnableVertexAttribArray(index_one);
c.glVertexAttribPointer(
index_one,
size_color,
c.GL_FLOAT,
c.GL_FALSE,
screenbuffer_stride,
@intToPtr(?*c_void, screenbuffer_offset_color), // Offset
);
c.glEnableVertexAttribArray(index_two);
c.glVertexAttribPointer(
index_two,
size_tex_coords,
c.GL_FLOAT,
c.GL_FALSE,
screenbuffer_stride,
@intToPtr(?*c_void, screenbuffer_offset_tex), // Offset
);
//c.glEnableVertexAttribArray(index_three);
//c.glVertexAttribPointer(
// index_three,
// size_index,
// c.GL_FLOAT,
// c.GL_FALSE,
// screenbuffer_stride,
// @intToPtr(?*c_void, screenbuffer_offset_index), // Offset
//);
// Setup framebuffers
// const screen_buffer_size = Vector2.new(1280, 720);
const screen_buffer_size = Application.viewportSize();
self.screenbuffer = try Framebuffer.new(allocator);
self.screenbuffer.?.bind(framebuffa.FramebufferType.Read);
self.screenbuffer.?.addColorAttachment(
allocator,
framebuffa.FramebufferAttachmentType.Color0,
screen_buffer_size,
);
self.screenbuffer.?.check();
framebuffa.Framebuffer.resetFramebuffer();
// Font Renderer
// ------------------------------------------
self.font_renderer_vertex_array.?.bind();
self.font_renderer_vertex_buffer.?.bind();
self.vertex_buffer.?.dataV(self.quad_vertex_base, BufferUsageGl.DynamicDraw);
// Bind IB
self.font_renderer_index_buffer.?.bind();
self.font_renderer_index_buffer.?.data(indicies_slice, BufferUsageGl.StaticDraw);
const font_stride = @intCast(c_longlong, @sizeOf(Vertex)); // 3 (pos(3)) + 2(tex(2)) + 4 (color(r, g, b, a)) + 1 (index(float))
c.glEnableVertexAttribArray(index_zero);
// Position
c.glVertexAttribPointer(
index_zero,
3,
c.GL_FLOAT,
c.GL_FALSE,
font_stride,
@intToPtr(?*c_void, 0), // Offset
);
c.glEnableVertexAttribArray(index_one);
// Color
c.glVertexAttribPointer(
index_one,
4,
c.GL_FLOAT,
c.GL_FALSE,
font_stride,
@intToPtr(?*c_void, size_f32 * 3),
);
c.glEnableVertexAttribArray(index_two);
// tex coords
c.glVertexAttribPointer(
index_two,
2,
c.GL_FLOAT,
c.GL_FALSE,
font_stride,
@intToPtr(?*c_void, size_f32 * 7),
);
c.glEnableVertexAttribArray(index_three);
// index
c.glVertexAttribPointer(
index_three,
1,
c.GL_FLOAT,
c.GL_FALSE,
font_stride,
@intToPtr(?*c_void, size_f32 * 9),
);
// Unbind VBO
c.glBindBuffer(c.GL_ARRAY_BUFFER, index_zero);
// Setup GUI
// -----------------------------------------------------------
self.gui_renderer_vertex_array.?.bind();
self.gui_renderer_vertex_buffer.?.bind();
// 6 vertices of 4 floats each
//self.gui_renderer_vertex_buffer.?.dataless(6 * 4, BufferUsageGl.DynamicDraw);
self.gui_renderer_vertex_buffer.?.dataV(self.quad_vertex_base, BufferUsageGl.DynamicDraw);
self.gui_renderer_index_buffer.?.bind();
self.gui_renderer_index_buffer.?.data(indicies_slice, BufferUsageGl.StaticDraw);
const gui_stride = @intCast(c_longlong, @sizeOf(Vertex));
// Position Attribute
c.glVertexAttribPointer(
index_zero, // Which vertex attribute we want to configure
size_position, // Size of vertex attribute (vec3 in this case)
c.GL_FLOAT, // Type of data
c.GL_FALSE, // Should the data be normalized?
gui_stride, // Stride
@intToPtr(?*c_void, offset_position), // Offset
);
c.glEnableVertexAttribArray(index_zero);
// Color Attribute
c.glVertexAttribPointer(
index_one, // Which vertex attribute we want to configure
size_color, // Size of vertex attribute (vec2 in this case)
c.GL_FLOAT, // Type of data
c.GL_FALSE, // Should the data be normalized?
gui_stride, // Stride
@intToPtr(?*c_void, offset_color), // Offset
);
c.glEnableVertexAttribArray(index_one);
// Texture Coordinates Attribute
c.glVertexAttribPointer(
index_two, // Which vertex attribute we want to configure
size_tex_coords, // Size of vertex attribute (vec2 in this case)
c.GL_FLOAT, // Type of data
c.GL_FALSE, // Should the data be normalized?
gui_stride, // Stride
@intToPtr(?*c_void, offset_tex), // Offset
);
c.glEnableVertexAttribArray(index_two);
// Texture Index Attribute
c.glVertexAttribPointer(
index_three, // Which vertex attribute we want to configure
size_index, // Size of vertex attribute (vec2 in this case)
c.GL_FLOAT, // Type of data
c.GL_FALSE, // Should the data be normalized?
gui_stride, // Stride
@intToPtr(?*c_void, offset_index), // Offset
);
c.glEnableVertexAttribArray(index_three);
// Unbind VBO
c.glBindBuffer(c.GL_ARRAY_BUFFER, index_zero);
// Unbind the VAO
c.glBindVertexArray(index_zero);
// ------------------------------
// Misc initializations
// Set the clear color
self.clear_color = Color.rgb(0.2, 0.2, 0.2);
self.default_draw_color = Color.rgb(1.0, 1.0, 1.0);
// Create the default texture
// TODO(devon): Switch from an actual texture to a dataless on with a width and height of (1,1)
const default_texture_op = try rh.ResourceHandler.loadTexture("default_texture", "assets/textures/t_default.png");
self.default_texture = default_texture_op orelse return texture.TextureErrors.FailedToLoad;
var samplers = [_]c_int{0} ** MAX_TEXTURE_SLOTS;
var sampler_index: usize = 0;
while(sampler_index < MAX_TEXTURE_SLOTS) : (sampler_index += 1) {
samplers[sampler_index] = @intCast(c_int, sampler_index);
}
self.shader_program.?.use();
self.shader_program.?.setIntArray("texture_slots", samplers[0..], MAX_TEXTURE_SLOTS);
self.font_renderer_program.?.use();
self.font_renderer_program.?.setIntArray("texture_slots", samplers[0..], MAX_TEXTURE_SLOTS);
self.texture_slots[0] = self.default_texture.?.id().id_gl;
return self;
}
/// Frees up any resources that was previously allocated
pub fn free(allocator: *std.mem.Allocator, self: *Self) void {
// Allow for OpenGL object to de-allocate any memory it needed
// -- Default
VertexArrayGl.free(allocator, self.vertex_array.?);
VertexBufferGl.free(allocator, self.vertex_buffer.?);
IndexBufferGl.free(allocator, self.index_buffer.?);
ShaderProgramGl.free(allocator, self.shader_program.?);
// - Screenbuffer
VertexArrayGl.free(allocator, self.screenbuffer_vertex_array.?);
VertexBufferGl.free(allocator, self.screenbuffer_vertex_buffer.?);
IndexBufferGl.free(allocator, self.screenbuffer_index_buffer.?);
ShaderProgramGl.free(allocator, self.screenbuffer_program.?);
Framebuffer.free(allocator, self.screenbuffer.?);
// - Font Renderer
VertexArrayGl.free(allocator, self.font_renderer_vertex_array.?);
VertexBufferGl.free(allocator, self.font_renderer_vertex_buffer.?);
IndexBufferGl.free(allocator, self.font_renderer_index_buffer.?);
ShaderProgramGl.free(allocator, self.font_renderer_program.?);
// - GUI Renderer
VertexArrayGl.free(allocator, self.gui_renderer_vertex_array.?);
VertexBufferGl.free(allocator, self.gui_renderer_vertex_buffer.?);
IndexBufferGl.free(allocator, self.gui_renderer_index_buffer.?);
ShaderProgramGl.free(allocator, self.gui_renderer_program.?);
// ---
//self.quad_vertices.deinit();
allocator.free(self.quad_vertex_base);
self.screenbuffer_vertices.deinit();
//self.texture_slots.deinit();
allocator.free(self.texture_slots);
allocator.destroy(self);
}
/// Setups up the OpenGL specific components for rendering
pub fn beginRender(self: *Self, camera: *Camera.Camera2d) void {
// Bind framebuffer
self.screenbuffer.?.bind(framebuffa.FramebufferType.Both);
// Clear the background color
self.clearColorAndDepth();
c.glEnable(c.GL_DEPTH_TEST);
c.glDepthFunc(c.GL_LESS);
c.glEnable(c.GL_CULL_FACE);
c.glCullFace(c.GL_BACK);
const camera_pos = camera.position();
const camera_target = camera.targetPosition();
const camera_direction = camera_pos.subtract(camera_target).normalize();
const camera_right = Vector3.up().cross(camera_direction).normalize();
const camera_up = camera_direction.cross(camera_right);
const camera_zoom = camera.zoom();
// Set up projection matrix
const viewport_size = Application.viewportSize();
const window_size = Application.windowSize();
const projection = Matrix4.orthographic(
0, // Left
viewport_size.x(), // Right
0, // top
viewport_size.y(), // bottom
-1.0, //Near
1.0, // Far
);
// Set up the view matrix
var view = Matrix4.fromTranslate(camera_pos).scale(Vector3.new(camera_zoom, camera_zoom, 0.0));
self.shader_program.?.use();
self.shader_program.?.setMatrix4("projection", projection);
self.shader_program.?.setMatrix4("view", view);
self.vertex_array.?.bind();
self.current_program = self.shader_program.?;
self.current_vertex_array = self.vertex_array.?;
self.current_vertex_buffer = self.vertex_buffer.?;
self.beginBatch();
}
/// Setups up the OpenGL specific components for rendering
pub fn beginGui(self: *Self) void {
// Set up projection matrix
const viewport_size = Application.viewportSize();
const window_size = Application.windowSize();
const gui_projection = Matrix4.orthographic(
0, // Left
window_size.x(), // Right
0, // top
window_size.y(), // bottom
-1.0, //Near
1.0, // Far
);
self.gui_renderer_program.?.use();
self.gui_renderer_program.?.setMatrix4("projection", gui_projection);
self.font_renderer_program.?.use();
self.font_renderer_program.?.setMatrix4("projection", gui_projection);
//self.current_program = self.font_renderer_program.?;
//self.current_vertex_array = self.font_renderer_vertex_array.?;
//self.current_vertex_buffer = self.font_renderer_vertex_buffer.?;
self.beginBatch();
}
/// Handles the framebuffer and clean up for the end of the user-defined render event
pub fn endRender(self: *Self) void {
// Submit to Gl
self.flush();
// Bind the default frame buffer
framebuffa.Framebuffer.resetFramebuffer();
// Disable depth testing
c.glDisable(c.GL_DEPTH_TEST);
self.clearColor();
// Use screenbuffer's shader program
self.screenbuffer_program.?.use();
// Bind screen vao
self.screenbuffer_vertex_array.?.bind();
// Bind screenbuffer's texture
self.screenbuffer.?.bindColorAttachment();
// Draw the quad
RendererGl.drawIndexed(6);
FrameStatistics.incrementQuadCount();
}
/// Handles the framebuffer and clean up for the end of the user-defined render event
pub fn endGui(self: *Self) void {
// Submit to Gl
self.flush();
}
/// Draws geometry with a index buffer
pub fn drawIndexed(index_count: u32) void {
const offset = @intToPtr(?*c_void, 0);
//const count: u32 = if (index_count == 0) v
// Draw
c.glDrawElements(
c.GL_TRIANGLES, // Primitive mode
@intCast(c_int, index_count), // Number of vertices/elements to draw
c.GL_UNSIGNED_INT, // Type of values in indices
offset, // Offset in a buffer or a pointer to the location where the indices are stored
);
FrameStatistics.incrementDrawCall();
}
/// Submit the render batch to OpenGl
pub fn flush(self: *Self) void {
// If there is nothing queued up to draw, then just leave.
if(self.index_count == 0) return;
// Bind program
self.current_program.use();
// Bind VAO
self.current_vertex_array.bind();
// Bind VBO
self.current_vertex_buffer.bind();
// Determine the size of the used portion of the quad vertex array
const data_size: u32 = @intCast(u32,
@ptrToInt(self.quad_vertex_ptr) - @ptrToInt(self.quad_vertex_base.ptr)
);
// Update the buffer data
self.current_vertex_buffer.subdataSize(self.quad_vertex_base, data_size);
// Bind all the batched textures
var index: c_uint = 0;
while(index < self.texture_slot_index) : (index += 1) {
TextureGl.bindUnit(index, self.texture_slots[index]);
}
RendererGl.drawIndexed(self.index_count);
}
/// Performs the required operations to begin batching
pub fn beginBatch(self: *Self) void {
self.index_count = 0;
self.quad_vertex_ptr = self.quad_vertex_base.ptr;
self.texture_slot_index = 1;
}
/// Submits the batch to draw, and begins a new batch.
pub fn endBatch(self: *Self) void {
self.flush();
self.beginBatch();
}
/// Sets up renderer to be able to draw a untextured quad.
pub fn drawQuad(self: *Self, position: Vector3) void {
// Bind Texture
c.glBindTexture(c.GL_TEXTURE_2D, self.default_texture.?.id().id_gl);
// Translation * Rotation * Scale
const transform = Matrix4.fromTranslate(position);
self.shader_program.?.setMatrix4("model", transform);
self.shader_program.?.setFloat3("sprite_color", self.default_draw_color.r, self.default_draw_color.g, self.default_draw_color.b);
// Bind the VAO
self.vertex_array.?.bind();
RendererGl.drawIndexed(6);
self.index_count += 6;
FrameStatistics.incrementQuadCount();
}
/// Sets up renderer to be able to draw a untextured quad.
pub fn drawColoredQuad(self: *Self, position: Vector3, size: Vector3, color: Color) void {
self.checkForProperProgram(self.shader_program.?, self.vertex_buffer.?, self.vertex_array.?);
const x = position.x();
const y = position.y();
const z = position.z();
const w = size.x();
const h = size.y();
//const d = size.z();
const r = color.r;
const g = color.g;
const b = color.b;
const a = color.a;
// Bottom Left
self.quad_vertex_ptr[0].x = x;
self.quad_vertex_ptr[0].y = y;
self.quad_vertex_ptr[0].z = z;
self.quad_vertex_ptr[0].r = r;
self.quad_vertex_ptr[0].g = g;
self.quad_vertex_ptr[0].b = b;
self.quad_vertex_ptr[0].a = a;
self.quad_vertex_ptr[0].u = 0.0;
self.quad_vertex_ptr[0].v = 0.0;
self.quad_vertex_ptr[0].index = 0;
self.quad_vertex_ptr += 1;
// Bottom Right
self.quad_vertex_ptr[0].x = x + w;
self.quad_vertex_ptr[0].y = y;
self.quad_vertex_ptr[0].z = z;
self.quad_vertex_ptr[0].r = r;
self.quad_vertex_ptr[0].g = g;
self.quad_vertex_ptr[0].b = b;
self.quad_vertex_ptr[0].a = a;
self.quad_vertex_ptr[0].u = 1.0;
self.quad_vertex_ptr[0].v = 0.0;
self.quad_vertex_ptr[0].index = 0;
self.quad_vertex_ptr += 1;
// Top Right
self.quad_vertex_ptr[0].x = x + w;
self.quad_vertex_ptr[0].y = y + h;
self.quad_vertex_ptr[0].z = z;
self.quad_vertex_ptr[0].r = r;
self.quad_vertex_ptr[0].g = g;
self.quad_vertex_ptr[0].b = b;
self.quad_vertex_ptr[0].a = a;
self.quad_vertex_ptr[0].u = 1.0;
self.quad_vertex_ptr[0].v = 1.0;
self.quad_vertex_ptr[0].index = 0;
self.quad_vertex_ptr += 1;
// Top Left
self.quad_vertex_ptr[0].x = x;
self.quad_vertex_ptr[0].y = y + h;
self.quad_vertex_ptr[0].z = z;
self.quad_vertex_ptr[0].r = r;
self.quad_vertex_ptr[0].g = g;
self.quad_vertex_ptr[0].b = b;
self.quad_vertex_ptr[0].a = a;
self.quad_vertex_ptr[0].u = 0.0;
self.quad_vertex_ptr[0].v = 1.0;
self.quad_vertex_ptr[0].index = 0;
self.quad_vertex_ptr += 1;
// ---
self.index_count += 6;
FrameStatistics.incrementQuadCount();
}
/// Sets up renderer to be able to draw a untextured quad.
pub fn drawColoredQuadGui(self: *Self, position: Vector3, size: Vector3, color: Color) void {
self.checkForProperProgram(self.gui_renderer_program.?, self.gui_renderer_vertex_buffer.?, self.gui_renderer_vertex_array.?);
const x = position.x();
const y = position.y();
const z = position.z();
const w = size.x();
const h = size.y();
//const d = size.z();
const r = color.r;
const g = color.g;
const b = color.b;
const a = color.a;
// Bottom Left
self.quad_vertex_ptr[0].x = x;
self.quad_vertex_ptr[0].y = y;
self.quad_vertex_ptr[0].z = z;
self.quad_vertex_ptr[0].r = r;
self.quad_vertex_ptr[0].g = g;
self.quad_vertex_ptr[0].b = b;
self.quad_vertex_ptr[0].a = a;
self.quad_vertex_ptr[0].u = 0.0;
self.quad_vertex_ptr[0].v = 0.0;
self.quad_vertex_ptr[0].index = 0;
self.quad_vertex_ptr += 1;
// Bottom Right
self.quad_vertex_ptr[0].x = x + w;
self.quad_vertex_ptr[0].y = y;
self.quad_vertex_ptr[0].z = z;
self.quad_vertex_ptr[0].r = r;
self.quad_vertex_ptr[0].g = g;
self.quad_vertex_ptr[0].b = b;
self.quad_vertex_ptr[0].a = a;
self.quad_vertex_ptr[0].u = 1.0;
self.quad_vertex_ptr[0].v = 0.0;
self.quad_vertex_ptr[0].index = 0;
self.quad_vertex_ptr += 1;
// Top Right
self.quad_vertex_ptr[0].x = x + w;
self.quad_vertex_ptr[0].y = y + h;
self.quad_vertex_ptr[0].z = z;
self.quad_vertex_ptr[0].r = r;
self.quad_vertex_ptr[0].g = g;
self.quad_vertex_ptr[0].b = b;
self.quad_vertex_ptr[0].a = a;
self.quad_vertex_ptr[0].u = 1.0;
self.quad_vertex_ptr[0].v = 1.0;
self.quad_vertex_ptr[0].index = 0;
self.quad_vertex_ptr += 1;
// Top Left
self.quad_vertex_ptr[0].x = x;
self.quad_vertex_ptr[0].y = y + h;
self.quad_vertex_ptr[0].z = z;
self.quad_vertex_ptr[0].r = r;
self.quad_vertex_ptr[0].g = g;
self.quad_vertex_ptr[0].b = b;
self.quad_vertex_ptr[0].a = a;
self.quad_vertex_ptr[0].u = 0.0;
self.quad_vertex_ptr[0].v = 1.0;
self.quad_vertex_ptr[0].index = 0;
self.quad_vertex_ptr += 1;
// ---
self.index_count += 6;
FrameStatistics.incrementQuadCount();
// Use Text Rendering shader program
//self.gui_renderer_program.?.use();
//
//// Pass the quad color
//self.gui_renderer_program.?.setFloat4("draw_color", color.r, color.g, color.b, color.a);
//// Activate Texture Slot 0
//c.glActiveTexture(c.GL_TEXTURE0);
//// Bind vao
//self.gui_renderer_vertex_array.?.bind();
// // Bind Texture
//c.glBindTexture(c.GL_TEXTURE_2D, self.default_texture.?.id().id_gl);
//const x = position.x();
//const y = position.y();
//const w = size.x();
//const h = size.y();
////zig fmt: off
//const vertices: [24]f32 = [24]f32 {
//// Position Texture Coords
// x, y, 0.0, 0.0,
// x, y+h, 0.0, 1.0,
// x+w, y+h, 1.0, 1.0,
// x, y, 0.0, 0.0,
// x+w, y+h, 1.0, 1.0,
// x+w, y, 1.0, 0.0,
//};
//const vertices_slice = vertices[0..];
//// Update VBO
//self.gui_renderer_vertex_buffer.?.bind();
//self.gui_renderer_vertex_buffer.?.subdata(vertices_slice);
//VertexBufferGl.clearBoundVertexBuffer();
//// Bind the VAO
//self.gui_renderer_vertex_array.?.bind();
//
//c.glDrawArrays(c.GL_TRIANGLES, 0, 6);
//FrameStatistics.incrementQuadCount();
//FrameStatistics.incrementDrawCall();
}
/// Queues a textured quad to be drawn
pub fn drawTexturedQuad(self: *Self, texture_region: *TextureRegion, position: Vector3, scale: Vector2, color: Color, flip_h: bool) void {
// Translation * Rotation * Scale
// Translation
var model = Matrix4.fromTranslate(position);
// Scaling
const texture_scale = Vector3.fromVector2(scale, 1.0);
model = model.scale(texture_scale);
// Determine if the sprite has a texture assigned to it
const texture_id = texture_region.texture().?.id();
const texture_coordinates = texture_region.textureCoordinates();
// Check to see if the current batch is full
self.checkBatch();
// Determine if the sprite's texture id has already been
// addded to the batch.
var texture_index = @intToFloat(f32, self.getTextureSlotIndex(texture_id.id_gl));
texture_index = if(texture_index == -1.0) 0.0 else texture_index;
// If not, then add it.
if (texture_index == 0.0) {
texture_index = @intToFloat(f32, self.texture_slot_index);
const no_errors = self.addTextureToBatch(texture_id.id_gl);
if(no_errors) {
self.texture_slot_index += 1;
}
}
const uv_min_x = texture_coordinates[0].x();
const uv_max_x = texture_coordinates[1].x();
const r = color.r;
const g = color.g;
const b = color.b;
const a = color.a;
const vertex_count: usize = 4;
var vertex_index: usize = 0;
while(vertex_index < vertex_count) : (vertex_index += 1) {
const position_4 = Vector4.fromVector3(QUAD_VERTEX_POSITIONS[vertex_index], 1.0);
const model_position = model.multiplyVec4(position_4);
const tex_coords = texture_coordinates[vertex_index];
self.quad_vertex_ptr[0].x = model_position.x();
self.quad_vertex_ptr[0].y = model_position.y();
self.quad_vertex_ptr[0].z = model_position.z();
self.quad_vertex_ptr[0].r = r;
self.quad_vertex_ptr[0].g = g;
self.quad_vertex_ptr[0].b = b;
self.quad_vertex_ptr[0].a = a;
self.quad_vertex_ptr[0].u = if(flip_h) uv_min_x + (uv_max_x - tex_coords.x()) else tex_coords.x();
self.quad_vertex_ptr[0].v = tex_coords.y();
self.quad_vertex_ptr[0].index = texture_index;
self.quad_vertex_ptr += 1;
}
self.index_count += 6;
FrameStatistics.incrementQuadCount();
}
/// Sets up renderer to be able to draw a Sprite.
pub fn drawSprite(self: *Self, sprite: *Sprite, position: Vector3) void {
// Translation * Rotation * Scale
// Translation
var model = Matrix4.fromTranslate(position);
//// Rotation
//const texture_coords_x = sprite_origin.x() / sprite_size.x();
//const texture_coords_y = sprite_origin.y() / sprite_size.y();
//const model_to_origin = Vector3.new(
// texture_coords_x,
// texture_coords_y,
// 0.0,
//);
//
//const origin_to_model = Vector3.new(
// -texture_coords_x,
// -texture_coords_y,
// 0.0,
//);
//// Translate to the selected origin
//model = model.translate(model_to_origin);
//// Perform the rotation
//model = model.rotate(sprite_angle, Vector3.forward());
//// Translate back
//model = model.translate(origin_to_model);
// Scaling
const size = sprite.size().?;
const sprite_scale = sprite.scale();
const w = size.x() * sprite_scale.x();
const h = size.y() * sprite_scale.y();
//const scale = Vector3.new(w, h, 1.0);
const scale = Vector3.fromVector2(sprite.scale(), 1.0);
model = model.scale(scale);
// Determine if the sprite has a texture assigned to it
const texture_id_op = sprite.textureId();
const texture_id = texture_id_op orelse {
self.drawQuad(position);
return;
};
const texture_coordinates = sprite.textureRegion().?.textureCoordinates();
// Check to see if the current batch is full
self.checkBatch();
// Determine if the sprite's texture id has already been
// addded to the batch.
var texture_index = @intToFloat(f32, self.getTextureSlotIndex(texture_id.id_gl));
texture_index = if(texture_index == -1.0) 0.0 else texture_index;
// If not, then add it.
if (texture_index == 0.0) {
texture_index = @intToFloat(f32, self.texture_slot_index);
const no_errors = self.addTextureToBatch(texture_id.id_gl);
if(no_errors) {
self.texture_slot_index += 1;
}
}
const color = sprite.color();
const sprite_flip = sprite.flipH();
//const d = size.z();
const r = color.r;
const g = color.g;
const b = color.b;
const a = color.a;
const vertex_count: usize = 4;
var vertex_index: usize = 0;
while(vertex_index < vertex_count) : (vertex_index += 1) {
const position_4 = Vector4.fromVector3(QUAD_VERTEX_POSITIONS[vertex_index], 1.0);
const model_position = model.multiplyVec4(position_4);
const tex_coords = texture_coordinates[vertex_index];
self.quad_vertex_ptr[0].x = model_position.x();
self.quad_vertex_ptr[0].y = model_position.y();
self.quad_vertex_ptr[0].z = model_position.z();
self.quad_vertex_ptr[0].r = r;
self.quad_vertex_ptr[0].g = g;
self.quad_vertex_ptr[0].b = b;
self.quad_vertex_ptr[0].a = a;
self.quad_vertex_ptr[0].u = tex_coords.x();//if(sprite_flip) 1.0 - tex_coords.x() else tex_coords.x();
self.quad_vertex_ptr[0].v = tex_coords.y();
self.quad_vertex_ptr[0].index = texture_index;
self.quad_vertex_ptr += 1;
}
self.index_count += 6;
FrameStatistics.incrementQuadCount();
}
/// Sets up the renderer to be able to draw text
pub fn drawText(self: *Self, text: []const u8, x: f32, y: f32, scale: f32, color: Color) void {
self.checkForProperProgram(self.font_renderer_program.?, self.font_renderer_vertex_buffer.?, self.font_renderer_vertex_array.?);
// Loops through and draw
var text_length = text.len;
var index: usize = 0;
var cursor_x = x;
const r = color.r;
const g = color.g;
const b = color.b;
const a = color.a;
while(index < text_length) : (index += 1) {
const character: u8 = text[index];
const current_glyph = app.default_font.?.glyph(character) catch |err| {
std.debug.print("[Renderer]: Error occurred when retrieving glyph {}! {s}\n", .{character, err});
@panic("[Renderer]: Failed to find glyph!");
};
self.checkBatch();
const texture_id = current_glyph.texture().?.id().id_gl;
// Determine if the sprite's texture id has already been
// addded to the batch.
var texture_index = @intToFloat(f32, self.getTextureSlotIndex(texture_id));
texture_index = if(texture_index == -1.0) 0.0 else texture_index;
// If not, then add it.
if (texture_index == 0.0) {
texture_index = @intToFloat(f32, self.texture_slot_index);
const no_errors = self.addTextureToBatch(texture_id);
if(no_errors) {
self.texture_slot_index += 1;
}else {
// Submit batch
}
}
const offset = current_glyph.offset();
const glyph_width = @intToFloat(f32, current_glyph.width());
const glyph_rows = @intToFloat(f32, current_glyph.rows());
const x_pos = cursor_x + offset.x() * scale;
const y_pos = y - (glyph_rows - offset.y()) * scale;
const advance = current_glyph.advance();
const width = glyph_width * scale;
const height = glyph_rows * scale;
const vertex_count: usize = 4;
var vertex_index: usize = 0;
while(vertex_index < vertex_count) : (vertex_index += 1) {
const v_position = QUAD_VERTEX_POSITIONS[vertex_index];
const tex_coords = QUAD_TEXTURE_UV[vertex_index];
const vx = v_position.x();
const vy = v_position.y();
const vz = v_position.z();
const vu = tex_coords.x();
const vv = tex_coords.y();
self.quad_vertex_ptr[0].x = if(vx == 0.0) x_pos else x_pos + width;
self.quad_vertex_ptr[0].y = if(vy == 0.0) y_pos else y_pos + height;
self.quad_vertex_ptr[0].z = vz;
self.quad_vertex_ptr[0].r = r;
self.quad_vertex_ptr[0].g = g;
self.quad_vertex_ptr[0].b = b;
self.quad_vertex_ptr[0].a = a;
self.quad_vertex_ptr[0].u = vu;
self.quad_vertex_ptr[0].v = if(vv == 0.0) 1.0 else 0.0;
self.quad_vertex_ptr[0].index = texture_index;
self.quad_vertex_ptr += 1;
}
const shifted = @intToFloat(f32, (advance >> 6)) * scale;
// Advance the cursor
cursor_x += shifted;
self.index_count += 6;
FrameStatistics.incrementQuadCount();
}
}
/// Changes to clear color
pub fn changeClearColor(self: *Self, color: Color) void {
self.clear_color = color;
}
/// Clears the background with the set clear color
pub fn clearColorAndDepth(self: *Self) void {
c.glClearColor(self.clear_color.r, self.clear_color.g, self.clear_color.b, self.clear_color.a);
c.glClear(c.GL_COLOR_BUFFER_BIT | c.GL_DEPTH_BUFFER_BIT);
}
/// Clears the background with the set clear color and no DEPTH buffer
pub fn clearColor(self: *Self) void {
c.glClearColor(self.clear_color.r, self.clear_color.g, self.clear_color.b, self.clear_color.a);
c.glClear(c.GL_COLOR_BUFFER_BIT);
}
/// Request to disable byte_alignment restriction
pub fn setByteAlignment(self: *Self, packing_mode: PackingMode, byte_alignment: ByteAlignment) void {
const pack_type = switch(packing_mode) {
PackingMode.Pack => @enumToInt(GlPackingMode.Pack),
PackingMode.Unpack => @enumToInt(GlPackingMode.Unpack),
};
const alignment: c_int = switch(byte_alignment) {
ByteAlignment.One => 1,
ByteAlignment.Two => 2,
ByteAlignment.Four => 4,
ByteAlignment.Eight => 8,
};
c.glPixelStorei(pack_type, alignment);
}
/// Clears out the currently bound texture
pub fn clearBoundTexture() void {
c.glBindTexture(c.GL_TEXTURE_2D, 0);
}
// Batch-related functions/methods
// -----------------------------------
/// Adds a texture to the texture batch, if the unique texture ID
/// was not already added into the set.
/// Returns true if no errors occurred.
pub fn addTextureToBatch(self: *Self, id: c_uint) bool {
if(self.texture_slot_index >= MAX_TEXTURE_SLOTS) return false;
self.texture_slots[self.texture_slot_index] = id;
return true;
}
/// Returns whether or not the texture_slots is already at maximum capacity
/// Returns true if the batch is already at MAX_TEXTURE_SLOTS.
/// Otherwise, false.
pub fn checkTextureSlots(self: *Self) bool {
if(self.texture_slots.len >= MAX_TEXTURE_SLOTS) return true;
return false;
}
/// Returns whether or not the passed `id` is already
/// in the texture slot set.
pub fn containsTextureId(self: *Self, id: c_uint) bool {
for(self.texture_slots) | slot_id | {
if(slot_id == id) return true;
}
return false;
}
/// Returns the index of the texture id, if found in the
/// set. Otherwise, it'll return -1.
pub fn getTextureSlotIndex(self: *Self, id: c_uint) i8 {
var index: i8 = -1;
var counter: usize = 0;
while(counter < self.texture_slot_index) : (counter += 1) {
if(self.texture_slots[counter] == id) {
index = @intCast(i8, counter);
break;
}
}
return index;
}
/// Checks to see if the batch maximum bounds have
/// already been reached, if so, then the old batch
/// will be submitted for render, and a new batch will
/// begin.
pub fn checkBatch(self: *Self) void {
if(self.index_count >= MAX_INDICES or self.texture_slot_index >= MAX_TEXTURE_SLOTS) self.endBatch();
}
/// Checks to ensure that the currently bound shader program
/// is the one that will be used for the current render command.
/// If not, then it will submit the current batch to the renderer.
/// Then set the proper shader program, vertex buffer, and vertex array.
fn checkForProperProgram(self: *Self, program: *ShaderProgramGl, vertex_buffer: *VertexBufferGl, vertex_array: *VertexArrayGl) void {
if(self.current_program != program) {
self.endBatch();
self.current_program = program;
self.current_vertex_buffer = vertex_buffer;
self.current_vertex_array = vertex_array;
}
}
// -----------------------------------
};
/// Resizes the viewport to the given size and position
/// Comments: This is for INTERNAL use only.
pub fn resizeViewport(x: c_int, y: c_int, width: c_int, height: c_int) void {
c.glViewport(x, y, width, height);
} | src/renderer/backend/renderer_opengl.zig |
const std = @import("std");
const zs = @import("zstack.zig");
/// A piece is made up of many blocks. A block right now only indicates which piece it belonds to.
/// However, in the future we can add new attributes to do some more interesting mechanics to
/// the field.
///
/// Note that a field block is different from a piece block and a falling piece does only
/// requires a bitset.
pub const Block = struct {
id: Piece.Id,
};
pub const Color = struct {
r: u8,
g: u8,
b: u8,
a: u8,
};
pub const Piece = struct {
pub const Id = enum {
pub const count = @memberCount(@This());
I,
J,
L,
O,
S,
T,
Z,
pub fn fromInt(i: var) Id {
std.debug.assert(i >= 0 and i < count);
return @intToEnum(Piece.Id, @intCast(u3, i));
}
// Default color-scheme for a specific id.
pub fn color(self: Id) Color {
return switch (self) {
.I => Color{ .r = 5, .g = 186, .b = 221, .a = 255 },
.J => Color{ .r = 238, .g = 23, .b = 234, .a = 255 },
.L => Color{ .r = 249, .g = 187, .b = 0, .a = 255 },
.O => Color{ .r = 7, .g = 94, .b = 240, .a = 255 },
.S => Color{ .r = 93, .g = 224, .b = 31, .a = 255 },
.T => Color{ .r = 250, .g = 105, .b = 0, .a = 255 },
.Z => Color{ .r = 237, .g = 225, .b = 0, .a = 255 },
};
}
};
pub const Theta = enum {
pub const count = @memberCount(@This());
R0,
R90,
R180,
R270,
pub fn rotate(self: Theta, rotation: zs.Rotation) Piece.Theta {
const p = @intCast(u8, i8(@enumToInt(self)) + 4 + i8(@enumToInt(rotation)));
return @intToEnum(Piece.Theta, @intCast(u2, p % Theta.count));
}
};
pub const Blocks = [4]zs.Coord(u8);
/// What kind of piece this is.
id: Id,
/// x coodinate. Origin is top-left corner of bounding box.
x: i8,
fn ux(piece: Piece) u8 {
return @intCast(u8, piece.x);
}
/// y coordinate. Origin is top-left corner of bounding box.
y: i8,
fn uy(piece: Piece) u8 {
return @intCast(u8, piece.y);
}
/// When falling, we don't drop a square every tick. We need to have a fractional value
/// stored which represents how far through the current block we actually are.
///
/// TODO: Maybe change y so only actual value exists and user has to call y() to get the whole value.
y_actual: zs.uq8p24,
/// Maximum y this piece can fall to. Cached since this is used every render frame for a ghost.
y_hard_drop: i8,
/// Current rotation.
theta: Theta,
/// Number of ticks elapsed in a locking state (e.g. .Landed).
lock_timer: u32,
/// Number of times this piece has been floorkicked.
/// NOTE: Make floorkicks not configurable?
floorkick_count: u32,
pub fn init(engine: zs.Engine, id: Id, x: i8, y: i8, theta: Theta) Piece {
return Piece{
.id = id,
.x = x,
.y = y,
.y_actual = zs.uq8p24.init(@intCast(u8, y), 0),
.y_hard_drop = yHardDrop(engine, id, x, y, theta),
.theta = theta,
.lock_timer = 0,
.floorkick_count = 0,
};
}
pub fn yHardDrop(e: zs.Engine, id: Id, x: i8, y: i8, theta: Theta) i8 {
if (x >= @intCast(i8, e.options.well_width) or y >= @intCast(i8, e.options.well_height)) {
return @intCast(i8, e.options.well_height);
}
var y_new = y + 1;
while (!e.isCollision(id, x, y_new, theta)) : (y_new += 1) {}
return y_new - 1;
}
pub fn handleFloorkick(piece: *Piece, engine: zs.Engine, is_floorkick: bool) void {
if (is_floorkick and engine.options.floorkick_limit != 0) {
piece.floorkick_count += 1;
if (piece.floorkick_count >= engine.options.floorkick_limit) {
piece.lock_timer = zs.ticks(engine.options.lock_delay_ms);
}
}
}
// Unchecked move to an arbitrary position in the well.
pub fn move(piece: *Piece, engine: zs.Engine, x: i8, y: i8, theta: Theta) void {
piece.x = x;
piece.y = y;
piece.y_actual = zs.uq8p24.init(piece.uy(), piece.y_actual.frac()); // preserve fractional y position
piece.y_hard_drop = yHardDrop(engine, piece.id, x, y, theta);
piece.theta = theta;
}
}; | src/piece.zig |
const stb = @cImport({
// @cInclude("stb/stb_image_resize.h");
@cDefine("STBI_ASSERT(x)", "zig_assert(x)");
@cDefine("STBI_MALLOC(x)", "zig_malloc(x)");
@cDefine("STBI_REALLOC(x, n)", "zig_realloc(x, n)");
@cDefine("STBI_FREE(x)", "zig_free(x)");
@cDefine("STBI_NO_STDIO", {});
@cInclude("stb_image.h");
});
const std = @import("std");
comptime {
_ = @import("stb/zlibc.zig");
}
const debug = std.debug;
const fs = std.fs;
const mem = std.mem;
const io = std.io;
pub const u8x4 = std.meta.Vector(4, u8);
const u5x4 = std.meta.Vector(4, u5);
pub const Format = enum {
RGBA,
ARGB,
ABGR,
BGRA,
pub fn shiftMask(self: Format) u5x4 {
return switch (self) {
.BGRA => u5x4{ 16, 8, 0, 24 },
.RGBA => u5x4{ 0, 8, 16, 24 },
.ARGB => u5x4{ 8, 16, 24, 0 },
.ABGR => u5x4{ 24, 16, 8, 0 },
};
}
};
pub const Image = struct {
allocator: *mem.Allocator,
width: u16,
height: u16,
bytes: []u8,
fn io_cb(comptime S: type) type {
return struct {
fn read(user: ?*c_void, data: [*c]u8, size: c_int) callconv(.C) c_int {
nosuspend {
var stream = @ptrCast(?*S, @alignCast(@alignOf(S), user)).?.*;
const bytes_read = stream.read(data[0..@intCast(usize, size)]) catch |e| {
debug.panic("unable to read from stream of type {}: {}", .{ @typeName(S), e });
};
return @intCast(c_int, bytes_read);
}
}
fn skip(user: ?*c_void, size: c_int) callconv(.C) void {
nosuspend {
var stream = @ptrCast(?*S, @alignCast(@alignOf(S), user)).?.*;
stream.seekBy(@as(isize, size)) catch |e| {
debug.panic("unable to seek stream of type {}: {}", .{ @typeName(S), e });
};
}
}
fn eof(user: ?*c_void) callconv(.C) c_int {
nosuspend {
var stream = @ptrCast(?*S, @alignCast(@alignOf(S), user)).?.*;
var pos = stream.getPos() catch |e| {
debug.panic("unable to get current position for stream of type {}: {}", .{ @typeName(S), e });
};
var end = stream.getEndPos() catch |e| {
debug.panic("unable to get end position for stream of type {}: {}", .{ @typeName(S), e });
};
return if (pos == end) 1 else 0;
}
}
fn cb() stb.stbi_io_callbacks {
return .{
.read = read,
.skip = skip,
.eof = eof,
};
}
};
}
fn loadPixels(comptime fmt: Format, dst: []u8, src: []const u8) void {
var src_32 = @ptrCast([*]const u32, @alignCast(@alignOf([*]u32), src.ptr))[0 .. src.len / 4];
var dst_32 = @ptrCast([*]u32, @alignCast(@alignOf([*]u32), dst.ptr))[0 .. dst.len / 4];
const dst_mask = fmt.shiftMask();
for (src_32) |s, i| {
const v = (@splat(4, s) >> Format.RGBA.shiftMask());
const v_comp = v & @splat(4, @as(u32, 0xff));
dst_32[i] = @reduce(.Or, v_comp << dst_mask);
}
}
fn initImage(comptime fmt: Format, allocator: *mem.Allocator, pixels: [*c]const u8, data: [3]c_int) !Image {
var result: Image = .{
.allocator = allocator,
.width = @intCast(u16, data[0]),
.height = @intCast(u16, data[1]),
.bytes = undefined,
};
const len = @intCast(usize, result.width) * @intCast(usize, result.height) * 4;
result.bytes = try allocator.alloc(u8, len);
loadPixels(fmt, result.bytes, pixels[0..len]);
return result;
}
pub fn deinit(self: *Image) void {
self.allocator.free(self.bytes);
}
pub fn fromStream(comptime fmt: Format, stream: anytype, allocator: *mem.Allocator) !Image {
const cb = io_cb(@TypeOf(stream));
var stream_v = stream;
var data: [3]c_int = undefined;
var pixels = stb.stbi_load_from_callbacks(&cb.cb(), @ptrCast(*c_void, &stream_v), &data[0], &data[1], &data[2], 4);
if (pixels) |p| {
defer stb.stbi_image_free(p);
return initImage(fmt, allocator, p, data);
} else {
return error.StbError;
}
}
pub fn fromBytes(comptime fmt: Format, allocator: *mem.Allocator, bytes: []const u8) !Image {
var data: [3]c_int = undefined;
var pixels = stb.stbi_load_from_memory(bytes.ptr, @intCast(c_int, bytes.len), &data[0], &data[1], &data[2], 4);
if (pixels) |p| {
defer stb.stbi_image_free(p);
return initImage(fmt, allocator, p, data);
} else {
return error.StbError;
}
}
// is this okay to do?
pub fn asVectors(self: Image, cast: bool) ![]u8x4 {
if (!cast) {
var src_32 = @ptrCast([*]const u32, @alignCast(@alignOf([*]u32), self.bytes.ptr))[0 .. self.bytes.len / 4];
var result = self.allocator.alloc(std.meta.Vector(4, u8), src_32.len);
for (src_32) |s, i| {
// the 2 lowest bytes contain the channels we want
const v = (@splat(4, s) >> Format.RGBA.shiftMask());
// mask to get those channels
result[i] = v & @splat(4, @as(u32, 0xff));
}
return result;
} else {
return @ptrCast([*]u8x4, @alignCast(@alignOf([*]u8x4), self.bytes.ptr))[0 .. self.bytes.len / 4];
}
}
};
test "asVectors" {} | stb/stb.zig |
const std = @import("std");
const mem = std.mem;
const fmt = std.fmt;
const testing = std.testing;
const heap = std.heap;
const fs = std.fs;
const log = std.log;
const process = std.process;
const debug = std.debug;
const builtin = std.builtin;
const io = std.io;
const network = @import("network");
const parsing = @import("./parsing.zig");
const connection = @import("./connection.zig");
const ArrayList = std.ArrayList;
const Socket = network.Socket;
const SocketSet = network.SocketSet;
const EndPoint = network.EndPoint;
const BlockList = @import("./blocklist.zig").BlockList;
const Connection = connection.Connection;
const ReceivingState = @import("./connection.zig").ReceivingState;
const SendingState = @import("./connection.zig").SendingState;
const handleConnection = @import("./connection.zig").handleConnection;
const debug_prints = false;
pub const log_level = .info;
const Options = struct {
port: u16,
chunk_size: u16 = 256,
static_root: []const u8 = "./static/",
uid: ?u32 = null,
blocklist: ?BlockList = null,
memory_debug: bool = false,
dynamic_cache_size: u64 = 0,
};
pub fn Server(comptime handle_connection: anytype) type {
return struct {
const Self = @This();
endpoint: network.EndPoint,
socket: Socket,
connections: ArrayList(Connection),
socket_set: SocketSet,
request_stack_allocator: *mem.Allocator,
fixed_buffer_allocator: *heap.FixedBufferAllocator,
long_lived_allocator: *mem.Allocator,
chunk_size: u16,
memory_debug: bool,
running: bool,
local_endpoint: network.EndPoint,
options: Options,
pub fn init(
fixed_buffer_allocator: *heap.FixedBufferAllocator,
infrastructure_allocator: *mem.Allocator,
long_lived_allocator: *mem.Allocator,
address: network.Address,
port: u16,
chunk_size: u16,
memory_debug: bool,
options: Options,
) !Self {
var request_stack_allocator = &fixed_buffer_allocator.allocator;
const endpoint = network.EndPoint{
.address = address,
.port = port,
};
const socket = try Socket.create(network.AddressFamily.ipv4, network.Protocol.tcp);
var connections = ArrayList(Connection).init(infrastructure_allocator);
try socket.bind(endpoint);
try socket.listen();
if (builtin.os.tag == .linux or builtin.os.tag == .freebsd) {
try socket.enablePortReuse(true);
}
var socket_set = try SocketSet.init(infrastructure_allocator);
try socket_set.add(socket, .{ .read = true, .write = true });
const local_endpoint = try socket.getLocalEndPoint();
return Self{
.endpoint = endpoint,
.socket = socket,
.socket_set = socket_set,
.request_stack_allocator = request_stack_allocator,
.fixed_buffer_allocator = fixed_buffer_allocator,
.long_lived_allocator = long_lived_allocator,
.chunk_size = chunk_size,
.memory_debug = memory_debug,
.connections = connections,
.running = false,
.local_endpoint = local_endpoint,
.options = options,
};
}
pub fn deinit(self: Self) void {
self.socket.close();
self.socket_set.deinit();
}
pub fn run(self: *Self) !void {
self.running = true;
while (self.running) {
_ = network.waitForSocketEvent(&self.socket_set, 10_000_000_000_000) catch |e| {
if (builtin.os.tag == .windows) {
switch (e) {
error.FileDescriptorNotASocket => {
debug.print("===== ERROR socket_set={}", .{self.socket_set});
for (self.connections.items) |c, i| {
debug.print("===== ERROR connection{}={}", .{ i, c });
}
process.exit(1);
},
error.OutOfMemory => {},
error.Unexpected => {},
}
} else {
switch (e) {
error.SystemResources,
error.Unexpected,
error.NetworkSubsystemFailed,
=> unreachable,
}
}
};
if (self.socket_set.isReadyRead(self.socket)) {
const client_socket = self.socket.accept() catch |e| {
switch (e) {
error.SocketNotListening => {
log.err("Socket not listening", .{});
continue;
},
error.ConnectionResetByPeer, error.ConnectionAborted => {
log.err("Client aborted connection", .{});
continue;
},
error.FileDescriptorNotASocket,
error.NetworkSubsystemFailed,
error.OperationNotSupported,
error.ProcessFdQuotaExceeded,
error.SystemFdQuotaExceeded,
error.SystemResources,
error.UnsupportedAddressFamily,
error.ProtocolFailure,
error.BlockedByFirewall,
error.WouldBlock,
error.PermissionDenied,
error.Unexpected,
=> {
continue;
},
}
};
const remote_endpoint = client_socket.getRemoteEndPoint() catch |endpoint_error| {
log.err("=== Unable to get client endpoint: {} ===", .{endpoint_error});
switch (endpoint_error) {
error.UnsupportedAddressFamily,
error.Unexpected,
error.InsufficientBytes,
error.SystemResources,
=> {
client_socket.close();
continue;
},
error.NotConnected => continue,
}
};
if (self.options.blocklist == null or
!self.options.blocklist.?.isBlocked(remote_endpoint.address.ipv4))
{
self.socket_set.add(
client_socket,
.{ .read = true, .write = true },
) catch |socket_add_error| {
switch (socket_add_error) {
error.OutOfMemory => {
log.err(
"=== OOM when trying to add socket in socket_set: {} ===",
.{remote_endpoint},
);
client_socket.close();
continue;
},
}
};
insertIntoFirstFree(
&self.connections,
client_socket,
remote_endpoint,
) catch |insert_connection_error| {
switch (insert_connection_error) {
error.OutOfMemory => {
log.err(
"=== OOM when trying to add connection: {} ===",
.{remote_endpoint},
);
client_socket.close();
continue;
},
}
};
} else {
client_socket.close();
log.info("Blocked connection from: {}", .{remote_endpoint});
}
}
for (self.connections.items) |*c| {
c.* = try handle_connection(
c,
self.request_stack_allocator,
self.long_lived_allocator,
self.local_endpoint,
&self.socket_set,
self.options.chunk_size,
self.options.memory_debug,
self.connections,
self.options.static_root,
&self.running,
);
self.fixed_buffer_allocator.reset();
}
}
for (self.connections.items) |*c| {
switch (c.*) {
.idle => {},
.receiving => |receiving| {
receiving.socket.close();
},
.sending => |*sending| {
sending.socket.close();
sending.deinit(&self.socket_set);
},
}
}
}
};
}
const GeneralPurposeAllocator = heap.GeneralPurposeAllocator(.{});
pub fn main() anyerror!void {
try network.init();
defer network.deinit();
const options = try getCommandLineOptions(heap.page_allocator);
var logging_allocator = heap.loggingAllocator(heap.page_allocator, io.getStdOut().writer());
var general_purpose_allocator = GeneralPurposeAllocator{};
const long_lived_allocator = if (options.memory_debug)
&logging_allocator.allocator
else
&general_purpose_allocator.allocator;
var memory_buffer: [max_stack_file_read_size]u8 = undefined;
var fixed_buffer_allocator = heap.FixedBufferAllocator.init(&memory_buffer);
var server = try Server(handleConnection).init(
&fixed_buffer_allocator,
heap.page_allocator,
long_lived_allocator,
network.Address{ .ipv4 = .{ .value = [_]u8{ 0, 0, 0, 0 } } },
options.port,
options.chunk_size,
options.memory_debug,
options,
);
if (options.uid) |uid| try setUid(uid);
try server.run();
}
fn setUid(id: u32) !void {
if (builtin.os.tag == .linux or builtin.os.tag == .freebsd) {
try std.os.setuid(id);
}
}
fn getCommandLineOptions(allocator: *mem.Allocator) !Options {
const arguments = try process.argsAlloc(allocator);
defer process.argsFree(allocator, arguments);
const process_name = arguments[0];
const usage = "Usage: {} <port> [chunk-size=256] [static-root=./static] [blocklist=null]" ++
" [uid=null] [memory-debug=false] [dynamic-cache-size=0]";
if (arguments.len < 2) {
log.err(usage, .{process_name});
process.exit(1);
}
const port = try fmt.parseInt(u16, arguments[1], 10);
var options = Options{ .port = port };
for (arguments) |argument| {
if (mem.startsWith(u8, argument, "memory-debug")) {
var it = mem.split(argument, "=");
_ = it.next();
if (it.next()) |memory_debug| {
options.memory_debug = mem.eql(u8, memory_debug, "true");
}
} else if (mem.startsWith(u8, argument, "dynamic-cache-size=")) {
var it = mem.split(argument, "=");
_ = it.next();
if (it.next()) |dynamic_cache_size_string| {
options.dynamic_cache_size = try fmt.parseUnsigned(
u64,
dynamic_cache_size_string,
10,
);
}
} else if (mem.startsWith(u8, argument, "uid=")) {
var it = mem.split(argument, "=");
_ = it.next();
if (it.next()) |uid_value| {
options.uid = try fmt.parseUnsigned(u16, uid_value, 10);
}
} else if (mem.startsWith(u8, argument, "blocklist")) {
var it = mem.split(argument, "=");
_ = it.next();
if (it.next()) |filename| {
const blockListSlice = try fs.cwd().readFileAlloc(
allocator,
filename,
1_000_000,
);
options.blocklist = try BlockList.fromSlice(allocator, blockListSlice);
}
} else if (mem.startsWith(u8, argument, "chunk-size")) {
var it = mem.split(argument, "=");
_ = it.next();
if (it.next()) |chunk_size| {
options.chunk_size = try fmt.parseUnsigned(u16, chunk_size, 10);
}
} else if (mem.startsWith(u8, argument, "static-root")) {
var it = mem.split(argument, "=");
_ = it.next();
if (it.next()) |static_root_argument| {
const static_root = if (!mem.endsWith(u8, static_root_argument, "/"))
try mem.concat(
allocator,
u8,
&[_][]const u8{ static_root_argument, "/" },
)
else
try allocator.dupe(u8, static_root_argument);
options.static_root = static_root;
}
}
}
return options;
}
fn insertIntoFirstFree(
connections: *ArrayList(Connection),
socket: Socket,
endpoint: EndPoint,
) !void {
const timestamp = std.time.nanoTimestamp();
var found_slot = false;
const receiving_connection = Connection.receiving(socket, endpoint);
for (connections.items) |*c, i| {
switch (c.*) {
.idle => {
c.* = receiving_connection;
found_slot = true;
break;
},
.receiving, .sending => {},
}
}
if (!found_slot) try connections.append(receiving_connection);
}
fn getShutDownKey() !u128 {
var random_bytes: [8]u8 = undefined;
try std.crypto.randomBytes(random_bytes[0..]);
const seed = mem.readIntLittle(u64, random_bytes[0..8]);
var r = std.rand.DefaultCsprng.init(seed);
return r.random.int(u128);
}
const max_stack_file_read_size = 4_000_000;
const max_heap_file_read_size = 1_000_000_000_000; | src/main.zig |
const std = @import("std");
inline fn isSet(set: u1024, idx: usize) bool {
const mask = @as(u1024, 1) << @intCast(u10, idx);
return set & mask != 0;
}
inline fn setBit(set: *u1024, idx: usize) void {
const mask = @as(u1024, 1) << @intCast(u10, idx);
set.* = set.* | mask;
}
fn common(most: bool, numbers: [][]const u8, skip: u1024, idx: usize) ?u8 {
var count: isize = 0;
for (numbers) |n, i| {
if (isSet(skip, i)) continue;
switch (n[idx]) {
'0' => count -= 1,
'1' => count += 1,
else => unreachable,
}
}
if (count < 0) {
if (most) return '0' else return '1';
} else if (count > 0) {
if (most) return '1' else return '0';
} else return null;
}
fn criteria(numbers: [][]const u8, tie: u8, most: bool) !u32 {
var skip: u1024 = 0;
var remaining = numbers.len;
loop: for (numbers[0]) |_, i| {
var bit = common(most, numbers, skip, i) orelse tie;
for (numbers) |n, j| {
if (isSet(skip, j)) continue;
if (n[i] != bit) {
setBit(&skip, j);
remaining -= 1;
}
if (remaining == 1) break :loop;
}
} else return error.NotFound;
return std.fmt.parseInt(u32, numbers[@ctz(u1024, ~skip)], 2);
}
fn run(input: []const u8) !u32 {
var numbers: [1024][]const u8 = undefined;
var count: usize = 0;
var tokens = std.mem.tokenize(u8, input, "\n ");
while (tokens.next()) |t| {
numbers[count] = t;
count += 1;
}
const oxygen = try criteria(numbers[0..count], '1', true);
const co2 = try criteria(numbers[0..count], '0', false);
return oxygen * co2;
}
pub fn main() !void {
const input = @embedFile("3.txt");
const result = try run(input);
std.debug.print("{}\n", .{result});
}
test "example" {
const input = @embedFile("3_example.txt");
const result = try run(input);
try std.testing.expectEqual(@as(u32, 230), result);
} | shritesh+zig/3b.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const web = @import("zhp.zig");
const responses = web.responses;
const Status = responses.Status;
const Headers = web.Headers;
const Request = web.Request;
const IOStream = web.IOStream;
const Bytes = std.ArrayList(u8);
pub const Response = struct {
pub const WriteError = error{OutOfMemory};
pub const Writer = std.io.Writer(*Response, WriteError, Response.writeFn);
// Allocator for this response
allocator: *Allocator = undefined,
headers: Headers,
status: Status = responses.OK,
disconnect_on_finish: bool = false,
chunking_output: bool = false,
// If this is set, the response will read from the stream
send_stream: bool = false,
// Set to true if your request handler already sent everything
finished: bool = false,
stream: Writer = undefined,
// Buffer for output body, if the response is too big use source_stream
body: Bytes,
pub fn initCapacity(allocator: *Allocator, buffer_size: usize, max_headers: usize) !Response {
return Response{
.allocator = allocator,
.headers = try Headers.initCapacity(allocator, max_headers),
.body = try Bytes.initCapacity(allocator, buffer_size),
};
}
// Must be called before writing
pub fn prepare(self: *Response) void {
self.stream = Writer{.context = self};
}
// Reset the request so it can be reused without reallocating memory
pub fn reset(self: *Response) void {
self.body.items.len = 0;
self.headers.reset();
self.status = responses.OK;
self.disconnect_on_finish = false;
self.chunking_output = false;
self.send_stream = false;
self.finished = false;
}
// Write into the body buffer
// TODO: If the body reaches a certain limit it should be written
// into a file instead
pub fn writeFn(self: *Response, bytes: []const u8) WriteError!usize {
try self.body.appendSlice(bytes);
return bytes.len;
}
/// Redirect to the given location
/// if something was written to the stream already it will be cleared
pub fn redirect(self: *Response, location: []const u8) !void {
try self.headers.put("Location", location);
self.status = web.responses.FOUND;
self.body.items.len = 0; // Erase anything that was written
}
pub fn deinit(self: *Response) void {
self.headers.deinit();
self.body.deinit();
}
};
test "response" {
const allocator = std.testing.allocator;
var response = try Response.initCapacity(allocator, 4096, 1096);
response.prepare();
defer response.deinit();
_ = try response.stream.write("Hello world!\n");
std.testing.expectEqualSlices(u8, "Hello world!\n", response.body.items);
_ = try response.stream.print("{s}\n", .{"Testing!"});
std.testing.expectEqualSlices(u8, "Hello world!\nTesting!\n", response.body.items);
try response.headers.put("Content-Type", "Keep-Alive");
}
test "response-fns" {
std.testing.refAllDecls(Response);
} | src/response.zig |
const std = @import("std");
const mem = std.mem;
const testing = std.testing;
const Allocator = std.mem.Allocator;
var gost_sbox_1: [256]u32 = undefined;
var gost_sbox_2: [256]u32 = undefined;
var gost_sbox_3: [256]u32 = undefined;
var gost_sbox_4: [256]u32 = undefined;
const sbox: [8][16]u32 =
.{ .{ 4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3 }, .{ 14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9 }, .{ 5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11 }, .{ 7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3 }, .{ 6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2 }, .{ 4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14 }, .{ 13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12 }, .{ 1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12 } };
const SUM_INT_WIDTH = 8;
const HASH_U32_SIZE = 8;
const HASH_BYTE_SIZE = HASH_U32_SIZE * 4;
const HASH_BIT_SIZE = HASH_BYTE_SIZE * 8;
const GostHashCtx = struct {
sum: [SUM_INT_WIDTH]u32,
hash: [SUM_INT_WIDTH]u32,
len: [SUM_INT_WIDTH]u32,
partial: [HASH_BYTE_SIZE]u8,
partial_bytes: usize,
const Self = @This();
pub fn init() Self {
return Self { .sum = .{0} ** SUM_INT_WIDTH, .hash = .{0} ** SUM_INT_WIDTH, .len = .{0} ** SUM_INT_WIDTH, .partial = .{0} ** HASH_BYTE_SIZE, .partial_bytes = 0 };
}
//Mix in len bytes of data for the given buffer.
pub fn update(self: *Self, buf: []const u8) void {
var i: usize = self.partial_bytes;
var j: usize = 0;
var len: usize = buf.len;
while (i < 32 and j < len) {
self.partial[i] = buf[j];
i += 1;
j += 1;
}
if (i < 32) {
self.partial_bytes = i;
return;
}
gosthash_bytes(self, self.partial[0..], HASH_BIT_SIZE);
while ((j + 32) < len) {
gosthash_bytes(self, buf[j..], HASH_BIT_SIZE);
j += 32;
}
i = 0;
while (j < len) {
self.partial[i] = buf[j];
i += 1;
j += 1;
}
self.partial_bytes = i;
}
// Compute and save the 32-byte digest.
pub fn make_final(self: *Self, digest: *[HASH_BYTE_SIZE]u8) void {
var i: usize = 0;
var j: usize = 0;
var a: u32 = undefined;
// adjust and mix in the last chunk
if (self.partial_bytes > 0) {
var it: usize = self.partial_bytes;
while (it < self.partial.len) : (it += 1) {
self.partial[it] = 0;
}
gosthash_bytes(self, self.partial[0..], self.partial_bytes << 3);
}
// mix in the length and the sum
gosthash_compress(&self.hash, &self.len);
gosthash_compress(&self.hash, &self.sum);
// convert the output to bytes
while (i < 8) : (i += 1) {
a = self.hash[i];
digest[j] = @truncate(u8, a);
digest[j + 1] = @truncate(u8, a >> 8);
digest[j + 2] = @truncate(u8, a >> 16);
digest[j + 3] = @truncate(u8, a >> 24);
j += 4;
}
}
// Returns a slice owned by the caller
pub fn make_final_slice(self: *Self, allocator: Allocator) !*[HASH_BYTE_SIZE]u8 {
var slice = try allocator.alloc(u8, HASH_BYTE_SIZE);
var pointer: *[HASH_BYTE_SIZE]u8 = slice[0..HASH_BYTE_SIZE];
make_final(self, pointer);
return pointer;
}
pub fn reset(self: *Self) void {
self.sum = .{0} ** SUM_INT_WIDTH;
self.hash = .{0} ** SUM_INT_WIDTH;
self.len = .{0} ** SUM_INT_WIDTH;
self.partial = .{0} ** HASH_BYTE_SIZE;
self.partial_bytes = 0;
}
};
fn gost_encrypt_round(k1: u32, k2: u32, t: *usize, l: *u32, r: *u32) void {
t.* = (k1) +% r.*;
l.* ^= gost_sbox_1[t.* & 0xff] ^ gost_sbox_2[(t.* >> 8) & 0xff] ^ gost_sbox_3[(t.* >> 16) & 0xff] ^ gost_sbox_4[t.* >> 24];
t.* = (k2) +% l.*;
r.* ^= gost_sbox_1[t.* & 0xff] ^ gost_sbox_2[(t.* >> 8) & 0xff] ^ gost_sbox_3[(t.* >> 16) & 0xff] ^ gost_sbox_4[t.* >> 24];
}
fn gost_encrypt(key: [8]u32, t: *usize, l: *u32, r: *u32) void {
gost_encrypt_round(key[0], key[1], t, l, r);
gost_encrypt_round(key[2], key[3], t, l, r);
gost_encrypt_round(key[4], key[5], t, l, r);
gost_encrypt_round(key[6], key[7], t, l, r);
gost_encrypt_round(key[0], key[1], t, l, r);
gost_encrypt_round(key[2], key[3], t, l, r);
gost_encrypt_round(key[4], key[5], t, l, r);
gost_encrypt_round(key[6], key[7], t, l, r);
gost_encrypt_round(key[0], key[1], t, l, r);
gost_encrypt_round(key[2], key[3], t, l, r);
gost_encrypt_round(key[4], key[5], t, l, r);
gost_encrypt_round(key[6], key[7], t, l, r);
gost_encrypt_round(key[7], key[6], t, l, r);
gost_encrypt_round(key[5], key[4], t, l, r);
gost_encrypt_round(key[3], key[2], t, l, r);
gost_encrypt_round(key[1], key[0], t, l, r);
t.* = r.*;
r.* = l.*;
l.* = @truncate(u32, t.*);
}
// initialize the lookup tables
pub fn gosthash_init() void {
var a: usize = 0;
var b: usize = 0;
var i: usize = 0;
var ax: u32 = undefined;
var bx: u32 = undefined;
var cx: u32 = undefined;
var dx: u32 = undefined;
i = 0;
a = 0;
while (a < 16) : (a += 1) {
ax = sbox[1][a] << 15;
bx = sbox[3][a] << 23;
cx = sbox[5][a];
cx = (cx >> 1) | (cx << 31);
dx = sbox[7][a] << 7;
b = 0;
while (b < 16) : (b += 1) {
gost_sbox_1[i] = ax | (sbox[0][b] << 11);
gost_sbox_2[i] = bx | (sbox[2][b] << 19);
gost_sbox_3[i] = cx | (sbox[4][b] << 27);
gost_sbox_4[i] = dx | (sbox[6][b] << 3);
i += 1;
}
}
}
//"chi" compression function. the result is stored over h
fn gosthash_compress(h: *[SUM_INT_WIDTH]u32, m: *[SUM_INT_WIDTH]u32) void {
var i: usize = 0;
var l: u32 = undefined;
var r: u32 = undefined;
var t: usize = undefined;
var key: [8]u32 = undefined;
var u: [8]u32 = undefined;
var v: [8]u32 = undefined;
var w: [8]u32 = undefined;
var s: [8]u32 = undefined;
mem.copy(u32, &u, h[0..HASH_U32_SIZE]);
mem.copy(u32, &v, m[0..HASH_U32_SIZE]);
while (i < 8) : (i += 2) {
w[0] = u[0] ^ v[0]; // w = u xor v
w[1] = u[1] ^ v[1];
w[2] = u[2] ^ v[2];
w[3] = u[3] ^ v[3];
w[4] = u[4] ^ v[4];
w[5] = u[5] ^ v[5];
w[6] = u[6] ^ v[6];
w[7] = u[7] ^ v[7];
// P-Transformation
key[0] = (w[0] & 0x000000ff) | ((w[2] & 0x000000ff) << 8) |
((w[4] & 0x000000ff) << 16) | ((w[6] & 0x000000ff) << 24);
key[1] = ((w[0] & 0x0000ff00) >> 8) | (w[2] & 0x0000ff00) |
((w[4] & 0x0000ff00) << 8) | ((w[6] & 0x0000ff00) << 16);
key[2] = ((w[0] & 0x00ff0000) >> 16) | ((w[2] & 0x00ff0000) >> 8) |
(w[4] & 0x00ff0000) | ((w[6] & 0x00ff0000) << 8);
key[3] = ((w[0] & 0xff000000) >> 24) | ((w[2] & 0xff000000) >> 16) |
((w[4] & 0xff000000) >> 8) | (w[6] & 0xff000000);
key[4] = (w[1] & 0x000000ff) | ((w[3] & 0x000000ff) << 8) |
((w[5] & 0x000000ff) << 16) | ((w[7] & 0x000000ff) << 24);
key[5] = ((w[1] & 0x0000ff00) >> 8) | (w[3] & 0x0000ff00) |
((w[5] & 0x0000ff00) << 8) | ((w[7] & 0x0000ff00) << 16);
key[6] = ((w[1] & 0x00ff0000) >> 16) | ((w[3] & 0x00ff0000) >> 8) |
(w[5] & 0x00ff0000) | ((w[7] & 0x00ff0000) << 8);
key[7] = ((w[1] & 0xff000000) >> 24) | ((w[3] & 0xff000000) >> 16) |
((w[5] & 0xff000000) >> 8) | (w[7] & 0xff000000);
r = h[i]; // enciphering transformation
l = h[i + 1];
gost_encrypt(key, &t, &l, &r);
s[i] = r;
s[i + 1] = l;
if (i == 6) break;
l = u[0] ^ u[2]; // U = A(U)
r = u[1] ^ u[3];
u[0] = u[2];
u[1] = u[3];
u[2] = u[4];
u[3] = u[5];
u[4] = u[6];
u[5] = u[7];
u[6] = l;
u[7] = r;
if (i == 2) // Constant C_3
{
u[0] ^= 0xff00ff00;
u[1] ^= 0xff00ff00;
u[2] ^= 0x00ff00ff;
u[3] ^= 0x00ff00ff;
u[4] ^= 0x00ffff00;
u[5] ^= 0xff0000ff;
u[6] ^= 0x000000ff;
u[7] ^= 0xff00ffff;
}
l = v[0]; // V = A(A(V))
r = v[2];
v[0] = v[4];
v[2] = v[6];
v[4] = l ^ r;
v[6] = v[0] ^ r;
l = v[1];
r = v[3];
v[1] = v[5];
v[3] = v[7];
v[5] = l ^ r;
v[7] = v[1] ^ r;
}
// 12 rounds of the LFSR (computed from a product matrix) and xor in M
u[0] = m[0] ^ s[6];
u[1] = m[1] ^ s[7];
u[2] = m[2] ^ (s[0] << 16) ^ (s[0] >> 16) ^ (s[0] & 0xffff) ^
(s[1] & 0xffff) ^ (s[1] >> 16) ^ (s[2] << 16) ^ s[6] ^ (s[6] << 16) ^
(s[7] & 0xffff0000) ^ (s[7] >> 16);
u[3] = m[3] ^ (s[0] & 0xffff) ^ (s[0] << 16) ^ (s[1] & 0xffff) ^
(s[1] << 16) ^ (s[1] >> 16) ^ (s[2] << 16) ^ (s[2] >> 16) ^
(s[3] << 16) ^ s[6] ^ (s[6] << 16) ^ (s[6] >> 16) ^ (s[7] & 0xffff) ^
(s[7] << 16) ^ (s[7] >> 16);
u[4] = m[4] ^
(s[0] & 0xffff0000) ^ (s[0] << 16) ^ (s[0] >> 16) ^
(s[1] & 0xffff0000) ^ (s[1] >> 16) ^ (s[2] << 16) ^ (s[2] >> 16) ^
(s[3] << 16) ^ (s[3] >> 16) ^ (s[4] << 16) ^ (s[6] << 16) ^
(s[6] >> 16) ^ (s[7] & 0xffff) ^ (s[7] << 16) ^ (s[7] >> 16);
u[5] = m[5] ^ (s[0] << 16) ^ (s[0] >> 16) ^ (s[0] & 0xffff0000) ^
(s[1] & 0xffff) ^ s[2] ^ (s[2] >> 16) ^ (s[3] << 16) ^ (s[3] >> 16) ^
(s[4] << 16) ^ (s[4] >> 16) ^ (s[5] << 16) ^ (s[6] << 16) ^
(s[6] >> 16) ^ (s[7] & 0xffff0000) ^ (s[7] << 16) ^ (s[7] >> 16);
u[6] = m[6] ^ s[0] ^ (s[1] >> 16) ^ (s[2] << 16) ^ s[3] ^ (s[3] >> 16) ^
(s[4] << 16) ^ (s[4] >> 16) ^ (s[5] << 16) ^ (s[5] >> 16) ^ s[6] ^
(s[6] << 16) ^ (s[6] >> 16) ^ (s[7] << 16);
u[7] = m[7] ^ (s[0] & 0xffff0000) ^ (s[0] << 16) ^ (s[1] & 0xffff) ^
(s[1] << 16) ^ (s[2] >> 16) ^ (s[3] << 16) ^ s[4] ^ (s[4] >> 16) ^
(s[5] << 16) ^ (s[5] >> 16) ^ (s[6] >> 16) ^ (s[7] & 0xffff) ^
(s[7] << 16) ^ (s[7] >> 16);
// 16 * 1 round of the LFSR and xor in H
v[0] = h[0] ^ (u[1] << 16) ^ (u[0] >> 16);
v[1] = h[1] ^ (u[2] << 16) ^ (u[1] >> 16);
v[2] = h[2] ^ (u[3] << 16) ^ (u[2] >> 16);
v[3] = h[3] ^ (u[4] << 16) ^ (u[3] >> 16);
v[4] = h[4] ^ (u[5] << 16) ^ (u[4] >> 16);
v[5] = h[5] ^ (u[6] << 16) ^ (u[5] >> 16);
v[6] = h[6] ^ (u[7] << 16) ^ (u[6] >> 16);
v[7] = h[7] ^ (u[0] & 0xffff0000) ^ (u[0] << 16) ^ (u[7] >> 16) ^
(u[1] & 0xffff0000) ^ (u[1] << 16) ^ (u[6] << 16) ^ (u[7] & 0xffff0000);
// 61 rounds of LFSR, mixing up h (computed from a product matrix)
h[0] = (v[0] & 0xffff0000) ^ (v[0] << 16) ^ (v[0] >> 16) ^ (v[1] >> 16) ^
(v[1] & 0xffff0000) ^ (v[2] << 16) ^ (v[3] >> 16) ^ (v[4] << 16) ^
(v[5] >> 16) ^ v[5] ^ (v[6] >> 16) ^ (v[7] << 16) ^ (v[7] >> 16) ^
(v[7] & 0xffff);
h[1] = (v[0] << 16) ^ (v[0] >> 16) ^ (v[0] & 0xffff0000) ^ (v[1] & 0xffff) ^
v[2] ^ (v[2] >> 16) ^ (v[3] << 16) ^ (v[4] >> 16) ^ (v[5] << 16) ^
(v[6] << 16) ^ v[6] ^ (v[7] & 0xffff0000) ^ (v[7] >> 16);
h[2] = (v[0] & 0xffff) ^ (v[0] << 16) ^ (v[1] << 16) ^ (v[1] >> 16) ^
(v[1] & 0xffff0000) ^ (v[2] << 16) ^ (v[3] >> 16) ^ v[3] ^ (v[4] << 16) ^
(v[5] >> 16) ^ v[6] ^ (v[6] >> 16) ^ (v[7] & 0xffff) ^ (v[7] << 16) ^
(v[7] >> 16);
h[3] = (v[0] << 16) ^ (v[0] >> 16) ^ (v[0] & 0xffff0000) ^
(v[1] & 0xffff0000) ^ (v[1] >> 16) ^ (v[2] << 16) ^ (v[2] >> 16) ^ v[2] ^
(v[3] << 16) ^ (v[4] >> 16) ^ v[4] ^ (v[5] << 16) ^ (v[6] << 16) ^
(v[7] & 0xffff) ^ (v[7] >> 16);
h[4] = (v[0] >> 16) ^ (v[1] << 16) ^ v[1] ^ (v[2] >> 16) ^ v[2] ^
(v[3] << 16) ^ (v[3] >> 16) ^ v[3] ^ (v[4] << 16) ^ (v[5] >> 16) ^
v[5] ^ (v[6] << 16) ^ (v[6] >> 16) ^ (v[7] << 16);
h[5] = (v[0] << 16) ^ (v[0] & 0xffff0000) ^ (v[1] << 16) ^ (v[1] >> 16) ^
(v[1] & 0xffff0000) ^ (v[2] << 16) ^ v[2] ^ (v[3] >> 16) ^ v[3] ^
(v[4] << 16) ^ (v[4] >> 16) ^ v[4] ^ (v[5] << 16) ^ (v[6] << 16) ^
(v[6] >> 16) ^ v[6] ^ (v[7] << 16) ^ (v[7] >> 16) ^ (v[7] & 0xffff0000);
h[6] = v[0] ^ v[2] ^ (v[2] >> 16) ^ v[3] ^ (v[3] << 16) ^ v[4] ^
(v[4] >> 16) ^ (v[5] << 16) ^ (v[5] >> 16) ^ v[5] ^ (v[6] << 16) ^
(v[6] >> 16) ^ v[6] ^ (v[7] << 16) ^ v[7];
h[7] = v[0] ^ (v[0] >> 16) ^ (v[1] << 16) ^ (v[1] >> 16) ^ (v[2] << 16) ^
(v[3] >> 16) ^ v[3] ^ (v[4] << 16) ^ v[4] ^ (v[5] >> 16) ^ v[5] ^
(v[6] << 16) ^ (v[6] >> 16) ^ (v[7] << 16) ^ v[7];
}
// Mix in a 32-byte chunk ("stage 3")
fn gosthash_bytes(ctx: *GostHashCtx, buf: []const u8, bits: usize) void {
var i: usize = 0;
var j: usize = 0;
var a: u32 = undefined;
var b: u32 = undefined;
var c: u32 = 0;
var m: [8]u32 = undefined;
// convert bytes to a long words and compute the sum
while (i < 8) : (i += 1) {
a = buf[j] |
(@as(u32, buf[j + 1]) << 8) |
(@as(u32, buf[j + 2]) << 16) |
(@as(u32, buf[j + 3]) << 24);
j += 4;
m[i] = a;
b = ctx.sum[i];
c = a +% c +% ctx.sum[i];
ctx.sum[i] = c;
if ((c < a) or (c < b)) {
c = 1;
} else {
c = 0;
}
}
// compress
gosthash_compress(&ctx.hash, &m);
// a 64-bit counter should be sufficient
ctx.len[0] += @truncate(u32, bits);
if (ctx.len[0] < bits) {
ctx.len[1] += 1;
}
}
fn digest_to_hex_string(digest: *[HASH_BYTE_SIZE]u8, string: *[2 * HASH_BYTE_SIZE]u8) void {
var range: [16]u8 = .{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
var i: usize = 0;
while (i < digest.len) : (i += 1) {
var upper: u8 = digest[i] >> 4;
var lower: u8 = digest[i] & 15;
string[2 * i] = range[upper];
string[(2 * i) + 1] = range[lower];
}
}
test "gosthash_init" {
_ = GostHashCtx.init();
}
test "reset_struct" {
var hash_struct: GostHashCtx = undefined;
hash_struct.reset();
}
test "empty string" {
gosthash_init();
var hash_struct: GostHashCtx = GostHashCtx.init();
var empty_block: []u8 = &.{};
hash_struct.update(empty_block);
var digest: [32]u8 = .{0} ** 32;
hash_struct.make_final(&digest);
var hash_string: [64]u8 = undefined;
digest_to_hex_string(&digest, &hash_string);
const expected: []const u8 = "ce85b99cc46752fffee35cab9a7b0278abb4c2d2055cff685af4912c49490f8d";
try testing.expectEqualSlices(u8, expected[0..], hash_string[0..]);
}
test "teststring1" {
gosthash_init();
var hash_struct: GostHashCtx = GostHashCtx.init();
hash_struct.update("a"[0..]);
var digest: [32]u8 = .{0} ** 32;
hash_struct.make_final(&digest);
var hash_string: [64]u8 = undefined;
digest_to_hex_string(&digest, &hash_string);
const expected: []const u8 = "d42c539e367c66e9c88a801f6649349c21871b4344c6a573f849fdce62f314dd";
try testing.expectEqualSlices(u8, expected[0..], hash_string[0..]);
}
test "teststring2" {
gosthash_init();
var hash_struct: GostHashCtx = GostHashCtx.init();
hash_struct.update( "message digest"[0..]);
var digest: [32]u8 = .{0} ** 32;
hash_struct.make_final(&digest);
var hash_string: [64]u8 = undefined;
digest_to_hex_string(&digest, &hash_string);
const expected: []const u8 = "ad4434ecb18f2c99b60cbe59ec3d2469582b65273f48de72db2fde16a4889a4d";
try testing.expectEqualSlices(u8, expected[0..], hash_string[0..]);
}
test "teststring3" {
gosthash_init();
var hash_struct: GostHashCtx = GostHashCtx.init();
const mystring_const: []const u8 = "U" ** 128;
hash_struct.update( mystring_const[0..]);
var digest: [32]u8 = .{0} ** 32;
hash_struct.make_final(&digest);
var hash_string: [64]u8 = undefined;
digest_to_hex_string(&digest, &hash_string);
const expected: []const u8 = "53a3a3ed25180cef0c1d85a074273e551c25660a87062a52d926a9e8fe5733a4";
try testing.expectEqualSlices(u8, expected[0..], hash_string[0..]);
}
test "teststring4" {
gosthash_init();
var hash_struct: GostHashCtx = GostHashCtx.init();
const mystring_const: []const u8 = "a" ** 1000000;
hash_struct.update( mystring_const[0..]);
var digest: [32]u8 = .{0} ** 32;
hash_struct.make_final(&digest);
var hash_string: [64]u8 = undefined;
digest_to_hex_string(&digest, &hash_string);
const expected: []const u8 = "5c00ccc2734cdd3332d3d4749576e3c1a7dbaf0e7ea74e9fa602413c90a129fa";
try testing.expectEqualSlices(u8, expected[0..], hash_string[0..]);
}
test "teststring5" {
gosthash_init();
var hash_struct: GostHashCtx = GostHashCtx.init();
const mystring_const: []const u8 = "The quick brown fox jumps over the lazy dog";
hash_struct.update( mystring_const[0..]);
var digest: [32]u8 = .{0} ** 32;
hash_struct.make_final(&digest);
var hash_string: [64]u8 = undefined;
digest_to_hex_string(&digest, &hash_string);
const expected: []const u8 = "77b7fa410c9ac58a25f49bca7d0468c9296529315eaca76bd1a10f376d1f4294";
try testing.expectEqualSlices(u8, expected[0..], hash_string[0..]);
}
test "teststring6" {
gosthash_init();
var hash_struct: GostHashCtx = GostHashCtx.init();
const mystring_const: []const u8 = "The quick brown fox jumps over the lazy cog";
hash_struct.update( mystring_const[0..]);
var digest: [32]u8 = .{0} ** 32;
hash_struct.make_final(&digest);
var hash_string: [64]u8 = undefined;
digest_to_hex_string(&digest, &hash_string);
const expected: []const u8 = "a3ebc4daaab78b0be131dab5737a7f67e602670d543521319150d2e14eeec445";
try testing.expectEqualSlices(u8, expected[0..], hash_string[0..]);
}
test "piecewise hashing 1" {
gosthash_init();
// Load "a" twice
var hash_struct1: GostHashCtx = GostHashCtx.init();
hash_struct1.update( "a"[0..]);
hash_struct1.update( "a"[0..]);
var digest1: [32]u8 = .{0} ** 32;
hash_struct1.make_final(&digest1);
var hash_struct2: GostHashCtx = GostHashCtx.init();
// Load "aa" once
hash_struct2.update("aa"[0..]);
var digest2: [32]u8 = .{0} ** 32;
hash_struct2.make_final(&digest2);
// Hashes should be equal
try testing.expectEqualSlices(u8, digest1[0..], digest2[0..]);
}
test "piecewise hashing 2" {
gosthash_init();
var hash_struct1: GostHashCtx = GostHashCtx.init();
hash_struct1.update("The quick brown"[0..]);
hash_struct1.update(" fox jumps over the lazy dog"[0..]);
var digest1: [32]u8 = .{0} ** 32;
hash_struct1.make_final(&digest1);
var hash_struct2: GostHashCtx = GostHashCtx.init();
hash_struct2.update("The quick brown fox jumps over the lazy dog"[0..]);
var digest2: [32]u8 = .{0} ** 32;
hash_struct2.make_final(&digest2);
// Hashes should be equal
try testing.expectEqualSlices(u8, digest1[0..], digest2[0..]);
}
test "create digest by allocator" {
gosthash_init();
var hash_struct: GostHashCtx = GostHashCtx.init();
hash_struct.update("a"[0..]);
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
var digest = try hash_struct.make_final_slice(allocator);
var hash_string: [64]u8 = undefined;
digest_to_hex_string(digest, &hash_string);
const expected: []const u8 = "d42c539e367c66e9c88a801f6649349c21871b4344c6a573f849fdce62f314dd";
try testing.expectEqualSlices(u8, expected[0..], hash_string[0..]);
} | gosthash.zig |
const std = @import("std");
const Currency = @This();
platinum: u32 = 0,
gold: u32 = 0,
silver: u32 = 0,
copper: u32 = 0,
pub fn init(platinum: u32, gold: u32, silver: u32, copper: u32) Currency {
return .{
.platinum = platinum,
.gold = gold,
.silver = silver,
.copper = copper,
};
}
/// Does not normalize the result
pub fn plus(lhs: Currency, rhs: Currency) Currency {
return .{
.platinum = lhs.platinum + rhs.platinum,
.gold = lhs.gold + rhs.gold,
.silver = lhs.silver + rhs.silver,
.copper = lhs.copper + rhs.copper,
};
}
/// Always normalizes the result
pub fn minus(lhs: Currency, rhs: Currency) ?Currency {
const lhs_copper = lhs.asCopper();
const rhs_copper = rhs.asCopper();
if (lhs_copper >= rhs_copper) return fromCopper(lhs_copper - rhs_copper);
return null;
}
pub fn normalize(self: Currency) Currency {
const copper = self.copper;
const silver = self.silver + copper / 10;
const gold = self.gold + silver / 10;
const platinum = self.platinum + gold / 10;
return .{
.platinum = platinum,
.gold = gold % 10,
.silver = silver % 10,
.copper = copper % 10,
};
}
pub fn asCopper(self: Currency) u32 {
return self.platinum * 10 * 10 * 10 + self.gold * 10 * 10 + self.silver * 10 + self.copper;
}
pub fn fromCopper(copper: u32) Currency {
return (Currency{ .copper = copper }).normalize();
}
pub fn format(
self: Currency,
comptime fmt: []const u8,
_: std.fmt.FormatOptions,
writer: anytype,
) !void {
if (fmt.len == 0) {
try writer.print("{}p {}g {}s {}c", .{ self.platinum, self.gold, self.silver, self.copper });
} else if (comptime std.mem.eql(u8, "total", fmt)) {
try writer.print("{}", .{self.normalize()});
} else if (comptime std.mem.eql(u8, "copper", fmt)) {
try writer.print("{}c", .{self.totalCopper()});
} else {
@compileLog(fmt);
@compileError("Currency format must be {}, {total}, or {copper}");
}
}
test "Currency.plus" {
try std.testing.expectEqual((Currency{}).plus(Currency{}), Currency{});
try std.testing.expectEqual(Currency.init(0, 1, 0, 1).plus(Currency.init(1, 0, 1, 0)), Currency.init(1, 1, 1, 1));
try std.testing.expectEqual(Currency.init(5, 1, 8, 0).plus(Currency.init(1, 0, 1, 0)), Currency.init(6, 1, 9, 0));
}
test "Currency.minus" {
try std.testing.expectEqual((Currency{}).minus(Currency{}), Currency{});
try std.testing.expectEqual(Currency.init(0, 1, 0, 1).minus(Currency.init(1, 0, 1, 0)), null);
try std.testing.expectEqual(Currency.init(5, 1, 8, 0).minus(Currency.init(1, 0, 1, 0)).?, Currency.init(4, 1, 7, 0));
try std.testing.expectEqual(Currency.init(5, 0, 0, 0).minus(Currency.init(0, 0, 1, 0)).?, Currency.init(4, 9, 9, 0));
}
test "Currency.normalize" {
for ([_][2]Currency{
.{ Currency{}, Currency.init(0, 0, 0, 0) },
.{ Currency.init(0, 0, 0, 10), Currency.init(0, 0, 1, 0) },
.{ Currency.init(0, 0, 10, 10), Currency.init(0, 1, 1, 0) },
.{ Currency.init(0, 10, 10, 10), Currency.init(1, 1, 1, 0) },
.{ Currency.init(10, 10, 10, 10), Currency.init(11, 1, 1, 0) },
}) |pair| {
try std.testing.expectEqual(pair[0].normalize(), pair[1]);
}
}
test "Currency.format" {
var buf: [1024]u8 = undefined;
for ([_]std.meta.Tuple(&[_]type{ Currency, []const u8 }){
.{ Currency{}, "0p 0g 0s 0c" },
.{ Currency.init(0, 0, 0, 10), "0p 0g 0s 10c" },
.{ Currency.init(0, 0, 10, 10), "0p 0g 10s 10c" },
.{ Currency.init(0, 10, 10, 10), "0p 10g 10s 10c" },
.{ Currency.init(10, 10, 10, 10), "10p 10g 10s 10c" },
}) |pair| {
try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{}", .{pair[0]}), pair[1]);
}
for ([_]std.meta.Tuple(&[_]type{ Currency, []const u8 }){
.{ Currency{}, "0p 0g 0s 0c" },
.{ Currency.init(0, 0, 0, 10), "0p 0g 1s 0c" },
.{ Currency.init(0, 0, 10, 10), "0p 1g 1s 0c" },
.{ Currency.init(0, 10, 10, 10), "1p 1g 1s 0c" },
.{ Currency.init(10, 10, 10, 10), "11p 1g 1s 0c" },
}) |pair| {
try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{total}", .{pair[0]}), pair[1]);
}
} | src/dnd/Currency.zig |
const std = @import("std");
const assert = std.debug.assert;
pub const Sleuth = struct {
match: Match,
lo: u32,
hi: u32,
pub const Match = enum {
TwoOrMore,
TwoOnly,
};
pub fn init(match: Match) Sleuth {
var self = Sleuth{
.match = match,
.lo = 0,
.hi = 0,
};
return self;
}
pub fn search(self: *Sleuth, str: []u8) usize {
self.lo = 0;
self.hi = 0;
var it = std.mem.split(u8, str, "-");
var first = true;
while (it.next()) |what| {
const number = std.fmt.parseInt(u32, what, 10) catch unreachable;
if (first) {
self.lo = number;
} else {
self.hi = number;
}
first = false;
}
var n: u32 = self.lo;
var count: usize = 0;
while (n <= self.hi) : (n += 1) {
const matched = switch (self.match) {
Match.TwoOrMore => match_two_or_more(n),
Match.TwoOnly => match_two_only(n),
};
if (matched) {
count += 1;
}
}
return count;
}
};
fn match_two_or_more(n: u32) bool {
// try out.print("GONZO {}\n", n);
var rep: usize = 0;
var dec: usize = 0;
var m = n;
var q: u8 = 99;
while (m > 0 and dec == 0) {
var d = @intCast(u8, m % 10);
m /= 10;
if (d > q) {
dec += 1;
break;
}
if (d == q) {
rep += 1;
}
q = d;
}
if (dec > 0) {
return false;
}
return (rep > 0);
}
fn match_two_only(n: u32) bool {
// try out.print("GONZO {}\n", n);
var rep: [10]usize = undefined;
var j: usize = 0;
while (j < 10) : (j += 1) {
rep[j] = 0;
}
var dec: usize = 0;
var m = n;
var q: u8 = 99;
while (m > 0 and dec == 0) {
var d = @intCast(u8, m % 10);
m /= 10;
if (d > q) {
dec += 1;
break;
}
if (d == q) {
rep[@intCast(usize, d)] += 1;
}
q = d;
}
if (dec > 0) {
return false;
}
var c2: usize = 0;
j = 0;
while (j < 10) : (j += 1) {
if (rep[j] == 1) {
c2 += 1;
}
}
return (c2 > 0);
}
test "match two or more" {
assert(match_two_or_more(112233));
assert(!match_two_or_more(223450));
assert(!match_two_or_more(123789));
}
test "match exactly two" {
assert(match_two_only(112233));
assert(!match_two_only(123444));
assert(match_two_only(111122));
} | 2019/p04/sleuth.zig |
const std = @import("std");
const with_trace = true;
const assert = std.debug.assert;
fn trace(comptime fmt: []const u8, args: anytype) void {
if (with_trace) std.debug.print(fmt, args);
}
const Ingredient = struct {
name: []const u8,
capacity: i32,
durability: i32,
flavor: i32,
texture: i32,
calories: i32,
};
fn parse_line(line: []const u8) Ingredient {
//Butterscotch: capacity -1, durability -2, flavor 6, texture 3, calories 8
var slice = line;
var sep = std.mem.indexOf(u8, slice, ": capacity ");
const name = slice[0..sep.?];
slice = slice[sep.? + 11 ..];
sep = std.mem.indexOf(u8, slice, ", durability ");
const capac = slice[0..sep.?];
slice = slice[sep.? + 13 ..];
sep = std.mem.indexOf(u8, slice, ", flavor ");
const durab = slice[0..sep.?];
slice = slice[sep.? + 9 ..];
sep = std.mem.indexOf(u8, slice, ", texture ");
const flav = slice[0..sep.?];
slice = slice[sep.? + 10 ..];
sep = std.mem.indexOf(u8, slice, ", calories ");
const tex = slice[0..sep.?];
const cal = slice[sep.? + 11 ..];
return Ingredient{
.name = name,
.capacity = std.fmt.parseInt(i32, capac, 10) catch unreachable,
.durability = std.fmt.parseInt(i32, durab, 10) catch unreachable,
.flavor = std.fmt.parseInt(i32, flav, 10) catch unreachable,
.texture = std.fmt.parseInt(i32, tex, 10) catch unreachable,
.calories = std.fmt.parseInt(i32, cal, 10) catch unreachable,
};
}
pub fn main() anyerror!void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
const limit = 1 * 1024 * 1024 * 1024;
const text = try std.fs.cwd().readFileAlloc(allocator, "day15.txt", limit);
const maxelem = 20;
var ingred: [maxelem]Ingredient = undefined;
var popu: u32 = 0;
var it = std.mem.tokenize(u8, text, "\n");
var combi: u32 = 1;
while (it.next()) |line| {
ingred[popu] = parse_line(line);
trace("{}\n", ingred[popu]);
popu += 1;
combi *= 100;
}
var best: i32 = 0;
var c: u32 = 0;
while (c < combi) : (c += 1) {
var recipe: [maxelem]i32 = undefined;
var rem = c;
var tot: i32 = 0;
for (recipe[0..popu]) |*r| {
r.* = @intCast(i32, rem % 100);
rem = rem / 100;
tot += r.*;
if (tot > 100)
break;
}
if (tot != 100)
continue;
var capacity: i32 = 0;
var durability: i32 = 0;
var flavor: i32 = 0;
var texture: i32 = 0;
var calories: i32 = 0;
for (recipe[0..popu]) |r, i| {
const ing = ingred[i];
capacity += ing.capacity * r;
durability += ing.durability * r;
flavor += ing.flavor * r;
texture += ing.texture * r;
calories += ing.calories * r;
}
if (calories != 500)
continue;
if (capacity < 0) capacity = 0;
if (durability < 0) durability = 0;
if (flavor < 0) flavor = 0;
if (texture < 0) texture = 0;
const score = capacity * durability * flavor * texture;
//trace("{} -> {} {} {} {} -> {}\n", recipe[0..popu], capacity, durability, flavor, texture, score);
if (score > best) best = score;
}
const out = std.io.getStdOut().writer();
try out.print("pass = {} (FROM {} combis)\n", best, combi);
// return error.SolutionNotFound;
} | 2015/day15.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();
// Pure Zig
const exe = b.addExecutable("handmade", "src/main.zig");
exe.setTarget(target);
exe.setBuildMode(mode);
exe.install();
exe.linkLibC();
exe.linkSystemLibrary("gdi32");
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);
// Pure C
const c_exe = b.addExecutable("c_handmade", null);
c_exe.setTarget(target);
c_exe.setBuildMode(mode);
c_exe.install();
c_exe.linkLibC();
c_exe.linkSystemLibrary("gdi32");
c_exe.linkSystemLibrary("user32");
c_exe.addCSourceFiles(&.{"src/main.c"}, &.{});
const run_c_cmd = c_exe.run();
run_c_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_c_cmd.addArgs(args);
}
const run_c_step = b.step("runc", "Run the C app");
run_c_step.dependOn(&run_c_cmd.step);
// Translated C to Zig
// const t_exe = b.addExecutable("t_handmade", "src/translated.zig");
// t_exe.setTarget(target);
// t_exe.setBuildMode(mode);
// t_exe.install();
// t_exe.linkLibC();
// t_exe.linkSystemLibrary("gdi32");
// t_exe.linkSystemLibrary("user32");
// const run_t_cmd = t_exe.run();
// run_t_cmd.step.dependOn(b.getInstallStep());
// if (b.args) |args| {
// run_t_cmd.addArgs(args);
// }
// const run_t_step = b.step("runt", "Run the translated app");
// run_t_step.dependOn(&run_t_cmd.step);
} | build.zig |
const std = @import("std");
const expect = std.testing.expect;
const Allocator = std.mem.Allocator;
const Node = struct {
//What changes would the children field need in order to implement sorting?
children: std.AutoHashMap(u8, *Node),
value: bool = false,
pub fn init(allocator: *Allocator) !*Node {
var node = try allocator.create(Node);
node.children = std.AutoHashMap(u8, *Node).init(allocator);
node.value = false;
return node;
}
};
///References: https://en.wikipedia.org/wiki/Trie
const Tree = struct {
root: *Node,
pub fn init(allocator: *Allocator) !Tree {
var node = try Node.init(allocator);
return Tree{ .root = node };
}
pub fn insert(self: *Tree, key: []const u8, allocator: *Allocator) !void {
var node = self.root;
for (key) |char| {
if (!node.children.contains(char)) {
var new_node = try Node.init(allocator);
try node.children.put(char, new_node);
}
node = node.children.get(char).?;
}
node.value = true;
}
//Returns true if the word is present in the trie
pub fn search(self: *Tree, key: []const u8) bool {
var node = self.root;
for (key) |char| {
if (node.children.contains(char)) {
node = node.children.get(char).?;
} else {
return false;
}
}
return node.value;
}
};
pub fn main() !void {}
test "search empty tree" {
var arena_allocator = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena_allocator.deinit();
const allocator = &arena_allocator.allocator;
var tree = try Tree.init(allocator);
var result = tree.search("car");
try expect(result == false);
}
test "search existing element" {
var arena_allocator = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena_allocator.deinit();
const allocator = &arena_allocator.allocator;
var tree = try Tree.init(allocator);
try tree.insert("car", allocator);
var result = tree.search("car");
try expect(result == true);
}
test "search non-existing element" {
var arena_allocator = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena_allocator.deinit();
const allocator = &arena_allocator.allocator;
var tree = try Tree.init(allocator);
try tree.insert("car", allocator);
var result = tree.search("There is no trie");
try expect(result == false);
//Make sure that partial matches are not marked as present
result = tree.search("ca");
try expect(result == false);
}
test "search with multiple words present" {
var arena_allocator = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena_allocator.deinit();
const allocator = &arena_allocator.allocator;
var tree = try Tree.init(allocator);
var words = [_][]const u8{
"A", "to", "tea", "ted", "ten", "i", "in", "inn",
};
for (words) |word| {
try tree.insert(word, allocator);
}
for (words) |word| {
var result = tree.search(word);
try expect(result == true);
}
//Root should have 'A', 't' and 'i' as its children
try expect(tree.root.children.count() == 3);
} | search_trees/trie.zig |
const std = @import("std");
const mem = std.mem;
const os = std.os;
const linux = @cImport({
@cInclude("linux/hidraw.h");
@cInclude("libudev.h");
@cInclude("sys/ioctl.h");
// for EVIOCGRAB:
@cInclude("linux/input.h");
});
const UNGRAB = 0;
const GRAB = 1;
const DeviceError = error{ CantGrab, NotFound };
pub fn open_touchpad() !os.fd_t {
const context = linux.udev_new() orelse
return error.@"Failed to create udev context";
defer _ = linux.udev_unref(context);
const devices = linux.udev_enumerate_new(context) orelse
return error.@"Failed to create enumerator";
defer _ = linux.udev_enumerate_unref(devices);
if (linux.udev_enumerate_add_match_subsystem(devices, "input") < 0) {
return error.@"No input devices available";
}
if (linux.udev_enumerate_add_match_property(devices, "ID_INPUT_TOUCHPAD", "1") < 0) {
return error.@"No touchpad devices available";
}
if (linux.udev_enumerate_scan_devices(devices) < 0) {
return error.@"Scan failed";
}
var entry = linux.udev_enumerate_get_list_entry(devices);
while (entry) |node| : (entry = linux.udev_list_entry_get_next(node)) {
const name = mem.sliceTo(linux.udev_list_entry_get_name(node), 0);
if (mem.indexOf(u8, name, "/event") != null) {
// std.debug.print("Found touchpad: {s}\n", .{name});
const dev = linux.udev_device_new_from_syspath(
context,
linux.udev_list_entry_get_name(node),
) orelse
return error.@"Failed to get device from syspath";
defer _ = linux.udev_device_unref(dev);
const devnode = mem.sliceTo(linux.udev_device_get_devnode(dev), 0);
std.debug.print("Found touchpad: {s}\n", .{devnode});
const fd = try os.open(devnode, os.O.RDONLY | os.O.NONBLOCK, 0);
return fd;
}
}
return DeviceError.NotFound;
}
pub fn grab(fd: os.fd_t) !void {
if (std.os.linux.ioctl(fd, linux.EVIOCGRAB, GRAB) < 0) {
return DeviceError.CantGrab;
}
}
pub fn ungrab(fd: os.fd_t) !void {
if (std.os.linux.ioctl(fd, linux.EVIOCGRAB, UNGRAB) < 0) {
return DeviceError.CantGrab;
}
}
pub fn close_touchpad(fd: os.fd_t) void {
ungrab(fd) catch {};
os.close(fd);
} | src/udev.zig |
usingnamespace @import("root").preamble;
const gdt = @import("gdt.zig");
const regs = @import("regs.zig");
const interrupts = @import("interrupts.zig");
const apic = @import("apic.zig");
const Tss = @import("tss.zig").Tss;
pub const sched_stack_size = 0x10000;
pub const int_stack_size = 0x10000;
pub const task_stack_size = 0x10000;
pub const stack_guard_size = 0x1000;
pub const ap_init_stack_size = 0x10000;
pub var bsp_task: os.thread.Task = .{
.name = "BSP task",
};
pub const kernel_gs_base = regs.MSR(u64, 0xC0000102);
pub const TaskData = struct {
//tss: *Tss = undefined,
syscall_stack: usize,
pub fn loadState(self: *@This()) void {
const cpu = os.platform.thread.get_current_cpu();
//self.tss.set_interrupt_stack(cpu.int_stack);
//self.tss.set_scheduler_stack(cpu.sched_stack);
//cpu.platform_data.gdt.update_tss(self.tss);
cpu.platform_data.shared_tss.set_syscall_stack(self.syscall_stack);
}
};
pub const CoreData = struct {
gdt: gdt.Gdt = .{},
shared_tss: Tss = .{},
shared_tss_loaded: bool = true,
rsp_stash: u64 = undefined, // Stash for rsp after syscall instruction
lapic: ?os.platform.phys_ptr(*volatile [0x100]u32) = undefined,
lapic_id: u32 = 0,
mwait_supported: bool = false,
wakeable: bool = false,
invlpg_counter: usize = 0,
pub fn ring(self: *@This()) void {
const current_cpu = os.platform.thread.get_current_cpu();
if (current_cpu.platform_data.lapic_id == self.lapic_id) {
return;
}
if (@atomicLoad(bool, &self.wakeable, .Acquire)) {
apic.ipi(self.lapic_id, interrupts.ring_vector);
}
}
pub fn start_monitoring(self: *@This()) void {
@atomicStore(bool, &self.wakeable, true, .Release);
}
pub fn wait(self: *@This()) void {
asm volatile ("sti; hlt; cli");
@atomicStore(bool, &self.wakeable, false, .Release);
}
pub fn invlpgIpi(self: *const @This()) void {
// Check the counter before the IPI
const counter = @atomicLoad(usize, &self.invlpg_counter, .Acquire);
apic.ipi(self.lapic_id, interrupts.invlpg_vector);
// Wait until the IPI is acknowledged
while (@atomicLoad(usize, &self.invlpg_counter, .Acquire) == counter) {}
}
};
const ephemeral = os.memory.vmm.backed(.Ephemeral);
pub fn enter_userspace(entry: u64, arg: u64, stack: u64) noreturn {
asm volatile (
\\ push %[userdata64]
\\ push %[stack]
\\ push $0x202
\\ push %[usercode64]
\\ push %[entry]
\\
\\ mov %[userdata64], %%rax
\\ mov %%rax, %%es
\\ mov %%rax, %%ds
\\
\\ xor %%rsi, %%rsi
\\ xor %%rax, %%rax
\\ xor %%rdx, %%rdx
\\ xor %%rcx, %%rcx
\\ xor %%rbp, %%rbp
\\ xor %%rbx, %%rbx
\\
\\ xor %%r8, %%r8
\\ xor %%r9, %%r9
\\ xor %%r10, %%r10
\\ xor %%r11, %%r11
\\ xor %%r12, %%r12
\\ xor %%r13, %%r13
\\ xor %%r14, %%r14
\\ xor %%r15, %%r15
\\
\\ iretq
\\
:
: [arg] "{rdi}" (arg),
[stack] "r" (stack),
[entry] "r" (entry),
[userdata64] "i" (gdt.selector.userdata64),
[usercode64] "i" (gdt.selector.usercode64)
);
unreachable;
}
pub fn init_task_call(new_task: *os.thread.Task, entry: *os.thread.NewTaskEntry) !void {
const cpu = os.platform.thread.get_current_cpu();
new_task.registers.eflags = regs.eflags();
new_task.registers.rdi = @ptrToInt(entry);
new_task.registers.rsp = lib.util.libalign.alignDown(usize, 16, @ptrToInt(entry));
new_task.registers.cs = gdt.selector.code64;
new_task.registers.ss = gdt.selector.data64;
new_task.registers.es = gdt.selector.data64;
new_task.registers.ds = gdt.selector.data64;
new_task.registers.rip = @ptrToInt(entry.function);
//const tss = try os.memory.vmm.backed(.Ephemeral).create(Tss);
//tss = .{};
//new_task.platform_data.tss = tss;
//tss.set_syscall_stack(new_task.stack);
new_task.platform_data.syscall_stack = new_task.stack;
}
pub fn sched_call_impl(fun: usize, ctx: usize) void {
asm volatile (
\\int %[sched_call_vector]
:
: [sched_call_vector] "i" (interrupts.sched_call_vector),
[_] "{rdi}" (fun),
[_] "{rsi}" (ctx)
: "memory"
);
}
pub fn sched_call_impl_handler(frame: *os.platform.InterruptFrame) void {
const fun: fn (*os.platform.InterruptFrame, usize) void = @intToPtr(fn (*os.platform.InterruptFrame, usize) void, frame.rdi);
const ctx: usize = frame.rsi;
fun(frame, ctx);
}
pub fn set_current_cpu(cpu_ptr: *os.platform.smp.CoreData) void {
kernel_gs_base.write(@ptrToInt(cpu_ptr));
}
pub fn get_current_cpu() *os.platform.smp.CoreData {
return @intToPtr(*os.platform.smp.CoreData, kernel_gs_base.read());
}
pub fn self_exited() ?*os.thread.Task {
const curr = os.platform.get_current_task();
if (curr == &bsp_task)
return null;
return curr;
} | subprojects/flork/src/platform/x86_64/thread.zig |
const std = @import("std");
const nvg = @import("nanovg");
const gui = @import("../gui.zig");
const Rect = @import("../geometry.zig").Rect;
const Label = @This();
widget: gui.Widget,
allocator: std.mem.Allocator,
text: []const u8,
text_alignment: gui.TextAlignment = .left,
padding: f32 = 0,
draw_border: bool = false,
const Self = @This();
pub fn init(allocator: std.mem.Allocator, rect: Rect(f32), text: []const u8) !*Self {
var self = try allocator.create(Self);
self.* = Self{
.widget = gui.Widget.init(allocator, rect),
.allocator = allocator,
.text = text,
};
self.widget.drawFn = draw;
return self;
}
pub fn deinit(self: *Self) void {
self.widget.deinit();
self.allocator.destroy(self);
}
pub fn draw(widget: *gui.Widget, vg: nvg) void {
const self = @fieldParentPtr(Self, "widget", widget);
const rect = widget.relative_rect;
if (self.draw_border) {
gui.drawPanelInset(vg, rect.x, rect.y, rect.w, rect.h, 1);
vg.scissor(rect.x + 1, rect.y + 1, rect.w - 2, rect.h - 2);
} else {
vg.scissor(rect.x, rect.y, rect.w, rect.h);
}
defer vg.resetScissor();
vg.fontFace("guifont");
vg.fontSize(12);
var text_align = nvg.TextAlign{ .vertical = .middle };
var x = rect.x;
var y = rect.y + 0.5 * rect.h;
switch (self.text_alignment) {
.left => {
text_align.horizontal = .left;
x += self.padding;
},
.center => {
text_align.horizontal = .center;
x += 0.5 * rect.w;
},
.right => {
text_align.horizontal = .right;
x += rect.w - self.padding;
},
}
vg.fillColor(nvg.rgb(0, 0, 0));
const has_newline = std.mem.indexOfScalar(u8, self.text, '\n') != null;
if (rect.w == 0 or !has_newline) {
vg.textAlign(text_align);
_ = vg.text(x, rect.y + 0.5 * rect.h, self.text);
} else {
// NanoVG only vertically aligns the first line. So we have to do our own vertical centering.
text_align.vertical = .top;
vg.textAlign(text_align);
vg.textLineHeight(14.0 / 12.0);
var bounds: [4]f32 = undefined;
vg.textBoxBounds(x, y, rect.w, self.text, &bounds);
y -= 0.5 * (bounds[3] - bounds[1]);
vg.textBox(x, y, rect.w, self.text);
}
} | src/gui/widgets/Label.zig |
const std = @import("std");
pub const App = @import("zt/app.zig").App;
pub const Allocators = @import("zt/allocators.zig");
/// Forwarding known_folders.zig, a popular zig framework for finding predetermined folders cross platform.
pub const known_folders = @import("pkg/known_folders.zig");
pub const custom_components = @import("zt/customComponents.zig");
pub const math = @import("pkg/zlm.zig");
pub const imgui_style = @import("zt/styler.zig");
/// Everything inside of `Game` is designed around making a game easier to work on. Things like physics, spatial hashing,
/// and general purpose rendering.
pub const game = struct {
/// A simple and very fast spatial hash with customizable entry type and bucket size.
pub const SpatialHash = @import("zt/spatialHash.zig");
/// Lots of functions for overlap testing shapes of different kinds.
pub const Physics = @import("zt/physics.zig");
/// A renderer made with `GenerateBuffer`, contains everything you need for a fast and simple graphic renderer.
pub const Renderer = @import("zt/renderer.zig");
};
/// These are thin wrappers around basic opengl constructs. Perfect for use in applications that need graphical capability,
/// and for games.
pub const gl = struct {
/// Creates an FBO and texture, allows for binding and unbinding to toggle what you're rendering to with opengl.
pub const RenderTarget = @import("zt/renderTarget.zig");
/// Creates a Shader Program in opengl from @embedFile or other bytes.
pub const Shader = @import("zt/shader.zig");
/// Uses stb_image to load textures into opengl, with wrapper struct for basic information.
pub const Texture = @import("zt/texture.zig");
/// Generates a basic opengl buffer automatically, based on a vertex struct.
pub const GenerateBuffer = @import("zt/generateBuffer.zig").GenerateBuffer;
};
/// Finds the folder of the binary, and sets the operating system's working directory
/// to it. Useful to keep relative file loading working properly(especially using `zig build run`)
/// when ran from any location.
pub fn makeCwd() !void {
var folder = (try known_folders.getPath(std.heap.c_allocator, known_folders.KnownFolder.executable_dir)).?;
try std.os.chdir(folder);
}
/// Takes a relative path from the executable's cwd, and returns an absolute path to the resource. Great for making
/// sure your application gets the right resources no matter where its launched from.
pub inline fn path(subpath: []const u8) []const u8 {
return pathEx(Allocators.ring(), subpath);
}
/// Same as path, but you own the memory.
pub fn pathEx(allocator: std.mem.Allocator, subpath: []const u8) []const u8 {
var executablePath = known_folders.getPath(allocator, .executable_dir) catch unreachable;
defer allocator.free(executablePath.?);
return std.fs.path.joinZ(allocator, &[_][]const u8{ executablePath.?, subpath }) catch unreachable;
} | src/zt.zig |
const std = @import("std");
const ascii = std.ascii;
const mem = std.mem;
usingnamespace @import("common.zig");
const HeaderList = std.ArrayList(Header);
pub const Headers = struct {
allocator: *mem.Allocator,
list: HeaderList,
pub fn init(allocator: *mem.Allocator) Headers {
return .{
.allocator = allocator,
.list = HeaderList.init(allocator),
};
}
pub fn deinit(self: *Headers) void {
for (self.list.items) |header| {
self.allocator.free(header.name);
self.allocator.free(header.value);
}
self.list.deinit();
}
pub fn ensureCapacity(self: *Headers, new_capacity: usize) !void {
return self.list.ensureCapacity(new_capacity);
}
pub fn appendValue(self: *Headers, name: []const u8, value: []const u8) !void {
const duped_name = try self.allocator.dupe(u8, name);
const duped_value = try self.allocator.dupe(u8, value);
try self.list.append(.{
.name = duped_name,
.value = duped_value,
});
}
pub fn append(self: *Headers, header: Header) !void {
return self.appendValue(header.name, header.value);
}
pub fn appendSlice(self: *Headers, headers: HeadersSlice) !void {
for (headers) |header| {
try self.appendValue(header.name, header.value);
}
}
pub fn contains(self: Headers, name: []const u8) bool {
for (self.list.items) |header| {
if (ascii.eqlIgnoreCase(header.name, name)) {
return true;
}
}
return false;
}
pub fn search(self: Headers, name: []const u8) ?Header {
for (self.list.items) |header| {
if (ascii.eqlIgnoreCase(header.name, name)) {
return header;
}
}
return null;
}
pub fn indexOf(self: Headers, name: []const u8) ?usize {
for (self.list.items) |header, index| {
if (ascii.eqlIgnoreCase(header.name, name)) {
return index;
}
}
return null;
}
pub fn set(self: *Headers, name: []const u8, value: []const u8) !void {
if (self.indexOf(name)) |idx| {
const duped_value = try self.allocator.dupe(u8, value);
const old = self.list.items[idx];
// Is this safe? possible use-after-free in userland code.
self.allocator.free(old.value);
self.list.items[idx] = .{
.name = old.name,
.value = duped_value,
};
} else {
return self.appendValue(name, value);
}
}
pub fn get(self: Headers, name: []const u8) ?[]const u8 {
if (self.search(name)) |header| {
return header.value;
} else {
return null;
}
}
};
const testing = std.testing;
test "headers append and get properly" {
var headers = Headers.init(testing.allocator);
defer headers.deinit();
var list = [_]Header{
.{ .name = "Header2", .value = "value2" },
.{ .name = "Header3", .value = "value3" },
};
try headers.appendValue("Host", "localhost");
try headers.append(.{ .name = "Header1", .value = "value1" });
try headers.appendSlice(&list);
testing.expectEqualStrings("value1", headers.search("Header1").?.value);
testing.expect(headers.contains("Header2"));
testing.expect(headers.indexOf("Header3").? == 3);
testing.expectEqualStrings("value1", headers.get("Header1").?);
try headers.set("Header1", "value4");
testing.expectEqualStrings("value4", headers.get("Header1").?);
}
comptime {
std.testing.refAllDecls(@This());
} | src/headers.zig |
const std = @import("std");
const shared = @import("../shared.zig");
const lib = @import("../../main.zig");
pub const c = @cImport({
@cInclude("gtk/gtk.h");
});
const wbin_new = @import("windowbin.zig").wbin_new;
const EventType = shared.BackendEventType;
const BackendError = shared.BackendError;
pub const Capabilities = .{ .useEventLoop = true };
var activeWindows = std.atomic.Atomic(usize).init(0);
var randomWindow: *c.GtkWidget = undefined;
var hasInit: bool = false;
pub fn init() BackendError!void {
if (!hasInit) {
hasInit = true;
if (c.gtk_init_check(0, null) == 0) {
return BackendError.InitializationError;
}
}
}
pub const MessageType = enum { Information, Warning, Error };
pub fn showNativeMessageDialog(msgType: MessageType, comptime fmt: []const u8, args: anytype) void {
const msg = std.fmt.allocPrintZ(lib.internal.scratch_allocator, fmt, args) catch {
std.log.err("Could not launch message dialog, original text: " ++ fmt, args);
return;
};
defer lib.internal.scratch_allocator.free(msg);
const cType = @intCast(c_uint, switch (msgType) {
.Information => c.GTK_MESSAGE_INFO,
.Warning => c.GTK_MESSAGE_WARNING,
.Error => c.GTK_MESSAGE_ERROR,
});
const dialog = c.gtk_message_dialog_new(null, c.GTK_DIALOG_DESTROY_WITH_PARENT, cType, c.GTK_BUTTONS_CLOSE, msg);
_ = c.gtk_dialog_run(@ptrCast(*c.GtkDialog, dialog));
c.gtk_widget_destroy(dialog);
}
pub const PeerType = *c.GtkWidget;
export fn gtkWindowHidden(_: *c.GtkWidget, _: usize) void {
_ = activeWindows.fetchSub(1, .Release);
}
pub const Window = struct {
peer: *c.GtkWidget,
wbin: *c.GtkWidget,
pub usingnamespace Events(Window);
pub fn create() BackendError!Window {
const window = c.gtk_window_new(c.GTK_WINDOW_TOPLEVEL) orelse return error.UnknownError;
//const screen = c.gtk_window_get_screen(@ptrCast(*c.GtkWindow, window));
//std.log.info("{d} dpi", .{c.gdk_screen_get_resolution(screen)});
const wbin = wbin_new() orelse unreachable;
c.gtk_container_add(@ptrCast(*c.GtkContainer, window), wbin);
c.gtk_widget_show(wbin);
_ = c.g_signal_connect_data(window, "hide", @ptrCast(c.GCallback, gtkWindowHidden), null, null, c.G_CONNECT_AFTER);
randomWindow = window;
return Window{ .peer = window, .wbin = wbin };
}
pub fn resize(self: *Window, width: c_int, height: c_int) void {
c.gtk_window_resize(@ptrCast(*c.GtkWindow, self.peer), width, height);
}
pub fn setChild(self: *Window, peer: ?*c.GtkWidget) void {
c.gtk_container_add(@ptrCast(*c.GtkContainer, self.wbin), peer);
}
pub fn show(self: *Window) void {
c.gtk_widget_show(self.peer);
_ = activeWindows.fetchAdd(1, .Release);
}
pub fn close(self: *Window) void {
c.gtk_window_close(@ptrCast(*c.GtkWindow, self.peer));
}
};
pub const MouseButton = enum(c_uint) {
Left = 1,
Middle = 2,
Right = 3,
_,
/// Returns the ID of the pressed or released finger or null if it is a mouse.
pub fn getFingerId(self: MouseButton) ?u8 {
_ = self;
return null;
}
};
// zig fmt: off
const EventFunctions = struct {
/// Only works for buttons
clickHandler: ?fn (data: usize) void = null,
mouseButtonHandler: ?fn (button: MouseButton, pressed: bool, x: u32, y: u32, data: usize) void = null,
// TODO: Mouse object with pressed buttons and more data
mouseMotionHandler: ?fn(x: u32, y: u32, data: usize) void = null,
keyTypeHandler: ?fn (str: []const u8, data: usize) void = null,
// TODO: dx and dy are in pixels, not in lines
scrollHandler: ?fn (dx: f32, dy: f32, data: usize) void = null,
resizeHandler: ?fn (width: u32, height: u32, data: usize) void = null,
/// Only works for canvas (althought technically it isn't required to)
drawHandler: ?fn (ctx: *Canvas.DrawContext, data: usize) void = null,
changedTextHandler: ?fn (data: usize) void = null,
};
/// user data used for handling events
pub const EventUserData = struct {
user: EventFunctions = .{},
class: EventFunctions = .{},
userdata: usize = 0,
classUserdata: usize = 0,
peer: PeerType,
};
// zig fmt: on
pub inline fn getEventUserData(peer: *c.GtkWidget) *EventUserData {
return @ptrCast(*EventUserData, @alignCast(@alignOf(EventUserData), c.g_object_get_data(@ptrCast(*c.GObject, peer), "eventUserData").?));
}
pub fn getWidthFromPeer(peer: PeerType) c_int {
return c.gtk_widget_get_allocated_width(peer);
}
pub fn getHeightFromPeer(peer: PeerType) c_int {
return c.gtk_widget_get_allocated_height(peer);
}
pub fn Events(comptime T: type) type {
return struct {
const Self = @This();
pub fn setupEvents(widget: *c.GtkWidget) BackendError!void {
_ = c.g_signal_connect_data(widget, "button-press-event", @ptrCast(c.GCallback, gtkButtonPress), null, null, c.G_CONNECT_AFTER);
_ = c.g_signal_connect_data(widget, "button-release-event", @ptrCast(c.GCallback, gtkButtonPress), null, null, c.G_CONNECT_AFTER);
_ = c.g_signal_connect_data(widget, "motion-notify-event", @ptrCast(c.GCallback, gtkMouseMotion), null, null, c.G_CONNECT_AFTER);
_ = c.g_signal_connect_data(widget, "scroll-event", @ptrCast(c.GCallback, gtkMouseScroll), null, null, c.G_CONNECT_AFTER);
_ = c.g_signal_connect_data(widget, "size-allocate", @ptrCast(c.GCallback, gtkSizeAllocate), null, null, c.G_CONNECT_AFTER);
if (T != Canvas)
_ = c.g_signal_connect_data(widget, "key-press-event", @ptrCast(c.GCallback, gtkKeyPress), null, null, c.G_CONNECT_AFTER);
c.gtk_widget_add_events(widget, c.GDK_SCROLL_MASK | c.GDK_BUTTON_PRESS_MASK | c.GDK_BUTTON_RELEASE_MASK | c.GDK_KEY_PRESS_MASK | c.GDK_POINTER_MOTION_MASK);
var data = try lib.internal.lasting_allocator.create(EventUserData);
data.* = EventUserData{ .peer = widget }; // ensure that it uses default values
c.g_object_set_data(@ptrCast(*c.GObject, widget), "eventUserData", data);
}
fn gtkSizeAllocate(peer: *c.GtkWidget, allocation: *c.GdkRectangle, userdata: usize) callconv(.C) void {
_ = userdata;
const data = getEventUserData(peer);
if (data.class.resizeHandler) |handler|
handler(@intCast(u32, allocation.width), @intCast(u32, allocation.height), @ptrToInt(data));
if (data.user.resizeHandler) |handler|
handler(@intCast(u32, allocation.width), @intCast(u32, allocation.height), data.userdata);
}
const GdkEventKey = extern struct {
type: c.GdkEventType,
window: *c.GdkWindow,
send_event: c.gint8,
time: c.guint32,
state: *c.GdkModifierType,
keyval: c.guint,
length: c.gint,
string: [*:0]c.gchar,
hardware_keycode: c.guint16,
group: c.guint8,
is_modifier: c.guint,
};
fn gtkKeyPress(peer: *c.GtkWidget, event: *GdkEventKey, userdata: usize) callconv(.C) c.gboolean {
_ = userdata;
const data = getEventUserData(peer);
const str = event.string[0..@intCast(usize, event.length)];
if (str.len != 0) {
if (data.class.keyTypeHandler) |handler| {
handler(str, @ptrToInt(data));
if (data.user.keyTypeHandler == null) return 1;
}
if (data.user.keyTypeHandler) |handler| {
handler(str, data.userdata);
return 1;
}
}
return 0;
}
fn gtkButtonPress(peer: *c.GtkWidget, event: *c.GdkEventButton, userdata: usize) callconv(.C) c.gboolean {
_ = userdata;
const data = getEventUserData(peer);
const pressed = switch (event.type) {
c.GDK_BUTTON_PRESS => true,
c.GDK_BUTTON_RELEASE => false,
// don't send released button in case of GDK_2BUTTON_PRESS, GDK_3BUTTON_PRESS, ...
else => return 0,
};
if (event.x < 0 or event.y < 0) return 0;
const button = @intToEnum(MouseButton, event.button);
const mx = @floatToInt(u32, @floor(event.x));
const my = @floatToInt(u32, @floor(event.y));
if (data.class.mouseButtonHandler) |handler| {
handler(button, pressed, mx, my, @ptrToInt(data));
}
if (data.user.mouseButtonHandler) |handler| {
c.gtk_widget_grab_focus(peer); // seems to be necessary for the canvas
handler(button, pressed, mx, my, data.userdata);
}
return 0;
}
fn gtkMouseMotion(peer: *c.GtkWidget, event: *c.GdkEventMotion, userdata: usize) callconv(.C) c.gboolean {
_ = userdata;
const data = getEventUserData(peer);
const mx = @floatToInt(u32, @floor(event.x));
const my = @floatToInt(u32, @floor(event.y));
if (data.class.mouseMotionHandler) |handler| {
handler(mx, my, @ptrToInt(data));
if (data.user.mouseMotionHandler == null) return 1;
}
if (data.user.mouseMotionHandler) |handler| {
handler(mx, my, data.userdata);
return 1;
}
return 0;
}
/// Temporary hack until translate-c can translate this struct
const GdkEventScroll = extern struct { type: c.GdkEventType, window: *c.GdkWindow, send_event: c.gint8, time: c.guint32, x: c.gdouble, y: c.gdouble, state: c.guint, direction: c.GdkScrollDirection, device: *c.GdkDevice, x_root: c.gdouble, y_root: c.gdouble, delta_x: c.gdouble, delta_y: c.gdouble, is_stop: c.guint };
fn gtkMouseScroll(peer: *c.GtkWidget, event: *GdkEventScroll, userdata: usize) callconv(.C) void {
_ = userdata;
const data = getEventUserData(peer);
const dx: f32 = switch (event.direction) {
c.GDK_SCROLL_LEFT => -1,
c.GDK_SCROLL_RIGHT => 1,
else => @floatCast(f32, event.delta_x),
};
const dy: f32 = switch (event.direction) {
c.GDK_SCROLL_UP => -1,
c.GDK_SCROLL_DOWN => 1,
else => @floatCast(f32, event.delta_y),
};
if (data.class.scrollHandler) |handler|
handler(dx, dy, @ptrToInt(data));
if (data.user.scrollHandler) |handler|
handler(dx, dy, data.userdata);
}
pub fn deinit(self: *const T) void {
std.log.info("peer = {} width = {d}", .{ self, self.getWidth() });
const data = getEventUserData(self.peer);
lib.internal.lasting_allocator.destroy(data);
}
pub inline fn setUserData(self: *T, data: anytype) void {
comptime {
if (!std.meta.trait.isSingleItemPtr(@TypeOf(data))) {
@compileError(std.fmt.comptimePrint("Expected single item pointer, got {s}", .{@typeName(@TypeOf(data))}));
}
}
getEventUserData(self.peer).userdata = @ptrToInt(data);
}
pub inline fn setCallback(self: *T, comptime eType: EventType, cb: anytype) !void {
const data = &getEventUserData(self.peer).user;
switch (eType) {
.Click => data.clickHandler = cb,
.Draw => data.drawHandler = cb,
.MouseButton => data.mouseButtonHandler = cb,
.MouseMotion => data.mouseMotionHandler = cb,
.Scroll => data.scrollHandler = cb,
.TextChanged => data.changedTextHandler = cb,
.Resize => data.resizeHandler = cb,
.KeyType => data.keyTypeHandler = cb,
}
}
pub fn setOpacity(self: *T, opacity: f64) void {
c.gtk_widget_set_opacity(self.peer, opacity);
}
/// Requests a redraw
pub fn requestDraw(self: *T) !void {
c.gtk_widget_queue_draw(self.peer);
}
pub fn getWidth(self: *const T) c_int {
return getWidthFromPeer(self.peer);
}
pub fn getHeight(self: *const T) c_int {
return getHeightFromPeer(self.peer);
}
};
}
const HandlerList = std.ArrayList(fn (data: usize) void);
// pub const Button = @import("../../flat/button.zig").FlatButton;
pub const Button = struct {
peer: *c.GtkWidget,
pub usingnamespace Events(Button);
fn gtkClicked(peer: *c.GtkWidget, userdata: usize) callconv(.C) void {
_ = userdata;
const data = getEventUserData(peer);
if (data.user.clickHandler) |handler| {
handler(data.userdata);
}
}
pub fn create() BackendError!Button {
const button = c.gtk_button_new_with_label("") orelse return error.UnknownError;
c.gtk_widget_show(button);
try Button.setupEvents(button);
_ = c.g_signal_connect_data(button, "clicked", @ptrCast(c.GCallback, gtkClicked), null, @as(c.GClosureNotify, null), 0);
return Button{ .peer = button };
}
pub fn setLabel(self: *const Button, label: [:0]const u8) void {
c.gtk_button_set_label(@ptrCast(*c.GtkButton, self.peer), label);
}
pub fn getLabel(self: *const Button) [:0]const u8 {
const label = c.gtk_button_get_label(@ptrCast(*c.GtkButton, self.peer));
return std.mem.span(label);
}
};
pub const Label = struct {
peer: *c.GtkWidget,
pub usingnamespace Events(Label);
pub fn create() BackendError!Label {
const label = c.gtk_label_new("") orelse return BackendError.UnknownError;
c.gtk_widget_show(label);
try Label.setupEvents(label);
return Label{ .peer = label };
}
pub fn setAlignment(self: *Label, alignment: f32) void {
c.gtk_label_set_xalign(@ptrCast(*c.GtkLabel, self.peer), alignment);
}
pub fn setText(self: *Label, text: [:0]const u8) void {
c.gtk_label_set_text(@ptrCast(*c.GtkLabel, self.peer), text);
}
pub fn getText(self: *Label) [:0]const u8 {
const text = c.gtk_label_get_text(@ptrCast(*c.GtkLabel, self.peer)).?;
return std.mem.span(text);
}
};
pub const TextArea = struct {
/// This is not actually the GtkTextView but this is the GtkScrolledWindow
peer: *c.GtkWidget,
textView: *c.GtkWidget,
pub usingnamespace Events(TextArea);
pub fn create() BackendError!TextArea {
const textArea = c.gtk_text_view_new() orelse return BackendError.UnknownError;
const scrolledWindow = c.gtk_scrolled_window_new(null, null) orelse return BackendError.UnknownError;
c.gtk_container_add(@ptrCast(*c.GtkContainer, scrolledWindow), textArea);
c.gtk_widget_show(textArea);
c.gtk_widget_show(scrolledWindow);
try TextArea.setupEvents(textArea);
return TextArea{ .peer = scrolledWindow, .textView = textArea };
}
pub fn setText(self: *TextArea, text: []const u8) void {
const buffer = c.gtk_text_view_get_buffer(@ptrCast(*c.GtkTextView, self.textView));
c.gtk_text_buffer_set_text(buffer, text.ptr, @intCast(c_int, text.len));
}
pub fn getText(self: *TextArea) [:0]const u8 {
const buffer = c.gtk_text_view_get_buffer(@ptrCast(*c.GtkTextView, self.textView));
var start: c.GtkTextIter = undefined;
var end: c.GtkTextIter = undefined;
c.gtk_text_buffer_get_bounds(buffer, &start, &end);
const text = c.gtk_text_buffer_get_text(buffer, &start, &end, 1);
return std.mem.span(text);
}
};
pub const TextField = struct {
peer: *c.GtkWidget,
pub usingnamespace Events(TextField);
fn gtkTextChanged(peer: *c.GtkWidget, userdata: usize) callconv(.C) void {
_ = userdata;
const data = getEventUserData(peer);
if (data.user.changedTextHandler) |handler| {
handler(data.userdata);
}
}
pub fn create() BackendError!TextField {
const textField = c.gtk_entry_new() orelse return BackendError.UnknownError;
c.gtk_widget_show(textField);
try TextField.setupEvents(textField);
_ = c.g_signal_connect_data(textField, "changed", @ptrCast(c.GCallback, gtkTextChanged), null, @as(c.GClosureNotify, null), c.G_CONNECT_AFTER);
return TextField{ .peer = textField };
}
pub fn setText(self: *TextField, text: []const u8) void {
var view = std.unicode.Utf8View.initUnchecked(text);
var iterator = view.iterator();
var numChars: c_int = 0;
while (iterator.nextCodepoint() != null) {
numChars += 1;
}
const buffer = c.gtk_entry_get_buffer(@ptrCast(*c.GtkEntry, self.peer));
c.gtk_entry_buffer_set_text(buffer, text.ptr, numChars);
}
pub fn getText(self: *TextField) [:0]const u8 {
const buffer = c.gtk_entry_get_buffer(@ptrCast(*c.GtkEntry, self.peer));
const text = c.gtk_entry_buffer_get_text(buffer);
const length = c.gtk_entry_buffer_get_bytes(buffer);
return text[0..length :0];
}
};
pub const Canvas = struct {
peer: *c.GtkWidget,
controller: *c.GtkEventController,
pub usingnamespace Events(Canvas);
pub const DrawContext = struct {
cr: *c.cairo_t,
widget: *c.GtkWidget,
pub const Font = struct {
face: [:0]const u8,
size: f64,
};
pub const TextSize = struct { width: u32, height: u32 };
pub const TextLayout = struct {
_layout: *c.PangoLayout,
_context: *c.PangoContext,
/// If null, no text wrapping is applied, otherwise the text is wrapping as if this was the maximum width.
wrap: ?f64 = null,
pub fn setFont(self: *TextLayout, font: Font) void {
const fontDescription = c.pango_font_description_from_string(font.face) orelse unreachable;
c.pango_font_description_set_size(fontDescription, @floatToInt(c_int, @floor(font.size * @as(f64, c.PANGO_SCALE))));
c.pango_layout_set_font_description(self._layout, fontDescription);
c.pango_font_description_free(fontDescription);
}
pub fn deinit(self: *TextLayout) void {
c.g_object_unref(self._layout);
c.g_object_unref(self._context);
}
pub fn getTextSize(self: *TextLayout, str: []const u8) TextSize {
var width: c_int = undefined;
var height: c_int = undefined;
c.pango_layout_set_width(self._layout, if (self.wrap) |w| @floatToInt(c_int, @floor(w * @as(f64, c.PANGO_SCALE))) else -1);
c.pango_layout_set_text(self._layout, str.ptr, @intCast(c_int, str.len));
c.pango_layout_get_pixel_size(self._layout, &width, &height);
return TextSize{ .width = @intCast(u32, width), .height = @intCast(u32, height) };
}
pub fn init() TextLayout {
const context = c.gdk_pango_context_get().?;
return TextLayout{ ._context = context, ._layout = c.pango_layout_new(context).? };
}
};
pub fn setColorByte(self: *DrawContext, color: lib.Color) void {
self.setColorRGBA(@intToFloat(f32, color.red) / 255.0, @intToFloat(f32, color.green) / 255.0, @intToFloat(f32, color.blue) / 255.0, @intToFloat(f32, color.alpha) / 255.0);
}
pub fn setColor(self: *DrawContext, r: f32, g: f32, b: f32) void {
self.setColorRGBA(r, g, b, 1);
}
pub fn setColorRGBA(self: *DrawContext, r: f32, g: f32, b: f32, a: f32) void {
const color = c.GdkRGBA{ .red = r, .green = g, .blue = b, .alpha = a };
c.gdk_cairo_set_source_rgba(self.cr, &color);
}
/// Add a rectangle to the current path
pub fn rectangle(self: *DrawContext, x: u32, y: u32, w: u32, h: u32) void {
c.cairo_rectangle(self.cr, @intToFloat(f64, x), @intToFloat(f64, y), @intToFloat(f64, w), @intToFloat(f64, h));
}
pub fn ellipse(self: *DrawContext, x: u32, y: u32, w: f32, h: f32) void {
if (w == h) { // if it is a circle, we can use something slightly faster
c.cairo_arc(self.cr, @intToFloat(f64, x), @intToFloat(f64, y), w, 0, 2 * std.math.pi);
return;
}
var matrix: c.cairo_matrix_t = undefined;
c.cairo_get_matrix(self.cr, &matrix);
const scale = w + h;
c.cairo_scale(self.cr, w / scale, h / scale);
c.cairo_arc(self.cr, @intToFloat(f64, x), @intToFloat(f64, y), scale, 0, 2 * std.math.pi);
c.cairo_set_matrix(self.cr, &matrix);
}
pub fn clear(self: *DrawContext, x: u32, y: u32, w: u32, h: u32) void {
const styleContext = c.gtk_widget_get_style_context(self.widget);
c.gtk_render_background(styleContext, self.cr, @intToFloat(f64, x), @intToFloat(f64, y), @intToFloat(f64, w), @intToFloat(f64, h));
}
pub fn text(self: *DrawContext, x: i32, y: i32, layout: TextLayout, str: []const u8) void {
const pangoLayout = layout._layout;
var inkRect: c.PangoRectangle = undefined;
c.pango_layout_get_pixel_extents(pangoLayout, null, &inkRect);
const dx = @intToFloat(f64, inkRect.x);
const dy = @intToFloat(f64, inkRect.y);
c.cairo_move_to(self.cr, @intToFloat(f64, x) + dx, @intToFloat(f64, y) + dy);
c.pango_layout_set_width(pangoLayout, if (layout.wrap) |w| @floatToInt(c_int, @floor(w * @as(f64, c.PANGO_SCALE))) else -1);
c.pango_layout_set_text(pangoLayout, str.ptr, @intCast(c_int, str.len));
c.pango_layout_set_single_paragraph_mode(pangoLayout, 1); // used for coherence with other backends
c.pango_cairo_update_layout(self.cr, pangoLayout);
c.pango_cairo_show_layout(self.cr, pangoLayout);
}
pub fn line(self: *DrawContext, x1: u32, y1: u32, x2: u32, y2: u32) void {
c.cairo_move_to(self.cr, @intToFloat(f64, x1), @intToFloat(f64, y1));
c.cairo_line_to(self.cr, @intToFloat(f64, x2), @intToFloat(f64, y2));
c.cairo_stroke(self.cr);
}
/// Stroke the current path and reset the path.
pub fn stroke(self: *DrawContext) void {
c.cairo_stroke(self.cr);
}
/// Fill the current path and reset the path.
pub fn fill(self: *DrawContext) void {
c.cairo_fill(self.cr);
}
};
fn gtkCanvasDraw(peer: *c.GtkWidget, cr: *c.cairo_t, userdata: usize) callconv(.C) c_int {
_ = userdata;
const data = getEventUserData(peer);
var dc = DrawContext{ .cr = cr, .widget = peer };
if (data.class.drawHandler) |handler|
handler(&dc, @ptrToInt(data));
if (data.user.drawHandler) |handler|
handler(&dc, data.userdata);
return 0; // propagate the event further
}
fn gtkImKeyPress(key: *c.GtkEventControllerKey, keyval: c.guint, keycode: c.guint, state: *c.GdkModifierType, userdata: c.gpointer) callconv(.C) c.gboolean {
_ = userdata;
_ = keycode;
_ = state;
const peer = c.gtk_event_controller_get_widget(@ptrCast(*c.GtkEventController, key));
const data = getEventUserData(peer);
_ = data;
var finalKeyval = @intCast(u21, keyval);
if (keyval >= 0xFF00 and keyval < 0xFF20) { // control characters
finalKeyval = @intCast(u21, keyval) - 0xFF00;
}
if (finalKeyval >= 32768) return 0;
var encodeBuffer: [4]u8 = undefined;
const strLength = std.unicode.utf8Encode(@intCast(u21, finalKeyval), &encodeBuffer) catch unreachable;
const str = encodeBuffer[0..strLength];
if (data.class.keyTypeHandler) |handler| {
handler(str, @ptrToInt(data));
if (data.user.keyTypeHandler == null) return 1;
}
if (data.user.keyTypeHandler) |handler| {
handler(str, data.userdata);
return 1;
}
return 1;
}
pub fn create() BackendError!Canvas {
const canvas = c.gtk_drawing_area_new() orelse return BackendError.UnknownError;
c.gtk_widget_show(canvas);
c.gtk_widget_set_can_focus(canvas, 1);
try Canvas.setupEvents(canvas);
_ = c.g_signal_connect_data(canvas, "draw", @ptrCast(c.GCallback, gtkCanvasDraw), null, @as(c.GClosureNotify, null), 0);
const controller = c.gtk_event_controller_key_new(canvas).?;
_ = c.g_signal_connect_data(controller, "key-pressed", @ptrCast(c.GCallback, gtkImKeyPress), null, null, c.G_CONNECT_AFTER);
return Canvas{ .peer = canvas, .controller = controller };
}
};
pub const Container = struct {
peer: *c.GtkWidget,
container: *c.GtkWidget,
pub usingnamespace Events(Container);
pub fn create() BackendError!Container {
const layout = c.gtk_fixed_new() orelse return BackendError.UnknownError;
c.gtk_widget_show(layout);
// A custom component is used to bypass GTK's minimum size mechanism
const wbin = wbin_new() orelse return BackendError.UnknownError;
c.gtk_container_add(@ptrCast(*c.GtkContainer, wbin), layout);
c.gtk_widget_show(wbin);
try Container.setupEvents(wbin);
return Container{ .peer = wbin, .container = layout };
}
pub fn add(self: *const Container, peer: PeerType) void {
c.gtk_fixed_put(@ptrCast(*c.GtkFixed, self.container), peer, 0, 0);
}
pub fn move(self: *const Container, peer: PeerType, x: u32, y: u32) void {
c.gtk_fixed_move(@ptrCast(*c.GtkFixed, self.container), peer, @intCast(c_int, x), @intCast(c_int, y));
}
pub fn resize(self: *const Container, peer: PeerType, w: u32, h: u32) void {
_ = w;
_ = h;
_ = peer;
_ = self;
// temporary fix and should be replaced by a proper way to resize down
//c.gtk_widget_set_size_request(peer, std.math.max(@intCast(c_int, w) - 5, 0), std.math.max(@intCast(c_int, h) - 5, 0));
c.gtk_widget_set_size_request(peer, @intCast(c_int, w), @intCast(c_int, h));
c.gtk_container_resize_children(@ptrCast(*c.GtkContainer, self.container));
}
};
pub const TabContainer = struct {
peer: *c.GtkWidget,
pub usingnamespace Events(TabContainer);
pub fn create() BackendError!TabContainer {
const layout = c.gtk_notebook_new() orelse return BackendError.UnknownError;
c.gtk_widget_show(layout);
try TabContainer.setupEvents(layout);
return TabContainer{ .peer = layout };
}
/// Returns the index of the newly added tab
pub fn insert(self: *const TabContainer, position: usize, peer: PeerType) usize {
return c.gtk_notebook_insert_page(@ptrCast(*c.GtkNotebook, self.peer), peer, null, position);
}
pub fn setLabel(self: *const TabContainer, position: usize, text: [:0]const u8) void {
const child = c.gtk_notebook_get_nth_page(@ptrCast(*c.GtkNotebook, self.peer), @intCast(c_int, position));
c.gtk_notebook_set_tab_label_text(@ptrCast(*c.GtkNotebook, self.peer), child, text);
}
/// Returns the number of tabs added to this tab container
pub fn getTabsNumber(self: *const TabContainer) usize {
return @intCast(usize, c.gtk_notebook_get_n_pages(@ptrCast(*c.GtkNotebook, self.peer)));
}
};
pub const ScrollView = struct {
peer: *c.GtkWidget,
pub usingnamespace Events(ScrollView);
pub fn create() BackendError!ScrollView {
const scrolledWindow = c.gtk_scrolled_window_new(null, null) orelse return BackendError.UnknownError;
c.gtk_widget_show(scrolledWindow);
try ScrollView.setupEvents(scrolledWindow);
return ScrollView{ .peer = scrolledWindow };
}
pub fn setChild(self: *ScrollView, peer: PeerType) void {
// TODO: remove old widget if there was one
c.gtk_container_add(@ptrCast(*c.GtkContainer, self.peer), peer);
}
};
pub const ImageData = struct {
peer: *c.GdkPixbuf,
pub fn from(width: usize, height: usize, stride: usize, cs: lib.Colorspace, bytes: []const u8) !ImageData {
const pixbuf = c.gdk_pixbuf_new_from_data(bytes.ptr, c.GDK_COLORSPACE_RGB, @boolToInt(cs == .RGBA), 8, @intCast(c_int, width), @intCast(c_int, height), @intCast(c_int, stride), null, null) orelse return BackendError.UnknownError;
return ImageData{ .peer = pixbuf };
}
};
pub const Image = struct {
peer: *c.GtkWidget,
pub usingnamespace Events(Image);
pub fn create() BackendError!Image {
const image = c.gtk_image_new() orelse return BackendError.UnknownError;
c.gtk_widget_show(image);
try Image.setupEvents(image);
return Image{ .peer = image };
}
pub fn setData(self: *Image, data: ImageData) void {
c.gtk_image_set_from_pixbuf(@ptrCast(*c.GtkImage, self.peer), data.peer);
}
};
// downcasting to [*]u8 due to translate-c bugs which won't even accept
// pointer to an event.
extern fn gdk_event_new(type: c_int) [*]align(8) u8;
extern fn gtk_main_do_event(event: [*c]u8) void;
pub fn postEmptyEvent() void {
// const event = gdk_event_new(c.GDK_DAMAGE);
// const expose = @ptrCast(*c.GdkEventExpose, event);
// expose.window = c.gtk_widget_get_window(randomWindow);
// expose.send_event = 1;
// expose.count = 0;
// expose.area = c.GdkRectangle {
// .x = 0, .y = 0, .width = 1000, .height = 1000
// };
// gtk_main_do_event(event);
var rect = c.GdkRectangle{ .x = 0, .y = 0, .width = 100, .height = 100 };
c.gdk_window_invalidate_rect(c.gtk_widget_get_window(randomWindow), &rect, 0);
}
pub fn runStep(step: shared.EventLoopStep) bool {
_ = c.gtk_main_iteration_do(@boolToInt(step == .Blocking));
return activeWindows.load(.Acquire) != 0;
} | src/backends/gtk/backend.zig |
const std = @import("../std.zig");
const assert = std.debug.assert;
const hmac = std.crypto.auth.hmac;
const mem = std.mem;
/// HKDF-SHA256
pub const HkdfSha256 = Hkdf(hmac.sha2.HmacSha256);
/// HKDF-SHA512
pub const HkdfSha512 = Hkdf(hmac.sha2.HmacSha512);
/// The Hkdf construction takes some source of initial keying material and
/// derives one or more uniform keys from it.
pub fn Hkdf(comptime Hmac: type) type {
return struct {
/// Return a master key from a salt and initial keying material.
fn extract(salt: []const u8, ikm: []const u8) [Hmac.mac_length]u8 {
var prk: [Hmac.mac_length]u8 = undefined;
Hmac.create(&prk, ikm, salt);
return prk;
}
/// Derive a subkey from a master key `prk` and a subkey description `ctx`.
fn expand(out: []u8, ctx: []const u8, prk: [Hmac.mac_length]u8) void {
assert(out.len < Hmac.mac_length * 255); // output size is too large for the Hkdf construction
var i: usize = 0;
var counter = [1]u8{1};
while (i + Hmac.mac_length <= out.len) : (i += Hmac.mac_length) {
var st = Hmac.init(&prk);
if (i != 0) {
st.update(out[i - Hmac.mac_length ..][0..Hmac.mac_length]);
}
st.update(ctx);
st.update(&counter);
st.final(out[i..][0..Hmac.mac_length]);
counter[0] += 1;
}
const left = out.len % Hmac.mac_length;
if (left > 0) {
var st = Hmac.init(&prk);
if (i != 0) {
st.update(out[i - Hmac.mac_length ..][0..Hmac.mac_length]);
}
st.update(ctx);
st.update(&counter);
var tmp: [Hmac.mac_length]u8 = undefined;
st.final(tmp[0..Hmac.mac_length]);
mem.copy(u8, out[i..][0..left], tmp[0..left]);
}
}
};
}
const htest = @import("test.zig");
test "Hkdf" {
const ikm = [_]u8{0x0b} ** 22;
const salt = [_]u8{ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c };
const context = [_]u8{ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9 };
const kdf = HkdfSha256;
const prk = kdf.extract(&salt, &ikm);
htest.assertEqual("077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5", &prk);
var out: [42]u8 = undefined;
kdf.expand(&out, &context, prk);
htest.assertEqual("3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865", &out);
} | lib/std/crypto/hkdf.zig |
const tic = @import("tic80.zig");
const std = @import("std");
const RndGen = std.rand.DefaultPrng;
var rnd : std.rand.Random = undefined;
const screenWidth = 240;
const screenHeight = 136;
const toolbarHeight = 6;
var t : u32 = 0;
fn randomFloat(lower: f32, greater: f32) f32 {
return rnd.float(f32) * (greater-lower) + lower;
}
const Bunny = struct {
width: f16 = 0,
height: f16 = 0,
x: f32 = 0,
y: f32 = 0,
speedX: f32 = 0,
speedY: f32 = 0,
sprite: u8 = 0,
fn initBunny(self: *Bunny) void {
self.width = 26;
self.height = 32;
self.sprite = 1;
self.x = randomFloat(0, screenWidth - self.width);
self.y = randomFloat(0, screenHeight - self.height);
self.speedX = randomFloat(-100, 100) / 60;
self.speedY = randomFloat(-100, 100) / 60;
}
fn draw(self: Bunny) void {
tic.spr(self.sprite, @floatToInt(i32,self.x), @floatToInt(i32,self.y), .{
.transparent = &.{1},
.w = 4,
.h = 4
});
}
fn update(self: *Bunny) void {
self.x += self.speedX;
self.y += self.speedY;
if (self.x + self.width > screenWidth) {
self.x = screenWidth - self.width;
self.speedX = self.speedX * -1;
}
if (self.x < 0) {
self.x = 0;
self.speedX = self.speedX * -1;
}
if (self.y + self.height > screenHeight) {
self.y = screenHeight - self.height;
self.speedY = self.speedY * -1;
}
if (self.y < toolbarHeight) {
self.y = toolbarHeight;
self.speedY = self.speedY * -1;
}
}
};
const FPS = struct {
value: u32 = 0,
frames: u32 = 0,
lastTime: f32 = 0,
fn initFPS(self: *FPS) void {
self.value = 0;
self.frames = 0;
self.lastTime = 0;
}
fn getValue(self: *FPS) u32 {
if (tic.time() - self.lastTime <= 1000) {
self.frames += 1;
} else {
self.value = self.frames;
self.frames = 0;
self.lastTime = tic.time();
}
return self.value;
}
};
const MAX_BUNNIES = 1200;
var fps : FPS = undefined;
var bunnyCount : usize = 0;
var bunnies : [MAX_BUNNIES]Bunny = undefined;
var started = false;
fn addBunny() void {
if (bunnyCount >= MAX_BUNNIES) return;
bunnies[bunnyCount].initBunny();
bunnyCount += 1;
}
fn removeBunny() void {
if (bunnyCount==0) return;
bunnyCount -= 1;
}
fn start() void {
rnd = RndGen.init(0).random();
fps.initFPS();
addBunny();
started = true;
// tic.ZERO = tic.FIRST + 1;
}
export fn testscreen() void {
var i : usize = 0;
while (i<2000) {
// tic.ZERO.* = 0x99;
tic.FRAMEBUFFER[i]=0x56;
// tic.FRAMEBUFFER2.*[i]=0x67;
// tic.ZERO[i]= 0x56;
// bunnies[i].draw();
i += 1;
}
}
export fn TIC() void {
if (!started) { start(); }
if (t==0) {
tic.music(0, .{});
}
if (t == 6*64*2.375) {
tic.music(1, .{});
}
t = t + 1;
if (tic.btn(0)) {
var i : i32 = 0;
while (i<5) {
addBunny();
i+=1;
}
}
if (tic.btn(1)) {
var i : i32 = 0;
while (i<5) {
removeBunny();
i+=1;
}
}
// -- Update
var i : u32 = 0;
while (i<bunnyCount) {
bunnies[i].update();
i += 1;
}
// -- Draw
tic.cls(15);
i = 0;
while (i<bunnyCount) {
bunnies[i].draw();
i += 1;
}
tic.rect(0, 0, screenWidth, toolbarHeight, 9);
_ = tic.printf("Bunnies: {d}", .{bunnyCount}, 1, 0, .{.color = 11});
_ = tic.printf("FPS: {d:.4}", .{fps.getValue()}, screenWidth / 2, 0, .{.color = 11});
_ = tic.print("hello people", 10, 10, .{.color = 11});
// var x : u32 = 100000000;
// tic.FRAMEBUFFER[x] = 56;
// testscreen();
} | demos/bunny/wasmmark/src/main.zig |
const std = @import("std");
pub const Parser = struct {
document: []const u8,
current_tag: []const u8 = undefined,
char_buffer: [4]u8 = undefined,
mode: enum { normal, attrs, chars, entity } = .normal,
pub fn init(document: []const u8) Parser {
return Parser{
.document = document,
};
}
pub fn next(p: *Parser) ?Event {
return switch (p.mode) {
.normal => p.nextNormal(),
.attrs => p.nextAttrs(),
.chars => p.nextChars(),
.entity => p.nextEntity(),
};
}
fn nextNormal(p: *Parser) ?Event {
p.skipWhitespace();
switch (p.peek(0) orelse return null) {
'<' => switch (p.peek(1) orelse return null) {
'?' => {
if (std.mem.indexOf(u8, p.document[2..], "?>")) |end| {
const ev = Event{ .processing_instruction = p.document[2 .. end + 2] };
p.document = p.document[end + 4 ..];
return ev;
}
},
'/' => switch (p.peek(2) orelse return null) {
':', 'A'...'Z', '_', 'a'...'z' => {
if (std.mem.indexOfScalar(u8, p.document[3..], '>')) |end| {
const ev = Event{ .close_tag = p.document[2 .. end + 3] };
p.document = p.document[end + 4 ..];
return ev;
}
},
else => {},
},
'!' => switch (p.peek(2) orelse return null) {
'-' => if ((p.peek(3) orelse return null) == '-') {
if (std.mem.indexOf(u8, p.document[3..], "-->")) |end| {
const ev = Event{ .comment = p.document[4 .. end + 3] };
p.document = p.document[end + 6 ..];
return ev;
}
},
'[' => if (std.mem.startsWith(u8, p.document[3..], "CDATA[")) {
if (std.mem.indexOf(u8, p.document, "]]>")) |end| {
const ev = Event{ .character_data = p.document[9..end] };
p.document = p.document[end + 3 ..];
return ev;
}
},
else => {},
},
':', 'A'...'Z', '_', 'a'...'z' => {
const angle = std.mem.indexOfScalar(u8, p.document, '>') orelse return null;
if (std.mem.indexOfScalar(u8, p.document[0..angle], ' ')) |space| {
const ev = Event{ .open_tag = p.document[1..space] };
p.current_tag = ev.open_tag;
p.document = p.document[space..];
p.mode = .attrs;
return ev;
}
if (std.mem.indexOfScalar(u8, p.document[0..angle], '/')) |slash| {
const ev = Event{ .open_tag = p.document[1..slash] };
p.current_tag = ev.open_tag;
p.document = p.document[slash..];
p.mode = .attrs;
return ev;
}
const ev = Event{ .open_tag = p.document[1..angle] };
p.current_tag = ev.open_tag;
p.document = p.document[angle..];
p.mode = .attrs;
return ev;
},
else => {},
},
else => {
p.mode = .chars;
return p.nextChars();
},
}
return null;
}
fn nextAttrs(p: *Parser) ?Event {
p.skipWhitespace();
switch (p.peek(0) orelse return null) {
'>' => {
p.document = p.document[1..];
p.mode = .normal;
return p.nextNormal();
},
'/' => {
const ev = Event{ .close_tag = p.current_tag };
if ((p.peek(1) orelse return null) != '>')
return null;
p.document = p.document[2..];
p.mode = .normal;
return ev;
},
else => {},
}
var i: usize = 0;
while (isNameChar(p.peek(i) orelse return null)) : (i += 1) {}
const name = p.document[0..i];
p.document = p.document[i..];
p.skipWhitespace();
if ((p.peek(0) orelse return null) != '=')
return null;
p.document = p.document[1..];
p.skipWhitespace();
const c = p.peek(0) orelse return null;
switch (c) {
'\'', '"' => {
if (std.mem.indexOfScalar(u8, p.document[1..], c)) |end| {
const ev = Event{
.attribute = .{
.name = name,
.raw_value = p.document[1 .. end + 1],
},
};
p.document = p.document[end + 2 ..];
return ev;
}
},
else => {},
}
return null;
}
fn nextChars(p: *Parser) ?Event {
var i: usize = 0;
while (true) : (i += 1) {
const c = p.peek(i) orelse return null;
if (c == '<' or c == '&') {
const ev = Event{ .character_data = p.document[0..i] };
p.document = p.document[i..];
p.mode = switch (c) {
'<' => .normal,
'&' => .entity,
else => unreachable,
};
return ev;
}
switch (c) {
'<', '&' => {},
else => {},
}
}
return null;
}
fn parseEntity(s: []const u8, buf: *[4]u8) ?usize {
const semi = std.mem.indexOfScalar(u8, s, ';') orelse return null;
const entity = s[0..semi];
if (std.mem.eql(u8, entity, "lt")) {
buf.* = std.mem.toBytes(@as(u32, '<'));
} else if (std.mem.eql(u8, entity, "gt")) {
buf.* = std.mem.toBytes(@as(u32, '>'));
} else if (std.mem.eql(u8, entity, "amp")) {
buf.* = std.mem.toBytes(@as(u32, '&'));
} else if (std.mem.eql(u8, entity, "apos")) {
buf.* = std.mem.toBytes(@as(u32, '\''));
} else if (std.mem.eql(u8, entity, "quot")) {
buf.* = std.mem.toBytes(@as(u32, '"'));
} else if (std.mem.startsWith(u8, entity, "#x")) {
const codepoint = std.fmt.parseInt(u21, entity[2..semi], 16) catch return null;
buf.* = std.mem.toBytes(@as(u32, codepoint));
} else if (std.mem.startsWith(u8, entity, "#")) {
const codepoint = std.fmt.parseInt(u21, entity[1..semi], 10) catch return null;
buf.* = std.mem.toBytes(@as(u32, codepoint));
} else {
return null;
}
return semi;
}
fn nextEntity(p: *Parser) ?Event {
if ((p.peek(0) orelse return null) != '&')
return null;
if (parseEntity(p.document[1..], &p.char_buffer)) |semi| {
const codepoint = std.mem.bytesToValue(u32, &p.char_buffer);
const n = std.unicode.utf8Encode(@intCast(u21, codepoint), &p.char_buffer) catch return null;
p.document = p.document[semi + 2 ..];
p.mode = .chars;
return Event{ .character_data = p.char_buffer[0..n] };
}
return null;
}
fn isNameChar(c: u8) bool {
return switch (c) {
':', 'A'...'Z', '_', 'a'...'z', '-', '.', '0'...'9' => true,
else => false,
};
}
fn skipWhitespace(p: *Parser) void {
while (true) {
switch (p.peek(0) orelse return) {
' ', '\t', '\n', '\r' => {
p.document = p.document[1..];
},
else => {
return;
},
}
}
}
fn peek(p: *Parser, n: usize) ?u8 {
if (p.document.len <= n)
return null;
return p.document[n];
}
};
pub const Event = union(enum) {
open_tag: []const u8,
close_tag: []const u8,
attribute: Attribute,
comment: []const u8,
processing_instruction: []const u8,
character_data: []const u8,
};
pub const Attribute = struct {
name: []const u8,
raw_value: []const u8,
char_buffer: [4]u8 = undefined,
pub fn dupeValue(attr: Attribute, allocator: *std.mem.Allocator) error{OutOfMemory}![]u8 {
var list = std.ArrayList(u8).init(allocator);
errdefer list.deinit();
var attr_copy = attr;
while (attr_copy.next()) |fragment|
try list.appendSlice(fragment);
return list.toOwnedSlice();
}
pub fn valueStartsWith(attr: Attribute, prefix: []const u8) bool {
var attr_copy = attr;
var i: usize = 0;
while (attr_copy.next()) |fragment| {
if (std.mem.startsWith(u8, fragment, prefix[i..])) {
i += fragment.len;
} else {
return false;
}
}
return i > prefix.len;
}
pub fn valueEql(attr: Attribute, value: []const u8) bool {
var attr_copy = attr;
var i: usize = 0;
while (attr_copy.next()) |fragment| {
if (std.mem.startsWith(u8, value[i..], fragment)) {
i += fragment.len;
} else {
return false;
}
}
return i == value.len;
}
pub fn next(attr: *Attribute) ?[]const u8 {
if (attr.raw_value.len == 0)
return null;
if (attr.raw_value[0] == '&') {
if (Parser.parseEntity(attr.raw_value[1..], &attr.char_buffer)) |semi| {
const codepoint = std.mem.bytesToValue(u32, &attr.char_buffer);
const n = std.unicode.utf8Encode(@intCast(u21, codepoint), &attr.char_buffer) catch return null;
attr.raw_value = attr.raw_value[semi + 2 ..];
return attr.char_buffer[0..n];
} else {
return null;
}
}
var i: usize = 0;
while (true) : (i += 1) {
if (attr.raw_value.len == i or attr.raw_value[i] == '&') {
const ret = attr.raw_value[0..i];
attr.raw_value = attr.raw_value[i..];
return ret;
}
}
}
}; | lib/zig-xml/xml.zig |
// Fundamental types
pub const F32x4 = @Vector(4, f32);
pub const F32x8 = @Vector(8, f32);
pub const F32x16 = @Vector(16, f32);
pub const Boolx4 = @Vector(4, bool);
pub const Boolx8 = @Vector(8, bool);
pub const Boolx16 = @Vector(16, bool);
// Higher-level 'geometric' types
pub const Vec = F32x4;
pub const Mat = [4]F32x4;
pub const Quat = F32x4;
// Helper types
pub const U32x4 = @Vector(4, u32);
pub const U32x8 = @Vector(8, u32);
pub const U32x16 = @Vector(16, u32);
const builtin = @import("builtin");
const std = @import("std");
const math = std.math;
const assert = std.debug.assert;
const expect = std.testing.expect;
const cpu_arch = builtin.cpu.arch;
const has_avx = if (cpu_arch == .x86_64) std.Target.x86.featureSetHas(builtin.cpu.features, .avx) else false;
const has_avx512f = if (cpu_arch == .x86_64) std.Target.x86.featureSetHas(builtin.cpu.features, .avx512f) else false;
const has_fma = if (cpu_arch == .x86_64) std.Target.x86.featureSetHas(builtin.cpu.features, .fma) else false;
// ------------------------------------------------------------------------------
//
// 1. Initialization functions
//
// ------------------------------------------------------------------------------
pub inline fn f32x4(e0: f32, e1: f32, e2: f32, e3: f32) F32x4 {
return .{ e0, e1, e2, e3 };
}
pub inline fn f32x8(e0: f32, e1: f32, e2: f32, e3: f32, e4: f32, e5: f32, e6: f32, e7: f32) F32x8 {
return .{ e0, e1, e2, e3, e4, e5, e6, e7 };
}
// zig fmt: off
pub inline fn f32x16(
e0: f32, e1: f32, e2: f32, e3: f32, e4: f32, e5: f32, e6: f32, e7: f32,
e8: f32, e9: f32, ea: f32, eb: f32, ec: f32, ed: f32, ee: f32, ef: f32) F32x16 {
return .{ e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, ea, eb, ec, ed, ee, ef };
}
// zig fmt: on
pub inline fn f32x4s(e0: f32) F32x4 {
return splat(F32x4, e0);
}
pub inline fn f32x8s(e0: f32) F32x8 {
return splat(F32x8, e0);
}
pub inline fn f32x16s(e0: f32) F32x16 {
return splat(F32x16, e0);
}
pub inline fn u32x4(e0: u32, e1: u32, e2: u32, e3: u32) U32x4 {
return .{ e0, e1, e2, e3 };
}
pub inline fn u32x8(e0: u32, e1: u32, e2: u32, e3: u32, e4: u32, e5: u32, e6: u32, e7: u32) U32x8 {
return .{ e0, e1, e2, e3, e4, e5, e6, e7 };
}
// zig fmt: off
pub inline fn u32x16(
e0: u32, e1: u32, e2: u32, e3: u32, e4: u32, e5: u32, e6: u32, e7: u32,
e8: u32, e9: u32, ea: u32, eb: u32, ec: u32, ed: u32, ee: u32, ef: u32) U32x16 {
return .{ e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, ea, eb, ec, ed, ee, ef };
}
// zig fmt: on
pub inline fn boolx4(e0: bool, e1: bool, e2: bool, e3: bool) Boolx4 {
return .{ e0, e1, e2, e3 };
}
pub inline fn boolx8(e0: bool, e1: bool, e2: bool, e3: bool, e4: bool, e5: bool, e6: bool, e7: bool) Boolx8 {
return .{ e0, e1, e2, e3, e4, e5, e6, e7 };
}
// zig fmt: off
pub inline fn boolx16(
e0: bool, e1: bool, e2: bool, e3: bool, e4: bool, e5: bool, e6: bool, e7: bool,
e8: bool, e9: bool, ea: bool, eb: bool, ec: bool, ed: bool, ee: bool, ef: bool) Boolx16 {
return .{ e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, ea, eb, ec, ed, ee, ef };
}
// zig fmt: on
pub fn veclen(comptime T: type) comptime_int {
return @typeInfo(T).Vector.len;
}
pub inline fn splat(comptime T: type, value: f32) T {
return @splat(veclen(T), value);
}
pub inline fn splatInt(comptime T: type, value: u32) T {
return @splat(veclen(T), @bitCast(f32, value));
}
pub inline fn usplat(comptime T: type, value: u32) T {
return @splat(veclen(T), value);
}
pub fn load(mem: []const f32, comptime T: type, comptime len: u32) T {
var v = splat(T, 0.0);
comptime var loop_len = if (len == 0) veclen(T) else len;
comptime var i: u32 = 0;
inline while (i < loop_len) : (i += 1) {
v[i] = mem[i];
}
return v;
}
test "zmath.load" {
const a = [7]f32{ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0 };
var ptr = &a;
var i: u32 = 0;
const v0 = load(a[i..], F32x4, 2);
try expect(approxEqAbs(v0, f32x4(1.0, 2.0, 0.0, 0.0), 0.0));
i += 2;
const v1 = load(a[i .. i + 2], F32x4, 2);
try expect(approxEqAbs(v1, f32x4(3.0, 4.0, 0.0, 0.0), 0.0));
const v2 = load(a[5..7], F32x4, 2);
try expect(approxEqAbs(v2, f32x4(6.0, 7.0, 0.0, 0.0), 0.0));
const v3 = load(ptr[1..], F32x4, 2);
try expect(approxEqAbs(v3, f32x4(2.0, 3.0, 0.0, 0.0), 0.0));
i += 1;
const v4 = load(ptr[i .. i + 2], F32x4, 2);
try expect(approxEqAbs(v4, f32x4(4.0, 5.0, 0.0, 0.0), 0.0));
}
pub fn store(mem: []f32, v: anytype, comptime len: u32) void {
const T = @TypeOf(v);
comptime var loop_len = if (len == 0) veclen(T) else len;
comptime var i: u32 = 0;
inline while (i < loop_len) : (i += 1) {
mem[i] = v[i];
}
}
test "zmath.store" {
var a = [7]f32{ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0 };
const v = load(a[1..], F32x4, 3);
store(a[2..], v, 4);
try expect(a[0] == 1.0);
try expect(a[1] == 2.0);
try expect(a[2] == 2.0);
try expect(a[3] == 3.0);
try expect(a[4] == 4.0);
try expect(a[5] == 0.0);
}
pub inline fn vec3ToArray(v: Vec) [3]f32 {
return .{ v[0], v[1], v[2] };
}
// ------------------------------------------------------------------------------
//
// 2. Functions that work on all vector components (F32xN = F32x4 or F32x8 or F32x16)
//
// ------------------------------------------------------------------------------
pub fn all(vb: anytype, comptime len: u32) bool {
const T = @TypeOf(vb);
if (len > veclen(T)) {
@compileError("zmath.all(): 'len' is greater than vector len of type " ++ @typeName(T));
}
comptime var loop_len = if (len == 0) veclen(T) else len;
const ab: [veclen(T)]bool = vb;
comptime var i: u32 = 0;
var result = true;
inline while (i < loop_len) : (i += 1) {
result = result and ab[i];
}
return result;
}
test "zmath.all" {
try expect(all(boolx8(true, true, true, true, true, false, true, false), 5) == true);
try expect(all(boolx8(true, true, true, true, true, false, true, false), 6) == false);
try expect(all(boolx8(true, true, true, true, false, false, false, false), 4) == true);
try expect(all(boolx4(true, true, true, false), 3) == true);
try expect(all(boolx4(true, true, true, false), 1) == true);
try expect(all(boolx4(true, false, false, false), 1) == true);
try expect(all(boolx4(false, true, false, false), 1) == false);
try expect(all(boolx8(true, true, true, true, true, false, true, false), 0) == false);
try expect(all(boolx4(false, true, false, false), 0) == false);
try expect(all(boolx4(true, true, true, true), 0) == true);
}
pub fn any(vb: anytype, comptime len: u32) bool {
const T = @TypeOf(vb);
if (len > veclen(T)) {
@compileError("zmath.any(): 'len' is greater than vector len of type " ++ @typeName(T));
}
comptime var loop_len = if (len == 0) veclen(T) else len;
const ab: [veclen(T)]bool = vb;
comptime var i: u32 = 0;
var result = false;
inline while (i < loop_len) : (i += 1) {
result = result or ab[i];
}
return result;
}
test "zmath.any" {
try expect(any(boolx8(true, true, true, true, true, false, true, false), 0) == true);
try expect(any(boolx8(false, false, false, true, true, false, true, false), 3) == false);
try expect(any(boolx8(false, false, false, false, false, true, false, false), 4) == false);
}
pub inline fn isNearEqual(
v0: anytype,
v1: anytype,
epsilon: anytype,
) @Vector(veclen(@TypeOf(v0)), bool) {
const T = @TypeOf(v0, v1);
const delta = v0 - v1;
const temp = maxFast(delta, splat(T, 0.0) - delta);
return temp <= epsilon;
}
test "zmath.isNearEqual" {
{
const v0 = f32x4(1.0, 2.0, -3.0, 4.001);
const v1 = f32x4(1.0, 2.1, 3.0, 4.0);
const b = isNearEqual(v0, v1, splat(F32x4, 0.01));
try expect(@reduce(.And, b == Boolx4{ true, false, false, true }));
}
{
const v0 = f32x8(1.0, 2.0, -3.0, 4.001, 1.001, 2.3, -0.0, 0.0);
const v1 = f32x8(1.0, 2.1, 3.0, 4.0, -1.001, 2.1, 0.0, 0.0);
const b = isNearEqual(v0, v1, splat(F32x8, 0.01));
try expect(@reduce(.And, b == Boolx8{ true, false, false, true, false, false, true, true }));
}
try expect(all(isNearEqual(
splat(F32x4, math.inf_f32),
splat(F32x4, math.inf_f32),
splat(F32x4, 0.0001),
), 0) == false);
try expect(all(isNearEqual(
splat(F32x4, -math.inf_f32),
splat(F32x4, math.inf_f32),
splat(F32x4, 0.0001),
), 0) == false);
try expect(all(isNearEqual(
splat(F32x4, -math.inf_f32),
splat(F32x4, -math.inf_f32),
splat(F32x4, 0.0001),
), 0) == false);
try expect(all(isNearEqual(
splat(F32x4, -math.nan_f32),
splat(F32x4, math.inf_f32),
splat(F32x4, 0.0001),
), 0) == false);
}
pub inline fn isNan(
v: anytype,
) @Vector(veclen(@TypeOf(v)), bool) {
return v != v;
}
test "zmath.isNan" {
{
const v0 = F32x4{ math.inf_f32, math.nan_f32, math.qnan_f32, 7.0 };
const b = isNan(v0);
try expect(@reduce(.And, b == Boolx4{ false, true, true, false }));
}
{
const v0 = F32x8{ 0, math.nan_f32, 0, 0, math.inf_f32, math.nan_f32, math.qnan_f32, 7.0 };
const b = isNan(v0);
try expect(@reduce(.And, b == Boolx8{ false, true, false, false, false, true, true, false }));
}
}
pub inline fn isInf(
v: anytype,
) @Vector(veclen(@TypeOf(v)), bool) {
const T = @TypeOf(v);
return abs(v) == splat(T, math.inf_f32);
}
test "zmath.isInf" {
{
const v0 = f32x4(math.inf_f32, math.nan_f32, math.qnan_f32, 7.0);
const b = isInf(v0);
try expect(@reduce(.And, b == boolx4(true, false, false, false)));
}
{
const v0 = f32x8(0, math.inf_f32, 0, 0, math.inf_f32, math.nan_f32, math.qnan_f32, 7.0);
const b = isInf(v0);
try expect(@reduce(.And, b == boolx8(false, true, false, false, true, false, false, false)));
}
}
pub inline fn isInBounds(
v: anytype,
bounds: anytype,
) @Vector(veclen(@TypeOf(v)), bool) {
const T = @TypeOf(v, bounds);
const Tu = @Vector(veclen(T), u1);
const Tr = @Vector(veclen(T), bool);
// 2 x cmpleps, xorps, load, andps
const b0 = v <= bounds;
const b1 = (bounds * splat(T, -1.0)) <= v;
const b0u = @bitCast(Tu, b0);
const b1u = @bitCast(Tu, b1);
return @bitCast(Tr, b0u & b1u);
}
test "zmath.isInBounds" {
{
const v0 = f32x4(0.5, -2.0, -1.0, 1.9);
const v1 = f32x4(-1.6, -2.001, -1.0, 1.9);
const bounds = f32x4(1.0, 2.0, 1.0, 2.0);
const b0 = isInBounds(v0, bounds);
const b1 = isInBounds(v1, bounds);
try expect(@reduce(.And, b0 == boolx4(true, true, true, true)));
try expect(@reduce(.And, b1 == boolx4(false, false, true, true)));
}
{
const v0 = f32x8(2.0, 1.0, 2.0, 1.0, 0.5, -2.0, -1.0, 1.9);
const bounds = f32x8(1.0, 1.0, 1.0, math.inf_f32, 1.0, math.nan_f32, 1.0, 2.0);
const b0 = isInBounds(v0, bounds);
try expect(@reduce(.And, b0 == boolx8(false, true, false, true, true, false, true, true)));
}
}
pub inline fn andInt(v0: anytype, v1: anytype) @TypeOf(v0, v1) {
const T = @TypeOf(v0, v1);
const Tu = @Vector(veclen(T), u32);
const v0u = @bitCast(Tu, v0);
const v1u = @bitCast(Tu, v1);
return @bitCast(T, v0u & v1u); // andps
}
test "zmath.andInt" {
{
const v0 = f32x4(0, @bitCast(f32, ~@as(u32, 0)), 0, @bitCast(f32, ~@as(u32, 0)));
const v1 = f32x4(1.0, 2.0, 3.0, math.inf_f32);
const v = andInt(v0, v1);
try expect(v[3] == math.inf_f32);
try expect(approxEqAbs(v, f32x4(0.0, 2.0, 0.0, math.inf_f32), 0.0));
}
{
const v0 = f32x8(0, 0, 0, 0, 0, @bitCast(f32, ~@as(u32, 0)), 0, @bitCast(f32, ~@as(u32, 0)));
const v1 = f32x8(0, 0, 0, 0, 1.0, 2.0, 3.0, math.inf_f32);
const v = andInt(v0, v1);
try expect(v[7] == math.inf_f32);
try expect(approxEqAbs(v, f32x8(0, 0, 0, 0, 0.0, 2.0, 0.0, math.inf_f32), 0.0));
}
}
pub inline fn andNotInt(v0: anytype, v1: anytype) @TypeOf(v0, v1) {
const T = @TypeOf(v0, v1);
const Tu = @Vector(veclen(T), u32);
const v0u = @bitCast(Tu, v0);
const v1u = @bitCast(Tu, v1);
return @bitCast(T, ~v0u & v1u); // andnps
}
test "zmath.andNotInt" {
{
const v0 = F32x4{ 1.0, 2.0, 3.0, 4.0 };
const v1 = F32x4{ 0, @bitCast(f32, ~@as(u32, 0)), 0, @bitCast(f32, ~@as(u32, 0)) };
const v = andNotInt(v1, v0);
try expect(approxEqAbs(v, F32x4{ 1.0, 0.0, 3.0, 0.0 }, 0.0));
}
{
const v0 = F32x8{ 0, 0, 0, 0, 1.0, 2.0, 3.0, 4.0 };
const v1 = F32x8{ 0, 0, 0, 0, 0, @bitCast(f32, ~@as(u32, 0)), 0, @bitCast(f32, ~@as(u32, 0)) };
const v = andNotInt(v1, v0);
try expect(approxEqAbs(v, F32x8{ 0, 0, 0, 0, 1.0, 0.0, 3.0, 0.0 }, 0.0));
}
}
pub inline fn orInt(v0: anytype, v1: anytype) @TypeOf(v0, v1) {
const T = @TypeOf(v0, v1);
const Tu = @Vector(veclen(T), u32);
const v0u = @bitCast(Tu, v0);
const v1u = @bitCast(Tu, v1);
return @bitCast(T, v0u | v1u); // orps
}
test "zmath.orInt" {
{
const v0 = F32x4{ 0, @bitCast(f32, ~@as(u32, 0)), 0, 0 };
const v1 = F32x4{ 1.0, 2.0, 3.0, 4.0 };
const v = orInt(v0, v1);
try expect(v[0] == 1.0);
try expect(@bitCast(u32, v[1]) == ~@as(u32, 0));
try expect(v[2] == 3.0);
try expect(v[3] == 4.0);
}
{
const v0 = F32x8{ 0, 0, 0, 0, 0, @bitCast(f32, ~@as(u32, 0)), 0, 0 };
const v1 = F32x8{ 0, 0, 0, 0, 1.0, 2.0, 3.0, 4.0 };
const v = orInt(v0, v1);
try expect(v[4] == 1.0);
try expect(@bitCast(u32, v[5]) == ~@as(u32, 0));
try expect(v[6] == 3.0);
try expect(v[7] == 4.0);
}
}
pub inline fn norInt(v0: anytype, v1: anytype) @TypeOf(v0, v1) {
const T = @TypeOf(v0, v1);
const Tu = @Vector(veclen(T), u32);
const v0u = @bitCast(Tu, v0);
const v1u = @bitCast(Tu, v1);
return @bitCast(T, ~(v0u | v1u)); // por, pcmpeqd, pxor
}
pub inline fn xorInt(v0: anytype, v1: anytype) @TypeOf(v0, v1) {
const T = @TypeOf(v0, v1);
const Tu = @Vector(veclen(T), u32);
const v0u = @bitCast(Tu, v0);
const v1u = @bitCast(Tu, v1);
return @bitCast(T, v0u ^ v1u); // xorps
}
test "zmath.xorInt" {
{
const v0 = F32x4{ 1.0, @bitCast(f32, ~@as(u32, 0)), 0, 0 };
const v1 = F32x4{ 1.0, 0, 0, 0 };
const v = xorInt(v0, v1);
try expect(v[0] == 0.0);
try expect(@bitCast(u32, v[1]) == ~@as(u32, 0));
try expect(v[2] == 0.0);
try expect(v[3] == 0.0);
}
{
const v0 = F32x8{ 0, 0, 0, 0, 1.0, @bitCast(f32, ~@as(u32, 0)), 0, 0 };
const v1 = F32x8{ 0, 0, 0, 0, 1.0, 0, 0, 0 };
const v = xorInt(v0, v1);
try expect(v[4] == 0.0);
try expect(@bitCast(u32, v[5]) == ~@as(u32, 0));
try expect(v[6] == 0.0);
try expect(v[7] == 0.0);
}
}
pub inline fn minFast(v0: anytype, v1: anytype) @TypeOf(v0, v1) {
return select(v0 < v1, v0, v1); // minps
}
test "zmath.minFast" {
{
const v0 = f32x4(1.0, 3.0, 2.0, 7.0);
const v1 = f32x4(2.0, 1.0, 4.0, math.inf_f32);
const v = minFast(v0, v1);
try expect(approxEqAbs(v, f32x4(1.0, 1.0, 2.0, 7.0), 0.0));
}
{
const v0 = f32x4(1.0, math.nan_f32, 5.0, math.qnan_f32);
const v1 = f32x4(2.0, 1.0, 4.0, math.inf_f32);
const v = minFast(v0, v1);
try expect(v[0] == 1.0);
try expect(v[1] == 1.0);
try expect(!math.isNan(v[1]));
try expect(v[2] == 4.0);
try expect(v[3] == math.inf_f32);
try expect(!math.isNan(v[3]));
}
}
pub inline fn maxFast(v0: anytype, v1: anytype) @TypeOf(v0, v1) {
return select(v0 > v1, v0, v1); // maxps
}
test "zmath.maxFast" {
{
const v0 = f32x4(1.0, 3.0, 2.0, 7.0);
const v1 = f32x4(2.0, 1.0, 4.0, math.inf_f32);
const v = maxFast(v0, v1);
try expect(approxEqAbs(v, f32x4(2.0, 3.0, 4.0, math.inf_f32), 0.0));
}
{
const v0 = f32x4(1.0, math.nan_f32, 5.0, math.qnan_f32);
const v1 = f32x4(2.0, 1.0, 4.0, math.inf_f32);
const v = maxFast(v0, v1);
try expect(v[0] == 2.0);
try expect(v[1] == 1.0);
try expect(v[2] == 5.0);
try expect(v[3] == math.inf_f32);
try expect(!math.isNan(v[3]));
}
}
pub inline fn min(v0: anytype, v1: anytype) @TypeOf(v0, v1) {
// This will handle inf & nan
return @minimum(v0, v1); // minps, cmpunordps, andps, andnps, orps
}
test "zmath.min" {
{
const v0 = f32x4(1.0, 3.0, 2.0, 7.0);
const v1 = f32x4(2.0, 1.0, 4.0, math.inf_f32);
const v = min(v0, v1);
try expect(approxEqAbs(v, f32x4(1.0, 1.0, 2.0, 7.0), 0.0));
}
{
const v0 = f32x8(0, 0, -2.0, 0, 1.0, 3.0, 2.0, 7.0);
const v1 = f32x8(0, 1.0, 0, 0, 2.0, 1.0, 4.0, math.inf_f32);
const v = min(v0, v1);
try expect(approxEqAbs(v, f32x8(0.0, 0.0, -2.0, 0.0, 1.0, 1.0, 2.0, 7.0), 0.0));
}
{
const v0 = f32x4(1.0, math.nan_f32, 5.0, math.qnan_f32);
const v1 = f32x4(2.0, 1.0, 4.0, math.inf_f32);
const v = min(v0, v1);
try expect(v[0] == 1.0);
try expect(v[1] == 1.0);
try expect(!math.isNan(v[1]));
try expect(v[2] == 4.0);
try expect(v[3] == math.inf_f32);
try expect(!math.isNan(v[3]));
}
{
const v0 = f32x4(-math.inf_f32, math.inf_f32, math.inf_f32, math.qnan_f32);
const v1 = f32x4(math.qnan_f32, -math.inf_f32, math.qnan_f32, math.nan_f32);
const v = min(v0, v1);
try expect(v[0] == -math.inf_f32);
try expect(v[1] == -math.inf_f32);
try expect(v[2] == math.inf_f32);
try expect(!math.isNan(v[2]));
try expect(math.isNan(v[3]));
try expect(!math.isInf(v[3]));
}
}
pub inline fn max(v0: anytype, v1: anytype) @TypeOf(v0, v1) {
// This will handle inf & nan
return @maximum(v0, v1); // maxps, cmpunordps, andps, andnps, orps
}
test "zmath.max" {
{
const v0 = f32x4(1.0, 3.0, 2.0, 7.0);
const v1 = f32x4(2.0, 1.0, 4.0, math.inf_f32);
const v = max(v0, v1);
try expect(approxEqAbs(v, f32x4(2.0, 3.0, 4.0, math.inf_f32), 0.0));
}
{
const v0 = f32x8(0, 0, -2.0, 0, 1.0, 3.0, 2.0, 7.0);
const v1 = f32x8(0, 1.0, 0, 0, 2.0, 1.0, 4.0, math.inf_f32);
const v = max(v0, v1);
try expect(approxEqAbs(v, f32x8(0.0, 1.0, 0.0, 0.0, 2.0, 3.0, 4.0, math.inf_f32), 0.0));
}
{
const v0 = f32x4(1.0, math.nan_f32, 5.0, math.qnan_f32);
const v1 = f32x4(2.0, 1.0, 4.0, math.inf_f32);
const v = max(v0, v1);
try expect(v[0] == 2.0);
try expect(v[1] == 1.0);
try expect(v[2] == 5.0);
try expect(v[3] == math.inf_f32);
try expect(!math.isNan(v[3]));
}
{
const v0 = f32x4(-math.inf_f32, math.inf_f32, math.inf_f32, math.qnan_f32);
const v1 = f32x4(math.qnan_f32, -math.inf_f32, math.qnan_f32, math.nan_f32);
const v = max(v0, v1);
try expect(v[0] == -math.inf_f32);
try expect(v[1] == math.inf_f32);
try expect(v[2] == math.inf_f32);
try expect(!math.isNan(v[2]));
try expect(math.isNan(v[3]));
try expect(!math.isInf(v[3]));
}
}
pub fn round(v: anytype) @TypeOf(v) {
const T = @TypeOf(v);
if (cpu_arch == .x86_64 and has_avx) {
if (T == F32x4) {
return asm ("vroundps $0, %%xmm0, %%xmm0"
: [ret] "={xmm0}" (-> T),
: [v] "{xmm0}" (v),
);
} else if (T == F32x8) {
return asm ("vroundps $0, %%ymm0, %%ymm0"
: [ret] "={ymm0}" (-> T),
: [v] "{ymm0}" (v),
);
} else if (T == F32x16 and has_avx512f) {
return asm ("vrndscaleps $0, %%zmm0, %%zmm0"
: [ret] "={zmm0}" (-> T),
: [v] "{zmm0}" (v),
);
} else if (T == F32x16 and !has_avx512f) {
const arr: [16]f32 = v;
var ymm0 = @as(F32x8, arr[0..8].*);
var ymm1 = @as(F32x8, arr[8..16].*);
ymm0 = asm ("vroundps $0, %%ymm0, %%ymm0"
: [ret] "={ymm0}" (-> F32x8),
: [v] "{ymm0}" (ymm0),
);
ymm1 = asm ("vroundps $0, %%ymm1, %%ymm1"
: [ret] "={ymm1}" (-> F32x8),
: [v] "{ymm1}" (ymm1),
);
return @shuffle(f32, ymm0, ymm1, [16]i32{ 0, 1, 2, 3, 4, 5, 6, 7, -1, -2, -3, -4, -5, -6, -7, -8 });
}
} else {
const sign = andInt(v, splatNegativeZero(T));
const magic = orInt(splatNoFraction(T), sign);
var r1 = v + magic;
r1 = r1 - magic;
const r2 = abs(v);
const mask = r2 <= splatNoFraction(T);
return select(mask, r1, v);
}
}
test "zmath.round" {
{
try expect(all(round(splat(F32x4, math.inf_f32)) == splat(F32x4, math.inf_f32), 0));
try expect(all(round(splat(F32x4, -math.inf_f32)) == splat(F32x4, -math.inf_f32), 0));
try expect(all(isNan(round(splat(F32x4, math.nan_f32))), 0));
try expect(all(isNan(round(splat(F32x4, -math.nan_f32))), 0));
try expect(all(isNan(round(splat(F32x4, math.qnan_f32))), 0));
try expect(all(isNan(round(splat(F32x4, -math.qnan_f32))), 0));
}
{
var v = round(F32x16{ 1.1, -1.1, -1.5, 1.5, 2.1, 2.8, 2.9, 4.1, 5.8, 6.1, 7.9, 8.9, 10.1, 11.2, 12.7, 13.1 });
try expect(approxEqAbs(
v,
F32x16{ 1.0, -1.0, -2.0, 2.0, 2.0, 3.0, 3.0, 4.0, 6.0, 6.0, 8.0, 9.0, 10.0, 11.0, 13.0, 13.0 },
0.0,
));
}
var v = round(F32x4{ 1.1, -1.1, -1.5, 1.5 });
try expect(approxEqAbs(v, F32x4{ 1.0, -1.0, -2.0, 2.0 }, 0.0));
const v1 = F32x4{ -10_000_000.1, -math.inf_f32, 10_000_001.5, math.inf_f32 };
v = round(v1);
try expect(v[3] == math.inf_f32);
try expect(approxEqAbs(v, F32x4{ -10_000_000.1, -math.inf_f32, 10_000_001.5, math.inf_f32 }, 0.0));
const v2 = F32x4{ -math.qnan_f32, math.qnan_f32, math.nan_f32, -math.inf_f32 };
v = round(v2);
try expect(math.isNan(v2[0]));
try expect(math.isNan(v2[1]));
try expect(math.isNan(v2[2]));
try expect(v2[3] == -math.inf_f32);
const v3 = F32x4{ 1001.5, -201.499, -10000.99, -101.5 };
v = round(v3);
try expect(approxEqAbs(v, F32x4{ 1002.0, -201.0, -10001.0, -102.0 }, 0.0));
const v4 = F32x4{ -1_388_609.9, 1_388_609.5, 1_388_109.01, 2_388_609.5 };
v = round(v4);
try expect(approxEqAbs(v, F32x4{ -1_388_610.0, 1_388_610.0, 1_388_109.0, 2_388_610.0 }, 0.0));
var f: f32 = -100.0;
var i: u32 = 0;
while (i < 100) : (i += 1) {
const vr = round(splat(F32x4, f));
const fr = @round(splat(F32x4, f));
const vr8 = round(splat(F32x8, f));
const fr8 = @round(splat(F32x8, f));
const vr16 = round(splat(F32x16, f));
const fr16 = @round(splat(F32x16, f));
try expect(approxEqAbs(vr, fr, 0.0));
try expect(approxEqAbs(vr8, fr8, 0.0));
try expect(approxEqAbs(vr16, fr16, 0.0));
f += 0.12345 * @intToFloat(f32, i);
}
}
pub fn trunc(v: anytype) @TypeOf(v) {
const T = @TypeOf(v);
if (cpu_arch == .x86_64 and has_avx) {
if (T == F32x4) {
return asm ("vroundps $3, %%xmm0, %%xmm0"
: [ret] "={xmm0}" (-> T),
: [v] "{xmm0}" (v),
);
} else if (T == F32x8) {
return asm ("vroundps $3, %%ymm0, %%ymm0"
: [ret] "={ymm0}" (-> T),
: [v] "{ymm0}" (v),
);
} else if (T == F32x16 and has_avx512f) {
return asm ("vrndscaleps $3, %%zmm0, %%zmm0"
: [ret] "={zmm0}" (-> T),
: [v] "{zmm0}" (v),
);
} else if (T == F32x16 and !has_avx512f) {
const arr: [16]f32 = v;
var ymm0 = @as(F32x8, arr[0..8].*);
var ymm1 = @as(F32x8, arr[8..16].*);
ymm0 = asm ("vroundps $3, %%ymm0, %%ymm0"
: [ret] "={ymm0}" (-> F32x8),
: [v] "{ymm0}" (ymm0),
);
ymm1 = asm ("vroundps $3, %%ymm1, %%ymm1"
: [ret] "={ymm1}" (-> F32x8),
: [v] "{ymm1}" (ymm1),
);
return @shuffle(f32, ymm0, ymm1, [16]i32{ 0, 1, 2, 3, 4, 5, 6, 7, -1, -2, -3, -4, -5, -6, -7, -8 });
}
} else {
const mask = abs(v) < splatNoFraction(T);
const result = floatToIntAndBack(v);
return select(mask, result, v);
}
}
test "zmath.trunc" {
{
try expect(all(trunc(splat(F32x4, math.inf_f32)) == splat(F32x4, math.inf_f32), 0));
try expect(all(trunc(splat(F32x4, -math.inf_f32)) == splat(F32x4, -math.inf_f32), 0));
try expect(all(isNan(trunc(splat(F32x4, math.nan_f32))), 0));
try expect(all(isNan(trunc(splat(F32x4, -math.nan_f32))), 0));
try expect(all(isNan(trunc(splat(F32x4, math.qnan_f32))), 0));
try expect(all(isNan(trunc(splat(F32x4, -math.qnan_f32))), 0));
}
{
var v = trunc(F32x16{ 1.1, -1.1, -1.5, 1.5, 2.1, 2.8, 2.9, 4.1, 5.8, 6.1, 7.9, 8.9, 10.1, 11.2, 12.7, 13.1 });
try expect(approxEqAbs(
v,
F32x16{ 1.0, -1.0, -1.0, 1.0, 2.0, 2.0, 2.0, 4.0, 5.0, 6.0, 7.0, 8.0, 10.0, 11.0, 12.0, 13.0 },
0.0,
));
}
var v = trunc(F32x4{ 1.1, -1.1, -1.5, 1.5 });
try expect(approxEqAbs(v, F32x4{ 1.0, -1.0, -1.0, 1.0 }, 0.0));
v = trunc(F32x4{ -10_000_002.1, -math.inf_f32, 10_000_001.5, math.inf_f32 });
try expect(approxEqAbs(v, F32x4{ -10_000_002.1, -math.inf_f32, 10_000_001.5, math.inf_f32 }, 0.0));
v = trunc(F32x4{ -math.qnan_f32, math.qnan_f32, math.nan_f32, -math.inf_f32 });
try expect(math.isNan(v[0]));
try expect(math.isNan(v[1]));
try expect(math.isNan(v[2]));
try expect(v[3] == -math.inf_f32);
v = trunc(F32x4{ 1000.5001, -201.499, -10000.99, 100.750001 });
try expect(approxEqAbs(v, F32x4{ 1000.0, -201.0, -10000.0, 100.0 }, 0.0));
v = trunc(F32x4{ -7_388_609.5, 7_388_609.1, 8_388_109.5, -8_388_509.5 });
try expect(approxEqAbs(v, F32x4{ -7_388_609.0, 7_388_609.0, 8_388_109.0, -8_388_509.0 }, 0.0));
var f: f32 = -100.0;
var i: u32 = 0;
while (i < 100) : (i += 1) {
const vr = trunc(splat(F32x4, f));
const fr = @trunc(splat(F32x4, f));
const vr8 = trunc(splat(F32x8, f));
const fr8 = @trunc(splat(F32x8, f));
const vr16 = trunc(splat(F32x16, f));
const fr16 = @trunc(splat(F32x16, f));
try expect(approxEqAbs(vr, fr, 0.0));
try expect(approxEqAbs(vr8, fr8, 0.0));
try expect(approxEqAbs(vr16, fr16, 0.0));
f += 0.12345 * @intToFloat(f32, i);
}
}
pub fn floor(v: anytype) @TypeOf(v) {
const T = @TypeOf(v);
if (cpu_arch == .x86_64 and has_avx) {
if (T == F32x4) {
return asm ("vroundps $1, %%xmm0, %%xmm0"
: [ret] "={xmm0}" (-> T),
: [v] "{xmm0}" (v),
);
} else if (T == F32x8) {
return asm ("vroundps $1, %%ymm0, %%ymm0"
: [ret] "={ymm0}" (-> T),
: [v] "{ymm0}" (v),
);
} else if (T == F32x16 and has_avx512f) {
return asm ("vrndscaleps $1, %%zmm0, %%zmm0"
: [ret] "={zmm0}" (-> T),
: [v] "{zmm0}" (v),
);
} else if (T == F32x16 and !has_avx512f) {
const arr: [16]f32 = v;
var ymm0 = @as(F32x8, arr[0..8].*);
var ymm1 = @as(F32x8, arr[8..16].*);
ymm0 = asm ("vroundps $1, %%ymm0, %%ymm0"
: [ret] "={ymm0}" (-> F32x8),
: [v] "{ymm0}" (ymm0),
);
ymm1 = asm ("vroundps $1, %%ymm1, %%ymm1"
: [ret] "={ymm1}" (-> F32x8),
: [v] "{ymm1}" (ymm1),
);
return @shuffle(f32, ymm0, ymm1, [16]i32{ 0, 1, 2, 3, 4, 5, 6, 7, -1, -2, -3, -4, -5, -6, -7, -8 });
}
} else {
const mask = abs(v) < splatNoFraction(T);
var result = floatToIntAndBack(v);
const larger_mask = result > v;
const larger = select(larger_mask, splat(T, -1.0), splat(T, 0.0));
result = result + larger;
return select(mask, result, v);
}
}
test "zmath.floor" {
{
try expect(all(floor(splat(F32x4, math.inf_f32)) == splat(F32x4, math.inf_f32), 0));
try expect(all(floor(splat(F32x4, -math.inf_f32)) == splat(F32x4, -math.inf_f32), 0));
try expect(all(isNan(floor(splat(F32x4, math.nan_f32))), 0));
try expect(all(isNan(floor(splat(F32x4, -math.nan_f32))), 0));
try expect(all(isNan(floor(splat(F32x4, math.qnan_f32))), 0));
try expect(all(isNan(floor(splat(F32x4, -math.qnan_f32))), 0));
}
{
var v = floor(F32x16{ 1.1, -1.1, -1.5, 1.5, 2.1, 2.8, 2.9, 4.1, 5.8, 6.1, 7.9, 8.9, 10.1, 11.2, 12.7, 13.1 });
try expect(approxEqAbs(
v,
F32x16{ 1.0, -2.0, -2.0, 1.0, 2.0, 2.0, 2.0, 4.0, 5.0, 6.0, 7.0, 8.0, 10.0, 11.0, 12.0, 13.0 },
0.0,
));
}
var v = floor(F32x4{ 1.5, -1.5, -1.7, -2.1 });
try expect(approxEqAbs(v, F32x4{ 1.0, -2.0, -2.0, -3.0 }, 0.0));
v = floor(F32x4{ -10_000_002.1, -math.inf_f32, 10_000_001.5, math.inf_f32 });
try expect(approxEqAbs(v, F32x4{ -10_000_002.1, -math.inf_f32, 10_000_001.5, math.inf_f32 }, 0.0));
v = floor(F32x4{ -math.qnan_f32, math.qnan_f32, math.nan_f32, -math.inf_f32 });
try expect(math.isNan(v[0]));
try expect(math.isNan(v[1]));
try expect(math.isNan(v[2]));
try expect(v[3] == -math.inf_f32);
v = floor(F32x4{ 1000.5001, -201.499, -10000.99, 100.75001 });
try expect(approxEqAbs(v, F32x4{ 1000.0, -202.0, -10001.0, 100.0 }, 0.0));
v = floor(F32x4{ -7_388_609.5, 7_388_609.1, 8_388_109.5, -8_388_509.5 });
try expect(approxEqAbs(v, F32x4{ -7_388_610.0, 7_388_609.0, 8_388_109.0, -8_388_510.0 }, 0.0));
var f: f32 = -100.0;
var i: u32 = 0;
while (i < 100) : (i += 1) {
const vr = floor(splat(F32x4, f));
const fr = @floor(splat(F32x4, f));
const vr8 = floor(splat(F32x8, f));
const fr8 = @floor(splat(F32x8, f));
const vr16 = floor(splat(F32x16, f));
const fr16 = @floor(splat(F32x16, f));
try expect(approxEqAbs(vr, fr, 0.0));
try expect(approxEqAbs(vr8, fr8, 0.0));
try expect(approxEqAbs(vr16, fr16, 0.0));
f += 0.12345 * @intToFloat(f32, i);
}
}
pub fn ceil(v: anytype) @TypeOf(v) {
const T = @TypeOf(v);
if (cpu_arch == .x86_64 and has_avx) {
if (T == F32x4) {
return asm ("vroundps $2, %%xmm0, %%xmm0"
: [ret] "={xmm0}" (-> T),
: [v] "{xmm0}" (v),
);
} else if (T == F32x8) {
return asm ("vroundps $2, %%ymm0, %%ymm0"
: [ret] "={ymm0}" (-> T),
: [v] "{ymm0}" (v),
);
} else if (T == F32x16 and has_avx512f) {
return asm ("vrndscaleps $2, %%zmm0, %%zmm0"
: [ret] "={zmm0}" (-> T),
: [v] "{zmm0}" (v),
);
} else if (T == F32x16 and !has_avx512f) {
const arr: [16]f32 = v;
var ymm0 = @as(F32x8, arr[0..8].*);
var ymm1 = @as(F32x8, arr[8..16].*);
ymm0 = asm ("vroundps $2, %%ymm0, %%ymm0"
: [ret] "={ymm0}" (-> F32x8),
: [v] "{ymm0}" (ymm0),
);
ymm1 = asm ("vroundps $2, %%ymm1, %%ymm1"
: [ret] "={ymm1}" (-> F32x8),
: [v] "{ymm1}" (ymm1),
);
return @shuffle(f32, ymm0, ymm1, [16]i32{ 0, 1, 2, 3, 4, 5, 6, 7, -1, -2, -3, -4, -5, -6, -7, -8 });
}
} else {
const mask = abs(v) < splatNoFraction(T);
var result = floatToIntAndBack(v);
const smaller_mask = result < v;
const smaller = select(smaller_mask, splat(T, -1.0), splat(T, 0.0));
result = result - smaller;
return select(mask, result, v);
}
}
test "zmath.ceil" {
{
try expect(all(ceil(splat(F32x4, math.inf_f32)) == splat(F32x4, math.inf_f32), 0));
try expect(all(ceil(splat(F32x4, -math.inf_f32)) == splat(F32x4, -math.inf_f32), 0));
try expect(all(isNan(ceil(splat(F32x4, math.nan_f32))), 0));
try expect(all(isNan(ceil(splat(F32x4, -math.nan_f32))), 0));
try expect(all(isNan(ceil(splat(F32x4, math.qnan_f32))), 0));
try expect(all(isNan(ceil(splat(F32x4, -math.qnan_f32))), 0));
}
{
var v = ceil(F32x16{ 1.1, -1.1, -1.5, 1.5, 2.1, 2.8, 2.9, 4.1, 5.8, 6.1, 7.9, 8.9, 10.1, 11.2, 12.7, 13.1 });
try expect(approxEqAbs(
v,
F32x16{ 2.0, -1.0, -1.0, 2.0, 3.0, 3.0, 3.0, 5.0, 6.0, 7.0, 8.0, 9.0, 11.0, 12.0, 13.0, 14.0 },
0.0,
));
}
var v = ceil(F32x4{ 1.5, -1.5, -1.7, -2.1 });
try expect(approxEqAbs(v, F32x4{ 2.0, -1.0, -1.0, -2.0 }, 0.0));
v = ceil(F32x4{ -10_000_002.1, -math.inf_f32, 10_000_001.5, math.inf_f32 });
try expect(approxEqAbs(v, F32x4{ -10_000_002.1, -math.inf_f32, 10_000_001.5, math.inf_f32 }, 0.0));
v = ceil(F32x4{ -math.qnan_f32, math.qnan_f32, math.nan_f32, -math.inf_f32 });
try expect(math.isNan(v[0]));
try expect(math.isNan(v[1]));
try expect(math.isNan(v[2]));
try expect(v[3] == -math.inf_f32);
v = ceil(F32x4{ 1000.5001, -201.499, -10000.99, 100.75001 });
try expect(approxEqAbs(v, F32x4{ 1001.0, -201.0, -10000.0, 101.0 }, 0.0));
v = ceil(F32x4{ -1_388_609.5, 1_388_609.1, 1_388_109.9, -1_388_509.9 });
try expect(approxEqAbs(v, F32x4{ -1_388_609.0, 1_388_610.0, 1_388_110.0, -1_388_509.0 }, 0.0));
var f: f32 = -100.0;
var i: u32 = 0;
while (i < 100) : (i += 1) {
const vr = ceil(splat(F32x4, f));
const fr = @ceil(splat(F32x4, f));
const vr8 = ceil(splat(F32x8, f));
const fr8 = @ceil(splat(F32x8, f));
const vr16 = ceil(splat(F32x16, f));
const fr16 = @ceil(splat(F32x16, f));
try expect(approxEqAbs(vr, fr, 0.0));
try expect(approxEqAbs(vr8, fr8, 0.0));
try expect(approxEqAbs(vr16, fr16, 0.0));
f += 0.12345 * @intToFloat(f32, i);
}
}
pub inline fn clamp(v: anytype, vmin: anytype, vmax: anytype) @TypeOf(v, vmin, vmax) {
var result = max(vmin, v);
result = min(vmax, result);
return result;
}
test "zmath.clamp" {
{
const v0 = f32x4(-1.0, 0.2, 1.1, -0.3);
const v = clamp(v0, splat(F32x4, -0.5), splat(F32x4, 0.5));
try expect(approxEqAbs(v, f32x4(-0.5, 0.2, 0.5, -0.3), 0.0001));
}
{
const v0 = f32x8(-2.0, 0.25, -0.25, 100.0, -1.0, 0.2, 1.1, -0.3);
const v = clamp(v0, splat(F32x8, -0.5), splat(F32x8, 0.5));
try expect(approxEqAbs(v, f32x8(-0.5, 0.25, -0.25, 0.5, -0.5, 0.2, 0.5, -0.3), 0.0001));
}
{
const v0 = f32x4(-math.inf_f32, math.inf_f32, math.nan_f32, math.qnan_f32);
const v = clamp(v0, f32x4(-100.0, 0.0, -100.0, 0.0), f32x4(0.0, 100.0, 0.0, 100.0));
try expect(approxEqAbs(v, f32x4(-100.0, 100.0, -100.0, 0.0), 0.0001));
}
{
const v0 = f32x4(math.inf_f32, math.inf_f32, -math.nan_f32, -math.qnan_f32);
const v = clamp(v0, splat(F32x4, -1.0), splat(F32x4, 1.0));
try expect(approxEqAbs(v, f32x4(1.0, 1.0, -1.0, -1.0), 0.0001));
}
}
pub inline fn clampFast(v: anytype, vmin: anytype, vmax: anytype) @TypeOf(v, vmin, vmax) {
var result = maxFast(vmin, v);
result = minFast(vmax, result);
return result;
}
test "zmath.clampFast" {
{
const v0 = f32x4(-1.0, 0.2, 1.1, -0.3);
const v = clampFast(v0, splat(F32x4, -0.5), splat(F32x4, 0.5));
try expect(approxEqAbs(v, f32x4(-0.5, 0.2, 0.5, -0.3), 0.0001));
}
}
pub inline fn saturate(v: anytype) @TypeOf(v) {
const T = @TypeOf(v);
var result = max(v, splat(T, 0.0));
result = min(result, splat(T, 1.0));
return result;
}
test "zmath.saturate" {
{
const v0 = f32x4(-1.0, 0.2, 1.1, -0.3);
const v = saturate(v0);
try expect(approxEqAbs(v, f32x4(0.0, 0.2, 1.0, 0.0), 0.0001));
}
{
const v0 = f32x8(0.0, 0.0, 2.0, -2.0, -1.0, 0.2, 1.1, -0.3);
const v = saturate(v0);
try expect(approxEqAbs(v, f32x8(0.0, 0.0, 1.0, 0.0, 0.0, 0.2, 1.0, 0.0), 0.0001));
}
{
const v0 = f32x4(-math.inf_f32, math.inf_f32, math.nan_f32, math.qnan_f32);
const v = saturate(v0);
try expect(approxEqAbs(v, f32x4(0.0, 1.0, 0.0, 0.0), 0.0001));
}
{
const v0 = f32x4(math.inf_f32, math.inf_f32, -math.nan_f32, -math.qnan_f32);
const v = saturate(v0);
try expect(approxEqAbs(v, f32x4(1.0, 1.0, 0.0, 0.0), 0.0001));
}
}
pub inline fn saturateFast(v: anytype) @TypeOf(v) {
const T = @TypeOf(v);
var result = maxFast(v, splat(T, 0.0));
result = minFast(result, splat(T, 1.0));
return result;
}
test "zmath.saturateFast" {
{
const v0 = f32x4(-1.0, 0.2, 1.1, -0.3);
const v = saturateFast(v0);
try expect(approxEqAbs(v, f32x4(0.0, 0.2, 1.0, 0.0), 0.0001));
}
{
const v0 = f32x8(0.0, 0.0, 2.0, -2.0, -1.0, 0.2, 1.1, -0.3);
const v = saturateFast(v0);
try expect(approxEqAbs(v, f32x8(0.0, 0.0, 1.0, 0.0, 0.0, 0.2, 1.0, 0.0), 0.0001));
}
{
const v0 = f32x4(-math.inf_f32, math.inf_f32, math.nan_f32, math.qnan_f32);
const v = saturateFast(v0);
try expect(approxEqAbs(v, f32x4(0.0, 1.0, 0.0, 0.0), 0.0001));
}
{
const v0 = f32x4(math.inf_f32, math.inf_f32, -math.nan_f32, -math.qnan_f32);
const v = saturateFast(v0);
try expect(approxEqAbs(v, f32x4(1.0, 1.0, 0.0, 0.0), 0.0001));
}
}
pub inline fn sqrt(v: anytype) @TypeOf(v) {
return @sqrt(v); // sqrtps
}
pub inline fn abs(v: anytype) @TypeOf(v) {
return @fabs(v); // load, andps
}
pub inline fn select(mask: anytype, v0: anytype, v1: anytype) @TypeOf(v0, v1) {
return @select(f32, mask, v0, v1);
}
pub inline fn lerp(v0: anytype, v1: anytype, t: f32) @TypeOf(v0, v1) {
const T = @TypeOf(v0, v1);
return v0 + (v1 - v0) * splat(T, t); // subps, shufps, addps, mulps
}
pub inline fn lerpV(v0: anytype, v1: anytype, t: anytype) @TypeOf(v0, v1, t) {
return v0 + (v1 - v0) * t; // subps, addps, mulps
}
pub const F32x4Component = enum { x, y, z, w };
pub inline fn swizzle(
v: F32x4,
comptime x: F32x4Component,
comptime y: F32x4Component,
comptime z: F32x4Component,
comptime w: F32x4Component,
) F32x4 {
return @shuffle(f32, v, undefined, [4]i32{ @enumToInt(x), @enumToInt(y), @enumToInt(z), @enumToInt(w) });
}
pub inline fn mod(v0: anytype, v1: anytype) @TypeOf(v0, v1) {
// vdivps, vroundps, vmulps, vsubps
return v0 - v1 * trunc(v0 / v1);
}
test "zmath.mod" {
try expect(approxEqAbs(mod(splat(F32x4, 3.1), splat(F32x4, 1.7)), splat(F32x4, 1.4), 0.0005));
try expect(approxEqAbs(mod(splat(F32x4, -3.0), splat(F32x4, 2.0)), splat(F32x4, -1.0), 0.0005));
try expect(approxEqAbs(mod(splat(F32x4, -3.0), splat(F32x4, -2.0)), splat(F32x4, -1.0), 0.0005));
try expect(approxEqAbs(mod(splat(F32x4, 3.0), splat(F32x4, -2.0)), splat(F32x4, 1.0), 0.0005));
try expect(all(isNan(mod(splat(F32x4, math.inf_f32), splat(F32x4, 1.0))), 0));
try expect(all(isNan(mod(splat(F32x4, -math.inf_f32), splat(F32x4, 123.456))), 0));
try expect(all(isNan(mod(splat(F32x4, math.nan_f32), splat(F32x4, 123.456))), 0));
try expect(all(isNan(mod(splat(F32x4, math.qnan_f32), splat(F32x4, 123.456))), 0));
try expect(all(isNan(mod(splat(F32x4, -math.qnan_f32), splat(F32x4, 123.456))), 0));
try expect(all(isNan(mod(splat(F32x4, 123.456), splat(F32x4, math.inf_f32))), 0));
try expect(all(isNan(mod(splat(F32x4, 123.456), splat(F32x4, -math.inf_f32))), 0));
try expect(all(isNan(mod(splat(F32x4, 123.456), splat(F32x4, math.nan_f32))), 0));
try expect(all(isNan(mod(splat(F32x4, math.inf_f32), splat(F32x4, math.inf_f32))), 0));
try expect(all(isNan(mod(splat(F32x4, math.inf_f32), splat(F32x4, math.nan_f32))), 0));
}
pub fn modAngle(v: anytype) @TypeOf(v) {
const T = @TypeOf(v);
return switch (T) {
f32 => modAngle32(v),
F32x4, F32x8, F32x16 => modAngle32xN(v),
else => @compileError("zmath.modAngle() not implemented for " ++ @typeName(T)),
};
}
pub inline fn modAngle32xN(v: anytype) @TypeOf(v) {
const T = @TypeOf(v);
return v - splat(T, math.tau) * round(v * splat(T, 1.0 / math.tau)); // 2 x vmulps, 2 x load, vroundps, vaddps
}
test "zmath.modAngle" {
try expect(approxEqAbs(modAngle(splat(F32x4, math.tau)), splat(F32x4, 0.0), 0.0005));
try expect(approxEqAbs(modAngle(splat(F32x4, 0.0)), splat(F32x4, 0.0), 0.0005));
try expect(approxEqAbs(modAngle(splat(F32x4, math.pi)), splat(F32x4, math.pi), 0.0005));
try expect(approxEqAbs(modAngle(splat(F32x4, 11 * math.pi)), splat(F32x4, math.pi), 0.0005));
try expect(approxEqAbs(modAngle(splat(F32x4, 3.5 * math.pi)), splat(F32x4, -0.5 * math.pi), 0.0005));
try expect(approxEqAbs(modAngle(splat(F32x4, 2.5 * math.pi)), splat(F32x4, 0.5 * math.pi), 0.0005));
}
pub inline fn mulAdd(v0: anytype, v1: anytype, v2: anytype) @TypeOf(v0, v1, v2) {
const T = @TypeOf(v0, v1, v2);
if (cpu_arch == .x86_64 and has_avx and has_fma) {
return @mulAdd(T, v0, v1, v2);
} else {
// NOTE(mziulek): On .x86_64 without HW fma instructions @mulAdd maps to really slow code!
return v0 * v1 + v2;
}
}
fn sin32xN(v: anytype) @TypeOf(v) {
// 11-degree minimax approximation
const T = @TypeOf(v);
var x = modAngle(v);
const sign = andInt(x, splatNegativeZero(T));
const c = orInt(sign, splat(T, math.pi));
const absx = andNotInt(sign, x);
const rflx = c - x;
const comp = absx <= splat(T, 0.5 * math.pi);
x = select(comp, x, rflx);
const x2 = x * x;
var result = mulAdd(splat(T, -2.3889859e-08), x2, splat(T, 2.7525562e-06));
result = mulAdd(result, x2, splat(T, -0.00019840874));
result = mulAdd(result, x2, splat(T, 0.0083333310));
result = mulAdd(result, x2, splat(T, -0.16666667));
result = mulAdd(result, x2, splat(T, 1.0));
return x * result;
}
test "zmath.sin" {
const epsilon = 0.0001;
try expect(approxEqAbs(sin(splat(F32x4, 0.5 * math.pi)), splat(F32x4, 1.0), epsilon));
try expect(approxEqAbs(sin(splat(F32x4, 0.0)), splat(F32x4, 0.0), epsilon));
try expect(approxEqAbs(sin(splat(F32x4, -0.0)), splat(F32x4, -0.0), epsilon));
try expect(approxEqAbs(sin(splat(F32x4, 89.123)), splat(F32x4, 0.916166), epsilon));
try expect(approxEqAbs(sin(splat(F32x8, 89.123)), splat(F32x8, 0.916166), epsilon));
try expect(approxEqAbs(sin(splat(F32x16, 89.123)), splat(F32x16, 0.916166), epsilon));
try expect(all(isNan(sin(splat(F32x4, math.inf_f32))), 0) == true);
try expect(all(isNan(sin(splat(F32x4, -math.inf_f32))), 0) == true);
try expect(all(isNan(sin(splat(F32x4, math.nan_f32))), 0) == true);
try expect(all(isNan(sin(splat(F32x4, math.qnan_f32))), 0) == true);
var f: f32 = -100.0;
var i: u32 = 0;
while (i < 100) : (i += 1) {
const vr = sin(splat(F32x4, f));
const fr = @sin(splat(F32x4, f));
const vr8 = sin(splat(F32x8, f));
const fr8 = @sin(splat(F32x8, f));
const vr16 = sin(splat(F32x16, f));
const fr16 = @sin(splat(F32x16, f));
try expect(approxEqAbs(vr, fr, epsilon));
try expect(approxEqAbs(vr8, fr8, epsilon));
try expect(approxEqAbs(vr16, fr16, epsilon));
f += 0.12345 * @intToFloat(f32, i);
}
}
fn cos32xN(v: anytype) @TypeOf(v) {
// 10-degree minimax approximation
const T = @TypeOf(v);
var x = modAngle(v);
var sign = andInt(x, splatNegativeZero(T));
const c = orInt(sign, splat(T, math.pi));
const absx = andNotInt(sign, x);
const rflx = c - x;
const comp = absx <= splat(T, 0.5 * math.pi);
x = select(comp, x, rflx);
sign = select(comp, splat(T, 1.0), splat(T, -1.0));
const x2 = x * x;
var result = mulAdd(splat(T, -2.6051615e-07), x2, splat(T, 2.4760495e-05));
result = mulAdd(result, x2, splat(T, -0.0013888378));
result = mulAdd(result, x2, splat(T, 0.041666638));
result = mulAdd(result, x2, splat(T, -0.5));
result = mulAdd(result, x2, splat(T, 1.0));
return sign * result;
}
test "zmath.cos" {
const epsilon = 0.0001;
try expect(approxEqAbs(cos(splat(F32x4, 0.5 * math.pi)), splat(F32x4, 0.0), epsilon));
try expect(approxEqAbs(cos(splat(F32x4, 0.0)), splat(F32x4, 1.0), epsilon));
try expect(approxEqAbs(cos(splat(F32x4, -0.0)), splat(F32x4, 1.0), epsilon));
try expect(all(isNan(cos(splat(F32x4, math.inf_f32))), 0) == true);
try expect(all(isNan(cos(splat(F32x4, -math.inf_f32))), 0) == true);
try expect(all(isNan(cos(splat(F32x4, math.nan_f32))), 0) == true);
try expect(all(isNan(cos(splat(F32x4, math.qnan_f32))), 0) == true);
var f: f32 = -100.0;
var i: u32 = 0;
while (i < 100) : (i += 1) {
const vr = cos(splat(F32x4, f));
const fr = @cos(splat(F32x4, f));
const vr8 = cos(splat(F32x8, f));
const fr8 = @cos(splat(F32x8, f));
const vr16 = cos(splat(F32x16, f));
const fr16 = @cos(splat(F32x16, f));
try expect(approxEqAbs(vr, fr, epsilon));
try expect(approxEqAbs(vr8, fr8, epsilon));
try expect(approxEqAbs(vr16, fr16, epsilon));
f += 0.12345 * @intToFloat(f32, i);
}
}
pub fn sin(v: anytype) @TypeOf(v) {
const T = @TypeOf(v);
return switch (T) {
f32 => sin32(v),
F32x4, F32x8, F32x16 => sin32xN(v),
else => @compileError("zmath.sin() not implemented for " ++ @typeName(T)),
};
}
pub fn cos(v: anytype) @TypeOf(v) {
const T = @TypeOf(v);
return switch (T) {
f32 => cos32(v),
F32x4, F32x8, F32x16 => cos32xN(v),
else => @compileError("zmath.cos() not implemented for " ++ @typeName(T)),
};
}
pub fn sincos(v: anytype) [2]@TypeOf(v) {
const T = @TypeOf(v);
return switch (T) {
f32 => sincos32(v),
F32x4, F32x8, F32x16 => sincos32xN(v),
else => @compileError("zmath.sincos() not implemented for " ++ @typeName(T)),
};
}
pub fn asin(v: anytype) @TypeOf(v) {
const T = @TypeOf(v);
return switch (T) {
f32 => asin32(v),
F32x4, F32x8, F32x16 => asin32xN(v),
else => @compileError("zmath.asin() not implemented for " ++ @typeName(T)),
};
}
pub fn acos(v: anytype) @TypeOf(v) {
const T = @TypeOf(v);
return switch (T) {
f32 => acos32(v),
F32x4, F32x8, F32x16 => acos32xN(v),
else => @compileError("zmath.acos() not implemented for " ++ @typeName(T)),
};
}
fn sincos32xN(v: anytype) [2]@TypeOf(v) {
const T = @TypeOf(v);
var x = modAngle(v);
var sign = andInt(x, splatNegativeZero(T));
const c = orInt(sign, splat(T, math.pi));
const absx = andNotInt(sign, x);
const rflx = c - x;
const comp = absx <= splat(T, 0.5 * math.pi);
x = select(comp, x, rflx);
sign = select(comp, splat(T, 1.0), splat(T, -1.0));
const x2 = x * x;
var sresult = mulAdd(splat(T, -2.3889859e-08), x2, splat(T, 2.7525562e-06));
sresult = mulAdd(sresult, x2, splat(T, -0.00019840874));
sresult = mulAdd(sresult, x2, splat(T, 0.0083333310));
sresult = mulAdd(sresult, x2, splat(T, -0.16666667));
sresult = x * mulAdd(sresult, x2, splat(T, 1.0));
var cresult = mulAdd(splat(T, -2.6051615e-07), x2, splat(T, 2.4760495e-05));
cresult = mulAdd(cresult, x2, splat(T, -0.0013888378));
cresult = mulAdd(cresult, x2, splat(T, 0.041666638));
cresult = mulAdd(cresult, x2, splat(T, -0.5));
cresult = sign * mulAdd(cresult, x2, splat(T, 1.0));
return .{ sresult, cresult };
}
test "zmath.sincos32xN" {
const epsilon = 0.0001;
var f: f32 = -100.0;
var i: u32 = 0;
while (i < 100) : (i += 1) {
const sc = sincos(splat(F32x4, f));
const sc8 = sincos(splat(F32x8, f));
const sc16 = sincos(splat(F32x16, f));
const s4 = @sin(splat(F32x4, f));
const s8 = @sin(splat(F32x8, f));
const s16 = @sin(splat(F32x16, f));
const c4 = @cos(splat(F32x4, f));
const c8 = @cos(splat(F32x8, f));
const c16 = @cos(splat(F32x16, f));
try expect(approxEqAbs(sc[0], s4, epsilon));
try expect(approxEqAbs(sc8[0], s8, epsilon));
try expect(approxEqAbs(sc16[0], s16, epsilon));
try expect(approxEqAbs(sc[1], c4, epsilon));
try expect(approxEqAbs(sc8[1], c8, epsilon));
try expect(approxEqAbs(sc16[1], c16, epsilon));
f += 0.12345 * @intToFloat(f32, i);
}
}
fn asin32xN(v: anytype) @TypeOf(v) {
// 7-degree minimax approximation
const T = @TypeOf(v);
const x = abs(v);
const root = sqrt(maxFast(splat(T, 0.0), splat(T, 1.0) - x));
var t0 = mulAdd(splat(T, -0.0012624911), x, splat(T, 0.0066700901));
t0 = mulAdd(t0, x, splat(T, -0.0170881256));
t0 = mulAdd(t0, x, splat(T, 0.0308918810));
t0 = mulAdd(t0, x, splat(T, -0.0501743046));
t0 = mulAdd(t0, x, splat(T, 0.0889789874));
t0 = mulAdd(t0, x, splat(T, -0.2145988016));
t0 = root * mulAdd(t0, x, splat(T, 1.5707963050));
const t1 = splat(T, math.pi) - t0;
return splat(T, 0.5 * math.pi) - select(v >= splat(T, 0.0), t0, t1);
}
fn acos32xN(v: anytype) @TypeOf(v) {
// 7-degree minimax approximation
const T = @TypeOf(v);
const x = abs(v);
const root = sqrt(maxFast(splat(T, 0.0), splat(T, 1.0) - x));
var t0 = mulAdd(splat(T, -0.0012624911), x, splat(T, 0.0066700901));
t0 = mulAdd(t0, x, splat(T, -0.0170881256));
t0 = mulAdd(t0, x, splat(T, 0.0308918810));
t0 = mulAdd(t0, x, splat(T, -0.0501743046));
t0 = mulAdd(t0, x, splat(T, 0.0889789874));
t0 = mulAdd(t0, x, splat(T, -0.2145988016));
t0 = root * mulAdd(t0, x, splat(T, 1.5707963050));
const t1 = splat(T, math.pi) - t0;
return select(v >= splat(T, 0.0), t0, t1);
}
pub fn atan(v: anytype) @TypeOf(v) {
// 17-degree minimax approximation
const T = @TypeOf(v);
const vabs = abs(v);
const vinv = splat(T, 1.0) / v;
var sign = select(v > splat(T, 1.0), splat(T, 1.0), splat(T, -1.0));
const comp = vabs <= splat(T, 1.0);
sign = select(comp, splat(T, 0.0), sign);
const x = select(comp, v, vinv);
const x2 = x * x;
var result = mulAdd(splat(T, 0.0028662257), x2, splat(T, -0.0161657367));
result = mulAdd(result, x2, splat(T, 0.0429096138));
result = mulAdd(result, x2, splat(T, -0.0752896400));
result = mulAdd(result, x2, splat(T, 0.1065626393));
result = mulAdd(result, x2, splat(T, -0.1420889944));
result = mulAdd(result, x2, splat(T, 0.1999355085));
result = mulAdd(result, x2, splat(T, -0.3333314528));
result = x * mulAdd(result, x2, splat(T, 1.0));
const result1 = sign * splat(T, 0.5 * math.pi) - result;
return select(sign == splat(T, 0.0), result, result1);
}
test "zmath.atan" {
const epsilon = 0.0001;
{
const v = f32x4(0.25, 0.5, 1.0, 1.25);
const e = f32x4(math.atan(v[0]), math.atan(v[1]), math.atan(v[2]), math.atan(v[3]));
try expect(approxEqAbs(e, atan(v), epsilon));
}
{
const v = f32x8(-0.25, 0.5, -1.0, 1.25, 100.0, -200.0, 300.0, 400.0);
// zig fmt: off
const e = f32x8(
math.atan(v[0]), math.atan(v[1]), math.atan(v[2]), math.atan(v[3]),
math.atan(v[4]), math.atan(v[5]), math.atan(v[6]), math.atan(v[7]),
);
// zig fmt: on
try expect(approxEqAbs(e, atan(v), epsilon));
}
{
// zig fmt: off
const v = f32x16(
-0.25, 0.5, -1.0, 0.0, 0.1, -0.2, 30.0, 400.0,
-0.25, 0.5, -1.0, -0.0, -0.05, -0.125, 0.0625, 4000.0
);
const e = f32x16(
math.atan(v[0]), math.atan(v[1]), math.atan(v[2]), math.atan(v[3]),
math.atan(v[4]), math.atan(v[5]), math.atan(v[6]), math.atan(v[7]),
math.atan(v[8]), math.atan(v[9]), math.atan(v[10]), math.atan(v[11]),
math.atan(v[12]), math.atan(v[13]), math.atan(v[14]), math.atan(v[15]),
);
// zig fmt: on
try expect(approxEqAbs(e, atan(v), epsilon));
}
{
try expect(approxEqAbs(atan(splat(F32x4, math.inf_f32)), splat(F32x4, 0.5 * math.pi), epsilon));
try expect(approxEqAbs(atan(splat(F32x4, -math.inf_f32)), splat(F32x4, -0.5 * math.pi), epsilon));
try expect(all(isNan(atan(splat(F32x4, math.nan_f32))), 0) == true);
try expect(all(isNan(atan(splat(F32x4, -math.nan_f32))), 0) == true);
}
}
pub fn atan2(vy: anytype, vx: anytype) @TypeOf(vx, vy) {
const T = @TypeOf(vx, vy);
const Tu = @Vector(veclen(T), u32);
const vx_is_positive =
(@bitCast(Tu, vx) & @splat(veclen(T), @as(u32, 0x8000_0000))) == @splat(veclen(T), @as(u32, 0));
const vy_sign = andInt(vy, splatNegativeZero(T));
const c0_25pi = orInt(vy_sign, splat(T, 0.25 * math.pi));
const c0_50pi = orInt(vy_sign, splat(T, 0.50 * math.pi));
const c0_75pi = orInt(vy_sign, splat(T, 0.75 * math.pi));
const c1_00pi = orInt(vy_sign, splat(T, 1.00 * math.pi));
var r1 = select(vx_is_positive, vy_sign, c1_00pi);
var r2 = select(vx == splat(T, 0.0), c0_50pi, splatInt(T, 0xffff_ffff));
const r3 = select(vy == splat(T, 0.0), r1, r2);
const r4 = select(vx_is_positive, c0_25pi, c0_75pi);
const r5 = select(isInf(vx), r4, c0_50pi);
const result = select(isInf(vy), r5, r3);
const result_valid = @bitCast(Tu, result) == @splat(veclen(T), @as(u32, 0xffff_ffff));
const v = vy / vx;
const r0 = atan(v);
r1 = select(vx_is_positive, splatNegativeZero(T), c1_00pi);
r2 = r0 + r1;
return select(result_valid, r2, result);
}
test "zmath.atan2" {
// From DirectXMath XMVectorATan2():
//
// Return the inverse tangent of Y / X in the range of -Pi to Pi with the following exceptions:
// Y == 0 and X is Negative -> Pi with the sign of Y
// y == 0 and x is positive -> 0 with the sign of y
// Y != 0 and X == 0 -> Pi / 2 with the sign of Y
// Y != 0 and X is Negative -> atan(y/x) + (PI with the sign of Y)
// X == -Infinity and Finite Y -> Pi with the sign of Y
// X == +Infinity and Finite Y -> 0 with the sign of Y
// Y == Infinity and X is Finite -> Pi / 2 with the sign of Y
// Y == Infinity and X == -Infinity -> 3Pi / 4 with the sign of Y
// Y == Infinity and X == +Infinity -> Pi / 4 with the sign of Y
const epsilon = 0.0001;
try expect(approxEqAbs(atan2(splat(F32x4, 0.0), splat(F32x4, -1.0)), splat(F32x4, math.pi), epsilon));
try expect(approxEqAbs(atan2(splat(F32x4, -0.0), splat(F32x4, -1.0)), splat(F32x4, -math.pi), epsilon));
try expect(approxEqAbs(atan2(splat(F32x4, 1.0), splat(F32x4, 0.0)), splat(F32x4, 0.5 * math.pi), epsilon));
try expect(approxEqAbs(atan2(splat(F32x4, -1.0), splat(F32x4, 0.0)), splat(F32x4, -0.5 * math.pi), epsilon));
try expect(approxEqAbs(
atan2(splat(F32x4, 1.0), splat(F32x4, -1.0)),
splat(F32x4, math.atan(@as(f32, -1.0)) + math.pi),
epsilon,
));
try expect(approxEqAbs(
atan2(splat(F32x4, -10.0), splat(F32x4, -2.0)),
splat(F32x4, math.atan(@as(f32, 5.0)) - math.pi),
epsilon,
));
try expect(approxEqAbs(atan2(splat(F32x4, 1.0), splat(F32x4, -math.inf_f32)), splat(F32x4, math.pi), epsilon));
try expect(approxEqAbs(atan2(splat(F32x4, -1.0), splat(F32x4, -math.inf_f32)), splat(F32x4, -math.pi), epsilon));
try expect(approxEqAbs(atan2(splat(F32x4, 1.0), splat(F32x4, math.inf_f32)), splat(F32x4, 0.0), epsilon));
try expect(approxEqAbs(atan2(splat(F32x4, -1.0), splat(F32x4, math.inf_f32)), splat(F32x4, -0.0), epsilon));
try expect(approxEqAbs(
atan2(splat(F32x4, math.inf_f32), splat(F32x4, 2.0)),
splat(F32x4, 0.5 * math.pi),
epsilon,
));
try expect(approxEqAbs(
atan2(splat(F32x4, -math.inf_f32), splat(F32x4, 2.0)),
splat(F32x4, -0.5 * math.pi),
epsilon,
));
try expect(approxEqAbs(
atan2(splat(F32x4, math.inf_f32), splat(F32x4, -math.inf_f32)),
splat(F32x4, 0.75 * math.pi),
epsilon,
));
try expect(approxEqAbs(
atan2(splat(F32x4, -math.inf_f32), splat(F32x4, -math.inf_f32)),
splat(F32x4, -0.75 * math.pi),
epsilon,
));
try expect(approxEqAbs(
atan2(splat(F32x4, math.inf_f32), splat(F32x4, math.inf_f32)),
splat(F32x4, 0.25 * math.pi),
epsilon,
));
try expect(approxEqAbs(
atan2(splat(F32x4, -math.inf_f32), splat(F32x4, math.inf_f32)),
splat(F32x4, -0.25 * math.pi),
epsilon,
));
try expect(approxEqAbs(
atan2(
f32x8(0.0, -math.inf_f32, -0.0, 2.0, math.inf_f32, math.inf_f32, 1.0, -math.inf_f32),
f32x8(-2.0, math.inf_f32, 1.0, 0.0, 10.0, -math.inf_f32, 1.0, -math.inf_f32),
),
f32x8(
math.pi,
-0.25 * math.pi,
-0.0,
0.5 * math.pi,
0.5 * math.pi,
0.75 * math.pi,
math.atan(@as(f32, 1.0)),
-0.75 * math.pi,
),
epsilon,
));
try expect(approxEqAbs(atan2(splat(F32x4, 0.0), splat(F32x4, 0.0)), splat(F32x4, 0.0), epsilon));
try expect(approxEqAbs(atan2(splat(F32x4, -0.0), splat(F32x4, 0.0)), splat(F32x4, 0.0), epsilon));
try expect(all(isNan(atan2(splat(F32x4, 1.0), splat(F32x4, math.nan_f32))), 0) == true);
try expect(all(isNan(atan2(splat(F32x4, -1.0), splat(F32x4, math.nan_f32))), 0) == true);
try expect(all(isNan(atan2(splat(F32x4, math.nan_f32), splat(F32x4, -1.0))), 0) == true);
try expect(all(isNan(atan2(splat(F32x4, -math.nan_f32), splat(F32x4, 1.0))), 0) == true);
}
// ------------------------------------------------------------------------------
//
// 3. 2D, 3D, 4D vector functions
//
// ------------------------------------------------------------------------------
pub inline fn dot2(v0: Vec, v1: Vec) F32x4 {
var xmm0 = v0 * v1; // | x0*x1 | y0*y1 | -- | -- |
var xmm1 = swizzle(xmm0, .y, .x, .x, .x); // | y0*y1 | -- | -- | -- |
xmm0 = F32x4{ xmm0[0] + xmm1[0], xmm0[1], xmm0[2], xmm0[3] }; // | x0*x1 + y0*y1 | -- | -- | -- |
return swizzle(xmm0, .x, .x, .x, .x);
}
test "zmath.dot2" {
const v0 = F32x4{ -1.0, 2.0, 300.0, -2.0 };
const v1 = F32x4{ 4.0, 5.0, 600.0, 2.0 };
var v = dot2(v0, v1);
try expect(approxEqAbs(v, splat(F32x4, 6.0), 0.0001));
}
pub inline fn dot3(v0: Vec, v1: Vec) F32x4 {
var dot = v0 * v1;
var temp = swizzle(dot, .y, .z, .y, .z);
dot = F32x4{ dot[0] + temp[0], dot[1], dot[2], dot[2] }; // addss
temp = swizzle(temp, .y, .y, .y, .y);
dot = F32x4{ dot[0] + temp[0], dot[1], dot[2], dot[2] }; // addss
return swizzle(dot, .x, .x, .x, .x);
}
test "zmath.dot3" {
const v0 = F32x4{ -1.0, 2.0, 3.0, 1.0 };
const v1 = F32x4{ 4.0, 5.0, 6.0, 1.0 };
var v = dot3(v0, v1);
try expect(approxEqAbs(v, splat(F32x4, 24.0), 0.0001));
}
pub inline fn dot4(v0: Vec, v1: Vec) F32x4 {
var xmm0 = v0 * v1; // | x0*x1 | y0*y1 | z0*z1 | w0*w1 |
var xmm1 = swizzle(xmm0, .y, .x, .w, .x); // | y0*y1 | -- | w0*w1 | -- |
xmm1 = xmm0 + xmm1; // | x0*x1 + y0*y1 | -- | z0*z1 + w0*w1 | -- |
xmm0 = swizzle(xmm1, .z, .x, .x, .x); // | z0*z1 + w0*w1 | -- | -- | -- |
xmm0 = F32x4{ xmm0[0] + xmm1[0], xmm0[1], xmm0[2], xmm0[2] }; // addss
return swizzle(xmm0, .x, .x, .x, .x);
}
test "zmath.dot4" {
const v0 = F32x4{ -1.0, 2.0, 3.0, -2.0 };
const v1 = F32x4{ 4.0, 5.0, 6.0, 2.0 };
var v = dot4(v0, v1);
try expect(approxEqAbs(v, splat(F32x4, 20.0), 0.0001));
}
pub inline fn cross3(v0: Vec, v1: Vec) Vec {
var xmm0 = swizzle(v0, .y, .z, .x, .w);
var xmm1 = swizzle(v1, .z, .x, .y, .w);
var result = xmm0 * xmm1;
xmm0 = swizzle(xmm0, .y, .z, .x, .w);
xmm1 = swizzle(xmm1, .z, .x, .y, .w);
result = result - xmm0 * xmm1;
return @bitCast(F32x4, @bitCast(U32x4, result) & u32x4_mask3);
}
test "zmath.cross3" {
{
const v0 = F32x4{ 1.0, 0.0, 0.0, 1.0 };
const v1 = F32x4{ 0.0, 1.0, 0.0, 1.0 };
var v = cross3(v0, v1);
try expect(approxEqAbs(v, F32x4{ 0.0, 0.0, 1.0, 0.0 }, 0.0001));
}
{
const v0 = F32x4{ 1.0, 0.0, 0.0, 1.0 };
const v1 = F32x4{ 0.0, -1.0, 0.0, 1.0 };
var v = cross3(v0, v1);
try expect(approxEqAbs(v, F32x4{ 0.0, 0.0, -1.0, 0.0 }, 0.0001));
}
{
const v0 = F32x4{ -3.0, 0, -2.0, 1.0 };
const v1 = F32x4{ 5.0, -1.0, 2.0, 1.0 };
var v = cross3(v0, v1);
try expect(approxEqAbs(v, F32x4{ -2.0, -4.0, 3.0, 0.0 }, 0.0001));
}
}
pub inline fn lengthSq2(v: Vec) F32x4 {
return dot2(v, v);
}
pub inline fn lengthSq3(v: Vec) F32x4 {
return dot3(v, v);
}
pub inline fn lengthSq4(v: Vec) F32x4 {
return dot4(v, v);
}
pub inline fn length2(v: Vec) F32x4 {
return sqrt(dot2(v, v));
}
pub inline fn length3(v: Vec) F32x4 {
return sqrt(dot3(v, v));
}
pub inline fn length4(v: Vec) F32x4 {
return sqrt(dot4(v, v));
}
test "zmath.length3" {
{
var v = length3(F32x4{ 1.0, -2.0, 3.0, 1000.0 });
try expect(approxEqAbs(v, splat(F32x4, math.sqrt(14.0)), 0.001));
}
{
var v = length3(F32x4{ 1.0, math.nan_f32, math.inf_f32, 1000.0 });
try expect(all(isNan(v), 0));
}
{
var v = length3(F32x4{ 1.0, math.inf_f32, 3.0, 1000.0 });
try expect(all(isInf(v), 0));
}
{
var v = length3(F32x4{ 3.0, 2.0, 1.0, math.nan_f32 });
try expect(approxEqAbs(v, splat(F32x4, math.sqrt(14.0)), 0.001));
}
}
pub inline fn normalize2(v: Vec) Vec {
return v * splat(F32x4, 1.0) / sqrt(dot2(v, v));
}
pub inline fn normalize3(v: Vec) Vec {
return v * splat(F32x4, 1.0) / sqrt(dot3(v, v));
}
pub inline fn normalize4(v: Vec) Vec {
return v * splat(F32x4, 1.0) / sqrt(dot4(v, v));
}
test "zmath.normalize3" {
{
const v0 = F32x4{ 1.0, -2.0, 3.0, 1000.0 };
var v = normalize3(v0);
try expect(approxEqAbs(v, v0 * splat(F32x4, 1.0 / math.sqrt(14.0)), 0.0005));
}
{
try expect(any(isNan(normalize3(F32x4{ 1.0, math.inf_f32, 1.0, 1.0 })), 0));
try expect(any(isNan(normalize3(F32x4{ -math.inf_f32, math.inf_f32, 0.0, 0.0 })), 0));
try expect(any(isNan(normalize3(F32x4{ -math.nan_f32, math.qnan_f32, 0.0, 0.0 })), 0));
try expect(any(isNan(normalize3(splat(F32x4, 0.0))), 0));
}
}
test "zmath.normalize4" {
{
const v0 = F32x4{ 1.0, -2.0, 3.0, 10.0 };
var v = normalize4(v0);
try expect(approxEqAbs(v, v0 * splat(F32x4, 1.0 / math.sqrt(114.0)), 0.0005));
}
{
try expect(any(isNan(normalize4(F32x4{ 1.0, math.inf_f32, 1.0, 1.0 })), 0));
try expect(any(isNan(normalize4(F32x4{ -math.inf_f32, math.inf_f32, 0.0, 0.0 })), 0));
try expect(any(isNan(normalize4(F32x4{ -math.nan_f32, math.qnan_f32, 0.0, 0.0 })), 0));
try expect(any(isNan(normalize4(splat(F32x4, 0.0))), 0));
}
}
fn vecMulMat(v: Vec, m: Mat) Vec {
var vx = @shuffle(f32, v, undefined, [4]i32{ 0, 0, 0, 0 });
var vy = @shuffle(f32, v, undefined, [4]i32{ 1, 1, 1, 1 });
var vz = @shuffle(f32, v, undefined, [4]i32{ 2, 2, 2, 2 });
var vw = @shuffle(f32, v, undefined, [4]i32{ 3, 3, 3, 3 });
return vx * m[0] + vy * m[1] + vz * m[2] + vw * m[3];
}
fn matMulVec(m: Mat, v: Vec) Vec {
return .{ dot4(m[0], v)[0], dot4(m[1], v)[0], dot4(m[2], v)[0], dot4(m[3], v)[0] };
}
test "zmath.vecMulMat" {
const m = Mat{
f32x4(1.0, 0.0, 0.0, 0.0),
f32x4(0.0, 1.0, 0.0, 0.0),
f32x4(0.0, 0.0, 1.0, 0.0),
f32x4(2.0, 3.0, 4.0, 1.0),
};
const vm = mul(f32x4(1.0, 2.0, 3.0, 1.0), m);
const mv = mul(m, f32x4(1.0, 2.0, 3.0, 1.0));
const v = mul(transpose(m), f32x4(1.0, 2.0, 3.0, 1.0));
try expect(approxEqAbs(vm, f32x4(3.0, 5.0, 7.0, 1.0), 0.0001));
try expect(approxEqAbs(mv, f32x4(1.0, 2.0, 3.0, 21.0), 0.0001));
try expect(approxEqAbs(v, f32x4(3.0, 5.0, 7.0, 1.0), 0.0001));
}
// ------------------------------------------------------------------------------
//
// 4. Matrix functions
//
// ------------------------------------------------------------------------------
pub fn identity() Mat {
const static = struct {
const identity = Mat{
f32x4(1.0, 0.0, 0.0, 0.0),
f32x4(0.0, 1.0, 0.0, 0.0),
f32x4(0.0, 0.0, 1.0, 0.0),
f32x4(0.0, 0.0, 0.0, 1.0),
};
};
return static.identity;
}
fn mulRetType(comptime Ta: type, comptime Tb: type) type {
if (Ta == Mat and Tb == Mat) {
return Mat;
} else if ((Ta == f32 and Tb == Mat) or (Ta == Mat and Tb == f32)) {
return Mat;
} else if ((Ta == Vec and Tb == Mat) or (Ta == Mat and Tb == Vec)) {
return Vec;
}
@compileError("zmath.mul() not implemented for types: " ++ @typeName(Ta) ++ @typeName(Tb));
}
pub fn mul(a: anytype, b: anytype) mulRetType(@TypeOf(a), @TypeOf(b)) {
const Ta = @TypeOf(a);
const Tb = @TypeOf(b);
if (Ta == Mat and Tb == Mat) {
return mulMat(a, b);
} else if (Ta == f32 and Tb == Mat) {
const va = splat(F32x4, a);
return Mat{ va * b[0], va * b[1], va * b[2], va * b[3] };
} else if (Ta == Mat and Tb == f32) {
const vb = splat(F32x4, b);
return Mat{ a[0] * vb, a[1] * vb, a[2] * vb, a[3] * vb };
} else if (Ta == Vec and Tb == Mat) {
return vecMulMat(a, b);
} else if (Ta == Mat and Tb == Vec) {
return matMulVec(a, b);
} else {
@compileError("zmath.mul() not implemented for types: " ++ @typeName(Ta) ++ ", " ++ @typeName(Tb));
}
}
test "zmath.mul" {
{
const m = Mat{
f32x4(0.1, 0.2, 0.3, 0.4),
f32x4(0.5, 0.6, 0.7, 0.8),
f32x4(0.9, 1.0, 1.1, 1.2),
f32x4(1.3, 1.4, 1.5, 1.6),
};
const ms = mul(@as(f32, 2.0), m);
try expect(approxEqAbs(ms[0], f32x4(0.2, 0.4, 0.6, 0.8), 0.0001));
try expect(approxEqAbs(ms[1], f32x4(1.0, 1.2, 1.4, 1.6), 0.0001));
try expect(approxEqAbs(ms[2], f32x4(1.8, 2.0, 2.2, 2.4), 0.0001));
try expect(approxEqAbs(ms[3], f32x4(2.6, 2.8, 3.0, 3.2), 0.0001));
}
}
fn mulMat(m0: Mat, m1: Mat) Mat {
var result: Mat = undefined;
comptime var row: u32 = 0;
inline while (row < 4) : (row += 1) {
var vx = @shuffle(f32, m0[row], undefined, [4]i32{ 0, 0, 0, 0 });
var vy = @shuffle(f32, m0[row], undefined, [4]i32{ 1, 1, 1, 1 });
var vz = @shuffle(f32, m0[row], undefined, [4]i32{ 2, 2, 2, 2 });
var vw = @shuffle(f32, m0[row], undefined, [4]i32{ 3, 3, 3, 3 });
vx = vx * m1[0];
vy = vy * m1[1];
vz = vz * m1[2];
vw = vw * m1[3];
vx = vx + vz;
vy = vy + vw;
vx = vx + vy;
result[row] = vx;
}
return result;
}
test "zmath.matrix.mul" {
const a = Mat{
f32x4(0.1, 0.2, 0.3, 0.4),
f32x4(0.5, 0.6, 0.7, 0.8),
f32x4(0.9, 1.0, 1.1, 1.2),
f32x4(1.3, 1.4, 1.5, 1.6),
};
const b = Mat{
f32x4(1.7, 1.8, 1.9, 2.0),
f32x4(2.1, 2.2, 2.3, 2.4),
f32x4(2.5, 2.6, 2.7, 2.8),
f32x4(2.9, 3.0, 3.1, 3.2),
};
const c = mul(a, b);
try expect(approxEqAbs(c[0], f32x4(2.5, 2.6, 2.7, 2.8), 0.0001));
try expect(approxEqAbs(c[1], f32x4(6.18, 6.44, 6.7, 6.96), 0.0001));
try expect(approxEqAbs(c[2], f32x4(9.86, 10.28, 10.7, 11.12), 0.0001));
try expect(approxEqAbs(c[3], f32x4(13.54, 14.12, 14.7, 15.28), 0.0001));
}
pub fn transpose(m: Mat) Mat {
const temp1 = @shuffle(f32, m[0], m[1], [4]i32{ 0, 1, ~@as(i32, 0), ~@as(i32, 1) });
const temp3 = @shuffle(f32, m[0], m[1], [4]i32{ 2, 3, ~@as(i32, 2), ~@as(i32, 3) });
const temp2 = @shuffle(f32, m[2], m[3], [4]i32{ 0, 1, ~@as(i32, 0), ~@as(i32, 1) });
const temp4 = @shuffle(f32, m[2], m[3], [4]i32{ 2, 3, ~@as(i32, 2), ~@as(i32, 3) });
return .{
@shuffle(f32, temp1, temp2, [4]i32{ 0, 2, ~@as(i32, 0), ~@as(i32, 2) }),
@shuffle(f32, temp1, temp2, [4]i32{ 1, 3, ~@as(i32, 1), ~@as(i32, 3) }),
@shuffle(f32, temp3, temp4, [4]i32{ 0, 2, ~@as(i32, 0), ~@as(i32, 2) }),
@shuffle(f32, temp3, temp4, [4]i32{ 1, 3, ~@as(i32, 1), ~@as(i32, 3) }),
};
}
test "zmath.matrix.transpose" {
const m = Mat{
f32x4(1.0, 2.0, 3.0, 4.0),
f32x4(5.0, 6.0, 7.0, 8.0),
f32x4(9.0, 10.0, 11.0, 12.0),
f32x4(13.0, 14.0, 15.0, 16.0),
};
const mt = transpose(m);
try expect(approxEqAbs(mt[0], f32x4(1.0, 5.0, 9.0, 13.0), 0.0001));
try expect(approxEqAbs(mt[1], f32x4(2.0, 6.0, 10.0, 14.0), 0.0001));
try expect(approxEqAbs(mt[2], f32x4(3.0, 7.0, 11.0, 15.0), 0.0001));
try expect(approxEqAbs(mt[3], f32x4(4.0, 8.0, 12.0, 16.0), 0.0001));
}
pub fn rotationX(angle: f32) Mat {
const sc = sincos(angle);
return .{
f32x4(1.0, 0.0, 0.0, 0.0),
f32x4(0.0, sc[1], sc[0], 0.0),
f32x4(0.0, -sc[0], sc[1], 0.0),
f32x4(0.0, 0.0, 0.0, 1.0),
};
}
pub fn rotationY(angle: f32) Mat {
const sc = sincos(angle);
return .{
f32x4(sc[1], 0.0, -sc[0], 0.0),
f32x4(0.0, 1.0, 0.0, 0.0),
f32x4(sc[0], 0.0, sc[1], 0.0),
f32x4(0.0, 0.0, 0.0, 1.0),
};
}
pub fn rotationZ(angle: f32) Mat {
const sc = sincos(angle);
return .{
f32x4(sc[1], sc[0], 0.0, 0.0),
f32x4(-sc[0], sc[1], 0.0, 0.0),
f32x4(0.0, 0.0, 1.0, 0.0),
f32x4(0.0, 0.0, 0.0, 1.0),
};
}
pub fn translation(x: f32, y: f32, z: f32) Mat {
return .{
f32x4(1.0, 0.0, 0.0, 0.0),
f32x4(0.0, 1.0, 0.0, 0.0),
f32x4(0.0, 0.0, 1.0, 0.0),
f32x4(x, y, z, 1.0),
};
}
pub fn translationV(v: Vec) Mat {
return translation(v[0], v[1], v[2]);
}
pub fn scaling(x: f32, y: f32, z: f32) Mat {
return .{
f32x4(x, 0.0, 0.0, 0.0),
f32x4(0.0, y, 0.0, 0.0),
f32x4(0.0, 0.0, z, 0.0),
f32x4(0.0, 0.0, 0.0, 1.0),
};
}
pub fn scalingV(v: Vec) Mat {
return scaling(v[0], v[1], v[2]);
}
pub fn lookToLh(eyepos: Vec, eyedir: Vec, updir: Vec) Mat {
const az = normalize3(eyedir);
const ax = normalize3(cross3(updir, az));
const ay = normalize3(cross3(az, ax));
return transpose(.{
f32x4(ax[0], ax[1], ax[2], -dot3(ax, eyepos)[0]),
f32x4(ay[0], ay[1], ay[2], -dot3(ay, eyepos)[0]),
f32x4(az[0], az[1], az[2], -dot3(az, eyepos)[0]),
f32x4(0.0, 0.0, 0.0, 1.0),
});
}
pub fn lookToRh(eyepos: Vec, eyedir: Vec, updir: Vec) Mat {
return lookToLh(eyepos, -eyedir, updir);
}
pub fn lookAtLh(eyepos: Vec, focuspos: Vec, updir: Vec) Mat {
return lookToLh(eyepos, focuspos - eyepos, updir);
}
pub fn lookAtRh(eyepos: Vec, focuspos: Vec, updir: Vec) Mat {
return lookToLh(eyepos, eyepos - focuspos, updir);
}
test "zmath.matrix.lookToLh" {
const m = lookToLh(f32x4(0.0, 0.0, -3.0, 1.0), f32x4(0.0, 0.0, 1.0, 0.0), f32x4(0.0, 1.0, 0.0, 0.0));
try expect(approxEqAbs(m[0], f32x4(1.0, 0.0, 0.0, 0.0), 0.001));
try expect(approxEqAbs(m[1], f32x4(0.0, 1.0, 0.0, 0.0), 0.001));
try expect(approxEqAbs(m[2], f32x4(0.0, 0.0, 1.0, 0.0), 0.001));
try expect(approxEqAbs(m[3], f32x4(0.0, 0.0, 3.0, 1.0), 0.001));
}
pub fn perspectiveFovLh(fovy: f32, aspect: f32, near: f32, far: f32) Mat {
const scfov = sincos(0.5 * fovy);
assert(near > 0.0 and far > 0.0 and far > near);
assert(!math.approxEqAbs(f32, scfov[0], 0.0, 0.001));
assert(!math.approxEqAbs(f32, far, near, 0.001));
assert(!math.approxEqAbs(f32, aspect, 0.0, 0.01));
const h = scfov[1] / scfov[0];
const w = h / aspect;
const r = far / (far - near);
return .{
f32x4(w, 0.0, 0.0, 0.0),
f32x4(0.0, h, 0.0, 0.0),
f32x4(0.0, 0.0, r, 1.0),
f32x4(0.0, 0.0, -r * near, 0.0),
};
}
pub fn perspectiveFovRh(fovy: f32, aspect: f32, near: f32, far: f32) Mat {
const scfov = sincos(0.5 * fovy);
assert(near > 0.0 and far > 0.0 and far > near);
assert(!math.approxEqAbs(f32, scfov[0], 0.0, 0.001));
assert(!math.approxEqAbs(f32, far, near, 0.001));
assert(!math.approxEqAbs(f32, aspect, 0.0, 0.01));
const h = scfov[1] / scfov[0];
const w = h / aspect;
const r = far / (near - far);
return .{
f32x4(w, 0.0, 0.0, 0.0),
f32x4(0.0, h, 0.0, 0.0),
f32x4(0.0, 0.0, r, -1.0),
f32x4(0.0, 0.0, r * near, 0.0),
};
}
pub fn orthographicLh(w: f32, h: f32, near: f32, far: f32) Mat {
assert(!math.approxEqAbs(f32, w, 0.0, 0.001));
assert(!math.approxEqAbs(f32, h, 0.0, 0.001));
assert(!math.approxEqAbs(f32, far, near, 0.001));
const r = 1 / (far - near);
return .{
f32x4(2 / w, 0.0, 0.0, 0.0),
f32x4(0.0, 2 / h, 0.0, 0.0),
f32x4(0.0, 0.0, r, 0.0),
f32x4(0.0, 0.0, -r * near, 1.0),
};
}
pub fn orthographicRh(w: f32, h: f32, near: f32, far: f32) Mat {
assert(!math.approxEqAbs(f32, w, 0.0, 0.001));
assert(!math.approxEqAbs(f32, h, 0.0, 0.001));
assert(!math.approxEqAbs(f32, far, near, 0.001));
const r = 1 / (near - far);
return .{
f32x4(2 / w, 0.0, 0.0, 0.0),
f32x4(0.0, 2 / h, 0.0, 0.0),
f32x4(0.0, 0.0, r, 0.0),
f32x4(0.0, 0.0, r * near, 1.0),
};
}
pub fn determinant(m: Mat) F32x4 {
var v0 = swizzle(m[2], .y, .x, .x, .x);
var v1 = swizzle(m[3], .z, .z, .y, .y);
var v2 = swizzle(m[2], .y, .x, .x, .x);
var v3 = swizzle(m[3], .w, .w, .w, .z);
var v4 = swizzle(m[2], .z, .z, .y, .y);
var v5 = swizzle(m[3], .w, .w, .w, .z);
var p0 = v0 * v1;
var p1 = v2 * v3;
var p2 = v4 * v5;
v0 = swizzle(m[2], .z, .z, .y, .y);
v1 = swizzle(m[3], .y, .x, .x, .x);
v2 = swizzle(m[2], .w, .w, .w, .z);
v3 = swizzle(m[3], .y, .x, .x, .x);
v4 = swizzle(m[2], .w, .w, .w, .z);
v5 = swizzle(m[3], .z, .z, .y, .y);
p0 = mulAdd(-v0, v1, p0);
p1 = mulAdd(-v2, v3, p1);
p2 = mulAdd(-v4, v5, p2);
v0 = swizzle(m[1], .w, .w, .w, .z);
v1 = swizzle(m[1], .z, .z, .y, .y);
v2 = swizzle(m[1], .y, .x, .x, .x);
var s = m[0] * f32x4(1.0, -1.0, 1.0, -1.0);
var r = v0 * p0;
r = mulAdd(-v1, p1, r);
r = mulAdd(v2, p2, r);
return dot4(s, r);
}
test "zmath.matrix.determinant" {
const m = Mat{
f32x4(10.0, -9.0, -12.0, 1.0),
f32x4(7.0, -12.0, 11.0, 1.0),
f32x4(-10.0, 10.0, 3.0, 1.0),
f32x4(1.0, 2.0, 3.0, 4.0),
};
try expect(approxEqAbs(determinant(m), splat(F32x4, 2939.0), 0.0001));
}
pub fn inverse(a: anytype) @TypeOf(a) {
const T = @TypeOf(a);
return switch (T) {
Mat => inverseMat(a),
Quat => inverseQuat(a),
else => @compileError("zmath.inverse() not implemented for " ++ @typeName(T)),
};
}
fn inverseMat(m: Mat) Mat {
return inverseDet(m, null);
}
pub fn inverseDet(m: Mat, out_det: ?*F32x4) Mat {
const mt = transpose(m);
var v0: [4]F32x4 = undefined;
var v1: [4]F32x4 = undefined;
v0[0] = swizzle(mt[2], .x, .x, .y, .y);
v1[0] = swizzle(mt[3], .z, .w, .z, .w);
v0[1] = swizzle(mt[0], .x, .x, .y, .y);
v1[1] = swizzle(mt[1], .z, .w, .z, .w);
v0[2] = @shuffle(f32, mt[2], mt[0], [4]i32{ 0, 2, ~@as(i32, 0), ~@as(i32, 2) });
v1[2] = @shuffle(f32, mt[3], mt[1], [4]i32{ 1, 3, ~@as(i32, 1), ~@as(i32, 3) });
var d0 = v0[0] * v1[0];
var d1 = v0[1] * v1[1];
var d2 = v0[2] * v1[2];
v0[0] = swizzle(mt[2], .z, .w, .z, .w);
v1[0] = swizzle(mt[3], .x, .x, .y, .y);
v0[1] = swizzle(mt[0], .z, .w, .z, .w);
v1[1] = swizzle(mt[1], .x, .x, .y, .y);
v0[2] = @shuffle(f32, mt[2], mt[0], [4]i32{ 1, 3, ~@as(i32, 1), ~@as(i32, 3) });
v1[2] = @shuffle(f32, mt[3], mt[1], [4]i32{ 0, 2, ~@as(i32, 0), ~@as(i32, 2) });
d0 = mulAdd(-v0[0], v1[0], d0);
d1 = mulAdd(-v0[1], v1[1], d1);
d2 = mulAdd(-v0[2], v1[2], d2);
v0[0] = swizzle(mt[1], .y, .z, .x, .y);
v1[0] = @shuffle(f32, d0, d2, [4]i32{ ~@as(i32, 1), 1, 3, 0 });
v0[1] = swizzle(mt[0], .z, .x, .y, .x);
v1[1] = @shuffle(f32, d0, d2, [4]i32{ 3, ~@as(i32, 1), 1, 2 });
v0[2] = swizzle(mt[3], .y, .z, .x, .y);
v1[2] = @shuffle(f32, d1, d2, [4]i32{ ~@as(i32, 3), 1, 3, 0 });
v0[3] = swizzle(mt[2], .z, .x, .y, .x);
v1[3] = @shuffle(f32, d1, d2, [4]i32{ 3, ~@as(i32, 3), 1, 2 });
var c0 = v0[0] * v1[0];
var c2 = v0[1] * v1[1];
var c4 = v0[2] * v1[2];
var c6 = v0[3] * v1[3];
v0[0] = swizzle(mt[1], .z, .w, .y, .z);
v1[0] = @shuffle(f32, d0, d2, [4]i32{ 3, 0, 1, ~@as(i32, 0) });
v0[1] = swizzle(mt[0], .w, .z, .w, .y);
v1[1] = @shuffle(f32, d0, d2, [4]i32{ 2, 1, ~@as(i32, 0), 0 });
v0[2] = swizzle(mt[3], .z, .w, .y, .z);
v1[2] = @shuffle(f32, d1, d2, [4]i32{ 3, 0, 1, ~@as(i32, 2) });
v0[3] = swizzle(mt[2], .w, .z, .w, .y);
v1[3] = @shuffle(f32, d1, d2, [4]i32{ 2, 1, ~@as(i32, 2), 0 });
c0 = mulAdd(-v0[0], v1[0], c0);
c2 = mulAdd(-v0[1], v1[1], c2);
c4 = mulAdd(-v0[2], v1[2], c4);
c6 = mulAdd(-v0[3], v1[3], c6);
v0[0] = swizzle(mt[1], .w, .x, .w, .x);
v1[0] = @shuffle(f32, d0, d2, [4]i32{ 2, ~@as(i32, 1), ~@as(i32, 0), 2 });
v0[1] = swizzle(mt[0], .y, .w, .x, .z);
v1[1] = @shuffle(f32, d0, d2, [4]i32{ ~@as(i32, 1), 0, 3, ~@as(i32, 0) });
v0[2] = swizzle(mt[3], .w, .x, .w, .x);
v1[2] = @shuffle(f32, d1, d2, [4]i32{ 2, ~@as(i32, 3), ~@as(i32, 2), 2 });
v0[3] = swizzle(mt[2], .y, .w, .x, .z);
v1[3] = @shuffle(f32, d1, d2, [4]i32{ ~@as(i32, 3), 0, 3, ~@as(i32, 2) });
const c1 = mulAdd(-v0[0], v1[0], c0);
const c3 = mulAdd(v0[1], v1[1], c2);
const c5 = mulAdd(-v0[2], v1[2], c4);
const c7 = mulAdd(v0[3], v1[3], c6);
c0 = mulAdd(v0[0], v1[0], c0);
c2 = mulAdd(-v0[1], v1[1], c2);
c4 = mulAdd(v0[2], v1[2], c4);
c6 = mulAdd(-v0[3], v1[3], c6);
var mr = Mat{
f32x4(c0[0], c1[1], c0[2], c1[3]),
f32x4(c2[0], c3[1], c2[2], c3[3]),
f32x4(c4[0], c5[1], c4[2], c5[3]),
f32x4(c6[0], c7[1], c6[2], c7[3]),
};
const det = dot4(mr[0], mt[0]);
if (out_det != null) {
out_det.?.* = det;
}
if (math.approxEqAbs(f32, det[0], 0.0, 0.0001)) {
return .{
f32x4(0.0, 0.0, 0.0, 0.0),
f32x4(0.0, 0.0, 0.0, 0.0),
f32x4(0.0, 0.0, 0.0, 0.0),
f32x4(0.0, 0.0, 0.0, 0.0),
};
}
const scale = splat(F32x4, 1.0) / det;
mr[0] *= scale;
mr[1] *= scale;
mr[2] *= scale;
mr[3] *= scale;
return mr;
}
test "zmath.matrix.inverse" {
const m = Mat{
f32x4(10.0, -9.0, -12.0, 1.0),
f32x4(7.0, -12.0, 11.0, 1.0),
f32x4(-10.0, 10.0, 3.0, 1.0),
f32x4(1.0, 2.0, 3.0, 4.0),
};
var det: F32x4 = undefined;
const mi = inverseDet(m, &det);
try expect(approxEqAbs(det, splat(F32x4, 2939.0), 0.0001));
try expect(approxEqAbs(mi[0], f32x4(-0.170806, -0.13576, -0.349439, 0.164001), 0.0001));
try expect(approxEqAbs(mi[1], f32x4(-0.163661, -0.14801, -0.253147, 0.141204), 0.0001));
try expect(approxEqAbs(mi[2], f32x4(-0.0871045, 0.00646478, -0.0785982, 0.0398095), 0.0001));
try expect(approxEqAbs(mi[3], f32x4(0.18986, 0.103096, 0.272882, 0.10854), 0.0001));
}
pub fn matFromNormAxisAngle(axis: Vec, angle: f32) Mat {
const sincos_angle = sincos(angle);
const c2 = splat(F32x4, 1.0 - sincos_angle[1]);
const c1 = splat(F32x4, sincos_angle[1]);
const c0 = splat(F32x4, sincos_angle[0]);
const n0 = swizzle(axis, .y, .z, .x, .w);
const n1 = swizzle(axis, .z, .x, .y, .w);
var v0 = c2 * n0 * n1;
const r0 = c2 * axis * axis + c1;
const r1 = c0 * axis + v0;
var r2 = v0 - c0 * axis;
v0 = @bitCast(F32x4, @bitCast(U32x4, r0) & u32x4_mask3);
var v1 = @shuffle(f32, r1, r2, [4]i32{ 0, 2, ~@as(i32, 1), ~@as(i32, 2) });
v1 = swizzle(v1, .y, .z, .w, .x);
var v2 = @shuffle(f32, r1, r2, [4]i32{ 1, 1, ~@as(i32, 0), ~@as(i32, 0) });
v2 = swizzle(v2, .x, .z, .x, .z);
r2 = @shuffle(f32, v0, v1, [4]i32{ 0, 3, ~@as(i32, 0), ~@as(i32, 1) });
r2 = swizzle(r2, .x, .z, .w, .y);
var m: Mat = undefined;
m[0] = r2;
r2 = @shuffle(f32, v0, v1, [4]i32{ 1, 3, ~@as(i32, 2), ~@as(i32, 3) });
r2 = swizzle(r2, .z, .x, .w, .y);
m[1] = r2;
v2 = @shuffle(f32, v2, v0, [4]i32{ 0, 1, ~@as(i32, 2), ~@as(i32, 3) });
m[2] = v2;
m[3] = f32x4(0.0, 0.0, 0.0, 1.0);
return m;
}
pub fn matFromAxisAngle(axis: Vec, angle: f32) Mat {
assert(!all(axis == splat(F32x4, 0.0), 3));
assert(!all(isInf(axis), 3));
const normal = normalize3(axis);
return matFromNormAxisAngle(normal, angle);
}
test "zmath.matrix.matFromAxisAngle" {
{
const m0 = matFromAxisAngle(f32x4(1.0, 0.0, 0.0, 0.0), math.pi * 0.25);
const m1 = rotationX(math.pi * 0.25);
try expect(approxEqAbs(m0[0], m1[0], 0.001));
try expect(approxEqAbs(m0[1], m1[1], 0.001));
try expect(approxEqAbs(m0[2], m1[2], 0.001));
try expect(approxEqAbs(m0[3], m1[3], 0.001));
}
{
const m0 = matFromAxisAngle(f32x4(0.0, 1.0, 0.0, 0.0), math.pi * 0.125);
const m1 = rotationY(math.pi * 0.125);
try expect(approxEqAbs(m0[0], m1[0], 0.001));
try expect(approxEqAbs(m0[1], m1[1], 0.001));
try expect(approxEqAbs(m0[2], m1[2], 0.001));
try expect(approxEqAbs(m0[3], m1[3], 0.001));
}
{
const m0 = matFromAxisAngle(f32x4(0.0, 0.0, 1.0, 0.0), math.pi * 0.333);
const m1 = rotationZ(math.pi * 0.333);
try expect(approxEqAbs(m0[0], m1[0], 0.001));
try expect(approxEqAbs(m0[1], m1[1], 0.001));
try expect(approxEqAbs(m0[2], m1[2], 0.001));
try expect(approxEqAbs(m0[3], m1[3], 0.001));
}
}
pub fn matFromQuat(quat: Quat) Mat {
var q0 = quat + quat;
var q1 = quat * q0;
var v0 = swizzle(q1, .y, .x, .x, .w);
v0 = @bitCast(F32x4, @bitCast(U32x4, v0) & u32x4_mask3);
var v1 = swizzle(q1, .z, .z, .y, .w);
v1 = @bitCast(F32x4, @bitCast(U32x4, v1) & u32x4_mask3);
var r0 = (f32x4(1.0, 1.0, 1.0, 0.0) - v0) - v1;
v0 = swizzle(quat, .x, .x, .y, .w);
v1 = swizzle(q0, .z, .y, .z, .w);
v0 = v0 * v1;
v1 = swizzle(quat, .w, .w, .w, .w);
var v2 = swizzle(q0, .y, .z, .x, .w);
v1 = v1 * v2;
var r1 = v0 + v1;
var r2 = v0 - v1;
v0 = @shuffle(f32, r1, r2, [4]i32{ 1, 2, ~@as(i32, 0), ~@as(i32, 1) });
v0 = swizzle(v0, .x, .z, .w, .y);
v1 = @shuffle(f32, r1, r2, [4]i32{ 0, 0, ~@as(i32, 2), ~@as(i32, 2) });
v1 = swizzle(v1, .x, .z, .x, .z);
q1 = @shuffle(f32, r0, v0, [4]i32{ 0, 3, ~@as(i32, 0), ~@as(i32, 1) });
q1 = swizzle(q1, .x, .z, .w, .y);
var m: Mat = undefined;
m[0] = q1;
q1 = @shuffle(f32, r0, v0, [4]i32{ 1, 3, ~@as(i32, 2), ~@as(i32, 3) });
q1 = swizzle(q1, .z, .x, .w, .y);
m[1] = q1;
q1 = @shuffle(f32, v1, r0, [4]i32{ 0, 1, ~@as(i32, 2), ~@as(i32, 3) });
m[2] = q1;
m[3] = f32x4(0.0, 0.0, 0.0, 1.0);
return m;
}
test "zmath.matrix.matFromQuat" {
{
const m = matFromQuat(f32x4(0.0, 0.0, 0.0, 1.0));
try expect(approxEqAbs(m[0], f32x4(1.0, 0.0, 0.0, 0.0), 0.0001));
try expect(approxEqAbs(m[1], f32x4(0.0, 1.0, 0.0, 0.0), 0.0001));
try expect(approxEqAbs(m[2], f32x4(0.0, 0.0, 1.0, 0.0), 0.0001));
try expect(approxEqAbs(m[3], f32x4(0.0, 0.0, 0.0, 1.0), 0.0001));
}
}
pub fn matFromRollPitchYaw(pitch: f32, yaw: f32, roll: f32) Mat {
return matFromRollPitchYawV(f32x4(pitch, yaw, roll, 0.0));
}
pub fn matFromRollPitchYawV(angles: Vec) Mat {
return matFromQuat(quatFromRollPitchYawV(angles));
}
pub fn matToQuat(m: Mat) Quat {
return quatFromMat(m);
}
pub inline fn loadMat(mem: []const f32) Mat {
return .{
load(mem[0..4], F32x4, 0),
load(mem[4..8], F32x4, 0),
load(mem[8..12], F32x4, 0),
load(mem[12..16], F32x4, 0),
};
}
test "zmath.loadMat" {
const a = [18]f32{
1.0, 2.0, 3.0, 4.0,
5.0, 6.0, 7.0, 8.0,
9.0, 10.0, 11.0, 12.0,
13.0, 14.0, 15.0, 16.0,
17.0, 18.0,
};
const m = loadMat(a[1..]);
try expect(approxEqAbs(m[0], f32x4(2.0, 3.0, 4.0, 5.0), 0.0));
try expect(approxEqAbs(m[1], f32x4(6.0, 7.0, 8.0, 9.0), 0.0));
try expect(approxEqAbs(m[2], f32x4(10.0, 11.0, 12.0, 13.0), 0.0));
try expect(approxEqAbs(m[3], f32x4(14.0, 15.0, 16.0, 17.0), 0.0));
}
pub inline fn storeMat(mem: []f32, m: Mat) void {
store(mem[0..4], m[0], 0);
store(mem[4..8], m[1], 0);
store(mem[8..12], m[2], 0);
store(mem[12..16], m[3], 0);
}
pub inline fn loadMat43(mem: []const f32) Mat {
return .{
f32x4(mem[0], mem[1], mem[2], 0.0),
f32x4(mem[3], mem[4], mem[5], 0.0),
f32x4(mem[6], mem[7], mem[8], 0.0),
f32x4(mem[9], mem[10], mem[11], 1.0),
};
}
pub inline fn storeMat43(mem: []f32, m: Mat) void {
store(mem[0..3], m[0], 3);
store(mem[3..6], m[1], 3);
store(mem[6..9], m[2], 3);
store(mem[9..12], m[3], 3);
}
pub inline fn loadMat34(mem: []const f32) Mat {
return .{
load(mem[0..4], F32x4, 0),
load(mem[4..8], F32x4, 0),
load(mem[8..12], F32x4, 0),
f32x4(0.0, 0.0, 0.0, 1.0),
};
}
pub inline fn storeMat34(mem: []f32, m: Mat) void {
store(mem[0..4], m[0], 0);
store(mem[4..8], m[1], 0);
store(mem[8..12], m[2], 0);
}
pub inline fn matToArray(m: Mat) [16]f32 {
var array: [16]f32 = undefined;
storeMat(array[0..], m);
return array;
}
pub inline fn mat43ToArray(m: Mat) [12]f32 {
var array: [12]f32 = undefined;
storeMat43(array[0..], m);
return array;
}
pub inline fn mat34ToArray(m: Mat) [12]f32 {
var array: [12]f32 = undefined;
storeMat34(array[0..], m);
return array;
}
// ------------------------------------------------------------------------------
//
// 5. Quaternion functions
//
// ------------------------------------------------------------------------------
fn qmul(q0: Quat, q1: Quat) Quat {
var result = swizzle(q1, .w, .w, .w, .w);
var q1x = swizzle(q1, .x, .x, .x, .x);
var q1y = swizzle(q1, .y, .y, .y, .y);
var q1z = swizzle(q1, .z, .z, .z, .z);
result = result * q0;
var q0_shuf = swizzle(q0, .w, .z, .y, .x);
q1x = q1x * q0_shuf;
q0_shuf = swizzle(q0_shuf, .y, .x, .w, .z);
result = mulAdd(q1x, f32x4(1.0, -1.0, 1.0, -1.0), result);
q1y = q1y * q0_shuf;
q0_shuf = swizzle(q0_shuf, .w, .z, .y, .x);
q1y = q1y * f32x4(1.0, 1.0, -1.0, -1.0);
q1z = q1z * q0_shuf;
q1y = mulAdd(q1z, f32x4(-1.0, 1.0, 1.0, -1.0), q1y);
return result + q1y;
}
test "zmath.quaternion.mul" {
{
const q0 = f32x4(2.0, 3.0, 4.0, 1.0);
const q1 = f32x4(3.0, 2.0, 1.0, 4.0);
try expect(approxEqAbs(qmul(q0, q1), f32x4(16.0, 4.0, 22.0, -12.0), 0.0001));
}
}
pub fn quatToMat(quat: Quat) Mat {
return matFromQuat(quat);
}
pub fn quatToAxisAngle(quat: Quat, axis: *Vec, angle: *f32) void {
axis.* = quat;
angle.* = 2.0 * acos(quat[3]);
}
test "zmath.quaternion.quatToAxisAngle" {
{
const q0 = quatFromNormAxisAngle(f32x4(1.0, 0.0, 0.0, 0.0), 0.25 * math.pi);
var axis: Vec = f32x4(4.0, 3.0, 2.0, 1.0);
var angle: f32 = 10.0;
quatToAxisAngle(q0, &axis, &angle);
try expect(math.approxEqAbs(f32, axis[0], math.sin(@as(f32, 0.25) * math.pi * 0.5), 0.0001));
try expect(axis[1] == 0.0);
try expect(axis[2] == 0.0);
try expect(math.approxEqAbs(f32, angle, 0.25 * math.pi, 0.0001));
}
}
pub fn quatFromMat(m: Mat) Quat {
const r0 = m[0];
const r1 = m[1];
const r2 = m[2];
const r00 = swizzle(r0, .x, .x, .x, .x);
const r11 = swizzle(r1, .y, .y, .y, .y);
const r22 = swizzle(r2, .z, .z, .z, .z);
const x2gey2 = (r11 - r00) <= splat(F32x4, 0.0);
const z2gew2 = (r11 + r00) <= splat(F32x4, 0.0);
const x2py2gez2pw2 = r22 <= splat(F32x4, 0.0);
var t0 = mulAdd(r00, f32x4(1.0, -1.0, -1.0, 1.0), splat(F32x4, 1.0));
var t1 = r11 * f32x4(-1.0, 1.0, -1.0, 1.0);
var t2 = mulAdd(r22, f32x4(-1.0, -1.0, 1.0, 1.0), t0);
const x2y2z2w2 = t1 + t2;
t0 = @shuffle(f32, r0, r1, [4]i32{ 1, 2, ~@as(i32, 2), ~@as(i32, 1) });
t1 = @shuffle(f32, r1, r2, [4]i32{ 0, 0, ~@as(i32, 0), ~@as(i32, 1) });
t1 = swizzle(t1, .x, .z, .w, .y);
const xyxzyz = t0 + t1;
t0 = @shuffle(f32, r2, r1, [4]i32{ 1, 0, ~@as(i32, 0), ~@as(i32, 0) });
t1 = @shuffle(f32, r1, r0, [4]i32{ 2, 2, ~@as(i32, 2), ~@as(i32, 1) });
t1 = swizzle(t1, .x, .z, .w, .y);
const xwywzw = (t0 - t1) * f32x4(-1.0, 1.0, -1.0, 1.0);
t0 = @shuffle(f32, x2y2z2w2, xyxzyz, [4]i32{ 0, 1, ~@as(i32, 0), ~@as(i32, 0) });
t1 = @shuffle(f32, x2y2z2w2, xwywzw, [4]i32{ 2, 3, ~@as(i32, 2), ~@as(i32, 0) });
t2 = @shuffle(f32, xyxzyz, xwywzw, [4]i32{ 1, 2, ~@as(i32, 0), ~@as(i32, 1) });
const tensor0 = @shuffle(f32, t0, t2, [4]i32{ 0, 2, ~@as(i32, 0), ~@as(i32, 2) });
const tensor1 = @shuffle(f32, t0, t2, [4]i32{ 2, 1, ~@as(i32, 1), ~@as(i32, 3) });
const tensor2 = @shuffle(f32, t2, t1, [4]i32{ 0, 1, ~@as(i32, 0), ~@as(i32, 2) });
const tensor3 = @shuffle(f32, t2, t1, [4]i32{ 2, 3, ~@as(i32, 2), ~@as(i32, 1) });
t0 = select(x2gey2, tensor0, tensor1);
t1 = select(z2gew2, tensor2, tensor3);
t2 = select(x2py2gez2pw2, t0, t1);
return t2 / length4(t2);
}
test "zmath.quatFromMat" {
{
const q0 = quatFromAxisAngle(f32x4(1.0, 0.0, 0.0, 0.0), 0.25 * math.pi);
const q1 = quatFromMat(rotationX(0.25 * math.pi));
try expect(approxEqAbs(q0, q1, 0.0001));
}
{
const q0 = quatFromAxisAngle(f32x4(1.0, 2.0, 0.5, 0.0), 0.25 * math.pi);
const q1 = quatFromMat(matFromAxisAngle(f32x4(1.0, 2.0, 0.5, 0.0), 0.25 * math.pi));
try expect(approxEqAbs(q0, q1, 0.0001));
}
{
const q0 = quatFromRollPitchYaw(0.1 * math.pi, -0.2 * math.pi, 0.3 * math.pi);
const q1 = quatFromMat(matFromRollPitchYaw(0.1 * math.pi, -0.2 * math.pi, 0.3 * math.pi));
try expect(approxEqAbs(q0, q1, 0.0001));
}
}
pub fn quatFromNormAxisAngle(axis: Vec, angle: f32) Quat {
var n = f32x4(axis[0], axis[1], axis[2], 1.0);
const sc = sincos(0.5 * angle);
return n * f32x4(sc[0], sc[0], sc[0], sc[1]);
}
pub fn quatFromAxisAngle(axis: Vec, angle: f32) Quat {
assert(!all(axis == splat(F32x4, 0.0), 3));
assert(!all(isInf(axis), 3));
const normal = normalize3(axis);
return quatFromNormAxisAngle(normal, angle);
}
test "zmath.quaternion.quatFromNormAxisAngle" {
{
const q0 = quatFromAxisAngle(f32x4(1.0, 0.0, 0.0, 0.0), 0.25 * math.pi);
const q1 = quatFromAxisAngle(f32x4(0.0, 1.0, 0.0, 0.0), 0.125 * math.pi);
const m0 = rotationX(0.25 * math.pi);
const m1 = rotationY(0.125 * math.pi);
const mr0 = quatToMat(qmul(q0, q1));
const mr1 = mul(m0, m1);
try expect(approxEqAbs(mr0[0], mr1[0], 0.0001));
try expect(approxEqAbs(mr0[1], mr1[1], 0.0001));
try expect(approxEqAbs(mr0[2], mr1[2], 0.0001));
try expect(approxEqAbs(mr0[3], mr1[3], 0.0001));
}
{
const m0 = quatToMat(quatFromAxisAngle(f32x4(1.0, 2.0, 0.5, 0.0), 0.25 * math.pi));
const m1 = matFromAxisAngle(f32x4(1.0, 2.0, 0.5, 0.0), 0.25 * math.pi);
try expect(approxEqAbs(m0[0], m1[0], 0.0001));
try expect(approxEqAbs(m0[1], m1[1], 0.0001));
try expect(approxEqAbs(m0[2], m1[2], 0.0001));
try expect(approxEqAbs(m0[3], m1[3], 0.0001));
}
}
pub fn conjugate(quat: Quat) Quat {
return quat * f32x4(-1.0, -1.0, -1.0, 1.0);
}
fn inverseQuat(quat: Quat) Quat {
const l = lengthSq4(quat);
const conj = conjugate(quat);
return select(l <= splat(F32x4, math.f32_epsilon), splat(F32x4, 0.0), conj / l);
}
test "zmath.quaternion.inverseQuat" {
try expect(approxEqAbs(
inverse(f32x4(2.0, 3.0, 4.0, 1.0)),
f32x4(-1.0 / 15.0, -1.0 / 10.0, -2.0 / 15.0, 1.0 / 30.0),
0.0001,
));
}
pub fn slerp(q0: Quat, q1: Quat, t: f32) Quat {
return slerpV(q0, q1, splat(F32x4, t));
}
pub fn slerpV(q0: Quat, q1: Quat, t: F32x4) Quat {
var cos_omega = dot4(q0, q1);
const sign = select(cos_omega < splat(F32x4, 0.0), splat(F32x4, -1.0), splat(F32x4, 1.0));
cos_omega = cos_omega * sign;
const sin_omega = sqrt(splat(F32x4, 1.0) - cos_omega * cos_omega);
const omega = atan2(sin_omega, cos_omega);
var v01 = t;
v01 = @bitCast(F32x4, (@bitCast(U32x4, v01) & u32x4_mask2) ^ u32x4_sign_mask1);
v01 = f32x4(1.0, 0.0, 0.0, 0.0) + v01;
var s0 = sin(v01 * omega) / sin_omega;
s0 = select(cos_omega < splat(F32x4, 1.0 - 0.00001), s0, v01);
var s1 = swizzle(s0, .y, .y, .y, .y);
s0 = swizzle(s0, .x, .x, .x, .x);
return q0 * s0 + sign * q1 * s1;
}
test "zmath.quaternion.slerp" {
const from = f32x4(0.0, 0.0, 0.0, 1.0);
const to = f32x4(0.5, 0.5, -0.5, 0.5);
const result = slerp(from, to, 0.5);
try expect(approxEqAbs(result, f32x4(0.28867513, 0.28867513, -0.28867513, 0.86602540), 0.0001));
}
pub fn quatFromRollPitchYaw(pitch: f32, yaw: f32, roll: f32) Quat {
return quatFromRollPitchYawV(f32x4(pitch, yaw, roll, 0.0));
}
pub fn quatFromRollPitchYawV(angles: Vec) Quat { // | pitch | yaw | roll | 0 |
const sc = sincos(splat(Vec, 0.5) * angles);
const p0 = @shuffle(f32, sc[1], sc[0], [4]i32{ ~@as(i32, 0), 0, 0, 0 });
const p1 = @shuffle(f32, sc[0], sc[1], [4]i32{ ~@as(i32, 0), 0, 0, 0 });
const y0 = @shuffle(f32, sc[1], sc[0], [4]i32{ 1, ~@as(i32, 1), 1, 1 });
const y1 = @shuffle(f32, sc[0], sc[1], [4]i32{ 1, ~@as(i32, 1), 1, 1 });
const r0 = @shuffle(f32, sc[1], sc[0], [4]i32{ 2, 2, ~@as(i32, 2), 2 });
const r1 = @shuffle(f32, sc[0], sc[1], [4]i32{ 2, 2, ~@as(i32, 2), 2 });
const q1 = p1 * f32x4(1.0, -1.0, -1.0, 1.0) * y1;
const q0 = p0 * y0 * r0;
return mulAdd(q1, r1, q0);
}
test "zmath.quaternion.quatFromRollPitchYawV" {
{
const m0 = quatToMat(quatFromRollPitchYawV(f32x4(0.25 * math.pi, 0.0, 0.0, 0.0)));
const m1 = rotationX(0.25 * math.pi);
try expect(approxEqAbs(m0[0], m1[0], 0.0001));
try expect(approxEqAbs(m0[1], m1[1], 0.0001));
try expect(approxEqAbs(m0[2], m1[2], 0.0001));
try expect(approxEqAbs(m0[3], m1[3], 0.0001));
}
{
const m0 = quatToMat(quatFromRollPitchYaw(0.1 * math.pi, 0.2 * math.pi, 0.3 * math.pi));
const m1 = mul(
rotationZ(0.3 * math.pi),
mul(rotationX(0.1 * math.pi), rotationY(0.2 * math.pi)),
);
try expect(approxEqAbs(m0[0], m1[0], 0.0001));
try expect(approxEqAbs(m0[1], m1[1], 0.0001));
try expect(approxEqAbs(m0[2], m1[2], 0.0001));
try expect(approxEqAbs(m0[3], m1[3], 0.0001));
}
}
// ------------------------------------------------------------------------------
//
// X. Misc functions
//
// ------------------------------------------------------------------------------
pub inline fn linePointDistance(linept0: Vec, linept1: Vec, pt: Vec) F32x4 {
const ptvec = pt - linept0;
const linevec = linept1 - linept0;
const scale = dot3(ptvec, linevec) / lengthSq3(linevec);
return length3(ptvec - linevec * scale);
}
test "zmath.linePointDistance" {
{
const linept0 = F32x4{ -1.0, -2.0, -3.0, 1.0 };
const linept1 = F32x4{ 1.0, 2.0, 3.0, 1.0 };
const pt = F32x4{ 1.0, 1.0, 1.0, 1.0 };
var v = linePointDistance(linept0, linept1, pt);
try expect(approxEqAbs(v, splat(F32x4, 0.654), 0.001));
}
}
fn sin32(v: f32) f32 {
var y = v - math.tau * @round(v * 1.0 / math.tau);
if (y > 0.5 * math.pi) {
y = math.pi - y;
} else if (y < -math.pi * 0.5) {
y = -math.pi - y;
}
const y2 = y * y;
// 11-degree minimax approximation
var sinv = mulAdd(@as(f32, -2.3889859e-08), y2, 2.7525562e-06);
sinv = mulAdd(sinv, y2, -0.00019840874);
sinv = mulAdd(sinv, y2, 0.0083333310);
sinv = mulAdd(sinv, y2, -0.16666667);
return y * mulAdd(sinv, y2, 1.0);
}
fn cos32(v: f32) f32 {
var y = v - math.tau * @round(v * 1.0 / math.tau);
const sign = blk: {
if (y > 0.5 * math.pi) {
y = math.pi - y;
break :blk @as(f32, -1.0);
} else if (y < -math.pi * 0.5) {
y = -math.pi - y;
break :blk @as(f32, -1.0);
} else {
break :blk @as(f32, 1.0);
}
};
const y2 = y * y;
// 10-degree minimax approximation
var cosv = mulAdd(@as(f32, -2.6051615e-07), y2, 2.4760495e-05);
cosv = mulAdd(cosv, y2, -0.0013888378);
cosv = mulAdd(cosv, y2, 0.041666638);
cosv = mulAdd(cosv, y2, -0.5);
return sign * mulAdd(cosv, y2, 1.0);
}
fn sincos32(v: f32) [2]f32 {
var y = v - math.tau * @round(v * 1.0 / math.tau);
const sign = blk: {
if (y > 0.5 * math.pi) {
y = math.pi - y;
break :blk @as(f32, -1.0);
} else if (y < -math.pi * 0.5) {
y = -math.pi - y;
break :blk @as(f32, -1.0);
} else {
break :blk @as(f32, 1.0);
}
};
const y2 = y * y;
// 11-degree minimax approximation
var sinv = mulAdd(@as(f32, -2.3889859e-08), y2, 2.7525562e-06);
sinv = mulAdd(sinv, y2, -0.00019840874);
sinv = mulAdd(sinv, y2, 0.0083333310);
sinv = mulAdd(sinv, y2, -0.16666667);
sinv = y * mulAdd(sinv, y2, 1.0);
// 10-degree minimax approximation
var cosv = mulAdd(@as(f32, -2.6051615e-07), y2, 2.4760495e-05);
cosv = mulAdd(cosv, y2, -0.0013888378);
cosv = mulAdd(cosv, y2, 0.041666638);
cosv = mulAdd(cosv, y2, -0.5);
cosv = sign * mulAdd(cosv, y2, 1.0);
return .{ sinv, cosv };
}
test "zmath.sincos32" {
const epsilon = 0.0001;
try expect(math.isNan(sincos32(math.inf_f32)[0]));
try expect(math.isNan(sincos32(math.inf_f32)[1]));
try expect(math.isNan(sincos32(-math.inf_f32)[0]));
try expect(math.isNan(sincos32(-math.inf_f32)[1]));
try expect(math.isNan(sincos32(math.nan_f32)[0]));
try expect(math.isNan(sincos32(-math.nan_f32)[1]));
try expect(math.isNan(sin32(math.inf_f32)));
try expect(math.isNan(cos32(math.inf_f32)));
try expect(math.isNan(sin32(-math.inf_f32)));
try expect(math.isNan(cos32(-math.inf_f32)));
try expect(math.isNan(sin32(math.nan_f32)));
try expect(math.isNan(cos32(-math.nan_f32)));
var f: f32 = -100.0;
var i: u32 = 0;
while (i < 100) : (i += 1) {
const sc = sincos32(f);
const s0 = sin32(f);
const c0 = cos32(f);
const s = @sin(f);
const c = @cos(f);
try expect(math.approxEqAbs(f32, sc[0], s, epsilon));
try expect(math.approxEqAbs(f32, sc[1], c, epsilon));
try expect(math.approxEqAbs(f32, s0, s, epsilon));
try expect(math.approxEqAbs(f32, c0, c, epsilon));
f += 0.12345 * @intToFloat(f32, i);
}
}
fn asin32(v: f32) f32 {
const x = @fabs(v);
var omx = 1.0 - x;
if (omx < 0.0) {
omx = 0.0;
}
const root = @sqrt(omx);
// 7-degree minimax approximation
var result = mulAdd(@as(f32, -0.0012624911), x, 0.0066700901);
result = mulAdd(result, x, -0.0170881256);
result = mulAdd(result, x, 0.0308918810);
result = mulAdd(result, x, -0.0501743046);
result = mulAdd(result, x, 0.0889789874);
result = mulAdd(result, x, -0.2145988016);
result = root * mulAdd(result, x, 1.5707963050);
return if (v >= 0.0) 0.5 * math.pi - result else result - 0.5 * math.pi;
}
test "zmath.asin32" {
const epsilon = 0.0001;
try expect(math.approxEqAbs(f32, asin(@as(f32, -1.1)), -0.5 * math.pi, epsilon));
try expect(math.approxEqAbs(f32, asin(@as(f32, 1.1)), 0.5 * math.pi, epsilon));
try expect(math.approxEqAbs(f32, asin(@as(f32, -1000.1)), -0.5 * math.pi, epsilon));
try expect(math.approxEqAbs(f32, asin(@as(f32, 100000.1)), 0.5 * math.pi, epsilon));
try expect(math.isNan(asin(math.inf_f32)));
try expect(math.isNan(asin(-math.inf_f32)));
try expect(math.isNan(asin(math.nan_f32)));
try expect(math.isNan(asin(-math.nan_f32)));
try expect(approxEqAbs(asin(splat(F32x8, -100.0)), splat(F32x8, -0.5 * math.pi), epsilon));
try expect(approxEqAbs(asin(splat(F32x16, 100.0)), splat(F32x16, 0.5 * math.pi), epsilon));
try expect(all(isNan(asin(splat(F32x4, math.inf_f32))), 0) == true);
try expect(all(isNan(asin(splat(F32x4, -math.inf_f32))), 0) == true);
try expect(all(isNan(asin(splat(F32x4, math.nan_f32))), 0) == true);
try expect(all(isNan(asin(splat(F32x4, math.qnan_f32))), 0) == true);
var f: f32 = -1.0;
var i: u32 = 0;
while (i < 8) : (i += 1) {
const r0 = asin32(f);
const r1 = math.asin(f);
const r4 = asin(splat(F32x4, f));
const r8 = asin(splat(F32x8, f));
const r16 = asin(splat(F32x16, f));
try expect(math.approxEqAbs(f32, r0, r1, epsilon));
try expect(approxEqAbs(r4, splat(F32x4, r1), epsilon));
try expect(approxEqAbs(r8, splat(F32x8, r1), epsilon));
try expect(approxEqAbs(r16, splat(F32x16, r1), epsilon));
f += 0.09 * @intToFloat(f32, i);
}
}
fn acos32(v: f32) f32 {
const x = @fabs(v);
var omx = 1.0 - x;
if (omx < 0.0) {
omx = 0.0;
}
const root = @sqrt(omx);
// 7-degree minimax approximation
var result = mulAdd(@as(f32, -0.0012624911), x, 0.0066700901);
result = mulAdd(result, x, -0.0170881256);
result = mulAdd(result, x, 0.0308918810);
result = mulAdd(result, x, -0.0501743046);
result = mulAdd(result, x, 0.0889789874);
result = mulAdd(result, x, -0.2145988016);
result = root * mulAdd(result, x, 1.5707963050);
return if (v >= 0.0) result else math.pi - result;
}
test "zmath.acos32" {
const epsilon = 0.1;
try expect(math.approxEqAbs(f32, acos(@as(f32, -1.1)), math.pi, epsilon));
try expect(math.approxEqAbs(f32, acos(@as(f32, -10000.1)), math.pi, epsilon));
try expect(math.approxEqAbs(f32, acos(@as(f32, 1.1)), 0.0, epsilon));
try expect(math.approxEqAbs(f32, acos(@as(f32, 1000.1)), 0.0, epsilon));
try expect(math.isNan(acos(math.inf_f32)));
try expect(math.isNan(acos(-math.inf_f32)));
try expect(math.isNan(acos(math.nan_f32)));
try expect(math.isNan(acos(-math.nan_f32)));
try expect(approxEqAbs(acos(splat(F32x8, -100.0)), splat(F32x8, math.pi), epsilon));
try expect(approxEqAbs(acos(splat(F32x16, 100.0)), splat(F32x16, 0.0), epsilon));
try expect(all(isNan(acos(splat(F32x4, math.inf_f32))), 0) == true);
try expect(all(isNan(acos(splat(F32x4, -math.inf_f32))), 0) == true);
try expect(all(isNan(acos(splat(F32x4, math.nan_f32))), 0) == true);
try expect(all(isNan(acos(splat(F32x4, math.qnan_f32))), 0) == true);
var f: f32 = -1.0;
var i: u32 = 0;
while (i < 8) : (i += 1) {
const r0 = acos32(f);
const r1 = math.acos(f);
const r4 = acos(splat(F32x4, f));
const r8 = acos(splat(F32x8, f));
const r16 = acos(splat(F32x16, f));
try expect(math.approxEqAbs(f32, r0, r1, epsilon));
try expect(approxEqAbs(r4, splat(F32x4, r1), epsilon));
try expect(approxEqAbs(r8, splat(F32x8, r1), epsilon));
try expect(approxEqAbs(r16, splat(F32x16, r1), epsilon));
f += 0.09 * @intToFloat(f32, i);
}
}
pub fn modAngle32(in_angle: f32) f32 {
const angle = in_angle + math.pi;
var temp: f32 = math.fabs(angle);
temp = temp - (2.0 * math.pi * @intToFloat(f32, @floatToInt(i32, temp / math.pi)));
temp = temp - math.pi;
if (angle < 0.0) {
temp = -temp;
}
return temp;
}
pub fn cmulSoa(re0: anytype, im0: anytype, re1: anytype, im1: anytype) [2]@TypeOf(re0, im0, re1, im1) {
const re0_re1 = re0 * re1;
const re0_im1 = re0 * im1;
return .{
mulAdd(-im0, im1, re0_re1), // re
mulAdd(re1, im0, re0_im1), // im
};
}
// ------------------------------------------------------------------------------
//
// FFT (implementation based on xdsp.h from DirectXMath)
//
// ------------------------------------------------------------------------------
fn fftButterflyDit4_1(re0: *F32x4, im0: *F32x4) void {
const re0l = swizzle(re0.*, .x, .x, .y, .y);
const re0h = swizzle(re0.*, .z, .z, .w, .w);
const im0l = swizzle(im0.*, .x, .x, .y, .y);
const im0h = swizzle(im0.*, .z, .z, .w, .w);
const re_temp = mulAdd(re0h, f32x4(1.0, -1.0, 1.0, -1.0), re0l);
const im_temp = mulAdd(im0h, f32x4(1.0, -1.0, 1.0, -1.0), im0l);
const re_shuf0 = @shuffle(f32, re_temp, im_temp, [4]i32{ 2, 3, ~@as(i32, 2), ~@as(i32, 3) });
const re_shuf = swizzle(re_shuf0, .x, .w, .x, .w);
const im_shuf = swizzle(re_shuf0, .z, .y, .z, .y);
const re_templ = swizzle(re_temp, .x, .y, .x, .y);
const im_templ = swizzle(im_temp, .x, .y, .x, .y);
re0.* = mulAdd(re_shuf, f32x4(1.0, 1.0, -1.0, -1.0), re_templ);
im0.* = mulAdd(im_shuf, f32x4(1.0, -1.0, -1.0, 1.0), im_templ);
}
fn fftButterflyDit4_4(
re0: *F32x4,
re1: *F32x4,
re2: *F32x4,
re3: *F32x4,
im0: *F32x4,
im1: *F32x4,
im2: *F32x4,
im3: *F32x4,
unity_table_re: []const F32x4,
unity_table_im: []const F32x4,
stride: u32,
last: bool,
) void {
const re_temp0 = re0.* + re2.*;
const im_temp0 = im0.* + im2.*;
const re_temp2 = re1.* + re3.*;
const im_temp2 = im1.* + im3.*;
const re_temp1 = re0.* - re2.*;
const im_temp1 = im0.* - im2.*;
const re_temp3 = re1.* - re3.*;
const im_temp3 = im1.* - im3.*;
var re_temp4 = re_temp0 + re_temp2;
var im_temp4 = im_temp0 + im_temp2;
var re_temp5 = re_temp1 + im_temp3;
var im_temp5 = im_temp1 - re_temp3;
var re_temp6 = re_temp0 - re_temp2;
var im_temp6 = im_temp0 - im_temp2;
var re_temp7 = re_temp1 - im_temp3;
var im_temp7 = im_temp1 + re_temp3;
{
const re_im = cmulSoa(re_temp5, im_temp5, unity_table_re[stride], unity_table_im[stride]);
re_temp5 = re_im[0];
im_temp5 = re_im[1];
}
{
const re_im = cmulSoa(re_temp6, im_temp6, unity_table_re[stride * 2], unity_table_im[stride * 2]);
re_temp6 = re_im[0];
im_temp6 = re_im[1];
}
{
const re_im = cmulSoa(re_temp7, im_temp7, unity_table_re[stride * 3], unity_table_im[stride * 3]);
re_temp7 = re_im[0];
im_temp7 = re_im[1];
}
if (last) {
fftButterflyDit4_1(&re_temp4, &im_temp4);
fftButterflyDit4_1(&re_temp5, &im_temp5);
fftButterflyDit4_1(&re_temp6, &im_temp6);
fftButterflyDit4_1(&re_temp7, &im_temp7);
}
re0.* = re_temp4;
im0.* = im_temp4;
re1.* = re_temp5;
im1.* = im_temp5;
re2.* = re_temp6;
im2.* = im_temp6;
re3.* = re_temp7;
im3.* = im_temp7;
}
fn fft4(re: []F32x4, im: []F32x4, count: u32) void {
assert(std.math.isPowerOfTwo(count));
assert(re.len >= count);
assert(im.len >= count);
var index: u32 = 0;
while (index < count) : (index += 1) {
fftButterflyDit4_1(&re[index], &im[index]);
}
}
test "zmath.fft4" {
const epsilon = 0.0001;
var re = [_]F32x4{f32x4(1.0, 2.0, 3.0, 4.0)};
var im = [_]F32x4{f32x4s(0.0)};
fft4(re[0..], im[0..], 1);
var re_uns: [1]F32x4 = undefined;
var im_uns: [1]F32x4 = undefined;
fftUnswizzle(re[0..], re_uns[0..]);
fftUnswizzle(im[0..], im_uns[0..]);
try expect(approxEqAbs(re_uns[0], f32x4(10.0, -2.0, -2.0, -2.0), epsilon));
try expect(approxEqAbs(im_uns[0], f32x4(0.0, 2.0, 0.0, -2.0), epsilon));
}
fn fft8(re: []F32x4, im: []F32x4, count: u32) void {
assert(std.math.isPowerOfTwo(count));
assert(re.len >= 2 * count);
assert(im.len >= 2 * count);
var index: u32 = 0;
while (index < count) : (index += 1) {
var pre = re[index * 2 ..];
var pim = im[index * 2 ..];
var odds_re = @shuffle(f32, pre[0], pre[1], [4]i32{ 1, 3, ~@as(i32, 1), ~@as(i32, 3) });
var evens_re = @shuffle(f32, pre[0], pre[1], [4]i32{ 0, 2, ~@as(i32, 0), ~@as(i32, 2) });
var odds_im = @shuffle(f32, pim[0], pim[1], [4]i32{ 1, 3, ~@as(i32, 1), ~@as(i32, 3) });
var evens_im = @shuffle(f32, pim[0], pim[1], [4]i32{ 0, 2, ~@as(i32, 0), ~@as(i32, 2) });
fftButterflyDit4_1(&odds_re, &odds_im);
fftButterflyDit4_1(&evens_re, &evens_im);
{
const re_im = cmulSoa(
odds_re,
odds_im,
f32x4(1.0, 0.70710677, 0.0, -0.70710677),
f32x4(0.0, -0.70710677, -1.0, -0.70710677),
);
pre[0] = evens_re + re_im[0];
pim[0] = evens_im + re_im[1];
}
{
const re_im = cmulSoa(
odds_re,
odds_im,
f32x4(-1.0, -0.70710677, 0.0, 0.70710677),
f32x4(0.0, 0.70710677, 1.0, 0.70710677),
);
pre[1] = evens_re + re_im[0];
pim[1] = evens_im + re_im[1];
}
}
}
test "zmath.fft8" {
const epsilon = 0.0001;
var re = [_]F32x4{ f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0) };
var im = [_]F32x4{ f32x4s(0.0), f32x4s(0.0) };
fft8(re[0..], im[0..], 1);
var re_uns: [2]F32x4 = undefined;
var im_uns: [2]F32x4 = undefined;
fftUnswizzle(re[0..], re_uns[0..]);
fftUnswizzle(im[0..], im_uns[0..]);
try expect(approxEqAbs(re_uns[0], f32x4(36.0, -4.0, -4.0, -4.0), epsilon));
try expect(approxEqAbs(re_uns[1], f32x4(-4.0, -4.0, -4.0, -4.0), epsilon));
try expect(approxEqAbs(im_uns[0], f32x4(0.0, 9.656854, 4.0, 1.656854), epsilon));
try expect(approxEqAbs(im_uns[1], f32x4(0.0, -1.656854, -4.0, -9.656854), epsilon));
}
fn fft16(re: []F32x4, im: []F32x4, count: u32) void {
assert(std.math.isPowerOfTwo(count));
assert(re.len >= 4 * count);
assert(im.len >= 4 * count);
const static = struct {
const unity_table_re = [4]F32x4{
f32x4(1.0, 1.0, 1.0, 1.0),
f32x4(1.0, 0.92387950, 0.70710677, 0.38268343),
f32x4(1.0, 0.70710677, -4.3711388e-008, -0.70710677),
f32x4(1.0, 0.38268343, -0.70710677, -0.92387950),
};
const unity_table_im = [4]F32x4{
f32x4(-0.0, -0.0, -0.0, -0.0),
f32x4(-0.0, -0.38268343, -0.70710677, -0.92387950),
f32x4(-0.0, -0.70710677, -1.0, -0.70710677),
f32x4(-0.0, -0.92387950, -0.70710677, 0.38268343),
};
};
var index: u32 = 0;
while (index < count) : (index += 1) {
fftButterflyDit4_4(
&re[index * 4],
&re[index * 4 + 1],
&re[index * 4 + 2],
&re[index * 4 + 3],
&im[index * 4],
&im[index * 4 + 1],
&im[index * 4 + 2],
&im[index * 4 + 3],
static.unity_table_re[0..],
static.unity_table_im[0..],
1,
true,
);
}
}
test "zmath.fft16" {
const epsilon = 0.0001;
var re = [_]F32x4{
f32x4(1.0, 2.0, 3.0, 4.0),
f32x4(5.0, 6.0, 7.0, 8.0),
f32x4(9.0, 10.0, 11.0, 12.0),
f32x4(13.0, 14.0, 15.0, 16.0),
};
var im = [_]F32x4{ f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0) };
fft16(re[0..], im[0..], 1);
var re_uns: [4]F32x4 = undefined;
var im_uns: [4]F32x4 = undefined;
fftUnswizzle(re[0..], re_uns[0..]);
fftUnswizzle(im[0..], im_uns[0..]);
try expect(approxEqAbs(re_uns[0], f32x4(136.0, -8.0, -8.0, -8.0), epsilon));
try expect(approxEqAbs(re_uns[1], f32x4(-8.0, -8.0, -8.0, -8.0), epsilon));
try expect(approxEqAbs(re_uns[2], f32x4(-8.0, -8.0, -8.0, -8.0), epsilon));
try expect(approxEqAbs(re_uns[3], f32x4(-8.0, -8.0, -8.0, -8.0), epsilon));
try expect(approxEqAbs(im_uns[0], f32x4(0.0, 40.218716, 19.313708, 11.972846), epsilon));
try expect(approxEqAbs(im_uns[1], f32x4(8.0, 5.345429, 3.313708, 1.591299), epsilon));
try expect(approxEqAbs(im_uns[2], f32x4(0.0, -1.591299, -3.313708, -5.345429), epsilon));
try expect(approxEqAbs(im_uns[3], f32x4(-8.0, -11.972846, -19.313708, -40.218716), epsilon));
}
fn fftN(re: []F32x4, im: []F32x4, unity_table: []const F32x4, length: u32, count: u32) void {
assert(length > 16);
assert(std.math.isPowerOfTwo(length));
assert(std.math.isPowerOfTwo(count));
assert(re.len >= length * count / 4);
assert(re.len == im.len);
const total = count * length;
const total_vectors = total / 4;
const stage_vectors = length / 4;
const stage_vectors_mask = stage_vectors - 1;
const stride = length / 16;
const stride_mask = stride - 1;
const stride_inv_mask = ~stride_mask;
var unity_table_re = unity_table;
var unity_table_im = unity_table[length / 4 ..];
var index: u32 = 0;
while (index < total_vectors / 4) : (index += 1) {
const n = (index & stride_inv_mask) * 4 + (index & stride_mask);
fftButterflyDit4_4(
&re[n],
&re[n + stride],
&re[n + stride * 2],
&re[n + stride * 3],
&im[n],
&im[n + stride],
&im[n + stride * 2],
&im[n + stride * 3],
unity_table_re[(n & stage_vectors_mask)..],
unity_table_im[(n & stage_vectors_mask)..],
stride,
false,
);
}
if (length > 16 * 4) {
fftN(re, im, unity_table[(length / 2)..], length / 4, count * 4);
} else if (length == 16 * 4) {
fft16(re, im, count * 4);
} else if (length == 8 * 4) {
fft8(re, im, count * 4);
} else if (length == 4 * 4) {
fft4(re, im, count * 4);
}
}
test "zmath.fftN" {
var unity_table: [128]F32x4 = undefined;
const epsilon = 0.0001;
// 32 samples
{
var re = [_]F32x4{
f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0),
f32x4(9.0, 10.0, 11.0, 12.0), f32x4(13.0, 14.0, 15.0, 16.0),
f32x4(17.0, 18.0, 19.0, 20.0), f32x4(21.0, 22.0, 23.0, 24.0),
f32x4(25.0, 26.0, 27.0, 28.0), f32x4(29.0, 30.0, 31.0, 32.0),
};
var im = [_]F32x4{
f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0),
f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0),
};
fftInitUnityTable(unity_table[0..32]);
fft(re[0..], im[0..], unity_table[0..32]);
try expect(approxEqAbs(re[0], f32x4(528.0, -16.0, -16.0, -16.0), epsilon));
try expect(approxEqAbs(re[1], f32x4(-16.0, -16.0, -16.0, -16.0), epsilon));
try expect(approxEqAbs(re[2], f32x4(-16.0, -16.0, -16.0, -16.0), epsilon));
try expect(approxEqAbs(re[3], f32x4(-16.0, -16.0, -16.0, -16.0), epsilon));
try expect(approxEqAbs(re[4], f32x4(-16.0, -16.0, -16.0, -16.0), epsilon));
try expect(approxEqAbs(re[5], f32x4(-16.0, -16.0, -16.0, -16.0), epsilon));
try expect(approxEqAbs(re[6], f32x4(-16.0, -16.0, -16.0, -16.0), epsilon));
try expect(approxEqAbs(re[7], f32x4(-16.0, -16.0, -16.0, -16.0), epsilon));
try expect(approxEqAbs(im[0], f32x4(0.0, 162.450726, 80.437432, 52.744931), epsilon));
try expect(approxEqAbs(im[1], f32x4(38.627417, 29.933895, 23.945692, 19.496056), epsilon));
try expect(approxEqAbs(im[2], f32x4(16.0, 13.130861, 10.690858, 8.552178), epsilon));
try expect(approxEqAbs(im[3], f32x4(6.627417, 4.853547, 3.182598, 1.575862), epsilon));
try expect(approxEqAbs(im[4], f32x4(0.0, -1.575862, -3.182598, -4.853547), epsilon));
try expect(approxEqAbs(im[5], f32x4(-6.627417, -8.552178, -10.690858, -13.130861), epsilon));
try expect(approxEqAbs(im[6], f32x4(-16.0, -19.496056, -23.945692, -29.933895), epsilon));
try expect(approxEqAbs(im[7], f32x4(-38.627417, -52.744931, -80.437432, -162.450726), epsilon));
}
// 64 samples
{
var re = [_]F32x4{
f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0),
f32x4(9.0, 10.0, 11.0, 12.0), f32x4(13.0, 14.0, 15.0, 16.0),
f32x4(17.0, 18.0, 19.0, 20.0), f32x4(21.0, 22.0, 23.0, 24.0),
f32x4(25.0, 26.0, 27.0, 28.0), f32x4(29.0, 30.0, 31.0, 32.0),
f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0),
f32x4(9.0, 10.0, 11.0, 12.0), f32x4(13.0, 14.0, 15.0, 16.0),
f32x4(17.0, 18.0, 19.0, 20.0), f32x4(21.0, 22.0, 23.0, 24.0),
f32x4(25.0, 26.0, 27.0, 28.0), f32x4(29.0, 30.0, 31.0, 32.0),
};
var im = [_]F32x4{
f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0),
f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0),
f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0),
f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0),
};
fftInitUnityTable(unity_table[0..64]);
fft(re[0..], im[0..], unity_table[0..64]);
try expect(approxEqAbs(re[0], f32x4(1056.0, 0.0, -32.0, 0.0), epsilon));
var i: u32 = 1;
while (i < 16) : (i += 1) {
try expect(approxEqAbs(re[i], f32x4(-32.0, 0.0, -32.0, 0.0), epsilon));
}
const expected = [_]f32{
0.0, 0.0, 324.901452, 0.000000, 160.874864, 0.0, 105.489863, 0.000000,
77.254834, 0.0, 59.867789, 0.0, 47.891384, 0.0, 38.992113, 0.0,
32.000000, 0.000000, 26.261721, 0.000000, 21.381716, 0.000000, 17.104356, 0.000000,
13.254834, 0.000000, 9.707094, 0.000000, 6.365196, 0.000000, 3.151725, 0.000000,
0.000000, 0.000000, -3.151725, 0.000000, -6.365196, 0.000000, -9.707094, 0.000000,
-13.254834, 0.000000, -17.104356, 0.000000, -21.381716, 0.000000, -26.261721, 0.000000,
-32.000000, 0.000000, -38.992113, 0.000000, -47.891384, 0.000000, -59.867789, 0.000000,
-77.254834, 0.000000, -105.489863, 0.000000, -160.874864, 0.000000, -324.901452, 0.000000,
};
for (expected) |e, ie| {
try expect(std.math.approxEqAbs(f32, e, im[(ie / 4)][ie % 4], epsilon));
}
}
// 128 samples
{
var re = [_]F32x4{
f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0),
f32x4(9.0, 10.0, 11.0, 12.0), f32x4(13.0, 14.0, 15.0, 16.0),
f32x4(17.0, 18.0, 19.0, 20.0), f32x4(21.0, 22.0, 23.0, 24.0),
f32x4(25.0, 26.0, 27.0, 28.0), f32x4(29.0, 30.0, 31.0, 32.0),
f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0),
f32x4(9.0, 10.0, 11.0, 12.0), f32x4(13.0, 14.0, 15.0, 16.0),
f32x4(17.0, 18.0, 19.0, 20.0), f32x4(21.0, 22.0, 23.0, 24.0),
f32x4(25.0, 26.0, 27.0, 28.0), f32x4(29.0, 30.0, 31.0, 32.0),
f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0),
f32x4(9.0, 10.0, 11.0, 12.0), f32x4(13.0, 14.0, 15.0, 16.0),
f32x4(17.0, 18.0, 19.0, 20.0), f32x4(21.0, 22.0, 23.0, 24.0),
f32x4(25.0, 26.0, 27.0, 28.0), f32x4(29.0, 30.0, 31.0, 32.0),
f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0),
f32x4(9.0, 10.0, 11.0, 12.0), f32x4(13.0, 14.0, 15.0, 16.0),
f32x4(17.0, 18.0, 19.0, 20.0), f32x4(21.0, 22.0, 23.0, 24.0),
f32x4(25.0, 26.0, 27.0, 28.0), f32x4(29.0, 30.0, 31.0, 32.0),
};
var im = [_]F32x4{
f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0),
f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0),
f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0),
f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0),
f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0),
f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0),
f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0),
f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0),
};
fftInitUnityTable(unity_table[0..128]);
fft(re[0..], im[0..], unity_table[0..128]);
try expect(approxEqAbs(re[0], f32x4(2112.0, 0.0, 0.0, 0.0), epsilon));
var i: u32 = 1;
while (i < 32) : (i += 1) {
try expect(approxEqAbs(re[i], f32x4(-64.0, 0.0, 0.0, 0.0), epsilon));
}
const expected = [_]f32{
0.000000, 0.000000, 0.000000, 0.000000, 649.802905, 0.000000, 0.000000, 0.000000,
321.749727, 0.000000, 0.000000, 0.000000, 210.979725, 0.000000, 0.000000, 0.000000,
154.509668, 0.000000, 0.000000, 0.000000, 119.735578, 0.000000, 0.000000, 0.000000,
95.782769, 0.000000, 0.000000, 0.000000, 77.984226, 0.000000, 0.000000, 0.000000,
64.000000, 0.000000, 0.000000, 0.000000, 52.523443, 0.000000, 0.000000, 0.000000,
42.763433, 0.000000, 0.000000, 0.000000, 34.208713, 0.000000, 0.000000, 0.000000,
26.509668, 0.000000, 0.000000, 0.000000, 19.414188, 0.000000, 0.000000, 0.000000,
12.730392, 0.000000, 0.000000, 0.000000, 6.303450, 0.000000, 0.000000, 0.000000,
0.000000, 0.000000, 0.000000, 0.000000, -6.303450, 0.000000, 0.000000, 0.000000,
-12.730392, 0.000000, 0.000000, 0.000000, -19.414188, 0.000000, 0.000000, 0.000000,
-26.509668, 0.000000, 0.000000, 0.000000, -34.208713, 0.000000, 0.000000, 0.000000,
-42.763433, 0.000000, 0.000000, 0.000000, -52.523443, 0.000000, 0.000000, 0.000000,
-64.000000, 0.000000, 0.000000, 0.000000, -77.984226, 0.000000, 0.000000, 0.000000,
-95.782769, 0.000000, 0.000000, 0.000000, -119.735578, 0.000000, 0.000000, 0.000000,
-154.509668, 0.000000, 0.000000, 0.000000, -210.979725, 0.000000, 0.000000, 0.000000,
-321.749727, 0.000000, 0.000000, 0.000000, -649.802905, 0.000000, 0.000000, 0.000000,
};
for (expected) |e, ie| {
try expect(std.math.approxEqAbs(f32, e, im[(ie / 4)][ie % 4], epsilon));
}
}
}
fn fftUnswizzle(input: []const F32x4, output: []F32x4) void {
assert(std.math.isPowerOfTwo(input.len));
assert(input.len == output.len);
assert(input.ptr != output.ptr);
const log2_length = std.math.log2_int(usize, input.len * 4);
assert(log2_length >= 2);
const length = input.len;
const f32_output = @ptrCast([*]f32, output.ptr)[0 .. output.len * 4];
const static = struct {
const swizzle_table = [256]u8{
0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0, 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4, 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8, 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC, 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1, 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5, 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9, 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD, 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2, 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6, 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA, 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE, 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3, 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7, 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB, 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF, 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF,
};
};
if ((log2_length & 1) == 0) {
const rev32 = @intCast(u6, 32 - log2_length);
var index: usize = 0;
while (index < length) : (index += 1) {
const n = index * 4;
const addr =
(@intCast(usize, static.swizzle_table[n & 0xff]) << 24) |
(@intCast(usize, static.swizzle_table[(n >> 8) & 0xff]) << 16) |
(@intCast(usize, static.swizzle_table[(n >> 16) & 0xff]) << 8) |
@intCast(usize, static.swizzle_table[(n >> 24) & 0xff]);
f32_output[addr >> rev32] = input[index][0];
f32_output[(0x40000000 | addr) >> rev32] = input[index][1];
f32_output[(0x80000000 | addr) >> rev32] = input[index][2];
f32_output[(0xC0000000 | addr) >> rev32] = input[index][3];
}
} else {
const rev7 = @as(usize, 1) << @intCast(u6, log2_length - 3);
const rev32 = @intCast(u6, 32 - (log2_length - 3));
var index: usize = 0;
while (index < length) : (index += 1) {
const n = index / 2;
var addr =
(((@intCast(usize, static.swizzle_table[n & 0xff]) << 24) |
(@intCast(usize, static.swizzle_table[(n >> 8) & 0xff]) << 16) |
(@intCast(usize, static.swizzle_table[(n >> 16) & 0xff]) << 8) |
(@intCast(usize, static.swizzle_table[(n >> 24) & 0xff]))) >> rev32) |
((index & 1) * rev7 * 4);
f32_output[addr] = input[index][0];
addr += rev7;
f32_output[addr] = input[index][1];
addr += rev7;
f32_output[addr] = input[index][2];
addr += rev7;
f32_output[addr] = input[index][3];
}
}
}
pub fn fftInitUnityTable(out_unity_table: []F32x4) void {
assert(std.math.isPowerOfTwo(out_unity_table.len));
assert(out_unity_table.len >= 32 and out_unity_table.len <= 512);
var unity_table = out_unity_table;
const v0123 = f32x4(0.0, 1.0, 2.0, 3.0);
var length = out_unity_table.len / 4;
var vlstep = f32x4s(0.5 * math.pi / @intToFloat(f32, length));
while (true) {
length /= 4;
var vjp = v0123;
var j: u32 = 0;
while (j < length) : (j += 1) {
unity_table[j] = f32x4s(1.0);
unity_table[j + length * 4] = f32x4s(0.0);
var vls = vjp * vlstep;
var sin_cos = sincos(vls);
unity_table[j + length] = sin_cos[1];
unity_table[j + length * 5] = sin_cos[0] * f32x4s(-1.0);
var vijp = vjp + vjp;
vls = vijp * vlstep;
sin_cos = sincos(vls);
unity_table[j + length * 2] = sin_cos[1];
unity_table[j + length * 6] = sin_cos[0] * f32x4s(-1.0);
vijp = vijp + vjp;
vls = vijp * vlstep;
sin_cos = sincos(vls);
unity_table[j + length * 3] = sin_cos[1];
unity_table[j + length * 7] = sin_cos[0] * f32x4s(-1.0);
vjp += f32x4s(4.0);
}
vlstep *= f32x4s(4.0);
unity_table = unity_table[8 * length ..];
if (length <= 4)
break;
}
}
pub fn fft(re: []F32x4, im: []F32x4, unity_table: []const F32x4) void {
const length = @intCast(u32, re.len * 4);
assert(std.math.isPowerOfTwo(length));
assert(length >= 4 and length <= 512);
assert(re.len == im.len);
var re_temp_storage: [128]F32x4 = undefined;
var im_temp_storage: [128]F32x4 = undefined;
var re_temp = re_temp_storage[0..re.len];
var im_temp = im_temp_storage[0..im.len];
std.mem.copy(F32x4, re_temp, re);
std.mem.copy(F32x4, im_temp, im);
if (length > 16) {
assert(unity_table.len == length);
fftN(re_temp, im_temp, unity_table, length, 1);
} else if (length == 16) {
fft16(re_temp, im_temp, 1);
} else if (length == 8) {
fft8(re_temp, im_temp, 1);
} else if (length == 4) {
fft4(re_temp, im_temp, 1);
}
fftUnswizzle(re_temp, re);
fftUnswizzle(im_temp, im);
}
pub fn ifft(re: []F32x4, im: []const F32x4, unity_table: []const F32x4) void {
const length = @intCast(u32, re.len * 4);
assert(std.math.isPowerOfTwo(length));
assert(length >= 4 and length <= 512);
assert(re.len == im.len);
var re_temp_storage: [128]F32x4 = undefined;
var im_temp_storage: [128]F32x4 = undefined;
var re_temp = re_temp_storage[0..re.len];
var im_temp = im_temp_storage[0..im.len];
const rnp = f32x4s(1.0 / @intToFloat(f32, length));
const rnm = f32x4s(-1.0 / @intToFloat(f32, length));
for (re) |_, i| {
re_temp[i] = re[i] * rnp;
im_temp[i] = im[i] * rnm;
}
if (length > 16) {
assert(unity_table.len == length);
fftN(re_temp, im_temp, unity_table, length, 1);
} else if (length == 16) {
fft16(re_temp, im_temp, 1);
} else if (length == 8) {
fft8(re_temp, im_temp, 1);
} else if (length == 4) {
fft4(re_temp, im_temp, 1);
}
fftUnswizzle(re_temp, re);
}
test "zmath.ifft" {
var unity_table: [512]F32x4 = undefined;
const epsilon = 0.0001;
// 64 samples
{
var re = [_]F32x4{
f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0),
f32x4(9.0, 10.0, 11.0, 12.0), f32x4(13.0, 14.0, 15.0, 16.0),
f32x4(17.0, 18.0, 19.0, 20.0), f32x4(21.0, 22.0, 23.0, 24.0),
f32x4(25.0, 26.0, 27.0, 28.0), f32x4(29.0, 30.0, 31.0, 32.0),
f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0),
f32x4(9.0, 10.0, 11.0, 12.0), f32x4(13.0, 14.0, 15.0, 16.0),
f32x4(17.0, 18.0, 19.0, 20.0), f32x4(21.0, 22.0, 23.0, 24.0),
f32x4(25.0, 26.0, 27.0, 28.0), f32x4(29.0, 30.0, 31.0, 32.0),
};
var im = [_]F32x4{
f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0),
f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0),
f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0),
f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0),
};
fftInitUnityTable(unity_table[0..64]);
fft(re[0..], im[0..], unity_table[0..64]);
try expect(approxEqAbs(re[0], f32x4(1056.0, 0.0, -32.0, 0.0), epsilon));
var i: u32 = 1;
while (i < 16) : (i += 1) {
try expect(approxEqAbs(re[i], f32x4(-32.0, 0.0, -32.0, 0.0), epsilon));
}
ifft(re[0..], im[0..], unity_table[0..64]);
try expect(approxEqAbs(re[0], f32x4(1.0, 2.0, 3.0, 4.0), epsilon));
try expect(approxEqAbs(re[1], f32x4(5.0, 6.0, 7.0, 8.0), epsilon));
try expect(approxEqAbs(re[2], f32x4(9.0, 10.0, 11.0, 12.0), epsilon));
try expect(approxEqAbs(re[3], f32x4(13.0, 14.0, 15.0, 16.0), epsilon));
try expect(approxEqAbs(re[4], f32x4(17.0, 18.0, 19.0, 20.0), epsilon));
try expect(approxEqAbs(re[5], f32x4(21.0, 22.0, 23.0, 24.0), epsilon));
try expect(approxEqAbs(re[6], f32x4(25.0, 26.0, 27.0, 28.0), epsilon));
try expect(approxEqAbs(re[7], f32x4(29.0, 30.0, 31.0, 32.0), epsilon));
}
// 512 samples
{
var re: [128]F32x4 = undefined;
var im = [_]F32x4{f32x4s(0.0)} ** 128;
for (re) |*v, i| {
const f = @intToFloat(f32, i * 4);
v.* = f32x4(f + 1.0, f + 2.0, f + 3.0, f + 4.0);
}
fftInitUnityTable(unity_table[0..512]);
fft(re[0..], im[0..], unity_table[0..512]);
for (re) |v, i| {
const f = @intToFloat(f32, i * 4);
try expect(!approxEqAbs(v, f32x4(f + 1.0, f + 2.0, f + 3.0, f + 4.0), epsilon));
}
ifft(re[0..], im[0..], unity_table[0..512]);
for (re) |v, i| {
const f = @intToFloat(f32, i * 4);
try expect(approxEqAbs(v, f32x4(f + 1.0, f + 2.0, f + 3.0, f + 4.0), epsilon));
}
}
}
// ------------------------------------------------------------------------------
//
// Private functions and constants
//
// ------------------------------------------------------------------------------
const f32x4_0x8000_0000: F32x4 = splatInt(F32x4, 0x8000_0000);
const f32x4_0x7fff_ffff: F32x4 = splatInt(F32x4, 0x7fff_ffff);
const f32x4_inf: F32x4 = splat(F32x4, math.inf_f32);
const u32x4_mask3: U32x4 = U32x4{ 0xffff_ffff, 0xffff_ffff, 0xffff_ffff, 0 };
const u32x4_mask2: U32x4 = U32x4{ 0xffff_ffff, 0xffff_ffff, 0, 0 };
const u32x4_sign_mask1: U32x4 = U32x4{ 0x8000_0000, 0, 0, 0 };
inline fn splatNegativeZero(comptime T: type) T {
return @splat(veclen(T), @bitCast(f32, @as(u32, 0x8000_0000)));
}
inline fn splatNoFraction(comptime T: type) T {
return @splat(veclen(T), @as(f32, 8_388_608.0));
}
inline fn splatAbsMask(comptime T: type) T {
return @splat(veclen(T), @bitCast(f32, @as(u32, 0x7fff_ffff)));
}
fn floatToIntAndBack(v: anytype) @TypeOf(v) {
// This routine won't handle nan, inf and numbers greater than 8_388_608.0 (will generate undefined values)
@setRuntimeSafety(false);
const T = @TypeOf(v);
const len = veclen(T);
var vi32: [len]i32 = undefined;
comptime var i: u32 = 0;
// vcvttps2dq
inline while (i < len) : (i += 1) {
vi32[i] = @floatToInt(i32, v[i]);
}
var vf32: [len]f32 = undefined;
i = 0;
// vcvtdq2ps
inline while (i < len) : (i += 1) {
vf32[i] = @intToFloat(f32, vi32[i]);
}
return vf32;
}
test "zmath.floatToIntAndBack" {
{
const v = floatToIntAndBack(F32x4{ 1.1, 2.9, 3.0, -4.5 });
try expect(approxEqAbs(v, F32x4{ 1.0, 2.0, 3.0, -4.0 }, 0.0));
}
{
const v = floatToIntAndBack(F32x8{ 1.1, 2.9, 3.0, -4.5, 2.5, -2.5, 1.1, -100.2 });
try expect(approxEqAbs(v, F32x8{ 1.0, 2.0, 3.0, -4.0, 2.0, -2.0, 1.0, -100.0 }, 0.0));
}
{
const v = floatToIntAndBack(F32x4{ math.inf_f32, 2.9, math.nan_f32, math.qnan_f32 });
try expect(v[1] == 2.0);
}
}
pub fn approxEqAbs(v0: anytype, v1: anytype, eps: f32) bool {
const T = @TypeOf(v0, v1);
comptime var i: comptime_int = 0;
inline while (i < veclen(T)) : (i += 1) {
if (!math.approxEqAbs(f32, v0[i], v1[i], eps)) {
return false;
}
}
return true;
}
// ------------------------------------------------------------------------------
// This software is available under 2 licenses -- choose whichever you prefer.
// ------------------------------------------------------------------------------
// ALTERNATIVE A - MIT License
// Copyright (c) 2022 <NAME>
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// ------------------------------------------------------------------------------
// ALTERNATIVE B - Public Domain (www.unlicense.org)
// This is free and unencumbered software released into the public domain.
// Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
// software, either in source code form or as a compiled binary, for any purpose,
// commercial or non-commercial, and by any means.
// In jurisdictions that recognize copyright laws, the author or authors of this
// software dedicate any and all copyright interest in the software to the public
// domain. We make this dedication for the benefit of the public at large and to
// the detriment of our heirs and successors. We intend this dedication to be an
// overt act of relinquishment in perpetuity of all present and future rights to
// this software under copyright law.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ------------------------------------------------------------------------------ | libs/zmath/zmath.zig |
const std = @import("std");
const input = @embedFile("day04.txt");
const Board = struct {
grid: [5][5]u8,
marked: u25,
};
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = &gpa.allocator;
var iter = std.mem.split(u8, input, "\n\n");
const nums: []u8 = result: {
var list = std.ArrayList(u8).init(allocator);
var nums_iter = std.mem.split(u8, iter.next().?, ",");
while (nums_iter.next()) |num_str| {
try list.append(try std.fmt.parseInt(u8, num_str, 10));
}
break :result list.toOwnedSlice();
};
defer allocator.free(nums);
const boards: []Board = result: {
var list = std.ArrayList(Board).init(allocator);
while (iter.next()) |board_str| {
var board: Board = undefined;
try parseBoard(board_str, &board);
try list.append(board);
}
break :result list.toOwnedSlice();
};
defer allocator.free(boards);
var bingo_count: u32 = 0;
var first_found_board: Board = undefined;
var first_found_num: u8 = undefined;
var last_found_board: Board = undefined;
var last_found_num: u8 = undefined;
for (nums) |num| {
for (boards) |*board| {
if (isBingo(board.marked)) continue;
markNum(board, num);
if (isBingo(board.marked)) {
bingo_count += 1;
if (bingo_count == 1) {
first_found_board = board.*;
first_found_num = num;
}
if (bingo_count == boards.len) {
last_found_board = board.*;
last_found_num = num;
}
}
}
}
std.debug.print("Part 1: {d}\n", .{countUnmarked(first_found_board) * first_found_num});
std.debug.print("Part 2: {d}\n", .{countUnmarked(last_found_board) * last_found_num});
}
fn parseBoard(board_str: []const u8, board: *Board) !void {
var rows = std.mem.split(u8, board_str, "\n");
var row_idx: usize = 0;
while (rows.next()) |row_str| : (row_idx += 1) {
var cols = std.mem.tokenize(u8, row_str, " ");
var col_idx: usize = 0;
while (cols.next()) |col_str| : (col_idx += 1) {
const n = try std.fmt.parseInt(u8, col_str, 10);
board.grid[row_idx][col_idx] = n;
}
}
board.marked = 0;
}
fn printBoard(board: Board) void {
for (board.grid) |row, row_idx| {
for (row) |n, col_idx| {
if (isMarked(board.marked, row_idx, col_idx)) {
std.debug.print("\x1b[41;1m{d:2}\x1b[0m ", .{n});
} else {
std.debug.print("{d:2} ", .{n});
}
}
std.debug.print("\n", .{});
}
}
fn isMarked(marked: u25, row_idx: usize, col_idx: usize) bool {
var nbit = row_idx * 5 + col_idx;
return marked & @as(u25, 1) << @intCast(u5, nbit) != 0;
}
fn markNum(board: *Board, num: u8) void {
for (board.grid) |row, row_idx| {
for (row) |n, col_idx| {
if (n == num) {
mark(&board.marked, row_idx, col_idx);
}
}
}
}
fn mark(marked: *u25, row_idx: usize, col_idx: usize) void {
var nbit = row_idx * 5 + col_idx;
marked.* |= @as(u25, 1) << @intCast(u5, nbit);
}
const bingo_patterns = [_]u25{
0b11111_00000_00000_00000_00000,
0b00000_11111_00000_00000_00000,
0b00000_00000_11111_00000_00000,
0b00000_00000_00000_11111_00000,
0b00000_00000_00000_00000_11111,
0b10000_10000_10000_10000_10000,
0b01000_01000_01000_01000_01000,
0b00100_00100_00100_00100_00100,
0b00010_00010_00010_00010_00010,
0b00001_00001_00001_00001_00001,
};
fn isBingo(marked: u25) bool {
for (bingo_patterns) |bingo_pattern| {
if (marked & bingo_pattern == bingo_pattern) return true;
}
return false;
}
fn countUnmarked(board: Board) u32 {
var unmarked_sum: u32 = 0;
for (board.grid) |row, row_idx| {
for (row) |n, col_idx| {
if (!isMarked(board.marked, row_idx, col_idx)) {
unmarked_sum += n;
}
}
}
return unmarked_sum;
} | 2021/day04.zig |
const std = @import("std");
const assert = std.debug.assert;
const tools = @import("tools");
fn collapse(input: []u8, tmp: []u8) usize {
const bufs = [_][]u8{ input, tmp };
var pingpong: u32 = 0;
var len = input.len;
var changed = true;
while (changed) {
const in = bufs[pingpong][0..len];
const out = bufs[1 - pingpong];
pingpong = 1 - pingpong;
len = 0;
changed = false;
var prev: u8 = '.';
for (in) |c| {
if (prev == '.') {
prev = c;
} else if (c == (prev + 'A') - 'a' or c == (prev + 'a') - 'A') {
changed = true;
prev = '.';
} else {
out[len] = prev;
len += 1;
prev = c;
}
}
if (prev != '.') {
out[len] = prev;
len += 1;
}
}
return len;
}
pub fn run(input: []const u8, allocator: std.mem.Allocator) ![2][]const u8 {
// part1
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const ans1 = ans: {
const bufs = [_][]u8{ try arena.allocator().alloc(u8, input.len), try arena.allocator().alloc(u8, input.len) };
std.mem.copy(u8, bufs[0], input);
const len = collapse(bufs[0], bufs[1]);
break :ans len;
};
// part2
const ans2 = ans: {
const bufs = [_][]u8{ try arena.allocator().alloc(u8, input.len), try arena.allocator().alloc(u8, input.len) };
var bestLen = input.len;
for ("abcdefghijklmnopqrstuvwxyz") |letter| {
const buf = bufs[0];
var l: usize = 0;
for (input) |c| {
if (c == (letter + 'A') - 'a' or c == letter)
continue;
buf[l] = c;
l += 1;
}
const newLen = collapse(buf[0..l], bufs[1]);
if (newLen < bestLen)
bestLen = newLen;
}
break :ans bestLen;
};
return [_][]const u8{
try std.fmt.allocPrint(allocator, "{}", .{ans1}),
try std.fmt.allocPrint(allocator, "{}", .{ans2}),
};
}
pub const main = tools.defaultMain("2018/input_day05.txt", run); | 2018/day05.zig |
const std = @import("std");
const Builder = std.build.Builder;
const Allocator = std.mem.Allocator;
const Sdk = @import("../Sdk.zig");
const UserConfig = Sdk.UserConfig;
// This config stores tool paths for the current machine
const build_config_dir = ".build_config";
const local_config_file = "config.json";
const print = std.debug.print;
pub fn findUserConfig(b: *Builder, versions: Sdk.ToolchainVersions) !UserConfig {
var str_buf: [5]u8 = undefined;
var config = UserConfig{};
var config_dirty: bool = false;
const local_config_path = pathConcat(b, build_config_dir, local_config_file);
const config_path = b.pathFromRoot(local_config_path);
// Check for a user config file.
if (std.fs.cwd().openFile(config_path, .{})) |file| {
defer file.close();
const bytes = file.readToEndAlloc(b.allocator, 1 * 1000 * 1000) catch |err| {
print("Unexpected error reading {s}: {s}\n", .{ config_path, @errorName(err) });
return err;
};
var stream = std.json.TokenStream.init(bytes);
if (std.json.parse(UserConfig, &stream, .{ .allocator = b.allocator })) |conf| {
config = conf;
} else |err| {
print("Could not parse {s} ({s}).\n", .{ config_path, @errorName(err) });
return err;
}
} else |err| switch (err) {
error.FileNotFound => {
config_dirty = true;
},
else => {
print("Unexpected error opening {s}: {s}\n", .{ config_path, @errorName(err) });
return err;
},
}
// Verify the user config and set new values if needed
// First the android home
if (config.android_sdk_root.len > 0) {
if (findProblemWithAndroidSdk(b, versions, config.android_sdk_root)) |problem| {
print("Invalid android root directory: {s}\n {s}\n Looking for a new one.\n", .{ config.android_sdk_root, problem });
config.android_sdk_root = "";
// N.B. Don't dirty the file for this. We don't want to nuke the file if we can't find a replacement.
}
}
if (config.android_sdk_root.len == 0) {
// try to find the android home
if (std.process.getEnvVarOwned(b.allocator, "ANDROID_HOME")) |value| {
if (value.len > 0) {
if (findProblemWithAndroidSdk(b, versions, value)) |problem| {
print("Cannot use ANDROID_HOME ({s}):\n {s}\n", .{ value, problem });
} else {
print("Using android sdk at ANDROID_HOME: {s}\n", .{value});
config.android_sdk_root = value;
config_dirty = true;
}
}
} else |err| {}
}
if (config.android_sdk_root.len == 0) {
// try to find the android home
if (std.process.getEnvVarOwned(b.allocator, "ANDROID_SDK_ROOT")) |value| {
if (value.len > 0) {
if (findProblemWithAndroidSdk(b, versions, value)) |problem| {
print("Cannot use ANDROID_SDK_ROOT ({s}):\n {s}\n", .{ value, problem });
} else {
print("Using android sdk at ANDROID_SDK_ROOT: {s}\n", .{value});
config.android_sdk_root = value;
config_dirty = true;
}
}
} else |err| {}
}
var android_studio_path: []const u8 = "";
// On windows, check for an android studio install.
// If it's present, it may have the sdk path stored in the registry.
// If not, check the default install location.
if (std.builtin.os.tag == .windows) {
const HKEY = ?*opaque {};
const LSTATUS = u32;
const DWORD = u32;
const HKEY_CLASSES_ROOT = @intToPtr(HKEY, 0x80000000);
const HKEY_CURRENT_USER = @intToPtr(HKEY, 0x80000001);
const HKEY_LOCAL_MACHINE = @intToPtr(HKEY, 0x80000002);
const HKEY_USERS = @intToPtr(HKEY, 0x80000003);
const RRF_RT_ANY: DWORD = 0xFFFF;
const RRF_RT_REG_BINARY: DWORD = 0x08;
const RRF_RT_REG_DWORD: DWORD = 0x10;
const RRF_RT_REG_EXPAND_SZ: DWORD = 0x04;
const RRF_RT_REG_MULTI_SZ: DWORD = 0x20;
const RRF_RT_REG_NONE: DWORD = 0x01;
const RRF_RT_REG_QWORD: DWORD = 0x40;
const RRF_RT_REG_SZ: DWORD = 0x02;
const RRF_RT_DWORD = RRF_RT_REG_DWORD | RRF_RT_REG_BINARY;
const RRF_RT_QWORD = RRF_RT_REG_QWORD | RRF_RT_REG_BINARY;
const RRF_NOEXPAND: DWORD = 0x10000000;
const RRF_ZEROONFAILURE: DWORD = 0x20000000;
const RRF_SUBKEY_WOW6464KEY: DWORD = 0x00010000;
const RRF_SUBKEY_WOW6432KEY: DWORD = 0x00020000;
const ERROR_SUCCESS: LSTATUS = 0;
const ERROR_MORE_DATA: LSTATUS = 234;
const reg = struct {
extern "Advapi32" fn RegOpenKeyA(key: HKEY, subKey: [*:0]const u8, result: *HKEY) LSTATUS;
extern "Advapi32" fn RegCloseKey(key: HKEY) LSTATUS;
extern "Advapi32" fn RegGetValueA(key: HKEY, subKey: ?[*:0]const u8, value: [*:0]const u8, flags: DWORD, type: ?*DWORD, data: ?*c_void, len: ?*DWORD) LSTATUS;
fn getStringAlloc(allocator: *Allocator, key: HKEY, value: [*:0]const u8) ?[]const u8 {
// query the length
var len: DWORD = 0;
var res = RegGetValueA(key, null, value, RRF_RT_REG_SZ, null, null, &len);
if (res == ERROR_SUCCESS) {
if (len == 0) {
return &[_]u8{};
}
} else if (res != ERROR_MORE_DATA) {
return null;
}
// get the data
const buffer = allocator.alloc(u8, len) catch unreachable;
len = @intCast(DWORD, buffer.len);
res = RegGetValueA(key, null, value, RRF_RT_REG_SZ, null, buffer.ptr, &len);
if (res == ERROR_SUCCESS) {
for (buffer[0..len]) |c, i| {
if (c == 0) return buffer[0..i];
}
return buffer[0..len];
}
allocator.free(buffer);
return null;
}
};
// Get the android studio registry entry
var android_studio_key: HKEY = for ([_]HKEY{ HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE }) |root_key| {
var software: HKEY = null;
if (reg.RegOpenKeyA(root_key, "software", &software) == ERROR_SUCCESS) {
defer _ = reg.RegCloseKey(software);
var android: HKEY = null;
if (reg.RegOpenKeyA(software, "Android Studio", &android) == ERROR_SUCCESS) {
if (android != null) break android;
}
}
} else null;
// Grab the paths to the android studio install and the sdk install.
if (android_studio_key != null) {
defer _ = reg.RegCloseKey(android_studio_key);
if (reg.getStringAlloc(b.allocator, android_studio_key, "Path")) |path| {
android_studio_path = path;
} else {
print("Could not get android studio path\n", .{});
}
if (reg.getStringAlloc(b.allocator, android_studio_key, "SdkPath")) |sdk_path| {
if (sdk_path.len > 0) {
if (findProblemWithAndroidSdk(b, versions, sdk_path)) |problem| {
print("Cannot use Android Studio sdk ({s}):\n {s}\n", .{ sdk_path, problem });
} else {
print("Using android sdk from Android Studio: {s}\n", .{sdk_path});
config.android_sdk_root = sdk_path;
config_dirty = true;
}
}
}
}
// If we didn't find an sdk in the registry, check the default install location.
// On windows, this is AppData/Local/Android.
if (config.android_sdk_root.len == 0) {
if (std.process.getEnvVarOwned(b.allocator, "LOCALAPPDATA")) |appdata_local| {
const sdk_path = pathConcat(b, appdata_local, "Android");
if (findProblemWithAndroidSdk(b, versions, sdk_path)) |problem| {
print("Cannot use default Android Studio SDK\n at {s}:\n {s}\n", .{ sdk_path, problem });
} else {
print("Using android sdk from Android Studio: {s}\n", .{sdk_path});
config.android_sdk_root = sdk_path;
config_dirty = true;
}
} else |err| {}
}
}
// Finally, if we still don't have an sdk, see if `adb` is on the path and try to use that.
if (config.android_sdk_root.len == 0) {
if (findProgramPath(b.allocator, "adb")) |path| {
const sep = std.fs.path.sep;
if (std.mem.lastIndexOfScalar(u8, path, sep)) |index| {
var rest = path[0..index];
const parent = "platform-tools";
if (std.mem.endsWith(u8, rest, parent) and rest[rest.len - parent.len - 1] == sep) {
const sdk_path = rest[0 .. rest.len - parent.len - 1];
if (findProblemWithAndroidSdk(b, versions, sdk_path)) |problem| {
print("Cannot use SDK near adb\n at {s}:\n {s}\n", .{ sdk_path, problem });
} else {
print("Using android sdk near adb: {s}\n", .{sdk_path});
config.android_sdk_root = sdk_path;
config_dirty = true;
}
}
}
}
}
// Next up, NDK.
if (config.android_ndk_root.len > 0) {
if (findProblemWithAndroidNdk(b, versions, config.android_ndk_root)) |problem| {
print("Saved NDK is invalid ({s})\n{s}\n", .{ config.android_ndk_root, problem });
config.android_ndk_root = "";
}
}
// first, check ANDROID_NDK_ROOT
if (config.android_ndk_root.len == 0) {
if (std.process.getEnvVarOwned(b.allocator, "ANDROID_NDK_ROOT")) |value| {
if (value.len > 0) {
if (findProblemWithAndroidNdk(b, versions, value)) |problem| {
print("Cannot use ANDROID_NDK_ROOT ({s}):\n {s}\n", .{ value, problem });
} else {
print("Using android ndk at ANDROID_NDK_ROOT: {s}\n", .{value});
config.android_ndk_root = value;
config_dirty = true;
}
}
} else |err| {}
}
// Then check for a side-by-side install
if (config.android_ndk_root.len == 0) {
if (config.android_sdk_root.len > 0) {
const ndk_root = std.fs.path.join(b.allocator, &[_][]const u8{
config.android_sdk_root,
"ndk",
versions.ndk_version,
}) catch unreachable;
if (findProblemWithAndroidNdk(b, versions, ndk_root)) |problem| {
print("Cannot use side by side NDK ({s}):\n {s}\n", .{ ndk_root, problem });
} else {
print("Using side by side NDK install: {s}\n", .{ndk_root});
config.android_ndk_root = ndk_root;
config_dirty = true;
}
}
}
// Finally, we need to find the JDK, for jarsigner.
if (config.java_home.len > 0) {
if (findProblemWithJdk(b, config.java_home)) |problem| {
print("Cannot use configured java install {s}: {s}\n", .{ config.java_home, problem });
config.java_home = "";
}
}
// Check the JAVA_HOME variable
if (config.java_home.len == 0) {
if (std.process.getEnvVarOwned(b.allocator, "JAVA_HOME")) |value| {
if (value.len > 0) {
if (findProblemWithJdk(b, value)) |problem| {
print("Cannot use JAVA_HOME ({s}):\n {s}\n", .{ value, problem });
} else {
print("Using java JAVA_HOME: {s}\n", .{value});
config.java_home = value;
config_dirty = true;
}
}
} else |err| {}
}
// Look for `where jarsigner`
if (config.java_home.len == 0) {
if (findProgramPath(b.allocator, "jarsigner")) |path| {
const sep = std.fs.path.sep;
if (std.mem.lastIndexOfScalar(u8, path, sep)) |last_slash| {
if (std.mem.lastIndexOfScalar(u8, path[0..last_slash], sep)) |second_slash| {
const home = path[0..second_slash];
if (findProblemWithJdk(b, home)) |problem| {
print("Cannot use java at ({s}):\n {s}\n", .{ home, problem });
} else {
print("Using java at {s}\n", .{home});
config.java_home = home;
config_dirty = true;
}
}
}
}
}
// If we have Android Studio installed, it packages a JDK.
// Check for that.
if (config.java_home.len == 0) {
if (android_studio_path.len > 0) {
const packaged_jre = pathConcat(b, android_studio_path, "jre");
if (findProblemWithJdk(b, packaged_jre)) |problem| {
print("Cannot use Android Studio java at ({s}):\n {s}\n", .{ packaged_jre, problem });
} else {
print("Using java from Android Studio: {s}\n", .{packaged_jre});
config.java_home = packaged_jre;
config_dirty = true;
}
}
}
// Write out the new config
if (config_dirty) {
std.fs.cwd().makeDir(local_config_path) catch {};
var file = std.fs.cwd().createFile(config_path, .{}) catch |err| {
print("Couldn't write config file {s}: {s}\n\n", .{ config_path, @errorName(err) });
return err;
};
defer file.close();
var buf_writer = std.io.bufferedWriter(file.writer());
std.json.stringify(config, .{}, buf_writer.writer()) catch |err| {
print("Error writing config file {s}: {s}\n", .{ config_path, @errorName(err) });
return err;
};
buf_writer.flush() catch |err| {
print("Error writing config file {s}: {s}\n", .{ config_path, @errorName(err) });
return err;
};
}
// Check if the config is invalid.
if (config.android_sdk_root.len == 0 or
config.android_ndk_root.len == 0 or
config.java_home.len == 0)
{
print("\nCould not find all needed tools. Please edit {s} to specify their paths.\n\n", .{local_config_path});
if (config.android_sdk_root.len == 0) {
print("Android SDK root is missing. Edit the config file, or set ANDROID_SDK_ROOT to your android install.\n", .{});
print("You will need build tools version {s} and android sdk platform {s}\n\n", .{ versions.build_tools_version, versions.androidSdkString(&str_buf) });
}
if (config.android_ndk_root.len == 0) {
print("Android NDK root is missing. Edit the config file, or set ANDROID_NDK_ROOT to your android NDK install.\n", .{});
print("You will need NDK version {s}\n\n", .{versions.ndk_version});
}
if (config.java_home.len == 0) {
print("Java JDK is missing. Edit the config file, or set JAVA_HOME to your JDK install.\n", .{});
if (std.builtin.os.tag == .windows) {
print("Installing Android Studio will also install a suitable JDK.\n", .{});
}
print("\n", .{});
}
std.os.exit(1);
}
if (config_dirty) {
print("New configuration:\nSDK: {s}\nNDK: {s}\nJDK: {s}\n", .{ config.android_sdk_root, config.android_ndk_root, config.java_home });
}
return config;
}
fn findProgramPath(allocator: *Allocator, program: []const u8) ?[]const u8 {
const args: []const []const u8 = if (std.builtin.os.tag == .windows)
&[_][]const u8{ "where", program }
else
&[_][]const u8{ "which", program };
const proc = std.ChildProcess.init(args, allocator) catch return null;
defer proc.deinit();
proc.stderr_behavior = .Close;
proc.stdout_behavior = .Pipe;
proc.stdin_behavior = .Close;
proc.spawn() catch return null;
const stdout = proc.stdout.?.readToEndAlloc(allocator, 1024) catch return null;
const term = proc.wait() catch return null;
switch (term) {
.Exited => |rc| {
if (rc != 0) return null;
},
else => return null,
}
var path = std.mem.trim(u8, stdout, " \t\r\n");
if (std.mem.indexOfScalar(u8, path, '\n')) |index| {
path = std.mem.trim(u8, path[0..index], " \t\r\n");
}
if (path.len > 0) return path;
return null;
}
// Returns the problem with an android_home path.
// If it seems alright, returns null.
fn findProblemWithAndroidSdk(b: *Builder, versions: Sdk.ToolchainVersions, path: []const u8) ?[]const u8 {
std.fs.cwd().access(path, .{}) catch |err| {
if (err == error.FileNotFound) return "Directory does not exist";
return b.fmt("Cannot access {s}, {s}", .{ path, @errorName(err) });
};
const build_tools = pathConcat(b, path, "build-tools");
std.fs.cwd().access(build_tools, .{}) catch |err| {
return b.fmt("Cannot access build-tools/, {s}", .{@errorName(err)});
};
const versioned_tools = pathConcat(b, build_tools, versions.build_tools_version);
std.fs.cwd().access(versioned_tools, .{}) catch |err| {
if (err == error.FileNotFound) {
return b.fmt("Missing build tools version {s}", .{versions.build_tools_version});
} else {
return b.fmt("Cannot access build-tools/{s}/, {s}", .{ versions.build_tools_version, @errorName(err) });
}
};
var str_buf: [5]u8 = undefined;
const android_version_str = versions.androidSdkString(&str_buf);
const platforms = pathConcat(b, path, "platforms");
const platform_version = pathConcat(b, platforms, b.fmt("android-{d}", .{versions.android_sdk_version}));
std.fs.cwd().access(platform_version, .{}) catch |err| {
if (err == error.FileNotFound) {
return b.fmt("Missing android platform version {s}", .{android_version_str});
} else {
return b.fmt("Cannot access platforms/android-{s}, {s}", .{ android_version_str, @errorName(err) });
}
};
return null;
}
// Returns the problem with an android ndk path.
// If it seems alright, returns null.
fn findProblemWithAndroidNdk(b: *Builder, versions: Sdk.ToolchainVersions, path: []const u8) ?[]const u8 {
std.fs.cwd().access(path, .{}) catch |err| {
if (err == error.FileNotFound) return "Directory does not exist";
return b.fmt("Cannot access {s}, {s}", .{ path, @errorName(err) });
};
const ndk_include_path = std.fs.path.join(b.allocator, &[_][]const u8{
path,
"sysroot",
"usr",
"include",
}) catch unreachable;
std.fs.cwd().access(ndk_include_path, .{}) catch |err| {
return b.fmt("Cannot access sysroot/usr/include/, {s}\nMake sure you are using NDK {s}.", .{ @errorName(err), versions.ndk_version });
};
return null;
}
// Returns the problem with a jdk install.
// If it seems alright, returns null.
fn findProblemWithJdk(b: *Builder, path: []const u8) ?[]const u8 {
std.fs.cwd().access(path, .{}) catch |err| {
if (err == error.FileNotFound) return "Directory does not exist";
return b.fmt("Cannot access {s}, {s}", .{ path, @errorName(err) });
};
const target_executable = if (std.builtin.os.tag == .windows) "bin\\jarsigner.exe" else "bin/jarsigner";
const target_path = pathConcat(b, path, target_executable);
std.fs.cwd().access(target_path, .{}) catch |err| {
return b.fmt("Cannot access jarsigner, {s}", .{@errorName(err)});
};
return null;
}
fn pathConcat(b: *Builder, left: []const u8, right: []const u8) []const u8 {
return std.fs.path.join(b.allocator, &[_][]const u8{ left, right }) catch unreachable;
} | build/auto-detect.zig |
const std = @import("../../../std.zig");
const linux = std.os.linux;
const socklen_t = linux.socklen_t;
const iovec = linux.iovec;
const iovec_const = linux.iovec_const;
const uid_t = linux.uid_t;
const gid_t = linux.gid_t;
const stack_t = linux.stack_t;
const sigset_t = linux.sigset_t;
pub const SYS_restart_syscall = 0;
pub const SYS_exit = 1;
pub const SYS_fork = 2;
pub const SYS_read = 3;
pub const SYS_write = 4;
pub const SYS_open = 5;
pub const SYS_close = 6;
pub const SYS_waitpid = 7;
pub const SYS_creat = 8;
pub const SYS_link = 9;
pub const SYS_unlink = 10;
pub const SYS_execve = 11;
pub const SYS_chdir = 12;
pub const SYS_time = 13;
pub const SYS_mknod = 14;
pub const SYS_chmod = 15;
pub const SYS_lchown = 16;
pub const SYS_break = 17;
pub const SYS_oldstat = 18;
pub const SYS_lseek = 19;
pub const SYS_getpid = 20;
pub const SYS_mount = 21;
pub const SYS_umount = 22;
pub const SYS_setuid = 23;
pub const SYS_getuid = 24;
pub const SYS_stime = 25;
pub const SYS_ptrace = 26;
pub const SYS_alarm = 27;
pub const SYS_oldfstat = 28;
pub const SYS_pause = 29;
pub const SYS_utime = 30;
pub const SYS_stty = 31;
pub const SYS_gtty = 32;
pub const SYS_access = 33;
pub const SYS_nice = 34;
pub const SYS_ftime = 35;
pub const SYS_sync = 36;
pub const SYS_kill = 37;
pub const SYS_rename = 38;
pub const SYS_mkdir = 39;
pub const SYS_rmdir = 40;
pub const SYS_dup = 41;
pub const SYS_pipe = 42;
pub const SYS_times = 43;
pub const SYS_prof = 44;
pub const SYS_brk = 45;
pub const SYS_setgid = 46;
pub const SYS_getgid = 47;
pub const SYS_signal = 48;
pub const SYS_geteuid = 49;
pub const SYS_getegid = 50;
pub const SYS_acct = 51;
pub const SYS_umount2 = 52;
pub const SYS_lock = 53;
pub const SYS_ioctl = 54;
pub const SYS_fcntl = 55;
pub const SYS_mpx = 56;
pub const SYS_setpgid = 57;
pub const SYS_ulimit = 58;
pub const SYS_oldolduname = 59;
pub const SYS_umask = 60;
pub const SYS_chroot = 61;
pub const SYS_ustat = 62;
pub const SYS_dup2 = 63;
pub const SYS_getppid = 64;
pub const SYS_getpgrp = 65;
pub const SYS_setsid = 66;
pub const SYS_sigaction = 67;
pub const SYS_sgetmask = 68;
pub const SYS_ssetmask = 69;
pub const SYS_setreuid = 70;
pub const SYS_setregid = 71;
pub const SYS_sigsuspend = 72;
pub const SYS_sigpending = 73;
pub const SYS_sethostname = 74;
pub const SYS_setrlimit = 75;
pub const SYS_getrlimit = 76;
pub const SYS_getrusage = 77;
pub const SYS_gettimeofday = 78;
pub const SYS_settimeofday = 79;
pub const SYS_getgroups = 80;
pub const SYS_setgroups = 81;
pub const SYS_select = 82;
pub const SYS_symlink = 83;
pub const SYS_oldlstat = 84;
pub const SYS_readlink = 85;
pub const SYS_uselib = 86;
pub const SYS_swapon = 87;
pub const SYS_reboot = 88;
pub const SYS_readdir = 89;
pub const SYS_mmap = 90;
pub const SYS_munmap = 91;
pub const SYS_truncate = 92;
pub const SYS_ftruncate = 93;
pub const SYS_fchmod = 94;
pub const SYS_fchown = 95;
pub const SYS_getpriority = 96;
pub const SYS_setpriority = 97;
pub const SYS_profil = 98;
pub const SYS_statfs = 99;
pub const SYS_fstatfs = 100;
pub const SYS_ioperm = 101;
pub const SYS_socketcall = 102;
pub const SYS_syslog = 103;
pub const SYS_setitimer = 104;
pub const SYS_getitimer = 105;
pub const SYS_stat = 106;
pub const SYS_lstat = 107;
pub const SYS_fstat = 108;
pub const SYS_olduname = 109;
pub const SYS_iopl = 110;
pub const SYS_vhangup = 111;
pub const SYS_idle = 112;
pub const SYS_vm86old = 113;
pub const SYS_wait4 = 114;
pub const SYS_swapoff = 115;
pub const SYS_sysinfo = 116;
pub const SYS_ipc = 117;
pub const SYS_fsync = 118;
pub const SYS_sigreturn = 119;
pub const SYS_clone = 120;
pub const SYS_setdomainname = 121;
pub const SYS_uname = 122;
pub const SYS_modify_ldt = 123;
pub const SYS_adjtimex = 124;
pub const SYS_mprotect = 125;
pub const SYS_sigprocmask = 126;
pub const SYS_create_module = 127;
pub const SYS_init_module = 128;
pub const SYS_delete_module = 129;
pub const SYS_get_kernel_syms = 130;
pub const SYS_quotactl = 131;
pub const SYS_getpgid = 132;
pub const SYS_fchdir = 133;
pub const SYS_bdflush = 134;
pub const SYS_sysfs = 135;
pub const SYS_personality = 136;
pub const SYS_afs_syscall = 137;
pub const SYS_setfsuid = 138;
pub const SYS_setfsgid = 139;
pub const SYS__llseek = 140;
pub const SYS_getdents = 141;
pub const SYS__newselect = 142;
pub const SYS_flock = 143;
pub const SYS_msync = 144;
pub const SYS_readv = 145;
pub const SYS_writev = 146;
pub const SYS_getsid = 147;
pub const SYS_fdatasync = 148;
pub const SYS__sysctl = 149;
pub const SYS_mlock = 150;
pub const SYS_munlock = 151;
pub const SYS_mlockall = 152;
pub const SYS_munlockall = 153;
pub const SYS_sched_setparam = 154;
pub const SYS_sched_getparam = 155;
pub const SYS_sched_setscheduler = 156;
pub const SYS_sched_getscheduler = 157;
pub const SYS_sched_yield = 158;
pub const SYS_sched_get_priority_max = 159;
pub const SYS_sched_get_priority_min = 160;
pub const SYS_sched_rr_get_interval = 161;
pub const SYS_nanosleep = 162;
pub const SYS_mremap = 163;
pub const SYS_setresuid = 164;
pub const SYS_getresuid = 165;
pub const SYS_vm86 = 166;
pub const SYS_query_module = 167;
pub const SYS_poll = 168;
pub const SYS_nfsservctl = 169;
pub const SYS_setresgid = 170;
pub const SYS_getresgid = 171;
pub const SYS_prctl = 172;
pub const SYS_rt_sigreturn = 173;
pub const SYS_rt_sigaction = 174;
pub const SYS_rt_sigprocmask = 175;
pub const SYS_rt_sigpending = 176;
pub const SYS_rt_sigtimedwait = 177;
pub const SYS_rt_sigqueueinfo = 178;
pub const SYS_rt_sigsuspend = 179;
pub const SYS_pread64 = 180;
pub const SYS_pwrite64 = 181;
pub const SYS_chown = 182;
pub const SYS_getcwd = 183;
pub const SYS_capget = 184;
pub const SYS_capset = 185;
pub const SYS_sigaltstack = 186;
pub const SYS_sendfile = 187;
pub const SYS_getpmsg = 188;
pub const SYS_putpmsg = 189;
pub const SYS_vfork = 190;
pub const SYS_ugetrlimit = 191;
pub const SYS_mmap2 = 192;
pub const SYS_truncate64 = 193;
pub const SYS_ftruncate64 = 194;
pub const SYS_stat64 = 195;
pub const SYS_lstat64 = 196;
pub const SYS_fstat64 = 197;
pub const SYS_lchown32 = 198;
pub const SYS_getuid32 = 199;
pub const SYS_getgid32 = 200;
pub const SYS_geteuid32 = 201;
pub const SYS_getegid32 = 202;
pub const SYS_setreuid32 = 203;
pub const SYS_setregid32 = 204;
pub const SYS_getgroups32 = 205;
pub const SYS_setgroups32 = 206;
pub const SYS_fchown32 = 207;
pub const SYS_setresuid32 = 208;
pub const SYS_getresuid32 = 209;
pub const SYS_setresgid32 = 210;
pub const SYS_getresgid32 = 211;
pub const SYS_chown32 = 212;
pub const SYS_setuid32 = 213;
pub const SYS_setgid32 = 214;
pub const SYS_setfsuid32 = 215;
pub const SYS_setfsgid32 = 216;
pub const SYS_pivot_root = 217;
pub const SYS_mincore = 218;
pub const SYS_madvise = 219;
pub const SYS_getdents64 = 220;
pub const SYS_fcntl64 = 221;
pub const SYS_gettid = 224;
pub const SYS_readahead = 225;
pub const SYS_setxattr = 226;
pub const SYS_lsetxattr = 227;
pub const SYS_fsetxattr = 228;
pub const SYS_getxattr = 229;
pub const SYS_lgetxattr = 230;
pub const SYS_fgetxattr = 231;
pub const SYS_listxattr = 232;
pub const SYS_llistxattr = 233;
pub const SYS_flistxattr = 234;
pub const SYS_removexattr = 235;
pub const SYS_lremovexattr = 236;
pub const SYS_fremovexattr = 237;
pub const SYS_tkill = 238;
pub const SYS_sendfile64 = 239;
pub const SYS_futex = 240;
pub const SYS_sched_setaffinity = 241;
pub const SYS_sched_getaffinity = 242;
pub const SYS_set_thread_area = 243;
pub const SYS_get_thread_area = 244;
pub const SYS_io_setup = 245;
pub const SYS_io_destroy = 246;
pub const SYS_io_getevents = 247;
pub const SYS_io_submit = 248;
pub const SYS_io_cancel = 249;
pub const SYS_fadvise64 = 250;
pub const SYS_exit_group = 252;
pub const SYS_lookup_dcookie = 253;
pub const SYS_epoll_create = 254;
pub const SYS_epoll_ctl = 255;
pub const SYS_epoll_wait = 256;
pub const SYS_remap_file_pages = 257;
pub const SYS_set_tid_address = 258;
pub const SYS_timer_create = 259;
pub const SYS_timer_settime = SYS_timer_create + 1;
pub const SYS_timer_gettime = SYS_timer_create + 2;
pub const SYS_timer_getoverrun = SYS_timer_create + 3;
pub const SYS_timer_delete = SYS_timer_create + 4;
pub const SYS_clock_settime = SYS_timer_create + 5;
pub const SYS_clock_gettime = SYS_timer_create + 6;
pub const SYS_clock_getres = SYS_timer_create + 7;
pub const SYS_clock_nanosleep = SYS_timer_create + 8;
pub const SYS_statfs64 = 268;
pub const SYS_fstatfs64 = 269;
pub const SYS_tgkill = 270;
pub const SYS_utimes = 271;
pub const SYS_fadvise64_64 = 272;
pub const SYS_vserver = 273;
pub const SYS_mbind = 274;
pub const SYS_get_mempolicy = 275;
pub const SYS_set_mempolicy = 276;
pub const SYS_mq_open = 277;
pub const SYS_mq_unlink = SYS_mq_open + 1;
pub const SYS_mq_timedsend = SYS_mq_open + 2;
pub const SYS_mq_timedreceive = SYS_mq_open + 3;
pub const SYS_mq_notify = SYS_mq_open + 4;
pub const SYS_mq_getsetattr = SYS_mq_open + 5;
pub const SYS_kexec_load = 283;
pub const SYS_waitid = 284;
pub const SYS_add_key = 286;
pub const SYS_request_key = 287;
pub const SYS_keyctl = 288;
pub const SYS_ioprio_set = 289;
pub const SYS_ioprio_get = 290;
pub const SYS_inotify_init = 291;
pub const SYS_inotify_add_watch = 292;
pub const SYS_inotify_rm_watch = 293;
pub const SYS_migrate_pages = 294;
pub const SYS_openat = 295;
pub const SYS_mkdirat = 296;
pub const SYS_mknodat = 297;
pub const SYS_fchownat = 298;
pub const SYS_futimesat = 299;
pub const SYS_fstatat64 = 300;
pub const SYS_unlinkat = 301;
pub const SYS_renameat = 302;
pub const SYS_linkat = 303;
pub const SYS_symlinkat = 304;
pub const SYS_readlinkat = 305;
pub const SYS_fchmodat = 306;
pub const SYS_faccessat = 307;
pub const SYS_pselect6 = 308;
pub const SYS_ppoll = 309;
pub const SYS_unshare = 310;
pub const SYS_set_robust_list = 311;
pub const SYS_get_robust_list = 312;
pub const SYS_splice = 313;
pub const SYS_sync_file_range = 314;
pub const SYS_tee = 315;
pub const SYS_vmsplice = 316;
pub const SYS_move_pages = 317;
pub const SYS_getcpu = 318;
pub const SYS_epoll_pwait = 319;
pub const SYS_utimensat = 320;
pub const SYS_signalfd = 321;
pub const SYS_timerfd_create = 322;
pub const SYS_eventfd = 323;
pub const SYS_fallocate = 324;
pub const SYS_timerfd_settime = 325;
pub const SYS_timerfd_gettime = 326;
pub const SYS_signalfd4 = 327;
pub const SYS_eventfd2 = 328;
pub const SYS_epoll_create1 = 329;
pub const SYS_dup3 = 330;
pub const SYS_pipe2 = 331;
pub const SYS_inotify_init1 = 332;
pub const SYS_preadv = 333;
pub const SYS_pwritev = 334;
pub const SYS_rt_tgsigqueueinfo = 335;
pub const SYS_perf_event_open = 336;
pub const SYS_recvmmsg = 337;
pub const SYS_fanotify_init = 338;
pub const SYS_fanotify_mark = 339;
pub const SYS_prlimit64 = 340;
pub const SYS_name_to_handle_at = 341;
pub const SYS_open_by_handle_at = 342;
pub const SYS_clock_adjtime = 343;
pub const SYS_syncfs = 344;
pub const SYS_sendmmsg = 345;
pub const SYS_setns = 346;
pub const SYS_process_vm_readv = 347;
pub const SYS_process_vm_writev = 348;
pub const SYS_kcmp = 349;
pub const SYS_finit_module = 350;
pub const SYS_sched_setattr = 351;
pub const SYS_sched_getattr = 352;
pub const SYS_renameat2 = 353;
pub const SYS_seccomp = 354;
pub const SYS_getrandom = 355;
pub const SYS_memfd_create = 356;
pub const SYS_bpf = 357;
pub const SYS_execveat = 358;
pub const SYS_socket = 359;
pub const SYS_socketpair = 360;
pub const SYS_bind = 361;
pub const SYS_connect = 362;
pub const SYS_listen = 363;
pub const SYS_accept4 = 364;
pub const SYS_getsockopt = 365;
pub const SYS_setsockopt = 366;
pub const SYS_getsockname = 367;
pub const SYS_getpeername = 368;
pub const SYS_sendto = 369;
pub const SYS_sendmsg = 370;
pub const SYS_recvfrom = 371;
pub const SYS_recvmsg = 372;
pub const SYS_shutdown = 373;
pub const SYS_userfaultfd = 374;
pub const SYS_membarrier = 375;
pub const SYS_mlock2 = 376;
pub const SYS_copy_file_range = 377;
pub const SYS_preadv2 = 378;
pub const SYS_pwritev2 = 379;
pub const SYS_pkey_mprotect = 380;
pub const SYS_pkey_alloc = 381;
pub const SYS_pkey_free = 382;
pub const SYS_statx = 383;
pub const SYS_arch_prctl = 384;
pub const SYS_io_pgetevents = 385;
pub const SYS_rseq = 386;
pub const SYS_semget = 393;
pub const SYS_semctl = 394;
pub const SYS_shmget = 395;
pub const SYS_shmctl = 396;
pub const SYS_shmat = 397;
pub const SYS_shmdt = 398;
pub const SYS_msgget = 399;
pub const SYS_msgsnd = 400;
pub const SYS_msgrcv = 401;
pub const SYS_msgctl = 402;
pub const SYS_clock_gettime64 = 403;
pub const SYS_clock_settime64 = 404;
pub const SYS_clock_adjtime64 = 405;
pub const SYS_clock_getres_time64 = 406;
pub const SYS_clock_nanosleep_time64 = 407;
pub const SYS_timer_gettime64 = 408;
pub const SYS_timer_settime64 = 409;
pub const SYS_timerfd_gettime64 = 410;
pub const SYS_timerfd_settime64 = 411;
pub const SYS_utimensat_time64 = 412;
pub const SYS_pselect6_time64 = 413;
pub const SYS_ppoll_time64 = 414;
pub const SYS_io_pgetevents_time64 = 416;
pub const SYS_recvmmsg_time64 = 417;
pub const SYS_mq_timedsend_time64 = 418;
pub const SYS_mq_timedreceive_time64 = 419;
pub const SYS_semtimedop_time64 = 420;
pub const SYS_rt_sigtimedwait_time64 = 421;
pub const SYS_futex_time64 = 422;
pub const SYS_sched_rr_get_interval_time64 = 423;
pub const SYS_pidfd_send_signal = 424;
pub const SYS_io_uring_setup = 425;
pub const SYS_io_uring_enter = 426;
pub const SYS_io_uring_register = 427;
pub const SYS_open_tree = 428;
pub const SYS_move_mount = 429;
pub const SYS_fsopen = 430;
pub const SYS_fsconfig = 431;
pub const SYS_fsmount = 432;
pub const SYS_fspick = 433;
pub const O_CREAT = 0o100;
pub const O_EXCL = 0o200;
pub const O_NOCTTY = 0o400;
pub const O_TRUNC = 0o1000;
pub const O_APPEND = 0o2000;
pub const O_NONBLOCK = 0o4000;
pub const O_DSYNC = 0o10000;
pub const O_SYNC = 0o4010000;
pub const O_RSYNC = 0o4010000;
pub const O_DIRECTORY = 0o200000;
pub const O_NOFOLLOW = 0o400000;
pub const O_CLOEXEC = 0o2000000;
pub const O_ASYNC = 0o20000;
pub const O_DIRECT = 0o40000;
pub const O_LARGEFILE = 0o100000;
pub const O_NOATIME = 0o1000000;
pub const O_PATH = 0o10000000;
pub const O_TMPFILE = 0o20200000;
pub const O_NDELAY = O_NONBLOCK;
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 = 8;
pub const F_GETOWN = 9;
pub const F_SETSIG = 10;
pub const F_GETSIG = 11;
pub const F_GETLK = 12;
pub const F_SETLK = 13;
pub const F_SETLKW = 14;
pub const F_SETOWN_EX = 15;
pub const F_GETOWN_EX = 16;
pub const F_GETOWNER_UIDS = 17;
pub const MAP_NORESERVE = 0x4000;
pub const MAP_GROWSDOWN = 0x0100;
pub const MAP_DENYWRITE = 0x0800;
pub const MAP_EXECUTABLE = 0x1000;
pub const MAP_LOCKED = 0x2000;
pub const MAP_32BIT = 0x40;
pub const MMAP2_UNIT = 4096;
pub const VDSO_CGT_SYM = "__vdso_clock_gettime";
pub const VDSO_CGT_VER = "LINUX_2.6";
pub const msghdr = extern struct {
msg_name: ?*sockaddr,
msg_namelen: socklen_t,
msg_iov: [*]iovec,
msg_iovlen: i32,
msg_control: ?*c_void,
msg_controllen: socklen_t,
msg_flags: i32,
};
pub const msghdr_const = extern struct {
msg_name: ?*const sockaddr,
msg_namelen: socklen_t,
msg_iov: [*]iovec_const,
msg_iovlen: i32,
msg_control: ?*c_void,
msg_controllen: socklen_t,
msg_flags: i32,
};
pub const blksize_t = i32;
pub const nlink_t = u32;
pub const time_t = isize;
pub const mode_t = u32;
pub const off_t = i64;
pub const ino_t = u64;
pub const dev_t = u64;
pub const blkcnt_t = i64;
/// Renamed to Stat to not conflict with the stat function.
/// 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 Stat = extern struct {
dev: dev_t,
__dev_padding: u32,
__ino_truncated: u32,
mode: mode_t,
nlink: nlink_t,
uid: uid_t,
gid: gid_t,
rdev: dev_t,
__rdev_padding: u32,
size: off_t,
blksize: blksize_t,
blocks: blkcnt_t,
atim: timespec,
mtim: timespec,
ctim: timespec,
ino: ino_t,
pub fn atime(self: Stat) timespec {
return self.atim;
}
pub fn mtime(self: Stat) timespec {
return self.mtim;
}
pub fn ctime(self: Stat) timespec {
return self.ctim;
}
};
pub const timespec = extern struct {
tv_sec: i32,
tv_nsec: i32,
};
pub const timeval = extern struct {
tv_sec: i32,
tv_usec: i32,
};
pub const timezone = extern struct {
tz_minuteswest: i32,
tz_dsttime: i32,
};
pub const mcontext_t = extern struct {
gregs: [19]usize,
fpregs: [*]u8,
oldmask: usize,
cr2: usize,
};
pub const REG_GS = 0;
pub const REG_FS = 1;
pub const REG_ES = 2;
pub const REG_DS = 3;
pub const REG_EDI = 4;
pub const REG_ESI = 5;
pub const REG_EBP = 6;
pub const REG_ESP = 7;
pub const REG_EBX = 8;
pub const REG_EDX = 9;
pub const REG_ECX = 10;
pub const REG_EAX = 11;
pub const REG_TRAPNO = 12;
pub const REG_ERR = 13;
pub const REG_EIP = 14;
pub const REG_CS = 15;
pub const REG_EFL = 16;
pub const REG_UESP = 17;
pub const REG_SS = 18;
pub const ucontext_t = extern struct {
flags: usize,
link: *ucontext_t,
stack: stack_t,
mcontext: mcontext_t,
sigmask: sigset_t,
regspace: [64]u64,
};
pub const Elf_Symndx = u32;
pub const user_desc = packed struct {
entry_number: u32,
base_addr: u32,
limit: u32,
seg_32bit: u1,
contents: u2,
read_exec_only: u1,
limit_in_pages: u1,
seg_not_present: u1,
useable: u1,
};
// socketcall() call numbers
pub const SC_socket = 1;
pub const SC_bind = 2;
pub const SC_connect = 3;
pub const SC_listen = 4;
pub const SC_accept = 5;
pub const SC_getsockname = 6;
pub const SC_getpeername = 7;
pub const SC_socketpair = 8;
pub const SC_send = 9;
pub const SC_recv = 10;
pub const SC_sendto = 11;
pub const SC_recvfrom = 12;
pub const SC_shutdown = 13;
pub const SC_setsockopt = 14;
pub const SC_getsockopt = 15;
pub const SC_sendmsg = 16;
pub const SC_recvmsg = 17;
pub const SC_accept4 = 18;
pub const SC_recvmmsg = 19;
pub const SC_sendmmsg = 20; | lib/std/os/bits/linux/i386.zig |
const std = @import("std");
const builtin = std.builtin;
const event = std.event;
const assert = std.debug.assert;
const testing = std.testing;
const os = std.os;
const mem = std.mem;
const windows = os.windows;
const Loop = event.Loop;
const fd_t = os.fd_t;
const File = std.fs.File;
const Allocator = mem.Allocator;
const global_event_loop = Loop.instance orelse
@compileError("std.fs.Watch currently only works with event-based I/O");
const WatchEventId = enum {
CloseWrite,
Delete,
};
const WatchEventError = error{
UserResourceLimitReached,
SystemResources,
AccessDenied,
Unexpected, // TODO remove this possibility
};
pub fn Watch(comptime V: type) type {
return struct {
channel: event.Channel(Event.Error!Event),
os_data: OsData,
allocator: *Allocator,
const OsData = switch (builtin.os.tag) {
// TODO https://github.com/ziglang/zig/issues/3778
.macos, .freebsd, .netbsd, .dragonfly, .openbsd => KqOsData,
.linux => LinuxOsData,
.windows => WindowsOsData,
else => @compileError("Unsupported OS"),
};
const KqOsData = struct {
table_lock: event.Lock,
file_table: FileTable,
const FileTable = std.StringHashMapUnmanaged(*Put);
const Put = struct {
putter_frame: @Frame(kqPutEvents),
cancelled: bool = false,
value: V,
};
};
const WindowsOsData = struct {
table_lock: event.Lock,
dir_table: DirTable,
cancelled: bool = false,
const DirTable = std.StringHashMapUnmanaged(*Dir);
const FileTable = std.StringHashMapUnmanaged(V);
const Dir = struct {
putter_frame: @Frame(windowsDirReader),
file_table: FileTable,
dir_handle: os.windows.HANDLE,
};
};
const LinuxOsData = struct {
putter_frame: @Frame(linuxEventPutter),
inotify_fd: i32,
wd_table: WdTable,
table_lock: event.Lock,
cancelled: bool = false,
const WdTable = std.AutoHashMapUnmanaged(i32, Dir);
const FileTable = std.StringHashMapUnmanaged(V);
const Dir = struct {
dirname: []const u8,
file_table: FileTable,
};
};
const Self = @This();
pub const Event = struct {
id: Id,
data: V,
dirname: []const u8,
basename: []const u8,
pub const Id = WatchEventId;
pub const Error = WatchEventError;
};
pub fn init(allocator: *Allocator, event_buf_count: usize) !*Self {
const self = try allocator.create(Self);
errdefer allocator.destroy(self);
switch (builtin.os.tag) {
.linux => {
const inotify_fd = try os.inotify_init1(os.linux.IN_NONBLOCK | os.linux.IN_CLOEXEC);
errdefer os.close(inotify_fd);
self.* = Self{
.allocator = allocator,
.channel = undefined,
.os_data = OsData{
.putter_frame = undefined,
.inotify_fd = inotify_fd,
.wd_table = OsData.WdTable.init(allocator),
.table_lock = event.Lock{},
},
};
var buf = try allocator.alloc(Event.Error!Event, event_buf_count);
self.channel.init(buf);
self.os_data.putter_frame = async self.linuxEventPutter();
return self;
},
.windows => {
self.* = Self{
.allocator = allocator,
.channel = undefined,
.os_data = OsData{
.table_lock = event.Lock{},
.dir_table = OsData.DirTable.init(allocator),
},
};
var buf = try allocator.alloc(Event.Error!Event, event_buf_count);
self.channel.init(buf);
return self;
},
.macos, .freebsd, .netbsd, .dragonfly, .openbsd => {
self.* = Self{
.allocator = allocator,
.channel = undefined,
.os_data = OsData{
.table_lock = event.Lock{},
.file_table = OsData.FileTable.init(allocator),
},
};
var buf = try allocator.alloc(Event.Error!Event, event_buf_count);
self.channel.init(buf);
return self;
},
else => @compileError("Unsupported OS"),
}
}
pub fn deinit(self: *Self) void {
switch (builtin.os.tag) {
.macos, .freebsd, .netbsd, .dragonfly, .openbsd => {
var it = self.os_data.file_table.iterator();
while (it.next()) |entry| {
const key = entry.key_ptr.*;
const value = entry.value_ptr.*;
value.cancelled = true;
// @TODO Close the fd here?
await value.putter_frame;
self.allocator.free(key);
self.allocator.destroy(value);
}
},
.linux => {
self.os_data.cancelled = true;
{
// Remove all directory watches linuxEventPutter will take care of
// cleaning up the memory and closing the inotify fd.
var dir_it = self.os_data.wd_table.keyIterator();
while (dir_it.next()) |wd_key| {
const rc = os.linux.inotify_rm_watch(self.os_data.inotify_fd, wd_key.*);
// Errno can only be EBADF, EINVAL if either the inotify fs or the wd are invalid
std.debug.assert(rc == 0);
}
}
await self.os_data.putter_frame;
},
.windows => {
self.os_data.cancelled = true;
var dir_it = self.os_data.dir_table.iterator();
while (dir_it.next()) |dir_entry| {
if (windows.kernel32.CancelIoEx(dir_entry.value.dir_handle, null) != 0) {
// We canceled the pending ReadDirectoryChangesW operation, but our
// frame is still suspending, now waiting indefinitely.
// Thus, it is safe to resume it ourslves
resume dir_entry.value.putter_frame;
} else {
std.debug.assert(windows.kernel32.GetLastError() == .NOT_FOUND);
// We are at another suspend point, we can await safely for the
// function to exit the loop
await dir_entry.value.putter_frame;
}
self.allocator.free(dir_entry.key_ptr.*);
var file_it = dir_entry.value.file_table.keyIterator();
while (file_it.next()) |file_entry| {
self.allocator.free(file_entry.*);
}
dir_entry.value.file_table.deinit(self.allocator);
self.allocator.destroy(dir_entry.value_ptr.*);
}
self.os_data.dir_table.deinit(self.allocator);
},
else => @compileError("Unsupported OS"),
}
self.allocator.free(self.channel.buffer_nodes);
self.channel.deinit();
self.allocator.destroy(self);
}
pub fn addFile(self: *Self, file_path: []const u8, value: V) !?V {
switch (builtin.os.tag) {
.macos, .freebsd, .netbsd, .dragonfly, .openbsd => return addFileKEvent(self, file_path, value),
.linux => return addFileLinux(self, file_path, value),
.windows => return addFileWindows(self, file_path, value),
else => @compileError("Unsupported OS"),
}
}
fn addFileKEvent(self: *Self, file_path: []const u8, value: V) !?V {
var realpath_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined;
const realpath = try os.realpath(file_path, &realpath_buf);
const held = self.os_data.table_lock.acquire();
defer held.release();
const gop = try self.os_data.file_table.getOrPut(self.allocator, realpath);
errdefer assert(self.os_data.file_table.remove(realpath));
if (gop.found_existing) {
const prev_value = gop.value_ptr.value;
gop.value_ptr.value = value;
return prev_value;
}
gop.key_ptr.* = try self.allocator.dupe(u8, realpath);
errdefer self.allocator.free(gop.key_ptr.*);
gop.value_ptr.* = try self.allocator.create(OsData.Put);
errdefer self.allocator.destroy(gop.value_ptr.*);
gop.value_ptr.* = .{
.putter_frame = undefined,
.value = value,
};
// @TODO Can I close this fd and get an error from bsdWaitKev?
const flags = if (comptime std.Target.current.isDarwin()) os.O_SYMLINK | os.O_EVTONLY else 0;
const fd = try os.open(realpath, flags, 0);
gop.value_ptr.putter_frame = async self.kqPutEvents(fd, gop.key_ptr.*, gop.value_ptr.*);
return null;
}
fn kqPutEvents(self: *Self, fd: os.fd_t, file_path: []const u8, put: *OsData.Put) void {
global_event_loop.beginOneEvent();
defer {
global_event_loop.finishOneEvent();
// @TODO: Remove this if we force close otherwise
os.close(fd);
}
// We need to manually do a bsdWaitKev to access the fflags.
var resume_node = event.Loop.ResumeNode.Basic{
.base = .{
.id = .Basic,
.handle = @frame(),
.overlapped = event.Loop.ResumeNode.overlapped_init,
},
.kev = undefined,
};
var kevs = [1]os.Kevent{undefined};
const kev = &kevs[0];
while (!put.cancelled) {
kev.* = os.Kevent{
.ident = @intCast(usize, fd),
.filter = os.EVFILT_VNODE,
.flags = os.EV_ADD | os.EV_ENABLE | os.EV_CLEAR | os.EV_ONESHOT |
os.NOTE_WRITE | os.NOTE_DELETE | os.NOTE_REVOKE,
.fflags = 0,
.data = 0,
.udata = @ptrToInt(&resume_node.base),
};
suspend {
global_event_loop.beginOneEvent();
errdefer global_event_loop.finishOneEvent();
const empty_kevs = &[0]os.Kevent{};
_ = os.kevent(global_event_loop.os_data.kqfd, &kevs, empty_kevs, null) catch |err| switch (err) {
error.EventNotFound,
error.ProcessNotFound,
error.Overflow,
=> unreachable,
error.AccessDenied, error.SystemResources => |e| {
self.channel.put(e);
continue;
},
};
}
if (kev.flags & os.EV_ERROR != 0) {
self.channel.put(os.unexpectedErrno(os.errno(kev.data)));
continue;
}
if (kev.fflags & os.NOTE_DELETE != 0 or kev.fflags & os.NOTE_REVOKE != 0) {
self.channel.put(Self.Event{
.id = .Delete,
.data = put.value,
.dirname = std.fs.path.dirname(file_path) orelse "/",
.basename = std.fs.path.basename(file_path),
});
} else if (kev.fflags & os.NOTE_WRITE != 0) {
self.channel.put(Self.Event{
.id = .CloseWrite,
.data = put.value,
.dirname = std.fs.path.dirname(file_path) orelse "/",
.basename = std.fs.path.basename(file_path),
});
}
}
}
fn addFileLinux(self: *Self, file_path: []const u8, value: V) !?V {
const dirname = std.fs.path.dirname(file_path) orelse if (file_path[0] == '/') "/" else ".";
const basename = std.fs.path.basename(file_path);
const wd = try os.inotify_add_watch(
self.os_data.inotify_fd,
dirname,
os.linux.IN_CLOSE_WRITE | os.linux.IN_ONLYDIR | os.linux.IN_DELETE | os.linux.IN_EXCL_UNLINK,
);
// wd is either a newly created watch or an existing one.
const held = self.os_data.table_lock.acquire();
defer held.release();
const gop = try self.os_data.wd_table.getOrPut(self.allocator, wd);
errdefer assert(self.os_data.wd_table.remove(wd));
if (!gop.found_existing) {
gop.value_ptr.* = OsData.Dir{
.dirname = try self.allocator.dupe(u8, dirname),
.file_table = OsData.FileTable.init(self.allocator),
};
}
const dir = gop.value_ptr;
const file_table_gop = try dir.file_table.getOrPut(self.allocator, basename);
errdefer assert(dir.file_table.remove(basename));
if (file_table_gop.found_existing) {
const prev_value = file_table_gop.value_ptr.*;
file_table_gop.value_ptr.* = value;
return prev_value;
} else {
file_table_gop.key_ptr.* = try self.allocator.dupe(u8, basename);
file_table_gop.value_ptr.* = value;
return null;
}
}
fn addFileWindows(self: *Self, file_path: []const u8, value: V) !?V {
// TODO we might need to convert dirname and basename to canonical file paths ("short"?)
const dirname = std.fs.path.dirname(file_path) orelse if (file_path[0] == '/') "/" else ".";
var dirname_path_space: windows.PathSpace = undefined;
dirname_path_space.len = try std.unicode.utf8ToUtf16Le(&dirname_path_space.data, dirname);
dirname_path_space.data[dirname_path_space.len] = 0;
const basename = std.fs.path.basename(file_path);
var basename_path_space: windows.PathSpace = undefined;
basename_path_space.len = try std.unicode.utf8ToUtf16Le(&basename_path_space.data, basename);
basename_path_space.data[basename_path_space.len] = 0;
const held = self.os_data.table_lock.acquire();
defer held.release();
const gop = try self.os_data.dir_table.getOrPut(self.allocator, dirname);
errdefer assert(self.os_data.dir_table.remove(dirname));
if (gop.found_existing) {
const dir = gop.value_ptr.*;
const file_gop = try dir.file_table.getOrPut(self.allocator, basename);
errdefer assert(dir.file_table.remove(basename));
if (file_gop.found_existing) {
const prev_value = file_gop.value_ptr.*;
file_gop.value_ptr.* = value;
return prev_value;
} else {
file_gop.value_ptr.* = value;
file_gop.key_ptr.* = try self.allocator.dupe(u8, basename);
return null;
}
} else {
const dir_handle = try windows.OpenFile(dirname_path_space.span(), .{
.dir = std.fs.cwd().fd,
.access_mask = windows.FILE_LIST_DIRECTORY,
.creation = windows.FILE_OPEN,
.io_mode = .evented,
.open_dir = true,
});
errdefer windows.CloseHandle(dir_handle);
const dir = try self.allocator.create(OsData.Dir);
errdefer self.allocator.destroy(dir);
gop.key_ptr.* = try self.allocator.dupe(u8, dirname);
errdefer self.allocator.free(gop.key_ptr.*);
dir.* = OsData.Dir{
.file_table = OsData.FileTable.init(self.allocator),
.putter_frame = undefined,
.dir_handle = dir_handle,
};
gop.value_ptr.* = dir;
try dir.file_table.put(self.allocator, try self.allocator.dupe(u8, basename), value);
dir.putter_frame = async self.windowsDirReader(dir, gop.key_ptr.*);
return null;
}
}
fn windowsDirReader(self: *Self, dir: *OsData.Dir, dirname: []const u8) void {
defer os.close(dir.dir_handle);
var resume_node = Loop.ResumeNode.Basic{
.base = Loop.ResumeNode{
.id = .Basic,
.handle = @frame(),
.overlapped = windows.OVERLAPPED{
.Internal = 0,
.InternalHigh = 0,
.DUMMYUNIONNAME = .{
.DUMMYSTRUCTNAME = .{
.Offset = 0,
.OffsetHigh = 0,
},
},
.hEvent = null,
},
},
};
var event_buf: [4096]u8 align(@alignOf(windows.FILE_NOTIFY_INFORMATION)) = undefined;
global_event_loop.beginOneEvent();
defer global_event_loop.finishOneEvent();
while (!self.os_data.cancelled) main_loop: {
suspend {
_ = windows.kernel32.ReadDirectoryChangesW(
dir.dir_handle,
&event_buf,
event_buf.len,
windows.FALSE, // watch subtree
windows.FILE_NOTIFY_CHANGE_FILE_NAME | windows.FILE_NOTIFY_CHANGE_DIR_NAME |
windows.FILE_NOTIFY_CHANGE_ATTRIBUTES | windows.FILE_NOTIFY_CHANGE_SIZE |
windows.FILE_NOTIFY_CHANGE_LAST_WRITE | windows.FILE_NOTIFY_CHANGE_LAST_ACCESS |
windows.FILE_NOTIFY_CHANGE_CREATION | windows.FILE_NOTIFY_CHANGE_SECURITY,
null, // number of bytes transferred (unused for async)
&resume_node.base.overlapped,
null, // completion routine - unused because we use IOCP
);
}
var bytes_transferred: windows.DWORD = undefined;
if (windows.kernel32.GetOverlappedResult(
dir.dir_handle,
&resume_node.base.overlapped,
&bytes_transferred,
windows.FALSE,
) == 0) {
const potential_error = windows.kernel32.GetLastError();
const err = switch (potential_error) {
.OPERATION_ABORTED, .IO_INCOMPLETE => err_blk: {
if (self.os_data.cancelled)
break :main_loop
else
break :err_blk windows.unexpectedError(potential_error);
},
else => |err| windows.unexpectedError(err),
};
self.channel.put(err);
} else {
var ptr: [*]u8 = &event_buf;
const end_ptr = ptr + bytes_transferred;
while (@ptrToInt(ptr) < @ptrToInt(end_ptr)) {
const ev = @ptrCast(*const windows.FILE_NOTIFY_INFORMATION, ptr);
const emit = switch (ev.Action) {
windows.FILE_ACTION_REMOVED => WatchEventId.Delete,
windows.FILE_ACTION_MODIFIED => .CloseWrite,
else => null,
};
if (emit) |id| {
const basename_ptr = @ptrCast([*]u16, ptr + @sizeOf(windows.FILE_NOTIFY_INFORMATION));
const basename_utf16le = basename_ptr[0 .. ev.FileNameLength / 2];
var basename_data: [std.fs.MAX_PATH_BYTES]u8 = undefined;
const basename = basename_data[0 .. std.unicode.utf16leToUtf8(&basename_data, basename_utf16le) catch unreachable];
if (dir.file_table.getEntry(basename)) |entry| {
self.channel.put(Event{
.id = id,
.data = entry.value_ptr.*,
.dirname = dirname,
.basename = entry.key_ptr.*,
});
}
}
if (ev.NextEntryOffset == 0) break;
ptr = @alignCast(@alignOf(windows.FILE_NOTIFY_INFORMATION), ptr + ev.NextEntryOffset);
}
}
}
}
pub fn removeFile(self: *Self, file_path: []const u8) !?V {
switch (builtin.os.tag) {
.linux => {
const dirname = std.fs.path.dirname(file_path) orelse if (file_path[0] == '/') "/" else ".";
const basename = std.fs.path.basename(file_path);
const held = self.os_data.table_lock.acquire();
defer held.release();
const dir = self.os_data.wd_table.get(dirname) orelse return null;
if (dir.file_table.fetchRemove(basename)) |file_entry| {
self.allocator.free(file_entry.key);
return file_entry.value;
}
return null;
},
.windows => {
const dirname = std.fs.path.dirname(file_path) orelse if (file_path[0] == '/') "/" else ".";
const basename = std.fs.path.basename(file_path);
const held = self.os_data.table_lock.acquire();
defer held.release();
const dir = self.os_data.dir_table.get(dirname) orelse return null;
if (dir.file_table.fetchRemove(basename)) |file_entry| {
self.allocator.free(file_entry.key);
return file_entry.value;
}
return null;
},
.macos, .freebsd, .netbsd, .dragonfly, .openbsd => {
var realpath_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined;
const realpath = try os.realpath(file_path, &realpath_buf);
const held = self.os_data.table_lock.acquire();
defer held.release();
const entry = self.os_data.file_table.getEntry(realpath) orelse return null;
entry.value_ptr.cancelled = true;
// @TODO Close the fd here?
await entry.value_ptr.putter_frame;
self.allocator.free(entry.key_ptr.*);
self.allocator.destroy(entry.value_ptr.*);
assert(self.os_data.file_table.remove(realpath));
},
else => @compileError("Unsupported OS"),
}
}
fn linuxEventPutter(self: *Self) void {
global_event_loop.beginOneEvent();
defer {
std.debug.assert(self.os_data.wd_table.count() == 0);
self.os_data.wd_table.deinit(self.allocator);
os.close(self.os_data.inotify_fd);
self.allocator.free(self.channel.buffer_nodes);
self.channel.deinit();
global_event_loop.finishOneEvent();
}
var event_buf: [4096]u8 align(@alignOf(os.linux.inotify_event)) = undefined;
while (!self.os_data.cancelled) {
const bytes_read = global_event_loop.read(self.os_data.inotify_fd, &event_buf, false) catch unreachable;
var ptr: [*]u8 = &event_buf;
const end_ptr = ptr + bytes_read;
while (@ptrToInt(ptr) < @ptrToInt(end_ptr)) {
const ev = @ptrCast(*const os.linux.inotify_event, ptr);
if (ev.mask & os.linux.IN_CLOSE_WRITE == os.linux.IN_CLOSE_WRITE) {
const basename_ptr = ptr + @sizeOf(os.linux.inotify_event);
const basename = std.mem.span(@ptrCast([*:0]u8, basename_ptr));
const dir = &self.os_data.wd_table.get(ev.wd).?;
if (dir.file_table.getEntry(basename)) |file_value| {
self.channel.put(Event{
.id = .CloseWrite,
.data = file_value.value_ptr.*,
.dirname = dir.dirname,
.basename = file_value.key_ptr.*,
});
}
} else if (ev.mask & os.linux.IN_IGNORED == os.linux.IN_IGNORED) {
// Directory watch was removed
const held = self.os_data.table_lock.acquire();
defer held.release();
if (self.os_data.wd_table.fetchRemove(ev.wd)) |wd_entry| {
var file_it = wd_entry.value.file_table.keyIterator();
while (file_it.next()) |file_entry| {
self.allocator.free(file_entry.*);
}
self.allocator.free(wd_entry.value.dirname);
wd_entry.value.file_table.deinit(self.allocator);
}
} else if (ev.mask & os.linux.IN_DELETE == os.linux.IN_DELETE) {
// File or directory was removed or deleted
const basename_ptr = ptr + @sizeOf(os.linux.inotify_event);
const basename = std.mem.span(@ptrCast([*:0]u8, basename_ptr));
const dir = &self.os_data.wd_table.get(ev.wd).?;
if (dir.file_table.getEntry(basename)) |file_value| {
self.channel.put(Event{
.id = .Delete,
.data = file_value.value_ptr.*,
.dirname = dir.dirname,
.basename = file_value.key_ptr.*,
});
}
}
ptr = @alignCast(@alignOf(os.linux.inotify_event), ptr + @sizeOf(os.linux.inotify_event) + ev.len);
}
}
}
};
}
const test_tmp_dir = "std_event_fs_test";
test "write a file, watch it, write it again, delete it" {
if (!std.io.is_async) return error.SkipZigTest;
// TODO https://github.com/ziglang/zig/issues/1908
if (builtin.single_threaded) return error.SkipZigTest;
try std.fs.cwd().makePath(test_tmp_dir);
defer std.fs.cwd().deleteTree(test_tmp_dir) catch {};
return testWriteWatchWriteDelete(std.testing.allocator);
}
fn testWriteWatchWriteDelete(allocator: *Allocator) !void {
const file_path = try std.fs.path.join(allocator, &[_][]const u8{ test_tmp_dir, "file.txt" });
defer allocator.free(file_path);
const contents =
\\line 1
\\line 2
;
const line2_offset = 7;
// first just write then read the file
try std.fs.cwd().writeFile(file_path, contents);
const read_contents = try std.fs.cwd().readFileAlloc(allocator, file_path, 1024 * 1024);
defer allocator.free(read_contents);
try testing.expectEqualSlices(u8, contents, read_contents);
// now watch the file
var watch = try Watch(void).init(allocator, 0);
defer watch.deinit();
try testing.expect((try watch.addFile(file_path, {})) == null);
var ev = async watch.channel.get();
var ev_consumed = false;
defer if (!ev_consumed) {
_ = await ev;
};
// overwrite line 2
const file = try std.fs.cwd().openFile(file_path, .{ .read = true, .write = true });
{
defer file.close();
const write_contents = "lorem ipsum";
var iovec = [_]os.iovec_const{.{
.iov_base = write_contents,
.iov_len = write_contents.len,
}};
_ = try file.pwritevAll(&iovec, line2_offset);
}
switch ((try await ev).id) {
.CloseWrite => {
ev_consumed = true;
},
.Delete => @panic("wrong event"),
}
const contents_updated = try std.fs.cwd().readFileAlloc(allocator, file_path, 1024 * 1024);
defer allocator.free(contents_updated);
try testing.expectEqualSlices(u8,
\\line 1
\\lorem ipsum
, contents_updated);
ev = async watch.channel.get();
ev_consumed = false;
try std.fs.cwd().deleteFile(file_path);
switch ((try await ev).id) {
.Delete => {
ev_consumed = true;
},
.CloseWrite => @panic("wrong event"),
}
}
// TODO Test: Add another file watch, remove the old file watch, get an event in the new | lib/std/fs/watch.zig |
const std = @import("../std.zig");
const CpuFeature = std.Target.Cpu.Feature;
const CpuModel = std.Target.Cpu.Model;
pub const Feature = enum {
@"64bit",
a,
c,
d,
e,
experimental_b,
experimental_v,
experimental_zba,
experimental_zbb,
experimental_zbc,
experimental_zbe,
experimental_zbf,
experimental_zbm,
experimental_zbp,
experimental_zbproposedc,
experimental_zbr,
experimental_zbs,
experimental_zbt,
experimental_zfh,
experimental_zvamo,
experimental_zvlsseg,
f,
m,
no_rvc_hints,
relax,
reserve_x1,
reserve_x10,
reserve_x11,
reserve_x12,
reserve_x13,
reserve_x14,
reserve_x15,
reserve_x16,
reserve_x17,
reserve_x18,
reserve_x19,
reserve_x2,
reserve_x20,
reserve_x21,
reserve_x22,
reserve_x23,
reserve_x24,
reserve_x25,
reserve_x26,
reserve_x27,
reserve_x28,
reserve_x29,
reserve_x3,
reserve_x30,
reserve_x31,
reserve_x4,
reserve_x5,
reserve_x6,
reserve_x7,
reserve_x8,
reserve_x9,
save_restore,
};
pub usingnamespace CpuFeature.feature_set_fns(Feature);
pub const all_features = blk: {
const len = @typeInfo(Feature).Enum.fields.len;
std.debug.assert(len <= CpuFeature.Set.needed_bit_count);
var result: [len]CpuFeature = undefined;
result[@enumToInt(Feature.@"64bit")] = .{
.llvm_name = "64bit",
.description = "Implements RV64",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.a)] = .{
.llvm_name = "a",
.description = "'A' (Atomic Instructions)",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.c)] = .{
.llvm_name = "c",
.description = "'C' (Compressed Instructions)",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.d)] = .{
.llvm_name = "d",
.description = "'D' (Double-Precision Floating-Point)",
.dependencies = featureSet(&[_]Feature{
.f,
}),
};
result[@enumToInt(Feature.e)] = .{
.llvm_name = "e",
.description = "Implements RV32E (provides 16 rather than 32 GPRs)",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.experimental_b)] = .{
.llvm_name = "experimental-b",
.description = "'B' (Bit Manipulation Instructions)",
.dependencies = featureSet(&[_]Feature{
.experimental_zba,
.experimental_zbb,
.experimental_zbc,
.experimental_zbe,
.experimental_zbf,
.experimental_zbm,
.experimental_zbp,
.experimental_zbr,
.experimental_zbs,
.experimental_zbt,
}),
};
result[@enumToInt(Feature.experimental_v)] = .{
.llvm_name = "experimental-v",
.description = "'V' (Vector Instructions)",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.experimental_zba)] = .{
.llvm_name = "experimental-zba",
.description = "'Zba' (Address calculation 'B' Instructions)",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.experimental_zbb)] = .{
.llvm_name = "experimental-zbb",
.description = "'Zbb' (Base 'B' Instructions)",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.experimental_zbc)] = .{
.llvm_name = "experimental-zbc",
.description = "'Zbc' (Carry-Less 'B' Instructions)",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.experimental_zbe)] = .{
.llvm_name = "experimental-zbe",
.description = "'Zbe' (Extract-Deposit 'B' Instructions)",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.experimental_zbf)] = .{
.llvm_name = "experimental-zbf",
.description = "'Zbf' (Bit-Field 'B' Instructions)",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.experimental_zbm)] = .{
.llvm_name = "experimental-zbm",
.description = "'Zbm' (Matrix 'B' Instructions)",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.experimental_zbp)] = .{
.llvm_name = "experimental-zbp",
.description = "'Zbp' (Permutation 'B' Instructions)",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.experimental_zbproposedc)] = .{
.llvm_name = "experimental-zbproposedc",
.description = "'Zbproposedc' (Proposed Compressed 'B' Instructions)",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.experimental_zbr)] = .{
.llvm_name = "experimental-zbr",
.description = "'Zbr' (Polynomial Reduction 'B' Instructions)",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.experimental_zbs)] = .{
.llvm_name = "experimental-zbs",
.description = "'Zbs' (Single-Bit 'B' Instructions)",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.experimental_zbt)] = .{
.llvm_name = "experimental-zbt",
.description = "'Zbt' (Ternary 'B' Instructions)",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.experimental_zfh)] = .{
.llvm_name = "experimental-zfh",
.description = "'Zfh' (Half-Precision Floating-Point)",
.dependencies = featureSet(&[_]Feature{
.f,
}),
};
result[@enumToInt(Feature.experimental_zvamo)] = .{
.llvm_name = "experimental-zvamo",
.description = "'Zvamo'(Vector AMO Operations)",
.dependencies = featureSet(&[_]Feature{
.experimental_v,
}),
};
result[@enumToInt(Feature.experimental_zvlsseg)] = .{
.llvm_name = "experimental-zvlsseg",
.description = "'Zvlsseg' (Vector segment load/store instructions)",
.dependencies = featureSet(&[_]Feature{
.experimental_v,
}),
};
result[@enumToInt(Feature.f)] = .{
.llvm_name = "f",
.description = "'F' (Single-Precision Floating-Point)",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.m)] = .{
.llvm_name = "m",
.description = "'M' (Integer Multiplication and Division)",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.no_rvc_hints)] = .{
.llvm_name = "no-rvc-hints",
.description = "Disable RVC Hint Instructions.",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.relax)] = .{
.llvm_name = "relax",
.description = "Enable Linker relaxation.",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.reserve_x1)] = .{
.llvm_name = "reserve-x1",
.description = "Reserve X1",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.reserve_x10)] = .{
.llvm_name = "reserve-x10",
.description = "Reserve X10",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.reserve_x11)] = .{
.llvm_name = "reserve-x11",
.description = "Reserve X11",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.reserve_x12)] = .{
.llvm_name = "reserve-x12",
.description = "Reserve X12",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.reserve_x13)] = .{
.llvm_name = "reserve-x13",
.description = "Reserve X13",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.reserve_x14)] = .{
.llvm_name = "reserve-x14",
.description = "Reserve X14",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.reserve_x15)] = .{
.llvm_name = "reserve-x15",
.description = "Reserve X15",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.reserve_x16)] = .{
.llvm_name = "reserve-x16",
.description = "Reserve X16",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.reserve_x17)] = .{
.llvm_name = "reserve-x17",
.description = "Reserve X17",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.reserve_x18)] = .{
.llvm_name = "reserve-x18",
.description = "Reserve X18",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.reserve_x19)] = .{
.llvm_name = "reserve-x19",
.description = "Reserve X19",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.reserve_x2)] = .{
.llvm_name = "reserve-x2",
.description = "Reserve X2",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.reserve_x20)] = .{
.llvm_name = "reserve-x20",
.description = "Reserve X20",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.reserve_x21)] = .{
.llvm_name = "reserve-x21",
.description = "Reserve X21",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.reserve_x22)] = .{
.llvm_name = "reserve-x22",
.description = "Reserve X22",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.reserve_x23)] = .{
.llvm_name = "reserve-x23",
.description = "Reserve X23",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.reserve_x24)] = .{
.llvm_name = "reserve-x24",
.description = "Reserve X24",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.reserve_x25)] = .{
.llvm_name = "reserve-x25",
.description = "Reserve X25",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.reserve_x26)] = .{
.llvm_name = "reserve-x26",
.description = "Reserve X26",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.reserve_x27)] = .{
.llvm_name = "reserve-x27",
.description = "Reserve X27",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.reserve_x28)] = .{
.llvm_name = "reserve-x28",
.description = "Reserve X28",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.reserve_x29)] = .{
.llvm_name = "reserve-x29",
.description = "Reserve X29",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.reserve_x3)] = .{
.llvm_name = "reserve-x3",
.description = "Reserve X3",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.reserve_x30)] = .{
.llvm_name = "reserve-x30",
.description = "Reserve X30",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.reserve_x31)] = .{
.llvm_name = "reserve-x31",
.description = "Reserve X31",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.reserve_x4)] = .{
.llvm_name = "reserve-x4",
.description = "Reserve X4",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.reserve_x5)] = .{
.llvm_name = "reserve-x5",
.description = "Reserve X5",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.reserve_x6)] = .{
.llvm_name = "reserve-x6",
.description = "Reserve X6",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.reserve_x7)] = .{
.llvm_name = "reserve-x7",
.description = "Reserve X7",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.reserve_x8)] = .{
.llvm_name = "reserve-x8",
.description = "Reserve X8",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.reserve_x9)] = .{
.llvm_name = "reserve-x9",
.description = "Reserve X9",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.save_restore)] = .{
.llvm_name = "save-restore",
.description = "Enable save/restore.",
.dependencies = featureSet(&[_]Feature{}),
};
const ti = @typeInfo(Feature);
for (result) |*elem, i| {
elem.index = i;
elem.name = ti.Enum.fields[i].name;
}
break :blk result;
};
pub const cpu = struct {
pub const baseline_rv32 = CpuModel{
.name = "baseline_rv32",
.llvm_name = null,
.features = featureSet(&[_]Feature{
.a,
.c,
.d,
.m,
}),
};
pub const baseline_rv64 = CpuModel{
.name = "baseline_rv64",
.llvm_name = null,
.features = featureSet(&[_]Feature{
.@"64bit",
.a,
.c,
.d,
.m,
}),
};
pub const generic_rv32 = CpuModel{
.name = "generic_rv32",
.llvm_name = "generic-rv32",
.features = featureSet(&[_]Feature{}),
};
pub const generic_rv64 = CpuModel{
.name = "generic_rv64",
.llvm_name = "generic-rv64",
.features = featureSet(&[_]Feature{
.@"64bit",
}),
};
pub const rocket_rv32 = CpuModel{
.name = "rocket_rv32",
.llvm_name = "rocket-rv32",
.features = featureSet(&[_]Feature{}),
};
pub const rocket_rv64 = CpuModel{
.name = "rocket_rv64",
.llvm_name = "rocket-rv64",
.features = featureSet(&[_]Feature{
.@"64bit",
}),
};
pub const sifive_7_rv32 = CpuModel{
.name = "sifive_7_rv32",
.llvm_name = "sifive-7-rv32",
.features = featureSet(&[_]Feature{}),
};
pub const sifive_7_rv64 = CpuModel{
.name = "sifive_7_rv64",
.llvm_name = "sifive-7-rv64",
.features = featureSet(&[_]Feature{
.@"64bit",
}),
};
pub const sifive_e31 = CpuModel{
.name = "sifive_e31",
.llvm_name = "sifive-e31",
.features = featureSet(&[_]Feature{
.a,
.c,
.m,
}),
};
pub const sifive_e76 = CpuModel{
.name = "sifive_e76",
.llvm_name = "sifive-e76",
.features = featureSet(&[_]Feature{
.a,
.c,
.f,
.m,
}),
};
pub const sifive_u54 = CpuModel{
.name = "sifive_u54",
.llvm_name = "sifive-u54",
.features = featureSet(&[_]Feature{
.@"64bit",
.a,
.c,
.d,
.m,
}),
};
pub const sifive_u74 = CpuModel{
.name = "sifive_u74",
.llvm_name = "sifive-u74",
.features = featureSet(&[_]Feature{
.@"64bit",
.a,
.c,
.d,
.m,
}),
};
}; | lib/std/target/riscv.zig |
const uefi = @import("std").os.uefi;
const Guid = uefi.Guid;
const Event = uefi.Event;
const Status = uefi.Status;
const Time = uefi.Time;
const Ip6ModeData = uefi.protocols.Ip6ModeData;
const Ip6Address = uefi.protocols.Ip6Address;
const ManagedNetworkConfigData = uefi.protocols.ManagedNetworkConfigData;
const SimpleNetworkMode = uefi.protocols.SimpleNetworkMode;
pub const Udp6Protocol = extern struct {
_get_mode_data: fn (*const Udp6Protocol, ?*Udp6ConfigData, ?*Ip6ModeData, ?*ManagedNetworkConfigData, ?*SimpleNetworkMode) callconv(.C) Status,
_configure: fn (*const Udp6Protocol, ?*const Udp6ConfigData) callconv(.C) Status,
_groups: fn (*const Udp6Protocol, bool, ?*const Ip6Address) callconv(.C) Status,
_transmit: fn (*const Udp6Protocol, *Udp6CompletionToken) callconv(.C) Status,
_receive: fn (*const Udp6Protocol, *Udp6CompletionToken) callconv(.C) Status,
_cancel: fn (*const Udp6Protocol, ?*Udp6CompletionToken) callconv(.C) Status,
_poll: fn (*const Udp6Protocol) callconv(.C) Status,
pub fn getModeData(self: *const Udp6Protocol, udp6_config_data: ?*Udp6ConfigData, ip6_mode_data: ?*Ip6ModeData, mnp_config_data: ?*ManagedNetworkConfigData, snp_mode_data: ?*SimpleNetworkMode) Status {
return self._get_mode_data(self, udp6_config_data, ip6_mode_data, mnp_config_data, snp_mode_data);
}
pub fn configure(self: *const Udp6Protocol, udp6_config_data: ?*const Udp6ConfigData) Status {
return self._configure(self, udp6_config_data);
}
pub fn groups(self: *const Udp6Protocol, join_flag: bool, multicast_address: ?*const Ip6Address) Status {
return self._groups(self, join_flag, multicast_address);
}
pub fn transmit(self: *const Udp6Protocol, token: *Udp6CompletionToken) Status {
return self._transmit(self, token);
}
pub fn receive(self: *const Udp6Protocol, token: *Udp6CompletionToken) Status {
return self._receive(self, token);
}
pub fn cancel(self: *const Udp6Protocol, token: ?*Udp6CompletionToken) Status {
return self._cancel(self, token);
}
pub fn poll(self: *const Udp6Protocol) Status {
return self._poll(self);
}
pub const guid align(8) = uefi.Guid{
.time_low = 0x4f948815,
.time_mid = 0xb4b9,
.time_high_and_version = 0x43cb,
.clock_seq_high_and_reserved = 0x8a,
.clock_seq_low = 0x33,
.node = [_]u8{ 0x90, 0xe0, 0x60, 0xb3, 0x49, 0x55 },
};
};
pub const Udp6ConfigData = extern struct {
accept_promiscuous: bool,
accept_any_port: bool,
allow_duplicate_port: bool,
traffic_class: u8,
hop_limit: u8,
receive_timeout: u32,
transmit_timeout: u32,
station_address: Ip6Address,
station_port: u16,
remote_address: Ip6Address,
remote_port: u16,
};
pub const Udp6CompletionToken = extern struct {
event: Event,
Status: usize,
packet: extern union {
RxData: *Udp6ReceiveData,
TxData: *Udp6TransmitData,
},
};
pub const Udp6ReceiveData = extern struct {
timestamp: Time,
recycle_signal: Event,
udp6_session: Udp6SessionData,
data_length: u32,
fragment_count: u32,
pub fn getFragments(self: *Udp6ReceiveData) []Udp6FragmentData {
return @ptrCast([*]Udp6FragmentData, @ptrCast([*]u8, self) + @sizeOf(Udp6ReceiveData))[0..self.fragment_count];
}
};
pub const Udp6TransmitData = extern struct {
udp6_session_data: ?*Udp6SessionData,
data_length: u32,
fragment_count: u32,
pub fn getFragments(self: *Udp6TransmitData) []Udp6FragmentData {
return @ptrCast([*]Udp6FragmentData, @ptrCast([*]u8, self) + @sizeOf(Udp6TransmitData))[0..self.fragment_count];
}
};
pub const Udp6SessionData = extern struct {
source_address: Ip6Address,
source_port: u16,
destination_address: Ip6Address,
destination_port: u16,
};
pub const Udp6FragmentData = extern struct {
fragment_length: u32,
fragment_buffer: [*]u8,
}; | lib/std/os/uefi/protocols/udp6_protocol.zig |
const std = @import("std");
usingnamespace (@import("../machine.zig"));
usingnamespace (@import("../util.zig"));
test "x87 floating point instructions" {
const m16 = Machine.init(.x86_16);
const m32 = Machine.init(.x86_32);
const m64 = Machine.init(.x64);
const sreg = Operand.register;
const memRm = Operand.memoryRmDef;
debugPrint(false);
{
testOp1(m64, .FLD, sreg(.ST0), "D9 C0");
testOp1(m64, .FLD, sreg(.ST1), "D9 C1");
testOp1(m64, .FLD, sreg(.ST2), "D9 C2");
testOp1(m64, .FLD, sreg(.ST3), "D9 C3");
testOp1(m64, .FLD, sreg(.ST4), "D9 C4");
testOp1(m64, .FLD, sreg(.ST5), "D9 C5");
testOp1(m64, .FLD, sreg(.ST6), "D9 C6");
testOp1(m64, .FLD, sreg(.ST7), "D9 C7");
}
{
const op1 = Operand.memoryRm(.DefaultSeg, .DWORD, .RAX, 0);
testOp1(m64, .FLD, op1, "D9 00");
}
{
const op1 = Operand.memoryRm(.DefaultSeg, .QWORD, .RAX, 0);
testOp1(m64, .FLD, op1, "DD 00");
}
{
const op1 = Operand.memoryRm(.DefaultSeg, .TBYTE, .RAX, 0);
testOp1(m64, .FLD, op1, "DB 28");
}
{
testOp1(m32, .FLDCW, memRm(.Void, .EAX, 0), "D9 28");
testOp1(m64, .FLDCW, memRm(.Void, .EAX, 0), "67 D9 28");
testOp1(m32, .FLDCW, memRm(.WORD, .EAX, 0), "D9 28");
testOp1(m64, .FLDCW, memRm(.WORD, .EAX, 0), "67 D9 28");
testOp1(m32, .FLDENV, memRm(.Void, .EAX, 0), "D9 20");
testOp1(m64, .FLDENV, memRm(.Void, .EAX, 0), "67 D9 20");
}
{
testOp1(m64, .FMUL, sreg(.ST0), "D8 C8");
testOp2(m64, .FMUL, sreg(.ST0), sreg(.ST7), "D8 CF");
testOp2(m64, .FMUL, sreg(.ST0), sreg(.ST0), "DC C8");
testOp2(m64, .FMUL, sreg(.ST7), sreg(.ST0), "DC CF");
testOp2(m64, .FMULP, sreg(.ST7), sreg(.ST0), "DE CF");
testOp0(m64, .FMULP, "DE C9");
testOp1(m64, .FIMUL, memRm( .WORD, .RAX, 0), "DE 08");
testOp1(m64, .FIMUL, memRm(.DWORD, .RAX, 0), "DA 08");
}
{
testOp1(m64, .FSAVE, memRm(.Void, .RAX, 0), "9B DD 30");
testOp1(m64, .FNSAVE, memRm(.Void, .RAX, 0), "DD 30");
}
// zero operands
{
testOp0(m64, .F2XM1, "D9 F0");
testOp0(m64, .FABS, "D9 E1");
testOp0(m64, .FADDP, "DE C1");
testOp0(m64, .FCHS, "D9 E0");
testOp0(m64, .FCLEX, "9B DB E2");
testOp0(m64, .FNCLEX, "DB E2");
testOp0(m64, .FCOM, "D8 D1");
testOp0(m64, .FCOMP, "D8 D9");
testOp0(m64, .FCOMPP, "DE D9");
testOp0(m64, .FDECSTP, "D9 F6");
testOp0(m64, .FDIVP, "DE F9");
testOp0(m64, .FDIVRP, "DE F1");
testOp0(m64, .FINCSTP, "D9 F7");
testOp0(m64, .FINIT, "9B DB E3");
testOp0(m64, .FNINIT, "DB E3");
testOp0(m64, .FLD1, "D9 E8");
testOp0(m64, .FLDL2T, "D9 E9");
testOp0(m64, .FLDL2E, "D9 EA");
testOp0(m64, .FLDPI, "D9 EB");
testOp0(m64, .FLDLG2, "D9 EC");
testOp0(m64, .FLDLN2, "D9 ED");
testOp0(m64, .FLDZ, "D9 EE");
testOp0(m64, .FMULP, "DE C9");
testOp0(m64, .FSUBP, "DE E9");
testOp0(m64, .FNOP, "D9 D0");
testOp0(m64, .FPATAN, "D9 F3");
testOp0(m64, .FPREM, "D9 F8");
testOp0(m64, .FPTAN, "D9 F2");
testOp0(m64, .FRNDINT, "D9 FC");
testOp0(m64, .FSCALE, "D9 FD");
testOp0(m64, .FSQRT, "D9 FA");
testOp0(m64, .FSUBRP, "DE E1");
testOp0(m64, .FTST, "D9 E4");
testOp0(m64, .FWAIT, "9B");
testOp0(m64, .FXAM, "D9 E5");
testOp0(m64, .FXCH, "D9 C9");
testOp0(m64, .FXTRACT, "D9 F4");
testOp0(m64, .FYL2X, "D9 F1");
testOp0(m64, .FYL2XP1, "D9 F9");
testOp0(m64, .FCOS, "D9 FF");
testOp0(m64, .FPREM1, "D9 F5");
testOp0(m64, .FSIN, "D9 FE");
testOp0(m64, .FSINCOS, "D9 FB");
testOp0(m64, .FUCOM, "DD E1");
testOp0(m64, .FUCOMP, "DD E9");
testOp0(m64, .FUCOMPP, "DA E9");
}
// one ST(i) reg operand
{
testOp1(m64, .FADD, sreg(.ST1), "D8 C1");
testOp1(m64, .FCOM, sreg(.ST1), "D8 D1");
testOp1(m64, .FCOMP, sreg(.ST1), "D8 D9");
testOp1(m64, .FDIV, sreg(.ST1), "D8 F1");
testOp1(m64, .FDIVR, sreg(.ST1), "D8 F9");
testOp1(m64, .FFREE, sreg(.ST1), "DD C1");
testOp1(m64, .FFREEP, sreg(.ST1), "DF C1");
testOp1(m64, .FLD, sreg(.ST1), "D9 C1");
testOp1(m64, .FMUL, sreg(.ST1), "D8 C9");
testOp1(m64, .FSUB, sreg(.ST1), "D8 E1");
testOp1(m64, .FSUBR, sreg(.ST1), "D8 E9");
testOp1(m64, .FST, sreg(.ST1), "DD D1");
testOp1(m64, .FSTP, sreg(.ST1), "DD D9");
testOp1(m64, .FXCH, sreg(.ST1), "D9 C9");
testOp1(m64, .FUCOM, sreg(.ST1), "DD E1");
testOp1(m64, .FUCOMP, sreg(.ST1), "DD E9");
testOp1(m64, .FCMOVB, sreg(.ST1), "DA C1");
testOp1(m64, .FCMOVE, sreg(.ST1), "DA C9");
testOp1(m64, .FCMOVBE, sreg(.ST1), "DA D1");
testOp1(m64, .FCMOVU, sreg(.ST1), "DA D9");
testOp1(m64, .FCMOVNB, sreg(.ST1), "DB C1");
testOp1(m64, .FCMOVNE, sreg(.ST1), "DB C9");
testOp1(m64, .FCMOVNBE, sreg(.ST1), "DB D1");
testOp1(m64, .FCMOVNU, sreg(.ST1), "DB D9");
testOp1(m64, .FCOMI, sreg(.ST1), "DB F1");
testOp1(m64, .FCOMIP, sreg(.ST1), "DF F1");
testOp1(m64, .FUCOMI, sreg(.ST1), "DB E9");
testOp1(m64, .FUCOMIP, sreg(.ST1), "DF E9");
// st(0)
testOp1(m64, .FCHS, sreg(.ST0), "D9 E0");
}
{
testOp2(m64, .FADD, sreg(.ST0), sreg(.ST1), "D8 C1");
testOp2(m64, .FCOM, sreg(.ST0), sreg(.ST1), "D8 D1");
testOp2(m64, .FCOMP, sreg(.ST0), sreg(.ST1), "D8 D9");
testOp2(m64, .FDIV, sreg(.ST0), sreg(.ST1), "D8 F1");
testOp2(m64, .FDIVR, sreg(.ST0), sreg(.ST1), "D8 F9");
testOp2(m64, .FMUL, sreg(.ST0), sreg(.ST1), "D8 C9");
testOp2(m64, .FSUB, sreg(.ST0), sreg(.ST1), "D8 E1");
testOp2(m64, .FSUBR, sreg(.ST0), sreg(.ST1), "D8 E9");
testOp2(m64, .FST, sreg(.ST0), sreg(.ST1), "DD D1");
testOp2(m64, .FSTP, sreg(.ST0), sreg(.ST1), "DD D9");
testOp2(m64, .FXCH, sreg(.ST0), sreg(.ST1), "D9 C9");
testOp2(m64, .FUCOM, sreg(.ST0), sreg(.ST1), "DD E1");
testOp2(m64, .FUCOMP, sreg(.ST0), sreg(.ST1), "DD E9");
testOp2(m64, .FCMOVB, sreg(.ST0), sreg(.ST1), "DA C1");
testOp2(m64, .FCMOVE, sreg(.ST0), sreg(.ST1), "DA C9");
testOp2(m64, .FCMOVBE, sreg(.ST0), sreg(.ST1), "DA D1");
testOp2(m64, .FCMOVU, sreg(.ST0), sreg(.ST1), "DA D9");
testOp2(m64, .FCMOVNB, sreg(.ST0), sreg(.ST1), "DB C1");
testOp2(m64, .FCMOVNE, sreg(.ST0), sreg(.ST1), "DB C9");
testOp2(m64, .FCMOVNBE, sreg(.ST0), sreg(.ST1), "DB D1");
testOp2(m64, .FCMOVNU, sreg(.ST0), sreg(.ST1), "DB D9");
testOp2(m64, .FCOMI, sreg(.ST0), sreg(.ST1), "DB F1");
testOp2(m64, .FCOMIP, sreg(.ST0), sreg(.ST1), "DF F1");
testOp2(m64, .FUCOMI, sreg(.ST0), sreg(.ST1), "DB E9");
testOp2(m64, .FUCOMIP, sreg(.ST0), sreg(.ST1), "DF E9");
}
{
testOp2(m64, .FADD, sreg(.ST1), sreg(.ST0), "DC C1");
testOp2(m64, .FADDP, sreg(.ST1), sreg(.ST0), "DE C1");
testOp2(m64, .FDIV, sreg(.ST1), sreg(.ST0), "DC F9");
testOp2(m64, .FDIVP, sreg(.ST1), sreg(.ST0), "DE F9");
testOp2(m64, .FDIVR, sreg(.ST1), sreg(.ST0), "DC F1");
testOp2(m64, .FDIVRP, sreg(.ST1), sreg(.ST0), "DE F1");
testOp2(m64, .FMUL, sreg(.ST1), sreg(.ST0), "DC C9");
testOp2(m64, .FMULP, sreg(.ST1), sreg(.ST0), "DE C9");
testOp2(m64, .FSUB, sreg(.ST1), sreg(.ST0), "DC E9");
testOp2(m64, .FSUBP, sreg(.ST1), sreg(.ST0), "DE E9");
testOp2(m64, .FSUBR, sreg(.ST1), sreg(.ST0), "DC E1");
testOp2(m64, .FSUBRP, sreg(.ST1), sreg(.ST0), "DE E1");
}
{
const op1 = Operand.memoryRm(.DefaultSeg, .WORD, .RAX, 0);
testOp1(m64, .FIADD, op1, "DE 00");
testOp1(m64, .FIDIV, op1, "DE 30");
testOp1(m64, .FIDIVR, op1, "DE 38");
testOp1(m64, .FICOM, op1, "DE 10");
testOp1(m64, .FICOMP, op1, "DE 18");
testOp1(m64, .FILD, op1, "DF 00");
testOp1(m64, .FIST, op1, "DF 10");
testOp1(m64, .FISTP, op1, "DF 18");
testOp1(m64, .FIMUL, op1, "DE 08");
testOp1(m64, .FSTCW, op1, "9B D9 38");
testOp1(m64, .FNSTCW, op1, "D9 38");
testOp1(m64, .FSTSW, op1, "9B DD 38");
testOp1(m64, .FNSTSW, op1, "DD 38");
testOp1(m64, .FISUB, op1, "DE 20");
testOp1(m64, .FISUBR, op1, "DE 28");
}
{
const op1 = Operand.register(.AX);
testOp1(m64, .FSTSW, op1, "9B DF E0");
testOp1(m64, .FNSTSW, op1, "DF E0");
}
{
const op1 = Operand.memoryRm(.DefaultSeg, .DWORD, .RAX, 0);
testOp1(m64, .FADD, op1, "D8 00");
testOp1(m64, .FIADD, op1, "DA 00");
testOp1(m64, .FCOM, op1, "D8 10");
testOp1(m64, .FCOMP, op1, "D8 18");
testOp1(m64, .FDIV, op1, "D8 30");
testOp1(m64, .FIDIV, op1, "DA 30");
testOp1(m64, .FDIVR, op1, "D8 38");
testOp1(m64, .FIDIVR, op1, "DA 38");
testOp1(m64, .FICOM, op1, "DA 10");
testOp1(m64, .FICOMP, op1, "DA 18");
testOp1(m64, .FILD, op1, "DB 00");
testOp1(m64, .FIST, op1, "DB 10");
testOp1(m64, .FISTP, op1, "DB 18");
testOp1(m64, .FLD, op1, "D9 00");
testOp1(m64, .FMUL, op1, "D8 08");
testOp1(m64, .FIMUL, op1, "DA 08");
testOp1(m64, .FST, op1, "D9 10");
testOp1(m64, .FSTP, op1, "D9 18");
testOp1(m64, .FSUB, op1, "D8 20");
testOp1(m64, .FISUB, op1, "DA 20");
testOp1(m64, .FSUBR, op1, "D8 28");
testOp1(m64, .FISUBR, op1, "DA 28");
}
{
const op1 = Operand.memoryRm(.DefaultSeg, .QWORD, .RAX, 0);
testOp1(m64, .FADD, op1, "DC 00");
testOp1(m64, .FCOM, op1, "DC 10");
testOp1(m64, .FCOMP, op1, "DC 18");
testOp1(m64, .FDIV, op1, "DC 30");
testOp1(m64, .FDIVR, op1, "DC 38");
testOp1(m64, .FILD, op1, "DF 28");
testOp1(m64, .FISTP, op1, "DF 38");
testOp1(m64, .FLD, op1, "DD 00");
testOp1(m64, .FMUL, op1, "DC 08");
testOp1(m64, .FST, op1, "DD 10");
testOp1(m64, .FSTP, op1, "DD 18");
testOp1(m64, .FSUB, op1, "DC 20");
testOp1(m64, .FSUBR, op1, "DC 28");
}
{
const op1 = Operand.memoryRm(.DefaultSeg, .Void, .EAX, 0);
testOp1(m64, .FRSTOR, op1, "67 DD 20");
testOp1(m64, .FRSTORD, op1, "67 DD 20");
testOp1(m64, .FRSTORW, op1, "66 67 DD 20");
testOp1(m64, .FSAVE, op1, "9B 67 DD 30");
testOp1(m64, .FSAVED, op1, "9B 67 DD 30");
testOp1(m64, .FSAVEW, op1, "9B 66 67 DD 30");
testOp1(m64, .FNSAVE, op1, "67 DD 30");
testOp1(m64, .FNSAVED, op1, "67 DD 30");
testOp1(m64, .FNSAVEW, op1, "66 67 DD 30");
testOp1(m64, .FSTENV, op1, "9B 67 D9 30");
testOp1(m64, .FSTENVD, op1, "9B 67 D9 30");
testOp1(m64, .FSTENVW, op1, "9B 66 67 D9 30");
testOp1(m64, .FNSTENV, op1, "67 D9 30");
testOp1(m64, .FNSTENVD, op1, "67 D9 30");
testOp1(m64, .FNSTENVW, op1, "66 67 D9 30");
testOp1(m32, .FRSTOR, op1, "DD 20");
testOp1(m32, .FRSTORD, op1, "DD 20");
testOp1(m32, .FRSTORW, op1, "66 DD 20");
testOp1(m32, .FSAVE, op1, "9B DD 30");
testOp1(m32, .FSAVED, op1, "9B DD 30");
testOp1(m32, .FSAVEW, op1, "9B 66 DD 30");
testOp1(m32, .FNSAVE, op1, "DD 30");
testOp1(m32, .FNSAVED, op1, "DD 30");
testOp1(m32, .FNSAVEW, op1, "66 DD 30");
testOp1(m32, .FSTENV, op1, "9B D9 30");
testOp1(m32, .FSTENVD, op1, "9B D9 30");
testOp1(m32, .FSTENVW, op1, "9B 66 D9 30");
testOp1(m32, .FNSTENV, op1, "D9 30");
testOp1(m32, .FNSTENVD, op1, "D9 30");
testOp1(m32, .FNSTENVW, op1, "66 D9 30");
testOp1(m16, .FRSTOR, op1, "67 DD 20");
testOp1(m16, .FRSTORD, op1, "66 67 DD 20");
testOp1(m16, .FRSTORW, op1, "67 DD 20");
testOp1(m16, .FSAVE, op1, "9B 67 DD 30");
testOp1(m16, .FSAVED, op1, "9B 66 67 DD 30");
testOp1(m16, .FSAVEW, op1, "9B 67 DD 30");
testOp1(m16, .FNSAVE, op1, "67 DD 30");
testOp1(m16, .FNSAVED, op1, "66 67 DD 30");
testOp1(m16, .FNSAVEW, op1, "67 DD 30");
testOp1(m16, .FSTENV, op1, "9B 67 D9 30");
testOp1(m16, .FSTENVD, op1, "9B 66 67 D9 30");
testOp1(m16, .FSTENVW, op1, "9B 67 D9 30");
testOp1(m16, .FNSTENV, op1, "67 D9 30");
testOp1(m16, .FNSTENVD, op1, "66 67 D9 30");
testOp1(m16, .FNSTENVW, op1, "67 D9 30");
testOp1(m64, .FSTSW, op1, "9B 67 DD 38");
testOp1(m64, .FNSTSW, op1, "67 DD 38");
testOp1(m64, .FSTCW, op1, "9B 67 D9 38");
testOp1(m64, .FNSTCW, op1, "67 D9 38");
}
{
const op1 = Operand.memoryRm(.DefaultSeg, .TBYTE, .RAX, 0);
testOp1(m64, .FBLD, op1, "DF 20");
testOp1(m64, .FBSTP, op1, "DF 30");
testOp1(m64, .FLD, op1, "DB 28");
testOp1(m64, .FSTP, op1, "DB 38");
}
} | src/x86/tests/float_x87.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const Value = @import("./value.zig").Value;
const String = @import("./object.zig").Obj.String;
const table_max_load = 0.75;
const Entry = struct {
key: ?*String = null,
value: Value = Value.nil,
};
pub const Table = struct {
count: u32,
entries: []Entry,
allocator: *Allocator,
pub fn init(allocator: *Allocator) Table {
return Table{
.count = 0,
.entries = &[_]Entry{},
.allocator = allocator,
};
}
/// adds the entry .{key, value} to the map, if the key already exists repalce the value,
/// return true when the key is inserted, false when key was already present
pub fn set(self: *Table, key: *String, value: Value) bool {
const capacity = self.entries.len;
if (@intToFloat(f64, self.count + 1) > @intToFloat(f64, capacity) * table_max_load) {
const new_capacity = if (capacity < 8) 8 else capacity * 2;
self.adjustCapacity(new_capacity);
}
const entry = findEntry(self.entries, key);
const is_new_key = entry.key == null;
if (is_new_key and entry.value.isNil()) self.count += 1;
entry.key = key;
entry.value = value;
return is_new_key;
}
pub fn get(self: *Table, key: *String) ?*Value {
if (self.count == 0) return null;
const entry = findEntry(self.entries, key);
if (entry.key == null) return null;
return &entry.value;
}
/// Return true when the entry is deleted from the table, false otherwise
pub fn delete(self: *Table, key: *String) bool {
if (self.count == 0) return false;
const entry = findEntry(self.entries, key);
if (entry.key == null) return false;
entry.key = null;
entry.value = Value.fromBool(true);
return true;
}
pub fn findString(self: *Table, bytes: []const u8, hash: u32) ?*String {
if (self.count == 0) return null;
var index = hash % self.entries.len;
while (true) {
const entry = &self.entries[index];
if (entry.key == null and entry.value.isNil()) return null;
if (hash == entry.key.?.hash and std.mem.eql(u8, entry.key.?.bytes, bytes)) return entry.key.?;
index = (index + 1) % self.entries.len;
}
}
pub fn deinit(self: *Table) void {
self.allocator.free(self.entries);
self.count = 0;
}
pub fn addAll(self: *Table, from: *Table) void {
for (from.entries) |*entry| {
if (entry.key != null) {
self.set(entry.key, entry.value);
}
}
}
fn adjustCapacity(self: *Table, new_capacity: usize) void {
const entries = self.allocator.alloc(Entry, new_capacity) catch @panic("Error allocating memery for new entries!");
for (entries) |*e| {
e.* = Entry{};
}
self.count = 0;
for (self.entries) |e| {
if (e.key == null) continue;
const dst: *Entry = findEntry(entries, e.key.?);
dst.key = e.key;
dst.value = e.value;
self.count += 1;
}
self.allocator.free(self.entries);
self.entries = entries;
}
fn findEntry(entries: []Entry, key: *String) *Entry {
const capacity = entries.len;
var index = key.hash % capacity;
var tombstone: ?*Entry = null;
while (true) {
const entry = &entries[index];
if (entry.key == null) {
if (entry.value.isNil()) {
// not a tombstone
return tombstone orelse entry;
} else {
// Found a tombstone
tombstone = entry;
}
return entry;
} else if (entry.key == key) {
return entry;
}
index = (index + 1) % capacity;
}
}
pub fn debug(self: *Table) void {
std.debug.print("[\n", .{});
for (self.entries) |entry| {
if (entry.key) |e| {
std.debug.print(" {s} => ", .{e.bytes});
} else {
std.debug.print(" -- => ", .{});
}
std.debug.print("{any}\n", .{entry.value});
}
std.debug.print("]\n", .{});
}
};
test "Add entry" {
const Vm = @import("./vm.zig").Vm;
const testing = std.testing;
var vm = Vm.init(testing.allocator);
defer vm.deinit();
var table = Table.init(testing.allocator);
defer table.deinit();
var k1 = String.copy(&vm, "Key1");
var result = table.set(k1, Value.fromBool(true));
try testing.expect(result);
result = table.set(k1, Value.fromNumber(13.0));
try testing.expect(!result);
}
test "query entry" {
const Vm = @import("./vm.zig").Vm;
const testing = std.testing;
var vm = Vm.init(testing.allocator);
defer vm.deinit();
var table = Table.init(testing.allocator);
defer table.deinit();
var k1 = String.copy(&vm, "Key1");
var result = table.set(k1, Value.fromNumber(42.0));
try testing.expect(result);
var val = table.get(k1);
try testing.expect(val != null);
try testing.expect(val.?.equals(Value.fromNumber(42.0)));
var k2 = String.copy(&vm, "NoExistant");
val = table.get(k2);
try testing.expectEqual(val, null);
}
test "delete entry" {
const Vm = @import("./vm.zig").Vm;
const testing = std.testing;
var vm = Vm.init(testing.allocator);
defer vm.deinit();
var table = Table.init(testing.allocator);
defer table.deinit();
var k1 = String.copy(&vm, "Key1");
var result = table.set(k1, Value.fromNumber(42.0));
try testing.expect(result);
result = table.delete(k1);
try testing.expect(result);
const val = table.get(k1);
try testing.expectEqual(val, null);
result = table.delete(k1);
try testing.expect(!result);
}
test "find string" {
const Vm = @import("./vm.zig").Vm;
const testing = std.testing;
var vm = Vm.init(testing.allocator);
defer vm.deinit();
var table = Table.init(testing.allocator);
defer table.deinit();
var k1 = String.copy(&vm, "Key1");
var result = table.set(k1, Value.fromNumber(42.0));
try testing.expect(result);
var k2 = table.findString("Key1", 506120967).?;
testing.expect(k1 == k2) catch {
std.debug.print("Expected k1: {*} == k2: {*}", .{ k1, k2 });
return error.TestUnexpectedResult;
};
}
test "add two" {
const Vm = @import("./vm.zig").Vm;
const testing = std.testing;
var vm = Vm.init(testing.allocator);
defer vm.deinit();
var table = Table.init(testing.allocator);
defer table.deinit();
var k1 = String.copy(&vm, "one");
var k2 = String.copy(&vm, "two");
var k3 = String.copy(&vm, "three");
var k4 = String.copy(&vm, "four");
var result = table.set(k1, Value.fromNumber(1.0));
try testing.expect(result);
result = table.set(k2, Value.fromNumber(2.0));
try testing.expect(result);
result = table.set(k3, Value.fromNumber(3.0));
try testing.expect(result);
result = table.set(k4, Value.fromNumber(4.0));
try testing.expect(result);
var val = table.get(k1);
try testing.expect(val != null);
val = table.get(k1);
try testing.expect(val != null);
} | src/table.zig |
const std = @import("std");
const zp = @import("../../zplay.zig");
const event = zp.event;
const sdl = zp.deps.sdl;
const sdl_impl = @import("sdl_impl.zig");
pub const c = @import("c.zig");
/// export friendly api
pub usingnamespace @import("api.zig");
/// icon font: font-awesome
pub const fontawesome = @import("fonts/fontawesome.zig");
/// export 3rd-party extensions
pub const ext = @import("ext/ext.zig");
extern fn _ImGui_ImplOpenGL3_Init(glsl_version: [*c]u8) bool;
extern fn _ImGui_ImplOpenGL3_Shutdown() void;
extern fn _ImGui_ImplOpenGL3_NewFrame() void;
extern fn _ImGui_ImplOpenGL3_RenderDrawData(draw_data: *c.ImDrawData) void;
/// internal static vars
var initialized = false;
var plot_ctx: ?*ext.plot.ImPlotContext = undefined;
var nodes_ctx: ?*ext.nodes.ImNodesContext = undefined;
/// initialize sdl2 and opengl3 backend
pub fn init(window: sdl.Window) !void {
_ = c.igCreateContext(null);
try sdl_impl.init(window.ptr);
if (!_ImGui_ImplOpenGL3_Init(null)) {
std.debug.panic("init render backend failed", .{});
}
plot_ctx = ext.plot.createContext();
if (plot_ctx == null) {
std.debug.panic("init imgui-extension:implot failed", .{});
}
nodes_ctx = ext.nodes.createContext();
if (nodes_ctx == null) {
std.debug.panic("init imgui-extension:imnodes failed", .{});
}
initialized = true;
}
/// release allocated resources
pub fn deinit() void {
if (!initialized) {
std.debug.panic("cimgui isn't initialized!", .{});
}
ext.nodes.destroyContext(nodes_ctx);
ext.plot.destroyContext(plot_ctx);
sdl_impl.deinit();
_ImGui_ImplOpenGL3_Shutdown();
initialized = false;
}
/// process i/o event
pub fn processEvent(e: event.Event) bool {
if (!initialized) {
std.debug.panic("cimgui isn't initialized!", .{});
}
return sdl_impl.processEvent(e);
}
/// begin frame
pub fn beginFrame() void {
if (!initialized) {
std.debug.panic("cimgui isn't initialized!", .{});
}
sdl_impl.newFrame();
_ImGui_ImplOpenGL3_NewFrame();
c.igNewFrame();
}
/// end frame
pub fn endFrame() void {
if (!initialized) {
std.debug.panic("cimgui isn't initialized!", .{});
}
c.igRender();
_ImGui_ImplOpenGL3_RenderDrawData(c.igGetDrawData());
}
/// load font awesome
pub fn loadFontAwesome(size: f32, regular: bool, monospaced: bool) !*c.ImFont {
if (!initialized) {
std.debug.panic("cimgui isn't initialized!", .{});
}
var font_atlas = c.igGetIO().*.Fonts;
_ = c.ImFontAtlas_AddFontDefault(
font_atlas,
null,
);
var ranges = [3]c.ImWchar{
fontawesome.ICON_MIN_FA,
fontawesome.ICON_MAX_FA,
0,
};
var cfg = c.ImFontConfig_ImFontConfig();
defer c.ImFontConfig_destroy(cfg);
cfg.*.PixelSnapH = true;
cfg.*.MergeMode = true;
if (monospaced) {
cfg.*.GlyphMinAdvanceX = size;
}
const font = c.ImFontAtlas_AddFontFromFileTTF(
font_atlas,
if (regular)
fontawesome.FONT_ICON_FILE_NAME_FAR
else
fontawesome.FONT_ICON_FILE_NAME_FAS,
size,
cfg,
&ranges,
);
if (font == null) {
std.debug.panic("load font awesome failed!", .{});
}
if (!c.ImFontAtlas_Build(font_atlas)) {
std.debug.panic("build font atlas failed!", .{});
}
return font;
}
/// load custom font
pub fn loadTTF(
path: [:0]const u8,
size: f32,
addional_ranges: ?[*c]const c.ImWchar,
) !*c.ImFont {
if (!initialized) {
std.debug.panic("cimgui isn't initialized!", .{});
}
var font_atlas = c.igGetIO().*.Fonts;
var default_ranges = c.ImFontAtlas_GetGlyphRangesDefault(font_atlas);
var font = c.ImFontAtlas_AddFontFromFileTTF(
font_atlas,
path.ptr,
size,
null,
default_ranges,
);
if (font == null) {
std.debug.panic("load font({s}) failed!", .{path});
}
if (addional_ranges) |ranges| {
var cfg = c.ImFontConfig_ImFontConfig();
defer c.ImFontConfig_destroy(cfg);
cfg.*.MergeMode = true;
font = c.ImFontAtlas_AddFontFromFileTTF(
font_atlas,
path.ptr,
size,
cfg,
ranges,
);
if (font == null) {
std.debug.panic("load font({s}) failed!", .{path});
}
}
if (!c.ImFontAtlas_Build(font_atlas)) {
std.debug.panic("build font atlas failed!", .{});
}
return font;
}
/// determine whether next character in given buffer is renderable
pub fn isCharRenderable(buf: []const u8) bool {
var char: c_uint = undefined;
_ = c.igImTextCharFromUtf8(&char, buf.ptr, buf.ptr + buf.len);
if (char == 0) {
return false;
}
return c.ImFont_FindGlyphNoFallback(
c.igGetFont(),
@intCast(c.ImWchar, char),
) != null;
} | src/deps/imgui/imgui.zig |
const std = @import("std");
const Value = @import("Value.zig");
const Gc = @import("Gc.zig");
pub const BuiltinError = error{ OutOfMemory, UnsupportedType, MismatchingTypes };
const BuiltinFn = Value.NativeFn;
pub const builtins = std.ComptimeStringMap(*Value, .{
.{ "len", &len_func.base },
.{ "add", &add_func.base },
.{ "pop", &pop_func.base },
});
var len_func = Value.Native{ .base = .{ .ty = .native, .is_marked = false, .next = null }, .func = len, .arg_len = 0 };
var add_func = Value.Native{ .base = .{ .ty = .native, .is_marked = false, .next = null }, .func = add, .arg_len = 1 };
var pop_func = Value.Native{ .base = .{ .ty = .native, .is_marked = false, .next = null }, .func = pop, .arg_len = 0 };
/// Returns the length of the `Value`.
/// Supports strings, arrays and maps.
fn len(gc: *Gc, args: []*Value) BuiltinError!*Value {
std.debug.assert(args.len == 1);
const arg = args[0];
const length: i64 = switch (arg.ty) {
.string => @intCast(i64, arg.toString().value.len),
.list => @intCast(i64, arg.toList().value.items.len),
.map => @intCast(i64, arg.toMap().value.items().len),
else => return BuiltinError.UnsupportedType,
};
return Value.Integer.create(gc, length);
}
/// Appends a new value to the list
fn add(gc: *Gc, args: []*Value) BuiltinError!*Value {
std.debug.assert(args.len >= 2);
return switch (args[0].ty) {
.list => {
var list = args[0].toList();
const val = args[args.len - 1];
if (list.value.items.len > 0) {
if (list.value.items[0].ty != val.ty) {
return BuiltinError.MismatchingTypes;
}
}
try list.value.append(gc.gpa, val);
return args[0];
},
.map => {
var map = args[0].toMap();
const key = args[args.len - 2];
const val = args[args.len - 1];
if (map.value.items().len > 0) {
const entry = map.value.items()[0];
if (entry.key.ty != key.ty) {
return BuiltinError.MismatchingTypes;
}
if (entry.value.ty != val.ty) {
return BuiltinError.MismatchingTypes;
}
}
try map.value.put(gc.gpa, key, val);
return args[0];
},
else => BuiltinError.UnsupportedType,
};
}
/// Pops the last value of a list and returns said value
/// Assures the list as atleast 1 value
fn pop(gc: *Gc, args: []*Value) BuiltinError!*Value {
std.debug.assert(args.len == 1);
return switch (args[0].ty) {
.list => {
return args[0].toList().value.pop();
},
else => BuiltinError.UnsupportedType,
};
} | src/builtins.zig |
const std = @import("std");
pub const Markov = struct {
rows: std.StringHashMap(std.StringHashMap(u8)),
firsts: std.StringHashMap(u8),
final: []u8 = undefined,
arena: std.heap.ArenaAllocator,
pub fn init() Markov {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
return .{
.rows = std.StringHashMap(std.StringHashMap(u8)).init(&arena.allocator),
.firsts = std.StringHashMap(u8).init(&arena.allocator),
.arena = arena,
};
}
pub fn deinit(self: *Markov) void {
self.arena.deinit();
}
fn choose(hashmap: std.StringHashMap(u8)) []const u8 {
var n: i32 = 0;
for (hashmap.items()) |entry| {
n += @intCast(i32, entry.value);
}
if (n <= 1) return hashmap.items()[0].key;
n = aya.math.rand.range(i32, 0, n);
for (hashmap.items()) |entry| {
n = n - @intCast(i32, entry.value);
if (n < 0) return entry.key;
}
unreachable;
}
pub fn generateChain(data: []const u8, width: usize, height: usize) []const u8 {
aya.math.rand.seed(@intCast(u64, std.time.milliTimestamp()));
var markov = Markov.init();
defer markov.deinit();
markov.addSourceMap(data, width, height);
var res = std.ArrayList([]const u8).init(&markov.arena.allocator);
var item = choose(markov.firsts);
while (!std.mem.eql(u8, item, markov.final)) {
res.append(item) catch unreachable;
item = choose(markov.rows.get(item).?);
}
var new_map = markov.arena.allocator.alloc(u8, res.items.len * width) catch unreachable;
var i: usize = 0;
for (res.items) |row| {
for (row) |tile| {
new_map[i] = tile;
i += 1;
}
}
return markov.generate(20);
}
pub fn generate(self: *Markov, min_rows: usize) []const u8 {
var res = std.ArrayList([]const u8).init(&self.arena.allocator);
var item = choose(self.firsts);
while (res.items.len < min_rows) {
while (!std.mem.eql(u8, item, self.final)) {
res.append(item) catch unreachable;
item = choose(self.rows.get(item).?);
}
// reset item for the next iteration
item = choose(self.rows.items()[aya.math.rand.range(usize, 0, self.rows.items().len)].value);
}
res.append(self.final) catch unreachable;
var new_map = aya.mem.allocator.alloc(u8, res.items.len * res.items[0].len) catch unreachable;
var i: usize = 0;
for (res.items) |row| {
for (row) |tile| {
new_map[i] = tile;
i += 1;
}
}
return new_map;
}
pub fn addSourceMap(self: *Markov, data: []const u8, width: usize, height: usize) void {
var all_rows = self.arena.allocator.alloc([]u8, height) catch unreachable;
var y: usize = 0;
while (y < height) : (y += 1) {
var current_row = self.arena.allocator.alloc(u8, width) catch unreachable;
var x: usize = 0;
while (x < width) : (x += 1) {
current_row[x] = data[x + y * width];
}
all_rows[y] = current_row;
}
incrementItemCount(&self.firsts, all_rows[0]);
for (all_rows) |row, i| {
if (i == 0) continue;
self.updateItem(all_rows[i - 1], row);
}
self.final = all_rows[all_rows.len - 1];
self.updateItem(self.final, self.final);
}
fn incrementItemCount(hashmap: *std.StringHashMap(u8), row: []u8) void {
var res = hashmap.getOrPut(row) catch unreachable;
if (!res.found_existing) {
res.entry.value = 1;
} else {
res.entry.value += 1;
}
}
fn updateItem(self: *Markov, item: []u8, next: []u8) void {
var entry = self.rows.getOrPut(item) catch unreachable;
if (!entry.found_existing) {
entry.entry.value = std.StringHashMap(u8).init(&self.arena.allocator);
}
incrementItemCount(&entry.entry.value, next);
}
}; | src/tilemaps/markov.zig |
const std = @import("std");
const mem = std.mem;
const testing = std.testing;
const build_options = @import("build_options");
const amqp = @import("zamqp");
const server = @import("server.zig");
var logOut: enum { syslog, stderr } = .syslog;
// override the std implementation
pub fn log(
comptime level: std.log.Level,
comptime scope: @TypeOf(.EnumLiteral),
comptime format: []const u8,
args: anytype,
) void {
const scope_prefix = if (scope == .default) "" else "(" ++ @tagName(scope) ++ "): ";
switch (logOut) {
.syslog => {
var buf: [4096]u8 = undefined;
const printed = std.fmt.bufPrintZ(&buf, scope_prefix ++ format, args) catch blk: {
buf[buf.len - 1] = 0;
break :blk buf[0 .. buf.len - 1 :0];
};
std.c.syslog(@enumToInt(level), "%s", printed.ptr);
},
.stderr => {
const level_prefix = "[" ++ @tagName(level) ++ "] ";
std.debug.print(level_prefix ++ scope_prefix ++ format ++ "\n", args);
},
}
}
fn fatal(comptime fmt: []const u8, args: anytype) noreturn {
std.debug.print("ERROR: " ++ fmt ++ "\n", args);
std.os.exit(1);
}
// percent decodes the query in-place
const UriQueryIterator = struct {
query: [:0]u8,
pos: usize = 0,
pub const Param = struct {
name: [:0]const u8,
value: ?[:0]const u8,
};
pub fn next(self: *UriQueryIterator) !?Param {
if (self.pos >= self.query.len) return null;
const start_pos = self.pos;
var write_pos = self.pos;
var param = Param{
.name = undefined,
.value = null,
};
if (self.query[self.pos] == '=' or self.query[self.pos] == '&') return error.BadUri;
self.query[write_pos] = try self.eatChar();
write_pos += 1;
while (true) {
if (self.pos >= self.query.len or self.query[self.pos] == '&') {
param.name = finishWord(self, start_pos, write_pos);
return param;
} else if (self.query[self.pos] == '=') {
param.name = finishWord(self, start_pos, write_pos);
write_pos += 1;
break;
} else {
self.query[write_pos] = try self.eatChar();
write_pos += 1;
}
}
while (true) {
if (self.pos >= self.query.len or self.query[self.pos] == '&') {
param.value = finishWord(self, start_pos + param.name.len + 1, write_pos);
return param;
} else {
self.query[write_pos] = try self.eatChar();
write_pos += 1;
}
}
}
fn eatChar(self: *UriQueryIterator) !u8 {
switch (self.query[self.pos]) {
'%' => {
if (self.pos + 3 > self.query.len) return error.BadUri;
const char = std.fmt.parseUnsigned(u8, self.query[self.pos + 1 .. self.pos + 3], 16) catch return error.BadUri;
self.pos += 3;
return if (char != 0) char else error.BadUri;
},
0 => {
return error.BadUri;
},
else => |char| {
self.pos += 1;
return char;
},
}
}
fn finishWord(self: *UriQueryIterator, start: usize, end: usize) [:0]const u8 {
self.pos += 1;
self.query[end] = 0;
return self.query[start..end :0];
}
};
test "UriQueryIterator" {
{
var query = "asd&qwe=zxc&%3D=%26&a=".*;
var it = UriQueryIterator{ .query = &query };
{
const p = (try it.next()).?;
try testing.expectEqualStrings("asd", p.name);
try testing.expectEqual(@as(?[:0]const u8, null), p.value);
}
{
const p = (try it.next()).?;
try testing.expectEqualStrings("qwe", p.name);
try testing.expectEqualStrings("zxc", p.value.?);
}
{
const p = (try it.next()).?;
try testing.expectEqualStrings("=", p.name);
try testing.expectEqualStrings("&", p.value.?);
}
{
const p = (try it.next()).?;
try testing.expectEqualStrings("a", p.name);
try testing.expectEqualStrings("", p.value.?);
}
try testing.expectEqual(@as(?UriQueryIterator.Param, null), try it.next());
}
{
var query = "".*;
var it = UriQueryIterator{ .query = &query };
try testing.expectEqual(@as(?UriQueryIterator.Param, null), try it.next());
}
{
var query = "asd\x00asd".*;
var it = UriQueryIterator{ .query = &query };
try testing.expectError(error.BadUri, it.next());
}
{
var query = "asd%00asd".*;
var it = UriQueryIterator{ .query = &query };
try testing.expectError(error.BadUri, it.next());
}
{
var query = "asd%n0asd".*;
var it = UriQueryIterator{ .query = &query };
try testing.expectError(error.BadUri, it.next());
}
{
var query = "asd%0".*;
var it = UriQueryIterator{ .query = &query };
try testing.expectError(error.BadUri, it.next());
}
{
var query = "=asd".*;
var it = UriQueryIterator{ .query = &query };
try testing.expectError(error.BadUri, it.next());
}
{
var query = "&asd".*;
var it = UriQueryIterator{ .query = &query };
try testing.expectError(error.BadUri, it.next());
}
}
const ArgIterator = struct {
uriIterator: ?UriQueryIterator = null,
cmdLineIterator: std.process.ArgIterator,
name: [:0]const u8 = undefined,
val: ?[:0]const u8 = undefined,
pub fn next(self: *ArgIterator) ?enum { opt, uri } {
if (self.uriIterator) |*uriIterator| {
if (uriIterator.next() catch fatal("ill-formed URI", .{})) |param| {
self.name = param.name;
self.val = param.value;
return .opt;
} else {
self.uriIterator = null;
}
}
if (self.cmdLineIterator.nextPosix()) |arg| {
if (mem.eql(u8, arg, "--uri-env")) {
const env_name = self.value([:0]const u8);
self.name = mem.span(std.c.getenv(env_name) orelse fatal("no URI environment variable '{s}'", .{env_name}));
self.val = null;
return .uri;
}
if (mem.startsWith(u8, arg, "--")) {
self.name = arg;
self.val = null;
return .opt;
} else {
self.name = arg;
self.val = null;
return .uri;
}
}
return null;
}
fn value(self: *ArgIterator, comptime T: type) T {
const val = (self.val orelse blk: {
if (self.uriIterator != null) fatal("missing argument for URI option {s}", .{self.name});
self.val = self.cmdLineIterator.nextPosix() orelse fatal("missing argument for option {s}", .{self.name});
break :blk self.val;
}).?;
if (T == [:0]const u8) {
return val;
}
if (@typeInfo(T) == .Int) {
return std.fmt.parseInt(T, val, 10) catch |err| switch (err) {
error.InvalidCharacter => fatal("argument for option {s} must be an integer", .{self.name}),
error.Overflow => fatal("argument for option {s} must be between {d} and {d}", .{ self.name, std.math.minInt(T), std.math.maxInt(T) }),
};
}
if (@typeInfo(T) == .Enum) {
return std.meta.stringToEnum(T, val) orelse fatal("invalid argument for option {s}", .{self.name});
}
if (@typeInfo(T) == .Bool) {
return (std.meta.stringToEnum(enum { @"true", @"false" }, val) orelse fatal("invalid argument for option {s}", .{self.name})) == .@"true";
}
@compileError("unimplemented type");
}
pub fn get(self: *ArgIterator, name: []const u8, comptime T: type) if (T == void) bool else ?T {
const matches = if (self.uriIterator != null)
mem.eql(u8, name, self.name)
else
mem.startsWith(u8, self.name, "--") and mem.eql(u8, self.name[2..], name);
if (T == void)
return matches
else
return if (matches) self.value(T) else null;
}
};
pub fn main() !void {
const alloc = std.heap.c_allocator;
var args = ArgIterator{ .cmdLineIterator = std.process.args() };
var uri: ?[:0]u8 = null;
var port: ?c_int = null;
var host: [*:0]const u8 = "localhost";
var vhost: [*:0]const u8 = "/";
var user: [*:0]const u8 = "guest";
var password: [*:0]const u8 = "<PASSWORD>";
var heartbeat: c_int = 60;
var tls = true;
var ca_cert_file: ?[*:0]const u8 = null;
var cert_file: ?[*:0]const u8 = null;
var key_file: ?[*:0]const u8 = null;
var verify_peer: ?bool = null;
var fail_if_no_peer_cert: ?bool = null;
var verify_hostname: ?bool = null;
var chan_settings = server.ChannelSettings{
.queue = "zone2json",
.prefetch_count = 10,
.max_batch = 10,
};
const str = [:0]const u8;
_ = args.next(); // skip exe path
while (args.next()) |arg_type| {
if (arg_type == .uri) {
if (uri != null) fatal("multiple URIs specified", .{});
uri = try alloc.dupeZ(u8, args.name);
if (mem.indexOfScalar(u8, uri.?, '?')) |index| {
uri.?[index] = 0;
args.uriIterator = UriQueryIterator{ .query = uri.?[index + 1 ..] };
}
const uri_params = amqp.parse_url(uri.?) catch fatal("ill-formed URI", .{});
host = uri_params.host;
port = uri_params.port;
vhost = uri_params.vhost;
user = uri_params.user;
password = <PASSWORD>;
tls = uri_params.ssl != 0;
} else if (args.get("log", @TypeOf(logOut))) |val| {
logOut = val;
} else if (args.get("host", str)) |val| {
host = val;
} else if (args.get("port", c_int)) |val| {
port = val;
} else if (args.get("vhost", str)) |val| {
vhost = val;
} else if (args.get("user", str)) |val| {
user = val;
} else if (args.get("password", str)) |val| {
password = val;
} else if (args.get("cacertfile", str)) |val| {
ca_cert_file = val;
} else if (args.get("certfile", str)) |val| {
cert_file = val;
} else if (args.get("keyfile", str)) |val| {
key_file = val;
} else if (args.get("verify", enum { verify_peer, verify_none })) |val| {
verify_peer = val == .verify_peer;
} else if (args.get("fail_if_no_peer_cert", bool)) |val| {
fail_if_no_peer_cert = val;
} else if (args.get("verify_hostname", bool)) |val| {
verify_hostname = val;
} else if (args.get("heartbeat", c_int)) |val| {
heartbeat = val;
} else if (args.get("queue", str)) |val| {
chan_settings.queue = val;
} else if (args.get("prefetch-count", u16)) |val| {
chan_settings.prefetch_count = val;
} else if (args.get("batch", u16)) |val| {
chan_settings.max_batch = if (val == 0) 1 else val;
} else if (args.get("no-tls", void)) {
tls = false;
} else if (args.get("help", void)) {
try help();
std.os.exit(0);
} else if (args.get("version", void)) {
try std.io.getStdOut().writeAll(build_options.version ++ "\n");
std.os.exit(0);
} else {
fatal("unknown option: {s}", .{args.name});
}
}
if (tls and ca_cert_file == null)
fatal("specify a trusted root certificates file with cacertfile or disable TLS", .{});
if (!tls and (ca_cert_file != null or cert_file != null or key_file != null or verify_peer != null or fail_if_no_peer_cert != null or verify_hostname != null))
fatal("TLS disabled, but TLS options specified", .{});
if ((cert_file != null) != (key_file != null))
fatal("both certfile and keyfile need to be specified or none at all", .{});
if ((verify_peer orelse true) != (fail_if_no_peer_cert orelse true))
fatal("if fail_if_no_peer_cert is specified, it must be true when verify=verify_peer and false when verify=verify_none", .{});
try server.run(alloc, .{
.port = port orelse if (tls) @as(c_int, 5671) else 5672,
.host = host,
.vhost = vhost,
.auth = .{ .plain = .{ .username = user, .password = password } },
.heartbeat = heartbeat,
.tls = if (tls) .{
.ca_cert_path = ca_cert_file.?,
.keys = if (cert_file != null) .{
.cert_path = cert_file.?,
.key_path = key_file.?,
} else null,
.verify_peer = verify_peer orelse true,
.verify_hostname = verify_hostname orelse true,
} else null,
}, chan_settings);
}
fn help() !void {
try std.io.getStdOut().writeAll(
\\Usage: zone2json-server [OPTIONS] [URI]
\\An AMQP RPC server that converts DNS zones to JSON
\\
\\Options can also be passed in as URI query parameters (without "--").
\\
\\URI options:
\\ --uri-env VAR_NAME Read URI from an environment variable.
\\Connection options:
\\ --host name default: localhost
\\ --port number default: 5671 (with TLS) / 5672 (without TLS)
\\ --vhost name default: /
\\ --user name default: guest
\\ --password password default: <PASSWORD>
\\ --heartbeat seconds default: 60 (0 to disable)
\\TLS options:
\\ --cacertfile path trusted root certificates file
\\ --certfile path certificate file
\\ --keyfile path private key file
\\ --verify (verify_peer|verify_none)
\\ peer verification (default: verify_peer)
\\ --fail_if_no_peer_cert (true|false)
\\ Exists for compatibility. If set, must be true when verify=verify_peer and false when verify=verify_none.
\\ --verify_hostname (true|false)
\\ hostname verification (default: true)
\\ --no-tls disable TLS
\\Channel options:
\\ --queue name default: zone2json
\\ --prefetch-count count default: 10 (0 means unlimited)
\\ --batch count Acknowledge in batches of size count (default: 10)
\\ (sooner if there are no messages to process)
\\Other options:
\\ --log (syslog|stderr) log output (default: syslog)
\\ --help display help and exit
\\
);
} | src/main.zig |
const std = @import("std");
const Lock = @import("./Lock.zig").Lock;
const Futex = @import("./Futex.zig").Futex;
const Thread = @import("./Thread.zig").Thread;
const Pool = @This();
counter: u32 = 0,
max_threads: u16,
spawned: ?*Worker = null,
run_queues: [Priority.Count]GlobalQueue = [_]GlobalQueue{.{}} ** Priority.Count,
pub const InitConfig = struct {
max_threads: ?u16 = null,
};
pub fn init(config: InitConfig) Pool {
return .{
.max_threads = std.math.min(
std.math.maxInt(u14),
std.math.max(1, config.max_threads orelse blk: {
const threads = std.Thread.cpuCount() catch 1;
break :blk @intCast(u14, threads);
}),
),
};
}
pub fn deinit(self: *Pool) void {
self.shutdownWorkers();
self.joinWorkers();
self.* = undefined;
}
pub fn shutdown(self: *Pool) void {
return self.shutdownWorkers();
}
pub const Priority = enum {
Low = 0,
Normal = 1,
High = 2,
pub const Max = Priority.High;
pub const Count = @enumToInt(Max) + 1;
fn toArrayIndex(self: Priority) usize {
return @enumToInt(Priority.Max) - @enumToInt(self);
}
};
pub const ScheduleHints = struct {
priority: Priority = .High,
};
pub fn schedule(self: *Pool, hints: ScheduleHints, batchable: anytype) void {
const batch = Batch.from(batchable);
if (batch.isEmpty()) {
return;
}
if (Worker.getCurrent()) |worker| {
worker.run_queues[hints.priority.toArrayIndex()].push(batch);
} else {
self.run_queues[hints.priority.toArrayIndex()].push(batch);
}
self.notifyWorkers(false);
}
pub const Batch = struct {
head: ?*Runnable = null,
tail: *Runnable = undefined,
pub fn from(batchable: anytype) Batch {
return switch (@TypeOf(batchable)) {
Batch => batchable,
?*Runnable => from(batchable orelse return Batch{}),
*Runnable => {
batchable.next = null;
return Batch{
.head = batchable,
.tail = batchable,
};
},
else => |typ| @compileError(@typeName(typ) ++
" cannot be converted into " ++
@typeName(Batch)),
};
}
pub fn isEmpty(self: Batch) bool {
return self.head == null;
}
pub const push = pushBack;
pub fn pushBack(self: *Batch, batchable: anytype) void {
const batch = from(batchable);
if (batch.isEmpty())
return;
if (self.isEmpty()) {
self.* = batch;
} else {
self.tail.next = batch.head;
self.tail = batch.tail;
}
}
pub fn pushFront(self: *Batch, batchable: anytype) void {
const batch = from(batchable);
if (batch.isEmpty())
return;
if (self.isEmpty()) {
self.* = batch;
} else {
batch.tail.next = self.head;
self.head = batch.head;
}
}
pub const pop = popFront;
pub fn popFront(self: *Batch) ?*Runnable {
const runnable = self.head orelse return null;
self.head = runnable.next;
return runnable;
}
};
pub const Runnable = struct {
next: ?*Runnable = null,
runFn: fn (*Runnable) void,
pub fn init(callback: fn (*Runnable) void) Runnable {
return .{ .runFn = callback };
}
pub fn run(self: *Runnable) void {
return (self.runFn)(self);
}
};
/////////////////////////////////////////////////////////////////////////
const Counter = struct {
idle: u16 = 0,
spawned: u16 = 0,
notified: bool = false,
state: State = .pending,
const State = enum(u2) {
pending = 0,
waking,
notified,
shutdown,
};
fn pack(self: Counter) u32 {
return ((@as(u32, @boolToInt(self.notified)) << 0) |
(@as(u32, @enumToInt(self.state)) << 1) |
(@as(u32, @intCast(u14, self.idle)) << 3) |
(@as(u32, @intCast(u14, self.spawned)) << (3 + 14)));
}
fn unpack(value: u32) Counter {
return .{
.notified = value & (1 << 0) != 0,
.state = @intToEnum(State, @truncate(u2, value >> 1)),
.idle = @truncate(u14, value >> 3),
.spawned = @truncate(u14, value >> (3 + 14)),
};
}
};
fn notifyWorkers(self: *Pool, _is_waking: bool) void {
const max_threads = self.max_threads;
var did_spawn = false;
var attempts: usize = 5;
var is_waking = _is_waking;
var counter = Counter.unpack(@atomicLoad(u32, &self.counter, .Monotonic));
while (true) {
if (counter.state == .shutdown) {
if (did_spawn)
self.markShutdown();
return;
}
var do_wake = false;
var do_spawn = false;
var new_counter = counter;
new_counter.notified = true;
if (is_waking) {
if (counter.state != .waking)
std.debug.panic("notifyWorkers(waking) when counter is not", .{});
if (attempts > 0 and counter.idle > 0) {
if (did_spawn)
new_counter.spawned -= 1;
new_counter.state = .notified;
do_wake = true;
} else if (attempts > 0 and (did_spawn or counter.spawned < max_threads)) {
if (!did_spawn)
new_counter.spawned += 1;
do_spawn = true;
} else {
if (did_spawn)
new_counter.spawned -= 1;
new_counter.state = .pending;
}
} else {
if (counter.state == .pending and counter.idle > 0) {
new_counter.state = .notified;
do_wake = true;
} else if (counter.state == .pending and counter.spawned < max_threads) {
new_counter.state = .waking;
new_counter.spawned += 1;
do_spawn = true;
} else if (counter.notified) {
return;
}
}
if (@cmpxchgWeak(
u32,
&self.counter,
counter.pack(),
new_counter.pack(),
.Release,
.Monotonic,
)) |updated| {
std.Thread.spinLoopHint();
counter = Counter.unpack(updated);
continue;
}
is_waking = true;
if (do_wake) {
Futex.wake(&self.counter, 1);
return;
}
did_spawn = true;
if (do_spawn and Thread.spawn(Worker.entry, @ptrToInt(self))) {
return;
} else if (!do_spawn) {
return;
}
attempts -= 1;
std.Thread.spinLoopHint();
counter = Counter.unpack(@atomicLoad(u32, &self.counter, .Monotonic));
}
}
fn suspendWorker(self: *Pool, worker: *Worker) ?bool {
var is_suspended = false;
var is_waking = worker.state == .waking;
var counter = Counter.unpack(@atomicLoad(u32, &self.counter, .Monotonic));
while (true) {
if (counter.state == .shutdown) {
self.markShutdown();
return null;
}
if (counter.notified or !is_suspended) {
var new_counter = counter;
new_counter.notified = false;
if (counter.state == .notified) {
if (is_suspended)
new_counter.idle -= 1;
new_counter.state = .waking;
} else if (counter.notified) {
if (is_suspended)
new_counter.idle -= 1;
if (is_waking)
new_counter.state = .waking;
} else {
if (is_waking)
new_counter.state = .pending;
new_counter.idle += 1;
}
if (@cmpxchgWeak(
u32,
&self.counter,
counter.pack(),
new_counter.pack(),
.Acquire,
.Monotonic,
)) |updated| {
std.Thread.spinLoopHint();
counter = Counter.unpack(updated);
continue;
}
if (counter.state == .notified)
return true;
if (counter.notified)
return is_waking;
is_waking = false;
is_suspended = true;
counter = new_counter;
}
Futex.wait(&self.counter, counter.pack(), null) catch unreachable;
counter = Counter.unpack(@atomicLoad(u32, &self.counter, .Monotonic));
}
}
fn markShutdown(self: *Pool) void {
var counter = Counter{ .spawned = 1 };
counter = Counter.unpack(@atomicRmw(u32, &self.counter, .Sub, counter.pack(), .Release));
if (counter.spawned == 1) {
Futex.wake(&self.counter, 1);
}
}
fn shutdownWorkers(self: *Pool) void {
var counter = Counter.unpack(@atomicLoad(u32, &self.counter, .Monotonic));
while (counter.state != .shutdown) {
var new_counter = counter;
new_counter.idle = 0;
new_counter.state = .shutdown;
if (@cmpxchgWeak(
u32,
&self.counter,
counter.pack(),
new_counter.pack(),
.Release,
.Monotonic,
)) |updated| {
counter = Counter.unpack(updated);
std.Thread.spinLoopHint();
continue;
}
Futex.wake(&self.counter, std.math.maxInt(u32));
return;
}
}
fn joinWorkers(self: *Pool) void {
while (true) {
const counter = Counter.unpack(@atomicLoad(u32, &self.counter, .Acquire));
if (counter.spawned == 0)
break;
Futex.wait(&self.counter, counter.pack(), null) catch unreachable;
}
if (@atomicLoad(?*Worker, &self.spawned, .Acquire)) |top_worker| {
top_worker.shutdown();
}
}
const Worker = struct {
pool: *Pool,
state: State,
shutdown_lock: Lock = .{},
next_target: ?*Worker = null,
spawned_next: ?*Worker = null,
run_tick: usize,
run_queues: [Priority.Count]LocalQueue = [_]LocalQueue{.{}} ** Priority.Count,
const State = enum(u32) {
running,
waking,
waiting,
shutdown,
};
const is_apple_silicon = std.Target.current.isDarwin() and std.builtin.arch != .x86_64;
const TLS = if (is_apple_silicon) DarwinTLS else DefaultTLS;
const DefaultTLS = struct {
threadlocal var tls: ?*Worker = null;
fn get() ?*Worker {
return tls;
}
fn set(worker: ?*Worker) void {
tls = worker;
}
};
const DarwinTLS = struct {
fn get() ?*Worker {
const key = getKey();
const ptr = pthread_getspecific(key);
return @ptrCast(?*Worker, @alignCast(@alignOf(Worker), ptr));
}
fn set(worker: ?*Worker) void {
const key = getKey();
const rc = pthread_setspecific(key, @ptrCast(?*anyopaque, worker));
std.debug.assert(rc == 0);
}
var tls_state: u8 = 0;
var tls_key: pthread_key_t = undefined;
const pthread_key_t = c_ulong;
extern "c" fn pthread_key_create(key: *pthread_key_t, destructor: ?fn (value: *anyopaque) callconv(.C) void) c_int;
extern "c" fn pthread_getspecific(key: pthread_key_t) ?*anyopaque;
extern "c" fn pthread_setspecific(key: pthread_key_t, value: ?*anyopaque) c_int;
fn getKey() pthread_key_t {
var state = @atomicLoad(u8, &tls_state, .Acquire);
while (true) {
switch (state) {
0 => state = @cmpxchgWeak(
u8,
&tls_state,
0,
1,
.Acquire,
.Acquire,
) orelse break,
1 => {
std.os.sched_yield() catch {};
state = @atomicLoad(u8, &tls_state, .Acquire);
},
2 => return tls_key,
else => std.debug.panic("failed to get pthread_key_t", .{}),
}
}
const rc = pthread_key_create(&tls_key, null);
if (rc == 0) {
@atomicStore(u8, &tls_state, 2, .Release);
return tls_key;
}
@atomicStore(u8, &tls_state, 3, .Monotonic);
std.debug.panic("failed to get pthread_key_t", .{});
}
};
fn getCurrent() ?*Worker {
return TLS.get();
}
fn setCurrent(worker: ?*Worker) void {
return TLS.set(worker);
}
fn entry(pool_ptr: usize) void {
const pool = @intToPtr(*Pool, pool_ptr);
var worker: Worker = undefined;
worker.run(pool);
}
fn run(self: *Worker, pool: *Pool) void {
setCurrent(self);
self.* = .{
.pool = pool,
.state = .waking,
.run_tick = @ptrToInt(self) *% 31,
};
var spawned_next = @atomicLoad(?*Worker, &pool.spawned, .Monotonic);
while (true) {
self.spawned_next = spawned_next;
spawned_next = @cmpxchgWeak(
?*Worker,
&pool.spawned,
spawned_next,
self,
.Release,
.Monotonic,
) orelse break;
}
while (true) {
if (self.pop()) |runnable| {
if (self.state == .waking)
pool.notifyWorkers(true);
self.state = .running;
runnable.run();
continue;
}
if (pool.suspendWorker(self)) |is_waking| {
self.state = if (is_waking) .waking else .running;
continue;
}
self.waitForShutdown();
return;
}
}
fn waitForShutdown(self: *Worker) void {
while (true) {
self.shutdown_lock.acquire();
if (self.state == .shutdown) {
self.shutdown_lock.release();
break;
}
self.state = .waiting;
self.shutdown_lock.release();
Futex.wait(
@ptrCast(*const u32, &self.state),
@enumToInt(State.waiting),
null,
) catch unreachable;
}
if (self.spawned_next) |next_worker|
next_worker.shutdown();
}
fn shutdown(self: *Worker) void {
self.shutdown_lock.acquire();
defer self.shutdown_lock.release();
const state = self.state;
@atomicStore(State, &self.state, .shutdown, .Unordered);
if (state == .waiting)
Futex.wake(@ptrCast(*const u32, &self.state), 1);
}
fn pop(self: *Worker) ?*Runnable {
self.run_tick +%= 1;
if (self.run_tick % 257 == 0) {
if (self.pollWorkers(0)) |runnable|
return runnable;
}
if (self.run_tick % 127 == 0) {
if (self.pollPool()) |runnable|
return runnable;
}
var priorities: [Priority.Count]Priority = undefined;
if (self.run_tick % 61 == 0) {
priorities = [_]Priority{ .Low, .Normal, .High };
} else if (self.run_tick % 31 == 0) {
priorities = [_]Priority{ .Normal, .High, .Low };
} else {
priorities = [_]Priority{ .High, .Normal, .Low };
}
for (priorities) |priority| {
if (self.run_queues[priority.toArrayIndex()].pop(self.run_tick)) |runnable|
return runnable;
}
const max_attempts = switch (std.builtin.arch) {
.x86_64 => 32,
.aarch64 => 16,
else => 8,
};
var steal_attempt: usize = 0;
while (steal_attempt < max_attempts) : (steal_attempt += 1) {
if (self.pollPool()) |runnable|
return runnable;
if (self.pollWorkers(steal_attempt)) |runnable|
return runnable;
}
if (self.pollPool()) |runnable|
return runnable;
return null;
}
fn pollPool(self: *Worker) ?*Runnable {
return self.pollWith(
std.math.maxInt(usize),
&self.pool.run_queues,
"popAndStealGlobal",
);
}
fn pollWorkers(self: *Worker, attempt: usize) ?*Runnable {
var threads = Counter.unpack(@atomicLoad(u32, &self.pool.counter, .Monotonic)).spawned;
while (threads > 0) : (threads -= 1) {
const target = self.next_target orelse @atomicLoad(?*Worker, &self.pool.spawned, .Acquire).?;
self.next_target = target.spawned_next;
if (target == self)
continue;
if (self.pollWith(attempt, &target.run_queues, "popAndStealLocal")) |runnable|
return runnable;
}
return null;
}
fn pollWith(
self: *Worker,
attempt: usize,
target_queues: anytype,
comptime pollFn: []const u8,
) ?*Runnable {
const priorities: []const Priority = switch (attempt) {
0 => &[_]Priority{.High},
1 => &[_]Priority{ .High, .Normal },
else => &[_]Priority{ .High, .Normal, .Low },
};
for (priorities) |priority| {
const index = priority.toArrayIndex();
const our_queue = &self.run_queues[index];
const target_queue = &target_queues[index];
if (@field(LocalQueue, pollFn)(our_queue, target_queue)) |runnable|
return runnable;
}
return null;
}
};
const GlobalQueue = UnboundedQueue;
const LocalQueue = struct {
buffer: BoundedQueue = .{},
overflow: UnboundedQueue = .{},
fn push(self: *LocalQueue, batch: Batch) void {
if (self.buffer.push(batch)) |overflowed|
self.overflow.push(overflowed);
}
fn pop(self: *LocalQueue, tick: usize) ?*Runnable {
if (tick % 61 == 0) {
if (self.buffer.pop()) |runnable|
return runnable;
}
if (self.buffer.stealUnbounded(&self.overflow)) |runnable|
return runnable;
if (self.buffer.pop()) |runnable|
return runnable;
return null;
}
fn popAndStealGlobal(self: *LocalQueue, target: *GlobalQueue) ?*Runnable {
return self.buffer.stealUnbounded(target);
}
fn popAndStealLocal(self: *LocalQueue, target: *LocalQueue) ?*Runnable {
if (self == target)
return self.pop(1);
if (self.buffer.stealUnbounded(&target.overflow)) |runnable|
return runnable;
if (self.buffer.stealBounded(&target.buffer)) |runnable|
return runnable;
return null;
}
};
const UnboundedQueue = struct {
head: ?*Runnable = null,
tail: usize = 0,
stub: Runnable = Runnable.init(undefined),
fn push(self: *UnboundedQueue, batch: Batch) void {
if (batch.isEmpty()) return;
const head = @atomicRmw(?*Runnable, &self.head, .Xchg, batch.tail, .AcqRel);
const prev = head orelse &self.stub;
@atomicStore(?*Runnable, &prev.next, batch.head, .Release);
}
fn tryAcquireConsumer(self: *UnboundedQueue) ?Consumer {
var tail = @atomicLoad(usize, &self.tail, .Monotonic);
while (true) : (std.Thread.spinLoopHint()) {
const head = @atomicLoad(?*Runnable, &self.head, .Monotonic);
if (head == null or head == &self.stub)
return null;
if (tail & 1 != 0)
return null;
tail = @cmpxchgWeak(
usize,
&self.tail,
tail,
tail | 1,
.Acquire,
.Monotonic,
) orelse return Consumer{
.queue = self,
.tail = @intToPtr(?*Runnable, tail) orelse &self.stub,
};
}
}
const Consumer = struct {
queue: *UnboundedQueue,
tail: *Runnable,
fn release(self: Consumer) void {
@atomicStore(usize, &self.queue.tail, @ptrToInt(self.tail), .Release);
}
fn pop(self: *Consumer) ?*Runnable {
var tail = self.tail;
var next = @atomicLoad(?*Runnable, &tail.next, .Acquire);
if (tail == &self.queue.stub) {
tail = next orelse return null;
self.tail = tail;
next = @atomicLoad(?*Runnable, &tail.next, .Acquire);
}
if (next) |runnable| {
self.tail = runnable;
return tail;
}
const head = @atomicLoad(?*Runnable, &self.queue.head, .Monotonic);
if (tail != head) {
return null;
}
self.queue.push(Batch.from(&self.queue.stub));
if (@atomicLoad(?*Runnable, &tail.next, .Acquire)) |runnable| {
self.tail = runnable;
return tail;
}
return null;
}
};
};
const BoundedQueue = struct {
head: Pos = 0,
tail: Pos = 0,
buffer: [capacity]*Runnable = undefined,
const Pos = std.meta.Int(.unsigned, std.meta.bitCount(usize) / 2);
const capacity = 64;
comptime {
std.debug.assert(capacity <= std.math.maxInt(Pos));
}
fn push(self: *BoundedQueue, _batch: Batch) ?Batch {
var batch = _batch;
if (batch.isEmpty()) {
return null;
}
var tail = self.tail;
var head = @atomicLoad(Pos, &self.head, .Monotonic);
while (true) {
if (batch.isEmpty())
return null;
if (tail -% head < self.buffer.len) {
while (tail -% head < self.buffer.len) {
const runnable = batch.pop() orelse break;
@atomicStore(*Runnable, &self.buffer[tail % self.buffer.len], runnable, .Unordered);
tail +%= 1;
}
@atomicStore(Pos, &self.tail, tail, .Release);
std.Thread.spinLoopHint();
head = @atomicLoad(Pos, &self.head, .Monotonic);
continue;
}
const new_head = head +% @intCast(Pos, self.buffer.len / 2);
if (@cmpxchgWeak(
Pos,
&self.head,
head,
new_head,
.Acquire,
.Monotonic,
)) |updated| {
head = updated;
continue;
}
var overflowed = Batch{};
while (head != new_head) : (head +%= 1) {
const runnable = self.buffer[head % self.buffer.len];
overflowed.pushBack(Batch.from(runnable));
}
overflowed.pushBack(batch);
return overflowed;
}
}
fn pop(self: *BoundedQueue) ?*Runnable {
var tail = self.tail;
var head = @atomicLoad(Pos, &self.head, .Monotonic);
while (tail != head) : (std.Thread.spinLoopHint()) {
head = @cmpxchgWeak(
Pos,
&self.head,
head,
head +% 1,
.Acquire,
.Monotonic,
) orelse return self.buffer[head % self.buffer.len];
}
return null;
}
fn stealUnbounded(self: *BoundedQueue, target: *UnboundedQueue) ?*Runnable {
var consumer = target.tryAcquireConsumer() orelse return null;
defer consumer.release();
const first_runnable = consumer.pop();
const head = @atomicLoad(Pos, &self.head, .Monotonic);
const tail = self.tail;
var new_tail = tail;
while (new_tail -% head < self.buffer.len) {
const runnable = consumer.pop() orelse break;
@atomicStore(*Runnable, &self.buffer[new_tail % self.buffer.len], runnable, .Unordered);
new_tail +%= 1;
}
if (new_tail != tail)
@atomicStore(Pos, &self.tail, new_tail, .Release);
return first_runnable;
}
fn stealBounded(self: *BoundedQueue, target: *BoundedQueue) ?*Runnable {
if (self == target)
return self.pop();
const head = @atomicLoad(Pos, &self.head, .Monotonic);
const tail = self.tail;
if (tail != head)
return self.pop();
var target_head = @atomicLoad(Pos, &target.head, .Monotonic);
while (true) {
const target_tail = @atomicLoad(Pos, &target.tail, .Acquire);
const target_size = target_tail -% target_head;
if (target_size == 0)
return null;
var steal = target_size - (target_size / 2);
if (steal > target.buffer.len / 2) {
std.Thread.spinLoopHint();
target_head = @atomicLoad(Pos, &target.head, .Monotonic);
continue;
}
const first_runnable = @atomicLoad(*Runnable, &target.buffer[target_head % target.buffer.len], .Unordered);
var new_target_head = target_head +% 1;
var new_tail = tail;
steal -= 1;
while (steal > 0) : (steal -= 1) {
const runnable = @atomicLoad(*Runnable, &target.buffer[new_target_head % target.buffer.len], .Unordered);
new_target_head +%= 1;
@atomicStore(*Runnable, &self.buffer[new_tail % self.buffer.len], runnable, .Unordered);
new_tail +%= 1;
}
if (@cmpxchgWeak(
Pos,
&target.head,
target_head,
new_target_head,
.AcqRel,
.Monotonic,
)) |updated| {
std.Thread.spinLoopHint();
target_head = updated;
continue;
}
if (new_tail != tail)
@atomicStore(Pos, &self.tail, new_tail, .Release);
return first_runnable;
}
}
}; | src/runtime/Pool.zig |
const std = @import("std");
pub fn build(b: *std.build.Builder) void {
const build_mode = b.standardReleaseOptions();
const target = b.standardTargetOptions(.{});
const tests = buildTests(b, build_mode, target);
const test_step = b.step("test", "Run enet tests");
test_step.dependOn(&tests.step);
}
pub fn buildTests(
b: *std.build.Builder,
build_mode: std.builtin.Mode,
target: std.zig.CrossTarget,
) *std.build.LibExeObjStep {
const tests = b.addTest(thisDir() ++ "/enet.zig");
tests.setBuildMode(build_mode);
tests.setTarget(target);
link(b, tests);
return tests;
}
fn buildLibrary(b: *std.build.Builder, step: *std.build.LibExeObjStep) *std.build.LibExeObjStep {
const lib = b.addStaticLibrary("enet", thisDir() ++ "/enet.zig");
lib.setBuildMode(step.build_mode);
lib.setTarget(step.target);
lib.want_lto = false;
lib.addIncludeDir(thisDir() ++ "/enet/include");
lib.linkSystemLibrary("c");
if (step.target.isWindows()) {
lib.linkSystemLibrary("ws2_32");
lib.linkSystemLibrary("winmm");
}
const defines = .{
"-DHAS_FCNTL=1",
"-DHAS_POLL=1",
"-DHAS_GETNAMEINFO=1",
"-DHAS_GETADDRINFO=1",
"-DHAS_GETHOSTBYNAME_R=1",
"-DHAS_GETHOSTBYADDR_R=1",
"-DHAS_INET_PTON=1",
"-DHAS_INET_NTOP=1",
"-DHAS_MSGHDR_FLAGS=1",
"-DHAS_SOCKLEN_T=1",
};
lib.addCSourceFile(thisDir() ++ "/enet/callbacks.c", &defines);
lib.addCSourceFile(thisDir() ++ "/enet/compress.c", &defines);
lib.addCSourceFile(thisDir() ++ "/enet/host.c", &defines);
lib.addCSourceFile(thisDir() ++ "/enet/list.c", &defines);
lib.addCSourceFile(thisDir() ++ "/enet/packet.c", &defines);
lib.addCSourceFile(thisDir() ++ "/enet/peer.c", &defines);
lib.addCSourceFile(thisDir() ++ "/enet/protocol.c", &defines);
lib.addCSourceFile(thisDir() ++ "/enet/unix.c", &defines);
lib.addCSourceFile(thisDir() ++ "/enet/win32.c", &defines);
lib.install();
return lib;
}
pub fn link(b: *std.build.Builder, step: *std.build.LibExeObjStep) void {
const lib = buildLibrary(b, step);
step.linkLibrary(lib);
}
fn thisDir() []const u8 {
return std.fs.path.dirname(@src().file) orelse ".";
} | build.zig |
pub const E_UNKNOWNTYPE = @import("../../zig.zig").typedConst(HRESULT, @as(i32, -2144665560));
//--------------------------------------------------------------------------------
// Section: Types (21)
//--------------------------------------------------------------------------------
pub const VisualMutationType = enum(i32) {
Add = 0,
Remove = 1,
};
pub const Add = VisualMutationType.Add;
pub const Remove = VisualMutationType.Remove;
pub const BaseValueSource = enum(i32) {
BaseValueSourceUnknown = 0,
BaseValueSourceDefault = 1,
BaseValueSourceBuiltInStyle = 2,
BaseValueSourceStyle = 3,
BaseValueSourceLocal = 4,
Inherited = 5,
DefaultStyleTrigger = 6,
TemplateTrigger = 7,
StyleTrigger = 8,
ImplicitStyleReference = 9,
ParentTemplate = 10,
ParentTemplateTrigger = 11,
Animation = 12,
Coercion = 13,
BaseValueSourceVisualState = 14,
};
pub const BaseValueSourceUnknown = BaseValueSource.BaseValueSourceUnknown;
pub const BaseValueSourceDefault = BaseValueSource.BaseValueSourceDefault;
pub const BaseValueSourceBuiltInStyle = BaseValueSource.BaseValueSourceBuiltInStyle;
pub const BaseValueSourceStyle = BaseValueSource.BaseValueSourceStyle;
pub const BaseValueSourceLocal = BaseValueSource.BaseValueSourceLocal;
pub const Inherited = BaseValueSource.Inherited;
pub const DefaultStyleTrigger = BaseValueSource.DefaultStyleTrigger;
pub const TemplateTrigger = BaseValueSource.TemplateTrigger;
pub const StyleTrigger = BaseValueSource.StyleTrigger;
pub const ImplicitStyleReference = BaseValueSource.ImplicitStyleReference;
pub const ParentTemplate = BaseValueSource.ParentTemplate;
pub const ParentTemplateTrigger = BaseValueSource.ParentTemplateTrigger;
pub const Animation = BaseValueSource.Animation;
pub const Coercion = BaseValueSource.Coercion;
pub const BaseValueSourceVisualState = BaseValueSource.BaseValueSourceVisualState;
pub const SourceInfo = extern struct {
FileName: ?BSTR,
LineNumber: u32,
ColumnNumber: u32,
CharPosition: u32,
Hash: ?BSTR,
};
pub const ParentChildRelation = extern struct {
Parent: u64,
Child: u64,
ChildIndex: u32,
};
pub const VisualElement = extern struct {
Handle: u64,
SrcInfo: SourceInfo,
Type: ?BSTR,
Name: ?BSTR,
NumChildren: u32,
};
pub const PropertyChainSource = extern struct {
Handle: u64,
TargetType: ?BSTR,
Name: ?BSTR,
Source: BaseValueSource,
SrcInfo: SourceInfo,
};
pub const MetadataBit = enum(i32) {
None = 0,
ValueHandle = 1,
PropertyReadOnly = 2,
ValueCollection = 4,
ValueCollectionReadOnly = 8,
ValueBindingExpression = 16,
ValueNull = 32,
ValueHandleAndEvaluatedValue = 64,
};
// NOTE: not creating aliases because this enum is 'Scoped'
pub const PropertyChainValue = extern struct {
Index: u32,
Type: ?BSTR,
DeclaringType: ?BSTR,
ValueType: ?BSTR,
ItemType: ?BSTR,
Value: ?BSTR,
Overridden: BOOL,
MetadataBits: i64,
PropertyName: ?BSTR,
PropertyChainIndex: u32,
};
pub const EnumType = extern struct {
Name: ?BSTR,
ValueInts: ?*SAFEARRAY,
ValueStrings: ?*SAFEARRAY,
};
pub const CollectionElementValue = extern struct {
Index: u32,
ValueType: ?BSTR,
Value: ?BSTR,
MetadataBits: i64,
};
pub const RenderTargetBitmapOptions = enum(i32) {
t = 0,
AndChildren = 1,
};
pub const RenderTarget = RenderTargetBitmapOptions.t;
pub const RenderTargetAndChildren = RenderTargetBitmapOptions.AndChildren;
pub const BitmapDescription = extern struct {
Width: u32,
Height: u32,
Format: DXGI_FORMAT,
AlphaMode: DXGI_ALPHA_MODE,
};
pub const ResourceType = enum(i32) {
Static = 0,
Theme = 1,
};
pub const ResourceTypeStatic = ResourceType.Static;
pub const ResourceTypeTheme = ResourceType.Theme;
pub const VisualElementState = enum(i32) {
Resolved = 0,
ResourceNotFound = 1,
InvalidResource = 2,
};
pub const ErrorResolved = VisualElementState.Resolved;
pub const ErrorResourceNotFound = VisualElementState.ResourceNotFound;
pub const ErrorInvalidResource = VisualElementState.InvalidResource;
// TODO: this type is limited to platform 'windows10.0.10240'
const IID_IVisualTreeServiceCallback_Value = Guid.initString("aa7a8931-80e4-4fec-8f3b-553f87b4966e");
pub const IID_IVisualTreeServiceCallback = &IID_IVisualTreeServiceCallback_Value;
pub const IVisualTreeServiceCallback = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
OnVisualTreeChange: fn(
self: *const IVisualTreeServiceCallback,
relation: ParentChildRelation,
element: VisualElement,
mutationType: VisualMutationType,
) 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 IVisualTreeServiceCallback_OnVisualTreeChange(self: *const T, relation: ParentChildRelation, element: VisualElement, mutationType: VisualMutationType) callconv(.Inline) HRESULT {
return @ptrCast(*const IVisualTreeServiceCallback.VTable, self.vtable).OnVisualTreeChange(@ptrCast(*const IVisualTreeServiceCallback, self), relation, element, mutationType);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.14393'
const IID_IVisualTreeServiceCallback2_Value = Guid.initString("bad9eb88-ae77-4397-b948-5fa2db0a19ea");
pub const IID_IVisualTreeServiceCallback2 = &IID_IVisualTreeServiceCallback2_Value;
pub const IVisualTreeServiceCallback2 = extern struct {
pub const VTable = extern struct {
base: IVisualTreeServiceCallback.VTable,
OnElementStateChanged: fn(
self: *const IVisualTreeServiceCallback2,
element: u64,
elementState: VisualElementState,
context: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IVisualTreeServiceCallback.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVisualTreeServiceCallback2_OnElementStateChanged(self: *const T, element: u64, elementState: VisualElementState, context: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IVisualTreeServiceCallback2.VTable, self.vtable).OnElementStateChanged(@ptrCast(*const IVisualTreeServiceCallback2, self), element, elementState, context);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IVisualTreeService_Value = Guid.initString("a593b11a-d17f-48bb-8f66-83910731c8a5");
pub const IID_IVisualTreeService = &IID_IVisualTreeService_Value;
pub const IVisualTreeService = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
AdviseVisualTreeChange: fn(
self: *const IVisualTreeService,
pCallback: ?*IVisualTreeServiceCallback,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UnadviseVisualTreeChange: fn(
self: *const IVisualTreeService,
pCallback: ?*IVisualTreeServiceCallback,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetEnums: fn(
self: *const IVisualTreeService,
pCount: ?*u32,
ppEnums: [*]?*EnumType,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateInstance: fn(
self: *const IVisualTreeService,
typeName: ?BSTR,
value: ?BSTR,
pInstanceHandle: ?*u64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPropertyValuesChain: fn(
self: *const IVisualTreeService,
instanceHandle: u64,
pSourceCount: ?*u32,
ppPropertySources: [*]?*PropertyChainSource,
pPropertyCount: ?*u32,
ppPropertyValues: [*]?*PropertyChainValue,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetProperty: fn(
self: *const IVisualTreeService,
instanceHandle: u64,
value: u64,
propertyIndex: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ClearProperty: fn(
self: *const IVisualTreeService,
instanceHandle: u64,
propertyIndex: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCollectionCount: fn(
self: *const IVisualTreeService,
instanceHandle: u64,
pCollectionSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCollectionElements: fn(
self: *const IVisualTreeService,
instanceHandle: u64,
startIndex: u32,
pElementCount: ?*u32,
ppElementValues: [*]?*CollectionElementValue,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddChild: fn(
self: *const IVisualTreeService,
parent: u64,
child: u64,
index: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveChild: fn(
self: *const IVisualTreeService,
parent: u64,
index: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ClearChildren: fn(
self: *const IVisualTreeService,
parent: 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 IVisualTreeService_AdviseVisualTreeChange(self: *const T, pCallback: ?*IVisualTreeServiceCallback) callconv(.Inline) HRESULT {
return @ptrCast(*const IVisualTreeService.VTable, self.vtable).AdviseVisualTreeChange(@ptrCast(*const IVisualTreeService, self), pCallback);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVisualTreeService_UnadviseVisualTreeChange(self: *const T, pCallback: ?*IVisualTreeServiceCallback) callconv(.Inline) HRESULT {
return @ptrCast(*const IVisualTreeService.VTable, self.vtable).UnadviseVisualTreeChange(@ptrCast(*const IVisualTreeService, self), pCallback);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVisualTreeService_GetEnums(self: *const T, pCount: ?*u32, ppEnums: [*]?*EnumType) callconv(.Inline) HRESULT {
return @ptrCast(*const IVisualTreeService.VTable, self.vtable).GetEnums(@ptrCast(*const IVisualTreeService, self), pCount, ppEnums);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVisualTreeService_CreateInstance(self: *const T, typeName: ?BSTR, value: ?BSTR, pInstanceHandle: ?*u64) callconv(.Inline) HRESULT {
return @ptrCast(*const IVisualTreeService.VTable, self.vtable).CreateInstance(@ptrCast(*const IVisualTreeService, self), typeName, value, pInstanceHandle);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVisualTreeService_GetPropertyValuesChain(self: *const T, instanceHandle: u64, pSourceCount: ?*u32, ppPropertySources: [*]?*PropertyChainSource, pPropertyCount: ?*u32, ppPropertyValues: [*]?*PropertyChainValue) callconv(.Inline) HRESULT {
return @ptrCast(*const IVisualTreeService.VTable, self.vtable).GetPropertyValuesChain(@ptrCast(*const IVisualTreeService, self), instanceHandle, pSourceCount, ppPropertySources, pPropertyCount, ppPropertyValues);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVisualTreeService_SetProperty(self: *const T, instanceHandle: u64, value: u64, propertyIndex: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVisualTreeService.VTable, self.vtable).SetProperty(@ptrCast(*const IVisualTreeService, self), instanceHandle, value, propertyIndex);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVisualTreeService_ClearProperty(self: *const T, instanceHandle: u64, propertyIndex: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVisualTreeService.VTable, self.vtable).ClearProperty(@ptrCast(*const IVisualTreeService, self), instanceHandle, propertyIndex);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVisualTreeService_GetCollectionCount(self: *const T, instanceHandle: u64, pCollectionSize: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVisualTreeService.VTable, self.vtable).GetCollectionCount(@ptrCast(*const IVisualTreeService, self), instanceHandle, pCollectionSize);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVisualTreeService_GetCollectionElements(self: *const T, instanceHandle: u64, startIndex: u32, pElementCount: ?*u32, ppElementValues: [*]?*CollectionElementValue) callconv(.Inline) HRESULT {
return @ptrCast(*const IVisualTreeService.VTable, self.vtable).GetCollectionElements(@ptrCast(*const IVisualTreeService, self), instanceHandle, startIndex, pElementCount, ppElementValues);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVisualTreeService_AddChild(self: *const T, parent: u64, child: u64, index: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVisualTreeService.VTable, self.vtable).AddChild(@ptrCast(*const IVisualTreeService, self), parent, child, index);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVisualTreeService_RemoveChild(self: *const T, parent: u64, index: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVisualTreeService.VTable, self.vtable).RemoveChild(@ptrCast(*const IVisualTreeService, self), parent, index);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVisualTreeService_ClearChildren(self: *const T, parent: u64) callconv(.Inline) HRESULT {
return @ptrCast(*const IVisualTreeService.VTable, self.vtable).ClearChildren(@ptrCast(*const IVisualTreeService, self), parent);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.10240'
const IID_IXamlDiagnostics_Value = Guid.initString("18c9e2b6-3f43-4116-9f2b-ff935d7770d2");
pub const IID_IXamlDiagnostics = &IID_IXamlDiagnostics_Value;
pub const IXamlDiagnostics = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetDispatcher: fn(
self: *const IXamlDiagnostics,
ppDispatcher: ?*?*IInspectable,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetUiLayer: fn(
self: *const IXamlDiagnostics,
ppLayer: ?*?*IInspectable,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetApplication: fn(
self: *const IXamlDiagnostics,
ppApplication: ?*?*IInspectable,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetIInspectableFromHandle: fn(
self: *const IXamlDiagnostics,
instanceHandle: u64,
ppInstance: ?*?*IInspectable,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetHandleFromIInspectable: fn(
self: *const IXamlDiagnostics,
pInstance: ?*IInspectable,
pHandle: ?*u64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
HitTest: fn(
self: *const IXamlDiagnostics,
rect: RECT,
pCount: ?*u32,
ppInstanceHandles: [*]?*u64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RegisterInstance: fn(
self: *const IXamlDiagnostics,
pInstance: ?*IInspectable,
pInstanceHandle: ?*u64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetInitializationData: fn(
self: *const IXamlDiagnostics,
pInitializationData: ?*?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 IXamlDiagnostics_GetDispatcher(self: *const T, ppDispatcher: ?*?*IInspectable) callconv(.Inline) HRESULT {
return @ptrCast(*const IXamlDiagnostics.VTable, self.vtable).GetDispatcher(@ptrCast(*const IXamlDiagnostics, self), ppDispatcher);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXamlDiagnostics_GetUiLayer(self: *const T, ppLayer: ?*?*IInspectable) callconv(.Inline) HRESULT {
return @ptrCast(*const IXamlDiagnostics.VTable, self.vtable).GetUiLayer(@ptrCast(*const IXamlDiagnostics, self), ppLayer);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXamlDiagnostics_GetApplication(self: *const T, ppApplication: ?*?*IInspectable) callconv(.Inline) HRESULT {
return @ptrCast(*const IXamlDiagnostics.VTable, self.vtable).GetApplication(@ptrCast(*const IXamlDiagnostics, self), ppApplication);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXamlDiagnostics_GetIInspectableFromHandle(self: *const T, instanceHandle: u64, ppInstance: ?*?*IInspectable) callconv(.Inline) HRESULT {
return @ptrCast(*const IXamlDiagnostics.VTable, self.vtable).GetIInspectableFromHandle(@ptrCast(*const IXamlDiagnostics, self), instanceHandle, ppInstance);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXamlDiagnostics_GetHandleFromIInspectable(self: *const T, pInstance: ?*IInspectable, pHandle: ?*u64) callconv(.Inline) HRESULT {
return @ptrCast(*const IXamlDiagnostics.VTable, self.vtable).GetHandleFromIInspectable(@ptrCast(*const IXamlDiagnostics, self), pInstance, pHandle);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXamlDiagnostics_HitTest(self: *const T, rect: RECT, pCount: ?*u32, ppInstanceHandles: [*]?*u64) callconv(.Inline) HRESULT {
return @ptrCast(*const IXamlDiagnostics.VTable, self.vtable).HitTest(@ptrCast(*const IXamlDiagnostics, self), rect, pCount, ppInstanceHandles);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXamlDiagnostics_RegisterInstance(self: *const T, pInstance: ?*IInspectable, pInstanceHandle: ?*u64) callconv(.Inline) HRESULT {
return @ptrCast(*const IXamlDiagnostics.VTable, self.vtable).RegisterInstance(@ptrCast(*const IXamlDiagnostics, self), pInstance, pInstanceHandle);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXamlDiagnostics_GetInitializationData(self: *const T, pInitializationData: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXamlDiagnostics.VTable, self.vtable).GetInitializationData(@ptrCast(*const IXamlDiagnostics, self), pInitializationData);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.14393'
const IID_IBitmapData_Value = Guid.initString("d1a34ef2-cad8-4635-a3d2-fcda8d3f3caf");
pub const IID_IBitmapData = &IID_IBitmapData_Value;
pub const IBitmapData = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
CopyBytesTo: fn(
self: *const IBitmapData,
sourceOffsetInBytes: u32,
maxBytesToCopy: u32,
pvBytes: [*:0]u8,
numberOfBytesCopied: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetStride: fn(
self: *const IBitmapData,
pStride: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetBitmapDescription: fn(
self: *const IBitmapData,
pBitmapDescription: ?*BitmapDescription,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSourceBitmapDescription: fn(
self: *const IBitmapData,
pBitmapDescription: ?*BitmapDescription,
) 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 IBitmapData_CopyBytesTo(self: *const T, sourceOffsetInBytes: u32, maxBytesToCopy: u32, pvBytes: [*:0]u8, numberOfBytesCopied: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IBitmapData.VTable, self.vtable).CopyBytesTo(@ptrCast(*const IBitmapData, self), sourceOffsetInBytes, maxBytesToCopy, pvBytes, numberOfBytesCopied);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IBitmapData_GetStride(self: *const T, pStride: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IBitmapData.VTable, self.vtable).GetStride(@ptrCast(*const IBitmapData, self), pStride);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IBitmapData_GetBitmapDescription(self: *const T, pBitmapDescription: ?*BitmapDescription) callconv(.Inline) HRESULT {
return @ptrCast(*const IBitmapData.VTable, self.vtable).GetBitmapDescription(@ptrCast(*const IBitmapData, self), pBitmapDescription);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IBitmapData_GetSourceBitmapDescription(self: *const T, pBitmapDescription: ?*BitmapDescription) callconv(.Inline) HRESULT {
return @ptrCast(*const IBitmapData.VTable, self.vtable).GetSourceBitmapDescription(@ptrCast(*const IBitmapData, self), pBitmapDescription);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.14393'
const IID_IVisualTreeService2_Value = Guid.initString("130f5136-ec43-4f61-89c7-9801a36d2e95");
pub const IID_IVisualTreeService2 = &IID_IVisualTreeService2_Value;
pub const IVisualTreeService2 = extern struct {
pub const VTable = extern struct {
base: IVisualTreeService.VTable,
GetPropertyIndex: fn(
self: *const IVisualTreeService2,
object: u64,
propertyName: ?[*:0]const u16,
pPropertyIndex: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetProperty: fn(
self: *const IVisualTreeService2,
object: u64,
propertyIndex: u32,
pValue: ?*u64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ReplaceResource: fn(
self: *const IVisualTreeService2,
resourceDictionary: u64,
key: u64,
newValue: u64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RenderTargetBitmap: fn(
self: *const IVisualTreeService2,
handle: u64,
options: RenderTargetBitmapOptions,
maxPixelWidth: u32,
maxPixelHeight: u32,
ppBitmapData: ?*?*IBitmapData,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IVisualTreeService.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVisualTreeService2_GetPropertyIndex(self: *const T, object: u64, propertyName: ?[*:0]const u16, pPropertyIndex: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVisualTreeService2.VTable, self.vtable).GetPropertyIndex(@ptrCast(*const IVisualTreeService2, self), object, propertyName, pPropertyIndex);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVisualTreeService2_GetProperty(self: *const T, object: u64, propertyIndex: u32, pValue: ?*u64) callconv(.Inline) HRESULT {
return @ptrCast(*const IVisualTreeService2.VTable, self.vtable).GetProperty(@ptrCast(*const IVisualTreeService2, self), object, propertyIndex, pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVisualTreeService2_ReplaceResource(self: *const T, resourceDictionary: u64, key: u64, newValue: u64) callconv(.Inline) HRESULT {
return @ptrCast(*const IVisualTreeService2.VTable, self.vtable).ReplaceResource(@ptrCast(*const IVisualTreeService2, self), resourceDictionary, key, newValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVisualTreeService2_RenderTargetBitmap(self: *const T, handle: u64, options: RenderTargetBitmapOptions, maxPixelWidth: u32, maxPixelHeight: u32, ppBitmapData: ?*?*IBitmapData) callconv(.Inline) HRESULT {
return @ptrCast(*const IVisualTreeService2.VTable, self.vtable).RenderTargetBitmap(@ptrCast(*const IVisualTreeService2, self), handle, options, maxPixelWidth, maxPixelHeight, ppBitmapData);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.15063'
const IID_IVisualTreeService3_Value = Guid.initString("0e79c6e0-85a0-4be8-b41a-655cf1fd19bd");
pub const IID_IVisualTreeService3 = &IID_IVisualTreeService3_Value;
pub const IVisualTreeService3 = extern struct {
pub const VTable = extern struct {
base: IVisualTreeService2.VTable,
ResolveResource: fn(
self: *const IVisualTreeService3,
resourceContext: u64,
resourceName: ?[*:0]const u16,
resourceType: ResourceType,
propertyIndex: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDictionaryItem: fn(
self: *const IVisualTreeService3,
dictionaryHandle: u64,
resourceName: ?[*:0]const u16,
resourceIsImplicitStyle: BOOL,
resourceHandle: ?*u64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddDictionaryItem: fn(
self: *const IVisualTreeService3,
dictionaryHandle: u64,
resourceKey: u64,
resourceHandle: u64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveDictionaryItem: fn(
self: *const IVisualTreeService3,
dictionaryHandle: u64,
resourceKey: u64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IVisualTreeService2.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVisualTreeService3_ResolveResource(self: *const T, resourceContext: u64, resourceName: ?[*:0]const u16, resourceType: ResourceType, propertyIndex: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVisualTreeService3.VTable, self.vtable).ResolveResource(@ptrCast(*const IVisualTreeService3, self), resourceContext, resourceName, resourceType, propertyIndex);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVisualTreeService3_GetDictionaryItem(self: *const T, dictionaryHandle: u64, resourceName: ?[*:0]const u16, resourceIsImplicitStyle: BOOL, resourceHandle: ?*u64) callconv(.Inline) HRESULT {
return @ptrCast(*const IVisualTreeService3.VTable, self.vtable).GetDictionaryItem(@ptrCast(*const IVisualTreeService3, self), dictionaryHandle, resourceName, resourceIsImplicitStyle, resourceHandle);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVisualTreeService3_AddDictionaryItem(self: *const T, dictionaryHandle: u64, resourceKey: u64, resourceHandle: u64) callconv(.Inline) HRESULT {
return @ptrCast(*const IVisualTreeService3.VTable, self.vtable).AddDictionaryItem(@ptrCast(*const IVisualTreeService3, self), dictionaryHandle, resourceKey, resourceHandle);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVisualTreeService3_RemoveDictionaryItem(self: *const T, dictionaryHandle: u64, resourceKey: u64) callconv(.Inline) HRESULT {
return @ptrCast(*const IVisualTreeService3.VTable, self.vtable).RemoveDictionaryItem(@ptrCast(*const IVisualTreeService3, self), dictionaryHandle, resourceKey);
}
};}
pub usingnamespace MethodMixin(@This());
};
//--------------------------------------------------------------------------------
// Section: Functions (2)
//--------------------------------------------------------------------------------
pub extern "Windows.UI.Xaml" fn InitializeXamlDiagnostic(
endPointName: ?[*:0]const u16,
pid: u32,
wszDllXamlDiagnostics: ?[*:0]const u16,
wszTAPDllName: ?[*:0]const u16,
tapClsid: Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows10.0.15063'
pub extern "Windows.UI.Xaml" fn InitializeXamlDiagnosticsEx(
endPointName: ?[*:0]const u16,
pid: u32,
wszDllXamlDiagnostics: ?[*:0]const u16,
wszTAPDllName: ?[*:0]const u16,
tapClsid: Guid,
wszInitializationData: ?[*:0]const u16,
) 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 (11)
//--------------------------------------------------------------------------------
const Guid = @import("../../zig.zig").Guid;
const BOOL = @import("../../foundation.zig").BOOL;
const BSTR = @import("../../foundation.zig").BSTR;
const DXGI_ALPHA_MODE = @import("../../graphics/dxgi/common.zig").DXGI_ALPHA_MODE;
const DXGI_FORMAT = @import("../../graphics/dxgi/common.zig").DXGI_FORMAT;
const HRESULT = @import("../../foundation.zig").HRESULT;
const IInspectable = @import("../../system/win_rt.zig").IInspectable;
const IUnknown = @import("../../system/com.zig").IUnknown;
const PWSTR = @import("../../foundation.zig").PWSTR;
const RECT = @import("../../foundation.zig").RECT;
const SAFEARRAY = @import("../../system/com.zig").SAFEARRAY;
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/xaml/diagnostics.zig |
const mdb = struct {
usingnamespace @cImport({
@cInclude("lmdb.h");
});
};
const std = @import("std");
const panic = std.debug.panic;
const assert = std.debug.assert;
const info = std.log.info;
const testing = std.testing;
const err = std.os.E;
const s2s = @import("s2s");
const serialize = s2s.serialize;
const deserialize = s2s.deserialize;
const BLOCK_DB = @import("blockchain.zig").BLOCK_DB;
pub const HASH_SIZE = 8; //size of std.hash.Fnv1a_64 is 64bit which is 8 byte
const Env = mdb.MDB_env;
const Key = mdb.MDB_val;
const Val = mdb.MDB_val;
const Txn = mdb.MDB_txn;
const DbHandle = mdb.MDB_dbi;
//TODO:folow convention of using upper case for structs in file
pub const Lmdb = @This();
const TxnType = enum { rw, ro };
db_env: *Env,
txn: ?*Txn = null,
txn_type: TxnType,
db_handle: DbHandle = undefined,
///`db_path` is the directory in which the database files reside. This directory must already exist and be writable.
///initialize db environment (mmap file) specifing the db mode `.rw/.ro`
///make sure to start a transaction .ie startTxn() fn before calling any db manipulation fn's
///a maximum of two named db's are allowed
pub fn initdb(db_path: []const u8, txn_type: TxnType) Lmdb {
var db_env: ?*Env = undefined;
const env_state = mdb.mdb_env_create(&db_env);
checkState(env_state) catch unreachable;
const max_num_of_dbs = 2;
const db_limit_state = mdb.mdb_env_set_maxdbs(db_env, max_num_of_dbs);
checkState(db_limit_state) catch unreachable;
//if .ro open the environment in read-only mode. No write operations will be allowed.
const db_flags: c_uint = if (txn_type == .ro) mdb.MDB_RDONLY else 0;
const permissions: c_uint = 0o0600; //octal permissions for created files in db_dir
const open_state = mdb.mdb_env_open(db_env, db_path.ptr, db_flags, permissions);
checkState(open_state) catch unreachable;
return .{
.db_env = db_env.?,
.txn_type = txn_type,
};
}
///close all opened db environment
pub fn deinitdb(lmdb: Lmdb) void {
mdb.mdb_env_close(lmdb.db_env);
}
///start a transaction in rw/ro mode and get a db handle for db manipulation
///commit changes with commitTxns() if .rw / doneReading() if .ro
pub fn startTxn(lmdb: Lmdb, txn_type: TxnType, db_name: []const u8) Lmdb {
const txn = beginTxn(lmdb, txn_type);
const handle = openDb(.{ .db_env = lmdb.db_env, .txn = txn, .txn_type = txn_type }, db_name);
return .{
.db_env = lmdb.db_env,
.txn = txn,
.txn_type = txn_type,
.db_handle = handle,
};
}
///open a different db in an already open transaction
pub fn openNewDb(lmdb: Lmdb, db_name: []const u8) Lmdb {
//make sure a transaction has been created already
ensureValidState(lmdb);
const handle = openDb(lmdb, db_name);
return .{
.db_handle = lmdb.db_env,
.txn = lmdb.txn.?,
.txn_type = lmdb.txn_type,
.db_handle = handle,
};
}
fn beginTxn(lmdb: Lmdb, txn_type: TxnType) *Txn {
// This transaction will not perform any write operations if ro.
const flags: c_uint = if (txn_type == .ro) mdb.MDB_RDONLY else 0;
if (flags != mdb.MDB_RDONLY and lmdb.txn_type == .ro) {
panic("Cannot begin a read-write transaction in a read-only environment", .{});
}
const parent = null; //no parent
var txn: ?*Txn = undefined; //where the new #MDB_txn handle will be stored
const txn_state = mdb.mdb_txn_begin(lmdb.db_env, parent, flags, &txn);
checkState(txn_state) catch unreachable;
return txn.?;
}
//TODO:may be support other flags for db like MDB_DUPSORT && MDB_DUPFIXED
fn openDb(lmdb: Lmdb, db_name: []const u8) DbHandle {
//Create the named database if it doesn't exist. This option is not allowed in a read-only transaction or a read-only environment.
const db_flags: c_uint = if (lmdb.txn_type == .rw) mdb.MDB_CREATE else 0;
var db_handle: mdb.MDB_dbi = undefined; //dbi Address where the new #MDB_dbi handle will be stored
const db_state = mdb.mdb_dbi_open(lmdb.txn.?, db_name.ptr, db_flags, &db_handle);
checkState(db_state) catch unreachable;
return db_handle;
}
inline fn ensureValidState(lmdb: Lmdb) void {
assert(lmdb.txn != null);
assert(lmdb.db_handle != undefined);
}
///delete entry in db with key `key_val`
///if db was opened with MDB_DUPSORT use `delDups` instead
pub fn del(lmdb: Lmdb, key_val: []const u8) !void {
ensureValidState(lmdb);
const del_state = mdb.mdb_del(lmdb.txn.?, lmdb.db_handle, &key(key_val), null);
try checkState(del_state);
}
///Use If the database supports sorted duplicate data items (MDB_DUPSORT) else the data parameter is ignored.
///because If the database supports sorted duplicates and the data parameter is NULL, all of the duplicate data items
///for the key will be deleted. While, if the data parameter is non-NULL only the matching data item will be deleted.
pub fn delDups(_: Lmdb, _: []const u8, _: anytype) void {
//This function will return MDB_NOTFOUND if the specified key/data pair is not in the database.
panic("TODO");
}
const InsertionType = enum {
put, //overwrite isn't allowed
update, //overwite data is allowed
};
//TODO:when MDB_DUPSORT is supported then support MDB_NODUPDATA flag
fn insert(lmdb: Lmdb, insertion_t: InsertionType, key_val: []const u8, data: anytype) !void {
const insert_flags: c_uint = switch (insertion_t) {
.put => mdb.MDB_NOOVERWRITE, // don't overwrite data if key already exist
.update => 0,
};
const DataType = @TypeOf(data);
var serialized_data: [HASH_SIZE + @sizeOf(DataType)]u8 = undefined;
var fbr = std.io.fixedBufferStream(&serialized_data);
const writer = fbr.writer();
serialize(writer, DataType, data) catch unreachable;
const put_state = mdb.mdb_put(
lmdb.txn.?,
lmdb.db_handle,
&key(key_val),
&value(serialized_data[0..]),
insert_flags,
);
try checkState(put_state);
}
///insert new key/data pair without overwriting already inserted pair
pub fn put(lmdb: Lmdb, key_val: []const u8, data: anytype) !void {
ensureValidState(lmdb);
try insert(lmdb, .put, key_val, data);
}
///insert/update already existing key/data pair
pub fn update(lmdb: Lmdb, key_val: []const u8, data: anytype) !void {
ensureValidState(lmdb);
try insert(lmdb, .update, key_val, data);
}
///commit all transaction on the current db handle
///should usually be called before the end of fn's to save db changes
pub fn commitTxns(lmdb: Lmdb) void {
ensureValidState(lmdb);
const commit_state = mdb.mdb_txn_commit(lmdb.txn.?);
checkState(commit_state) catch unreachable;
}
///put db in a consistent state after performing a read-only transaction
pub fn doneReading(lmdb: Lmdb) void {
ensureValidState(lmdb);
abortTxns(lmdb);
}
///update the read state of a read-only transaction
///this fn should be called after performing a read-write operation in a different transaction
///it will update the current read-only transaction to see the changes made in the read-write transaction
pub fn updateRead(lmdb: Lmdb) void {
ensureValidState(lmdb);
mdb.mdb_txn_reset(lmdb.txn.?);
const rewew_state = mdb.mdb_txn_renew(lmdb.txn.?);
checkState(rewew_state) catch unreachable;
}
///cancel/discard all transaction on the current db handle
pub fn abortTxns(lmdb: Lmdb) void {
mdb.mdb_txn_abort(lmdb.txn.?);
}
fn getRawBytes(data: ?*anyopaque, start: usize, size: usize) []u8 {
return @ptrCast([*]u8, data.?)[start..size];
}
///get byte slice representing data
pub fn getBytes(comptime len: usize, data: ?*anyopaque, size: usize) []u8 {
return getBytesAs([len]u8, data, size)[0..];
}
//TODO: handle the case where the type to deserialize needs to be allocated with a fixedBufferAllocator
pub fn getBytesAs(comptime T: type, data: ?*anyopaque, size: usize) T {
// return std.mem.bytesAsSlice(T, getBytes(data.?, size))[0];
const serialized_data = getRawBytes(data, 0, size);
var fbr = std.io.fixedBufferStream(serialized_data);
fbr.seekTo(0) catch unreachable;
const reader = fbr.reader();
return deserialize(reader, T) catch unreachable;
}
///This is any unsafe cast which discards const
pub fn cast(comptime T: type, any_ptr: anytype) T {
return @intToPtr(T, @ptrToInt(any_ptr));
}
///get the data as a slice of bytes
pub fn get(lmdb: Lmdb, key_val: []const u8, comptime value_len: usize) ![]u8 {
ensureValidState(lmdb);
var data: Val = undefined;
const get_state = mdb.mdb_get(
lmdb.txn.?,
lmdb.db_handle,
&key(key_val),
&data,
);
try checkState(get_state);
return getBytes(value_len, data.mv_data, data.mv_size);
}
///get the data as type `T`
pub fn getAs(lmdb: Lmdb, comptime T: type, key_val: []const u8) !T {
ensureValidState(lmdb);
var data: Val = undefined;
const get_state = mdb.mdb_get(
lmdb.txn.?,
lmdb.db_handle,
&key(key_val),
&data,
);
try checkState(get_state);
return getBytesAs(T, data.mv_data, data.mv_size);
}
fn key(data: []const u8) Key {
return value(data);
}
fn value(data: []const u8) Val {
return .{ .mv_size = data.len, .mv_data = cast(*anyopaque, data.ptr) };
}
///check state of operation to make sure there where no errors
fn checkState(state: c_int) !void {
switch (state) {
//lmdb errors Return Codes
//Successful result */
mdb.MDB_SUCCESS => {},
//key/data pair already exists */
mdb.MDB_KEYEXIST => {
info("'{}' -> {s}", .{ state, mdb.mdb_strerror(state) });
return error.KeyAlreadyExist;
},
//key/data pair not found (EOF) */
mdb.MDB_NOTFOUND => {
info("'{}' -> {s}", .{ state, mdb.mdb_strerror(state) });
return error.KeyNotFound;
},
//Requested page not found - this usually indicates corruption */
mdb.MDB_PAGE_NOTFOUND => {
info("'{}' -> {s}", .{ state, mdb.mdb_strerror(state) });
return error.RequestedPageNotFound;
},
//Located page was wrong type */
mdb.MDB_CORRUPTED => {
info("'{}' -> {s}", .{ state, mdb.mdb_strerror(state) });
return error.WrongPageType;
},
//Update of meta page failed or environment had fatal error */
mdb.MDB_PANIC => {
info("'{}' -> {s}", .{ state, mdb.mdb_strerror(state) });
return error.EnvFatalError;
},
//Environment version mismatch */
mdb.MDB_VERSION_MISMATCH => {
info("'{}' -> {s}", .{ state, mdb.mdb_strerror(state) });
return error.EnvVersionMismatch;
},
//File is not a valid LMDB file */
mdb.MDB_INVALID => {
info("'{}' -> {s}", .{ state, mdb.mdb_strerror(state) });
return error.InvalidDbFile;
},
//Environment mapsize reached */
mdb.MDB_MAP_FULL => {
info("'{}' -> {s}", .{ state, mdb.mdb_strerror(state) });
return error.EnvMapsizeFull;
},
//Environment maxdbs reached */
mdb.MDB_DBS_FULL => {
info("'{}' -> {s}", .{ state, mdb.mdb_strerror(state) });
return error.EnvMaxDbsOpened;
},
//Environment maxreaders reached */
mdb.MDB_READERS_FULL => {
info("'{}' -> {s}", .{ state, mdb.mdb_strerror(state) });
return error.EnvMaxReaders;
},
//Too many TLS keys in use - Windows only */
mdb.MDB_TLS_FULL => {
info("'{}' -> {s}", .{ state, mdb.mdb_strerror(state) });
return error.ManyTlsKeysUsed;
},
//Txn has too many dirty pages */
mdb.MDB_TXN_FULL => {
info("'{}' -> {s}", .{ state, mdb.mdb_strerror(state) });
return error.ManyTxnDirtyPages;
},
//Cursor stack too deep - internal error */
mdb.MDB_CURSOR_FULL => {
info("'{}' -> {s}", .{ state, mdb.mdb_strerror(state) });
return error.DeepCursorStack;
},
//Page has not enough space - internal error */
mdb.MDB_PAGE_FULL => {
info("'{}' -> {s}", .{ state, mdb.mdb_strerror(state) });
return error.NotEnoughPageSpace;
},
//Database contents grew beyond environment mapsize */
mdb.MDB_MAP_RESIZED => {
info("'{}' -> {s}", .{ state, mdb.mdb_strerror(state) });
return error.DbSizeGtEnvMapsize;
},
//Operation and DB incompatible, or DB type changed. This can mean:
//The operation expects an #MDB_DUPSORT /#MDB_DUPFIXED database.
//Opening a named DB when the unnamed DB has #MDB_DUPSORT /#MDB_INTEGERKEY.
//Accessing a data record as a database, or vice versa.
//The database was dropped and recreated with different flags.
mdb.MDB_INCOMPATIBLE => {
info("'{}' -> {s}", .{ state, mdb.mdb_strerror(state) });
return error.OpAndDbIncompatible;
},
//Invalid reuse of reader locktable slot */
mdb.MDB_BAD_RSLOT => {
info("'{}' -> {s}", .{ state, mdb.mdb_strerror(state) });
return error.InvalidReaderSlotReuse;
},
//Transaction must abort, has a child, or is invalid */
mdb.MDB_BAD_TXN => {
info("'{}' -> {s}", .{ state, mdb.mdb_strerror(state) });
return error.InvalidTxn;
},
//Unsupported size of key/DB name/data, or wrong DUPFIXED size */
mdb.MDB_BAD_VALSIZE => {
info("'{}' -> {s}", .{ state, mdb.mdb_strerror(state) });
return error.UnsupportedComponentSize;
},
//The specified DBI was changed unexpectedly */
mdb.MDB_BAD_DBI => {
info("'{}' -> {s}", .{ state, mdb.mdb_strerror(state) });
return error.InvalidDbHandle;
},
//out of memory.
@enumToInt(err.NOENT) => {
info("'{}' -> {s}", .{ state, mdb.mdb_strerror(state) });
return error.NoSuchFileOrDirectory;
},
//don't have adecuate permissions to perform operation
@enumToInt(err.ACCES) => {
info("'{}' -> {s}", .{ state, mdb.mdb_strerror(state) });
return error.PermissionDenied;
},
//the environment was locked by another process.
@enumToInt(err.AGAIN) => {
info("'{}' -> {s}", .{ state, mdb.mdb_strerror(state) });
return error.EnvLockedTryAgain;
},
@enumToInt(err.NOMEM) => {
info("'{}' -> {s}", .{ state, mdb.mdb_strerror(state) });
return error.OutOfMemory;
},
//an invalid parameter was specified.
@enumToInt(err.INVAL) => {
info("'{}' -> {s}", .{ state, mdb.mdb_strerror(state) });
return error.InvalidArgument;
},
//a low-level I/O error occurred
@enumToInt(err.IO) => {
info("'{}' -> {s}", .{ state, mdb.mdb_strerror(state) });
return error.IOFailed;
},
//no more disk space on device.
@enumToInt(err.NOSPC) => {
info("'{}' -> {s}", .{ state, mdb.mdb_strerror(state) });
return error.DiskSpaceFull;
},
else => panic("'{}' -> {s}", .{ state, mdb.mdb_strerror(state) }),
}
}
test "test db key:str / value:str" {
var dbh = initdb("./testdb", .rw);
defer deinitdb(dbh);
const wtxn = dbh.startTxn(.rw, BLOCK_DB);
const val: [5]u8 = "value".*;
try wtxn.update("key", val);
wtxn.commitTxns();
const rtxn = dbh.startTxn(.ro, BLOCK_DB);
defer rtxn.doneReading();
try testing.expectEqualSlices(u8, "value", (try rtxn.get("key", val.len)));
}
test "test db update" {
var dbh = initdb("./testdb", .rw);
defer deinitdb(dbh);
const txn = dbh.startTxn(.rw, BLOCK_DB);
//TODO(ultracode): find out why this causes a segfault
defer txn.commitTxns();
const Data = struct {
char: [21]u8,
int: u8,
ochar: [21]u8,
};
const data = Data{
.char = "is my data still here".*,
.int = 254,
.ochar = "is my data still here".*,
};
try txn.update("data_key", data);
const gotten_data = try txn.getAs(Data, "data_key");
try testing.expectEqualSlices(u8, data.char[0..], gotten_data.char[0..]);
try testing.expectEqualSlices(u8, data.ochar[0..], gotten_data.ochar[0..]);
try testing.expect(data.int == gotten_data.int);
} | src/lmdb.zig |
const std = @import("std");
const fs = std.fs;
const num_indices: usize = 20;
const Range = struct {
min: u32 = 0xFFFFFFFF,
max: u32 = 0,
const Self = @This();
pub fn fromString(s: []const u8) !Self {
var it = std.mem.tokenize(s, "-");
return Self{
.min = try std.fmt.parseInt(u32, it.next().?, 10),
.max = try std.fmt.parseInt(u32, it.next().?, 10)
};
}
};
const Field = struct {
name: []const u8,
r0: Range,
r1: Range,
index: i32 = -1,
const Self = @This();
pub fn isValidV(self: *const Self, v: u32) bool {
return (v >= self.r0.min and v <= self.r0.max) or (v >= self.r1.min and v <= self.r1.max);
}
};
const Ticket = struct {
vals: [num_indices]u32 = undefined,
const Self = @This();
pub fn fromString(s: []const u8) !Self {
var res = Self{};
var vals = std.mem.tokenize(std.mem.trim(u8, s, " \r\n"), ",");
var i: usize = 0;
while (i < num_indices) : (i += 1) {
const val = vals.next().?;
//std.debug.print("Parse: \"{}\"\n", .{val});
res.vals[i] = try std.fmt.parseInt(u32, val, 10);
}
return res;
}
};
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = &gpa.allocator;
const input = try fs.cwd().readFileAlloc(allocator, "data/input_16_1.txt", std.math.maxInt(usize));
var fields = std.ArrayList(Field).init(allocator);
defer fields.deinit();
var tickets = std.ArrayList(Ticket).init(allocator);
defer tickets.deinit();
var my_ticket = Ticket{};
{ // parse input
var lines = std.mem.tokenize(input, "\n");
// Parse fields
while (lines.next()) |raw_line| {
const line = std.mem.trim(u8, raw_line, " \r\n");
if (line.len == 0)
break;
var field_it = std.mem.tokenize(line, ":");
const name = std.mem.trim(u8, field_it.next().?, " ");
const ranges = std.mem.trim(u8, field_it.next().?, " \r\n");
const or_idx = std.ascii.indexOfIgnoreCase(ranges, " or ").?;
const range1 = ranges[0..or_idx];
const range2 = ranges[or_idx+" or ".len..];
try fields.append(Field{ .name = name,
.r0 = try Range.fromString(range1),
.r1 = try Range.fromString(range2) });
}
std.debug.assert(std.mem.eql(u8, std.mem.trim(u8, lines.next().?, " \r\n"), "your ticket:"));
my_ticket = try Ticket.fromString(lines.next().?);
_ = lines.next(); // empty line
std.debug.assert(std.mem.eql(u8, std.mem.trim(u8, lines.next().?, " \r\n"), "nearby tickets:"));
while (lines.next()) |raw_line| {
const line = std.mem.trim(u8, raw_line, " \r\n");
try tickets.append(try Ticket.fromString(line));
}
}
var valid_tickets = std.ArrayList(Ticket).init(allocator);
defer valid_tickets.deinit();
{ // Solution one
var accum: u32 = 0;
for (tickets.items) |ticket| {
var is_valid_ticket = true;
for (ticket.vals) |v| {
var is_valid = for (fields.items) |f| {
if (f.isValidV(v)) {
break true;
}
} else false;
if (!is_valid) {
accum += v;
is_valid_ticket = false;
}
}
if (is_valid_ticket) {
try valid_tickets.append(ticket);
}
}
std.debug.print("Day 16 - Solution 1: {}\n", .{accum});
}
{ // Solution two
var count: usize = 0;
outer: while (true) {
for (fields.items) |_, vi| {
var match_field: usize = 0;
var matched: u32 = 0;
for (fields.items) |field, fi| {
if (field.index >= 0) continue;
var match = for (valid_tickets.items) |ticket| {
if (!field.isValidV(ticket.vals[vi])) break false;
} else true;
if (match) {
match_field =fi;
matched += 1;
if (matched > 1) break;
}
}
if (matched == 1) {
fields.items[@intCast(usize, match_field)].index = @intCast(i32, vi);
count += 1;
//std.debug.print("Matched: {} fields\n", .{count});
if (count == fields.items.len) break :outer;
continue :outer;
}
}
unreachable;
}
var accum: u64 = 1;
{ var i: usize = 0; while (i < 6) : (i += 1) { // All the departures
accum *= @intCast(u64, my_ticket.vals[@intCast(usize, fields.items[i].index)]);
}}
std.debug.print("Day 16 - Solution 2: {}", .{accum});
}
} | 2020/src/day_16.zig |
const tone = @import("tone.zig");
const tune = @import("tune.zig");
const note = @import("note.zig");
const music = @import("music.zig");
const c4 = note.getFreq("C 4".*);
const c5 = note.getFreq("C 5".*);
const g4 = note.getFreq("G 4".*);
const a4 = note.getFreq("A 4".*);
const d4 = note.getFreq("D 4".*);
const e4 = note.getFreq("E 4".*);
const e3 = note.getFreq("E 3".*);
const eb3 = note.getFreq("Eb3".*);
const g3 = note.getFreq("G 3".*);
const gb3 = note.getFreq("Gb3".*);
const c3 = note.getFreq("C 3".*);
const f3 = note.getFreq("F 3".*);
const f4 = note.getFreq("F 4".*);
const gb4 = note.getFreq("Gb4".*);
const bb2 = note.getFreq("Bb2".*);
const a2 = note.getFreq("A 2".*);
const g2 = note.getFreq("G 2".*);
var melodyTone = tone.Tone{ .sfreq = c5, .efreq = c5, .channel = 1 };
var drumTone = tone.Tone{ .sfreq = c5, .efreq = c5, .channel = 3, .release = 60, .volume = 25, .mode = 2 };
var bassTone = tone.Tone{ .sfreq = c5, .efreq = c5, .channel = 2 };
var melodyNotes = [_]note.Note{
note.Note{ .sfreq = c5, .efreq = c5, .length = 45 },
note.Note{ .sfreq = g4, .efreq = g4, .length = 45 },
note.Note{ .sfreq = a4, .efreq = a4, .length = 45 },
note.Note{ .sfreq = d4, .efreq = d4, .length = 45 },
note.Note{ .sfreq = e4, .efreq = e4, .length = 90 },
note.Note{ .sfreq = 307, .efreq = 287, .length = 90 },
note.Note{ .sfreq = 294, .efreq = 255, .length = 180 },
note.Note{ .sfreq = c4, .efreq = c4, .length = 45, .on = false },
note.Note{ .sfreq = c4, .efreq = c4, .length = 45 },
note.Note{ .sfreq = f4, .efreq = f4, .length = 45 },
note.Note{ .sfreq = e4, .efreq = e4, .length = 45 },
note.Note{ .sfreq = e4, .efreq = e4, .length = 22, .on = false },
note.Note{ .sfreq = e4, .efreq = e4, .length = 45 },
note.Note{ .sfreq = a4, .efreq = a4, .length = 23 },
note.Note{ .sfreq = g4, .efreq = g4, .length = 45 },
note.Note{ .sfreq = d4, .efreq = d4, .length = 45 },
note.Note{ .sfreq = a4, .efreq = a4, .length = 22 },
note.Note{ .sfreq = g4, .efreq = g4, .length = 23 },
note.Note{ .sfreq = f4, .efreq = f4, .length = 22 },
note.Note{ .sfreq = g4, .efreq = g4, .length = 23 },
note.Note{ .sfreq = e4, .efreq = e4, .length = 90 },
note.Note{ .sfreq = d4, .efreq = d4, .length = 90 },
note.Note{ .sfreq = g4, .efreq = g4, .length = 90 },
note.Note{ .sfreq = c5, .efreq = c5, .length = 45 },
note.Note{ .sfreq = g4, .efreq = g4, .length = 45 },
note.Note{ .sfreq = a4, .efreq = a4, .length = 45 },
note.Note{ .sfreq = d4, .efreq = d4, .length = 45 },
note.Note{ .sfreq = e4, .efreq = e4, .length = 22, .on = false },
note.Note{ .sfreq = e4, .efreq = e4, .length = 45 },
note.Note{ .sfreq = a4, .efreq = a4, .length = 23 },
note.Note{ .sfreq = g4, .efreq = g4, .length = 45 },
note.Note{ .sfreq = d4, .efreq = d4, .length = 45 },
note.Note{ .sfreq = a4, .efreq = a4, .length = 22 },
note.Note{ .sfreq = g4, .efreq = g4, .length = 23 },
note.Note{ .sfreq = f4, .efreq = f4, .length = 22 },
note.Note{ .sfreq = g4, .efreq = g4, .length = 23 },
note.Note{ .sfreq = e4, .efreq = e4, .length = 22 },
note.Note{ .sfreq = e4, .efreq = f4, .length = 45 },
note.Note{ .sfreq = e4, .efreq = g4, .length = 45 },
note.Note{ .sfreq = d4, .efreq = d4, .length = 45 },
note.Note{ .sfreq = d4, .efreq = e4, .length = 45 },
note.Note{ .sfreq = g4, .efreq = g4, .length = 45 },
note.Note{ .sfreq = gb4, .efreq = gb4, .length = 23 },
note.Note{ .sfreq = e4, .efreq = e4, .length = 45 },
note.Note{ .sfreq = 307, .efreq = 287, .length = 45 },
note.Note{ .sfreq = 294, .efreq = 255, .length = 90 },
};
var drumNotes = [_]note.Note{
note.Note{ .sfreq = e3, .efreq = e3, .length = 45 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 45 },
note.Note{ .sfreq = eb3, .efreq = eb3, .length = 45 },
note.Note{ .sfreq = gb3, .efreq = g3, .length = 45 },
note.Note{ .sfreq = e3, .efreq = e3, .length = 45 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 45 },
note.Note{ .sfreq = eb3, .efreq = eb3, .length = 45 },
note.Note{ .sfreq = gb3, .efreq = g3, .length = 45 },
note.Note{ .sfreq = e3, .efreq = e3, .length = 45 },
note.Note{ .sfreq = 1, .efreq = 1, .length = 45 },
note.Note{ .sfreq = 1, .efreq = 1, .length = 45 },
note.Note{ .sfreq = 1, .efreq = 1, .length = 45 },
note.Note{ .sfreq = e3, .efreq = e3, .length = 45 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 45 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 22, .on = false },
note.Note{ .sfreq = e3, .efreq = e3, .length = 23 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 45 },
note.Note{ .sfreq = e3, .efreq = e3, .length = 45 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 45 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 22, .on = false },
note.Note{ .sfreq = e3, .efreq = e3, .length = 23 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 45 },
note.Note{ .sfreq = e3, .efreq = e3, .length = 45 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 45 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 22, .on = false },
note.Note{ .sfreq = e3, .efreq = e3, .length = 23 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 45 },
note.Note{ .sfreq = e3, .efreq = e3, .length = 45 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 45 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 22, .on = false },
note.Note{ .sfreq = e3, .efreq = e3, .length = 23 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 45 },
note.Note{ .sfreq = e3, .efreq = e3, .length = 45 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 45 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 22, .on = false },
note.Note{ .sfreq = e3, .efreq = e3, .length = 23 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 45 },
note.Note{ .sfreq = e3, .efreq = e3, .length = 45 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 45 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 22, .on = false },
note.Note{ .sfreq = e3, .efreq = e3, .length = 23 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 45 },
note.Note{ .sfreq = e3, .efreq = e3, .length = 45 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 45 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 22, .on = false },
note.Note{ .sfreq = e3, .efreq = e3, .length = 23 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 45 },
note.Note{ .sfreq = e3, .efreq = e3, .length = 45 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 45 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 22, .on = false },
note.Note{ .sfreq = e3, .efreq = e3, .length = 23 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 45 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 45 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 45 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 35 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 35 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 20 },
};
var bassNotes = [_]note.Note{
note.Note{ .sfreq = c3, .efreq = c3, .length = 90 },
note.Note{ .sfreq = e3, .efreq = e3, .length = 90 },
note.Note{ .sfreq = g3, .efreq = g3, .length = 90 },
note.Note{ .sfreq = gb3, .efreq = gb3, .length = 90 },
note.Note{ .sfreq = f3, .efreq = g3, .length = 180 },
note.Note{ .sfreq = c3, .efreq = c3, .length = 90 },
note.Note{ .sfreq = bb2, .efreq = c3, .length = 90 },
note.Note{ .sfreq = c3, .efreq = c3, .length = 90 },
note.Note{ .sfreq = bb2, .efreq = c3, .length = 22, .on = false },
note.Note{ .sfreq = bb2, .efreq = c3, .length = 68 },
};
var melody = tune.Tune{ .notes = &melodyNotes, .numNotes = melodyNotes.len, .tone = &melodyTone, .introEndNote = 7 };
var drums = tune.Tune{ .notes = &drumNotes, .numNotes = drumNotes.len, .tone = &drumTone, .introEndNote = 12 };
var bass = tune.Tune{ .notes = &bassNotes, .numNotes = bassNotes.len, .tone = &bassTone, .introEndNote = 5 };
pub const mainMenuMusic = music.Music{ .part1 = &melody, .part2 = &drums, .part3 = &bass }; | src/music/title-theme.zig |
const std = @import("std");
const os = @import("root").os;
const kepler = os.kepler;
/// Type of the object that can be stored in local object namespace
pub const ObjectType = enum {
/// Object which exposes Stream interface. See Stream class description
/// in kepler/ipc.zig. Not shareable.
Stream,
/// Object which exposes Endpoint interface. See Stream class description
/// in kepler/ipc.zig. Shareable.
Endpoint,
/// Object which allows to access memory shared between arenas.
/// See MemoryObject class description in kepler/memory.zig. Shareable
MemoryObject,
/// LockedHandle is the object that stores one integer only
/// owner can access. See LockedHandle description in this file. Shareable
LockedHandle,
/// InterruptObject is the object that owns interrupt source of any kind.
InterruptObject,
/// Used to indicate that this reference cell is empty
None,
};
/// Type that represents local reference to the object
/// Unlike SharedObjectRef, it can represent references
/// to not shareable objects such as streams. It can store
/// local metadata (e.g. address of the mapping for memory objects)
/// as well
pub const ObjectRef = union(ObjectType) {
/// Stream reference data
Stream: struct {
/// Role of the reference owner in the connection
peer: kepler.ipc.Stream.Peer,
/// Reference to the stream object itself
ref: *kepler.ipc.Stream,
},
/// Endpoint reference data
Endpoint: struct {
/// Reference to the endpoint itself
ref: *kepler.ipc.Endpoint,
/// True if reference is owning reference
is_owning: bool,
},
/// Memory object reference data
MemoryObject: struct {
/// Reference to the memory object itself
ref: *kepler.memory.MemoryObject,
/// null if memory object was not mapped
/// address of the mapping
mapped_to: ?usize,
},
/// Interrupt object
InterruptObject: *kepler.interrupts.InterruptObject,
/// Locked handle reference
LockedHandle: *LockedHandle,
/// None means that there is no reference to any object
None: void,
/// Drop reference. mapper is the Mapper used by the arena (for .MemoryObject objects)
pub fn drop(self: *const @This(), mapper: *kepler.memory.Mapper) void {
switch (self.*) {
.Stream => |stream| stream.ref.abandon(stream.peer),
.Endpoint => |endpoint| {
if (endpoint.is_owning) {
endpoint.ref.shutdown();
} else {
endpoint.ref.drop();
}
},
.MemoryObject => |memory_object| {
if (memory_object.mapped_to) |offset| {
mapper.unmap(memory_object.ref, offset);
}
},
.LockedHandle => |locked_handle| locked_handle.drop(),
.InterruptObject => |interrupt_object| interrupt_object.shutdown(),
.None => {},
}
}
/// Drop and swap with null
pub fn drop_and_swap(self: *@This()) void {
self.drop();
self.* = @This().None;
}
/// Borrow shareable reference. Increments refcount
pub fn pack_shareable(self: *const @This()) !SharedObjectRef {
switch (self.*) {
.Stream, .InterruptObject => return error.ObjectNotShareable,
.Endpoint => |endpoint| return SharedObjectRef{ .Endpoint = endpoint.ref.borrow() },
.MemoryObject => |memory_obj| return SharedObjectRef{ .MemoryObject = memory_obj.ref.borrow() },
.LockedHandle => |locked_handle| return SharedObjectRef{ .LockedHandle = locked_handle.borrow() },
.None => return SharedObjectRef.None,
}
}
/// Unpack from shareable. Consumes ref, hence does not increment reference count
pub fn unpack_shareable(ref: SharedObjectRef) @This() {
switch (ref) {
.Endpoint => |endpoint| return @This(){ .Endpoint = .{ .ref = endpoint, .is_owning = false } },
.MemoryObject => |memory_obj| return @This(){ .MemoryObject = .{ .ref = memory_obj, .mapped_to = null } },
.LockedHandle => |locked_handle| return @This(){ .LockedHandle = locked_handle },
.None => return @This().None,
}
}
};
/// Type of the object that can be passed with IPC
pub const SharedObjectType = enum {
/// Shareable endpoint reference
Endpoint,
/// Shareable memory object reference
MemoryObject,
/// Shareable locked handle reference
LockedHandle,
/// Used to indicate that this reference cell is empty
None,
};
/// Shareable reference to the object. Smaller than ObjectRef
/// as it doesn't store any local metadata. Can't store references
/// to non-shareable objects such as streams as well. Used in IPC
pub const SharedObjectRef = union(SharedObjectType) {
/// Shareable reference to the endpoint
Endpoint: *kepler.ipc.Endpoint,
/// Shareable reference to the memory objects
MemoryObject: *kepler.memory.MemoryObject,
/// Shareable reference to the locked handle
LockedHandle: *LockedHandle,
/// Idk, just none :^)
None: void,
/// Drop reference
pub fn drop(self: *const @This()) void {
switch (self.*) {
.Endpoint => |endpoint| endpoint.drop(),
.LockedHandle => |locked_handle| locked_handle.drop(),
.MemoryObject => |memory_obj| memory_obj.drop(),
.None => {},
}
}
};
/// Object that is used to pass references to other objects between threads
pub const ObjectRefMailbox = struct {
/// Permissions for a given reference cell
const Permissions = enum(u8) {
/// Default state. Consumer is allowed to read or write
/// to cell and immediately grant rights to the producer after that.
/// Producer is not allowed to do anything.
OwnedByConsumer,
/// Consumer has granted rights to read from cell. Now it can't do anything
/// Producer is allowed to do one read and give rights back (aka burn after read)
GrantedReadRights,
/// Consumer has granted rights ro write to cell. Now it can't do anything
/// Producer is allowed to do one write and give rights back (aka burn after write)
GrantedWriteRights,
/// Consumer can read value from this location and transfer to OwnedByConsumer state
/// Producer has no rights
ToBeReadByConsumer,
};
/// Cell is a combination of permissions and references
const Cell = struct {
perms: Permissions,
ref: SharedObjectRef,
};
/// Array of cells
cells: []Cell,
/// Allocator used to allocate this object
allocator: *std.mem.Allocator,
/// Create mailbox
pub fn init(allocator: *std.mem.Allocator, num: usize) !@This() {
var result: @This() = undefined;
result.cells = try allocator.alloc(Cell, num);
for (result.cells) |*ref| {
// Initially consumer owns every cell, as it is the one that
// initiates requests
ref.* = Cell{ .perms = .OwnedByConsumer, .ref = SharedObjectRef.None };
}
result.allocator = allocator;
return result;
}
/// Dispose internal structures
pub fn drop(self: *const @This()) void {
for (self.cells) |ref| {
ref.ref.drop();
}
self.allocator.free(self.cells);
}
/// Checks that
/// 1) Index is in bounds
/// 2) Permission for the cell are equal to perms
/// 3) If perms == .OwnedByConsumer, asserts that cell points to null in debug mode
fn check_bounds_and_status(self: *@This(), index: usize, perms: Permissions) !void {
if (index > self.cells.len) {
return error.OutOfBounds;
}
// Assert permission
if (@atomicLoad(Permissions, &self.cells[index].perms, .Acquire) != perms) {
return error.NotEnoughPermissions;
}
// Cells consumer has access to should always be nulled
std.debug.assert(perms != .OwnedByConsumer or std.meta.activeTag(self.cells[index].ref) == .None);
}
/// Grant write rights. Invoked from consumer only
pub fn grant_write(self: *@This(), index: usize) !void {
try self.check_bounds_and_status(index, .OwnedByConsumer);
@atomicStore(Permissions, &self.cells[index].perms, .GrantedWriteRights, .Release);
}
/// Assert permissions, read reference, modify permissions for a given cell
fn read(self: *@This(), index: usize, old_perms: Permissions, new_perms: Permissions) !ObjectRef {
// Assert perms
try self.check_bounds_and_status(index, old_perms);
// Move reference and set reference at this cell to None
const result = ObjectRef.unpack_shareable(self.cells[index].ref);
self.cells[index].ref = SharedObjectRef.None;
// Modify perms
@atomicStore(Permissions, &self.cells[index].perms, new_perms, .Release);
return result;
}
/// Read reference from the consumer side at a given index
pub fn read_from_consumer(self: *@This(), index: usize) !ObjectRef {
return self.read(index, .ToBeReadByConsumer, .OwnedByConsumer);
}
/// Read reference from the producer side at a given index
pub fn read_from_producer(self: *@This(), index: usize) !ObjectRef {
return self.read(index, .GrantedReadRights, .OwnedByConsumer);
}
/// Write reference from consumer side
pub fn write_from_consumer(self: *@This(), index: usize, object: ObjectRef) !void {
try self.check_bounds_and_status(index, .OwnedByConsumer);
self.cells[index].ref = try object.pack_shareable();
@atomicStore(Permissions, &self.cells[index].perms, .GrantedReadRights, .Release);
}
/// Write reference from producer side
pub fn write_from_producer(self: *@This(), index: usize, object: ObjectRef) !void {
try self.check_bounds_and_status(index, .GrantedWriteRights);
self.cells[index].ref = try object.pack_shareable();
@atomicStore(Permissions, &self.cells[index].perms, .ToBeReadByConsumer, .Release);
}
};
/// Locked handle object is the object that is capable of storing a single usize
/// integer in a way that only allows threads from owning arena to get the
/// integer value, while the object can be passed around freely
pub const LockedHandle = struct {
/// Reference count
ref_count: usize,
/// Locked integer value
handle: usize,
/// Password. TODO: Set to arena ID or something
password: usize,
/// Allocator used to allocate the object
/// TODO: Consider storing allocator somewhere else, storing it here may
/// be too wasteful. For now I just add it to pad it to 32 bytes :^)
allocator: *std.mem.Allocator,
pub fn create(allocator: *std.mem.Allocator, handle: usize, password: usize) !*LockedHandle {
const instance = try allocator.create(@This());
instance.ref_count = 1;
instance.password = password;
instance.handle = handle;
return instance;
}
pub fn borrow(self: *@This()) *@This() {
_ = @atomicRmw(usize, &self.ref_count, .Add, 1, .AcqRel);
return self;
}
pub fn drop(self: *@This()) void {
if (@atomicRmw(usize, &self.ref_count, .Sub, 1, .AcqRel) > 1) {
return;
}
self.allocator.destroy(self);
}
pub fn peek(self: *const @This(), password: usize) !usize {
if (self.password != password) {
return error.AuthenticationFailed;
}
return self.handle;
}
}; | src/kepler/objects.zig |
const Wwise = @import("../wwise.zig").Wwise;
const ImGui = @import("../imgui.zig").ImGui;
const DemoInterface = @import("demo_interface.zig").DemoInterface;
const std = @import("std");
pub const RtpcCarEngineDemo = struct {
allocator: std.mem.Allocator = undefined,
isVisibleState: bool = false,
bankID: u32 = 0,
isPlaying: bool = false,
rpmValue: i32 = 0,
const Self = @This();
const DemoGameObjectID = 4;
const MinRPMValue = 1000;
const MaxRPMValue = 10000;
pub fn init(self: *Self, allocator: std.mem.Allocator) !void {
self.allocator = allocator;
self.rpmValue = MinRPMValue;
self.bankID = try Wwise.loadBankByString("Car.bnk");
try Wwise.registerGameObj(DemoGameObjectID, "Car");
try Wwise.setRTPCValueByString("RPM", @intToFloat(f32, self.rpmValue), DemoGameObjectID);
}
pub fn deinit(self: *Self) void {
_ = Wwise.unloadBankByID(self.bankID);
Wwise.unregisterGameObj(DemoGameObjectID);
self.allocator.destroy(self);
}
pub fn onUI(self: *Self) !void {
if (ImGui.igBegin("RTPC Demo (Car Engine)", &self.isVisibleState, ImGui.ImGuiWindowFlags_AlwaysAutoResize)) {
const buttonText = if (self.isPlaying) "Stop Engine" else "Start Engine";
if (ImGui.igButton(buttonText, .{ .x = 0, .y = 0 })) {
if (self.isPlaying) {
_ = try Wwise.postEvent("Stop_Engine", DemoGameObjectID);
self.isPlaying = false;
} else {
_ = try Wwise.postEvent("Play_Engine", DemoGameObjectID);
self.isPlaying = true;
}
}
if (ImGui.igSliderInt("RPM", &self.rpmValue, MinRPMValue, MaxRPMValue, "%u")) {
try Wwise.setRTPCValueByString("RPM", @intToFloat(f32, self.rpmValue), DemoGameObjectID);
}
ImGui.igEnd();
}
if (!self.isVisibleState) {
Wwise.stopAllOnGameObject(DemoGameObjectID);
}
}
pub fn isVisible(self: *Self) bool {
return self.isVisibleState;
}
pub fn show(self: *Self) void {
self.isVisibleState = true;
}
pub fn getInterface(self: *Self) DemoInterface {
return DemoInterface{
.instance = @ptrCast(DemoInterface.InstanceType, self),
.initFn = @ptrCast(DemoInterface.InitFn, init),
.deinitFn = @ptrCast(DemoInterface.DeinitFn, deinit),
.onUIFn = @ptrCast(DemoInterface.OnUIFn, onUI),
.isVisibleFn = @ptrCast(DemoInterface.IsVisibleFn, isVisible),
.showFn = @ptrCast(DemoInterface.ShowFn, show),
};
}
}; | src/demos/rtpc_car_engine_demo.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.
// b.addStaticLibrary("libcurl", "");
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("sapt", "src/main.zig");
exe.linkSystemLibrary("c");
exe.setTarget(target);
// This seems quite hacky, but makes it currently possible to cross-build provided we have prebuilt libcurl.dll/.so/.dylib (and zlib1?)
// Cross-builds with windows host: always libcurl
// Cross-builds with WSL host:
if(target.isNative()) {
exe.linkSystemLibrary("libcurl");
} else {
std.debug.print("Crossbuilding\n", .{});
// exe.addIncludeDir("/usr/include/");
// exe.addLibPath("/usr/include/"); // TODO: Only for linux as host?
// TODO: Check arch as well to ensure x86_64
switch(target.getOsTag()) {
.linux => {
exe.linkSystemLibrary("libcurl");
// try exe.lib_paths.resize(0); // Workaround, as linkSystemLibrary adds system link-path, and we want to override this with a custom one
try exe.lib_paths.insert(0, "xbuild/libs/x86_64-linux");
},
.macos => {
exe.linkSystemLibrary("libcurl");
// try exe.lib_paths.resize(0); // Workaround, as linkSystemLibrary adds system link-path, and we want to override this with a custom one
try exe.lib_paths.insert(0, "xbuild/libs/x86_64-macos");
},
.windows => {
exe.linkSystemLibrary("libcurl");
// try exe.lib_paths.resize(0); // Workaround, as linkSystemLibrary adds system link-path, and we want to override this with a custom one
try exe.lib_paths.insert(0, "xbuild/libs/x86_64-windows");
// TODO: Copy in zlib1.dll and libcurl.dll to prefix
},
else => {
// Not supported?
return error.UnsupportedCrossTarget;
}
}
}
exe.setBuildMode(mode);
// try exe.lib_paths.resize(0);
// exe.addLibPath("xbuild/libs/x86_64-linux");
// exe.addLibPath("xbuild/libs/x86_64-mac");
// exe.addLibPath("xbuild/libs/x86_64-windows/lib");
exe.install();
const run_cmd = exe.run();
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
var all_tests = b.addTest("src/test.zig");
all_tests.setBuildMode(mode);
const test_step = b.step("test", "Run default test suite");
test_step.dependOn(&all_tests.step);
if(target.isNative()) {
var all_itests = b.addTest("src/integration_test.zig");
all_itests.setBuildMode(mode);
all_itests.setFilter("integration:"); // Run only tests prefixed with "integration:"
all_itests.linkSystemLibrary("c");
all_itests.linkSystemLibrary("libcurl");
const itest_step = b.step("itest", "Run default integration test suite");
itest_step.dependOn(&all_itests.step);
}
} | build.zig |
const combn = @import("combn.zig");
const Result = combn.gllparser.Result;
const Parser = combn.gllparser.Parser;
const Error = combn.gllparser.Error;
const Context = combn.gllparser.Context;
const PosKey = combn.gllparser.PosKey;
const ParserPath = combn.gllparser.ParserPath;
const Literal = combn.parser.Literal;
const LiteralValue = combn.parser.literal.Value;
const MapTo = combn.combinator.MapTo;
const Optional = combn.combinator.Optional;
const Reentrant = combn.combinator.Reentrant;
const SequenceAmbiguous = combn.combinator.SequenceAmbiguous;
const SequenceAmbiguousValue = combn.combinator.sequence_ambiguous.Value;
const std = @import("std");
const mem = std.mem;
const testing = std.testing;
// Confirms that a direct left-recursive grammar for an empty language actually rejects
// all input strings, and does not just hang indefinitely:
//
// ```ebnf
// Expr = Expr ;
// Grammar = Expr ;
// ```
//
// See https://cs.stackexchange.com/q/138447/134837
test "direct_left_recursion_empty_language" {
nosuspend {
const allocator = testing.allocator;
const node = struct {
name: []const u8,
pub fn deinit(self: *const @This(), _allocator: mem.Allocator) void {
_ = self;
_ = _allocator;
}
};
const Payload = void;
const ctx = try Context(Payload, node).init(allocator, "abcabcabc123abc", {});
defer ctx.deinit();
var parsers = [_]*Parser(Payload, node){
undefined, // placeholder for left-recursive Expr itself
};
var expr = try MapTo(Payload, SequenceAmbiguousValue(node), node).init(allocator, .{
.parser = (try SequenceAmbiguous(Payload, node).init(allocator, &parsers, .borrowed)).ref(),
.mapTo = struct {
fn mapTo(in: Result(SequenceAmbiguousValue(node)), payload: Payload, _allocator: mem.Allocator, key: PosKey, path: ParserPath) callconv(.Async) Error!?Result(node) {
_ = payload;
switch (in.result) {
.err => return Result(node).initError(in.offset, in.result.err),
else => {
var flattened = try in.result.value.flatten(_allocator, key, path);
defer flattened.deinit();
return Result(node).init(in.offset, node{ .name = "Expr" });
},
}
}
}.mapTo,
});
defer expr.deinit(allocator, null);
parsers[0] = expr.ref();
try expr.parse(&ctx);
var sub = ctx.subscribe();
var first = sub.next().?;
try testing.expect(sub.next() == null); // stream closed
// TODO(slimsag): perhaps better if it's not an error?
try testing.expectEqual(@as(usize, 0), first.offset);
try testing.expectEqualStrings("matches only the empty language", first.result.err);
}
}
// Confirms that a direct left-recursive grammar for a valid languages works:
//
// ```ebnf
// Expr = Expr?, "abc" ;
// Grammar = Expr ;
// ```
//
test "direct_left_recursion" {
const allocator = testing.allocator;
const node = struct {
name: std.ArrayList(u8),
pub fn deinit(self: *const @This(), _allocator: mem.Allocator) void {
_ = _allocator;
self.name.deinit();
}
};
const Payload = void;
const ctx = try Context(Payload, node).init(allocator, "abcabcabc123abc", {});
defer ctx.deinit();
var abcAsNode = try MapTo(Payload, LiteralValue, node).init(allocator, .{
.parser = (try Literal(Payload).init(allocator, "abc")).ref(),
.mapTo = struct {
fn mapTo(in: Result(LiteralValue), payload: Payload, _allocator: mem.Allocator, key: PosKey, path: ParserPath) callconv(.Async) Error!?Result(node) {
_ = _allocator;
_ = payload;
_ = key;
_ = path;
switch (in.result) {
.err => return Result(node).initError(in.offset, in.result.err),
else => {
var name = std.ArrayList(u8).init(_allocator);
try name.appendSlice("abc");
return Result(node).init(in.offset, node{ .name = name });
},
}
}
}.mapTo,
});
var parsers = [_]*Parser(Payload, node){
undefined, // placeholder for left-recursive Expr itself
abcAsNode.ref(),
};
var expr = try Reentrant(Payload, node).init(
allocator,
try MapTo(Payload, SequenceAmbiguousValue(node), node).init(allocator, .{
.parser = (try SequenceAmbiguous(Payload, node).init(allocator, &parsers, .borrowed)).ref(),
.mapTo = struct {
fn mapTo(in: Result(SequenceAmbiguousValue(node)), payload: Payload, _allocator: mem.Allocator, key: PosKey, path: ParserPath) callconv(.Async) Error!?Result(node) {
_ = payload;
switch (in.result) {
.err => return Result(node).initError(in.offset, in.result.err),
else => {
var name = std.ArrayList(u8).init(_allocator);
var flattened = try in.result.value.flatten(_allocator, key, path);
defer flattened.deinit();
var sub = flattened.subscribe(key, path, Result(node).initError(0, "matches only the empty language"));
try name.appendSlice("(");
var prev = false;
while (sub.next()) |next| {
if (prev) {
try name.appendSlice(",");
}
prev = true;
try name.appendSlice(next.result.value.name.items);
}
try name.appendSlice(")");
return Result(node).init(in.offset, node{ .name = name });
},
}
}
}.mapTo,
}),
);
var optionalExpr = try MapTo(Payload, ?node, node).init(allocator, .{
.parser = (try Optional(Payload, node).init(allocator, expr.ref())).ref(),
.mapTo = struct {
fn mapTo(in: Result(?node), payload: Payload, _allocator: mem.Allocator, key: PosKey, path: ParserPath) callconv(.Async) Error!?Result(node) {
_ = payload;
_ = key;
_ = path;
switch (in.result) {
.err => return Result(node).initError(in.offset, in.result.err),
else => {
if (in.result.value == null) {
var name = std.ArrayList(u8).init(_allocator);
try name.appendSlice("null");
return Result(node).init(in.offset, node{ .name = name });
}
var name = std.ArrayList(u8).init(_allocator);
try name.appendSlice(in.result.value.?.name.items);
return Result(node).init(in.offset, node{ .name = name });
},
}
}
}.mapTo,
});
parsers[0] = optionalExpr.ref();
defer expr.deinit(allocator, null);
try expr.parse(&ctx);
var sub = ctx.subscribe();
var first = sub.next().?;
try testing.expect(sub.next() == null); // stream closed
try testing.expectEqual(@as(usize, 0), first.offset);
try testing.expectEqualStrings("(((null,abc),abc),abc)", first.result.value.name.items);
} | src/combn/test_complex.zig |
const builtin = @import("builtin");
const std = @import("std");
const Builder = std.build.Builder;
var framework_dir: ?[]u8 = null;
const build_impl_type: enum { exe, static_lib, object_files } = .static_lib;
pub fn build(b: *std.build.Builder) !void {
const exe = b.addStaticLibrary("JunkLib", null);
linkArtifact(b, exe, b.standardTargetOptions(.{}), .static, "");
exe.install();
}
/// prefix_path is used to add package paths. It should be the the same path used to include this build file
pub fn linkArtifact(b: *Builder, exe: *std.build.LibExeObjStep, target: std.zig.CrossTarget, comptime prefix_path: []const u8) void {
if (prefix_path.len > 0 and !std.mem.endsWith(u8, prefix_path, "/")) @panic("prefix-path must end with '/' if it is not empty");
exe.addPackage(getImGuiPackage(prefix_path));
if (target.isWindows()) {
exe.linkSystemLibrary("user32");
exe.linkSystemLibrary("gdi32");
} else if (target.isDarwin()) {
const frameworks_dir = macosFrameworksDir(b) catch unreachable;
exe.addFrameworkDir(frameworks_dir);
exe.linkFramework("Foundation");
exe.linkFramework("Cocoa");
exe.linkFramework("Quartz");
exe.linkFramework("QuartzCore");
exe.linkFramework("Metal");
exe.linkFramework("MetalKit");
exe.linkFramework("OpenGL");
exe.linkFramework("Audiotoolbox");
exe.linkFramework("CoreAudio");
exe.linkSystemLibrary("c++");
} else {
exe.linkLibC();
exe.linkSystemLibrary("c++");
}
const base_path = prefix_path ++ "gamekit/deps/imgui/";
exe.addIncludeDir(base_path ++ "cimgui/imgui");
exe.addIncludeDir(base_path ++ "cimgui/imgui/examples");
const cpp_args = [_][]const u8{"-Wno-return-type-c-linkage"};
exe.addCSourceFile(base_path ++ "cimgui/imgui/imgui.cpp", &cpp_args);
exe.addCSourceFile(base_path ++ "cimgui/imgui/imgui_demo.cpp", &cpp_args);
exe.addCSourceFile(base_path ++ "cimgui/imgui/imgui_draw.cpp", &cpp_args);
exe.addCSourceFile(base_path ++ "cimgui/imgui/imgui_widgets.cpp", &cpp_args);
exe.addCSourceFile(base_path ++ "cimgui/cimgui.cpp", &cpp_args);
exe.addCSourceFile(base_path ++ "temporary_hacks.cpp", &cpp_args);
}
/// helper function to get SDK path on Mac
fn macosFrameworksDir(b: *Builder) ![]u8 {
if (framework_dir) |dir| return dir;
var str = try b.exec(&[_][]const u8{ "xcrun", "--show-sdk-path" });
const strip_newline = std.mem.lastIndexOf(u8, str, "\n");
if (strip_newline) |index| {
str = str[0..index];
}
framework_dir = try std.mem.concat(b.allocator, u8, &[_][]const u8{ str, "/System/Library/Frameworks" });
return framework_dir.?;
}
pub fn getImGuiPackage(comptime prefix_path: []const u8) std.build.Pkg {
if (prefix_path.len > 0 and !std.mem.endsWith(u8, prefix_path, "/")) @panic("prefix-path must end with '/' if it is not empty");
return .{
.name = "imgui",
.path = .{ .path = prefix_path ++ "gamekit/deps/imgui/imgui.zig" },
};
} | gamekit/deps/imgui/build.zig |
const std = @import("std");
// Returns true if the version includes https://github.com/ziglang/zig/pull/10572/commits.
// When this is false, trying to place the stack first will result in data corruption.
fn version_supports_stack_first(zig_version: std.SemanticVersion) !bool {
if (zig_version.order(try std.SemanticVersion.parse("0.10.0")).compare(.gte)) {
// Merged here: https://github.com/ziglang/zig/pull/10572
return true;
}
if (zig_version.major == 0 and zig_version.minor == 10) {
// Check for 0.10.0-dev.258+. Conservatively check the prefix of the tag
// in case zig uses other prefixes that don't respect semver ordering.
if (zig_version.pre) |pre| {
// Merged here: https://github.com/ziglang/zig/pull/10572
return std.mem.startsWith(u8, pre, "dev.") and zig_version.order(try std.SemanticVersion.parse("0.10.0-dev.258")).compare(.gte);
}
}
// Backported here: https://github.com/ziglang/zig/commit/6f49233ac6a6569b909b689f22fc260dc8c19234
return zig_version.order(try std.SemanticVersion.parse("0.9.1")).compare(.gte);
}
test "stack version check" {
const expect = std.testing.expect;
const parse = std.SemanticVersion.parse;
try expect(!try version_supports_stack_first(try parse("0.8.0")));
try expect(!try version_supports_stack_first(try parse("0.9.0")));
try expect(!try version_supports_stack_first(try parse("0.9.1-dev.259")));
try expect(try version_supports_stack_first(try parse("0.9.1")));
// Conservatively don't recognize tags other than 'dev'.
try expect(!try version_supports_stack_first(try parse("0.10.0-aev.259")));
try expect(!try version_supports_stack_first(try parse("0.10.0-zev.259")));
try expect(!try version_supports_stack_first(try parse("0.10.0-dev.257")));
try expect(try version_supports_stack_first(try parse("0.10.0-dev.258")));
try expect(try version_supports_stack_first(try parse("0.10.0-dev.259")));
try expect(try version_supports_stack_first(try parse("0.10.0")));
try expect(try version_supports_stack_first(try parse("0.10.1-dev.100")));
try expect(try version_supports_stack_first(try parse("0.10.1-dev.300")));
try expect(try version_supports_stack_first(try parse("0.10.1")));
try expect(try version_supports_stack_first(try parse("1.0.0")));
}
pub fn build(b: *std.build.Builder) !void {
const zig_version = @import("builtin").zig_version;
const mode = b.standardReleaseOptions();
const lib = b.addSharedLibrary("cart", "src/main.zig", .unversioned);
lib.setBuildMode(mode);
lib.setTarget(.{ .cpu_arch = .wasm32, .os_tag = .freestanding });
lib.import_memory = true;
lib.initial_memory = 65536;
lib.max_memory = 65536;
if (try version_supports_stack_first(zig_version)) {
lib.stack_size = 14752;
} else {
// `--stack-first` option have been reenabled on wasm targets with https://github.com/ziglang/zig/pull/10572
std.log.warn("Update to Zig >=0.9.1 (or >=0.10.0-dev.258 for nightly) to detect stack overflows at runtime.", .{});
lib.global_base = 6560;
lib.stack_size = 8192;
}
// Workaround https://github.com/ziglang/zig/issues/2910, preventing
// functions from compiler_rt getting incorrectly marked as exported, which
// prevents them from being removed even if unused.
lib.export_symbol_names = &[_][]const u8{ "start", "update" };
lib.install();
} | cli/assets/templates/zig/build.zig |
const std = @import("std");
const builtin = @import("builtin");
const os = std.os;
const io = std.io;
const mem = std.mem;
const Allocator = mem.Allocator;
const ArrayList = std.ArrayList;
const Buffer = std.Buffer;
const arg = @import("arg.zig");
const c = @import("c.zig");
const introspect = @import("introspect.zig");
const Args = arg.Args;
const Flag = arg.Flag;
const Module = @import("module.zig").Module;
const Target = @import("target.zig").Target;
var stderr: &io.OutStream(io.FileOutStream.Error) = undefined;
var stdout: &io.OutStream(io.FileOutStream.Error) = undefined;
const usage =
\\usage: zig [command] [options]
\\
\\Commands:
\\
\\ build Build project from build.zig
\\ build-exe [source] Create executable from source or object files
\\ build-lib [source] Create library from source or object files
\\ build-obj [source] Create object from source or assembly
\\ fmt [source] Parse file and render in canonical zig format
\\ run [source] Create executable and run immediately
\\ targets List available compilation targets
\\ test [source] Create and run a test build
\\ translate-c [source] Convert c code to zig code
\\ version Print version number and exit
\\ zen Print zen of zig and exit
\\
\\
;
const Command = struct {
name: []const u8,
exec: fn(&Allocator, []const []const u8) error!void,
};
pub fn main() !void {
var allocator = std.heap.c_allocator;
var stdout_file = try std.io.getStdOut();
var stdout_out_stream = std.io.FileOutStream.init(&stdout_file);
stdout = &stdout_out_stream.stream;
var stderr_file = try std.io.getStdErr();
var stderr_out_stream = std.io.FileOutStream.init(&stderr_file);
stderr = &stderr_out_stream.stream;
const args = try os.argsAlloc(allocator);
defer os.argsFree(allocator, args);
if (args.len <= 1) {
try stderr.write(usage);
os.exit(1);
}
const commands = []Command {
Command { .name = "build", .exec = cmdBuild },
Command { .name = "build-exe", .exec = cmdBuildExe },
Command { .name = "build-lib", .exec = cmdBuildLib },
Command { .name = "build-obj", .exec = cmdBuildObj },
Command { .name = "fmt", .exec = cmdFmt },
Command { .name = "run", .exec = cmdRun },
Command { .name = "targets", .exec = cmdTargets },
Command { .name = "test", .exec = cmdTest },
Command { .name = "translate-c", .exec = cmdTranslateC },
Command { .name = "version", .exec = cmdVersion },
Command { .name = "zen", .exec = cmdZen },
// undocumented commands
Command { .name = "help", .exec = cmdHelp },
Command { .name = "internal", .exec = cmdInternal },
};
for (commands) |command| {
if (mem.eql(u8, command.name, args[1])) {
try command.exec(allocator, args[2..]);
return;
}
}
try stderr.print("unknown command: {}\n\n", args[1]);
try stderr.write(usage);
}
// cmd:build ///////////////////////////////////////////////////////////////////////////////////////
const usage_build =
\\usage: zig build <options>
\\
\\General Options:
\\ --help Print this help and exit
\\ --init Generate a build.zig template
\\ --build-file [file] Override path to build.zig
\\ --cache-dir [path] Override path to cache directory
\\ --verbose Print commands before executing them
\\ --prefix [path] Override default install prefix
\\
\\Project-Specific Options:
\\
\\ Project-specific options become available when the build file is found.
\\
\\Advanced Options:
\\ --build-file [file] Override path to build.zig
\\ --cache-dir [path] Override path to cache directory
\\ --verbose-tokenize Enable compiler debug output for tokenization
\\ --verbose-ast Enable compiler debug output for parsing into an AST
\\ --verbose-link Enable compiler debug output for linking
\\ --verbose-ir Enable compiler debug output for Zig IR
\\ --verbose-llvm-ir Enable compiler debug output for LLVM IR
\\ --verbose-cimport Enable compiler debug output for C imports
\\
\\
;
const args_build_spec = []Flag {
Flag.Bool("--help"),
Flag.Bool("--init"),
Flag.Arg1("--build-file"),
Flag.Arg1("--cache-dir"),
Flag.Bool("--verbose"),
Flag.Arg1("--prefix"),
Flag.Arg1("--build-file"),
Flag.Arg1("--cache-dir"),
Flag.Bool("--verbose-tokenize"),
Flag.Bool("--verbose-ast"),
Flag.Bool("--verbose-link"),
Flag.Bool("--verbose-ir"),
Flag.Bool("--verbose-llvm-ir"),
Flag.Bool("--verbose-cimport"),
};
const missing_build_file =
\\No 'build.zig' file found.
\\
\\Initialize a 'build.zig' template file with `zig build --init`,
\\or build an executable directly with `zig build-exe $FILENAME.zig`.
\\
\\See: `zig build --help` or `zig help` for more options.
\\
;
fn cmdBuild(allocator: &Allocator, args: []const []const u8) !void {
var flags = try Args.parse(allocator, args_build_spec, args);
defer flags.deinit();
if (flags.present("help")) {
try stderr.write(usage_build);
os.exit(0);
}
const zig_lib_dir = try introspect.resolveZigLibDir(allocator);
defer allocator.free(zig_lib_dir);
const zig_std_dir = try os.path.join(allocator, zig_lib_dir, "std");
defer allocator.free(zig_std_dir);
const special_dir = try os.path.join(allocator, zig_std_dir, "special");
defer allocator.free(special_dir);
const build_runner_path = try os.path.join(allocator, special_dir, "build_runner.zig");
defer allocator.free(build_runner_path);
const build_file = flags.single("build-file") ?? "build.zig";
const build_file_abs = try os.path.resolve(allocator, ".", build_file);
defer allocator.free(build_file_abs);
const build_file_exists = os.File.access(allocator, build_file_abs, os.default_file_mode) catch false;
if (flags.present("init")) {
if (build_file_exists) {
try stderr.print("build.zig already exists\n");
os.exit(1);
}
// need a new scope for proper defer scope finalization on exit
{
const build_template_path = try os.path.join(allocator, special_dir, "build_file_template.zig");
defer allocator.free(build_template_path);
try os.copyFile(allocator, build_template_path, build_file_abs);
try stderr.print("wrote build.zig template\n");
}
os.exit(0);
}
if (!build_file_exists) {
try stderr.write(missing_build_file);
os.exit(1);
}
// TODO: Invoke build.zig entrypoint directly?
var zig_exe_path = try os.selfExePath(allocator);
defer allocator.free(zig_exe_path);
var build_args = ArrayList([]const u8).init(allocator);
defer build_args.deinit();
const build_file_basename = os.path.basename(build_file_abs);
const build_file_dirname = os.path.dirname(build_file_abs);
var full_cache_dir: []u8 = undefined;
if (flags.single("cache-dir")) |cache_dir| {
full_cache_dir = try os.path.resolve(allocator, ".", cache_dir, full_cache_dir);
} else {
full_cache_dir = try os.path.join(allocator, build_file_dirname, "zig-cache");
}
defer allocator.free(full_cache_dir);
const path_to_build_exe = try os.path.join(allocator, full_cache_dir, "build");
defer allocator.free(path_to_build_exe);
try build_args.append(path_to_build_exe);
try build_args.append(zig_exe_path);
try build_args.append(build_file_dirname);
try build_args.append(full_cache_dir);
var proc = try os.ChildProcess.init(build_args.toSliceConst(), allocator);
defer proc.deinit();
var term = try proc.spawnAndWait();
switch (term) {
os.ChildProcess.Term.Exited => |status| {
if (status != 0) {
try stderr.print("{} exited with status {}\n", build_args.at(0), status);
os.exit(1);
}
},
os.ChildProcess.Term.Signal => |signal| {
try stderr.print("{} killed by signal {}\n", build_args.at(0), signal);
os.exit(1);
},
os.ChildProcess.Term.Stopped => |signal| {
try stderr.print("{} stopped by signal {}\n", build_args.at(0), signal);
os.exit(1);
},
os.ChildProcess.Term.Unknown => |status| {
try stderr.print("{} encountered unknown failure {}\n", build_args.at(0), status);
os.exit(1);
},
}
}
// cmd:build-exe ///////////////////////////////////////////////////////////////////////////////////
const usage_build_generic =
\\usage: zig build-exe <options> [file]
\\ zig build-lib <options> [file]
\\ zig build-obj <options> [file]
\\
\\General Options:
\\ --help Print this help and exit
\\ --color [auto|off|on] Enable or disable colored error messages
\\
\\Compile Options:
\\ --assembly [source] Add assembly file to build
\\ --cache-dir [path] Override the cache directory
\\ --emit [filetype] Emit a specific file format as compilation output
\\ --enable-timing-info Print timing diagnostics
\\ --libc-include-dir [path] Directory where libc stdlib.h resides
\\ --name [name] Override output name
\\ --output [file] Override destination path
\\ --output-h [file] Override generated header file path
\\ --pkg-begin [name] [path] Make package available to import and push current pkg
\\ --pkg-end Pop current pkg
\\ --release-fast Build with optimizations on and safety off
\\ --release-safe Build with optimizations on and safety on
\\ --static Output will be statically linked
\\ --strip Exclude debug symbols
\\ --target-arch [name] Specify target architecture
\\ --target-environ [name] Specify target environment
\\ --target-os [name] Specify target operating system
\\ --verbose-tokenize Turn on compiler debug output for tokenization
\\ --verbose-ast-tree Turn on compiler debug output for parsing into an AST (tree view)
\\ --verbose-ast-fmt Turn on compiler debug output for parsing into an AST (render source)
\\ --verbose-link Turn on compiler debug output for linking
\\ --verbose-ir Turn on compiler debug output for Zig IR
\\ --verbose-llvm-ir Turn on compiler debug output for LLVM IR
\\ --verbose-cimport Turn on compiler debug output for C imports
\\ -dirafter [dir] Same as -isystem but do it last
\\ -isystem [dir] Add additional search path for other .h files
\\ -mllvm [arg] Additional arguments to forward to LLVM's option processing
\\
\\Link Options:
\\ --ar-path [path] Set the path to ar
\\ --dynamic-linker [path] Set the path to ld.so
\\ --each-lib-rpath Add rpath for each used dynamic library
\\ --libc-lib-dir [path] Directory where libc crt1.o resides
\\ --libc-static-lib-dir [path] Directory where libc crtbegin.o resides
\\ --msvc-lib-dir [path] (windows) directory where vcruntime.lib resides
\\ --kernel32-lib-dir [path] (windows) directory where kernel32.lib resides
\\ --library [lib] Link against lib
\\ --forbid-library [lib] Make it an error to link against lib
\\ --library-path [dir] Add a directory to the library search path
\\ --linker-script [path] Use a custom linker script
\\ --object [obj] Add object file to build
\\ -rdynamic Add all symbols to the dynamic symbol table
\\ -rpath [path] Add directory to the runtime library search path
\\ -mconsole (windows) --subsystem console to the linker
\\ -mwindows (windows) --subsystem windows to the linker
\\ -framework [name] (darwin) link against framework
\\ -mios-version-min [ver] (darwin) set iOS deployment target
\\ -mmacosx-version-min [ver] (darwin) set Mac OS X deployment target
\\ --ver-major [ver] Dynamic library semver major version
\\ --ver-minor [ver] Dynamic library semver minor version
\\ --ver-patch [ver] Dynamic library semver patch version
\\
\\
;
const args_build_generic = []Flag {
Flag.Bool("--help"),
Flag.Option("--color", []const []const u8 { "auto", "off", "on" }),
Flag.ArgMergeN("--assembly", 1),
Flag.Arg1("--cache-dir"),
Flag.Option("--emit", []const []const u8 { "asm", "bin", "llvm-ir" }),
Flag.Bool("--enable-timing-info"),
Flag.Arg1("--libc-include-dir"),
Flag.Arg1("--name"),
Flag.Arg1("--output"),
Flag.Arg1("--output-h"),
// NOTE: Parsed manually after initial check
Flag.ArgN("--pkg-begin", 2),
Flag.Bool("--pkg-end"),
Flag.Bool("--release-fast"),
Flag.Bool("--release-safe"),
Flag.Bool("--static"),
Flag.Bool("--strip"),
Flag.Arg1("--target-arch"),
Flag.Arg1("--target-environ"),
Flag.Arg1("--target-os"),
Flag.Bool("--verbose-tokenize"),
Flag.Bool("--verbose-ast-tree"),
Flag.Bool("--verbose-ast-fmt"),
Flag.Bool("--verbose-link"),
Flag.Bool("--verbose-ir"),
Flag.Bool("--verbose-llvm-ir"),
Flag.Bool("--verbose-cimport"),
Flag.Arg1("-dirafter"),
Flag.ArgMergeN("-isystem", 1),
Flag.Arg1("-mllvm"),
Flag.Arg1("--ar-path"),
Flag.Arg1("--dynamic-linker"),
Flag.Bool("--each-lib-rpath"),
Flag.Arg1("--libc-lib-dir"),
Flag.Arg1("--libc-static-lib-dir"),
Flag.Arg1("--msvc-lib-dir"),
Flag.Arg1("--kernel32-lib-dir"),
Flag.ArgMergeN("--library", 1),
Flag.ArgMergeN("--forbid-library", 1),
Flag.ArgMergeN("--library-path", 1),
Flag.Arg1("--linker-script"),
Flag.ArgMergeN("--object", 1),
// NOTE: Removed -L since it would need to be special-cased and we have an alias in library-path
Flag.Bool("-rdynamic"),
Flag.Arg1("-rpath"),
Flag.Bool("-mconsole"),
Flag.Bool("-mwindows"),
Flag.ArgMergeN("-framework", 1),
Flag.Arg1("-mios-version-min"),
Flag.Arg1("-mmacosx-version-min"),
Flag.Arg1("--ver-major"),
Flag.Arg1("--ver-minor"),
Flag.Arg1("--ver-patch"),
};
fn buildOutputType(allocator: &Allocator, args: []const []const u8, out_type: Module.Kind) !void {
var flags = try Args.parse(allocator, args_build_generic, args);
defer flags.deinit();
if (flags.present("help")) {
try stderr.write(usage_build_generic);
os.exit(0);
}
var build_mode = builtin.Mode.Debug;
if (flags.present("release-fast")) {
build_mode = builtin.Mode.ReleaseFast;
} else if (flags.present("release-safe")) {
build_mode = builtin.Mode.ReleaseSafe;
}
var color = Module.ErrColor.Auto;
if (flags.single("color")) |color_flag| {
if (mem.eql(u8, color_flag, "auto")) {
color = Module.ErrColor.Auto;
} else if (mem.eql(u8, color_flag, "on")) {
color = Module.ErrColor.On;
} else if (mem.eql(u8, color_flag, "off")) {
color = Module.ErrColor.Off;
} else {
unreachable;
}
}
var emit_type = Module.Emit.Binary;
if (flags.single("emit")) |emit_flag| {
if (mem.eql(u8, emit_flag, "asm")) {
emit_type = Module.Emit.Assembly;
} else if (mem.eql(u8, emit_flag, "bin")) {
emit_type = Module.Emit.Binary;
} else if (mem.eql(u8, emit_flag, "llvm-ir")) {
emit_type = Module.Emit.LlvmIr;
} else {
unreachable;
}
}
var cur_pkg = try Module.CliPkg.init(allocator, "", "", null); // TODO: Need a path, name?
defer cur_pkg.deinit();
var i: usize = 0;
while (i < args.len) : (i += 1) {
const arg_name = args[i];
if (mem.eql(u8, "--pkg-begin", arg_name)) {
// following two arguments guaranteed to exist due to arg parsing
i += 1;
const new_pkg_name = args[i];
i += 1;
const new_pkg_path = args[i];
var new_cur_pkg = try Module.CliPkg.init(allocator, new_pkg_name, new_pkg_path, cur_pkg);
try cur_pkg.children.append(new_cur_pkg);
cur_pkg = new_cur_pkg;
} else if (mem.eql(u8, "--pkg-end", arg_name)) {
if (cur_pkg.parent == null) {
try stderr.print("encountered --pkg-end with no matching --pkg-begin\n");
os.exit(1);
}
cur_pkg = ??cur_pkg.parent;
}
}
if (cur_pkg.parent != null) {
try stderr.print("unmatched --pkg-begin\n");
os.exit(1);
}
var in_file: ?[]const u8 = undefined;
switch (flags.positionals.len) {
0 => {
try stderr.write("--name [name] not provided and unable to infer\n");
os.exit(1);
},
1 => {
in_file = flags.positionals.at(0);
},
else => {
try stderr.write("only one zig input file is accepted during build\n");
os.exit(1);
},
}
const basename = os.path.basename(??in_file);
var it = mem.split(basename, ".");
const root_name = it.next() ?? {
try stderr.write("file name cannot be empty\n");
os.exit(1);
};
const asm_a= flags.many("assembly");
const obj_a = flags.many("object");
if (in_file == null and (obj_a == null or (??obj_a).len == 0) and (asm_a == null or (??asm_a).len == 0)) {
try stderr.write("Expected source file argument or at least one --object or --assembly argument\n");
os.exit(1);
}
if (out_type == Module.Kind.Obj and (obj_a != null and (??obj_a).len != 0)) {
try stderr.write("When building an object file, --object arguments are invalid\n");
os.exit(1);
}
const zig_root_source_file = in_file;
const full_cache_dir = os.path.resolve(allocator, ".", flags.single("cache-dir") ?? "zig-cache"[0..]) catch {
os.exit(1);
};
defer allocator.free(full_cache_dir);
const zig_lib_dir = introspect.resolveZigLibDir(allocator) catch os.exit(1);
defer allocator.free(zig_lib_dir);
var module =
try Module.create(
allocator,
root_name,
zig_root_source_file,
Target.Native,
out_type,
build_mode,
zig_lib_dir,
full_cache_dir
);
defer module.destroy();
module.version_major = try std.fmt.parseUnsigned(u32, flags.single("ver-major") ?? "0", 10);
module.version_minor = try std.fmt.parseUnsigned(u32, flags.single("ver-minor") ?? "0", 10);
module.version_patch = try std.fmt.parseUnsigned(u32, flags.single("ver-patch") ?? "0", 10);
module.is_test = false;
if (flags.single("linker-script")) |linker_script| {
module.linker_script = linker_script;
}
module.each_lib_rpath = flags.present("each-lib-rpath");
var clang_argv_buf = ArrayList([]const u8).init(allocator);
defer clang_argv_buf.deinit();
if (flags.many("mllvm")) |mllvm_flags| {
for (mllvm_flags) |mllvm| {
try clang_argv_buf.append("-mllvm");
try clang_argv_buf.append(mllvm);
}
module.llvm_argv = mllvm_flags;
module.clang_argv = clang_argv_buf.toSliceConst();
}
module.strip = flags.present("strip");
module.is_static = flags.present("static");
if (flags.single("libc-lib-dir")) |libc_lib_dir| {
module.libc_lib_dir = libc_lib_dir;
}
if (flags.single("libc-static-lib-dir")) |libc_static_lib_dir| {
module.libc_static_lib_dir = libc_static_lib_dir;
}
if (flags.single("libc-include-dir")) |libc_include_dir| {
module.libc_include_dir = libc_include_dir;
}
if (flags.single("msvc-lib-dir")) |msvc_lib_dir| {
module.msvc_lib_dir = msvc_lib_dir;
}
if (flags.single("kernel32-lib-dir")) |kernel32_lib_dir| {
module.kernel32_lib_dir = kernel32_lib_dir;
}
if (flags.single("dynamic-linker")) |dynamic_linker| {
module.dynamic_linker = dynamic_linker;
}
module.verbose_tokenize = flags.present("verbose-tokenize");
module.verbose_ast_tree = flags.present("verbose-ast-tree");
module.verbose_ast_fmt = flags.present("verbose-ast-fmt");
module.verbose_link = flags.present("verbose-link");
module.verbose_ir = flags.present("verbose-ir");
module.verbose_llvm_ir = flags.present("verbose-llvm-ir");
module.verbose_cimport = flags.present("verbose-cimport");
module.err_color = color;
if (flags.many("library-path")) |lib_dirs| {
module.lib_dirs = lib_dirs;
}
if (flags.many("framework")) |frameworks| {
module.darwin_frameworks = frameworks;
}
if (flags.many("rpath")) |rpath_list| {
module.rpath_list = rpath_list;
}
if (flags.single("output-h")) |output_h| {
module.out_h_path = output_h;
}
module.windows_subsystem_windows = flags.present("mwindows");
module.windows_subsystem_console = flags.present("mconsole");
module.linker_rdynamic = flags.present("rdynamic");
if (flags.single("mmacosx-version-min") != null and flags.single("mios-version-min") != null) {
try stderr.write("-mmacosx-version-min and -mios-version-min options not allowed together\n");
os.exit(1);
}
if (flags.single("mmacosx-version-min")) |ver| {
module.darwin_version_min = Module.DarwinVersionMin { .MacOS = ver };
}
if (flags.single("mios-version-min")) |ver| {
module.darwin_version_min = Module.DarwinVersionMin { .Ios = ver };
}
module.emit_file_type = emit_type;
if (flags.many("object")) |objects| {
module.link_objects = objects;
}
if (flags.many("assembly")) |assembly_files| {
module.assembly_files = assembly_files;
}
try module.build();
try module.link(flags.single("out-file") ?? null);
if (flags.present("print-timing-info")) {
// codegen_print_timing_info(g, stderr);
}
try stderr.print("building {}: {}\n", @tagName(out_type), in_file);
}
fn cmdBuildExe(allocator: &Allocator, args: []const []const u8) !void {
try buildOutputType(allocator, args, Module.Kind.Exe);
}
// cmd:build-lib ///////////////////////////////////////////////////////////////////////////////////
fn cmdBuildLib(allocator: &Allocator, args: []const []const u8) !void {
try buildOutputType(allocator, args, Module.Kind.Lib);
}
// cmd:build-obj ///////////////////////////////////////////////////////////////////////////////////
fn cmdBuildObj(allocator: &Allocator, args: []const []const u8) !void {
try buildOutputType(allocator, args, Module.Kind.Obj);
}
// cmd:fmt /////////////////////////////////////////////////////////////////////////////////////////
const usage_fmt =
\\usage: zig fmt [file]...
\\
\\ Formats the input files and modifies them in-place.
\\
\\Options:
\\ --help Print this help and exit
\\ --keep-backups Retain backup entries for every file
\\
\\
;
const args_fmt_spec = []Flag {
Flag.Bool("--help"),
Flag.Bool("--keep-backups"),
};
fn cmdFmt(allocator: &Allocator, args: []const []const u8) !void {
var flags = try Args.parse(allocator, args_fmt_spec, args);
defer flags.deinit();
if (flags.present("help")) {
try stderr.write(usage_fmt);
os.exit(0);
}
if (flags.positionals.len == 0) {
try stderr.write("expected at least one source file argument\n");
os.exit(1);
}
for (flags.positionals.toSliceConst()) |file_path| {
var file = try os.File.openRead(allocator, file_path);
defer file.close();
const source_code = io.readFileAlloc(allocator, file_path) catch |err| {
try stderr.print("unable to open '{}': {}", file_path, err);
continue;
};
defer allocator.free(source_code);
var tokenizer = std.zig.Tokenizer.init(source_code);
var parser = std.zig.Parser.init(&tokenizer, allocator, file_path);
defer parser.deinit();
var tree = parser.parse() catch |err| {
try stderr.print("error parsing file '{}': {}\n", file_path, err);
continue;
};
defer tree.deinit();
var original_file_backup = try Buffer.init(allocator, file_path);
defer original_file_backup.deinit();
try original_file_backup.append(".backup");
try os.rename(allocator, file_path, original_file_backup.toSliceConst());
try stderr.print("{}\n", file_path);
// TODO: BufferedAtomicFile has some access problems.
var out_file = try os.File.openWrite(allocator, file_path);
defer out_file.close();
var out_file_stream = io.FileOutStream.init(&out_file);
try parser.renderSource(out_file_stream.stream, tree.root_node);
if (!flags.present("keep-backups")) {
try os.deleteFile(allocator, original_file_backup.toSliceConst());
}
}
}
// cmd:targets /////////////////////////////////////////////////////////////////////////////////////
fn cmdTargets(allocator: &Allocator, args: []const []const u8) !void {
try stdout.write("Architectures:\n");
{
comptime var i: usize = 0;
inline while (i < @memberCount(builtin.Arch)) : (i += 1) {
comptime const arch_tag = @memberName(builtin.Arch, i);
// NOTE: Cannot use empty string, see #918.
comptime const native_str =
if (comptime mem.eql(u8, arch_tag, @tagName(builtin.arch))) " (native)\n" else "\n";
try stdout.print(" {}{}", arch_tag, native_str);
}
}
try stdout.write("\n");
try stdout.write("Operating Systems:\n");
{
comptime var i: usize = 0;
inline while (i < @memberCount(builtin.Os)) : (i += 1) {
comptime const os_tag = @memberName(builtin.Os, i);
// NOTE: Cannot use empty string, see #918.
comptime const native_str =
if (comptime mem.eql(u8, os_tag, @tagName(builtin.os))) " (native)\n" else "\n";
try stdout.print(" {}{}", os_tag, native_str);
}
}
try stdout.write("\n");
try stdout.write("Environments:\n");
{
comptime var i: usize = 0;
inline while (i < @memberCount(builtin.Environ)) : (i += 1) {
comptime const environ_tag = @memberName(builtin.Environ, i);
// NOTE: Cannot use empty string, see #918.
comptime const native_str =
if (comptime mem.eql(u8, environ_tag, @tagName(builtin.environ))) " (native)\n" else "\n";
try stdout.print(" {}{}", environ_tag, native_str);
}
}
}
// cmd:version /////////////////////////////////////////////////////////////////////////////////////
fn cmdVersion(allocator: &Allocator, args: []const []const u8) !void {
try stdout.print("{}\n", std.cstr.toSliceConst(c.ZIG_VERSION_STRING));
}
// cmd:test ////////////////////////////////////////////////////////////////////////////////////////
const usage_test =
\\usage: zig test [file]...
\\
\\Options:
\\ --help Print this help and exit
\\
\\
;
const args_test_spec = []Flag {
Flag.Bool("--help"),
};
fn cmdTest(allocator: &Allocator, args: []const []const u8) !void {
var flags = try Args.parse(allocator, args_build_spec, args);
defer flags.deinit();
if (flags.present("help")) {
try stderr.write(usage_test);
os.exit(0);
}
if (flags.positionals.len != 1) {
try stderr.write("expected exactly one zig source file\n");
os.exit(1);
}
// compile the test program into the cache and run
// NOTE: May be overlap with buildOutput, take the shared part out.
try stderr.print("testing file {}\n", flags.positionals.at(0));
}
// cmd:run /////////////////////////////////////////////////////////////////////////////////////////
// Run should be simple and not expose the full set of arguments provided by build-exe. If specific
// build requirements are need, the user should `build-exe` then `run` manually.
const usage_run =
\\usage: zig run [file] -- <runtime args>
\\
\\Options:
\\ --help Print this help and exit
\\
\\
;
const args_run_spec = []Flag {
Flag.Bool("--help"),
};
fn cmdRun(allocator: &Allocator, args: []const []const u8) !void {
var compile_args = args;
var runtime_args: []const []const u8 = []const []const u8 {};
for (args) |argv, i| {
if (mem.eql(u8, argv, "--")) {
compile_args = args[0..i];
runtime_args = args[i+1..];
break;
}
}
var flags = try Args.parse(allocator, args_run_spec, compile_args);
defer flags.deinit();
if (flags.present("help")) {
try stderr.write(usage_run);
os.exit(0);
}
if (flags.positionals.len != 1) {
try stderr.write("expected exactly one zig source file\n");
os.exit(1);
}
try stderr.print("runtime args:\n");
for (runtime_args) |cargs| {
try stderr.print("{}\n", cargs);
}
}
// cmd:translate-c /////////////////////////////////////////////////////////////////////////////////
const usage_translate_c =
\\usage: zig translate-c [file]
\\
\\Options:
\\ --help Print this help and exit
\\ --enable-timing-info Print timing diagnostics
\\ --output [path] Output file to write generated zig file (default: stdout)
\\
\\
;
const args_translate_c_spec = []Flag {
Flag.Bool("--help"),
Flag.Bool("--enable-timing-info"),
Flag.Arg1("--libc-include-dir"),
Flag.Arg1("--output"),
};
fn cmdTranslateC(allocator: &Allocator, args: []const []const u8) !void {
var flags = try Args.parse(allocator, args_translate_c_spec, args);
defer flags.deinit();
if (flags.present("help")) {
try stderr.write(usage_translate_c);
os.exit(0);
}
if (flags.positionals.len != 1) {
try stderr.write("expected exactly one c source file\n");
os.exit(1);
}
// set up codegen
const zig_root_source_file = null;
// NOTE: translate-c shouldn't require setting up the full codegen instance as it does in
// the C++ compiler.
// codegen_create(g);
// codegen_set_out_name(g, null);
// codegen_translate_c(g, flags.positional.at(0))
var output_stream = stdout;
if (flags.single("output")) |output_file| {
var file = try os.File.openWrite(allocator, output_file);
defer file.close();
var file_stream = io.FileOutStream.init(&file);
// TODO: Not being set correctly, still stdout
output_stream = &file_stream.stream;
}
// ast_render(g, output_stream, g->root_import->root, 4);
try output_stream.write("pub const example = 10;\n");
if (flags.present("enable-timing-info")) {
// codegen_print_timing_info(g, stdout);
try stderr.write("printing timing info for translate-c\n");
}
}
// cmd:help ////////////////////////////////////////////////////////////////////////////////////////
fn cmdHelp(allocator: &Allocator, args: []const []const u8) !void {
try stderr.write(usage);
}
// cmd:zen /////////////////////////////////////////////////////////////////////////////////////////
const info_zen =
\\
\\ * Communicate intent precisely.
\\ * Edge cases matter.
\\ * Favor reading code over writing code.
\\ * Only one obvious way to do things.
\\ * Runtime crashes are better than bugs.
\\ * Compile errors are better than runtime crashes.
\\ * Incremental improvements.
\\ * Avoid local maximums.
\\ * Reduce the amount one must remember.
\\ * Minimize energy spent on coding style.
\\ * Together we serve end users.
\\
\\
;
fn cmdZen(allocator: &Allocator, args: []const []const u8) !void {
try stdout.write(info_zen);
}
// cmd:internal ////////////////////////////////////////////////////////////////////////////////////
const usage_internal =
\\usage: zig internal [subcommand]
\\
\\Sub-Commands:
\\ build-info Print static compiler build-info
\\
\\
;
fn cmdInternal(allocator: &Allocator, args: []const []const u8) !void {
if (args.len == 0) {
try stderr.write(usage_internal);
os.exit(1);
}
const sub_commands = []Command {
Command { .name = "build-info", .exec = cmdInternalBuildInfo },
};
for (sub_commands) |sub_command| {
if (mem.eql(u8, sub_command.name, args[0])) {
try sub_command.exec(allocator, args[1..]);
return;
}
}
try stderr.print("unknown sub command: {}\n\n", args[0]);
try stderr.write(usage_internal);
}
fn cmdInternalBuildInfo(allocator: &Allocator, args: []const []const u8) !void {
try stdout.print(
\\ZIG_CMAKE_BINARY_DIR {}
\\ZIG_CXX_COMPILER {}
\\ZIG_LLVM_CONFIG_EXE {}
\\ZIG_LLD_INCLUDE_PATH {}
\\ZIG_LLD_LIBRARIES {}
\\ZIG_STD_FILES {}
\\ZIG_C_HEADER_FILES {}
\\ZIG_DIA_GUIDS_LIB {}
\\
,
std.cstr.toSliceConst(c.ZIG_CMAKE_BINARY_DIR),
std.cstr.toSliceConst(c.ZIG_CXX_COMPILER),
std.cstr.toSliceConst(c.ZIG_LLVM_CONFIG_EXE),
std.cstr.toSliceConst(c.ZIG_LLD_INCLUDE_PATH),
std.cstr.toSliceConst(c.ZIG_LLD_LIBRARIES),
std.cstr.toSliceConst(c.ZIG_STD_FILES),
std.cstr.toSliceConst(c.ZIG_C_HEADER_FILES),
std.cstr.toSliceConst(c.ZIG_DIA_GUIDS_LIB),
);
} | src-self-hosted/main.zig |
const std = @import("std");
const zang = @import("../zang.zig");
const Source = @import("tokenize.zig").Source;
const BuiltinPackage = @import("builtins.zig").BuiltinPackage;
const BuiltinEnumValue = @import("builtins.zig").BuiltinEnumValue;
const ParamType = @import("parse.zig").ParamType;
const ModuleParam = @import("parse.zig").ModuleParam;
const ParseResult = @import("parse.zig").ParseResult;
const CodeGenResult = @import("codegen.zig").CodeGenResult;
const BufferDest = @import("codegen.zig").BufferDest;
const ExpressionResult = @import("codegen.zig").ExpressionResult;
const InstrCopyBuffer = @import("codegen.zig").InstrCopyBuffer;
const InstrFloatToBuffer = @import("codegen.zig").InstrFloatToBuffer;
const InstrCobToBuffer = @import("codegen.zig").InstrCobToBuffer;
const InstrArithFloat = @import("codegen.zig").InstrArithFloat;
const InstrArithBuffer = @import("codegen.zig").InstrArithBuffer;
const InstrArithFloatFloat = @import("codegen.zig").InstrArithFloatFloat;
const InstrArithFloatBuffer = @import("codegen.zig").InstrArithFloatBuffer;
const InstrArithBufferFloat = @import("codegen.zig").InstrArithBufferFloat;
const InstrArithBufferBuffer = @import("codegen.zig").InstrArithBufferBuffer;
const InstrCall = @import("codegen.zig").InstrCall;
const InstrTrackCall = @import("codegen.zig").InstrTrackCall;
const InstrDelay = @import("codegen.zig").InstrDelay;
const Instruction = @import("codegen.zig").Instruction;
const CodeGenCustomModuleInner = @import("codegen.zig").CodeGenCustomModuleInner;
const CompiledScript = @import("compile.zig").CompiledScript;
pub const Value = union(enum) {
constant: f32,
buffer: []const f32,
cob: zang.ConstantOrBuffer,
boolean: bool,
curve: []const zang.CurveNode,
one_of: struct { label: []const u8, payload: ?f32 },
// turn a Value into a zig value
pub fn toZig(value: Value, comptime P: type) P {
switch (P) {
bool => switch (value) {
.boolean => |v| return v,
else => unreachable,
},
f32 => switch (value) {
.constant => |v| return v,
else => unreachable,
},
[]const f32 => switch (value) {
.buffer => |v| return v,
else => unreachable,
},
zang.ConstantOrBuffer => switch (value) {
.cob => |v| return v,
else => unreachable,
},
[]const zang.CurveNode => switch (value) {
.curve => |v| return v,
else => unreachable,
},
else => switch (@typeInfo(P)) {
.Enum => |enum_info| {
switch (value) {
.one_of => |v| {
inline for (enum_info.fields) |enum_field, i| {
if (std.mem.eql(u8, v.label, enum_field.name)) {
return @intToEnum(P, i);
}
}
unreachable;
},
else => unreachable,
}
},
.Union => |union_info| {
switch (value) {
.one_of => |v| {
inline for (union_info.fields) |union_field, i| {
if (std.mem.eql(u8, v.label, union_field.name)) {
switch (union_field.field_type) {
void => return @unionInit(P, union_field.name, {}),
f32 => return @unionInit(P, union_field.name, v.payload.?),
// the above are the only payload types allowed by the language so far
else => unreachable,
}
}
}
unreachable;
},
else => unreachable,
}
},
else => unreachable,
},
}
}
// turn a zig value into a Value
fn fromZig(param_type: ParamType, zig_value: var) ?Value {
switch (param_type) {
.boolean => if (@TypeOf(zig_value) == bool) return Value{ .boolean = zig_value },
.buffer => if (@TypeOf(zig_value) == []const f32) return Value{ .buffer = zig_value },
.constant => if (@TypeOf(zig_value) == f32) return Value{ .constant = zig_value },
.constant_or_buffer => if (@TypeOf(zig_value) == zang.ConstantOrBuffer) return Value{ .cob = zig_value },
.curve => if (@TypeOf(zig_value) == []const zang.CurveNode) return Value{ .curve = zig_value },
.one_of => |builtin_enum| {
switch (@typeInfo(@TypeOf(zig_value))) {
.Enum => |enum_info| {
// just check if the current value of `zig_value` fits structurally
const label = @tagName(zig_value);
for (builtin_enum.values) |bev| {
if (std.mem.eql(u8, bev.label, label) and bev.payload_type == .none) {
return Value{ .one_of = .{ .label = label, .payload = null } };
}
}
},
.Union => |union_info| {
// just check if the current value of `zig_value` fits structurally
for (builtin_enum.values) |bev| {
inline for (union_info.fields) |field, i| {
if (@enumToInt(zig_value) == i and std.mem.eql(u8, bev.label, field.name)) {
return payloadFromZig(bev, @field(zig_value, field.name));
}
}
}
},
else => {},
}
},
}
return null;
}
fn payloadFromZig(bev: BuiltinEnumValue, zig_payload: var) ?Value {
switch (bev.payload_type) {
.none => {
if (@TypeOf(zig_payload) == void) {
return Value{ .one_of = .{ .label = bev.label, .payload = null } };
}
},
.f32 => {
if (@TypeOf(zig_payload) == f32) {
return Value{ .one_of = .{ .label = bev.label, .payload = zig_payload } };
}
},
}
return null;
}
};
pub const ModuleBase = struct {
num_outputs: usize,
num_temps: usize,
params: []const ModuleParam,
deinitFn: fn (base: *ModuleBase) void,
paintFn: fn (base: *ModuleBase, span: zang.Span, outputs: []const []f32, temps: []const []f32, note_id_changed: bool, params: []const Value) void,
pub fn deinit(base: *ModuleBase) void {
base.deinitFn(base);
}
pub fn paint(base: *ModuleBase, span: zang.Span, outputs: []const []f32, temps: []const []f32, note_id_changed: bool, params: []const Value) void {
base.paintFn(base, span, outputs, temps, note_id_changed, params);
}
// convenience function for interfacing with runtime scripts from zig code.
// you give it an impromptu struct of params and it will validate and convert that into the array of Values that the runtime expects
pub fn makeParams(self: *const ModuleBase, comptime T: type, params: T) ?[@typeInfo(T).Struct.fields.len]Value {
const struct_fields = @typeInfo(T).Struct.fields;
var values: [struct_fields.len]Value = undefined;
for (self.params) |param, i| {
var found = false;
inline for (struct_fields) |field| {
if (std.mem.eql(u8, field.name, param.name)) {
values[i] = Value.fromZig(param.param_type, @field(params, field.name)) orelse {
std.debug.warn("makeParams: type mismatch on param \"{}\"\n", .{param.name});
return null;
};
found = true;
}
}
if (!found) {
std.debug.warn("makeParams: missing param \"{}\"\n", .{param.name});
return null;
}
}
return values;
}
};
pub fn initModule(
script: *const CompiledScript,
module_index: usize,
comptime builtin_packages: []const BuiltinPackage,
allocator: *std.mem.Allocator,
) error{OutOfMemory}!*ModuleBase {
switch (script.module_results[module_index].inner) {
.builtin => {
inline for (builtin_packages) |pkg| {
const package = if (comptime std.mem.eql(u8, pkg.zig_import_path, "zang"))
@import("../zang.zig")
else
@import("../../" ++ pkg.zig_import_path);
inline for (pkg.builtins) |builtin| {
const builtin_name = script.modules[module_index].builtin_name.?;
if (std.mem.eql(u8, builtin.name, builtin_name)) {
const T = @field(package, builtin.name);
return BuiltinModule(T).init(script, module_index, allocator);
}
}
}
unreachable;
},
.custom => |x| {
return ScriptModule.init(script, module_index, builtin_packages, allocator);
},
}
}
fn BuiltinModule(comptime T: type) type {
return struct {
base: ModuleBase,
allocator: *std.mem.Allocator,
mod: T,
id: usize,
fn init(script: *const CompiledScript, module_index: usize, allocator: *std.mem.Allocator) !*ModuleBase {
var self = try allocator.create(@This());
self.base = .{
.num_outputs = T.num_outputs,
.num_temps = T.num_temps,
.params = script.modules[module_index].params,
.deinitFn = deinitFn,
.paintFn = paintFn,
};
self.allocator = allocator;
self.mod = T.init();
return &self.base;
}
fn deinitFn(base: *ModuleBase) void {
var self = @fieldParentPtr(@This(), "base", base);
self.allocator.destroy(self);
}
fn paintFn(
base: *ModuleBase,
span: zang.Span,
outputs_slice: []const []f32,
temps_slice: []const []f32,
note_id_changed: bool,
param_values: []const Value,
) void {
var self = @fieldParentPtr(@This(), "base", base);
const outputs = outputs_slice[0..T.num_outputs].*;
const temps = temps_slice[0..T.num_temps].*;
var params: T.Params = undefined;
inline for (@typeInfo(T.Params).Struct.fields) |field| {
const param_index = getParamIndex(self.base.params, field.name);
@field(params, field.name) = param_values[param_index].toZig(field.field_type);
}
self.mod.paint(span, outputs, temps, note_id_changed, params);
}
fn getParamIndex(params: []const ModuleParam, name: []const u8) usize {
for (params) |param, i| {
if (std.mem.eql(u8, name, param.name)) {
return i;
}
}
unreachable;
}
};
}
const ScriptCurve = struct { start: usize, end: usize };
const ScriptModule = struct {
base: ModuleBase,
allocator: *std.mem.Allocator,
script: *const CompiledScript,
curve_points: []zang.CurveNode, // TODO shouldn't be per module. runtime should have something around CompiledScript with additions
curves: []ScriptCurve,
module_index: usize,
module_instances: []*ModuleBase,
delay_instances: []zang.Delay(11025),
temp_floats: []f32,
callee_temps: [][]f32,
callee_params: []Value,
fn init(
script: *const CompiledScript,
module_index: usize,
comptime builtin_packages: []const BuiltinPackage,
allocator: *std.mem.Allocator,
) !*ModuleBase {
const inner = switch (script.module_results[module_index].inner) {
.builtin => unreachable,
.custom => |x| x,
};
var self = try allocator.create(ScriptModule);
errdefer allocator.destroy(self);
self.base = .{
.num_outputs = script.module_results[module_index].num_outputs,
.num_temps = script.module_results[module_index].num_temps,
.params = script.modules[module_index].params,
.deinitFn = deinitFn,
.paintFn = paintFn,
};
self.allocator = allocator;
self.script = script;
self.module_index = module_index;
const num_curve_points = blk: {
var count: usize = 0;
for (script.curves) |curve| count += curve.points.len;
break :blk count;
};
self.curve_points = try allocator.alloc(zang.CurveNode, num_curve_points);
errdefer allocator.free(self.curve_points);
self.curves = try allocator.alloc(ScriptCurve, script.curves.len);
errdefer allocator.free(self.curves);
{
var index: usize = 0;
for (script.curves) |curve, i| {
self.curves[i].start = index;
for (curve.points) |point, j| {
self.curve_points[index] = .{
.t = point.t.value,
.value = point.value.value,
};
index += 1;
}
self.curves[i].end = index;
}
}
self.module_instances = try allocator.alloc(*ModuleBase, inner.resolved_fields.len);
errdefer allocator.free(self.module_instances);
var num_initialized_fields: usize = 0;
errdefer for (self.module_instances[0..num_initialized_fields]) |module_instance| {
module_instance.deinit();
};
for (inner.resolved_fields) |field_module_index, i| {
self.module_instances[i] = try initModule(script, field_module_index, builtin_packages, allocator);
num_initialized_fields += 1;
}
self.delay_instances = try allocator.alloc(zang.Delay(11025), inner.delays.len);
errdefer allocator.free(self.delay_instances);
for (inner.delays) |delay_decl, i| {
// ignoring delay_decl.num_samples because we need a comptime value
self.delay_instances[i] = zang.Delay(11025).init();
}
self.temp_floats = try allocator.alloc(f32, script.module_results[module_index].num_temp_floats);
errdefer allocator.free(self.temp_floats);
var most_callee_temps: usize = 0;
var most_callee_params: usize = 0;
for (inner.resolved_fields) |field_module_index| {
const callee_temps = script.module_results[field_module_index].num_temps;
if (callee_temps > most_callee_temps) {
most_callee_temps = callee_temps;
}
const callee_params = script.modules[field_module_index].params;
if (callee_params.len > most_callee_params) {
most_callee_params = callee_params.len;
}
}
self.callee_temps = try allocator.alloc([]f32, most_callee_temps);
errdefer allocator.free(self.callee_temps);
self.callee_params = try allocator.alloc(Value, most_callee_params);
errdefer allocator.free(self.callee_params);
return &self.base;
}
fn deinitFn(base: *ModuleBase) void {
var self = @fieldParentPtr(ScriptModule, "base", base);
self.allocator.free(self.callee_params);
self.allocator.free(self.callee_temps);
self.allocator.free(self.temp_floats);
self.allocator.free(self.delay_instances);
self.allocator.free(self.curve_points);
self.allocator.free(self.curves);
for (self.module_instances) |module_instance| {
module_instance.deinit();
}
self.allocator.free(self.module_instances);
self.allocator.destroy(self);
}
const PaintArgs = struct {
inner: CodeGenCustomModuleInner,
outputs: []const []f32,
temps: []const []f32,
note_id_changed: bool,
params: []const Value,
};
fn paintFn(
base: *ModuleBase,
span: zang.Span,
outputs: []const []f32,
temps: []const []f32,
note_id_changed: bool,
params: []const Value,
) void {
var self = @fieldParentPtr(ScriptModule, "base", base);
std.debug.assert(outputs.len == self.script.module_results[self.module_index].num_outputs);
std.debug.assert(temps.len == self.script.module_results[self.module_index].num_temps);
const p: PaintArgs = .{
.inner = switch (self.script.module_results[self.module_index].inner) {
.builtin => unreachable,
.custom => |x| x,
},
.outputs = outputs,
.temps = temps,
.note_id_changed = note_id_changed,
.params = params,
};
for (p.inner.instructions) |instr| {
self.paintInstruction(p, span, instr);
}
}
// FIXME - if x.out is an output, we should be doing `+=`, not `=`! see codegen_zig which already does this
fn paintInstruction(self: *const ScriptModule, p: PaintArgs, span: zang.Span, instr: Instruction) void {
switch (instr) {
.copy_buffer => |x| self.paintCopyBuffer(p, span, x),
.float_to_buffer => |x| self.paintFloatToBuffer(p, span, x),
.cob_to_buffer => |x| self.paintCobToBuffer(p, span, x),
.call => |x| self.paintCall(p, span, x),
.track_call => |x| self.paintTrackCall(p, span, x),
.arith_float => |x| self.paintArithFloat(p, span, x),
.arith_buffer => |x| self.paintArithBuffer(p, span, x),
.arith_float_float => |x| self.paintArithFloatFloat(p, span, x),
.arith_float_buffer => |x| self.paintArithFloatBuffer(p, span, x),
.arith_buffer_float => |x| self.paintArithBufferFloat(p, span, x),
.arith_buffer_buffer => |x| self.paintArithBufferBuffer(p, span, x),
.delay => |x| self.paintDelay(p, span, x),
}
}
fn paintCopyBuffer(self: *const ScriptModule, p: PaintArgs, span: zang.Span, x: InstrCopyBuffer) void {
zang.copy(span, getOut(p, x.out), self.getResultAsBuffer(p, x.in));
}
fn paintFloatToBuffer(self: *const ScriptModule, p: PaintArgs, span: zang.Span, x: InstrFloatToBuffer) void {
zang.set(span, getOut(p, x.out), self.getResultAsFloat(p, x.in));
}
fn paintCobToBuffer(self: *const ScriptModule, p: PaintArgs, span: zang.Span, x: InstrCobToBuffer) void {
var out = getOut(p, x.out);
switch (p.params[x.in_self_param]) {
.cob => |cob| switch (cob) {
.constant => |v| zang.set(span, out, v),
.buffer => |v| zang.copy(span, out, v),
},
else => unreachable,
}
}
fn paintCall(self: *const ScriptModule, p: PaintArgs, span: zang.Span, x: InstrCall) void {
var out = getOut(p, x.out);
const callee_module_index = p.inner.resolved_fields[x.field_index];
const callee_base = self.module_instances[x.field_index];
for (x.temps) |n, i| {
self.callee_temps[i] = p.temps[n];
}
for (x.args) |arg, i| {
const param_type = self.script.modules[callee_module_index].params[i].param_type;
self.callee_params[i] = self.getResultValue(p, param_type, arg);
}
zang.zero(span, out);
callee_base.paintFn(
callee_base,
span,
&[1][]f32{out},
self.callee_temps[0..x.temps.len],
p.note_id_changed,
self.callee_params[0..x.args.len],
);
}
fn paintTrackCall(self: *const ScriptModule, p: PaintArgs, span: zang.Span, x: InstrTrackCall) void {
unreachable; // TODO
}
fn paintArithFloat(self: *const ScriptModule, p: PaintArgs, span: zang.Span, x: InstrArithFloat) void {
const a = self.getResultAsFloat(p, x.a);
self.temp_floats[x.out.temp_float_index] = switch (x.op) {
.abs => std.math.fabs(a),
.cos => std.math.cos(a),
.neg => -a,
.sin => std.math.sin(a),
.sqrt => std.math.sqrt(a),
};
}
fn paintArithBuffer(self: *const ScriptModule, p: PaintArgs, span: zang.Span, x: InstrArithBuffer) void {
var out = getOut(p, x.out);
const a = self.getResultAsBuffer(p, x.a);
var i: usize = span.start;
switch (x.op) {
.abs => {
while (i < span.end) : (i += 1) out[i] = std.math.fabs(a[i]);
},
.cos => {
while (i < span.end) : (i += 1) out[i] = std.math.cos(a[i]);
},
.neg => {
while (i < span.end) : (i += 1) out[i] = -a[i];
},
.sin => {
while (i < span.end) : (i += 1) out[i] = std.math.sin(a[i]);
},
.sqrt => {
while (i < span.end) : (i += 1) out[i] = std.math.sqrt(a[i]);
},
}
}
fn paintArithFloatFloat(self: *const ScriptModule, p: PaintArgs, span: zang.Span, x: InstrArithFloatFloat) void {
const a = self.getResultAsFloat(p, x.a);
const b = self.getResultAsFloat(p, x.b);
self.temp_floats[x.out.temp_float_index] = switch (x.op) {
.add => a + b,
.sub => a - b,
.mul => a * b,
.div => a / b,
.pow => std.math.pow(f32, a, b),
.min => std.math.min(a, b),
.max => std.math.max(a, b),
};
}
fn paintArithFloatBuffer(self: *const ScriptModule, p: PaintArgs, span: zang.Span, x: InstrArithFloatBuffer) void {
var out = getOut(p, x.out);
const a = self.getResultAsFloat(p, x.a);
const b = self.getResultAsBuffer(p, x.b);
switch (x.op) {
.add => {
zang.zero(span, out);
zang.addScalar(span, out, b, a);
},
.sub => {
var i: usize = span.start;
while (i < span.end) : (i += 1) {
out[i] = a - b[i];
}
},
.mul => {
zang.zero(span, out);
zang.multiplyScalar(span, out, b, a);
},
.div => {
var i: usize = span.start;
while (i < span.end) : (i += 1) {
out[i] = a / b[i];
}
},
.pow => {
var i: usize = span.start;
while (i < span.end) : (i += 1) {
out[i] = std.math.pow(f32, a, b[i]);
}
},
.min => {
var i: usize = span.start;
while (i < span.end) : (i += 1) {
out[i] = std.math.min(a, b[i]);
}
},
.max => {
var i: usize = span.start;
while (i < span.end) : (i += 1) {
out[i] = std.math.max(a, b[i]);
}
},
}
}
fn paintArithBufferFloat(self: *const ScriptModule, p: PaintArgs, span: zang.Span, x: InstrArithBufferFloat) void {
var out = getOut(p, x.out);
const a = self.getResultAsBuffer(p, x.a);
const b = self.getResultAsFloat(p, x.b);
switch (x.op) {
.add => {
zang.zero(span, out);
zang.addScalar(span, out, a, b);
},
.sub => {
var i: usize = span.start;
while (i < span.end) : (i += 1) {
out[i] = a[i] - b;
}
},
.mul => {
zang.zero(span, out);
zang.multiplyScalar(span, out, a, b);
},
.div => {
var i: usize = span.start;
while (i < span.end) : (i += 1) {
out[i] = a[i] / b;
}
},
.pow => {
var i: usize = span.start;
while (i < span.end) : (i += 1) {
out[i] = std.math.pow(f32, a[i], b);
}
},
.min => {
var i: usize = span.start;
while (i < span.end) : (i += 1) {
out[i] = std.math.min(a[i], b);
}
},
.max => {
var i: usize = span.start;
while (i < span.end) : (i += 1) {
out[i] = std.math.max(a[i], b);
}
},
}
}
fn paintArithBufferBuffer(self: *const ScriptModule, p: PaintArgs, span: zang.Span, x: InstrArithBufferBuffer) void {
var out = getOut(p, x.out);
const a = self.getResultAsBuffer(p, x.a);
const b = self.getResultAsBuffer(p, x.b);
switch (x.op) {
.add => {
zang.zero(span, out);
zang.add(span, out, a, b);
},
.sub => {
var i: usize = span.start;
while (i < span.end) : (i += 1) {
out[i] = a[i] - b[i];
}
},
.mul => {
zang.zero(span, out);
zang.multiply(span, out, a, b);
},
.div => {
var i: usize = span.start;
while (i < span.end) : (i += 1) {
out[i] = a[i] / b[i];
}
},
.pow => {
var i: usize = span.start;
while (i < span.end) : (i += 1) {
out[i] = std.math.pow(f32, a[i], b[i]);
}
},
.min => {
var i: usize = span.start;
while (i < span.end) : (i += 1) {
out[i] = std.math.min(a[i], b[i]);
}
},
.max => {
var i: usize = span.start;
while (i < span.end) : (i += 1) {
out[i] = std.math.max(a[i], b[i]);
}
},
}
}
fn paintDelay(self: *const ScriptModule, p: PaintArgs, span: zang.Span, x: InstrDelay) void {
// FIXME - what is `out` here? it's not even used?
var out = getOut(p, x.out);
zang.zero(span, out);
var start = span.start;
const end = span.end;
while (start < end) {
zang.zero(zang.Span.init(start, end), p.temps[x.feedback_out_temp_buffer_index]);
zang.zero(zang.Span.init(start, end), p.temps[x.feedback_temp_buffer_index]);
const samples_read = self.delay_instances[x.delay_index].readDelayBuffer(p.temps[x.feedback_temp_buffer_index][start..end]);
const inner_span = zang.Span.init(start, start + samples_read);
for (x.instructions) |sub_instr| {
self.paintInstruction(p, inner_span, sub_instr);
}
self.delay_instances[x.delay_index].writeDelayBuffer(p.temps[x.feedback_out_temp_buffer_index][start .. start + samples_read]);
start += samples_read;
}
}
fn getOut(p: PaintArgs, buffer_dest: BufferDest) []f32 {
return switch (buffer_dest) {
.temp_buffer_index => |i| p.temps[i],
.output_index => |i| p.outputs[i],
};
}
fn getResultValue(self: *const ScriptModule, p: PaintArgs, param_type: ParamType, result: ExpressionResult) Value {
switch (param_type) {
.boolean => return .{ .boolean = self.getResultAsBool(p, result) },
.buffer => return .{ .buffer = self.getResultAsBuffer(p, result) },
.constant => return .{ .constant = self.getResultAsFloat(p, result) },
.constant_or_buffer => return .{ .cob = self.getResultAsCob(p, result) },
.curve => return .{ .curve = self.getResultAsCurve(p, result) },
.one_of => |builtin_enum| {
return switch (result) {
.literal_enum_value => |literal| {
const payload = if (literal.payload) |result_payload|
self.getResultAsFloat(p, result_payload.*)
else
null;
return .{ .one_of = .{ .label = literal.label, .payload = payload } };
},
.self_param => |param_index| switch (p.params[param_index]) {
.one_of => |v| return .{ .one_of = v },
.constant, .buffer, .cob, .boolean, .curve => unreachable,
},
.track_param => |x| unreachable, // TODO
.nothing, .temp_float, .temp_buffer, .literal_boolean, .literal_number, .literal_curve, .literal_track, .literal_module => unreachable,
};
},
}
}
fn getResultAsBuffer(self: *const ScriptModule, p: PaintArgs, result: ExpressionResult) []const f32 {
return switch (result) {
.temp_buffer => |temp_ref| p.temps[temp_ref.index],
.self_param => |param_index| switch (p.params[param_index]) {
.buffer => |v| v,
.constant, .cob, .boolean, .curve, .one_of => unreachable,
},
.track_param => |x| unreachable, // TODO
.nothing, .temp_float, .literal_boolean, .literal_number, .literal_enum_value, .literal_curve, .literal_track, .literal_module => unreachable,
};
}
fn getResultAsFloat(self: *const ScriptModule, p: PaintArgs, result: ExpressionResult) f32 {
return switch (result) {
.literal_number => |literal| literal.value,
.temp_float => |temp_ref| self.temp_floats[temp_ref.index],
.self_param => |param_index| switch (p.params[param_index]) {
.constant => |v| v,
.buffer, .cob, .boolean, .curve, .one_of => unreachable,
},
.track_param => |x| unreachable, // TODO
.nothing, .temp_buffer, .literal_boolean, .literal_enum_value, .literal_curve, .literal_track, .literal_module => unreachable,
};
}
fn getResultAsCob(self: *const ScriptModule, p: PaintArgs, result: ExpressionResult) zang.ConstantOrBuffer {
return switch (result) {
.temp_buffer => |temp_ref| zang.buffer(p.temps[temp_ref.index]),
.temp_float => |temp_ref| zang.constant(self.temp_floats[temp_ref.index]),
.literal_number => |literal| zang.constant(literal.value),
.self_param => |param_index| switch (p.params[param_index]) {
.constant => |v| zang.constant(v),
.buffer => |v| zang.buffer(v),
.cob => |v| v,
.boolean, .curve, .one_of => unreachable,
},
.track_param => |x| unreachable, // TODO
.nothing, .literal_boolean, .literal_enum_value, .literal_curve, .literal_track, .literal_module => unreachable,
};
}
fn getResultAsBool(self: *const ScriptModule, p: PaintArgs, result: ExpressionResult) bool {
return switch (result) {
.literal_boolean => |v| v,
.self_param => |param_index| switch (p.params[param_index]) {
.boolean => |v| v,
.constant, .buffer, .cob, .curve, .one_of => unreachable,
},
.track_param => |x| unreachable, // TODO
.nothing, .temp_buffer, .temp_float, .literal_number, .literal_enum_value, .literal_curve, .literal_track, .literal_module => unreachable,
};
}
fn getResultAsCurve(self: *const ScriptModule, p: PaintArgs, result: ExpressionResult) []const zang.CurveNode {
return switch (result) {
.literal_curve => |curve_index| {
const curve = self.curves[curve_index];
return self.curve_points[curve.start..curve.end];
},
.self_param => |param_index| switch (p.params[param_index]) {
.curve => |v| v,
.boolean, .constant, .buffer, .cob, .one_of => unreachable,
},
.track_param => |x| unreachable, // TODO
.nothing, .temp_buffer, .temp_float, .literal_boolean, .literal_number, .literal_enum_value, .literal_track, .literal_module => unreachable,
};
}
}; | src/zangscript/runtime.zig |
const std = @import("std");
const mem = std.mem;
const math = std.math;
const assert = std.debug.assert;
const maxTreeHeight = 36;
// TODO:
//
// I would like some things optional at comptime that has storage or compute
// implications. For example by passing a struct like this to TreeType to enable
// certain features.
//
// const TreeOptions = struct {
// withLen: bool = false,
// withIter: bool = false,
// };
//
// At the moment I think Zig lacks the support to implement this fully.
// TODO: Iterator support
//
// This is a port of a Go implementation which in turn is a port of a C
// implementation. The original implementations has iterator support but I have
// not got around to implement it for this version yet. Unfortunately iterators
// requires carrying some state as this AVL tree does not record parent pointers
// in the nodes to save space.
//
/// AVL tree holding nodes.
///
/// This is a low level API where the user is responsible for node resource management. Keys are part
/// of the single data type stored into the tree to reduce memory management. A key must never be
/// mutated as long as the node containing it is stored in the tree.
///
/// Note that D can be set to void if you prefer to store nodes in another struct as opposed to
/// nodes carrying data. In that case use @fieldParentPtr to perform necessary pointer
/// manipulations.
///
/// D: Type of datum carried by nodes.
/// K: Type of key in datum.
/// getKey: Obtain key from datum.
/// cmpKey: Compare keys for ordering.
///
pub fn TreeType(comptime D: type, comptime K: type, getKey: fn(*NodeType(D)) K, cmpKey: fn(lhs: K, rhs: K) math.Order) type {
return struct {
const Self = @This();
const Node = NodeType(D);
root: ?*Node = null,
len: usize = 0,
/// Insert node into tree.
/// Returns the inserted node or one already in the tree with an identical key.
/// The inserter must check the return value to determine if the node was inserted or a
/// duplicate was found.
pub fn insert(self: *Self, node: *Node) *Node {
// Empty tree case.
if (self.root == null) {
self.root = node;
self.len += 1;
return node;
}
const key = getKey(node);
// Set up false tree root to ease maintenance
var head = Node{.datum = undefined};
var t = &head;
t.links[Right] = self.root;
var dir: Direction = undefined;
var s = t.links[Right].?; // Place to rebalance and parent
var p = s; // Iterator
// Search down the tree, saving rebalance points
while (true) {
const order = cmpKey(getKey(p), key);
if (order == .eq) {
return p;
}
dir = directionOfBool(order == .lt);
if (p.links[dir]) |q| {
if (q.balance != 0) {
t = p;
s = q;
}
p = q;
} else {
break;
}
}
p.links[dir] = node;
// Update balance factors
p = s;
while (p != node) : (p = p.links[dir].?) {
dir = directionOfBool(cmpKey(getKey(p), key) == .lt);
p.balance += balanceOfDirection(dir);
}
var q = s; // Save rebalance point for parent fix
// Rebalance if necessary
if (abs(s.balance) > 1) {
dir = directionOfBool(cmpKey(getKey(s), key) == .lt);
s = s.insertBalance(dir);
}
// Fix parent
if (q == head.links[Right]) {
self.root = s;
} else {
t.links[directionOfBool(q == t.links[Right])] = s;
}
self.len += 1;
return node;
}
/// Remove node associated with key from tree.
pub fn remove(self: *Self, key: K) ?*Node {
var curr = self.root orelse return null;
var up: [maxTreeHeight]*Node = undefined;
var upd: [maxTreeHeight]Direction = undefined;
var top: usize = 0;
// Search down tree and save path
while (true) {
const order = cmpKey(getKey(curr), key);
if (order == .eq) {
break;
}
// Push direction and node onto stack
const dir = directionOfBool(order == .lt);
upd[top] = dir;
up[top] = curr;
top += 1;
curr = curr.links[dir] orelse return null;
}
// Remove the node
const leftNode = curr.links[Left];
const rightNode = curr.links[Right];
if (leftNode == null or rightNode == null) {
// Which child is non-nil?
const dir = directionOfBool(leftNode == null);
// Fix parent
if (top > 0) {
up[top-1].links[upd[top-1]] = curr.links[dir];
} else {
self.root = curr.links[dir];
}
} else {
// Find the inorder successor
var heir = rightNode.?;
var parent: ?*Node = null;
var parentDir = Left;
if (top > 0) {
parent = up[top-1];
parentDir = upd[top-1];
}
// Save this path too
upd[top] = Right;
up[top] = curr;
const currPos = top;
top += 1;
while (heir.links[Left]) |heirLeftNode| {
upd[top] = Left;
up[top] = heir;
top += 1;
heir = heirLeftNode;
}
const dir = directionOfBool(up[top-1] == curr);
up[top-1].links[dir] = heir.links[Right];
if (parent) |xparent| {
xparent.links[parentDir] = heir;
} else {
self.root = heir;
}
up[currPos] = heir;
heir.copyLinksFrom(curr);
}
// Walk back up the search path
var done = false;
while (top > 0 and !done) : (top -= 1) {
const i = top - 1;
// Update balance factors
up[i].balance += inverseBalanceOfDirection(upd[i]);
// Terminate or rebalance as necessary
const absBalance = abs(up[i].balance);
if (absBalance == 1) {
break;
} else if (absBalance > 1) {
up[i] = up[i].removeBalance(upd[i], &done);
// Fix parent
if (i > 0) {
up[i-1].links[upd[i-1]] = up[i];
} else {
self.root = up[0];
}
}
}
curr.deinitLinks();
self.len -= 1;
return curr;
}
/// Remove all nodes from the tree.
/// The release function with supplied context is called on each removed node.
/// Use {} as context if no release function is supplied.
pub fn clear(self: *Self, context: anytype, releaseFn: ?fn(@TypeOf(context), *Node) anyerror!void) anyerror!void {
var curr = self.root;
// Destruction by rotation
while (curr) |xcurr| {
curr = blk: {
if (xcurr.links[Left]) |left| {
// Rotate right
xcurr.links[Left] = left.links[Right];
left.links[Right] = xcurr;
break :blk left;
} else {
// Remove node
const right = xcurr.links[Right];
if (releaseFn) |f| {
try f(context, xcurr);
}
break :blk right;
}
};
}
self.root = null;
self.len = 0;
}
/// Find node associated with key.
pub fn find(self: *Self, key: K) ?*Node {
var curr = self.root;
while (curr) |node| {
const order = cmpKey(getKey(node), key);
if (order == .eq) {
break;
}
curr = node.links[directionOfBool(order == .lt)];
}
return curr;
}
/// Find node associated with key or one whose key is immediately lesser.
pub fn findEqualOrLesser(self: *Self, key: K) ?*Node {
var curr = self.root;
var lesser: ?*Node = null;
while (curr) |node| {
const order = cmpKey(getKey(node), key);
if (order == .eq) {
break;
}
if (order == .lt) {
lesser = node;
}
curr = node.links[directionOfBool(order == .lt)];
}
return if (curr != null) curr else lesser;
}
/// Find node associated with key or one whose key is immediately greater.
pub fn findEqualOrGreater(self: *Self, key: K) ?*Node {
var curr = self.root;
var greater: ?*Node = null;
while (curr) |node| {
const order = cmpKey(getKey(node), key);
if (order == .eq) {
break;
}
if (order == .gt) {
greater = node;
}
curr = node.links[directionOfBool(order == .lt)];
}
return if (curr != null) curr else greater;
}
/// Returns the leftmost node in the tree.
pub fn leftmost(self: *Self) ?*Node {
return self.edgeNode(Left);
}
/// Returns the rightmost node in the tree.
pub fn rightmost(self: *Self) ?*Node {
return self.edgeNode(Right);
}
fn edgeNode(self: *Self, dir: Direction) ?*Node {
var node = self.root;
while (node) |xnode| {
if (xnode.links[dir]) |child| {
node = child;
} else {
break;
}
}
return node;
}
/// Apply calls the given function on all data stored in the tree left to right.
/// Stops iterations if applyFn returns an error and reports it.
pub fn apply(self: *Self, context: anytype, applyFn: fn(@TypeOf(context), *Node) anyerror!void) anyerror!void {
if (self.root) |root| {
try applyNode(root, context, applyFn);
}
}
fn applyNode(node: *Node, context: anytype, applyFn: fn(@TypeOf(context), *Node) anyerror!void) anyerror!void {
if (node.links[Left]) |left| {
try applyNode(left, context, applyFn);
}
try applyFn(context, node);
if (node.links[Right]) |right| {
try applyNode(right, context, applyFn);
}
}
/// Validate tree invariants.
/// A valid tree should always be balanced and sorted.
pub fn validate(self: *Self) ValidationResult {
var result = ValidationResult{};
if (self.root) |node| {
_ = self.validateNode(node, &result.balanced, &result.sorted, 0);
}
return result;
}
fn validateNode(self: *Self, node: *Node, balanced: *bool, sorted: *bool, depth: i32) i32 {
const key = getKey(node);
var depthLink = [DirectionCount]i32{0, 0};
for ([_]Direction{Left, Right}) |dir| {
depthLink[dir] = blk: {
if (node.links[dir]) |childNode| {
const order = cmpKey(getKey(childNode), key);
if (order == .eq or dir == directionOfBool(order == .lt)) {
sorted.* = false;
}
break :blk self.validateNode(childNode, balanced, sorted, depth + 1);
} else {
break :blk depth + 1;
}
};
}
const depthLeft = depthLink[Left];
const depthRight = depthLink[Right];
if (abs(depthLeft - depthRight) > 1) {
balanced.* = false;
}
return max(depthLeft, depthRight);
}
};
}
/// Node stored in AVL tree.
///
/// D: Type of datum carried by node.
///
pub fn NodeType(comptime D: type) type {
return struct {
const Self = @This();
links: [DirectionCount]?*Self = [DirectionCount]?*Self{null, null},
balance: i32 = 0,
datum: D,
fn deinitLinks(self: *Self) void {
self.links[0] = null;
self.links[1] = null;
self.balance = 0;
}
fn copyLinksFrom(self: *Self, other: *Self) void {
self.links = other.links;
self.balance = other.balance;
}
// Two way single rotation.
fn single(self: *Self, dir: Direction) *Self {
const odir = otherDirection(dir);
const save = self.links[odir].?;
self.links[odir] = save.links[dir];
save.links[dir] = self;
return save;
}
// Two way double rotation.
fn double(self: *Self, dir: Direction) *Self {
const odir = otherDirection(dir);
const save = self.links[odir].?.links[dir].?;
self.links[odir].?.links[dir] = save.links[odir];
save.links[odir] = self.links[odir];
self.links[odir] = save;
const save2 = self.links[odir].?;
self.links[odir] = save2.links[dir];
save2.links[dir] = self;
return save;
}
// Adjust balance before double rotation.
fn adjustBalance(self: *Self, dir: Direction, bal: i32) void {
const n1 = self.links[dir].?;
const n2 = n1.links[otherDirection(dir)].?;
if (n2.balance == 0) {
self.balance = 0;
n1.balance = 0;
} else if (n2.balance == bal) {
self.balance = -bal;
n1.balance = 0;
} else {
// n2.balance == -bal
self.balance = 0;
n1.balance = bal;
}
n2.balance = 0;
}
// Rebalance after insertion.
fn insertBalance(self: *Self, dir: Direction) *Self {
const n = self.links[dir].?;
const bal = balanceOfDirection(dir);
return blk: {
if (n.balance == bal) {
self.balance = 0;
n.balance = 0;
break :blk self.single(otherDirection(dir));
} else {
// n.balance == -bal
self.adjustBalance(dir, bal);
break :blk self.double(otherDirection(dir));
}
};
}
// Rebalance after deletion.
fn removeBalance(self: *Self, dir: Direction, done: *bool) *Self {
const n = self.links[otherDirection(dir)].?;
const bal = balanceOfDirection(dir);
return blk: {
if (n.balance == -bal) {
self.balance = 0;
n.balance = 0;
break :blk self.single(dir);
} else if (n.balance == bal) {
self.adjustBalance(otherDirection(dir), -bal);
break :blk self.double(dir);
} else {
// n.balance == 0
self.balance = -bal;
n.balance = bal;
done.* = true;
break :blk self.single(dir);
}
};
}
};
}
/// Tree validation result.
pub const ValidationResult = struct {
balanced: bool = true,
sorted: bool = true,
};
const Direction = u1;
const Left: Direction = 0;
const Right: Direction = 1;
const DirectionCount = 2;
inline fn otherDirection(dir: Direction) Direction {
return ~dir;
}
inline fn balanceOfDirection(dir: Direction) i32 {
return switch (dir) {
Left => -1,
Right => 1,
};
}
inline fn inverseBalanceOfDirection(dir: Direction) i32 {
return switch (dir) {
Left => 1,
Right => -1,
};
}
inline fn directionOfBool(b: bool) Direction {
return if (b) Right else Left;
}
const max = std.math.max;
// We can do without the error checks of std.math.absInt
inline fn abs(x: anytype) @TypeOf(x) {
return if (x < 0) -x else x;
}
const runCpuIntensiveTests = true;
test "invariants: permute insert" {
if (!runCpuIntensiveTests) return;
const N = 10;
var tree = Test.Tree{};
const src = Test.valuesInSequence(N);
var dst: [N]Test.Value = undefined;
var nodes: [N]Test.Node = undefined;
var seq: u32 = 0;
while (Test.permuteValues(&dst, &src, seq)) {
Test.initNodes(&nodes, &dst);
for (nodes) |*node, i| {
const rnode = tree.insert(node);
if (rnode != node) {
std.debug.panic("Failed to insert datum={}, index={}, insertSequence={}, returnedDatum={}",
.{node.datum, i, seq, rnode.datum});
}
const validation = tree.validate();
if (!validation.balanced or !validation.sorted) {
std.debug.panic("Invalid tree invariant: balanced={}, sorted={}, insertSequence={}",
.{validation.balanced, validation.sorted, seq});
}
}
try tree.clear({}, null);
seq += 1;
}
}
test "invariants: permute remove" {
if (!runCpuIntensiveTests) return;
const N = 10;
var tree = Test.Tree{};
const src = Test.valuesInSequence(N);
var dst: [N]Test.Value = undefined;
var nodes: [N]Test.Node = undefined;
var seq: u32 = 0;
while (Test.permuteValues(&dst, &src, seq)) {
Test.initNodes(&nodes, &dst);
for (nodes) |*node, i| {
const rnode = tree.insert(node);
if (rnode != node) {
std.debug.panic("Failed to insert datum={}, index={}, insertSequence={}, returnedDatum={}",
.{node.datum, i, seq, rnode.datum});
}
}
for (dst) |value, i| {
const rnode = tree.remove(value);
if (rnode) |node| {
if (node.datum != value) {
std.debug.panic("Failed to remove datum={}, index={}, removeSequence={}, returnedDatum={}",
.{value, i, seq, node.datum});
}
} else {
std.debug.panic("Failed to remove datum={}, index={}, removeSequence={}, returnedNode={}",
.{value, i, seq, rnode});
}
const validation = tree.validate();
if (!validation.balanced or !validation.sorted) {
std.debug.panic("Invalid tree invariant: balanced={}, sorted={}, insertSequence={}",
.{validation.balanced, validation.sorted, seq});
}
}
try tree.clear({}, null);
seq += 1;
}
}
test "insert existing" {
var tree = Test.Tree{};
var a = Test.Tree.Node{.datum = 1};
var b = Test.Tree.Node{.datum = 1};
try Test.expectEqual(&a, tree.insert(&a));
try Test.expectEqual(&a, tree.insert(&b));
}
// TODO: test "iter update"
// TODO: test "iter empty"
// TODO: test "iter cancel"
test "remove from empty tree" {
var tree = Test.Tree{};
var node = tree.remove(1);
try Test.expectEqual(@as(?*Test.Tree.Node, null), node);
}
test "remove non existing" {
const testValues = [_]Test.Value{1, 2, 3, 5};
var nodes: [testValues.len]Test.Tree.Node = undefined;
Test.initNodes(&nodes, &testValues);
var tree = Test.Tree{};
Test.populateTree(&tree, &nodes);
var node = tree.remove(4);
try Test.expectEqual(@as(?*Test.Tree.Node, null), node);
}
test "clear" {
const testValues = [_]Test.Value{1, 2, 3, 4, 5, 6, 7, 8, 9};
var nodes: [testValues.len]Test.Tree.Node = undefined;
Test.initNodes(&nodes, &testValues);
var tree = Test.Tree{};
Test.populateTree(&tree, &nodes);
// TODO: test iterator invalidation (if iterators are added).
const ReleaseContext = struct {
testValues: []const Test.Value,
index: usize = 0,
fn f(self: *@This(), node: *Test.Tree.Node) !void {
try Test.expectEqual(self.testValues[self.index], node.datum);
self.index += 1;
}
};
var ctx = ReleaseContext{.testValues = &testValues};
try tree.clear(&ctx, ReleaseContext.f);
try Test.expectEqual(@as(?*Test.Tree.Node, null), tree.root);
try Test.expectEqual(@as(usize, 0), tree.len);
// TODO: test iterator invalidation (if iterators are added).
}
test "clearEmpty" {
var tree = Test.Tree{};
const ReleaseContext = struct {
fn f(self: void, node: *Test.Tree.Node) !void {
return error.TestUnexpectedCallback;
}
};
try tree.clear({}, ReleaseContext.f);
}
test "apply" {
const testValues = [_]Test.Value{1, 2, 3, 4, 5, 6, 7, 8, 9};
var nodes: [testValues.len]Test.Tree.Node = undefined;
Test.initNodes(&nodes, &testValues);
var tree = Test.Tree{};
Test.populateTree(&tree, &nodes);
const ApplyContext = struct {
testValues: []const Test.Value,
index: usize = 0,
fn f(self: *@This(), node: *Test.Tree.Node) !void {
try Test.expectEqual(self.testValues[self.index], node.datum);
self.index += 1;
}
};
var ctx = ApplyContext{.testValues = &testValues};
try tree.apply(&ctx, ApplyContext.f);
}
test "applyEmpty" {
var tree = Test.Tree{};
const ApplyContext = struct {
fn f(self: void, node: *Test.Tree.Node) !void {
return error.TestUnexpectedCallback;
}
};
try tree.apply({}, ApplyContext.f);
}
test "len" {
const testValues = [_]Test.Value{1, 2, 3};
const nonExistingValue: Test.Value = 4;
var nodes: [testValues.len]Test.Tree.Node = undefined;
Test.initNodes(&nodes, &testValues);
var tree = Test.Tree{};
try Test.expectEqual(@as(usize, 0), tree.len);
var insertCount: usize = 0;
for (nodes) |*node| {
const rnode = tree.insert(node);
if (rnode != node) {
std.debug.panic("Failed to populate tree with datum {}, found existing datum {}",
.{node.datum, rnode.datum});
}
insertCount += 1;
try Test.expectEqual(insertCount, tree.len);
}
// Removing non existing value should not modify tree count.
_ = tree.remove(nonExistingValue);
try Test.expectEqual(insertCount, tree.len);
var removeCount: usize = 0;
for (testValues) |v| {
_ = tree.remove(v);
removeCount += 1;
try Test.expectEqual(insertCount - removeCount, tree.len);
}
}
test "find" {
const testValues = [_]Test.Value{2, 5, 6, 7, 10};
var nodes: [testValues.len]Test.Tree.Node = undefined;
Test.initNodes(&nodes, &testValues);
var tree = Test.Tree{};
Test.populateTree(&tree, &nodes);
const T = struct {
name: []const u8,
lookupFn: fn(*Test.Tree, u32) ?u32,
input: u32,
output: ?u32,
};
const F = struct {
fn find(xtree: *Test.Tree, xvalue: u32) ?u32 {
if (xtree.find(xvalue)) |node| { return node.datum; } else { return null; }
}
fn findLe(xtree: *Test.Tree, xvalue: u32) ?u32 {
if (xtree.findEqualOrLesser(xvalue)) |node| { return node.datum; } else { return null; }
}
fn findGe(xtree: *Test.Tree, xvalue: u32) ?u32 {
if (xtree.findEqualOrGreater(xvalue)) |node| { return node.datum; } else { return null; }
}
};
const testData = [_]T{
T{.name = "Find(NonExisting)", .lookupFn = F.find, .input = 1, .output = null},
T{.name = "Find(NonExisting)", .lookupFn = F.find, .input = 4, .output = null},
T{.name = "Find(NonExisting)", .lookupFn = F.find, .input = 8, .output = null},
T{.name = "Find(NonExisting)", .lookupFn = F.find, .input = 11, .output = null},
T{.name = "Find(Existing)", .lookupFn = F.find, .input = 2, .output = 2},
T{.name = "Find(Existing)", .lookupFn = F.find, .input = 6, .output = 6},
T{.name = "Find(Existing)", .lookupFn = F.find, .input = 10, .output = 10},
T{.name = "FindLe(NonExisting)", .lookupFn = F.findLe, .input = 11, .output = 10},
T{.name = "FindLe(NonExisting)", .lookupFn = F.findLe, .input = 9, .output = 7},
T{.name = "FindLe(NonExisting)", .lookupFn = F.findLe, .input = 4, .output = 2},
T{.name = "FindLe(NonExisting)", .lookupFn = F.findLe, .input = 1, .output = null},
T{.name = "FindLe(Existing)", .lookupFn = F.findLe, .input = 2, .output = 2},
T{.name = "FindLe(Existing)", .lookupFn = F.findLe, .input = 6, .output = 6},
T{.name = "FindLe(Existing)", .lookupFn = F.findLe, .input = 10, .output = 10},
T{.name = "FindGe(NonExisting)", .lookupFn = F.findGe, .input = 11, .output = null},
T{.name = "FindGe(NonExisting)", .lookupFn = F.findGe, .input = 8, .output = 10},
T{.name = "FindGe(NonExisting)", .lookupFn = F.findGe, .input = 3, .output = 5},
T{.name = "FindGe(NonExisting)", .lookupFn = F.findGe, .input = 1, .output = 2},
T{.name = "FindGe(Existing)", .lookupFn = F.findGe, .input = 2, .output = 2},
T{.name = "FindGe(Existing)", .lookupFn = F.findGe, .input = 6, .output = 6},
T{.name = "FindGe(Existing)", .lookupFn = F.findGe, .input = 10, .output = 10},
};
for (testData) |*t| {
const output = t.lookupFn(&tree, t.input);
const noneMarker = 99;
if ((output orelse noneMarker) != (t.output orelse noneMarker)) {
std.debug.panic("{s}: input={}, output={}; expect={}", .{t.name, t.input, output, t.output});
}
}
}
test "leftmost" {
var tree = Test.Tree{};
const expected: ?*Test.Tree.Node = null;
try Test.expectEqual(expected, tree.leftmost());
const testValues = [_]Test.Value{42, 3, 99, 76};
var nodes: [testValues.len]Test.Tree.Node = undefined;
Test.initNodes(&nodes, &testValues);
Test.populateTree(&tree, &nodes);
try Test.expectEqual(@as(Test.Value, 3), tree.leftmost().?.datum);
}
test "rightmost" {
var tree = Test.Tree{};
const expected: ?*Test.Tree.Node = null;
try Test.expectEqual(expected, tree.rightmost());
const testValues = [_]Test.Value{42, 3, 99, 76};
var nodes: [testValues.len]Test.Tree.Node = undefined;
Test.initNodes(&nodes, &testValues);
Test.populateTree(&tree, &nodes);
try Test.expectEqual(@as(Test.Value, 99), tree.rightmost().?.datum);
}
const Test = struct {
const expectEqual = std.testing.expectEqual;
const Tree = TreeType(u32, u32, getKey, cmpKey);
fn getKey(node: *NodeType(u32)) u32 {
return node.datum;
}
fn cmpKey(lhs: u32, rhs: u32) math.Order {
if (lhs < rhs) {
return .lt;
} else if (lhs > rhs) {
return .gt;
}
return .eq;
}
const Value = u32;
const Node = Tree.Node;
fn valuesInSequence(comptime n: usize) [n]Value {
var t: [n]Value = undefined;
for (t) |_, i| {
t[i] = @intCast(Value, i);
}
return t;
}
fn initNodes(nodes: []Node, values: []const Value) void {
for (values) |value, i| {
nodes[i] = Tree.Node{.datum = value};
}
}
fn populateTree(tree: *Tree, nodes: []Node) void {
for (nodes) |*node| {
const rnode = tree.insert(node);
if (rnode != node) {
std.debug.panic("Failed to populate tree with datum {}, found existing datum {}",
.{node.datum, rnode.datum});
}
}
}
fn factorial(n: u32) u32 {
var r: u32 = 1;
var i: u32 = 2;
while (i < n) : (i += 1) {
r *= i;
}
return r;
}
fn permuteValues(dst: []Value, src: []const Value, seq: u32) bool {
assert(src.len == dst.len);
const alen = @intCast(u32, src.len);
var fact = factorial(alen);
// Out of range?
if ((seq / alen) >= fact) {
return false;
}
mem.copy(u32, dst[0..], src[0..]);
var i: u32 = 0;
while (i < (alen - 1)) : (i += 1) {
const tmpi = (seq / fact) % (alen - i);
const tmp = dst[i+tmpi];
var j: u32 = i + tmpi;
while (j > i) : (j -= 1) {
dst[j] = dst[j-1];
}
dst[i] = tmp;
fact /= (alen - (i + 1));
}
return true;
}
}; | avl_tree.zig |
const std = @import("std");
const zfetch = @import("zfetch");
const uca = @import("src/types.zig");
const fmtValueLiteral = @import("fmt-valueliteral").fmtValueLiteral;
const csi = @import("ansi").csi;
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const alloc = &gpa.allocator;
const max_size = std.math.maxInt(usize);
//
const file = try std.fs.cwd().createFile("src/allkeys.zig", .{});
defer file.close();
const w = file.writer();
try w.writeAll(
\\// This file defines the Default Unicode Collation Element Table (DUCET) for the Unicode Collation Algorithm
\\//
\\// See https://www.unicode.org/reports/tr10/ for more information.
\\//
\\const uca = @import("./lib.zig");
\\
\\pub const allkeys = [_]uca.CollationElement{
\\
);
const req = try zfetch.Request.init(alloc, "https://www.unicode.org/Public/UCA/latest/allkeys.txt", null);
defer req.deinit();
try req.do(.GET, null, null);
const r = req.reader();
var line_num: usize = 1;
std.debug.print("\n", .{});
while (true) {
const line = r.readUntilDelimiterAlloc(alloc, '\n', max_size) catch |e| if (e == error.EndOfStream) break else return e;
if (line.len == 0) {
continue;
}
if (line[0] == '#' or line[0] == '@') {
continue;
}
const codes = blk: {
const res = &std.ArrayList(u21).init(alloc);
defer res.deinit();
const read = line[0..std.mem.indexOf(u8, line, ";").?];
var it = std.mem.split(read, " ");
while (it.next()) |item| {
if (item.len == 0) continue;
try res.append(try std.fmt.parseUnsigned(u21, item, 16));
}
break :blk res.toOwnedSlice();
};
const weights = blk: {
const res = &std.ArrayList(uca.CollationElement.Weight).init(alloc);
defer res.deinit();
const read = line[std.mem.indexOf(u8, line, ";").? + 2 .. std.mem.indexOf(u8, line, "#").? - 1];
var it = std.mem.split(read, "[");
_ = it.next().?;
while (it.next()) |item| {
const first = item[0];
var it2 = std.mem.split(item[1 .. item.len - 1], ".");
const a = try std.fmt.parseUnsigned(u16, it2.next().?, 16);
const b = try std.fmt.parseUnsigned(u16, it2.next().?, 16);
const c = try std.fmt.parseUnsigned(u16, it2.next().?, 16);
if (it2.next()) |_| {
std.debug.assert(false);
}
const wght = blk2: {
if (first == '*') break :blk2 uca.CollationElement.Weight{ .Variable = .{ a, b, c } };
if (c == 0) break :blk2 uca.CollationElement.Weight{ .Ignorable = void{} };
if (b == 0) break :blk2 uca.CollationElement.Weight{ .Tertiary = .{c} };
if (a == 0) break :blk2 uca.CollationElement.Weight{ .Secondary = .{ b, c } };
break :blk2 uca.CollationElement.Weight{ .Primary = .{ a, b, c } };
};
try res.append(wght);
}
break :blk res.toOwnedSlice();
};
const name = blk: {
break :blk line[std.mem.indexOf(u8, line, "#").? + 2 .. line.len];
};
const element = uca.CollationElement{
.codepoints = codes,
.weights = weights,
};
try w.print(" ", .{});
try fmtValueLiteral(w, element, false);
try w.print(", // {s}\n", .{name});
std.debug.print("{s}", .{comptime csi.CursorUp(1)});
std.debug.print("{s}", .{comptime csi.EraseInLine(0)});
std.debug.print("{d}\n", .{line_num});
line_num += 1;
}
try w.writeAll("};\n");
std.log.info("allkeys done", .{});
//
const file2 = try std.fs.cwd().createFile("src/decomps.zig", .{});
defer file2.close();
const w2 = file2.writer();
try w2.writeAll(
\\// This file lists decompositions used in generating the Default Unicode Collation Element Table (DUCET) for the Unicode Collation Algorithm
\\//
\\// See https://www.unicode.org/reports/tr10/ for more information.
\\//
\\const uca = @import("./lib.zig");
\\
\\pub const decomps = [_]uca.Decomposition{
\\
);
const req2 = try zfetch.Request.init(alloc, "https://www.unicode.org/Public/UCA/latest/decomps.txt", null);
defer req2.deinit();
try req2.do(.GET, null, null);
const r2 = req2.reader();
const set = &std.BufSet.init(alloc);
while (true) {
const line = r2.readUntilDelimiterAlloc(alloc, '\n', max_size) catch |e| if (e == error.EndOfStream) break else return e;
if (line.len == 0) {
continue;
}
if (line[0] == '#') {
continue;
}
var it = std.mem.split(line, ";");
const point = try std.fmt.parseUnsigned(u21, it.next().?, 16);
const tag = blk: {
const s = it.next().?;
if (s.len == 0) {
break :blk null;
}
const k = s[1 .. s.len - 1];
const e = std.meta.stringToEnum(uca.Decomposition.Tag, k);
if (e) |_| {
break :blk e.?;
} else {
try set.put(k);
break :blk null;
}
};
var name: []const u8 = undefined;
const decomp = blk: {
const res = &std.ArrayList(u21).init(alloc);
const s = it.next().?;
var it2 = std.mem.split(s, " ");
while (it2.next()) |item| {
if (item[0] == '#') {
name = it2.rest();
break;
}
try res.append(try std.fmt.parseUnsigned(u21, item, 16));
}
break :blk res.toOwnedSlice();
};
const element = uca.Decomposition{
.codepoint = point,
.tag = tag,
.decomposition = decomp,
};
try w2.print(" ", .{});
try fmtValueLiteral(w2, element, false);
try w2.print(", // {s}\n", .{name});
}
try w2.writeAll("};\n");
var sit = set.iterator();
while (sit.next()) |entry| {
std.debug.print("{s},\n", .{entry.key});
}
std.log.info("decomps done", .{});
} | generate.zig |
const std = @import("std");
const tools = @import("tools");
const with_trace = true;
const assert = std.debug.assert;
fn trace(comptime fmt: []const u8, args: anytype) void {
if (with_trace) std.debug.print(fmt, args);
}
pub fn main() anyerror!void {
const stdout = std.io.getStdOut().writer();
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
const numelves = 3005290;
var len: usize = numelves;
var elves = try allocator.alloc(u22, numelves);
defer allocator.free(elves);
{
var i: u22 = 1;
while (i <= numelves) : (i += 1) {
elves[numelves - i] = i;
}
}
// brute force... pleins de copies!
{
var victim: usize = (len - 1) / 2;
var i: usize = 0;
while (len > 1) {
if (len % 2 == 0) {
victim = (victim + 1) % len;
} else {
victim = victim % len;
}
const eliminated = if (false) // part 1
(i + 1) % len
else // part 2
victim;
// ((i + i + len) / 2) % len;
//trace("elf {} eliminated. remaining:", .{elves[len - 1 - eliminated]});
//for (elves[0..len]) |e, j| {
// if (j == ((len - 1) - (i % (len - 1)))) {
// trace("|{}|,", .{e});
// } else if (j == ((len - 1) - (eliminated % (len - 1)))) {
// trace("x{}x,", .{e});
// } else {
// trace("{},", .{e});
// }
//}
//trace("\n", .{});
assert(victim == ((i + (i + len)) / 2) % len);
std.mem.copy(u22, elves[len - 1 - eliminated .. len - 1], elves[len - eliminated .. len]);
len -= 1;
if (victim >= i) {
i = (i + 1) % len;
} else {
i = i % len;
}
if (len % 1000 == 0)
trace("len = {}\n", .{len});
}
}
try stdout.print("last elf={}\n", .{elves[0]});
} | 2016/day19.zig |
const std = @import("std");
const testing = std.testing;
const math = @import("std").math;
const f_eq = @import("utils.zig").f_eq;
const debug = @import("std").debug;
pub const Vec4 = packed struct {
x: f32,
y: f32,
z: f32,
w: f32,
pub fn create(x: f32, y: f32, z: f32, w: f32) Vec4 {
return Vec4{
.x = x,
.y = y,
.z = z,
.w = w,
};
}
pub fn add(a: Vec4, b: Vec4) Vec4 {
return Vec4{
.x = a.x + b.x,
.y = a.y + b.y,
.z = a.z + b.z,
.w = a.w + b.w,
};
}
test "add" {
const a = Vec4.create(1, 2, 3, 4);
const b = Vec4.create(5, 6, 7, 8);
const out = Vec4.add(a, b);
const expected = Vec4.create(6, 8, 10, 12);
try expectEqual(expected, out);
}
pub fn substract(a: Vec4, b: Vec4) Vec4 {
return Vec4{
.x = a.x - b.x,
.y = a.y - b.y,
.z = a.z - b.z,
.w = a.w - b.w,
};
}
test "substract" {
const a = Vec4.create(1, 2, 3, 4);
const b = Vec4.create(5, 6, 7, 8);
const out = Vec4.sub(a, b);
const expected = Vec4.create(-4, -4, -4, -4);
try expectEqual(expected, out);
}
pub fn multiply(a: Vec4, b: Vec4) Vec4 {
return Vec4{
.x = a.x * b.x,
.y = a.y * b.y,
.z = a.z * b.z,
.w = a.w * b.w,
};
}
test "multiply" {
const a = Vec4.create(1, 2, 3, 4);
const b = Vec4.create(5, 6, 7, 8);
const out = Vec4.mul(a, b);
const expected = Vec4.create(5, 12, 21, 32);
try expectEqual(expected, out);
}
pub fn divide(a: Vec4, b: Vec4) Vec4 {
return Vec4{
.x = a.x / b.x,
.y = a.y / b.y,
.z = a.z / b.z,
.w = a.w / b.w,
};
}
test "divide" {
const a = Vec4.create(1, 2, 3, 4);
const b = Vec4.create(5, 6, 7, 8);
const out = Vec4.div(a, b);
const expected = Vec4.create(0.2, 0.33333, 0.428571, 0.5);
try expectEqual(expected, out);
}
pub fn ceil(a: Vec4) Vec4 {
return Vec4{
.x = @ceil(a.x),
.y = @ceil(a.y),
.z = @ceil(a.z),
.w = @ceil(a.w),
};
}
test "ceil" {
const a = Vec4.create(math.e, math.pi, @sqrt(2.0), 1.0 / @sqrt(2.0));
const out = Vec4.ceil(a);
const expected = Vec4.create(3, 4, 2, 1);
try expectEqual(expected, out);
}
pub fn floor(a: Vec4) Vec4 {
return Vec4{
.x = @floor(a.x),
.y = @floor(a.y),
.z = @floor(a.z),
.w = @floor(a.w),
};
}
test "floor" {
const a = Vec4.create(math.e, math.pi, @sqrt(2.0), 1.0 / @sqrt(2.0));
const out = Vec4.floor(a);
const expected = Vec4.create(2, 3, 1, 0);
try expectEqual(expected, out);
}
pub fn min(a: Vec4, b: Vec4) Vec4 {
return Vec4{
.x = math.min(a.x, b.x),
.y = math.min(a.y, b.y),
.z = math.min(a.z, b.z),
.w = math.min(a.w, b.w),
};
}
test "min" {
const a = Vec4.create(1, 3, 1, 3);
const b = Vec4.create(3, 1, 3, 1);
const out = Vec4.min(a, b);
const expected = Vec4.create(1, 1, 1, 1);
try expectEqual(expected, out);
}
pub fn max(a: Vec4, b: Vec4) Vec4 {
return Vec4{
.x = math.max(a.x, b.x),
.y = math.max(a.y, b.y),
.z = math.max(a.z, b.z),
.w = math.max(a.w, b.w),
};
}
test "max" {
const a = Vec4.create(1, 3, 1, 3);
const b = Vec4.create(3, 1, 3, 1);
const out = Vec4.max(a, b);
const expected = Vec4.create(3, 3, 3, 3);
try expectEqual(expected, out);
}
pub fn round(a: Vec4) Vec4 {
return Vec4{
.x = @round(a.x),
.y = @round(a.y),
.z = @round(a.z),
.w = @round(a.w),
};
}
test "round" {
const a = Vec4.create(math.e, math.pi, @sqrt(2.0), 1.0 / @sqrt(2.0));
const out = Vec4.round(a);
const expected = Vec4.create(3, 3, 1, 1);
try expectEqual(expected, out);
}
pub fn scale(a: Vec4, s: f32) Vec4 {
return Vec4{
.x = a.x * s,
.y = a.y * s,
.z = a.z * s,
.w = a.w * s,
};
}
test "scale" {
const a = Vec4.create(1, 2, 3, 4);
const out = Vec4.scale(a, 2);
const expected = Vec4.create(2, 4, 6, 8);
try expectEqual(expected, out);
}
pub fn scaleAndAdd(a: Vec4, b: Vec4, s: f32) Vec4 {
return Vec4{
.x = a.x + (b.x * s),
.y = a.y + (b.y * s),
.z = a.z + (b.z * s),
.w = a.w + (b.w * s),
};
}
test "scaleAndAdd" {
const a = Vec4.create(1, 2, 3, 4);
const b = Vec4.create(5, 6, 7, 8);
const out = Vec4.scaleAndAdd(a, b, 0.5);
const expected = Vec4.create(3.5, 5, 6.5, 8);
try expectEqual(expected, out);
}
pub fn distance(a: Vec4, b: Vec4) f32 {
// TODO: use std.math.hypot
return @sqrt(Vec4.squaredDistance(a, b));
}
test "distance" {
const a = Vec4.create(1, 2, 3, 4);
const b = Vec4.create(5, 6, 7, 8);
const out = Vec4.distance(a, b);
try std.testing.expectEqual(out, 8);
}
pub fn squaredDistance(a: Vec4, b: Vec4) f32 {
const x = a.x - b.x;
const y = a.y - b.y;
const z = a.z - b.z;
const w = a.w - b.w;
return x * x + y * y + z * z + w * w;
}
test "squaredDistance" {
const a = Vec4.create(1, 2, 3, 4);
const b = Vec4.create(5, 6, 7, 8);
const out = Vec4.squaredDistance(a, b);
try std.testing.expectEqual(out, 64);
}
pub fn length(a: Vec4) f32 {
// TODO: use std.math.hypot
return @sqrt(a.squaredLength());
}
test "length" {
const a = Vec4.create(1, 2, 3, 4);
const out = Vec4.length(a);
try std.testing.expect(f_eq(out, 5.477225));
}
pub fn squaredLength(a: Vec4) f32 {
const x = a.x;
const y = a.y;
const z = a.z;
const w = a.w;
return x * x + y * y + z * z + w * w;
}
test "squaredLength" {
const a = Vec4.create(1, 2, 3, 4);
const out = Vec4.squaredLength(a);
try std.testing.expect(f_eq(out, 30));
}
pub fn negate(a: Vec4) Vec4 {
return Vec4{
.x = -a.x,
.y = -a.y,
.z = -a.z,
.w = -a.w,
};
}
test "negate" {
const a = Vec4.create(1, 2, 3, 4);
const out = Vec4.negate(a);
const expected = Vec4.create(-1, -2, -3, -4);
try expectEqual(expected, out);
}
pub fn inverse(a: Vec4) Vec4 {
return Vec4{
.x = -(1.0 / a.x),
.y = -(1.0 / a.y),
.z = -(1.0 / a.z),
.w = -(1.0 / a.w),
};
}
pub fn normalize(a: Vec4) Vec4 {
const x = a.x;
const y = a.y;
const z = a.z;
const w = a.w;
var l = x * x + y * y + z * z + w * w;
if (l > 0)
l = 1 / @sqrt(l);
return Vec4{
.x = x * l,
.y = y * l,
.z = z * l,
.w = w * l,
};
}
test "normalize" {
const a = Vec4.create(5, 0, 0, 0);
const out = Vec4.normalize(a);
const expected = Vec4.create(1, 0, 0, 0);
try expectEqual(expected, out);
}
pub fn dot(a: Vec4, b: Vec4) f32 {
return a.x * b.x //
+ a.y * b.y //
+ a.z * b.z //
+ a.w * b.w;
}
test "dot" {
const a = Vec4.create(1, 2, 3, 4);
const b = Vec4.create(5, 6, 7, 8);
const out = Vec4.dot(a, b);
const expected = 70.0;
try std.testing.expect(f_eq(expected, out));
}
/// Returns the cross-product of three vectors in a 4-dimensional space
pub fn cross(u: Vec4, v: Vec4, w: Vec4) Vec4 {
const A = (v.x * w.y) - (v.y * w.x);
const B = (v.x * w.z) - (v.z * w.x);
const C = (v.x * w.w) - (v.w * w.x);
const D = (v.y * w.z) - (v.z * w.y);
const E = (v.y * w.w) - (v.w * w.y);
const F = (v.z * w.w) - (v.w * w.z);
const G = u.x;
const H = u.y;
const I = u.z;
const J = u.w;
return Vec4{
.x = (H * F) - (I * E) + (J * D),
.y = -(G * F) + (I * C) - (J * B),
.z = (G * E) - (H * C) + (J * A),
.w = -(G * D) + (H * B) - (I * A),
};
}
test "cross" {
const a = Vec4.create(1, 0, 0, 0);
const b = Vec4.create(0, 1, 0, 0);
const c = Vec4.create(0, 0, 1, 0);
const out = Vec4.cross(a, b, c);
const expected = Vec4.create(0, 0, 0, -1);
try expectEqual(expected, out);
}
pub fn lerp(a: Vec4, b: Vec4, t: f32) Vec4 {
return Vec4{
.x = a.x + t * (b.x - a.x),
.y = a.y + t * (b.y - a.y),
.z = a.z + t * (b.z - a.z),
.w = a.w + t * (b.w - a.w),
};
}
test "lerp" {
const a = Vec4.create(1, 2, 3, 4);
const b = Vec4.create(5, 6, 7, 8);
const out = Vec4.lerp(a, b, 0.5);
const expected = Vec4.create(3, 4, 5, 6);
try expectEqual(expected, out);
}
pub fn equals(a: Vec4, b: Vec4) bool {
return f_eq(a.x, b.x) and f_eq(a.y, b.y) and f_eq(a.z, b.z) and f_eq(a.w, b.w);
}
pub fn equalsExact(a: Vec4, b: Vec4) bool {
return a.x == b.x and a.y == b.y and a.z == b.z and a.w == b.w;
}
pub fn format(
value: @This(),
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = options;
_ = fmt;
return std.fmt.format(
writer,
"Vec4({d:.3}, {d:.3}, {d:.3}, {d:.3})",
.{ value.x, value.y, value.z, value.w },
);
}
pub const sub = substract;
pub const mul = multiply;
pub const div = divide;
pub const dist = distance;
pub const sqrDist = squaredDistance;
pub const len = length;
pub const sqrLen = squaredLength;
fn expectEqual(expected: Vec4, actual: Vec4) !void {
if (!equals(expected, actual)) {
std.debug.warn("Expected: {}, found {}", .{ expected, actual });
return error.NotEqual;
}
}
}; | src/vec4.zig |
pub const Key = @import("keys.zig").Key;
pub const Kind = enum {
Pressed, // Key is depressed. Should be followed by a release.
Released, // Key was released.
Hit, // Key doesn't support seperate pressed and released states.
};
pub const Modifiers = struct {
right_shift_is_pressed: bool = false,
left_shift_is_pressed: bool = false,
right_alt_is_pressed: bool = false,
left_alt_is_pressed: bool = false,
right_control_is_pressed: bool = false,
left_control_is_pressed: bool = false,
pub fn shift_is_pressed(self: *const Modifiers) bool {
return self.right_shift_is_pressed or self.left_shift_is_pressed;
}
pub fn alt_is_pressed(self: *const Modifiers) bool {
return self.right_alt_is_pressed or self.left_alt_is_pressed;
}
pub fn control_is_pressed(self: *const Modifiers) bool {
return self.right_control_is_pressed or self.left_control_is_pressed;
}
pub fn update(self: *Modifiers, event: *const Event) void {
switch (event.unshifted_key) {
.Key_LeftShift => self.left_shift_is_pressed = event.kind == .Pressed,
.Key_RightShift => self.right_shift_is_pressed = event.kind == .Pressed,
.Key_LeftAlt => self.left_alt_is_pressed = event.kind == .Pressed,
.Key_RightAlt => self.right_alt_is_pressed = event.kind == .Pressed,
.Key_LeftControl => self.left_control_is_pressed = event.kind == .Pressed,
.Key_RightControl => self.right_control_is_pressed = event.kind == .Pressed,
else => {},
}
}
};
pub const Event = struct {
unshifted_key: Key,
kind: Kind,
modifiers: Modifiers,
key: Key,
char: ?u8,
pub fn new(
unshifted_key: Key, shifted_key: ?Key,
kind: Kind, modifiers: *const Modifiers) Event {
return Event {
.unshifted_key = unshifted_key,
.kind = kind,
.modifiers = modifiers.*,
.key = if (shifted_key != null and modifiers.shift_is_pressed())
shifted_key.? else unshifted_key,
.char = null,
};
}
}; | libs/georgios/keyboard.zig |
const std=@import("std");
const debug =std.debug;
const assert = std.debug.assert;
const mem =std.mem;
const encoding =enum.{
path,
pathSegment,
host,
zone,
userPassword,
queryComponent,
fragment,
};
pub const Error = error.{
EscapeError,
InvalidHostError,
};
fn shouldEscape(c : u8, mode: encoding) bool{
if ('A' <= c and c <= 'Z' or 'a' <= c and c <= 'z' or '0' <= c and c <= '9'){
return false;
}
if (mode==encoding.host or mode==encoding.zone){
switch (c){
'!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '[', ']', '<', '>', '"' => return false,
else => {},
}
}
switch(c){
'-', '_', '.', '~' => return false,
'$', '&', '+', ',', '/', ':', ';', '=', '?', '@' => {
switch(mode){
encoding.path =>return c=='?',
encoding.pathSegment => return c == '/' or c == ';' or c == ',' or c == '?',
encoding.userPassword => return c == '@' or c == '/' or c == '?' or c == ':',
encoding.queryComponent => return true,
encoding.fragment => return false,
else => {},
}
},
else => {},
}
if (mode==encoding.fragment){
switch (c){
'!', '(', ')', '*' => return false,
else => {},
}
}
return true;
}
fn ishex ( c : u8) bool{
if ('0' <= c and c <= '9'){
return true ;
}
if ('a' <= c and c <= 'f'){
return true;
}
if ('A' <= c and c <= 'F'){
return true;
}
return false;
}
fn unhex(c:u8) u8{
if ('0' <= c and c <= '9'){
return c - '0';
}
if ('a' <= c and c <= 'f'){
return c - 'a' + 10 ;
}
if ('A' <= c and c <= 'F'){
return c - 'A' + 10 ;
}
return 0 ;
}
fn is25 (s : []const u8)bool{
return mem.eql(u8,s, "%25");
}
fn unescape(a : *std.Buffer, s :[]const u8, mode :encoding) !void{
var n : usize =0;
var hasPlus : bool=true;
var tmpa: [3]u8 =undefined;
var tm =tmpa[0..];
var i : usize =0;
while (i <s.len){
switch (s[i]){
'%' =>{
n=n+1;
if (i+2>= s.len or !ishex(s[i+1]) or !ishex(s[i+2])){
return Error.EscapeError;
}
if (mode==encoding.host and unhex(s[i+1])<9 and !is25(s[i..i+3])){
return Error.EscapeError;
}
if (mode==encoding.zone){
const v =unhex(s[i+1])<<4 | unhex(s[i+2]);
if (!is25(s[i..i+3]) and v!= ' ' and shouldEscape(v,encoding.host)){
return Error.EscapeError;
}
}
i= i+3 ;
},
'+' => {
hasPlus=mode== encoding.queryComponent;
i=i+1;
},
else => {
if ( (mode ==encoding.host or mode ==encoding.zone) and s[i] < 0x80 and shouldEscape(s[i], mode) ){
return Error.InvalidHostError;
}
i= i+1;
}
}
}
if (n==0 and !hasPlus){
try a.append(s);
}else{
try a.resize(s.len - 2*n);
var t = a.toSlice();
var j: usize=0;
i=0;
while(i<s.len) {
switch (s[i]){
'%' => {
t[j]=unhex(s[i+1])<<4 | unhex(s[i+2]);
j= j+1;
i=i+3;
},
'+' => {
if (mode==encoding.queryComponent){
t[j]=' ';
} else {
t[j]='+';
}
j=j+1;
i=i+1;
},
else => {
t[j]=s[i];
j=j+1;
i=i+1;
}
}
}
}
}
pub fn queryUnEscape(a : *std.Buffer, s: []const u8) !void{
return unescape(a,s, encoding.queryComponent);
}
pub fn pathUnescape(a : *std.Buffer, s: []const u8) !void{
return unescape(s, encoding.path);
}
pub fn pathEscape(a: *std.Buffer, s: []const u8)!void{
return escape(a,s, encoding.pathSegment);
}
pub fn queryEscape(a: *std.Buffer, s: []const u8)!void{
return escape(a,s, encoding.queryComponent);
}
fn escape(a: *std.Buffer, s: []const u8, mode:encoding) !void{
var spaceCount: usize =0;
var hexCount: usize =0;
for (s) |c| {
if (shouldEscape(c,mode)){
if (c== ' ' and mode==encoding.queryComponent){
spaceCount=spaceCount+1;
} else{
hexCount=hexCount+1;
}
}
}
if (spaceCount==0 and hexCount==0){
try a.append(s);
} else {
const required =s.len+2*hexCount;
try a.resize(required);
var t = a.toSlice();
var i: usize=0;
if (hexCount==0){
while (i<s.len){
if (s[i]==' '){
t[i]='+';
}else{
t[i]=s[i];
}
i=i+1;
}
} else{
i=0;
var j: usize=0;
const alpha: []const u8 ="0123456789ABCDEF";
while (i<s.len){
const c= s[i];
if (c==' ' and mode==encoding.queryComponent){
t[j]='+' ;
j=j+1;
} else if (shouldEscape(c,mode)){
t[j]='%';
t[j+1]=alpha[c>>4];
t[j+2]=alpha[c&15];
j= j+3 ;
} else{
t[j]=s[i];
j=j+1;
}
i=i+1;
}
}
}
}
// A URL represents a parsed URL (technically, a URI reference).
//
// The general form represented is:
//
// [scheme:][//[userinfo@]host][/]path[?query][#fragment]
//
// URLs that do not start with a slash after the scheme are interpreted as:
//
//scheme:opaque[?query][#fragment]
//
// Note that the Path field is stored in decoded form: /%47%6f%2f becomes /Go/.
// A consequence is that it is impossible to tell which slashes in the Path were
// slashes in the raw URL and which were %2f. This distinction is rarely important,
// but when it is, code must not use Path directly.
// The Parse function sets both Path and RawPath in the URL it returns,
// and URL's String method uses RawPath if it is a valid encoding of Path,
// by calling the EscapedPath method.
pub const URL =struct.{
scheme :? []const u8,
opaque :?[]const u8,
user :?*UserInfo,
host :?[]const u8,
path :?[]const u8,
raw_path :?[]const u8,
force_query : bool,
raw_query :?[]const u8,
fragment :?[]const u8,
allocator: *mem.Allocator,
fn init(allocator : *mem.Allocator)URL{
return URL.{
.scheme=null,
.opaque=null,
.user=null,
.host=null,
.path=null,
.raw_path=null,
.force_query=false,
.raw_query=null,
.fragment=null,
.allocator=allocator,
};
}
fn deinit(u: *URL) void{
if (u.scheme!=null){
u.allocator.free(u.scheme.?);
}
if (u.scheme!=null){
u.allocator.free(u.scheme.?);
}
if (u.opaque!=null){
u.allocator.free(u.opaque.?);
}
if (u.user!=null){
if(u.user.?.username!=null){
u.allocator.free(u.user.?.username.?);
}
if (u.user.?.password!=null){
u.allocator.free(u.user.?.password.?);
}
}
if(u.host!=null){
u.allocator.free(u.host.?);
}
if(u.path!=null){
u.allocator.free(u.path.?);
}
if(u.raw_path!=null){
u.allocator.free(u.raw_path.?);
}
if (u.raw_query!=null){
u.allocator.free(u.raw_query.?);
}
if (u.fragment!=null){
u.allocator.free(u.fragment.?);
}
}
fn getScheme(u: *URI, raw: []const u8) !void{
var i: usize=0;
while(i<raw.len){
const c=raw[i];
if ('a' <= c and c <= 'z' or 'A' <= c and c <= 'Z'){
// do nothing
} else if ('0' <= c and c <= '9' and c == '+' and c == '-' and c == '.'){
if (i==0){
const path= try u.allocator.alloc(u8,raw.len);
mem.copy(u8,path,raw);
u.path=path;
return;
}
} else if (c == ':'){
if (i==0){
return error.MissingProtocolScheme;
}
var a=raw[0..i];
const scheme= try u.allocator.alloc(u8,a.len);
mem.copy(u8,scheme,a);
u.scheme=scheme;
var b=raw[i+1..];
const path= try u.allocator.alloc(u8,b.len);
mem.copy(u8,path,b);
u.path=path;
} else{
// we have encountered an invalid character,
// so there is no valid scheme
const path= try u.allocator.alloc(u8,raw.len);
mem.copy(u8,path,raw);
u.path=path;
return;
}
i=i+1;
}
const path= try u.allocator.alloc(u8,raw.len);
mem.copy(u8,path,raw);
u.path=path;
}
fn parse(u: URL,raw_url []const u8, via_request: bool)!void{
if (raw_url=="" and via_request){
return error.EmptyURL;
}
if (raw_url=="*"){
u.path="*";
return;
}
try u.getScheme(raw_url);
//TODO : lowercase scheme
if (u.path!=null){
const path= try u.allocator.alloc(u8,u.?.path.len);
mem.copy(u8,path,u.?.path);
}
}
};
pub const UserInfo =struct.{
username: ?[]const u8,
password: ?[]<PASSWORD>,
password_set: bool,
fn init(name: []const u8) UserInfo{
return UserInfo.{
.username=name,
.password=<PASSWORD>,
.password_set=false,
};
}
fn initWithPassword(name: []const u8,password:[]const u8)UserInfo{
return UserInfo.{
.username=name,
.password=password,
.password_set=true,
};
}
fn encode(u: *UserInfo, buf: *std.Buffer) !void{
if(u.username!=null){
try escape(buf, u.username.?, encoding.userPassword);
}
if (u.password_set){
try buf.appendByte(':');
try escape(buf, u.username.?, encoding.userPassword);
}
}
}; | src/net/url/url.zig |
const std = @import("std");
const pokemon = @import("pokemon");
const math = std.math;
const gen2 = pokemon.gen2;
const common = pokemon.common;
pub const Trainer = struct {
name: []const u8,
kind: u8,
party: []const gen2.Party.Member.WithBoth,
};
pub const first_trainers = []Trainer{
// FalknerGroup
Trainer{
// "FALKNER@"
.name = "\x85\x80\x8B\x8A\x8D\x84\x91\x50",
.kind = gen2.Party.has_moves,
.party = []gen2.Party.Member.WithBoth{
gen2.Party.Member.WithBoth{
.base = gen2.Party.Member{
.level = 7,
.species = 0x10, // Pidgey
},
.item = undefined,
.moves = [4]u8{
0x21, // Tackle
0xBD, // Mud Slap
0x00,
0x00,
},
},
gen2.Party.Member.WithBoth{
.base = gen2.Party.Member{
.level = 9,
.species = 0x11, // Pidgey
},
.item = undefined,
.moves = [4]u8{
0x21, // Tackle
0xBD, // Mud Slap
0x10, // Gust
0x00,
},
},
},
}};
pub const last_trainers = []Trainer{
// MysticalmanGroup
Trainer{
// "EUSINE@"
.name = "\x84\x94\x92\x88\x8D\x84\x50",
.kind = gen2.Party.has_moves,
.party = []gen2.Party.Member.WithBoth{
gen2.Party.Member.WithBoth{
.base = gen2.Party.Member{
.level = 23,
.species = 0x60, // Drowzee
},
.item = undefined,
.moves = [4]u8{
0x8A, // Dream Eater
0x5F, // Hypnosis
0x32, // Disable
0x5D, // Confusion
},
},
gen2.Party.Member.WithBoth{
.base = gen2.Party.Member{
.level = 23,
.species = 0x5D, // Haunter
},
.item = undefined,
.moves = [4]u8{
0x7A, // Lick
0x5F, // Hypnosis
0xD4, // Mean Look
0xAE, // Curse
},
},
gen2.Party.Member.WithBoth{
.base = gen2.Party.Member{
.level = 25,
.species = 0x65, // Electrode
},
.item = undefined,
.moves = [4]u8{
0x67, // Screech
0x31, // Sonicboom
0x57, // Thunder
0xCD, // Rollout
},
},
},
}};
pub const first_base_stats = []gen2.BasePokemon{
// Bulbasaur
gen2.BasePokemon{
.pokedex_number = 1,
.stats = common.Stats{
.hp = 45,
.attack = 49,
.defense = 49,
.speed = 45,
.sp_attack = 65,
.sp_defense = 65,
},
.types = [2]gen2.Type{ gen2.Type.Grass, gen2.Type.Poison },
.catch_rate = 45,
.base_exp_yield = 64,
.items = [2]u8{ 0, 0 },
.gender_ratio = undefined,
.unknown1 = 100,
.egg_cycles = 20,
.unknown2 = 5,
.dimension_of_front_sprite = undefined,
.blank = undefined,
.growth_rate = common.GrowthRate.MediumSlow,
.egg_group1 = common.EggGroup.Grass,
.egg_group2 = common.EggGroup.Monster,
.machine_learnset = undefined,
}};
pub const last_base_stats = []gen2.BasePokemon{
// Celebi
gen2.BasePokemon{
.pokedex_number = 251,
.stats = common.Stats{
.hp = 100,
.attack = 100,
.defense = 100,
.speed = 100,
.sp_attack = 100,
.sp_defense = 100,
},
.types = [2]gen2.Type{ gen2.Type.Psychic, gen2.Type.Grass },
.catch_rate = 45,
.base_exp_yield = 64,
.items = [2]u8{ 0, 0x6D },
.gender_ratio = undefined,
.unknown1 = 100,
.egg_cycles = 120,
.unknown2 = 5,
.dimension_of_front_sprite = undefined,
.blank = undefined,
.growth_rate = common.GrowthRate.MediumSlow,
.egg_group1 = common.EggGroup.Undiscovered,
.egg_group2 = common.EggGroup.Undiscovered,
.machine_learnset = undefined,
}}; | tools/offset-finder/gen2-constants.zig |
const std = @import("std");
var a: *std.mem.Allocator = undefined;
const stdout = std.io.getStdOut().writer(); //prepare stdout to write in
const Type = enum {
bright,
clear,
dark,
dim,
dotted,
drab,
dull,
faded,
light,
mirrored,
muted,
pale,
plaid,
posh,
shiny,
striped,
vibrant,
wavy,
invalid,
pub fn init(ipt: []const u8) Type {
if (std.mem.eql(u8, ipt, "bright")) {
return Type.bright;
} else if (std.mem.eql(u8, ipt, "clear")) {
return Type.clear;
} else if (std.mem.eql(u8, ipt, "dark")) {
return Type.dark;
} else if (std.mem.eql(u8, ipt, "dim")) {
return Type.dim;
} else if (std.mem.eql(u8, ipt, "dotted")) {
return Type.dotted;
} else if (std.mem.eql(u8, ipt, "drab")) {
return Type.drab;
} else if (std.mem.eql(u8, ipt, "dull")) {
return Type.dull;
} else if (std.mem.eql(u8, ipt, "faded")) {
return Type.faded;
} else if (std.mem.eql(u8, ipt, "light")) {
return Type.light;
} else if (std.mem.eql(u8, ipt, "mirrored")) {
return Type.mirrored;
} else if (std.mem.eql(u8, ipt, "muted")) {
return Type.muted;
} else if (std.mem.eql(u8, ipt, "pale")) {
return Type.pale;
} else if (std.mem.eql(u8, ipt, "plaid")) {
return Type.plaid;
} else if (std.mem.eql(u8, ipt, "posh")) {
return Type.posh;
} else if (std.mem.eql(u8, ipt, "shiny")) {
return Type.shiny;
} else if (std.mem.eql(u8, ipt, "striped")) {
return Type.striped;
} else if (std.mem.eql(u8, ipt, "vibrant")) {
return Type.vibrant;
} else if (std.mem.eql(u8, ipt, "wavy")) {
return Type.wavy;
}
return Type.invalid;
}
};
const Color = enum {
aqua,
beige,
black,
blue,
bronze,
brown,
chartreuse,
coral,
crimson,
cyan,
fuchsia,
gold,
gray,
green,
indigo,
lavender,
lime,
magenta,
maroon,
olive,
orange,
plum,
purple,
red,
salmon,
silver,
tan,
teal,
tomato,
turquoise,
violet,
white,
yellow,
invalid,
pub fn init(ipt: []const u8) Color {
if (std.mem.eql(u8, ipt, "aqua")) {
return Color.aqua;
} else if (std.mem.eql(u8, ipt, "beige")) {
return Color.beige;
} else if (std.mem.eql(u8, ipt, "black")) {
return Color.black;
} else if (std.mem.eql(u8, ipt, "blue")) {
return Color.blue;
} else if (std.mem.eql(u8, ipt, "bronze")) {
return Color.bronze;
} else if (std.mem.eql(u8, ipt, "brown")) {
return Color.brown;
} else if (std.mem.eql(u8, ipt, "chartreuse")) {
return Color.chartreuse;
} else if (std.mem.eql(u8, ipt, "coral")) {
return Color.coral;
} else if (std.mem.eql(u8, ipt, "crimson")) {
return Color.crimson;
} else if (std.mem.eql(u8, ipt, "cyan")) {
return Color.cyan;
} else if (std.mem.eql(u8, ipt, "fuchsia")) {
return Color.fuchsia;
} else if (std.mem.eql(u8, ipt, "gold")) {
return Color.gold;
} else if (std.mem.eql(u8, ipt, "gray")) {
return Color.gray;
} else if (std.mem.eql(u8, ipt, "green")) {
return Color.green;
} else if (std.mem.eql(u8, ipt, "indigo")) {
return Color.indigo;
} else if (std.mem.eql(u8, ipt, "lavender")) {
return Color.lavender;
} else if (std.mem.eql(u8, ipt, "lime")) {
return Color.lime;
} else if (std.mem.eql(u8, ipt, "magenta")) {
return Color.magenta;
} else if (std.mem.eql(u8, ipt, "maroon")) {
return Color.maroon;
} else if (std.mem.eql(u8, ipt, "olive")) {
return Color.olive;
} else if (std.mem.eql(u8, ipt, "orange")) {
return Color.orange;
} else if (std.mem.eql(u8, ipt, "plum")) {
return Color.plum;
} else if (std.mem.eql(u8, ipt, "purple")) {
return Color.purple;
} else if (std.mem.eql(u8, ipt, "red")) {
return Color.red;
} else if (std.mem.eql(u8, ipt, "salmon")) {
return Color.salmon;
} else if (std.mem.eql(u8, ipt, "silver")) {
return Color.silver;
} else if (std.mem.eql(u8, ipt, "tan")) {
return Color.tan;
} else if (std.mem.eql(u8, ipt, "teal")) {
return Color.teal;
} else if (std.mem.eql(u8, ipt, "tomato")) {
return Color.tomato;
} else if (std.mem.eql(u8, ipt, "turquoise")) {
return Color.turquoise;
} else if (std.mem.eql(u8, ipt, "violet")) {
return Color.violet;
} else if (std.mem.eql(u8, ipt, "white")) {
return Color.white;
} else if (std.mem.eql(u8, ipt, "yellow")) {
return Color.yellow;
}
return Color.invalid;
}
};
const BagProperties = struct {
_type: Type, color: Color, amount: u32 = 1
};
const Bag = struct {
definition: BagProperties, children: [10]?BagProperties, children_sum: u32 = 0, visited: bool = false
};
var all_bags: [600]?Bag = [_]?Bag{null} ** 600;
fn count_children(bag: *Bag) u32 {
if (bag.visited) {
return bag.children_sum;
}
var children_sum: u32 = 0;
for (bag.children) |*child_opt| {
if (child_opt.*) |child| {
children_sum += child.amount;
for (all_bags) |*cur_opt| {
if (cur_opt.*) |*cur| {
if (child._type == cur.definition._type and child.color == cur.definition.color) {
children_sum += count_children(cur) * child.amount;
}
}
}
} else {
break;
}
}
bag.children_sum = children_sum;
bag.visited = true;
return children_sum;
}
fn run(input: [:0]u8) u32 {
var out: u32 = 0;
var all_lines_it = std.mem.split(input, "\n");
var bag_number: u16 = 0;
while (all_lines_it.next()) |line| {
if (line.len == 0) {
break;
}
var tokenizer = std.mem.tokenize(line, " ,");
const _type: Type = Type.init(tokenizer.next().?);
const color: Color = Color.init(tokenizer.next().?);
var current: Bag = Bag{
.definition = BagProperties{
._type = _type,
.color = color,
},
.children = [_]?BagProperties{null} ** 10,
};
var children_counter: u8 = 0;
_ = tokenizer.next(); // bags
_ = tokenizer.next(); // contain
while (tokenizer.next()) |token| {
if (std.mem.eql(u8, token, "no")) {
// no other children
break;
}
const c_count: u8 = std.fmt.parseInt(u8, token, 10) catch unreachable;
const c_type: Type = Type.init(tokenizer.next().?);
const c_color: Color = Color.init(tokenizer.next().?);
var child: BagProperties = BagProperties{
._type = c_type,
.color = c_color,
.amount = c_count,
};
_ = tokenizer.next(); // bag(s)
current.children[children_counter] = child;
children_counter += 1;
}
all_bags[bag_number] = current;
bag_number += 1;
}
for (all_bags) |*cur_opt| {
if (cur_opt.*) |*cur| {
if (cur.definition.color == Color.gold and cur.definition._type == Type.shiny) {
return count_children(cur);
}
} else {
break;
}
}
return out;
}
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); // create memory allocator for strings
defer arena.deinit(); // clear memory
var arg_it = std.process.args();
_ = arg_it.skip(); // skip over exe name
a = &arena.allocator; // get ref to allocator
const input: [:0]u8 = try (arg_it.next(a)).?; // get the first argument
const start: i128 = std.time.nanoTimestamp(); // start time
const answer = run(input); // compute answer
const elapsed_nano: f128 = @intToFloat(f128, std.time.nanoTimestamp() - start);
const elapsed_milli: f64 = @floatCast(f64, @divFloor(elapsed_nano, 1_000_000));
try stdout.print("_duration:{d}\n{}\n", .{ elapsed_milli, answer }); // emit actual lines parsed by AOC
}
// TESTS
test "one bag" {
all_bags = [_]?Bag{null} ** 600;
// shiny gold bag contain 1 dark red bag
var children: [10]?BagProperties = [_]?BagProperties{null} ** 10;
children[0] = BagProperties{ .color = Color.red, ._type = Type.dark, .amount = 1 };
var test_bag: Bag = Bag{
.definition = BagProperties{
.color = Color.gold,
._type = Type.shiny,
},
.children = children,
};
all_bags[0] = test_bag;
std.testing.expect(count_children(&test_bag) == 1);
}
test "two bags" {
all_bags = [_]?Bag{null} ** 600;
// shiny gold bag contain 2 shiny cyan bag
var children_1: [10]?BagProperties = [_]?BagProperties{null} ** 10;
children_1[0] = BagProperties{ .color = Color.cyan, ._type = Type.shiny, .amount = 2 };
var test_bag_1: Bag = Bag{
.definition = BagProperties{
.color = Color.red,
._type = Type.light,
},
.children = children_1,
};
// shiny cyan bag contain 1 dark red bag
var children_2: [10]?BagProperties = [_]?BagProperties{null} ** 10;
children_2[0] = BagProperties{ .color = Color.red, ._type = Type.dark, .amount = 1 };
var test_bag_2: Bag = Bag{
.definition = BagProperties{
.color = Color.cyan,
._type = Type.shiny,
},
.children = children_2,
};
all_bags[0] = test_bag_1;
all_bags[1] = test_bag_2;
std.testing.expect(count_children(&test_bag_1) == 4);
}
test "run 1" {
all_bags = [_]?Bag{null} ** 600;
const i =
\\shiny gold bag contain 1 dark red bag
;
var b = i.*;
const ans = run(&b);
std.testing.expect(ans == 1);
}
test "run 2" {
all_bags = [_]?Bag{null} ** 600;
const i =
\\shiny gold bags contain 2 shiny cyan bag.
\\vibrant plum bags contain no other bags.
\\shiny cyan bag contain 3 dark red bag
;
var b = i.*;
const ans = run(&b);
std.testing.expect(ans == 8);
}
test "run 3" {
all_bags = [_]?Bag{null} ** 600;
const i =
\\shiny gold bags contain 1 light red bag.
\\light red bags contain 1 shiny cyan bag.
\\vibrant plum bags contain no other bags.
\\shiny cyan bag contain 1 light olive bag
;
var b = i.*;
const ans = run(&b);
std.testing.expect(ans == 3);
}
test "aoc input 1" {
all_bags = [_]?Bag{null} ** 600;
const i =
\\light red bags contain 1 bright white bag, 2 muted yellow bags.
\\dark orange bags contain 3 bright white bags, 4 muted yellow bags.
\\bright white bags contain 1 shiny gold bag.
\\muted yellow bags contain 2 shiny gold bags, 9 faded blue bags.
\\shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags.
\\dark olive bags contain 3 faded blue bags, 4 dotted black bags.
\\vibrant plum bags contain 5 faded blue bags, 6 dotted black bags.
\\faded blue bags contain no other bags.
\\dotted black bags contain no other bags.
;
var b = i.*;
const ans = run(&b);
std.testing.expect(ans == 32);
}
test "aoc input 2" {
all_bags = [_]?Bag{null} ** 600;
const i =
\\shiny gold bags contain 2 dark red bags.
\\dark red bags contain 2 dark orange bags.
\\dark orange bags contain 2 dark yellow bags.
\\dark yellow bags contain 2 dark green bags.
\\dark green bags contain 2 dark blue bags.
\\dark blue bags contain 2 dark violet bags.
\\dark violet bags contain no other bags.
;
var b = i.*;
const ans = run(&b);
std.testing.expect(ans == 126);
} | day-07/part-2/lelithium.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("audiometa", "src/main.zig");
exe.setTarget(target);
exe.setBuildMode(mode);
exe.addPackagePath("audiometa", "src/audiometa.zig");
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);
// Tests
const test_filter = b.option([]const u8, "test-filter", "Skip tests that do not match filter");
var tests = b.addTest("src/audiometa.zig");
tests.setBuildMode(mode);
tests.setTarget(target);
tests.setFilter(test_filter);
var parse_tests = b.addTest("test/parse_tests.zig");
parse_tests.setBuildMode(mode);
parse_tests.setTarget(target);
parse_tests.setFilter(test_filter);
parse_tests.addPackagePath("audiometa", "src/audiometa.zig");
const test_step = b.step("test", "Run all tests");
test_step.dependOn(&tests.step);
test_step.dependOn(&parse_tests.step);
var test_against_taglib = b.addTest("test/test_against_taglib.zig");
test_against_taglib.setBuildMode(mode);
test_against_taglib.setTarget(target);
test_against_taglib.setFilter(test_filter);
test_against_taglib.addPackagePath("audiometa", "src/audiometa.zig");
const test_against_taglib_step = b.step("test_against_taglib", "Test tag parsing against taglib");
test_against_taglib_step.dependOn(&test_against_taglib.step);
var test_against_ffprobe = b.addTest("test/test_against_ffprobe.zig");
test_against_ffprobe.setBuildMode(mode);
test_against_ffprobe.setTarget(target);
test_against_ffprobe.setFilter(test_filter);
test_against_ffprobe.addPackagePath("audiometa", "src/audiometa.zig");
const test_against_ffprobe_step = b.step("test_against_ffprobe", "Test tag parsing against ffprobe");
test_against_ffprobe_step.dependOn(&test_against_ffprobe.step);
// Tools
const extract_tag_exe = b.addExecutable("extract_tag", "tools/extract_tag.zig");
extract_tag_exe.addPackagePath("audiometa", "src/audiometa.zig");
extract_tag_exe.setTarget(target);
extract_tag_exe.setBuildMode(mode);
extract_tag_exe.install();
const extract_tag_run = extract_tag_exe.run();
extract_tag_run.step.dependOn(b.getInstallStep());
if (b.args) |args| {
extract_tag_run.addArgs(args);
}
const extract_tag_run_step = b.step("run_extract_tag", "Run the extract tag tool");
extract_tag_run_step.dependOn(&extract_tag_run.step);
const synchsafe_exe = b.addExecutable("synchsafe", "tools/synchsafe.zig");
synchsafe_exe.addPackagePath("audiometa", "src/audiometa.zig");
synchsafe_exe.setTarget(target);
synchsafe_exe.setBuildMode(mode);
synchsafe_exe.install();
// Fuzz
_ = addFuzzer(b, "fuzz", &.{}) catch unreachable;
var fuzz_oom = addFuzzer(b, "fuzz-oom", &.{}) catch unreachable;
// setup build options
{
const debug_options = b.addOptions();
debug_options.addOption(bool, "is_zig_debug_version", true);
fuzz_oom.debug_exe.addOptions("build_options", debug_options);
const afl_options = b.addOptions();
afl_options.addOption(bool, "is_zig_debug_version", false);
fuzz_oom.lib.addOptions("build_options", afl_options);
}
}
fn addFuzzer(b: *std.build.Builder, comptime name: []const u8, afl_clang_args: []const []const u8) !FuzzerSteps {
// The library
const fuzz_lib = b.addStaticLibrary(name ++ "-lib", "test/" ++ name ++ ".zig");
fuzz_lib.addPackagePath("audiometa", "src/audiometa.zig");
fuzz_lib.setBuildMode(.Debug);
fuzz_lib.want_lto = true;
fuzz_lib.bundle_compiler_rt = true;
// Setup the output name
const fuzz_executable_name = name;
const fuzz_exe_path = try std.fs.path.join(b.allocator, &.{ b.cache_root, fuzz_executable_name });
// We want `afl-clang-lto -o path/to/output path/to/library`
const fuzz_compile = b.addSystemCommand(&.{ "afl-clang-lto", "-o", fuzz_exe_path });
// Add the path to the library file to afl-clang-lto's args
fuzz_compile.addArtifactArg(fuzz_lib);
// Custom args
fuzz_compile.addArgs(afl_clang_args);
// Install the cached output to the install 'bin' path
const fuzz_install = b.addInstallBinFile(.{ .path = fuzz_exe_path }, fuzz_executable_name);
// Add a top-level step that compiles and installs the fuzz executable
const fuzz_compile_run = b.step(name, "Build executable for fuzz testing '" ++ name ++ "' using afl-clang-lto");
fuzz_compile_run.dependOn(&fuzz_compile.step);
fuzz_compile_run.dependOn(&fuzz_install.step);
// Compile a companion exe for debugging crashes
const fuzz_debug_exe = b.addExecutable(name ++ "-debug", "test/" ++ name ++ ".zig");
fuzz_debug_exe.addPackagePath("audiometa", "src/audiometa.zig");
fuzz_debug_exe.setBuildMode(.Debug);
// Only install fuzz-debug when the fuzz step is run
const install_fuzz_debug_exe = b.addInstallArtifact(fuzz_debug_exe);
fuzz_compile_run.dependOn(&install_fuzz_debug_exe.step);
return FuzzerSteps{
.lib = fuzz_lib,
.debug_exe = fuzz_debug_exe,
};
}
const FuzzerSteps = struct {
lib: *std.build.LibExeObjStep,
debug_exe: *std.build.LibExeObjStep,
pub fn libExes(self: *const FuzzerSteps) [2]*std.build.LibExeObjStep {
return [_]*std.build.LibExeObjStep{ self.lib, self.debug_exe };
}
}; | build.zig |
const is_test = @import("builtin").is_test;
const std = @import("std");
const math = std.math;
const Log2Int = std.math.Log2Int;
const maxInt = std.math.maxInt;
const minInt = std.math.minInt;
const warn = std.debug.warn;
const DBG = false;
pub fn fixint(comptime fp_t: type, comptime fixint_t: type, a: fp_t) fixint_t {
@setRuntimeSafety(is_test);
const D = switch (fixint_t) {
i1 => false, // We can't print i1
else => DBG,
};
const fixuint_t = @IntType(false, fixint_t.bit_count);
const rep_t = switch (fp_t) {
f32 => u32,
f64 => u64,
f128 => u128,
else => unreachable,
};
const srep_t = @IntType(true, rep_t.bit_count);
const significandBits = switch (fp_t) {
f32 => 23,
f64 => 52,
f128 => 112,
else => unreachable,
};
const typeWidth = rep_t.bit_count;
const exponentBits = (typeWidth - significandBits - 1);
const signBit = (rep_t(1) << (significandBits + exponentBits));
const maxExponent = ((1 << exponentBits) - 1);
const exponentBias = (maxExponent >> 1);
const implicitBit = (rep_t(1) << significandBits);
const significandMask = (implicitBit - 1);
// Break a into negative, exponent, significand
const aRep: rep_t = @bitCast(rep_t, a);
const absMask = signBit - 1;
const aAbs: rep_t = aRep & absMask;
const negative = (aRep & signBit) != 0;
const exponent = @intCast(i32, aAbs >> significandBits) - exponentBias;
const significand: rep_t = (aAbs & significandMask) | implicitBit;
if (DBG) warn("negative={x} exponent={}:{x} significand={}:{x}\n", negative, exponent, exponent, significand, significand);
// If exponent is negative, the result is zero.
if (exponent < 0) {
if (DBG) warn("neg exponent result=0:0\n");
return 0;
}
var result: fixint_t = undefined;
const ShiftedResultType = if (fixint_t.bit_count > rep_t.bit_count) fixuint_t else rep_t;
var shifted_result: ShiftedResultType = undefined;
// If the value is too large for the integer type, saturate.
if (@intCast(usize, exponent) >= fixint_t.bit_count) {
result = if (negative) fixint_t(minInt(fixint_t)) else fixint_t(maxInt(fixint_t));
if (D) warn("too large result={}:{x}\n", result, result);
return result;
}
// If 0 <= exponent < significandBits, right shift to get the result.
// Otherwise, shift left.
if (exponent < significandBits) {
if (DBG) warn("exponent:{} < significandBits:{})\n", exponent, usize(significandBits));
var diff = @intCast(ShiftedResultType, significandBits - exponent);
if (DBG) warn("diff={}:{x}\n", diff, diff);
var shift = @intCast(Log2Int(ShiftedResultType), diff);
if (DBG) warn("significand={}:{x} right shift={}:{x}\n", significand, significand, shift, shift);
shifted_result = @intCast(ShiftedResultType, significand) >> shift;
} else {
if (DBG) warn("exponent:{} >= significandBits:{})\n", exponent, usize(significandBits));
var diff = @intCast(ShiftedResultType, exponent - significandBits);
if (DBG) warn("diff={}:{x}\n", diff, diff);
var shift = @intCast(Log2Int(ShiftedResultType), diff);
if (D) warn("significand={}:{x} left shift={}:{x}\n", significand, significand, shift, shift);
shifted_result = @intCast(ShiftedResultType, significand) << shift;
}
if (DBG) warn("shifted_result={}\n", shifted_result);
if (negative) {
// The result will be negative, but shifted_result is unsigned so compare >= -maxInt
if (shifted_result >= -math.minInt(fixint_t)) {
// Saturate
result = math.minInt(fixint_t);
} else {
// Cast shifted_result to result
result = -1 * @intCast(fixint_t, shifted_result);
}
} else {
// The result will be positive
if (shifted_result >= math.maxInt(fixint_t)) {
// Saturate
result = math.maxInt(fixint_t);
} else {
// Cast shifted_result to result
result = @intCast(fixint_t, shifted_result);
}
}
if (D) warn("result={}:{x}\n", result, result);
return result;
}
fn test__fixint(comptime fp_t: type, comptime fixint_t: type, a: fp_t, expected: fixint_t) void {
const x = fixint(fp_t, fixint_t, a);
std.debug.assert(x == expected);
}
test "fixint" {
if (DBG) warn("\n");
test__fixint(f32, i1, -math.inf_f32, -1);
test__fixint(f32, i1, -math.f32_max, -1);
test__fixint(f32, i1, -2.0, -1);
test__fixint(f32, i1, -1.1, -1);
test__fixint(f32, i1, -1.0, -1);
test__fixint(f32, i1, -0.9, 0);
test__fixint(f32, i1, -0.1, 0);
test__fixint(f32, i1, -math.f32_min, 0);
test__fixint(f32, i1, -0.0, 0);
test__fixint(f32, i1, 0.0, 0);
test__fixint(f32, i1, math.f32_min, 0);
test__fixint(f32, i1, 0.1, 0);
test__fixint(f32, i1, 0.9, 0);
test__fixint(f32, i1, 1.0, 0);
test__fixint(f32, i1, 2.0, 0);
test__fixint(f32, i1, math.f32_max, 0);
test__fixint(f32, i1, math.inf_f32, 0);
test__fixint(f32, i2, -math.inf_f32, -2);
test__fixint(f32, i2, -math.f32_max, -2);
test__fixint(f32, i2, -2.0, -2);
test__fixint(f32, i2, -1.9, -1);
test__fixint(f32, i2, -1.1, -1);
test__fixint(f32, i2, -1.0, -1);
test__fixint(f32, i2, -0.9, 0);
test__fixint(f32, i2, -0.1, 0);
test__fixint(f32, i2, -math.f32_min, 0);
test__fixint(f32, i2, -0.0, 0);
test__fixint(f32, i2, 0.0, 0);
test__fixint(f32, i2, math.f32_min, 0);
test__fixint(f32, i2, 0.1, 0);
test__fixint(f32, i2, 0.9, 0);
test__fixint(f32, i2, 1.0, 1);
test__fixint(f32, i2, 2.0, 1);
test__fixint(f32, i2, math.f32_max, 1);
test__fixint(f32, i2, math.inf_f32, 1);
test__fixint(f32, i3, -math.inf_f32, -4);
test__fixint(f32, i3, -math.f32_max, -4);
test__fixint(f32, i3, -4.0, -4);
test__fixint(f32, i3, -3.0, -3);
test__fixint(f32, i3, -2.0, -2);
test__fixint(f32, i3, -1.9, -1);
test__fixint(f32, i3, -1.1, -1);
test__fixint(f32, i3, -1.0, -1);
test__fixint(f32, i3, -0.9, 0);
test__fixint(f32, i3, -0.1, 0);
test__fixint(f32, i3, -math.f32_min, 0);
test__fixint(f32, i3, -0.0, 0);
test__fixint(f32, i3, 0.0, 0);
test__fixint(f32, i3, math.f32_min, 0);
test__fixint(f32, i3, 0.1, 0);
test__fixint(f32, i3, 0.9, 0);
test__fixint(f32, i3, 1.0, 1);
test__fixint(f32, i3, 2.0, 2);
test__fixint(f32, i3, 3.0, 3);
test__fixint(f32, i3, 4.0, 3);
test__fixint(f32, i3, math.f32_max, 3);
test__fixint(f32, i3, math.inf_f32, 3);
test__fixint(f64, i32, -math.inf_f64, math.minInt(i32));
test__fixint(f64, i32, -math.f64_max, math.minInt(i32));
test__fixint(f64, i32, @intToFloat(f64, math.minInt(i32)), math.minInt(i32));
test__fixint(f64, i32, @intToFloat(f64, math.minInt(i32))+1, math.minInt(i32)+1);
test__fixint(f64, i32, -2.0, -2);
test__fixint(f64, i32, -1.9, -1);
test__fixint(f64, i32, -1.1, -1);
test__fixint(f64, i32, -1.0, -1);
test__fixint(f64, i32, -0.9, 0);
test__fixint(f64, i32, -0.1, 0);
test__fixint(f64, i32, -math.f32_min, 0);
test__fixint(f64, i32, -0.0, 0);
test__fixint(f64, i32, 0.0, 0);
test__fixint(f64, i32, math.f32_min, 0);
test__fixint(f64, i32, 0.1, 0);
test__fixint(f64, i32, 0.9, 0);
test__fixint(f64, i32, 1.0, 1);
test__fixint(f64, i32, @intToFloat(f64, math.maxInt(i32))-1, math.maxInt(i32)-1);
test__fixint(f64, i32, @intToFloat(f64, math.maxInt(i32)), math.maxInt(i32));
test__fixint(f64, i32, math.f64_max, math.maxInt(i32));
test__fixint(f64, i32, math.inf_f64, math.maxInt(i32));
test__fixint(f64, i64, -math.inf_f64, math.minInt(i64));
test__fixint(f64, i64, -math.f64_max, math.minInt(i64));
test__fixint(f64, i64, @intToFloat(f64, math.minInt(i64)), math.minInt(i64));
test__fixint(f64, i64, @intToFloat(f64, math.minInt(i64))+1, math.minInt(i64));
test__fixint(f64, i64, -2.0, -2);
test__fixint(f64, i64, -1.9, -1);
test__fixint(f64, i64, -1.1, -1);
test__fixint(f64, i64, -1.0, -1);
test__fixint(f64, i64, -0.9, 0);
test__fixint(f64, i64, -0.1, 0);
test__fixint(f64, i64, -math.f32_min, 0);
test__fixint(f64, i64, -0.0, 0);
test__fixint(f64, i64, 0.0, 0);
test__fixint(f64, i64, math.f32_min, 0);
test__fixint(f64, i64, 0.1, 0);
test__fixint(f64, i64, 0.9, 0);
test__fixint(f64, i64, 1.0, 1);
test__fixint(f64, i64, @intToFloat(f64, math.maxInt(i64))-1, math.maxInt(i64));
test__fixint(f64, i64, @intToFloat(f64, math.maxInt(i64)), math.maxInt(i64));
test__fixint(f64, i64, math.f64_max, math.maxInt(i64));
test__fixint(f64, i64, math.inf_f64, math.maxInt(i64));
test__fixint(f64, i128, -math.inf_f64, math.minInt(i128));
test__fixint(f64, i128, -math.f64_max, math.minInt(i128));
test__fixint(f64, i128, @intToFloat(f64, math.minInt(i128)), math.minInt(i128));
test__fixint(f64, i128, @intToFloat(f64, math.minInt(i128))+1, math.minInt(i128));
test__fixint(f64, i128, -2.0, -2);
test__fixint(f64, i128, -1.9, -1);
test__fixint(f64, i128, -1.1, -1);
test__fixint(f64, i128, -1.0, -1);
test__fixint(f64, i128, -0.9, 0);
test__fixint(f64, i128, -0.1, 0);
test__fixint(f64, i128, -math.f32_min, 0);
test__fixint(f64, i128, -0.0, 0);
test__fixint(f64, i128, 0.0, 0);
test__fixint(f64, i128, math.f32_min, 0);
test__fixint(f64, i128, 0.1, 0);
test__fixint(f64, i128, 0.9, 0);
test__fixint(f64, i128, 1.0, 1);
test__fixint(f64, i128, @intToFloat(f64, math.maxInt(i128))-1, math.maxInt(i128));
test__fixint(f64, i128, @intToFloat(f64, math.maxInt(i128)), math.maxInt(i128));
test__fixint(f64, i128, math.f64_max, math.maxInt(i128));
test__fixint(f64, i128, math.inf_f64, math.maxInt(i128));
test__fixint(f64, i128, 0x1.0p+0, i128(1) << 0);
test__fixint(f64, i128, 0x1.0p+1, i128(1) << 1);
test__fixint(f64, i128, 0x1.0p+2, i128(1) << 2);
test__fixint(f64, i128, 0x1.0p+50, i128(1) << 50);
test__fixint(f64, i128, 0x1.0p+51, i128(1) << 51);
test__fixint(f64, i128, 0x1.0p+52, i128(1) << 52);
test__fixint(f64, i128, 0x1.0p+53, i128(1) << 53);
test__fixint(f64, i128, 0x1.0p+125, i128(0x1) << 125-0);
test__fixint(f64, i128, 0x1.8p+125, i128(0x3) << 125-1);
test__fixint(f64, i128, 0x1.Cp+125, i128(0x7) << 125-2);
test__fixint(f64, i128, 0x1.Ep+125, i128(0xF) << 125-3);
test__fixint(f64, i128, 0x1.Fp+125, i128(0x1F) << 125-4);
test__fixint(f64, i128, 0x1.F8p+125, i128(0x3F) << 125-5);
test__fixint(f64, i128, 0x1.FCp+125, i128(0x7F) << 125-6);
test__fixint(f64, i128, 0x1.FEp+125, i128(0xFF) << 125-7);
test__fixint(f64, i128, 0x1.FFp+125, i128(0x1FF) << 125-8);
test__fixint(f64, i128, 0x1.FF8p+125, i128(0x3FF) << 125-9);
test__fixint(f64, i128, 0x1.FFFp+125, i128(0x1FFF) << 125-12);
test__fixint(f64, i128, 0x1.FFFFp+125, i128(0x1FFFF) << 125-16);
test__fixint(f64, i128, 0x1.FFFFFp+125, i128(0x1FFFFF) << 125-20);
test__fixint(f64, i128, 0x1.FFFFFFFFFp+125, i128(0x1FFFFFFFFF) << 125-36);
test__fixint(f64, i128, 0x1.FFFFFFFFFFFFEp+125, i128(0xFFFFFFFFFFFFF) << 125-51);
test__fixint(f64, i128, 0x1.FFFFFFFFFFFFFp+125, i128(0x1FFFFFFFFFFFFF) << 125-52);
} | float_to_int/fixint.zig |
const std = @import("std");
const log = std.log;
const cuda = @import("cudaz");
const cu = cuda.cu;
const ShmemReduce = cuda.Function("shmem_reduce_kernel");
const GlobalReduce = cuda.Function("global_reduce_kernel");
pub fn main() !void {
log.info("***** Lesson 3 ******", .{});
var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};
const gpa = general_purpose_allocator.allocator();
var stream = try cuda.Stream.init(0);
try main_reduce(&stream, gpa);
try main_histo(&stream, gpa);
}
fn main_reduce(stream: *const cuda.Stream, gpa: std.mem.Allocator) !void {
const array_size: i32 = 1 << 20;
// generate the input array on the host
var h_in = try gpa.alloc(f32, array_size);
defer gpa.free(h_in);
log.debug("h_in = {*}", .{h_in.ptr});
var prng = std.rand.DefaultPrng.init(0).random();
var sum: f32 = 0.0;
for (h_in) |*value| {
// generate random float in [-1.0f, 1.0f]
var v = -1.0 + prng.float(f32) * 2.0;
value.* = v;
sum += v;
}
log.info("original sum = {}", .{sum});
// allocate GPU memory
var d_in = try cuda.allocAndCopy(f32, h_in);
defer cuda.free(d_in);
var d_intermediate = try cuda.alloc(f32, array_size); // overallocated
defer cuda.free(d_intermediate);
var d_out = try cuda.alloc(f32, 1);
defer cuda.free(d_out);
// launch the kernel
// Run shared_reduced first because it doesn't modify d_in
_ = try benchmark_reduce(stream, 100, d_out, d_intermediate, d_in, true);
_ = try benchmark_reduce(stream, 100, d_out, d_intermediate, d_in, false);
}
fn benchmark_reduce(
stream: *const cuda.Stream,
iter: u32,
d_out: []f32,
d_intermediate: []f32,
d_in: []f32,
uses_shared_memory: bool,
) !f32 {
if (uses_shared_memory) {
log.info("Running shared memory reduce {} times.", .{iter});
} else {
log.info("Running global reduce {} times.", .{iter});
}
log.info("using cuda: {}", .{cuda});
var reduce_kernel: GlobalReduce = undefined;
if (uses_shared_memory) {
reduce_kernel = GlobalReduce{ .f = (try ShmemReduce.init()).f };
} else {
reduce_kernel = try GlobalReduce.init();
}
// Set the buffers to 0 to have correct computation on the first try
try cuda.memset(f32, d_intermediate, 0.0);
try cuda.memset(f32, d_out, 0.0);
var timer = cuda.GpuTimer.start(stream);
errdefer timer.deinit();
var result: f32 = undefined;
var i: usize = 0;
while (i < iter) : (i += 1) {
var r_i = try reduce(
stream,
reduce_kernel,
d_out,
d_intermediate,
d_in,
uses_shared_memory,
);
if (i == 0) {
result = r_i;
}
}
timer.stop();
var avg_time = timer.elapsed() / @intToFloat(f32, iter) * 1000.0;
log.info("average time elapsed: {d:.1}ms", .{avg_time});
log.info("found sum = {}", .{result});
return result;
}
fn reduce(stream: *const cuda.Stream, reduce_kernel: GlobalReduce, d_out: []f32, d_intermediate: []f32, d_in: []f32, uses_shared_memory: bool) !f32 {
// assumes that size is not greater than blockSize^2
// and that size is a multiple of blockSize
const blockSize: usize = 1024;
var size = d_in.len;
if (size % blockSize != 0 or size > blockSize * blockSize) {
log.err("Can't run reduce operator on an array of size {} with blockSize={} ({})", .{ size, blockSize, blockSize * blockSize });
@panic("Invalid reduce on too big array");
}
const full_grid = cuda.Grid.init1D(size, blockSize);
var shared_mem = if (uses_shared_memory) blockSize * @sizeOf(f32) else 0;
try reduce_kernel.launchWithSharedMem(
stream,
full_grid,
shared_mem,
.{ d_intermediate.ptr, d_in.ptr },
);
// try cuda.synchronize();
// now we're down to one block left, so reduce it
const one_block = cuda.Grid.init1D(blockSize, 0);
try reduce_kernel.launchWithSharedMem(
stream,
one_block,
shared_mem,
.{ d_out.ptr, d_intermediate.ptr },
);
// try cuda.synchronize();
var result: [1]f32 = undefined;
try cuda.memcpyDtoH(f32, &result, d_out);
return result[0];
}
fn main_histo(stream: *const cuda.Stream, gpa: std.mem.Allocator) !void {
const array_size = 65536;
const bin_count = 16;
// generate the input array on the host
var cpu_bins = [_]i32{0} ** bin_count;
var h_in = try gpa.alloc(i32, array_size);
for (h_in) |*value, i| {
var item = bit_reverse(@intCast(i32, i), log2(array_size));
value.* = item;
cpu_bins[@intCast(usize, @mod(item, bin_count))] += 1;
}
log.info("Cpu bins: {any}", .{cpu_bins});
var naive_bins = [_]i32{0} ** bin_count;
var simple_bins = [_]i32{0} ** bin_count;
// allocate GPU memory
var d_in = try cuda.allocAndCopy(i32, h_in);
var d_bins = try cuda.allocAndCopy(i32, &naive_bins);
log.info("Running naive histo", .{});
const grid = cuda.Grid{ .blocks = .{ .x = @divExact(array_size, 64) }, .threads = .{ .x = 64 } };
const naive_histo = try cuda.Function("naive_histo").init();
try naive_histo.launch(stream, grid, .{ .@"0" = d_bins.ptr, .@"1" = d_in.ptr, .@"2" = bin_count });
try cuda.memcpyDtoH(i32, &naive_bins, d_bins);
log.info("naive bins: {any}", .{naive_bins});
log.info("Running simple histo", .{});
try cuda.memcpyHtoD(i32, d_bins, &simple_bins);
const simple_histo = try cuda.Function("simple_histo").init();
try simple_histo.launch(stream, grid, .{ .@"0" = d_bins.ptr, .@"1" = d_in.ptr, .@"2" = bin_count });
try cuda.memcpyDtoH(i32, &simple_bins, d_bins);
log.info("simple bins: {any}", .{simple_bins});
}
fn log2(i: i32) u5 {
var r: u5 = 0;
var j = i;
while (j > 0) : (j >>= 1) {
r += 1;
}
return r;
}
fn bit_reverse(w: i32, bits: u5) i32 {
var r: i32 = 0;
var i: u5 = 0;
while (i < bits) : (i += 1) {
const bit = (w & (@intCast(i32, 1) << i)) >> i;
r |= bit << (bits - i - 1);
}
return r;
} | CS344/src/lesson3.zig |
const std = @import("std");
pub fn EmbeddedRingQueue(comptime TElement: type) type {
const assert = std.debug.assert;
return struct {
const Self = @This();
pub const Error = error{
Empty,
Full,
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
pub const Element = TElement;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
head: usize = 0,
tail: usize = 0,
storage: []Element = &.{},
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
pub fn init(buffer: []Element) Self {
return .{ .storage = buffer };
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
pub fn capacity(self: Self) usize {
return self.storage.len;
}
pub fn len(self: Self) usize {
return self.tail -% self.head;
}
pub fn empty(self: Self) bool {
return self.len() == 0;
}
pub fn full(self: Self) bool {
return self.len() == self.capacity();
}
pub fn clear(self: *Self) void {
self.head = 0;
self.tail = 0;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
pub fn enqueue(self: *Self, value: Element) Error!void {
if (self.enqueueIfNotFull(value)) {
return;
}
return Error.Full;
}
pub fn dequeue(self: *Self) Error!Element {
var value: Element = undefined;
if (self.dequeueIfNotEmpty(&value)) {
return value;
}
return Error.Empty;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
pub fn enqueueIfNotFull(self: *Self, value: Element) bool {
if (self.full()) {
return false;
}
self.enqueueUnchecked(value);
return true;
}
pub fn dequeueIfNotEmpty(self: *Self, value: *Element) bool {
if (self.empty()) {
return false;
}
self.dequeueUnchecked(value);
return true;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
pub fn enqueueAssumeNotFull(self: *Self, value: Element) void {
assert(!self.full());
self.enqueueUnchecked(value);
}
pub fn dequeueAssumeNotEmpty(self: *Self) Element {
assert(!self.empty());
var value: Element = undefined;
self.dequeueUnchecked(&value);
return value;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
pub fn enqueueUnchecked(self: *Self, value: Element) void {
const tail_index = self.tail % self.storage.len;
self.storage[tail_index] = value;
self.tail +%= 1;
}
pub fn dequeueUnchecked(self: *Self, value: *Element) void {
const head_index = self.head % self.storage.len;
value.* = self.storage[head_index];
self.head +%= 1;
}
};
}
//------------------------------------------------------------------------------
const expectEqual = std.testing.expectEqual;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
test "EmbeddedRingQueue basics" {
var buffer: [16]usize = undefined;
var queue = EmbeddedRingQueue(usize).init(buffer[0..]);
try expectEqual(buffer.len, queue.capacity());
try expectEqual(@as(usize, 0), queue.len());
try expectEqual(true, queue.empty());
try expectEqual(false, queue.full());
for (buffer) |_, i| {
try expectEqual(i, queue.len());
try queue.enqueue(i);
try expectEqual(i, buffer[i]);
}
try expectEqual(buffer.len, queue.capacity());
try expectEqual(buffer.len, queue.len());
try expectEqual(false, queue.empty());
try expectEqual(true, queue.full());
for (buffer) |_, i| {
try expectEqual(buffer.len - i, queue.len());
const j = try queue.dequeue();
try expectEqual(i, j);
}
try expectEqual(buffer.len, queue.capacity());
try expectEqual(@as(usize, 0), queue.len());
try expectEqual(true, queue.empty());
try expectEqual(false, queue.full());
for (buffer) |_, i| {
try expectEqual(i, queue.len());
try queue.enqueue(i);
try expectEqual(i, buffer[i]);
}
try expectEqual(buffer.len, queue.capacity());
try expectEqual(buffer.len, queue.len());
try expectEqual(false, queue.empty());
try expectEqual(true, queue.full());
queue.clear();
try expectEqual(buffer.len, queue.capacity());
try expectEqual(@as(usize, 0), queue.len());
try expectEqual(true, queue.empty());
try expectEqual(false, queue.full());
}
//------------------------------------------------------------------------------ | libs/zpool/src/embedded_ring_queue.zig |
const std = @import("../std.zig");
const math = std.math;
const expect = std.testing.expect;
/// Returns e raised to the power of x (e^x).
///
/// Special Cases:
/// - exp(+inf) = +inf
/// - exp(nan) = nan
pub fn exp(x: anytype) @TypeOf(x) {
const T = @TypeOf(x);
return switch (T) {
f32 => exp32(x),
f64 => exp64(x),
else => @compileError("exp not implemented for " ++ @typeName(T)),
};
}
fn exp32(x_: f32) f32 {
const half = [_]f32{ 0.5, -0.5 };
const ln2hi = 6.9314575195e-1;
const ln2lo = 1.4286067653e-6;
const invln2 = 1.4426950216e+0;
const P1 = 1.6666625440e-1;
const P2 = -2.7667332906e-3;
var x = x_;
var hx = @bitCast(u32, x);
const sign = @intCast(i32, hx >> 31);
hx &= 0x7FFFFFFF;
if (math.isNan(x)) {
return x;
}
// |x| >= -87.33655 or nan
if (hx >= 0x42AEAC50) {
// nan
if (hx > 0x7F800000) {
return x;
}
// x >= 88.722839
if (hx >= 0x42b17218 and sign == 0) {
return x * 0x1.0p127;
}
if (sign != 0) {
math.doNotOptimizeAway(-0x1.0p-149 / x); // overflow
// x <= -103.972084
if (hx >= 0x42CFF1B5) {
return 0;
}
}
}
var k: i32 = undefined;
var hi: f32 = undefined;
var lo: f32 = undefined;
// |x| > 0.5 * ln2
if (hx > 0x3EB17218) {
// |x| > 1.5 * ln2
if (hx > 0x3F851592) {
k = @floatToInt(i32, invln2 * x + half[@intCast(usize, sign)]);
} else {
k = 1 - sign - sign;
}
const fk = @intToFloat(f32, k);
hi = x - fk * ln2hi;
lo = fk * ln2lo;
x = hi - lo;
}
// |x| > 2^(-14)
else if (hx > 0x39000000) {
k = 0;
hi = x;
lo = 0;
} else {
math.doNotOptimizeAway(0x1.0p127 + x); // inexact
return 1 + x;
}
const xx = x * x;
const c = x - xx * (P1 + xx * P2);
const y = 1 + (x * c / (2 - c) - lo + hi);
if (k == 0) {
return y;
} else {
return math.scalbn(y, k);
}
}
fn exp64(x_: f64) f64 {
const half = [_]f64{ 0.5, -0.5 };
const ln2hi: f64 = 6.93147180369123816490e-01;
const ln2lo: f64 = 1.90821492927058770002e-10;
const invln2: f64 = 1.44269504088896338700e+00;
const P1: f64 = 1.66666666666666019037e-01;
const P2: f64 = -2.77777777770155933842e-03;
const P3: f64 = 6.61375632143793436117e-05;
const P4: f64 = -1.65339022054652515390e-06;
const P5: f64 = 4.13813679705723846039e-08;
var x = x_;
var ux = @bitCast(u64, x);
var hx = ux >> 32;
const sign = @intCast(i32, hx >> 31);
hx &= 0x7FFFFFFF;
if (math.isNan(x)) {
return x;
}
// |x| >= 708.39 or nan
if (hx >= 0x4086232B) {
// nan
if (hx > 0x7FF00000) {
return x;
}
if (x > 709.782712893383973096) {
// overflow if x != inf
if (!math.isInf(x)) {
math.raiseOverflow();
}
return math.inf(f64);
}
if (x < -708.39641853226410622) {
// underflow if x != -inf
// math.doNotOptimizeAway(@as(f32, -0x1.0p-149 / x));
if (x < -745.13321910194110842) {
return 0;
}
}
}
// argument reduction
var k: i32 = undefined;
var hi: f64 = undefined;
var lo: f64 = undefined;
// |x| > 0.5 * ln2
if (hx > 0x3EB17218) {
// |x| >= 1.5 * ln2
if (hx > 0x3FF0A2B2) {
k = @floatToInt(i32, invln2 * x + half[@intCast(usize, sign)]);
} else {
k = 1 - sign - sign;
}
const dk = @intToFloat(f64, k);
hi = x - dk * ln2hi;
lo = dk * ln2lo;
x = hi - lo;
}
// |x| > 2^(-28)
else if (hx > 0x3E300000) {
k = 0;
hi = x;
lo = 0;
} else {
// inexact if x != 0
// math.doNotOptimizeAway(0x1.0p1023 + x);
return 1 + x;
}
const xx = x * x;
const c = x - xx * (P1 + xx * (P2 + xx * (P3 + xx * (P4 + xx * P5))));
const y = 1 + (x * c / (2 - c) - lo + hi);
if (k == 0) {
return y;
} else {
return math.scalbn(y, k);
}
}
test "math.exp" {
expect(exp(@as(f32, 0.0)) == exp32(0.0));
expect(exp(@as(f64, 0.0)) == exp64(0.0));
}
test "math.exp32" {
const epsilon = 0.000001;
expect(exp32(0.0) == 1.0);
expect(math.approxEqAbs(f32, exp32(0.0), 1.0, epsilon));
expect(math.approxEqAbs(f32, exp32(0.2), 1.221403, epsilon));
expect(math.approxEqAbs(f32, exp32(0.8923), 2.440737, epsilon));
expect(math.approxEqAbs(f32, exp32(1.5), 4.481689, epsilon));
}
test "math.exp64" {
const epsilon = 0.000001;
expect(exp64(0.0) == 1.0);
expect(math.approxEqAbs(f64, exp64(0.0), 1.0, epsilon));
expect(math.approxEqAbs(f64, exp64(0.2), 1.221403, epsilon));
expect(math.approxEqAbs(f64, exp64(0.8923), 2.440737, epsilon));
expect(math.approxEqAbs(f64, exp64(1.5), 4.481689, epsilon));
}
test "math.exp32.special" {
expect(math.isPositiveInf(exp32(math.inf(f32))));
expect(math.isNan(exp32(math.nan(f32))));
}
test "math.exp64.special" {
expect(math.isPositiveInf(exp64(math.inf(f64))));
expect(math.isNan(exp64(math.nan(f64))));
} | lib/std/math/exp.zig |
const std = @import("std");
const builtin = std.builtin;
const page_size = std.mem.page_size;
pub const tokenizer = @import("c/tokenizer.zig");
pub const Token = tokenizer.Token;
pub const Tokenizer = tokenizer.Tokenizer;
pub const parse = @import("c/parse.zig").parse;
pub const ast = @import("c/ast.zig");
test "" {
_ = tokenizer;
}
pub usingnamespace @import("os/bits.zig");
pub usingnamespace switch (std.Target.current.os.tag) {
.linux => @import("c/linux.zig"),
.windows => @import("c/windows.zig"),
.macos, .ios, .tvos, .watchos => @import("c/darwin.zig"),
.freebsd, .kfreebsd => @import("c/freebsd.zig"),
.netbsd => @import("c/netbsd.zig"),
.dragonfly => @import("c/dragonfly.zig"),
.openbsd => @import("c/openbsd.zig"),
.haiku => @import("c/haiku.zig"),
.hermit => @import("c/hermit.zig"),
.solaris => @import("c/solaris.zig"),
.fuchsia => @import("c/fuchsia.zig"),
.minix => @import("c/minix.zig"),
.emscripten => @import("c/emscripten.zig"),
else => struct {},
};
pub fn getErrno(rc: anytype) u16 {
if (rc == -1) {
return @intCast(u16, _errno().*);
} else {
return 0;
}
}
/// The return type is `type` to force comptime function call execution.
/// TODO: https://github.com/ziglang/zig/issues/425
/// If not linking libc, returns struct{pub const ok = false;}
/// If linking musl libc, returns struct{pub const ok = true;}
/// If linking gnu libc (glibc), the `ok` value will be true if the target
/// version is greater than or equal to `glibc_version`.
/// If linking a libc other than these, returns `false`.
pub fn versionCheck(glibc_version: builtin.Version) type {
return struct {
pub const ok = blk: {
if (!builtin.link_libc) break :blk false;
if (std.Target.current.abi.isMusl()) break :blk true;
if (std.Target.current.isGnuLibC()) {
const ver = std.Target.current.os.version_range.linux.glibc;
const order = ver.order(glibc_version);
break :blk switch (order) {
.gt, .eq => true,
.lt => false,
};
} else {
break :blk false;
}
};
};
}
pub extern "c" var environ: [*:null]?[*:0]u8;
pub extern "c" fn fopen(filename: [*:0]const u8, modes: [*:0]const u8) ?*FILE;
pub extern "c" fn fclose(stream: *FILE) c_int;
pub extern "c" fn fwrite(ptr: [*]const u8, size_of_type: usize, item_count: usize, stream: *FILE) usize;
pub extern "c" fn fread(ptr: [*]u8, size_of_type: usize, item_count: usize, stream: *FILE) usize;
pub extern "c" fn printf(format: [*:0]const u8, ...) c_int;
pub extern "c" fn abort() noreturn;
pub extern "c" fn exit(code: c_int) noreturn;
pub extern "c" fn isatty(fd: fd_t) c_int;
pub extern "c" fn close(fd: fd_t) c_int;
pub extern "c" fn lseek(fd: fd_t, offset: off_t, whence: c_int) off_t;
pub extern "c" fn open(path: [*:0]const u8, oflag: c_uint, ...) c_int;
pub extern "c" fn openat(fd: c_int, path: [*:0]const u8, oflag: c_uint, ...) c_int;
pub extern "c" fn ftruncate(fd: c_int, length: off_t) c_int;
pub extern "c" fn raise(sig: c_int) c_int;
pub extern "c" fn read(fd: fd_t, buf: [*]u8, nbyte: usize) isize;
pub extern "c" fn readv(fd: c_int, iov: [*]const iovec, iovcnt: c_uint) isize;
pub extern "c" fn pread(fd: fd_t, buf: [*]u8, nbyte: usize, offset: u64) isize;
pub extern "c" fn preadv(fd: c_int, iov: [*]const iovec, iovcnt: c_uint, offset: u64) isize;
pub extern "c" fn writev(fd: c_int, iov: [*]const iovec_const, iovcnt: c_uint) isize;
pub extern "c" fn pwritev(fd: c_int, iov: [*]const iovec_const, iovcnt: c_uint, offset: u64) isize;
pub extern "c" fn write(fd: fd_t, buf: [*]const u8, nbyte: usize) isize;
pub extern "c" fn pwrite(fd: fd_t, buf: [*]const u8, nbyte: usize, offset: u64) isize;
pub extern "c" fn mmap(addr: ?*align(page_size) c_void, len: usize, prot: c_uint, flags: c_uint, fd: fd_t, offset: u64) *c_void;
pub extern "c" fn munmap(addr: *align(page_size) c_void, len: usize) c_int;
pub extern "c" fn mprotect(addr: *align(page_size) c_void, len: usize, prot: c_uint) c_int;
pub extern "c" fn unlink(path: [*:0]const u8) c_int;
pub extern "c" fn unlinkat(dirfd: fd_t, path: [*:0]const u8, flags: c_uint) c_int;
pub extern "c" fn getcwd(buf: [*]u8, size: usize) ?[*]u8;
pub extern "c" fn waitpid(pid: c_int, stat_loc: *c_uint, options: c_uint) c_int;
pub extern "c" fn fork() c_int;
pub extern "c" fn access(path: [*:0]const u8, mode: c_uint) c_int;
pub extern "c" fn faccessat(dirfd: fd_t, path: [*:0]const u8, mode: c_uint, flags: c_uint) c_int;
pub extern "c" fn pipe(fds: *[2]fd_t) c_int;
pub extern "c" fn pipe2(fds: *[2]fd_t, flags: u32) c_int;
pub extern "c" fn mkdir(path: [*:0]const u8, mode: c_uint) c_int;
pub extern "c" fn mkdirat(dirfd: fd_t, path: [*:0]const u8, mode: u32) c_int;
pub extern "c" fn symlink(existing: [*:0]const u8, new: [*:0]const u8) c_int;
pub extern "c" fn symlinkat(oldpath: [*:0]const u8, newdirfd: fd_t, newpath: [*:0]const u8) c_int;
pub extern "c" fn rename(old: [*:0]const u8, new: [*:0]const u8) c_int;
pub extern "c" fn renameat(olddirfd: fd_t, old: [*:0]const u8, newdirfd: fd_t, new: [*:0]const u8) c_int;
pub extern "c" fn chdir(path: [*:0]const u8) c_int;
pub extern "c" fn fchdir(fd: fd_t) c_int;
pub extern "c" fn execve(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8, envp: [*:null]const ?[*:0]const u8) c_int;
pub extern "c" fn dup(fd: fd_t) c_int;
pub extern "c" fn dup2(old_fd: fd_t, new_fd: fd_t) c_int;
pub extern "c" fn readlink(noalias path: [*:0]const u8, noalias buf: [*]u8, bufsize: usize) isize;
pub extern "c" fn readlinkat(dirfd: fd_t, noalias path: [*:0]const u8, noalias buf: [*]u8, bufsize: usize) isize;
pub usingnamespace switch (builtin.os.tag) {
.macos, .ios, .watchos, .tvos => struct {
pub const realpath = @"realpath$DARWIN_EXTSN";
pub const fstatat = _fstatat;
},
else => struct {
pub extern "c" fn realpath(noalias file_name: [*:0]const u8, noalias resolved_name: [*]u8) ?[*:0]u8;
pub extern "c" fn fstatat(dirfd: fd_t, path: [*:0]const u8, stat_buf: *libc_stat, flags: u32) c_int;
},
};
pub extern "c" fn rmdir(path: [*:0]const u8) c_int;
pub extern "c" fn getenv(name: [*:0]const u8) ?[*:0]u8;
pub extern "c" fn sysctl(name: [*]const c_int, namelen: c_uint, oldp: ?*c_void, oldlenp: ?*usize, newp: ?*c_void, newlen: usize) c_int;
pub extern "c" fn sysctlbyname(name: [*:0]const u8, oldp: ?*c_void, oldlenp: ?*usize, newp: ?*c_void, newlen: usize) c_int;
pub extern "c" fn sysctlnametomib(name: [*:0]const u8, mibp: ?*c_int, sizep: ?*usize) c_int;
pub extern "c" fn tcgetattr(fd: fd_t, termios_p: *termios) c_int;
pub extern "c" fn tcsetattr(fd: fd_t, optional_action: TCSA, termios_p: *const termios) c_int;
pub extern "c" fn fcntl(fd: fd_t, cmd: c_int, ...) c_int;
pub extern "c" fn flock(fd: fd_t, operation: c_int) c_int;
pub extern "c" fn ioctl(fd: fd_t, request: c_int, ...) c_int;
pub extern "c" fn uname(buf: *utsname) c_int;
pub extern "c" fn gethostname(name: [*]u8, len: usize) c_int;
pub extern "c" fn shutdown(socket: fd_t, how: c_int) c_int;
pub extern "c" fn bind(socket: fd_t, address: ?*const sockaddr, address_len: socklen_t) c_int;
pub extern "c" fn socketpair(domain: c_uint, sock_type: c_uint, protocol: c_uint, sv: *[2]fd_t) c_int;
pub extern "c" fn listen(sockfd: fd_t, backlog: c_uint) c_int;
pub extern "c" fn getsockname(sockfd: fd_t, noalias addr: *sockaddr, noalias addrlen: *socklen_t) c_int;
pub extern "c" fn connect(sockfd: fd_t, sock_addr: *const sockaddr, addrlen: socklen_t) c_int;
pub extern "c" fn accept(sockfd: fd_t, addr: ?*sockaddr, addrlen: ?*socklen_t) c_int;
pub extern "c" fn accept4(sockfd: fd_t, addr: ?*sockaddr, addrlen: ?*socklen_t, flags: c_uint) c_int;
pub extern "c" fn getsockopt(sockfd: fd_t, level: u32, optname: u32, optval: ?*c_void, optlen: *socklen_t) c_int;
pub extern "c" fn setsockopt(sockfd: fd_t, level: u32, optname: u32, optval: ?*const c_void, optlen: socklen_t) c_int;
pub extern "c" fn send(sockfd: fd_t, buf: *const c_void, len: usize, flags: u32) isize;
pub extern "c" fn sendto(
sockfd: fd_t,
buf: *const c_void,
len: usize,
flags: u32,
dest_addr: ?*const sockaddr,
addrlen: socklen_t,
) isize;
pub extern fn recv(sockfd: fd_t, arg1: ?*c_void, arg2: usize, arg3: c_int) isize;
pub extern fn recvfrom(
sockfd: fd_t,
noalias buf: *c_void,
len: usize,
flags: u32,
noalias src_addr: ?*sockaddr,
noalias addrlen: ?*socklen_t,
) isize;
pub usingnamespace switch (builtin.os.tag) {
.netbsd => struct {
pub const clock_getres = __clock_getres50;
pub const clock_gettime = __clock_gettime50;
pub const fstat = __fstat50;
pub const getdents = __getdents30;
pub const getrusage = __getrusage50;
pub const gettimeofday = __gettimeofday50;
pub const nanosleep = __nanosleep50;
pub const sched_yield = __libc_thr_yield;
pub const sigaction = __sigaction14;
pub const sigaltstack = __sigaltstack14;
pub const sigprocmask = __sigprocmask14;
pub const stat = __stat50;
},
.macos, .ios, .watchos, .tvos => struct {
// XXX: close -> close$NOCANCEL
// XXX: getdirentries -> _getdirentries64
pub extern "c" fn clock_getres(clk_id: c_int, tp: *timespec) c_int;
pub extern "c" fn clock_gettime(clk_id: c_int, tp: *timespec) c_int;
pub const fstat = _fstat;
pub extern "c" fn getrusage(who: c_int, usage: *rusage) c_int;
pub extern "c" fn gettimeofday(noalias tv: ?*timeval, noalias tz: ?*timezone) c_int;
pub extern "c" fn nanosleep(rqtp: *const timespec, rmtp: ?*timespec) c_int;
pub extern "c" fn sched_yield() c_int;
pub extern "c" fn sigaction(sig: c_int, noalias act: *const Sigaction, noalias oact: ?*Sigaction) c_int;
pub extern "c" fn sigprocmask(how: c_int, noalias set: ?*const sigset_t, noalias oset: ?*sigset_t) c_int;
pub extern "c" fn socket(domain: c_uint, sock_type: c_uint, protocol: c_uint) c_int;
pub extern "c" fn stat(noalias path: [*:0]const u8, noalias buf: *libc_stat) c_int;
},
.windows => struct {
// TODO: copied the else case and removed the socket function (because its in ws2_32)
// need to verify which of these is actually supported on windows
pub extern "c" fn clock_getres(clk_id: c_int, tp: *timespec) c_int;
pub extern "c" fn clock_gettime(clk_id: c_int, tp: *timespec) c_int;
pub extern "c" fn fstat(fd: fd_t, buf: *libc_stat) c_int;
pub extern "c" fn getrusage(who: c_int, usage: *rusage) c_int;
pub extern "c" fn gettimeofday(noalias tv: ?*timeval, noalias tz: ?*timezone) c_int;
pub extern "c" fn nanosleep(rqtp: *const timespec, rmtp: ?*timespec) c_int;
pub extern "c" fn sched_yield() c_int;
pub extern "c" fn sigaction(sig: c_int, noalias act: *const Sigaction, noalias oact: ?*Sigaction) c_int;
pub extern "c" fn sigprocmask(how: c_int, noalias set: ?*const sigset_t, noalias oset: ?*sigset_t) c_int;
pub extern "c" fn stat(noalias path: [*:0]const u8, noalias buf: *libc_stat) c_int;
},
else => struct {
pub extern "c" fn clock_getres(clk_id: c_int, tp: *timespec) c_int;
pub extern "c" fn clock_gettime(clk_id: c_int, tp: *timespec) c_int;
pub extern "c" fn fstat(fd: fd_t, buf: *libc_stat) c_int;
pub extern "c" fn getrusage(who: c_int, usage: *rusage) c_int;
pub extern "c" fn gettimeofday(noalias tv: ?*timeval, noalias tz: ?*timezone) c_int;
pub extern "c" fn nanosleep(rqtp: *const timespec, rmtp: ?*timespec) c_int;
pub extern "c" fn sched_yield() c_int;
pub extern "c" fn sigaction(sig: c_int, noalias act: *const Sigaction, noalias oact: ?*Sigaction) c_int;
pub extern "c" fn sigprocmask(how: c_int, noalias set: ?*const sigset_t, noalias oset: ?*sigset_t) c_int;
pub extern "c" fn socket(domain: c_uint, sock_type: c_uint, protocol: c_uint) c_int;
pub extern "c" fn stat(noalias path: [*:0]const u8, noalias buf: *libc_stat) c_int;
},
};
pub extern "c" fn kill(pid: pid_t, sig: c_int) c_int;
pub extern "c" fn getdirentries(fd: fd_t, buf_ptr: [*]u8, nbytes: usize, basep: *i64) isize;
pub extern "c" fn setuid(uid: uid_t) c_int;
pub extern "c" fn setgid(gid: gid_t) c_int;
pub extern "c" fn seteuid(euid: uid_t) c_int;
pub extern "c" fn setegid(egid: gid_t) c_int;
pub extern "c" fn setreuid(ruid: uid_t, euid: uid_t) c_int;
pub extern "c" fn setregid(rgid: gid_t, egid: gid_t) c_int;
pub extern "c" fn setresuid(ruid: uid_t, euid: uid_t, suid: uid_t) c_int;
pub extern "c" fn setresgid(rgid: gid_t, egid: gid_t, sgid: gid_t) c_int;
pub extern "c" fn malloc(usize) ?*c_void;
pub extern "c" fn realloc(?*c_void, usize) ?*c_void;
pub extern "c" fn free(*c_void) void;
pub extern "c" fn futimes(fd: fd_t, times: *[2]timeval) c_int;
pub extern "c" fn utimes(path: [*:0]const u8, times: *[2]timeval) c_int;
pub extern "c" fn utimensat(dirfd: fd_t, pathname: [*:0]const u8, times: *[2]timespec, flags: u32) c_int;
pub extern "c" fn futimens(fd: fd_t, times: *const [2]timespec) c_int;
pub extern "c" fn pthread_create(noalias newthread: *pthread_t, noalias attr: ?*const pthread_attr_t, start_routine: fn (?*c_void) callconv(.C) ?*c_void, noalias arg: ?*c_void) c_int;
pub extern "c" fn pthread_attr_init(attr: *pthread_attr_t) c_int;
pub extern "c" fn pthread_attr_setstack(attr: *pthread_attr_t, stackaddr: *c_void, stacksize: usize) c_int;
pub extern "c" fn pthread_attr_setguardsize(attr: *pthread_attr_t, guardsize: usize) c_int;
pub extern "c" fn pthread_attr_destroy(attr: *pthread_attr_t) c_int;
pub extern "c" fn pthread_self() pthread_t;
pub extern "c" fn pthread_join(thread: pthread_t, arg_return: ?*?*c_void) c_int;
pub extern "c" fn kqueue() c_int;
pub extern "c" fn kevent(
kq: c_int,
changelist: [*]const Kevent,
nchanges: c_int,
eventlist: [*]Kevent,
nevents: c_int,
timeout: ?*const timespec,
) c_int;
pub extern "c" fn getaddrinfo(
noalias node: [*:0]const u8,
noalias service: [*:0]const u8,
noalias hints: *const addrinfo,
noalias res: **addrinfo,
) EAI;
pub extern "c" fn freeaddrinfo(res: *addrinfo) void;
pub extern "c" fn getnameinfo(
noalias addr: *const sockaddr,
addrlen: socklen_t,
noalias host: [*]u8,
hostlen: socklen_t,
noalias serv: [*]u8,
servlen: socklen_t,
flags: u32,
) EAI;
pub extern "c" fn gai_strerror(errcode: EAI) [*:0]const u8;
pub extern "c" fn poll(fds: [*]pollfd, nfds: nfds_t, timeout: c_int) c_int;
pub extern "c" fn ppoll(fds: [*]pollfd, nfds: nfds_t, timeout: ?*const timespec, sigmask: ?*const sigset_t) c_int;
pub extern "c" fn dn_expand(
msg: [*:0]const u8,
eomorig: [*:0]const u8,
comp_dn: [*:0]const u8,
exp_dn: [*:0]u8,
length: c_int,
) c_int;
pub const PTHREAD_MUTEX_INITIALIZER = pthread_mutex_t{};
pub extern "c" fn pthread_mutex_lock(mutex: *pthread_mutex_t) c_int;
pub extern "c" fn pthread_mutex_unlock(mutex: *pthread_mutex_t) c_int;
pub extern "c" fn pthread_mutex_destroy(mutex: *pthread_mutex_t) c_int;
pub const PTHREAD_COND_INITIALIZER = pthread_cond_t{};
pub extern "c" fn pthread_cond_wait(noalias cond: *pthread_cond_t, noalias mutex: *pthread_mutex_t) c_int;
pub extern "c" fn pthread_cond_timedwait(noalias cond: *pthread_cond_t, noalias mutex: *pthread_mutex_t, noalias abstime: *const timespec) c_int;
pub extern "c" fn pthread_cond_signal(cond: *pthread_cond_t) c_int;
pub extern "c" fn pthread_cond_broadcast(cond: *pthread_cond_t) c_int;
pub extern "c" fn pthread_cond_destroy(cond: *pthread_cond_t) c_int;
pub const pthread_t = *opaque {};
pub const FILE = opaque {};
pub extern "c" fn dlopen(path: [*:0]const u8, mode: c_int) ?*c_void;
pub extern "c" fn dlclose(handle: *c_void) c_int;
pub extern "c" fn dlsym(handle: ?*c_void, symbol: [*:0]const u8) ?*c_void;
pub extern "c" fn sync() void;
pub extern "c" fn syncfs(fd: c_int) c_int;
pub extern "c" fn fsync(fd: c_int) c_int;
pub extern "c" fn fdatasync(fd: c_int) c_int;
pub extern "c" fn prctl(option: c_int, ...) c_int;
pub extern "c" fn getrlimit(resource: rlimit_resource, rlim: *rlimit) c_int;
pub extern "c" fn setrlimit(resource: rlimit_resource, rlim: *const rlimit) c_int;
pub const max_align_t = if (std.Target.current.abi == .msvc)
f64
else if (std.Target.current.isDarwin())
c_longdouble
else
extern struct {
a: c_longlong,
b: c_longdouble,
}; | lib/std/c.zig |
const tests = @import("tests.zig");
const builtin = @import("builtin");
pub fn addCases(cases: *tests.TranslateCContext) void {
if (builtin.os != builtin.Os.windows) {
// Windows treats this as an enum with type c_int
cases.add("big negative enum init values when C ABI supports long long enums",
\\enum EnumWithInits {
\\ VAL01 = 0,
\\ VAL02 = 1,
\\ VAL03 = 2,
\\ VAL04 = 3,
\\ VAL05 = -1,
\\ VAL06 = -2,
\\ VAL07 = -3,
\\ VAL08 = -4,
\\ VAL09 = VAL02 + VAL08,
\\ VAL10 = -1000012000,
\\ VAL11 = -1000161000,
\\ VAL12 = -1000174001,
\\ VAL13 = VAL09,
\\ VAL14 = VAL10,
\\ VAL15 = VAL11,
\\ VAL16 = VAL13,
\\ VAL17 = (VAL16 - VAL10 + 1),
\\ VAL18 = 0x1000000000000000L,
\\ VAL19 = VAL18 + VAL18 + VAL18 - 1,
\\ VAL20 = VAL19 + VAL19,
\\ VAL21 = VAL20 + 0xFFFFFFFFFFFFFFFF,
\\ VAL22 = 0xFFFFFFFFFFFFFFFF + 1,
\\ VAL23 = 0xFFFFFFFFFFFFFFFF,
\\};
,
\\pub const enum_EnumWithInits = extern enum(c_longlong) {
\\ VAL01 = 0,
\\ VAL02 = 1,
\\ VAL03 = 2,
\\ VAL04 = 3,
\\ VAL05 = -1,
\\ VAL06 = -2,
\\ VAL07 = -3,
\\ VAL08 = -4,
\\ VAL09 = -3,
\\ VAL10 = -1000012000,
\\ VAL11 = -1000161000,
\\ VAL12 = -1000174001,
\\ VAL13 = -3,
\\ VAL14 = -1000012000,
\\ VAL15 = -1000161000,
\\ VAL16 = -3,
\\ VAL17 = 1000011998,
\\ VAL18 = 1152921504606846976,
\\ VAL19 = 3458764513820540927,
\\ VAL20 = 6917529027641081854,
\\ VAL21 = 6917529027641081853,
\\ VAL22 = 0,
\\ VAL23 = -1,
\\};
);
}
cases.add("predefined expressions",
\\void foo(void) {
\\ __func__;
\\ __FUNCTION__;
\\ __PRETTY_FUNCTION__;
\\}
,
\\pub fn foo() void {
\\ _ = c"foo";
\\ _ = c"foo";
\\ _ = c"void foo(void)";
\\}
);
cases.add("ignore result",
\\void foo() {
\\ int a;
\\ 1;
\\ "hey";
\\ 1 + 1;
\\ 1 - 1;
\\ a = 1;
\\}
,
\\pub fn foo() void {
\\ var a: c_int = undefined;
\\ _ = 1;
\\ _ = c"hey";
\\ _ = (1 + 1);
\\ _ = (1 - 1);
\\ a = 1;
\\}
);
cases.add("for loop with var init but empty body",
\\void foo(void) {
\\ for (int x = 0; x < 10; x++);
\\}
,
\\pub fn foo() void {
\\ {
\\ var x: c_int = 0;
\\ while (x < 10) : (x += 1) {}
\\ }
\\}
);
cases.add("do while with empty body",
\\void foo(void) {
\\ do ; while (1);
\\}
, // TODO this should be if (1 != 0) break
\\pub fn foo() void {
\\ while (true) {
\\ {}
\\ if (!1) break;
\\ }
\\}
);
cases.add("for with empty body",
\\void foo(void) {
\\ for (;;);
\\}
,
\\pub fn foo() void {
\\ while (true) {}
\\}
);
cases.add("while with empty body",
\\void foo(void) {
\\ while (1);
\\}
,
\\pub fn foo() void {
\\ while (1 != 0) {}
\\}
);
cases.add("double define struct",
\\typedef struct Bar Bar;
\\typedef struct Foo Foo;
\\
\\struct Foo {
\\ Foo *a;
\\};
\\
\\struct Bar {
\\ Foo *a;
\\};
,
\\pub const struct_Foo = extern struct {
\\ a: [*c]Foo,
\\};
\\pub const Foo = struct_Foo;
\\pub const struct_Bar = extern struct {
\\ a: [*c]Foo,
\\};
);
cases.addAllowWarnings("simple data types",
\\#include <stdint.h>
\\int foo(char a, unsigned char b, signed char c);
\\int foo(char a, unsigned char b, signed char c); // test a duplicate prototype
\\void bar(uint8_t a, uint16_t b, uint32_t c, uint64_t d);
\\void baz(int8_t a, int16_t b, int32_t c, int64_t d);
,
\\pub extern fn foo(a: u8, b: u8, c: i8) c_int;
,
\\pub extern fn bar(a: u8, b: u16, c: u32, d: u64) void;
,
\\pub extern fn baz(a: i8, b: i16, c: i32, d: i64) void;
);
cases.add("noreturn attribute",
\\void foo(void) __attribute__((noreturn));
,
\\pub extern fn foo() noreturn;
);
cases.addC("simple function",
\\int abs(int a) {
\\ return a < 0 ? -a : a;
\\}
,
\\export fn abs(a: c_int) c_int {
\\ return if (a < 0) -a else a;
\\}
);
cases.add("enums",
\\enum Foo {
\\ FooA,
\\ FooB,
\\ Foo1,
\\};
,
\\pub const enum_Foo = extern enum {
\\ A,
\\ B,
\\ @"1",
\\};
,
\\pub const FooA = enum_Foo.A;
,
\\pub const FooB = enum_Foo.B;
,
\\pub const Foo1 = enum_Foo.@"1";
,
\\pub const Foo = enum_Foo;
);
cases.add("enums",
\\enum Foo {
\\ FooA = 2,
\\ FooB = 5,
\\ Foo1,
\\};
,
\\pub const enum_Foo = extern enum {
\\ A = 2,
\\ B = 5,
\\ @"1" = 6,
\\};
,
\\pub const FooA = enum_Foo.A;
,
\\pub const FooB = enum_Foo.B;
,
\\pub const Foo1 = enum_Foo.@"1";
,
\\pub const Foo = enum_Foo;
);
cases.add("restrict -> noalias",
\\void foo(void *restrict bar, void *restrict);
,
\\pub extern fn foo(noalias bar: ?*c_void, noalias arg1: ?*c_void) void;
);
cases.add("simple struct",
\\struct Foo {
\\ int x;
\\ char *y;
\\};
,
\\const struct_Foo = extern struct {
\\ x: c_int,
\\ y: [*c]u8,
\\};
,
\\pub const Foo = struct_Foo;
);
cases.add("qualified struct and enum",
\\struct Foo {
\\ int x;
\\ int y;
\\};
\\enum Bar {
\\ BarA,
\\ BarB,
\\};
\\void func(struct Foo *a, enum Bar **b);
,
\\pub const struct_Foo = extern struct {
\\ x: c_int,
\\ y: c_int,
\\};
,
\\pub const enum_Bar = extern enum {
\\ A,
\\ B,
\\};
,
\\pub const BarA = enum_Bar.A;
,
\\pub const BarB = enum_Bar.B;
,
\\pub extern fn func(a: [*c]struct_Foo, b: [*c]([*c]enum_Bar)) void;
,
\\pub const Foo = struct_Foo;
,
\\pub const Bar = enum_Bar;
);
cases.add("constant size array",
\\void func(int array[20]);
,
\\pub extern fn func(array: [*c]c_int) void;
);
cases.add("self referential struct with function pointer",
\\struct Foo {
\\ void (*derp)(struct Foo *foo);
\\};
,
\\pub const struct_Foo = extern struct {
\\ derp: ?extern fn([*c]struct_Foo) void,
\\};
,
\\pub const Foo = struct_Foo;
);
cases.add("struct prototype used in func",
\\struct Foo;
\\struct Foo *some_func(struct Foo *foo, int x);
,
\\pub const struct_Foo = @OpaqueType();
,
\\pub extern fn some_func(foo: ?*struct_Foo, x: c_int) ?*struct_Foo;
,
\\pub const Foo = struct_Foo;
);
cases.add("#define a char literal",
\\#define A_CHAR 'a'
,
\\pub const A_CHAR = 97;
);
cases.add("#define an unsigned integer literal",
\\#define CHANNEL_COUNT 24
,
\\pub const CHANNEL_COUNT = 24;
);
cases.add("#define referencing another #define",
\\#define THING2 THING1
\\#define THING1 1234
,
\\pub const THING1 = 1234;
,
\\pub const THING2 = THING1;
);
cases.add("variables",
\\extern int extern_var;
\\static const int int_var = 13;
,
\\pub extern var extern_var: c_int;
,
\\pub const int_var: c_int = 13;
);
cases.add("circular struct definitions",
\\struct Bar;
\\
\\struct Foo {
\\ struct Bar *next;
\\};
\\
\\struct Bar {
\\ struct Foo *next;
\\};
,
\\pub const struct_Bar = extern struct {
\\ next: [*c]struct_Foo,
\\};
,
\\pub const struct_Foo = extern struct {
\\ next: [*c]struct_Bar,
\\};
);
cases.add("typedef void",
\\typedef void Foo;
\\Foo fun(Foo *a);
,
\\pub const Foo = c_void;
,
\\pub extern fn fun(a: ?*Foo) Foo;
);
cases.add("generate inline func for #define global extern fn",
\\extern void (*fn_ptr)(void);
\\#define foo fn_ptr
\\
\\extern char (*fn_ptr2)(int, float);
\\#define bar fn_ptr2
,
\\pub extern var fn_ptr: ?extern fn() void;
,
\\pub inline fn foo() void {
\\ return fn_ptr.?();
\\}
,
\\pub extern var fn_ptr2: ?extern fn(c_int, f32) u8;
,
\\pub inline fn bar(arg0: c_int, arg1: f32) u8 {
\\ return fn_ptr2.?(arg0, arg1);
\\}
);
cases.add("#define string",
\\#define foo "a string"
,
\\pub const foo = c"a string";
);
cases.add("__cdecl doesn't mess up function pointers",
\\void foo(void (__cdecl *fn_ptr)(void));
,
\\pub extern fn foo(fn_ptr: ?extern fn() void) void;
);
cases.add("comment after integer literal",
\\#define SDL_INIT_VIDEO 0x00000020 /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */
,
\\pub const SDL_INIT_VIDEO = 32;
);
cases.add("u integer suffix after hex literal",
\\#define SDL_INIT_VIDEO 0x00000020u /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */
,
\\pub const SDL_INIT_VIDEO = c_uint(32);
);
cases.add("l integer suffix after hex literal",
\\#define SDL_INIT_VIDEO 0x00000020l /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */
,
\\pub const SDL_INIT_VIDEO = c_long(32);
);
cases.add("ul integer suffix after hex literal",
\\#define SDL_INIT_VIDEO 0x00000020ul /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */
,
\\pub const SDL_INIT_VIDEO = c_ulong(32);
);
cases.add("lu integer suffix after hex literal",
\\#define SDL_INIT_VIDEO 0x00000020lu /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */
,
\\pub const SDL_INIT_VIDEO = c_ulong(32);
);
cases.add("ll integer suffix after hex literal",
\\#define SDL_INIT_VIDEO 0x00000020ll /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */
,
\\pub const SDL_INIT_VIDEO = c_longlong(32);
);
cases.add("ull integer suffix after hex literal",
\\#define SDL_INIT_VIDEO 0x00000020ull /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */
,
\\pub const SDL_INIT_VIDEO = c_ulonglong(32);
);
cases.add("llu integer suffix after hex literal",
\\#define SDL_INIT_VIDEO 0x00000020llu /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */
,
\\pub const SDL_INIT_VIDEO = c_ulonglong(32);
);
cases.add("zig keywords in C code",
\\struct comptime {
\\ int defer;
\\};
,
\\pub const struct_comptime = extern struct {
\\ @"defer": c_int,
\\};
,
\\pub const @"comptime" = struct_comptime;
);
cases.add("macro defines string literal with hex",
\\#define FOO "aoeu\xab derp"
\\#define FOO2 "aoeu\x0007a derp"
\\#define FOO_CHAR '\xfF'
,
\\pub const FOO = c"aoeu\xab derp";
,
\\pub const FOO2 = c"aoeuz derp";
,
\\pub const FOO_CHAR = 255;
);
cases.add("macro defines string literal with octal",
\\#define FOO "aoeu\023 derp"
\\#define FOO2 "aoeu\0234 derp"
\\#define FOO_CHAR '\077'
,
\\pub const FOO = c"aoeu\x13 derp";
,
\\pub const FOO2 = c"aoeu\x134 derp";
,
\\pub const FOO_CHAR = 63;
);
cases.add("macro with parens around negative number",
\\#define LUA_GLOBALSINDEX (-10002)
,
\\pub const LUA_GLOBALSINDEX = -10002;
);
cases.addC("post increment",
\\unsigned foo1(unsigned a) {
\\ a++;
\\ return a;
\\}
\\int foo2(int a) {
\\ a++;
\\ return a;
\\}
,
\\pub export fn foo1(_arg_a: c_uint) c_uint {
\\ var a = _arg_a;
\\ a +%= 1;
\\ return a;
\\}
\\pub export fn foo2(_arg_a: c_int) c_int {
\\ var a = _arg_a;
\\ a += 1;
\\ return a;
\\}
);
cases.addC("shift right assign",
\\int log2(unsigned a) {
\\ int i = 0;
\\ while (a > 0) {
\\ a >>= 1;
\\ }
\\ return i;
\\}
,
\\pub export fn log2(_arg_a: c_uint) c_int {
\\ var a = _arg_a;
\\ var i: c_int = 0;
\\ while (a > c_uint(0)) {
\\ a >>= @import("std").math.Log2Int(c_uint)(1);
\\ }
\\ return i;
\\}
);
cases.addC("if statement",
\\int max(int a, int b) {
\\ if (a < b)
\\ return b;
\\
\\ if (a < b)
\\ return b;
\\ else
\\ return a;
\\
\\ if (a < b) ; else ;
\\}
,
\\pub export fn max(a: c_int, b: c_int) c_int {
\\ if (a < b) return b;
\\ if (a < b) return b else return a;
\\ if (a < b) {} else {}
\\}
);
cases.addC("==, !=",
\\int max(int a, int b) {
\\ if (a == b)
\\ return a;
\\ if (a != b)
\\ return b;
\\ return a;
\\}
,
\\pub export fn max(a: c_int, b: c_int) c_int {
\\ if (a == b) return a;
\\ if (a != b) return b;
\\ return a;
\\}
);
cases.addC("add, sub, mul, div, rem",
\\int s(int a, int b) {
\\ int c;
\\ c = a + b;
\\ c = a - b;
\\ c = a * b;
\\ c = a / b;
\\ c = a % b;
\\}
\\unsigned u(unsigned a, unsigned b) {
\\ unsigned c;
\\ c = a + b;
\\ c = a - b;
\\ c = a * b;
\\ c = a / b;
\\ c = a % b;
\\}
,
\\pub export fn s(a: c_int, b: c_int) c_int {
\\ var c: c_int = undefined;
\\ c = (a + b);
\\ c = (a - b);
\\ c = (a * b);
\\ c = @divTrunc(a, b);
\\ c = @rem(a, b);
\\}
\\pub export fn u(a: c_uint, b: c_uint) c_uint {
\\ var c: c_uint = undefined;
\\ c = (a +% b);
\\ c = (a -% b);
\\ c = (a *% b);
\\ c = (a / b);
\\ c = (a % b);
\\}
);
cases.addC("bitwise binary operators",
\\int max(int a, int b) {
\\ return (a & b) ^ (a | b);
\\}
,
\\pub export fn max(a: c_int, b: c_int) c_int {
\\ return (a & b) ^ (a | b);
\\}
);
cases.addC("logical and, logical or",
\\int max(int a, int b) {
\\ if (a < b || a == b)
\\ return b;
\\ if (a >= b && a == b)
\\ return a;
\\ return a;
\\}
,
\\pub export fn max(a: c_int, b: c_int) c_int {
\\ if ((a < b) or (a == b)) return b;
\\ if ((a >= b) and (a == b)) return a;
\\ return a;
\\}
);
cases.addC("logical and, logical or on none bool values",
\\int and_or_none_bool(int a, float b, void *c) {
\\ if (a && b) return 0;
\\ if (b && c) return 1;
\\ if (a && c) return 2;
\\ if (a || b) return 3;
\\ if (b || c) return 4;
\\ if (a || c) return 5;
\\ return 6;
\\}
,
\\pub export fn and_or_none_bool(a: c_int, b: f32, c: ?*c_void) c_int {
\\ if ((a != 0) and (b != 0)) return 0;
\\ if ((b != 0) and (c != 0)) return 1;
\\ if ((a != 0) and (c != 0)) return 2;
\\ if ((a != 0) or (b != 0)) return 3;
\\ if ((b != 0) or (c != 0)) return 4;
\\ if ((a != 0) or (c != 0)) return 5;
\\ return 6;
\\}
);
cases.addC("assign",
\\int max(int a) {
\\ int tmp;
\\ tmp = a;
\\ a = tmp;
\\}
,
\\pub export fn max(_arg_a: c_int) c_int {
\\ var a = _arg_a;
\\ var tmp: c_int = undefined;
\\ tmp = a;
\\ a = tmp;
\\}
);
cases.addC("chaining assign",
\\void max(int a) {
\\ int b, c;
\\ c = b = a;
\\}
,
\\pub export fn max(a: c_int) void {
\\ var b: c_int = undefined;
\\ var c: c_int = undefined;
\\ c = (x: {
\\ const _tmp = a;
\\ b = _tmp;
\\ break :x _tmp;
\\ });
\\}
);
cases.addC("shift right assign with a fixed size type",
\\#include <stdint.h>
\\int log2(uint32_t a) {
\\ int i = 0;
\\ while (a > 0) {
\\ a >>= 1;
\\ }
\\ return i;
\\}
,
\\pub export fn log2(_arg_a: u32) c_int {
\\ var a = _arg_a;
\\ var i: c_int = 0;
\\ while (a > c_uint(0)) {
\\ a >>= u5(1);
\\ }
\\ return i;
\\}
);
cases.add("anonymous enum",
\\enum {
\\ One,
\\ Two,
\\};
,
\\pub const One = 0;
\\pub const Two = 1;
);
cases.addC("function call",
\\static void bar(void) { }
\\static int baz(void) { return 0; }
\\void foo(void) {
\\ bar();
\\ baz();
\\}
,
\\pub fn bar() void {}
\\pub fn baz() c_int {
\\ return 0;
\\}
\\pub export fn foo() void {
\\ bar();
\\ _ = baz();
\\}
);
cases.addC("field access expression",
\\struct Foo {
\\ int field;
\\};
\\int read_field(struct Foo *foo) {
\\ return foo->field;
\\}
,
\\pub const struct_Foo = extern struct {
\\ field: c_int,
\\};
\\pub export fn read_field(foo: [*c]struct_Foo) c_int {
\\ return foo.?.field;
\\}
);
cases.addC("null statements",
\\void foo(void) {
\\ ;;;;;
\\}
,
\\pub export fn foo() void {
\\ {}
\\ {}
\\ {}
\\ {}
\\ {}
\\}
);
cases.add("undefined array global",
\\int array[100];
,
\\pub var array: [100]c_int = undefined;
);
cases.addC("array access",
\\int array[100];
\\int foo(int index) {
\\ return array[index];
\\}
,
\\pub var array: [100]c_int = undefined;
\\pub export fn foo(index: c_int) c_int {
\\ return array[index];
\\}
);
cases.addC("c style cast",
\\int float_to_int(float a) {
\\ return (int)a;
\\}
,
\\pub export fn float_to_int(a: f32) c_int {
\\ return c_int(a);
\\}
);
cases.addC("void cast",
\\void foo(int a) {
\\ (void) a;
\\}
,
\\pub export fn foo(a: c_int) void {
\\ _ = a;
\\}
);
cases.addC("implicit cast to void *",
\\void *foo(unsigned short *x) {
\\ return x;
\\}
,
\\pub export fn foo(x: [*c]c_ushort) ?*c_void {
\\ return @ptrCast(?*c_void, x);
\\}
);
cases.addC("sizeof",
\\#include <stddef.h>
\\size_t size_of(void) {
\\ return sizeof(int);
\\}
,
\\pub export fn size_of() usize {
\\ return @sizeOf(c_int);
\\}
);
cases.addC("null pointer implicit cast",
\\int* foo(void) {
\\ return 0;
\\}
,
\\pub export fn foo() [*c]c_int {
\\ return 0;
\\}
);
cases.addC("comma operator",
\\int foo(void) {
\\ return 1, 2;
\\}
,
\\pub export fn foo() c_int {
\\ return x: {
\\ _ = 1;
\\ break :x 2;
\\ };
\\}
);
cases.addC("statement expression",
\\int foo(void) {
\\ return ({
\\ int a = 1;
\\ a;
\\ });
\\}
,
\\pub export fn foo() c_int {
\\ return x: {
\\ var a: c_int = 1;
\\ break :x a;
\\ };
\\}
);
cases.addC("__extension__ cast",
\\int foo(void) {
\\ return __extension__ 1;
\\}
,
\\pub export fn foo() c_int {
\\ return 1;
\\}
);
cases.addC("bitshift",
\\int foo(void) {
\\ return (1 << 2) >> 1;
\\}
,
\\pub export fn foo() c_int {
\\ return (1 << @import("std").math.Log2Int(c_int)(2)) >> @import("std").math.Log2Int(c_int)(1);
\\}
);
cases.addC("compound assignment operators",
\\void foo(void) {
\\ int a = 0;
\\ a += (a += 1);
\\ a -= (a -= 1);
\\ a *= (a *= 1);
\\ a &= (a &= 1);
\\ a |= (a |= 1);
\\ a ^= (a ^= 1);
\\ a >>= (a >>= 1);
\\ a <<= (a <<= 1);
\\}
,
\\pub export fn foo() void {
\\ var a: c_int = 0;
\\ a += (x: {
\\ const _ref = &a;
\\ _ref.* = (_ref.* + 1);
\\ break :x _ref.*;
\\ });
\\ a -= (x: {
\\ const _ref = &a;
\\ _ref.* = (_ref.* - 1);
\\ break :x _ref.*;
\\ });
\\ a *= (x: {
\\ const _ref = &a;
\\ _ref.* = (_ref.* * 1);
\\ break :x _ref.*;
\\ });
\\ a &= (x: {
\\ const _ref = &a;
\\ _ref.* = (_ref.* & 1);
\\ break :x _ref.*;
\\ });
\\ a |= (x: {
\\ const _ref = &a;
\\ _ref.* = (_ref.* | 1);
\\ break :x _ref.*;
\\ });
\\ a ^= (x: {
\\ const _ref = &a;
\\ _ref.* = (_ref.* ^ 1);
\\ break :x _ref.*;
\\ });
\\ a >>= @import("std").math.Log2Int(c_int)((x: {
\\ const _ref = &a;
\\ _ref.* = (_ref.* >> @import("std").math.Log2Int(c_int)(1));
\\ break :x _ref.*;
\\ }));
\\ a <<= @import("std").math.Log2Int(c_int)((x: {
\\ const _ref = &a;
\\ _ref.* = (_ref.* << @import("std").math.Log2Int(c_int)(1));
\\ break :x _ref.*;
\\ }));
\\}
);
cases.addC("compound assignment operators unsigned",
\\void foo(void) {
\\ unsigned a = 0;
\\ a += (a += 1);
\\ a -= (a -= 1);
\\ a *= (a *= 1);
\\ a &= (a &= 1);
\\ a |= (a |= 1);
\\ a ^= (a ^= 1);
\\ a >>= (a >>= 1);
\\ a <<= (a <<= 1);
\\}
,
\\pub export fn foo() void {
\\ var a: c_uint = c_uint(0);
\\ a +%= (x: {
\\ const _ref = &a;
\\ _ref.* = (_ref.* +% c_uint(1));
\\ break :x _ref.*;
\\ });
\\ a -%= (x: {
\\ const _ref = &a;
\\ _ref.* = (_ref.* -% c_uint(1));
\\ break :x _ref.*;
\\ });
\\ a *%= (x: {
\\ const _ref = &a;
\\ _ref.* = (_ref.* *% c_uint(1));
\\ break :x _ref.*;
\\ });
\\ a &= (x: {
\\ const _ref = &a;
\\ _ref.* = (_ref.* & c_uint(1));
\\ break :x _ref.*;
\\ });
\\ a |= (x: {
\\ const _ref = &a;
\\ _ref.* = (_ref.* | c_uint(1));
\\ break :x _ref.*;
\\ });
\\ a ^= (x: {
\\ const _ref = &a;
\\ _ref.* = (_ref.* ^ c_uint(1));
\\ break :x _ref.*;
\\ });
\\ a >>= @import("std").math.Log2Int(c_uint)((x: {
\\ const _ref = &a;
\\ _ref.* = (_ref.* >> @import("std").math.Log2Int(c_uint)(1));
\\ break :x _ref.*;
\\ }));
\\ a <<= @import("std").math.Log2Int(c_uint)((x: {
\\ const _ref = &a;
\\ _ref.* = (_ref.* << @import("std").math.Log2Int(c_uint)(1));
\\ break :x _ref.*;
\\ }));
\\}
);
cases.addC("duplicate typedef",
\\typedef long foo;
\\typedef int bar;
\\typedef long foo;
\\typedef int baz;
,
\\pub const foo = c_long;
\\pub const bar = c_int;
\\pub const baz = c_int;
);
cases.addC("post increment/decrement",
\\void foo(void) {
\\ int i = 0;
\\ unsigned u = 0;
\\ i++;
\\ i--;
\\ u++;
\\ u--;
\\ i = i++;
\\ i = i--;
\\ u = u++;
\\ u = u--;
\\}
,
\\pub export fn foo() void {
\\ var i: c_int = 0;
\\ var u: c_uint = c_uint(0);
\\ i += 1;
\\ i -= 1;
\\ u +%= 1;
\\ u -%= 1;
\\ i = (x: {
\\ const _ref = &i;
\\ const _tmp = _ref.*;
\\ _ref.* += 1;
\\ break :x _tmp;
\\ });
\\ i = (x: {
\\ const _ref = &i;
\\ const _tmp = _ref.*;
\\ _ref.* -= 1;
\\ break :x _tmp;
\\ });
\\ u = (x: {
\\ const _ref = &u;
\\ const _tmp = _ref.*;
\\ _ref.* +%= 1;
\\ break :x _tmp;
\\ });
\\ u = (x: {
\\ const _ref = &u;
\\ const _tmp = _ref.*;
\\ _ref.* -%= 1;
\\ break :x _tmp;
\\ });
\\}
);
cases.addC("pre increment/decrement",
\\void foo(void) {
\\ int i = 0;
\\ unsigned u = 0;
\\ ++i;
\\ --i;
\\ ++u;
\\ --u;
\\ i = ++i;
\\ i = --i;
\\ u = ++u;
\\ u = --u;
\\}
,
\\pub export fn foo() void {
\\ var i: c_int = 0;
\\ var u: c_uint = c_uint(0);
\\ i += 1;
\\ i -= 1;
\\ u +%= 1;
\\ u -%= 1;
\\ i = (x: {
\\ const _ref = &i;
\\ _ref.* += 1;
\\ break :x _ref.*;
\\ });
\\ i = (x: {
\\ const _ref = &i;
\\ _ref.* -= 1;
\\ break :x _ref.*;
\\ });
\\ u = (x: {
\\ const _ref = &u;
\\ _ref.* +%= 1;
\\ break :x _ref.*;
\\ });
\\ u = (x: {
\\ const _ref = &u;
\\ _ref.* -%= 1;
\\ break :x _ref.*;
\\ });
\\}
);
cases.addC("do loop",
\\void foo(void) {
\\ int a = 2;
\\ do {
\\ a--;
\\ } while (a != 0);
\\
\\ int b = 2;
\\ do
\\ b--;
\\ while (b != 0);
\\}
,
\\pub export fn foo() void {
\\ var a: c_int = 2;
\\ while (true) {
\\ a -= 1;
\\ if (!(a != 0)) break;
\\ }
\\ var b: c_int = 2;
\\ while (true) {
\\ b -= 1;
\\ if (!(b != 0)) break;
\\ }
\\}
);
cases.addC("deref function pointer",
\\void foo(void) {}
\\int baz(void) { return 0; }
\\void bar(void) {
\\ void(*f)(void) = foo;
\\ int(*b)(void) = baz;
\\ f();
\\ (*(f))();
\\ foo();
\\ b();
\\ (*(b))();
\\ baz();
\\}
,
\\pub export fn foo() void {}
\\pub export fn baz() c_int {
\\ return 0;
\\}
\\pub export fn bar() void {
\\ var f: ?extern fn() void = foo;
\\ var b: ?extern fn() c_int = baz;
\\ f.?();
\\ f.?();
\\ foo();
\\ _ = b.?();
\\ _ = b.?();
\\ _ = baz();
\\}
);
cases.addC("normal deref",
\\void foo(int *x) {
\\ *x = 1;
\\}
,
\\pub export fn foo(x: [*c]c_int) void {
\\ x.?.* = 1;
\\}
);
cases.add("simple union",
\\union Foo {
\\ int x;
\\ double y;
\\};
,
\\pub const union_Foo = extern union {
\\ x: c_int,
\\ y: f64,
\\};
,
\\pub const Foo = union_Foo;
);
cases.add("address of operator",
\\int foo(void) {
\\ int x = 1234;
\\ int *ptr = &x;
\\ return *ptr;
\\}
,
\\pub fn foo() c_int {
\\ var x: c_int = 1234;
\\ var ptr: [*c]c_int = &x;
\\ return ptr.?.*;
\\}
);
cases.add("string literal",
\\const char *foo(void) {
\\ return "bar";
\\}
,
\\pub fn foo() [*c]const u8 {
\\ return c"bar";
\\}
);
cases.add("return void",
\\void foo(void) {
\\ return;
\\}
,
\\pub fn foo() void {
\\ return;
\\}
);
cases.add("for loop",
\\void foo(void) {
\\ for (int i = 0; i < 10; i += 1) { }
\\}
,
\\pub fn foo() void {
\\ {
\\ var i: c_int = 0;
\\ while (i < 10) : (i += 1) {}
\\ }
\\}
);
cases.add("empty for loop",
\\void foo(void) {
\\ for (;;) { }
\\}
,
\\pub fn foo() void {
\\ while (true) {}
\\}
);
cases.add("break statement",
\\void foo(void) {
\\ for (;;) {
\\ break;
\\ }
\\}
,
\\pub fn foo() void {
\\ while (true) {
\\ break;
\\ }
\\}
);
cases.add("continue statement",
\\void foo(void) {
\\ for (;;) {
\\ continue;
\\ }
\\}
,
\\pub fn foo() void {
\\ while (true) {
\\ continue;
\\ }
\\}
);
cases.add("macros with field targets",
\\typedef unsigned int GLbitfield;
\\typedef void (*PFNGLCLEARPROC) (GLbitfield mask);
\\typedef void(*OpenGLProc)(void);
\\union OpenGLProcs {
\\ OpenGLProc ptr[1];
\\ struct {
\\ PFNGLCLEARPROC Clear;
\\ } gl;
\\};
\\extern union OpenGLProcs glProcs;
\\#define glClearUnion glProcs.gl.Clear
\\#define glClearPFN PFNGLCLEARPROC
,
\\pub const GLbitfield = c_uint;
,
\\pub const PFNGLCLEARPROC = ?extern fn(GLbitfield) void;
,
\\pub const OpenGLProc = ?extern fn() void;
,
\\pub const union_OpenGLProcs = extern union {
\\ ptr: [1]OpenGLProc,
\\ gl: extern struct {
\\ Clear: PFNGLCLEARPROC,
\\ },
\\};
,
\\pub extern var glProcs: union_OpenGLProcs;
,
\\pub const glClearPFN = PFNGLCLEARPROC;
,
\\pub inline fn glClearUnion(arg0: GLbitfield) void {
\\ return glProcs.gl.Clear.?(arg0);
\\}
,
\\pub const OpenGLProcs = union_OpenGLProcs;
);
cases.add("variable name shadowing",
\\int foo(void) {
\\ int x = 1;
\\ {
\\ int x = 2;
\\ x += 1;
\\ }
\\ return x;
\\}
,
\\pub fn foo() c_int {
\\ var x: c_int = 1;
\\ {
\\ var x_0: c_int = 2;
\\ x_0 += 1;
\\ }
\\ return x;
\\}
);
cases.add("pointer casting",
\\float *ptrcast(int *a) {
\\ return (float *)a;
\\}
,
\\fn ptrcast(a: [*c]c_int) [*c]f32 {
\\ return @ptrCast([*c]f32, a);
\\}
);
cases.add("bin not",
\\int foo(int x) {
\\ return ~x;
\\}
,
\\pub fn foo(x: c_int) c_int {
\\ return ~x;
\\}
);
cases.add("bool not",
\\int foo(int a, float b, void *c) {
\\ return !(a == 0);
\\ return !a;
\\ return !b;
\\ return !c;
\\}
,
\\pub fn foo(a: c_int, b: f32, c: ?*c_void) c_int {
\\ return !(a == 0);
\\ return !(a != 0);
\\ return !(b != 0);
\\ return !(c != 0);
\\}
);
cases.add("primitive types included in defined symbols",
\\int foo(int u32) {
\\ return u32;
\\}
,
\\pub fn foo(u32_0: c_int) c_int {
\\ return u32_0;
\\}
);
cases.add("const ptr initializer",
\\static const char *v0 = "0.0.0";
,
\\pub var v0: [*c]const u8 = c"0.0.0";
);
cases.add("static incomplete array inside function",
\\void foo(void) {
\\ static const char v2[] = "2.2.2";
\\}
,
\\pub fn foo() void {
\\ const v2: [*c]const u8 = c"2.2.2";
\\}
);
cases.add("macro pointer cast",
\\#define NRF_GPIO ((NRF_GPIO_Type *) NRF_GPIO_BASE)
,
\\pub const NRF_GPIO = if (@typeId(@typeOf(NRF_GPIO_BASE)) == @import("builtin").TypeId.Pointer) @ptrCast([*c]NRF_GPIO_Type, NRF_GPIO_BASE) else if (@typeId(@typeOf(NRF_GPIO_BASE)) == @import("builtin").TypeId.Int) @intToPtr([*c]NRF_GPIO_Type, NRF_GPIO_BASE) else ([*c]NRF_GPIO_Type)(NRF_GPIO_BASE);
);
cases.add("if on non-bool",
\\enum SomeEnum { A, B, C };
\\int if_none_bool(int a, float b, void *c, enum SomeEnum d) {
\\ if (a) return 0;
\\ if (b) return 1;
\\ if (c) return 2;
\\ if (d) return 3;
\\ return 4;
\\}
,
\\pub const A = enum_SomeEnum.A;
\\pub const B = enum_SomeEnum.B;
\\pub const C = enum_SomeEnum.C;
\\pub const enum_SomeEnum = extern enum {
\\ A,
\\ B,
\\ C,
\\};
\\pub fn if_none_bool(a: c_int, b: f32, c: ?*c_void, d: enum_SomeEnum) c_int {
\\ if (a != 0) return 0;
\\ if (b != 0) return 1;
\\ if (c != 0) return 2;
\\ if (d != @bitCast(enum_SomeEnum, @TagType(enum_SomeEnum)(0))) return 3;
\\ return 4;
\\}
);
cases.add("while on non-bool",
\\int while_none_bool(int a, float b, void *c) {
\\ while (a) return 0;
\\ while (b) return 1;
\\ while (c) return 2;
\\ return 3;
\\}
,
\\pub fn while_none_bool(a: c_int, b: f32, c: ?*c_void) c_int {
\\ while (a != 0) return 0;
\\ while (b != 0) return 1;
\\ while (c != 0) return 2;
\\ return 3;
\\}
);
cases.add("for on non-bool",
\\int for_none_bool(int a, float b, void *c) {
\\ for (;a;) return 0;
\\ for (;b;) return 1;
\\ for (;c;) return 2;
\\ return 3;
\\}
,
\\pub fn for_none_bool(a: c_int, b: f32, c: ?*c_void) c_int {
\\ while (a != 0) return 0;
\\ while (b != 0) return 1;
\\ while (c != 0) return 2;
\\ return 3;
\\}
);
cases.add("switch on int",
\\int switch_fn(int i) {
\\ int res = 0;
\\ switch (i) {
\\ case 0:
\\ res = 1;
\\ case 1:
\\ res = 2;
\\ default:
\\ res = 3 * i;
\\ break;
\\ case 2:
\\ res = 5;
\\ }
\\}
,
\\pub fn switch_fn(i: c_int) c_int {
\\ var res: c_int = 0;
\\ __switch: {
\\ __case_2: {
\\ __default: {
\\ __case_1: {
\\ __case_0: {
\\ switch (i) {
\\ 0 => break :__case_0,
\\ 1 => break :__case_1,
\\ else => break :__default,
\\ 2 => break :__case_2,
\\ }
\\ }
\\ res = 1;
\\ }
\\ res = 2;
\\ }
\\ res = (3 * i);
\\ break :__switch;
\\ }
\\ res = 5;
\\ }
\\}
);
cases.addC("Parameterless function prototypes",
\\void foo() {}
\\void bar(void) {}
,
\\pub export fn foo() void {}
\\pub export fn bar() void {}
);
cases.addC(
"u integer suffix after 0 (zero) in macro definition",
"#define ZERO 0U",
"pub const ZERO = c_uint(0);",
);
cases.addC(
"l integer suffix after 0 (zero) in macro definition",
"#define ZERO 0L",
"pub const ZERO = c_long(0);",
);
cases.addC(
"ul integer suffix after 0 (zero) in macro definition",
"#define ZERO 0UL",
"pub const ZERO = c_ulong(0);",
);
cases.addC(
"lu integer suffix after 0 (zero) in macro definition",
"#define ZERO 0LU",
"pub const ZERO = c_ulong(0);",
);
cases.addC(
"ll integer suffix after 0 (zero) in macro definition",
"#define ZERO 0LL",
"pub const ZERO = c_longlong(0);",
);
cases.addC(
"ull integer suffix after 0 (zero) in macro definition",
"#define ZERO 0ULL",
"pub const ZERO = c_ulonglong(0);",
);
cases.addC(
"llu integer suffix after 0 (zero) in macro definition",
"#define ZERO 0LLU",
"pub const ZERO = c_ulonglong(0);",
);
cases.addC(
"bitwise not on u-suffixed 0 (zero) in macro definition",
"#define NOT_ZERO (~0U)",
"pub const NOT_ZERO = ~c_uint(0);",
);
cases.addC("implicit casts",
\\#include <stdbool.h>
\\
\\void fn_int(int x);
\\void fn_f32(float x);
\\void fn_f64(double x);
\\void fn_char(char x);
\\void fn_bool(bool x);
\\void fn_ptr(void *x);
\\
\\void call(int q) {
\\ fn_int(3.0f);
\\ fn_int(3.0);
\\ fn_int(3.0L);
\\ fn_int('ABCD');
\\ fn_f32(3);
\\ fn_f64(3);
\\ fn_char('3');
\\ fn_char('\x1');
\\ fn_char(0);
\\ fn_f32(3.0f);
\\ fn_f64(3.0);
\\ fn_bool(123);
\\ fn_bool(0);
\\ fn_bool(&fn_int);
\\ fn_int(&fn_int);
\\ fn_ptr(42);
\\}
,
\\pub extern fn fn_int(x: c_int) void;
\\pub extern fn fn_f32(x: f32) void;
\\pub extern fn fn_f64(x: f64) void;
\\pub extern fn fn_char(x: u8) void;
\\pub extern fn fn_bool(x: bool) void;
\\pub extern fn fn_ptr(x: ?*c_void) void;
\\pub export fn call(q: c_int) void {
\\ fn_int(@floatToInt(c_int, 3.000000));
\\ fn_int(@floatToInt(c_int, 3.000000));
\\ fn_int(@floatToInt(c_int, 3.000000));
\\ fn_int(1094861636);
\\ fn_f32(@intToFloat(f32, 3));
\\ fn_f64(@intToFloat(f64, 3));
\\ fn_char(u8('3'));
\\ fn_char(u8('\x01'));
\\ fn_char(u8(0));
\\ fn_f32(3.000000);
\\ fn_f64(3.000000);
\\ fn_bool(true);
\\ fn_bool(false);
\\ fn_bool(@ptrToInt(&fn_int) != 0);
\\ fn_int(@intCast(c_int, @ptrToInt(&fn_int)));
\\ fn_ptr(@intToPtr(?*c_void, 42));
\\}
);
// cases.add("empty array with initializer",
// "int a[4] = {};"
// ,
// "pub var a: [4]c_int = [1]c_int{0} ** 4;"
// );
// cases.add("array with initialization",
// "int a[4] = {1, 2, 3, 4};"
// ,
// "pub var a: [4]c_int = [4]c_int{1, 2, 3, 4};"
// );
// cases.add("array with incomplete initialization",
// "int a[4] = {3, 4};"
// ,
// "pub var a: [4]c_int = [2]c_int{3, 4} ++ ([1]c_int{0} ** 2);"
// );
// cases.add("2D array with initialization",
// "int a[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };"
// ,
// "pub var a: [3][3]c_int = [3][3]c_int{[3]c_int{1, 2, 3}, [3]c_int{4, 5, 6}, [3]c_int{7, 8, 9}};"
// );
// cases.add("2D array with incomplete initialization",
// "int a[3][3] = { {1, 2}, {4, 5, 6} };"
// ,
// "pub var a: [3][3]c_int = [2][3]c_int{[2]c_int{1, 2} ++ [1]c_int{0}, [3]c_int{4, 5, 6}} ++ [1][3]c_int{[1]c_int{0} ** 3};"
// );
} | test/translate_c.zig |
//! A condition provides a way for a kernel thread to block until it is signaled
//! to wake up. Spurious wakeups are possible.
//! This API supports static initialization and does not require deinitialization.
impl: Impl = .{},
const std = @import("../std.zig");
const Condition = @This();
const windows = std.os.windows;
const linux = std.os.linux;
const Mutex = std.Thread.Mutex;
const assert = std.debug.assert;
pub fn wait(cond: *Condition, mutex: *Mutex) void {
cond.impl.wait(mutex);
}
pub fn signal(cond: *Condition) void {
cond.impl.signal();
}
pub fn broadcast(cond: *Condition) void {
cond.impl.broadcast();
}
const Impl = if (std.builtin.single_threaded)
SingleThreadedCondition
else if (std.Target.current.os.tag == .windows)
WindowsCondition
else if (std.Thread.use_pthreads)
PthreadCondition
else
AtomicCondition;
pub const SingleThreadedCondition = struct {
pub fn wait(cond: *SingleThreadedCondition, mutex: *Mutex) void {
_ = cond;
_ = mutex;
unreachable; // deadlock detected
}
pub fn signal(cond: *SingleThreadedCondition) void {
_ = cond;
}
pub fn broadcast(cond: *SingleThreadedCondition) void {
_ = cond;
}
};
pub const WindowsCondition = struct {
cond: windows.CONDITION_VARIABLE = windows.CONDITION_VARIABLE_INIT,
pub fn wait(cond: *WindowsCondition, mutex: *Mutex) void {
const rc = windows.kernel32.SleepConditionVariableSRW(
&cond.cond,
&mutex.srwlock,
windows.INFINITE,
@as(windows.ULONG, 0),
);
assert(rc != windows.FALSE);
}
pub fn signal(cond: *WindowsCondition) void {
windows.kernel32.WakeConditionVariable(&cond.cond);
}
pub fn broadcast(cond: *WindowsCondition) void {
windows.kernel32.WakeAllConditionVariable(&cond.cond);
}
};
pub const PthreadCondition = struct {
cond: std.c.pthread_cond_t = .{},
pub fn wait(cond: *PthreadCondition, mutex: *Mutex) void {
const rc = std.c.pthread_cond_wait(&cond.cond, &mutex.impl.pthread_mutex);
assert(rc == 0);
}
pub fn signal(cond: *PthreadCondition) void {
const rc = std.c.pthread_cond_signal(&cond.cond);
assert(rc == 0);
}
pub fn broadcast(cond: *PthreadCondition) void {
const rc = std.c.pthread_cond_broadcast(&cond.cond);
assert(rc == 0);
}
};
pub const AtomicCondition = struct {
pending: bool = false,
queue_mutex: Mutex = .{},
queue_list: QueueList = .{},
pub const QueueList = std.SinglyLinkedList(QueueItem);
pub const QueueItem = struct {
futex: i32 = 0,
fn wait(cond: *@This()) void {
while (@atomicLoad(i32, &cond.futex, .Acquire) == 0) {
switch (std.Target.current.os.tag) {
.linux => {
switch (linux.getErrno(linux.futex_wait(
&cond.futex,
linux.FUTEX_PRIVATE_FLAG | linux.FUTEX_WAIT,
0,
null,
))) {
0 => {},
std.os.EINTR => {},
std.os.EAGAIN => {},
else => unreachable,
}
},
else => std.atomic.spinLoopHint(),
}
}
}
fn notify(cond: *@This()) void {
@atomicStore(i32, &cond.futex, 1, .Release);
switch (std.Target.current.os.tag) {
.linux => {
switch (linux.getErrno(linux.futex_wake(
&cond.futex,
linux.FUTEX_PRIVATE_FLAG | linux.FUTEX_WAKE,
1,
))) {
0 => {},
std.os.EFAULT => {},
else => unreachable,
}
},
else => {},
}
}
};
pub fn wait(cond: *AtomicCondition, mutex: *Mutex) void {
var waiter = QueueList.Node{ .data = .{} };
{
const held = cond.queue_mutex.acquire();
defer held.release();
cond.queue_list.prepend(&waiter);
@atomicStore(bool, &cond.pending, true, .SeqCst);
}
mutex.force_release_internal();
waiter.data.wait();
_ = mutex.acquire();
}
pub fn signal(cond: *AtomicCondition) void {
if (@atomicLoad(bool, &cond.pending, .SeqCst) == false)
return;
const maybe_waiter = blk: {
const held = cond.queue_mutex.acquire();
defer held.release();
const maybe_waiter = cond.queue_list.popFirst();
@atomicStore(bool, &cond.pending, cond.queue_list.first != null, .SeqCst);
break :blk maybe_waiter;
};
if (maybe_waiter) |waiter|
waiter.data.notify();
}
pub fn broadcast(cond: *AtomicCondition) void {
if (@atomicLoad(bool, &cond.pending, .SeqCst) == false)
return;
@atomicStore(bool, &cond.pending, false, .SeqCst);
var waiters = blk: {
const held = cond.queue_mutex.acquire();
defer held.release();
const waiters = cond.queue_list;
cond.queue_list = .{};
break :blk waiters;
};
while (waiters.popFirst()) |waiter|
waiter.data.notify();
}
}; | lib/std/Thread/Condition.zig |
const std = @import("std");
const direct_allocator = std.heap.direct_allocator;
const separate = std.mem.separate;
const parseInt = std.fmt.parseInt;
const warn = std.debug.warn;
const ArrayList = std.ArrayList;
const copy = std.mem.copy;
// Assume the input program is correct
const input = "1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,9,1,19,1,9,19,23,1,23,5,27,2,27,10,31,1,6,31,35,1,6,35,39,2,9,39,43,1,6,43,47,1,47,5,51,1,51,13,55,1,55,13,59,1,59,5,63,2,63,6,67,1,5,67,71,1,71,13,75,1,10,75,79,2,79,6,83,2,9,83,87,1,5,87,91,1,91,5,95,2,9,95,99,1,6,99,103,1,9,103,107,2,9,107,111,1,111,6,115,2,9,115,119,1,119,6,123,1,123,9,127,2,127,13,131,1,131,9,135,1,10,135,139,2,139,10,143,1,143,5,147,2,147,6,151,1,151,5,155,1,2,155,159,1,6,159,0,99,2,0,14,0";
pub fn main() !void {
var vec = ArrayList(u32).init(direct_allocator);
defer vec.deinit();
// Parse the input into an array of opcodes.
{
var it = separate(input, ",");
while (it.next()) |str|
try vec.append(try parseInt(u32, str, 10));
}
// Set the initial program state as specified
vec.toSlice()[1] = 12;
vec.toSlice()[2] = 2;
const orig = vec.toSliceConst();
// Create scratch memory we can restore after each execution
const scratch = try direct_allocator.alloc(u32, orig.len);
defer direct_allocator.free(scratch);
copy(u32, scratch, orig);
warn("The solution for part 1 is {}\n", .{execute(scratch)});
var noun: u32 = 0;
while (noun <= 99) : (noun += 1) {
var verb: u32 = 0;
while (verb <= 99) : (verb += 1) {
copy(u32, scratch, orig); // Clear memory from the previous attempt
scratch[1] = noun;
scratch[2] = verb;
if (execute(scratch) == 19690720) {
warn("The solution for part 2 is {}{}\n", .{noun, verb});
return;
}
}
}
warn("Could not find solution for part 2 :(\n", .{});
}
/// Returns the value at address 0 after the program halts
fn execute(mem: []u32) u32 {
var ip: u32 = 0; // Instruction pointer
while (true) {
switch (mem[ip]) {
// Add instruction
1 => {
mem[mem[ip + 3]] = mem[mem[ip + 1]] + mem[mem[ip + 2]];
ip += 4;
},
// Muliply instruction
2 => {
mem[mem[ip + 3]] = mem[mem[ip + 1]] * mem[mem[ip + 2]];
ip += 4;
},
// Halt instruction
99 => return mem[0],
// Unexpected
else => unreachable,
}
}
} | aoc-2019/day2.zig |
const std = @import("std");
const os = std.os;
const panic = std.debug.panic;
const c = @import("c.zig");
const math3d = @import("math3d.zig");
const debug_gl = @import("debug_gl.zig");
const Vec4 = math3d.Vec4;
const Mat4x4 = math3d.Mat4x4;
const c_allocator = @import("std").heap.c_allocator;
pub const AllShaders = struct {
primitive: ShaderProgram,
primitive_attrib_position: c.GLint,
primitive_uniform_mvp: c.GLint,
primitive_uniform_color: c.GLint,
texture: ShaderProgram,
texture_attrib_tex_coord: c.GLint,
texture_attrib_position: c.GLint,
texture_uniform_mvp: c.GLint,
texture_uniform_tex: c.GLint,
pub fn create() !AllShaders {
var as: AllShaders = undefined;
as.primitive = try ShaderProgram.create(
\\#version 150 core
\\
\\in vec3 VertexPosition;
\\
\\uniform mat4 MVP;
\\
\\void main(void) {
\\ gl_Position = vec4(VertexPosition, 1.0) * MVP;
\\}
,
\\#version 150 core
\\
\\out vec4 FragColor;
\\
\\uniform vec4 Color;
\\
\\void main(void) {
\\ FragColor = Color;
\\}
, null);
as.primitive_attrib_position = as.primitive.attribLocation("VertexPosition");
as.primitive_uniform_mvp = as.primitive.uniformLocation("MVP");
as.primitive_uniform_color = as.primitive.uniformLocation("Color");
as.texture = try ShaderProgram.create(
\\#version 150 core
\\
\\in vec3 VertexPosition;
\\in vec2 TexCoord;
\\
\\out vec2 FragTexCoord;
\\
\\uniform mat4 MVP;
\\
\\void main(void)
\\{
\\ FragTexCoord = TexCoord;
\\ gl_Position = vec4(VertexPosition, 1.0) * MVP;
\\}
,
\\#version 150 core
\\
\\in vec2 FragTexCoord;
\\out vec4 FragColor;
\\
\\uniform sampler2D Tex;
\\
\\void main(void)
\\{
\\ FragColor = texture(Tex, FragTexCoord);
\\}
, null);
as.texture_attrib_tex_coord = as.texture.attribLocation("TexCoord");
as.texture_attrib_position = as.texture.attribLocation("VertexPosition");
as.texture_uniform_mvp = as.texture.uniformLocation("MVP");
as.texture_uniform_tex = as.texture.uniformLocation("Tex");
debug_gl.assertNoError();
return as;
}
pub fn destroy(as: *AllShaders) void {
as.primitive.destroy();
as.texture.destroy();
}
};
pub const ShaderProgram = struct {
program_id: c.GLuint,
vertex_id: c.GLuint,
fragment_id: c.GLuint,
maybe_geometry_id: ?c.GLuint,
pub fn bind(sp: ShaderProgram) void {
c.glUseProgram(sp.program_id);
}
pub fn attribLocation(sp: ShaderProgram, name: [*]const u8) c.GLint {
const id = c.glGetAttribLocation(sp.program_id, name);
if (id == -1) {
panic("invalid attrib: {any}\n", .{name});
}
return id;
}
pub fn uniformLocation(sp: ShaderProgram, name: [*]const u8) c.GLint {
const id = c.glGetUniformLocation(sp.program_id, name);
if (id == -1) {
panic("invalid uniform: {any}\n", .{name});
}
return id;
}
pub fn setUniformInt(sp: ShaderProgram, uniform_id: c.GLint, value: c_int) void {
c.glUniform1i(uniform_id, value);
}
pub fn setUniformFloat(sp: ShaderProgram, uniform_id: c.GLint, value: f32) void {
c.glUniform1f(uniform_id, value);
}
pub fn setUniformVec3(sp: ShaderProgram, uniform_id: c.GLint, value: math3d.Vec3) void {
c.glUniform3fv(uniform_id, 1, &value.data[0]);
}
pub fn setUniformVec4(sp: ShaderProgram, uniform_id: c.GLint, value: Vec4) void {
c.glUniform4fv(uniform_id, 1, &value.data[0]);
}
pub fn setUniformMat4x4(sp: ShaderProgram, uniform_id: c.GLint, value: Mat4x4) void {
c.glUniformMatrix4fv(uniform_id, 1, c.GL_FALSE, &value.data[0][0]);
}
pub fn create(
vertex_source: []const u8,
frag_source: []const u8,
maybe_geometry_source: ?[]u8,
) !ShaderProgram {
var sp: ShaderProgram = undefined;
sp.vertex_id = try initGlShader(vertex_source, "vertex", c.GL_VERTEX_SHADER);
sp.fragment_id = try initGlShader(frag_source, "fragment", c.GL_FRAGMENT_SHADER);
sp.maybe_geometry_id = if (maybe_geometry_source) |geo_source|
try initGlShader(geo_source, "geometry", c.GL_GEOMETRY_SHADER)
else
null;
sp.program_id = c.glCreateProgram();
c.glAttachShader(sp.program_id, sp.vertex_id);
c.glAttachShader(sp.program_id, sp.fragment_id);
if (sp.maybe_geometry_id) |geo_id| {
c.glAttachShader(sp.program_id, geo_id);
}
c.glLinkProgram(sp.program_id);
var ok: c.GLint = undefined;
c.glGetProgramiv(sp.program_id, c.GL_LINK_STATUS, &ok);
if (ok != 0) return sp;
var error_size: c.GLint = undefined;
c.glGetProgramiv(sp.program_id, c.GL_INFO_LOG_LENGTH, &error_size);
const message = try c_allocator.alloc(u8, @intCast(usize, error_size));
c.glGetProgramInfoLog(sp.program_id, error_size, &error_size, message.ptr);
panic("Error linking shader program: {any}\n", .{message.ptr});
}
pub fn destroy(sp: *ShaderProgram) void {
if (sp.maybe_geometry_id) |geo_id| {
c.glDetachShader(sp.program_id, geo_id);
}
c.glDetachShader(sp.program_id, sp.fragment_id);
c.glDetachShader(sp.program_id, sp.vertex_id);
if (sp.maybe_geometry_id) |geo_id| {
c.glDeleteShader(geo_id);
}
c.glDeleteShader(sp.fragment_id);
c.glDeleteShader(sp.vertex_id);
c.glDeleteProgram(sp.program_id);
}
};
fn initGlShader(source: []const u8, name: [*]const u8, kind: c.GLenum) !c.GLuint {
const shader_id = c.glCreateShader(kind);
const source_ptr: ?[*]const u8 = source.ptr;
const source_len = @intCast(c.GLint, source.len);
c.glShaderSource(shader_id, 1, &source_ptr, &source_len);
c.glCompileShader(shader_id);
var ok: c.GLint = undefined;
c.glGetShaderiv(shader_id, c.GL_COMPILE_STATUS, &ok);
if (ok != 0) return shader_id;
var error_size: c.GLint = undefined;
c.glGetShaderiv(shader_id, c.GL_INFO_LOG_LENGTH, &error_size);
const message = try c_allocator.alloc(u8, @intCast(usize, error_size));
c.glGetShaderInfoLog(shader_id, error_size, &error_size, message.ptr);
panic("Error compiling {any} shader:\n{any}\n", .{ name, message.ptr });
} | src/all_shaders.zig |
const std = @import("std");
const fmt = std.fmt;
const mem = std.mem;
const Allocator = mem.Allocator;
const Linenoise = @import("main.zig").Linenoise;
const term = @import("term.zig");
const global_allocator = std.heap.c_allocator;
var global_linenoise = Linenoise.init(global_allocator);
var c_completion_callback: ?linenoiseCompletionCallback = null;
var c_hints_callback: ?linenoiseHintsCallback = null;
var c_free_hints_callback: ?linenoiseFreeHintsCallback = null;
const LinenoiseCompletions = extern struct {
len: usize,
cvec: ?[*][*:0]u8,
pub fn free(self: *LinenoiseCompletions) void {
if (self.cvec) |raw_completions| {
const len = @intCast(usize, self.len);
for (raw_completions[0..len]) |x| global_allocator.free(mem.span(x));
global_allocator.free(raw_completions[0..len]);
}
}
};
const linenoiseCompletionCallback = fn ([*:0]const u8, *LinenoiseCompletions) callconv(.C) void;
const linenoiseHintsCallback = fn ([*:0]const u8, *c_int, *c_int) callconv(.C) ?[*:0]u8;
const linenoiseFreeHintsCallback = fn (*anyopaque) callconv(.C) void;
export fn linenoiseSetCompletionCallback(fun: linenoiseCompletionCallback) void {
c_completion_callback = fun;
global_linenoise.completions_callback = completionsCallback;
}
export fn linenoiseSetHintsCallback(fun: linenoiseHintsCallback) void {
c_hints_callback = fun;
global_linenoise.hints_callback = hintsCallback;
}
export fn linenoiseSetFreeHintsCallback(fun: linenoiseFreeHintsCallback) void {
c_free_hints_callback = fun;
}
export fn linenoiseAddCompletion(lc: *LinenoiseCompletions, str: [*:0]const u8) void {
const dupe = global_allocator.dupeZ(u8, mem.span(str)) catch return;
var completions: std.ArrayList([*:0]u8) = undefined;
if (lc.cvec) |raw_completions| {
completions = std.ArrayList([*:0]u8).fromOwnedSlice(global_allocator, raw_completions[0..lc.len]);
} else {
completions = std.ArrayList([*:0]u8).init(global_allocator);
}
completions.append(dupe) catch return;
lc.cvec = completions.toOwnedSlice().ptr;
lc.len += 1;
}
fn completionsCallback(allocator: Allocator, line: []const u8) ![]const []const u8 {
if (c_completion_callback) |cCompletionCallback| {
const lineZ = try allocator.dupeZ(u8, line);
defer allocator.free(lineZ);
var lc = LinenoiseCompletions{
.len = 0,
.cvec = null,
};
cCompletionCallback(lineZ, &lc);
if (lc.cvec) |raw_completions| {
defer lc.free();
const completions = try allocator.alloc([]const u8, lc.len);
for (completions) |*x, i| {
x.* = try allocator.dupe(u8, mem.span(raw_completions[i]));
}
return completions;
}
}
return &[_][]const u8{};
}
fn hintsCallback(allocator: Allocator, line: []const u8) !?[]const u8 {
if (c_hints_callback) |cHintsCallback| {
const lineZ = try allocator.dupeZ(u8, line);
defer allocator.free(lineZ);
var color: c_int = -1;
var bold: c_int = 0;
const maybe_hint = cHintsCallback(lineZ, &color, &bold);
if (maybe_hint) |hintZ| {
defer {
if (c_free_hints_callback) |cFreeHintsCallback| {
cFreeHintsCallback(hintZ);
}
}
const hint = mem.span(hintZ);
if (bold == 1 and color == -1) {
color = 37;
}
return try fmt.allocPrint(allocator, "\x1B[{};{};49m{s}\x1B[0m", .{
bold,
color,
hint,
});
}
}
return null;
}
export fn linenoise(prompt: [*:0]const u8) ?[*:0]u8 {
const result = global_linenoise.linenoise(mem.span(prompt)) catch return null;
if (result) |line| {
defer global_allocator.free(line);
return global_allocator.dupeZ(u8, line) catch return null;
} else return null;
}
export fn linenoiseFree(ptr: *anyopaque) void {
global_allocator.free(mem.span(@ptrCast([*:0]const u8, ptr)));
}
export fn linenoiseHistoryAdd(line: [*:0]const u8) c_int {
global_linenoise.history.add(mem.span(line)) catch return -1;
return 0;
}
export fn linenoiseHistorySetMaxLen(len: c_int) c_int {
global_linenoise.history.setMaxLen(@intCast(usize, len)) catch return -1;
return 0;
}
export fn linenoiseHistorySave(filename: [*:0]const u8) c_int {
global_linenoise.history.save(mem.span(filename)) catch return -1;
return 0;
}
export fn linenoiseHistoryLoad(filename: [*:0]const u8) c_int {
global_linenoise.history.load(mem.span(filename)) catch return -1;
return 0;
}
export fn linenoiseClearScreen() void {
term.clearScreen() catch return;
}
export fn linenoiseSetMultiLine(ml: c_int) void {
global_linenoise.multiline_mode = ml != 0;
}
/// Not implemented in linenoize
export fn linenoisePrintKeyCodes() void {}
export fn linenoiseMaskModeEnable() void {
global_linenoise.mask_mode = true;
}
export fn linenoiseMaskModeDisable() void {
global_linenoise.mask_mode = false;
} | src/c.zig |
const c = @import("c.zig");
const std = @import("std");
const Allocator = std.mem.Allocator;
const log = std.log.scoped(.glfw);
pub const WindowError = error {
InitializationError
};
fn checkError(shader: c.GLuint) void {
var status: c.GLint = undefined;
c.glGetShaderiv(shader, c.GL_COMPILE_STATUS, &status);
if (status != c.GL_TRUE) {
log.warn("uncorrect shader:\n", .{});
var buf: [512]u8 = undefined;
var totalLen: c.GLsizei = undefined;
c.glGetShaderInfoLog(shader, 512, &totalLen, buf[0..]);
var totalSize: usize = @bitCast(u32, totalLen);
log.warn("{s}\n", .{buf[0..totalSize]});
}
}
const WIDTH = 1000;
const HEIGHT = 700;
pub const FontMetrics = struct {
ascent: f64,
descent: f64,
height: f64
};
pub const TextMetrics = struct {
width: f64,
height: f64
};
pub const Cursor = enum {
Normal,
Text
};
pub const CairoBackend = struct {
window: *c.GLFWwindow,
cairo: *c.cairo_t,
surface: *c.cairo_surface_t,
gl_texture: c.GLuint,
frame_requested: bool,
previousCursor: Cursor = .Normal,
/// For animation
request_next_frame: bool = false,
mouseButtonCb: ?fn(backend: *CairoBackend, button: MouseButton, pressed: bool) void = null,
mouseScrollCb: ?fn(backend: *CairoBackend, yOffset: f64) void = null,
keyTypedCb: ?fn(backend: *CairoBackend, codepoint: u21) void = null,
keyPressedCb: ?fn(backend: *CairoBackend, key: u32, mods: u32) void = null,
windowResizeCb: ?fn(backend: *CairoBackend, width: f64, height: f64) void = null,
userData: usize = 0,
currentFontDesc: ?*c.PangoFontDescription = null,
currentFont: *c.PangoFont = undefined,
textLayout: *c.PangoLayout = undefined,
textContext: *c.PangoContext,
pub const BackspaceKey = c.GLFW_KEY_BACKSPACE;
pub const EnterKey = c.GLFW_KEY_ENTER;
pub const UpKey = c.GLFW_KEY_UP;
pub const DownKey = c.GLFW_KEY_DOWN;
pub const MouseButton = enum(c_int) {
Left = c.GLFW_MOUSE_BUTTON_LEFT,
Right = c.GLFW_MOUSE_BUTTON_RIGHT,
Middle = c.GLFW_MOUSE_BUTTON_MIDDLE
};
export fn windowSizeCallback(window: ?*c.GLFWwindow, width: c_int, height: c_int) void {
var self = @ptrCast(?*CairoBackend, @alignCast(@alignOf(*CairoBackend), c.glfwGetWindowUserPointer(window))) orelse unreachable;
c.cairo_destroy(self.cairo);
c.cairo_surface_destroy(self.surface);
self.surface = c.cairo_image_surface_create(c.cairo_format_t.CAIRO_FORMAT_ARGB32, width, height) orelse unreachable;
self.cairo = c.cairo_create(self.surface) orelse unreachable;
self.frame_requested = true;
if (self.windowResizeCb) |callback| {
callback(self, @intToFloat(f64, width), @intToFloat(f64, height));
}
// var w: c_int = 0;
// var h: c_int = 0;
// c.glfwGetFramebufferSize(self.window, &w, &h);
// c.glViewport(0, 0, w, h);
// c.cairo_surface_flush(self.surface);
// var data = c.cairo_image_surface_get_data(self.surface);
// c.glTexImage2D(c.GL_TEXTURE_2D, 0, c.GL_RGB,
// c.cairo_image_surface_get_width(self.surface),
// c.cairo_image_surface_get_height(self.surface), 0, c.GL_RGBA, c.GL_UNSIGNED_BYTE, data);
// c.glDrawElements(c.GL_TRIANGLES, 6, c.GL_UNSIGNED_INT, null);
// c.glfwSwapBuffers(self.window);
}
export fn mouseButtonCallback(window: ?*c.GLFWwindow, button: c_int, action: c_int, mods: c_int) void {
var self = @ptrCast(?*CairoBackend, @alignCast(@alignOf(*CairoBackend), c.glfwGetWindowUserPointer(window))) orelse unreachable;
if (self.mouseButtonCb) |callback| {
callback(self, @intToEnum(MouseButton, button), action == c.GLFW_PRESS);
}
}
export fn mouseScrollCallback(window: ?*c.GLFWwindow, xOffset: f64, yOffset: f64) void {
var self = @ptrCast(?*CairoBackend, @alignCast(@alignOf(*CairoBackend), c.glfwGetWindowUserPointer(window))) orelse unreachable;
if (self.mouseScrollCb) |callback| {
callback(self, yOffset);
}
}
export fn characterCallback(window: ?*c.GLFWwindow, codepoint: c_uint) void {
var self = @ptrCast(?*CairoBackend, @alignCast(@alignOf(*CairoBackend), c.glfwGetWindowUserPointer(window))) orelse unreachable;
if (self.keyTypedCb) |callback| {
callback(self, @intCast(u21, codepoint));
}
}
export fn keyCallback(window: ?*c.GLFWwindow, key: c_int, scancode: c_int, action: c_int, mods: c_int) void {
var self = @ptrCast(?*CairoBackend, @alignCast(@alignOf(*CairoBackend), c.glfwGetWindowUserPointer(window))) orelse unreachable;
if (action == c.GLFW_PRESS or action == c.GLFW_REPEAT) {
if (self.keyPressedCb) |callback| {
callback(self, @bitCast(u32, key), @bitCast(u32, mods));
}
}
}
pub fn init() !CairoBackend {
if (c.glfwInit() != 1) {
log.err("Could not init GLFW!\n", .{});
return WindowError.InitializationError;
}
errdefer c.glfwTerminate();
c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MAJOR, 3);
c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MINOR, 2);
c.glfwWindowHint(c.GLFW_OPENGL_PROFILE, c.GLFW_OPENGL_CORE_PROFILE);
c.glfwWindowHint(c.GLFW_RESIZABLE, c.GLFW_TRUE);
const window = c.glfwCreateWindow(WIDTH, HEIGHT, "Test Cairo backend", null, null) orelse return WindowError.InitializationError;
const surface = c.cairo_image_surface_create(c.cairo_format_t.CAIRO_FORMAT_ARGB32, WIDTH, HEIGHT) orelse return WindowError.InitializationError;
const cairo = c.cairo_create(surface) orelse return WindowError.InitializationError;
c.glfwMakeContextCurrent(window);
_ = c.glfwSetFramebufferSizeCallback(window, windowSizeCallback);
_ = c.glfwSetMouseButtonCallback(window, mouseButtonCallback);
_ = c.glfwSetScrollCallback(window, mouseScrollCallback);
_ = c.glfwSetCharCallback(window, characterCallback);
_ = c.glfwSetKeyCallback(window, keyCallback);
var vert: [:0]const u8 =
\\ #version 150
\\ in vec2 position;
\\ in vec2 texcoord;
\\ out vec2 texCoord;
\\ void main() {
\\ gl_Position = vec4(position, 0.0, 1.0);
\\ texCoord = texcoord;
\\ }
;
var frag: [:0]const u8 =
\\ #version 150
\\ in vec2 texCoord;
\\ out vec4 outColor;
\\ uniform sampler2D tex;
\\ void main() {
\\ vec4 color = texture(tex, texCoord);
\\ outColor.r = color.b;
\\ outColor.g = color.g;
\\ outColor.b = color.r;
\\ }
;
const sqLen = 1;
var vertices = [_]f32 {
-sqLen, sqLen, 0.0, 0.0,
-sqLen, -sqLen, 0.0, 1.0,
sqLen, -sqLen, 1.0, 1.0,
sqLen, sqLen, 1.0, 0.0
};
var elements = [_]c.GLuint {
0, 1, 2,
0, 3, 2
};
var vbo: c.GLuint = 0;
c.glGenBuffers(1, &vbo);
c.glBindBuffer(c.GL_ARRAY_BUFFER, vbo);
var vao: c.GLuint = 0;
c.glGenVertexArrays(1, &vao);
c.glBindVertexArray(vbo);
var ebo: c.GLuint = 0;
c.glGenBuffers(1, &ebo);
c.glBindBuffer(c.GL_ELEMENT_ARRAY_BUFFER, ebo);
c.glBufferData(c.GL_ELEMENT_ARRAY_BUFFER, @sizeOf(@TypeOf(elements)), elements[0..], c.GL_STATIC_DRAW);
c.glBufferData(c.GL_ARRAY_BUFFER, @sizeOf(@TypeOf(vertices)), vertices[0..], c.GL_STATIC_DRAW);
const vertexShader = c.glCreateShader(c.GL_VERTEX_SHADER);
c.glShaderSource(vertexShader, 1, &vert, null);
c.glCompileShader(vertexShader);
checkError(vertexShader);
const fragmentShader = c.glCreateShader(c.GL_FRAGMENT_SHADER);
c.glShaderSource(fragmentShader, 1, &frag, null);
c.glCompileShader(fragmentShader);
checkError(fragmentShader);
const shaderProgram = c.glCreateProgram();
c.glAttachShader(shaderProgram, vertexShader);
c.glAttachShader(shaderProgram, fragmentShader);
c.glBindFragDataLocation(shaderProgram, 0, "outColor");
c.glLinkProgram(shaderProgram);
c.glUseProgram(shaderProgram);
const stride = 4 * @sizeOf(f32);
const posAttrib = c.glGetAttribLocation(shaderProgram, "position");
c.glVertexAttribPointer(@bitCast(c.GLuint, posAttrib), 2, c.GL_FLOAT, c.GL_FALSE, stride, 0);
c.glEnableVertexAttribArray(@bitCast(c.GLuint, posAttrib));
const texAttrib = c.glGetAttribLocation(shaderProgram, "texcoord");
c.glVertexAttribPointer(@bitCast(c.GLuint, texAttrib), 2, c.GL_FLOAT, c.GL_FALSE, stride, 2*@sizeOf(f32));
c.glEnableVertexAttribArray(@bitCast(c.GLuint, texAttrib));
var tex: c.GLuint = 0;
c.glGenTextures(1, &tex);
c.glBindTexture(c.GL_TEXTURE_2D, tex);
c.glPixelStorei(c.GL_UNPACK_ALIGNMENT, 1);
c.glTexParameteri(c.GL_TEXTURE_2D, c.GL_TEXTURE_MIN_FILTER, c.GL_NEAREST);
c.glTexParameteri(c.GL_TEXTURE_2D, c.GL_TEXTURE_MAG_FILTER, c.GL_NEAREST);
var backend = CairoBackend {
.frame_requested = true,
.window = window,
.gl_texture = tex,
.cairo = cairo,
.surface = surface,
.textContext = c.pango_cairo_create_context(cairo) orelse unreachable
};
backend.textLayout = c.pango_layout_new(backend.textContext) orelse unreachable;
c.pango_layout_set_wrap(backend.textLayout, .PANGO_WRAP_WORD_CHAR);
backend.setFontFace("Nunito 12");
c.glfwSetWindowUserPointer(window, &backend);
return backend;
}
/// Return true if loop should continue.
pub fn update(self: *CairoBackend) bool {
c.glfwSetWindowUserPointer(self.window, self);
var width: c_int = 0;
var height: c_int = 0;
c.glfwGetFramebufferSize(self.window, &width, &height);
c.glViewport(0, 0, width, height);
if (self.frame_requested) {
c.cairo_surface_flush(self.surface);
var data = c.cairo_image_surface_get_data(self.surface);
c.glTexImage2D(c.GL_TEXTURE_2D, 0, c.GL_RGB,
c.cairo_image_surface_get_width(self.surface),
c.cairo_image_surface_get_height(self.surface), 0, c.GL_RGBA, c.GL_UNSIGNED_BYTE, data);
if (self.request_next_frame) {
self.request_next_frame = false;
} else {
self.frame_requested = false;
}
}
c.glDrawElements(c.GL_TRIANGLES, 6, c.GL_UNSIGNED_INT, null);
std.time.sleep(16*1000000);
c.glfwSwapBuffers(self.window);
c.glfwPollEvents();
return c.glfwWindowShouldClose(self.window) != 1;
}
pub fn getCursorX(self: *CairoBackend) f64 {
var x: f64 = undefined;
c.glfwGetCursorPos(self.window, &x, null);
return x;
}
pub fn getCursorY(self: *CairoBackend) f64 {
var y: f64 = undefined;
c.glfwGetCursorPos(self.window, null, &y);
return y;
}
pub fn setCursor(self: *CairoBackend, cursor: Cursor) void {
if (cursor == self.previousCursor) return;
if (cursor == .Normal) {
c.glfwSetCursor(self.window, null);
} else {
const cursorType: c_int = switch (cursor) {
.Text => c.GLFW_IBEAM_CURSOR,
.Normal => unreachable
};
const glfwCursor = c.glfwCreateStandardCursor(cursorType);
c.glfwSetCursor(self.window, glfwCursor);
//c.glfwDestroyCursor(glfwCursor);
}
self.previousCursor = cursor;
}
pub fn isMousePressed(self: *CairoBackend, btn: MouseButton) bool {
return c.glfwGetMouseButton(self.window, @enumToInt(btn)) == c.GLFW_PRESS;
}
pub fn getWidth(self: *CairoBackend) f64 {
return @intToFloat(f64, c.cairo_image_surface_get_width(self.surface));
}
pub fn getHeight(self: *CairoBackend) f64 {
return @intToFloat(f64, c.cairo_image_surface_get_height(self.surface));
}
pub fn deinit(self: *CairoBackend) void {
c.cairo_surface_destroy(self.surface);
c.cairo_destroy(self.cairo);
c.glfwTerminate();
}
// Draw functions
pub fn fill(self: *CairoBackend) void {
c.cairo_fill(self.cairo);
}
pub fn stroke(self: *CairoBackend) void {
c.cairo_stroke(self.cairo);
}
pub fn setSourceRGB(self: *CairoBackend, r: f64, g: f64, b: f64) void {
c.cairo_set_source_rgb(self.cairo, r, g, b);
}
pub fn setSourceRGBA(self: *CairoBackend, r: f64, g: f64, b: f64, a: f64) void {
c.cairo_set_source_rgba(self.cairo, r, g, b, a);
}
// Path
pub fn moveTo(self: *CairoBackend, x: f64, y: f64) void {
c.cairo_move_to(self.cairo, x, y);
}
pub fn moveBy(self: *CairoBackend, x: f64, y: f64) void {
c.cairo_rel_move_to(self.cairo, x, y);
}
pub fn lineTo(self: *CairoBackend, x: f64, y: f64) void {
c.cairo_line_to(self.cairo, x, y);
}
pub fn rectangle(self: *CairoBackend, x: f64, y: f64, width: f64, height: f64) void {
c.cairo_rectangle(self.cairo, x, y, width, height);
}
pub fn setTextWrap(self: *CairoBackend, width: ?f64) void {
c.pango_layout_set_width(self.textLayout, if (width) |w| @floatToInt(c_int, @floor(w * @as(f64, c.PANGO_SCALE))) else -1);
}
pub fn text(self: *CairoBackend, str: [:0]const u8) void {
var inkRect: c.PangoRectangle = undefined;
c.pango_layout_get_pixel_extents(self.textLayout, null, &inkRect);
c.cairo_save(self.cairo);
const dx = @intToFloat(f64, inkRect.x);
const dy = @intToFloat(f64, inkRect.y);
c.cairo_rel_move_to(self.cairo, dx, dy);
c.pango_layout_set_text(self.textLayout, str, @intCast(c_int, str.len));
c.pango_cairo_update_layout(self.cairo, self.textLayout);
c.pango_cairo_show_layout(self.cairo, self.textLayout);
c.cairo_restore(self.cairo);
}
pub fn setFontFace(self: *CairoBackend, font: [:0]const u8) void {
if (self.currentFontDesc != null) {
c.pango_font_description_free(self.currentFontDesc);
}
self.currentFontDesc = c.pango_font_description_from_string(font) orelse unreachable;
self.currentFont = c.pango_context_load_font(self.textContext, self.currentFontDesc);
c.pango_layout_set_font_description(self.textLayout, self.currentFontDesc);
}
pub fn setFontSize(self: *CairoBackend, size: f64) void {
c.pango_font_description_set_size(self.currentFontDesc, @floatToInt(c_int, @floor(size * @as(f64, c.PANGO_SCALE))));
c.pango_layout_set_font_description(self.textLayout, self.currentFontDesc);
self.currentFont = c.pango_context_load_font(self.textContext, self.currentFontDesc);
}
pub fn getFontMetrics(self: *CairoBackend) FontMetrics {
var metrics: c.cairo_font_extents_t = undefined;
c.cairo_font_extents(self.cairo, &metrics);
const metrics = c.pango_font_get_metrics(self.currentFont);
defer c.pango_font_metrics_unref(metrics);
return .{
.ascent = c.pango_font_metrics_get_ascent(metrics),
.descent = c.pango_font_metrics_get_descent(metrics),
.height = c.pango_font_metrics_get_height(metrics)
};
}
pub fn getTextMetrics(self: *CairoBackend, str: [:0]const u8) TextMetrics {
var width: c_int = undefined;
var height: c_int = undefined;
c.pango_layout_set_text(self.textLayout, str, @intCast(c_int, str.len));
c.pango_layout_get_pixel_size(self.textLayout, &width, &height);
return .{
.width = @intToFloat(f64, width),
.height = @intToFloat(f64, height)
};
}
pub fn clear(self: *CairoBackend) void {
c.cairo_set_source_rgb(self.cairo, 1.0, 1.0, 1.0);
c.cairo_rectangle(self.cairo, 0, 0, self.getWidth(), self.getHeight());
c.cairo_fill(self.cairo);
}
}; | src/cairo.zig |
const c = @import("c.zig");
const nk = @import("../nuklear.zig");
const std = @import("std");
const mem = std.mem;
const testing = std.testing;
pub const Behavior = c.nk_button_behavior;
pub fn label(ctx: *nk.Context, title: []const u8) bool {
return c.nk_button_label(ctx, nk.slice(title)) != 0;
}
pub fn color(ctx: *nk.Context, col: nk.Color) bool {
return c.nk_button_color(ctx, col) != 0;
}
pub fn symbol(ctx: *nk.Context, sym: nk.SymbolType) bool {
return c.nk_button_symbol(ctx, sym) != 0;
}
pub fn image(ctx: *nk.Context, img: nk.Image) bool {
return c.nk_button_image(ctx, img) != 0;
}
pub fn symbolLabel(ctx: *nk.Context, sym: nk.SymbolType, title: []const u8, flags: nk.Flags) bool {
return c.nk_button_symbol_label(ctx, sym, nk.slice(title), flags) != 0;
}
pub fn imageLabel(ctx: *nk.Context, img: nk.Image, title: []const u8, flags: nk.Flags) bool {
return c.nk_button_image_label(ctx, img, nk.slice(title), flags) != 0;
}
pub fn labelStyled(ctx: *nk.Context, style: *const nk.StyleButton, title: []const u8) bool {
return c.nk_button_label_styled(ctx, style, nk.slice(title)) != 0;
}
pub fn symbolStyled(ctx: *nk.Context, style: *const nk.StyleButton, sym: nk.SymbolType) bool {
return c.nk_button_symbol_styled(ctx, style, sym) != 0;
}
pub fn imageStyled(ctx: *nk.Context, style: *const nk.StyleButton, img: nk.Image) bool {
return c.nk_button_image_styled(ctx, style, img) != 0;
}
pub fn symbolLabelStyled(
ctx: *nk.Context,
style: *const nk.StyleButton,
sym: nk.SymbolType,
title: []const u8,
flags: nk.Flags,
) bool {
return c.nk_button_symbol_label_styled(ctx, style, sym, nk.slice(title), flags) != 0;
}
pub fn imageLabelStyled(
ctx: *nk.Context,
style: *const nk.StyleButton,
img: nk.Image,
title: []const u8,
flags: nk.Flags,
) bool {
return c.nk_button_image_label_styled(ctx, style, img, nk.slice(title), flags) != 0;
}
pub fn setBehavior(ctx: *nk.Context, behavior: Behavior) void {
return c.nk_button_set_behavior(ctx, behavior);
}
pub fn pushBehavior(ctx: *nk.Context, behavior: Behavior) bool {
return c.nk_button_push_behavior(ctx, behavior) != 0;
}
pub fn popBehavior(ctx: *nk.Context) bool {
return c.nk_button_pop_behavior(ctx) != 0;
}
test {
testing.refAllDecls(@This());
} | src/button.zig |
pub const WasmError = opaque {
/// Gets the error message
pub fn getMessage(self: *WasmError) ByteVec {
var bytes: ByteVec = undefined;
wasmtime_error_message(self, &bytes);
return bytes;
}
/// Frees the error resources
pub fn deinit(self: *WasmError) void {
wasmtime_error_delete(self);
}
extern fn wasmtime_error_delete(*WasmError) void;
extern fn wasmtime_error_message(*WasmError, *ByteVec) void;
};
pub const Trap = opaque {
pub fn deinit(self: *Trap) void {
wasm_trap_delete(self);
}
extern fn wasm_trap_delete(*Trap) void;
};
pub const Extern = opaque {
/// Returns the `Extern` as a function
pub fn asFunc(self: *Extern) ?*c_void {
return wasm_extern_as_func(self);
}
extern fn wasm_extern_as_func(external: *c_void) ?*c_void;
};
pub const ExportType = opaque {
pub fn name(self: *ExportType) *ByteVec {
return self.wasm_exporttype_name().?;
}
extern fn wasm_exporttype_name(*ExportType) ?*ByteVec;
};
pub const ExportTypeVec = extern struct {
size: usize,
data: [*]?*ExportType,
pub fn toSlice(self: *const ExportTypeVec) []const ?*ExportType {
return self.data[0..self.size];
}
pub fn deinit(self: *ExportTypeVec) void {
self.wasm_exporttype_vec_delete();
}
extern fn wasm_exporttype_vec_delete(*ExportTypeVec) void;
};
pub const InstanceType = opaque {
pub fn deinit(self: *InstanceType) void {
self.wasm_instancetype_delete();
}
pub fn exports(self: *InstanceType) ExportTypeVec {
var export_vec: ExportTypeVec = undefined;
self.wasm_instancetype_exports(&export_vec);
return export_vec;
}
extern fn wasm_instancetype_delete(*InstanceType) void;
extern fn wasm_instancetype_exports(*InstanceType, ?*ExportTypeVec) void;
};
pub const Callback = fn (?*const Valtype, ?*Valtype) callconv(.C) ?*Trap;
// Bits
pub const ByteVec = extern struct {
size: usize,
data: [*]u8,
/// Initializes a new wasm byte vector
pub fn initWithCapacity(size: usize) ByteVec {
var bytes: ByteVec = undefined;
wasm_byte_vec_new_uninitialized(&bytes, size);
return bytes;
}
/// Returns a slice to the byte vector
pub fn toSlice(self: ByteVec) []const u8 {
return self.data[0..self.size];
}
/// Frees the memory allocated by initWithCapacity
pub fn deinit(self: *ByteVec) void {
wasm_byte_vec_delete(self);
}
extern fn wasm_byte_vec_new_uninitialized(ptr: *ByteVec, size: usize) void;
extern fn wasm_byte_vec_delete(ptr: *ByteVec) void;
};
pub const ExternVec = extern struct {
size: usize,
data: [*]?*Extern,
pub fn empty() ExternVec {
return .{ .size = 0, .data = undefined };
}
pub fn deinit(self: *ExternVec) void {
wasm_extern_vec_delete(self);
}
pub fn initWithCapacity(size: usize) ExternVec {
var externs: ExternVec = undefined;
wasm_extern_vec_new_uninitialized(&externs, size);
return externs;
}
extern fn wasm_extern_vec_new_empty(ptr: *ExternVec) void;
extern fn wasm_extern_vec_new_uninitialized(ptr: *ExternVec, size: usize) void;
extern fn wasm_extern_vec_delete(ptr: *ExternVec) void;
};
pub const Valkind = extern enum(u8) {
i32 = 0,
i64 = 1,
f32 = 2,
f64 = 3,
anyref = 128,
funcref = 129,
};
pub const Value = extern struct {
kind: Valkind,
of: extern union {
i32: i32,
i64: i64,
f32: f32,
f64: f64,
ref: ?*c_void,
},
};
pub const Valtype = opaque {
/// Initializes a new `Valtype` based on the given `Valkind`
pub fn init(kind: Valkind) *Valtype {
return wasm_valtype_new(@enumToInt(kind));
}
pub fn deinit(self: *Valtype) void {
wasm_valtype_delete(self);
}
/// Returns the `Valkind` of the given `Valtype`
pub fn kind(self: *Valtype) Valkind {
return @intToEnum(Valkind, wasm_valtype_kind(self));
}
extern fn wasm_valtype_new(kind: u8) *Valtype;
extern fn wasm_valtype_delete(*Valkind) void;
extern fn wasm_valtype_kind(*Valkind) u8;
};
pub const ValtypeVec = extern struct {
size: usize,
data: [*]?*Valtype,
pub fn empty() ValtypeVec {
return .{ .size = 0, .data = undefined };
}
};
pub const ValVec = extern struct {
size: usize,
data: [*]Value,
pub fn initWithCapacity(size: usize) ValVec {
var bytes: ValVec = undefined;
wasm_val_vec_new_uninitialized(&bytes, size);
return bytes;
}
pub fn deinit(self: *ValVec) void {
self.wasm_val_vec_delete();
}
extern fn wasm_val_vec_new_uninitialized(*ValVec, usize) void;
extern fn wasm_val_vec_delete(*ValVec) void;
};
// Func
pub extern fn wasm_functype_new(args: *ValtypeVec, results: *ValtypeVec) ?*c_void;
pub extern fn wasm_functype_delete(functype: *c_void) void;
// Helpers
pub extern fn wasmtime_wat2wasm(wat: *ByteVec, wasm: *ByteVec) ?*WasmError; | src/c.zig |
const std = @import("std");
const zbs = std.build;
const fs = std.fs;
const mem = std.mem;
pub fn build(b: *zbs.Builder) void {
const target = b.standardTargetOptions(.{});
const mode = b.standardReleaseOptions();
const scanner = ScanProtocolsStep.create(b);
inline for ([_][]const u8{ "globals", "list", "listener", "seats" }) |example| {
const exe = b.addExecutable(example, "example/" ++ example ++ ".zig");
exe.setTarget(target);
exe.setBuildMode(mode);
exe.step.dependOn(&scanner.step);
exe.addPackage(scanner.getPkg());
scanner.addCSource(exe);
exe.linkLibC();
exe.linkSystemLibrary("wayland-client");
exe.install();
}
const test_step = b.step("test", "Run the tests");
for ([_][]const u8{ "src/scanner.zig", "src/common_core.zig" }) |file| {
const t = b.addTest(file);
t.setTarget(target);
t.setBuildMode(mode);
test_step.dependOn(&t.step);
}
{
const ref_all = b.addTest("src/ref_all.zig");
ref_all.setTarget(target);
ref_all.setBuildMode(mode);
ref_all.step.dependOn(&scanner.step);
ref_all.addPackage(scanner.getPkg());
scanner.addCSource(ref_all);
ref_all.linkLibC();
ref_all.linkSystemLibrary("wayland-client");
ref_all.linkSystemLibrary("wayland-server");
ref_all.linkSystemLibrary("wayland-egl");
ref_all.linkSystemLibrary("wayland-cursor");
test_step.dependOn(&ref_all.step);
}
}
pub const ScanProtocolsStep = struct {
const scanner = @import("src/scanner.zig");
builder: *zbs.Builder,
step: zbs.Step,
/// zig-cache/zig-wayland of the importing project
out_path: []const u8,
/// Slice of absolute paths of protocol xml files to be scanned
protocol_paths: std.ArrayList([]const u8),
pub fn create(builder: *zbs.Builder) *ScanProtocolsStep {
const ally = builder.allocator;
const self = ally.create(ScanProtocolsStep) catch unreachable;
self.* = .{
.builder = builder,
.step = zbs.Step.init(.Custom, "Scan Protocols", ally, make),
.out_path = fs.path.resolve(ally, &[_][]const u8{
builder.build_root,
builder.cache_root,
"zig-wayland",
}) catch unreachable,
.protocol_paths = std.ArrayList([]const u8).init(ally),
};
return self;
}
/// Generate bindings from the protocol xml at the given absolute or relative path
pub fn addProtocolPath(self: *ScanProtocolsStep, path: []const u8) void {
self.protocol_paths.append(path) catch unreachable;
}
/// Generate bindings from protocol xml provided by the wayland-protocols
/// package given the relative path (e.g. "stable/xdg-shell/xdg-shell.xml")
pub fn addSystemProtocol(self: *ScanProtocolsStep, relative_path: []const u8) void {
const protocol_dir = mem.trim(u8, self.builder.exec(
&[_][]const u8{ "pkg-config", "--variable=pkgdatadir", "wayland-protocols" },
) catch unreachable, &std.ascii.spaces);
self.addProtocolPath(fs.path.join(
self.builder.allocator,
&[_][]const u8{ protocol_dir, relative_path },
) catch unreachable);
}
fn make(step: *zbs.Step) !void {
const self = @fieldParentPtr(ScanProtocolsStep, "step", step);
const ally = self.builder.allocator;
const wayland_dir = mem.trim(u8, try self.builder.exec(
&[_][]const u8{ "pkg-config", "--variable=pkgdatadir", "wayland-scanner" },
), &std.ascii.spaces);
const wayland_xml = try fs.path.join(ally, &[_][]const u8{ wayland_dir, "wayland.xml" });
var root = try fs.cwd().openDir(self.builder.build_root, .{});
defer root.close();
try scanner.scan(root, self.out_path, wayland_xml, self.protocol_paths.items);
// Once https://github.com/ziglang/zig/issues/131 is implemented
// we can stop generating/linking C code.
for (self.protocol_paths.items) |path| {
_ = try self.builder.exec(
&[_][]const u8{ "wayland-scanner", "private-code", path, self.getCodePath(path) },
);
}
}
/// Add the necessary C source to the compilation unit.
/// Once https://github.com/ziglang/zig/issues/131 we can remove this.
pub fn addCSource(self: *ScanProtocolsStep, obj: *zbs.LibExeObjStep) void {
for (self.protocol_paths.items) |path|
obj.addCSourceFile(self.getCodePath(path), &[_][]const u8{"-std=c99"});
}
pub fn getPkg(self: *ScanProtocolsStep) zbs.Pkg {
const ally = self.builder.allocator;
return .{
.name = "wayland",
.path = fs.path.join(ally, &[_][]const u8{ self.out_path, "wayland.zig" }) catch unreachable,
};
}
fn getCodePath(self: *ScanProtocolsStep, xml_in_path: []const u8) []const u8 {
const ally = self.builder.allocator;
// Extension is .xml, so slice off the last 4 characters
const basename = fs.path.basename(xml_in_path);
const basename_no_ext = basename[0..(basename.len - 4)];
const code_filename = std.fmt.allocPrint(ally, "{}-protocol.c", .{basename_no_ext}) catch unreachable;
return fs.path.join(ally, &[_][]const u8{ self.out_path, code_filename }) catch unreachable;
}
}; | build.zig |
usingnamespace @import("raylib");
usingnamespace @import("raylib-math");
const MAX_BUILDINGS = 100;
pub fn main() anyerror!void
{
// Initialization
//--------------------------------------------------------------------------------------
const screenWidth = 800;
const screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib-zig [core] example - 2d camera");
var player = Rectangle { .x = 400, .y = 280, .width = 40, .height = 40 };
var buildings: [MAX_BUILDINGS]Rectangle = undefined;
var buildColors: [MAX_BUILDINGS]Color = undefined;
var spacing: i32 = 0;
for (buildings) |building, i|
{
buildings[i].width = @intToFloat(f32, GetRandomValue(50, 200));
buildings[i].height = @intToFloat(f32, GetRandomValue(100, 800));
buildings[i].y = screenHeight - 130 - buildings[i].height;
buildings[i].x = @intToFloat(f32, -6000 + spacing);
spacing += @floatToInt(i32, buildings[i].width);
buildColors[i] = Color { .r = @intCast(u8, GetRandomValue(200, 240)), .g = @intCast(u8, GetRandomValue(200, 240)),
.b = @intCast(u8, GetRandomValue(200, 250)), .a = 255 };
}
var camera = Camera2D {
.target = Vector2 { .x = player.x + 20, .y = player.y + 20 },
.offset = Vector2 { .x = screenWidth/2, .y = screenHeight/2 },
.rotation = 0,
.zoom = 1,
};
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
// Update
//----------------------------------------------------------------------------------
// Player movement
if (IsKeyDown(KeyboardKey.KEY_RIGHT)) { player.x += 2; }
else if (IsKeyDown(KeyboardKey.KEY_LEFT)) { player.x -= 2; }
// Camera target follows player
camera.target = Vector2 { .x = player.x + 20, .y = player.y + 20 };
// Camera rotation controls
if (IsKeyDown(KeyboardKey.KEY_A)) { camera.rotation -= 1; }
else if (IsKeyDown(KeyboardKey.KEY_S)) { camera.rotation += 1; }
// Limit camera rotation to 80 degrees (-40 to 40)
camera.rotation = Clamp(camera.rotation, -40, 40);
// Camera zoom controls
camera.zoom += @intToFloat(f32, GetMouseWheelMove() * @floatToInt(c_int, 0.05));
camera.zoom = Clamp(camera.zoom, 0.1, 3.0);
// Camera reset (zoom and rotation)
if (IsKeyPressed(KeyboardKey.KEY_R))
{
camera.zoom = 1.0;
camera.rotation = 0.0;
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(RAYWHITE);
camera.Begin();
DrawRectangle(-6000, 320, 13000, 8000, DARKGRAY);
for (buildings) |building, i|
{
//DrawRectangleRec(building, buildColors[i]);
DrawRectangle(@floatToInt(c_int, building.x), @floatToInt(c_int, building.y),
@floatToInt(c_int, building.width), @floatToInt(c_int, building.height), buildColors[i]);
}
DrawRectangle(@floatToInt(c_int, player.x), @floatToInt(c_int, player.y),
@floatToInt(c_int, player.width), @floatToInt(c_int, player.height), DARKGRAY);
//DrawRectangleRec(player, RED);
DrawLine(@floatToInt(c_int, camera.target.x), -screenHeight*10, @floatToInt(c_int, camera.target.x), screenHeight*10, GREEN);
DrawLine(-screenWidth*10, @floatToInt(c_int, camera.target.y), screenWidth*10, @floatToInt(c_int, camera.target.y), GREEN);
camera.End();
DrawText("SCREEN AREA", 640, 10, 20, RED);
DrawRectangle(0, 0, screenWidth, 5, RED);
DrawRectangle(0, 5, 5, screenHeight - 10, RED);
DrawRectangle(screenWidth - 5, 5, 5, screenHeight - 10, RED);
DrawRectangle(0, screenHeight - 5, screenWidth, 5, RED);
DrawRectangle( 10, 10, 250, 113, Fade(SKYBLUE, 0.5));
DrawRectangleLines( 10, 10, 250, 113, BLUE);
DrawText("Free 2d camera controls:", 20, 20, 10, BLACK);
DrawText("- Right/Left to move Offset", 40, 40, 10, DARKGRAY);
DrawText("- Mouse Wheel to Zoom in-out", 40, 60, 10, DARKGRAY);
DrawText("- A / S to Rotate", 40, 80, 10, DARKGRAY);
DrawText("- R to reset Zoom and Rotation", 40, 100, 10, DARKGRAY);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
} | examples/core/2d_camera.zig |
/// perfect.zig
/// Module to find perfect numbers
///
const std = @import("std");
//const heap = std.heap;
//const mem = std.mem;
//const warn = std.debug.warn;
/// Finding perfect numbers
/// Predicate for perfect numbers
pub fn is_perfect(comptime T: type, n: T) bool {
var i: T = 1;
var sum: T = 0;
while (i < n) : (i += 1) {
if (n % i == 0) sum += i;
}
return sum == n;
}
/// Generates perfect number up to given limit [n]
pub fn perfect_numbers(comptime T: type, allocator: *std.mem.Allocator, limit: T) !std.ArrayList(T) {
var res = std.ArrayList(T).init(allocator);
var i: T = 1;
while (i <= limit) : (i += 1) {
if (is_perfect(T, i)) {
try res.append(i);
}
}
return res;
}
/// String representation of perfect numbers array list
pub fn to_str(comptime T: type, allocator: *std.mem.Allocator, ary: std.ArrayList(T)) !std.ArrayList(u8) {
var buf = std.ArrayList(u8).init(allocator);
const w = buf.writer();
const slice = ary.items;
_ = try w.write("[");
if (slice.len > 0) {
try w.print("{}", .{slice[0]});
for (slice[1..]) |e| {
try w.print(", {}", .{e});
}
//try w.print("length: {}", .{slice.len});
}
_ = try w.write("]");
return buf;
}
fn print_list_head(comptime T: type, list: std.SinglyLinkedList(T)) void {
if (list.first) |head| {
std.debug.print("head: {}", .{head.data});
if (head.next) |snd| {
std.debug.print(" snd: {}", .{snd.data});
if (snd.next) |third| {
std.debug.print(" third: {}", .{third.data});
}
}
} else {
std.debug.print("<EMPTY>", .{});
}
std.debug.print("\n", .{});
}
/// Generates perfect number up to given limit [n]
pub fn perfect_number_list(comptime T: type, limit: T) std.SinglyLinkedList(T) {
const L = std.SinglyLinkedList(T);
var res = L{};
var i: T = 1;
while (i <= limit) : (i += 1) {
if (is_perfect(T, i)) {
var entry = L.Node{ .data = i };
std.debug.print("new node: {}\n", .{entry});
res.prepend(&entry);
print_list_head(T, res);
}
}
return res;
}
/// String representation of a singly linked list
//pub fn to_str(comptime T: type, l: std.SinglyLinkedList(T)) ![]u8 {
// const allocator = heap.page_allocator;
// var buf = try std.Buffer.init(allocator, "[");
// defer buf.deinit();
//
// var it = l.first;
// while (it) |node| : (it = node.next) {
// // concat to given string
// try std.fmt.formatIntValue(node.data, "", std.fmt.FormatOptions{}, &buf, @TypeOf(std.Buffer.append).ReturnType.ErrorSet, std.Buffer.append);
// try buf.append(",");
// }
// try buf.append("]");
//
// return buf.toOwnedSlice();
//}
const testing = std.testing;
test "is perfect" {
try testing.expect(!is_perfect(u32, 1));
try testing.expect(!is_perfect(u32, 2));
try testing.expect(!is_perfect(u32, 3));
try testing.expect(!is_perfect(u32, 4));
try testing.expect(!is_perfect(u32, 5));
try testing.expect(is_perfect(u32, 6));
try testing.expect(!is_perfect(u32, 7));
try testing.expect(is_perfect(u32, 28));
}
test "perfect numbers" {
const test_allocator = testing.allocator;
const exp = [_]u32{ 6, 28, 496 };
var res = try perfect_numbers(u32, test_allocator, 1000);
defer res.deinit();
try testing.expect(std.mem.eql(u32, res.items, exp[0..]));
}
//test "perfect number list" {
// var res = perfect_number_list(u32, 1000);
// const exp = [_]u32{ 496, 28, 6 };
// {
// var it = res.first;
// var idx: u32 = 0;
// //std.debug.print("\n", .{});
// while (it) |node| : (it = node.next) { // FIXME: test failure all node.data = 496?
// //std.debug.print("idx: {}, &node: {}, data: {}, next: {}\n", .{ idx, &node, node.data, &node.next });
// //testing.expect(node.data == exp[idx]);
// idx += 1;
// if (idx > 10) break;
// }
// }
//}
test "string representation of perfect numbers list" {
const test_allocator = testing.allocator;
const res_0 = try perfect_numbers(u32, test_allocator, 5);
defer res_0.deinit();
const res_1 = try perfect_numbers(u32, test_allocator, 10);
defer res_1.deinit();
const res_2 = try perfect_numbers(u32, test_allocator, 30);
defer res_2.deinit();
const res_0_str = try to_str(u32, test_allocator, res_0);
defer res_0_str.deinit();
const res_1_str = try to_str(u32, test_allocator, res_1);
defer res_1_str.deinit();
const res_2_str = try to_str(u32, test_allocator, res_2);
defer res_2_str.deinit();
try testing.expect(std.mem.eql(u8, res_0_str.items, "[]"));
try testing.expect(std.mem.eql(u8, res_1_str.items, "[6]"));
try testing.expect(std.mem.eql(u8, res_2_str.items, "[6, 28]"));
} | Zig/benchmark/src/perfect.zig |
const std = @import("std");
const Sha1 = std.crypto.hash.Sha1;
const expectEqual = std.testing.expectEqual;
const fmt = std.fmt;
const mem = std.mem;
const os = std.os;
const testing = std.testing;
const des = @import("zig-crypto").des;
const DES = des.DES;
const TDES = des.TDES;
fn desRoundsInt(comptime crypt_mode: des.CryptMode, keyLong: u64, dataLong: u64) u64 {
const reversedKey = @byteSwap(u64, keyLong);
const key = mem.asBytes(&reversedKey).*;
const reversedData = @byteSwap(u64, dataLong);
const source = mem.asBytes(&reversedData);
var dest: [8]u8 = undefined;
var cipher = DES.init(key);
cipher.crypt(crypt_mode, &dest, source);
return mem.readIntBig(u64, &dest);
}
fn desEncryptTest(keyLong: u64, dataLong: u64) u64 {
return desRoundsInt(.Encrypt, keyLong, dataLong);
}
fn desDecryptTest(keyLong: u64, dataLong: u64) u64 {
return desRoundsInt(.Decrypt, keyLong, dataLong);
}
// https://www.cosic.esat.kuleuven.be/nessie/testvectors/bc/des/Des-64-64.test-vectors
test "DES encrypt" {
expectEqual(@as(u64, 0x994D4DC157B96C52), desEncryptTest(0x0101010101010101, 0x0101010101010101));
expectEqual(@as(u64, 0xE127C2B61D98E6E2), desEncryptTest(0x0202020202020202, 0x0202020202020202));
expectEqual(@as(u64, 0x984C91D78A269CE3), desEncryptTest(0x0303030303030303, 0x0303030303030303));
expectEqual(@as(u64, 0x1F4570BB77550683), desEncryptTest(0x0404040404040404, 0x0404040404040404));
expectEqual(@as(u64, 0x3990ABF98D672B16), desEncryptTest(0x0505050505050505, 0x0505050505050505));
expectEqual(@as(u64, 0x3F5150BBA081D585), desEncryptTest(0x0606060606060606, 0x0606060606060606));
expectEqual(@as(u64, 0xC65242248C9CF6F2), desEncryptTest(0x0707070707070707, 0x0707070707070707));
expectEqual(@as(u64, 0x10772D40FAD24257), desEncryptTest(0x0808080808080808, 0x0808080808080808));
expectEqual(@as(u64, 0xF0139440647A6E7B), desEncryptTest(0x0909090909090909, 0x0909090909090909));
expectEqual(@as(u64, 0x0A288603044D740C), desEncryptTest(0x0A0A0A0A0A0A0A0A, 0x0A0A0A0A0A0A0A0A));
expectEqual(@as(u64, 0x6359916942F7438F), desEncryptTest(0x0B0B0B0B0B0B0B0B, 0x0B0B0B0B0B0B0B0B));
expectEqual(@as(u64, 0x934316AE443CF08B), desEncryptTest(0x0C0C0C0C0C0C0C0C, 0x0C0C0C0C0C0C0C0C));
expectEqual(@as(u64, 0xE3F56D7F1130A2B7), desEncryptTest(0x0D0D0D0D0D0D0D0D, 0x0D0D0D0D0D0D0D0D));
expectEqual(@as(u64, 0xA2E4705087C6B6B4), desEncryptTest(0x0E0E0E0E0E0E0E0E, 0x0E0E0E0E0E0E0E0E));
expectEqual(@as(u64, 0xD5D76E09A447E8C3), desEncryptTest(0x0F0F0F0F0F0F0F0F, 0x0F0F0F0F0F0F0F0F));
expectEqual(@as(u64, 0xDD7515F2BFC17F85), desEncryptTest(0x1010101010101010, 0x1010101010101010));
expectEqual(@as(u64, 0xF40379AB9E0EC533), desEncryptTest(0x1111111111111111, 0x1111111111111111));
expectEqual(@as(u64, 0x96CD27784D1563E5), desEncryptTest(0x1212121212121212, 0x1212121212121212));
expectEqual(@as(u64, 0x2911CF5E94D33FE1), desEncryptTest(0x1313131313131313, 0x1313131313131313));
expectEqual(@as(u64, 0x377B7F7CA3E5BBB3), desEncryptTest(0x1414141414141414, 0x1414141414141414));
expectEqual(@as(u64, 0x701AA63832905A92), desEncryptTest(0x1515151515151515, 0x1515151515151515));
expectEqual(@as(u64, 0x2006E716C4252D6D), desEncryptTest(0x1616161616161616, 0x1616161616161616));
expectEqual(@as(u64, 0x452C1197422469F8), desEncryptTest(0x1717171717171717, 0x1717171717171717));
expectEqual(@as(u64, 0xC33FD1EB49CB64DA), desEncryptTest(0x1818181818181818, 0x1818181818181818));
expectEqual(@as(u64, 0x7572278F364EB50D), desEncryptTest(0x1919191919191919, 0x1919191919191919));
expectEqual(@as(u64, 0x69E51488403EF4C3), desEncryptTest(0x1A1A1A1A1A1A1A1A, 0x1A1A1A1A1A1A1A1A));
expectEqual(@as(u64, 0xFF847E0ADF192825), desEncryptTest(0x1B1B1B1B1B1B1B1B, 0x1B1B1B1B1B1B1B1B));
expectEqual(@as(u64, 0x521B7FB3B41BB791), desEncryptTest(0x1C1C1C1C1C1C1C1C, 0x1C1C1C1C1C1C1C1C));
expectEqual(@as(u64, 0x26059A6A0F3F6B35), desEncryptTest(0x1D1D1D1D1D1D1D1D, 0x1D1D1D1D1D1D1D1D));
expectEqual(@as(u64, 0xF24A8D2231C77538), desEncryptTest(0x1E1E1E1E1E1E1E1E, 0x1E1E1E1E1E1E1E1E));
expectEqual(@as(u64, 0x4FD96EC0D3304EF6), desEncryptTest(0x1F1F1F1F1F1F1F1F, 0x1F1F1F1F1F1F1F1F));
}
test "DES decrypt" {
expectEqual(@as(u64, 0x0101010101010101), desDecryptTest(0x0101010101010101, 0x994D4DC157B96C52));
expectEqual(@as(u64, 0x0202020202020202), desDecryptTest(0x0202020202020202, 0xE127C2B61D98E6E2));
expectEqual(@as(u64, 0x0303030303030303), desDecryptTest(0x0303030303030303, 0x984C91D78A269CE3));
expectEqual(@as(u64, 0x0404040404040404), desDecryptTest(0x0404040404040404, 0x1F4570BB77550683));
expectEqual(@as(u64, 0x0505050505050505), desDecryptTest(0x0505050505050505, 0x3990ABF98D672B16));
expectEqual(@as(u64, 0x0606060606060606), desDecryptTest(0x0606060606060606, 0x3F5150BBA081D585));
expectEqual(@as(u64, 0x0707070707070707), desDecryptTest(0x0707070707070707, 0xC65242248C9CF6F2));
expectEqual(@as(u64, 0x0808080808080808), desDecryptTest(0x0808080808080808, 0x10772D40FAD24257));
expectEqual(@as(u64, 0x0909090909090909), desDecryptTest(0x0909090909090909, 0xF0139440647A6E7B));
expectEqual(@as(u64, 0x0A0A0A0A0A0A0A0A), desDecryptTest(0x0A0A0A0A0A0A0A0A, 0x0A288603044D740C));
expectEqual(@as(u64, 0x0B0B0B0B0B0B0B0B), desDecryptTest(0x0B0B0B0B0B0B0B0B, 0x6359916942F7438F));
expectEqual(@as(u64, 0x0C0C0C0C0C0C0C0C), desDecryptTest(0x0C0C0C0C0C0C0C0C, 0x934316AE443CF08B));
expectEqual(@as(u64, 0x0D0D0D0D0D0D0D0D), desDecryptTest(0x0D0D0D0D0D0D0D0D, 0xE3F56D7F1130A2B7));
expectEqual(@as(u64, 0x0E0E0E0E0E0E0E0E), desDecryptTest(0x0E0E0E0E0E0E0E0E, 0xA2E4705087C6B6B4));
expectEqual(@as(u64, 0x0F0F0F0F0F0F0F0F), desDecryptTest(0x0F0F0F0F0F0F0F0F, 0xD5D76E09A447E8C3));
expectEqual(@as(u64, 0x1010101010101010), desDecryptTest(0x1010101010101010, 0xDD7515F2BFC17F85));
expectEqual(@as(u64, 0x1111111111111111), desDecryptTest(0x1111111111111111, 0xF40379AB9E0EC533));
expectEqual(@as(u64, 0x1212121212121212), desDecryptTest(0x1212121212121212, 0x96CD27784D1563E5));
expectEqual(@as(u64, 0x1313131313131313), desDecryptTest(0x1313131313131313, 0x2911CF5E94D33FE1));
expectEqual(@as(u64, 0x1414141414141414), desDecryptTest(0x1414141414141414, 0x377B7F7CA3E5BBB3));
expectEqual(@as(u64, 0x1515151515151515), desDecryptTest(0x1515151515151515, 0x701AA63832905A92));
expectEqual(@as(u64, 0x1616161616161616), desDecryptTest(0x1616161616161616, 0x2006E716C4252D6D));
expectEqual(@as(u64, 0x1717171717171717), desDecryptTest(0x1717171717171717, 0x452C1197422469F8));
expectEqual(@as(u64, 0x1818181818181818), desDecryptTest(0x1818181818181818, 0xC33FD1EB49CB64DA));
expectEqual(@as(u64, 0x1919191919191919), desDecryptTest(0x1919191919191919, 0x7572278F364EB50D));
expectEqual(@as(u64, 0x1A1A1A1A1A1A1A1A), desDecryptTest(0x1A1A1A1A1A1A1A1A, 0x69E51488403EF4C3));
expectEqual(@as(u64, 0x1B1B1B1B1B1B1B1B), desDecryptTest(0x1B1B1B1B1B1B1B1B, 0xFF847E0ADF192825));
expectEqual(@as(u64, 0x1C1C1C1C1C1C1C1C), desDecryptTest(0x1C1C1C1C1C1C1C1C, 0x521B7FB3B41BB791));
expectEqual(@as(u64, 0x1D1D1D1D1D1D1D1D), desDecryptTest(0x1D1D1D1D1D1D1D1D, 0x26059A6A0F3F6B35));
expectEqual(@as(u64, 0x1E1E1E1E1E1E1E1E), desDecryptTest(0x1E1E1E1E1E1E1E1E, 0xF24A8D2231C77538));
expectEqual(@as(u64, 0x1F1F1F1F1F1F1F1F), desDecryptTest(0x1F1F1F1F1F1F1F1F, 0x4FD96EC0D3304EF6));
}
fn tdesRoundsInt(comptime crypt_mode: des.CryptMode, keyLong: u192, dataLong: u64) u64 {
const reversedKey = @byteSwap(u192, keyLong);
const smallKey = mem.asBytes(&reversedKey).*;
var key: [24]u8 = undefined;
mem.copy(u8, &key, &smallKey);
const reversedData = @byteSwap(u64, dataLong);
const source = mem.asBytes(&reversedData);
var dest: [8]u8 = undefined;
var cipher = TDES.init(key);
cipher.crypt(crypt_mode, &dest, source);
return mem.readIntBig(u64, &dest);
}
fn tdesEncryptTest(keyLong: u192, dataLong: u64) u64 {
return tdesRoundsInt(.Encrypt, keyLong, dataLong);
}
fn tdesDecryptTest(keyLong: u192, dataLong: u64) u64 {
return tdesRoundsInt(.Decrypt, keyLong, dataLong);
}
// https://www.cosic.esat.kuleuven.be/nessie/testvectors/bc/des/Triple-Des-3-Key-192-64.unverified.test-vectors
test "TDES encrypt" {
expectEqual(@as(u64, 0x95A8D72813DAA94D), tdesEncryptTest(0x800000000000000000000000000000000000000000000000, 0x0000000000000000));
expectEqual(@as(u64, 0x0EEC1487DD8C26D5), tdesEncryptTest(0x400000000000000000000000000000000000000000000000, 0x0000000000000000));
expectEqual(@as(u64, 0x7AD16FFB79C45926), tdesEncryptTest(0x200000000000000000000000000000000000000000000000, 0x0000000000000000));
expectEqual(@as(u64, 0xD3746294CA6A6CF3), tdesEncryptTest(0x100000000000000000000000000000000000000000000000, 0x0000000000000000));
expectEqual(@as(u64, 0x809F5F873C1FD761), tdesEncryptTest(0x080000000000000000000000000000000000000000000000, 0x0000000000000000));
expectEqual(@as(u64, 0xC02FAFFEC989D1FC), tdesEncryptTest(0x040000000000000000000000000000000000000000000000, 0x0000000000000000));
expectEqual(@as(u64, 0x4615AA1D33E72F10), tdesEncryptTest(0x020000000000000000000000000000000000000000000000, 0x0000000000000000));
expectEqual(@as(u64, 0x8CA64DE9C1B123A7), tdesEncryptTest(0x010000000000000000000000000000000000000000000000, 0x0000000000000000));
expectEqual(@as(u64, 0x2055123350C00858), tdesEncryptTest(0x008000000000000000000000000000000000000000000000, 0x0000000000000000));
expectEqual(@as(u64, 0xDF3B99D6577397C8), tdesEncryptTest(0x004000000000000000000000000000000000000000000000, 0x0000000000000000));
expectEqual(@as(u64, 0x31FE17369B5288C9), tdesEncryptTest(0x002000000000000000000000000000000000000000000000, 0x0000000000000000));
expectEqual(@as(u64, 0xDFDD3CC64DAE1642), tdesEncryptTest(0x001000000000000000000000000000000000000000000000, 0x0000000000000000));
expectEqual(@as(u64, 0x178C83CE2B399D94), tdesEncryptTest(0x000800000000000000000000000000000000000000000000, 0x0000000000000000));
expectEqual(@as(u64, 0x50F636324A9B7F80), tdesEncryptTest(0x000400000000000000000000000000000000000000000000, 0x0000000000000000));
expectEqual(@as(u64, 0xA8468EE3BC18F06D), tdesEncryptTest(0x000200000000000000000000000000000000000000000000, 0x0000000000000000));
expectEqual(@as(u64, 0x8CA64DE9C1B123A7), tdesEncryptTest(0x000100000000000000000000000000000000000000000000, 0x0000000000000000));
}
test "TDES decrypt" {
expectEqual(@as(u64, 0x0000000000000000), tdesDecryptTest(0x800000000000000000000000000000000000000000000000, 0x95A8D72813DAA94D));
expectEqual(@as(u64, 0x0000000000000000), tdesDecryptTest(0x400000000000000000000000000000000000000000000000, 0x0EEC1487DD8C26D5));
expectEqual(@as(u64, 0x0000000000000000), tdesDecryptTest(0x200000000000000000000000000000000000000000000000, 0x7AD16FFB79C45926));
expectEqual(@as(u64, 0x0000000000000000), tdesDecryptTest(0x100000000000000000000000000000000000000000000000, 0xD3746294CA6A6CF3));
expectEqual(@as(u64, 0x0000000000000000), tdesDecryptTest(0x080000000000000000000000000000000000000000000000, 0x809F5F873C1FD761));
expectEqual(@as(u64, 0x0000000000000000), tdesDecryptTest(0x040000000000000000000000000000000000000000000000, 0xC02FAFFEC989D1FC));
expectEqual(@as(u64, 0x0000000000000000), tdesDecryptTest(0x020000000000000000000000000000000000000000000000, 0x4615AA1D33E72F10));
expectEqual(@as(u64, 0x0000000000000000), tdesDecryptTest(0x010000000000000000000000000000000000000000000000, 0x8CA64DE9C1B123A7));
expectEqual(@as(u64, 0x0000000000000000), tdesDecryptTest(0x008000000000000000000000000000000000000000000000, 0x2055123350C00858));
expectEqual(@as(u64, 0x0000000000000000), tdesDecryptTest(0x004000000000000000000000000000000000000000000000, 0xDF3B99D6577397C8));
expectEqual(@as(u64, 0x0000000000000000), tdesDecryptTest(0x002000000000000000000000000000000000000000000000, 0x31FE17369B5288C9));
expectEqual(@as(u64, 0x0000000000000000), tdesDecryptTest(0x001000000000000000000000000000000000000000000000, 0xDFDD3CC64DAE1642));
expectEqual(@as(u64, 0x0000000000000000), tdesDecryptTest(0x000800000000000000000000000000000000000000000000, 0x178C83CE2B399D94));
expectEqual(@as(u64, 0x0000000000000000), tdesDecryptTest(0x000400000000000000000000000000000000000000000000, 0x50F636324A9B7F80));
expectEqual(@as(u64, 0x0000000000000000), tdesDecryptTest(0x000200000000000000000000000000000000000000000000, 0xA8468EE3BC18F06D));
expectEqual(@as(u64, 0x0000000000000000), tdesDecryptTest(0x000100000000000000000000000000000000000000000000, 0x8CA64DE9C1B123A7));
}
// Copied from std/crypto/test.zig cause I couldn't figure out how to import it
pub fn assertEqual(comptime expected: []const u8, input: []const u8) void {
var expected_bytes: [expected.len / 2]u8 = undefined;
for (expected_bytes) |*r, i| {
r.* = fmt.parseInt(u8, expected[2 * i .. 2 * i + 2], 16) catch unreachable;
}
testing.expectEqualSlices(u8, &expected_bytes, input);
}
test "encrypt random data with ECB" {
var keyLong: u64 = <KEY>;
var keyBytes = mem.asBytes(&keyLong);
mem.reverse(u8, keyBytes);
const cipher = DES.init(keyBytes.*);
var allocator = std.heap.page_allocator;
const contents = try std.fs.cwd().readFileAlloc(allocator, "test/random_test_data_small.bin", 1000 * 1000 * 1000);
defer allocator.free(contents);
var encryptedData = try allocator.alloc(u8, contents.len);
defer allocator.free(encryptedData);
{
var i: usize = 0;
while (i < contents.len) : (i += des.block_size) {
cipher.crypt(
.Encrypt,
encryptedData[i..(i + des.block_size)],
contents[i..(i + des.block_size)]
);
}
}
var digest = Sha1.init(.{});
digest.update(encryptedData);
var out: [Sha1.digest_length]u8 = undefined;
digest.final(&out);
assertEqual("9e250e46b4c79d5d09afb5a54635b7d43740dce5", &out);
}
test "decrypt random data with ECB" {
var keyLong: u64 = <KEY>;
var keyBytes = mem.asBytes(&keyLong);
mem.reverse(u8, keyBytes);
const cipher = DES.init(keyBytes.*);
var allocator = std.heap.page_allocator;
const contents = try std.fs.cwd().readFileAlloc(allocator, "test/random_test_data_small.bin", 1000 * 1000 * 1000);
defer allocator.free(contents);
var encryptedData = try allocator.alloc(u8, contents.len);
{
var i: usize = 0;
while (i < contents.len) : (i += des.block_size) {
cipher.crypt(
.Encrypt,
encryptedData[i..(i + des.block_size)],
contents[i..(i + des.block_size)]
);
}
}
defer allocator.free(encryptedData);
var decryptedData = try allocator.alloc(u8, contents.len);
{
var i: usize = 0;
while (i < contents.len) : (i += des.block_size) {
cipher.crypt(
.Decrypt,
decryptedData[i..(i + des.block_size)],
encryptedData[i..(i + des.block_size)]
);
}
}
defer allocator.free(decryptedData);
testing.expectEqualSlices(u8, contents, decryptedData);
}
test "3DES ECB crypt" {
var allocator = std.heap.page_allocator;
var inData = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0 };
var encryptedData = try allocator.alloc(u8, inData.len);
var decryptedData = try allocator.alloc(u8, inData.len);
defer allocator.free(encryptedData);
defer allocator.free(decryptedData);
var key = [_]u8{0} ** 24;
var cipher = TDES.init(key);
var out = [_]u8{ 0x8C, 0xA6, 0x4D, 0xE9, 0xC1, 0xB1, 0x23, 0xA7 };
cipher.crypt(.Encrypt, encryptedData, &inData);
cipher.crypt(.Decrypt, decryptedData, encryptedData);
testing.expectEqualSlices(u8, encryptedData, &out);
testing.expectEqualSlices(u8, decryptedData, &inData);
key = [_]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };
cipher = TDES.init(key);
out = [_]u8{ 0x89, 0x4B, 0xC3, 0x08, 0x54, 0x26, 0xA4, 0x41 };
cipher.crypt(.Encrypt, encryptedData, &inData);
cipher.crypt(.Decrypt, decryptedData, encryptedData);
testing.expectEqualSlices(u8, encryptedData, &out);
testing.expectEqualSlices(u8, decryptedData, &inData);
key = [_]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };
cipher = TDES.init(key);
inData = [_]u8{ 0, 1, 2, 3, 4, 5, 6, 7 };
out = [_]u8{ 0x58, 0xED, 0x24, 0x8F, 0x77, 0xF6, 0xB1, 0x9E };
cipher.crypt(.Encrypt, encryptedData, &inData);
cipher.crypt(.Decrypt, decryptedData, encryptedData);
testing.expectEqualSlices(u8, encryptedData, &out);
testing.expectEqualSlices(u8, decryptedData, &inData);
} | test/des_test.zig |
const std = @import("std");
const Target = std.Target;
const CrossTarget = std.zig.CrossTarget;
fn setFeature(cpu: *Target.Cpu, feature: Target.x86.Feature, enabled: bool) void {
const idx = @as(Target.Cpu.Feature.Set.Index, @enumToInt(feature));
if (enabled) cpu.features.addFeature(idx) else cpu.features.removeFeature(idx);
}
inline fn bit(input: u32, offset: u5) bool {
return (input >> offset) & 1 != 0;
}
pub fn detectNativeCpuAndFeatures(arch: Target.Cpu.Arch, os: Target.Os, cross_target: CrossTarget) Target.Cpu {
var cpu = Target.Cpu{
.arch = arch,
.model = Target.Cpu.Model.generic(arch),
.features = Target.Cpu.Feature.Set.empty,
};
// First we detect features, to use as hints when detecting CPU Model.
detectNativeFeatures(&cpu, os.tag);
var leaf = cpuid(0, 0);
const max_leaf = leaf.eax;
const vendor = leaf.ebx;
if (max_leaf > 0) {
leaf = cpuid(0x1, 0);
const brand_id = leaf.ebx & 0xff;
// Detect model and family
var family = (leaf.eax >> 8) & 0xf;
var model = (leaf.eax >> 4) & 0xf;
if (family == 6 or family == 0xf) {
if (family == 0xf) {
family += (leaf.eax >> 20) & 0xff;
}
model += ((leaf.eax >> 16) & 0xf) << 4;
}
// Now we detect the model.
switch (vendor) {
0x756e6547 => {
detectIntelProcessor(&cpu, family, model, brand_id);
},
0x68747541 => {
detectAMDProcessor(&cpu, family, model);
},
else => {},
}
}
// Add the CPU model's feature set into the working set, but then
// override with actual detected features again.
cpu.features.addFeatureSet(cpu.model.features);
detectNativeFeatures(&cpu, os.tag);
cpu.features.populateDependencies(cpu.arch.allFeaturesList());
return cpu;
}
fn detectIntelProcessor(cpu: *Target.Cpu, family: u32, model: u32, brand_id: u32) void {
if (brand_id != 0) {
return;
}
switch (family) {
3 => {
cpu.model = &Target.x86.cpu._i386;
return;
},
4 => {
cpu.model = &Target.x86.cpu._i486;
return;
},
5 => {
if (Target.x86.featureSetHas(cpu.features, .mmx)) {
cpu.model = &Target.x86.cpu.pentium_mmx;
return;
}
cpu.model = &Target.x86.cpu.pentium;
return;
},
6 => {
switch (model) {
0x01 => {
cpu.model = &Target.x86.cpu.pentiumpro;
return;
},
0x03, 0x05, 0x06 => {
cpu.model = &Target.x86.cpu.pentium2;
return;
},
0x07, 0x08, 0x0a, 0x0b => {
cpu.model = &Target.x86.cpu.pentium3;
return;
},
0x09, 0x0d, 0x15 => {
cpu.model = &Target.x86.cpu.pentium_m;
return;
},
0x0e => {
cpu.model = &Target.x86.cpu.yonah;
return;
},
0x0f, 0x16 => {
cpu.model = &Target.x86.cpu.core2;
return;
},
0x17, 0x1d => {
cpu.model = &Target.x86.cpu.penryn;
return;
},
0x1a, 0x1e, 0x1f, 0x2e => {
cpu.model = &Target.x86.cpu.nehalem;
return;
},
0x25, 0x2c, 0x2f => {
cpu.model = &Target.x86.cpu.westmere;
return;
},
0x2a, 0x2d => {
cpu.model = &Target.x86.cpu.sandybridge;
return;
},
0x3a, 0x3e => {
cpu.model = &Target.x86.cpu.ivybridge;
return;
},
0x3c, 0x3f, 0x45, 0x46 => {
cpu.model = &Target.x86.cpu.haswell;
return;
},
0x3d, 0x47, 0x4f, 0x56 => {
cpu.model = &Target.x86.cpu.broadwell;
return;
},
0x4e, 0x5e, 0x8e, 0x9e => {
cpu.model = &Target.x86.cpu.skylake;
return;
},
0x55 => {
if (Target.x86.featureSetHas(cpu.features, .avx512bf16)) {
cpu.model = &Target.x86.cpu.cooperlake;
return;
} else if (Target.x86.featureSetHas(cpu.features, .avx512vnni)) {
cpu.model = &Target.x86.cpu.cascadelake;
return;
} else {
cpu.model = &Target.x86.cpu.skylake_avx512;
return;
}
},
0x66 => {
cpu.model = &Target.x86.cpu.cannonlake;
return;
},
0x7d, 0x7e => {
cpu.model = &Target.x86.cpu.icelake_client;
return;
},
0x6a, 0x6c => {
cpu.model = &Target.x86.cpu.icelake_server;
return;
},
0x1c, 0x26, 0x27, 0x35, 0x36 => {
cpu.model = &Target.x86.cpu.bonnell;
return;
},
0x37, 0x4a, 0x4d, 0x5a, 0x5d, 0x4c => {
cpu.model = &Target.x86.cpu.silvermont;
return;
},
0x5c, 0x5f => {
cpu.model = &Target.x86.cpu.goldmont;
return;
},
0x7a => {
cpu.model = &Target.x86.cpu.goldmont_plus;
return;
},
0x86 => {
cpu.model = &Target.x86.cpu.tremont;
return;
},
0x57 => {
cpu.model = &Target.x86.cpu.knl;
return;
},
0x85 => {
cpu.model = &Target.x86.cpu.knm;
return;
},
else => return, // Unknown CPU Model
}
},
15 => {
if (Target.x86.featureSetHas(cpu.features, .@"64bit")) {
cpu.model = &Target.x86.cpu.nocona;
return;
}
if (Target.x86.featureSetHas(cpu.features, .sse3)) {
cpu.model = &Target.x86.cpu.prescott;
return;
}
cpu.model = &Target.x86.cpu.pentium4;
return;
},
else => return, // Unknown CPU Model
}
}
fn detectAMDProcessor(cpu: *Target.Cpu, family: u32, model: u32) void {
// AMD's cpuid information is less than optimal for determining a CPU model.
// This is very unscientific, and not necessarily correct.
switch (family) {
4 => {
cpu.model = &Target.x86.cpu._i486;
return;
},
5 => {
cpu.model = &Target.x86.cpu.pentium;
switch (model) {
6, 7 => {
cpu.model = &Target.x86.cpu.k6;
return;
},
8 => {
cpu.model = &Target.x86.cpu.k6_2;
return;
},
9, 13 => {
cpu.model = &Target.x86.cpu.k6_3;
return;
},
10 => {
cpu.model = &Target.x86.cpu.geode;
return;
},
else => {},
}
return;
},
6 => {
if (Target.x86.featureSetHas(cpu.features, .sse)) {
cpu.model = &Target.x86.cpu.athlon_xp;
return;
}
cpu.model = &Target.x86.cpu.athlon;
return;
},
15 => {
if (Target.x86.featureSetHas(cpu.features, .sse3)) {
cpu.model = &Target.x86.cpu.k8_sse3;
return;
}
cpu.model = &Target.x86.cpu.k8;
return;
},
16 => {
cpu.model = &Target.x86.cpu.amdfam10;
return;
},
20 => {
cpu.model = &Target.x86.cpu.btver1;
return;
},
21 => {
cpu.model = &Target.x86.cpu.bdver1;
if (model >= 0x60 and model <= 0x7f) {
cpu.model = &Target.x86.cpu.bdver4;
return;
}
if (model >= 0x30 and model <= 0x3f) {
cpu.model = &Target.x86.cpu.bdver3;
return;
}
if ((model >= 0x10 and model <= 0x1f) or model == 0x02) {
cpu.model = &Target.x86.cpu.bdver2;
return;
}
return;
},
22 => {
cpu.model = &Target.x86.cpu.btver2;
return;
},
23 => {
cpu.model = &Target.x86.cpu.znver1;
if ((model >= 0x30 and model <= 0x3f) or model == 0x71) {
cpu.model = &Target.x86.cpu.znver2;
return;
}
return;
},
else => {
return;
},
}
}
fn detectNativeFeatures(cpu: *Target.Cpu, os_tag: Target.Os.Tag) void {
var leaf = cpuid(0, 0);
const max_level = leaf.eax;
leaf = cpuid(1, 0);
setFeature(cpu, .cx8, bit(leaf.edx, 8));
setFeature(cpu, .cx8, bit(leaf.edx, 8));
setFeature(cpu, .cmov, bit(leaf.edx, 15));
setFeature(cpu, .mmx, bit(leaf.edx, 23));
setFeature(cpu, .fxsr, bit(leaf.edx, 24));
setFeature(cpu, .sse, bit(leaf.edx, 25));
setFeature(cpu, .sse2, bit(leaf.edx, 26));
setFeature(cpu, .sse3, bit(leaf.ecx, 0));
setFeature(cpu, .pclmul, bit(leaf.ecx, 1));
setFeature(cpu, .ssse3, bit(leaf.ecx, 9));
setFeature(cpu, .cx16, bit(leaf.ecx, 13));
setFeature(cpu, .sse4_1, bit(leaf.ecx, 19));
setFeature(cpu, .sse4_2, bit(leaf.ecx, 20));
setFeature(cpu, .movbe, bit(leaf.ecx, 22));
setFeature(cpu, .popcnt, bit(leaf.ecx, 23));
setFeature(cpu, .aes, bit(leaf.ecx, 25));
setFeature(cpu, .rdrnd, bit(leaf.ecx, 30));
// If the CPU supports XSAVE/XRESTORE (bit 27) and AVX (bit 28) also check
// if the AVX registers are saved & restored on context switch
const has_avx_save = bit(leaf.ecx, 27) and
bit(leaf.ecx, 28) and
((getXCR0() & 0x6) == 0x6);
// LLVM approaches avx512_save by hardcoding it to true on Darwin,
// because the kernel saves the context even if the bit is not set.
// https://github.com/llvm/llvm-project/blob/bca373f73fc82728a8335e7d6cd164e8747139ec/llvm/lib/Support/Host.cpp#L1378
//
// Google approaches this by using a different series of checks and flags,
// and this may report the feature more accurately on a technically correct
// but ultimately less useful level.
// https://github.com/google/cpu_features/blob/b5c271c53759b2b15ff91df19bd0b32f2966e275/src/cpuinfo_x86.c#L113
// (called from https://github.com/google/cpu_features/blob/b5c271c53759b2b15ff91df19bd0b32f2966e275/src/cpuinfo_x86.c#L1052)
//
// Right now, we use LLVM's approach, because even if the target doesn't support
// the feature, the kernel should provide the same functionality transparently,
// so the implementation details don't make a difference.
// That said, this flag impacts other CPU features' availability,
// so until we can verify that this doesn't come with side affects,
// we'll say TODO verify this.
// Darwin lazily saves the AVX512 context on first use: trust that the OS will
// save the AVX512 context if we use AVX512 instructions, even if the bit is not
// set right now.
const has_avx512_save = switch (os_tag.isDarwin()) {
true => true,
false => has_avx_save and ((leaf.eax & 0xE0) == 0xE0),
};
setFeature(cpu, .avx, has_avx_save);
setFeature(cpu, .fma, has_avx_save and bit(leaf.ecx, 12));
// Only enable XSAVE if OS has enabled support for saving YMM state.
setFeature(cpu, .xsave, has_avx_save and bit(leaf.ecx, 26));
setFeature(cpu, .f16c, has_avx_save and bit(leaf.ecx, 29));
leaf = cpuid(0x80000000, 0);
const max_ext_level = leaf.eax;
if (max_ext_level >= 0x80000001) {
leaf = cpuid(0x80000001, 0);
setFeature(cpu, .sahf, bit(leaf.ecx, 0));
setFeature(cpu, .lzcnt, bit(leaf.ecx, 5));
setFeature(cpu, .sse4a, bit(leaf.ecx, 6));
setFeature(cpu, .prfchw, bit(leaf.ecx, 8));
setFeature(cpu, .xop, bit(leaf.ecx, 11) and has_avx_save);
setFeature(cpu, .lwp, bit(leaf.ecx, 15));
setFeature(cpu, .fma4, bit(leaf.ecx, 16) and has_avx_save);
setFeature(cpu, .tbm, bit(leaf.ecx, 21));
setFeature(cpu, .mwaitx, bit(leaf.ecx, 29));
setFeature(cpu, .@"64bit", bit(leaf.edx, 29));
} else {
for ([_]Target.x86.Feature{
.sahf, .lzcnt, .sse4a, .prfchw, .xop,
.lwp, .fma4, .tbm, .mwaitx, .@"64bit",
}) |feat| {
setFeature(cpu, feat, false);
}
}
// Misc. memory-related features.
if (max_ext_level >= 0x80000008) {
leaf = cpuid(0x80000008, 0);
setFeature(cpu, .clzero, bit(leaf.ebx, 0));
setFeature(cpu, .wbnoinvd, bit(leaf.ebx, 9));
} else {
for ([_]Target.x86.Feature{ .clzero, .wbnoinvd }) |feat| {
setFeature(cpu, feat, false);
}
}
if (max_level >= 0x7) {
leaf = cpuid(0x7, 0);
setFeature(cpu, .fsgsbase, bit(leaf.ebx, 0));
setFeature(cpu, .sgx, bit(leaf.ebx, 2));
setFeature(cpu, .bmi, bit(leaf.ebx, 3));
// AVX2 is only supported if we have the OS save support from AVX.
setFeature(cpu, .avx2, bit(leaf.ebx, 5) and has_avx_save);
setFeature(cpu, .bmi2, bit(leaf.ebx, 8));
setFeature(cpu, .invpcid, bit(leaf.ebx, 10));
setFeature(cpu, .rtm, bit(leaf.ebx, 11));
// AVX512 is only supported if the OS supports the context save for it.
setFeature(cpu, .avx512f, bit(leaf.ebx, 16) and has_avx512_save);
setFeature(cpu, .avx512dq, bit(leaf.ebx, 17) and has_avx512_save);
setFeature(cpu, .rdseed, bit(leaf.ebx, 18));
setFeature(cpu, .adx, bit(leaf.ebx, 19));
setFeature(cpu, .avx512ifma, bit(leaf.ebx, 21) and has_avx512_save);
setFeature(cpu, .clflushopt, bit(leaf.ebx, 23));
setFeature(cpu, .clwb, bit(leaf.ebx, 24));
setFeature(cpu, .avx512pf, bit(leaf.ebx, 26) and has_avx512_save);
setFeature(cpu, .avx512er, bit(leaf.ebx, 27) and has_avx512_save);
setFeature(cpu, .avx512cd, bit(leaf.ebx, 28) and has_avx512_save);
setFeature(cpu, .sha, bit(leaf.ebx, 29));
setFeature(cpu, .avx512bw, bit(leaf.ebx, 30) and has_avx512_save);
setFeature(cpu, .avx512vl, bit(leaf.ebx, 31) and has_avx512_save);
setFeature(cpu, .prefetchwt1, bit(leaf.ecx, 0));
setFeature(cpu, .avx512vbmi, bit(leaf.ecx, 1) and has_avx512_save);
setFeature(cpu, .pku, bit(leaf.ecx, 4));
setFeature(cpu, .waitpkg, bit(leaf.ecx, 5));
setFeature(cpu, .avx512vbmi2, bit(leaf.ecx, 6) and has_avx512_save);
setFeature(cpu, .shstk, bit(leaf.ecx, 7));
setFeature(cpu, .gfni, bit(leaf.ecx, 8));
setFeature(cpu, .vaes, bit(leaf.ecx, 9) and has_avx_save);
setFeature(cpu, .vpclmulqdq, bit(leaf.ecx, 10) and has_avx_save);
setFeature(cpu, .avx512vnni, bit(leaf.ecx, 11) and has_avx512_save);
setFeature(cpu, .avx512bitalg, bit(leaf.ecx, 12) and has_avx512_save);
setFeature(cpu, .avx512vpopcntdq, bit(leaf.ecx, 14) and has_avx512_save);
setFeature(cpu, .avx512vp2intersect, bit(leaf.edx, 8) and has_avx512_save);
setFeature(cpu, .rdpid, bit(leaf.ecx, 22));
setFeature(cpu, .cldemote, bit(leaf.ecx, 25));
setFeature(cpu, .movdiri, bit(leaf.ecx, 27));
setFeature(cpu, .movdir64b, bit(leaf.ecx, 28));
setFeature(cpu, .enqcmd, bit(leaf.ecx, 29));
// There are two CPUID leafs which information associated with the pconfig
// instruction:
// EAX=0x7, ECX=0x0 indicates the availability of the instruction (via the 18th
// bit of EDX), while the EAX=0x1b leaf returns information on the
// availability of specific pconfig leafs.
// The target feature here only refers to the the first of these two.
// Users might need to check for the availability of specific pconfig
// leaves using cpuid, since that information is ignored while
// detecting features using the "-march=native" flag.
// For more info, see X86 ISA docs.
setFeature(cpu, .pconfig, bit(leaf.edx, 18));
// TODO I feel unsure about this check.
// It doesn't really seem to check for 7.1, just for 7.
// Is this a sound assumption to make?
// Note that this is what other implementations do, so I kind of trust it.
const has_leaf_7_1 = max_level >= 7;
if (has_leaf_7_1) {
leaf = cpuid(0x7, 0x1);
setFeature(cpu, .avx512bf16, bit(leaf.eax, 5) and has_avx512_save);
} else {
setFeature(cpu, .avx512bf16, false);
}
} else {
for ([_]Target.x86.Feature{
.fsgsbase, .sgx, .bmi, .avx2,
.bmi2, .invpcid, .rtm, .avx512f,
.avx512dq, .rdseed, .adx, .avx512ifma,
.clflushopt, .clwb, .avx512pf, .avx512er,
.avx512cd, .sha, .avx512bw, .avx512vl,
.prefetchwt1, .avx512vbmi, .pku, .waitpkg,
.avx512vbmi2, .shstk, .gfni, .vaes,
.vpclmulqdq, .avx512vnni, .avx512bitalg, .avx512vpopcntdq,
.avx512vp2intersect, .rdpid, .cldemote, .movdiri,
.movdir64b, .enqcmd, .pconfig, .avx512bf16,
}) |feat| {
setFeature(cpu, feat, false);
}
}
if (max_level >= 0xD and has_avx_save) {
leaf = cpuid(0xD, 0x1);
// Only enable XSAVE if OS has enabled support for saving YMM state.
setFeature(cpu, .xsaveopt, bit(leaf.eax, 0));
setFeature(cpu, .xsavec, bit(leaf.eax, 1));
setFeature(cpu, .xsaves, bit(leaf.eax, 3));
} else {
for ([_]Target.x86.Feature{ .xsaveopt, .xsavec, .xsaves }) |feat| {
setFeature(cpu, feat, false);
}
}
if (max_level >= 0x14) {
leaf = cpuid(0x14, 0);
setFeature(cpu, .ptwrite, bit(leaf.ebx, 4));
} else {
setFeature(cpu, .ptwrite, false);
}
}
const CpuidLeaf = packed struct {
eax: u32,
ebx: u32,
ecx: u32,
edx: u32,
};
fn cpuid(leaf_id: u32, subid: u32) CpuidLeaf {
// Workaround for https://github.com/ziglang/zig/issues/215
// Inline assembly in zig only supports one output,
// so we pass a pointer to the struct.
var cpuid_leaf: CpuidLeaf = undefined;
// valid for both x86 and x86_64
asm volatile (
\\ cpuid
\\ movl %%eax, 0(%[leaf_ptr])
\\ movl %%ebx, 4(%[leaf_ptr])
\\ movl %%ecx, 8(%[leaf_ptr])
\\ movl %%edx, 12(%[leaf_ptr])
:
: [leaf_id] "{eax}" (leaf_id),
[subid] "{ecx}" (subid),
[leaf_ptr] "r" (&cpuid_leaf)
: "eax", "ebx", "ecx", "edx"
);
return cpuid_leaf;
}
// Read control register 0 (XCR0). Used to detect features such as AVX.
fn getXCR0() u32 {
return asm volatile (
\\ xor %%ecx, %%ecx
\\ xgetbv
: [ret] "={eax}" (-> u32)
:
: "eax", "edx", "ecx"
);
} | lib/std/zig/system/x86.zig |
const std = @import("std");
const assert = std.debug.assert;
pub const math = std.math;
pub const Scalar = f32;
pub const Vec3 = [3]Scalar;
pub const Mat4 = [4][4]Scalar;
pub const scalar = struct {
pub fn modAngle(in_angle: Scalar) Scalar {
const angle = in_angle + math.pi;
var temp: Scalar = math.fabs(angle);
temp = temp - (2.0 * math.pi * @intToFloat(Scalar, @floatToInt(i32, temp / math.pi)));
temp = temp - math.pi;
if (angle < 0.0) {
temp = -temp;
}
return temp;
}
};
pub const vec3 = struct {
pub fn dot(a: Vec3, b: Vec3) Scalar {
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
}
pub fn cross(a: Vec3, b: Vec3) Vec3 {
return .{
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
};
}
pub fn add(a: Vec3, b: Vec3) Vec3 {
return .{ a[0] + b[0], a[1] + b[1], a[2] + b[2] };
}
pub fn sub(a: Vec3, b: Vec3) Vec3 {
return .{ a[0] - b[0], a[1] - b[1], a[2] - b[2] };
}
pub fn scale(a: Vec3, b: Scalar) Vec3 {
return .{ a[0] * b, a[1] * b, a[2] * b };
}
pub fn init(x: Scalar, y: Scalar, z: Scalar) Vec3 {
return .{ x, y, z };
}
pub fn length(a: Vec3) Scalar {
return math.sqrt(dot(a, a));
}
pub fn normalize(a: Vec3) Vec3 {
const len = length(a);
assert(!math.approxEq(Scalar, len, 0.0, 0.0001));
const rcplen = 1.0 / len;
return .{ rcplen * a[0], rcplen * a[1], rcplen * a[2] };
}
pub fn transform(a: Vec3, b: Mat4) Vec3 {
return .{
a[0] * b[0][0] + a[1] * b[1][0] + a[2] * b[2][0] + b[3][0],
a[0] * b[0][1] + a[1] * b[1][1] + a[2] * b[2][1] + b[3][1],
a[0] * b[0][2] + a[1] * b[1][2] + a[2] * b[2][2] + b[3][2],
};
}
pub fn transformNormal(a: Vec3, b: Mat4) Vec3 {
return .{
a[0] * b[0][0] + a[1] * b[1][0] + a[2] * b[2][0],
a[0] * b[0][1] + a[1] * b[1][1] + a[2] * b[2][1],
a[0] * b[0][2] + a[1] * b[1][2] + a[2] * b[2][2],
};
}
};
pub const mat4 = struct {
pub fn transpose(a: Mat4) Mat4 {
return .{
[_]Scalar{ a[0][0], a[1][0], a[2][0], a[3][0] },
[_]Scalar{ a[0][1], a[1][1], a[2][1], a[3][1] },
[_]Scalar{ a[0][2], a[1][2], a[2][2], a[3][2] },
[_]Scalar{ a[0][3], a[1][3], a[2][3], a[3][3] },
};
}
pub fn mul(a: Mat4, b: Mat4) Mat4 {
return .{
[_]Scalar{
a[0][0] * b[0][0] + a[0][1] * b[1][0] + a[0][2] * b[2][0] + a[0][3] * b[3][0],
a[0][0] * b[0][1] + a[0][1] * b[1][1] + a[0][2] * b[2][1] + a[0][3] * b[3][1],
a[0][0] * b[0][2] + a[0][1] * b[1][2] + a[0][2] * b[2][2] + a[0][3] * b[3][2],
a[0][0] * b[0][3] + a[0][1] * b[1][3] + a[0][2] * b[2][3] + a[0][3] * b[3][3],
},
[_]Scalar{
a[1][0] * b[0][0] + a[1][1] * b[1][0] + a[1][2] * b[2][0] + a[1][3] * b[3][0],
a[1][0] * b[0][1] + a[1][1] * b[1][1] + a[1][2] * b[2][1] + a[1][3] * b[3][1],
a[1][0] * b[0][2] + a[1][1] * b[1][2] + a[1][2] * b[2][2] + a[1][3] * b[3][2],
a[1][0] * b[0][3] + a[1][1] * b[1][3] + a[1][2] * b[2][3] + a[1][3] * b[3][3],
},
[_]Scalar{
a[2][0] * b[0][0] + a[2][1] * b[1][0] + a[2][2] * b[2][0] + a[2][3] * b[3][0],
a[2][0] * b[0][1] + a[2][1] * b[1][1] + a[2][2] * b[2][1] + a[2][3] * b[3][1],
a[2][0] * b[0][2] + a[2][1] * b[1][2] + a[2][2] * b[2][2] + a[2][3] * b[3][2],
a[2][0] * b[0][3] + a[2][1] * b[1][3] + a[2][2] * b[2][3] + a[2][3] * b[3][3],
},
[_]Scalar{
a[3][0] * b[0][0] + a[3][1] * b[1][0] + a[3][2] * b[2][0] + a[3][3] * b[3][0],
a[3][0] * b[0][1] + a[3][1] * b[1][1] + a[3][2] * b[2][1] + a[3][3] * b[3][1],
a[3][0] * b[0][2] + a[3][1] * b[1][2] + a[3][2] * b[2][2] + a[3][3] * b[3][2],
a[3][0] * b[0][3] + a[3][1] * b[1][3] + a[3][2] * b[2][3] + a[3][3] * b[3][3],
},
};
}
pub fn initRotationX(angle: Scalar) Mat4 {
const sinv = math.sin(angle);
const cosv = math.cos(angle);
return .{
[_]Scalar{ 1.0, 0.0, 0.0, 0.0 },
[_]Scalar{ 0.0, cosv, sinv, 0.0 },
[_]Scalar{ 0.0, -sinv, cosv, 0.0 },
[_]Scalar{ 0.0, 0.0, 0.0, 1.0 },
};
}
pub fn initRotationY(angle: Scalar) Mat4 {
const sinv = math.sin(angle);
const cosv = math.cos(angle);
return .{
[_]Scalar{ cosv, 0.0, -sinv, 0.0 },
[_]Scalar{ 0.0, 1.0, 0.0, 0.0 },
[_]Scalar{ sinv, 0.0, cosv, 0.0 },
[_]Scalar{ 0.0, 0.0, 0.0, 1.0 },
};
}
pub fn initRotationZ(angle: Scalar) Mat4 {
const sinv = math.sin(angle);
const cosv = math.cos(angle);
return .{
[_]Scalar{ cosv, sinv, 0.0, 0.0 },
[_]Scalar{ -sinv, cosv, 0.0, 0.0 },
[_]Scalar{ 0.0, 0.0, 1.0, 0.0 },
[_]Scalar{ 0.0, 0.0, 0.0, 1.0 },
};
}
pub fn initPerspective(fovy: Scalar, aspect: Scalar, near: Scalar, far: Scalar) Mat4 {
const sinfov = math.sin(0.5 * fovy);
const cosfov = math.cos(0.5 * fovy);
assert(near > 0.0 and far > 0.0 and far > near);
assert(!math.approxEq(Scalar, sinfov, 0.0, 0.0001));
assert(!math.approxEq(Scalar, far, near, 0.001));
assert(!math.approxEq(Scalar, aspect, 0.0, 0.01));
const h = cosfov / sinfov;
const w = h / aspect;
const r = far / (far - near);
return .{
[_]Scalar{ w, 0.0, 0.0, 0.0 },
[_]Scalar{ 0.0, h, 0.0, 0.0 },
[_]Scalar{ 0.0, 0.0, r, 1.0 },
[_]Scalar{ 0.0, 0.0, -r * near, 0.0 },
};
}
pub fn initIdentity() Mat4 {
return .{
[_]Scalar{ 1.0, 0.0, 0.0, 0.0 },
[_]Scalar{ 0.0, 1.0, 0.0, 0.0 },
[_]Scalar{ 0.0, 0.0, 1.0, 0.0 },
[_]Scalar{ 0.0, 0.0, 0.0, 1.0 },
};
}
pub fn initTranslation(a: Vec3) Mat4 {
return .{
[_]Scalar{ 1.0, 0.0, 0.0, 0.0 },
[_]Scalar{ 0.0, 1.0, 0.0, 0.0 },
[_]Scalar{ 0.0, 0.0, 1.0, 0.0 },
[_]Scalar{ a[0], a[1], a[2], 1.0 },
};
}
pub fn initLookAt(eye: Vec3, at: Vec3, up: Vec3) Mat4 {
const az = vec3.normalize(vec3.sub(at, eye));
const ax = vec3.normalize(vec3.cross(up, az));
const ay = vec3.normalize(vec3.cross(az, ax));
return .{
[_]Scalar{ ax[0], ay[0], az[0], 0.0 },
[_]Scalar{ ax[1], ay[1], az[1], 0.0 },
[_]Scalar{ ax[2], ay[2], az[2], 0.0 },
[_]Scalar{ -vec3.dot(ax, eye), -vec3.dot(ay, eye), -vec3.dot(az, eye), 1.0 },
};
}
}; | src/math.zig |
const std = @import("std");
const Builder = std.build.Builder;
const sabaton = @import("extern/Sabaton/build.zig");
fn baremetal_target(exec: *std.build.LibExeObjStep, arch: std.Target.Cpu.Arch) void {
var disabled_features = std.Target.Cpu.Feature.Set.empty;
var enabled_feautres = std.Target.Cpu.Feature.Set.empty;
switch (arch) {
.x86_64 => {
const features = std.Target.x86.Feature;
disabled_features.addFeature(@enumToInt(features.mmx));
disabled_features.addFeature(@enumToInt(features.sse));
disabled_features.addFeature(@enumToInt(features.sse2));
disabled_features.addFeature(@enumToInt(features.avx));
disabled_features.addFeature(@enumToInt(features.avx2));
enabled_feautres.addFeature(@enumToInt(features.soft_float));
exec.code_model = .kernel;
},
.aarch64 => {
const features = std.Target.aarch64.Feature;
disabled_features.addFeature(@enumToInt(features.fp_armv8));
disabled_features.addFeature(@enumToInt(features.crypto));
disabled_features.addFeature(@enumToInt(features.neon));
exec.code_model = .small;
},
else => unreachable,
}
exec.disable_stack_probing = true;
exec.setTarget(.{
.cpu_arch = arch,
.os_tag = std.Target.Os.Tag.freestanding,
.abi = std.Target.Abi.none,
.cpu_features_sub = disabled_features,
.cpu_features_add = enabled_feautres,
});
}
fn stivale2_kernel(b: *Builder, arch: std.Target.Cpu.Arch) *std.build.LibExeObjStep {
const kernel_filename = b.fmt("kernel_{s}.elf", .{@tagName(arch)});
const kernel = b.addExecutable(kernel_filename, "kernel/stivale2.zig");
kernel.addIncludeDir("extern/stivale/");
kernel.setMainPkgPath(".");
kernel.setOutputDir(b.cache_root);
kernel.setBuildMode(.ReleaseSafe);
kernel.install();
baremetal_target(kernel, arch);
kernel.setLinkerScriptPath(.{ .path = "kernel/linker.ld" });
b.default_step.dependOn(&kernel.step);
return kernel;
}
fn run_qemu_with_x86_bios_image(b: *Builder, image_path: []const u8) *std.build.RunStep {
const cmd = &[_][]const u8{
// zig fmt: off
"qemu-system-x86_64",
"-cdrom", image_path,
"-debugcon", "stdio",
"-vga", "virtio",
"-m", "4G",
"-machine", "q35,accel=kvm:whpx:tcg",
// zig fmt: on
};
const run_step = b.addSystemCommand(cmd);
const run_command = b.step("run-x86_64-bios", "Run on x86_64 with Limine BIOS bootloader");
run_command.dependOn(&run_step.step);
return run_step;
}
fn get_ovmf(_: *Builder) ![]const u8 {
if (std.os.getenv("OVMF_PATH")) |p|
return p;
return "OVMF path not found - please set envvar OVMF_PATH";
}
fn run_qemu_with_x86_uefi_image(b: *Builder, image_path: []const u8) *std.build.RunStep {
const cmd = &[_][]const u8{
// zig fmt: off
"qemu-system-x86_64",
"-cdrom", image_path,
"-debugcon", "stdio",
"-vga", "virtio",
"-m", "4G",
"-machine", "q35,accel=kvm:whpx:tcg",
"-drive", b.fmt("if=pflash,format=raw,unit=0,file={s},readonly=on", .{get_ovmf(b)}),
// zig fmt: on
};
const run_step = b.addSystemCommand(cmd);
const run_command = b.step("run-x86_64-uefi", "Run on x86_64 with Limine UEFI bootloader");
run_command.dependOn(&run_step.step);
return run_step;
}
fn run_qemu_with_sabaton(b: *Builder, kernel: *std.build.LibExeObjStep) *std.build.RunStep {
const bootloader_blob = sabaton.aarch64VirtBlob(b);
const bootloader_path = b.getInstallPath(bootloader_blob.dest_dir, bootloader_blob.dest_filename);
const kernel_path = b.getInstallPath(kernel.install_step.?.dest_dir, kernel.out_filename);
const cmd = &[_][]const u8{
// zig fmt: off
"qemu-system-aarch64",
"-M", "virt,accel=kvm:whpx:tcg,gic-version=3",
"-cpu", "cortex-a57",
"-drive", b.fmt("if=pflash,format=raw,file={s},readonly=on", .{bootloader_path}),
"-fw_cfg", b.fmt("opt/Sabaton/kernel,file={s}", .{kernel_path}),
"-m", "4G",
"-serial", "stdio",
"-smp", "4",
"-device", "ramfb",
// zig fmt: on
};
const run_step = b.addSystemCommand(cmd);
run_step.step.dependOn(&kernel.install_step.?.step);
run_step.step.dependOn(&bootloader_blob.step);
const run_command = b.step("run-aarch64", "Run on aarch64 with Sabaton bootloader");
run_command.dependOn(&run_step.step);
return run_step;
}
fn build_limine_image(b: *Builder, kernel: *std.build.LibExeObjStep, image_path: []const u8) *std.build.RunStep {
const img_dir = b.fmt("{s}/img_dir", .{b.cache_root});
const kernel_path = b.getInstallPath(kernel.install_step.?.dest_dir, kernel.out_filename);
const cmd = &[_][]const u8{
"/bin/sh", "-c",
std.mem.concat(b.allocator, u8, &[_][]const u8{
// zig fmt: off
"rm ", image_path, " || true && ",
"mkdir -p ", img_dir, "/EFI/BOOT && ",
"make -C extern/limine-bin limine-install && ",
"cp ",
"extern/limine-bin/limine-eltorito-efi.bin ",
"extern/limine-bin/limine-cd.bin ",
"extern/limine-bin/limine.sys ",
"limine.cfg ",
img_dir, " && ",
"cp extern/limine-bin/BOOTX64.EFI ", img_dir, "/EFI/BOOT/ && ",
"cp ", kernel_path, " ", img_dir, " && ",
"xorriso -as mkisofs -quiet -b limine-cd.bin ",
"-no-emul-boot -boot-load-size 4 -boot-info-table ",
"--efi-boot limine-eltorito-efi.bin ",
"-efi-boot-part --efi-boot-image --protective-msdos-label ",
img_dir, " -o ", image_path, " && ",
"extern/limine-bin/limine-install ", image_path, " && ",
"true",
// zig fmt: on
}) catch unreachable,
};
const image_step = b.addSystemCommand(cmd);
image_step.step.dependOn(&kernel.install_step.?.step);
b.default_step.dependOn(&image_step.step);
const image_command = b.step("x86_64-universal-image", "Build the x86_64 universal (bios and uefi) image");
image_command.dependOn(&image_step.step);
return image_step;
}
fn build_x86(b: *Builder) void {
const kernel = stivale2_kernel(b, .x86_64);
const image_path = b.fmt("{s}/universal.iso", .{b.cache_root});
const image = build_limine_image(b, kernel, image_path);
const uefi_step = run_qemu_with_x86_uefi_image(b, image_path);
uefi_step.step.dependOn(&image.step);
const bios_step = run_qemu_with_x86_bios_image(b, image_path);
bios_step.step.dependOn(&image.step);
}
pub fn build(b: *Builder) void {
build_x86(b);
// Just boots your kernel using sabaton, without a filesystem.
_ = run_qemu_with_sabaton(b, stivale2_kernel(b, .aarch64));
} | build.zig |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.