1/*
2 * Copyright 2018-present Facebook, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#pragma once
18
19#include <cstddef>
20#include <vector>
21
22#include <folly/Function.h>
23
24namespace folly {
25namespace detail {
26
27/*
28 * This class represents a sliding window that can be used to track stats over
29 * time. Buckets are dropped and new ones are added with the slide() method.
30 * New buckets are created with the constructor function given at construction.
31 */
32template <typename BucketT>
33class SlidingWindow {
34 public:
35 SlidingWindow(Function<BucketT(void)> fn, size_t numBuckets);
36
37 SlidingWindow(SlidingWindow&& rhs);
38
39 std::vector<BucketT> get() const;
40
41 void set(size_t idx, BucketT bucket);
42
43 BucketT front() const;
44
45 /*
46 * Slides the SlidingWindow by nBuckets, inserting new buckets using the
47 * Function given during construction.
48 */
49 void slide(size_t nBuckets);
50
51 private:
52 Function<BucketT(void)> fn_;
53 std::vector<BucketT> buckets_;
54 size_t curHead_;
55};
56
57} // namespace detail
58} // namespace folly
59