owned_ttf_parser/
owned.rs

1use crate::preparse::{FaceSubtables, PreParsedSubtables};
2#[cfg(not(feature = "std"))]
3use alloc::{boxed::Box, vec::Vec};
4use core::{fmt, marker::PhantomPinned, pin::Pin, slice};
5
6/// An owned version of font [`Face`](struct.Face.html).
7pub struct OwnedFace(Pin<Box<SelfRefVecFace>>);
8
9impl OwnedFace {
10    /// Creates an `OwnedFace` from owned data.
11    ///
12    /// You can set index for font collections. For simple ttf fonts set index to 0.
13    ///
14    /// # Example
15    /// ```
16    /// # use owned_ttf_parser::OwnedFace;
17    /// # let owned_font_data = include_bytes!("../fonts/font.ttf").to_vec();
18    /// let owned_face = OwnedFace::from_vec(owned_font_data, 0).unwrap();
19    /// ```
20    // Note: not `try_from_vec` to better mimic `ttf_parser::Face::from_data`.
21    pub fn from_vec(data: Vec<u8>, index: u32) -> Result<Self, ttf_parser::FaceParsingError> {
22        let inner = SelfRefVecFace::try_from_vec(data, index)?;
23        Ok(Self(inner))
24    }
25
26    pub(crate) fn pre_parse_subtables(self) -> PreParsedSubtables<'static, Self> {
27        // build subtables referencing fake static data
28        let subtables = FaceSubtables::from(match self.0.face.as_ref() {
29            Some(f) => f,
30            None => unsafe { core::hint::unreachable_unchecked() },
31        });
32
33        // bundle everything together so self-reference lifetimes hold
34        PreParsedSubtables {
35            face: self,
36            subtables,
37        }
38    }
39
40    /// Extracts a slice containing the data passed into [`OwnedFace::from_vec`].
41    ///
42    /// # Example
43    /// ```
44    /// # use owned_ttf_parser::OwnedFace;
45    /// # let owned_font_data = include_bytes!("../fonts/font.ttf").to_vec();
46    /// let data_clone = owned_font_data.clone();
47    /// let owned_face = OwnedFace::from_vec(owned_font_data, 0).unwrap();
48    /// assert_eq!(owned_face.as_slice(), data_clone);
49    /// ```
50    pub fn as_slice(&self) -> &[u8] {
51        &self.0.data
52    }
53
54    /// Unwraps the data passed into [`OwnedFace::from_vec`].
55    ///
56    /// # Example
57    /// ```
58    /// # use owned_ttf_parser::OwnedFace;
59    /// # let owned_font_data = include_bytes!("../fonts/font.ttf").to_vec();
60    /// let data_clone = owned_font_data.clone();
61    /// let owned_face = OwnedFace::from_vec(owned_font_data, 0).unwrap();
62    /// assert_eq!(owned_face.into_vec(), data_clone);
63    /// ```
64    pub fn into_vec(self) -> Vec<u8> {
65        // safe as the `Face` is dropped.
66        unsafe { Pin::into_inner_unchecked(self.0).data }
67    }
68}
69
70impl fmt::Debug for OwnedFace {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        write!(f, "OwnedFace()")
73    }
74}
75
76impl crate::convert::AsFaceRef for OwnedFace {
77    #[inline]
78    fn as_face_ref(&self) -> &ttf_parser::Face<'_> {
79        self.0.inner_ref()
80    }
81}
82
83impl crate::convert::AsFaceRef for &OwnedFace {
84    #[inline]
85    fn as_face_ref(&self) -> &ttf_parser::Face<'_> {
86        self.0.inner_ref()
87    }
88}
89
90impl crate::convert::FaceMut for OwnedFace {
91    fn set_variation(&mut self, axis: ttf_parser::Tag, value: f32) -> Option<()> {
92        unsafe {
93            let mut_ref = Pin::as_mut(&mut self.0);
94            let mut_inner = mut_ref.get_unchecked_mut();
95            match mut_inner.face.as_mut() {
96                Some(face) => face.set_variation(axis, value),
97                None => None,
98            }
99        }
100    }
101}
102impl crate::convert::FaceMut for &mut OwnedFace {
103    #[inline]
104    fn set_variation(&mut self, axis: ttf_parser::Tag, value: f32) -> Option<()> {
105        (*self).set_variation(axis, value)
106    }
107}
108
109// Face data in a `Vec` with a self-referencing `Face`.
110struct SelfRefVecFace {
111    data: Vec<u8>,
112    face: Option<ttf_parser::Face<'static>>,
113    _pin: PhantomPinned,
114}
115
116impl SelfRefVecFace {
117    /// Creates an underlying face object from owned data.
118    fn try_from_vec(
119        data: Vec<u8>,
120        index: u32,
121    ) -> Result<Pin<Box<Self>>, ttf_parser::FaceParsingError> {
122        let face = Self {
123            data,
124            face: None,
125            _pin: PhantomPinned,
126        };
127        let mut b = Box::pin(face);
128        unsafe {
129            // 'static lifetime is a lie, this data is owned, it has pseudo-self lifetime.
130            let slice: &'static [u8] = slice::from_raw_parts(b.data.as_ptr(), b.data.len());
131            let mut_ref: Pin<&mut Self> = Pin::as_mut(&mut b);
132            let mut_inner = mut_ref.get_unchecked_mut();
133            mut_inner.face = Some(ttf_parser::Face::from_slice(slice, index)?);
134        }
135        Ok(b)
136    }
137
138    // Must not leak the fake 'static lifetime that we lied about earlier to the
139    // compiler. Since the lifetime 'a will not outlive our owned data it's
140    // safe to provide Face<'a>
141    #[inline]
142    #[allow(clippy::needless_lifetimes)] // explicit is nice as it's important 'static isn't leaked
143    fn inner_ref<'a>(self: &'a Pin<Box<Self>>) -> &'a ttf_parser::Face<'a> {
144        match self.face.as_ref() {
145            Some(f) => f,
146            None => unsafe { core::hint::unreachable_unchecked() },
147        }
148    }
149}