Ion
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
circularbuffer.h
Go to the documentation of this file.
1 
18 #ifndef ION_BASE_CIRCULARBUFFER_H_
19 #define ION_BASE_CIRCULARBUFFER_H_
20 
23 
24 namespace ion {
25 namespace base {
26 
29 template<typename T>
31  public:
36  size_t capacity, const ion::base::AllocatorPtr& alloc, bool do_reserve);
37 
40  void AddItem(const T& item) {
43  if (buffer_.size() < capacity_) {
44  buffer_.push_back(item);
45  } else {
46  buffer_[next_pos_] = item;
47  }
48  next_pos_ = (next_pos_ + 1) % capacity_;
49  }
50 
53  const T& GetItem(size_t i) const {
54  DCHECK(i < buffer_.size());
55  DCHECK(i < capacity_);
56  if (buffer_.size() < capacity_) {
57  return buffer_[i];
58  } else {
59  size_t wrap_threshold = capacity_ - next_pos_;
60  if (i < wrap_threshold) {
61  return buffer_[i + next_pos_];
62  } else {
63  return buffer_[i - wrap_threshold];
64  }
65  }
66  }
67 
69  size_t GetSize() const { return std::min(buffer_.size(), capacity_); }
70 
72  size_t GetCapacity() const { return capacity_; }
73 
74  private:
76  const size_t capacity_;
77 
79  size_t next_pos_;
80 
83 };
84 
85 template<typename T>
87  size_t capacity, const ion::base::AllocatorPtr& alloc, bool do_reserve)
88  : capacity_(capacity), next_pos_(0), buffer_(alloc) {
89  if (do_reserve) {
91  buffer_.reserve(capacity_);
92  }
93 }
94 
95 } // namespace base
96 } // namespace ion
97 
98 #endif // ION_BASE_CIRCULARBUFFER_H_
size_t GetSize() const
Get the current number of items in the buffer.
Simple circular buffer class that has fixed capacity and does not grow automatically.
#define DCHECK(expr)
Definition: logging.h:331
Allocatable is an abstract base class for classes whose memory is managed by an Allocator.
Definition: allocatable.h:60
void AddItem(const T &item)
Add an item to the buffer.
const T & GetItem(size_t i) const
Return the item at position i.
size_t GetCapacity() const
Get the total capacity of the buffer.
CircularBuffer(size_t capacity, const ion::base::AllocatorPtr &alloc, bool do_reserve)
Create CircularBuffer with maximum size capacity allocated from alloc.
This class can be used in place of std::vector to allow an Ion Allocator to be used for memory alloca...
Definition: allocvector.h:50