Skip to content

Commit

Permalink
fix bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
s3bk committed Dec 1, 2023
1 parent 0de4f2d commit e54cbe4
Show file tree
Hide file tree
Showing 5 changed files with 30 additions and 11 deletions.
2 changes: 1 addition & 1 deletion pdf/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ euclid = { version = "0.22.7", optional = true }
bitflags = "1.3"
istring = { version = "0.3.3", features = ["std", "size"] }
datasize = "0.2.13"
globalcache = { version = "0.2", features = ["sync"], optional = true }
globalcache = { version = "0.2.2", features = ["sync"], optional = true }
indexmap = "2.1.0"

[dev-dependencies]
Expand Down
21 changes: 13 additions & 8 deletions pdf/src/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,19 +39,24 @@ impl<T> PromisedRef<T> {

pub trait Cache<T: Clone> {
fn get_or_compute(&self, key: PlainRef, compute: impl FnOnce() -> T) -> T;
fn clear(&self);
}
pub struct NoCache;
impl<T: Clone> Cache<T> for NoCache {
fn get_or_compute(&self, _key: PlainRef, compute: impl FnOnce() -> T) -> T {
compute()
}
fn clear(&self) {}
}

#[cfg(feature="cache")]
impl<T: Clone + ValueSize + Send + 'static> Cache<T> for Arc<SyncCache<PlainRef, T>> {
fn get_or_compute(&self, key: PlainRef, compute: impl FnOnce() -> T) -> T {
self.get(key, compute)
}
fn clear(&self) {
(**self).clear()
}
}

pub trait Log {
Expand All @@ -67,7 +72,7 @@ pub struct Storage<B, OC, SC, L> {
stream_cache: SC,

// objects that differ from the backend
changes: HashMap<ObjNr, Primitive>,
changes: HashMap<ObjNr, (Primitive, GenNr)>,

refs: XRefTable,

Expand Down Expand Up @@ -226,7 +231,7 @@ where
}
fn resolve_ref(&self, r: PlainRef, flags: ParseFlags, resolve: &impl Resolve) -> Result<Primitive> {
match self.changes.get(&r.id) {
Some(p) => Ok((*p).clone()),
Some((p, _)) => Ok((*p).clone()),
None => match t!(self.refs.get(r.id)) {
XRef::Raw {pos, ..} => {
let mut lexer = Lexer::with_offset(t!(self.backend.read(self.start_offset + pos ..)), self.start_offset + pos);
Expand Down Expand Up @@ -347,7 +352,7 @@ where
let id = self.refs.len() as u64;
self.refs.push(XRef::Promised);
let primitive = obj.to_primitive(self)?;
self.changes.insert(id, primitive);
self.changes.insert(id, (primitive, 0));
let rc = Shared::new(obj);
let r = PlainRef { id, gen: 0 };

Expand All @@ -362,7 +367,7 @@ where
XRef::Invalid => panic!()
};
let primitive = obj.to_primitive(self)?;
self.changes.insert(old.id, primitive);
self.changes.insert(old.id, (primitive, r.gen));
let rc = Shared::new(obj);

Ok(RcRef::new(r, rc))
Expand Down Expand Up @@ -400,14 +405,13 @@ where

let xref_promise = self.promise::<Stream<XRefInfo>>();


let mut changes: Vec<_> = self.changes.iter().collect();
changes.sort_unstable_by_key(|&(id, _)| id);

for (&id, primitive) in changes.iter() {
for &(&id, &(ref primitive, gen)) in changes.iter() {
let pos = self.backend.len();
self.refs.set(id, XRef::Raw { pos: pos as _, gen_nr: 0 });
writeln!(self.backend, "{} {} obj", id, 0)?;
self.refs.set(id, XRef::Raw { pos: pos as _, gen_nr: gen });
writeln!(self.backend, "{} {} obj", id, gen)?;
primitive.serialize(&mut self.backend)?;
writeln!(self.backend, "endobj")?;
}
Expand All @@ -431,6 +435,7 @@ where
write!(self.backend, "\nstartxref\n{}\n%%EOF", xref_pos).unwrap();

// update trailer which may have change now.
self.cache.clear();
*trailer = Trailer::from_dict(trailer_dict, &self.resolver())?;

Ok(&self.backend)
Expand Down
2 changes: 1 addition & 1 deletion pdf/src/font.rs
Original file line number Diff line number Diff line change
Expand Up @@ -517,7 +517,7 @@ impl ToUnicodeMap {
pub fn utf16be_to_char(
data: &[u8],
) -> impl Iterator<Item = std::result::Result<char, std::char::DecodeUtf16Error>> + '_ {
char::decode_utf16(data.chunks(2).map(|w| u16::from_be_bytes([w[0], w[1]])))
char::decode_utf16(data.chunks_exact(2).map(|w| u16::from_be_bytes([w[0], w[1]])))
}
/// converts UTF16-BE to a string replacing illegal/unknown characters
pub fn utf16be_to_string_lossy(data: &[u8]) -> String {
Expand Down
3 changes: 3 additions & 0 deletions pdf/src/object/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -958,6 +958,9 @@ pub struct FieldDictionary {

#[pdf(key="AA")]
pub actions: Option<Dictionary>,

#[pdf(other)]
pub other: Dictionary
}

#[derive(Debug, DataSize)]
Expand Down
13 changes: 12 additions & 1 deletion pdf_derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -725,6 +725,17 @@ fn impl_objectwrite_for_struct(ast: &DeriveInput, fields: &Fields) -> SynStream
None => quote! {}
};

let other = parts.iter().filter(|(field, attrs, _)| attrs.other).flat_map(|(field, _, _)| field).next();

Check warning on line 728 in pdf_derive/src/lib.rs

View workflow job for this annotation

GitHub Actions / clippy

unused variable: `field`

warning: unused variable: `field` --> pdf_derive/src/lib.rs:728:39 | 728 | let other = parts.iter().filter(|(field, attrs, _)| attrs.other).flat_map(|(field, _, _)| field).next(); | ^^^^^ help: if this is intentional, prefix it with an underscore: `_field`

Check warning on line 728 in pdf_derive/src/lib.rs

View workflow job for this annotation

GitHub Actions / clippy

unused variable: `field`

warning: unused variable: `field` --> pdf_derive/src/lib.rs:728:39 | 728 | let other = parts.iter().filter(|(field, attrs, _)| attrs.other).flat_map(|(field, _, _)| field).next(); | ^^^^^ help: if this is intentional, prefix it with an underscore: `_field`

Check warning on line 728 in pdf_derive/src/lib.rs

View workflow job for this annotation

GitHub Actions / tests

unused variable: `field`
let init_dict = if let Some(other) = other {
quote! {
let mut dict = self.#other.clone();
}
} else {
quote! {
let mut dict = pdf::primitive::Dictionary::new();
}
};

quote! {
impl #impl_generics pdf::object::ObjectWrite for #id #ty_generics #where_clause {
fn to_primitive(&self, update: &mut impl pdf::object::Updater) -> Result<pdf::primitive::Primitive> {
Expand All @@ -733,7 +744,7 @@ fn impl_objectwrite_for_struct(ast: &DeriveInput, fields: &Fields) -> SynStream
}
impl #impl_generics pdf::object::ToDict for #id #ty_generics #where_clause {
fn to_dict(&self, updater: &mut impl pdf::object::Updater) -> Result<pdf::primitive::Dictionary> {
let mut dict = pdf::primitive::Dictionary::new();
#init_dict
#pdf_type
#( #checks_code )*
#(#fields_ser)*
Expand Down

0 comments on commit e54cbe4

Please sign in to comment.