Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

compare buffer bytes directly for faster detection #70

Merged
merged 2 commits into from
Dec 6, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions bench/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,10 @@ const ONE_BILLION = 1000000000

const fixtures = path.resolve(__dirname, '../test/fixtures')

// Load all PNG images in test/fixtures.
let files = fs.readdirSync(fixtures)
files = files.filter(function (f) { return f.endsWith('.png') })
// Specify the images in test/fixtures to use for benchmarking.
const files: string[] = [
'304x85.png'
]

// Create a benchmark for each image.
const benchmarks: any[] = []
Expand Down
25 changes: 18 additions & 7 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,14 +61,25 @@ function measurePNG (header: Buffer): Result {
// detect returns the file format of the given header buffer. Format.UNKNOWN is
// returned if the file type is not supported.
function detect (header: Buffer): Format {
if (ascii(header, 1, 8) === 'PNG\r\n\x1a\n' && ascii(header, 12, 16) === 'IHDR') {
// PNG
if (
// _PNG\r\n\x1a\n
header[0] === 0x89 &&
header[1] === 0x50 &&
header[2] === 0x4e &&
header[3] === 0x47 &&
header[4] === 0x0d &&
header[5] === 0x0a &&
header[6] === 0x1a &&
header[7] === 0x0a &&
// IHDR
header[12] === 0x49 &&
header[13] === 0x48 &&
header[14] === 0x44 &&
header[15] === 0x52
) {
return Format.PNG
}
return Format.UNKNOWN
}

// ascii returns an ASCII string represented by the bytes in b from the start to
// end indexes.
function ascii (b: Buffer, start: number, end: number): string {
return b.toString('ascii', start, end)
return Format.UNKNOWN
}