forked from jim-lake/node-postgres-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
buffer_reader.js
102 lines (98 loc) · 2.33 KB
/
buffer_reader.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
'use strict';
module.exports = BufferReader;
function BufferReader(buffer) {
if (this instanceof BufferReader) {
this._buffer = buffer;
this._offset = 0;
} else {
return new BufferReader(buffer);
}
return this;
}
BufferReader.prototype.readCString = function() {
const next_zero = this._buffer.indexOf(0,this._offset);
let ret;
if (next_zero == this._offset) {
ret = "";
this._offset++;
} else if (next_zero > this._offset) {
ret = this._buffer.toString('utf8',this._offset,next_zero);
this._offset = next_zero + 1;
}
return ret;
};
BufferReader.prototype.readChar = function() {
const byte = this.readByte();
let ret;
if (byte !== undefined) {
ret = String.fromCharCode(byte);
}
return ret;
};
BufferReader.prototype.readByte = function() {
let ret;
if (this.hasBytesAvailable(1)) {
ret = this._buffer.readUInt8(this._offset++);
}
return ret;
};
BufferReader.prototype.readInt16 = function() {
let ret;
if (this.hasBytesAvailable(2)) {
ret = this._buffer.readInt16BE(this._offset);
this._offset += 2;
}
return ret;
};
BufferReader.prototype.readInt32 = function() {
let ret;
if (this.hasBytesAvailable(4)) {
ret = this._buffer.readInt32BE(this._offset);
this._offset += 4;
}
return ret;
};
BufferReader.prototype.readPString = function() {
const len = this.readInt32();
let ret;
if (len == -1) {
ret = null;
} else if (len == 0) {
ret = "";
} else if (len > 0) {
ret = this._buffer.toString('utf8',this._offset,this._offset + len)
this._offset += len;
}
return ret;
};
BufferReader.prototype.readInt16List = function(count) {
let ret = [];
for (let i = 0 ; i < count ; i++) {
ret.push(this.readInt16());
}
return ret;
};
BufferReader.prototype.readInt16List = function(count) {
let ret = [];
for (let i = 0 ; i < count ; i++) {
ret.push(this.readInt16());
}
return ret;
};
BufferReader.prototype.readInt32List = function(count) {
let ret = [];
for (let i = 0 ; i < count ; i++) {
ret.push(this.readInt32());
}
return ret;
};
BufferReader.prototype.readPStringList = function(count) {
let ret = [];
for (let i = 0 ; i < count ; i++) {
ret.push(this.readPString());
}
return ret;
};
BufferReader.prototype.hasBytesAvailable = function(num) {
return this._offset + num <= this._buffer.length;
};