Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos
repos/tokamak/README.md
# tokamak > I wrote a short blog post about the **[motivation and the design of the > framework](https://tomsik.cz/posts/tokamak/)** > > I am doing some breaking changes, so maybe check one of the [previous > versions](https://github.com/cztomsik/tokamak/tree/629dfd45bd95f310646d61f635604ec393253990) > if you want to use it right now. The most up-to-date example is/might be in > the [Ava PLS](https://github.com/cztomsik/ava) repository. Server-side framework for Zig, relying heavily on dependency injection. The code has been extracted from [Ava PLS](https://github.com/cztomsik/ava) which has been using it for a few months already, and I'm using it in one other project which is going to production soon, so it's not just a toy, it actually works. That said, it is **not designed to be used alone**, but with a reverse proxy in front of it, like Nginx or Cloudfront, which will handle SSL, caching, sanitization, etc. ## Getting started Simple things should be easy to do. ```zig const tk = @import("tokamak"); pub fn main() !void { var server = try tk.Server.start(allocator, hello, .{ .port = 8080 }); server.wait(); } fn hello() ![]const u8 { return "Hello"; } ``` ## Dependency injection The framework is built around the concept of dependency injection. This means that your handler function can take any number of parameters, and the framework will try to provide them for you. Notable types you can inject are: - `std.mem.Allocator` (request-scoped arena allocator) - `*tk.Request` (current request, including headers, body reader, etc.) - `*tk.Response` (current response, with methods to send data, set headers, etc.) - `*tk.Injector` (the injector itself, see below) - and everything you provide yourself For example, you can you easily write a handler function which will create a string on the fly and return it to the client without any tight coupling to the server or the request/response types. ```zig fn hello(allocator: std.mem.Allocator) ![]const u8 { return std.fmt.allocPrint(allocator, "Hello {}", .{std.time.timestamp()}); } ``` If you return any other type than `[]const u8`, the framework will try to serialize it to JSON. ```zig fn hello() !HelloRes { return .{ .message = "Hello" }; } ``` If you need a more fine-grained control over the response, you can inject a `*tk.Response` and use its methods directly. > But this will of course make your code tightly coupled to respective types > and it should be avoided if possible. ```zig fn hello(res: *tk.Response) !void { try res.sendJson(.{ .message = "Hello" }); } ``` ## Custom dependencies You can also provide your own (global) dependencies by passing your own `tk.Injector` to the server. ```zig pub fn main() !void { var db = try sqlite.open("my.db"); var server = try tk.Server.start(allocator, hello, .{ .injector = tk.Injector.from(.{ &db }), .port = 8080 }); server.wait(); } ``` ## Middlewares The framework supports special functions, called middlewares, which can alter the flow of the request by either responding directly or calling the next middleware. For example, here's a simple logger middleware: ```zig fn handleLogger(ctx: *Context) anyerror!void { log.debug("{s} {s}", .{ @tagName(ctx.req.method), ctx.req.url }); return ctx.next(); } ``` As you can see, the middleware takes a `*Context` and returns `anyerror!void`. It can do some pre-processing, logging, etc., and then call `ctx.next()` to continue with the next middleware or the handler function. There are few built-in middlewares, like `tk.chain()`, or `tk.send()`, and they work similarly to Express.js except that we don't have closures in Zig, so some things are a bit more verbose and/or need custom-scoping (see below). ```zig var server = try tk.Server.start(gpa.allocator(), handler, .{ .port = 8080 }); server.wait(); const handler = tk.chain(.{ // Log every request tk.logger(.{}), // Send "Hello" for GET requests to "/" tk.get("/", tk.send("Hello")), // Send 404 for anything else tk.send(error.NotFound), }); ``` ## Custom-scoping Zig doesn't have closures, so we can't just capture variables from the outer scope. But what we can do is to use our dependency injection context to provide some dependencies to any middleware or handler function further in the chain. > Middlewares do not support the shorthand syntax for dependency injection, > so you need to use `ctx.injector.get(T)` to get your dependencies manually. ```zig fn auth(ctx: *Context) anyerror!void { const db = ctx.injector.get(*Db); const token = try jwt.parse(ctx.req.getHeader("Authorization")); const user = db.find(User, token.id) catch null; ctx.injector.push(&user); return ctx.next(); } ``` ## Routing There's a simple router built in, in the spirit of Express.js. It supports up to 16 basic path params, and `*` wildcard. ```zig const tk = @import("tokamak"); const api = struct { // Path params need to be in the order they appear in the path // Dependencies go always first pub fn @"GET /:name"(allocator: std.mem.Allocator, name: []const u8) ![]const u8 { return std.fmt.allocPrint(allocator, "Hello, {s}", .{name}); } // In case of POST/PUT there's also a body // The body is deserialized from JSON pub fn @"POST /:id"(allocator: std.mem.Allocator, id: u32, data: struct {}) ![]const u8 { ... } ... } pub fn main() !void { var server = try tk.Server.start(allocator, api, .{ .port = 8080 }); server.wait(); } ``` For the convenience, you can pass the api struct directly to the server, but under the hood it's just another middleware, which you can compose to a more complex hierarchy. ```zig var server = try tk.Server.start(gpa.allocator(), handler, .{ .port = 8080 }); server.wait(); const handler = tk.chain(.{ tk.logger(.{}), tk.get("/", tk.send("Hello")), // this is classic, express-style routing tk.group("/api", tk.router(api)), // and this is our shorthand tk.send(error.NotFound), }); const api = struct { pub fn @"GET /"() []const u8 { return "Hello"; } pub fn @"GET /:name"(allocator: std.mem.Allocator, name: []const u8) ![]const u8 { return std.fmt.allocPrint(allocator, "Hello {s}", .{name}); } }; ``` ## Error handling If your handler returns an error, the framework will try to serialize it to JSON and send it to the client. ```zig fn hello() !void { // This will send 500 and {"error": "TODO"} return error.TODO; } ``` ## Static files > TODO: It is not possible to serve whole directories yet. To send a static file, you can use the `tk.sendStatic(path)` middleware. ```zig const handler = tk.chain(.{ tk.logger(.{}), tk.get("/", tk.sendStatic("static/index.html")), tk.send(error.NotFound), }); ``` If you want to embed some files into the binary, you can specify such paths to the `tokamak` module in your `build.zig` file. ```zig const embed: []const []const u8 = &.{ "static/index.html", }; const tokamak = b.dependency("tokamak", .{ .embed = embed }); exe.root_module.addImport("tokamak", tokamak.module("tokamak")); ``` In this case, only the files listed in the `embed` array will be embedded into the binary and any other files will be served from the filesystem. ## MIME types The framework will try to guess the MIME type based on the file extension, but you can also provide your own in the root module. ```zig pub const mime_types = tk.mime_types ++ .{ .{ ".foo", "text/foo" }, }; ``` ## Config For a simple configuration, you can use the `tk.config.read(T, opts)` function, which will read the configuration from a JSON file. The `opts` parameter is optional and can be used to specify the path to the config file and parsing options. ```zig const Cfg = struct { foo: u32, bar: []const u8, }; const cfg = try tk.config.read(Cfg, .{ .path = "config.json" }); ``` There's also experimental `tk.config.write(T, opts)` function, which will write the configuration back to the file. ## Monitor The `tk.monitor(procs)` allows you to execute multiple processes in parallel and restart them automatically if they exit. It takes a tuple of `{ name, fn_ptr, args_tuple }` triples as input. It will only work on systems with `fork()`. What this means is that you can easily create a self-contained binary which will stay up and running, even if something crashes unexpectedly. > The function takes over the main thread, forks, and it might lead to > unexpected behavior if you're not careful. Only use it if you know what you're > doing. ```zig monitor(.{ .{ "server", &runServer, .{ 8080 } }, .{ "worker", &runWorker, .{} }, ... }); ``` ## License MIT
0
repos
repos/tokamak/build.zig.zon
.{ .name = "tokamak", .version = "0.0.1", .paths = .{ "build.zig", "build.zig.zon", "src", "LICENSE", "README.md", }, }
0
repos
repos/tokamak/build.zig
const std = @import("std"); const log = std.log.scoped(.tokamak); pub fn build(b: *std.Build) !void { const embed = b.option([]const []const u8, "embed", "Files to embed in the binary") orelse &.{}; const root = b.addModule("tokamak", .{ .root_source_file = .{ .path = "src/main.zig" }, }); try embedFiles(b, root, @alignCast(embed)); const tests = b.addTest(.{ .root_source_file = .{ .path = "src/main.zig" } }); const run_tests = b.addRunArtifact(tests); const test_step = b.step("test", "Run tests"); test_step.dependOn(&run_tests.step); } // TODO: This is simple and it works, it even recompiles if the files change. // However, it's impossible to control when the files are read. So ie. it // fails for `npm run build` fn embedFiles(b: *std.Build, root: *std.Build.Module, files: []const []const u8) !void { const options = b.addOptions(); root.addOptions("embed", options); const contents = try b.allocator.alloc([]const u8, files.len); for (files, 0..) |path, i| { errdefer |e| { if (e == error.FileNotFound) { log.err("File not found: {s}", .{path}); } } contents[i] = try std.fs.cwd().readFileAlloc( b.allocator, path, std.math.maxInt(u32), ); } options.addOption([]const []const u8, "files", files); options.addOption([]const []const u8, "contents", contents); }
0
repos/tokamak
repos/tokamak/example/build.zig.zon
.{ .name = "example", .version = "0.0.0", .dependencies = .{ .tokamak = .{ .path = ".." } }, .paths = .{ "", }, }
0
repos/tokamak
repos/tokamak/example/build.zig
const std = @import("std"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const exe = b.addExecutable(.{ .name = "example", .root_source_file = .{ .path = "src/example.zig" }, .target = target, .optimize = optimize, }); exe.root_module.addImport("tokamak", b.dependency("tokamak", .{}).module("tokamak")); b.installArtifact(exe); const run_cmd = b.addRunArtifact(exe); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { run_cmd.addArgs(args); } const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); }
0
repos/tokamak/example
repos/tokamak/example/src/example.zig
const std = @import("std"); const tk = @import("tokamak"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); var server = try tk.Server.start(gpa.allocator(), handler, .{ .port = 8080 }); server.wait(); } const handler = tk.chain(.{ tk.logger(.{}), tk.get("/", tk.send("Hello")), tk.group("/api", tk.router(api)), tk.send(error.NotFound), }); const api = struct { pub fn @"GET /"() []const u8 { return "Hello"; } pub fn @"GET /:name"(allocator: std.mem.Allocator, name: []const u8) ![]const u8 { return std.fmt.allocPrint(allocator, "Hello {s}", .{name}); } };
0
repos/tokamak
repos/tokamak/src/response.zig
const std = @import("std"); const Request = @import("request.zig").Request; pub const Response = struct { req: *Request, responded: bool = false, keep_alive: bool = true, sse: bool = false, status: std.http.Status = .ok, headers: std.ArrayList(std.http.Header), out: ?std.http.Server.Response = null, buf: [1024]u8 = undefined, /// Sets a header. If the response has already been sent, this function /// returns an error. Both `name` and `value` must be valid for the entire /// lifetime of the response. pub fn setHeader(self: *Response, name: []const u8, value: []const u8) !void { if (self.responded) return error.HeadersAlreadySent; try self.headers.append(.{ .name = name, .value = value }); } /// Sets a cookie. If the response has already been sent, this function /// returns an error. pub fn setCookie(self: *Response, name: []const u8, value: []const u8, options: CookieOptions) !void { if (self.responded) return error.HeadersAlreadySent; // TODO: start with current header? var buf = std.ArrayList(u8).init(self.req.allocator); try buf.appendSlice(name); try buf.append('='); try buf.appendSlice(value); if (options.max_age) |age| { try buf.appendSlice("; Max-Age="); try buf.writer().print("{d}", .{age}); } if (options.domain) |d| { try buf.appendSlice("; Domain="); try buf.appendSlice(d); } if (options.http_only) { try buf.appendSlice("; HttpOnly"); } if (options.secure) { try buf.appendSlice("; Secure"); } try self.setHeader("Set-Cookie", buf.items); } /// Returns a writer for the response body. If the response has already been /// sent, this function returns an error. pub fn writer(self: *Response) !std.io.AnyWriter { if (!self.responded) try self.respond(); return self.out.?.writer(); } /// Sends a response depending on the type of the value. pub fn send(self: *Response, res: anytype) !void { if (comptime @TypeOf(res) == []const u8) return self.sendChunk(res); return switch (comptime @typeInfo(@TypeOf(res))) { .Void => if (!self.responded) self.sendStatus(.no_content), .ErrorSet => self.sendError(res), .ErrorUnion => if (res) |r| self.send(r) else |e| self.sendError(e), else => self.sendJson(res), }; } /// Sends a status code. pub fn sendStatus(self: *Response, status: std.http.Status) !void { self.status = status; try self.respond(); } /// Sends an error response. pub fn sendError(self: *Response, err: anyerror) !void { self.status = switch (err) { error.InvalidCharacter, error.UnexpectedToken, error.InvalidNumber, error.Overflow, error.InvalidEnumTag, error.DuplicateField, error.UnknownField, error.MissingField, error.LengthMismatch => .bad_request, error.Unauthorized => .unauthorized, error.NotFound => .not_found, error.Forbidden => .forbidden, else => .internal_server_error, }; return self.sendJson(.{ .@"error" = err }); } /// Sends a chunk of data. pub fn sendChunk(self: *Response, chunk: []const u8) !void { var w = try self.writer(); try w.writeAll(chunk); try self.out.?.flush(); } /// Sends a chunk of JSON. The chunk is always either single line, or in /// case of SSE, it's a valid message ending with \n\n. /// Supports values, slices and iterators. pub fn sendJson(self: *Response, body: anytype) !void { if (!self.responded) { try self.setHeader("Content-Type", "application/json"); } var w = try self.writer(); if (self.sse) { try w.writeAll("data: "); } if (comptime std.meta.hasFn(@TypeOf(body), "next")) { var copy = body; var i: usize = 0; try w.writeAll("["); while (try copy.next()) |item| : (i += 1) { if (i != 0) try w.writeAll(","); try std.json.stringify(item, .{}, w); } try w.writeAll("]"); } else { try std.json.stringify(body, .{}, w); } try w.writeAll(if (self.sse) "\n\n" else "\r\n"); try self.out.?.flush(); } /// Sends a chunk of JSON lines. The chunk always ends with a newline. /// Expects an iterator. pub fn sendJsonLines(self: *Response, iterator: anytype) !void { if (!self.responded) { try self.setHeader("Content-Type", "application/jsonlines"); try self.respond(); } var copy = iterator; while (try copy.next()) |item| { try self.sendJson(item); } } /// Starts an SSE stream. pub fn startSse(self: *Response) !void { try self.setHeader("Content-Type", "text/event-stream"); try self.setHeader("Cache-Control", "no-cache"); try self.setHeader("Connection", "keep-alive"); self.sse = true; try self.respond(); } /// Redirects the response to a different URL. pub fn redirect(self: *Response, url: []const u8, options: struct { status: std.http.Status = .found }) !void { try self.setHeader("Location", url); try self.sendStatus(options.status); } /// Adds no-cache headers to the response. pub fn noCache(self: *Response) !void { try self.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); try self.setHeader("Pragma", "no-cache"); try self.setHeader("Expires", "0"); } /// Start the response manually. pub fn respond(self: *Response) !void { if (self.responded) return error.ResponseAlreadyStarted; self.responded = true; self.out = self.req.raw.respondStreaming(.{ .send_buffer = &self.buf, .respond_options = .{ .status = self.status, .keep_alive = self.keep_alive, .extra_headers = self.headers.items, }, }); } }; pub const CookieOptions = struct { domain: ?[]const u8 = null, max_age: ?u32 = null, http_only: bool = false, secure: bool = false, };
0
repos/tokamak
repos/tokamak/src/server.zig
const std = @import("std"); const log = std.log.scoped(.server); const Injector = @import("injector.zig").Injector; const Request = @import("request.zig").Request; const Response = @import("response.zig").Response; pub const Options = struct { injector: Injector = .{}, hostname: []const u8 = "127.0.0.1", port: u16, n_threads: usize = 8, keep_alive: bool = true, }; pub const Handler = fn (*Context) anyerror!void; pub const Context = struct { allocator: std.mem.Allocator, req: Request, res: Response, injector: Injector, chain: []const *const fn (*Context) anyerror!void = &.{}, drained: bool = false, fn init(self: *Context, allocator: std.mem.Allocator, server: *Server, http: *std.http.Server) !void { const raw = http.receiveHead() catch |e| { if (e == error.HttpHeadersUnreadable) return error.HttpConnectionClosing; return e; }; self.* = .{ .allocator = allocator, .req = try Request.init(allocator, raw), .res = .{ .req = &self.req, .headers = std.ArrayList(std.http.Header).init(allocator) }, .injector = .{ .parent = &server.injector }, }; self.res.keep_alive = server.keep_alive; try self.injector.push(@as(*const std.mem.Allocator, &self.allocator)); try self.injector.push(&self.req); try self.injector.push(&self.res); try self.injector.push(self); } /// Run a handler in a scoped context. This means `next` will only run the /// remaining handlers in the provided chain and the injector will be reset /// to its previous state after the handler has been run. If all the /// handlers have been run, it will return `true`, otherwise `false`. pub fn runScoped(self: *Context, handler: *const Handler, chain: []const *const Handler) !bool { const n_deps = self.injector.registry.len; const prev = self.chain; defer { self.injector.registry.len = n_deps; self.chain = prev; self.drained = false; } self.chain = chain; self.drained = false; try handler(self); return self.drained; } /// Run the next middleware or handler in the chain. pub inline fn next(self: *Context) !void { if (self.chain.len > 0) { const handler = self.chain[0]; self.chain = self.chain[1..]; return handler(self); } else { self.drained = true; } } pub fn wrap(fun: anytype) Handler { if (@TypeOf(fun) == Handler) return fun; const H = struct { fn handle(ctx: *Context) anyerror!void { return ctx.res.send(ctx.injector.call(fun, .{})); } }; return H.handle; } }; /// A simple HTTP server with dependency injection. pub const Server = struct { allocator: std.mem.Allocator, injector: Injector, net: std.net.Server, threads: []std.Thread, mutex: std.Thread.Mutex = .{}, stopping: std.Thread.ResetEvent = .{}, stopped: std.Thread.ResetEvent = .{}, handler: *const Handler, keep_alive: bool, /// Run the server, blocking the current thread. pub fn run(allocator: std.mem.Allocator, handler: anytype, options: Options) !void { var server = try start(allocator, handler, options); defer server.deinit(); server.wait(); } /// Start a new server. pub fn start(allocator: std.mem.Allocator, handler: anytype, options: Options) !*Server { const self = try allocator.create(Server); errdefer allocator.destroy(self); const address = try std.net.Address.parseIp(options.hostname, options.port); var net = try address.listen(.{ .reuse_address = true }); errdefer net.deinit(); const threads = try allocator.alloc(std.Thread, options.n_threads); errdefer allocator.free(threads); self.* = .{ .allocator = allocator, .injector = options.injector, .net = net, .threads = threads, .handler = Context.wrap(switch (comptime @typeInfo(@TypeOf(handler))) { .Type => @import("router.zig").router(handler), .Fn => handler, else => @compileError("handler must be a function or a struct"), }), .keep_alive = options.keep_alive, }; for (threads) |*t| { t.* = std.Thread.spawn(.{}, loop, .{self}) catch @panic("thread spawn"); } return self; } /// Wait for the server to stop. pub fn wait(self: *Server) void { self.stopped.wait(); } /// Stop and deinitialize the server. pub fn deinit(self: *Server) void { self.stopping.set(); if (std.net.tcpConnectToAddress(self.net.listen_address)) |c| c.close() else |_| {} self.net.deinit(); for (self.threads) |t| t.join(); self.allocator.free(self.threads); self.stopped.set(); self.allocator.destroy(self); } fn accept(self: *Server) ?std.net.Server.Connection { self.mutex.lock(); defer self.mutex.unlock(); if (self.stopping.isSet()) return null; const conn = self.net.accept() catch |e| { if (self.stopping.isSet()) return null; // TODO: not sure what we can do here // but we should not just throw because that would crash the thread silently std.debug.panic("accept: {}", .{e}); }; const timeout = std.posix.timeval{ .tv_sec = @as(i32, 5), .tv_usec = @as(i32, 0), }; std.posix.setsockopt(conn.stream.handle, std.posix.SOL.SOCKET, std.posix.SO.RCVTIMEO, std.mem.asBytes(&timeout)) catch {}; return conn; } fn loop(server: *Server) void { var arena = std.heap.ArenaAllocator.init(server.allocator); defer arena.deinit(); accept: while (server.accept()) |conn| { defer conn.stream.close(); var buf: [10 * 1024]u8 = undefined; var http = std.http.Server.init(conn, &buf); while (http.state == .ready) { defer _ = arena.reset(.{ .retain_with_limit = 8 * 1024 * 1024 }); var ctx: Context = undefined; ctx.init(arena.allocator(), server, &http) catch |e| { if (e != error.HttpConnectionClosing) log.err("context: {}", .{e}); continue :accept; }; defer { if (!ctx.res.responded) ctx.res.sendStatus(.no_content) catch {}; ctx.res.out.?.end() catch {}; } server.handler(&ctx) catch |e| { log.err("handler: {}", .{e}); ctx.res.sendError(e) catch {}; continue :accept; }; } } } };
0
repos/tokamak
repos/tokamak/src/middleware.zig
const std = @import("std"); const Context = @import("server.zig").Context; const Handler = @import("server.zig").Handler; /// Returns a middleware that executes given steps as a chain. Every step should /// either respond or call the next step in the chain. pub fn chain(comptime steps: anytype) Handler { const handlers = comptime brk: { var tmp: [steps.len]*const Handler = undefined; for (steps, 0..) |m, i| tmp[i] = &Context.wrap(m); const res = tmp; break :brk &res; }; const H = struct { fn handleChain(ctx: *Context) anyerror!void { if (!try ctx.runScoped(handlers[0], handlers[1..])) { return; } // TODO: tail-call? return ctx.next(); } }; return H.handleChain; } /// Returns a middleware that matches the request path prefix and calls the /// given handler/middleware. If the prefix matches, the request path is /// modified to remove the prefix. If the handler/middleware responds, the /// chain is stopped. pub fn group(comptime prefix: []const u8, handler: anytype) Handler { const H = struct { fn handleGroup(ctx: *Context) anyerror!void { if (std.mem.startsWith(u8, ctx.req.path, prefix)) { const orig = ctx.req.path; ctx.req.path = ctx.req.path[prefix.len..]; defer ctx.req.path = orig; if (!try ctx.runScoped(&Context.wrap(handler), &.{})) return; } // TODO: tail-call? return ctx.next(); } }; return H.handleGroup; } /// Returns a middleware for providing a dependency to the rest of the current /// scope. Accepts a factory that returns the dependency. The factory can /// use the current scope to resolve its own dependencies. If the resulting /// type has a `deinit` method, it will be called at the end of the scope. pub fn provide(comptime factory: anytype) Handler { const H = struct { fn handleProvide(ctx: *Context) anyerror!void { var dep = try ctx.injector.call(factory, .{}); try ctx.injector.push(&dep); defer if (comptime hasDeinit(@TypeOf(dep))) { dep.deinit(); }; return ctx.next(); } fn hasDeinit(comptime T: type) bool { return switch (@typeInfo(T)) { .Pointer => |ptr| hasDeinit(ptr.child), else => @hasDecl(T, "deinit"), }; } }; return H.handleProvide; } /// Returns a handler that sends the given, comptime response. pub fn send(comptime res: anytype) Handler { const H = struct { fn handleSend(ctx: *Context) anyerror!void { return ctx.res.send(res); } }; return H.handleSend; } /// Returns a middleware for logging all requests going through it. pub fn logger(options: struct { scope: @TypeOf(.EnumLiteral) = .server }) Handler { const log = std.log.scoped(options.scope); const H = struct { fn handleLogger(ctx: *Context) anyerror!void { const start = std.time.milliTimestamp(); defer log.debug("{s} {s} {} [{}ms]", .{ @tagName(ctx.req.method), ctx.req.raw.head.target, @intFromEnum(ctx.res.status), std.time.milliTimestamp() - start, }); return ctx.next(); } }; return H.handleLogger; } /// Returns a middleware that sets the CORS headers for the request. pub fn cors() Handler { const H = struct { fn handleCors(ctx: *Context) anyerror!void { try ctx.res.setHeader("Access-Control-Allow-Origin", ctx.req.getHeader("Origin") orelse "*"); if (ctx.req.method == .OPTIONS) { try ctx.res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); try ctx.res.setHeader("Access-Control-Allow-Headers", "Content-Type"); try ctx.res.setHeader("Access-Control-Allow-Private-Network", "true"); try ctx.res.sendStatus(.no_content); return; } return ctx.next(); } }; return H.handleCors; }
0
repos/tokamak
repos/tokamak/src/monitor.zig
const std = @import("std"); const log = std.log.scoped(.monitor); /// Runs the given processes in parallel, restarting them if they exit. /// /// The processes are tuples of the form: /// .{ "name", &fn, .{ ...args } } /// /// Example: /// pub fn main() !void { /// // do some init checks and setup if needed /// /// return monitor(.{ /// .{ "server", &serverFn, .{ 8080 } }, /// .{ "worker 1", &workerFn, .{ 1 } }, /// .{ "worker 2", &workerFn, .{ 2 } }, /// }); /// } pub fn monitor(processes: anytype) noreturn { if (comptime !isTupleOfProcesses(@TypeOf(processes))) { @compileError("Expected tuple of .{ \"name\", &fn, .{ ...args } }"); } var pids = std.mem.zeroes([processes.len]std.posix.pid_t); while (true) { inline for (0..processes.len) |i| { if (pids[i] == 0) { const child = std.posix.fork() catch @panic("fork failed"); if (child == 0) return run(processes[i]); log.debug("start: #{d} {s} pid: {d}", .{ i, processes[i][0], child }); pids[i] = child; } } const exited = std.posix.waitpid(0, 0).pid; inline for (0..processes.len) |i| { if (pids[i] == exited) { log.debug("exit: #{d} {s} pid: {d}", .{ i, processes[i][0], exited }); pids[i] = 0; } } } } fn run(proc: anytype) noreturn { // Helps with mixing logs from different processes. std.posix.nanosleep(0, 100_000_000); setproctitle(proc[0]); const res = @call(.auto, proc[1], proc[2]); if (comptime @typeInfo(@TypeOf(res)) == .ErrorUnion) { _ = res catch |e| { log.err("{s}", .{@errorName(e)}); if (@errorReturnTrace()) |trace| { std.debug.dumpStackTrace(trace.*); } std.posix.exit(1); }; } std.posix.exit(0); } fn setproctitle(name: [:0]const u8) void { // name includes path so we should always have some extra space const dest = std.mem.span(std.os.argv[0]); if (std.os.argv.len == 1 and dest.len >= name.len) { @memcpy(dest[0..name.len], name); dest.ptr[name.len] = 0; } else log.debug("Could not rewrite process name {s}\ndest: {s}", .{ name, std.os.argv[0] }); } fn isTupleOfProcesses(comptime T: type) bool { if (!isTuple(T)) return false; inline for (@typeInfo(T).Struct.fields) |f| { if (!isTuple(f.type)) return false; if (@typeInfo(f.type).Struct.fields.len != 3) return false; } return true; } fn isTuple(comptime T: type) bool { const info = @typeInfo(T); return info == .Struct and info.Struct.is_tuple; }
0
repos/tokamak
repos/tokamak/src/main.zig
const std = @import("std"); pub const config = @import("config.zig"); pub const monitor = @import("monitor.zig").monitor; pub const Injector = @import("injector.zig").Injector; pub const Server = @import("server.zig").Server; pub const ServerOptions = @import("server.zig").Options; pub const Handler = @import("server.zig").Handler; pub const Context = @import("server.zig").Context; pub const Request = @import("request.zig").Request; pub const Params = @import("request.zig").Params; pub const Response = @import("response.zig").Response; pub const chain = @import("middleware.zig").chain; pub const group = @import("middleware.zig").group; pub const provide = @import("middleware.zig").provide; pub const send = @import("middleware.zig").send; pub const logger = @import("middleware.zig").logger; pub const cors = @import("middleware.zig").cors; pub const sendStatic = @import("static.zig").sendStatic; pub const router = @import("router.zig").router; pub const get = @import("router.zig").get; pub const post = @import("router.zig").post; pub const put = @import("router.zig").put; pub const patch = @import("router.zig").patch; pub const delete = @import("router.zig").delete; test { std.testing.refAllDecls(@This()); }
0
repos/tokamak
repos/tokamak/src/config.zig
const std = @import("std"); const log = std.log.scoped(.config); const DEFAULT_PATH = "config.json"; const ReadOptions = struct { path: []const u8 = DEFAULT_PATH, cwd: ?std.fs.Dir = null, parse: std.json.ParseOptions = .{ .ignore_unknown_fields = true }, }; pub fn read(comptime T: type, allocator: std.mem.Allocator, options: ReadOptions) !std.json.Parsed(T) { const cwd = options.cwd orelse std.fs.cwd(); const file = cwd.openFile(options.path, .{ .mode = .read_only }) catch |e| switch (e) { error.FileNotFound => return std.json.parseFromSlice(T, allocator, "{}", .{}), else => return e, }; defer file.close(); var reader = std.json.reader(allocator, file.reader()); defer reader.deinit(); errdefer log.debug("Failed to parse config: {s}", .{reader.scanner.input[reader.scanner.cursor..]}); return try std.json.parseFromTokenSource(T, allocator, &reader, options.parse); } const WriteOptions = struct { path: []const u8 = DEFAULT_PATH, cwd: ?std.fw.Dir = null, stringify: std.json.StringifyOptions = .{ .whitespace = .indent_2 }, }; pub fn write(comptime T: type, config: T, options: WriteOptions) !void { const cwd = options.cwd orelse std.fs.cwd(); const file = try cwd.createFile(options.path, .w); defer file.close(); try std.json.stringify( config, options.stringify, file.writer(), ); }
0
repos/tokamak
repos/tokamak/src/request.zig
const std = @import("std"); pub const Request = struct { allocator: std.mem.Allocator, raw: std.http.Server.Request, method: std.http.Method, path: []const u8, query_params: []const QueryParam, pub const QueryParam = struct { name: []const u8, value: []const u8, }; pub fn init(allocator: std.mem.Allocator, raw: std.http.Server.Request) !Request { const target: []u8 = try allocator.dupe(u8, raw.head.target); const i = std.mem.indexOfScalar(u8, target, '?') orelse target.len; return .{ .allocator = allocator, .raw = raw, .method = raw.head.method, .path = decodeInplace(target[0..i]), .query_params = if (i < target.len) try parseQueryParams(allocator, target[i + 1 ..]) else &.{}, }; } /// Returns the value of the given query parameter or null if it doesn't /// exist. pub fn getQueryParam(self: *const Request, name: []const u8) ?[]const u8 { for (self.query_params) |param| { if (std.mem.eql(u8, param.name, name)) { return param.value; } } return null; } /// Returns the value of the given header or null if it doesn't exist. pub fn getHeader(self: *Request, name: []const u8) ?[]const u8 { var it = self.raw.iterateHeaders(); while (it.next()) |header| { if (std.ascii.eqlIgnoreCase(header.name, name)) return header.value; } return null; } /// Returns the value of the given cookie or null if it doesn't exist. pub fn getCookie(self: *Request, name: []const u8) ?[]const u8 { const header = self.getHeader("cookie") orelse return null; var it = std.mem.splitSequence(u8, header, "; "); while (it.next()) |part| { const i = std.mem.indexOfScalar(u8, part, '=') orelse continue; const key = part[0..i]; const value = part[i + 1 ..]; if (std.mem.eql(u8, key, name)) return value; } return null; } /// Tries to match the request path against the given pattern and returns /// the parsed parameters. pub fn match(self: *const Request, pattern: []const u8) ?Params { return Params.match(pattern, self.path); } /// Reads the query parameters into a struct. pub fn readQuery(self: *const Request, comptime T: type) !T { var res: T = undefined; inline for (@typeInfo(T).Struct.fields) |f| { if (self.getQueryParam(f.name)) |param| { @field(res, f.name) = try parse(f.type, param); } else if (f.default_value) |ptr| { @field(res, f.name) = @as(*const f.type, @ptrCast(@alignCast(ptr))).*; } else { return error.MissingField; } } return res; } /// Reads the request body as JSON. pub fn readJson(self: *Request, comptime T: type) !T { var reader = std.json.reader(self.allocator, try self.raw.reader()); return std.json.parseFromTokenSourceLeaky( T, self.allocator, &reader, .{ .ignore_unknown_fields = true }, ); } fn parseQueryParams(allocator: std.mem.Allocator, query: []u8) ![]const QueryParam { const res = try allocator.alloc(QueryParam, std.mem.count(u8, query, "&") + 1); var i: usize = 0; for (res) |*p| { const part = query[i .. std.mem.indexOfScalarPos(u8, query, i, '&') orelse query.len]; const eq = std.mem.indexOfScalar(u8, part, '='); p.name = decodeInplace(part[0 .. eq orelse part.len]); p.value = if (eq) |j| decodeInplace(part[j + 1 ..]) else ""; i += part.len; if (i < query.len) i += 1; } return res; } fn decodeInplace(buf: []u8) []u8 { std.mem.replaceScalar(u8, buf, '+', ' '); return std.Uri.percentDecodeInPlace(buf); } }; fn fakeReq(arena: *std.heap.ArenaAllocator, input: []const u8) !Request { const bytes = try arena.allocator().dupe(u8, input); var server: std.http.Server = undefined; server.read_buffer = bytes; return Request.init( arena.allocator(), std.http.Server.Request{ .server = &server, .head = try std.http.Server.Request.Head.parse(bytes), .head_end = bytes.len, .reader_state = undefined, }, ); } test "request parsing" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const req1 = try fakeReq(&arena, "GET /test HTTP/1.0\r\n\r\n"); const req2 = try fakeReq(&arena, "POST /foo%20bar HTTP/1.0\r\n\r\n"); const req3 = try fakeReq(&arena, "PUT /foo%3Abar+baz HTTP/1.0\r\n\r\n"); const req4 = try fakeReq(&arena, "DELETE /test?foo=hello%20world&bar=baz%3Aqux&opt=null HTTP/1.0\r\n\r\n"); try std.testing.expectEqual(std.http.Method.GET, req1.method); try std.testing.expectEqual(std.http.Method.POST, req2.method); try std.testing.expectEqual(std.http.Method.PUT, req3.method); try std.testing.expectEqual(std.http.Method.DELETE, req4.method); try std.testing.expectEqualStrings("/test", req1.path); try std.testing.expectEqualStrings("/foo bar", req2.path); try std.testing.expectEqualStrings("/foo:bar baz", req3.path); try std.testing.expectEqualStrings("/test", req4.path); try std.testing.expectEqualStrings("hello world", req4.getQueryParam("foo").?); try std.testing.expectEqualStrings("baz:qux", req4.getQueryParam("bar").?); try std.testing.expectEqualStrings("null", req4.getQueryParam("opt").?); try std.testing.expectEqual(null, req4.getQueryParam("missing")); } test "req.getHeader()" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); var req = try fakeReq(&arena, "GET /test HTTP/1.0\r\nFoo: bar\r\n\r\n"); try std.testing.expectEqualStrings("bar", req.getHeader("foo").?); try std.testing.expectEqual(null, req.getHeader("missing")); } test "req.getCookie()" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); var req = try fakeReq(&arena, "GET /test HTTP/1.0\r\nCookie: foo=bar; baz=qux\r\n\r\n"); try std.testing.expectEqualStrings("bar", req.getCookie("foo").?); try std.testing.expectEqualStrings("qux", req.getCookie("baz").?); try std.testing.expectEqual(null, req.getCookie("missing")); } test "req.readQuery()" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); var req = try fakeReq(&arena, "GET /test?str=foo&num=123&opt=null HTTP/1.0\r\n\r\n"); const q1 = try req.readQuery(struct { str: []const u8, num: u32, opt: ?u32 }); try std.testing.expectEqualStrings("foo", q1.str); try std.testing.expectEqual(123, q1.num); try std.testing.expectEqual(null, q1.opt); const q2 = try req.readQuery(struct { missing: ?u32 = null, opt: ?u32 }); try std.testing.expectEqual(null, q2.missing); try std.testing.expectEqual(null, q2.opt); const q3 = try req.readQuery(struct { num: u32 = 0, missing: u32 = 123 }); try std.testing.expectEqual(123, q3.num); try std.testing.expectEqual(123, q3.missing); } pub const Params = struct { matches: [16][]const u8 = undefined, len: usize = 0, pub fn match(pattern: []const u8, path: []const u8) ?Params { var res = Params{}; var pattern_parts = std.mem.tokenizeScalar(u8, pattern, '/'); var path_parts = std.mem.tokenizeScalar(u8, path, '/'); while (true) { const pat = pattern_parts.next() orelse return if (pattern[pattern.len - 1] == '*' or path_parts.next() == null) res else null; const pth = path_parts.next() orelse return null; const dynamic = pat[0] == ':' or pat[0] == '*'; if (std.mem.indexOfScalar(u8, pat, '.')) |i| { const j = (if (dynamic) std.mem.lastIndexOfScalar(u8, pth, '.') else std.mem.indexOfScalar(u8, pth, '.')) orelse return null; if (match(pat[i + 1 ..], pth[j + 1 ..])) |ch| { for (ch.matches, res.len..) |s, l| res.matches[l] = s; res.len += ch.len; } else return null; } if (!dynamic and !std.mem.eql(u8, pat, pth)) return null; if (pat[0] == ':') { res.matches[res.len] = pth; res.len += 1; } } } pub fn get(self: *const Params, index: usize, comptime T: type) !T { if (index >= self.len) return error.NoMatch; return parse(T, self.matches[index]); } }; fn parse(comptime T: type, s: []const u8) !T { return switch (@typeInfo(T)) { .Optional => |o| if (std.mem.eql(u8, s, "null")) null else try parse(o.child, s), .Int => std.fmt.parseInt(T, s, 10), .Enum => std.meta.stringToEnum(T, s) orelse error.InvalidEnumTag, else => s, }; } fn expectMatch(pattern: []const u8, path: []const u8, len: usize) !void { if (Params.match(pattern, path)) |m| { try std.testing.expectEqual(m.len, len); } else return error.ExpectedMatch; } test "Params matching" { try expectMatch("/", "/", 0); // TODO: fix this, but we need more tests first // try expectMatch("/*", "/", 0); try expectMatch("/*", "/foo", 0); try expectMatch("/*.js", "/foo.js", 0); try expectMatch("/foo", "/foo", 0); try expectMatch("/:foo", "/foo", 1); try expectMatch("/:foo/bar", "/foo/bar", 1); }
0
repos/tokamak
repos/tokamak/src/mime.zig
const root = @import("root"); const std = @import("std"); // This can be overridden in your root module (with `pub const mime_types = ...;`) // and it doesn't have to be a comptime map either pub const mime_types = if (@hasDecl(root, "mime_types")) root.mime_types else std.ComptimeStringMap([]const u8, .{ .{ ".html", "text/html" }, .{ ".css", "text/css" }, .{ ".png", "image/png" }, .{ ".jpg", "image/jpeg" }, .{ ".jpeg", "image/jpeg" }, .{ ".gif", "image/gif" }, .{ ".svg", "image/svg+xml" }, .{ ".ico", "image/x-icon" }, .{ ".js", "text/javascript" }, .{ ".md", "text/markdown" }, }); /// Get the MIME type for a given file extension. pub fn mime(comptime ext: []const u8) []const u8 { return mime_types.get(ext) orelse "application/octet-stream"; }
0
repos/tokamak
repos/tokamak/src/injector.zig
const std = @import("std"); /// Hierarchical, stack-based dependency injection context implemented as a /// fixed-size array of (TypeId, *anyopaque) pairs. /// /// The stack structure is well-suited for middleware-based applications, as it /// allows for easy addition and removal of dependencies whenever the scope /// starts or ends. /// /// When a dependency is requested, the context is searched from top to bottom. /// If the dependency is not found, the parent context is searched. If the /// dependency is still not found, an error is returned. pub const Injector = struct { registry: std.BoundedArray(struct { TypeId, *anyopaque }, 32) = .{}, parent: ?*const Injector = null, /// Create a new injector from a tuple of pointers. pub fn from(refs: anytype) !Injector { const T = @TypeOf(refs); comptime if (@typeInfo(T) != .Struct or !@typeInfo(T).Struct.is_tuple) { @compileError("Expected tuple of pointers"); }; var res = Injector{}; inline for (std.meta.fields(T)) |f| { try res.push(@field(refs, f.name)); } return res; } /// Create a new injector from a parent context and a tuple of pointers. pub fn fromParent(parent: *const Injector, refs: anytype) !Injector { var res = try Injector.from(refs); res.parent = parent; return res; } /// Add a dependency to the context. pub fn push(self: *Injector, ref: anytype) !void { const T = @TypeOf(ref); comptime if (@typeInfo(T) != .Pointer) { @compileError("Expected a pointer"); }; // This should be safe because we always check TypeId first. try self.registry.append(.{ TypeId.from(T), @constCast(ref) }); } /// Remove the last dependency from the context. pub fn pop(self: *Injector) void { _ = self.registry.pop(); } /// Get a dependency from the context. pub fn get(self: *const Injector, comptime T: type) !T { if (comptime T == *const Injector) return self; if (comptime @typeInfo(T) != .Pointer) { return (try self.get(*const T)).*; } for (self.registry.constSlice()) |node| { if (TypeId.from(T).id == node[0].id) { return @ptrCast(@alignCast(node[1])); } } if (self.parent) |parent| { return parent.get(T); } else { std.log.debug("Missing dependency: {s}", .{@typeName(T)}); return error.MissingDependency; } } /// Call a function with dependencies. The `extra_args` tuple is used to /// pass additional arguments to the function. pub fn call(self: *const Injector, comptime fun: anytype, extra_args: anytype) CallRes(@TypeOf(fun)) { if (@typeInfo(@TypeOf(extra_args)) != .Struct) @compileError("Expected a tuple of arguments"); var args: std.meta.ArgsTuple(@TypeOf(fun)) = undefined; const extra_start = args.len - extra_args.len; inline for (0..extra_start) |i| { args[i] = try self.get(@TypeOf(args[i])); } inline for (extra_start..args.len, 0..) |i, j| { args[i] = extra_args[j]; } return @call(.auto, fun, args); } // TODO: This is a hack which allows embedding ServerOptions in the // configuration file but maybe there's a better way... pub fn jsonParse(_: std.mem.Allocator, _: anytype, _: std.json.ParseOptions) !Injector { return .{}; } }; const TypeId = struct { id: [*:0]const u8, fn from(comptime T: type) TypeId { return .{ .id = @typeName(T) }; } }; fn CallRes(comptime F: type) type { switch (@typeInfo(F)) { .Fn => |f| { const R = f.return_type orelse @compileError("Invalid function"); return switch (@typeInfo(R)) { .ErrorUnion => |e| return anyerror!e.payload, else => anyerror!R, }; }, else => @compileError("Expected a function, got " ++ @typeName(@TypeOf(F))), } }
0
repos/tokamak
repos/tokamak/src/router.zig
const std = @import("std"); const Context = @import("server.zig").Context; const Handler = @import("server.zig").Handler; const chain = @import("middleware.zig").chain; /// Returns GET handler which can be used as middleware. pub fn get(comptime pattern: []const u8, comptime handler: anytype) Handler { return route(.GET, pattern, false, handler); } /// Returns POST handler which can be used as middleware. pub fn post(comptime pattern: []const u8, comptime handler: anytype) Handler { return route(.POST, pattern, true, handler); } /// Like `post` but without a body. pub fn post0(comptime pattern: []const u8, comptime handler: anytype) Handler { return route(.POST, pattern, false, handler); } /// Returns PUT handler which can be used as middleware. pub fn put(comptime pattern: []const u8, comptime handler: anytype) Handler { return route(.PUT, pattern, true, handler); } /// Like `put` but without a body. pub fn put0(comptime pattern: []const u8, comptime handler: anytype) Handler { return route(.PUT, pattern, false, handler); } /// Returns PATCH handler which can be used as middleware. pub fn patch(comptime pattern: []const u8, comptime handler: anytype) Handler { return route(.PATCH, pattern, true, handler); } /// Like `patch` but without a body. pub fn patch0(comptime pattern: []const u8, comptime handler: anytype) Handler { return route(.PATCH, pattern, false, handler); } /// Returns DELETE handler which can be used as middleware. pub fn delete(comptime pattern: []const u8, comptime handler: anytype) Handler { return route(.DELETE, pattern, false, handler); } /// Returns middleware which tries to match any of the provided routes. /// Expects a struct with fn declarations named after the HTTP methods and the /// route pattern. pub fn router(comptime routes: type) Handler { const decls = @typeInfo(routes).Struct.decls; var handlers: [decls.len]Handler = undefined; for (decls, 0..) |d, i| { const j = std.mem.indexOfScalar(u8, d.name, ' ') orelse @compileError("route must contain a space"); var buf: [j]u8 = undefined; const method = std.ascii.lowerString(&buf, d.name[0..j]); handlers[i] = @field(@This(), method)(d.name[j + 1 ..], @field(routes, d.name)); } return chain(handlers); } fn route(comptime method: std.http.Method, comptime pattern: []const u8, comptime has_body: bool, comptime handler: anytype) Handler { const has_query = comptime pattern[pattern.len - 1] == '?'; const n_params = comptime brk: { var n: usize = 0; for (pattern) |c| { if (c == ':') n += 1; } break :brk n; }; const H = struct { fn handleRoute(ctx: *Context) anyerror!void { if (ctx.req.method == method) { if (ctx.req.match(comptime pattern[0 .. pattern.len - @intFromBool(has_query)])) |params| { var args: std.meta.ArgsTuple(@TypeOf(handler)) = undefined; const mid = args.len - n_params - @intFromBool(has_query) - @intFromBool(has_body); inline for (0..mid) |i| { args[i] = try ctx.injector.get(@TypeOf(args[i])); } inline for (0..n_params, mid..) |j, i| { args[i] = try params.get(j, @TypeOf(args[i])); } if (comptime has_query) { args[mid + n_params] = try ctx.req.readQuery(@TypeOf(args[mid + n_params])); } if (comptime has_body) { args[args.len - 1] = try ctx.req.readJson(@TypeOf(args[args.len - 1])); } try ctx.res.send(@call(.auto, handler, args)); return; } } return ctx.next(); } }; return H.handleRoute; }
0
repos/tokamak
repos/tokamak/src/static.zig
const builtin = @import("builtin"); const embed = @import("embed"); const std = @import("std"); const mime = @import("mime.zig").mime; const Context = @import("server.zig").Context; const Handler = @import("server.zig").Handler; const E = std.ComptimeStringMap([]const u8, kvs: { var res: [embed.files.len]struct { []const u8, []const u8 } = undefined; for (embed.files, embed.contents, 0..) |f, c, i| res[i] = .{ f, c }; break :kvs &res; }); // TODO: serveStatic(dir) /// Sends a static resource. pub fn sendStatic(comptime path: []const u8) Handler { const H = struct { pub fn handleStatic(ctx: *Context) anyerror!void { // TODO: charset should only be set for text files. try ctx.res.setHeader("Content-Type", comptime mime(std.fs.path.extension(path)) ++ "; charset=utf-8"); try ctx.res.noCache(); var body = E.get(path); if (body == null or comptime builtin.mode == .Debug) { body = try std.fs.cwd().readFileAlloc(ctx.allocator, path, std.math.maxInt(usize)); } try ctx.res.sendChunk(body.?); } }; return H.handleStatic; }
0
repos
repos/zig-idioms/README.md
# Zig idioms [![](https://github.com/zigcc/zig-idioms/actions/workflows/ci.yml/badge.svg)](https://github.com/zigcc/zig-idioms/actions/workflows/ci.yml) > Zig, despite its simplicity, harbors unique features rarely found in other programming languages. This project aims to collect these techniques, serving as a valuable complement to the [Zig Language Reference](https://ziglang.org/documentation/master). Each idiom is accompanied by an illustrative example named after its corresponding sequence number. These examples can be executed using the command `zig build run-{number}`, or `zig build run-all` to execute all. ## 01. Zig files are structs > Source: https://ziglang.org/documentation/master/#import Zig source files are implicitly structs, with a name equal to the file's basename with the extension truncated. `@import` returns the struct type corresponding to the file. ```zig // Foo.zig pub var a: usize = 1; b: usize, const Self = @This(); pub fn inc(self: *Self) void { self.b += 1; } // main.zig const Foo = @import("Foo.zig"); pub fn main() !void { const foo = Foo{ .b = 100 }; std.debug.print("Type of Foo is {any}, foo is {any}\n", .{ @TypeOf(Foo), @TypeOf(foo), }); foo.inc(); std.debug.print("foo.b = {d}\n", .{foo.b}); } ``` This will output ```text Type of Foo is type, foo is foo foo.b = 101 ``` ## 02. Naming Convention > Source: https://www.openmymind.net/Zig-Quirks/ In general: - Functions are `camelCase` - Types are `PascalCase` - Variables are `lowercase_with_underscores` So we know `file_path` is mostly a variable, and `FilePath` is mostly a type. One exception to those rules is functions that return types. They are `PascalCase`, eg: ```zig pub fn ArrayList(comptime T: type) type { return ArrayListAligned(T, null); } ``` Normally, file names are `lowercase_with_underscore`. However, files that expose a type directly (like our first example), follow the type naming rule. Thus, the file should be named `Foo.zig`, not `foo.zig`. ## 03. Dot Literals In Zig `.{ ... }` is everywhere, it can be used to initialize struct/tuple/enum, depending on its context. ```zig const Rect = struct { w: usize, h: usize, }; const Color = enum { Red, Green, Blue }; fn mySquare(x: usize) usize { return x * x; } pub fn main() !void { const rect: Rect = .{ .w = 1, .h = 2 }; const rect2 = .{ .w = 1, .h = 2 }; std.debug.print("Type of rect is {any}\n", .{@TypeOf(rect)}); std.debug.print("Type of rect2 is {any}\n", .{@TypeOf(rect2)}); const c: Color = .Red; const c2 = .Red; std.debug.print("Type of c is {any}\n", .{@TypeOf(c)}); std.debug.print("Type of c2 is {any}\n", .{@TypeOf(c2)}); // We can use .{ ... } to construct a tuple of tuples // This can be handy when test different inputs of functions. inline for (.{ .{ 1, 1 }, .{ 2, 4 }, .{ 3, 9 }, }) |case| { try std.testing.expectEqual(mySquare(case.@"0"), case.@"1"); } } ``` This will output ```text Type of rect is main.Rect Type of rect2 is struct{comptime w: comptime_int = 1, comptime h: comptime_int = 2} Type of c is main.Color Type of c2 is @TypeOf(.enum_literal) ``` # Other learning materials - [Problems of C, and how Zig addresses them](https://avestura.dev/blog/problems-of-c-and-how-zig-addresses-them)
0
repos/zig-idioms
repos/zig-idioms/examples/build.zig
const std = @import("std"); pub fn build(b: *std.Build) !void { var run_all_step = b.step("run-all", "Run all examples"); inline for (1..4) |num| { // This will padding number like 01, 02, .. 99 const seq = std.fmt.comptimePrint("{d:0>2}", .{num}); const exe = b.addExecutable(.{ .name = "examples-" ++ seq, .root_source_file = .{ .path = "src/" ++ seq ++ ".zig" }, .target = .{}, .optimize = .Debug, }); const run_step = &b.addRunArtifact(exe).step; b.step("run-" ++ seq, "Run example " ++ seq).dependOn(run_step); run_all_step.dependOn(run_step); } }
0
repos/zig-idioms/examples
repos/zig-idioms/examples/src/02.zig
const std = @import("std"); const Rect = struct { w: usize, h: usize, fn init(w: usize, h: usize) Rect { return .{ .w = w, .h = h }; } fn getArea(self: Rect) usize { return self.w * self.h; } }; pub fn main() !void { const rect = Rect.init(1, 2); std.debug.print("Area of rect is {d}\n", .{rect.getArea()}); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); var list = std.ArrayList(Rect).init(allocator); defer list.deinit(); try list.append(rect); std.debug.print("Len of list is {d}\n", .{list.items.len}); }
0
repos/zig-idioms/examples
repos/zig-idioms/examples/src/03.zig
const std = @import("std"); const Rect = struct { w: usize, h: usize, }; const Color = enum { Red, Green, Blue }; fn mySquare(x: usize) usize { return x * x; } pub fn main() !void { const rect: Rect = .{ .w = 1, .h = 2 }; const rect2 = .{ .w = 1, .h = 2 }; std.debug.print("Type of rect is {any}\n", .{@TypeOf(rect)}); std.debug.print("Type of rect2 is {any}\n", .{@TypeOf(rect2)}); // inline for (@typeInfo(@TypeOf(rect)).Struct.fields) |fld| { // std.debug.print("field name:{s}, field:{any}\n", .{ fld.name, fld }); // } // inline for (@typeInfo(@TypeOf(rect2)).Struct.fields) |fld| { // std.debug.print("field name:{s}, field:{any}\n", .{ fld.name, fld }); // } const c: Color = .Red; const c2 = .Red; std.debug.print("Type of c is {any}\n", .{@TypeOf(c)}); std.debug.print("Type of c2 is {any}\n", .{@TypeOf(c2)}); // We can rely on .{ ... } to construct a tuple of tuples // This can be handy when testing different inputs of functions. inline for (.{ .{ 1, 1 }, .{ 2, 4 }, .{ 3, 9 }, }) |case| { try std.testing.expectEqual(mySquare(case.@"0"), case.@"1"); } }
0
repos/zig-idioms/examples
repos/zig-idioms/examples/src/Foo.zig
pub var a: usize = 1; b: usize, const Self = @This(); pub fn inc(self: *Self) void { self.b += 1; }
0
repos/zig-idioms/examples
repos/zig-idioms/examples/src/01.zig
const std = @import("std"); const Foo = @import("Foo.zig"); pub fn main() !void { var foo = Foo{ .b = 100 }; std.debug.print("Type of Foo is {any}, foo is {any}\n", .{ @TypeOf(Foo), @TypeOf(foo), }); foo.inc(); std.debug.print("foo.b = {d}\n", .{foo.b}); }
0
repos
repos/ArrayVec/CODE_OF_CONDUCT.md
# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at . All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq
0
repos
repos/ArrayVec/README.md
# ArrayVec [![License:EUPL](https://img.shields.io/badge/License-MIT-brightgreen.svg)](https://opensource.org/licenses/MIT) ![Zig](https://github.com/DutchGhost/ArrayVec/workflows/Zig/badge.svg?branch=master) A library with an ArrayList-like API, except its a static array
0
repos
repos/ArrayVec/build.zig
const Builder = @import("std").build.Builder; pub fn build(b: *Builder) void { const mode = b.standardReleaseOptions(); const lib = b.addStaticLibrary("ArrayVec", "src/array.zig"); lib.setBuildMode(mode); var main_tests = b.addTest("src/array.zig"); main_tests.setBuildMode(mode); const test_step = b.step("test", "Run library tests"); test_step.dependOn(&main_tests.step); b.default_step.dependOn(&lib.step); b.installArtifact(lib); }
0
repos/ArrayVec
repos/ArrayVec/src/array.zig
pub const ArrayError = error{CapacityError}; pub fn ArrayVec(comptime T: type, comptime SIZE: usize) type { return struct { array: [SIZE]T, length: usize, const Self = @This(); fn set_len(self: *Self, new_len: usize) void { self.length = new_len; } /// Returns a new, empty ArrayVec. pub fn new() Self { return Self{ .array = undefined, .length = @as(usize, 0), }; } /// Returns the length of the ArrayVec pub fn len(self: *const Self) usize { return self.length; } /// Returns the capacity of the ArrayVec pub fn capacity(self: *const Self) usize { return SIZE; } /// Returns a boolean indicating whether /// the ArrayVec is full pub fn isFull(self: *const Self) bool { return self.len() == self.capacity(); } /// Returns a boolean indicating whether /// the ArrayVec is empty pub fn isEmpty(self: *const Self) bool { return self.len() == 0; } /// Returns the remaing capacity of the ArrayVec. /// This is the number of elements remaing untill /// the ArrayVec is full. pub fn remainingCapacity(self: *const Self) usize { return self.capacity() - self.len(); } /// Returns a const slice to the underlying memory pub fn asConstSlice(self: *const Self) []const T { return self.array[0..self.len()]; } /// Returns a (mutable) slice to the underlying /// memory. pub fn asSlice(self: *Self) []T { return self.array[0..self.len()]; } /// Truncates the ArrayVec to the new length. It is /// the programmers responsability to deallocate any /// truncated elements if nessecary. /// Notice that truncate is lazy, and doesn't touch /// any truncated elements. pub fn truncate(self: *Self, new_len: usize) void { if (new_len < self.len()) { self.set_len(new_len); } } /// Clears the entire ArrayVec. It is /// the programmers responsability to deallocate the /// cleared items if nessecary. /// Notice that clear is lazy, and doesn't touch any /// cleared items. pub fn clear(self: *Self) void { self.truncate(0); } pub fn push(self: *Self, element: T) !void { if (self.len() < self.capacity()) { self.push_unchecked(element); } else { return ArrayError.CapacityError; } } pub fn push_unchecked(self: *Self, element: T) void { @setRuntimeSafety(false); const self_len = self.len(); self.array[self_len] = element; self.set_len(self_len + 1); } pub fn pop(self: *Self) ?T { if (!self.isEmpty()) { return self.pop_unchecked(); } else { return null; } } pub fn pop_unchecked(self: *Self) T { @setRuntimeSafety(false); const new_len = self.len() - 1; self.set_len(new_len); return self.array[new_len]; } pub fn extend_from_slice(self: *Self, other: []const T) !void { if (self.remainingCapacity() >= other.len) { self.extend_from_slice_unchecked(other); } else { return ArrayError.CapacityError; } } pub fn extend_from_slice_unchecked(self: *Self, other: []const T) void { @setRuntimeSafety(false); const mem = @import("std").mem; mem.copy(T, self.array[self.length..], other); self.set_len(self.length + other.len); } }; } const testing = if (@import("builtin").is_test) struct { fn expectEqual(x: anytype, y: anytype) void { @import("std").debug.assert(x == y); } } else void; test "test new" { comptime { var array = ArrayVec(i32, 10).new(); } } test "test len, cap, empty" { const CAP: usize = 20; comptime { var array = ArrayVec(i32, CAP).new(); testing.expectEqual(array.isEmpty(), true); testing.expectEqual(array.len(), 0); testing.expectEqual(array.capacity(), CAP); testing.expectEqual(array.remainingCapacity(), CAP); } } test "try push" { const CAP: usize = 10; comptime { var array = ArrayVec(i32, CAP).new(); comptime var i = 0; inline while (i < CAP) { i += 1; try array.push(i); testing.expectEqual(array.len(), i); testing.expectEqual(array.remainingCapacity(), CAP - i); } testing.expectEqual(array.isFull(), true); } } test "try pop" { const CAP: usize = 10; comptime { var array = ArrayVec(i32, CAP).new(); comptime var i = 0; { inline while (i < CAP) { i += 1; try array.push(i); defer if (array.pop()) |elem| testing.expectEqual(elem, i) else @panic("Failed to pop"); } } testing.expectEqual(array.isEmpty(), true); } } test "extend from slice" { const CAP: usize = 10; const SLICE = &[_]i32{ 1, 2, 3, 4, 5, 6 }; comptime { var array = ArrayVec(i32, CAP).new(); try array.extend_from_slice(SLICE); testing.expectEqual(array.len(), SLICE.len); for (array.asConstSlice()) |elem, idx| { testing.expectEqual(elem, SLICE[idx]); } } }
0
repos
repos/zig-overlay/shell.nix
(import ( let flake-compat = (builtins.fromJSON (builtins.readFile ./flake.lock)).nodes.flake-compat; in fetchTarball { url = "https://github.com/edolstra/flake-compat/archive/${flake-compat.locked.rev}.tar.gz"; sha256 = flake-compat.locked.narHash; } ) {src = ./.;}) .shellNix
0
repos
repos/zig-overlay/default.nix
{ pkgs ? import <nixpkgs> {}, system ? builtins.currentSystem, }: let inherit (pkgs) lib; sources = builtins.fromJSON (lib.strings.fileContents ./sources.json); # mkBinaryInstall makes a derivation that installs Zig from a binary. mkBinaryInstall = { url, version, sha256, }: pkgs.stdenv.mkDerivation { inherit version; pname = "zig"; src = pkgs.fetchurl {inherit url sha256;}; dontConfigure = true; dontBuild = true; dontFixup = true; installPhase = '' mkdir -p $out/{doc,bin,lib} [ -d docs ] && cp -r docs/* $out/doc [ -d doc ] && cp -r doc/* $out/doc cp -r lib/* $out/lib cp zig $out/bin/zig ''; }; # The packages that are tagged releases taggedPackages = lib.attrsets.mapAttrs (k: v: mkBinaryInstall {inherit (v.${system}) version url sha256;}) (lib.attrsets.filterAttrs (k: v: (builtins.hasAttr system v) && (v.${system}.url != null) && (v.${system}.sha256 != null)) (builtins.removeAttrs sources ["master"])); # The master packages masterPackages = lib.attrsets.mapAttrs' ( k: v: lib.attrsets.nameValuePair ( if k == "latest" then "master" else ("master-" + k) ) (mkBinaryInstall {inherit (v.${system}) version url sha256;}) ) (lib.attrsets.filterAttrs (k: v: (builtins.hasAttr system v) && (v.${system}.url != null)) sources.master); # This determines the latest /released/ version. latest = lib.lists.last ( builtins.sort (x: y: (builtins.compareVersions x y) < 0) (builtins.attrNames taggedPackages) ); in # We want the packages but also add a "default" that just points to the # latest released version. taggedPackages // masterPackages // {"default" = taggedPackages.${latest};}

Zig LLama

This dataset is used to fine-tune meta-llama/Meta-Llama-3.1-8B-Instruct.

Dataset Details

The dataset uses ~1100 of the most popular and recently updated Zig repos on GitHub.

Dataset Sources

The full list of source repos used.

The folder of source repos used.

Downloads last month
73