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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
//! Bindings to libxxhash, an xxHash implementation.
//!
//! This library contains safe Rust bindings to the libxxhash library which
//! contains an implementation of the xxHash algorithm. There are Rust
//! implementations available of this hash algorithm, but it is intended that
//! this library is a binding to the official C source.
//!
//! The xxHash algorith comes in 32 and 64 bit variants. reflected in the
//! exported types and functions of this crate.
//!
//! # Examples
//!
//! ```
//! assert_eq!(xxhash2::hash32(&[1, 2, 3, 4], 0), 4271296924);
//! assert_eq!(xxhash2::hash64(&[1, 2, 3, 4], 0), 6063570110359613137);
//!
//! let mut s = xxhash2::State32::new();
//! s.reset(0);
//! s.update(&[1, 2, 3, 4]);
//! assert_eq!(s.finish(), 4271296924);
//!
//! let mut s = xxhash2::State64::new();
//! s.reset(0);
//! s.update(&[1, 2, 3, 4]);
//! assert_eq!(s.finish(), 6063570110359613137);
//! ```

extern crate libc;
extern crate xxhash_sys;

use std::fmt;
use std::hash::Hasher;
use std::mem;

use libc::{size_t, c_void};

/// Representation of the intermediate state of a 32-bit xxHash instance.
///
/// This structure can be used to generate a 32-bit hash of a block of bytes.
pub struct State32 {
    inner: xxhash_sys::XXH32_stateBody_t,
}

/// Representation of the intermediate state of a 64-bit xxHash instance.
///
/// This structure can be used to generate a 64-bit hash of a block of bytes.
pub struct State64 {
    inner: xxhash_sys::XXH64_stateBody_t,
}

/// Canonical representation of a 32-bit hash.
///
/// This structure provides a conversion from a 32-bit hash value to a list of
/// bytes in a canonical format. Note that the bytes returned are not
/// necessarily hex.
pub struct Hash32 {
    inner: xxhash_sys::XXH32_canonical_t,
}

/// Canonical representation of a 64-bit hash.
///
/// This structure provides a conversion from a 64-bit hash value to a list of
/// bytes in a canonical format. Note that the bytes returned are not
/// necessarily hex.
pub struct Hash64 {
    inner: xxhash_sys::XXH64_canonical_t,
}

/// Hash a block of bytes with a given seed, returning the 32-bit hash.
///
/// This function, optimized for speed, will hash an entire block all at once
/// and return the hash value.
///
/// # Examples
///
/// ```
/// assert_eq!(xxhash2::hash32(&[1, 2, 3, 4], 0), 4271296924);
/// ```
pub fn hash32(data: &[u8], seed: u32) -> u32 {
    unsafe {
        xxhash_sys::XXH32(data.as_ptr() as *const c_void,
                          data.len() as size_t,
                          seed) as u32
    }
}

/// Hash a block of bytes with a given seed, returning the 64-bit hash.
///
/// This function, optimized for speed, will hash an entire block all at once
/// and return the hash value.
///
/// # Examples
///
/// ```
/// assert_eq!(xxhash2::hash64(&[1, 2, 3, 4], 0), 6063570110359613137);
/// ```
pub fn hash64(data: &[u8], seed: u64) -> u64 {
    unsafe {
        xxhash_sys::XXH64(data.as_ptr() as *const c_void,
                          data.len() as size_t,
                          seed) as u64
    }
}

impl State32 {
    /// Creates a new blank instance of the 32-bit xxHash state.
    ///
    /// This state can then be used to hash a list of bytes and acquire the
    /// result via the `finish` method.
    ///
    /// # Examples
    ///
    /// ```
    /// let state = xxhash2::State32::new();
    /// ```
    pub fn new() -> State32 {
        unsafe {
            State32 { inner: mem::zeroed() }
        }
    }

    /// Input a block of bytes into this hasher.
    ///
    /// This function will update the internal state of this hasher with a new
    /// list of bytes to feed in. To get the hash value of the block (and all
    /// previous bytes), call the `finish` function.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut state = xxhash2::State32::new();
    /// state.update(&[1, 2, 3, 4]);
    /// ```
    pub fn update(&mut self, data: &[u8]) {
        let r = unsafe {
            xxhash_sys::XXH32_update(self.inner(),
                                     data.as_ptr() as *const c_void,
                                     data.len() as size_t)
        };
        assert_eq!(r, xxhash_sys::XXH_OK);
    }

    /// Reset the internal state of this hasher with a given seed.
    ///
    /// This is useful to reuse a hasher or to persist the state across
    /// multiple runs of a hasher.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut state = xxhash2::State32::new();
    /// state.update(&[1, 2, 3, 4]);
    /// ```
    pub fn reset(&mut self, seed: u32) {
        let r = unsafe {
            xxhash_sys::XXH32_reset(self.inner(), seed)
        };
        assert_eq!(r, xxhash_sys::XXH_OK);
    }

    /// Computes the final hash result of all bytes that have been input to
    /// this hasher.
    ///
    /// Returns the 32-bit checksum of the result.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut state = xxhash2::State32::new();
    /// state.update(&[1, 2, 3, 4]);
    /// assert_eq!(state.finish(), 4271296924);
    /// ```
    pub fn finish(&self) -> u32 {
        unsafe {
            xxhash_sys::XXH32_digest(&self.inner as *const _ as *const _)
        }
    }

    fn inner(&mut self) -> *mut xxhash_sys::XXH32_state_t {
        &mut self.inner as *mut _ as *mut _
    }
}

impl Hasher for State32 {
    fn write(&mut self, data: &[u8]) {
        self.update(data)
    }

    fn finish(&self) -> u64 {
        self.finish() as u64
    }
}

impl Clone for State32 {
    fn clone(&self) -> State32 {
        State32 { inner: self.inner }
    }
}

impl Default for State32 {
    fn default() -> State32 {
        State32::new()
    }
}

impl State64 {
    /// Creates a new blank instance of the 64-bit xxHash state.
    ///
    /// This state can then be used to hash a list of bytes and acquire the
    /// result via the `finish` method.
    ///
    /// # Examples
    ///
    /// ```
    /// let state = xxhash2::State64::new();
    /// ```
    pub fn new() -> State64 {
        unsafe {
            State64 { inner: mem::zeroed() }
        }
    }

    /// Input a block of bytes into this hasher.
    ///
    /// This function will update the internal state of this hasher with a new
    /// list of bytes to feed in. To get the hash value of the block (and all
    /// previous bytes), call the `finish` function.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut state = xxhash2::State64::new();
    /// state.update(&[1, 2, 3, 4]);
    /// ```
    pub fn update(&mut self, data: &[u8]) {
        let r = unsafe {
            xxhash_sys::XXH64_update(self.inner(),
                                     data.as_ptr() as *const c_void,
                                     data.len() as size_t)
        };
        assert_eq!(r, xxhash_sys::XXH_OK);
    }

    /// Reset the internal state of this hasher with a given seed.
    ///
    /// This is useful to reuse a hasher or to persist the state across
    /// multiple runs of a hasher.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut state = xxhash2::State64::new();
    /// state.update(&[1, 2, 3, 4]);
    /// ```
    pub fn reset(&mut self, seed: u64) {
        let r = unsafe {
            xxhash_sys::XXH64_reset(self.inner(), seed)
        };
        assert_eq!(r, xxhash_sys::XXH_OK);
    }

    /// Computes the final hash result of all bytes that have been input to
    /// this hasher.
    ///
    /// Returns the 64-bit checksum of the result.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut state = xxhash2::State64::new();
    /// state.update(&[1, 2, 3, 4]);
    /// assert_eq!(state.finish(), 6063570110359613137);
    /// ```
    pub fn finish(&self) -> u64 {
        unsafe {
            xxhash_sys::XXH64_digest(&self.inner as *const _ as *const _)
        }
    }

    fn inner(&mut self) -> *mut xxhash_sys::XXH64_state_t {
        &mut self.inner as *mut _ as *mut _
    }
}

impl Hasher for State64 {
    fn write(&mut self, data: &[u8]) {
        self.update(data)
    }

    fn finish(&self) -> u64 {
        self.finish()
    }
}

impl Clone for State64 {
    fn clone(&self) -> State64 {
        State64 { inner: self.inner }
    }
}

impl Default for State64 {
    fn default() -> State64 {
        State64::new()
    }
}

impl Hash32 {
    /// Returns the underlying hash as a list of bytes in a canonical
    /// representation.
    pub fn bytes(&self) -> &[u8; 4] {
        &self.inner.digest
    }

    /// Returns this canonical hash value as a 32-bit integer.
    ///
    /// Converts from the underlying list of bytes to an integer.
    pub fn value(&self) -> u32 {
        unsafe {
            xxhash_sys::XXH32_hashFromCanonical(&self.inner)
        }
    }
}

impl From<u32> for Hash32 {
    /// Creates a new canonical representation of a 32-bit hash value.
    ///
    /// The returned value can be viewed as a list of bytes.
    fn from(val: u32) -> Hash32 {
        unsafe {
            let mut ret = Hash32 { inner: mem::zeroed() };
            xxhash_sys::XXH32_canonicalFromHash(&mut ret.inner, val);
            return ret
        }
    }
}

impl From<[u8; 4]> for Hash32 {
    /// Creates a new canonical representation of a hash from the 4-byte
    /// canonical representation.
    ///
    /// The returned value can be viewed as a `u32`.
    fn from(val: [u8; 4]) -> Hash32 {
        Hash32 { inner: xxhash_sys::XXH32_canonical_t { digest: val } }
    }
}

impl fmt::Debug for Hash32 {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.inner.digest.fmt(f)
    }
}

impl Hash64 {
    /// Returns the underlying hash as a list of bytes in a canonical
    /// representation.
    pub fn bytes(&self) -> &[u8; 8] {
        &self.inner.digest
    }

    /// Returns this canonical hash value as a 64-bit integer.
    ///
    /// Converts from the underlying list of bytes to an integer.
    pub fn value(&self) -> u64 {
        unsafe {
            xxhash_sys::XXH64_hashFromCanonical(&self.inner)
        }
    }
}

impl From<u64> for Hash64 {
    /// Creates a new canonical representation of a 64-bit hash value.
    ///
    /// The returned value can be viewed as a list of bytes.
    fn from(val: u64) -> Hash64 {
        unsafe {
            let mut ret = Hash64 { inner: mem::zeroed() };
            xxhash_sys::XXH64_canonicalFromHash(&mut ret.inner, val);
            return ret
        }
    }
}

impl From<[u8; 8]> for Hash64 {
    /// Creates a new canonical representation of a hash from the 8-byte
    /// canonical representation.
    ///
    /// The returned value can be viewed as a `u64`.
    fn from(val: [u8; 8]) -> Hash64 {
        Hash64 { inner: xxhash_sys::XXH64_canonical_t { digest: val } }
    }
}

impl fmt::Debug for Hash64 {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.inner.digest.fmt(f)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn test32(data: &[u8], seed: u32, expected: u32) {
        assert_eq!(hash32(data, seed), expected);
        let mut state = State32::new();
        state.reset(seed);
        state.update(data);
        assert_eq!(state.finish(), expected);
        assert_eq!(state.finish(), expected);

        state.reset(seed);
        for i in 0..data.len() {
            state.update(&data[i..i+1]);
        }
        assert_eq!(state.finish(), expected);
    }

    fn test64(data: &[u8], seed: u64, expected: u64) {
        assert_eq!(hash64(data, seed), expected);
        let mut state = State64::new();
        state.reset(seed);
        state.update(data);
        assert_eq!(state.finish(), expected);
        assert_eq!(state.finish(), expected);

        state.reset(seed);
        for i in 0..data.len() {
            state.update(&data[i..i+1]);
        }
        assert_eq!(state.finish(), expected);
    }

    #[test]
    fn smoke() {
        test32(&[], 0, 46947589);
        test64(&[], 0, 17241709254077376921);
        test32(&[1], 0, 949155633);
        test64(&[1], 0, 9962287286179718960);
        test32(&[1, 2, 3, 4], 0, 4271296924);
        test64(&[1, 2, 3, 4], 0, 6063570110359613137);
    }

    #[test]
    fn hash() {
        assert_eq!(Hash32::from(0).bytes(), &[0, 0, 0, 0]);
        assert_eq!(Hash32::from(0).value(), 0);
        assert_eq!(Hash32::from(0x12345678).bytes(), &[0x12, 0x34, 0x56, 0x78]);
        assert_eq!(Hash32::from(0x12345678).value(), 0x12345678);
        assert_eq!(Hash64::from(0).bytes(), &[0, 0, 0, 0, 0, 0, 0, 0]);
        assert_eq!(Hash64::from(0).value(), 0);
        assert_eq!(Hash64::from(0x12345678).bytes(),
                   &[0, 0, 0, 0, 0x12, 0x34, 0x56, 0x78]);
        assert_eq!(Hash64::from(0x12345678).value(), 0x12345678);
    }
}