utils.h
Go to the documentation of this file.
1 /*
2  * Copyright 2015-2019 CNRS-UM LIRMM, CNRS-AIST JRL
3  */
4 
5 #pragma once
6 
7 #include <mc_rtc/logging.h>
8 
9 #include <atomic>
10 
11 namespace
12 {
13 
21 template<typename T, size_t Size>
22 struct CircularBuffer
23 {
24 public:
25  enum
26  {
27  Capacity = Size + 1
28  };
29 
30  CircularBuffer() : tail_(0), head_(0)
31  {
32  if(!tail_.is_lock_free())
33  {
34  mc_rtc::log::warning("Your platform does not support std::atomic_size_t as lock free operations");
35  }
36  }
37 
39  bool push(const T & item)
40  {
41  size_t tail = tail_;
42  auto next_tail = increment(tail);
43  if(next_tail != head_)
44  {
45  data_[tail] = item;
46  tail_ = next_tail;
47  return true;
48  }
49  return false;
50  }
51 
53  bool pop(T & item)
54  {
55  const size_t head = head_;
56  if(head == tail_) { return false; }
57  item = data_[head];
58  head_ = increment(head);
59  return true;
60  }
61 
63  bool empty() { return head_ == tail_; }
64 
65 private:
66  size_t increment(size_t idx) const { return (idx + 1) % Capacity; }
67 
68  T data_[Capacity];
69  std::atomic_size_t tail_;
70  std::atomic_size_t head_;
71 };
72 
73 } // namespace
mc_rtc::log::warning
void warning(Args &&... args)
Definition: logging.h:69
logging.h