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
// Copyright 2017 Mikhail Zabaluev <mikhail.zabaluev@gmail.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use byteorder;
use byteorder::ByteOrder;
use digest;
use digest::generic_array::GenericArray;

use std::fmt;
use std::fmt::Debug;
use std::marker;
use std::mem;

macro_rules! endian_method {
    ($t:ty, $size:expr, $name:ident, $bo_func:ident) => {
        fn $name(&mut self, n: $t) {
            let mut buf: [u8; $size]
                         = unsafe { mem::uninitialized() };
            <Self::ByteOrder>::$bo_func(&mut buf, n);
            self.process(&buf);
        }
    }
}

/// Extends `digest::Input` to provide primitives for type-safe hashing.
///
/// `EndianInput` provides methods to process machine-independent values
/// of bit widths larger than 8 bit. The values are serialized with the
/// byte order which is defined in the associated type `ByteOrder`.
pub trait EndianInput : digest::Input {

    /// The byte order this implementation provides.
    ///
    /// This type binding determines the "endianness" of how integer
    /// and floating-point values are serialized by this implementation
    /// towards computation of the digest.
    type ByteOrder : ByteOrder;

    /// Feeds an unsigned 8-bit value into the digest function.
    ///
    /// This method is agnostic to the byte order, and is only provided
    /// for completeness.
    fn process_u8(&mut self, n: u8) {
        self.process(&[n]);
    }

    /// Feeds a signed 8-bit value into the digest function.
    ///
    /// This method is agnostic to the byte order, and is only provided
    /// for completeness.
    fn process_i8(&mut self, n: i8) {
        self.process(&[n as u8]);
    }

    for_all_mi_words!(endian_method!);
}

/// An adapter to provide digest functions with endian-awareness.
#[derive(Clone)]
pub struct Endian<D, Bo> {
    inner: D,
    phantom: marker::PhantomData<Bo>
}

/// A type alias for `Endian` specialized for big endian byte order.
pub type BigEndian<D> = Endian<D, byteorder::BigEndian>;

/// A type alias for `Endian` specialized for little endian byte order.
pub type LittleEndian<D> = Endian<D, byteorder::LittleEndian>;

/// A type alias for `Endian` specialized for network byte order.
///
/// Network byte order is defined by [RFC 1700][rfc1700] to be big-endian,
/// and is referred to in several protocol specifications.
/// This type is an alias of `BigEndian`.
///
/// [rfc1700]: https://tools.ietf.org/html/rfc1700
pub type NetworkEndian<D> = BigEndian<D>;

impl<D, Bo> Endian<D, Bo>
    where Bo: ByteOrder
{
    /// Returns a string describing the byte order used by this
    /// `Endian` type instance.
    ///
    /// This is mainly used for debugging purposes. The user
    /// should not rely on any particular output.
    pub fn byte_order_str() -> &'static str {
        // Do a bit of runtime testing.
        let mut buf = [0u8; 4];
        Bo::write_u32(&mut buf, 0x01020304);
        let le = byteorder::LittleEndian::read_u32(&buf);
        match le {
            0x01020304 => "LittleEndian",
            0x04030201 => "BigEndian",
            _ => "unknown byte order"
        }
    }
}

impl<D, Bo> Debug for Endian<D, Bo>
    where D: Debug,
          Bo: ByteOrder
{
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        f.debug_struct(Self::byte_order_str())
         .field("digest", &self.inner)
         .finish()
    }
}

impl<D, Bo> EndianInput for Endian<D, Bo>
    where D: digest::Input,
          Bo: ByteOrder
{
    type ByteOrder = Bo;
}

impl<D, Bo> digest::Input for Endian<D, Bo>
    where D: digest::Input
{
    fn process(&mut self, input: &[u8]) { self.inner.process(input) }
}

impl<D, Bo> digest::BlockInput for Endian<D, Bo>
    where D: digest::BlockInput
{
    type BlockSize = D::BlockSize;
}

impl<D, Bo> digest::FixedOutput for Endian<D, Bo>
    where D: digest::FixedOutput
{
    type OutputSize = D::OutputSize;

    fn fixed_result(self) -> GenericArray<u8, Self::OutputSize> {
        self.inner.fixed_result()
    }
}

impl<D, Bo> Endian<D, Bo>
    where D: digest::Input,
          D: Default,
          Bo: ByteOrder
{
    /// Constructs an instance of an endian-aware hasher.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate digest_hash;
    /// # extern crate sha2;
    /// # use sha2::Sha256;
    /// # fn main() {
    /// let hasher = digest_hash::BigEndian::<Sha256>::new();
    /// # }
    /// ```
    pub fn new() -> Self {
        Endian {
            inner: D::default(),
            phantom: marker::PhantomData
        }
    }
}

impl<D, Bo> Default for Endian<D, Bo>
    where D: digest::Input,
          D: Default,
          Bo: ByteOrder
{
    fn default() -> Self { Self::new() }
}

impl<D, Bo> From<D> for Endian<D, Bo>
    where D: digest::Input,
          Bo: ByteOrder
{
    fn from(digest: D) -> Self {
        Endian {
            inner: digest,
            phantom: marker::PhantomData
        }
    }
}

impl<D, Bo> Endian<D, Bo> {
    /// Consumes self and returns the underlying digest implementation.
    pub fn into_inner(self) -> D { self.inner }
}


#[cfg(test)]
mod tests {
    use {BigEndian, LittleEndian, NetworkEndian};
    use EndianInput;

    use testmocks::MockDigest;
    use testmocks::conv_with;

    use std::mem;
    use std::{f32, f64};

    #[test]
    fn default_works() {
        let _ = NetworkEndian::<MockDigest>::default();
    }

    macro_rules! test_endian_debug {
        (   $test:ident,
            $Endian:ident) =>
        {
            #[test]
            fn $test() {
                assert_eq!($Endian::<MockDigest>::byte_order_str(),
                            stringify!($Endian));
                let hasher = $Endian::<MockDigest>::new();
                let repr = format!("{:?}", hasher);
                assert!(repr.starts_with(stringify!($Endian)));
                assert!(repr.contains("MockDigest"));
                assert!(!repr.contains("PhantomData"));
            }
        }
    }

    test_endian_debug!(debug_be, BigEndian);
    test_endian_debug!(debug_le, LittleEndian);

    macro_rules! test_endian_input {
        (   $test:ident,
            $Endian:ident,
            $method:ident,
            $val:expr,
            $to_endian_bits:expr) =>
        {
            #[test]
            fn $test() {
                let mut hasher = $Endian::<MockDigest>::new();
                hasher.$method($val);
                let output = hasher.into_inner().bytes;
                let val_bits = conv_with($val, $to_endian_bits);
                let expected = bytes_from_endian!(val_bits);
                assert_eq!(output, expected);
            }
        }
    }

    macro_rules! test_byte_input {
        (   $be_test:ident,
            $le_test:ident,
            $method:ident,
            $val:expr) =>
        {
            test_endian_input!(
                $be_test, BigEndian, $method, $val,
                |v| { v });
            test_endian_input!(
                $le_test, LittleEndian, $method, $val,
                |v| { v });
        };
    }

    macro_rules! test_word_input {
        (   $be_test:ident,
            $le_test:ident,
            $method:ident,
            $val:expr) =>
        {
            test_word_input!(
                $be_test, $le_test, $method, $val,
                |v| { v });
        };

        (   $be_test:ident,
            $le_test:ident,
            $method:ident,
            $val:expr,
            $conv:expr) =>
        {
            test_endian_input!(
                $be_test, BigEndian, $method, $val,
                |v| { conv_with(v, $conv).to_be() });
            test_endian_input!(
                $le_test, LittleEndian, $method, $val,
                |v| { conv_with(v, $conv).to_le() });
        };
    }

    macro_rules! test_float_input {
        (   $be_test:ident,
            $le_test:ident,
            $method:ident,
            $val:expr) =>
        {
            test_word_input!(
                $be_test, $le_test, $method, $val,
                |v| { v.to_bits() });
        }
    }

    test_byte_input!(
            u8_be_input,  u8_le_input, process_u8, 0xA5u8);
    test_byte_input!(
            i8_be_input,  i8_le_input, process_i8, -128i8);
    test_word_input!(
        u16_be_input, u16_le_input, process_u16, 0xA55Au16);
    test_word_input!(
        i16_be_input, i16_le_input, process_i16, -0x7FFEi16);
    test_word_input!(
        u32_be_input, u32_le_input, process_u32, 0xA0B0_C0D0u32);
    test_word_input!(
        i32_be_input, i32_le_input, process_i32, -0x7F01_02FDi32);
    test_word_input!(
        u64_be_input, u64_le_input, process_u64, 0xA0B0_C0D0_0102_0304u64);
    test_word_input!(
        i64_be_input, i64_le_input, process_i64, -0x7F01_0203_0405_FFFDi64);
    test_float_input!(
        f32_be_input, f32_le_input, process_f32, f32::consts::PI);
    test_float_input!(
        f64_be_input, f64_le_input, process_f64, f64::consts::PI);
}