rustsim-core 0.0.1

Core ABM engine: agents, models, stores, schedulers, stepping, data collection
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
737
738
739
740
741
742
743
744
745
746
//! Inter-agent messaging system inspired by FlameGPU2.
//!
//! FlameGPU2 achieves massive GPU throughput by decoupling agent communication
//! from direct neighbor queries. Agents **output messages** in one phase, then
//! **read messages** in the next. This two-phase approach eliminates data races
//! and enables efficient GPU-side spatial indexing.
//!
//! rustsim mirrors this with a CPU-first messaging layer that can be backed
//! by GPU buffers when CUDA is available.
//!
//! # Message Types
//!
//! | Type | Description | FlameGPU2 equivalent |
//! |------|-------------|---------------------|
//! | [`BruteForceMessages`] | All-to-all; every agent reads every message | `MessageBruteForce` |
//! | [`SpatialMessages2D`] | Spatial-hashing 2D; agents read messages within a radius | `MessageSpatial2D` |
//! | [`SpatialMessages3D`] | Spatial-hashing 3D; agents read messages within a radius | `MessageSpatial3D` |
//!
//! # Two-Phase Pattern
//!
//! ```ignore
//! // Phase 1: agents output messages
//! for id in agent_ids {
//!     let agent = store.get(id);
//!     messages.output(MyMessage { x: agent.x, y: agent.y, vx: agent.vx });
//! }
//! messages.finalize(); // build spatial index
//!
//! // Phase 2: agents read messages and update
//! for id in agent_ids {
//!     let mut agent = store.get_mut(id);
//!     for msg in messages.read_nearby(agent.x, agent.y, radius) {
//!         // accumulate forces, etc.
//!     }
//! }
//! messages.clear();
//! ```

use std::collections::HashMap;
use thiserror::Error;

/// Errors returned by messaging configuration validation.
#[derive(Debug, Clone, Copy, PartialEq, Error)]
pub enum MessageConfigError {
    #[error("radius must be positive")]
    InvalidRadius,
}

/// Errors returned when a message buffer is used outside its valid phase.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
pub enum MessagePhaseError {
    /// Messages can only be output before finalization.
    #[error("cannot output messages after finalize")]
    AlreadyFinalized,
    /// Messages can only be read after finalization.
    #[error("must finalize messages before reading")]
    NotFinalized,
}

/// A message that can be exchanged between agents.
///
/// Messages are value types -- they are copied into the message buffer
/// during the output phase. Implement this trait for your message struct.
pub trait Message: Clone + Send + Sync + 'static {}

// Blanket impl: anything Clone + Send + Sync + 'static is a Message.
impl<T: Clone + Send + Sync + 'static> Message for T {}

/// Brute-force message list -- every agent can read every message.
///
/// This is the simplest messaging pattern. Each step, agents push messages
/// in the output phase, then iterate all messages in the input phase.
///
/// Performance: O(N) per agent for N messages. Suitable for small populations
/// or global broadcasts.
///
/// Mirrors FlameGPU2 `MessageBruteForce`.
#[derive(Debug, Clone)]
pub struct BruteForceMessages<M> {
    buffer: Vec<M>,
    finalized: bool,
}

impl<M: Clone> BruteForceMessages<M> {
    /// Create an empty brute-force message list.
    pub fn new() -> Self {
        Self {
            buffer: Vec::new(),
            finalized: false,
        }
    }

    /// Create with pre-allocated capacity.
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            buffer: Vec::with_capacity(capacity),
            finalized: false,
        }
    }

    /// Output a message (phase 1).
    pub fn output(&mut self, message: M) {
        self.try_output(message)
            .expect("cannot output after finalize");
    }

    /// Try to output a message (phase 1), returning a typed phase error on misuse.
    pub fn try_output(&mut self, message: M) -> Result<(), MessagePhaseError> {
        if self.finalized {
            return Err(MessagePhaseError::AlreadyFinalized);
        }
        self.buffer.push(message);
        Ok(())
    }

    /// Finalize the message list for reading (phase boundary).
    ///
    /// For brute-force, this is a no-op but enforces the two-phase protocol.
    pub fn finalize(&mut self) {
        self.finalized = true;
    }

    /// Iterate all messages (phase 2).
    ///
    /// # Panics
    ///
    /// Panics if called before [`finalize`](Self::finalize). Use
    /// [`try_read_all`](Self::try_read_all) to handle phase errors explicitly.
    pub fn read_all(&self) -> &[M] {
        self.try_read_all()
            .expect("must finalize messages before reading")
    }

    /// Try to iterate all messages (phase 2), returning a typed phase error on misuse.
    pub fn try_read_all(&self) -> Result<&[M], MessagePhaseError> {
        if !self.finalized {
            return Err(MessagePhaseError::NotFinalized);
        }
        Ok(&self.buffer)
    }

    /// Whether the message buffer has been finalized for reading.
    pub fn is_finalized(&self) -> bool {
        self.finalized
    }

    /// Number of messages in the buffer.
    pub fn len(&self) -> usize {
        self.buffer.len()
    }

    /// Returns `true` if no messages have been output.
    pub fn is_empty(&self) -> bool {
        self.buffer.is_empty()
    }

    /// Clear the message buffer for the next step.
    pub fn clear(&mut self) {
        self.buffer.clear();
        self.finalized = false;
    }
}

impl<M: Clone> Default for BruteForceMessages<M> {
    fn default() -> Self {
        Self::new()
    }
}

/// 2D spatial message list with spatial-hashing neighbor lookup.
///
/// Messages carry an `(x, y)` position. During finalization, messages are
/// sorted into a uniform grid of bins (side length = `radius`). During
/// the read phase, agents query nearby messages by position and only
/// iterate bins within the search radius.
///
/// This mirrors FlameGPU2's `MessageSpatial2D` and its **Partition Boundary
/// Matrix (PBM)** -- a sorted index of messages by spatial bin.
///
/// Performance: O(k) per agent where k = messages in neighboring bins.
#[derive(Debug, Clone)]
pub struct SpatialMessages2D<M> {
    messages: Vec<M>,
    positions: Vec<(f32, f32)>,
    radius: f32,
    // PBM-like: bin -> (start_index, count) into the sorted message arrays
    bin_map: HashMap<(i32, i32), (usize, usize)>,
    // Sorted indices for spatial iteration
    sorted_indices: Vec<usize>,
    finalized: bool,
}

impl<M: Clone> SpatialMessages2D<M> {
    /// Create a new 2D spatial message list.
    ///
    /// `radius` is both the search radius and the bin side length.
    pub fn new(radius: f32) -> Result<Self, MessageConfigError> {
        if radius <= 0.0 {
            return Err(MessageConfigError::InvalidRadius);
        }
        Ok(Self {
            messages: Vec::new(),
            positions: Vec::new(),
            radius,
            bin_map: HashMap::new(),
            sorted_indices: Vec::new(),
            finalized: false,
        })
    }

    /// Output a message at a 2D position (phase 1).
    pub fn output(&mut self, message: M, x: f32, y: f32) {
        self.try_output(message, x, y)
            .expect("cannot output after finalize");
    }

    /// Try to output a message at a 2D position, returning a typed phase error on misuse.
    pub fn try_output(&mut self, message: M, x: f32, y: f32) -> Result<(), MessagePhaseError> {
        if self.finalized {
            return Err(MessagePhaseError::AlreadyFinalized);
        }
        self.messages.push(message);
        self.positions.push((x, y));
        Ok(())
    }

    /// Build the spatial index (phase boundary).
    ///
    /// This constructs a PBM-like structure: messages are logically sorted
    /// by bin, and a map records the (start, count) of each bin.
    pub fn finalize(&mut self) {
        let n = self.messages.len();
        let inv_radius = 1.0 / self.radius;

        // Assign each message to a bin
        let mut bin_assignments: Vec<(i32, i32)> = Vec::with_capacity(n);
        for &(x, y) in &self.positions {
            let bx = (x * inv_radius).floor() as i32;
            let by = (y * inv_radius).floor() as i32;
            bin_assignments.push((bx, by));
        }

        // Create sorted index by bin (mimics PBM sort)
        self.sorted_indices.clear();
        self.sorted_indices.extend(0..n);
        self.sorted_indices
            .sort_unstable_by(|&a, &b| bin_assignments[a].cmp(&bin_assignments[b]));

        // Build bin_map: (bin) -> (start_in_sorted, count)
        self.bin_map.clear();
        if !self.sorted_indices.is_empty() {
            let mut current_bin = bin_assignments[self.sorted_indices[0]];
            let mut start = 0;

            for i in 1..n {
                let bin = bin_assignments[self.sorted_indices[i]];
                if bin != current_bin {
                    self.bin_map.insert(current_bin, (start, i - start));
                    current_bin = bin;
                    start = i;
                }
            }
            self.bin_map.insert(current_bin, (start, n - start));
        }

        self.finalized = true;
    }

    /// Iterate messages within `radius` of `(x, y)` (phase 2).
    ///
    /// Returns an iterator yielding `(message_ref, distance_squared)`.
    /// The caller should filter by `distance_squared <= radius * radius`
    /// for exact circular queries (the method returns a superset from
    /// the bin neighborhood).
    ///
    /// # Panics
    ///
    /// Panics if called before [`finalize`](Self::finalize). Use
    /// [`try_read_nearby`](Self::try_read_nearby) to handle phase errors explicitly.
    pub fn read_nearby(&self, x: f32, y: f32, radius: f32) -> SpatialIter2D<'_, M> {
        self.try_read_nearby(x, y, radius)
            .expect("must finalize messages before reading")
    }

    /// Try to iterate messages within `radius` of `(x, y)` (phase 2).
    pub fn try_read_nearby(
        &self,
        x: f32,
        y: f32,
        radius: f32,
    ) -> Result<SpatialIter2D<'_, M>, MessagePhaseError> {
        if !self.finalized {
            return Err(MessagePhaseError::NotFinalized);
        }
        let inv = 1.0 / self.radius;
        let center_bx = (x * inv).floor() as i32;
        let center_by = (y * inv).floor() as i32;
        let grid_r = ((radius / self.radius).ceil() as i32).max(1);

        // Seed the first bin
        let first_dx = -grid_r;
        let first_dy = -grid_r;
        let bx = center_bx + first_dx;
        let by = center_by + first_dy;
        let (bin_start, bin_count) = self.bin_map.get(&(bx, by)).copied().unwrap_or((0, 0));

        Ok(SpatialIter2D {
            messages: &self.messages,
            positions: &self.positions,
            sorted_indices: &self.sorted_indices,
            bin_map: &self.bin_map,
            query_x: x,
            query_y: y,
            radius_sq: radius * radius,
            center_bx,
            center_by,
            grid_r,
            cur_dx: first_dx,
            cur_dy: first_dy,
            bin_start,
            bin_offset: 0,
            bin_count,
        })
    }

    /// Whether the message buffer has been finalized for reading.
    pub fn is_finalized(&self) -> bool {
        self.finalized
    }

    /// Number of messages.
    pub fn len(&self) -> usize {
        self.messages.len()
    }

    /// Returns `true` if no messages have been output.
    pub fn is_empty(&self) -> bool {
        self.messages.is_empty()
    }

    /// Clear all messages and the spatial index for the next step.
    pub fn clear(&mut self) {
        self.messages.clear();
        self.positions.clear();
        self.bin_map.clear();
        self.sorted_indices.clear();
        self.finalized = false;
    }
}

/// Iterator over spatially-nearby messages.
pub struct SpatialIter2D<'a, M> {
    messages: &'a [M],
    positions: &'a [(f32, f32)],
    sorted_indices: &'a [usize],
    bin_map: &'a HashMap<(i32, i32), (usize, usize)>,
    query_x: f32,
    query_y: f32,
    radius_sq: f32,
    center_bx: i32,
    center_by: i32,
    grid_r: i32,
    cur_dx: i32,
    cur_dy: i32,
    // Current bin's start offset in sorted_indices and remaining count
    bin_start: usize,
    bin_offset: usize,
    bin_count: usize,
}

impl<'a, M> Iterator for SpatialIter2D<'a, M> {
    type Item = (&'a M, f32);

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            // Drain entries from the current bin
            while self.bin_offset < self.bin_count {
                let idx = self.sorted_indices[self.bin_start + self.bin_offset];
                self.bin_offset += 1;

                let (px, py) = self.positions[idx];
                let dx = self.query_x - px;
                let dy = self.query_y - py;
                let dist_sq = dx * dx + dy * dy;
                if dist_sq <= self.radius_sq {
                    return Some((&self.messages[idx], dist_sq));
                }
            }

            // Advance to next bin in the grid neighborhood
            loop {
                self.cur_dx += 1;
                if self.cur_dx > self.grid_r {
                    self.cur_dx = -self.grid_r;
                    self.cur_dy += 1;
                    if self.cur_dy > self.grid_r {
                        return None; // exhausted all bins
                    }
                }

                let bx = self.center_bx + self.cur_dx;
                let by = self.center_by + self.cur_dy;
                if let Some(&(start, count)) = self.bin_map.get(&(bx, by)) {
                    self.bin_start = start;
                    self.bin_offset = 0;
                    self.bin_count = count;
                    break; // found a non-empty bin, go drain it
                }
            }
        }
    }
}

/// 3D spatial message list with spatial-hashing neighbor lookup.
///
/// Same concept as [`SpatialMessages2D`] but for 3D positions.
///
/// Mirrors FlameGPU2 `MessageSpatial3D` and its 3D Partition Boundary Matrix.
#[derive(Debug, Clone)]
pub struct SpatialMessages3D<M> {
    messages: Vec<M>,
    positions: Vec<(f32, f32, f32)>,
    radius: f32,
    bin_map: HashMap<(i32, i32, i32), (usize, usize)>,
    sorted_indices: Vec<usize>,
    finalized: bool,
}

impl<M: Clone> SpatialMessages3D<M> {
    /// Create a new 3D spatial message list.
    pub fn new(radius: f32) -> Result<Self, MessageConfigError> {
        if radius <= 0.0 {
            return Err(MessageConfigError::InvalidRadius);
        }
        Ok(Self {
            messages: Vec::new(),
            positions: Vec::new(),
            radius,
            bin_map: HashMap::new(),
            sorted_indices: Vec::new(),
            finalized: false,
        })
    }

    /// Output a message at a 3D position (phase 1).
    pub fn output(&mut self, message: M, x: f32, y: f32, z: f32) {
        self.try_output(message, x, y, z)
            .expect("cannot output after finalize");
    }

    /// Try to output a message at a 3D position, returning a typed phase error on misuse.
    pub fn try_output(
        &mut self,
        message: M,
        x: f32,
        y: f32,
        z: f32,
    ) -> Result<(), MessagePhaseError> {
        if self.finalized {
            return Err(MessagePhaseError::AlreadyFinalized);
        }
        self.messages.push(message);
        self.positions.push((x, y, z));
        Ok(())
    }

    /// Build the spatial index (phase boundary).
    pub fn finalize(&mut self) {
        let n = self.messages.len();
        let inv_radius = 1.0 / self.radius;

        let mut bin_assignments: Vec<(i32, i32, i32)> = Vec::with_capacity(n);
        for &(x, y, z) in &self.positions {
            let bx = (x * inv_radius).floor() as i32;
            let by = (y * inv_radius).floor() as i32;
            let bz = (z * inv_radius).floor() as i32;
            bin_assignments.push((bx, by, bz));
        }

        self.sorted_indices.clear();
        self.sorted_indices.extend(0..n);
        self.sorted_indices
            .sort_unstable_by(|&a, &b| bin_assignments[a].cmp(&bin_assignments[b]));

        self.bin_map.clear();
        if !self.sorted_indices.is_empty() {
            let mut current_bin = bin_assignments[self.sorted_indices[0]];
            let mut start = 0;

            for i in 1..n {
                let bin = bin_assignments[self.sorted_indices[i]];
                if bin != current_bin {
                    self.bin_map.insert(current_bin, (start, i - start));
                    current_bin = bin;
                    start = i;
                }
            }
            self.bin_map.insert(current_bin, (start, n - start));
        }

        self.finalized = true;
    }

    /// Iterate messages within `radius` of `(x, y, z)` (phase 2).
    ///
    /// Returns an iterator yielding `(message_ref, distance_squared)`.
    ///
    /// # Panics
    ///
    /// Panics if called before [`finalize`](Self::finalize). Use
    /// [`try_read_nearby`](Self::try_read_nearby) to handle phase errors explicitly.
    pub fn read_nearby(&self, x: f32, y: f32, z: f32, radius: f32) -> SpatialIter3D<'_, M> {
        self.try_read_nearby(x, y, z, radius)
            .expect("must finalize messages before reading")
    }

    /// Try to iterate messages within `radius` of `(x, y, z)` (phase 2).
    pub fn try_read_nearby(
        &self,
        x: f32,
        y: f32,
        z: f32,
        radius: f32,
    ) -> Result<SpatialIter3D<'_, M>, MessagePhaseError> {
        if !self.finalized {
            return Err(MessagePhaseError::NotFinalized);
        }
        let inv = 1.0 / self.radius;
        let center_bx = (x * inv).floor() as i32;
        let center_by = (y * inv).floor() as i32;
        let center_bz = (z * inv).floor() as i32;
        let grid_r = ((radius / self.radius).ceil() as i32).max(1);

        // Seed the first bin
        let first_dx = -grid_r;
        let first_dy = -grid_r;
        let first_dz = -grid_r;
        let bx = center_bx + first_dx;
        let by = center_by + first_dy;
        let bz = center_bz + first_dz;
        let (bin_start, bin_count) = self.bin_map.get(&(bx, by, bz)).copied().unwrap_or((0, 0));

        Ok(SpatialIter3D {
            messages: &self.messages,
            positions: &self.positions,
            sorted_indices: &self.sorted_indices,
            bin_map: &self.bin_map,
            query_x: x,
            query_y: y,
            query_z: z,
            radius_sq: radius * radius,
            center_bx,
            center_by,
            center_bz,
            grid_r,
            cur_dx: first_dx,
            cur_dy: first_dy,
            cur_dz: first_dz,
            bin_start,
            bin_offset: 0,
            bin_count,
        })
    }

    /// Whether the message buffer has been finalized for reading.
    pub fn is_finalized(&self) -> bool {
        self.finalized
    }

    /// Number of messages.
    pub fn len(&self) -> usize {
        self.messages.len()
    }

    /// Returns `true` if no messages have been output.
    pub fn is_empty(&self) -> bool {
        self.messages.is_empty()
    }

    /// Clear all messages and the spatial index for the next step.
    pub fn clear(&mut self) {
        self.messages.clear();
        self.positions.clear();
        self.bin_map.clear();
        self.sorted_indices.clear();
        self.finalized = false;
    }
}

/// Iterator over spatially-nearby 3D messages.
pub struct SpatialIter3D<'a, M> {
    messages: &'a [M],
    positions: &'a [(f32, f32, f32)],
    sorted_indices: &'a [usize],
    bin_map: &'a HashMap<(i32, i32, i32), (usize, usize)>,
    query_x: f32,
    query_y: f32,
    query_z: f32,
    radius_sq: f32,
    center_bx: i32,
    center_by: i32,
    center_bz: i32,
    grid_r: i32,
    cur_dx: i32,
    cur_dy: i32,
    cur_dz: i32,
    bin_start: usize,
    bin_offset: usize,
    bin_count: usize,
}

impl<'a, M> Iterator for SpatialIter3D<'a, M> {
    type Item = (&'a M, f32);

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            // Drain entries from the current bin
            while self.bin_offset < self.bin_count {
                let idx = self.sorted_indices[self.bin_start + self.bin_offset];
                self.bin_offset += 1;

                let (px, py, pz) = self.positions[idx];
                let dx = self.query_x - px;
                let dy = self.query_y - py;
                let dz = self.query_z - pz;
                let dist_sq = dx * dx + dy * dy + dz * dz;
                if dist_sq <= self.radius_sq {
                    return Some((&self.messages[idx], dist_sq));
                }
            }

            // Advance to next bin in the 3D grid neighborhood
            loop {
                self.cur_dx += 1;
                if self.cur_dx > self.grid_r {
                    self.cur_dx = -self.grid_r;
                    self.cur_dy += 1;
                    if self.cur_dy > self.grid_r {
                        self.cur_dy = -self.grid_r;
                        self.cur_dz += 1;
                        if self.cur_dz > self.grid_r {
                            return None; // exhausted all bins
                        }
                    }
                }

                let bx = self.center_bx + self.cur_dx;
                let by = self.center_by + self.cur_dy;
                let bz = self.center_bz + self.cur_dz;
                if let Some(&(start, count)) = self.bin_map.get(&(bx, by, bz)) {
                    self.bin_start = start;
                    self.bin_offset = 0;
                    self.bin_count = count;
                    break; // found a non-empty bin, go drain it
                }
            }
        }
    }
}

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

    #[test]
    fn brute_force_basic() {
        let mut msgs = BruteForceMessages::new();
        msgs.output(42i32);
        msgs.output(99);
        msgs.finalize();
        assert_eq!(msgs.read_all(), &[42, 99]);
        msgs.clear();
        assert!(msgs.is_empty());
    }

    #[test]
    fn brute_force_phase_errors_are_typed() {
        let mut msgs = BruteForceMessages::new();
        assert_eq!(msgs.try_read_all(), Err(MessagePhaseError::NotFinalized));
        msgs.try_output(1).unwrap();
        msgs.finalize();
        assert_eq!(msgs.try_output(2), Err(MessagePhaseError::AlreadyFinalized));
        assert_eq!(msgs.try_read_all().unwrap(), &[1]);
    }

    #[test]
    fn spatial_2d_basic() {
        let mut msgs = SpatialMessages2D::new(1.0).unwrap();
        msgs.output("a", 0.0, 0.0);
        msgs.output("b", 0.5, 0.5);
        msgs.output("c", 10.0, 10.0);
        msgs.finalize();

        // Query near origin -- should find "a" and "b" but not "c"
        let nearby: Vec<_> = msgs.read_nearby(0.0, 0.0, 1.0).collect();
        assert_eq!(nearby.len(), 2);
        let labels: Vec<&str> = nearby.iter().map(|(&m, _)| m).collect();
        assert!(labels.contains(&"a"));
        assert!(labels.contains(&"b"));
    }

    #[test]
    fn spatial_2d_phase_errors_are_typed() {
        let mut msgs = SpatialMessages2D::new(1.0).unwrap();
        assert_eq!(
            msgs.try_read_nearby(0.0, 0.0, 1.0).err(),
            Some(MessagePhaseError::NotFinalized)
        );
        msgs.try_output("a", 0.0, 0.0).unwrap();
        msgs.finalize();
        assert_eq!(
            msgs.try_output("b", 1.0, 1.0),
            Err(MessagePhaseError::AlreadyFinalized)
        );
    }

    #[test]
    fn spatial_3d_basic() {
        let mut msgs = SpatialMessages3D::new(1.0).unwrap();
        msgs.output("a", 0.0, 0.0, 0.0);
        msgs.output("b", 0.5, 0.5, 0.5);
        msgs.output("c", 10.0, 10.0, 10.0);
        msgs.finalize();

        let nearby: Vec<_> = msgs.read_nearby(0.0, 0.0, 0.0, 1.0).collect();
        assert_eq!(nearby.len(), 2);
        let labels: Vec<&str> = nearby.iter().map(|(&m, _)| m).collect();
        assert!(labels.contains(&"a"));
        assert!(labels.contains(&"b"));
    }

    #[test]
    fn spatial_3d_phase_errors_are_typed() {
        let mut msgs = SpatialMessages3D::new(1.0).unwrap();
        assert_eq!(
            msgs.try_read_nearby(0.0, 0.0, 0.0, 1.0).err(),
            Some(MessagePhaseError::NotFinalized)
        );
        msgs.try_output("a", 0.0, 0.0, 0.0).unwrap();
        msgs.finalize();
        assert_eq!(
            msgs.try_output("b", 1.0, 1.0, 1.0),
            Err(MessagePhaseError::AlreadyFinalized)
        );
    }
}