Merge dabef054883e95bc35444af369fd6132332bc1a7 into 0a3c6939dd274f40672484695d909c2cc0d0d755

This commit is contained in:
Malo 2025-07-08 14:42:59 +02:00 committed by GitHub
commit c0bd8c1eb3
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 24 additions and 6 deletions

View File

@ -178,25 +178,39 @@ impl Str {
self.0.len()
}
/// Extracts the first grapheme cluster of the string.
/// Fails with an error if the string is empty.
/// Extracts the first grapheme cluster of the string. Fails with an error
/// if the string is empty. Returns the default value if the string is empty
/// or fails with an error is no default value was specified.
#[func]
pub fn first(&self) -> StrResult<Str> {
pub fn first(
&self,
/// A default value to return if the string is empty.
#[named]
default: Option<Str>,
) -> StrResult<Str> {
self.0
.graphemes(true)
.next()
.map(Into::into)
.or(default)
.ok_or_else(string_is_empty)
}
/// Extracts the last grapheme cluster of the string.
/// Fails with an error if the string is empty.
/// Extracts the last grapheme cluster of the string. Fails with an error if
/// the string is empty. Returns the default value if the string is empty or
/// fails with an error is no default value was specified.
#[func]
pub fn last(&self) -> StrResult<Str> {
pub fn last(
&self,
/// A default value to return if the string is empty.
#[named]
default: Option<Str>,
) -> StrResult<Str> {
self.0
.graphemes(true)
.next_back()
.map(Into::into)
.or(default)
.ok_or_else(string_is_empty)
}

View File

@ -103,6 +103,10 @@
#test("Hello".last(), "o")
#test("🏳🌈A🏳".first(), "🏳️‍🌈")
#test("🏳🌈A🏳".last(), "🏳️‍⚧️")
#test("hey".first(default: "d"), "h")
#test("".first(default: "d"), "d")
#test("hey".last(default: "d"), "y")
#test("".last(default: "d"), "d")
--- string-first-empty ---
// Error: 2-12 string is empty