added test for parsing CString

This commit is contained in:
brianc 2010-09-29 00:20:10 -05:00
parent a921d6c144
commit 9688d8947f
2 changed files with 35 additions and 18 deletions

View File

@ -46,27 +46,26 @@ Client.prototype.connect = function() {
};
var Parser = function() {
this.offset = 0;
};
var p = Parser.prototype;
p.parse = function(buffer, offset) {
offset = offset || 0;
switch(buffer[offset]) {
p.parse = function(buffer) {
switch(buffer[this.offset]) {
case UTF8.R:
return this.parseR(buffer, offset);
return this.parseR(buffer);
case UTF8.S:
return this.parseS(buffer, offset);
return this.parseS(buffer);
default:
throw new Error("Unsupported message ID");
}
};
p.parseR = function(buffer, offset) {
var type = buffer[offset++];
var length = this.parseLength(buffer, offset);
offset += 4;
p.parseR = function(buffer) {
var type = buffer[this.offset++];
var length = this.parseLength(buffer);
if(length == 8) {
return {
name: 'AuthenticationOk',
@ -76,11 +75,12 @@ p.parseR = function(buffer, offset) {
}
throw new Error("Unknown AuthenticatinOk message type");
};
p.parseS = function(buffer, offset) {
var type = buffer[offset++];
var length = this.parseLength(buffer, offset);
p.parseS = function(buffer) {
var offset = 0;
var type = buffer[this.offset++];
var length = this.parseLength(buffer,this.offset);
offset += 4;
var start = offset;
var start = this.offset;
while(buffer[offset++]) { }
var end = offset -1;
var parameterName = buffer.toString('utf8',start, end);
@ -97,14 +97,21 @@ p.parseS = function(buffer, offset) {
}
};
p.parseLength = function(buffer, offset) {
var length = ((buffer[offset++] << 24) +
(buffer[offset++] << 16) +
(buffer[offset++] << 8) +
buffer[offset++]);
p.parseLength = function(buffer) {
var length = ((buffer[this.offset++] << 24) +
(buffer[this.offset++] << 16) +
(buffer[this.offset++] << 8) +
buffer[this.offset++]);
return length;
};
p.parseCString = function(buffer) {
var start = this.offset;
while(buffer[this.offset++]) { };
var end = this.offset - 1;
return buffer.toString('utf8',start, end);
};
module.exports = {
Client: Client,

View File

@ -18,5 +18,15 @@ test('Parser on single messages', function() {
assert.equal(result.parameterName, "client_encoding");
assert.equal(result.parameterValue, "UTF8");
});
test('parses normal CString', function() {
var result = new Parser().parseCString(Buffer([33,00]));
assert.equal(result,"!");
});
test('parses empty CString', function() {
var result = new Parser().parseCString(Buffer([0]));
assert.equal(result, '');
});
});