summaryrefslogtreecommitdiff
path: root/std/node/buffer.ts
diff options
context:
space:
mode:
authorMarcos Casagrande <marcoscvp90@gmail.com>2020-06-27 21:56:39 +0200
committerGitHub <noreply@github.com>2020-06-27 15:56:39 -0400
commit4302941b06b51233b13cd1f7293a4f38e0ec8073 (patch)
treec59aa18b29af839931d12d8377e29e38b01409a2 /std/node/buffer.ts
parent0b28c80e9adbb67f5fa8ec782fb5bd1f7b56a21a (diff)
fix(std/node): add fill & encoding args to Buffer.alloc (#6526)
Diffstat (limited to 'std/node/buffer.ts')
-rw-r--r--std/node/buffer.ts49
1 files changed, 47 insertions, 2 deletions
diff --git a/std/node/buffer.ts b/std/node/buffer.ts
index b9b33be99..e74ece196 100644
--- a/std/node/buffer.ts
+++ b/std/node/buffer.ts
@@ -40,8 +40,53 @@ export default class Buffer extends Uint8Array {
/**
* Allocates a new Buffer of size bytes.
*/
- static alloc(size: number): Buffer {
- return new Buffer(size);
+ static alloc(
+ size: number,
+ fill?: number | string | Uint8Array | Buffer,
+ encoding = "utf8"
+ ): Buffer {
+ if (typeof size !== "number") {
+ throw new TypeError(
+ `The "size" argument must be of type number. Received type ${typeof size}`
+ );
+ }
+
+ const buf = new Buffer(size);
+ if (size === 0) return buf;
+
+ let bufFill;
+ if (typeof fill === "string") {
+ encoding = checkEncoding(encoding);
+ if (typeof fill === "string" && fill.length === 1 && encoding === "utf8")
+ buf.fill(fill.charCodeAt(0));
+ else bufFill = Buffer.from(fill, encoding);
+ } else if (typeof fill === "number") buf.fill(fill);
+ else if (fill instanceof Uint8Array) {
+ if (fill.length === 0) {
+ throw new TypeError(
+ `The argument "value" is invalid. Received ${fill.constructor.name} []`
+ );
+ }
+
+ bufFill = fill;
+ }
+
+ if (bufFill) {
+ if (bufFill.length > buf.length)
+ bufFill = bufFill.subarray(0, buf.length);
+
+ let offset = 0;
+ while (offset < size) {
+ buf.set(bufFill, offset);
+ offset += bufFill.length;
+ if (offset + bufFill.length >= size) break;
+ }
+ if (offset !== size) {
+ buf.set(bufFill.subarray(0, size - offset), offset);
+ }
+ }
+
+ return buf;
}
/**