systemless 0.66.0

High-Level Emulation for classic Macintosh applications
Documentation
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
//! Retained text detail for guest memory outside the framebuffer.
//!
//! Offscreen pixmaps (GWorlds, save-behind buffers) hold the same per-pixel
//! detail cells as the screen, but at arbitrary addresses. Cells are stored
//! by content in fixed 256-byte address chunks, each keeping its cells'
//! values and sample indices contiguously, a text bitmask and sparse ink.
//! A pixmap row is a contiguous address span, so erasing, capturing and
//! copying text rows walk chunks and bitmasks instead of one heap object per
//! pixel, and drawing a glyph pixel rewrites array slots instead of
//! allocating a cell.
//!
//! The API keeps the shape of the address-keyed map it replaced. A cell is
//! handed out as an `Arc<DetailCell>` built on first request and cached
//! until the cell changes, so snapshots of unchanged text still share one
//! immutable cell, and a cell stored from a snapshot is returned as that
//! same `Arc`.

use super::samples::{ink_entry, ink_remove, InkList};
use super::{DetailCell, Ink, SampleOffsetHasher, TILE_SAMPLES};
use std::cell::RefCell;
use std::collections::{BTreeMap, HashMap};
use std::hash::BuildHasherDefault;
use std::sync::Arc;

const CHUNK_SHIFT: u32 = 8;
const CHUNK_BYTES: usize = 1 << CHUNK_SHIFT;
const MASK_WORDS: usize = CHUNK_BYTES / 64;

type CellInkMap = HashMap<usize, Ink, BuildHasherDefault<SampleOffsetHasher>>;

/// A chunk emptied of cells is kept for reuse: text drawn, erased and
/// drawn again at the same addresses (a menu's save-behind buffer, a text
/// crawl) would otherwise free and re-zero it every time.
struct Chunk {
    /// Bit `slot` is set when the slot holds a cell.
    present: [u64; MASK_WORDS],
    /// Bit `slot` is set when the slot may hold ink. It is set whenever ink
    /// is added and cleared only with the slot, so an unset bit proves the
    /// slot has none and lets clearing and lookups skip the ink list.
    inked: [u64; MASK_WORDS],
    values: [u8; CHUNK_BYTES],
    /// Sample count of each cell (`scale²` of the presentation that made it).
    lens: [u8; CHUNK_BYTES],
    /// `TILE_SAMPLES` indices per slot, of which the first `lens[slot]` count.
    indices: Box<[u8; CHUNK_BYTES * TILE_SAMPLES]>,
    /// Partial-coverage ink per slot, each list sorted by sample. Empty
    /// until the chunk first holds ink; a cleared slot keeps its capacity.
    inks: Vec<InkList>,
    /// Cells already handed out as `Arc`s and unchanged since.
    shared: RefCell<Vec<Option<Arc<DetailCell>>>>,
    count: usize,
}

impl Chunk {
    fn new() -> Self {
        Self {
            present: [0; MASK_WORDS],
            inked: [0; MASK_WORDS],
            values: [0; CHUNK_BYTES],
            lens: [0; CHUNK_BYTES],
            indices: Box::new([0; CHUNK_BYTES * TILE_SAMPLES]),
            inks: Vec::new(),
            shared: RefCell::new(Vec::new()),
            count: 0,
        }
    }

    fn has(&self, slot: usize) -> bool {
        self.present[slot / 64] & (1 << (slot % 64)) != 0
    }

    /// Give an empty `slot` a cell of `len` samples of `background` with no
    /// ink, reporting whether it was empty.
    #[inline]
    fn insert_blank(&mut self, slot: usize, background: u8, len: usize) -> bool {
        if self.has(slot) {
            return false;
        }
        assert!(len <= TILE_SAMPLES, "cell samples exceed a tile");
        self.present[slot / 64] |= 1 << (slot % 64);
        self.count += 1;
        self.values[slot] = background;
        self.lens[slot] = len as u8;
        self.indices[slot * TILE_SAMPLES..slot * TILE_SAMPLES + len].fill(background);
        self.forget_shared(slot);
        true
    }

    fn may_have_ink(&self, slot: usize) -> bool {
        self.inked[slot / 64] & (1 << (slot % 64)) != 0
    }

    /// The slot's ink, sorted by sample.
    fn slot_ink(&self, slot: usize) -> &[(u8, Ink)] {
        if self.may_have_ink(slot) {
            &self.inks[slot]
        } else {
            &[]
        }
    }

    /// The slot's ink list for changes, marking the slot as inked.
    fn slot_ink_mut(&mut self, slot: usize) -> &mut InkList {
        if self.inks.is_empty() {
            self.inks.resize_with(CHUNK_BYTES, Vec::new);
        }
        self.inked[slot / 64] |= 1 << (slot % 64);
        &mut self.inks[slot]
    }

    fn forget_shared(&mut self, slot: usize) {
        if let Some(cached) = self.shared.get_mut().get_mut(slot) {
            *cached = None;
        }
    }

    fn cell(&self, slot: usize) -> Arc<DetailCell> {
        if let Some(Some(cell)) = self.shared.borrow().get(slot) {
            return cell.clone();
        }
        let len = usize::from(self.lens[slot]);
        let mut ink = CellInkMap::default();
        for (sample, value) in self.slot_ink(slot) {
            ink.insert(usize::from(*sample), value.clone());
        }
        let cell = Arc::new(DetailCell {
            value: self.values[slot],
            indices: self.indices[slot * TILE_SAMPLES..slot * TILE_SAMPLES + len].to_vec(),
            ink,
        });
        let mut shared = self.shared.borrow_mut();
        if shared.is_empty() {
            shared.resize(CHUNK_BYTES, None);
        }
        shared[slot] = Some(cell.clone());
        cell
    }

    fn matches(&self, slot: usize, cell: &DetailCell) -> bool {
        let len = usize::from(self.lens[slot]);
        if self.values[slot] != cell.value
            || len != cell.indices.len()
            || self.indices[slot * TILE_SAMPLES..slot * TILE_SAMPLES + len] != cell.indices[..]
        {
            return false;
        }
        let held = self.slot_ink(slot);
        held.len() == cell.ink.len()
            && held
                .iter()
                .all(|(sample, ink)| cell.ink.get(&usize::from(*sample)) == Some(ink))
    }

    /// Store `cell` in `slot`, which must not hold one. `shared` is the
    /// `Arc` to hand out for it, if the caller has one.
    fn store(&mut self, slot: usize, cell: &DetailCell, shared: Option<&Arc<DetailCell>>) {
        assert!(cell.indices.len() <= TILE_SAMPLES, "cell samples exceed a tile");
        self.present[slot / 64] |= 1 << (slot % 64);
        self.count += 1;
        self.values[slot] = cell.value;
        self.lens[slot] = cell.indices.len() as u8;
        self.indices[slot * TILE_SAMPLES..slot * TILE_SAMPLES + cell.indices.len()]
            .copy_from_slice(&cell.indices);
        if !cell.ink.is_empty() {
            let held = self.slot_ink_mut(slot);
            held.clear();
            held.extend(cell.ink.iter().map(|(&sample, ink)| (sample as u8, ink.clone())));
            held.sort_unstable_by_key(|&(sample, _)| sample);
        }
        match shared {
            Some(cell) => {
                let shared = self.shared.get_mut();
                if shared.is_empty() {
                    shared.resize(CHUNK_BYTES, None);
                }
                shared[slot] = Some(cell.clone());
            }
            None => self.forget_shared(slot),
        }
    }

    fn clear(&mut self, slot: usize) {
        self.present[slot / 64] &= !(1 << (slot % 64));
        self.count -= 1;
        if self.may_have_ink(slot) {
            self.inks[slot].clear();
            self.inked[slot / 64] &= !(1 << (slot % 64));
        }
        self.forget_shared(slot);
    }

    /// Clear every occupied slot in `[first, end)`, returning how many.
    fn clear_span(&mut self, first: usize, end: usize) -> usize {
        let mut cleared = 0;
        for word in first / 64..end.div_ceil(64) {
            let low = if word == first / 64 { first % 64 } else { 0 };
            let high = if word == (end - 1) / 64 { (end - 1) % 64 + 1 } else { 64 };
            let mask = (u64::MAX >> (64 - (high - low))) << low;
            let hit = self.present[word] & mask;
            if hit == 0 {
                continue;
            }
            cleared += hit.count_ones() as usize;
            self.present[word] &= !hit;
            let mut inked = self.inked[word] & hit;
            self.inked[word] &= !hit;
            while inked != 0 {
                self.inks[word * 64 + inked.trailing_zeros() as usize].clear();
                inked &= inked - 1;
            }
            if let Some(shared) = self.shared.get_mut().get_mut(word * 64..word * 64 + 64) {
                let mut bits = hit;
                while bits != 0 {
                    shared[bits.trailing_zeros() as usize] = None;
                    bits &= bits - 1;
                }
            }
        }
        self.count -= cleared;
        cleared
    }
}

/// Move an ink out, leaving a placeholder that allocates nothing.
pub(super) fn take_ink(ink: &mut Ink) -> Ink {
    std::mem::replace(
        ink,
        Ink { foreground: 0, alpha: 0, background: super::IndexedColor::Solid(0) },
    )
}

/// Read access to one offscreen cell's contents, without building an `Arc`.
pub(super) struct OffscreenCellRef<'a> {
    chunk: &'a Chunk,
    slot: usize,
}

impl OffscreenCellRef<'_> {
    /// The cell's sample indices.
    pub(super) fn indices(&self) -> &[u8] {
        let start = self.slot * TILE_SAMPLES;
        &self.chunk.indices[start..start + usize::from(self.chunk.lens[self.slot])]
    }

    /// The cell's ink as `(sample, ink)` in sample order.
    pub(super) fn inks(&self) -> impl Iterator<Item = (usize, &Ink)> {
        self.chunk
            .slot_ink(self.slot)
            .iter()
            .map(|(sample, ink)| (usize::from(*sample), ink))
    }
}

/// Mutable access to one offscreen cell. Any change forgets the cell's
/// shared `Arc`, so later reads see the new contents.
pub(super) struct OffscreenCellMut<'a> {
    chunk: &'a mut Chunk,
    slot: usize,
}

impl OffscreenCellMut<'_> {
    pub(super) fn len(&self) -> usize {
        usize::from(self.chunk.lens[self.slot])
    }

    pub(super) fn set_value(&mut self, value: u8) {
        self.chunk.forget_shared(self.slot);
        self.chunk.values[self.slot] = value;
    }

    pub(super) fn index(&self, sample: usize) -> u8 {
        assert!(sample < self.len());
        self.chunk.indices[self.slot * TILE_SAMPLES + sample]
    }

    pub(super) fn set_index(&mut self, sample: usize, index: u8) {
        assert!(sample < self.len());
        self.chunk.forget_shared(self.slot);
        self.chunk.indices[self.slot * TILE_SAMPLES + sample] = index;
    }

    pub(super) fn remove_ink(&mut self, sample: usize) {
        if !self.chunk.may_have_ink(self.slot) {
            return;
        }
        let held = &mut self.chunk.inks[self.slot];
        if held.iter().any(|&(held, _)| usize::from(held) == sample) {
            ink_remove(held, sample);
            self.chunk.forget_shared(self.slot);
        }
    }

    /// The ink of `sample`, inserting `ink()` when it has none.
    pub(super) fn ink_or_insert_with(&mut self, sample: usize, ink: impl FnOnce() -> Ink) -> &mut Ink {
        self.chunk.forget_shared(self.slot);
        ink_entry(self.chunk.slot_ink_mut(self.slot), sample, ink)
    }
}

#[derive(Default)]
pub(super) struct OffscreenDetail {
    chunks: BTreeMap<u32, Box<Chunk>>,
    count: usize,
}

fn split(address: u32) -> (u32, usize) {
    (address >> CHUNK_SHIFT, (address as usize) & (CHUNK_BYTES - 1))
}

impl OffscreenDetail {
    #[cfg(test)]
    pub(super) fn len(&self) -> usize {
        self.count
    }

    pub(super) fn contains(&self, address: u32) -> bool {
        let (chunk, slot) = split(address);
        self.chunks.get(&chunk).is_some_and(|chunk| chunk.has(slot))
    }

    pub(super) fn get(&self, address: u32) -> Option<Arc<DetailCell>> {
        let (chunk, slot) = split(address);
        let chunk = self.chunks.get(&chunk)?;
        chunk.has(slot).then(|| chunk.cell(slot))
    }

    /// Whether `address` holds exactly `cell` (or, for `None`, nothing),
    /// compared by contents as the replaced map compared its `Arc`s.
    pub(super) fn matches(&self, address: u32, cell: Option<&DetailCell>) -> bool {
        let (chunk, slot) = split(address);
        let held = self.chunks.get(&chunk).filter(|chunk| chunk.has(slot));
        match (held, cell) {
            (None, None) => true,
            (Some(chunk), Some(cell)) => chunk.matches(slot, cell),
            _ => false,
        }
    }

    /// Store `cell` at `address`, replacing any cell there, and hand out this
    /// same `Arc` for it until it changes.
    pub(super) fn insert(&mut self, address: u32, cell: &Arc<DetailCell>) {
        let (chunk, slot) = split(address);
        let chunk = self.chunks.entry(chunk).or_insert_with(|| Box::new(Chunk::new()));
        if chunk.has(slot) {
            chunk.clear(slot);
        } else {
            self.count += 1;
        }
        chunk.store(slot, cell, Some(cell));
    }

    /// Remove the cell at `address`, reporting whether there was one.
    pub(super) fn remove(&mut self, address: u32) -> bool {
        let (key, slot) = split(address);
        let Some(chunk) = self.chunks.get_mut(&key) else {
            return false;
        };
        if !chunk.has(slot) {
            return false;
        }
        chunk.clear(slot);
        self.count -= 1;
        true
    }

    /// Remove every cell in `[from, to)`, reporting whether any existed.
    /// `to` may lie past the last address; the span ends there.
    pub(super) fn remove_range(&mut self, from: u32, to: u64) -> bool {
        let to = to.min(1 << 32);
        if u64::from(from) >= to {
            return false;
        }
        let last = (to - 1) as u32;
        let mut removed = false;
        for (&key, chunk) in self.chunks.range_mut(from >> CHUNK_SHIFT..=last >> CHUNK_SHIFT) {
            let base = key << CHUNK_SHIFT;
            let first = from.saturating_sub(base).min(CHUNK_BYTES as u32) as usize;
            let end = (u64::from(last) - u64::from(base) + 1).min(CHUNK_BYTES as u64) as usize;
            let cleared = chunk.clear_span(first, end);
            self.count -= cleared;
            removed |= cleared != 0;
        }
        removed
    }

    /// Whether every cell in `[from, to)` has `len` samples.
    pub(super) fn all_cells_have_len(&self, from: u32, to: u64, len: usize) -> bool {
        let mut all = true;
        self.visit(from, to, |_, chunk, slot| {
            all = usize::from(chunk.lens[slot]) == len;
            all
        });
        all
    }

    /// Whether any cell lies in `[from, to)`.
    pub(super) fn any_in(&self, from: u32, to: u64) -> bool {
        let mut any = false;
        self.visit(from, to, |_, _, _| {
            any = true;
            false
        });
        any
    }

    /// The cells in `[from, to)` in address order.
    pub(super) fn range(&self, from: u32, to: u64) -> Vec<(u32, Arc<DetailCell>)> {
        let mut cells = Vec::new();
        self.visit(from, to, |address, chunk, slot| {
            cells.push((address, chunk.cell(slot)));
            true
        });
        cells
    }

    /// Visit the occupied slots in `[from, to)` in address order until
    /// `visit` returns false.
    fn visit(&self, from: u32, to: u64, mut visit: impl FnMut(u32, &Chunk, usize) -> bool) {
        let to = to.min(1 << 32);
        if u64::from(from) >= to {
            return;
        }
        let last = (to - 1) as u32;
        for (&key, chunk) in self.chunks.range(from >> CHUNK_SHIFT..=last >> CHUNK_SHIFT) {
            let base = key << CHUNK_SHIFT;
            let first = from.saturating_sub(base).min(CHUNK_BYTES as u32) as usize;
            let end = (u64::from(last) - u64::from(base) + 1).min(CHUNK_BYTES as u64) as usize;
            for word in first / 64..end.div_ceil(64) {
                let mut bits = chunk.present[word];
                while bits != 0 {
                    let slot = word * 64 + bits.trailing_zeros() as usize;
                    bits &= bits - 1;
                    if slot < first || slot >= end {
                        continue;
                    }
                    if !visit(base + slot as u32, chunk, slot) {
                        return;
                    }
                }
            }
        }
    }

    /// Visit each cell in `[from, from + len)` in address order, with its
    /// offset from `from`.
    pub(super) fn visit_cells(&self, from: u32, len: usize, mut visit: impl FnMut(usize, OffscreenCellRef<'_>)) {
        self.visit(from, u64::from(from) + len as u64, |address, chunk, slot| {
            visit((address - from) as usize, OffscreenCellRef { chunk, slot });
            true
        });
    }

    /// Make `address` hold the cell `value` / `indices` / `ink` (ink sorted
    /// by sample), unless it already holds exactly that cell, and report
    /// whether it changed. The ink is moved out of `ink`.
    pub(super) fn store_parts(&mut self, address: u32, value: u8, indices: &[u8], ink: &mut [(u8, Ink)]) -> bool {
        assert!(indices.len() <= TILE_SAMPLES, "cell samples exceed a tile");
        let (key, slot) = split(address);
        let chunk = self.chunks.entry(key).or_insert_with(|| Box::new(Chunk::new()));
        if chunk.has(slot) {
            let start = slot * TILE_SAMPLES;
            if chunk.values[slot] == value
                && usize::from(chunk.lens[slot]) == indices.len()
                && chunk.indices[start..start + indices.len()] == *indices
                && chunk.slot_ink(slot) == &*ink
            {
                return false;
            }
            chunk.clear(slot);
            self.count -= 1;
        }
        chunk.present[slot / 64] |= 1 << (slot % 64);
        chunk.count += 1;
        self.count += 1;
        chunk.values[slot] = value;
        chunk.lens[slot] = indices.len() as u8;
        let start = slot * TILE_SAMPLES;
        chunk.indices[start..start + indices.len()].copy_from_slice(indices);
        if !ink.is_empty() {
            let held = chunk.slot_ink_mut(slot);
            held.clear();
            held.extend(ink.iter_mut().map(|(sample, ink)| (*sample, take_ink(ink))));
        }
        chunk.forget_shared(slot);
        true
    }

    /// Every occupied address, in order.
    pub(super) fn addresses(&self) -> Vec<u32> {
        let mut addresses = Vec::with_capacity(self.count);
        self.visit(0, 1 << 32, |address, _, _| {
            addresses.push(address);
            true
        });
        addresses
    }

    pub(super) fn cell_mut(&mut self, address: u32) -> Option<OffscreenCellMut<'_>> {
        let (chunk, slot) = split(address);
        let chunk = self.chunks.get_mut(&chunk)?;
        chunk.has(slot).then(|| OffscreenCellMut { chunk, slot })
    }

    /// The cell at `address`, first creating one of `len` samples of
    /// `background` with no ink when there is none.
    pub(super) fn cell_mut_or_insert(
        &mut self,
        address: u32,
        background: u8,
        len: usize,
    ) -> OffscreenCellMut<'_> {
        let (key, slot) = split(address);
        let chunk = self.chunks.entry(key).or_insert_with(|| Box::new(Chunk::new()));
        if chunk.insert_blank(slot, background, len) {
            self.count += 1;
        }
        OffscreenCellMut { chunk, slot }
    }

    /// `cell_mut_or_insert` for each of the consecutive addresses from
    /// `address`, one per byte of `backgrounds`, visiting each cell with its
    /// offset. Each chunk is looked up once. The span must not wrap.
    pub(super) fn cells_mut_or_insert(
        &mut self,
        address: u32,
        backgrounds: &[u8],
        len: usize,
        mut visit: impl FnMut(usize, &mut OffscreenCellMut<'_>),
    ) {
        assert!(
            u64::from(address) + backgrounds.len() as u64 <= 1 << 32,
            "offscreen span wraps"
        );
        let mut offset = 0;
        while offset < backgrounds.len() {
            let (key, first) = split(address + offset as u32);
            let run = (CHUNK_BYTES - first).min(backgrounds.len() - offset);
            let chunk = self.chunks.entry(key).or_insert_with(|| Box::new(Chunk::new()));
            for (i, slot) in (first..first + run).enumerate() {
                if chunk.insert_blank(slot, backgrounds[offset + i], len) {
                    self.count += 1;
                }
                visit(offset + i, &mut OffscreenCellMut { chunk, slot });
            }
            offset += run;
        }
    }
}

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

    fn cell(value: u8, indices: &[u8], ink: &[(usize, u8)]) -> Arc<DetailCell> {
        Arc::new(DetailCell {
            value,
            indices: indices.to_vec(),
            ink: ink
                .iter()
                .map(|&(sample, foreground)| {
                    (
                        sample,
                        Ink {
                            foreground,
                            alpha: 90,
                            background: IndexedColor::Solid(value),
                        },
                    )
                })
                .collect(),
        })
    }

    /// Deterministic xorshift: the model test needs varied but repeatable ops.
    fn next(state: &mut u64) -> u64 {
        *state ^= *state << 13;
        *state ^= *state >> 7;
        *state ^= *state << 17;
        *state
    }

    /// Every operation agrees with the address-keyed map it replaced,
    /// including across chunk boundaries, removals that empty a chunk,
    /// in-place edits and ranges reaching the last address.
    #[test]
    fn chunk_store_agrees_with_an_ordered_map() {
        let mut store = OffscreenDetail::default();
        let mut model: BTreeMap<u32, DetailCell> = BTreeMap::new();
        let mut rng = 0x9E37_79B9_7F4A_7C15u64;
        let bases = [0x0003_0000u32, 0x0003_00F0, 0xFFFF_FF00, 0x0010_0000];
        for step in 0..20_000 {
            let r = next(&mut rng);
            let base = bases[(r % bases.len() as u64) as usize];
            let address = base.wrapping_add((r >> 8) as u32 % 600);
            match (r >> 20) % 8 {
                0 | 1 => {
                    let len = [4usize, 9, 16][((r >> 24) % 3) as usize];
                    let indices: Vec<u8> = (0..len).map(|i| (r >> (i % 8)) as u8).collect();
                    let ink: Vec<(usize, u8)> = (0..len)
                        .filter(|i| (r >> (32 + i)) & 3 == 0)
                        .map(|i| (i, (r >> 40) as u8))
                        .collect();
                    let new = cell((r >> 48) as u8, &indices, &ink);
                    store.insert(address, &new);
                    model.insert(address, (*new).clone());
                }
                2 => {
                    assert_eq!(store.remove(address), model.remove(&address).is_some(), "step {step}");
                }
                3 => {
                    let to = u64::from(address) + (r >> 40) % 700;
                    let expected: Vec<u32> = model
                        .range(address..)
                        .take_while(|(&key, _)| u64::from(key) < to)
                        .map(|(&key, _)| key)
                        .collect();
                    for key in &expected {
                        model.remove(key);
                    }
                    assert_eq!(store.remove_range(address, to), !expected.is_empty(), "step {step}");
                }
                4 => {
                    let value = (r >> 30) as u8;
                    if let Some(mut held) = store.cell_mut(address) {
                        held.set_value(value);
                        let sample = (r >> 36) as usize % held.len();
                        held.set_index(sample, value ^ 0x55);
                        held.remove_ink(sample);
                        let model_cell = model.get_mut(&address).unwrap();
                        model_cell.value = value;
                        model_cell.indices[sample] = value ^ 0x55;
                        model_cell.ink.remove(&sample);
                    } else {
                        assert!(!model.contains_key(&address), "step {step}");
                    }
                }
                5 => {
                    let mut held = store.cell_mut_or_insert(address, 7, 16);
                    let sample = (r >> 36) as usize % held.len();
                    let foreground = (r >> 44) as u8;
                    held.ink_or_insert_with(sample, || Ink {
                        foreground,
                        alpha: 0,
                        background: IndexedColor::Solid(3),
                    })
                    .alpha = 200;
                    let model_cell = model.entry(address).or_insert_with(|| DetailCell {
                        value: 7,
                        indices: vec![7; 16],
                        ink: HashMap::default(),
                    });
                    model_cell
                        .ink
                        .entry(sample)
                        .or_insert_with(|| Ink {
                            foreground,
                            alpha: 0,
                            background: IndexedColor::Solid(3),
                        })
                        .alpha = 200;
                }
                6 => {
                    let to = u64::from(address) + (r >> 40) % 700;
                    let expected: Vec<(u32, DetailCell)> = model
                        .range(address..)
                        .take_while(|(&key, _)| u64::from(key) < to)
                        .map(|(&key, cell)| (key, cell.clone()))
                        .collect();
                    let got: Vec<(u32, DetailCell)> = store
                        .range(address, to)
                        .into_iter()
                        .map(|(key, cell)| (key, (*cell).clone()))
                        .collect();
                    assert_eq!(got, expected, "step {step}");
                    assert_eq!(store.any_in(address, to), !expected.is_empty(), "step {step}");
                    for len in [4usize, 16] {
                        assert_eq!(
                            store.all_cells_have_len(address, to, len),
                            expected.iter().all(|(_, cell)| cell.indices.len() == len),
                            "step {step}"
                        );
                    }
                }
                _ => {
                    let held = model.get(&address);
                    assert_eq!(store.get(address).map(|cell| (*cell).clone()).as_ref(), held, "step {step}");
                    assert!(store.matches(address, held), "step {step}");
                    assert_eq!(store.contains(address), held.is_some(), "step {step}");
                    let mut viewed = None;
                    store.visit_cells(address, 1, |offset, view| {
                        assert_eq!(offset, 0);
                        let ink: Vec<(usize, Ink)> = view.inks().map(|(k, v)| (k, v.clone())).collect();
                        viewed = Some((view.indices().to_vec(), ink));
                    });
                    let expected = held.map(|cell| {
                        let mut ink: Vec<(usize, Ink)> = cell.ink.iter().map(|(&k, v)| (k, v.clone())).collect();
                        ink.sort_by_key(|&(sample, _)| sample);
                        (cell.indices.clone(), ink)
                    });
                    assert_eq!(viewed, expected, "step {step}");
                    // Storing a cell's own parts back changes nothing; a
                    // different value replaces it.
                    if let Some((indices, ink)) = expected {
                        let mut parts: Vec<(u8, Ink)> = ink.iter().map(|(k, v)| (*k as u8, v.clone())).collect();
                        let value = held.unwrap().value;
                        assert!(!store.store_parts(address, value, &indices, &mut parts), "step {step}");
                        let mut parts: Vec<(u8, Ink)> = ink.iter().map(|(k, v)| (*k as u8, v.clone())).collect();
                        assert!(store.store_parts(address, value ^ 1, &indices, &mut parts), "step {step}");
                        model.get_mut(&address).unwrap().value ^= 1;
                    }
                }
            }
            assert_eq!(store.len(), model.len(), "step {step}");
        }
        assert_eq!(store.addresses(), model.keys().copied().collect::<Vec<_>>());
    }

    /// Unchanged cells are handed out as one shared `Arc`, and a stored
    /// `Arc` is handed back; any edit ends the sharing.
    #[test]
    fn unchanged_cells_keep_their_identity() {
        let mut store = OffscreenDetail::default();
        let stored = cell(1, &[1, 2, 3, 4], &[(2, 9)]);
        store.insert(0x4_0000, &stored);
        assert!(Arc::ptr_eq(&store.get(0x4_0000).unwrap(), &stored));
        store.cell_mut_or_insert(0x4_0001, 5, 4);
        let built = store.get(0x4_0001).unwrap();
        assert!(Arc::ptr_eq(&store.get(0x4_0001).unwrap(), &built));
        store.cell_mut(0x4_0000).unwrap().set_value(8);
        let changed = store.get(0x4_0000).unwrap();
        assert!(!Arc::ptr_eq(&changed, &stored));
        assert_eq!(changed.value, 8);
        assert_eq!(changed.ink, stored.ink);
    }
}