ferravex_play/ui/
notices.rs

1//! Bounded transient text/semantic notices, driven by accepted game events.
2//!
3//! Storage is inline, with no allocation by the queue. Payloads and keys may
4//! borrow caller data or use fixed-size types; their own allocations and work
5//! are the caller's responsibility. The queue neither validates game actions
6//! nor deduplicates event IDs: deliver each accepted event once, after rules
7//! run (and after any network/event deduplication). A key groups notices, not
8//! events. Keep must-read outcomes/result panels outside this transient queue.
9//!
10//! All live entries age, including those hidden by higher priorities. The host
11//! chooses simulation or presentation seconds in [`NoticeQueue::advance`]; no
12//! clock, renderer, motion/flash preference or gameplay state is consulted.
13//! Render the same text under reduced motion, suppressing only host animation.
14//!
15//! This Pinball-style recipe consumes an accepted-score stream, never a score
16//! difference or an attempted bumper hit. Its saturating sum is explicit caller
17//! policy; a rejected request produces no accepted-score event. A real Pinball
18//! adapter can feed `PinballFeedback::points` after each `advance` exactly once.
19//!
20//! ```
21//! use ferravex_play::ui::notices::{
22//!     Notice, NoticeChange, NoticeLifetime, NoticePriority, NoticeQueue,
23//! };
24//!
25//! #[derive(Debug, PartialEq)]
26//! struct RecoveredPoints(u32);
27//! enum RuleResult { AcceptedScore(u32), RejectedRequest }
28//! let events = [RuleResult::AcceptedScore(100), RuleResult::RejectedRequest,
29//!               RuleResult::AcceptedScore(200)];
30//! let mut notices = NoticeQueue::<4, RecoveredPoints>::new();
31//! for event in events {
32//!     if let RuleResult::AcceptedScore(points) = event {
33//!         let change = notices.coalesce_with(Notice {
34//!             key: Some(1), priority: NoticePriority::Normal,
35//!             message: RecoveredPoints(points), lifetime_seconds: 2.,
36//!         }, NoticeLifetime::Refresh, |a, b| {
37//!             RecoveredPoints(a.0.saturating_add(b.0))
38//!         }).unwrap();
39//!         // Every displaced/incoming payload is returned for caller disposal.
40//!         assert!(matches!(change, NoticeChange::Inserted { evicted: None }
41//!             | NoticeChange::Coalesced { .. }));
42//!     }
43//! }
44//! assert_eq!(notices.front().unwrap().notice.message, RecoveredPoints(300));
45//! assert_eq!(notices.advance(0.5), Ok(0));
46//! assert_eq!(notices.front().unwrap().remaining_seconds, 1.5);
47//! let dismissed = notices.dismiss(&1).unwrap();
48//! assert_eq!(dismissed.message.0, 300);
49//! notices.clear(); // Restart transient presentation; no game state is changed.
50//! assert!(notices.is_empty());
51//! ```
52
53/// Higher priorities appear first and can displace strictly lower priorities.
54#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
55pub enum NoticePriority {
56    Low,
57    Normal,
58    High,
59    Critical,
60}
61
62/// Caller-owned notice specification. `None` keys are always independent.
63///
64/// Insertion validates a finite, strictly positive lifetime in seconds. Invalid
65/// specifications are returned intact. This duration remains the authored
66/// specification; read [`NoticeView::remaining_seconds`] for current expiry.
67#[derive(Debug, PartialEq)]
68pub struct Notice<T, K = u64> {
69    pub key: Option<K>,
70    pub priority: NoticePriority,
71    pub message: T,
72    pub lifetime_seconds: f64,
73}
74
75/// Policy for an existing matching key. This is grouping, not event deduplication.
76#[derive(Clone, Copy, Debug, PartialEq, Eq)]
77pub enum NoticeDuplicate {
78    /// Reject the incoming notice, preserving the existing entry and expiry.
79    Keep,
80    /// Replace even a higher priority matching notice; restart its lifetime.
81    Replace,
82}
83
84/// Expiry policy when a matching key is coalesced successfully.
85#[derive(Clone, Copy, Debug, PartialEq, Eq)]
86pub enum NoticeLifetime {
87    KeepRemaining,
88    /// Use the incoming duration, which can shorten the remaining lifetime.
89    Refresh,
90    /// Add the incoming duration, saturating at finite `f64::MAX` on overflow.
91    Extend,
92}
93
94/// Rejection leaves queue contents and expiry unchanged.
95#[derive(Clone, Copy, Debug, PartialEq, Eq)]
96pub enum NoticeRejection {
97    InvalidLifetime,
98    DuplicateKey,
99    /// Zero capacity or no entry with strictly lower priority.
100    Capacity,
101}
102
103/// A rejected insertion retains ownership of its entire input.
104#[derive(Debug, PartialEq)]
105pub struct NoticeRejected<T, K = u64> {
106    pub reason: NoticeRejection,
107    pub notice: Notice<T, K>,
108}
109
110/// Successful submission, returning payloads the queue no longer needs.
111/// No caller payload/key destructor is invoked by successful submission itself.
112#[derive(Debug, PartialEq)]
113pub enum NoticeChange<T, K = u64> {
114    Inserted {
115        evicted: Option<Notice<T, K>>,
116    },
117    Replaced {
118        previous: Notice<T, K>,
119    },
120    Coalesced {
121        previous_message: T,
122        incoming: Notice<T, K>,
123    },
124}
125
126/// A presentation snapshot borrowing the queue; iteration never consumes text.
127#[derive(Debug)]
128pub struct NoticeView<'a, T, K = u64> {
129    pub notice: &'a Notice<T, K>,
130    pub remaining_seconds: f64,
131}
132
133/// Invalid delta: nonfinite or negative. No time or entries were changed.
134#[derive(Clone, Copy, Debug, PartialEq, Eq)]
135pub struct NoticeTimeError;
136
137#[derive(Debug)]
138struct Entry<T, K> {
139    notice: Notice<T, K>,
140    remaining_seconds: f64,
141}
142
143/// Fixed inline storage with stable descending-priority presentation order.
144///
145/// Equal priorities retain arrival order. At saturation, an incoming notice can
146/// evict only a strictly lower priority: the oldest entry at the lowest priority
147/// is evicted first. Existing critical entries survive unrelated bursts, even
148/// critical bursts. Keyed replacement explicitly bypasses that rule and counts
149/// as a new arrival. Coalescing keeps the original key/specification, promotes
150/// priority to the larger value, and keeps its place unless promoted; promotion
151/// joins behind existing entries of the new priority.
152///
153/// Submission/removal use O(N) queue work and O(1) additional storage, excluding
154/// caller equality, merge and destructor work. Expiring multiple entries can
155/// take O(N²) work because each removal preserves order before disposal. Clear
156/// is O(N). No `Clone`, `Default` or `Copy` bound is required for messages or keys.
157/// Choose N/payload sizes to suit stack limits. Timing uses ordinary f64
158/// arithmetic: deltas below the representable precision may not reduce a large
159/// remaining lifetime; no cross-platform bitwise determinism is promised.
160///
161/// # Panic and disposal boundaries
162///
163/// Equality and merge callbacks run before structural mutation; a panic leaves
164/// queue metadata unchanged. Interior mutation/side effects in caller code are
165/// not rolled back. Coalescing receives shared references, returns a new payload
166/// and returns both discarded inputs to the host. `advance`, `clear`, dropping
167/// the queue, and dropping returned values can execute caller destructors.
168/// A destructor panic is not transactional: earlier changes remain, later work
169/// may be incomplete. Removed slots are detached/compacted before disposal, so
170/// storage/length remain valid. Destructors must not panic for normal use.
171#[derive(Debug)]
172pub struct NoticeQueue<const N: usize, T, K = u64> {
173    entries: [Option<Entry<T, K>>; N],
174    len: usize,
175}
176
177impl<const N: usize, T, K> Default for NoticeQueue<N, T, K> {
178    fn default() -> Self {
179        Self::new()
180    }
181}
182
183impl<const N: usize, T, K> NoticeQueue<N, T, K> {
184    /// Empty, reusable storage. Zero capacity is supported and rejects all input.
185    pub fn new() -> Self {
186        Self {
187            entries: std::array::from_fn(|_| None),
188            len: 0,
189        }
190    }
191
192    pub const fn capacity(&self) -> usize {
193        N
194    }
195
196    pub fn len(&self) -> usize {
197        self.len
198    }
199
200    pub fn is_empty(&self) -> bool {
201        self.len == 0
202    }
203
204    /// Highest priority, oldest entry at that priority; no visibility side effect.
205    pub fn front(&self) -> Option<NoticeView<'_, T, K>> {
206        self.iter().next()
207    }
208
209    /// All entries in presentation order, including ones a host chooses to hide.
210    pub fn iter(&self) -> impl ExactSizeIterator<Item = NoticeView<'_, T, K>> {
211        self.entries[..self.len].iter().map(|entry| {
212            let entry = entry.as_ref().expect("occupied prefix");
213            NoticeView {
214                notice: &entry.notice,
215                remaining_seconds: entry.remaining_seconds,
216            }
217        })
218    }
219
220    /// Remove the front notice without dropping its payload, including unkeyed text.
221    pub fn pop_front(&mut self) -> Option<Notice<T, K>> {
222        (!self.is_empty()).then(|| self.remove(0).notice)
223    }
224
225    /// Age every entry by explicit finite, nonnegative seconds. Zero is a no-op;
226    /// a delta reaching/exceeding remaining lifetime expires and drops the entry.
227    /// Subtraction clamps at zero without overflow. Returns the number expired.
228    /// Hidden entries expire too; no total wall time is accumulated.
229    pub fn advance(&mut self, delta_seconds: f64) -> Result<usize, NoticeTimeError> {
230        if !delta_seconds.is_finite() || delta_seconds < 0. {
231            return Err(NoticeTimeError);
232        }
233        let mut expired = 0;
234        let mut index = 0;
235        while index < self.len {
236            let entry = self.entries[index].as_mut().expect("occupied prefix");
237            entry.remaining_seconds = (entry.remaining_seconds - delta_seconds).max(0.);
238            if entry.remaining_seconds == 0. {
239                let removed = self.remove(index);
240                expired += 1;
241                drop(removed);
242            } else {
243                index += 1;
244            }
245        }
246        Ok(expired)
247    }
248
249    /// Drop all transient entries on restart, reusing the same inline storage.
250    /// No key or remaining lifetime survives reset. The queue owns no accumulated
251    /// clock, arrival counter or external event history.
252    pub fn clear(&mut self) {
253        while self.len > 0 {
254            drop(self.remove(self.len - 1));
255        }
256    }
257
258    fn remove(&mut self, index: usize) -> Entry<T, K> {
259        let entry = self.entries[index].take().expect("occupied prefix");
260        for next in index + 1..self.len {
261            self.entries[next - 1] = self.entries[next].take();
262        }
263        self.len -= 1;
264        entry
265    }
266
267    fn insert_sorted(&mut self, entry: Entry<T, K>) {
268        let index = self.entries[..self.len]
269            .iter()
270            .position(|other| other.as_ref().unwrap().notice.priority < entry.notice.priority)
271            .unwrap_or(self.len);
272        for previous in (index..self.len).rev() {
273            self.entries[previous + 1] = self.entries[previous].take();
274        }
275        self.entries[index] = Some(entry);
276        self.len += 1;
277    }
278}
279
280impl<const N: usize, T, K: Eq> NoticeQueue<N, T, K> {
281    /// Insert or apply an explicit duplicate-key policy. All lifetimes are
282    /// validated before key matching, including when keeping an existing entry.
283    ///
284    /// ```
285    /// use ferravex_play::ui::notices::{
286    ///     Notice, NoticeDuplicate, NoticePriority, NoticeQueue,
287    /// };
288    /// let mut notices = NoticeQueue::<2, &str, &str>::new();
289    /// notices.insert(Notice {
290    ///     key: Some("objective"), priority: NoticePriority::High,
291    ///     message: "Altar I awakened. The second altar is ready.",
292    ///     lifetime_seconds: 3.5,
293    /// }, NoticeDuplicate::Replace).unwrap(); // After objective acceptance.
294    /// assert_eq!(notices.capacity(), 2);
295    /// assert_eq!(notices.iter().len(), 1);
296    /// assert_eq!(notices.pop_front().unwrap().key, Some("objective"));
297    /// assert!(notices.is_empty());
298    /// ```
299    pub fn insert(
300        &mut self,
301        notice: Notice<T, K>,
302        duplicate: NoticeDuplicate,
303    ) -> Result<NoticeChange<T, K>, NoticeRejected<T, K>> {
304        self.validate(notice).and_then(|notice| {
305            if let Some(index) = self.matching(&notice.key) {
306                match duplicate {
307                    NoticeDuplicate::Keep => Err(NoticeRejected {
308                        reason: NoticeRejection::DuplicateKey,
309                        notice,
310                    }),
311                    NoticeDuplicate::Replace => {
312                        let previous = self.remove(index).notice;
313                        self.insert_sorted(Entry {
314                            remaining_seconds: notice.lifetime_seconds,
315                            notice,
316                        });
317                        Ok(NoticeChange::Replaced { previous })
318                    }
319                }
320            } else {
321                self.insert_new(notice)
322            }
323        })
324    }
325
326    /// Merge matching payloads using caller arithmetic/overflow policy. Missing
327    /// keys follow ordinary insertion/saturation, without invoking `merge`.
328    /// Invalid lifetimes also skip the callback. No payload is cloned or dropped
329    /// internally. Key equality/merge panics occur before queue mutation.
330    pub fn coalesce_with(
331        &mut self,
332        notice: Notice<T, K>,
333        lifetime: NoticeLifetime,
334        merge: impl FnOnce(&T, &T) -> T,
335    ) -> Result<NoticeChange<T, K>, NoticeRejected<T, K>> {
336        let notice = self.validate(notice)?;
337        let Some(index) = self.matching(&notice.key) else {
338            return self.insert_new(notice);
339        };
340        let entry = self.entries[index].as_ref().expect("occupied prefix");
341        let remaining_seconds = match lifetime {
342            NoticeLifetime::KeepRemaining => entry.remaining_seconds,
343            NoticeLifetime::Refresh => notice.lifetime_seconds,
344            NoticeLifetime::Extend => {
345                (entry.remaining_seconds + notice.lifetime_seconds).min(f64::MAX)
346            }
347        };
348        let message = merge(&entry.notice.message, &notice.message);
349        let entry = self.entries[index].as_mut().expect("occupied prefix");
350        let previous_message = std::mem::replace(&mut entry.notice.message, message);
351        entry.remaining_seconds = remaining_seconds;
352        if notice.priority > entry.notice.priority {
353            entry.notice.priority = notice.priority;
354            let entry = self.remove(index);
355            self.insert_sorted(entry);
356        }
357        Ok(NoticeChange::Coalesced {
358            previous_message,
359            incoming: notice,
360        })
361    }
362
363    /// Remove a keyed notice, returning ownership. A stale/missing key is a no-op.
364    pub fn dismiss(&mut self, key: &K) -> Option<Notice<T, K>> {
365        let index = self.entries[..self.len]
366            .iter()
367            .position(|entry| entry.as_ref().unwrap().notice.key.as_ref() == Some(key))?;
368        Some(self.remove(index).notice)
369    }
370
371    fn matching(&self, key: &Option<K>) -> Option<usize> {
372        key.as_ref().and_then(|key| {
373            self.entries[..self.len]
374                .iter()
375                .position(|entry| entry.as_ref().unwrap().notice.key.as_ref() == Some(key))
376        })
377    }
378
379    fn validate(&self, notice: Notice<T, K>) -> Result<Notice<T, K>, NoticeRejected<T, K>> {
380        if !notice.lifetime_seconds.is_finite() || notice.lifetime_seconds <= 0. {
381            Err(NoticeRejected {
382                reason: NoticeRejection::InvalidLifetime,
383                notice,
384            })
385        } else {
386            Ok(notice)
387        }
388    }
389
390    fn insert_new(
391        &mut self,
392        notice: Notice<T, K>,
393    ) -> Result<NoticeChange<T, K>, NoticeRejected<T, K>> {
394        let evicted = if self.len == N {
395            let candidate = self.entries[..self.len].last().and_then(|last| {
396                let lowest = last.as_ref().unwrap().notice.priority;
397                (lowest < notice.priority).then(|| {
398                    self.entries[..self.len]
399                        .iter()
400                        .position(|entry| entry.as_ref().unwrap().notice.priority == lowest)
401                        .unwrap()
402                })
403            });
404            let Some(index) = candidate else {
405                return Err(NoticeRejected {
406                    reason: NoticeRejection::Capacity,
407                    notice,
408                });
409            };
410            Some(self.remove(index).notice)
411        } else {
412            None
413        };
414        self.insert_sorted(Entry {
415            remaining_seconds: notice.lifetime_seconds,
416            notice,
417        });
418        Ok(NoticeChange::Inserted { evicted })
419    }
420}
421
422#[cfg(test)]
423mod tests {
424    use super::*;
425    use std::{cell::Cell, panic::AssertUnwindSafe, rc::Rc};
426
427    fn notice(key: u64, priority: NoticePriority, message: u32) -> Notice<u32> {
428        Notice {
429            key: Some(key),
430            priority,
431            message,
432            lifetime_seconds: 2.,
433        }
434    }
435
436    fn keys<const N: usize>(queue: &NoticeQueue<N, u32>) -> Vec<u64> {
437        queue.iter().map(|view| view.notice.key.unwrap()).collect()
438    }
439
440    #[test]
441    fn priority_saturation_preserves_critical_and_evicts_oldest_lowest() {
442        use NoticePriority::*;
443        let mut queue = NoticeQueue::<4, u32>::new();
444        for (key, priority) in [(1, Low), (2, Critical), (3, Low), (4, Normal)] {
445            queue
446                .insert(notice(key, priority, 100), NoticeDuplicate::Keep)
447                .unwrap();
448        }
449        assert_eq!(keys(&queue), [2, 4, 1, 3]);
450        let change = queue
451            .insert(notice(5, High, 100), NoticeDuplicate::Keep)
452            .unwrap();
453        assert!(matches!(
454            change,
455            NoticeChange::Inserted {
456                evicted: Some(Notice { key: Some(1), .. })
457            }
458        ));
459        assert_eq!(keys(&queue), [2, 5, 4, 3]);
460        for key in 6..10 {
461            queue
462                .insert(notice(key, Critical, 100), NoticeDuplicate::Keep)
463                .ok();
464        }
465        assert_eq!(keys(&queue), [2, 6, 7, 8]);
466        let rejected = queue
467            .insert(notice(10, Critical, 100), NoticeDuplicate::Keep)
468            .unwrap_err();
469        assert_eq!(rejected.reason, NoticeRejection::Capacity);
470        assert_eq!(rejected.notice.key, Some(10));
471        assert_eq!(keys(&queue), [2, 6, 7, 8]);
472    }
473
474    #[test]
475    fn replacement_and_keep_are_explicit_at_capacity() {
476        use NoticePriority::*;
477        let mut queue = NoticeQueue::<2, u32>::new();
478        queue
479            .insert(notice(1, Critical, 10), NoticeDuplicate::Keep)
480            .unwrap();
481        queue
482            .insert(notice(2, Normal, 20), NoticeDuplicate::Keep)
483            .unwrap();
484        queue.advance(1.).unwrap();
485        let rejected = queue
486            .insert(notice(1, Low, 99), NoticeDuplicate::Keep)
487            .unwrap_err();
488        assert_eq!(rejected.reason, NoticeRejection::DuplicateKey);
489        assert_eq!(queue.front().unwrap().remaining_seconds, 1.);
490        assert_eq!(queue.front().unwrap().notice.message, 10);
491        assert!(matches!(
492            queue
493                .insert(notice(1, Normal, 99), NoticeDuplicate::Replace)
494                .unwrap(),
495            NoticeChange::Replaced {
496                previous: Notice { message: 10, .. }
497            }
498        ));
499        assert_eq!(keys(&queue), [2, 1]); // Replacement is a new arrival.
500        assert_eq!(queue.iter().nth(1).unwrap().remaining_seconds, 2.);
501        assert_eq!(queue.dismiss(&1).unwrap().message, 99);
502        assert_eq!(queue.dismiss(&1), None);
503        assert_eq!(queue.pop_front().unwrap().key, Some(2));
504        assert_eq!(queue.pop_front(), None);
505    }
506
507    #[test]
508    fn coalescing_retains_order_promotes_priority_and_returns_inputs() {
509        use NoticePriority::*;
510        let mut queue = NoticeQueue::<3, u32>::new();
511        for (key, priority) in [(1, High), (2, Normal), (3, Normal)] {
512            queue
513                .insert(notice(key, priority, 100), NoticeDuplicate::Keep)
514                .unwrap();
515        }
516        queue.advance(0.5).unwrap();
517        let result = queue
518            .coalesce_with(notice(2, Low, 50), NoticeLifetime::KeepRemaining, |a, b| {
519                a.saturating_add(*b)
520            })
521            .unwrap();
522        assert!(matches!(
523            result,
524            NoticeChange::Coalesced {
525                previous_message: 100,
526                incoming: Notice { message: 50, .. }
527            }
528        ));
529        assert_eq!(keys(&queue), [1, 2, 3]);
530        assert_eq!(queue.iter().nth(1).unwrap().remaining_seconds, 1.5);
531        queue
532            .coalesce_with(notice(3, High, 25), NoticeLifetime::Refresh, |a, b| a + b)
533            .unwrap();
534        assert_eq!(keys(&queue), [1, 3, 2]);
535        let promoted = queue.iter().nth(1).unwrap();
536        assert_eq!(promoted.notice.message, 125);
537        assert_eq!(promoted.remaining_seconds, 2.);
538    }
539
540    #[test]
541    fn coalescing_lifetimes_and_point_overflow_saturate_without_infinity() {
542        let mut queue = NoticeQueue::<1, u32>::new();
543        queue
544            .insert(
545                notice(1, NoticePriority::Normal, u32::MAX),
546                NoticeDuplicate::Keep,
547            )
548            .unwrap();
549        queue.advance(1.5).unwrap();
550        let mut incoming = notice(1, NoticePriority::Low, 100);
551        incoming.lifetime_seconds = 0.25;
552        queue
553            .coalesce_with(incoming, NoticeLifetime::Refresh, |a, b| {
554                a.saturating_add(*b)
555            })
556            .unwrap();
557        assert_eq!(queue.front().unwrap().remaining_seconds, 0.25);
558        assert_eq!(queue.front().unwrap().notice.message, u32::MAX);
559        for _ in 0..2 {
560            let mut incoming = notice(1, NoticePriority::Low, 0);
561            incoming.lifetime_seconds = f64::MAX;
562            queue
563                .coalesce_with(incoming, NoticeLifetime::Extend, |a, _| *a)
564                .unwrap();
565        }
566        assert_eq!(queue.front().unwrap().remaining_seconds, f64::MAX);
567        assert_eq!(queue.advance(f64::MAX), Ok(1));
568    }
569
570    #[test]
571    fn invalid_time_is_atomic_and_skips_mergers_even_on_duplicate_or_empty_queue() {
572        let mut queue = NoticeQueue::<2, u32>::new();
573        queue
574            .insert(notice(1, NoticePriority::Normal, 5), NoticeDuplicate::Keep)
575            .unwrap();
576        for seconds in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1., 0., -0.] {
577            let mut invalid = notice(1, NoticePriority::Critical, 999);
578            invalid.lifetime_seconds = seconds;
579            let rejected = queue
580                .coalesce_with(invalid, NoticeLifetime::Extend, |_, _| {
581                    panic!("invalid input must not merge")
582                })
583                .unwrap_err();
584            assert_eq!(rejected.reason, NoticeRejection::InvalidLifetime);
585            assert_eq!(rejected.notice.message, 999);
586            let mut invalid = notice(1, NoticePriority::Low, 0);
587            invalid.lifetime_seconds = seconds;
588            assert_eq!(
589                queue
590                    .insert(invalid, NoticeDuplicate::Keep)
591                    .unwrap_err()
592                    .reason,
593                NoticeRejection::InvalidLifetime
594            );
595        }
596        for delta in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1.] {
597            assert_eq!(queue.advance(delta), Err(NoticeTimeError));
598            assert_eq!(queue.front().unwrap().remaining_seconds, 2.);
599            assert_eq!(queue.front().unwrap().notice.message, 5);
600        }
601        assert_eq!(queue.advance(-0.), Ok(0));
602        let mut empty = NoticeQueue::<0, u32>::new();
603        assert_eq!(empty.advance(f64::NAN), Err(NoticeTimeError));
604    }
605
606    #[test]
607    fn zero_capacity_unkeyed_and_missing_key_do_not_invoke_merge() {
608        let mut zero = NoticeQueue::<0, u32>::new();
609        assert_eq!(zero.capacity(), 0);
610        assert_eq!(
611            zero.coalesce_with(
612                notice(1, NoticePriority::Critical, 5),
613                NoticeLifetime::Refresh,
614                |_, _| panic!("no match")
615            )
616            .unwrap_err()
617            .reason,
618            NoticeRejection::Capacity
619        );
620        assert!(zero.front().is_none());
621        assert_eq!(zero.iter().len(), 0);
622        assert_eq!(zero.advance(1.), Ok(0));
623        assert!(zero.dismiss(&1).is_none());
624        zero.clear();
625        let mut queue = NoticeQueue::<2, u32>::new();
626        for _ in 0..2 {
627            let mut item = notice(1, NoticePriority::Normal, 5);
628            item.key = None;
629            queue
630                .coalesce_with(item, NoticeLifetime::Refresh, |_, _| panic!("unkeyed"))
631                .unwrap();
632        }
633        assert_eq!(queue.len(), 2);
634        assert!(queue.dismiss(&1).is_none());
635    }
636
637    #[test]
638    fn expiry_ages_hidden_entries_exactly_and_reset_reuses_storage() {
639        let mut queue = NoticeQueue::<4, u32>::default();
640        let storage = queue.entries.as_ptr();
641        for round in 0..8 {
642            for key in 1..=4 {
643                let priority = if key == 4 {
644                    NoticePriority::Critical
645                } else {
646                    NoticePriority::Low
647                };
648                let mut item = notice(key, priority, round);
649                item.lifetime_seconds = key as f64;
650                queue.insert(item, NoticeDuplicate::Keep).unwrap();
651            }
652            assert_eq!(queue.advance(0.), Ok(0));
653            assert_eq!(queue.advance(1.), Ok(1));
654            assert_eq!(keys(&queue), [4, 2, 3]);
655            assert_eq!(queue.advance(1.), Ok(1));
656            assert_eq!(keys(&queue), [4, 3]);
657            queue.clear();
658            assert_eq!(queue.len(), 0);
659            assert!(queue.entries.iter().all(Option::is_none));
660            assert_eq!(queue.entries.as_ptr(), storage);
661            assert_eq!(queue.advance(f64::MAX), Ok(0));
662        }
663    }
664
665    #[test]
666    fn accepted_rule_results_coalesce_once_and_preferences_do_not_remove_text() {
667        // A tiny authoritative claim rule: rejected repeats emit nothing.
668        let mut claimed = [false; 2];
669        let mut queue = NoticeQueue::<2, u32>::new();
670        for (id, points) in [(0, 100), (0, 999), (1, 200)] {
671            let accepted_points = if claimed[id] {
672                None
673            } else {
674                claimed[id] = true;
675                Some(points)
676            };
677            if let Some(points) = accepted_points {
678                queue
679                    .coalesce_with(
680                        notice(1, NoticePriority::Normal, points),
681                        NoticeLifetime::Refresh,
682                        |a, b| a.saturating_add(*b),
683                    )
684                    .unwrap();
685            }
686        }
687        assert_eq!(queue.front().unwrap().notice.message, 300);
688        for motion in [false, true] {
689            let policy = crate::feedback::FeedbackPolicy::new(motion, true, 0.).unwrap();
690            assert_eq!(policy.reduced_motion(), motion);
691            // Paint semantic text for either policy; only animation consults it.
692            assert_eq!(queue.front().unwrap().notice.message, 300);
693        }
694    }
695
696    #[test]
697    fn merge_panic_preserves_queue_and_new_key_never_calls_merge() {
698        let mut queue = NoticeQueue::<1, u32>::new();
699        queue
700            .coalesce_with(
701                notice(1, NoticePriority::Normal, 5),
702                NoticeLifetime::Refresh,
703                |_, _| panic!("no match"),
704            )
705            .unwrap();
706        queue.advance(1.).unwrap();
707        let panic = std::panic::catch_unwind(AssertUnwindSafe(|| {
708            queue.coalesce_with(
709                notice(1, NoticePriority::Critical, 10),
710                NoticeLifetime::Extend,
711                |_, _| panic!("caller merge"),
712            )
713        }));
714        assert!(panic.is_err());
715        let retained = queue.front().unwrap();
716        assert_eq!(retained.notice.message, 5);
717        assert_eq!(retained.notice.priority, NoticePriority::Normal);
718        assert_eq!(retained.remaining_seconds, 1.);
719        assert_eq!(queue.len(), 1);
720    }
721
722    #[test]
723    fn equality_panic_preserves_queue_and_expiry() {
724        #[derive(Debug)]
725        struct Key(bool);
726        impl PartialEq for Key {
727            fn eq(&self, other: &Self) -> bool {
728                assert!(!other.0, "caller equality");
729                true
730            }
731        }
732        impl Eq for Key {}
733        let mut queue = NoticeQueue::<1, u32, Key>::new();
734        let make = |panic| Notice {
735            key: Some(Key(panic)),
736            message: 5,
737            priority: NoticePriority::Normal,
738            lifetime_seconds: 2.,
739        };
740        queue.insert(make(false), NoticeDuplicate::Keep).unwrap();
741        queue.advance(1.).unwrap();
742        let panic = std::panic::catch_unwind(AssertUnwindSafe(|| {
743            queue.insert(make(true), NoticeDuplicate::Replace)
744        }));
745        assert!(panic.is_err());
746        assert_eq!(queue.len(), 1);
747        assert_eq!(queue.front().unwrap().remaining_seconds, 1.);
748        assert!(!queue.front().unwrap().notice.key.as_ref().unwrap().0);
749    }
750
751    #[test]
752    fn borrowed_nonclone_payloads_and_returned_drops_stay_caller_controlled() {
753        #[derive(Debug)]
754        struct Message<'a>(&'a Cell<u32>);
755        impl Drop for Message<'_> {
756            fn drop(&mut self) {
757                self.0.set(self.0.get() + 1);
758            }
759        }
760        let drops = Cell::new(0);
761        let make = |priority| Notice {
762            key: Some("caption"),
763            priority,
764            message: Message(&drops),
765            lifetime_seconds: 1.,
766        };
767        let mut queue = NoticeQueue::<1, Message<'_>, &str>::new();
768        queue
769            .insert(make(NoticePriority::Low), NoticeDuplicate::Keep)
770            .unwrap();
771        let change = queue
772            .coalesce_with(
773                make(NoticePriority::High),
774                NoticeLifetime::Refresh,
775                |a, _| Message(a.0),
776            )
777            .unwrap();
778        assert_eq!(drops.get(), 0);
779        drop(change);
780        assert_eq!(drops.get(), 2); // Prior and incoming messages returned.
781        let replaced = queue
782            .insert(make(NoticePriority::Normal), NoticeDuplicate::Replace)
783            .unwrap();
784        assert_eq!(drops.get(), 2);
785        drop(replaced);
786        assert_eq!(drops.get(), 3);
787        let rejected = queue
788            .insert(make(NoticePriority::Low), NoticeDuplicate::Keep)
789            .unwrap_err();
790        assert_eq!(drops.get(), 3);
791        drop(rejected);
792        assert_eq!(drops.get(), 4);
793        queue.advance(1.).unwrap();
794        assert_eq!(drops.get(), 5);
795        queue
796            .insert(make(NoticePriority::Normal), NoticeDuplicate::Keep)
797            .unwrap();
798        queue.clear();
799        assert_eq!(drops.get(), 6);
800    }
801
802    #[test]
803    fn destructor_panic_detaches_slot_before_unwind_and_storage_can_be_reused() {
804        #[derive(Debug)]
805        struct Message(Rc<Cell<bool>>);
806        impl Drop for Message {
807            fn drop(&mut self) {
808                assert!(!self.0.replace(false), "caller drop");
809            }
810        }
811        let panic_next_drop = Rc::new(Cell::new(true));
812        let mut queue = NoticeQueue::<3, Message>::new();
813        let make = |key, panic_on_drop| Notice {
814            key: Some(key),
815            priority: NoticePriority::Normal,
816            message: Message(panic_on_drop),
817            lifetime_seconds: 1.,
818        };
819        queue
820            .insert(make(1, panic_next_drop.clone()), NoticeDuplicate::Keep)
821            .unwrap();
822        queue
823            .insert(make(2, Rc::new(Cell::new(false))), NoticeDuplicate::Keep)
824            .unwrap();
825        queue
826            .insert(make(3, Rc::new(Cell::new(false))), NoticeDuplicate::Keep)
827            .unwrap();
828        assert!(std::panic::catch_unwind(AssertUnwindSafe(|| queue.advance(1.))).is_err());
829        assert_eq!(queue.len(), 2);
830        assert_eq!(queue.front().unwrap().notice.key, Some(2));
831        assert_eq!(queue.front().unwrap().remaining_seconds, 1.); // Tail was not aged.
832        assert!(queue.entries[2].is_none());
833        queue
834            .insert(make(4, panic_next_drop), NoticeDuplicate::Keep)
835            .unwrap();
836        queue.clear();
837        assert!(queue.is_empty());
838    }
839}