Skip to content

Commit d13078b

Browse files
committed
Add clone method to List
1 parent 9796e68 commit d13078b

File tree

4 files changed

+34
-7
lines changed

4 files changed

+34
-7
lines changed

include/scratchcpp/list.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@ class LIBSCRATCHCPP_EXPORT List
3939

4040
std::string toString() const;
4141

42+
std::shared_ptr<List> clone();
43+
4244
private:
4345
spimpl::unique_impl_ptr<ListPrivate> impl;
4446
};

src/scratch/list.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,3 +76,14 @@ std::string List::toString() const
7676

7777
return ret;
7878
}
79+
80+
/*! Creates a copy of the list. */
81+
std::shared_ptr<List> List::clone()
82+
{
83+
auto copy = std::make_shared<List>(id(), impl->name);
84+
85+
for (const Value &item : *this)
86+
copy->push_back(item);
87+
88+
return copy;
89+
}

src/scratch/sprite.cpp

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -61,13 +61,8 @@ std::shared_ptr<Sprite> Sprite::clone()
6161

6262
const auto &l = lists();
6363

64-
for (auto list : l) {
65-
auto newList = std::make_shared<List>(list->id(), list->name());
66-
clone->addList(newList);
67-
68-
for (const Value &item : *list)
69-
newList->push_back(item);
70-
}
64+
for (auto list : l)
65+
clone->addList(list->clone());
7166

7267
clone->setCurrentCostume(currentCostume());
7368
clone->setLayerOrder(layerOrder());

test/scratch_classes/list_test.cpp

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,3 +170,22 @@ TEST(ListTest, ToString)
170170
list.push_back(8);
171171
ASSERT_EQ(list.toString(), "098");
172172
}
173+
174+
TEST(ListTest, Clone)
175+
{
176+
List list("abc", "test list");
177+
list.push_back("Lorem");
178+
list.push_back("ipsum");
179+
list.push_back("dolor");
180+
list.push_back("sit");
181+
list.push_back("amet");
182+
183+
std::shared_ptr<List> clone = list.clone();
184+
ASSERT_TRUE(clone);
185+
ASSERT_EQ(clone->id(), list.id());
186+
ASSERT_EQ(clone->name(), list.name());
187+
ASSERT_EQ(clone->size(), list.size());
188+
189+
for (std::size_t i = 0; i < list.size(); i++)
190+
ASSERT_EQ(list[i], (*clone)[i]);
191+
}

0 commit comments

Comments
 (0)