From f042ca64b5dd3516f34ee1cf2d2c01ff3f3a73b8 Mon Sep 17 00:00:00 2001 From: Thomas Lindner Date: Sun, 6 Feb 2022 16:15:18 +0100 Subject: [PATCH] solve Challenge 1 of Set 1 --- .gitignore | 4 ++++ set1/challenge1_hex2base64/build.zig | 27 +++++++++++++++++++++++++ set1/challenge1_hex2base64/src/main.zig | 27 +++++++++++++++++++++++++ 3 files changed, 58 insertions(+) create mode 100644 .gitignore create mode 100644 set1/challenge1_hex2base64/build.zig create mode 100644 set1/challenge1_hex2base64/src/main.zig diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..42328ee --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.*.swp + +*/*/zig-cache +*/*/zig-out diff --git a/set1/challenge1_hex2base64/build.zig b/set1/challenge1_hex2base64/build.zig new file mode 100644 index 0000000..0675f53 --- /dev/null +++ b/set1/challenge1_hex2base64/build.zig @@ -0,0 +1,27 @@ +const std = @import("std"); + +pub fn build(b: *std.build.Builder) void { + // Standard target options allows the person running `zig build` to choose + // what target to build for. Here we do not override the defaults, which + // means any target is allowed, and the default is native. Other options + // for restricting supported target set are available. + const target = b.standardTargetOptions(.{}); + + // Standard release options allow the person running `zig build` to select + // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. + const mode = b.standardReleaseOptions(); + + const exe = b.addExecutable("challenge1_hex2base64", "src/main.zig"); + exe.setTarget(target); + exe.setBuildMode(mode); + exe.install(); + + const run_cmd = exe.run(); + run_cmd.step.dependOn(b.getInstallStep()); + if (b.args) |args| { + run_cmd.addArgs(args); + } + + const run_step = b.step("run", "Run the app"); + run_step.dependOn(&run_cmd.step); +} diff --git a/set1/challenge1_hex2base64/src/main.zig b/set1/challenge1_hex2base64/src/main.zig new file mode 100644 index 0000000..d9871a6 --- /dev/null +++ b/set1/challenge1_hex2base64/src/main.zig @@ -0,0 +1,27 @@ +const std = @import("std"); + +pub fn main() anyerror!void { + const stdin = std.io.bufferedReader(std.io.getStdIn().reader()).reader(); + const stdout = std.io.getStdOut().writer(); + + var inputbuffer = std.mem.zeroes([1024]u8); + var rawbuffer = std.mem.zeroes([512]u8); + var outputbuffer = std.mem.zeroes([1024]u8); + + while (true) { + const line = stdin.readUntilDelimiterOrEof(inputbuffer[0..], '\n') catch |err| { + std.log.err("input failed: {s}\n", .{err}); + return; + }; + const hex = line orelse return; + const raw = std.fmt.hexToBytes(rawbuffer[0..], hex) catch { + std.log.err("not a valid hexadecimal\n", .{}); + continue; + }; + const base64 = std.base64.standard.Encoder.encode(outputbuffer[0..], raw); + stdout.print("{s}\n", .{base64}) catch |err| { + std.log.err("output failed: {s}\n", .{err}); + return; + }; + } +}