Skip to content

Commit f882ab8

Browse files
committed
containers: Implement queue's more correctly.
1 parent f3b8837 commit f882ab8

File tree

1 file changed

+25
-31
lines changed

1 file changed

+25
-31
lines changed

src/watt/containers/queue.volt

Lines changed: 25 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -26,41 +26,25 @@ private:
2626
mStore: T[32];
2727
mArr: T[];
2828
mLength: size_t;
29-
mInsert: size_t;
29+
mRear: size_t;
3030

3131
public:
3232
/*!
3333
* Add a value to become the back of the queue.
3434
*/
3535
fn enqueue(val: T)
3636
{
37-
newSize := mLength + 1;
3837
if (mArr.length == 0) {
3938
mArr = mStore[0 .. $];
40-
mInsert = mArr.length - 1;
4139
}
4240

43-
if (newSize <= mArr.length) {
44-
mLength++;
45-
mArr[mInsert--] = val;
46-
return;
41+
if (mLength + 1 > mArr.length) {
42+
resize();
4743
}
4844

49-
allocSize := mArr.length;
50-
while (allocSize < newSize) {
51-
if (allocSize >= MaxSize) {
52-
allocSize += MaxSize;
53-
} else {
54-
allocSize = allocSize * 2;
55-
}
56-
}
57-
58-
n := new T[](allocSize);
59-
n[$-mLength .. $] = mArr[0 .. mLength];
60-
mInsert += (n.length - mArr.length);
45+
mArr[(mRear+mLength) % $] = val;
6146
mLength++;
62-
n[mInsert--] = val;
63-
mArr = n;
47+
return;
6448
}
6549

6650
/*!
@@ -69,7 +53,8 @@ public:
6953
fn dequeue() T
7054
{
7155
assert(mArr.length > 0, "dequeue()ed an empty queue");
72-
T val = mArr[mInsert+mLength];
56+
T val = mArr[mRear];
57+
mRear = (mRear + 1) % mArr.length;
7358
mLength--;
7459
return val;
7560
}
@@ -80,7 +65,7 @@ public:
8065
fn peek() T
8166
{
8267
assert(mArr.length > 0, "peek()ed an empty queue");
83-
return mArr[mInsert+mLength];
68+
return mArr[mRear];
8469
}
8570

8671
/*!
@@ -90,16 +75,25 @@ public:
9075
{
9176
mArr = null;
9277
mLength = 0;
93-
mInsert = 0;
78+
mRear = 0;
9479
}
9580

96-
/*!
97-
* Unsafely get a reference to the underlying array.
98-
* Mutating this array may (or may not) impact the queue data structure.
99-
* Taking a copy and mutating *that* is recommended.
100-
*/
101-
fn borrowUnsafe() T[]
81+
private:
82+
fn resize()
10283
{
103-
return mArr[mInsert+1 .. mInsert+mLength+1];
84+
allocSize := mArr.length;
85+
while (allocSize < mLength + 1) {
86+
if (allocSize >= MaxSize) {
87+
allocSize += MaxSize;
88+
} else {
89+
allocSize = allocSize * 2;
90+
}
91+
}
92+
n := new T[](allocSize);
93+
for (k: size_t = 0; k < mLength; ++k) {
94+
n[k] = mArr[(mRear+k) % $];
95+
}
96+
mArr = n;
97+
mRear = 0;
10498
}
10599
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy