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