writer_buffer.js
2.18 KB
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
77
78
79
80
81
"use strict";
module.exports = BufferWriter;
// extends Writer
var Writer = require("./writer");
(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;
var util = require("./util/minimal");
var Buffer = util.Buffer;
/**
* Constructs a new buffer writer instance.
* @classdesc Wire format writer using node buffers.
* @extends Writer
* @constructor
*/
function BufferWriter() {
Writer.call(this);
}
/**
* Allocates a buffer of the specified size.
* @param {number} size Buffer size
* @returns {Buffer} Buffer
*/
BufferWriter.alloc = function alloc_buffer(size) {
return (BufferWriter.alloc = util._Buffer_allocUnsafe)(size);
};
var writeBytesBuffer = Buffer && Buffer.prototype instanceof Uint8Array && Buffer.prototype.set.name === "set"
? function writeBytesBuffer_set(val, buf, pos) {
buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)
// also works for plain array values
}
/* istanbul ignore next */
: function writeBytesBuffer_copy(val, buf, pos) {
if (val.copy) // Buffer values
val.copy(buf, pos, 0, val.length);
else for (var i = 0; i < val.length;) // plain array values
buf[pos++] = val[i++];
};
/**
* @override
*/
BufferWriter.prototype.bytes = function write_bytes_buffer(value) {
if (util.isString(value))
value = util._Buffer_from(value, "base64");
var len = value.length >>> 0;
this.uint32(len);
if (len)
this._push(writeBytesBuffer, len, value);
return this;
};
function writeStringBuffer(val, buf, pos) {
if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)
util.utf8.write(val, buf, pos);
else
buf.utf8Write(val, pos);
}
/**
* @override
*/
BufferWriter.prototype.string = function write_string_buffer(value) {
var len = Buffer.byteLength(value);
this.uint32(len);
if (len)
this._push(writeStringBuffer, len, value);
return this;
};
/**
* Finishes the write operation.
* @name BufferWriter#finish
* @function
* @returns {Buffer} Finished buffer
*/