Skip to main content

wacore_binary/
token.rs

1pub const DICT_VERSION: u8 = 3;
2
3// --- Public Constants for Special Tags ---
4pub const LIST_EMPTY: u8 = 0;
5pub const DICTIONARY_0: u8 = 236;
6pub const DICTIONARY_1: u8 = 237;
7pub const DICTIONARY_2: u8 = 238;
8pub const DICTIONARY_3: u8 = 239;
9
10pub const JID_PAIR: u8 = 250;
11pub const HEX_8: u8 = 251;
12pub const BINARY_8: u8 = 252;
13pub const BINARY_20: u8 = 253;
14pub const BINARY_32: u8 = 254;
15pub const NIBBLE_8: u8 = 255;
16pub const INTEROP_JID: u8 = 245;
17pub const FB_JID: u8 = 246;
18pub const AD_JID: u8 = 247;
19pub const LIST_8: u8 = 248;
20pub const LIST_16: u8 = 249;
21
22pub const PACKED_MAX: u8 = 127;
23pub const SINGLE_BYTE_MAX: u16 = 256;
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum TokenKind {
27    Single(u8),
28    Double(u8, u8),
29}
30
31include!("token_maps.generated.rs");
32
33/// The table uses open addressing. Keys of up to four bytes match their
34/// padded u32 exactly. Longer keys match a two-load signature and are
35/// compared byte for byte on signature hits. A miss skips the full comparison.
36#[inline]
37pub fn index_of_token(token: &str) -> Option<TokenKind> {
38    lookup_bytes(token.as_bytes())
39}
40
41#[inline(always)]
42fn decode_kind(kind: u16) -> TokenKind {
43    if kind < SINGLE_BYTE_MAX {
44        TokenKind::Single(kind as u8)
45    } else {
46        TokenKind::Double((kind >> 8) as u8 - 1, kind as u8)
47    }
48}
49
50#[inline(always)]
51fn lookup_bytes(key: &[u8]) -> Option<TokenKind> {
52    let len = key.len();
53    if len == 0 || len > MAX_TOKEN_LEN {
54        return None;
55    }
56    // Key derivation must mirror the generator. For len <= 4 the padded
57    // word IS the key (tokens are NUL-free, so padding can't collide with
58    // real bytes) and the meta tag pins the exact length; longer keys match
59    // a signature and byte-verify against the length-prefixed blob. In both
60    // loops 0 marks an empty slot (the generator rejects zero keys), so most
61    // misses stop on the first load, and a false key match — an alias across
62    // the short/long split or a signature collision — just keeps probing:
63    // the real owner may live further down the chain.
64    if len <= 4 {
65        let x = match *key {
66            [a] => a as u32,
67            [a, b] => u32::from_le_bytes([a, b, 0, 0]),
68            [a, b, c] => u32::from_le_bytes([a, b, c, 0]),
69            _ => u32::from_le_bytes([key[0], key[1], key[2], key[3]]),
70        };
71        let mut h = (x.wrapping_mul(TOK_MUL) >> TOK_SHIFT) as usize;
72        loop {
73            let k = TOK_KEYS[h];
74            if k == 0 {
75                return None;
76            }
77            if k == x {
78                let meta = TOK_META[h];
79                if (meta >> 11) as usize == len - 1 {
80                    return Some(decode_kind(meta & 0x7FF));
81                }
82            }
83            h = (h + 1) & TOK_MASK;
84        }
85    }
86    let head = u32::from_le_bytes([key[0], key[1], key[2], key[3]]);
87    let tail = u32::from_le_bytes([key[len - 4], key[len - 3], key[len - 2], key[len - 1]]);
88    let x = head.rotate_left(11) ^ tail ^ (len as u32).wrapping_mul(0x9E37_79B1);
89    let mut h = (x.wrapping_mul(TOK_MUL) >> TOK_SHIFT) as usize;
90    loop {
91        let k = TOK_KEYS[h];
92        if k == 0 {
93            return None;
94        }
95        if k == x {
96            let meta = TOK_META[h];
97            if meta >> 11 == 31 {
98                let off = TOK_OFF[h] as usize;
99                if TOK_BLOB[off] as usize == len && &TOK_BLOB[off + 1..off + 1 + len] == key {
100                    return Some(decode_kind(meta & 0x7FF));
101                }
102            }
103        }
104        h = (h + 1) & TOK_MASK;
105    }
106}
107
108pub fn get_single_token(index: u8) -> Option<&'static str> {
109    SINGLE_BYTE_TOKENS.get(index as usize).copied()
110}
111
112pub fn get_double_token(dict: u8, index: u8) -> Option<&'static str> {
113    DOUBLE_BYTE_TOKENS
114        .get(dict as usize)
115        .and_then(|d| d.get(index as usize))
116        .copied()
117}
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122
123    #[test]
124    fn test_single_byte_token_roundtrip() {
125        for i in 1u8..=235 {
126            if let Some(token) = get_single_token(i) {
127                let result = index_of_token(token);
128                assert!(
129                    matches!(result, Some(TokenKind::Single(idx)) if idx == i),
130                    "Token '{}' at index {} doesn't round-trip",
131                    token,
132                    i,
133                );
134            }
135        }
136    }
137
138    #[test]
139    fn test_double_byte_token_roundtrip() {
140        for dict in 0..4u8 {
141            for idx in 0..255u8 {
142                if let Some(token) = get_double_token(dict, idx) {
143                    let result = index_of_token(token);
144                    assert!(
145                        matches!(result, Some(TokenKind::Double(d, i)) if d == dict && i == idx),
146                        "Token '{}' at dict {} index {} doesn't round-trip",
147                        token,
148                        dict,
149                        idx,
150                    );
151                }
152            }
153        }
154    }
155
156    #[test]
157    fn test_unknown_string_returns_none() {
158        assert!(index_of_token("xyzzy_not_a_token_12345").is_none());
159    }
160
161    #[test]
162    fn test_empty_string_returns_none() {
163        assert!(index_of_token("").is_none());
164    }
165
166    #[test]
167    fn test_token_boundary_indices() {
168        let token_0 = get_single_token(0);
169        assert_eq!(token_0, Some(""), "Index 0 should be empty string token");
170        assert!(get_single_token(LIST_8).is_none());
171        assert!(get_single_token(LIST_16).is_none());
172        assert!(get_single_token(JID_PAIR).is_none());
173        assert!(get_single_token(HEX_8).is_none());
174        assert!(get_single_token(BINARY_8).is_none());
175        assert!(get_single_token(BINARY_20).is_none());
176        assert!(get_single_token(BINARY_32).is_none());
177        assert!(get_single_token(NIBBLE_8).is_none());
178    }
179
180    #[test]
181    fn test_almost_matching_strings() {
182        let token = get_single_token(1).expect("single token at index 1 must exist");
183        assert!(index_of_token(&format!("{}_modified", token)).is_none());
184        assert!(index_of_token(&format!("prefix_{}", token)).is_none());
185        assert!(index_of_token(&format!("{}!", token)).is_none());
186    }
187
188    #[test]
189    fn test_out_of_bounds_dictionary() {
190        assert!(get_double_token(4, 0).is_none());
191        assert!(get_double_token(5, 100).is_none());
192        assert!(get_double_token(255, 0).is_none());
193    }
194
195    /// Exhaustive equivalence guard: against a reference map built from the token
196    /// tables, every one-byte input and every single-byte mutation (all 256
197    /// values) of every token must resolve to the reference value (the token or
198    /// `None`). Probes the length-bucketed lookup for any discriminator collision
199    /// that would silently map a non-token (a JID/id) onto a token and corrupt the
200    /// wire, and stays durable against future token-set edits.
201    ///
202    /// Ignored under Miri: ~3M lookups (every byte position of every token,
203    /// times 256) is minutes of interpretation for a table probe that holds no
204    /// `unsafe` and no raw pointers, so there is nothing there for the
205    /// interpreter to find.
206    #[test]
207    #[cfg_attr(miri, ignore)]
208    fn lookup_matches_reference_under_byte_mutation() {
209        use std::collections::HashMap;
210
211        let mut reference: HashMap<Vec<u8>, TokenKind> = HashMap::new();
212        for i in 0u8..=235 {
213            if let Some(t) = get_single_token(i) {
214                reference
215                    .entry(t.as_bytes().to_vec())
216                    .or_insert(TokenKind::Single(i));
217            }
218        }
219        for dict in 0..4u8 {
220            for idx in 0..=255u8 {
221                if let Some(t) = get_double_token(dict, idx) {
222                    reference
223                        .entry(t.as_bytes().to_vec())
224                        .or_insert(TokenKind::Double(dict, idx));
225                }
226            }
227        }
228
229        let check = |bytes: &[u8]| {
230            assert_eq!(
231                lookup_bytes(bytes),
232                reference.get(bytes).copied(),
233                "lookup disagrees with reference for {bytes:?}",
234            );
235        };
236
237        for b in 0u8..=255 {
238            check(&[b]);
239        }
240
241        let keys: Vec<Vec<u8>> = reference.keys().cloned().collect();
242        for key in &keys {
243            let mut m = key.clone();
244            for pos in 0..m.len() {
245                let orig = m[pos];
246                for b in 0u8..=255 {
247                    m[pos] = b;
248                    check(&m);
249                }
250                m[pos] = orig;
251            }
252        }
253    }
254}