-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathtri_state_ptr_test.cc
More file actions
80 lines (66 loc) · 2.34 KB
/
tri_state_ptr_test.cc
File metadata and controls
80 lines (66 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/* Copyright 2022 Google LLC. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "cpp/tri_state_ptr.h"
#include <utility>
#include "gtest/gtest.h"
#include "absl/synchronization/notification.h"
#include "cpp/common.h"
#include "cpp/thread_pool.h"
#include "riegeli/base/maker.h"
namespace array_record {
namespace {
class FooBase {
public:
virtual ~FooBase() = default;
virtual int value() const = 0;
virtual void add_value(int v) = 0;
virtual void mul_value(int v) = 0;
};
class Foo : public FooBase {
public:
explicit Foo(int v) : value_(v) {}
DECLARE_MOVE_ONLY_CLASS(Foo);
int value() const override { return value_; };
void add_value(int v) override { value_ += v; }
void mul_value(int v) override { value_ *= v; }
private:
int value_;
};
class TriStatePtrTest : public testing::Test {
public:
TriStatePtrTest() : pool_(ArrayRecordGlobalPool()) {}
protected:
ARThreadPool* pool_;
};
TEST_F(TriStatePtrTest, SanityTest) {
TriStatePtr<FooBase> foo_main(std::move(riegeli::Maker<Foo>(1)));
EXPECT_EQ(foo_main.state(), TriStatePtr<FooBase>::State::kNoRef);
absl::Notification notification;
{
pool_->Schedule(
[foo_shared = foo_main.MakeShared(), ¬ification]() mutable {
notification.WaitForNotification();
EXPECT_EQ(foo_shared->value(), 1);
const auto second_foo_shared = foo_shared;
foo_shared->add_value(1);
EXPECT_EQ(second_foo_shared->value(), 2);
});
}
EXPECT_EQ(foo_main.state(), TriStatePtr<FooBase>::State::kSharing);
notification.Notify();
auto foo_unique = foo_main.WaitAndMakeUnique();
foo_unique->mul_value(3);
EXPECT_EQ(foo_unique->value(), 6);
EXPECT_EQ(foo_main.state(), TriStatePtr<FooBase>::State::kUnique);
}
} // namespace
} // namespace array_record