Replace endpoint /calendar/schedule_recipe by /calendar/sheduled_recipe
[recipes.git] / common / src / utils.rs
1 use crate::consts;
2
3 pub enum PasswordValidation {
4 Ok,
5 TooShort,
6 }
7
8 pub fn validate_password(password: &str) -> PasswordValidation {
9 if password.len() < consts::MIN_PASSWORD_SIZE {
10 PasswordValidation::TooShort
11 } else {
12 PasswordValidation::Ok
13 }
14 }
15
16 pub fn substitute(str: &str, pattern: &str, replacements: &[&str]) -> String {
17 let mut result = String::with_capacity(
18 (str.len() + replacements.iter().map(|s| s.len()).sum::<usize>())
19 .saturating_sub(pattern.len() * replacements.len()),
20 );
21
22 let mut i = 0;
23 for s in str.split(pattern) {
24 result.push_str(s);
25 if i < replacements.len() {
26 result.push_str(replacements[i]);
27 }
28 i += 1;
29 }
30
31 if i == 1 {
32 return str.to_string();
33 }
34
35 result
36 }
37
38 /// Example: substitute_with_names("{hello}, {world}!", &["{hello}", "{world"], &["Hello", "World"])
39 pub fn substitute_with_names(str: &str, names: &[&str], replacements: &[&str]) -> String {
40 let mut result = str.to_string();
41 for (i, name) in names.iter().enumerate() {
42 if i >= replacements.len() {
43 break;
44 }
45 result = result.replace(name, replacements[i]);
46 }
47 result
48 }
49
50 #[cfg(test)]
51 mod tests {
52 use super::*;
53
54 #[test]
55 fn test_substitute() {
56 assert_eq!(substitute("", "", &[]), "");
57 assert_eq!(substitute("", "", &[""]), "");
58 assert_eq!(substitute("", "{}", &["a"]), "");
59 assert_eq!(substitute("a", "{}", &["b"]), "a");
60 assert_eq!(substitute("a{}", "{}", &["b"]), "ab");
61 assert_eq!(substitute("{}c", "{}", &["b"]), "bc");
62 assert_eq!(substitute("a{}c", "{}", &["b"]), "abc");
63 assert_eq!(substitute("{}b{}", "{}", &["a", "c"]), "abc");
64 assert_eq!(substitute("{}{}{}", "{}", &["a", "bc", "def"]), "abcdef");
65 assert_eq!(substitute("{}{}{}", "{}", &["a"]), "a");
66 }
67
68 #[test]
69 fn test_substitute_with_names() {
70 assert_eq!(
71 substitute_with_names("{hello}, {world}!", &["{hello}"], &["Hello", "World"]),
72 "Hello, {world}!"
73 );
74
75 assert_eq!(
76 substitute_with_names("{hello}, {world}!", &[], &["Hello", "World"]),
77 "{hello}, {world}!"
78 );
79
80 assert_eq!(
81 substitute_with_names("{hello}, {world}!", &["{hello}", "{world}"], &["Hello"]),
82 "Hello, {world}!"
83 );
84
85 assert_eq!(
86 substitute_with_names("{hello}, {world}!", &["{hello}", "{world}"], &[]),
87 "{hello}, {world}!"
88 );
89
90 assert_eq!(
91 substitute_with_names(
92 "{hello}, {world}!",
93 &["{hello}", "{world}"],
94 &["Hello", "World"]
95 ),
96 "Hello, World!"
97 );
98 }
99 }