Add some phonenumberutil functions

This commit is contained in:
Vlasislav Kashin
2025-07-09 13:22:32 +03:00
parent 29f5e5664c
commit 7692433296
11 changed files with 1409 additions and 91 deletions

36
src/string_util.rs Normal file
View File

@@ -0,0 +1,36 @@
use std::borrow::Cow;
/// Strips prefix of given string Cow. Returns option with `Some` if
/// prefix found and stripped.
///
/// Calls `drain` if string is owned and returns slice if string is borrowed
pub fn strip_cow_prefix<'a>(cow: Cow<'a, str>, prefix: &str) -> Option<Cow<'a, str>> {
match cow {
Cow::Borrowed(s) => s.strip_prefix(prefix).map(| s | Cow::Borrowed(s)),
Cow::Owned(mut s) => {
if s.starts_with(prefix) {
s.drain(0..prefix.len());
return Some(Cow::Owned(s));
}
None
}
}
}
#[cfg(test)]
mod tests {
use std::borrow::Cow;
use crate::string_util::strip_cow_prefix;
#[test]
fn test_usage() {
let str_to_strip = Cow::Owned("test0:test".to_owned());
let stripped = strip_cow_prefix(str_to_strip, "test0");
assert_eq!(stripped, Some(Cow::Owned(":test".to_owned())));
let str_to_strip = Cow::Owned("test:test0".to_owned());
let stripped = strip_cow_prefix(str_to_strip, "test0");
assert_eq!(stripped, None)
}
}