forked from protobufjs/bytebuffer.js
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbinary.js
74 lines (71 loc) · 2.26 KB
/
binary.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
//? if (BINARY) {
// encodings/binary
/**
* Encodes this ByteBuffer to a binary encoded string, that is using only characters 0x00-0xFF as bytes.
* @param {number=} begin Offset to begin at. Defaults to {@link ByteBuffer#offset}.
* @param {number=} end Offset to end at. Defaults to {@link ByteBuffer#limit}.
* @returns {string} Binary encoded string
* @throws {RangeError} If `offset > limit`
* @expose
*/
ByteBufferPrototype.toBinary = function(begin, end) {
if (typeof begin === 'undefined')
begin = this.offset;
if (typeof end === 'undefined')
end = this.limit;
begin |= 0; end |= 0;
if (begin < 0 || end > this.capacity() || begin > end)
throw RangeError("begin, end");
//? if (NODE)
return this.buffer.toString("binary", begin, end);
//? else {
if (begin === end)
return "";
var chars = [],
parts = [];
while (begin < end) {
//? if (NODE)
chars.push(this.buffer[begin++]);
//? else if (DATAVIEW)
chars.push(this.view.getUint8(begin++));
//? else
chars.push(this.view[begin++]);
if (chars.length >= 1024)
parts.push(String.fromCharCode.apply(String, chars)),
chars = [];
}
return parts.join('') + String.fromCharCode.apply(String, chars);
//? }
};
/**
* Decodes a binary encoded string, that is using only characters 0x00-0xFF as bytes, to a ByteBuffer.
* @param {string} str String to decode
* @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
* {@link ByteBuffer.DEFAULT_ENDIAN}.
* @returns {!ByteBuffer} ByteBuffer
* @expose
*/
ByteBuffer.fromBinary = function(str, littleEndian) {
//? if (NODE) {
return ByteBuffer.wrap(Buffer.from(str, "binary"), littleEndian);
//? } else {
if (typeof str !== 'string')
throw TypeError("str");
var i = 0,
k = str.length,
charCode,
bb = new ByteBuffer(k, littleEndian);
while (i<k) {
charCode = str.charCodeAt(i);
if (charCode > 0xff)
throw RangeError("illegal char code: "+charCode);
//? if (DATAVIEW)
bb.view.setUint8(i++, charCode);
//? else
bb.view[i++] = charCode;
}
bb.limit = k;
//? }
return bb;
};
//? }