2020-01-18 08:38:21 +00:00
|
|
|
/*
|
|
|
|
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
|
|
|
|
*
|
2021-04-22 08:24:48 +00:00
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
2020-01-18 08:38:21 +00:00
|
|
|
*/
|
|
|
|
|
2021-04-25 05:53:23 +00:00
|
|
|
#include <LibTest/TestCase.h>
|
2019-08-02 09:35:05 +00:00
|
|
|
|
|
|
|
#include <AK/NonnullRefPtr.h>
|
2019-09-06 13:34:26 +00:00
|
|
|
#include <AK/String.h>
|
2019-08-02 09:35:05 +00:00
|
|
|
|
|
|
|
struct Object : public RefCounted<Object> {
|
|
|
|
int x;
|
|
|
|
};
|
|
|
|
|
|
|
|
TEST_CASE(basics)
|
|
|
|
{
|
2021-04-23 14:46:57 +00:00
|
|
|
auto object = adopt_ref(*new Object);
|
2020-06-12 13:33:38 +00:00
|
|
|
EXPECT_EQ(object->ref_count(), 1u);
|
2019-08-02 09:35:05 +00:00
|
|
|
object->ref();
|
2020-06-12 13:33:38 +00:00
|
|
|
EXPECT_EQ(object->ref_count(), 2u);
|
2020-01-23 14:14:21 +00:00
|
|
|
object->unref();
|
2020-06-12 13:33:38 +00:00
|
|
|
EXPECT_EQ(object->ref_count(), 1u);
|
2019-08-02 09:35:05 +00:00
|
|
|
|
|
|
|
{
|
|
|
|
NonnullRefPtr another = object;
|
2020-06-12 13:33:38 +00:00
|
|
|
EXPECT_EQ(object->ref_count(), 2u);
|
2019-08-02 09:35:05 +00:00
|
|
|
}
|
|
|
|
|
2020-06-12 13:33:38 +00:00
|
|
|
EXPECT_EQ(object->ref_count(), 1u);
|
2019-08-02 09:35:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
TEST_CASE(assign_reference)
|
|
|
|
{
|
2021-04-23 14:46:57 +00:00
|
|
|
auto object = adopt_ref(*new Object);
|
2020-06-12 13:33:38 +00:00
|
|
|
EXPECT_EQ(object->ref_count(), 1u);
|
2019-08-02 09:35:05 +00:00
|
|
|
object = *object;
|
2020-06-12 13:33:38 +00:00
|
|
|
EXPECT_EQ(object->ref_count(), 1u);
|
2019-08-02 09:35:05 +00:00
|
|
|
}
|
|
|
|
|
2020-01-18 12:33:44 +00:00
|
|
|
TEST_CASE(assign_owner_of_self)
|
|
|
|
{
|
|
|
|
struct Object : public RefCounted<Object> {
|
|
|
|
RefPtr<Object> parent;
|
|
|
|
};
|
|
|
|
|
2021-04-23 14:46:57 +00:00
|
|
|
auto parent = adopt_ref(*new Object);
|
|
|
|
auto child = adopt_ref(*new Object);
|
2020-01-18 12:33:44 +00:00
|
|
|
child->parent = move(parent);
|
|
|
|
|
|
|
|
child = *child->parent;
|
2020-06-12 13:33:38 +00:00
|
|
|
EXPECT_EQ(child->ref_count(), 1u);
|
2020-01-18 12:33:44 +00:00
|
|
|
}
|
|
|
|
|
2020-01-19 09:29:21 +00:00
|
|
|
TEST_CASE(swap_with_self)
|
|
|
|
{
|
2021-04-23 14:46:57 +00:00
|
|
|
auto object = adopt_ref(*new Object);
|
2020-01-19 09:29:21 +00:00
|
|
|
swap(object, object);
|
2020-06-12 13:33:38 +00:00
|
|
|
EXPECT_EQ(object->ref_count(), 1u);
|
2020-01-19 09:29:21 +00:00
|
|
|
}
|