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
use core::hash::{Hash, Hasher};
use core::mem::size_of;
use crate::buf::{Buf, OwnedBuf, StoreBuf, Visit};
use crate::endian::ByteOrder;
use crate::error::Error;
use crate::pointer::{Ref, Size};
use crate::sip::SipHasher13;
use crate::swiss::constructor::Constructor;
use crate::swiss::map::RawTableRef;
use crate::swiss::raw::{self};
use crate::swiss::{Entry, MapRef, SetRef};
use crate::ZeroCopy;
const FIXED_SEED: u64 = 1234567890;
/// Store a [SwissTable] map into an [`OwnedBuf`].
///
/// This returns a [`MapRef`] which can be bound into a [`Map`] through the
/// [`bind()`] method for convenience.
///
/// See the [module level documentation] for more information.
///
/// [`bind()`]: crate::buf::Buf::bind
/// [`Map`]: crate::swiss::Map
/// [SwissTable]: https://abseil.io/about/design/swisstables
/// [module level documentation]: crate::swiss
///
/// # Duplicates
///
/// The caller is responsible for ensuring that no duplicate keys are provided
/// to the constructor, since the input will be used to size the table.
///
/// In the face of duplicate keys, the default accessor will return a random
/// element and the table will waste space.
///
/// Technically the elements are stored so the length is affected, and a future
/// update might make them available.
///
/// ```
/// use musli_zerocopy::OwnedBuf;
/// use musli_zerocopy::swiss;
///
/// let mut buf = OwnedBuf::new();
///
/// let map = swiss::store_map(&mut buf, [(10, 1u32), (10, 2u32)])?;
/// let map = buf.bind(map)?;
///
/// assert!(matches!(map.get(&10)?, Some(&1) | Some(&2)));
/// assert_eq!(map.len(), 2);
/// # Ok::<_, musli_zerocopy::Error>(())
/// ```
///
/// # Examples
///
/// ```
/// use musli_zerocopy::OwnedBuf;
/// use musli_zerocopy::swiss;
///
/// let mut buf = OwnedBuf::new();
///
/// let pairs = [
/// (buf.store_unsized("first"), 1u32),
/// (buf.store_unsized("second"), 2u32),
/// ];
///
/// let map = swiss::store_map(&mut buf, pairs)?;
/// let map = buf.bind(map)?;
///
/// assert_eq!(map.get("first")?, Some(&1));
/// assert_eq!(map.get("second")?, Some(&2));
/// assert_eq!(map.get("third")?, None);
/// # Ok::<_, musli_zerocopy::Error>(())
/// ```
///
/// Using non-references as keys:
///
/// ```
/// use musli_zerocopy::OwnedBuf;
/// use musli_zerocopy::swiss;
///
/// let mut buf = OwnedBuf::new();
///
/// let map = swiss::store_map(&mut buf, [(10u64, 1u32), (20u64, 2u32)])?;
/// let map = buf.bind(map)?;
///
/// assert_eq!(map.get(&10u64)?, Some(&1));
/// assert_eq!(map.get(&20u64)?, Some(&2));
/// assert_eq!(map.get(&30u64)?, None);
/// # Ok::<_, musli_zerocopy::Error>(())
/// ```
///
/// Storing a zero-sized type:
///
/// ```
/// use musli_zerocopy::OwnedBuf;
/// use musli_zerocopy::swiss;
///
/// let mut buf = OwnedBuf::new();
///
/// let map = swiss::store_map(&mut buf, [((), ()), ((), ())])?;
/// let map = buf.bind(map)?;
///
/// assert_eq!(map.get(&())?, Some(&()));
/// # Ok::<_, musli_zerocopy::Error>(())
/// ```
pub fn store_map<K, V, I, E: ByteOrder, O: Size>(
buf: &mut OwnedBuf<E, O>,
entries: I,
) -> Result<MapRef<K, V, E, O>, Error>
where
K: Visit + ZeroCopy,
V: ZeroCopy,
K::Target: Hash,
I: IntoIterator<Item = (K, V)>,
I::IntoIter: ExactSizeIterator,
{
let (key, ctrl, buckets, bucket_mask, len) = store_raw(entries, buf, |buf, (k, v), hasher| {
k.visit(buf, |key| key.hash(hasher))?;
Ok(Entry::new(k, v))
})?;
Ok(MapRef::new(
key,
RawTableRef::new(ctrl, buckets, bucket_mask, len),
))
}
/// Store a [SwissTable] set into an [`OwnedBuf`].
///
/// This returns a [`SetRef`] which can be bound into a [`Set`] through the
/// [`bind()`] method for convenience.
///
/// See the [module level documentation] for more information.
///
/// [`bind()`]: crate::buf::Buf::bind
/// [`Set`]: crate::swiss::Set
/// [SwissTable]: https://abseil.io/about/design/swisstables
/// [module level documentation]: crate::swiss
///
/// # Duplicates
///
/// The caller is responsible for ensuring that no duplicate values are provided
/// to the constructor, since the input will be used to size the table.
///
/// In the face of duplicate values, one of the entries will be preserved at
/// random and the table will waste space.
///
/// # Examples
///
/// ```
/// use musli_zerocopy::OwnedBuf;
/// use musli_zerocopy::swiss;
///
/// let mut buf = OwnedBuf::new();
///
/// let first = buf.store_unsized("first");
/// let second = buf.store_unsized("second");
/// let third = buf.store_unsized("third");
///
/// let set = swiss::store_set(&mut buf, [first, second])?;
/// let set = buf.bind(set)?;
///
/// assert!(set.contains("first")?);
/// assert!(set.contains(&first)?);
/// assert!(set.contains("second")?);
/// assert!(set.contains(&second)?);
/// assert!(!set.contains("third")?);
/// assert!(!set.contains(&third)?);
/// # Ok::<_, musli_zerocopy::Error>(())
/// ```
///
/// Using non-references as keys:
///
/// ```
/// use musli_zerocopy::OwnedBuf;
/// use musli_zerocopy::swiss;
///
/// let mut buf = OwnedBuf::new();
///
/// let set = swiss::store_set(&mut buf, [1, 2])?;
/// let set = buf.bind(set)?;
///
/// assert!(set.contains(&1)?);
/// assert!(set.contains(&2)?);
/// assert!(!set.contains(&3)?);
/// # Ok::<_, musli_zerocopy::Error>(())
/// ```
///
/// Storing a zero-sized type:
///
/// ```
/// use musli_zerocopy::OwnedBuf;
/// use musli_zerocopy::swiss;
///
/// let mut buf = OwnedBuf::new();
///
/// let set = swiss::store_set(&mut buf, [(), ()])?;
/// let set = buf.bind(set)?;
///
/// assert!(set.contains(&())?);
/// # Ok::<_, musli_zerocopy::Error>(())
/// ```
pub fn store_set<T, I, S>(
buf: &mut S,
entries: I,
) -> Result<SetRef<T, S::ByteOrder, S::Size>, Error>
where
T: Visit + ZeroCopy,
T::Target: Hash,
I: IntoIterator<Item = T>,
I::IntoIter: ExactSizeIterator,
S: ?Sized + StoreBuf,
{
let (key, ctrl, buckets, bucket_mask, len) = store_raw(entries, buf, |buf, v, hasher| {
v.visit(buf, |key| key.hash(hasher))?;
Ok(v)
})?;
Ok(SetRef::new(
key,
RawTableRef::new(ctrl, buckets, bucket_mask, len),
))
}
// Output from storing raw values.
type Raw<U, E, O> = (u64, Ref<[u8], E, O>, Ref<[U], E, O>, usize, usize);
// Raw store function which is capable of storing any value using a hashing
// adapter.
fn store_raw<T, U, I, S>(
entries: I,
buf: &mut S,
hash: fn(&Buf, T, &mut SipHasher13) -> Result<U, Error>,
) -> Result<Raw<U, S::ByteOrder, S::Size>, Error>
where
U: ZeroCopy,
I: IntoIterator<Item = T>,
I::IntoIter: ExactSizeIterator,
S: ?Sized + StoreBuf,
{
let entries = entries.into_iter();
let key = FIXED_SEED;
let Some(buckets) = raw::capacity_to_buckets(entries.len()) else {
panic!("Capacity overflow");
};
let ctrl_len = buckets + size_of::<raw::Group>();
let ctrl_align = raw::Group::WIDTH;
debug_assert!(ctrl_align.is_power_of_two());
buf.next_offset_with_and_reserve(ctrl_align, ctrl_len);
let ctrl_ptr = buf.len();
// All ones indicates that the table is empty, since the ctrl byte for empty
// buckets is 1111_1111.
buf.fill(raw::EMPTY, ctrl_len + size_of::<raw::Group>());
let base_ptr = buf.next_offset::<U>();
buf.fill(0, size_of::<T>().wrapping_mul(buckets));
let (bucket_mask, len) = {
buf.align_in_place();
let mut table = Constructor::<U, _>::with_buf(buf, ctrl_ptr, base_ptr, buckets);
for v in entries {
let mut hasher = SipHasher13::new_with_keys(0, key);
let v = hash(table.buf(), v, &mut hasher)?;
let hash = hasher.finish();
table.insert(hash, &v)?;
}
(table.bucket_mask(), table.len())
};
let ctrl = Ref::with_metadata(ctrl_ptr, ctrl_len);
let buckets = Ref::with_metadata(base_ptr, buckets);
Ok((key, ctrl, buckets, bucket_mask, len))
}