Commit Diff


commit - /dev/null
commit + eaa5129ccbc84abcbd970519518d6de5677b1b3b
blob - /dev/null
blob + a600a9a34dd4c4d24fc1bfca17733f083e085f87 (mode 644)
--- /dev/null
+++ .gitignore
@@ -0,0 +1,24 @@
+# This file is for zig-specific build artifacts.
+# If you have OS-specific or editor-specific files to ignore,
+# such as *.swp or .DS_Store, put those in your global
+# ~/.gitignore and put this in your ~/.gitconfig:
+#
+# [core]
+#     excludesfile = ~/.gitignore
+#
+# Cheers!
+# -andrewrk
+
+.zig-cache/
+zig-out/
+/release/
+/debug/
+/build/
+/build-*/
+/docgen_tmp/
+
+# Although this was renamed to .zig-cache, let's leave it here for a few
+# releases to make it less annoying to work with multiple branches.
+zig-cache/
+
+.idea/
\ No newline at end of file
blob - /dev/null
blob + 53ad1ff991c2e8fb4938df150d5eb715e987b3bc (mode 644)
--- /dev/null
+++ build.zig
@@ -0,0 +1,52 @@
+const std = @import("std");
+
+// Although this function looks imperative, note that its job is to
+// declaratively construct a build graph that will be executed by an external
+// runner.
+pub fn build(b: *std.Build) void {
+    // Standard target options allows the person running `zig build` to choose
+    // what target to build for. Here we do not override the defaults, which
+    // means any target is allowed, and the default is native. Other options
+    // for restricting supported target set are available.
+    const target = b.standardTargetOptions(.{});
+
+    // Standard optimization options allow the person running `zig build` to select
+    // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not
+    // set a preferred release mode, allowing the user to decide how to optimize.
+    const optimize = b.standardOptimizeOption(.{});
+
+    const exe = b.addExecutable(.{
+        .name = "baze64",
+        .root_source_file = b.path("src/main.zig"),
+        .target = target,
+        .optimize = optimize,
+    });
+
+    // This declares intent for the executable to be installed into the
+    // standard location when the user invokes the "install" step (the default
+    // step when running `zig build`).
+    b.installArtifact(exe);
+
+    // This *creates* a Run step in the build graph, to be executed when another
+    // step is evaluated that depends on it. The next line below will establish
+    // such a dependency.
+    const run_cmd = b.addRunArtifact(exe);
+
+    // By making the run step depend on the install step, it will be run from the
+    // installation directory rather than directly from within the cache directory.
+    // This is not necessary, however, if the application depends on other installed
+    // files, this ensures they will be present and in the expected location.
+    run_cmd.step.dependOn(b.getInstallStep());
+
+    // This allows the user to pass arguments to the application in the build
+    // command itself, like this: `zig build run -- arg1 arg2 etc`
+    if (b.args) |args| {
+        run_cmd.addArgs(args);
+    }
+
+    // This creates a build step. It will be visible in the `zig build --help` menu,
+    // and can be selected like this: `zig build run`
+    // This will evaluate the `run` step rather than the default, which is "install".
+    const run_step = b.step("run", "Run the app");
+    run_step.dependOn(&run_cmd.step);
+}
blob - /dev/null
blob + 7bd4fc43438aed9f4d2846ca947eb6952e02e12a (mode 644)
--- /dev/null
+++ build.zig.zon
@@ -0,0 +1,72 @@
+.{
+    // This is the default name used by packages depending on this one. For
+    // example, when a user runs `zig fetch --save <url>`, this field is used
+    // as the key in the `dependencies` table. Although the user can choose a
+    // different name, most users will stick with this provided value.
+    //
+    // It is redundant to include "zig" in this name because it is already
+    // within the Zig package namespace.
+    .name = "baze64",
+
+    // This is a [Semantic Version](https://semver.org/).
+    // In a future version of Zig it will be used for package deduplication.
+    .version = "0.0.0",
+
+    // This field is optional.
+    // This is currently advisory only; Zig does not yet do anything
+    // with this value.
+    //.minimum_zig_version = "0.11.0",
+
+    // This field is optional.
+    // Each dependency must either provide a `url` and `hash`, or a `path`.
+    // `zig build --fetch` can be used to fetch all dependencies of a package, recursively.
+    // Once all dependencies are fetched, `zig build` no longer requires
+    // internet connectivity.
+    .dependencies = .{
+        // See `zig fetch --save <url>` for a command-line interface for adding dependencies.
+        //.example = .{
+        //    // When updating this field to a new URL, be sure to delete the corresponding
+        //    // `hash`, otherwise you are communicating that you expect to find the old hash at
+        //    // the new URL.
+        //    .url = "https://example.com/foo.tar.gz",
+        //
+        //    // This is computed from the file contents of the directory of files that is
+        //    // obtained after fetching `url` and applying the inclusion rules given by
+        //    // `paths`.
+        //    //
+        //    // This field is the source of truth; packages do not come from a `url`; they
+        //    // come from a `hash`. `url` is just one of many possible mirrors for how to
+        //    // obtain a package matching this `hash`.
+        //    //
+        //    // Uses the [multihash](https://multiformats.io/multihash/) format.
+        //    .hash = "...",
+        //
+        //    // When this is provided, the package is found in a directory relative to the
+        //    // build root. In this case the package's hash is irrelevant and therefore not
+        //    // computed. This field and `url` are mutually exclusive.
+        //    .path = "foo",
+        //
+        //    // When this is set to `true`, a package is declared to be lazily
+        //    // fetched. This makes the dependency only get fetched if it is
+        //    // actually used.
+        //    .lazy = false,
+        //},
+    },
+
+    // Specifies the set of files and directories that are included in this package.
+    // Only files and directories listed here are included in the `hash` that
+    // is computed for this package. Only files listed here will remain on disk
+    // when using the zig package manager. As a rule of thumb, one should list
+    // files required for compilation plus any license(s).
+    // Paths are relative to the build root. Use the empty string (`""`) to refer to
+    // the build root itself.
+    // A directory listed here means that all files within, recursively, are included.
+    .paths = .{
+        "build.zig",
+        "build.zig.zon",
+        "src",
+        // For example...
+        //"LICENSE",
+        //"README.md",
+    },
+}
blob - /dev/null
blob + 012f15012880a9e81f3aac78532b418bb34fd318 (mode 644)
--- /dev/null
+++ src/base64.zig
@@ -0,0 +1,178 @@
+const std = @import("std");
+const stdout = std.io.getStdOut().writer();
+
+pub const err = error{
+    IndexNotFound,
+};
+
+pub const Base64 = struct {
+    table: *const [64]u8,
+
+    pub const init: Base64 = .{
+        .table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
+    };
+
+    fn char_at(self: Base64, index: u8) u8 {
+        return self.table[index];
+    }
+
+    pub fn encode(self: Base64, allocator: std.mem.Allocator, input: []const u8) ![]u8 {
+        if (input.len == 0) {
+            return "";
+        }
+
+        const encode_length = try calc_encode_length(input);
+        var out = try allocator.alloc(u8, encode_length);
+        var buf = [3]u8{0, 0, 0};
+        var count: u16 = 0;
+        var outc: u16 = 0;
+
+        for (input) |b| {
+            buf[count] = b;
+            count += 1;
+            if (count == 3) {
+                out[outc] = self.char_at(buf[0] >> 2);
+                out[outc + 1] = self.char_at(((buf[0] & 0x03) << 4) + (buf[1] >> 4));
+                out[outc + 2] = self.char_at(((buf[1] & 0x0F) << 2) + (buf[2] >> 6));
+                out[outc + 3] = self.char_at(buf[2] & 0x3F);
+                count = 0;
+                outc += 4;
+            }
+        }
+
+        if (count == 2) {
+            out[outc] = self.char_at(buf[0] >> 2);
+            out[outc + 1] = self.char_at((buf[0] & 0x03) << 4) + (buf[1] >> 4);
+            out[outc + 2] = self.char_at((buf[1] & 0x0F) << 2);
+            out[outc + 3] = '=';
+        } else if (count == 1) {
+            out[outc] = self.char_at(buf[0] >> 2);
+            out[outc + 1] = self.char_at((buf[0] & 0x03) << 4);
+            out[outc + 2] = '=';
+            out[outc + 3] = '=';
+        }
+
+        return out;
+    }
+
+    fn decode_index(self: Base64, char: u8) err!u8 {
+        if (char == '=') {
+            return 64;
+        }
+        if (char >= 'A' and char <= 'Z') {
+            return char - 'A';
+        } else if (char >= 'a' and char <= 'z') {
+            return char - 'a' + 26;
+        } else {
+            for (52..64) |i| {
+                const idx: u8 = @intCast(i);
+                if (self.char_at(idx) == char) {
+                    return idx;
+                }
+            }
+        }
+        return err.IndexNotFound;
+    }
+
+    pub fn decode(self: Base64, allocator: std.mem.Allocator, input: []const u8) ![]u8 {
+        if (input.len == 0) {
+            return "";
+        }
+
+        const output_sz = try calc_decode_length(input);
+        var output = try allocator.alloc(u8, output_sz);
+        var count: u8 = 0;
+        var iout: u64 = 0;
+        var buf = [4]u8{ 0, 0, 0, 0 };
+
+        for (0..input.len) |i| {
+            buf[count] = try self.decode_index(input[i]);
+            count += 1;
+            if (count == 4) {
+                output[iout] = (buf[0] << 2) + (buf[1] >> 4);
+                if (buf[2] != 64) {
+                    output[iout + 1] = (buf[1] << 4) + (buf[2] >> 2);
+                }
+                if (buf[3] != 64) {
+                    output[iout + 2] = (buf[2] << 6) + buf[3];
+                }
+                iout += 3;
+                count = 0;
+            }
+        }
+
+        return output;
+    }
+};
+
+fn calc_encode_length(input: []const u8) !usize {
+    if (input.len < 3) {
+        return 4;
+    }
+    const n_output: usize = try std.math.divCeil(usize, input.len, 3);
+    return n_output * 4;
+}
+
+fn calc_decode_length(input: []const u8) !usize {
+    if (input.len < 4) {
+        return 3;
+    }
+    const n_output: usize = try std.math.divFloor(usize, input.len, 4);
+    return n_output * 3;
+}
+
+test "encode hello" {
+    var b = Base64.init;
+    var gpa = std.heap.GeneralPurposeAllocator(.{}).init;
+    const allocator = gpa.allocator();
+
+    const encoded = try b.encode(allocator, "hello");
+    try std.testing.expect(std.mem.eql(u8, encoded, "aGVsbG8="));
+}
+
+test "encode long" {
+    var b = Base64.init;
+    var gpa = std.heap.GeneralPurposeAllocator(.{}).init;
+    const allocator = gpa.allocator();
+
+    const encoded = try b.encode(allocator, "Hey, it's me. I'm the problem. It's me");
+    try std.testing.expect(std.mem.eql(u8, encoded, "SGV5LCBpdCdzIG1lLiBJJ20gdGhlIHByb2JsZW0uIEl0J3MgbWU="));
+}
+
+test "decode hello" {
+    var b = Base64.init;
+    var gpa = std.heap.GeneralPurposeAllocator(.{}).init;
+    const allocator = gpa.allocator();
+
+    const encoded = try b.decode(allocator, "aGVsbG8=");
+    try stdout.print("{s}\n", .{encoded});
+    try std.testing.expect(std.mem.eql(u8, encoded, "hello"));
+}
+
+test "decode long" {
+    var b = Base64.init;
+    var gpa = std.heap.GeneralPurposeAllocator(.{}).init;
+    const allocator = gpa.allocator();
+
+    const encoded = try b.decode(allocator, "SGV5LCBpdCdzIG1lLiBJJ20gdGhlIHByb2JsZW0uIEl0J3MgbWU=");
+    try stdout.print("{s}\n", .{encoded});
+    try std.testing.expect(std.mem.eql(u8, encoded, "Hey, it's me. I'm the problem. It's me"));
+}
+
+test "decode_index" {
+    var b = Base64.init;
+
+    try std.testing.expectError(err.IndexNotFound, b.decode_index('{'));
+
+    var r :u8 = 0;
+    r = try b.decode_index('A');
+    try std.testing.expect(r == 0);
+    r = try b.decode_index('a');
+    try std.testing.expect(r == 26);
+    r = try b.decode_index('0');
+    try std.testing.expect(r == 52);
+    r = try b.decode_index('/');
+    try std.testing.expect(r == 63);
+    r = try b.decode_index('=');
+    try std.testing.expect(r == 64);
+}
blob - /dev/null
blob + 56015e8a737a28061417174c3b491cda98bf5ab1 (mode 644)
--- /dev/null
+++ src/main.zig
@@ -0,0 +1,37 @@
+const std = @import("std");
+const stdout = std.io.getStdOut().writer();
+
+const b64 = @import("base64.zig");
+
+const usageText =
+    \\Usage: baze64 {-d/-D} input
+    \\Args:
+    \\  -d -D: decode instead of encode
+    ;
+
+
+pub fn main() !void {
+    var gpa = std.heap.GeneralPurposeAllocator(.{}).init;
+    const allocator = gpa.allocator();
+    var args = try std.process.argsWithAllocator(allocator);
+    defer args.deinit();
+
+    var b = b64.Base64.init;
+
+    // Skip arg[0]
+    _ = args.skip();
+
+    var a = args.next();
+    if (a) |arg| {
+        if (std.mem.eql(u8, arg, "-d") or std.mem.eql(u8, arg, "-D")) {
+            a = args.next();
+            const decoded = try b.decode(allocator, arg);
+            try stdout.print("{s}", .{decoded});
+        } else {
+            const encoded = try b.decode(allocator, arg);
+            try stdout.print("{s}", .{encoded});
+        }
+    } else {
+        try stdout.print("{s}", .{usageText});
+    }
+}