1use crate::error::{ParseError, RawTag};
5use crate::reader::Reader;
6use crate::tables;
7use crate::tables::glyf::{GlyphOutline, GlyphRef, MAX_COMPONENT_DEPTH, MAX_OUTLINE_POINTS};
8use crate::tables::{Cmap, HeadTable};
9use crate::tag::TableTag;
10use alloc::vec::Vec;
11use font_types::{F2Dot14, GlyphId, Tag};
12
13const SFNT_VERSION_TRUE: u32 = 0x0001_0000;
14const SFNT_VERSION_OTTO: u32 = 0x4F54_544F; const SFNT_VERSION_TRUE_APPLE: u32 = 0x7472_7565; const TTC_TAG: RawTag = *b"ttcf";
17const SFNT_TAG: RawTag = *b"sfnt";
18
19const ENTRY: usize = 16;
21
22fn is_known_sfnt_version(version: u32) -> bool {
23 matches!(
24 version,
25 SFNT_VERSION_TRUE | SFNT_VERSION_OTTO | SFNT_VERSION_TRUE_APPLE
26 )
27}
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub struct FontRef<'a> {
36 data: &'a [u8],
37 dir_offset: usize,
40 num_tables: u16,
41 sfnt_version: u32,
42}
43
44impl<'a> FontRef<'a> {
45 pub fn new(data: &'a [u8]) -> Result<Self, ParseError> {
56 let mut r = Reader::new(data, SFNT_TAG);
57 let version = r.u32()?;
58 if !is_known_sfnt_version(version) {
59 return Err(ParseError::InvalidSfnt);
60 }
61 let num_tables = r.u16()?;
62 if num_tables == 0 {
63 return Err(ParseError::InvalidSfnt);
64 }
65 r.skip(6)?; validate_directory(data, 0, num_tables)?;
67 Ok(Self {
68 data,
69 dir_offset: 0,
70 num_tables,
71 sfnt_version: version,
72 })
73 }
74
75 #[must_use]
77 pub fn as_bytes(&self) -> &'a [u8] {
78 self.data
79 }
80
81 #[must_use]
83 pub const fn sfnt_version(&self) -> u32 {
84 self.sfnt_version
85 }
86
87 #[must_use]
89 pub const fn is_cff(&self) -> bool {
90 self.sfnt_version == SFNT_VERSION_OTTO
91 }
92
93 #[must_use]
95 pub fn is_variable(&self) -> bool {
96 self.table(TableTag::Fvar).is_some()
97 }
98
99 #[must_use]
101 pub const fn num_tables(&self) -> u16 {
102 self.num_tables
103 }
104
105 #[must_use]
107 pub fn table(&self, tag: TableTag) -> Option<&'a [u8]> {
108 self.table_by_tag(tag.to_tag())
109 }
110
111 #[must_use]
113 pub fn table_by_tag(&self, tag: Tag) -> Option<&'a [u8]> {
114 let want = tag.to_be_bytes();
115 for i in 0..usize::from(self.num_tables) {
116 let at = self.dir_offset + 12 + i * ENTRY;
117 let found = crate::reader::slice_at(self.data, at, 4, SFNT_TAG).ok()?;
118 if found == want {
119 let offset = crate::reader::be_u32_at(self.data, at + 8, SFNT_TAG).ok()?;
120 let length = crate::reader::be_u32_at(self.data, at + 12, SFNT_TAG).ok()?;
121 let offset = usize::try_from(offset).ok()?;
122 let length = usize::try_from(length).ok()?;
123 let end = offset.checked_add(length)?;
124 return self.data.get(offset..end);
125 }
126 }
127 None
128 }
129
130 #[must_use]
133 pub fn table_directory(&self) -> Vec<(RawTag, u32, u32, u32)> {
134 let mut out = Vec::with_capacity(usize::from(self.num_tables));
135 for i in 0..usize::from(self.num_tables) {
136 let at = self.dir_offset + 12 + i * ENTRY;
137 let (Ok(raw_tag), Ok(checksum), Ok(offset), Ok(length)) = (
138 crate::reader::be_u32_at(self.data, at, SFNT_TAG),
139 crate::reader::be_u32_at(self.data, at + 4, SFNT_TAG),
140 crate::reader::be_u32_at(self.data, at + 8, SFNT_TAG),
141 crate::reader::be_u32_at(self.data, at + 12, SFNT_TAG),
142 ) else {
143 continue;
144 };
145 out.push((raw_tag.to_be_bytes(), checksum, offset, length));
146 }
147 out
148 }
149
150 fn table_or_err(&self, tag: TableTag) -> Result<&'a [u8], ParseError> {
153 self.table(tag)
154 .ok_or(ParseError::UnknownTableTag(tag.to_bytes()))
155 }
156
157 pub fn head(&self) -> Result<HeadTable<'a>, ParseError> {
162 HeadTable::parse(self.table_or_err(TableTag::Head)?)
163 }
164
165 pub fn hhea(&self) -> Result<tables::HheaTable<'a>, ParseError> {
170 tables::HheaTable::parse(self.table_or_err(TableTag::Hhea)?)
171 }
172
173 pub fn hmtx(&self) -> Result<tables::HmtxTable<'a>, ParseError> {
178 let num_h_metrics = self.hhea()?.number_of_h_metrics()?;
179 tables::HmtxTable::parse(
180 self.table_or_err(TableTag::Hmtx)?,
181 num_h_metrics,
182 self.num_glyphs(),
183 )
184 }
185
186 pub fn maxp(&self) -> Result<tables::MaxpTable<'a>, ParseError> {
191 tables::MaxpTable::parse(self.table_or_err(TableTag::Maxp)?)
192 }
193
194 #[must_use]
196 pub fn num_glyphs(&self) -> u16 {
197 self.table(TableTag::Maxp)
198 .and_then(|d| tables::MaxpTable::parse(d).ok())
199 .map_or(0, |m| m.num_glyphs())
200 }
201
202 pub fn cmap(&self) -> Result<Cmap<'a>, ParseError> {
207 Cmap::parse(self.table_or_err(TableTag::Cmap)?)
208 }
209
210 pub fn name(&self) -> Result<tables::NameTable<'a>, ParseError> {
215 tables::NameTable::parse(self.table_or_err(TableTag::Name)?)
216 }
217
218 pub fn os2(&self) -> Result<tables::Os2Table<'a>, ParseError> {
223 tables::Os2Table::parse(self.table_or_err(TableTag::Os2)?)
224 }
225
226 pub fn post(&self) -> Result<tables::PostTable<'a>, ParseError> {
231 tables::PostTable::parse(self.table_or_err(TableTag::Post)?)
232 }
233
234 pub fn stat(&self) -> Result<tables::StatTable<'a>, ParseError> {
241 tables::StatTable::parse(self.table_or_err(TableTag::Stat)?)
242 }
243
244 pub fn dsig(&self) -> Result<tables::DsigTable<'a>, ParseError> {
249 tables::DsigTable::parse(self.table_or_err(TableTag::Dsig)?)
250 }
251
252 pub fn layout(&self, kind: tables::LayoutKind) -> Result<tables::LayoutTable<'a>, ParseError> {
257 let tag = kind.tag();
258 let data = self
259 .table_by_tag(Tag::new(&tag))
260 .ok_or(ParseError::UnknownTableTag(tag))?;
261 tables::LayoutTable::parse(data, kind)
262 }
263
264 pub fn variable(&self) -> Result<VariableFont<'a>, ParseError> {
269 let fvar = tables::FvarTable::parse(self.table_or_err(TableTag::Fvar)?)?;
270 let avar = self
271 .table(TableTag::Avar)
272 .map(tables::AvarTable::parse)
273 .transpose()?;
274 let gvar = self
275 .table(TableTag::Gvar)
276 .map(|d| tables::GvarTable::parse(d, self.num_glyphs()))
277 .transpose()?;
278 Ok(VariableFont {
279 font: *self,
280 fvar,
281 avar,
282 gvar,
283 })
284 }
285
286 pub fn glyph_data(&self, gid: GlyphId) -> Result<Option<&'a [u8]>, ParseError> {
294 let Some(range) = self.locus(gid)? else {
295 return Ok(None);
296 };
297 let glyf = self.table_or_err(TableTag::Glyf)?;
298 Ok(glyf.get(range.start..range.end))
299 }
300
301 pub fn glyph(&self, gid: GlyphId) -> Result<Option<GlyphRef<'a>>, ParseError> {
306 match self.glyph_data(gid)? {
307 None => Ok(None),
308 Some(data) => GlyphRef::parse(data),
309 }
310 }
311
312 fn loca(&self) -> Result<tables::LocaTable<'a>, ParseError> {
314 let long = self.head()?.index_to_loc_format()? == 1;
315 tables::LocaTable::parse(self.table_or_err(TableTag::Loca)?, self.num_glyphs(), long)
316 }
317
318 fn locus(&self, gid: GlyphId) -> Result<Option<core::ops::Range<usize>>, ParseError> {
321 let Ok(id) = u16::try_from(gid.to_u32()) else {
322 return Ok(None);
323 };
324 self.loca()?.glyph_range(id)
325 }
326
327 pub fn advance_width(&self, gid: GlyphId) -> Result<u16, ParseError> {
332 let Ok(id) = u16::try_from(gid.to_u32()) else {
333 return Ok(0); };
335 self.hmtx()?.advance(id)
336 }
337
338 pub fn outline(&self, gid: GlyphId) -> Result<Option<GlyphOutline>, ParseError> {
352 self.outline_bounded(gid, 0, &mut 0)
353 }
354
355 fn outline_bounded(
356 &self,
357 gid: GlyphId,
358 depth: u8,
359 budget: &mut usize,
360 ) -> Result<Option<GlyphOutline>, ParseError> {
361 if depth > MAX_COMPONENT_DEPTH {
362 return Err(ParseError::InvalidGlyphFormat);
363 }
364 let Some(glyph) = self.glyph(gid)? else {
365 return Ok(None);
366 };
367 match glyph {
368 GlyphRef::Simple(simple) => {
369 let outline = simple.outline()?;
370 *budget = budget.saturating_add(outline.point_count());
371 if *budget > MAX_OUTLINE_POINTS {
372 return Err(ParseError::InvalidGlyphFormat);
373 }
374 Ok(Some(outline))
375 }
376 GlyphRef::Composite(composite) => {
377 let mut contours = Vec::new();
378 for component in composite.components()? {
379 *budget = budget.saturating_add(1);
380 if *budget > MAX_OUTLINE_POINTS {
381 return Err(ParseError::InvalidGlyphFormat);
382 }
383 let Some(inner) = self.outline_bounded(component.glyph, depth + 1, budget)?
384 else {
385 continue;
386 };
387 let (dx, dy) = if component.args_are_offsets() {
388 (
389 f32::from(i16::try_from(component.args.0).unwrap_or(0)),
390 f32::from(i16::try_from(component.args.1).unwrap_or(0)),
391 )
392 } else {
393 (0.0, 0.0)
395 };
396 let [a, b, c, d] = component.transform;
397 for mut contour in inner.contours {
398 for pt in &mut contour.points {
399 let x = a * pt.x + c * pt.y + dx;
400 let y = b * pt.x + d * pt.y + dy;
401 pt.x = x;
402 pt.y = y;
403 }
404 contours.push(contour);
405 }
406 }
407 Ok(Some(GlyphOutline { contours }))
408 }
409 }
410 }
411
412 pub fn gvar_deltas(&self, gid: GlyphId) -> Result<Vec<tables::TupleVariation>, ParseError> {
419 let Some(gvar) = self.table(TableTag::Gvar) else {
420 return Ok(Vec::new());
421 };
422 let point_count = self.outline_point_count(gid)?;
423 let gvar = tables::GvarTable::parse(gvar, self.num_glyphs())?;
424 let Ok(id) = u16::try_from(gid.to_u32()) else {
425 return Ok(Vec::new());
426 };
427 gvar.glyph_deltas(id, point_count)
428 }
429
430 fn outline_point_count(&self, gid: GlyphId) -> Result<u16, ParseError> {
435 let Some(data) = self.glyph_data(gid)? else {
436 return Ok(4); };
438 let n = match GlyphRef::parse(data)? {
439 None => 0,
440 Some(GlyphRef::Simple(s)) => {
441 let pts = s.points()?;
442 usize::from(u16::try_from(pts.len()).map_err(|_| ParseError::InvalidGlyphFormat)?)
443 }
444 Some(GlyphRef::Composite(c)) => {
445 let comps = c.components()?;
446 usize::from(u16::try_from(comps.len()).map_err(|_| ParseError::InvalidGlyphFormat)?)
447 }
448 };
449 u16::try_from(n + 4).map_err(|_| ParseError::InvalidGlyphFormat)
450 }
451}
452
453#[derive(Debug, Clone)]
459pub struct OwnedFont {
460 data: Vec<u8>,
461}
462
463impl OwnedFont {
464 pub fn from_sfnt(data: Vec<u8>) -> Result<Self, ParseError> {
469 FontRef::new(&data)?;
470 Ok(Self { data })
471 }
472
473 #[cfg(feature = "woff")]
478 pub fn from_woff(data: &[u8]) -> Result<Self, ParseError> {
479 crate::woff::decode(data)
480 }
481
482 #[cfg(feature = "woff2")]
491 pub fn from_woff2(data: &[u8]) -> Result<Self, ParseError> {
492 crate::woff2::decode(data)
493 }
494
495 pub fn from_collection(data: &[u8], index: usize) -> Result<Self, ParseError> {
502 let collection = FontCollection::parse(data)?;
503 let font = collection.font(index)?;
504 let mut tables_to_build: Vec<(RawTag, Vec<u8>)> = Vec::new();
505 for (tag, _checksum, offset, length) in font.table_directory() {
506 let off = usize::try_from(offset).map_err(|_| ParseError::InvalidSfnt)?;
507 let len = usize::try_from(length).map_err(|_| ParseError::InvalidSfnt)?;
508 let bytes = crate::reader::slice_at(font.data, off, len, tag)?;
509 tables_to_build.push((tag, bytes.to_vec()));
510 }
511 let flavor = font.sfnt_version();
512 build_sfnt(flavor, &mut tables_to_build).map(|data| Self { data })
513 }
514
515 pub fn as_font_ref(&self) -> Result<FontRef<'_>, ParseError> {
522 FontRef::new(&self.data)
523 }
524
525 #[must_use]
527 pub fn as_slice(&self) -> &[u8] {
528 &self.data
529 }
530
531 #[must_use]
533 pub fn into_vec(self) -> Vec<u8> {
534 self.data
535 }
536}
537
538#[derive(Debug, Clone)]
540pub struct FontCollection<'a> {
541 data: &'a [u8],
542 offsets: Vec<usize>,
543 version: u32,
544}
545
546impl<'a> FontCollection<'a> {
547 pub fn parse(data: &'a [u8]) -> Result<Self, ParseError> {
553 if data.len() < 12 {
554 return Err(ParseError::TruncatedTable {
555 tag: TTC_TAG,
556 expected: 12,
557 got: data.len(),
558 });
559 }
560 let tag = crate::reader::slice_at(data, 0, 4, TTC_TAG)?;
561 if tag != TTC_TAG.as_slice() {
562 return Err(ParseError::InvalidSfnt);
563 }
564 let version = crate::reader::be_u32_at(data, 4, TTC_TAG)?;
565 let num = crate::reader::be_u32_at(data, 8, TTC_TAG)?;
566 let num = usize::try_from(num).map_err(|_| ParseError::InvalidSfnt)?;
567 let end = 12usize
568 .checked_add(num.checked_mul(4).ok_or(ParseError::InvalidSfnt)?)
569 .ok_or(ParseError::InvalidSfnt)?;
570 if data.len() < end {
571 return Err(ParseError::TruncatedTable {
572 tag: TTC_TAG,
573 expected: end,
574 got: data.len(),
575 });
576 }
577 let mut offsets = Vec::with_capacity(num);
578 for i in 0..num {
579 let off = crate::reader::be_u32_at(data, 12 + i * 4, TTC_TAG)?;
580 let off = usize::try_from(off).map_err(|_| ParseError::InvalidSfnt)?;
581 offsets.push(off);
582 }
583 Ok(Self {
584 data,
585 offsets,
586 version,
587 })
588 }
589
590 #[must_use]
592 pub const fn version(&self) -> u32 {
593 self.version
594 }
595
596 #[must_use]
598 pub fn len(&self) -> usize {
599 self.offsets.len()
600 }
601
602 #[must_use]
604 pub fn is_empty(&self) -> bool {
605 self.offsets.is_empty()
606 }
607
608 pub fn font(&self, index: usize) -> Result<FontRef<'a>, ParseError> {
616 let dir_offset =
617 *self
618 .offsets
619 .get(index)
620 .ok_or(ParseError::CollectionIndexOutOfBounds {
621 index,
622 count: self.offsets.len(),
623 })?;
624 let sub = self.data.get(dir_offset..).ok_or(ParseError::InvalidSfnt)?;
625 let mut r = Reader::new(sub, TTC_TAG);
626 let version = r.u32()?;
627 if !is_known_sfnt_version(version) {
628 return Err(ParseError::InvalidSfnt);
629 }
630 let num_tables = r.u16()?;
631 if num_tables == 0 {
632 return Err(ParseError::InvalidSfnt);
633 }
634 r.skip(6)?;
635 validate_directory(self.data, dir_offset, num_tables)?;
636 Ok(FontRef {
637 data: self.data,
638 dir_offset,
639 num_tables,
640 sfnt_version: version,
641 })
642 }
643
644 pub fn fonts(&self) -> Result<Vec<FontRef<'a>>, ParseError> {
649 let mut out = Vec::with_capacity(self.offsets.len());
650 for i in 0..self.offsets.len() {
651 out.push(self.font(i)?);
652 }
653 Ok(out)
654 }
655
656 pub fn fonts_in(data: &'a [u8]) -> Result<Vec<FontRef<'a>>, ParseError> {
661 Self::parse(data)?.fonts()
662 }
663}
664
665fn validate_directory(data: &[u8], dir_offset: usize, num_tables: u16) -> Result<(), ParseError> {
667 let dir_end = dir_offset
668 .checked_add(12 + usize::from(num_tables) * ENTRY)
669 .ok_or(ParseError::InvalidSfnt)?;
670 if data.len() < dir_end {
671 return Err(ParseError::TruncatedTable {
672 tag: SFNT_TAG,
673 expected: dir_end,
674 got: data.len(),
675 });
676 }
677 for i in 0..usize::from(num_tables) {
678 let at = dir_offset + 12 + i * ENTRY;
679 let offset = crate::reader::be_u32_at(data, at + 8, SFNT_TAG)?;
680 let length = crate::reader::be_u32_at(data, at + 12, SFNT_TAG)?;
681 let offset = usize::try_from(offset).map_err(|_| ParseError::InvalidSfnt)?;
682 let length = usize::try_from(length).map_err(|_| ParseError::InvalidSfnt)?;
683 let end = offset.checked_add(length).ok_or(ParseError::InvalidSfnt)?;
684 if end > data.len() {
685 let mut tag: RawTag = *b"????";
686 if let Some(found) = data.get(at..at + 4) {
687 tag.copy_from_slice(found);
688 }
689 return Err(ParseError::TruncatedTable {
690 tag,
691 expected: end,
692 got: data.len(),
693 });
694 }
695 }
696 Ok(())
697}
698
699#[derive(Debug, Clone, Copy)]
702pub struct VariableFont<'a> {
703 font: FontRef<'a>,
704 fvar: tables::FvarTable<'a>,
705 avar: Option<tables::AvarTable<'a>>,
706 gvar: Option<tables::GvarTable<'a>>,
707}
708
709impl<'a> VariableFont<'a> {
710 pub fn axes(&self) -> Result<Vec<tables::VariationAxis>, ParseError> {
715 self.fvar.axes()
716 }
717
718 pub fn instances(&self) -> Result<Vec<tables::VarInstance>, ParseError> {
723 self.fvar.instances()
724 }
725
726 #[must_use]
728 pub const fn avar(&self) -> Option<tables::AvarTable<'a>> {
729 self.avar
730 }
731
732 #[must_use]
734 pub const fn gvar(&self) -> Option<tables::GvarTable<'a>> {
735 self.gvar
736 }
737
738 #[must_use]
740 pub const fn font(&self) -> FontRef<'a> {
741 self.font
742 }
743
744 pub fn normalize(&self, axis: usize, value: font_types::Fixed) -> Result<F2Dot14, ParseError> {
751 let axes = self.fvar.axes()?;
752 let axis_rec = axes.get(axis).ok_or(ParseError::InvalidGlyphFormat)?;
753 let min = axis_rec.min.to_f64();
754 let def = axis_rec.default.to_f64();
755 let max = axis_rec.max.to_f64();
756 let v = value.to_f64();
757 let normalized: f64 = if v < def {
760 if (def - min).abs() < f64::EPSILON {
761 -1.0
762 } else {
763 (v - def) / (def - min)
764 }
765 } else if (max - def).abs() < f64::EPSILON {
766 1.0
767 } else {
768 (v - def) / (max - def)
769 };
770 let scaled = normalized.clamp(-1.0, 1.0) * 16_384.0;
773 let shifted = if scaled < 0.0 {
774 scaled - 0.5
775 } else {
776 scaled + 0.5
777 };
778 let bits_wide = shifted as i64; let bits = i16::try_from(bits_wide).map_err(|_| ParseError::InvalidGlyphFormat)?;
780 let coord = F2Dot14::from_bits(bits);
781 match self.avar {
782 Some(avar) => {
783 let maps = avar.segment_maps()?;
784 Ok(maps.get(axis).map_or(coord, |m| m.map(coord)))
785 }
786 None => Ok(coord),
787 }
788 }
789}
790
791pub(crate) fn build_sfnt(
794 flavor: u32,
795 tables_in: &mut [(RawTag, Vec<u8>)],
796) -> Result<Vec<u8>, ParseError> {
797 if tables_in.is_empty() {
798 return Err(ParseError::InvalidSfnt);
799 }
800 tables_in.sort_by_key(|t| t.0);
801 let n = tables_in.len();
802 let entry_selector = 31 - (n as u32).leading_zeros(); let search_range: u32 = 16 << entry_selector;
804 let range_shift = n as u32 * 16 - search_range;
805
806 let dir_len = 12 + n * ENTRY;
807 let mut out = Vec::with_capacity(dir_len + 1024);
808 out.extend_from_slice(&flavor.to_be_bytes());
809 out.extend_from_slice(&(n as u16).to_be_bytes());
810 out.extend_from_slice(&(search_range as u16).to_be_bytes());
811 out.extend_from_slice(&(entry_selector as u16).to_be_bytes());
812 out.extend_from_slice(&(range_shift as u16).to_be_bytes());
813
814 let mut offset: u32 = dir_len as u32;
816 let mut entries = Vec::with_capacity(n);
817 for (tag, bytes) in tables_in.iter() {
818 entries.push((*tag, table_checksum(bytes), offset, bytes.len() as u32));
819 let end = offset
821 .checked_add(bytes.len() as u32)
822 .ok_or(ParseError::InvalidSfnt)?;
823 let pad = (4 - (end % 4)) % 4;
824 offset = end.checked_add(pad).ok_or(ParseError::InvalidSfnt)?;
825 }
826 for (tag, checksum, off, len) in &entries {
827 out.extend_from_slice(tag);
828 out.extend_from_slice(&checksum.to_be_bytes());
829 out.extend_from_slice(&off.to_be_bytes());
830 out.extend_from_slice(&len.to_be_bytes());
831 }
832 for (_, bytes) in tables_in.iter() {
833 out.extend_from_slice(bytes);
834 while out.len() % 4 != 0 {
835 out.push(0);
836 }
837 }
838 let head_off = entries
841 .iter()
842 .find(|(t, _, _, _)| t == b"head")
843 .map(|(_, _, off, _)| *off as usize);
844 if let Some(head_at) = head_off {
845 set_bytes(&mut out, head_at + 8, &[0, 0, 0, 0])?;
846 let adjustment = 0xB1B0_AFBAu32.wrapping_sub(table_checksum(&out));
847 set_bytes(&mut out, head_at + 8, &adjustment.to_be_bytes())?;
848 }
849 Ok(out)
850}
851
852fn set_bytes(out: &mut [u8], at: usize, bytes: &[u8; 4]) -> Result<(), ParseError> {
854 out.get_mut(at..at + 4)
855 .ok_or(ParseError::InvalidSfnt)?
856 .copy_from_slice(bytes);
857 Ok(())
858}
859
860pub(crate) fn table_checksum(bytes: &[u8]) -> u32 {
862 let mut sum: u32 = 0;
863 let mut chunks = bytes.chunks_exact(4);
864 for c in chunks.by_ref() {
865 if let Ok(word) = <[u8; 4]>::try_from(c) {
866 sum = sum.wrapping_add(u32::from_be_bytes(word));
867 }
868 }
869 let rest = chunks.remainder();
870 if !rest.is_empty() {
871 let mut last = [0u8; 4];
872 for (i, &b) in rest.iter().enumerate() {
873 if let Some(slot) = last.get_mut(i) {
874 *slot = b;
875 }
876 }
877 sum = sum.wrapping_add(u32::from_be_bytes(last));
878 }
879 sum
880}