Skip to main content

ghast_world/
shared.rs

1//! [`SharedChunks`]: one copy of identical chunk sections for many worlds in one process.
2
3use std::sync::Arc;
4
5#[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
6use crate::paletted::{Ident, Section, VOLUME, WeakSection};
7#[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
8use std::collections::HashMap;
9#[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
10use std::hash::{BuildHasher, BuildHasherDefault, Hasher, RandomState};
11#[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
12use std::sync::{Mutex, MutexGuard, PoisonError, Weak};
13
14/// A process-wide store that lets the worlds of many bots hold **one** copy of each identical
15/// chunk section (16×16×16 blocks) instead of one copy per bot.
16///
17/// Bots standing in the same area receive the same chunks, and at view distance 10 a world's
18/// section storage is almost all of a bot's memory. Give the same handle to every
19/// [`Client`](https://docs.rs/ghast-client/latest/ghast_client/struct.Client.html) (its
20/// `shared_chunks` option) or to every world ([`v26_1::World::set_shared_chunks`]) and the
21/// section storage is held once per distinct section.
22///
23/// - **Opt-in.** A world without a handle stores its sections exactly as before.
24/// - **Per section, copy on write, and shared again.** A shared section is immutable and
25///   reference counted. A block change (a server block update or a local
26///   [`set_block_state`]) never touches storage another world can read: the changing world
27///   moves to the section with the new content, which is looked up in the store first and
28///   only copied when no world holds it yet. So bots that receive the same block updates keep
29///   holding one copy, and no world ever sees another world's packets: every world reads
30///   exactly the blocks its own packets produced.
31/// - **Whole columns too.** The per-column array of section handles is shared the same way
32///   between worlds whose columns hold the same sections.
33/// - **Reads do not change.** A block read is the same match and the same pointer hops as an
34///   unshared section: no lock, no atomic, no extra indirection. The handle's lock is taken
35///   while a chunk packet is applied (once per column that is already in the store), for a
36///   block change in a shared section, and when the last holder of a section drops it.
37/// - **Decoded once.** A section's key is a 128-bit keyed hash of its exact bytes in the chunk
38///   packet, found with a cheap skip pass; on a hit the section is not decoded at all.
39/// - **Freed with the last holder.** The store holds weak references only: when the last
40///   world unloads a section (chunk unload, a later full chunk for the same column, a
41///   dimension change, a dropped world, a block change) its memory is freed and its entry is
42///   removed at once.
43///
44/// What is shared: the block states of non-uniform sections and the columns' section arrays.
45/// Uniform sections (all air, all stone) take no heap memory and are kept inline as before.
46/// Biomes (off by default in the client, at most 128 bytes per section) and block entities
47/// stay per world; the modern worlds do not keep light. Only the modern worlds (26.1 – 26.3)
48/// use the store: the 1.8.9, 1.12.2 and 1.16.5 worlds ignore it (their sections are
49/// byte-per-block and are not shared). Worlds of different protocols can share one handle;
50/// their sections never mix.
51///
52/// A section that changed is found again by its *content*: its key is the XOR, over the 4096
53/// blocks, of a keyed 128-bit hash of (protocol, block index, state), so a block change moves
54/// the key by two hashes and the order of the changes does not matter. A section a world
55/// decoded without a store, or changed while it had none, stays that world's own.
56///
57/// The handle is cheap to clone (`Arc`) and `Send + Sync`: bots on different threads (for
58/// example on the workers of a `Swarm`) can share it.
59///
60/// [`v26_1::World::set_shared_chunks`]: crate::v26_1::World::set_shared_chunks
61/// [`set_block_state`]: crate::v26_1::World::set_block_state
62///
63/// ```
64/// let cache = ghast_world::SharedChunks::new();
65/// let for_second_bot = cache.clone();
66/// assert_eq!(cache.sections(), 0);
67/// # drop(for_second_bot);
68/// ```
69#[derive(Clone, Default)]
70pub struct SharedChunks {
71    inner: Arc<Inner>,
72}
73
74/// Two kinds of keys name a section in the store, and a key always names one content:
75///
76/// - the **wire key** of a decoded section: SipHash-1-3 with its 128-bit output (the keyed
77///   pseudo-random function std's `HashMap` uses, in the output width of rustc's
78///   `SipHasher128`) over the section's exact bytes;
79/// - the **content key** of a section made by block changes: the XOR over all 4096 blocks of
80///   the same function of (block index, state), under a different key. Two different contents
81///   differ in at least one block, so the XOR of their keys is the XOR of at least two outputs
82///   of the function on distinct inputs: for a pseudo-random function that is 0 with
83///   probability 2⁻¹²⁸, as for the wire key. It can be updated per block change, and it does
84///   not depend on how the content is packed (which decides no read).
85///
86/// Both use a secret 128-bit key drawn per store from std's `RandomState` (OS randomness); the
87/// protocol number is folded into the key, so different protocols never share. Accidental
88/// collisions: about n² / 2¹²⁹ for n distinct sections (below 10⁻²⁶ for a million). A server
89/// cannot aim for a collision either: it does not know the key.
90///
91/// The table of section arrays needs no such argument: its 64-bit hash only finds a candidate,
92/// which is then compared handle by handle (uniform value or section key).
93#[cfg_attr(
94    not(any(feature = "v26_1", feature = "v26_2", feature = "v26_3")),
95    derive(Default)
96)]
97pub(crate) struct Inner {
98    #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
99    key: [u64; 2],
100    #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
101    tables: Mutex<Tables>,
102}
103
104/// What the store's lock guards. Nothing that can be the last handle to a section or to a
105/// section array is ever dropped while the lock is held (the last drop of a section takes it).
106#[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
107#[derive(Default)]
108pub(crate) struct Tables {
109    /// Shared section storage by wire key or content key.
110    sections: HashMap<u128, WeakSection, BuildHasherDefault<KeyHasher>>,
111    /// Shared section arrays by the hash of their handles ([`SharedChunks::column_hash`]).
112    columns: HashMap<u64, Weak<[Section]>, BuildHasherDefault<KeyHasher>>,
113    /// `columns` is swept for dead entries when it reaches this size (arrays have no drop
114    /// hook: worlds remove their entry when they let go of the last handle, and this sweep
115    /// catches what that misses, such as two threads letting go at once).
116    sweep_at: usize,
117    /// Content keys of uniform sections by `protocol << 16 | state` (a small cache).
118    uniform: HashMap<u32, u128, BuildHasherDefault<KeyHasher>>,
119}
120
121#[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
122impl Default for Inner {
123    fn default() -> Self {
124        let rs = RandomState::new();
125        Inner {
126            key: [rs.hash_one(0x6b30_u64), rs.hash_one(0x6b31_u64)],
127            tables: Mutex::default(),
128        }
129    }
130}
131
132/// SipHash-c-d (Aumasson and Bernstein's reference algorithm), 128-bit output when `WIDE`,
133/// else the 64-bit one (in the low half).
134#[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
135fn siphash<const C: usize, const D: usize, const WIDE: bool>(k0: u64, k1: u64, m: &[u8]) -> u128 {
136    #[inline(always)]
137    fn round(v: &mut [u64; 4]) {
138        v[0] = v[0].wrapping_add(v[1]);
139        v[1] = v[1].rotate_left(13) ^ v[0];
140        v[0] = v[0].rotate_left(32);
141        v[2] = v[2].wrapping_add(v[3]);
142        v[3] = v[3].rotate_left(16) ^ v[2];
143        v[0] = v[0].wrapping_add(v[3]);
144        v[3] = v[3].rotate_left(21) ^ v[0];
145        v[2] = v[2].wrapping_add(v[1]);
146        v[1] = v[1].rotate_left(17) ^ v[2];
147        v[2] = v[2].rotate_left(32);
148    }
149    let mut v = [
150        k0 ^ 0x736f_6d65_7073_6575,
151        k1 ^ 0x646f_7261_6e64_6f6d ^ if WIDE { 0xee } else { 0 },
152        k0 ^ 0x6c79_6765_6e65_7261,
153        k1 ^ 0x7465_6462_7974_6573,
154    ];
155    let mut compress = |w: u64| {
156        v[3] ^= w;
157        for _ in 0..C {
158            round(&mut v);
159        }
160        v[0] ^= w;
161    };
162    let (words, tail) = m.as_chunks::<8>();
163    for w in words {
164        compress(u64::from_le_bytes(*w));
165    }
166    let mut last = (m.len() as u64) << 56;
167    for (i, &b) in tail.iter().enumerate() {
168        last |= u64::from(b) << (8 * i);
169    }
170    compress(last);
171    v[2] ^= if WIDE { 0xee } else { 0xff };
172    for _ in 0..D {
173        round(&mut v);
174    }
175    let lo = v[0] ^ v[1] ^ v[2] ^ v[3];
176    if !WIDE {
177        return u128::from(lo);
178    }
179    v[1] ^= 0xdd;
180    for _ in 0..D {
181        round(&mut v);
182    }
183    let hi = v[0] ^ v[1] ^ v[2] ^ v[3];
184    (u128::from(hi) << 64) | u128::from(lo)
185}
186
187/// The keys are already uniformly random: use their low bits.
188#[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
189#[derive(Default)]
190pub(crate) struct KeyHasher(u64);
191
192#[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
193impl Hasher for KeyHasher {
194    #[inline]
195    fn finish(&self) -> u64 {
196        self.0
197    }
198
199    #[inline]
200    fn write(&mut self, bytes: &[u8]) {
201        for &b in bytes {
202            self.0 = self.0.rotate_left(8) ^ u64::from(b);
203        }
204    }
205
206    #[inline]
207    fn write_u128(&mut self, v: u128) {
208        self.0 = v as u64;
209    }
210
211    #[inline]
212    fn write_u64(&mut self, v: u64) {
213        self.0 = v;
214    }
215
216    #[inline]
217    fn write_u32(&mut self, v: u32) {
218        self.0 = u64::from(v).wrapping_mul(0x9e37_79b9_7f4a_7c15);
219    }
220}
221
222impl std::fmt::Debug for SharedChunks {
223    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
224        f.debug_struct("SharedChunks")
225            .field("sections", &self.sections())
226            .finish_non_exhaustive()
227    }
228}
229
230impl SharedChunks {
231    /// An empty store.
232    #[must_use]
233    pub fn new() -> Self {
234        SharedChunks::default()
235    }
236
237    /// Number of distinct sections currently held by at least one world.
238    #[must_use]
239    pub fn sections(&self) -> usize {
240        #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
241        {
242            self.lock()
243                .sections
244                .values()
245                .filter(|w| !w.is_dead())
246                .count()
247        }
248        #[cfg(not(any(feature = "v26_1", feature = "v26_2", feature = "v26_3")))]
249        0
250    }
251
252    /// Number of distinct section arrays (one per column whose sections are all uniform or
253    /// shared) currently held by at least one world.
254    #[must_use]
255    pub fn columns(&self) -> usize {
256        #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
257        {
258            self.lock()
259                .columns
260                .values()
261                .filter(|w| w.strong_count() > 0)
262                .count()
263        }
264        #[cfg(not(any(feature = "v26_1", feature = "v26_2", feature = "v26_3")))]
265        0
266    }
267
268    /// Heap bytes of the shared section storage and the shared section arrays (each distinct
269    /// one counted once) plus the store's own tables. A world's
270    /// [`heap_bytes`](crate::v26_1::World::heap_bytes) does not count what it shares.
271    #[must_use]
272    pub fn heap_bytes(&self) -> usize {
273        #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
274        {
275            let t = self.lock();
276            let sections = t.sections.capacity() * (size_of::<(u128, WeakSection)>() + 1)
277                + t.sections
278                    .values()
279                    .filter(|w| !w.is_dead())
280                    .map(WeakSection::storage_bytes)
281                    .sum::<usize>();
282            let columns = t.columns.capacity() * (size_of::<(u64, Weak<[Section]>)>() + 1)
283                + t.columns
284                    .values()
285                    .filter(|w| w.strong_count() > 0)
286                    .map(|w| 2 * size_of::<usize>() + w.as_ptr().len() * size_of::<Section>())
287                    .sum::<usize>();
288            sections + columns + t.uniform.capacity() * (size_of::<(u32, u128)>() + 1)
289        }
290        #[cfg(not(any(feature = "v26_1", feature = "v26_2", feature = "v26_3")))]
291        0
292    }
293
294    /// `true` when both handles are the same store.
295    #[must_use]
296    pub fn same_store(&self, other: &SharedChunks) -> bool {
297        Arc::ptr_eq(&self.inner, &other.inner)
298    }
299}
300
301/// What a call collected to drop once the store's lock is released (see [`Tables`]).
302#[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
303#[derive(Default)]
304struct Trash {
305    sections: [Option<Section>; 2],
306    arrays: [Option<Arc<[Section]>>; 2],
307}
308
309/// `true` when `entry` is the store entry of `arr`.
310#[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
311fn is_entry_of(entry: &Weak<[Section]>, arr: &Arc<[Section]>) -> bool {
312    std::ptr::addr_eq(entry.as_ptr(), Arc::as_ptr(arr))
313}
314
315#[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
316impl Tables {
317    /// Stores `arr` under `hash` unless a live array is there (then `arr` stays unshared).
318    fn register_column(&mut self, hash: u64, arr: &Arc<[Section]>) {
319        if self
320            .columns
321            .get(&hash)
322            .is_some_and(|w| w.strong_count() > 0)
323        {
324            return;
325        }
326        if self.columns.len() >= self.sweep_at {
327            self.columns.retain(|_, w| w.strong_count() > 0);
328            self.sweep_at = (self.columns.len() * 2).max(64);
329        }
330        // A dead entry dropped here frees memory only (its sections went with the last handle).
331        self.columns.insert(hash, Arc::downgrade(arr));
332    }
333
334    /// Removes the entry of `arr` (when `hash` is its hash and the entry is its own).
335    fn unregister_column(&mut self, hash: Option<u64>, arr: &Arc<[Section]>) {
336        if let Some(h) = hash
337            && self.columns.get(&h).is_some_and(|w| is_entry_of(w, arr))
338        {
339            self.columns.remove(&h);
340        }
341    }
342}
343
344#[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
345impl SharedChunks {
346    fn lock(&self) -> MutexGuard<'_, Tables> {
347        self.inner
348            .tables
349            .lock()
350            .unwrap_or_else(PoisonError::into_inner)
351    }
352
353    /// The address that identifies this store in its sections.
354    fn id(&self) -> *const Inner {
355        Arc::as_ptr(&self.inner)
356    }
357
358    /// The key of a section's exact wire bytes for `protocol` (see [`Inner`]).
359    pub(crate) fn key(&self, protocol: u16, bytes: &[u8]) -> u128 {
360        let [k0, k1] = self.inner.key;
361        siphash::<1, 3, true>(k0, k1 ^ (u64::from(protocol) << 48), bytes)
362    }
363
364    /// One block's share of a content key (see [`Inner`]).
365    fn term(&self, protocol: u16, i: usize, state: u16) -> u128 {
366        let [k0, k1] = self.inner.key;
367        let m = ((i as u64) << 16) | u64::from(state);
368        siphash::<1, 3, true>(
369            k0 ^ 0x636f_6e74_656e_7421,
370            k1 ^ (u64::from(protocol) << 48),
371            &m.to_le_bytes(),
372        )
373    }
374
375    /// The content key of a section of this store: `None` for owned storage and for storage
376    /// shared through another store (such sections are not this store's to replace).
377    fn content_key(&self, protocol: u16, section: &Section) -> Option<u128> {
378        if let Section::Uniform(u) = *section {
379            let id = (u32::from(protocol) << 16) | u32::from(u);
380            if let Some(&k) = self.lock().uniform.get(&id) {
381                return Some(k);
382            }
383            let mut k = 0;
384            for i in 0..VOLUME {
385                k ^= self.term(protocol, i, u);
386            }
387            let mut t = self.lock();
388            if t.uniform.len() < 1024 {
389                t.uniform.insert(id, k);
390            }
391            return Some(k);
392        }
393        let cell = section.content_cell(self.id())?;
394        Some(*cell.get_or_init(|| {
395            let mut k = 0;
396            section.for_each(|i, s| k ^= self.term(protocol, i, s));
397            k
398        }))
399    }
400
401    /// Hash of a section array's handles for the table of arrays (a candidate is always
402    /// compared handle by handle, so this needs no collision resistance; the secret key keeps
403    /// a server from crowding one bucket).
404    fn column_hash(&self, idents: impl Iterator<Item = Ident>) -> u64 {
405        let mut h = self.inner.key[1];
406        for id in idents {
407            h = self.hash_step(h, id);
408        }
409        h ^ (h >> 31)
410    }
411
412    /// One handle's step of [`SharedChunks::column_hash`].
413    #[inline]
414    fn hash_step(&self, h: u64, ident: Ident) -> u64 {
415        let v = match ident {
416            Ident::Uniform(u) => u64::from(u) ^ 0x756e_6966_6f72_6d00,
417            Ident::Keyed(k) => k as u64,
418        };
419        (h.rotate_left(27) ^ v).wrapping_mul(self.inner.key[0] | 1)
420    }
421
422    /// The hashes of `arr` as it is and with `new` at index `j`, in one pass; `None` when a
423    /// section in it (other than `j`) is not this store's.
424    fn hashes_with(&self, arr: &[Section], j: usize, new: Ident) -> Option<(u64, u64)> {
425        let id = self.id();
426        let (mut old_h, mut new_h) = (self.inner.key[1], self.inner.key[1]);
427        for (k, s) in arr.iter().enumerate() {
428            let ident = s.ident(id)?;
429            old_h = self.hash_step(old_h, ident);
430            new_h = self.hash_step(new_h, if k == j { new } else { ident });
431        }
432        Some((old_h ^ (old_h >> 31), new_h ^ (new_h >> 31)))
433    }
434
435    /// [`SharedChunks::column_hash`] of an array; `None` when a section in it is not this
436    /// store's (such an array is never in the table).
437    fn hash_of(&self, arr: &[Section]) -> Option<u64> {
438        let id = self.id();
439        if arr.iter().any(|s| s.ident(id).is_none()) {
440            return None;
441        }
442        Some(self.column_hash(arr.iter().filter_map(|s| s.ident(id))))
443    }
444
445    /// Number of entries, dead ones included (tests: dead entries must not linger).
446    #[cfg(test)]
447    pub(crate) fn entries(&self) -> usize {
448        self.lock().sections.len()
449    }
450
451    /// Number of section array entries, dead ones included.
452    #[cfg(test)]
453    pub(crate) fn column_entries(&self) -> usize {
454        self.lock().columns.len()
455    }
456
457    /// The live section stored under `key`.
458    pub(crate) fn get(&self, key: u128) -> Option<Section> {
459        // Upgrading under the lock is what makes the last-holder check in `forget` race-free.
460        self.lock()
461            .sections
462            .get(&key)
463            .and_then(WeakSection::upgrade)
464    }
465
466    /// Stores a freshly decoded section under `key` and returns the shared section to keep. A
467    /// uniform section is returned as it is (it owns no heap memory). When another thread
468    /// stored the same key meanwhile, its section is returned and `section` is dropped.
469    pub(crate) fn insert(&self, key: u128, section: Section) -> Section {
470        let (shared, weak) = match section.into_shared(key, None, Arc::downgrade(&self.inner)) {
471            Ok(s) => s,
472            Err(uniform) => return uniform,
473        };
474        let existing = {
475            let mut t = self.lock();
476            match t.sections.get(&key).and_then(WeakSection::upgrade) {
477                Some(live) => Some(live),
478                None => {
479                    t.sections.insert(key, weak);
480                    None
481                }
482            }
483        };
484        // `shared` is dropped outside the lock (its last drop takes the lock).
485        existing.unwrap_or(shared)
486    }
487
488    /// The shared section array whose handles are exactly `idents` (in a chunk packet: the
489    /// uniform values and wire keys of its sections), if a world holds one.
490    pub(crate) fn find_column(
491        &self,
492        idents: impl Iterator<Item = Ident> + Clone,
493    ) -> Option<Arc<[Section]>> {
494        let hash = self.column_hash(idents.clone());
495        let id = self.id();
496        let found = self.lock().columns.get(&hash).and_then(Weak::upgrade)?;
497        // Compared (and, on a mismatch, dropped) outside the lock.
498        let mut idents = idents;
499        let same = found.iter().all(|s| s.ident(id) == idents.next()) && idents.next().is_none();
500        same.then_some(found)
501    }
502
503    /// Shares a freshly decoded section array: returns the array already in the store for the
504    /// same handles, else stores `arr` and returns it. An array with a section that is not
505    /// this store's (owned storage) is returned as it is.
506    pub(crate) fn intern_column(&self, arr: Arc<[Section]>) -> Arc<[Section]> {
507        let Some(hash) = self.hash_of(&arr) else {
508            return arr;
509        };
510        let id = self.id();
511        let found = {
512            let mut t = self.lock();
513            let found = t.columns.get(&hash).and_then(Weak::upgrade);
514            if found.is_none() {
515                t.register_column(hash, &arr);
516            }
517            found
518        };
519        match found {
520            Some(f)
521                if f.len() == arr.len()
522                    && f.iter()
523                        .zip(arr.iter())
524                        .all(|(a, b)| a.ident(id) == b.ident(id)) =>
525            {
526                f
527            }
528            // Another array with the same hash: `arr` stays unshared.
529            _ => arr,
530        }
531    }
532
533    /// Lets go of a section array a world held, removing its entry with the last handle.
534    pub(crate) fn release_column(&self, arr: Arc<[Section]>) {
535        // The counts are a hint: two threads letting go of the last two handles at once both
536        // skip this, and the entry is swept later (see `Tables::sweep_at`).
537        if Arc::strong_count(&arr) == 1 && Arc::weak_count(&arr) > 0 {
538            let hash = self.hash_of(&arr);
539            let mut t = self.lock();
540            // Under the lock nobody can take a new handle from the entry.
541            if Arc::strong_count(&arr) == 1 {
542                t.unregister_column(hash, &arr);
543            }
544        }
545        drop(arr);
546    }
547
548    /// Applies block changes to section `j` of a world's section array: `recs` are `(block
549    /// index, new state)` in packet order, `on_change(index, old, new)` (if any) is called for
550    /// every record in order. Returns `false` and does nothing when the section is not this
551    /// store's (owned storage: the caller changes it in place as a world without a store does).
552    ///
553    /// Exactness: the world ends up reading the section it had with `recs` applied in order.
554    /// The new section is named by its content key, the old content key moved by the two
555    /// terms of every changed block; a section found under that key has exactly that content.
556    /// Nothing another world can read is ever written: storage is changed in place only
557    /// through `Arc::get_mut`, on the array and on the section, which succeeds only for the
558    /// one and only handle.
559    pub(crate) fn update<I>(
560        &self,
561        protocol: u16,
562        arr: &mut Arc<[Section]>,
563        j: usize,
564        recs: I,
565        mut on_change: Option<&mut dyn FnMut(usize, u16, u16)>,
566    ) -> bool
567    where
568        I: Iterator<Item = (usize, u16)> + Clone,
569    {
570        let Some(section) = arr.get(j) else {
571            return false;
572        };
573        let Some(old_key) = self.content_key(protocol, section) else {
574            return false;
575        };
576        // The new key without touching the storage, when no block is named twice.
577        let mut key = old_key;
578        let mut changes = 0usize;
579        let mut single = (0, 0);
580        let mut twice = false;
581        let mut rest = recs.clone();
582        if let (Some((i, s)), None) = (rest.next(), rest.next()) {
583            // One record (a `block_update`, a prediction).
584            let i = i & (VOLUME - 1);
585            let old = section.get(i);
586            if old != s {
587                key ^= self.term(protocol, i, old) ^ self.term(protocol, i, s);
588                changes = 1;
589                single = (i, s);
590            }
591        } else {
592            let mut seen = [0u64; VOLUME / 64];
593            for (i, s) in recs.clone() {
594                let i = i & (VOLUME - 1);
595                let bit = 1u64 << (i & 63);
596                if seen[i >> 6] & bit != 0 {
597                    twice = true;
598                    break;
599                }
600                seen[i >> 6] |= bit;
601                let old = section.get(i);
602                if old != s {
603                    key ^= self.term(protocol, i, old) ^ self.term(protocol, i, s);
604                    changes += 1;
605                    single = (i, s);
606                }
607            }
608        }
609        // The section with the changes applied, once it had to be built.
610        let mut built = None;
611        if twice {
612            let mut owned = section.to_owned_storage();
613            key = old_key;
614            for (i, s) in recs.clone() {
615                let i = i & (VOLUME - 1);
616                let old = owned.set(i, s);
617                if old != s {
618                    key ^= self.term(protocol, i, old) ^ self.term(protocol, i, s);
619                }
620                if let Some(f) = on_change.as_mut() {
621                    f(i, old, s);
622                }
623            }
624            if key == old_key {
625                return true;
626            }
627            built = Some(owned);
628            changes = usize::MAX;
629        } else {
630            if let Some(f) = on_change.as_mut() {
631                for (i, s) in recs.clone() {
632                    f(i & (VOLUME - 1), section.get(i), s);
633                }
634            }
635            if changes == 0 {
636                return true;
637            }
638        }
639        // The array's hash now and with the new section, which will be stored under `key`.
640        let hashes = self.hashes_with(arr, j, Ident::Keyed(key));
641        // Declared before the lock guard: dropped after it.
642        let mut trash = Trash::default();
643        loop {
644            let mut t = self.lock();
645            let live = t.sections.get(&key).and_then(WeakSection::upgrade);
646            let new = match (live, built.take()) {
647                (Some(live), _) => live,
648                (None, Some(owned)) => {
649                    match owned.into_shared(key, Some(key), Arc::downgrade(&self.inner)) {
650                        Ok((shared, weak)) => {
651                            t.sections.insert(key, weak);
652                            shared
653                        }
654                        Err(uniform) => uniform,
655                    }
656                }
657                (None, None) => {
658                    if changes == 1 && self.set_in_place(&mut t, arr, hashes, j, single, key) {
659                        return true;
660                    }
661                    drop(t);
662                    // Copy and apply outside the lock, then look again.
663                    let mut owned = arr[j].to_owned_storage();
664                    for (i, s) in recs.clone() {
665                        owned.set(i, s);
666                    }
667                    built = Some(owned);
668                    continue;
669                }
670            };
671            self.replace_section(&mut t, arr, hashes, j, new, &mut trash);
672            return true;
673        }
674    }
675
676    /// The sole-holder path of [`SharedChunks::update`]: when this world is the only holder of
677    /// the array and the array the only holder of the section's storage, the block is changed
678    /// in the storage itself and the storage moves to its new key. `false` when that is not
679    /// possible (then at most the entries of the array and the section were removed, which is
680    /// harmless: the caller replaces the section next).
681    fn set_in_place(
682        &self,
683        t: &mut Tables,
684        arr: &mut Arc<[Section]>,
685        hashes: Option<(u64, u64)>,
686        j: usize,
687        (i, state): (usize, u16),
688        key: u128,
689    ) -> bool {
690        // Under the lock no handle can be made from a store entry, and every other way to a
691        // new handle needs one of the handles counted here.
692        if Arc::strong_count(arr) != 1 || arr[j].shared_holders() != Some(1) {
693            return false;
694        }
695        let Some(Ident::Keyed(old_key)) = arr[j].ident(self.id()) else {
696            return false;
697        };
698        t.unregister_column(hashes.map(|h| h.0), arr);
699        let Some(slots) = Arc::get_mut(arr) else {
700            return false;
701        };
702        if t.sections
703            .get(&old_key)
704            .is_some_and(|w| w.points_to(&slots[j]))
705        {
706            t.sections.remove(&old_key);
707        }
708        let Some(weak) = slots[j].set_sole(i, state, key) else {
709            return false;
710        };
711        // `key` had no live entry (the caller looked under this lock).
712        t.sections.insert(key, weak);
713        if let Some((_, hash)) = hashes {
714            t.register_column(hash, arr);
715        }
716        true
717    }
718
719    /// Puts `new` at index `j` of a world's section array without writing to an array another
720    /// world can read: takes the array already in the store for the resulting handles, else
721    /// changes the world's array in place when it is its only holder, else builds a new array.
722    fn replace_section(
723        &self,
724        t: &mut Tables,
725        arr: &mut Arc<[Section]>,
726        hashes: Option<(u64, u64)>,
727        j: usize,
728        new: Section,
729        trash: &mut Trash,
730    ) {
731        let id = self.id();
732        let new_ident = new.ident(id);
733        let old_hash = hashes.map(|h| h.0);
734        // `hashes` assumed keyed storage; anything else (a section that became uniform, which
735        // a change never yields) is hashed again.
736        let new_hash = match (hashes, new_ident) {
737            (Some((_, h)), Some(Ident::Keyed(_))) => Some(h),
738            (Some(_), Some(ident)) => self.hashes_with(arr, j, ident).map(|h| h.1),
739            _ => None,
740        };
741        if let Some(hash) = new_hash
742            && let Some(found) = t.columns.get(&hash).and_then(Weak::upgrade)
743        {
744            let same =
745                found.len() == arr.len()
746                    && found.iter().zip(arr.iter()).enumerate().all(|(k, (f, s))| {
747                        f.ident(id) == if k == j { new_ident } else { s.ident(id) }
748                    });
749            if same {
750                let old = std::mem::replace(arr, found);
751                if Arc::strong_count(&old) == 1 {
752                    t.unregister_column(old_hash, &old);
753                }
754                trash.arrays[0] = Some(old);
755                trash.sections[0] = Some(new);
756                return;
757            }
758            trash.arrays[1] = Some(found);
759        }
760        if Arc::strong_count(arr) == 1 {
761            t.unregister_column(old_hash, arr);
762            if let Some(slots) = Arc::get_mut(arr) {
763                trash.sections[0] = Some(std::mem::replace(&mut slots[j], new));
764                if let Some(hash) = new_hash {
765                    t.register_column(hash, arr);
766                }
767                return;
768            }
769        }
770        let built: Arc<[Section]> = arr
771            .iter()
772            .enumerate()
773            .map(|(k, s)| if k == j { new.clone() } else { s.clone() })
774            .collect();
775        trash.sections[0] = Some(new);
776        if let Some(hash) = new_hash {
777            t.register_column(hash, &built);
778        }
779        trash.arrays[0] = Some(std::mem::replace(arr, built));
780    }
781}
782
783/// Called by a shared section's storage when its last holder dropped it: removes the dead
784/// entry (unless the key was stored again meanwhile).
785#[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
786pub(crate) fn forget(cache: &Weak<Inner>, key: u128) {
787    let Some(inner) = cache.upgrade() else {
788        return;
789    };
790    let mut t = inner.tables.lock().unwrap_or_else(PoisonError::into_inner);
791    if t.sections.get(&key).is_some_and(WeakSection::is_dead) {
792        t.sections.remove(&key);
793    }
794    drop(t);
795    drop(inner);
796}
797
798#[cfg(all(test, any(feature = "v26_1", feature = "v26_2", feature = "v26_3")))]
799mod tests {
800    use super::siphash;
801
802    /// The reference implementation's first SipHash-2-4-128 vector (key 00..0f, empty message).
803    #[test]
804    fn siphash_reference_vector() {
805        let k0 = u64::from_le_bytes([0, 1, 2, 3, 4, 5, 6, 7]);
806        let k1 = u64::from_le_bytes([8, 9, 10, 11, 12, 13, 14, 15]);
807        let want: [u8; 16] = [
808            0xa3, 0x81, 0x7f, 0x04, 0xba, 0x25, 0xa8, 0xe6, 0x6d, 0xf6, 0x72, 0x14, 0xc7, 0x55,
809            0x02, 0x93,
810        ];
811        assert_eq!(siphash::<2, 4, true>(k0, k1, &[]).to_le_bytes(), want);
812    }
813
814    /// The same code in 64-bit mode is std's SipHash-2-4 on every length up to 70 (rounds,
815    /// word order, the length / tail block).
816    #[test]
817    fn rounds_and_tail_match_std() {
818        #[allow(deprecated)]
819        fn std24(k0: u64, k1: u64, m: &[u8]) -> u64 {
820            use std::hash::Hasher;
821            let mut h = std::hash::SipHasher::new_with_keys(k0, k1);
822            h.write(m);
823            h.finish()
824        }
825        let m: Vec<u8> = (0..70u8).map(|i| i.wrapping_mul(37) ^ 0x5a).collect();
826        for n in 0..=m.len() {
827            let (k0, k1) = (0x0706_0504_0302_0100 ^ n as u64, 0x0f0e_0d0c_0b0a_0908);
828            let ours = siphash::<2, 4, false>(k0, k1, &m[..n]);
829            assert_eq!(ours, u128::from(std24(k0, k1, &m[..n])), "len {n}");
830        }
831        // One flipped bit, one byte less or another key: another key.
832        let a = siphash::<1, 3, true>(1, 2, &m);
833        assert_ne!(a, siphash::<1, 3, true>(1, 2, &m[..69]));
834        assert_ne!(a, siphash::<1, 3, true>(1, 3, &m));
835        let mut m2 = m.clone();
836        m2[40] ^= 1;
837        assert_ne!(a, siphash::<1, 3, true>(1, 2, &m2));
838    }
839}