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

Keywords Fix and Refactoring #7

Merged
merged 5 commits into from
May 8, 2019
Merged
Show file tree
Hide file tree
Changes from 4 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
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ readme = "README.md"
build = "src/build_metrics.rs"

[build-dependencies]
lazy_static = "0.2"
lazy_static = "1.2"

[dependencies]
lazy_static = "0.2"
lazy_static = "1.2"
time = "0.1"
5 changes: 2 additions & 3 deletions src/build_metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,7 @@ fn write_cond(f: &mut File, name: &str, encoding: &Encoding) -> Result<()> {
}
}
}
writeln!(f, "]);")?;
Ok(())
writeln!(f, "]);")
}

fn main() {
Expand Down Expand Up @@ -78,7 +77,7 @@ fn main() {
lazy_static! {{",
)
.unwrap();
for font in textfonts.iter() {
for font in &textfonts {
write_cond(f, font, &WIN_ANSI_ENCODING).unwrap();
}
write_cond(f, "Symbol", &SYMBOL_ENCODING).unwrap();
Expand Down
33 changes: 15 additions & 18 deletions src/canvas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,20 +20,20 @@ pub struct Canvas<'a> {
outline_items: &'a mut Vec<OutlineItem>,
}

// Should not be called by user code.
pub fn create_canvas<'a>(
output: &'a mut Write,
fonts: &'a mut HashMap<BuiltinFont, FontRef>,
outline_items: &'a mut Vec<OutlineItem>,
) -> Canvas<'a> {
Canvas {
output,
fonts,
outline_items,
impl<'a> Canvas<'a> {
// Should not be called by user code.
pub(crate) fn new(
output: &'a mut Write,
fonts: &'a mut HashMap<BuiltinFont, FontRef>,
outline_items: &'a mut Vec<OutlineItem>,
) -> Self {
Canvas {
output,
fonts,
outline_items,
}
}
}

impl<'a> Canvas<'a> {
/// Append a closed rectangle with a corner at (x, y) and
/// extending width × height to the to the current path.
pub fn rectangle(
Expand Down Expand Up @@ -163,8 +163,7 @@ impl<'a> Canvas<'a> {
self.curve_to(leftp, top, left, up, left, y)?;
self.curve_to(left, down, leftp, bottom, x, bottom)?;
self.curve_to(rightp, bottom, right, down, right, y)?;
self.curve_to(right, up, rightp, top, x, top)?;
Ok(())
self.curve_to(right, up, rightp, top, x, top)
}
/// Stroke the current path.
pub fn stroke(&mut self) -> io::Result<()> {
Expand All @@ -180,12 +179,11 @@ impl<'a> Canvas<'a> {
}
/// Get a FontRef for a specific font.
pub fn get_font(&mut self, font: BuiltinFont) -> FontRef {
use fontref::create_font_ref;
let next_n = self.fonts.len();
self.fonts
.entry(font)
.or_insert_with(|| {
create_font_ref(
FontRef::new(
next_n,
font.get_encoding().clone(),
Arc::new(font.get_metrics()),
Expand All @@ -204,9 +202,8 @@ impl<'a> Canvas<'a> {
where
F: FnOnce(&mut TextObject) -> io::Result<T>,
{
use textobject::create_text_object;
writeln!(self.output, "BT")?;
let result = render_text(&mut create_text_object(self.output))?;
let result = render_text(&mut TextObject::new(self.output))?;
writeln!(self.output, "ET")?;
Ok(result)
}
Expand Down
116 changes: 58 additions & 58 deletions src/encoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,7 @@ impl Encoding {
/// assert_eq!(None, enc.get_code("☺"));
/// ````
pub fn get_code(&self, name: &str) -> Option<u8> {
match self.name_to_code.get(name) {
Some(&code) => Some(code),
None => None,
}
self.name_to_code.get(name).cloned()
}

/// Get the encoded code point from a (unicode) character.
Expand Down Expand Up @@ -88,7 +85,12 @@ impl Encoding {
/// symb_enc.encode_string("α ∈ ℜ"));
/// ````
pub fn encode_string(&self, text: &str) -> Vec<u8> {
let mut result = Vec::new();
let size = text.len()
+ text
.chars()
.filter(|&c| c == '\\' || c == '(' || c == ')')
.count();
let mut result = Vec::with_capacity(size);
for ch in text.chars() {
match self.encode_char(ch) {
Some(b'\\') => {
Expand All @@ -110,11 +112,9 @@ impl Encoding {
result
}

fn init_block(&mut self, start: u8, data: Vec<&'static str>) {
let mut i = start - 1;
for name in data {
i += 1;
self.name_to_code.insert(name, i);
fn init_block(&mut self, start: u8, data: &[&'static str]) {
for (i, name) in data.iter().enumerate() {
self.name_to_code.insert(name, start + (i as u8));
}
}
}
Expand Down Expand Up @@ -159,78 +159,78 @@ lazy_static! {
name_to_code: BTreeMap::new(),
unicode_to_code: codes
};
result.init_block(0o40, vec!(
result.init_block(0o40, &[
"space", "exclam", "quotedbl", "numbersign",
"dollar", "percent", "ampersand", "quotesingle"));
result.init_block(0o50, vec!(
"dollar", "percent", "ampersand", "quotesingle"]);
result.init_block(0o50, &[
"parenleft", "parenright", "asterisk", "plus",
"comma", "hyphen", "period", "slash"));
result.init_block(0o60, vec!(
"zero", "one", "two", "three", "four", "five", "six", "seven"));
result.init_block(0o70, vec!(
"comma", "hyphen", "period", "slash"]);
result.init_block(0o60, &[
"zero", "one", "two", "three", "four", "five", "six", "seven"]);
result.init_block(0o70, &[
"eight", "nine", "colon", "semicolon",
"less", "equal", "greater", "question"));
result.init_block(0o100, vec!(
"less", "equal", "greater", "question"]);
result.init_block(0o100, &[
"at", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
"W", "X", "Y", "Z"));
result.init_block(0o133, vec!(
"W", "X", "Y", "Z"]);
result.init_block(0o133, &[
"bracketleft",
"backslash", "bracketright", "asciicircum", "underscore"));
result.init_block(0o140, vec!(
"backslash", "bracketright", "asciicircum", "underscore"]);
result.init_block(0o140, &[
"grave", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
"k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
"w", "x", "y", "z"));
result.init_block(0o173, vec!(
"braceleft", "bar", "braceright", "asciitilde"));
result.init_block(0o200, vec!(
"w", "x", "y", "z"]);
result.init_block(0o173, &[
"braceleft", "bar", "braceright", "asciitilde"]);
result.init_block(0o200, &[
"Euro", "..1", "quotesinglbase", "florin",
"quotedblbase", "ellipsis", "dagger", "daggerdbl"));
result.init_block(0o210, vec!(
"quotedblbase", "ellipsis", "dagger", "daggerdbl"]);
result.init_block(0o210, &[
"circumflex", "perthousand", "Scaron", "guilsinglleft",
"OE", "..5", "Zcaron", "..7"));
result.init_block(0o220, vec!(
"OE", "..5", "Zcaron", "..7"]);
result.init_block(0o220, &[
"..0", "quoteleft", "quoteright", "quotedblleft",
"quotedblright", "bullet", "endash", "emdash"));
result.init_block(0o230, vec!(
"quotedblright", "bullet", "endash", "emdash"]);
result.init_block(0o230, &[
"tilde", "trademark", "scaron", "guilsinglright",
"oe", "..5", "zcaron", "Ydieresis"));
result.init_block(0o240, vec!(
"oe", "..5", "zcaron", "Ydieresis"]);
result.init_block(0o240, &[
"..0", "exclamdown", "cent", "sterling",
"currency", "yen", "brokenbar", "section"));
result.init_block(0o250, vec!(
"currency", "yen", "brokenbar", "section"]);
result.init_block(0o250, &[
"dieresis", "copyright", "ordfeminine", "guillemotleft",
"logicalnot", "..5", "registered", "macron"));
result.init_block(0o260, vec!(
"logicalnot", "..5", "registered", "macron"]);
result.init_block(0o260, &[
"degree", "plusminus", "twosuperior", "threesuperior",
"acute", "mu", "paragraph", "periodcentered"));
result.init_block(0o270, vec!(
"acute", "mu", "paragraph", "periodcentered"]);
result.init_block(0o270, &[
"cedilla", "onesuperior", "ordmasculine", "guillemotright",
"onequarter", "onehalf", "threequarters", "questiondown"));
result.init_block(0o300, vec!(
"onequarter", "onehalf", "threequarters", "questiondown"]);
result.init_block(0o300, &[
"Agrave", "Aacute", "Acircumflex", "Atilde",
"Adieresis", "Aring", "AE", "Ccedilla"));
result.init_block(0o310, vec!(
"Adieresis", "Aring", "AE", "Ccedilla"]);
result.init_block(0o310, &[
"Egrave", "Eacute", "Ecircumflex", "Edieresis",
"Igrave", "Iacute", "Icircumflex", "Idieresis"));
result.init_block(0o320, vec!(
"Igrave", "Iacute", "Icircumflex", "Idieresis"]);
result.init_block(0o320, &[
"Eth", "Ntilde", "Ograve", "Oacute",
"Ocircumflex", "Otilde", "Odieresis", "multiply"));
result.init_block(0o330, vec!(
"Ocircumflex", "Otilde", "Odieresis", "multiply"]);
result.init_block(0o330, &[
"Oslash", "Ugrave", "Uacute", "Ucircumflex",
"Udieresis", "Yacute", "Thorn", "germandbls"));
result.init_block(0o340, vec!(
"Udieresis", "Yacute", "Thorn", "germandbls"]);
result.init_block(0o340, &[
"agrave", "aacute", "acircumflex", "atilde",
"adieresis", "aring", "ae", "ccedilla"));
result.init_block(0o350, vec!(
"adieresis", "aring", "ae", "ccedilla"]);
result.init_block(0o350, &[
"egrave", "eacute", "ecircumflex", "edieresis",
"igrave", "iacute", "icircumflex", "idieresis"));
result.init_block(0o360, vec!(
"igrave", "iacute", "icircumflex", "idieresis"]);
result.init_block(0o360, &[
"eth", "ntilde", "ograve", "oacute",
"ocircumflex", "otilde", "odieresis", "divide"));
result.init_block(0o370, vec!(
"ocircumflex", "otilde", "odieresis", "divide"]);
result.init_block(0o370, &[
"oslash", "ugrave", "uacute", "ucircumflex",
"udieresis", "yacute", "thorn", "ydieresis"));
"udieresis", "yacute", "thorn", "ydieresis"]);
result
};

Expand Down
5 changes: 1 addition & 4 deletions src/fontmetrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,7 @@ impl FontMetrics {
/// Get the width of a specific character.
/// The character is given in the encoding of the FontMetrics object.
pub fn get_width(&self, char: u8) -> Option<u16> {
match self.widths.get(&char) {
Some(&w) => Some(w),
None => None,
}
self.widths.get(&char).cloned()
}
}

Expand Down
43 changes: 21 additions & 22 deletions src/fontref.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,20 +24,20 @@ pub struct FontRef {
metrics: Arc<FontMetrics>,
}

// Hidden from user code by not beeing a constructor method of FontRef.
pub fn create_font_ref(
n: usize,
encoding: Encoding,
metrics: Arc<FontMetrics>,
) -> FontRef {
FontRef {
n,
encoding,
metrics,
impl FontRef {
// Hidden from user code by not beeing a constructor method of FontRef.
pub(crate) fn new(
n: usize,
encoding: Encoding,
metrics: Arc<FontMetrics>,
) -> Self {
FontRef {
n,
encoding,
metrics,
}
}
}

impl FontRef {
/// Get the encoding used by the referenced font.
pub fn get_encoding(&self) -> &Encoding {
&self.encoding
Expand All @@ -53,16 +53,15 @@ impl FontRef {
/// This unit is what is used in some places internally in pdf files
/// and in some methods on a [TextObject](struct.TextObject.html).
pub fn get_width_raw(&self, text: &str) -> u32 {
let mut result = 0;
for char in text.chars() {
result += u32::from(
self.encoding
.encode_char(char)
.and_then(|ch| self.metrics.get_width(ch))
.unwrap_or(100),
);
}
result
text.chars().fold(0, |result, char| {
result
+ u32::from(
self.encoding
.encode_char(char)
.and_then(|ch| self.metrics.get_width(ch))
.unwrap_or(100),
)
})
}
}

Expand Down
12 changes: 6 additions & 6 deletions src/fontsource.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use fontmetrics::{get_builtin_metrics, FontMetrics};
use std::cmp::Eq;
use std::hash::Hash;
use std::io::{self, Write};
use std::ops::Add;
use Pdf;

/// The "Base14" built-in fonts in PDF.
Expand Down Expand Up @@ -117,11 +116,12 @@ impl FontSource for BuiltinFont {

fn get_width_raw(&self, text: &str) -> u32 {
let metrics = self.get_metrics();
self.get_encoding()
.encode_string(text)
.iter()
.map(|&ch| u32::from(metrics.get_width(ch).unwrap_or(100)))
.fold(0, Add::add)
self.get_encoding().encode_string(text).iter().fold(
0,
|result, &ch| {
result + u32::from(metrics.get_width(ch).unwrap_or(100))
},
)
}

fn get_metrics(&self) -> FontMetrics {
Expand Down
Loading