-
Notifications
You must be signed in to change notification settings - Fork 0
/
bufferusercreator.js
53 lines (49 loc) · 1.67 KB
/
bufferusercreator.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
function createBufferUser(execlib, BufferUserBase, toBuffer) {
'use strict';
var lib = execlib.lib,
_LENBUFFSIZE = 4;
function BufferUser(buff, cursor) {
BufferUserBase.call(this, buff, cursor);
this.buflen = null;
}
lib.inherit(BufferUser, BufferUserBase);
BufferUser.prototype.destroy = function () {
this.buflen = null;
BufferUserBase.prototype.destroy.call(this);
};
BufferUser.prototype.init = function (buff, cursor) {
BufferUserBase.prototype.init.call(this, buff, cursor);
this.buflen = null;
};
BufferUser.prototype.use = function () {
if (!this.buflen && this.availableBytes()>_LENBUFFSIZE) {
this.buflen = this.buffer.readUInt32LE(this.cursor);
}
if (!this.buflen) {
return;
}
var neededbytes = this.buflen+_LENBUFFSIZE,
availablebytes = this.buffer.length-this.cursor,
ret;
//console.log('BufferUser needs', neededbytes, 'bytes');
if (neededbytes<=availablebytes) {
//console.log('slicing from', this.cursor, 'for', this.buflen, 'bytes on buffer of', this.buffer.length, 'bytes');
ret = this.buffer.slice(this.cursor+_LENBUFFSIZE, this.cursor+_LENBUFFSIZE+this.buflen);
//console.log('final result is', ret);
this.buflen = null;
this.cursor += neededbytes;
return ret;
}
};
BufferUser.prototype.neededBytes = function (buff) {
buff = toBuffer(buff);
return buff.length+_LENBUFFSIZE;
};
BufferUser.prototype.toBuffer = function (bufferitem, buffer) {
bufferitem = toBuffer(bufferitem);
buffer.writeUInt32LE(bufferitem.length, 0);
bufferitem.copy(buffer, _LENBUFFSIZE);
};
return BufferUser;
}
module.exports = createBufferUser;