Skip to content

Commit ec09d43

Browse files
committed
buffer: proof of concept that everything is possible
1 parent ab3306a commit ec09d43

File tree

1 file changed

+30
-17
lines changed

1 file changed

+30
-17
lines changed

lib/buffer.js

Lines changed: 30 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -8,20 +8,42 @@ const internalUtil = require('internal/util');
88

99
class FastBuffer extends Uint8Array {}
1010

11-
FastBuffer.prototype.constructor = Buffer;
12-
Buffer.prototype = FastBuffer.prototype;
11+
const kFromErrorMsg = 'First argument must be a string, Buffer, ' +
12+
'ArrayBuffer, Array, or array-like object.';
1313

14-
exports.Buffer = Buffer;
15-
exports.SlowBuffer = SlowBuffer;
1614
exports.INSPECT_MAX_BYTES = 50;
1715
exports.kMaxLength = binding.kMaxLength;
1816

19-
const kFromErrorMsg = 'First argument must be a string, Buffer, ' +
20-
'ArrayBuffer, Array, or array-like object.';
21-
2217
Buffer.poolSize = 8 * 1024;
2318
var poolSize, poolOffset, allocPool;
2419

20+
const BufferClass = ((BufferFn) => class Buffer extends FastBuffer {
21+
constructor(arg, encodingOrOffset, length) {
22+
let realbuf;
23+
24+
// Common case.
25+
if (typeof arg === 'number') {
26+
if (typeof encodingOrOffset === 'string') {
27+
throw new Error(
28+
'If encoding is specified then the first argument must be a string'
29+
);
30+
}
31+
realbuf = BufferFn.allocUnsafe(arg);
32+
} else {
33+
realbuf = BufferFn.from(arg, encodingOrOffset, length);
34+
}
35+
36+
super(realbuf.buffer, realbuf.byteOffset, realbuf.byteLength);
37+
}
38+
})(Buffer);
39+
40+
FastBuffer.prototype.constructor = Buffer;
41+
BufferClass.prototype.constructor = Buffer;
42+
Buffer.prototype = FastBuffer.prototype;
43+
44+
exports.Buffer = Buffer;
45+
exports.SlowBuffer = SlowBuffer;
46+
exports.BufferClass = BufferClass;
2547

2648
binding.setupBufferJS(Buffer.prototype, bindingObj);
2749

@@ -65,16 +87,7 @@ function alignPool() {
6587
* would ever actually be removed.
6688
**/
6789
function Buffer(arg, encodingOrOffset, length) {
68-
// Common case.
69-
if (typeof arg === 'number') {
70-
if (typeof encodingOrOffset === 'string') {
71-
throw new Error(
72-
'If encoding is specified then the first argument must be a string'
73-
);
74-
}
75-
return Buffer.allocUnsafe(arg);
76-
}
77-
return Buffer.from(arg, encodingOrOffset, length);
90+
return new BufferClass(arg, encodingOrOffset, length);
7891
}
7992

8093
/**

0 commit comments

Comments
 (0)