From 7411f5f9b86a3ab7422bc2e378553ba186f30119 Mon Sep 17 00:00:00 2001 From: jaina heartles Date: Thu, 2 Jun 2022 11:33:16 -0700 Subject: [PATCH] Add PathIter --- src/util/PathIter.zig | 68 +++++++++++++++++++++++++++++++++++++++++++ src/util/lib.zig | 2 ++ 2 files changed, 70 insertions(+) create mode 100644 src/util/PathIter.zig diff --git a/src/util/PathIter.zig b/src/util/PathIter.zig new file mode 100644 index 0000000..802300f --- /dev/null +++ b/src/util/PathIter.zig @@ -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()); +} diff --git a/src/util/lib.zig b/src/util/lib.zig index 4a7e3df..a6a98b5 100644 --- a/src/util/lib.zig +++ b/src/util/lib.zig @@ -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; }