fediglam/src/util/PathIter.zig
2022-06-02 11:33:16 -07:00

68 lines
1.7 KiB
Zig

const Self = @This();
const std = @import("std");
is_first: bool,
path: []const u8,
pub fn from(path: []const u8) Self {
return .{ .path = path, .is_first = true };
}
pub fn next(self: *Self) ?[]const u8 {
if (self.path.len == 0) {
if (self.is_first) {
self.is_first = false;
return self.path;
} else {
return null;
}
}
var start: usize = 0;
var end: usize = start;
while (end < self.path.len) : (end += 1) {
// skip leading slash
if (end == start and self.path[start] == '/') {
start += 1;
continue;
} else if (self.path[end] == '/') {
break;
}
}
if (start == end) {
self.path = self.path[end..end];
self.is_first = false;
return null;
}
const result = self.path[start..end];
self.path = self.path[end..];
self.is_first = false;
return result;
}
test "PathIter /ab/cd/" {
const path = "/ab/cd/";
var it = from(path);
try std.testing.expectEqualStrings("ab", it.next().?);
try std.testing.expectEqualStrings("cd", it.next().?);
try std.testing.expectEqual(@as(?[]const u8, null), it.next());
}
test "PathIter ''" {
const path = "";
var it = from(path);
try std.testing.expectEqualStrings("", it.next().?);
try std.testing.expectEqual(@as(?[]const u8, null), it.next());
}
test "PathIter ab/c//defg/" {
const path = "ab/c//defg/";
var it = from(path);
try std.testing.expectEqualStrings("ab", it.next().?);
try std.testing.expectEqualStrings("c", it.next().?);
try std.testing.expectEqualStrings("defg", it.next().?);
try std.testing.expectEqual(@as(?[]const u8, null), it.next());
}