Turi Create  4.0
flex_dict_view.hpp
1 /* Copyright © 2017 Apple Inc. All rights reserved.
2  *
3  * Use of this source code is governed by a BSD-3-clause license that can
4  * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
5  */
6 #ifndef TURI_UNITY_FLEX_DICT_HPP
7 #define TURI_UNITY_FLEX_DICT_HPP
8 
9 #include <vector>
10 #include <core/data/flexible_type/flexible_type.hpp>
11 
12 namespace turi {
13 
14  /**
15  * A thin wrapper around flex_dict to facilitate access of the underneath
16  * sparse vector.
17  *
18  * It can be used the following way, suppose sa_iter is an iterator on top
19  * of sarray:
20  * flex_dict_view value = (*sa_iter);
21  *
22  * Internally, sparse vector points to a flex_dict structure. It will not make
23  * copy of the data to avoid memory allocation
24  **/
26  public:
27  /**
28  * Default constructor.
29  */
30  flex_dict_view() = delete;
31 
32  /**
33  * Constructs a sparse vector from a flexible type that is DICT type
34  */
35  flex_dict_view(const flex_dict& value);
36 
37  /**
38  * Constructs a sparse vector from a flexible type. This only works when
39  * the value is of type flex_type_enum::DICT, it will throw otherwise
40  */
41  flex_dict_view(const flexible_type& value);
42 
43  /**
44  * Given a key retrieve the value, throws if the key doesn't exist
45  */
46  const flexible_type& operator[](const flexible_type& key) const;
47 
48  /**
49  * Returns whether or not a given key exists in the sparse vector
50  */
51  bool has_key(const flexible_type& key) const;
52 
53  /**
54  * Returns number of elements in the sparse vector
55  */
56  size_t size() const;
57 
58  /**
59  * Returns all keys in a vector
60  */
61  const std::vector<flexible_type>& keys();
62 
63  /**
64  * Returns all values in a vector
65  */
66  const std::vector<flexible_type>& values();
67 
68  /**
69  * Returns an iterator that gives out items from beginning
70  */
71  flex_dict::const_iterator begin() const;
72 
73  /**
74  * Returns an iterator that points to end position
75  */
76  flex_dict::const_iterator end() const;
77 
78  private:
79  const flex_dict* m_flex_dict_ptr;
80 
81  // keys and values are lazily materialized when queried
82  std::vector<flexible_type> m_keys;
83  std::vector<flexible_type> m_values;
84  };
85 }
86 
87 
88 
89 #endif
flex_dict::const_iterator end() const
const std::vector< flexible_type > & values()
flex_dict::const_iterator begin() const
size_t size() const
const flexible_type & operator[](const flexible_type &key) const
std::vector< std::pair< flexible_type, flexible_type > > flex_dict
bool has_key(const flexible_type &key) const
const std::vector< flexible_type > & keys()