pltrs_render/pdf/
object.rs1use crate::vector::{VectorError, trimmed};
5
6#[derive(Clone, Debug, PartialEq)]
21pub enum Obj {
22 Null,
24 Bool(bool),
26 Int(i64),
28 Real(f64),
30 Name(String),
32 Str(Vec<u8>),
34 Array(Vec<Obj>),
36 Dict(Vec<(String, Obj)>),
38 Ref(u32),
40 Seq(Vec<Obj>),
43 Raw(Vec<u8>),
45}
46
47impl Obj {
48 pub fn name(name: impl Into<String>) -> Self {
50 Self::Name(name.into())
51 }
52
53 pub fn op(op: &str) -> Self {
55 Self::Raw(op.as_bytes().to_vec())
56 }
57
58 pub(super) fn dict<const N: usize>(entries: [(&str, Obj); N]) -> Self {
60 Self::Dict(
61 entries
62 .into_iter()
63 .map(|(k, v)| (k.to_owned(), v))
64 .collect(),
65 )
66 }
67
68 pub(super) fn reals(values: impl IntoIterator<Item = f64>) -> Self {
70 Self::Array(values.into_iter().map(Self::Real).collect())
71 }
72
73 pub fn repr(&self) -> Result<Vec<u8>, VectorError> {
80 Ok(match self {
81 Self::Null => b"null".to_vec(),
82 Self::Bool(b) => {
83 if *b {
84 b"true".to_vec()
85 } else {
86 b"false".to_vec()
87 }
88 }
89 Self::Int(i) => i.to_string().into_bytes(),
90 Self::Real(r) => {
91 if !r.is_finite() {
92 return Err(VectorError::NonFinite("number in a PDF"));
93 }
94 trimmed(*r, 10).into_bytes()
95 }
96 Self::Name(name) => name_repr(name),
97 Self::Str(bytes) => string_repr(bytes),
98 Self::Array(items) => {
99 let mut parts = vec![b"[".to_vec()];
100 for item in items {
101 parts.push(item.repr()?);
102 }
103 parts.push(b"]".to_vec());
104 fill(&parts)
105 }
106 Self::Dict(entries) => {
107 let mut parts = vec![b"<<".to_vec()];
108 for (key, value) in entries {
109 let mut part = name_repr(key);
110 part.push(b' ');
111 part.extend(value.repr()?);
112 parts.push(part);
113 }
114 parts.push(b">>".to_vec());
115 fill(&parts)
116 }
117 Self::Ref(id) => format!("{id} 0 R").into_bytes(),
118 Self::Seq(items) => fill(&items.iter().map(Obj::repr).collect::<Result<Vec<_>, _>>()?),
119 Self::Raw(bytes) => bytes.clone(),
120 })
121 }
122}
123
124fn name_repr(name: &str) -> Vec<u8> {
126 let mut out = vec![b'/'];
127 for c in name.chars() {
128 match u32::from(c) {
129 0x21..=0x7e => out.push(c as u8),
130 code => out.extend(format!("#{:02x}", code & 0xff).into_bytes()),
131 }
132 }
133 out
134}
135
136fn string_repr(bytes: &[u8]) -> Vec<u8> {
139 let mut out = Vec::with_capacity(bytes.len() + 2);
140 out.push(b'(');
141 for &b in bytes {
142 match b {
143 b'\\' => out.extend_from_slice(b"\\\\"),
144 b'(' => out.extend_from_slice(b"\\("),
145 b')' => out.extend_from_slice(b"\\)"),
146 b'\n' => out.extend_from_slice(b"\\n"),
147 b'\r' => out.extend_from_slice(b"\\r"),
148 _ => out.push(b),
149 }
150 }
151 out.push(b')');
152 out
153}
154
155pub fn text_string(text: &str) -> Obj {
164 if text.is_ascii() {
165 Obj::Str(text.as_bytes().to_vec())
166 } else {
167 let mut bytes = vec![0xfe, 0xff];
168 for unit in text.encode_utf16() {
169 bytes.extend_from_slice(&unit.to_be_bytes());
170 }
171 Obj::Str(bytes)
172 }
173}
174
175pub fn line(objects: &[Obj]) -> Result<Vec<u8>, VectorError> {
187 let parts = objects
188 .iter()
189 .map(Obj::repr)
190 .collect::<Result<Vec<_>, _>>()?;
191 let mut line = fill(&parts);
192 line.push(b'\n');
193 Ok(line)
194}
195
196pub(super) fn fill(parts: &[Vec<u8>]) -> Vec<u8> {
199 const LINE: usize = 75;
200 let mut lines: Vec<Vec<u8>> = Vec::new();
201 let (mut position, mut start) = (0, 0);
202 for (i, part) in parts.iter().enumerate() {
203 if position + part.len() < LINE {
204 position += part.len() + 1;
205 } else {
206 lines.push(parts[start..i].join(&b' '));
207 start = i;
208 position = part.len();
209 }
210 }
211 lines.push(parts[start..].join(&b' '));
212 lines.join(&b'\n')
213}
214
215#[cfg(test)]
216mod tests {
217 use super::*;
218
219 fn text(obj: &Obj) -> String {
220 String::from_utf8(obj.repr().unwrap()).unwrap()
221 }
222
223 #[test]
224 fn scalars() {
225 assert_eq!(text(&Obj::Real(31.0 / 255.0)), "0.1215686275");
226 assert_eq!(text(&Obj::Real(-0.0)), "-0");
227 assert_eq!(text(&Obj::Real(460.8)), "460.8");
228 assert_eq!(text(&Obj::Int(42)), "42");
229 assert_eq!(text(&Obj::name("A b#")), "/A#20b#");
230 assert_eq!(text(&Obj::Str(b"a(b)\\\n".to_vec())), "(a\\(b\\)\\\\\\n)");
231 assert_eq!(text(&Obj::Ref(3)), "3 0 R");
232 assert!(Obj::Real(f64::NAN).repr().is_err());
233 assert_eq!(text_string("é"), Obj::Str(vec![0xfe, 0xff, 0, 0xe9]));
234 }
235
236 #[test]
237 fn containers_fill_lines() {
238 let dict = Obj::dict([
239 ("Type", Obj::name("Page")),
240 ("MediaBox", Obj::reals([0.0, 0.0, 460.8, 345.6])),
241 ]);
242 assert_eq!(
243 text(&dict),
244 "<< /Type /Page /MediaBox [ 0 0 460.8 345.6 ] >>"
245 );
246 let long = vec![b"x".repeat(80)];
247 assert_eq!(fill(&long), [b"\n".to_vec(), b"x".repeat(80)].concat());
248 let words: Vec<Vec<u8>> = (0..30).map(|i| format!("w{i:02}").into_bytes()).collect();
249 let filled = String::from_utf8(fill(&words)).unwrap();
250 assert!(filled.lines().all(|line| line.len() < 75));
251 assert_eq!(filled.lines().count(), 2);
252 }
253}