62 lines
1.5 KiB
Rust
62 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)
|
||
|
);
|
||
|
}
|
||
|
}
|