From 53fb0e4b55f45a4a57ab96cf6a135065c409faa5 Mon Sep 17 00:00:00 2001 From: Joyee Cheung Date: Thu, 25 Apr 2024 19:26:29 +0200 Subject: [PATCH] zlib: expose zlib.crc32() This patch exposes the crc32() function from zlib to user-land. It computes a 32-bit Cyclic Redundancy Check checksum of `data`. If `value` is specified, it is used as the starting value of the checksum, otherwise, 0 is used as the starting value. ```js const zlib = require('node:zlib'); const { Buffer } = require('node:buffer'); let crc = zlib.crc32('hello'); // 907060870 crc = zlib.crc32('world', crc); // 4192936109 crc = zlib.crc32(Buffer.from('hello')); // 907060870 crc = zlib.crc32(Buffer.from('world'), crc); // 4192936109 ``` --- doc/api/zlib.md | 39 ++++++ lib/zlib.js | 11 ++ src/node_zlib.cc | 30 +++++ test/parallel/test-zlib-crc32.js | 211 +++++++++++++++++++++++++++++++ 4 files changed, 291 insertions(+) create mode 100644 test/parallel/test-zlib-crc32.js diff --git a/doc/api/zlib.md b/doc/api/zlib.md index d5daa16a007f9f..95b4ecbe3c5fa9 100644 --- a/doc/api/zlib.md +++ b/doc/api/zlib.md @@ -712,6 +712,44 @@ The `zlib.bytesWritten` property specifies the number of bytes written to the engine, before the bytes are processed (compressed or decompressed, as appropriate for the derived class). +### `zlib.crc32(data[, value])` + + + +* `data` {string|Buffer|TypedArray|DataView} When `data` is a string, + it will be encoded as UTF-8 before being used for computation. +* `value` {integer} An optional starting value. It must be a 32-bit unsigned + integer. **Default:** `0` +* Returns: {integer} A 32-bit unsigned integer containing the checksum. + +Computes a 32-bit [Cyclic Redundancy Check][] checksum of `data`. If +`value` is specified, it is used as the starting value of the checksum, +otherwise, 0 is used as the starting value. + +```mjs +import zlib from 'node:zlib'; +import { Buffer } from 'node:buffer'; + +let crc = zlib.crc32('hello'); // 907060870 +crc = zlib.crc32('world', crc); // 4192936109 + +crc = zlib.crc32(Buffer.from('hello')); // 907060870 +crc = zlib.crc32(Buffer.from('world'), crc); // 4192936109 +``` + +```cjs +const zlib = require('node:zlib'); +const { Buffer } = require('node:buffer'); + +let crc = zlib.crc32('hello'); // 907060870 +crc = zlib.crc32('world', crc); // 4192936109 + +crc = zlib.crc32(Buffer.from('hello')); // 907060870 +crc = zlib.crc32(Buffer.from('world'), crc); // 4192936109 +``` + ### `zlib.close([callback])`