custom_tryread/
custom_tryread.rs1use smart_read::*;
2
3
4
5fn main() {
7 let input = read!(PasswordInput {min_len: 10, min_digits: 1});
8 println!("You entered: \"{input}\"");
9}
10
11
12
13struct PasswordInput {
14 pub min_len: usize,
15 pub min_digits: usize,
16}
17
18impl TryRead for PasswordInput {
19 type Output = String;
20 type Default = (); fn try_read_line(self, prompt: Option<String>, _default: Option<Self::Default>) -> smart_read::BoxResult<Self::Output> {
22 let prompt = prompt.unwrap_or_else(
23 || format!("Enter a password (must have {}+ characters and have {}+ digits): ", self.min_len, self.min_digits)
24 );
25 loop {
26
27 print!("{prompt}");
29 let password = read_stdin()?;
30
31 if password.len() < 10 {
32 println!("Invalid, password must have at least 10 characters");
33 continue;
34 }
35 if password.chars().filter(|c| c.is_digit(10)).count() < 1 {
36 println!("Invalid, password must have at least 1 digit");
37 continue;
38 }
39
40 return Ok(password)
41
42 }
43 }
44}