xref: /aosp_15_r20/external/vulkan-validation-layers/layers/sparse_containers.h (revision b7893ccf7851cd6a48cc5a1e965257d8a5cdcc70)
1*b7893ccfSSadaf Ebrahimi /* Copyright (c) 2019 The Khronos Group Inc.
2*b7893ccfSSadaf Ebrahimi  * Copyright (c) 2019 Valve Corporation
3*b7893ccfSSadaf Ebrahimi  * Copyright (c) 2019 LunarG, Inc.
4*b7893ccfSSadaf Ebrahimi  * Copyright (C) 2019 Google Inc.
5*b7893ccfSSadaf Ebrahimi  *
6*b7893ccfSSadaf Ebrahimi  * Licensed under the Apache License, Version 2.0 (the "License");
7*b7893ccfSSadaf Ebrahimi  * you may not use this file except in compliance with the License.
8*b7893ccfSSadaf Ebrahimi  * You may obtain a copy of the License at
9*b7893ccfSSadaf Ebrahimi  *
10*b7893ccfSSadaf Ebrahimi  *     http://www.apache.org/licenses/LICENSE-2.0
11*b7893ccfSSadaf Ebrahimi  *
12*b7893ccfSSadaf Ebrahimi  * Unless required by applicable law or agreed to in writing, software
13*b7893ccfSSadaf Ebrahimi  * distributed under the License is distributed on an "AS IS" BASIS,
14*b7893ccfSSadaf Ebrahimi  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15*b7893ccfSSadaf Ebrahimi  * See the License for the specific language governing permissions and
16*b7893ccfSSadaf Ebrahimi  * limitations under the License.
17*b7893ccfSSadaf Ebrahimi  *
18*b7893ccfSSadaf Ebrahimi  * John Zulauf <[email protected]>
19*b7893ccfSSadaf Ebrahimi  *
20*b7893ccfSSadaf Ebrahimi  */
21*b7893ccfSSadaf Ebrahimi #ifndef SPARSE_CONTAINERS_H_
22*b7893ccfSSadaf Ebrahimi #define SPARSE_CONTAINERS_H_
23*b7893ccfSSadaf Ebrahimi #define NOMINMAX
24*b7893ccfSSadaf Ebrahimi #include <cassert>
25*b7893ccfSSadaf Ebrahimi #include <memory>
26*b7893ccfSSadaf Ebrahimi #include <unordered_map>
27*b7893ccfSSadaf Ebrahimi #include <vector>
28*b7893ccfSSadaf Ebrahimi 
29*b7893ccfSSadaf Ebrahimi namespace sparse_container {
30*b7893ccfSSadaf Ebrahimi // SparseVector:
31*b7893ccfSSadaf Ebrahimi //
32*b7893ccfSSadaf Ebrahimi // Defines a sparse single-dimensional container which is targeted for three distinct use cases
33*b7893ccfSSadaf Ebrahimi // 1) Large range of indices sparsely populated ("Sparse access" below)
34*b7893ccfSSadaf Ebrahimi // 2) Large range of indices where all values are the same ("Sparse access" below)
35*b7893ccfSSadaf Ebrahimi // 3) Large range of values densely populated (more that 1/4 full) ("Dense access" below)
36*b7893ccfSSadaf Ebrahimi // 4) Small range of values where direct access is most efficient ("Dense access" below)
37*b7893ccfSSadaf Ebrahimi //
38*b7893ccfSSadaf Ebrahimi // To update semantics are supported bases on kSetReplaces:
39*b7893ccfSSadaf Ebrahimi //    true -- updates to already set (valid) indices replace current value
40*b7893ccfSSadaf Ebrahimi //    false -- updates to already set (valid) indicies are ignored.
41*b7893ccfSSadaf Ebrahimi //
42*b7893ccfSSadaf Ebrahimi // Theory of operation:
43*b7893ccfSSadaf Ebrahimi //
44*b7893ccfSSadaf Ebrahimi // When created, a sparse vector is created (based on size relative to
45*b7893ccfSSadaf Ebrahimi // the kSparseThreshold) in either Sparse or Dense access mode.
46*b7893ccfSSadaf Ebrahimi //
47*b7893ccfSSadaf Ebrahimi // In "Sparse access" mode individual values are stored in a map keyed
48*b7893ccfSSadaf Ebrahimi // by the index.  A "full range" value (if set) defines the value of all
49*b7893ccfSSadaf Ebrahimi // entries not present in the map. Setting a full range value via
50*b7893ccfSSadaf Ebrahimi //
51*b7893ccfSSadaf Ebrahimi //     SetRange(range_min, range_max, full_range_value )
52*b7893ccfSSadaf Ebrahimi //
53*b7893ccfSSadaf Ebrahimi // either clears the map (kSetReplaces==true) or prevents further
54*b7893ccfSSadaf Ebrahimi // updates to the vector (kSetReplaces==false).  If the map becomes
55*b7893ccfSSadaf Ebrahimi // more than // 1/kConversionThreshold (4) full, the SparseVector is
56*b7893ccfSSadaf Ebrahimi // converted into "Dense access" mode.  Entries are copied from map,
57*b7893ccfSSadaf Ebrahimi // with non-present indices set to the default value (kDefaultValue)
58*b7893ccfSSadaf Ebrahimi // or the full range value (if present).
59*b7893ccfSSadaf Ebrahimi //
60*b7893ccfSSadaf Ebrahimi // In "Dense access" mode, values are  stored in a vector the size of
61*b7893ccfSSadaf Ebrahimi // the valid range indexed by the incoming index value minus range_min_.
62*b7893ccfSSadaf Ebrahimi // The same upate semantic applies bases on kSetReplaces.
63*b7893ccfSSadaf Ebrahimi //
64*b7893ccfSSadaf Ebrahimi // Note that when kSparseThreshold
65*b7893ccfSSadaf Ebrahimi //
66*b7893ccfSSadaf Ebrahimi // Access:
67*b7893ccfSSadaf Ebrahimi //
68*b7893ccfSSadaf Ebrahimi // NOTE all "end" indices (in construction or access) are *exclusive*.
69*b7893ccfSSadaf Ebrahimi //
70*b7893ccfSSadaf Ebrahimi // Given the variable semantics and effective compression of Sparse
71*b7893ccfSSadaf Ebrahimi // access mode, all access is through Get, Set, and SetRange functions
72*b7893ccfSSadaf Ebrahimi // and a constant iterator. Get return either the value found (using
73*b7893ccfSSadaf Ebrahimi // the current access mode) or the kDefaultValue.  Set and SetRange
74*b7893ccfSSadaf Ebrahimi // return whether or not state was updated, in order to support dirty
75*b7893ccfSSadaf Ebrahimi // bit updates for any dependent state.
76*b7893ccfSSadaf Ebrahimi //
77*b7893ccfSSadaf Ebrahimi // The iterator ConstIterator provides basic, "by value" access. The
78*b7893ccfSSadaf Ebrahimi // "by value" nature of the access reflect the compressed nature
79*b7893ccfSSadaf Ebrahimi // operators *, ++, ==, and != are provided, with the latter two only
80*b7893ccfSSadaf Ebrahimi // suitable for comparisons vs. cend.  The iterator skips all
81*b7893ccfSSadaf Ebrahimi // kDefaultValue entries in either access mode, returning a std::pair
82*b7893ccfSSadaf Ebrahimi // containing {IndexType, ValueType}. The multiple access modes give
83*b7893ccfSSadaf Ebrahimi // the iterator a bit more complexity than is optimal, but hides the
84*b7893ccfSSadaf Ebrahimi // underlying complexity from the callers.
85*b7893ccfSSadaf Ebrahimi //
86*b7893ccfSSadaf Ebrahimi // TODO: Update iterator to use a reference (likely using
87*b7893ccfSSadaf Ebrahimi // reference_wrapper...)
88*b7893ccfSSadaf Ebrahimi 
89*b7893ccfSSadaf Ebrahimi template <typename IndexType_, typename T, bool kSetReplaces, T kDefaultValue = T(), size_t kSparseThreshold = 16>
90*b7893ccfSSadaf Ebrahimi class SparseVector {
91*b7893ccfSSadaf Ebrahimi    public:
92*b7893ccfSSadaf Ebrahimi     typedef IndexType_ IndexType;
93*b7893ccfSSadaf Ebrahimi     typedef T value_type;
94*b7893ccfSSadaf Ebrahimi     typedef value_type ValueType;
95*b7893ccfSSadaf Ebrahimi     typedef std::unordered_map<IndexType, ValueType> SparseType;
96*b7893ccfSSadaf Ebrahimi     typedef std::vector<ValueType> DenseType;
97*b7893ccfSSadaf Ebrahimi 
SparseVector(IndexType start,IndexType end)98*b7893ccfSSadaf Ebrahimi     SparseVector(IndexType start, IndexType end)
99*b7893ccfSSadaf Ebrahimi         : range_min_(start), range_max_(end), threshold_((end - start) / kConversionThreshold) {
100*b7893ccfSSadaf Ebrahimi         assert(end > start);
101*b7893ccfSSadaf Ebrahimi         Reset();
102*b7893ccfSSadaf Ebrahimi     }
103*b7893ccfSSadaf Ebrahimi 
104*b7893ccfSSadaf Ebrahimi     // Initial access mode is set based on range size vs. kSparseThreshold.  Either sparse_ or dense_ is always set, but only
105*b7893ccfSSadaf Ebrahimi     // ever one at a time
Reset()106*b7893ccfSSadaf Ebrahimi     void Reset() {
107*b7893ccfSSadaf Ebrahimi         has_full_range_value_ = false;
108*b7893ccfSSadaf Ebrahimi         full_range_value_ = kDefaultValue;
109*b7893ccfSSadaf Ebrahimi         size_t count = range_max_ - range_min_;
110*b7893ccfSSadaf Ebrahimi         if (kSparseThreshold && (count > kSparseThreshold)) {
111*b7893ccfSSadaf Ebrahimi             sparse_.reset(new SparseType());
112*b7893ccfSSadaf Ebrahimi             dense_.reset();
113*b7893ccfSSadaf Ebrahimi         } else {
114*b7893ccfSSadaf Ebrahimi             sparse_.reset();
115*b7893ccfSSadaf Ebrahimi             dense_.reset(new DenseType(count, kDefaultValue));
116*b7893ccfSSadaf Ebrahimi         }
117*b7893ccfSSadaf Ebrahimi     }
118*b7893ccfSSadaf Ebrahimi 
Get(const IndexType index)119*b7893ccfSSadaf Ebrahimi     const ValueType &Get(const IndexType index) const {
120*b7893ccfSSadaf Ebrahimi         // Note that here (and similarly below, the 'IsSparse' clause is
121*b7893ccfSSadaf Ebrahimi         // eliminated as dead code in release builds if kSparseThreshold==0
122*b7893ccfSSadaf Ebrahimi         if (IsSparse()) {
123*b7893ccfSSadaf Ebrahimi             if (!sparse_->empty()) {  // Don't attempt lookup in empty map
124*b7893ccfSSadaf Ebrahimi                 auto it = sparse_->find(index);
125*b7893ccfSSadaf Ebrahimi                 if (it != sparse_->cend()) {
126*b7893ccfSSadaf Ebrahimi                     return it->second;
127*b7893ccfSSadaf Ebrahimi                 }
128*b7893ccfSSadaf Ebrahimi             }
129*b7893ccfSSadaf Ebrahimi             // If there is a full_range_value, return it, but there isn't a full_range_value_, it's set to  kDefaultValue
130*b7893ccfSSadaf Ebrahimi             // so it's still the correct this to return
131*b7893ccfSSadaf Ebrahimi             return full_range_value_;
132*b7893ccfSSadaf Ebrahimi         } else {
133*b7893ccfSSadaf Ebrahimi             // Direct access
134*b7893ccfSSadaf Ebrahimi             assert(dense_.get());
135*b7893ccfSSadaf Ebrahimi             const ValueType &value = (*dense_)[index - range_min_];
136*b7893ccfSSadaf Ebrahimi             return value;
137*b7893ccfSSadaf Ebrahimi         }
138*b7893ccfSSadaf Ebrahimi     }
139*b7893ccfSSadaf Ebrahimi 
140*b7893ccfSSadaf Ebrahimi     // Set a indexes value, based on the access mode, update semantics are enforced within the access mode specific function
Set(const IndexType index,const ValueType & value)141*b7893ccfSSadaf Ebrahimi     bool Set(const IndexType index, const ValueType &value) {
142*b7893ccfSSadaf Ebrahimi         bool updated = false;
143*b7893ccfSSadaf Ebrahimi         if (IsSparse()) {
144*b7893ccfSSadaf Ebrahimi             updated = SetSparse(index, value);
145*b7893ccfSSadaf Ebrahimi         } else {
146*b7893ccfSSadaf Ebrahimi             assert(dense_.get());
147*b7893ccfSSadaf Ebrahimi             updated = SetDense(index, value);
148*b7893ccfSSadaf Ebrahimi         }
149*b7893ccfSSadaf Ebrahimi         return updated;
150*b7893ccfSSadaf Ebrahimi     }
151*b7893ccfSSadaf Ebrahimi 
152*b7893ccfSSadaf Ebrahimi     // Set a range of values based on access mode, with some update semantics applied a the range level
SetRange(const IndexType start,IndexType end,ValueType value)153*b7893ccfSSadaf Ebrahimi     bool SetRange(const IndexType start, IndexType end, ValueType value) {
154*b7893ccfSSadaf Ebrahimi         bool updated = false;
155*b7893ccfSSadaf Ebrahimi         if (IsSparse()) {
156*b7893ccfSSadaf Ebrahimi             if (!kSetReplaces && HasFullRange()) return false;  // We have full coverage, we can change this no more
157*b7893ccfSSadaf Ebrahimi 
158*b7893ccfSSadaf Ebrahimi             bool is_full_range = IsFullRange(start, end);
159*b7893ccfSSadaf Ebrahimi             if (kSetReplaces && is_full_range) {
160*b7893ccfSSadaf Ebrahimi                 updated = value != full_range_value_;
161*b7893ccfSSadaf Ebrahimi                 full_range_value_ = value;
162*b7893ccfSSadaf Ebrahimi                 if (HasSparseSubranges()) {
163*b7893ccfSSadaf Ebrahimi                     updated = true;
164*b7893ccfSSadaf Ebrahimi                     sparse_->clear();  // full range replaces all subranges
165*b7893ccfSSadaf Ebrahimi                 }
166*b7893ccfSSadaf Ebrahimi                 // has_full_range_value_ state of the full_range_value_ to avoid ValueType comparisons
167*b7893ccfSSadaf Ebrahimi                 has_full_range_value_ = value != kDefaultValue;
168*b7893ccfSSadaf Ebrahimi             } else if (!kSetReplaces && (value != kDefaultValue) && is_full_range && !HasFullRange()) {
169*b7893ccfSSadaf Ebrahimi                 // With the update only invalid semantics, the value becomes the fallback, and will prevent other updates
170*b7893ccfSSadaf Ebrahimi                 full_range_value_ = value;
171*b7893ccfSSadaf Ebrahimi                 has_full_range_value_ = true;
172*b7893ccfSSadaf Ebrahimi                 updated = true;
173*b7893ccfSSadaf Ebrahimi                 // Clean up the sparse map a bit
174*b7893ccfSSadaf Ebrahimi                 for (auto it = sparse_->begin(); it != sparse_->end();) {  // no increment clause because of erase below
175*b7893ccfSSadaf Ebrahimi                     if (it->second == value) {
176*b7893ccfSSadaf Ebrahimi                         it = sparse_->erase(it);  // remove redundant entries
177*b7893ccfSSadaf Ebrahimi                     } else {
178*b7893ccfSSadaf Ebrahimi                         ++it;
179*b7893ccfSSadaf Ebrahimi                     }
180*b7893ccfSSadaf Ebrahimi                 }
181*b7893ccfSSadaf Ebrahimi             } else {
182*b7893ccfSSadaf Ebrahimi                 for (IndexType index = start; index < end; ++index) {
183*b7893ccfSSadaf Ebrahimi                     // NOTE: We can't use SetSparse here, because this may be converted to dense access mid update
184*b7893ccfSSadaf Ebrahimi                     updated |= Set(index, value);
185*b7893ccfSSadaf Ebrahimi                 }
186*b7893ccfSSadaf Ebrahimi             }
187*b7893ccfSSadaf Ebrahimi         } else {
188*b7893ccfSSadaf Ebrahimi             // Note that "Dense Access" does away with the full_range_value_ logic, storing empty entries using kDefaultValue
189*b7893ccfSSadaf Ebrahimi             assert(dense_);
190*b7893ccfSSadaf Ebrahimi             for (IndexType index = start; index < end; ++index) {
191*b7893ccfSSadaf Ebrahimi                 updated = SetDense(index, value);
192*b7893ccfSSadaf Ebrahimi             }
193*b7893ccfSSadaf Ebrahimi         }
194*b7893ccfSSadaf Ebrahimi         return updated;
195*b7893ccfSSadaf Ebrahimi     }
196*b7893ccfSSadaf Ebrahimi 
197*b7893ccfSSadaf Ebrahimi     // Set only the non-default values from another sparse vector
Merge(const SparseVector & from)198*b7893ccfSSadaf Ebrahimi     bool Merge(const SparseVector &from) {
199*b7893ccfSSadaf Ebrahimi         // Must not set from Sparse arracy with larger bounds...
200*b7893ccfSSadaf Ebrahimi         assert((range_min_ <= from.range_min_) && (range_max_ >= from.range_max_));
201*b7893ccfSSadaf Ebrahimi         bool updated = false;
202*b7893ccfSSadaf Ebrahimi         if (from.IsSparse()) {
203*b7893ccfSSadaf Ebrahimi             if (from.HasFullRange() && !from.HasSparseSubranges()) {
204*b7893ccfSSadaf Ebrahimi                 // Short cut to copy a full range if that's all we have
205*b7893ccfSSadaf Ebrahimi                 updated |= SetRange(from.range_min_, from.range_max_, from.full_range_value_);
206*b7893ccfSSadaf Ebrahimi             } else {
207*b7893ccfSSadaf Ebrahimi                 // Have to do it the complete (potentially) slow way
208*b7893ccfSSadaf Ebrahimi                 // TODO add sorted keys to iterator to reduce hash lookups
209*b7893ccfSSadaf Ebrahimi                 for (auto it = from.cbegin(); it != from.cend(); ++it) {
210*b7893ccfSSadaf Ebrahimi                     const IndexType index = (*it).first;
211*b7893ccfSSadaf Ebrahimi                     const ValueType &value = (*it).second;
212*b7893ccfSSadaf Ebrahimi                     Set(index, value);
213*b7893ccfSSadaf Ebrahimi                 }
214*b7893ccfSSadaf Ebrahimi             }
215*b7893ccfSSadaf Ebrahimi         } else {
216*b7893ccfSSadaf Ebrahimi             assert(from.dense_);
217*b7893ccfSSadaf Ebrahimi             DenseType &ray = *from.dense_;
218*b7893ccfSSadaf Ebrahimi             for (IndexType entry = from.range_min_; entry < from.range_max_; ++entry) {
219*b7893ccfSSadaf Ebrahimi                 IndexType index = entry - from.range_min_;
220*b7893ccfSSadaf Ebrahimi                 if (ray[index] != kDefaultValue) {
221*b7893ccfSSadaf Ebrahimi                     updated |= Set(entry, ray[index]);
222*b7893ccfSSadaf Ebrahimi                 }
223*b7893ccfSSadaf Ebrahimi             }
224*b7893ccfSSadaf Ebrahimi         }
225*b7893ccfSSadaf Ebrahimi         return updated;
226*b7893ccfSSadaf Ebrahimi     }
227*b7893ccfSSadaf Ebrahimi 
228*b7893ccfSSadaf Ebrahimi     friend class ConstIterator;
229*b7893ccfSSadaf Ebrahimi     class ConstIterator {
230*b7893ccfSSadaf Ebrahimi        public:
231*b7893ccfSSadaf Ebrahimi         using SparseType = typename SparseVector::SparseType;
232*b7893ccfSSadaf Ebrahimi         using SparseIterator = typename SparseType::const_iterator;
233*b7893ccfSSadaf Ebrahimi         using IndexType = typename SparseVector::IndexType;
234*b7893ccfSSadaf Ebrahimi         using ValueType = typename SparseVector::ValueType;
235*b7893ccfSSadaf Ebrahimi         using IteratorValueType = std::pair<IndexType, ValueType>;
236*b7893ccfSSadaf Ebrahimi         const IteratorValueType &operator*() const { return current_value_; }
237*b7893ccfSSadaf Ebrahimi 
238*b7893ccfSSadaf Ebrahimi         ConstIterator &operator++() {
239*b7893ccfSSadaf Ebrahimi             if (delegated_) {  // implies sparse
240*b7893ccfSSadaf Ebrahimi                 ++it_sparse_;
241*b7893ccfSSadaf Ebrahimi                 if (it_sparse_ == vec_->sparse_->cend()) {
242*b7893ccfSSadaf Ebrahimi                     the_end_ = true;
243*b7893ccfSSadaf Ebrahimi                     current_value_.first = vec_->range_max_;
244*b7893ccfSSadaf Ebrahimi                     current_value_.second = SparseVector::DefaultValue();
245*b7893ccfSSadaf Ebrahimi                 } else {
246*b7893ccfSSadaf Ebrahimi                     current_value_.first = it_sparse_->first;
247*b7893ccfSSadaf Ebrahimi                     current_value_.second = it_sparse_->second;
248*b7893ccfSSadaf Ebrahimi                 }
249*b7893ccfSSadaf Ebrahimi             } else {
250*b7893ccfSSadaf Ebrahimi                 index_++;
251*b7893ccfSSadaf Ebrahimi                 SetCurrentValue();
252*b7893ccfSSadaf Ebrahimi             }
253*b7893ccfSSadaf Ebrahimi             return *this;
254*b7893ccfSSadaf Ebrahimi         }
255*b7893ccfSSadaf Ebrahimi         bool operator!=(const ConstIterator &rhs) const {
256*b7893ccfSSadaf Ebrahimi             return (the_end_ != rhs.the_end_);  // Just good enough for cend checks
257*b7893ccfSSadaf Ebrahimi         }
258*b7893ccfSSadaf Ebrahimi 
259*b7893ccfSSadaf Ebrahimi         bool operator==(const ConstIterator &rhs) const {
260*b7893ccfSSadaf Ebrahimi             return (the_end_ == rhs.the_end_);  // Just good enough for cend checks
261*b7893ccfSSadaf Ebrahimi         }
262*b7893ccfSSadaf Ebrahimi 
263*b7893ccfSSadaf Ebrahimi         // The iterator has two modes:
264*b7893ccfSSadaf Ebrahimi         //     delegated:
265*b7893ccfSSadaf Ebrahimi         //         where we are in sparse access mode and have no full_range_value
266*b7893ccfSSadaf Ebrahimi         //         and thus can delegate our iteration to underlying map
267*b7893ccfSSadaf Ebrahimi         //     non-delegated:
268*b7893ccfSSadaf Ebrahimi         //         either dense mode or we have a full range value and thus
269*b7893ccfSSadaf Ebrahimi         //         must iterate over the whole range
ConstIterator(const SparseVector & vec)270*b7893ccfSSadaf Ebrahimi         ConstIterator(const SparseVector &vec) : vec_(&vec) {
271*b7893ccfSSadaf Ebrahimi             if (!vec_->IsSparse() || vec_->HasFullRange()) {
272*b7893ccfSSadaf Ebrahimi                 // Must iterated over entire ranges skipping (in the case of dense access), invalid entries
273*b7893ccfSSadaf Ebrahimi                 delegated_ = false;
274*b7893ccfSSadaf Ebrahimi                 index_ = vec_->range_min_;
275*b7893ccfSSadaf Ebrahimi                 SetCurrentValue();  // Skips invalid and sets the_end_
276*b7893ccfSSadaf Ebrahimi             } else if (vec_->HasSparseSubranges()) {
277*b7893ccfSSadaf Ebrahimi                 // The subranges store the non-default values... and their is no full range value
278*b7893ccfSSadaf Ebrahimi                 delegated_ = true;
279*b7893ccfSSadaf Ebrahimi                 it_sparse_ = vec_->sparse_->cbegin();
280*b7893ccfSSadaf Ebrahimi                 current_value_.first = it_sparse_->first;
281*b7893ccfSSadaf Ebrahimi                 current_value_.second = it_sparse_->second;
282*b7893ccfSSadaf Ebrahimi                 the_end_ = false;  // the sparse map is non-empty (per HasSparseSubranges() above)
283*b7893ccfSSadaf Ebrahimi             } else {
284*b7893ccfSSadaf Ebrahimi                 // Sparse, but with no subranges
285*b7893ccfSSadaf Ebrahimi                 the_end_ = true;
286*b7893ccfSSadaf Ebrahimi             }
287*b7893ccfSSadaf Ebrahimi         }
288*b7893ccfSSadaf Ebrahimi 
ConstIterator()289*b7893ccfSSadaf Ebrahimi         ConstIterator() : vec_(nullptr), the_end_(true) {}
290*b7893ccfSSadaf Ebrahimi 
291*b7893ccfSSadaf Ebrahimi        protected:
292*b7893ccfSSadaf Ebrahimi         const SparseVector *vec_;
293*b7893ccfSSadaf Ebrahimi         bool the_end_;
294*b7893ccfSSadaf Ebrahimi         SparseIterator it_sparse_;
295*b7893ccfSSadaf Ebrahimi         bool delegated_;
296*b7893ccfSSadaf Ebrahimi         IndexType index_;
297*b7893ccfSSadaf Ebrahimi         ValueType value_;
298*b7893ccfSSadaf Ebrahimi 
299*b7893ccfSSadaf Ebrahimi         IteratorValueType current_value_;
300*b7893ccfSSadaf Ebrahimi 
301*b7893ccfSSadaf Ebrahimi         // in the non-delegated case we use normal accessors and skip default values.
SetCurrentValue()302*b7893ccfSSadaf Ebrahimi         void SetCurrentValue() {
303*b7893ccfSSadaf Ebrahimi             the_end_ = true;
304*b7893ccfSSadaf Ebrahimi             while (index_ < vec_->range_max_) {
305*b7893ccfSSadaf Ebrahimi                 value_ = vec_->Get(index_);
306*b7893ccfSSadaf Ebrahimi                 if (value_ != SparseVector::DefaultValue()) {
307*b7893ccfSSadaf Ebrahimi                     the_end_ = false;
308*b7893ccfSSadaf Ebrahimi                     current_value_ = IteratorValueType(index_, value_);
309*b7893ccfSSadaf Ebrahimi                     break;
310*b7893ccfSSadaf Ebrahimi                 }
311*b7893ccfSSadaf Ebrahimi                 index_++;
312*b7893ccfSSadaf Ebrahimi             }
313*b7893ccfSSadaf Ebrahimi         }
314*b7893ccfSSadaf Ebrahimi     };
315*b7893ccfSSadaf Ebrahimi     typedef ConstIterator const_iterator;
316*b7893ccfSSadaf Ebrahimi 
cbegin()317*b7893ccfSSadaf Ebrahimi     ConstIterator cbegin() const { return ConstIterator(*this); }
cend()318*b7893ccfSSadaf Ebrahimi     ConstIterator cend() const { return ConstIterator(); }
319*b7893ccfSSadaf Ebrahimi 
RangeMax()320*b7893ccfSSadaf Ebrahimi     IndexType RangeMax() const { return range_max_; }
RangeMin()321*b7893ccfSSadaf Ebrahimi     IndexType RangeMin() const { return range_min_; }
322*b7893ccfSSadaf Ebrahimi 
323*b7893ccfSSadaf Ebrahimi     static const unsigned kConversionThreshold = 4;
324*b7893ccfSSadaf Ebrahimi     const IndexType range_min_;  // exclusive
325*b7893ccfSSadaf Ebrahimi     const IndexType range_max_;  // exclusive
326*b7893ccfSSadaf Ebrahimi     const IndexType threshold_;  // exclusive
327*b7893ccfSSadaf Ebrahimi 
328*b7893ccfSSadaf Ebrahimi     // Data for sparse mode
329*b7893ccfSSadaf Ebrahimi     // We have a short cut for full range values when in sparse mode
330*b7893ccfSSadaf Ebrahimi     bool has_full_range_value_;
331*b7893ccfSSadaf Ebrahimi     ValueType full_range_value_;
332*b7893ccfSSadaf Ebrahimi     std::unique_ptr<SparseType> sparse_;
333*b7893ccfSSadaf Ebrahimi 
334*b7893ccfSSadaf Ebrahimi     // Data for dense mode
335*b7893ccfSSadaf Ebrahimi     std::unique_ptr<DenseType> dense_;
336*b7893ccfSSadaf Ebrahimi 
DefaultValue()337*b7893ccfSSadaf Ebrahimi     static const ValueType &DefaultValue() {
338*b7893ccfSSadaf Ebrahimi         static ValueType value = kDefaultValue;
339*b7893ccfSSadaf Ebrahimi         return value;
340*b7893ccfSSadaf Ebrahimi     }
341*b7893ccfSSadaf Ebrahimi     // Note that IsSparse is compile-time reducible if kSparseThreshold is zero...
IsSparse()342*b7893ccfSSadaf Ebrahimi     inline bool IsSparse() const { return kSparseThreshold && sparse_.get(); }
IsFullRange(IndexType start,IndexType end)343*b7893ccfSSadaf Ebrahimi     bool IsFullRange(IndexType start, IndexType end) const { return (start == range_min_) && (end == range_max_); }
IsFullRangeValue(const ValueType & value)344*b7893ccfSSadaf Ebrahimi     bool IsFullRangeValue(const ValueType &value) const { return has_full_range_value_ && (value == full_range_value_); }
HasFullRange()345*b7893ccfSSadaf Ebrahimi     bool HasFullRange() const { return IsSparse() && has_full_range_value_; }
HasSparseSubranges()346*b7893ccfSSadaf Ebrahimi     bool HasSparseSubranges() const { return IsSparse() && !sparse_->empty(); }
347*b7893ccfSSadaf Ebrahimi 
348*b7893ccfSSadaf Ebrahimi     // This is called unconditionally, to encapsulate the conversion criteria and logic here
SparseToDenseConversion()349*b7893ccfSSadaf Ebrahimi     void SparseToDenseConversion() {
350*b7893ccfSSadaf Ebrahimi         // If we're using more threshold of the sparse range, convert to dense_
351*b7893ccfSSadaf Ebrahimi         if (IsSparse() && (sparse_->size() > threshold_)) {
352*b7893ccfSSadaf Ebrahimi             ValueType default_value = HasFullRange() ? full_range_value_ : kDefaultValue;
353*b7893ccfSSadaf Ebrahimi             dense_.reset(new DenseType((range_max_ - range_min_), default_value));
354*b7893ccfSSadaf Ebrahimi             DenseType &ray = *dense_;
355*b7893ccfSSadaf Ebrahimi             for (auto const &item : *sparse_) {
356*b7893ccfSSadaf Ebrahimi                 ray[item.first - range_min_] = item.second;
357*b7893ccfSSadaf Ebrahimi             }
358*b7893ccfSSadaf Ebrahimi             sparse_.reset();
359*b7893ccfSSadaf Ebrahimi             has_full_range_value_ = false;
360*b7893ccfSSadaf Ebrahimi         }
361*b7893ccfSSadaf Ebrahimi     }
362*b7893ccfSSadaf Ebrahimi 
363*b7893ccfSSadaf Ebrahimi     // Dense access mode setter with update semantics implemented
SetDense(IndexType index,const ValueType & value)364*b7893ccfSSadaf Ebrahimi     bool SetDense(IndexType index, const ValueType &value) {
365*b7893ccfSSadaf Ebrahimi         bool updated = false;
366*b7893ccfSSadaf Ebrahimi         ValueType &current_value = (*dense_)[index - range_min_];
367*b7893ccfSSadaf Ebrahimi         if ((kSetReplaces || current_value == kDefaultValue) && (value != current_value)) {
368*b7893ccfSSadaf Ebrahimi             current_value = value;
369*b7893ccfSSadaf Ebrahimi             updated = true;
370*b7893ccfSSadaf Ebrahimi         }
371*b7893ccfSSadaf Ebrahimi         return updated;
372*b7893ccfSSadaf Ebrahimi     }
373*b7893ccfSSadaf Ebrahimi 
374*b7893ccfSSadaf Ebrahimi     // Sparse access mode setter with update full range and update semantics implemented
SetSparse(IndexType index,const ValueType & value)375*b7893ccfSSadaf Ebrahimi     bool SetSparse(IndexType index, const ValueType &value) {
376*b7893ccfSSadaf Ebrahimi         if (!kSetReplaces && HasFullRange()) {
377*b7893ccfSSadaf Ebrahimi             return false;  // We have full coverage, we can change this no more
378*b7893ccfSSadaf Ebrahimi         }
379*b7893ccfSSadaf Ebrahimi 
380*b7893ccfSSadaf Ebrahimi         if (kSetReplaces && IsFullRangeValue(value) && HasSparseSubranges()) {
381*b7893ccfSSadaf Ebrahimi             auto erasure = sparse_->erase(index);  // Remove duplicate record from map
382*b7893ccfSSadaf Ebrahimi             return erasure > 0;
383*b7893ccfSSadaf Ebrahimi         }
384*b7893ccfSSadaf Ebrahimi 
385*b7893ccfSSadaf Ebrahimi         // Use insert to reduce the number of hash lookups
386*b7893ccfSSadaf Ebrahimi         auto map_pair = std::make_pair(index, value);
387*b7893ccfSSadaf Ebrahimi         auto insert_pair = sparse_->insert(map_pair);
388*b7893ccfSSadaf Ebrahimi         auto &it = insert_pair.first;  // use references to avoid nested pair accesses
389*b7893ccfSSadaf Ebrahimi         const bool inserted = insert_pair.second;
390*b7893ccfSSadaf Ebrahimi         bool updated = false;
391*b7893ccfSSadaf Ebrahimi         if (inserted) {
392*b7893ccfSSadaf Ebrahimi             updated = true;
393*b7893ccfSSadaf Ebrahimi             SparseToDenseConversion();
394*b7893ccfSSadaf Ebrahimi         } else if (kSetReplaces && value != it->second) {
395*b7893ccfSSadaf Ebrahimi             // Only replace value if semantics allow it and it has changed.
396*b7893ccfSSadaf Ebrahimi             it->second = value;
397*b7893ccfSSadaf Ebrahimi             updated = true;
398*b7893ccfSSadaf Ebrahimi         }
399*b7893ccfSSadaf Ebrahimi         return updated;
400*b7893ccfSSadaf Ebrahimi     }
401*b7893ccfSSadaf Ebrahimi };
402*b7893ccfSSadaf Ebrahimi 
403*b7893ccfSSadaf Ebrahimi }  // namespace sparse_container
404*b7893ccfSSadaf Ebrahimi #endif
405