Skip to content

Commit

Permalink
(fix) Chunk matching
Browse files Browse the repository at this point in the history
Fixes bug where chunk would not be found if preceded by a part of itself
  • Loading branch information
vHeemstra committed Aug 9, 2024
1 parent b2ee727 commit 28d27c2
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 7 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@
"scripts": {
"lint": "eslint ./src/",
"lint:fix": "eslint ./src/ --fix",
"build:watch": "cross-env NODE_ENV=development rollup --config rollup.config.js --watch --sourcemap inline",
"build:watch": "cross-env NODE_ENV=development rollup --config rollup.config.js --sourcemap inline --watch",
"build:dev": "cross-env NODE_ENV=development rollup --config rollup.config.js --sourcemap inline",
"build": "cross-env NODE_ENV=production rollup --config rollup.config.js",
"test": "ava",
Expand Down
15 changes: 15 additions & 0 deletions src/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,18 @@ test('returns false when missing IDAT', (t) => {
),
)
})

test('chunks should be found when preceded by a partial of themselves', (t) => {
t.true(
isApng(
new Uint8Array([
// PNG header
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
// a acTL
0x61, 0x61, 0x63, 0x54, 0x4c,
// I IDAT
0x49, 0x49, 0x44, 0x41, 0x54,
]),
),
)
})
19 changes: 13 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,22 +39,29 @@ export default function isApng(buffer: Buffer | Uint8Array): boolean {
let firstIndex = 0
let secondIndex = 0
for (let i = 0; i < buffer.length; i++) {
if (buffer[i] === sequences.animationControlChunk[firstIndex]) {
if (
!foundFirst &&
(buffer[i] === sequences.animationControlChunk[firstIndex] ||
(firstIndex > 0 &&
((firstIndex = 0) ||
buffer[i] === sequences.animationControlChunk[firstIndex])))
) {
firstIndex++
if (firstIndex === sequences.animationControlChunk.length) {
foundFirst = true
}
} else {
firstIndex = 0
}

if (buffer[i] === sequences.imageDataChunk[secondIndex]) {
if (
buffer[i] === sequences.imageDataChunk[secondIndex] ||
(secondIndex > 0 &&
((secondIndex = 0) ||
buffer[i] === sequences.imageDataChunk[secondIndex]))
) {
secondIndex++
if (secondIndex === sequences.imageDataChunk.length) {
return foundFirst
}
} else {
secondIndex = 0
}
}

Expand Down

0 comments on commit 28d27c2

Please sign in to comment.