Skip to content

Use static factories to create NodeJS buffers #351

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 12, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion src/v1/internal/buf.js
Original file line number Diff line number Diff line change
Expand Up @@ -511,7 +511,7 @@ class CombinedBuffer extends BaseBuffer {
*/
class NodeBuffer extends BaseBuffer {
constructor(arg) {
let buffer = arg instanceof _node.Buffer ? arg : new _node.Buffer(arg);
const buffer = arg instanceof _node.Buffer ? arg : newNodeJSBuffer(arg);
super(buffer.length);
this._buffer = buffer;
}
Expand Down Expand Up @@ -559,6 +559,16 @@ class NodeBuffer extends BaseBuffer {
}
}

function newNodeJSBuffer(arg) {
if (typeof arg === 'number' && typeof _node.Buffer.alloc === 'function') {
// use static factory function present in newer NodeJS versions to allocate new buffer with specified size
return _node.Buffer.alloc(arg);
} else {
// fallback to the old, potentially deprecated constructor
return new _node.Buffer(arg);
}
}

// Use HeapBuffer by default, unless Buffer API is available, see below
let _DefaultBuffer = HeapBuffer;
try {
Expand Down
15 changes: 11 additions & 4 deletions src/v1/internal/utf8.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,21 +20,28 @@
// This module defines a cross-platform UTF-8 encoder and decoder that works
// with the Buffer API defined in buf.js

import {alloc, NodeBuffer, HeapBuffer, CombinedBuffer} from "./buf";
import {alloc, CombinedBuffer, HeapBuffer, NodeBuffer} from './buf';
import {StringDecoder} from 'string_decoder';
import {newError} from './../error';

let platformObj = {};


try {
// This will throw an exception is 'buffer' is not available
require.resolve("buffer");
let decoder = new StringDecoder('utf8');
let node = require("buffer");
const decoder = new StringDecoder('utf8');
const node = require('buffer');

// use static factory function present in newer NodeJS versions to create a buffer containing the given string
// or fallback to the old, potentially deprecated constructor
const newNodeJSBuffer = typeof node.Buffer.from === 'function'
? str => node.Buffer.from(str, 'utf8')
: str => new node.Buffer(str, 'utf8');

platformObj = {
"encode": function (str) {
return new NodeBuffer(new node.Buffer(str, "UTF-8"));
return new NodeBuffer(newNodeJSBuffer(str));
},
"decode": function (buffer, length) {
if (buffer instanceof NodeBuffer) {
Expand Down