text
stringlengths 32
314k
| url
stringlengths 93
243
|
---|---|
// MIT License
// Copyright (c) 2019 Vexu
// 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.
const std = @import("std");
const mem = std.mem;
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const parseUnsigned = std.fmt.parseUnsigned;
const net = std.net;
const testing = std.testing;
const expect = testing.expect;
const expectEqualStrings = testing.expectEqualStrings;
const ValueMap = std.StringHashMap([]const u8);
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,
/// possible uri host values
pub const Host = union(enum) {
ip: net.Address,
name: []const u8,
};
/// 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) Allocator.Error!ValueMap {
if (query.len == 0) {
return ValueMap.init(allocator);
}
var map = ValueMap.init(allocator);
errdefer map.deinit();
var start: usize = 0;
var mid: usize = 0;
for (query) |c, i| {
if (c == '&') {
if (mid != 0) {
_ = try map.put(query[start..mid], query[mid + 1 .. i]);
} else {
_ = try map.put(query[start..i], "");
}
start = i + 1;
mid = 0;
} else if (c == '=') {
mid = i;
}
}
if (mid != 0) {
_ = try map.put(query[start..mid], query[mid + 1 ..]);
} else {
_ = try map.put(query[start..], "");
}
return map;
}
/// possible errors for decode and encode
pub const EncodeError = error{
InvalidCharacter,
OutOfMemory,
};
/// decode path if it is percent encoded
pub fn decode(allocator: *Allocator, path: []const u8) EncodeError!?[]u8 {
var ret: ?[]u8 = null;
errdefer if (ret) |some| allocator.free(some);
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) |some| return allocator.shrink(some, ret_index);
return null;
}
/// 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) |some| return allocator.shrink(some, ret_index);
return null;
}
/// 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);
defer 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;
for (list.items) |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.shrink(buf, len);
}
pub const scheme_to_port = std.ComptimeStringMap(u16, .{
.{ "acap", 674 },
.{ "afp", 548 },
.{ "dict", 2628 },
.{ "dns", 53 },
.{ "ftp", 21 },
.{ "git", 9418 },
.{ "gopher", 70 },
.{ "http", 80 },
.{ "https", 443 },
.{ "imap", 143 },
.{ "ipp", 631 },
.{ "ipps", 631 },
.{ "irc", 194 },
.{ "ircs", 6697 },
.{ "ldap", 389 },
.{ "ldaps", 636 },
.{ "mms", 1755 },
.{ "msrp", 2855 },
.{ "mtqp", 1038 },
.{ "nfs", 111 },
.{ "nntp", 119 },
.{ "nntps", 563 },
.{ "pop", 110 },
.{ "prospero", 1525 },
.{ "redis", 6379 },
.{ "rsync", 873 },
.{ "rtsp", 554 },
.{ "rtsps", 322 },
.{ "rtspu", 5005 },
.{ "sftp", 22 },
.{ "smb", 445 },
.{ "snmp", 161 },
.{ "ssh", 22 },
.{ "svn", 3690 },
.{ "telnet", 23 },
.{ "ventrilo", 3784 },
.{ "vnc", 5900 },
.{ "wais", 210 },
.{ "ws", 80 },
.{ "wss", 443 },
});
/// 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,
};
/// 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.port = scheme_to_port.get(u.scheme);
u.len += u.scheme.len + 1; // +1 for the ':'
return;
},
else => {
// not a valid scheme
return;
},
}
}
}
fn parseAuth(u: *Uri, input: []const u8) Error!void {
var i: u32 = 0;
var at_index = i;
while (i < input.len) : (i += 1) {
switch (input[i]) {
'@' => at_index = i,
'[' => {
if (i != 0) return error.InvalidCharacter;
return u.parseIP6(input);
},
else => if (!isPchar(input[i..])) break,
}
}
if (at_index != 0) {
u.username = input[0..at_index];
if (mem.indexOfScalar(u8, u.username, ':')) |colon| {
u.password = u.username[colon + 1 ..];
u.username = u.username[0..colon];
}
at_index += 1;
}
u.host.name = input[at_index..i];
u.len += i;
if (mem.indexOfScalar(u8, u.host.name, ':')) |colon| {
u.port = parseUnsigned(u16, u.host.name[colon + 1 ..], 10) catch return error.InvalidCharacter;
u.host.name = u.host.name[0..colon];
}
}
fn parseIP6(u: *Uri, input: []const u8) Error!void {
const end = mem.indexOfScalar(u8, input, ']') orelse return error.InvalidCharacter;
const 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 {
var i: u32 = 0;
while (i < input.len) : (i += 1) {
switch (input[i]) {
'0'...'9' => {}, // digits
else => break,
}
}
if (i == 0) return error.InvalidCharacter;
u.port = parseUnsigned(u16, input[0..i], 10) catch return error.InvalidCharacter;
u.len += i;
}
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,
};
}
};
test "basic url" {
const uri = try Uri.parse("https://ziglang.org:80/documentation/master/?test#toc-Introduction", false);
try expectEqualStrings("https", uri.scheme);
try expectEqualStrings("", uri.username);
try expectEqualStrings("", uri.password);
try expectEqualStrings("ziglang.org", uri.host.name);
try expect(uri.port.? == 80);
try expectEqualStrings("/documentation/master/", uri.path);
try expectEqualStrings("test", uri.query);
try expectEqualStrings("toc-Introduction", uri.fragment);
try expect(uri.len == 66);
}
test "short" {
const uri = try Uri.parse("telnet://192.0.2.16:80/", false);
try expectEqualStrings("telnet", uri.scheme);
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("192.0.2.16:80", ip);
try expect(uri.port.? == 80);
try expectEqualStrings("/", uri.path);
try expectEqualStrings("", uri.query);
try expectEqualStrings("", uri.fragment);
try expect(uri.len == 23);
}
test "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("a", uri.path);
try expectEqualStrings("", uri.query);
try expectEqualStrings("", uri.fragment);
try expect(uri.len == 1);
}
test "ipv6" {
const uri = try Uri.parse("ldap://[2001:db8::7]/c=GB?objectClass?one", false);
try expectEqualStrings("ldap", uri.scheme);
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("[2001:db8::7]:389", ip);
try expect(uri.port.? == 389);
try expectEqualStrings("/c=GB", uri.path);
try expectEqualStrings("objectClass?one", uri.query);
try expectEqualStrings("", uri.fragment);
try expect(uri.len == 41);
}
test "mailto" {
const uri = try Uri.parse("mailto:[email protected]", false);
try expectEqualStrings("mailto", uri.scheme);
try expectEqualStrings("", uri.username);
try expectEqualStrings("", uri.password);
try expectEqualStrings("", uri.host.name);
try expect(uri.port == null);
try expectEqualStrings("[email protected]", uri.path);
try expectEqualStrings("", uri.query);
try expectEqualStrings("", uri.fragment);
try expect(uri.len == 27);
}
test "tel" {
const uri = try Uri.parse("tel:+1-816-555-1212", false);
try expectEqualStrings("tel", uri.scheme);
try expectEqualStrings("", uri.username);
try expectEqualStrings("", uri.password);
try expectEqualStrings("", uri.host.name);
try expect(uri.port == null);
try expectEqualStrings("+1-816-555-1212", uri.path);
try expectEqualStrings("", uri.query);
try expectEqualStrings("", uri.fragment);
try expect(uri.len == 19);
}
test "urn" {
const uri = try Uri.parse("urn:oasis:names:specification:docbook:dtd:xml:4.1.2", false);
try expectEqualStrings("urn", uri.scheme);
try expectEqualStrings("", uri.username);
try expectEqualStrings("", uri.password);
try expectEqualStrings("", uri.host.name);
try expect(uri.port == null);
try expectEqualStrings("oasis:names:specification:docbook:dtd:xml:4.1.2", uri.path);
try expectEqualStrings("", uri.query);
try expectEqualStrings("", uri.fragment);
try expect(uri.len == 51);
}
test "userinfo" {
const uri = try Uri.parse("ftp://username:[email protected]/", false);
try expectEqualStrings("ftp", uri.scheme);
try expectEqualStrings("username", uri.username);
try expectEqualStrings("password", uri.password);
try expectEqualStrings("host.com", uri.host.name);
try expect(uri.port.? == 21);
try expectEqualStrings("/", uri.path);
try expectEqualStrings("", uri.query);
try expectEqualStrings("", uri.fragment);
try expect(uri.len == 33);
}
test "map query" {
const uri = try Uri.parse("https://ziglang.org:80/documentation/master/?test;1=true&false#toc-Introduction", false);
try expectEqualStrings("https", uri.scheme);
try expectEqualStrings("", uri.username);
try expectEqualStrings("", uri.password);
try expectEqualStrings("ziglang.org", uri.host.name);
try expect(uri.port.? == 80);
try expectEqualStrings("/documentation/master/", uri.path);
try expectEqualStrings("test;1=true&false", uri.query);
try expectEqualStrings("toc-Introduction", uri.fragment);
var map = try Uri.mapQuery(std.testing.allocator, uri.query);
defer map.deinit();
try expectEqualStrings("true", map.get("test;1").?);
try expectEqualStrings("", map.get("false").?);
}
test "ends in space" {
const uri = try Uri.parse("https://ziglang.org/documentation/master/ something else", false);
try expectEqualStrings("https", uri.scheme);
try expectEqualStrings("", uri.username);
try expectEqualStrings("", uri.password);
try expectEqualStrings("ziglang.org", uri.host.name);
try expectEqualStrings("/documentation/master/", uri.path);
try expect(uri.len == 41);
}
test "assume auth" {
const uri = try Uri.parse("ziglang.org", true);
try expectEqualStrings("ziglang.org", uri.host.name);
try expect(uri.len == 11);
}
test "username contains @" {
const uri = try Uri.parse("https://1.1.1.1&@2.2.2.2%[email protected]", false);
try expectEqualStrings("https", uri.scheme);
try expectEqualStrings("1.1.1.1&@2.2.2.2%23", 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("3.3.3.3:443", ip);
try expect(uri.port.? == 443);
try expectEqualStrings("", uri.path);
try expect(uri.len == 35);
}
test "encode" {
const path = (try Uri.encode(testing.allocator, "/μλ
νμΈμ.html")).?;
defer testing.allocator.free(path);
try expectEqualStrings("/%EC%95%88%EB%85%95%ED%95%98%EC%84%B8%EC%9A%94.html", path);
}
test "decode" {
const path = (try Uri.decode(testing.allocator, "/%EC%95%88%EB%85%95%ED%95%98%EC%84%B8%EC%9A%94.html")).?;
defer testing.allocator.free(path);
try expectEqualStrings("/μλ
νμΈμ.html", path);
}
test "resolvePath" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
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/b/", a);
a = try Uri.resolvePath(alloc, "/a/b/c/../d/..");
try expectEqualStrings("/a/b", a);
a = try Uri.resolvePath(alloc, "/a/b/c/../d/.././");
try expectEqualStrings("/a/b/", a);
a = try Uri.resolvePath(alloc, "/a/b/c/../d/../.");
try expectEqualStrings("/a/b", a);
a = try Uri.resolvePath(alloc, "/a/../../");
try expectEqualStrings("/", a);
}
| https://raw.githubusercontent.com/lithdew/rheia/162293d0f0e8d6572a8954c0add83f13f76b3cc6/uri.zig |
//***************************************************************************
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership. The
// ASF licenses this file to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance with the
// License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
//
//***************************************************************************
//! PinePhone Allwinner A64 MIPI DPHY (Display Physical Layer) Driver for Apache NuttX RTOS
//! See https://lupyuen.github.io/articles/dsi#appendix-enable-mipi-display-physical-layer-dphy
//! "A64 Page ???" refers to Allwinner A64 User Manual: https://github.com/lupyuen/pinephone-nuttx/releases/download/doc/Allwinner_A64_User_Manual_V1.1.pdf
/// Import the Zig Standard Library
const std = @import("std");
/// Import NuttX Functions from C
const c = @cImport({
// NuttX Defines
@cDefine("__NuttX__", "");
@cDefine("NDEBUG", "");
@cDefine("FAR", "");
// NuttX Header Files
@cInclude("arch/types.h");
@cInclude("../../nuttx/include/limits.h");
@cInclude("nuttx/config.h");
@cInclude("inttypes.h");
@cInclude("unistd.h");
@cInclude("stdlib.h");
@cInclude("stdio.h");
});
/// Base Address of Allwinner A64 CCU Controller (A64 Page 82)
const CCU_BASE_ADDRESS = 0x01C2_0000;
/// Base Address of Allwinner A64 MIPI DPHY Controller (A64 Page 74)
const DPHY_BASE_ADDRESS = 0x01CA_1000;
/// Enable MIPI Display Physical Layer (DPHY).
/// Based on https://lupyuen.github.io/articles/dsi#appendix-enable-mipi-display-physical-layer-dphy
pub export fn dphy_enable() void {
debug("dphy_enable: start", .{});
defer { debug("dphy_enable: end", .{}); }
// Set DSI Clock to 150 MHz (600 MHz / 4)
// MIPI_DSI_CLK_REG: CCU Offset 0x168 (A64 Page 122)
// Set DSI_DPHY_GATING (Bit 15) to 1 (DSI DPHY Clock is On)
// Set DSI_DPHY_SRC_SEL (Bits 8 to 9) to 0b10 (DSI DPHY Clock Source is PLL_PERIPH0(1X))
// Set DPHY_CLK_DIV_M (Bits 0 to 3) to 3 (DSI DPHY Clock divide ratio - 1)
debug("Set DSI Clock to 150 MHz", .{});
const MIPI_DSI_CLK_REG = CCU_BASE_ADDRESS + 0x168;
comptime{ assert(MIPI_DSI_CLK_REG == 0x1c20168); }
const DSI_DPHY_GATING: u16 = 1 << 15;
const DSI_DPHY_SRC_SEL: u10 = 0b10 << 8;
const DPHY_CLK_DIV_M: u4 = 3 << 0;
const MIPI_DSI_CLK = DSI_DPHY_GATING
| DSI_DPHY_SRC_SEL
| DPHY_CLK_DIV_M;
comptime{ assert(MIPI_DSI_CLK == 0x8203); }
putreg32(MIPI_DSI_CLK, MIPI_DSI_CLK_REG); // TODO: DMB
// Power on DPHY Tx (Undocumented)
// DPHY_TX_CTL_REG: DPHY Offset 0x04
// Set to 0x1000 0000
debug("Power on DPHY Tx", .{});
const DPHY_TX_CTL_REG = DPHY_BASE_ADDRESS + 0x04;
comptime{ assert(DPHY_TX_CTL_REG == 0x1ca1004); }
putreg32(0x10000000, DPHY_TX_CTL_REG); // TODO: DMB
// DPHY_TX_TIME0_REG: DPHY Offset 0x10
// Set to 0xa06 000e
const DPHY_TX_TIME0_REG = DPHY_BASE_ADDRESS + 0x10;
comptime{ assert(DPHY_TX_TIME0_REG == 0x1ca1010); }
putreg32(0xa06000e, DPHY_TX_TIME0_REG); // TODO: DMB
// DPHY_TX_TIME1_REG: DPHY Offset 0x14
// Set to 0xa03 3207
const DPHY_TX_TIME1_REG = DPHY_BASE_ADDRESS + 0x14;
comptime{ assert(DPHY_TX_TIME1_REG == 0x1ca1014); }
putreg32(0xa033207, DPHY_TX_TIME1_REG); // TODO: DMB
// DPHY_TX_TIME2_REG: DPHY Offset 0x18
// Set to 0x1e
const DPHY_TX_TIME2_REG = DPHY_BASE_ADDRESS + 0x18;
comptime{ assert(DPHY_TX_TIME2_REG == 0x1ca1018); }
putreg32(0x1e, DPHY_TX_TIME2_REG); // TODO: DMB
// DPHY_TX_TIME3_REG: DPHY Offset 0x1c
// Set to 0x0
const DPHY_TX_TIME3_REG = DPHY_BASE_ADDRESS + 0x1c;
comptime{ assert(DPHY_TX_TIME3_REG == 0x1ca101c); }
putreg32(0x0, DPHY_TX_TIME3_REG); // TODO: DMB
// DPHY_TX_TIME4_REG: DPHY Offset 0x20
// Set to 0x303
const DPHY_TX_TIME4_REG = DPHY_BASE_ADDRESS + 0x20;
comptime{ assert(DPHY_TX_TIME4_REG == 0x1ca1020); }
putreg32(0x303, DPHY_TX_TIME4_REG); // TODO: DMB
// Enable DPHY (Undocumented)
// DPHY_GCTL_REG: DPHY Offset 0x00 (Enable DPHY)
// Set to 0x31
debug("Enable DPHY", .{});
const DPHY_GCTL_REG = DPHY_BASE_ADDRESS + 0x00;
comptime{ assert(DPHY_GCTL_REG == 0x1ca1000); }
putreg32(0x31, DPHY_GCTL_REG); // TODO: DMB
// DPHY_ANA0_REG: DPHY Offset 0x4c (PWS)
// Set to 0x9f00 7f00
const DPHY_ANA0_REG = DPHY_BASE_ADDRESS + 0x4c;
comptime{ assert(DPHY_ANA0_REG == 0x1ca104c); }
putreg32(0x9f007f00, DPHY_ANA0_REG); // TODO: DMB
// DPHY_ANA1_REG: DPHY Offset 0x50 (CSMPS)
// Set to 0x1700 0000
const DPHY_ANA1_REG = DPHY_BASE_ADDRESS + 0x50;
comptime{ assert(DPHY_ANA1_REG == 0x1ca1050); }
putreg32(0x17000000, DPHY_ANA1_REG); // TODO: DMB
// DPHY_ANA4_REG: DPHY Offset 0x5c (CKDV)
// Set to 0x1f0 1555
const DPHY_ANA4_REG = DPHY_BASE_ADDRESS + 0x5c;
comptime{ assert(DPHY_ANA4_REG == 0x1ca105c); }
putreg32(0x1f01555, DPHY_ANA4_REG); // TODO: DMB
// DPHY_ANA2_REG: DPHY Offset 0x54 (ENIB)
// Set to 0x2
const DPHY_ANA2_REG = DPHY_BASE_ADDRESS + 0x54;
comptime{ assert(DPHY_ANA2_REG == 0x1ca1054); }
putreg32(0x2, DPHY_ANA2_REG); // TODO: DMB
// Wait 5 microseconds
_ = c.usleep(5);
// Enable LDOR, LDOC, LDOD (Undocumented)
// DPHY_ANA3_REG: DPHY Offset 0x58 (Enable LDOR, LDOC, LDOD)
// Set to 0x304 0000
debug("Enable LDOR, LDOC, LDOD", .{});
const DPHY_ANA3_REG = DPHY_BASE_ADDRESS + 0x58;
comptime{ assert(DPHY_ANA3_REG == 0x1ca1058); }
putreg32(0x3040000, DPHY_ANA3_REG); // TODO: DMB
// Wait 1 microsecond
_ = c.usleep(1);
// DPHY_ANA3_REG: DPHY Offset 0x58 (Enable VTTC, VTTD)
// Set bits 0xf800 0000
comptime{ assert(DPHY_ANA3_REG == 0x1ca1058); }
const EnableVTTC = 0xf8000000;
modreg32(EnableVTTC, EnableVTTC, DPHY_ANA3_REG); // TODO: DMB
// Wait 1 microsecond
_ = c.usleep(1);
// DPHY_ANA3_REG: DPHY Offset 0x58 (Enable DIV)
// Set bits 0x400 0000
comptime{ assert(DPHY_ANA3_REG == 0x1ca1058); }
const EnableDIV = 0x4000000;
modreg32(EnableDIV, EnableDIV, DPHY_ANA3_REG); // TODO: DMB
// Wait 1 microsecond
_ = c.usleep(1);
// DPHY_ANA2_REG: DPHY Offset 0x54 (Enable CK_CPU)
comptime{ assert(DPHY_ANA2_REG == 0x1ca1054); }
const EnableCKCPU = 0x10;
modreg32(EnableCKCPU, EnableCKCPU, DPHY_ANA2_REG); // TODO: DMB
// Set bits 0x10
// Wait 1 microsecond
_ = c.usleep(1);
// DPHY_ANA1_REG: DPHY Offset 0x50 (VTT Mode)
// Set bits 0x8000 0000
comptime{ assert(DPHY_ANA1_REG == 0x1ca1050); }
const VTTMode = 0x80000000;
modreg32(VTTMode, VTTMode, DPHY_ANA1_REG); // TODO: DMB
// DPHY_ANA2_REG: DPHY Offset 0x54 (Enable P2S CPU)
// Set bits 0xf00 0000
comptime{ assert(DPHY_ANA2_REG == 0x1ca1054); }
const EnableP2SCPU = 0xf000000;
modreg32(EnableP2SCPU, EnableP2SCPU, DPHY_ANA2_REG); // TODO: DMB
}
/// Modify the specified bits in a memory mapped register.
/// Based on https://github.com/apache/nuttx/blob/master/arch/arm64/src/common/arm64_arch.h#L473
fn modreg32(
comptime val: u32, // Bits to set, like (1 << bit)
comptime mask: u32, // Bits to clear, like (1 << bit)
addr: u64 // Address to modify
) void {
comptime { assert(val & mask == val); }
debug(" *0x{x}: clear 0x{x}, set 0x{x}", .{ addr, mask, val & mask });
putreg32(
(getreg32(addr) & ~(mask))
| ((val) & (mask)),
(addr)
);
}
/// Get the 32-bit value at the address
fn getreg32(addr: u64) u32 {
const ptr = @intToPtr(*const volatile u32, addr);
return ptr.*;
}
/// Set the 32-bit value at the address
fn putreg32(val: u32, addr: u64) void {
if (enableLog) { debug(" *0x{x} = 0x{x}", .{ addr, val }); }
const ptr = @intToPtr(*volatile u32, addr);
ptr.* = val;
}
/// Set to False to disable log
var enableLog = true;
///////////////////////////////////////////////////////////////////////////////
// Panic Handler
/// Called by Zig when it hits a Panic. We print the Panic Message, Stack Trace and halt. See
/// https://andrewkelley.me/post/zig-stack-traces-kernel-panic-bare-bones-os.html
/// https://github.com/ziglang/zig/blob/master/lib/std/builtin.zig#L763-L847
pub fn panic(
message: []const u8,
_stack_trace: ?*std.builtin.StackTrace
) noreturn {
// Print the Panic Message
_ = _stack_trace;
_ = puts("\n!ZIG PANIC!");
_ = puts(@ptrCast([*c]const u8, message));
// Print the Stack Trace
_ = puts("Stack Trace:");
var it = std.debug.StackIterator.init(@returnAddress(), null);
while (it.next()) |return_address| {
_ = printf("%p\n", return_address);
}
// Halt
c.exit(1);
}
///////////////////////////////////////////////////////////////////////////////
// Logging
/// Called by Zig for `std.log.debug`, `std.log.info`, `std.log.err`, ...
/// https://gist.github.com/leecannon/d6f5d7e5af5881c466161270347ce84d
pub fn log(
comptime _message_level: std.log.Level,
comptime _scope: @Type(.EnumLiteral),
comptime format: []const u8,
args: anytype,
) void {
_ = _message_level;
_ = _scope;
// Format the message
var buf: [100]u8 = undefined; // Limit to 100 chars
var slice = std.fmt.bufPrint(&buf, format, args)
catch { _ = puts("*** log error: buf too small"); return; };
// Terminate the formatted message with a null
var buf2: [buf.len + 1 : 0]u8 = undefined;
std.mem.copy(
u8,
buf2[0..slice.len],
slice[0..slice.len]
);
buf2[slice.len] = 0;
// Print the formatted message
_ = puts(&buf2);
}
///////////////////////////////////////////////////////////////////////////////
// Imported Functions and Variables
/// For safety, we import these functions ourselves to enforce Null-Terminated Strings.
/// We changed `[*c]const u8` to `[*:0]const u8`
extern fn printf(format: [*:0]const u8, ...) c_int;
extern fn puts(str: [*:0]const u8) c_int;
/// Aliases for Zig Standard Library
const assert = std.debug.assert;
const debug = std.log.debug;
| https://raw.githubusercontent.com/lupyuen/pinephone-nuttx/700afea277d94090efa3926a96352b4a6319e99f/dphy.zig |
const root = @import("root");
pub const c = if (@hasDecl(root, "loadable_extension"))
@import("c/loadable_extension.zig")
else
@cImport({
@cInclude("sqlite3.h");
@cInclude("workaround.h");
});
// versionGreaterThanOrEqualTo returns true if the SQLite version is >= to the major.minor.patch provided.
pub fn versionGreaterThanOrEqualTo(major: u8, minor: u8, patch: u8) bool {
return c.SQLITE_VERSION_NUMBER >= @as(u32, major) * 1000000 + @as(u32, minor) * 1000 + @as(u32, patch);
}
comptime {
if (!versionGreaterThanOrEqualTo(3, 21, 0)) {
@compileError("must use SQLite >= 3.21.0");
}
}
| https://raw.githubusercontent.com/vrischmann/zig-sqlite/91e5fedd15c5ea3cb42ccceefb3d0f4bb9bad68f/c.zig |
pub fn main() !void {
try renderer.render(.{
.Shader = SimpleBlendShader,
//.Shader = CheckerShader,
//.Shader = BandingShader,
//.Shader = CliffordAttractorShader,
//.Shader = JuliaSetShader,
//.Shader = SimplexNoiseShader,
//.Shader = GeometryShader,
//.Shader = QuantizeShader,
//.Shader = IntNoiseShader,
//.Shader = SurfaceNormalShader,
.preview = true,
.memoryLimitMiB = 128,
.ssaa = 3,
.preview_ssaa = 1,
.preview_samples = 600000,
.frames = 1,
//.frames = 30 * 8, // ffmpeg -r 30 -f image2 -i 'frame-%06d.png' -vcodec libx264 -pix_fmt yuv420p -profile:v main -level 3.1 -preset medium -crf 23 -x264-params ref=4 -movflags +faststart out.mp4
.path = "out/out.png",
.frameTemplate = "out/frame-{d:0>6}.png",
.res = Resolutions.Instagram.square,
//.res = Resolutions.Instagram.portrait,
//.res = Resolutions.Instagram.landscape,
//.res = Resolutions.Prints._8x10,
//.res = comptime Resolutions.Prints._8x10.landscape(),
//.res = Resolutions.Screen._4k,
//.res = Resolutions.Screen._1080p,
//.res = Resolutions.Wallpapers.iosParallax,
//.res = comptime Resolutions.Prints._5x15.landscape(),
//.res = Resolutions.Prints._5x15,
//.res = @import("lib/resolutions.zig").Res{ .width = 256, .height = 256 },
});
}
const SimpleBlendShader = struct {
const Self = @This();
pub fn init(allocator: *Allocator, config: renderer.ShaderConfig) !Self {
return Self{};
}
pub fn deinit(self: *const Self, allocator: *Allocator) void {}
pub fn shade(self: *const Self, x: f64, y: f64) Jazbz {
return mix(
mix(colors.goldenYellow, colors.seaBlue, saturate(x)),
mix(colors.navyBlue, colors.bloodRed, saturate(x)),
saturate(y),
);
}
};
const CheckerShader = struct {
const Self = @This();
pub fn init(allocator: *Allocator, config: renderer.ShaderConfig) !Self {
return Self{};
}
pub fn deinit(self: *const Self, allocator: *Allocator) void {}
pub fn shade(self: *const Self, x: f64, y: f64) Jazbz {
return (comptime @import("lib/debug_shaders.zig").CheckedBackground(16)).content(colors.neonGreen, x, y);
}
};
const BandingShader = struct {
const Self = @This();
pub fn init(allocator: *Allocator, config: renderer.ShaderConfig) !Self {
return Self{};
}
pub fn deinit(self: *const Self, allocator: *Allocator) void {}
pub fn shade(self: *const Self, x: f64, y: f64) Jazbz {
if (x >= 0 and x <= 1 and y >= 0 and y <= 1) {
const banding = @import("lib/banding.zig").Banding(pattern, (1 << 6) * phi, 640).sample(x, y);
return mix(colors.goldenYellow, colors.bloodRed, banding);
} else {
return colors.navyBlue;
}
}
fn pattern(x: f64, y: f64) [2]f64 {
return [_]f64{
x * y,
y + x * x,
};
}
};
const CliffordAttractorShader = struct {
const Self = @This();
const Pixel = struct {
count: usize = 0,
};
const Screen = @import("lib/screen.zig").Screen;
const PixelScreen = Screen(Pixel);
screen: PixelScreen,
countCorrection: f64 = 1,
pub fn init(allocator: *Allocator, config: renderer.ShaderConfig) !Self {
var self = Self{
.screen = try PixelScreen.init(allocator, config.res.width, config.res.height, .{ .count = 0 }),
};
errdefer self.screen.deinit();
var n: usize = 4 << 20;
const a = 1.7;
const b = 1.7;
const c = 0.6;
const d = 1.2;
const scale = comptime math.max(if (c < 0) -c else c, if (d < 0) -d else d) + 1.0;
var x: f64 = a;
var y: f64 = b;
while (n != 0) : (n -= 1) {
if (self.screen.ref(coMix(-scale, scale, x), coMix(-scale, scale, y))) |pixel| {
pixel.count += 1;
}
const x1 = math.sin(a * y) + c * math.cos(a * x);
const y1 = math.sin(b * x) + d * math.cos(b * y);
x = x1;
y = y1;
}
var highest: usize = 1;
for (self.screen.cells) |pixel| {
if (pixel.count > highest) {
highest = pixel.count;
}
}
self.countCorrection = 1 / @intToFloat(f64, highest);
return self;
}
pub fn deinit(self: *const Self, allocator: *Allocator) void {
self.screen.deinit();
}
pub fn shade(self: *const Self, x: f64, y: f64) Jazbz {
if (self.screen.get(x, y)) |pixel| {
const count = @intToFloat(f64, pixel.count) * self.countCorrection;
return mix(colors.white, colors.darkGreen, gmath.mapDynamicRange(0, 1, 0, 1, 0.3, 0.5, 1.0, count));
} else {
return colors.white;
}
}
};
const JuliaSetShader = struct {
const Self = @This();
pub fn init(allocator: *Allocator, config: renderer.ShaderConfig) !Self {
return Self{};
}
pub fn deinit(self: *const Self, allocator: *Allocator) void {}
pub fn shade(self: *const Self, x: f64, y: f64) Jazbz {
const nLimit: usize = 1 << 9;
const cx = -0.76;
const cy = -0.09;
var zx = mix(-0.8, 0.8, y);
var zy = mix(-0.8, 0.8, x);
var xx = zx * zx;
var yy = zy * zy;
var n: usize = nLimit;
while (n != 0 and xx + yy < 4) : (n -= 1) {
zy *= zx;
zy *= 2;
zy += cy;
zx = xx - yy + cx;
xx = zx * zx;
yy = zy * zy;
}
const n01 = coMix(0, comptime @intToFloat(f64, nLimit), @intToFloat(f64, n));
return rainbowRamp(n01).scaleJ(vignette(x, y));
}
fn rainbowRamp(x: f64) Jazbz {
return Jazbz{
.j = mix(0.0, 0.7, gmath.quantize(1.0 / 8.0, gmath.sigmoidC3(sq(x)))),
.azbz = AzBz.initCh(0.6, fract(x * 12)),
};
}
fn vignette(x: f64, y: f64) f64 {
return mix(0.4, 1, 1.3 - (1 - (1 - sq(x)) * (1 - sq(y))));
}
};
const SimplexNoiseShader = struct {
const sn = @import("lib/simplexnoise1234.zig");
const Self = @This();
pub fn init(allocator: *Allocator, config: renderer.ShaderConfig) !Self {
return Self{};
}
pub fn deinit(self: *const Self, allocator: *Allocator) void {}
pub fn shade(self: *const Self, x: f64, y: f64) Jazbz {
const h1 = sn.noise2(mix(100, 104, x), mix(200, 204, y)) * 1.0;
const h2 = sn.noise2(mix(300, 308, x), mix(400, 408, y)) * 0.5;
const h3 = sn.noise2(mix(500, 516, x), mix(600, 616, y)) * 0.25;
const cloud = coMix(-1.75, 1.75, h1 + h2 + h3);
var result = mix(colors.goldenYellow, colors.darkPurple, cloud);
result.j = gmath.sigmoidSkew(mix(0.0, 0.4, y), 0.5, result.j);
return result;
}
};
const GeometryShader = struct {
const geom = @import("lib/geom.zig");
const sdf2 = @import("lib/sdf2.zig");
const brdf = @import("lib/brdf.zig");
const sn = @import("lib/simplexnoise1234.zig");
const Self = @This();
pub fn init(allocator: *Allocator, config: renderer.ShaderConfig) !Self {
return Self{};
}
pub fn deinit(self: *const Self, allocator: *Allocator) void {}
pub fn shade(self: *const Self, x: f64, y: f64) Jazbz {
const circleRadius = comptime mix(0.1, 0.16666666666666666, 0.5);
const inset = 0.33333333333333333;
const offset = comptime v2(0.025, -0.0125);
const Dp1 = DotPipe(comptime v2(inset, inset).add(offset), circleRadius, V2.degree90);
const Dp2 = DotPipe(comptime v2(1 - inset, 1 - inset).add(offset), circleRadius, V2.degree0);
const Dp3 = DotPipe(comptime v2(inset, 1 - inset).add(offset), circleRadius, V2.degree315);
const p = v2(x, y);
const p1 = Dp1.signedDists(p);
const p2 = Dp2.signedDists(p);
const p3 = Dp3.signedDists(p);
const dotSd = p1.dot.merge(p2.dot).merge(p3.dot);
const pipeSd = dotSd.merge(p1.pipe).merge(p2.pipe).merge(p3.pipe);
const redMat = Surface{
.material = .{
.baseColor = mix(colors.leafGreen, colors.black, mix(0.0, 0.25, y)),
.reflectance = 0.2,
.roughness = 0.5,
},
.noise = 1,
.noiseSize = 192,
};
const blackMat = Surface{
.material = .{
.baseColor = colors.almostBlack,
.metallic = 1,
.clearcoat = 1,
.clearcoatRoughness = 0.35,
},
.noise = 0,
.noiseSize = 192,
};
const whiteMat = Surface{
.material = .{
.baseColor = colors.eggShell,
},
.noise = 0,
.noiseSize = 192,
};
const smooth = 0.001;
var mat = redMat;
mat = mix(mat, blackMat, pipeSd.smoothstepC3(smooth, 0));
mat = mix(mat, whiteMat, dotSd.smoothstepC3(smooth, 0));
const prepared = mat.material.prepare();
const point = v3(p.x, p.y, 0);
const h1 = sn.noise2(mix(100, 100 + mat.noiseSize, x), mix(200, 200 + mat.noiseSize, y));
const h2 = sn.noise2(mix(300, 300 + mat.noiseSize, x), mix(400, 400 + mat.noiseSize, y));
const normal = v3(h1 * mat.noise, h2 * mat.noise, 1).normalize();
const camera = v3(0.5, 0.5, 128);
const light1 = comptime v3(inset, inset, 0.5);
const light2 = comptime v3(inset, 1 - inset, 0.5);
const light3 = comptime v3(1 - inset, 1 - inset, 0.5);
const sample1 = prepared.brdf(normal, camera.sub(point).normalize(), light1.sub(point).normalize()).scaleJ(1.2);
const sample2 = prepared.brdf(normal, camera.sub(point).normalize(), light2.sub(point).normalize()).scaleJ(0.7);
const sample3 = prepared.brdf(normal, camera.sub(point).normalize(), light3.sub(point).normalize()).scaleJ(0.8);
var result = sample1.addLight(sample2).addLight(sample3).toJazbz();
const blackPoint = 0.03;
const whitePoint = 0.75;
result.j = gmath.filmicDynamicRange(blackPoint, whitePoint, 0.4, 0.5, result.j);
result.j = gmath.sigmoidSkew(0.3, 1 - y, result.j);
result.j = saturate(result.j);
return result;
}
const Surface = struct {
material: brdf.Material,
noise: f64 = 0,
noiseSize: f64 = 0,
pub fn mix(self: @This(), other: @This(), alpha: f64) @This() {
return .{
.material = gmath.mix(self.material, other.material, alpha),
.noise = gmath.mix(self.noise, other.noise, alpha),
.noiseSize = gmath.mix(self.noiseSize, other.noiseSize, alpha),
};
}
};
fn DotPipe(c: V2, r: f64, dir: V2) type {
const n = dir;
const e = n.rotate90();
const s = n.rotate180();
const w = n.rotate270();
const circle = geom.Circle.rp(r, c);
const line1 = geom.Line.pn(c.add(e.scale(r)), s);
const line2 = geom.Line.pn(c.add(w.scale(r)), n);
const line3 = geom.Line.pn(c, e);
return struct {
dot: sdf2.Sd,
pipe: sdf2.Sd,
fn signedDists(p: V2) @This() {
return .{
.dot = dotSd(p),
.pipe = pipeSd(p),
};
}
fn dotSd(p: V2) sdf2.Sd {
return circle.signedDist(p);
}
fn pipeSd(p: V2) sdf2.Sd {
const sd1 = line1.signedDistBefore(p);
const sd2 = line2.signedDistBefore(p);
const sd3 = line3.signedDistBefore(p);
return sd1.match(sd2).cut(sd3);
}
};
}
};
const QuantizeShader = struct {
const sqn = @import("lib/squirrel3noise.zig");
const Self = @This();
pub fn init(allocator: *Allocator, config: renderer.ShaderConfig) !Self {
return Self{};
}
pub fn deinit(self: *const Self, allocator: *Allocator) void {}
pub fn shade(self: *const Self, x: f64, y: f64) Jazbz {
const xq = gmath.quantize(0.1, x);
const yq = gmath.quantize(0.1, y);
const xf = gmath.fract(x / 0.1);
const yf = gmath.fract(y / 0.1);
var result = mix(
mix(colors.white, colors.black, xq),
mix(colors.navyBlue, colors.leafGreen, xq),
yq,
);
result.j = mix(result.j, xf, mix(0.05, 0.0, yf));
return result;
}
};
const IntNoiseShader = struct {
const gs = @import("lib/gridsize.zig");
const sqn = @import("lib/squirrel3noise.zig");
const Self = @This();
const Gs = gs.GridSize(7, 7);
const Cell = struct {
vertex: V2,
color: Jazbz,
};
grid: [Gs.len]Cell,
pub fn init(allocator: *Allocator, config: renderer.ShaderConfig) !Self {
var self = Self{
.grid = undefined,
};
var rng = sqn.squirrelRng(0);
for (self.grid) |*cell| {
cell.vertex = .{
.x = rng.f01(),
.y = rng.f01(),
};
cell.color = Jazbz.initJch(rng.mixf(0.5, 0.8), 0.3, rng.f01());
}
return self;
}
pub fn deinit(self: *const Self, allocator: *Allocator) void {}
pub fn shade(self: *const Self, x: f64, y: f64) Jazbz {
var result = colors.black;
if (Gs.pos(x, y)) |centerPos| {
var win_d: f64 = 1;
var win_color = colors.white;
for (centerPos.neighbors9()) |candidatePos| {
if (candidatePos) |pos| {
const q = v2(pos.cellx(x), pos.celly(y));
const cell = &self.grid[pos.index];
const c = cell.vertex;
const d = saturate(c.distTo(q));
if (d < win_d) {
win_d = d;
win_color = cell.color;
}
}
}
result = mix(result, win_color, coSq(1 - win_d));
result.j = gmath.sigmoidSkew(0.3, 1 - y, result.j);
}
return result;
}
};
const SurfaceNormalShader = struct {
const geom = @import("lib/geom.zig");
const sdf2 = @import("lib/sdf2.zig");
const brdf = @import("lib/brdf.zig");
const surf = @import("lib/surfacenormal.zig");
const Self = @This();
pub fn init(allocator: *Allocator, config: renderer.ShaderConfig) !Self {
return Self{};
}
pub fn deinit(self: *const Self, allocator: *Allocator) void {}
pub fn shade(self: *const Self, x: f64, y: f64) Jazbz {
const p = v2(x, y);
const circle = geom.Circle.rp(0.3, v2(0.5, 0.5));
var layer = mix(colors.bloodRed, colors.goldenYellow, x);
if (surf.EllipticalTorus.forCircle(circle, 0.15, 0.2, p)) |surface| {
const material = brdf.Material{
.baseColor = mix(colors.bloodRed, colors.goldenYellow, 1 - x),
.reflectance = 0.4,
.roughness = 0.6,
.clearcoat = 1,
.clearcoatRoughness = 0.3,
};
const shaded = surf.shade(surface, &material.prepare());
layer = mix(layer, shaded, surface.blend.smoothstepC3(0.001, 0));
}
layer.j = gmath.sigmoidSkew(0.3, 1 - y, layer.j);
layer.j = saturate(layer.j);
return layer;
}
};
pub const enable_segfault_handler: bool = true;
const std = @import("std");
const math = std.math;
const Allocator = std.mem.Allocator;
const renderer = @import("lib/renderer.zig");
const Resolutions = @import("lib/resolutions.zig").Resolutions;
const V2 = @import("lib/affine.zig").V2;
const V3 = @import("lib/affine.zig").V3;
const v2 = V2.init;
const v3 = V3.init;
const Jazbz = @import("lib/jabz.zig").Jazbz(f64);
const AzBz = Jazbz.AzBz;
const colors = @import("lib/colors.zig").Colors(Jazbz);
const gmath = @import("lib/gmath.zig").gmath(f64);
const fract = gmath.fract;
const clamp = gmath.clamp;
const saturate = gmath.saturate;
const linearstep = gmath.linearstep;
const smoothstepC1 = gmath.smoothstepC1;
const smoothstepC2 = gmath.smoothstepC2;
const smoothstepC3 = gmath.smoothstepC3;
const mix = gmath.mix;
const coMix = gmath.coMix;
const sq = gmath.sq;
const coSq = gmath.coSq;
const pi = gmath.pi;
const invPi = gmath.invPi;
const tau = gmath.tau;
const invTau = gmath.invTau;
const phi = gmath.phi;
const invPhi = gmath.invPhi;
const sqrt2 = gmath.sqrt2;
const invSqrt2 = gmath.invSqrt2;
const sqrt3 = gmath.sqrt3;
const halfSqrt3 = gmath.halfSqrt3;
| https://raw.githubusercontent.com/quag/zig-generative-template/c59b72641ba7baef4c0f49e71f4576a67a4ec66c/main.zig |
pub const Cairo = @import("gdk/Cairo.zig");
pub const Display = @import("gdk/Display.zig").Display;
pub const Pixbuf = @import("gdk/Pixbuf.zig").Pixbuf;
pub const Wayland = @import("gdk/Wayland.zig");
fn refAllDeclsRecursive(comptime T: type) void {
comptime {
for (@import("std").meta.declarations(T)) |decl| {
if (decl.is_pub) {
switch (decl.data) {
.Type => |T2| refAllDeclsRecursive(T2),
else => _ = decl,
}
}
}
}
}
test {
@setEvalBranchQuota(100000);
refAllDeclsRecursive(@This());
}
| https://raw.githubusercontent.com/davidmhewitt/zig-gtk/8130922d5437aeb296d1f4b928d7a76f04ca27be/gdk.zig |
// Copyright (C) 2021-2024 Chadwain Holness
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
pub const token = @import("source/token.zig");
pub const Tokenizer = @import("source/Tokenizer.zig");
pub const Dom = @import("source/Dom.zig");
pub const tree_construction = @import("source/tree_construction.zig");
pub const Parser = @import("source/Parser.zig");
pub const util = @import("source/util.zig");
comptime {
if (@import("builtin").is_test) {
@import("std").testing.refAllDecls(@This());
}
}
| https://raw.githubusercontent.com/chadwain/rem/68dcb476a9090c9bbe0044dd26914ee1266924ed/rem.zig |
const std = @import("std");
pub fn main() void {
var sum: i64 = 0;
var i: i64 = 1;
while (i <= 1000000000): (i += 1) {
sum += i;
}
std.debug.print("{any}\n", .{sum});
}
| https://raw.githubusercontent.com/clarkzjw/one-two-three...infinity/f944fe3d68923f8e2bf3e5ec75bfc53fe4e52618/Zig.zig |
pub fn puts(str: [*:0]const u8) c_int {
return asm volatile (
\\ li $9, 0x3f
\\ j 0xa0
: [ret] "={r2}" (-> c_int)
: [str] "{r4}" (str)
);
}
| https://raw.githubusercontent.com/XaviDCR92/psx-zig/d1e2090f46938fff210c3cf2d79b60b1f8e98d25/puts.zig |
const std = @import("std");
pub const json = @import("./json.zig");
const Map = json.DeserializeMap;
pub const glTF = struct {
extensionsUsed: [][]const u8 = &[_][]const u8{},
extensionsRequired: [][]const u8 = &[_][]const u8{},
accessors: []Accessor = &[_]Accessor{},
//animations: []Animation,
asset: Asset,
buffers: []Buffer = &[_]Buffer{},
bufferViews: []BufferView = &[_]BufferView{},
//cameras: []Camera,
images: []Image = &[_]Image{},
materials: []Material = &[_]Material{},
meshes: []Mesh = &[_]Mesh{},
nodes: []Node = &[_]Node{},
samplers: []Sampler = &[_]Sampler{},
scene: ?usize = null,
scenes: []Scene = &[_]Scene{},
//skins: []Skin,
textures: []Texture = &[_]Texture{},
extensions: ?Map(json.Value) = null,
extras: ?json.Value = null,
};
pub const BYTE = 5120;
pub const UNSIGNED_BYTE = 5121;
pub const SHORT = 5122;
pub const UNSIGNED_SHORT = 5123;
pub const UNSIGNED_INT = 5125;
pub const FLOAT = 5126;
/// A typed view into a bufferView. A bufferView contains raw binary data. An accessor provides a
/// typed view into a bufferView or a subset of a bufferView similar to how WebGL's
/// vertexAttribPointer() defines an attribute in a buffer.
pub const Accessor = struct {
/// The index of the bufferView. When not defined, accessor must be initialized with zeros;
/// sparse property or extensions could override zeros with actual values.
bufferView: ?usize = null,
/// The offset relative to the start of the bufferView in bytes. This must be a multiple of the
/// size of the component datatype.
byteOffset: usize = 0,
/// The datatype of components in the attribute. All valid values correspond to WebGL enums. The
/// corresponding typed arrays are Int8Array, Uint8Array, Int16Array, Uint16Array, Uint32Array,
/// and Float32Array, respectively. 5125 (UNSIGNED_INT) is only allowed when the accessor
/// contains indices, i.e., the accessor is only referenced by primitive.indices.
componentType: ComponentType,
/// Specifies whether integer data values should be normalized (true) to [0, 1] (for unsigned
/// types) or [-1, 1] (for signed types), or converted directly (false) when they are accessed.
/// This property is defined only for accessors that contain vertex attributes or animation
/// output data.
normalized: bool = false,
/// The number of attributes referenced by this accessor, not to be confused with the number of
/// bytes or number of components.
count: usize,
// TODO: maybe change this from enum to a string? Extensions may require it
/// Specifies if the attribute is a scalar, vector, or matrix.
@"type": enum {
SCALAR,
VEC2,
VEC3,
VEC4,
MAT2,
MAT3,
MAT4,
pub fn size(self: @This()) usize {
return switch (self) {
.SCALAR => 1,
.VEC2 => 2,
.VEC3 => 3,
.VEC4 => 4,
.MAT2 => 4,
.MAT3 => 9,
.MAT4 => 16,
};
}
},
/// Maximum value of each component in this attribute. Array elements must be treated as having
/// the same data type as accessor's `componentType`. Both min and max arrays have the same
/// length. The length is determined by the value of the type property; it can be 1, 2, 3, 4, 9,
/// or 16.
///
/// `normalized` property has no effect on array values: they always correspond to the actual
/// values stored in the buffer. When accessor is sparse, this property must contain max values
/// of accessor data with sparse substitution applied.
max: ?[]f64 = null,
/// Maximum value of each component in this attribute. Array elements must be treated as having
/// the same data type as accessor's `componentType`. Both min and max arrays have the same
/// length. The length is determined by the value of the type property; it can be 1, 2, 3, 4, 9,
/// or 16.
///
/// `normalized` property has no effect on array values: they always correspond to the actual
/// values stored in the buffer. When accessor is sparse, this property must contain max values
/// of accessor data with sparse substitution applied.
min: ?[]f64 = null,
/// Sparse storage of attributes that deviate from their initialization value.
sparse: ?Sparse = null,
/// The user-defined name of this object. This is not necessarily unique, e.g., an accessor and
/// a buffer could have the same name, or two accessors could even have the same name.
name: ?[]const u8 = null,
/// Dictionary object with extension-specific objects.
extensions: ?Map(json.Value) = null,
/// Application-specific data
extras: ?json.Value = null,
pub const ComponentType = enum(u32) {
Byte = BYTE,
UnsignedByte = UNSIGNED_BYTE,
Short = SHORT,
UnsignedShort = UNSIGNED_SHORT,
UnsignedInt = UNSIGNED_INT,
Float = FLOAT,
};
pub const Sparse = struct {
count: usize,
indices: struct {
bufferView: usize,
byteOffset: usize,
componentType: ComponentType,
},
values: struct {
bufferView: usize,
byteOffset: usize,
},
};
};
pub const Asset = struct {
copyright: ?[]const u8 = null,
generator: ?[]const u8 = null,
version: []const u8,
minVersion: ?[]const u8 = null,
extensions: ?Map(json.Value) = null,
extras: ?json.Value = null,
};
pub const Buffer = struct {
uri: ?[]const u8 = null,
byteLength: usize,
name: ?[]const u8 = null,
extensions: ?Map(json.Value) = null,
extras: ?json.Value = null,
};
pub const ARRAY_BUFFER = 34962;
pub const ELEMENT_ARRAY_BUFFER = 34963;
pub const BufferView = struct {
buffer: usize,
byteOffset: usize = 0,
byteLength: usize,
stride: ?usize = null,
target: ?enum(u32) {
ArrayBuffer = ARRAY_BUFFER,
ElementArrayBuffer = ELEMENT_ARRAY_BUFFER,
} = null,
name: ?[]const u8 = null,
extensions: ?Map(json.Value) = null,
extras: ?json.Value = null,
};
pub const Image = struct {
uri: ?[]const u8 = null,
mimeType: ?[]const u8 = null,
bufferView: ?usize = null,
name: ?[]const u8 = null,
extensions: ?Map(json.Value) = null,
extras: ?json.Value = null,
};
pub const Material = struct {
name: ?[]const u8 = null,
extensions: ?Map(json.Value) = null,
extras: ?json.Value = null,
pbrMetallicRoughness: PBR_MetallicRoughness = PBR_MetallicRoughness{},
normalTexture: ?NormalTexture = null,
occlusionTexture: ?OcclusionTexture = null,
emissiveTexture: ?EmissiveTexture = null,
emissiveFactor: [3]f64 = [_]f64{ 0, 0, 0 },
alphaMode: enum {
OPAQUE,
MASK,
BLEND,
} = .OPAQUE,
alphaCutoff: f64 = 0.5,
doubleSided: bool = false,
pub const PBR_MetallicRoughness = struct {
baseColorFactor: [4]f64 = [4]f64{ 1, 1, 1, 1 },
baseColorTexture: ?Map(json.Value) = null,
metallicFactor: f64 = 1,
roughnessFactor: f64 = 1,
metallicRoughnessTexture: ?Map(json.Value) = null,
extensions: ?Map(json.Value) = null,
extras: ?json.Value = null,
};
pub const NormalTexture = struct {
index: usize,
texCoord: usize = 0,
scale: f64 = 1,
extensions: ?Map(json.Value) = null,
extras: ?json.Value = null,
};
pub const OcclusionTexture = struct {
index: usize,
texCoord: usize = 0,
strength: f64 = 1,
extensions: ?Map(json.Value) = null,
extras: ?json.Value = null,
};
pub const EmissiveTexture = struct {
index: usize,
texCoord: usize = 0,
extensions: ?Map(json.Value) = null,
extras: ?json.Value = null,
};
};
const POINTS = 0;
const LINES = 1;
const LINE_LOOP = 2;
const LINE_STRIP = 3;
const TRIANGLES = 4;
const TRIANGLE_STRIP = 5;
const TRIANGLE_FAN = 6;
pub const Mesh = struct {
primitives: []Primitive,
weights: ?[]f64 = null,
name: ?[]const u8 = null,
extensions: ?Map(json.Value) = null,
extras: ?json.Value = null,
pub const Primitive = struct {
attributes: Map(usize),
indices: ?usize = null,
material: ?usize = null,
mode: enum {
Points = POINTS,
Lines = LINES,
LineLoop = LINE_LOOP,
LineStrip = LINE_STRIP,
Triangles = TRIANGLES,
TriangleStrip = TRIANGLE_STRIP,
TriangleFan = TRIANGLE_FAN,
} = .Triangles,
targets: ?[]Map(usize) = null,
extensions: ?Map(json.Value) = null,
extras: ?json.Value = null,
};
};
pub const Node = struct {
camera: ?usize = null,
children: []usize = &[_]usize{},
skin: ?usize = null,
matrix: ?[16]f64 = null,
mesh: ?usize = null,
rotation: ?[4]f64 = null,
scale: ?[3]f64 = null,
translation: ?[3]f64 = null,
weights: ?[]f64 = null,
name: ?[]const u8 = null,
extensions: ?Map(json.Value) = null,
extras: ?json.Value = null,
};
pub const NEAREST = 9728;
pub const LINEAR = 9729;
pub const NEAREST_MIPMAP_NEAREST = 9984;
pub const LINEAR_MIPMAP_NEAREST = 9985;
pub const NEAREST_MIPMAP_LINEAR = 9986;
pub const LINEAR_MIPMAP_LINEAR = 9987;
pub const CLAMP_TO_EDGE = 33071;
pub const MIRRORED_REPEAT = 33648;
pub const REPEAT = 10497;
pub const Sampler = struct {
magFilter: ?enum(u32) {
Nearest = NEAREST,
Linear = LINEAR,
} = null,
minFilter: ?enum(u32) {
Nearest = NEAREST,
Linear = LINEAR,
NearestMipmapNearest = NEAREST_MIPMAP_NEAREST,
LinearMipmapNearest = LINEAR_MIPMAP_NEAREST,
NearestMipmapLinear = NEAREST_MIPMAP_LINEAR,
LinearMipmapLinear = LINEAR_MIPMAP_LINEAR,
} = null,
wrapS: WrappingMode = .Repeat,
wrapT: WrappingMode = .Repeat,
name: ?[]const u8 = null,
extensions: ?Map(json.Value) = null,
extras: ?json.Value = null,
pub const WrappingMode = enum(u32) {
ClampToEdge = CLAMP_TO_EDGE,
MirroredRepeat = MIRRORED_REPEAT,
Repeat = REPEAT,
};
};
pub const Scene = struct {
nodes: []usize = &[_]usize{},
name: ?[]const u8 = null,
extensions: ?Map(json.Value) = null,
extras: ?json.Value = null,
};
pub const Texture = struct {
sampler: ?usize = null,
source: ?usize = null,
name: ?[]const u8 = null,
extensions: ?Map(json.Value) = null,
extras: ?json.Value = null,
};
| https://raw.githubusercontent.com/leroycep/gltf-zig/9df88e095a578fed8d456911171f3ec7110eeae4/gltf.zig |
const std = @import("std");
const data = @embedFile("./day2.data");
// const data =
// \\forward 5
// \\down 5
// \\forward 8
// \\up 3
// \\down 8
// \\forward 2
// ;
pub fn main() !void {
var it = std.mem.split(u8, data, "\n");
var x: u64 = 0;
var y: u64 = 0;
var aim: u64 = 0;
while(it.next()) |token| {
if (std.mem.indexOf(u8, token, "forward") != null) {
const n = try std.fmt.parseInt(u32, token[8..], 10);
// increases your horizontal position by n units
x += n;
// increases your depth by your aim multiplied by n
y += aim * n;
} else if(std.mem.indexOf(u8, token, "down") != null) {
const n = try std.fmt.parseInt(u32, token[5..], 10);
// down n increases your aim by n units
aim += n;
} else {
// up
const n = try std.fmt.parseInt(u32, token[3..], 10);
// up n decreases your aim by n units
aim -= n;
}
// std.debug.print("{s} | x = {d}, y = {d}, aim = {d} \n", .{token, x, y, aim});
}
std.debug.print("x = {d}, y = {d}, product = {d} \n", .{x, y, x * y});
} | https://raw.githubusercontent.com/IwanKaramazow/adventofcode21/0531d3835cd2fa4908829948d3800c5aee675bf4/day2.zig |
const std = @import("std");
pub fn is_alsa_playing() !bool {
var argv = [_][]const u8{ "sh", "-c", "grep RUNNING /proc/asound/card*/pcm*/sub*/status" };
var result = try std.ChildProcess.exec(.{ .allocator = std.heap.page_allocator, .argv = &argv });
// std.debug.print("stderr={s}\n", .{result.stderr});
// std.debug.print("stdout={s}\n", .{result.stdout});
return result.stdout.len != 0;
}
| https://raw.githubusercontent.com/Ryp/gpio-zig/fcca36f13cfbe0f223dcbe41b68ecb33eafd80c2/alsa.zig |
const std = @import("std");
const expect = std.testing.expect;
const test_allocator = std.testing.allocator;
test "stack" {
const string = "(()())";
var stack = std.ArrayList(usize).init(
test_allocator,
);
defer stack.deinit();
const Pair = struct { open: usize, close: usize };
var pairs = std.ArrayList(Pair).init(
test_allocator,
);
defer pairs.deinit();
for (string, 0..) |char, i| {
if (char == '(') try stack.append(i);
if (char == ')')
try pairs.append(.{
.open = stack.pop(),
.close = i,
});
}
for (pairs.items, 0..) |pair, i| {
try expect(std.meta.eql(pair, switch (i) {
0 => Pair{ .open = 1, .close = 2 },
1 => Pair{ .open = 3, .close = 4 },
2 => Pair{ .open = 0, .close = 5 },
else => unreachable,
}));
}
} | https://raw.githubusercontent.com/akalmannakarmi/zig-try/d3ed6d7e54ae8044ed760340d8139f353d3e0d3e/e4j.zig |
const std = @import("std");
pub const Format = enum {
unsigned8,
signed16_lsb,
signed24_lsb,
signed32_lsb,
pub fn getNumBytes(self: Format) u16 {
return switch (self) {
.unsigned8 => 1,
.signed16_lsb => 2,
.signed24_lsb => 3,
.signed32_lsb => 4,
};
}
};
pub const PreloadedInfo = struct {
num_channels: usize,
sample_rate: usize,
format: Format,
num_samples: usize,
pub fn getNumBytes(self: PreloadedInfo) usize {
return self.num_samples * self.num_channels * self.format.getNumBytes();
}
};
// verbose is comptime so we can avoid using std.debug.warn which doesn't
// exist on some targets (e.g. wasm)
pub fn Loader(comptime Reader: type, comptime verbose: bool) type {
return struct {
fn readIdentifier(reader: *Reader) ![4]u8 {
var quad: [4]u8 = undefined;
try reader.readNoEof(&quad);
return quad;
}
fn toIdentifier(reader: *Reader, id: [4]u8) !void {
while (true) {
const quad = try readIdentifier(reader);
if (std.mem.eql(u8, &quad, &id))
return;
const size = try reader.readIntLittle(u32);
try reader.skipBytes(size, .{});
}
}
fn preloadError(comptime message: []const u8) !PreloadedInfo {
if (verbose) {
std.debug.warn("{s}\n", .{message});
}
return error.WavLoadFailed;
}
pub fn preload(reader: *Reader) !PreloadedInfo {
// read RIFF chunk descriptor (12 bytes)
const chunk_id = try readIdentifier(reader);
if (!std.mem.eql(u8, &chunk_id, "RIFF")) {
return preloadError("missing \"RIFF\" header");
}
try reader.skipBytes(4, .{}); // ignore chunk_size
const format_id = try readIdentifier(reader);
if (!std.mem.eql(u8, &format_id, "WAVE")) {
return preloadError("missing \"WAVE\" identifier");
}
// read "fmt" sub-chunk
const subchunk1_id = try readIdentifier(reader);
if (!std.mem.eql(u8, &subchunk1_id, "fmt ")) {
return preloadError("missing \"fmt \" header");
}
const subchunk1_size = try reader.readIntLittle(u32);
if (subchunk1_size != 16) {
return preloadError("not PCM (subchunk1_size != 16)");
}
const audio_format = try reader.readIntLittle(u16);
if (audio_format != 1) {
return preloadError("not integer PCM (audio_format != 1)");
}
const num_channels = try reader.readIntLittle(u16);
const sample_rate = try reader.readIntLittle(u32);
const byte_rate = try reader.readIntLittle(u32);
const block_align = try reader.readIntLittle(u16);
const bits_per_sample = try reader.readIntLittle(u16);
if (num_channels < 1 or num_channels > 16) {
return preloadError("invalid number of channels");
}
if (sample_rate < 1 or sample_rate > 192000) {
return preloadError("invalid sample_rate");
}
const format: Format = switch (bits_per_sample) {
8 => .unsigned8,
16 => .signed16_lsb,
24 => .signed24_lsb,
32 => .signed32_lsb,
else => return preloadError("invalid number of bits per sample"),
};
const bytes_per_sample = format.getNumBytes();
if (byte_rate != sample_rate * num_channels * bytes_per_sample) {
return preloadError("invalid byte_rate");
}
if (block_align != num_channels * bytes_per_sample) {
return preloadError("invalid block_align");
}
// read "data" sub-chunk header
toIdentifier(reader, "data".*) catch |e| switch (e) {
error.EndOfStream => return preloadError("missing \"data\" header"),
else => return e,
};
const subchunk2_size = try reader.readIntLittle(u32);
if ((subchunk2_size % (num_channels * bytes_per_sample)) != 0) {
return preloadError("invalid subchunk2_size");
}
const num_samples = subchunk2_size / (num_channels * bytes_per_sample);
return PreloadedInfo{
.num_channels = num_channels,
.sample_rate = sample_rate,
.format = format,
.num_samples = num_samples,
};
}
pub fn load(
reader: *Reader,
preloaded: PreloadedInfo,
out_buffer: []u8,
) !void {
const num_bytes = preloaded.getNumBytes();
std.debug.assert(out_buffer.len >= num_bytes);
try reader.readNoEof(out_buffer[0..num_bytes]);
}
};
}
pub const SaveInfo = struct {
num_channels: usize,
sample_rate: usize,
format: Format,
};
pub fn Saver(comptime Writer: type) type {
const data_chunk_pos: u32 = 36; // location of "data" header
return struct {
fn writeHelper(writer: Writer, info: SaveInfo, maybe_data: ?[]const u8) !void {
const bytes_per_sample = info.format.getNumBytes();
const num_channels = try std.math.cast(u16, info.num_channels);
const sample_rate = try std.math.cast(u32, info.sample_rate);
const byte_rate = sample_rate * @as(u32, num_channels) * bytes_per_sample;
const block_align: u16 = num_channels * bytes_per_sample;
const bits_per_sample: u16 = bytes_per_sample * 8;
const data_len = if (maybe_data) |data| try std.math.cast(u32, data.len) else 0;
try writer.writeAll("RIFF");
if (maybe_data != null) {
try writer.writeIntLittle(u32, data_chunk_pos + 8 + data_len - 8);
} else {
try writer.writeIntLittle(u32, 0);
}
try writer.writeAll("WAVE");
try writer.writeAll("fmt ");
try writer.writeIntLittle(u32, 16); // PCM
try writer.writeIntLittle(u16, 1); // uncompressed
try writer.writeIntLittle(u16, num_channels);
try writer.writeIntLittle(u32, sample_rate);
try writer.writeIntLittle(u32, byte_rate);
try writer.writeIntLittle(u16, block_align);
try writer.writeIntLittle(u16, bits_per_sample);
try writer.writeAll("data");
if (maybe_data) |data| {
try writer.writeIntLittle(u32, data_len);
try writer.writeAll(data);
} else {
try writer.writeIntLittle(u32, 0);
}
}
// write wav header with placeholder values for length. use this when
// you are going to stream to the wav file and won't know the length
// till you are done.
pub fn writeHeader(writer: Writer, info: SaveInfo) !void {
try writeHelper(writer, info, null);
}
// after streaming, call this to seek back and patch the wav header
// with length values.
pub fn patchHeader(writer: Writer, seeker: anytype, data_len: usize) !void {
const data_len_u32 = try std.math.cast(u32, data_len);
try seeker.seekTo(4);
try writer.writeIntLittle(u32, data_chunk_pos + 8 + data_len_u32 - 8);
try seeker.seekTo(data_chunk_pos + 4);
try writer.writeIntLittle(u32, data_len_u32);
}
// save a prepared wav (header and data) in one shot.
pub fn save(writer: Writer, data: []const u8, info: SaveInfo) !void {
try writeHelper(writer, info, data);
}
};
}
test "basic coverage (loading)" {
const null_wav = [_]u8{
0x52, 0x49, 0x46, 0x46, 0x7C, 0x00, 0x00, 0x00, 0x57, 0x41, 0x56,
0x45, 0x66, 0x6D, 0x74, 0x20, 0x10, 0x00, 0x00, 0x00, 0x01, 0x00,
0x01, 0x00, 0x44, 0xAC, 0x00, 0x00, 0x88, 0x58, 0x01, 0x00, 0x02,
0x00, 0x10, 0x00, 0x64, 0x61, 0x74, 0x61, 0x58, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFF, 0xFF, 0x02, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00,
0x00, 0xFF, 0xFF, 0x02, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0xFE, 0xFF, 0x01, 0x00, 0x01,
0x00, 0xFE, 0xFF, 0x03, 0x00, 0xFD, 0xFF, 0x02, 0x00, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0xFF, 0xFF, 0x01, 0x00, 0xFE,
0xFF, 0x02, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x01, 0x00, 0xFF, 0xFF,
0x00, 0x00, 0x01, 0x00, 0xFE, 0xFF, 0x02, 0x00, 0xFF, 0xFF, 0x00,
0x00, 0x00, 0x00, 0xFF, 0xFF, 0x03, 0x00, 0xFC, 0xFF, 0x03, 0x00,
};
var reader = std.io.fixedBufferStream(&null_wav).reader();
const MyLoader = Loader(@TypeOf(reader), true);
const preloaded = try MyLoader.preload(&reader);
std.testing.expectEqual(@as(usize, 1), preloaded.num_channels);
std.testing.expectEqual(@as(usize, 44100), preloaded.sample_rate);
std.testing.expectEqual(@as(Format, .signed16_lsb), preloaded.format);
std.testing.expectEqual(@as(usize, 44), preloaded.num_samples);
var buffer: [88]u8 = undefined;
try MyLoader.load(&reader, preloaded, &buffer);
}
test "basic coverage (saving)" {
var buffer: [1000]u8 = undefined;
var writer = std.io.fixedBufferStream(&buffer).writer();
try Saver(@TypeOf(writer)).save(writer, &[_]u8{ 0, 0, 0, 0, 0, 0, 0, 0 }, .{
.num_channels = 1,
.sample_rate = 44100,
.format = .signed16_lsb,
});
std.testing.expectEqualSlices(u8, "RIFF", buffer[0..4]);
}
test "basic coverage (streaming out)" {
var buffer: [1000]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buffer);
const MySaver = Saver(@TypeOf(fbs).Writer);
try MySaver.writeHeader(fbs.writer(), .{
.num_channels = 1,
.sample_rate = 44100,
.format = .signed16_lsb,
});
std.testing.expectEqual(@as(u64, 44), try fbs.getPos());
std.testing.expectEqual(@as(u32, 0), std.mem.readIntLittle(u32, buffer[4..8]));
std.testing.expectEqual(@as(u32, 0), std.mem.readIntLittle(u32, buffer[40..44]));
const data = &[_]u8{ 0, 0, 0, 0, 0, 0, 0, 0 };
try fbs.writer().writeAll(data);
std.testing.expectEqual(@as(u64, 52), try fbs.getPos());
try MySaver.patchHeader(fbs.writer(), fbs.seekableStream(), data.len);
std.testing.expectEqual(@as(u32, 44), std.mem.readIntLittle(u32, buffer[4..8]));
std.testing.expectEqual(@as(u32, 8), std.mem.readIntLittle(u32, buffer[40..44]));
}
| https://raw.githubusercontent.com/marler8997/audio-deinterlacer/9a30af1f0d8ca50155b8168773bf56763b084d44/wav.zig |
// This is free and unencumbered software released into the public domain.
pub usingnamespace @import("src/angle.zig");
pub usingnamespace @import("src/latitude.zig");
pub usingnamespace @import("src/longitude.zig");
test "Dogma" { // zig test dogma.zig
const meta = @import("std").meta;
meta.refAllDecls(@This());
}
| https://raw.githubusercontent.com/dogmatists/dogma.zig/15c0227896fb5b37b06cd4e3386d28ca58f9a3e3/dogma.zig |
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const tomlZigName = "toml-zig";
const dep_opts = .{ .target = target, .optimize = optimize };
const tomlZig = b.dependency(tomlZigName, dep_opts).module(tomlZigName);
// const lib = b.addStaticLibrary(.{
// .name = "tinytask",
// .root_source_file = .{ .path = "src/root.zig" },
// .target = target,
// .optimize = optimize,
// });
// lib.root_module.addImport(tomlZigName, tomlZig);
// b.installArtifact(lib);
const exe = b.addExecutable(.{
.name = "tinytask",
.root_source_file = .{ .path = "src/main.zig" },
.target = target,
.optimize = optimize,
});
exe.root_module.addImport(tomlZigName, tomlZig);
b.installArtifact(exe);
const run_cmd = b.addRunArtifact(exe);
run_cmd.step.dependOn(b.getInstallStep());
// zig build run -- arg1 arg2 etc`
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
// const lib_unit_tests = b.addTest(.{
// .root_source_file = .{ .path = "src/root.zig" },
// .target = target,
// .optimize = optimize,
// });
// const run_lib_unit_tests = b.addRunArtifact(lib_unit_tests);
const exe_unit_tests = b.addTest(.{
.root_source_file = .{ .path = "src/main.zig" },
.target = target,
.optimize = optimize,
});
const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests);
const test_step = b.step("test", "Run unit tests");
// test_step.dependOn(&run_lib_unit_tests.step);
test_step.dependOn(&run_exe_unit_tests.step);
}
| https://raw.githubusercontent.com/sirenkovladd/tinytask/3374a7fde03125e1ae07e6db6d7fcc9e43fd5083/build.zig |
const std = @import("std");
const cli = @import("cli");
const dawn = @import("dawn");
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
var port_receive_option = cli.Option{
.long_name = "port_receive",
.help = "port to receive osc messages on (optional).",
.value = cli.OptionValue{ .int = 2502 },
};
var port_send_option = cli.Option{
.long_name = "port_send",
.help = "port to send osc messages to (optional).",
.value = cli.OptionValue{ .int = 2501 },
};
var app = &cli.App{
.name = "dawn",
.version = dawn.version,
.description =
\\dawn is a modular synth.
,
.options = &.{ &port_send_option, &port_receive_option },
.action = run_dawn,
.help_config = cli.HelpConfig{
.color_usage = cli.ColorUsage.never,
},
};
pub fn log(
comptime level: std.log.Level,
comptime scope: @Type(.EnumLiteral),
comptime format: []const u8,
args: anytype,
) void {
const stdout = std.io.getStdOut().writer();
const prefix = "[" ++ comptime level.asText() ++ "] " ++ "(" ++ @tagName(scope) ++ ") ";
nosuspend stdout.print(prefix ++ format ++ "\n", args) catch return;
}
pub const std_options = struct {
pub const log_level = .info;
pub const logFn = log;
};
var patch: *dawn.Patch = undefined;
fn run_dawn(_: []const []const u8) !void {
var port_send = port_send_option.value.int orelse unreachable;
var port_receive = port_receive_option.value.int orelse unreachable;
const logger = std.log.scoped(.dawn);
logger.info("start of session", .{});
defer logger.info("end of session", .{});
patch = try dawn.Patch.create(allocator);
patch.port_receive = @intCast(port_receive);
patch.port_send = @intCast(port_send);
logger.info("initialized patch", .{});
defer patch.destroy(allocator);
logger.info("adding opensoundcontrol module to patch", .{});
try patch.add_module("opensoundcontrol", "opensoundcontrol");
logger.info("adding soundio module to patch", .{});
try patch.add_module("soundio", "soundio");
while (true) {
std.time.sleep(std.time.ns_per_s); // TODO: reconsider
}
}
pub fn main() !void {
return cli.run(app, allocator);
}
| https://raw.githubusercontent.com/dawnsynth/dawn/c9062931757d1df06766026b0bdac5a572ece30b/dawn.zig |
//! https://adventofcode.com/2023/day/4
const std = @import("std");
const A = std.BoundedArray(u32, 32);
fn parseWins(line: []const u8, ns: *A) !usize {
ns.len = 0;
var win_count: usize = 0;
var it = std.mem.splitScalar(u8, line, ':');
_ = it.next().?;
const x = it.next().?;
var it2 = std.mem.splitScalar(u8, x, '|');
const ws = it2.next().?;
const nums = it2.next().?;
var winiter = std.mem.tokenizeAny(u8, ws, ", ");
while (winiter.next()) |win|
try ns.append(try std.fmt.parseInt(u32, win, 10));
var numiter = std.mem.tokenizeAny(u8, nums, ", ");
while (numiter.next()) |num| {
const n = try std.fmt.parseInt(u32, num, 10);
if (std.mem.indexOfScalar(u32, ns.constSlice(), n)) |_|
win_count += 1;
}
return win_count;
}
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const alloc = arena.allocator();
const args = try std.process.argsAlloc(alloc);
const file = try std.fs.cwd().openFile(args[1], .{});
defer file.close();
const input = try file.readToEndAlloc(alloc, std.math.maxInt(u32));
var part1: usize = 0;
var part2: usize = 0;
// init copies for part 2
var lines = std.mem.tokenizeScalar(u8, input, '\n');
var lines_count: usize = 0;
while (lines.next()) |_| lines_count += 1;
lines.reset();
var copies = try std.ArrayList(u32).initCapacity(alloc, lines_count);
copies.expandToCapacity();
@memset(copies.items, 1);
var ns = try A.init(0);
var cardid: usize = 0;
while (lines.next()) |line| : (cardid += 1) {
const wins = try parseWins(line, &ns);
part1 += if (wins > 0)
@as(usize, 1) << @as(u6, @intCast(wins)) - 1
else
wins;
for (0..wins) |win_idx|
copies.items[win_idx + cardid + 1] += copies.items[cardid];
part2 += copies.items[cardid];
}
std.debug.print("part1 {} part2 {}\n", .{ part1, part2 });
// std.debug.assert(part1 == 21088);
// std.debug.assert(part2 == 6874754);
}
| https://raw.githubusercontent.com/travisstaloch/advent-of-code-2023/e9b7cc6003191bd45bf55277567531e9e5fe9a4a/04.zig |
const root = @import("root");
pub const c = if (@hasDecl(root, "loadable_extension"))
@import("c/loadable_extension.zig")
else
@cImport({
@cInclude("sqlite3.h");
});
// versionGreaterThanOrEqualTo returns true if the SQLite version is >= to the major.minor.patch provided.
pub fn versionGreaterThanOrEqualTo(major: u8, minor: u8, patch: u8) bool {
return c.SQLITE_VERSION_NUMBER >= @as(u32, major) * 1000000 + @as(u32, minor) * 1000 + @as(u32, patch);
}
comptime {
if (!versionGreaterThanOrEqualTo(3, 21, 0)) {
@compileError("must use SQLite >= 3.21.0");
}
}
| https://raw.githubusercontent.com/malcolmstill/clerk/06d23ad09ece6aaf74127a316d9512ff23cb883a/lib/zig-sqlite/c.zig |
const std = @import("std.zig");
const avr = @import("atmega328p.zig");
const led_pin: u8 = 5;
const loop_ms = 0x0a52;
const one_second = 63974;
fn bit(comptime b: u3) comptime u8 {
return (1 << b);
}
fn flipLed() void {
avr.portb.* ^= bit(led_pin);
}
// Timer interrupt
// When this uses callconv(.Interrupt) llvm emits an extra sei
// instruction. The callconv(.Signal) avoids that.
export fn __vector_13() callconv(.Signal) void {
flipLed();
avr.tcnt1.* = one_second;
}
export fn main() noreturn {
avr.ddrb.* = bit(led_pin);
avr.portb.* = bit(led_pin);
avr.tcnt1.* = one_second;
avr.tccr1a.* = 0;
avr.tccr1b.* = bit(0) | bit(2); // clock select: clkio/1024
avr.timsk1.* = bit(0); // Interrupt on overflow enable
avr.sei();
while (true) {}
}
| https://raw.githubusercontent.com/ryanplusplus/avr-zig/7e240340a63d358665e04875d9cde7906d63e061/main.zig |
const std = @import("std");
pub fn insertionSort(comptime T: type, slice: []T) void {
for (1..slice.len) |i| {
var base = slice[i];
var j = i;
while (j >= 1 and slice[j - 1] > base) : (j -= 1) {
slice[j] = slice[j - 1];
}
slice[j] = base;
}
}
fn partition(comptime T: type, slice: []T, left: usize, right: usize) usize {
var med = blk: {
var mid = @divFloor(left + right, 2);
if ((slice[left] < slice[mid]) != (slice[left] < slice[right])) {
break :blk left;
} else if ((slice[mid] < slice[left]) != (slice[mid] < slice[right])) {
break :blk mid;
}
break :blk right;
};
std.mem.swap(T, &slice[left], &slice[med]);
var i = left;
var j = right;
while (i < j) {
while (i < j and slice[j] >= slice[left]) j -= 1;
while (i < j and slice[i] <= slice[left]) i += 1;
std.mem.swap(T, &slice[i], &slice[j]);
}
std.mem.swap(T, &slice[i], &slice[left]);
return i;
}
pub fn quickSort(comptime T: type, slice: []T) void {
if (slice.len == 0) return;
var left: usize = 0;
var right = slice.len - 1;
while (left < right) {
var pivot = partition(T, slice, left, right);
if (pivot - left < right - pivot) {
quickSort(T, slice[left..pivot]);
left = pivot + 1;
} else {
quickSort(T, slice[pivot + 1 .. right + 1]);
right = pivot - 1;
}
}
}
pub fn mergeSort(comptime T: type, slice: []T) !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
try mergePart(T, allocator, slice);
}
fn mergePart(comptime T: type, gpa: std.mem.Allocator, slice: []T) !void {
if (slice.len <= 1) return;
var mid = @divFloor(slice.len, 2);
try mergePart(T, gpa, slice[0..mid]);
try mergePart(T, gpa, slice[mid..]);
try merge(T, gpa, slice, mid);
}
fn merge(comptime T: type, gpa: std.mem.Allocator, slice: []T, mid: usize) !void {
var tmp = try gpa.alloc(T, slice.len);
defer gpa.free(tmp);
@memcpy(tmp, slice);
var i: usize = 0;
var j = mid;
var k: usize = 0;
while (k < slice.len) : (k += 1) {
if (i > mid - 1) {
slice[k] = tmp[j];
j += 1;
} else if (j >= slice.len or tmp[i] <= tmp[j]) {
slice[k] = tmp[i];
i += 1;
} else {
slice[k] = tmp[j];
j += 1;
}
}
}
pub fn ListMergeSort(comptime T: type) type {
return struct {
const L = std.SinglyLinkedList(T);
fn innerMerge(_a: ?*L.Node, _b: ?*L.Node) ?*L.Node {
var head = L.Node{ .data = 0 };
var c: ?*L.Node = &head;
var a = _a;
var b = _b;
while (a != null and b != null) {
if (a.?.data < b.?.data) {
c.?.next = a;
c = a;
a = a.?.next;
} else {
c.?.next = b;
c = b;
b = b.?.next;
}
}
c.?.next = if (a == null) b else a;
return head.next;
}
pub fn sort(list: *std.SinglyLinkedList(T)) void {
list.first = innerSort(list.first);
}
fn innerSort(first: ?*L.Node) ?*L.Node {
if (first == null or first.?.next == null) return first;
var c = first;
var a = c;
var b = c.?.next;
while (b != null and b.?.next != null) {
c = c.?.next;
b = b.?.next.?.next;
}
b = c.?.next;
c.?.next = null;
return innerMerge(innerSort(a), innerSort(b));
}
};
}
pub fn countingSort(slice: []u32) !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
var max: usize = 0;
for (slice) |el| {
if (el > max) max = @intCast(el);
}
var counter = try allocator.alloc(usize, max + 1);
defer allocator.free(counter);
@memset(counter, 0);
for (slice) |el| {
counter[@intCast(el)] += 1;
}
for (0..max) |i| {
counter[i + 1] += counter[i];
}
var tmp = try allocator.dupe(u32, slice);
defer allocator.free(tmp);
var pos = tmp.len;
while (pos > 0) : (pos -= 1) {
var num = tmp[pos - 1];
counter[num] -= 1;
slice[counter[num]] = num;
}
}
inline fn digit(el: u32, exp: u32) usize {
return @intCast(@rem(@divFloor(el, exp), 10));
}
fn countingSortDigit(gpa: std.mem.Allocator, slice: []u32, exp: u32) !void {
var counter = [_]u32{0} ** 10;
for (slice) |el| {
counter[digit(el, exp)] += 1;
}
for (1..10) |i| {
counter[i] += counter[i - 1];
}
var tmp = try gpa.dupe(u32, slice);
defer gpa.free(tmp);
var pos = tmp.len;
while (pos > 0) : (pos -= 1) {
var num = tmp[pos - 1];
var d = digit(num, exp);
counter[d] -= 1;
slice[counter[d]] = num;
}
}
pub fn radixSort(slice: []u32) !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
var max: usize = 0;
for (slice) |el| {
if (el > max) max = @intCast(el);
}
var exp: u32 = 1;
while (exp <= max) : (exp *= 10) {
try countingSortDigit(allocator, slice, exp);
}
}
pub fn main() !void {
const printSlice = @import("print_util.zig").printSlice;
var arr = [_]u32{ 9, 2, 4, 1, 12, 0, 3, 14, 5, 8, 6, 7, 10, 15, 13, 11 };
quickSort(u32, &arr);
printSlice(u32, &arr);
var arr2 = [_]u32{ 9, 2, 4, 1, 12, 0, 3, 14, 5, 8, 6, 7, 10, 15, 13, 11 };
insertionSort(u32, &arr2);
printSlice(u32, &arr2);
var arr3 = [_]u32{ 9, 2, 4, 1, 12, 0, 3, 14, 5, 8, 6, 7, 10, 15, 13, 11 };
mergeSort(u32, &arr3) catch unreachable;
printSlice(u32, &arr3);
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
const Link = std.SinglyLinkedList(u32);
var link = Link{};
var arr4 = [_]u32{ 9, 2, 4, 1, 12, 0, 3, 14, 5, 8, 6, 7, 10, 15, 13, 11 };
for (arr4) |val| {
var node = try allocator.create(Link.Node);
node.* = .{ .data = val };
link.prepend(node);
}
ListMergeSort(u32).sort(&link);
var it = link.first;
while (it) |ptr| : (it = it.?.next) {
std.debug.print("{d}{s}", .{ ptr.data, if (ptr.next != null) ", " else "\n" });
}
var arr5 = [_]u32{ 1, 0, 1, 2, 0, 4, 0, 2, 2, 4 };
try countingSort(&arr5);
printSlice(u32, &arr5);
var arr6 = [_]u32{ 10546151, 35663510, 42865989, 34862445, 81883077, 88906420, 72429244, 30524779, 82060337, 63832996 };
try radixSort(&arr6);
printSlice(u32, &arr6);
}
| https://raw.githubusercontent.com/rsphing/algo.zig/66b4ddfcc48f9cd006e5f726145f2408b55a7848/sort.zig |
const std = @import("std");
const stdx = @import("./stdx.zig");
const MAX = 64;
const Stack = std.BoundedArray(u8, MAX);
const Stacks = [MAX]Stack;
const Move = struct {
from: u32,
to: u32,
count: u32,
fn parse(line: []u8) !Move {
var rest = line;
_ = stdx.cut(&rest, "move ") orelse return error.BadInput;
const count_str = stdx.cut(&rest, " ") orelse return error.BadInput;
_ = stdx.cut(&rest, "from ") orelse return error.BadInput;
const from_str = stdx.cut(&rest, " ") orelse return error.BadInput;
_ = stdx.cut(&rest, "to ") orelse return error.BadInput;
const to_str = rest;
return Move{
.from = (try std.fmt.parseInt(u32, from_str, 10)) - 1,
.to = (try std.fmt.parseInt(u32, to_str, 10)) - 1,
.count = try std.fmt.parseInt(u32, count_str, 10),
};
}
};
const Moves = std.ArrayList(Move);
const Pos = struct {
stack: usize,
offset: usize,
};
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
var lines = stdx.StdinLines.new();
const stdout = std.io.getStdOut().writer();
var stacks: Stacks = undefined;
std.mem.set(Stack, &stacks, Stack.init(0) catch unreachable);
var moves = Moves.init(allocator);
while (true) {
const line = try lines.next();
if (std.mem.indexOf(u8, line, "[") == null) break;
var i: usize = 0;
while (i < line.len) : (i += 4) {
const item = line[i + 1];
if (item != ' ') stacks[i / 4].addOneAssumeCapacity().* = item;
}
}
const stack_count = blk: {
var count: usize = 0;
var it = std.mem.tokenize(u8, lines.curr, " ");
while (it.next() != null) count += 1;
break :blk count;
};
{
const line = try lines.next();
if (line.len != 0) return error.BadInput;
}
while (try lines.next_opt()) |line| {
const move = try Move.parse(line);
(try moves.addOne()).* = move;
}
var states: [MAX]Pos = undefined;
for (states) |*s, i| s.* = Pos{ .stack = i, .offset = 0 };
{
var i: usize = moves.items.len;
while (i > 0) {
i -= 1;
const move = moves.items[i];
std.debug.assert(move.from != move.to);
for (states) |*s| {
if (s.stack == move.from) {
s.offset += move.count;
}
if (s.stack == move.to) {
if (s.offset < move.count) {
s.stack = move.from;
// s.offset = move.count - s.offset - 1;
} else {
s.offset -= move.count;
}
}
}
}
}
var result = std.BoundedArray(u8, MAX).init(stack_count) catch unreachable;
for (result.slice()) |*slot, i| {
const pos = states[i];
const stack = stacks[pos.stack].slice();
slot.* = stack[pos.offset];
}
try stdout.print("{s}\n", .{result.slice()});
}
| https://raw.githubusercontent.com/matklad/aoc2022/67800cfb0aa3dcb0103da06c0b6f2103f1494dc7/day5.zig |
const std = @import("std");
const testing = std.testing;
pub const SpinLock = struct {
pub const Held = struct {
self: *SpinLock,
pub fn release(held: Held) void {
@atomicStore(bool, &held.self.locked, false, .Release);
}
};
locked: bool = false,
pub fn acquire(self: *SpinLock) Held {
while (@atomicRmw(bool, &self.locked, .Xchg, true, .Acquire)) {
std.Thread.spinLoopHint();
}
return Held{ .self = self };
}
};
test {
testing.refAllDecls(@This());
}
test "sync/spin_lock: acquire and release" {
var lock: SpinLock = .{};
const held = lock.acquire();
defer held.release();
}
| https://raw.githubusercontent.com/lithdew/hyperia/c1d166f81b6f011d9a23ef818b620e68eee3f49a/sync.zig |
// --- Day 5: Sunny with a Chance of Asteroids ---
//
// You're starting to sweat as the ship makes its way toward Mercury. The Elves suggest that you
// get the air conditioner working by upgrading your ship computer to support the Thermal
// Environment Supervision Terminal.
//
// The Thermal Environment Supervision Terminal (TEST) starts by running a diagnostic program
// (your puzzle input). The TEST diagnostic program will run on your existing Intcode computer
// after a few modifications:
//
// First, you'll need to add two new instructions:
//
// Opcode 3 takes a single integer as input and saves it to the position given by its only
// parameter. For example, the instruction 3,50 would take an input value and store it at
// address 50.
// Opcode 4 outputs the value of its only parameter. For example, the instruction 4,50 would
// output the value at address 50.
//
// Programs that use these instructions will come with documentation that explains what should be
// connected to the input and output. The program 3,0,4,0,99 outputs whatever it gets as input,
// then halts.
//
// Second, you'll need to add support for parameter modes:
//
// Each parameter of an instruction is handled based on its parameter mode. Right now, your ship
// computer already understands parameter mode 0, position mode, which causes the parameter to be
// interpreted as a position - if the parameter is 50, its value is the value stored at address
// 50 in memory. Until now, all parameters have been in position mode.
//
// Now, your ship computer will also need to handle parameters in mode 1, immediate mode. In
// immediate mode, a parameter is interpreted as a value - if the parameter is 50, its value is
// simply 50.
//
// Parameter modes are stored in the same value as the instruction's opcode. The opcode is a
// two-digit number based only on the ones and tens digit of the value, that is, the opcode is the
// rightmost two digits of the first value in an instruction. Parameter modes are single digits,
// one per parameter, read right-to-left from the opcode: the first parameter's mode is in the
// hundreds digit, the second parameter's mode is in the thousands digit, the third parameter's
// mode is in the ten-thousands digit, and so on. Any missing modes are 0.
//
// For example, consider the program 1002,4,3,4,33.
//
// The first instruction, 1002,4,3,4, is a multiply instruction - the rightmost two digits of the
// first value, 02, indicate opcode 2, multiplication. Then, going right to left, the parameter
// modes are 0 (hundreds digit), 1 (thousands digit), and 0 (ten-thousands digit, not present and
// therefore zero):
//
// ABCDE
// 1002
//
// DE - two-digit opcode, 02 == opcode 2
// C - mode of 1st parameter, 0 == position mode
// B - mode of 2nd parameter, 1 == immediate mode
// A - mode of 3rd parameter, 0 == position mode,
// omitted due to being a leading zero
//
// This instruction multiplies its first two parameters. The first parameter, 4 in position mode,
// works like it did before - its value is the value stored at address 4 (33). The second parameter,
// 3 in immediate mode, simply has value 3. The result of this operation, 33 * 3 = 99, is written
// according to the third parameter, 4 in position mode, which also works like it did before - 99
// is written to address 4.
//
// Parameters that an instruction writes to will never be in immediate mode.
//
// Finally, some notes:
//
// It is important to remember that the instruction pointer should increase by the number of
// values in the instruction after the instruction finishes. Because of the new instructions,
// this amount is no longer always 4.
// Integers can be negative: 1101,100,-1,4,0 is a valid program (find 100 + -1, store the
// result in position 4).
//
// The TEST diagnostic program will start by requesting from the user the ID of the system to test
// by running an input instruction - provide it 1, the ID for the ship's air conditioner unit.
//
// It will then perform a series of diagnostic tests confirming that various parts of the Intcode
// computer, like parameter modes, function correctly. For each test, it will run an output
// instruction indicating how far the result of the test was from the expected value, where 0 means
// the test was successful. Non-zero outputs mean that a function is not working correctly; check
// the instructions that were run before the output instruction to see which one failed.
//
// Finally, the program will output a diagnostic code and immediately halt. This final output isn't
// an error; an output followed immediately by a halt means the program finished. If all outputs
// were zero except the diagnostic code, the diagnostic program ran successfully.
//
// After providing 1 to the only input instruction and passing all the tests, what diagnostic code
// does the program produce?
const std = @import("std");
const id = 1;
fn U(n: isize) usize {
return @intCast(usize, n);
}
fn P(mem: []const isize, m: isize, ip: usize) isize {
return switch (m) {
0 => mem[U(mem[ip])],
1 => mem[ip],
else => unreachable,
};
}
pub fn main() void {
var ip: usize = 0;
var mem = input;
program: while (true) {
const op = @mod(mem[ip], 100);
const m1 = @mod(@divFloor(mem[ip], 100), 10);
const m2 = @mod(@divFloor(mem[ip], 1000), 10);
const m3 = @mod(@divFloor(mem[ip], 10000), 10);
switch (op) {
1 => {
const p1 = P(mem[0..], m1, ip + 1);
const p2 = P(mem[0..], m2, ip + 2);
mem[U(mem[ip + 3])] = p1 + p2;
ip += 4;
},
2 => {
const p1 = P(mem[0..], m1, ip + 1);
const p2 = P(mem[0..], m2, ip + 2);
mem[U(mem[ip + 3])] = p1 * p2;
ip += 4;
},
3 => {
mem[U(mem[ip + 1])] = id;
ip += 2;
},
4 => {
const p1 = P(mem[0..], m1, ip + 1);
std.debug.warn("{}", p1);
ip += 2;
},
99 => {
break :program;
},
else => {
unreachable;
},
}
}
}
const input = [_]isize{
3, 225, 1, 225, 6, 6, 1100, 1, 238, 225, 104, 0, 1102, 91,
92, 225, 1102, 85, 13, 225, 1, 47, 17, 224, 101, -176, 224, 224,
4, 224, 1002, 223, 8, 223, 1001, 224, 7, 224, 1, 223, 224, 223,
1102, 79, 43, 225, 1102, 91, 79, 225, 1101, 94, 61, 225, 1002, 99,
42, 224, 1001, 224, -1890, 224, 4, 224, 1002, 223, 8, 223, 1001, 224,
6, 224, 1, 224, 223, 223, 102, 77, 52, 224, 1001, 224, -4697, 224,
4, 224, 102, 8, 223, 223, 1001, 224, 7, 224, 1, 224, 223, 223,
1101, 45, 47, 225, 1001, 43, 93, 224, 1001, 224, -172, 224, 4, 224,
102, 8, 223, 223, 1001, 224, 1, 224, 1, 224, 223, 223, 1102, 53,
88, 225, 1101, 64, 75, 225, 2, 14, 129, 224, 101, -5888, 224, 224,
4, 224, 102, 8, 223, 223, 101, 6, 224, 224, 1, 223, 224, 223,
101, 60, 126, 224, 101, -148, 224, 224, 4, 224, 1002, 223, 8, 223,
1001, 224, 2, 224, 1, 224, 223, 223, 1102, 82, 56, 224, 1001, 224,
-4592, 224, 4, 224, 1002, 223, 8, 223, 101, 4, 224, 224, 1, 224,
223, 223, 1101, 22, 82, 224, 1001, 224, -104, 224, 4, 224, 1002, 223,
8, 223, 101, 4, 224, 224, 1, 223, 224, 223, 4, 223, 99, 0,
0, 0, 677, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1105, 0, 99999, 1105, 227, 247, 1105, 1, 99999, 1005, 227, 99999, 1005, 0,
256, 1105, 1, 99999, 1106, 227, 99999, 1106, 0, 265, 1105, 1, 99999, 1006,
0, 99999, 1006, 227, 274, 1105, 1, 99999, 1105, 1, 280, 1105, 1, 99999,
1, 225, 225, 225, 1101, 294, 0, 0, 105, 1, 0, 1105, 1, 99999,
1106, 0, 300, 1105, 1, 99999, 1, 225, 225, 225, 1101, 314, 0, 0,
106, 0, 0, 1105, 1, 99999, 8, 226, 677, 224, 102, 2, 223, 223,
1005, 224, 329, 1001, 223, 1, 223, 1007, 226, 226, 224, 1002, 223, 2,
223, 1006, 224, 344, 101, 1, 223, 223, 108, 226, 226, 224, 1002, 223,
2, 223, 1006, 224, 359, 1001, 223, 1, 223, 107, 226, 677, 224, 102,
2, 223, 223, 1006, 224, 374, 101, 1, 223, 223, 8, 677, 677, 224,
102, 2, 223, 223, 1006, 224, 389, 1001, 223, 1, 223, 1008, 226, 677,
224, 1002, 223, 2, 223, 1006, 224, 404, 101, 1, 223, 223, 7, 677,
677, 224, 1002, 223, 2, 223, 1005, 224, 419, 101, 1, 223, 223, 1108,
226, 677, 224, 1002, 223, 2, 223, 1005, 224, 434, 101, 1, 223, 223,
1108, 226, 226, 224, 102, 2, 223, 223, 1005, 224, 449, 1001, 223, 1,
223, 107, 226, 226, 224, 102, 2, 223, 223, 1005, 224, 464, 101, 1,
223, 223, 1007, 677, 677, 224, 102, 2, 223, 223, 1006, 224, 479, 101,
1, 223, 223, 1007, 226, 677, 224, 102, 2, 223, 223, 1005, 224, 494,
1001, 223, 1, 223, 1008, 226, 226, 224, 1002, 223, 2, 223, 1005, 224,
509, 1001, 223, 1, 223, 1108, 677, 226, 224, 1002, 223, 2, 223, 1006,
224, 524, 1001, 223, 1, 223, 108, 677, 677, 224, 1002, 223, 2, 223,
1005, 224, 539, 101, 1, 223, 223, 108, 226, 677, 224, 1002, 223, 2,
223, 1005, 224, 554, 101, 1, 223, 223, 1008, 677, 677, 224, 1002, 223,
2, 223, 1006, 224, 569, 1001, 223, 1, 223, 1107, 677, 677, 224, 102,
2, 223, 223, 1005, 224, 584, 1001, 223, 1, 223, 7, 677, 226, 224,
102, 2, 223, 223, 1005, 224, 599, 1001, 223, 1, 223, 8, 677, 226,
224, 1002, 223, 2, 223, 1005, 224, 614, 1001, 223, 1, 223, 7, 226,
677, 224, 1002, 223, 2, 223, 1006, 224, 629, 101, 1, 223, 223, 1107,
677, 226, 224, 1002, 223, 2, 223, 1005, 224, 644, 1001, 223, 1, 223,
1107, 226, 677, 224, 102, 2, 223, 223, 1006, 224, 659, 1001, 223, 1,
223, 107, 677, 677, 224, 1002, 223, 2, 223, 1005, 224, 674, 101, 1,
223, 223, 4, 223, 99, 226,
};
| https://raw.githubusercontent.com/tiehuis/advent-of-code-2019/07f48c42d0870a7030d21c08626fcc40a447e695/5_1.zig |
const std = @import("std");
const memory_size = 1 << 16;
const program_start = 0x3000;
const Reg = enum(u16) { R0 = 0, R1, R2, R3, R4, R5, R6, R7, PC, COND, COUNT };
const Op = enum(u16) { BR = 0, ADD, LD, ST, JSR, AND, LDR, STR, RTI, NOT, LDI, STI, JMP, RES, LEA, TRAP };
const Flags = enum(u16) {
POS = 1 << 0,
ZRO = 1 << 1,
NEG = 1 << 2,
};
const VM = struct {
memory: [memory_size]u16 = undefined,
reg: [@intFromEnum(Reg.COUNT)]u16 = undefined,
run: bool = false,
pub fn init() VM {
var vm = VM{};
vm.memory = [_]u16{0} ** memory_size;
vm.reg = [_]u16{0} ** @intFromEnum(Reg.COUNT);
vm.reg[@intFromEnum(Reg.PC)] = program_start;
vm.reg[@intFromEnum(Reg.COND)] = @intFromEnum(Flags.ZRO);
return vm;
}
pub fn start(self: *VM) void {
self.run = true;
// while (self.run) {
const program_counter = self.reg[@intFromEnum(Reg.PC)];
const instruction = self.memory[program_counter];
const op: Op = @enumFromInt(instruction >> 12);
switch (op) {
.ADD => self.op_add(instruction),
else => {},
}
self.reg[@intFromEnum(Reg.PC)] = self.reg[@intFromEnum(Reg.PC)] + 1;
// }
}
pub fn op_add(self: *VM, program_counter: u16) void {
_ = self;
_ = program_counter;
std.log.info("ADD", .{});
}
};
pub fn main() void {
var vm = VM.init();
vm.memory[program_start] = 0x1240;
vm.memory[program_start + 1] = 0;
std.log.info("PC: {}", .{vm.reg[@intFromEnum(Reg.PC)]});
vm.start();
std.log.info("PC: {}", .{vm.reg[@intFromEnum(Reg.PC)]});
vm.start();
}
| https://raw.githubusercontent.com/unbalancedparentheses/lc3-vm.zig/9de025f029e546251d0611cb750f094c33706ce7/lc3.zig |
const std = @import("std");
const Card = struct {
nr: i9,
winning_nrs: [10]i8,
nrs: [25]i8,
};
fn parseNrStr(comptime T: type, buf: []const u8) !T {
var str = std.mem.trim(u8, buf, " ");
var it = std.mem.split(u8, str, " ");
var nrs: T = undefined;
var i: usize = 0;
while (it.next()) |nr_str| {
if (std.mem.eql(u8, nr_str, "")) continue;
nrs[i] = try std.fmt.parseInt(i8, nr_str, 10);
i += 1;
}
return nrs;
}
pub fn main() !void {
var input = try std.fs.cwd().openFile("input.txt", .{});
defer input.close();
var in_reader = std.io.bufferedReader(input.reader());
var in_stream = in_reader.reader();
var buf: [1024]u8 = undefined;
var total_points: usize = 0;
while (try in_stream.readUntilDelimiterOrEof(&buf, '\n')) |line| {
var it = std.mem.split(u8, line, ":");
var prefix = it.next().?;
var suffix = it.next().?;
prefix = std.mem.trimLeft(u8, prefix, "Card ");
var nr = try std.fmt.parseInt(i9, prefix, 10);
it = std.mem.split(u8, suffix, "|");
var winning_nrs = try parseNrStr([10]i8, it.next().?);
var nrs = try parseNrStr([25]i8, it.next().?);
var card = Card{
.nr = nr,
.winning_nrs = winning_nrs,
.nrs = nrs,
};
var found_nrs: usize = 0;
for (card.nrs) |card_nr| {
var is_found = false;
for (card.winning_nrs) |winning_nr| {
if (card_nr == winning_nr) is_found = true;
}
if (is_found) found_nrs += 1;
}
var points: usize = 0;
if (found_nrs > 0) {
points = std.math.pow(usize, 2, found_nrs - 1);
}
total_points += points;
}
std.debug.print("{}\n", .{total_points});
}
| https://raw.githubusercontent.com/froehlichA/aoc2023/2335f02043a267aed2d0e35c4fc6871b08a6dac5/04/1.zig |
const std = @import("std");
const data = @embedFile("input.txt");
fn readFirstNumber(
line: []const u8,
start_index: *usize,
end_index_exclusive: *usize,
) !?u32 {
var i = end_index_exclusive.*;
while (line.len > i and !std.ascii.isDigit(line[i])) {
i += 1;
}
if (line.len <= i) {
end_index_exclusive.* = i;
return null;
}
var j = i;
while (line.len > i and std.ascii.isDigit(line[j])) {
j += 1;
}
start_index.* = i;
end_index_exclusive.* = j;
return try std.fmt.parseInt(u32, line[i..j], 10);
}
fn handleAround(around: [3]?[]const u8, sum: *u32) !void {
if (around[1]) |center| {
var i: usize = 0;
var j: usize = 0;
while (try readFirstNumber(center, &i, &j)) |num| {
const lower_bound: usize =
@intCast(@max(0, @as(isize, @intCast(i)) - 1));
const upper_bound = @min(center.len - 1, j + 1);
var success = false;
for (around) |single_arround| {
if (single_arround) |single_arround_not_null| {
for (lower_bound..upper_bound) |index| {
const c = single_arround_not_null[index];
if (!std.ascii.isDigit(c) and c != '.') {
success = true;
break;
}
}
}
if (success) {
break;
}
}
if (success) {
sum.* += num;
}
}
}
}
pub fn main() !void {
var lines = std.mem.tokenizeScalar(u8, data, '\n');
var sum: u64 = 0;
while (lines.next()) |line| {
var colon = false;
var pipe = false;
var num_start: ?usize = null;
const allocator = std.heap.page_allocator;
var winning_list = std.ArrayList(u8).init(allocator);
defer winning_list.deinit();
var winning_count: usize = 0;
for (line, 0..) |c, idx| {
if (!colon) {
if (c == ':') {
colon = true;
}
continue;
}
if (c == ' ') {
if (num_start) |num_start_nn| {
const num = try std.fmt.parseInt(
u8,
line[num_start_nn..idx],
10,
);
num_start = null;
if (!pipe) {
try winning_list.append(num);
} else {
for (winning_list.items) |winning| {
if (num == winning) {
winning_count += 1;
break;
}
}
}
}
continue;
}
if (c == '|') {
pipe = true;
continue;
}
if (std.ascii.isDigit(c) and num_start == null) {
num_start = idx;
}
}
if (num_start) |num_start_nn| {
const num = try std.fmt.parseInt(
u8,
line[num_start_nn .. line.len - 1],
10,
);
for (winning_list.items) |winning| {
if (num == winning) {
winning_count += 1;
break;
}
}
}
if (winning_count > 0) {
sum += std.math.pow(usize, 2, winning_count - 1);
}
}
std.debug.print("{}\n", .{sum});
}
| https://raw.githubusercontent.com/kkard2/aoc2023/6ec8e32bd8b1bc411c37748d1c2659a3b6ffec3d/04/a.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const VEC_SIZE_F32 = std.simd.suggestVectorSize(f32) orelse 4;
// XXX: Because of the limitation of build system in zig v0.11, we cannot
// switch between `tracy_full` and `tracy_stub` by passing compilation flags.
// So we have to do this kind of "conditional import". See also section
// "conditional compilation" in "docs/ISSUES.md".
const use_tracy = @import("build_options").use_tracy;
const ztracy = if (use_tracy) @import("ztracy");
const tracy_wrapper_stub = struct {
pub inline fn startZone(
_: std.builtin.SourceLocation,
_: [*:0]const u8,
_: u64,
) void {}
pub inline fn endZone(_: *const anyopaque) void {}
};
const tracy_wrapper_full = struct {
pub inline fn startZone(
src_loc: std.builtin.SourceLocation,
name: [*:0]const u8,
color: u64,
) ztracy.ZoneCtx {
const zone = if (use_tracy) ztracy.ZoneNC(src_loc, name, color);
return zone;
}
pub inline fn endZone(zone: *const anyopaque) void {
if (use_tracy) @as(*ztracy.ZoneCtx, @constCast(@alignCast(@ptrCast(zone)))).End();
}
};
const TracyWrapper = if (use_tracy) tracy_wrapper_full else tracy_wrapper_stub;
// Helper function for development
fn printStruct(s: anytype) void {
inline for (std.meta.fields(@TypeOf(s))) |f| {
std.debug.print(f.name ++ ": {any}\n", .{@as(f.type, @field(s, f.name))});
}
}
// For model exported by `legacy_export()` (v0)
// NOTE: We should use `extern struct` as it supports guaranteed layout.
// Otherwise, `std.io.Reader.readStruct()` would fail.
pub const Config = extern struct {
dim: i32, // transformer dimension (model.params.dim)
hidden_dim: i32,
n_layers: i32,
n_heads: i32,
n_kv_heads: i32,
vocab_size: i32,
seq_len: i32,
};
pub const TransformerWeights = struct {
token_embedding_table: [*]f32, // (vocab_size, dim)
rms_att_weight: [*]f32, // (layer, dim)
rms_ffn_weight: [*]f32, // (layer, dim)
// weights for matmuls. note dim == n_heads * head_size
wq: [*]f32, // (layer, dim, n_heads * head_size)
wk: [*]f32, // (layer, dim, n_kv_heads * head_size)
wv: [*]f32, // (layer, dim, n_kv_heads * head_size)
wo: [*]f32, // (layer, n_heads * head_size, dim)
// weights for ffn
w1: [*]f32, // (layer, hidden_dim, dim)
w2: [*]f32, // (layer, dim, hidden_dim)
w3: [*]f32, // (layer, hidden_dim, dim)
// final rmsnorm
rms_final_weight: [*]f32, // (dim,)
// (optional) classifier weights for the logits, on the last layer
wcls: [*]f32,
// NOTE: Here we follow the way to mmap weights in `llama2.c/runq.c` by
// taking `*anyopaque` without presuming all weights are f32.
pub fn init(p: *Config, weights_ptr: *anyopaque, shared_weights: bool) TransformerWeights {
var w: TransformerWeights = undefined;
// NOTE: cast i32 to usize to avoid overflow for 13B+ models.
const dim: usize = @intCast(p.dim);
const hidden_dim: usize = @intCast(p.hidden_dim);
const n_layers: usize = @intCast(p.n_layers);
const n_heads: usize = @intCast(p.n_heads);
const n_kv_heads: usize = @intCast(p.n_kv_heads);
const vocab_size: usize = @intCast(p.vocab_size);
const seq_len: usize = @intCast(p.seq_len);
const head_size: usize = dim / n_heads;
var ptr: [*]f32 = @alignCast(@ptrCast(weights_ptr));
w.token_embedding_table = ptr;
ptr += vocab_size * dim;
w.rms_att_weight = ptr;
ptr += n_layers * dim;
w.wq = ptr;
ptr += n_layers * dim * (n_heads * head_size);
w.wk = ptr;
ptr += n_layers * dim * (n_kv_heads * head_size);
w.wv = ptr;
ptr += n_layers * dim * (n_kv_heads * head_size);
w.wo = ptr;
ptr += n_layers * (n_heads * head_size) * dim;
w.rms_ffn_weight = ptr;
ptr += n_layers * dim;
w.w1 = ptr;
ptr += n_layers * dim * hidden_dim;
w.w2 = ptr;
ptr += n_layers * hidden_dim * dim;
w.w3 = ptr;
ptr += n_layers * dim * hidden_dim;
w.rms_final_weight = ptr;
ptr += dim;
ptr += seq_len * head_size / 2; // skip what used to be freq_cis_real (for RoPE)
ptr += seq_len * head_size / 2; // skip what used to be freq_cis_imag (for RoPE)
w.wcls = if (shared_weights) w.token_embedding_table else ptr;
return w;
}
};
const RunState = struct {
x: []f32, // activation at current time stamp (dim,)
xb: []f32,
xb2: []f32,
hb: []f32, // buffer for hidden dimension in the ffn (hidden_dim,)
hb2: []f32,
q: []f32, // query (dim,)
// NOTE: we don't need to allocate memory for k, v as we can point them to
// kv caches.
// https://github.com/karpathy/llama2.c/blob/b3c4b6c/run.c#L255-L257
// https://github.com/karpathy/llama2.c/pull/400
k: []f32 = undefined, // key (dim,)
v: []f32 = undefined, // value (dim,)
att: []f32, // buffer for scores/attention values (n_heads, seq_len)
logits: []f32, // output logits, distribution of vocabulary (vocab_size)
key_cache: []f32, // (layer, seq_len, dim)
value_cache: []f32, // (layer, seq_len, dim)
pub fn init(p: *const Config, allocator: Allocator) !RunState {
const dim: usize = @intCast(p.dim);
const hidden_dim: usize = @intCast(p.hidden_dim);
const n_layers: usize = @intCast(p.n_layers);
const n_heads: usize = @intCast(p.n_heads);
const n_kv_heads: usize = @intCast(p.n_kv_heads);
const vocab_size: usize = @intCast(p.vocab_size);
const seq_len: usize = @intCast(p.seq_len);
const kv_dim: usize = (dim * n_kv_heads) / n_heads;
// TODO: consider alignment for SIMD?
// https://github.com/cgbur/llama2.zig/blob/main/src/main.zig#L140C32-L152
return RunState{
.x = try allocator.alloc(f32, dim),
.xb = try allocator.alloc(f32, dim),
.xb2 = try allocator.alloc(f32, dim),
.hb = try allocator.alloc(f32, hidden_dim),
.hb2 = try allocator.alloc(f32, hidden_dim),
.q = try allocator.alloc(f32, dim),
.key_cache = try allocator.alloc(f32, n_layers * seq_len * kv_dim),
.value_cache = try allocator.alloc(f32, n_layers * seq_len * kv_dim),
.att = try allocator.alloc(f32, n_heads * seq_len),
.logits = try allocator.alloc(f32, vocab_size),
};
}
pub fn deinit(self: RunState, allocator: Allocator) void {
allocator.free(self.x);
allocator.free(self.xb);
allocator.free(self.xb2);
allocator.free(self.hb);
allocator.free(self.hb2);
allocator.free(self.q);
allocator.free(self.key_cache);
allocator.free(self.value_cache);
allocator.free(self.att);
allocator.free(self.logits);
}
};
// ----------------------------------------------------------------------
pub const Transformer = struct {
config: Config = undefined,
weights: TransformerWeights = undefined,
state: RunState = undefined,
// XXX: In llama2.c, `fd` was kept to be closed manually while program is
// about to exit, but we can actually close it right after mmap is done.
fd: std.fs.File = undefined,
data: *anyopaque = undefined,
file_size: u64 = undefined,
pub fn forward(self: *Transformer, token: u32, pos: u32) []f32 {
const p = self.config;
const w = self.weights;
var s = self.state;
var x = s.x;
const dim: usize = @intCast(p.dim);
const hidden_dim: usize = @intCast(p.hidden_dim);
const n_layers: usize = @intCast(p.n_layers);
const n_heads: usize = @intCast(p.n_heads);
const n_kv_heads: usize = @intCast(p.n_kv_heads);
const vocab_size: usize = @intCast(p.vocab_size);
const seq_len: usize = @intCast(p.seq_len);
const kv_dim: usize = (dim * n_kv_heads) / n_heads;
const kv_mul: usize = n_heads / n_kv_heads; // integer multiplier of the kv sharing in multiquery
const head_size: usize = dim / n_heads;
const content_row = w.token_embedding_table[(dim * token)..(dim * (token + 1))];
@memcpy(x, content_row);
// forward all the layers
for (0..n_layers) |l| {
// attention rmsnorm
rmsnorm(s.xb, x, w.rms_att_weight[l * dim .. (l + 1) * dim]);
// key and value point to the kv cache
const loff = l * seq_len * kv_dim;
s.k = s.key_cache[(loff + pos * kv_dim)..(loff + (pos + 1) * kv_dim)];
s.v = s.value_cache[(loff + pos * kv_dim)..(loff + (pos + 1) * kv_dim)];
// op: `xq, xk, xv = self.wq(x), self.wk(x), self.wv(x)`
// src: Attention.forward()
matmul(s.q, s.xb, w.wq[l * dim * dim .. (l + 1) * dim * dim], dim, dim);
matmul(s.k, s.xb, w.wk[l * dim * kv_dim .. (l + 1) * dim * kv_dim], dim, kv_dim);
matmul(s.v, s.xb, w.wv[l * dim * kv_dim .. (l + 1) * dim * kv_dim], dim, kv_dim);
// RoPE relative positional encoding
var j: usize = 0;
while (j < dim) : (j += 2) {
const head_dim: f32 = @floatFromInt(j % head_size);
const freq: f32 = 1.0 / std.math.pow(f32, 10000.0, head_dim / @as(f32, @floatFromInt(head_size)));
const val: f32 = @as(f32, @floatFromInt(pos)) * freq;
const fcr = std.math.cos(val);
const fci = std.math.sin(val);
const rotn: usize = if (j < kv_dim) 2 else 1; // how many vectors? 2 = q & k, 1 = q only
for (0..rotn) |v| {
const vec = if (v == 0) s.q else s.k;
const v0 = vec[j];
const v1 = vec[j + 1];
vec[j] = v0 * fcr - v1 * fci;
vec[j + 1] = v0 * fci + v1 * fcr;
}
}
// multihead attention. iterate over all heads
for (0..n_heads) |h| {
// get the query vector for this head
const q = s.q[h * head_size .. (h + 1) * head_size];
// attention scores for this head
const att = s.att[h * seq_len .. (h + 1) * seq_len];
// iterate over all timesteps, including the current one
for (0..pos + 1) |t| {
const il: usize = loff + t * kv_dim + (h / kv_mul) * head_size;
const ir = il + head_size;
const k = s.key_cache[il..ir];
var score: f32 = 0.0;
for (0..head_size) |i| {
score += q[i] * k[i];
}
score /= std.math.sqrt(@as(f32, @floatFromInt(head_size)));
att[t] = score;
}
// softmax the scores to get attention weights, from 0..pos inclusively
// NOTE: in `Attention.forward()::model.py`, this works with a mask of
// upper triangular matrix filling with -inf.
softmax(att[0 .. pos + 1]);
// weighted sum of the values, store back into xb
var xb = s.xb[h * head_size .. (h + 1) * head_size];
@memset(xb, 0.0);
for (0..pos + 1) |t| {
const il: usize = loff + t * kv_dim + (h / kv_mul) * head_size;
const ir = il + head_size;
const v = s.value_cache[il..ir];
const a = att[t];
for (0..head_size) |i| {
xb[i] += a * v[i];
}
}
}
// final matmul to get the output of the attention
// op: `output = self.wo(output)`
// src: Attention.forward()
matmul(s.xb2, s.xb, w.wo[l * dim * dim .. (l + 1) * dim * dim], dim, dim);
// residual connection back into x
// op: `h = x + self.attention.forward(...)`
// src: TransformerBlock.forward()
for (0..dim) |i| {
x[i] += s.xb2[i];
}
// ffn rmsnorm
rmsnorm(s.xb, x, w.rms_ffn_weight[l * dim .. (l + 1) * dim]);
// Now for FFN in PyTorch we have: self.w2(F.silu(self.w1(x)) * self.w3(x))
matmul(s.hb, s.xb, w.w1[l * dim * hidden_dim .. (l + 1) * dim * hidden_dim], dim, hidden_dim);
matmul(s.hb2, s.xb, w.w3[l * dim * hidden_dim .. (l + 1) * dim * hidden_dim], dim, hidden_dim);
// SwiGLU non-linearity
for (0..hidden_dim) |i| {
var val: f32 = s.hb[i];
// silu(x)=x*Ο(x), where Ο(x) is the logistic sigmoid
val *= (1.0 / (1.0 + std.math.exp(-val)));
// elementwise multiply with w3(x)
val *= s.hb2[i];
s.hb[i] = val;
}
// final matmul to get the output of the ffn
matmul(s.xb, s.hb, w.w2[l * dim * hidden_dim .. (l + 1) * dim * hidden_dim], hidden_dim, dim);
// residual connection
for (0..dim) |i| {
x[i] += s.xb[i];
}
}
// final rmsnorm
rmsnorm(x, x, w.rms_final_weight[0..dim]);
// classifier into logits
matmul(s.logits, x, w.wcls[0 .. dim * vocab_size], dim, vocab_size);
return s.logits;
}
};
pub fn rmsnorm(o: []f32, x: []f32, weight: []f32) void {
assert(o.len == x.len);
assert(o.len == weight.len);
const size = o.len;
var ss: f32 = 0.0;
// calculate sum of sqaures
for (0..size) |j| {
ss += x[j] * x[j];
}
ss /= @as(f32, @floatFromInt(size));
ss += 1e-5;
ss = 1.0 / std.math.sqrt(ss);
// normalize and scale
for (0..size) |j| {
o[j] = weight[j] * (ss * x[j]);
}
}
pub fn softmax(x: []f32) void {
const size = x.len;
// find max value (for numerical stability)
var max_val = x[0];
for (1..size) |i| {
if (x[i] > max_val) {
max_val = x[i];
}
}
// exp and sum
var sum: f32 = 0.0;
for (0..size) |i| {
x[i] = std.math.exp(x[i] - max_val);
sum += x[i];
}
// normalize
for (0..size) |i| {
x[i] /= sum;
}
}
/// Matrix multiplication: W (d,n) @ x (n,) -> xout (d,)
pub fn matmul(xout: []f32, x: []f32, w: []f32, n: usize, d: usize) void {
const zone = TracyWrapper.startZone(@src(), "matmul", 0x00_00_ff_00);
defer TracyWrapper.endZone(&zone);
// matmul_naive(xout, x, w, n, d);
matmul_simd(xout, x, w, n, d);
}
fn matmul_naive(xout: []f32, x: []f32, w: []f32, n: usize, d: usize) void {
for (0..d) |i| {
var val: f32 = 0.0;
for (0..n) |j| {
val += w[i * n + j] * x[j];
}
xout[i] = val;
}
}
fn matmul_simd(xout: []f32, x: []f32, w: []f32, n: usize, d: usize) void {
const vec_sz = VEC_SIZE_F32;
const n_vec: usize = n / vec_sz;
const n_rem: usize = n % vec_sz;
for (0..d) |i| {
var val: f32 = 0.0;
const offset: usize = i * n;
var vsum: @Vector(vec_sz, f32) = @splat(0.0);
for (0..n_vec) |nv| {
// NOTE: SIMD vector requires a known size at compile time, so we
// need to access slice like this.
const vx: @Vector(vec_sz, f32) = x[nv * vec_sz ..][0..vec_sz].*;
const vw: @Vector(vec_sz, f32) = w[offset + nv * vec_sz ..][0..vec_sz].*;
vsum += vx * vw;
}
val = @reduce(.Add, vsum);
// Process remaining elements
const offset2: usize = vec_sz * n_vec;
for (0..n_rem) |j| {
val += w[offset + offset2 + j] * x[offset2 + j];
}
xout[i] = val;
}
}
/// Read checkpoint and initialize transformer. Note that user is responsible to
/// call `freeTransformer()` to delete the memory mapping.
pub fn readCheckpoint(
checkpoint: []const u8,
transformer: *Transformer,
use_mmap: bool,
allocator: Allocator,
) !void {
const file = try std.fs.cwd().openFile(checkpoint, .{ .mode = .read_only });
// NOTE: we can close file after `mmap()` call has returned
defer file.close();
var config: *Config = &transformer.config;
config.* = try file.reader().readStruct(Config);
// XXX: (llama2.c) negative vocab size -> unshared weights
const shared_weights: bool = config.vocab_size > 0;
config.vocab_size = try std.math.absInt(config.vocab_size);
transformer.file_size = (try file.stat()).size;
// Reposition to the head of file. Offset of `Config` will be handled later.
try file.seekTo(0);
var data: []align(std.mem.page_size) u8 = undefined;
if (use_mmap) {
data = try std.os.mmap(
null,
transformer.file_size,
std.os.PROT.READ,
std.os.MAP.PRIVATE,
file.handle,
0,
);
} else {
data = blk: {
const buffer = try allocator.alignedAlloc(u8, std.mem.page_size, transformer.file_size);
const read_len = try file.readAll(buffer);
if (read_len != transformer.file_size) {
std.debug.print("error: failed to read checkpoint file\n", .{});
return std.os.ReadError.OperationAborted;
}
break :blk buffer;
};
}
transformer.data = @ptrCast(data);
// View `data` as `void*` from C perspective (`*anyopaque` in zig)
var weights_ptr: *anyopaque = @ptrCast(data);
// View `weights_ptr` in byte (u8), and offset it with the size of `Config`.
// So that we don't need to assume all fields in `Config` are the same type.
weights_ptr = @as([*]u8, @ptrCast(weights_ptr)) + @sizeOf(Config);
transformer.weights = TransformerWeights.init(config, weights_ptr, shared_weights);
}
fn buildTransformer(
transformer: *Transformer,
checkpoint_path: []const u8,
use_mmap: bool,
allocator: Allocator,
) !void {
try readCheckpoint(checkpoint_path, transformer, use_mmap, allocator);
transformer.state = try RunState.init(&transformer.config, allocator);
}
fn freeTransformer(transformer: *Transformer, use_mmap: bool, allocator: Allocator) void {
// Cast pointer of mmap data from `*anyopaque` to the original output type
// `[]align(std.mem.page_size) u8`.
const data = @as(
[*]align(std.mem.page_size) u8,
@alignCast(@ptrCast(transformer.data)),
)[0..transformer.file_size];
if (use_mmap) {
// Delete memory mapping
std.os.munmap(data);
} else {
allocator.free(data);
}
transformer.state.deinit(allocator);
}
// ----------------------------------------------------------------------
pub const TokenIndex = struct {
str: []const u8,
id: u32,
/// Comparator. True: a < b.
pub fn desc(_: void, a: TokenIndex, b: TokenIndex) bool {
return strcmp(a.str, b.str) < 0;
}
};
pub const Tokenizer = struct {
vocab: [][]u8 = undefined,
vocab_scores: []f32 = undefined,
sorted_vocab: ?[]TokenIndex = null,
vocab_size: i32 = undefined,
max_token_length: u32 = undefined,
byte_pieces: [256]u8 = undefined, // stores all single-byte strings
pub fn init(tokenizer_path: []const u8, vocab_size: i32, allocator: Allocator) !Tokenizer {
var t = Tokenizer{};
// NOTE: vocab_size might be written into tokenizer file in the future,
// then we could change this accordingly.
t.vocab_size = vocab_size;
const n_vocab: usize = @intCast(vocab_size);
t.vocab = try allocator.alloc([]u8, n_vocab);
t.vocab_scores = try allocator.alloc(f32, n_vocab);
// NOTE: every element in `byte_pieces` will be used as a slice with
// length 1, so that we don't need to append a null terminator to it.
for (0..256) |i| {
t.byte_pieces[i] = @intCast(i);
}
const file = try std.fs.cwd().openFile(tokenizer_path, .{ .mode = .read_only });
defer file.close();
var buf_x32: [4]u8 = undefined;
var buffered_file = std.io.bufferedReader(file.reader());
// number of bytes read
var nb_read = try buffered_file.read(&buf_x32);
if (nb_read != 4) {
std.debug.print("failed read\n", .{});
return std.fs.File.ReadError.Unexpected;
}
t.max_token_length = std.mem.readIntSliceLittle(u32, &buf_x32);
// read tokens, lengths of tokens, and scores
var len: i32 = undefined;
for (0..n_vocab) |i| {
// score
nb_read = try buffered_file.read(&buf_x32);
if (nb_read != 4) {
std.debug.print("failed read\n", .{});
return std.fs.File.ReadError.Unexpected;
}
t.vocab_scores[i] = @bitCast(buf_x32);
// length of token
nb_read = try buffered_file.read(&buf_x32);
if (nb_read != 4) {
std.debug.print("failed read\n", .{});
return std.fs.File.ReadError.Unexpected;
}
len = @bitCast(buf_x32);
// token
// NOTE: here we make use of zig's slice since it contains length
// information of a sequence, so we don't need to append a sentinel
// ('\x00') to the end of a string. However, if we do need it, we
// can call `allocator.allocSentinel()` to allocate a buffer which
// ends with a sentinel while the sentinel char is not counted into
// `buffer.len` (this is useful for reading data in zig style since
// the number of bytes to read is determined by length of the buffer).
t.vocab[i] = try allocator.alloc(u8, @intCast(len));
nb_read = try buffered_file.read(t.vocab[i]);
if (nb_read != len) {
std.debug.print("failed read\n", .{});
return std.fs.File.ReadError.Unexpected;
}
}
return t;
}
pub fn deinit(self: Tokenizer, allocator: Allocator) void {
for (0..self.vocab.len) |i| {
allocator.free(self.vocab[i]);
}
allocator.free(self.vocab);
allocator.free(self.vocab_scores);
if (self.sorted_vocab != null) {
allocator.free(self.sorted_vocab.?);
}
}
pub fn strLookup(self: Tokenizer, str: []const u8) ?u32 {
const tok = TokenIndex{ .str = str, .id = undefined };
// NOTE: `bsearch` in C returns a pointer, this returns an index.
const res = std.sort.binarySearch(TokenIndex, tok, self.sorted_vocab.?, {}, compareToken);
const idx = res orelse return null;
const tok_id = self.sorted_vocab.?[idx].id;
return tok_id;
}
pub fn encode(
self: *Tokenizer,
text: []const u8,
bos: bool,
eos: bool,
tokens: []u32,
allocator: Allocator,
) !u32 {
// XXX: we need to update member in Tokenizer here, that's why the first
// parameter of this function should be a pointer. (not sure what's the
// conventional way to do this)
if (self.sorted_vocab == null) {
// lazily initialize the vocabulary
const n_vocab: usize = @intCast(self.vocab_size);
self.sorted_vocab = try allocator.alloc(TokenIndex, n_vocab);
for (0..n_vocab) |i| {
self.sorted_vocab.?[i] = TokenIndex{
.str = self.vocab[i],
.id = @intCast(i),
};
}
// sort vocab
std.sort.pdq(TokenIndex, self.sorted_vocab.?, {}, TokenIndex.desc);
}
// (llama2.c) Temporary buffer to store merge candidates of always two
// consecutive tokens. *2 for concat, +1 for null terminator, +2 for
// UTF8 (in case max_token_length is 1).
var str_buffer = try allocator.alloc(u8, self.max_token_length * 2 + 1 + 2);
defer allocator.free(str_buffer);
var str_len: usize = 0;
var n_tokens: u32 = 0; // retval
if (bos) {
tokens[n_tokens] = 1;
n_tokens += 1;
}
// add dummy prefix
// TODO: need to read through source code of sentencepice to figure out
// how it work properly.
if (text.len != 0) {
const dummy_prefix = self.strLookup(" ").?;
tokens[n_tokens] = dummy_prefix;
n_tokens += 1;
}
// process the raw (UTF-8) byte sequence of the input string
for (0..text.len) |i| {
const c = text[i];
// Check whether the highest 2 bits are 10 (0b10xxxxxx)
// mask: 0xC0 (0b11000000)
if ((c & 0xC0) != 0x80) {
str_len = 0;
}
str_buffer[str_len] = c;
str_len += 1;
// NOTE: we don't need to set the last byte to null everytime here,
// check out the comment related to `strLookup` below.
// str_buffer[str_len] = '\x00';
// NOTE: we will peek the next byte in text, so we need to make
// sure the index won't exceed the length of it. (in llama2.c, this
// loop checks with null terminator, so it doesn't need to do so)
if ((i + 1) < text.len and (text[i + 1] & 0xC0) == 0x80 and str_len < 4) {
continue;
}
// NOTE: (IMPORTANT!) since our implementation of `strcmp` checks
// with length of string instead of the null terminator, we need to
// pass a `slice` instead of the whole buffer to search.
const lookup_result = self.strLookup(str_buffer[0..str_len]);
if (lookup_result != null) {
tokens[n_tokens] = lookup_result.?;
n_tokens += 1;
} else {
// fallback: encode each byte literally
for (0..str_len) |j| {
// +3: offset for the first 3 vocabs (<unk>, <s>, </s>)
tokens[n_tokens] = str_buffer[j] + 3;
n_tokens += 1;
}
}
str_len = 0;
}
while (true) {
var best_score: f32 = -std.math.inf(f32);
var best_id: ?u32 = null;
var best_idx: ?usize = null;
for (0..(n_tokens - 1)) |i| {
const token1 = self.vocab[tokens[i]];
const token2 = self.vocab[tokens[i + 1]];
_ = try std.fmt.bufPrint(str_buffer, "{s}{s}", .{ token1, token2 });
var len = token1.len + token2.len;
const lookup_result = self.strLookup(str_buffer[0..len]);
if (lookup_result != null and self.vocab_scores[lookup_result.?] > best_score) {
const id = lookup_result.?;
best_score = self.vocab_scores[id];
best_id = id;
best_idx = i;
}
}
if (best_idx == null) {
break; // cannot find any more pairs to merge, so quit this loop
}
// merge the consecutive pair (best_idx, best_idx+1) into new token best_id
tokens[best_idx.?] = best_id.?;
// delete token at position best_idx+1, shift the entire sequence back 1
for ((best_idx.? + 1)..(n_tokens - 1)) |i| {
tokens[i] = tokens[i + 1];
}
n_tokens -= 1;
}
if (eos) {
tokens[n_tokens] = 2;
n_tokens += 1;
}
return n_tokens;
}
// XXX: if `self` is not specified as a pointer here, the returned value
// would be gibberish.
pub fn decode(self: *Tokenizer, prev_token: u32, token: u32) []u8 {
var piece: []u8 = self.vocab[token];
// NOTE: (llama2.c) following BOS token, sentencepiece decoder strips
// any leading whitespace.
if (prev_token == 1 and piece[0] == ' ') {
piece = piece[1..];
}
// In llama2.c, `piece` is checked with pattern "<0x%02hhX>", and it
// can be breakdown into:
// - "<0x": literally matching these characters
// - "%02hhX": matching a 2-digit number
// - "02": 2-digit number, padding with 0 if necessary
// - "hh": these 2-digit number are 2-byte variable
// - "X": interprete this 2-digit number as a hexadecimal number
// - ">": literally matching it
if (piece.len == 6 and piece[0] == '<' and piece[5] == '>') {
const byte_val: u8 = std.fmt.parseUnsigned(u8, piece[1..5], 0) catch |err| switch (err) {
else => {
std.log.err("Failed to parse token, id: {d}\n", .{token});
return piece;
},
};
// NOTE: type coercion explanation (`...` denotes the former item)
// 1. `self.byte_pieces[byte_val]`: u8
// 2. `&...`: *u8 (a single-item pointer to u8)
// 3. `@as(*[1]u8, ...)`: *[1]u8 (a pointer to a u8 array with length 1)
// 4. `piece = ...`: []u8 (a slice of u8)
//
// In 3., if we try to directly cast type to `[]u8`, compiler will
// complain "error: expected type '[]u8', found '*u8'", because
// compiler doesn't know the length of it.
// In 4., it works because slice is a fat pointer (ptr + len), and
// `*[1]u8` is a pointer with length info, so type coercion is valid.
piece = @as(*[1]u8, &self.byte_pieces[byte_val]);
}
return piece;
}
};
/// Compare strings like how `strcmp` works in C. Note that this implementation
/// does not rely on null terminator, but it relies on how `slice` works in zig
/// as it provides length infomation of a sequence.
pub fn strcmp(a: []const u8, b: []const u8) i32 {
var i: usize = 0;
while (i < a.len and i < b.len) {
if (a[i] != b[i]) {
return @as(i32, a[i]) - @as(i32, b[i]);
}
i += 1;
}
// Now, we ran out of characters from either a or b. So we just need to
// check with the lengths of them.
const len_a: i32 = @intCast(a.len);
const len_b: i32 = @intCast(b.len);
return len_a - len_b;
}
/// Compare 2 `TokenIndex`s and return `math.Order`.
pub fn compareToken(context: void, a: TokenIndex, b: TokenIndex) std.math.Order {
_ = context;
const res = strcmp(a.str, b.str);
if (res < 0) {
return std.math.Order.lt;
} else if (res == 0) {
return std.math.Order.eq;
} else {
return std.math.Order.gt;
}
}
pub fn safePrint(piece: []const u8) void {
if (piece.len == 1) {
if (piece[0] == '\x00') return;
const byte_val: u8 = piece[0];
if (!(std.ascii.isPrint(byte_val) or std.ascii.isWhitespace(byte_val))) {
std.log.warn("Found non-printable input, len: {d}\n", .{piece.len});
return;
}
}
std.debug.print("{s}", .{piece});
}
pub fn buildTokenizer(
t: *Tokenizer,
tokenizer_path: []const u8,
vocab_size: i32,
allocator: Allocator,
) !void {
t.* = try Tokenizer.init(tokenizer_path, vocab_size, allocator);
}
pub fn freeTokenizer(tokenizer: *Tokenizer, allocator: Allocator) void {
tokenizer.deinit(allocator);
}
// ----------------------------------------------------------------------
pub const ProbIndex = struct {
prob: f32,
index: usize,
/// Comparator. True: a > b.
pub fn asc(_: void, a: ProbIndex, b: ProbIndex) bool {
return a.prob > b.prob;
}
};
pub const Sampler = struct {
vocab_size: i32,
probindex: []ProbIndex,
temperature: f32,
topp: f32,
rng_state: u64,
pub fn init(
vocab_size: i32,
temperature: f32,
topp: f32,
rng_seed: u64,
allocator: Allocator,
) !Sampler {
const n_vocab: usize = @intCast(vocab_size);
return Sampler{
.vocab_size = vocab_size,
.temperature = temperature,
.topp = topp,
.rng_state = rng_seed,
.probindex = try allocator.alloc(ProbIndex, n_vocab),
};
}
pub fn deinit(self: Sampler, allocator: Allocator) void {
allocator.free(self.probindex);
}
pub fn sample(self: *Sampler, logits: []f32) u32 {
// sample the token given the logits and some hyperparameters
var next: usize = 0;
if (self.temperature == 0.0) {
// greedy argmax sampling: take the token with the highest probability
next = sampleArgmax(logits);
} else {
// apply the temperature to the logits
const n_vocab: usize = @intCast(self.vocab_size);
for (0..n_vocab) |q| {
logits[q] /= self.temperature;
}
// apply softmax to the logits to get the probabilities for next token
softmax(logits);
// flip a (float) coin (this is our source of entropy for sampling)
const coin = randomF32(&self.rng_state);
// we sample from this distribution to get the next token
if (self.topp <= 0 or self.topp >= 1) {
// simply sample from the predicted probability distribution
next = sampleMult(logits, coin);
} else {
// top-p (nucleus) sampling, clamping the least likely tokens to zero
next = sampleTopp(logits, self.topp, self.probindex, coin);
}
}
return @as(u32, @intCast(next));
}
};
// TODO: should we change the output type to u32? (other sampling functions
// below should be changed too)
pub fn sampleArgmax(probabilities: []f32) usize {
// return the index that has the highest probability
var max_i: usize = 0;
var max_p: f32 = probabilities[0];
for (1..probabilities.len) |i| {
if (probabilities[i] > max_p) {
max_i = i;
max_p = probabilities[i];
}
}
return max_i;
}
pub fn sampleMult(probabilities: []f32, coin: f32) usize {
var cdf: f32 = 0.0;
for (0..probabilities.len) |i| {
cdf += probabilities[i];
if (coin < cdf) {
return i;
}
}
return probabilities.len - 1; // in case of rounding errors
}
pub fn sampleTopp(probabilities: []f32, topp: f32, probindex: []ProbIndex, coin: f32) usize {
var n0: usize = 0;
// filter out probs < (1 - topp) / (n - 1) before sorting
const cutoff: f32 = (1.0 - topp) / @as(f32, @floatFromInt(probabilities.len - 1));
for (0..probabilities.len) |i| {
if (probabilities[i] >= cutoff) {
probindex[n0].index = i;
probindex[n0].prob = probabilities[i];
n0 += 1;
}
}
std.sort.pdq(ProbIndex, probindex[0..n0], {}, ProbIndex.asc);
// truncate the list where cumulative probability exceeds topp
var cumulative_prob: f32 = 0.0;
var last_idx = n0 - 1;
for (0..n0) |i| {
cumulative_prob += probindex[i].prob;
if (cumulative_prob > topp) {
last_idx = i;
break; // note that last index is included now
}
}
// sample from the truncated list
const r = coin * cumulative_prob;
var cdf: f32 = 0.0;
for (0..(last_idx + 1)) |i| {
cdf += probindex[i].prob;
if (r < cdf) {
return probindex[i].index;
}
}
return probindex[last_idx].index;
}
pub fn randomU32(state: *u64) u32 {
state.* ^= state.* >> 12;
state.* ^= state.* << 25;
state.* ^= state.* >> 27;
return @as(u32, @intCast((state.* *% @as(u64, 0x2545F4914F6CDD1D)) >> 32));
}
pub fn randomF32(state: *u64) f32 {
// 16777216 = 2^24 = "0 10010111 00000000000000000000000"
// sign: 0, exponent: 10010111 (-127 + 151 = 24), mantissa: 0
const magic: f32 = 16777216.0;
return @as(f32, @floatFromInt(randomU32(state) >> 8)) / magic;
}
// ----------------------------------------------------------------------
pub fn generate(
transformer: *Transformer,
tokenizer: *Tokenizer,
sampler: *Sampler,
prompt: []const u8,
steps: u32,
allocator: Allocator,
) !void {
var prompt_tokens: []u32 = try allocator.alloc(u32, prompt.len + 3);
defer allocator.free(prompt_tokens);
const n_tokens = try tokenizer.encode(prompt, true, false, prompt_tokens, allocator);
var start: i64 = 0;
var next: u32 = undefined;
var token = prompt_tokens[0];
var pos: u32 = 0;
while (pos < steps) {
// forward the transformer to get logits for the next token
var logits: []f32 = transformer.forward(token, pos);
if (pos < n_tokens - 1) {
next = prompt_tokens[pos + 1];
} else {
next = sampler.sample(logits);
}
pos += 1;
// data-dependent terminating condition: the BOS (=1) token delimits sequences
if (next == 1) {
break;
}
const piece = tokenizer.decode(token, next);
safePrint(piece);
token = next;
// init the timer here because the first iteration can be slower
if (start == 0) {
start = std.time.milliTimestamp();
}
}
std.debug.print("\n", .{});
if (pos > 1) {
const end: i64 = std.time.milliTimestamp();
const tok_per_sec: f32 = @as(f32, @floatFromInt(pos - 1)) / @as(f32, @floatFromInt((end - start))) * 1000;
std.debug.print("achieved tok/s: {d}\n", .{tok_per_sec});
}
}
fn errorUsage() void {
const msg =
\\ Usage: run <checkpoint> [options]
\\ Example: run model.bin -n 256 -i \"Once upon a time\"
\\ Options:
\\ -t <float> temperature in [0,inf], default i.0
\\ -p <float> p value in top-p (nucleus) sampling in [0,1] default 0.9
\\ -s <int> random seed, default time(NULL)
\\ -n <int> number of steps to run for, default 256. 0 = max_seq_len
\\ -i <string> input prompt
\\ -z <string> optional path to custom tokenizer
\\ -m <string> mode: generate|chat, default: generate
\\ -y <string> (optional) system prompt in chat mode
\\ -l <int> (optional) use mmap for checkpoint (0: disable, 1: enable)
;
std.debug.print("{s}\n", .{msg});
std.process.exit(1);
}
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
const args = try std.process.argsAlloc(allocator);
defer std.process.argsFree(allocator, args);
if (args.len < 2) {
std.debug.print("No model checkpoint is specified\n", .{});
errorUsage();
}
const checkpoint_path = args[1];
var tokenizer_path: []const u8 = "tokenizer.bin";
var temperature: f32 = 1.0;
var topp: f32 = 0.9;
var steps: u32 = 256;
var prompt: []const u8 = "";
var rng_seed: u64 = 0;
var mode: []const u8 = "generate";
var system_prompt: []const u8 = "";
var use_mmap: bool = true;
var i: usize = 2;
while (i < args.len) : (i += 2) {
if (i + 1 > args.len) {
errorUsage();
}
const arg = args[i];
const val = args[i + 1];
if (arg[0] != '-' or arg.len != 2) {
errorUsage();
}
if (arg[1] == 't') {
temperature = try std.fmt.parseFloat(f32, val);
} else if (arg[1] == 'p') {
topp = try std.fmt.parseFloat(f32, val);
} else if (arg[1] == 's') {
rng_seed = try std.fmt.parseUnsigned(u64, val, 10);
} else if (arg[1] == 'n') {
steps = try std.fmt.parseUnsigned(u32, val, 10);
} else if (arg[1] == 'i') {
prompt = val;
} else if (arg[1] == 'z') {
tokenizer_path = val;
} else if (arg[1] == 'm') {
mode = val;
} else if (arg[1] == 'y') {
system_prompt = val;
} else if (arg[1] == 'l') {
const tmp = try std.fmt.parseInt(u1, val, 0);
use_mmap = if (tmp == 1) true else false;
} else {
errorUsage();
}
}
// parameter validation/overrides
if (rng_seed <= 0) {
rng_seed = @intCast(std.time.timestamp());
}
if (temperature < 0.0) {
temperature = 0.0;
}
if (topp < 0.0 or 1.0 < topp) {
topp = 0.9;
}
if (steps < 0) {
steps = 0;
}
if (!std.mem.eql(u8, mode, "generate")) {
std.debug.print("[ERROR] Currently only 'generate' mode is supported.\n", .{});
std.process.exit(1);
}
var transformer = Transformer{};
try buildTransformer(&transformer, checkpoint_path, use_mmap, allocator);
defer freeTransformer(&transformer, use_mmap, allocator);
if (steps == 0) {
steps = @intCast(transformer.config.seq_len);
} else if (steps > transformer.config.seq_len) {
// XXX: Currently we will clip `steps` if it exceeds the maximal
// sequence length (see also llama2.c issue#348). But maybe we can
// apply RoPE scaling to make it able to inference with longer context?
std.debug.print("warning: clipping `steps` because it exceeds `max_seq_len`\n", .{});
steps = @intCast(transformer.config.seq_len);
}
// Build tokenizer
var tokenizer = Tokenizer{};
try buildTokenizer(&tokenizer, tokenizer_path, 32000, allocator);
defer freeTokenizer(&tokenizer, allocator);
// Build sampler
var sampler = try Sampler.init(32000, temperature, topp, rng_seed, allocator);
defer sampler.deinit(allocator);
try generate(&transformer, &tokenizer, &sampler, prompt, steps, allocator);
}
| https://raw.githubusercontent.com/NaleRaphael/llama2.zig/3ea6b14bf7db4ccec25a50db275655f5192cd0d2/run.zig |
const std = @import("std");
const fs = std.fs;
const print = std.debug.print;
const label = [_]u8{'J', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'Q', 'K', 'A'};
const Record = struct {
hand : []u8,
bid : usize,
};
fn cmp(_:void, a:u8, b:u8) bool {
const ra = std.mem.indexOf(u8, &label, &[_]u8{a}).?;
const rb = std.mem.indexOf(u8, &label, &[_]u8{b}).?;
if (ra < rb) {
return true;
} else {
return false;
}
}
fn rank(hand: []u8) usize {
var sorted:[5]u8 = undefined;
var i:usize = 0;
var sorted_size:usize = 0;
var j_cnt:u8 = 0;
while (i < 5) : ( i += 1) {
if (hand[i] != 'J') {
sorted[sorted_size] = hand[i];
sorted_size += 1;
} else {
j_cnt += 1;
}
}
if (sorted_size == 0) {
return 6;
}
std.sort.block(u8, sorted[0..sorted_size], {}, cmp);
var r:[5]u8 = [_]u8{0} ** 5;
i = 1;
var j:usize = 0;
r[j] = 1;
while (i < sorted_size) : (i += 1) {
if (sorted[i] == sorted[i-1]) {
r[j] +=1;
} else {
j += 1;
r[j] = 1;
}
}
std.sort.block(u8, &r, {}, std.sort.desc(u8));
r[0] += j_cnt;
//print ("{d} {c}\n", .{r, hand});
if (j == 0)
return 6;
if (j == 1) {
if (r[0] == 4) {
return 5;
} else {
return 4;
}
}
if (j == 2) {
if (r[0] == 3 and r[1] == 1)
return 3;
if (r[0] == 2 and r[1] == 2)
return 2;
unreachable;
}
if (j == 3) {
return 1;
}
return 0;
}
fn handCmp(_: void, a: Record, b: Record) bool {
const ra = rank(a.hand);
const rb = rank(b.hand);
if (ra < rb) {
return true;
} else if (ra > rb) {
return false;
} else {
var i:usize = 0;
while (i < 5 ) : ( i += 1) {
const rla = std.mem.indexOf(u8, &label, &[_]u8{a.hand[i]}).?;
const rlb = std.mem.indexOf(u8, &label, &[_]u8{b.hand[i]}).?;
if (rla < rlb) {
return true;
} else if (rla > rlb) {
return false;
}
}
}
unreachable;
}
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
const file = try fs.cwd().openFile("input", .{});
defer file.close();
const rdr = file.reader();
var list = std.ArrayList(Record).init(allocator);
defer list.deinit();
while (try rdr.readUntilDelimiterOrEofAlloc(allocator, '\n', 4096)) |line| {
defer allocator.free(line);
var it = std.mem.split(u8, line, " ");
const hand_str = it.next().?;
const hand = try allocator.alloc(u8, hand_str.len);
@memcpy(hand, hand_str);
const bid = try std.fmt.parseInt(usize, it.next().?, 10);
try list.append(Record{.hand = hand, .bid = bid});
}
const s = try list.toOwnedSlice();
defer allocator.free(s);
defer {
for (s) |*r| {
allocator.free(r.hand);
}
}
std.sort.block(Record, s, {}, handCmp);
var bid:usize = 0;
for (s, 1 .. ) |*r, i| {
print ("{c} {}\n", .{ r.hand, r.bid});
bid += r.bid * i;
}
print ("{}\n", .{bid});
}
| https://raw.githubusercontent.com/xnhp0320/aoc2023/6e42c1e3791ba8e50c3ea0930572cade5caaef5b/7/s2.zig |
const std = @import("std");
pub fn getMimeType(path: []const u8) ?[]const u8 {
const extension = std.mem.lastIndexOf(u8, path, ".") orelse return null;
if (std.mem.eql(u8, path[extension + 1 ..], "html")) {
return "text/html";
} else if (std.mem.eql(u8, path[extension + 1 ..], "css")) {
return "text/css";
} else if (std.mem.eql(u8, path[extension + 1 ..], "js")) {
return "application/javascript";
} else if (std.mem.eql(u8, path[extension + 1 ..], "png")) {
return "image/png";
} else if (std.mem.eql(u8, path[extension + 1 ..], "jpg") or std.mem.eql(u8, path[extension + 1 ..], "jpeg")) {
return "image/jpeg";
} else if (std.mem.eql(u8, path[extension + 1 ..], "gif")) {
return "image/gif";
} else if (std.mem.eql(u8, path[extension + 1 ..], "svg")) {
return "image/svg+xml";
} else if (std.mem.eql(u8, path[extension + 1 ..], "mp4")) {
return "video/mp4";
} else if (std.mem.eql(u8, path[extension + 1 ..], "webm")) {
return "video/webm";
} else if (std.mem.eql(u8, path[extension + 1 ..], "mp3")) {
return "audio/mpeg";
} else if (std.mem.eql(u8, path[extension + 1 ..], "wav")) {
return "audio/wav";
} else if (std.mem.eql(u8, path[extension + 1 ..], "pdf")) {
return "application/pdf";
} else if (std.mem.eql(u8, path[extension + 1 ..], "ico")) {
return "image/x-icon";
} else {
return null;
}
}
| https://raw.githubusercontent.com/hajsf/zig-server/22d3e3f821217f50e0dff9e13ee5450d221c5d30/mime.zig |
const std = @import("std");
const print = std.debug.print;
pub fn main() !void {
var file = try std.fs.cwd().openFile("data/input2.txt", .{});
defer file.close();
var reader = file.reader();
var buf: [4096]u8 = undefined;
var hpos: u32 = 0;
var ypos: u32 = 0;
var aim: u32 = 0;
while (try reader.readUntilDelimiterOrEof(&buf, '\n')) |line| {
var splitter = std.mem.tokenize(u8, line, " ");
var move = splitter.next().?;
var amount = try std.fmt.parseInt(u32, splitter.next().?, 0);
if (std.mem.eql(u8, move, "forward")) {
hpos += amount;
ypos += aim*amount;
} else if (std.mem.eql(u8, move, "backward")) {
hpos -= amount;
} else if (std.mem.eql(u8, move, "down")) {
aim += amount;
} else {
aim -= amount;
}
}
print("prod {}\n", .{hpos*ypos});
} | https://raw.githubusercontent.com/angeris/advent-of-code-2021/fcd858e08f2da93ef53a8aee0698921c896df2ec/d2-2.zig |
const std = @import("std");
const Nihilist = @import("nihilist.zig").Nihilist;
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
var allocator = &arena.allocator;
var args = try std.process.argsAlloc(allocator);
defer std.process.argsFree(allocator, args);
if (args.len < 4) {
std.debug.warn("Usage: nihilist <encrypt|decrypt> <polybius_key> <nihilist_key> <plaintext|ciphertext>\n", .{});
return;
}
var enc = std.mem.eql(u8, args[1], "encrypt");
var dec = std.mem.eql(u8, args[1], "decrypt");
if (!(enc or dec)) {
std.debug.warn("Usage: nihilist <encrypt|decrypt> <polybius_key> <nihilist_key> <plaintext|ciphertext>\n", .{});
return;
}
var nihilist = try Nihilist.init(allocator, args[2], args[3]);
var output = if (dec) nihilist.decrypt(args[4]) else nihilist.encrypt(args[4]);
if (output) |out| {
std.debug.warn("{}\n", .{out});
} else |err| {
switch (err) {
error.InvalidKey => {
std.debug.warn("Invalid key!\n", .{});
},
error.InvalidCiphertext => {
std.debug.warn("Invalid ciphertext!\n", .{});
},
else => {
std.debug.warn("Error: {}\n", .{err});
}
}
}
}
| https://raw.githubusercontent.com/stripedpajamas/nihilist/578019241123857630858161e30832788fd92e3b/main.zig |
const std = @import("std");
const g = @cImport({
@cInclude("glib-object.h");
});
pub fn main() void {
const obj1: ?*g.GObject = @alignCast(@ptrCast(g.g_object_new(g.G_TYPE_OBJECT, null)));
const obj2: ?*g.GObject = @alignCast(@ptrCast(g.g_object_new(g.G_TYPE_OBJECT, null)));
const instance1: ?*g.GTypeInstance = @ptrCast(obj1);
const instance2: ?*g.GTypeInstance = @ptrCast(obj2);
const class1: ?*g.GTypeClass = instance1.?.*.g_class;
const class2: ?*g.GTypeClass = instance2.?.*.g_class;
std.debug.print("addr1 {*}\n", .{obj1});
std.debug.print("addr2 {*}\n", .{obj2});
std.debug.print("klass1 {*}\n", .{class1});
std.debug.print("klass2 {*}\n", .{class2});
g.g_object_unref(obj1);
g.g_object_unref(obj2);
}
| https://raw.githubusercontent.com/evaporei/zobject/23f6bd4c5d72ebda3da82dd189052aa1e70db985/main.zig |
pub const compare = @import("./compare.zig");
pub const meta = @import("./meta.zig");
pub const sentinel = @import("./sentinel.zig");
pub const limitslice = @import("./limitslice.zig");
// disabled for now, too many things to fix during a zig update
//pub const range = @import("./range.zig");
pub const mem = @import("./mem.zig");
pub const stringpool = @import("./stringpool.zig");
// Stuff taken from git-extra
pub const tuple = @import("./tuple.zig");
pub const appendlib = @import("./appendlib.zig");
pub const runutil = @import("./runutil.zig");
pub const cmdlinetool = @import("./cmdlinetool.zig");
const std = @import("std");
test {
std.testing.refAllDecls(@This());
}
| https://raw.githubusercontent.com/marler8997/zog/0f5f075792ba1a9c76901a9a766125386a33cce6/zog.zig |
const std = @import("std");
const libvirt = @import("libvirt");
pub fn main() !void {
std.log.info("All your codebase are belong to us.", .{});
std.log.info("libvirt version: {d}", .{libvirt.c.LIBVIR_VERSION_NUMBER});
}
| https://raw.githubusercontent.com/nektro/zig-libvirt/af019d9f5f5e51d5934b92ad539b3c50d67d0638/main.zig |
pub usingnamespace @import("src/main.zig");
pub const bun = @import("src/bun.zig");
pub const content = struct {
pub const error_js_path = "packages/bun-error/dist/index.js";
pub const error_js = @embedFile(error_js_path);
pub const error_css_path = "packages/bun-error/dist/bun-error.css";
pub const error_css_path_dev = "packages/bun-error/bun-error.css";
pub const error_css = @embedFile(error_css_path);
};
pub const completions = struct {
pub const bash = @embedFile("./completions/bun.bash");
pub const zsh = @embedFile("./completions/bun.zsh");
pub const fish = @embedFile("./completions/bun.fish");
};
pub const JavaScriptCore = @import("./src/jsc.zig");
pub const C = @import("./src/c.zig");
| https://raw.githubusercontent.com/txthinking/jb/d0e3ddce48be1ca0490904397bcd030c5aa7032e/root.zig |
//! This file is auto-generated by zpm-update and *should*
//! not be changed. This file can be checked into your VCS
//! and is able to work standalone.
const std = @import("std");
pub const pkgs = struct {
pub const ziggysynth = std.build.Pkg{
.name = "ziggysynth",
.source = .{ .path = "vendor/ziggysynth//src/ziggysynth.zig" },
};
pub const libgamestudio = std.build.Pkg{
.name = "libgamestudio",
.source = .{ .path = "vendor/libgamestudio/src/main.zig" },
};
pub const zlm = std.build.Pkg{
.name = "zlm",
.source = .{ .path = "vendor/zlm/zlm.zig" },
};
pub const maps = std.build.Pkg{
.name = "maps",
.source = .{ .path = "vendor/maps/src/maps.zig" },
};
pub const ode = std.build.Pkg{
.name = "ode",
.source = .{ .path = "vendor/ode/src/ode.zig" },
};
};
pub const sdks = struct {
pub const @"zero-graphics" = @import("vendor/zero-graphics/Sdk.zig");
pub const soundio = @import("vendor/soundio/Sdk.zig");
pub const ode = @import("vendor/ode/Sdk.zig");
};
| https://media.githubusercontent.com/media/ikskuh/zyclone/ae63975f672d9504b5cf1c9b7616454c67193500/zpm.zig |
const lua = @cImport({
@cInclude("lua.h");
@cInclude("lualib.h");
@cInclude("lauxlib.h");
});
export fn add(s: ?*lua.lua_State) c_int {
const a = lua.luaL_checkinteger(s, 1);
const b = lua.luaL_checkinteger(s, 2);
const c = a + b;
lua.lua_pushinteger(s, c);
return 1;
}
pub fn main() void {
var s = lua.luaL_newstate();
lua.luaL_openlibs(s);
lua.lua_register(s, "zig_add", add);
// TODO translate-c: luaL_dostring
_ = lua.luaL_loadstring(s, "print(zig_add(3, 5))");
// TODO translate-c: lua_pcall
_ = lua.lua_pcallk(s, 0, lua.LUA_MULTRET, 0, 0, null);
}
| https://raw.githubusercontent.com/tiehuis/zig-lua/bb4e2759304b4b38df10919a499528fadfe33632/main.zig |
pub extern fn add(a: i32, b: i32) i32;
pub extern fn sub(a: i32, b: i32) i32;
| https://raw.githubusercontent.com/hajsf/zig-and-go-simple-example/746c6a774a6f537a996c3d20effebc98d47ed47d/def.zig |
const expect = @import("std").testing.expect;
// 5. for loops are used to iterate over the arrays
//5. for loop
test "for loop" {
const rust_name = [_]u8{ 'r', 'u', 's', 't' }; // character literals are equivalent to integer literals
for (rust_name, 0..) |character, index| {
_ = character; //we use _ because rust does not allow us to have unused values
_ = index;
}
for (rust_name) |character| {
_ = character;
}
for (rust_name, 0..) |_, index| {
_ = index;
}
for (rust_name) |_| {}
}
| https://raw.githubusercontent.com/muathendirangu/zig/9566d8190e6e980418fdd2bdcf72b418b91b8948/for.zig |
const expect = @import("std").testing.expect;
test "for" {
//character literals are equivalent to integer literals
const string = [_]u8{ 'a', 'b', 'c' };
for (string, 0..) |character, index| {
_ = character;
_ = index;
}
for (string) |character| {
_ = character;
}
for (string, 0..) |_, index| {
_ = index;
}
for (string) |_| {}
}
| https://raw.githubusercontent.com/wolffshots/ziglearn/5743d7a6748bf38207e5395ea0cc7b5dbdeaf230/for.zig |
const std = @import("std");
const builtin = @import("builtin");
const Self = @This();
pub const AndroidVersion = enum(u16) {
/// KitKat
android_4 = 19,
/// Lollipop
android_5 = 21,
/// Marshmallow
android_6 = 23,
/// Nougat
android_7 = 24,
/// Oreo
android_8 = 26,
/// Pie
android_9 = 28,
/// Quince Tart
android_10 = 29,
/// Red Velvet Cake
android_11 = 30,
/// Snow Cone
android_12 = 31,
/// Tiramisu
android_13 = 33,
};
/// A resource that will be packed into the appliation.
pub const Resource = struct {
/// This is the relative path to the resource root
path: []const u8,
/// This is the content of the file.
content: std.build.FileSource,
};
const CreateResourceDirectory = struct {
builder: *std.build.Builder,
step: std.build.Step,
resources: std.ArrayList(Resource),
directory: std.build.GeneratedFile,
pub fn create(b: *std.build.Builder) *CreateResourceDirectory {
const self = b.allocator.create(CreateResourceDirectory) catch @panic("out of memory");
self.* = CreateResourceDirectory{
.builder = b,
.step = std.Build.Step.init(.{
.id = .custom,
.name = "populate resource directory",
.owner = b,
.makeFn = CreateResourceDirectory.make,
}),
.directory = .{ .step = &self.step },
.resources = std.ArrayList(Resource).init(b.allocator),
};
return self;
}
pub fn add(self: *CreateResourceDirectory, resource: Resource) void {
self.resources.append(Resource{
.path = self.builder.dupe(resource.path),
.content = resource.content.dupe(self.builder),
}) catch @panic("out of memory");
resource.content.addStepDependencies(&self.step);
}
pub fn getOutputDirectory(self: *CreateResourceDirectory) std.build.FileSource {
return .{ .generated = &self.directory };
}
fn make(step: *std.Build.Step, progress: *std.Progress.Node) !void {
_ = progress;
const self = @fieldParentPtr(CreateResourceDirectory, "step", step);
// if (std.fs.path.dirname(strings_xml)) |dir| {
// std.fs.cwd().makePath(dir) catch unreachable;
// }
var cacher = createCacheBuilder(self.builder);
for (self.resources.items) |res| {
cacher.addBytes(res.path);
try cacher.addFile(res.content);
}
const root = try cacher.createAndGetDir();
for (self.resources.items) |res| {
if (std.fs.path.dirname(res.path)) |folder| {
try root.dir.makePath(folder);
}
const src_path = res.content.getPath(self.builder);
try std.fs.Dir.copyFile(
std.fs.cwd(),
src_path,
root.dir,
res.path,
.{},
);
}
self.directory.path = root.path;
}
};
fn createCacheBuilder(b: *std.build.Builder) CacheBuilder {
return CacheBuilder.init(b, "android-sdk");
}
const CacheBuilder = struct {
builder: *std.build.Builder,
hasher: std.crypto.hash.Sha1,
subdir: ?[]const u8,
pub fn init(builder: *std.build.Builder, subdir: ?[]const u8) CacheBuilder {
return CacheBuilder{
.builder = builder,
.hasher = std.crypto.hash.Sha1.init(.{}),
.subdir = if (subdir) |s|
builder.dupe(s)
else
null,
};
}
pub fn addBytes(self: *CacheBuilder, bytes: []const u8) void {
self.hasher.update(bytes);
}
pub fn addFile(self: *CacheBuilder, file: std.build.FileSource) !void {
const path = file.getPath(self.builder);
const data = try std.fs.cwd().readFileAlloc(self.builder.allocator, path, 1 << 32); // 4 GB
defer self.builder.allocator.free(data);
self.addBytes(data);
}
fn createPath(self: *CacheBuilder) ![]const u8 {
var hash: [20]u8 = undefined;
self.hasher.final(&hash);
const path = if (self.subdir) |subdir|
try std.fmt.allocPrint(
self.builder.allocator,
"{s}/{s}/o/{}",
.{
self.builder.cache_root.path.?,
subdir,
std.fmt.fmtSliceHexLower(&hash),
},
)
else
try std.fmt.allocPrint(
self.builder.allocator,
"{s}/o/{}",
.{
self.builder.cache_root.path.?,
std.fmt.fmtSliceHexLower(&hash),
},
);
return path;
}
pub const DirAndPath = struct {
dir: std.fs.Dir,
path: []const u8,
};
pub fn createAndGetDir(self: *CacheBuilder) !DirAndPath {
const path = try self.createPath();
return DirAndPath{
.path = path,
.dir = try std.fs.cwd().makeOpenPath(path, .{}),
};
}
pub fn createAndGetPath(self: *CacheBuilder) ![]const u8 {
const path = try self.createPath();
try std.fs.cwd().makePath(path);
return path;
}
};
pub const KeyStore = struct {
file: []const u8,
alias: []const u8,
password: []const u8,
};
fn semanticCompare(context: void, lhs: std.SemanticVersion, rhs: std.SemanticVersion) bool {
_ = context;
std.debug.assert(lhs.order(rhs) != .eq);
return lhs.order(rhs) == .gt;
}
const AndroidTools = struct {
aapt: []const u8,
zipalign: []const u8,
apksigner: []const u8,
d8: []const u8,
javac: []const u8,
pub fn findTools(b: *std.Build, sdk_root: []const u8) !AndroidTools {
var exe_append = if (builtin.os.tag == .windows) ".exe" else "";
var bat_append = if (builtin.os.tag == .windows) ".bat" else "";
var self: AndroidTools = undefined;
//Get the newest version of the build tools
var latest_sdk_version = blk: {
var build_tools_dir = try std.fs.openIterableDirAbsolute(
try std.fs.path.join(b.allocator, &.{
sdk_root,
"build-tools",
}),
.{},
);
defer build_tools_dir.close();
var iterator = build_tools_dir.iterate();
var versions = std.ArrayList(std.SemanticVersion).init(b.allocator);
defer versions.deinit();
var next: ?std.fs.IterableDir.Entry = try iterator.next();
while (next != null) {
var name = next.?.name;
next = try iterator.next();
var version = try std.SemanticVersion.parse(name);
try versions.append(version);
}
std.sort.block(std.SemanticVersion, versions.items, {}, semanticCompare);
break :blk b.fmt("{any}", .{versions.items[0]});
};
self.aapt = try std.fs.path.join(b.allocator, &.{
sdk_root,
"build-tools",
latest_sdk_version,
"aapt" ++ exe_append,
});
self.zipalign = try std.fs.path.join(b.allocator, &.{
sdk_root,
"build-tools",
latest_sdk_version,
"zipalign" ++ exe_append,
});
self.apksigner = try std.fs.path.join(b.allocator, &.{
sdk_root,
"build-tools",
latest_sdk_version,
"apksigner" ++ bat_append,
});
self.d8 = try std.fs.path.join(b.allocator, &.{
sdk_root,
"build-tools",
latest_sdk_version,
"lib", //we put lib here because calling `d8` directly seems to be borked, idk blame google
"d8.jar",
});
//TODO: find java folder manually, dont rely on it being in the path
self.javac = try std.fs.path.join(b.allocator, &.{
"javac" ++ exe_append,
});
return self;
}
};
///Get the tag for the Android NDK host toolchain
pub fn toolchainHostTag() []const u8 {
const os = builtin.os.tag;
const arch = builtin.cpu.arch;
return @tagName(os) ++ "-" ++ @tagName(arch);
}
///Get the android target triple
pub fn androidTriple(b: *std.Build, target: std.zig.CrossTarget) []const u8 {
//x86 is different from zig to android, we need to change x86 -> i686
if (target.getCpuArch() == .x86) {
return b.fmt("i686-{s}-{s}", .{
@tagName(target.getOsTag()),
@tagName(target.getAbi()),
});
}
//Arm is special and wants androideabi instead of just android
if (target.getCpuArch() == .arm and target.getAbi() == .android) {
return b.fmt("{s}-{s}-androideabi", .{
@tagName(target.getCpuArch()),
@tagName(target.getOsTag()),
});
}
return b.fmt("{s}-{s}-{s}", .{
@tagName(target.getCpuArch()),
@tagName(target.getOsTag()),
@tagName(target.getAbi()),
});
}
fn glob_class_files(allocator: std.mem.Allocator, starting_dir: []const u8) ![]const u8 {
var class_list = std.ArrayList([]const u8).init(allocator);
var dir = try std.fs.openIterableDirAbsolute(starting_dir, .{});
defer dir.close();
var walker: std.fs.IterableDir.Walker = try dir.walk(allocator);
defer walker.deinit();
var itr_next: ?std.fs.IterableDir.Walker.WalkerEntry = try walker.next();
while (itr_next != null) {
var next: std.fs.IterableDir.Walker.WalkerEntry = itr_next.?;
//if the file is a class file
if (std.mem.endsWith(u8, next.path, ".class")) {
var item = try allocator.alloc(u8, next.path.len + starting_dir.len);
//copy the root first
std.mem.copy(u8, item, starting_dir);
//copy the filepath next
std.mem.copy(u8, item[starting_dir.len..], next.path);
try class_list.append(item);
}
itr_next = try walker.next();
}
return class_list.toOwnedSlice();
}
target_android_version: AndroidVersion,
sdk_version: u16,
sdk_root: []const u8,
ndk_root: []const u8,
root_jar: []const u8,
include_dir: []const u8,
tools: AndroidTools,
build: *std.Build,
pub const Feature = struct {
name: []const u8,
required: bool,
};
///Create an APK file, and packs in all `shared_objects` into their respective folders
pub fn createApk(
sdk: Self,
package_name: []const u8,
permissions: []const []const u8,
features: []const Feature,
java_files_opt: ?[]const []const u8,
resources: []const Resource,
key_store: KeyStore,
application: []const u8,
apk_filename: []const u8,
shared_objects: []const *std.Build.Step.Compile,
) !*std.Build.Step.InstallFile {
const write_xml_step = sdk.build.addWriteFiles();
var manifest = write_xml_step.add("AndroidManifest.xml", blk: {
var buf = std.ArrayList(u8).init(sdk.build.allocator);
defer buf.deinit();
var writer = buf.writer();
try writer.print(
\\<?xml version="1.0" encoding="utf-8" standalone="no"?>
\\<manifest xmlns:tools="http://schemas.android.com/tools" xmlns:android="http://schemas.android.com/apk/res/android" package="{s}">
\\ {s}
\\
\\ {s}
\\
\\ {s}
\\</manifest>
, .{
package_name,
perm_blk: {
var perm_buf = std.ArrayList(u8).init(sdk.build.allocator);
defer perm_buf.deinit();
var perm_writer = perm_buf.writer();
for (permissions) |permission| {
try perm_writer.print(
\\<uses-permission android:name="{s}"/>
\\
, .{
permission,
});
}
break :perm_blk try perm_buf.toOwnedSlice();
},
feat_blk: {
var feat_buf = std.ArrayList(u8).init(sdk.build.allocator);
defer feat_buf.deinit();
var feat_writer = feat_buf.writer();
for (features) |feature| {
try feat_writer.print(
\\<uses-feature android:name="{s}" android:required="{any}"/>
\\
, .{
feature.name,
feature.required,
});
}
break :feat_blk try feat_buf.toOwnedSlice();
},
application,
});
break :blk try buf.toOwnedSlice();
});
const resource_dir_step = CreateResourceDirectory.create(sdk.build);
for (resources) |resource| {
resource_dir_step.add(resource);
}
const unaligned_apk_name = sdk.build.fmt("unaligned-{s}", .{std.fs.path.basename(apk_filename)});
const make_unsigned_apk = sdk.build.addSystemCommand(&.{
sdk.tools.aapt,
"package",
"-f", //overwrite existing files
"-I", sdk.root_jar, //add an existing package to base include set
"-F", //specify the apk file output
});
const unaligned_apk_file = make_unsigned_apk.addOutputFileArg(unaligned_apk_name);
//Specify the full path to the manifest file
make_unsigned_apk.addArg("-M");
make_unsigned_apk.addFileSourceArg(manifest);
//Specify the full path to the resource directory
make_unsigned_apk.addArg("-S");
make_unsigned_apk.addDirectorySourceArg(resource_dir_step.getOutputDirectory());
//Specify verbose output and the target android SDK version
make_unsigned_apk.addArgs(&.{
"-v",
"--target-sdk-version",
sdk.build.fmt("{d}", .{sdk.sdk_version}),
});
//todo: asset directories
// for (app_config.asset_directories) |dir| {
// make_unsigned_apk.addArg("-A"); // additional directory in which to find raw asset files
// make_unsigned_apk.addArg(sdk.sdk.build.pathFromRoot(dir));
// }
//NOTE: align happens *AFTER* adding the shared objects, but we have it before in the function so that the copy shared object tasks can be depended on!
const align_step = sdk.build.addSystemCommand(&.{
sdk.tools.zipalign,
"-p", // ensure shared libraries are aligned to 4KiB boundaries
"-f", // overwrite existing files
"-v", // enable verbose output
"-z", // recompress output
"4",
});
// align_step.addFileSourceArg(copy_to_zip_output);
align_step.addFileSourceArg(unaligned_apk_file);
// align_step.step.dependOn(&make_unsigned_apk.step);
const apk_file = align_step.addOutputFileArg(apk_filename);
var last_run_step: ?*std.Build.Step.Run = null;
for (shared_objects, 0..) |shared_object, i| {
// https://developer.android.com/ndk/guides/abis#native-code-in-app-packages
const so_dir = switch (shared_object.target.getCpuArch()) {
.aarch64 => "lib/arm64-v8a",
.arm => "lib/armeabi-v7a",
.x86_64 => "lib/x86_64",
.x86 => "lib/x86",
else => @panic("Unknown arch!"),
};
if (shared_object.target.getAbi() != .android) {
@panic("Non-android shared object added");
}
const target_filename = sdk.build.fmt("lib{s}.so", .{shared_object.name});
const target_path = sdk.build.fmt("{s}/{s}", .{ so_dir, target_filename });
const delete_old_so = sdk.build.addSystemCommand(&.{
"7z",
"d",
});
//The archive
delete_old_so.addFileSourceArg(unaligned_apk_file);
//The path to delete
delete_old_so.addArg(target_path);
delete_old_so.step.dependOn(&make_unsigned_apk.step);
//Run zip with the -j flag, to copy the so file to the root of the apk
const add_to_zip_root = sdk.build.addSystemCommand(&.{
"zip",
"-j",
});
//The target zip file
add_to_zip_root.addFileSourceArg(unaligned_apk_file);
//The .so file
add_to_zip_root.addFileSourceArg(shared_object.getOutputSource());
add_to_zip_root.step.dependOn(&shared_object.step);
add_to_zip_root.step.dependOn(&delete_old_so.step);
//Run 7z to move the file to the right folder
const move_so_to_folder = sdk.build.addSystemCommand(&.{
"7z",
"-tzip",
"-aou",
"rn",
});
//The archive
move_so_to_folder.addFileSourceArg(unaligned_apk_file);
move_so_to_folder.addArgs(&.{
target_filename, //the source path
target_path, //the destination path
});
move_so_to_folder.step.dependOn(&add_to_zip_root.step);
if (last_run_step) |last_step| {
delete_old_so.step.dependOn(&last_step.step);
}
last_run_step = move_so_to_folder;
//Only on the last element,
if (i == shared_objects.len - 1) {
//Make align step depend on the move step
align_step.step.dependOn(&move_so_to_folder.step);
}
}
const java_dir = sdk.build.getInstallPath(.lib, "java");
var root = try std.fs.openDirAbsolute(root_path, .{});
defer root.close();
root.makePath(try std.fs.path.relative(sdk.build.allocator, root_path, java_dir)) catch |err| {
if (err != error.PathAlreadyExists) return err;
};
if (java_files_opt) |java_files| {
if (java_files.len == 0) {
return error.NoJavaFilesPassedPassNullPlease;
}
//HACK: this should be done LITERALLY ANY OTHER WAY,
// but im too lazy to write the 50 lines of code, so this will do for now :)
const d8_cmd = sdk.build.addSystemCommand(&.{
"zsh",
"-c",
});
var final_command = std.ArrayList(u8).init(sdk.build.allocator);
try final_command.appendSlice("java ");
try final_command.appendSlice("-cp ");
try final_command.appendSlice(sdk.tools.d8);
try final_command.appendSlice(" com.android.tools.r8.D8");
try final_command.append(' ');
try final_command.appendSlice("--lib ");
try final_command.appendSlice(sdk.root_jar);
try final_command.append(' ');
const javac_cmd = sdk.build.addSystemCommand(&.{
sdk.tools.javac,
//The classpath
"-cp",
sdk.root_jar,
//The directory
"-d",
java_dir,
});
d8_cmd.step.dependOn(&javac_cmd.step);
for (java_files) |java_file| {
//The java file source
javac_cmd.addFileSourceArg(std.build.FileSource.relative(java_file));
}
try final_command.appendSlice(java_dir);
try final_command.appendSlice("/**/*.class ");
try final_command.appendSlice("--classpath ");
try final_command.appendSlice(java_dir);
try final_command.append(' ');
try final_command.appendSlice("--output ");
try final_command.appendSlice(java_dir);
d8_cmd.addArg(try final_command.toOwnedSlice());
d8_cmd.step.dependOn(&make_unsigned_apk.step);
const dex_file = try std.fs.path.resolve(sdk.build.allocator, &.{ java_dir, "classes.dex" });
//Run zip with the -j flag, to copy the so file to the root of the apk
const add_dex_to_zip = sdk.build.addSystemCommand(&.{
"zip",
"-j",
});
//The target zip file
add_dex_to_zip.addFileSourceArg(unaligned_apk_file);
//The .so file
add_dex_to_zip.addFileSourceArg(.{ .path = dex_file });
//Make the add dex step run after d8
add_dex_to_zip.step.dependOn(&d8_cmd.step);
//Make align depend on adding dex
align_step.step.dependOn(&add_dex_to_zip.step);
}
const sign_step = sdk.build.addSystemCommand(&[_][]const u8{
sdk.tools.apksigner,
"sign",
"--ks", // keystore
key_store.file,
});
sign_step.step.dependOn(&align_step.step);
{
const pass = sdk.build.fmt("pass:{s}", .{key_store.password});
sign_step.addArgs(&.{ "--ks-pass", pass });
sign_step.addFileSourceArg(apk_file);
}
const apk_install = sdk.build.addInstallBinFile(apk_file, apk_filename);
apk_install.step.dependOn(&sign_step.step);
return apk_install;
}
pub const AndroidTarget = struct {
sdk: Self,
sys_include_dir: []const u8,
lib_dir: []const u8,
libc_file: std.build.FileSource,
target: std.zig.CrossTarget,
pub fn setupCompileStep(self: AndroidTarget, step: *std.Build.Step.Compile) void {
//Set the libc file
step.setLibCFile(self.libc_file);
//Make the compile step depend on the libc file
self.libc_file.addStepDependencies(&step.step);
step.addIncludePath(.{ .path = self.sdk.include_dir });
step.addLibraryPath(.{ .path = self.lib_dir });
}
};
pub fn createTarget(sdk: Self, target: std.zig.CrossTarget) !AndroidTarget {
//Path that contains the system headers
const sys_include_dir = try std.fs.path.resolve(sdk.build.allocator, &.{
sdk.include_dir,
androidTriple(sdk.build, target),
});
//Path that contains all the native libraries
const lib_dir = try std.fs.path.resolve(sdk.build.allocator, &.{
sdk.ndk_root,
"toolchains",
"llvm",
"prebuilt",
comptime toolchainHostTag(),
"sysroot",
"usr",
"lib",
androidTriple(sdk.build, target),
sdk.build.fmt("{d}", .{@intFromEnum(sdk.target_android_version)}),
});
var libc_file = try createAndroidLibCFile(
sdk.build,
sdk.target_android_version,
@tagName(target.getCpuArch()),
sdk.include_dir,
sys_include_dir,
lib_dir,
);
return AndroidTarget{
.sys_include_dir = sys_include_dir,
.libc_file = libc_file,
.lib_dir = lib_dir,
.target = target,
.sdk = sdk,
};
}
pub fn init(b: *std.Build, target_android_version: AndroidVersion) !Self {
const sdk_version: u16 = @intFromEnum(target_android_version);
//The root folder of the Android SDK
const sdk_root = try std.process.getEnvVarOwned(b.allocator, "ANDROID_HOME");
//Get the Android NDK root, try first from the env var, then try `sdk_root/ndk-bundle` (is ndk-bundle cross platform?)
const ndk_root = std.process.getEnvVarOwned(b.allocator, "ANDROID_NDK") catch |err| blk: {
if (err != error.EnvironmentVariableNotFound) {
return err;
}
break :blk try std.fs.path.resolve(b.allocator, &.{
sdk_root,
"ndk-bundle",
});
};
//The root jar for the android platform
const root_jar = try std.fs.path.resolve(b.allocator, &.{
sdk_root,
"platforms",
b.fmt("android-{d}", .{sdk_version}),
"android.jar",
});
//The android tools
var tools = try AndroidTools.findTools(b, sdk_root);
//Path that contains the main android headers
const include_dir = try std.fs.path.resolve(b.allocator, &.{
ndk_root,
"toolchains",
"llvm",
"prebuilt",
comptime toolchainHostTag(),
"sysroot",
"usr",
"include",
});
return Self{
.target_android_version = target_android_version,
.sdk_version = sdk_version,
.sdk_root = sdk_root,
.ndk_root = ndk_root,
.root_jar = root_jar,
.include_dir = include_dir,
.tools = tools,
.build = b,
};
}
fn createAndroidLibCFile(b: *std.Build, version: AndroidVersion, folder_name: []const u8, include_dir: []const u8, sys_include_dir: []const u8, crt_dir: []const u8) !std.build.FileSource {
const fname = b.fmt("android-{d}-{s}.conf", .{ @intFromEnum(version), folder_name });
var contents = std.ArrayList(u8).init(b.allocator);
errdefer contents.deinit();
var writer = contents.writer();
// The directory that contains `stdlib.h`.
// On POSIX-like systems, include directories be found with: `cc -E -Wp,-v -xc /dev/null
try writer.print("include_dir={s}\n", .{include_dir});
// The system-specific include directory. May be the same as `include_dir`.
// On Windows it's the directory that includes `vcruntime.h`.
// On POSIX it's the directory that includes `sys/errno.h`.
try writer.print("sys_include_dir={s}\n", .{sys_include_dir});
try writer.print("crt_dir={s}\n", .{crt_dir});
try writer.writeAll("msvc_lib_dir=\n");
try writer.writeAll("kernel32_lib_dir=\n");
try writer.writeAll("gcc_dir=\n");
const step = b.addWriteFiles();
return step.add(fname, contents.items);
}
fn root_dir() []const u8 {
return std.fs.path.dirname(@src().file) orelse ".";
}
const root_path = root_dir() ++ "/";
| https://raw.githubusercontent.com/Beyley/zig-android/63971a19b2ecc9652393d4326111cbae9de35972/sdk.zig |
// Shaders
extern fn compileShader(source: *const u8 , len: c_uint, type: c_uint) c_uint;
extern fn linkShaderProgram(vertexShaderId: c_uint, fragmentShaderId: c_uint) c_uint;
// GL
extern fn glClearColor(_: f32, _: f32, _: f32, _: f32) void;
extern fn glEnable(_: c_uint) void;
extern fn glDepthFunc(_: c_uint) void;
extern fn glClear(_: c_uint) void;
extern fn glGetAttribLocation(_: c_uint, _: *const u8, _: c_uint) c_int ;
extern fn glGetUniformLocation(_: c_uint, _: *const u8, _: c_uint) c_int;
extern fn glUniform4fv(_: c_int, _: f32, _: f32, _: f32, _: f32) void;
extern fn glCreateBuffer() c_uint;
extern fn glBindBuffer(_: c_uint, _: c_uint) void;
extern fn glBufferData(_: c_uint, _: *const f32, _:c_uint, _: c_uint) void;
extern fn glUseProgram(_: c_uint) void;
extern fn glEnableVertexAttribArray(_: c_uint) void;
extern fn glVertexAttribPointer(_: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint) void;
extern fn glDrawArrays(_: c_uint, _: c_uint, _: c_uint) void;
// Identifier constants pulled from WebGLRenderingContext
const GL_VERTEX_SHADER: c_uint = 35633;
const GL_FRAGMENT_SHADER: c_uint = 35632;
const GL_ARRAY_BUFFER: c_uint = 34962;
const GL_TRIANGLES: c_uint = 4;
const GL_STATIC_DRAW: c_uint = 35044;
const GL_f32: c_uint = 5126;
const GL_DEPTH_TEST: c_uint = 2929;
const GL_LEQUAL: c_uint = 515;
const GL_COLOR_BUFFER_BIT: c_uint = 16384;
const GL_DEPTH_BUFFER_BIT: c_uint = 256;
const vertexShader =
\\attribute vec4 a_position;
\\uniform vec4 u_offset;
\\void main() {
\\ gl_Position = a_position + u_offset;
\\}
;
const fragmentShader =
\\precision mediump float;
\\void main() {
\\ gl_FragColor = vec4(0.3, 0.6, 1.0, 1.0);
\\}
;
const positions = [_]f32 {0, 0, 0, 0.5, 0.7, 0};
var program_id: c_uint = undefined;
var positionAttributeLocation: c_int = undefined;
var offsetUniformLocation: c_int = undefined;
var positionBuffer: c_uint = undefined;
export fn onInit() void {
glClearColor(0.1, 0.1, 0.1, 1.0);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
const vertex_shader_id = compileShader(&vertexShader[0], vertexShader.len, GL_VERTEX_SHADER);
const fsId = compileShader(&fragmentShader[0], fragmentShader.len, GL_FRAGMENT_SHADER);
program_id = linkShaderProgram(vertex_shader_id, fsId);
const a_position = "a_position";
const u_offset = "u_offset";
positionAttributeLocation = glGetAttribLocation(program_id, &a_position[0], a_position.len);
offsetUniformLocation = glGetUniformLocation(program_id, &u_offset[0], u_offset.len);
positionBuffer = glCreateBuffer();
glBindBuffer(GL_ARRAY_BUFFER, positionBuffer);
glBufferData(GL_ARRAY_BUFFER, &positions[0], 6, GL_STATIC_DRAW);
}
var previous: c_int = 0;
var x: f32 = 0;
export fn onAnimationFrame(timestamp: c_int) void {
const delta = if(previous > 0) timestamp - previous else 0;
x += @intToFloat(f32, delta) / 1000.0;
if(x > 1) x = -2;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(program_id);
glEnableVertexAttribArray(@intCast(c_uint, positionAttributeLocation));
glBindBuffer(GL_ARRAY_BUFFER, positionBuffer);
glVertexAttribPointer(@intCast(c_uint, positionAttributeLocation), 2, GL_f32, 0, 0, 0);
glUniform4fv(offsetUniformLocation, x, 0.0, 0.0, 0.0);
glDrawArrays(GL_TRIANGLES, 0, 3);
previous = timestamp;
}
pub fn main() void {
} | https://raw.githubusercontent.com/seflless/zig-wasm-webgl/31f726d1f2afa6256c069efb9c57d50fba2fcb90/main.zig |
const std = @import("std");
const ArrayList = std.ArrayList;
const Allocator = std.mem.Allocator;
pub fn readFile(allocator: Allocator, comptime name: []const u8) !ArrayList([]const u8) {
const file = @embedFile(name);
var lines = ArrayList([]const u8).init(allocator);
var iter = std.mem.tokenize(u8, file, "\n");
while (iter.next()) |line| {
try lines.append(line);
}
return lines;
}
| https://raw.githubusercontent.com/boingram/advent-of-code-2023/efbebfc342c54df1c090e199b6233943d0bbee67/io.zig |
const std = @import("std");
const logger = @import("logger.zig");
const builtin = @import("builtin");
const zod = @import("zod.zig");
pub fn main() !void {
logger.log("info", "Welcome to DDoS.zig v1.00 (L7)");
const stdin = std.io.getStdIn().reader();
var inputBuffer: [101]u8 = undefined;
std.debug.print("[TARGET URL]: ", .{});
const t = try stdin.read(&inputBuffer);
std.debug.print("\n", .{});
const url = inputBuffer[0..t];
logger.log("target", zod.validateURL(url));
}
| https://raw.githubusercontent.com/EdamAme-x/DDoS.zig/dacd2a070ee969a6af14c5a3017e93a3ba2ca5a5/DDoS.zig |
const std = @import("std");
const flecs = @import("flecs");
const rl = @import("raylib.zig");
const components = @import("components/export.zig");
const systems = @import("systems/export.zig");
pub fn init(world: *flecs.World, allocator: *std.mem.Allocator) std.mem.Allocator.Error!void {
// add components and systems
components.init(world);
systems.init(world);
// create raylib camera
var rlcamera = try allocator.create(rl.Camera);
rlcamera.* = rl.Camera {
.position = rl.Vector3{ .x = 5, .y = 4, .z = 5 },
.target = rl.Vector3{ .x = 0, .y = 2, .z = 0 },
.up = rl.Vector3{ .x = 0, .y = 1, .z = 0 },
.fovy = 45,
.projection = rl.CAMERA_PERSPECTIVE
};
// add entities
const ecamera = world.new();
world.set(ecamera, &components.Camera{
.camera = rlcamera
});
rl.SetCameraMode(rlcamera.*, rl.CAMERA_FIRST_PERSON);
const ecube = world.new();
world.set(ecube, &components.Cube{
.size = rl.Vector3 {
.x = 10,
.y = 5,
.z = 10
},
.color = rl.RED,
.cam_ptr = rlcamera
});
world.set(ecube, &components.Position{
.x = -10,
.y = 0,
.z = -10
});
const egrid = world.new();
world.set(egrid, &components.Grid{
.slices = 50,
.spacing = 1,
.cam_ptr = rlcamera
});
} | https://raw.githubusercontent.com/madcerto/zig-raylib-flecs-3d/328d302dbd3becbbbb89da65c01d3068f8541e80/init.zig |
const std = @import("std");
const String = @import("utils/string.zig");
pub fn main() !void {
const file = @embedFile("inputs/day1.txt");
var stringAllocator = std.heap.page_allocator;
const lines = try String.split(stringAllocator, file, "\n");
defer lines.deinit();
const numbers = [9][]const u8{ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
const staticString = "Hello";
_ = staticString;
var sum: i32 = 0;
for (lines.items, 0..) |line, lineNum| {
_ = lineNum;
// std.debug.print("\n==Start Line \"{s}\"==\n", .{line});
const allocator = std.heap.page_allocator;
var list = std.ArrayList(i8).init(allocator);
defer list.deinit();
var i: usize = 0;
const wordAllocator = std.heap.page_allocator;
var word = std.ArrayList([1]u8).init(wordAllocator);
defer word.deinit();
// std.debug.print("\tinit word: {s}\n", .{word.items});
while (i < line.len) {
const char = [1]u8{line[i]};
i += 1;
const num = std.fmt.parseInt(i8, &char, 10) catch -1;
// std.debug.print("Parsed {s} -> {d}\n", .{ char, num });
if (num == -1) {
// It's a character, not a number
// std.debug.print("Appending {s}\n", .{&char});
try word.append(char);
// std.debug.print("\tnew word: {s}\n", .{word.items});
for (numbers, 0..) |number, n| {
if (number.len <= word.items.len) {
// std.debug.print("Checking {s} for word {s}\n", .{ word.items, number });
var j: usize = word.items.len - 1;
var k: usize = 0;
while (k >= 0) {
if (j == k or number.len == k) {
break;
}
// std.debug.print(". j={d}, k={d}, number.len={d}\n", .{ j, k, number.len });
const endChar = [_]u8{number[number.len - 1 - k]};
const curChar = word.items[j - k];
// std.debug.print("Comparing {s} vs {s}({s}) for word {s}\n", .{ curChar, endChar, number, word.items });
if (!std.mem.eql(u8, &endChar, &curChar)) {
// std.debug.print(" . Did not match! Bailing early.\n", .{});
k = 0;
break;
}
// std.debug.print("\tj={d}, k={d}\n", .{ j, k });
k += 1;
}
//std.debug.print(" . k={d}\n", .{k});
if (k > 0) {
const toAdd: i8 = @intCast(n + 1);
//std.debug.print(" .WasWord: Add {d}\n", .{toAdd});
try list.append(toAdd);
//std.debug.print("Found word: {s}, compared {s} in {s}\n", .{ number, word.items, line });
break;
}
}
}
continue;
}
word.clearAndFree();
// std.debug.print(" . IsNum: Add {d}\n", .{num});
try list.append(num);
}
const nums = list.items;
if (nums.len == 0) {
continue;
}
//std.debug.print("Numbers in line {d}, \"{s}\": {d} -> {d}{d}\n", .{ lineNum + 1, line, nums, nums[0], nums[nums.len - 1] });
sum += (nums[0] * 10) + nums[nums.len - 1];
}
std.debug.print("Result: {d}\n", .{sum});
}
| https://raw.githubusercontent.com/kolyaventuri/advent-of-code-2023/bfec85a7c08cc11ed8bac17dcaaf7c63b4e0f4e7/day1.zig |
const std = @import("std");
const String = @import("utils/string.zig");
const Data = struct { destination: i64, range_start: i64, range_size: i64 };
fn cmpByData(_: void, a: Data, b: Data) bool {
return a.destination < b.destination;
}
pub fn main() !void {
const file = @embedFile("inputs/day5.txt");
var allocator = std.heap.page_allocator;
const lines = try String.split(allocator, file, "\n");
defer lines.deinit();
var index: usize = 0;
var sections = [8]std.ArrayList(i64){ std.ArrayList(i64).init(allocator), std.ArrayList(i64).init(allocator), std.ArrayList(i64).init(allocator), std.ArrayList(i64).init(allocator), std.ArrayList(i64).init(allocator), std.ArrayList(i64).init(allocator), std.ArrayList(i64).init(allocator), std.ArrayList(i64).init(allocator) };
for (sections) |section| {
defer section.deinit();
}
// Parsing
for (lines.items) |line| {
if (line.len == 0) {
index += 1;
continue;
}
var temp: i64 = -1;
var numbers = std.ArrayList(i64).init(allocator);
defer numbers.deinit();
for (line, 0..) |c, i| {
const char = [1]u8{c};
const num = std.fmt.parseInt(i8, &char, 10) catch -1;
const is_space = std.mem.eql(u8, &char, " ");
if (num == -1 and !is_space) {
temp = -1;
// First line is formatted "label: 1 2 3"
if (index == 0) {
continue;
}
break;
} else if (num == -1) {
if (temp > -1) {
try numbers.append(temp);
}
temp = -1;
continue;
}
if (temp == -1) {
temp = 0;
}
// std.debug.print("({d} -> {d} + {d}) ", .{ temp, temp * 10, num });
temp *= 10;
temp += num;
if (i == line.len - 1) {
try numbers.append(temp);
}
}
if (numbers.items.len > 0) {
for (numbers.items) |n| {
try sections[index].append(n);
}
}
}
var lists = [_]std.ArrayList(Data){std.ArrayList(Data).init(allocator)} ** 7;
for (lists) |list| {
defer list.deinit();
}
for (sections[1..sections.len], 0..) |section, i| {
// std.debug.print("Section {d} (size {d})...\n", .{ i + 1, section.items.len });
var j: usize = 0;
while (j < section.items.len) {
const destination = section.items[j];
const range_start = section.items[j + 1];
const range_size = section.items[j + 2];
const data = Data{ .destination = destination, .range_start = range_start, .range_size = range_size };
try lists[i].append(data);
// std.debug.print("\tStored row {d} vs {d}\n", .{ j, section.items.len });
j += 3;
}
std.mem.sort(Data, lists[i].items, {}, cmpByData);
}
// std.debug.print("Done parsing.\n", .{});
// End Parse
// Begin logic
var min: i64 = -1;
for (sections[0].items) |seed| {
var temp: i64 = seed;
// std.debug.print("Seed {d}: {d}\n", .{ seed, seed });
for (lists) |list| {
for (list.items) |data| {
const destination_start = data.destination;
const source_start = data.range_start;
const size = data.range_size - 1;
if (temp >= source_start and temp <= source_start + size) {
// std.debug.print("{d} -> ", .{temp});
// std.debug.print("(s: {d}, se: {d})", .{ source_start, source_start + size });
// std.debug.print("(d: {d}, de: {d})", .{ destination_start, destination_start + size });
const offset = destination_start - source_start;
temp = temp + offset;
break;
}
}
// std.debug.print("\n", .{});
}
// std.debug.print("Check {d}\n", .{temp});
if (min == -1) {
min = temp;
} else if (temp < min) {
min = temp;
}
}
std.debug.print("Part 1: {d}\n", .{min});
// Part 2
// Get seed ranges
var value: i64 = -1;
var size: i64 = -1;
var seed_ranges = std.ArrayList([2]i64).init(allocator);
defer seed_ranges.deinit();
for (sections[0].items, 0..) |num, i| {
if (i % 2 == 0) {
// Start of range
value = num;
} else {
// Range size
size = num;
}
if (value > -1 and size > -1) {
try seed_ranges.append([2]i64{ value, size });
value = -1;
size = -1;
}
}
std.debug.print("{d}\n", .{seed_ranges.items});
var total: i64 = 0;
var max_seed: i64 = -1;
for (seed_ranges.items) |range| {
total += range[1];
const seed = range[0] + range[1] - 1;
if (seed > max_seed) {
max_seed = seed;
}
}
std.debug.print("{d} total seeds, largest is {d}\n", .{ total, max_seed });
var curr: i64 = 0;
while (true) {
// Iterate backwards through the maps
// std.debug.print("Location {d} maps back to...\n", .{curr});
var i: usize = 7;
var temp: i64 = curr;
while (i >= 1) {
const section = sections[i];
// std.debug.print("\tSection {d} ({d})...\n", .{ i, temp });
var j: usize = 0;
while (j < section.items.len) {
const destination = section.items[j];
const source = section.items[j + 1];
const length = section.items[j + 2];
if (temp >= destination and temp < destination + length) {
// std.debug.print("\t\tMatch {d} -> {d} + {d} = {d}\n", .{ temp, destination, destination - source, temp - (source - destination) });
temp += source - destination;
break;
}
j += 3;
}
i -= 1;
}
// std.debug.print("\tResult: {d}\n", .{temp});
var found = false;
for (seed_ranges.items) |range| {
const min_range = range[0];
const max = range[0] + range[1] - 1;
if (temp >= min_range and temp <= max) {
// std.debug.print("\t\t{d} is in range {d} -> {d}\n", .{ temp, min_range, max });
found = true;
break;
}
}
if (found) {
break;
}
curr += 1;
}
std.debug.print("Part 2: {d}\n", .{curr});
}
| https://raw.githubusercontent.com/kolyaventuri/advent-of-code-2023/bfec85a7c08cc11ed8bac17dcaaf7c63b4e0f4e7/day5.zig |
const std = @import("std");
const mem = std.mem;
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
const expectError = std.testing.expectError;
const Error = error{ Codec, Overrun };
//
//
// Deserialization
//
//
pub const Deserialize = struct {
const Self = @This();
ptr: *anyopaque,
vtable: *const VTable,
pub const VTable = struct {
visit_tag: *const fn (*anyopaque, u64) Visitor,
};
pub fn visitTag(self: Self, tag: u64) Visitor {
return (self.vtable.visit_tag)(tag);
}
};
pub const Visitor = struct {
const Self = @This();
ptr: *anyopaque,
vtable: *const VTable,
pub const VTable = struct {
visit_wire_type_varint: *const fn (*anyopaque, u64) anyerror!void,
visit_wire_type_i64: *const fn (*anyopaque, u64) anyerror!void,
visit_wire_type_len: *const fn (*anyopaque, []const u8) anyerror!void,
visit_wire_type_i32: *const fn (*anyopaque, u32) anyerror!void,
};
pub fn visitWireTypeVarint(self: Self, varint: u64) !void {
return (self.vtable.visit_wire_type_varint)(self.ptr, varint);
}
pub fn visitWireTypeI64(self: Self, val: u64) !void {
return (self.vtable.visit_wire_type_i64)(self.ptr, val);
}
pub fn visitWireTypeLen(self: Self, bytes: []const u8) !void {
return (self.vtable.visit_wire_type_len)(self.ptr, bytes);
}
pub fn visitWireTypeI32(self: Self, val: u32) !void {
return (self.vtable.visit_wire_type_i32)(self.ptr, val);
}
//
// Visitor implementors
//
fn visitUInt32(ptr: *anyopaque, val: u64) !void {
var concrete_ptr: *u32 = @ptrCast(@alignCast(ptr));
concrete_ptr.* = @truncate(val);
}
pub fn UInt32(ptr: *u32) Visitor {
return .{ .ptr = @ptrCast(ptr), .vtable = &.{
.visit_wire_type_varint = visitUInt32,
.visit_wire_type_i64 = visitWireTypeI64Null,
.visit_wire_type_len = visitWireTypeLenNull,
.visit_wire_type_i32 = visitWireTypeI32Null,
} };
}
const UInt32ArrayListImpl = struct {
fn visitWireTypeVarint(ptr: *anyopaque, val: u64) !void {
var concrete_ptr: *std.ArrayList(u32) = @ptrCast(@alignCast(ptr));
try concrete_ptr.append(@truncate(val));
}
fn visitWireTypeLen(ptr: *anyopaque, bytes: []const u8) !void {
var concrete_ptr: *std.ArrayList(u32) = @ptrCast(@alignCast(ptr));
var xs = bytes;
while (xs.len != 0) {
const x = try decodeVarint(&xs);
try concrete_ptr.append(@truncate(x));
}
}
};
pub fn UInt32ArrayList(ptr: *std.ArrayList(u32)) Visitor {
return .{
.ptr = @ptrCast(ptr),
.vtable = &.{
.visit_wire_type_varint = UInt32ArrayListImpl.visitWireTypeVarint,
.visit_wire_type_i64 = visitWireTypeI64Null,
.visit_wire_type_len = UInt32ArrayListImpl.visitWireTypeLen,
.visit_wire_type_i32 = visitWireTypeI32Null,
},
};
}
fn UInt32BoundedArrayImpl(comptime capacity: usize) type {
return struct {
fn visitWireTypeVarint(
ptr: *anyopaque,
val: u64,
) !void {
var concrete_ptr: *std.BoundedArray(u32, capacity) = @ptrCast(@alignCast(ptr));
try concrete_ptr.append(@truncate(val));
}
fn visitWireTypeLen(
ptr: *anyopaque,
bytes: []const u8,
) !void {
var xs = bytes;
var concrete_ptr: *std.BoundedArray(u32, capacity) = @ptrCast(@alignCast(ptr));
while (xs.len != 0) {
const x = try decodeVarint(&xs);
try concrete_ptr.append(@truncate(x));
}
}
};
}
pub fn UInt32BoundedArray(
comptime capacity: usize,
ptr: *std.BoundedArray(u32, capacity),
) Visitor {
return .{
.ptr = @ptrCast(ptr),
.vtable = &.{
.visit_wire_type_varint = UInt32BoundedArrayImpl(capacity).visitWireTypeVarint,
.visit_wire_type_i64 = visitWireTypeI64Null,
.visit_wire_type_len = UInt32BoundedArrayImpl(capacity).visitWireTypeLen,
.visit_wire_type_i32 = visitWireTypeI32Null,
},
};
}
/// A visitor which doesn't do anything.
pub const Null: Visitor = .{
.ptr = @alignCast(@ptrCast(@constCast(&.{}))),
.vtable = &.{
.visit_wire_type_varint = visitWireTypeVarintNull,
.visit_wire_type_i64 = visitWireTypeI64Null,
.visit_wire_type_len = visitWireTypeLenNull,
.visit_wire_type_i32 = visitWireTypeI32Null,
},
};
};
fn visitWireTypeVarintNull(_: *anyopaque, _: u64) !void {}
fn visitWireTypeI64Null(_: *anyopaque, _: u64) !void {}
fn visitWireTypeLenNull(_: *anyopaque, _: []const u8) !void {}
fn visitWireTypeI32Null(_: *anyopaque, _: u32) !void {}
//
//
// Helper functions
//
//
fn popByte(xs: *[]const u8) !u8 {
if (xs.len > 0) {
const x = xs.*[0];
xs.* = xs.*[1..];
return x;
} else {
return error.Overrun;
}
}
fn popBytes(xs: *[]const u8, comptime n: usize) ![n]u8 {
if (xs.len >= n) {
const ys = xs.*[0..n];
xs.* = xs.*[n..];
return ys.*;
} else {
return error.Overrun;
}
}
fn decodeVarint(xs: *[]const u8) !u64 {
var varint: u64 = 0;
for (0..10) |count| {
const x = @as(u64, try popByte(xs));
varint |= (x & 0x7f) << @intCast(count * 7);
if (x <= 0x7f) {
if (count == 9 and x >= 2) {
return error.Codec;
}
return varint;
}
}
return error.Codec;
}
inline fn decodeFixed32(xs: *[]const u8) !u32 {
const bytes = try popBytes(xs, 4);
return mem.readIntNative(u32, bytes);
}
inline fn decodeFixed64(xs: *[]const u8) !u64 {
const bytes = try popBytes(xs, 8);
return mem.readIntNative(u64, bytes);
}
//
//
// Test suite
//
//
test "pop byte" {
var bytes = [_]u8{ 1, 2, 3 };
var slice: []u8 = &bytes;
try expectEqual(try popByte(&slice), bytes[0]);
try expect(mem.eql(u8, slice, bytes[1..]));
try expectEqual(try popByte(&slice), bytes[1]);
try expect(mem.eql(u8, slice, bytes[2..]));
try expectEqual(try popByte(&slice), bytes[2]);
try expect(mem.eql(u8, slice, &[_]u8{}));
try expectError(error.Overrun, popByte(&slice));
}
test "pop bytes" {
var bytes = [_]u8{ 1, 2, 3, 4, 5, 6 };
var slice: []u8 = &bytes;
try expect(mem.eql(u8, &try popBytes(&slice, 2), bytes[0..2]));
try expect(mem.eql(u8, slice, bytes[2..]));
try expect(mem.eql(u8, &try popBytes(&slice, 3), bytes[2..5]));
try expect(mem.eql(u8, slice, bytes[5..]));
try expect(mem.eql(u8, &try popBytes(&slice, 1), bytes[5..]));
try expect(mem.eql(u8, slice, &[_]u8{}));
try expectError(error.Overrun, popByte(&slice));
}
test "decode varint" {
{
var bytes = [_]u8{1};
var slice: []u8 = &bytes;
try expectEqual(try decodeVarint(&slice), 1);
}
{
var bytes = [_]u8{ 128, 1 };
var slice: []u8 = &bytes;
try expectEqual(try decodeVarint(&slice), 128);
}
{
var bytes = [_]u8{ 128, 128, 1 };
var slice: []u8 = &bytes;
try expectEqual(try decodeVarint(&slice), 16384);
}
}
test "u32 [uint32] visit varint" {
var x: u32 = 0;
const visitor = Visitor.UInt32(&x);
try visitor.visitWireTypeVarint(123);
try expectEqual(x, 123);
}
test "ArrayList(u32) [repeated uint32] visit varint" {
var xs = std.ArrayList(u32).init(std.testing.allocator);
defer xs.deinit();
const visitor = Visitor.UInt32ArrayList(&xs);
try visitor.visitWireTypeVarint(123);
try visitor.visitWireTypeVarint(456);
try expectEqual(xs.pop(), 456);
try expectEqual(xs.pop(), 123);
try expectEqual(xs.popOrNull(), null);
}
test "ArrayList(u32) [repeated uint32] visit len" {
const bytes = [_]u8{ 123, 200, 3 };
var xs = std.ArrayList(u32).init(std.testing.allocator);
defer xs.deinit();
const visitor = Visitor.UInt32ArrayList(&xs);
try visitor.visitWireTypeLen(&bytes);
try expectEqual(xs.pop(), 456);
try expectEqual(xs.pop(), 123);
try expectEqual(xs.popOrNull(), null);
}
test "BoundedArray(u32, 2) [repeated uint32] visit varint" {
var xs = try std.BoundedArray(u32, 2).init(0);
const visitor = Visitor.UInt32BoundedArray(2, &xs);
try visitor.visitWireTypeVarint(123);
try visitor.visitWireTypeVarint(456);
try expectEqual(xs.pop(), 456);
try expectEqual(xs.pop(), 123);
try expectEqual(xs.popOrNull(), null);
}
test "BoundedArray(u32, 2) [repeated uint32] visit len" {
const bytes = [_]u8{ 123, 200, 3 };
var xs = try std.BoundedArray(u32, 2).init(0);
const visitor = Visitor.UInt32BoundedArray(2, &xs);
try visitor.visitWireTypeLen(&bytes);
try expectEqual(xs.pop(), 456);
try expectEqual(xs.pop(), 123);
try expectEqual(xs.popOrNull(), null);
}
| https://raw.githubusercontent.com/rjsberry/pb.zig/a945094a18d89a97937ea83e17fd37ad281e6f65/pb.zig |
//! Matrix math operations
pub fn mul(comptime M: usize, comptime N: usize, comptime P: usize, comptime T: type, a: [N][M]T, b: [P][N]T) [P][M]T {
var res: [P][M]T = undefined;
for (&res, 0..) |*column, i| {
for (column, 0..) |*c, j| {
var va: @Vector(N, T) = undefined;
comptime var k: usize = 0;
inline while (k < N) : (k += 1) {
va[k] = a[k][j];
}
const vb: @Vector(N, T) = b[i];
c.* = @reduce(.Add, va * vb);
}
}
return res;
}
const std = @import("std");
test mul {
try std.testing.expectEqualDeep([3][4]f32{
.{ 5, 8, 6, 11 },
.{ 4, 9, 5, 9 },
.{ 3, 5, 3, 6 },
}, mul(
4,
3,
3,
f32,
.{
.{ 1, 2, 0, 1 },
.{ 0, 1, 1, 1 },
.{ 1, 1, 1, 2 },
},
.{
.{ 1, 2, 4 },
.{ 2, 3, 2 },
.{ 1, 1, 2 },
},
));
try std.testing.expectEqualDeep([1][4]f32{
.{ 1, 2, 3, 4 },
}, mul(
4,
4,
1,
f32,
.{
.{ 1, 0, 0, 0 },
.{ 0, 1, 0, 0 },
.{ 0, 0, 1, 0 },
.{ 0, 0, 0, 1 },
},
.{
.{ 1, 2, 3, 4 },
},
));
try std.testing.expectEqualDeep([4][4]f32{
.{ 1, 0, 0, 0 },
.{ 0, 1, 0, 0 },
.{ 0, 0, 1, 0 },
.{ 7, 9, 11, 1 },
}, mul(
4,
4,
4,
f32,
.{
.{ 1, 0, 0, 0 },
.{ 0, 1, 0, 0 },
.{ 0, 0, 1, 0 },
.{ 2, 3, 4, 1 },
},
.{
.{ 1, 0, 0, 0 },
.{ 0, 1, 0, 0 },
.{ 0, 0, 1, 0 },
.{ 5, 6, 7, 1 },
},
));
try std.testing.expectEqualDeep([4][4]f32{
.{ 1, 0, 0, 0 },
.{ 0, 1, 0, 0 },
.{ 0, 0, 1, 0 },
.{ 5, 6, 7, 0 },
}, mul(
4,
4,
4,
f32,
.{
.{ 1, 0, 0, 0 },
.{ 0, 1, 0, 0 },
.{ 0, 0, 1, 0 },
.{ 2, 3, 4, 0 },
},
.{
.{ 1, 0, 0, 0 },
.{ 0, 1, 0, 0 },
.{ 0, 0, 1, 0 },
.{ 5, 6, 7, 0 },
},
));
}
| https://raw.githubusercontent.com/leroycep/seizer/54a39bf2c2f867a2caa69c4a63fa4732ebc7ac71/src/geometry/mat.zig |
const std = @import("std");
const sort = std.sort;
const warn = std.debug.warn;
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const Edge = struct {
from: i32,
to: i32,
distance: i32,
const Self = @This();
pub fn asc(l: Edge, r: Edge) bool {
return l.distance < r.distance;
}
pub fn dsc(l: Edge, r: Edge) bool {
return l.distance > r.distance;
}
pub fn equals(self: Self, other: Edge) bool {
return (self.from == other.from) and (self.to == other.to) and (self.distance == other.distance);
}
};
const Tree = struct {
parent: usize,
rank: usize,
};
const UnionFindForest = struct {
forest: []Tree,
const Self = @This();
pub fn find(self: Self, i: usize) usize {
const f = self.forest;
if (f[i].parent != i) {
f[i].parent = self.find(f[i].parent);
}
return f[i].parent;
}
pub fn isSameTree(self: Self, e: Edge) bool {
const from = @intCast(usize, e.from);
const to = @intCast(usize, e.to);
return self.find(from) == self.find(to);
}
pub fn merge(self: UnionFindForest, e: Edge) void {
const from = @intCast(usize, e.from);
const to = @intCast(usize, e.to);
const f = self.forest;
const x = self.find(from);
const y = self.find(to);
if (f[x].rank < f[y].rank) {
f[x].parent = y;
} else if (f[x].rank > f[y].rank) {
f[y].parent = x;
} else {
f[y].parent = x;
f[x].rank += 1;
}
}
pub fn init(size: usize, allocator: *Allocator) !Self {
const a = try allocator.alloc(Tree, size);
for (a) |_, i| {
a[i] = Tree{
.parent = i,
.rank = 1,
};
}
return Self{ .forest = a };
}
};
inline fn edge(from: i32, to: i32, distance: i32) Edge {
return Edge{
.from = from,
.to = to,
.distance = distance,
};
}
pub fn kruskal(edges: []const Edge, size: usize, allocator: *Allocator) !?[]const Edge {
const forest = try UnionFindForest.init(size, allocator);
var mst = try allocator.alloc(Edge, size - 1);
var j: usize = 0;
for (edges) |e| {
if (j == size - 1) {
return mst;
}
if (!forest.isSameTree(e)) {
forest.merge(e);
mst[j] = e;
j += 1;
}
}
return null;
}
test "Minimal Spanning Tree test" {
var directAllocator = std.heap.DirectAllocator.init();
defer directAllocator.deinit();
sort.sort(Edge, &graph, Edge.asc);
const optional_mst = try kruskal(&graph, vertices, &directAllocator.allocator);
assert(optional_mst != null);
if (optional_mst) |mst| {
for (mst) |e, i| {
assert(e.equals(minimalSpanningTree[i]));
}
}
}
const vertices = 11;
var graph = []const Edge{
edge(0, 1, 2),
edge(0, 3, 5),
edge(1, 3, 1),
edge(1, 2, 4),
edge(1, 4, 7),
edge(4, 8, 2),
edge(4, 9, 1),
edge(7, 8, 1),
edge(7, 10, 8),
edge(8, 10, 2),
edge(8, 9, 3),
edge(9, 5, 5),
edge(9, 6, 3),
edge(5, 6, 2),
edge(5, 10, 4),
edge(9, 10, 5),
};
const minimalSpanningTree = []const Edge{
edge(1, 3, 1),
edge(4, 9, 1),
edge(7, 8, 1),
edge(0, 1, 2),
edge(4, 8, 2),
edge(8, 10, 2),
edge(5, 6, 2),
edge(9, 6, 3),
edge(1, 2, 4),
edge(1, 4, 7),
};
| https://raw.githubusercontent.com/Dussim/Zig/7a4da6f57cdea4f19d09f9303d1e828d542776f7/mst.zig |
const std = @import("std");
const windows = @import("windows.zig");
const ws2_32 = @import("ws2_32.zig");
const os = std.os;
const net = std.net;
const math = std.math;
const Handle = struct {
const Self = @This();
inner: windows.HANDLE,
pub fn init(handle: windows.HANDLE) Self {
return Self{ .inner = handle };
}
pub fn deinit(self: *const Self) void {
windows.closesocket(@ptrCast(ws2_32.SOCKET, self.inner)) catch {};
}
pub inline fn unwrap(self: *const Self) windows.HANDLE {
return self.inner;
}
};
const Overlapped = struct {
const Self = @This();
inner: windows.OVERLAPPED,
frame: anyframe,
pub fn init(frame: anyframe) Self {
return .{
.inner = .{
.Internal = 0,
.InternalHigh = 0,
.Offset = 0,
.OffsetHigh = 0,
.hEvent = null,
},
.frame = frame,
};
}
};
const Poller = struct {
const Self = @This();
port: windows.HANDLE,
pub fn init() !Self {
const port = try windows.CreateIoCompletionPort(
windows.INVALID_HANDLE_VALUE,
null,
undefined,
math.maxInt(windows.DWORD),
);
errdefer windows.CloseHandle(port);
return Self{ .port = port };
}
pub fn deinit(self: *const Self) void {
windows.CloseHandle(self.port);
}
pub fn register(self: *const Self, handle: *const Handle) !void {
try windows.SetFileCompletionNotificationModes(handle.unwrap(), windows.FILE_SKIP_SET_EVENT_ON_HANDLE | windows.FILE_SKIP_COMPLETION_PORT_ON_SUCCESS);
_ = try windows.CreateIoCompletionPort(handle.unwrap(), self.port, 0, 0);
}
pub fn poll(self: *const Self) !void {
var events: [1024]windows.OVERLAPPED_ENTRY = undefined;
const num_events = try windows.GetQueuedCompletionStatusEx(self.port, &events, null, false);
for (events[0..num_events]) |event| {
// std.debug.print("IOCP Notification ({})\n", .{event});
const overlapped = @fieldParentPtr(Overlapped, "inner", event.lpOverlapped);
resume overlapped.frame;
}
}
};
pub fn bind(handle: *Handle, addr: net.Address) !void {
try windows.bind_(@ptrCast(ws2_32.SOCKET, handle.unwrap()), &addr.any, addr.getOsSockLen());
}
pub fn listen(handle: *Handle, backlog: usize) !void {
try windows.listen_(@ptrCast(ws2_32.SOCKET, handle.unwrap()), backlog);
}
pub fn connect(handle: *Handle, addr: net.Address) callconv(.Async) !void {
try bind(handle, net.Address.initIp4(.{0, 0, 0, 0}, 0));
var overlapped = Overlapped.init(@frame());
windows.ConnectEx(
@ptrCast(ws2_32.SOCKET, handle.unwrap()),
&addr.any,
addr.getOsSockLen(),
&overlapped.inner,
) catch |err| switch (err) {
error.WouldBlock => {
suspend;
},
else => return err,
};
try windows.getsockoptError(@ptrCast(ws2_32.SOCKET, handle.unwrap()));
try windows.setsockopt(
@ptrCast(ws2_32.SOCKET, handle.unwrap()),
ws2_32.SOL_SOCKET,
ws2_32.SO_UPDATE_CONNECT_CONTEXT,
null,
);
}
pub fn accept(handle: *Handle) callconv(.Async) !Handle {
var accepted = Handle.init(try windows.WSASocketW(
ws2_32.AF_UNSPEC,
ws2_32.SOCK_STREAM,
ws2_32.IPPROTO_TCP,
null,
0,
ws2_32.WSA_FLAG_OVERLAPPED,
));
errdefer accepted.deinit();
var overlapped = Overlapped.init(@frame());
windows.AcceptEx(
@ptrCast(ws2_32.SOCKET, handle.unwrap()),
@ptrCast(ws2_32.SOCKET, accepted.unwrap()),
&overlapped.inner,
) catch |err| switch (err) {
error.WouldBlock => {
suspend;
},
else => return err,
};
var opt_val: []const u8 = undefined;
opt_val.ptr = @ptrCast([*]const u8, &handle.unwrap());
opt_val.len = @sizeOf(ws2_32.SOCKET);
try windows.setsockopt(
@ptrCast(ws2_32.SOCKET, accepted.unwrap()),
ws2_32.SOL_SOCKET,
ws2_32.SO_UPDATE_ACCEPT_CONTEXT,
opt_val,
);
return accepted;
}
pub fn read(handle: *Handle, buf: []u8) callconv(.Async) !usize {
var overlapped = Overlapped.init(@frame());
windows.ReadFile_(handle.unwrap(), buf, &overlapped.inner) catch |err| switch (err) {
error.WouldBlock => {
suspend;
},
else => return err,
};
return overlapped.inner.InternalHigh;
}
pub fn write(handle: *Handle, buf: []const u8) callconv(.Async) !usize {
var overlapped = Overlapped.init(@frame());
windows.WriteFile_(handle.unwrap(), buf, &overlapped.inner) catch |err| switch (err) {
error.WouldBlock => {
suspend;
},
else => return err,
};
return overlapped.inner.InternalHigh;
}
pub fn runClient(poller: *Poller, stopped: *bool) callconv(.Async) !void {
errdefer |err| std.debug.print("Got an error: {}\n", .{@errorName(err)});
defer stopped.* = true;
const addr = try net.Address.parseIp("127.0.0.1", 9000);
var handle = Handle.init(
try windows.WSASocketW(
addr.any.family,
ws2_32.SOCK_STREAM,
ws2_32.IPPROTO_TCP,
null,
0,
ws2_32.WSA_FLAG_OVERLAPPED,
),
);
defer handle.deinit();
try poller.register(&handle);
try connect(&handle, addr);
std.debug.print("Connected to {}!\n", .{addr});
var buf: [1024]u8 = undefined;
std.debug.print("Got: {}", .{buf[0..try read(&handle, buf[0..])]});
std.debug.print("Got: {}", .{buf[0..try read(&handle, buf[0..])]});
_ = try write(&handle, "Hello world!");
}
pub fn runServer(poller: *Poller, stopped: *bool) callconv(.Async) !void {
errdefer |err| std.debug.print("Got an error: {}\n", .{@errorName(err)});
defer stopped.* = true;
const addr = try net.Address.parseIp("127.0.0.1", 9000);
var handle = Handle.init(
try windows.WSASocketW(
addr.any.family,
ws2_32.SOCK_STREAM,
ws2_32.IPPROTO_TCP,
null,
0,
ws2_32.WSA_FLAG_OVERLAPPED,
),
);
defer handle.deinit();
try poller.register(&handle);
try bind(&handle, addr);
try listen(&handle, 128);
std.debug.print("Listening for peers on: {}\n", .{addr});
var client = try accept(&handle);
defer client.deinit();
try poller.register(&client);
std.debug.print("A client has connected!\n", .{});
var buf: [1024]u8 = undefined;
std.debug.print("Got: {}", .{buf[0..try read(&client, buf[0..])]});
std.debug.print("Got: {}", .{buf[0..try read(&client, buf[0..])]});
}
pub fn runBenchmarkClient(poller: *Poller, stopped: *bool) callconv(.Async) !void {
errdefer |err| std.debug.print("Got an error: {}\n", .{@errorName(err)});
defer stopped.* = true;
const addr = try net.Address.parseIp("127.0.0.1", 9000);
var handle = Handle.init(
try windows.WSASocketW(
addr.any.family,
ws2_32.SOCK_STREAM,
ws2_32.IPPROTO_TCP,
null,
0,
ws2_32.WSA_FLAG_OVERLAPPED,
),
);
defer handle.deinit();
try poller.register(&handle);
try connect(&handle, addr);
std.debug.print("Connected to {}!\n", .{addr});
var buf: [65536]u8 = undefined;
while (true) {
_ = try write(&handle, buf[0..]);
}
}
pub fn runBenchmarkServer(poller: *Poller, stopped: *bool) callconv(.Async) !void {
errdefer |err| std.debug.print("Got an error: {}\n", .{@errorName(err)});
defer stopped.* = true;
const addr = try net.Address.parseIp("127.0.0.1", 9000);
var handle = Handle.init(
try windows.WSASocketW(
addr.any.family,
ws2_32.SOCK_STREAM,
ws2_32.IPPROTO_TCP,
null,
0,
ws2_32.WSA_FLAG_OVERLAPPED,
),
);
defer handle.deinit();
try poller.register(&handle);
try bind(&handle, addr);
try listen(&handle, 128);
std.debug.print("Listening for peers on: {}\n", .{addr});
var client = try accept(&handle);
defer client.deinit();
try poller.register(&client);
std.debug.print("A client has connected!\n", .{});
var buf: [65536]u8 = undefined;
while (true) {
_ = try read(&client, buf[0..]);
}
}
pub fn main() !void {
_ = try windows.WSAStartup(2, 2);
defer windows.WSACleanup() catch {};
var poller = try Poller.init();
defer poller.deinit();
var stopped = false;
var frame = async runClient(&poller, &stopped);
while (!stopped) {
try poller.poll();
}
try nosuspend await frame;
}
// pub fn main() !void {
// _ = try windows.WSAStartup(2, 2);
// defer windows.WSACleanup() catch {};
// var poller = try Poller.init();
// defer poller.deinit();
// var stopped = false;
// var server_frame = async runBenchmarkServer(&poller, &stopped);
// var client_frame = async runBenchmarkClient(&poller, &stopped);
// while (!stopped) {
// try poller.poll();
// }
// try nosuspend await server_frame;
// try nosuspend await client_frame;
// }
| https://raw.githubusercontent.com/lithdew/afd/af5146e99443705ff5b54af8fdd88e1cd887722a/main.zig |
// This file originates from https://github.com/silversquirl/deps.zig
//
// Copyright (c) 2021 silversquirl
//
// 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.
// Possible TODOs:
// - Parse source to ensure all dependencies are actually used
// - Allow multiple packages in one repo
// - Fetch packages at build time
const std = @import("std");
const builtin = @import("builtin");
update_step: std.build.Step,
b: *std.build.Builder,
dir: []const u8,
deps: std.StringArrayHashMapUnmanaged(Dep) = .{},
import_set: std.StringArrayHashMapUnmanaged(void) = .{},
const Deps = @This();
pub const Dep = union(enum) {
managed: struct { // Fully managed dependency - we download these
url: []const u8, // Git URL for the package
path: []const u8, // Path to package directory
main_path: []const u8, // Path to package main file
deps: []const []const u8, // Dependency names of this package
},
tracked: struct { // Partially managed - we add dependencies to these
main_path: []const u8, // Path to package main file
deps: []const []const u8, // Dependency names of this package
},
unmanaged: struct { // Unmanaged - we just allow these as deps of other deps
main_path: std.build.FileSource, // Path to package main file
deps: ?[]const std.build.Pkg, // Dependencies of this package
},
};
pub fn init(b: *std.build.Builder) *Deps {
const self = initNoStep(b);
const step = b.step("update", "Update all dependencies to the latest allowed version");
step.dependOn(&self.update_step);
return self;
}
pub fn initNoStep(b: *std.build.Builder) *Deps {
const dir = std.os.getenv("DEPS_ZIG_CACHE") orelse switch (builtin.os.tag) {
.windows => b.fmt("{s}\\Temp\\deps-zig", .{std.os.getenv("LOCALAPPDATA").?}),
.macos => b.fmt("{s}/Library/Caches/deps-zig", .{std.os.getenv("HOME").?}),
else => if (std.os.getenv("XDG_CACHE_HOME")) |cache|
b.fmt("{s}/deps-zig", .{cache})
else
b.fmt("{s}/.cache/deps-zig", .{std.os.getenv("HOME").?}),
};
std.fs.cwd().makeDir(dir) catch {};
var dirh = std.fs.cwd().openDir(dir, .{}) catch |err| {
std.debug.print("Could not open packages dir '{}': {s}\n", .{ std.fmt.fmtSliceEscapeLower(dir), @errorName(err) });
std.os.exit(1);
};
defer dirh.close();
// Purposefully leak the file descriptor - it will be unlocked when the process exits
_ = dirh.createFile(".lock", .{ .lock = .Exclusive, .lock_nonblocking = true }) catch |err| {
std.debug.print("Failed to aqcuire package lock: {s}\n", .{@errorName(err)});
std.os.exit(1);
};
const self = b.allocator.create(Deps) catch unreachable;
self.* = .{
.update_step = std.build.Step.init(.custom, "update-deps", b.allocator, makeUpdate),
.b = b,
.dir = dir,
};
return self;
}
pub fn addTo(self: Deps, step: *std.build.LibExeObjStep) void {
var it = self.deps.iterator();
while (it.next()) |entry| {
step.addPackage(self.createPkg(entry.key_ptr.*, entry.value_ptr.*));
}
}
fn createPkg(self: Deps, name: []const u8, dependency: Dep) std.build.Pkg {
return switch (dependency) {
.managed => |dep| .{
.name = name,
.path = .{ .path = dep.main_path },
.dependencies = self.createPkgDeps(dep.deps),
},
.tracked => |dep| .{
.name = name,
.path = .{ .path = dep.main_path },
.dependencies = self.createPkgDeps(dep.deps),
},
.unmanaged => |dep| .{
.name = name,
.path = dep.main_path,
.dependencies = dep.deps,
},
};
}
fn createPkgDeps(self: Deps, dep_names: []const []const u8) ?[]const std.build.Pkg {
if (dep_names.len == 0) return null;
const deps = self.b.allocator.alloc(std.build.Pkg, dep_names.len) catch unreachable;
var i: usize = 0;
for (dep_names) |dname| {
if (self.deps.get(dname)) |ddep| {
deps[i] = self.createPkg(dname, ddep);
i += 1;
}
// If we don't have the dep, ignore it and let the compiler error
}
return deps[0..i];
}
pub fn add(self: *Deps, url: []const u8, version: []const u8) void {
const name = trimEnds(
std.fs.path.basenamePosix(url),
&.{"zig-"},
&.{ ".git", ".zig", "-zig" },
);
const path = self.fetchPkg(name, url, version);
const main_file = blk: {
var dirh = std.fs.cwd().openDir(path, .{}) catch {
std.debug.print("Failed to open package dir: {s}\n", .{path});
std.os.exit(1);
};
for ([_][]const u8{
self.b.fmt("{s}.zig", .{name}),
"main.zig",
self.b.fmt("src{c}{s}.zig", .{ std.fs.path.sep, name }),
"src" ++ [_]u8{std.fs.path.sep} ++ "main.zig",
}) |p| {
if (dirh.access(p, .{})) |_| {
dirh.close();
break :blk p;
} else |_| {}
}
dirh.close();
std.debug.print("Could not find package entrypoint, attempted {s}.zig, main.zig, src{c}{[0]s}.zig and src{[1]c}main.zig\n", .{ name, std.fs.path.sep });
std.os.exit(1);
};
const main_path = std.fs.path.join(self.b.allocator, &.{ path, main_file }) catch unreachable;
const deps = self.parsePackageDeps(main_path) catch |err| switch (err) {
error.InvalidSyntax => &[_][]const u8{},
else => {
std.debug.print("Failed to parse package dependencies for {s}: {s}\n", .{ main_file, @errorName(err) });
std.os.exit(1);
},
};
const dep = Dep{ .managed = .{
.url = url,
.path = path,
.main_path = main_path,
.deps = deps,
} };
if (self.deps.fetchPut(self.b.allocator, name, dep) catch unreachable) |_| {
std.debug.print("Duplicate dependency '{s}'\n", .{std.fmt.fmtSliceEscapeLower(name)});
std.os.exit(1);
}
}
pub fn addPackagePath(self: *Deps, name: []const u8, main_path: []const u8) void {
const deps = self.parsePackageDeps(main_path) catch |err| switch (err) {
error.InvalidSyntax => &[_][]const u8{},
else => {
std.debug.print("Failed to parse package dependencies for {s}: {s}\n", .{ name, @errorName(err) });
std.os.exit(1);
},
};
const dep = Dep{ .tracked = .{
.main_path = main_path,
.deps = deps,
} };
if (self.deps.fetchPut(self.b.allocator, name, dep) catch unreachable) |_| {
std.debug.print("Duplicate dependency '{s}'\n", .{std.fmt.fmtSliceEscapeLower(name)});
std.os.exit(1);
}
}
pub fn addPackage(self: *Deps, package: std.build.Pkg) void {
const dep = Dep{ .unmanaged = .{
.main_path = package.path,
.deps = package.dependencies,
} };
if (self.deps.fetchPut(self.b.allocator, package.name, dep) catch unreachable) |_| {
std.debug.print("Duplicate dependency '{s}'\n", .{std.fmt.fmtSliceEscapeLower(package.name)});
std.os.exit(1);
}
}
fn fetchPkg(self: Deps, name: []const u8, url: []const u8, version: []const u8) []const u8 {
const path = self.b.allocator.alloc(u8, self.dir.len + 1 + url.len + 1 + version.len) catch unreachable;
// Base dir
var i: usize = 0;
std.mem.copy(u8, path[i..], self.dir);
i += self.dir.len;
// Path separator
path[i] = std.fs.path.sep;
i += 1;
// Encoded URL (/ replaced with : so it's a valid path)
std.mem.copy(u8, path[i..], url);
std.mem.replaceScalar(u8, path[i .. i + url.len], '/', ':');
i += url.len;
// Version separator
path[i] = '@';
i += 1;
// Version
std.mem.copy(u8, path[i..], version);
i += version.len;
std.debug.assert(i == path.len);
// If we don't have the dep already, clone it
std.fs.cwd().access(path, .{}) catch self.updateDep(name, path, url, version);
return path;
}
fn parsePackageDeps(self: *Deps, main_file: []const u8) ![]const []const u8 {
defer self.import_set.clearRetainingCapacity();
var npkg = try self.collectImports(std.fs.cwd(), main_file);
const pkgs = try self.b.allocator.alloc([]const u8, npkg);
for (self.import_set.keys()) |key| {
if (isPkg(key)) {
npkg -= 1;
pkgs[npkg] = key;
}
}
return pkgs;
}
fn collectImports(self: *Deps, dir: std.fs.Dir, import: []const u8) CollectImportsError!usize {
const data = dir.readFileAllocOptions(self.b.allocator, import, 4 << 30, null, 1, 0) catch |err| switch (err) {
error.FileTooBig => {
// If you have a 4GiB source file, you have a problem
// However, we probably shouldn't outright error in this situation, so instead we'll warn and skip this file
std.debug.print("Could not parse exceptionally large source file '{s}', skipping\n", .{std.fmt.fmtSliceEscapeLower(import)});
return 0;
},
else => |e| return e,
};
var subdir = try dir.openDir(std.fs.path.dirname(import) orelse ".", .{});
defer subdir.close();
var toks = std.zig.Tokenizer.init(data);
var npkg: usize = 0;
while (true) {
const tok = toks.next();
if (tok.tag == .eof) break;
if (tok.tag == .builtin and std.mem.eql(u8, data[tok.loc.start..tok.loc.end], "@import")) {
if (toks.next().tag != .l_paren) return error.InvalidSyntax;
const name_tok = toks.next();
if (name_tok.tag != .string_literal) return error.InvalidSyntax;
if (toks.next().tag != .r_paren) return error.InvalidSyntax;
const name = std.zig.string_literal.parseAlloc(
self.b.allocator,
data[name_tok.loc.start..name_tok.loc.end],
) catch |err| switch (err) {
error.InvalidStringLiteral => return error.InvalidSyntax,
else => |e| return e,
};
if (try self.import_set.fetchPut(self.b.allocator, name, {})) |_| {
// Do nothing, the entry is already in the set
} else if (isPkg(name)) {
npkg += 1;
} else if (std.mem.endsWith(u8, name, ".zig")) {
npkg += try self.collectImports(subdir, name);
}
}
}
return npkg;
}
const CollectImportsError =
std.fs.Dir.OpenError ||
std.fs.File.OpenError ||
std.fs.File.ReadError ||
std.fs.File.SeekError ||
std.mem.Allocator.Error ||
error{InvalidSyntax};
fn makeUpdate(step: *std.build.Step) !void {
const self = @fieldParentPtr(Deps, "update_step", step);
var it = self.deps.iterator();
while (it.next()) |entry| {
switch (entry.value_ptr.*) {
.managed => |dep| {
const version_idx = 1 + std.mem.lastIndexOfScalar(u8, dep.path, '@').?;
const version = dep.path[version_idx..];
self.updateDep(entry.key_ptr.*, dep.path, dep.url, version);
},
else => {},
}
}
}
fn updateDep(self: Deps, name: []const u8, path: []const u8, url: []const u8, version: []const u8) void {
std.fs.cwd().access(path, .{}) catch self.exec(&.{
"git",
"clone",
"--depth=1",
"--no-single-branch",
"--shallow-submodules",
"--",
url,
path,
}, null);
self.exec(&.{ "git", "fetch", "--all", "-Ppqt" }, path);
// Check if there are changes - we don't want to clobber them
if (self.execOk(&.{ "git", "diff", "--quiet", "HEAD" }, path)) {
// Clean; check if version is a branch
if (self.execOk(&.{
"git",
"show-ref",
"--verify",
"--",
self.b.fmt("refs/remotes/origin/{s}", .{version}),
}, path)) {
// It is, so switch to it and pull
self.exec(&.{ "git", "switch", "-q", "--", version }, path);
self.exec(&.{ "git", "pull", "-q", "--ff-only" }, path);
} else {
// It isn't, check out detached
self.exec(&.{ "git", "switch", "-dq", "--", version }, path);
}
} else {
// Dirty; print a warning
std.debug.print("WARNING: package {s} contains uncommitted changes, not attempting to update\n", .{name});
}
}
fn isPkg(name: []const u8) bool {
if (std.mem.endsWith(u8, name, ".zig")) return false;
if (std.mem.eql(u8, name, "std")) return false;
if (std.mem.eql(u8, name, "root")) return false;
return true;
}
/// Remove each prefix, then each suffix, in order
fn trimEnds(haystack: []const u8, prefixes: []const []const u8, suffixes: []const []const u8) []const u8 {
var s = haystack;
for (prefixes) |prefix| {
if (std.mem.startsWith(u8, s, prefix)) {
s = s[prefix.len..];
}
}
for (suffixes) |suffix| {
if (std.mem.endsWith(u8, s, suffix)) {
s = s[0 .. s.len - suffix.len];
}
}
return s;
}
fn exec(self: Deps, argv: []const []const u8, cwd: ?[]const u8) void {
if (!self.execInternal(argv, cwd, .Inherit)) {
std.debug.print("Command failed: {s}", .{argv[0]});
for (argv[1..]) |arg| {
std.debug.print(" {s}", .{arg});
}
std.debug.print("\n", .{});
std.os.exit(1);
}
}
fn execOk(self: Deps, argv: []const []const u8, cwd: ?[]const u8) bool {
return self.execInternal(argv, cwd, .Ignore);
}
fn execInternal(self: Deps, argv: []const []const u8, cwd: ?[]const u8, io: std.ChildProcess.StdIo) bool {
const child = std.ChildProcess.init(argv, self.b.allocator) catch unreachable;
defer child.deinit();
child.cwd = cwd;
child.stdin_behavior = .Ignore;
child.stdout_behavior = io;
child.stderr_behavior = io;
child.env_map = self.b.env_map;
const term = child.spawnAndWait() catch |err| {
std.debug.print("Unable to spawn {s}: {s}\n", .{ argv[0], @errorName(err) });
return false;
};
switch (term) {
.Exited => |code| if (code != 0) {
return false;
},
.Signal, .Stopped, .Unknown => {
return false;
},
}
return true;
}
| https://raw.githubusercontent.com/silversquirl/deps.zig/793f3fe2430271592590f523e99614bf215ddb5b/Deps.zig |
const std = @import("std");
const ArrayList = std.ArrayList;
const print = std.debug.print;
const Task = struct {
id: u32,
name: []const u8,
done: bool = false,
};
pub const App = struct {
task_list: ArrayList(Task),
next_id: u32,
pub fn init(allocator: std.mem.Allocator) App {
var task_list = ArrayList(Task).init(allocator);
var app = App{
.task_list = task_list,
.next_id = 1,
};
return app;
}
pub fn deinit(self: *App) void {
self.task_list.deinit();
}
// TODO: Number overflow
fn getId(self: *App) u32 {
var n = self.*.next_id;
self.*.next_id += 1;
return n;
}
pub fn add(self: *App, name: []const u8) void {
if (name.len == 0) {
print("Missing task name.\n", .{});
return;
}
var new_task = Task{ .name = name, .id = self.*.getId() };
self.task_list.append(new_task) catch {
print("\nError adding task. Not enough memory.\n", .{});
};
}
pub fn list(self: *App) void {
print("\n == Task list ==\n", .{});
print("ID\tNAME\tDONE\n", .{});
for (self.*.task_list.items) |item| {
var status = if (item.done) "done" else "pending";
print("{d}\t{s}\t{s}\n", .{ item.id, item.name, status });
}
print("\n", .{});
}
pub fn remove(self: *App, id: u32) void {
var index_to_remove: ?usize = undefined;
for (self.*.task_list.items, 0..) |item, index| {
if (item.id == id) {
index_to_remove = index;
}
}
if (index_to_remove == undefined) {
print("Invalid id.\n", .{});
return;
}
_ = self.*.task_list.orderedRemove(index_to_remove.?);
}
pub fn rename(self: *App, id: u32, new_name: []const u8) void {
for (self.*.task_list.items, 0..) |item, index| {
if (item.id == id) {
self.*.task_list.items[index].name = new_name;
return;
}
}
print("Id not found.\n", .{});
}
pub fn set(self: *App, id: u32, status: bool) void {
for (self.*.task_list.items, 0..) |item, index| {
if (item.id == id) {
self.*.task_list.items[index].done = status;
return;
}
}
print("Id not found.\n", .{});
}
pub fn help(self: *App) void {
_ = self;
print("{s}\n\n", .{
\\ Commands:
\\ list -> List all tasks
\\ add {name} -> Create new task with name
\\ remove {id} -> Remove task by id
\\ set {id} {status} -> Update task status(pending | done) by id
\\ rename {id} {name} -> Rename task by id
\\ help -> Display available commands
\\ exit -> Exit app
});
}
};
| https://raw.githubusercontent.com/cauesmelo/zig-todo/89745ced111bd523a350c810b57049985fd83c3d/app.zig |
const std = @import("std");
const lib = @import("lib.zig");
pub fn main() !void {
// const n: u16 = 0b10110000_00001111;
// const arr: [2]u8 = @bitCast(n);
// std.debug.print("{b} {b}\n", .{ arr[0], arr[1] });
// above works
const n2: u4 = 0b1011;
var arr2: [2]u2 = undefined;
const n = @typeInfo(@TypeOf(n2)).Int.bits / 8 + 1;
const I = @Type(.{ .Int = .{ .bits = n * 8, .signedness = .unsigned } });
// const I = u8;
var bytes: [n]u8 = @bitCast(@as(I, n2));
const s = std.PackedIntSlice(u2).init(&bytes, 2);
arr2[0] = s.get(0);
arr2[1] = s.get(1);
// const arr2: [2]u2 = @bitCast(n2);
std.debug.print("{b} {b}\n", .{ arr2[0], arr2[1] });
const n3: u6 = 0b101101;
const arr3: [3]u2 = lib.bitCastArray(u2, n3);
std.debug.print("{b} {b} {b}\n", .{ arr3[0], arr3[1], arr3[2] });
const TwoBits = enum(u2) {
Zero = 0b00,
One = 0b01,
Two = 0b10,
Three = 0b11,
};
const num: u6 = 0b10_11_01;
const arr: [3]TwoBits = lib.bitCastArray(TwoBits, num);
std.debug.print("{} {} {}\n", .{ arr[0], arr[1], arr[2] });
// TwoBits.One TwoBits.Three TwoBits.Two
const field: u64 = 0b11111111_11111111_00000000_00000000_00000000_00000000_00000000_10000001;
const board: [8]u8 = lib.bitCastArray(u8, field);
std.debug.print("0:{b:08}\n1:{b:08}\n2:{b:08}\n3:{b:08}\n4:{b:08}\n5:{b:08}\n6:{b:08}\n7:{b:08}\n", .{
board[0],
board[1],
board[2],
board[3],
board[4],
board[5],
board[6],
board[7],
});
}
| https://raw.githubusercontent.com/PierreV23/zig-chess-bits/3636073a1575141948c9c71bb935acbe2335a0cc/ding.zig |
const std = @import("std");
const Pair = struct {
x: usize,
y: usize,
};
pub fn Matrix(comptime T: type, width: usize, height: usize) type {
return struct {
const Self = @This();
data: [height * width]T,
pub fn width(self: Self) usize {
return width;
}
pub fn height(self: Self) usize {
return height;
}
pub fn reset(self: *Self, val: T) void {
std.mem.set(T, self.data[0..], val);
}
pub fn get(self: Self, x: usize, y: usize) T {
const i = self.idx(x, y);
return self.data[i];
}
pub fn set(self: *Self, x: usize, y: usize, val: T) void {
const i = self.idx(x, y);
self.data[i] = val;
}
fn idx(self: Self, x: usize, y: usize) usize {
std.debug.assert(x < width);
std.debug.assert(y < height);
return x + y * width;
}
fn pair(self: Self, i: usize) Pair {
return Pair{
.x = i % width,
.y = i / width,
};
}
};
}
const origin = Pair{ .x = 10000, .y = 10000 };
fn manhattanDistance(lhs: Pair, rhs: Pair) usize {
return std.math.absCast(@bitCast(isize, lhs.x -% rhs.x)) + std.math.absCast(@bitCast(isize, lhs.y -% rhs.y));
}
pub fn main() !void {
const file = try std.fs.cwd().openRead("03.input");
var wire0 = try std.heap.page_allocator.create(Matrix(u32, origin.x * 2, origin.y * 2));
defer std.heap.page_allocator.destroy(wire0);
wire0.reset(0);
var line_buf: [2000]u8 = undefined;
var file_in_stream = file.inStream();
{
const line0 = try file_in_stream.stream.readUntilDelimiterOrEof(line_buf[0..], '\n');
var x: usize = origin.x;
var y: usize = origin.y;
var step0: u32 = 0;
var inner_buf: [10]u8 = undefined;
var line_stream = std.io.SliceInStream.init(line0.?);
while (line_stream.stream.readUntilDelimiterOrEof(inner_buf[0..], ',')) |segment| {
if (segment == null) break;
var value = try std.fmt.parseUnsigned(u32, segment.?[1..], 10);
while (value > 0) {
step0 += 1;
value -= 1;
switch (segment.?[0]) {
'R' => x += 1,
'L' => x -= 1,
'U' => y += 1,
'D' => y -= 1,
else => unreachable,
}
wire0.set(x, y, step0);
}
} else |err| return err;
}
var min_d: usize = std.math.maxInt(usize);
var min_steps: usize = std.math.maxInt(usize);
{
const line1 = try file_in_stream.stream.readUntilDelimiterOrEof(line_buf[0..], '\n');
var x: usize = origin.x;
var y: usize = origin.y;
var steps1: u32 = 0;
var inner_buf: [10]u8 = undefined;
var line_stream = std.io.SliceInStream.init(line1.?);
while (line_stream.stream.readUntilDelimiterOrEof(inner_buf[0..], ',')) |segment| {
if (segment == null) break;
var value = try std.fmt.parseUnsigned(u32, segment.?[1..], 10);
while (value > 0) {
steps1 += 1;
value -= 1;
switch (segment.?[0]) {
'R' => x += 1,
'L' => x -= 1,
'U' => y += 1,
'D' => y -= 1,
else => unreachable,
}
const steps0 = wire0.get(x, y);
if (steps0 > 0) {
min_steps = std.math.min(min_steps, steps0 + steps1);
min_d = std.math.min(min_d, manhattanDistance(origin, .{ .x = x, .y = y }));
}
}
} else |err| return err;
}
std.debug.warn("Shortest distance: {}\n", min_d);
std.debug.warn("Shortest steps: {}\n", min_steps);
}
| https://raw.githubusercontent.com/fengb/advent/dc741e527899cb22630d200bf1883ffd9356d01e/03.zig |
const std = @import("std");
const os = std.os;
const print = std.debug.print;
pub fn main() !void {
var buf: [256]u8 = undefined;
var fba = std.heap.FixedBufferAllocator.init(&buf);
var allocator = &fba.allocator;
const cwd = try allocator.alloc(u8, 256);
defer allocator.free(cwd);
const z = try os.getcwd(cwd);
print("{}\n", .{z});
}
| https://raw.githubusercontent.com/jordanorelli/learn-zig/83479b2652b3326d482645925fc2101626d00dfd/pwd.zig |
const std = @import("std");
const warn = std.debug.warn;
const mem = std.mem;
const os = std.os;
const io = std.io;
const ArrayList = std.ArrayList;
const Map = std.AutoHashMap;
const globals = @import("globals.zig");
const atof = @import("atof.zig");
use @import("utils.zig");
pub const TokenType = enum {
// single character
LEFT_PAREN,
RIGHT_PAREN,
LEFT_BRACE,
RIGHT_BRACE,
COMMA,
DOT,
MINUS,
PLUS,
SEMICOLON,
SLASH,
STAR,
// one or two characters
BANG, BANG_EQUAL,
EQUAL, EQUAL_EQUAL,
GREATER, GREATER_EQUAL,
LESS, LESS_EQUAL,
// literals
IDENTIFIER, STRING, NUMBER,
// keywords
AND, CLASS, ELSE, FALSE, FUN, FOR, IF, NIL, OR,
PRINT, RETURN, SUPER, THIS, TRUE, VAR, WHILE,
EOF
};
pub const Literal = union(enum) {
String: []const u8,
Number: f64,
// TODO(cgag): these are only used in parser.zig,
// we need to etiehr fully seperate this and the parser,
// or usnify them
Bool: bool,
// TODO(cgag): unused value
Nil: bool,
};
pub const Token = struct {
type: TokenType,
lexeme: []const u8,
literal: ?Literal,
line: u32,
pub fn init(token_type: TokenType,
lexeme: []const u8,
literal: ?Literal,
line: u32) Token {
return Token {
.type = token_type,
.lexeme = lexeme,
.literal = literal,
.line = line,
};
}
// caller needs to free.
pub fn to_string(self: *Token, allocator: *mem.Allocator) ![]const u8 {
const buf = try std.fmt.allocPrint(
allocator,
"type: {}, lexeme: {}",
@tagName(self.type), self.lexeme
);
errdefer allocator.free(buf);
return buf;
}
};
pub const Scanner = struct {
source: []const u8,
tokens: ArrayList(Token),
start: u32,
current: u32,
line: u32,
keywords: Map([]const u8, TokenType),
pub fn init(allocator: *mem.Allocator, source: []const u8) !Scanner {
var keywords = Map([]const u8, TokenType).init(allocator);
_ = try keywords.put("and", TokenType.AND);
_ = try keywords.put("class", TokenType.CLASS);
_ = try keywords.put("else", TokenType.ELSE);
_ = try keywords.put("false", TokenType.FALSE);
_ = try keywords.put("for", TokenType.FOR);
_ = try keywords.put("fun", TokenType.FUN);
_ = try keywords.put("if", TokenType.IF);
_ = try keywords.put("nil", TokenType.NIL);
_ = try keywords.put("or", TokenType.OR);
_ = try keywords.put("print", TokenType.PRINT);
_ = try keywords.put("return", TokenType.RETURN);
_ = try keywords.put("super", TokenType.SUPER);
_ = try keywords.put("this", TokenType.THIS);
_ = try keywords.put("true", TokenType.TRUE);
_ = try keywords.put("var", TokenType.VAR);
_ = try keywords.put("while", TokenType.WHILE);
return Scanner {
.source = source,
.tokens = ArrayList(Token).init(allocator),
.start = 0,
.current = 0,
.line = 0,
.keywords = keywords,
};
}
pub fn deinit(self: *Scanner) void {
self.keywords.deinit();
// TODO(cgag): maybe this should be here
self.tokens.deinit();
}
pub fn scan(self: *Scanner) !ArrayList(Token) {
// TODO(cgag): actually do the scanning
while (!self.is_at_end()) {
self.start = self.current;
try self.scan_token();
}
try self.tokens.append(Token.init(TokenType.EOF, "", null, self.line));
return self.tokens;
}
fn scan_token(self: *Scanner) !void {
var c = self.advance();
switch (c) {
'(' => { try self.add_simple_token(TokenType.LEFT_PAREN); },
')' => { try self.add_simple_token(TokenType.RIGHT_PAREN); },
'{' => { try self.add_simple_token(TokenType.LEFT_BRACE); },
'}' => { try self.add_simple_token(TokenType.RIGHT_BRACE); },
',' => { try self.add_simple_token(TokenType.COMMA); },
'.' => { try self.add_simple_token(TokenType.DOT); },
'-' => { try self.add_simple_token(TokenType.MINUS); },
'+' => { try self.add_simple_token(TokenType.PLUS); },
';' => { try self.add_simple_token(TokenType.SEMICOLON); },
'*' => { try self.add_simple_token(TokenType.STAR); },
'!' => {
var token = if (self.match('=')) TokenType.BANG_EQUAL else TokenType.BANG;
try self.add_simple_token(token);
},
'=' => {
var token = if (self.match('=')) TokenType.EQUAL_EQUAL else TokenType.EQUAL;
try self.add_simple_token(token);
},
'<' => {
var token = if (self.match('=')) TokenType.LESS_EQUAL else TokenType.LESS;
try self.add_simple_token(token);
},
'>' => {
var token = if (self.match('=')) TokenType.GREATER_EQUAL else TokenType.GREATER;
try self.add_simple_token(token);
},
// comments and whitespace
'/' => {
if (self.match('/')) {
// comment goes until end of the line
while (self.peek() != '\n' and !self.is_at_end()) {
_ = self.advance();
}
} else {
try self.add_simple_token(TokenType.SLASH);
}
},
' ' => {},
'\r' => {},
'\t' => {},
'\n' => { self.line += 1; },
'"' => { try self.string(); },
'0'...'9' => {
_ = try self.number();
},
else => {
if (is_alpha(c)) {
try self.identifier_or_keyword();
} else {
warn("unexpected char: {c}\n", c);
err(self.line, "Unexpected character");
}
},
}
}
fn string(self: *Scanner) !void {
while (self.peek() != '"' and !self.is_at_end()) {
if (self.peek() == '\n') { self.line += 1; }
_ = self.advance();
}
if (self.is_at_end()) {
err(self.line, "unterminated string");
return;
}
// consume closing ", TODO(cgag): assert(match('"'))?
_ = self.advance();
const lit = Literal { .String = self.source[self.start+1..self.current-1] };
try self.add_token(TokenType.STRING, lit);
}
fn identifier_or_keyword(self: *Scanner) !void {
while (is_alphanumeric(self.peek())) {
_ = self.advance();
}
const text = self.source[self.start..self.current];
// check for reserved words
// TODO(cgag): lowercase??
if (self.keywords.get(text)) |reserved_token_type_kv| {
try self.add_simple_token(reserved_token_type_kv.value);
} else {
try self.add_simple_token(TokenType.IDENTIFIER);
}
}
fn number(self: *Scanner) !void {
while (is_digit(self.peek())) {
_ = self.advance();
}
if (self.peek() == '.') {
// consume '.'
_ = self.advance();
while (is_digit(self.peek())) {
_ = self.advance();
}
}
try self.add_token(
TokenType.NUMBER,
Literal { .Number = try atof.atof(self.source[self.start..self.current]) },
);
}
fn is_at_end(self: *Scanner) bool {
return self.current >= self.source.len;
}
fn advance(self: *Scanner) u8 {
self.current += 1;
return self.source[self.current - 1];
}
fn match(self: *Scanner, char: u8) bool {
if (self.is_at_end()) return false;
if (self.source[self.current] != char) return false;
self.current += 1;
return true;
}
fn peek(self: *Scanner) u8 {
if (self.is_at_end()) { return 0; }
return self.source[self.current];
}
fn add_simple_token(self: *Scanner, token_type: TokenType) !void {
try self.add_token(token_type, null);
}
fn add_token(self: *Scanner, token_type: TokenType, literal: ?Literal) !void {
var text = self.source[self.start..self.current];
try self.tokens.append(Token.init(token_type, text, literal, self.line));
}
};
fn is_digit(c: u8) bool {
return c >= '0' and c <= '9';
}
fn is_alpha(c: u8) bool {
return (c >= 'a' and c <= 'z') or
(c >= 'A' and c <= 'Z') or
(c == '_');
}
fn is_alphanumeric(c: u8) bool {
return is_alpha(c) or is_digit(c);
}
| https://raw.githubusercontent.com/cgag/crafting-interpreters-zig/8be458bd2994e9194b022e8a6439dce3455604e9/lex.zig |
const std = @import("std");
const clap = @import("clap");
const debug = std.debug;
const io = std.io;
const decompress = @import("decompress.zig");
pub fn main() !void {
var direct_allocator = std.heap.DirectAllocator.init();
var allocator = &direct_allocator.allocator;
defer direct_allocator.deinit();
// First we specify what parameters our program can take.
const params = []clap.Param(u8){
clap.Param(u8).flag('h', clap.Names.both("help")),
clap.Param(u8).option('i', clap.Names.both("input")),
clap.Param(u8).option('o', clap.Names.both("output")),
};
// We then initialize an argument iterator. We will use the OsIterator as it nicely
// wraps iterating over arguments the most efficient way on each os.
var iter = clap.args.OsIterator.init(allocator);
defer iter.deinit();
// Consume the exe arg.
const exe = try iter.next();
// Finally we initialize our streaming parser.
var parser = clap.StreamingClap(u8, clap.args.OsIterator).init(params, &iter);
var input: ?[]const u8 = null;
var output: ?[]const u8 = null;
// Because we use a streaming parser, we have to consume each argument parsed individually.
while (try parser.next()) |arg| {
// arg.param will point to the parameter which matched the argument.
switch (arg.param.id) {
'h' => {
debug.warn("Help!\n");
return;
},
'i' => input = arg.value,
'o' => output = arg.value.?,
else => unreachable,
}
}
if (output) |_| {
} else {
output = try std.mem.join(allocator, ".", []const []const u8{input.?, "out"});
}
const stdout_file = try std.io.getStdOut();
const compressed = try io.readFileAlloc(allocator, input.?);
var decompressor: decompress.Decompressor = undefined;
const decompressed = try decompressor.decompressAlloc(allocator, compressed);
try io.writeFile(output.?, decompressed);
debug.warn("Input: {}\nOutput: {}\n", input, output);
}
| https://raw.githubusercontent.com/BarabasGitHub/LZig4/23bdba8facb7e7def308d70610bc033a4ecd1974/main.zig |
pub fn main() u8 {
return 0;
}
| https://raw.githubusercontent.com/joachimschmidt557/zbase/907591a9f0bbf47e4e59c0bbe17e3fae69b84516/true.zig |
const std = @import("std");
pub usingnamespace @import("utils/benchmark.zig");
pub usingnamespace @import("utils/grid.zig");
pub const Map = std.AutoHashMap; | https://raw.githubusercontent.com/fjebaker/advent-of-code-2022/92aa3b1f9fc946e9946b4cb02f0737667fd06ea0/util.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const List = std.ArrayList;
const Map = std.AutoHashMap;
const StrMap = std.StringHashMap;
const BitSet = std.DynamicBitSet;
const Str = []const u8;
const util = @import("util.zig");
const gpa = util.gpa;
const data = @embedFile("../01.txt");
pub fn main() !void {
var count: u32 = 0;
var window: [3]i64 = .{ 0, 0, 0 };
var part1: u32 = 0;
var part2: u32 = 0;
var lines = tokenize(u8, data, "\r\n");
while (lines.next()) |line| {
const num = parseInt(i64, line, 10) catch unreachable;
if (count >= 1 and num > window[2]) {
part1 += 1;
}
if (count >= 3 and num > window[0]) {
part2 += 1;
}
window[0] = window[1];
window[1] = window[2];
window[2] = num;
count += 1;
}
print("part1={}, part2={}\n", .{part1, part2});
}
// Useful stdlib functions
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const indexOf = std.mem.indexOfScalar;
const indexOfAny = std.mem.indexOfAny;
const indexOfStr = std.mem.indexOfPosLinear;
const lastIndexOf = std.mem.lastIndexOfScalar;
const lastIndexOfAny = std.mem.lastIndexOfAny;
const lastIndexOfStr = std.mem.lastIndexOfLinear;
const trim = std.mem.trim;
const sliceMin = std.mem.min;
const sliceMax = std.mem.max;
const parseInt = std.fmt.parseInt;
const parseFloat = std.fmt.parseFloat;
const min = std.math.min;
const min3 = std.math.min3;
const max = std.math.max;
const max3 = std.math.max3;
const print = std.debug.print;
const assert = std.debug.assert;
const sort = std.sort.sort;
const asc = std.sort.asc;
const desc = std.sort.desc;
| https://raw.githubusercontent.com/mattias-lundell/aoc2022/ada2a442ea5fc615944d8c96534bf8b0c5afab09/01.zig |
const std = @import("std");
const assert = std.debug.assert;
pub fn RangeTo(n: usize) type {
return struct {
idx: usize,
pub fn new() RangeTo(n) {
return .{ .idx = 0 };
}
pub fn next(self: *RangeTo(n)) ?usize {
if (self.idx >= n) {
return null;
}
var r = self.idx;
self.idx += 1;
return r;
}
};
}
pub const Relu1 = struct {
pub const Param = struct {};
pub const Input = f32;
pub const Output = f32;
fn initializeParams(param: *Param, rng: *std.rand.Random) void {
// nothing
}
fn updateGradient(gradient: *Param, scale: f32, update: *Param) void {
// nothing
}
fn run(input: *Input, param: Param, output: *Output) void {
if (input > 0) {
output.* = input;
}
}
fn reverse(
input: Input,
param: Param,
delta: Output,
backprop: *Input,
gradient: *Param,
) void {
if (input > 0) {
backprop.* = delta;
}
}
};
pub fn Lin(size: usize) type {
return struct {
pub const Param = struct { weights: [size]f32, bias: f32 };
pub const Input = [size]f32;
pub const Output = f32;
fn initializeParams(param: *Param, rng: *std.rand.Random) void {
var iter = RangeTo(size).new();
while (iter.next()) |i| {
param.weights[i] = rng.float(f32) * 2 - 1;
}
param.bias = rng.float(f32) * 4 - 2;
}
fn updateGradient(gradient: *Param, scale: f32, update: *Param) void {
var iter = RangeTo(size).new();
while (iter.next()) |i| {
gradient.weights[i] += scale * update.weights[i];
}
gradient.bias += scale * update.bias;
}
fn run(input: Input, param: Param, output: *Output) void {
for (input) |x, i| {
output.* += x * param.weights[i];
}
output.* += param.bias;
}
fn reverse(
input: Input,
param: Param,
delta: Output,
backprop: *Input, // add
gradient: *Param, // add
) void {
gradient.bias = delta;
for (input) |x, i| {
backprop.*[i] += delta * param.weights[i];
gradient.weights[i] += delta * x;
}
}
};
}
pub fn zeroed(comptime T: type) T {
var x: T = undefined;
@memset(@ptrCast([*]u8, &x), 0, @sizeOf(T));
return x;
}
fn Seq2(comptime Net1: type, comptime Net2: type) type {
assert(Net1.Output == Net2.Input);
return struct {
pub const Param = struct {
first: Net1.Param,
second: Net2.Param,
};
pub const Input = Net1.Input;
pub const Output = Net2.Output;
pub fn initializeParams(param: *Param, rng: *std.rand.Random) void {
Net1.initializeParams(¶m.first, rng);
Net2.initializeParams(¶m.second, rng);
}
pub fn updateGradient(gradient: *Param, scale: f32, update: *Param) void {
Net1.updateGradient(&gradient.first, scale, &update.first);
Net2.updateGradient(&gradient.second, scale, &update.second);
}
pub fn run(input: Input, param: Param, output: *Output) void {
var scratch: Net1.Output = zeroed(Net1.Output);
Net1.run(input, ¶m.first, &scratch);
Net2.run(scratch, ¶m.second, output);
}
pub fn reverse(
input: Input,
param: Param,
delta: Output,
backprop: *Input, // add
gradient: *Param, // add
) void {
var scratch: Net1.Output = zeroed(Net1.Output);
Net1.run(input, ¶m.first, &scratch);
var middleDelta: Net1.Output = zeroed(Net1.Output);
Net2.reverse(scratch, ¶m.second, delta, &middleDelta, &gradient.second);
Net1.reverse(input, ¶m.first, middleDelta, backprop, &gradient.first);
}
};
}
fn SeqFrom(comptime Nets: var, index: usize) type {
if (index == Nets.len - 1) {
return Nets[index];
}
return Seq2(Nets[index], SeqFrom(Nets, index + 1));
}
pub fn Seq(comptime Nets: var) type {
assert(Nets.len > 0);
return SeqFrom(Nets, 0);
}
pub fn Fan(comptime by: usize, Net: type) type {
return struct {
pub const Input = Net.Input;
pub const Output = [by]Net.Output;
pub const Param = [by]Net.Param;
pub fn initializeParams(param: *Param, rng: *std.rand.Random) void {
var iter = RangeTo(by).new();
while (iter.next()) |i| {
Net.initializeParams(¶m[i], rng);
}
}
pub fn updateGradient(gradient: *Param, scale: f32, update: *Param) void {
var iter = RangeTo(by).new();
while (iter.next()) |i| {
Net.updateGradient(&gradient.*[i], scale, &update.*[i]);
}
}
pub fn run(input: Input, param: Param, output: *Output) void {
var iter = RangeTo(by).new();
while (iter.next()) |i| {
Net.run(input, param[i], &output[i]);
}
}
pub fn reverse(
input: Input,
param: Param,
delta: Output,
backprop: *Input, // add
gradient: *Param, // add
) void {
var iter = RangeTo(by).new();
while (iter.next()) |i| {
Net.reverse(input, param[i], delta[i], backprop, &gradient[i]);
}
}
};
}
pub fn Relu(comptime in: usize, comptime out: usize) type {
return Fan(out, Seq(.{ Lin(in), Relu1 }));
}
pub fn LossSum(comptime LossNet: type) type {
assert(LossNet.Output == f32);
return struct {
pub const Input = []LossNet.Input;
pub const Output = f32;
pub const Param = LossNet.Param;
pub fn initializeParams(param: *Param, rng: *std.rand.Random) void {
LossNet.initializeParams(param, rng);
}
pub fn updateGradient(gradient: *Param, scale: f32, update: *Param) void {
LossNet.updateGradient(gradient, scale, update);
}
pub fn run(input: Input, param: Param, output: *Output) void {
var loss: f32 = 0.0;
for (input) |item, index| {
var lossAdd: f32 = 0.0;
LossNet.run(input[index], param, &lossAdd);
loss += lossAdd;
}
output.* += loss;
}
pub fn reverse(
input: Input,
param: Param,
delta: Output,
backprop: *Input, // add
gradient: *Param, // add
) void {
// TODO: backprop is not set; should we have non-differentiable inputs?
for (input) |_, index| {
var discardInputDelta = zeroed(LossNet.Input);
// here we rely on gradients being added, instead of set:
LossNet.reverse(input[index], param, delta, &discardInputDelta, gradient);
}
}
};
}
pub fn TrainingExample(comptime T: type, comptime G: type) type {
return struct {
input: T,
target: G,
};
}
pub fn LossL2(comptime Net: type) type {
return struct {
pub const Input = TrainingExample(Net.Input, f32);
pub const Output = f32;
pub const Param = Net.Param;
pub fn initializeParams(param: *Param, rng: *std.rand.Random) void {
Net.initializeParams(param, rng);
}
pub fn updateGradient(gradient: *Param, scale: f32, update: *Param) void {
Net.updateGradient(gradient, scale, update);
}
pub fn run(input: Input, param: Param, output: *Output) void {
var predicted = [1]f32{0};
Net.run(input.input, param, &predicted);
var loss = (predicted[0] - input.target) * (predicted[0] - input.target);
output.* += loss;
}
pub fn reverse(
input: Input,
param: Param,
delta: Output,
backprop: *Input, // add
gradient: *Param, // add
) void {
// 'delta' indicates how much being wrong counts.
// the amount we pass back into the previous layer is therefore based
// on how far off the current estimate is.
// So we first need to run forward to obtain a prediction:
var predicted = [1]f32{0};
Net.run(input.input, param, &predicted);
// We have: L = (pred - target)^2
// and we know dE / dL
// we want to find dpred / dL
// dE/dA = dE/dL dL/dA
// so take d/dpred of both sides:
// dL/dpred = 2(pred-target)
// so dE/dpred = dE/dL 2 (pred - target).
var adjustedDelta: Net.Output = [1]f32{2 * delta * (predicted[0] - input.target)};
var discardInputBackprop = zeroed(Net.Input);
Net.reverse(
input.input,
param,
adjustedDelta,
&discardInputBackprop,
gradient,
);
}
};
}
| https://raw.githubusercontent.com/Nathan-Fenner/zig-net/8c04ab33577bb0ec9e4d44a645560b48330d7196/net.zig |
const std = @import("std");
fn fatal(comptime fmt: []const u8, args: anytype) noreturn {
std.log.err(fmt, args);
std.process.exit(0xff);
}
fn oom(err: std.mem.Allocator.Error) noreturn {
_ = err catch {};
@panic("Out of memory");
}
const global = struct {
var arena_instance = std.heap.ArenaAllocator.init(std.heap.page_allocator);
pub const arena = arena_instance.allocator();
};
pub fn main() !void {
const cmd_args = blk: {
const all_args = try std.process.argsAlloc(global.arena);
if (all_args.len <= 1) {
std.log.err("Usage: chana DEST_PATH INCLUDE_PATH", .{});
std.process.exit(0xff);
}
break :blk all_args[1..];
};
if (cmd_args.len != 2) {
fatal("expected 2 cmdline arguments but got {}", .{cmd_args.len});
}
const dest_path = cmd_args[0];
const inc_path = cmd_args[1];
std.log.info("{s} and {s}", .{dest_path, inc_path});
const inc_dir = std.fs.cwd().openDir(inc_path, .{ .iterate = true }) catch |err|
fatal("failed to open include path '{s}' with {s}", .{inc_path, @errorName(err)});
// no need to close
try std.fs.cwd().makePath(dest_path);
const dest_dir = try std.fs.cwd().openDir(dest_path, .{});
// no need to close
try analyzeDir("", dest_dir, inc_dir);
}
fn analyzeDir(path: []const u8, dest_dir: std.fs.Dir, inc_dir: std.fs.Dir) !void {
var it = inc_dir.iterate();
while (try it.next()) |entry| {
const child_path = try std.fs.path.join(global.arena, &.{path, entry.name});
defer global.arena.free(child_path);
switch (entry.kind) {
.file => {
const sep: []const u8 = if (path.len == 0) "" else "/";
std.log.info("{s}{s}{s}", .{path, sep, entry.name});
const file = try dest_dir.createFile(child_path, .{});
defer file.close();
try analyzeFile(file.writer());
},
.directory => {
var child_dir = try inc_dir.openDir(entry.name, .{ .iterate = true });
defer child_dir.close();
try dest_dir.makeDir(child_path);
try analyzeDir(child_path, dest_dir, child_dir);
},
else => |kind| fatal("unsupported file type {s}", .{@tagName(kind)}),
}
}
}
fn analyzeFile(writer: anytype) !void {
try writer.writeAll("todo: implement analyze");
}
| https://raw.githubusercontent.com/marler8997/chana/3c432e223fdd61e07fed7c24a351bbf586dffc47/main.zig |
const assert = @import("std").debug.assert;
// goto is present, but should typically not be used.
// error-handling should instead be performed via defer.
test "goto" {
var value = false;
goto label;
value = true;
label:
assert(value == false);
}
| https://raw.githubusercontent.com/tiehuis/zig-notes/1ef776a684228ed1536ba54e405bfcbae586c95e/goto.zig |
const std = @import("std");
pub const pkgs = struct {
pub const zfetch = std.build.Pkg{
.name = "zfetch",
.path = .{ .path = "deps/zfetch/src/main.zig" },
.dependencies = &[_]std.build.Pkg{
std.build.Pkg{
.name = "hzzp",
.path = .{ .path = "deps/hzzp/src/main.zig" },
},
std.build.Pkg{
.name = "iguanaTLS",
.path = .{ .path = "deps/iguanaTLS/src/main.zig" },
},
std.build.Pkg{
.name = "network",
.path = .{ .path = "deps/zig-network/network.zig" },
},
std.build.Pkg{
.name = "uri",
.path = .{ .path = "deps/zig-uri/uri.zig" },
},
},
};
pub const zjson = std.build.Pkg{
.name = "zjson",
.path = .{ .path = "deps/zjson/src/lib.zig" },
};
pub fn addAllTo(artifact: *std.build.LibExeObjStep) void {
@setEvalBranchQuota(1_000_000);
inline for (std.meta.declarations(pkgs)) |decl| {
if (decl.is_pub and decl.data == .Var) {
artifact.addPackage(@field(pkgs, decl.name));
}
}
}
};
pub const exports = struct {
pub const ytmusic = std.build.Pkg{
.name = "ytmusic",
.path = .{ .path = "src/main.zig" },
.dependencies = &.{
pkgs.zfetch,
},
};
};
pub const base_dirs = struct {
pub const wz = "lib/wz";
};
| https://raw.githubusercontent.com/xyaman/ytmusic-zig/d7f9a07c8131a006e3d43213da208365d77cfd2f/deps.zig |
const std = @import("std");
const constants = @import("constants");
const print = std.debug.print;
const Snippet = @import("snippet").Snippet;
const Flags = @import("flags").Flags;
const FlagEval = @import("flags").FlagEval;
const validateFile = @import("modify_snippet").validateFile;
const checkFileExists = @import("modify_snippet").checkFileExists;
const handleFileNotExists = @import("create_file").handleFileNotExists;
const inlineBufferedIO = @import("write_results").inlineBufferedIO;
const writeBufferedIO = @import("write_results").writeBufferedIO;
const transformDir = @import("snippet").transformDir;
const parseCLI = @import("cli_parser").parseCLI;
pub fn main() !void {
const allocator = std.heap.c_allocator;
const flags = try parseCLI(allocator);
switch (flags.evalCmds()) {
FlagEval.file => { // => vsfragment -f <file>
try parseFileStreamOutput(allocator, flags);
},
FlagEval.file_out => { // => vsfragment -f <file> -o <file>
try parseInputWriteOutput(allocator, flags);
},
FlagEval.dir => { // => vsfragment --dir <path>
_ = try transformDir(flags.dir_path, flags.output_path);
},
FlagEval.inline_code => { // => vsfragment -c '{text}'
print("{s}", .{constants.stdout_inline});
var snippet = try Snippet.createFromString(allocator, flags.code_str, true);
snippet.setMetadata(flags.title, flags.prefix, flags.description, flags.confirmation, flags.force, flags.time);
try inlineBufferedIO(snippet);
},
FlagEval.invalid => {
try flags.printHelp();
},
}
}
pub fn parseFileStreamOutput(allocator: std.mem.Allocator, args: Flags) !void {
if (!try validateFile(allocator, args.file_path))
return;
var snippet = try Snippet.convertFileToSnippet(allocator, args.file_path, false);
snippet.setMetadata(args.title, args.prefix, args.description, args.confirmation, args.force, args.time);
try writeBufferedIO(snippet);
}
pub fn parseInputWriteOutput(allocator: std.mem.Allocator, args: Flags) !void {
print("{s}", .{constants.stdout_flags_f_o});
if (!try validateFile(allocator, args.file_path))
return;
var snippet = try Snippet.convertFileToSnippet(allocator, args.file_path, args.confirmation);
snippet.setMetadata(args.title, args.prefix, args.description, args.confirmation, args.force, args.time);
try writeBufferedIO(snippet); // - buffer snippet stdout
switch (try checkFileExists(args.output_path)) {
true => try snippet.appendSnippet(allocator, args.output_path, true),
false => try snippet.writeSnippet(args.output_path, true),
}
}
| https://raw.githubusercontent.com/kuro337/vsfragments/038752b30b0c21478eb62e5c1508f12b7e38b29c/main.zig |
const std = @import("std");
const mach = @import("mach");
const gpu = @import("gpu");
const App = @This();
pipeline: gpu.RenderPipeline,
queue: gpu.Queue,
pub fn init(app: *App, engine: *mach.Engine) !void {
const vs_module = engine.device.createShaderModule(&.{
.label = "my vertex shader",
.code = .{ .wgsl = @embedFile("vert.wgsl") },
});
const fs_module = engine.device.createShaderModule(&.{
.label = "my fragment shader",
.code = .{ .wgsl = @embedFile("frag.wgsl") },
});
// Fragment state
const blend = gpu.BlendState{
.color = .{
.operation = .add,
.src_factor = .one,
.dst_factor = .zero,
},
.alpha = .{
.operation = .add,
.src_factor = .one,
.dst_factor = .zero,
},
};
const color_target = gpu.ColorTargetState{
.format = engine.swap_chain_format,
.blend = &blend,
.write_mask = gpu.ColorWriteMask.all,
};
const fragment = gpu.FragmentState{
.module = fs_module,
.entry_point = "main",
.targets = &.{color_target},
.constants = null,
};
const pipeline_descriptor = gpu.RenderPipeline.Descriptor{
.fragment = &fragment,
.layout = null,
.depth_stencil = null,
.vertex = .{
.module = vs_module,
.entry_point = "main",
.buffers = null,
},
.multisample = .{
.count = 1,
.mask = 0xFFFFFFFF,
.alpha_to_coverage_enabled = false,
},
.primitive = .{
.front_face = .ccw,
.cull_mode = .none,
.topology = .triangle_list,
.strip_index_format = .none,
},
};
app.pipeline = engine.device.createRenderPipeline(&pipeline_descriptor);
app.queue = engine.device.getQueue();
vs_module.release();
fs_module.release();
}
pub fn deinit(_: *App, _: *mach.Engine) void {}
pub fn update(app: *App, engine: *mach.Engine) !void {
const back_buffer_view = engine.swap_chain.?.getCurrentTextureView();
const color_attachment = gpu.RenderPassColorAttachment{
.view = back_buffer_view,
.resolve_target = null,
.clear_value = std.mem.zeroes(gpu.Color),
.load_op = .clear,
.store_op = .store,
};
const encoder = engine.device.createCommandEncoder(null);
const render_pass_info = gpu.RenderPassEncoder.Descriptor{
.color_attachments = &.{color_attachment},
.depth_stencil_attachment = null,
};
const pass = encoder.beginRenderPass(&render_pass_info);
pass.setPipeline(app.pipeline);
pass.draw(3, 1, 0, 0);
pass.end();
pass.release();
var command = encoder.finish(null);
encoder.release();
app.queue.submit(&.{command});
command.release();
engine.swap_chain.?.present();
back_buffer_view.release();
}
| https://raw.githubusercontent.com/hi7/mach-template/c2e8de108b6129d72f9b430999dabc1952972870/main.zig |
const std = @import("std");
pub const Version = std.meta.Tuple(&[_]type{ usize, usize });
pub const CompileStep = struct {
pub const base_id = .install_dir;
const Self = @This();
step: std.build.Step,
builder: *std.build.Builder,
/// Version of the Java source
source_version: Version,
/// Version of the target JVM bytecode
target_version: Version,
/// Name of the jar (name.jar)
name: []const u8,
/// Bin path
output_path: []const u8,
/// Classpath
classpath: std.ArrayList([]const u8),
/// Classes that should be compiled
classes: std.ArrayList([]const u8),
/// List of classes that should be compiled
pub fn init(builder: *std.build.Builder, name_raw: []const u8, version: Version) *Self {
const name = builder.dupe(name_raw);
const self = builder.allocator.create(Self) catch unreachable;
self.* = Self{
.step = std.build.Step.init(base_id, name, builder.allocator, make),
.builder = builder,
.source_version = version,
.target_version = version,
.name = name,
.output_path = std.fs.path.join(self.builder.allocator, &[_][]const u8{ self.builder.install_prefix, builder.fmt("{s}-bin", .{self.name}) }) catch unreachable,
.classpath = std.ArrayList([]const u8).init(builder.allocator),
.classes = std.ArrayList([]const u8).init(builder.allocator),
};
return self;
}
pub fn install(self: *Self) void {
self.builder.getInstallStep().dependOn(&self.step);
}
pub fn addClass(self: *Self, path: []const u8) void {
self.classes.append(path) catch unreachable;
}
pub fn jar(self: *Self) *JarStep {
return JarStep.init(self.builder, self.name, self.output_path);
}
fn make(step: *std.build.Step) !void {
const self = @fieldParentPtr(CompileStep, "step", step);
try self.build();
}
fn build(self: *Self) !void {
const builder = self.builder;
var java_args = std.ArrayList([]const u8).init(builder.allocator);
defer java_args.deinit();
try java_args.append("javac");
try java_args.append("-verbose");
try java_args.append("-d");
try java_args.append(self.output_path);
try java_args.append("-source");
try java_args.append(builder.fmt("{d}", .{self.source_version[0]}));
try java_args.append("-target");
try java_args.append(builder.fmt("{d}", .{self.target_version[0]}));
for (self.classes.items) |class| {
try java_args.append(class);
}
const child = std.ChildProcess.init(java_args.items, self.builder.allocator) catch unreachable;
defer child.deinit();
child.stderr_behavior = .Pipe;
child.env_map = self.builder.env_map;
child.spawn() catch |err| {
std.log.warn("Unable to spawn {s}: {s}\n", .{ java_args.items[0], @errorName(err) });
return err;
};
var progress = std.Progress{};
const root_node = progress.start(self.builder.fmt("{s}", .{self.name}), 0) catch |err| switch (err) {
// TODO still run tests in this case
error.TimerUnsupported => @panic("timer unsupported"),
};
var reader = child.stderr.?.reader();
var buf: [256]u8 = undefined;
while (try reader.readUntilDelimiterOrEof(&buf, '\n')) |line| {
if (std.mem.startsWith(u8, line, "[")) {
var test_node = root_node.start(line, 0);
test_node.activate();
progress.refresh();
test_node.end();
// root_node.setEstimatedTotalItems();
// root_node.completeOne();
} else {
try std.io.getStdErr().writer().print("{s}\n", .{line});
}
}
_ = try child.wait();
root_node.end();
}
};
pub const JarStep = struct {
pub const base_id = .run;
const Self = @This();
step: std.build.Step,
builder: *std.build.Builder,
/// Name of the jar (name.jar)
name: []const u8,
/// Directory of compiled class files
bin_path: []const u8,
/// Output path
output_path: []const u8,
pub fn init(builder: *std.build.Builder, name_raw: []const u8, bin_path_raw: []const u8) *Self {
const name = builder.dupe(name_raw);
const bin_path = builder.dupe(bin_path_raw);
const self = builder.allocator.create(Self) catch unreachable;
self.* = Self{
.step = std.build.Step.init(base_id, name, builder.allocator, make),
.builder = builder,
.name = name,
.bin_path = bin_path,
.output_path = std.fs.path.join(self.builder.allocator, &[_][]const u8{ self.builder.install_prefix, "jar", builder.fmt("{s}.jar", .{self.name}) }) catch unreachable,
};
return self;
}
fn make(step: *std.build.Step) !void {
const self = @fieldParentPtr(JarStep, "step", step);
const builder = self.builder;
std.fs.cwd().makePath(self.output_path) catch unreachable;
var java_args = std.ArrayList([]const u8).init(builder.allocator);
defer java_args.deinit();
try java_args.append("jar");
try java_args.append("cf");
try java_args.append(self.output_path);
try java_args.append(std.fs.path.join(self.builder.allocator, &[_][]const u8{ self.bin_path, "*" }) catch unreachable);
try builder.spawnChild(java_args.items);
}
};
| https://raw.githubusercontent.com/zig-java/jbt/1e314aa9530c6cfeb2ce5b4a47880dd47923da45/jbt.zig |
const std = @import("std");
const stdout = std.io.getStdOut().writer();
fn Box(comptime T: type) type {
return struct {
value: T,
};
}
const Point = struct {
X: i32 = 1,
Y: i32 = 2,
};
pub fn main() !void {
var vbox = Box(Point){
.value = undefined, // this is gonna be junk
};
try stdout.print("var box with undefined: {}\n", vbox);
var vbox2 = Box(Point){
.value = Point{}, // this is the default value
};
try stdout.print("var box with explicit defaults: {}\n", vbox2);
// looks like the value of this winds up in bss.
// https://en.wikipedia.org/wiki/.bss
const cbox = Box(Point){
.value = undefined, // this is zeroed out memory
};
try stdout.print("const box with undefined: {}\n", cbox);
try stdout.print("Box literal with undefined: {}\n", Box(Point){
.value = undefined, // this is also zeroed out memory
});
}
| https://raw.githubusercontent.com/jordanorelli/learn-zig/83479b2652b3326d482645925fc2101626d00dfd/box.zig |
/// Showcase example usage of RexMap.
const std = @import("std");
const RexMap = @import("RexMap.zig");
pub fn main() anyerror!void {
// Get an allocator up and running
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
// Read in a file. In this case it's simply an xp file with the text "Hello,
// World!" on two alternating layers.
const map = try RexMap.initFromFile(arena.allocator(), "tests/layer_test.xp");
defer map.deinit();
// Display the image to the terminal via escape sequences.
//
var y: usize = 0;
while (y < map.height) : (y += 1) {
var x: usize = 0;
while (x < map.width) : (x += 1) {
// Various map.get* functions can be used. This one just grabs the
// first non-transparent tile from a coordinate, starting from the
// top layer.
const tile = map.get(x, y);
if (tile.isTransparent()) {
std.debug.print("\x1b[m ", .{});
continue;
}
std.debug.print(
"\x1b[38;2;{};{};{}m\x1b[48;2;{};{};{}m",
.{ tile.fg.r, tile.fg.g, tile.fg.b, tile.bg.r, tile.bg.g, tile.bg.b },
);
// By default, tile.ch contains the "raw" character value that was
// stored in the xp file. REXPaint treats this value as an index
// into a tilemap, *not* as an actual Unicode codepoint. For this
// reason, box-drawing characters are stored as values in the
// 128...255 range, not their actual Unicode values.
//
// In this case, we just get the real Unicode value from
// DEFAULT_TILEMAP.
std.debug.print("{u}", .{RexMap.DEFAULT_TILEMAP[tile.ch]});
}
std.debug.print("\x1b[m\n", .{});
}
}
| https://raw.githubusercontent.com/kiedtl/zig-rexpaint/9fe0640ef61b3fd0f8b2f54f4a2b4081611bceed/main.zig |
// --- Day 6: Universal Orbit Map ---
//
// You've landed at the Universal Orbit Map facility on Mercury. Because navigation in space often
// involves transferring between orbits, the orbit maps here are useful for finding efficient
// routes between, for example, you and Santa. You download a map of the local orbits (your puzzle
// input).
//
// Except for the universal Center of Mass (COM), every object in space is in orbit around exactly
// one other object. An orbit looks roughly like this:
//
// \
// \
// |
// |
// AAA--> o o <--BBB
// |
// |
// /
// /
//
// In this diagram, the object BBB is in orbit around AAA. The path that BBB takes around AAA (drawn
// with lines) is only partly shown. In the map data, this orbital relationship is written AAA)BBB,
// which means "BBB is in orbit around AAA".
//
// Before you use your map data to plot a course, you need to make sure it wasn't corrupted during
// the download. To verify maps, the Universal Orbit Map facility uses orbit count checksums - the
// total number of direct orbits (like the one shown above) and indirect orbits.
//
// Whenever A orbits B and B orbits C, then A indirectly orbits C. This chain can be any number of
// objects long: if A orbits B, B orbits C, and C orbits D, then A indirectly orbits D.
//
// For example, suppose you have the following map:
//
// COM)B
// B)C
// C)D
// D)E
// E)F
// B)G
// G)H
// D)I
// E)J
// J)K
// K)L
//
// Visually, the above map of orbits looks like this:
//
// G - H J - K - L
// / /
// COM - B - C - D - E - F
// \
// I
//
// In this visual representation, when two objects are connected by a line, the one on the right
// directly orbits the one on the left.
//
// Here, we can count the total number of orbits as follows:
//
// D directly orbits C and indirectly orbits B and COM, a total of 3 orbits.
// L directly orbits K and indirectly orbits J, E, D, C, B, and COM, a total of 7 orbits.
// COM orbits nothing.
//
// The total number of direct and indirect orbits in this example is 42.
//
// What is the total number of direct and indirect orbits in your map data?
const std = @import("std");
const Node = struct {
id: []const u8,
// Every object in space is in orbit around exactly one other object
parent: ?*Node,
orbiters: std.ArrayList(*Node),
pub fn init(allocator: *std.mem.Allocator, id: []const u8) !*Node {
var node = try allocator.create(Node);
node.id = id;
node.parent = null;
node.orbiters = std.ArrayList(*Node).init(allocator);
return node;
}
};
fn traverse(link: *Node, steps: usize) usize {
var sum = steps;
for (link.orbiters.toSliceConst()) |orbiter| {
sum += traverse(orbiter, steps + 1);
}
return sum;
}
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
var allocator = &arena.allocator;
defer arena.deinit();
var space = std.StringHashMap(*Node).init(allocator);
defer space.deinit();
// Input data will not have COM as an orbiter of any other object
try space.putNoClobber("COM", try Node.init(allocator, "COM"));
for (input) |orbit| {
// Get or create existing orbitee
var target = try space.getOrPut(orbit.target);
if (!target.found_existing) {
target.kv.value = try Node.init(allocator, orbit.target);
}
// Point orbiter at the target
var orbiter = try space.getOrPut(orbit.id);
if (!orbiter.found_existing) {
orbiter.kv.value = try Node.init(allocator, orbit.id);
}
orbiter.kv.value.parent = target.kv.value;
// Fill backlinks for reverse traversal
try target.kv.value.orbiters.append(orbiter.kv.value);
}
var origin = space.getValue("COM").?;
std.debug.warn("{}\n", traverse(origin, 0));
}
const Orbit = struct {
id: []const u8,
target: []const u8,
};
fn O(target: *const [3]u8, id: *const [3]u8) Orbit {
return Orbit{
.id = id[0..],
.target = target[0..],
};
}
const input = blk: {
@setEvalBranchQuota(20000);
break :blk [_]Orbit{
O("36S", "VWN"), O("6FM", "RNW"), O("S2M", "329"), O("DQ3", "5CD"), O("XYW", "X2Y"),
O("LFS", "LXR"), O("SMP", "C57"), O("2YY", "MSP"), O("4TM", "DPK"), O("PZQ", "77L"),
O("SNX", "Y6Q"), O("JSS", "T26"), O("KDF", "PR8"), O("SNM", "XBG"), O("46X", "P5S"),
O("CPN", "C93"), O("VXL", "ZHS"), O("B9V", "XZN"), O("B6X", "H3Y"), O("234", "FHY"),
O("BZY", "L3T"), O("6YT", "Q53"), O("JK6", "RC4"), O("TW9", "64K"), O("3VT", "2GJ"),
O("XKG", "7L4"), O("ZM3", "36S"), O("C2S", "5T2"), O("RYH", "8Z1"), O("YK6", "G7K"),
O("7YB", "WQ7"), O("X7D", "SNW"), O("8QS", "ZRP"), O("HNX", "812"), O("TN4", "K68"),
O("H6L", "PFY"), O("69Y", "1DT"), O("JKH", "41K"), O("RDZ", "S52"), O("DH8", "4HT"),
O("MH8", "HB3"), O("NCR", "PY1"), O("3L1", "8Z9"), O("HRQ", "BBC"), O("SNW", "99L"),
O("5VY", "L15"), O("D69", "9FP"), O("DRC", "S4T"), O("NJV", "MTR"), O("6ND", "49Z"),
O("RF1", "82H"), O("329", "Y37"), O("HCL", "ZBZ"), O("Q47", "ZVJ"), O("QDM", "6QM"),
O("DR8", "KWZ"), O("M2N", "PWL"), O("RLF", "N2D"), O("41G", "XTK"), O("5CF", "CFW"),
O("BBC", "KYF"), O("SX1", "G9C"), O("791", "HQD"), O("9KV", "MZC"), O("B6C", "RBX"),
O("Q5H", "R7X"), O("488", "4C5"), O("5D5", "ZTC"), O("5ZK", "G2C"), O("2HC", "SMP"),
O("CB2", "91H"), O("F4T", "J17"), O("VCJ", "HZV"), O("G3D", "LMX"), O("KMD", "98B"),
O("8Q2", "MKP"), O("4BK", "152"), O("M3H", "57J"), O("SS3", "BC7"), O("VP8", "6MV"),
O("ZDZ", "W55"), O("997", "5S5"), O("67Q", "N7M"), O("PWL", "BMZ"), O("D8V", "PBJ"),
O("KT4", "RPQ"), O("D9G", "69Y"), O("BWS", "9SV"), O("3HV", "K1J"), O("HZR", "959"),
O("WDT", "15T"), O("SLW", "C1P"), O("4VV", "1Q4"), O("D6G", "KBZ"), O("B7W", "5QP"),
O("6YL", "TFD"), O("NHZ", "XNK"), O("93V", "K1N"), O("9PS", "KTX"), O("LYZ", "P92"),
O("LTJ", "JMP"), O("CJL", "MW2"), O("L15", "LF5"), O("MRL", "PTW"), O("WNB", "NK3"),
O("TF2", "KVF"), O("MF9", "VFF"), O("J2G", "V88"), O("GBR", "NJJ"), O("CLZ", "PRR"),
O("ZLL", "ZFB"), O("9JW", "8G1"), O("SXK", "ZQ8"), O("2VP", "4XG"), O("ZQ8", "288"),
O("NQ3", "61J"), O("79G", "4ZM"), O("NL3", "SD6"), O("R38", "LCH"), O("SBX", "4S2"),
O("2VB", "8C2"), O("ND1", "3VP"), O("C93", "NHM"), O("M8L", "FL6"), O("FFV", "M61"),
O("5V5", "FDH"), O("29D", "ZYC"), O("32S", "YL6"), O("YMY", "DSJ"), O("3KS", "3GK"),
O("JZ5", "X9Q"), O("F1P", "3YV"), O("D6L", "Q94"), O("Y77", "8M4"), O("MZN", "XD7"),
O("Q7H", "C78"), O("RCD", "8KB"), O("QVD", "NP7"), O("9NM", "LRT"), O("4S6", "67F"),
O("H1W", "9MH"), O("Z68", "7LV"), O("75K", "693"), O("38K", "9ZG"), O("RZX", "M3K"),
O("XQW", "WPK"), O("6L8", "7LR"), O("RL8", "NJH"), O("W9Q", "7V7"), O("S4S", "KR5"),
O("R2F", "4MX"), O("QCY", "TY3"), O("8C2", "Z68"), O("CFW", "B7B"), O("6GV", "CST"),
O("3HG", "N6V"), O("BNW", "YQP"), O("WZZ", "6YL"), O("6QT", "39G"), O("8M4", "ML1"),
O("XW7", "6XH"), O("YY6", "3HZ"), O("KYF", "6KB"), O("NMS", "BVR"), O("V7M", "ZZB"),
O("152", "2ZP"), O("7LD", "CLM"), O("6K8", "YCB"), O("8VS", "96S"), O("7R5", "8QJ"),
O("YBS", "BVQ"), O("H82", "7SR"), O("JCL", "CMP"), O("7XX", "4BV"), O("WGM", "WCS"),
O("LDY", "H1F"), O("KS3", "2BT"), O("HKQ", "JVY"), O("7RG", "BWZ"), O("248", "629"),
O("HMJ", "QN6"), O("L1J", "BCJ"), O("JLV", "G7P"), O("M61", "S45"), O("Q8L", "9B4"),
O("HBX", "K9Z"), O("TCV", "NM4"), O("TBX", "BQC"), O("JDG", "3HS"), O("PLQ", "DXW"),
O("4WS", "CR1"), O("PSK", "CNM"), O("4HT", "37C"), O("9L1", "QL2"), O("LL4", "LGQ"),
O("W1V", "91R"), O("JTF", "W3M"), O("QVV", "4TM"), O("K6C", "4RM"), O("7F5", "PDF"),
O("QYV", "MW8"), O("KBZ", "WMV"), O("Q7H", "NMS"), O("DZ9", "7TV"), O("K82", "D4Y"),
O("YQP", "ZDZ"), O("R8S", "L8Y"), O("DTS", "X8T"), O("CLG", "5X3"), O("11F", "GMT"),
O("VMG", "787"), O("63B", "NVC"), O("S5Y", "X5N"), O("5FV", "MPK"), O("J6B", "34Z"),
O("25Y", "DV9"), O("Q4R", "D7F"), O("1R6", "K1Q"), O("5T2", "3PD"), O("YHR", "C7V"),
O("1B3", "TGT"), O("F53", "8JX"), O("6MV", "4S6"), O("DQ3", "QSG"), O("ZSF", "Y5C"),
O("SK9", "FKR"), O("XD7", "6H9"), O("8TY", "3Z1"), O("WPK", "F1X"), O("JD2", "QBH"),
O("HF3", "5HX"), O("SJC", "Q6T"), O("2WS", "G4T"), O("MDJ", "D84"), O("5ZN", "JVT"),
O("NV7", "D8G"), O("Q8C", "RYH"), O("XGB", "M11"), O("Z4H", "LXD"), O("G4T", "NPV"),
O("FZS", "Q51"), O("VL3", "17R"), O("9W2", "THD"), O("6GP", "H65"), O("8YK", "WV7"),
O("F8Y", "2FF"), O("PR8", "GDT"), O("N3J", "FLX"), O("4TY", "318"), O("7NV", "213"),
O("773", "DGG"), O("HY6", "W1J"), O("WJG", "X1V"), O("279", "8V3"), O("M1Z", "FB4"),
O("GHV", "YF7"), O("WMW", "2GY"), O("L9F", "TS1"), O("PQ2", "HZ2"), O("WQD", "MG6"),
O("8HR", "27Z"), O("5V6", "5V5"), O("BT1", "RQ5"), O("2T9", "3V9"), O("FDD", "Q27"),
O("FGP", "9LY"), O("6QM", "X38"), O("ZT2", "QWP"), O("MZC", "PVN"), O("R8G", "2JS"),
O("VRS", "W3C"), O("6TQ", "24L"), O("W1X", "JJ3"), O("QVZ", "HBN"), O("5JK", "X57"),
O("49Z", "2CV"), O("XZN", "ZN1"), O("G5Y", "6K4"), O("KYW", "255"), O("ZW2", "3KB"),
O("WRG", "FN4"), O("QJ2", "9CW"), O("RH2", "V3K"), O("2HP", "G7L"), O("3MS", "3P9"),
O("JD9", "11F"), O("FLX", "2ZY"), O("N4C", "GJD"), O("VZV", "8T9"), O("JRT", "764"),
O("KCK", "SNP"), O("V8K", "SK9"), O("46T", "JCM"), O("H3N", "FK2"), O("ZW4", "1BP"),
O("CLQ", "7BR"), O("QSS", "723"), O("VZY", "K9J"), O("32W", "Z6L"), O("PKC", "XMM"),
O("MGW", "46X"), O("FT1", "WPC"), O("6B4", "C4W"), O("Z99", "1Z6"), O("QB4", "BT1"),
O("9LQ", "V4K"), O("1C2", "4DN"), O("GHM", "VS1"), O("YRQ", "6QT"), O("XGV", "DQW"),
O("7WD", "FG3"), O("ZV5", "P84"), O("XR8", "Y89"), O("WQP", "5P9"), O("R4P", "TTV"),
O("5RP", "5MJ"), O("DZR", "QVZ"), O("D9R", "DWV"), O("Y44", "YSZ"), O("R23", "6DK"),
O("ZRP", "GTP"), O("M7C", "9FL"), O("HN9", "NZX"), O("HWY", "HSC"), O("7L4", "YH3"),
O("VJ5", "YR2"), O("85G", "65K"), O("KRN", "T3J"), O("9JV", "FVR"), O("3FV", "QSW"),
O("GMZ", "K1R"), O("HSZ", "HWY"), O("9DT", "W14"), O("5KH", "PLQ"), O("MXX", "4YT"),
O("T9P", "8VW"), O("7V7", "2N1"), O("733", "C6C"), O("G5Y", "7V3"), O("NGT", "NZC"),
O("2H6", "FGY"), O("6TT", "CSW"), O("K1Q", "D6L"), O("9BN", "HHH"), O("PDZ", "4NK"),
O("QZY", "BZH"), O("JY9", "NG4"), O("HX7", "7TB"), O("F1X", "NT5"), O("DKR", "HN9"),
O("HYQ", "QV1"), O("T3X", "HPW"), O("WR8", "18C"), O("1XF", "GT3"), O("NR3", "D69"),
O("ZN6", "YFM"), O("NVX", "2VP"), O("7CV", "YHJ"), O("LLZ", "BTM"), O("8LL", "38K"),
O("Y3X", "Q1N"), O("GJD", "VQ3"), O("MFR", "V6R"), O("6RS", "DXL"), O("1GH", "L45"),
O("62B", "7FX"), O("HRJ", "Z9Z"), O("3YQ", "X8J"), O("CMP", "TZP"), O("749", "FWW"),
O("D6P", "KNG"), O("8D3", "Y9B"), O("CLZ", "GKN"), O("34Z", "LLZ"), O("7W9", "86N"),
O("9PC", "Y3X"), O("JHX", "56F"), O("91P", "2MZ"), O("LRQ", "CLQ"), O("N2Z", "R6N"),
O("M64", "NWV"), O("T1M", "TPD"), O("Y9L", "6DY"), O("JT5", "V4Y"), O("DHH", "C8V"),
O("RNH", "JB4"), O("Y5C", "VK7"), O("36H", "6L8"), O("T26", "S7Q"), O("HHY", "PPD"),
O("4YT", "8RK"), O("QZY", "WSJ"), O("764", "XMK"), O("7NT", "W71"), O("7F5", "9QN"),
O("K96", "V2L"), O("CCY", "DYM"), O("3HG", "YC9"), O("46X", "YMC"), O("HW3", "YKQ"),
O("FGQ", "B27"), O("CFZ", "PY7"), O("ZN1", "VHW"), O("Z68", "Q83"), O("4WS", "7F1"),
O("TF3", "HKC"), O("D4Y", "TD2"), O("Z9Z", "2HP"), O("Y8F", "91P"), O("3ML", "9NM"),
O("6DK", "HQM"), O("FDH", "V5J"), O("N4Z", "GD9"), O("86Y", "597"), O("D4G", "G7R"),
O("16M", "X2D"), O("72W", "5QS"), O("WGT", "DYT"), O("MTR", "7QG"), O("GDF", "VN5"),
O("39G", "8LL"), O("RBY", "KQK"), O("P9G", "WK3"), O("LTH", "NV5"), O("SVY", "LW1"),
O("723", "5N1"), O("NJH", "8MQ"), O("1HF", "KPV"), O("YCH", "XGB"), O("8R2", "JV3"),
O("NPV", "8Q2"), O("4YP", "9BN"), O("YN6", "DZR"), O("QJS", "DHH"), O("77L", "DXN"),
O("JNN", "FTQ"), O("YV5", "JPS"), O("KKD", "JRT"), O("6XH", "CG8"), O("MJY", "LNJ"),
O("9T5", "HJ3"), O("MZC", "9S1"), O("JGN", "TXD"), O("3VP", "FN6"), O("RC4", "75K"),
O("Y37", "69L"), O("5CW", "T4L"), O("R4W", "VWK"), O("FVL", "ZW2"), O("LL2", "2H6"),
O("CMY", "GRL"), O("1DT", "YW6"), O("TV5", "S5P"), O("8WR", "717"), O("3V9", "KN6"),
O("RTL", "3BZ"), O("LN4", "54L"), O("TXF", "MKH"), O("1WM", "J65"), O("YFM", "5NT"),
O("JS6", "7F8"), O("WNN", "W6Z"), O("KVF", "FFX"), O("CRJ", "STR"), O("N1D", "BZ2"),
O("1KB", "R4P"), O("C1S", "626"), O("VS1", "67Q"), O("JMP", "7X5"), O("17K", "GYC"),
O("WPK", "72W"), O("4DN", "641"), O("WC5", "YRQ"), O("S6B", "GXJ"), O("5N7", "3VT"),
O("3GK", "SXK"), O("41G", "K96"), O("WHJ", "LRZ"), O("3PD", "TXF"), O("7J9", "PKC"),
O("GS6", "JX4"), O("736", "2ZB"), O("FW5", "2T9"), O("V88", "YQX"), O("KVB", "VX3"),
O("4ZD", "GYB"), O("JTK", "MHK"), O("CCC", "XXQ"), O("PXG", "JCL"), O("PP2", "Y7J"),
O("SHY", "XYX"), O("QBZ", "MQW"), O("BCJ", "F53"), O("7LR", "HZQ"), O("SZX", "41J"),
O("RNW", "K6N"), O("S2W", "78F"), O("JLF", "ZM3"), O("JV1", "SXG"), O("WWR", "WZS"),
O("MXG", "RFT"), O("HQD", "GBR"), O("C8C", "7NV"), O("F59", "758"), O("T26", "LX3"),
O("62P", "CLG"), O("HJ3", "4KT"), O("33Q", "DSD"), O("ZHS", "DXK"), O("6RY", "QK8"),
O("3H7", "414"), O("GYC", "ZQH"), O("65K", "YHV"), O("L8L", "D6P"), O("MJS", "H5K"),
O("7ML", "834"), O("VW4", "Q6W"), O("PVM", "6Q3"), O("5Z2", "2LS"), O("1B5", "RNH"),
O("318", "JHH"), O("T3J", "5FV"), O("CXK", "MRW"), O("7GK", "KT4"), O("YX8", "26Z"),
O("8J9", "3T2"), O("DWV", "N88"), O("9T9", "BSS"), O("HN6", "L9F"), O("9TH", "7J9"),
O("RR2", "MSS"), O("V5F", "QSS"), O("J2R", "1W8"), O("PLT", "DX7"), O("GFL", "N73"),
O("PVN", "KN2"), O("96L", "NGT"), O("8M7", "JGW"), O("YW6", "92B"), O("9V7", "4W7"),
O("SKL", "GHM"), O("94K", "6H2"), O("XBH", "1WD"), O("8DS", "QKH"), O("HJP", "BKD"),
O("27Z", "X36"), O("9CR", "5ZN"), O("XYD", "SXC"), O("NYH", "VMB"), O("TCC", "3ML"),
O("4BV", "2JY"), O("5QP", "7NT"), O("WMX", "B7W"), O("SLQ", "7RR"), O("7SC", "R5N"),
O("ZNY", "W5C"), O("656", "T84"), O("VM1", "JZ8"), O("H2X", "NHD"), O("3RQ", "MPG"),
O("7WF", "T44"), O("268", "C2S"), O("W7D", "9YD"), O("DWF", "8BB"), O("TZ2", "BK3"),
O("R17", "DQT"), O("MRW", "K9L"), O("8MQ", "W1K"), O("L4V", "6FM"), O("SWR", "FNL"),
O("PMB", "J2G"), O("N4X", "3YT"), O("NP7", "KS3"), O("DXN", "WFH"), O("3BZ", "JD9"),
O("QCD", "W5J"), O("P22", "B9V"), O("NR1", "WX7"), O("G42", "CMW"), O("SS6", "KY6"),
O("D84", "X97"), O("QV1", "8DS"), O("TQM", "VJX"), O("4VB", "JHX"), O("4WM", "9TT"),
O("T8H", "K2G"), O("Q72", "H6L"), O("QN6", "Y7K"), O("C4M", "YY6"), O("W8P", "WYP"),
O("NCC", "31C"), O("HVZ", "93C"), O("Y13", "XXZ"), O("93V", "QXS"), O("NRL", "9J8"),
O("JZW", "FW3"), O("BVR", "16M"), O("W5C", "XC5"), O("XC5", "HJF"), O("4PG", "FFW"),
O("TWM", "C9R"), O("MNG", "GHV"), O("V5F", "FC2"), O("RBJ", "JXR"), O("94W", "1KD"),
O("SYP", "TQR"), O("T84", "MTZ"), O("T1F", "7XK"), O("ZFX", "F7Q"), O("GT3", "X4X"),
O("YHB", "V16"), O("SQZ", "8QS"), O("FGY", "5FJ"), O("N2D", "N4C"), O("P84", "72Z"),
O("MYP", "6LP"), O("717", "J1Q"), O("3V8", "8D9"), O("7ZP", "RM7"), O("PK9", "HTS"),
O("6J1", "RWN"), O("CCC", "V2X"), O("L14", "92M"), O("91H", "VTN"), O("MCF", "G5Y"),
O("9R5", "LCZ"), O("CR1", "P9M"), O("15T", "2WS"), O("7XK", "V8S"), O("J8T", "D3P"),
O("TVD", "4YP"), O("PTC", "K7P"), O("L82", "6RD"), O("N6V", "FSX"), O("5TH", "C9H"),
O("HY9", "52F"), O("249", "VXL"), O("LRQ", "SCP"), O("FHK", "RQQ"), O("Y3J", "F5Q"),
O("4LH", "9Q9"), O("MW2", "BHT"), O("JBS", "1B3"), O("D3P", "BK8"), O("G7R", "FW5"),
O("HPW", "Z3T"), O("TT6", "L8L"), O("2FY", "CLZ"), O("V8T", "T97"), O("P2G", "W9Q"),
O("144", "SRL"), O("MHK", "H3P"), O("Q35", "FQ5"), O("V3K", "BZY"), O("TQP", "V7V"),
O("HF6", "LWB"), O("BZ9", "L4V"), O("GRS", "BDM"), O("45R", "YBS"), O("5SF", "4BG"),
O("FPF", "CG7"), O("R4R", "K6C"), O("D5P", "9BC"), O("9XJ", "GBV"), O("B5L", "T59"),
O("D82", "K93"), O("R6D", "KKW"), O("XXQ", "F9N"), O("SNP", "M74"), O("BXC", "TQM"),
O("81T", "CHD"), O("213", "8M7"), O("RQQ", "H4G"), O("NZT", "7QP"), O("6KB", "85G"),
O("93C", "DVQ"), O("P7F", "2FY"), O("N3Z", "QS4"), O("PVT", "FGQ"), O("JB4", "VCJ"),
O("QFS", "1B5"), O("NH3", "1KF"), O("DPH", "FL2"), O("GTP", "FR4"), O("G8M", "WWD"),
O("FB6", "ZNS"), O("842", "PMB"), O("GBV", "46N"), O("YC9", "1Y8"), O("FL2", "HLY"),
O("DPK", "3TJ"), O("8QJ", "6BY"), O("C1P", "ZRH"), O("9Q9", "TVB"), O("W14", "WLW"),
O("XWR", "972"), O("7V7", "NVX"), O("H9X", "ZZ8"), O("BYG", "YSK"), O("FDD", "3H1"),
O("5WQ", "NZ5"), O("ZLD", "7CV"), O("4RZ", "1GV"), O("V8C", "N2G"), O("N2J", "VX8"),
O("TBK", "TWM"), O("M3K", "W1V"), O("G85", "T14"), O("N5L", "RTT"), O("6ZZ", "54W"),
O("8N1", "7W3"), O("42N", "R73"), O("54W", "9FV"), O("7TS", "HD6"), O("S45", "HZG"),
O("KQK", "BMQ"), O("8V5", "F91"), O("M3J", "HM9"), O("W54", "268"), O("DV9", "JDT"),
O("63D", "GMZ"), O("6B3", "8V5"), O("KNV", "RFX"), O("JH5", "MK3"), O("YQQ", "Q7Y"),
O("V9W", "5LX"), O("KZK", "4VB"), O("RXX", "YNY"), O("NM4", "XZR"), O("ZBZ", "33Q"),
O("ZW7", "279"), O("QKH", "DP7"), O("6KQ", "WL9"), O("3Q3", "9TH"), O("9QN", "7X9"),
O("9YD", "RLF"), O("FB4", "Q5H"), O("8S3", "XTC"), O("CLV", "P4L"), O("FP1", "N1D"),
O("GKN", "CNT"), O("X8J", "8KK"), O("V5H", "T8M"), O("Y4L", "H4W"), O("BXZ", "DRZ"),
O("6VP", "6HP"), O("1BP", "BDJ"), O("GLB", "71J"), O("Q4P", "VD7"), O("YKQ", "XWZ"),
O("YRY", "V5S"), O("T5L", "V15"), O("2LS", "4R8"), O("2Z3", "7FZ"), O("JVY", "7LD"),
O("C4W", "QFS"), O("T94", "P9G"), O("S2Q", "FTC"), O("K36", "9XL"), O("RR5", "43C"),
O("7TB", "NLQ"), O("8BN", "56N"), O("M7Y", "H6V"), O("PFY", "96L"), O("NB3", "51P"),
O("TTR", "BKW"), O("PLT", "HZR"), O("PZQ", "563"), O("HTW", "Q6J"), O("CB9", "J7C"),
O("3YV", "4PG"), O("LCZ", "7YB"), O("HW4", "YHB"), O("95K", "J8K"), O("Q3F", "YGH"),
O("R82", "Q35"), O("4LQ", "54X"), O("1FB", "22B"), O("W5J", "JSJ"), O("GY8", "JKH"),
O("N7Z", "TTS"), O("B7B", "VLB"), O("LX3", "8XL"), O("T5L", "KKG"), O("G2C", "NWH"),
O("T8M", "W24"), O("KJ5", "LFS"), O("SQP", "RNF"), O("Y6Q", "PSL"), O("SR9", "XBH"),
O("YDF", "HL4"), O("22B", "XKP"), O("V5H", "81T"), O("1CN", "L5B"), O("JPX", "T62"),
O("RPQ", "H82"), O("ZBG", "462"), O("TKG", "WMW"), O("KRQ", "R6S"), O("1KD", "NN4"),
O("XTW", "L14"), O("FN6", "D67"), O("JD5", "RL8"), O("GD9", "GQ8"), O("67F", "RJX"),
O("Y4J", "23M"), O("YHV", "WKJ"), O("5XR", "VJ5"), O("NZ5", "3TH"), O("2ZP", "313"),
O("78F", "K98"), O("N1L", "RR5"), O("5X4", "814"), O("MKR", "C8C"), O("NYY", "1R4"),
O("J7J", "JZW"), O("P9Y", "Q47"), O("VNS", "XDG"), O("4VB", "YMY"), O("LZR", "LTH"),
O("J2N", "Z5P"), O("56N", "VNJ"), O("QC6", "XVY"), O("8J4", "KWP"), O("JLP", "5V3"),
O("4PP", "Q5M"), O("CR1", "R17"), O("VQC", "CPN"), O("K6N", "CTX"), O("75G", "G1T"),
O("3V1", "QDM"), O("3V4", "XHD"), O("BVQ", "9CR"), O("5NT", "MXV"), O("1R4", "G98"),
O("XZN", "5C5"), O("M7Y", "Y1D"), O("Q5M", "HVK"), O("R31", "LLL"), O("T62", "7R5"),
O("6PY", "X6G"), O("4RM", "RH2"), O("BRS", "DCV"), O("3L5", "YDF"), O("F55", "GR2"),
O("HVN", "9RJ"), O("K7P", "CRD"), O("9V7", "3MQ"), O("284", "736"), O("CRD", "BWF"),
O("N5J", "C75"), O("L21", "BGB"), O("91R", "C1S"), O("9B4", "777"), O("HL9", "Y13"),
O("4RY", "NR1"), O("N73", "937"), O("DV9", "3H7"), O("8NZ", "CRJ"), O("YR2", "Y4J"),
O("ZN6", "HSZ"), O("S52", "L1J"), O("XKP", "72F"), O("7M7", "MXG"), O("YQX", "KCK"),
O("Q6S", "2MT"), O("VK7", "1V3"), O("M8R", "JY9"), O("KKG", "WC5"), O("T97", "L47"),
O("KP2", "HGF"), O("NJJ", "R4R"), O("W55", "QCD"), O("RHJ", "P7F"), O("XTC", "TC1"),
O("QSG", "WZZ"), O("GWZ", "YX8"), O("9J8", "JG8"), O("LGQ", "KVJ"), O("T6B", "XZ7"),
O("PRR", "XTW"), O("MC4", "8YL"), O("42Y", "V1M"), O("43X", "8NZ"), O("NYS", "1KB"),
O("Q1N", "B5L"), O("61J", "SQZ"), O("QL7", "6S8"), O("9X9", "YZH"), O("BMC", "WMX"),
O("HZV", "3MS"), O("MSP", "FGP"), O("MCN", "VDT"), O("SJL", "XDV"), O("KQ1", "GNT"),
O("YX7", "BN4"), O("MKP", "SX9"), O("1W8", "1DF"), O("VNJ", "N3Z"), O("YT8", "8QV"),
O("JPS", "VF2"), O("G7P", "KGY"), O("4ZD", "MDX"), O("HHS", "THP"), O("WCS", "5SD"),
O("N63", "RTL"), O("4ZG", "YQQ"), O("ZRH", "HRQ"), O("5P6", "MMY"), O("MMY", "V4N"),
O("Q27", "M3F"), O("J65", "VH7"), O("JHH", "NHZ"), O("X4V", "W5L"), O("2H6", "NP4"),
O("XH5", "48R"), O("X61", "656"), O("WQ5", "BV7"), O("4FH", "TQP"), O("DMF", "WZ3"),
O("CHD", "PP2"), O("7FX", "TJT"), O("92B", "2GG"), O("37C", "ZV5"), O("H3P", "N4Z"),
O("MJF", "842"), O("F8H", "ZGB"), O("XRS", "MPT"), O("7BR", "BYF"), O("FCT", "SB9"),
O("NV3", "Z4H"), O("SQM", "WHJ"), O("4NB", "FJ7"), O("HMD", "R38"), O("VC7", "HFT"),
O("31C", "57K"), O("RX2", "SWR"), O("H65", "GXT"), O("23M", "8ZQ"), O("PWL", "VFB"),
O("FW3", "79G"), O("57K", "TZ2"), O("7TV", "1MS"), O("FV1", "VF7"), O("W55", "RCJ"),
O("TS1", "P22"), O("W5X", "XZX"), O("Z9H", "9ZV"), O("8XQ", "9KP"), O("L8Y", "6KL"),
O("5LX", "FD3"), O("DZV", "ZQ4"), O("8MK", "46T"), O("3FV", "V6G"), O("RFT", "MG8"),
O("41K", "2HC"), O("YC4", "M7B"), O("QWP", "HYK"), O("DYF", "WP2"), O("VXJ", "D7Y"),
O("BYG", "VQ2"), O("V6G", "SQ3"), O("17K", "248"), O("9XL", "DVV"), O("WWD", "QM4"),
O("HG1", "Q4R"), O("C2H", "Q3F"), O("2MT", "YOU"), O("V16", "17K"), O("PTW", "XQW"),
O("46N", "D3L"), O("VM1", "ZW4"), O("SKY", "SF8"), O("LLL", "H48"), O("SX9", "784"),
O("17R", "HGT"), O("S27", "GY8"), O("G7V", "7WD"), O("24C", "RBY"), O("HHV", "4NB"),
O("WVX", "TCC"), O("FC2", "36H"), O("NHT", "63D"), O("XXW", "7ML"), O("FG3", "BMC"),
O("FVD", "FN1"), O("GFG", "1JY"), O("X6G", "CMY"), O("BGB", "DR8"), O("ZTC", "2G7"),
O("9HF", "T9P"), O("MWN", "W54"), O("JSJ", "SX1"), O("XWZ", "SLW"), O("H2N", "RX2"),
O("C7S", "YNS"), O("6K7", "X4Y"), O("V83", "N68"), O("V9T", "R4W"), O("YMC", "HRJ"),
O("T94", "NR3"), O("6H1", "YT8"), O("GW8", "T94"), O("FQ5", "62P"), O("CNM", "N8R"),
O("TJ4", "G3D"), O("X34", "N2J"), O("JHJ", "G3C"), O("NSG", "1CN"), O("QKZ", "873"),
O("RC4", "1HF"), O("BL4", "TKG"), O("JH2", "D6C"), O("716", "N5B"), O("CD6", "YV5"),
O("NZC", "4LH"), O("5X3", "5W3"), O("BY2", "TKD"), O("3H7", "SMW"), O("K1J", "J6B"),
O("Q51", "BZW"), O("N6J", "6Q5"), O("MPG", "6XK"), O("VBG", "R7V"), O("MLP", "L82"),
O("STK", "WNN"), O("WSJ", "JW1"), O("QDD", "LWS"), O("DG3", "JRQ"), O("TVV", "8G8"),
O("LL2", "NSZ"), O("5V4", "YP4"), O("WDH", "GZG"), O("937", "JK6"), O("H6V", "B95"),
O("VFB", "DPN"), O("CQW", "V7M"), O("W5X", "RCD"), O("ZNS", "WWR"), O("6DY", "CV6"),
O("NWV", "7F5"), O("8TV", "445"), O("92M", "HVN"), O("XW7", "VXJ"), O("V2L", "135"),
O("KPV", "836"), O("H3H", "SMB"), O("WKJ", "WDH"), O("678", "TF2"), O("D12", "8YK"),
O("7X9", "MXX"), O("NYH", "VTH"), O("5GM", "JS2"), O("KLY", "HYQ"), O("G7L", "DZ9"),
O("WRG", "D47"), O("8YL", "K7F"), O("7RG", "YGR"), O("641", "G85"), O("Z1M", "R8T"),
O("XDG", "SHY"), O("V5Y", "Z76"), O("BN4", "JZ5"), O("QLD", "XPW"), O("3SS", "GD6"),
O("X2Y", "HY6"), O("QTM", "FHK"), O("FPW", "HG1"), O("SQ3", "WR8"), O("VF7", "1NN"),
O("CQD", "V8W"), O("HJF", "GTM"), O("MF1", "7BP"), O("C7V", "2C2"), O("FHY", "QTM"),
O("RL8", "PZQ"), O("ML1", "HY9"), O("VVK", "8QH"), O("7LN", "QYQ"), O("WDG", "855"),
O("9ZV", "KMV"), O("597", "87V"), O("R5B", "3L1"), O("RM6", "6B3"), O("VN5", "WSR"),
O("CLM", "MF1"), O("MG8", "YK6"), O("TQP", "PVM"), O("3S1", "5GR"), O("Q5D", "GWZ"),
O("ZW4", "3V1"), O("4JF", "D12"), O("JBY", "MD5"), O("C75", "R6R"), O("RWN", "5P6"),
O("5P9", "MNG"), O("2TK", "G68"), O("C6C", "CB2"), O("6K4", "MP2"), O("K7F", "DZ4"),
O("959", "NRL"), O("3H1", "FQQ"), O("MRL", "YFX"), O("W3M", "9X9"), O("TM6", "VNS"),
O("TY3", "QYV"), O("TXJ", "WVJ"), O("YCB", "65X"), O("H4G", "Z9H"), O("2ZY", "SZR"),
O("P31", "X61"), O("9QN", "K2W"), O("S71", "GN7"), O("6GV", "3HG"), O("418", "2YY"),
O("VNV", "9T5"), O("T4L", "N6J"), O("3YT", "4VG"), O("1X3", "6ND"), O("DCV", "5WQ"),
O("XXZ", "75G"), O("H7C", "4G2"), O("CB2", "32S"), O("8HN", "7FP"), O("HVP", "MF9"),
O("D47", "V24"), O("HZY", "G1S"), O("2GJ", "WGT"), O("FFX", "R4T"), O("R6N", "444"),
O("XWY", "G42"), O("TJT", "13B"), O("THD", "Y5P"), O("L47", "KTF"), O("PKS", "7XX"),
O("GC9", "BKL"), O("D6C", "2W3"), O("J9G", "395"), O("XNR", "T7S"), O("YQ7", "VL3"),
O("FBJ", "R31"), O("5FJ", "JBS"), O("XX7", "LRQ"), O("LF5", "MJY"), O("GR3", "8S3"),
O("S4T", "X7D"), O("HQX", "MC4"), O("KVJ", "3NK"), O("L14", "W2B"), O("Z2S", "XMG"),
O("24L", "4SK"), O("VJX", "K5W"), O("SXC", "4VV"), O("FTQ", "R5S"), O("YDB", "Y3J"),
O("C9N", "YBP"), O("L36", "9PC"), O("FKR", "QQ1"), O("8T9", "LCM"), O("S7Q", "C3T"),
O("2N1", "9JW"), O("YSZ", "XXW"), O("LWS", "DQ3"), O("H1F", "24C"), O("LNJ", "YFD"),
O("7V3", "5V6"), O("XDW", "RPJ"), O("814", "M64"), O("9SV", "GJ4"), O("NHD", "M2R"),
O("HB3", "KR8"), O("4BG", "SYP"), O("W71", "T7N"), O("CG7", "T1M"), O("VFF", "21F"),
O("L8Y", "H2N"), O("N68", "3NV"), O("L63", "MKR"), O("9RJ", "81G"), O("F5Q", "LJJ"),
O("25B", "SJL"), O("TJ4", "LZR"), O("KZD", "N7Q"), O("5V3", "7W9"), O("MD5", "X4C"),
O("D6P", "NV7"), O("6H9", "CLV"), O("3NK", "3L6"), O("5S5", "XW1"), O("J2R", "RXX"),
O("2KN", "298"), O("7FZ", "8N1"), O("VTC", "5RG"), O("SJ8", "571"), O("VQ2", "GPR"),
O("PY7", "DKV"), O("MPC", "54J"), O("2BT", "H2X"), O("CSC", "KDF"), O("LJ4", "X3V"),
O("V22", "NHT"), O("ZVJ", "8DW"), O("2FC", "FCT"), O("PLR", "5JB"), O("51J", "KNV"),
O("BYF", "HW4"), O("JXR", "KX7"), O("NV9", "R23"), O("K8R", "BSP"), O("96P", "J52"),
O("NB3", "SQM"), O("JDT", "KZD"), O("LWB", "6TT"), O("5N1", "QC6"), O("BGN", "9V7"),
O("QBH", "P5T"), O("T14", "4JF"), O("HM9", "Y6K"), O("KR2", "6ZZ"), O("K87", "JPX"),
O("69N", "5GV"), O("629", "GYP"), O("BZW", "YC4"), O("7PG", "9R5"), O("PPD", "RQ8"),
O("NSZ", "TW9"), O("G2H", "WJG"), O("NP4", "W5X"), O("FZ4", "TCR"), O("X8T", "XQY"),
O("3L6", "QZP"), O("N7M", "ZR8"), O("V15", "2GW"), O("6BY", "4XL"), O("YCH", "BNW"),
O("DHQ", "5SF"), O("5SZ", "846"), O("F1V", "ZT2"), O("82H", "LTJ"), O("ZYC", "H3H"),
O("HHY", "Q6S"), O("BKL", "4XY"), O("XKY", "RSY"), O("VTN", "HVZ"), O("9TH", "XNR"),
O("6KL", "S8G"), O("C78", "J9G"), O("7QP", "LN4"), O("VQH", "W1C"), O("FN6", "CSC"),
O("BSP", "NZT"), O("6RD", "ZFX"), O("5VY", "DZV"), O("HHH", "95J"), O("B7K", "JNN"),
O("2MZ", "DY1"), O("4SK", "P5H"), O("HZG", "TZD"), O("F9N", "5Z2"), O("Q5H", "8D3"),
O("HVK", "WQ5"), O("F7Q", "2YV"), O("L5K", "R2W"), O("Z6L", "7GK"), O("P9M", "H1V"),
O("W5G", "HL8"), O("5WQ", "R8G"), O("CG8", "QKZ"), O("6S8", "SS3"), O("YML", "2BC"),
O("ZQH", "B4Z"), O("84W", "R2S"), O("YSY", "6VP"), O("W3T", "XLJ"), O("94W", "G8P"),
O("HGF", "JH5"), O("XHD", "HX7"), O("F6Q", "R82"), O("4NW", "J7J"), O("CV6", "J8T"),
O("TRG", "XX5"), O("LW1", "5GM"), O("956", "5JK"), O("FVR", "VW4"), O("4YT", "716"),
O("5NG", "2FC"), O("GDT", "S7D"), O("RPJ", "YCH"), O("5ZZ", "5KH"), O("54L", "SWD"),
O("KZ5", "J3M"), O("3MQ", "6X2"), O("HFT", "F3Z"), O("455", "F4T"), O("RWN", "JHN"),
O("TFD", "N5L"), O("XW1", "WS1"), O("2DH", "KHP"), O("N2G", "8WR"), O("V2V", "WNQ"),
O("Z4V", "ZX3"), O("N59", "FB6"), O("R7X", "KZK"), O("TQC", "59M"), O("CQ5", "25B"),
O("8KZ", "N4S"), O("T1F", "VP8"), O("C9H", "6H1"), O("86N", "DH8"), O("96S", "23D"),
O("ZB7", "NCR"), O("7ZP", "6L2"), O("PFG", "9L1"), O("G98", "6KQ"), O("846", "GBD"),
O("3NV", "JLP"), O("LYM", "LL2"), O("GPR", "TL5"), O("7NR", "GWR"), O("1Q4", "583"),
O("1DT", "YRY"), O("WBW", "JLF"), O("Z43", "KHR"), O("72Z", "Y44"), O("WQP", "NC5"),
O("26Z", "PQ2"), O("11Y", "4ZG"), O("KTX", "DHZ"), O("98B", "3SF"), O("H48", "YSY"),
O("V8N", "SZX"), O("T3G", "MG1"), O("FDJ", "HHV"), O("56F", "FQ9"), O("P7W", "WNB"),
O("WV7", "SLZ"), O("53L", "YXT"), O("LVR", "M7C"), O("8V3", "QCY"), O("JR1", "HW3"),
O("33Q", "NGJ"), O("H3Y", "6J1"), O("XLJ", "PSK"), O("VHW", "NBZ"), O("7LV", "7NR"),
O("27X", "V9T"), O("213", "CQD"), O("SD6", "Z43"), O("PBJ", "17Q"), O("R73", "V5H"),
O("MGX", "9XV"), O("GTM", "JHF"), O("KR5", "W1H"), O("MJF", "MFR"), O("R5N", "GC9"),
O("CJK", "VNV"), O("FHK", "XVL"), O("LF8", "1L4"), O("RM7", "HHY"), O("M6H", "PXG"),
O("XMM", "BXZ"), O("7BP", "T6Y"), O("LXD", "7PG"), O("48R", "XRS"), O("6Q3", "51J"),
O("TZD", "SQP"), O("7ZL", "F55"), O("M64", "NYY"), O("FBJ", "F72"), O("2GW", "F1P"),
O("444", "HBX"), O("V1M", "84W"), O("D8V", "VRS"), O("QLX", "8HR"), O("NZ7", "LJD"),
O("HT8", "B6X"), O("F91", "S27"), O("9MH", "XT4"), O("FGB", "JLV"), O("6XH", "1XF"),
O("23K", "ZDP"), O("834", "RM6"), O("GJ4", "818"), O("XJD", "7SC"), O("13N", "D4G"),
O("HGS", "P2G"), O("TWB", "DWF"), O("KT9", "GH6"), O("YHB", "36R"), O("FWW", "7DR"),
O("H9N", "HTG"), O("C1V", "QX5"), O("J3M", "KT9"), O("SLZ", "1GH"), O("ZYD", "K55"),
O("BDJ", "C4L"), O("395", "TBX"), O("J8K", "4C2"), O("8G1", "WDG"), O("TZD", "3XG"),
O("MXV", "HF6"), O("P5T", "NV9"), O("MHG", "4D2"), O("V2X", "DTS"), O("1Z6", "1WM"),
O("BC7", "GW8"), O("NV5", "4ZD"), O("26Z", "PLT"), O("FR4", "GS6"), O("1DF", "TNP"),
O("NLQ", "MPC"), O("ZFL", "45R"), O("Z3T", "7WF"), O("3P9", "P9Y"), O("V7V", "2QT"),
O("X3M", "ZBG"), O("XMG", "HT8"), O("ZSJ", "HS1"), O("TCR", "V9W"), O("VTH", "TBK"),
O("BTM", "WBW"), O("27X", "BS6"), O("WNQ", "HTW"), O("BQC", "SJ8"), O("GCM", "WVX"),
O("SB7", "MJF"), O("X9Q", "YQ7"), O("D6K", "MRL"), O("HSZ", "F8F"), O("BWS", "PKS"),
O("9KP", "9W2"), O("43C", "DWN"), O("KN2", "GZQ"), O("G1L", "NXL"), O("TCL", "8TY"),
O("BKW", "B21"), O("M82", "9DT"), O("B27", "GLB"), O("JDG", "F26"), O("99X", "Y9L"),
O("566", "CQW"), O("MPK", "SLQ"), O("WL9", "956"), O("N13", "653"), O("SWS", "JR1"),
O("N35", "29D"), O("QVK", "J2R"), O("4C2", "P8F"), O("C1S", "4TY"), O("YF7", "6RS"),
O("BDM", "YX7"), O("9TY", "ZYD"), O("TPD", "8XQ"), O("DYM", "JPR"), O("TKD", "TWB"),
O("WVJ", "N4X"), O("41J", "KSY"), O("HTG", "Q8C"), O("N8R", "H9X"), O("XVR", "RQM"),
O("WSR", "KMD"), O("S99", "V83"), O("BS3", "8VP"), O("QPH", "23K"), O("3VF", "S6B"),
O("23D", "76X"), O("827", "9VC"), O("5GV", "SDR"), O("635", "FDJ"), O("RQM", "8TV"),
O("51Z", "9VM"), O("NT5", "95K"), O("F72", "9FR"), O("YP4", "7Y4"), O("G42", "3N2"),
O("PY1", "CC3"), O("S4P", "JRR"), O("7X5", "566"), O("KR8", "VS8"), O("13B", "NZ7"),
O("X4C", "VQH"), O("VLB", "BZM"), O("LCM", "V3V"), O("K1R", "9TY"), O("7K5", "N13"),
O("W1H", "S2M"), O("V8S", "635"), O("J1L", "TRG"), O("ZR8", "Q8L"), O("XPW", "QRY"),
O("XDV", "997"), O("M74", "VWG"), O("395", "T7W"), O("QYV", "RDZ"), O("8JX", "4NW"),
O("4C5", "FZ4"), O("XVL", "1C2"), O("WDT", "FV1"), O("R2W", "VQ8"), O("C4L", "TV5"),
O("N57", "GQS"), O("9FR", "QLX"), O("6C4", "L5K"), O("F3Z", "62B"), O("W9M", "S3G"),
O("JHH", "7LN"), O("HBN", "GYK"), O("DY9", "CJK"), O("787", "2Z3"), O("44V", "LF8"),
O("C3T", "13N"), O("XTK", "5ZK"), O("571", "HL9"), O("TTQ", "R9R"), O("VWK", "MWN"),
O("DYT", "8ZN"), O("CCH", "YCF"), O("JPJ", "JHJ"), O("JHF", "DKR"), O("SPP", "FPW"),
O("MKR", "78L"), O("X8Q", "C9N"), O("J1Q", "SPP"), O("Y7J", "YML"), O("2JS", "F6Q"),
O("56T", "DHL"), O("3N2", "6YT"), O("DF4", "K82"), O("Y89", "VR6"), O("59M", "SZ2"),
O("1MV", "CTP"), O("626", "Z2S"), O("7D7", "L36"), O("V6V", "H1W"), O("T7W", "D3D"),
O("WPJ", "71N"), O("75G", "XFP"), O("71J", "HGL"), O("WK3", "S3T"), O("SMW", "QVK"),
O("T3L", "Y8F"), O("P84", "NL3"), O("TF4", "6GD"), O("KMK", "FQC"), O("2QT", "CXK"),
O("8LL", "PDZ"), O("4C2", "32W"), O("5JB", "Q4P"), O("4W7", "5N7"), O("QZP", "TQ2"),
O("7QG", "Q72"), O("SDR", "LZH"), O("C9R", "7ZP"), O("QXS", "X2K"), O("D7Y", "YYG"),
O("9BC", "4RY"), O("976", "6TQ"), O("QL2", "BXC"), O("ZXK", "HQX"), O("D3D", "6C4"),
O("NK3", "S2Q"), O("B95", "SKL"), O("NN4", "2VB"), O("NHT", "1X3"), O("RHG", "F8Y"),
O("GRL", "RS8"), O("2GY", "41G"), O("D48", "F4D"), O("2YV", "3V8"), O("JC5", "V8C"),
O("T7S", "TYM"), O("KRN", "7K5"), O("K1N", "RTD"), O("X97", "MCF"), O("3TH", "5XR"),
O("MNG", "MHG"), O("QX5", "STK"), O("D82", "D9R"), O("KNG", "K36"), O("288", "4FF"),
O("W1G", "LZN"), O("FJ7", "TVV"), O("YXT", "BVH"), O("RQ8", "QB4"), O("5QS", "7DY"),
O("FZX", "T5L"), O("BZ2", "WRG"), O("GYP", "X8Q"), O("NY3", "N3J"), O("298", "JS9"),
O("KHR", "JTK"), O("T7N", "JC5"), O("2J7", "KKD"), O("HL9", "PDT"), O("XZX", "WQP"),
O("GXJ", "T6B"), O("NHM", "PCD"), O("R4T", "JBY"), O("3SF", "J2N"), O("MW8", "9T9"),
O("3YQ", "D5P"), O("6J1", "NC9"), O("VDT", "4RZ"), O("9VM", "FZQ"), O("G77", "2TK"),
O("YL6", "H3N"), O("QSW", "V4V"), O("GR2", "KYS"), O("MPT", "PTC"), O("N1L", "D6K"),
O("F8N", "T1F"), O("K2W", "R5B"), O("RC1", "D9J"), O("PP2", "WJ4"), O("JRR", "V8N"),
O("GZW", "4LQ"), O("21F", "2VL"), O("HQM", "4XJ"), O("CNT", "HH7"), O("7DY", "ZGV"),
O("FQC", "L63"), O("972", "JS6"), O("BK3", "SWS"), O("9CW", "4WS"), O("V5S", "Q7H"),
O("2WP", "QX6"), O("C57", "6GF"), O("BZH", "GFL"), O("FK2", "SJF"), O("NBZ", "RBV"),
O("4NK", "CCY"), O("JRQ", "QVV"), O("3HS", "M7Y"), O("6HP", "G77"), O("TNP", "9LQ"),
O("8G8", "NH3"), O("DVQ", "3V4"), O("K98", "G2J"), O("BSS", "JSS"), O("KGY", "G8M"),
O("SZR", "2KN"), O("KWZ", "NJV"), O("WJG", "FPF"), O("F26", "ZFL"), O("TVB", "2M8"),
O("445", "KJ5"), O("RQ8", "2P3"), O("SDR", "XJD"), O("HL8", "M82"), O("TLY", "3YQ"),
O("R16", "249"), O("2CV", "144"), O("L45", "W7D"), O("P5S", "R8S"), O("V3V", "HNX"),
O("G7K", "X34"), O("W1V", "DXZ"), O("HXJ", "BVV"), O("TLY", "7ZL"), O("BVH", "CQ5"),
O("QSG", "GRS"), O("Q53", "96P"), O("RCJ", "TVD"), O("YGR", "VC7"), O("P92", "C2H"),
O("D3D", "N7Z"), O("NWH", "XYW"), O("8XL", "T3G"), O("824", "3L5"), O("M3K", "KLY"),
O("QQ1", "QJ2"), O("NXL", "L21"), O("N88", "KYB"), O("DWN", "JT5"), O("TPW", "NY3"),
O("HGT", "SVY"), O("LZH", "SC2"), O("CP6", "S1B"), O("51P", "6RY"), O("GZ9", "DHQ"),
O("FSX", "FGB"), O("NZX", "KMK"), O("RMT", "8BN"), O("71N", "TQC"), O("BHT", "NYS"),
O("W1G", "8J9"), O("LMG", "K87"), O("SF8", "CCC"), O("7DH", "JD5"), O("59M", "M6H"),
O("V8N", "JH2"), O("8KK", "HVP"), O("R6S", "42Y"), O("8Z1", "5V4"), O("ZX3", "69N"),
O("VWN", "GZW"), O("JCM", "HKQ"), O("G61", "M1Z"), O("6Q5", "N91"), O("89H", "CFK"),
O("MW2", "W5H"), O("M11", "5F4"), O("YXV", "HVW"), O("563", "KQ1"), O("GBN", "7TS"),
O("LJD", "TF3"), O("1TM", "C1V"), O("RS8", "5CF"), O("96S", "XR8"), O("GZQ", "NB3"),
O("W5L", "976"), O("BZM", "TPW"), O("D67", "488"), O("1JY", "PLR"), O("DXK", "B9Y"),
O("7W3", "3KS"), O("COM", "N59"), O("2JY", "M2N"), O("Y1D", "DG3"), O("K1Q", "H9L"),
O("Y4J", "7M7"), O("YMC", "M8R"), O("S5P", "GBM"), O("KN6", "TXJ"), O("T44", "L7C"),
O("HK4", "HGS"), O("P9R", "3FV"), O("CTX", "8J4"), O("N5D", "H7C"), O("WZ1", "1BF"),
O("7Y4", "6VZ"), O("LLZ", "827"), O("JS9", "S4P"), O("HLY", "773"), O("8KB", "RR2"),
O("4VG", "5NG"), O("87V", "NL7"), O("1BF", "HJP"), O("X4Y", "MYW"), O("9LQ", "VTC"),
O("RNH", "XWR"), O("ZFB", "RC1"), O("KSY", "MGL"), O("9PY", "Z1M"), O("15Y", "MYP"),
O("LV3", "614"), O("2C2", "R6D"), O("8Z9", "XH5"), O("HH7", "FZX"), O("HGL", "JGN"),
O("HTS", "XGV"), O("17Q", "45Q"), O("J17", "99X"), O("LMX", "BY2"), O("GZG", "YXV"),
O("8D9", "BRS"), O("18C", "MZN"), O("DP7", "VVK"), O("MXX", "PFG"), O("P1K", "9XJ"),
O("99L", "ZN6"), O("2G7", "C4M"), O("GXT", "W1G"), O("72F", "4CC"), O("YFD", "HZY"),
O("65X", "56T"), O("YR2", "5SZ"), O("D3L", "7NQ"), O("K9J", "SJC"), O("Q83", "9PS"),
O("Z91", "4T7"), O("W1K", "KVB"), O("SJF", "FVD"), O("ZG1", "63B"), O("NV5", "R16"),
O("DHZ", "FP1"), O("LZN", "ND1"), O("Z2S", "93V"), O("J8T", "GZ9"), O("W3T", "94W"),
O("JG8", "6QV"), O("MG1", "W8P"), O("FNL", "DYF"), O("255", "RF1"), O("X38", "BWS"),
O("KX7", "5ZZ"), O("9Y2", "V22"), O("QBX", "DXQ"), O("K93", "N1L"), O("653", "P31"),
O("LR9", "7FH"), O("9ZG", "3PN"), O("V5J", "CP6"), O("PDF", "15Y"), O("ZQP", "N35"),
O("ZZ8", "TCV"), O("NK3", "FDD"), O("23K", "N5J"), O("BK8", "TLY"), O("S3G", "HCL"),
O("BS6", "HK4"), O("W1J", "3Q3"), O("D7F", "X3M"), O("YWL", "ZW7"), O("DVV", "YHR"),
O("K9Z", "T8H"), O("5D5", "HLB"), O("MYW", "8R2"), O("J5M", "ZLD"), O("1GQ", "6T9"),
O("L21", "KRQ"), O("6GD", "Y77"), O("MDX", "R2N"), O("NC5", "DR9"), O("K55", "TFC"),
O("YH3", "P7W"), O("4FF", "6S4"), O("BMZ", "9PY"), O("P5H", "XKG"), O("BV7", "QBX"),
O("135", "PK9"), O("LZR", "DPH"), O("N57", "TM6"), O("VH7", "XX7"), O("MPC", "LYZ"),
O("L5B", "V6V"), O("JS2", "BS3"), O("784", "ZT7"), O("95J", "D8V"), O("F91", "4BK"),
O("3TJ", "43X"), O("6B4", "LDY"), O("DR9", "J5M"), O("3T2", "CFZ"), O("5XK", "5TH"),
O("XKG", "1SC"), O("M7B", "D48"), O("DX7", "G9P"), O("CST", "DMF"), O("7ML", "7D7"),
O("TVM", "YWL"), O("L47", "G61"), O("XBC", "W9M"), O("F4D", "3SS"), O("JV1", "T1T"),
O("G1T", "86Y"), O("3YP", "JPJ"), O("DHL", "G1L"), O("QYQ", "9PL"), O("Z76", "GFG"),
O("NGV", "TTR"), O("Q7Y", "QL7"), O("BWF", "M6M"), O("KN2", "3RQ"), O("WYP", "NZZ"),
O("KY6", "SB7"), O("JHN", "19T"), O("836", "NYV"), O("LXQ", "KG6"), O("SKJ", "XV2"),
O("XVY", "Y4L"), O("W3C", "J1L"), O("Z5P", "6B4"), O("78L", "LMG"), O("X1V", "S99"),
O("JVT", "5X4"), O("GD6", "42N"), O("RDZ", "S5Y"), O("4S2", "CJM"), O("G1L", "455"),
O("HSC", "733"), O("WZS", "N6W"), O("W5H", "ZQP"), O("QBZ", "D82"), O("V24", "K8R"),
O("CSW", "VMG"), O("X4X", "VBG"), O("C8V", "SAN"), O("YSK", "LL4"), O("FLX", "RKC"),
O("GH1", "234"), O("H5K", "T3L"), O("JZ8", "ZG1"), O("VD7", "GR3"), O("WQ7", "8KZ"),
O("Y5P", "RZX"), O("P4L", "ZSJ"), O("VMB", "32K"), O("Y7K", "JD2"), O("LYZ", "XW7"),
O("JV3", "CCH"), O("VX3", "XWY"), O("XMK", "P9R"), O("TYM", "1TM"), O("J7C", "DV8"),
O("1KF", "WQV"), O("TD2", "G4H"), O("WJ4", "XVR"), O("JW1", "VM1"), O("DRZ", "9KV"),
O("ZWJ", "TCL"), O("4D2", "8VS"), O("5RG", "W3T"), O("T6Y", "NB5"), O("GYB", "NSG"),
O("414", "1FB"), O("YRQ", "M8L"), O("YYF", "LJ4"), O("SB9", "QJS"), O("V4K", "B7K"),
O("YZH", "WGM"), O("YGH", "1MV"), O("RTD", "VZY"), O("HVK", "VZV"), O("DXW", "QDD"),
O("4G2", "MDJ"), O("R8T", "VQC"), O("1KD", "ZB7"), O("XFP", "H9N"), O("Q72", "XBC"),
O("HDD", "SS6"), O("JZ8", "N2Z"), O("X3V", "XYD"), O("FQQ", "Z4V"), O("H9L", "5CW"),
O("R2N", "LVR"), O("RKC", "MJS"), O("NYV", "3S1"), O("TRG", "G5T"), O("XZ7", "1R6"),
O("6QV", "P17"), O("WS1", "6GV"), O("W2M", "P1K"), O("1WD", "5VY"), O("RBV", "HF3"),
O("GPR", "4FH"), O("855", "BP6"), O("W2B", "LR9"), O("GN7", "9JV"), O("BP6", "4WM"),
O("JGW", "94K"), O("VWG", "Q5D"), O("LXR", "PJ7"), O("LZ1", "HXJ"), O("WLW", "NCC"),
O("MCN", "V5F"), O("5CD", "RMT"), O("57L", "LYM"), O("J52", "QLD"), O("GBD", "FBJ"),
O("HZ2", "51Z"), O("3Z1", "DF4"), O("LRZ", "8MK"), O("M2R", "G7V"), O("G98", "3VF"),
O("NB5", "JV1"), O("LL4", "25Y"), O("6T9", "6PY"), O("V4V", "R8C"), O("F7J", "BZ9"),
O("HVW", "V8K"), O("R6R", "SNM"), O("53L", "F1V"), O("R7V", "WQD"), O("3VP", "BFP"),
O("SD6", "SBX"), O("CQW", "CJL"), O("ZGV", "7RG"), O("STR", "WPJ"), O("HZQ", "R2F"),
O("M6M", "N57"), O("SCP", "D6G"), O("G3C", "DBX"), O("3XG", "V8T"), O("MSS", "F8H"),
O("VT8", "57L"), O("2W3", "MGW"), O("QK8", "HHS"), O("5HX", "TN4"), O("FLZ", "791"),
O("9XV", "3CB"), O("N6W", "KZ5"), O("NJW", "284"), O("4T7", "SKJ"), O("36R", "GBN"),
O("FTC", "V2V"), O("MQW", "X4V"), O("FPW", "G2H"), O("Q4R", "8HN"), O("2FF", "27X"),
O("818", "WDT"), O("81G", "KR2"), O("H4W", "MLP"), O("1R4", "F7J"), O("V6R", "WZ1"),
O("3PN", "N63"), O("DXL", "W1X"), O("5KH", "469"), O("V8W", "NJW"), O("6H2", "TF4"),
O("TC1", "GCM"), O("GZG", "ZXK"), O("WMV", "76P"), O("RQ5", "FT1"), O("583", "V5Y"),
O("LRT", "XDW"), O("S3T", "824"), O("GQS", "Z91"), O("YYG", "KYW"), O("GH6", "T3X"),
O("4KT", "SNX"), O("X5N", "KP2"), O("HD6", "NGV"), O("5W3", "TVM"), O("SXG", "JTF"),
O("7NQ", "2NX"), O("VQ3", "NYH"), O("7FP", "LZ1"), O("FL6", "MH8"), O("MQW", "51M"),
O("GMT", "FZS"), O("N13", "BGN"), O("STR", "MBF"), O("2P3", "MGX"), O("NGJ", "YN6"),
O("B4Z", "YYF"), O("127", "PVT"), O("SMB", "9Y2"), O("6LP", "YDB"), O("V4N", "S2W"),
O("LMX", "5RJ"), O("W1C", "FLZ"), O("BFP", "QXB"), O("BCJ", "9HF"), O("9PL", "FFV"),
O("777", "TTQ"), O("52F", "11Y"), O("7F1", "S71"), O("R4W", "Y5R"), O("9FP", "6JH"),
O("S7D", "6K7"), O("F3Z", "LV3"), O("2GG", "B6C"), O("6S4", "MYX"), O("TTS", "3YP"),
O("KMV", "MTG"), O("R8C", "ZSF"), O("8RK", "ZLL"), O("5F4", "RHJ"), O("KYS", "BL4"),
O("19T", "44V"), O("XWZ", "VT8"), O("L7C", "Z99"), O("BVV", "QPH"), O("7DR", "W5G"),
O("1B5", "RBJ"), O("1Y8", "KRN"), O("57J", "QVD"), O("S8G", "FVL"), O("F8F", "RHG"),
O("RBX", "GH1"), O("JX4", "HDD"), O("G9P", "D9G"), O("H1V", "TT6"), O("51M", "2DH"),
O("7M7", "TJ4"), O("XYX", "678"), O("G5T", "3HV"), O("758", "BYG"), O("6GF", "QZY"),
O("MYX", "JDG"), O("9S1", "ZNY"), O("T59", "NQ3"), O("CTP", "NV3"), O("DBX", "XKY"),
O("8N1", "4PP"), O("D6C", "7DH"), O("2BC", "QBZ"), O("CC3", "C7S"), O("DQT", "127"),
O("RNF", "53L"), O("ZQ4", "2J7"), O("873", "M3J"), O("XMK", "MCN"), O("BC7", "DRC"),
O("4XY", "89H"), O("8VW", "5XK"), O("8BB", "HMJ"), O("PJ7", "GDF"), O("G9C", "HMD"),
O("6VZ", "CB9"), O("32K", "S4S"), O("CMW", "ZWJ"), O("7SR", "5RP"), O("W24", "418"),
O("6L2", "F8N"), O("8QV", "W2M"), O("TXD", "M3H"), O("RBJ", "749"), O("DSJ", "SKY"),
O("DY1", "SR9"), O("VR6", "6GP"), O("1GV", "CD6"), O("S7D", "DY9"), O("8QH", "HPX"),
O("GNT", "5D5"), O("KG6", "6K8"), O("DSD", "HN6"), O("NG4", "2WP"), O("N5D", "1GQ"),
O("X2K", "F59"), O("45Q", "LXQ"), O("L3T", "N5D"),
};
};
| https://raw.githubusercontent.com/tiehuis/advent-of-code-2019/07f48c42d0870a7030d21c08626fcc40a447e695/6_1.zig |
const builtin = @import("builtin");
const std = @import("std");
pub const OpenOptions = struct {
mode: enum { read_only, read_write } = .read_only,
};
pub fn open(dir: std.fs.Dir, path: []const u8, opt: OpenOptions) !std.fs.File {
if (builtin.os.tag == .windows) {
const path_w = try std.os.windows.sliceToPrefixedFileW(path);
return std.fs.File{
.handle = try std.os.windows.OpenFile(path_w.span(), .{
.dir = dir.fd,
.access_mask = switch (opt.mode) {
.read_only => std.os.windows.SYNCHRONIZE | std.os.windows.GENERIC_READ,
.read_write =>
std.os.windows.SYNCHRONIZE |
std.os.windows.GENERIC_READ |
std.os.windows.GENERIC_WRITE,
},
.creation = std.os.windows.FILE_OPEN,
.io_mode = .blocking,
.filter = .any,
}),
.capable_io_mode = std.io.default_mode,
.intended_io_mode = .blocking,
};
}
return std.fs.File{
.handle = try std.os.openat(
dir.fd,
path,
switch (opt.mode) {
.read_only => std.os.O.RDONLY,
.read_write => std.os.O.RDWR,
},
0,
),
.capable_io_mode = std.io.default_mode,
.intended_io_mode = .blocking,
};
}
| https://raw.githubusercontent.com/marler8997/windows-coreutils/8368278afebd5d1edab6f04866b2868685869ae1/fs.zig |
const sprites = @import("sprites.zig");
const map = @import("map.zig");
const gfx = @import("gfx.zig");
const utils = @import("utils.zig");
const entity = @import("entity.zig");
const camera = @import("camera.zig");
pub const Sun = struct {
entity: entity.Entity,
x: f32,
y: f32,
width: f32 = 16,
height: f32 = 16,
pub fn init(x: f32, y: f32) Sun {
return .{
.x = x,
.y = y,
.entity = entity.Entity{
.updateFn = @ptrCast(&update),
.drawFn = @ptrCast(&draw),
},
};
}
pub fn update(self: *Sun) void {
self.x += 0.01;
}
pub fn draw(self: *Sun) void {
gfx.blit(&sprites.skull, 16, @as(i32, @intFromFloat(self.x)) - camera.xi, @as(i32, @intFromFloat(self.y)) - camera.yi, 0xe8 | (1 << 8));
}
};
| https://raw.githubusercontent.com/kivutar/uw8-platformer/290d1f7467fed4f6571251b9ac5fbe9351909fc5/sun.zig |
const std = @import("std");
// fn WindowReader(comptime len: usize) type {
// return struct {
// const Self = @This();
// buffer: [len]u8,
// reader: std.io.BufferedReader(4096, std.io.AnyReader),
// buffer_fullness: usize = 0,
// at_eof: bool = false,
// pub fn init(reader: std.io.AnyReader) Self {
// return .{
// .buffer = undefined,
// .reader = std.io.bufferedReader(reader),
// };
// }
// pub fn next(self: *Self) ?[]const u8 {
// if (self.buffer_fullness < self.buffer.len) {
// }
// }
// };
// }
pub fn main() !void {
var buf: [5]u8 = undefined;
var slice: []u8 = buf[0..1];
const stdin = std.io.getStdIn();
var buffered_reader = std.io.bufferedReader(stdin.reader());
const reader = buffered_reader.reader();
var first_digit: ?u8 = null;
var last_digit: u8 = 0;
var sum: u64 = 0;
var hit_eof = false;
read_loop: while (true) {
if (try reader.readAll(slice[slice.len - 1 ..]) == 0) {
hit_eof = true;
if (slice.len <= 1) break :read_loop;
slice = slice[0 .. slice.len - 1];
}
const current_digit = blk: {
if ('0' <= slice[0] and slice[0] <= '9') {
break :blk slice[0] - '0';
}
inline for (.{
.{ 1, "one" },
.{ 2, "two" },
.{ 3, "three" },
.{ 4, "four" },
.{ 5, "five" },
.{ 6, "six" },
.{ 7, "seven" },
.{ 8, "eight" },
.{ 9, "nine" },
}) |tup| {
const digit, const string = tup;
if (std.mem.startsWith(u8, slice, string)) {
break :blk digit;
}
}
break :blk null;
};
if (current_digit) |digit| {
if (first_digit == null) first_digit = digit;
last_digit = digit;
} else if (slice[0] == '\n') {
sum += 10 * first_digit.? + last_digit;
first_digit = null;
}
if (slice.len < buf.len and !hit_eof) {
slice = buf[0 .. slice.len + 1];
} else {
std.mem.copyForwards(u8, buf[0 .. buf.len - 1], buf[1..]);
}
}
std.debug.print("{}\n", .{sum});
}
| https://raw.githubusercontent.com/190n/aoc2023/1ce62583b707125a244f0c115d2f0ebb328ba7d6/1-2.zig |
const camera = @import("camera.zig");
pub extern fn blitSprite(i32, i32, i32, i32, i32) void;
pub extern fn rectangle(f32, f32, f32, f32, i32) void;
pub fn blit(spr: *const [256]u8, size: i32, x: i32, y: i32, ctrl: i32) void {
blitSprite(@intCast(@intFromPtr(spr)), size, x, y, ctrl);
}
pub const Anim = struct {
frames: []const [256]u8,
counter: u8 = 0,
};
| https://raw.githubusercontent.com/kivutar/uw8-platformer/290d1f7467fed4f6571251b9ac5fbe9351909fc5/gfx.zig |
const std = @import("std");
pub fn main() !void {
const stdin = std.io.getStdIn().reader();
const stdout = std.io.getStdOut().writer();
var buf: [32]u8 = undefined;
var score: u32 = 0;
while (try stdin.readUntilDelimiterOrEof(buf[0..], '\n')) |line| {
if (line.len == 0) continue;
if (line.len != 3) return error.BadLen;
const l = line[0] - 'A';
const o = line[2] - 'X';
const r = (3 + l + o - 1) % 3;
score += ([_]u8{0, 3, 6})[o] + ([_]u8{1, 2, 3})[r];
}
try stdout.print("{}\n", .{score});
}
| https://raw.githubusercontent.com/matklad/aoc2022/67800cfb0aa3dcb0103da06c0b6f2103f1494dc7/day2.zig |
//! Portable Numbers
const std = @import("std");
const builtin = @import("builtin");
pub fn getIntByteSlice(comptime T: type, n: *T) []u8 {
return @ptrCast([*]u8, n)[0..@sizeOf(T)];
}
fn zigZagEncode(comptime T: type, n: T) T {
if (n >= 0) {
var k1: T = undefined;
@shlWithOverflow(T, n, 1, &k1);
return k1;
} else {
var k1: T = undefined;
@shlWithOverflow(T, -n-1, 1, &k1);
return k1 | 1;
}
}
fn reserveInt(comptime T: type, n: T) T {
if (@typeInfo(T).Int.signedness == .signed) @compileError("expect unsigned integer");
var arr = std.PackedIntArray(T, 1).initAllTo(n).sliceCast(u8);
var buf = std.PackedIntArray(T, 1).initAllTo(n).sliceCast(u8);
for (buf.bytes) |*c, i| {
const length = if (@typeInfo(@TypeOf(arr.len)) == .BoundFn) arr.len() else arr.len;
c.* = arr.bytes[length-i-1];
}
return buf.sliceCast(T).get(0);
}
pub fn fromPortableInt(comptime T: type, n: T) T {
if (@hasDecl(std.mem, "nativeToBig")) {
return std.mem.nativeToBig(T, n);
} else {
return switch (builtin.cpu.arch.endian()) {
.Big => n,
.Little => reserveInt(T, n),
};
}
}
pub fn toPortableInt(comptime T: type, n: T) T {
if (@hasDecl(std.mem, "toNative")) {
return std.mem.toNative(T, n, .Big);
} else {
return fromPortableInt(T, n);
}
}
test "PortableInt" {
const _t = std.testing;
{
var number = @as(u8, 127);
var n = fromPortableInt(u8, number);
var n0 = toPortableInt(u8, n);
try _t.expectEqual(number, n0);
}
}
| https://raw.githubusercontent.com/kacheproject/libkache/2039d3bcc4fc841368dde04611048c866971afcb/pn.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const Location = @import("location.zig");
pub const Node = union(enum) {
alias: *Alias,
@"and": *And,
annotation: *Annotation,
annotation_def: *AnnotationDef,
arg: *Arg,
array_literal: *ArrayLiteral,
@"asm": *Asm,
asm_operand: *AsmOperand,
assign: *Assign,
block: *Block,
bool_literal: *BoolLiteral,
@"break": *Break,
c_struct_or_union_def: *CStructOrUnionDef,
call: *Call,
case: *Case,
cast: *Cast,
char_literal: *CharLiteral,
class_def: *ClassDef,
class_var: *ClassVar,
def: *Def,
double_splat: *DoubleSplat,
enum_def: *EnumDef,
exception_handler: *ExceptionHandler,
expressions: *Expressions,
extend: *Extend,
external_var: *ExternalVar,
fun_def: *FunDef,
generic: *Generic,
global: *Global,
hash_literal: *HashLiteral,
@"if": *If,
implicit_obj: *ImplicitObj,
include: *Include,
instance_size_of: *InstanceSizeOf,
instance_var: *InstanceVar,
is_a: *IsA,
lib_def: *LibDef,
macro: *Macro,
macro_expression: *MacroExpression,
macro_for: *MacroFor,
macro_if: *MacroIf,
macro_literal: *MacroLiteral,
macro_var: *MacroVar,
macro_verbatim: *MacroVerbatim,
magic_constant: *MagicConstant,
metaclass: *Metaclass,
module_def: *ModuleDef,
multi_assign: *MultiAssign,
named_argument: *NamedArgument,
named_tuple_literal: *NamedTupleLiteral,
next: *Next,
nil: *Nil,
nilable_cast: *NilableCast,
nop: *Nop,
not: *Not,
number_literal: *NumberLiteral,
offset_of: *OffsetOf,
op_assign: *OpAssign,
@"or": *Or,
out: *Out,
path: *Path,
pointer_of: *PointerOf,
proc_literal: *ProcLiteral,
proc_notation: *ProcNotation,
proc_pointer: *ProcPointer,
range_literal: *RangeLiteral,
read_instance_var: *ReadInstanceVar,
regex_literal: *RegexLiteral,
require: *Require,
rescue: *Rescue,
responds_to: *RespondsTo,
@"return": *Return,
select: *Select,
self: *Self,
size_of: *SizeOf,
splat: *Splat,
string_interpolation: *StringInterpolation,
string_literal: *StringLiteral,
symbol_literal: *SymbolLiteral,
tuple_literal: *TupleLiteral,
type_declaration: *TypeDeclaration,
type_def: *TypeDef,
type_of: *TypeOf,
underscore: *Underscore,
uninitialized_var: *UninitializedVar,
@"union": *Union,
unless: *Unless,
until: *Until,
@"var": *Var,
visibility_modifier: *VisibilityModifier,
when: *CaseWhen,
@"while": *While,
yield: *Yield,
pub fn init(exp: anytype) Node {
return exp.toNode();
}
pub fn location(node: Node) ?Location {
switch (node) {
inline else => |n| return n.location,
}
}
pub fn endLocation(node: Node) ?Location {
switch (node) {
inline else => |n| return n.end_location,
}
}
pub fn setLocation(node: Node, loc: ?Location) void {
switch (node) {
inline else => |n| n.location = loc,
}
}
pub fn setEndLocation(node: Node, end_location: ?Location) void {
switch (node) {
inline else => |n| n.end_location = end_location,
}
}
pub fn copyLocation(self: Node, node: Node) void {
self.setLocation(node.location());
self.setEndLocation(node.endLocation());
}
pub fn copyEndLocation(self: Node, node: Node) void {
self.setEndLocation(node.endLocation());
}
pub fn isNop(node: Node) bool {
return node == .nop;
}
pub fn isTrueLiteral(node: Node) bool {
return node == .bool_literal and node.bool_literal.value;
}
pub fn isFalseLiteral(node: Node) bool {
return node == .bool_literal and !node.bool_literal.value;
}
pub fn singleExpression(node: Node) Node {
switch (node) {
.expressions => |expressions| {
if (expressions.singleExpression()) |single_expression| {
return single_expression;
} else {
return node;
}
},
else => return node,
}
}
pub fn isSingleExpression(node: Node) bool {
return switch (node) {
.expressions => |expressions| expressions.isSingleExpression(),
else => false,
};
}
};
fn NodeAllocator(
comptime name: []const u8,
comptime NodeType: type,
comptime expressions: []const []const u8,
) type {
const parameters = @typeInfo(NodeType).Struct.fields;
invalid: inline for (expressions) |exp| {
inline for (parameters) |param| {
if (comptime std.mem.eql(u8, param.name, exp))
continue :invalid;
}
@compileError("invalid parameter '" ++ exp ++ "' for " ++ @typeName(NodeType));
}
return struct {
pub fn allocate(allocator: Allocator, options: anytype) !*NodeType {
const OptionsType = @TypeOf(options);
const options_type_info = @typeInfo(OptionsType);
if (options_type_info != .Struct) {
@compileError("expected tuple or struct argument, found " ++ @typeName(OptionsType));
}
const arguments = options_type_info.Struct.fields;
unknown: inline for (arguments) |arg| {
inline for (parameters) |param| {
if (comptime std.mem.eql(u8, param.name, arg.name))
continue :unknown;
}
@compileError("unknown argument '" ++ arg.name ++ "' for " ++ @typeName(NodeType));
}
const instance = try allocator.create(NodeType);
inline for (parameters) |param| {
@field(instance, param.name) = blk: {
inline for (arguments) |arg| {
if (comptime std.mem.eql(u8, param.name, arg.name)) {
const value = @field(options, arg.name);
inline for (expressions) |exp| {
if (comptime std.mem.eql(u8, exp, arg.name))
break :blk try Expressions.from(allocator, value);
}
break :blk value;
}
}
if (param.default_value) |default_value|
break :blk @ptrCast(*align(1) const param.field_type, default_value).*;
@compileError("missing argument '" ++ param.name ++ "' for " ++ @typeName(NodeType));
};
}
return instance;
}
pub fn node(allocator: Allocator, options: anytype) !Node {
return Node.init(try allocate(allocator, options));
}
fn toNode(self: *NodeType) Node {
return @unionInit(Node, name, self);
}
};
}
fn Singleton(comptime name: []const u8) type {
return struct {
location: ?Location = null,
end_location: ?Location = null,
pub usingnamespace NodeAllocator(name, @This(), &.{});
};
}
pub const Nop = Singleton("nop");
pub const Nil = Singleton("nil");
pub const Expressions = struct {
pub const Keyword = enum {
none,
paren,
begin,
};
location: ?Location = null,
end_location: ?Location = null,
expressions: ArrayList(Node),
keyword: Keyword = .none,
pub usingnamespace NodeAllocator("expressions", Expressions, &.{});
pub fn from(allocator: Allocator, obj: anytype) !Node {
switch (@TypeOf(obj)) {
@TypeOf(null) => return Nop.node(allocator, .{}),
ArrayList(Node) => {
switch (obj.items.len) {
0 => return Nop.node(allocator, .{}),
1 => return obj.items[0],
else => return Expressions.node(allocator, .{
.expressions = obj,
}),
}
},
Node => return obj,
?Node => return if (obj) |n| n else Nop.node(allocator, .{}),
else => @compileError("Expected Node or ArrayList(Node), found " ++ @typeName(@TypeOf(obj))),
}
}
pub fn isEmpty(self: *const @This()) bool {
return self.expressions.items.len == 0;
}
pub fn at(self: *const @This(), i: usize) Node {
return self.expressions.items[i];
}
pub fn last(self: *const @This()) Node {
const expressions = self.expressions.items;
return expressions[expressions.len - 1];
}
pub fn isSingleExpression(self: *const @This()) bool {
return self.expressions.items.len == 1;
}
pub fn singleExpression(self: *const @This()) ?Node {
if (self.isSingleExpression()) {
return self.expressions.items[0].singleExpression();
} else {
return null;
}
}
};
pub const BoolLiteral = struct {
location: ?Location = null,
end_location: ?Location = null,
value: bool,
pub usingnamespace NodeAllocator("bool_literal", @This(), &.{});
};
pub const NumberKind = enum {
i8,
i16,
i32,
i64,
i128,
u8,
u16,
u32,
u64,
u128,
f32,
f64,
pub fn bytesize(self: @This()) u8 {
return switch (self) {
.i8 => 8,
.i16 => 16,
.i32 => 32,
.i64 => 64,
.i128 => 128,
.u8 => 8,
.u16 => 16,
.u32 => 32,
.u64 => 64,
.u128 => 128,
.f32 => 32,
.f64 => 64,
};
}
pub fn isSignedInt(self: @This()) bool {
return switch (self) {
.i8, .i16, .i32, .i64, .i128 => true,
else => false,
};
}
pub fn isUnignedInt(self: @This()) bool {
return switch (self) {
.u8, .u16, .u32, .u64, .u128 => true,
else => false,
};
}
pub fn isFloat(self: @This()) bool {
return switch (self) {
.f32, .f64 => true,
else => false,
};
}
pub fn fromNumber(number: anytype) @This() {
switch (@TypeOf(number)) {
i8 => return .i8,
i16 => return .i16,
i32 => return .i32,
i64 => return .i64,
i128 => return .i128,
u8 => return .u8,
u16 => return .u16,
u32 => return .u32,
u64 => return .u64,
u128 => return .u128,
f32 => return .f32,
f64 => return .f64,
comptime_int => comptime {
if (number >= std.math.minInt(i32) and number <= std.math.maxInt(i32)) return .i32;
if (number >= std.math.minInt(i64) and number <= std.math.maxInt(i64)) return .i64;
if (number >= std.math.minInt(i128) and number <= std.math.maxInt(i128)) return .i128;
if (number >= std.math.minInt(u128) and number <= std.math.maxInt(u128)) return .u128;
@compileError("Unsupported int for NumberLiteral: " ++ std.fmt.comptimePrint("{}", .{number}));
},
comptime_float => comptime {
if (number == 0.0) return .f32;
if (@fabs(number) >= std.math.f32_min and @fabs(number) <= std.math.f32_max) return .f32;
if (@fabs(number) >= std.math.f64_min and @fabs(number) <= std.math.f64_max) return .f64;
@compileError("Unsupported float for NumberLiteral: " ++ std.fmt.comptimePrint("{}", .{number}));
},
else => @compileError("Unsupported number type for NumberLiteral: " ++ @typeName(@TypeOf(number))),
}
}
pub fn numberType(self: @This()) type {
return switch (self) {
.i8 => i8,
.i16 => i16,
.i32 => i32,
.i64 => i64,
.i128 => i128,
.u8 => u8,
.u16 => u16,
.u32 => u32,
.u64 => u64,
.u128 => u128,
.f32 => f32,
.f64 => f64,
};
}
};
pub const NumberLiteral = struct {
location: ?Location = null,
end_location: ?Location = null,
value: []const u8,
kind: NumberKind = .i32,
pub usingnamespace NodeAllocator("number_literal", @This(), &.{});
pub fn fromNumber(allocator: Allocator, number: anytype) !Node {
return NumberLiteral.node(allocator, .{
.value = try std.fmt.allocPrint(
allocator,
"{d}",
.{number},
),
.kind = NumberKind.fromNumber(number),
});
}
pub fn hasSign(self: *const @This()) bool {
return self.value[0] == '+' or self.value[0] == '-';
}
};
pub const CharLiteral = struct {
location: ?Location = null,
end_location: ?Location = null,
value: u8,
pub usingnamespace NodeAllocator("char_literal", @This(), &.{});
};
pub const StringLiteral = struct {
location: ?Location = null,
end_location: ?Location = null,
value: []const u8,
pub usingnamespace NodeAllocator("string_literal", @This(), &.{});
};
pub const StringInterpolation = struct {
location: ?Location = null,
end_location: ?Location = null,
expressions: ArrayList(Node),
heredoc_indent: i32 = 0,
pub usingnamespace NodeAllocator("string_interpolation", @This(), &.{});
};
pub const SymbolLiteral = struct {
location: ?Location = null,
end_location: ?Location = null,
value: []const u8,
pub usingnamespace NodeAllocator("symbol_literal", @This(), &.{});
};
pub const ArrayLiteral = struct {
location: ?Location = null,
end_location: ?Location = null,
elements: ArrayList(Node),
of: ?Node = null,
name: ?Node = null,
pub usingnamespace NodeAllocator("array_literal", @This(), &.{});
pub fn map(
allocator: Allocator,
values: anytype,
options: struct {
of: ?Node = null,
},
block: anytype,
) !Node {
// TODO: validate values and block
var new_values = try ArrayList(Node).initCapacity(allocator, values.items.len);
for (values.items) |value| {
new_values.appendAssumeCapacity(try block(allocator, value));
}
return ArrayLiteral.node(allocator, .{
.elements = new_values,
.of = options.of,
});
}
pub fn mapWithIndex(
allocator: Allocator,
values: anytype,
block: anytype,
) !Node {
// TODO: validate values and block
var new_values = try ArrayList(Node).initCapacity(allocator, values.items.len);
for (values.items) |value, index| {
new_values.appendAssumeCapacity(try block(allocator, value, index));
}
return ArrayLiteral.node(allocator, .{
.elements = new_values,
.of = null,
});
}
};
pub const HashLiteral = struct {
location: ?Location = null,
end_location: ?Location = null,
entries: ArrayList(Entry),
of: ?Entry = null,
name: ?Node = null,
pub usingnamespace NodeAllocator("hash_literal", @This(), &.{});
pub const Entry = struct {
key: Node,
value: Node,
pub fn init(key: Node, value: Node) Entry {
return .{ .key = key, .value = value };
}
};
};
pub const NamedTupleLiteral = struct {
location: ?Location = null,
end_location: ?Location = null,
entries: ArrayList(Entry),
pub usingnamespace NodeAllocator("named_tuple_literal", @This(), &.{});
pub const Entry = struct { key: []const u8, value: Node };
};
pub const RangeLiteral = struct {
location: ?Location = null,
end_location: ?Location = null,
from: Node,
to: Node,
is_exclusive: bool,
pub usingnamespace NodeAllocator("range_literal", @This(), &.{});
};
pub const RegexOptions = struct {
location: ?Location = null,
end_location: ?Location = null,
ignore_case: bool = false,
multiline: bool = false,
extended: bool = false,
anchored: bool = false,
utf_8: bool = false,
no_utf8_check: bool = false,
dupnames: bool = false,
ucp: bool = false,
};
pub const RegexLiteral = struct {
location: ?Location = null,
end_location: ?Location = null,
value: Node,
options: RegexOptions = .{},
pub usingnamespace NodeAllocator("regex_literal", @This(), &.{});
};
pub const TupleLiteral = struct {
location: ?Location = null,
end_location: ?Location = null,
elements: ArrayList(Node),
pub usingnamespace NodeAllocator("tuple_literal", @This(), &.{});
};
fn SpecialVar(comptime NodeType: type) type {
return struct {
pub fn isSpecialVar(self: *const NodeType) bool {
return std.mem.startsWith(u8, self.name, "$");
}
};
}
pub const Var = struct {
pub usingnamespace SpecialVar(@This());
location: ?Location = null,
end_location: ?Location = null,
name: []const u8,
pub usingnamespace NodeAllocator("var", @This(), &.{});
};
pub const Block = struct {
location: ?Location = null,
end_location: ?Location = null,
args: ArrayList(*Var),
body: Node,
call: ?*Call = null,
splat_index: ?i32 = null,
pub usingnamespace NodeAllocator("block", @This(), &.{"body"});
};
pub const Call = struct {
location: ?Location = null,
end_location: ?Location = null,
obj: ?Node,
name: []const u8,
args: ArrayList(Node),
block: ?*Block = null,
block_arg: ?Node = null,
named_args: ?ArrayList(*NamedArgument) = null,
name_location: ?Location = null,
// name_size: ?usize = null,
doc: ?[]const u8 = null,
visibility: Visibility = .public,
is_global: bool = false,
is_expansion: bool = false,
has_parentheses: bool = false,
pub usingnamespace NodeAllocator("call", @This(), &.{});
};
pub const NamedArgument = struct {
location: ?Location = null,
end_location: ?Location = null,
name: []const u8,
value: Node,
pub usingnamespace NodeAllocator("named_argument", @This(), &.{});
};
pub const If = struct {
location: ?Location = null,
end_location: ?Location = null,
cond: Node,
then: Node,
@"else": Node,
is_ternary: bool = false,
pub usingnamespace NodeAllocator(
"if",
@This(),
&.{ "then", "else" },
);
};
pub const Unless = struct {
location: ?Location = null,
end_location: ?Location = null,
cond: Node,
then: Node,
@"else": Node,
pub usingnamespace NodeAllocator(
"unless",
@This(),
&.{ "then", "else" },
);
};
pub const Assign = struct {
location: ?Location = null,
end_location: ?Location = null,
target: Node,
value: Node,
doc: ?[]const u8 = null,
pub usingnamespace NodeAllocator("assign", @This(), &.{});
};
pub const OpAssign = struct {
location: ?Location = null,
end_location: ?Location = null,
target: Node,
op: []const u8,
value: Node,
pub usingnamespace NodeAllocator("op_assign", @This(), &.{});
};
pub const MultiAssign = struct {
location: ?Location = null,
end_location: ?Location = null,
targets: ArrayList(Node),
values: ArrayList(Node),
pub usingnamespace NodeAllocator("multi_assign", @This(), &.{});
};
fn SimpleNamedNode(comptime name: []const u8) type {
return struct {
location: ?Location = null,
end_location: ?Location = null,
name: []const u8,
pub usingnamespace NodeAllocator(name, @This(), &.{});
};
}
pub const InstanceVar = SimpleNamedNode("instance_var");
pub const ReadInstanceVar = struct {
location: ?Location = null,
end_location: ?Location = null,
obj: Node,
name: []const u8,
pub usingnamespace NodeAllocator("read_instance_var", @This(), &.{});
};
pub const ClassVar = SimpleNamedNode("class_var");
pub const Global = SimpleNamedNode("global");
fn BinaryOp(comptime name: []const u8) type {
return struct {
location: ?Location = null,
end_location: ?Location = null,
left: Node,
right: Node,
pub usingnamespace NodeAllocator(name, @This(), &.{});
};
}
pub const And = BinaryOp("and");
pub const Or = BinaryOp("or");
pub const Arg = struct {
location: ?Location = null,
end_location: ?Location = null,
name: []const u8,
external_name: []const u8,
default_value: ?Node = null,
restruction: ?Node = null,
doc: ?[]const u8 = null,
pub usingnamespace NodeAllocator("arg", @This(), &.{});
};
pub const ProcNotation = struct {
location: ?Location = null,
end_location: ?Location = null,
inputs: ?ArrayList(Node) = null,
output: ?Node = null,
pub usingnamespace NodeAllocator("proc_notation", @This(), &.{});
};
pub const Def = struct {
location: ?Location = null,
end_location: ?Location = null,
free_vars: ?ArrayList([]const u8) = null,
receiver: ?Node = null,
name: []const u8,
args: ArrayList(*Arg),
double_splat: ?*Arg = null,
body: Node,
block_arg: ?*Arg = null,
return_type: ?Node = null,
yields: ?i32 = null,
splat_index: ?i32 = null,
doc: ?[]const u8 = null,
visibility: Visibility = .public,
is_macro_def: bool = false,
calls_super: bool = false,
calls_initialize: bool = false,
calls_previous_def: bool = false,
uses_block_arg: bool = false,
assigns_special_var: bool = false,
is_abstract: bool = false,
pub usingnamespace NodeAllocator("def", @This(), &.{"body"});
};
pub const Macro = struct {
location: ?Location = null,
end_location: ?Location = null,
name: []const u8,
args: ArrayList(*Arg),
body: Node,
double_splat: ?*Arg = null,
block_arg: ?*Arg = null,
splat_index: ?i32 = null,
doc: ?[]const u8 = null,
visibility: Visibility = .public,
pub usingnamespace NodeAllocator("macro", @This(), &.{"body"});
};
fn UnaryExpression(comptime name: []const u8) type {
return struct {
location: ?Location = null,
end_location: ?Location = null,
exp: Node,
pub usingnamespace NodeAllocator(name, @This(), &.{});
};
}
pub const Not = UnaryExpression("not");
pub const PointerOf = UnaryExpression("pointer_of");
pub const SizeOf = UnaryExpression("size_of");
pub const InstanceSizeOf = UnaryExpression("instance_size_of");
pub const Out = UnaryExpression("out");
pub const OffsetOf = struct {
location: ?Location = null,
end_location: ?Location = null,
offsetof_type: Node,
offset: Node,
pub usingnamespace NodeAllocator("offset_of", @This(), &.{});
};
pub const VisibilityModifier = struct {
location: ?Location = null,
end_location: ?Location = null,
modifier: Visibility,
exp: Node,
doc: ?[]const u8 = null,
pub usingnamespace NodeAllocator("visibility_modifier", @This(), &.{});
};
pub const IsA = struct {
location: ?Location = null,
end_location: ?Location = null,
obj: Node,
@"const": Node,
is_nil_check: bool = false,
pub usingnamespace NodeAllocator("is_a", @This(), &.{});
};
pub const RespondsTo = struct {
location: ?Location = null,
end_location: ?Location = null,
obj: Node,
name: []const u8,
pub usingnamespace NodeAllocator("responds_to", @This(), &.{});
};
pub const Require = struct {
location: ?Location = null,
end_location: ?Location = null,
string: []const u8,
pub usingnamespace NodeAllocator("require", @This(), &.{});
};
pub usingnamespace struct {
// Conflicts with Select.When
pub const When = CaseWhen;
};
const CaseWhen = struct {
location: ?Location = null,
end_location: ?Location = null,
conds: ArrayList(Node),
body: Node,
is_exhaustive: bool = false,
pub usingnamespace NodeAllocator("when", @This(), &.{"body"});
};
pub const Case = struct {
location: ?Location = null,
end_location: ?Location = null,
cond: ?Node,
whens: ArrayList(*CaseWhen),
@"else": ?Node,
is_exhaustive: bool,
pub usingnamespace NodeAllocator("case", @This(), &.{});
};
pub const Select = struct {
pub const When = struct {
condition: Node,
body: Node,
pub fn init(condition: Node, body: Node) When {
return .{ .condition = condition, .body = body };
}
};
location: ?Location = null,
end_location: ?Location = null,
whens: ArrayList(When),
@"else": ?Node = null,
pub usingnamespace NodeAllocator("select", @This(), &.{});
};
pub const ImplicitObj = struct {
location: ?Location = null,
end_location: ?Location = null,
pub usingnamespace NodeAllocator("implicit_obj", @This(), &.{});
};
pub const Path = struct {
location: ?Location = null,
end_location: ?Location = null,
names: ArrayList([]const u8),
is_global: bool = false,
visibility: Visibility = .public,
pub usingnamespace NodeAllocator("path", @This(), &.{});
pub fn global(allocator: Allocator, name: []const u8) !Node {
var names = ArrayList([]const u8).init(allocator);
try names.append(name);
return Node.init(try Path.allocate(allocator, .{
.names = names,
.is_global = true,
}));
}
};
pub const ClassDef = struct {
location: ?Location = null,
end_location: ?Location = null,
name: *Path,
body: Node,
superclass: ?Node = null,
type_vars: ?ArrayList([]const u8) = null,
doc: ?[]const u8 = null,
splat_index: ?i32 = null,
is_abstract: bool = false,
is_struct: bool = false,
visibility: Visibility = .public,
pub usingnamespace NodeAllocator("class_def", @This(), &.{"body"});
};
pub const ModuleDef = struct {
location: ?Location = null,
end_location: ?Location = null,
name: *Path,
body: Node,
type_vars: ?ArrayList([]const u8) = null,
splat_index: ?i32 = null,
doc: ?[]const u8 = null,
visibility: Visibility = .public,
pub usingnamespace NodeAllocator("module_def", @This(), &.{"body"});
};
pub const AnnotationDef = struct {
location: ?Location = null,
end_location: ?Location = null,
name: *Path,
doc: ?[]const u8 = null,
pub usingnamespace NodeAllocator("annotation_def", @This(), &.{});
};
pub const While = struct {
location: ?Location = null,
end_location: ?Location = null,
cond: Node,
body: Node,
pub usingnamespace NodeAllocator("while", @This(), &.{"body"});
};
pub const Until = struct {
location: ?Location = null,
end_location: ?Location = null,
cond: Node,
body: Node,
pub usingnamespace NodeAllocator("until", @This(), &.{"body"});
};
pub const Generic = struct {
location: ?Location = null,
end_location: ?Location = null,
name: Node,
type_vars: ArrayList(Node),
named_args: ?ArrayList(*NamedArgument) = null,
suffix: Suffix = .none,
pub const Suffix = enum {
none,
question,
asterisk,
bracket,
};
pub usingnamespace NodeAllocator("generic", @This(), &.{});
};
pub const TypeDeclaration = struct {
location: ?Location = null,
end_location: ?Location = null,
@"var": Node,
declared_type: Node,
value: ?Node = null,
pub usingnamespace NodeAllocator("type_declaration", @This(), &.{});
};
pub const UninitializedVar = struct {
location: ?Location = null,
end_location: ?Location = null,
@"var": Node,
declared_type: Node,
pub usingnamespace NodeAllocator("uninitialized_var", @This(), &.{});
};
pub const Rescue = struct {
location: ?Location = null,
end_location: ?Location = null,
body: Node,
types: ?ArrayList(Node) = null,
name: ?[]const u8 = null,
pub usingnamespace NodeAllocator("rescue", @This(), &.{"body"});
};
pub const ExceptionHandler = struct {
location: ?Location = null,
end_location: ?Location = null,
body: Node,
rescues: ?ArrayList(*Rescue) = null,
@"else": ?Node = null,
ensure: ?Node = null,
is_implicit: bool = false,
is_suffix: bool = false,
pub usingnamespace NodeAllocator(
"exception_handler",
@This(),
&.{"body"},
);
};
pub const ProcLiteral = struct {
location: ?Location = null,
end_location: ?Location = null,
def: *Def,
pub usingnamespace NodeAllocator("proc_literal", @This(), &.{});
};
pub const ProcPointer = struct {
location: ?Location = null,
end_location: ?Location = null,
obj: ?Node,
name: []const u8,
args: ArrayList(Node),
pub usingnamespace NodeAllocator("proc_pointer", @This(), &.{});
};
pub const Union = struct {
location: ?Location = null,
end_location: ?Location = null,
types: ArrayList(Node),
pub usingnamespace NodeAllocator("union", @This(), &.{});
};
pub const Self = Singleton("self");
fn ControlExpression(comptime name: []const u8) type {
return struct {
location: ?Location = null,
end_location: ?Location = null,
exp: ?Node = null,
pub usingnamespace NodeAllocator(name, @This(), &.{});
};
}
pub const Return = ControlExpression("return");
pub const Break = ControlExpression("break");
pub const Next = ControlExpression("next");
pub const Yield = struct {
location: ?Location = null,
end_location: ?Location = null,
exps: ArrayList(Node),
scope: ?Node = null,
has_parentheses: bool = false,
pub usingnamespace NodeAllocator("yield", @This(), &.{});
};
pub const Include = struct {
location: ?Location = null,
end_location: ?Location = null,
name: Node,
pub usingnamespace NodeAllocator("include", @This(), &.{});
};
pub const Extend = struct {
location: ?Location = null,
end_location: ?Location = null,
name: Node,
pub usingnamespace NodeAllocator("extend", @This(), &.{});
};
pub const LibDef = struct {
location: ?Location = null,
end_location: ?Location = null,
name: []const u8,
body: Node,
name_location: ?Location = null,
visibility: Visibility = .public,
pub usingnamespace NodeAllocator("lib_def", @This(), &.{"body"});
};
pub const FunDef = struct {
location: ?Location = null,
end_location: ?Location = null,
name: []const u8,
args: ArrayList(*Arg),
return_type: ?Node = null,
body: ?Node = null,
real_name: []const u8,
doc: ?[]const u8 = null,
varargs: bool = false,
pub usingnamespace NodeAllocator("fun_def", @This(), &.{});
};
pub const TypeDef = struct {
location: ?Location = null,
end_location: ?Location = null,
name: []const u8,
type_spec: Node,
name_location: ?Location = null,
pub usingnamespace NodeAllocator("type_def", @This(), &.{});
};
pub const CStructOrUnionDef = struct {
location: ?Location = null,
end_location: ?Location = null,
name: []const u8,
body: Node,
is_union: bool = false,
pub usingnamespace NodeAllocator(
"c_struct_or_union_def",
@This(),
&.{"body"},
);
};
pub const EnumDef = struct {
location: ?Location = null,
end_location: ?Location = null,
name: *Path,
members: ArrayList(Node),
base_type: ?Node = null,
doc: ?[]const u8 = null,
visibility: Visibility = .public,
pub usingnamespace NodeAllocator("enum_def", @This(), &.{});
};
pub const ExternalVar = struct {
location: ?Location = null,
end_location: ?Location = null,
name: []const u8,
type_spec: Node,
real_name: ?[]const u8 = null,
pub usingnamespace NodeAllocator("external_var", @This(), &.{});
};
pub const Alias = struct {
location: ?Location = null,
end_location: ?Location = null,
name: *Path,
value: Node,
doc: ?[]const u8 = null,
visibility: Visibility = .public,
pub usingnamespace NodeAllocator("alias", @This(), &.{});
};
pub const Metaclass = struct {
location: ?Location = null,
end_location: ?Location = null,
name: Node,
pub usingnamespace NodeAllocator("metaclass", @This(), &.{});
};
pub const Cast = struct {
location: ?Location = null,
end_location: ?Location = null,
obj: Node,
to: Node,
pub usingnamespace NodeAllocator("cast", @This(), &.{});
};
pub const NilableCast = struct {
location: ?Location = null,
end_location: ?Location = null,
obj: Node,
to: Node,
pub usingnamespace NodeAllocator("nilable_cast", @This(), &.{});
};
pub const TypeOf = struct {
location: ?Location = null,
end_location: ?Location = null,
expressions: ArrayList(Node),
pub usingnamespace NodeAllocator("type_of", @This(), &.{});
};
pub const Annotation = struct {
location: ?Location = null,
end_location: ?Location = null,
path: Path,
args: ArrayList(Node),
named_args: ?ArrayList(*NamedArgument) = null,
doc: ?[]const u8 = null,
pub usingnamespace NodeAllocator("annotation", @This(), &.{});
};
pub const MacroExpression = struct {
location: ?Location = null,
end_location: ?Location = null,
exp: Node,
output: bool = true,
pub usingnamespace NodeAllocator("macro_expression", @This(), &.{});
};
pub const MacroLiteral = struct {
location: ?Location = null,
end_location: ?Location = null,
value: []const u8,
pub usingnamespace NodeAllocator("macro_literal", @This(), &.{});
};
pub const MacroVerbatim = UnaryExpression("macro_verbatim");
pub const MacroIf = struct {
location: ?Location = null,
end_location: ?Location = null,
cond: Node,
then: Node,
@"else": Node,
pub usingnamespace NodeAllocator(
"macro_if",
@This(),
&.{ "then", "else" },
);
};
pub const MacroFor = struct {
location: ?Location = null,
end_location: ?Location = null,
vars: ArrayList(*Var),
exp: Node,
body: Node,
pub usingnamespace NodeAllocator("macro_for", @This(), &.{});
};
pub const MacroVar = struct {
location: ?Location = null,
end_location: ?Location = null,
name: []const u8,
exps: ?ArrayList(Node) = null,
pub usingnamespace NodeAllocator("macro_var", @This(), &.{});
};
pub const Underscore = Singleton("underscore");
pub const Splat = UnaryExpression("splat");
pub const DoubleSplat = UnaryExpression("double_splat");
pub const MagicConstant = struct {
location: ?Location = null,
end_location: ?Location = null,
name: []const u8, // Symbol
pub fn expandLineNode(
allocator: Allocator,
location: ?Location,
) !Node {
return NumberLiteral.fromNumber(allocator, try expandLine(location));
}
pub fn expandLine(location: ?Location) !i32 {
if (location) |loc| {
return std.math.cast(i32, loc.line_number) orelse error.Overflow;
}
return 0;
}
};
pub const Asm = struct {
location: ?Location = null,
end_location: ?Location = null,
text: []const u8,
outputs: ?ArrayList(*AsmOperand) = null,
inputs: ?ArrayList(*AsmOperand) = null,
clobbers: ?ArrayList([]const u8) = null,
@"volatile": bool = false,
alignstack: bool = false,
intel: bool = false,
can_throw: bool = false,
pub usingnamespace NodeAllocator("asm", @This(), &.{});
};
pub const AsmOperand = struct {
location: ?Location = null,
end_location: ?Location = null,
constraint: []const u8,
exp: Node,
pub usingnamespace NodeAllocator("asm_operand", @This(), &.{});
};
pub const Visibility = enum(i8) {
public,
protected,
private,
};
// zig fmt: off
pub fn main() !void {
// const p = @import("std").debug.print;
const p = struct {
fn f(fmt: []const u8, args: anytype) void {
_ = fmt;
_ = args;
}
}.f;
const assert = @import("std").debug.assert;
const allocator = std.heap.page_allocator;
var n: Node = undefined;
p("{}\n", .{ @TypeOf(std.debug) });
p("{}\n", .{ @as(std.meta.Tag(Node), .nop) });
// p("{}\n", .{ Node { .expressions = .{ .expressions = &.{} } } });
// p("{}\n", .{ Node { .expressions = .{ .expressions = &.{}, .keyword = .paren } } });
assert(NumberKind.fromNumber(0) != .i8);
assert(NumberKind.fromNumber(128) != .i16);
assert(NumberKind.fromNumber(32768) == .i32);
assert(NumberKind.fromNumber(2147483648) == .i64);
assert(NumberKind.fromNumber(9223372036854775808) == .i128);
assert(NumberKind.fromNumber(170141183460469231731687303715884105728) == .u128);
assert(NumberKind.fromNumber(0.0) == .f32);
assert(NumberKind.fromNumber(-3.402823466385288598121e+38) == .f64);
// p("{}\n", .{NumberKind.fromNumber(-1.797693134862315708151e+308)});
// p("{}\n", .{NumberKind.fromNumber(340282366920938463463374607431768211456)});
p("{}\n", .{NumberKind.fromNumber(@as(f64, -3.402823466385288598121e+38))});
p("{}\n", .{NumberKind.fromNumber(@as(f64, -1.79769313486231570815e+308))});
p("{}\n", .{NumberKind.fromNumber(@as(i8, 1))});
p("{}\n", .{NumberKind.fromNumber(@as(i16, 1))});
p("{}\n", .{NumberKind.fromNumber(@as(i32, 1))});
p("{}\n", .{NumberKind.fromNumber(@as(i64, 1))});
p("{}\n", .{NumberKind.fromNumber(@as(i128, 1))});
p("{}\n", .{NumberKind.fromNumber(@as(u8, 1))});
p("{}\n", .{NumberKind.fromNumber(@as(u16, 1))});
p("{}\n", .{NumberKind.fromNumber(@as(u32, 1))});
p("{}\n", .{NumberKind.fromNumber(@as(u64, 1))});
p("{}\n", .{NumberKind.fromNumber(@as(u128, 1))});
p("{}\n", .{NumberKind.fromNumber(@as(f32, 1))});
p("{}\n", .{NumberKind.fromNumber(@as(f64, 1))});
p("{}\n", .{NumberKind.fromNumber(@as(i8, 1)).bytesize()});
p("{}\n", .{NumberKind.fromNumber(@as(i16, 1)).bytesize()});
p("{}\n", .{NumberKind.fromNumber(@as(i32, 1)).bytesize()});
p("{}\n", .{NumberKind.fromNumber(@as(i64, 1)).bytesize()});
p("{}\n", .{NumberKind.fromNumber(@as(i128, 1)).bytesize()});
p("{}\n", .{NumberKind.fromNumber(@as(u8, 1)).bytesize()});
p("{}\n", .{NumberKind.fromNumber(@as(u16, 1)).bytesize()});
p("{}\n", .{NumberKind.fromNumber(@as(u32, 1)).bytesize()});
p("{}\n", .{NumberKind.fromNumber(@as(u64, 1)).bytesize()});
p("{}\n", .{NumberKind.fromNumber(@as(u128, 1)).bytesize()});
p("{}\n", .{NumberKind.fromNumber(@as(f32, 1)).bytesize()});
p("{}\n", .{NumberKind.fromNumber(@as(f64, 1)).bytesize()});
p("{}\n", .{NumberKind.fromNumber(@as(i32, 1)).isSignedInt()});
p("{}\n", .{NumberKind.fromNumber(@as(i32, 1)).isUnignedInt()});
p("{}\n", .{NumberKind.fromNumber(@as(i32, 1)).isFloat()});
p("{}\n", .{NumberKind.fromNumber(@as(u32, 1)).isSignedInt()});
p("{}\n", .{NumberKind.fromNumber(@as(u32, 1)).isUnignedInt()});
p("{}\n", .{NumberKind.fromNumber(@as(u32, 1)).isFloat()});
p("{}\n", .{NumberKind.fromNumber(@as(f32, 1)).isSignedInt()});
p("{}\n", .{NumberKind.fromNumber(@as(f32, 1)).isUnignedInt()});
p("{}\n", .{NumberKind.fromNumber(@as(f32, 1)).isFloat()});
// p("{}\n", .{ Node { .number_literal = .{ .value = "1", .kind = .i8 } } });
// p("{}\n", .{ Node { .number_literal = .{ .value = "1", .kind = .i16 } } });
// p("{}\n", .{ Node { .number_literal = .{ .value = "1", .kind = .i32 } } });
// p("{}\n", .{ Node { .number_literal = .{ .value = "1", .kind = .i64 } } });
// p("{}\n", .{ Node { .number_literal = .{ .value = "1", .kind = .i128 } } });
// p("{}\n", .{ Node { .number_literal = .{ .value = "1", .kind = .u8 } } });
// p("{}\n", .{ Node { .number_literal = .{ .value = "1", .kind = .u16 } } });
// p("{}\n", .{ Node { .number_literal = .{ .value = "1", .kind = .u32 } } });
// p("{}\n", .{ Node { .number_literal = .{ .value = "1", .kind = .u64 } } });
// p("{}\n", .{ Node { .number_literal = .{ .value = "1", .kind = .u128 } } });
// p("{}\n", .{ Node { .number_literal = .{ .value = "1", .kind = .f32 } } });
// p("{}\n", .{ Node { .number_literal = .{ .value = "1", .kind = .f64 } } });
// n = .{ .number_literal = .{ .value = "1" } }; p("{}\n", .{ n.number_literal.hasSign() });
// n = .{ .number_literal = .{ .value = "+1" } }; p("{}\n", .{ n.number_literal.hasSign() });
// n = .{ .number_literal = .{ .value = "-1" } }; p("{}\n", .{ n.number_literal.hasSign() });
n = try NumberLiteral.fromNumber(allocator, 1); p("{s}\n", .{ n.number_literal.value });
n = try NumberLiteral.fromNumber(allocator, 1); p("{}\n", .{ n.number_literal.hasSign() });
// p("{}\n", .{@TypeOf(null)});
// p("{}\n", .{@Type(.Null)});
p("{}\n", .{try Expressions.from(allocator, null)});
// const x: []*Node = &.{};
// p("{}\n", .{[]*Node});
// p("{}\n", .{@TypeOf(x)});
p("{}\n", .{try Expressions.from(allocator, try NumberLiteral.fromNumber(allocator, 1))});
p("{}\n", .{try Expressions.from(allocator, ArrayList(Node).init(allocator))});
// {
// var list = ArrayList(Node).init(allocator);
// list = ArrayList(Node).init(allocator); try list.append(try NumberLiteral.fromNumber(allocator, 2)); p("{}\n", .{try Expressions.from(allocator, list)});
// list = ArrayList(Node).init(allocator); try list.append(try NumberLiteral.fromNumber(allocator, 3)); try list.append(try NumberLiteral.fromNumber(allocator, 4)); p("{any}\n", .{(try Expressions.from(allocator, list)).expressions.expressions});
// }
p("{}\n", .{try Block.node(allocator, .{ .args = ArrayList(*Var).init(allocator), .body = null })});
p("{}\n", .{try If.node(allocator, .{ .cond = try BoolLiteral.node(allocator, .{ .value = true }), .then = null, .@"else" = null })});
p("{}\n", .{try Unless.node(allocator, .{ .cond = try BoolLiteral.node(allocator, .{ .value = true }), .then = null, .@"else" = null })});
p("{}\n", .{try Def.node(allocator, .{ .name = "foo", .args = ArrayList(*Arg).init(allocator), .body = null })});
p("{}\n", .{try CaseWhen.node(allocator, .{ .conds = ArrayList(Node).init(allocator), .body = null })});
p("{}\n", .{try Path.allocate(allocator, .{ .names = ArrayList([]const u8).init(allocator), .is_global = false })});
p("{}\n", .{Node.init(try Path.allocate(allocator, .{ .names = ArrayList([]const u8).init(allocator), .is_global = false }))});
p("{}\n", .{try ClassDef.node(allocator, .{ .name = try Path.allocate(allocator, .{ .names = ArrayList([]const u8).init(allocator), .is_global = false }), .body = null })});
p("{}\n", .{try ModuleDef.node(allocator, .{ .name = try Path.allocate(allocator, .{ .names = ArrayList([]const u8).init(allocator), .is_global = false }), .body = null })});
p("{}\n", .{try While.node(allocator, .{ .cond = try BoolLiteral.node(allocator, .{ .value = true }), .body = null })});
p("{}\n", .{try Until.node(allocator, .{ .cond = try BoolLiteral.node(allocator, .{ .value = true }), .body = null })});
p("{}\n", .{try Rescue.node(allocator, .{ .body = null })});
p("{}\n", .{try ExceptionHandler.node(allocator, .{ .body = null })});
p("{}\n", .{try LibDef.node(allocator, .{ .name = "Foo", .body = null })});
p("{}\n", .{try CStructOrUnionDef.node(allocator, .{ .name = "Foo", .body = null })});
p("{}\n", .{try MacroIf.node(allocator, .{ .cond = try BoolLiteral.node(allocator, .{ .value = true }), .then = null, .@"else" = null })});
p("{}\n", .{(try Nop.node(allocator, .{})).isNop()});
p("{}\n", .{(try BoolLiteral.node(allocator, .{ .value = true })).isTrueLiteral()});
p("{}\n", .{(try BoolLiteral.node(allocator, .{ .value = false })).isFalseLiteral()});
p("{}\n", .{(try NumberLiteral.fromNumber(allocator, 1)).singleExpression()});
p("{}\n", .{(try Expressions.node(allocator, .{ .expressions = ArrayList(Node).init(allocator) })).singleExpression()});
{
var expressions = ArrayList(Node).init(allocator);
try expressions.append(try NumberLiteral.fromNumber(allocator, 1));
p("{}\n", .{(try Expressions.node(allocator, .{ .expressions = expressions })).singleExpression()});
}
{
var expressions = ArrayList(Node).init(allocator);
try expressions.append(try NumberLiteral.fromNumber(allocator, 1));
try expressions.append(try NumberLiteral.fromNumber(allocator, 2));
p("{}\n", .{(try Expressions.node(allocator, .{ .expressions = expressions })).singleExpression()});
}
{
var values = ArrayList(Node).init(allocator);
try values.append(try BoolLiteral.node(allocator, .{ .value = true }));
try values.append(try BoolLiteral.node(allocator, .{ .value = false }));
const array = try ArrayLiteral.node(allocator, .{ .elements = values });
const array2 = try ArrayLiteral.map(allocator, values, .{}, struct {
fn f(_: Allocator, node: Node) !Node {
return try BoolLiteral.node(allocator, .{ .value = !node.bool_literal.value });
}
}.f);
const array3 = try ArrayLiteral.mapWithIndex(allocator, values, struct {
fn f(_: Allocator, node: Node, index: usize) !Node {
return if (index == 0) try BoolLiteral.node(allocator, .{ .value = !node.bool_literal.value }) else node;
}
}.f);
p("{}\n", .{array.array_literal.elements.items[0]});
p("{}\n", .{array2.array_literal.elements.items[0]});
p("{}\n", .{array3.array_literal.elements.items[0]});
p("{}\n", .{array3.array_literal.elements.items[1]});
var node = try Nop.node(allocator, .{});
node.setLocation(Location.new("foo", 1, 2));
node.setEndLocation(Location.new("bar", 3, 4));
p("{?} {?}\n", .{node.location(), node.endLocation()});
}
}
| https://raw.githubusercontent.com/FnControlOption/zig-crystal-ast/686def5c9ebf823d8f967e6dec1781697a8fcab1/ast.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const print = @import("std").debug.print;
const Node = struct {
name: []const u8 = "",
kids: std.ArrayList(Node),
parent: ?*Node = null,
fn leaf(allocator: Allocator, name: []const u8) Node {
return parent(allocator, name, &.{}) catch unreachable;
}
fn parent(allocator: Allocator, name: []const u8, kids: []Node) !Node {
var kids_list = std.ArrayList(Node).init(allocator);
try kids_list.ensureTotalCapacityPrecise(kids.len);
try kids_list.appendSlice(kids);
return Node{ .name = name, .kids = kids_list };
}
fn deinit(self: Node) void {
// TODO Reverse order to crash!
for (self.kids.items) |*kid| {
kid.deinit();
}
self.kids.deinit();
}
};
fn initParents(tree: *Node) void {
for (tree.kids.items) |*kid| {
kid.parent = tree;
initParents(kid);
}
}
fn walkDepth(
comptime Result: type,
value: Result,
tree: Node,
comptime action: fn (Result, Node, usize) Result,
depth: usize
) Result {
var result = action(value, tree, depth);
// for (tree.kids.items) |kid| {
var i = @as(usize, 0);
while (i < tree.kids.items.len) : (i += 1) {
const kid = tree.kids.items[i];
result = walkDepth(Result, result, kid, action, depth + 1);
}
return result;
}
fn walk(
comptime Result: type,
value: Result,
tree: Node,
comptime action: fn (Result, Node, usize) Result
) Result {
return walkDepth(Result, value, tree, action, 0);
}
fn printNode(_: void, node: Node, depth: usize) void {
var i = @as(usize, 0);
while (i < 2 * depth) : (i += 1) {
print(" ", .{});
}
print("{s}\n", .{node.name});
}
fn printTree(tree: Node) void {
var v: void = undefined;
walk(void, v, tree, printNode);
}
fn calcTotalDepthNode(total: usize, _: Node, depth: usize) usize {
return total + depth;
}
fn calcTotalDepth(tree: Node) usize {
return walk(usize, 0, tree, calcTotalDepthNode);
}
fn process(intro: *Node) !Node {
const allocator = intro.kids.allocator;
var tree = try Node.parent(allocator, "root", &.{
intro.*,
try Node.parent(allocator, "one", &.{
Node.leaf(allocator, "two"),
Node.leaf(allocator, "three"),
}),
Node.leaf(allocator, "four"),
});
// defer tree.deinit();
initParents(&tree);
const internal_intro = &tree.kids.items[0];
// try tree.kids.append(Node.leaf(allocator, "outro"));
print("{s}\n", .{internal_intro.name});
printTree(tree);
var total_depth = @as(usize, 0);
var calc_repeats = @as(usize, 0);
while (calc_repeats < 200_000) : (calc_repeats += 1) {
total_depth += calcTotalDepth(tree);
}
print("Total depth: {}\n", .{total_depth});
// return internal_intro;
return tree;
}
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var intro = Node.leaf(allocator, "intro");
const tree = try process(&intro);
defer tree.deinit();
_ = tree;
print("{s}\n", .{tree.name});
} | https://raw.githubusercontent.com/ekusiadadus/msafety/c0625e3ae3d397d2a3d67f5c6e06402bf3ef6e11/walk.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const io = @import("io.zig");
const StringHashMap = std.StringHashMap;
const Trie = @import("trie.zig").Trie;
pub fn run(allocator: Allocator) !void {
const lines = try io.readFile(allocator, "input/day1.txt");
defer lines.deinit();
var wordsToNums = try getWordsToNums(allocator);
defer wordsToNums.deinit();
var trieNode = Trie.new(allocator);
defer trieNode.deinit();
var numWordIter = wordsToNums.keyIterator();
while (numWordIter.next()) |numWord| {
try trieNode.insert(numWord.*);
}
var sum: usize = 0;
for (lines.items) |line| {
var a: ?usize = null;
var b: ?usize = null;
var i: usize = 0;
while (i < line.len) {
if (line[i] >= 48 and line[i] <= 57) {
const n = try std.fmt.parseInt(u8, line[i .. i + 1], 10);
if (a == null) {
a = n;
} else {
b = n;
}
} else if (trieNode.containsSubstring(line[i..])) |sub| {
const n = wordsToNums.get(sub).?;
if (a == null) {
a = n;
} else {
b = n;
}
}
i += 1;
}
if (b == null) {
sum += a.? * 10 + a.?;
} else {
sum += a.? * 10 + b.?;
}
}
std.debug.print("sum = {d}\n", .{sum});
}
fn getWordsToNums(allocator: Allocator) !StringHashMap(usize) {
const numbers = [_][]const u8{
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
};
var map = StringHashMap(usize).init(allocator);
for (numbers, 1..) |n, i| {
try map.put(n, i);
}
return map;
}
| https://raw.githubusercontent.com/boingram/advent-of-code-2023/efbebfc342c54df1c090e199b6233943d0bbee67/day1.zig |
const std = @import("std");
const ArrayList = std.ArrayList;
const expect = std.testing.expect;
fn NthIterator(comptime T: type) type {
return struct {
data: []const T,
nth: usize,
index: usize = 0,
fn next(self: *NthIterator(T)) ?T {
if (self.index > self.data.len) {
return null;
}
const result = self.data[self.index];
self.index = self.index + self.nth;
return result;
}
};
}
pub fn range(len: usize) []const u0 {
return @as([*]u0, undefined)[0..len];
}
fn parseMap(input: []const u8) anyerror!ArrayList(ArrayList(u8)) {
var lines = std.mem.split(u8, input, "\n");
var stacks_initialized = false;
var stacks: ArrayList(ArrayList(u8)) = undefined;
outer: while (lines.next()) |line| {
// init
if (!stacks_initialized) {
const size = (line.len + 1) / 4;
stacks = try ArrayList(ArrayList(u8)).initCapacity(std.heap.c_allocator, size);
for (range(size)) |_| {
stacks.appendAssumeCapacity(ArrayList(u8).init(std.heap.c_allocator));
}
stacks_initialized = true;
}
var iter = NthIterator(u8){ .data = line, .nth = 4, .index = 1 };
var column: usize = 0;
while (iter.next()) |char| {
var stack = &stacks.items[column];
column += 1;
if (std.ascii.isDigit(char)) break :outer;
if (char != ' ') {
try stack.append(char);
}
}
}
for (range(stacks.items.len)) |_, i| {
// std.debug.print("\n== {d} before: {any} ==\n", .{i, stacks.items[i].items});
std.mem.reverse(u8, stacks.items[i].items);
}
return stacks;
}
test "parse map" {
const map = try parseMap(
\\ [D] \
\\[N] [C] \
\\[Z] [M] [P]\
\\ 1 2 3
);
try expect(null == null);
try expect(map.items.len == 3);
try expect(std.mem.eql(u8, map.items[0].items, &[_]u8{ 'Z', 'N' }));
try expect(std.mem.eql(u8, map.items[1].items, &[_]u8{ 'M', 'C', 'D' }));
try expect(std.mem.eql(u8, map.items[2].items, &[_]u8{'P'}));
}
const Instruction = struct {
size: usize,
from: usize,
to: usize,
fn parse(line: []const u8) ?Instruction {
var iter = std.mem.split(u8, line, " ");
var parts:[6]([]const u8) = undefined;
var i: usize = 0;
while(iter.next()) |part| {
parts[i] = part;
i += 1;
}
return Instruction {
.size = std.fmt.parseInt(u32, parts[1], 10) catch return null,
.from = ( std.fmt.parseInt(u32, parts[3], 10) catch return null ) - 1,
.to = ( std.fmt.parseInt(u32, parts[5], 10) catch return null ) - 1,
};
}
fn execute(self: *const Instruction, map: *ArrayList(ArrayList(u8))) error{OutOfMemory}!void {
var from = &map.items[self.from];
var to = &map.items[self.to];
for (range(self.size)) |_| {
try to.append(from.popOrNull() orelse continue);
}
}
fn execute2(self: *const Instruction, map: *ArrayList(ArrayList(u8))) error{OutOfMemory}!void {
var from = &map.items[self.from];
var to = &map.items[self.to];
var tmp = try ArrayList(u8).initCapacity(std.heap.c_allocator, self.size);
for (range(self.size)) |_| {
tmp.appendAssumeCapacity(from.popOrNull() orelse continue);
}
for (range(tmp.items.len)) |_| {
try to.append(tmp.pop());
}
}
};
test "parse instruction" {
const instruction = Instruction.parse("move 1 from 2 to 1").?;
try expect(instruction.size == 1);
try expect(instruction.from == 1);
try expect(instruction.to == 0);
const instr = Instruction.parse("move 18 from 23 to 51").?;
try expect(instr.size == 18);
try expect(instr.from == 22);
try expect(instr.to == 50);
}
test "execute instruction" {
const instruction = Instruction.parse("move 1 from 2 to 1").?;
var map = try parseMap(
\\ [D] \
\\[N] [C] \
\\[Z] [M] [P]\
\\ 1 2 3
);
try instruction.execute(&map);
try expect(std.mem.eql(u8, map.items[0].items, &[_]u8{ 'Z', 'N', 'D' }));
try expect(std.mem.eql(u8, map.items[1].items, &[_]u8{ 'M', 'C' }));
try expect(std.mem.eql(u8, map.items[2].items, &[_]u8{'P'}));
}
fn printMap(map: *ArrayList(ArrayList(u8))) void {
std.debug.print("\n", .{});
for (range(map.items.len)) |_, i| {
std.debug.print("[{d}] = ", .{i});
for (range(map.items[i].items.len)) |_, j| {
std.debug.print("[{c}] ", .{map.items[i].items[j]});
}
std.debug.print("\n", .{});
}
}
pub fn main() anyerror!void {
var buffer: [512]u8 = undefined;
var buf = std.io.bufferedReader(std.io.getStdIn().reader());
var reader = buf.reader();
var rawMapBuffer = try ArrayList(u8).initCapacity(std.heap.c_allocator, 10240);
var rawMap = rawMapBuffer.writer();
while (try reader.readUntilDelimiterOrEof(&buffer, '\n')) |line| {
if (line.len == 0) {
break;
}
_ = try rawMap.write(line);
_ = try rawMap.write("\n");
}
var map = try parseMap(rawMapBuffer.items);
printMap(&map);
while (try reader.readUntilDelimiterOrEof(&buffer, '\n')) |line| {
const instr = Instruction.parse(line) orelse continue;
instr.execute2(&map) catch continue;
printMap(&map);
}
}
| https://raw.githubusercontent.com/fanzeyi/aoc2022/91ecf0021ebfcc3bd3ba31924af8c625ce29a526/day5.zig |
const std = @import("std");
const print = std.debug.print;
pub const ram_size = 4 * 1024; // 4 KiB
pub const rom_offset = 512;
pub const max_rom_size = ram_size - rom_offset;
pub const Error = error{
IllegalOpcode,
};
const Nibble = u4;
const DoubleNibble = struct {
x: u4,
y: u4,
};
const TripleNibble = struct {
x: u4,
y: u4,
z: u4,
};
const NibbleByte = struct {
x: u4,
kk: u8,
};
const Twelve = u12;
pub const Opcode = union(enum) {
sys: Twelve,
cls: void,
ret: void,
jp: Twelve,
call: Twelve,
sexkk: NibbleByte,
snexkk: NibbleByte,
sexy: DoubleNibble,
ldxkk: NibbleByte,
addxkk: NibbleByte,
ldxy: DoubleNibble,
orxy: DoubleNibble,
andxy: DoubleNibble,
xorxy: DoubleNibble,
addxy: DoubleNibble,
subxy: DoubleNibble,
shrxy: DoubleNibble,
subnxy: DoubleNibble,
shlxy: DoubleNibble,
snexy: DoubleNibble,
ldnnn: Twelve,
jpnnn: Twelve,
rndxkk: NibbleByte,
drwxyn: TripleNibble,
skpx: Nibble,
sknpx: Nibble,
ldxdt: Nibble,
ldxk: Nibble,
lddtx: Nibble,
ldstx: Nibble,
addix: Nibble,
ldfx: Nibble,
ldbx: Nibble,
ldix: Nibble,
ldxi: Nibble,
pub fn decode(opcode: u16) ?Opcode {
const nnn: u12 = @truncate(u12, opcode);
const x: u4 = @truncate(u4, opcode >> 8);
const y: u4 = @truncate(u4, opcode >> 4);
const kk: u8 = @truncate(u8, opcode);
const n: u4 = @truncate(u4, opcode);
switch (opcode & 0xF000) {
0x0000 => {
if (opcode == 0x00E0)
return Opcode.cls;
if (opcode == 0x00EE)
return Opcode.ret;
return Opcode{ .sys = nnn };
},
0x1000 => return Opcode{ .jp = nnn },
0x2000 => return Opcode{ .call = nnn },
0x3000 => return Opcode{ .sexkk = .{ .x = x, .kk = kk } },
0x4000 => return Opcode{ .snexkk = .{ .x = x, .kk = kk } },
0x5000 => return Opcode{ .sexy = .{ .x = x, .y = y } },
0x6000 => return Opcode{ .ldxkk = .{ .x = x, .kk = kk } },
0x7000 => return Opcode{ .addxkk = .{ .x = x, .kk = kk } },
0x8000 => {
switch (n) {
0x0 => return Opcode{ .ldxy = .{ .x = x, .y = y } },
0x1 => return Opcode{ .orxy = .{ .x = x, .y = y } },
0x2 => return Opcode{ .andxy = .{ .x = x, .y = y } },
0x3 => return Opcode{ .xorxy = .{ .x = x, .y = y } },
0x4 => return Opcode{ .addxy = .{ .x = x, .y = y } },
0x5 => return Opcode{ .subxy = .{ .x = x, .y = y } },
0x6 => return Opcode{ .shrxy = .{ .x = x, .y = y } },
0x7 => return Opcode{ .subnxy = .{ .x = x, .y = y } },
0xE => return Opcode{ .shlxy = .{ .x = x, .y = y } },
else => return null,
}
},
0x9000 => return Opcode{ .snexy = .{ .x = x, .y = y } },
0xA000 => return Opcode{ .ldnnn = nnn },
0xB000 => return Opcode{ .jpnnn = nnn },
0xC000 => return Opcode{ .rndxkk = .{ .x = x, .kk = kk } },
0xD000 => return Opcode{ .drwxyn = .{ .x = x, .y = y, .z = n } },
0xE000 => {
if (kk == 0x9E)
return Opcode{ .skpx = x };
if (kk == 0xA1)
return Opcode{ .sknpx = x };
return null;
},
0xF000 => {
switch (kk) {
0x07 => return Opcode{ .ldxdt = x },
0x0A => return Opcode{ .ldxk = x },
0x15 => return Opcode{ .lddtx = x },
0x18 => return Opcode{ .ldstx = x },
0x1E => return Opcode{ .addix = x },
0x29 => return Opcode{ .ldfx = x },
0x33 => return Opcode{ .ldbx = x },
0x55 => return Opcode{ .ldix = x },
0x65 => return Opcode{ .ldxi = x },
else => return null,
}
},
else => return null,
}
return null;
}
fn eq(self: Opcode, other: Opcode) bool {
switch (self) {
inline else => |val, tag| {
if (tag != other)
return false;
const oval = @field(other, @tagName(tag));
if (@TypeOf(val) == void)
return true;
if (@TypeOf(val) == Twelve)
return val == oval;
if (@TypeOf(val) == Nibble)
return val == oval;
if (@TypeOf(val) == DoubleNibble)
return val.x == oval.x and val.y == oval.y;
if (@TypeOf(val) == TripleNibble)
return val.x == oval.x and val.y == oval.y and val.z == oval.z;
if (@TypeOf(val) == NibbleByte)
return val.x == oval.x and val.kk == oval.kk;
@compileError("Unhandled union variant");
},
}
return false;
}
pub fn print(self: Opcode, pc: u16, writer: anytype) !void {
switch (self) {
.sys => |nnn| try writer.print("0x{X:0>4}: SYS 0x{X}\n", .{ pc, nnn }),
.cls => try writer.print("0x{X:0>4}: CLS\n", .{pc}),
.ret => try writer.print("0x{X:0>4}: RET\n", .{pc}),
.jp => |nnn| try writer.print("0x{X:0>4}: JP 0x{X:0>4}\n", .{ pc, nnn }),
.call => |nnn| try writer.print("0x{X:0>4}: CALL 0x{X:0>4}\n", .{ pc, nnn }),
.sexkk => |nb| try writer.print("0x{X:0>4}: SE V{d}, 0x{X:0>2}\n", .{ pc, nb.x, nb.kk }),
.snexkk => |nb| try writer.print("0x{X:0>4}: SNE V{d}, 0x{X:0>2}\n", .{ pc, nb.x, nb.kk }),
.sexy => |dn| try writer.print("0x{X:0>4}: SE V{d}, V{d}\n", .{ pc, dn.x, dn.y }),
.ldxkk => |nb| try writer.print("0x{X:0>4}: LD V{d}, 0x{X:0>2}\n", .{ pc, nb.x, nb.kk }),
.addxkk => |nb| try writer.print("0x{X:0>4}: ADD V{d}, 0x{X:0>2}\n", .{ pc, nb.x, nb.kk }),
.ldxy => |dn| try writer.print("0x{X:0>4}: LD V{d}, V{d}\n", .{ pc, dn.x, dn.y }),
.orxy => |dn| try writer.print("0x{X:0>4}: OR V{d}, V{d}\n", .{ pc, dn.x, dn.y }),
.andxy => |dn| try writer.print("0x{X:0>4}: AND V{d}, V{d}\n", .{ pc, dn.x, dn.y }),
.xorxy => |dn| try writer.print("0x{X:0>4}: XOR V{d}, V{d}\n", .{ pc, dn.x, dn.y }),
.addxy => |dn| try writer.print("0x{X:0>4}: ADD V{d}, V{d}\n", .{ pc, dn.x, dn.y }),
.subxy => |dn| try writer.print("0x{X:0>4}: SUB V{d}, V{d}\n", .{ pc, dn.x, dn.y }),
.shrxy => |dn| try writer.print("0x{X:0>4}: SHR V{d}\n", .{ pc, dn.x }),
.subnxy => |dn| try writer.print("0x{X:0>4}: SUBN V{d}, V{d}\n", .{ pc, dn.x, dn.y }),
.shlxy => |dn| try writer.print("0x{X:0>4}: SHL V{d}\n", .{ pc, dn.x }),
.snexy => |dn| try writer.print("0x{X:0>4}: SNE V{d}, V{d}\n", .{ pc, dn.x, dn.y }),
.ldnnn => |nnn| try writer.print("0x{X:0>4}: LD I, 0x{X:0>4}\n", .{ pc, nnn }),
.jpnnn => |nnn| try writer.print("0x{X:0>4}: JP V0, 0x{X:0>4}\n", .{ pc, nnn }),
.rndxkk => |nb| try writer.print("0x{X:0>4}: RND V{d}, 0x{X:0>2}\n", .{ pc, nb.x, nb.kk }),
.drwxyn => |tn| try writer.print("0x{X:0>4}: DRW V{d}, V{d}, 0x{X}\n", .{ pc, tn.x, tn.y, tn.z }),
.skpx => |x| try writer.print("0x{X:0>4}: SKP V{d}\n", .{ pc, x }),
.sknpx => |x| try writer.print("0x{X:0>4}: SKNP V{d}\n", .{ pc, x }),
.ldxdt => |x| try writer.print("0x{X:0>4}: LD V{d}, DT\n", .{ pc, x }),
.ldxk => |x| try writer.print("0x{X:0>4}: LD V{d}, K\n", .{ pc, x }),
.lddtx => |x| try writer.print("0x{X:0>4}: LD DT, V{d}\n", .{ pc, x }),
.ldstx => |x| try writer.print("0x{X:0>4}: LD ST, V{d}\n", .{ pc, x }),
.addix => |x| try writer.print("0x{X:0>4}: ADD I, V{d}\n", .{ pc, x }),
.ldfx => |x| try writer.print("0x{X:0>4}: LD F, V{d}\n", .{ pc, x }),
.ldbx => |x| try writer.print("0x{X:0>4}: LD B, V{d}\n", .{ pc, x }),
.ldix => |x| try writer.print("0x{X:0>4}: LD [I], V{d}\n", .{ pc, x }),
.ldxi => |x| try writer.print("0x{X:0>4}: LD V{d}, [I]\n", .{ pc, x }),
}
}
};
test "opcode decode" {
const expect = @import("std").testing.expect;
const Case = struct {
opcode: u16,
expected: Opcode,
};
// TODO(alexandre): add more test cases.
const cases = [_]Case{
Case{ .opcode = 0xA2B4, .expected = Opcode{ .ldnnn = 0x2B4 } },
Case{ .opcode = 0x23E6, .expected = Opcode{ .call = 0x3E6 } },
};
for (cases) |case| {
const got = Opcode.decode(case.opcode) orelse return Error.IllegalOpcode;
try expect(got.eq(case.expected));
}
}
| https://raw.githubusercontent.com/alexandreyc/chip8-zig/0cb105a9cbab22cfc7bbf2f06ce0e79ad98cba82/c8.zig |
// zig fmt: off
const std = @import("std");
const builtin = @import("builtin");
const string = []const u8;
pub const GitExactStep = struct {
step: std.Build.Step,
builder: *std.Build,
url: string,
commit: string,
pub fn create(b: *std.Build, url: string, commit: string) *GitExactStep {
var result = b.allocator.create(GitExactStep) catch @panic("memory");
result.* = GitExactStep{
.step = std.Build.Step.init(.{
.id = .custom,
.name = b.fmt("git clone {s} @ {s}", .{ url, commit }),
.owner = b,
.makeFn = make,
}),
.builder = b,
.url = url,
.commit = commit,
};
var urlpath = url;
urlpath = trimPrefix(u8, urlpath, "https://");
urlpath = trimPrefix(u8, urlpath, "git://");
const repopath = b.fmt("{s}/zigmod/deps/git/{s}/{s}", .{ b.cache_root.path.?, urlpath, commit });
flip(std.fs.cwd().access(repopath, .{})) catch return result;
var clonestep = std.Build.Step.Run.create(b, "clone");
clonestep.addArgs(&.{ "git", "clone", "-q", "--progress", url, repopath });
var checkoutstep = std.Build.Step.Run.create(b, "checkout");
checkoutstep.addArgs(&.{ "git", "-C", repopath, "checkout", "-q", commit });
result.step.dependOn(&checkoutstep.step);
checkoutstep.step.dependOn(&clonestep.step);
return result;
}
fn make(step: *std.Build.Step, prog_node: *std.Progress.Node) !void {
_ = step;
_ = prog_node;
}
};
pub fn fetch(exe: *std.Build.Step.Compile) *std.Build.Step {
const b = exe.step.owner;
const step = b.step("fetch", "");
inline for (comptime std.meta.declarations(package_data)) |decl| {
const path = &@field(package_data, decl.name).entry;
const root = if (@field(package_data, decl.name).store) |_| b.cache_root.path.? else ".";
if (path.* != null) path.* = b.fmt("{s}/zigmod/deps{s}", .{ root, path.*.? });
}
step.dependOn(&GitExactStep.create(b, "https://github.com/marlersoft/zigwin32", "c778640d3dc153e900fbe37e2816b5176af3c802").step);
step.dependOn(&GitExactStep.create(b, "https://github.com/nektro/arqv-ini", "38a018ad3a19d5b4663a5364d2d31271f250846b").step);
step.dependOn(&GitExactStep.create(b, "https://github.com/nektro/iguanaTLS", "4dc8850883b49e4a452871298788b06b1af9fe24").step);
step.dependOn(&GitExactStep.create(b, "https://github.com/nektro/zfetch", "863be236188e5f24d16554f9dcd7df96dd254a13").step);
step.dependOn(&GitExactStep.create(b, "https://github.com/nektro/zig-ansi", "c3e439f86b0484e4428f38c4d8b07b7b5ae1634b").step);
step.dependOn(&GitExactStep.create(b, "https://github.com/nektro/zig-detect-license", "3ff57d0681b7bd7f8ca9bd092afa0b4bfe2f1afd").step);
step.dependOn(&GitExactStep.create(b, "https://github.com/nektro/zig-extras", "74f0ddb0a4dfa7921739b88cc381951a6b6e73ce").step);
step.dependOn(&GitExactStep.create(b, "https://github.com/nektro/zig-inquirer", "9e1d873db79e9ffa6ae6e06bd372428c9be85d97").step);
step.dependOn(&GitExactStep.create(b, "https://github.com/nektro/zig-leven", "e548b0bcc7b6f34f636c0b6b905928d31254c54d").step);
step.dependOn(&GitExactStep.create(b, "https://github.com/nektro/zig-licenses", "f46d9f774df929885eef66c733a1e2a46bf16aec").step);
step.dependOn(&GitExactStep.create(b, "https://github.com/nektro/zig-licenses-text", "b01e5a2dffcc564bddd8f514fe64bab9b5c52572").step);
step.dependOn(&GitExactStep.create(b, "https://github.com/nektro/zig-range", "4b2f12808aa09be4b27a163efc424dd4e0415992").step);
step.dependOn(&GitExactStep.create(b, "https://github.com/nektro/zig-time", "ba546bbf2e8438c9b2325f36f392c9d95b432e8e").step);
step.dependOn(&GitExactStep.create(b, "https://github.com/nektro/zig-yaml", "0d17fb99cba338aedc1abac12d78d5e5f04f0b6b").step);
step.dependOn(&GitExactStep.create(b, "https://github.com/truemedian/hzzp", "a7f03a1e652abe8c89b376d090cec50acb0d2a1a").step);
step.dependOn(&GitExactStep.create(b, "https://github.com/ziglibs/known-folders", "0ad514dcfb7525e32ae349b9acc0a53976f3a9fa").step);
step.dependOn(&GitExactStep.create(b, "https://github.com/yaml/libyaml", "2c891fc7a770e8ba2fec34fc6b545c672beb37e6").step);
return step;
}
fn trimPrefix(comptime T: type, haystack: []const T, needle: []const T) []const T {
if (std.mem.startsWith(T, haystack, needle)) {
return haystack[needle.len .. haystack.len];
}
return haystack;
}
fn flip(foo: anytype) !void {
_ = foo catch return;
return error.ExpectedError;
}
pub fn addAllTo(exe: *std.Build.Step.Compile) void {
checkMinZig(builtin.zig_version, exe);
const fetch_step = fetch(exe);
@setEvalBranchQuota(1_000_000);
for (packages) |pkg| {
const module = pkg.module(exe, fetch_step);
exe.root_module.addImport(pkg.name, module);
}
}
var link_lib_c = false;
pub const Package = struct {
name: string = "",
entry: ?string = null,
store: ?string = null,
deps: []const *Package = &.{},
c_include_dirs: []const string = &.{},
c_source_files: []const string = &.{},
c_source_flags: []const string = &.{},
system_libs: []const string = &.{},
frameworks: []const string = &.{},
module_memo: ?*std.Build.Module = null,
pub fn module(self: *Package, exe: *std.Build.Step.Compile, fetch_step: *std.Build.Step) *std.Build.Module {
if (self.module_memo) |cached| {
return cached;
}
const b = exe.step.owner;
const result = b.createModule(.{});
const dummy_library = b.addStaticLibrary(.{
.name = "dummy",
.target = exe.root_module.resolved_target orelse b.host,
.optimize = exe.root_module.optimize.?,
});
dummy_library.step.dependOn(fetch_step);
if (self.entry) |capture| {
result.root_source_file = .{ .path = capture };
}
for (self.deps) |item| {
const module_dep = item.module(exe, fetch_step);
if (module_dep.root_source_file != null) {
result.addImport(item.name, module_dep);
}
for (module_dep.include_dirs.items) |jtem| {
switch (jtem) {
.path => result.addIncludePath(jtem.path),
.path_system, .path_after, .framework_path, .framework_path_system, .other_step, .config_header_step => {},
}
}
}
for (self.c_include_dirs) |item| {
result.addIncludePath(.{ .cwd_relative = b.fmt("{s}/zigmod/deps{s}/{s}", .{ b.cache_root.path.?, self.store.?, item }) });
dummy_library.addIncludePath(.{ .cwd_relative = b.fmt("{s}/zigmod/deps{s}/{s}", .{ b.cache_root.path.?, self.store.?, item }) });
link_lib_c = true;
}
for (self.c_source_files) |item| {
dummy_library.addCSourceFile(.{ .file = .{ .cwd_relative = b.fmt("{s}/zigmod/deps{s}/{s}", .{ b.cache_root.path.?, self.store.?, item }) }, .flags = self.c_source_flags });
}
for (self.system_libs) |item| {
dummy_library.linkSystemLibrary(item);
}
for (self.frameworks) |item| {
dummy_library.linkFramework(item);
}
if (self.c_source_files.len > 0 or self.system_libs.len > 0 or self.frameworks.len > 0) {
dummy_library.linkLibC();
exe.root_module.linkLibrary(dummy_library);
link_lib_c = true;
}
if (link_lib_c) {
result.link_libc = true;
}
self.module_memo = result;
return result;
}
};
fn checkMinZig(current: std.SemanticVersion, exe: *std.Build.Step.Compile) void {
const min = std.SemanticVersion.parse("0.12.0") catch return;
if (current.order(min).compare(.lt)) @panic(exe.step.owner.fmt("Your Zig version v{} does not meet the minimum build requirement of v{}", .{current, min}));
}
pub const package_data = struct {
pub var _o6ogpor87xc2 = Package{
.store = "/git/github.com/marlersoft/zigwin32/c778640d3dc153e900fbe37e2816b5176af3c802",
.name = "win32",
.entry = "/git/github.com/marlersoft/zigwin32/c778640d3dc153e900fbe37e2816b5176af3c802/win32.zig",
};
pub var _u7sysdckdymi = Package{
.store = "/git/github.com/nektro/arqv-ini/38a018ad3a19d5b4663a5364d2d31271f250846b",
.name = "ini",
.entry = "/git/github.com/nektro/arqv-ini/38a018ad3a19d5b4663a5364d2d31271f250846b/src/ini.zig",
};
pub var _csbnipaad8n7 = Package{
.store = "/git/github.com/nektro/iguanaTLS/4dc8850883b49e4a452871298788b06b1af9fe24",
.name = "iguanaTLS",
.entry = "/git/github.com/nektro/iguanaTLS/4dc8850883b49e4a452871298788b06b1af9fe24/src/main.zig",
};
pub var _s84v9o48ucb0 = Package{
.store = "/git/github.com/nektro/zig-ansi/c3e439f86b0484e4428f38c4d8b07b7b5ae1634b",
.name = "ansi",
.entry = "/git/github.com/nektro/zig-ansi/c3e439f86b0484e4428f38c4d8b07b7b5ae1634b/src/lib.zig",
};
pub var _f7dubzb7cyqe = Package{
.store = "/git/github.com/nektro/zig-extras/74f0ddb0a4dfa7921739b88cc381951a6b6e73ce",
.name = "extras",
.entry = "/git/github.com/nektro/zig-extras/74f0ddb0a4dfa7921739b88cc381951a6b6e73ce/src/lib.zig",
};
pub var _0npcrzfdlrvk = Package{
.store = "/git/github.com/nektro/zig-licenses/f46d9f774df929885eef66c733a1e2a46bf16aec",
.name = "licenses",
.entry = "/git/github.com/nektro/zig-licenses/f46d9f774df929885eef66c733a1e2a46bf16aec/src/lib.zig",
};
pub var _pt88y5d80m25 = Package{
.store = "/git/github.com/nektro/zig-licenses-text/b01e5a2dffcc564bddd8f514fe64bab9b5c52572",
.name = "licenses-text",
.entry = "/git/github.com/nektro/zig-licenses-text/b01e5a2dffcc564bddd8f514fe64bab9b5c52572/src/lib.zig",
};
pub var _tnj3qf44tpeq = Package{
.store = "/git/github.com/nektro/zig-range/4b2f12808aa09be4b27a163efc424dd4e0415992",
.name = "range",
.entry = "/git/github.com/nektro/zig-range/4b2f12808aa09be4b27a163efc424dd4e0415992/src/lib.zig",
};
pub var _c1xirp1ota5p = Package{
.store = "/git/github.com/nektro/zig-inquirer/9e1d873db79e9ffa6ae6e06bd372428c9be85d97",
.name = "inquirer",
.entry = "/git/github.com/nektro/zig-inquirer/9e1d873db79e9ffa6ae6e06bd372428c9be85d97/src/lib.zig",
.deps = &[_]*Package{ &_s84v9o48ucb0, &_tnj3qf44tpeq },
};
pub var _96h80ezrvj7i = Package{
.store = "/git/github.com/nektro/zig-leven/e548b0bcc7b6f34f636c0b6b905928d31254c54d",
.name = "leven",
.entry = "/git/github.com/nektro/zig-leven/e548b0bcc7b6f34f636c0b6b905928d31254c54d/src/lib.zig",
.deps = &[_]*Package{ &_tnj3qf44tpeq },
};
pub var _2ovav391ivak = Package{
.store = "/git/github.com/nektro/zig-detect-license/3ff57d0681b7bd7f8ca9bd092afa0b4bfe2f1afd",
.name = "detect-license",
.entry = "/git/github.com/nektro/zig-detect-license/3ff57d0681b7bd7f8ca9bd092afa0b4bfe2f1afd/src/lib.zig",
.deps = &[_]*Package{ &_pt88y5d80m25, &_96h80ezrvj7i },
};
pub var _iecwp4b3bsfm = Package{
.store = "/git/github.com/nektro/zig-time/ba546bbf2e8438c9b2325f36f392c9d95b432e8e",
.name = "time",
.entry = "/git/github.com/nektro/zig-time/ba546bbf2e8438c9b2325f36f392c9d95b432e8e/time.zig",
.deps = &[_]*Package{ &_f7dubzb7cyqe },
};
pub var _g982zq6e8wsv = Package{
.store = "/git/github.com/nektro/zig-yaml/0d17fb99cba338aedc1abac12d78d5e5f04f0b6b",
.name = "yaml",
.entry = "/git/github.com/nektro/zig-yaml/0d17fb99cba338aedc1abac12d78d5e5f04f0b6b/yaml.zig",
.deps = &[_]*Package{ &_8mdbh0zuneb0, &_f7dubzb7cyqe },
};
pub var _9k24gimke1an = Package{
.store = "/git/github.com/truemedian/hzzp/a7f03a1e652abe8c89b376d090cec50acb0d2a1a",
.name = "hzzp",
.entry = "/git/github.com/truemedian/hzzp/a7f03a1e652abe8c89b376d090cec50acb0d2a1a/src/main.zig",
};
pub var _ejw82j2ipa0e = Package{
.store = "/git/github.com/nektro/zfetch/863be236188e5f24d16554f9dcd7df96dd254a13",
.name = "zfetch",
.entry = "/git/github.com/nektro/zfetch/863be236188e5f24d16554f9dcd7df96dd254a13/src/main.zig",
.deps = &[_]*Package{ &_9k24gimke1an, &_csbnipaad8n7 },
};
pub var _2ta738wrqbaq = Package{
.store = "/git/github.com/ziglibs/known-folders/0ad514dcfb7525e32ae349b9acc0a53976f3a9fa",
.name = "known-folders",
.entry = "/git/github.com/ziglibs/known-folders/0ad514dcfb7525e32ae349b9acc0a53976f3a9fa/known-folders.zig",
};
pub var _89ujp8gq842x = Package{
.name = "zigmod",
.entry = "/../..//src/lib.zig",
.deps = &[_]*Package{ &_g982zq6e8wsv, &_s84v9o48ucb0, &_2ta738wrqbaq, &_0npcrzfdlrvk, &_ejw82j2ipa0e, &_2ovav391ivak, &_c1xirp1ota5p, &_u7sysdckdymi, &_iecwp4b3bsfm, &_f7dubzb7cyqe },
};
pub var _root = Package{
};
pub var _8mdbh0zuneb0 = Package{
.store = "/git/github.com/yaml/libyaml/2c891fc7a770e8ba2fec34fc6b545c672beb37e6",
.c_include_dirs = &.{ "include" },
.c_source_files = &.{ "src/api.c", "src/dumper.c", "src/emitter.c", "src/loader.c", "src/parser.c", "src/reader.c", "src/scanner.c", "src/writer.c" },
.c_source_flags = &.{ "-DYAML_VERSION_MAJOR=0", "-DYAML_VERSION_MINOR=2", "-DYAML_VERSION_PATCH=5", "-DYAML_VERSION_STRING=\"0.2.5\"", "-DYAML_DECLARE_STATIC=1" },
};
};
pub const packages = [_]*Package{
&package_data._89ujp8gq842x,
&package_data._o6ogpor87xc2,
&package_data._f7dubzb7cyqe,
&package_data._s84v9o48ucb0,
};
pub const pkgs = struct {
pub const zigmod = &package_data._89ujp8gq842x;
pub const win32 = &package_data._o6ogpor87xc2;
pub const extras = &package_data._f7dubzb7cyqe;
pub const ansi = &package_data._s84v9o48ucb0;
};
pub const imports = struct {
};
| https://raw.githubusercontent.com/nektro/zigmod/3caa1188c9e0d926b51908e42905162b4551668a/deps.zig |
const std = @import("std");
const net = @cImport( @cInclude("netinet/in.h") );
const socket = @cImport( @cInclude("sys/socket.h") );
const cio = @cImport( @cInclude("stdio.h") );
const netdb = @cImport( @cInclude("netdb.h") );
const assert = std.debug.assert;
const warn = std.debug.warn;
const irc_port = 6667;
const addr = c"address.of.irc.server"; // c string for gethostbyname() libc call
const channel = "#channel_name";
const nick = "zig_bot";
const real = nick;
const user = nick;
const recv_buf_len = 1024;
var recv_buf: [recv_buf_len]u8 = undefined;
fn strchr(str: []const u8, char: u8) ?usize {
for (str) |c, i| {
if (c == char) {
return i;
}
}
return null;
}
test "strings contain characters" {
assert(strchr("foobar", 'f').? == 0);
assert(strchr("foobar", 'o').? == 1);
assert(strchr("foobar", 'b').? == 3);
assert(strchr("foobar", 'a').? == 4);
assert(strchr("foobar", 'x') == null);
}
fn streq(s: []const u8, t: []const u8) bool {
if (s.len != t.len) {
return false;
}
var i: usize = 0;
while (i < s.len) : (i += 1) {
if (s[i] != t[i]) {
return false;
}
}
return true;
}
test "strings are equal to each other" {
assert(streq("foo bar", "foo bar"));
assert(streq("", ""));
assert(! streq("foo", "foobar"));
assert(! streq("foo", "bar"));
}
fn strstr(str: []const u8, s: []const u8) ?usize {
if (s.len == 0) {
return 0;
}
outer: for (str) |c, i| {
if (i + s.len > str.len) {
break;
}
for (s) |sc, si| {
if (sc != str[i + si]) {
continue :outer;
}
}
return i;
}
return null;
}
test "strings contain other strings" {
assert(strstr("foobar", "foo").? == 0);
assert(strstr("foobar", "bar").? == 3);
assert(strstr("foobar", "foox") == null);
assert(strstr("foobar", "xfoo") == null);
}
fn parse_nick(line: []const u8) ?[]const u8 {
if (line[0] == ':') {
var spce = strchr(line, ' ') orelse return null;
var excl = strchr(line, '!') orelse return null;
if (spce < excl) {
return null;
}
var nick_end: usize = excl;
return line[1..nick_end];
}
return null;
}
test "parse nickname" {
const line = ":tyler!testtesttest foo bar :trail\r\n";
assert(streq(parse_nick(line).?, "tyler"));
const line2 = "foo bar :trail\r\n";
assert(parse_nick(line2) == null);
}
fn parse_command(line: []const u8) ?[]const u8 {
var cmd_start: usize = 0;
var cmd_end: usize = 0;
if (line[0] == ':') {
cmd_start = strchr(line, ' ') orelse unreachable;
cmd_start += 1;
cmd_end = strchr(line[cmd_start..], ' ') orelse strchr(line[cmd_start..], '\r') orelse unreachable;
cmd_end += cmd_start;
} else {
cmd_end = strchr(line, ' ') orelse strchr(line, '\r') orelse unreachable;
}
return line[cmd_start..cmd_end];
}
test "parse command" {
const line = ":tyler!testtesttest foo bar :trail\r\n";
assert(streq(parse_command(line).?, "foo"));
const line2 = "foo bar :trail\r\n";
assert(streq(parse_command(line2).?, "foo"));
}
const CError = error.CError;
fn perror(msg: []const u8) error {
cio.perror(msg.ptr);
return error.CError;
}
fn irc_send(sock: i32, value: []const u8) void {
// for loop on var args kills compiler
// for (args) |arg| {
// warn("{}", arg);
// socket.send(sock, arg, arg.len, 0);
// }
// var i: usize = 0;
// while (i < args.len) : (i += 1) {
// warn("{}", args[i]);
// _ = socket.send(sock, args[i], args[i].len, 0);
// }
// inline for (args) |arg| {
// warn("{}", arg);
// socket.send(sock, arg, arg.len, 0);
// }
warn("<< {}\n", value);
_ = socket.send(sock, value.ptr, value.len, 0);
_ = socket.send(sock, "\r\n", 2, 0);
}
pub fn main() error!void {
var stdout = try std.io.getStdOut();
try stdout.write("Test\n");
const buf_index: usize = 0;
const host: ?*netdb.hostent = @ptrCast(?*netdb.hostent, netdb.gethostbyname(addr))
orelse return perror("getaddr");
const sock: i32 = socket.socket(socket.AF_INET, @enumToInt(socket.SOCK_STREAM), 0);
if (sock == -1) {
return perror("sock");
}
var remote = net.sockaddr_in{
.sin_family = socket.AF_INET,
.sin_port = net.htons(irc_port),
.sin_addr = undefined,
.sin_zero = [8]u8{0, 0, 0, 0, 0, 0, 0, 0},
};
// @ptrCast(*net.in_addr, @alignCast(4, host.?.h_addr_list.?[0].?)).*,
@memcpy(
@ptrCast([*]u8, &remote.sin_addr),
host.?.h_addr_list.?[0].?,
@sizeOf(@typeOf(remote.sin_addr))
);
var conn_result = socket.connect(
sock,
@ptrCast([*]const socket.sockaddr, &remote),
@sizeOf(@typeOf(remote))
);
if (conn_result == -1) {
return perror("connect");
}
irc_send(sock, "USER " ++ nick ++ " 0 * :" ++ nick);
irc_send(sock, "NICK " ++ nick);
irc_send(sock, "JOIN " ++ channel);
var buffer_index: usize = 0;
while (true) {
// main loop
var len: isize = 0;
warn("buffer_index: {}\n", buffer_index);
len = socket.recv(sock, @ptrCast(?*c_void, &recv_buf[buffer_index]), recv_buf_len - buffer_index, 0);
// is there a better way to do this?
var buf_view: []u8 = undefined;
buf_view.ptr = @ptrCast([*]u8, &recv_buf);
buf_view.len = @intCast(usize, len) + buffer_index;
var one_line_end = strchr(recv_buf, '\n');
while (one_line_end != null) {
warn("buf view at {} - {}\n",
@ptrToInt(buf_view.ptr) - @ptrToInt(&recv_buf),
@ptrToInt(buf_view.ptr) - @ptrToInt(&recv_buf) + buf_view.len
);
warn("buf_view len: {}\n", buf_view.len);
warn("recv_buf: {x}\n", recv_buf);
warn("buf_view: {x}\n", buf_view);
warn("one_line_end: {}\n", one_line_end.?);
var line = buf_view[0..one_line_end.?-1];
warn(">> {}\n", line);
var line_nick = parse_nick(line);
var line_command = parse_command(line);
warn(" nick: {}\n", line_nick);
warn(" command: {}\n", line_command);
if (streq(line_command.?, "PING")) {
line[1] = 'O'; // @fragile
irc_send(sock, line);
}
if (streq(line_command.?, "MODE")) {
irc_send(sock, "PRIVMSG NickServ :IDENTIFY your_password");
irc_send(sock, "JOIN " ++ channel);
}
if (strstr(line, "~test")) |_| {
irc_send(sock, "PRIVMSG " ++ channel ++ " :ayy test");
}
// var zero_used: usize = 0;
// while (buf_view[zero_used] != '\n') : (zero_used += 1) {
// buf_view[zero_used] = 0;
// }
// buf_view[zero_used] = 0;
buf_view = buf_view[one_line_end.?+1 ..];
one_line_end = strchr(buf_view, '\n');
}
// warn("recv_buf: 0x{x}\n", @ptrToInt(&recv_buf));
// warn("buf_view: 0x{x}\n", @ptrToInt(buf_view.ptr));
// warn("moving {}\n", recv_buf_len - (@ptrToInt(buf_view.ptr) - @ptrToInt(&recv_buf)));
// @memset(
// @ptrCast([*]u8, &recv_buf) + buf_view.len,
// 0,
// recv_buf_len - buf_view.len
// );
if (buf_view.len != 0) {
@memcpy(
&recv_buf,
buf_view.ptr,
buf_view.len,
);
// var i: usize = buf_view.len;
// while (i<recv_buf_len) : (i += 1) {
// recv_buf[i] = 0;
// }
buffer_index = buf_view.len;
} else {
buffer_index = 0;
}
}
}
| https://raw.githubusercontent.com/tyler569/zig-irc/149757d310854922eff74b56c3e71887cf952060/irc.zig |
const std = @import("std");
// const // print = std.debug.// print;
const memEql = std.mem.eql;
const stringToEnum = std.meta.stringToEnum;
const types = @import("types.zig");
const parse = @import("parse.zig");
const Atom = types.Atom;
const AtomList = types.AtomList;
const Variable = types.Variable;
const VarList = types.VarList;
const Value = types.Value;
const SpecialForms = types.SpecialForms;
const Func = types.Func;
const Function = types.Function;
const SyntaxErrors = types.SyntaxErrors;
/// Addition; some dummy functions to play with -> add takes 2 params (order independant)
pub fn add(l: Atom, r: Atom) Atom {
return Atom{ .number = l.number + r.number };
}
/// Division; order dependant
pub fn sub(l: Atom, r: Atom) Atom {
return Atom{ .number = l.number - r.number };
}
/// Negation; neg takes 1 param
pub fn neg(l: Atom) Atom {
return Atom{ .number = -l.number };
}
pub fn less(l: Atom, r: Atom) Atom {
return Atom{ .number = if (l.number < r.number) 1.0 else 0 };
}
pub const Env = struct {
outer: ?*Env,
varlist: VarList,
pub fn copy(self: *const Env) Env {
return Env{ .outer = self.outer, .varlist = self.varlist };
}
pub fn push(self: *Env, symbol: []const u8, value: Value) void {
var node = VarList.Node{ .data = Variable{ .name = symbol, .value = value } };
self.varlist.prepend(&node);
}
pub fn find(self: *const Env, symbol: []const u8) ?*const Env {
var it = self.varlist.first;
while (it) |node| : (it = node.next) {
if (memEql(u8, node.data.name, symbol)) return self;
}
return if (self.outer) |outer_node| outer_node.find(symbol) else null;
}
pub fn get(self: *const Env, symbol: []const u8) !Value {
if (self.find(symbol)) |env| {
var it = env.varlist.first;
while (it) |node| : (it = node.next) {
if (memEql(u8, node.data.name, symbol)) return node.data.value;
}
return error.KeyDisappearedAfterFinding;
} else {
return error.CannotFindKeyInEnvs;
}
}
pub fn addArgs(self: *Env, names: AtomList, values: AtomList) SyntaxErrors!void {
if (names.len() != values.len()) return error.UserFunctionParameterArgumentLengthMismatch;
comptime var i = 0;
var name = names.first;
var value = values.first;
while (name) |nameNode| : (name = nameNode.next) {
if (value) |valueNode| {
self.push(nameNode.data.keyword, Value{ .atom = valueNode.data });
value = valueNode.next; // the same as name = nameNode.next on continuation
}
}
}
};
pub fn evalProgram(comptime ast: AtomList) SyntaxErrors!AtomList {
var corelist = VarList{};
const functions = [_]Variable{
Variable{ .name = "add", .value = Value{ .func = Func{ .funcTwo = &add } } },
Variable{ .name = "sub", .value = Value{ .func = Func{ .funcTwo = &sub } } },
Variable{ .name = "less", .value = Value{ .func = Func{ .funcTwo = &less } } },
};
for (functions) |function| {
var func = VarList.Node{ .data = function };
corelist.prepend(&func);
}
var global_env = Env{ .outer = null, .varlist = corelist };
var results = AtomList{};
var it = ast.first;
while (it) |node| : (it = node.next) {
const evaluation = try comptime eval(node.data, &global_env);
var new_node = AtomList.Node{ .data = evaluation };
if (results.len() >= 1) {
results.first.?.findLast().insertAfter(&new_node); // front to back growth
} else {
results.prepend(&new_node);
}
}
return results;
}
pub fn eval(x: Atom, env: *Env) SyntaxErrors!Atom {
@setEvalBranchQuota(1_000_000);
return switch (x) {
.number => x, // number evaluates to itself
.keyword => (try env.get(x.keyword)).atom, // non function keywords
.function => error.NoFunctionShouldBeHere, // we shouldn't see a bare function
.list => blk: {
if (x.list.len() == 0) break :blk x; // list is empty, return emptylist
const node = comptime x.list.first.?;
const data = comptime node.data;
const next = comptime node.next;
if (data != .keyword) break :blk eval(comptime data, comptime env); // evaluate it if not a kwd
if (next == null) break :blk (try env.get(data.keyword)).atom; // if its termina, find it (variable)
if (stringToEnum(comptime SpecialForms, data.keyword)) |special_form| { // special form
break :blk switch (special_form) {
.def => handleDefSpecialForm(next.?, env),
.@"if" => handleIfSpecialForm(next.?, env),
.@"fn" => handleFnSpecialForm(next.?, env),
};
} else { // function that's not a special form
break :blk handleFunction(node, env);
}
},
};
}
/// No bool values, like the cool kids
pub fn handleIfSpecialForm(conditional: *types.AtomList.Node, env: *Env) SyntaxErrors!Atom {
const evaluated_condition = try eval(conditional.data, env);
const is_true = switch (evaluated_condition) {
.number => if (evaluated_condition.number == 0.0) false else true, // only 0.0 is false!
else => true,
};
const first = conditional.next.?.data; // first branch if true
const second = conditional.next.?.next.?.data; // take second branch if false
return if (is_true) try eval(first, env) else try eval(second, env);
}
/// Define variables and functions
pub fn handleDefSpecialForm(variable_name_node: *types.AtomList.Node, env: *Env) SyntaxErrors!Atom {
const value_node = variable_name_node.next orelse return error.NoDefinedValue;
const atom = try eval(value_node.data, env);
const value = switch (atom) {
.function => Value{ .func = Func{ .funcUser = atom.function } },
else => Value{ .atom = atom },
};
env.push(variable_name_node.data.keyword, value);
return atom;
}
// build arg and body lists for function
pub fn handleFnSpecialForm(args: *types.AtomList.Node, env: *Env) SyntaxErrors!Atom {
var arg = AtomList{};
var argnode = AtomList.Node{ .data = args.data };
arg.prepend(&argnode);
var bod = AtomList{};
if (args.next) |body| bod.prepend(body);
var new_env = env.copy();
var func_data = Function{ .args = arg, .body = bod, .env = &new_env };
return Atom{ .function = &func_data };
}
pub fn handleFunction(topnode: *types.AtomList.Node, env: *Env) SyntaxErrors!Atom {
const next = topnode.next.?;
var copy = AtomList.Node{ .data = try eval(next.data, env) };
var args = AtomList{};
args.prepend(©);
var it = next.next;
while (it) |node| : (it = node.next) { // traverse any other args
var new_node = AtomList.Node{ .data = try eval(node.data, env) };
copy.insertAfter(&new_node); // append
}
const val = (try env.get(topnode.data.keyword));
switch (val) {
.func => return try applyFunction(val.func, args),
.atom => return val.atom,
}
return (try env.get(topnode.data.keyword)).atom;
}
pub fn applyFunction(func: Func, args: AtomList) !Atom {
return switch (func) {
.funcZero => func.funcZero.*(),
.funcOne => func.funcOne.*(args.first.?.data),
.funcTwo => func.funcTwo.*(args.first.?.data, args.first.?.next.?.data),
.funcUser => blk: {
const n = func.funcUser.args.first.?.data;
var new_env = Env{ .outer = func.funcUser.env, .varlist = VarList{} };
switch (func.funcUser.args.first.?.data) {
.list => {
const names = Atom{ .list = n.list };
try new_env.addArgs(names.list, args);
},
.keyword => {
const names = Atom{ .keyword = n.keyword };
var list = AtomList{};
var node = AtomList.Node{ .data = names };
list.prepend(&node);
try new_env.addArgs(list, args);
},
else => return error.SomethingFellThroughTheEvalCracks,
}
break :blk try eval(Atom{ .list = func.funcUser.body }, &new_env);
},
};
}
| https://raw.githubusercontent.com/igmanthony/zig_comptime_lisp/67ac465a345629311f6aa96c0de1f3c698fa3964/eval.zig |
//! LVGL Module that wraps the LVGL API (incomplete)
/// Import the Zig Standard Library
const std = @import("std");
/// Import the LVGL Library from C
const c = @cImport({
// NuttX Defines
@cDefine("__NuttX__", "");
@cDefine("NDEBUG", "");
@cDefine("ARCH_RISCV", "");
@cDefine("LV_LVGL_H_INCLUDE_SIMPLE", "");
// Workaround for "Unable to translate macro: undefined identifier `LL`"
@cDefine("LL", "");
@cDefine("__int_c_join(a, b)", "a"); // Bypass zig/lib/include/stdint.h
// NuttX Header Files
@cInclude("arch/types.h");
@cInclude("../../nuttx/include/limits.h");
// LVGL Header Files
@cInclude("lvgl/lvgl.h");
});
/// Return the Active Screen
pub fn getActiveScreen() !Object {
// Get the Active Screen
const screen = c.lv_scr_act();
// If successfully fetched...
if (screen) |s| {
// Wrap Active Screen as Object and return it
return Object.init(s);
} else {
// Unable to get Active Screen
std.log.err("lv_scr_act failed", .{});
return LvglError.UnknownError;
}
}
/// LVGL Object
pub const Object = struct {
/// Pointer to LVGL Object
obj: *c.lv_obj_t,
/// Init the Object
pub fn init(obj: *c.lv_obj_t) Object {
return .{ .obj = obj };
}
/// Create a Label as a child of the Object
pub fn createLabel(self: *Object) !Label {
// Assume we won't copy from another Object
const copy: ?*const c.lv_obj_t = null;
// Create the Label
const label = c.lv_label_create(self.obj, copy);
// If successfully created...
if (label) |l| {
// Wrap as Label and return it
return Label.init(l);
} else {
// Unable to create Label
std.log.err("lv_label_create failed", .{});
return LvglError.UnknownError;
}
}
};
/// LVGL Label
pub const Label = struct {
/// Pointer to LVGL Label
obj: *c.lv_obj_t,
/// Init the Label
pub fn init(obj: *c.lv_obj_t) Label {
return .{ .obj = obj };
}
/// Set the wrapping of long lines in the label text
pub fn setLongMode(self: *Label, long_mode: c.lv_label_long_mode_t) void {
c.lv_label_set_long_mode(self.obj, long_mode);
}
/// Set the label text alignment
pub fn setAlign(self: *Label, alignment: c.lv_label_align_t) void {
c.lv_label_set_align(self.obj, alignment);
}
/// Enable or disable color codes in the label text
pub fn setRecolor(self: *Label, en: bool) void {
c.lv_label_set_recolor(self.obj, en);
}
/// Set the label text and colors
pub fn setText(self: *Label, text: [*c]const u8) void {
c.lv_label_set_text(self.obj, text);
}
/// Set the object width
pub fn setWidth(self: *Label, w: c.lv_coord_t) void {
c.lv_obj_set_width(self.obj, w);
}
/// Set the object alignment
pub fn alignObject(self: *Label, alignment: c.lv_align_t, x_ofs: c.lv_coord_t, y_ofs: c.lv_coord_t) void {
const base: ?*const c.lv_obj_t = null;
c.lv_obj_align(self.obj, base, alignment, x_ofs, y_ofs);
}
};
/// LVGL Errors
pub const LvglError = error{ UnknownError };
| https://raw.githubusercontent.com/lupyuen/zig-lvgl-nuttx/fd4f285b181a58f9b0bc14c14aa810b1e3fcdf0c/lvgl.zig |
const std = @import("std");
const os = std.os;
const mem = std.mem;
const assert = std.debug.assert;
const warn = std.debug.warn;
const ArrayList = std.ArrayList;
const layout = @import("chunk_layout.zig");
const TypeLayout = layout.TypeLayout;
const layoutChunk = layout.layoutChunk;
const util = @import("util.zig");
const PageArenaAllocator = @import("page_arena_allocator.zig").PageArenaAllocator;
const BlockHeap = @import("block_heap.zig").BlockHeap;
const type_meta = @import("type_meta.zig");
const pages = @import("pages.zig");
const jobs = @import("job_system.zig");
const chunkSize = 16 * 1024;
const entityChunkSize = 64 * 1024;
const dataChunkSize = 8 * 1024;
const archChunkSize = 8 * 1024;
var tempAllocator = PageArenaAllocator.init(64 * 1024);
var permAllocator = PageArenaAllocator.init(64 * 1024);
var heapAllocator = BlockHeap.init();
const stdTempAllocator = &tempAllocator.allocator;
const stdPermAllocator = &permAllocator.allocator;
const stdHeapAllocator = &heapAllocator.allocator;
var lowMemory = false;
/// Creates a ZCS type for the given set of components.
/// This file should be used via this syntax:
/// const ZCS = @import("zcs.zig").Schema(&[_]type{
/// // component types go here
/// });
pub fn Schema(comptime componentTypes: []const type) type {
const TypeIndex = type_meta.TypeIndex(componentTypes);
const ArchMask = TypeIndex.ArchMask;
const ArchID = TypeIndex.ArchID;
const ComponentMeta = struct {
componentIndex: u32,
chunkOffset: u32,
};
const ChunkDataHeader = struct {
data: [chunkSize]u8 align(mem.page_size),
};
const EntityManager = struct {
const Self = @This();
const EntityData = union(enum) {
Chunk: ChunkID,
Index: u16,
Gen: Generation,
};
const ChunkSchema = layout.SOASchema(util.EmptyStruct, EntityData);
const Chunk = ChunkSchema.Chunk;
const chunkLayout = comptime ChunkSchema.layout(entityChunkSize);
const ChunkList = ArrayList(*Chunk);
const Item = struct {
chunk: *Chunk,
index: u32,
fn getValue(self: Item, comptime value: ChunkSchema.Values) ChunkSchema.ValType(value) {
return chunkLayout.getValues(self.chunk, value)[self.index];
}
};
chunks: ChunkList,
fn init() Self {
return Self{
.chunks = ChunkList.init(stdHeapAllocator),
};
}
fn resolveItem(self: Self, index: u32) error{InvalidID}!Item {
const chunkID = index / chunkLayout.numItems;
const indexInChunk = index % chunkLayout.numItems;
if (chunkID >= self.chunks.items.len) return error.InvalidID;
return Item{
.chunk = self.chunks.at(chunkID),
.index = indexInChunk,
};
}
};
const DataManager = struct {
const Self = @This();
const ChunkMetaData = union(enum) {
ChunkData: *ChunkDataHeader,
Arch: ArchID,
Mask: ArchMask,
Count: u16,
};
const ChunkSchema = layout.SOASchema(util.EmptyStruct, ChunkMetaData);
const Chunk = ChunkSchema.Chunk;
const chunkLayout = comptime ChunkSchema.layout(dataChunkSize);
const ChunkList = ArrayList(*Chunk);
const Item = struct {
chunk: *Chunk,
index: u32,
fn getValue(self: Item, comptime value: ChunkSchema.Values) ChunkSchema.ValType(value) {
return chunkLayout.getValues(self.chunk, value)[self.index];
}
};
chunks: ChunkList,
fn init() Self {
return Self{
.chunks = ChunkList.init(stdHeapAllocator),
};
}
fn resolveItem(self: Self, index: u32) error{InvalidID}!Item {
const chunkID = index / chunkLayout.numItems;
const indexInChunk = index % chunkLayout.numItems;
if (chunkID >= self.chunks.items.len) return error.InvalidID;
return Item{
.chunk = self.chunks.at(chunkID),
.index = indexInChunk,
};
}
};
const ArchetypeManager = struct {
const Self = @This();
const ArchetypeData = union(enum) {
Components: []ComponentMeta,
Mask: ArchMask,
ItemsPerChunk: u16,
};
const ChunkSchema = layout.SOASchema(util.EmptyStruct, ArchetypeData);
const Chunk = ChunkSchema.Chunk;
const chunkLayout = comptime ChunkSchema.layout(archChunkSize);
const ChunkList = ArrayList(*Chunk);
const Item = struct {
chunk: *Chunk,
index: u32,
fn getValue(self: Item, comptime value: ChunkSchema.Values) ChunkSchema.ValType(value) {
return chunkLayout.getValues(self.chunk, value)[self.index];
}
};
chunks: ChunkList,
fn init() Self {
return Self{
.chunks = ChunkList.init(stdHeapAllocator),
};
}
fn resolveItem(self: Self, index: u32) error{InvalidID}!Item {
const chunkID = index / chunkLayout.layout.numItems;
const indexInChunk = index % chunkLayout.layout.numItems;
if (chunkID >= self.chunks.items.len) return error.InvalidID;
return Item{
.chunk = self.chunks.at(chunkID),
.index = indexInChunk,
};
}
};
return ZCS(TypeIndex, EntityManager, ArchetypeManager, DataManager);
}
fn ZCS(
comptime _TypeIndex: type,
comptime _EntityManager: type,
comptime _ArchetypeManager: type,
comptime _DataManager: type,
) type {
return struct {
const Self = @This();
pub const TypeIndex = _TypeIndex;
pub const ArchMask = TypeIndex.ArchMask;
pub const ArchID = TypeIndex.ArchID;
pub const EntityManager = _EntityManager;
pub const ArchetypeManager = _ArchetypeManager;
pub const DataManager = _DataManager;
pub const JobSystem = jobs.JobSystem;
pub const JobID = jobs.JobID;
pub const JobInterface = jobs.JobInterface;
pub const ArchetypeChunk = struct {
arch: ArchetypeManager.Item,
data: DataManager.Item,
pub fn getCount(self: ArchetypeChunk) u32 {
return self.data.getValue(.Count);
}
pub fn getEntities(self: ArchetypeChunk) []Entity {
const dataChunk = self.data.getValue(.ChunkData);
const validNum = self.data.getValue(.Count);
return util.typedSlice(Entity, dataChunk, 0, validNum);
}
pub fn hasComponent(self: ArchetypeChunk, comptime T: type) bool {
const compIndex = comptime TypeIndex.getComponentIndex(T);
const components = self.arch.getValue(.Components);
for (components) |component| {
if (component.componentIndex == compIndex)
return true;
}
return false;
}
pub fn getComponents(self: ArchetypeChunk, comptime T: type) error{MissingComponent}![]T {
const compIndex = comptime TypeIndex.getComponentIndex(T);
const components = self.arch.getValue(.Components);
const offset = for (components) |component| {
if (component.componentIndex == compIndex)
break component.chunkOffset;
} else {
return error.MissingComponent;
};
const dataChunk = self.data.getValue(.ChunkData);
const validNum = self.data.getValue(.Count);
return util.typedSlice(T, dataChunk, 0, validNum);
}
};
entityManager: _EntityManager,
archetypeManager: _ArchetypeManager,
dataManager: _DataManager,
jobSystem: JobSystem,
pub fn init() Self {
var self = Self{
.entityManager = _EntityManager.init(),
.archetypeManager = _ArchetypeManager.init(),
.dataManager = _DataManager.init(),
.jobSystem = JobSystem.init(stdHeapAllocator),
};
return self;
}
pub fn startJobSystem(self: *Self, numThreads: u32) !void {
try self.jobSystem.startup(numThreads);
}
pub fn shutdown(self: *Self) void {
warn("shutting down ZCS\n", .{});
self.jobSystem.shutdown();
}
pub fn forEntities(self: *Self, comptime func: var) JobID {
return self.forEntitiesExcludeWithDeps(0, func, util.emptySlice(JobID));
}
pub fn forEntitiesExclude(self: *Self, excludeMask: ArchMask, comptime func: var) JobID {
return self.forEntitiesExcludeWithDeps(excludeMask, func, util.emptySlice(JobID));
}
pub fn forEntitiesWithDep(self: *Self, comptime func: var, dep: JobID) JobID {
return self.forEntitiesExcludeWithDeps(0, func, &[_]JobID{dep});
}
pub fn forEntitiesWithDeps(self: *Self, comptime func: var, deps: []const JobID) JobID {
return self.forEntitiesExcludeWithDeps(0, func, deps);
}
pub fn forEntitiesExcludeWithDep(self: *Self, excludeMask: ArchMask, comptime func: var, dep: JobID) JobID {
return self.forEntitiesExcludeWithDeps(excludeMask, func, &[_]JobID{dep});
}
pub fn forEntitiesExcludeWithDeps(self: *Self, excludeMask: ArchMask, comptime func: var, deps: []const JobID) JobID {
const FuncType = @TypeOf(func);
// Get the type of the second argument to func
const ComponentStruct = switch (@typeInfo(FuncType)) {
.Fn, .BoundFn => |funcInfo| Blk: {
if (funcInfo.return_type.? != void) @compileError("parameter func must not return a value");
if (funcInfo.args.len != 1) @compileError("parameter func must take one argument");
break :Blk funcInfo.args[0].arg_type.?;
},
else => @compileError("parameter func must be a function"),
};
// This gives a better error message than letting it get validated later
const componentInfo = switch (@typeInfo(ComponentStruct)) {
.Struct => |structInfo| structInfo,
else => @compileError("parameter to func must be a struct of components"),
};
const Codegen = struct {
fn dataAdapter(_: util.EmptyStruct, data: ComponentStruct) void {
@call(.{ .modifier = .always_inline }, func, .{data});
}
};
return self.forEntitiesWithDataExcludeWithDeps(excludeMask, util.EmptyStruct{}, Codegen.dataAdapter, deps);
}
pub fn forEntitiesWithData(self: *Self, data: var, comptime func: var) JobID {
return self.forEntitiesWithDataExcludeWithDeps(0, data, func, util.emptySlice(JobID));
}
pub fn forEntitiesWithDataExclude(self: *Self, excludeMask: ArchMask, data: var, comptime func: var) JobID {
return self.forEntitiesWithDataExcludeWithDeps(excludeMask, data, func, util.emptySlice(JobID));
}
pub fn forEntitiesWithDataWithDep(self: *Self, data: var, comptime func: var, dep: JobID) JobID {
return self.forEntitiesWithDataExcludeWithDeps(0, data, func, &[_]JobID{dep});
}
pub fn forEntitiesWithDataWithDeps(self: *Self, data: var, comptime func: var, deps: []const JobID) JobID {
return self.forEntitiesWithDataExcludeWithDeps(0, data, func, deps);
}
pub fn forEntitiesWithDataExcludeWithDep(self: *Self, excludeMask: ArchMask, data: var, comptime func: var, dep: JobID) JobID {
return self.forEntitiesWithDataExcludeWithDeps(excludeMask, data, func, &[_]JobID{dep});
}
pub fn forEntitiesWithDataExcludeWithDeps(self: *Self, excludeMask: ArchMask, data: var, comptime func: var, deps: []const JobID) JobID {
const ExtraData = @TypeOf(data);
const FuncType = @TypeOf(func);
// Get the type of the second argument to func
const ComponentStruct = switch (@typeInfo(FuncType)) {
.Fn, .BoundFn => |funcInfo| Blk: {
if (funcInfo.return_type.? != void) @compileError("parameter func must not return a value");
if (funcInfo.args.len != 2) @compileError("parameter func must take two arguments");
if (funcInfo.args[0].arg_type.? != ExtraData) @compileError("parameter func must take data as its first argument");
break :Blk funcInfo.args[1].arg_type.?;
},
else => @compileError("parameter func must be a function"),
};
// Get the struct info for that argument
const componentInfo = switch (@typeInfo(ComponentStruct)) {
.Struct => |structInfo| structInfo,
else => @compileError("second argument to func must be a struct of components"),
};
// Get the mask for the set of needed components
comptime var includeMask: ArchMask = 0;
inline for (componentInfo.fields) |field| {
includeMask |= comptime TypeIndex.getComponentBit(field.field_type.Child);
}
assert(includeMask & excludeMask == 0);
// Generate parameter data layouts for the job system
const SpawnQueryData = struct {
self: *Self,
excludeMask: ArchMask,
data: ExtraData,
};
const QueryData = struct {
self: *Self,
chunk: *DataManager.Chunk,
excludeMask: ArchMask,
data: ExtraData,
};
const ChunkData = struct {
chunk: ArchetypeChunk,
data: ExtraData,
};
// Generate code for the job functions
const Adapter = struct {
// Root job: for each chunk of chunks, run queryJob
fn spawnQueryJobs(job: JobInterface, jobData: SpawnQueryData) void {
for (jobData.self.dataManager.chunks.toSlice()) |chunk| {
const subData = QueryData{
.self = jobData.self,
.chunk = chunk,
.excludeMask = jobData.excludeMask,
.data = jobData.data,
};
_ = job.addSubJob(subData, queryJob);
}
}
// for each chunk, if its archetype matches our requirements, run rawChunkJob
fn queryJob(job: JobInterface, jobData: QueryData) void {
const archIDs = DataManager.chunkLayout.getValues(jobData.chunk, .Arch);
const masks = DataManager.chunkLayout.getValues(jobData.chunk, .Mask);
const careMask = includeMask | jobData.excludeMask;
for (masks) |mask, i| {
if (mask & careMask == includeMask) {
const subData = ChunkData{
.chunk = ArchetypeChunk{
.arch = jobData.self.archetypeManager.resolveItem(archIDs[i]) catch unreachable,
.data = DataManager.Item{
.chunk = jobData.chunk,
.index = @intCast(u32, i),
},
},
.data = jobData.data,
};
_ = job.addSubJob(subData, rawChunkJob);
}
}
}
// for each item in the chunk, run the job function
fn rawChunkJob(job: JobInterface, jobData: ChunkData) void {
// get the data pointers for the chunks
var componentPtrs: [componentInfo.fields.len][*]u8 = undefined;
inline for (componentInfo.fields) |field, i| {
const slice = jobData.chunk.getComponents(field.field_type.Child) catch unreachable;
componentPtrs[i] = @ptrCast([*]u8, slice.ptr);
}
const numInChunk = jobData.chunk.getCount();
var chunkIndex: u32 = 0;
while (chunkIndex < numInChunk) : (chunkIndex += 1) {
var components: ComponentStruct = undefined;
inline for (componentInfo.fields) |field, i| {
const typedPtr = @ptrCast([*]field.field_type.Child, @alignCast(@alignOf(field.field_type.Child), componentPtrs[i]));
@field(components, field.name) = &typedPtr[i];
}
@call(.{ .modifier = .always_inline }, func, .{ jobData.data, components });
}
}
};
// Schedule the job
const jobData = SpawnQueryData{
.self = self,
.excludeMask = excludeMask,
.data = data,
};
return self.jobSystem.scheduleWithDeps(jobData, Adapter.spawnQueryJobs, deps);
}
};
}
pub const Generation = struct {
value: u8,
};
pub const ChunkID = struct {
value: u32,
};
pub const invalidChunkID = ChunkID{
.value = 0xFFFFFFFF,
};
pub const Entity = struct {
/// MSB 8 bytes are generation, rest is index
gen_index: u32,
};
test "Masks" {
const vec3 = struct {
x: f32,
y: f32,
z: f32,
};
const Position = struct {
pos: vec3,
};
const Velocity = struct {
vel: vec3,
};
const Acceleration = struct {
acc: vec3,
};
const GravityTag = struct {};
const GravityTag2 = GravityTag;
const DampenTag = struct {};
const Jobs = struct {
fn resetAcc(entity: struct {
vel: *Velocity,
}) void {
entity.vel.* = Velocity{ .vel = vec3{ .x = 0, .y = 0, .z = 0 } };
}
fn accVel(dt: f32, entity: struct {
acc: *const Acceleration,
vel: *Velocity,
}) void {
entity.vel.vel.x += entity.acc.acc.x * dt;
entity.vel.vel.y += entity.acc.acc.y * dt;
entity.vel.vel.z += entity.acc.acc.z * dt;
}
};
const ECS = Schema(&[_]type{ Position, Velocity, Acceleration, GravityTag, DampenTag });
const TypeIndex = ECS.TypeIndex;
assert(ECS.ArchMask == u8);
assert(TypeIndex.getComponentBit(Position) == 1);
assert(TypeIndex.getComponentBit(Velocity) == 2);
assert(TypeIndex.getComponentBit(Acceleration) == 4);
assert(TypeIndex.getComponentBit(GravityTag) == 8);
assert(TypeIndex.getComponentBit(GravityTag2) == 8);
assert(TypeIndex.getComponentBit(DampenTag) == 16);
assert(TypeIndex.getArchMask(&[_]type{ Position, Velocity, GravityTag }) == 11);
warn("\nLaid out chunks:\n", .{});
warn("Entity {}\n", .{ECS.EntityManager.chunkLayout.layout.numItems});
warn("Arch {}\n", .{ECS.ArchetypeManager.chunkLayout.layout.numItems});
warn("Data {}\n", .{ECS.DataManager.chunkLayout.layout.numItems});
var ecs = ECS.init();
try ecs.startJobSystem(0);
const accVelJob = ecs.forEntitiesWithData(@as(f32, 0.016666), Jobs.accVel);
_ = ecs.forEntitiesWithDep(Jobs.resetAcc, accVelJob);
ecs.shutdown();
const AC = ECS.ArchetypeChunk;
const ac: AC = undefined;
//_ = ac.getEntities();
//_ = try ac.getComponents(Velocity);
//_ = ac.hasComponent(GravityTag);
//_ = ecs.archetypeManager.findAllArchetypes(0, 0);
}
| https://raw.githubusercontent.com/SpexGuy/Zig-ECS/25479d427d6077313b37e052181369a67e389ca5/zcs.zig |
const std = @import("std");
const print = std.debug.print;
fn readIntUntilDelimiterOrEof(reader: anytype, buf: []u8, delimiter: u8) !i32 {
const maybe_int = reader.*.readUntilDelimiterOrEof(buf, delimiter) catch |err| return err;
return std.fmt.parseInt(i32, maybe_int orelse "", 0);
}
fn isOverlap(from1: i32, to1: i32, from2: i32, _: i32) bool {
return from1 <= from2 and from2 <= to1;
}
pub fn main() !void {
const file = try std.fs.cwd().openFile(
"input.txt",
.{},
);
defer file.close();
var reader = std.io.bufferedReader(file.reader());
var in = reader.reader();
var count: i32 = 0;
var buf: [4]u8 = undefined;
while (true) {
const from1 = readIntUntilDelimiterOrEof(&in, &buf, '-') catch break;
const to1 = readIntUntilDelimiterOrEof(&in, &buf, ',') catch unreachable;
const from2 = readIntUntilDelimiterOrEof(&in, &buf, '-') catch unreachable;
const to2 = readIntUntilDelimiterOrEof(&in, &buf, '\n') catch unreachable;
if (isOverlap(from1, to1, from2, to2) or isOverlap(from2, to2, from1, to1)) {
count += 1;
}
}
print("count = {!}\n", .{count});
std.debug.assert(count == 931);
}
| https://raw.githubusercontent.com/baboikus/advent-of-code-2022/f50080475f9ac214869b8d126fde7d38d1fd0665/4/4.zig |
const std = @import("std");
pub fn main() anyerror!void {
//Create arraylist in zig
var elves = std.ArrayList(i64).init(std.heap.page_allocator);
defer elves.deinit();
var file = try std.fs.cwd().openFile("input.txt", .{});
defer file.close();
var buf_reader = std.io.bufferedReader(file.reader());
var in_stream = buf_reader.reader();
try elves.append(0); //first elf
var line_buf: [1024]u8 = undefined;
while (try in_stream.readUntilDelimiterOrEof(&line_buf, '\n')) |line| {
if (line.len == 0) {
//next elf, init with capacity of 0
try elves.append(0);
} else {
//update capacity of existing elf
var to_add = try std.fmt.parseInt(i64, line, 10);
var elf = &elves.items.ptr[elves.items.len - 1];
elf.* = elf.* + to_add;
}
}
std.sort.sort(i64, elves.items, {}, comptime std.sort.desc(i64));
var first = elves.items[0];
var second = elves.items[1];
var third = elves.items[2];
const stdout = std.io.getStdOut().writer();
try stdout.print("{d}\n", .{first + second + third});
}
| https://raw.githubusercontent.com/mojasp/aoc_2022/2a57945b7dc5c0ad6420b81d3904fc88ae03bac7/1/1.zig |
pub export fn math(a: i32, b: i32) i32 {
return a + b;
}
| https://raw.githubusercontent.com/zigster64/bun-issue-6517/64a5dc42813b6ac209f498ea694f8b78f43c494b/add.zig |
const std = @import("std");
const builtin = @import("builtin");
const Pkg = std.build.Pkg;
const string = []const u8;
pub const cache = ".zigmod/deps";
pub fn addAllTo(exe: *std.build.LibExeObjStep) void {
checkMinZig(builtin.zig_version, exe);
@setEvalBranchQuota(1_000_000);
for (packages) |pkg| {
exe.addPackage(pkg.pkg.?);
}
var llc = false;
var vcpkg = false;
inline for (comptime std.meta.declarations(package_data)) |decl| {
const pkg = @as(Package, @field(package_data, decl.name));
inline for (pkg.system_libs) |item| {
exe.linkSystemLibrary(item);
llc = true;
}
inline for (pkg.c_include_dirs) |item| {
exe.addIncludeDir(@field(dirs, decl.name) ++ "/" ++ item);
llc = true;
}
inline for (pkg.c_source_files) |item| {
exe.addCSourceFile(@field(dirs, decl.name) ++ "/" ++ item, pkg.c_source_flags);
llc = true;
}
vcpkg = vcpkg or pkg.vcpkg;
}
if (llc) exe.linkLibC();
if (builtin.os.tag == .windows and vcpkg) exe.addVcpkgPaths(.static) catch |err| @panic(@errorName(err));
}
pub const Package = struct {
directory: string,
pkg: ?Pkg = null,
c_include_dirs: []const string = &.{},
c_source_files: []const string = &.{},
c_source_flags: []const string = &.{},
system_libs: []const string = &.{},
vcpkg: bool = false,
};
fn checkMinZig(current: std.SemanticVersion, exe: *std.build.LibExeObjStep) void {
const min = std.SemanticVersion.parse("null") catch return;
if (current.order(min).compare(.lt)) @panic(exe.builder.fmt("Your Zig version v{} does not meet the minimum build requirement of v{}", .{current, min}));
}
pub const dirs = struct {
pub const _root = "";
pub const _0swf8h5rdusx = cache ++ "/../..";
pub const _s84v9o48ucb0 = cache ++ "/v/git/github.com/nektro/zig-ansi/commit-d4a53bcac5b87abecc65491109ec22aaf5f3dc2f";
pub const _o6ogpor87xc2 = cache ++ "/v/git/github.com/marlersoft/zigwin32/commit-032a1b51b83b8fe64e0a97d7fe5da802065244c6";
};
pub const package_data = struct {
pub const _0swf8h5rdusx = Package{
.directory = dirs._0swf8h5rdusx,
};
pub const _s84v9o48ucb0 = Package{
.directory = dirs._s84v9o48ucb0,
.pkg = Pkg{ .name = "ansi", .path = .{ .path = dirs._s84v9o48ucb0 ++ "/src/lib.zig" }, .dependencies = null },
};
pub const _o6ogpor87xc2 = Package{
.directory = dirs._o6ogpor87xc2,
.pkg = Pkg{ .name = "win32", .path = .{ .path = dirs._o6ogpor87xc2 ++ "/win32.zig" }, .dependencies = null },
};
pub const _root = Package{
.directory = dirs._root,
};
};
pub const packages = &[_]Package{
package_data._s84v9o48ucb0,
package_data._o6ogpor87xc2,
};
pub const pkgs = struct {
pub const ansi = package_data._s84v9o48ucb0;
pub const win32 = package_data._o6ogpor87xc2;
};
pub const imports = struct {
pub const ansi = @import(".zigmod/deps/v/git/github.com/nektro/zig-ansi/commit-d4a53bcac5b87abecc65491109ec22aaf5f3dc2f/src/lib.zig");
pub const win32 = @import(".zigmod/deps/v/git/github.com/marlersoft/zigwin32/commit-032a1b51b83b8fe64e0a97d7fe5da802065244c6/win32.zig");
};
| https://raw.githubusercontent.com/svc-user/zigoph/db506d6a6bee02eb587593d2326f5229902d6463/deps.zig |
// (C) 2021 Ronsor Labs.
pub inline fn tuplicate(a: u32, b: u32) u64 {
return @intCast(u64, a) << 32 | @intCast(u64, b);
}
| https://raw.githubusercontent.com/Ronsor/riscv-zig/c8522753fd44d1306cf7f827fc7b033c6ac586dc/util.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
// Parse flags from an ArgIterator according to the provided Flags struct. Skips the first arg
pub fn parse(allocator: Allocator, comptime Flags: type, args: *std.process.ArgIterator) !Flags {
std.debug.assert(args.skip());
return parseRaw(allocator, Flags, args);
}
// Parse flags from an ArgIterator according to the provided Flags struct
pub fn parseRaw(allocator: Allocator, comptime Flags: type, args: *std.process.ArgIterator) !Flags {
return parseIter(allocator, Flags, args, argPeek, argAdvance);
}
fn argPeek(args: *std.process.ArgIterator) ?[]const u8 {
var argsCopy = args.*;
return argsCopy.next() orelse null;
}
fn argAdvance(args: *std.process.ArgIterator) void {
std.debug.assert(args.skip());
}
const ParseError = error{
InvalidFlag,
MissingParameter,
InvalidCharacter,
Overflow,
OutOfMemory,
};
pub fn parseIter(
allocator: Allocator,
comptime Flags: type,
context: anytype,
peek: fn (@TypeOf(context)) ?[]const u8,
advance: fn (@TypeOf(context)) void,
) ParseError!Flags {
var flags: Flags = .{};
while (peek(context)) |arg| {
if (arg.len < 2 or !std.mem.startsWith(u8, arg, "-")) break;
advance(context);
if (std.mem.eql(u8, arg, "--")) break;
arg_flags: for (arg[1..], 0..) |opt, i| {
inline for (std.meta.fields(Flags)) |field| {
if (field.name.len != 1) {
@compileError("An argument name must be a single character");
}
if (opt == field.name[0]) {
const T = Unwrap(field.type);
if (T == bool) {
@field(flags, field.name) = true;
} else {
var param: []const u8 = undefined;
if (i + 2 < arg.len) {
param = arg[i + 2 ..];
} else {
param = peek(context) orelse {
return error.MissingParameter;
};
advance(context);
}
if (T == []const u8) {
@field(flags, field.name) = param;
} else {
@field(flags, field.name) = switch (@typeInfo(T)) {
.Int => try std.fmt.parseInt(T, param, 10),
.Float => try std.fmt.parseFloat(T, param),
else => @compileError("Unsupported flag type '" ++ @typeName(field.type) ++ "'"),
};
}
// Ensure we don't try to parse any more flags from this arg
break :arg_flags;
}
break;
}
} else {
return error.InvalidFlag;
}
}
}
// Dupe all strings
const fields = std.meta.fields(Flags);
inline for (fields, 0..) |field, i| {
if (field.type == []const u8) {
@field(flags, field.name) = allocator.dupe(u8, @field(flags, field.name)) catch |err| {
// Free all previously allocated strings
comptime var j = i;
inline while (j > 0) {
j -= 1;
if (fields[j].type == []const u8) {
allocator.free(@field(flags, fields[j].name));
}
}
return err;
};
}
}
return flags;
}
fn Unwrap(comptime T: type) type {
return if (@typeInfo(T) == .Optional) std.meta.Child(T) else T;
}
fn parseTest(comptime Flags: type, args: []const []const u8) !Flags {
var argsV = args;
return parseIter(std.testing.allocator, Flags, &argsV, testPeek, testAdvance);
}
fn testPeek(args: *[]const []const u8) ?[]const u8 {
if (args.*.len == 0) return null;
return args.*[0];
}
fn testAdvance(args: *[]const []const u8) void {
args.* = args.*[1..];
}
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
const expectEqualStrings = std.testing.expectEqualStrings;
test "arg iterator" {
var args = try std.process.argsWithAllocator(std.testing.allocator);
defer args.deinit();
_ = try parse(std.testing.allocator, struct {}, &args);
}
test "bool flag - default" {
const flags = try parseTest(
struct { b: bool = false },
&.{},
);
try expect(!flags.b);
}
test "bool flag - specified" {
const flags = try parseTest(
struct { b: bool = false },
&.{"-b"},
);
try expect(flags.b);
}
test "string flag - default" {
const flags = try parseTest(
struct { s: []const u8 = "default value" },
&.{},
);
defer std.testing.allocator.free(flags.s);
try expectEqualStrings(flags.s, "default value");
}
test "string flag - separated" {
const flags = try parseTest(
struct { s: []const u8 = "default value" },
&.{ "-s", "separate value" },
);
defer std.testing.allocator.free(flags.s);
try expectEqualStrings(flags.s, "separate value");
}
test "string flag - combined" {
const flags = try parseTest(
struct { s: []const u8 = "default value" },
&.{"-scombined value"},
);
defer std.testing.allocator.free(flags.s);
try expectEqualStrings(flags.s, "combined value");
}
test "int flag - default" {
const flags = try parseTest(
struct { s: u8 = 7 },
&.{},
);
try expectEqual(flags.s, 7);
}
test "int flag - separated" {
const flags = try parseTest(
struct { s: u8 = 7 },
&.{ "-s", "40" },
);
try expectEqual(flags.s, 40);
}
test "int flag - combined" {
const flags = try parseTest(
struct { s: u8 = 7 },
&.{"-s70"},
);
try expectEqual(flags.s, 70);
}
test "float flag - default" {
const flags = try parseTest(
struct { s: f32 = 9.6 },
&.{},
);
try expectEqual(flags.s, 9.6);
}
test "float flag - separated" {
const flags = try parseTest(
struct { s: f32 = 9.6 },
&.{ "-s", "4.2" },
);
try expectEqual(flags.s, 4.2);
}
test "float flag - combined" {
const flags = try parseTest(
struct { s: f32 = 9.6 },
&.{"-s0.36"},
);
try expectEqual(flags.s, 0.36);
}
test "bool and string flags" {
const flags = try parseTest(
struct {
b: bool = false,
s: []const u8 = "",
},
&.{ "-s", "foo" },
);
defer std.testing.allocator.free(flags.s);
try expectEqual(flags.b, false);
try expectEqualStrings(flags.s, "foo");
}
| https://raw.githubusercontent.com/silversquirl/optz/a57f38365d85a8c1151171a7e3a715ed285e2a9d/optz.zig |
const std = @import("std");
fn greaterThan(context: void, a: u32, b: u32) std.math.Order {
_ = context;
return std.math.order(a, b).invert();
}
fn printHeap(comptime T: type, gpa: std.mem.Allocator, items: []T) !void {
const binary_tree = @import("binary_tree.zig");
const printTree = @import("print_util.zig").printTree;
var tree = try binary_tree.arrToTree(T, gpa, items);
printTree(T, tree.?);
binary_tree.destroyTree(T, gpa, tree);
}
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
var max_heap = std.PriorityQueue(u32, void, greaterThan).init(allocator, {});
defer max_heap.deinit();
try max_heap.add(1);
try max_heap.add(3);
try max_heap.add(6);
try max_heap.add(4);
try max_heap.add(5);
try max_heap.add(7);
try printHeap(u32, allocator, max_heap.items[0..max_heap.count()]);
}
| https://raw.githubusercontent.com/rsphing/algo.zig/66b4ddfcc48f9cd006e5f726145f2408b55a7848/heap.zig |
// raylib-zig (c) Nikolas Wipper 2020-2024
const std = @import("std");
const builtin = @import("builtin");
const emccOutputDir = "zig-out" ++ std.fs.path.sep_str ++ "htmlout" ++ std.fs.path.sep_str;
const emccOutputFile = "index.html";
pub fn emscriptenRunStep(b: *std.Build) !*std.Build.Step.Run {
// Find emrun.
if (b.sysroot == null) {
@panic("Pass '--sysroot \"[path to emsdk installation]/upstream/emscripten\"'");
}
// If compiling on windows , use emrun.bat.
const emrunExe = switch (builtin.os.tag) {
.windows => "emrun.bat",
else => "emrun",
};
const emrun_run_arg = try b.allocator.alloc(u8, b.sysroot.?.len + emrunExe.len + 1);
defer b.allocator.free(emrun_run_arg);
_ = try std.fmt.bufPrint(emrun_run_arg, "{s}" ++ std.fs.path.sep_str ++ "{s}", .{ b.sysroot.?, emrunExe });
const run_cmd = b.addSystemCommand(&[_][]const u8{ emrun_run_arg, emccOutputDir ++ emccOutputFile });
return run_cmd;
}
// Creates the static library to build a project for Emscripten.
pub fn compileForEmscripten(
b: *std.Build,
name: []const u8,
root_source_file: []const u8,
target: std.zig.CrossTarget,
optimize: std.builtin.Mode,
) *std.Build.Step.Compile {
// TODO: It might be a good idea to create a custom compile step, that does
// both the compile to static library and the link with emcc by overidding
// the make function of the step. However it might also be a bad idea since
// it messes with the build system itself.
const new_target = updateTargetForWeb(target);
// The project is built as a library and linked later.
const exe_lib = b.addStaticLibrary(.{
.name = name,
.root_source_file = .{ .path = root_source_file },
.target = new_target,
.optimize = optimize,
});
// There are some symbols that need to be defined in C.
const webhack_c_file_step = b.addWriteFiles();
const webhack_c_file = webhack_c_file_step.add("webhack.c", webhack_c);
exe_lib.addCSourceFile(.{ .file = webhack_c_file, .flags = &[_][]u8{} });
// Since it's creating a static library, the symbols raylib uses to webgl
// and glfw don't need to be linked by emscripten yet.
exe_lib.step.dependOn(&webhack_c_file_step.step);
return exe_lib;
}
// Links a set of items together using emscripten.
//
// Will accept objects and static libraries as items to link. As for files to
// include, it is recomended to have a single resources directory and just pass
// the entire directory instead of passing every file individually. The entire
// path given will be the path to read the file within the program. So, if
// "resources/image.png" is passed, your program will use "resources/image.png"
// as the path to load the file.
//
// TODO: Test if shared libraries are accepted, I don't remember if emcc can
// link a shared library with a project or not.
// TODO: Add a parameter that allows a custom output directory.
pub fn linkWithEmscripten(
b: *std.Build,
itemsToLink: []const *std.Build.Step.Compile,
) !*std.Build.Step.Run {
// Raylib uses --sysroot in order to find emscripten, so do the same here.
if (b.sysroot == null) {
@panic("Pass '--sysroot \"[path to emsdk installation]/upstream/emscripten\"'");
}
const emccExe = switch (builtin.os.tag) {
.windows => "emcc.bat",
else => "emcc",
};
var emcc_run_arg = try b.allocator.alloc(u8, b.sysroot.?.len + emccExe.len + 1);
defer b.allocator.free(emcc_run_arg);
emcc_run_arg = try std.fmt.bufPrint(
emcc_run_arg,
"{s}" ++ std.fs.path.sep_str ++ "{s}",
.{ b.sysroot.?, emccExe },
);
// Create the output directory because emcc can't do it.
const mkdir_command = b.addSystemCommand(&[_][]const u8{ "mkdir", "-p", emccOutputDir });
// Actually link everything together.
const emcc_command = b.addSystemCommand(&[_][]const u8{emcc_run_arg});
for (itemsToLink) |item| {
emcc_command.addFileArg(item.getEmittedBin());
emcc_command.step.dependOn(&item.step);
}
// This puts the file in zig-out/htmlout/index.html.
emcc_command.step.dependOn(&mkdir_command.step);
emcc_command.addArgs(&[_][]const u8{
"-o",
emccOutputDir ++ emccOutputFile,
"-sFULL-ES3=1",
"-sUSE_GLFW=3",
"-sASYNCIFY",
"-O3",
"--emrun",
});
return emcc_command;
}
// TODO: See if zig's standard library already has somehing like this.
fn lastIndexOf(string: []const u8, character: u8) usize {
// Interestingly, Zig has no nice way of iterating a slice backwards.
for (0..string.len) |i| {
const index = string.len - i - 1;
if (string[index] == character) return index;
}
return string.len - 1;
}
// TODO: each zig update, remove this and see if everything still works.
// https://github.com/ziglang/zig/issues/16776 is where the issue is submitted.
fn updateTargetForWeb(target: std.zig.CrossTarget) std.zig.CrossTarget {
// Zig building to emscripten doesn't work, because the Zig standard library
// is missing some things in the C system. "std/c.zig" is missing fd_t,
// which causes compilation to fail. So build to wasi instead, until it gets
// fixed.
return std.zig.CrossTarget{
.cpu_arch = target.cpu_arch,
.cpu_model = target.cpu_model,
.cpu_features_add = target.cpu_features_add,
.cpu_features_sub = target.cpu_features_sub,
.os_tag = .wasi,
.os_version_min = target.os_version_min,
.os_version_max = target.os_version_max,
.glibc_version = target.glibc_version,
.abi = target.abi,
.dynamic_linker = target.dynamic_linker,
.ofmt = target.ofmt,
};
}
const webhack_c =
\\// Zig adds '__stack_chk_guard', '__stack_chk_fail', and 'errno',
\\// which emscripten doesn't actually support.
\\// Seems that zig ignores disabling stack checking,
\\// and I honestly don't know why emscripten doesn't have errno.
\\// TODO: when the updateTargetForWeb workaround gets removed, see if those are nessesary anymore
\\#include <stdint.h>
\\uintptr_t __stack_chk_guard;
\\//I'm not certain if this means buffer overflows won't be detected,
\\// However, zig is pretty safe from those, so don't worry about it too much.
\\void __stack_chk_fail(void){}
\\int errno;
;
| https://raw.githubusercontent.com/fhlmorrison/plong/8e4dca7fe55a4c8ad4c90271e3b3230c53069a8a/emcc.zig |
const std = @import("std");
const assert = std.debug.assert;
const c = @cImport(@cInclude("zmq.h"));
pub const Context = extern struct {
raw: *anyopaque,
pub const GetOption = enum(c_int) {
io_threads = c.ZMQ_IO_THREADS,
max_sockets = c.ZMQ_MAX_SOCKETS,
socket_limit = c.ZMQ_SOCKET_LIMIT,
thread_sched_policy = c.ZMQ_THREAD_SCHED_POLICY,
max_msgsz = c.ZMQ_MAX_MSGSZ,
msg_t_size = c.ZMQ_MSG_T_SIZE,
thread_affinity_cpu_add = c.ZMQ_THREAD_AFFINITY_CPU_ADD,
thread_affinity_cpu_remove = c.ZMQ_THREAD_AFFINITY_CPU_REMOVE,
thread_name_prefix = c.ZMQ_THREAD_NAME_PREFIX,
};
pub const SetOption = enum(c_int) {
io_threads = c.ZMQ_IO_THREADS,
max_sockets = c.ZMQ_MAX_SOCKETS,
thread_priority = c.ZMQ_THREAD_PRIORITY,
thread_sched_policy = c.ZMQ_THREAD_SCHED_POLICY,
max_msgsz = c.ZMQ_MAX_MSGSZ,
msg_t_size = c.ZMQ_MSG_T_SIZE,
thread_affinity_cpu_add = c.ZMQ_THREAD_AFFINITY_CPU_ADD,
thread_affinity_cpu_remove = c.ZMQ_THREAD_AFFINITY_CPU_REMOVE,
thread_name_prefix = c.ZMQ_THREAD_NAME_PREFIX,
};
pub fn init() !Context {
const raw = try okOrErrno(c.zmq_ctx_new());
return .{ .raw = raw };
}
pub fn deinit(ctx: Context) void {
_ = c.zmq_ctx_term(ctx.raw);
}
pub fn getExt(ctx: Context, option: GetOption, buf: []u8) ![]u8 {
// TODO: use zmq_ctx_get_ext() once it is available
const value_len = @sizeOf(c_int);
if (buf.len < value_len) return error.TooSmallBuffer;
const value_ptr = std.mem.bytesAsValue(c_int, buf[0..value_len]);
const value = c.zmq_ctx_get(ctx.raw, @intFromEnum(option));
try okOrErrno(value);
value_ptr.* = value;
return buf[0..value_len];
}
pub fn get(ctx: Context, option: GetOption) !c_int {
var value: c_int = undefined;
_ = try ctx.getExt(option, std.mem.asBytes(&value));
return value;
}
pub fn setExt(ctx: Context, option: SetOption, value_buf: []const u8) !void {
// TODO: use zmq_ctx_set_ext() once it is available
const value_len = @sizeOf(c_int);
if (value_buf.len != value_len) return error.WrongSizeBuffer;
const value = std.mem.bytesToValue(c_int, value_buf[0..value_len]);
try okOrErrno(c.zmq_ctx_set(ctx.raw, @intFromEnum(option), value));
}
pub fn set(ctx: Context, option: SetOption, value: c_int) !void {
try ctx.setExt(option, std.mem.asBytes(&value));
}
pub fn open(ctx: Context, typ: Socket.Type) !Socket {
const raw = try okOrErrno(c.zmq_socket(ctx.raw, @intFromEnum(typ)));
return .{ .raw = raw };
}
};
pub const Socket = extern struct {
raw: *anyopaque,
pub const SendFlags = packed struct(c_uint) {
dont_wait: bool = false,
snd_more: bool = false,
__1: std.meta.Int(.unsigned, @bitSizeOf(c_uint) - 2) = 0,
};
pub const RecvFlags = packed struct(c_uint) {
dont_wait: bool = false,
__1: std.meta.Int(.unsigned, @bitSizeOf(c_uint) - 1) = 0,
};
pub const Type = enum(c_int) {
pair = c.ZMQ_PAIR,
@"pub" = c.ZMQ_PUB,
sub = c.ZMQ_SUB,
req = c.ZMQ_REQ,
rep = c.ZMQ_REP,
dealer = c.ZMQ_DEALER,
router = c.ZMQ_ROUTER,
pull = c.ZMQ_PULL,
push = c.ZMQ_PUSH,
xpub = c.ZMQ_XPUB,
xsub = c.ZMQ_XSUB,
stream = c.ZMQ_STREAM,
};
pub const Option = enum(c_int) {
affinity = c.ZMQ_AFFINITY,
routing_id = c.ZMQ_ROUTING_ID,
subscribe = c.ZMQ_SUBSCRIBE,
unsubscribe = c.ZMQ_UNSUBSCRIBE,
rate = c.ZMQ_RATE,
recovery_ivl = c.ZMQ_RECOVERY_IVL,
sndbuf = c.ZMQ_SNDBUF,
rcvbuf = c.ZMQ_RCVBUF,
rcvmore = c.ZMQ_RCVMORE,
fd = c.ZMQ_FD,
events = c.ZMQ_EVENTS,
type = c.ZMQ_TYPE,
linger = c.ZMQ_LINGER,
reconnect_ivl = c.ZMQ_RECONNECT_IVL,
backlog = c.ZMQ_BACKLOG,
reconnect_ivl_max = c.ZMQ_RECONNECT_IVL_MAX,
maxmsgsize = c.ZMQ_MAXMSGSIZE,
sndhwm = c.ZMQ_SNDHWM,
rcvhwm = c.ZMQ_RCVHWM,
multicast_hops = c.ZMQ_MULTICAST_HOPS,
rcvtimeo = c.ZMQ_RCVTIMEO,
sndtimeo = c.ZMQ_SNDTIMEO,
last_endpoint = c.ZMQ_LAST_ENDPOINT,
router_mandatory = c.ZMQ_ROUTER_MANDATORY,
tcp_keepalive = c.ZMQ_TCP_KEEPALIVE,
tcp_keepalive_cnt = c.ZMQ_TCP_KEEPALIVE_CNT,
tcp_keepalive_idle = c.ZMQ_TCP_KEEPALIVE_IDLE,
tcp_keepalive_intvl = c.ZMQ_TCP_KEEPALIVE_INTVL,
immediate = c.ZMQ_IMMEDIATE,
xpub_verbose = c.ZMQ_XPUB_VERBOSE,
router_raw = c.ZMQ_ROUTER_RAW,
ipv6 = c.ZMQ_IPV6,
mechanism = c.ZMQ_MECHANISM,
plain_server = c.ZMQ_PLAIN_SERVER,
plain_username = c.ZMQ_PLAIN_USERNAME,
plain_password = c.ZMQ_PLAIN_PASSWORD,
curve_server = c.ZMQ_CURVE_SERVER,
curve_publickey = c.ZMQ_CURVE_PUBLICKEY,
curve_secretkey = c.ZMQ_CURVE_SECRETKEY,
curve_serverkey = c.ZMQ_CURVE_SERVERKEY,
probe_router = c.ZMQ_PROBE_ROUTER,
req_correlate = c.ZMQ_REQ_CORRELATE,
req_relaxed = c.ZMQ_REQ_RELAXED,
conflate = c.ZMQ_CONFLATE,
zap_domain = c.ZMQ_ZAP_DOMAIN,
router_handover = c.ZMQ_ROUTER_HANDOVER,
tos = c.ZMQ_TOS,
connect_routing_id = c.ZMQ_CONNECT_ROUTING_ID,
gssapi_server = c.ZMQ_GSSAPI_SERVER,
gssapi_principal = c.ZMQ_GSSAPI_PRINCIPAL,
gssapi_service_principal = c.ZMQ_GSSAPI_SERVICE_PRINCIPAL,
gssapi_plaintext = c.ZMQ_GSSAPI_PLAINTEXT,
handshake_ivl = c.ZMQ_HANDSHAKE_IVL,
socks_proxy = c.ZMQ_SOCKS_PROXY,
xpub_nodrop = c.ZMQ_XPUB_NODROP,
blocky = c.ZMQ_BLOCKY,
xpub_manual = c.ZMQ_XPUB_MANUAL,
xpub_welcome_msg = c.ZMQ_XPUB_WELCOME_MSG,
stream_notify = c.ZMQ_STREAM_NOTIFY,
invert_matching = c.ZMQ_INVERT_MATCHING,
heartbeat_ivl = c.ZMQ_HEARTBEAT_IVL,
heartbeat_ttl = c.ZMQ_HEARTBEAT_TTL,
heartbeat_timeout = c.ZMQ_HEARTBEAT_TIMEOUT,
xpub_verboser = c.ZMQ_XPUB_VERBOSER,
connect_timeout = c.ZMQ_CONNECT_TIMEOUT,
tcp_maxrt = c.ZMQ_TCP_MAXRT,
thread_safe = c.ZMQ_THREAD_SAFE,
multicast_maxtpdu = c.ZMQ_MULTICAST_MAXTPDU,
vmci_buffer_size = c.ZMQ_VMCI_BUFFER_SIZE,
vmci_buffer_min_size = c.ZMQ_VMCI_BUFFER_MIN_SIZE,
vmci_buffer_max_size = c.ZMQ_VMCI_BUFFER_MAX_SIZE,
vmci_connect_timeout = c.ZMQ_VMCI_CONNECT_TIMEOUT,
use_fd = c.ZMQ_USE_FD,
gssapi_principal_nametype = c.ZMQ_GSSAPI_PRINCIPAL_NAMETYPE,
gssapi_service_principal_nametype = c.ZMQ_GSSAPI_SERVICE_PRINCIPAL_NAMETYPE,
bindtodevice = c.ZMQ_BINDTODEVICE,
};
pub fn close(sock: Socket) void {
_ = c.zmq_close(sock.raw);
}
pub fn getOpt(sock: Socket, opt: Option, buf: []u8) ![]u8 {
var buflen: usize = buf.len;
try okOrErrno(c.zmq_getsockopt(sock, @intFromEnum(opt), @ptrCast(buf.ptr), &buflen));
return buf[0..buflen];
}
pub fn setOpt(sock: Socket, opt: Option, value: []const u8) !void {
return okOrErrno(c.zmq_setsockopt(sock.raw, @intFromEnum(opt), @ptrCast(value.ptr), value.len));
}
pub fn bind(sock: Socket, addr: [:0]const u8) !void {
return okOrErrno(c.zmq_bind(sock.raw, addr.ptr));
}
pub fn connect(sock: Socket, addr: [:0]const u8) !void {
return okOrErrno(c.zmq_connect(sock.raw, addr.ptr));
}
pub fn send(sock: Socket, buf: []const u8, flags: SendFlags) !void {
try okOrErrno(c.zmq_send(
sock.raw,
@ptrCast(buf.ptr),
buf.len,
@bitCast(flags),
));
}
pub fn recv(sock: Socket, buf: []u8, flags: RecvFlags) ![]u8 {
const len = c.zmq_recv(
sock.raw,
@ptrCast(buf.ptr),
buf.len,
@bitCast(flags),
);
try okOrErrno(len);
return buf[0..@intCast(len)];
}
};
pub const Message = extern struct {
inner: c.zmq_msg_t,
pub fn init(msg: *Message) void {
// This function always returns zero.
_ = c.zmq_msg_init(&msg.inner);
}
pub fn close(msg: *Message) void {
// This function may fail with EFAULT on invalid message but this still counts as closed.
_ = c.zmq_msg_close(&msg.inner);
}
pub fn hasMore(msg: *Message) bool {
return c.zmq_msg_more(&msg.inner) != 0;
}
pub fn recv(msg: *Message, socket: Socket, flags: Socket.RecvFlags) !void {
try okOrErrno(c.zmq_msg_recv(&msg.inner, socket.raw, @bitCast(flags)));
}
pub fn send(msg: *Message, socket: Socket, flags: Socket.SendFlags) !void {
try okOrErrno(c.zmq_msg_send(&msg.inner, socket.raw, @bitCast(flags)));
}
};
pub const PollItem = extern struct {
socket: ?*anyopaque = null,
fd: std.os.fd_t = 0,
events: Flags = .{},
revents: Flags = undefined,
pub const Flags = packed struct(c_ushort) {
in: bool = false,
out: bool = false,
err: bool = false,
pri: bool = false,
__1: std.meta.Int(.unsigned, @bitSizeOf(c_ushort) - 4) = 0,
};
};
pub fn poll(items: []PollItem, timeout: c_long) !c_ulong {
const count = c.zmq_poll(@ptrCast(items.ptr), @intCast(items.len), timeout);
try okOrErrno(count);
return @intCast(count);
}
pub fn proxy(frontend: Socket, backend: Socket, capture: ?Socket) !void {
try okOrErrno(c.zmq_proxy(frontend.raw, backend.raw, if (capture) |sock| sock.raw else null));
}
pub fn version() std.SemanticVersion {
var major: c_int = undefined;
var minor: c_int = undefined;
var patch: c_int = undefined;
c.zmq_version(&major, &minor, &patch);
return .{ .major = @intCast(major), .minor = @intCast(minor), .patch = @intCast(patch) };
}
fn OkOrErrno(comptime T: type) type {
return ErrnoError!switch (@typeInfo(T)) {
.Int => void,
.Optional => |info| switch (@typeInfo(info.child)) {
.Pointer => info.child,
else => @compileError("invalid type: " ++ @typeName(T)),
},
else => @compileError("invalid type: " ++ @typeName(T)),
};
}
fn okOrErrno(ret: anytype) OkOrErrno(@TypeOf(ret)) {
return switch (@typeInfo(@TypeOf(ret))) {
.Int => if (ret != -1) {} else return errno(),
.Optional => |info| switch (@typeInfo(info.child)) {
.Pointer => ret orelse return errno(),
else => unreachable,
},
else => unreachable,
};
}
const ErrnoError = error{ Unexpected, Interrupted };
fn errno() ErrnoError {
const e = @as(std.c.E, @enumFromInt(std.c._errno().*));
return switch (e) {
.INTR => error.Interrupted,
else => error.Unexpected,
};
}
| https://raw.githubusercontent.com/lacc97/zmq-z/a9f4f5a5a76e6f111f47e65cfdc6a65f81aed4de/zmq.zig |
const grid = @This();
pub fn posToIndex(comptime D: usize, strides: [D]usize, pos: [D]usize) usize {
var index: usize = 0;
for (pos, strides) |p, stride| {
index += p * stride;
}
return index;
}
pub fn Buffer(comptime D: usize, comptime T: type) type {
return BufferAligned(D, @alignOf(T), T);
}
pub fn BufferAligned(comptime D: usize, comptime A: usize, comptime T: type) type {
return struct {
data: [*]align(A) T,
size: [D]usize,
pub fn slice(this: @This()) []align(A) T {
var len: usize = 1;
for (this.size) |size| {
len *= size;
}
return this.data[0..len];
}
pub fn asSlice(this: @This()) SliceAligned(D, A, T) {
var strides: [D]usize = undefined;
var len: usize = 1;
for (&strides, this.size) |*stride, size| {
stride.* = len;
len *= size;
}
return Slice(D, T){
.data = this.data,
.stride = strides,
.size = this.size,
};
}
pub fn asConstSlice(this: @This()) ConstSliceAligned(D, A, T) {
var strides: [D]usize = undefined;
var len: usize = 1;
for (&strides, this.size) |*stride, size| {
stride.* = len;
len *= size;
}
return ConstSlice(D, T){
.data = this.data,
.stride = strides,
.size = this.size,
};
}
pub fn idx(this: @This(), pos: [D]usize) *align(A) T {
const posv = @as(@Vector(D, usize), pos);
std.debug.assert(@reduce(.And, posv < this.size));
var strides: [D]usize = undefined;
var len: usize = 1;
for (&strides, this.size) |*stride, size| {
stride.* = len;
len *= size;
}
return &this.data[posToIndex(D, strides, pos)];
}
pub fn region(this: @This(), start: [D]usize, end: [D]usize) Slice(D, A, T) {
const startv: @Vector(D, usize) = start;
const endv: @Vector(D, usize) = end;
std.debug.assert(@reduce(.And, startv < this.size));
std.debug.assert(@reduce(.And, startv <= endv));
std.debug.assert(@reduce(.And, endv <= this.size));
const sizev: @Vector(D, usize) = endv - startv;
var strides: [D]usize = undefined;
var len: usize = 1;
for (&strides, this.size) |*stride, size| {
stride.* = len;
len *= size;
}
const start_index = posToIndex(D, strides, start);
const end_index = posToIndex(D, strides, end);
return Slice(D, T){
.data = this.data[start_index..end_index].ptr,
.stride = this.stride,
.size = sizev,
};
}
pub fn add(dest: @This(), a: @This(), b: @This()) void {
std.debug.assert(std.mem.eql(usize, &dest.size, &a.size));
std.debug.assert(std.mem.eql(usize, &dest.size, &b.size));
for (dest.slice(), a.slice(), b.slice()) |*z, x, y| {
z.* = x + y;
}
}
pub fn div(dest: @This(), a: @This(), b: @This()) void {
std.debug.assert(std.mem.eql(usize, &dest.size, &a.size));
std.debug.assert(std.mem.eql(usize, &dest.size, &b.size));
for (dest.slice(), a.slice(), b.slice()) |*z, x, y| {
z.* = x / y;
}
}
};
}
pub fn Slice(comptime D: usize, comptime T: type) type {
return SliceAligned(D, @alignOf(T), T);
}
pub fn SliceAligned(comptime D: usize, comptime A: usize, comptime T: type) type {
return struct {
data: [*]align(A) T,
stride: [D]usize,
size: [D]usize,
pub fn asConstSlice(this: @This()) ConstSlice(D, T) {
return ConstSlice(D, T){
.data = this.data,
.stride = this.stride,
.size = this.size,
};
}
pub fn idx(this: @This(), pos: [D]usize) *T {
const posv = @as(@Vector(D, usize), pos);
std.debug.assert(@reduce(.And, posv < this.size));
return &this.data[posToIndex(D, this.stride, pos)];
}
pub fn region(this: @This(), start: [D]usize, end: [D]usize) @This() {
const startv: @Vector(D, usize) = start;
const endv: @Vector(D, usize) = end;
std.debug.assert(@reduce(.And, startv < this.size));
std.debug.assert(@reduce(.And, startv <= endv));
std.debug.assert(@reduce(.And, endv <= this.size));
const sizev: @Vector(D, usize) = endv - startv;
const start_index = posToIndex(D, this.stride, start);
const end_index = posToIndex(D, this.stride, end);
return @This(){
.data = this.data[start_index..end_index].ptr,
.stride = this.stride,
.size = sizev,
};
}
};
}
pub fn ConstSlice(comptime D: usize, comptime T: type) type {
return ConstSliceAligned(D, @alignOf(T), T);
}
pub fn ConstSliceAligned(comptime D: usize, comptime A: usize, comptime T: type) type {
return struct {
data: [*]align(A) const T,
stride: [D]usize,
size: [D]usize,
pub const Pos = [D]usize;
pub fn getPos(this: @This(), pos: [D]usize) T {
const posv = @as(@Vector(D, usize), pos);
std.debug.assert(@reduce(.And, posv < this.size));
return this.data[posToIndex(D, this.stride, pos)];
}
pub fn idx(this: @This(), pos: [D]usize) *align(A) const T {
const posv = @as(@Vector(D, usize), pos);
std.debug.assert(@reduce(.And, posv < this.size));
return &this.data[posToIndex(D, this.stride, pos)];
}
pub fn region(this: @This(), start: [D]usize, end: [D]usize) @This() {
const startv: @Vector(D, usize) = start;
const endv: @Vector(D, usize) = end;
std.debug.assert(@reduce(.And, startv < this.size));
std.debug.assert(@reduce(.And, startv <= endv));
std.debug.assert(@reduce(.And, endv <= this.size));
const sizev: @Vector(D, usize) = endv - startv;
const start_index = posToIndex(D, this.stride, start);
const end_index = posToIndex(D, this.stride, end);
return @This(){
.data = this.data[start_index..end_index].ptr,
.stride = this.stride,
.size = sizev,
};
}
};
}
pub fn alloc(comptime D: usize, comptime T: type, allocator: std.mem.Allocator, size: [D]usize) !Buffer(D, T) {
return allocAligned(D, @alignOf(T), T, allocator, size);
}
pub fn allocAligned(comptime D: usize, comptime A: u29, comptime T: type, allocator: std.mem.Allocator, size: [D]usize) !BufferAligned(D, A, T) {
var len: usize = 1;
for (size) |s| {
len *= s;
}
const data = try allocator.allocWithOptions(T, len, A, null);
return .{
.data = data.ptr,
.size = size,
};
}
pub fn copy(comptime D: usize, comptime T: type, dest: Slice(D, T), src: ConstSlice(D, T)) void {
std.debug.assert(std.mem.eql(usize, &dest.size, &src.size));
var iter = iterateRange(D, dest.size);
while (iter.next()) |pos| {
dest.idx(pos).* = src.idx(pos).*;
}
}
pub fn dupe(comptime D: usize, comptime T: type, allocator: std.mem.Allocator, src: ConstSlice(D, T)) !Buffer(D, T) {
var result = try alloc(D, T, allocator, src.size);
copy(D, T, result.asSlice(), src);
return result;
}
test dupe {
var result = try dupe(2, f32, std.testing.allocator, .{
.data = &[_]f32{
2, 3, 0,
4, 5, 0,
},
.size = .{ 2, 2 },
.stride = .{ 1, 3 },
});
defer std.testing.allocator.free(result.slice());
try std.testing.expectEqualSlices(
f32,
&.{ 2, 3, 4, 5 },
result.slice(),
);
}
pub fn set(comptime D: usize, comptime T: type, dest: Slice(D, T), value: T) void {
var iter = iterateRange(D, dest.size);
while (iter.next()) |pos| {
dest.idx(pos).* = value;
}
}
test set {
var result = try alloc(3, f32, std.testing.allocator, .{ 3, 3, 3 });
defer std.testing.allocator.free(result.slice());
set(3, f32, result.asSlice(), 42);
try std.testing.expectEqualSlices(f32, &([_]f32{42} ** 27), result.data[0..27]);
}
pub fn flip(comptime T: type, dest: Slice(2, T), flipOnAxis: [2]bool) void {
// The x/y coordinate where we can stop copying. We should only need to swap half the pixels.
const swap_to: [2]usize = if (flipOnAxis[1]) .{ dest.size[0], dest.size[1] / 2 } else if (flipOnAxis[0]) .{ dest.size[0] / 2, dest.size[1] } else return;
for (0..swap_to[1]) |y0| {
const y1 = if (flipOnAxis[1]) dest.size[1] - 1 - y0 else y0;
const row0 = dest.data[y0 * dest.stride ..][0..dest.size[0]];
const row1 = dest.data[y1 * dest.stride ..][0..dest.size[0]];
for (0..swap_to[0]) |x0| {
const x1 = if (flipOnAxis[0]) dest.size[0] - 1 - x0 else x0;
std.mem.swap(T, &row0[x0], &row1[x1]);
}
}
}
pub fn add(comptime D: usize, comptime T: type, dest: Slice(D, T), a: ConstSlice(D, T), b: ConstSlice(D, T)) void {
std.debug.assert(std.mem.eql(usize, &dest.size, &b.size));
std.debug.assert(std.mem.eql(usize, &a.size, &b.size));
var iter = iterateRange(D, dest.size);
while (iter.next()) |pos| {
dest.idx(pos).* = a.idx(pos).* + b.idx(pos).*;
}
}
test add {
var result = try alloc(2, f32, std.testing.allocator, .{ 3, 2 });
defer std.testing.allocator.free(result.slice());
add(2, f32, result.asSlice(), .{
.data = &[_]f32{
1, 2, 3,
4, 5, 6,
},
.size = .{ 3, 2 },
.stride = .{ 1, 3 },
}, .{
.data = &[_]f32{
1, 1, 2,
3, 5, 8,
},
.size = .{ 3, 2 },
.stride = .{ 1, 3 },
});
try std.testing.expectEqualSlices(
f32,
&.{
2, 3, 5,
7, 10, 14,
},
result.data[0..6],
);
}
pub fn addSaturating(comptime D: usize, comptime T: type, dest: Slice(D, T), a: ConstSlice(D, T), b: ConstSlice(D, T)) void {
std.debug.assert(std.mem.eql(usize, &dest.size, &b.size));
std.debug.assert(std.mem.eql(usize, &a.size, &b.size));
var iter = iterateRange(D, dest.size);
while (iter.next()) |pos| {
dest.idx(pos).* = a.idx(pos).* +| b.idx(pos).*;
}
}
pub fn sub(comptime D: usize, comptime T: type, dest: Slice(D, T), a: ConstSlice(D, T), b: ConstSlice(D, T)) void {
std.debug.assert(std.mem.eql(usize, &dest.size, &b.size));
std.debug.assert(std.mem.eql(usize, &a.size, &b.size));
var iter = iterateRange(D, dest.size);
while (iter.next()) |pos| {
dest.idx(pos).* = a.idx(pos).* - b.idx(pos).*;
}
}
pub fn subSaturating(comptime D: usize, comptime T: type, dest: Slice(D, T), a: ConstSlice(D, T), b: ConstSlice(D, T)) void {
std.debug.assert(std.mem.eql(usize, &dest.size, &b.size));
std.debug.assert(std.mem.eql(usize, &a.size, &b.size));
var iter = iterateRange(D, dest.size);
while (iter.next()) |pos| {
dest.idx(pos).* = a.idx(pos).* -| b.idx(pos).*;
}
}
pub fn mul(comptime D: usize, comptime T: type, dest: Slice(D, T), a: ConstSlice(D, T), b: ConstSlice(D, T)) void {
std.debug.assert(std.mem.eql(usize, &dest.size, &b.size));
std.debug.assert(std.mem.eql(usize, &a.size, &b.size));
var iter = iterateRange(D, dest.size);
while (iter.next()) |pos| {
dest.idx(pos).* = a.idx(pos).* * b.idx(pos).*;
}
}
test mul {
var result = try alloc(2, f32, std.testing.allocator, .{ 3, 3 });
defer std.testing.allocator.free(result.slice());
mul(2, f32, result.asSlice(), .{
.data = &[_]f32{
0, 1, 2,
3, 4, 5,
6, 7, 8,
},
.size = .{ 3, 3 },
.stride = .{ 1, 3 },
}, .{
.data = &[_]f32{
1, 1, 2,
3, 5, 8,
14, 22, 36,
},
.size = .{ 3, 3 },
.stride = .{ 1, 3 },
});
try std.testing.expectEqualSlices(
f32,
&.{ 0, 1, 4, 9, 20, 40, 84, 154, 288 },
result.slice(),
);
}
pub fn mulScalar(comptime D: usize, comptime T: type, dest: Slice(D, T), src: ConstSlice(D, T), scalar: T) void {
var iter = iterateRange(D, dest.size);
while (iter.next()) |pos| {
dest.idx(pos).* = src.idx(pos).* * scalar;
}
}
test mulScalar {
var result = try alloc(2, f32, std.testing.allocator, .{ 3, 3 });
defer std.testing.allocator.free(result.slice());
mulScalar(2, f32, result.asSlice(), .{
.data = &[_]f32{
0, 1, 2,
3, 4, 5,
6, 7, 8,
},
.stride = .{ 1, 3 },
.size = .{ 3, 3 },
}, 10);
try std.testing.expectEqualSlices(
f32,
&[_]f32{ 0.0, 10, 20, 30, 40, 50, 60, 70, 80 },
result.slice(),
);
}
pub fn div(comptime D: usize, comptime T: type, dest: Slice(D, T), a: ConstSlice(D, T), b: ConstSlice(D, T)) void {
std.debug.assert(std.mem.eql(usize, &dest.size, &a.size));
std.debug.assert(std.mem.eql(usize, &dest.size, &b.size));
var iter = iterateRange(D, dest.size);
while (iter.next()) |pos| {
dest.idx(pos).* = a.idx(pos).* / b.idx(pos).*;
}
}
test div {
var result = try alloc(2, f32, std.testing.allocator, .{ 3, 3 });
defer std.testing.allocator.free(result.slice());
div(2, f32, result.asSlice(), .{
.data = &[_]f32{
0, 1, 2,
3, 4, 5,
6, 7, 8,
},
.size = .{ 3, 3 },
.stride = .{ 1, 3 },
}, .{
.data = &[_]f32{
1, 1, 2,
3, 5, 8,
14, 22, 36,
},
.size = .{ 3, 3 },
.stride = .{ 1, 3 },
});
try std.testing.expectEqualSlices(
f32,
&[_]f32{ 0, 1, 1, 1, 0.8, 0.625, 0.42857142857142855, 0.3181818181818182, 0.2222222222222222 },
result.slice(),
);
}
pub fn divScalar(comptime D: usize, comptime T: type, dest: Slice(D, T), src: ConstSlice(D, T), scalar: T) void {
var iter = iterateRange(D, dest.size);
while (iter.next()) |pos| {
dest.idx(pos).* = src.idx(pos).* / scalar;
}
}
test divScalar {
var result = try alloc(2, f32, std.testing.allocator, .{ 3, 3 });
defer std.testing.allocator.free(result.slice());
divScalar(2, f32, result.asSlice(), .{
.data = &[_]f32{
0, 1, 2,
3, 4, 5,
6, 7, 8,
},
.stride = .{ 1, 3 },
.size = .{ 3, 3 },
}, 10);
try std.testing.expectEqualSlices(
f32,
&[_]f32{ 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8 },
result.slice(),
);
}
pub fn sqrt(comptime D: usize, comptime T: type, dest: Slice(D, T), src: ConstSlice(D, T)) void {
var iter = iterateRange(D, dest.size);
while (iter.next()) |pos| {
dest.idx(pos).* = @sqrt(src.idx(pos).*);
}
}
test sqrt {
var result = try alloc(2, f32, std.testing.allocator, .{ 2, 2 });
defer std.testing.allocator.free(result.slice());
sqrt(2, f32, result.asSlice(), .{
.data = &[_]f32{
4, 9,
16, 25,
},
.size = .{ 2, 2 },
.stride = .{ 1, 2 },
});
try std.testing.expectEqualSlices(
f32,
&.{ 2, 3, 4, 5 },
result.data[0..4],
);
}
pub fn matrixMul(comptime T: type, dest: Slice(2, T), a: ConstSlice(2, T), b: ConstSlice(2, T)) void {
std.debug.assert(dest.size[0] == b.size[0]);
std.debug.assert(a.size[1] == b.size[0]);
std.debug.assert(dest.size[1] == a.size[1]);
for (0..dest.size[1]) |k| {
for (0..dest.size[0]) |i| {
dest.idx(.{ i, k }).* = 0;
for (0..a.size[0]) |l| {
dest.idx(.{ i, k }).* += a.idx(.{ l, k }).* * b.idx(.{ i, l }).*;
}
}
}
}
test matrixMul {
// Multiplying a 3x2 matrix by a 2x3 matrix:
// [ 1 2]
// [ 3 4]
// [ 5 6]
// -------
// [-2 5 6] | [43 52]
// [ 5 2 7] | [46 60]
const c = try alloc(2, f32, std.testing.allocator, .{ 2, 2 });
defer std.testing.allocator.free(c.slice());
matrixMul(f32, c.asSlice(), .{
.data = &[_]f32{
-2, 5, 6,
5, 2, 7,
},
.stride = .{ 1, 3 },
.size = .{ 3, 2 },
}, .{
.data = &[_]f32{
1, 2,
3, 4,
5, 6,
},
.stride = .{ 1, 2 },
.size = .{ 2, 3 },
});
try std.testing.expectEqualSlices(f32, &[_]f32{
43, 52,
46, 60,
}, c.data[0..4]);
}
pub fn RangeIterator(comptime D: usize) type {
return struct {
pos: [D]usize,
size: [D]usize,
pub fn next(this: *@This()) ?[D]usize {
for (this.pos[0 .. D - 1], this.pos[1..D], this.size[0 .. D - 1]) |*axis, *next_axis, size| {
if (axis.* >= size) {
axis.* = 0;
next_axis.* += 1;
}
}
if (this.pos[D - 1] >= this.size[D - 1]) {
return null;
}
defer this.pos[0] += 1;
return this.pos;
}
};
}
pub fn iterateRange(comptime D: usize, size: [D]usize) RangeIterator(D) {
return RangeIterator(D){
.pos = [_]usize{0} ** D,
.size = size,
};
}
const std = @import("std");
| https://raw.githubusercontent.com/leroycep/utils.zig/51e07120e8b05e6c5941bc53c765b072a9958c0f/grid.zig |
const std = @import("std");
// invariant: `right != null` iff `left != null`
pub fn Rope(comptime T: type) type {
return struct {
const Self = @This();
const AnyNode = union(enum) {
node: *Node,
leaf: *LeafNode,
fn destroy(node: *AnyNode, allocator: std.mem.Allocator) void {
switch (node.*) {
inline else => |n| n.destroy(allocator),
}
}
/// Gets `length` for `Node`s and `value.len` for `LeafNode`s
fn getLength(node: AnyNode) u32 {
return switch (node) {
.node => |n| n.length,
.leaf => |l| @intCast(l.value.len),
};
}
fn getGraphvizUniqueId(node: AnyNode) usize {
return switch (node) {
inline else => |v| @intFromPtr(v),
};
}
pub fn printGraphviz(node: AnyNode, writer: anytype) !void {
switch (node) {
.node => |n| {
try writer.print("{d}[label=\"{d}\"];\n", .{ node.getGraphvizUniqueId(), n.length });
if (n.left) |l| {
try writer.print("{d} -> {d} [label=\"L\"];\n", .{ node.getGraphvizUniqueId(), l.getGraphvizUniqueId() });
try l.printGraphviz(writer);
}
if (n.right) |r| {
try writer.print("{d} -> {d} [label=\"R\"];\n", .{ node.getGraphvizUniqueId(), r.getGraphvizUniqueId() });
try r.printGraphviz(writer);
}
},
.leaf => |l| {
try writer.print("{d}[label=\"{s} ({d})\"];\n", .{ node.getGraphvizUniqueId(), l.value, l.value.len });
},
}
}
};
pub const Node = struct {
left: ?AnyNode = null,
right: ?AnyNode = null,
length: u32 = 0,
/// Rope dupes value.
fn create(allocator: std.mem.Allocator) error{OutOfMemory}!*Node {
const node = try allocator.create(Node);
node.* = .{};
return node;
}
fn destroy(node: *Node, allocator: std.mem.Allocator) void {
if (node.left) |*left| left.destroy(allocator);
if (node.right) |*right| right.destroy(allocator);
node.* = undefined;
allocator.destroy(node);
}
};
pub const LeafNode = struct {
value: []T,
/// Rope dupes value.
fn create(allocator: std.mem.Allocator, value: []const T) error{OutOfMemory}!*LeafNode {
const node = try allocator.create(LeafNode);
node.* = .{
.value = try allocator.dupe(u8, value),
};
return node;
}
fn destroy(node: *LeafNode, allocator: std.mem.Allocator) void {
allocator.free(node.value);
node.* = undefined;
allocator.destroy(node);
}
};
root: Node = .{},
// total_length: u32 = 0,
pub fn deinit(rope: *Self, allocator: std.mem.Allocator) void {
if (rope.root.left) |*left| left.destroy(allocator);
if (rope.root.right) |*right| right.destroy(allocator);
}
pub fn prepend(rope: *Self, allocator: std.mem.Allocator, value: []const T) !void {
if (rope.root.left == null) {
rope.root.left = .{ .leaf = try LeafNode.create(allocator, value) };
rope.root.length = @intCast(value.len);
return;
}
const node = try Node.create(allocator);
node.* = rope.root;
const leaf = try LeafNode.create(allocator, value);
rope.root.right = .{ .node = node };
rope.root.left = .{ .leaf = leaf };
rope.root.length = @as(u32, @intCast(value.len)) + if (rope.root.right) |r| r.getLength() else 0;
}
pub fn append(rope: *Self, allocator: std.mem.Allocator, value: []const T) !void {
if (rope.root.left == null) {
rope.root.left = .{ .leaf = try LeafNode.create(allocator, value) };
rope.root.length = @intCast(value.len);
return;
}
if (rope.root.right == null) {
rope.root.right = .{ .leaf = try LeafNode.create(allocator, value) };
rope.root.length += @intCast(value.len);
return;
}
const node = try Node.create(allocator);
node.* = rope.root;
const leaf = try LeafNode.create(allocator, value);
rope.root.left = .{ .node = node };
rope.root.right = .{ .leaf = leaf };
rope.root.length += @intCast(value.len);
}
pub const Iterator = struct {
stack: std.ArrayList(AnyNode),
pub fn next(iterator: *Iterator) error{OutOfMemory}!?*LeafNode {
const result = iterator.stack.popOrNull() orelse return null;
while (iterator.stack.popOrNull()) |parent| {
if (parent.node.right) |right_node| {
var node = right_node;
while (node == .node and node.node.left != null) {
try iterator.stack.append(node);
node = node.node.left.?;
}
try iterator.stack.append(node);
std.debug.assert(node == .leaf);
break;
}
}
return result.leaf;
}
pub fn deinit(iterator: *Iterator) void {
iterator.stack.deinit();
iterator.* = undefined;
}
};
/// Caller must deinit `Iterator` when they are done.
pub fn iterate(rope: *Self, allocator: std.mem.Allocator) error{OutOfMemory}!Iterator {
var iterator = Iterator{ .stack = std.ArrayList(AnyNode).init(allocator) };
if (rope.root.left == null) return iterator;
var node = AnyNode{ .node = &rope.root };
while (node == .node and node.node.left != null) {
try iterator.stack.append(node);
node = node.node.left.?;
}
try iterator.stack.append(node);
std.debug.assert(node == .leaf);
return iterator;
}
/// Iterate through rope and collect into a list
pub fn collect(rope: *Self, allocator: std.mem.Allocator, list: *std.ArrayListUnmanaged(T)) error{OutOfMemory}!void {
var iterator = try rope.iterate(allocator);
defer iterator.deinit();
while (try iterator.next()) |leaf| {
try list.appendSlice(allocator, leaf.value);
}
}
pub fn at(rope: *Self, index: u32) T {
var node = &rope.root;
var adjusted_index = index;
while (true) {
const next_node, adjusted_index = if (adjusted_index < node.left.?.getLength())
.{ node.left, adjusted_index }
else
.{ node.right, adjusted_index - node.left.?.getLength() };
switch (next_node.?) {
.node => |n| node = n,
.leaf => |l| return l.value[adjusted_index],
}
}
}
/// Combine two `Rope`s.
pub fn concat(left: Self, right: Self, allocator: std.mem.Allocator) error{OutOfMemory}!Self {
const new_left = try allocator.create(Node);
new_left.* = left.root;
const new_right = try allocator.create(Node);
new_right.* = right.root;
return .{
.node = .{
.left = new_left,
.right = new_right,
.length = left.root.length + right.root.length,
},
};
}
pub fn printGraphviz(rope: *Self, writer: anytype) !void {
try writer.writeAll("digraph preview {");
try (AnyNode{ .node = &rope.root }).printGraphviz(writer);
try writer.writeAll("}");
}
};
}
test {
const allocator = std.testing.allocator;
// const allocator = std.heap.page_allocator;
const StringRope = Rope(u8);
var rope = StringRope{};
defer rope.deinit(allocator);
try rope.prepend(allocator, ") void ");
try rope.prepend(allocator, "abc(");
try rope.append(allocator, "{");
try rope.append(allocator, "hello();");
try rope.prepend(allocator, "fn ");
try rope.prepend(allocator, "pub ");
try rope.append(allocator, "}");
var out = try std.fs.cwd().createFile("abc.dot", .{});
defer out.close();
try rope.printGraphviz(out.writer());
var collected = std.ArrayListUnmanaged(u8){};
defer collected.deinit(allocator);
try rope.collect(allocator, &collected);
for (collected.items, 0..) |c, i| {
try std.testing.expectFmt(&.{c}, "{c}", .{rope.at(@intCast(i))});
}
}
| https://raw.githubusercontent.com/SuperAuguste/random-dsa-dump/acba5f5b29106e06b372761d69a9a73622f1c063/rope.zig |
processor 6502
include "vcs.h"
include "macro.h"
include "xmacro.h"
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Variables segment
seg.u Variables
org $80
Temp .byte
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Code segment
seg Code
org $f000
Start
CLEAN_START
NextFrame
lsr SWCHB ; test Game Reset switch
bcc Start ; reset?
; 1 + 3 lines of VSYNC
VERTICAL_SYNC
; 37 lines of underscan
TIMER_SETUP 37
TIMER_WAIT
; 192 lines of frame
TIMER_SETUP 192
TIMER_WAIT
; 29 lines of overscan
TIMER_SETUP 29
TIMER_WAIT
; total = 262 lines, go to next frame
jmp NextFrame
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Epilogue
org $fffc
.word Start ; reset vector
.word Start ; BRK vector
| https://raw.githubusercontent.com/MikeDX/dwarf-zig/0253597252a82655517cbab716ac277a0230cacb/dwarf.zig |
const root = @import("root");
pub const c = if (@hasDecl(root, "loadable_extension"))
@import("c/loadable_extension.zig")
else
@cImport({
@cInclude("sqlite3.h");
@cInclude("workaround.h");
});
// versionGreaterThanOrEqualTo returns true if the SQLite version is >= to the major.minor.patch provided.
pub fn versionGreaterThanOrEqualTo(major: u8, minor: u8, patch: u8) bool {
return c.SQLITE_VERSION_NUMBER >= @as(u32, major) * 1000000 + @as(u32, minor) * 1000 + @as(u32, patch);
}
comptime {
if (!versionGreaterThanOrEqualTo(3, 21, 0)) {
@compileError("must use SQLite >= 3.21.0");
}
}
| https://raw.githubusercontent.com/gx14ac/zig-sqlite/86bd0b9422957c9d9227415a8acc9c3812e9dd24/c.zig |