1/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
2/*
3 *     Copyright 2017 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 "config.h"
19
20#include <platform/non_negative_counter.h>
21
22#include <gtest/gtest.h>
23
24TEST(NonNegativeCounterTest, Increment) {
25    cb::NonNegativeCounter<size_t> nnAtomic(1);
26    ASSERT_EQ(1u, nnAtomic);
27
28    EXPECT_EQ(2u, ++nnAtomic);
29    EXPECT_EQ(2u, nnAtomic++);
30    EXPECT_EQ(3u, nnAtomic);
31}
32
33TEST(NonNegativeCounterTest, Add) {
34    cb::NonNegativeCounter<size_t> nnAtomic(1);
35    ASSERT_EQ(1u, nnAtomic);
36
37    EXPECT_EQ(3u, nnAtomic += 2);
38    EXPECT_EQ(3u, nnAtomic.fetch_add(2));
39    EXPECT_EQ(5u, nnAtomic);
40}
41
42TEST(NonNegativeCounterTest, Decrement) {
43    cb::NonNegativeCounter<size_t> nnAtomic(2);
44    ASSERT_EQ(2u, nnAtomic);
45
46    EXPECT_EQ(1u, --nnAtomic);
47    EXPECT_EQ(1u, nnAtomic--);
48    EXPECT_EQ(0u, nnAtomic);
49}
50
51TEST(NonNegativeCounterTest, Subtract) {
52    cb::NonNegativeCounter<size_t> nnAtomic(4);
53    ASSERT_EQ(4u, nnAtomic);
54
55    EXPECT_EQ(2u, nnAtomic -= 2);
56    EXPECT_EQ(2u, nnAtomic.fetch_sub(2));
57    EXPECT_EQ(0u, nnAtomic);
58}
59
60// Test that a NonNegativeCounter will clamp to zero.
61TEST(NonNegativeCounterTest, ClampsToZero) {
62    cb::NonNegativeCounter<size_t, cb::ClampAtZeroUnderflowPolicy> nnAtomic(0);
63
64    EXPECT_EQ(0u, --nnAtomic);
65    EXPECT_EQ(0u, nnAtomic--);
66    EXPECT_EQ(0u, nnAtomic);
67
68    nnAtomic = 5;
69    EXPECT_EQ(5u, nnAtomic.fetch_sub(10)); // returns previous value
70    EXPECT_EQ(0u, nnAtomic); // has been clamped to zero
71}
72
73// Test the ThrowException policy.
74TEST(NonNegativeCounterTest, ThrowExceptionPolicy) {
75    cb::NonNegativeCounter<size_t, cb::ThrowExceptionUnderflowPolicy> nnAtomic(0);
76
77    EXPECT_THROW(--nnAtomic, std::underflow_error);
78    EXPECT_EQ(0u, nnAtomic);
79    EXPECT_THROW(nnAtomic--, std::underflow_error);
80    EXPECT_EQ(0u, nnAtomic);
81
82    nnAtomic = 1;
83    EXPECT_THROW(nnAtomic -= 2, std::underflow_error);
84    EXPECT_EQ(1u, nnAtomic);
85}
86