Skip to content

Commit 1c07805

Browse files
committed
feat: add prepend method.
1 parent 1867530 commit 1c07805

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

src/dynamicBuffer.ts

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -753,6 +753,50 @@ export class DynamicBuffer {
753753
return this.buffer.subarray(0, this.length).map(callbackfn, thisArg);
754754
}
755755

756+
/**
757+
* Prepends string to this buffer according to the character encoding.
758+
*
759+
* ```js
760+
* const buf = new DynamicBuffer('world!');
761+
* buf.prepend('Hello ');
762+
* console.log(buf.toString());
763+
* // Hello world!
764+
* ```
765+
*
766+
* @param data String to write to buffer.
767+
* @param length Maximum number of bytes to write, default the length of string.
768+
* @param encoding The character encoding to use, default from buffer encoding.
769+
* @returns The number of bytes written.
770+
*/
771+
prepend(
772+
data: string,
773+
length?: number,
774+
encoding?: BufferEncoding,
775+
): number {
776+
if (typeof data !== 'string') {
777+
throw new TypeError('argument must be a string');
778+
}
779+
780+
let lengthToWrite = data.length || 0;
781+
if (length !== undefined && length >= 0 && length <= data.length) {
782+
lengthToWrite = length;
783+
}
784+
785+
if (lengthToWrite === 0) {
786+
return 0;
787+
}
788+
789+
this.ensureSize(lengthToWrite + this.used);
790+
791+
this.buffer?.copy(this.buffer, lengthToWrite, 0, this.used);
792+
793+
this.writeString(data, 0, lengthToWrite, encoding);
794+
795+
this.used += lengthToWrite;
796+
797+
return lengthToWrite;
798+
}
799+
756800
/**
757801
* Reads and returns a byte at the position `offset` in this buffer.
758802
*

0 commit comments

Comments
 (0)