owned_ttf_parser/
owned.rs1use crate::preparse::{FaceSubtables, PreParsedSubtables};
2#[cfg(not(feature = "std"))]
3use alloc::{boxed::Box, vec::Vec};
4use core::{fmt, marker::PhantomPinned, pin::Pin, slice};
5
6pub struct OwnedFace(Pin<Box<SelfRefVecFace>>);
8
9impl OwnedFace {
10 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 let subtables = FaceSubtables::from(match self.0.face.as_ref() {
29 Some(f) => f,
30 None => unsafe { core::hint::unreachable_unchecked() },
31 });
32
33 PreParsedSubtables {
35 face: self,
36 subtables,
37 }
38 }
39
40 pub fn as_slice(&self) -> &[u8] {
51 &self.0.data
52 }
53
54 pub fn into_vec(self) -> Vec<u8> {
65 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
109struct SelfRefVecFace {
111 data: Vec<u8>,
112 face: Option<ttf_parser::Face<'static>>,
113 _pin: PhantomPinned,
114}
115
116impl SelfRefVecFace {
117 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 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 #[inline]
142 #[allow(clippy::needless_lifetimes)] 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}