Skip to content

Commit

Permalink
Turn Data into a wrapper type instead
Browse files Browse the repository at this point in the history
  • Loading branch information
LaurenzV committed Mar 1, 2025
1 parent d511d34 commit 87cffac
Show file tree
Hide file tree
Showing 9 changed files with 85 additions and 38 deletions.
12 changes: 5 additions & 7 deletions crates/krilla/src/font/bitmap.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
//! Drawing bitmap-based glyphs to a surface.
use std::sync::Arc;

use skrifa::{GlyphId, MetadataProvider};
use tiny_skia_path::{Size, Transform};

Expand All @@ -23,7 +21,7 @@ pub(crate) fn draw_glyph(font: Font, glyph: GlyphId, surface: &mut Surface) -> O

match bitmap_glyph.data {
BitmapData::Png(data) => {
let image = Image::from_png(Arc::new(data.to_vec()), false)?;
let image = Image::from_png(data.to_vec().into(), false)?;
let size = Size::from_wh(image.size().0 as f32, image.size().1 as f32).unwrap();

// Adapted from vello.
Expand Down Expand Up @@ -447,6 +445,7 @@ mod utils {
mod tests {
use crate::document::Document;
use crate::tests::{all_glyphs_to_pdf, NOTO_COLOR_EMOJI_CBDT};
use crate::Data;
use krilla_macros::visreg;

// We don't run on pdf.js because it leads to a high pixel difference in CI
Expand All @@ -460,10 +459,9 @@ mod tests {
#[cfg(target_os = "macos")]
#[visreg(document, all)]
fn apple_color_emoji(document: &mut Document) {
use std::sync::Arc;

let font_data =
Arc::new(std::fs::read("/System/Library/Fonts/Apple Color Emoji.ttc").unwrap());
let font_data: Data = std::fs::read("/System/Library/Fonts/Apple Color Emoji.ttc")
.unwrap()
.into();
all_glyphs_to_pdf(font_data, None, false, true, document);
}
}
22 changes: 13 additions & 9 deletions crates/krilla/src/font/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,18 +69,22 @@ impl Font {
pub fn new(data: Data, index: u32, allow_color: bool) -> Option<Self> {
let font_info = FontInfo::new(data.as_ref().as_ref(), index, allow_color)?;

Font::new_with_info(data, Arc::new(font_info))
Font::new_with_info(data.clone(), Arc::new(font_info))
}

pub(crate) fn new_with_info(data: Data, font_info: Arc<FontInfo>) -> Option<Self> {
let font_ref_yoke =
Yoke::<FontRefYoke<'static>, Data>::attach_to_cart(data.clone(), |data| {
let font_ref = FontRef::from_index(data.as_ref(), 0).unwrap();
FontRefYoke {
font_ref: font_ref.clone(),
glyph_metrics: font_ref.glyph_metrics(Size::unscaled(), LocationRef::default()),
}
});
Yoke::<FontRefYoke<'static>, Arc<dyn AsRef<[u8]> + Send + Sync>>::attach_to_cart(
data.0.clone(),
|data| {
let font_ref = FontRef::from_index(data.as_ref(), 0).unwrap();
FontRefYoke {
font_ref: font_ref.clone(),
glyph_metrics: font_ref
.glyph_metrics(Size::unscaled(), LocationRef::default()),
}
},
);

Some(Font(Arc::new(Prehashed::new(Repr {
font_data: data,
Expand Down Expand Up @@ -200,7 +204,7 @@ pub(crate) struct FontInfo {
struct Repr {
font_info: Arc<FontInfo>,
font_data: Data,
font_ref_yoke: Yoke<FontRefYoke<'static>, Data>,
font_ref_yoke: Yoke<FontRefYoke<'static>, Arc<dyn AsRef<[u8]> + Send + Sync>>,
}

impl Hash for Repr {
Expand Down
41 changes: 38 additions & 3 deletions crates/krilla/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ let mut font = {
let path =
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts/NotoSans-Regular.ttf");
let data = std::fs::read(&path).unwrap();
Font::new(Arc::new(data), 0, true).unwrap()
Font::new(data.into(), 0, true).unwrap()
};
// Add a new page with dimensions 200x200.
Expand Down Expand Up @@ -123,7 +123,10 @@ pub mod geom;
pub mod metadata;

pub use object::*;
use std::hash::{Hash, Hasher};
use std::sync::Arc;
use yoke::Yokeable;

pub mod paint;
pub mod path;
pub mod stream;
Expand All @@ -136,8 +139,40 @@ pub(crate) mod content;
#[cfg(test)]
pub(crate) mod tests;

/// Type alias for `Arc<dyn AsRef<[u8]> + Send + Sync>`.
pub type Data = Arc<dyn AsRef<[u8]> + Send + Sync>;
/// A type that holds some bytes.
#[derive(Clone)]
pub struct Data(Arc<dyn AsRef<[u8]> + Send + Sync>);

impl Data {
/// Return a reference to the underlying bytes.
pub fn as_ref(&self) -> &[u8] {
self.0.as_ref().as_ref()
}
}

impl Hash for Data {
fn hash<H: Hasher>(&self, state: &mut H) {
self.0.as_ref().as_ref().hash(state);
}
}

impl From<Arc<dyn AsRef<[u8]> + Send + Sync>> for Data {
fn from(value: Arc<dyn AsRef<[u8]> + Send + Sync>) -> Self {
Self(value)
}
}

impl From<Vec<u8>> for Data {
fn from(value: Vec<u8>) -> Self {
Self(Arc::new(value))
}
}

impl From<Arc<Vec<u8>>> for Data {
fn from(value: Arc<Vec<u8>>) -> Self {
Self(value)
}
}

pub use document::*;
pub use serialize::{SerializeSettings, SvgSettings};
8 changes: 4 additions & 4 deletions crates/krilla/src/object/font/cid_font.rs
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,7 @@ mod tests {
use crate::serialize::SerializeContext;
use crate::surface::{Surface, TextDirection};
use crate::tests::{LATIN_MODERN_ROMAN, NOTO_SANS, NOTO_SANS_ARABIC};
use crate::Data;
use krilla_macros::{snapshot, visreg};
use skrifa::GlyphId;
use tiny_skia_path::Point;
Expand Down Expand Up @@ -465,10 +466,9 @@ mod tests {
#[cfg(target_os = "macos")]
#[visreg(macos)]
fn cid_font_true_type_collection(surface: &mut Surface) {
use std::sync::Arc;

let font_data =
Arc::new(std::fs::read("/System/Library/Fonts/Supplemental/Songti.ttc").unwrap());
let font_data: Data = std::fs::read("/System/Library/Fonts/Supplemental/Songti.ttc")
.unwrap()
.into();
let font_1 = Font::new(font_data.clone(), 0, true).unwrap();
let font_2 = Font::new(font_data.clone(), 3, true).unwrap();
let font_3 = Font::new(font_data, 6, true).unwrap();
Expand Down
5 changes: 3 additions & 2 deletions crates/krilla/src/object/image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -742,7 +742,6 @@ mod tests {
};
use crate::Document;
use krilla_macros::{snapshot, visreg};
use std::sync::Arc;
use tiny_skia_path::Size;

#[snapshot]
Expand Down Expand Up @@ -961,7 +960,9 @@ mod tests {
#[snapshot(single_page)]
fn image_interpolate(page: &mut Page) {
let image = Image::from_png(
Arc::new(std::fs::read(ASSETS_PATH.join("images").join("rgba8.png")).unwrap()),
std::fs::read(ASSETS_PATH.join("images").join("rgba8.png"))
.unwrap()
.into(),
true,
)
.unwrap();
Expand Down
2 changes: 1 addition & 1 deletion crates/krilla/src/serialize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -348,7 +348,7 @@ impl SerializeContext {
.font_cache
.get(&font_info.clone())
.cloned()
.unwrap_or(Font::new_with_info(font_data, font_info).unwrap());
.unwrap_or(Font::new_with_info(font_data.into(), font_info).unwrap());
map.insert(id, font);
}
}
Expand Down
8 changes: 4 additions & 4 deletions crates/krilla/src/svg/image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,19 +25,19 @@ pub(crate) fn render(

match image.kind() {
ImageKind::JPEG(d) => {
let image = Image::from_jpeg(d.clone(), false)?;
let image = Image::from_jpeg(d.clone().into(), false)?;
surface.draw_image(image, size);
}
ImageKind::PNG(d) => {
let image = Image::from_png(d.clone(), false)?;
let image = Image::from_png(d.clone().into(), false)?;
surface.draw_image(image, size);
}
ImageKind::GIF(d) => {
let image = Image::from_gif(d.clone(), false)?;
let image = Image::from_gif(d.clone().into(), false)?;
surface.draw_image(image, size);
}
ImageKind::WEBP(d) => {
let image = Image::from_webp(d.clone(), false)?;
let image = Image::from_webp(d.clone().into(), false)?;
surface.draw_image(image, size);
}
ImageKind::SVG(t) => {
Expand Down
23 changes: 16 additions & 7 deletions crates/krilla/src/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ use crate::stream::StreamBuilder;
use crate::surface::Surface;
use crate::validation::Validator;
use crate::version::PdfVersion;
use crate::Data;
use crate::{SerializeSettings, SvgSettings};

#[allow(dead_code)]
Expand Down Expand Up @@ -83,8 +84,8 @@ static FONT_PATH: LazyLock<PathBuf> = LazyLock::new(|| WORKSPACE_PATH.join("asse

macro_rules! lazy_font {
($name:ident, $path:expr) => {
pub static $name: LazyLock<Arc<Vec<u8>>> =
LazyLock::new(|| Arc::new(std::fs::read($path).unwrap()));
pub static $name: LazyLock<Data> =
LazyLock::new(|| Arc::new(std::fs::read($path).unwrap()).into());
};
}

Expand Down Expand Up @@ -273,31 +274,39 @@ pub fn rect_to_path(x1: f32, y1: f32, x2: f32, y2: f32) -> Path {

pub fn load_png_image(name: &str) -> Image {
Image::from_png(
Arc::new(std::fs::read(ASSETS_PATH.join("images").join(name)).unwrap()),
std::fs::read(ASSETS_PATH.join("images").join(name))
.unwrap()
.into(),
false,
)
.unwrap()
}

pub fn load_jpg_image(name: &str) -> Image {
Image::from_jpeg(
Arc::new(std::fs::read(ASSETS_PATH.join("images").join(name)).unwrap()),
std::fs::read(ASSETS_PATH.join("images").join(name))
.unwrap()
.into(),
false,
)
.unwrap()
}

pub fn load_gif_image(name: &str) -> Image {
Image::from_gif(
Arc::new(std::fs::read(ASSETS_PATH.join("images").join(name)).unwrap()),
std::fs::read(ASSETS_PATH.join("images").join(name))
.unwrap()
.into(),
false,
)
.unwrap()
}

pub fn load_webp_image(name: &str) -> Image {
Image::from_webp(
Arc::new(std::fs::read(ASSETS_PATH.join("images").join(name)).unwrap()),
std::fs::read(ASSETS_PATH.join("images").join(name))
.unwrap()
.into(),
false,
)
.unwrap()
Expand Down Expand Up @@ -543,7 +552,7 @@ fn is_pix_diff(pixel1: &Rgba<u8>, pixel2: &Rgba<u8>) -> bool {
}

pub fn all_glyphs_to_pdf(
font_data: Arc<Vec<u8>>,
font_data: Data,
glyphs: Option<Vec<(GlyphId, String)>>,
color_cycling: bool,
allow_color: bool,
Expand Down
2 changes: 1 addition & 1 deletion examples/parley/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ fn main() {
// Get the krilla font.
let krilla_font = font_cache
.entry(id)
.or_insert_with(|| Font::new(font_data, font.index, true).unwrap());
.or_insert_with(|| Font::new(font_data.into(), font.index, true).unwrap());
let font_size = run.font_size();

// This is part is somewhat convoluted, the reason being that each glyph might
Expand Down

0 comments on commit 87cffac

Please sign in to comment.