1 // Copyright 2024 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14
15 #include "pw_containers/intrusive_set.h"
16
17 #include "pw_unit_test/framework.h"
18
19 namespace examples {
20
21 // DOCSTAG: [pw_containers-intrusive_set]
22
23 class Book : public pw::IntrusiveSet<Book>::Item {
24 private:
25 using Item = pw::IntrusiveSet<Book>::Item;
26
27 public:
Book(const char * name)28 explicit Book(const char* name) : name_(name) {}
name() const29 const char* name() const { return name_; }
operator <(const Book & rhs) const30 bool operator<(const Book& rhs) const {
31 return strcmp(name_, rhs.name()) < 0;
32 }
33
34 private:
35 const char* name_;
36 };
37
38 std::array<Book, 8> books = {
39 Book("A Tale of Two Cities"),
40 Book("The Little Prince"),
41 Book("The Alchemist"),
42 Book("Harry Potter and the Philosopher's Stone"),
43 Book("And Then There Were None"),
44 Book("Dream of the Red Chamber"),
45 Book("The Hobbit"),
46 Book("Alice's Adventures in Wonderland"),
47 };
48
49 pw::IntrusiveSet<Book> library(books.begin(), books.end());
50
VisitLibrary(pw::IntrusiveSet<Book> & book_bag)51 void VisitLibrary(pw::IntrusiveSet<Book>& book_bag) {
52 // Return any books we previously checked out.
53 library.merge(book_bag);
54
55 // Pick out some new books to read to the kids, but only if they're available.
56 std::array<const char*, 3> titles = {
57 "The Hobbit",
58 "Curious George",
59 "Harry Potter and the Philosopher's Stone",
60 };
61 for (const char* title : titles) {
62 Book requested(title);
63 auto iter = library.find(requested);
64 if (iter != library.end()) {
65 Book& book = *iter;
66 library.erase(iter);
67 book_bag.insert(book);
68 }
69 }
70 }
71
72 // DOCSTAG: [pw_containers-intrusive_set]
73
74 } // namespace examples
75
76 namespace {
77
TEST(IntrusiveMapExampleTest,VisitLibrary)78 TEST(IntrusiveMapExampleTest, VisitLibrary) {
79 examples::Book book("One Hundred Years of Solitude");
80 pw::IntrusiveSet<examples::Book> book_bag;
81 book_bag.insert(book);
82
83 examples::VisitLibrary(book_bag);
84 auto iter = book_bag.begin();
85 EXPECT_STREQ((iter++)->name(), "Harry Potter and the Philosopher's Stone");
86 EXPECT_STREQ((iter++)->name(), "The Hobbit");
87 EXPECT_EQ(iter, book_bag.end());
88
89 // Remove books before items go out scope.
90 book_bag.clear();
91 examples::library.clear();
92 }
93
94 } // namespace
95