1use crate::*;
5use std::borrow::Cow;
6
7pub struct Heading<'a> {
11 raw: &'a [u8],
12 pairs: Vec<(&'a [u8], Cow<'a, [u8]>)>,
13 raw_pairs: Vec<(&'a [u8], &'a [u8])>,
14}
15
16impl<'a> Heading<'a> {
17 pub(crate) fn new(
18 raw: &'a [u8],
19 pairs: Vec<(&'a [u8], Cow<'a, [u8]>)>,
20 raw_pairs: Vec<(&'a [u8], &'a [u8])>,
21 ) -> Self {
22 Heading {
23 raw,
24 pairs,
25 raw_pairs,
26 }
27 }
28
29 pub fn empty() -> Self {
31 Heading {
32 raw: &[],
33 pairs: Vec::new(),
34 raw_pairs: Vec::new(),
35 }
36 }
37
38 pub fn raw(&self) -> &'a [u8] {
40 self.raw
41 }
42
43 pub fn pairs(&self) -> &[(&'a [u8], Cow<'a, [u8]>)] {
46 &self.pairs
47 }
48
49 pub fn get(&self, key: &str) -> Option<&[u8]> {
51 let mut found = None;
52 for (k, v) in &self.pairs {
53 if *k == key.as_bytes() {
54 found = Some(v.as_ref());
55 }
56 }
57 found
58 }
59
60 pub fn keys(&self) -> Vec<&'a [u8]> {
62 self.pairs.iter().map(|(k, _)| *k).collect()
63 }
64
65 pub fn shape(&self) -> Option<&str> {
67 self.get("shape").and_then(|v| std::str::from_utf8(v).ok())
68 }
69
70 pub fn version(&self) -> u32 {
72 self.get("version")
73 .and_then(|v| std::str::from_utf8(v).ok())
74 .and_then(|s| s.parse().ok())
75 .unwrap_or(1)
76 }
77
78 pub fn schema(&self) -> Option<&[u8]> {
81 self.get("schema")
82 }
83
84 pub fn raw_blob(&self) -> Option<&'a [u8]> {
86 let mut found = None;
87 for (k, v) in &self.raw_pairs {
88 if *k == b"blob" {
89 found = Some(*v);
90 }
91 }
92 found
93 }
94
95 pub fn blob(&self) -> Result<Option<Body<'a>>> {
97 match self.raw_blob() {
98 Some(raw) if is_level(raw) => Body::of_level(raw).map(Some),
99 _ => Ok(None),
100 }
101 }
102
103 pub fn is_empty(&self) -> bool {
104 self.pairs.is_empty()
105 }
106}
107
108const KNOWN_KEYS: [&[u8]; 4] = [b"shape", b"schema", b"version", b"blob"];
109const KNOWN_SHAPES: [&str; 2] = ["diff", "stream"];
110
111pub struct Document<'a> {
115 buf: &'a [u8],
116 heading: Heading<'a>,
117 body: Body<'a>,
118 start: usize,
119 stop: usize,
120 has_syn: bool,
121 has_eot: bool,
122 warnings: Vec<String>,
123}
124
125impl<'a> Document<'a> {
126 pub fn new(buf: &'a [u8]) -> Result<Self> {
128 Self::at(buf, 0)
129 }
130
131 pub fn at(buf: &'a [u8], start: usize) -> Result<Self> {
133 let mut parser = Parser::new(buf, false);
134 Self::parse(buf, start, buf.len(), &mut parser)
135 }
136
137 pub(crate) fn parse(
139 buf: &'a [u8],
140 start: usize,
141 stop: usize,
142 p: &mut Parser<'a>,
143 ) -> Result<Self> {
144 let mut warnings = Vec::new();
145 let mut pos = p.layout(start, stop);
146 let has_syn = pos < stop && buf[pos] == SYN;
147 let heading = if has_syn {
148 p.not_canonical("SYN in a canonical span");
149 let (h, after) = p.heading(pos + 1, stop)?;
150 pos = after;
151 h
152 } else {
153 warnings.push("no SYN at the start of the document".to_string());
154 Heading::empty()
155 };
156 let body_start = pos;
157 let (files, body_end) = p.body(pos, stop, false)?;
158 let body = Body::from_parts(buf, body_start, body_end, files);
159 pos = p.layout(body_end, stop);
160 let has_eot = pos < stop && buf[pos] == EOT;
161 if has_eot {
162 p.not_canonical("EOT in a canonical span");
163 pos += 1;
164 } else if heading.shape() != Some("stream") {
165 warnings.push("no EOT at the end of the document".to_string());
166 }
167 let mut seen: Vec<&[u8]> = Vec::new();
168 for k in heading.keys() {
169 let name = String::from_utf8_lossy(k);
170 if !KNOWN_KEYS.contains(&k) {
171 warnings.push(format!("unknown heading key '{name}'"));
172 }
173 if seen.contains(&k) {
174 warnings.push(format!("duplicate heading key '{name}': last wins"));
175 } else {
176 seen.push(k);
177 }
178 }
179 if let Some(shape) = heading.get("shape") {
180 let known = std::str::from_utf8(shape).is_ok_and(|s| KNOWN_SHAPES.contains(&s));
181 if !known {
182 warnings.push(format!(
183 "unknown shape '{}'",
184 String::from_utf8_lossy(shape)
185 ));
186 }
187 }
188 if let Some(v) = heading.get("version") {
189 if v != b"1" {
190 warnings.push(format!("unknown version '{}'", String::from_utf8_lossy(v)));
191 }
192 }
193 Ok(Document {
194 buf,
195 heading,
196 body,
197 start,
198 stop: pos,
199 has_syn,
200 has_eot,
201 warnings,
202 })
203 }
204
205 pub fn heading(&self) -> &Heading<'a> {
206 &self.heading
207 }
208
209 pub fn body(&self) -> &Body<'a> {
210 &self.body
211 }
212
213 pub fn start(&self) -> usize {
215 self.start
216 }
217
218 pub fn stop(&self) -> usize {
220 self.stop
221 }
222
223 pub fn has_syn(&self) -> bool {
224 self.has_syn
225 }
226
227 pub fn has_eot(&self) -> bool {
228 self.has_eot
229 }
230
231 pub fn warnings(&self) -> &[String] {
233 &self.warnings
234 }
235
236 pub fn raw(&self) -> &'a [u8] {
238 &self.buf[self.start..self.stop]
239 }
240
241 pub fn shape(&self) -> Option<&str> {
242 self.heading.shape()
243 }
244
245 pub fn name(&self) -> &'a [u8] {
248 self.body.name()
249 }
250
251 pub fn files(&self) -> &[FileView<'a>] {
252 self.body.files()
253 }
254
255 pub fn groups(&self) -> impl Iterator<Item = &Group<'a>> + '_ {
256 self.body.groups()
257 }
258
259 pub fn group_count(&self) -> usize {
260 self.body.group_count()
261 }
262
263 pub fn group(&self, i: usize) -> &Group<'a> {
264 self.body.group(i)
265 }
266
267 pub fn group_by_name(&self, name: &str) -> Result<&Group<'a>> {
268 self.body.group_by_name(name)
269 }
270
271 pub fn group_names(&self) -> Vec<&'a [u8]> {
272 self.body.group_names()
273 }
274
275 pub fn records(&self) -> &[Record<'a>] {
276 self.body.records()
277 }
278}
279
280pub struct Container<'a> {
283 documents: Vec<Document<'a>>,
284 tail: &'a [u8],
285 has_em: bool,
286 warnings: Vec<String>,
287}
288
289impl<'a> Container<'a> {
290 pub fn new(buf: &'a [u8]) -> Result<Self> {
291 let mut parser = Parser::new(buf, false);
292 Self::parse(buf, buf.len(), &mut parser)
293 }
294
295 pub(crate) fn parse(buf: &'a [u8], stop: usize, p: &mut Parser<'a>) -> Result<Self> {
298 let mut documents: Vec<Document<'a>> = Vec::new();
299 let mut tail: &'a [u8] = &[];
300 let mut has_em = false;
301 let mut warnings = Vec::new();
302 let mut pos = p.layout(0, stop);
303 let mut first = true;
304 while pos < stop {
305 if buf[pos] == EM {
306 p.not_canonical("EM in a canonical span");
307 has_em = true;
308 tail = &buf[pos + 1..];
309 break;
310 }
311 if !first && buf[pos] != SYN {
312 return Err(Error::syntax(
313 "a document after the first must begin with SYN",
314 pos,
315 ));
316 }
317 let doc = Document::parse(buf, pos, stop, p)?;
318 first = false;
319 pos = p.layout(doc.stop, stop);
320 let has_eot = doc.has_eot;
321 documents.push(doc);
322 if pos < stop && buf[pos] != SYN && buf[pos] != EM {
323 return Err(Error::syntax(
324 if has_eot {
325 "unexpected byte after EOT"
326 } else {
327 "unexpected byte after document"
328 },
329 pos,
330 ));
331 }
332 }
333 for (i, doc) in documents.iter().enumerate() {
334 let Some(raw) = doc.heading.raw_blob() else {
335 continue;
336 };
337 if i > 0 {
338 warnings.push("blob table in a later heading is ignored".to_string());
339 } else if !is_level(raw) {
340 warnings.push("blob is not a level: declares nothing".to_string());
341 } else {
342 let has_header = doc
343 .heading
344 .blob()
345 .ok()
346 .flatten()
347 .is_some_and(|b| b.groups().next().is_some_and(|g| g.has_header()));
348 if !has_header {
349 warnings.push("blob table has no header row: declares nothing".to_string());
350 }
351 }
352 }
353 if has_em
354 && documents
355 .first()
356 .is_none_or(|d| d.heading.raw_blob().is_none())
357 {
358 warnings.push("EM with no blob table: the region is unaddressable".to_string());
359 }
360 Ok(Container {
361 documents,
362 tail,
363 has_em,
364 warnings,
365 })
366 }
367
368 pub fn documents(&self) -> &[Document<'a>] {
370 &self.documents
371 }
372
373 pub fn first(&self) -> Option<&Document<'a>> {
375 self.documents.first()
376 }
377
378 pub fn tail(&self) -> &'a [u8] {
380 self.tail
381 }
382
383 pub fn has_em(&self) -> bool {
384 self.has_em
385 }
386
387 pub fn warnings(&self) -> &[String] {
390 &self.warnings
391 }
392
393 pub fn blob(&self) -> Result<Option<Body<'a>>> {
395 match self.documents.first() {
396 Some(d) => d.heading.blob(),
397 None => Ok(None),
398 }
399 }
400
401 pub fn blob_bytes(&self, name: &str) -> Result<Option<&'a [u8]>> {
404 let Some(table) = self.blob()? else {
405 return Ok(None);
406 };
407 let Some(g) = table.groups().next() else {
408 return Ok(None);
409 };
410 let ni = g.column("name").unwrap_or(0);
411 let oi = g.column("offset").unwrap_or(1);
412 let li = g.column("length").unwrap_or(2);
413 let mut found = None;
414 for r in g.records() {
415 if r.value(ni)?.as_ref() != name.as_bytes() {
416 continue;
417 }
418 let off = parse_usize(&r.value(oi)?);
419 let len = parse_usize(&r.value(li)?);
420 if let (Some(off), Some(len)) = (off, len) {
421 found = self.tail.get(off..off + len);
422 }
423 }
424 Ok(found)
425 }
426}
427
428fn parse_usize(v: &[u8]) -> Option<usize> {
429 std::str::from_utf8(v).ok()?.trim().parse().ok()
430}