ttf_parser/
writer.rs
1#![allow(missing_docs)]
4#![allow(dead_code)]
5
6use std::vec::Vec;
7
8#[allow(missing_debug_implementations)]
9#[derive(Clone, Copy)]
10pub enum TtfType {
11 Raw(&'static [u8]),
12 TrueTypeMagic,
13 OpenTypeMagic,
14 FontCollectionMagic,
15 Int8(i8),
16 UInt8(u8),
17 Int16(i16),
18 UInt16(u16),
19 Int32(i32),
20 UInt32(u32),
21 CFFInt(i32),
22}
23
24pub fn convert(values: &[TtfType]) -> Vec<u8> {
25 let mut data = Vec::with_capacity(256);
26 for v in values {
27 convert_type(*v, &mut data);
28 }
29
30 data
31}
32
33pub fn convert_type(value: TtfType, data: &mut Vec<u8>) {
34 match value {
35 TtfType::Raw(bytes) => {
36 data.extend_from_slice(bytes);
37 }
38 TtfType::TrueTypeMagic => {
39 data.extend_from_slice(&[0x00, 0x01, 0x00, 0x00]);
40 }
41 TtfType::OpenTypeMagic => {
42 data.extend_from_slice(&[0x4F, 0x54, 0x54, 0x4F]);
43 }
44 TtfType::FontCollectionMagic => {
45 data.extend_from_slice(&[0x74, 0x74, 0x63, 0x66]);
46 }
47 TtfType::Int8(n) => {
48 data.extend_from_slice(&i8::to_be_bytes(n));
49 }
50 TtfType::UInt8(n) => {
51 data.extend_from_slice(&u8::to_be_bytes(n));
52 }
53 TtfType::Int16(n) => {
54 data.extend_from_slice(&i16::to_be_bytes(n));
55 }
56 TtfType::UInt16(n) => {
57 data.extend_from_slice(&u16::to_be_bytes(n));
58 }
59 TtfType::Int32(n) => {
60 data.extend_from_slice(&i32::to_be_bytes(n));
61 }
62 TtfType::UInt32(n) => {
63 data.extend_from_slice(&u32::to_be_bytes(n));
64 }
65 TtfType::CFFInt(n) => {
66 match n {
67 -107..=107 => {
68 data.push((n as i16 + 139) as u8);
69 }
70 108..=1131 => {
71 let n = n - 108;
72 data.push(((n >> 8) + 247) as u8);
73 data.push((n & 0xFF) as u8);
74 }
75 -1131..=-108 => {
76 let n = -n - 108;
77 data.push(((n >> 8) + 251) as u8);
78 data.push((n & 0xFF) as u8);
79 }
80 -32768..=32767 => {
81 data.push(28);
82 data.extend_from_slice(&i16::to_be_bytes(n as i16));
83 }
84 _ => {
85 data.push(29);
86 data.extend_from_slice(&i32::to_be_bytes(n));
87 }
88 }
89 }
90 }
91}
92
93#[derive(Debug)]
94pub struct Writer {
95 pub data: Vec<u8>,
96}
97
98impl Writer {
99 pub fn new() -> Self {
100 Writer { data: Vec::with_capacity(256) }
101 }
102
103 pub fn offset(&self) -> usize {
104 self.data.len()
105 }
106
107 pub fn write(&mut self, value: TtfType) {
108 convert_type(value, &mut self.data);
109 }
110}