Skip to content

Commit

Permalink
Fix checksum calculation for TrueType tables
Browse files Browse the repository at this point in the history
The current way of calculating the checksum is wrong because the last 1,
2 or 3 bytes are not respected.
  • Loading branch information
gettalong committed Nov 4, 2024
1 parent 59ded97 commit 4f8f493
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
## Unreleased

### Fixed

* Checksum calculation for TrueType tables


## 1.0.1 - 2024-11-04

### Changed
Expand Down
7 changes: 6 additions & 1 deletion lib/hexapdf/font/true_type/table.rb
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,12 @@ class Table

# Calculates the checksum for the given data.
def self.calculate_checksum(data)
data.unpack('N*').inject(0) {|sum, long| sum + long } % 2**32
checksum = 0
if (remainder_length = data.length % 4) != 0
checksum = (data[-remainder_length, remainder_length] << "\0" * (4 - remainder_length)).
unpack1('N')
end
checksum + data.unpack('N*').inject(0) {|sum, long| sum + long } % 2**32
end

# The TrueType font object associated with this table.
Expand Down
12 changes: 12 additions & 0 deletions test/hexapdf/font/true_type/test_table.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,18 @@
@entry = HexaPDF::Font::TrueType::Table::Directory::Entry.new('tagg', 0, 0, @file.io.string.length)
end

describe "self.calculate_checksum" do
it "works for data with a length divisible by four" do
klass = HexaPDF::Font::TrueType::Table
assert_equal(256, klass.calculate_checksum("\x00\x00\x00\x01\x00\x00\x00\xFF"))
end

it "works for data with a length not divisible by four" do
klass = HexaPDF::Font::TrueType::Table
assert_equal(512, klass.calculate_checksum("\x00\x00\x00\x01\x00\x00\x00\xFF\x00\x00\x01"))
end
end

describe "initialize" do
it "reads the data from the associated file" do
table = TrueTypeTestTable.new(@file, @entry)
Expand Down

0 comments on commit 4f8f493

Please sign in to comment.