blob: 36f34a11705a554aec1ecf663332c530311abc86 [file] [log] [blame]
Adedeji Adebisi12c5f112021-07-22 18:07:52 +00001// Copyright 2021 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#pragma once
16
17#include <stdio.h>
18
19#include <vector>
20
21template <typename ValueType>
22class BarGraph
23{
24 public:
25 std::vector<ValueType> history_; // is actually a ring buffer.
26 int next_; // index to the slot where the next insertion will go
27 int length_; // total # of data points that have ever been added
28 explicit BarGraph(int capacity) : next_(0), length_(0)
29 {
30 history_.resize(capacity);
31 std::fill(history_.begin(), history_.end(), 0);
32 }
33
34 // The last value is in [0], so on and so forth
35 // Note: if there are not enough data, this function will return as much
36 // as is available
37 std::vector<float> GetLastNValues(int x)
38 {
39 std::vector<float> ret;
40 const int N = static_cast<int>(history_.size());
41 int imax = x;
42 imax = std::min(imax, length_);
43 imax = std::min(imax, N);
44 int idx = (next_ - 1 + N) % N;
45 for (int i = 0; i < imax; i++)
46 {
47 ret.push_back(history_[idx]);
48 idx = (idx - 1 + N) % N;
49 }
50 return ret;
51 }
52
53 void AddValue(ValueType x)
54 {
55 history_[next_] = x;
56 next_ = (next_ + 1) % history_.size();
57 length_++;
58 }
59};