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
//! A hash-set analogue that does not own its data.
//!
//! It can be used to "mark" items without the need to transfer ownership to the map
//!
//! # Example use case
//! ```
//! # use refset::HashRefSet;
//! /// Process arguments while ignoring duplicates
//! fn process_args(args: impl IntoIterator<Item=String>) {
//!   let mut same=  HashRefSet::new();
//!   for argument in args.into_iter()
//!   {
//!     if !same.insert(argument.as_str()) {
//!       // Already processed this input, ignore
//!       continue;
//!     }
//!     //do work...
//!   }
//! }
//! ```
//! # Serialisation support with `serde` crate
//! `HashRefSet` and `HashType` both implement `Serialize` and `Deserialize` from the `serde` crate if the `serde` feature is enabled. By default it is not.
//! # Drawbacks
//! Since the item is not inserted itself, we cannot use `Eq` to double check there was not a hash collision.
//! While the hashing algorithm used (Sha512) is extremely unlikely to produce collisions, especially for small data types, keep in mind that it is not infallible.

#![cfg_attr(nightly, feature(test))] 
#[cfg(nightly)] extern crate test;

use std::{
    collections::{
	hash_set,
	HashSet,
    },
    marker::{
	PhantomData,
	Send,
	Sync,
    },
    hash::Hash,
    borrow::Borrow,
};

mod hashing;

#[cfg(feature="smallmap")] pub mod small;

/// The type used to store the hash of each item.
///
/// It is a result of the `SHA512` algorithm as a newtype 64 byte array marked with `#[repr(transparent)]`.
/// If you want to get the bytes from it, you can transmute safely.
/// ```
/// # use refset::HashType;
/// fn hash_bytes(hash: HashType) -> [u8; 64]
/// {
///   unsafe {
///     std::mem::transmute(hash)
///   }
/// }
///
/// fn hash_bytes_assert()
/// {
///   assert_eq!(hash_bytes(Default::default()), [0u8; 64]);
/// }
/// ```
pub type HashType = hashing::Sha512Hash;

/// Compute the `HashType` value for this `T`.
fn compute_hash_for<T: ?Sized + Hash>(value: &T)  -> HashType
{
    let mut hasher = hashing::Sha512Hasher::new();
    value.hash(&mut hasher);
    hasher.finalize()
}

#[allow(dead_code)]
#[cold] fn compute_both_hash_for<T: ?Sized + Hash>(value: &T)  -> (u64, HashType)
{
    use sha2::{
	Digest,
	digest::generic_array::sequence::Split,
    };
    let mut hasher = hashing::Sha512Hasher::new();
    value.hash(&mut hasher);
    let sha512 = hasher.into_inner();

    let full = sha512.finalize();

    let mut arr = [0u8; hashing::HASH_SIZE];
    debug_assert_eq!(arr.len(), full.len());
    unsafe {
	std::ptr::copy_nonoverlapping(&full[0] as *const u8, &mut arr[0] as *mut u8, hashing::HASH_SIZE);
    }
    (u64::from_ne_bytes(full.split().0.into()), HashType::from_bytes(arr))
}

/// A hash-set of references to an item.
///
/// Instead of inserting the item into the set, the set is "marked" with the item.
/// Think of this as inserting a reference into the set with no lifetime.
///
/// Any type that can borrow to `T` can be used to insert, and neither type needs to be `Sized`.
/// `T` need only implement `Hash`.
///
/// # Hashing algorithm
/// The hasing algorithm used is `Sha512`, which is rather large (64 bytes).
/// At present there is no way to change the hasher used, I might implement that functionality in the future.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature="serde", derive(serde::Serialize, serde::Deserialize))] 
pub struct HashRefSet<T: ?Sized>(HashSet<HashType>, PhantomData<HashSet<*const T>>);

unsafe impl<T: ?Sized + Send> Send for HashRefSet<T>{}
unsafe impl<T: ?Sized + Send + Sync> Sync for HashRefSet<T>{}

impl<T:?Sized + Hash> HashRefSet<T>
{
    /// Create a new empty `HashRefSet`
    pub fn new() -> Self
    {
	Self(
	    HashSet::new(),
	    PhantomData
	)
    }
    /// Consume into the inner `HashSet`.
    pub fn into_inner(self) -> HashSet<HashType>
    {
	self.0
    }
    /// Create a new `HashRefSet` with a capacity
    pub fn with_capacity(cap: usize) -> Self
    {
	Self(HashSet::with_capacity(cap), PhantomData)
    }

    /// Insert a reference into the set. The reference can be any type that borrows to `T`.
    ///
    /// Returns `true` if there was no previous item, `false` if there was.
    pub fn insert<Q>(&mut self, value: &Q) -> bool
    where Q: ?Sized + Borrow<T>
    {
	self.0.insert(compute_hash_for(value.borrow()))
    }

    /// Remove a reference from the set.
    ///
    /// Returns `true` if it existed.
    pub fn remove<Q>(&mut self, value: &Q) -> bool
    where Q: ?Sized + Borrow<T>
    {
	self.0.remove(&compute_hash_for(value.borrow()))
    }

    /// Check if this value has been inserted into the set.
    pub fn contains<Q>(&mut self, value: &Q) -> bool
    where Q: ?Sized + Borrow<T>
    {
	self.0.contains(&compute_hash_for(value.borrow()))
    }

    /// The number of items stored in the set
    pub fn len(&self) -> usize
    {
	self.0.len()
    }

    /// Is the set empty
    pub fn is_empty(&self) -> bool
    {
	self.0.is_empty()
    }

    /// An iterator over the hashes stored in the set.
    pub fn hashes_iter(&self) -> hash_set::Iter<'_, HashType>
    {
	self.0.iter()
    }

    #[inline] fn into_hashes_iter(self) -> hash_set::IntoIter<HashType>
    {
	self.0.into_iter()
    }
}

impl<T: ?Sized + Hash> IntoIterator for HashRefSet<T>
{
    type Item= HashType;
    type IntoIter = hash_set::IntoIter<HashType>;

    #[inline] fn into_iter(self) -> Self::IntoIter
    {
	self.into_hashes_iter()
    }
}


#[cfg(test)]
mod tests
{
    use super::*;
    #[test]
    fn insert()
    {
	let mut refset = HashRefSet::new();

	let values=  vec![
	    "hi",
	    "hello",
	    "one",
	    "two",
	];
	for &string in values.iter()
	{
	    refset.insert(string);
	}

	for string in values
	{
	    assert!(refset.contains(string));
	}

	assert!(refset.insert("none"));
	assert!(!refset.insert("two"));
    }

    #[cfg(nightly)]
    mod benchmarks
    {
	use test::{black_box, Bencher};
	const STRINGS: &str = "leo vel fringilla est ullamcorper eget nulla facilisi etiam dignissim diam quis enim lobortis scelerisque fermentum dui faucibus in ornare quam viverra orci sagittis eu volutpat odio facilisis mauris sit amet massa vitae tortor condimentum lacinia quis vel eros donec ac odio tempor orci dapibus ultrices in iaculis nunc sed augue lacus viverra vitae congue eu consequat ac felis donec et odio pellentesque diam volutpat commodo sed egestas egestas fringilla phasellus faucibus scelerisque eleifend donec pretium vulputate sapien nec sagittis aliquam malesuada bibendum arcu vitae elementum curabitur vitae nunc sed velit dignissim sodales ut eu sem integer vitae justo eget";
	const INTS: &[u32] = &[182,248,69,225,164,219,73,122,14,205,148,221,24,107,209,83,210,87,148,249,234,181,217,154,180,240,132,145,208,15,77,4,117,16,43,1,95,49,150,18,207,161,107,216,215,100,76,198,43,21,99,177,77,28,29,172,117,136,151,96,66,208,244,138,90];
	
	#[bench] fn non_owning_strings(b: &mut Bencher)
	{
	    let strings: Vec<String> = STRINGS.split(char::is_whitespace).map(ToOwned::to_owned).collect();
	    let mut map = super::HashRefSet::new();
	    b.iter(|| {
		for string in strings.iter() {
		    black_box(map.insert(string.as_str()));
		}
	    })
	}
	#[bench] fn owning_strings(b: &mut Bencher)
	{
	    let strings: Vec<String> = STRINGS.split(char::is_whitespace).map(ToOwned::to_owned).collect();
	    let mut map = std::collections::HashSet::new();
	    b.iter(|| {
		for string in strings.iter() {
		    black_box(map.insert(string.clone())); //clone is needed here :/
		}
	    })
	}
	
	#[bench] fn non_owning_ints(b: &mut Bencher)
	{
	    let mut map = super::HashRefSet::new();
	    b.iter(|| {
		for int in INTS.iter() {
		    black_box(map.insert(int));
		}
	    })
	}
	#[bench] fn owning_ints(b: &mut Bencher)
	{
	    let mut map = std::collections::HashSet::new();
	    b.iter(|| {
		for int in INTS.iter() {
		    black_box(map.insert(int));
		}
	    })
	}
    }
}