| 1 | //! https://www.crockford.com/base32.html |
| 2 | |
| 3 | const std = @import("std"); |
| 4 | const string = []const u8; |
| 5 | |
| 6 | const alphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; |
| 7 | |
| 8 | pub fn decode(alloc: std.mem.Allocator, input: string) ![]const u5 { |
| 9 | var list = std.array_list.Managed(u5).init(alloc); |
| 10 | errdefer list.deinit(); |
| 11 | |
| 12 | for (input) |c| { |
| 13 | for (alphabet, 0..) |d, i| { |
| 14 | if (c == d) { |
| 15 | try list.append(@intCast(i)); |
| 16 | } |
| 17 | } |
| 18 | } |
| 19 | return list.toOwnedSlice(); |
| 20 | } |
| 21 | |
| 22 | pub fn formatInt(comptime T: type, n: T, buf: []u8) void { |
| 23 | const l: T = @intCast(alphabet.len); |
| 24 | var x = n; |
| 25 | var i = buf.len; |
| 26 | for (0..i) |j| { |
| 27 | buf[j] = alphabet[0]; |
| 28 | } |
| 29 | while (true) { |
| 30 | const a: usize = @intCast(x % l); |
| 31 | x = x / l; |
| 32 | buf[i - 1] = alphabet[a]; |
| 33 | i -= 1; |
| 34 | if (x == 0) break; |
| 35 | } |
| 36 | } |