summaryrefslogtreecommitdiff
path: root/std/node
diff options
context:
space:
mode:
authorMarcos Casagrande <marcoscvp90@gmail.com>2020-07-06 00:01:36 +0200
committerGitHub <noreply@github.com>2020-07-05 18:01:36 -0400
commit91767501e127a0de40d34d38bf769702fcb7c942 (patch)
treea1575991ed9194e6e519c939b816d5f13f4bbfe0 /std/node
parente4e80f20c2f85cfb9ea1ae1a499ac24fd206f99b (diff)
feat(std/node): add buf.equals method (#6640)
Diffstat (limited to 'std/node')
-rw-r--r--std/node/buffer.ts20
-rw-r--r--std/node/buffer_test.ts30
2 files changed, 50 insertions, 0 deletions
diff --git a/std/node/buffer.ts b/std/node/buffer.ts
index 9ec7c04ff..0fc8be6f1 100644
--- a/std/node/buffer.ts
+++ b/std/node/buffer.ts
@@ -200,6 +200,26 @@ export default class Buffer extends Uint8Array {
return sourceBuffer.length;
}
+ /*
+ * Returns true if both buf and otherBuffer have exactly the same bytes, false otherwise.
+ */
+ equals(otherBuffer: Uint8Array | Buffer): boolean {
+ if (!(otherBuffer instanceof Uint8Array)) {
+ throw new TypeError(
+ `The "otherBuffer" argument must be an instance of Buffer or Uint8Array. Received type ${typeof otherBuffer}`
+ );
+ }
+
+ if (this === otherBuffer) return true;
+ if (this.byteLength !== otherBuffer.byteLength) return false;
+
+ for (let i = 0; i < this.length; i++) {
+ if (this[i] !== otherBuffer[i]) return false;
+ }
+
+ return true;
+ }
+
readBigInt64BE(offset = 0): bigint {
return new DataView(
this.buffer,
diff --git a/std/node/buffer_test.ts b/std/node/buffer_test.ts
index 4e6dc9afc..2e0a8c176 100644
--- a/std/node/buffer_test.ts
+++ b/std/node/buffer_test.ts
@@ -518,3 +518,33 @@ Deno.test({
});
},
});
+
+// ported from:
+// https://github.com/nodejs/node/blob/56dbe466fdbc598baea3bfce289bf52b97b8b8f7/test/parallel/test-buffer-equals.js#L6
+Deno.test({
+ name: "buf.equals",
+ fn() {
+ const b = Buffer.from("abcdf");
+ const c = Buffer.from("abcdf");
+ const d = Buffer.from("abcde");
+ const e = Buffer.from("abcdef");
+
+ assertEquals(b.equals(c), true);
+ assertEquals(d.equals(d), true);
+ assertEquals(
+ d.equals(new Uint8Array([0x61, 0x62, 0x63, 0x64, 0x65])),
+ true
+ );
+
+ assertEquals(c.equals(d), false);
+ assertEquals(d.equals(e), false);
+
+ assertThrows(
+ // deno-lint-ignore ban-ts-comment
+ // @ts-ignore
+ () => Buffer.alloc(1).equals("abc"),
+ TypeError,
+ `The "otherBuffer" argument must be an instance of Buffer or Uint8Array. Received type string`
+ );
+ },
+});