Serenity Operating System
1/*
2 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 */
6
7#include <LibTest/TestCase.h>
8
9#include <AK/DeprecatedString.h>
10#include <AK/NonnullRefPtr.h>
11
12struct Object : public RefCounted<Object> {
13 int x;
14};
15
16TEST_CASE(basics)
17{
18 auto object = adopt_ref(*new Object);
19 EXPECT_EQ(object->ref_count(), 1u);
20 object->ref();
21 EXPECT_EQ(object->ref_count(), 2u);
22 object->unref();
23 EXPECT_EQ(object->ref_count(), 1u);
24
25 {
26 NonnullRefPtr another = object;
27 EXPECT_EQ(object->ref_count(), 2u);
28 }
29
30 EXPECT_EQ(object->ref_count(), 1u);
31}
32
33TEST_CASE(assign_reference)
34{
35 auto object = adopt_ref(*new Object);
36 EXPECT_EQ(object->ref_count(), 1u);
37 object = *object;
38 EXPECT_EQ(object->ref_count(), 1u);
39}
40
41TEST_CASE(assign_owner_of_self)
42{
43 struct Object : public RefCounted<Object> {
44 RefPtr<Object> parent;
45 };
46
47 auto parent = adopt_ref(*new Object);
48 auto child = adopt_ref(*new Object);
49 child->parent = move(parent);
50
51 child = *child->parent;
52 EXPECT_EQ(child->ref_count(), 1u);
53}
54
55TEST_CASE(swap_with_self)
56{
57 auto object = adopt_ref(*new Object);
58 swap(object, object);
59 EXPECT_EQ(object->ref_count(), 1u);
60}