//
// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
//
// The contents of this file are covered under the licence agreement in the
// file "LICENCE" distributed with Cforall.
//
// utility.h --
//
// Author           : Richard C. Bilson
// Created On       : Mon May 18 07:44:20 2015
// Last Modified By : Peter A. Buhr
// Last Modified On : Fri Sep 23 11:46:47 2016
// Update Count     : 28
//

#ifndef _UTILITY_H
#define _UTILITY_H

#include <cctype>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <list>
#include <memory>
#include <sstream>
#include <string>
#include <cassert>

template< typename T >
static inline T * maybeClone( const T *orig ) {
	if ( orig ) {
		return orig->clone();
	} else {
		return 0;
	} // if
}

template<typename T, typename U>
struct maybeBuild_t {
	static T * doit( const U *orig ) {
		if ( orig ) {
			return orig->build();
		} else {
			return 0;
		} // if
	}
};

template< typename T, typename U >
static inline T * maybeBuild( const U *orig ) {
	return maybeBuild_t<T,U>::doit(orig);
}

template< typename T, typename U >
static inline T * maybeMoveBuild( const U *orig ) {
	T* ret = maybeBuild<T>(orig);
	delete orig;
	return ret;
}

template< typename Input_iterator >
void printEnums( Input_iterator begin, Input_iterator end, const char * const *name_array, std::ostream &os ) {
	for ( Input_iterator i = begin; i != end; ++i ) {
		os << name_array[ *i ] << ' ';
	} // for
}

template< typename Container >
void deleteAll( Container &container ) {
	for ( typename Container::iterator i = container.begin(); i != container.end(); ++i ) {
		delete *i;
	} // for
}

template< typename Container >
void printAll( const Container &container, std::ostream &os, int indent = 0 ) {
	for ( typename Container::const_iterator i = container.begin(); i != container.end(); ++i ) {
		if ( *i ) {
			os << std::string( indent,  ' ' );
			(*i)->print( os, indent + 2 );
			// need an endl after each element because it's not easy to know when each individual item should end
			os << std::endl;
		} // if
	} // for
}

template< typename SrcContainer, typename DestContainer >
void cloneAll( const SrcContainer &src, DestContainer &dest ) {
	typename SrcContainer::const_iterator in = src.begin();
	std::back_insert_iterator< DestContainer > out( dest );
	while ( in != src.end() ) {
		*out++ = (*in++)->clone();
	} // while
}

template< typename Container >
void assertAll( const Container &container ) {
	int count = 0;
	for ( typename Container::const_iterator i = container.begin(); i != container.end(); ++i ) {
		if ( !(*i) ) {
			std::cerr << count << " is null" << std::endl;
		} // if
	} // for
}

template < typename T >
std::list<T> tail( std::list<T> l ) {
	if ( ! l.empty() ) {
		std::list<T> ret(++(l.begin()), l.end());
		return ret;
	} // if
}

template < typename T >
std::list<T> flatten( std::list < std::list<T> > l) {
	typedef std::list <T> Ts;

	Ts ret;

	switch ( l.size() ) {
	  case 0:
		return ret;
	  case 1:
		return l.front();
	  default:
		ret = flatten(tail(l));
		ret.insert(ret.begin(), l.front().begin(), l.front().end());
		return ret;
	} // switch
}

template < typename T >
void toString_single( std::ostream & os, const T & value ) {
	os << value;
}

template < typename T, typename... Params >
void toString_single( std::ostream & os, const T & value, const Params & ... params ) {
	os << value;
	toString_single( os, params ... );
}

template < typename ... Params >
std::string toString( const Params & ... params ) {
	std::ostringstream os;
	toString_single( os, params... );
	return os.str();
}

// replace element of list with all elements of another list
template< typename T >
void replace( std::list< T > &org, typename std::list< T >::iterator pos, std::list< T > &with ) {
	typename std::list< T >::iterator next = pos; advance( next, 1 );

	//if ( next != org.end() ) {
	org.erase( pos );
	org.splice( next, with );
	//}

	return;
}

// replace range of a list with a single element
template< typename T >
void replace( std::list< T > &org, typename std::list< T >::iterator begin, typename std::list< T >::iterator end, const T & with ) {
	org.insert( begin, with );
	org.erase( begin, end );
}

template< typename... Args >
auto filter(Args&&... args) -> decltype(std::copy_if(std::forward<Args>(args)...)) {
  return std::copy_if(std::forward<Args>(args)...);
}

template< typename... Args >
auto zip(Args&&... args) -> decltype(zipWith(std::forward<Args>(args)..., std::make_pair)) {
  return zipWith(std::forward<Args>(args)..., std::make_pair);
}

template< class InputIterator1, class InputIterator2, class OutputIterator, class BinFunction >
void zipWith( InputIterator1 b1, InputIterator1 e1, InputIterator2 b2, InputIterator2 e2, OutputIterator out, BinFunction func ) {
	while ( b1 != e1 && b2 != e2 )
		*out++ = func(*b1++, *b2++);
}

// it's nice to actually be able to increment iterators by an arbitrary amount
template< class InputIt, class Distance >
InputIt operator+( InputIt it, Distance n ) {
	advance(it, n);
	return it;
}

template< typename T >
void warn_single( const T & arg ) {
	std::cerr << arg << std::endl;
}

template< typename T, typename... Params >
void warn_single(const T & arg, const Params & ... params ) {
	std::cerr << arg;
	warn_single( params... );
}

template< typename... Params >
void warn( const Params & ... params ) {
	std::cerr << "Warning: ";
	warn_single( params... );
}

// -----------------------------------------------------------------------------
// Ref Counted Singleton class
// Objects that inherit from this class will have at most one reference to it
// but if all references die, the object will be deleted.

template< typename ThisType >
class RefCountSingleton {
  public:
	static std::shared_ptr<ThisType> get() {
		if( global_instance.expired() ) {
			std::shared_ptr<ThisType> new_instance = std::make_shared<ThisType>();
			global_instance = new_instance;
			return std::move(new_instance);
		}
		return global_instance.lock();
	}
  private:
	static std::weak_ptr<ThisType> global_instance;
};

template< typename ThisType >
std::weak_ptr<ThisType> RefCountSingleton<ThisType>::global_instance;

// -----------------------------------------------------------------------------
// RAII object to regulate "save and restore" behaviour, e.g.
// void Foo::bar() {
//   ValueGuard<int> guard(var); // var is a member of type Foo
//   var = ...;
// } // var's original value is restored
template< typename T >
struct ValueGuard {
	T old;
	T& ref;

	ValueGuard(T& inRef) : old(inRef), ref(inRef) {}
	~ValueGuard() { ref = old; }
};

// -----------------------------------------------------------------------------
// Helper struct and function to support
// for ( val : reverseIterate( container ) ) {}
// syntax to have a for each that iterates backwards

template< typename T >
struct reverseIterate_t {
	T& ref;

	reverseIterate_t( T & ref ) : ref(ref) {}

	typedef typename T::reverse_iterator iterator;
	iterator begin() { return ref.rbegin(); }
	iterator end() { return ref.rend(); }
};

template< typename T >
reverseIterate_t< T > reverseIterate( T & ref ) {
	return reverseIterate_t< T >( ref );
}

#endif // _UTILITY_H

// Local Variables: //
// tab-width: 4 //
// mode: c++ //
// compile-command: "make install" //
// End: //
