RingBuffer.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. * Not Thread Safe !
  3. */
  4. #pragma once
  5. #include <stddef.h>
  6. class Filler
  7. {
  8. public:
  9. virtual size_t Read(void *dest, size_t len)=0;
  10. };
  11. class Drainer
  12. {
  13. public:
  14. virtual size_t Write(const void *dest, size_t len)=0;
  15. };
  16. class RingBuffer
  17. {
  18. public:
  19. RingBuffer();
  20. ~RingBuffer();
  21. void Reset();
  22. bool reserve( size_t bytes ); // destructive.
  23. int expand( size_t bytes ); // like reserve, but only expands upward. non-destructive. returns an NError
  24. bool empty() const;
  25. size_t avail() const; // how much available for writing
  26. size_t size() const; // how much available for reading
  27. void clear();
  28. size_t read( void *dest, size_t len ); // returns amount actually read
  29. size_t advance( size_t len ); // same as read() but doesn't write the data any where.
  30. size_t peek( void *dest, size_t len ) const; // same as read() but doesn't advance the read pointer
  31. size_t write( const void *src, size_t len );
  32. size_t fill( Filler *filler, size_t max_bytes );
  33. size_t drain( Drainer *drainer, size_t max_bytes );
  34. size_t at( size_t offset, void *dest, size_t len ) const; // peeks() from offset. returns bytes read
  35. size_t write_position() const; // returns an integer representing a write position
  36. size_t read_position() const; // returns an integer representing the read position
  37. void get_read_buffer( size_t bytes, const void **buffer, size_t *bytes_available ) const; /* returns a pointer that you can read data from, call advance() when you are done */
  38. /* DO NOT USING THIS UNLESS YOU KNOW WHAT YOU'RE DOING
  39. you should only use it when the ring buffer is empty
  40. 1) call clear() beforehand - very important!
  41. 2) call LockBuffer(), it'll give you a buffer
  42. 3) call UnlockBufer() with how much you've written
  43. 4) you catch the man
  44. */
  45. void *LockBuffer();
  46. void UnlockBuffer( size_t written );
  47. private:
  48. volatile size_t ringBufferUsed;
  49. size_t ringBufferSize;
  50. char *ringBuffer;
  51. char *ringWritePosition;
  52. char *ringReadPosition;
  53. };