1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-11-22 15:06:54 -05:00

feat(std/node): add buf.equals method (#6640)

This commit is contained in:
Marcos Casagrande 2020-07-06 00:01:36 +02:00 committed by GitHub
parent e4e80f20c2
commit 91767501e1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 50 additions and 0 deletions

View file

@ -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,

View file

@ -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`
);
},
});