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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
// 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: Nice License 1.0.0 _(see LICENSE file at root directory of `master` branch)_
//! - _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! code_name  { () => { "dia-assert" }}
macro_rules! version    { () => { "1.4.0" }}

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

/// # Crate code name
pub const CODE_NAME: &'static str = code_name!();

/// # Crate version
pub const VERSION: &'static str = version!();

/// # Crate release date (year/month/day)
pub const RELEASE_DATE: (u16, u8, u8) = (2019, 3, 28);

/// # 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!(code_name!(), "::83221b81::", version!());

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

#[test]
fn test_crate_version() {
    assert_eq!(VERSION, env!("CARGO_PKG_VERSION"));
}

#[macro_use]
#[allow(unused_macros)]
mod __;

pub mod version_info;

use std::{
    fs::OpenOptions,
    io::{self, Error, ErrorKind, Read, Write},
    mem,
    path::PathBuf,
    process,
    time::{UNIX_EPOCH, SystemTime},
};

/// # Level
pub enum Level {

    /// # Low
    Low,

    /// # Normal
    Normal,

    /// # Medium
    Medium,

    /// # High
    High,

    /// # Critical
    Critical,

}

impl Level {

    /// # Generates some random bytes from current time
    ///
    /// Worthy bytes start from zeroth index, and go upward.
    fn rand_bytes_from_current_time() -> [u8; mem::size_of::<u64>()] {
        let value = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| {
            let mut result = 1_u128;
            for v in [d.subsec_millis(), d.subsec_micros(), d.subsec_nanos()].iter() {
                if let Some(v) = result.checked_mul(*v as u128) {
                    result = v;
                }
            }
            result.checked_mul(d.as_secs() as u128).unwrap_or_else(|| result.checked_add(d.as_secs() as u128).unwrap_or(result))
        })
            .unwrap_or_else(|_| u128::max_value());

        // Convert to little-endian. Since we'll process them from first to last element...
        let value = ((value % u64::max_value() as u128) as u64).to_le();

        unsafe {
            // - This call is dangerous: <https://doc.rust-lang.org/std/mem/fn.transmute.html>
            // - Again, this call is dangerous: <https://doc.rust-lang.org/nomicon/transmutes.html>
            // - TODO: when `::to_bytes()` is stable, switch to it.
            mem::transmute::<u64, [u8; mem::size_of::<u64>()]>(value)
        }
    }

    /// # Generates some random bytes
    ///
    /// ## Notes
    ///
    /// This function uses current time as source. Worthy bytes start from zeroth index, and go upward.
    #[cfg(not(unix))]
    fn rand_bytes() -> [u8; mem::size_of::<u64>()] {
        Self::rand_bytes_from_current_time()
    }

    /// # Generates some random bytes
    ///
    /// ## Notes
    ///
    /// - This function will try to read some bytes from `/dev/urandom`. If any error raises, it reverts back to using current time as source.
    /// - If current time is used, worthy bytes start from zeroth index, and go upward.
    #[cfg(unix)]
    fn rand_bytes() -> [u8; mem::size_of::<u64>()] {
        use ::std::os::unix::fs::FileTypeExt;

        const PATH: &'static str = "/dev/urandom";

        let some_bytes = Self::rand_bytes_from_current_time();

        match PathBuf::from(PATH).metadata().map(|m| m.file_type()) {
            Ok(file_type) => match
                file_type.is_dir() == false && file_type.is_file() == false && file_type.is_char_device() && file_type.is_socket() == false
            {
                true => match OpenOptions::new().read(true).write(true).open(PATH) {
                    Ok(mut file) => {
                        let mut result = [0_u8; mem::size_of::<u64>()];
                        match file.read_exact(&mut result) {
                            Ok(()) => {
                                // Be a good friend, send something back
                                match file.write_all(&some_bytes) {
                                    Ok(()) => if cfg!(test) {
                                        __p!("Sent some bytes to {:?}", PATH);
                                    },
                                    Err(err) => __e!("Couldn't write to {:?} -> {}", PATH, &err),
                                };
                                result
                            },
                            Err(_) => some_bytes,
                        }
                    },
                    Err(_) => some_bytes,
                },
                false => {
                    __e!("Malformed {:?}", PATH);
                    some_bytes
                },
            },
            Err(_) => some_bytes,
        }
    }

    /// # Generates a random string based on current level
    ///
    /// ## Notes
    ///
    /// - On non-Unix systems, this function will generate a random string based on current time.
    /// - On Unix systems, it will try to read some bytes from `/dev/urandom`. If any error raises, it reverts back to above method.
    /// - Per a same level, the output strings' lengths are _not_ guaranteed to be the same in different calls. However, higher levels always
    ///   generate longer strings.
    ///
    /// They _might_ look like these:
    ///
    /// | Level        | Sample
    /// | ------------ | ------
    /// | [`Low`]      | `e9`
    /// | [`Normal`]   | `ac8c`
    /// | [`Medium`]   | `db9c-725a`
    /// | [`High`]     | `dca9-e93c-f8b2`
    /// | [`Critical`] | `115a-a983-4c11-4a38`
    ///
    /// [`Low`]: enum.Level.html#variant.Low
    /// [`Normal`]: enum.Level.html#variant.Normal
    /// [`Medium`]: enum.Level.html#variant.Medium
    /// [`High`]: enum.Level.html#variant.High
    /// [`Critical`]: enum.Level.html#variant.Critical
    pub fn rand_s(&self) -> String {
        let bytes = Self::rand_bytes();

        let limit = match *self {
            Level::Low => 1,
            Level::Normal => 2,
            Level::Medium => 4,
            Level::High => 6,
            Level::Critical => 8,
        };

        let mut result = String::new();
        for (index, byte) in bytes[..bytes.len().min(limit)].iter().enumerate() {
            if index > 0 && index % 2 == 0 {
                result.push('-');
            }
            result.push_str(&format!("{:02x}", byte));
        }
        result
    }

}

#[test]
fn test_levels() {
    assert!(u128::max_value() as f64 > u64::max_value() as f64 * 1e3 * 1e6 * 1e9);
    assert_eq!(Level::rand_bytes().len(), mem::size_of::<u64>());
}

impl AsRef<Level> for Level {

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

}

/// # 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) -> Self {
        Self {
            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_. If the user fails, an error with kind of
    /// [`InvalidInput`] will be returned.
    ///
    /// [`Level.rand_s()`]: enum.Level.html#method.rand_s
    /// [`InvalidInput`]: https://doc.rust-lang.org/std/io/enum.ErrorKind.html#variant.InvalidInput
    pub fn try_with<F>(&self, f: F) -> io::Result<()> where F: FnOnce() -> String {
        let mut input = String::new();
        io::stdin().read_line(&mut input)?;
        let code = f();
        match code.to_lowercase() == input.trim().to_lowercase() {
            true => Ok(()),
            false => Err(Error::new(ErrorKind::InvalidInput, format!("Assertion failed: {:?} != {:?}", code, input))),
        }
    }

    /// # 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>(&self, n: u8, f: F) where F: Fn() -> String {
        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>(&self, f: F) where F: Fn() -> String {
        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) -> io::Result<()> {
        // Format and print out
        let rand_s = level.as_ref().rand_s();
        io::stdout().write(format!("To continue, type '{}': ", &rand_s).as_bytes())?;
        io::stdout().flush()?;
        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>(n: u8, f: F) where F: Fn() -> String {
    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>(f: F) where F: Fn() -> String {
    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);
}