string_util/lib.rs
1//! # `string_util` provides support for a small number of operations involving strings.
2
3use std::fmt::{Display, Formatter, Result as FmtResult};
4
5/// Capitalizes the first character of the given string according to `cap_type`.
6/// Returns `Err(EmptyStringError)` if the string is empty.
7///
8/// # Example
9///
10/// ```
11/// use string_util::Capitalization;
12///
13/// let result = string_util::capitalize(String::from("ngozi"), Capitalization::UpperCase).unwrap();
14/// assert_eq!(result, String::from("Ngozi"));
15///
16/// let result = string_util::capitalize(String::from("Shalewa"), Capitalization::LowerCase).unwrap();
17/// assert_eq!(result, String::from("shalewa"));
18/// ```
19pub fn capitalize(txt: String, cap_type: Capitalization) -> Result<String, EmptyStringError> {
20 let txt = txt.trim();
21 let mut char_vec = txt.chars().collect::<Vec<char>>();
22
23 if let Some(first_char) = char_vec.get_mut(0) {
24 if first_char.is_whitespace() {
25 return Err(EmptyStringError);
26 }
27
28 if let Capitalization::UpperCase = cap_type {
29 first_char.make_ascii_uppercase();
30 } else {
31 first_char.make_ascii_lowercase();
32 }
33
34 let mut result = String::new();
35 for ch in char_vec {
36 let mut buf = [0; 4];
37 let str_char = ch.encode_utf8(&mut buf);
38 result.push_str(str_char);
39 }
40 Ok(result)
41 } else {
42 Err(EmptyStringError)
43 }
44}
45
46/// Converts a vector of any `Display` type to a string delimited by the passed character.
47///
48/// # Example
49///
50/// ```
51/// use string_util;
52///
53/// let vect1 = vec!["APC".to_string(), "PDP".to_string(), "ANPP".to_string()];
54/// let vect2 = vec!["127".to_string(), "0".to_string(), "0".to_string(), "1".to_string()];
55///
56/// let delim_string_1 = string_util::vec_to_delimited_str(&vect1, ':');
57/// let delim_string_2 = string_util::vec_to_delimited_str(&vect2, '.');
58///
59/// assert!(delim_string_2.contains("127.0.0.1"));
60/// assert!(delim_string_1.contains("APC:PDP:ANPP"));
61/// ```
62pub fn vec_to_delimited_str<T: Display>(str_vec: &Vec<T>, delimiter: char) -> String {
63 let mut result = String::new();
64
65 for (i, str) in str_vec.iter().enumerate() {
66 if i > 0 {
67 result.push(delimiter);
68 }
69 result.push_str(str.to_string().as_str())
70 }
71
72 result
73}
74#[derive(Debug, Clone)]
75pub struct EmptyStringError;
76
77impl Display for EmptyStringError {
78 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
79 write!(f, "The supplied string is empty")
80 }
81}
82pub enum Capitalization {
83 LowerCase,
84 UpperCase,
85}