25 lines
761 B
Zig
25 lines
761 B
Zig
const std = @import("std");
|
|
|
|
/// Convert a string to lowercase using a pre-allocated buffer.
|
|
/// Returns null if the buffer is too small.
|
|
pub fn toLower(s: []const u8, buf: []u8) ?[]const u8 {
|
|
if (s.len > buf.len) return null;
|
|
for (s, 0..) |c, i| {
|
|
buf[i] = std.ascii.toLower(c);
|
|
}
|
|
return buf[0..s.len];
|
|
}
|
|
|
|
test "toLower" {
|
|
const testing = std.testing;
|
|
var buf: [64]u8 = undefined;
|
|
|
|
try testing.expectEqualStrings("hello", toLower("HELLO", &buf).?);
|
|
try testing.expectEqualStrings("hello", toLower("hello", &buf).?);
|
|
try testing.expectEqualStrings("hello123", toLower("HeLLo123", &buf).?);
|
|
|
|
// Buffer too small
|
|
var small_buf: [2]u8 = undefined;
|
|
try testing.expect(toLower("hello", &small_buf) == null);
|
|
}
|