Struct swash::FontRef

source ·
pub struct FontRef<'a> {
    pub data: &'a [u8],
    pub offset: u32,
    pub key: CacheKey,
}
Expand description

Reference to a font.

This struct encapsulates the data required to access font resources and uniquely identify the font in various caches. Font files can be organized into collections of multiple fonts, so along with a reference to the actual content of the file, we also store a byte offset to the header of the selected font (although most fonts are not collections so this is almost always zero). Note that internal references in the font are stored relative to the base of the file, so the entire file must be kept in memory and it is an error to slice the data at the offset.

§Getting started

As a primer, let’s write a function to read a font file, construct a font reference and print the Attributes and all of the associated LocalizedStrings (including names, copyright information and other metadata).

fn print_localized_strings(font_path: &str) -> Option<()> {
    use swash::FontRef;
    // Read the full font file
    let font_data = std::fs::read(font_path).ok()?;
    // Create a font reference for the first font in the file
    let font = FontRef::from_index(&font_data, 0)?;
    // Print the font attributes (stretch, weight and style)
    println!("{}", font.attributes());
    // Iterate through the localized strings
    for string in font.localized_strings() {
        // Print the string identifier and the actual value
        println!("[{:?}] {}", string.id(), string.to_string());
    }
    Some(())
}

§Owning your fonts

The FontRef struct is designed to be agnostic with regard to the font management policy of higher level crates and applications, and as such, contains borrowed data and is intended to be used as a transient resource. If you’re using this library, you’ll likely want to create your own type to represent a font. Regardless of the complexity of your management strategy, the basic pattern remains the same, so we’ll build a simple Font struct here that can load fonts from a file using a basic Vec<u8> as a backing store.

use swash::{Attributes, CacheKey, Charmap, FontRef};

pub struct Font {
    // Full content of the font file
    data: Vec<u8>,
    // Offset to the table directory
    offset: u32,
    // Cache key
    key: CacheKey,
}

impl Font {
    pub fn from_file(path: &str, index: usize) -> Option<Self> {
        // Read the full font file
        let data = std::fs::read(path).ok()?;
        // Create a temporary font reference for the first font in the file.
        // This will do some basic validation, compute the necessary offset
        // and generate a fresh cache key for us.
        let font = FontRef::from_index(&data, index)?;
        let (offset, key) = (font.offset, font.key);
        // Return our struct with the original file data and copies of the
        // offset and key from the font reference
        Some(Self { data, offset, key })
    }

    // As a convenience, you may want to forward some methods.
    pub fn attributes(&self) -> Attributes {
        self.as_ref().attributes()
    }

    pub fn charmap(&self) -> Charmap {
        self.as_ref().charmap()
    }

    // Create the transient font reference for accessing this crate's
    // functionality.
    pub fn as_ref(&self) -> FontRef {
        // Note that you'll want to initialize the struct directly here as
        // using any of the FontRef constructors will generate a new key which,
        // while completely safe, will nullify the performance optimizations of
        // the caching mechanisms used in this crate.
        FontRef {
            data: &self.data,
            offset: self.offset,
            key: self.key
        }
    }
}

In the example above, it’s trivial to replace the Vec<u8> with an Rc<Vec<u8>> for a reference counted version or an Arc<Vec<u8>> for fonts that are shareable across threads. You may also consider memory mapping your font data, particularly for larger fonts (hello Apple Color Emoji!).

Fields§

§data: &'a [u8]

Full content of a file containing the font.

§offset: u32

Offset to the table directory of the font.

§key: CacheKey

Key for identifying a font in various caches.

Implementations§

source§

impl<'a> FontRef<'a>

source

pub fn from_index(data: &'a [u8], index: usize) -> Option<Self>

Creates a new font from the specified font data and the index of the desired font. Returns None if the data does not represent a font file or the index is out of bounds.

source

pub fn from_offset(data: &'a [u8], offset: u32) -> Option<Self>

Creates a new font from the specified font data and offset to the table directory. Returns None if the offset is out of bounds or the data at the offset does not represent a table directory.

source§

impl<'a> FontRef<'a>

source

pub fn attributes(&self) -> Attributes

Returns the primary attributes for the font.

source

pub fn localized_strings(&self) -> LocalizedStrings<'a>

Returns an iterator over the localized strings for the font.

source

pub fn variations(&self) -> Variations<'a>

Returns an iterator over the variations for the font.

source

pub fn instances(&self) -> Instances<'a>

Returns an iterator over the named instances for the font.

source

pub fn writing_systems(&self) -> WritingSystems<'a>

Returns an iterator over writing systems supported by the font.

source

pub fn features(&self) -> Features<'a>

Returns an iterator over the features supported by a font.

source

pub fn metrics(&self, coords: &'a [NormalizedCoord]) -> Metrics

Returns metrics for the font and the specified normalized variation coordinates.

source

pub fn glyph_metrics(&self, coords: &'a [NormalizedCoord]) -> GlyphMetrics<'a>

Returns glyph metrics for the font and the specified normalized variation coordinates.

source

pub fn charmap(&self) -> Charmap<'a>

Returns the character map for the font.

source

pub fn color_palettes(&self) -> ColorPalettes<'a>

Returns an iterator over the color palettes for the font.

source

pub fn alpha_strikes(&self) -> BitmapStrikes<'a>

Returns an iterator over the alpha bitmap strikes for the font.

source

pub fn color_strikes(&self) -> BitmapStrikes<'a>

Returns an iterator over the color bitmap strikes for the font.

source

pub fn table(&self, tag: Tag) -> Option<&'a [u8]>

Returns the table data for the specified tag.

Trait Implementations§

source§

impl<'a> Clone for FontRef<'a>

source§

fn clone(&self) -> FontRef<'a>

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<'a> TableProvider for &'a FontRef<'a>

source§

fn table_by_tag(&self, tag: Tag) -> Option<&[u8]>

Returns the table for the specified tag.
source§

impl<'a> TableProvider for FontRef<'a>

source§

fn table_by_tag(&self, tag: Tag) -> Option<&[u8]>

Returns the table for the specified tag.
source§

impl<'a> Copy for FontRef<'a>

Auto Trait Implementations§

§

impl<'a> Freeze for FontRef<'a>

§

impl<'a> RefUnwindSafe for FontRef<'a>

§

impl<'a> Send for FontRef<'a>

§

impl<'a> Sync for FontRef<'a>

§

impl<'a> Unpin for FontRef<'a>

§

impl<'a> UnwindSafe for FontRef<'a>

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> CloneToUninit for T
where T: Clone,

source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for T
where T: Clone,

source§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

source§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.