Skip to content

Commit d3c8117

Browse files
committed
add to_string method for StringView
1 parent 4cf8019 commit d3c8117

File tree

3 files changed

+22
-0
lines changed

3 files changed

+22
-0
lines changed

string/string.mbti

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ impl StringView {
2323
op_as_view(Self, start~ : Int = .., end? : Int) -> Self
2424
op_get(Self, Int) -> Char
2525
rev_get(Self, Int) -> Char
26+
to_string(Self) -> String
2627
}
2728
impl Show for StringView
2829

string/view.mbt

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -426,6 +426,20 @@ pub impl Show for StringView with output(self, logger) {
426426
String::output(substr, logger)
427427
}
428428
429+
///|
430+
/// Returns a new String containing a copy of the characters in this view.
431+
///
432+
/// # Examples
433+
///
434+
/// ```
435+
/// let str = "Hello World"
436+
/// let view = str[0:5] // "Hello"
437+
/// inspect!(view.to_string(), content="Hello")
438+
/// ```
439+
pub fn to_string(self : StringView) -> String {
440+
self.str.substring(start=self.start, end=self.end)
441+
}
442+
429443
///|
430444
/// Returns an iterator over the Unicode characters in the string view.
431445
pub fn StringView::iter(self : StringView) -> Iter[Char] {

string/view_test.mbt

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -514,3 +514,10 @@ test "panic stringview negative index3" {
514514
let _ = str[-1:-2]
515515

516516
}
517+
518+
test "to_string" {
519+
let s = "Hello World"
520+
let view = s[0:5]
521+
let ss = "\{view} Moonbit"
522+
inspect!(ss, content="Hello Moonbit")
523+
}

0 commit comments

Comments
 (0)