Advertisement
Zoadian

ringbuffer.d

Aug 31st, 2011
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.43 KB | None | 0 0
  1. /**
  2.  * Authors: Felix Hufnagel
  3.  * Copyright: Copyright 2011 Felix Hufnagel
  4.  * License: The BSD 3-Clause License, http://www.opensource.org/licenses/BSD-3-Clause
  5.  */
  6. module util.ringbuffer;
  7.  
  8. class Ringbuffer(T)
  9. {
  10. public:
  11.     this(size_t size)
  12.     {
  13.         this._buffer.length = size;
  14.     }
  15.    
  16.     this(Ringbuffer!T t)
  17.     {
  18.         this._buffer = t._buffer;
  19.     }
  20.    
  21.     void resize(size_t size)
  22.     {
  23.         this._buffer = this._buffer[this.pos..$] ~ this._buffer[0..this.pos];
  24.         this._buffer.length = size;
  25.         this.pos = 0;
  26.     }
  27.    
  28.     void push(T t)
  29.     {
  30.         this._buffer[this.pos] = t;
  31.         ++this.pos;
  32.         if(this.pos > this._buffer.length-1)
  33.             this.pos = 0;
  34.            
  35.     }
  36.    
  37.     void opCatAssign(T t)
  38.     {
  39.         this.push(t);
  40.     }
  41.    
  42.     T opIndex(size_t i1)
  43.     {
  44.         return _buffer[i1];
  45.     }
  46.    
  47.     @property T[] dup()
  48.     {      
  49.         return this._buffer[this.pos..$] ~ this._buffer[0..this.pos];
  50.     }
  51.    
  52.     @property size_t length(){ return this._buffer.length; }
  53.    
  54.    
  55.     int opApply(int delegate(ref T) dg)
  56.     {
  57.         int result = 0;
  58.         foreach(i;this._buffer)
  59.         {
  60.             result = dg(i);
  61.             if(result)
  62.                 break;
  63.         }
  64.         return result;
  65.     }
  66.    
  67.    
  68. private:   
  69.     T[] _buffer;
  70.     size_t pos=0;
  71. }
  72.  
  73.  
  74.  
  75.  
  76. import std.stdio;
  77. unittest
  78. {
  79.     auto rb = new Ringbuffer!float(10);
  80.     foreach(i; 0..100)
  81.     {
  82.         rb.push(i);
  83.     }
  84.    
  85.     uint counter;
  86.     foreach(val; rb.dup)
  87.     {
  88.         counter++;
  89.     }
  90.     assert(rb.length == 10);
  91.     assert(counter == 10);
  92.    
  93.     foreach(float i; rb)
  94.     {
  95.         writeln(i);
  96.     }
  97.    
  98.     delete rb;
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement