Skip to content

Commit 5643e52

Browse files
author
Michael Hayes
committed
cleanup buffer copy size logic
1 parent f9d54bc commit 5643e52

1 file changed

Lines changed: 18 additions & 10 deletions

File tree

jsonparse.js

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ proto.charError = function (buffer, i) {
8989
this.onError(new Error("Unexpected " + JSON.stringify(String.fromCharCode(buffer[i])) + " at position " + i + " in state " + Parser.toknam(this.tState)));
9090
};
9191
proto.appendStringChar = function (char) {
92-
if (this.stringBufferOffset === STRING_BUFFER_SIZE) {
92+
if (this.stringBufferOffset >= STRING_BUFFER_SIZE) {
9393
this.string += this.stringBuffer.toString('utf8');
9494
this.stringBufferOffset = 0;
9595
}
@@ -98,13 +98,21 @@ proto.appendStringChar = function (char) {
9898
};
9999
proto.appendStringBuf = function (buf, start, end) {
100100
var size = buf.length;
101-
if (end < 0) {
102-
size += end ;// add a negative to subtract
103-
} else if (end) {
104-
size = end;
101+
if (typeof start === 'number') {
102+
if (typeof end === 'number') {
103+
if (end < 0) {
104+
// adding a negative end decreeses the size
105+
size = buf.length - start + end;
106+
} else {
107+
size = end - start;
108+
}
109+
} else {
110+
size = buf.length - start;
111+
}
105112
}
106-
if (start) {
107-
size -= start;
113+
114+
if (size < 0) {
115+
size = 0;
108116
}
109117

110118
if (this.stringBufferOffset + size > STRING_BUFFER_SIZE) {
@@ -154,7 +162,7 @@ proto.write = function (buffer) {
154162
this.temp_buffs[this.bytes_in_sequence][this.bytes_in_sequence - this.bytes_remaining + j] = buffer[j];
155163
}
156164

157-
this.appendStringBuf(this.temp_buffs[this.bytes_in_sequence])
165+
this.appendStringBuf(this.temp_buffs[this.bytes_in_sequence]);
158166
this.bytes_in_sequence = this.bytes_remaining = 0;
159167
i = i + j - 1;
160168
} else if (this.bytes_remaining === 0 && n >= 128) { // else if no remainder bytes carried over, parse multi byte (>=128) chars one at a time
@@ -171,7 +179,7 @@ proto.write = function (buffer) {
171179
this.bytes_remaining = (i + this.bytes_in_sequence) - buffer.length;
172180
i = buffer.length - 1;
173181
} else {
174-
this.appendStringBuf(buffer, i, i + this.bytes_in_sequence)
182+
this.appendStringBuf(buffer, i, i + this.bytes_in_sequence);
175183
i = i + this.bytes_in_sequence - 1;
176184
}
177185
} else if (n === 0x22) {
@@ -185,7 +193,7 @@ proto.write = function (buffer) {
185193
else if (n === 0x5c) {
186194
this.tState = STRING2;
187195
}
188-
else if (n >= 0x20) { this.appendStringChar(n) }
196+
else if (n >= 0x20) { this.appendStringChar(n); }
189197
else {
190198
return this.charError(buffer, i);
191199
}

0 commit comments

Comments
 (0)