TorchCraftAI
A bot for machine learning research on StarCraft: Brood War
circularbuffer.h
1 /*
2  * Copyright (c) 2017-present, Facebook, Inc.
3  *
4  * This source code is licensed under the MIT license found in the
5  * LICENSE file in the root directory of this source tree.
6  */
7 
8 #pragma once
9 
10 #include <algorithm>
11 #include <cstdlib>
12 
13 #ifdef WITHOUT_POSIX
14 #include <BaseTsd.h>
15 typedef SSIZE_T ssize_t;
16 #endif // WITHOUT_POSIX
17 
18 namespace common {
19 template <typename T>
21  public:
22  CircularBuffer(size_t capacity) : pos_(-1), size_(0), max_(capacity) {
23  buf_ = new T[capacity];
24  }
26  delete[] buf_;
27  }
28 
29  void push() {
30  pos_ = (pos_ + 1) % max_;
31  buf_[pos_] = T();
32  size_ = std::min(size_ + 1, max_);
33  }
34  void push(T const& value) {
35  pos_ = (pos_ + 1) % max_;
36  buf_[pos_] = value;
37  size_ = std::min(size_ + 1, max_);
38  }
39  void push(T& value) {
40  pos_ = (pos_ + 1) % max_;
41  buf_[pos_] = value;
42  size_ = std::min(size_ + 1, max_);
43  }
44 
45  size_t size() const {
46  return size_;
47  }
48 
49  // 0: get most recent element
50  // <0: get past elements
51  T const& at(ssize_t pos) const {
52  pos = (pos + pos_) % max_;
53  while (pos < 0) {
54  pos = max_ + pos;
55  }
56  return buf_[pos];
57  }
58  T& at(ssize_t pos) {
59  pos = (pos + pos_) % max_;
60  while (pos < 0) {
61  pos = max_ + pos;
62  }
63  return buf_[pos];
64  }
65 
66  private:
67  T* buf_;
68  /*
69  * max_ needs to be ssize_t for the module operator in at() to work correctly
70  * with negative positions (which looks like a nice API). _size is >= 0 but
71  * frequently compared to _max in std::min() which demands identical types for
72  * its arguments.
73  */
74  ssize_t pos_, size_, max_;
75 };
76 
77 } // namespace common
size_t size() const
Definition: circularbuffer.h:45
void push(T &value)
Definition: circularbuffer.h:39
void push(T const &value)
Definition: circularbuffer.h:34
~CircularBuffer()
Definition: circularbuffer.h:25
T & at(ssize_t pos)
Definition: circularbuffer.h:58
CircularBuffer(size_t capacity)
Definition: circularbuffer.h:22
General utilities.
Definition: assert.cpp:7
T const & at(ssize_t pos) const
Definition: circularbuffer.h:51
void push()
Definition: circularbuffer.h:29
Definition: circularbuffer.h:20