Updated license
[anna.git] / include / anna / core / util / SortedVector.hpp
1 // ANNA - Anna is Not Nothingness Anymore
2 //
3 // (c) Copyright 2005-2014 Eduardo Ramos Testillano & Francisco Ruiz Rayo
4 //
5 // https://bitbucket.org/testillano/anna
6 //
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
9 // are met:
10 //
11 //     * Redistributions of source code must retain the above copyright
12 // notice, this list of conditions and the following disclaimer.
13 //     * Redistributions in binary form must reproduce the above
14 // copyright notice, this list of conditions and the following disclaimer
15 // in the documentation and/or other materials provided with the
16 // distribution.
17 //     * Neither the name of Google Inc. nor the names of its
18 // contributors may be used to endorse or promote products derived from
19 // this software without specific prior written permission.
20 //
21 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 //
33 // Authors: eduardo.ramos.testillano@gmail.com
34 //          cisco.tierra@gmail.com
35
36
37 #ifndef anna_core_util_SortedVector_hpp
38 #define anna_core_util_SortedVector_hpp
39
40 #include <map>
41
42 #include <anna/core/RuntimeException.hpp>
43 #include <anna/config/defines.hpp>
44
45 namespace anna {
46
47 /**
48    Patron para ordenar instancias de objetos en base de una clave.
49
50    \param T Clase del patron.
51    \param SortBy Clase que ofrece el valor por el que ordenar. Debe implementar un metodo constante con la
52     signatura: TKey value (const T*)
53    \param TKey Tipo de clave usado para calcular la ordenacion. Debe implementar los operadores '=', '<' y '==' y el
54    contructor copia.
55
56    \warning no actua como clase segura en MT, ver #anna::SafeSortedVector.
57 */
58 template < typename T, typename SortBy, typename TKey = int > class SortedVector : public std::map <TKey, T*> {
59 public:
60   typedef typename std::map <TKey, T*> container;
61   typedef typename container::iterator iterator;
62   typedef typename container::const_iterator const_iterator;
63   typedef typename container::value_type value_type;
64
65   /**
66      Constructor.
67   */
68   SortedVector() {;}
69
70   /**
71      Constructor copia.
72      \param other Instancia de la que copiar.
73   */
74   explicit SortedVector(const SortedVector& other) :
75     container(other) {}
76
77   /**
78      Destructor.
79   */
80   virtual ~SortedVector() { container::clear(); }
81
82   /**
83      Devolvera \em true si la instancia recibida como parametro esta contenido en el
84      map o \em en otro caso. Si la instancia recibida es NULL siempre devolvera \em false.
85      \param t Instancia a comprobar.
86      \return \em true si la instancia recibida como parametro esta contenido en el
87      map o \em en otro caso.
88   */
89   bool contains(const T* t) const
90   throw() {
91     if(t == NULL)
92       return false;
93
94     TKey key(SortBy::value(t));
95     return find(key) != NULL;
96   }
97
98   /**
99      Incorpora la instancia recibida como parametro en la lista ordenada de objetos.
100      \param t Instancia a guardar en el map. Si es NULL la operacion no tendra ningun efecto.
101      \return \em true si ha registrado la nueva instancia o \em false en otro caso.
102   */
103   bool add(T* t)
104   throw(RuntimeException) {
105     if(t == NULL)
106       return false;
107
108     TKey key(SortBy::value(t));
109     value_type v(key, t);
110     std::pair <iterator, bool> result = container::insert(v);
111     return result.second;
112   }
113
114   /**
115      Elimina la instancia recibida como parametro de la lista ordenada de objetos.
116      \param t Instancia a guardar en el map. Si es NULL la operacion no tendra ningun efecto.
117      \return \em true si ha eliminado la instancia o \em false en otro caso.
118   */
119   bool erase(T* t)
120   throw(RuntimeException) {
121     if(t == NULL)
122       return false;
123
124     bool result = false;
125     TKey key(SortBy::value(t));
126     iterator ii = container::find(key);
127
128     if(ii != container::end()) {
129       container::erase(ii);
130       result = true;
131     }
132
133     return result;
134   }
135
136   /**
137      Devuelve la instancia asociada a la clave recibida como parametro o NULL si no existe.
138      \param key Clave a buscar en el map.
139      \return la instancia asociada a la clave recibida como parametro o NULL si no existe.
140   */
141   T* find(const TKey key)
142   throw() {
143     iterator ii = container::find(key);
144     return (ii == container::end()) ? NULL : ii->second;
145   }
146
147   /**
148      Devuelve la instancia asociada a la clave recibida como parametro o NULL si no existe.
149      \param key Clave a buscar en el map.
150      \return la instancia asociada a la clave recibida como parametro o NULL si no existe.
151   */
152   const T* find(const TKey key) const throw() {
153     return const_cast <SortedVector <T, SortBy, TKey>*>(this)->find(key);
154   }
155
156   /**
157      Devuelve el objeto referenciado por el iterador.
158      \return El objeto referenciado por el iterador.
159   */
160   static T* data(iterator ii) throw() { return ii->second; }
161
162   /**
163      Devuelve el objeto referenciado por el iterador.
164      \return El objeto referenciado por el iterador.
165   */
166   static const T* data(const_iterator ii) throw() { return ii->second; }
167 };
168
169 }
170
171 #endif