1// font-kit/src/handle.rs
2//
3// Copyright © 2018 The Pathfinder Project Developers.
4//
5// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8// option. This file may not be copied, modified, or distributed
9// except according to those terms.
10
11//! Encapsulates the information needed to locate and open a font.
12//!
13//! This is either the path to the font or the raw in-memory font data.
14//!
15//! To open the font referenced by a handle, use a loader.
16
17use std::path::PathBuf;
18use std::sync::Arc;
19
20use crate::error::FontLoadingError;
21use crate::font::Font;
22
23/// Encapsulates the information needed to locate and open a font.
24///
25/// This is either the path to the font or the raw in-memory font data.
26///
27/// To open the font referenced by a handle, use a loader.
28#[derive(Debug, Clone)]
29pub enum Handle {
30 /// A font on disk referenced by a path.
31 Path {
32 /// The path to the font.
33 path: PathBuf,
34 /// The index of the font, if the path refers to a collection.
35 ///
36 /// If the path refers to a single font, this value will be 0.
37 font_index: u32,
38 },
39 /// A font in memory.
40 Memory {
41 /// The raw TrueType/OpenType/etc. data that makes up this font.
42 bytes: Arc<Vec<u8>>,
43 /// The index of the font, if the memory consists of a collection.
44 ///
45 /// If the memory consists of a single font, this value will be 0.
46 font_index: u32,
47 },
48}
49
50impl Handle {
51 /// Creates a new handle from a path.
52 ///
53 /// `font_index` specifies the index of the font to choose if the path points to a font
54 /// collection. If the path points to a single font file, pass 0.
55 #[inline]
56 pub fn from_path(path: PathBuf, font_index: u32) -> Handle {
57 Handle::Path { path, font_index }
58 }
59
60 /// Creates a new handle from raw TTF/OTF/etc. data in memory.
61 ///
62 /// `font_index` specifies the index of the font to choose if the memory represents a font
63 /// collection. If the memory represents a single font file, pass 0.
64 #[inline]
65 pub fn from_memory(bytes: Arc<Vec<u8>>, font_index: u32) -> Handle {
66 Handle::Memory { bytes, font_index }
67 }
68
69 /// A convenience method to load this handle with the default loader, producing a Font.
70 #[inline]
71 pub fn load(&self) -> Result<Font, FontLoadingError> {
72 Font::from_handle(self)
73 }
74}
75