source: src/Common/PersistentMap.h @ b419abb

ADTarm-ehast-experimentalcleanup-dtorsenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpersistent-indexerpthread-emulationqualifiedEnum
Last change on this file since b419abb was b419abb, checked in by Aaron Moss <a3moss@…>, 5 years ago

Lazy scope initialization for indexer

  • Property mode set to 100644
File size: 7.4 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// PersistentMap.h --
8//
9// Author           : Aaron B. Moss
10// Created On       : Thu Mar  7 15:50:00 2019
11// Last Modified By : Aaron B. Moss
12// Last Modified On : Thu Mar  7 15:50:00 2019
13// Update Count     : 1
14//
15
16#pragma once
17
18#include <cassert>        // for assertf
19#include <cstddef>        // for size_t
20#include <functional>     // for hash, equal_to
21#include <memory>         // for shared_ptr, enable_shared_from_this, make_shared
22#include <unordered_map>  // for unordered_map
23#include <utility>        // for forward, move
24
25/// Wraps a hash table in a persistent data structure, using a technique based
26/// on the persistent array in Conchon & Filliatre "A Persistent Union-Find
27/// Data Structure"
28
29template<typename Key, typename Val,
30         typename Hash = std::hash<Key>, typename Eq = std::equal_to<Key>>
31class PersistentMap 
32        : public std::enable_shared_from_this<PersistentMap<Key, Val, Hash, Eq>> {
33public:
34        /// Type of this class
35        using Self = PersistentMap<Key, Val, Hash, Eq>;
36        /// Type of pointer to this class
37        using Ptr = std::shared_ptr<Self>;
38
39        /// Types of version nodes
40        enum Mode { 
41                BASE,  ///< Root node of version tree
42                REM,   ///< Key removal node
43                INS,   ///< Key update node
44                UPD    ///< Key update node
45        };
46
47private:
48        using Base = std::unordered_map<Key, Val, Hash, Eq>;
49
50        /// Insertion/update node
51        struct Ins {
52                Ptr base;  ///< Modified map
53                Key key;   ///< Key inserted
54                Val val;   ///< Value stored
55
56                template<typename P, typename K, typename V>
57                Ins(P&& p, K&& k, V&& v)
58                : base(std::forward<P>(p)), key(std::forward<K>(k)), val(std::forward<V>(v)) {}
59        };
60
61        /// Removal node
62        struct Rem {
63                Ptr base;  ///< Modified map
64                Key key;   ///< Key removed
65               
66                template<typename P, typename K>
67                Rem(P&& p, K&& k) : base(std::forward<P>(p)), key(std::forward<K>(k)) {}
68        };
69
70        /// Underlying storage
71        union Data {
72                char def;
73                Base base;
74                Ins ins;
75                Rem rem;
76
77                Data() : def('\0') {}
78                ~Data() {}
79        } data;
80
81        /// Type of node
82        mutable Mode mode;
83
84        /// get mutable reference as T
85        template<typename T>
86        T& as() { return reinterpret_cast<T&>(data); }
87
88        /// get const reference as T
89        template<typename T>
90        const T& as() const { return reinterpret_cast<const T&>(data); }
91
92        /// get rvalue reference as T
93        template<typename T>
94        T&& take_as() { return std::move(as<T>()); }
95
96        /// initialize as T
97        template<typename T, typename... Args>
98        void init( Args&&... args ) {
99                new( &as<T>() ) T { std::forward<Args>(args)... };
100        }
101
102        /// reset as current mode
103        void reset() {
104                switch( mode ) {
105                        case BASE:          as<Base>().~Base(); break;
106                        case REM:           as<Rem>().~Rem();   break;
107                        case INS: case UPD: as<Ins>().~Ins();   break;
108                }
109        }
110
111        /// reset as base
112        void reset_as_base() {
113                as<Base>().~Base();
114        }
115
116public:
117        using size_type = std::size_t;
118
119        using iterator = typename Base::const_iterator;
120
121        PersistentMap() : data(), mode(BASE) { init<Base>(); }
122
123        PersistentMap( Base&& b ) : data(), mode(BASE) { init<Base>(std::move(b)); }
124
125        PersistentMap( const Self& o ) = delete;
126
127        Self& operator= ( const Self& o ) = delete;
128
129        ~PersistentMap() { reset(); }
130
131        /// Create a pointer to a new, empty persistent map
132        static Ptr new_ptr() { return std::make_shared<Self>(); }
133
134        /// reroot persistent map at current node
135        void reroot() const {
136                // recursive base case
137                if ( mode == BASE ) return;
138
139                // reroot base
140                Self* mut_this = const_cast<Self*>(this);
141                Ptr base = ( mode == REM ) ? mut_this->as<Rem>().base : mut_this->as<Ins>().base;
142                base->reroot();
143
144                // remove map from base
145                Base base_map = base->take_as<Base>();
146                base->reset_as_base();
147                // xxx -- investigate checking ref-count and omitting re-initialization if 1
148
149                // switch base to inverse of self and mutate base map
150                switch ( mode ) {
151                        case REM: {
152                                Rem& self = mut_this->as<Rem>();
153                                auto it = base_map.find( self.key );
154
155                                base->init<Ins>( 
156                                        mut_this->shared_from_this(), std::move(self.key), std::move(it->second) );
157                                base->mode = INS;
158
159                                base_map.erase( it );
160                                break;
161                        }
162                        case INS: {
163                                Ins& self = mut_this->as<Ins>();
164
165                                base->init<Rem>( mut_this->shared_from_this(), self.key );
166                                base->mode = REM;
167
168                                base_map.emplace( std::move(self.key), std::move(self.val) );
169                                break;
170                        }
171                        case UPD: {
172                                Ins& self = mut_this->as<Ins>();
173                                auto it = base_map.find( self.key );
174
175                                base->init<Ins>( 
176                                        mut_this->shared_from_this(), std::move(self.key), std::move(it->second) );
177                                base->mode = UPD;
178
179                                it->second = std::move(self.val);
180                                break;
181                        }
182                        case BASE: assertf(false, "unreachable"); break;
183                }
184
185                // set base map into self
186                mut_this->reset();
187                mut_this->init<Base>( std::move(base_map) );
188                mode = BASE;
189        }
190
191private:
192        /// the base after rerooting at the current node
193        const Base& rerooted() const {
194                reroot();
195                return as<Base>();
196        }
197
198public:
199        /// true iff the map is empty
200        bool empty() const { return rerooted().empty(); }
201
202        /// number of entries in map
203        size_type size() const { return rerooted().size(); }
204
205        /// begin iterator for map; may be invalidated by calls to non-iteration functions
206        /// or functions on other maps in the same tree
207        iterator begin() const { return rerooted().begin(); }
208
209        /// end iterator for map; may be invalidated by calls to non-iteration functions
210        /// or functions on other maps in the same tree
211        iterator end() const { return rerooted().end(); }
212
213        /// underlying map iterator for value
214        iterator find(const Key& k) const { return rerooted().find( k ); }
215
216        /// check if value is present
217        size_type count(const Key& k) const { return rerooted().count( k ); }
218
219        /// get value; undefined behaviour if not present
220        const Val& get(const Key& k) const {
221                const Base& self = rerooted();
222                auto it = self.find( k );
223                return it->second;
224        }
225
226        /// get value; returns default if not present
227        template<typename V>
228        Val get_or_default(const Key& k, V&& d) const {
229                const Base& self = rerooted();
230                auto it = self.find( k );
231                if ( it == self.end() ) return d;
232                else return it->second;
233        }
234
235        /// set value, storing new map in output variable
236        template<typename K, typename V>
237        Ptr set(K&& k, V&& v) {
238                reroot();
239
240                // transfer map to new node
241                Ptr ret = std::make_shared<Self>( take_as<Base>() );
242                reset_as_base();
243                Base& base_map = ret->as<Base>();
244
245                // check if this is update or insert
246                auto it = base_map.find( k );
247                if ( it == base_map.end() ) {
248                        // set self to REM node and insert into base
249                        init<Rem>( ret, k );
250                        mode = REM;
251
252                        base_map.emplace_hint( it, std::forward<K>(k), std::forward<V>(v) );
253                } else {
254                        // set self to UPD node and modify base
255                        init<Ins>( ret, std::forward<K>(k), std::move(it->second) );
256                        mode = UPD;
257
258                        it->second = std::forward<V>(v);
259                }
260
261                return ret;
262        }
263
264        /// remove value, storing new map in output variable; does nothing if key not in map
265        Ptr erase(const Key& k) {
266                reroot();
267               
268                // exit early if key does not exist in map
269                if ( ! as<Base>().count( k ) ) return this->shared_from_this();
270
271                // transfer map to new node
272                Ptr ret = std::make_shared<Self>( take_as<Base>() );
273                reset_as_base();
274                Base& base_map = ret->as<Base>();
275
276                // set self to INS node and remove from base
277                init<Ins>( ret, k, base_map[k] );
278                mode = INS;
279
280                base_map.erase( k );
281
282                return ret;
283        }
284};
285
286// Local Variables: //
287// tab-width: 4 //
288// mode: c++ //
289// compile-command: "make install" //
290// End: //
Note: See TracBrowser for help on using the repository browser.