source: src/Common/utility.h @ b6d7f44

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumwith_gc
Last change on this file since b6d7f44 was b6d7f44, checked in by Peter A. Buhr <pabuhr@…>, 6 years ago

adjust compiler specific #if

  • Property mode set to 100644
File size: 13.0 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 : Peter A. Buhr
12// Last Modified On : Sun May  6 22:24:16 2018
13// Update Count     : 40
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#define toCString( ... ) toString( __VA_ARGS__ ).c_str()
165
166// replace element of list with all elements of another list
167template< typename T >
168void replace( std::list< T > &org, typename std::list< T >::iterator pos, std::list< T > &with ) {
169        typename std::list< T >::iterator next = pos; advance( next, 1 );
170
171        //if ( next != org.end() ) {
172        org.erase( pos );
173        org.splice( next, with );
174        //}
175
176        return;
177}
178
179// replace range of a list with a single element
180template< typename T >
181void replace( std::list< T > &org, typename std::list< T >::iterator begin, typename std::list< T >::iterator end, const T & with ) {
182        org.insert( begin, with );
183        org.erase( begin, end );
184}
185
186template< typename... Args >
187auto filter(Args&&... args) -> decltype(std::copy_if(std::forward<Args>(args)...)) {
188  return std::copy_if(std::forward<Args>(args)...);
189}
190
191template <typename E, typename UnaryPredicate, template< typename, typename...> class Container, typename... Args >
192void filter( Container< E *, Args... > & container, UnaryPredicate pred, bool doDelete ) {
193        auto i = begin( container );
194        while ( i != end( container ) ) {
195                auto it = next( i );
196                if ( pred( *i ) ) {
197                        if ( doDelete ) {
198                                delete *i;
199                        } // if
200                        container.erase( i );
201                } // if
202                i = it;
203        } // while
204}
205
206template< typename... Args >
207auto zip(Args&&... args) -> decltype(zipWith(std::forward<Args>(args)..., std::make_pair)) {
208  return zipWith(std::forward<Args>(args)..., std::make_pair);
209}
210
211template< class InputIterator1, class InputIterator2, class OutputIterator, class BinFunction >
212void zipWith( InputIterator1 b1, InputIterator1 e1, InputIterator2 b2, InputIterator2 e2, OutputIterator out, BinFunction func ) {
213        while ( b1 != e1 && b2 != e2 )
214                *out++ = func(*b1++, *b2++);
215}
216
217// it's nice to actually be able to increment iterators by an arbitrary amount
218template< class InputIt, class Distance >
219InputIt operator+( InputIt it, Distance n ) {
220        advance(it, n);
221        return it;
222}
223
224template< typename T >
225void warn_single( const T & arg ) {
226        std::cerr << arg << std::endl;
227}
228
229template< typename T, typename... Params >
230void warn_single(const T & arg, const Params & ... params ) {
231        std::cerr << arg;
232        warn_single( params... );
233}
234
235template< typename... Params >
236void warn( const Params & ... params ) {
237        std::cerr << "Warning: ";
238        warn_single( params... );
239}
240
241/// determines if `pref` is a prefix of `str`
242static inline bool isPrefix( const std::string & str, const std::string & pref ) {
243        if ( pref.size() > str.size() ) return false;
244        auto its = std::mismatch( pref.begin(), pref.end(), str.begin() );
245        return its.first == pref.end();
246}
247
248// -----------------------------------------------------------------------------
249// Ref Counted Singleton class
250// Objects that inherit from this class will have at most one reference to it
251// but if all references die, the object will be deleted.
252
253template< typename ThisType >
254class RefCountSingleton {
255  public:
256        static std::shared_ptr<ThisType> get() {
257                if( global_instance.expired() ) {
258                        std::shared_ptr<ThisType> new_instance = std::make_shared<ThisType>();
259                        global_instance = new_instance;
260                        return std::move(new_instance);
261                }
262                return global_instance.lock();
263        }
264  private:
265        static std::weak_ptr<ThisType> global_instance;
266};
267
268template< typename ThisType >
269std::weak_ptr<ThisType> RefCountSingleton<ThisType>::global_instance;
270
271// -----------------------------------------------------------------------------
272// RAII object to regulate "save and restore" behaviour, e.g.
273// void Foo::bar() {
274//   ValueGuard<int> guard(var); // var is a member of type Foo
275//   var = ...;
276// } // var's original value is restored
277template< typename T >
278struct ValueGuard {
279        T old;
280        T& ref;
281
282        ValueGuard(T& inRef) : old(inRef), ref(inRef) {}
283        ~ValueGuard() { ref = old; }
284};
285
286template< typename T >
287struct ValueGuardPtr {
288        T old;
289        T* ref;
290
291        ValueGuardPtr(T * inRef) : old( inRef ? *inRef : T() ), ref(inRef) {}
292        ~ValueGuardPtr() { if( ref ) *ref = old; }
293};
294
295template< typename aT >
296struct FuncGuard {
297        aT m_after;
298
299        template< typename bT >
300        FuncGuard( bT before, aT after ) : m_after( after ) {
301                before();
302        }
303
304        ~FuncGuard() {
305                m_after();
306        }
307};
308
309template< typename bT, typename aT >
310FuncGuard<aT> makeFuncGuard( bT && before, aT && after ) {
311        return FuncGuard<aT>( std::forward<bT>(before), std::forward<aT>(after) );
312}
313
314template< typename T >
315struct ValueGuardPtr< std::list< T > > {
316        std::list< T > old;
317        std::list< T >* ref;
318
319        ValueGuardPtr( std::list< T > * inRef) : old(), ref(inRef) {
320                if( ref ) { swap( *ref, old ); }
321        }
322        ~ValueGuardPtr() { if( ref ) { swap( *ref, old ); } }
323};
324
325// -----------------------------------------------------------------------------
326// Helper struct and function to support
327// for ( val : reverseIterate( container ) ) {}
328// syntax to have a for each that iterates backwards
329
330template< typename T >
331struct reverse_iterate_t {
332        T& ref;
333
334        reverse_iterate_t( T & ref ) : ref(ref) {}
335
336        typedef typename T::reverse_iterator iterator;
337        iterator begin() { return ref.rbegin(); }
338        iterator end() { return ref.rend(); }
339};
340
341template< typename T >
342reverse_iterate_t< T > reverseIterate( T & ref ) {
343        return reverse_iterate_t< T >( ref );
344}
345
346template< typename OutType, typename Range, typename Functor >
347OutType map_range( const Range& range, Functor&& functor ) {
348        OutType out;
349
350        std::transform(
351                begin( range ),
352                end( range ),
353                std::back_inserter( out ),
354                std::forward< Functor >( functor )
355        );
356
357        return out;
358}
359
360// -----------------------------------------------------------------------------
361// Helper struct and function to support
362// for ( val : group_iterate( container1, container2, ... ) ) {}
363// syntax to have a for each that iterates multiple containers of the same length
364// TODO: update to use variadic arguments
365
366template< typename T1, typename T2 >
367struct group_iterate_t {
368private:
369        std::tuple<T1, T2> args;
370public:
371        group_iterate_t( bool skipBoundsCheck, const T1 & v1, const T2 & v2 ) : args(v1, v2) {
372                assertf(skipBoundsCheck || v1.size() == v2.size(), "group iteration requires containers of the same size: <%zd, %zd>.", v1.size(), v2.size());
373        };
374
375        typedef std::tuple<decltype(*std::get<0>(args).begin()), decltype(*std::get<1>(args).begin())> value_type;
376        typedef decltype(std::get<0>(args).begin()) T1Iter;
377        typedef decltype(std::get<1>(args).begin()) T2Iter;
378
379        struct iterator {
380                typedef std::tuple<T1Iter, T2Iter> IterTuple;
381                IterTuple it;
382                iterator( T1Iter i1, T2Iter i2 ) : it( i1, i2 ) {}
383                iterator operator++() {
384                        return iterator( ++std::get<0>(it), ++std::get<1>(it) );
385                }
386                bool operator!=( const iterator &other ) const { return it != other.it; }
387                value_type operator*() const { return std::tie( *std::get<0>(it), *std::get<1>(it) ); }
388        };
389
390        iterator begin() { return iterator( std::get<0>(args).begin(), std::get<1>(args).begin() ); }
391        iterator end() { return iterator( std::get<0>(args).end(), std::get<1>(args).end() ); }
392};
393
394/// performs bounds check to ensure that all arguments are of the same length.
395template< typename... Args >
396group_iterate_t<Args...> group_iterate( Args &&... args ) {
397        return group_iterate_t<Args...>(false, std::forward<Args>( args )...);
398}
399
400/// does not perform a bounds check - requires user to ensure that iteration terminates when appropriate.
401template< typename... Args >
402group_iterate_t<Args...> unsafe_group_iterate( Args &&... args ) {
403        return group_iterate_t<Args...>(true, std::forward<Args>( args )...);
404}
405
406// -----------------------------------------------------------------------------
407// Helper struct and function to support
408// for ( val : lazy_map( container1, f ) ) {}
409// syntax to have a for each that iterates a container, mapping each element by applying f
410template< typename T, typename Func >
411struct lambda_iterate_t {
412        const T & ref;
413        std::function<Func> f;
414
415        struct iterator {
416                typedef decltype(begin(ref)) Iter;
417                Iter it;
418                std::function<Func> f;
419                iterator( Iter it, std::function<Func> f ) : it(it), f(f) {}
420                iterator & operator++() {
421                        ++it; return *this;
422                }
423                bool operator!=( const iterator &other ) const { return it != other.it; }
424                auto operator*() const -> decltype(f(*it)) { return f(*it); }
425        };
426
427        lambda_iterate_t( const T & ref, std::function<Func> f ) : ref(ref), f(f) {}
428
429        auto begin() const -> decltype(iterator(std::begin(ref), f)) { return iterator(std::begin(ref), f); }
430        auto end() const   -> decltype(iterator(std::end(ref), f)) { return iterator(std::end(ref), f); }
431};
432
433template< typename... Args >
434lambda_iterate_t<Args...> lazy_map( const Args &... args ) {
435        return lambda_iterate_t<Args...>( args...);
436}
437
438// -----------------------------------------------------------------------------
439// O(1) polymorphic integer ilog2, using clz, which returns the number of leading 0-bits, starting at the most
440// significant bit (single instruction on x86)
441
442template<typename T>
443inline
444#if defined(__GNUC__) && __GNUC__ > 4
445constexpr
446#endif
447T ilog2(const T & t) {
448        if(std::is_integral<T>::value) {
449                const constexpr int r = sizeof(t) * __CHAR_BIT__ - 1;
450                if( sizeof(T) == sizeof(unsigned       int) ) return r - __builtin_clz  ( t );
451                if( sizeof(T) == sizeof(unsigned      long) ) return r - __builtin_clzl ( t );
452                if( sizeof(T) == sizeof(unsigned long long) ) return r - __builtin_clzll( t );
453        }
454        assert(false);
455        return -1;
456} // ilog2
457
458
459// Local Variables: //
460// tab-width: 4 //
461// mode: c++ //
462// compile-command: "make install" //
463// End: //
Note: See TracBrowser for help on using the repository browser.