use std::fmt;
use std::io;
use std::ops::Deref;
use std::sync::Arc;
use skrifa::font::{Blob, Font};
#[derive(Clone)]
pub struct FontBytes(Bytes);
#[derive(Clone)]
enum Bytes {
Static(&'static [u8]),
Shared(Arc<[u8]>),
}
impl FontBytes {
pub(crate) fn blob(&self) -> Blob {
match &self.0 {
Bytes::Static(bytes) => Blob::Static(bytes),
Bytes::Shared(bytes) => Blob::Shared(Arc::new(Arc::clone(bytes))),
}
}
}
impl From<&'static [u8]> for FontBytes {
fn from(bytes: &'static [u8]) -> Self {
Self(Bytes::Static(bytes))
}
}
impl From<Arc<[u8]>> for FontBytes {
fn from(bytes: Arc<[u8]>) -> Self {
Self(Bytes::Shared(bytes))
}
}
impl Deref for FontBytes {
type Target = [u8];
fn deref(&self) -> &[u8] {
match &self.0 {
Bytes::Static(bytes) => bytes,
Bytes::Shared(bytes) => bytes,
}
}
}
impl AsRef<[u8]> for FontBytes {
fn as_ref(&self) -> &[u8] {
self
}
}
impl PartialEq for FontBytes {
fn eq(&self, other: &Self) -> bool {
**self == **other
}
}
impl Eq for FontBytes {}
impl fmt::Debug for FontBytes {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "FontBytes({} bytes)", self.len())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum FaceOrigin {
Caller,
BuiltIn,
}
pub(crate) struct LoadedFile {
pub(crate) data: FontBytes,
pub(crate) fonts: Box<[Font]>,
}
impl LoadedFile {
pub(crate) fn new(data: FontBytes, fonts: Vec<Font>) -> Self {
Self {
data,
fonts: fonts.into(),
}
}
}
pub(crate) enum FaceSource {
Given(LoadedFile),
#[cfg(not(target_arch = "wasm32"))]
Folder(crate::folder::FolderFile),
}
impl FaceSource {
pub(crate) fn load(&self) -> Result<&LoadedFile, FileNotRead> {
match self {
Self::Given(file) => Ok(file),
#[cfg(not(target_arch = "wasm32"))]
Self::Folder(file) => file.load(),
}
}
pub(crate) fn loaded(&self) -> Option<&LoadedFile> {
match self {
Self::Given(file) => Some(file),
#[cfg(not(target_arch = "wasm32"))]
Self::Folder(file) => file.loaded().ok(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub struct FileNotRead {
pub file: String,
pub cause: NotReadCause,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum NotReadCause {
Changed,
Unreadable(io::ErrorKind),
}
impl fmt::Display for NotReadCause {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Changed => f.write_str("the file changed after its folder was read"),
Self::Unreadable(kind) => write!(f, "the file could not be read ({kind})"),
}
}
}
impl fmt::Display for FileNotRead {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"the font file {} did not load: {}",
self.file, self.cause
)
}
}
impl std::error::Error for FileNotRead {}