Skip to content

Instantly share code, notes, and snippets.

@txdv
Forked from IridescentRose/uuid.zig
Last active March 12, 2021 08:58
Show Gist options
  • Save txdv/f638fbfc5e39f42ba6a6b7b8a772bec3 to your computer and use it in GitHub Desktop.
Save txdv/f638fbfc5e39f42ba6a6b7b8a772bec3 to your computer and use it in GitHub Desktop.
A simple UUID v4 Generator
const std = @import("std");
const stdout = std.io.getStdOut().writer();
pub fn hasArguments() !bool {
var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};
const gpa = &general_purpose_allocator.allocator;
const args = try std.process.argsAlloc(gpa);
defer std.process.argsFree(gpa, args);
return args.len > 1;
}
const UUID = struct {
uuid: [16]u8 = [16]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
pub fn new() UUID {
var u = UUID{};
std.crypto.random.bytes(u.uuid[0..]);
u.uuid[6] = (u.uuid[6] & 0b00001111) | 0b01000000;
return u;
}
const zero = UUID{};
pub fn str(u: UUID, buf: *[36] u8) void {
const charset = "0123456789abcdef";
var j: u8 = 0;
for (u.uuid) |c, i| {
if (i == 4 or i == 6 or i == 8 or i == 10) {
buf[j] = '-';
j += 1;
}
buf[j] = charset[c >> 4];
buf[j + 1] = charset[c & 15];
j += 2;
}
}
pub fn newstr(u: UUID) [36]u8 {
var buf: [36]u8 = undefined;
u.str(&buf);
return buf;
}
};
pub fn main() !void {
var args = try hasArguments();
const u = if (args) UUID.zero else UUID.new();
_ = try stdout.write(u.newstr()[0..]);
}
uuid: main.zig
zig build-exe --strip --single-threaded main.zig
mv main uuid
run: uuid
./uuid
const std = @import("std");
const chars: []const u8 = "0123456789ABCDEF";
pub const UUID = struct {
const Self = @This();
id: [36]u8,
pub fn new(seed: u64) !*Self {
var r = std.rand.DefaultPrng.init(seed);
var uu = try std.heap.page_allocator.create(Self);
var i: usize = 0;
while (i < 36) : (i += 1) {
uu.id[i] = '0';
}
uu.id[8] = '-';
uu.id[13] = '-';
uu.id[14] = '4';
uu.id[18] = '-';
uu.id[23] = '-';
i = 0;
while (i < 36) : (i += 1) {
if (i != 8 and i != 13 and i != 14 and i != 18 and i != 23) {
var res: u8 = r.random.uintLessThanBiased(u8, 16);
uu.id[i] = chars[res];
}
}
return uu;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment