use std::borrow::Borrow;
use std::fs::File;
use std::io::Read;
use std::path::Path;
use std::sync::{Arc, OnceLock};
use rusttype;
pub struct Font {
font: rusttype::Font<'static>,
}
impl Font {
pub fn new(path: &Path) -> Option<Font> {
let mut memory = Vec::new();
let mut file = File::open(path).unwrap();
let _ = file.read_to_end(&mut memory).unwrap();
Font::from_bytes(&memory)
}
pub fn from_bytes(memory: &[u8]) -> Option<Font> {
let font = rusttype::Font::try_from_vec(memory.to_vec()).unwrap();
Some(Font { font })
}
#[allow(clippy::should_implement_trait)]
pub fn default() -> Arc<Font> {
const DATA: &[u8] = include_bytes!("WorkSans-Regular.ttf");
static DEFAULT_FONT_SINGLETON: OnceLock<Arc<Font>> = OnceLock::new();
DEFAULT_FONT_SINGLETON
.get_or_init(|| {
Arc::new(Font::from_bytes(DATA).expect("Default font creation failed."))
})
.clone()
}
#[inline]
pub fn font(&self) -> &rusttype::Font<'static> {
&self.font
}
#[inline]
pub fn uid(font: &Arc<Font>) -> usize {
(*font).borrow() as *const Font as usize
}
}