Skip to main content

wa_wire_codec/
value.rs

1//! A decoded scalar, in whatever form the frame carried it.
2//!
3//! Nothing here owns anything. A token is a `&'static str` from the table, raw
4//! bytes borrow from the frame, and the two forms that have no string in the
5//! buffer at all — packed digit runs and JIDs — stay in parts and render on
6//! demand. That is what lets the parser touch a 433 KB stanza without
7//! allocating.
8
9use core::fmt;
10
11use crate::jid::Jid;
12use crate::packed::Packed;
13
14/// A scalar read from a frame.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum Value<'a> {
17    /// An absent value.
18    Nil,
19    /// A token resolved through the table.
20    Token(&'a str),
21    /// Raw bytes. Text in an attribute position, opaque in a content position.
22    Bytes(&'a [u8]),
23    /// A packed nibble or hex run.
24    Packed(Packed<'a>),
25    /// A JID, held as parts.
26    Jid(Jid<'a>),
27}
28
29impl<'a> Value<'a> {
30    /// Whether this is the absent value.
31    #[must_use]
32    pub const fn is_nil(self) -> bool {
33        matches!(self, Self::Nil)
34    }
35
36    /// The value as a borrowed string, when one exists in the frame already.
37    ///
38    /// Returns `None` for packed runs and JIDs — not because they are not
39    /// textual, but because their text exists nowhere to borrow from. Use
40    /// [`eq_str`](Self::eq_str) to compare them, or `Display` to render them.
41    #[must_use]
42    pub fn as_str(self) -> Option<&'a str> {
43        match self {
44            Self::Token(token) => Some(token),
45            Self::Bytes(bytes) => core::str::from_utf8(bytes).ok(),
46            Self::Nil | Self::Packed(_) | Self::Jid(_) => None,
47        }
48    }
49
50    /// The value's bytes, when it is raw.
51    #[must_use]
52    pub const fn as_bytes(self) -> Option<&'a [u8]> {
53        match self {
54            Self::Bytes(bytes) => Some(bytes),
55            _ => None,
56        }
57    }
58
59    /// The JID, if this is one.
60    #[must_use]
61    pub const fn as_jid(self) -> Option<Jid<'a>> {
62        match self {
63            Self::Jid(jid) => Some(jid),
64            _ => None,
65        }
66    }
67
68    /// The packed run, if this is one.
69    #[must_use]
70    pub const fn as_packed(self) -> Option<Packed<'a>> {
71        match self {
72            Self::Packed(packed) => Some(packed),
73            _ => None,
74        }
75    }
76
77    /// Whether the value renders as exactly `other`, without building a string.
78    ///
79    /// This is the comparison L1 derivation actually needs — `attrs["type"] ==
80    /// "text"` and the like — so it must not allocate.
81    #[must_use]
82    pub fn eq_str(self, other: &str) -> bool {
83        match self {
84            Self::Nil => false,
85            Self::Token(token) => token == other,
86            Self::Bytes(bytes) => bytes == other.as_bytes(),
87            Self::Packed(packed) => packed.eq_str(other),
88            Self::Jid(jid) => {
89                let mut compare = StrEq::new(other);
90                // Writing into the comparator cannot fail; a mismatch just
91                // stops it matching.
92                let _ = fmt::write(&mut compare, format_args!("{jid}"));
93                compare.finished()
94            }
95        }
96    }
97
98    /// Whether two values mean the same thing, whatever form each arrived in.
99    ///
100    /// This is the comparison a conformance run needs. Two engines can encode
101    /// one value differently and both be right — a token here, the same text as
102    /// bytes there — and calling that a divergence would bury the real ones.
103    #[must_use]
104    pub fn semantic_eq(self, other: Value<'_>) -> bool {
105        match (self, other) {
106            (Self::Nil, Value::Nil) => true,
107            (Self::Jid(a), Value::Jid(b)) => a.semantic_eq(b),
108            (Self::Packed(a), Value::Packed(b)) => a.semantic_eq(b),
109            (Self::Packed(packed), textual) => {
110                textual.as_str().is_some_and(|text| packed.eq_str(text))
111            }
112            (textual, Value::Packed(packed)) => {
113                textual.as_str().is_some_and(|text| packed.eq_str(text))
114            }
115            // A JID compared against text renders once and matches or does not;
116            // `eq_str` walks the parts, so nothing is built.
117            (Self::Jid(jid), textual) => textual
118                .as_str()
119                .is_some_and(|text| Value::Jid(jid).eq_str(text)),
120            (textual, Value::Jid(jid)) => textual
121                .as_str()
122                .is_some_and(|text| Value::Jid(jid).eq_str(text)),
123            (a, b) => match (a.as_str(), b.as_str()) {
124                (Some(x), Some(y)) => x == y,
125                // Two byte strings that are not valid text still compare, since
126                // being unreadable does not make them unequal.
127                _ => match (a.as_bytes(), b.as_bytes()) {
128                    (Some(x), Some(y)) => x == y,
129                    _ => false,
130                },
131            },
132        }
133    }
134
135    /// Whether the value is textual in the sense the protocol means: anything
136    /// that appears in an attribute position.
137    #[must_use]
138    pub const fn is_textual(self) -> bool {
139        matches!(
140            self,
141            Self::Token(_) | Self::Bytes(_) | Self::Packed(_) | Self::Jid(_)
142        )
143    }
144}
145
146impl fmt::Display for Value<'_> {
147    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148        match self {
149            Self::Nil => Ok(()),
150            Self::Token(token) => f.write_str(token),
151            Self::Bytes(bytes) => match core::str::from_utf8(bytes) {
152                Ok(text) => f.write_str(text),
153                Err(_) => f.write_str("\u{FFFD}"),
154            },
155            Self::Packed(packed) => write!(f, "{packed}"),
156            Self::Jid(jid) => write!(f, "{jid}"),
157        }
158    }
159}
160
161/// Compares a `Display` rendering against a string as it is written, so a JID
162/// can be matched without being built.
163struct StrEq<'a> {
164    expected: &'a str,
165    matched: bool,
166}
167
168impl<'a> StrEq<'a> {
169    const fn new(expected: &'a str) -> Self {
170        Self {
171            expected,
172            matched: true,
173        }
174    }
175
176    /// Whether everything written matched and nothing was left over.
177    const fn finished(&self) -> bool {
178        self.matched && self.expected.is_empty()
179    }
180}
181
182impl fmt::Write for StrEq<'_> {
183    fn write_str(&mut self, chunk: &str) -> fmt::Result {
184        if !self.matched {
185            return Ok(());
186        }
187        match self.expected.strip_prefix(chunk) {
188            Some(rest) => self.expected = rest,
189            None => self.matched = false,
190        }
191        Ok(())
192    }
193}
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198    extern crate alloc;
199    use alloc::string::ToString;
200
201    use crate::jid::User;
202    use crate::packed::Alphabet;
203    use crate::token::{SERVER_LID, SERVER_PN};
204
205    fn packed() -> Packed<'static> {
206        Packed::new(Alphabet::Nibble, &[0x12, 0x34], false)
207    }
208
209    fn jid() -> Jid<'static> {
210        Jid::with_device(User::Token("5511"), SERVER_PN, 3)
211    }
212
213    #[test]
214    fn nil_is_absent_and_matches_nothing() {
215        let value = Value::Nil;
216        assert!(value.is_nil());
217        assert!(!value.is_textual());
218        assert_eq!(value.as_str(), None);
219        assert_eq!(value.as_bytes(), None);
220        assert_eq!(value.as_jid(), None);
221        assert_eq!(value.as_packed(), None);
222        assert_eq!(value.to_string(), "");
223        assert!(!value.eq_str(""), "nil is absent, not the empty string");
224    }
225
226    #[test]
227    fn tokens_borrow_from_the_table() {
228        let value = Value::Token("message");
229        assert!(!value.is_nil());
230        assert!(value.is_textual());
231        assert_eq!(value.as_str(), Some("message"));
232        assert_eq!(value.as_bytes(), None);
233        assert_eq!(value.to_string(), "message");
234        assert!(value.eq_str("message"));
235        assert!(!value.eq_str("receipt"));
236    }
237
238    #[test]
239    fn bytes_read_as_text_when_they_are_valid_utf8() {
240        let value = Value::Bytes(b"hello");
241        assert_eq!(value.as_str(), Some("hello"));
242        assert_eq!(value.as_bytes(), Some(&b"hello"[..]));
243        assert_eq!(value.to_string(), "hello");
244        assert!(value.eq_str("hello"));
245        assert!(!value.eq_str("hell"));
246    }
247
248    #[test]
249    fn invalid_utf8_stays_readable_as_bytes() {
250        let value = Value::Bytes(&[0xff, 0xfe]);
251        assert_eq!(value.as_str(), None, "not valid text");
252        assert_eq!(value.as_bytes(), Some(&[0xff, 0xfe][..]));
253        assert_eq!(value.to_string(), "\u{FFFD}");
254        assert!(value.is_textual());
255    }
256
257    #[test]
258    fn packed_runs_have_no_borrowable_string_but_still_compare() {
259        let value = Value::Packed(packed());
260        assert_eq!(
261            value.as_str(),
262            None,
263            "the digits exist nowhere in the buffer"
264        );
265        assert_eq!(value.as_packed(), Some(packed()));
266        assert_eq!(value.to_string(), "1234");
267        assert!(value.eq_str("1234"));
268        assert!(!value.eq_str("123"));
269        assert!(value.is_textual());
270    }
271
272    #[test]
273    fn jids_compare_without_being_built() {
274        let value = Value::Jid(jid());
275        assert_eq!(value.as_str(), None);
276        assert_eq!(value.as_jid(), Some(jid()));
277        assert_eq!(value.to_string(), "5511:3@s.whatsapp.net");
278        assert!(value.eq_str("5511:3@s.whatsapp.net"));
279        assert!(!value.eq_str("5511@s.whatsapp.net"), "device differs");
280        assert!(!value.eq_str("5511:3@lid"), "server differs");
281        assert!(!value.eq_str("5511:3@s.whatsapp.ne"), "truncated");
282        assert!(
283            !value.eq_str("5511:3@s.whatsapp.nett"),
284            "expected string left over"
285        );
286        assert!(!value.eq_str(""));
287    }
288
289    #[test]
290    fn jid_comparison_handles_a_bare_server() {
291        let value = Value::Jid(Jid::pair(User::None, SERVER_LID));
292        assert!(value.eq_str("lid"));
293        assert!(!value.eq_str("@lid"));
294    }
295
296    #[test]
297    fn a_mismatch_early_in_a_jid_does_not_match_later() {
298        // Once the comparator diverges it must stay diverged, even if a later
299        // chunk would have lined up.
300        let value = Value::Jid(jid());
301        assert!(!value.eq_str("XXXX:3@s.whatsapp.net"));
302    }
303
304    #[test]
305    fn accessors_reject_the_wrong_variant() {
306        assert_eq!(Value::Token("t").as_jid(), None);
307        assert_eq!(Value::Token("t").as_packed(), None);
308        assert_eq!(Value::Jid(jid()).as_bytes(), None);
309        assert_eq!(Value::Packed(packed()).as_bytes(), None);
310        assert_eq!(Value::Packed(packed()).as_jid(), None);
311        assert_eq!(Value::Jid(jid()).as_packed(), None);
312    }
313
314    #[test]
315    fn semantic_equality_looks_past_the_encoding() {
316        // One engine sends a token, another the same text as bytes. Both right.
317        assert!(Value::Token("read").semantic_eq(Value::Bytes(b"read")));
318        assert!(Value::Bytes(b"read").semantic_eq(Value::Token("read")));
319        assert!(!Value::Token("read").semantic_eq(Value::Bytes(b"delivery")));
320
321        // A packed digit run against the same digits as text.
322        let digits = Packed::new(Alphabet::Nibble, &[0x12, 0x34], false);
323        assert!(Value::Packed(digits).semantic_eq(Value::Token("1234")));
324        assert!(Value::Token("1234").semantic_eq(Value::Packed(digits)));
325        assert!(Value::Packed(digits).semantic_eq(Value::Bytes(b"1234")));
326        assert!(!Value::Packed(digits).semantic_eq(Value::Token("1235")));
327
328        // A JID against its rendering.
329        assert!(Value::Jid(jid()).semantic_eq(Value::Bytes(b"5511:3@s.whatsapp.net")));
330        assert!(Value::Bytes(b"5511:3@s.whatsapp.net").semantic_eq(Value::Jid(jid())));
331        assert!(!Value::Jid(jid()).semantic_eq(Value::Bytes(b"5511@s.whatsapp.net")));
332    }
333
334    #[test]
335    fn semantic_equality_is_reflexive_across_every_variant() {
336        for value in [
337            Value::Nil,
338            Value::Token("t"),
339            Value::Bytes(b"b"),
340            Value::Packed(packed()),
341            Value::Jid(jid()),
342        ] {
343            assert!(value.semantic_eq(value), "{value:?} differs from itself");
344        }
345    }
346
347    #[test]
348    fn nil_is_not_semantically_anything_else() {
349        // Absent is not the empty string, and not an empty digit run either.
350        for other in [
351            Value::Token(""),
352            Value::Bytes(b""),
353            Value::Packed(Packed::new(Alphabet::Nibble, &[], false)),
354            Value::Jid(jid()),
355        ] {
356            assert!(!Value::Nil.semantic_eq(other), "{other:?}");
357            assert!(!other.semantic_eq(Value::Nil), "{other:?}");
358        }
359    }
360
361    #[test]
362    fn unreadable_bytes_still_compare_to_themselves() {
363        // Not valid text, so `as_str` gives nothing — but identical bytes are
364        // not a divergence.
365        let invalid = Value::Bytes(&[0xff, 0xfe]);
366        assert!(invalid.semantic_eq(Value::Bytes(&[0xff, 0xfe])));
367        assert!(!invalid.semantic_eq(Value::Bytes(&[0xff, 0xfd])));
368        assert!(!invalid.semantic_eq(Value::Token("x")));
369        assert!(!invalid.semantic_eq(Value::Packed(packed())));
370    }
371
372    #[test]
373    fn values_are_comparable() {
374        assert_eq!(Value::Token("a"), Value::Token("a"));
375        assert_ne!(Value::Token("a"), Value::Token("b"));
376        assert_ne!(Value::Token("a"), Value::Bytes(b"a"));
377        assert!(!alloc::format!("{:?}", Value::Nil).is_empty());
378    }
379}