CircularBuffer.hh 1.57 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
#ifndef CircularBuffer_HH
#define CircularBuffer_HH

// Write pointer points to next location to write to
// Read pointer points to next location to read from

#include "MultipleUltraRam.hh"

template <unsigned NumberOfUltraRams>
class CircularBuffer {
public:
  enum {
    CircularBufferLength=NumberOfUltraRams*UltraRam::UltraRamBufferLength
  };

  CircularBuffer() {
    reset();
  }

  bool writeAndIncrementPtr(uint64_t d) {
    if(((fWritePtr+1)%CircularBufferLength)==fReadPtr) return false;

    fMultipleUltraRam.write(fWritePtr,d);
    fWritePtr++;
    if(fWritePtr>=CircularBufferLength) fWritePtr-=CircularBufferLength;

    return true;
  }

  bool read(uint64_t& d) const {
    if(fReadPtr==fWritePtr) return false;

    d=fMultipleUltraRam.read(fReadPtr);
    return true;
  }

  bool incrementReadPtr() {
    if(fReadPtr==fWritePtr) return false;

    fReadPtr++;
    if(fReadPtr>=CircularBufferLength) fReadPtr-=CircularBufferLength;
    
    return true;
  }

  bool readAndIncrementPtr(uint64_t& d) {
    if(!read(d)) return false;
    return incrementReadPtr();
  }

  unsigned space() const {
    if(fWritePtr<fReadPtr) return fReadPtr-fWritePtr-1;
    return fReadPtr+CircularBufferLength-fWritePtr-1;
  }

  unsigned used() const {
dauncey's avatar
dauncey committed
57
    if(fReadPtr<=fWritePtr) return fWritePtr-fReadPtr;
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
    return fWritePtr+CircularBufferLength-fReadPtr;
  }

  bool empty() const {
    return fWritePtr==fReadPtr;
  }
  
  void reset() {
    fWritePtr=0;
    fReadPtr=0;
  }

private:
  MultipleUltraRam<NumberOfUltraRams> fMultipleUltraRam;
  unsigned fWritePtr;
  unsigned fReadPtr;
};

#endif