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
// License: see LICENSE file at root directory of `master` branch

//! # Level

use std::{
    mem,
    time::{UNIX_EPOCH, SystemTime},
};

#[cfg(unix)]
use std::{
    fs::OpenOptions,
    io::{Read, Write},
    path::PathBuf,
};

const RANDOM_BYTE_COUNT: usize = mem::size_of::<u64>();

/// # Level
///
/// For important tasks, if you want to confirm the user, you can use [`hash()`][::hash()] to generate a random string, and ask them to type it.
///
/// [::hash()]: #method.hash
#[derive(Debug, Eq, PartialEq, Hash, Clone, Copy)]
pub enum Level {

    /// # Low
    Low,

    /// # Normal
    Normal,

    /// # Medium
    Medium,

    /// # High
    High,

    /// # Critical
    Critical,

}

impl Level {

    /// # Generates a random hash 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. Also:
    ///
    ///     + For security reason, if it detects some abnormal attributes from that file, it will print warnings to stderr, and will _not_ read
    ///       any bytes.
    ///
    ///     + If reading succeeds, as a nice gesture, it will write some bytes back to that file.
    ///
    /// - Higher levels always generate longer strings.
    ///
    /// They _might_ look like these:
    ///
    /// | Level                    | Sample
    /// | ------------------------ | ------
    /// | [`Low`][::Low]           | `e9`
    /// | [`Normal`][::Normal]     | `ac8c`
    /// | [`Medium`][::Medium]     | `db9c-725a`
    /// | [`High`][::High]         | `dca9-e93c-f8b2`
    /// | [`Critical`][::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 hash(&self) -> String {
        let bytes = rand_bytes();

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

        let mut result = String::with_capacity({
            let separators = (limit / 2).saturating_sub(1);
            limit.saturating_mul(2).saturating_add(separators)
        });
        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
    }

}

/// # Generates some random bytes from current time
///
/// Worthy bytes start from zeroth index, and go upward.
fn rand_bytes_from_current_time() -> [u8; RANDOM_BYTE_COUNT] {
    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();
    value.to_ne_bytes()
}

/// # 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; RANDOM_BYTE_COUNT] {
    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; RANDOM_BYTE_COUNT] {
    use ::std::os::unix::fs::FileTypeExt;

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

    let some_bytes = 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; RANDOM_BYTE_COUNT];
                    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,
    }
}

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