Implementing a cache

Jack Stouffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jul 3 11:40:41 PDT 2016


On Sunday, 3 July 2016 at 17:15:32 UTC, Lodovico Giaretta wrote:
> To avoid the ~= operator and reallocations of the cache array, 
> you could impose a max number of cache entries, preallocate the 
> array and use it as a circular buffer.

Here's a simple ring buffer I use, feel free to take it

struct RingBuffer (T, uint buffer_length = 10) {
     private T[buffer_length] buffer;
     private int lastIndex;

     @safe @nogc nothrow pure {
         this(const T initial_value) {
             this.lastIndex = 0;
             reset(initial_value);
         }

         void reset(const T value) {
             for (int i = 0; i < this.buffer.length; ++i) {
                 this.buffer[i] = value;
             }
         }

         void put(const T value) {
             this.buffer[this.lastIndex] = value; // store the new 
sample

             // advance the index and wrap it around
             this.lastIndex += 1;
             if (this.lastIndex >= buffer_length) {
                 this.lastIndex = 0;
             }
         }

         auto ref opIndex(size_t n) { return buffer[n]; }
         auto opSlice() { return buffer[]; }
         auto opAssign(T[] rhs)
         in
         {
             assert(rhs.length <= buffer.length);
         }
         body
         {
             reset();
             foreach (e; rhs)
             {
                 put(e);
             }
             return this;
          }
     }
}




More information about the Digitalmars-d-learn mailing list