From ca64a4afc3ae948f4f1b725b05ef2ff7f96d958c Mon Sep 17 00:00:00 2001 From: Josh Wolfe Date: Sun, 20 Oct 2024 10:10:59 -0400 Subject: [PATCH] automatically use node:zlib.crc32 when available --- index.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/index.js b/index.js index 83b6847..a263e5a 100644 --- a/index.js +++ b/index.js @@ -54,16 +54,44 @@ function bufferizeInt(num) { } function _crc32(buf, previous) { + // Parameter validation and coercion. buf = ensureBuffer(buf); if (Buffer.isBuffer(previous)) { previous = previous.readUInt32BE(0); } + // Delegate to the implementation. + return _impl(buf, previous); +} + +function _jsImpl(buf, previous) { let crc = ~~previous ^ -1; for (var n = 0; n < buf.length; n++) { crc = CRC_TABLE[(crc ^ buf[n]) & 0xff] ^ (crc >>> 8); } return crc ^ -1; } +function _impl(buf, previous) { + // Returns a signed integer. + // After this function is called once, references to it are replaced by a different implementation. + + // Determine which implementation to use. + try { + var nodeCrc32 = require('node:zlib').crc32; + } catch (e) { + // Older versions of node don't support the `node:` prefix, + // and also don't have the crc32 implementation anyway. + } + if (typeof nodeCrc32 === 'function') { + // Use node implementation. + _impl = function _nodeImpl(buf, previous) { + // Node returns an unsigned integer. Coerce to signed. + return nodeCrc32(buf, previous) | 0; + }; + } else { + // Use JS implementation. + _impl = _jsImpl; + } +} function crc32() { return bufferizeInt(_crc32.apply(null, arguments));