1use crate::{array, offset::CheckedOffset};
4
5include!("../../generated/generated_bitmap.rs");
6
7impl BitmapSize {
8 pub fn location(
16 &self,
17 offset_data: FontData,
18 glyph_id: GlyphId,
19 ) -> Result<BitmapLocation, ReadError> {
20 if !(self.start_glyph_index()..=self.end_glyph_index()).contains(&glyph_id) {
21 return Err(ReadError::OutOfBounds);
22 }
23 let subtable_list = self.index_subtable_list(offset_data)?;
24 let mut location = BitmapLocation {
25 bit_depth: self.bit_depth,
26 ..BitmapLocation::default()
27 };
28 for record in subtable_list.index_subtable_records() {
29 let subtable = record.index_subtable(subtable_list.offset_data())?;
30 if !(record.first_glyph_index()..=record.last_glyph_index()).contains(&glyph_id) {
31 continue;
32 }
33 let glyph_ix =
35 glyph_id.to_u32() as usize - record.first_glyph_index().to_u32() as usize;
36 match &subtable {
37 IndexSubtable::Format1(st) => {
38 location.format = st.image_format();
39 let [first_offset, second_offset] =
40 array::get_pair(st.sbit_offsets(), glyph_ix)?.map(|o| o.get() as usize);
41 let base = CheckedOffset::new(st.image_data_offset() as usize);
42 let start = base.add(first_offset).ok_or_oob()?;
43 let end = base.add(second_offset).ok_or_oob()?;
44 location.data_offset = start;
45 if end < start {
46 return Err(ReadError::OutOfBounds);
47 }
48 location.data_size = end - start;
49 }
50 IndexSubtable::Format2(st) => {
51 location.format = st.image_format();
52 let data_size = st.image_size() as usize;
53 location.data_size = data_size;
54 location.data_offset = CheckedOffset::new(glyph_ix)
55 .mul(data_size)
56 .add(st.image_data_offset() as usize)
57 .ok_or_oob()?;
58 location.metrics = Some(*st.big_metrics());
59 }
60 IndexSubtable::Format3(st) => {
61 location.format = st.image_format();
62 let [first_offset, second_offset] =
63 array::get_pair(st.sbit_offsets(), glyph_ix)?.map(|o| o.get() as usize);
64 let base = CheckedOffset::new(st.image_data_offset() as usize);
65 let start = base.add(first_offset).ok_or_oob()?;
66 let end = base.add(second_offset).ok_or_oob()?;
67 location.data_offset = start;
68 if end < start {
69 return Err(ReadError::OutOfBounds);
70 }
71 location.data_size = end - start;
72 }
73 IndexSubtable::Format4(st) => {
74 location.format = st.image_format();
75 let array = st.glyph_array();
76 let array_ix = match array
77 .binary_search_by(|x| x.glyph_id().to_u32().cmp(&glyph_id.to_u32()))
78 {
79 Ok(ix) => ix,
80 _ => return Err(ReadError::InvalidCollectionIndex(glyph_id.to_u32())),
81 };
82 let [first_offset, second_offset] =
83 array::get_pair(array, array_ix)?.map(|p| p.sbit_offset() as usize);
84 let base = CheckedOffset::new(st.image_data_offset() as usize);
85 let start = base.add(first_offset).ok_or_oob()?;
86 let end = base.add(second_offset).ok_or_oob()?;
87 location.data_offset = start;
88 if end < start {
89 return Err(ReadError::OutOfBounds);
90 }
91 location.data_size = end - start;
92 }
93 IndexSubtable::Format5(st) => {
94 location.format = st.image_format();
95 let array = st.glyph_array();
96 let array_ix = match array
97 .binary_search_by(|gid| gid.get().to_u32().cmp(&glyph_id.to_u32()))
98 {
99 Ok(ix) => ix,
100 _ => return Err(ReadError::InvalidCollectionIndex(glyph_id.to_u32())),
101 };
102 let data_size = st.image_size() as usize;
103 location.data_size = data_size;
104 location.data_offset = CheckedOffset::new(array_ix)
105 .mul(data_size)
106 .add(st.image_data_offset() as usize)
107 .ok_or_oob()?;
108 location.metrics = Some(*st.big_metrics());
109 }
110 }
111 return Ok(location);
112 }
113 Err(ReadError::OutOfBounds)
114 }
115
116 pub fn index_subtable_list<'a>(
121 &self,
122 offset_data: FontData<'a>,
123 ) -> Result<IndexSubtableList<'a>, ReadError> {
124 let start = self.index_subtable_list_offset() as usize;
125 let data = offset_data.split_off(start).ok_or(ReadError::OutOfBounds)?;
133 IndexSubtableList::read(data, self.number_of_index_subtables())
134 }
135}
136
137#[derive(Clone, Default)]
138pub struct BitmapLocation {
139 pub format: u16,
141 pub data_offset: usize,
143 pub data_size: usize,
145 pub bit_depth: u8,
148 pub metrics: Option<BigGlyphMetrics>,
150}
151
152impl BitmapLocation {
153 pub fn is_empty(&self) -> bool {
156 self.data_size == 0
157 }
158}
159
160#[derive(Copy, Clone, PartialEq, Eq, Debug)]
161pub enum BitmapDataFormat {
162 BitAligned,
164 ByteAligned,
166 Png,
167}
168
169#[derive(Clone)]
170pub enum BitmapMetrics {
171 Small(SmallGlyphMetrics),
172 Big(BigGlyphMetrics),
173}
174
175#[derive(Clone)]
176pub struct BitmapData<'a> {
177 pub metrics: BitmapMetrics,
178 pub content: BitmapContent<'a>,
179}
180
181#[derive(Clone)]
182pub enum BitmapContent<'a> {
183 Data(BitmapDataFormat, &'a [u8]),
184 Composite(&'a [BdtComponent]),
185}
186
187pub(crate) fn bitmap_data<'a>(
188 offset_data: FontData<'a>,
189 location: &BitmapLocation,
190 is_color: bool,
191) -> Result<BitmapData<'a>, ReadError> {
192 let start = location.data_offset;
193 let end = CheckedOffset::new(start)
194 .add(location.data_size)
195 .ok_or_oob()?;
196 let mut image_data = offset_data
197 .slice(start..end)
198 .ok_or(ReadError::OutOfBounds)?
199 .cursor();
200 match location.format {
201 1 => {
204 let metrics = read_small_metrics(&mut image_data)?;
205 let pitch = (metrics.width as usize * location.bit_depth as usize).div_ceil(8);
207 let height = metrics.height as usize;
208 let data = image_data.read_array::<u8>(pitch * height)?;
209 Ok(BitmapData {
210 metrics: BitmapMetrics::Small(metrics),
211 content: BitmapContent::Data(BitmapDataFormat::ByteAligned, data),
212 })
213 }
214 2 => {
217 let metrics = read_small_metrics(&mut image_data)?;
218 let width = metrics.width as usize * location.bit_depth as usize;
219 let height = metrics.height as usize;
220 let data = image_data.read_array::<u8>((width * height).div_ceil(8))?;
222 Ok(BitmapData {
223 metrics: BitmapMetrics::Small(metrics),
224 content: BitmapContent::Data(BitmapDataFormat::BitAligned, data),
225 })
226 }
227 5 => {
235 let metrics = location.metrics.ok_or(ReadError::MalformedData(
236 "expected metrics from location table",
237 ))?;
238 let width = metrics.width as usize * location.bit_depth as usize;
239 let height = metrics.height as usize;
240 let data = image_data.read_array::<u8>((width * height).div_ceil(8))?;
242 Ok(BitmapData {
243 metrics: BitmapMetrics::Big(metrics),
244 content: BitmapContent::Data(BitmapDataFormat::BitAligned, data),
245 })
246 }
247 6 => {
250 let metrics = read_big_metrics(&mut image_data)?;
251 let pitch = (metrics.width as usize * location.bit_depth as usize).div_ceil(8);
253 let height = metrics.height as usize;
254 let data = image_data.read_array::<u8>(pitch * height)?;
255 Ok(BitmapData {
256 metrics: BitmapMetrics::Big(metrics),
257 content: BitmapContent::Data(BitmapDataFormat::ByteAligned, data),
258 })
259 }
260 7 => {
263 let metrics = read_big_metrics(&mut image_data)?;
264 let width = metrics.width as usize * location.bit_depth as usize;
265 let height = metrics.height as usize;
266 let data = image_data.read_array::<u8>((width * height).div_ceil(8))?;
268 Ok(BitmapData {
269 metrics: BitmapMetrics::Big(metrics),
270 content: BitmapContent::Data(BitmapDataFormat::BitAligned, data),
271 })
272 }
273 8 => {
276 let metrics = read_small_metrics(&mut image_data)?;
277 let _pad = image_data.read::<u8>()?;
278 let count = image_data.read::<u16>()? as usize;
279 let components = image_data.read_array::<BdtComponent>(count)?;
280 Ok(BitmapData {
281 metrics: BitmapMetrics::Small(metrics),
282 content: BitmapContent::Composite(components),
283 })
284 }
285 9 => {
288 let metrics = read_big_metrics(&mut image_data)?;
289 let count = image_data.read::<u16>()? as usize;
290 let components = image_data.read_array::<BdtComponent>(count)?;
291 Ok(BitmapData {
292 metrics: BitmapMetrics::Big(metrics),
293 content: BitmapContent::Composite(components),
294 })
295 }
296 17 if is_color => {
299 let metrics = read_small_metrics(&mut image_data)?;
300 let data_len = image_data.read::<u32>()? as usize;
301 let data = image_data.read_array::<u8>(data_len)?;
302 Ok(BitmapData {
303 metrics: BitmapMetrics::Small(metrics),
304 content: BitmapContent::Data(BitmapDataFormat::Png, data),
305 })
306 }
307 18 if is_color => {
310 let metrics = read_big_metrics(&mut image_data)?;
311 let data_len = image_data.read::<u32>()? as usize;
312 let data = image_data.read_array::<u8>(data_len)?;
313 Ok(BitmapData {
314 metrics: BitmapMetrics::Big(metrics),
315 content: BitmapContent::Data(BitmapDataFormat::Png, data),
316 })
317 }
318 19 if is_color => {
321 let metrics = location.metrics.ok_or(ReadError::MalformedData(
322 "expected metrics from location table",
323 ))?;
324 let data_len = image_data.read::<u32>()? as usize;
325 let data = image_data.read_array::<u8>(data_len)?;
326 Ok(BitmapData {
327 metrics: BitmapMetrics::Big(metrics),
328 content: BitmapContent::Data(BitmapDataFormat::Png, data),
329 })
330 }
331 _ => Err(ReadError::MalformedData("unexpected bitmap data format")),
332 }
333}
334
335fn read_small_metrics(cursor: &mut Cursor) -> Result<SmallGlyphMetrics, ReadError> {
336 Ok(cursor.read_array::<SmallGlyphMetrics>(1)?[0])
337}
338
339fn read_big_metrics(cursor: &mut Cursor) -> Result<BigGlyphMetrics, ReadError> {
340 Ok(cursor.read_array::<BigGlyphMetrics>(1)?[0])
341}
342
343#[derive(Clone)]
345pub enum IndexSubtable<'a> {
346 Format1(IndexSubtable1<'a>),
347 Format2(IndexSubtable2<'a>),
348 Format3(IndexSubtable3<'a>),
349 Format4(IndexSubtable4<'a>),
350 Format5(IndexSubtable5<'a>),
351}
352
353impl<'a> IndexSubtable<'a> {
354 pub fn offset_data(&self) -> FontData<'a> {
356 match self {
357 Self::Format1(item) => item.offset_data(),
358 Self::Format2(item) => item.offset_data(),
359 Self::Format3(item) => item.offset_data(),
360 Self::Format4(item) => item.offset_data(),
361 Self::Format5(item) => item.offset_data(),
362 }
363 }
364
365 pub fn index_format(&self) -> u16 {
367 match self {
368 Self::Format1(item) => item.index_format(),
369 Self::Format2(item) => item.index_format(),
370 Self::Format3(item) => item.index_format(),
371 Self::Format4(item) => item.index_format(),
372 Self::Format5(item) => item.index_format(),
373 }
374 }
375
376 pub fn image_format(&self) -> u16 {
378 match self {
379 Self::Format1(item) => item.image_format(),
380 Self::Format2(item) => item.image_format(),
381 Self::Format3(item) => item.image_format(),
382 Self::Format4(item) => item.image_format(),
383 Self::Format5(item) => item.image_format(),
384 }
385 }
386
387 pub fn image_data_offset(&self) -> u32 {
389 match self {
390 Self::Format1(item) => item.image_data_offset(),
391 Self::Format2(item) => item.image_data_offset(),
392 Self::Format3(item) => item.image_data_offset(),
393 Self::Format4(item) => item.image_data_offset(),
394 Self::Format5(item) => item.image_data_offset(),
395 }
396 }
397}
398
399impl ReadArgs for IndexSubtable<'_> {
400 type Args = (GlyphId16, GlyphId16);
401}
402impl<'a> FontRead<'a> for IndexSubtable<'a> {
403 fn read_with_args(data: FontData<'a>, args: Self::Args) -> Result<Self, ReadError> {
404 let format: u16 = data.read_at(0usize)?;
405 match format {
406 IndexSubtable1::FORMAT => FontRead::read_with_args(data, args).map(Self::Format1),
407 IndexSubtable2::FORMAT => FontRead::read(data).map(Self::Format2),
408 IndexSubtable3::FORMAT => FontRead::read_with_args(data, args).map(Self::Format3),
409 IndexSubtable4::FORMAT => FontRead::read(data).map(Self::Format4),
410 IndexSubtable5::FORMAT => FontRead::read(data).map(Self::Format5),
411 other => Err(ReadError::InvalidFormat(other.into())),
412 }
413 }
414}
415
416impl<'a> MinByteRange<'a> for IndexSubtable<'a> {
417 fn min_byte_range(&self) -> Range<usize> {
418 match self {
419 Self::Format1(item) => item.min_byte_range(),
420 Self::Format2(item) => item.min_byte_range(),
421 Self::Format3(item) => item.min_byte_range(),
422 Self::Format4(item) => item.min_byte_range(),
423 Self::Format5(item) => item.min_byte_range(),
424 }
425 }
426
427 fn min_table_bytes(&self) -> &'a [u8] {
428 match self {
429 Self::Format1(item) => item.min_table_bytes(),
430 Self::Format2(item) => item.min_table_bytes(),
431 Self::Format3(item) => item.min_table_bytes(),
432 Self::Format4(item) => item.min_table_bytes(),
433 Self::Format5(item) => item.min_table_bytes(),
434 }
435 }
436}
437
438#[cfg(test)]
439mod tests {
440 use super::*;
441 use crate::{types::GlyphId16, FontData};
442 use font_test_data::bebuffer::BeBuffer;
443
444 fn bitmap_size_location(data: &[u8], glyph_id: GlyphId) -> Result<BitmapLocation, ReadError> {
445 let data = FontData::new(data);
446 let size = data.read_ref_at::<BitmapSize>(0).unwrap();
447 size.location(data, glyph_id)
448 }
449
450 fn bitmap_size_with_subtable(subtable: &[u8]) -> BeBuffer {
451 BeBuffer::new()
452 .push(BitmapSize::RAW_BYTE_LEN as u32)
453 .push((IndexSubtableRecord::RAW_BYTE_LEN + subtable.len()) as u32)
454 .push(1u32)
455 .push(0u32)
456 .extend([0u8; SbitLineMetrics::RAW_BYTE_LEN])
457 .extend([0u8; SbitLineMetrics::RAW_BYTE_LEN])
458 .push(GlyphId16::new(0))
459 .push(GlyphId16::new(0))
460 .push(0u8)
461 .push(0u8)
462 .push(1u8)
463 .push(0u8)
464 .push(GlyphId16::new(0))
465 .push(GlyphId16::new(0))
466 .push(IndexSubtableRecord::RAW_BYTE_LEN as u32)
467 .extend(subtable.iter().copied())
468 }
469
470 #[test]
471 fn short_index_tables_size_is_ignored() {
472 let subtable = BeBuffer::new()
476 .push(2u16) .push(5u16) .push(0u32) .push(4u32) .extend([0u8; 8]); let subtable = subtable.data();
482 let data = BeBuffer::new()
483 .push(BitmapSize::RAW_BYTE_LEN as u32)
484 .push(IndexSubtableRecord::RAW_BYTE_LEN as u32)
486 .push(1u32)
487 .push(0u32)
488 .extend([0u8; SbitLineMetrics::RAW_BYTE_LEN])
489 .extend([0u8; SbitLineMetrics::RAW_BYTE_LEN])
490 .push(GlyphId16::new(0))
491 .push(GlyphId16::new(1))
492 .push(0u8)
493 .push(0u8)
494 .push(1u8)
495 .push(0u8)
496 .push(GlyphId16::new(0))
497 .push(GlyphId16::new(1))
498 .push(IndexSubtableRecord::RAW_BYTE_LEN as u32)
499 .extend(subtable.iter().copied());
500 let location = bitmap_size_location(data.data(), GlyphId::new(1)).unwrap();
501 assert_eq!(location.data_offset, 4);
502 assert_eq!(location.data_size, 4);
503 }
504
505 #[test]
506 fn format_2_truncated_metrics_returns_error_instead_of_panicking() {
507 let data =
508 bitmap_size_with_subtable(&BeBuffer::new().push(2u16).push(5u16).push(0u32).push(1u32));
509 let result = bitmap_size_location(data.data(), GlyphId::new(0));
511 assert!(matches!(result, Err(ReadError::OutOfBounds)));
512 }
513
514 #[test]
515 fn format_4_sbit_offsets_are_relative_to_image_data_offset() {
516 let data = bitmap_size_with_subtable(
517 &BeBuffer::new()
518 .push(4u16) .push(17u16) .push(1000u32) .push(1u32) .push(GlyphId16::new(0))
523 .push(20u16) .push(GlyphId16::new(1))
525 .push(30u16), );
527 let location = bitmap_size_location(data.data(), GlyphId::new(0)).unwrap();
528 assert_eq!(location.data_offset, 1020);
529 assert_eq!(location.data_size, 10);
530 }
531
532 #[test]
533 fn format_5_truncated_metrics_returns_error_instead_of_panicking() {
534 let data = bitmap_size_with_subtable(
535 &BeBuffer::new()
536 .push(5u16)
537 .push(5u16)
538 .push(0u32)
539 .push(1u32)
540 .push(0u32),
541 );
542 let result = bitmap_size_location(data.data(), GlyphId::new(0));
544 assert!(result.is_err());
545 }
546}