1use 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
19const LINEAR_SCAN_LIMIT: usize = 32;
30
31const 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 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
82fn 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
99fn write_utf(out: &mut impl Write, s: &str) -> Result<()> {
101 write_bytes_blob(out, s.as_bytes())
102}
103
104pub struct AbxWriter<W: Write> {
109 writer: W,
110 pool: InternedPool,
111}
112
113impl<W: Write> AbxWriter<W> {
114 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 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 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 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 pub fn into_inner(self) -> W {
204 self.writer
205 }
206}