Skip to content

Commit 1461786

Browse files
committed
Fix buffer overflow
1 parent d6b5c3e commit 1461786

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

JavaScript/4-unrolled.js

+8-2
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@ class QueueNode {
1111
}
1212

1313
enqueue(item) {
14-
if (this.length === this.size) return false;
14+
if (this.length === this.size || this.writeIndex >= this.size) {
15+
return false;
16+
}
1517
this.buffer[this.writeIndex++] = item;
1618
this.length++;
1719
return true;
@@ -21,6 +23,10 @@ class QueueNode {
2123
if (this.length === 0) return null;
2224
const item = this.buffer[this.readIndex++];
2325
this.length--;
26+
if (this.length === 0) {
27+
this.readIndex = 0;
28+
this.writeIndex = 0;
29+
}
2430
return item;
2531
}
2632
}
@@ -34,7 +40,7 @@ class UnrolledQueue {
3440
constructor(options = {}) {
3541
const { nodeSize } = options;
3642
if (nodeSize) this.#nodeSize = nodeSize;
37-
const node = new QueueNode({ size: nodeSize });
43+
const node = new QueueNode({ size: this.#nodeSize });
3844
this.#head = node;
3945
this.#tail = node;
4046
}

TypeScript/queue.js

+8-2
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@ class QueueNode {
1111
}
1212

1313
enqueue(item) {
14-
if (this.length === this.size) return false;
14+
if (this.length === this.size || this.writeIndex >= this.size) {
15+
return false;
16+
}
1517
this.buffer[this.writeIndex++] = item;
1618
this.length++;
1719
return true;
@@ -21,6 +23,10 @@ class QueueNode {
2123
if (this.length === 0) return null;
2224
const item = this.buffer[this.readIndex++];
2325
this.length--;
26+
if (this.length === 0) {
27+
this.readIndex = 0;
28+
this.writeIndex = 0;
29+
}
2430
return item;
2531
}
2632
}
@@ -34,7 +40,7 @@ class UnrolledQueue {
3440
constructor(options = {}) {
3541
const { nodeSize } = options;
3642
if (nodeSize) this.#nodeSize = nodeSize;
37-
const node = new QueueNode({ size: nodeSize });
43+
const node = new QueueNode({ size: this.#nodeSize });
3844
this.#head = node;
3945
this.#tail = node;
4046
}

0 commit comments

Comments
 (0)