1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
//! `Object` trait, along with some implementations. References.
//!
//! Some of the structs are incomplete (missing fields that are in the PDF references).

mod types;
mod stream;
mod color;
mod function;

pub use self::types::*;
pub use self::stream::*;
pub use self::color::*;
pub use self::function::*;

use crate::primitive::*;
use crate::error::*;
use crate::enc::*;

use std::io;
use std::fmt;
use std::marker::PhantomData;
use std::collections::HashMap;
use std::rc::Rc;

pub type ObjNr = u64;
pub type GenNr = u16;

pub trait Resolve: {
    fn resolve(&self, r: PlainRef) -> Result<Primitive>;
    fn get<T: Object>(&self, r: Ref<T>) -> Result<Rc<T>>;
}

pub struct NoResolve;
impl Resolve for NoResolve {
    fn resolve(&self, _: PlainRef) -> Result<Primitive> {
        Err(PdfError::Reference)
    }
    fn get<T: Object>(&self, _r: Ref<T>) -> Result<Rc<T>> {
        Err(PdfError::Reference)
    }
}

/// A PDF Object
pub trait Object: Sized + 'static {
    /// Write object as a byte stream
    fn serialize<W: io::Write>(&self, out: &mut W) -> Result<()>;
    /// Convert primitive to Self
    fn from_primitive(p: Primitive, resolve: &impl Resolve) -> Result<Self>;
    
    fn from_dict(dict: Dictionary, resolve: &impl Resolve) -> Result<Self> {
        Self::from_primitive(Primitive::Dictionary(dict), resolve)
    }
}

///////
// Refs
///////

// TODO move to primitive.rs
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub struct PlainRef {
    pub id:     ObjNr,
    pub gen:    GenNr,
}
impl Object for PlainRef {
    fn serialize<W: io::Write>(&self, out: &mut W) -> Result<()>  {
        write!(out, "{} {} R", self.id, self.gen)?;
        Ok(())
    }
    fn from_primitive(p: Primitive, _: &impl Resolve) -> Result<Self> {
        p.into_reference()
    }
}


// NOTE: Copy & Clone implemented manually ( https://github.com/rust-lang/rust/issues/26925 )

pub struct Ref<T> {
    inner:      PlainRef,
    _marker:    PhantomData<T>
}
impl<T> Clone for Ref<T> {
    fn clone(&self) -> Ref<T> {
        Ref {
            inner: self.inner,
            _marker: PhantomData
        }
    }
}
impl<T> Copy for Ref<T> {}

impl<T> Ref<T> {
    pub fn new(inner: PlainRef) -> Ref<T> {
        Ref {
            inner,
            _marker:    PhantomData::default(),
        }
    }
    pub fn from_id(id: ObjNr) -> Ref<T> {
        Ref {
            inner:      PlainRef {id, gen: 0},
            _marker:    PhantomData::default(),
        }
    }
    pub fn get_inner(&self) -> PlainRef {
        self.inner
    }
}
impl<T: Object> Ref<T> {
    pub fn resolve(&self, r: &impl Resolve) -> Result<T> {
        T::from_primitive(r.resolve(self.inner)?, r)
    }
}
impl<T: Object> Object for Ref<T> {
    fn serialize<W: io::Write>(&self, out: &mut W) -> Result<()>  {
        self.inner.serialize(out)
    }
    fn from_primitive(p: Primitive, _: &impl Resolve) -> Result<Self> {
        Ok(Ref::new(p.into_reference()?))
    }
}

impl<T> fmt::Debug for Ref<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Ref({})", self.inner.id)
    }
}

//////////////////////////////////////
// Object for Primitives & other types
//////////////////////////////////////

impl Object for i32 {
    fn serialize<W: io::Write>(&self, out: &mut W) -> Result<()> {
        write!(out, "{}", self)?;
        Ok(())
    }
    fn from_primitive(p: Primitive, r: &impl Resolve) -> Result<Self> {
        match p {
            Primitive::Reference(id) => r.resolve(id)?.as_integer(),
            p => p.as_integer()
        }
    }
}
impl Object for u32 {
    fn serialize<W: io::Write>(&self, out: &mut W) -> Result<()> {
        write!(out, "{}", self)?;
        Ok(())
    }
    fn from_primitive(p: Primitive, r: &impl Resolve) -> Result<Self> {
        match p {
            Primitive::Reference(id) => r.resolve(id)?.as_u32(),
            p => p.as_u32()
        }
    }
}
impl Object for usize {
    fn serialize<W: io::Write>(&self, out: &mut W) -> Result<()> {
        write!(out, "{}", self)?;
        Ok(())
    }
    fn from_primitive(p: Primitive, r: &impl Resolve) -> Result<Self> {
        match p {
            Primitive::Reference(id) => Ok(r.resolve(id)?.as_u32()? as usize),
            p => Ok(p.as_u32()? as usize)
        }
    }
}
impl Object for f32 {
    fn serialize<W: io::Write>(&self, out: &mut W) -> Result<()> {
        write!(out, "{}", self)?;
        Ok(())
    }
    fn from_primitive(p: Primitive, r: &impl Resolve) -> Result<Self> {
        match p {
            Primitive::Reference(id) => r.resolve(id)?.as_number(),
            p => p.as_number()
        }
    }
}
impl Object for bool {
    fn serialize<W: io::Write>(&self, out: &mut W) -> Result<()> {
        write!(out, "{}", self)?;
        Ok(())
    }
    fn from_primitive(p: Primitive, r: &impl Resolve) -> Result<Self> {
        match p {
            Primitive::Reference(id) => r.resolve(id)?.as_bool(),
            p => p.as_bool()
        }
    }
}
impl Object for Dictionary {
    fn serialize<W: io::Write>(&self, out: &mut W) -> Result<()> {
        write!(out, "<<")?;
        for (key, val) in self.iter() {
            write!(out, "/{} ", key)?;
            val.serialize(out)?;
        }
        write!(out, ">>")?;
        Ok(())
    }
    fn from_primitive(p: Primitive, r: &impl Resolve) -> Result<Self> {
        match p {
            Primitive::Dictionary(dict) => Ok(dict),
            Primitive::Reference(id) => Dictionary::from_primitive(r.resolve(id)?, r),
            _ => Err(PdfError::UnexpectedPrimitive {expected: "Dictionary", found: p.get_debug_name()}),
        }
    }
}

impl Object for String {
    fn serialize<W: io::Write>(&self, out: &mut W) -> Result<()> {
        for b in self.as_str().chars() {
            match b {
                '\\' | '(' | ')' => write!(out, r"\")?,
                c if c > '~' => panic!("only ASCII"),
                _ => ()
            }
            write!(out, "{}", b)?;
        }
        Ok(())
    }
    fn from_primitive(p: Primitive, _: &impl Resolve) -> Result<Self> {
        Ok(p.into_name()?)
    }
}

impl<T: Object> Object for Vec<T> {
    fn serialize<W: io::Write>(&self, out: &mut W) -> Result<()> {
        write_list(out, self.iter())
    }
    /// Will try to convert `p` to `T` first, then try to convert `p` to Vec<T>
    fn from_primitive(p: Primitive, r: &impl Resolve) -> Result<Self> {
        Ok(
        match p {
            Primitive::Array(_) => {
                p.into_array(r)?
                    .into_iter()
                    .map(|p| T::from_primitive(p, r))
                    .collect::<Result<Vec<T>>>()?
            },
            Primitive::Null => {
                Vec::new()
            }
            Primitive::Reference(id) => Self::from_primitive(r.resolve(id)?, r)?,
            _ => vec![T::from_primitive(p, r)?]
        }
        )
    }
}
/*
pub struct Data(pub Vec<u8>);
impl Object for Data {
    fn serialize<W: io::Write>(&self, out: &mut W) -> Result<()> {
        unimplemented!()
    }
    /// Will try to convert `p` to `T` first, then try to convert `p` to Vec<T>
    fn from_primitive(p: Primitive, r: &impl Resolve) -> Result<Self> {
        match p {
            Primitive::Array(_) => {
                p.into_array(r)?
                    .into_iter()
                    .map(|p| u8::from_primitive(p, r))
                    .collect::<Result<Vec<T>>>()?
            },
            Primitive::Null => {
                Vec::new()
            }
            Primitive::Reference(id) => Self::from_primitive(r.resolve(id)?, r)?,
            _ => 
        }
    }
}*/

impl Object for Primitive {
    fn serialize<W: io::Write>(&self, out: &mut W) -> Result<()> {
        match *self {
            Primitive::Null => write!(out, "null")?,
            Primitive::Integer (ref x) => x.serialize(out)?,
            Primitive::Number (ref x) => x.serialize(out)?,
            Primitive::Boolean (ref x) => x.serialize(out)?,
            Primitive::String (ref x) => x.serialize(out)?,
            Primitive::Stream (ref x) => x.serialize(out)?,
            Primitive::Dictionary (ref x) => x.serialize(out)?,
            Primitive::Array (ref x) => x.serialize(out)?,
            Primitive::Reference (ref x) => x.serialize(out)?,
            Primitive::Name (ref x) => x.serialize(out)?,
        }
        Ok(())
    }
    fn from_primitive(p: Primitive, _: &impl Resolve) -> Result<Self> {
        Ok(p)
    }
}

impl<V: Object> Object for HashMap<String, V> {
    fn serialize<W: io::Write>(&self, _out: &mut W) -> Result<()> {
        unimplemented!();
    }
    fn from_primitive(p: Primitive, resolve: &impl Resolve) -> Result<Self> {
        match p {
            Primitive::Null => Ok(HashMap::new()),
            Primitive::Dictionary (dict) => {
                let mut new = Self::new();
                for (key, val) in dict.iter() {
                    new.insert(key.clone(), V::from_primitive(val.clone(), resolve)?);
                }
                Ok(new)
            }
            Primitive::Reference (id) => HashMap::from_primitive(resolve.resolve(id)?, resolve),
            p =>  Err(PdfError::UnexpectedPrimitive {expected: "Dictionary", found: p.get_debug_name()})
        }
    }
}

impl<T: Object + std::fmt::Debug> Object for Rc<T> {
    fn serialize<W: io::Write>(&self, out: &mut W) -> Result<()> {
        (**self).serialize(out)
    }
    fn from_primitive(p: Primitive, resolve: &impl Resolve) -> Result<Self> {
        match p {
            Primitive::Reference(r) => resolve.get(Ref::new(r)),
            p => Ok(Rc::new(T::from_primitive(p, resolve)?))
        }
    }
}

impl<T: Object> Object for Option<T> {
    fn serialize<W: io::Write>(&self, _out: &mut W) -> Result<()> {
        // TODO: the Option here is most often or always about whether the entry exists in a
        // dictionary. Hence it should probably be more up to the Dictionary impl of serialize, to
        // handle Options. 
        unimplemented!();
    }
    fn from_primitive(p: Primitive, resolve: &impl Resolve) -> Result<Self> {
        match p {
            Primitive::Null => Ok(None),
            p => match T::from_primitive(p, resolve) {
                Ok(p) => Ok(Some(p)),
                // References to non-existing objects ought not to be an error
                Err(PdfError::NullRef {..}) => Ok(None),
                Err(PdfError::FreeObject {..}) => Ok(None),
                Err(e) => Err(e),
            }
        }
    }
}

impl Object for () {
    fn serialize<W: io::Write>(&self, out: &mut W) -> Result<()> {
        write!(out, "null")?;
        Ok(())
    }
    fn from_primitive(_p: Primitive, _resolve: &impl Resolve) -> Result<Self> {
        Ok(())
    }
}

impl<T, U> Object for (T, U) where T: Object, U: Object {
    fn serialize<W: io::Write>(&self, out: &mut W) -> Result<()> {
        write!(out, "[")?;
        self.0.serialize(out)?;
        write!(out, " ")?;
        self.1.serialize(out)?;
        write!(out, "]")?;
        Ok(())
    }
    fn from_primitive(p: Primitive, resolve: &impl Resolve) -> Result<Self> {
        let mut arr = p.into_array(resolve)?;
        if arr.len() != 2 {
            bail!("expected array of length 2 (found {})", arr.len());
        }
        let b = arr.pop().unwrap();
        let a = arr.pop().unwrap();
        Ok((T::from_primitive(a, resolve)?, U::from_primitive(b, resolve)?))
    }
}