summaryrefslogtreecommitdiff
path: root/src/eval/str.rs
diff options
context:
space:
mode:
authorMichael Lohr <michael@lohr.dev>2023-05-03 12:34:35 +0200
committerGitHub <noreply@github.com>2023-05-03 12:34:35 +0200
commitffad8516af0b91121dc0761c8026e0a12939a7d4 (patch)
treeada5c6b5510b5f509997ccf5308a9cafc8618990 /src/eval/str.rs
parentca8462642a96ec282afeb0774b6d5daf546ac236 (diff)
Implement default values for at() (#995)
Diffstat (limited to 'src/eval/str.rs')
-rw-r--r--src/eval/str.rs11
1 files changed, 9 insertions, 2 deletions
diff --git a/src/eval/str.rs b/src/eval/str.rs
index 89be3699..d7e00bf6 100644
--- a/src/eval/str.rs
+++ b/src/eval/str.rs
@@ -69,12 +69,13 @@ impl Str {
}
/// Extract the grapheme cluster at the given index.
- pub fn at(&self, index: i64) -> StrResult<Self> {
+ pub fn at<'a>(&'a self, index: i64, default: Option<&'a str>) -> StrResult<Self> {
let len = self.len();
let grapheme = self.0[self.locate(index)?..]
.graphemes(true)
.next()
- .ok_or_else(|| out_of_bounds(index, len))?;
+ .or(default)
+ .ok_or_else(|| no_default_and_out_of_bounds(index, len))?;
Ok(grapheme.into())
}
@@ -348,6 +349,12 @@ fn out_of_bounds(index: i64, len: i64) -> EcoString {
eco_format!("string index out of bounds (index: {}, len: {})", index, len)
}
+/// The out of bounds access error message when no default value was given.
+#[cold]
+fn no_default_and_out_of_bounds(index: i64, len: i64) -> EcoString {
+ eco_format!("no default value was specified and string index out of bounds (index: {}, len: {})", index, len)
+}
+
/// The char boundary access error message.
#[cold]
fn not_a_char_boundary(index: i64) -> EcoString {