Add PathIter

This commit is contained in:
jaina heartles 2022-06-02 11:33:16 -07:00
parent 48c12f2e8c
commit 7411f5f9b8
2 changed files with 70 additions and 0 deletions

68
src/util/PathIter.zig Normal file
View file

@ -0,0 +1,68 @@
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());
}

View file

@ -1,7 +1,9 @@
pub const ciutf8 = @import("./ciutf8.zig");
pub const Uuid = @import("./Uuid.zig");
pub const PathIter = @import("./PathIter.zig");
test {
_ = ciutf8;
_ = Uuid;
_ = PathIter;
}