Debian Codegraph @

debian/rust-vendor/aws-lc-sys/aws-lc/crypto/refcount_test.cc

raw
1 // Copyright (c) 2015, Google Inc.
2 // SPDX-License-Identifier: ISC
3
4 #include "internal.h"
5
6 #include <gtest/gtest.h>
7
8 #if defined(OPENSSL_THREADS)
9 #include <thread>
10 #endif
11
12
13 TEST(RefCountTest, Basic) {
14 CRYPTO_refcount_t count = 0;
15
16 CRYPTO_refcount_inc(&count);
17 EXPECT_EQ(1u, count);
18
19 EXPECT_TRUE(CRYPTO_refcount_dec_and_test_zero(&count));
20 EXPECT_EQ(0u, count);
21
22 count = CRYPTO_REFCOUNT_MAX;
23 CRYPTO_refcount_inc(&count);
24 EXPECT_EQ(CRYPTO_REFCOUNT_MAX, count)
25 << "Count did not saturate correctly when incrementing.";
26 EXPECT_FALSE(CRYPTO_refcount_dec_and_test_zero(&count));
27 EXPECT_EQ(CRYPTO_REFCOUNT_MAX, count)
28 << "Count did not saturate correctly when decrementing.";
29
30 count = 2;
31 EXPECT_FALSE(CRYPTO_refcount_dec_and_test_zero(&count));
32 EXPECT_EQ(1u, count);
33 }
34
35 #if defined(OPENSSL_THREADS)
36 // This test is primarily intended to run under ThreadSanitizer.
37 TEST(RefCountTest, Threads) {
38 CRYPTO_refcount_t count = 0;
39
40 // Race two increments.
41 {
42 std::thread thread([&] { CRYPTO_refcount_inc(&count); });
43 CRYPTO_refcount_inc(&count);
44 thread.join();
45 EXPECT_EQ(2u, count);
46 }
47
48 // Race an increment with a decrement.
49 {
50 std::thread thread([&] { CRYPTO_refcount_inc(&count); });
51 EXPECT_FALSE(CRYPTO_refcount_dec_and_test_zero(&count));
52 thread.join();
53 EXPECT_EQ(2u, count);
54 }
55
56 // Race two decrements.
57 {
58 bool thread_saw_zero;
59 std::thread thread(
60 [&] { thread_saw_zero = CRYPTO_refcount_dec_and_test_zero(&count); });
61 bool saw_zero = CRYPTO_refcount_dec_and_test_zero(&count);
62 thread.join();
63 EXPECT_EQ(0u, count);
64 // Exactly one thread should see zero.
65 EXPECT_NE(saw_zero, thread_saw_zero);
66 }
67 }
68 #endif