Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Authors: Felix Hufnagel
- * Copyright: Copyright 2011 Felix Hufnagel
- * License: The BSD 3-Clause License, http://www.opensource.org/licenses/BSD-3-Clause
- */
- module util.ringbuffer;
- class Ringbuffer(T)
- {
- public:
- this(size_t size)
- {
- this._buffer.length = size;
- }
- this(Ringbuffer!T t)
- {
- this._buffer = t._buffer;
- }
- void resize(size_t size)
- {
- this._buffer = this._buffer[this.pos..$] ~ this._buffer[0..this.pos];
- this._buffer.length = size;
- this.pos = 0;
- }
- void push(T t)
- {
- this._buffer[this.pos] = t;
- ++this.pos;
- if(this.pos > this._buffer.length-1)
- this.pos = 0;
- }
- void opCatAssign(T t)
- {
- this.push(t);
- }
- T opIndex(size_t i1)
- {
- return _buffer[i1];
- }
- @property T[] dup()
- {
- return this._buffer[this.pos..$] ~ this._buffer[0..this.pos];
- }
- @property size_t length(){ return this._buffer.length; }
- int opApply(int delegate(ref T) dg)
- {
- int result = 0;
- foreach(i;this._buffer)
- {
- result = dg(i);
- if(result)
- break;
- }
- return result;
- }
- private:
- T[] _buffer;
- size_t pos=0;
- }
- import std.stdio;
- unittest
- {
- auto rb = new Ringbuffer!float(10);
- foreach(i; 0..100)
- {
- rb.push(i);
- }
- uint counter;
- foreach(val; rb.dup)
- {
- counter++;
- }
- assert(rb.length == 10);
- assert(counter == 10);
- foreach(float i; rb)
- {
- writeln(i);
- }
- delete rb;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement