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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
// License: see LICENSE file at root directory of `master` branch

//! # A small kit for confirming user actions via command line
//!
//! # Project
//!
//! - Repository: <https://bitbucket.org/haibison/dia-assert>
//! - License: [Free Public License 1.0.0](https://opensource.org/licenses/FPL-1.0.0)
//!
//! # Features
//!
//! For important tasks, if you want to confirm the user, you can use [`Assert`]. It generates a string and asks the user to type it. You can
//! catch if the user fails, and process with your solution. Or you can let [`Assert`] exit the process peacefully via [`process::exit()`].
//!
//! [`Assert`]: struct.Assert.html
//! [`try()`]: struct.Assert.html#method.try
//! [`process::exit()`]: https://doc.rust-lang.org/std/process/fn.exit.html

// ╔═════════════════╗
// ║   IDENTIFIERS   ║
// ╚═════════════════╝

macro_rules! crate_code_name {
    () => {
        "dia-assert"
    }
}

macro_rules! crate_version_name {
    () => {
        "0.0.4"
    }
}

/// # Crate name.
pub const CRATE_NAME: &'static str = "Dia-assert";

/// # Crate code name.
pub const CRATE_CODE_NAME: &'static str = crate_code_name!();

/// # Crate version name.
pub const CRATE_VERSION_NAME: &'static str = crate_version_name!();

/// # Crate release date (year/month/day).
pub const CRATE_RELEASE_DATE: [u16; 3] = [2018, 5, 4];

/// # Unique universally identifier of this crate. Its CRC-32 is `83221b81`.
pub const UUID: &'static str = "c4f0e8bd-8731-4699-9cbd-9a53cc4b3471";

/// # Tag, which can be used for logging...
pub const TAG: &'static str = concat!(crate_code_name!(), "_83221b81_", crate_version_name!());

// ╔════════════════════╗
// ║   IMPLEMENTATION   ║
// ╚════════════════════╝

use std::error::Error;
use std::fmt::{self, Display};
use std::io::{self, Write};
use std::process;
use std::time::{UNIX_EPOCH, SystemTime};

/// # Level.
pub enum Level {

    /// # Low.
    Low,

    /// # Normal.
    Normal,

    /// # Medium.
    Medium,

    /// # High.
    High,

    /// # Critical.
    Critical,

}

impl Level {

    /// # Generates a random string based on current level.
    pub fn rand_s(&self) -> String {
        let secs = match SystemTime::now().duration_since(UNIX_EPOCH) {
            Ok(d) => d.as_secs(),
            Err(_) => std::u64::MAX,
        };

        // Do some simple random
        let mut value = 0.0;
        for (i, b) in secs.to_string().as_bytes().to_vec().into_iter().enumerate() {
            value += (b as f64).powi(i as i32) as f64;
        }
        let value = if value > std::u64::MAX as f64 { std::u64::MAX } else { value as u64 };

        // Now generate a value based on level
        let (v0, v1) = match *self {
            Level::Low => (value % std::u8::MAX as u64, 0),
            Level::Normal => (value % std::u16::MAX as u64, 0),
            Level::Medium => (value % std::u32::MAX as u64, 0),
            Level::High => (value, 0),
            Level::Critical => (value / 2, value),
        };
        let value = match v1 {
            0 => format!("{:x}", v0),
            _ => format!("{:x}{:x}", v0, v1),
        };

        // Separate characters into groups of 4
        let count = value.chars().count();
        let start = count % 4;
        let mut result = String::new();
        for (i, ch) in value.chars().enumerate() {
            if i > 0 && i.wrapping_rem(4).wrapping_sub(start) == 0 {
                result.push('-');
            }
            result.push(ch);
        }
        result
    }

}

/// # Failed.
#[derive(Debug)]
pub enum Failed {

    /// # User failure.
    User,

    /// # Stdout failure.
    Stdout,

}

impl Display for Failed {

    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        write!(f, "{}", self.description())
    }

}

impl Error for Failed {

    fn description(&self) -> &str {
        match *self {
            Failed::User => "User failure",
            Failed::Stdout => "Stdout failure",
        }
    }

}

/// # Use this struct with [`Level`] to assert a user action.
///
/// [`Level`]: enum.Level.html
pub struct Assert {

    custom_formats: Option<(String, String)>,
    exit_code: i32,

}

impl Assert {

    /// # Makes new instance.
    ///
    /// - `custom_formats`: currently Rust doesn't support runtime formatting. So it's impossible to provide you a simpler solution. This is a
    ///   workaround: the first string will be placed before the generated-string to be displayed to the user. The second string will be placed
    ///   after that. If you provide `None`, a pre-defined format will be used.
    ///
    /// - `exit_code`: will be passed to [`process::exit()`].
    ///
    /// [`process::exit()`]: https://doc.rust-lang.org/std/process/fn.exit.html
    pub fn new(custom_formats: Option<(String, String)>, exit_code: i32) -> Assert {
        Assert {
            custom_formats,
            exit_code,
        }
    }

    /// # Tries an assert.
    ///
    /// The function generates a string with difficulty based on level. Then asks the user to type that string.
    pub fn try(&self, level: &Level) -> Result<(), Failed> {
        let rand_s = level.rand_s();

        // Format and print out
        let msg = match self.custom_formats {
            Some(ref f) => format!("{}{}{}", f.0, &rand_s, f.1),
            None => format!("To continue, type '{}': ", &rand_s),
        };
        if io::stdout().write(msg.as_bytes()).is_err() {
            return Err(Failed::Stdout);
        }
        if io::stdout().flush().is_err() {
            return Err(Failed::Stdout);
        }

        // Verify
        let mut input = String::new();
        match io::stdin().read_line(&mut input) {
            Ok(_) if rand_s == input.trim().to_lowercase() => Ok(()),
            _ => Err(Failed::User),
        }
    }

    /// # Tries `n` times.
    ///
    /// This function calls [`try()`].
    ///
    /// - If the user passed, it returns peacefully.
    /// - For other cases (the user fails, or stdout failure...), it calls [`process::exit()`] with the exit code you provided in [`::new()`].
    ///
    /// [`try()`]: #method.try
    /// [`process::exit()`]: https://doc.rust-lang.org/std/process/fn.exit.html
    /// [`::new()`]: #method.new
    pub fn try_n(&self, level: &Level, n: u8) {
        for i in 0..n {
            match self.try(level) {
                Ok(()) => return,
                Err(_) => if i >= n - 1 {
                    process::exit(self.exit_code);
                },
            };
        }
    }

    /// # Tries once.
    ///
    /// This function calls [`try_n()`] with `1` passed as `n`.
    ///
    /// [`try_n()`]: #method.try_n
    pub fn try_once(&self, level: &Level) {
        self.try_n(level, 1);
    }

}

/// # Tries `n` times.
///
/// This function makes new [`Assert`] with default formats, and `1` as exit code; then calls [`try_n()`].
///
/// [`Assert`]: struct.Assert.html
/// [`try_n()`]: struct.Assert.html#method.try_n
pub fn try_n(level: &Level, n: u8) {
    Assert::new(None, 1).try_n(level, n);
}

/// # Tries once.
///
/// This function calls [`try_n()`] with `1` passed as `n`.
///
/// [`try_n()`]: fn.try_n.html
pub fn try_once(level: &Level) {
    try_n(level, 1);
}