Working on the shogi serializer.
[tagua.git] / src / hlvariant / poolcollection.h
blobbf6732852ad7120e9417123fb1047050fe4efae4
1 #ifndef HLVARIANT__POOLCOLLECTION_H
2 #define HLVARIANT__POOLCOLLECTION_H
4 namespace HLVariant {
6 template <typename _Pool>
7 class PoolCollection {
8 public:
9 typedef _Pool Pool;
10 private:
11 typedef typename Pool::Piece Piece;
12 typedef typename Piece::Color Color;
13 typedef std::map<Color, Pool> Pools;
15 Pools m_pools;
16 public:
17 virtual ~PoolCollection();
19 virtual bool operator==(const PoolCollection<Pool>& other) const;
20 virtual bool operator!=(const PoolCollection<Pool>& other) const;
22 virtual Pool& pool(Color player);
23 virtual const Pool& pool(Color player) const;
26 // IMPLEMENTATION
28 template <typename Pool>
29 PoolCollection<Pool>::~PoolCollection() { }
31 template <typename Pool>
32 bool PoolCollection<Pool>::operator==(const PoolCollection<Pool>& other) const {
33 typename Pools::const_iterator i = m_pools.begin();
34 typename Pools::const_iterator j = other.m_pools.begin();
36 while (i != m_pools.end() && j != other.m_pools.end()) {
37 if (i->first < j->first) {
38 if (!i->second.empty())
39 return false;
40 else
41 ++i;
43 else if (i->first > j->first) {
44 if (!j->second.empty())
45 return false;
46 else
47 ++j;
49 else {
50 // same key, compare values
51 if (i->second != j->second)
52 return false;
53 else {
54 ++i;
55 ++j;
60 // check tail
61 while (i != m_pools.end()) {
62 if (!i->second.empty())
63 return false;
64 ++i;
66 while (j != other.m_pools.end()) {
67 if (!j->second.empty())
68 return false;
69 ++j;
72 return true;
75 template <typename Pool>
76 bool PoolCollection<Pool>::operator!=(const PoolCollection<Pool>& other) const {
77 return !((*this) == other);
80 template <typename Pool>
81 Pool& PoolCollection<Pool>::pool(Color player) {
82 // return pool if it exists
83 typename Pools::iterator it = m_pools.find(player);
84 if (it != m_pools.end()) {
85 return it->second;
88 // if not, create it
89 m_pools.insert(std::make_pair(player, Pool(player)));
90 return m_pools.find(player)->second;
93 template <typename Pool>
94 const Pool& PoolCollection<Pool>::pool(Color player) const {
95 // here we use const cast, because our semantics of PoolCollection
96 // considers an empty pool the same thing as no pool.
97 return const_cast<PoolCollection*>(this)->pool(player);
102 #endif // HLVARIANT__POOLCOLLECTION_H