Skip to main content

vector_core/
compact.rs

1//! Compact message storage with binary IDs and interned strings.
2//!
3//! Part of vector-core — the single source of truth for compact message types.
4//!
5//! This module provides memory-efficient message storage:
6//! - `[u8; 32]` for IDs instead of hex strings (saves ~56 bytes per ID)
7//! - Interned npubs via `NpubInterner` (each unique npub stored once)
8//! - Bitflags for boolean states (1 byte instead of 4+)
9//! - Binary search for O(log n) message lookup
10//! - Boxed optional fields (replied_to, wrapper_id) to save inline space
11//! - Compact timestamp (u32 seconds since 2020 epoch)
12
13use crate::types::{Attachment, EditEntry, ImageMetadata, Reaction, SiteMetadata};
14use crate::simd::hex::{bytes_to_hex_32, bytes_to_hex_string, hex_to_bytes_32};
15
16/// Decode a hex string of up to 32 hex chars into [u8; 16], left-aligned.
17/// Pads short inputs with '0' on the right before decoding.
18fn hex_to_bytes_16(hex: &str) -> [u8; 16] {
19    let mut out = [0u8; 16];
20    let h = hex.as_bytes();
21    // Pad to 32 hex chars with '0'
22    let mut padded = [b'0'; 32];
23    let copy_len = h.len().min(32);
24    padded[..copy_len].copy_from_slice(&h[..copy_len]);
25    for i in 0..16 {
26        let hi = hex_nibble(padded[i * 2]);
27        let lo = hex_nibble(padded[i * 2 + 1]);
28        out[i] = (hi << 4) | lo;
29    }
30    out
31}
32
33#[inline]
34fn hex_nibble(b: u8) -> u8 {
35    match b {
36        b'0'..=b'9' => b - b'0',
37        b'a'..=b'f' => b - b'a' + 10,
38        b'A'..=b'F' => b - b'A' + 10,
39        _ => 0,
40    }
41}
42
43// ============================================================================
44// Pending ID Encoding
45// ============================================================================
46
47/// Marker byte for pending IDs (first byte = 0x01).
48const PENDING_ID_MARKER: u8 = 0x01;
49
50/// Trailing sentinel for encoded pending ids (bytes 17..32). The marker byte
51/// alone is NOT safe: real event ids are uniform hashes, so 1 in 256 begins
52/// with 0x01 and would decode as a phantom "pending-…" string — mangling read
53/// markers, frontend-facing ids, every decode consumer. Requiring marker AND
54/// sentinel makes that misread a ~2^-120 event.
55const PENDING_ID_SENTINEL: [u8; 15] = [0xFE; 15];
56
57/// Encode an ID string to 32 bytes, handling pending IDs specially.
58/// - Pending IDs ("pending-{nanoseconds}") are encoded as marker byte +
59///   timestamp + sentinel tail
60/// - Regular hex IDs are decoded normally
61#[inline]
62pub fn encode_message_id(id: &str) -> [u8; 32] {
63    if let Some(timestamp_str) = id.strip_prefix("pending-") {
64        // Encode pending ID: marker byte + timestamp as u128 (16 bytes)
65        let mut bytes = [0u8; 32];
66        bytes[0] = PENDING_ID_MARKER;
67        if let Ok(timestamp) = timestamp_str.parse::<u128>() {
68            bytes[1..17].copy_from_slice(&timestamp.to_le_bytes());
69        }
70        bytes[17..32].copy_from_slice(&PENDING_ID_SENTINEL);
71        bytes
72    } else {
73        hex_to_bytes_32(id)
74    }
75}
76
77/// Decode 32 bytes back to an ID string, handling pending IDs specially.
78#[inline]
79pub fn decode_message_id(bytes: &[u8; 32]) -> String {
80    if bytes[0] == PENDING_ID_MARKER && bytes[17..32] == PENDING_ID_SENTINEL {
81        // Decode pending ID: extract timestamp from bytes 1-16
82        let mut timestamp_bytes = [0u8; 16];
83        timestamp_bytes.copy_from_slice(&bytes[1..17]);
84        let timestamp = u128::from_le_bytes(timestamp_bytes);
85        format!("pending-{}", timestamp)
86    } else {
87        bytes_to_hex_32(bytes)
88    }
89}
90
91// ============================================================================
92// Compact Timestamp
93// ============================================================================
94
95/// Convert milliseconds timestamp to compact storage.
96/// Stores full u64 milliseconds — no precision loss.
97#[inline]
98pub fn timestamp_to_compact(ms: u64) -> u64 {
99    ms
100}
101
102/// Convert compact timestamp back to milliseconds.
103#[inline]
104pub fn timestamp_from_compact(compact: u64) -> u64 {
105    compact
106}
107
108/// Distinct-emoji ceiling on a single message's reaction set. Joining an
109/// existing group is never bounded by this; opening a group past it is
110/// refused at the STATE chokepoint (inbound and outbound alike). The UI's
111/// reaction row mirrors this number.
112pub const MAX_REACTION_GROUPS: usize = 12;
113
114/// Custom epoch in seconds: 2020-01-01 00:00:00 UTC
115const EPOCH_2020_SECS: u64 = 1577836800;
116
117/// Convert Unix seconds timestamp to compact u32 (seconds since 2020).
118/// Preserves 0 as sentinel for "never set".
119#[inline]
120pub fn secs_to_compact(secs: u64) -> u32 {
121    if secs == 0 { return 0; }
122    secs.saturating_sub(EPOCH_2020_SECS) as u32
123}
124
125/// Convert compact u32 back to Unix seconds timestamp.
126/// Preserves 0 as sentinel for "never set".
127#[inline]
128pub fn secs_from_compact(compact: u32) -> u64 {
129    if compact == 0 { return 0; }
130    EPOCH_2020_SECS + compact as u64
131}
132
133// ============================================================================
134// Message Flags
135// ============================================================================
136
137/// Bitflags for message state (1 byte instead of 4+ bytes for separate bools)
138///
139/// Layout (bits): 0=mine, 1=pending, 2=failed, 3-4=replied_to_has_attachment
140/// replied_to_has_attachment: 00=None, 01=Some(false), 10=Some(true)
141///
142/// Note: No EDITED flag - check `edit_history.is_some()` instead
143#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
144pub struct MessageFlags(u8);
145
146impl MessageFlags {
147    pub const NONE: Self = Self(0);
148    pub const MINE: Self = Self(0b00001);
149    pub const PENDING: Self = Self(0b00010);
150    pub const FAILED: Self = Self(0b00100);
151    /// A restricted Channel's writer address carried it.
152    pub const WRITER: Self = Self(0b100000);
153    /// Its writers' rules don't stand behind it.
154    pub const UNAUTHORIZED: Self = Self(0b1000000);
155    // Bits 3-4 for replied_to_has_attachment:
156    // 00 = None, 01 = Some(false), 10 = Some(true)
157    const REPLY_ATTACH_MASK: u8 = 0b11000;
158    const REPLY_ATTACH_SHIFT: u8 = 3;
159
160    #[inline]
161    pub fn is_mine(self) -> bool {
162        self.0 & Self::MINE.0 != 0
163    }
164
165    #[inline]
166    pub fn is_pending(self) -> bool {
167        self.0 & Self::PENDING.0 != 0
168    }
169
170    #[inline]
171    pub fn is_failed(self) -> bool {
172        self.0 & Self::FAILED.0 != 0
173    }
174
175    #[inline]
176    pub fn is_writer(self) -> bool {
177        self.0 & Self::WRITER.0 != 0
178    }
179
180    #[inline]
181    pub fn set_writer(&mut self, value: bool) {
182        if value {
183            self.0 |= Self::WRITER.0;
184        } else {
185            self.0 &= !Self::WRITER.0;
186        }
187    }
188
189    #[inline]
190    pub fn is_unauthorized(self) -> bool {
191        self.0 & Self::UNAUTHORIZED.0 != 0
192    }
193
194    #[inline]
195    pub fn set_unauthorized(&mut self, value: bool) {
196        if value {
197            self.0 |= Self::UNAUTHORIZED.0;
198        } else {
199            self.0 &= !Self::UNAUTHORIZED.0;
200        }
201    }
202
203    /// Get replied_to_has_attachment as `Option<bool>`
204    /// Returns None (unknown), Some(false), or Some(true)
205    #[inline]
206    pub fn replied_to_has_attachment(self) -> Option<bool> {
207        match (self.0 & Self::REPLY_ATTACH_MASK) >> Self::REPLY_ATTACH_SHIFT {
208            0b00 => None,           // Unknown
209            0b01 => Some(false),    // No attachment
210            0b10 => Some(true),     // Has attachment
211            _ => None,              // Invalid, treat as unknown
212        }
213    }
214
215    #[inline]
216    pub fn set_mine(&mut self, value: bool) {
217        if value {
218            self.0 |= Self::MINE.0;
219        } else {
220            self.0 &= !Self::MINE.0;
221        }
222    }
223
224    #[inline]
225    pub fn set_pending(&mut self, value: bool) {
226        if value {
227            self.0 |= Self::PENDING.0;
228        } else {
229            self.0 &= !Self::PENDING.0;
230        }
231    }
232
233    #[inline]
234    pub fn set_failed(&mut self, value: bool) {
235        if value {
236            self.0 |= Self::FAILED.0;
237        } else {
238            self.0 &= !Self::FAILED.0;
239        }
240    }
241
242    /// Set replied_to_has_attachment from `Option<bool>`
243    #[inline]
244    pub fn set_replied_to_has_attachment(&mut self, value: Option<bool>) {
245        // Clear existing bits
246        self.0 &= !Self::REPLY_ATTACH_MASK;
247        // Set new value
248        let bits = match value {
249            None => 0b00,
250            Some(false) => 0b01,
251            Some(true) => 0b10,
252        };
253        self.0 |= bits << Self::REPLY_ATTACH_SHIFT;
254    }
255
256    /// Create flags from individual booleans
257    #[inline]
258    pub fn from_bools(mine: bool, pending: bool, failed: bool) -> Self {
259        let mut flags = Self::NONE;
260        flags.set_mine(mine);
261        flags.set_pending(pending);
262        flags.set_failed(failed);
263        flags
264    }
265
266    /// Create flags from all values including replied_to_has_attachment
267    #[inline]
268    pub fn from_all(mine: bool, pending: bool, failed: bool, replied_to_has_attachment: Option<bool>) -> Self {
269        let mut flags = Self::from_bools(mine, pending, failed);
270        flags.set_replied_to_has_attachment(replied_to_has_attachment);
271        flags
272    }
273}
274
275// ============================================================================
276// TinyVec - 8-byte thin pointer for small collections
277// ============================================================================
278
279use std::alloc::{alloc, dealloc, realloc, Layout};
280use std::marker::PhantomData;
281use std::ptr::NonNull;
282
283/// Ultra-compact vector using a thin pointer (8 bytes on stack).
284///
285/// Memory layout:
286/// - Stack: single pointer (8 bytes) - null for empty
287/// - Heap: `[len: u32][items: T...]` - exact-sized, only allocated when non-empty
288///
289/// Compared to standard types:
290/// - `Vec<T>`: 24 bytes (ptr + len + cap), plus growth slack
291/// - `Box<[T]>`: 16 bytes (fat pointer)
292/// - `TinyVec<T>`: 8 bytes (thin pointer)
293///
294/// No spare capacity: a push reallocates in place where the allocator can, which suits
295/// collections that are mostly empty or tiny and grow one item at a time.
296pub struct TinyVec<T> {
297    /// Null = empty, otherwise points to: [len: u32][items: T...]
298    ptr: Option<NonNull<u8>>,
299    _marker: PhantomData<T>,
300}
301
302impl<T> TinyVec<T> {
303    /// Create an empty TinyVec (no allocation)
304    #[inline]
305    pub const fn new() -> Self {
306        Self {
307            ptr: None,
308            _marker: PhantomData,
309        }
310    }
311
312    /// Create from a Vec, consuming it
313    pub fn from_vec(vec: Vec<T>) -> Self {
314        let mut out = Self::new();
315        if vec.is_empty() {
316            return out;
317        }
318        let len = vec.len();
319        let (layout, items_offset) = Self::layout_for(len);
320        unsafe {
321            let ptr = alloc(layout);
322            if ptr.is_null() {
323                std::alloc::handle_alloc_error(layout);
324            }
325            *(ptr as *mut u32) = len as u32;
326            let items_ptr = ptr.add(items_offset) as *mut T;
327            for (i, item) in vec.into_iter().enumerate() {
328                std::ptr::write(items_ptr.add(i), item);
329            }
330            out.ptr = NonNull::new(ptr);
331        }
332        out
333    }
334
335    /// Calculate layout for allocation
336    fn layout_for(len: usize) -> (Layout, usize) {
337        let header_layout = Layout::new::<u32>();
338        let items_layout = Layout::array::<T>(len).unwrap();
339        header_layout.extend(items_layout).unwrap()
340    }
341
342    /// Number of items
343    #[inline]
344    pub fn len(&self) -> usize {
345        match self.ptr {
346            None => 0,
347            Some(ptr) => unsafe { *(ptr.as_ptr() as *const u32) as usize },
348        }
349    }
350
351    #[inline]
352    pub fn is_empty(&self) -> bool {
353        self.ptr.is_none()
354    }
355
356    /// Get items offset within allocation
357    #[inline]
358    fn items_offset() -> usize {
359        Self::layout_for(1).1
360    }
361
362    #[inline]
363    fn items_ptr(&self) -> *mut T {
364        match self.ptr {
365            None => NonNull::dangling().as_ptr(),
366            Some(ptr) => unsafe { ptr.as_ptr().add(Self::items_offset()) as *mut T },
367        }
368    }
369
370    /// Get a slice of the items
371    #[inline]
372    pub fn as_slice(&self) -> &[T] {
373        unsafe { std::slice::from_raw_parts(self.items_ptr(), self.len()) }
374    }
375
376    /// Get a mutable slice of the items
377    #[inline]
378    pub fn as_mut_slice(&mut self) -> &mut [T] {
379        unsafe { std::slice::from_raw_parts_mut(self.items_ptr(), self.len()) }
380    }
381
382    /// Iterate over items
383    #[inline]
384    pub fn iter(&self) -> std::slice::Iter<'_, T> {
385        self.as_slice().iter()
386    }
387
388    /// Iterate mutably
389    #[inline]
390    pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, T> {
391        self.as_mut_slice().iter_mut()
392    }
393
394    /// Convert to Vec (clones items)
395    pub fn to_vec(&self) -> Vec<T>
396    where
397        T: Clone,
398    {
399        self.as_slice().to_vec()
400    }
401
402    /// Get the first item (immutable)
403    #[inline]
404    pub fn first(&self) -> Option<&T> {
405        self.as_slice().first()
406    }
407
408    /// Get the last item (immutable)
409    #[inline]
410    pub fn last(&self) -> Option<&T> {
411        self.as_slice().last()
412    }
413
414    /// Get the last item (mutable)
415    #[inline]
416    pub fn last_mut(&mut self) -> Option<&mut T> {
417        self.as_mut_slice().last_mut()
418    }
419
420    /// Get item by index (immutable)
421    #[inline]
422    pub fn get(&self, index: usize) -> Option<&T> {
423        self.as_slice().get(index)
424    }
425
426    /// Get item by index (mutable)
427    #[inline]
428    pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
429        self.as_mut_slice().get_mut(index)
430    }
431
432    /// Append an item, growing the allocation by exactly one slot (moved, never cloned).
433    pub fn push(&mut self, item: T) {
434        let len = self.len();
435        assert!(len < u32::MAX as usize, "TinyVec length overflow");
436        let (new_layout, items_offset) = Self::layout_for(len + 1);
437        unsafe {
438            let ptr = match self.ptr {
439                None => alloc(new_layout),
440                Some(old) => realloc(old.as_ptr(), Self::layout_for(len).0, new_layout.size()),
441            };
442            if ptr.is_null() {
443                std::alloc::handle_alloc_error(new_layout);
444            }
445            std::ptr::write((ptr.add(items_offset) as *mut T).add(len), item);
446            *(ptr as *mut u32) = (len + 1) as u32;
447            self.ptr = NonNull::new(ptr);
448        }
449    }
450
451    /// Keep the items matching a predicate, compacting in place and shrinking to fit.
452    pub fn retain<F>(&mut self, mut f: F)
453    where
454        F: FnMut(&T) -> bool,
455    {
456        let len = self.len();
457        if len == 0 {
458            return;
459        }
460        let items = self.items_ptr();
461        // Detached while items move: a panicking predicate leaks the block, never double-drops.
462        let base = self.ptr.take().unwrap().as_ptr();
463        let mut kept = 0;
464        unsafe {
465            for i in 0..len {
466                if f(&*items.add(i)) {
467                    if i != kept {
468                        std::ptr::copy_nonoverlapping(items.add(i), items.add(kept), 1);
469                    }
470                    kept += 1;
471                } else {
472                    std::ptr::drop_in_place(items.add(i));
473                }
474            }
475            if kept == 0 {
476                dealloc(base, Self::layout_for(len).0);
477                return;
478            }
479            let ptr = if kept == len {
480                base
481            } else {
482                realloc(base, Self::layout_for(len).0, Self::layout_for(kept).0.size())
483            };
484            if ptr.is_null() {
485                std::alloc::handle_alloc_error(Self::layout_for(kept).0);
486            }
487            *(ptr as *mut u32) = kept as u32;
488            self.ptr = NonNull::new(ptr);
489        }
490    }
491
492    /// Bytes this holds on the heap (header and items; nothing the items own).
493    pub fn heap_bytes(&self) -> usize {
494        if self.is_empty() { 0 } else { Self::layout_for(self.len()).0.size() }
495    }
496
497    /// Check if any item matches a predicate
498    pub fn any<F>(&self, f: F) -> bool
499    where
500        F: FnMut(&T) -> bool,
501    {
502        self.as_slice().iter().any(f)
503    }
504}
505
506impl<T> FromIterator<T> for TinyVec<T> {
507    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
508        Self::from_vec(iter.into_iter().collect())
509    }
510}
511
512// Index trait for direct indexing (msg.attachments[0])
513impl<T> std::ops::Index<usize> for TinyVec<T> {
514    type Output = T;
515
516    fn index(&self, index: usize) -> &Self::Output {
517        &self.as_slice()[index]
518    }
519}
520
521impl<T> std::ops::IndexMut<usize> for TinyVec<T> {
522    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
523        &mut self.as_mut_slice()[index]
524    }
525}
526
527// IntoIterator for &TinyVec
528impl<'a, T> IntoIterator for &'a TinyVec<T> {
529    type Item = &'a T;
530    type IntoIter = std::slice::Iter<'a, T>;
531
532    fn into_iter(self) -> Self::IntoIter {
533        self.as_slice().iter()
534    }
535}
536
537// IntoIterator for &mut TinyVec
538impl<'a, T> IntoIterator for &'a mut TinyVec<T> {
539    type Item = &'a mut T;
540    type IntoIter = std::slice::IterMut<'a, T>;
541
542    fn into_iter(self) -> Self::IntoIter {
543        self.as_mut_slice().iter_mut()
544    }
545}
546
547impl<T> Default for TinyVec<T> {
548    fn default() -> Self {
549        Self::new()
550    }
551}
552
553impl<T: Clone> Clone for TinyVec<T> {
554    fn clone(&self) -> Self {
555        Self::from_vec(self.to_vec())
556    }
557}
558
559impl<T: std::fmt::Debug> std::fmt::Debug for TinyVec<T> {
560    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
561        f.debug_list().entries(self.as_slice()).finish()
562    }
563}
564
565impl<T> Drop for TinyVec<T> {
566    fn drop(&mut self) {
567        if let Some(ptr) = self.ptr {
568            unsafe {
569                let len = self.len();
570                std::ptr::drop_in_place(std::ptr::slice_from_raw_parts_mut(self.items_ptr(), len));
571                dealloc(ptr.as_ptr(), Self::layout_for(len).0);
572            }
573        }
574    }
575}
576
577// Safety: TinyVec is Send/Sync if T is
578unsafe impl<T: Send> Send for TinyVec<T> {}
579unsafe impl<T: Sync> Sync for TinyVec<T> {}
580
581// ============================================================================
582// Compact Reaction
583// ============================================================================
584
585/// Memory-efficient reaction: binary id, interned author, interned (emoji, url) pair.
586/// 40 bytes and `Copy`, so adding or removing one never allocates per reaction.
587#[derive(Clone, Copy, Debug, PartialEq, Eq)]
588pub struct CompactReaction {
589    /// Reaction event ID as binary
590    pub id: [u8; 32],
591    /// The (emoji, NIP-30 url) pair, interned via [`NpubInterner::intern_emoji`]
592    pub emoji_idx: u32,
593    /// Author npub index (interned via NpubInterner)
594    pub author_idx: u16,
595}
596
597impl CompactReaction {
598    /// Get reaction ID as hex string
599    #[inline]
600    pub fn id_hex(&self) -> String {
601        bytes_to_hex_32(&self.id)
602    }
603
604    /// The emoji, resolved through the interner it was interned with.
605    #[inline]
606    pub fn emoji<'a>(&self, interner: &'a NpubInterner) -> &'a str {
607        interner.emoji(self.emoji_idx).0
608    }
609
610    /// Convert from regular Reaction, interning author and emoji
611    pub fn from_reaction(reaction: &Reaction, interner: &mut NpubInterner) -> Self {
612        Self {
613            id: hex_to_bytes_32(&reaction.id),
614            emoji_idx: interner.intern_emoji(&reaction.emoji, reaction.emoji_url.as_deref()),
615            author_idx: interner.intern(&reaction.author_id),
616        }
617    }
618
619    /// Convert from regular Reaction (owned), interning author and emoji
620    pub fn from_reaction_owned(reaction: Reaction, interner: &mut NpubInterner) -> Self {
621        Self::from_reaction(&reaction, interner)
622    }
623
624    /// Convert back to regular Reaction, resolving author from interner.
625    /// `parent_hex` is the reacted-to message's id: a CompactReaction is always nested
626    /// inside that message, so its id IS the reference.
627    pub fn to_reaction(&self, parent_hex: &str, interner: &NpubInterner) -> Reaction {
628        let (emoji, emoji_url) = interner.emoji(self.emoji_idx);
629        Reaction {
630            id: self.id_hex(),
631            reference_id: parent_hex.to_string(),
632            author_id: interner.resolve(self.author_idx)
633                .map(|s| s.to_string())
634                .unwrap_or_default(),
635            emoji: emoji.to_string(),
636            emoji_url: emoji_url.map(|s| s.to_string()),
637        }
638    }
639}
640
641// ============================================================================
642// Compact Attachment
643// ============================================================================
644
645/// Packed attachment state: the three bools, where the local path comes from, and
646/// whether the original hash is the id.
647#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
648pub struct AttachmentFlags(u8);
649
650impl AttachmentFlags {
651    pub const NONE: Self = Self(0);
652    const DOWNLOADING: u8 = 0b0001;
653    const DOWNLOADED: u8  = 0b0010;
654    const SHORT_NONCE: u8 = 0b0100; // 12-byte nonce (legacy) vs 16-byte (DM)
655    const PATH_MASK: u8 = 0b1_1000;
656    /// `{download dir}{id}.{ext}`
657    const PATH_HASHED: u8 = 0b0_1000;
658    /// `{download dir}{name}`
659    const PATH_NAMED: u8 = 0b1_0000;
660    /// Held verbatim in the cold box
661    const PATH_CUSTOM: u8 = 0b1_1000;
662    const ORIGINAL_IS_ID: u8 = 0b10_0000;
663    const VERIFIED: u8 = 0b100_0000;
664
665    #[inline]
666    pub fn is_downloading(self) -> bool { self.0 & Self::DOWNLOADING != 0 }
667    #[inline]
668    pub fn is_downloaded(self) -> bool { self.0 & Self::DOWNLOADED != 0 }
669    #[inline]
670    pub fn is_short_nonce(self) -> bool { self.0 & Self::SHORT_NONCE != 0 }
671    #[inline]
672    pub fn is_verified(self) -> bool { self.0 & Self::VERIFIED != 0 }
673
674    #[inline]
675    pub fn set_downloading(&mut self, value: bool) {
676        if value { self.0 |= Self::DOWNLOADING; } else { self.0 &= !Self::DOWNLOADING; }
677    }
678    #[inline]
679    pub fn set_downloaded(&mut self, value: bool) {
680        if value { self.0 |= Self::DOWNLOADED; } else { self.0 &= !Self::DOWNLOADED; }
681    }
682    #[inline]
683    pub fn set_short_nonce(&mut self, value: bool) {
684        if value { self.0 |= Self::SHORT_NONCE; } else { self.0 &= !Self::SHORT_NONCE; }
685    }
686    #[inline]
687    pub fn set_verified(&mut self, value: bool) {
688        if value { self.0 |= Self::VERIFIED; } else { self.0 &= !Self::VERIFIED; }
689    }
690
691    #[inline]
692    fn path_kind(self) -> u8 { self.0 & Self::PATH_MASK }
693
694    #[inline]
695    fn set_path_kind(&mut self, kind: u8) { self.0 = (self.0 & !Self::PATH_MASK) | kind; }
696
697    pub fn from_bools(downloading: bool, downloaded: bool) -> Self {
698        let mut flags = Self::NONE;
699        flags.set_downloading(downloading);
700        flags.set_downloaded(downloaded);
701        flags
702    }
703}
704
705/// Extensions held as their index here; anything else rides the cold box as [`EXT_COLD`].
706const EXTENSIONS: [&str; 93] = [
707    "", "jpg", "jpeg", "png", "gif", "webp", "avif", "heic", "heif", "bmp", "tiff", "tif", "ico", "svg", "jfif",
708    "mp4", "mov", "webm", "mkv", "avi", "m4v", "3gp", "mpg", "mpeg", "ogv", "flv", "wmv",
709    "mp3", "m4a", "ogg", "oga", "opus", "wav", "flac", "aac", "wma", "weba", "caf", "amr",
710    "pdf", "txt", "md", "csv", "json", "xml", "yaml", "yml", "toml", "rtf", "log", "html", "htm", "css",
711    "doc", "docx", "xls", "xlsx", "ppt", "pptx", "odt", "ods", "odp", "epub",
712    "zip", "7z", "rar", "tar", "gz", "tgz", "bz2", "xz", "iso", "dmg", "apk", "jar", "exe", "deb",
713    "xdc", "js", "ts", "py", "rs", "sql", "sh",
714    "glb", "gltf", "obj", "stl", "dae", "arw", "cr2", "dng", "nef",
715];
716const EXT_COLD: u8 = u8::MAX;
717
718fn extension_code(ext: &str) -> u8 {
719    EXTENSIONS.iter().position(|&e| e == ext).map_or(EXT_COLD, |i| i as u8)
720}
721
722/// The download directory as a path prefix, captured once so a derived path rebuilds
723/// to the same string for the life of the process, whatever the directory does later.
724fn download_prefix() -> &'static str {
725    static PREFIX: std::sync::OnceLock<Box<str>> = std::sync::OnceLock::new();
726    PREFIX.get_or_init(|| {
727        let probe = crate::db::get_download_dir().join("x");
728        let probe = probe.to_string_lossy();
729        probe[..probe.len() - 1].into()
730    })
731}
732
733const HEX: &[u8; 16] = b"0123456789abcdef";
734
735/// `s` is exactly the lowercase hex of `id`, as [`bytes_to_hex_32`] writes it.
736fn is_hex_of(s: &[u8], id: &[u8; 32]) -> bool {
737    s.len() == 64
738        && id.iter().enumerate().all(|(i, b)| s[2 * i] == HEX[(b >> 4) as usize] && s[2 * i + 1] == HEX[(b & 0xf) as usize])
739}
740
741/// Which derivation reproduces `path` byte for byte, if any.
742fn classify_path(path: &str, id: &[u8; 32], ext: &str, name: &str) -> u8 {
743    if path.is_empty() {
744        return 0;
745    }
746    let Some(file) = path.strip_prefix(download_prefix()).map(str::as_bytes) else {
747        return AttachmentFlags::PATH_CUSTOM;
748    };
749    if !name.is_empty() && file == name.as_bytes() {
750        return AttachmentFlags::PATH_NAMED;
751    }
752    if file.len() == 65 + ext.len() && file[64] == b'.' && file[65..] == *ext.as_bytes() && is_hex_of(&file[..64], id) {
753        return AttachmentFlags::PATH_HASHED;
754    }
755    AttachmentFlags::PATH_CUSTOM
756}
757
758/// The fields few attachments carry, boxed together so the rest pay 8 bytes.
759#[derive(Clone, Debug, Default)]
760struct AttachmentCold {
761    /// Set when the extension has no code
762    extension: Box<str>,
763    /// Set when the path has no derivation
764    path: Box<str>,
765    /// Mirror URLs for the same ciphertext
766    fallback_urls: Box<[Box<str>]>,
767    /// WebXDC topic (Mini Apps only)
768    webxdc_topic: Option<Box<str>>,
769    /// Original file hash, when it differs from the id
770    original_hash: Option<Box<[u8; 32]>>,
771    /// Legacy group ID for key derivation
772    group_id: Option<Box<[u8; 32]>>,
773}
774
775impl AttachmentCold {
776    fn is_empty(&self) -> bool {
777        self.extension.is_empty()
778            && self.path.is_empty()
779            && self.fallback_urls.is_empty()
780            && self.webxdc_topic.is_none()
781            && self.original_hash.is_none()
782            && self.group_id.is_none()
783    }
784}
785
786/// Memory-efficient attachment: binary hashes, the extension as a code, the local path
787/// derived from the id or name when it can be, image metadata in one allocation, and
788/// the rarely-set fields behind one box.
789#[derive(Clone, Debug)]
790pub struct CompactAttachment {
791    /// SHA256 file hash as binary. A derived path follows it.
792    id: [u8; 32],
793    /// Encryption key - 32 bytes (empty = legacy derived)
794    pub key: [u8; 32],
795    /// Encryption nonce - 16 bytes (AES-256-GCM with 0xChat compatibility)
796    pub nonce: [u8; 16],
797    /// File size in bytes
798    pub size: u64,
799    /// Host URL (blossom server, etc.)
800    pub url: Box<str>,
801    /// Original filename (e.g. "memories.zip"). Empty = fallback to {hash}.{ext}. A
802    /// derived path follows it.
803    name: Box<str>,
804    /// `[width u32 LE][height u32 LE][thumbhash]`; empty when there is none
805    img_meta: TinyVec<u8>,
806    cold: Option<Box<AttachmentCold>>,
807    /// Packed boolean flags, path kind and original-hash bit
808    flags: AttachmentFlags,
809    /// Index into [`EXTENSIONS`], or [`EXT_COLD`]
810    ext: u8,
811}
812
813impl CompactAttachment {
814    // === Convenience accessors for flags ===
815    #[inline]
816    pub fn downloaded(&self) -> bool { self.flags.is_downloaded() }
817    #[inline]
818    pub fn downloading(&self) -> bool { self.flags.is_downloading() }
819    #[inline]
820    pub fn set_downloaded(&mut self, value: bool) { self.flags.set_downloaded(value); }
821    #[inline]
822    pub fn set_downloading(&mut self, value: bool) { self.flags.set_downloading(value); }
823    #[inline]
824    pub fn verified(&self) -> bool { self.flags.is_verified() }
825    #[inline]
826    pub fn set_verified(&mut self, value: bool) { self.flags.set_verified(value); }
827
828    /// Check if this attachment's ID matches a hex string
829    #[inline]
830    pub fn id_eq(&self, hex_id: &str) -> bool {
831        self.id == hex_to_bytes_32(hex_id)
832    }
833
834    /// Get file ID as hex string
835    #[inline]
836    pub fn id_hex(&self) -> String {
837        bytes_to_hex_32(&self.id)
838    }
839
840    /// Get encryption key as hex string (empty if zeros)
841    pub fn key_hex(&self) -> String {
842        if self.key == [0u8; 32] {
843            String::new()
844        } else {
845            bytes_to_hex_32(&self.key)
846        }
847    }
848
849    /// Get nonce as hex string (empty if zeros, respects original length)
850    pub fn nonce_hex(&self) -> String {
851        if self.nonce == [0u8; 16] {
852            String::new()
853        } else if self.flags.is_short_nonce() {
854            // 12-byte nonce (legacy/MIP-04)
855            bytes_to_hex_string(&self.nonce[..12])
856        } else {
857            // 16-byte nonce (DM/0xChat)
858            bytes_to_hex_string(&self.nonce)
859        }
860    }
861
862    #[inline]
863    fn cold(&self) -> Option<&AttachmentCold> {
864        self.cold.as_deref()
865    }
866
867    fn cold_mut(&mut self) -> &mut AttachmentCold {
868        self.cold.get_or_insert_with(Default::default)
869    }
870
871    fn drop_empty_cold(&mut self) {
872        if self.cold.as_ref().is_some_and(|c| c.is_empty()) {
873            self.cold = None;
874        }
875    }
876
877    /// File extension (e.g., "png", "mp4")
878    #[inline]
879    pub fn extension(&self) -> &str {
880        match EXTENSIONS.get(self.ext as usize) {
881            Some(ext) => ext,
882            None => self.cold().map_or("", |c| &c.extension),
883        }
884    }
885
886    /// Whether a local path is set, without building it.
887    #[inline]
888    pub fn has_path(&self) -> bool {
889        self.flags.path_kind() != 0
890    }
891
892    /// Local file path (empty if not downloaded). Allocates only for a derived path.
893    pub fn path(&self) -> std::borrow::Cow<'_, str> {
894        use std::borrow::Cow;
895        match self.flags.path_kind() {
896            AttachmentFlags::PATH_HASHED => {
897                let (prefix, ext) = (download_prefix(), self.extension());
898                let mut path = String::with_capacity(prefix.len() + 65 + ext.len());
899                path.push_str(prefix);
900                for b in self.id {
901                    path.push(HEX[(b >> 4) as usize] as char);
902                    path.push(HEX[(b & 0xf) as usize] as char);
903                }
904                path.push('.');
905                path.push_str(ext);
906                Cow::Owned(path)
907            }
908            AttachmentFlags::PATH_NAMED => Cow::Owned([download_prefix(), &self.name].concat()),
909            AttachmentFlags::PATH_CUSTOM => Cow::Borrowed(self.cold().map_or("", |c| &c.path)),
910            _ => Cow::Borrowed(""),
911        }
912    }
913
914    #[inline]
915    pub fn id(&self) -> &[u8; 32] {
916        &self.id
917    }
918
919    #[inline]
920    pub fn name(&self) -> &str {
921        &self.name
922    }
923
924    #[inline]
925    pub fn flags(&self) -> AttachmentFlags {
926        self.flags
927    }
928
929    /// The path and original hash stay what they were: both may be derived from the id.
930    pub fn set_id(&mut self, id: [u8; 32]) {
931        if id == self.id {
932            return;
933        }
934        let path = self.path().into_owned();
935        if self.flags.0 & AttachmentFlags::ORIGINAL_IS_ID != 0 {
936            self.flags.0 &= !AttachmentFlags::ORIGINAL_IS_ID;
937            let old = self.id;
938            self.cold_mut().original_hash = Some(Box::new(old));
939        }
940        self.id = id;
941        self.set_path(path);
942    }
943
944    /// The path stays what it was: it may be derived from the name.
945    pub fn set_name(&mut self, name: &str) {
946        if *name == *self.name {
947            return;
948        }
949        let path = self.path().into_owned();
950        self.name = name.into();
951        self.set_path(path);
952    }
953
954    pub fn set_path(&mut self, path: String) {
955        let kind = classify_path(&path, &self.id, self.extension(), &self.name);
956        self.flags.set_path_kind(kind);
957        if kind == AttachmentFlags::PATH_CUSTOM {
958            self.cold_mut().path = path.into_boxed_str();
959        } else if let Some(cold) = self.cold.as_mut() {
960            cold.path = Box::default();
961            self.drop_empty_cold();
962        }
963    }
964
965    /// Image dimensions and thumbhash (only for images/videos)
966    pub fn img_meta(&self) -> Option<ImageMetadata> {
967        let b = self.img_meta.as_slice();
968        (b.len() >= 8).then(|| ImageMetadata {
969            width: u32::from_le_bytes([b[0], b[1], b[2], b[3]]),
970            height: u32::from_le_bytes([b[4], b[5], b[6], b[7]]),
971            thumbhash: std::str::from_utf8(&b[8..]).unwrap_or_default().to_string(),
972        })
973    }
974
975    #[inline]
976    pub fn has_img_meta(&self) -> bool {
977        !self.img_meta.is_empty()
978    }
979
980    pub fn set_img_meta(&mut self, meta: Option<&ImageMetadata>) {
981        self.img_meta = pack_img_meta(meta);
982    }
983
984    /// Original file hash before encryption
985    pub fn original_hash(&self) -> Option<[u8; 32]> {
986        if self.flags.0 & AttachmentFlags::ORIGINAL_IS_ID != 0 {
987            return Some(self.id);
988        }
989        self.cold().and_then(|c| c.original_hash.as_deref().copied())
990    }
991
992    /// Legacy group ID for key derivation
993    pub fn group_id(&self) -> Option<[u8; 32]> {
994        self.cold().and_then(|c| c.group_id.as_deref().copied())
995    }
996
997    /// WebXDC topic (Mini Apps only)
998    #[inline]
999    pub fn webxdc_topic(&self) -> Option<&str> {
1000        self.cold().and_then(|c| c.webxdc_topic.as_deref())
1001    }
1002
1003    /// Mirror URLs for the same ciphertext
1004    #[inline]
1005    pub fn fallback_urls(&self) -> &[Box<str>] {
1006        self.cold().map_or(&[], |c| &c.fallback_urls)
1007    }
1008
1009    pub fn set_fallback_urls(&mut self, urls: impl IntoIterator<Item = Box<str>>) {
1010        let urls: Box<[Box<str>]> = urls.into_iter().collect();
1011        if !urls.is_empty() {
1012            self.cold_mut().fallback_urls = urls;
1013        } else if let Some(cold) = self.cold.as_mut() {
1014            cold.fallback_urls = Box::default();
1015            self.drop_empty_cold();
1016        }
1017    }
1018
1019    /// Convert from regular Attachment (borrowed)
1020    pub fn from_attachment(att: &Attachment) -> Self {
1021        Self::compact(
1022            att,
1023            att.url.as_str().into(),
1024            att.name.as_str().into(),
1025            att.fallback_urls.iter().map(|s| s.as_str().into()).collect(),
1026            att.webxdc_topic.as_deref().map(Into::into),
1027        )
1028    }
1029
1030    /// Convert from regular Attachment (owned) - zero-copy where possible
1031    pub fn from_attachment_owned(mut att: Attachment) -> Self {
1032        let url = std::mem::take(&mut att.url).into_boxed_str();
1033        let name = std::mem::take(&mut att.name).into_boxed_str();
1034        let fallback_urls = std::mem::take(&mut att.fallback_urls).into_iter().map(String::into_boxed_str).collect();
1035        let webxdc_topic = att.webxdc_topic.take().map(String::into_boxed_str);
1036        Self::compact(&att, url, name, fallback_urls, webxdc_topic)
1037    }
1038
1039    fn compact(
1040        att: &Attachment,
1041        url: Box<str>,
1042        name: Box<str>,
1043        fallback_urls: Box<[Box<str>]>,
1044        webxdc_topic: Option<Box<str>>,
1045    ) -> Self {
1046        let id = hex_to_bytes_32(&att.id);
1047        let ext = extension_code(&att.extension);
1048        let mut flags = AttachmentFlags::from_bools(att.downloading, att.downloaded);
1049        flags.set_verified(att.verified);
1050        // Detect short nonce (12 bytes = 24 hex chars) for legacy attachments
1051        flags.set_short_nonce(att.nonce.len() == 24);
1052        let path_kind = classify_path(&att.path, &id, &att.extension, &name);
1053        flags.set_path_kind(path_kind);
1054
1055        let original = att.original_hash.as_deref().map(hex_to_bytes_32);
1056        if original == Some(id) {
1057            flags.0 |= AttachmentFlags::ORIGINAL_IS_ID;
1058        }
1059        let cold = AttachmentCold {
1060            extension: if ext == EXT_COLD { att.extension.as_str().into() } else { Box::default() },
1061            path: if path_kind == AttachmentFlags::PATH_CUSTOM { att.path.as_str().into() } else { Box::default() },
1062            fallback_urls,
1063            webxdc_topic,
1064            original_hash: original.filter(|h| *h != id).map(Box::new),
1065            group_id: att.group_id.as_deref().map(|s| Box::new(hex_to_bytes_32(s))),
1066        };
1067
1068        Self {
1069            id,
1070            key: if att.key.is_empty() { [0u8; 32] } else { hex_to_bytes_32(&att.key) },
1071            nonce: if att.nonce.is_empty() { [0u8; 16] } else { parse_nonce(&att.nonce) },
1072            size: att.size,
1073            url,
1074            name,
1075            img_meta: pack_img_meta(att.img_meta.as_ref()),
1076            cold: (!cold.is_empty()).then(|| Box::new(cold)),
1077            flags,
1078            ext,
1079        }
1080    }
1081
1082    /// Convert back to regular Attachment
1083    pub fn to_attachment(&self) -> Attachment {
1084        Attachment {
1085            id: self.id_hex(),
1086            key: self.key_hex(),
1087            nonce: self.nonce_hex(),
1088            extension: self.extension().to_string(),
1089            name: self.name.to_string(),
1090            url: self.url.to_string(),
1091            path: self.path().into_owned(),
1092            size: self.size,
1093            img_meta: self.img_meta(),
1094            downloading: self.flags.is_downloading(),
1095            downloaded: self.flags.is_downloaded(),
1096            verified: self.flags.is_verified(),
1097            resident: crate::media::resident(&self.id),
1098            webxdc_topic: self.webxdc_topic().map(str::to_string),
1099            group_id: self.group_id().map(|b| bytes_to_hex_32(&b)),
1100            original_hash: self.original_hash().map(|b| bytes_to_hex_32(&b)),
1101            fallback_urls: self.fallback_urls().iter().map(|u| u.to_string()).collect(),
1102        }
1103    }
1104
1105    /// Heap bytes held beyond the struct itself (DeepSize).
1106    #[cfg(any(debug_assertions, feature = "bench"))]
1107    pub(crate) fn heap_bytes(&self) -> usize {
1108        self.url.len()
1109            + self.name.len()
1110            + self.img_meta.heap_bytes()
1111            + self.cold().map_or(0, |c| {
1112                std::mem::size_of::<AttachmentCold>()
1113                    + c.extension.len()
1114                    + c.path.len()
1115                    + std::mem::size_of_val(&*c.fallback_urls)
1116                    + c.fallback_urls.iter().map(|u| u.len()).sum::<usize>()
1117                    + c.webxdc_topic.as_ref().map_or(0, |t| t.len())
1118                    + c.original_hash.as_ref().map_or(0, |_| 32)
1119                    + c.group_id.as_ref().map_or(0, |_| 32)
1120            })
1121    }
1122}
1123
1124fn pack_img_meta(meta: Option<&ImageMetadata>) -> TinyVec<u8> {
1125    let Some(m) = meta else { return TinyVec::new() };
1126    let mut b = Vec::with_capacity(8 + m.thumbhash.len());
1127    b.extend_from_slice(&m.width.to_le_bytes());
1128    b.extend_from_slice(&m.height.to_le_bytes());
1129    b.extend_from_slice(m.thumbhash.as_bytes());
1130    TinyVec::from_vec(b)
1131}
1132
1133/// Parse a hex nonce string into [u8; 16], left-aligned, zero-allocation.
1134/// Both DM (32 hex chars) and legacy (24 hex chars) nonces are decoded.
1135/// Short nonces are right-padded with '0' to reach 32 chars before decode.
1136#[inline]
1137fn parse_nonce(hex: &str) -> [u8; 16] {
1138    hex_to_bytes_16(hex)
1139}
1140
1141// ============================================================================
1142// Npub Interner
1143// ============================================================================
1144
1145/// Strings laid end to end in one buffer: entry `i` is `bytes[ends[i - 1]..ends[i]]`.
1146#[derive(Clone, Debug, Default)]
1147struct StrArena {
1148    bytes: Vec<u8>,
1149    ends: Vec<u32>,
1150}
1151
1152impl StrArena {
1153    /// Whether `extra` more bytes keep every offset within u32.
1154    #[inline]
1155    fn fits(&self, extra: usize) -> bool {
1156        u32::try_from(self.bytes.len() + extra).is_ok()
1157    }
1158
1159    /// Append `s` and return its index. Callers check [`Self::fits`] first; a truncated end
1160    /// offset would let `get` slice through a character.
1161    fn push(&mut self, s: &str) -> usize {
1162        let end = u32::try_from(self.bytes.len() + s.len()).expect("arena past u32");
1163        self.bytes.extend_from_slice(s.as_bytes());
1164        self.ends.push(end);
1165        self.ends.len() - 1
1166    }
1167
1168    #[inline]
1169    fn get(&self, i: usize) -> Option<&str> {
1170        let end = *self.ends.get(i)? as usize;
1171        let start = if i == 0 { 0 } else { self.ends[i - 1] as usize };
1172        let bytes = &self.bytes[start..end];
1173        debug_assert!(std::str::from_utf8(bytes).is_ok(), "arena entry {i} split a character");
1174        // SAFETY: `push` appends whole `&str`s only, and nothing else writes the buffer.
1175        Some(unsafe { std::str::from_utf8_unchecked(bytes) })
1176    }
1177
1178    #[inline]
1179    fn len(&self) -> usize {
1180        self.ends.len()
1181    }
1182
1183    fn reserve(&mut self, entries: usize, bytes: usize) {
1184        self.ends.reserve(entries);
1185        self.bytes.reserve(bytes);
1186    }
1187
1188    fn shrink_to_fit(&mut self) {
1189        self.ends.shrink_to_fit();
1190        self.bytes.shrink_to_fit();
1191    }
1192
1193    fn heap_bytes(&self) -> usize {
1194        self.bytes.capacity() + self.ends.capacity() * std::mem::size_of::<u32>()
1195    }
1196}
1197
1198/// Length of a bech32 npub, for sizing the arena ahead of a bulk load.
1199const NPUB_LEN: usize = 63;
1200
1201/// String interner for npubs using sorted Vec + binary search.
1202///
1203/// Each unique npub is stored exactly once. Messages reference npubs by u16 index.
1204/// - `intern()`: O(log n) lookup + O(n) insert for new strings
1205/// - `resolve()`: O(1) by index
1206///
1207/// Memory: the npub bytes in one arena, plus a 4-byte offset and a 2-byte sorted index each.
1208#[derive(Clone, Debug, Default)]
1209pub struct NpubInterner {
1210    /// npubs in insertion order - index is the stable ID used by messages
1211    npubs: StrArena,
1212    /// Indices into npubs, sorted alphabetically for binary search
1213    sorted: Vec<u16>,
1214    /// Reaction (emoji, NIP-30 url) pairs in insertion order, two entries each; a few hundred per session.
1215    emojis: StrArena,
1216    /// Per pair: whether it has a url, since an absent url and an empty one are different keys.
1217    emoji_has_url: Vec<bool>,
1218    /// Indices into emojis, sorted by pair for binary search
1219    emojis_sorted: Vec<u32>,
1220}
1221
1222/// Sentinel value for "no npub" (avoids Option overhead)
1223pub const NO_NPUB: u16 = u16::MAX;
1224
1225impl NpubInterner {
1226    pub fn new() -> Self {
1227        Self::default()
1228    }
1229
1230    /// Pre-allocate capacity for expected number of unique npubs
1231    pub fn with_capacity(capacity: usize) -> Self {
1232        let mut interner = Self::default();
1233        interner.reserve(capacity);
1234        interner
1235    }
1236
1237    /// Room for `additional` more npubs, so a bulk load grows each buffer once.
1238    pub fn reserve(&mut self, additional: usize) {
1239        self.npubs.reserve(additional, additional * NPUB_LEN);
1240        self.sorted.reserve(additional);
1241    }
1242
1243    /// Drop the growth slack, once a bulk load is done.
1244    pub fn shrink_to_fit(&mut self) {
1245        self.npubs.shrink_to_fit();
1246        self.sorted.shrink_to_fit();
1247        self.emojis.shrink_to_fit();
1248        self.emoji_has_url.shrink_to_fit();
1249        self.emojis_sorted.shrink_to_fit();
1250    }
1251
1252    #[inline]
1253    fn emoji_pair(&self, idx: usize) -> Option<(&str, Option<&str>)> {
1254        let at = idx.checked_mul(2)?;
1255        let emoji = self.emojis.get(at)?;
1256        let url = self.emojis.get(at + 1)?;
1257        Some((emoji, self.emoji_has_url[idx].then_some(url)))
1258    }
1259
1260    /// Intern a reaction's (emoji, url) pair, returning its stable index.
1261    pub fn intern_emoji(&mut self, emoji: &str, url: Option<&str>) -> u32 {
1262        let key = (emoji, url);
1263        let found = self.emojis_sorted.binary_search_by(|&i| {
1264            self.emoji_pair(i as usize).unwrap_or(("", None)).cmp(&key)
1265        });
1266        match found {
1267            Ok(pos) => self.emojis_sorted[pos],
1268            Err(pos) => {
1269                // Past u32 the pair reads as no emoji, as an unknown index does.
1270                let Ok(idx) = u32::try_from(self.emoji_has_url.len()) else { return u32::MAX };
1271                if idx == u32::MAX || !self.emojis.fits(emoji.len() + url.map_or(0, str::len)) {
1272                    return u32::MAX;
1273                }
1274                self.emojis.push(emoji);
1275                self.emojis.push(url.unwrap_or(""));
1276                self.emoji_has_url.push(url.is_some());
1277                self.emojis_sorted.insert(pos, idx);
1278                idx
1279            }
1280        }
1281    }
1282
1283    /// Resolve an interned (emoji, url) pair; an unknown index reads as no emoji.
1284    #[inline]
1285    pub fn emoji(&self, idx: u32) -> (&str, Option<&str>) {
1286        self.emoji_pair(idx as usize).unwrap_or(("", None))
1287    }
1288
1289    #[inline]
1290    fn npub_at(&self, idx: u16) -> &str {
1291        self.npubs.get(idx as usize).unwrap_or("")
1292    }
1293
1294    /// Intern an npub string, returning its stable index.
1295    ///
1296    /// If the npub already exists, returns the existing index.
1297    /// If new, stores it and returns a new index.
1298    pub fn intern(&mut self, npub: &str) -> u16 {
1299        // Binary search in sorted order
1300        let result = self.sorted.binary_search_by(|&idx| self.npub_at(idx).cmp(npub));
1301
1302        match result {
1303            Ok(pos) => self.sorted[pos], // Found existing
1304            Err(insert_pos) => {
1305                // u16::MAX is the NO_NPUB sentinel; at/past it new indices would alias the
1306                // sentinel then wrap, misattributing authors — degrade to authorless instead.
1307                if self.npubs.len() >= NO_NPUB as usize || !self.npubs.fits(npub.len()) {
1308                    return NO_NPUB;
1309                }
1310                let new_idx = self.npubs.push(npub) as u16;
1311                self.sorted.insert(insert_pos, new_idx);
1312                new_idx
1313            }
1314        }
1315    }
1316
1317    /// Intern an optional npub, returning NO_NPUB sentinel for None.
1318    #[inline]
1319    pub fn intern_opt(&mut self, npub: Option<&str>) -> u16 {
1320        match npub {
1321            Some(s) if !s.is_empty() => self.intern(s),
1322            _ => NO_NPUB,
1323        }
1324    }
1325
1326    /// Look up an npub without inserting. Returns its handle if already interned.
1327    pub fn lookup(&self, npub: &str) -> Option<u16> {
1328        self.sorted.binary_search_by(|&idx| self.npub_at(idx).cmp(npub)).ok().map(|pos| self.sorted[pos])
1329    }
1330
1331    /// Resolve an index back to the npub string.
1332    ///
1333    /// Returns None for NO_NPUB sentinel or out-of-bounds index.
1334    #[inline]
1335    pub fn resolve(&self, idx: u16) -> Option<&str> {
1336        if idx == NO_NPUB {
1337            return None;
1338        }
1339        self.npubs.get(idx as usize)
1340    }
1341
1342    /// Number of unique npubs stored
1343    #[inline]
1344    pub fn len(&self) -> usize {
1345        self.npubs.len()
1346    }
1347
1348    #[inline]
1349    pub fn is_empty(&self) -> bool {
1350        self.npubs.len() == 0
1351    }
1352
1353    /// Total memory used by the interner (approximate)
1354    pub fn memory_usage(&self) -> usize {
1355        std::mem::size_of::<Self>()
1356            + self.npubs.heap_bytes()
1357            + self.sorted.capacity() * std::mem::size_of::<u16>()
1358            + self.emojis.heap_bytes()
1359            + self.emoji_has_url.capacity()
1360            + self.emojis_sorted.capacity() * std::mem::size_of::<u32>()
1361    }
1362}
1363
1364#[cfg(test)]
1365mod interner_arena_tests {
1366    use super::*;
1367
1368    #[test]
1369    fn arena_entries_of_any_length_read_back() {
1370        let mut a = StrArena::default();
1371        let words = ["", "a", "npub1xyz", "", "猫🐈 multi-byte", &"z".repeat(70_000), "end"];
1372        for (i, w) in words.iter().enumerate() {
1373            assert!(a.fits(w.len()));
1374            assert_eq!(a.push(w), i);
1375        }
1376        for (i, w) in words.iter().enumerate() {
1377            assert_eq!(a.get(i), Some(*w), "entry {i}");
1378        }
1379        assert_eq!(a.get(words.len()), None);
1380        assert_eq!(a.bytes.len(), words.iter().map(|w| w.len()).sum::<usize>(), "no separators, no padding");
1381    }
1382
1383    #[test]
1384    fn npubs_intern_resolve_and_look_up_through_the_arena() {
1385        let npubs: Vec<String> = (0..500).rev().map(|i| format!("npub1{i:0>58}")).collect();
1386        let mut interner = NpubInterner::new();
1387        let handles: Vec<u16> = npubs.iter().map(|n| interner.intern(n)).collect();
1388        assert_eq!(handles, (0..500).collect::<Vec<u16>>(), "handles follow insertion order");
1389        for (n, &h) in npubs.iter().zip(&handles) {
1390            assert_eq!(interner.resolve(h), Some(n.as_str()));
1391            assert_eq!(interner.lookup(n), Some(h));
1392            assert_eq!(interner.intern(n), h, "a repeat keeps its handle");
1393        }
1394        assert_eq!(interner.len(), 500);
1395        assert_eq!(interner.lookup("npub1missing"), None);
1396        assert_eq!(interner.npubs.bytes.len(), 500 * 63);
1397    }
1398
1399    #[test]
1400    fn the_handle_space_stops_short_of_the_sentinel() {
1401        let mut interner = NpubInterner::new();
1402        for i in 0..NO_NPUB as usize {
1403            assert_eq!(interner.intern(&format!("n{i:06}")), i as u16);
1404        }
1405        assert_eq!(interner.intern("n999999"), NO_NPUB, "the 65536th npub degrades to authorless");
1406        assert_eq!(interner.len(), NO_NPUB as usize);
1407        assert_eq!(interner.intern("n000000"), 0, "known npubs still resolve");
1408        assert_eq!(interner.resolve(65534), Some("n065534"));
1409        assert_eq!(interner.resolve(NO_NPUB), None);
1410    }
1411
1412    #[test]
1413    fn reserve_and_shrink_keep_every_entry() {
1414        let mut interner = NpubInterner::new();
1415        interner.reserve(100);
1416        assert!(interner.npubs.bytes.capacity() >= 100 * NPUB_LEN);
1417        let a = interner.intern("npub1a");
1418        let e = interner.intern_emoji("🔥", None);
1419        interner.shrink_to_fit();
1420        assert_eq!(interner.npubs.bytes.capacity(), interner.npubs.bytes.len());
1421        assert_eq!(interner.resolve(a), Some("npub1a"));
1422        assert_eq!(interner.emoji(e), ("🔥", None));
1423    }
1424
1425    #[test]
1426    fn emoji_pairs_keep_an_absent_url_apart_from_an_empty_one() {
1427        let mut interner = NpubInterner::new();
1428        let none = interner.intern_emoji("party", None);
1429        let empty = interner.intern_emoji("party", Some(""));
1430        let url = interner.intern_emoji("party", Some("https://e/p.png"));
1431        let fire = interner.intern_emoji("🔥", None);
1432        assert_eq!([none, empty, url, fire], [0, 1, 2, 3]);
1433        assert_eq!(interner.emoji(none), ("party", None));
1434        assert_eq!(interner.emoji(empty), ("party", Some("")));
1435        assert_eq!(interner.emoji(url), ("party", Some("https://e/p.png")));
1436        assert_eq!(interner.emoji(fire), ("🔥", None));
1437        assert_eq!(interner.intern_emoji("party", Some("")), empty);
1438        assert_eq!(interner.intern_emoji("🔥", None), fire);
1439        assert_eq!(interner.emoji(4), ("", None));
1440        assert_eq!(interner.emoji(u32::MAX), ("", None));
1441    }
1442
1443    #[test]
1444    fn the_arena_costs_less_than_a_string_per_npub() {
1445        let mut interner = NpubInterner::new();
1446        interner.reserve(2000);
1447        for i in 0..2000 {
1448            interner.intern(&format!("npub1{i:0>58}"));
1449        }
1450        let per = interner.memory_usage() / 2000;
1451        assert!(per <= 63 + 4 + 2 + 1, "{per} B per npub");
1452    }
1453}
1454
1455// ============================================================================
1456// Compact Message
1457// ============================================================================
1458
1459/// Memory-efficient message: binary ids, interned npubs and emoji, packed flags, and the
1460/// fields most messages never carry (a reply, edits, a link preview, custom emoji, bot
1461/// targets) behind two optional boxes. 96 bytes inline.
1462#[derive(Clone, Debug)]
1463pub struct CompactMessage {
1464    /// Message ID as binary (64 hex chars -> 32 bytes)
1465    id: [u8; 32],
1466    /// Timestamp in milliseconds (full precision for sub-second ordering)
1467    pub at: u64,
1468    /// Message content (`Box<str>` = 16 bytes vs String's 24 bytes)
1469    content: Box<str>,
1470    /// File attachments
1471    pub attachments: TinyVec<CompactAttachment>,
1472    /// Emoji reactions
1473    pub reactions: TinyVec<CompactReaction>,
1474    /// What this message replies to, when it does
1475    pub reply: Option<Box<CompactReply>>,
1476    /// Edit history, link preview, custom emoji and bot targets, when any are present
1477    pub extras: Option<Box<MessageExtras>>,
1478    /// NIP-40 expiry as unix SECONDS (0 = permanent). Inline: the self-destruct sweep
1479    /// scans it across every message.
1480    pub expiration_secs: u32,
1481    /// Index into NpubInterner for sender's npub (NO_NPUB if none)
1482    pub npub_idx: u16,
1483    /// Packed boolean flags (mine, pending, failed, replied_to_has_attachment)
1484    pub flags: MessageFlags,
1485}
1486
1487/// The replied-to message, as quoted on this one.
1488#[derive(Clone, Debug)]
1489pub struct CompactReply {
1490    pub id: [u8; 32],
1491    /// Index into NpubInterner for the replied-to author (NO_NPUB if none)
1492    pub npub_idx: u16,
1493    pub content: Option<Box<str>>,
1494    /// The quote's NIP-30 emoji, interned (see [`NpubInterner::intern_emoji`])
1495    pub emoji_tags: TinyVec<u32>,
1496}
1497
1498/// One revision of an edited message.
1499#[derive(Clone, Debug)]
1500struct CompactEdit {
1501    /// Empty for the newest revision while [`MessageExtras::tail_is_content`]: that text is the message's own.
1502    content: Box<str>,
1503    edited_at: u64,
1504}
1505
1506/// A text span as held: a colour run's stops packed to `0xRRGGBB` when every one is
1507/// canonical `#rrggbb`, which is all the parsers emit.
1508#[derive(Clone, Debug)]
1509enum HeldSpan {
1510    Color { from: u32, to: u32, effect: crate::text_color::Effect, colors: TinyVec<u32> },
1511    Time(crate::text_spans::TimeSpan),
1512    Raw(Box<crate::text_spans::ColorSpan>),
1513}
1514
1515fn pack_color(c: &str) -> Option<u32> {
1516    let h = c.strip_prefix('#')?.as_bytes();
1517    if h.len() != 6 || !h.iter().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(b)) {
1518        return None;
1519    }
1520    Some(h.iter().fold(0u32, |v, &b| (v << 4) | (b as char).to_digit(16).unwrap_or(0)))
1521}
1522
1523impl HeldSpan {
1524    fn hold(span: crate::text_spans::TextSpan) -> Self {
1525        use crate::text_spans::TextSpan;
1526        match span {
1527            TextSpan::Time(t) => HeldSpan::Time(t),
1528            TextSpan::Color(c) => match c.colors.iter().map(|s| pack_color(s)).collect::<Option<Vec<u32>>>() {
1529                Some(colors) => HeldSpan::Color { from: c.from, to: c.to, effect: c.effect, colors: TinyVec::from_vec(colors) },
1530                None => HeldSpan::Raw(Box::new(c)),
1531            },
1532        }
1533    }
1534
1535    fn to_span(&self) -> crate::text_spans::TextSpan {
1536        use crate::text_spans::{ColorSpan, TextSpan};
1537        match self {
1538            HeldSpan::Color { from, to, effect, colors } => TextSpan::Color(ColorSpan {
1539                from: *from,
1540                to: *to,
1541                effect: *effect,
1542                colors: colors.iter().map(|v| format!("#{v:06x}")).collect(),
1543            }),
1544            HeldSpan::Time(t) => TextSpan::Time(t.clone()),
1545            HeldSpan::Raw(c) => TextSpan::Color((**c).clone()),
1546        }
1547    }
1548
1549    #[cfg(any(debug_assertions, feature = "bench"))]
1550    fn heap_bytes(&self) -> usize {
1551        match self {
1552            HeldSpan::Color { colors, .. } => colors.heap_bytes(),
1553            HeldSpan::Time(_) => 0,
1554            HeldSpan::Raw(c) => {
1555                std::mem::size_of::<crate::text_spans::ColorSpan>()
1556                    + c.colors.capacity() * std::mem::size_of::<String>()
1557                    + c.colors.iter().map(|s| s.capacity()).sum::<usize>()
1558            }
1559        }
1560    }
1561}
1562
1563fn hold_spans(spans: Vec<crate::text_spans::TextSpan>) -> TinyVec<HeldSpan> {
1564    spans.into_iter().map(HeldSpan::hold).collect()
1565}
1566
1567/// Preview presence bits, in [`preview_fields`] order, then the two "same as og_" bits.
1568const PREVIEW_TITLE_IS_OG: u16 = 1 << 8;
1569const PREVIEW_DESC_IS_OG: u16 = 1 << 9;
1570
1571fn preview_fields(m: &SiteMetadata) -> [&Option<String>; 8] {
1572    [&m.og_title, &m.og_description, &m.og_image, &m.og_url, &m.og_type, &m.title, &m.description, &m.favicon]
1573}
1574
1575fn put_str(out: &mut Vec<u8>, s: &str) {
1576    let mut n = s.len();
1577    while n >= 0x80 {
1578        out.push(n as u8 | 0x80);
1579        n >>= 7;
1580    }
1581    out.push(n as u8);
1582    out.extend_from_slice(s.as_bytes());
1583}
1584
1585fn take_str<'a>(b: &'a [u8], pos: &mut usize) -> &'a str {
1586    let (mut n, mut shift) = (0usize, 0);
1587    while let Some(&byte) = b.get(*pos) {
1588        *pos += 1;
1589        n |= ((byte & 0x7f) as usize) << shift;
1590        if byte < 0x80 {
1591            break;
1592        }
1593        shift += 7;
1594    }
1595    let s = b.get(*pos..*pos + n).and_then(|s| std::str::from_utf8(s).ok()).unwrap_or_default();
1596    *pos += n;
1597    s
1598}
1599
1600/// A link preview in one allocation: presence bits, then the domain and each present
1601/// string length-prefixed; a title or description equal to its og_ twin is stored once.
1602fn pack_preview(m: &SiteMetadata) -> TinyVec<u8> {
1603    let fields = preview_fields(m);
1604    let mut bits = 0u16;
1605    if m.title.is_some() && m.title == m.og_title {
1606        bits |= PREVIEW_TITLE_IS_OG;
1607    }
1608    if m.description.is_some() && m.description == m.og_description {
1609        bits |= PREVIEW_DESC_IS_OG;
1610    }
1611    let len = fields.iter().filter_map(|f| f.as_ref()).map(|s| s.len() + 3).sum::<usize>() + m.domain.len() + 5;
1612    let mut out = Vec::with_capacity(len);
1613    out.extend_from_slice(&[0, 0]);
1614    put_str(&mut out, &m.domain);
1615    for (i, f) in fields.iter().enumerate() {
1616        let Some(s) = f else { continue };
1617        bits |= 1 << i;
1618        let deduped = (i == 5 && bits & PREVIEW_TITLE_IS_OG != 0) || (i == 6 && bits & PREVIEW_DESC_IS_OG != 0);
1619        if !deduped {
1620            put_str(&mut out, s);
1621        }
1622    }
1623    out[..2].copy_from_slice(&bits.to_le_bytes());
1624    TinyVec::from_vec(out)
1625}
1626
1627fn unpack_preview(b: &[u8]) -> Option<SiteMetadata> {
1628    let bits = u16::from_le_bytes([*b.first()?, *b.get(1)?]);
1629    let mut pos = 2;
1630    let domain = take_str(b, &mut pos).to_string();
1631    let mut f: [Option<String>; 8] = Default::default();
1632    for i in 0..8 {
1633        if bits & (1 << i) == 0 {
1634            continue;
1635        }
1636        f[i] = Some(match i {
1637            5 if bits & PREVIEW_TITLE_IS_OG != 0 => f[0].clone().unwrap_or_default(),
1638            6 if bits & PREVIEW_DESC_IS_OG != 0 => f[1].clone().unwrap_or_default(),
1639            _ => take_str(b, &mut pos).to_string(),
1640        });
1641    }
1642    let [og_title, og_description, og_image, og_url, og_type, title, description, favicon] = f;
1643    Some(SiteMetadata { domain, og_title, og_description, og_image, og_url, og_type, title, description, favicon })
1644}
1645
1646/// The rarely-set parts of a message, boxed together so a plain message pays 8 bytes.
1647#[derive(Clone, Debug, Default)]
1648pub struct MessageExtras {
1649    /// Oldest first
1650    edits: TinyVec<CompactEdit>,
1651    /// Packed by [`pack_preview`]; empty when there is none
1652    preview: TinyVec<u8>,
1653    /// NIP-30 emoji tags travelling with this rumor, interned
1654    pub emoji_tags: TinyVec<u32>,
1655    /// Bot routing targets as interned npub handles
1656    pub addressed_bots: TinyVec<u16>,
1657    spans: TinyVec<HeldSpan>,
1658    role_mentions: TinyVec<[u8; 32]>,
1659    /// The newest edit's text is the message content, held there once
1660    tail_is_content: bool,
1661}
1662
1663impl MessageExtras {
1664    fn is_empty(&self) -> bool {
1665        self.edits.is_empty()
1666            && self.preview.is_empty()
1667            && self.emoji_tags.is_empty()
1668            && self.addressed_bots.is_empty()
1669            && self.spans.is_empty()
1670            && self.role_mentions.is_empty()
1671    }
1672
1673    fn edit_history(&self, content: &str) -> Vec<EditEntry> {
1674        let last = self.edits.len().wrapping_sub(1);
1675        self.edits
1676            .iter()
1677            .enumerate()
1678            .map(|(i, e)| EditEntry {
1679                content: if i == last && self.tail_is_content { content.to_string() } else { e.content.to_string() },
1680                edited_at: e.edited_at,
1681            })
1682            .collect()
1683    }
1684
1685    /// Heap bytes held beyond the box itself (DeepSize).
1686    #[cfg(any(debug_assertions, feature = "bench"))]
1687    pub(crate) fn heap_bytes(&self) -> usize {
1688        self.edits.heap_bytes()
1689            + self.edits.iter().map(|e| e.content.len()).sum::<usize>()
1690            + self.preview.heap_bytes()
1691            + self.emoji_tags.heap_bytes()
1692            + self.addressed_bots.heap_bytes()
1693            + self.spans.heap_bytes()
1694            + self.spans.iter().map(HeldSpan::heap_bytes).sum::<usize>()
1695            + self.role_mentions.heap_bytes()
1696    }
1697}
1698
1699fn intern_emoji_tags(tags: &[crate::types::EmojiTag], interner: &mut NpubInterner) -> TinyVec<u32> {
1700    tags.iter().map(|t| interner.intern_emoji(&t.shortcode, Some(&t.url))).collect()
1701}
1702
1703fn resolve_emoji_tags(tags: &TinyVec<u32>, interner: &NpubInterner) -> Vec<crate::types::EmojiTag> {
1704    tags.iter()
1705        .map(|&i| {
1706            let (shortcode, url) = interner.emoji(i);
1707            crate::types::EmojiTag { shortcode: shortcode.to_string(), url: url.unwrap_or_default().to_string() }
1708        })
1709        .collect()
1710}
1711
1712impl CompactMessage {
1713    /// Check if this message has a replied-to reference
1714    #[inline]
1715    pub fn has_reply(&self) -> bool {
1716        self.reply.is_some()
1717    }
1718
1719    /// Check if this message has been edited
1720    #[inline]
1721    pub fn is_edited(&self) -> bool {
1722        self.extras.as_ref().is_some_and(|x| !x.edits.is_empty())
1723    }
1724
1725    /// The edit history, oldest first; empty when never edited.
1726    pub fn edit_history(&self) -> Vec<EditEntry> {
1727        self.extras.as_ref().map_or_else(Vec::new, |x| x.edit_history(&self.content))
1728    }
1729
1730    pub fn preview_metadata(&self) -> Option<SiteMetadata> {
1731        self.extras.as_ref().and_then(|x| unpack_preview(x.preview.as_slice()))
1732    }
1733
1734    pub fn set_preview_metadata(&mut self, metadata: Option<SiteMetadata>) {
1735        self.extras_mut().preview = metadata.as_ref().map_or_else(TinyVec::new, pack_preview);
1736        self.drop_empty_extras();
1737    }
1738
1739    /// The extras box, created on first use.
1740    fn extras_mut(&mut self) -> &mut MessageExtras {
1741        self.extras.get_or_insert_with(Default::default)
1742    }
1743
1744    fn drop_empty_extras(&mut self) {
1745        if self.extras.as_ref().is_some_and(|x| x.is_empty()) {
1746            self.extras = None;
1747        }
1748    }
1749
1750    /// Fixed once stored: the index orders positions by it.
1751    #[inline]
1752    pub fn id(&self) -> &[u8; 32] {
1753        &self.id
1754    }
1755
1756    /// Also the newest revision of the edit history; change it through an edit.
1757    #[inline]
1758    pub fn content(&self) -> &str {
1759        &self.content
1760    }
1761
1762    /// Get the message ID as a string (hex for event IDs, "pending-..." for pending)
1763    #[inline]
1764    pub fn id_hex(&self) -> String {
1765        decode_message_id(&self.id)
1766    }
1767
1768    /// Get the replied-to ID as a hex string, or empty if none
1769    #[inline]
1770    pub fn replied_to_hex(&self) -> String {
1771        match &self.reply {
1772            Some(r) => bytes_to_hex_32(&r.id),
1773            None => String::new(),
1774        }
1775    }
1776
1777    /// Get timestamp as milliseconds (for compatibility with frontend)
1778    #[inline]
1779    pub fn timestamp_ms(&self) -> u64 {
1780        timestamp_from_compact(self.at)
1781    }
1782
1783    /// Apply an edit to this message.
1784    ///
1785    /// `emoji_tags` are the NIP-30 custom-emoji tags resolved from the new
1786    /// content; they're adopted only when this edit is the newest revision so
1787    /// an out-of-order older edit can't clobber the live content's emoji.
1788    pub fn apply_edit(&mut self, mut new_content: String, edited_at: u64, emoji_tags: Vec<crate::types::EmojiTag>, text_spans: Vec<crate::text_spans::TextSpan>, interner: &mut NpubInterner) {
1789        let original_at = self.timestamp_ms();
1790        let extras = self.extras.get_or_insert_with(Default::default);
1791        // Initialize edit history with original content if not present
1792        if extras.edits.is_empty() {
1793            extras.edits.push(CompactEdit { content: Box::default(), edited_at: original_at });
1794            extras.tail_is_content = true;
1795        }
1796        // Deduplicate: skip if we already have this edit
1797        if extras.edits.iter().any(|e| e.edited_at == edited_at) {
1798            return;
1799        }
1800        // Only the newest revision drives the visible content + emoji.
1801        let is_latest = extras.edits.iter().all(|e| e.edited_at < edited_at);
1802        if std::mem::take(&mut extras.tail_is_content) {
1803            if let Some(tail) = extras.edits.last_mut() {
1804                tail.content = if is_latest { std::mem::take(&mut self.content) } else { self.content.clone() };
1805            }
1806        }
1807        let content = if is_latest { Box::default() } else { std::mem::take(&mut new_content).into_boxed_str() };
1808        extras.edits.push(CompactEdit { content, edited_at });
1809        extras.edits.as_mut_slice().sort_by_key(|e| e.edited_at);
1810        if is_latest {
1811            self.content = new_content.into_boxed_str();
1812            extras.tail_is_content = true;
1813            extras.emoji_tags = intern_emoji_tags(&emoji_tags, interner);
1814            extras.spans = hold_spans(text_spans);
1815        } else if let Some(tail) = extras.edits.last_mut().filter(|t| t.content == self.content) {
1816            tail.content = Box::default();
1817            extras.tail_is_content = true;
1818        }
1819    }
1820
1821    /// Get replied_to_has_attachment from flags
1822    #[inline]
1823    pub fn replied_to_has_attachment(&self) -> Option<bool> {
1824        self.flags.replied_to_has_attachment()
1825    }
1826
1827    /// Add a reaction to this message
1828    /// (see [`MAX_REACTION_GROUPS`] for the distinct-emoji ceiling)
1829    pub fn add_reaction(&mut self, reaction: Reaction, interner: &mut NpubInterner) -> bool {
1830        let reaction_id = hex_to_bytes_32(&reaction.id);
1831        if self.reactions.iter().any(|r| r.id == reaction_id) {
1832            return false;
1833        }
1834
1835        // The interned form of `Reaction::same_slot`: the set is keyed by
1836        // (author, emoji), so a second event from the same author carrying the
1837        // same emoji is the reaction we already hold, not another one.
1838        let author_idx = interner.intern(&reaction.author_id);
1839        let emoji = reaction.emoji.as_str();
1840        if self.reactions.iter().any(|r| r.author_idx == author_idx && r.emoji(interner) == emoji) {
1841            return false;
1842        }
1843
1844        // Distinct-emoji ceiling: joining an existing group is always fine,
1845        // but a reaction opening a group past the cap is refused — the same
1846        // bound the UI draws, enforced against hostile inbound too.
1847        if !self.reactions.iter().any(|r| r.emoji(interner) == emoji) {
1848            let mut groups: [&str; MAX_REACTION_GROUPS] = [""; MAX_REACTION_GROUPS];
1849            let mut n = 0;
1850            for r in self.reactions.iter() {
1851                let e = r.emoji(interner);
1852                if !groups[..n].contains(&e) {
1853                    if n == MAX_REACTION_GROUPS {
1854                        return false;
1855                    }
1856                    groups[n] = e;
1857                    n += 1;
1858                }
1859            }
1860            if n >= MAX_REACTION_GROUPS {
1861                return false;
1862            }
1863        }
1864
1865        let compact = CompactReaction {
1866            id: reaction_id,
1867            emoji_idx: interner.intern_emoji(emoji, reaction.emoji_url.as_deref()),
1868            author_idx,
1869        };
1870        self.reactions.push(compact);
1871        true
1872    }
1873
1874    /// Remove a reaction by its hex event id. Returns true if one was removed.
1875    pub fn remove_reaction(&mut self, reaction_id: &str) -> bool {
1876        let target = hex_to_bytes_32(reaction_id);
1877        if !self.reactions.iter().any(|r| r.id == target) {
1878            return false;
1879        }
1880        self.reactions.retain(|r| r.id != target);
1881        true
1882    }
1883
1884    // Flag accessors for compatibility
1885    #[inline]
1886    pub fn is_mine(&self) -> bool { self.flags.is_mine() }
1887    #[inline]
1888    pub fn is_pending(&self) -> bool { self.flags.is_pending() }
1889    #[inline]
1890    pub fn is_failed(&self) -> bool { self.flags.is_failed() }
1891
1892    // Flag setters
1893    #[inline]
1894    pub fn set_pending(&mut self, value: bool) { self.flags.set_pending(value); }
1895    #[inline]
1896    pub fn set_failed(&mut self, value: bool) { self.flags.set_failed(value); }
1897    #[inline]
1898    pub fn set_mine(&mut self, value: bool) { self.flags.set_mine(value); }
1899}
1900
1901// ============================================================================
1902// Compact Message Vec with Binary Search
1903// ============================================================================
1904
1905/// Sorted message storage with O(log n) lookup by ID.
1906///
1907/// Messages are stored sorted by timestamp. A separate index of positions, ordered by
1908/// each message's id, gives O(log n) lookup by binary search through the positions.
1909#[derive(Clone, Debug, Default)]
1910pub struct CompactMessageVec {
1911    /// Messages sorted by timestamp (ascending)
1912    messages: Vec<CompactMessage>,
1913    /// Positions in `messages`, sorted by the id at each
1914    id_index: Vec<u32>,
1915}
1916
1917/// Room for `additional` more, growing by an eighth (at least 8) when full: a large
1918/// chat's next live message must not double its buffers.
1919fn reserve_slack<T>(v: &mut Vec<T>, additional: usize) {
1920    if v.capacity() - v.len() < additional {
1921        v.reserve_exact(additional.max(v.len() / 8).max(8));
1922    }
1923}
1924
1925impl CompactMessageVec {
1926    pub fn new() -> Self {
1927        Self {
1928            messages: Vec::new(),
1929            id_index: Vec::new(),
1930        }
1931    }
1932
1933    pub fn with_capacity(capacity: usize) -> Self {
1934        Self {
1935            messages: Vec::with_capacity(capacity),
1936            id_index: Vec::with_capacity(capacity),
1937        }
1938    }
1939
1940    /// Number of messages
1941    #[inline]
1942    pub fn len(&self) -> usize {
1943        self.messages.len()
1944    }
1945
1946    #[inline]
1947    pub fn is_empty(&self) -> bool {
1948        self.messages.is_empty()
1949    }
1950
1951    /// Get all messages (sorted by timestamp)
1952    #[inline]
1953    pub fn messages(&self) -> &[CompactMessage] {
1954        &self.messages
1955    }
1956
1957    /// Get a mutable reference to all messages. Call `rebuild_index()` after changing
1958    /// any id or the order.
1959    #[inline]
1960    pub fn messages_mut(&mut self) -> &mut Vec<CompactMessage> {
1961        &mut self.messages
1962    }
1963
1964    /// Iterate over messages (supports .rev())
1965    #[inline]
1966    pub fn iter(&self) -> std::slice::Iter<'_, CompactMessage> {
1967        self.messages.iter()
1968    }
1969
1970    /// Iterate over messages mutably
1971    #[inline]
1972    pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, CompactMessage> {
1973        self.messages.iter_mut()
1974    }
1975
1976    /// Get the last message
1977    #[inline]
1978    pub fn last(&self) -> Option<&CompactMessage> {
1979        self.messages.last()
1980    }
1981
1982    /// Get last message timestamp (in milliseconds)
1983    #[inline]
1984    pub fn last_timestamp(&self) -> Option<u64> {
1985        self.messages.last().map(|m| timestamp_from_compact(m.at))
1986    }
1987
1988    /// Get the first message
1989    #[inline]
1990    pub fn first(&self) -> Option<&CompactMessage> {
1991        self.messages.first()
1992    }
1993
1994    /// Binary search of the index: `Ok(rank)` where `id` is held, else where it would go.
1995    /// A stale position (between a bulk change and `rebuild_index`) sorts last rather than panicking.
1996    #[inline]
1997    fn search(&self, id: &[u8; 32]) -> Result<usize, usize> {
1998        let messages = &self.messages;
1999        self.id_index.binary_search_by(|&pos| {
2000            messages.get(pos as usize).map_or(std::cmp::Ordering::Greater, |m| m.id.cmp(id))
2001        })
2002    }
2003
2004    /// Find a message by ID using binary search - O(log n)
2005    pub fn find_by_id(&self, id: &[u8; 32]) -> Option<&CompactMessage> {
2006        let rank = self.search(id).ok()?;
2007        self.messages.get(self.id_index[rank] as usize)
2008    }
2009
2010    /// Find a message by ID (mutable) - O(log n)
2011    pub fn find_by_id_mut(&mut self, id: &[u8; 32]) -> Option<&mut CompactMessage> {
2012        let rank = self.search(id).ok()?;
2013        let pos = self.id_index[rank] as usize;
2014        self.messages.get_mut(pos)
2015    }
2016
2017    /// Find a message by ID string (hex or pending) - O(log n)
2018    pub fn find_by_hex_id(&self, id_str: &str) -> Option<&CompactMessage> {
2019        if id_str.is_empty() {
2020            return None;
2021        }
2022        let id = encode_message_id(id_str);
2023        self.find_by_id(&id)
2024    }
2025
2026    /// Find a message by ID string (mutable) - O(log n)
2027    pub fn find_by_hex_id_mut(&mut self, id_str: &str) -> Option<&mut CompactMessage> {
2028        if id_str.is_empty() {
2029            return None;
2030        }
2031        let id = encode_message_id(id_str);
2032        self.find_by_id_mut(&id)
2033    }
2034
2035    /// Check if a message with the given ID exists - O(log n)
2036    pub fn contains_id(&self, id: &[u8; 32]) -> bool {
2037        self.search(id).is_ok()
2038    }
2039
2040    /// Remove a message by hex ID string. Returns true if removed.
2041    pub fn remove_by_hex_id(&mut self, id_str: &str) -> bool {
2042        if id_str.is_empty() {
2043            return false;
2044        }
2045        self.remove_by_id(&encode_message_id(id_str))
2046    }
2047
2048    /// Remove a message by binary ID. Returns true if removed.
2049    pub fn remove_by_id(&mut self, id: &[u8; 32]) -> bool {
2050        let Ok(rank) = self.search(id) else { return false };
2051        let msg_pos = self.id_index.remove(rank);
2052        self.messages.remove(msg_pos as usize);
2053        // Positions past the hole shift down by one; the id order is untouched.
2054        for pos in &mut self.id_index {
2055            if *pos > msg_pos {
2056                *pos -= 1;
2057            }
2058        }
2059        true
2060    }
2061
2062    /// Give a message a new id in place (a pending send taking its event id), moving only
2063    /// its own index entry. Returns false if `old` isn't held or `new` already is.
2064    pub fn rekey(&mut self, old: &[u8; 32], new: [u8; 32]) -> bool {
2065        if old == &new {
2066            return self.contains_id(old);
2067        }
2068        let Ok(old_rank) = self.search(old) else { return false };
2069        let Err(new_rank) = self.search(&new) else { return false };
2070        let msg_pos = self.id_index.remove(old_rank);
2071        let new_rank = if new_rank > old_rank { new_rank - 1 } else { new_rank };
2072        self.id_index.insert(new_rank, msg_pos);
2073        self.messages[msg_pos as usize].id = new;
2074        true
2075    }
2076
2077    /// Check if a message with the given ID string exists - O(log n)
2078    pub fn contains_hex_id(&self, id_str: &str) -> bool {
2079        if id_str.is_empty() {
2080            return false;
2081        }
2082        let id = encode_message_id(id_str);
2083        self.contains_id(&id)
2084    }
2085
2086    /// Insert a message, maintaining sort order by timestamp.
2087    ///
2088    /// Returns true if the message was added, false if duplicate ID.
2089    ///
2090    /// **Performance**: append costs a binary search plus one index shift (ids are random, so
2091    /// the shift averages half the index); an out-of-order insert is O(n).
2092    pub fn insert(&mut self, msg: CompactMessage) -> bool {
2093        let Err(rank) = self.search(&msg.id) else { return false };
2094        reserve_slack(&mut self.messages, 1);
2095        reserve_slack(&mut self.id_index, 1);
2096
2097        // Fast path: append if message is newer than or equal to last (common case)
2098        if self.messages.last().is_none_or(|last| msg.at >= last.at) {
2099            self.id_index.insert(rank, self.messages.len() as u32);
2100            self.messages.push(msg);
2101            return true;
2102        }
2103
2104        // Slow path: out-of-order insert (rare for real-time chat)
2105        let msg_pos = match self.messages.binary_search_by(|m| m.at.cmp(&msg.at)) {
2106            Ok(pos) => pos,
2107            Err(pos) => pos,
2108        } as u32;
2109
2110        // Positions at or past the insert shift up; the id order is untouched - O(n)
2111        for pos in &mut self.id_index {
2112            if *pos >= msg_pos {
2113                *pos += 1;
2114            }
2115        }
2116        self.messages.insert(msg_pos as usize, msg);
2117        self.id_index.insert(rank, msg_pos);
2118        true
2119    }
2120
2121    /// Rebuild the ID index (call after bulk modifications)
2122    pub fn rebuild_index(&mut self) {
2123        let messages = &self.messages;
2124        let mut index: Vec<u32> = (0..messages.len() as u32).collect();
2125        index.sort_unstable_by(|&a, &b| messages[a as usize].id.cmp(&messages[b as usize].id).then(a.cmp(&b)));
2126        self.id_index = index;
2127    }
2128
2129    /// The positions in `range`, ordered by id.
2130    fn ranked(&self, range: std::ops::Range<usize>) -> Vec<u32> {
2131        let messages = &self.messages;
2132        let mut fresh: Vec<u32> = (range.start as u32..range.end as u32).collect();
2133        fresh.sort_unstable_by(|&a, &b| messages[a as usize].id.cmp(&messages[b as usize].id).then(a.cmp(&b)));
2134        fresh
2135    }
2136
2137    /// Merge id-ordered `fresh` positions into the index in O(n + k).
2138    fn merge_into_index(&mut self, fresh: Vec<u32>) {
2139        let messages = &self.messages;
2140        let id = |pos: u32| &messages[pos as usize].id;
2141        let old = std::mem::take(&mut self.id_index);
2142        let mut merged = Vec::with_capacity(old.len() + fresh.len());
2143        let (mut a, mut b) = (old.into_iter().peekable(), fresh.into_iter().peekable());
2144        loop {
2145            let take_old = match (a.peek(), b.peek()) {
2146                (Some(&o), Some(&n)) => id(o) < id(n),
2147                (Some(_), None) => true,
2148                (None, Some(_)) => false,
2149                (None, None) => break,
2150            };
2151            merged.extend(if take_old { a.next() } else { b.next() });
2152        }
2153        self.id_index = merged;
2154    }
2155
2156    /// Batch insert messages - optimized for different scenarios.
2157    ///
2158    /// Returns the number of messages actually added (excludes duplicates).
2159    ///
2160    /// **Performance**:
2161    /// - Append case (newer msgs): O(k log k + n)
2162    /// - Prepend case (older msgs): O(k log k + n)
2163    /// - Mixed: O(n log n) full sort
2164    pub fn insert_batch(&mut self, messages: impl IntoIterator<Item = CompactMessage>) -> usize {
2165        let messages: Vec<_> = messages.into_iter().collect();
2166        if messages.is_empty() {
2167            return 0;
2168        }
2169
2170        // Quick dedup check using the index
2171        let mut to_add: Vec<CompactMessage> = Vec::with_capacity(messages.len());
2172        for msg in messages {
2173            if !self.contains_id(&msg.id) {
2174                to_add.push(msg);
2175            }
2176        }
2177
2178        if to_add.is_empty() {
2179            return 0;
2180        }
2181
2182        let added = to_add.len();
2183
2184        // Determine the insertion strategy based on timestamps
2185        let our_first = self.messages.first().map(|m| m.at);
2186        let our_last = self.messages.last().map(|m| m.at);
2187        let their_min = to_add.iter().map(|m| m.at).min().unwrap();
2188        let their_max = to_add.iter().map(|m| m.at).max().unwrap();
2189
2190        if self.messages.is_empty() {
2191            // Empty vec - just add and sort
2192            self.messages = to_add;
2193            self.messages.sort_by_key(|m| m.at);
2194            self.rebuild_index();
2195        } else if their_min >= our_last.unwrap() {
2196            // All new messages are NEWER - append path (common for real-time + catch-up).
2197            // Appended positions are past every existing one, so none shifts.
2198            to_add.sort_by_key(|m| m.at);
2199            let base = self.messages.len();
2200            reserve_slack(&mut self.messages, to_add.len());
2201            self.messages.extend(to_add);
2202            let fresh = self.ranked(base..self.messages.len());
2203            self.merge_into_index(fresh);
2204        } else if their_max <= our_first.unwrap() {
2205            // All new messages are OLDER - prepend path (common for pagination)
2206            to_add.sort_by_key(|m| m.at);
2207            let prepend_count = to_add.len();
2208            for pos in &mut self.id_index {
2209                *pos += prepend_count as u32;
2210            }
2211            let mut joined = Vec::with_capacity(prepend_count + self.messages.len());
2212            joined.extend(to_add);
2213            joined.append(&mut self.messages);
2214            self.messages = joined;
2215            let fresh = self.ranked(0..prepend_count);
2216            self.merge_into_index(fresh);
2217        } else {
2218            // Mixed timestamps - fall back to full sort
2219            reserve_slack(&mut self.messages, to_add.len());
2220            self.messages.extend(to_add);
2221            self.messages.sort_by_key(|m| m.at);
2222            self.rebuild_index();
2223        }
2224
2225        added
2226    }
2227
2228    /// Heap held by the two vectors, at capacity (not what the messages own)
2229    pub fn memory_usage(&self) -> usize {
2230        self.messages.capacity() * std::mem::size_of::<CompactMessage>()
2231            + self.id_index.capacity() * std::mem::size_of::<u32>()
2232            // Note: doesn't include heap allocations inside CompactMessage
2233    }
2234
2235    /// Keep the newest `keep` messages plus any still pending (a pending send exists nowhere
2236    /// else until it lands), then hand the freed capacity back. Returns how many went.
2237    pub fn retain_newest(&mut self, keep: usize) -> usize {
2238        let n = self.messages.len();
2239        if n <= keep {
2240            return 0;
2241        }
2242        let cut = n - keep;
2243        let mut i = 0;
2244        self.messages.retain(|m| {
2245            let kept = i >= cut || m.is_pending();
2246            i += 1;
2247            kept
2248        });
2249        self.messages.shrink_to_fit();
2250        self.rebuild_index();
2251        n - self.messages.len()
2252    }
2253
2254    /// Drain messages from a range (rebuilds index after)
2255    pub fn drain(&mut self, range: std::ops::Range<usize>) -> std::vec::Drain<'_, CompactMessage> {
2256        let drain = self.messages.drain(range);
2257        // Note: caller should call rebuild_index() after consuming the drain
2258        drain
2259    }
2260
2261    /// Sort messages by a key (rebuilds index after)
2262    pub fn sort_by_key<K, F>(&mut self, f: F)
2263    where
2264        F: FnMut(&CompactMessage) -> K,
2265        K: Ord,
2266    {
2267        self.messages.sort_by_key(f);
2268        self.rebuild_index();
2269    }
2270
2271    /// Clear all messages, releasing both buffers
2272    pub fn clear(&mut self) {
2273        self.messages = Vec::new();
2274        self.id_index = Vec::new();
2275    }
2276}
2277
2278// ============================================================================
2279// Conversion from/to Message
2280// ============================================================================
2281
2282use crate::types::Message;
2283
2284impl CompactMessage {
2285    /// Convert from a regular Message (borrowed), interning npubs
2286    pub fn from_message(msg: &Message, interner: &mut NpubInterner) -> Self {
2287        Self::from_message_owned(
2288            Message {
2289                attachments: Vec::new(),
2290                reactions: Vec::new(),
2291                ..msg.clone()
2292            },
2293            interner,
2294        )
2295        .with_parts(
2296            msg.attachments.iter().map(CompactAttachment::from_attachment).collect(),
2297            msg.reactions.iter().map(|r| CompactReaction::from_reaction(r, interner)).collect(),
2298        )
2299    }
2300
2301    fn with_parts(mut self, attachments: TinyVec<CompactAttachment>, reactions: TinyVec<CompactReaction>) -> Self {
2302        self.attachments = attachments;
2303        self.reactions = reactions;
2304        self
2305    }
2306
2307    /// Convert from a regular Message (owned), moving its strings rather than copying them.
2308    pub fn from_message_owned(msg: Message, interner: &mut NpubInterner) -> Self {
2309        let reply = (!msg.replied_to.is_empty()).then(|| {
2310            Box::new(CompactReply {
2311                id: hex_to_bytes_32(&msg.replied_to),
2312                npub_idx: interner.intern_opt(msg.replied_to_npub.as_deref()),
2313                content: msg.replied_to_content.map(String::into_boxed_str),
2314                emoji_tags: msg.replied_to_emoji_tags.as_deref().map_or_else(TinyVec::new, |t| intern_emoji_tags(t, interner)),
2315            })
2316        });
2317        let history = msg.edit_history.unwrap_or_default();
2318        let tail_is_content = history.last().is_some_and(|e| e.content == msg.content);
2319        let tail = history.len().wrapping_sub(1);
2320        let extras = MessageExtras {
2321            edits: history
2322                .into_iter()
2323                .enumerate()
2324                .map(|(i, e)| CompactEdit {
2325                    content: if tail_is_content && i == tail { Box::default() } else { e.content.into_boxed_str() },
2326                    edited_at: e.edited_at,
2327                })
2328                .collect(),
2329            preview: msg.preview_metadata.as_ref().map_or_else(TinyVec::new, pack_preview),
2330            emoji_tags: intern_emoji_tags(&msg.emoji_tags, interner),
2331            addressed_bots: msg.addressed_bots.iter().map(|n| interner.intern(n)).collect(),
2332            spans: hold_spans(msg.text_spans),
2333            role_mentions: msg.role_mentions.iter().filter_map(|id| crate::simd::hex::hex_to_bytes_32_checked(id)).collect(),
2334            tail_is_content,
2335        };
2336        Self {
2337            id: encode_message_id(&msg.id),
2338            at: timestamp_to_compact(msg.at),
2339            content: msg.content.into_boxed_str(),
2340            attachments: msg.attachments.into_iter().map(CompactAttachment::from_attachment_owned).collect(),
2341            reactions: msg.reactions.into_iter().map(|r| CompactReaction::from_reaction_owned(r, interner)).collect(),
2342            reply,
2343            extras: (!extras.is_empty()).then(|| Box::new(extras)),
2344            expiration_secs: msg.expiration.map(|e| e as u32).unwrap_or(0),
2345            npub_idx: interner.intern_opt(msg.npub.as_deref()),
2346            flags: {
2347                let mut flags = MessageFlags::from_all(msg.mine, msg.pending, msg.failed, msg.replied_to_has_attachment);
2348                flags.set_writer(msg.writer);
2349                flags.set_unauthorized(msg.unauthorized);
2350                flags
2351            },
2352        }
2353    }
2354
2355    /// Convert back to a regular Message, resolving npubs and emoji from the interner
2356    pub fn to_message(&self, interner: &NpubInterner) -> Message {
2357        let id = self.id_hex();
2358        let reactions = self.reactions.iter().map(|r| r.to_reaction(&id, interner)).collect();
2359        let reply = self.reply.as_deref();
2360        let extras = self.extras.as_deref();
2361        Message {
2362            id,
2363            reactions,
2364            at: self.timestamp_ms(),
2365            expiration: if self.expiration_secs == 0 { None } else { Some(self.expiration_secs as u64) },
2366            mine: self.flags.is_mine(),
2367            pending: self.flags.is_pending(),
2368            failed: self.flags.is_failed(),
2369            edited: self.is_edited(),
2370            npub: interner.resolve(self.npub_idx).map(|s| s.to_string()),
2371            replied_to: self.replied_to_hex(),
2372            replied_to_content: reply.and_then(|r| r.content.as_deref()).map(str::to_string),
2373            replied_to_emoji_tags: reply.filter(|r| !r.emoji_tags.is_empty()).map(|r| resolve_emoji_tags(&r.emoji_tags, interner)),
2374            replied_to_npub: reply.and_then(|r| interner.resolve(r.npub_idx)).map(|s| s.to_string()),
2375            replied_to_has_attachment: self.flags.replied_to_has_attachment(),
2376            // Re-resolved per get_message_views / populate_reply_context; the compact
2377            // form keeps only the bool, so this stays None on the RAM path.
2378            replied_to_attachment_extension: None,
2379            // Never held in memory: every first save carries the original, and a re-save
2380            // keeps the stored link (`save_event` COALESCEs it).
2381            wrapper_event_id: None,
2382            content: self.content.to_string(),
2383            attachments: self.attachments.iter().map(|a| a.to_attachment()).collect(),
2384            edit_history: extras.filter(|x| !x.edits.is_empty()).map(|x| x.edit_history(&self.content)),
2385            preview_metadata: extras.and_then(|x| unpack_preview(x.preview.as_slice())),
2386            emoji_tags: extras.map(|x| resolve_emoji_tags(&x.emoji_tags, interner)).unwrap_or_default(),
2387            addressed_bots: extras
2388                .map(|x| x.addressed_bots.iter().filter_map(|&i| interner.resolve(i).map(|s| s.to_string())).collect())
2389                .unwrap_or_default(),
2390            text_spans: extras.map(|x| x.spans.iter().map(HeldSpan::to_span).collect()).unwrap_or_default(),
2391            role_mentions: extras
2392                .map(|x| x.role_mentions.iter().map(crate::simd::hex::bytes_to_hex_32).collect())
2393                .unwrap_or_default(),
2394            writer: self.flags.is_writer(),
2395            unauthorized: self.flags.is_unauthorized(),
2396        }
2397    }
2398}
2399
2400#[cfg(test)]
2401mod tests {
2402
2403    #[test]
2404    fn a_new_id_keeps_the_original_hash_and_path() {
2405        let ox = "ab".repeat(32);
2406        let att = crate::types::Attachment {
2407            id: ox.clone(),
2408            extension: "png".into(),
2409            path: "/elsewhere/file.png".into(),
2410            original_hash: Some(ox.clone()),
2411            ..Default::default()
2412        };
2413        let mut c = CompactAttachment::from_attachment(&att);
2414        c.set_id([0xcd; 32]);
2415        let back = c.to_attachment();
2416        assert_eq!(back.id, "cd".repeat(32));
2417        assert_eq!(back.original_hash.as_deref(), Some(ox.as_str()), "the original hash is not the new id");
2418        assert_eq!(back.path, "/elsewhere/file.png");
2419    }
2420    use super::*;
2421
2422    // A real event id that happens to start with the pending marker byte must
2423    // round-trip EXACTLY — the marker alone once misread 1 in 256 real ids as
2424    // phantom "pending-…" strings, wedging read markers among other consumers.
2425    #[test]
2426    fn real_id_starting_with_marker_byte_roundtrips() {
2427        let id = "01b95c05179c6d6abbc60b9a35198fdee6e0ce5b80a0b7ac8d465d81d038a73d";
2428        let encoded = encode_message_id(id);
2429        assert_eq!(decode_message_id(&encoded), id);
2430    }
2431
2432    #[test]
2433    fn pending_id_roundtrips() {
2434        let id = "pending-306878031314";
2435        let encoded = encode_message_id(id);
2436        assert_eq!(encoded[0], PENDING_ID_MARKER);
2437        assert_eq!(decode_message_id(&encoded), id);
2438    }
2439
2440    #[test]
2441    fn marker_byte_without_sentinel_decodes_as_hex() {
2442        // Marker byte + arbitrary tail (no sentinel) is a real id, not pending.
2443        let mut bytes = [0xABu8; 32];
2444        bytes[0] = PENDING_ID_MARKER;
2445        let decoded = decode_message_id(&bytes);
2446        assert!(!decoded.starts_with("pending-"));
2447        assert_eq!(decoded.len(), 64);
2448    }
2449
2450    #[test]
2451    fn test_message_flags() {
2452        let mut flags = MessageFlags::NONE;
2453        assert!(!flags.is_mine());
2454        assert!(!flags.is_pending());
2455        assert!(!flags.is_failed());
2456
2457        flags.set_mine(true);
2458        assert!(flags.is_mine());
2459
2460        flags.set_pending(true);
2461        assert!(flags.is_pending());
2462        assert!(flags.is_mine()); // Still set
2463
2464        flags.set_mine(false);
2465        assert!(!flags.is_mine());
2466        assert!(flags.is_pending()); // Still set
2467    }
2468
2469    #[test]
2470    fn test_npub_interner() {
2471        let mut interner = NpubInterner::new();
2472
2473        let idx1 = interner.intern("npub1alice");
2474        let idx2 = interner.intern("npub1bob");
2475        let idx3 = interner.intern("npub1alice"); // Duplicate
2476
2477        assert_eq!(idx1, idx3); // Same string = same index
2478        assert_ne!(idx1, idx2);
2479
2480        assert_eq!(interner.resolve(idx1), Some("npub1alice"));
2481        assert_eq!(interner.resolve(idx2), Some("npub1bob"));
2482        assert_eq!(interner.resolve(NO_NPUB), None);
2483    }
2484
2485    #[test]
2486    fn test_compact_message_vec_insert_and_find() {
2487        let mut vec = CompactMessageVec::new();
2488        let mut interner = NpubInterner::new();
2489
2490        let msg1 = CompactMessage {
2491            id: hex_to_bytes_32("0000000000000000000000000000000000000000000000000000000000000001"),
2492            at: 1000,
2493            expiration_secs: 0,
2494            flags: MessageFlags::NONE,
2495            npub_idx: interner.intern("npub1test"),
2496            content: "First message".to_string().into_boxed_str(),
2497            attachments: TinyVec::new(),
2498            reactions: TinyVec::new(),
2499            reply: None,
2500            extras: None,
2501        };
2502
2503        let msg2 = CompactMessage {
2504            id: hex_to_bytes_32("0000000000000000000000000000000000000000000000000000000000000002"),
2505            at: 2000,
2506            expiration_secs: 0,
2507            flags: MessageFlags::MINE,
2508            npub_idx: interner.intern("npub1me"),
2509            content: "Second message".to_string().into_boxed_str(),
2510            attachments: TinyVec::new(),
2511            reactions: TinyVec::new(),
2512            reply: None,
2513            extras: None,
2514        };
2515
2516        assert!(vec.insert(msg1));
2517        assert!(vec.insert(msg2));
2518        assert_eq!(vec.len(), 2);
2519
2520        // Find by ID
2521        let found = vec.find_by_hex_id("0000000000000000000000000000000000000000000000000000000000000001");
2522        assert!(found.is_some());
2523        assert_eq!(&*found.unwrap().content, "First message");
2524
2525        // Find non-existent
2526        let not_found = vec.find_by_hex_id("0000000000000000000000000000000000000000000000000000000000000099");
2527        assert!(not_found.is_none());
2528    }
2529
2530    #[test]
2531    fn test_duplicate_insert_rejected() {
2532        let mut vec = CompactMessageVec::new();
2533
2534        let msg = CompactMessage {
2535            id: hex_to_bytes_32("abcd000000000000000000000000000000000000000000000000000000000000"),
2536            at: 1000,
2537            expiration_secs: 0,
2538            flags: MessageFlags::NONE,
2539            npub_idx: NO_NPUB,
2540            content: "Test".to_string().into_boxed_str(),
2541            attachments: TinyVec::new(),
2542            reactions: TinyVec::new(),
2543            reply: None,
2544            extras: None,
2545        };
2546
2547        assert!(vec.insert(msg.clone()));
2548        assert!(!vec.insert(msg)); // Duplicate rejected
2549        assert_eq!(vec.len(), 1);
2550    }
2551
2552    // ========================================================================
2553    // Pending ID Encoding Tests
2554    // ========================================================================
2555
2556    #[test]
2557    fn pending_id_roundtrip_regular_hex() {
2558        let hex = "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789";
2559        let encoded = encode_message_id(hex);
2560        let decoded = decode_message_id(&encoded);
2561        assert_eq!(decoded, hex, "regular hex ID should roundtrip exactly");
2562    }
2563
2564    #[test]
2565    fn pending_id_roundtrip_pending() {
2566        let id = "pending-1234567890123456789";
2567        let encoded = encode_message_id(id);
2568        let decoded = decode_message_id(&encoded);
2569        assert_eq!(decoded, id, "pending ID should roundtrip exactly");
2570    }
2571
2572    #[test]
2573    fn pending_id_zero_timestamp() {
2574        let id = "pending-0";
2575        let encoded = encode_message_id(id);
2576        assert_eq!(encoded[0], PENDING_ID_MARKER, "first byte should be marker");
2577        let decoded = decode_message_id(&encoded);
2578        assert_eq!(decoded, id, "pending-0 should roundtrip");
2579    }
2580
2581    #[test]
2582    fn pending_id_max_u128_timestamp() {
2583        let max = u128::MAX;
2584        let id = format!("pending-{}", max);
2585        let encoded = encode_message_id(&id);
2586        let decoded = decode_message_id(&encoded);
2587        assert_eq!(decoded, id, "pending with max u128 should roundtrip");
2588    }
2589
2590    #[test]
2591    fn pending_id_all_zero_hex() {
2592        let hex = "0000000000000000000000000000000000000000000000000000000000000000";
2593        let encoded = encode_message_id(hex);
2594        let decoded = decode_message_id(&encoded);
2595        assert_eq!(decoded, hex, "all-zero hex ID should roundtrip");
2596        // All-zero should NOT be detected as pending since byte 0 is 0x00, not 0x01
2597        assert_ne!(encoded[0], PENDING_ID_MARKER);
2598    }
2599
2600    #[test]
2601    fn pending_id_all_ff_hex() {
2602        let hex = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
2603        let encoded = encode_message_id(hex);
2604        let decoded = decode_message_id(&encoded);
2605        assert_eq!(decoded, hex, "all-ff hex ID should roundtrip");
2606        assert_eq!(encoded, [0xff; 32], "all-ff should decode to all 0xff bytes");
2607    }
2608
2609    #[test]
2610    fn pending_id_mixed_case_hex() {
2611        let lower = "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789";
2612        let mixed = "ABCDEF0123456789abcdef0123456789ABCDEF0123456789abcdef0123456789";
2613        let encoded_lower = encode_message_id(lower);
2614        let encoded_mixed = encode_message_id(mixed);
2615        assert_eq!(encoded_lower, encoded_mixed, "mixed case should produce same bytes as lowercase");
2616    }
2617
2618    #[test]
2619    fn pending_id_short_hex_partial_decode() {
2620        // SIMD hex_to_bytes_32 partially decodes short input (decodes what it can)
2621        let short = "abcdef";
2622        let encoded = encode_message_id(short);
2623        // Short input is decoded as far as possible, remaining bytes are zero
2624        assert_eq!(encoded[0..14], [0u8; 14], "leading bytes should be zero for short input");
2625    }
2626
2627    #[test]
2628    fn pending_id_marker_distinguishes_from_real_id() {
2629        // A real event ID starting with 0x01 must NOT be confused with pending:
2630        // 1 in 256 real ids begin with the marker byte, and misreading them
2631        // mangled read markers into phantom "pending-…" strings. Only the
2632        // marker + sentinel combination reads as pending.
2633        let hex = "0100000000000000000000000000000000000000000000000000000000000000";
2634        let encoded = encode_message_id(hex);
2635        let decoded = decode_message_id(&encoded);
2636        assert_eq!(decoded, hex, "marker-leading real id must roundtrip exactly");
2637    }
2638
2639    #[test]
2640    fn pending_id_large_timestamp() {
2641        let id = "pending-99999999999999999";
2642        let encoded = encode_message_id(&id);
2643        let decoded = decode_message_id(&encoded);
2644        assert_eq!(decoded, id, "large but valid timestamp should roundtrip");
2645    }
2646
2647    #[test]
2648    fn pending_id_invalid_timestamp_becomes_zero() {
2649        // If the timestamp part can't be parsed, it stays as all-zeros in bytes 1..17
2650        let id = "pending-notanumber";
2651        let encoded = encode_message_id(id);
2652        assert_eq!(encoded[0], PENDING_ID_MARKER);
2653        // Bytes 1..17 should all be 0
2654        assert_eq!(&encoded[1..17], &[0u8; 16]);
2655        let decoded = decode_message_id(&encoded);
2656        assert_eq!(decoded, "pending-0", "invalid timestamp parses as pending-0");
2657    }
2658
2659    // ========================================================================
2660    // Timestamp Tests
2661    // ========================================================================
2662
2663    #[test]
2664    fn timestamp_to_compact_and_back_roundtrip() {
2665        // A representative timestamp: 2024-01-15 12:00:00 UTC in milliseconds
2666        let ms: u64 = 1705320000000;
2667        let compact = timestamp_to_compact(ms);
2668        let restored = timestamp_from_compact(compact);
2669        // The sub-second part is lost (ms -> seconds -> ms), so restored is floored to seconds
2670        assert_eq!(restored / 1000, ms / 1000, "roundtrip should preserve seconds");
2671    }
2672
2673    #[test]
2674    fn secs_to_compact_and_back_roundtrip() {
2675        let secs: u64 = 1705320000; // 2024-01-15 12:00:00 UTC
2676        let compact = secs_to_compact(secs);
2677        let restored = secs_from_compact(compact);
2678        assert_eq!(restored, secs, "secs should roundtrip exactly");
2679    }
2680
2681    #[test]
2682    fn timestamp_zero_preservation() {
2683        // Zero is a sentinel for "never set" in secs_to_compact/secs_from_compact
2684        assert_eq!(secs_to_compact(0), 0, "zero secs should produce zero compact");
2685        assert_eq!(secs_from_compact(0), 0, "zero compact should produce zero secs");
2686    }
2687
2688    #[test]
2689    fn timestamp_epoch_boundary() {
2690        // Exactly 2020-01-01 00:00:00 UTC = EPOCH_2020_SECS
2691        let epoch_secs: u64 = 1577836800;
2692        let compact = secs_to_compact(epoch_secs);
2693        assert_eq!(compact, 0, "epoch boundary should map to compact 0");
2694        let restored = secs_from_compact(compact);
2695        // secs_from_compact(0) returns 0 (sentinel), not epoch
2696        assert_eq!(restored, 0, "compact 0 returns sentinel 0");
2697    }
2698
2699    #[test]
2700    fn timestamp_epoch_boundary_ms() {
2701        let epoch_ms: u64 = 1577836800000;
2702        let compact = timestamp_to_compact(epoch_ms);
2703        assert_eq!(compact, epoch_ms, "full u64 — identity function");
2704        let restored = timestamp_from_compact(compact);
2705        assert_eq!(restored, epoch_ms, "roundtrip preserves value");
2706    }
2707
2708    #[test]
2709    fn timestamp_current_time_roundtrip() {
2710        // Simulate a current-ish timestamp: 2026-03-27 in seconds
2711        let secs: u64 = 1774800000;
2712        let compact = secs_to_compact(secs);
2713        let restored = secs_from_compact(compact);
2714        assert_eq!(restored, secs, "current-era timestamp should roundtrip");
2715        assert!(compact > 0, "current time should be past epoch");
2716    }
2717
2718    #[test]
2719    fn timestamp_far_future_year_2100() {
2720        // 2100-01-01 00:00:00 UTC
2721        let secs: u64 = 4102444800;
2722        let compact = secs_to_compact(secs);
2723        let restored = secs_from_compact(compact);
2724        assert_eq!(restored, secs, "year 2100 should roundtrip");
2725        // Verify it fits in u32
2726        assert!(compact <= u32::MAX, "year 2100 should fit in u32");
2727    }
2728
2729    #[test]
2730    fn timestamp_pre_epoch_saturates_to_zero() {
2731        // A timestamp before 2020 epoch
2732        let secs: u64 = 1500000000; // ~2017
2733        let compact = secs_to_compact(secs);
2734        // saturating_sub means this becomes 0
2735        assert_eq!(compact, 0, "pre-epoch timestamp should saturate to 0");
2736    }
2737
2738    #[test]
2739    fn timestamp_ms_sub_second_precision_preserved() {
2740        let ms: u64 = 1705320000999;
2741        let compact = timestamp_to_compact(ms);
2742        let restored = timestamp_from_compact(compact);
2743        assert_eq!(restored, ms, "sub-second ms must be preserved");
2744    }
2745
2746    #[test]
2747    fn timestamp_one_second_after_epoch() {
2748        let secs: u64 = 1577836801; // one second after epoch
2749        let compact = secs_to_compact(secs);
2750        assert_eq!(compact, 1, "one second after epoch should be compact 1");
2751        let restored = secs_from_compact(compact);
2752        assert_eq!(restored, secs, "should restore to original");
2753    }
2754
2755    // ========================================================================
2756    // MessageFlags Tests
2757    // ========================================================================
2758
2759    #[test]
2760    fn message_flags_mine_independent() {
2761        let mut flags = MessageFlags::NONE;
2762        flags.set_mine(true);
2763        assert!(flags.is_mine(), "mine should be set");
2764        assert!(!flags.is_pending(), "pending should not be set");
2765        assert!(!flags.is_failed(), "failed should not be set");
2766    }
2767
2768    #[test]
2769    fn message_flags_pending_independent() {
2770        let mut flags = MessageFlags::NONE;
2771        flags.set_pending(true);
2772        assert!(!flags.is_mine(), "mine should not be set");
2773        assert!(flags.is_pending(), "pending should be set");
2774        assert!(!flags.is_failed(), "failed should not be set");
2775    }
2776
2777    #[test]
2778    fn message_flags_failed_independent() {
2779        let mut flags = MessageFlags::NONE;
2780        flags.set_failed(true);
2781        assert!(!flags.is_mine(), "mine should not be set");
2782        assert!(!flags.is_pending(), "pending should not be set");
2783        assert!(flags.is_failed(), "failed should be set");
2784    }
2785
2786    #[test]
2787    fn message_flags_from_bools_all_false() {
2788        let flags = MessageFlags::from_bools(false, false, false);
2789        assert!(!flags.is_mine());
2790        assert!(!flags.is_pending());
2791        assert!(!flags.is_failed());
2792        assert_eq!(flags, MessageFlags::NONE, "all false should equal NONE");
2793    }
2794
2795    #[test]
2796    fn message_flags_from_bools_all_true() {
2797        let flags = MessageFlags::from_bools(true, true, true);
2798        assert!(flags.is_mine(), "mine should be set");
2799        assert!(flags.is_pending(), "pending should be set");
2800        assert!(flags.is_failed(), "failed should be set");
2801    }
2802
2803    #[test]
2804    fn message_flags_from_bools_various_combos() {
2805        let flags = MessageFlags::from_bools(true, false, true);
2806        assert!(flags.is_mine());
2807        assert!(!flags.is_pending());
2808        assert!(flags.is_failed());
2809
2810        let flags = MessageFlags::from_bools(false, true, false);
2811        assert!(!flags.is_mine());
2812        assert!(flags.is_pending());
2813        assert!(!flags.is_failed());
2814    }
2815
2816    #[test]
2817    fn message_flags_from_all_replied_to_none() {
2818        let flags = MessageFlags::from_all(false, false, false, None);
2819        assert_eq!(flags.replied_to_has_attachment(), None, "None should roundtrip");
2820    }
2821
2822    #[test]
2823    fn message_flags_from_all_replied_to_some_false() {
2824        let flags = MessageFlags::from_all(false, false, false, Some(false));
2825        assert_eq!(flags.replied_to_has_attachment(), Some(false), "Some(false) should roundtrip");
2826    }
2827
2828    #[test]
2829    fn message_flags_from_all_replied_to_some_true() {
2830        let flags = MessageFlags::from_all(false, false, false, Some(true));
2831        assert_eq!(flags.replied_to_has_attachment(), Some(true), "Some(true) should roundtrip");
2832    }
2833
2834    #[test]
2835    fn message_flags_multiple_set_simultaneously() {
2836        let flags = MessageFlags::from_all(true, true, false, Some(true));
2837        assert!(flags.is_mine());
2838        assert!(flags.is_pending());
2839        assert!(!flags.is_failed());
2840        assert_eq!(flags.replied_to_has_attachment(), Some(true));
2841    }
2842
2843    #[test]
2844    fn message_flags_default_is_all_false() {
2845        let flags = MessageFlags::default();
2846        assert!(!flags.is_mine());
2847        assert!(!flags.is_pending());
2848        assert!(!flags.is_failed());
2849        assert_eq!(flags.replied_to_has_attachment(), None);
2850        assert_eq!(flags, MessageFlags::NONE);
2851    }
2852
2853    #[test]
2854    fn message_flags_bit_patterns_correct() {
2855        assert_eq!(MessageFlags::MINE.0, 0b00001, "MINE bit pattern");
2856        assert_eq!(MessageFlags::PENDING.0, 0b00010, "PENDING bit pattern");
2857        assert_eq!(MessageFlags::FAILED.0, 0b00100, "FAILED bit pattern");
2858    }
2859
2860    #[test]
2861    fn message_flags_set_then_clear() {
2862        let mut flags = MessageFlags::from_bools(true, true, true);
2863        flags.set_mine(false);
2864        assert!(!flags.is_mine(), "mine should be cleared");
2865        assert!(flags.is_pending(), "pending should remain set");
2866        assert!(flags.is_failed(), "failed should remain set");
2867    }
2868
2869    #[test]
2870    fn message_flags_replied_to_overwrite() {
2871        let mut flags = MessageFlags::from_all(false, false, false, Some(true));
2872        assert_eq!(flags.replied_to_has_attachment(), Some(true));
2873        flags.set_replied_to_has_attachment(Some(false));
2874        assert_eq!(flags.replied_to_has_attachment(), Some(false), "overwrite should work");
2875        flags.set_replied_to_has_attachment(None);
2876        assert_eq!(flags.replied_to_has_attachment(), None, "clearing to None should work");
2877    }
2878
2879    #[test]
2880    fn message_flags_replied_to_does_not_interfere_with_other_bits() {
2881        let mut flags = MessageFlags::from_bools(true, true, true);
2882        flags.set_replied_to_has_attachment(Some(true));
2883        assert!(flags.is_mine(), "mine should still be set");
2884        assert!(flags.is_pending(), "pending should still be set");
2885        assert!(flags.is_failed(), "failed should still be set");
2886        assert_eq!(flags.replied_to_has_attachment(), Some(true));
2887    }
2888
2889    // ========================================================================
2890    // AttachmentFlags Tests
2891    // ========================================================================
2892
2893    #[test]
2894    fn attachment_flags_downloading_independent() {
2895        let mut flags = AttachmentFlags::NONE;
2896        flags.set_downloading(true);
2897        assert!(flags.is_downloading());
2898        assert!(!flags.is_downloaded());
2899        assert!(!flags.is_short_nonce());
2900    }
2901
2902    #[test]
2903    fn attachment_flags_downloaded_independent() {
2904        let mut flags = AttachmentFlags::NONE;
2905        flags.set_downloaded(true);
2906        assert!(!flags.is_downloading());
2907        assert!(flags.is_downloaded());
2908        assert!(!flags.is_short_nonce());
2909    }
2910
2911    #[test]
2912    fn attachment_flags_short_nonce_independent() {
2913        let mut flags = AttachmentFlags::NONE;
2914        flags.set_short_nonce(true);
2915        assert!(!flags.is_downloading());
2916        assert!(!flags.is_downloaded());
2917        assert!(flags.is_short_nonce());
2918    }
2919
2920    #[test]
2921    fn attachment_flags_from_bools() {
2922        let flags = AttachmentFlags::from_bools(true, false);
2923        assert!(flags.is_downloading());
2924        assert!(!flags.is_downloaded());
2925
2926        let flags = AttachmentFlags::from_bools(false, true);
2927        assert!(!flags.is_downloading());
2928        assert!(flags.is_downloaded());
2929    }
2930
2931    #[test]
2932    fn attachment_flags_all_set() {
2933        let mut flags = AttachmentFlags::NONE;
2934        flags.set_downloading(true);
2935        flags.set_downloaded(true);
2936        flags.set_short_nonce(true);
2937        assert!(flags.is_downloading());
2938        assert!(flags.is_downloaded());
2939        assert!(flags.is_short_nonce());
2940    }
2941
2942    #[test]
2943    fn attachment_flags_set_then_clear() {
2944        let mut flags = AttachmentFlags::NONE;
2945        flags.set_downloading(true);
2946        flags.set_downloaded(true);
2947        flags.set_downloading(false);
2948        assert!(!flags.is_downloading(), "downloading should be cleared");
2949        assert!(flags.is_downloaded(), "downloaded should remain set");
2950    }
2951
2952    #[test]
2953    fn attachment_flags_default_none() {
2954        let flags = AttachmentFlags::NONE;
2955        assert!(!flags.is_downloading());
2956        assert!(!flags.is_downloaded());
2957        assert!(!flags.is_short_nonce());
2958        assert_eq!(flags, AttachmentFlags::default());
2959    }
2960
2961    #[test]
2962    fn attachment_flags_bit_values() {
2963        // Verify the bit constants are distinct
2964        let mut flags = AttachmentFlags::NONE;
2965        flags.set_downloading(true);
2966        assert_eq!(flags.0, 0b0001);
2967
2968        let mut flags = AttachmentFlags::NONE;
2969        flags.set_downloaded(true);
2970        assert_eq!(flags.0, 0b0010);
2971
2972        let mut flags = AttachmentFlags::NONE;
2973        flags.set_short_nonce(true);
2974        assert_eq!(flags.0, 0b0100);
2975    }
2976
2977    // ========================================================================
2978    // NpubInterner Tests
2979    // ========================================================================
2980
2981    #[test]
2982    fn interner_returns_incrementing_handles() {
2983        let mut interner = NpubInterner::new();
2984        let h0 = interner.intern("npub1aaa");
2985        let h1 = interner.intern("npub1bbb");
2986        let h2 = interner.intern("npub1ccc");
2987        assert_eq!(h0, 0, "first intern should be handle 0");
2988        assert_eq!(h1, 1, "second intern should be handle 1");
2989        assert_eq!(h2, 2, "third intern should be handle 2");
2990    }
2991
2992    #[test]
2993    fn interner_lookup_finds_interned() {
2994        let mut interner = NpubInterner::new();
2995        let h = interner.intern("npub1alice");
2996        let found = interner.lookup("npub1alice");
2997        assert_eq!(found, Some(h), "lookup should find interned string");
2998    }
2999
3000    #[test]
3001    fn interner_lookup_returns_none_for_unknown() {
3002        let interner = NpubInterner::new();
3003        assert_eq!(interner.lookup("npub1unknown"), None, "lookup on empty interner should be None");
3004    }
3005
3006    #[test]
3007    fn interner_lookup_returns_none_for_not_interned() {
3008        let mut interner = NpubInterner::new();
3009        interner.intern("npub1alice");
3010        assert_eq!(interner.lookup("npub1bob"), None, "lookup for non-interned should be None");
3011    }
3012
3013    #[test]
3014    fn interner_resolve_returns_string() {
3015        let mut interner = NpubInterner::new();
3016        let h = interner.intern("npub1test123");
3017        assert_eq!(interner.resolve(h), Some("npub1test123"), "resolve should return the original string");
3018    }
3019
3020    #[test]
3021    fn interner_resolve_returns_none_for_no_npub() {
3022        let interner = NpubInterner::new();
3023        assert_eq!(interner.resolve(NO_NPUB), None, "resolve(NO_NPUB) should be None");
3024    }
3025
3026    #[test]
3027    fn interner_resolve_returns_none_for_out_of_bounds() {
3028        let mut interner = NpubInterner::new();
3029        interner.intern("npub1only");
3030        assert_eq!(interner.resolve(999), None, "out-of-bounds handle should resolve to None");
3031    }
3032
3033    #[test]
3034    fn interner_duplicate_returns_same_handle() {
3035        let mut interner = NpubInterner::new();
3036        let h1 = interner.intern("npub1dup");
3037        let h2 = interner.intern("npub1dup");
3038        let h3 = interner.intern("npub1dup");
3039        assert_eq!(h1, h2, "duplicate intern should return same handle");
3040        assert_eq!(h2, h3, "duplicate intern should return same handle");
3041        assert_eq!(interner.len(), 1, "duplicates should not increase length");
3042    }
3043
3044    #[test]
3045    fn interner_100_unique_npubs_stress() {
3046        let mut interner = NpubInterner::new();
3047        let mut handles = Vec::new();
3048
3049        for i in 0..100 {
3050            let npub = format!("npub1stress{:04}", i);
3051            let h = interner.intern(&npub);
3052            handles.push((h, npub));
3053        }
3054
3055        assert_eq!(interner.len(), 100, "should have 100 unique npubs");
3056
3057        // Verify all handles resolve correctly
3058        for (h, npub) in &handles {
3059            assert_eq!(interner.resolve(*h), Some(npub.as_str()),
3060                "handle {} should resolve to {}", h, npub);
3061        }
3062
3063        // Verify all lookups work
3064        for (h, npub) in &handles {
3065            assert_eq!(interner.lookup(npub), Some(*h),
3066                "lookup for {} should return handle {}", npub, h);
3067        }
3068
3069        // Re-interning should return same handles
3070        for (h, npub) in &handles {
3071            assert_eq!(interner.intern(npub), *h,
3072                "re-interning {} should return same handle {}", npub, h);
3073        }
3074        assert_eq!(interner.len(), 100, "re-interning should not grow interner");
3075    }
3076
3077    #[test]
3078    fn interner_memory_usage_reasonable() {
3079        let mut interner = NpubInterner::new();
3080        for i in 0..50 {
3081            interner.intern(&format!("npub1{:0>62}", i));
3082        }
3083        let mem = interner.memory_usage();
3084        // Should be in the ballpark of 50 * (64 bytes string + overhead)
3085        assert!(mem > 0, "memory usage should be positive");
3086        assert!(mem < 100_000, "memory usage for 50 npubs should be under 100KB, was {}", mem);
3087    }
3088
3089    #[test]
3090    fn interner_empty() {
3091        let interner = NpubInterner::new();
3092        assert_eq!(interner.len(), 0);
3093        assert!(interner.is_empty());
3094        assert_eq!(interner.resolve(0), None);
3095        assert_eq!(interner.lookup("anything"), None);
3096        assert!(interner.memory_usage() > 0, "even empty interner has struct overhead");
3097    }
3098
3099    #[test]
3100    fn interner_intern_opt_none() {
3101        let mut interner = NpubInterner::new();
3102        let h = interner.intern_opt(None);
3103        assert_eq!(h, NO_NPUB, "intern_opt(None) should return NO_NPUB");
3104        assert_eq!(interner.len(), 0, "None should not add to interner");
3105    }
3106
3107    #[test]
3108    fn interner_intern_opt_empty_string() {
3109        let mut interner = NpubInterner::new();
3110        let h = interner.intern_opt(Some(""));
3111        assert_eq!(h, NO_NPUB, "intern_opt(Some('')) should return NO_NPUB");
3112    }
3113
3114    #[test]
3115    fn interner_intern_opt_some_value() {
3116        let mut interner = NpubInterner::new();
3117        let h = interner.intern_opt(Some("npub1real"));
3118        assert_ne!(h, NO_NPUB, "intern_opt(Some(value)) should not return NO_NPUB");
3119        assert_eq!(interner.resolve(h), Some("npub1real"));
3120    }
3121
3122    // ========================================================================
3123    // CompactMessageVec Tests
3124    // ========================================================================
3125
3126    /// Helper to create a minimal CompactMessage with given hex ID and timestamp
3127    fn make_compact_msg(hex_id: &str, timestamp: u64) -> CompactMessage {
3128        CompactMessage {
3129            id: encode_message_id(hex_id),
3130            at: timestamp,
3131            expiration_secs: 0,
3132            flags: MessageFlags::NONE,
3133            npub_idx: NO_NPUB,
3134            content: "test".into(),
3135            attachments: TinyVec::new(),
3136            reactions: TinyVec::new(),
3137            reply: None,
3138            extras: None,
3139        }
3140    }
3141
3142    #[test]
3143    fn compact_vec_insert_single_message() {
3144        let mut vec = CompactMessageVec::new();
3145        let msg = make_compact_msg(
3146            "1111111111111111111111111111111111111111111111111111111111111111",
3147            100,
3148        );
3149        assert!(vec.insert(msg), "insert should succeed");
3150        assert_eq!(vec.len(), 1);
3151        assert!(!vec.is_empty());
3152    }
3153
3154    #[test]
3155    fn compact_vec_insert_duplicate_rejected() {
3156        let mut vec = CompactMessageVec::new();
3157        let id = "2222222222222222222222222222222222222222222222222222222222222222";
3158        let msg1 = make_compact_msg(id, 100);
3159        let msg2 = make_compact_msg(id, 200); // same ID, different timestamp
3160        assert!(vec.insert(msg1), "first insert should succeed");
3161        assert!(!vec.insert(msg2), "duplicate ID should be rejected");
3162        assert_eq!(vec.len(), 1);
3163    }
3164
3165    #[test]
3166    fn compact_vec_insert_batch_multiple() {
3167        let mut vec = CompactMessageVec::new();
3168        let msgs = vec![
3169            make_compact_msg("aa00000000000000000000000000000000000000000000000000000000000000", 100),
3170            make_compact_msg("bb00000000000000000000000000000000000000000000000000000000000000", 200),
3171            make_compact_msg("cc00000000000000000000000000000000000000000000000000000000000000", 300),
3172        ];
3173        let added = vec.insert_batch(msgs);
3174        assert_eq!(added, 3, "all 3 should be added");
3175        assert_eq!(vec.len(), 3);
3176    }
3177
3178    #[test]
3179    fn compact_vec_append_batch_merge_keeps_index_consistent() {
3180        // Seed older messages, then append a large batch of NEWER ones — exercises the
3181        // O(n+k) append-merge index build. Every id must stay findable (proves the merged
3182        // id_index is complete + sorted) and dedup must still work off it.
3183        let mut vec = CompactMessageVec::new();
3184        let mk = |n: u32, at: u64| make_compact_msg(&format!("{:064x}", n), at);
3185        let seed: Vec<_> = (0..50).map(|n| mk(n, n as u64)).collect();
3186        assert_eq!(vec.insert_batch(seed), 50);
3187        let batch: Vec<_> = (1000..1200).map(|n| mk(n, n as u64)).collect();
3188        assert_eq!(vec.insert_batch(batch), 200, "all newer messages appended");
3189        assert_eq!(vec.len(), 250);
3190        for n in (0..50).chain(1000..1200) {
3191            assert!(vec.find_by_hex_id(&format!("{:064x}", n)).is_some(), "id {n} must be findable via the merged index");
3192        }
3193        assert!(vec.find_by_hex_id(&format!("{:064x}", 9999u32)).is_none(), "never-inserted id must not be found");
3194        let dup: Vec<_> = (1000..1200).map(|n| mk(n, n as u64)).collect();
3195        assert_eq!(vec.insert_batch(dup), 0, "re-appended batch fully deduped via the merged index");
3196    }
3197
3198    #[test]
3199    fn compact_vec_insert_batch_dedup() {
3200        let mut vec = CompactMessageVec::new();
3201        let id = "dd00000000000000000000000000000000000000000000000000000000000000";
3202        vec.insert(make_compact_msg(id, 100));
3203
3204        let msgs = vec![
3205            make_compact_msg(id, 200), // duplicate
3206            make_compact_msg("ee00000000000000000000000000000000000000000000000000000000000000", 300),
3207        ];
3208        let added = vec.insert_batch(msgs);
3209        assert_eq!(added, 1, "only non-duplicate should be added");
3210        assert_eq!(vec.len(), 2);
3211    }
3212
3213    #[test]
3214    fn compact_vec_find_by_hex_id() {
3215        let mut vec = CompactMessageVec::new();
3216        let id = "ff00000000000000000000000000000000000000000000000000000000000001";
3217        let mut msg = make_compact_msg(id, 500);
3218        msg.content = "found me".into();
3219        vec.insert(msg);
3220
3221        let found = vec.find_by_hex_id(id);
3222        assert!(found.is_some(), "should find by hex id");
3223        assert_eq!(&*found.unwrap().content, "found me");
3224    }
3225
3226    #[test]
3227    fn compact_vec_find_by_hex_id_not_found() {
3228        let mut vec = CompactMessageVec::new();
3229        vec.insert(make_compact_msg(
3230            "aa00000000000000000000000000000000000000000000000000000000000000", 100,
3231        ));
3232        let found = vec.find_by_hex_id(
3233            "bb00000000000000000000000000000000000000000000000000000000000000",
3234        );
3235        assert!(found.is_none(), "should not find non-existent ID");
3236    }
3237
3238    #[test]
3239    fn compact_vec_find_by_hex_id_empty_string() {
3240        let mut vec = CompactMessageVec::new();
3241        vec.insert(make_compact_msg(
3242            "aa00000000000000000000000000000000000000000000000000000000000000", 100,
3243        ));
3244        assert!(vec.find_by_hex_id("").is_none(), "empty string should return None");
3245    }
3246
3247    #[test]
3248    fn compact_vec_find_by_hex_id_mut() {
3249        let mut vec = CompactMessageVec::new();
3250        let id = "ff00000000000000000000000000000000000000000000000000000000000002";
3251        vec.insert(make_compact_msg(id, 500));
3252
3253        let found = vec.find_by_hex_id_mut(id);
3254        assert!(found.is_some(), "should find mutable ref by hex id");
3255        found.unwrap().content = "modified".into();
3256
3257        // Verify modification stuck
3258        let found = vec.find_by_hex_id(id);
3259        assert_eq!(&*found.unwrap().content, "modified");
3260    }
3261
3262    #[test]
3263    fn compact_vec_contains_hex_id() {
3264        let mut vec = CompactMessageVec::new();
3265        let id = "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef";
3266        vec.insert(make_compact_msg(id, 100));
3267
3268        assert!(vec.contains_hex_id(id), "should contain inserted ID");
3269        assert!(!vec.contains_hex_id(
3270            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"),
3271            "should not contain non-inserted ID");
3272        assert!(!vec.contains_hex_id(""), "empty string should not match");
3273    }
3274
3275    #[test]
3276    fn compact_vec_remove_by_hex_id() {
3277        let mut vec = CompactMessageVec::new();
3278        let id1 = "1100000000000000000000000000000000000000000000000000000000000000";
3279        let id2 = "2200000000000000000000000000000000000000000000000000000000000000";
3280        vec.insert(make_compact_msg(id1, 100));
3281        vec.insert(make_compact_msg(id2, 200));
3282        assert_eq!(vec.len(), 2);
3283
3284        assert!(vec.remove_by_hex_id(id1), "remove should succeed");
3285        assert_eq!(vec.len(), 1);
3286        assert!(!vec.contains_hex_id(id1), "removed ID should not be found");
3287        assert!(vec.contains_hex_id(id2), "remaining ID should still be found");
3288    }
3289
3290    #[test]
3291    fn compact_vec_remove_nonexistent() {
3292        let mut vec = CompactMessageVec::new();
3293        vec.insert(make_compact_msg(
3294            "1100000000000000000000000000000000000000000000000000000000000000", 100,
3295        ));
3296        assert!(!vec.remove_by_hex_id(
3297            "9900000000000000000000000000000000000000000000000000000000000000"),
3298            "removing non-existent should return false");
3299        assert!(!vec.remove_by_hex_id(""), "removing empty should return false");
3300        assert_eq!(vec.len(), 1);
3301    }
3302
3303    #[test]
3304    fn compact_vec_last_timestamp() {
3305        let mut vec = CompactMessageVec::new();
3306        assert_eq!(vec.last_timestamp(), None, "empty vec should have no last timestamp");
3307
3308        vec.insert(make_compact_msg(
3309            "aa00000000000000000000000000000000000000000000000000000000000000", 100,
3310        ));
3311        vec.insert(make_compact_msg(
3312            "bb00000000000000000000000000000000000000000000000000000000000000", 300,
3313        ));
3314        vec.insert(make_compact_msg(
3315            "cc00000000000000000000000000000000000000000000000000000000000000", 200,
3316        ));
3317
3318        let last_ts = vec.last_timestamp().unwrap();
3319        // Messages are sorted by timestamp, so last should be the one with at=300
3320        let expected = timestamp_from_compact(300);
3321        assert_eq!(last_ts, expected, "last timestamp should be the largest");
3322    }
3323
3324    #[test]
3325    fn compact_vec_empty_operations() {
3326        let vec = CompactMessageVec::new();
3327        assert!(vec.is_empty());
3328        assert_eq!(vec.len(), 0);
3329        assert!(vec.last().is_none());
3330        assert!(vec.first().is_none());
3331        assert!(vec.last_timestamp().is_none());
3332        assert!(!vec.contains_hex_id("anything"));
3333        assert!(vec.find_by_hex_id("anything").is_none());
3334    }
3335
3336    #[test]
3337    fn compact_vec_1000_message_stress() {
3338        let mut vec = CompactMessageVec::new();
3339
3340        // Insert 1000 messages
3341        for i in 0..1000u64 {
3342            let id = format!("{:0>64x}", i);
3343            let msg = make_compact_msg(&id, i * 10);
3344            assert!(vec.insert(msg), "insert {} should succeed", i);
3345        }
3346        assert_eq!(vec.len(), 1000);
3347
3348        // Verify every message can be found
3349        for i in 0..1000u64 {
3350            let id = format!("{:0>64x}", i);
3351            assert!(vec.contains_hex_id(&id), "should find message {}", i);
3352            let found = vec.find_by_hex_id(&id).unwrap();
3353            assert_eq!(found.at, i * 10, "timestamp should match for message {}", i);
3354        }
3355
3356        // Verify non-existent IDs are not found
3357        for i in 1000..1010u64 {
3358            let id = format!("{:0>64x}", i);
3359            assert!(!vec.contains_hex_id(&id), "should not find non-existent {}", i);
3360        }
3361
3362        // Messages should be in timestamp order
3363        let timestamps: Vec<u64> = vec.iter().map(|m| m.at).collect();
3364        for w in timestamps.windows(2) {
3365            assert!(w[0] <= w[1], "messages should be sorted by timestamp: {} <= {}", w[0], w[1]);
3366        }
3367    }
3368
3369    #[test]
3370    fn compact_vec_rebuild_index_after_id_change() {
3371        let mut vec = CompactMessageVec::new();
3372        let old_id = "aa00000000000000000000000000000000000000000000000000000000000000";
3373        let new_id = "ff00000000000000000000000000000000000000000000000000000000000000";
3374        let others = ["bb00000000000000000000000000000000000000000000000000000000000000", "cc00000000000000000000000000000000000000000000000000000000000000"];
3375        vec.insert(make_compact_msg(old_id, 100));
3376        vec.insert(make_compact_msg(others[0], 200));
3377        vec.insert(make_compact_msg(others[1], 300));
3378
3379        // Mutate the message's ID directly (simulating an ID update like pending -> confirmed):
3380        // it now sorts last but sits first in the index until a rebuild.
3381        vec.messages_mut()[0].id = encode_message_id(new_id);
3382
3383        // Rebuild index
3384        vec.rebuild_index();
3385        assert!(vec.contains_hex_id(new_id), "after rebuild, new ID should be found");
3386        assert!(!vec.contains_hex_id(old_id), "after rebuild, old ID should not be found");
3387        assert!(others.iter().all(|id| vec.contains_hex_id(id)), "the untouched ids still resolve");
3388    }
3389
3390    #[test]
3391    fn compact_vec_pending_id_lookup() {
3392        let mut vec = CompactMessageVec::new();
3393        let pending = "pending-9876543210";
3394        vec.insert(make_compact_msg(pending, 500));
3395
3396        assert!(vec.contains_hex_id(pending), "should find pending ID");
3397        let found = vec.find_by_hex_id(pending);
3398        assert!(found.is_some(), "should find pending message");
3399        assert_eq!(found.unwrap().id_hex(), pending, "id_hex should match pending string");
3400    }
3401
3402    #[test]
3403    fn compact_vec_out_of_order_insert() {
3404        let mut vec = CompactMessageVec::new();
3405        // Insert messages out of timestamp order
3406        vec.insert(make_compact_msg(
3407            "bb00000000000000000000000000000000000000000000000000000000000000", 300,
3408        ));
3409        vec.insert(make_compact_msg(
3410            "aa00000000000000000000000000000000000000000000000000000000000000", 100,
3411        ));
3412        vec.insert(make_compact_msg(
3413            "cc00000000000000000000000000000000000000000000000000000000000000", 200,
3414        ));
3415
3416        assert_eq!(vec.len(), 3);
3417        // Verify sorted by timestamp
3418        let timestamps: Vec<u64> = vec.iter().map(|m| m.at).collect();
3419        assert_eq!(timestamps, vec![100, 200, 300], "should be sorted by timestamp");
3420
3421        // All lookups should still work
3422        assert!(vec.contains_hex_id("aa00000000000000000000000000000000000000000000000000000000000000"));
3423        assert!(vec.contains_hex_id("bb00000000000000000000000000000000000000000000000000000000000000"));
3424        assert!(vec.contains_hex_id("cc00000000000000000000000000000000000000000000000000000000000000"));
3425    }
3426
3427    #[test]
3428    fn compact_vec_batch_prepend() {
3429        let mut vec = CompactMessageVec::new();
3430        // First insert newer messages
3431        vec.insert(make_compact_msg(
3432            "cc00000000000000000000000000000000000000000000000000000000000000", 300,
3433        ));
3434        vec.insert(make_compact_msg(
3435            "dd00000000000000000000000000000000000000000000000000000000000000", 400,
3436        ));
3437
3438        // Then batch-insert older messages (pagination scenario)
3439        let older = vec![
3440            make_compact_msg("aa00000000000000000000000000000000000000000000000000000000000000", 100),
3441            make_compact_msg("bb00000000000000000000000000000000000000000000000000000000000000", 200),
3442        ];
3443        let added = vec.insert_batch(older);
3444        assert_eq!(added, 2);
3445        assert_eq!(vec.len(), 4);
3446
3447        // Verify order
3448        let timestamps: Vec<u64> = vec.iter().map(|m| m.at).collect();
3449        assert_eq!(timestamps, vec![100, 200, 300, 400]);
3450
3451        // All lookups should work
3452        assert!(vec.contains_hex_id("aa00000000000000000000000000000000000000000000000000000000000000"));
3453        assert!(vec.contains_hex_id("dd00000000000000000000000000000000000000000000000000000000000000"));
3454    }
3455
3456    #[test]
3457    fn compact_vec_clear() {
3458        let mut vec = CompactMessageVec::new();
3459        vec.insert(make_compact_msg(
3460            "aa00000000000000000000000000000000000000000000000000000000000000", 100,
3461        ));
3462        vec.insert(make_compact_msg(
3463            "bb00000000000000000000000000000000000000000000000000000000000000", 200,
3464        ));
3465        assert_eq!(vec.len(), 2);
3466
3467        vec.clear();
3468        assert!(vec.is_empty());
3469        assert_eq!(vec.len(), 0);
3470        assert!(!vec.contains_hex_id("aa00000000000000000000000000000000000000000000000000000000000000"));
3471    }
3472
3473    // ========================================================================
3474    // CompactMessage from_message / to_message Tests
3475    // ========================================================================
3476
3477    /// Helper to create a full Message with all fields populated
3478    fn make_full_message() -> Message {
3479        Message {
3480            expiration: Some(1893456000),
3481            id: "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".into(),
3482            content: "Hello, world!".into(),
3483            replied_to: "1111111111111111111111111111111111111111111111111111111111111111".into(),
3484            replied_to_content: Some("Original message".into()),
3485            replied_to_emoji_tags: Some(vec![crate::types::EmojiTag {
3486                shortcode: "catJAM".into(),
3487                url: "https://example.com/catjam.png".into(),
3488            }]),
3489            replied_to_npub: Some("npub1replier".into()),
3490            replied_to_has_attachment: Some(true),
3491            replied_to_attachment_extension: None,
3492            preview_metadata: Some(SiteMetadata {
3493                domain: "example.com".into(),
3494                og_title: Some("Test Page".into()),
3495                og_description: Some("A test description".into()),
3496                og_image: Some("https://example.com/img.png".into()),
3497                og_url: Some("https://example.com".into()),
3498                og_type: Some("website".into()),
3499                title: Some("Test".into()),
3500                description: Some("Desc".into()),
3501                favicon: Some("https://example.com/favicon.ico".into()),
3502            }),
3503            attachments: vec![Attachment {
3504                id: "aaaa000000000000000000000000000000000000000000000000000000000000".into(),
3505                key: "bbbb000000000000000000000000000000000000000000000000000000000000".into(),
3506                nonce: "cccccccccccccccccccccccccccccccc".into(), // 32 hex chars = 16 bytes
3507                extension: "png".into(),
3508                name: "photo.png".into(),
3509                url: "https://blossom.example.com".into(),
3510                path: "/tmp/photo.png".into(),
3511                size: 12345,
3512                img_meta: Some(ImageMetadata {
3513                    thumbhash: "abc123".into(),
3514                    width: 800,
3515                    height: 600,
3516                }),
3517                downloading: false,
3518                downloaded: true, verified: false, resident: false,
3519                webxdc_topic: None,
3520                group_id: None,
3521                original_hash: None,
3522                fallback_urls: Vec::new(),
3523            }],
3524            reactions: vec![Reaction {
3525                id: "dddd000000000000000000000000000000000000000000000000000000000000".into(),
3526                reference_id: "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".into(),
3527                author_id: "npub1reactor".into(),
3528                emoji: "\u{1f44d}".into(), // thumbs up
3529                emoji_url: None,
3530            }],
3531            at: 1705320000000, // 2024-01-15 12:00:00 UTC ms
3532            pending: false,
3533            failed: false,
3534            mine: true,
3535            npub: Some("npub1sender".into()),
3536            wrapper_event_id: Some("eeee000000000000000000000000000000000000000000000000000000000000".into()),
3537            edited: true,
3538            edit_history: Some(vec![
3539                EditEntry { content: "Original".into(), edited_at: 1705320000000 },
3540                EditEntry { content: "Edited".into(), edited_at: 1705320060000 },
3541            ]),
3542            emoji_tags: Vec::new(),
3543            addressed_bots: vec!["npub1botrouting0000000000000000000000000000000000000000000000".into()],
3544            role_mentions: vec!["ab".repeat(32), "cd".repeat(32)],
3545            writer: true,
3546            unauthorized: true,
3547            text_spans: vec![crate::text_spans::TextSpan::Color(crate::text_color::ColorSpan { from: 0, to: 2, effect: crate::text_color::Effect::Rainbow, colors: Vec::new() })],
3548        }
3549    }
3550
3551    #[test]
3552    fn compact_add_reaction_rejects_a_resend_under_a_new_event_id() {
3553        let mut interner = NpubInterner::new();
3554        let mut compact = CompactMessage::from_message(&Message::default(), &mut interner);
3555        // Real hex — the id check would mask the slot check if these collapsed.
3556        let slot = |id: String, emoji: &str| Reaction {
3557            id,
3558            reference_id: "a".repeat(64),
3559            author_id: "npub1author".to_string(),
3560            emoji: emoji.to_string(),
3561            emoji_url: None,
3562        };
3563        assert!(compact.add_reaction(slot("1".repeat(64), "\u{1F44D}"), &mut interner));
3564        assert!(
3565            !compact.add_reaction(slot("2".repeat(64), "\u{1F44D}"), &mut interner),
3566            "distinct event ids but one (author, emoji) slot — this is the double-count"
3567        );
3568        assert_eq!(compact.reactions.len(), 1);
3569        assert!(
3570            compact.add_reaction(slot("3".repeat(64), "\u{2764}\u{FE0F}"), &mut interner),
3571            "a different emoji from the same author is its own reaction"
3572        );
3573        assert_eq!(compact.reactions.len(), 2);
3574    }
3575
3576    #[test]
3577    fn a_message_caps_at_twelve_reaction_groups_but_joins_stay_open() {
3578        let mut interner = NpubInterner::new();
3579        let mut compact = CompactMessage::from_message(&Message::default(), &mut interner);
3580        let react = |i: usize, author: &str, emoji: &str| Reaction {
3581            id: format!("{:064x}", i + 1),
3582            reference_id: "a".repeat(64),
3583            author_id: author.to_string(),
3584            emoji: emoji.to_string(),
3585            emoji_url: None,
3586        };
3587        for i in 0..MAX_REACTION_GROUPS {
3588            assert!(
3589                compact.add_reaction(react(i, "npub1opener", &format!("emoji{i}")), &mut interner),
3590                "group {i} fits under the ceiling"
3591            );
3592        }
3593        assert!(
3594            !compact.add_reaction(react(100, "npub1opener", "emoji-thirteen"), &mut interner),
3595            "a thirteenth distinct emoji is refused"
3596        );
3597        assert!(
3598            compact.add_reaction(react(101, "npub1joiner", "emoji0"), &mut interner),
3599            "joining an existing group is never bounded by the ceiling"
3600        );
3601        assert_eq!(compact.reactions.len(), MAX_REACTION_GROUPS + 1);
3602    }
3603
3604    /// The hot structs' footprint, pinned so a new field can't quietly grow every message.
3605    #[cfg(target_pointer_width = "64")]
3606    #[test]
3607    fn compact_layouts_hold_their_size() {
3608        assert_eq!(std::mem::size_of::<CompactMessage>(), 96);
3609        assert_eq!(std::mem::size_of::<CompactReaction>(), 40);
3610        assert_eq!(std::mem::size_of::<TinyVec<CompactReaction>>(), 8);
3611        assert_eq!(std::mem::size_of::<CompactAttachment>(), 144);
3612        assert_eq!(std::mem::size_of::<MessageExtras>(), 56);
3613        assert_eq!(std::mem::size_of::<CompactEdit>(), 24);
3614        assert_eq!(std::mem::size_of::<HeldSpan>(), 32);
3615    }
3616
3617    #[test]
3618    fn targeted_rekey_and_remove_match_a_full_rebuild() {
3619        let mut interner = NpubInterner::new();
3620        let id = |n: u64| {
3621            let mut b = [0u8; 32];
3622            b[..8].copy_from_slice(&n.wrapping_mul(0x9E37_79B9_7F4A_7C15).to_le_bytes());
3623            b
3624        };
3625        let mut v = CompactMessageVec::new();
3626        for n in 0..200u64 {
3627            let msg = Message { id: bytes_to_hex_32(&id(n)), at: n * 10, ..Default::default() };
3628            v.insert(CompactMessage::from_message(&msg, &mut interner));
3629        }
3630        let check = |v: &CompactMessageVec| {
3631            let mut rebuilt = v.clone();
3632            rebuilt.rebuild_index();
3633            assert_eq!(v.id_index, rebuilt.id_index);
3634        };
3635        for n in (0..200u64).step_by(7) {
3636            assert!(v.rekey(&id(n), id(n + 10_000)));
3637            check(&v);
3638        }
3639        assert!(!v.rekey(&id(1), id(2)), "a held id is never overwritten");
3640        for n in (3..200u64).step_by(11).filter(|n| n % 7 != 0) {
3641            assert!(v.remove_by_id(&id(n)));
3642            check(&v);
3643        }
3644        assert!(v.find_by_id(&id(10_007)).is_some_and(|m| m.at == 70));
3645    }
3646
3647    #[test]
3648    fn a_group_grows_past_255_reactions() {
3649        let mut interner = NpubInterner::new();
3650        let mut compact = CompactMessage::from_message(&Message::default(), &mut interner);
3651        let react = |i: usize| Reaction {
3652            id: format!("{:064x}", i + 1),
3653            reference_id: "a".repeat(64),
3654            author_id: format!("npub1joiner{i}"),
3655            emoji: "👍".to_string(),
3656            emoji_url: None,
3657        };
3658        for i in 0..300 {
3659            assert!(compact.add_reaction(react(i), &mut interner), "reaction {i} lands");
3660        }
3661        assert_eq!(compact.reactions.len(), 300);
3662        let loaded = Message { reactions: (0..300).map(react).collect(), ..Default::default() };
3663        assert_eq!(CompactMessage::from_message(&loaded, &mut interner).reactions.len(), 300, "history loads whole");
3664        compact.remove_reaction(&format!("{:064x}", 1));
3665        assert_eq!(compact.reactions.len(), 299);
3666    }
3667
3668    #[test]
3669    fn compact_message_from_message_roundtrip_all_fields() {
3670        let msg = make_full_message();
3671        let mut interner = NpubInterner::new();
3672        let compact = CompactMessage::from_message(&msg, &mut interner);
3673        let restored = compact.to_message(&interner);
3674
3675        assert_eq!(restored.id, msg.id, "id mismatch");
3676        assert_eq!(restored.content, msg.content, "content mismatch");
3677        assert_eq!(restored.mine, msg.mine, "mine mismatch");
3678        assert_eq!(restored.pending, msg.pending, "pending mismatch");
3679        assert_eq!(restored.failed, msg.failed, "failed mismatch");
3680        assert_eq!(restored.npub, msg.npub, "npub mismatch");
3681        assert_eq!(restored.replied_to, msg.replied_to, "replied_to mismatch");
3682        assert_eq!(restored.replied_to_content, msg.replied_to_content, "replied_to_content mismatch");
3683        assert_eq!(restored.replied_to_npub, msg.replied_to_npub, "replied_to_npub mismatch");
3684        assert_eq!(restored.replied_to_has_attachment, msg.replied_to_has_attachment, "replied_to_has_attachment mismatch");
3685        assert_eq!(restored.wrapper_event_id, None, "the wrapper link lives in the DB, not in memory");
3686        assert_eq!(restored.edited, msg.edited, "edited mismatch");
3687        assert_eq!(restored.edit_history, msg.edit_history, "edit_history mismatch");
3688        assert_eq!(restored.preview_metadata, msg.preview_metadata, "preview_metadata mismatch");
3689        // Timestamp loses sub-second precision but seconds should match
3690        assert_eq!(restored.at / 1000, msg.at / 1000, "timestamp seconds mismatch");
3691        // Attachments
3692        assert_eq!(restored.attachments.len(), 1, "should have 1 attachment");
3693        assert_eq!(restored.attachments[0].id, msg.attachments[0].id);
3694        assert_eq!(restored.attachments[0].name, msg.attachments[0].name);
3695        assert_eq!(restored.attachments[0].size, msg.attachments[0].size);
3696        // Reactions
3697        assert_eq!(restored.reactions.len(), 1, "should have 1 reaction");
3698        assert_eq!(restored.reactions[0].emoji, msg.reactions[0].emoji);
3699        // Bot routing targets round-trip through the interner.
3700        assert_eq!(restored.addressed_bots, msg.addressed_bots, "addressed_bots mismatch");
3701        assert_eq!(restored.role_mentions, msg.role_mentions, "role_mentions mismatch");
3702        assert_eq!(restored.writer, msg.writer, "writer mismatch");
3703        assert_eq!(restored.unauthorized, msg.unauthorized, "unauthorized mismatch");
3704    }
3705
3706    // The compact form deliberately keeps only the "replied-to has an attachment"
3707    // bool, so the extension does NOT survive a trip through STATE. Every path
3708    // that emits a message read back out of RAM has to re-run
3709    // populate_reply_context, or a quoted "GIF Animation" renders as a generic
3710    // "Attachment" the moment a reaction re-emits the row.
3711    #[test]
3712    fn compact_drops_replied_to_attachment_extension() {
3713        let mut msg = make_full_message();
3714        msg.replied_to_has_attachment = Some(true);
3715        msg.replied_to_attachment_extension = Some("gif".to_string());
3716
3717        let mut interner = NpubInterner::new();
3718        let restored = CompactMessage::from_message(&msg, &mut interner).to_message(&interner);
3719
3720        assert_eq!(restored.replied_to_has_attachment, Some(true), "the bool survives RAM");
3721        assert_eq!(
3722            restored.replied_to_attachment_extension, None,
3723            "the extension does not survive RAM — emitters must re-resolve it"
3724        );
3725    }
3726
3727    #[test]
3728    fn compact_message_from_message_owned_roundtrip() {
3729        let msg = make_full_message();
3730        let msg_clone = msg.clone();
3731        let mut interner = NpubInterner::new();
3732        let compact = CompactMessage::from_message_owned(msg, &mut interner);
3733        let restored = compact.to_message(&interner);
3734
3735        assert_eq!(restored.id, msg_clone.id, "id mismatch");
3736        assert_eq!(restored.content, msg_clone.content, "content mismatch");
3737        assert_eq!(restored.mine, msg_clone.mine, "mine mismatch");
3738        assert_eq!(restored.npub, msg_clone.npub, "npub mismatch");
3739        assert_eq!(restored.edit_history, msg_clone.edit_history, "edit_history mismatch");
3740    }
3741
3742    #[test]
3743    fn compact_message_pending_flag() {
3744        let msg = Message {
3745            id: "pending-1234567890".into(),
3746            pending: true,
3747            ..Message::default()
3748        };
3749        let mut interner = NpubInterner::new();
3750        let compact = CompactMessage::from_message(&msg, &mut interner);
3751        assert!(compact.is_pending(), "pending flag should be set");
3752        let restored = compact.to_message(&interner);
3753        assert!(restored.pending, "pending should roundtrip");
3754        assert_eq!(restored.id, "pending-1234567890", "pending ID should roundtrip");
3755    }
3756
3757    #[test]
3758    fn compact_message_failed_flag() {
3759        let msg = Message {
3760            id: "pending-999".into(),
3761            failed: true,
3762            pending: true,
3763            ..Message::default()
3764        };
3765        let mut interner = NpubInterner::new();
3766        let compact = CompactMessage::from_message(&msg, &mut interner);
3767        assert!(compact.is_failed(), "failed flag should be set");
3768        assert!(compact.is_pending(), "pending flag should also be set");
3769        let restored = compact.to_message(&interner);
3770        assert!(restored.failed);
3771        assert!(restored.pending);
3772    }
3773
3774    #[test]
3775    fn compact_message_with_attachments_roundtrip() {
3776        let msg = Message {
3777            id: "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".into(),
3778            attachments: vec![
3779                Attachment {
3780                    id: "1111111111111111111111111111111111111111111111111111111111111111".into(),
3781                    extension: "jpg".into(),
3782                    name: "sunset.jpg".into(),
3783                    size: 5000,
3784                    downloaded: true,
3785                    ..Attachment::default()
3786                },
3787                Attachment {
3788                    id: "2222222222222222222222222222222222222222222222222222222222222222".into(),
3789                    extension: "mp4".into(),
3790                    name: "video.mp4".into(),
3791                    size: 50000,
3792                    downloaded: false,
3793                    downloading: true,
3794                    ..Attachment::default()
3795                },
3796            ],
3797            ..Message::default()
3798        };
3799        let mut interner = NpubInterner::new();
3800        let compact = CompactMessage::from_message(&msg, &mut interner);
3801        assert_eq!(compact.attachments.len(), 2);
3802
3803        let restored = compact.to_message(&interner);
3804        assert_eq!(restored.attachments.len(), 2);
3805        assert_eq!(restored.attachments[0].name, "sunset.jpg");
3806        assert_eq!(restored.attachments[0].extension, "jpg");
3807        assert!(restored.attachments[0].downloaded);
3808        assert_eq!(restored.attachments[1].name, "video.mp4");
3809        assert!(restored.attachments[1].downloading);
3810        assert!(!restored.attachments[1].downloaded);
3811    }
3812
3813    #[test]
3814    fn compact_message_with_reactions_roundtrip() {
3815        let msg = Message {
3816            id: "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".into(),
3817            reactions: vec![
3818                Reaction {
3819                    id: "aaa0000000000000000000000000000000000000000000000000000000000000".into(),
3820                    reference_id: "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".into(),
3821                    author_id: "npub1alice".into(),
3822                    emoji: "\u{2764}".into(), // heart
3823                    emoji_url: None,
3824                },
3825                Reaction {
3826                    id: "bbb0000000000000000000000000000000000000000000000000000000000000".into(),
3827                    reference_id: "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".into(),
3828                    author_id: "npub1bob".into(),
3829                    emoji: "\u{1f525}".into(), // fire
3830                    emoji_url: None,
3831                },
3832            ],
3833            ..Message::default()
3834        };
3835        let mut interner = NpubInterner::new();
3836        let compact = CompactMessage::from_message(&msg, &mut interner);
3837        let restored = compact.to_message(&interner);
3838
3839        assert_eq!(restored.reactions.len(), 2);
3840        assert_eq!(restored.reactions[0].emoji, "\u{2764}");
3841        assert_eq!(restored.reactions[0].author_id, "npub1alice");
3842        assert_eq!(restored.reactions[1].emoji, "\u{1f525}");
3843        assert_eq!(restored.reactions[1].author_id, "npub1bob");
3844    }
3845
3846    #[test]
3847    fn compact_message_with_edit_history_roundtrip() {
3848        let msg = Message {
3849            id: "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".into(),
3850            content: "Final version".into(),
3851            edited: true,
3852            edit_history: Some(vec![
3853                EditEntry { content: "First draft".into(), edited_at: 1000 },
3854                EditEntry { content: "Second draft".into(), edited_at: 2000 },
3855                EditEntry { content: "Final version".into(), edited_at: 3000 },
3856            ]),
3857            ..Message::default()
3858        };
3859        let mut interner = NpubInterner::new();
3860        let compact = CompactMessage::from_message(&msg, &mut interner);
3861        assert!(compact.is_edited());
3862
3863        let restored = compact.to_message(&interner);
3864        assert!(restored.edited);
3865        let history = restored.edit_history.unwrap();
3866        assert_eq!(history.len(), 3);
3867        assert_eq!(history[0].content, "First draft");
3868        assert_eq!(history[2].content, "Final version");
3869    }
3870
3871    #[test]
3872    fn compact_message_with_preview_metadata_roundtrip() {
3873        let meta = SiteMetadata {
3874            domain: "example.com".into(),
3875            og_title: Some("Title".into()),
3876            og_description: Some("Desc".into()),
3877            og_image: Some("https://example.com/img.png".into()),
3878            og_url: None,
3879            og_type: None,
3880            title: None,
3881            description: None,
3882            favicon: None,
3883        };
3884        let msg = Message {
3885            id: "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".into(),
3886            preview_metadata: Some(meta.clone()),
3887            ..Message::default()
3888        };
3889        let mut interner = NpubInterner::new();
3890        let compact = CompactMessage::from_message(&msg, &mut interner);
3891        let restored = compact.to_message(&interner);
3892
3893        let restored_meta = restored.preview_metadata.unwrap();
3894        assert_eq!(restored_meta.domain, "example.com");
3895        assert_eq!(restored_meta.og_title, Some("Title".into()));
3896        assert_eq!(restored_meta.og_image, Some("https://example.com/img.png".into()));
3897        assert_eq!(restored_meta.og_url, None);
3898    }
3899
3900    #[test]
3901    fn compact_message_with_replied_to_roundtrip() {
3902        let msg = Message {
3903            id: "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".into(),
3904            replied_to: "1111111111111111111111111111111111111111111111111111111111111111".into(),
3905            replied_to_content: Some("Original text".into()),
3906            replied_to_npub: Some("npub1original".into()),
3907            replied_to_has_attachment: Some(false),
3908            ..Message::default()
3909        };
3910        let mut interner = NpubInterner::new();
3911        let compact = CompactMessage::from_message(&msg, &mut interner);
3912        assert!(compact.has_reply());
3913
3914        let restored = compact.to_message(&interner);
3915        assert_eq!(restored.replied_to, "1111111111111111111111111111111111111111111111111111111111111111");
3916        assert_eq!(restored.replied_to_content, Some("Original text".into()));
3917        assert_eq!(restored.replied_to_npub, Some("npub1original".into()));
3918        assert_eq!(restored.replied_to_has_attachment, Some(false));
3919    }
3920
3921    #[test]
3922    fn compact_message_empty_roundtrip() {
3923        let msg = Message::default();
3924        let mut interner = NpubInterner::new();
3925        let compact = CompactMessage::from_message(&msg, &mut interner);
3926        let restored = compact.to_message(&interner);
3927
3928        assert_eq!(restored.id, "0000000000000000000000000000000000000000000000000000000000000000",
3929            "empty ID should decode as all zeros hex");
3930        assert_eq!(restored.content, "");
3931        assert!(!restored.mine);
3932        assert!(!restored.pending);
3933        assert!(!restored.failed);
3934        assert!(!restored.edited);
3935        assert_eq!(restored.npub, None);
3936        assert!(restored.replied_to.is_empty() || restored.replied_to == "0000000000000000000000000000000000000000000000000000000000000000");
3937        assert_eq!(restored.replied_to_content, None);
3938        assert_eq!(restored.replied_to_npub, None);
3939        assert_eq!(restored.replied_to_has_attachment, None);
3940        assert_eq!(restored.wrapper_event_id, None);
3941        assert!(restored.attachments.is_empty());
3942        assert!(restored.reactions.is_empty());
3943        assert_eq!(restored.edit_history, None);
3944        assert_eq!(restored.preview_metadata, None);
3945    }
3946
3947    // ========================================================================
3948    // CompactAttachment Tests
3949    // ========================================================================
3950
3951    #[test]
3952    fn compact_attachment_from_attachment_roundtrip() {
3953        let att = Attachment {
3954            id: "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".into(),
3955            key: "1111111111111111111111111111111111111111111111111111111111111111".into(),
3956            nonce: "aabbccddaabbccddaabbccddaabbccdd".into(), // 32 hex = 16-byte DM nonce
3957            extension: "zip".into(),
3958            name: "archive.zip".into(),
3959            url: "https://blossom.test.com".into(),
3960            path: "/downloads/archive.zip".into(),
3961            size: 99999,
3962            img_meta: None,
3963            downloading: false,
3964            downloaded: true, verified: false, resident: false,
3965            webxdc_topic: None,
3966            group_id: None,
3967            original_hash: None,
3968            fallback_urls: Vec::new(),
3969        };
3970
3971        let compact = CompactAttachment::from_attachment(&att);
3972        let restored = compact.to_attachment();
3973
3974        assert_eq!(restored.id, att.id, "id mismatch");
3975        assert_eq!(restored.key, att.key, "key mismatch");
3976        assert_eq!(restored.nonce, att.nonce, "nonce mismatch");
3977        assert_eq!(restored.extension, att.extension, "extension mismatch");
3978        assert_eq!(restored.name, att.name, "name mismatch");
3979        assert_eq!(restored.url, att.url, "url mismatch");
3980        assert_eq!(restored.path, att.path, "path mismatch");
3981        assert_eq!(restored.size, att.size, "size mismatch");
3982        assert_eq!(restored.downloading, att.downloading, "downloading mismatch");
3983        assert_eq!(restored.downloaded, att.downloaded, "downloaded mismatch");
3984        assert!(!restored.verified);
3985
3986        let proven = Attachment { verified: true, ..att.clone() };
3987        let restored = CompactAttachment::from_attachment(&proven).to_attachment();
3988        assert!(restored.verified, "verified survives the compact form");
3989        assert_eq!(restored.path, att.path, "and leaves the path kind alone");
3990        let mut compact = CompactAttachment::from_attachment(&proven);
3991        compact.set_verified(false);
3992        assert!(!compact.verified() && compact.downloaded());
3993    }
3994
3995    #[test]
3996    fn compact_attachment_from_attachment_owned_roundtrip() {
3997        let att = Attachment {
3998            id: "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".into(),
3999            key: "1111111111111111111111111111111111111111111111111111111111111111".into(),
4000            nonce: "aabbccddaabbccddaabbccddaabbccdd".into(),
4001            extension: "pdf".into(),
4002            name: "document.pdf".into(),
4003            url: "https://server.com".into(),
4004            path: "".into(),
4005            size: 1024,
4006            img_meta: None,
4007            downloading: false,
4008            downloaded: false, verified: false, resident: false,
4009            webxdc_topic: None,
4010            group_id: None,
4011            original_hash: None,
4012            fallback_urls: Vec::new(),
4013        };
4014        let att_clone = att.clone();
4015
4016        let compact = CompactAttachment::from_attachment_owned(att);
4017        let restored = compact.to_attachment();
4018
4019        assert_eq!(restored.id, att_clone.id);
4020        assert_eq!(restored.name, att_clone.name);
4021        assert_eq!(restored.size, att_clone.size);
4022    }
4023
4024    #[test]
4025    fn compact_attachment_key_nonce_zeros() {
4026        let att = Attachment {
4027            id: "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".into(),
4028            key: "".into(), // empty key = legacy derived
4029            nonce: "".into(), // empty nonce
4030            ..Attachment::default()
4031        };
4032        let compact = CompactAttachment::from_attachment(&att);
4033        assert_eq!(compact.key, [0u8; 32], "empty key should be all zeros");
4034        assert_eq!(compact.nonce, [0u8; 16], "empty nonce should be all zeros");
4035
4036        let restored = compact.to_attachment();
4037        assert_eq!(restored.key, "", "zero key should restore as empty string");
4038        assert_eq!(restored.nonce, "", "zero nonce should restore as empty string");
4039    }
4040
4041    #[test]
4042    fn compact_attachment_short_nonce_mls_12byte() {
4043        // Legacy short nonce is 12 bytes = 24 hex chars
4044        let att = Attachment {
4045            id: "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".into(),
4046            nonce: "aabbccddaabbccddaabbccdd".into(), // 24 hex chars = 12 bytes
4047            ..Attachment::default()
4048        };
4049        let compact = CompactAttachment::from_attachment(&att);
4050        assert!(compact.flags.is_short_nonce(), "12-byte nonce should set short_nonce flag");
4051
4052        let restored = compact.to_attachment();
4053        assert_eq!(restored.nonce, "aabbccddaabbccddaabbccdd", "short nonce should roundtrip");
4054    }
4055
4056    #[test]
4057    fn compact_attachment_long_nonce_dm_16byte() {
4058        // DM nonce is 16 bytes = 32 hex chars
4059        let att = Attachment {
4060            id: "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".into(),
4061            nonce: "aabbccddaabbccddaabbccddaabbccdd".into(), // 32 hex chars = 16 bytes
4062            ..Attachment::default()
4063        };
4064        let compact = CompactAttachment::from_attachment(&att);
4065        assert!(!compact.flags.is_short_nonce(), "16-byte nonce should NOT set short_nonce flag");
4066
4067        let restored = compact.to_attachment();
4068        assert_eq!(restored.nonce, "aabbccddaabbccddaabbccddaabbccdd", "long nonce should roundtrip");
4069    }
4070
4071    #[test]
4072    fn compact_attachment_id_eq_comparison() {
4073        let att = Attachment {
4074            id: "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".into(),
4075            ..Attachment::default()
4076        };
4077        let compact = CompactAttachment::from_attachment(&att);
4078
4079        assert!(compact.id_eq("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789"),
4080            "id_eq should match same hex");
4081        assert!(!compact.id_eq("1111111111111111111111111111111111111111111111111111111111111111"),
4082            "id_eq should not match different hex");
4083    }
4084
4085    #[test]
4086    fn compact_attachment_all_optional_fields_none() {
4087        let att = Attachment::default();
4088        let compact = CompactAttachment::from_attachment(&att);
4089
4090        assert!(!compact.has_img_meta());
4091        assert!(compact.group_id().is_none());
4092        assert!(compact.original_hash().is_none());
4093        assert!(compact.webxdc_topic().is_none());
4094
4095        let restored = compact.to_attachment();
4096        assert!(restored.img_meta.is_none());
4097        assert!(restored.group_id.is_none());
4098        assert!(restored.original_hash.is_none());
4099        assert!(restored.webxdc_topic.is_none());
4100    }
4101
4102    #[test]
4103    fn compact_attachment_all_optional_fields_some() {
4104        let att = Attachment {
4105            id: "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".into(),
4106            key: "1111111111111111111111111111111111111111111111111111111111111111".into(),
4107            nonce: "aabbccddaabbccddaabbccddaabbccdd".into(),
4108            extension: "xdc".into(),
4109            name: "app.xdc".into(),
4110            url: "https://server.com/file".into(),
4111            path: "/local/app.xdc".into(),
4112            size: 50000,
4113            img_meta: Some(ImageMetadata {
4114                thumbhash: "hash123".into(),
4115                width: 1920,
4116                height: 1080,
4117            }),
4118            downloading: false,
4119            downloaded: true, verified: false, resident: false,
4120            webxdc_topic: Some("game-state".into()),
4121            group_id: Some("cccc000000000000000000000000000000000000000000000000000000000000".into()),
4122            original_hash: Some("dddd000000000000000000000000000000000000000000000000000000000000".into()),
4123            fallback_urls: Vec::new(),
4124        };
4125
4126        let compact = CompactAttachment::from_attachment(&att);
4127
4128        assert!(compact.has_img_meta());
4129        assert!(compact.group_id().is_some());
4130        assert!(compact.original_hash().is_some());
4131        assert!(compact.webxdc_topic().is_some());
4132
4133        let restored = compact.to_attachment();
4134        let meta = restored.img_meta.unwrap();
4135        assert_eq!(meta.thumbhash, "hash123");
4136        assert_eq!(meta.width, 1920);
4137        assert_eq!(meta.height, 1080);
4138        assert_eq!(restored.webxdc_topic, Some("game-state".into()));
4139        assert_eq!(restored.group_id.unwrap(), att.group_id.unwrap());
4140        assert_eq!(restored.original_hash.unwrap(), att.original_hash.unwrap());
4141    }
4142
4143    // ========================================================================
4144    // CompactReaction Tests
4145    // ========================================================================
4146
4147    #[test]
4148    fn compact_reaction_from_reaction_roundtrip() {
4149        let reaction = Reaction {
4150            id: "aaaa000000000000000000000000000000000000000000000000000000000000".into(),
4151            reference_id: "bbbb000000000000000000000000000000000000000000000000000000000000".into(),
4152            author_id: "npub1alice".into(),
4153            emoji: "+".into(),
4154            emoji_url: None,
4155        };
4156        let mut interner = NpubInterner::new();
4157        let compact = CompactReaction::from_reaction(&reaction, &mut interner);
4158        let restored = compact.to_reaction(&reaction.reference_id, &interner);
4159
4160        assert_eq!(restored.id, reaction.id, "id mismatch");
4161        assert_eq!(restored.reference_id, reaction.reference_id, "reference_id mismatch");
4162        assert_eq!(restored.author_id, reaction.author_id, "author_id mismatch");
4163        assert_eq!(restored.emoji, reaction.emoji, "emoji mismatch");
4164    }
4165
4166    #[test]
4167    fn compact_reaction_author_resolved_via_interner() {
4168        let mut interner = NpubInterner::new();
4169        let alice_handle = interner.intern("npub1alice");
4170
4171        let reaction = Reaction {
4172            id: "aaaa000000000000000000000000000000000000000000000000000000000000".into(),
4173            reference_id: "bbbb000000000000000000000000000000000000000000000000000000000000".into(),
4174            author_id: "npub1alice".into(),
4175            emoji: "+".into(),
4176            emoji_url: None,
4177        };
4178        let compact = CompactReaction::from_reaction(&reaction, &mut interner);
4179        assert_eq!(compact.author_idx, alice_handle, "should reuse existing interner handle");
4180
4181        let resolved = interner.resolve(compact.author_idx).unwrap();
4182        assert_eq!(resolved, "npub1alice");
4183    }
4184
4185    #[test]
4186    fn compact_reaction_unicode_emoji() {
4187        let reaction = Reaction {
4188            id: "aaaa000000000000000000000000000000000000000000000000000000000000".into(),
4189            reference_id: "bbbb000000000000000000000000000000000000000000000000000000000000".into(),
4190            author_id: "npub1test".into(),
4191            emoji: "\u{1f431}\u{200d}\u{1f4bb}".into(), // cat with laptop (ZWJ sequence)
4192            emoji_url: None,
4193        };
4194        let mut interner = NpubInterner::new();
4195        let compact = CompactReaction::from_reaction(&reaction, &mut interner);
4196        let restored = compact.to_reaction(&reaction.reference_id, &interner);
4197        assert_eq!(restored.emoji, "\u{1f431}\u{200d}\u{1f4bb}", "complex unicode emoji should roundtrip");
4198    }
4199
4200    #[test]
4201    fn compact_reaction_custom_emoji() {
4202        let reaction = Reaction {
4203            id: "aaaa000000000000000000000000000000000000000000000000000000000000".into(),
4204            reference_id: "bbbb000000000000000000000000000000000000000000000000000000000000".into(),
4205            author_id: "npub1test".into(),
4206            emoji: ":cat_heart_eyes:".into(),
4207            emoji_url: None,
4208        };
4209        let mut interner = NpubInterner::new();
4210        let compact = CompactReaction::from_reaction(&reaction, &mut interner);
4211        let restored = compact.to_reaction(&reaction.reference_id, &interner);
4212        assert_eq!(restored.emoji, ":cat_heart_eyes:", "custom emoji shortcode should roundtrip");
4213    }
4214
4215    #[test]
4216    fn compact_reaction_owned_conversion() {
4217        let reaction = Reaction {
4218            id: "aaaa000000000000000000000000000000000000000000000000000000000000".into(),
4219            reference_id: "bbbb000000000000000000000000000000000000000000000000000000000000".into(),
4220            author_id: "npub1bob".into(),
4221            emoji: "\u{1f44d}".into(), // thumbs up
4222            emoji_url: None,
4223        };
4224        let reaction_clone = reaction.clone();
4225        let mut interner = NpubInterner::new();
4226        let compact = CompactReaction::from_reaction_owned(reaction, &mut interner);
4227        let restored = compact.to_reaction(&reaction_clone.reference_id, &interner);
4228
4229        assert_eq!(restored.id, reaction_clone.id);
4230        assert_eq!(restored.author_id, reaction_clone.author_id);
4231        assert_eq!(restored.emoji, reaction_clone.emoji);
4232    }
4233
4234    // ========================================================================
4235    // TinyVec Tests
4236    // ========================================================================
4237
4238    #[test]
4239    fn tinyvec_empty() {
4240        let tv: TinyVec<u32> = TinyVec::new();
4241        assert!(tv.is_empty());
4242        assert_eq!(tv.len(), 0);
4243        assert_eq!(tv.as_slice(), &[] as &[u32]);
4244        assert_eq!(tv.first(), None);
4245        assert_eq!(tv.last(), None);
4246    }
4247
4248    #[test]
4249    fn tinyvec_from_vec_and_back() {
4250        let original = vec![1u32, 2, 3, 4, 5];
4251        let tv = TinyVec::from_vec(original.clone());
4252        assert_eq!(tv.len(), 5);
4253        assert_eq!(tv.to_vec(), original);
4254    }
4255
4256    #[test]
4257    fn tinyvec_indexing() {
4258        let tv = TinyVec::from_vec(vec![10u32, 20, 30]);
4259        assert_eq!(tv[0], 10);
4260        assert_eq!(tv[1], 20);
4261        assert_eq!(tv[2], 30);
4262        assert_eq!(tv.get(0), Some(&10));
4263        assert_eq!(tv.get(3), None);
4264    }
4265
4266    #[test]
4267    fn tinyvec_push() {
4268        let mut tv = TinyVec::from_vec(vec![1u32, 2]);
4269        tv.push(3);
4270        assert_eq!(tv.len(), 3);
4271        assert_eq!(tv.to_vec(), vec![1, 2, 3]);
4272    }
4273
4274    #[test]
4275    fn tinyvec_clone() {
4276        let tv = TinyVec::from_vec(vec!["hello".to_string(), "world".to_string()]);
4277        let cloned = tv.clone();
4278        assert_eq!(cloned.len(), 2);
4279        assert_eq!(cloned[0], "hello");
4280        assert_eq!(cloned[1], "world");
4281    }
4282
4283    #[test]
4284    fn tinyvec_retain() {
4285        let mut tv = TinyVec::from_vec(vec![1u32, 2, 3, 4, 5]);
4286        tv.retain(|&x| x % 2 == 0);
4287        assert_eq!(tv.to_vec(), vec![2, 4]);
4288    }
4289
4290    #[test]
4291    fn tinyvec_empty_from_empty_vec() {
4292        let tv = TinyVec::<u32>::from_vec(vec![]);
4293        assert!(tv.is_empty());
4294        assert_eq!(tv.len(), 0);
4295    }
4296
4297    #[test]
4298    fn tinyvec_iter() {
4299        let tv = TinyVec::from_vec(vec![10u32, 20, 30]);
4300        let sum: u32 = tv.iter().sum();
4301        assert_eq!(sum, 60);
4302    }
4303
4304    #[test]
4305    fn tinyvec_any() {
4306        let tv = TinyVec::from_vec(vec![1u32, 2, 3]);
4307        assert!(tv.any(|&x| x == 2));
4308        assert!(!tv.any(|&x| x == 99));
4309    }
4310
4311    // ========================================================================
4312    // hex_to_bytes_16 / bytes_to_hex_string Tests
4313    // ========================================================================
4314
4315    #[test]
4316    fn hex_to_bytes_16_full_32_chars() {
4317        let hex = "aabbccddaabbccddaabbccddaabbccdd";
4318        let bytes = hex_to_bytes_16(hex);
4319        assert_eq!(bytes[0], 0xaa);
4320        assert_eq!(bytes[1], 0xbb);
4321        assert_eq!(bytes[15], 0xdd);
4322    }
4323
4324    #[test]
4325    fn hex_to_bytes_16_short_input_padded() {
4326        // Short input gets right-padded with '0' before decode
4327        let hex = "aabb";
4328        let bytes = hex_to_bytes_16(hex);
4329        assert_eq!(bytes[0], 0xaa);
4330        assert_eq!(bytes[1], 0xbb);
4331        // Remaining bytes should be 0 (from padding)
4332        for i in 2..16 {
4333            assert_eq!(bytes[i], 0, "byte {} should be 0 from padding", i);
4334        }
4335    }
4336
4337    #[test]
4338    fn bytes_to_hex_string_roundtrip() {
4339        let bytes: Vec<u8> = vec![0xaa, 0xbb, 0xcc, 0xdd];
4340        let hex = bytes_to_hex_string(&bytes);
4341        assert_eq!(hex, "aabbccdd");
4342    }
4343
4344    // ========================================================================
4345    // Resident representation: exact round trips
4346    // ========================================================================
4347
4348    fn hex64(n: u64) -> String {
4349        format!("{:064x}", n.wrapping_mul(0x9E37_79B9_7F4A_7C15))
4350    }
4351
4352    fn att_with(id: &str, ext: &str, name: &str, path: String) -> Attachment {
4353        Attachment {
4354            id: id.into(),
4355            key: hex64(7),
4356            nonce: "aabbccddaabbccddaabbccddaabbccdd".into(),
4357            extension: ext.into(),
4358            name: name.into(),
4359            url: format!("https://blossom.example/{id}"),
4360            path,
4361            size: 4242,
4362            img_meta: None,
4363            downloading: false,
4364            downloaded: true, verified: false, resident: false,
4365            webxdc_topic: None,
4366            group_id: None,
4367            original_hash: Some(id.into()),
4368            fallback_urls: Vec::new(),
4369        }
4370    }
4371
4372    fn path_kind_of(att: &Attachment) -> u8 {
4373        CompactAttachment::from_attachment(att).flags.path_kind()
4374    }
4375
4376    /// Both conversions, then back: the boundary type must come out identical.
4377    fn assert_exact(msg: &Message) {
4378        let mut interner = NpubInterner::new();
4379        let borrowed = CompactMessage::from_message(msg, &mut interner).to_message(&interner);
4380        assert_eq!(&borrowed, msg, "from_message round trip");
4381        let owned = CompactMessage::from_message_owned(msg.clone(), &mut interner).to_message(&interner);
4382        assert_eq!(&owned, msg, "from_message_owned round trip");
4383    }
4384
4385    /// A message whose every field survives RAM: the wrapper link and quoted extension
4386    /// never do, and a reaction's reference is its parent.
4387    fn rich_message() -> Message {
4388        let id = hex64(1);
4389        let mut msg = make_full_message();
4390        msg.id = id.clone();
4391        msg.wrapper_event_id = None;
4392        msg.replied_to_attachment_extension = None;
4393        msg.content = "Edited".into();
4394        for r in &mut msg.reactions {
4395            r.reference_id = id.clone();
4396        }
4397        msg.attachments = vec![att_with(&hex64(2), "png", "photo.png", format!("{}photo.png", download_prefix()))];
4398        msg
4399    }
4400
4401    #[test]
4402    fn a_rich_message_round_trips_exactly() {
4403        assert_exact(&rich_message());
4404        assert_exact(&Message { id: hex64(3), content: "plain".into(), at: 1_700_000_000_123, ..Default::default() });
4405    }
4406
4407    #[test]
4408    fn every_path_kind_round_trips_exactly() {
4409        let id = hex64(10);
4410        let prefix = download_prefix();
4411        let cases = [
4412            (String::new(), 0, "empty"),
4413            (format!("{prefix}{id}.jpg"), AttachmentFlags::PATH_HASHED, "hashed"),
4414            (format!("{prefix}holiday.jpg"), AttachmentFlags::PATH_NAMED, "named"),
4415            (format!("{prefix}holiday-1.jpg"), AttachmentFlags::PATH_CUSTOM, "collision suffix"),
4416            (format!("{prefix}{}.jpg", id.to_uppercase()), AttachmentFlags::PATH_CUSTOM, "uppercase hash"),
4417            (format!("{prefix}{id}.png"), AttachmentFlags::PATH_CUSTOM, "hash with another extension"),
4418            (format!("{prefix}{}.jpg", hex64(11)), AttachmentFlags::PATH_CUSTOM, "another hash"),
4419            (format!("{prefix}{id}.jpg.part"), AttachmentFlags::PATH_CUSTOM, "hashed plus a tail"),
4420            ("/elsewhere/holiday.jpg".to_string(), AttachmentFlags::PATH_CUSTOM, "another directory"),
4421            (format!("{prefix}sub/holiday.jpg"), AttachmentFlags::PATH_CUSTOM, "a subdirectory"),
4422        ];
4423        for (path, kind, label) in cases {
4424            let att = att_with(&id, "jpg", "holiday.jpg", path);
4425            assert_eq!(path_kind_of(&att), kind, "{label}");
4426            assert_eq!(CompactAttachment::from_attachment(&att).to_attachment(), att, "{label}");
4427            assert_eq!(CompactAttachment::from_attachment_owned(att.clone()).to_attachment(), att, "{label} (owned)");
4428        }
4429        // No name: the prefix alone is not a named path.
4430        let bare = att_with(&id, "jpg", "", prefix.to_string());
4431        assert_eq!(path_kind_of(&bare), AttachmentFlags::PATH_CUSTOM);
4432        assert_eq!(CompactAttachment::from_attachment(&bare).to_attachment(), bare);
4433        // A name equal to the hashed file name reproduces either way.
4434        let both = att_with(&id, "jpg", &format!("{id}.jpg"), format!("{prefix}{id}.jpg"));
4435        assert_eq!(CompactAttachment::from_attachment(&both).to_attachment(), both);
4436    }
4437
4438    #[test]
4439    fn a_derived_path_follows_set_path() {
4440        let id = hex64(20);
4441        let mut c = CompactAttachment::from_attachment(&att_with(&id, "mp4", "clip.mp4", String::new()));
4442        assert!(!c.has_path());
4443        assert!(c.cold.is_none());
4444        c.set_path(format!("{}clip.mp4", download_prefix()));
4445        assert_eq!(c.flags.path_kind(), AttachmentFlags::PATH_NAMED);
4446        assert!(c.cold.is_none(), "a derived path needs no cold box");
4447        c.set_path("/custom/clip.mp4".into());
4448        assert_eq!(c.path(), "/custom/clip.mp4");
4449        assert!(c.cold.is_some());
4450        c.set_path(String::new());
4451        assert!(!c.has_path());
4452        assert_eq!(c.path(), "");
4453        assert!(c.cold.is_none(), "clearing the only cold field drops the box");
4454        assert!(c.downloaded(), "the path kind leaves the other flags alone");
4455    }
4456
4457    #[test]
4458    fn cold_fields_round_trip_exactly() {
4459        let id = hex64(30);
4460        let mut att = att_with(&id, "tar.zst", "", "/var/x".into());
4461        att.original_hash = Some(hex64(31));
4462        att.group_id = Some(hex64(32));
4463        att.webxdc_topic = Some("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567ABCDEFGHIJKLMNOPQRST".into());
4464        att.fallback_urls = vec!["https://a.example/x".into(), "https://b.example/x".into()];
4465        att.img_meta = Some(ImageMetadata { thumbhash: "ẞ-thumb".into(), width: 7, height: 9 });
4466        let c = CompactAttachment::from_attachment(&att);
4467        assert_eq!(c.ext, EXT_COLD);
4468        assert_eq!(c.to_attachment(), att);
4469
4470        // Unknown or differently-cased extensions keep their exact spelling.
4471        for ext in ["JPG", "Png", "weird", ""] {
4472            let a = att_with(&id, ext, "", String::new());
4473            assert_eq!(CompactAttachment::from_attachment(&a).to_attachment(), a, "{ext:?}");
4474        }
4475        // An image with an empty thumbhash is still an image.
4476        let mut a = att_with(&id, "png", "", String::new());
4477        a.img_meta = Some(ImageMetadata { thumbhash: String::new(), width: 0, height: 0 });
4478        assert_eq!(CompactAttachment::from_attachment(&a).to_attachment(), a);
4479        // No original hash, and one that differs only from the id.
4480        a.original_hash = None;
4481        assert_eq!(CompactAttachment::from_attachment(&a).to_attachment(), a);
4482        assert!(CompactAttachment::from_attachment(&a).cold.is_none());
4483    }
4484
4485    #[test]
4486    fn the_common_attachment_holds_nothing_cold() {
4487        let id = hex64(40);
4488        let att = att_with(&id, "webp", "", format!("{}{id}.webp", download_prefix()));
4489        let c = CompactAttachment::from_attachment(&att);
4490        assert!(c.cold.is_none(), "known extension, hashed path and original == id need no box");
4491        assert_eq!(c.to_attachment(), att);
4492        for ext in ["png", "mp4", "", "tar.zst"] {
4493            let a = att_with(&id, ext, "", format!("{}{id}.{ext}", download_prefix()));
4494            assert_eq!(path_kind_of(&a), AttachmentFlags::PATH_HASHED, "{ext:?}");
4495            assert_eq!(CompactAttachment::from_attachment(&a).to_attachment(), a, "{ext:?}");
4496        }
4497        assert_eq!(c.flags.0 & AttachmentFlags::ORIGINAL_IS_ID, AttachmentFlags::ORIGINAL_IS_ID);
4498        assert_eq!(c.original_hash(), Some(c.id));
4499    }
4500
4501    #[test]
4502    fn every_extension_code_reads_back() {
4503        for (i, ext) in EXTENSIONS.iter().enumerate() {
4504            assert_eq!(extension_code(ext) as usize, i, "{ext} must appear once");
4505        }
4506        assert!(EXTENSIONS.len() < EXT_COLD as usize);
4507    }
4508
4509    fn preview(title: Option<&str>, og_title: Option<&str>, desc: Option<&str>, og_desc: Option<&str>) -> SiteMetadata {
4510        SiteMetadata {
4511            domain: "example.com".into(),
4512            og_title: og_title.map(Into::into),
4513            og_description: og_desc.map(Into::into),
4514            og_image: Some("https://example.com/i.png".into()),
4515            og_url: None,
4516            og_type: Some("article".into()),
4517            title: title.map(Into::into),
4518            description: desc.map(Into::into),
4519            favicon: Some(String::new()),
4520        }
4521    }
4522
4523    #[test]
4524    fn previews_round_trip_exactly() {
4525        let long = "ü".repeat(9000);
4526        let cases = [
4527            preview(Some("Same"), Some("Same"), Some("D"), Some("D")),
4528            preview(Some("Mine"), Some("Theirs"), Some("D1"), Some("D2")),
4529            preview(Some("Only title"), None, None, Some("Only og")),
4530            preview(None, Some("Only og"), Some("Only desc"), None),
4531            preview(None, None, None, None),
4532            preview(Some(""), Some(""), Some(""), None),
4533            preview(Some(&long), Some(&long), Some(&long[..200]), Some(&long)),
4534        ];
4535        for meta in cases {
4536            assert_eq!(unpack_preview(pack_preview(&meta).as_slice()).as_ref(), Some(&meta));
4537            let msg = Message { id: hex64(50), preview_metadata: Some(meta.clone()), ..Default::default() };
4538            assert_exact(&msg);
4539            let mut interner = NpubInterner::new();
4540            let mut c = CompactMessage::from_message(&Message { id: hex64(51), ..Default::default() }, &mut interner);
4541            c.set_preview_metadata(Some(meta.clone()));
4542            assert_eq!(c.preview_metadata(), Some(meta));
4543            c.set_preview_metadata(None);
4544            assert!(c.extras.is_none(), "removing the only extra drops the box");
4545        }
4546        let same = preview(Some("Same title"), Some("Same title"), Some("Same desc"), Some("Same desc"));
4547        let differ = preview(Some("Same title"), Some("Other title"), Some("Same desc"), Some("Other desc"));
4548        assert!(pack_preview(&same).len() + 18 < pack_preview(&differ).len(), "equal twins are stored once");
4549    }
4550
4551    #[test]
4552    fn spans_round_trip_exactly() {
4553        use crate::text_spans::{ColorSpan, TextSpan, TimeSpan};
4554        use crate::text_color::Effect;
4555        let color = |colors: &[&str]| TextSpan::Color(ColorSpan {
4556            from: 1,
4557            to: 4,
4558            effect: Effect::Gradient,
4559            colors: colors.iter().map(|c| c.to_string()).collect(),
4560        });
4561        let spans = vec![
4562            color(&["#000000", "#ffffff", "#0a1b2c"]),
4563            color(&["#ABCDEF", "#abcdef"]),
4564            color(&["red"]),
4565            color(&["#abc"]),
4566            TextSpan::Color(ColorSpan { from: 0, to: 9, effect: Effect::Rainbow, colors: Vec::new() }),
4567            TextSpan::Time(TimeSpan { from: 2, to: 8, unix: -62_167_219_200, style: 'R' }),
4568        ];
4569        let held: Vec<_> = spans.iter().cloned().map(HeldSpan::hold).collect();
4570        assert!(matches!(held[0], HeldSpan::Color { .. }), "canonical stops pack");
4571        assert!(matches!(held[1], HeldSpan::Raw(_)), "a non-canonical stop keeps the span verbatim");
4572        assert!(matches!(held[2], HeldSpan::Raw(_)));
4573        assert!(matches!(held[3], HeldSpan::Raw(_)));
4574        let msg = Message { id: hex64(60), content: "0123456789".into(), text_spans: spans, ..Default::default() };
4575        assert_exact(&msg);
4576    }
4577
4578    #[test]
4579    fn edit_history_round_trips_exactly() {
4580        let edits = |v: &[(&str, u64)]| Some(v.iter().map(|&(c, at)| EditEntry { content: c.into(), edited_at: at }).collect::<Vec<_>>());
4581        let base = |content: &str, history| Message { id: hex64(70), content: content.into(), at: 1000, edited: true, edit_history: history, ..Default::default() };
4582        let cases = [
4583            base("v2", edits(&[("v1", 1000), ("v2", 2000)])),
4584            base("v1", edits(&[("v1", 1000), ("v2", 2000)])),
4585            base("", edits(&[("", 1000)])),
4586            base("x", edits(&[("b", 3000), ("x", 1000)])),
4587            base("same", edits(&[("same", 1000), ("same", 2000)])),
4588        ];
4589        for msg in cases {
4590            assert_exact(&msg);
4591        }
4592        let mut interner = NpubInterner::new();
4593        let tail = CompactMessage::from_message(&base("v2", edits(&[("v1", 1000), ("v2", 2000)])), &mut interner);
4594        let x = tail.extras.as_deref().unwrap();
4595        assert!(x.tail_is_content && x.edits[1].content.is_empty(), "the newest revision is held once");
4596    }
4597
4598    /// The edit rules on plain data, which the shared-tail history must reproduce.
4599    fn reference_apply(content: &mut String, history: &mut Vec<EditEntry>, at: u64, new: &str, edited_at: u64) {
4600        if history.is_empty() {
4601            history.push(EditEntry { content: content.clone(), edited_at: at });
4602        }
4603        if history.iter().any(|e| e.edited_at == edited_at) {
4604            return;
4605        }
4606        history.push(EditEntry { content: new.to_string(), edited_at });
4607        history.sort_by_key(|e| e.edited_at);
4608        if history.last().is_none_or(|e| e.edited_at == edited_at) {
4609            *content = new.to_string();
4610        }
4611    }
4612
4613    #[test]
4614    fn apply_edit_matches_the_reference_rules() {
4615        let mut seed = 0x2545_F491_4F6C_DD1Du64;
4616        let mut next = move |n: u64| {
4617            seed ^= seed << 13;
4618            seed ^= seed >> 7;
4619            seed ^= seed << 17;
4620            seed % n
4621        };
4622        for round in 0..400 {
4623            let at = 1000 + next(5) * 1000;
4624            let mut content = format!("c{}", next(3));
4625            let mut history: Vec<EditEntry> = Vec::new();
4626            // Some messages arrive already edited, a few out of order.
4627            if next(3) == 0 {
4628                for _ in 0..1 + next(3) {
4629                    history.push(EditEntry { content: format!("c{}", next(3)), edited_at: next(8) * 1000 });
4630                }
4631                history.dedup_by_key(|e| e.edited_at);
4632                if next(2) == 0 {
4633                    content = history.last().unwrap().content.clone();
4634                }
4635            }
4636            let msg = Message {
4637                id: hex64(round),
4638                content: content.clone(),
4639                at,
4640                edited: !history.is_empty(),
4641                edit_history: (!history.is_empty()).then(|| history.clone()),
4642                ..Default::default()
4643            };
4644            let mut interner = NpubInterner::new();
4645            let mut compact = CompactMessage::from_message(&msg, &mut interner);
4646            for _ in 0..next(6) {
4647                let new = format!("c{}", next(3));
4648                let edited_at = next(8) * 1000;
4649                reference_apply(&mut content, &mut history, at, &new, edited_at);
4650                compact.apply_edit(new, edited_at, Vec::new(), Vec::new(), &mut interner);
4651                let out = compact.to_message(&interner);
4652                assert_eq!(out.content, content, "round {round}");
4653                assert_eq!(out.edit_history.unwrap_or_default(), history, "round {round}");
4654                assert_eq!(compact.edit_history(), history, "round {round}");
4655            }
4656        }
4657    }
4658
4659    #[test]
4660    fn a_newest_edit_brings_its_emoji_and_spans() {
4661        use crate::text_spans::{ColorSpan, TextSpan};
4662        let mut interner = NpubInterner::new();
4663        let mut c = CompactMessage::from_message(&Message { id: hex64(80), content: "a".into(), at: 1000, ..Default::default() }, &mut interner);
4664        let span = TextSpan::Color(ColorSpan { from: 0, to: 1, effect: crate::text_color::Effect::Solid, colors: vec!["#f472b6".into()] });
4665        let tag = crate::types::EmojiTag { shortcode: "cat".into(), url: "https://e.example/cat.png".into() };
4666        c.apply_edit("b".into(), 2000, vec![tag.clone()], vec![span.clone()], &mut interner);
4667        c.apply_edit("older".into(), 1500, Vec::new(), Vec::new(), &mut interner);
4668        let out = c.to_message(&interner);
4669        assert_eq!(out.content, "b");
4670        assert_eq!(out.text_spans, vec![span]);
4671        assert_eq!(out.emoji_tags, vec![tag]);
4672        assert_eq!(out.edit_history.unwrap().iter().map(|e| e.content.as_str()).collect::<Vec<_>>(), ["a", "older", "b"]);
4673    }
4674
4675    // ========================================================================
4676    // Position index
4677    // ========================================================================
4678
4679    /// The index must hold every position once, ordered by the id at each.
4680    fn assert_index_sound(v: &CompactMessageVec) {
4681        assert_eq!(v.id_index.len(), v.messages.len());
4682        let mut seen = vec![false; v.messages.len()];
4683        for &p in &v.id_index {
4684            assert!(!std::mem::replace(&mut seen[p as usize], true), "position {p} twice");
4685        }
4686        for w in v.id_index.windows(2) {
4687            assert!(v.messages[w[0] as usize].id < v.messages[w[1] as usize].id, "index out of id order");
4688        }
4689        for w in v.messages.windows(2) {
4690            assert!(w[0].at <= w[1].at, "messages out of time order");
4691        }
4692        for m in &v.messages {
4693            assert_eq!(v.find_by_id(&m.id).map(|f| f.id), Some(m.id));
4694        }
4695    }
4696
4697    #[test]
4698    fn the_index_stays_sound_through_every_path() {
4699        let mut seed = 0x9E37_79B9_7F4A_7C15u64;
4700        let mut next = move |n: u64| {
4701            seed ^= seed << 13;
4702            seed ^= seed >> 7;
4703            seed ^= seed << 17;
4704            seed % n
4705        };
4706        let mut v = CompactMessageVec::new();
4707        let mut held: Vec<String> = Vec::new();
4708        let (mut serial, mut rekeys) = (0u64, 0u64);
4709        let mut fresh = |at: u64, held: &mut Vec<String>| {
4710            serial += 1;
4711            let id = hex64(serial);
4712            held.push(id.clone());
4713            make_compact_msg(&id, at)
4714        };
4715        for _ in 0..600 {
4716            let first = v.first().map_or(10_000, |m| m.at);
4717            let last = v.last().map_or(10_000, |m| m.at);
4718            match next(7) {
4719                0 => assert!(v.insert(fresh(last + next(3), &mut held))),
4720                1 => assert!(v.insert(fresh(first + next(last - first + 1), &mut held))),
4721                2 => {
4722                    let batch: Vec<_> = (0..1 + next(30)).map(|_| fresh(last + next(50), &mut held)).collect();
4723                    assert_eq!(v.insert_batch(batch.clone()), batch.len());
4724                    assert_eq!(v.insert_batch(batch), 0, "a repeated batch adds nothing");
4725                }
4726                3 => {
4727                    let batch: Vec<_> = (0..1 + next(30)).map(|_| fresh(first.saturating_sub(next(50)), &mut held)).collect();
4728                    v.insert_batch(batch);
4729                }
4730                4 => {
4731                    let batch: Vec<_> = (0..1 + next(30)).map(|_| fresh(first + next(last - first + 100), &mut held)).collect();
4732                    v.insert_batch(batch);
4733                }
4734                5 if !held.is_empty() => {
4735                    let id = held.swap_remove(next(held.len() as u64) as usize);
4736                    assert!(v.remove_by_hex_id(&id));
4737                    assert!(!v.contains_hex_id(&id));
4738                }
4739                6 if !held.is_empty() => {
4740                    let i = next(held.len() as u64) as usize;
4741                    rekeys += 1;
4742                    let new = hex64(1 << 40 | rekeys);
4743                    assert!(v.rekey(&encode_message_id(&held[i]), encode_message_id(&new)));
4744                    held[i] = new;
4745                }
4746                _ => {}
4747            }
4748            assert_index_sound(&v);
4749            assert_eq!(v.len(), held.len());
4750        }
4751        assert!(v.len() > 50);
4752        assert_eq!(v.retain_newest(50), held.len() - 50);
4753        assert_index_sound(&v);
4754        assert_eq!(v.memory_usage(), 50 * (std::mem::size_of::<CompactMessage>() + 4), "eviction hands capacity back");
4755    }
4756
4757    #[test]
4758    fn a_live_message_grows_a_loaded_chat_by_an_eighth() {
4759        let mut v = CompactMessageVec::new();
4760        v.insert_batch((0..1000u64).map(|n| make_compact_msg(&hex64(n), n)));
4761        let loaded = v.memory_usage();
4762        assert_eq!(loaded, 1000 * (std::mem::size_of::<CompactMessage>() + 4), "a page loads at exact capacity");
4763        assert!(v.insert(make_compact_msg(&hex64(5000), 5000)));
4764        assert_eq!(v.memory_usage(), 1125 * (std::mem::size_of::<CompactMessage>() + 4));
4765        // Older pages join without slack; the next arrival grows again by an eighth.
4766        v.insert_batch((0..200u64).map(|n| make_compact_msg(&hex64(10_000 + n), 0)));
4767        assert_index_sound(&v);
4768        assert_eq!(v.messages.capacity(), 1201);
4769    }
4770}