1 //
2 // Copyright (C) 2012 The Android Open Source Project
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16 
17 #ifndef SHILL_PROPERTY_ITERATOR_H_
18 #define SHILL_PROPERTY_ITERATOR_H_
19 
20 #include <map>
21 #include <string>
22 
23 #include "shill/accessor_interface.h"
24 #include "shill/error.h"
25 
26 namespace shill {
27 
28 // An iterator wrapper class to hide the details of what kind of data structure
29 // we're using to store key/value pairs for properties. It is intended for use
30 // with PropertyStore and always advances to the next readable property.
31 template <class V>
32 class ReadablePropertyConstIterator {
33  public:
~ReadablePropertyConstIterator()34   ~ReadablePropertyConstIterator() {}
35 
AtEnd()36   bool AtEnd() const { return it_ == collection_.end(); }
37 
Advance()38   void Advance() {
39     if (!AtEnd()) {
40       do {
41         ++it_;
42       } while (MustAdvance());
43     }
44   }
45 
Key()46   const std::string& Key() const { return it_->first; }
47 
value()48   const V& value() const { return value_; }
49 
50  private:
51   friend class PropertyStore;
52 
53   typedef std::shared_ptr<AccessorInterface<V>> VAccessorPtr;
54 
ReadablePropertyConstIterator(const typename std::map<std::string,VAccessorPtr> & collection)55   explicit ReadablePropertyConstIterator(
56       const typename std::map<std::string, VAccessorPtr>& collection)
57       : collection_(collection),
58         it_(collection_.begin()),
59         value_() {
60     if (MustAdvance()) {
61       Advance();
62     }
63   }
64 
MustAdvance()65   bool MustAdvance() { return !AtEnd() && !RetrieveCurrentValue(); }
66 
RetrieveCurrentValue()67   bool RetrieveCurrentValue() {
68     Error error;
69     value_ = it_->second->Get(&error);
70     return error.IsSuccess();
71   }
72 
73   const typename std::map<std::string, VAccessorPtr>& collection_;
74   typename std::map<std::string, VAccessorPtr>::const_iterator it_;
75   V value_;
76 };
77 
78 }  // namespace shill
79 
80 #endif  // SHILL_PROPERTY_ITERATOR_H_
81