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

//! # Root

use std::{
    convert::TryFrom,
    fmt,
    hash::{Hash, Hasher},
    io::{self, Error, ErrorKind},
};

/// # 128 bits (16 bytes)
pub type Z128 = [u8; 128 / 8];

/// # 224 bits (28 bytes)
pub type Z224 = [u8; 224 / 8];

/// # 256 bits (32 bytes)
pub type Z256 = [u8; 256 / 8];

/// # 384 bits (48 bytes)
pub type Z384 = [u8; 384 / 8];

/// # 512 bits (64 bytes)
pub type Z512 = [u8; 512 / 8];

const HEX_STRS: &[&str] = &[
    "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f", "10", "11", "12", "13", "14", "15", "16",
    "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d",
    "2e", "2f", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44",
    "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b",
    "5c", "5d", "5e", "5f", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f", "70", "71", "72",
    "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89",
    "8a", "8b", "8c", "8d", "8e", "8f", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f", "a0",
    "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7",
    "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf", "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce",
    "cf", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3", "e4", "e5",
    "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc",
    "fd", "fe", "ff",
];

#[test]
fn test_hex_strs() {
    assert!(HEX_STRS.len() > usize::from(u8::max_value()));
    for i in 0..HEX_STRS.len() {
        assert_eq!(format!("{:02x}", i), HEX_STRS[i]);
    }
}

/// # Formats a byte slice as a hexadecimal string, in lower-case
///
/// ## Examples
///
/// ```
/// assert_eq!(zeros::bytes_to_hex(&[202, 254]), "cafe");
/// ```
pub fn bytes_to_hex(bytes: &[u8]) -> String {
    let mut result = String::with_capacity(bytes.len().saturating_mul(2));
    for b in bytes {
        result.push_str(HEX_STRS[usize::from(*b)]);
    }
    result
}

const DEC_STRS: &[&str] = &[
    "0", "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",
];

#[test]
fn test_dec_strs() {
    assert!(DEC_STRS.len() > usize::from(u8::max_value()));
    for i in 0..DEC_STRS.len() {
        assert_eq!(i.to_string(), DEC_STRS[i]);
    }
}

/// # Zeros
///
/// ## Features
///
/// - Can be converted from some common hash slices such as `[u8; 16]`, `[u8; 64]`...
///
/// - Implemented [`Display`][r::Display], which prints hex string of the hash, in lower-case.
///
/// - Implemented [`Eq`][r::Eq] and [`Hash`][r::Hash] traits, so you can use it in [`HashSet`][r::HashSet], [`HashMap`][r::HashMap]...
///
/// - [`Debug`][r::Debug] implementation:
///
///     + `{:#?}` prints bytes in _hexadecimal_ format.
///     + `{:?}` prints bytes in _decimal_ format.
///
/// ## Hexadecimal format (in lower case)
///
/// Examples:
///
/// ```
/// use zeros::Zeros;
///
/// let zeros = Zeros::from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]);
/// assert_eq!(zeros.to_string(), "000102030405060708090a0b0c0d0e0f");
/// ```
///
/// [r::Eq]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
/// [r::HashMap]: https://doc.rust-lang.org/std/collections/struct.HashMap.html
/// [r::HashSet]: https://doc.rust-lang.org/std/collections/struct.HashSet.html
/// [r::Debug]: https://doc.rust-lang.org/std/fmt/trait.Debug.html
/// [r::Display]: https://doc.rust-lang.org/std/fmt/trait.Display.html
/// [r::Hash]: https://doc.rust-lang.org/std/hash/trait.Hash.html
#[derive(Clone)]
pub enum Zeros {

    /// # 128 bits (16 bytes)
    Z128(Z128),

    /// # 224 bits (28 bytes)
    Z224(Z224),

    /// # 256 bits (32 bytes)
    Z256(Z256),

    /// # 384 bits (48 bytes)
    Z384(Z384),

    /// # 512 bits (64 bytes)
    Z512(Z512),

}

impl Zeros {

    /// # Gets number of bytes
    pub fn len(&self) -> usize {
        match self {
            Zeros::Z128(bytes) => bytes.len(),
            Zeros::Z224(bytes) => bytes.len(),
            Zeros::Z256(bytes) => bytes.len(),
            Zeros::Z384(bytes) => bytes.len(),
            Zeros::Z512(bytes) => bytes.len(),
        }
    }

    /// # Checks if this instance is same class as one other
    ///
    /// ## Examples
    ///
    /// ```
    /// use zeros::Zeros;
    ///
    /// assert!(Zeros::from([0; 16]).same_class(&Zeros::from([0; 32])) == false);
    /// assert!(Zeros::from([6; 48]).same_class(&Zeros::from([9; 48])));
    /// ```
    pub fn same_class(&self, other: &Self) -> bool {
        match (self, other) {
            (Zeros::Z128(_), Zeros::Z128(_)) => true,
            (Zeros::Z224(_), Zeros::Z224(_)) => true,
            (Zeros::Z256(_), Zeros::Z256(_)) => true,
            (Zeros::Z384(_), Zeros::Z384(_)) => true,
            (Zeros::Z512(_), Zeros::Z512(_)) => true,
            _ => false,
        }
    }

}

/// # Compares slices
fn cmp_slices(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    for i in 0..a.len() {
        if a[i] != b[i] {
            return false;
        }
    }
    true
}

impl Eq for Zeros {}

impl PartialEq for Zeros {

    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Zeros::Z128(a), Zeros::Z128(b)) => cmp_slices(a, b),
            (Zeros::Z224(a), Zeros::Z224(b)) => cmp_slices(a, b),
            (Zeros::Z256(a), Zeros::Z256(b)) => cmp_slices(a, b),
            (Zeros::Z384(a), Zeros::Z384(b)) => cmp_slices(a, b),
            (Zeros::Z512(a), Zeros::Z512(b)) => cmp_slices(a, b),
            _ => false,
        }
    }

}

impl Hash for Zeros {

    fn hash<H>(&self, h: &mut H) where H: Hasher {
        match self {
            Zeros::Z128(bytes) => bytes.hash(h),
            Zeros::Z224(bytes) => bytes.hash(h),
            Zeros::Z256(bytes) => bytes.hash(h),
            Zeros::Z384(bytes) => bytes.hash(h),
            Zeros::Z512(bytes) => bytes.hash(h),
        };
    }

}

macro_rules! impl_from_slices_for_zeros { ($($ty: ty, $code: tt,)+) => {
    $(
        impl From<$ty> for Zeros {

            fn from(slice: $ty) -> Self {
                $code(slice)
            }

        }
    )+
}}

impl_from_slices_for_zeros! {
    Z128, (Zeros::Z128),
    Z224, (Zeros::Z224),
    Z256, (Zeros::Z256),
    Z384, (Zeros::Z384),
    Z512, (Zeros::Z512),
}

impl AsRef<[u8]> for Zeros {

    fn as_ref(&self) -> &[u8] {
        match self {
            Zeros::Z128(bytes) => bytes,
            Zeros::Z224(bytes) => bytes,
            Zeros::Z256(bytes) => bytes,
            Zeros::Z384(bytes) => bytes,
            Zeros::Z512(bytes) => bytes,
        }
    }

}

/// # Makes a new vector and copies the original slice's content into it
impl From<&Zeros> for Vec<u8> {

    fn from(zeros: &Zeros) -> Vec<u8> {
        match zeros {
            Zeros::Z128(bytes) => bytes.to_vec(),
            Zeros::Z224(bytes) => bytes.to_vec(),
            Zeros::Z256(bytes) => bytes.to_vec(),
            Zeros::Z384(bytes) => bytes.to_vec(),
            Zeros::Z512(bytes) => bytes.to_vec(),
        }
    }

}

/// # Makes a new vector and copies the original slice's content into it
impl From<Zeros> for Vec<u8> {

    fn from(zeros: Zeros) -> Vec<u8> {
        (&zeros).into()
    }

}

/// # Converts a [`&Zeros`][::Zeros] into a hexadecimal string, in lower-case
///
/// ## Examples
///
/// ```
/// use zeros::Zeros;
///
/// assert_eq!(
///     String::from(Zeros::from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])),
///     "000102030405060708090a0b0c0d0e0f",
/// );
/// ```
///
/// [::Zeros]: struct.Zeros.html
impl From<&Zeros> for String {

    fn from(zeros: &Zeros) -> String {
        match zeros {
            Zeros::Z128(bytes) => bytes_to_hex(bytes),
            Zeros::Z224(bytes) => bytes_to_hex(bytes),
            Zeros::Z256(bytes) => bytes_to_hex(bytes),
            Zeros::Z384(bytes) => bytes_to_hex(bytes),
            Zeros::Z512(bytes) => bytes_to_hex(bytes),
        }
    }

}

/// # Converts a [`Zeros`][::Zeros] into a hexadecimal string, in lower-case
///
/// [::Zeros]: struct.Zeros.html
impl From<Zeros> for String {

    fn from(zeros: Zeros) -> String {
        String::from(&zeros)
    }

}

impl fmt::Display for Zeros {

    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        f.write_str(&String::from(self))
    }

}

impl fmt::Debug for Zeros {

    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        let bytes = match self {
            Zeros::Z128(bytes) => {
                f.write_str("Zeros::Z128([")?;
                &bytes[..]
            }
            Zeros::Z224(bytes) => {
                f.write_str("Zeros::Z224([")?;
                &bytes[..]
            }
            Zeros::Z256(bytes) => {
                f.write_str("Zeros::Z256([")?;
                &bytes[..]
            }
            Zeros::Z384(bytes) => {
                f.write_str("Zeros::Z384([")?;
                &bytes[..]
            }
            Zeros::Z512(bytes) => {
                f.write_str("Zeros::Z512([")?;
                &bytes[..]
            }
        };

        let alternate = f.alternate();
        for (i, b) in bytes.iter().enumerate() {
            if i > 0 {
                f.write_str(", ")?;
            }
            match alternate {
                true => write!(f, "0x{}", HEX_STRS[usize::from(*b)])?,
                false => f.write_str(DEC_STRS[usize::from(*b)])?,
            };
        }

        f.write_str("])")
    }

}

macro_rules! impl_try_from_zeros_for_slices { ($($code: tt, $ty: ty,)+) => {
    $(
        impl TryFrom<Zeros> for $ty {

            type Error = Error;

            fn try_from(zeros: Zeros) -> io::Result<Self> {
                match zeros {
                    Zeros::$code(slice) => Ok(slice),
                    _ => Err(Error::new(ErrorKind::InvalidData, format!("Not an instance of {:?}", stringify!($code)))),
                }
            }

        }
    )+
}}

impl_try_from_zeros_for_slices! {
    Z128, Z128,
    Z224, Z224,
    Z256, Z256,
    Z384, Z384,
    Z512, Z512,
}