Skip to content

Commit

Permalink
Merge pull request #4 from JakubSzark/experimental
Browse files Browse the repository at this point in the history
Added StringIterator
  • Loading branch information
JakubSzark authored Sep 17, 2020
2 parents eb67468 + affc93d commit 1f60935
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
12 changes: 12 additions & 0 deletions zig-string-tests.zig
Original file line number Diff line number Diff line change
Expand Up @@ -165,4 +165,16 @@ test "String Tests" {
const mySlice = try myStr.toOwned();
assert(eql(u8, mySlice.?, "This is a Test!"));
arena.allocator.free(mySlice.?);

// StringIterator
var i: usize = 0;
var iter = myStr.iterator();
while (iter.next()) |ch| {
if (i == 0) {
assert(eql(u8, "T", ch));
}
i += 1;
}

assert(i == myStr.len());
}
26 changes: 26 additions & 0 deletions zig-string.zig
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,32 @@ pub const String = struct {
return m.len;
}
};

// Iterator support
pub usingnamespace struct {
pub const StringIterator = struct {
string: *String,
index: usize,

pub fn next(it: *StringIterator) ?[]const u8 {
if (it.string.buffer) |buffer| {
if (it.index == it.string.size) return null;
var i = it.index;
it.index += Utility.getUTF8Size(buffer[i]);
return buffer[i..it.index];
} else {
return null;
}
}
};

pub fn iterator(self: *String) StringIterator {
return StringIterator{
.string = self,
.index = 0,
};
}
};
};

/// Contains UTF-8 utility functions
Expand Down

0 comments on commit 1f60935

Please sign in to comment.