source: src/Common/utility.h @ 4a161be

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 4a161be was 54c9000, checked in by Rob Schluntz <rschlunt@…>, 6 years ago

Fix missing attribute warning

  • Property mode set to 100644
File size: 12.3 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// utility.h --
8//
9// Author           : Richard C. Bilson
10// Created On       : Mon May 18 07:44:20 2015
11// Last Modified By : Andrew Beach
12// Last Modified On : Thr Aug 17 11:38:00 2017
13// Update Count     : 34
14//
15
16#pragma once
17
18#include <cctype>
19#include <algorithm>
20#include <functional>
21#include <iostream>
22#include <iterator>
23#include <list>
24#include <memory>
25#include <sstream>
26#include <string>
27#include <type_traits>
28
29#include <cassert>
30
31#include "Common/Indenter.h"
32
33template< typename T >
34static inline T * maybeClone( const T *orig ) {
35        if ( orig ) {
36                return orig->clone();
37        } else {
38                return 0;
39        } // if
40}
41
42template< typename T, typename U >
43struct maybeBuild_t {
44        static T * doit( const U *orig ) {
45                if ( orig ) {
46                        return orig->build();
47                } else {
48                        return 0;
49                } // if
50        }
51};
52
53template< typename T, typename U >
54static inline T * maybeBuild( const U *orig ) {
55        return maybeBuild_t<T,U>::doit(orig);
56}
57
58template< typename T, typename U >
59static inline T * maybeMoveBuild( const U *orig ) {
60        T* ret = maybeBuild<T>(orig);
61        delete orig;
62        return ret;
63}
64
65template< typename Input_iterator >
66void printEnums( Input_iterator begin, Input_iterator end, const char * const *name_array, std::ostream &os ) {
67        for ( Input_iterator i = begin; i != end; ++i ) {
68                os << name_array[ *i ] << ' ';
69        } // for
70}
71
72template< typename Container >
73void deleteAll( Container &container ) {
74        for ( typename Container::iterator i = container.begin(); i != container.end(); ++i ) {
75                delete *i;
76        } // for
77}
78
79template< typename Container >
80void printAll( const Container &container, std::ostream &os, Indenter indent = {} ) {
81        for ( typename Container::const_iterator i = container.begin(); i != container.end(); ++i ) {
82                if ( *i ) {
83                        os << indent;
84                        (*i)->print( os, indent );
85                        // need an endl after each element because it's not easy to know when each individual item should end
86                        os << std::endl;
87                } // if
88        } // for
89}
90
91template< typename SrcContainer, typename DestContainer >
92void cloneAll( const SrcContainer &src, DestContainer &dest ) {
93        typename SrcContainer::const_iterator in = src.begin();
94        std::back_insert_iterator< DestContainer > out( dest );
95        while ( in != src.end() ) {
96                *out++ = (*in++)->clone();
97        } // while
98}
99
100template< typename SrcContainer, typename DestContainer, typename Predicate >
101void cloneAll_if( const SrcContainer &src, DestContainer &dest, Predicate pred ) {
102        std::back_insert_iterator< DestContainer > out( dest );
103        for ( auto x : src ) {
104                if ( pred(x) ) {
105                        *out++ = x->clone();
106                }
107        } // while
108}
109
110template< typename Container >
111void assertAll( const Container &container ) {
112        int count = 0;
113        for ( typename Container::const_iterator i = container.begin(); i != container.end(); ++i ) {
114                if ( !(*i) ) {
115                        std::cerr << count << " is null" << std::endl;
116                } // if
117        } // for
118}
119
120template < typename T >
121std::list<T> tail( std::list<T> l ) {
122        if ( ! l.empty() ) {
123                std::list<T> ret(++(l.begin()), l.end());
124                return ret;
125        } // if
126}
127
128template < typename T >
129std::list<T> flatten( std::list < std::list<T> > l) {
130        typedef std::list <T> Ts;
131
132        Ts ret;
133
134        switch ( l.size() ) {
135          case 0:
136                return ret;
137          case 1:
138                return l.front();
139          default:
140                ret = flatten(tail(l));
141                ret.insert(ret.begin(), l.front().begin(), l.front().end());
142                return ret;
143        } // switch
144}
145
146template < typename T >
147void toString_single( std::ostream & os, const T & value ) {
148        os << value;
149}
150
151template < typename T, typename... Params >
152void toString_single( std::ostream & os, const T & value, const Params & ... params ) {
153        os << value;
154        toString_single( os, params ... );
155}
156
157template < typename ... Params >
158std::string toString( const Params & ... params ) {
159        std::ostringstream os;
160        toString_single( os, params... );
161        return os.str();
162}
163
164// replace element of list with all elements of another list
165template< typename T >
166void replace( std::list< T > &org, typename std::list< T >::iterator pos, std::list< T > &with ) {
167        typename std::list< T >::iterator next = pos; advance( next, 1 );
168
169        //if ( next != org.end() ) {
170        org.erase( pos );
171        org.splice( next, with );
172        //}
173
174        return;
175}
176
177// replace range of a list with a single element
178template< typename T >
179void replace( std::list< T > &org, typename std::list< T >::iterator begin, typename std::list< T >::iterator end, const T & with ) {
180        org.insert( begin, with );
181        org.erase( begin, end );
182}
183
184template< typename... Args >
185auto filter(Args&&... args) -> decltype(std::copy_if(std::forward<Args>(args)...)) {
186  return std::copy_if(std::forward<Args>(args)...);
187}
188
189template <typename E, typename UnaryPredicate, template< typename, typename...> class Container, typename... Args >
190void filter( Container< E *, Args... > & container, UnaryPredicate pred, bool doDelete ) {
191        auto i = begin( container );
192        while ( i != end( container ) ) {
193                auto it = next( i );
194                if ( pred( *i ) ) {
195                        if ( doDelete ) {
196                                delete *i;
197                        } // if
198                        container.erase( i );
199                } // if
200                i = it;
201        } // while
202}
203
204template< typename... Args >
205auto zip(Args&&... args) -> decltype(zipWith(std::forward<Args>(args)..., std::make_pair)) {
206  return zipWith(std::forward<Args>(args)..., std::make_pair);
207}
208
209template< class InputIterator1, class InputIterator2, class OutputIterator, class BinFunction >
210void zipWith( InputIterator1 b1, InputIterator1 e1, InputIterator2 b2, InputIterator2 e2, OutputIterator out, BinFunction func ) {
211        while ( b1 != e1 && b2 != e2 )
212                *out++ = func(*b1++, *b2++);
213}
214
215// it's nice to actually be able to increment iterators by an arbitrary amount
216template< class InputIt, class Distance >
217InputIt operator+( InputIt it, Distance n ) {
218        advance(it, n);
219        return it;
220}
221
222template< typename T >
223void warn_single( const T & arg ) {
224        std::cerr << arg << std::endl;
225}
226
227template< typename T, typename... Params >
228void warn_single(const T & arg, const Params & ... params ) {
229        std::cerr << arg;
230        warn_single( params... );
231}
232
233template< typename... Params >
234void warn( const Params & ... params ) {
235        std::cerr << "Warning: ";
236        warn_single( params... );
237}
238
239/// determines if `pref` is a prefix of `str`
240static inline bool isPrefix( const std::string & str, const std::string & pref ) {
241        if ( pref.size() > str.size() ) return false;
242        auto its = std::mismatch( pref.begin(), pref.end(), str.begin() );
243        return its.first == pref.end();
244}
245
246// -----------------------------------------------------------------------------
247// Ref Counted Singleton class
248// Objects that inherit from this class will have at most one reference to it
249// but if all references die, the object will be deleted.
250
251template< typename ThisType >
252class RefCountSingleton {
253  public:
254        static std::shared_ptr<ThisType> get() {
255                if( global_instance.expired() ) {
256                        std::shared_ptr<ThisType> new_instance = std::make_shared<ThisType>();
257                        global_instance = new_instance;
258                        return std::move(new_instance);
259                }
260                return global_instance.lock();
261        }
262  private:
263        static std::weak_ptr<ThisType> global_instance;
264};
265
266template< typename ThisType >
267std::weak_ptr<ThisType> RefCountSingleton<ThisType>::global_instance;
268
269// -----------------------------------------------------------------------------
270// RAII object to regulate "save and restore" behaviour, e.g.
271// void Foo::bar() {
272//   ValueGuard<int> guard(var); // var is a member of type Foo
273//   var = ...;
274// } // var's original value is restored
275template< typename T >
276struct ValueGuard {
277        T old;
278        T& ref;
279
280        ValueGuard(T& inRef) : old(inRef), ref(inRef) {}
281        ~ValueGuard() { ref = old; }
282};
283
284template< typename T >
285struct ValueGuardPtr {
286        T old;
287        T* ref;
288
289        ValueGuardPtr(T * inRef) : old( inRef ? *inRef : T() ), ref(inRef) {}
290        ~ValueGuardPtr() { if( ref ) *ref = old; }
291};
292
293template< typename aT >
294struct FuncGuard {
295        aT m_after;
296
297        template< typename bT >
298        FuncGuard( bT before, aT after ) : m_after( after ) {
299                before();
300        }
301
302        ~FuncGuard() {
303                m_after();
304        }
305};
306
307template< typename bT, typename aT >
308FuncGuard<aT> makeFuncGuard( bT && before, aT && after ) {
309        return FuncGuard<aT>( std::forward<bT>(before), std::forward<aT>(after) );
310}
311
312template< typename T >
313struct ValueGuardPtr< std::list< T > > {
314        std::list< T > old;
315        std::list< T >* ref;
316
317        ValueGuardPtr( std::list< T > * inRef) : old(), ref(inRef) {
318                if( ref ) { swap( *ref, old ); }
319        }
320        ~ValueGuardPtr() { if( ref ) { swap( *ref, old ); } }
321};
322
323// -----------------------------------------------------------------------------
324// Helper struct and function to support
325// for ( val : reverseIterate( container ) ) {}
326// syntax to have a for each that iterates backwards
327
328template< typename T >
329struct reverse_iterate_t {
330        T& ref;
331
332        reverse_iterate_t( T & ref ) : ref(ref) {}
333
334        typedef typename T::reverse_iterator iterator;
335        iterator begin() { return ref.rbegin(); }
336        iterator end() { return ref.rend(); }
337};
338
339template< typename T >
340reverse_iterate_t< T > reverseIterate( T & ref ) {
341        return reverse_iterate_t< T >( ref );
342}
343
344template< typename OutType, typename Range, typename Functor >
345OutType map_range( const Range& range, Functor&& functor ) {
346        OutType out;
347
348        std::transform(
349                begin( range ),
350                end( range ),
351                std::back_inserter( out ),
352                std::forward< Functor >( functor )
353        );
354
355        return out;
356}
357
358// -----------------------------------------------------------------------------
359// Helper struct and function to support
360// for ( val : group_iterate( container1, container2, ... ) ) {}
361// syntax to have a for each that iterates multiple containers of the same length
362// TODO: update to use variadic arguments
363
364template< typename T1, typename T2 >
365struct group_iterate_t {
366private:
367        std::tuple<T1, T2> args;
368public:
369        group_iterate_t( bool skipBoundsCheck, const T1 & v1, const T2 & v2 ) : args(v1, v2) {
370                assertf(skipBoundsCheck || v1.size() == v2.size(), "group iteration requires containers of the same size: <%zd, %zd>.", v1.size(), v2.size());
371        };
372
373        typedef std::tuple<decltype(*std::get<0>(args).begin()), decltype(*std::get<1>(args).begin())> value_type;
374        typedef decltype(std::get<0>(args).begin()) T1Iter;
375        typedef decltype(std::get<1>(args).begin()) T2Iter;
376
377        struct iterator {
378                typedef std::tuple<T1Iter, T2Iter> IterTuple;
379                IterTuple it;
380                iterator( T1Iter i1, T2Iter i2 ) : it( i1, i2 ) {}
381                iterator operator++() {
382                        return iterator( ++std::get<0>(it), ++std::get<1>(it) );
383                }
384                bool operator!=( const iterator &other ) const { return it != other.it; }
385                value_type operator*() const { return std::tie( *std::get<0>(it), *std::get<1>(it) ); }
386        };
387
388        iterator begin() { return iterator( std::get<0>(args).begin(), std::get<1>(args).begin() ); }
389        iterator end() { return iterator( std::get<0>(args).end(), std::get<1>(args).end() ); }
390};
391
392/// performs bounds check to ensure that all arguments are of the same length.
393template< typename... Args >
394group_iterate_t<Args...> group_iterate( Args &&... args ) {
395        return group_iterate_t<Args...>(false, std::forward<Args>( args )...);
396}
397
398/// does not perform a bounds check - requires user to ensure that iteration terminates when appropriate.
399template< typename... Args >
400group_iterate_t<Args...> unsafe_group_iterate( Args &&... args ) {
401        return group_iterate_t<Args...>(true, std::forward<Args>( args )...);
402}
403
404// -----------------------------------------------------------------------------
405// Helper struct and function to support
406// for ( val : lazy_map( container1, f ) ) {}
407// syntax to have a for each that iterates a container, mapping each element by applying f
408template< typename T, typename Func >
409struct lambda_iterate_t {
410        const T & ref;
411        std::function<Func> f;
412
413        struct iterator {
414                typedef decltype(begin(ref)) Iter;
415                Iter it;
416                std::function<Func> f;
417                iterator( Iter it, std::function<Func> f ) : it(it), f(f) {}
418                iterator & operator++() {
419                        ++it; return *this;
420                }
421                bool operator!=( const iterator &other ) const { return it != other.it; }
422                auto operator*() const -> decltype(f(*it)) { return f(*it); }
423        };
424
425        lambda_iterate_t( const T & ref, std::function<Func> f ) : ref(ref), f(f) {}
426
427        auto begin() const -> decltype(iterator(std::begin(ref), f)) { return iterator(std::begin(ref), f); }
428        auto end() const   -> decltype(iterator(std::end(ref), f)) { return iterator(std::end(ref), f); }
429};
430
431template< typename... Args >
432lambda_iterate_t<Args...> lazy_map( const Args &... args ) {
433        return lambda_iterate_t<Args...>( args...);
434}
435
436
437
438// Local Variables: //
439// tab-width: 4 //
440// mode: c++ //
441// compile-command: "make install" //
442// End: //
Note: See TracBrowser for help on using the repository browser.