Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce the Buf type #47

Open
wants to merge 26 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion benches/oneshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ fn bench_content() -> Vec<u8> {
c.save_state();
c.set_flatness(10);
c.restore_state();
c.finish()
c.finish().into_bytes()
}

fn bench_new() -> Pdf {
Expand Down
53 changes: 53 additions & 0 deletions examples/limits.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
//! This example shows how you can track PDF limits of your chunks.

use pdf_writer::{Chunk, Content, Limits, Name, Ref};

fn main() {
let mut limits = Limits::new();

let mut content = Content::new();
content.transform([-3.4, 0.0, 0.0, 3.1, 100.0, 100.0]);
content.line_to(15.0, -26.1);
let buf = content.finish();
// This will have the limits:
// - Max real number: 26.1 (for negative values we use their absolute value)
// - Max int number 100 (even though above 100.0 is a float number, it will be coerced into an
// integer, and thus counts towards the int limit)
limits.merge(buf.limits());

let mut chunk = Chunk::new();
chunk.stream(Ref::new(1), &buf.into_bytes());
chunk.type3_font(Ref::new(2)).name(Name(b"A_long_font_name"));
// This will update the limit for the maximum name and dictionary length.
limits.merge(chunk.limits());

// This is what the final PDF will look like.
assert_eq!(
chunk.as_bytes(),
b"1 0 obj
<<
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Asserting the PDF in the example is a bit unconventional. Do you think we need this?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Print it instead? Or just remove it completely?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The other examples write it to a file

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm yeah but the other examples also create an actually valid PDF file. :p

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can change it so it’s a valid PDF too, but maybe a bit unnecessary if it’s just about showing how to use the Limits API.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see. Maybe we can just completely ignore it?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So remove all asserts? Or just the one from the PDF buffer?

/Length 34
>>
stream
-3.4 0 0 3.1 100 100 cm
15 -26.1 l
endstream
endobj

2 0 obj
<<
/Type /Font
/Subtype /Type3
/Name /A_long_font_name
>>
endobj

"
);

// And the limits should match, as well!
assert_eq!(limits.int(), 100);
assert_eq!(limits.real(), 26.1);
assert_eq!(limits.name_len(), 16);
assert_eq!(limits.dict_entries(), 3);
}
246 changes: 225 additions & 21 deletions src/buf.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,132 @@
use super::Primitive;

/// Additional methods for byte buffers.
pub trait BufExt {
fn push_val<T: Primitive>(&mut self, value: T);
fn push_int(&mut self, value: i32);
fn push_float(&mut self, value: f32);
fn push_decimal(&mut self, value: f32);
fn push_hex(&mut self, value: u8);
fn push_hex_u16(&mut self, value: u16);
fn push_octal(&mut self, value: u8);
use std::ops::Deref;
LaurenzV marked this conversation as resolved.
Show resolved Hide resolved

/// Tracks the limits of data types used in a buffer.
#[derive(Clone, PartialEq, Debug, Default)]
pub struct Limits {
int: i32,
real: f32,
name_len: usize,
str_len: usize,
array_len: usize,
dict_entries: usize,
}

impl Limits {
/// Create a new `Limits` struct with all values initialized to zero.
pub fn new() -> Self {
Self::default()
}

/// Get the absolute value of the largest positive/negative integer number.
pub fn int(&self) -> i32 {
self.int
}

/// Get the absolute value of the largest positive/negative real number.
pub fn real(&self) -> f32 {
self.real
}

/// Get the maximum length of any used name.
pub fn name_len(&self) -> usize {
self.name_len
}

/// Get the maximum length of any used array.
pub fn array_len(&self) -> usize {
self.array_len
}

/// Get the maximum number of entries in any dictionary.
pub fn dict_entries(&self) -> usize {
self.dict_entries
}

/// Get the maximum length of any used string.
pub fn str_len(&self) -> usize {
self.str_len
}

pub(crate) fn register_int(&mut self, val: i32) {
self.int = self.int.max(val.abs());
}

pub(crate) fn register_real(&mut self, val: f32) {
self.real = self.real.max(val.abs());
}

pub(crate) fn register_name_len(&mut self, len: usize) {
self.name_len = self.name_len.max(len);
}

pub(crate) fn register_str_len(&mut self, len: usize) {
self.str_len = self.str_len.max(len);
}

pub(crate) fn register_array_len(&mut self, len: usize) {
self.array_len = self.array_len.max(len);
}

pub(crate) fn register_dict_entries(&mut self, len: usize) {
self.dict_entries = self.dict_entries.max(len);
}

/// Merge two `Limits` with each other, taking the maximum
/// of each field from both.
pub fn merge(&mut self, other: &Limits) {
self.register_int(other.int);
self.register_real(other.real);
self.register_name_len(other.name_len);
self.register_str_len(other.str_len);
self.register_array_len(other.array_len);
self.register_dict_entries(other.dict_entries);
}
}

/// A buffer of arbitrary PDF content.
#[derive(Clone, PartialEq, Debug)]
pub struct Buf {
pub(crate) inner: Vec<u8>,
pub(crate) limits: Limits,
}

impl BufExt for Vec<u8> {
impl Buf {
pub(crate) fn new() -> Self {
Self { inner: Vec::new(), limits: Limits::new() }
}

pub(crate) fn with_capacity(capacity: usize) -> Self {
Self {
inner: Vec::with_capacity(capacity),
limits: Limits::new(),
}
}

/// Get the underlying bytes of the buffer.
pub fn into_bytes(self) -> Vec<u8> {
self.inner
}

/// Return the limits of the buffer.
pub fn limits(&self) -> &Limits {
&self.limits
}

#[inline]
fn push_val<T: Primitive>(&mut self, value: T) {
pub(crate) fn push_val<T: Primitive>(&mut self, value: T) {
value.write(self);
}

#[inline]
fn push_int(&mut self, value: i32) {
self.extend(itoa::Buffer::new().format(value).as_bytes());
pub(crate) fn push_int(&mut self, value: i32) {
self.limits.register_int(value);
self.extend_slice(itoa::Buffer::new().format(value).as_bytes());
}

#[inline]
fn push_float(&mut self, value: f32) {
pub(crate) fn push_float(&mut self, value: f32) {
// Don't write the decimal point if we don't need it.
// Also, integer formatting is way faster.
if value as i32 as f32 == value {
Expand All @@ -35,22 +138,40 @@ impl BufExt for Vec<u8> {

/// Like `push_float`, but forces the decimal point.
#[inline]
fn push_decimal(&mut self, value: f32) {
pub(crate) fn push_decimal(&mut self, value: f32) {
self.limits.register_real(value);

if value == 0.0 || (value.abs() > 1e-6 && value.abs() < 1e12) {
self.extend(ryu::Buffer::new().format(value).as_bytes());
self.extend_slice(ryu::Buffer::new().format(value).as_bytes());
} else {
#[inline(never)]
fn write_extreme(buf: &mut Vec<u8>, value: f32) {
fn write_extreme(buf: &mut Buf, value: f32) {
use std::io::Write;
write!(buf, "{}", value).unwrap();
write!(buf.inner, "{}", value).unwrap();
}

write_extreme(self, value);
}
}

#[inline]
fn push_hex(&mut self, value: u8) {
pub(crate) fn extend_slice(&mut self, other: &[u8]) {
self.inner.extend(other);
}

#[inline]
pub(crate) fn extend(&mut self, other: &Buf) {
self.limits.merge(&other.limits);
self.inner.extend(&other.inner);
}

#[inline]
pub(crate) fn push(&mut self, b: u8) {
self.inner.push(b);
}

#[inline]
pub(crate) fn push_hex(&mut self, value: u8) {
fn hex(b: u8) -> u8 {
if b < 10 {
b'0' + b
Expand All @@ -64,13 +185,13 @@ impl BufExt for Vec<u8> {
}

#[inline]
fn push_hex_u16(&mut self, value: u16) {
pub(crate) fn push_hex_u16(&mut self, value: u16) {
self.push_hex((value >> 8) as u8);
self.push_hex(value as u8);
}

#[inline]
fn push_octal(&mut self, value: u8) {
pub(crate) fn push_octal(&mut self, value: u8) {
fn octal(b: u8) -> u8 {
b'0' + b
}
Expand All @@ -79,4 +200,87 @@ impl BufExt for Vec<u8> {
self.push(octal((value >> 3) & 7));
self.push(octal(value & 7));
}

#[inline]
pub(crate) fn reserve(&mut self, additional: usize) {
self.inner.reserve(additional)
}
}

impl Deref for Buf {
type Target = [u8];

fn deref(&self) -> &Self::Target {
&self.inner
}
}

#[cfg(test)]
mod tests {
use super::*;
use crate::{Chunk, Content, Finish, Name, Rect, Ref, Str, TextStr};

#[test]
fn test_content_limits() {
let mut limits = Limits::default();

let mut content = Content::new();
content.cubic_to(14.3, 16.2, 22.6, 30.9, 50.1, 40.0);
content.show(Str(b"Some text"));
content.set_font(Name(b"NotoSans"), 10.0);
let buf = content.finish();
limits.merge(buf.limits());

let mut content = Content::new();
content.line_to(55.0, -75.3);
content.set_font(Name(b"Noto"), 10.0);
content
.show_positioned()
.items()
.show(Str(b"A"))
.show(Str(b"B"))
.adjust(32.0);
content
.marked_content_point_with_properties(Name(b"Hi"))
.properties()
.actual_text(TextStr("text"));
let buf = content.finish();
limits.merge(buf.limits());

assert_eq!(
limits,
Limits {
int: 55,
real: 75.3,
name_len: 10,
str_len: 9,
array_len: 3,
dict_entries: 1,
}
)
}

#[test]
fn test_chunk_limits() {
let mut limits = Limits::default();

let mut chunk = Chunk::new();
let mut x_object = chunk.form_xobject(Ref::new(1), &[]);
x_object.bbox(Rect::new(4.0, 6.0, 22.1, 31.0));
x_object.finish();

limits.merge(chunk.limits());

assert_eq!(
limits,
Limits {
int: 31,
real: 22.1,
name_len: 7,
str_len: 0,
array_len: 4,
dict_entries: 4,
}
)
}
}
Loading