Line data Source code
1 : /*
2 : *
3 : * Copyright (c) 2022 Project CHIP Authors
4 : *
5 : * Licensed under the Apache License, Version 2.0 (the "License");
6 : * you may not use this file except in compliance with the License.
7 : * You may obtain a copy of the License at
8 : *
9 : * http://www.apache.org/licenses/LICENSE-2.0
10 : *
11 : * Unless required by applicable law or agreed to in writing, software
12 : * distributed under the License is distributed on an "AS IS" BASIS,
13 : * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 : * See the License for the specific language governing permissions and
15 : * limitations under the License.
16 : */
17 :
18 : /**
19 : * @file
20 : * Contains a standard iterator class.
21 : */
22 :
23 : #pragma once
24 :
25 : #include <stddef.h>
26 :
27 : namespace chip {
28 :
29 : /**
30 : * Template used to generate a custom iterator
31 : */
32 : template <typename T>
33 : class CommonIterator
34 : {
35 : public:
36 3127 : virtual ~CommonIterator() = default;
37 :
38 : /**
39 : * @retval The number of entries in total that will be iterated.
40 : */
41 : virtual size_t Count() = 0;
42 :
43 : /**
44 : * @param[out] item Value associated with the next element in the iteration.
45 : * @retval true if the next entry is successfully retrieved.
46 : * @retval false if no more entries can be found.
47 : */
48 : virtual bool Next(T & item) = 0;
49 :
50 : /**
51 : * Release the memory allocated by this iterator.
52 : * Must be called before the iterator goes out of scope if the iterator was dynamically allocated.
53 : */
54 : virtual void Release() = 0;
55 :
56 : /**
57 : * Wraps an iterator pointer and auto-releases it when going out of scope.
58 : */
59 : class AutoReleasing
60 : {
61 : public:
62 123 : AutoReleasing(CommonIterator * iterator) : mIterator(iterator) {}
63 123 : ~AutoReleasing()
64 : {
65 123 : if (mIterator != nullptr)
66 : {
67 123 : mIterator->Release();
68 : }
69 123 : }
70 :
71 : AutoReleasing(const AutoReleasing &) = delete;
72 : AutoReleasing & operator=(const AutoReleasing &) = delete;
73 :
74 122 : bool IsValid() const { return mIterator != nullptr; }
75 63 : size_t Count() const { return mIterator != nullptr ? mIterator->Count() : 0; }
76 183 : bool Next(T & value) { return (mIterator == nullptr) ? false : mIterator->Next(value); }
77 :
78 : private:
79 : CommonIterator * mIterator;
80 : };
81 :
82 : protected:
83 3127 : CommonIterator() = default;
84 : };
85 :
86 : } // namespace chip
|