vanikam/src/utils/string.rs
Aravinth Manivannan ac1964d21a
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/pr/woodpecker Pipeline was successful
feat: define LineItem with add and update events and commands
2024-07-23 14:46:52 +05:30

61 lines
1.5 KiB
Rust

// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
// if let s: Option<String> = Some("".into()); transform to None;
pub fn clean_option_empty_string(s: Option<String>) -> Option<String> {
if let Some(s) = s {
let s = s.trim();
if s.is_empty() {
None
} else {
Some(s.to_owned())
}
} else {
None
}
}
pub fn empty_string_err<E: std::error::Error>(s: String, e: E) -> Result<String, E> {
let s = s.trim().to_owned();
if s.is_empty() {
return Err(e);
}
Ok(s)
}
#[cfg(test)]
mod tests {
use derive_more::{Display, Error};
use super::*;
#[test]
fn test_clean_option_empty_string() {
assert!(clean_option_empty_string(Some("".into())).is_none());
assert!(clean_option_empty_string(Some("foo".into())).is_some());
assert_eq!(
clean_option_empty_string(Some("foo".into())).unwrap(),
"foo"
);
}
#[test]
fn test_empty_string_err() {
let s: String = "foo".into();
#[derive(Display, Debug, Eq, PartialEq, Error)]
enum TestError {
EmptyString,
}
assert_eq!(
empty_string_err(format!(" {s} "), TestError::EmptyString).unwrap(),
s
);
assert_eq!(
empty_string_err(format!(" "), TestError::EmptyString),
Err(TestError::EmptyString)
);
}
}