1/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
2/*
3 *     Copyright 2016 Couchbase, Inc
4 *
5 *   Licensed under the Apache License, Version 2.0 (the "License");
6 *   you may not use this file except in compliance with the License.
7 *   You may obtain a copy of the License at
8 *
9 *       http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *   Unless required by applicable law or agreed to in writing, software
12 *   distributed under the License is distributed on an "AS IS" BASIS,
13 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *   See the License for the specific language governing permissions and
15 *   limitations under the License.
16 */
17
18#include <gtest/gtest.h>
19#include <platform/ring_buffer.h>
20#include <vector>
21
22using cb::RingBuffer;
23using cb::RingBufferVector;
24
25// Wrapper class that gives us a 'fixed' 10-element ring buffer.
26template <typename T>
27class TestRingBufferVector : public RingBufferVector<T> {
28public:
29    TestRingBufferVector<T>() : RingBufferVector<T>(10) {
30    }
31    void reset() {
32        RingBufferVector<T>::reset(10);
33    }
34};
35
36template <typename T>
37class RingBufferTest : public ::testing::Test {
38public:
39    typedef T RingBufferType;
40};
41
42typedef ::testing::Types<RingBuffer<int, 10>, TestRingBufferVector<int>>
43    MyTypes;
44TYPED_TEST_CASE(RingBufferTest, MyTypes);
45
46TYPED_TEST(RingBufferTest, testRingBuffer) {
47    TypeParam rb;
48    ASSERT_EQ(10u, rb.size());
49    for (int i = 0; i < 10; ++i) {
50        ASSERT_EQ(0, rb[i]);
51    }
52
53    rb.push_back(42);
54    ASSERT_EQ(42, rb.back());
55    ASSERT_EQ(0, rb.front());
56    ASSERT_EQ(10u, rb.size());
57
58    // Fill up the ring buffer
59    for (int i = 0; i < 10; i++) {
60        rb.push_back((i + 1) * 100);
61    }
62
63    // Test iteration
64    std::vector<int> nums;
65    for (auto num : rb) {
66        nums.push_back(num);
67    }
68    ASSERT_EQ(10u, nums.size());
69
70    // Test iteration on const values
71    std::vector<int> const_nums;
72    for (const auto& num : rb) {
73        const_nums.push_back(num);
74    }
75
76    for (int i = 0; i < 10; i++) {
77        int exp = (i + 1) * 100;
78        ASSERT_EQ(exp, nums[i]);
79        ASSERT_EQ(exp, const_nums[i]);
80    }
81
82    rb.reset();
83    for (auto num : rb) {
84        ASSERT_EQ(0, num);
85    }
86
87    for (int i = 0; i < 10; i++) {
88        rb.emplace_back(i + 1);
89    }
90
91    ASSERT_EQ(10u, rb.size());
92    for (size_t i = 0; i < rb.size(); ++i) {
93        ASSERT_EQ(int(i) + 1, rb[i]);
94    }
95}
96