1mod cmap;
43mod content;
44pub(crate) mod crypt;
45mod filter;
46pub(crate) mod font;
47pub(crate) mod lex;
48mod nav;
49mod object;
50mod render;
51pub(crate) mod tables;
52mod text;
53pub(crate) mod xref;
54
55pub use content::{Op, Ops};
56pub use nav::{Action, Annotation, Attachment, Dest, Field, FieldKind, Outline, Signature, View};
57pub use object::{text_string, Dict, Name, Object, Ref, Stream};
58pub use render::{FontQuery, FontSource, RenderOptions, SystemFonts};
59pub use text::{PageText, TextItem};
60
61use crate::{Date, Info};
62use alloc::collections::{BTreeMap, BTreeSet};
63use alloc::rc::Rc;
64use alloc::string::String;
65use alloc::vec::Vec;
66use core::cell::{Cell, OnceCell, RefCell};
67use xref::Entry;
68
69#[derive(Clone, Debug)]
71pub struct Options {
72 pub password: String,
74 pub max_stream: usize,
76}
77
78impl Default for Options {
79 fn default() -> Options {
80 Options { password: String::new(), max_stream: 256 << 20 }
81 }
82}
83
84#[derive(Clone, Copy, Debug, PartialEq, Eq)]
86#[non_exhaustive]
87pub enum Error {
88 NotPdf,
90 Damaged(&'static str),
92 Password,
94 Unsupported(&'static str),
97 Invalid(&'static str),
99 Limit(&'static str),
101 NoPage,
103}
104
105impl core::fmt::Display for Error {
106 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
107 match self {
108 Error::NotPdf => f.write_str("not a PDF file"),
109 Error::Damaged(s) => write!(f, "damaged: {s}"),
110 Error::Password => f.write_str("the password is missing or wrong"),
111 Error::Unsupported(s) => write!(f, "not supported: {s}"),
112 Error::Invalid(s) => write!(f, "invalid: {s}"),
113 Error::Limit(s) => write!(f, "limit: {s}"),
114 Error::NoPage => f.write_str("no such page"),
115 }
116 }
117}
118
119impl core::error::Error for Error {}
120
121#[derive(Clone, Debug)]
123pub struct Page {
124 pub obj: Option<Ref>,
126 pub media_box: [f64; 4],
128 pub crop_box: [f64; 4],
130 pub rotate: u16,
132 pub user_unit: f64,
134 pub dict: Dict,
136 pub resources: Dict,
137}
138
139impl Page {
140 pub fn size(&self) -> (f64, f64) {
142 let w = (self.crop_box[2] - self.crop_box[0]) * self.user_unit;
143 let h = (self.crop_box[3] - self.crop_box[1]) * self.user_unit;
144 if self.rotate % 180 == 90 { (h, w) } else { (w, h) }
145 }
146}
147
148struct ObjStm {
149 data: Vec<u8>,
150 first: usize,
151 index: Vec<(u32, usize)>,
153 by_num: BTreeMap<u32, usize>,
155}
156
157const MAX_CHAIN: u32 = 32;
159const MAX_LOAD_DEPTH: u32 = 8;
161const MAX_PAGES: usize = 1 << 20;
163const OBJSTM_DECODES: usize = 4;
167const OBJSTM_PER_BYTE: usize = 64;
168
169pub struct Document {
171 data: Vec<u8>,
172 xref: xref::Xref,
173 scan: OnceCell<BTreeMap<u32, (usize, u16)>>,
174 ends: OnceCell<lex::Ends>,
175 heads: OnceCell<xref::Heads>,
177 objstms: RefCell<BTreeMap<u32, Option<Rc<ObjStm>>>>,
178 objstm_held: Cell<usize>,
181 objstm_left: Cell<usize>,
182 crypt: Option<crypt::Crypt>,
183 encrypt_ref: Option<Ref>,
184 pages: Vec<Page>,
185 page_index: BTreeMap<Ref, usize>,
186 version: (u8, u8),
187 max_stream: usize,
188 render: render::Cache,
190 cidmaps: RefCell<BTreeMap<Vec<u8>, Option<Rc<cidmap::CMap>>>>,
192 cid_texts: RefCell<BTreeMap<cidmap::Collection, Rc<cidmap::ToUnicode>>>,
193}
194
195impl Document {
196 pub fn open(data: Vec<u8>) -> Result<Document, Error> {
198 Document::open_with(data, &Options::default())
199 }
200
201 pub fn open_with(data: Vec<u8>, opt: &Options) -> Result<Document, Error> {
202 let head = lex::find(&data[..data.len().min(1024)], b"%PDF-", 0);
203 let version = head
204 .map(|h| {
205 let d = |i: usize| data.get(h + i).filter(|c| c.is_ascii_digit()).map(|c| c - b'0');
206 (d(5).unwrap_or(1), d(7).unwrap_or(4))
207 })
208 .unwrap_or((1, 4));
209 let x = xref::load(&data);
210 if x.entries.is_empty() && head.is_none() {
211 return Err(Error::NotPdf);
212 }
213 let data_len = data.len();
214 let mut doc = Document {
215 data,
216 xref: x,
217 scan: OnceCell::new(),
218 ends: OnceCell::new(),
219 heads: OnceCell::new(),
220 objstms: RefCell::new(BTreeMap::new()),
221 objstm_held: Cell::new(0),
222 objstm_left: Cell::new(opt.max_stream.saturating_mul(OBJSTM_DECODES).saturating_add(data_len.saturating_mul(OBJSTM_PER_BYTE))),
223 crypt: None,
224 encrypt_ref: None,
225 pages: Vec::new(),
226 page_index: BTreeMap::new(),
227 version,
228 max_stream: opt.max_stream,
229 render: render::Cache::default(),
230 cidmaps: RefCell::new(BTreeMap::new()),
231 cid_texts: RefCell::new(BTreeMap::new()),
232 };
233 doc.setup_crypt(&opt.password)?;
234 if !doc.xref.repaired && doc.catalog().is_empty() {
236 let x = xref::scan(&doc.data);
237 doc.xref = x;
238 doc.objstms.borrow_mut().clear();
239 doc.objstm_held.set(0);
240 doc.setup_crypt(&opt.password)?;
241 }
242 if doc.xref.repaired {
243 doc.add_objstm_entries();
244 if doc.catalog().is_empty() {
245 let nums: Vec<u32> = doc.xref.entries.keys().copied().collect();
247 let found = nums.into_iter().rev().take(1 << 20).find(|&n| doc.get(Ref { num: n, generation: 0 }).as_dict().is_some_and(|d| d.is("Type", "Catalog")));
248 if let Some(n) = found {
249 doc.xref.trailer.insert("Root", Object::Ref(Ref { num: n, generation: 0 }));
250 }
251 }
252 }
253 if let Some(v) = doc.catalog().name("Version") {
254 if v.len() >= 3 && v[0].is_ascii_digit() && v[2].is_ascii_digit() && (v[0] - b'0', v[2] - b'0') > doc.version {
255 doc.version = (v[0] - b'0', v[2] - b'0');
256 }
257 }
258 doc.collect_pages();
259 if doc.pages.is_empty() && doc.catalog().is_empty() {
260 return Err(Error::Damaged("no catalog and no pages"));
261 }
262 Ok(doc)
263 }
264
265 fn setup_crypt(&mut self, password: &str) -> Result<(), Error> {
266 self.crypt = None;
267 self.encrypt_ref = None;
268 let Some(e) = self.xref.trailer.get("Encrypt").cloned() else { return Ok(()) };
269 if e.is_null() {
270 return Ok(());
271 }
272 self.encrypt_ref = e.as_ref();
273 let enc = match self.resolve(&e) {
274 Object::Dict(d) => d,
275 _ => return Err(Error::Damaged("the encryption dictionary")),
276 };
277 let id0 = match self.xref.trailer.get("ID") {
278 Some(Object::Array(a)) => a.first().and_then(Object::as_bytes).map(<[u8]>::to_vec).unwrap_or_default(),
279 _ => Vec::new(),
280 };
281 self.crypt = Some(crypt::Crypt::open(&enc, &id0, password)?);
282 Ok(())
283 }
284
285 fn add_objstm_entries(&mut self) {
287 let list = core::mem::take(&mut self.xref.objstms);
288 for s in list {
289 let Some(st) = self.objstm(s, 0) else { continue };
290 for (i, &(num, _)) in st.index.iter().enumerate() {
291 self.xref.entries.entry(num).or_insert((Entry::InStream(s, i as u32), 0));
292 }
293 }
294 }
295
296 pub fn version(&self) -> (u8, u8) {
298 self.version
299 }
300
301 pub fn is_encrypted(&self) -> bool {
302 self.crypt.is_some()
303 }
304
305 pub fn permissions(&self) -> Option<u32> {
309 self.crypt.as_ref().map(|c| c.permissions)
310 }
311
312 pub fn encryption_revision(&self) -> Option<u8> {
314 self.crypt.as_ref().map(|c| c.revision)
315 }
316
317 pub fn opened_as_owner(&self) -> bool {
319 self.crypt.as_ref().is_some_and(|c| c.owner)
320 }
321
322 pub fn was_repaired(&self) -> bool {
324 self.xref.repaired
325 }
326
327 pub fn trailer(&self) -> &Dict {
328 &self.xref.trailer
329 }
330
331 pub fn catalog(&self) -> Dict {
333 match self.xref.trailer.get("Root") {
334 Some(r) => self.dict(r),
335 None => Dict::new(),
336 }
337 }
338
339 pub fn data(&self) -> &[u8] {
341 &self.data
342 }
343
344 pub(crate) fn xref_entries(&self) -> &BTreeMap<u32, (Entry, u16)> {
346 &self.xref.entries
347 }
348
349 pub(crate) fn xref_start(&self) -> Option<(usize, bool)> {
352 if self.xref.repaired { None } else { self.xref.start }
353 }
354
355 pub(crate) fn crypt(&self) -> Option<&crypt::Crypt> {
356 self.crypt.as_ref()
357 }
358
359 pub(crate) fn encrypt_ref(&self) -> Option<Ref> {
361 self.encrypt_ref
362 }
363
364 fn scan(&self) -> &BTreeMap<u32, (usize, u16)> {
365 self.scan.get_or_init(|| xref::scan_objects(&self.data))
366 }
367
368 pub fn get(&self, r: Ref) -> Object {
370 self.load(r, 0)
371 }
372
373 fn load(&self, r: Ref, depth: u32) -> Object {
374 if depth > MAX_LOAD_DEPTH {
375 return Object::Null;
376 }
377 match self.xref.entries.get(&r.num).copied() {
378 Some((Entry::At(off), _)) => {
379 if let Some(o) = self.at(off, r, depth) {
380 return o;
381 }
382 if !self.xref.repaired {
383 if let Some(&(o2, _)) = self.scan().get(&r.num) {
384 if o2 != off {
385 return self.at(o2, r, depth).unwrap_or_default();
386 }
387 }
388 }
389 Object::Null
390 }
391 Some((Entry::InStream(s, i), _)) => self.in_stream(s, i, r.num, depth).unwrap_or_default(),
392 _ if self.xref.repaired || self.xref.deleted(r.num) => Object::Null,
393 _ => match self.scan().get(&r.num) {
395 Some(&(off, _)) => self.at(off, r, depth).unwrap_or_default(),
396 None => Object::Null,
397 },
398 }
399 }
400
401 fn at(&self, off: usize, r: Ref, depth: u32) -> Option<Object> {
402 let ends = |from: usize| self.ends.get_or_init(|| lex::Ends::of(&self.data)).after(from);
403 let limit = match self.xref.repaired {
406 true => self.heads.get_or_init(|| xref::Heads::from_offsets(self.xref.entries.values().filter_map(|e| if let Entry::At(o) = e.0 { Some(o) } else { None }))).after(off, self.data.len()),
407 false => self.data.len(),
408 };
409 let (got, mut obj) = lex::indirect(&self.data, off, limit, &mut |lr| self.load(lr, depth + 1).as_int(), &ends)?;
410 if got.num != r.num {
411 return None;
412 }
413 if let Some(c) = &self.crypt {
414 if self.encrypt_ref != Some(r) {
415 c.strings_in(r, &mut obj, 0);
416 }
417 }
418 Some(obj)
419 }
420
421 fn objstm(&self, num: u32, depth: u32) -> Option<Rc<ObjStm>> {
422 if let Some(v) = self.objstms.borrow().get(&num) {
423 return v.clone();
424 }
425 let built = (|| {
426 let o = self.load(Ref { num, generation: 0 }, depth + 1);
427 let s = o.as_stream()?;
428 let left = self.objstm_left.get();
431 if left == 0 {
432 return None;
433 }
434 let decoded = self.decode_d(s, depth + 1);
435 let used = match &decoded {
437 Ok(d) => d.0.len(),
438 Err(Error::Limit(_)) => self.max_stream,
439 Err(_) => 0,
440 };
441 self.objstm_left.set(left.saturating_sub(used));
442 let (data, img) = decoded.ok()?;
443 if img.is_some() {
444 return None;
445 }
446 let n = s.dict.int("N").unwrap_or(0).max(0) as usize;
447 let first = usize::try_from(s.dict.int("First")?).ok()?;
448 let mut lx = lex::Lexer::new(&data, 0);
449 let mut index = Vec::new();
450 let mut by_num = BTreeMap::new();
451 while index.len() < n && lx.pos < first.min(data.len()) {
452 let (lex::Tok::Int(a), lex::Tok::Int(b)) = (lx.next(), lx.next()) else { break };
453 let (Ok(a), Ok(b)) = (u32::try_from(a), usize::try_from(b)) else { break };
454 index.push((a, b));
455 by_num.entry(a).or_insert(b);
456 }
457 Some(Rc::new(ObjStm { data, first, index, by_num }))
458 })();
459 let mut cache = self.objstms.borrow_mut();
460 if let Some(st) = &built {
461 let len = st.data.len();
463 while self.objstm_held.get() + len > self.max_stream {
464 let Some(k) = cache.iter().find(|e| e.1.is_some()).map(|e| *e.0) else { break };
465 let gone = cache.remove(&k).flatten().map_or(0, |s| s.data.len());
466 self.objstm_held.set(self.objstm_held.get().saturating_sub(gone));
467 }
468 self.objstm_held.set(self.objstm_held.get() + len);
469 }
470 if let Some(old) = cache.insert(num, built.clone()).flatten() {
471 self.objstm_held.set(self.objstm_held.get().saturating_sub(old.data.len()));
473 }
474 built
475 }
476
477 fn in_stream(&self, s: u32, i: u32, num: u32, depth: u32) -> Option<Object> {
478 let st = self.objstm(s, depth)?;
479 let off = match st.index.get(i as usize) {
480 Some(&(n, off)) if n == num => off,
481 _ => *st.by_num.get(&num)?,
482 };
483 let mut lx = lex::Lexer::new(&st.data, st.first.checked_add(off)?);
484 lx.object(true).ok()
485 }
486
487 pub fn resolve(&self, o: &Object) -> Object {
489 let mut cur = match o {
490 Object::Ref(r) => self.get(*r),
491 o => return o.clone(),
492 };
493 for _ in 0..MAX_CHAIN {
494 match cur {
495 Object::Ref(r) => cur = self.get(r),
496 _ => return cur,
497 }
498 }
499 Object::Null
500 }
501
502 pub(crate) fn dict(&self, o: &Object) -> Dict {
504 match self.resolve(o) {
505 Object::Dict(d) => d,
506 Object::Stream(s) => s.dict,
507 _ => Dict::new(),
508 }
509 }
510
511 pub(crate) fn key(&self, d: &Dict, key: &str) -> Object {
513 d.get(key).map(|o| self.resolve(o)).unwrap_or_default()
514 }
515
516 pub(crate) fn cidmap(&self, name: &[u8]) -> Option<Rc<cidmap::CMap>> {
519 if let Some(c) = self.cidmaps.borrow().get(name) {
520 return c.clone();
521 }
522 let c = cidmap::predefined(name).map(Rc::new);
523 let mut m = self.cidmaps.borrow_mut();
524 if m.len() < 256 {
525 m.insert(name.to_vec(), c.clone());
526 }
527 c
528 }
529
530 pub(crate) fn cid_text(&self, c: cidmap::Collection) -> Rc<cidmap::ToUnicode> {
532 self.cid_texts.borrow_mut().entry(c).or_insert_with(|| Rc::new(cidmap::to_unicode(c))).clone()
533 }
534
535 pub fn decode(&self, s: &Stream) -> Result<Vec<u8>, Error> {
536 match self.decode_d(s, 0)? {
537 (d, None) => Ok(d),
538 (_, Some(_)) => Err(Error::Unsupported("an image filter (decode_until_image)")),
539 }
540 }
541
542 pub fn decode_until_image(&self, s: &Stream) -> Result<(Vec<u8>, Option<(Name, Dict)>), Error> {
545 self.decode_d(s, 0)
546 }
547
548 fn decode_d(&self, s: &Stream, depth: u32) -> Result<(Vec<u8>, Option<(Name, Dict)>), Error> {
549 let raw = self.data.get(s.start..s.end).ok_or(Error::Damaged("a stream outside the file"))?;
550 let mut fd = Dict::new();
552 for k in ["Filter", "DecodeParms"] {
553 if let Some(o) = s.dict.get(k) {
554 let v = match self.resolve_d(o, depth) {
555 Object::Array(a) => Object::Array(a.iter().map(|e| self.resolve_d(e, depth)).collect()),
556 v => v,
557 };
558 fd.insert(k, v);
559 }
560 }
561 let chain = filter::chain(&fd);
562 let mut data = raw.to_vec();
563 if let (Some(c), Some(r)) = (&self.crypt, s.owner) {
564 let exempt = s.dict.is("Type", "XRef") || (!c.encrypt_metadata && s.dict.is("Type", "Metadata"));
565 if !exempt {
566 let cf = match chain.first() {
567 Some((n, p)) if n == "Crypt" => Some(p.name("Name").unwrap_or(b"Identity")),
568 _ => None,
569 };
570 data = c.stream(r, &data, cf, s.dict.is("Type", "EmbeddedFile"));
571 }
572 }
573 filter::apply(&chain, data, self.max_stream)
574 }
575
576 fn resolve_d(&self, o: &Object, depth: u32) -> Object {
577 match o {
578 Object::Ref(r) => match self.load(*r, depth + 1) {
579 Object::Ref(_) => Object::Null,
580 v => v,
581 },
582 o => o.clone(),
583 }
584 }
585
586 fn collect_pages(&mut self) {
587 #[derive(Clone, Default)]
588 struct Inh {
589 resources: Option<Object>,
590 media: Option<Object>,
591 crop: Option<Object>,
592 rotate: Option<i64>,
593 }
594 let cat = self.catalog();
595 let mut pages = Vec::new();
596 let mut seen = BTreeSet::new();
597 let mut stack: Vec<(Object, Rc<Inh>, u32)> = Vec::new();
600 if let Some(root) = cat.get("Pages") {
601 stack.push((root.clone(), Rc::new(Inh::default()), 0));
602 }
603 let budget = self.xref.entries.len().saturating_mul(2).max(64);
604 let mut nodes = 0usize;
605 while let Some((node, inh, depth)) = stack.pop() {
606 nodes += 1;
607 if nodes > budget || pages.len() >= MAX_PAGES || depth > 256 {
608 break;
609 }
610 let r = node.as_ref();
611 if let Some(r) = r {
612 if !seen.insert(r) {
613 continue; }
615 }
616 let d = self.dict(&node);
617 if d.is_empty() {
618 continue;
619 }
620 let rotate = d.get("Rotate").map(|o| self.resolve(o)).and_then(|o| o.as_int());
621 let mut inh = inh;
622 if d.contains("Resources") || d.contains("MediaBox") || d.contains("CropBox") || rotate.is_some() {
623 let mut own = (*inh).clone();
624 if let Some(v) = d.get("Resources") {
625 own.resources = Some(v.clone());
626 }
627 if let Some(v) = d.get("MediaBox") {
628 own.media = Some(v.clone());
629 }
630 if let Some(v) = d.get("CropBox") {
631 own.crop = Some(v.clone());
632 }
633 if rotate.is_some() {
634 own.rotate = rotate;
635 }
636 inh = Rc::new(own);
637 }
638 let kids = match self.key(&d, "Kids") {
639 Object::Array(a) => Some(a),
640 _ => None,
641 };
642 let is_page = d.is("Type", "Page") || (kids.is_none() && !d.is("Type", "Pages"));
643 if !is_page {
644 for k in kids.unwrap_or_default().into_iter().rev() {
645 if k.as_ref().is_some_and(|r| seen.contains(&r)) {
647 continue;
648 }
649 stack.push((k, inh.clone(), depth + 1));
650 }
651 continue;
652 }
653 pages.push((r, d, inh));
654 }
655 if pages.is_empty() {
657 let nums: Vec<u32> = self.xref.entries.keys().copied().collect();
658 for num in nums.into_iter().take(1 << 20) {
659 let r = Ref { num, generation: self.xref.entries.get(&num).map(|e| e.1).unwrap_or(0) };
660 let d = self.dict(&Object::Ref(r));
661 if d.is("Type", "Page") {
662 let inh = Inh { resources: d.get("Resources").cloned(), ..Inh::default() };
663 pages.push((Some(r), d, Rc::new(inh)));
664 }
665 }
666 }
667 let mut shared: BTreeMap<Ref, Dict> = BTreeMap::new();
670 for (r, d, inh) in pages {
671 let rect = |o: &Option<Object>| o.as_ref().map(|o| self.resolve(o)).and_then(|o| o.as_rect());
672 let media = rect(&inh.media).filter(|b| b[2] > b[0] && b[3] > b[1]).unwrap_or([0.0, 0.0, 612.0, 792.0]);
673 let crop = rect(&inh.crop)
674 .map(|c| [c[0].max(media[0]), c[1].max(media[1]), c[2].min(media[2]), c[3].min(media[3])])
675 .filter(|c| c[2] > c[0] && c[3] > c[1])
676 .unwrap_or(media);
677 let rotate = (inh.rotate.unwrap_or(0).rem_euclid(360) / 90 * 90) as u16;
678 let user_unit = d.num("UserUnit").filter(|&u| u > 0.0 && u < 1e4).unwrap_or(1.0);
679 let resources = match &inh.resources {
680 Some(Object::Ref(rr)) => shared.entry(*rr).or_insert_with(|| self.dict(&Object::Ref(*rr))).clone(),
681 Some(o) => self.dict(o),
682 None => Dict::new(),
683 };
684 if let Some(r) = r {
685 self.page_index.insert(r, self.pages.len());
686 }
687 self.pages.push(Page { obj: r, media_box: media, crop_box: crop, rotate, user_unit, dict: d, resources });
688 }
689 }
690
691 pub fn page_count(&self) -> usize {
692 self.pages.len()
693 }
694
695 pub fn pages(&self) -> &[Page] {
696 &self.pages
697 }
698
699 pub fn page(&self, i: usize) -> Result<&Page, Error> {
700 self.pages.get(i).ok_or(Error::NoPage)
701 }
702
703 pub fn page_of(&self, r: Ref) -> Option<usize> {
705 self.page_index.get(&r).copied()
706 }
707
708 pub fn contents(&self, i: usize) -> Result<Vec<u8>, Error> {
711 let p = self.page(i)?;
712 let mut out = Vec::new();
713 let parts = match self.key(&p.dict, "Contents") {
714 Object::Array(a) => a,
715 Object::Stream(s) => alloc::vec![Object::Stream(s)],
716 _ => Vec::new(),
717 };
718 for part in parts {
719 if let Object::Stream(s) = self.resolve(&part) {
720 if let Ok(d) = self.decode(&s) {
721 if out.len() + d.len() > self.max_stream {
722 return Err(Error::Limit("the page's content is larger than max_stream"));
723 }
724 out.extend_from_slice(&d);
725 out.push(b'\n');
726 }
727 }
728 }
729 Ok(out)
730 }
731
732 pub fn info(&self) -> Info {
734 let d = match self.xref.trailer.get("Info") {
735 Some(o) => self.dict(o),
736 None => Dict::new(),
737 };
738 let s = |k: &str| match self.key(&d, k) {
739 Object::String(b) => Some(text_string(&b)),
740 _ => None,
741 };
742 Info {
743 title: s("Title"),
744 author: s("Author"),
745 subject: s("Subject"),
746 keywords: s("Keywords"),
747 creator: s("Creator"),
748 producer: s("Producer"),
749 created: s("CreationDate").and_then(|t| parse_date(&t)),
750 modified: s("ModDate").and_then(|t| parse_date(&t)),
751 }
752 }
753
754 pub fn metadata(&self) -> Option<Vec<u8>> {
756 match self.key(&self.catalog(), "Metadata") {
757 Object::Stream(s) => self.decode(&s).ok(),
758 _ => None,
759 }
760 }
761
762 pub fn language(&self) -> Option<String> {
764 match self.key(&self.catalog(), "Lang") {
765 Object::String(b) => Some(text_string(&b)),
766 _ => None,
767 }
768 }
769}
770
771pub fn parse_date(s: &str) -> Option<Date> {
774 let s = s.trim();
775 let s = s.strip_prefix("D:").unwrap_or(s).as_bytes();
776 let num = |i: usize, n: usize| -> Option<u32> {
777 let p = s.get(i..i + n)?;
778 p.iter().all(u8::is_ascii_digit).then(|| p.iter().fold(0u32, |a, &c| a * 10 + (c - b'0') as u32))
779 };
780 let year = num(0, 4)?;
781 let mut parts = [1u32, 1, 0, 0, 0];
782 let mut i = 4;
783 for p in parts.iter_mut() {
784 let Some(v) = num(i, 2) else { break };
785 *p = v;
786 i += 2;
787 }
788 let [month, day, hour, minute, second] = parts;
789 if !(1..=12).contains(&month) || !(1..=31).contains(&day) || hour > 23 || minute > 59 || second > 60 {
790 return None;
791 }
792 let mut offset = 0i32;
793 match s.get(i) {
794 Some(&c @ (b'+' | b'-')) => {
795 let h = num(i + 1, 2).unwrap_or(0) as i32;
796 let m = s.get(i + 3).filter(|&&c| c == b'\'').map_or_else(|| num(i + 3, 2), |_| num(i + 4, 2)).unwrap_or(0) as i32;
797 offset = (h * 60 + m).min(1439) * if c == b'-' { -1 } else { 1 };
798 }
799 _ => {}
800 }
801 Some(Date { year: year as u16, month: month as u8, day: day as u8, hour: hour as u8, minute: minute as u8, second: second.min(59) as u8, offset_minutes: offset as i16 })
802}