// SPDX-FileCopyrightText: 2024 Aravinth Manivannan // // SPDX-License-Identifier: AGPL-3.0-or-later // if let s: Option = Some("".into()); transform to None; pub fn clean_option_empty_string(s: Option) -> Option { 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(s: String, e: E) -> Result { 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) ); } }