fediglam/src/util/lib.zig

66 lines
1.8 KiB
Zig
Raw Normal View History

2022-07-30 05:46:00 +00:00
const std = @import("std");
2022-06-09 05:54:41 +00:00
pub const ciutf8 = @import("./ciutf8.zig");
pub const Uuid = @import("./Uuid.zig");
2022-07-18 07:03:29 +00:00
pub const DateTime = @import("./DateTime.zig");
2022-06-02 18:33:16 +00:00
pub const PathIter = @import("./PathIter.zig");
2022-06-09 05:54:41 +00:00
2022-07-30 05:46:00 +00:00
pub const case = struct {
// returns the number of capital letters in a string.
// only works with ascii characters
fn countCaps(str: []const u8) usize {
var count: usize = 0;
for (str) |ch| {
if (std.ascii.isUpper(ch)) {
count += 1;
}
}
return count;
}
// converts a string from PascalCase to snake_case at comptime.
// only works with ascii characters
2022-07-30 20:40:20 +00:00
pub fn pascalToSnake(comptime str: []const u8) Return: {
2022-07-30 05:46:00 +00:00
break :Return if (str.len == 0)
*const [0:0]u8
else
*const [str.len + countCaps(str) - 1:0]u8;
} {
comptime {
if (str.len == 0) return "";
var buf = std.mem.zeroes([str.len + countCaps(str) - 1:0]u8);
var i = 0;
for (str) |ch| {
if (std.ascii.isUpper(ch)) {
if (i != 0) {
buf[i] = '_';
i += 1;
}
buf[i] = std.ascii.toLower(ch);
} else {
buf[i] = ch;
}
i += 1;
}
return &buf;
}
}
};
test "pascalToSnake" {
2022-07-30 20:40:20 +00:00
try std.testing.expectEqual("", case.pascalToSnake(""));
try std.testing.expectEqual("abc", case.pascalToSnake("Abc"));
try std.testing.expectEqual("a_bc", case.pascalToSnake("ABc"));
try std.testing.expectEqual("a_b_c", case.pascalToSnake("ABC"));
try std.testing.expectEqual("ab_c", case.pascalToSnake("AbC"));
2022-07-30 05:46:00 +00:00
}
2022-06-09 05:54:41 +00:00
test {
_ = ciutf8;
_ = Uuid;
2022-06-02 18:33:16 +00:00
_ = PathIter;
2022-07-18 07:03:29 +00:00
_ = DateTime;
2022-06-09 05:54:41 +00:00
}