1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
// License: see LICENSE file at root directory of `master` branch

//! # Kit for working with user

use {
    core::{
        fmt::{self, Display, Formatter},
        hash::{Hash, Hasher},
        str::FromStr,
    },
    std::{
        collections::HashSet,
        io::{Error, ErrorKind},
    },

    crate::Result,
};

/// # Answer
///
/// Each variant can have an optional representation string. If not provided, defaults will be used.
///
/// See [`ask_user()`][fn:ask_user] for usage.
///
/// [fn:ask_user]: fn.ask_user.html
#[derive(Debug, Eq)]
pub enum Answer<'a> {

    /// # Yes
    Yes(Option<&'a str>),

    /// # No
    No(Option<&'a str>),

    /// # Retry
    Retry(Option<&'a str>),

    /// # Next
    Next(Option<&'a str>),

    /// # Cancel
    Cancel(Option<&'a str>),

}

impl PartialEq for Answer<'_> {

    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Answer::Yes(_), Answer::Yes(_)) => true,
            (Answer::No(_), Answer::No(_)) => true,
            (Answer::Retry(_), Answer::Retry(_)) => true,
            (Answer::Next(_), Answer::Next(_)) => true,
            (Answer::Cancel(_), Answer::Cancel(_)) => true,
            _ => false,
        }
    }

}

impl Hash for Answer<'_> {

    fn hash<H>(&self, h: &mut H) where H: Hasher {
        let idx: u8 = match self {
            Answer::Yes(_) => 0,
            Answer::No(_) => 1,
            Answer::Retry(_) => 2,
            Answer::Next(_) => 3,
            Answer::Cancel(_) => 4,
        };
        idx.hash(h);
    }

}

#[test]
fn test_answers() {
    let answers = &[
        Answer::Yes(Some(concat!())), Answer::Yes(None),
        Answer::No(Some(concat!())), Answer::No(None),
        Answer::Retry(Some(concat!())), Answer::Retry(None),
        Answer::Next(Some(concat!())), Answer::Next(None),
        Answer::Cancel(Some(concat!())), Answer::Cancel(None),
    ];
    assert_eq!(answers.iter().collect::<HashSet<_>>().len(), 5);
}

impl Display for Answer<'_> {

    fn fmt(&self, f: &mut Formatter) -> core::result::Result<(), fmt::Error> {
        match self {
            Answer::Yes(Some(s)) | Answer::No(Some(s)) | Answer::Retry(Some(s)) | Answer::Next(Some(s)) | Answer::Cancel(Some(s))
            => f.write_str(s),
            Answer::Yes(None) => f.write_str("Yes"),
            Answer::No(None) => f.write_str("No"),
            Answer::Retry(None) => f.write_str("Retry"),
            Answer::Next(None) => f.write_str("Next"),
            Answer::Cancel(None) => f.write_str("Cancel"),
        }
    }

}

/// # Asks user some question
///
/// Notes:
///
/// - The question will be printed first. Then one line break. Then each answer will be printed on each line.
///
/// - The user can enter either:
///
///     + An answer index.
///     + Or some part of an answer.
///
/// - The function will start again if:
///
///     + The user enters a wrong index.
///     + The phrase entered is presented in more than one answer.
///
/// - The function returns an error if you provide duplicate answers, or no answers at all.
pub fn ask_user<'a, 'b, S>(question: S, answers: &'a[Answer<'b>]) -> Result<&'a Answer<'b>> where S: AsRef<str> {
    if answers.is_empty() {
        return Err(Error::new(ErrorKind::InvalidData, "There are no answers"));
    }
    if answers.iter().collect::<HashSet<_>>().len() != answers.len() {
        return Err(Error::new(ErrorKind::InvalidData, "There are duplicate answers"));
    }

    loop {
        crate::lock_write_out(format!("{}\n\n", question.as_ref().trim()))?;
        for (idx, answer) in answers.iter().enumerate() {
            crate::lock_write_out(format!("[{idx}] {answer}\n", idx=idx + 1, answer=answer))?;
        }

        crate::lock_write_out("\n-> ")?;

        let user_choice = crate::read_line::<String>()?;
        if user_choice.is_empty() {
            continue;
        }

        // Try index first
        match usize::from_str(&user_choice).map(|i| i.checked_sub(1)) {
            Ok(Some(idx)) => if idx < answers.len() {
                return Ok(&answers[idx]);
            },
            Ok(None) => continue,
            // Now try phrase
            Err(_) => {
                let user_choice = user_choice.to_lowercase();
                match answers.iter().try_fold(None, |found_answer, answer| if answer.to_string().to_lowercase().contains(&user_choice) {
                    match found_answer {
                        None => Ok(Some(answer)),
                        Some(_) => Err(Error::new(ErrorKind::Other, "User choice matches more than one answer")),
                    }
                } else {
                    Ok(found_answer)
                }) {
                    Ok(Some(answer)) => return Ok(answer),
                    _ => continue,
                };
            },
        };
    }
}