Skip to main content

i8051_disassembler/
note.rs

1use std::collections::{BTreeMap, BTreeSet};
2use std::fmt;
3use std::ops::RangeBounds;
4use std::str::FromStr;
5
6use serde::{Deserialize, Deserializer, Serialize};
7use xxhash_rust::xxh64::xxh64;
8
9use crate::address::{AddressRange, AddressSpace, AddressValue};
10
11const BASE32: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
12
13/// A lexicographically sortable note identifier (fixed-width base32, 26 chars).
14///
15/// The 128-bit value uses Lamport depth in the high 64 bits and a content hash in
16/// the low 64 bits. The ID is assigned once and never recomputed. Fixed-width
17/// encoding makes string order identical to numeric Lamport order.
18#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize)]
19#[serde(transparent)]
20pub struct NoteId(String);
21
22impl NoteId {
23    pub const ENCODED_LEN: usize = 26;
24
25    /// Allocate the next ID after `previous_tip` for `content`.
26    pub fn allocate(previous_tip: Option<&Self>, content: &str) -> Self {
27        let depth = previous_tip.map(Self::depth).unwrap_or(0).saturating_add(1);
28        let hash = hash_payload(previous_tip, content);
29        Self::from_parts(depth, hash)
30    }
31
32    /// Return the Lamport tip from an iterator of existing note IDs.
33    pub fn tip<'a>(ids: impl IntoIterator<Item = &'a Self>) -> Option<Self> {
34        ids.into_iter().max().cloned()
35    }
36
37    pub fn as_str(&self) -> &str {
38        &self.0
39    }
40
41    pub fn depth(&self) -> u64 {
42        decode(self.as_str()).0
43    }
44
45    pub fn hash(&self) -> u64 {
46        decode(self.as_str()).1
47    }
48
49    fn from_parts(depth: u64, hash: u64) -> Self {
50        let value = ((depth as u128) << 64) | (hash as u128);
51        Self(encode(value))
52    }
53}
54
55impl<'de> Deserialize<'de> for NoteId {
56    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
57    where
58        D: Deserializer<'de>,
59    {
60        let value = String::deserialize(deserializer)?;
61        Self::from_str(&value).map_err(serde::de::Error::custom)
62    }
63}
64
65impl fmt::Debug for NoteId {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        f.debug_tuple("NoteId").field(&self.0).finish()
68    }
69}
70
71impl fmt::Display for NoteId {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        f.write_str(&self.0)
74    }
75}
76
77impl FromStr for NoteId {
78    type Err = NoteIdError;
79
80    fn from_str(value: &str) -> Result<Self, Self::Err> {
81        if value.is_empty() || value.len() > Self::ENCODED_LEN {
82            return Err(NoteIdError::InvalidLength);
83        }
84        let (depth, hash) = try_decode(value)?;
85        Ok(Self::from_parts(depth, hash))
86    }
87}
88
89impl AsRef<str> for NoteId {
90    fn as_ref(&self) -> &str {
91        self.as_str()
92    }
93}
94
95#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96pub enum NoteIdError {
97    InvalidLength,
98    InvalidCharacter,
99}
100
101impl fmt::Display for NoteIdError {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        match self {
104            Self::InvalidLength => write!(
105                f,
106                "note id must be 1..={} base32 characters",
107                NoteId::ENCODED_LEN
108            ),
109            Self::InvalidCharacter => write!(f, "note id contains invalid base32 character"),
110        }
111    }
112}
113
114impl std::error::Error for NoteIdError {}
115
116/// A dotted global path (`a.b.c`) into the shared note namespace.
117#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
118#[serde(transparent)]
119pub struct NotePath(String);
120
121impl NotePath {
122    pub fn parse(path: &str) -> Result<Self, NotePathError> {
123        if path.is_empty() {
124            return Err(NotePathError::Empty);
125        }
126        if path.starts_with('.') || path.ends_with('.') || path.contains("..") {
127            return Err(NotePathError::Invalid);
128        }
129        for segment in path.split('.') {
130            if segment.is_empty() {
131                return Err(NotePathError::Invalid);
132            }
133        }
134        Ok(Self(path.to_string()))
135    }
136
137    pub fn as_str(&self) -> &str {
138        &self.0
139    }
140
141    pub fn segments(&self) -> impl Iterator<Item = &str> {
142        self.0.split('.')
143    }
144}
145
146impl fmt::Display for NotePath {
147    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148        f.write_str(&self.0)
149    }
150}
151
152impl FromStr for NotePath {
153    type Err = NotePathError;
154
155    fn from_str(value: &str) -> Result<Self, Self::Err> {
156        Self::parse(value)
157    }
158}
159
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub enum NotePathError {
162    Empty,
163    Invalid,
164}
165
166impl fmt::Display for NotePathError {
167    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168        match self {
169            Self::Empty => write!(f, "note path must not be empty"),
170            Self::Invalid => write!(f, "note path must be dot-separated segments"),
171        }
172    }
173}
174
175impl std::error::Error for NotePathError {}
176
177#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
178pub enum NoteField {
179    String(String),
180    List(Vec<String>),
181}
182
183/// A disassembly note. The [`NoteId`] is fixed at creation; edits change
184/// [`content`](Self::content), tags, fields, and links only.
185#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
186pub struct Note {
187    pub id: NoteId,
188    pub content: String,
189    pub tags: BTreeSet<String>,
190    pub fields: BTreeMap<String, NoteField>,
191    pub links: BTreeSet<NoteId>,
192}
193
194impl Note {
195    pub fn new(previous_tip: Option<&NoteId>, content: impl Into<String>) -> Self {
196        let content = content.into();
197        let id = NoteId::allocate(previous_tip, &content);
198        Self {
199            id,
200            content,
201            tags: BTreeSet::new(),
202            fields: BTreeMap::new(),
203            links: BTreeSet::new(),
204        }
205    }
206
207    pub fn with_metadata(
208        previous_tip: Option<&NoteId>,
209        content: impl Into<String>,
210        tags: BTreeSet<String>,
211        fields: BTreeMap<String, NoteField>,
212        links: BTreeSet<NoteId>,
213    ) -> Self {
214        let mut note = Self::new(previous_tip, content);
215        note.tags = tags;
216        note.fields = fields;
217        note.links = links;
218        note
219    }
220
221    pub fn set_content(&mut self, content: impl Into<String>) {
222        self.content = content.into();
223    }
224}
225
226/// All notes keyed by opaque ID.
227#[derive(Debug, Default, Clone, PartialEq, Eq)]
228pub struct Notes {
229    by_id: BTreeMap<NoteId, Note>,
230}
231
232impl Notes {
233    pub fn insert(&mut self, note: Note) -> Option<Note> {
234        self.by_id.insert(note.id.clone(), note)
235    }
236
237    pub fn remove(&mut self, id: &NoteId) -> Option<Note> {
238        self.by_id.remove(id)
239    }
240
241    pub fn get(&self, id: &NoteId) -> Option<&Note> {
242        self.by_id.get(id)
243    }
244
245    pub fn tip(&self) -> Option<NoteId> {
246        self.by_id.keys().next_back().cloned()
247    }
248
249    pub fn create(&mut self, content: impl Into<String>) -> Note {
250        let note = Note::new(self.tip().as_ref(), content);
251        assert!(
252            self.by_id.insert(note.id.clone(), note.clone()).is_none(),
253            "duplicate note id"
254        );
255        note
256    }
257
258    pub fn iter(&self) -> impl Iterator<Item = (&NoteId, &Note)> {
259        self.by_id.iter()
260    }
261
262    pub fn len(&self) -> usize {
263        self.by_id.len()
264    }
265
266    pub fn is_empty(&self) -> bool {
267        self.by_id.is_empty()
268    }
269}
270
271/// A note located by a proximity query, tagged with how far the probe address
272/// sits from the note's range.
273#[derive(Debug, Clone, Copy)]
274pub struct ProximateNote<'a> {
275    /// Bytes between the probe address and the note's range (`0` if inside).
276    pub distance: AddressValue,
277    /// The address range the note is attached to.
278    pub range: AddressRange,
279    pub note: &'a Note,
280}
281
282/// Distance from a point to a half-open range: `0` when the point is inside.
283fn point_distance(range: AddressRange, addr: AddressValue) -> AddressValue {
284    if addr < range.start {
285        range.start - addr
286    } else if addr >= range.end {
287        addr - range.end + 1
288    } else {
289        0
290    }
291}
292
293/// Maps address ranges to note IDs within one address space.
294#[derive(Debug, Default, Clone, PartialEq, Eq)]
295pub struct NoteAddressIndex {
296    positions: rangemap::RangeMap<AddressValue, Vec<NoteId>>,
297    ranges: BTreeMap<NoteId, AddressRange>,
298}
299
300impl NoteAddressIndex {
301    pub fn insert(&mut self, range: AddressRange, id: NoteId) {
302        if let Some(old_range) = self.ranges.remove(&id) {
303            self.remove_id_from_positions(old_range, &id);
304        }
305        self.ranges.insert(id.clone(), range);
306        self.add_id_to_positions(range, id);
307    }
308
309    pub fn remove(&mut self, id: &NoteId) -> Option<AddressRange> {
310        let range = self.ranges.remove(id)?;
311        self.remove_id_from_positions(range, id);
312        Some(range)
313    }
314
315    pub fn range(&self, id: &NoteId) -> Option<AddressRange> {
316        self.ranges.get(id).copied()
317    }
318
319    pub fn overlapping<'a>(&'a self, range: AddressRange, notes: &'a Notes) -> Vec<&'a Note> {
320        self.positions
321            .overlapping(range.start..range.end)
322            .flat_map(|(_, ids)| ids.iter())
323            .filter_map(|id| notes.get(id))
324            .collect()
325    }
326
327    pub fn inside<'a>(&'a self, range: AddressRange, notes: &'a Notes) -> Vec<&'a Note> {
328        self.positions
329            .overlapping(range.start..range.end)
330            .flat_map(|(indexed, ids)| {
331                if range.start <= indexed.start && indexed.end <= range.end {
332                    ids.iter()
333                } else {
334                    [].iter()
335                }
336            })
337            .filter_map(|id| notes.get(id))
338            .collect()
339    }
340
341    /// Notes within `window` bytes of `addr`, paired with their distance
342    /// (`0` = the address falls inside the note's range), nearest first.
343    pub fn near<'a>(
344        &'a self,
345        addr: AddressValue,
346        window: AddressValue,
347        notes: &'a Notes,
348    ) -> Vec<ProximateNote<'a>> {
349        let lo = addr.saturating_sub(window);
350        let hi = addr.saturating_add(window).saturating_add(1);
351        let mut seen = BTreeSet::new();
352        let mut out = Vec::new();
353        for (_, ids) in self.positions.overlapping(lo..hi) {
354            for id in ids {
355                if !seen.insert(id.clone()) {
356                    continue;
357                }
358                let (Some(&range), Some(note)) = (self.ranges.get(id), notes.get(id)) else {
359                    continue;
360                };
361                let distance = point_distance(range, addr);
362                if distance <= window {
363                    out.push(ProximateNote {
364                        distance,
365                        range,
366                        note,
367                    });
368                }
369            }
370        }
371        out.sort_by(|a, b| {
372            a.distance
373                .cmp(&b.distance)
374                .then_with(|| a.note.id.cmp(&b.note.id))
375        });
376        out
377    }
378
379    fn add_id_to_positions(&mut self, range: AddressRange, id: NoteId) {
380        let mut ids = self.ids_at_exact_range(range);
381        if !ids.contains(&id) {
382            ids.push(id);
383        }
384        self.positions.remove(range.start..range.end);
385        self.positions.insert(range.start..range.end, ids);
386    }
387
388    fn remove_id_from_positions(&mut self, range: AddressRange, id: &NoteId) {
389        let ids: Vec<NoteId> = self
390            .ids_at_exact_range(range)
391            .into_iter()
392            .filter(|existing| existing != id)
393            .collect();
394        self.positions.remove(range.start..range.end);
395        if !ids.is_empty() {
396            self.positions.insert(range.start..range.end, ids);
397        }
398    }
399
400    fn ids_at_exact_range(&self, range: AddressRange) -> Vec<NoteId> {
401        self.positions
402            .overlapping(range.start..range.end)
403            .find(|(indexed, _)| indexed.start == range.start && indexed.end == range.end)
404            .map(|(_, ids)| ids.clone())
405            .unwrap_or_default()
406    }
407}
408
409/// Maps dotted global paths to note IDs.
410#[derive(Debug, Default, Clone, PartialEq, Eq)]
411pub struct NoteGlobalIndex {
412    paths: BTreeMap<NotePath, NoteId>,
413    by_id: BTreeMap<NoteId, NotePath>,
414}
415
416impl NoteGlobalIndex {
417    pub fn insert(&mut self, path: NotePath, id: NoteId) {
418        if let Some(old_path) = self.by_id.remove(&id) {
419            self.paths.remove(&old_path);
420        }
421        if let Some(old_id) = self.paths.remove(&path) {
422            self.by_id.remove(&old_id);
423        }
424        self.paths.insert(path.clone(), id.clone());
425        self.by_id.insert(id, path);
426    }
427
428    pub fn remove(&mut self, id: &NoteId) -> Option<NotePath> {
429        let path = self.by_id.remove(id)?;
430        self.paths.remove(&path);
431        Some(path)
432    }
433
434    pub fn path(&self, id: &NoteId) -> Option<&NotePath> {
435        self.by_id.get(id)
436    }
437
438    pub fn get<'a>(&'a self, path: &NotePath, notes: &'a Notes) -> Option<&'a Note> {
439        let id = self.paths.get(path)?;
440        notes.get(id)
441    }
442}
443
444/// Note storage and indexes sharing one ID namespace.
445#[derive(Debug, Default, Clone, PartialEq, Eq)]
446pub struct NoteDb {
447    pub notes: Notes,
448    pub global: NoteGlobalIndex,
449    address: BTreeMap<AddressSpace, NoteAddressIndex>,
450}
451
452impl NoteDb {
453    pub fn tip(&self) -> Option<NoteId> {
454        self.notes.tip()
455    }
456
457    pub fn create(&mut self, content: impl Into<String>) -> Note {
458        self.notes.create(content)
459    }
460
461    pub fn get(&self, id: &NoteId) -> Option<&Note> {
462        self.notes.get(id)
463    }
464
465    pub fn get_by_path(&self, path: &NotePath) -> Option<&Note> {
466        self.global.get(path, &self.notes)
467    }
468
469    pub fn address_index(&self, space: AddressSpace) -> Option<&NoteAddressIndex> {
470        self.address.get(&space)
471    }
472
473    pub fn set_address(&mut self, space: AddressSpace, range: AddressRange, note: Note) {
474        let id = note.id.clone();
475        self.notes.insert(note);
476        self.address.entry(space).or_default().insert(range, id);
477    }
478
479    pub fn set_global(&mut self, path: NotePath, note: Note) {
480        let id = note.id.clone();
481        self.notes.insert(note);
482        self.global.insert(path, id);
483    }
484
485    pub fn clear(&mut self, id: &NoteId) -> Option<Note> {
486        let note = self.notes.remove(id)?;
487        self.global.remove(id);
488        for index in self.address.values_mut() {
489            index.remove(id);
490        }
491        Some(note)
492    }
493
494    pub fn clear_address(&mut self, id: &NoteId) -> Option<(AddressSpace, AddressRange, Note)> {
495        let mut located = None;
496        for (&space, index) in &mut self.address {
497            if let Some(range) = index.remove(id) {
498                located = Some((space, range));
499                break;
500            }
501        }
502        let (space, range) = located?;
503        let note = self.notes.remove(id)?;
504        self.global.remove(id);
505        Some((space, range, note))
506    }
507
508    pub fn note_range(&self, space: AddressSpace, id: &NoteId) -> Option<AddressRange> {
509        self.address.get(&space)?.range(id)
510    }
511
512    pub fn get_notes_overlapping(
513        &self,
514        space: AddressSpace,
515        range: impl RangeBounds<AddressValue>,
516    ) -> Vec<&Note> {
517        let range = AddressRange::from(range);
518        self.address
519            .get(&space)
520            .map(|index| index.overlapping(range, &self.notes))
521            .unwrap_or_default()
522    }
523
524    pub fn get_notes_inside(
525        &self,
526        space: AddressSpace,
527        range: impl RangeBounds<AddressValue>,
528    ) -> Vec<&Note> {
529        let range = AddressRange::from(range);
530        self.address
531            .get(&space)
532            .map(|index| index.inside(range, &self.notes))
533            .unwrap_or_default()
534    }
535
536    /// Notes within `window` bytes of `addr` in `space`, nearest first, each
537    /// tagged with its distance (`0` = the address is inside the note).
538    pub fn notes_near(
539        &self,
540        space: AddressSpace,
541        addr: AddressValue,
542        window: AddressValue,
543    ) -> Vec<ProximateNote<'_>> {
544        self.address
545            .get(&space)
546            .map(|index| index.near(addr, window, &self.notes))
547            .unwrap_or_default()
548    }
549
550    /// Find where a note is attached, if it has an address location.
551    pub fn location(&self, id: &NoteId) -> Option<(AddressSpace, AddressRange)> {
552        self.address
553            .iter()
554            .find_map(|(&space, index)| index.range(id).map(|range| (space, range)))
555    }
556
557    /// Notes whose content, tags, or field values contain `query`
558    /// (case-insensitive). An empty query matches every note. Results are in
559    /// note-id (Lamport) order.
560    pub fn search(&self, query: &str) -> Vec<&Note> {
561        let needle = query.to_lowercase();
562        self.notes
563            .iter()
564            .map(|(_, note)| note)
565            .filter(|note| note_matches(note, &needle))
566            .collect()
567    }
568}
569
570/// Whether a note matches an already-lowercased search needle.
571fn note_matches(note: &Note, needle: &str) -> bool {
572    if needle.is_empty() {
573        return true;
574    }
575    if note.content.to_lowercase().contains(needle) {
576        return true;
577    }
578    if note
579        .tags
580        .iter()
581        .any(|tag| tag.to_lowercase().contains(needle))
582    {
583        return true;
584    }
585    note.fields.iter().any(|(key, value)| {
586        key.to_lowercase().contains(needle)
587            || match value {
588                NoteField::String(s) => s.to_lowercase().contains(needle),
589                NoteField::List(items) => items
590                    .iter()
591                    .any(|item| item.to_lowercase().contains(needle)),
592            }
593    })
594}
595
596fn hash_payload(previous_tip: Option<&NoteId>, content: &str) -> u64 {
597    match previous_tip {
598        None => xxh64(content.as_bytes(), 0),
599        Some(tip) => {
600            let tip_bytes = tip.as_str().as_bytes();
601            let content_bytes = content.as_bytes();
602            let mut combined = Vec::with_capacity(2 + tip_bytes.len() + 2 + content_bytes.len());
603            combined.extend_from_slice(&(tip_bytes.len() as u16).to_le_bytes());
604            combined.extend_from_slice(tip_bytes);
605            combined.extend_from_slice(&(content_bytes.len() as u16).to_le_bytes());
606            combined.extend_from_slice(content_bytes);
607            xxh64(&combined, 0)
608        }
609    }
610}
611
612fn encode(mut value: u128) -> String {
613    let mut buf = [0u8; NoteId::ENCODED_LEN];
614    for slot in buf.iter_mut().rev() {
615        *slot = BASE32[(value & 0x1F) as usize];
616        value >>= 5;
617    }
618    String::from_utf8(buf.to_vec()).expect("base32 alphabet is ascii")
619}
620
621fn decode(value: &str) -> (u64, u64) {
622    try_decode(value).expect("note id is canonical fixed-width")
623}
624
625fn try_decode(value: &str) -> Result<(u64, u64), NoteIdError> {
626    if value.is_empty() || value.len() > NoteId::ENCODED_LEN {
627        return Err(NoteIdError::InvalidLength);
628    }
629    let padded = format!(
630        "{:0>width$}",
631        value.to_ascii_uppercase(),
632        width = NoteId::ENCODED_LEN
633    );
634    let bytes = padded.as_bytes();
635    let msb = decode_base32(bytes[0]).ok_or(NoteIdError::InvalidCharacter)? as u128;
636    if msb > 0x7 {
637        return Err(NoteIdError::InvalidCharacter);
638    }
639    let mut lower = 0u128;
640    for (i, &byte) in bytes[1..].iter().enumerate() {
641        let digit = decode_base32(byte).ok_or(NoteIdError::InvalidCharacter)? as u128;
642        let shift = 5 * (bytes.len() - 2 - i);
643        lower |= digit << shift;
644    }
645    let bits = (msb << 125) | lower;
646    Ok(((bits >> 64) as u64, bits as u64))
647}
648
649fn decode_base32(byte: u8) -> Option<u8> {
650    match byte {
651        b'0'..=b'9' => Some(byte - b'0'),
652        b'A'..=b'H' => Some(byte - b'A' + 10),
653        b'J' | b'K' => Some(byte - b'A' + 10 - 1),
654        b'M' | b'N' => Some(byte - b'A' + 10 - 2),
655        b'P'..=b'T' => Some(byte - b'A' + 10 - 3),
656        b'V'..=b'Z' => Some(byte - b'A' + 10 - 4),
657        b'a'..=b'h' => Some(byte - b'a' + 10),
658        b'j' | b'k' => Some(byte - b'a' + 10 - 1),
659        b'm' | b'n' => Some(byte - b'a' + 10 - 2),
660        b'p'..=b't' => Some(byte - b'a' + 10 - 3),
661        b'v'..=b'z' => Some(byte - b'a' + 10 - 4),
662        _ => None,
663    }
664}
665
666#[cfg(test)]
667mod tests {
668    use super::*;
669
670    #[test]
671    fn ids_are_fixed_width() {
672        let id = NoteId::allocate(None, "hello");
673        assert_eq!(id.as_str().len(), NoteId::ENCODED_LEN);
674    }
675
676    #[test]
677    fn ids_sort_lamport() {
678        let first = Note::new(None, "alpha");
679        let second = Note::new(Some(&first.id), "beta");
680        let third = Note::new(Some(&second.id), "gamma");
681
682        assert!(first.id < second.id);
683        assert!(second.id < third.id);
684        assert_eq!(
685            NoteId::tip([&first.id, &second.id, &third.id]),
686            Some(third.id.clone())
687        );
688    }
689
690    #[test]
691    fn ids_sort_lexicographically() {
692        let first = Note::new(None, "alpha");
693        let second = Note::new(Some(&first.id), "beta");
694        let third = Note::new(Some(&second.id), "gamma");
695
696        let mut sorted = [
697            first.id.to_string(),
698            second.id.to_string(),
699            third.id.to_string(),
700        ];
701        sorted.sort();
702        assert_eq!(
703            sorted,
704            [
705                first.id.to_string(),
706                second.id.to_string(),
707                third.id.to_string()
708            ]
709        );
710        assert_eq!(sorted.last().unwrap(), &third.id.to_string());
711    }
712
713    #[test]
714    fn concurrent_notes_differ() {
715        let first = Note::new(None, "shared tip");
716        let left = Note::new(Some(&first.id), "branch a");
717        let right = Note::new(Some(&first.id), "branch b");
718
719        assert_eq!(left.id.depth(), right.id.depth());
720        assert_ne!(left.id, right.id);
721        assert_ne!(left.id.hash(), right.id.hash());
722    }
723
724    #[test]
725    fn create_advances_tip() {
726        let mut notes = Notes::default();
727        let first = notes.create("one");
728        let second = notes.create("two");
729        assert_ne!(first.id, second.id);
730        assert_eq!(notes.tip(), Some(second.id));
731    }
732
733    #[test]
734    fn editing_keeps_id() {
735        let mut note = Note::new(None, "original");
736        let id = note.id.clone();
737        note.set_content("edited body");
738        note.tags.insert("todo".into());
739        assert_eq!(note.id, id);
740    }
741
742    #[test]
743    fn replay_is_deterministic() {
744        let steps = ["map rom", "disassemble reset vector", "label main"];
745        let mut tip = None;
746        let mut ids = Vec::new();
747
748        for content in steps {
749            let note = Note::new(tip.as_ref(), content);
750            ids.push(note.id.to_string());
751            tip = Some(note.id);
752        }
753
754        assert_eq!(
755            ids,
756            [
757                "0000000000000G6MX6SW56W8JJ",
758                "00000000000016Q7FK68C75XDV",
759                "0000000000001PH81Q8ZKYJY1J",
760            ]
761        );
762    }
763
764    #[test]
765    fn encode_decode_roundtrip_values() {
766        for depth in [1u64, 2, 100, u64::MAX] {
767            for hash in [0u64, 1, 12345, u64::MAX] {
768                let value = ((depth as u128) << 64) | (hash as u128);
769                let encoded = encode(value);
770                let (decoded_depth, decoded_hash) = try_decode(&encoded).unwrap();
771                assert_eq!(decoded_depth, depth, "depth for {encoded}");
772                assert_eq!(decoded_hash, hash, "hash for {encoded}");
773                assert_eq!(
774                    encode(((decoded_depth as u128) << 64) | (decoded_hash as u128)),
775                    encoded,
776                    "re-encode for {encoded}"
777                );
778            }
779        }
780    }
781
782    #[test]
783    fn roundtrip_base32_encoding() {
784        let id = NoteId::allocate(None, "hello");
785        assert_eq!(id.as_str().len(), NoteId::ENCODED_LEN);
786        let parsed = id.as_str().parse::<NoteId>().unwrap();
787        assert_eq!(parsed, id);
788        assert_eq!(parsed.depth(), id.depth());
789        assert_eq!(parsed.hash(), id.hash());
790    }
791
792    #[test]
793    fn deserialize_canonicalizes_input() {
794        let id = NoteId::allocate(None, "hello");
795        let trimmed = id.as_str().trim_start_matches('0');
796        let parsed = trimmed.parse::<NoteId>().unwrap();
797        assert_eq!(parsed, id);
798    }
799
800    #[test]
801    fn overlap_finds_byte_note() {
802        let mut db = NoteDb::default();
803        let note = db.create("one byte");
804        db.set_address(
805            crate::platform::i8051::CODE,
806            AddressRange::from(4..5),
807            note.clone(),
808        );
809
810        assert_eq!(
811            db.get_notes_overlapping(crate::platform::i8051::CODE, 4..5)
812                .len(),
813            1
814        );
815        assert_eq!(
816            db.get_notes_inside(crate::platform::i8051::CODE, 4..5)
817                .len(),
818            1
819        );
820        // The adjacent byte must not match: the range is half-open `[4, 5)`.
821        assert!(
822            db.get_notes_overlapping(crate::platform::i8051::CODE, 5..6)
823                .is_empty()
824        );
825    }
826
827    #[test]
828    fn two_notes_both_retrievable() {
829        let mut db = NoteDb::default();
830        let range = AddressRange::from(0..4);
831        let human = db.create("human note on ISR");
832        let llm = db.create("llm note on ISR");
833        db.set_address(crate::platform::i8051::CODE, range, human.clone());
834        db.set_address(crate::platform::i8051::CODE, range, llm.clone());
835
836        let found = db.get_notes_inside(crate::platform::i8051::CODE, 0..4);
837        assert_eq!(found.len(), 2);
838        let ids: BTreeSet<_> = found.iter().map(|note| &note.id).collect();
839        assert!(ids.contains(&human.id));
840        assert!(ids.contains(&llm.id));
841    }
842
843    #[test]
844    fn notes_near_orders_distance() {
845        let mut db = NoteDb::default();
846        let a = db.create("note at 0x10");
847        let b = db.create("note at 0x40");
848        let c = db.create("far note at 0x200");
849        db.set_address(
850            crate::platform::i8051::CODE,
851            AddressRange::from(0x10..0x14),
852            a.clone(),
853        );
854        db.set_address(
855            crate::platform::i8051::CODE,
856            AddressRange::from(0x40..0x44),
857            b.clone(),
858        );
859        db.set_address(
860            crate::platform::i8051::CODE,
861            AddressRange::from(0x200..0x204),
862            c.clone(),
863        );
864
865        // Probe inside `a`'s range, with a window that reaches `b` but not `c`.
866        let near = db.notes_near(crate::platform::i8051::CODE, 0x12, 0x40);
867        assert_eq!(near.len(), 2, "c is outside the window");
868        assert_eq!(near[0].note.id, a.id);
869        assert_eq!(near[0].distance, 0, "probe is inside a");
870        assert_eq!(near[1].note.id, b.id);
871        assert_eq!(near[1].distance, 0x40 - 0x12);
872
873        // A different space has no notes.
874        assert!(
875            db.notes_near(crate::platform::i8051::XDATA, 0x12, 0x1000)
876                .is_empty()
877        );
878    }
879
880    #[test]
881    fn search_matches_case_insensitive() {
882        let mut db = NoteDb::default();
883        let mut isr = db.create("Reset Vector handler");
884        isr.tags.insert("isr".into());
885        db.notes.insert(isr.clone());
886        db.create("loop body");
887
888        assert_eq!(db.search("reset").len(), 1);
889        assert_eq!(db.search("ISR").len(), 1, "tag match, case-insensitive");
890        assert_eq!(db.search("body").len(), 1);
891        assert_eq!(db.search("").len(), 2, "empty query matches all");
892        assert!(db.search("nonexistent").is_empty());
893    }
894
895    #[test]
896    fn note_db_shares_namespace() {
897        let mut db = NoteDb::default();
898        let note = db.create("global and local");
899        let id = note.id.clone();
900        db.global
901            .insert(NotePath::parse("project.vt420").unwrap(), id.clone());
902        db.address
903            .entry(crate::platform::i8051::CODE)
904            .or_default()
905            .insert(AddressRange::from(0..4), id.clone());
906
907        assert_eq!(db.get(&id).unwrap().content, "global and local");
908        assert_eq!(
909            db.get_by_path(&NotePath::parse("project.vt420").unwrap())
910                .unwrap()
911                .id,
912            id
913        );
914        assert_eq!(
915            db.get_notes_inside(crate::platform::i8051::CODE, 0..4)
916                .len(),
917            1
918        );
919
920        db.clear(&id);
921        assert!(db.notes.is_empty());
922        assert!(
923            db.get_by_path(&NotePath::parse("project.vt420").unwrap())
924                .is_none()
925        );
926        assert!(
927            db.get_notes_overlapping(crate::platform::i8051::CODE, 0..4)
928                .is_empty()
929        );
930    }
931}