Skip to content

Commit

Permalink
add iter() method for StringView (#1503)
Browse files Browse the repository at this point in the history
* add iter for stringview

* info

* tweak
  • Loading branch information
Yu-zh authored Jan 18, 2025
1 parent b73094c commit d6afbb0
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
1 change: 1 addition & 0 deletions string/string.mbti
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ impl Show for StringIndex

type StringView
impl StringView {
iter(Self) -> Iter[Char]
length(Self) -> Int
length_eq(Self, Int) -> Bool
length_ge(Self, Int) -> Bool
Expand Down
22 changes: 22 additions & 0 deletions string/view.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -411,3 +411,25 @@ pub impl Show for StringView with output(self, logger) {
let substr = self.str.substring(start=self.start, end=self.end)
String::output(substr, logger)
}

///|
/// Returns an iterator over the Unicode characters in the string view.
pub fn StringView::iter(self : StringView) -> Iter[Char] {
Iter::new(fn(yield_) {
for index = self.start; index < self.end; index = index + 1 {
let c1 = self.str[index]
if is_leading_surrogate(c1) && index + 1 < self.end {
let c2 = self.str[index + 1]
if is_trailing_surrogate(c2) {
let c = code_point_of_surrogate_pair(c1, c2)
guard let IterContinue = yield_(c) else { x => break x }
continue index + 2
}
}
guard let IterContinue = yield_(c1) else { x => break x }

} else {
IterContinue
}
})
}
10 changes: 10 additions & 0 deletions string/view_test.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -444,3 +444,13 @@ test "panic rev_get2" {
let _ = view.rev_get(-1)

}

test "stringview iter" {
let str = "hello🤣🤣🤣"
guard let Some(start) = str.index_at(1)
guard let Some(end) = str.index_at(6)
let view = str[start:end]
let iter = view.iter()
inspect!(iter.count(), content="5")
inspect!(iter, content="['e', 'l', 'l', 'o', '🤣']")
}

0 comments on commit d6afbb0

Please sign in to comment.