@@ -26,41 +26,25 @@ private:
26
26
mStore: T[32 ];
27
27
mArr: T[];
28
28
mLength: size_t ;
29
- mInsert : size_t ;
29
+ mRear : size_t ;
30
30
31
31
public :
32
32
/* !
33
33
* Add a value to become the back of the queue.
34
34
*/
35
35
fn enqueue (val: T)
36
36
{
37
- newSize := mLength + 1 ;
38
37
if (mArr.length == 0 ) {
39
38
mArr = mStore[0 .. $];
40
- mInsert = mArr.length - 1 ;
41
39
}
42
40
43
- if (newSize <= mArr.length) {
44
- mLength++ ;
45
- mArr[mInsert-- ] = val;
46
- return ;
41
+ if (mLength + 1 > mArr.length) {
42
+ resize();
47
43
}
48
44
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;
61
46
mLength++ ;
62
- n[mInsert-- ] = val;
63
- mArr = n;
47
+ return ;
64
48
}
65
49
66
50
/* !
@@ -69,7 +53,8 @@ public:
69
53
fn dequeue () T
70
54
{
71
55
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;
73
58
mLength-- ;
74
59
return val;
75
60
}
@@ -80,7 +65,7 @@ public:
80
65
fn peek () T
81
66
{
82
67
assert (mArr.length > 0 , " peek()ed an empty queue" );
83
- return mArr[mInsert + mLength ];
68
+ return mArr[mRear ];
84
69
}
85
70
86
71
/* !
@@ -90,16 +75,25 @@ public:
90
75
{
91
76
mArr = null ;
92
77
mLength = 0 ;
93
- mInsert = 0 ;
78
+ mRear = 0 ;
94
79
}
95
80
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 ()
102
83
{
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 ;
104
98
}
105
99
}
0 commit comments