-
Notifications
You must be signed in to change notification settings - Fork 153
/
Copy pathtoBuffer.js
77 lines (75 loc) · 2.75 KB
/
toBuffer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
* Returns a copy of the backing buffer that contains this ByteBuffer's contents. Contents are the bytes between
* {@link ByteBuffer#offset} and {@link ByteBuffer#limit}.
* @param {boolean=} forceCopy If `true` returns a copy, otherwise returns a view referencing the same memory if
* possible. Defaults to `false`
//? if (NODE) {
* @returns {!Buffer} Contents as a Buffer
//? } else {
* @returns {!ArrayBuffer} Contents as an ArrayBuffer
//? }
* @expose
*/
ByteBufferPrototype.toBuffer = function(forceCopy) {
var offset = this.offset,
limit = this.limit;
if (!this.noAssert) {
//? ASSERT_RANGE('offset', 'limit');
}
//? if (NODE) {
if (forceCopy) {
var buffer = Buffer.alloc(limit - offset);
this.buffer.copy(buffer, 0, offset, limit);
return buffer;
} else {
if (offset === 0 && limit === this.buffer.length)
return this.buffer;
else
return this.buffer.slice(offset, limit);
}
//? } else {
// NOTE: It's not possible to have another ArrayBuffer reference the same memory as the backing buffer. This is
// possible with Uint8Array#subarray only, but we have to return an ArrayBuffer by contract. So:
if (!forceCopy && offset === 0 && limit === this.buffer.byteLength)
return this.buffer;
if (offset === limit)
return EMPTY_BUFFER;
var buffer = new ArrayBuffer(limit - offset);
new Uint8Array(buffer).set(new Uint8Array(this.buffer).subarray(offset, limit), 0);
return buffer;
//? }
};
//? if (NODE) {
/**
* Returns a copy of the backing buffer compacted to contain this ByteBuffer's contents. Contents are the bytes between
* {@link ByteBuffer#offset} and {@link ByteBuffer#limit}.
* @returns {!ArrayBuffer} Contents as an ArrayBuffer
*/
ByteBufferPrototype.toArrayBuffer = function() {
var offset = this.offset,
limit = this.limit;
if (!this.noAssert) {
//? ASSERT_RANGE('offset', 'limit');
}
var ab = new ArrayBuffer(limit - offset);
if (memcpy) { // Fast
memcpy(ab, 0, this.buffer, offset, limit);
} else { // Slow
var dst = new Uint8Array(ab);
for (var i=offset; i<limit; ++i)
dst[i-offset] = this.buffer[i];
}
return ab;
};
//? } else {
/**
* Returns a raw buffer compacted to contain this ByteBuffer's contents. Contents are the bytes between
* {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. This is an alias of {@link ByteBuffer#toBuffer}.
* @function
* @param {boolean=} forceCopy If `true` returns a copy, otherwise returns a view referencing the same memory.
* Defaults to `false`
* @returns {!ArrayBuffer} Contents as an ArrayBuffer
* @expose
*/
ByteBufferPrototype.toArrayBuffer = ByteBufferPrototype.toBuffer;
//? }