Stack-based @nogc dynamic array

Mike Franklin slavo5150 at yahoo.com
Fri May 17 08:27:21 UTC 2019


On Thursday, 16 May 2019 at 12:16:26 UTC, Marco de Wild wrote:

> Or are there any tips to roll my own implementation?

I took a stab at it:

---
@nogc:
nothrow:
pure:

struct NoGcArray(size_t maxSize, T)
{
     private T[maxSize] _buffer;
     private T[] _slice;
     private size_t _frontIndex;

     size_t length() const
     {
         return _slice.length;
     }

     void opOpAssign(string op)(T element)
     {
         static if(op == "~")
         {
             _buffer[_frontIndex + length] = element;
             _slice = _buffer[_frontIndex..(length + 1)];
         }
         else
         {
             static assert(false, "Only concatenation supported");
         }
     }

     T opIndex(size_t index) const
     {
         return _slice[index];
     }

     T front() const
     {
         return _slice[0];
     }

     void popFront()
     {
         _frontIndex++;
         _slice = _slice[1..$];
     }

     bool empty() const
     {
         return _slice.length == 0;
     }
}

void main()
{
     import std.algorithm : sum, map;
     NoGcArray!(4, int) array;
     array ~= 420;
     array ~= 42;
     assert(array.map!(x => x*2).sum == 924);
}
---

Mike


More information about the Digitalmars-d-learn mailing list