Skip to content

Commit 24bef3d

Browse files
committed
feat: add resize factor.
1 parent a7a454c commit 24bef3d

File tree

1 file changed

+13
-4
lines changed

1 file changed

+13
-4
lines changed

src/dynamicBuffer.ts

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ export interface DynamicBufferOptions {
2323
* Character encoding for `fill` if `fill` is a string, default 'utf8'.
2424
*/
2525
encoding?: BufferEncoding;
26+
27+
factor?: number;
2628
}
2729

2830
/**
@@ -45,6 +47,8 @@ export class DynamicBuffer {
4547
*/
4648
private readonly DefaultInitialSize: number = 16;
4749

50+
private readonly DefaultResizeFactor: number = 0.75;
51+
4852
/**
4953
* Internal buffer to stores data.
5054
*/
@@ -70,6 +74,8 @@ export class DynamicBuffer {
7074
*/
7175
private encoding?: BufferEncoding;
7276

77+
private factor: number;
78+
7379
constructor(options?: DynamicBufferOptions) {
7480
if (options?.size !== undefined) {
7581
this.size = options.size;
@@ -84,6 +90,11 @@ export class DynamicBuffer {
8490
this.used = 0;
8591
this.fill = options?.fill || 0;
8692
this.encoding = options?.encoding || 'utf8';
93+
this.factor = options?.factor || this.DefaultResizeFactor;
94+
95+
if (this.factor <= 0 || Number.isNaN(this.factor)) {
96+
throw new TypeError('Invalid factor');
97+
}
8798

8899
if (this.size > 0) {
89100
this.buffer = Buffer.alloc(this.size, this.fill, this.encoding);
@@ -626,10 +637,8 @@ export class DynamicBuffer {
626637
throw new Error('Buffer size is overflow');
627638
}
628639

629-
let newSize = this.size ? this.size * 2 : expectSize;
630-
while (newSize < expectSize) {
631-
newSize *= 2;
632-
}
640+
const sizeWithFactor = Math.ceil(this.size * (1 + this.factor));
641+
let newSize = expectSize > sizeWithFactor ? expectSize : sizeWithFactor;
633642

634643
if (newSize > constants.MAX_LENGTH) {
635644
newSize = constants.MAX_LENGTH;

0 commit comments

Comments
 (0)