blob: 428a9e1fe27ea9bb46c316d7353338bd8e670b55 [file] [log] [blame]
Leo Repp58b9f112021-11-22 11:57:47 +01001/* Node.js 6.4.0 and up has full support */
2var hasFullSupport = (function () {
3 try {
4 if (!Buffer.isEncoding('latin1')) {
5 return false
6 }
7
8 var buf = Buffer.alloc ? Buffer.alloc(4) : new Buffer(4)
9
10 buf.fill('ab', 'ucs2')
11
12 return (buf.toString('hex') === '61006200')
13 } catch (_) {
14 return false
15 }
16}())
17
18function isSingleByte (val) {
19 return (val.length === 1 && val.charCodeAt(0) < 256)
20}
21
22function fillWithNumber (buffer, val, start, end) {
23 if (start < 0 || end > buffer.length) {
24 throw new RangeError('Out of range index')
25 }
26
27 start = start >>> 0
28 end = end === undefined ? buffer.length : end >>> 0
29
30 if (end > start) {
31 buffer.fill(val, start, end)
32 }
33
34 return buffer
35}
36
37function fillWithBuffer (buffer, val, start, end) {
38 if (start < 0 || end > buffer.length) {
39 throw new RangeError('Out of range index')
40 }
41
42 if (end <= start) {
43 return buffer
44 }
45
46 start = start >>> 0
47 end = end === undefined ? buffer.length : end >>> 0
48
49 var pos = start
50 var len = val.length
51 while (pos <= (end - len)) {
52 val.copy(buffer, pos)
53 pos += len
54 }
55
56 if (pos !== end) {
57 val.copy(buffer, pos, 0, end - pos)
58 }
59
60 return buffer
61}
62
63function fill (buffer, val, start, end, encoding) {
64 if (hasFullSupport) {
65 return buffer.fill(val, start, end, encoding)
66 }
67
68 if (typeof val === 'number') {
69 return fillWithNumber(buffer, val, start, end)
70 }
71
72 if (typeof val === 'string') {
73 if (typeof start === 'string') {
74 encoding = start
75 start = 0
76 end = buffer.length
77 } else if (typeof end === 'string') {
78 encoding = end
79 end = buffer.length
80 }
81
82 if (encoding !== undefined && typeof encoding !== 'string') {
83 throw new TypeError('encoding must be a string')
84 }
85
86 if (encoding === 'latin1') {
87 encoding = 'binary'
88 }
89
90 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
91 throw new TypeError('Unknown encoding: ' + encoding)
92 }
93
94 if (val === '') {
95 return fillWithNumber(buffer, 0, start, end)
96 }
97
98 if (isSingleByte(val)) {
99 return fillWithNumber(buffer, val.charCodeAt(0), start, end)
100 }
101
102 val = new Buffer(val, encoding)
103 }
104
105 if (Buffer.isBuffer(val)) {
106 return fillWithBuffer(buffer, val, start, end)
107 }
108
109 // Other values (e.g. undefined, boolean, object) results in zero-fill
110 return fillWithNumber(buffer, 0, start, end)
111}
112
113module.exports = fill