Skip to main content

android_abx/encode/
writer.rs

1//! [`AbxWriter`] — encodes [`Event`]s to the ABX wire format, the mechanical
2//! reverse of [`crate::AbxParser`]/[`crate::AbxStreamParser`]'s decoding.
3
4use std::collections::HashMap;
5use std::io::Write;
6
7use crate::{AbxError, Attribute, AttributeValue, Event, InternedStr, MAGIC, Result};
8use crate::{
9    CMD_ATTRIBUTE, CMD_CDSECT, CMD_COMMENT, CMD_DOCDECL, CMD_END_DOCUMENT, CMD_END_TAG,
10    CMD_ENTITY_REF, CMD_IGNORABLE_WHITESPACE, CMD_PROCESSING_INSTRUCTION, CMD_START_DOCUMENT,
11    CMD_START_TAG, CMD_TEXT,
12};
13use crate::{
14    INTERNED_NEW, TYPE_BOOLEAN_FALSE, TYPE_BOOLEAN_TRUE, TYPE_BYTES_BASE64, TYPE_BYTES_HEX,
15    TYPE_DOUBLE, TYPE_FLOAT, TYPE_INT, TYPE_INT_HEX, TYPE_LONG, TYPE_LONG_HEX, TYPE_NULL,
16    TYPE_STRING, TYPE_STRING_INTERNED,
17};
18
19/// Tracks tag/attribute names already written, so repeats become a `u16`
20/// back-reference instead of a fresh string. Covers names only, never
21/// attribute values — matches AOSP's `attribute()`, which never
22/// auto-interns a value.
23///
24/// Below `LINEAR_SCAN_LIMIT` unique names, scans `names` linearly instead
25/// of hashing — real documents repeat a small, bounded vocabulary of
26/// names, so scanning a short `Vec` beats hash overhead. A linear scan is
27/// O(n²) in the number of unique names though, so past the limit this
28/// switches to a `HashMap`.
29const LINEAR_SCAN_LIMIT: usize = 32;
30
31/// Largest length a `u16` wire length-prefix can express. Matches AOSP's
32/// `FastDataOutput.MAX_UNSIGNED_SHORT` — `writeUTF()` throws past this, and
33/// `BinaryXmlSerializer.attributeBytesHex`/`attributeBytesBase64` check it
34/// explicitly before writing anything.
35const MAX_UNSIGNED_SHORT: usize = 65_535;
36
37struct InternedPool {
38    names: Vec<InternedStr>,
39    index: Option<HashMap<InternedStr, u16>>,
40}
41
42impl InternedPool {
43    fn new() -> Self {
44        InternedPool {
45            names: Vec::new(),
46            index: None,
47        }
48    }
49
50    fn find(&self, s: &InternedStr) -> Option<u16> {
51        match &self.index {
52            Some(index) => index.get(s).copied(),
53            None => self.names.iter().position(|n| n == s).map(|i| i as u16),
54        }
55    }
56
57    fn write(&mut self, out: &mut impl Write, s: &InternedStr) -> Result<()> {
58        if let Some(idx) = self.find(s) {
59            out.write_all(&idx.to_be_bytes())?;
60        } else {
61            out.write_all(&INTERNED_NEW.to_be_bytes())?;
62            write_utf(out, s)?;
63
64            // 0xFFFF is the INTERNED_NEW sentinel, so indices only go up
65            // to 0xFFFE -- past that, stop caching. Matches real AOSP,
66            // which also keeps working past its cap instead of erroring;
67            // only uncached names lose the back-reference.
68            if self.names.len() < INTERNED_NEW as usize {
69                let idx = self.names.len() as u16;
70                self.names.push(s.clone());
71                if let Some(index) = &mut self.index {
72                    index.insert(s.clone(), idx);
73                } else if self.names.len() > LINEAR_SCAN_LIMIT {
74                    self.index = Some(self.names.iter().cloned().zip(0u16..).collect());
75                }
76            }
77        }
78        Ok(())
79    }
80}
81
82/// Errors (rather than truncating the `u16` length prefix, which would
83/// silently corrupt the stream for anything written after) when `bytes` is
84/// longer than a `u16` length can express — same boundary and same
85/// reject-don't-truncate behavior as AOSP's `writeUTF()`/
86/// `attributeBytesHex`/`attributeBytesBase64` length checks.
87fn write_bytes_blob(out: &mut impl Write, bytes: &[u8]) -> Result<()> {
88    if bytes.len() > MAX_UNSIGNED_SHORT {
89        return Err(AbxError::ValueTooLong {
90            len: bytes.len(),
91            max: MAX_UNSIGNED_SHORT,
92        });
93    }
94    out.write_all(&(bytes.len() as u16).to_be_bytes())?;
95    out.write_all(bytes)?;
96    Ok(())
97}
98
99/// See [`write_bytes_blob`] — same overflow check, for a UTF-8 string.
100fn write_utf(out: &mut impl Write, s: &str) -> Result<()> {
101    write_bytes_blob(out, s.as_bytes())
102}
103
104/// Encodes [`Event`]s to any `W: Write` sink. `Vec<u8>` covers the
105/// in-memory case (it implements `Write`); a file/socket/`BufWriter` covers
106/// streaming — unlike the decode side, writing has no ring-buffer/refill
107/// complexity to split across two types.
108pub struct AbxWriter<W: Write> {
109    writer: W,
110    pool: InternedPool,
111}
112
113impl<W: Write> AbxWriter<W> {
114    /// Create a writer, writing the 4-byte magic header immediately.
115    pub fn new(mut writer: W) -> Result<Self> {
116        writer.write_all(&MAGIC)?;
117        Ok(AbxWriter {
118            writer,
119            pool: InternedPool::new(),
120        })
121    }
122
123    /// Encode and write a single [`Event`].
124    pub fn write_event(&mut self, ev: &Event) -> Result<()> {
125        match ev {
126            Event::StartDocument => self.writer.write_all(&[CMD_START_DOCUMENT | TYPE_NULL])?,
127            Event::EndDocument => self.writer.write_all(&[CMD_END_DOCUMENT | TYPE_NULL])?,
128            Event::StartTag { name, attributes } => {
129                self.writer
130                    .write_all(&[TYPE_STRING_INTERNED | CMD_START_TAG])?;
131                self.pool.write(&mut self.writer, name)?;
132                for attr in attributes {
133                    self.write_attribute(attr)?;
134                }
135            }
136            Event::EndTag { name } => {
137                self.writer
138                    .write_all(&[TYPE_STRING_INTERNED | CMD_END_TAG])?;
139                self.pool.write(&mut self.writer, name)?;
140            }
141            Event::Text(s) => self.write_text_token(CMD_TEXT, s)?,
142            Event::CdataSection(s) => self.write_text_token(CMD_CDSECT, s)?,
143            Event::Comment(s) => self.write_text_token(CMD_COMMENT, s)?,
144            Event::ProcessingInstruction(s) => {
145                self.write_text_token(CMD_PROCESSING_INSTRUCTION, s)?
146            }
147            Event::EntityReference(s) => self.write_text_token(CMD_ENTITY_REF, s)?,
148            Event::IgnorableWhitespace(s) => self.write_text_token(CMD_IGNORABLE_WHITESPACE, s)?,
149            Event::DocDecl(s) => self.write_text_token(CMD_DOCDECL, s)?,
150        }
151        Ok(())
152    }
153
154    /// Shared shape for the seven text-bearing events: always `TYPE_STRING`
155    /// plus length-prefixed UTF-8, even for an empty string. Never
156    /// `TYPE_NULL` — real AOSP's own parser can't correctly read that form
157    /// back (a confirmed bug: it calls `readUTF()` unconditionally here,
158    /// unlike the `ATTRIBUTE` branch), so `TYPE_STRING` with an empty
159    /// payload is the only safe choice.
160    fn write_text_token(&mut self, cmd: u8, s: &str) -> Result<()> {
161        self.writer.write_all(&[TYPE_STRING | cmd])?;
162        write_utf(&mut self.writer, s)?;
163        Ok(())
164    }
165
166    /// Write one attribute: `type_nibble|CMD_ATTRIBUTE` + interned name +
167    /// the value's payload. `String` values are never interned — matches
168    /// AOSP's `attribute()`, which only interns the name.
169    fn write_attribute(&mut self, attr: &Attribute) -> Result<()> {
170        let type_nibble = match &attr.value {
171            AttributeValue::Null => TYPE_NULL,
172            AttributeValue::String(_) => TYPE_STRING,
173            AttributeValue::BytesHex(_) => TYPE_BYTES_HEX,
174            AttributeValue::BytesBase64(_) => TYPE_BYTES_BASE64,
175            AttributeValue::Int(_) => TYPE_INT,
176            AttributeValue::IntHex(_) => TYPE_INT_HEX,
177            AttributeValue::Long(_) => TYPE_LONG,
178            AttributeValue::LongHex(_) => TYPE_LONG_HEX,
179            AttributeValue::Float(_) => TYPE_FLOAT,
180            AttributeValue::Double(_) => TYPE_DOUBLE,
181            AttributeValue::Boolean(true) => TYPE_BOOLEAN_TRUE,
182            AttributeValue::Boolean(false) => TYPE_BOOLEAN_FALSE,
183        };
184        self.writer.write_all(&[type_nibble | CMD_ATTRIBUTE])?;
185        self.pool.write(&mut self.writer, &attr.name)?;
186        match &attr.value {
187            AttributeValue::Null | AttributeValue::Boolean(_) => {}
188            AttributeValue::String(s) => write_utf(&mut self.writer, s)?,
189            AttributeValue::BytesHex(b) | AttributeValue::BytesBase64(b) => {
190                write_bytes_blob(&mut self.writer, b)?
191            }
192            AttributeValue::Int(v) => self.writer.write_all(&v.to_be_bytes())?,
193            AttributeValue::IntHex(v) => self.writer.write_all(&v.to_be_bytes())?,
194            AttributeValue::Long(v) => self.writer.write_all(&v.to_be_bytes())?,
195            AttributeValue::LongHex(v) => self.writer.write_all(&v.to_be_bytes())?,
196            AttributeValue::Float(v) => self.writer.write_all(&v.to_be_bytes())?,
197            AttributeValue::Double(v) => self.writer.write_all(&v.to_be_bytes())?,
198        }
199        Ok(())
200    }
201
202    /// Unwrap the underlying writer.
203    pub fn into_inner(self) -> W {
204        self.writer
205    }
206}