Skip to content

Commit

Permalink
compare buffer bytes directly for faster detection
Browse files Browse the repository at this point in the history
Previously, in order to detect the type of the file, the buffer was
converted to ASCII strings and then compared to hard-coded strings. Now,
the bytes of the buffer are compared directly to hard-coded bytes, which
is more efficient.

    name                        old time/op  new time/op  delta
    Calipers/png-304x85         90.9µs ± 3%  85.6µs ± 3%   -5.85%  (p=0.008 n=5+5)
    Calipers/png-304x85-buffer  2.14µs ± 8%  1.29µs ± 3%  -39.67%  (p=0.008 n=5+5)
  • Loading branch information
mgartner committed Dec 6, 2020
1 parent f1e86a5 commit 06cffda
Showing 1 changed file with 18 additions and 7 deletions.
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
}

0 comments on commit 06cffda

Please sign in to comment.