UNPKG

2.11 kBJavaScriptView Raw
1/* eslint-disable node/no-deprecated-api */
2
3'use strict'
4
5var buffer = require('buffer')
6var Buffer = buffer.Buffer
7
8var safer = {}
9
10var key
11
12for (key in buffer) {
13 if (!buffer.hasOwnProperty(key)) continue
14 if (key === 'SlowBuffer' || key === 'Buffer') continue
15 safer[key] = buffer[key]
16}
17
18var Safer = safer.Buffer = {}
19for (key in Buffer) {
20 if (!Buffer.hasOwnProperty(key)) continue
21 if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue
22 Safer[key] = Buffer[key]
23}
24
25safer.Buffer.prototype = Buffer.prototype
26
27if (!Safer.from || Safer.from === Uint8Array.from) {
28 Safer.from = function (value, encodingOrOffset, length) {
29 if (typeof value === 'number') {
30 throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value)
31 }
32 if (value && typeof value.length === 'undefined') {
33 throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value)
34 }
35 return Buffer(value, encodingOrOffset, length)
36 }
37}
38
39if (!Safer.alloc) {
40 Safer.alloc = function (size, fill, encoding) {
41 if (typeof size !== 'number') {
42 throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size)
43 }
44 if (size < 0 || size >= 2 * (1 << 30)) {
45 throw new RangeError('The value "' + size + '" is invalid for option "size"')
46 }
47 var buf = Buffer(size)
48 if (!fill || fill.length === 0) {
49 buf.fill(0)
50 } else if (typeof encoding === 'string') {
51 buf.fill(fill, encoding)
52 } else {
53 buf.fill(fill)
54 }
55 return buf
56 }
57}
58
59if (!safer.kStringMaxLength) {
60 try {
61 safer.kStringMaxLength = process.binding('buffer').kStringMaxLength
62 } catch (e) {
63 // we can't determine kStringMaxLength in environments where process.binding
64 // is unsupported, so let's not set it
65 }
66}
67
68if (!safer.constants) {
69 safer.constants = {
70 MAX_LENGTH: safer.kMaxLength
71 }
72 if (safer.kStringMaxLength) {
73 safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength
74 }
75}
76
77module.exports = safer