1use core::convert::{TryFrom, TryInto};
7use core::ops::Range;
8
9pub trait FromData: Sized {
13 const SIZE: usize;
17
18 fn parse(data: &[u8]) -> Option<Self>;
20}
21
22pub trait FromSlice<'a>: Sized {
26 fn parse(data: &'a [u8]) -> Option<Self>;
28}
29
30impl FromData for () {
31 const SIZE: usize = 0;
32
33 #[inline]
34 fn parse(_: &[u8]) -> Option<Self> {
35 Some(())
36 }
37}
38
39impl FromData for u8 {
40 const SIZE: usize = 1;
41
42 #[inline]
43 fn parse(data: &[u8]) -> Option<Self> {
44 data.get(0).copied()
45 }
46}
47
48impl FromData for i8 {
49 const SIZE: usize = 1;
50
51 #[inline]
52 fn parse(data: &[u8]) -> Option<Self> {
53 data.get(0).copied().map(|n| n as i8)
54 }
55}
56
57impl FromData for u16 {
58 const SIZE: usize = 2;
59
60 #[inline]
61 fn parse(data: &[u8]) -> Option<Self> {
62 data.try_into().ok().map(u16::from_be_bytes)
63 }
64}
65
66impl FromData for i16 {
67 const SIZE: usize = 2;
68
69 #[inline]
70 fn parse(data: &[u8]) -> Option<Self> {
71 data.try_into().ok().map(i16::from_be_bytes)
72 }
73}
74
75impl FromData for u32 {
76 const SIZE: usize = 4;
77
78 #[inline]
79 fn parse(data: &[u8]) -> Option<Self> {
80 data.try_into().ok().map(u32::from_be_bytes)
81 }
82}
83
84impl FromData for i32 {
85 const SIZE: usize = 4;
86
87 #[inline]
88 fn parse(data: &[u8]) -> Option<Self> {
89 data.try_into().ok().map(i32::from_be_bytes)
90 }
91}
92
93impl FromData for u64 {
94 const SIZE: usize = 8;
95
96 #[inline]
97 fn parse(data: &[u8]) -> Option<Self> {
98 data.try_into().ok().map(u64::from_be_bytes)
99 }
100}
101
102#[derive(Clone, Copy, Debug)]
108pub struct U24(pub u32);
109
110impl FromData for U24 {
111 const SIZE: usize = 3;
112
113 #[inline]
114 fn parse(data: &[u8]) -> Option<Self> {
115 let data: [u8; 3] = data.try_into().ok()?;
116 Some(U24(u32::from_be_bytes([0, data[0], data[1], data[2]])))
117 }
118}
119
120#[derive(Clone, Copy, Debug)]
122pub struct F2DOT14(pub i16);
123
124impl F2DOT14 {
125 #[inline]
127 pub fn to_f32(self) -> f32 {
128 f32::from(self.0) / 16384.0
129 }
130
131 #[cfg(feature = "variable-fonts")]
132 #[inline]
133 pub fn apply_float_delta(&self, delta: f32) -> f32 {
134 self.to_f32() + (delta as f64 * (1.0 / 16384.0)) as f32
135 }
136}
137
138impl FromData for F2DOT14 {
139 const SIZE: usize = 2;
140
141 #[inline]
142 fn parse(data: &[u8]) -> Option<Self> {
143 i16::parse(data).map(F2DOT14)
144 }
145}
146
147#[derive(Clone, Copy, Debug)]
149pub struct Fixed(pub f32);
150
151impl FromData for Fixed {
152 const SIZE: usize = 4;
153
154 #[inline]
155 fn parse(data: &[u8]) -> Option<Self> {
156 i32::parse(data).map(|n| Fixed(n as f32 / 65536.0))
158 }
159}
160
161impl Fixed {
162 #[cfg(feature = "variable-fonts")]
163 #[inline]
164 pub(crate) fn apply_float_delta(&self, delta: f32) -> f32 {
165 self.0 + (delta as f64 * (1.0 / 65536.0)) as f32
166 }
167}
168
169pub trait NumFrom<T>: Sized {
175 fn num_from(_: T) -> Self;
177}
178
179impl NumFrom<u32> for usize {
180 #[inline]
181 fn num_from(v: u32) -> Self {
182 #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
183 {
184 v as usize
185 }
186
187 }
189}
190
191impl NumFrom<char> for usize {
192 #[inline]
193 fn num_from(v: char) -> Self {
194 #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
195 {
196 v as usize
197 }
198
199 }
201}
202
203pub trait TryNumFrom<T>: Sized {
205 fn try_num_from(_: T) -> Option<Self>;
207}
208
209impl TryNumFrom<f32> for u8 {
210 #[inline]
211 fn try_num_from(v: f32) -> Option<Self> {
212 i32::try_num_from(v).and_then(|v| u8::try_from(v).ok())
213 }
214}
215
216impl TryNumFrom<f32> for i16 {
217 #[inline]
218 fn try_num_from(v: f32) -> Option<Self> {
219 i32::try_num_from(v).and_then(|v| i16::try_from(v).ok())
220 }
221}
222
223impl TryNumFrom<f32> for u16 {
224 #[inline]
225 fn try_num_from(v: f32) -> Option<Self> {
226 i32::try_num_from(v).and_then(|v| u16::try_from(v).ok())
227 }
228}
229
230#[allow(clippy::manual_range_contains)]
231impl TryNumFrom<f32> for i32 {
232 #[inline]
233 fn try_num_from(v: f32) -> Option<Self> {
234 const MIN: f32 = i32::MIN as f32;
242 const MAX_P1: f32 = i32::MAX as f32;
245 if v >= MIN && v < MAX_P1 { Some(v as i32) } else { None }
246 }
247}
248
249#[derive(Clone, Copy)]
253pub struct LazyArray16<'a, T> {
254 data: &'a [u8],
255 data_type: core::marker::PhantomData<T>,
256}
257
258impl<T> Default for LazyArray16<'_, T> {
259 #[inline]
260 fn default() -> Self {
261 LazyArray16 {
262 data: &[],
263 data_type: core::marker::PhantomData,
264 }
265 }
266}
267
268impl<'a, T: FromData> LazyArray16<'a, T> {
269 #[inline]
271 pub fn new(data: &'a [u8]) -> Self {
272 LazyArray16 {
273 data,
274 data_type: core::marker::PhantomData,
275 }
276 }
277
278 #[inline]
280 pub fn get(&self, index: u16) -> Option<T> {
281 if index < self.len() {
282 let start = usize::from(index) * T::SIZE;
283 let end = start + T::SIZE;
284 self.data.get(start..end).and_then(T::parse)
285 } else {
286 None
287 }
288 }
289
290 #[inline]
292 pub fn last(&self) -> Option<T> {
293 if !self.is_empty() {
294 self.get(self.len() - 1)
295 } else {
296 None
297 }
298 }
299
300 #[inline]
302 pub fn slice(&self, range: Range<u16>) -> Option<Self> {
303 let start = usize::from(range.start) * T::SIZE;
304 let end = usize::from(range.end) * T::SIZE;
305 Some(LazyArray16 {
306 data: self.data.get(start..end)?,
307 ..LazyArray16::default()
308 })
309 }
310
311 #[inline]
313 pub fn len(&self) -> u16 {
314 (self.data.len() / T::SIZE) as u16
315 }
316
317 #[inline]
319 pub fn is_empty(&self) -> bool {
320 self.len() == 0
321 }
322
323 #[inline]
325 pub fn binary_search(&self, key: &T) -> Option<(u16, T)>
326 where
327 T: Ord,
328 {
329 self.binary_search_by(|p| p.cmp(key))
330 }
331
332 #[inline]
334 pub fn binary_search_by<F>(&self, mut f: F) -> Option<(u16, T)>
335 where
336 F: FnMut(&T) -> core::cmp::Ordering,
337 {
338 use core::cmp::Ordering;
341
342 let mut size = self.len();
343 if size == 0 {
344 return None;
345 }
346
347 let mut base = 0;
348 while size > 1 {
349 let half = size / 2;
350 let mid = base + half;
351 let cmp = f(&self.get(mid)?);
355 base = if cmp == Ordering::Greater { base } else { mid };
356 size -= half;
357 }
358
359 let value = self.get(base)?;
361 if f(&value) == Ordering::Equal {
362 Some((base, value))
363 } else {
364 None
365 }
366 }
367}
368
369impl<'a, T: FromData + core::fmt::Debug + Copy> core::fmt::Debug for LazyArray16<'a, T> {
370 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
371 f.debug_list().entries(*self).finish()
372 }
373}
374
375impl<'a, T: FromData> IntoIterator for LazyArray16<'a, T> {
376 type Item = T;
377 type IntoIter = LazyArrayIter16<'a, T>;
378
379 #[inline]
380 fn into_iter(self) -> Self::IntoIter {
381 LazyArrayIter16 { data: self, index: 0 }
382 }
383}
384
385#[derive(Clone, Copy)]
387#[allow(missing_debug_implementations)]
388pub struct LazyArrayIter16<'a, T> {
389 data: LazyArray16<'a, T>,
390 index: u16,
391}
392
393impl<T: FromData> Default for LazyArrayIter16<'_, T> {
394 #[inline]
395 fn default() -> Self {
396 LazyArrayIter16 {
397 data: LazyArray16::new(&[]),
398 index: 0,
399 }
400 }
401}
402
403impl<'a, T: FromData> Iterator for LazyArrayIter16<'a, T> {
404 type Item = T;
405
406 #[inline]
407 fn next(&mut self) -> Option<Self::Item> {
408 self.index += 1; self.data.get(self.index - 1)
410 }
411
412 #[inline]
413 fn count(self) -> usize {
414 usize::from(self.data.len().saturating_sub(self.index))
415 }
416}
417
418#[derive(Clone, Copy)]
422pub struct LazyArray32<'a, T> {
423 data: &'a [u8],
424 data_type: core::marker::PhantomData<T>,
425}
426
427impl<T> Default for LazyArray32<'_, T> {
428 #[inline]
429 fn default() -> Self {
430 LazyArray32 {
431 data: &[],
432 data_type: core::marker::PhantomData,
433 }
434 }
435}
436
437impl<'a, T: FromData> LazyArray32<'a, T> {
438 #[inline]
440 pub fn new(data: &'a [u8]) -> Self {
441 LazyArray32 {
442 data,
443 data_type: core::marker::PhantomData,
444 }
445 }
446
447 #[inline]
449 pub fn get(&self, index: u32) -> Option<T> {
450 if index < self.len() {
451 let start = usize::num_from(index) * T::SIZE;
452 let end = start + T::SIZE;
453 self.data.get(start..end).and_then(T::parse)
454 } else {
455 None
456 }
457 }
458
459 #[inline]
461 pub fn len(&self) -> u32 {
462 (self.data.len() / T::SIZE) as u32
463 }
464
465 pub fn is_empty(&self) -> bool {
467 self.len() == 0
468 }
469
470 #[inline]
472 pub fn binary_search(&self, key: &T) -> Option<(u32, T)>
473 where
474 T: Ord,
475 {
476 self.binary_search_by(|p| p.cmp(key))
477 }
478
479 #[inline]
481 pub fn binary_search_by<F>(&self, mut f: F) -> Option<(u32, T)>
482 where
483 F: FnMut(&T) -> core::cmp::Ordering,
484 {
485 use core::cmp::Ordering;
488
489 let mut size = self.len();
490 if size == 0 {
491 return None;
492 }
493
494 let mut base = 0;
495 while size > 1 {
496 let half = size / 2;
497 let mid = base + half;
498 let cmp = f(&self.get(mid)?);
502 base = if cmp == Ordering::Greater { base } else { mid };
503 size -= half;
504 }
505
506 let value = self.get(base)?;
508 if f(&value) == Ordering::Equal {
509 Some((base, value))
510 } else {
511 None
512 }
513 }
514}
515
516impl<'a, T: FromData + core::fmt::Debug + Copy> core::fmt::Debug for LazyArray32<'a, T> {
517 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
518 f.debug_list().entries(*self).finish()
519 }
520}
521
522impl<'a, T: FromData> IntoIterator for LazyArray32<'a, T> {
523 type Item = T;
524 type IntoIter = LazyArrayIter32<'a, T>;
525
526 #[inline]
527 fn into_iter(self) -> Self::IntoIter {
528 LazyArrayIter32 { data: self, index: 0 }
529 }
530}
531
532#[derive(Clone, Copy)]
534#[allow(missing_debug_implementations)]
535pub struct LazyArrayIter32<'a, T> {
536 data: LazyArray32<'a, T>,
537 index: u32,
538}
539
540impl<'a, T: FromData> Iterator for LazyArrayIter32<'a, T> {
541 type Item = T;
542
543 #[inline]
544 fn next(&mut self) -> Option<Self::Item> {
545 self.index += 1; self.data.get(self.index - 1)
547 }
548
549 #[inline]
550 fn count(self) -> usize {
551 usize::num_from(self.data.len().saturating_sub(self.index))
552 }
553}
554
555#[derive(Clone, Copy)]
561pub struct LazyOffsetArray16<'a, T: FromSlice<'a>> {
562 data: &'a [u8],
563 offsets: LazyArray16<'a, Option<Offset16>>,
565 data_type: core::marker::PhantomData<T>,
566}
567
568impl<'a, T: FromSlice<'a>> LazyOffsetArray16<'a, T> {
569 #[allow(dead_code)]
571 pub fn new(data: &'a [u8], offsets: LazyArray16<'a, Option<Offset16>>) -> Self {
572 Self {
573 data,
574 offsets,
575 data_type: core::marker::PhantomData,
576 }
577 }
578
579 #[allow(dead_code)]
581 pub fn parse(data: &'a [u8]) -> Option<Self> {
582 let mut s = Stream::new(data);
583 let count = s.read::<u16>()?;
584 let offsets = s.read_array16(count)?;
585 Some(Self {
586 data,
587 offsets,
588 data_type: core::marker::PhantomData,
589 })
590 }
591
592 #[inline]
594 pub fn get(&self, index: u16) -> Option<T> {
595 let offset = self.offsets.get(index)??.to_usize();
596 self.data.get(offset..).and_then(T::parse)
597 }
598
599 #[inline]
601 pub fn len(&self) -> u16 {
602 self.offsets.len()
603 }
604
605 #[inline]
607 #[allow(dead_code)]
608 pub fn is_empty(&self) -> bool {
609 self.len() == 0
610 }
611}
612
613impl<'a, T: FromSlice<'a> + core::fmt::Debug + Copy> core::fmt::Debug for LazyOffsetArray16<'a, T> {
614 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
615 f.debug_list().entries(*self).finish()
616 }
617}
618
619#[derive(Clone, Copy)]
621#[allow(missing_debug_implementations)]
622pub struct LazyOffsetArrayIter16<'a, T: FromSlice<'a>> {
623 array: LazyOffsetArray16<'a, T>,
624 index: u16,
625}
626
627impl<'a, T: FromSlice<'a>> IntoIterator for LazyOffsetArray16<'a, T> {
628 type Item = T;
629 type IntoIter = LazyOffsetArrayIter16<'a, T>;
630
631 #[inline]
632 fn into_iter(self) -> Self::IntoIter {
633 LazyOffsetArrayIter16 { array: self, index: 0 }
634 }
635}
636
637impl<'a, T: FromSlice<'a>> Iterator for LazyOffsetArrayIter16<'a, T> {
638 type Item = T;
639
640 fn next(&mut self) -> Option<Self::Item> {
641 if self.index < self.array.len() {
642 self.index += 1;
643 self.array.get(self.index - 1)
644 } else {
645 None
646 }
647 }
648
649 #[inline]
650 fn count(self) -> usize {
651 usize::from(self.array.len().saturating_sub(self.index))
652 }
653}
654
655#[derive(Clone, Default, Debug)]
657pub struct Stream<'a> {
658 data: &'a [u8],
659 offset: usize,
660}
661
662impl<'a> Stream<'a> {
663 #[inline]
665 pub fn new(data: &'a [u8]) -> Self {
666 Stream { data, offset: 0 }
667 }
668
669 #[inline]
673 pub fn new_at(data: &'a [u8], offset: usize) -> Option<Self> {
674 if offset <= data.len() {
675 Some(Stream { data, offset })
676 } else {
677 None
678 }
679 }
680
681 #[inline]
683 pub fn at_end(&self) -> bool {
684 self.offset >= self.data.len()
685 }
686
687 #[inline]
691 pub fn jump_to_end(&mut self) {
692 self.offset = self.data.len();
693 }
694
695 #[inline]
697 pub fn offset(&self) -> usize {
698 self.offset
699 }
700
701 #[inline]
705 pub fn tail(&self) -> Option<&'a [u8]> {
706 self.data.get(self.offset..)
707 }
708
709 #[inline]
713 pub fn skip<T: FromData>(&mut self) {
714 self.advance(T::SIZE);
715 }
716
717 #[inline]
721 pub fn advance(&mut self, len: usize) {
722 self.offset += len;
723 }
724
725 #[inline]
727 pub fn advance_checked(&mut self, len: usize) -> Option<()> {
728 if self.offset + len <= self.data.len() {
729 self.advance(len);
730 Some(())
731 } else {
732 None
733 }
734 }
735
736 #[inline]
741 pub fn read<T: FromData>(&mut self) -> Option<T> {
742 self.read_bytes(T::SIZE).and_then(T::parse)
743 }
744
745 #[inline]
747 pub fn read_at<T: FromData>(data: &[u8], offset: usize) -> Option<T> {
748 data.get(offset..offset + T::SIZE).and_then(T::parse)
749 }
750
751 #[inline]
753 pub fn read_bytes(&mut self, len: usize) -> Option<&'a [u8]> {
754 debug_assert!(self.offset as u64 + len as u64 <= u32::MAX as u64);
758
759 let v = self.data.get(self.offset..self.offset + len)?;
760 self.advance(len);
761 Some(v)
762 }
763
764 #[inline]
766 pub fn read_array16<T: FromData>(&mut self, count: u16) -> Option<LazyArray16<'a, T>> {
767 let len = usize::from(count) * T::SIZE;
768 self.read_bytes(len).map(LazyArray16::new)
769 }
770
771 #[inline]
773 pub fn read_array32<T: FromData>(&mut self, count: u32) -> Option<LazyArray32<'a, T>> {
774 let len = usize::num_from(count) * T::SIZE;
775 self.read_bytes(len).map(LazyArray32::new)
776 }
777
778 #[allow(dead_code)]
779 #[inline]
780 pub fn read_at_offset16(&mut self, data: &'a [u8]) -> Option<&'a [u8]> {
781 let offset = self.read::<Offset16>()?.to_usize();
782 data.get(offset..)
783 }
784}
785
786pub trait Offset {
788 fn to_usize(&self) -> usize;
790}
791
792#[derive(Clone, Copy, Debug)]
794pub struct Offset16(pub u16);
795
796impl Offset for Offset16 {
797 #[inline]
798 fn to_usize(&self) -> usize {
799 usize::from(self.0)
800 }
801}
802
803impl FromData for Offset16 {
804 const SIZE: usize = 2;
805
806 #[inline]
807 fn parse(data: &[u8]) -> Option<Self> {
808 u16::parse(data).map(Offset16)
809 }
810}
811
812impl FromData for Option<Offset16> {
813 const SIZE: usize = Offset16::SIZE;
814
815 #[inline]
816 fn parse(data: &[u8]) -> Option<Self> {
817 let offset = Offset16::parse(data)?;
818 if offset.0 != 0 { Some(Some(offset)) } else { Some(None) }
819 }
820}
821
822#[derive(Clone, Copy, Debug)]
824pub struct Offset24(pub u32);
825
826impl Offset for Offset24 {
827 #[inline]
828 fn to_usize(&self) -> usize {
829 usize::num_from(self.0)
830 }
831}
832
833impl FromData for Offset24 {
834 const SIZE: usize = 3;
835
836 #[inline]
837 fn parse(data: &[u8]) -> Option<Self> {
838 U24::parse(data).map(|n| Offset24(n.0))
839 }
840}
841
842impl FromData for Option<Offset24> {
843 const SIZE: usize = Offset24::SIZE;
844
845 #[inline]
846 fn parse(data: &[u8]) -> Option<Self> {
847 let offset = Offset24::parse(data)?;
848 if offset.0 != 0 { Some(Some(offset)) } else { Some(None) }
849 }
850}
851
852#[derive(Clone, Copy, Debug)]
854pub struct Offset32(pub u32);
855
856impl Offset for Offset32 {
857 #[inline]
858 fn to_usize(&self) -> usize {
859 usize::num_from(self.0)
860 }
861}
862
863impl FromData for Offset32 {
864 const SIZE: usize = 4;
865
866 #[inline]
867 fn parse(data: &[u8]) -> Option<Self> {
868 u32::parse(data).map(Offset32)
869 }
870}
871
872impl FromData for Option<Offset32> {
873 const SIZE: usize = Offset32::SIZE;
874
875 #[inline]
876 fn parse(data: &[u8]) -> Option<Self> {
877 let offset = Offset32::parse(data)?;
878 if offset.0 != 0 { Some(Some(offset)) } else { Some(None) }
879 }
880}
881
882#[inline]
883pub fn i16_bound(min: i16, val: i16, max: i16) -> i16 {
884 use core::cmp;
885 cmp::max(min, cmp::min(max, val))
886}
887
888#[inline]
889pub fn f32_bound(min: f32, val: f32, max: f32) -> f32 {
890 debug_assert!(min.is_finite());
891 debug_assert!(val.is_finite());
892 debug_assert!(max.is_finite());
893
894 if val > max {
895 return max;
896 } else if val < min {
897 return min;
898 }
899
900 val
901}