|
| 1 | +const std = @import("std"); |
| 2 | +const Allocator = std.mem.Allocator; |
| 3 | +const testing = std.testing; |
| 4 | + |
| 5 | +pub const CidVersion = enum(u64) { |
| 6 | + V0 = 0, |
| 7 | + V1 = 1, |
| 8 | +}; |
| 9 | + |
| 10 | +pub const Codec = enum(u64) { |
| 11 | + Raw = 0x55, |
| 12 | + DagPb = 0x70, |
| 13 | + DagCbor = 0x71, |
| 14 | +}; |
| 15 | + |
| 16 | +pub const Cid = struct { |
| 17 | + version: CidVersion, |
| 18 | + codec: Codec, |
| 19 | + hash: []const u8, |
| 20 | + allocator: Allocator, |
| 21 | + |
| 22 | + pub fn init(allocator: Allocator, version: CidVersion, codec: Codec, hash: []const u8) !Cid { |
| 23 | + const hash_copy = try allocator.dupe(u8, hash); |
| 24 | + return Cid{ |
| 25 | + .version = version, |
| 26 | + .codec = codec, |
| 27 | + .hash = hash_copy, |
| 28 | + .allocator = allocator, |
| 29 | + }; |
| 30 | + } |
| 31 | + |
| 32 | + pub fn deinit(self: *Cid) void { |
| 33 | + self.allocator.free(self.hash); |
| 34 | + } |
| 35 | + |
| 36 | + pub fn format(self: Cid, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { |
| 37 | + _ = fmt; |
| 38 | + _ = options; |
| 39 | + |
| 40 | + switch (self.version) { |
| 41 | + .V0 => { |
| 42 | + if (self.codec != .DagPb) { |
| 43 | + return error.InvalidV0Codec; |
| 44 | + } |
| 45 | + try writer.writeAll(try std.fmt.allocPrint(self.allocator, "Qm{}", .{std.fmt.fmtSliceHexLower(self.hash)})); |
| 46 | + }, |
| 47 | + .V1 => { |
| 48 | + try writer.writeAll(try std.fmt.allocPrint( |
| 49 | + self.allocator, |
| 50 | + "b{}{}{}", |
| 51 | + .{ |
| 52 | + @intFromEnum(self.version), |
| 53 | + @intFromEnum(self.codec), |
| 54 | + std.fmt.fmtSliceHexLower(self.hash), |
| 55 | + }, |
| 56 | + )); |
| 57 | + }, |
| 58 | + } |
| 59 | + } |
| 60 | +}; |
| 61 | + |
| 62 | +test "CID v0" { |
| 63 | + const allocator = testing.allocator; |
| 64 | + |
| 65 | + var hash = [_]u8{ 1, 2, 3, 4, 5 }; |
| 66 | + var cid = try Cid.init(allocator, .V0, .DagPb, &hash); |
| 67 | + defer cid.deinit(); |
| 68 | + |
| 69 | + try testing.expect(cid.version == .V0); |
| 70 | + try testing.expect(cid.codec == .DagPb); |
| 71 | + try testing.expectEqualSlices(u8, &hash, cid.hash); |
| 72 | +} |
| 73 | + |
| 74 | +test "CID v1" { |
| 75 | + const allocator = testing.allocator; |
| 76 | + |
| 77 | + var hash = [_]u8{ 1, 2, 3, 4, 5 }; |
| 78 | + var cid = try Cid.init(allocator, .V1, .DagCbor, &hash); |
| 79 | + defer cid.deinit(); |
| 80 | + |
| 81 | + try testing.expect(cid.version == .V1); |
| 82 | + try testing.expect(cid.codec == .DagCbor); |
| 83 | + try testing.expectEqualSlices(u8, &hash, cid.hash); |
| 84 | +} |
0 commit comments