source: src/Common/utility.h@ 184557e

new-env
Last change on this file since 184557e was ff29f08, checked in by Aaron Moss <a3moss@…>, 7 years ago

Merge remote-tracking branch 'origin/master' into with_gc

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