1
#![deny(missing_docs)]
2

            
3
//! Checksum calculation routines.
4

            
5
use std::num::Wrapping;
6

            
7
use crate::binary::read::ReadScope;
8
use crate::binary::U32Be;
9
use crate::error::ParseError;
10

            
11
/// Calculate a checksum of `data` according to the OpenType table checksum algorithm
12
///
13
/// <https://docs.microsoft.com/en-us/typography/opentype/spec/otff#calculating-checksums>
14
pub fn table_checksum(data: &[u8]) -> Result<Wrapping<u32>, ParseError> {
15
    assert_eq!(data.len() % 4, 0, "data end is not 32-bit aligned");
16

            
17
    let mut ctxt = ReadScope::new(data).ctxt();
18
    let array = ctxt.read_array::<U32Be>(data.len() / 4)?;
19
    Ok(array.iter().map(Wrapping).sum())
20
}
21

            
22
#[cfg(test)]
23
mod tests {
24
    use super::Wrapping;
25

            
26
    #[test]
27
    fn test_table_checksum() {
28
        let data = [0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4];
29

            
30
        assert_eq!(super::table_checksum(&data).unwrap(), Wrapping(10));
31
    }
32

            
33
    #[test]
34
    fn test_table_checksum_overflow() {
35
        let data = [0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 2];
36

            
37
        assert_eq!(super::table_checksum(&data).unwrap(), Wrapping(1));
38
    }
39
}