dataset/pick.hh

00001 // This file is a part of Catsfoot.
00002 // Copyright (C) 2011  Uni Research
00003 //
00004 // This program is free software: you can redistribute it and/or modify
00005 // it under the terms of the GNU Lesser Public License as published by
00006 // the Free Software Foundation, either version 3 of the License, or
00007 // (at your option) any later version.
00008 //
00009 // This program is distributed in the hope that it will be useful,
00010 // but WITHOUT ANY WARRANTY; without even the implied warranty of
00011 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00012 // GNU Lesser Public License for more details.
00013 //
00014 // You should have received a copy of the GNU Lesser Public License
00015 // along with this program.  If not, see <http://www.gnu.org/licenses/>.
00016 
00017 #ifndef __PICK_HH
00018 # define __PICK_HH
00019 
00020 # include "dataset.hh"
00021 
00022 namespace catsfoot {
00023   template <typename T, typename Generator>
00024   struct pick_functor {
00025   private:
00026     typedef typename std::decay<decltype(std::declval<Generator&>().get(selector<T>()))>::type container;
00027     container s;
00028     typename container::iterator i;
00029   public:
00030     pick_functor(Generator& g): s(g.get(selector<T>())), i(s.begin()) {
00031     }
00032     pick_functor(const pick_functor& other): s(other.s), i(s.begin()) {
00033     }
00034     pick_functor(pick_functor&& other): s(std::move(other.s)),
00035                                         i(std::move(other.i)) {
00036     }
00037 
00038     pick_functor& operator=(pick_functor&& other) {
00039       std::swap(s, other.s);
00040       std::swap(i, other.i);
00041       return *this;
00042     }
00043 
00044     pick_functor& operator=(const pick_functor& other) {
00045       return *this = pick_functor(other);
00046     }
00047 
00048     T& operator()() {
00049       if (i == s.end()) {
00050         i = s.begin();
00051         assert(i != s.end());
00052       }
00053       return *i++;
00054     }
00055   };
00056 
00057   template <typename T, typename Generator>
00058   std::function<T()> pick(Generator& g) {
00059     return pick_functor<T, Generator>(g);
00060   }
00061 }
00062 
00063 #endif