diff --git a/std/node/buffer.ts b/std/node/buffer.ts index 9ec7c04ffb..0fc8be6f1f 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 4e6dc9afc5..2e0a8c176d 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` + ); + }, +});