# How do I implement a deque in Solidity?

I have an array of finite size, say something like `uint[100] Arr;`.

My question is, if I want to continually push to this array, what happens if it already has 100 uints in it and I push another one? Will I crash? Or will it automatically pop out the first element?

If it does not pop out the first element, am I okay to do something like this:

``````if (Arr.length == 100) {
delete Arr[0];
}
Arr.push(new_uint);
``````

You can't `push` to an array of fixed size. (The code you wrote above would not compile.)

`push` modifies an array's size, so it's an operation that doesn't make sense for a fixed-size array. It only exists for dynamic arrays.

UPDATE

I believe that `delete Arr[0]` is equivalent to `Arr[0] = 0`, so it's also not doing anything useful for you.

If you explain what you're trying to do, perhaps people can help more. (It looks like you're trying to implement a deque using a fixed-size array? But what is supposed to happen when you run out of space?)

UPDATE 2

Per the comments, it sounds like you just want a regular circular buffer.

Untested, but I believe this should work:

``````pragma solidity ^0.4.17;

contract CircularBuffer {
uint[100] Arr;

// Represents the index in the array of the oldest element
uint8 start;

// Represents the next position to write to
uint8 end;

// Represents the size of the data (max of 100)
uint8 size;

function append(uint value) public {
Arr[end] = value;
end = (end + 1) % 100;

if (size < 100) {
size += 1;
} else {
// start was just overwritten
start = (start + 1) % 100;
}
}

function enumerate() public {
for (uint8 i = 0; i < size; i++) {
uint value = Arr[(start + i) % 100];
// do something with value here
}
}
}
``````
• In essence, I want to keep the last 100 records. I am trying to implement a deque with a maximum length of elements. So when that length is reached, the oldest element is popped. I guess it doesn't need to be a deque because I don't intend to pop from the other side. But hopefully that makes sense. Commented Sep 25, 2017 at 17:44
• @Wapiti Yeah, sounds like a regular circular buffer will do. See my edit. Commented Sep 25, 2017 at 20:22
• Wow, that is cool! It destroys the ordering of the records within the array but I can always get them in their temporal order because of the start index. Thanks;) Commented Sep 25, 2017 at 21:09
• The `enumerate` function enumerates them in the correct order. Commented Sep 25, 2017 at 21:47
• Yes, I saw that. I take it this is a standard data structure? I have not heard of it before. Commented Sep 25, 2017 at 22:00