Skip to content
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
16 changes: 16 additions & 0 deletions fontique/src/collection/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,12 @@ impl Collection {
}
}

/// Converts an unshared collection into a shared collection
#[cfg(feature = "std")]
pub fn make_shared(&mut self) {
self.inner.make_shared();
}

/// Load system fonts. If system fonts are already loaded then this does nothing.
pub fn load_system_fonts(&mut self) {
if self.inner.system.is_none() {
Expand Down Expand Up @@ -254,6 +260,16 @@ impl Inner {
}
}

#[cfg(feature = "std")]
pub fn make_shared(&mut self) {
if self.shared.is_none() {
self.shared = Some(Arc::new(Shared {
data: Mutex::new(core::mem::take(&mut self.data)),
version: AtomicCounter::new(self.shared_version),
}));
}
}

/// Load system fonts. If system fonts are already loaded then they will be reloaded.
pub fn load_system_fonts(&mut self) {
self.system = Some(System::new());
Expand Down
33 changes: 33 additions & 0 deletions fontique/src/source_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,15 @@ impl SourceCache {
}
}

/// Turns an unshared cache into a shared cache that can used to ensure that fonts only get loaded once
/// even when they are loaded across multiple threads.
#[cfg(feature = "std")]
pub fn make_shared(&mut self) {
if self.shared.is_none() {
self.shared = Some(Arc::new(Mutex::new(Shared::from_local(&self.cache))));
}
}

/// Returns the [blob] for the given font data, attempting to load
/// it from the file system if not already present.
///
Expand Down Expand Up @@ -159,6 +168,17 @@ struct Shared {

#[cfg(feature = "std")]
impl Shared {
/// Bootstrap a shared cache from a local one
fn from_local(unshared: &HashMap<SourceId, Entry<Blob<u8>>>) -> Self {
let shared_cache: HashMap<SourceId, Entry<WeakBlob<u8>>> = unshared
.iter()
.map(|(key, value)| (*key, value.into()))
.collect();
Self {
cache: shared_cache,
}
}

pub fn get(&mut self, id: SourceId, path: &Path) -> Option<Blob<u8>> {
use hashbrown::hash_map::Entry as HashEntry;
match self.cache.entry(id) {
Expand Down Expand Up @@ -213,6 +233,19 @@ struct EntryData<T> {
serial: u64,
}

#[cfg(feature = "std")]
impl<T> From<&Entry<Blob<T>>> for Entry<WeakBlob<T>> {
fn from(value: &Entry<Blob<T>>) -> Self {
match value {
Entry::Loaded(entry_data) => Self::Loaded(EntryData {
font_data: entry_data.font_data.downgrade(),
serial: entry_data.serial,
}),
Entry::Failed => Self::Failed,
}
}
}

#[cfg(feature = "std")]
pub(crate) fn load_blob(path: &Path) -> Option<Blob<u8>> {
let file = std::fs::File::open(path).ok()?;
Expand Down