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
use std::ops::BitXor;

use error::{LengthError, LengthResult, LengthErrorKind};

mod builder;

pub use sha::builder::ShaHashBuilder;

/// Length of a SHA-1 hash.
pub const SHA_HASH_LEN: usize = 20;

/// SHA-1 hash wrapper type for performing operations on the hash.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
pub struct ShaHash {
    hash: [u8; SHA_HASH_LEN],
}

impl ShaHash {
    /// Create a ShaHash by hashing the given bytes.
    pub fn from_bytes(bytes: &[u8]) -> ShaHash {
        ShaHashBuilder::new().add_bytes(bytes).build()
    }

    /// Create a ShaHash directly from the given hash.
    pub fn from_hash(hash: &[u8]) -> LengthResult<ShaHash> {
        if hash.len() != SHA_HASH_LEN {
            Err(LengthError::new(LengthErrorKind::LengthExpected, SHA_HASH_LEN))
        } else {
            let mut my_hash = [0u8; SHA_HASH_LEN];

            my_hash.iter_mut().zip(hash.iter()).map(|(dst, src)| *dst = *src).count();

            Ok(ShaHash { hash: my_hash })
        }
    }

    pub fn bits<'a>(&'a self) -> Bits<'a> {
        Bits::new(&self.hash)
    }

    pub fn len() -> usize {
        SHA_HASH_LEN
    }
}

impl AsRef<[u8]> for ShaHash {
    fn as_ref(&self) -> &[u8] {
        &self.hash
    }
}

impl Into<[u8; SHA_HASH_LEN]> for ShaHash {
    fn into(self) -> [u8; SHA_HASH_LEN] {
        self.hash
    }
}

impl From<[u8; SHA_HASH_LEN]> for ShaHash {
    fn from(sha_hash: [u8; SHA_HASH_LEN]) -> ShaHash {
        ShaHash { hash: sha_hash }
    }
}

impl PartialEq<[u8]> for ShaHash {
    fn eq(&self, other: &[u8]) -> bool {
        let is_equal = other.len() == self.hash.len();

        self.hash.iter().zip(other.iter()).fold(is_equal, |prev, (h, o)| prev && h == o)
    }
}

impl BitXor<ShaHash> for ShaHash {
    type Output = ShaHash;

    fn bitxor(mut self, rhs: ShaHash) -> ShaHash {
        for (src, dst) in rhs.hash.iter().zip(self.hash.iter_mut()) {
            *dst = *src ^ *dst;
        }

        self
    }
}

// ----------------------------------------------------------------------------//

/// Representation of a bit after a xor operation.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub enum XorRep {
    /// Bits were equal (1).
    Diff,
    /// Bits were not equal (0).
    Same,
}

/// Iterator over the bits of a xor operation.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct XorBits<'a> {
    bits: Bits<'a>,
}

impl<'a> Iterator for XorBits<'a> {
    type Item = XorRep;

    fn next(&mut self) -> Option<XorRep> {
        self.bits.next().map(|n| {
            match n {
                BitRep::Set => XorRep::Diff,
                BitRep::Unset => XorRep::Same,
            }
        })
    }
}

// ----------------------------------------------------------------------------//

/// Representation of a bit.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub enum BitRep {
    /// Bit is set (1).
    Set,
    /// Bit is not set (0).
    Unset,
}

impl PartialEq<XorRep> for BitRep {
    fn eq(&self, other: &XorRep) -> bool {
        match (self, other) {
            (&BitRep::Set, &XorRep::Diff) => true,
            (&BitRep::Unset, &XorRep::Same) => true,
            _ => false,
        }
    }
}

/// Iterator over some bits.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct Bits<'a> {
    bytes: &'a [u8],
    bit_pos: usize,
}

impl<'a> Bits<'a> {
    fn new(bytes: &'a [u8]) -> Bits<'a> {
        Bits {
            bytes: bytes,
            bit_pos: 0,
        }
    }
}

impl<'a> Iterator for Bits<'a> {
    type Item = BitRep;

    fn next(&mut self) -> Option<BitRep> {
        if self.bit_pos < self.bytes.len() * 8 {
            let byte_index = self.bit_pos / 8;
            let bit_offset = 7 - (self.bit_pos % 8);
            let bit_value = self.bytes[byte_index] >> bit_offset;

            self.bit_pos += 1;

            Some(bit_value).map(|x| if x == 1 {
                BitRep::Set
            } else {
                BitRep::Unset
            })
        } else {
            None
        }
    }
}

// ----------------------------------------------------------------------------//

#[cfg(test)]
mod tests {
    use super::{ShaHash, XorRep};

    #[test]
    fn positive_no_leading_zeroes() {
        let zero_bits = ShaHash::from([0u8; super::SHA_HASH_LEN]);
        let one_bits = ShaHash::from([255u8; super::SHA_HASH_LEN]);

        let xor_hash = zero_bits ^ one_bits;

        let leading_zeroes = xor_hash.bits().take_while(|&n| n == XorRep::Same).count();
        assert!(leading_zeroes == 0);
    }

    #[test]
    fn positive_all_leading_zeroes() {
        let first_one_bits = ShaHash::from([255u8; super::SHA_HASH_LEN]);
        let second_one_bits = ShaHash::from([255u8; super::SHA_HASH_LEN]);

        let xor_hash = first_one_bits ^ second_one_bits;

        let leading_zeroes = xor_hash.bits().take_while(|&n| n == XorRep::Same).count();
        assert!(leading_zeroes == (super::SHA_HASH_LEN * 8));
    }

    #[test]
    fn positive_one_leading_zero() {
        let zero_bits = ShaHash::from([0u8; super::SHA_HASH_LEN]);

        let mut bytes = [255u8; super::SHA_HASH_LEN];
        bytes[0] = 127;
        let mostly_one_bits = ShaHash::from(bytes);

        let xor_hash = zero_bits ^ mostly_one_bits;

        let leading_zeroes = xor_hash.bits().take_while(|&n| n == XorRep::Same).count();
        assert!(leading_zeroes == 1);
    }

    #[test]
    fn positive_one_trailing_zero() {
        let zero_bits = ShaHash::from([0u8; super::SHA_HASH_LEN]);

        let mut bytes = [255u8; super::SHA_HASH_LEN];
        bytes[super::SHA_HASH_LEN - 1] = 254;
        let mostly_zero_bits = ShaHash::from(bytes);

        let xor_hash = zero_bits ^ mostly_zero_bits;

        let leading_zeroes = xor_hash.bits().take_while(|&n| n == XorRep::Same).count();
        assert!(leading_zeroes == 0);
    }

    #[test]
    #[should_panic]
    fn negative_from_hash_too_long() {
        let bits = [0u8; super::SHA_HASH_LEN + 1];

        ShaHash::from_hash(&bits).unwrap();
    }

    #[test]
    #[should_panic]
    fn negative_from_hash_too_short() {
        let bits = [0u8; super::SHA_HASH_LEN - 1];

        ShaHash::from_hash(&bits).unwrap();
    }
}