1use alloc::collections::BTreeMap;
7use alloc::string::String;
8use alloc::sync::Arc;
9use alloc::vec::Vec;
10use core::borrow::Borrow;
11
12#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
14pub struct Ref {
15 pub num: u32,
16 pub generation: u16,
17}
18
19impl core::fmt::Debug for Ref {
21 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
22 write!(f, "{} {} R", self.num, self.generation)
23 }
24}
25
26#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
28pub struct Name(pub Vec<u8>);
29
30impl core::fmt::Debug for Name {
32 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
33 f.write_str("/")?;
34 for &c in &self.0 {
35 if c.is_ascii_graphic() && !super::lex::is_delim(c) && c != b'#' {
36 write!(f, "{}", c as char)?;
37 } else {
38 write!(f, "#{c:02X}")?;
39 }
40 }
41 Ok(())
42 }
43}
44
45impl Name {
46 pub fn as_bytes(&self) -> &[u8] {
47 &self.0
48 }
49 pub fn to_text(&self) -> String {
51 String::from_utf8_lossy(&self.0).into_owned()
52 }
53}
54
55impl Borrow<[u8]> for Name {
56 fn borrow(&self) -> &[u8] {
57 &self.0
58 }
59}
60
61impl PartialEq<str> for Name {
62 fn eq(&self, o: &str) -> bool {
63 self.0 == o.as_bytes()
64 }
65}
66
67impl PartialEq<&str> for Name {
68 fn eq(&self, o: &&str) -> bool {
69 self.0 == o.as_bytes()
70 }
71}
72
73#[derive(Clone, Debug, PartialEq, Default)]
77pub struct Dict(pub(crate) Arc<BTreeMap<Name, Object>>);
78
79impl Dict {
80 pub fn new() -> Dict {
81 Dict(Arc::new(BTreeMap::new()))
82 }
83 pub(crate) fn from_map(m: BTreeMap<Name, Object>) -> Dict {
84 Dict(Arc::new(m))
85 }
86 pub(crate) fn map_mut(&mut self) -> &mut BTreeMap<Name, Object> {
88 Arc::make_mut(&mut self.0)
89 }
90 pub fn get(&self, key: &str) -> Option<&Object> {
92 self.0.get(key.as_bytes())
93 }
94 pub fn get_bytes(&self, key: &[u8]) -> Option<&Object> {
95 self.0.get(key)
96 }
97 pub fn contains(&self, key: &str) -> bool {
98 self.0.contains_key(key.as_bytes())
99 }
100 pub fn insert(&mut self, key: &str, value: Object) {
101 self.map_mut().insert(Name(key.as_bytes().to_vec()), value);
102 }
103 pub fn remove(&mut self, key: &str) -> Option<Object> {
105 self.map_mut().remove(key.as_bytes())
106 }
107 pub fn len(&self) -> usize {
108 self.0.len()
109 }
110 pub fn is_empty(&self) -> bool {
111 self.0.is_empty()
112 }
113 pub fn iter(&self) -> impl Iterator<Item = (&Name, &Object)> {
114 self.0.iter()
115 }
116 pub fn name(&self, key: &str) -> Option<&[u8]> {
118 self.get(key).and_then(Object::as_name)
119 }
120 pub fn is(&self, key: &str, v: &str) -> bool {
122 self.name(key) == Some(v.as_bytes())
123 }
124 pub fn int(&self, key: &str) -> Option<i64> {
125 self.get(key).and_then(Object::as_int)
126 }
127 pub fn num(&self, key: &str) -> Option<f64> {
128 self.get(key).and_then(Object::as_f64)
129 }
130}
131
132#[derive(Clone, Debug, PartialEq)]
134pub struct Stream {
135 pub dict: Dict,
136 pub(crate) start: usize,
137 pub(crate) end: usize,
138 pub(crate) owner: Option<Ref>,
140}
141
142impl Stream {
143 pub fn raw_len(&self) -> usize {
145 self.end - self.start
146 }
147}
148
149#[derive(Clone, Debug, PartialEq, Default)]
151pub enum Object {
152 #[default]
153 Null,
154 Bool(bool),
155 Int(i64),
156 Real(f64),
157 String(Vec<u8>),
159 Name(Name),
160 Array(Vec<Object>),
161 Dict(Dict),
162 Stream(alloc::boxed::Box<Stream>),
164 Ref(Ref),
165}
166
167impl Object {
168 pub fn name(s: &str) -> Object {
169 Object::Name(Name(s.as_bytes().to_vec()))
170 }
171 pub fn is_null(&self) -> bool {
172 matches!(self, Object::Null)
173 }
174 pub fn as_bool(&self) -> Option<bool> {
175 match self {
176 Object::Bool(b) => Some(*b),
177 _ => None,
178 }
179 }
180 pub fn as_int(&self) -> Option<i64> {
182 match *self {
183 Object::Int(i) => Some(i),
184 Object::Real(r) if r.is_finite() && r == (r as i64) as f64 => Some(r as i64),
185 _ => None,
186 }
187 }
188 pub fn as_f64(&self) -> Option<f64> {
190 match *self {
191 Object::Int(i) => Some(i as f64),
192 Object::Real(r) if r.is_finite() => Some(r),
193 _ => None,
194 }
195 }
196 pub fn as_name(&self) -> Option<&[u8]> {
197 match self {
198 Object::Name(n) => Some(&n.0),
199 _ => None,
200 }
201 }
202 pub fn as_bytes(&self) -> Option<&[u8]> {
204 match self {
205 Object::String(s) => Some(s),
206 _ => None,
207 }
208 }
209 pub fn as_array(&self) -> Option<&[Object]> {
210 match self {
211 Object::Array(a) => Some(a),
212 _ => None,
213 }
214 }
215 pub fn as_dict(&self) -> Option<&Dict> {
217 match self {
218 Object::Dict(d) => Some(d),
219 Object::Stream(s) => Some(&s.dict),
220 _ => None,
221 }
222 }
223 pub fn as_stream(&self) -> Option<&Stream> {
224 match self {
225 Object::Stream(s) => Some(s),
226 _ => None,
227 }
228 }
229 pub fn as_ref(&self) -> Option<Ref> {
230 match self {
231 Object::Ref(r) => Some(*r),
232 _ => None,
233 }
234 }
235 pub fn as_rect(&self) -> Option<[f64; 4]> {
237 let a = self.as_array()?;
238 if a.len() < 4 {
239 return None;
240 }
241 let v = [a[0].as_f64()?, a[1].as_f64()?, a[2].as_f64()?, a[3].as_f64()?];
242 Some([v[0].min(v[2]), v[1].min(v[3]), v[0].max(v[2]), v[1].max(v[3])])
243 }
244}
245
246pub fn text_string(b: &[u8]) -> String {
249 if b.len() >= 2 && (b[0] == 0xFE && b[1] == 0xFF || b[0] == 0xFF && b[1] == 0xFE) {
250 let be = b[0] == 0xFE;
251 let units = b[2..].chunks_exact(2).map(|c| if be { u16::from_be_bytes([c[0], c[1]]) } else { u16::from_le_bytes([c[0], c[1]]) });
252 let s: String = char::decode_utf16(units).map(|r| r.unwrap_or('\u{FFFD}')).collect();
253 let Some(last) = s.rfind('\u{1B}') else { return s };
257 let mut out = String::with_capacity(s.len());
258 let mut skip = false;
259 for (i, ch) in s.char_indices() {
260 if ch == '\u{1B}' && (skip || i < last) {
261 skip = !skip;
262 continue;
263 }
264 if !skip {
265 out.push(ch);
266 }
267 }
268 return out;
269 }
270 if b.len() >= 3 && b[..3] == [0xEF, 0xBB, 0xBF] {
271 return String::from_utf8_lossy(&b[3..]).into_owned();
272 }
273 b.iter().filter_map(|&c| char::from_u32(super::tables::PDFDOC[c as usize] as u32).filter(|&ch| ch != '\0' || c == 0)).collect()
274}