// src/templates/sequences.tcc - Copyright 2005, 2006, University
//               of Padova, dept. of Pure and Applied
//               Mathematics
//
// This file is part of SGPEMv2.
//
// This is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// SGPEMv2 is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with SGPEMv2; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA


/* Helper templates to make easier to work on an entire sequence over a container */

#include <iterator>
#include <utility>

// Class defining an input sequence

template<typename In>
class Iseq : protected std::pair<In, In>
{
public:
  typedef typename In::pointer     pointer;
  typedef typename In::reference   reference;

  explicit Iseq(In a, In b)
    : std::pair<In, In>(a, b)
  {}

  operator bool() 
  { return Iseq::first != Iseq::second; }

  Iseq& operator++() 
  { ++Iseq::first; return *this;  }

  Iseq  operator++(int)
  { Iseq t = *this; ++Iseq::first; return t; }

  const reference operator*() const
  { return *Iseq::first; }

  const In& operator->() const
  { return Iseq::first; }

  bool operator==(const Iseq& i) const
  { return Iseq::first == i.first; }

  bool operator!=(const Iseq& i) const
  { return Iseq::first != i.first; }
};



// Adaptor functions for containers:

template<class Container>
Iseq<typename Container::const_iterator> 
iseq(const Container& c)
{
  return Iseq<typename Container::const_iterator>(c.begin(), c.end());
}


template<class Container>
Iseq<typename Container::iterator> 
iseq(Container& c)
{
  return Iseq<typename Container::iterator>(c.begin(), c.end());
}


// Adaptor functions for containers that support reverse iteration

template<class Container>
Iseq<typename Container::const_reverse_iterator> 
riseq(const Container& c)
{
  return Iseq<typename Container::const_reverse_iterator>(c.rbegin(), c.rend());
}


template<class Container>
Iseq<typename Container::reverse_iterator> 
riseq(Container& c)
{
  return Iseq<typename Container::reverse_iterator>(c.rbegin(), c.rend());
}


template<class Container, class Functor>
Functor
for_each_in(const Container& c, Functor functor)
{
  Iseq<typename Container::const_iterator> seq = iseq(c);
  while(seq)
    {
      functor(*seq);
      ++seq;
    }
  return functor;
}
