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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
// 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)
//! - _This project follows [Semantic Versioning 2.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()`].
//!
//! [Semantic Versioning 2.0.0]: https://semver.org/spec/v2.0.0.html
//! [`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.7"
    }
}

/// # 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, u8, u8) = (2018, 5, 12);

/// # 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::convert::AsRef;
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 value = 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 value.1 {
            0 => format!("{:x}", value.0),
            _ => format!("{:x}{:x}", value.0, value.1),
        };

        // 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
    }

}

impl AsRef<Level> for Level {

    fn as_ref(&self) -> &Self {
        self
    }

}

/// # 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 {

    exit_code: i32,

}

impl Assert {

    /// # Makes new instance.
    ///
    /// - `exit_code`: will be passed to [`process::exit()`].
    ///
    /// [`process::exit()`]: https://doc.rust-lang.org/std/process/fn.exit.html
    pub fn new(exit_code: i32) -> Assert {
        Assert {
            exit_code,
        }
    }

    /// # Tries an assert with your own string.
    ///
    /// Sometimes you need to print your own messages and/or your verification string, instead of the pre-defined ones provided by this crate.
    /// This function can help you with that.
    ///
    /// - Inside closure `f`, you can print your messages.
    /// - Then `f` returns the string to be verified. You can make use of [`Level.rand_s()`] if you want to.
    ///
    /// The function will read user input from stdin and verify it. Note that case is _ignored_.
    ///
    /// [`Level.rand_s()`]: enum.Level.html#method.rand_s
    pub fn try_with<F, S>(&self, f: F) -> Result<(), Failed> where F: FnOnce() -> S, S: AsRef<str>, {
        let mut input = String::new();
        match io::stdin().read_line(&mut input) {
            Ok(_) if f().as_ref().to_lowercase() == input.trim().to_lowercase() => Ok(()),
            _ => Err(Failed::User),
        }
    }

    /// # Tries `n` times.
    ///
    /// This function calls [`try_with()`].
    ///
    /// - 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_with()`]: #method.try_with
    /// [`process::exit()`]: https://doc.rust-lang.org/std/process/fn.exit.html
    /// [`::new()`]: #method.new
    pub fn try_n_with<F, S>(&self, n: u8, f: F) where F: Fn() -> S, S: AsRef<str>, {
        for i in 0..n {
            match self.try_with(&f) {
                Ok(()) => return,
                Err(_) => if i >= n - 1 {
                    process::exit(self.exit_code);
                },
            };
        }
    }

    /// # Tries once.
    ///
    /// This function calls [`try_n_with()`] with `1` passed as `n`.
    ///
    /// [`try_n_with()`]: #method.try_n_with
    pub fn try_once_with<F, S>(&self, f: F) where F: Fn() -> S, S: AsRef<str>, {
        self.try_n_with(1, f)
    }

    /// # Tries an assert.
    ///
    /// The function generates a string with difficulty based on level. Then asks the user to type that string.
    pub fn try<T: AsRef<Level>>(&self, level: T) -> Result<(), Failed> {
        // Format and print out
        let rand_s = level.as_ref().rand_s();
        if io::stdout().write(format!("To continue, type '{}': ", &rand_s).as_bytes()).is_err() {
            return Err(Failed::Stdout);
        }
        if io::stdout().flush().is_err() {
            return Err(Failed::Stdout);
        }
        self.try_with(|| rand_s)
    }

    /// # 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<T: AsRef<Level>>(&self, level: T, n: u8) {
        // TODO: this for loop looks like a duplicate of `try_n_with()`
        let level = level.as_ref();
        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<T: AsRef<Level>>(&self, level: T) {
        self.try_n(level, 1);
    }

}

/// # Tries `n` times.
///
/// This function makes new [`Assert`] with `1` as exit code; then calls [`try_n_with()`].
///
/// [`Assert`]: struct.Assert.html
/// [`try_n_with()`]: struct.Assert.html#method.try_n_with
pub fn try_n_with<F, S>(n: u8, f: F) where F: Fn() -> S, S: AsRef<str>, {
    Assert::new(1).try_n_with(n, f);
}

/// # Tries once.
///
/// This function calls [`try_n_with()`] with `1` passed as `n`.
///
/// [`try_n_with()`]: fn.try_n_with.html
pub fn try_once_with<F, S>(f: F) where F: Fn() -> S, S: AsRef<str>, {
    try_n_with(1, f)
}

/// # Tries `n` times.
///
/// This function makes new [`Assert`] with `1` as exit code; then calls [`try_n()`].
///
/// [`Assert`]: struct.Assert.html
/// [`try_n()`]: struct.Assert.html#method.try_n
pub fn try_n<T: AsRef<Level>>(level: T, n: u8) {
    Assert::new(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<T: AsRef<Level>>(level: T) {
    try_n(level, 1);
}