From 5963853c4fdbabab946bd11959e38f1689521df5 Mon Sep 17 00:00:00 2001 From: MINGtoMING <3575188313@qq.com> Date: Wed, 14 May 2025 01:04:43 +0800 Subject: [PATCH] Add `data` and `start_offset` methods for `StringView` --- string/string.mbti | 6 ++++++ string/view.mbt | 13 +++++++++++++ string/view_test.mbt | 14 ++++++++++++++ 3 files changed, 33 insertions(+) diff --git a/string/string.mbti b/string/string.mbti index 59717fc1c..3a12ec992 100644 --- a/string/string.mbti +++ b/string/string.mbti @@ -8,6 +8,8 @@ fn contains(String, StringView) -> Bool fn contains_char(String, Char) -> Bool +fn data(StringView) -> String + fn default() -> String #deprecated @@ -59,6 +61,8 @@ fn rev_iter(String) -> Iter[Char] fn split(String, StringView) -> Iter[StringView] +fn start_offset(StringView) -> Int + #deprecated fn starts_with(String, String) -> Bool @@ -92,6 +96,7 @@ fn StringView::charcode_at(Self, Int) -> Int fn StringView::charcodes(Self, start~ : Int = .., end~ : Int = ..) -> Self fn StringView::contains(Self, Self) -> Bool fn StringView::contains_char(Self, Char) -> Bool +fn StringView::data(Self) -> String fn StringView::find(Self, Self) -> Int? fn StringView::find_by(Self, (Char) -> Bool) -> Int? fn[A] StringView::fold(Self, init~ : A, (A, Char) -> A) -> A @@ -119,6 +124,7 @@ fn StringView::rev_find(Self, Self) -> Int? fn[A] StringView::rev_fold(Self, init~ : A, (A, Char) -> A) -> A fn StringView::rev_iter(Self) -> Iter[Char] fn StringView::split(Self, Self) -> Iter[Self] +fn StringView::start_offset(Self) -> Int fn StringView::to_lower(Self) -> Self fn StringView::to_upper(Self) -> Self fn StringView::trim(Self, Self) -> Self diff --git a/string/view.mbt b/string/view.mbt index 45844351a..df931bc42 100644 --- a/string/view.mbt +++ b/string/view.mbt @@ -58,6 +58,19 @@ pub fn View::op_get(self : View, index : Int) -> Int { self.str.unsafe_charcode_at(self.start + index) } +///| +/// Returns the original string that is being viewed. +pub fn data(self : View) -> String { + self.str +} + +///| +/// Returns the starting offset (in UTF-16 code units) of this view into its +/// underlying string. +pub fn start_offset(self : View) -> Int { + self.start +} + ///| /// Returns the length of the view. /// diff --git a/string/view_test.mbt b/string/view_test.mbt index 28fab87be..e0e7c03f3 100644 --- a/string/view_test.mbt +++ b/string/view_test.mbt @@ -65,6 +65,20 @@ test "stringview rev_get" { inspect(view.rev_iter().nth(4).unwrap(), content="e") } +///| +test "stringview data" { + let str = "Hello🤣🤣🤣" + let view = str.view(start_offset=1, end_offset=7) + inspect!(view.data(), content="Hello🤣🤣🤣") +} + +///| +test "stringview start_offset" { + let str = "Hello🤣🤣🤣" + let view = str.view(start_offset=1, end_offset=7) + inspect!(view.start_offset(), content="1") +} + ///| test "stringview length" { let str = "Hello🤣🤣🤣"